diff --git a/TTS/Kokoro/.venv/Lib/site-packages/num2words-0.5.14.dist-info/COPYING b/TTS/Kokoro/.venv/Lib/site-packages/num2words-0.5.14.dist-info/COPYING new file mode 100644 index 0000000000000000000000000000000000000000..a7b7406f02f769167539316e5093cd58f609dce5 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/num2words-0.5.14.dist-info/COPYING @@ -0,0 +1,145 @@ +GNU Lesser General Public License + +Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + + [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] + +Preamble + +The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. + +This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. + +When we speak of free software, we are referring to freedom of use, 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 this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. + +To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. + +For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. + +We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. + +To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. + +Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. + +Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. + +When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. + +We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. + +For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. + +In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. + +Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. + +The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. +TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + +0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". + +A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. + +The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) + +"Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. + +Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. + +1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. + +You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. + +2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. + + (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) + + These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. + + Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. + + In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. + +3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. + +Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. + +This option is useful when you wish to copy part of the code of the Library into a program that is not a library. + +4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. + +If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. + +5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. + +However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. + +When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. + +If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) + +Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. + +6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. + +You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: + + a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. + + e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. + +For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. + +It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. + +7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. + + b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. + +8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. + +9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. + +10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. + +11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), 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 distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. + +This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. + +12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. + +13. The Free Software Foundation may publish revised and/or new versions of the Lesser 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 Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. + +14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. + +NO WARRANTY + +15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "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 LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY 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 LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +END OF TERMS AND CONDITIONS diff --git a/TTS/Kokoro/.venv/Lib/site-packages/num2words-0.5.14.dist-info/INSTALLER b/TTS/Kokoro/.venv/Lib/site-packages/num2words-0.5.14.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/num2words-0.5.14.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/TTS/Kokoro/.venv/Lib/site-packages/num2words-0.5.14.dist-info/METADATA b/TTS/Kokoro/.venv/Lib/site-packages/num2words-0.5.14.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..00651009441c3d92a4014d7f42f5599c2a6e4767 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/num2words-0.5.14.dist-info/METADATA @@ -0,0 +1,398 @@ +Metadata-Version: 2.1 +Name: num2words +Version: 0.5.14 +Summary: Modules to convert numbers to words. Easily extensible. +Home-page: https://github.com/savoirfairelinux/num2words +Author: Taro Ogawa +Author-email: tos@users.sourceforge.net +Maintainer: Savoir-faire Linux inc. +Maintainer-email: support@savoirfairelinux.com +License: LGPL +Keywords: number word numbers words convert conversion i18n localisation localization internationalisation internationalization +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL) +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Topic :: Software Development :: Internationalization +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Topic :: Software Development :: Localization +Classifier: Topic :: Text Processing :: Linguistic +Description-Content-Type: text/markdown +License-File: COPYING +Requires-Dist: docopt>=0.6.2 + +num2words library - Convert numbers to words in multiple languages +================================================================== + +.. image:: https://img.shields.io/pypi/v/num2words.svg + :target: https://pypi.python.org/pypi/num2words + +.. image:: https://travis-ci.org/savoirfairelinux/num2words.svg?branch=master + :target: https://travis-ci.org/savoirfairelinux/num2words + +.. image:: https://coveralls.io/repos/github/savoirfairelinux/num2words/badge.svg?branch=master + :target: https://coveralls.io/github/savoirfairelinux/num2words?branch=master + + +``num2words`` is a library that converts numbers like ``42`` to words like ``forty-two``. +It supports multiple languages (see the list below for full list +of languages) and can even generate ordinal numbers like ``forty-second`` +(although this last feature is a bit buggy for some languages at the moment). + +The project is hosted on GitHub_. Contributions are welcome. + +.. _GitHub: https://github.com/savoirfairelinux/num2words + +Installation +------------ + +The easiest way to install ``num2words`` is to use pip:: + + pip install num2words + +Otherwise, you can download the source package and then execute:: + + python setup.py install + +The test suite in this library is new, so it's rather thin, but it can be run with:: + + python setup.py test + +To run the full CI test suite which includes linting and multiple python environments:: + + pip install tox + tox + +Usage +----- +Command line:: + + $ num2words 10001 + ten thousand and one + $ num2words 24,120.10 + twenty-four thousand, one hundred and twenty point one + $ num2words 24,120.10 -l es + veinticuatro mil ciento veinte punto uno + $num2words 2.14 -l es --to currency + dos euros con catorce céntimos + +In code there's only one function to use:: + + >>> from num2words import num2words + >>> num2words(42) + forty-two + >>> num2words(42, to='ordinal') + forty-second + >>> num2words(42, lang='fr') + quarante-deux + +Besides the numerical argument, there are two main optional arguments, ``to:`` and ``lang:`` + +**to:** The converter to use. Supported values are: + +* ``cardinal`` (default) +* ``ordinal`` +* ``ordinal_num`` +* ``year`` +* ``currency`` + +**lang:** The language in which to convert the number. Supported values are: + +* ``en`` (English, default) +* ``am`` (Amharic) +* ``ar`` (Arabic) +* ``az`` (Azerbaijani) +* ``be`` (Belarusian) +* ``bn`` (Bangladeshi) +* ``ca`` (Catalan) +* ``ce`` (Chechen) +* ``cs`` (Czech) +* ``cy`` (Welsh) +* ``da`` (Danish) +* ``de`` (German) +* ``en_GB`` (English - Great Britain) +* ``en_IN`` (English - India) +* ``en_NG`` (English - Nigeria) +* ``es`` (Spanish) +* ``es_CO`` (Spanish - Colombia) +* ``es_CR`` (Spanish - Costa Rica) +* ``es_GT`` (Spanish - Guatemala) +* ``es_VE`` (Spanish - Venezuela) +* ``eu`` (EURO) +* ``fa`` (Farsi) +* ``fi`` (Finnish) +* ``fr`` (French) +* ``fr_BE`` (French - Belgium) +* ``fr_CH`` (French - Switzerland) +* ``fr_DZ`` (French - Algeria) +* ``he`` (Hebrew) +* ``hu`` (Hungarian) +* ``id`` (Indonesian) +* ``is`` (Icelandic) +* ``it`` (Italian) +* ``ja`` (Japanese) +* ``kn`` (Kannada) +* ``ko`` (Korean) +* ``kz`` (Kazakh) +* ``lt`` (Lithuanian) +* ``lv`` (Latvian) +* ``nl`` (Dutch) +* ``no`` (Norwegian) +* ``pl`` (Polish) +* ``pt`` (Portuguese) +* ``pt_BR`` (Portuguese - Brazilian) +* ``ro`` (Romanian) +* ``ru`` (Russian) +* ``sl`` (Slovene) +* ``sk`` (Slovak) +* ``sr`` (Serbian) +* ``sv`` (Swedish) +* ``te`` (Telugu) +* ``tet`` (Tetum) +* ``tg`` (Tajik) +* ``tr`` (Turkish) +* ``th`` (Thai) +* ``uk`` (Ukrainian) +* ``vi`` (Vietnamese) + +You can supply values like ``fr_FR``; if the country doesn't exist but the +language does, the code will fall back to the base language (i.e. ``fr``). If +you supply an unsupported language, ``NotImplementedError`` is raised. +Therefore, if you want to call ``num2words`` with a fallback, you can do:: + + try: + return num2words(42, lang=mylang) + except NotImplementedError: + return num2words(42, lang='en') + +Additionally, some converters and languages support other optional arguments +that are needed to make the converter useful in practice. + +Wiki +---- +For additional information on some localization please check the Wiki_. +And feel free to propose wiki enhancement. + +.. _Wiki: https://github.com/savoirfairelinux/num2words/wiki + +History +------- + +``num2words`` is based on an old library, ``pynum2word``, created by Taro Ogawa +in 2003. Unfortunately, the library stopped being maintained and the author +can't be reached. There was another developer, Marius Grigaitis, who in 2011 +added Lithuanian support, but didn't take over maintenance of the project. + +I am thus basing myself on Marius Grigaitis' improvements and re-publishing +``pynum2word`` as ``num2words``. + +Virgil Dupras, Savoir-faire Linux + +Changelog +========= + +Version 0.5.14 -- 2024/12/16 +---------------------------- + +* Fixed a typo in PL (#466) +* Run tests against Python 3.12 (#544) +* ADD num2words: es_CR language (#565) +* New languages: Welsh (Celtic) and Chechen (Nakho-Dagestanian) (#543) +* Add catalan language support (#581) +* Adding Tetum Language (#576) +* FIX ISO code for Belarusian language is be, not by. (#574) +* Add test to improve coverage (#595) +* Added Bangla language support to num2word for Bangladesh. (#589) +* Czech language ISO 639-1 code fix (#587) +* Added support for Tunisian Dinar (#593) +* Change danish language code to DA (#596) + + +Version 0.5.13 -- 2023/10/18 +--------------------------- + +* Fix a problem in Brazilian Portuguese code referred to thousands when the hundreds are exact. (#421) +* Fix issue with the hundreds of millions, billions, ... when the hundreds of those are exact. (#436) +* Fix negative number problem (#477) +* Fix lang_DK issues (#366) +* Norwegian uplift (#484) +* BYN to EU and RU (#439) +* Change python3.6 to python3.11 because deprecation in ubuntu 22.04 (#494) +* Add support for Azerbaijani language (#495) +* Add Icelandic (#380) +* Hebrew long-form spelling, gender, ordinals, fractions, maxval=1e66, construct forms (#490) +* Fix 15, 16, 17, 18, 19 issue (#505) +* Added support for the Nigerian Naira (#507) +* Fix several issues with num2words in Arabic (#512) +* Guatemalan currency support (#510) +* Fix #508: Handle string inputs in Italian to_ordinal (#518) +* Add Slovak language support (#533) +* Add gender and morphological cases support for Ukrainian (#530) +* Adding genders for Russian language (#503) +* Lang By Added (#506) +* Add Saudi Riyal to english (#531) + +Version 0.5.12 -- 2022/08/19 +---------------------------- + +* Support Japanese Reiwa (令和/れいわ) era. (#412) +* Add basic farsi support (#354) +* Added Tajik language support (#406) +* Fix Amharic language support (#465) +* Fix Hebrew pluralize and implement to_currency (#330) +* Add support to translate some currencies in italian language (#434) +* Fix Polish twenties (#345) +* Add uzs for ru and en (#422) +* Added support for Esperanto numbers. (#387) +* [ADD] to ordinal number for Turkish (#468) +* Fix zeroth in Dutch to nulde fixing (#326) + +Version 0.5.11 -- 2022/08/03 +---------------------------- + +* Add KZT and UAH currencies to lang RU (#264) +* Add es_NI currency (#276) +* Update .gitignore to add .eggs/ directory (#280) +* Fix Hebrew support (#289) +* Update test_tr.py to increase coverage (#298) +* Add ordinal 12,345 to ES test suite to increase coverage (#287) +* Add simple tests for lang_DK.py (#286) +* Add testcase for lang_EN.py (#288) +* Add more tests to base.py (#283) +* Fixed misspelling of 21 (cardinal and ordinal number) in IT language (#270) +* Romanian issues 259 (#260) +* Adding Language Support for Telugu / Bug Fix in Kannada (#263) +* Add support of Kazakh language (KZ) (#306) +* Update README.rst (#307) +* Added support for Hungarian language (#310) +* [UPD] Readme file (#363) +* [ADD] num2words: add traslation to spanish of several currencies (#356) +* added swedish language including test cases (#352) +* Remove dupplicated line in lang_PT_BR (#355) +* Fix ordinal_num output for Dutch (NL) (#369) +* Polishordinals (#367) +* [tr] return Turkish 0 ordinal and cardinal (#347) +* Improve Ukrainian support and minor fixes in CZ, KZ, LT, LV, PL, RU, SR languages (#400) +* feat: ci: replace travis by github workflows (#448) +* [ES] Added missing accents ("dieciséis", "dólar", "dólares", "veintiún"), improved currency gender handling, fixed pound cent names (#443) + +Version 0.5.10 -- 2019/05/12 +---------------------------- + +* Add Kannada language localization (#243) +* Revert some copyrights changed by mistake (#254) +* Add indian rupee to the supported currencies (#248) +* Improve currency functions for German and French (#247) +* Improve Slovene localization (#246) +* Improve Spanish localization (#240) +* Fix typo 'seperator' on source code (#238) +* Convert string to decimal values (#223) +* Improve German localization and test coverage (#237) +* Improve Polish localization (#233) +* Fix ordinal number for French ending on 1 (#236) + +Version 0.5.9 -- 2019/01/10 +--------------------------- + +* Fix encoding issue on release 0.5.8 (#229) +* Improve Polish localization (#228) + + +Version 0.5.8 -- 2018/11/17 +--------------------------- + +* Add Portuguese (Portugal) localization (#198) +* Add a command line tool to use num2words +* Use language iso code for Vietnamese +* Improve Korean localization (#219) +* Improve Serbian (Latin) localization (#207) +* Improve testing setup (#220) +* Improve German localization (#214) (#222) +* Improve Romanian localization (#215) +* Improve Spanish localization (#187) (#200) +* Improve Russian localization (#211) (#212) +* Improve French localization (23902ab) +* Improve Arabic localization (#176) +* Improve Lithuanian and Latvian localization (#185) +* Improve Ukrainian localization (#183) + + +Version 0.5.7 -- 2018/06/27 +--------------------------- + +* Add Finnish localization. (#170) +* Add Japanese localization. (#171) +* Add belgian-french localization. (#151) +* Add Czech localization. (#154) +* Add Thai localization. (#139) +* Improve English localization. (#144) +* Improve Spanish localization. (#167) +* Improve Italian localization. (#143) +* Improve documentation. (#155, #145, #174) + +Version 0.5.6 -- 2017/11/22 +--------------------------- + +* Refactor to_currency (#135) +* Allow the use of other convertes to_currency, to_year (#95) +* Fix code to respect PEP8 (#98, #105) +* Add Slovene localization (#97) +* Add Ukrainian localization (#93) +* Add Dutch localization (#91) +* Add Algeria-French localization (#86) +* Add Turkish localization (#85) + +Version 0.5.5 -- 2017/07/02 +--------------------------- + +* Add Arabic localization (#72) +* Add Spanish-Colombian and Spanish-Venezuelan localization (#67) +* Add VietNam localization (#61) +* Add Italian localization (#56, #59) +* Improve Russian localization (#62) +* Improve Polish localization (#58) + +Version 0.5.4 -- 2016/10/18 +--------------------------- + +* Tons of new languages! +* Add Polish localization. (#23) +* Add Swiss-French localization. (#38) +* Add Russian localization. (#28, #46, #48) +* Add Indonesian localization. (#29) +* Add Norwegian localization. (#33) +* Add Danish localization. (#40) +* Add Brazilian localization. (#37, #47) +* Improve German localization. (#25, #27, #49) +* Improve Lithuanian localization. (#52) +* Improve floating point spelling. (#24) + +Version 0.5.3 -- 2015/06/09 +--------------------------- + +* Fix packaging issues. (#21, #22) + +Version 0.5.2 -- 2015/01/23 +--------------------------- + +* Added Latvian localization. (#9) +* Improved Spanish localization. (#10, #13, #14) +* Improved Lithuanian localization. (#12) + +Version 0.5.1 -- 2014/03/14 +--------------------------- + +* Added Python 3 support with 2to3. (#3) +* Fixed big numbers in spanish. (#2) +* Fixed bugs in tanslation from 30 to 40 in spanish. (#4) +* Fixed word joining in english. (#8) + +Version 0.5.0 -- 2013/05/28 +--------------------------- + +* Created ``num2words`` based on the old ``pynum2word`` project. diff --git a/TTS/Kokoro/.venv/Lib/site-packages/num2words-0.5.14.dist-info/RECORD b/TTS/Kokoro/.venv/Lib/site-packages/num2words-0.5.14.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..fb872e86596b935953acf138d479938d8cc86e0f --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/num2words-0.5.14.dist-info/RECORD @@ -0,0 +1,131 @@ +../../Scripts/num2words,sha256=7zjYklXXBbCQBIiwaLYpDZegOd1mUFvIaBqo1nJum5Y,3039 +num2words-0.5.14.dist-info/COPYING,sha256=FFegPZKK6wavPqde8GXFF-kV1-QSg9VQ3U-hirIM2hI,23995 +num2words-0.5.14.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +num2words-0.5.14.dist-info/METADATA,sha256=e1uSF9sYJ02w_bdcHn3ug8Yb5PQIvk2deWoiU9VXht8,13164 +num2words-0.5.14.dist-info/RECORD,, +num2words-0.5.14.dist-info/WHEEL,sha256=PZUExdf71Ui_so67QXpySuHtCi3-J3wvF4ORK6k_S8U,91 +num2words-0.5.14.dist-info/top_level.txt,sha256=TCTV-xtX6whCC1B0WTe4hTqpAqJaPmEHFsuNOrfbaq0,10 +num2words/__init__.py,sha256=uphwgHFsS5kIyjjyDyhYSyvwyf0ML7lKWCTCrryCUeU,4270 +num2words/__pycache__/__init__.cpython-312.pyc,, +num2words/__pycache__/base.cpython-312.pyc,, +num2words/__pycache__/compat.cpython-312.pyc,, +num2words/__pycache__/currency.cpython-312.pyc,, +num2words/__pycache__/lang_AM.cpython-312.pyc,, +num2words/__pycache__/lang_AR.cpython-312.pyc,, +num2words/__pycache__/lang_AZ.cpython-312.pyc,, +num2words/__pycache__/lang_BE.cpython-312.pyc,, +num2words/__pycache__/lang_BN.cpython-312.pyc,, +num2words/__pycache__/lang_CA.cpython-312.pyc,, +num2words/__pycache__/lang_CE.cpython-312.pyc,, +num2words/__pycache__/lang_CS.cpython-312.pyc,, +num2words/__pycache__/lang_CY.cpython-312.pyc,, +num2words/__pycache__/lang_DA.cpython-312.pyc,, +num2words/__pycache__/lang_DE.cpython-312.pyc,, +num2words/__pycache__/lang_EN.cpython-312.pyc,, +num2words/__pycache__/lang_EN_IN.cpython-312.pyc,, +num2words/__pycache__/lang_EN_NG.cpython-312.pyc,, +num2words/__pycache__/lang_EO.cpython-312.pyc,, +num2words/__pycache__/lang_ES.cpython-312.pyc,, +num2words/__pycache__/lang_ES_CO.cpython-312.pyc,, +num2words/__pycache__/lang_ES_CR.cpython-312.pyc,, +num2words/__pycache__/lang_ES_GT.cpython-312.pyc,, +num2words/__pycache__/lang_ES_NI.cpython-312.pyc,, +num2words/__pycache__/lang_ES_VE.cpython-312.pyc,, +num2words/__pycache__/lang_EU.cpython-312.pyc,, +num2words/__pycache__/lang_FA.cpython-312.pyc,, +num2words/__pycache__/lang_FI.cpython-312.pyc,, +num2words/__pycache__/lang_FR.cpython-312.pyc,, +num2words/__pycache__/lang_FR_BE.cpython-312.pyc,, +num2words/__pycache__/lang_FR_CH.cpython-312.pyc,, +num2words/__pycache__/lang_FR_DZ.cpython-312.pyc,, +num2words/__pycache__/lang_HE.cpython-312.pyc,, +num2words/__pycache__/lang_HU.cpython-312.pyc,, +num2words/__pycache__/lang_ID.cpython-312.pyc,, +num2words/__pycache__/lang_IS.cpython-312.pyc,, +num2words/__pycache__/lang_IT.cpython-312.pyc,, +num2words/__pycache__/lang_JA.cpython-312.pyc,, +num2words/__pycache__/lang_KN.cpython-312.pyc,, +num2words/__pycache__/lang_KO.cpython-312.pyc,, +num2words/__pycache__/lang_KZ.cpython-312.pyc,, +num2words/__pycache__/lang_LT.cpython-312.pyc,, +num2words/__pycache__/lang_LV.cpython-312.pyc,, +num2words/__pycache__/lang_NL.cpython-312.pyc,, +num2words/__pycache__/lang_NO.cpython-312.pyc,, +num2words/__pycache__/lang_PL.cpython-312.pyc,, +num2words/__pycache__/lang_PT.cpython-312.pyc,, +num2words/__pycache__/lang_PT_BR.cpython-312.pyc,, +num2words/__pycache__/lang_RO.cpython-312.pyc,, +num2words/__pycache__/lang_RU.cpython-312.pyc,, +num2words/__pycache__/lang_SK.cpython-312.pyc,, +num2words/__pycache__/lang_SL.cpython-312.pyc,, +num2words/__pycache__/lang_SR.cpython-312.pyc,, +num2words/__pycache__/lang_SV.cpython-312.pyc,, +num2words/__pycache__/lang_TE.cpython-312.pyc,, +num2words/__pycache__/lang_TET.cpython-312.pyc,, +num2words/__pycache__/lang_TG.cpython-312.pyc,, +num2words/__pycache__/lang_TH.cpython-312.pyc,, +num2words/__pycache__/lang_TR.cpython-312.pyc,, +num2words/__pycache__/lang_UK.cpython-312.pyc,, +num2words/__pycache__/lang_VI.cpython-312.pyc,, +num2words/__pycache__/utils.cpython-312.pyc,, +num2words/base.py,sha256=UjVvFxf3w5J8FfFexC9nBjW_ovMi7Q68pqtIeR1SSbQ,10022 +num2words/compat.py,sha256=XjAqKKpuP6NZgcGzg6f3NsdaXMlz2L_54P8Zr9U4clY,1040 +num2words/currency.py,sha256=arQf4Fbqm2lvrDwniwure1HLBsV6UNv4SXfeUDvlkck,1761 +num2words/lang_AM.py,sha256=vqWBs2PfEdNFC82OVyEK28TprXBufvdzH1paaG9SAZs,5614 +num2words/lang_AR.py,sha256=koOZLRxSy-4sjPC3udbV1GwAGjG5G1_I6nDEPiVZhbg,18436 +num2words/lang_AZ.py,sha256=25ClKjhLk-S3K1_XqyjFZhMoOUL7Laq09z2pIm7m8lI,6315 +num2words/lang_BE.py,sha256=h-4VNv8Ur4Qn3XgYU2U50YYPkSA2g7ArNnEblnAiv3Y,11850 +num2words/lang_BN.py,sha256=8OkS3_dfZ-8gUtmqmJwQHOOhk4ZOAqfwnbAV5p3NqoM,8746 +num2words/lang_CA.py,sha256=ju-XADqgjqQnWRbTM4KLVjk3mczF6ANsyKlaivt_wgA,18855 +num2words/lang_CE.py,sha256=i4yQA-iv7iooLPktRCEPJaflPhpaWoPJ3LQiSsM2zLg,16032 +num2words/lang_CS.py,sha256=L_sxsWjNqJgBWM4ydIXa21HQ23UI1_Tk-NrapKbP8Hg,4301 +num2words/lang_CY.py,sha256=Jwzgvoi4W_gU1_FvCkrmZOZgRr0WkAyX9ZlKaORmut4,20093 +num2words/lang_DA.py,sha256=TyJTeiCPesza5DG28jS-UywZefnJwpfjEJKCS58pP2M,5107 +num2words/lang_DE.py,sha256=dPzUZTaOiPTh8-3I1uR9rmi3McXJbjjOPnkSS0D5wHg,6166 +num2words/lang_EN.py,sha256=4toqx0cH4I-to0DSrZN9HZRiWQitxLtCMWVG0_lS4W4,4410 +num2words/lang_EN_IN.py,sha256=giFHJPjJie7s3FKTi0XidlzPSzY19NglMGoOAx7t_4Q,1098 +num2words/lang_EN_NG.py,sha256=w7Y9EPae2ltD_5KAxPf852TCU4JbhyQNgWP3SakS2Ms,1402 +num2words/lang_EO.py,sha256=63owo5IeQPIWW1wo3quFa9FDcmoyjxjjMBltgAaZhzM,4835 +num2words/lang_ES.py,sha256=MQzB6aUqUFVyJJa95rcHriUCIJ4XUYA1EX48whkOn0A,19705 +num2words/lang_ES_CO.py,sha256=-Gw4FitaMY68wFA2EjxnY2BO-iYxpQZX36DOjcIPzas,1324 +num2words/lang_ES_CR.py,sha256=xBPn1muwYEOio5nnvLXANoLf84DOR45CXXy_HWp8jjY,1388 +num2words/lang_ES_GT.py,sha256=t1kGcHpK61nCT1Pl96GkytoCMsqRZNdU-XIm3wEg-1k,1406 +num2words/lang_ES_NI.py,sha256=wbkRVUMzEkKqq92sadTfoJei185U9MML2nWqgCA-Nb8,1415 +num2words/lang_ES_VE.py,sha256=hYRijWDWmnJTh3ZLVozq3b3b81DKtr5rZtGqygHOYFg,1390 +num2words/lang_EU.py,sha256=ADf9Fx18OFHyDTF4IcJ-9YZnV1Up82dsZrkb18KRQYo,3868 +num2words/lang_FA.py,sha256=Zb-xK7ITlunV-eUQkSTHqe3CanMpRwzqFqJqmBhsKuU,4880 +num2words/lang_FI.py,sha256=I1sIz2vMms-3OmhVfoNUHJiLWDS-i4d65UIS0xGRTUw,23855 +num2words/lang_FR.py,sha256=p-Z-hcfjhYilseG7F2dWg0xiJLiBWLVcP5BKt6WsCAY,4257 +num2words/lang_FR_BE.py,sha256=hhlPKqU5-5YDUlnH-JVe_6sDfHu4jsHQQPXzHh61LEs,1942 +num2words/lang_FR_CH.py,sha256=4APdDhfHmgH7w-SuaKo0g6-yKtNfMmBHiivOVTyF6Yo,1937 +num2words/lang_FR_DZ.py,sha256=pHJ7-x--0ZNRX0tUG6kzsEKCeqabZsPzIQ-AR-JiD3M,1373 +num2words/lang_HE.py,sha256=XPfzYclZzAH8VecwPHjydQgAdKzxoxC2f6C8hcjmJas,11583 +num2words/lang_HU.py,sha256=l5nmKAozvjx1P9XskLOqeqlp4iFlBuz44HBeXGk_kxc,6068 +num2words/lang_ID.py,sha256=wwtBMR-9ZgELcDzHkhteh5hxG7sN3N6rZSJrD_dShSQ,6431 +num2words/lang_IS.py,sha256=idBsMdRdizjUMUHSpZSFBijqFQ21kwXywMbF2MmBWOw,4634 +num2words/lang_IT.py,sha256=x0cU-FajOQgEh_hyt_3oxdHsfwsjAv5YB5mbSXrssbI,8838 +num2words/lang_JA.py,sha256=vByBHXsdpo521G_KQYzmcenzAcBE4qHgZhHFnxNPct0,22325 +num2words/lang_KN.py,sha256=LQ6cq14q7qgWJEIFsmACUgX58BhkZfLlqHuYSJElXFE,7223 +num2words/lang_KO.py,sha256=5szKHGTp1qE6At2feb3u8ErHLy3_ixX3Nja8qwCN35E,5212 +num2words/lang_KZ.py,sha256=T-BuTcjYe8MVa6JbRWEa6-Q-auFkMq0OOdf3kOGJWPA,3501 +num2words/lang_LT.py,sha256=rtcm2FKI0jF28otw0VPsDb3_hBh4Rwindo7wTA8-4MY,5301 +num2words/lang_LV.py,sha256=evZ0pupMUOV8rBJyhTNIw2KibcXQHdl62HtF2SgzSaU,5900 +num2words/lang_NL.py,sha256=CXnjn3zw8t_SGLlo05Wxp6iz_QGtCnfvEU4F7jbR5h8,5690 +num2words/lang_NO.py,sha256=rNuUk_7lULl0PywHKSS0wnrFwFvzPlwuGOOj9Edxe-o,4952 +num2words/lang_PL.py,sha256=K46fLsvyew4JPGm_fECSF-l-iZhbjPeWcXB4DqlH6yc,7874 +num2words/lang_PT.py,sha256=ebNkDRXkqfAcAt1_DuZmE1vwwJEhzti-yx7b5F9qAkE,8503 +num2words/lang_PT_BR.py,sha256=hnyaYeQyL-vyDoC5s4Fj9tk827pHVXU_0zRgDygVoSg,3772 +num2words/lang_RO.py,sha256=XH3Q9mrpfdn-Deoch_vzutCPkqh1fGp4aE8ZDTJ704Q,6817 +num2words/lang_RU.py,sha256=3cjf9gl6xLz8nln4IbPBLGFHDHOlenCgY1ZvAcwoADc,21338 +num2words/lang_SK.py,sha256=Kett5iEm7PagLoB42ThlGRB73A9n5_AF5-hPhtOoTTA,4629 +num2words/lang_SL.py,sha256=02hBPN19fEVpzFiieMoanpsCQ2hkRLzNYzi3cvWsQWM,6322 +num2words/lang_SR.py,sha256=gqGSn_fzZV6PsGzhlMILV9zoYjrjXG03CWgHcytBMNc,6689 +num2words/lang_SV.py,sha256=ZEtiPY_MiAh9NsYQAnYdy8Tl1KWYj8D9ykL--EhDg4k,4625 +num2words/lang_TE.py,sha256=jUdTF61vsw_rljdBqVBvddi1CktisXLA7cC2B-vCACI,6390 +num2words/lang_TET.py,sha256=PWcDNE27LlKDZgD-yvCD70yLn2LgWv3Y7QdbYwLUgA0,8479 +num2words/lang_TG.py,sha256=_4jf4p0X9VS24_ZkpAUaguIIjtkNKs7W6C6uIXUCQ0A,5076 +num2words/lang_TH.py,sha256=925dUlzTqyA4WF1UIWpbK3BgQjsL56CsRzxLvxFNwNQ,5771 +num2words/lang_TR.py,sha256=WU8LZKDyCwI2qUZNVcopBFSF_PpzUqtcyFf0otQlAZQ,40168 +num2words/lang_UK.py,sha256=CubgZMVFOXMp5-aRzbclLvgpbKSkKn55fw17uyNYybY,40900 +num2words/lang_VI.py,sha256=Z_AxFOW4MSTW0zb4GZyVlPFBzKlXTleb--5j16FTM4E,4151 +num2words/utils.py,sha256=Wkz6OQRku0E0-RlNESYb_ZuFAhsMCvD-LdoOxs6lvYE,1360 diff --git a/TTS/Kokoro/.venv/Lib/site-packages/num2words-0.5.14.dist-info/WHEEL b/TTS/Kokoro/.venv/Lib/site-packages/num2words-0.5.14.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..ae527e7d64811439e61b93aa375defb30e06edfe --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/num2words-0.5.14.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (75.6.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/TTS/Kokoro/.venv/Lib/site-packages/num2words-0.5.14.dist-info/top_level.txt b/TTS/Kokoro/.venv/Lib/site-packages/num2words-0.5.14.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..4b38fe3d2b2cc0b24a652c4be30ef0b4b8f80226 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/num2words-0.5.14.dist-info/top_level.txt @@ -0,0 +1 @@ +num2words diff --git a/TTS/Kokoro/.venv/Lib/site-packages/num2words/__init__.py b/TTS/Kokoro/.venv/Lib/site-packages/num2words/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..882aa229e09641aac231c78ac78337136a85746f --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/num2words/__init__.py @@ -0,0 +1,111 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2003, Taro Ogawa. All Rights Reserved. +# Copyright (c) 2013, Savoir-faire Linux inc. All Rights Reserved. + +# This library 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. +# This library 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 along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301 USA + +from __future__ import unicode_literals + +from . import (lang_AM, lang_AR, lang_AZ, lang_BE, lang_BN, lang_CA, lang_CE, + lang_CS, lang_CY, lang_DA, lang_DE, lang_EN, lang_EN_IN, + lang_EN_NG, lang_EO, lang_ES, lang_ES_CO, lang_ES_CR, + lang_ES_GT, lang_ES_NI, lang_ES_VE, lang_FA, lang_FI, lang_FR, + lang_FR_BE, lang_FR_CH, lang_FR_DZ, lang_HE, lang_HU, lang_ID, + lang_IS, lang_IT, lang_JA, lang_KN, lang_KO, lang_KZ, lang_LT, + lang_LV, lang_NL, lang_NO, lang_PL, lang_PT, lang_PT_BR, + lang_RO, lang_RU, lang_SK, lang_SL, lang_SR, lang_SV, lang_TE, + lang_TET, lang_TG, lang_TH, lang_TR, lang_UK, lang_VI) + +CONVERTER_CLASSES = { + 'am': lang_AM.Num2Word_AM(), + 'ar': lang_AR.Num2Word_AR(), + 'az': lang_AZ.Num2Word_AZ(), + 'be': lang_BE.Num2Word_BE(), + 'bn': lang_BN.Num2Word_BN(), + 'ca': lang_CA.Num2Word_CA(), + 'ce': lang_CE.Num2Word_CE(), + 'cs': lang_CS.Num2Word_CS(), + 'cy': lang_CY.Num2Word_CY(), + 'en': lang_EN.Num2Word_EN(), + 'en_IN': lang_EN_IN.Num2Word_EN_IN(), + 'en_NG': lang_EN_NG.Num2Word_EN_NG(), + 'fa': lang_FA.Num2Word_FA(), + 'fr': lang_FR.Num2Word_FR(), + 'fr_CH': lang_FR_CH.Num2Word_FR_CH(), + 'fr_BE': lang_FR_BE.Num2Word_FR_BE(), + 'fr_DZ': lang_FR_DZ.Num2Word_FR_DZ(), + 'de': lang_DE.Num2Word_DE(), + 'fi': lang_FI.Num2Word_FI(), + 'eo': lang_EO.Num2Word_EO(), + 'es': lang_ES.Num2Word_ES(), + 'es_CO': lang_ES_CO.Num2Word_ES_CO(), + 'es_CR': lang_ES_CR.Num2Word_ES_CR(), + 'es_GT': lang_ES_GT.Num2Word_ES_GT(), + 'es_NI': lang_ES_NI.Num2Word_ES_NI(), + 'es_VE': lang_ES_VE.Num2Word_ES_VE(), + 'id': lang_ID.Num2Word_ID(), + 'ja': lang_JA.Num2Word_JA(), + 'kn': lang_KN.Num2Word_KN(), + 'ko': lang_KO.Num2Word_KO(), + 'kz': lang_KZ.Num2Word_KZ(), + 'lt': lang_LT.Num2Word_LT(), + 'lv': lang_LV.Num2Word_LV(), + 'pl': lang_PL.Num2Word_PL(), + 'ro': lang_RO.Num2Word_RO(), + 'ru': lang_RU.Num2Word_RU(), + 'sk': lang_SK.Num2Word_SK(), + 'sl': lang_SL.Num2Word_SL(), + 'sr': lang_SR.Num2Word_SR(), + 'sv': lang_SV.Num2Word_SV(), + 'no': lang_NO.Num2Word_NO(), + 'da': lang_DA.Num2Word_DA(), + 'pt': lang_PT.Num2Word_PT(), + 'pt_BR': lang_PT_BR.Num2Word_PT_BR(), + 'he': lang_HE.Num2Word_HE(), + 'it': lang_IT.Num2Word_IT(), + 'vi': lang_VI.Num2Word_VI(), + 'tg': lang_TG.Num2Word_TG(), + 'th': lang_TH.Num2Word_TH(), + 'tr': lang_TR.Num2Word_TR(), + 'nl': lang_NL.Num2Word_NL(), + 'uk': lang_UK.Num2Word_UK(), + 'te': lang_TE.Num2Word_TE(), + 'tet': lang_TET.Num2Word_TET(), + 'hu': lang_HU.Num2Word_HU(), + 'is': lang_IS.Num2Word_IS(), +} + +CONVERTES_TYPES = ['cardinal', 'ordinal', 'ordinal_num', 'year', 'currency'] + + +def num2words(number, ordinal=False, lang='en', to='cardinal', **kwargs): + # We try the full language first + if lang not in CONVERTER_CLASSES: + # ... and then try only the first 2 letters + lang = lang[:2] + if lang not in CONVERTER_CLASSES: + raise NotImplementedError() + converter = CONVERTER_CLASSES[lang] + + if isinstance(number, str): + number = converter.str_to_number(number) + + # backwards compatible + if ordinal: + to = 'ordinal' + + if to not in CONVERTES_TYPES: + raise NotImplementedError() + + return getattr(converter, 'to_{}'.format(to))(number, **kwargs) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_FR_CH.py b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_FR_CH.py new file mode 100644 index 0000000000000000000000000000000000000000..da150db0c358747bdda80766c91a3dedadf085de --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_FR_CH.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2003, Taro Ogawa. All Rights Reserved. +# Copyright (c) 2013, Savoir-faire Linux inc. All Rights Reserved. + +# This library 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. +# This library 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 along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301 USA +from __future__ import print_function, unicode_literals + +from .lang_FR import Num2Word_FR + + +class Num2Word_FR_CH(Num2Word_FR): + def setup(self): + Num2Word_FR.setup(self) + + self.mid_numwords = [(1000, "mille"), (100, "cent"), (90, "nonante"), + (80, "huitante"), (70, "septante"), + (60, "soixante"), (50, "cinquante"), + (40, "quarante"), (30, "trente")] + + def merge(self, curr, next): + ctext, cnum, ntext, nnum = curr + next + + if cnum == 1: + if nnum < 1000000: + return next + + if cnum < 1000 and nnum != 1000 and\ + ntext[-1] != "s" and not nnum % 100: + ntext += "s" + + if nnum < cnum < 100: + if nnum % 10 == 1: + return ("%s et %s" % (ctext, ntext), cnum + nnum) + return ("%s-%s" % (ctext, ntext), cnum + nnum) + if nnum > cnum: + return ("%s %s" % (ctext, ntext), cnum * nnum) + return ("%s %s" % (ctext, ntext), cnum + nnum) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_FR_DZ.py b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_FR_DZ.py new file mode 100644 index 0000000000000000000000000000000000000000..176d700a40f34f4520775fd1a17c3874c5a607f4 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_FR_DZ.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2003, Taro Ogawa. All Rights Reserved. +# Copyright (c) 2013, Savoir-faire Linux inc. All Rights Reserved. + +# This library 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. +# This library 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 along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301 USA + +from __future__ import unicode_literals + +from .lang_FR import Num2Word_FR + + +class Num2Word_FR_DZ(Num2Word_FR): + CURRENCY_FORMS = { + 'DIN': (('dinard', 'dinards'), ('centime', 'centimes')), + } + + def to_currency(self, val, currency='DIN', cents=True, separator=' et', + adjective=False): + result = super(Num2Word_FR, self).to_currency( + val, currency=currency, cents=cents, separator=separator, + adjective=adjective) + return result diff --git a/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_HE.py b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_HE.py new file mode 100644 index 0000000000000000000000000000000000000000..8898d6670750080b0f9ebb14497592a4bec9da7a --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_HE.py @@ -0,0 +1,327 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2003, Taro Ogawa. All Rights Reserved. +# Copyright (c) 2013, Savoir-faire Linux inc. All Rights Reserved. + +# This library 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. +# This library 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 along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301 USA + + +from __future__ import print_function, unicode_literals + +from .base import Num2Word_Base +from .compat import to_s +from .currency import parse_currency_parts +from .utils import get_digits, splitbyx + +ZERO = (u'אפס',) + +ONES = { + 1: (u'אחת', u'אחד', u'אחת', u'אחד', + u'ראשונה', u'ראשון', u'ראשונות', u'ראשונים'), + 2: (u'שתיים', u'שניים', u'שתי', u'שני', + u'שנייה', u'שני', u'שניות', u'שניים'), + 3: (u'שלוש', u'שלושה', u'שלוש', u'שלושת', + u'שלישית', u'שלישי', u'שלישיות', u'שלישיים'), + 4: (u'ארבע', u'ארבעה', u'ארבע', u'ארבעת', + u'רביעית', u'רביעי', u'רביעיות', u'רביעיים'), + 5: (u'חמש', u'חמישה', u'חמש', u'חמשת', + u'חמישית', u'חמישי', u'חמישיות', u'חמישיים'), + 6: (u'שש', u'שישה', u'שש', u'ששת', + u'שישית', u'שישי', u'שישיות', u'שישיים'), + 7: (u'שבע', u'שבעה', u'שבע', u'שבעת', + u'שביעית', u'שביעי', u'שביעיות', u'שביעיים'), + 8: (u'שמונה', u'שמונה', u'שמונה', u'שמונת', + u'שמינית', u'שמיני', u'שמיניות', u'שמיניים'), + 9: (u'תשע', u'תשעה', u'תשע', u'תשעת', + u'תשיעית', u'תשיעי', u'תשיעיות', u'תשיעיים'), +} + +TENS = { + 0: (u'עשר', u'עשרה', u'עשר', u'עשרת', + u'עשירית', u'עשירי', u'עשיריות', u'עשיריים'), + 1: (u'עשרה', u'עשר'), + 2: (u'שתים עשרה', u'שנים עשר'), +} + +TWENTIES = { + 2: (u'עשרים',), + 3: (u'שלושים',), + 4: (u'ארבעים',), + 5: (u'חמישים',), + 6: (u'שישים',), + 7: (u'שבעים',), + 8: (u'שמונים',), + 9: (u'תשעים',), +} + +HUNDREDS = { + 1: (u'מאה', u'מאת'), + 2: (u'מאתיים',), + 3: (u'מאות',) +} + +THOUSANDS = { + 1: (u'אלף',), + 2: (u'אלפיים',), + 3: (u'אלפים', 'אלפי'), +} + +LARGE = { + 1: (u'מיליון', u'מיליוני'), + 2: (u'מיליארד', u'מיליארדי'), + 3: (u'טריליון', u'טריליוני'), + 4: (u'קוודריליון', u'קוודריליוני'), + 5: (u'קווינטיליון', u'קווינטיליוני'), + 6: (u'סקסטיליון', u'סקסטיליוני'), + 7: (u'ספטיליון', u'ספטיליוני'), + 8: (u'אוקטיליון', u'אוקטיליוני'), + 9: (u'נוניליון', u'נוניליוני'), + 10: (u'דסיליון', u'דסיליוני'), + 11: (u'אונדסיליון', u'אונדסיליוני'), + 12: (u'דואודסיליון', u'דואודסיליוני'), + 13: (u'טרדסיליון', u'טרדסיליוני'), + 14: (u'קווטואורדסיליון', u'קווטואורדסיליוני'), + 15: (u'קווינדסיליון', u'קווינדסיליוני'), + 16: (u'סקסדסיליון', u'סקסדסיליוני'), + 17: (u'ספטנדסיליון', u'ספטנדסיליוני'), + 18: (u'אוקטודסיליון', u'אוקטודסיליוני'), + 19: (u'נובמדסיליון', u'נובמדסיליוני'), + 20: (u'ויגינטיליון', u'ויגינטיליוני') +} + +AND = u'ו' + +DEF = u'ה' + +MAXVAL = int('1' + '0'*66) + + +def chunk2word(n, i, x, gender='f', construct=False, + ordinal=False, plural=False): + words = [] + n1, n2, n3 = get_digits(x) + + if n3 > 0: + if construct and n == 100: + words.append(HUNDREDS[n3][1]) + elif n3 <= 2: + words.append(HUNDREDS[n3][0]) + else: + words.append(ONES[n3][0] + ' ' + HUNDREDS[3][0]) + + if n2 > 1: + words.append(TWENTIES[n2][0]) + + if i == 0 or x >= 11: + male = gender == 'm' or i > 0 + cop = (2*(construct and i == 0)+4*ordinal+2*plural) * (n < 11) + if n2 == 1: + if n1 == 0: + words.append(TENS[n1][male + cop]) + elif n1 == 2: + words.append(TENS[n1][male]) + else: + words.append(ONES[n1][male] + ' ' + TENS[1][male]) + elif n1 > 0: + words.append(ONES[n1][male + cop]) + + construct_last = construct and (n % 1000 ** i == 0) + + if i == 1: + if x >= 11: + words[-1] = words[-1] + ' ' + THOUSANDS[1][0] + elif n1 == 0: + words.append(TENS[0][3] + ' ' + THOUSANDS[3][construct_last]) + elif n1 <= 2: + words.append(THOUSANDS[n1][0]) + else: + words.append(ONES[n1][3] + ' ' + THOUSANDS[3][construct_last]) + + elif i > 1: + if x >= 11: + words[-1] = words[-1] + ' ' + LARGE[i - 1][construct_last] + elif n1 == 0: + words.append(TENS[0][1 + 2*construct_last] + ' ' + + LARGE[i - 1][construct_last]) + elif n1 == 1: + words.append(LARGE[i - 1][0]) + else: + words.append(ONES[n1][1 + 2*(construct_last or x == 2)] + ' ' + + LARGE[i - 1][construct_last]) + + return words + + +def int2word(n, gender='f', construct=False, + ordinal=False, definite=False, plural=False): + assert n == int(n) + assert not construct or not ordinal + assert ordinal or (not definite and not plural) + if n >= MAXVAL: + raise OverflowError('abs(%s) must be less than %s.' % (n, MAXVAL)) + + if n == 0: + if ordinal: + return DEF + ZERO[0] + return ZERO[0] + + words = [] + + chunks = list(splitbyx(str(n), 3)) + i = len(chunks) + for x in chunks: + i -= 1 + + if x == 0: + continue + + words += chunk2word(n, i, x, gender=gender, construct=construct, + ordinal=ordinal, plural=plural) + + # https://hebrew-academy.org.il/2017/01/30/%D7%95-%D7%94%D7%97%D7%99%D7%91%D7%95%D7%A8-%D7%91%D7%9E%D7%A1%D7%A4%D7%A8%D7%99%D7%9D # noqa + if len(words) > 1: + words[-1] = AND + words[-1] + + if ordinal and (n >= 11 or definite): + words[0] = DEF + words[0] + + return ' '.join(words) + + +class Num2Word_HE(Num2Word_Base): + CURRENCY_FORMS = { + 'ILS': ((u'שקל', u'שקלים'), (u'אגורה', u'אגורות')), + 'EUR': ((u'אירו', u'אירו'), (u'סנט', u'סנטים')), + 'USD': ((u'דולר', u'דולרים'), (u'סנט', u'סנטים')), + } + + CURRENCY_GENDERS = { + 'ILS': ('m', 'f'), + 'EUR': ('m', 'm'), + 'USD': ('m', 'm'), + } + + def __init__(self, makaf='-'): + super(Num2Word_HE, self).__init__() + self.makaf = makaf + + def setup(self): + super(Num2Word_HE, self).setup() + self.negword = u'מינוס' + self.pointword = u'נקודה' + self.MAXVAL = MAXVAL + + def to_cardinal_float(self, value, gender='f'): + try: + float(value) == value + except (ValueError, TypeError, AssertionError, AttributeError): + raise TypeError(self.errmsg_nonnum % value) + + pre, post = self.float2tuple(float(value)) + + post = str(post) + post = '0'*(self.precision - len(post)) + post + + out = [self.to_cardinal(pre, gender=gender)] + if self.precision: + out.append(self.title(self.pointword)) + + for i in range(self.precision): + curr = int(post[i]) + out.append(to_s(self.to_cardinal(curr))) + + return ' '.join(out) + + def to_cardinal(self, value, gender='f', construct=False): + try: + assert int(value) == value + except (ValueError, TypeError, AssertionError): + # https://hebrew-academy.org.il/2019/12/03/%D7%A2%D7%9C-%D7%94%D7%91%D7%A2%D7%AA-%D7%94%D7%9E%D7%A1%D7%A4%D7%A8-%D7%94%D7%9E%D7%A2%D7%95%D7%A8%D7%91 # noqa + return self.to_cardinal_float(value, gender=gender) + + out = "" + if value < 0: + value = abs(value) + out = "%s " % self.negword.strip() + + if value >= self.MAXVAL: + raise OverflowError(self.errmsg_toobig % (value, self.MAXVAL)) + + return out + int2word(int(value), gender=gender, construct=construct) + + def to_ordinal(self, value, gender='m', definite=False, plural=False): + self.verify_ordinal(value) + + if value >= self.MAXVAL: + raise OverflowError(self.errmsg_toobig % (value, self.MAXVAL)) + + return int2word(int(value), gender=gender, ordinal=True, + definite=definite, plural=plural) + + def pluralize(self, n, forms, currency=None, prefer_singular=False): + assert n == int(n) + form = 1 + if n == 1 or prefer_singular and ( + abs(n) >= 11 or n == 0 or currency != 'ILS'): + form = 0 + return forms[form] + + def to_currency(self, val, currency='ILS', cents=True, + separator=AND, adjective=False, + prefer_singular=False, prefer_singular_cents=False): + left, right, is_negative = parse_currency_parts(val) + + if not separator.startswith(' '): + separator = ' ' + separator + + try: + cr1, cr2 = self.CURRENCY_FORMS[currency] + + except KeyError: + raise NotImplementedError( + 'Currency code "%s" not implemented for "%s"' % + (currency, self.__class__.__name__)) + + minus_str = "%s " % self.negword.strip() if is_negative else "" + try: + gender1, gender2 = self.CURRENCY_GENDERS[currency] + except KeyError: + gender1 = gender2 = '' + + money_str = self.to_cardinal(left, gender=gender1, + construct=left == 2) + if cents: + cents_str = self.to_cardinal(right, gender=gender2, + construct=right == 2) + else: + cents_str = self._cents_terse(right, currency) + sep_parts = separator.split() + if sep_parts and sep_parts[-1] == AND: + separator += self.makaf + + strings = [ + minus_str, + money_str, + self.pluralize(left, cr1, currency=currency, + prefer_singular=prefer_singular), + separator, + cents_str, + self.pluralize(right, cr2, currency=currency, + prefer_singular=prefer_singular_cents) + ] + if left == 1: + strings[1], strings[2] = strings[2], strings[1] + if right == 1: + strings[4], strings[5] = strings[5], strings[4] + # In Hebrew the separator is along with the following word + return u'%s%s %s%s%s %s' % tuple(strings) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_HU.py b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_HU.py new file mode 100644 index 0000000000000000000000000000000000000000..1bf54cf874005eb98df15ef960e5ad754a829bcc --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_HU.py @@ -0,0 +1,165 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2003, Taro Ogawa. All Rights Reserved. +# Copyright (c) 2013, Savoir-faire Linux inc. All Rights Reserved. + +# This library 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. +# This library 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 along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301 USA + +from __future__ import division, print_function, unicode_literals + +from . import lang_EU + +ZERO = 'nulla' + + +class Num2Word_HU(lang_EU.Num2Word_EU): + GIGA_SUFFIX = "illiárd" + MEGA_SUFFIX = "illió" + + def setup(self): + super(Num2Word_HU, self).setup() + + self.negword = "mínusz " + self.pointword = "egész" + + self.mid_numwords = [(1000, "ezer"), (100, "száz"), (90, "kilencven"), + (80, "nyolcvan"), (70, "hetven"), (60, "hatvan"), + (50, "ötven"), (40, "negyven"), (30, "harminc")] + + low_numwords = ["kilenc", "nyolc", "hét", "hat", "öt", "négy", "három", + "kettő", "egy"] + self.low_numwords = (['tizen' + w for w in low_numwords] + + ['tíz'] + + low_numwords) + self.low_numwords = (['huszon' + w for w in low_numwords] + + ['húsz'] + + self.low_numwords + + [ZERO]) + + self.partial_ords = { + 'nulla': 'nullad', + 'egy': 'egyed', + 'kettő': 'ketted', + 'három': 'harmad', + 'négy': 'negyed', + 'öt': 'ötöd', + 'hat': 'hatod', + 'hét': 'heted', + 'nyolc': 'nyolcad', + 'kilenc': 'kilenced', + 'tíz': 'tized', + 'húsz': 'huszad', + 'harminc': 'harmincad', + 'negyven': 'negyvened', + 'ötven': 'ötvened', + 'hatvan': 'hatvanad', + 'hetven': 'hetvened', + 'nyolcvan': 'nyolcvanad', + 'kilencven': 'kilencvened', + 'száz': 'század', + 'ezer': 'ezred', + 'illió': 'milliomod', + 'illiárd': 'milliárdod' + } + + def to_cardinal(self, value, zero=ZERO): + if int(value) != value: + return self.to_cardinal_float(value) + elif value < 0: + out = self.negword + self.to_cardinal(-value) + elif value == 0: + out = zero + elif zero == '' and value == 2: + out = 'két' + elif value < 30: + out = self.cards[value] + elif value < 100: + out = self.tens_to_cardinal(value) + elif value < 1000: + out = self.hundreds_to_cardinal(value) + elif value < 10**6: + out = self.thousands_to_cardinal(value) + else: + out = self.big_number_to_cardinal(value) + return out + + def tens_to_cardinal(self, value): + try: + return self.cards[value] + except KeyError: + return self.cards[value // 10 * 10] + self.to_cardinal(value % 10) + + def hundreds_to_cardinal(self, value): + hundreds = value // 100 + prefix = "száz" + if hundreds != 1: + prefix = self.to_cardinal(hundreds, zero="") + prefix + postfix = self.to_cardinal(value % 100, zero="") + return prefix + postfix + + def thousands_to_cardinal(self, value): + thousands = value // 1000 + prefix = "ezer" + if thousands != 1: + prefix = self.to_cardinal(thousands, zero="") + prefix + postfix = self.to_cardinal(value % 1000, zero="") + return prefix + ('' if value <= 2000 or not postfix else '-') + postfix + + def big_number_to_cardinal(self, value): + digits = len(str(value)) + digits = digits if digits % 3 != 0 else digits - 2 + exp = 10 ** (digits // 3 * 3) + rest = self.to_cardinal(value % exp, '') + return (self.to_cardinal(value // exp, '') + self.cards[exp] + + ('-' + rest if rest else '')) + + def to_ordinal(self, value): + if value < 0: + return self.negword + self.to_ordinal(-value) + if value == 1: + return 'első' + elif value == 2: + return 'második' + else: + out = self.to_cardinal(value) + for card_word, ord_word in self.partial_ords.items(): + if out[-len(card_word):] == card_word: + out = out[:-len(card_word)] + ord_word + break + return out + 'ik' + + def to_ordinal_num(self, value): + self.verify_ordinal(value) + return str(value) + '.' + + def to_year(self, val, suffix=None, longval=True): + # suffix is prefix here + prefix = '' + if val < 0 or suffix is not None: + val = abs(val) + prefix = (suffix + ' ' if suffix is not None else 'i. e. ') + return prefix + self.to_cardinal(val) + + def to_currency(self, val, currency='HUF', cents=True, separator=',', + adjective=False): + return super(Num2Word_HU, self).to_currency( + val, currency, cents, separator, adjective) + + def to_cardinal_float(self, value): + if abs(value) != value: + return self.negword + self.to_cardinal_float(-value) + left, right = str(value).split('.') + return (self.to_cardinal(int(left)) + + ' egész ' + + self.to_cardinal(int(right)) + + ' ' + self.partial_ords[self.cards[10 ** len(right)]]) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_ID.py b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_ID.py new file mode 100644 index 0000000000000000000000000000000000000000..54e636f95ae64cd509d8e0ed52b7fff1750c259e --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_ID.py @@ -0,0 +1,204 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2003, Taro Ogawa. All Rights Reserved. +# Copyright (c) 2013, Savoir-faire Linux inc. All Rights Reserved. + +# This library 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. +# This library 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 along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301 USA + +from __future__ import print_function, unicode_literals + + +class Num2Word_ID(): + BASE = {0: [], + 1: ["satu"], + 2: ["dua"], + 3: ["tiga"], + 4: ["empat"], + 5: ["lima"], + 6: ["enam"], + 7: ["tujuh"], + 8: ["delapan"], + 9: ["sembilan"]} + + TENS_TO = {3: "ribu", + 6: "juta", + 9: "miliar", + 12: "triliun", + 15: "kuadriliun", + 18: "kuantiliun", + 21: "sekstiliun", + 24: "septiliun", + 27: "oktiliun", + 30: "noniliun", + 33: "desiliun"} + + errmsg_floatord = "Cannot treat float number as ordinal" + errmsg_negord = "Cannot treat negative number as ordinal" + errmsg_toobig = "Number is too large to convert to words (abs(%s) > %s)." + MAXVAL = 10 ** 36 + + def split_by_koma(self, number): + return str(number).split('.') + + def split_by_3(self, number): + """ + starting here, it groups the number by three from the tail + '1234567' -> (('1',),('234',),('567',)) + :param number:str + :rtype:tuple + """ + blocks = () + length = len(number) + + if length < 3: + blocks += ((number,),) + else: + len_of_first_block = length % 3 + + if len_of_first_block > 0: + first_block = number[0:len_of_first_block], + blocks += first_block, + + for i in range(len_of_first_block, length, 3): + next_block = (number[i:i + 3],), + blocks += next_block + + return blocks + + def spell(self, blocks): + """ + it adds the list of spelling to the blocks + ( + ('1',),('034',)) -> (('1',['satu']),('234',['tiga', 'puluh', 'empat']) + ) + :param blocks: tuple + :rtype: tuple + """ + word_blocks = () + first_block = blocks[0] + if len(first_block[0]) == 1: + if first_block[0] == '0': + spelling = ['nol'] + else: + spelling = self.BASE[int(first_block[0])] + elif len(first_block[0]) == 2: + spelling = self.puluh(first_block[0]) + else: + spelling = ( + self.ratus(first_block[0][0]) + self.puluh(first_block[0][1:3]) + ) + + word_blocks += (first_block[0], spelling), + + for block in blocks[1:]: + spelling = self.ratus(block[0][0]) + self.puluh(block[0][1:3]) + block += spelling, + word_blocks += block, + + return word_blocks + + def ratus(self, number): + # it is used to spell + if number == '1': + return ['seratus'] + elif number == '0': + return [] + else: + return self.BASE[int(number)] + ['ratus'] + + def puluh(self, number): + # it is used to spell + if number[0] == '1': + if number[1] == '0': + return ['sepuluh'] + elif number[1] == '1': + return ['sebelas'] + else: + return self.BASE[int(number[1])] + ['belas'] + elif number[0] == '0': + return self.BASE[int(number[1])] + else: + return ( + self.BASE[int(number[0])] + ['puluh'] + + self.BASE[int(number[1])] + ) + + def spell_float(self, float_part): + # spell the float number + word_list = [] + for n in float_part: + if n == '0': + word_list += ['nol'] + continue + word_list += self.BASE[int(n)] + return ' '.join(['', 'koma'] + word_list) + + def join(self, word_blocks, float_part): + """ + join the words by first join lists in the tuple + :param word_blocks: tuple + :rtype: str + """ + word_list = [] + length = len(word_blocks) - 1 + first_block = word_blocks[0], + start = 0 + + if length == 1 and first_block[0][0] == '1': + word_list += ['seribu'] + start = 1 + + for i in range(start, length + 1, 1): + word_list += word_blocks[i][1] + if not word_blocks[i][1]: + continue + if i == length: + break + word_list += [self.TENS_TO[(length - i) * 3]] + + return ' '.join(word_list) + float_part + + def to_cardinal(self, number): + if number >= self.MAXVAL: + raise OverflowError(self.errmsg_toobig % (number, self.MAXVAL)) + minus = '' + if number < 0: + minus = 'min ' + float_word = '' + n = self.split_by_koma(abs(number)) + if len(n) == 2: + float_word = self.spell_float(n[1]) + return minus + self.join(self.spell(self.split_by_3(n[0])), float_word) + + def to_ordinal(self, number): + self.verify_ordinal(number) + out_word = self.to_cardinal(number) + if out_word == "satu": + return "pertama" + return "ke" + out_word + + def to_ordinal_num(self, number): + self.verify_ordinal(number) + return "ke-" + str(number) + + def to_currency(self, value): + return self.to_cardinal(value) + " rupiah" + + def to_year(self, value): + return self.to_cardinal(value) + + def verify_ordinal(self, value): + if not value == int(value): + raise TypeError(self.errmsg_floatord % value) + if not abs(value) == value: + raise TypeError(self.errmsg_negord % value) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_IS.py b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_IS.py new file mode 100644 index 0000000000000000000000000000000000000000..e29eb7a73be6798b4131170437b47147494e718d --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_IS.py @@ -0,0 +1,127 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2003, Taro Ogawa. All Rights Reserved. +# Copyright (c) 2013, Savoir-faire Linux inc. All Rights Reserved. + +# This library 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. +# This library 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 along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301 USA + +from __future__ import division, print_function, unicode_literals + +from . import lang_EU + +# Genders +KK = 0 # Karlkyn (male) +KVK = 1 # Kvenkyn (female) +HK = 2 # Hvorugkyn (neuter) + +GENDERS = { + "einn": ("einn", "ein", "eitt"), + "tveir": ("tveir", "tvær", "tvö"), + "þrír": ("þrír", "þrjár", "þrjú"), + "fjórir": ("fjórir", "fjórar", "fjögur"), +} + +PLURALS = { + "hundrað": ("hundrað", "hundruð"), +} + + +class Num2Word_IS(lang_EU.Num2Word_EU): + + GIGA_SUFFIX = "illjarður" + MEGA_SUFFIX = "illjón" + + def setup(self): + lows = ["okt", "sept", "sext", "kvint", "kvaðr", "tr", "b", "m"] + self.high_numwords = self.gen_high_numwords([], [], lows) + + self.negword = "mínus " + self.pointword = "komma" + + # All words should be excluded, title case is not used in Icelandic + self.exclude_title = ["og", "komma", "mínus"] + + self.mid_numwords = [(1000, "þúsund"), (100, "hundrað"), + (90, "níutíu"), (80, "áttatíu"), (70, "sjötíu"), + (60, "sextíu"), (50, "fimmtíu"), (40, "fjörutíu"), + (30, "þrjátíu")] + self.low_numwords = ["tuttugu", "nítján", "átján", "sautján", + "sextán", "fimmtán", "fjórtán", "þrettán", + "tólf", "ellefu", "tíu", "níu", "átta", + "sjö", "sex", "fimm", "fjórir", "þrír", + "tveir", "einn", "núll"] + self.ords = {"einn": "fyrsti", + "tveir": "annar", + "þrír": "þriðji", + "fjórir": "fjórði", + "fimm": "fimmti", + "sex": "sjötti", + "sjö": "sjöundi", + "átta": "áttundi", + "níu": "níundi", + "tíu": "tíundi", + "ellefu": "ellefti", + "tólf": "tólfti"} + + def pluralize(self, n, noun): + form = 0 if (n % 10 == 1 and n % 100 != 11) else 1 + if form == 0: + return noun + elif self.GIGA_SUFFIX in noun: + return noun.replace(self.GIGA_SUFFIX, "illjarðar") + elif self.MEGA_SUFFIX in noun: + return noun.replace(self.MEGA_SUFFIX, "illjónir") + elif noun not in PLURALS: + return noun + return PLURALS[noun][form] + + def genderize(self, adj, noun): + last = adj.split()[-1] + if last not in GENDERS: + return adj + gender = KK + if "hund" in noun or "þús" in noun: + gender = HK + elif "illjarð" in noun: + gender = KK + elif "illjón" in noun: + gender = KVK + return adj.replace(last, GENDERS[last][gender]) + + def merge(self, lpair, rpair): + ltext, lnum = lpair + rtext, rnum = rpair + + if lnum == 1 and rnum < 100: + return (rtext, rnum) + elif lnum < rnum: + rtext = self.pluralize(lnum, rtext) + ltext = self.genderize(ltext, rtext) + return ("%s %s" % (ltext, rtext), lnum * rnum) + elif lnum > rnum and rnum in self.cards: + rtext = self.pluralize(lnum, rtext) + ltext = self.genderize(ltext, rtext) + return ("%s og %s" % (ltext, rtext), lnum + rnum) + return ("%s %s" % (ltext, rtext), lnum + rnum) + + def to_ordinal(self, value): + raise NotImplementedError + + def to_ordinal_num(self, value): + raise NotImplementedError + + def to_year(self, val, suffix=None, longval=True): + raise NotImplementedError + + def to_currency(self, val, longval=True): + raise NotImplementedError diff --git a/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_IT.py b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_IT.py new file mode 100644 index 0000000000000000000000000000000000000000..427e6d36852d6298d8ef3bceb4cdf851d30eff03 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_IT.py @@ -0,0 +1,241 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2018-2019, Filippo Costa. All Rights Reserved. + +# This library 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. +# This library 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 along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301 USA + +from __future__ import unicode_literals + +from .lang_EU import Num2Word_EU + +# Globals +# ------- + +ZERO = "zero" + +CARDINAL_WORDS = [ + ZERO, "uno", "due", "tre", "quattro", "cinque", "sei", "sette", "otto", + "nove", "dieci", "undici", "dodici", "tredici", "quattordici", "quindici", + "sedici", "diciassette", "diciotto", "diciannove" +] + +ORDINAL_WORDS = [ + ZERO, "primo", "secondo", "terzo", "quarto", "quinto", "sesto", "settimo", + "ottavo", "nono", "decimo", "undicesimo", "dodicesimo", "tredicesimo", + "quattordicesimo", "quindicesimo", "sedicesimo", "diciassettesimo", + "diciottesimo", "diciannovesimo" +] + +# The script can extrapolate the missing numbers from the base forms. +STR_TENS = {2: "venti", 3: "trenta", 4: "quaranta", 6: "sessanta"} + +# These prefixes are used for extremely big numbers. +EXPONENT_PREFIXES = [ + ZERO, "m", "b", "tr", "quadr", "quint", "sest", "sett", "ott", "nov", "dec" +] + + +GENERIC_DOLLARS = ('dollaro', 'dollari') +GENERIC_CENTS = ('centesimo', 'centesimi') +CURRENCIES_UNA = ('GBP') + + +# Main class +# ========== + +class Num2Word_IT(Num2Word_EU): + CURRENCY_FORMS = { + 'EUR': (('euro', 'euro'), GENERIC_CENTS), + 'USD': (GENERIC_DOLLARS, GENERIC_CENTS), + 'GBP': (('sterlina', 'sterline'), ('penny', 'penny')), + 'CNY': (('yuan', 'yuan'), ('fen', 'fen')), + } + MINUS_PREFIX_WORD = "meno " + FLOAT_INFIX_WORD = " virgola " + + def setup(self): + Num2Word_EU.setup(self) + + def __init__(self): + pass + + def float_to_words(self, float_number, ordinal=False): + if ordinal: + prefix = self.to_ordinal(int(float_number)) + else: + prefix = self.to_cardinal(int(float_number)) + float_part = str(float_number).split('.')[1] + postfix = " ".join( + # Drops the trailing zero and comma + [self.to_cardinal(int(c)) for c in float_part] + ) + return prefix + Num2Word_IT.FLOAT_INFIX_WORD + postfix + + def tens_to_cardinal(self, number): + tens = number // 10 + units = number % 10 + if tens in STR_TENS: + prefix = STR_TENS[tens] + else: + prefix = CARDINAL_WORDS[tens][:-1] + "anta" + postfix = omitt_if_zero(CARDINAL_WORDS[units]) + return phonetic_contraction(prefix + postfix) + + def hundreds_to_cardinal(self, number): + hundreds = number // 100 + prefix = "cento" + if hundreds != 1: + prefix = CARDINAL_WORDS[hundreds] + prefix + postfix = omitt_if_zero(self.to_cardinal(number % 100)) + return phonetic_contraction(prefix + postfix) + + def thousands_to_cardinal(self, number): + thousands = number // 1000 + if thousands == 1: + prefix = "mille" + else: + prefix = self.to_cardinal(thousands) + "mila" + postfix = omitt_if_zero(self.to_cardinal(number % 1000)) + # "mille" and "mila" don't need any phonetic contractions + return prefix + postfix + + def big_number_to_cardinal(self, number): + digits = [c for c in str(number)] + length = len(digits) + if length >= 66: + raise NotImplementedError("The given number is too large.") + # This is how many digits come before the "illion" term. + # cento miliardi => 3 + # dieci milioni => 2 + # un miliardo => 1 + predigits = length % 3 or 3 + multiplier = digits[:predigits] + exponent = digits[predigits:] + # Default infix string: "milione", "biliardo", "sestilione", ecc. + infix = exponent_length_to_string(len(exponent)) + if multiplier == ["1"]: + prefix = "un " + else: + prefix = self.to_cardinal(int("".join(multiplier))) + # Plural form ~~~~~~~~~~~ + infix = " " + infix[:-1] + "i" + # Read as: Does the value of exponent equal 0? + if set(exponent) != set("0"): + postfix = self.to_cardinal(int("".join(exponent))) + if " e " in postfix: + infix += ", " + else: + infix += " e " + else: + postfix = "" + return prefix + infix + postfix + + def to_cardinal(self, number): + if number < 0: + string = Num2Word_IT.MINUS_PREFIX_WORD + self.to_cardinal(-number) + elif isinstance(number, float): + string = self.float_to_words(number) + elif number < 20: + string = CARDINAL_WORDS[int(number)] + elif number < 100: + string = self.tens_to_cardinal(int(number)) + elif number < 1000: + string = self.hundreds_to_cardinal(int(number)) + elif number < 1000000: + string = self.thousands_to_cardinal(int(number)) + else: + string = self.big_number_to_cardinal(number) + return accentuate(string) + + def to_ordinal(self, number): + tens = number % 100 + # Italian grammar is poorly defined here ¯\_(ツ)_/¯: + # centodecimo VS centodieciesimo VS centesimo decimo? + is_outside_teens = not 10 < tens < 20 + if number < 0: + return Num2Word_IT.MINUS_PREFIX_WORD + self.to_ordinal(-number) + elif number % 1 != 0: + return self.float_to_words(number, ordinal=True) + elif number < 20: + return ORDINAL_WORDS[int(number)] + elif is_outside_teens and tens % 10 == 3: + # Gets rid of the accent + return self.to_cardinal(number)[:-1] + "eesimo" + elif is_outside_teens and tens % 10 == 6: + return self.to_cardinal(number) + "esimo" + else: + string = self.to_cardinal(number)[:-1] + if string[-3:] == "mil": + string += "l" + return string + "esimo" + + def to_currency(self, val, currency='EUR', cents=True, separator=' e', + adjective=False): + result = super(Num2Word_IT, self).to_currency( + val, currency=currency, cents=cents, separator=separator, + adjective=adjective) + # Handle exception. In italian language is "un euro", + # "un dollaro" etc. (not "uno euro", "uno dollaro"). + # There is an exception, some currencies need "una": + # e.g. "una sterlina" + if currency in CURRENCIES_UNA: + list_result = result.split(" ") + if list_result[0] == "uno": + list_result[0] = list_result[0].replace("uno", "una") + result = " ".join(list_result) + result = result.replace("uno", "un") + return result + +# Utils +# ===== + + +def phonetic_contraction(string): + return (string + .replace("oo", "o") # ex. "centootto" + .replace("ao", "o") # ex. "settantaotto" + .replace("io", "o") # ex. "ventiotto" + .replace("au", "u") # ex. "trentauno" + .replace("iu", "u") # ex. "ventiunesimo" + ) + + +def exponent_length_to_string(exponent_length): + # We always assume `exponent` to be a multiple of 3. If it's not true, then + # Num2Word_IT.big_number_to_cardinal did something wrong. + prefix = EXPONENT_PREFIXES[exponent_length // 6] + if exponent_length % 6 == 0: + return prefix + "ilione" + else: + return prefix + "iliardo" + + +def accentuate(string): + # This is inefficient: it may do several rewritings when deleting + # half-sentence accents. However, it is the easiest method and speed is + # not crucial (duh), so... + return " ".join( + # Deletes half-sentence accents and accentuates the last "tre" + [w.replace("tré", "tre")[:-3] + "tré" + # We shouldn't accentuate a single "tre": is has to be a composite + # word. ~~~~~~~~~~ + if w[-3:] == "tre" and len(w) > 3 + # Deletes half-sentence accents anyway + # ~~~~~~~~~~~~~~~~~~~~~~ + else w.replace("tré", "tre") + for w in string.split() + ]) + + +def omitt_if_zero(number_to_string): + return "" if number_to_string == ZERO else number_to_string diff --git a/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_JA.py b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_JA.py new file mode 100644 index 0000000000000000000000000000000000000000..1e0e62220577df77ca6a01fe895e9bea4f99bd5d --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_JA.py @@ -0,0 +1,590 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2003, Taro Ogawa. All Rights Reserved. +# Copyright (c) 2013, Savoir-faire Linux inc. All Rights Reserved. + +# This library 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. +# This library 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 along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301 USA + +from __future__ import division, print_function, unicode_literals + +from .base import Num2Word_Base +from .compat import strtype, to_s +from .currency import parse_currency_parts, prefix_currency + + +def select_text(text, reading=False, prefer=None): + """Select the correct text from the Japanese number, reading and + alternatives""" + # select kanji number or kana reading + if reading: + text = text[1] + else: + text = text[0] + + # select the preferred one or the first one from multiple alternatives + if not isinstance(text, strtype): + common = set(text) & set(prefer or set()) + if len(common) == 1: + text = common.pop() + else: + text = text[0] + + return text + + +def rendaku_merge_pairs(lpair, rpair): + """Merge lpair < rpair while applying semi-irregular rendaku rules""" + ltext, lnum = lpair + rtext, rnum = rpair + if lnum > rnum: + raise ValueError + + if rpair == ("ひゃく", 100): + if lpair == ("さん", 3): + rtext = "びゃく" + elif lpair == ("ろく", 6): + ltext = "ろっ" + rtext = "ぴゃく" + elif lpair == ("はち", 8): + ltext = "はっ" + rtext = "ぴゃく" + elif rpair == ("せん", 1000): + if lpair == ("さん", 3): + rtext = "ぜん" + elif lpair == ("はち", 8): + ltext = "はっ" + elif rpair == ("ちょう", 10**12): + if lpair == ("いち", 1): + ltext = "いっ" + elif lpair == ("はち", 8): + ltext = "はっ" + elif lpair == ("じゅう", 10): + ltext = "じゅっ" + elif rpair == ("けい", 10**16): + if lpair == ("いち", 1): + ltext = "いっ" + elif lpair == ("ろく", 6): + ltext = "ろっ" + elif lpair == ("はち", 8): + ltext = "はっ" + elif lpair == ("じゅう", 10): + ltext = "じゅっ" + elif lpair == ("ひゃく", 100): + ltext = "ひゃっ" + + return ("%s%s" % (ltext, rtext), lnum * rnum) + + +# Source: https://www.sljfaq.org/afaq/era-list.html +# if there are multiple eras for the same year, use the last one +ERA_START = [ + (645, ("大化", "たいか")), + (650, ("白雉", "はくち")), + (686, ("朱鳥", "しゅちょう")), + (701, ("大宝", "たいほう")), + (704, ("慶雲", "けいうん")), + (708, ("和銅", "わどう")), + (715, ("霊亀", "れいき")), + (717, ("養老", "ようろう")), + (724, ("神亀", "じんき")), + (729, ("天平", "てんぴょう")), + (749, ("天平感宝", "てんぴょうかんぽう")), + (749, ("天平勝宝", "てんぴょうしょうほう")), + (757, ("天平宝字", "てんぴょうじょうじ")), + (765, ("天平神護", "てんぴょうじんご")), + (767, ("神護景雲", "じんごけいうん")), + (770, ("宝亀", "ほうき")), + (781, ("天応", "てんおう")), + (782, ("延暦", "えんりゃく")), + (806, ("大同", "だいどう")), + (810, ("弘仁", "こうにん")), + (823, ("天長", "てんちょう")), + (834, ("承和", "じょうわ")), + (848, ("嘉祥", "かしょう")), + (851, ("仁寿", "にんじゅ")), + (855, ("斉衡", "さいこう")), + (857, ("天安", "てんあん")), + (859, ("貞観", "じょうがん")), + (877, ("元慶", "がんぎょう")), + (885, ("仁和", "にんな")), + (889, ("寛平", "かんぴょう")), + (898, ("昌泰", "しょうたい")), + (901, ("延喜", "えんぎ")), + (923, ("延長", "えんちょう")), + (931, ("承平", "じょうへい")), + (938, ("天慶", "てんぎょう")), + (947, ("天暦", "てんりゃく")), + (957, ("天徳", "てんとく")), + (961, ("応和", "おうわ")), + (964, ("康保", "こうほう")), + (968, ("安和", "あんな")), + (970, ("天禄", "てんろく")), + (974, ("天延", "てんえん")), + (976, ("貞元", "じょうげん")), + (979, ("天元", "てんげん")), + (983, ("永観", "えいかん")), + (985, ("寛和", "かんな")), + (987, ("永延", "えいえん")), + (989, ("永祚", "えいそ")), + (990, ("正暦", "しょうりゃく")), + (995, ("長徳", "ちょうとく")), + (999, ("長保", "ちょうほう")), + (1004, ("寛弘", "かんこう")), + (1013, ("長和", "ちょうわ")), + (1017, ("寛仁", "かんにん")), + (1021, ("治安", "じあん")), + (1024, ("万寿", "まんじゅ")), + (1028, ("長元", "ちょうげん")), + (1037, ("長暦", "ちょうりゃく")), + (1040, ("長久", "ちょうきゅう")), + (1045, ("寛徳", "かんとく")), + (1046, ("永承", "えいしょう")), + (1053, ("天喜", "てんぎ")), + (1058, ("康平", "こうへい")), + (1065, ("治暦", "じりゃく")), + (1069, ("延久", "えんきゅう")), + (1074, ("承保", "じょうほう")), + (1078, ("承暦", "じょうりゃく")), + (1081, ("永保", "えいほう")), + (1084, ("応徳", "おうとく")), + (1087, ("寛治", "かんじ")), + (1095, ("嘉保", "かほう")), + (1097, ("永長", "えいちょう")), + (1098, ("承徳", "じょうとく")), + (1099, ("康和", "こうわ")), + (1104, ("長治", "ちょうじ")), + (1106, ("嘉承", "かじょう")), + (1108, ("天仁", "てんにん")), + (1110, ("天永", "てんねい")), + (1113, ("永久", "えいきゅう")), + (1118, ("元永", "げんえい")), + (1120, ("保安", "ほうあん")), + (1124, ("天治", "てんじ")), + (1126, ("大治", "だいじ")), + (1131, ("天承", "てんしょう")), + (1132, ("長承", "ちょうしょう")), + (1135, ("保延", "ほうえん")), + (1141, ("永治", "えいじ")), + (1142, ("康治", "こうじ")), + (1144, ("天養", "てんよう")), + (1145, ("久安", "きゅうあん")), + (1151, ("仁平", "にんぺい")), + (1154, ("久寿", "きゅうじゅ")), + (1156, ("保元", "ほうげん")), + (1159, ("平治", "へいじ")), + (1160, ("永暦", "えいりゃく")), + (1161, ("応保", "おうほう")), + (1163, ("長寛", "ちょうかん")), + (1165, ("永万", "えいまん")), + (1166, ("仁安", "にんあん")), + (1169, ("嘉応", "かおう")), + (1171, ("承安", "しょうあん")), + (1175, ("安元", "あんげん")), + (1177, ("治承", "じしょう")), + (1181, ("養和", "ようわ")), + (1182, ("寿永", "じゅえい")), + (1184, ("元暦", "げんりゃく")), + (1185, ("文治", "ぶんじ")), + (1190, ("建久", "けんきゅう")), + (1199, ("正治", "しょうじ")), + (1201, ("建仁", "けんにん")), + (1204, ("元久", "げんきゅう")), + (1206, ("建永", "けんえい")), + (1207, ("承元", "じょうげん")), + (1211, ("建暦", "けんりゃく")), + (1214, ("建保", "けんぽう")), + (1219, ("承久", "じょうきゅう")), + (1222, ("貞応", "じょうおう")), + (1225, ("元仁", "げんにん")), + (1225, ("嘉禄", "かろく")), + (1228, ("安貞", "あんてい")), + (1229, ("寛喜", "かんき")), + (1232, ("貞永", "じょうえい")), + (1233, ("天福", "てんぷく")), + (1235, ("文暦", "ぶんりゃく")), + (1235, ("嘉禎", "かてい")), + (1239, ("暦仁", "りゃくにん")), + (1239, ("延応", "えんおう")), + (1240, ("仁治", "にんじ")), + (1243, ("寛元", "かんげん")), + (1247, ("宝治", "ほうじ")), + (1249, ("建長", "けんちょう")), + (1256, ("康元", "こうげん")), + (1257, ("正嘉", "しょうか")), + (1259, ("正元", "しょうげん")), + (1260, ("文応", "ぶんおう")), + (1261, ("弘長", "こうちょう")), + (1264, ("文永", "ぶんえい")), + (1275, ("健治", "けんじ")), + (1278, ("弘安", "こうあん")), + (1288, ("正応", "しょうおう")), + (1293, ("永仁", "えいにん")), + (1299, ("正安", "しょうあん")), + (1303, ("乾元", "けんげん")), + (1303, ("嘉元", "かげん")), + (1307, ("徳治", "とくじ")), + (1308, ("延慶", "えんきょう")), + (1311, ("応長", "おうちょう")), + (1312, ("正和", "しょうわ")), + (1317, ("文保", "ぶんぽう")), + (1319, ("元応", "げんおう")), + (1321, ("元亨", "げんこう")), + (1325, ("正中", "しょうちゅ")), + (1326, ("嘉暦", "かりゃく")), + (1329, ("元徳", "げんとく")), + (1331, ("元弘", "げんこう")), + (1332, ("正慶", "しょうけい")), + (1334, ("建武", "けんむ")), + (1336, ("延元", "えいげん")), + (1338, ("暦応", "りゃくおう")), + (1340, ("興国", "こうこく")), + (1342, ("康永", "こうえい")), + (1345, ("貞和", "じょうわ")), + (1347, ("正平", "しょうへい")), + (1350, ("観応", "かんおう")), + (1352, ("文和", "ぶんな")), + (1356, ("延文", "えんぶん")), + (1361, ("康安", "こうあん")), + (1362, ("貞治", "じょうじ")), + (1368, ("応安", "おうあん")), + (1370, ("建徳", "けんとく")), + (1372, ("文中", "ぶんちゅう")), + (1375, ("永和", "えいわ")), + (1375, ("天授", "てんじゅ")), + (1379, ("康暦", "こうりゃく")), + (1381, ("永徳", "えいとく")), + (1381, ("弘和", "こうわ")), + (1384, ("至徳", "しとく")), + (1384, ("元中", "げんちゅう")), + (1387, ("嘉慶", "かけい")), + (1389, ("康応", "こうおう")), + (1390, ("明徳", "めいとく")), + (1394, ("応永", "おうえい")), + (1428, ("正長", "しょうちょう")), + (1429, ("永享", "えいきょう")), + (1441, ("嘉吉", "かきつ")), + (1444, ("文安", "ぶんあん")), + (1449, ("宝徳", "ほうとく")), + (1452, ("享徳", "きょうとく")), + (1455, ("康正", "こうしょう")), + (1457, ("長禄", "ちょうろく")), + (1461, ("寛正", "かんしょう")), + (1466, ("文正", "ぶんしょう")), + (1467, ("応仁", "おうにん")), + (1469, ("文明", "ぶんめい")), + (1487, ("長享", "ちょうきょう")), + (1489, ("延徳", "えんとく")), + (1492, ("明応", "めいおう")), + (1501, ("文亀", "ぶんき")), + (1504, ("永正", "えいしょう")), + (1521, ("大永", "だいえい")), + (1528, ("享禄", "きょうろく")), + (1532, ("天文", "てんぶん")), + (1555, ("弘治", "こうじ")), + (1558, ("永禄", "えいろく")), + (1570, ("元亀", "げんき")), + (1573, ("天正", "てんしょう")), + (1593, ("文禄", "ぶんろく")), + (1596, ("慶長", "けいちょう")), + (1615, ("元和", "げんな")), + (1624, ("寛永", "かんえい")), + (1645, ("正保", "しょうほう")), + (1648, ("慶安", "けいあん")), + (1652, ("承応", "じょうおう")), + (1655, ("明暦", "めいれき")), + (1658, ("万治", "まんじ")), + (1661, ("寛文", "かんぶん")), + (1673, ("延宝", "えんぽう")), + (1681, ("天和", "てんな")), + (1684, ("貞享", "じょうきょう")), + (1688, ("元禄", "げんろく")), + (1704, ("宝永", "ほうえい")), + (1711, ("正徳", "しょうとく")), + (1716, ("享保", "きょうほう")), + (1736, ("元文", "げんぶん")), + (1741, ("寛保", "かんぽう")), + (1744, ("延享", "えんきょう")), + (1748, ("寛延", "かんえん")), + (1751, ("宝暦", "ほうれき")), + (1764, ("明和", "めいわ")), + (1773, ("安永", "あんえい")), + (1781, ("天明", "てんめい")), + (1801, ("寛政", "かんせい")), + (1802, ("享和", "きょうわ")), + (1804, ("文化", "ぶんか")), + (1818, ("文政", "ぶんせい")), + (1831, ("天保", "てんぽう")), + (1845, ("弘化", "こうか")), + (1848, ("嘉永", "かえい")), + (1855, ("安政", "あんせい")), + (1860, ("万延", "まんえい")), + (1861, ("文久", "ぶんきゅう")), + (1864, ("元治", "げんじ")), + (1865, ("慶応", "けいおう")), + (1868, ("明治", "めいじ")), + (1912, ("大正", "たいしょう")), + (1926, ("昭和", "しょうわ")), + (1989, ("平成", "へいせい")), + (2019, ("令和", "れいわ")), +] + + +class Num2Word_JA(Num2Word_Base): + CURRENCY_FORMS = { + 'JPY': (('円', 'えん'), ()), + } + + def set_high_numwords(self, high): + max = 4 * len(high) + for word, n in zip(high, range(max, 0, -4)): + self.cards[10 ** n] = word + + def setup(self): + self.negword = "マイナス" + self.pointword = ("点", "てん") + self.exclude_title = ["点", "マイナス"] + + self.high_numwords = [ + ("万", "まん"), # 10**4 man + ("億", "おく"), # 10**8 oku + ("兆", "ちょう"), # 10**12 chō + ("京", "けい"), # 10**16 kei + ("垓", "がい"), # 10**20 gai + ("秭", "し"), # 10**24 shi + ("穣", "じょう"), # 10**28 jō + ("溝", "こう"), # 10**32 kō + ("澗", "かん"), # 10**36 kan + ("正", "せい"), # 10**40 sei + ("載", "さい"), # 10**44 sai + ("極", "ごく"), # 10**48 goku + ] + + self.high_numwords.reverse() + + self.mid_numwords = [ + (1000, ("千", "せん")), + (100, ("百", "ひゃく")), + ] + + self.low_numwords = [ + ("十", "じゅう"), # 10 jū + ("九", "きゅう"), # 9 kyū + ("八", "はち"), # 8 hachi + ("七", ("なな", "しち")), # 7 nana, shichi + ("六", "ろく"), # 6 roku + ("五", "ご"), # 5 go + ("四", ("よん", "し")), # 4 yon, shi + ("三", "さん"), # 3 san + ("二", "に"), # 2 ni + ("一", "いち"), # 1 ichi + # both are alternatives, 零 doesn't map to ゼロ or 〇 to れい + (("零", "〇"), ("ゼロ", "れい")), # 0 ZERO, rei + ] + + def merge(self, lpair, rpair): + ltext, lnum = lpair + rtext, rnum = rpair + + fmt = "%s%s" + # ignore lpair if lnum is 1 and rnum is less than 10000 + if lnum == 1 and rnum < 10000: + return rpair + # rnum is added to lnum + elif lnum > rnum: + return (fmt % (ltext, rtext), lnum + rnum) + # rnum is multiplied by lnum + elif lnum < rnum: + return rendaku_merge_pairs(lpair, rpair) + + def _ordinal_suffix(self, reading, counter): + if reading: + if counter == "番": + return "ばんめ" + else: + raise NotImplementedError( + "Reading not implemented for %s" % counter) + else: + return counter + "目" + + def to_ordinal(self, value, reading=False, prefer=None, counter="番"): + self.verify_ordinal(value) + base = self.to_cardinal(value, reading=reading, prefer=prefer) + return "%s%s" % (base, self._ordinal_suffix(reading, counter)) + + def to_ordinal_num(self, value, reading=False, counter="番"): + return "%s%s" % (value, self._ordinal_suffix(reading, counter)) + + def to_year(self, val, suffix=None, longval=True, reading=False, + prefer=None, era=True): + year = val + # Gregorian calendar + if not era: + prefix = "" + if year < 0: + year = abs(year) + prefix = "きげんぜん" if reading else "紀元前" + + year_words = self.to_cardinal(year, reading=reading, prefer=prefer) + if reading and year % 10 == 9: + year_words = year_words[:-3] + "く" + + return "%s%s%s" % (prefix, year_words, "ねん" if reading else "年") + + # Era calendar (default) + min_year = ERA_START[0][0] + last_era_idx = len(ERA_START) - 1 + if year < min_year: + raise ValueError( + "Can't convert years less than %s to era" % min_year) + + first = 0 + last = last_era_idx + era_idx = None + while era_idx is None: + mid = (first + last) // 2 + if mid == last_era_idx or (ERA_START[mid][0] <= year and + ERA_START[mid + 1][0] > year): + era_idx = mid + # if an era lasting less than a year is preferred, choose it + if prefer: + i = mid - 1 + while i >= 0 and ERA_START[i][0] == year: + # match kanji or hiragana + if set(ERA_START[i][1]) & set(prefer): + era_idx = i + break + i -= 1 + + # ends up at the last index where year >= ERA_START[mid][0] + if year < ERA_START[mid][0]: + last = mid - 1 + else: + first = mid + 1 + + era = ERA_START[era_idx] + era_name = era[1][0] + era_year = year - era[0] + 1 + fmt = "%s%s年" + if reading == "arabic": + era_year_words = str(era_year) + elif reading: + era_name = era[1][1] + era_year_words = (self.to_cardinal(era_year, reading=True, + prefer=prefer) + if era_year != 1 else "がん") + if era_year % 10 == 9: + era_year_words = era_year_words[:-3] + "く" + fmt = "%s%sねん" + else: + era_year_words = (self.to_cardinal(era_year, reading=False, + prefer=prefer) + if era_year != 1 else "元") + + return fmt % (era_name, era_year_words) + + def to_currency(self, val, currency="JPY", cents=False, separator="", + adjective=False, reading=False, prefer=None): + left, right, is_negative = parse_currency_parts( + val, is_int_with_cents=cents) + + try: + cr1, cr2 = self.CURRENCY_FORMS[currency] + if (cents or abs(val) != left) and not cr2: + raise ValueError('Decimals not supported for "%s"' % currency) + except KeyError: + raise NotImplementedError( + 'Currency code "%s" not implemented for "%s"' % + (currency, self.__class__.__name__)) + + if adjective and currency in self.CURRENCY_ADJECTIVES: + cr1 = prefix_currency(self.CURRENCY_ADJECTIVES[currency], cr1) + + minus_str = self.negword if is_negative else "" + + return '%s%s%s%s%s' % ( + minus_str, + self.to_cardinal(left, reading=reading, prefer=prefer), + cr1[1] if reading else cr1[0], + self.to_cardinal(right, reading=reading, prefer=prefer) + if cr2 else '', + (cr2[1] if reading else cr2[0]) if cr2 else '', + ) + + def splitnum(self, value, reading, prefer): + for elem in self.cards: + if elem > value: + continue + + out = [] + if value == 0: + div, mod = 1, 0 + else: + div, mod = divmod(value, elem) + + if div == 1: + out.append((select_text(self.cards[1], reading, prefer), 1)) + else: + if div == value: # The system tallies, eg Roman Numerals + return [( + div * select_text(self.cards[elem], reading, prefer), + div * elem)] + out.append(self.splitnum(div, reading, prefer)) + + out.append((select_text(self.cards[elem], reading, prefer), elem)) + + if mod: + out.append(self.splitnum(mod, reading, prefer)) + + return out + + def to_cardinal(self, value, reading=False, prefer=None): + try: + assert int(value) == value + except (ValueError, TypeError, AssertionError): + return self.to_cardinal_float(value, reading=reading, + prefer=prefer) + + out = "" + if value < 0: + value = abs(value) + out = self.negword + + if value >= self.MAXVAL: + raise OverflowError(self.errmsg_toobig % (value, self.MAXVAL)) + + val = self.splitnum(value, reading, prefer) + words, _ = self.clean(val) + return self.title(out + words) + + def to_cardinal_float(self, value, reading=False, prefer=None): + prefer = prefer or ["れい"] + try: + float(value) == value + except (ValueError, TypeError, AssertionError): + raise TypeError(self.errmsg_nonnum % value) + + pre, post = self.float2tuple(float(value)) + + post = str(post) + post = '0' * (self.precision - len(post)) + post + + out = [self.to_cardinal(pre, reading=reading, prefer=prefer)] + if self.precision: + out.append(self.title(self.pointword[1 if reading else 0])) + + for i in range(self.precision): + curr = int(post[i]) + out.append(to_s( + self.to_cardinal(curr, reading=reading, prefer=prefer))) + + return "".join(out) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_KN.py b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_KN.py new file mode 100644 index 0000000000000000000000000000000000000000..3bc1ccae31de0f182d42b33d7ee58a75b5187ee3 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_KN.py @@ -0,0 +1,182 @@ +# -*- encoding: utf-8 -*- +# Copyright (c) 2003, Taro Ogawa. All Rights Reserved. +# Copyright (c) 2013, Savoir-faire Linux inc. All Rights Reserved. + +# This library 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. +# This library 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 along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301 USA + +from __future__ import unicode_literals + +from .lang_EU import Num2Word_EU + + +class Num2Word_KN(Num2Word_EU): + def set_high_numwords(self, high): + for n, word in self.high_numwords: + self.cards[10**n] = word + + def setup(self): + self.low_numwords = [ + "ತೊಂಬತ್ತೊಂಬತ್ತು", + "ತೊಂಬತ್ತೆಂಟು", + "ತೊಂಬತ್ತೇಳು", + "ತೊಂಬತ್ತಾರು", + "ತೊಂಬತ್ತೈದು", + "ತೊಂಬತ್ತ ನಾಲ್ಕು", + "ತೊಂಬತ್ತ ಮೂರು", + "ತೊಂಬತ್ತೆರಡು", + "ತೊಂಬತ್ತೊಂದು", + "ತೊಂಬತ್ತು", + "ಎಂಬತ್ತೊಂಬತ್ತು", + "ಎಂಬತ್ತೆಂಟು", + "ಎಂಬತ್ತೇಳು", + "ಎಂಬತ್ತಾರು", + "ಎಂಬತ್ತೈದು", + "ಎಂಬತ್ತ್ ನಾಲ್ಕು", + "ಎಂಬತ್ತ್ ಮೂರು", + "ಎಂಬತ್ತೆರಡು", + "ಎಂಬತ್ತೊಂದು", + "ಎಂಬತ್ತು", + "ಎಪ್ಪತ್ತೊಂಬತ್ತು", + "ಎಪ್ಪತ್ತೆಂಟು", + "ಎಪ್ಪತ್ತೇಳು", + "ಎಪ್ಪತ್ತಾರು", + "ಎಪ್ಪತ್ತೈದು", + "ಎಪ್ಪತ್ತ್ ನಾಲ್ಕು", + "ಎಪ್ಪತ್ತ್ ಮೂರು", + "ಎಪ್ಪತ್ತೆರಡು", + "ಎಪ್ಪತ್ತೊಂದು", + "ಎಪ್ಪತ್ತು", + "ಅರವತ್ತೊಂಬತ್ತು", + "ಅರವತ್ತೆಂಟು", + "ಅರವತ್ತೇಳು", + "ಅರವತ್ತಾರು", + "ಅರವತ್ತೈದು", + "ಅರವತ್ತ್ ನಾಲ್ಕು", + "ಅರವತ್ತ್ ಮೂರು", + "ಅರವತ್ತೆರಡು", + "ಅರವತ್ತೊಂದು", + "ಅರವತ್ತು", + "ಐವತ್ತೊಂಬತ್ತು", + "ಐವತ್ತೆಂಟು", + "ಐವತ್ತೇಳು", + "ಐವತ್ತಾರು", + "ಐವತ್ತೈದು", + "ಐವತ್ತ್ನಾಲ್ಕು", + "ಐವತ್ತಮೂರು", + "ಐವತ್ತೆರಡು", + "ಐವತ್ತೊಂದು", + "ಐವತ್ತು", + "ನಲವತ್ತೊಂಬತ್ತು", + "ನಲವತ್ತೆಂಟು", + "ನಲವತ್ತೇಳು", + "ನಲವತ್ತಾರು", + "ನಲವತ್ತೈದು", + "ನಲವತ್ತ್ ನಾಲ್ಕು", + "ನಲವತ್ತ್ ಮೂರು", + "ನಲವತ್ತ್ ಎರಡು", + "ನಲವತ್ತೊಂದು", + "ನಲವತ್ತು", + "ಮೂವತ್ತ್ ಒಂಬತ್ತು", + "ಮೂವತ್ಎಂಟು", + "ಮೂವತ್ಏಳು", + "ಮೂವತ್ಆರು", + "ಮೂವತ್ತ್ ಐದು", + "ಮೂವತ್ತ್ ನಾಲ್ಕು", + "ಮೂವತ್ತ್ ಮೂರು", + "ಮೂವತ್ತ್ಎರಡು", + "ಮೂವತ್ತ್ಒಂದು", + "ಮೂವತ್ತು", + "ಇಪ್ಪತ್ತ್ಒಂಬತ್ತು", + "ಇಪ್ಪತ್ತ್ಎಂಟು", + "ಇಪ್ಪತ್ತ್ಏಳು", + "ಇಪ್ಪತ್ತ್ಆರು", + "ಇಪ್ಪತ್ತ್ ಐದು", + "ಇಪ್ಪತ್ತ್ ನಾಲ್ಕು", + "ಇಪ್ಪತ್ತ್ ಮೂರು", + "ಇಪ್ಪತ್ತ್ ಎರಡು", + "ಇಪ್ಪತ್ತ್ ಒಂದು", + "ಇಪ್ಪತ್ತು", + "ಹತ್ತೊಂಬತ್ತು", + "ಹದಿನೆಂಟು", + "ಹದಿನೇಳು", + "ಹದಿನಾರು", + "ಹದಿನೈದು", + "ಹದಿನಾಲ್ಕು", + "ಹದಿಮೂರು", + "ಹನ್ನೆರಡು", + "ಹನ್ನೊಂದು", + "ಹತ್ತು", + "ಒಂಬತ್ತು", + "ಎಂಟು", + "ಏಳು", + "ಆರು", + "ಐದು", + "ನಾಲ್ಕು", + "ಮೂರು", + "ಎರಡು", + "ಒಂದು", + "ಸೊನ್ನೆ", + ] + + self.mid_numwords = [(100, "ನೂರು")] + + self.high_numwords = [(7, "ಕೋಟಿ"), (5, "ಒಂದು ಲಕ್ಷ"), (3, "ಸಾವಿರ")] + + self.pointword = "ಬಿಂದು" + + self.modifiers = [ + "್", + "ಾ", + "ಿ", + "ೀ", + "ೀ", + "ು", + "ೂ", + "ೃ", + "ೆ", + "ೇ", + "ೈ", + "ೊ", + "ೋ", + "ೌ", + "ೕ", + ] + + def merge(self, lpair, rpair): + ltext, lnum = lpair + rtext, rnum = rpair + if lnum == 1 and rnum < 100: + return (rtext, rnum) + elif 100 > lnum > rnum: + return ("%s-%s" % (ltext, rtext), lnum + rnum) + elif lnum >= 100 > rnum: + if ltext[-1] in self.modifiers: + return ("%s %s" % (ltext[:-1], rtext), lnum + rnum) + else: + return ("%s %s" % (ltext + "ದ", rtext), lnum + rnum) + elif rnum > lnum: + return ("%s %s" % (ltext, rtext), lnum * rnum) + return ("%s %s" % (ltext, rtext), lnum + rnum) + + def to_ordinal_num(self, value): + self.verify_ordinal(value) + return "%s%s" % (value, self.to_ordinal(value)) + + def to_ordinal(self, value): + self.verify_ordinal(value) + outwords = self.to_cardinal(value) + if outwords[-1] in self.modifiers: + outwords = outwords[:-1] + ordinal_num = outwords + "ನೇ" + return ordinal_num diff --git a/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_KO.py b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_KO.py new file mode 100644 index 0000000000000000000000000000000000000000..65f4531e3ac5b4dbb818e2090f90e14a92b50343 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_KO.py @@ -0,0 +1,148 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2003, Taro Ogawa. All Rights Reserved. +# Copyright (c) 2013, Savoir-faire Linux inc. All Rights Reserved. + +# This library 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. +# This library 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 along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301 USA + +from __future__ import division, print_function, unicode_literals + +from .base import Num2Word_Base +from .currency import parse_currency_parts + + +class Num2Word_KO(Num2Word_Base): + CURRENCY_FORMS = { + 'KRW': ('원', None), + 'USD': ('달러', '센트'), + 'JPY': ('엔', None) + } + + def set_high_numwords(self, high): + max = 4 * len(high) + for word, n in zip(high, range(max, 0, -4)): + self.cards[10 ** n] = word + + def setup(self): + super(Num2Word_KO, self).setup() + + self.negword = "마이너스 " + self.pointword = "점" + + self.high_numwords = [ + '무량대수', + '불가사의', + '나유타', + '아승기', + '항하사', + '극', + '재', + '정', + '간', + '구', + '양', + '자', + '해', + '경', + '조', + '억', + '만'] + self.mid_numwords = [(1000, "천"), (100, "백")] + self.low_numwords = ["십", "구", "팔", "칠", "육", "오", "사", "삼", "이", + "일", "영"] + self.ords = {"일": "한", + "이": "두", + "삼": "세", + "사": "네", + "오": "다섯", + "육": "여섯", + "칠": "일곱", + "팔": "여덟", + "구": "아홉", + "십": "열", + "이십": "스물", + "삼십": "서른", + "사십": "마흔", + "오십": "쉰", + "육십": "예순", + "칠십": "일흔", + "팔십": "여든", + "구십": "아흔"} + + def merge(self, lpair, rpair): + ltext, lnum = lpair + rtext, rnum = rpair + if lnum == 1 and rnum <= 10000: + return rpair + elif 10000 > lnum > rnum: + return ("%s%s" % (ltext, rtext), lnum + rnum) + elif lnum >= 10000 and lnum > rnum: + return ("%s %s" % (ltext, rtext), lnum + rnum) + else: + return ("%s%s" % (ltext, rtext), lnum * rnum) + + def to_ordinal(self, value): + self.verify_ordinal(value) + if value == 1: + return "첫 번째" + outwords = self.to_cardinal(value).split(" ") + lastwords = outwords[-1].split("백") + if "십" in lastwords[-1]: + ten_one = lastwords[-1].split("십") + ten_one[0] = self.ords[ten_one[0] + "십"] + try: + ten_one[1] = self.ords[ten_one[1]] + ten_one[0] = ten_one[0].replace("스무", "스물") + except KeyError: + pass + lastwords[-1] = ''.join(ten_one) + else: + lastwords[-1] = self.ords[lastwords[-1]] + outwords[-1] = "백 ".join(lastwords) + return " ".join(outwords) + " 번째" + + def to_ordinal_num(self, value): + self.verify_ordinal(value) + return "%s 번째" % (value) + + def to_year(self, val, suffix=None, longval=True): + if val < 0: + val = abs(val) + suffix = '기원전' if not suffix else suffix + valtext = self.to_cardinal(val) + return ("%s년" % valtext if not suffix + else "%s %s년" % (suffix, valtext)) + + def to_currency(self, val, currency="KRW", cents=False, separator="", + adjective=False): + left, right, is_negative = parse_currency_parts( + val, is_int_with_cents=cents) + + try: + cr1, cr2 = self.CURRENCY_FORMS[currency] + if (cents or right) and not cr2: + raise ValueError('Decimals not supported for "%s"' % currency) + except KeyError: + raise NotImplementedError( + 'Currency code "%s" not implemented for "%s"' % + (currency, self.__class__.__name__)) + + minus_str = self.negword if is_negative else "" + return '%s%s%s%s%s' % ( + minus_str, + ''.join(self.to_cardinal(left).split()), + cr1, + ' ' + self.to_cardinal(right) + if cr2 else '', + cr2 if cr2 else '', + ) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_KZ.py b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_KZ.py new file mode 100644 index 0000000000000000000000000000000000000000..67df20ed86a2c63de35652b47ccf0635f4f05c69 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_KZ.py @@ -0,0 +1,133 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2003, Taro Ogawa. All Rights Reserved. +# Copyright (c) 2013, Savoir-faire Linux inc. All Rights Reserved. + +# This library 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. +# This library 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 along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301 USA + +from __future__ import unicode_literals + +from .base import Num2Word_Base +from .utils import get_digits, splitbyx + +ZERO = 'нөл' + +ONES = { + 1: 'бір', + 2: 'екі', + 3: 'үш', + 4: 'төрт', + 5: 'бес', + 6: 'алты', + 7: 'жеті', + 8: 'сегіз', + 9: 'тоғыз', +} + +TEN = 'он' + +TWENTIES = { + 2: 'жиырма', + 3: 'отыз', + 4: 'қырық', + 5: 'елу', + 6: 'алпыс', + 7: 'жетпіс', + 8: 'сексен', + 9: 'тоқсан', +} + +HUNDRED = 'жүз' + +THOUSANDS = { + 1: 'мың', + 2: 'миллион', + 3: 'миллиард', + 4: 'триллион', + 5: 'квадриллион', + 6: 'квинтиллион', + 7: 'секстиллион', + 8: 'септиллион', + 9: 'октиллион', + 10: 'нониллион', +} + + +class Num2Word_KZ(Num2Word_Base): + CURRENCY_FORMS = { + 'USD': ('доллар', 'цент'), + 'KZT': ('теңге', 'тиын'), + } + + def setup(self): + self.negword = "минус" + self.pointword = "бүтін" + + def to_cardinal(self, number): + n = str(number).replace(',', '.') + if '.' in n: + left, right = n.split('.') + leading_zero_count = len(right) - len(right.lstrip('0')) + return u'%s %s %s' % ( + self._int2word(int(left)), + self.pointword, + (ZERO + ' ') * leading_zero_count + self._int2word(int(right)) + ) + else: + return self._int2word(int(n)) + + def pluralize(self, n, form): + return form + + def _cents_verbose(self, number, currency): + return self._int2word(number, currency == 'KZT') + + def _int2word(self, n, feminine=False): + if n < 0: + return ' '.join([self.negword, self._int2word(abs(n))]) + + if n == 0: + return ZERO + + words = [] + chunks = list(splitbyx(str(n), 3)) + i = len(chunks) + for x in chunks: + i -= 1 + + if x == 0: + continue + + n1, n2, n3 = get_digits(x) + + if n3 > 0: + if n3 > 1: + words.append(ONES[n3]) + words.append(HUNDRED) + + if n2 == 1: + words.append(TEN) + elif n2 > 1: + words.append(TWENTIES[n2]) + + if n1 > 0: + words.append(ONES[n1]) + + if i > 0: + words.append(THOUSANDS[i]) + + return ' '.join(words) + + def to_ordinal(self, number): + # TODO: Implement to_ordinal + raise NotImplementedError() diff --git a/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_LT.py b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_LT.py new file mode 100644 index 0000000000000000000000000000000000000000..8f723e889a13ef56988bbcd72a15c2edb7db0753 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_LT.py @@ -0,0 +1,182 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2003, Taro Ogawa. All Rights Reserved. +# Copyright (c) 2013, Savoir-faire Linux inc. All Rights Reserved. + +# This library 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. +# This library 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 along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301 USA + +from __future__ import unicode_literals + +from .base import Num2Word_Base +from .utils import get_digits, splitbyx + +ZERO = ('nulis',) + +ONES_FEMININE = { + 1: ('viena',), + 2: ('dvi',), + 3: ('trys',), + 4: ('keturios',), + 5: ('penkios',), + 6: ('šešios',), + 7: ('septynios',), + 8: ('aštuonios',), + 9: ('devynios',), +} + +ONES = { + 1: ('vienas',), + 2: ('du',), + 3: ('trys',), + 4: ('keturi',), + 5: ('penki',), + 6: ('šeši',), + 7: ('septyni',), + 8: ('aštuoni',), + 9: ('devyni',), +} + +TENS = { + 0: ('dešimt',), + 1: ('vienuolika',), + 2: ('dvylika',), + 3: ('trylika',), + 4: ('keturiolika',), + 5: ('penkiolika',), + 6: ('šešiolika',), + 7: ('septyniolika',), + 8: ('aštuoniolika',), + 9: ('devyniolika',), +} + +TWENTIES = { + 2: ('dvidešimt',), + 3: ('trisdešimt',), + 4: ('keturiasdešimt',), + 5: ('penkiasdešimt',), + 6: ('šešiasdešimt',), + 7: ('septyniasdešimt',), + 8: ('aštuoniasdešimt',), + 9: ('devyniasdešimt',), +} + +HUNDRED = ('šimtas', 'šimtai') + +THOUSANDS = { + 1: ('tūkstantis', 'tūkstančiai', 'tūkstančių'), + 2: ('milijonas', 'milijonai', 'milijonų'), + 3: ('milijardas', 'milijardai', 'milijardų'), + 4: ('trilijonas', 'trilijonai', 'trilijonų'), + 5: ('kvadrilijonas', 'kvadrilijonai', 'kvadrilijonų'), + 6: ('kvintilijonas', 'kvintilijonai', 'kvintilijonų'), + 7: ('sikstilijonas', 'sikstilijonai', 'sikstilijonų'), + 8: ('septilijonas', 'septilijonai', 'septilijonų'), + 9: ('oktilijonas', 'oktilijonai', 'oktilijonų'), + 10: ('naintilijonas', 'naintilijonai', 'naintilijonų'), +} + +GENERIC_CENTS = ('centas', 'centai', 'centų') + + +class Num2Word_LT(Num2Word_Base): + CURRENCY_FORMS = { + 'LTL': (('litas', 'litai', 'litų'), GENERIC_CENTS), + 'EUR': (('euras', 'eurai', 'eurų'), GENERIC_CENTS), + 'USD': (('doleris', 'doleriai', 'dolerių'), GENERIC_CENTS), + 'GBP': ( + ('svaras sterlingų', 'svarai sterlingų', 'svarų sterlingų'), + ('pensas', 'pensai', 'pensų') + ), + 'PLN': ( + ('zlotas', 'zlotai', 'zlotų'), + ('grašis', 'grašiai', 'grašių')), + 'RUB': ( + ('rublis', 'rubliai', 'rublių'), + ('kapeika', 'kapeikos', 'kapeikų') + ), + } + + def setup(self): + self.negword = "minus" + self.pointword = "kablelis" + + def pluralize(self, n, forms): + n1, n2, n3 = get_digits(n) + if n2 == 1 or n1 == 0 or n == 0: + return forms[2] + elif n1 == 1: + return forms[0] + else: + return forms[1] + + def to_cardinal(self, number): + n = str(number).replace(',', '.') + base_str, n = self.parse_minus(n) + if '.' in n: + left, right = n.split('.') + leading_zero_count = len(right) - len(right.lstrip('0')) + decimal_part = ((ZERO[0] + ' ') * leading_zero_count + + self._int2word(int(right))) + return '%s%s %s %s' % ( + base_str, + self._int2word(int(left)), + self.pointword, + decimal_part + ) + else: + return "%s%s" % (base_str, self._int2word(int(n))) + + def to_ordinal(self, number): + raise NotImplementedError() + + def _cents_verbose(self, number, currency): + return self._int2word(number, currency == 'RUB') + + def _int2word(self, n, feminine=False): + if n == 0: + return ZERO[0] + + words = [] + chunks = list(splitbyx(str(n), 3)) + i = len(chunks) + + for x in chunks: + i -= 1 + + if x == 0: + continue + + n1, n2, n3 = get_digits(x) + + if n3 > 0: + words.append(ONES[n3][0]) + if n3 > 1: + words.append(HUNDRED[1]) + else: + words.append(HUNDRED[0]) + + if n2 > 1: + words.append(TWENTIES[n2][0]) + + if n2 == 1: + words.append(TENS[n1][0]) + elif n1 > 0: + if (i == 1 or feminine and i == 0) and n < 1000: + words.append(ONES_FEMININE[n1][0]) + else: + words.append(ONES[n1][0]) + + if i > 0: + words.append(self.pluralize(x, THOUSANDS[i])) + + return ' '.join(words) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_LV.py b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_LV.py new file mode 100644 index 0000000000000000000000000000000000000000..6e71c60904834e2bb6f8a9df77547ba1106b3eca --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_LV.py @@ -0,0 +1,189 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2003, Taro Ogawa. All Rights Reserved. +# Copyright (c) 2013, Savoir-faire Linux inc. All Rights Reserved. + +# This library 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. +# This library 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 along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301 USA + +from __future__ import unicode_literals + +from .base import Num2Word_Base +from .utils import get_digits, splitbyx + +ZERO = ('nulle',) + +ONES = { + 1: ('viens',), + 2: ('divi',), + 3: ('trīs',), + 4: ('četri',), + 5: ('pieci',), + 6: ('seši',), + 7: ('septiņi',), + 8: ('astoņi',), + 9: ('deviņi',), +} + +TENS = { + 0: ('desmit',), + 1: ('vienpadsmit',), + 2: ('divpadsmit',), + 3: ('trīspadsmit',), + 4: ('četrpadsmit',), + 5: ('piecpadsmit',), + 6: ('sešpadsmit',), + 7: ('septiņpadsmit',), + 8: ('astoņpadsmit',), + 9: ('deviņpadsmit',), +} + +TWENTIES = { + 2: ('divdesmit',), + 3: ('trīsdesmit',), + 4: ('četrdesmit',), + 5: ('piecdesmit',), + 6: ('sešdesmit',), + 7: ('septiņdesmit',), + 8: ('astoņdesmit',), + 9: ('deviņdesmit',), +} + +HUNDRED = ('simts', 'simti', 'simtu') + +THOUSANDS = { + 1: ('tūkstotis', 'tūkstoši', 'tūkstošu'), + 2: ('miljons', 'miljoni', 'miljonu'), + 3: ('miljards', 'miljardi', 'miljardu'), + 4: ('triljons', 'triljoni', 'triljonu'), + 5: ('kvadriljons', 'kvadriljoni', 'kvadriljonu'), + 6: ('kvintiljons', 'kvintiljoni', 'kvintiljonu'), + 7: ('sikstiljons', 'sikstiljoni', 'sikstiljonu'), + 8: ('septiljons', 'septiljoni', 'septiljonu'), + 9: ('oktiljons', 'oktiljoni', 'oktiljonu'), + 10: ('nontiljons', 'nontiljoni', 'nontiljonu'), +} + +GENERIC_DOLLARS = ('dolārs', 'dolāri', 'dolāru') +GENERIC_CENTS = ('cents', 'centi', 'centu') + +GENERIC_KRONA = ('krona', 'kronas', 'kronu') +GENERIC_ERA = ('ēre', 'ēras', 'ēru') + + +class Num2Word_LV(Num2Word_Base): + """ + Sadly we have a legal form (used in legal and finance documents): + http://www.eiro.lv/files/upload/files/Eiro_rakstiba-1.pdf + https://likumi.lv/doc.php?id=254741 + http://eur-lex.europa.eu/legal-content/LV/TXT/HTML/?uri=CELEX:31998R0974&from=LV + + Source: http://publications.europa.eu/code/lv/lv-5000500.htm + """ + CURRENCY_FORMS = { + 'AUD': (GENERIC_DOLLARS, GENERIC_CENTS), + 'CAD': (GENERIC_DOLLARS, GENERIC_CENTS), + # repalced by EUR + 'EEK': (GENERIC_KRONA, GENERIC_CENTS), + 'EUR': (('eiro', 'eiro', 'eiro'), GENERIC_CENTS), + 'EUR_LEGAL': (('euro', 'euro', 'euro'), GENERIC_CENTS), + 'GBP': ( + ('sterliņu mārciņa', 'sterliņu mārciņas', 'sterliņu mārciņu'), + ('penss', 'pensi', 'pensu')), + # replaced by EUR + 'LTL': (('lits', 'liti', 'litu'), GENERIC_CENTS), + # replaced by EUR + 'LVL': (('lats', 'lati', 'latu'), + ('santīms', 'santīmi', 'santīmu')), + 'USD': (GENERIC_DOLLARS, GENERIC_CENTS), + 'RUB': (('rublis', 'rubļi', 'rubļu'), + ('kapeika', 'kapeikas', 'kapeiku')), + 'SEK': (GENERIC_KRONA, GENERIC_ERA), + 'NOK': (GENERIC_KRONA, GENERIC_ERA), + 'PLN': (('zlots', 'zloti', 'zlotu'), + ('grasis', 'graši', 'grašu')), + } + + CURRENCY_ADJECTIVES = { + 'AUD': 'Austrālijas', + 'CAD': 'Kanādas', + 'EEK': 'Igaunijas', + 'USD': 'ASV', + 'RUB': 'Kreivijas', + 'SEK': 'Zviedrijas', + 'NOK': 'Norvēģijas', + } + + def setup(self): + self.negword = "mīnus" + self.pointword = "komats" + + def to_cardinal(self, number): + n = str(number).replace(',', '.') + base_str, n = self.parse_minus(n) + if '.' in n: + left, right = n.split('.') + leading_zero_count = len(right) - len(right.lstrip('0')) + decimal_part = ((ZERO[0] + ' ') * leading_zero_count + + self._int2word(int(right))) + return '%s%s %s %s' % ( + base_str, + self._int2word(int(left)), + self.pointword, + decimal_part + ) + else: + return "%s%s" % (base_str, self._int2word(int(n))) + + def pluralize(self, n, forms): + form = 0 if (n % 10 == 1 and n % 100 != 11) else 1 if n != 0 else 2 + return forms[form] + + def to_ordinal(self, number): + raise NotImplementedError() + + def _int2word(self, n): + if n == 0: + return ZERO[0] + + words = [] + chunks = list(splitbyx(str(n), 3)) + i = len(chunks) + for x in chunks: + i -= 1 + + if x == 0: + continue + + n1, n2, n3 = get_digits(x) + + if n3 > 0: + if n3 == 1 and n2 == 0 and n1 > 0: + words.append(HUNDRED[2]) + elif n3 > 1: + words.append(ONES[n3][0]) + words.append(HUNDRED[1]) + else: + words.append(HUNDRED[0]) + + if n2 > 1: + words.append(TWENTIES[n2][0]) + + if n2 == 1: + words.append(TENS[n1][0]) + elif n1 > 0 and not (i > 0 and x == 1): + words.append(ONES[n1][0]) + + if i > 0: + words.append(self.pluralize(x, THOUSANDS[i])) + + return ' '.join(words) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_NL.py b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_NL.py new file mode 100644 index 0000000000000000000000000000000000000000..7251e2ac4cd7a951624df781f6ef53121791b191 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_NL.py @@ -0,0 +1,158 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2003, Taro Ogawa. All Rights Reserved. +# Copyright (c) 2013, Savoir-faire Linux inc. All Rights Reserved. + +# This library 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. +# This library 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 along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301 USA + +from __future__ import print_function, unicode_literals + +from .lang_EU import Num2Word_EU + + +class Num2Word_NL(Num2Word_EU): + CURRENCY_FORMS = { + 'EUR': (('euro', 'euro'), ('cent', 'cent')), + 'GBP': (('pond', 'pond'), ('penny', 'pence')), + 'USD': (('dollar', 'dollar'), ('cent', 'cent')), + 'CNY': (('yuan', 'yuan'), ('jiao', 'fen')), + } + + GIGA_SUFFIX = "iljard" + MEGA_SUFFIX = "iljoen" + + def setup(self): + super(Num2Word_NL, self).setup() + + self.negword = "min " + self.pointword = "komma" + # "Cannot treat float %s as ordinal." + self.errmsg_floatord = ( + "Het zwevende puntnummer %s kan niet omgezet worden " + + "naar een ordernummer." + ) + # "type(((type(%s)) ) not in [long, int, float]" + self.errmsg_nonnum = ( + "Alleen nummers (type (%s)) kunnen naar " + + "woorden omgezet worden." + ) + # "Cannot treat negative num %s as ordinal." + self.errmsg_negord = ( + "Het negatieve getal %s kan niet omgezet " + + "worden naar een ordernummer." + ) + # "abs(%s) must be less than %s." + self.errmsg_toobig = "Het getal %s moet minder zijn dan %s." + self.exclude_title = [] + + lows = ["non", "okt", "sept", "sext", "quint", "quadr", "tr", "b", "m"] + units = ["", "un", "duo", "tre", "quattuor", "quin", "sex", "sept", + "okto", "novem"] + tens = ["dez", "vigint", "trigint", "quadragint", "quinquagint", + "sexagint", "septuagint", "oktogint", "nonagint"] + + self.high_numwords = ( + ["zend"] + self.gen_high_numwords(units, tens, lows)) + + self.mid_numwords = [(1000, "duizend"), (100, "honderd"), + (90, "negentig"), (80, "tachtig"), + (70, "zeventig"), (60, "zestig"), + (50, "vijftig"), (40, "veertig"), + (30, "dertig")] + + self.low_numwords = ["twintig", "negentien", "achttien", "zeventien", + "zestien", "vijftien", "veertien", "dertien", + "twaalf", "elf", "tien", "negen", "acht", "zeven", + "zes", "vijf", "vier", "drie", "twee", "één", + "nul"] + + # Wiktionary says it is "nulde", not "nulte" or "nule" + # https://en.wiktionary.org/wiki/nulde + self.ords = {"nul": "nuld", + "één": "eerst", + "twee": "tweed", + "drie": "derd", + "vier": "vierd", + "vijf": "vijfd", + "zes": "zesd", + "zeven": "zevend", + "acht": "achtst", + "negen": "negend", + "tien": "tiend", + "elf": "elfd", + "twaalf": "twaalfd", + + "ig": "igst", + "erd": "erdst", + "end": "endst", + "joen": "joenst", + "rd": "rdst"} + + def merge(self, curr, next): + ctext, cnum, ntext, nnum = curr + next + + if cnum == 1: + if nnum < 10 ** 6: + return next + ctext = "een" + + if nnum > cnum: + if nnum >= 10 ** 6: + ctext += " " + val = cnum * nnum + else: + if nnum < 10 < cnum < 100: + if nnum == 1: + ntext = "een" + + if ntext.endswith("e"): + ntext += "ën" # "n" + else: + ntext += "en" + ntext, ctext = ctext, ntext # + "en" + elif cnum >= 10 ** 6: + ctext += " " + val = cnum + nnum + + word = ctext + ntext + return word, val + + def to_ordinal(self, value): + self.verify_ordinal(value) + outword = self.to_cardinal(value) + for key in self.ords: + if outword.endswith(key): + outword = outword[:len(outword) - len(key)] + self.ords[key] + break + return outword + "e" + + def to_ordinal_num(self, value): + self.verify_ordinal(value) + return str(value) + "e" + + def pluralize(self, n, forms): + """ + :param n: + :param forms: + :return: + + gettext form is nplurals=2; plural=(n != 1); + but this claims https://onzetaal.nl/taaladvies/euro-euros/ + not sure if it's applied only to euro + """ + return forms[0] + + def to_year(self, val, longval=True): + if not (val // 100) % 10: + return self.to_cardinal(val) + return self.to_splitnum(val, hightxt="honderd", longval=longval) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_NO.py b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_NO.py new file mode 100644 index 0000000000000000000000000000000000000000..b4d33380a40cca60eb11627b62e3c99eb711ab68 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_NO.py @@ -0,0 +1,122 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2003, Taro Ogawa. All Rights Reserved. +# Copyright (c) 2013, Savoir-faire Linux inc. All Rights Reserved. + +# This library 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. +# This library 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 along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301 USA + +from __future__ import division, print_function, unicode_literals + +from . import lang_EU + + +class Num2Word_NO(lang_EU.Num2Word_EU): + GIGA_SUFFIX = "illard" + MEGA_SUFFIX = "illion" + CURRENCY_FORMS = {'NOK': (('krone', 'kroner'), ('øre', 'øre'))} + + def set_high_numwords(self, high): + cap = 3 + 6 * len(high) + + for word, n in zip(high, range(cap, 3, -6)): + if self.GIGA_SUFFIX: + self.cards[10 ** n] = word + self.GIGA_SUFFIX + + if self.MEGA_SUFFIX: + self.cards[10 ** (n - 3)] = word + self.MEGA_SUFFIX + + def setup(self): + super(Num2Word_NO, self).setup() + + self.negword = "minus " + self.pointword = "komma" + self.exclude_title = ["og", "komma", "minus"] + + self.mid_numwords = [(1000, "tusen"), (100, "hundre"), + (90, "nitti"), (80, "\xe5tti"), (70, "sytti"), + (60, "seksti"), (50, "femti"), (40, "f\xf8rti"), + (30, "tretti")] + self.low_numwords = ["tjue", "nitten", "atten", "sytten", + "seksten", "femten", "fjorten", "tretten", + "tolv", "elleve", "ti", "ni", "\xe5tte", + "syv", "seks", "fem", "fire", "tre", "to", + "en", "null"] + self.ords_pl = {"to": "andre", + "tre": "tredje", + "fire": "fjerde", + "fem": "femte", + "seks": "sjette", + "syv": "syvende", + "\xe5tte": "\xe5ttende", + "ni": "niende", + "ti": "tiende", + "elleve": "ellevte", + "tolv": "tolvte", + "fjorten": "fjortende", + "femten": "femtende", + "seksten": "sekstende", + "sytten": "syttende", + "atten": "attende", + "nitten": "nittende", + "tjue": "tjuende", + "hundre": "hundrede", + "tusen": "tusende", + "million": "millionte"} + # this needs to be done separately to not block 13-19 to_ordinal + self.ords_sg = {"en": "f\xf8rste"} + + def merge(self, lpair, rpair): + ltext, lnum = lpair + rtext, rnum = rpair + if lnum == 1 and rnum < 100: + return (rtext, rnum) + elif 100 > lnum > rnum: + return ("%s%s" % (ltext, rtext), lnum + rnum) + elif lnum >= 100 > rnum: + return ("%s og %s" % (ltext, rtext), lnum + rnum) + elif rnum > lnum: + return ("%s %s" % (ltext, rtext), lnum * rnum) + return ("%s %s" % (ltext, rtext), lnum + rnum) + + def to_ordinal(self, value): + self.verify_ordinal(value) + outword = self.to_cardinal(value) + for key in self.ords_pl: + if outword.endswith(key): + outword = outword[:len(outword) - len(key)] + self.ords_pl[key] + break + for key in self.ords_sg: + if outword.endswith(key): + outword = outword[:len(outword) - len(key)] + self.ords_sg[key] + break + return outword + + def to_ordinal_num(self, value): + self.verify_ordinal(value) + return str(value) + "." + + def to_year(self, val, longval=True): + if not (val // 100) % 10: + return self.to_cardinal(val) + return self.to_splitnum(val, hightxt="hundre", jointxt="og", + longval=longval) + + def to_currency(self, val, currency='NOK', cents=True, separator=' og', + adjective=False): + result = super(Num2Word_NO, self).to_currency( + val, currency=currency, cents=cents, separator=separator, + adjective=adjective) + + # do not print "og null øre" + result = result.replace(' og null øre', '') + return result diff --git a/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_PL.py b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_PL.py new file mode 100644 index 0000000000000000000000000000000000000000..376b0a1055a6ca108c8e819fa62c01095eadf2b3 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_PL.py @@ -0,0 +1,272 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2003, Taro Ogawa. All Rights Reserved. +# Copyright (c) 2013, Savoir-faire Linux inc. All Rights Reserved. + +# This library 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. +# This library 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 along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301 USA + +from __future__ import unicode_literals + +import itertools + +from .base import Num2Word_Base +from .utils import get_digits, splitbyx + +ZERO = ('zero',) + +ONES = { + 1: ('jeden',), + 2: ('dwa',), + 3: ('trzy',), + 4: ('cztery',), + 5: ('pięć',), + 6: ('sześć',), + 7: ('siedem',), + 8: ('osiem',), + 9: ('dziewięć',), +} + +ONES_ORDINALS = { + 1: ('pierwszy', "pierwszo"), + 2: ('drugi', "dwu"), + 3: ('trzeci', "trzy"), + 4: ('czwarty', "cztero"), + 5: ('piąty', "pięcio"), + 6: ('szósty', "sześcio"), + 7: ('siódmy', "siedmio"), + 8: ('ósmy', "ośmio"), + 9: ('dziewiąty', "dziewięcio"), + 10: ('dziesiąty', "dziesięcio"), + 11: ('jedenasty', "jedenasto"), + 12: ('dwunasty', "dwunasto"), + 13: ('trzynasty', "trzynasto"), + 14: ('czternasty', "czternasto"), + 15: ('piętnasty', "piętnasto"), + 16: ('szesnasty', "szesnasto"), + 17: ('siedemnasty', "siedemnasto"), + 18: ('osiemnasty', "osiemnasto"), + 19: ('dziewiętnasty', "dziewiętnasto"), +} + +TENS = { + 0: ('dziesięć',), + 1: ('jedenaście',), + 2: ('dwanaście',), + 3: ('trzynaście',), + 4: ('czternaście',), + 5: ('piętnaście',), + 6: ('szesnaście',), + 7: ('siedemnaście',), + 8: ('osiemnaście',), + 9: ('dziewiętnaście',), +} + + +TWENTIES = { + 2: ('dwadzieścia',), + 3: ('trzydzieści',), + 4: ('czterdzieści',), + 5: ('pięćdziesiąt',), + 6: ('sześćdziesiąt',), + 7: ('siedemdziesiąt',), + 8: ('osiemdziesiąt',), + 9: ('dziewięćdziesiąt',), +} + +TWENTIES_ORDINALS = { + 2: ('dwudziesty', "dwudziesto"), + 3: ('trzydziesty', "trzydiesto"), + 4: ('czterdziesty', "czterdziesto"), + 5: ('pięćdziesiąty', "pięćdziesięcio"), + 6: ('sześćdziesiąty', "sześćdziesięcio"), + 7: ('siedemdziesiąty', "siedemdziesięcio"), + 8: ('osiemdziesiąty', "osiemdziesięcio"), + 9: ('dziewięćdziesiąty', "dziewięćdziesięcio"), +} + +HUNDREDS = { + 1: ('sto',), + 2: ('dwieście',), + 3: ('trzysta',), + 4: ('czterysta',), + 5: ('pięćset',), + 6: ('sześćset',), + 7: ('siedemset',), + 8: ('osiemset',), + 9: ('dziewięćset',), +} + +HUNDREDS_ORDINALS = { + 1: ('setny', "stu"), + 2: ('dwusetny', "dwustu"), + 3: ('trzysetny', "trzystu"), + 4: ('czterysetny', "czterystu"), + 5: ('pięćsetny', "pięcset"), + 6: ('sześćsetny', "sześćset"), + 7: ('siedemsetny', "siedemset"), + 8: ('osiemsetny', "ośiemset"), + 9: ('dziewięćsetny', "dziewięćset"), +} + +THOUSANDS = { + 1: ('tysiąc', 'tysiące', 'tysięcy'), # 10^3 +} + +prefixes_ordinal = { + 1: "tysięczny", + 2: "milionowy", + 3: "milairdowy" +} + +prefixes = ( # 10^(6*x) + "mi", # 10^6 + "bi", # 10^12 + "try", # 10^18 + "kwadry", # 10^24 + "kwinty", # 10^30 + "seksty", # 10^36 + "septy", # 10^42 + "okty", # 10^48 + "nony", # 10^54 + "decy" # 10^60 +) +suffixes = ("lion", "liard") # 10^x or 10^(x+3) + +for idx, (p, s) in enumerate(itertools.product(prefixes, suffixes)): + name = p + s + THOUSANDS[idx+2] = (name, name + 'y', name + 'ów') + + +class Num2Word_PL(Num2Word_Base): + CURRENCY_FORMS = { + 'PLN': ( + ('złoty', 'złote', 'złotych'), ('grosz', 'grosze', 'groszy') + ), + 'EUR': ( + ('euro', 'euro', 'euro'), ('cent', 'centy', 'centów') + ), + 'USD': ( + ( + 'dolar amerykański', + 'dolary amerykańskie', + 'dolarów amerykańskich' + ), + ( + 'cent', + 'centy', + 'centów' + ) + ), + } + + def setup(self): + self.negword = "minus" + self.pointword = "przecinek" + + def to_cardinal(self, number): + n = str(number).replace(',', '.') + if '.' in n: + left, right = n.split('.') + leading_zero_count = len(right) - len(right.lstrip('0')) + decimal_part = ((ZERO[0] + ' ') * leading_zero_count + + self._int2word(int(right))) + return u'%s %s %s' % ( + self._int2word(int(left)), + self.pointword, + decimal_part + ) + else: + return self._int2word(int(n)) + + def pluralize(self, n, forms): + if n == 1: + form = 0 + elif 5 > n % 10 > 1 and (n % 100 < 10 or n % 100 > 20): + form = 1 + else: + form = 2 + return forms[form] + + def last_fragment_to_ordinal(self, last, words, level): + n1, n2, n3 = get_digits(last) + last_two = n2*10+n1 + if last_two == 0: + words.append(HUNDREDS_ORDINALS[n3][level]) + elif level == 1 and last == 1: + return + elif last_two < 20: + if n3 > 0: + words.append(HUNDREDS[n3][level]) + words.append(ONES_ORDINALS[last_two][level]) + elif last_two % 10 == 0: + if n3 > 0: + words.append(HUNDREDS[n3][level]) + words.append(TWENTIES_ORDINALS[n2][level]) + else: + if n3 > 0: + words.append(HUNDREDS[n3][0]) + words.append(TWENTIES_ORDINALS[n2][0]) + words.append(ONES_ORDINALS[n1][0]) + + def to_ordinal(self, number): + if number % 1 != 0: + raise NotImplementedError() + words = [] + fragments = list(splitbyx(str(number), 3)) + level = 0 + last = fragments[-1] + while last == 0: + level = level+1 + fragments.pop() + last = fragments[-1] + if len(fragments) > 1: + pre_part = self._int2word(number-(last*1000**level)) + words.append(pre_part) + self.last_fragment_to_ordinal(last, words, 0 if level == 0 else 1) + output = " ".join(words) + if last == 1 and level > 0 and output != "": + output = output + " " + if level > 0: + output = output + prefixes_ordinal[level] + return output + + def _int2word(self, n): + if n == 0: + return ZERO[0] + + words = [] + chunks = list(splitbyx(str(n), 3)) + i = len(chunks) + for x in chunks: + i -= 1 + + if x == 0: + continue + + n1, n2, n3 = get_digits(x) + + if n3 > 0: + words.append(HUNDREDS[n3][0]) + + if n2 > 1: + words.append(TWENTIES[n2][0]) + + if n2 == 1: + words.append(TENS[n1][0]) + elif n1 > 0 and not (i > 0 and x == 1): + words.append(ONES[n1][0]) + + if i > 0: + words.append(self.pluralize(x, THOUSANDS[i])) + + return ' '.join(words) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_PT.py b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_PT.py new file mode 100644 index 0000000000000000000000000000000000000000..ddfa771313f1501a1183931aca233a614629bec3 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_PT.py @@ -0,0 +1,241 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2003, Taro Ogawa. All Rights Reserved. +# Copyright (c) 2013, Savoir-faire Linux inc. All Rights Reserved. + +# This library 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. +# This library 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 along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301 USA + +from __future__ import division, unicode_literals + +import re + +from .lang_EU import Num2Word_EU + +DOLLAR = ('dólar', 'dólares') +CENTS = ('cêntimo', 'cêntimos') + + +class Num2Word_PT(Num2Word_EU): + + CURRENCY_FORMS = { + 'AUD': (DOLLAR, CENTS), + 'CAD': (DOLLAR, CENTS), + 'EUR': (('euro', 'euros'), CENTS), + 'GBP': (('libra', 'libras'), ('péni', 'pence')), + 'USD': (DOLLAR, CENTS), + } + + GIGA_SUFFIX = None + MEGA_SUFFIX = "ilião" + + def setup(self): + super(Num2Word_PT, self).setup() + lows = ["quatr", "tr", "b", "m"] + self.high_numwords = self.gen_high_numwords([], [], lows) + self.negword = "menos " + self.pointword = "vírgula" + self.exclude_title = ["e", "vírgula", "menos"] + + self.mid_numwords = [ + (1000, "mil"), (100, "cem"), (90, "noventa"), + (80, "oitenta"), (70, "setenta"), (60, "sessenta"), + (50, "cinquenta"), (40, "quarenta"), (30, "trinta") + ] + self.low_numwords = [ + "vinte", "dezanove", "dezoito", "dezassete", "dezasseis", + "quinze", "catorze", "treze", "doze", "onze", "dez", + "nove", "oito", "sete", "seis", "cinco", "quatro", "três", "dois", + "um", "zero" + ] + self.ords = [ + { + 0: "", + 1: "primeiro", + 2: "segundo", + 3: "terceiro", + 4: "quarto", + 5: "quinto", + 6: "sexto", + 7: "sétimo", + 8: "oitavo", + 9: "nono", + }, + { + 0: "", + 1: "décimo", + 2: "vigésimo", + 3: "trigésimo", + 4: "quadragésimo", + 5: "quinquagésimo", + 6: "sexagésimo", + 7: "septuagésimo", + 8: "octogésimo", + 9: "nonagésimo", + }, + { + 0: "", + 1: "centésimo", + 2: "ducentésimo", + 3: "tricentésimo", + 4: "quadrigentésimo", + 5: "quingentésimo", + 6: "seiscentésimo", + 7: "septigentésimo", + 8: "octigentésimo", + 9: "nongentésimo", + }, + ] + self.thousand_separators = { + 3: "milésimo", + 6: "milionésimo", + 9: "milésimo milionésimo", + 12: "bilionésimo", + 15: "milésimo bilionésimo" + } + self.hundreds = { + 1: "cento", + 2: "duzentos", + 3: "trezentos", + 4: "quatrocentos", + 5: "quinhentos", + 6: "seiscentos", + 7: "setecentos", + 8: "oitocentos", + 9: "novecentos", + } + + def merge(self, curr, next): + ctext, cnum, ntext, nnum = curr + next + + if cnum == 1: + if nnum < 1000000: + return next + ctext = "um" + elif cnum == 100 and not nnum % 1000 == 0: + ctext = "cento" + + if nnum < cnum: + if cnum < 100: + return ("%s e %s" % (ctext, ntext), cnum + nnum) + return ("%s e %s" % (ctext, ntext), cnum + nnum) + + elif (not nnum % 1000000000) and cnum > 1: + ntext = ntext[:-4] + "liões" + elif (not nnum % 1000000) and cnum > 1: + ntext = ntext[:-4] + "lhões" + # correct "milião" to "milhão" + if ntext == 'milião': + ntext = 'milhão' + if nnum == 100: + ctext = self.hundreds[cnum] + ntext = "" + + else: + ntext = " " + ntext + + return (ctext + ntext, cnum * nnum) + + def to_cardinal(self, value): + result = super(Num2Word_PT, self).to_cardinal(value) + + # Transforms "mil e cento e catorze" into "mil cento e catorze" + # Transforms "cem milhões e duzentos mil e duzentos e dez" em "cem + # milhões duzentos mil duzentos e dez" but "cem milhões e duzentos + # mil e duzentos" in "cem milhões duzentos mil e duzentos" and not in + # "cem milhões duzentos mil duzentos" + for ext in ( + 'mil', 'milhão', 'milhões', 'mil milhões', + 'bilião', 'biliões', 'mil biliões'): + if re.match('.*{} e \\w*entos? (?=.*e)'.format(ext), result): + result = result.replace( + '{} e'.format(ext), '{}'.format(ext) + ) + + return result + + # for the ordinal conversion the code is similar to pt_BR code, + # although there are other rules that are probably more correct in + # Portugal. Concerning numbers from 2000th on, saying "dois + # milésimos" instead of "segundo milésimo" (the first number + # would be used in the cardinal form instead of the ordinal) is better. + # This was not implemented. + # source: + # https://ciberduvidas.iscte-iul.pt/consultorio/perguntas/a-forma-por-extenso-de-2000-e-de-outros-ordinais/16428 + def to_ordinal(self, value): + # Before changing this function remember this is used by pt-BR + # so act accordingly + self.verify_ordinal(value) + + result = [] + value = str(value) + thousand_separator = '' + + for idx, char in enumerate(value[::-1]): + if idx and idx % 3 == 0: + thousand_separator = self.thousand_separators[idx] + + if char != '0' and thousand_separator: + # avoiding "segundo milionésimo milésimo" for 6000000, + # for instance + result.append(thousand_separator) + thousand_separator = '' + + result.append(self.ords[idx % 3][int(char)]) + + result = ' '.join(result[::-1]) + result = result.strip() + result = re.sub('\\s+', ' ', result) + + if result.startswith('primeiro') and value != '1': + # avoiding "primeiro milésimo", "primeiro milionésimo" and so on + result = result[9:] + + return result + + def to_ordinal_num(self, value): + # Before changing this function remember this is used by pt-BR + # so act accordingly + self.verify_ordinal(value) + return "%sº" % (value) + + def to_year(self, val, longval=True): + # Before changing this function remember this is used by pt-BR + # so act accordingly + if val < 0: + return self.to_cardinal(abs(val)) + ' antes de Cristo' + return self.to_cardinal(val) + + def to_currency(self, val, currency='EUR', cents=True, separator=' e', + adjective=False): + # change negword because base.to_currency() does not need space after + backup_negword = self.negword + self.negword = self.negword[:-1] + result = super(Num2Word_PT, self).to_currency( + val, currency=currency, cents=cents, separator=separator, + adjective=adjective) + # undo the change on negword + self.negword = backup_negword + + # transforms "milhões euros" em "milhões de euros" + cr1, _ = self.CURRENCY_FORMS[currency] + + for ext in ( + 'milhão', 'milhões', 'bilião', + 'biliões', 'trilião', 'triliões'): + if re.match('.*{} (?={})'.format(ext, cr1[1]), result): + result = result.replace( + '{}'.format(ext), '{} de'.format(ext), 1 + ) + # do not print "e zero cêntimos" + result = result.replace(' e zero cêntimos', '') + return result diff --git a/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_PT_BR.py b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_PT_BR.py new file mode 100644 index 0000000000000000000000000000000000000000..2aea06cb4ed00163907682ce6575adbaf69e4db2 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_PT_BR.py @@ -0,0 +1,115 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2003, Taro Ogawa. All Rights Reserved. +# Copyright (c) 2013, Savoir-faire Linux inc. All Rights Reserved. + +# This library 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. +# This library 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 along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301 USA +from __future__ import division, unicode_literals + +import re + +from . import lang_PT + + +class Num2Word_PT_BR(lang_PT.Num2Word_PT): + def set_high_numwords(self, high): + max = 3 + 3*len(high) + for word, n in zip(high, range(max, 3, -3)): + self.cards[10**n] = word + "ilhão" + + def setup(self): + super(Num2Word_PT_BR, self).setup() + + self.low_numwords[1] = 'dezenove' + self.low_numwords[3] = 'dezessete' + self.low_numwords[4] = 'dezesseis' + + self.thousand_separators = { + 3: "milésimo", + 6: "milionésimo", + 9: "bilionésimo", + 12: "trilionésimo", + 15: "quadrilionésimo" + } + + def merge(self, curr, next): + ctext, cnum, ntext, nnum = curr + next + + if cnum == 1: + if nnum < 1000000: + return next + ctext = "um" + elif cnum == 100 and nnum % 1000 != 0: + ctext = "cento" + + if nnum < cnum: + if cnum < 100: + return ("%s e %s" % (ctext, ntext), cnum + nnum) + return ("%s e %s" % (ctext, ntext), cnum + nnum) + + elif (not nnum % 1000000) and cnum > 1: + ntext = ntext[:-4] + "lhões" + + if nnum == 100: + ctext = self.hundreds[cnum] + ntext = "" + + else: + ntext = " " + ntext + + return (ctext + ntext, cnum * nnum) + + def to_cardinal(self, value): + result = lang_PT.Num2Word_EU.to_cardinal(self, value) + + # Transforms "mil E cento e catorze reais" into "mil, cento e catorze + # reais" + for ext in ( + 'mil', 'milhão', 'milhões', 'bilhão', 'bilhões', + 'trilhão', 'trilhões', 'quatrilhão', 'quatrilhões'): + if re.match('.*{} e \\w*entos? (?=.*e)'.format(ext), result): + result = result.replace( + '{} e'.format(ext), '{},'.format(ext), 1 + ) + + return result + + def to_currency(self, val, longval=True): + integer_part, decimal_part = ('%.2f' % val).split('.') + + result = self.to_cardinal(int(integer_part)) + + appended_currency = False + for ext in ( + 'milhão', 'milhões', 'bilhão', 'bilhões', + 'trilhão', 'trilhões', 'quatrilhão', 'quatrilhões'): + if result.endswith(ext): + result += ' de reais' + appended_currency = True + + if result in ['um', 'menos um']: + result += ' real' + appended_currency = True + if not appended_currency: + result += ' reais' + + if int(decimal_part): + cents = self.to_cardinal(int(decimal_part)) + result += ' e ' + cents + + if cents == 'um': + result += ' centavo' + else: + result += ' centavos' + + return result diff --git a/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_RO.py b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_RO.py new file mode 100644 index 0000000000000000000000000000000000000000..feb96105a4185c90bfc3ec975e78f232a0b52070 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_RO.py @@ -0,0 +1,174 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2003, Taro Ogawa. All Rights Reserved. +# Copyright (c) 2013, Savoir-faire Linux inc. All Rights Reserved. + +# This library 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. +# This library 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 along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301 USA + +from __future__ import division, print_function, unicode_literals + +from . import lang_EU + + +class Num2Word_RO(lang_EU.Num2Word_EU): + GIGA_SUFFIX = "iliard/e" + MEGA_SUFFIX = "ilion" + # inflection for mi/billion follows different rule + MEGA_SUFFIX_I = "ilioane" + GIGA_SUFFIX_I = "iliarde" + + def setup(self): + super(Num2Word_RO, self).setup() + + self.negword = "minus " + self.pointword = "virgulă" + self.exclude_title = ["și", "virgulă", "minus"] + self.errmsg_toobig = ( + "Numărul e prea mare pentru a \ +fi convertit în cuvinte (abs(%s) > %s)." + ) + self.mid_numwords = [(1000, "mie/i"), (100, "sută/e"), + (90, "nouăzeci"), (80, "optzeci"), + (70, "șaptezeci"), (60, "șaizeci"), + (50, "cincizeci"), (40, "patruzeci"), + (30, "treizeci")] + self.low_numwords = ["douăzeci", "nouăsprezece", "optsprezece", + "șaptesprezece", "șaisprezece", "cincisprezece", + "paisprezece", "treisprezece", "doisprezece", + "unsprezece", "zece", "nouă", "opt", "șapte", + "șase", "cinci", "patru", "trei", "doi", + "unu", "zero"] + self.gen_numwords = ["", "o", "două", "trei", "patru", "cinci", + "șase", "șapte", "opt", "nouă"] + self.gen_numwords_n = ["", "un", "două", "trei", "patru", "cinci", + "șase", "șapte", "opt", "nouă"] + self.numwords_inflections = { + 100: self.gen_numwords, + 1000: self.gen_numwords, + 1000000: self.gen_numwords_n, + 1000000000: self.gen_numwords_n + } + self.ords = {"unu": "primul", + "doi": "al doilea", + "three": "al treilea", + "cinci": "al cincilea", + "opt": "al optulea", + "nouă": "al nouălea", + "doisprezece": "al doisprezecelea"} + + def merge(self, lpair, rpair): + ltext, lnum = lpair + rtext, rnum = rpair + rtext_i = self.inflect(rnum, rtext, lnum) + if 1 <= lnum < 10: + if rnum not in self.numwords_inflections: + return (rtext, rnum) + else: + rtext_i = self.inflect(lnum * rnum, rtext, lnum) + lresult = (self.numwords_inflections[rnum][lnum], rtext_i) + return ("%s %s" % lresult, rnum) + elif 10 < lnum < 100: + if lnum % 10 == 0: + if rnum in self.numwords_inflections: + rtext_i = self.inflect(lnum * rnum, rtext, lnum) + return ("%s %s" % (ltext, rtext_i), lnum * rnum) + else: + return ("%s și %s" % (ltext, rtext), lnum + rnum) + else: + rtext_i = self.inflect(lnum * rnum, rtext, lnum) + ltext_i = ltext if lnum % 10 != 2 \ + else ltext.replace("doi", "două") + return ("%s %s" % (ltext_i, rtext_i), lnum * rnum) + else: + if rnum in self.numwords_inflections: + rtext_i = self.inflect(lnum * rnum, rtext, lnum) + return ("%s %s" % (ltext, rtext_i), lnum * rnum) + + def to_ordinal(self, value): + self.verify_ordinal(value) + if value == 1: + return "primul" + else: + value = self.to_cardinal(value) + return "al %slea" % (value) + + def to_ordinal_num(self, value): + self.verify_ordinal(value) + if value == 1: + return "1-ul" + return "al %s-lea" % (value) + + def pluralize(self, n, forms): + if n == 1: + form = 0 + elif n == 0 or (n % 100 > 0 and n % 100 < 20): + form = 1 + else: + form = 2 + return forms[form] + + def inflect(self, value, text, side_effect=-1): + text = text.split("/") + result = text[0] + if len(text) > 1: + forms = [ + text[0], + text[0][:-1] + text[1], + "de " + text[0][:-1] + text[1] + ] + result = self.pluralize(side_effect, forms) + # mega inflections are different + if side_effect > 1 and result.endswith(self.MEGA_SUFFIX): + result = result.replace(self.MEGA_SUFFIX, self.MEGA_SUFFIX_I) + elif side_effect > 1 and result.endswith("iliare"): + result = result.replace("iliare", self.GIGA_SUFFIX_I) + return result + + def to_currency(self, val, currency="RON", cents=False, separator=" și", + adjective=False): + # romanian currency has a particularity for numeral: one + self.gen_numwords[1] = "una" + result = super(Num2Word_RO, self).to_currency( + int(round(val*100)), + currency, + True, + separator, + adjective + ) + self.gen_numwords[1] = "o" # revert numeral + return result.replace( + "unu leu", "un leu" + ).replace( + "unu ban", "un ban" + ).replace( + # if the romanian low text is 0, it is not usually printed + separator + " zero bani", "" + ) + + def to_year(self, val, suffix=None, longval=True): + result = super(Num2Word_RO, self).to_year( + val, + longval=longval + ) + # for years we want the era negation e.g. B.C., in our case + # it's î.Hr. or î.e.n + if result.startswith(self.negword): + result = result.replace(self.negword, "") + suffix = "î.Hr." if not suffix else suffix + if suffix: + result = "".join([ + result, + " ", + suffix + ]) + return result diff --git a/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_RU.py b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_RU.py new file mode 100644 index 0000000000000000000000000000000000000000..2ff1c0a011ac8d4920a8b27f80b672ee3c22e598 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_RU.py @@ -0,0 +1,501 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2003, Taro Ogawa. All Rights Reserved. +# Copyright (c) 2013, Savoir-faire Linux inc. All Rights Reserved. + +# This library 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. +# This library 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 along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301 USA + +from __future__ import unicode_literals + +from .base import Num2Word_Base +from .utils import get_digits, splitbyx + +GENDER_PLURAL_INDEXES = { + 'm': 0, 'masculine': 0, 'м': 0, 'мужской': 0, + 'f': 1, 'feminine': 1, 'ж': 0, 'женский': 0, + 'n': 2, 'neuter': 2, 'с': 0, 'средний': 0, + 'p': 3, 'plural': 3 +} +CASE_INDEXES = { + 'n': 0, 'nominative': 0, 'и': 0, 'именительный': 0, + 'g': 1, 'genitive': 1, 'р': 1, 'родительный': 1, + 'd': 2, 'dative': 2, 'д': 2, 'дательный': 2, + 'a': 3, 'accusative': 3, 'в': 3, 'винительный': 3, + 'i': 4, 'instrumental': 4, 'т': 4, 'творительный': 4, + 'p': 5, 'prepositional': 5, 'п': 5, 'предложный': 5 +} +# Default values +D_CASE = 'n' +D_PLURAL = False +D_GENDER = 'm' +D_ANIMATE = True + + +def get_num_element(cases_dict, num, **kwargs): + return case_classifier_element(cases_dict[num], **kwargs) + + +def case_classifier_element(classifier, case=D_CASE, plural=D_PLURAL, + gender=D_GENDER, animate=D_ANIMATE): + case = classifier[CASE_INDEXES[case]] + if isinstance(case, str): + return case + + if plural: + gender = case[GENDER_PLURAL_INDEXES['plural']] + else: + gender = case[GENDER_PLURAL_INDEXES[gender]] + if isinstance(gender, str): + return gender + + if animate: + return gender[0] + return gender[1] + + +# format: +# {n : [case_1 .. case_5]} +# case: text or [gender_1 .. gender_3 plural_4] +# gender: text or [animate, inanimate] +ONES = { + 0: ['ноль', 'ноля', 'нолю', 'ноль', 'нолём', 'ноле'], + 1: [['один', 'одна', 'одно', 'одни'], + ['одного', 'одной', 'одного', 'одних'], + ['одному', 'одной', 'одному', 'одним'], + [['одного', 'один'], 'одну', 'одно', ['одних', 'одни']], + ['одним', 'одной', 'одним', 'одними'], + ['одном', 'одной', 'одном', 'одних']], + 2: [['два', 'две', 'два', 'двое'], + ['двух'] * 3 + ['двоих'], + ['двум'] * 3 + ['двоим'], + [['двух', 'два'], ['двух', 'две'], 'два', 'двоих'], + ['двумя'] * 3 + ['двоими'], + ['двух'] * 3 + ['двоих']], + 3: [['три'] * 3 + ['трое'], + ['трёх'] * 3 + ['троих'], + ['трём'] * 3 + ['троим'], + [['трёх', 'три'], ['трёх', 'три'], 'три', 'троих'], + ['тремя'] * 3 + ['троими'], + ['трёх'] * 3 + ['троих']], + 4: [['четыре'] * 3 + ['четверо'], + ['четырёх'] * 3 + ['четверых'], + ['четырём'] * 3 + ['четверым'], + [['четырёх', 'четыре'], ['четырёх', 'четыре'], 'четыре', 'четверых'], + ['четырьмя'] * 3 + ['четверыми'], + ['четырёх'] * 3 + ['четверых']], + 5: ['пять', 'пяти', 'пяти', 'пять', 'пятью', 'пяти'], + 6: ['шесть', 'шести', 'шести', 'шесть', 'шестью', 'шести'], + 7: ['семь', 'семи', 'семи', 'семь', 'семью', 'семи'], + 8: ['восемь', 'восьми', 'восьми', 'восемь', 'восемью', 'восьми'], + 9: ['девять', 'девяти', 'девяти', 'девять', 'девятью', 'девяти'] +} + +ONES_ORD_PREFIXES = {0: 'нулев', 1: 'перв', 2: 'втор', 4: 'четвёрт', 5: 'пят', + 6: 'шест', 7: 'седьм', 8: 'восьм', 9: 'девят'} +ONES_ORD_POSTFIXES_GROUPS = {0: 0, 1: 1, 2: 0, 4: 1, 5: 1, 6: 0, 7: 0, 8: 0, + 9: 1} +CASE_POSTFIXES = [[{0: 'ой', 1: 'ый'}, 'ая', 'ое', 'ые'], + ['ого', 'ой', 'ого', 'ых'], + ['ому', 'ой', 'ому', 'ым'], + [['ого', {0: 'ой', 1: 'ый'}], 'ую', 'ое', ['ых', 'ые']], + ['ым', 'ой', 'ым', 'ыми'], + ['ом', 'ой', 'ом', 'ых']] + + +def get_cases(prefix, post_group): + return [[ + prefix + postfix if isinstance(postfix, str) else + [prefix + animate if isinstance(animate, str) else + prefix + animate[post_group] + for animate in postfix] if isinstance(postfix, list) else + prefix + postfix[post_group] + for postfix in case] + for case in CASE_POSTFIXES] + + +def get_ord_classifier(prefixes, post_groups): + if isinstance(post_groups, int): + post_groups = {n: post_groups for n, i in prefixes.items()} + return { + num: get_cases(prefix, post_groups[num]) + for num, prefix in prefixes.items() + } + + +ONES_ORD = { + 3: [['третий', 'третья', 'третье', 'третьи'], + ['третьего', 'третьей', 'третьего', 'третьих'], + ['третьему', 'третьей', 'третьему', 'третьим'], + [['третьего', 'третий'], 'третью', 'третье', ['третьих', 'третьи']], + ['третьим', 'третьей', 'третьим', 'третьими'], + ['третьем', 'третьей', 'третьем', 'третьих']], +} +ONES_ORD.update( + get_ord_classifier(ONES_ORD_PREFIXES, ONES_ORD_POSTFIXES_GROUPS) +) + +TENS_PREFIXES = {1: 'один', 2: 'две', 3: 'три', 4: 'четыр', 5: 'пят', + 6: 'шест', 7: 'сем', 8: 'восем', 9: 'девят'} +TENS_POSTFIXES = ['надцать', 'надцати', 'надцати', 'надцать', 'надцатью', + 'надцати'] +TENS = {0: ['десять', 'десяти', 'десяти', 'десять', 'десятью', 'десяти']} +TENS.update({ + num: [prefix + postfix for postfix in TENS_POSTFIXES] + for num, prefix in TENS_PREFIXES.items() +}) + +TENS_ORD_PREFIXES = {0: "десят"} +TENS_ORD_PREFIXES.update({ + num: prefix + 'надцат' for num, prefix in TENS_PREFIXES.items() +}) +TENS_ORD = get_ord_classifier(TENS_ORD_PREFIXES, 1) + +TWENTIES = { + 2: ['двадцать', 'двадцати', 'двадцати', 'двадцать', 'двадцатью', + 'двадцати'], + 3: ['тридцать', 'тридцати', 'тридцати', 'тридцать', 'тридцатью', + 'тридцати'], + 4: ['сорок', 'сорока', 'сорока', 'сорок', 'сорока', 'сорока'], + 5: ['пятьдесят', 'пятидесяти', 'пятидесяти', 'пятьдесят', 'пятьюдесятью', + 'пятидесяти'], + 6: ['шестьдесят', 'шестидесяти', 'шестидесяти', 'шестьдесят', + 'шестьюдесятью', 'шестидесяти'], + 7: ['семьдесят', 'семидесяти', 'семидесяти', 'семьдесят', 'семьюдесятью', + 'семидесяти'], + 8: ['восемьдесят', 'восьмидесяти', 'восьмидесяти', 'восемьдесят', + 'восемьюдесятью', 'восьмидесяти'], + 9: ['девяносто', 'девяноста', 'девяноста', 'девяносто', 'девяноста', + 'девяноста'], +} + +TWENTIES_ORD_PREFIXES = {2: 'двадцат', 3: 'тридцат', 4: 'сороков', + 5: 'пятидесят', 6: 'шестидесят', 7: 'семидесят', + 8: 'восьмидесят', 9: 'девяност'} +TWENTIES_ORD_POSTFIXES_GROUPS = {2: 1, 3: 1, 4: 0, 5: 1, 6: 1, 7: 1, 8: 1, + 9: 1} +TWENTIES_ORD = get_ord_classifier(TWENTIES_ORD_PREFIXES, + TWENTIES_ORD_POSTFIXES_GROUPS) + +HUNDREDS = { + 1: ['сто', 'ста', 'ста', 'сто', 'ста', 'ста'], + 2: ['двести', 'двухсот', 'двумстам', 'двести', 'двумястами', 'двухстах'], + 3: ['триста', 'трёхсот', 'трёмстам', 'триста', 'тремястами', 'трёхстах'], + 4: ['четыреста', 'четырёхсот', 'четырёмстам', 'четыреста', 'четырьмястами', + 'четырёхстах'], + 5: ['пятьсот', 'пятисот', 'пятистам', 'пятьсот', 'пятьюстами', 'пятистах'], + 6: ['шестьсот', 'шестисот', 'шестистам', 'шестьсот', 'шестьюстами', + 'шестистах'], + 7: ['семьсот', 'семисот', 'семистам', 'семьсот', 'семьюстами', 'семистах'], + 8: ['восемьсот', 'восьмисот', 'восьмистам', 'восемьсот', 'восемьюстами', + 'восьмистах'], + 9: ['девятьсот', 'девятисот', 'девятистам', 'девятьсот', 'девятьюстами', + 'девятистах'], +} + +HUNDREDS_ORD_PREFIXES = { + num: case[1] if num != 1 else 'сот' for num, case in HUNDREDS.items() +} +HUNDREDS_ORD = get_ord_classifier(HUNDREDS_ORD_PREFIXES, 1) + + +THOUSANDS_PREFIXES = {2: 'миллион', 3: 'миллиард', 4: 'триллион', + 5: 'квадриллион', 6: 'квинтиллион', 7: 'секстиллион', + 8: 'септиллион', 9: 'октиллион', 10: 'нониллион'} +THOUSANDS_POSTFIXES = [('', 'а', 'ов'), + ('а', 'ов', 'ов'), + ('у', 'ам', 'ам'), + ('', 'а', 'ов'), + ('ом', 'ами', 'ами'), + ('е', 'ах', 'ах')] +THOUSANDS = { + 1: [['тысяча', 'тысячи', 'тысяч'], + ['тысячи', 'тысяч', 'тысяч'], + ['тысяче', 'тысячам', 'тысячам'], + ['тысячу', 'тысячи', 'тысяч'], + ['тысячей', 'тысячами', 'тысячами'], + ['тысяче', 'тысячах', 'тысячах']] +} +THOUSANDS.update({ + num: [ + [prefix + postfix for postfix in case] for case in THOUSANDS_POSTFIXES + ] for num, prefix in THOUSANDS_PREFIXES.items() +}) + + +def get_thousands_elements(num, case): + return THOUSANDS[num][CASE_INDEXES[case]] + + +THOUSANDS_ORD_PREFIXES = {1: 'тысячн'} +THOUSANDS_ORD_PREFIXES.update({ + num: prefix + 'н' for num, prefix in THOUSANDS_PREFIXES.items() +}) +THOUSANDS_ORD = get_ord_classifier(THOUSANDS_ORD_PREFIXES, 1) + + +class Num2Word_RU(Num2Word_Base): + CURRENCY_FORMS = { + 'RUB': ( + ('рубль', 'рубля', 'рублей'), ('копейка', 'копейки', 'копеек') + ), + 'EUR': ( + ('евро', 'евро', 'евро'), ('цент', 'цента', 'центов') + ), + 'USD': ( + ('доллар', 'доллара', 'долларов'), ('цент', 'цента', 'центов') + ), + 'UAH': ( + ('гривна', 'гривны', 'гривен'), ('копейка', 'копейки', 'копеек') + ), + 'KZT': ( + ('тенге', 'тенге', 'тенге'), ('тиын', 'тиына', 'тиынов') + ), + 'BYN': ( + ('белорусский рубль', 'белорусских рубля', 'белорусских рублей'), + ('копейка', 'копейки', 'копеек') + ), + 'UZS': ( + ('сум', 'сума', 'сумов'), ('тийин', 'тийина', 'тийинов') + ), + 'PLN': ( + ('польский злотый', 'польских слотых', 'польских злотых'), + ('грош', 'гроша', 'грошей') + ), + } + + def setup(self): + self.negword = "минус" + self.pointword = ('целая', 'целых', 'целых') + self.pointword_ord = get_cases("цел", 1) + + def to_cardinal(self, number, case=D_CASE, plural=D_PLURAL, + gender=D_GENDER, animate=D_ANIMATE): + n = str(number).replace(',', '.') + if '.' in n: + left, right = n.split('.') + decimal_part = self._int2word(int(right), cardinal=True, + gender='f') + return u'%s %s %s %s' % ( + self._int2word(int(left), cardinal=True, gender='f'), + self.pluralize(int(left), self.pointword), + decimal_part, + self.__decimal_bitness(right) + ) + else: + return self._int2word(int(n), cardinal=True, case=case, + plural=plural, gender=gender, + animate=animate) + + def __decimal_bitness(self, n): + if n[-1] == "1" and n[-2:] != "11": + return self._int2word(10 ** len(n), cardinal=False, gender='f') + return self._int2word(10 ** len(n), cardinal=False, case='g', + plural=True) + + def pluralize(self, n, forms): + if n % 100 in (11, 12, 13, 14): + return forms[2] + if n % 10 == 1: + return forms[0] + if n % 10 in (2, 3, 4): + return forms[1] + return forms[2] + + def to_ordinal(self, number, case=D_CASE, plural=D_PLURAL, gender=D_GENDER, + animate=D_ANIMATE): + self.verify_ordinal(number) + n = str(number).replace(',', '.') + return self._int2word(int(n), cardinal=False, case=case, plural=plural, + gender=gender, animate=animate) + + def _money_verbose(self, number, currency): + if currency == 'UAH': + return self._int2word(number, gender='f') + return self._int2word(number, gender='m') + + def _cents_verbose(self, number, currency): + if currency in ('UAH', 'RUB', 'BYN'): + return self._int2word(number, gender='f') + return self._int2word(number, gender='m') + + def _int2word(self, n, feminine=False, cardinal=True, case=D_CASE, + plural=D_PLURAL, gender=D_GENDER, animate=D_ANIMATE): + """ + n: number + feminine: not used - for backward compatibility + cardinal:True - cardinal + False - ordinal + case: 'n' - nominative + 'g' - genitive + 'd' - dative + 'a' - accusative + 'i' - instrumental + 'p' - prepositional + plural: True - plural + False - singular + gender: 'f' - masculine + 'm' - feminine + 'n' - neuter + animate: True - animate + False - inanimate + """ + # For backward compatibility + if feminine: + gender = 'f' + + kwargs = {'case': case, 'plural': plural, 'gender': gender, + 'animate': animate} + + if n < 0: + return ' '.join([self.negword, self._int2word(abs(n), + cardinal=cardinal, + **kwargs)]) + + if n == 0: + return get_num_element(ONES, 0, **kwargs) if cardinal else \ + get_num_element(ONES_ORD, 0, **kwargs) + + words = [] + chunks = list(splitbyx(str(n), 3)) + ord_join = chunks[-1] == 0 # join in one word if ending on 'тысячный' + i = len(chunks) + rightest_nonzero_chunk_i = i - 1 - max( + [i for i, e in enumerate(chunks) if e != 0]) + for x in chunks: + chunk_words = [] + i -= 1 + + if x == 0: + continue + + n1, n2, n3 = get_digits(x) + + if cardinal: + chunk_words.extend( + self.__chunk_cardianl(n3, n2, n1, i, **kwargs) + ) + if i > 0: + chunk_words.append( + self.pluralize(x, get_thousands_elements(i, case))) + # ordinal, not joined like 'двухтысячный' + elif not (ord_join and rightest_nonzero_chunk_i == i): + chunk_words.extend( + self.__chunk_ordinal(n3, n2, n1, i, **kwargs) + ) + if i > 0: + t_case = case if rightest_nonzero_chunk_i == i else 'n' + chunk_words.append( + self.pluralize(x, get_thousands_elements(i, t_case))) + # ordinal, joined + else: + chunk_words.extend( + self.__chunk_ordinal_join(n3, n2, n1, i, **kwargs) + ) + if i > 0: + chunk_words.append( + get_num_element(THOUSANDS_ORD, i, **kwargs)) + + chunk_words = [''.join(chunk_words)] + + words.extend(chunk_words) + + return ' '.join(words) + + def __chunk_cardianl(self, hundreds, tens, ones, chunk_num, **kwargs): + words = [] + if hundreds > 0: + words.append(get_num_element(HUNDREDS, hundreds, **kwargs)) + + if tens > 1: + words.append(get_num_element(TWENTIES, tens, **kwargs)) + + if tens == 1: + words.append(get_num_element(TENS, ones, **kwargs)) + elif ones > 0: + if chunk_num == 0: + w_ones = get_num_element(ONES, ones, **kwargs) + elif chunk_num == 1: + # Thousands are feminine + f_kwargs = kwargs.copy() + f_kwargs['gender'] = 'f' + w_ones = get_num_element(ONES, ones, **f_kwargs) + else: + w_ones = get_num_element(ONES, ones, **kwargs) + + words.append(w_ones) + return words + + def __chunk_ordinal(self, hundreds, tens, ones, chunk_num, **kwargs): + words = [] + if hundreds > 0: + if tens == 0 and ones == 0: + words.append(get_num_element(HUNDREDS_ORD, hundreds, **kwargs)) + else: + words.append(get_num_element(HUNDREDS, hundreds)) + + if tens > 1: + if ones == 0: + words.append(get_num_element(TWENTIES_ORD, tens, **kwargs)) + else: + words.append(get_num_element(TWENTIES, tens)) + + if tens == 1: + words.append(get_num_element(TENS_ORD, ones, **kwargs)) + elif ones > 0: + if chunk_num == 0: + w_ones = get_num_element(ONES_ORD, ones, **kwargs) + # тысячный, миллионнный и т.д. + elif chunk_num > 0 and ones == 1 and hundreds == 0 and tens == 0: + w_ones = None + elif chunk_num == 1: + # Thousands are feminine + w_ones = get_num_element(ONES, ones, gender='f') + else: + w_ones = get_num_element(ONES, ones) + + if w_ones: + words.append(w_ones) + + return words + + def __chunk_ordinal_join(self, hundreds, tens, ones, chunk_num, **kwargs): + words = [] + + if hundreds > 1: + words.append(get_num_element(HUNDREDS, hundreds, case='g')) + elif hundreds == 1: + words.append(get_num_element(HUNDREDS, hundreds)) # стО, not стА + + if tens == 9: + words.append(get_num_element(TWENTIES, tens)) # девяностО, not А + elif tens > 1: + words.append(get_num_element(TWENTIES, tens, case='g')) + + if tens == 1: + words.append(get_num_element(TENS, ones, case='g')) + elif ones > 0: + if chunk_num == 0: + w_ones = get_num_element(ONES_ORD, ones, **kwargs) + # тысячный, миллионнный и т.д., двадцатиодномиллионный + elif chunk_num > 0 and ones == 1 and tens != 1: + if tens == 0 and hundreds == 0: + w_ones = None + else: + w_ones = get_num_element(ONES, 1, gender='n') + else: + w_ones = get_num_element(ONES, ones, case='g') + + if w_ones: + words.append(w_ones) + + return words diff --git a/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_SK.py b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_SK.py new file mode 100644 index 0000000000000000000000000000000000000000..35ece024f13cf90999d3ca4954229f1d4994a4ba --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_SK.py @@ -0,0 +1,160 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2013, Savoir-faire Linux inc. All Rights Reserved. + +# This library 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. +# This library 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 along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301 USA + +from __future__ import unicode_literals + +from .base import Num2Word_Base +from .utils import get_digits, splitbyx + +ZERO = ('nula',) + +ONES = { + 1: ('jeden', 'jeden', set()), + 2: ('dva', 'dve', {1, 3, 5, 7, 9}), + 3: ('tri', 'tri', set()), + 4: ('štyri', 'štyri', set()), + 5: ('päť', 'päť', set()), + 6: ('šesť', 'šesť', set()), + 7: ('sedem', 'sedem', set()), + 8: ('osem', 'osem', set()), + 9: ('deväť', 'deväť', set()), +} + +TENS = { + 0: ('desať',), + 1: ('jedenásť',), + 2: ('dvanásť',), + 3: ('trinásť',), + 4: ('štrnásť',), + 5: ('pätnásť',), + 6: ('šestnásť',), + 7: ('sedemnásť',), + 8: ('osemnásť',), + 9: ('devätnásť',), +} + +TWENTIES = { + 2: ('dvadsať',), + 3: ('tridsať',), + 4: ('štyridsať',), + 5: ('päťdesiat',), + 6: ('šesťdesiat',), + 7: ('sedemdesiat',), + 8: ('osemdesiat',), + 9: ('deväťdesiat',), +} + +HUNDREDS = { + 1: ('sto',), + 2: ('dvesto',), + 3: ('tristo',), + 4: ('štyristo',), + 5: ('päťsto',), + 6: ('šesťsto',), + 7: ('sedemsto',), + 8: ('osemsto',), + 9: ('deväťsto',), +} + +THOUSANDS = { + 1: ('tisíc', 'tisíc', 'tisíc'), # 10^3 + 2: ('milión', 'milióny', 'miliónov'), # 10^6 + 3: ('miliarda', 'miliardy', 'miliárd'), # 10^9 + 4: ('bilión', 'bilióny', 'biliónov'), # 10^12 + 5: ('biliarda', 'biliardy', 'biliárd'), # 10^15 + 6: ('trilión', 'trilióny', 'triliónov'), # 10^18 + 7: ('triliarda', 'triliardy', 'triliárd'), # 10^21 + 8: ('kvadrilión', 'kvadrilióny', 'kvadriliónov'), # 10^24 + 9: ('kvadriliarda', 'kvadriliardy', 'kvadriliárd'), # 10^27 + 10: ('kvintilión', 'kvintillióny', 'kvintiliónov'), # 10^30 +} + + +class Num2Word_SK(Num2Word_Base): + CURRENCY_FORMS = { + 'EUR': ( + ('euro', 'eurá', 'eur'), ('cent', 'centy', 'centov') + ), + } + + def setup(self): + self.negword = "mínus" + self.pointword = "celých" + + def to_cardinal(self, number): + n = str(number).replace(',', '.') + if '.' in n: + left, right = n.split('.') + leading_zero_count = len(right) - len(right.lstrip('0')) + decimal_part = ((ZERO[0] + ' ') * leading_zero_count + + self._int2word(int(right))) + return u'%s %s %s' % ( + self._int2word(int(left)), + self.pointword, + decimal_part + ) + else: + return self._int2word(int(n)) + + def pluralize(self, n, forms): + if n == 1: + form = 0 + elif 0 < n < 5: + form = 1 + else: + form = 2 + return forms[form] + + def to_ordinal(self, value): + raise NotImplementedError() + + def _int2word(self, n): + if n == 0: + return ZERO[0] + + words = [] + chunks = list(splitbyx(str(n), 3)) + i = len(chunks) + for x in chunks: + i -= 1 + + if x == 0: + continue + + n1, n2, n3 = get_digits(x) + + word_chunk = [] + + if n3 > 0: + word_chunk.append(HUNDREDS[n3][0]) + + if n2 > 1: + word_chunk.append(TWENTIES[n2][0]) + + if n2 == 1: + word_chunk.append(TENS[n1][0]) + elif n1 > 0 and not (i > 0 and x == 1): + if n2 == 0 and n3 == 0 and i in ONES[n1][2]: + word_chunk.append(ONES[n1][1]) + else: + word_chunk.append(ONES[n1][0]) + if i > 1 and word_chunk: + word_chunk.append(' ') + if i > 0: + word_chunk.append(self.pluralize(x, THOUSANDS[i])) + words.append(''.join(word_chunk)) + + return ' '.join(words[:-1]) + ''.join(words[-1:]) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_SL.py b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_SL.py new file mode 100644 index 0000000000000000000000000000000000000000..617b0335ed862779d661b513b7a12de270e04053 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_SL.py @@ -0,0 +1,171 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2003, Taro Ogawa. All Rights Reserved. +# Copyright (c) 2013, Savoir-faire Linux inc. All Rights Reserved. +# Copyright (c) 2015, Blaz Bregar. All Rights Reserved. + +# This library 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. +# This library 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 along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301 USA + +from __future__ import unicode_literals + +from .lang_EU import Num2Word_EU + + +class Num2Word_SL(Num2Word_EU): + GIGA_SUFFIX = "ilijard" + MEGA_SUFFIX = "ilijon" + + def setup(self): + super(Num2Word_SL, self).setup() + + self.negword = "minus " + self.pointword = "celih" + self.errmsg_nonnum = "Only numbers may be converted to words." + self.errmsg_toobig = ( + "Number is too large to convert to words (abs(%s) > %s)." + ) + self.exclude_title = [] + + self.mid_numwords = [(1000, "tisoč"), (900, "devetsto"), + (800, "osemsto"), (700, "sedemsto"), + (600, "šeststo"), (500, "petsto"), + (400, "štiristo"), (300, "tristo"), + (200, "dvesto"), (100, "sto"), + (90, "devetdeset"), (80, "osemdeset"), + (70, "sedemdeset"), (60, "šestdeset"), + (50, "petdeset"), (40, "štirideset"), + (30, "trideset")] + self.low_numwords = ["dvajset", "devetnajst", "osemnajst", + "sedemnajst", "šestnajst", "petnajst", + "štirinajst", "trinajst", "dvanajst", + "enajst", "deset", "devet", "osem", "sedem", + "šest", "pet", "štiri", "tri", "dve", "ena", + "nič"] + self.ords = {"ena": "prv", + "dve": "drug", + "tri": "tretj", + "štiri": "četrt", + "sedem": "sedm", + "osem": "osm", + "sto": "stot", + "tisoč": "tisoč", + "milijon": "milijont" + } + self.ordflag = False + + def merge(self, curr, next): + ctext, cnum, ntext, nnum = curr + next + + if ctext.endswith("dve") and self.ordflag and nnum <= 1000000: + ctext = ctext[:len(ctext)-1] + "a" + + if ctext == "dve" and not self.ordflag and nnum < 1000000000: + ctext = "dva" + + if (ctext.endswith("tri") or ctext.endswith("štiri")) and\ + nnum == 1000000 and not self.ordflag: + if ctext.endswith("štiri"): + ctext = ctext[:-1] + ctext = ctext + "je" + + if cnum >= 20 and cnum < 100 and nnum == 2: + ntext = "dva" + + if ctext.endswith("ena") and nnum >= 1000: + ctext = ctext[0:-1] + + if cnum == 1: + if nnum < 10**6 or self.ordflag: + return next + ctext = "" + + if nnum > cnum: + if nnum >= 10**6: + if self.ordflag: + ntext += "t" + + elif cnum == 2: + if ntext.endswith("d"): + ntext += "i" + else: + ntext += "a" + + elif 2 < cnum < 5: + if ntext.endswith("d"): + ntext += "e" + elif not ntext.endswith("d"): + ntext += "i" + + elif ctext.endswith("en"): + if ntext.endswith("d") or ntext.endswith("n"): + ntext += "" + + elif ctext.endswith("dve") and ntext.endswith("n"): + ctext = ctext[:-1] + "a" + ntext += "a" + + elif ctext.endswith("je") and ntext.endswith("n"): + ntext += "i" + + else: + if ntext.endswith("d"): + ntext += "a" + elif ntext.endswith("n"): + ntext += "" + elif ntext.endswith("d"): + ntext += "e" + else: + ntext += "ov" + + if nnum >= 10**2 and self.ordflag is False and ctext: + ctext += " " + + val = cnum * nnum + else: + if nnum < 10 < cnum < 100: + ntext, ctext = ctext, ntext + "in" + elif cnum >= 10**2 and self.ordflag is False: + ctext += " " + val = cnum + nnum + + word = ctext + ntext + return (word, val) + + def to_ordinal(self, value): + self.verify_ordinal(value) + self.ordflag = True + outword = self.to_cardinal(value) + self.ordflag = False + for key in self.ords: + if outword.endswith(key): + outword = outword[:len(outword) - len(key)] + self.ords[key] + break + return outword + "i" + + # Is this correct?? + def to_ordinal_num(self, value): + self.verify_ordinal(value) + return str(value) + "." + + def to_currency(self, val, longval=True, old=False): + if old: + return self.to_splitnum(val, hightxt="evro/a/v", + lowtxt="stotin/a/i/ov", + jointxt="in", longval=longval) + return super(Num2Word_SL, self).to_currency(val, jointxt="in", + longval=longval) + + def to_year(self, val, longval=True): + if not (val//100) % 10: + return self.to_cardinal(val) + return self.to_splitnum(val, hightxt="hundert", longval=longval) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_SR.py b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_SR.py new file mode 100644 index 0000000000000000000000000000000000000000..254209fe7eb55685dbbcf2ea1b7549f6df8fff12 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_SR.py @@ -0,0 +1,219 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2003, Taro Ogawa. All Rights Reserved. +# Copyright (c) 2013, Savoir-faire Linux inc. All Rights Reserved. + +# This library 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. +# This library 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 along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301 USA + +from __future__ import unicode_literals + +from .base import Num2Word_Base +from .currency import parse_currency_parts, prefix_currency +from .utils import get_digits, splitbyx + +ZERO = ('nula',) + +ONES = { + 1: ('jedan', 'jedna'), + 2: ('dva', 'dve'), + 3: ('tri', 'tri'), + 4: ('četiri', 'četiri'), + 5: ('pet', 'pet'), + 6: ('šest', 'šest'), + 7: ('sedam', 'sedam'), + 8: ('osam', 'osam'), + 9: ('devet', 'devet'), +} + +TENS = { + 0: ('deset',), + 1: ('jedanaest',), + 2: ('dvanaest',), + 3: ('trinaest',), + 4: ('četrnaest',), + 5: ('petnaest',), + 6: ('šesnaest',), + 7: ('sedamnaest',), + 8: ('osamnaest',), + 9: ('devetnaest',), +} + +TWENTIES = { + 2: ('dvadeset',), + 3: ('trideset',), + 4: ('četrdeset',), + 5: ('pedeset',), + 6: ('šezdeset',), + 7: ('sedamdeset',), + 8: ('osamdeset',), + 9: ('devedeset',), +} + +HUNDREDS = { + 1: ('sto',), + 2: ('dvesta',), + 3: ('trista',), + 4: ('četristo',), + 5: ('petsto',), + 6: ('šesto',), + 7: ('sedamsto',), + 8: ('osamsto',), + 9: ('devetsto',), +} + +SCALE = { + 0: ('', '', '', False), + 1: ('hiljada', 'hiljade', 'hiljada', True), # 10^3 + 2: ('milion', 'miliona', 'miliona', False), # 10^6 + 3: ('bilion', 'biliona', 'biliona', False), # 10^9 + 4: ('trilion', 'triliona', 'triliona', False), # 10^12 + 5: ('kvadrilion', 'kvadriliona', 'kvadriliona', False), # 10^15 + 6: ('kvintilion', 'kvintiliona', 'kvintiliona', False), # 10^18 + 7: ('sekstilion', 'sekstiliona', 'sekstiliona', False), # 10^21 + 8: ('septilion', 'septiliona', 'septiliona', False), # 10^24 + 9: ('oktilion', 'oktiliona', 'oktiliona', False), # 10^27 + 10: ('nonilion', 'noniliona', 'noniliona', False), # 10^30 +} + + +class Num2Word_SR(Num2Word_Base): + CURRENCY_FORMS = { + 'RUB': ( + ('rublja', 'rublje', 'rublji', True), + ('kopejka', 'kopejke', 'kopejki', True) + ), + 'EUR': ( + ('evro', 'evra', 'evra', False), + ('cent', 'centa', 'centi', False) + ), + 'RSD': ( + ('dinar', 'dinara', 'dinara', False), + ('para', 'pare', 'para', True) + ), + } + + def setup(self): + self.negword = "minus" + self.pointword = "zapeta" + + def to_cardinal(self, number, feminine=False): + n = str(number).replace(',', '.') + if '.' in n: + left, right = n.split('.') + leading_zero_count = len(right) - len(right.lstrip('0')) + decimal_part = ((ZERO[0] + ' ') * leading_zero_count + + self._int2word(int(right), feminine)) + return u'%s %s %s' % ( + self._int2word(int(left), feminine), + self.pointword, + decimal_part + ) + else: + return self._int2word(int(n), feminine) + + def pluralize(self, number, forms): + if number % 100 < 10 or number % 100 > 20: + if number % 10 == 1: + form = 0 + elif 1 < number % 10 < 5: + form = 1 + else: + form = 2 + else: + form = 2 + return forms[form] + + def to_ordinal(self, number): + raise NotImplementedError() + + def _cents_verbose(self, number, currency): + return self._int2word( + number, + self.CURRENCY_FORMS[currency][1][-1] + ) + + def _int2word(self, number, feminine=False): + if number < 0: + return ' '.join([self.negword, self._int2word(abs(number))]) + + if number == 0: + return ZERO[0] + + words = [] + chunks = list(splitbyx(str(number), 3)) + chunk_len = len(chunks) + for chunk in chunks: + chunk_len -= 1 + digit_right, digit_mid, digit_left = get_digits(chunk) + + if digit_left > 0: + words.append(HUNDREDS[digit_left][0]) + + if digit_mid > 1: + words.append(TWENTIES[digit_mid][0]) + + if digit_mid == 1: + words.append(TENS[digit_right][0]) + elif digit_right > 0: + is_feminine = feminine or SCALE[chunk_len][-1] + gender_idx = int(is_feminine) + words.append( + ONES[digit_right][gender_idx] + ) + + if chunk_len > 0 and chunk != 0: + words.append(self.pluralize(chunk, SCALE[chunk_len])) + + return ' '.join(words) + + def to_currency(self, val, currency='EUR', cents=True, separator=',', + adjective=False): + """ + Args: + val: Numeric value + currency (str): Currency code + cents (bool): Verbose cents + separator (str): Cent separator + adjective (bool): Prefix currency name with adjective + Returns: + str: Formatted string + + """ + left, right, is_negative = parse_currency_parts(val) + + try: + cr1, cr2 = self.CURRENCY_FORMS[currency] + + except KeyError: + raise NotImplementedError( + 'Currency code "%s" not implemented for "%s"' % + (currency, self.__class__.__name__)) + + if adjective and currency in self.CURRENCY_ADJECTIVES: + cr1 = prefix_currency( + self.CURRENCY_ADJECTIVES[currency], + cr1 + ) + + minus_str = "%s " % self.negword if is_negative else "" + cents_str = self._cents_verbose(right, currency) \ + if cents else self._cents_terse(right, currency) + + return u'%s%s %s%s %s %s' % ( + minus_str, + self.to_cardinal(left, feminine=cr1[-1]), + self.pluralize(left, cr1), + separator, + cents_str, + self.pluralize(right, cr2) + ) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_SV.py b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_SV.py new file mode 100644 index 0000000000000000000000000000000000000000..4e32841cffde3333692c55deb329f9969f67f825 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_SV.py @@ -0,0 +1,117 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2003, Taro Ogawa. All Rights Reserved. +# Copyright (c) 2013, Savoir-faire Linux inc. All Rights Reserved. + +# This library 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. +# This library 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 along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301 USA + +from __future__ import division, print_function, unicode_literals + +from . import lang_EU + + +class Num2Word_SV(lang_EU.Num2Word_EU): + GIGA_SUFFIX = "iljarder" + MEGA_SUFFIX = "iljoner" + + def set_high_numwords(self, high): + cap = 3 + 6 * len(high) + + for word, n in zip(high, range(cap, 3, -6)): + if self.GIGA_SUFFIX: + self.cards[10 ** n] = word + self.GIGA_SUFFIX + + if self.MEGA_SUFFIX: + self.cards[10 ** (n - 3)] = word + self.MEGA_SUFFIX + + def setup(self): + super(Num2Word_SV, self).setup() + + self.negword = "minus " + self.pointword = "komma" + self.exclude_title = ["och", "komma", "minus"] + + self.mid_numwords = [(1000, "tusen"), (100, "hundra"), + (90, "nittio"), (80, "åttio"), (70, "sjuttio"), + (60, "sextio"), (50, "femtio"), (40, "förtio"), + (30, "trettio")] + self.low_numwords = ["tjugo", "nitton", "arton", "sjutton", + "sexton", "femton", "fjorton", "tretton", + "tolv", "elva", "tio", "nio", "åtta", + "sju", "sex", "fem", "fyra", "tre", "två", + "ett", "noll"] + self.ords = {"noll": "nollte", + "ett": "första", + "två": "andra", + "tre": "tredje", + "fyra": "fjärde", + "fem": "femte", + "sex": "sjätte", + "sju": "sjunde", + "åtta": "åttonde", + "nio": "nionde", + "tio": "tionde", + "elva": "elfte", + "tolv": "tolfte", + "tjugo": "tjugonde"} + + def merge(self, lpair, rpair): + ltext, lnum = lpair + rtext, rnum = rpair + if lnum == 1 and rnum < 100: + return (rtext, rnum) + elif 100 > lnum > rnum: + return ("%s%s" % (ltext, rtext), lnum + rnum) + elif lnum >= 100 > rnum: + return ("%s%s" % (ltext, rtext), lnum + rnum) + elif rnum >= 1000000 and lnum == 1: + return ("%s %s" % ('en', rtext[:-2]), lnum + rnum) + elif rnum >= 1000000 and lnum > 1: + return ("%s %s" % (ltext, rtext), lnum + rnum) + elif rnum > lnum: + return ("%s%s" % (ltext, rtext), lnum * rnum) + return ("%s %s" % (ltext, rtext), lnum + rnum) + + def to_ordinal(self, value): + self.verify_ordinal(value) + outwords = self.to_cardinal(value).split(" ") + lastword = outwords[-1] + ending_length = 0 + try: + lastword_ending = self.ords[lastword[-4:]] + ending_length = 4 + except KeyError: + try: + lastword_ending = self.ords[lastword[-3:]] + ending_length = 3 + except KeyError: + lastword_ending = "de" + if lastword_ending == 'de': + lastword_first_part = self.title(lastword)[:] + else: + lastword_first_part = self.title(lastword)[:-ending_length] + lastword_correct = lastword_first_part + lastword_ending + outwords[-1] = lastword_correct + return " ".join(outwords) + + def to_ordinal_num(self, value): + raise NotImplementedError( + "'ordinal_num' is not implemented for swedish language") + + def to_year(self, val, longval=True): + raise NotImplementedError( + "'year' is not implemented for swedish language") + + def to_currency(self, val, longval=True): + raise NotImplementedError( + "'currency' is not implemented for swedish language") diff --git a/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_TE.py b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_TE.py new file mode 100644 index 0000000000000000000000000000000000000000..274d3125425618b11f876b23c56c0b2d693fd49d --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_TE.py @@ -0,0 +1,169 @@ +# -*- coding: utf-8 -*- + +from __future__ import unicode_literals + +from .lang_EU import Num2Word_EU + + +class Num2Word_TE(Num2Word_EU): + def set_high_numwords(self, high): + for n, word in self.high_numwords: + self.cards[10**n] = word + + def setup(self): + self.low_numwords = [ + "తొంభై తొమ్మిది", + "తొంభై ఎనిమిది", + "తొంభై ఏడు", + "తొంభై ఆరు", + "తొంభై అయిదు", + "తొంభై నాలుగు", + "తొంభై మూడు", + "తొంభై రెండు", + "తొంభై ఒకటి", + "తొంభై", + "ఎనభై తొమ్మిది", + "ఎనభై ఎనిమిది", + "ఎనభై ఏడు", + "ఎనభై ఆరు", + "ఎనభై అయిదు", + "ఎనభై నాలుగు", + "ఎనభై మూడు", + "ఎనభై రెండు", + "ఎనభై ఒకటి", + "ఎనభై", + "డెబ్బై తొమ్మిది", + "డెబ్బై ఎనిమిది", + "డెబ్బై ఏడు", + "డెబ్బై ఆరు", + "డెబ్బై అయిదు", + "డెబ్బై నాలుగు", + "డెబ్బై మూడు", + "డెబ్బై రెండు", + "డెబ్బై ఒకటి", + "డెబ్బై", + "అరవై తొమ్మిది", + "అరవై ఎనిమిది", + "అరవై ఏడు", + "అరవై ఆరు", + "అరవై అయిదు", + "అరవై నాలుగు", + "అరవై మూడు", + "అరవై రెండు", + "అరవై ఒకటి", + "అరవై", + "యాభై తొమ్మిది", + "యాభై ఎనిమిది", + "యాభై ఏడు", + "యాభై ఆరు", + "యాభై అయిదు", + "యాభై నాలుగు", + "యాభై మూడు", + "యాభై రెండు", + "యాభై ఒకటి", + "యాభై ", + "నలభై తొమ్మిది", + "నలభై ఎనిమిది", + "నలభై ఏడు", + "నలభై ఆరు", + "నలభై అయిదు", + "నలభై నాలుగు", + "నలభై మూడు", + "నలభై రెండు", + "నలభై ఒకటి", + "నలభై", + "ముప్పై తొమ్మిది", + "ముప్పై ఎనిమిది", + "ముప్పై ఏడు", + "ముప్పై ఆరు", + "ముప్పై ఐదు", + "ముప్పై నాలుగు", + "ముప్పై మూడు", + "ముప్పై రెండు", + "ముప్పై ఒకటి", + "ముప్పై", + "ఇరవై తొమ్మిది", + "ఇరవై ఎనిమిది", + "ఇరవై ఏడు", + "ఇరవై ఆరు", + "ఇరవై అయిదు", + "ఇరవై నాలుగు", + "ఇరవై మూడు", + "ఇరవై రెండు", + "ఇరవై ఒకటి", + "ఇరవై", + "పందొమ్మిది", + "పధ్ధెనిమిది", + "పదిహేడు", + "పదహారు", + "పదునయిదు", + "పధ్నాలుగు", + "పదమూడు", + "పన్నెండు", + "పదకొండు", + "పది", + "తొమ్మిది", + "ఎనిమిది", + "ఏడు", + "ఆరు", + "అయిదు", + "నాలుగు", + "మూడు", + "రెండు", + "ఒకటి", + "సున్న", + ] + + self.mid_numwords = [(100, "వంద")] + + self.high_numwords = [(7, "కోట్ల"), (5, "లక్ష"), (3, "వేయి")] + + self.pointword = "బిందువు " + + self.modifiers = [ + " ్ ", + "ా ", + " ి ", + " ీ ", + " ు ", + " ూ ", + " ృ ", + " ౄ ", + " ె ", + " ే ", + " ై ", + " ొ", + " ో ", + " ౌ ", + " ఁ ", + " ం ", + " ః ", + ] + + def merge(self, lpair, rpair): + ltext, lnum = lpair + rtext, rnum = rpair + if lnum == 1 and rnum < 100: + return (rtext, rnum) + elif 100 > lnum > rnum: + return ("%s-%s" % (ltext, rtext), lnum + rnum) + elif lnum >= 100 > rnum: + if ltext[-1] in self.modifiers: + return ("%s %s" % (ltext[:-1], rtext), lnum + rnum) + else: + return ("%s %s" % (ltext+"ల", rtext), lnum + rnum) + elif rnum > lnum: + return ("%s %s" % (ltext, rtext), lnum * rnum) + return ("%s %s" % (ltext, rtext), lnum + rnum) + + def to_ordinal_num(self, value): + self.verify_ordinal(value) + return "%s%s" % (value, self.to_ordinal(value)[-1:]) + + def to_ordinal(self, value): + self.verify_ordinal(value) + outwords = self.to_cardinal(value) + if outwords[-1] in self.modifiers: + outwords = outwords[:-1] + ordinal_num = outwords + "వ" + return ordinal_num diff --git a/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_TET.py b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_TET.py new file mode 100644 index 0000000000000000000000000000000000000000..141a8c66836ff002ab8f3fcc8cfd761b61d3f125 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_TET.py @@ -0,0 +1,251 @@ +# -*- coding: utf-8 -*-Num2Word_TET +# Copyright (c) 2003, Taro Ogawa. All Rights Reserved. +# Copyright (c) 2013, Savoir-faire Linux inc. All Rights Reserved. + +# This library 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. +# This library 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 along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301 USA + + +from num2words.currency import parse_currency_parts + +from .lang_EU import Num2Word_EU + +DOLLAR = ('dolar', 'dolar') +CENTS = ('sentavu', 'sentavu') + + +class Num2Word_TET(Num2Word_EU): + + CURRENCY_FORMS = { + 'AUD': (DOLLAR, CENTS), + 'CAD': (DOLLAR, CENTS), + 'EUR': (('euro', 'euros'), CENTS), + 'GBP': (('pound sterling', 'pound sterling'), ('pence', 'pence')), + 'USD': (DOLLAR, CENTS), + } + + GIGA_SUFFIX = None + MEGA_SUFFIX = "iliaun" + + def setup(self): + super().setup() + lows = ["kuatr", "tr", "b", "m"] + self.high_numwords = self.gen_high_numwords([], [], lows) + self.negword = "menus " + self.pointword = "vírgula" + self.exclude_title = ["resin", "vírgula", "menus"] + self.count = 0 + + self.mid_numwords = [ + (1000, "rihun"), (100, "atus"), (90, "sianulu"), + (80, "ualunulu"), (70, "hitunulu"), (60, "neenulu"), + (50, "limanulu"), (40, "haatnulu"), (30, "tolunulu"), + (20, "ruanulu") + ] + self.low_numwords = [ + "sanulu", + "sia", "ualu", "hitu", "neen", "lima", "haat", "tolu", "rua", + "ida", "mamuk" + ] + self.hundreds = { + 1: "atus", + 2: "atus rua", + 3: "atus tolu", + 4: "atus haat", + 5: "atus lima", + 6: "atus neen", + 7: "atus hitu", + 8: "atus ualu", + 9: "atus sia", + } + + def merge(self, curr, next): + ctext, cnum, ntext, nnum = curr + next + + if cnum == 1 and nnum < 100: + return next + + if nnum < cnum: + if nnum < 10: + value_str = str(cnum + nnum) + if int(value_str) > 100: + zero_list = value_str[1:-1] + all_zero = all(element == '0' for element in zero_list) + if all_zero: + if self.count >= 1: + self.count += 0 + return ( + "ho %s %s" % (ctext, ntext), + cnum + nnum + ) + self.count += 1 + return ("%s %s" % (ctext, ntext), cnum + nnum) + + return ("%s resin %s" % (ctext, ntext), cnum + nnum) + else: + return ("%s %s" % (ctext, ntext), cnum + nnum) + + return (ntext + " " + ctext, cnum * nnum) + + def ho_result(self, result, value): + index = result.find('ho') + count_ho = result.count('ho') + + if index != -1 and count_ho >= 1: + index_rihun = result.find('rihun') + value_str = len(str(value)) + if index_rihun != -1 and value_str > 7: + result = result.replace("rihun ho", "ho rihun") + lows = ["kuatr", "tr", "b", "m"] + MEGA_SUFFIX = "iliaun" + for low in lows: + result = result.replace( + low + MEGA_SUFFIX + " ho", "ho " + low + MEGA_SUFFIX) + remove_first_ho = result.startswith('ho') + if remove_first_ho: + result = result[3:] + return result + + def remove_ho(self, result, value): + value_str = str(value) + result = self.ho_result(result, value) + end_value = value_str[:-4] + end_true = end_value.endswith('0') + if end_true is False: + if value > 100: + if value_str[-1] != '0' and value_str[-2] == '0': + result = result.replace("ho", "") + result = result.replace(" ", " ") + + return result + + def to_cardinal(self, value): + result = super().to_cardinal(value) + + results = self.remove_ho(result, value) + return results + + def to_ordinal(self, value): + self.verify_ordinal(value) + out = "" + val = self.splitnum(value) + outs = val + while len(val) != 1: + outs = [] + left, right = val[:2] + if isinstance(left, tuple) and isinstance(right, tuple): + outs.append(self.merge(left, right)) + if val[2:]: + outs.append(val[2:]) + else: + for elem in val: + if isinstance(elem, list): + if len(elem) == 1: + outs.append(elem[0]) + else: + outs.append(self.clean(elem)) + else: + outs.append(elem) + val = outs + + words, num = outs[0] + + words = self.remove_ho(words, value) + + if num in [90, 80, 70, 60, 50, 40, 30, 20, 10, 9, 8, 7, 5, 3, 2]: + words = 'da'+words+'k' + if num in [6, 4]: + words = 'da'+words + if num == 1: + words = 'dahuluk' + if num in [900, 800, 700, 500, 300, 200, 100]: + words = 'dah'+words+'k' + if num in [600, 400]: + words = 'dah'+words + + words_split = words.split() + if len(words_split) >= 3 and num < 100: + first_word = 'da'+words_split[0] + second_word = " ".join(words_split[1:]) + if 'haat' in second_word or 'neen' in second_word: + words = first_word+" "+second_word + else: + words = first_word+" "+second_word+'k' + + word_first = 'dah'+words_split[0] + if word_first == 'dahatus' and len(words_split) >= 3: + word_second = " ".join(words_split[1:]) + if 'haat' in word_second or 'neen' in word_second: + words = word_first+" "+word_second + else: + words = word_first+" "+word_second+'k' + + if len(str(num)) > 3: + if 'haat' in words_split[-1:] or 'neen' in words_split[-1:]: + words = 'da'+words + else: + words = 'da'+words+'k' + + result = self.title(out + words) + + return result + + def to_ordinal_num(self, value): + self.verify_ordinal(value) + return "%sº" % (value) + + def to_year(self, val, longval=True): + if val < 0: + return self.to_cardinal(abs(val)) + ' antes Kristu' + return self.to_cardinal(val) + + def to_currency(self, val, currency='USD', cents=True): + """ + Args: + val: Numeric value + currency (str): Currency code + cents (bool): Verbose cents + adjective (bool): Prefix currency name with adjective + Returns: + str: Formatted string + + """ + left, right, is_negative = parse_currency_parts(val) + + try: + cr1, cr2 = self.CURRENCY_FORMS[currency] + + except KeyError: + raise NotImplementedError( + 'Currency code "%s" not implemented for "%s"' % + (currency, self.__class__.__name__)) + + minus_str = "%s " % self.negword.strip() if is_negative else "" + money_str = self._money_verbose(left, currency) + cents_str = self._cents_verbose(right, currency) \ + if cents else self._cents_terse(right, currency) + + if right == 0: + return u'%s%s %s' % ( + minus_str, + self.pluralize(left, cr1), + money_str + ) + else: + return u'%s%s %s %s %s' % ( + minus_str, + self.pluralize(left, cr1), + money_str, + self.pluralize(right, cr2), + cents_str + ) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_TG.py b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_TG.py new file mode 100644 index 0000000000000000000000000000000000000000..48291a269b2ad423fb797d53976fc16c84bfe8a3 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_TG.py @@ -0,0 +1,149 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2003, Taro Ogawa. All Rights Reserved. +# Copyright (c) 2013, Savoir-faire Linux inc. All Rights Reserved. + +# This library 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. +# This library 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 along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301 USA + +from __future__ import division, print_function, unicode_literals + +from . import lang_EU + +GENERIC_DOLLARS = ("доллар", "доллар") +GENERIC_CENTS = ("сент", "сент") + + +class Num2Word_TG(lang_EU.Num2Word_EU): + CURRENCY_FORMS = { + # repalced by EUR + "EUR": (("евро", "евро"), GENERIC_CENTS), + # replaced by EUR + "USD": (GENERIC_DOLLARS, GENERIC_CENTS), + "RUB": (("рубл", "рубл"), ("копейк", "копейк")), + "TJS": (("сомонӣ", "сомонӣ"), ("дирам", "дирам")), + } + + GIGA_SUFFIX = "иллиард" + MEGA_SUFFIX = "иллион" + + def set_high_numwords(self, high): + cap = 3 * (len(high) + 1) + + for word, n in zip(high, range(cap, 5, -3)): + if n == 9: + self.cards[10 ** n] = word + self.GIGA_SUFFIX + + else: + self.cards[10 ** n] = word + self.MEGA_SUFFIX + + def setup(self): + super(Num2Word_TG, self).setup() + + lows = ["квинт", "квадр", "тр", "м", "м"] + self.high_numwords = self.gen_high_numwords([], [], lows) + self.negword = "минус " + self.pointword = "нуқта" + self.exclude_title = ["ва", "минус", "нуқта"] + + self.mid_numwords = [ + (1000, "ҳазор"), + (100, "сад"), + (90, "навад"), + (80, "ҳаштод"), + (70, "ҳафтод"), + (60, "шаст"), + (50, "панҷоҳ"), + (40, "чил"), + (30, "си"), + ] + self.low_numwords = [ + "бист", + "нуздаҳ", + "ҳаждаҳ", + "ҳабдаҳ", + "шонздаҳ", + "понздаҳ", + "чордаҳ", + "сенздаҳ", + "дувоздаҳ", + "ёздаҳ", + "даҳ", + "нӯҳ", + "ҳашт", + "ҳафт", + "шаш", + "панҷ", + "чор", + "се", + "ду", + "як", + "сифр", + ] + + def to_cardinal(self, value): + try: + assert int(value) == value + except (ValueError, TypeError, AssertionError): + return self.to_cardinal_float(value) + + out = "" + if value < 0: + value = abs(value) + out = self.negword + + if value >= self.MAXVAL: + raise OverflowError(self.errmsg_toobig % (value, self.MAXVAL)) + + if value == 100: + return self.title(out + "сад") + else: + val = self.splitnum(value) + words, num = self.clean(val) + return self.title(out + words) + + def merge(self, lpair, rpair): + ltext, lnum = lpair + rtext, rnum = rpair + if lnum == 1 and rnum < 100: + return (rtext, rnum) + elif 100 > lnum > rnum: + if ltext == "си": + return ("%sю %s" % (ltext, rtext), lnum + rnum) + elif ltext == "панҷоҳ": + return ("панҷову %s" % (rtext), lnum + rnum) + else: + return ("%sу %s" % (ltext, rtext), lnum + rnum) + elif lnum >= 100 > rnum: + return ("%sу %s" % (ltext, rtext), lnum + rnum) + elif rnum > lnum: + if ltext == "яксад" and rtext not in self.low_numwords: + return ("сад %s" % (rtext), lnum * rnum) + if rtext == "сад": + return ("%s%s" % (ltext, rtext), lnum * rnum) + else: + return ("%s %s" % (ltext, rtext), lnum * rnum) + return ("%sу %s" % (ltext, rtext), lnum + rnum) + + def to_ordinal(self, value): + self.verify_ordinal(value) + cardinal = self.to_cardinal(value) + outwords = cardinal.split(" ") + lastword = outwords[-1] + if lastword in ["ду", "се", "си"]: + return "%sюм" % (cardinal) + else: + return "%sум" % (cardinal) + + def to_ordinal_num(self, value): + self.verify_ordinal(value) + return "%s%s" % (value, self.to_ordinal(value)[-2:]) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_TH.py b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_TH.py new file mode 100644 index 0000000000000000000000000000000000000000..42811ea4d6e52e24afbf3e4b4e4f198e6efa857d --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_TH.py @@ -0,0 +1,183 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2003, Taro Ogawa. All Rights Reserved. +# Copyright (c) 2013, Savoir-faire Linux inc. All Rights Reserved. + +# This library 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. +# This library 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 along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301 USA + +from __future__ import unicode_literals + +from num2words.base import Num2Word_Base +from num2words.currency import parse_currency_parts +from num2words.utils import splitbyx + + +class Num2Word_TH(Num2Word_Base): + + def setup(self): + self.negword = 'ติดลบ' + self.pointword = 'จุด' + + self.CURRENCY_FORMS = { + 'THB': (('บาท', 'บาท'), ('สตางค์', 'สตางค์')), + 'USD': (('ดอลลาร์', 'ดอลลาร์'), ('เซนต์', 'เซนต์')), + 'EUR': (('ยูโร', 'ยูโร'), ('เซนต์', 'เซนต์')), + } + + self.high_numwords = [] + + self.mid_numwords = ['', 'สิบ', 'ร้อย', 'พัน', 'หมื่น', 'แสน', 'ล้าน'] + + self.low_numwords = [ + 'ศูนย์', 'หนึ่ง', 'สอง', 'สาม', 'สี่', + 'ห้า', 'หก', 'เจ็ด', 'แปด', 'เก้า' + ] + + def set_high_numwords(self, high_numwords): + pass + + def set_mid_numwords(self, mid_numwords): + pass + + def splitnum(self, six_num): + length = len(six_num) > 1 + word_num = '' + + for index, num in enumerate(map(int, six_num)): + if num: + if index: + word_num = self.mid_numwords[index] + word_num + + if length and num == 1 and index == 0: + word_num += 'เอ็ด' + elif index == 1 and num == 2: + word_num = 'ยี่' + word_num + elif index != 1 or num != 1: + word_num = self.low_numwords[num] + word_num + + elif num == 0 and index == 0 and length == 0: + word_num = self.low_numwords[0] + + return word_num + + def split_six(self, num_txt): + result = splitbyx(num_txt, 6, format_int=False) + result = list(result)[::-1] + number_list = [] + for i in result: + number_list.append(i[::-1]) + return number_list + + def add_text_million(self, word_num): + result = '' + + for index, t in enumerate(reversed(word_num)): + if index == 0: + result = t + else: + result = result + 'ล้าน' + t + + return result + + def round_2_decimal(self, number): + integer, cents, negative = parse_currency_parts( + number, is_int_with_cents=False + ) + integer = '{}'.format(integer) + cents = '{}'.format(cents) + + if len(cents) < 2: + add_zero = 2 - len(cents) + cents = ('0' * add_zero) + cents + + text_num = integer + '.' + cents + + return text_num, negative + + def left_num_to_text(self, number): + + left_num_list = self.split_six(number) + + left_text_list = [] + for i in left_num_list: + left_text_list.append(self.splitnum(i)) + + left_text = self.add_text_million(left_text_list) + return left_text + + def to_cardinal(self, number): + negative = number < 0 + + pre, post = self.float2tuple(number) + precision = self.precision + pre = '{}'.format(pre) + post = '{}'.format(post) + + if negative: + pre = pre.lstrip('-') + + if len(post) < precision: + add_zero = precision - len(post) + post = ('0' * add_zero) + post + + result = self.left_num_to_text(pre) + + right_text = '' + if not post == '0': + for i in map(int, post): + right_text = right_text + self.low_numwords[i] + result = result + 'จุด' + right_text + + if negative: + result = 'ติดลบ' + result + + return result + + def to_ordinal(self, number): + return self.to_cardinal(number) + + def to_currency(self, number, currency='THB'): + + number, negative = self.round_2_decimal(number) + + split_num = number.split('.') + + left_num = split_num[0] + left_text = self.left_num_to_text(left_num) + + right_num = split_num[1] + right_text = self.splitnum(right_num[::-1].rstrip('0')) + + try: + cr1, cr2 = self.CURRENCY_FORMS[currency] + + except KeyError: + raise NotImplementedError( + 'Currency code "%s" not implemented for "%s"' % + (currency, self.__class__.__name__)) + + if right_num == '00': + if currency == 'THB': + result = left_text + cr1[0] + 'ถ้วน' + else: + result = left_text + cr1[0] + else: + if left_num == '0': + result = right_text + cr2[0] + else: + result = left_text + cr1[0] + right_text + cr2[0] + + if negative: + result = self.negword + result + + return result diff --git a/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_TR.py b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_TR.py new file mode 100644 index 0000000000000000000000000000000000000000..2f20dd66960d912c3720df6bc7d739c10cad56bf --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_TR.py @@ -0,0 +1,856 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2003, Taro Ogawa. All Rights Reserved. +# Copyright (c) 2013, Savoir-faire Linux inc. All Rights Reserved. +# Copyright (c) 2017, Tufan Kaynak, Framras. All Rights Reserved. + +# This library 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. +# This library 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 along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301 USA + +from __future__ import unicode_literals + +from .base import Num2Word_Base + + +class Num2Word_TR(Num2Word_Base): + def __init__(self): + self.precision = 2 + self.negword = u"eksi" + self.pointword = u"virgül" + self.CURRENCY_UNIT = u"lira" + self.CURRENCY_SUBUNIT = u"kuruş" + self.errmsg_nonnum = u"Sadece sayılar yazıya çevrilebilir." + self.errmsg_floatord = u"Tam sayı olmayan {} sıralamada kullanılamaz." + self.errmsg_negord = u"Pozitif olmayan {} sıralamada kullanılamaz." + self.errmsg_toobig = u"abs({}) sayı yazıya çevirmek için çok büyük. " \ + u"Yazıya çevrilebilecek en büyük rakam {}." + self.exclude_title = [] + self.DECIMAL_SIGN = "," + self.ORDINAL_SIGN = "." + self.ZERO = u"sıfır" + self.CARDINAL_ONES = { + "1": u"bir", + "2": u"iki", + "3": u"üç", + "4": u"dört", + "5": u"beş", + "6": u"altı", + "7": u"yedi", + "8": u"sekiz", + "9": u"dokuz" + } + self.ORDINAL_ONES = { + "1": u"birinci", + "2": u"ikinci", + "3": u"üçüncü", + "4": u"dördüncü", + "5": u"beşinci", + "6": u"altıncı", + "7": u"yedinci", + "8": u"sekizinci", + "9": u"dokuzuncu" + } + self.CARDINAL_TENS = { + "1": u"on", + "2": u"yirmi", + "3": u"otuz", + "4": u"kırk", + "5": u"elli", + "6": u"altmış", + "7": u"yetmiş", + "8": u"seksen", + "9": u"doksan" + } + self.ORDINAL_TENS = { + "1": u"onuncu", + "2": u"yirminci", + "3": u"otuzuncu", + "4": u"kırkıncı", + "5": u"ellinci", + "6": u"altmışıncı", + "7": u"yetmişinci", + "8": u"sekseninci", + "9": u"doksanıncı" + } + self.HUNDREDS = { + "2": u"iki", + "3": u"üç", + "4": u"dört", + "5": u"beş", + "6": u"altı", + "7": u"yedi", + "8": u"sekiz", + "9": u"dokuz" + } + self.CARDINAL_HUNDRED = (u"yüz",) + self.ORDINAL_HUNDRED = (u"yüzüncü",) + self.CARDINAL_TRIPLETS = { + 1: u"bin", + 2: u"milyon", + 3: u"milyar", + 4: u"trilyon", + 5: u"katrilyon", + 6: u"kentilyon" + } + self.ORDINAL_TRIPLETS = { + 1: u"bininci", + 2: u"milyonuncu", + 3: u"milyarıncı", + 4: u"trilyonuncu", + 5: u"katrilyonuncu", + 6: u"kentilyon" + } + self.MAXVAL = (10 ** ((len(self.CARDINAL_TRIPLETS) + 1) * 3)) - 1 + + self.integers_to_read = [] + self.total_triplets_to_read = 0 + self.total_digits_outside_triplets = 0 + self.order_of_last_zero_digit = 0 + + def to_cardinal(self, value): + wrd = "" + is_cardinal = self.verify_cardinal(value) + if not is_cardinal: + return wrd + + if not int(value) == value: + return self.to_cardinal_float(value) + + if str(value).startswith("-"): + pre_word, value = self.negword, float(str(value)[1:]) + else: + pre_word, value = "", float(value) + + self.to_splitnum(value) + + if self.order_of_last_zero_digit >= len(self.integers_to_read[0]): + # number like 00 and all 0s and even more, raise error + return "%s%s" % (pre_word, wrd) + + if self.total_triplets_to_read == 1: + if self.total_digits_outside_triplets == 2: + if self.order_of_last_zero_digit == 1: + # number like x0, read cardinal x0 and return + wrd += self.CARDINAL_TENS.get( + self.integers_to_read[0][0], "" + ) + return "%s%s" % (pre_word, wrd) + if self.order_of_last_zero_digit == 0: + # number like xy, read cardinal xy and return + wrd += self.CARDINAL_TENS.get( + self.integers_to_read[0][0], "" + ) + wrd += self.CARDINAL_ONES.get( + self.integers_to_read[0][1], "" + ) + return "%s%s" % (pre_word, wrd) + + if self.total_digits_outside_triplets == 1: + if self.order_of_last_zero_digit == 0: + # number like x, read cardinal x and return + wrd += self.CARDINAL_ONES.get( + self.integers_to_read[0][0], "" + ) + if self.integers_to_read[0][0] == "0": + return self.ZERO + return "%s%s" % (pre_word, wrd) + + if self.total_digits_outside_triplets == 0: + if self.order_of_last_zero_digit == 2: + # number like x00, read cardinal x00 and return + wrd += self.HUNDREDS.get( + self.integers_to_read[0][0], "" + ) + wrd += self.CARDINAL_HUNDRED[0] + return "%s%s" % (pre_word, wrd) + if self.order_of_last_zero_digit == 1: + # number like xy0, read cardinal xy0 and return + wrd += self.HUNDREDS.get( + self.integers_to_read[0][0], "" + ) + wrd += self.CARDINAL_HUNDRED[0] + wrd += self.CARDINAL_TENS.get( + self.integers_to_read[0][1], "" + ) + return "%s%s" % (pre_word, wrd) + if self.order_of_last_zero_digit == 0: + # number like xyz, read cardinal xyz and return + wrd += self.HUNDREDS.get( + self.integers_to_read[0][0], "" + ) + wrd += self.CARDINAL_HUNDRED[0] + wrd += self.CARDINAL_TENS.get( + self.integers_to_read[0][1], "" + ) + wrd += self.CARDINAL_ONES.get( + self.integers_to_read[0][2], "" + ) + return "%s%s" % (pre_word, wrd) + + if self.total_triplets_to_read >= 2: + if self.total_digits_outside_triplets == 2: + if self.order_of_last_zero_digit == len( + self.integers_to_read[0]) - 1: + # number like x0 and all 0s, read cardinal x0 0..0 + # and return + wrd += self.CARDINAL_TENS.get( + self.integers_to_read[0][0], "" + ) + wrd += self.CARDINAL_TRIPLETS[ + self.total_triplets_to_read - 1 + ] + return "%s%s" % (pre_word, wrd) + if self.order_of_last_zero_digit == len( + self.integers_to_read[0]) - 2: + # number like xy and all 0s, read cardinal xy 0..0 + # and return + wrd += self.CARDINAL_TENS.get( + self.integers_to_read[0][0], "" + ) + wrd += self.CARDINAL_ONES.get( + self.integers_to_read[0][1], "" + ) + wrd += self.CARDINAL_TRIPLETS[ + self.total_triplets_to_read - 1 + ] + return "%s%s" % (pre_word, wrd) + if self.order_of_last_zero_digit < len( + self.integers_to_read[0]) - 2: + # number like xy and others, read cardinal xy n..n + # and return + wrd += self.CARDINAL_TENS.get( + self.integers_to_read[0][0], "" + ) + wrd += self.CARDINAL_ONES.get( + self.integers_to_read[0][1], "" + ) + wrd += self.CARDINAL_TRIPLETS[ + self.total_triplets_to_read - 1 + ] + + if self.total_digits_outside_triplets == 1: + if self.order_of_last_zero_digit == len( + self.integers_to_read[0]) - 1: + # number like x and all 0s, read cardinal x 0..0 + # and return + if not (self.total_triplets_to_read == 2 and + self.integers_to_read[0][0] == "1"): + wrd += self.CARDINAL_ONES.get( + self.integers_to_read[0][0], "" + ) + wrd += self.CARDINAL_TRIPLETS[ + self.total_triplets_to_read - 1 + ] + return "%s%s" % (pre_word, wrd) + if self.order_of_last_zero_digit < len( + self.integers_to_read[0]) - 1: + # number like x and others, read cardinal x n..n + # and return + if not (self.total_triplets_to_read == 2 and + self.integers_to_read[0][0] == "1"): + wrd += self.CARDINAL_ONES.get( + self.integers_to_read[0][0], "" + ) + wrd += self.CARDINAL_TRIPLETS[ + self.total_triplets_to_read - 1 + ] + + if self.total_digits_outside_triplets == 0: + if self.order_of_last_zero_digit == len( + self.integers_to_read[0]) - 1: + # number like x00 and all 0s, read cardinal x00 0..0 + # and return + wrd += self.HUNDREDS.get(self.integers_to_read[0][0], "") + wrd += self.CARDINAL_HUNDRED[0] + wrd += self.CARDINAL_TRIPLETS[ + self.total_triplets_to_read - 1 + ] + return "%s%s" % (pre_word, wrd) + if self.order_of_last_zero_digit == len( + self.integers_to_read[0]) - 2: + # number like xy0 and all 0s, read cardinal xy0 0..0 + # and return + wrd += self.HUNDREDS.get( + self.integers_to_read[0][0], "" + ) + wrd += self.CARDINAL_HUNDRED[0] + wrd += self.CARDINAL_TENS.get( + self.integers_to_read[0][1], "" + ) + wrd += self.CARDINAL_TRIPLETS[ + self.total_triplets_to_read - 1 + ] + return "%s%s" % (pre_word, wrd) + if self.order_of_last_zero_digit == len( + self.integers_to_read[0]) - 3: + # number like xyz and all 0s, read cardinal xyz 0..0 + # and return + wrd += self.HUNDREDS.get(self.integers_to_read[0][0], "") + wrd += self.CARDINAL_HUNDRED[0] + wrd += self.CARDINAL_TENS.get( + self.integers_to_read[0][1], "" + ) + wrd += self.CARDINAL_ONES.get( + self.integers_to_read[0][2], "" + ) + wrd += self.CARDINAL_TRIPLETS[ + self.total_triplets_to_read - 1 + ] + return "%s%s" % (pre_word, wrd) + if self.order_of_last_zero_digit < len( + self.integers_to_read[0]) - 3: + # number like xyz and all others, read cardinal xyz n..n + wrd += self.HUNDREDS.get(self.integers_to_read[0][0], "") + wrd += self.CARDINAL_HUNDRED[0] + wrd += self.CARDINAL_TENS.get( + self.integers_to_read[0][1], "" + ) + if not (self.total_triplets_to_read == 2 and + self.integers_to_read[0][2] == "1"): + wrd += self.CARDINAL_ONES.get( + self.integers_to_read[0][2], "" + ) + wrd += self.CARDINAL_TRIPLETS[ + self.total_triplets_to_read - 1 + ] + + for i in list(range(self.total_triplets_to_read - 1, 0, -1)): + reading_triplet_order = self.total_triplets_to_read - i + if self.total_digits_outside_triplets == 0: + last_read_digit_order = reading_triplet_order * 3 + else: + last_read_digit_order = (reading_triplet_order - 1) * 3 +\ + self.total_digits_outside_triplets + + if not self.integers_to_read[0][ + last_read_digit_order: last_read_digit_order + 3 + ] == "000": + if not self.integers_to_read[0][ + last_read_digit_order + ] == "0": + wrd += self.HUNDREDS.get( + self.integers_to_read[0][last_read_digit_order], "" + ) + if self.order_of_last_zero_digit == len( + self.integers_to_read[0]) - ( + last_read_digit_order) - 1: + if i == 1: + wrd += self.CARDINAL_HUNDRED[0] + return "%s%s" % (pre_word, wrd) + elif i > 1: + wrd += self.CARDINAL_HUNDRED[0] + wrd += self.CARDINAL_TRIPLETS[i - 1] + return "%s%s" % (pre_word, wrd) + else: + wrd += self.CARDINAL_HUNDRED[0] + + if not self.integers_to_read[0][ + last_read_digit_order + 1] == "0": + if self.order_of_last_zero_digit == len( + self.integers_to_read[0]) - ( + last_read_digit_order) - 2: + if i == 1: + wrd += self.CARDINAL_TENS.get( + self.integers_to_read[0][ + last_read_digit_order + 1], "" + ) + return "%s%s" % (pre_word, wrd) + elif i > 1: + wrd += self.CARDINAL_TENS.get( + self.integers_to_read[0][ + last_read_digit_order + 1], "" + ) + wrd += self.CARDINAL_TRIPLETS[i - 1] + return "%s%s" % (pre_word, wrd) + else: + wrd += self.CARDINAL_TENS.get( + self.integers_to_read[0][ + last_read_digit_order + 1], "" + ) + + if not self.integers_to_read[0][ + last_read_digit_order + 2] == "0": + if self.order_of_last_zero_digit == len( + self.integers_to_read[0]) - ( + last_read_digit_order) - 3: + if i == 1: + wrd += self.CARDINAL_ONES.get( + self.integers_to_read[0][ + last_read_digit_order + 2], "" + ) + return "%s%s" % (pre_word, wrd) + if i == 2: + if not self.integers_to_read[0][ + last_read_digit_order: + last_read_digit_order + 2 + ] == "00": + wrd += self.CARDINAL_ONES.get( + self.integers_to_read[0][ + last_read_digit_order + 2], "" + ) + elif not self.integers_to_read[0][ + last_read_digit_order + 2] == "1": + wrd += self.CARDINAL_ONES.get( + self.integers_to_read[0][ + last_read_digit_order + 2], "" + ) + wrd += self.CARDINAL_TRIPLETS[i - 1] + return "%s%s" % (pre_word, wrd) + if i > 2: + wrd += self.CARDINAL_ONES.get( + self.integers_to_read[0][ + last_read_digit_order + 2], "" + ) + wrd += self.CARDINAL_TRIPLETS[i - 1] + return "%s%s" % (pre_word, wrd) + else: + if not self.integers_to_read[0][ + last_read_digit_order: + last_read_digit_order + 2 + ] == "00": + wrd += self.CARDINAL_ONES.get( + self.integers_to_read[0][ + last_read_digit_order + 2], "" + ) + else: + if i == 2: + if not self.integers_to_read[0][ + last_read_digit_order: + last_read_digit_order + 2 + ] == "00": + wrd += self.CARDINAL_ONES.get( + self.integers_to_read[0][ + last_read_digit_order + 2], "" + ) + elif not self.integers_to_read[0][ + last_read_digit_order + 2 + ] == "1": + wrd += self.CARDINAL_ONES.get( + self.integers_to_read[0][ + last_read_digit_order + 2], "" + ) + + wrd += self.CARDINAL_TRIPLETS[i - 1] + + return "%s%s" % (pre_word, wrd) + + def to_cardinal_float(self, value): + self.to_splitnum(value) + wrd = "" + wrd += self.pointword + if len(self.integers_to_read[1]) >= 1: + wrd += self.CARDINAL_TENS.get(self.integers_to_read[1][0], "") + + if len(self.integers_to_read[1]) == 2: + wrd += self.CARDINAL_ONES.get(self.integers_to_read[1][1], "") + + if self.integers_to_read[0] == "0": + wrd = self.ZERO + wrd + else: + wrd = self.to_cardinal(int(self.integers_to_read[0])) + wrd + return wrd + + def verify_cardinal(self, value): + iscardinal = True + try: + if not float(value) == value: + iscardinal = False + except (ValueError, TypeError): + raise TypeError(self.errmsg_nonnum) + if abs(value) >= self.MAXVAL: + raise OverflowError(self.errmsg_toobig.format(value, self.MAXVAL)) + return iscardinal + + def verify_ordinal(self, value): + isordinal = True + try: + if not int(value) == value: + isordinal = False + if not abs(value) == value: + raise TypeError(self.errmsg_negord.format(value)) + except (ValueError, TypeError): + raise TypeError(self.errmsg_nonnum) + if abs(value) >= self.MAXVAL: + raise OverflowError(self.errmsg_toobig.format(value, self.MAXVAL)) + return isordinal + + def to_ordinal(self, value): + wrd = "" + isordinal = self.verify_ordinal(value) + if isordinal: + self.to_splitnum(value) + + if self.order_of_last_zero_digit >= len(self.integers_to_read[0]): + # number like 00 and all 0s and even more, raise error + return wrd + + if self.total_triplets_to_read == 1: + if self.total_digits_outside_triplets == 2: + if self.order_of_last_zero_digit == 1: + # number like x0, read ordinal x0 and return + wrd += self.ORDINAL_TENS.get( + self.integers_to_read[0][0], "" + ) + return wrd + if self.order_of_last_zero_digit == 0: + # number like xy, read ordinal xy and return + wrd += self.CARDINAL_TENS.get( + self.integers_to_read[0][0], "" + ) + wrd += self.ORDINAL_ONES.get( + self.integers_to_read[0][1], "" + ) + return wrd + + if self.total_digits_outside_triplets == 1: + if self.order_of_last_zero_digit == 0: + # number like x, read ordinal x and return + wrd += self.ORDINAL_ONES.get( + self.integers_to_read[0][0], "" + ) + if self.integers_to_read[0][0] == "0": + return u"sıfırıncı" + return wrd + + if self.total_digits_outside_triplets == 0: + if self.order_of_last_zero_digit == 2: + # number like x00, read ordinal x00 and return + wrd += self.HUNDREDS.get( + self.integers_to_read[0][0], "" + ) + wrd += self.ORDINAL_HUNDRED[0] + return wrd + if self.order_of_last_zero_digit == 1: + # number like xy0, read ordinal xy0 and return + wrd += self.HUNDREDS.get( + self.integers_to_read[0][0], "" + ) + wrd += self.CARDINAL_HUNDRED[0] + wrd += self.ORDINAL_TENS.get( + self.integers_to_read[0][1], "" + ) + return wrd + if self.order_of_last_zero_digit == 0: + # number like xyz, read ordinal xyz and return + wrd += self.HUNDREDS.get( + self.integers_to_read[0][0], "" + ) + wrd += self.CARDINAL_HUNDRED[0] + wrd += self.CARDINAL_TENS.get( + self.integers_to_read[0][1], "" + ) + if not self.integers_to_read[0][2] == "0": + wrd += self.ORDINAL_ONES.get( + self.integers_to_read[0][2], "" + ) + return wrd + + if self.total_triplets_to_read >= 2: + if self.total_digits_outside_triplets == 2: + if self.order_of_last_zero_digit == len( + self.integers_to_read[0]) - 1: + # number like x0 and all 0s, read ordinal x0 0..0 + # and return + wrd += self.CARDINAL_TENS.get( + self.integers_to_read[0][0], "" + ) + wrd += self.ORDINAL_TRIPLETS[ + self.total_triplets_to_read - 1 + ] + return wrd + if self.order_of_last_zero_digit == len( + self.integers_to_read[0]) - 2: + # number like xy and all 0s, read ordinal xy 0..0 + # and return + wrd += self.CARDINAL_TENS.get( + self.integers_to_read[0][0], "" + ) + wrd += self.CARDINAL_ONES.get( + self.integers_to_read[0][1], "" + ) + wrd += self.ORDINAL_TRIPLETS[ + self.total_triplets_to_read - 1 + ] + return wrd + if self.order_of_last_zero_digit < len( + self.integers_to_read[0]) - 2: + # number like xy and others, read cardinal xy n..n + # and return + wrd += self.CARDINAL_TENS.get( + self.integers_to_read[0][0], "" + ) + wrd += self.CARDINAL_ONES.get( + self.integers_to_read[0][1], "" + ) + wrd += self.CARDINAL_TRIPLETS[ + self.total_triplets_to_read - 1 + ] + + if self.total_digits_outside_triplets == 1: + if self.order_of_last_zero_digit == len( + self.integers_to_read[0]) - 1: + # number like x and all 0s, read ordinal x 0..0 + # and return + if not (self.total_triplets_to_read == 2 and + self.integers_to_read[0][0] == "1"): + wrd += self.CARDINAL_ONES.get( + self.integers_to_read[0][0], "" + ) + wrd += self.ORDINAL_TRIPLETS[ + self.total_triplets_to_read - 1 + ] + return wrd + if self.order_of_last_zero_digit < len( + self.integers_to_read[0]) - 1: + # number like x and others, read cardinal x n..n + # and return + if not (self.total_triplets_to_read == 2 and + self.integers_to_read[0][0] == "1"): + wrd += self.CARDINAL_ONES.get( + self.integers_to_read[0][0], "" + ) + wrd += self.CARDINAL_TRIPLETS[ + self.total_triplets_to_read - 1 + ] + + if self.total_digits_outside_triplets == 0: + if self.order_of_last_zero_digit == len( + self.integers_to_read[0]) - 1: + # number like x00 and all 0s, read ordinal x00 0..0 + # and return + wrd += self.HUNDREDS.get( + self.integers_to_read[0][0], "" + ) + wrd += self.CARDINAL_HUNDRED[0] + wrd += self.ORDINAL_TRIPLETS[ + self.total_triplets_to_read - 1 + ] + return wrd + if self.order_of_last_zero_digit == len( + self.integers_to_read[0]) - 2: + # number like xy0 and all 0s, read ordinal xy0 0..0 + # and return + wrd += self.HUNDREDS.get( + self.integers_to_read[0][0], "" + ) + wrd += self.CARDINAL_HUNDRED[0] + wrd += self.CARDINAL_TENS.get( + self.integers_to_read[0][1], "" + ) + wrd += self.ORDINAL_TRIPLETS[ + self.total_triplets_to_read - 1 + ] + return wrd + if self.order_of_last_zero_digit == len( + self.integers_to_read[0]) - 3: + # number like xyz and all 0s, read ordinal xyz 0..0 + # and return + wrd += self.HUNDREDS.get( + self.integers_to_read[0][0], "" + ) + wrd += self.CARDINAL_HUNDRED[0] + wrd += self.CARDINAL_TENS.get( + self.integers_to_read[0][1], "" + ) + wrd += self.CARDINAL_ONES.get( + self.integers_to_read[0][2], "" + ) + wrd += self.ORDINAL_TRIPLETS[ + self.total_triplets_to_read - 1 + ] + return wrd + if self.order_of_last_zero_digit < len( + self.integers_to_read[0]) - 3: + # number like xyz and all others, read cardinal + # xyz n..n + wrd += self.HUNDREDS.get( + self.integers_to_read[0][0], "" + ) + wrd += self.CARDINAL_HUNDRED[0] + wrd += self.CARDINAL_TENS.get( + self.integers_to_read[0][1], "" + ) + if not (self.total_triplets_to_read == 2 and + self.integers_to_read[0][2] == "1"): + wrd += self.CARDINAL_ONES.get( + self.integers_to_read[0][2], "" + ) + wrd += self.CARDINAL_TRIPLETS[ + self.total_triplets_to_read - 1 + ] + + for i in list(range(self.total_triplets_to_read - 1, 0, -1)): + reading_triplet_order = self.total_triplets_to_read - i + if self.total_digits_outside_triplets == 0: + last_read_digit_order = reading_triplet_order * 3 + else: + last_read_digit_order = \ + (reading_triplet_order - 1) * 3 + \ + self.total_digits_outside_triplets + + if not self.integers_to_read[0][ + last_read_digit_order: last_read_digit_order + 3 + ] == "000": + if not self.integers_to_read[0][ + last_read_digit_order + ] == "0": + if not self.integers_to_read[0][ + last_read_digit_order + ] == "1": + wrd += self.CARDINAL_ONES.get( + self.integers_to_read[0][ + last_read_digit_order + ], "" + ) + if self.order_of_last_zero_digit == len( + self.integers_to_read[0]) - ( + last_read_digit_order) - 1: + if i == 1: + wrd += self.ORDINAL_HUNDRED[0] + return wrd + elif i > 1: + wrd += self.CARDINAL_HUNDRED[0] + wrd += self.ORDINAL_TRIPLETS[i - 1] + return wrd + else: + wrd += self.CARDINAL_HUNDRED[0] + + if not self.integers_to_read[0][ + last_read_digit_order + 1 + ] == "0": + if self.order_of_last_zero_digit == len( + self.integers_to_read[0]) - ( + last_read_digit_order) - 2: + if i == 1: + wrd += self.ORDINAL_TENS.get( + self.integers_to_read[0][ + last_read_digit_order + 1], "" + ) + return wrd + elif i > 1: + wrd += self.CARDINAL_TENS.get( + self.integers_to_read[0][ + last_read_digit_order + 1], "" + ) + wrd += self.ORDINAL_TRIPLETS[i - 1] + return wrd + else: + wrd += self.CARDINAL_TENS.get( + self.integers_to_read[0][ + last_read_digit_order + 1], "" + ) + + if not self.integers_to_read[0][ + last_read_digit_order + 2 + ] == "0": + if self.order_of_last_zero_digit == len( + self.integers_to_read[0]) - ( + last_read_digit_order) - 3: + if i == 1: + wrd += self.ORDINAL_ONES.get( + self.integers_to_read[0][ + last_read_digit_order + 2], "" + ) + return wrd + if i == 2: + if not self.integers_to_read[0][ + last_read_digit_order: + last_read_digit_order + 2] == "00": + wrd += self.CARDINAL_ONES.get( + self.integers_to_read[0][ + last_read_digit_order + 2], "" + ) + elif not self.integers_to_read[0][ + last_read_digit_order + 2 + ] == "1": + wrd += self.CARDINAL_ONES.get( + self.integers_to_read[0][ + last_read_digit_order + 2], "" + ) + wrd += self.ORDINAL_TRIPLETS[i - 1] + return wrd + if i > 2: + wrd += self.CARDINAL_ONES.get( + self.integers_to_read[0][ + last_read_digit_order + 2], "" + ) + wrd += self.ORDINAL_TRIPLETS[i - 1] + return wrd + else: + if not self.integers_to_read[0][ + last_read_digit_order: + last_read_digit_order + 2] == "00": + wrd += self.CARDINAL_ONES.get( + self.integers_to_read[0][ + last_read_digit_order + 2], "" + ) + else: + if not self.integers_to_read[0][ + last_read_digit_order: + last_read_digit_order + 2] == "00": + wrd += self.CARDINAL_ONES.get( + self.integers_to_read[0][ + last_read_digit_order + 2], "" + ) + elif not self.integers_to_read[0][ + last_read_digit_order + 2] == "1": + wrd += self.CARDINAL_ONES.get( + self.integers_to_read[0][ + last_read_digit_order + 2], "" + ) + + wrd += self.CARDINAL_TRIPLETS[i - 1] + + return wrd + + def to_ordinal_num(self, value): + self.verify_ordinal(value) + return "%s%s" % (value, self.to_ordinal(value)[-4:]) + + def to_splitnum(self, val): + float_digits = str(int(val * 10 ** self.precision)) + if not int(val) == 0: + self.integers_to_read = [ + str(int(val)), + float_digits[len(float_digits) - self.precision:] + ] + else: + self.integers_to_read = [ + "0", + "0" * (self.precision - len(float_digits)) + + float_digits[len(float_digits) - self.precision:] + ] + if len(self.integers_to_read[0]) % 3 > 0: + self.total_triplets_to_read = (len(self.integers_to_read[0]) // 3)\ + + 1 + elif len(self.integers_to_read[0]) % 3 == 0: + self.total_triplets_to_read = len(self.integers_to_read[0]) // 3 + self.total_digits_outside_triplets = len(self.integers_to_read[0]) % 3 + + okunacak = list(self.integers_to_read[0][::-1]) + self.order_of_last_zero_digit = 0 + found = 0 + for i in range(len(okunacak) - 1): + if int(okunacak[i]) == 0 and found == 0: + self.order_of_last_zero_digit = i + 1 + else: + found = 1 + + def to_currency(self, value): + if int(value) == 0: + return u"bedelsiz" + valueparts = self.to_cardinal(value).split(self.pointword) + if len(valueparts) == 1: + return valueparts[0] + self.CURRENCY_UNIT + if len(valueparts) == 2: + return self.CURRENCY_UNIT.join(valueparts) + \ + self.CURRENCY_SUBUNIT diff --git a/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_UK.py b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_UK.py new file mode 100644 index 0000000000000000000000000000000000000000..188d7ced78396901bced789b18765dfb781a7bd0 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_UK.py @@ -0,0 +1,1067 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2003, Taro Ogawa. All Rights Reserved. +# Copyright (c) 2013, Savoir-faire Linux inc. All Rights Reserved. + +# This library 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. +# This library 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 along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301 USA + +from __future__ import unicode_literals + +from .base import Num2Word_Base +from .utils import get_digits, splitbyx + +ZERO = ('нуль',) + +ONES_FEMININE = { + 1: ('одна', "однієї", "одній", "одну", "однією", "одній"), + 2: ('дві', "двох", "двом", "дві", "двома", "двох"), + 3: ('три', "трьох", "трьом", "три", "трьома", "трьох"), + 4: ('чотири', "чотирьох", "чотирьом", "чотири", "чотирма", "чотирьох"), + 5: ('п\'ять', "п'яти", "п'яти", "п'ять", "п'ятьма", "п'яти"), + 6: ('шість', "шести", "шести", "шість", "шістьма", "шести"), + 7: ('сім', "семи", "семи", "сім", "сьома", "семи"), + 8: ('вісім', "восьми", "восьми", "вісім", "вісьма", "восьми"), + 9: ("дев'ять", "дев'яти", "дев'яти", "дев'ять", "дев'ятьма", "дев'яти"), +} + +ONES = { + 1: ('один', 'одного', "одному", "один", "одним", "одному"), + 2: ('два', 'двох', "двом", "два", "двома", "двох"), + 3: ('три', 'трьох', "трьом", "три", "трьома", "трьох"), + 4: ('чотири', 'чотирьох', "чотирьом", "чотири", "чотирма", "чотирьох"), + 5: ('п\'ять', "п'яти", "п'яти", "п'ять", "п'ятьма", "п'яти"), + 6: ('шість', 'шести', "шести", "шість", "шістьма", "шести"), + 7: ('сім', 'семи', "семи", "сім", "сьома", "семи"), + 8: ('вісім', 'восьми', "восьми", "вісім", "вісьма", "восьми"), + 9: ("дев'ять", "дев'яти", "дев'яти", "дев'ять", "дев'ятьма", "дев'яти"), +} + +ONES_ORDINALS = { + 1: ("перший", "одно"), + 2: ("другий", "двох"), + 3: ("третій", "трьох"), + 4: ("четвертий", "чотирьох"), + 5: ("п'ятий", "п'яти"), + 6: ("шостий", "шести"), + 7: ("сьомий", "семи"), + 8: ("восьмий", "восьми"), + 9: ("дев'ятий", "дев'яти"), + 10: ("десятий", "десяти"), + 11: ("одинадцятий", "одинадцяти"), + 12: ("дванадцятий", "дванадцяти"), + 13: ("тринадцятий", "тринадцяти"), + 14: ("чотирнадцятий", "чотирнадцяти"), + 15: ("п'ятнадцятий", "п'ятнадцяти"), + 16: ("шістнадцятий", "шістнадцяти"), + 17: ("сімнадцятий", "сімнадцяти"), + 18: ("вісімнадцятий", "вісімнадцяти"), + 19: ("дев'ятнадцятий", "дев'ятнадцяти"), +} +TENS = { + 0: ('десять', + 'десяти', + "десяти", + "десять", + "десятьма", + "десяти"), + 1: ('одинадцять', + 'одинадцяти', + "одинадцяти", + "одинадцять", + "одинадцятьма", + "одинадцяти"), + 2: ('дванадцять', + 'дванадцяти', + "дванадцяти", + "дванадцять", + "дванадцятьма", + "дванадцяти"), + 3: ('тринадцять', + 'тринадцяти', + "тринадцяти", + "тринадцять", + "тринадцятьма", + "тринадцяти"), + 4: ('чотирнадцять', + 'чотирнадцяти', + "чотирнадцяти", + "чотирнадцять", + "чотирнадцятьма", + "чотирнадцяти"), + 5: ("п'ятнадцять", + "п'ятнадцяти", + "п'ятнадцяти", + "п'ятнадцять", + "п'ятнадцятьма", + "п'ятнадцяти"), + 6: ('шістнадцять', + 'шістнадцяти', + "шістнадцяти", + "шістнадцять", + "шістнадцятьма", + "шістнадцяти"), + 7: ('сімнадцять', + 'сімнадцяти', + "сімнадцяти", + "сімнадцять", + "сімнадцятьма", + "сімнадцяти"), + 8: ('вісімнадцять', + 'вісімнадцяти', + "вісімнадцяти", + "вісімнадцять", + "вісімнадцятьма", + "вісімнадцяти"), + 9: ("дев'ятнадцять", + "дев'ятнадцяти", + "дев'ятнадцяти", + "дев'ятнадцять", + "дев'ятнадцятьма", + "дев'ятнадцяти"), +} + +TWENTIES = { + 2: ('двадцять', + "двадцяти", + "двадцяти", + "двадцять", + "двадцятьма", + "двадцяти"), + 3: ('тридцять', + "тридцяти", + "тридцяти", + "тридцять", + "тридцятьма", + "тридцяти"), + 4: ('сорок', + "сорока", + "сорока", + "сорок", + "сорока", + "сорока"), + 5: ('п\'ятдесят', + "п'ятдесяти", + "п'ятдесяти", + "п'ятдесят", + "п'ятдесятьма", + "п'ятдесяти"), + 6: ('шістдесят', + "шістдесяти", + "шістдесяти", + "шістдесят", + "шістдесятьма", + "шістдесяти"), + 7: ('сімдесят', + "сімдесяти", + "сімдесяти", + "сімдесят", + "сімдесятьма", + "сімдесяти"), + 8: ('вісімдесят', + "вісімдесяти", + "вісімдесяти", + "вісімдесят", + "вісімдесятьма", + "вісімдесяти"), + 9: ('дев\'яносто', + "дев'яноста", + "дев'яноста", + "дев'яносто", + "дев'яностами", + "дев'яноста"), +} + +TWENTIES_ORDINALS = { + 2: ("двадцятий", "двадцяти"), + 3: ("тридцятий", "тридцяти"), + 4: ("сороковий", "сорока"), + 5: ("п'ятдесятий", "п'ятдесяти"), + 6: ("шістдесятий", "шістдесяти"), + 7: ("сімдесятий", "сімдесяти"), + 8: ("вісімдесятий", "вісімдесяти"), + 9: ("дев'яностий", "дев'яности"), +} + +HUNDREDS = { + 1: ('сто', + "ста", + "ста", + "сто", + "стами", + "стах"), + 2: ('двісті', + "двохста", + "двомстам", + "двісті", + "двомастами", + "двохстах"), + 3: ('триста', + "трьохста", + "трьомстам", + "триста", + "трьомастами", + "трьохстах"), + 4: ('чотириста', + "чотирьохста", + "чотирьомстам", + "чотириста", + "чотирмастами", + "чотирьохстах"), + 5: ('п\'ятсот', + "п'ятиста", + "п'ятистам", + "п'ятсот", + "п'ятьмастами", + "п'ятистах"), + 6: ('шістсот', + "шестиста", + "шестистам", + "шістсот", + "шістьмастами", + "шестистах"), + 7: ('сімсот', + "семиста", + "семистам", + "сімсот", + "сьомастами", + "семистах"), + 8: ('вісімсот', + "восьмиста", + "восьмистам", + "вісімсот", + "восьмастами", + "восьмистах"), + 9: ("дев'ятсот", + "дев'ятиста", + "дев'ятистам", + "дев'ятсот", + "дев'ятьмастами", + "дев'ятистах"), +} + +HUNDREDS_ORDINALS = { + 1: ("сотий", "сто"), + 2: ("двохсотий", "двохсот"), + 3: ("трьохсотий", "трьохсот"), + 4: ("чотирьохсотий", "чотирьохсот"), + 5: ("п'ятисотий", "п'ятсот"), + 6: ("шестисотий", "шістсот"), + 7: ("семисотий", "сімсот"), + 8: ("восьмисотий", "вісімсот"), + 9: ("дев'ятисотий", "дев'ятсот"), +} + +THOUSANDS = { + # 10^3 + 1: (('тисяча', 'тисячі', 'тисяч'), + ('тисячи', 'тисяч', 'тисяч'), + ('тисячі', 'тисячам', 'тисячам'), + ('тисячу', 'тисячі', 'тисяч'), + ('тисячею', 'тисячами', 'тисячами'), + ('тисячі', 'тисячах', 'тисячах'),), + # 10^6 + 2: (('мільйон', 'мільйони', 'мільйонів'), + ('мільйона', 'мільйонів', 'мільйонів'), + ('мільйону', 'мільйонам', 'мільйонам'), + ('мільйон', 'мільйони', 'мільйонів'), + ('мільйоном', 'мільйонами', 'мільйонів'), + ('мільйоні', 'мільйонах', 'мільйонах'),), + # 10^9 + 3: (('мільярд', 'мільярди', 'мільярдів'), + ('мільярда', 'мільярдів', 'мільярдів'), + ('мільярду', 'мільярдам', 'мільярдам'), + ('мільярд', 'мільярди', 'мільярдів'), + ('мільярдом', 'мільярдами', 'мільярдів'), + ('мільярді', 'мільярдах', 'мільярдах'),), + # 10^12 + 4: (('трильйон', 'трильйони', 'трильйонів'), + ('трильйона', 'трильйонів', 'трильйонів'), + ('трильйону', 'трильйонам', 'трильйонам'), + ('трильйон', 'трильйони', 'трильйонів'), + ('трильйоном', 'трильйонами', 'трильйонів'), + ('трильйоні', 'трильйонах', 'трильйонах'),), + # 10^15 + 5: (('квадрильйон', 'квадрильйони', 'квадрильйонів'), + ('квадрильйона', 'квадрильйонів', 'квадрильйонів'), + ('квадрильйону', 'квадрильйонам', 'квадрильйонам'), + ('квадрильйон', 'квадрильйони', 'квадрильйонів'), + ('квадрильйоном', 'квадрильйонами', 'квадрильйонів'), + ('квадрильйоні', 'квадрильйонах', 'квадрильйонах'),), + # 10^18 + 6: (('квінтильйон', 'квінтильйони', 'квінтильйонів'), + ('квінтильйона', 'квінтильйонів', 'квінтильйонів'), + ('квінтильйону', 'квінтильйонам', 'квінтильйонам'), + ('квінтильйон', 'квінтильйони', 'квінтильйонів'), + ('квінтильйоном', 'квінтильйонами', 'квінтильйонів'), + ('квінтильйоні', 'квінтильйонах', 'квінтильйонах'),), + # 10^21 + 7: (('секстильйон', 'секстильйони', 'секстильйонів'), + ('секстильйона', 'секстильйонів', 'секстильйонів'), + ('секстильйону', 'секстильйонам', 'секстильйонам'), + ('секстильйон', 'секстильйони', 'секстильйонів'), + ('секстильйоном', 'секстильйонами', 'секстильйонів'), + ('секстильйоні', 'секстильйонах', 'секстильйонах'),), + # 10^24 + 8: (('септильйон', 'септильйони', 'септильйонів'), + ('септильйона', 'септильйонів', 'септильйонів'), + ('септильйону', 'септильйонам', 'септильйонам'), + ('септильйон', 'септильйони', 'септильйонів'), + ('септильйоном', 'септильйонами', 'септильйонів'), + ('септильйоні', 'септильйонах', 'септильйонах'),), + # 10^27 + 9: (('октильйон', 'октильйони', 'октильйонів'), + ('октильйона', 'октильйонів', 'октильйонів'), + ('октильйону', 'октильйонам', 'октильйонам'), + ('октильйон', 'октильйони', 'октильйонів'), + ('октильйоном', 'октильйонами', 'октильйонів'), + ('октильйоні', 'октильйонах', 'октильйонах'),), + # 10^30 + 10: (('нонільйон', 'нонільйони', 'нонільйонів'), + ('нонільйона', 'нонільйонів', 'нонільйонів'), + ('нонільйону', 'нонільйонам', 'нонільйонам'), + ('нонільйон', 'нонільйони', 'нонільйонів'), + ('нонільйоном', 'нонільйонами', 'нонільйонів'), + ('нонільйоні', 'нонільйонах', 'нонільйонах'),), +} + +prefixes_ordinal = { + 1: "тисячний", + 2: "мільйонний", + 3: "мільярдний", + 4: "трильйонний", + 5: "квадрильйонний", + 6: "квінтильйонний", + 7: "секстильйонний", + 8: "септильйонний", + 9: "октильйонний", + 10: "нонільйонний", +} + +FEMININE_MONEY = ('AOA', 'BAM', 'BDT', 'BWP', 'CZK', 'DKK', + 'ERN', 'HNL', 'HRK', 'IDR', 'INR', 'ISK', + 'JPY', 'KPW', 'KRW', 'LKR', 'MOP', 'MRU', + 'MUR', 'MVR', 'MWK', 'NGN', 'NIO', 'NOK', + 'NPR', 'PKR', 'SCR', 'SEK', 'STN', 'TRY', + 'WST', 'UAH', 'ZMW') +FEMININE_CENTS = ('ALL', 'BDT', 'BGN', 'BYN', 'GHS', 'HRK', + 'ILS', 'INR', 'NPR', 'OMR', 'OMR', 'PKR', + 'RSD', 'RUB', 'UAH') + +GENERIC_DOLLARS = ('долар', 'долари', 'доларів') +GENERIC_CENTS = ('цент', 'центи', 'центів') + + +class Num2Word_UK(Num2Word_Base): + CURRENCY_FORMS = { + 'AED': ( + ('дирхам', 'дирхами', 'дирхамів'), + ('філс', 'філси', 'філсів') + ), + 'AFN': ( + ('афгані', 'афгані', 'афгані'), + ('пул', 'пули', 'пулів') + ), + 'ALL': ( + ('лек', 'леки', 'леків'), + ('кіндарка', 'кіндарки', 'кіндарок') + ), + 'AMD': ( + ('драм', 'драми', 'драмів'), + ('лум', 'лум', 'лум') + ), + 'ANG': ( + ('гульден', 'гульдени', 'гульденів'), + GENERIC_CENTS + ), + 'AOA': ( + ('кванза', 'кванзи', 'кванз'), + ('сентимо', 'сентимо', 'сентимо') + ), + 'ARS': ( + ('песо', 'песо', 'песо'), + ('сентаво', 'сентаво', 'сентаво') + ), + 'AUD': (GENERIC_DOLLARS, GENERIC_CENTS), + 'AWG': ( + ('флорин', 'флорини', 'флоринів'), + GENERIC_CENTS + ), + 'AZN': ( + ('манат', 'манати', 'манатів'), + ('гяпік', 'гяпіки', 'гяпіків') + ), + 'BAM': ( + ('марка', 'марки', 'марок'), + ('фенінг', 'фенінги', 'фенінгів') + ), + 'BBD': (GENERIC_DOLLARS, GENERIC_CENTS), + 'BDT': ( + ('така', 'таки', 'так'), + ('пойша', 'пойші', 'пойш') + ), + 'BGN': ( + ('лев', 'леви', 'левів'), + ('стотинка', 'стотинки', 'стотинок') + ), + 'BHD': ( + ('динар', 'динари', 'динарів'), + ('філс', 'філси', 'філсів') + ), + 'BIF': ( + ('франк', 'франки', 'франків'), + ('сантим', 'сантими', 'сантимів') + ), + 'BMD': (GENERIC_DOLLARS, GENERIC_CENTS), + 'BND': (GENERIC_DOLLARS, GENERIC_CENTS), + 'BOB': ( + ('болівіано', 'болівіано', 'болівіано'), + ('сентаво', 'сентаво', 'сентаво') + ), + 'BRL': ( + ('реал', 'реали', 'реалів'), + ('сентаво', 'сентаво', 'сентаво') + ), + 'BSD': (GENERIC_DOLLARS, GENERIC_CENTS), + 'BTN': ( + ('нгултрум', 'нгултруми', 'нгултрумів'), + ('четрум', 'четруми', 'четрумів') + ), + 'BWP': ( + ('пула', 'пули', 'пул'), + ('тхебе', 'тхебе', 'тхебе') + ), + 'BYN': ( + ('рубель', 'рублі', 'рублів'), + ('копійка', 'копійки', 'копійок') + ), + 'BZD': (GENERIC_DOLLARS, GENERIC_CENTS), + 'CAD': (GENERIC_DOLLARS, GENERIC_CENTS), + 'CDF': ( + ('франк', 'франки', 'франків'), + ('сантим', 'сантими', 'сантимів') + ), + 'CHF': ( + ('франк', 'франки', 'франків'), + ('сантим', 'сантими', 'сантимів') + ), + 'CLP': ( + ('песо', 'песо', 'песо'), + ('сентаво', 'сентаво', 'сентаво') + ), + 'CNY': ( + ('юань', 'юані', 'юанів'), + ('финь', 'фині', 'финів') + ), + 'COP': ( + ('песо', 'песо', 'песо'), + ('сентаво', 'сентаво', 'сентаво') + ), + 'CRC': ( + ('колон', 'колони', 'колонів'), + ('сентімо', 'сентімо', 'сентімо') + ), + 'CUC': ( + ('песо', 'песо', 'песо'), + ('сентаво', 'сентаво', 'сентаво') + ), + 'CUP': ( + ('песо', 'песо', 'песо'), + ('сентаво', 'сентаво', 'сентаво') + ), + 'CVE': ( + ('ескудо', 'ескудо', 'ескудо'), + ('сентаво', 'сентаво', 'сентаво') + ), + 'CZK': ( + ('крона', 'крони', 'крон'), + ('гелер', 'гелери', 'гелерів') + ), + 'DJF': ( + ('франк', 'франки', 'франків'), + ('сантим', 'сантими', 'сантимів') + ), + 'DKK': ( + ('крона', 'крони', 'крон'), + ('ере', 'ере', 'ере') + ), + 'DOP': ( + ('песо', 'песо', 'песо'), + ('сентаво', 'сентаво', 'сентаво') + ), + 'DZD': ( + ('динар', 'динари', 'динарів'), + ('сантим', 'сантими', 'сантимів') + ), + 'EGP': ( + ('фунт', 'фунти', 'фунтів'), + ('піастр', 'піастри', 'піастрів') + ), + 'ERN': ( + ('накфа', 'накфи', 'накф'), + GENERIC_CENTS + ), + 'ETB': ( + ('бир', 'бири', 'бирів'), + GENERIC_CENTS + ), + 'EUR': ( + ('євро', 'євро', 'євро'), + GENERIC_CENTS + ), + 'FJD': (GENERIC_DOLLARS, GENERIC_CENTS), + 'FKP': ( + ('фунт', 'фунти', 'фунтів'), + ('пенс', 'пенси', 'пенсів') + ), + 'GBP': ( + ('фунт', 'фунти', 'фунтів'), + ('пенс', 'пенси', 'пенсів') + ), + 'GEL': ( + ('ларі', 'ларі', 'ларі'), + ('тетрі', 'тетрі', 'тетрі') + ), + 'GHS': ( + ('седі', 'седі', 'седі'), + ('песева', 'песеви', 'песев') + ), + 'GIP': ( + ('фунт', 'фунти', 'фунтів'), + ('пенс', 'пенси', 'пенсів') + ), + 'GMD': ( + ('даласі', 'даласі', 'даласі'), + ('бутут', 'бутути', 'бутутів') + ), + 'GNF': ( + ('франк', 'франки', 'франків'), + ('сантим', 'сантими', 'сантимів') + ), + 'GTQ': ( + ('кетсаль', 'кетсалі', 'кетсалів'), + ('сентаво', 'сентаво', 'сентаво') + ), + 'GYD': (GENERIC_DOLLARS, GENERIC_CENTS), + 'HKD': (GENERIC_DOLLARS, GENERIC_CENTS), + 'HNL': ( + ('лемпіра', 'лемпіри', 'лемпір'), + ('сентаво', 'сентаво', 'сентаво') + ), + 'HRK': ( + ('куна', 'куни', 'кун'), + ('ліпа', 'ліпи', 'ліп') + ), + 'HTG': ( + ('гурд', 'гурди', 'гурдів'), + ('сантим', 'сантими', 'сантимів') + ), + 'HUF': ( + ('форинт', 'форинти', 'форинтів'), + ('філлер', 'філлери', 'філлерів') + ), + 'IDR': ( + ('рупія', 'рупії', 'рупій'), + GENERIC_CENTS + ), + 'ILS': ( + ('шекель', 'шекелі', 'шекелів'), + ('агора', 'агори', 'агор') + ), + 'INR': ( + ('рупія', 'рупії', 'рупій'), + ('пайса', 'пайси', 'пайс') + ), + 'IQD': ( + ('динар', 'динари', 'динарів'), + ('філс', 'філси', 'філсів') + ), + 'IRR': ( + ('ріал', 'ріали', 'ріалів'), + ('динар', 'динари', 'динарів') + ), + 'ISK': ( + ('крона', 'крони', 'крон'), + ('ейре', 'ейре', 'ейре') + ), + 'JMD': (GENERIC_DOLLARS, GENERIC_CENTS), + 'JOD': ( + ('динар', 'динари', 'динарів'), + ('філс', 'філси', 'філсів') + ), + 'JPY': ( + ('єна', 'єни', 'єн'), + ('сен', 'сен', 'сен') + ), + 'KES': ( + ('шилінг', 'шилінги', 'шилінгів'), + GENERIC_CENTS + ), + 'KGS': ( + ('сом', 'соми', 'сомів'), + ('тиїн', 'тиїни', 'тиїнів') + ), + 'KHR': ( + ('рієль', 'рієлі', 'рієлів'), + ('су', 'су', 'су') + ), + 'KMF': ( + ('франк', 'франки', 'франків'), + ('сантим', 'сантими', 'сантимів') + ), + 'KPW': ( + ('вона', 'вони', 'вон'), + ('чон', 'чони', 'чонів') + ), + 'KRW': ( + ('вона', 'вони', 'вон'), + ('джеон', 'джеони', 'джеонів') + ), + 'KWD': ( + ('динар', 'динари', 'динарів'), + ('філс', 'філси', 'філсів') + ), + 'KYD': (GENERIC_DOLLARS, GENERIC_CENTS), + 'KZT': ( + ('теньге', 'теньге', 'теньге'), + ('тиїн', 'тиїни', 'тиїнів')), + 'LAK': ( + ('кіп', 'кіпи', 'кіпів'), + ('ат', 'ати', 'атів') + ), + 'LBP': ( + ('фунт', 'фунти', 'фунтів'), + ('піастр', 'піастри', 'піастрів') + ), + 'LKR': ( + ('рупія', 'рупії', 'рупій'), + GENERIC_CENTS + ), + 'LRD': (GENERIC_DOLLARS, GENERIC_CENTS), + 'LSL': ( + ('лоті', 'малоті', 'малоті'), + ('сенте', 'лісенте', 'лісенте') + ), + 'LYD': ( + ('динар', 'динари', 'динарів'), + ('дирхам', 'дирхами', 'дирхамів') + ), + 'MAD': ( + ('дирхам', 'дирхами', 'дирхамів'), + ('сантим', 'сантими', 'сантимів') + ), + 'MDL': ( + ('лей', 'леї', 'леї'), + ('бан', 'бані', 'бані') + ), + 'MGA': ( + ('аріарі', 'аріарі', 'аріарі'), + ('іраймбіланья', 'іраймбіланья', 'іраймбіланья') + ), + 'MKD': ( + ('денар', 'денари', 'денарів'), + ('дені', 'дені', 'дені') + ), + 'MMK': ( + ('к\'ят', 'к\'ят', 'к\'ят'), + ('п\'я', 'п\'я', 'п\'я') + ), + 'MNT': ( + ('тугрик', 'тугрики', 'тугриків'), + ('мунгу', 'мунгу', 'мунгу') + ), + 'MOP': ( + ('патака', 'патакі', 'патак'), + ('аво', 'аво', 'аво') + ), + 'MRU': ( + ('угія', 'угії', 'угій'), + ('хумс', 'хумс', 'хумс') + ), + 'MUR': ( + ('рупія', 'рупії', 'рупій'), + GENERIC_CENTS + ), + 'MVR': ( + ('руфія', 'руфії', 'руфій'), + ('ларі', 'ларі', 'ларі') + ), + 'MWK': ( + ('квача', 'квачі', 'квач'), + ('тамбала', 'тамбала', 'тамбала') + ), + 'MXN': ( + ('песо', 'песо', 'песо'), + ('сентаво', 'сентаво', 'сентаво') + ), + 'MYR': ( + ('рингіт', 'рингіти', 'рингітів'), + GENERIC_CENTS + ), + 'MZN': ( + ('метікал', 'метікали', 'метікалів'), + ('сентаво', 'сентаво', 'сентаво') + ), + 'NAD': (GENERIC_DOLLARS, GENERIC_CENTS), + 'NGN': ( + ('найра', 'найри', 'найр'), + ('кобо', 'кобо', 'кобо') + ), + 'NIO': ( + ('кордоба', 'кордоби', 'кордоб'), + ('сентаво', 'сентаво', 'сентаво') + ), + 'NOK': ( + ('крона', 'крони', 'крон'), + ('ере', 'ере', 'ере') + ), + 'NPR': ( + ('рупія', 'рупії', 'рупій'), + ('пайса', 'пайси', 'пайс') + ), + 'NZD': (GENERIC_DOLLARS, GENERIC_CENTS), + 'OMR': ( + ('ріал', 'ріали', 'ріалів'), + ('байза', 'байзи', 'байз') + ), + 'PAB': ( + ('бальбоа', 'бальбоа', 'бальбоа'), + ('сентесімо', 'сентесімо', 'сентесімо') + ), + 'PEN': ( + ('соль', 'соль', 'соль'), + ('сентімо', 'сентімо', 'сентімо') + ), + 'PGK': ( + ('кіна', 'кіна', 'кіна'), + ('тойя', 'тойя', 'тойя') + ), + 'PHP': ( + ('песо', 'песо', 'песо'), + ('сентаво', 'сентаво', 'сентаво') + ), + 'PKR': ( + ('рупія', 'рупії', 'рупій'), + ('пайса', 'пайси', 'пайс') + ), + 'PLN': ( + ('злотий', 'злоті', 'злотих'), + ('грош', 'гроші', 'грошів') + ), + 'PYG': ( + ('гуарані', 'гуарані', 'гуарані'), + ('сентімо', 'сентімо', 'сентімо') + ), + 'QAR': ( + ('ріал', 'ріали', 'ріалів'), + ('дирхам', 'дирхами', 'дирхамів') + ), + 'RON': ( + ('лей', 'леї', 'леї'), + ('бан', 'бані', 'бані') + ), + 'RSD': ( + ('динар', 'динари', 'динарів'), + ('пара', 'пари', 'пар') + ), + 'RUB': ( + ('рубль', 'рублі', 'рублів'), + ('копійка', 'копійки', 'копійок') + ), + 'RWF': ( + ('франк', 'франки', 'франків'), + ('сантим', 'сантими', 'сантимів') + ), + 'SAR': ( + ('ріал', 'ріали', 'ріалів'), + ('халал', 'халали', 'халалів') + ), + 'SBD': (GENERIC_DOLLARS, GENERIC_CENTS), + 'SCR': ( + ('рупія', 'рупії', 'рупій'), + GENERIC_CENTS + ), + 'SDG': ( + ('фунт', 'фунти', 'фунтів'), + ('піастр', 'піастри', 'піастрів') + ), + 'SEK': ( + ('крона', 'крони', 'крон'), + ('ере', 'ере', 'ере') + ), + 'SGD': (GENERIC_DOLLARS, GENERIC_CENTS), + 'SHP': ( + ('фунт', 'фунти', 'фунтів'), + ('пенс', 'пенси', 'пенсів') + ), + 'SLL': ( + ('леоне', 'леоне', 'леоне'), + GENERIC_CENTS + ), + 'SOS': ( + ('шилінг', 'шилінги', 'шилінгів'), + GENERIC_CENTS + ), + 'SRD': (GENERIC_DOLLARS, GENERIC_CENTS), + 'SSP': ( + ('фунт', 'фунти', 'фунтів'), + ('піастр', 'піастри', 'піастрів') + ), + 'STN': ( + ('добра', 'добри', 'добр'), + ('сентімо', 'сентімо', 'сентімо') + ), + 'SYP': ( + ('фунт', 'фунти', 'фунтів'), + ('піастр', 'піастри', 'піастрів') + ), + 'SZL': ( + ('ліланґені', 'ліланґені', 'ліланґені'), + GENERIC_CENTS + ), + 'THB': ( + ('бат', 'бати', 'батів'), + ('сатанг', 'сатанги', 'сатангів') + ), + 'TJS': ( + ('сомоні', 'сомоні', 'сомоні'), + ('дірам', 'дірами', 'дірамів') + ), + 'TMT': ( + ('манат', 'манати', 'манатів'), + ('тенге', 'тенге', 'тенге') + ), + 'TND': ( + ('динар', 'динари', 'динарів'), + ('міллім', 'мілліми', 'міллімів') + ), + 'TOP': ( + ('паанга', 'паанга', 'паанга'), + ('сеніті', 'сеніті', 'сеніті') + ), + 'TRY': ( + ('ліра', 'ліри', 'лір'), + ('куруш', 'куруші', 'курушів') + ), + 'TTD': (GENERIC_DOLLARS, GENERIC_CENTS), + 'TWD': ( + ('новий долар', 'нові долари', 'нових доларів'), + GENERIC_CENTS + ), + 'TZS': ( + ('шилінг', 'шилінги', 'шилінгів'), + GENERIC_CENTS + ), + 'UAH': ( + ('гривня', 'гривні', 'гривень'), + ('копійка', 'копійки', 'копійок') + ), + 'UGX': ( + ('шилінг', 'шилінги', 'шилінгів'), + GENERIC_CENTS + ), + 'USD': (GENERIC_DOLLARS, GENERIC_CENTS), + 'UYU': ( + ('песо', 'песо', 'песо'), + ('сентесімо', 'сентесімо', 'сентесімо') + ), + 'UZS': ( + ('сум', 'суми', 'сумів'), + ('тиїн', 'тиїни', 'тиїнів') + ), + 'VND': ( + ('донг', 'донги', 'донгів'), + ('су', 'су', 'су') + ), + 'WST': ( + ('тала', 'тали', 'тал'), + ('сене', 'сене', 'сене') + ), + 'XCD': (GENERIC_DOLLARS, GENERIC_CENTS), + 'YER': ( + ('ріал', 'ріали', 'ріалів'), + ('філс', 'філси', 'філсів') + ), + 'ZAR': ( + ('ранд', 'ранди', 'рандів'), + GENERIC_CENTS + ), + 'ZMW': ( + ('квача', 'квачі', 'квач'), + ('нгве', 'нгве', 'нгве') + ), + } + + def setup(self): + self.negword = "мінус" + self.pointword = "кома" + + def to_cardinal(self, number, **kwargs): + if 'case' in kwargs: + case = kwargs['case'] + morphological_case = [ + "nominative", + "genitive", + "dative", + "accusative", + "instrumental", + "locative"].index(case) + else: + morphological_case = 0 + + if 'gender' in kwargs: + gender = kwargs['gender'] == 'feminine' + else: + gender = False + + n = str(number).replace(',', '.') + if '.' in n: + left, right = n.split('.') + leading_zero_count = len(right) - len(right.lstrip('0')) + right_side = self._int2word(int(right), gender, morphological_case) + decimal_part = ((ZERO[0] + ' ') * leading_zero_count + + right_side) + return u'%s %s %s' % ( + self._int2word(int(left), gender, morphological_case), + self.pointword, + decimal_part + ) + else: + return self._int2word(int(n), gender, morphological_case) + + def pluralize(self, n, forms): + if n % 100 < 10 or n % 100 > 20: + if n % 10 == 1: + form = 0 + elif 5 > n % 10 > 1: + form = 1 + else: + form = 2 + else: + form = 2 + + return forms[form] + + def _int2word(self, n, feminine=False, morphological_case=0): + if n < 0: + n_value = self._int2word(abs(n), feminine, morphological_case) + return ' '.join([self.negword, + n_value]) + + if n == 0: + return ZERO[0] + + words = [] + chunks = list(splitbyx(str(n), 3)) + i = len(chunks) + for x in chunks: + i -= 1 + + if x == 0: + continue + + n1, n2, n3 = get_digits(x) + + if n3 > 0: + words.append(HUNDREDS[n3][morphological_case]) + + if n2 > 1: + words.append(TWENTIES[n2][morphological_case]) + + if n2 == 1: + words.append(TENS[n1][morphological_case]) + # elif n1 > 0 and not (i > 0 and x == 1): + elif n1 > 0: + ones = ONES_FEMININE if i == 1 or feminine and i == 0 else ONES + words.append(ones[n1][morphological_case]) + + if i > 0: + thousands_val = THOUSANDS[i][morphological_case] + words.append(self.pluralize(x, thousands_val)) + + return ' '.join(words) + + def _money_verbose(self, number, currency): + return self._int2word(number, currency in FEMININE_MONEY) + + def _cents_verbose(self, number, currency): + return self._int2word(number, currency in FEMININE_CENTS) + + @staticmethod + def last_fragment_to_ordinal(last, words, level): + n1, n2, n3 = get_digits(last) + last_two = n2*10+n1 + if last_two == 0: + words.append(HUNDREDS_ORDINALS[n3][level]) + elif level == 1 and last == 1: + return + elif last_two < 20: + if level == 0: + if n3 > 0: + words.append(HUNDREDS[n3][0]) + words.append(ONES_ORDINALS[last_two][0]) + else: + last_fragment_string = '' + if n3 > 0: + last_fragment_string += HUNDREDS_ORDINALS[n3][1] + last_fragment_string += ONES_ORDINALS[last_two][1] + words.append(last_fragment_string) + elif last_two % 10 == 0: + if level == 0: + if n3 > 0: + words.append(HUNDREDS[n3][0]) + words.append(TWENTIES_ORDINALS[n2][0]) + else: + last_fragment_string = '' + if n3 > 0: + last_fragment_string += HUNDREDS_ORDINALS[n3][1] + last_fragment_string += TWENTIES_ORDINALS[n2][1] + words.append(last_fragment_string) + else: + if level == 0: + if n3 > 0: + words.append(HUNDREDS[n3][0]) + words.append(TWENTIES[n2][0]) + words.append(ONES_ORDINALS[n1][0]) + else: + last_fragment_string = '' + if n3 > 0: + last_fragment_string += HUNDREDS_ORDINALS[n3][1] + last_fragment_string += TWENTIES_ORDINALS[n2][1] + last_fragment_string += ONES_ORDINALS[n1][1] + words.append(last_fragment_string) + + def to_ordinal(self, number): + self.verify_ordinal(number) + + words = [] + fragments = list(splitbyx(str(number), 3)) + level = 0 + last = fragments[-1] + while last == 0: + level = level + 1 + fragments.pop() + last = fragments[-1] + if len(fragments) > 1: + pre_part = self._int2word(number - (last * 1000 ** level)) + words.append(pre_part) + Num2Word_UK.last_fragment_to_ordinal( + last, + words, + 0 if level == 0 else 1 + ) + output = " ".join(words) + if last == 1 and level > 0 and output != "": + output = output + " " + if level > 0: + output = output + prefixes_ordinal[level] + return output diff --git a/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_VI.py b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_VI.py new file mode 100644 index 0000000000000000000000000000000000000000..d30fca2397bbb6f325b93863edc9327bcb5639ea --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/num2words/lang_VI.py @@ -0,0 +1,101 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2003, Taro Ogawa. All Rights Reserved. +# Copyright (c) 2013, Savoir-faire Linux inc. All Rights Reserved. + +# This library 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. +# This library 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 along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301 USA + +from __future__ import unicode_literals + +to_19 = (u'không', u'một', u'hai', u'ba', u'bốn', u'năm', u'sáu', + u'bảy', u'tám', u'chín', u'mười', u'mười một', u'mười hai', + u'mười ba', u'mười bốn', u'mười lăm', u'mười sáu', u'mười bảy', + u'mười tám', u'mười chín') +tens = (u'hai mươi', u'ba mươi', u'bốn mươi', u'năm mươi', + u'sáu mươi', u'bảy mươi', u'tám mươi', u'chín mươi') +denom = ('', + u'nghìn', u'triệu', u'tỷ', u'nghìn tỷ', u'trăm nghìn tỷ', + 'Quintillion', 'Sextillion', 'Septillion', 'Octillion', 'Nonillion', + 'Decillion', 'Undecillion', 'Duodecillion', 'Tredecillion', + 'Quattuordecillion', 'Sexdecillion', 'Septendecillion', + 'Octodecillion', 'Novemdecillion', 'Vigintillion') + + +class Num2Word_VI(object): + + def _convert_nn(self, val): + if val < 20: + return to_19[val] + for (dcap, dval) in ((k, 20 + (10 * v)) for (v, k) in enumerate(tens)): + if dval + 10 > val: + if val % 10: + a = u'lăm' + if to_19[val % 10] == u'một': + a = u'mốt' + else: + a = to_19[val % 10] + if to_19[val % 10] == u'năm': + a = u'lăm' + return dcap + ' ' + a + return dcap + + def _convert_nnn(self, val): + word = '' + (mod, rem) = (val % 100, val // 100) + if rem > 0: + word = to_19[rem] + u' trăm' + if mod > 0: + word = word + ' ' + if mod > 0 and mod < 10: + if mod == 5: + word = word != '' and word + u'lẻ năm' or word + u'năm' + else: + word = word != '' and word + u'lẻ ' \ + + self._convert_nn(mod) or word + self._convert_nn(mod) + if mod >= 10: + word = word + self._convert_nn(mod) + return word + + def vietnam_number(self, val): + if val < 100: + return self._convert_nn(val) + if val < 1000: + return self._convert_nnn(val) + for (didx, dval) in ((v - 1, 1000 ** v) for v in range(len(denom))): + if dval > val: + mod = 1000 ** didx + lval = val // mod + r = val - (lval * mod) + + ret = self._convert_nnn(lval) + u' ' + denom[didx] + if 99 >= r > 0: + ret = self._convert_nnn(lval) + u' ' + denom[didx] + u' lẻ' + if r > 0: + ret = ret + ' ' + self.vietnam_number(r) + return ret + + def number_to_text(self, number): + number = '%.2f' % number + the_list = str(number).split('.') + start_word = self.vietnam_number(int(the_list[0])) + final_result = start_word + if len(the_list) > 1 and int(the_list[1]) > 0: + end_word = self.vietnam_number(int(the_list[1])) + final_result = final_result + ' phẩy ' + end_word + return final_result + + def to_cardinal(self, number): + return self.number_to_text(number) + + def to_ordinal(self, number): + return self.to_cardinal(number) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/num2words/utils.py b/TTS/Kokoro/.venv/Lib/site-packages/num2words/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b5e4611be5fafe19324a00594b2648d75bd17bd8 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/num2words/utils.py @@ -0,0 +1,35 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2003, Taro Ogawa. All Rights Reserved. +# Copyright (c) 2013, Savoir-faire Linux inc. All Rights Reserved. + +# This library 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. +# This library 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 along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301 USA + + +def splitbyx(n, x, format_int=True): + length = len(n) + if length > x: + start = length % x + if start > 0: + result = n[:start] + yield int(result) if format_int else result + for i in range(start, length, x): + result = n[i:i+x] + yield int(result) if format_int else result + else: + yield int(n) if format_int else n + + +def get_digits(n): + a = [int(x) for x in reversed(list(('%03d' % n)[-3:]))] + return a diff --git a/TTS/Kokoro/.venv/Lib/site-packages/numpy-2.4.2.dist-info/DELVEWHEEL b/TTS/Kokoro/.venv/Lib/site-packages/numpy-2.4.2.dist-info/DELVEWHEEL new file mode 100644 index 0000000000000000000000000000000000000000..f99d2018eefa05b14204e8731e3efa8e4eef6468 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/numpy-2.4.2.dist-info/DELVEWHEEL @@ -0,0 +1,2 @@ +Version: 1.11.2 +Arguments: ['C:\\Users\\runneradmin\\AppData\\Local\\Temp\\cibw-run-s5wc8nbf\\cp312-win_amd64\\build\\venv\\Scripts\\delvewheel', 'repair', '--add-path', 'D:/a/numpy-release/numpy-release/.openblas/lib', '-w', 'C:\\Users\\runneradmin\\AppData\\Local\\Temp\\cibw-run-s5wc8nbf\\cp312-win_amd64\\repaired_wheel', 'C:\\Users\\runneradmin\\AppData\\Local\\Temp\\cibw-run-s5wc8nbf\\cp312-win_amd64\\built_wheel\\numpy-2.4.2-cp312-cp312-win_amd64.whl'] diff --git a/TTS/Kokoro/.venv/Lib/site-packages/numpy-2.4.2.dist-info/INSTALLER b/TTS/Kokoro/.venv/Lib/site-packages/numpy-2.4.2.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/numpy-2.4.2.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/TTS/Kokoro/.venv/Lib/site-packages/numpy-2.4.2.dist-info/METADATA b/TTS/Kokoro/.venv/Lib/site-packages/numpy-2.4.2.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..1914a435168c07e8ee9113bb3758059116d0c57c --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/numpy-2.4.2.dist-info/METADATA @@ -0,0 +1,139 @@ +Metadata-Version: 2.4 +Name: numpy +Version: 2.4.2 +Summary: Fundamental package for array computing in Python +Author: Travis E. Oliphant et al. +Maintainer-Email: NumPy Developers +License-Expression: BSD-3-Clause AND 0BSD AND MIT AND Zlib AND CC0-1.0 +License-File: LICENSE.txt +License-File: numpy/_core/include/numpy/libdivide/LICENSE.txt +License-File: numpy/_core/src/common/pythoncapi-compat/COPYING +License-File: numpy/_core/src/highway/LICENSE +License-File: numpy/_core/src/multiarray/dragon4_LICENSE.txt +License-File: numpy/_core/src/npysort/x86-simd-sort/LICENSE.md +License-File: numpy/_core/src/umath/svml/LICENSE +License-File: numpy/fft/pocketfft/LICENSE.md +License-File: numpy/linalg/lapack_lite/LICENSE.txt +License-File: numpy/ma/LICENSE +License-File: numpy/random/LICENSE.md +License-File: numpy/random/src/distributions/LICENSE.md +License-File: numpy/random/src/mt19937/LICENSE.md +License-File: numpy/random/src/pcg64/LICENSE.md +License-File: numpy/random/src/philox/LICENSE.md +License-File: numpy/random/src/sfc64/LICENSE.md +License-File: numpy/random/src/splitmix64/LICENSE.md +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Science/Research +Classifier: Intended Audience :: Developers +Classifier: Programming Language :: C +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Topic :: Software Development +Classifier: Topic :: Scientific/Engineering +Classifier: Typing :: Typed +Classifier: Operating System :: Microsoft :: Windows +Classifier: Operating System :: POSIX +Classifier: Operating System :: Unix +Classifier: Operating System :: MacOS +Project-URL: homepage, https://numpy.org +Project-URL: documentation, https://numpy.org/doc/ +Project-URL: source, https://github.com/numpy/numpy +Project-URL: download, https://pypi.org/project/numpy/#files +Project-URL: tracker, https://github.com/numpy/numpy/issues +Project-URL: release notes, https://numpy.org/doc/stable/release +Requires-Python: >=3.11 +Description-Content-Type: text/markdown + +

+ +


+ + +[![Powered by NumFOCUS](https://img.shields.io/badge/powered%20by-NumFOCUS-orange.svg?style=flat&colorA=E1523D&colorB=007D8A)]( +https://numfocus.org) +[![PyPI Downloads](https://img.shields.io/pypi/dm/numpy.svg?label=PyPI%20downloads)]( +https://pypi.org/project/numpy/) +[![Conda Downloads](https://img.shields.io/conda/dn/conda-forge/numpy.svg?label=Conda%20downloads)]( +https://anaconda.org/conda-forge/numpy) +[![Stack Overflow](https://img.shields.io/badge/stackoverflow-Ask%20questions-blue.svg)]( +https://stackoverflow.com/questions/tagged/numpy) +[![Nature Paper](https://img.shields.io/badge/DOI-10.1038%2Fs41586--020--2649--2-blue)]( +https://doi.org/10.1038/s41586-020-2649-2) +[![LFX Health Score](https://insights.linuxfoundation.org/api/badge/health-score?project=numpy)](https://insights.linuxfoundation.org/project/numpy) +[![OpenSSF Scorecard](https://api.securityscorecards.dev/projects/github.com/numpy/numpy/badge)](https://securityscorecards.dev/viewer/?uri=github.com/numpy/numpy) +[![Typing](https://img.shields.io/pypi/types/numpy)](https://pypi.org/project/numpy/) + + +NumPy is the fundamental package for scientific computing with Python. + +- **Website:** https://numpy.org +- **Documentation:** https://numpy.org/doc +- **Mailing list:** https://mail.python.org/mailman/listinfo/numpy-discussion +- **Source code:** https://github.com/numpy/numpy +- **Contributing:** https://numpy.org/devdocs/dev/index.html +- **Bug reports:** https://github.com/numpy/numpy/issues +- **Report a security vulnerability:** https://tidelift.com/docs/security + +It provides: + +- a powerful N-dimensional array object +- sophisticated (broadcasting) functions +- tools for integrating C/C++ and Fortran code +- useful linear algebra, Fourier transform, and random number capabilities + +Testing: + +NumPy requires `pytest` and `hypothesis`. Tests can then be run after installation with: + + python -c "import numpy, sys; sys.exit(numpy.test() is False)" + +Code of Conduct +---------------------- + +NumPy is a community-driven open source project developed by a diverse group of +[contributors](https://numpy.org/teams/). The NumPy leadership has made a strong +commitment to creating an open, inclusive, and positive community. Please read the +[NumPy Code of Conduct](https://numpy.org/code-of-conduct/) for guidance on how to interact +with others in a way that makes our community thrive. + +Call for Contributions +---------------------- + +The NumPy project welcomes your expertise and enthusiasm! + +Small improvements or fixes are always appreciated. If you are considering larger contributions +to the source code, please contact us through the [mailing +list](https://mail.python.org/mailman/listinfo/numpy-discussion) first. + +Writing code isn’t the only way to contribute to NumPy. You can also: +- review pull requests +- help us stay on top of new and old issues +- develop tutorials, presentations, and other educational materials +- maintain and improve [our website](https://github.com/numpy/numpy.org) +- develop graphic design for our brand assets and promotional materials +- translate website content +- help with outreach and onboard new contributors +- write grant proposals and help with other fundraising efforts + +For more information about the ways you can contribute to NumPy, visit [our website](https://numpy.org/contribute/). +If you’re unsure where to start or how your skills fit in, reach out! You can +ask on the mailing list or here, on GitHub, by opening a new issue or leaving a +comment on a relevant issue that is already open. + +Our preferred channels of communication are all public, but if you’d like to +speak to us in private first, contact our community coordinators at +numpy-team@googlegroups.com or on Slack (write numpy-team@googlegroups.com for +an invitation). + +We also have a biweekly community call, details of which are announced on the +mailing list. You are very welcome to join. + +If you are new to contributing to open source, [this +guide](https://opensource.guide/how-to-contribute/) helps explain why, what, +and how to successfully get involved. diff --git a/TTS/Kokoro/.venv/Lib/site-packages/numpy-2.4.2.dist-info/RECORD b/TTS/Kokoro/.venv/Lib/site-packages/numpy-2.4.2.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..b2d39e4f29e57ba5e51250937e9da6e8e358d19c --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/numpy-2.4.2.dist-info/RECORD @@ -0,0 +1,1342 @@ +../../Scripts/f2py.exe,sha256=Y9XptEsthxhW6onv_1oCCn5BYLDWWcL_cGLsi3STB1s,108380 +../../Scripts/numpy-config.exe,sha256=vg0Bjn6u_wLtuUXlDmk5PmLe--tITCk2CF-ROjuYa9w,108380 +numpy-2.4.2.dist-info/DELVEWHEEL,sha256=3zbLwjOIBTU8k8kaztQ13E1O0i4NmHVzU82FxOs9208,462 +numpy-2.4.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +numpy-2.4.2.dist-info/METADATA,sha256=Z4I6ylNqyiVKm0ml3h-Ja0pjGziZKxOGfSz1uX7OXEY,6608 +numpy-2.4.2.dist-info/RECORD,, +numpy-2.4.2.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy-2.4.2.dist-info/WHEEL,sha256=50PeAbplA6PkI0hYOYoeacB9US1R6EguyfOnsccH0WU,85 +numpy-2.4.2.dist-info/entry_points.txt,sha256=7Cb63gyL2sIRpsHdADpl6xaIW5JTlUI-k_yqEVr0BSw,220 +numpy-2.4.2.dist-info/licenses/LICENSE.txt,sha256=qATf8OrZ-txSk0VkELy_wyvwJL6cRRNFlmP7e0QtI0E,45831 +numpy-2.4.2.dist-info/licenses/numpy/_core/include/numpy/libdivide/LICENSE.txt,sha256=1UR2FVi1EIZsIffootVxb8p24LmBF-O2uGMU23JE0VA,1039 +numpy-2.4.2.dist-info/licenses/numpy/_core/src/common/pythoncapi-compat/COPYING,sha256=rqQZdscg-RvRlyXBaRahrOQOsepCYg00Dlh6XeS7zqA,704 +numpy-2.4.2.dist-info/licenses/numpy/_core/src/highway/LICENSE,sha256=0ggVLid3_9ASbqzBvSHAMg1p5Oa2ItIaKhKkfo73N2M,21155 +numpy-2.4.2.dist-info/licenses/numpy/_core/src/multiarray/dragon4_LICENSE.txt,sha256=sP1ZLU6tVjFI45d-e1iRadRqXvL_Ezx1WoGviAo_yRk,1441 +numpy-2.4.2.dist-info/licenses/numpy/_core/src/npysort/x86-simd-sort/LICENSE.md,sha256=pzKXeFNTAGZ5DEKBcIf0gptRjdmNNAyRasv9In4508s,1542 +numpy-2.4.2.dist-info/licenses/numpy/_core/src/umath/svml/LICENSE,sha256=WFSDkFsT1LQvgAxVupnonW4uM8zV9QPiAcB1MdFI_0E,1573 +numpy-2.4.2.dist-info/licenses/numpy/fft/pocketfft/LICENSE.md,sha256=jbAA4VjBYuckl4eFLYxpdkcGUCzO5yXAZkGzHB6VyK8,1523 +numpy-2.4.2.dist-info/licenses/numpy/linalg/lapack_lite/LICENSE.txt,sha256=GQYO9GXheX1oLuD8MIG9JasTlemV5D0lydE8ldmjzWs,2314 +numpy-2.4.2.dist-info/licenses/numpy/ma/LICENSE,sha256=1427IIuA2StNMz5BpLquUNEkRPRuUxmfp3Jqkd5uLac,1616 +numpy-2.4.2.dist-info/licenses/numpy/random/LICENSE.md,sha256=tLwvT6HJV3jx7T3Y8UcGvs45lHW5ePnzS1081yUhtIo,3582 +numpy-2.4.2.dist-info/licenses/numpy/random/src/distributions/LICENSE.md,sha256=z1YZ8lsRLVznyJbv_8jmELyzRd-tzBnywUYKpI__LJ4,2805 +numpy-2.4.2.dist-info/licenses/numpy/random/src/mt19937/LICENSE.md,sha256=ksEGmYhDIfHClH_ipwqyOw-_FQf3Vtid0I84xh_D1Po,2986 +numpy-2.4.2.dist-info/licenses/numpy/random/src/pcg64/LICENSE.md,sha256=QRkGY7d77lMCOGSVoHt-q_v6Vxqgri8R2mdkFiBi_E8,1176 +numpy-2.4.2.dist-info/licenses/numpy/random/src/philox/LICENSE.md,sha256=MirEbYcMiu6tbFOtzMyDkpb7PI5Fbq4VUIEpfa9_gBM,1540 +numpy-2.4.2.dist-info/licenses/numpy/random/src/sfc64/LICENSE.md,sha256=KMrYLOE3ncUp3zDaeOwBLX0NHVdrA93LkziK7lNln1k,1253 +numpy-2.4.2.dist-info/licenses/numpy/random/src/splitmix64/LICENSE.md,sha256=RU7HNQ5HjgNwYYULZzlXU7QlscsKNLvCYpCwIL-J12M,340 +numpy.libs/libscipy_openblas64_-74a408729250596b0973e69fdd954eea.dll,sha256=dKQIcpJQWWsJc-af3ZVO6genD_Unodusz5riEke4A3c,20404736 +numpy.libs/msvcp140-a4c2229bdc2a2a630acdc095b4d86008.dll,sha256=pMIim9wqKmMKzcCVtNhgCOXD47x3cxdDVPPaT1vrnN4,575056 +numpy/__config__.py,sha256=3uacYH-JdfjF1GP76p8cSfx_dS0lD0irAf7KQsSOCHY,5741 +numpy/__config__.pyi,sha256=L6Ml7eJWLoOvEOeI5FCVERMuiPVQUkFOuTmG5lduhzc,2486 +numpy/__init__.cython-30.pxd,sha256=PByDh5eNFDlvCdDfpw7J1RwWPUItbLHUeuoneaoWx7g,48396 +numpy/__init__.pxd,sha256=C1ZTNkpIVrh_YD9ZYrC0beDjHbDJgjcqFKUKddj28k4,44944 +numpy/__init__.py,sha256=sWpPNHxlg8h44Zc6IIVk4BaGt5zHCRGtAVfgXY7s2jc,27212 +numpy/__init__.pyi,sha256=36E0y_ydNWWLd4TItoFZjWMKOF_ILN0m2PyA1XAurZI,242576 +numpy/__pycache__/__config__.cpython-312.pyc,, +numpy/__pycache__/__init__.cpython-312.pyc,, +numpy/__pycache__/_array_api_info.cpython-312.pyc,, +numpy/__pycache__/_configtool.cpython-312.pyc,, +numpy/__pycache__/_distributor_init.cpython-312.pyc,, +numpy/__pycache__/_expired_attrs_2_0.cpython-312.pyc,, +numpy/__pycache__/_globals.cpython-312.pyc,, +numpy/__pycache__/_pytesttester.cpython-312.pyc,, +numpy/__pycache__/conftest.cpython-312.pyc,, +numpy/__pycache__/dtypes.cpython-312.pyc,, +numpy/__pycache__/exceptions.cpython-312.pyc,, +numpy/__pycache__/matlib.cpython-312.pyc,, +numpy/__pycache__/version.cpython-312.pyc,, +numpy/_array_api_info.py,sha256=AeGuRBPBcJ0PeOSi2AB3rkOHFTkWa1N7tYq_Gj9ri3o,10731 +numpy/_array_api_info.pyi,sha256=c77RlN8Pan3QlqXonfTzus7yWI3F4BDMtedWlVO3q-s,5068 +numpy/_configtool.py,sha256=qqay_oP0bqkryU55jFBE6RzgKJkquJ0bBvaYt9D-Gbs,1046 +numpy/_configtool.pyi,sha256=IlC395h8TlcZ4DiSW5i6NBQO9I74ERfXpwSYAktzoaU,25 +numpy/_core/__init__.py,sha256=c8V6fzpU4zOZ3bmxQusn7TquK_S-L0wVk5Z4jha2IOU,6865 +numpy/_core/__init__.pyi,sha256=eRDqlKeg5cDyDbN2Mfq8mUDRvD-hxmIkoEx-89UmMPk,10639 +numpy/_core/__pycache__/__init__.cpython-312.pyc,, +numpy/_core/__pycache__/_add_newdocs.cpython-312.pyc,, +numpy/_core/__pycache__/_add_newdocs_scalars.cpython-312.pyc,, +numpy/_core/__pycache__/_asarray.cpython-312.pyc,, +numpy/_core/__pycache__/_dtype.cpython-312.pyc,, +numpy/_core/__pycache__/_dtype_ctypes.cpython-312.pyc,, +numpy/_core/__pycache__/_exceptions.cpython-312.pyc,, +numpy/_core/__pycache__/_internal.cpython-312.pyc,, +numpy/_core/__pycache__/_methods.cpython-312.pyc,, +numpy/_core/__pycache__/_string_helpers.cpython-312.pyc,, +numpy/_core/__pycache__/_type_aliases.cpython-312.pyc,, +numpy/_core/__pycache__/_ufunc_config.cpython-312.pyc,, +numpy/_core/__pycache__/arrayprint.cpython-312.pyc,, +numpy/_core/__pycache__/cversions.cpython-312.pyc,, +numpy/_core/__pycache__/defchararray.cpython-312.pyc,, +numpy/_core/__pycache__/einsumfunc.cpython-312.pyc,, +numpy/_core/__pycache__/fromnumeric.cpython-312.pyc,, +numpy/_core/__pycache__/function_base.cpython-312.pyc,, +numpy/_core/__pycache__/getlimits.cpython-312.pyc,, +numpy/_core/__pycache__/memmap.cpython-312.pyc,, +numpy/_core/__pycache__/multiarray.cpython-312.pyc,, +numpy/_core/__pycache__/numeric.cpython-312.pyc,, +numpy/_core/__pycache__/numerictypes.cpython-312.pyc,, +numpy/_core/__pycache__/overrides.cpython-312.pyc,, +numpy/_core/__pycache__/printoptions.cpython-312.pyc,, +numpy/_core/__pycache__/records.cpython-312.pyc,, +numpy/_core/__pycache__/shape_base.cpython-312.pyc,, +numpy/_core/__pycache__/strings.cpython-312.pyc,, +numpy/_core/__pycache__/umath.cpython-312.pyc,, +numpy/_core/_add_newdocs.py,sha256=KKzqLHTCXxLzPTg8V8K531Bqh_Ai8BMSFu7EbXu3dUk,222742 +numpy/_core/_add_newdocs.pyi,sha256=ipvUNHAUG15ziSDqc4aGEfQ1jrqpW-zJrogC8G0DOog,136 +numpy/_core/_add_newdocs_scalars.py,sha256=ViMWUAIlsUKosd1mEpLo907cZeaS7Vg_GerzCDIAUUQ,13314 +numpy/_core/_add_newdocs_scalars.pyi,sha256=NNXiuLe2kckDpvpR_WTesOZG1AWSQapqIlGD7tgVtxE,565 +numpy/_core/_asarray.py,sha256=MU1nK76mQ4gDZCWZbdV-zmkmZphAVAkNwghbk4TgqlQ,4024 +numpy/_core/_asarray.pyi,sha256=7oijVMV32GQMEv5xV8sOYfjHHJCjZSo_oJT4zr6u-Kw,1190 +numpy/_core/_dtype.py,sha256=TEjPZXHmpw5-HhfGfKS-PfQT9A9sk8cnaE6icAXVb34,10913 +numpy/_core/_dtype.pyi,sha256=1_fGj6V5NxTYRkN2-cfZBOQOkc1rJ1wET2deS1ANpdw,1888 +numpy/_core/_dtype_ctypes.py,sha256=e8EgfaqXiJ8-UYi8FM5sm9W8ehqvcG_rTpDROaKwTKg,3846 +numpy/_core/_dtype_ctypes.pyi,sha256=d5BudSdtj6n046OX9c-rUoX5zVGghdoO22yEhkjVRoM,3765 +numpy/_core/_exceptions.py,sha256=umxWh9TLhDXy9LmW77wkIHMegFk_KFfBB5ndxsJd5F4,5321 +numpy/_core/_exceptions.pyi,sha256=cWcq9Uf4GrYuKI5IEH-ioVaYDYU1adD9WIPpNu02d-M,1904 +numpy/_core/_internal.py,sha256=LDBumIfjDMIO8cNSfo014AcYngsdkXms6TFLNetZuxY,30405 +numpy/_core/_internal.pyi,sha256=Kax8zq8oAmuPIpkUDU-7ojkjR3C_wtHcA8uNHeftJmI,2212 +numpy/_core/_methods.py,sha256=XdcMBZ5zWZFpUJiL-im2SCtsvyYn_NDirSWICkzt2fw,9645 +numpy/_core/_methods.pyi,sha256=7Mc4H9O3KYU9VwCsOo8X0q6mg9vDr2S6xbwuJ7PXPX4,548 +numpy/_core/_multiarray_tests.cp312-win_amd64.lib,sha256=Mlw_94f56bVbqqGMjqnJgHNEOSAjXfcY5GABDTptPw0,2418 +numpy/_core/_multiarray_tests.cp312-win_amd64.pyd,sha256=ZlEp8MHeGOhO2jrrhOslr0EsX0SqLkNlvmqz9mEOYzE,65536 +numpy/_core/_multiarray_umath.cp312-win_amd64.lib,sha256=CMaDGeCuY4zT0u7EPSaQxBqpV746HUkD7NzO9OXvqrs,2192 +numpy/_core/_multiarray_umath.cp312-win_amd64.pyd,sha256=vkhsTMavV7GemQ1t5BUIc2Z1kI_GgELGH4ztthjA1so,3710464 +numpy/_core/_operand_flag_tests.cp312-win_amd64.lib,sha256=w4N9EnAJe36EHMa07KFSvlJDBzecntKaZOr6Wtdhe_4,2228 +numpy/_core/_operand_flag_tests.cp312-win_amd64.pyd,sha256=y70JKuuS2LWswHF6GEA-IG8pmw2r3ROlIb_ZTKhjpDM,12288 +numpy/_core/_rational_tests.cp312-win_amd64.lib,sha256=7tuYOSDxPaDbRh_rVf5r8h6paSVo2N5z37di9ibHMbM,2156 +numpy/_core/_rational_tests.cp312-win_amd64.pyd,sha256=SjST-Kjfkmos2T6ToOgWUvp0j7-E_dpgl8fL_-_GRGo,39936 +numpy/_core/_simd.cp312-win_amd64.lib,sha256=5YhlCkuoUKtK4N-ExWE8bHdECtp2zvj2etkR80i_SDw,1976 +numpy/_core/_simd.cp312-win_amd64.pyd,sha256=l6eKuKx1fRcpdiOSqpbQKdgvozVyLAhRpHPz1RGRf9g,832000 +numpy/_core/_simd.pyi,sha256=vLr3cmfU5D-UytIPEzQHUwoEOZGzfLI63uwPYN-bvIU,1013 +numpy/_core/_string_helpers.py,sha256=aX1N5UsNeUFy54o5tuTC6X6N9AJueFN2_6QIyIUD2Xg,2945 +numpy/_core/_string_helpers.pyi,sha256=bThH7ichGlrmQ6O38n71QcJ7Oi_mRPUf-DFMU5hdYU0,370 +numpy/_core/_struct_ufunc_tests.cp312-win_amd64.lib,sha256=5FCMZgkJpaurKbWwwlZBakDtkOgpmpW6Cms_DZOsIrA,2228 +numpy/_core/_struct_ufunc_tests.cp312-win_amd64.pyd,sha256=LtDmeLefs0xXkR31Pxwm0vkGHsVyrE8k9fkPlafmRqI,14336 +numpy/_core/_type_aliases.py,sha256=U51em1dU7qluFYICpmrygSHLfk-y4UoqD0JJM-psCjE,3886 +numpy/_core/_type_aliases.pyi,sha256=-t_aBa6lQ06Z0wsOzpiE84XW0-2FU-hkA3HSTWlavAk,2306 +numpy/_core/_ufunc_config.py,sha256=xeJy3K7KPV5PpJbkW9ncWY_UnnLHlM9M6rX4C9eNs2k,16126 +numpy/_core/_ufunc_config.pyi,sha256=Fpec58dVzJmrKRSiOsnWZvdS5wuyORMmPkzoOy15YwY,1930 +numpy/_core/_umath_tests.cp312-win_amd64.lib,sha256=HMv4bOxKDRbfdVYrMIlgsDW-yhlHBfAqbWHr3lHZ_4U,2104 +numpy/_core/_umath_tests.cp312-win_amd64.pyd,sha256=O0lpCGEMQiIWzs7Z8m7RWdyfrEkksQJ6-NUZ-V-W8tM,33280 +numpy/_core/_umath_tests.pyi,sha256=KwadAqagA7lloXXeOQQp3Gkp0T_HuuT87pI4dz3ttTY,2344 +numpy/_core/arrayprint.py,sha256=lpxDgWjCALcJThUtdKVUVOiM4Vrd4Xn7qaHnquc0tzw,67050 +numpy/_core/arrayprint.pyi,sha256=El-bKIjihbdXa2N05qohoYm_amZG6gwGn1lLsc19f1E,4688 +numpy/_core/cversions.py,sha256=FISv1d4R917Bi5xJjKKy8Lo6AlFkV00WvSoB7l3acA4,360 +numpy/_core/defchararray.py,sha256=4S8fU1YI2vGGUGYxRSr0536JJTO-S-Y9aMYe6BnQipY,39231 +numpy/_core/defchararray.pyi,sha256=qeYhLiloeDFogxBxYd_Ax9DDHQNI8nu2wyp3X2qfLYw,29794 +numpy/_core/einsumfunc.py,sha256=_mRaqmbQeZ3TDW4Y6gLz4nmDE4WfFL9UxKSAJBzGujc,59578 +numpy/_core/einsumfunc.pyi,sha256=j7eufFy3WhOcAGWT9FO8dxHB2kTLJNH6S84MPxtALS8,5109 +numpy/_core/fromnumeric.py,sha256=5T-r7fxkHbdvJiBfWVD6mwI7bbi2E95F0z9XFeBq-CI,146891 +numpy/_core/fromnumeric.pyi,sha256=o6l_ETLBkqmhOq8Ga3QBxWznwpZbfY94fX1UDrJKsXM,46598 +numpy/_core/function_base.py,sha256=zBvtIUZoUVe_sGSPdnDmOXc9GMX232Iqx5FtkMp5e8c,20224 +numpy/_core/function_base.pyi,sha256=Z5DaKdqR3t1sun85xnT2t6OkUsyDSW6gAO8oNBmfEjY,7321 +numpy/_core/getlimits.py,sha256=tX7eDWVY3113HFBztt5JOttUTI31S4-rC0bVXYJRG4M,15465 +numpy/_core/getlimits.pyi,sha256=Ok2rv9SELwkPHbC4qttkIDRpUZbv7ey6LDvCGvUSEeE,3921 +numpy/_core/include/numpy/__multiarray_api.c,sha256=ucLypGZeaaHhl2OX-4YQrrCGTUl-8XwObmmN8zQjRjU,13074 +numpy/_core/include/numpy/__multiarray_api.h,sha256=9OcLvWKEidFXT_YzbInua3Ft8ruCXgUtG-vl9w9WluQ,63371 +numpy/_core/include/numpy/__ufunc_api.c,sha256=7mulmWQI9Hdlx3IjZF-GWhZYZtrFn4I6tCG0Uoo0LCc,1854 +numpy/_core/include/numpy/__ufunc_api.h,sha256=oxLZE6JL-8gWdzf5RA760Gr7KnjqXhMwycaO53cxaRk,13754 +numpy/_core/include/numpy/_neighborhood_iterator_imp.h,sha256=s5TK2aPpClbw4CbVJCij__hzoh5IgHIIZK0k6FKtqfc,1947 +numpy/_core/include/numpy/_numpyconfig.h,sha256=jIeId55dTsklMKBXl8zsicKcReSVSYn7kIFMLOn-qKE,902 +numpy/_core/include/numpy/_public_dtype_api_table.h,sha256=4ylG8s52kZEx__QODt_7Do8QitmhDSvTeZ7Lar0fOgo,4660 +numpy/_core/include/numpy/arrayobject.h,sha256=ghWzloPUkSaVkcsAnBnpbrxtXeXL-mkzVGJQEHFxjnk,211 +numpy/_core/include/numpy/arrayscalars.h,sha256=LKd4F3obZd65HWDmHD6GS9LJ91r2J0GX0VPVPtTBztE,4522 +numpy/_core/include/numpy/dtype_api.h,sha256=7HG7Pn8WOChR0ifvAOmVARSVnql7dqL07MQLWhRHpco,22002 +numpy/_core/include/numpy/halffloat.h,sha256=qYgX5iQfNzXICsnd0MCRq5ELhhfFjlRGm1xXGimQm44,2029 +numpy/_core/include/numpy/ndarrayobject.h,sha256=WWy6pljDNLhzFf0QWNfvH7-jO2afkRbbrtFYSet16v4,12359 +numpy/_core/include/numpy/ndarraytypes.h,sha256=N8FTdkiDL8l04ZriXBDDDEA0ycaPUVkb8WCAtkdLoLk,68964 +numpy/_core/include/numpy/npy_2_compat.h,sha256=VxsRXAtDfLlXkvH-ErZRSuH49k9EjcFwcSUSfTPRzAU,8795 +numpy/_core/include/numpy/npy_2_complexcompat.h,sha256=uW0iF-qMwQNn4PvIfWCrYce6b4OrYUO4BWu-VYYAZag,885 +numpy/_core/include/numpy/npy_3kcompat.h,sha256=0yiCfXGefB938r_IykVf5DaRUJQeYOLvFY__VOF0ezI,10047 +numpy/_core/include/numpy/npy_common.h,sha256=fjuQ8bWFPrfhmrzet2yUQEmAeNwWn5AwgLYTbTMSEZE,33873 +numpy/_core/include/numpy/npy_cpu.h,sha256=G1W2dMD7IbMjCrOmAtEv7nNOH6awBsY0fotNAp3ebaE,4478 +numpy/_core/include/numpy/npy_endian.h,sha256=f1BT0ALH-Gca3cco_CgTm53HMLxmBmo4ZfzVxxLNlKM,2957 +numpy/_core/include/numpy/npy_math.h,sha256=ksdiKBXDfpEHB1s9m5yinyhjdcc0h-zJcfXEuoVHAd8,19460 +numpy/_core/include/numpy/npy_no_deprecated_api.h,sha256=jIcjEP2AbovDTfgE-qtvdP51_dVGjVnEGBX86rlGSKE,698 +numpy/_core/include/numpy/npy_os.h,sha256=j044vd1C1oCcW52r3htiVNhUaJSEqCjKrODwMHq3TU0,1298 +numpy/_core/include/numpy/numpyconfig.h,sha256=1EsdOVVuZb1tH7Yi1UO0q0yyZtuMRqMsnI0gBFhKNLo,7651 +numpy/_core/include/numpy/random/LICENSE.txt,sha256=1UR2FVi1EIZsIffootVxb8p24LmBF-O2uGMU23JE0VA,1039 +numpy/_core/include/numpy/random/bitgen.h,sha256=_H0uXqmnub4PxnJWdMWaNqfpyFDu2KB0skf2wc5vjUc,508 +numpy/_core/include/numpy/random/distributions.h,sha256=GLURa3sFESZE0_0RK-3Gqmfa96itBHw8LlsNyy9EPt4,10070 +numpy/_core/include/numpy/random/libdivide.h,sha256=F9PLx6TcOk-sd0dObe0nWLyz4HhbHv2K7voR_kolpGU,82217 +numpy/_core/include/numpy/ufuncobject.h,sha256=uI5m_WOrFQtaL3BwgRmiZ7BN8CypKXfC5EcQfdhH-Eg,12123 +numpy/_core/include/numpy/utils.h,sha256=vzJAbatJYfxHmX2yL_xBirmB4mEGLOhJ92JlV9s8yPs,1222 +numpy/_core/lib/npy-pkg-config/mlib.ini,sha256=hYWFyoBxE036dh19si8UPka01H2cv64qlc4ZtgoA_7A,156 +numpy/_core/lib/npy-pkg-config/npymath.ini,sha256=e0rdsb00Y93VuammuvIIFlzZtnUAXwsS1XNKlCU8mFQ,381 +numpy/_core/lib/npymath.lib,sha256=Q3ENEZJLpwqrCMSSxNdkqcEZoFNwo5-fkmE6W5GhWUU,156686 +numpy/_core/lib/pkgconfig/numpy.pc,sha256=gd_zcQg2ptXJ6Rt_ip9sHb5WGZ7JhLpXRW6h8opUPbk,198 +numpy/_core/memmap.py,sha256=7HWQGjK5bS3SzAPx4wAlHwH6YFrX13sBpa6E52zxatc,13014 +numpy/_core/memmap.pyi,sha256=n0kBe4iQD5lcWvAvVhdUU18YIoPX6Sf5e2qh9IdO5uQ,50 +numpy/_core/multiarray.py,sha256=fiWmU-pL0WOeS7TT_flBueqKmz08gibdrBFCoanSSoE,58526 +numpy/_core/multiarray.pyi,sha256=JPMPttIq_yU0K1QgJ6r3mQwUWJzCcvoXqiTcSUWZ46k,36157 +numpy/_core/numeric.py,sha256=f36Y3XitfH2ga7zH2EZ4gctI1TywvTYoJyqtFepXpNA,85809 +numpy/_core/numeric.pyi,sha256=TwBDlYXpbMmBHv-uAIzagUCnTZdaxfKHLU-OblqprBw,32989 +numpy/_core/numerictypes.py,sha256=sBii4N4PX66DFZJ_QlDepfugXHToV4MqVTl9DrkTCko,16600 +numpy/_core/numerictypes.pyi,sha256=BuVBOeILfBBRLLVinSA_mCVqYtgoaM4ukXK2MOr4xVQ,3699 +numpy/_core/overrides.py,sha256=7xQXbKNNTDqDFR3cL6vcBbgczarMVdOiKjWfHM5zS4A,7668 +numpy/_core/overrides.pyi,sha256=yiWM44pF9yPJn3-VOebjxtwU0W9PyHV0QxCA2lkDrMQ,1777 +numpy/_core/printoptions.py,sha256=ZXekBr6fI18dVxsM6bxAGi80CiMlaMN4dpbPHDQiBOI,1088 +numpy/_core/printoptions.pyi,sha256=QE36MVL3BgqflyQuj6UOzywbnELMiLeyNz_1sALvOSU,622 +numpy/_core/records.py,sha256=AOi0UTbYqHe8U5AntKvc967O8hmtVw8pSqiahfJhtI8,37842 +numpy/_core/records.pyi,sha256=ecWlyL8cskXhQihOa2iyNNANhqYLhACgf2u7UaINjRk,9515 +numpy/_core/shape_base.py,sha256=oy42iPojaLjQjsQy1c35Xl72w0VtLZCbtipZlb8XGoo,33708 +numpy/_core/shape_base.pyi,sha256=_k-bDbnUgvQTYBn1I_Y75sUz23B-N3nhw07obXhbmp4,5437 +numpy/_core/strings.py,sha256=CJ6R0-LYceFfxuaOLhZL1tZwWvYdlaoaT3f0qLXpj1o,52391 +numpy/_core/strings.pyi,sha256=d3MRp3JMOqg7qiMNM5E3lJ6qWZmpR9m-h8DCNsrf0KI,14127 +numpy/_core/tests/__pycache__/_locales.cpython-312.pyc,, +numpy/_core/tests/__pycache__/_natype.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test__exceptions.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_abc.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_api.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_argparse.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_array_api_info.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_array_coercion.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_array_interface.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_arraymethod.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_arrayobject.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_arrayprint.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_casting_floatingpoint_errors.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_casting_unittests.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_conversion_utils.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_cpu_dispatcher.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_cpu_features.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_custom_dtypes.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_cython.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_datetime.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_defchararray.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_deprecations.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_dlpack.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_dtype.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_einsum.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_errstate.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_extint128.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_finfo.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_function_base.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_getlimits.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_half.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_hashtable.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_indexerrors.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_indexing.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_item_selection.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_limited_api.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_longdouble.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_mem_overlap.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_mem_policy.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_memmap.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_multiarray.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_multiprocessing.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_multithreading.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_nditer.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_nep50_promotions.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_numeric.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_numerictypes.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_overrides.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_print.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_protocols.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_records.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_regression.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_scalar_ctors.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_scalar_methods.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_scalarbuffer.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_scalarinherit.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_scalarmath.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_scalarprint.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_shape_base.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_simd.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_simd_module.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_stringdtype.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_strings.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_ufunc.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_umath.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_umath_accuracy.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_umath_complex.cpython-312.pyc,, +numpy/_core/tests/__pycache__/test_unicode.cpython-312.pyc,, +numpy/_core/tests/_locales.py,sha256=byq7PFI0o_eF8Ddsvgj2EQ7oEjgxYZEa2EW0SJmR_xc,2248 +numpy/_core/tests/_natype.py,sha256=ncMM01bhYe4KxM62PTwIaH6Xpze6D9mSVFZSQqqaZzQ,4531 +numpy/_core/tests/data/astype_copy.pkl,sha256=lWSzCcvzRB_wpuRGj92spGIw-rNPFcd9hwJaRVvfWdk,716 +numpy/_core/tests/data/generate_umath_validation_data.cpp,sha256=9TBdxpPo0djv1CKxQ6_DbGKRxIZVawitAm7AMmWKroI,6012 +numpy/_core/tests/data/recarray_from_file.fits,sha256=NA0kliz31FlLnYxv3ppzeruONqNYkuEvts5wzXEeIc4,8640 +numpy/_core/tests/data/umath-validation-set-README.txt,sha256=GfrkmU_wTjpLkOftWDuGayEDdV3RPpN2GRVQX61VgWI,982 +numpy/_core/tests/data/umath-validation-set-arccos.csv,sha256=VUdQdKBFrpXHLlPtX2WYIK_uwkaXgky85CZ4aNuvmD4,62794 +numpy/_core/tests/data/umath-validation-set-arccosh.csv,sha256=tbuOQkvnYxSyJf_alGk3Zw3Vyv0HO5dMC1hUle2hWwQ,62794 +numpy/_core/tests/data/umath-validation-set-arcsin.csv,sha256=JPEWWMxgPKdNprDq0pH5QhJ2oiVCzuDbK-3WhTKny8o,62768 +numpy/_core/tests/data/umath-validation-set-arcsinh.csv,sha256=fwuq25xeS57kBExBuSNfewgHb-mgoR9wUGVqcOXbfoI,61718 +numpy/_core/tests/data/umath-validation-set-arctan.csv,sha256=nu33YyL-ALXSSF5cupCTaf_jTPLK_QyUfciNQGpffkY,61734 +numpy/_core/tests/data/umath-validation-set-arctanh.csv,sha256=wHSKFY2Yvbv3fnmmfLqPYpjhkEM88YHkFVpZQioyBDw,62768 +numpy/_core/tests/data/umath-validation-set-cbrt.csv,sha256=FFi_XxEnGrfJd7OxtjVFT6WFC2tUqKhVV8fmQfb0z8o,62275 +numpy/_core/tests/data/umath-validation-set-cos.csv,sha256=ccDri5_jQ84D_kAmSwZ_ztNUPIhzhgycDtNsPB7m8dc,60497 +numpy/_core/tests/data/umath-validation-set-cosh.csv,sha256=DnN6RGvKQHAWIofchmhGH7kkJej2VtNwGGMRZGzBkTQ,62298 +numpy/_core/tests/data/umath-validation-set-exp.csv,sha256=mPhjF4KLe0bdwx38SJiNipD24ntLI_5aWc8h-V0UMgM,17903 +numpy/_core/tests/data/umath-validation-set-exp2.csv,sha256=sD94pK2EAZAyD2fDEocfw1oXNw1qTlW1TBwRlcpbcsI,60053 +numpy/_core/tests/data/umath-validation-set-expm1.csv,sha256=tyfZN5D8tlm7APgxCIPyuy774AZHytMOB59H9KewxEs,61728 +numpy/_core/tests/data/umath-validation-set-log.csv,sha256=CDPky64PjaURWhqkHxkLElmMiI21v5ugGGyzhdfUbnI,11963 +numpy/_core/tests/data/umath-validation-set-log10.csv,sha256=dW6FPEBlRx2pcS-7eui_GtqTpXzOy147il55qdP-8Ak,70551 +numpy/_core/tests/data/umath-validation-set-log1p.csv,sha256=2aEsHVcvRym-4535CkvJTsmHywkt01ZMfmjl-d4fvVI,61732 +numpy/_core/tests/data/umath-validation-set-log2.csv,sha256=aVZ7VMQ5urGOx5MMMOUmMKBhFLFE-U7y6DVCTeXQfo0,70546 +numpy/_core/tests/data/umath-validation-set-sin.csv,sha256=GvPrQUEYMX1iB2zjbfK26JUJOxtqbfiRUgXuAO1QcP0,59981 +numpy/_core/tests/data/umath-validation-set-sinh.csv,sha256=lc7OYcYWWpkxbMuRAWmogQ5cKi7EwsQ2ibiMdpJWYbw,61722 +numpy/_core/tests/data/umath-validation-set-tan.csv,sha256=fn7Dr9s6rcqGUzsmyJxve_Z18J4AUaSm-uo2N3N_hfk,61728 +numpy/_core/tests/data/umath-validation-set-tanh.csv,sha256=xSY5fgfeBXN6fal4XDed-VUcgFIy9qKOosa7vQ5v1-U,61728 +numpy/_core/tests/examples/cython/__pycache__/setup.cpython-312.pyc,, +numpy/_core/tests/examples/cython/checks.pyx,sha256=ALc3Mmp-LI2f3AA4E7sl-dBBYSF4l1_bG3WhO3M1mXs,11182 +numpy/_core/tests/examples/cython/meson.build,sha256=EaUdTgpleUBROExDaFVMnWIYW4XDxFLFGK9ej_pTtQg,1311 +numpy/_core/tests/examples/cython/setup.py,sha256=h5vJxfwGpwRWaa7iWTYeCstbcDNHN0Yd_rP963v7sZ0,898 +numpy/_core/tests/examples/limited_api/__pycache__/setup.cpython-312.pyc,, +numpy/_core/tests/examples/limited_api/limited_api1.c,sha256=93ZjLJTtIfXUE7sc2QuEohjHzNSxapzZhgFXtTn8Yyg,326 +numpy/_core/tests/examples/limited_api/limited_api2.pyx,sha256=4P5-yu0yr8NBa-TFtw4v30LGjccRroRAQFFLaztEK9I,214 +numpy/_core/tests/examples/limited_api/limited_api_latest.c,sha256=YRgkeYJEtIfijcJwRqyz97ItrkUwOoiyrKy90WTkQW4,471 +numpy/_core/tests/examples/limited_api/meson.build,sha256=Sin_YDuMzgpDW8n2_WWJ5EYgRQg7FPs7JiJPaUEbFqw,1725 +numpy/_core/tests/examples/limited_api/setup.py,sha256=47iWsN-5wYB29Lb7vqSjzrAS3UtkdFufkt93XzzG-lE,461 +numpy/_core/tests/test__exceptions.py,sha256=ov3cdaYBfP28w_FcLF57ROlF5w6fwCFRNcmOVyRA-IU,3012 +numpy/_core/tests/test_abc.py,sha256=qdC7_lkQvaF_3A4xJ9H_Ih3FDlMpA9dxQHjsg4Tn-uc,2275 +numpy/_core/tests/test_api.py,sha256=mFEuLfhn2f0piUdgc-MvYw6jKKQJLdrkaN1tPZBbAUE,24915 +numpy/_core/tests/test_argparse.py,sha256=vPctuxToPkZMlbgjnzE924XkxXYUdBxlR6LsP2_-aQM,2914 +numpy/_core/tests/test_array_api_info.py,sha256=YySxzABrxjo2XVC9bwslv5VGBIiDK5N0DXpKLfhwBio,3176 +numpy/_core/tests/test_array_coercion.py,sha256=tjGrdd1RGUC9vyvu9SST6L06EubVwAoEPJD40CbtL1c,36319 +numpy/_core/tests/test_array_interface.py,sha256=s-mrGDOBpWOfIShNHrnfPuUeZDTBX5eD8R1kY4-JrUc,8065 +numpy/_core/tests/test_arraymethod.py,sha256=piiJcgPMH7cx15UykJyj_WVnzH51wIyxQIyftLtsmHE,3307 +numpy/_core/tests/test_arrayobject.py,sha256=xM3NSqoUuPJYGf_1v7DG0_g-1JCeq7KnevbIllgSbi8,3431 +numpy/_core/tests/test_arrayprint.py,sha256=UGJplHWOJaaZb6bYeKgK0akATbJP9l6H2NDvtLwb3kA,51898 +numpy/_core/tests/test_casting_floatingpoint_errors.py,sha256=fMotyIWxYMxJ_mF7zZMg3j3l7j-C6nfm_YUPw1ln5dA,5230 +numpy/_core/tests/test_casting_unittests.py,sha256=BUtpp1cJcfH-vfdicDThvcEUUtXpadhk6ulUvoVm0Aw,41899 +numpy/_core/tests/test_conversion_utils.py,sha256=Kh56ducSAax3n8E9cXQ66GvE1ZXZ_pkWTpQy0jTEwAk,6715 +numpy/_core/tests/test_cpu_dispatcher.py,sha256=oS8EAcRN88tQJ8DhSnwcLNNotmxbfMY-xrzntwcKFxw,1619 +numpy/_core/tests/test_cpu_features.py,sha256=egAbz8ZSIY-qHduR_-InVxJQOxwxrGch96gDvWSUXCw,16252 +numpy/_core/tests/test_custom_dtypes.py,sha256=QBlykvsEq9Wns38ey1gRHn0uaJjwsp2Cfm8FKiQiRHY,14889 +numpy/_core/tests/test_cython.py,sha256=LSVOHhtIggMCeftdS8R36TnzB0aBUR60gRu-LIB1y0o,10570 +numpy/_core/tests/test_datetime.py,sha256=NyZN30MA9NOSVHND6Ox_oePoz6AG_pgzSkvWk7ouswU,127545 +numpy/_core/tests/test_defchararray.py,sha256=bADzj5CgBanE83hUp9-bPgAIsD6X9nVP59M8koH_4nQ,31541 +numpy/_core/tests/test_deprecations.py,sha256=2c7iQRBI7123mHRy-9BkgNwtW57gq9Ooy5JtUfHdeG4,17940 +numpy/_core/tests/test_dlpack.py,sha256=YJu603N6gqqraJx8f5xzArbmYVFPFDJ32DZyYom2q5c,6021 +numpy/_core/tests/test_dtype.py,sha256=4TKjus3b0tRykFwp36QF3gzagffeyi6KKZJ7N_KS4ig,85332 +numpy/_core/tests/test_einsum.py,sha256=4XOd0yyzDKW4bh5bkFGT5QD2Qs5S_EgDgq0XHyDf4qc,59244 +numpy/_core/tests/test_errstate.py,sha256=UbPwl97JxUu050tMPJN2NTyqFkUaNpRKwqex34DxJ1E,4759 +numpy/_core/tests/test_extint128.py,sha256=pKScJ8lsYGfvX4rMTAf9bwoTzLYkK1hnLZmfF1jKAo4,5842 +numpy/_core/tests/test_finfo.py,sha256=Py3BfM_eaxrbYg0bhesDMT6LtiaGfCOjlXcTZ_CnvSs,2574 +numpy/_core/tests/test_function_base.py,sha256=NuclhwR2CVPl_bnKrFOPAksM7ssK9dmaFKaGrzyGqQs,18187 +numpy/_core/tests/test_getlimits.py,sha256=PV40xaQ1thmbtePVWRpYAvFrkvkS6RWi38cB-gbYxOE,5624 +numpy/_core/tests/test_half.py,sha256=SLfewT9i3igCumuVhWpRPT9YqyBYBYSMQ0HgXNuPKnY,25853 +numpy/_core/tests/test_hashtable.py,sha256=SDZHeVow_7hEus0A0hpG-yYorz6Z4jA734xJh2YP6SA,1184 +numpy/_core/tests/test_indexerrors.py,sha256=lQZFzPModGwJDh8kPxU_F1CJAhFJXAVZok31V6JkJyo,4835 +numpy/_core/tests/test_indexing.py,sha256=WRXgPDF4_20vmOi5xqV8U5HXjTghRTeadof0Zpm9Ylw,66315 +numpy/_core/tests/test_item_selection.py,sha256=erSTKqbX9C5i9EJeTI4tIenDW4vlo1PO-wqFRKtBB68,6798 +numpy/_core/tests/test_limited_api.py,sha256=bN6sU8V2vtFOxwhf3n0EtEXJuT5ifw2i6S2DHTDJHMQ,3565 +numpy/_core/tests/test_longdouble.py,sha256=JZ3s4NRsteMn5tW3nG8rPU4XKGlJ50Udu2mkRh0omAg,12824 +numpy/_core/tests/test_mem_overlap.py,sha256=-EocVf7okOS3d3khQz12zm1fRxsnfkXQBdJ2y5lZz8w,30250 +numpy/_core/tests/test_mem_policy.py,sha256=vAjCbfroLALRl2hd-5iqNbCiJbRdwEriKKEB_umWg5M,17301 +numpy/_core/tests/test_memmap.py,sha256=QSo4Z23N-GGkIVXqa8TXOVsCpY-vS8-Aei4wEQiELV8,8546 +numpy/_core/tests/test_multiarray.py,sha256=LWSS4gOS0MAdQuxJfXWgKQWpjQI6GCwtzBaRuEHreXA,431040 +numpy/_core/tests/test_multiprocessing.py,sha256=fxmHyEXpaYp2f-QEKFSnx5wBJqn3aH0dy_OHNcVb5-s,2089 +numpy/_core/tests/test_multithreading.py,sha256=kT3i0zCxPm7r3RHcfykhm2dKo4PqexVCYkCfEV8Pzyg,12498 +numpy/_core/tests/test_nditer.py,sha256=6jzzlDHpN0za_lCN9ghG8rB14YSWoBPwwlXYjmqYNaI,141372 +numpy/_core/tests/test_nep50_promotions.py,sha256=sw60eH2T2EBrpO0VeulZrHpnRCz6wE0MiA4U9B3_MFQ,10355 +numpy/_core/tests/test_numeric.py,sha256=VCpaYp6i1GdubO_mHtavO6ofEMjMJjZVnyKf5xbaTmM,164905 +numpy/_core/tests/test_numerictypes.py,sha256=fSNA-EhkNQwJU33c4wEBAEgV4rLeibDTdXK0bZG0FOg,24824 +numpy/_core/tests/test_overrides.py,sha256=UDdhmwueEuHjBJQf6NvJ7o8K5A2JRq92a5XG2LQaiEY,28577 +numpy/_core/tests/test_print.py,sha256=UPdSzvGrdCZnB8NoBkY9gKXOkr4NZsUjfaypNgm3iA4,7117 +numpy/_core/tests/test_protocols.py,sha256=b1clvp3Rr7EQ6x8Mtxm9jAiHxPymEU_VJBjwnMingUU,1219 +numpy/_core/tests/test_records.py,sha256=3_z_6E-TKMowzkXujZG0JyxkeiH471GMHWOQeheVm1g,21156 +numpy/_core/tests/test_regression.py,sha256=kmmkC60tAsF1tsl-TAGWm9bHoczfMHQpQ6ooNs5HBXg,98849 +numpy/_core/tests/test_scalar_ctors.py,sha256=RZBTUxU_z4rg7q2fMcRce_VYqjUgcBvL7SF3txjtrzc,6896 +numpy/_core/tests/test_scalar_methods.py,sha256=lJyS9hUf_99haU6K0FKeADApcIdD8iP6GALWb2ECIF8,12839 +numpy/_core/tests/test_scalarbuffer.py,sha256=FkcZR3rDC5tEYhknI_pMhVs-G9jQXcx7hu1WZCR6kvE,5787 +numpy/_core/tests/test_scalarinherit.py,sha256=WVjRrpNkKvQbO2n-joJ7EF6lG1zFcT4pgANAtvT7C5M,2692 +numpy/_core/tests/test_scalarmath.py,sha256=Q4vg6st6pVkDxGGwfJ85d0KFDKfcwzq2rZedow67dHQ,47385 +numpy/_core/tests/test_scalarprint.py,sha256=aDQz8rz3KXQ5EBiaIaxmvHpLaIUkZeI-8PoTqZ4kvyM,20108 +numpy/_core/tests/test_shape_base.py,sha256=CkSHU_VkczeAvIOHSpXt-YQzsBmVt5HnnQVG7i8qFi8,32771 +numpy/_core/tests/test_simd.py,sha256=85MWw13IIWQ88SI0I61gyQar94AaLTfJTvxyFFOxrVs,50239 +numpy/_core/tests/test_simd_module.py,sha256=ml8Wu6vrAwx7Qbs_nft2eR0o3TunJuNkETtVJ271mT4,4055 +numpy/_core/tests/test_stringdtype.py,sha256=jgjl_8BBUjcGCVve2NjOUYbWo7rlKp3uUKfWRukwO6o,60358 +numpy/_core/tests/test_strings.py,sha256=Id52CzqaLS3fF5A5fFbaKNept1FeipXZ92pwcuIRMEM,61679 +numpy/_core/tests/test_ufunc.py,sha256=r8ZWPx3wketfjfqjNqCZLOoShJSqJnIP_uExNWd099U,143118 +numpy/_core/tests/test_umath.py,sha256=Yelw68ER27ru-jee6G1Vs0TXsR0bpEb0RRPqNPiSc34,200811 +numpy/_core/tests/test_umath_accuracy.py,sha256=ZCqjVUPFdn_WaKDBwmND_aZZFzdPWomf6_Yui6BV_tk,5953 +numpy/_core/tests/test_umath_complex.py,sha256=CKzN_RQ8o9LPK7Ax9WaF-1kQpSZj8Lg9BGN45GrEMv4,24242 +numpy/_core/tests/test_unicode.py,sha256=6_hND3jRcv1MkmOpjKxZSG-uBKS3WvjUz3rozgimq8U,13356 +numpy/_core/umath.py,sha256=NWmvoyWQXFuCOCQi3rOXYAlNcIfhSiKm4WNzxCCn9fc,2200 +numpy/_core/umath.pyi,sha256=dTF_yXVG0t6Sw-q7oa2otpZV8E0LweJ9Ru6jF-ENQ7M,3948 +numpy/_distributor_init.py,sha256=h5_Cq7ItDrt1JZoAh04aO54ZXsXRRkyGoNFFH9T-08U,436 +numpy/_distributor_init.pyi,sha256=CSrbSp2YYxHTxlX7R0nT3RpH7EloB1wIvo7YOA7QWy8,28 +numpy/_expired_attrs_2_0.py,sha256=Qjxzbnge_WAK5nO2glybK2Bv9gNulmxGofjbGwLLkw8,3849 +numpy/_expired_attrs_2_0.pyi,sha256=V7NCR-ik42HqU4sRKPbPOyFNYoFwREWyw6MLxh28p9Y,1300 +numpy/_globals.py,sha256=QC41LPui5xIF0vbXrBtrBlxJV8JKvxZsCc3d9yPTmLY,4276 +numpy/_globals.pyi,sha256=kst3Vm7ZbznOtHsPya0PzU0KbjRGZ8xhMmTNMafvT-4,297 +numpy/_pyinstaller/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/_pyinstaller/__init__.pyi,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/_pyinstaller/__pycache__/__init__.cpython-312.pyc,, +numpy/_pyinstaller/__pycache__/hook-numpy.cpython-312.pyc,, +numpy/_pyinstaller/hook-numpy.py,sha256=bJTm7LIuDHC5QyGTqUWE48gYsRcolKm3naQXoE1o_C4,1398 +numpy/_pyinstaller/hook-numpy.pyi,sha256=28DtDC-8ixBS_9WXTKnyzC1o_7K92wUk8_UfN7WBd78,156 +numpy/_pyinstaller/tests/__init__.py,sha256=l38bo7dpp3u1lVMPErlct_5uBLKj35zuS_r35e7c19c,345 +numpy/_pyinstaller/tests/__pycache__/__init__.cpython-312.pyc,, +numpy/_pyinstaller/tests/__pycache__/pyinstaller-smoke.cpython-312.pyc,, +numpy/_pyinstaller/tests/__pycache__/test_pyinstaller.cpython-312.pyc,, +numpy/_pyinstaller/tests/pyinstaller-smoke.py,sha256=xt3dl_DjxuzVTPrqmVmMOZm5-24wBG2TxldQl78Xt1g,1175 +numpy/_pyinstaller/tests/test_pyinstaller.py,sha256=31zWlvlAC2sfhdew97x8aDvcYUaV3Tc_0CwFk8pgKaM,1170 +numpy/_pytesttester.py,sha256=USOh37bWhXAzQLeGD1U63XpDnbkatfr-aiQu-gHkdBA,6529 +numpy/_pytesttester.pyi,sha256=Rbl_BWY754H8JGfNwexVusncuX-3XOQv2PdW0Ua-FxI,521 +numpy/_typing/__init__.py,sha256=KACZs_8l8cNG4TolvZkqv5YKLA7EyG6om9ct4fsXppg,5639 +numpy/_typing/__pycache__/__init__.cpython-312.pyc,, +numpy/_typing/__pycache__/_add_docstring.cpython-312.pyc,, +numpy/_typing/__pycache__/_array_like.cpython-312.pyc,, +numpy/_typing/__pycache__/_char_codes.cpython-312.pyc,, +numpy/_typing/__pycache__/_dtype_like.cpython-312.pyc,, +numpy/_typing/__pycache__/_extended_precision.cpython-312.pyc,, +numpy/_typing/__pycache__/_nbit.cpython-312.pyc,, +numpy/_typing/__pycache__/_nbit_base.cpython-312.pyc,, +numpy/_typing/__pycache__/_nested_sequence.cpython-312.pyc,, +numpy/_typing/__pycache__/_scalars.cpython-312.pyc,, +numpy/_typing/__pycache__/_shape.cpython-312.pyc,, +numpy/_typing/__pycache__/_ufunc.cpython-312.pyc,, +numpy/_typing/_add_docstring.py,sha256=Oje462jvQMs5dDxRFWrDiKdK08-5sU-b6WKoSRAg2B4,4152 +numpy/_typing/_array_like.py,sha256=N-e4p17RNfe7H3jnpcX0cUXur4AIcjiTi95baW-0EZY,4294 +numpy/_typing/_char_codes.py,sha256=VZvjzpRG1Ehf2frndiRLLbPRa59A6FocdwGwjHEOorM,8977 +numpy/_typing/_dtype_like.py,sha256=HCEugkIDjsGQBYhk6QfnFtRtD-2ZigCSKeSm_7Z9cz0,3978 +numpy/_typing/_extended_precision.py,sha256=3jaNHY4qJwWODLFWvlfUQROLblfqqFDjOlp8bHnhMBI,449 +numpy/_typing/_nbit.py,sha256=pjOpz0sIdhphsXMK0dCQeQWXsrDpxCVZrYJ1wmALf04,651 +numpy/_typing/_nbit_base.py,sha256=PnQt_VbBKX_Uj17g_0yfoUqwh0bnN3LEyFHgR6GzNaw,3152 +numpy/_typing/_nbit_base.pyi,sha256=-9bQ2dXrhwqyROh5WXWM1APeDzi8QlwjJEAox-sriOU,778 +numpy/_typing/_nested_sequence.py,sha256=gZZRCnko04ZbsGaLbAx9VSsvKPR7UuwuzRAxwd1FYX0,2584 +numpy/_typing/_scalars.py,sha256=rTil_dSaoBGmmGD9QQZ0NqEP2BeZtkOEK9ZayDMB-l0,964 +numpy/_typing/_shape.py,sha256=5csdB-yj390thRrWPnwU7LcVfq-wYnd8QvXyuGdjAX4,283 +numpy/_typing/_ufunc.py,sha256=lok5QhQ5aJBARpyVoffrbeuEJsJ5vA6DaJ4aHTeUhms,163 +numpy/_typing/_ufunc.pyi,sha256=KwQANghYtbDNTZT7QvVj_aW99FgEfnpxhb5zU__W0Nk,30596 +numpy/_utils/__init__.py,sha256=q3vMrxeBeeU9pvCvLOkodDgzZS5V1jeI1_UZd4BbzDU,3572 +numpy/_utils/__init__.pyi,sha256=j1KKiEZW0MOWI3lwRzyIr-pHVqjJWkjb-NlwQok8838,728 +numpy/_utils/__pycache__/__init__.cpython-312.pyc,, +numpy/_utils/__pycache__/_convertions.cpython-312.pyc,, +numpy/_utils/__pycache__/_inspect.cpython-312.pyc,, +numpy/_utils/__pycache__/_pep440.cpython-312.pyc,, +numpy/_utils/_convertions.py,sha256=vetZFqC1qB-Z9jvc7RKuU_5ETOaSbjhbKa-sVwYV8TU,347 +numpy/_utils/_convertions.pyi,sha256=zkZfkdBk6-XcyD3zmr7E5sJbYasvyDCInUtWvrtjVhY,122 +numpy/_utils/_inspect.py,sha256=fpHbL1Gx7flw4HHjnNHNN-v8NKx1WgFBWgnX8T5hliY,7628 +numpy/_utils/_inspect.pyi,sha256=JLkhqPtHYvfBg5CN0VfGhO0u3ilzZGBThIfwxbk8YrI,2324 +numpy/_utils/_pep440.py,sha256=MZ5ZR1-o_4kA-68YcdUfkHkqUf3wRcKxQm08uv2GoE8,14474 +numpy/_utils/_pep440.pyi,sha256=cFEepudci4bYPJbIVshObOtflKvxGJVISkfemy8FPz8,3964 +numpy/char/__init__.py,sha256=KAKgke3wwjmEwxfiwkEXehe17DoN1OR_vkLBA9WFaGs,95 +numpy/char/__init__.pyi,sha256=XN-Twg_XKK4bMmir1UZ4nCtlW7nOezcU5Ix4N7X4OhQ,1651 +numpy/char/__pycache__/__init__.cpython-312.pyc,, +numpy/conftest.py,sha256=XdNfW6RkzEfbsZzdGxheAxmiAlH84kBueZKTN75WR7c,8900 +numpy/core/__init__.py,sha256=mCDTG1UnW38pcRG0sikf7oE2oP4MpO86ndHjquhL85U,1323 +numpy/core/__init__.pyi,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/core/__pycache__/__init__.cpython-312.pyc,, +numpy/core/__pycache__/_dtype.cpython-312.pyc,, +numpy/core/__pycache__/_dtype_ctypes.cpython-312.pyc,, +numpy/core/__pycache__/_internal.cpython-312.pyc,, +numpy/core/__pycache__/_multiarray_umath.cpython-312.pyc,, +numpy/core/__pycache__/_utils.cpython-312.pyc,, +numpy/core/__pycache__/arrayprint.cpython-312.pyc,, +numpy/core/__pycache__/defchararray.cpython-312.pyc,, +numpy/core/__pycache__/einsumfunc.cpython-312.pyc,, +numpy/core/__pycache__/fromnumeric.cpython-312.pyc,, +numpy/core/__pycache__/function_base.cpython-312.pyc,, +numpy/core/__pycache__/getlimits.cpython-312.pyc,, +numpy/core/__pycache__/multiarray.cpython-312.pyc,, +numpy/core/__pycache__/numeric.cpython-312.pyc,, +numpy/core/__pycache__/numerictypes.cpython-312.pyc,, +numpy/core/__pycache__/overrides.cpython-312.pyc,, +numpy/core/__pycache__/records.cpython-312.pyc,, +numpy/core/__pycache__/shape_base.cpython-312.pyc,, +numpy/core/__pycache__/umath.cpython-312.pyc,, +numpy/core/_dtype.py,sha256=BW-GFvu8BQiN-j6-3mESSWN3IQv9w8wNa3N53lisryI,333 +numpy/core/_dtype.pyi,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/core/_dtype_ctypes.py,sha256=pwXec_vp-L06nnzFO66mwjBuPpJPhICecnyfvW2yEMg,361 +numpy/core/_dtype_ctypes.pyi,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/core/_internal.py,sha256=i8Uf68tmcvQEmYoRWF3YqnJGCWI3GxZZEAecy5euNqg,976 +numpy/core/_multiarray_umath.py,sha256=zstXKBlwOv7q3YjVdb-zn4ypnyyI6fAGc6ahkEBav-g,2155 +numpy/core/_utils.py,sha256=dAaZtXVWhOEFiwmVsz8Mn77HsynMDKhZ7HkrjD1Q3vc,944 +numpy/core/arrayprint.py,sha256=zsOt7vFu-b1_7rPlKr7iGh12n4CmwzmU_fWV2CedPi4,349 +numpy/core/defchararray.py,sha256=4JjDjl62Abk7fNp-HZeuNSQUNNKJddNro6mD6ef4gq8,357 +numpy/core/einsumfunc.py,sha256=cW79vhPJJsi2oD-rXc_w5EKq4hlRo1YlyqI3ZnmsMx8,349 +numpy/core/fromnumeric.py,sha256=HD3e5PrYjtMOYQCMXTGZlgkikwvYWc1XRuNT5xhSxVg,353 +numpy/core/function_base.py,sha256=z5aEiXHQ4AAkHfGLQ8ul_hvjCWL2lDkgPLlWJE_4w-M,361 +numpy/core/getlimits.py,sha256=Tut0lg_HyjJXHSfB3c0Z0DvOR7amxUksqI_1MpOlXAo,345 +numpy/core/multiarray.py,sha256=nN54eP9dzhnY4oNoVBN2q7yDjF1w7PbMQx4a7oMqTVI,818 +numpy/core/numeric.py,sha256=Qev9oaDAGdyblrDjVXBzTY069E8Z-R3PIOnDp3K6XRY,372 +numpy/core/numerictypes.py,sha256=CHNOCimC3CarkejHOm-rV7b7bmykIlJAAhXj923pKq0,357 +numpy/core/overrides.py,sha256=wETB95vH9MSwFC3rg3GAUGozKJbCuKdVMhS_zC5baUw,345 +numpy/core/overrides.pyi,sha256=HScieJk23k4Lk14q8u9CEc3ZEVOQ6hGu_FeWDR2Tyu8,532 +numpy/core/records.py,sha256=xWh78TWkPZxZx5VY05Jia8-y1HyIzkEvmrF8BiKBb68,337 +numpy/core/shape_base.py,sha256=BWl-Of1Gl8nr0eBguDIdKbS5h9OdmO-VZPUQOe2e62Y,349 +numpy/core/umath.py,sha256=XggXI2bTIR9O4U2vyfgoja0kKI2q7sF3dMCWmukWIqQ,329 +numpy/ctypeslib/__init__.py,sha256=o9oMM6-vOwS4PVageFyXsh6x23hQtcsemoAVVR3kuHw,206 +numpy/ctypeslib/__init__.pyi,sha256=GTndWDhLTrUX0PBarv8JhXsXJXDPghNd6tZL3nd1ZYY,382 +numpy/ctypeslib/__pycache__/__init__.cpython-312.pyc,, +numpy/ctypeslib/__pycache__/_ctypeslib.cpython-312.pyc,, +numpy/ctypeslib/_ctypeslib.py,sha256=ry2JWVuqOh8IjE_m_UIyQoOpWkYoDue2xZAa3Mz8zdc,19682 +numpy/ctypeslib/_ctypeslib.pyi,sha256=7WyPfrcJRmdXKjiArSGGkJ9d3PcYJTi87CXgtes7ARU,8531 +numpy/doc/__pycache__/ufuncs.cpython-312.pyc,, +numpy/doc/ufuncs.py,sha256=jMnfQhRknVIhgFVS9z2l5oYM8N1tuQtf5bXMBL449oI,5552 +numpy/dtypes.py,sha256=cPkS6BLRvpfsUzhd7Vk1L7_VcenWb1nuHuCxc9fYC4I,1353 +numpy/dtypes.pyi,sha256=FqSJWLCA-I3MV8OHMluYNSLG6r1doOr6gFcOsYeFVxk,16159 +numpy/exceptions.py,sha256=HgT_ErZLiTfceCv0y2dYoestDpKt2IR66MHu-LAVpNI,7955 +numpy/exceptions.pyi,sha256=EdR0sub_Tjf2-7aPz_4VUGkLqc1w2MIDQjywR68x9C4,821 +numpy/f2py/__init__.py,sha256=1sHuSvD-wFPLK6vD_pjY527X4KP8Jlz3bsbqY2ImAaI,2534 +numpy/f2py/__init__.pyi,sha256=PDHjLyKbEWWTjnWcBuO0A6yVpG5lkMcyNPbwNl-R6IQ,118 +numpy/f2py/__main__.py,sha256=TDesy_2fDX-g27uJt4yXIXWzSor138R2t2V7HFHwqAk,135 +numpy/f2py/__pycache__/__init__.cpython-312.pyc,, +numpy/f2py/__pycache__/__main__.cpython-312.pyc,, +numpy/f2py/__pycache__/__version__.cpython-312.pyc,, +numpy/f2py/__pycache__/_isocbind.cpython-312.pyc,, +numpy/f2py/__pycache__/_src_pyf.cpython-312.pyc,, +numpy/f2py/__pycache__/auxfuncs.cpython-312.pyc,, +numpy/f2py/__pycache__/capi_maps.cpython-312.pyc,, +numpy/f2py/__pycache__/cb_rules.cpython-312.pyc,, +numpy/f2py/__pycache__/cfuncs.cpython-312.pyc,, +numpy/f2py/__pycache__/common_rules.cpython-312.pyc,, +numpy/f2py/__pycache__/crackfortran.cpython-312.pyc,, +numpy/f2py/__pycache__/diagnose.cpython-312.pyc,, +numpy/f2py/__pycache__/f2py2e.cpython-312.pyc,, +numpy/f2py/__pycache__/f90mod_rules.cpython-312.pyc,, +numpy/f2py/__pycache__/func2subr.cpython-312.pyc,, +numpy/f2py/__pycache__/rules.cpython-312.pyc,, +numpy/f2py/__pycache__/symbolic.cpython-312.pyc,, +numpy/f2py/__pycache__/use_rules.cpython-312.pyc,, +numpy/f2py/__version__.py,sha256=u3yEZEhZzW9QwLBqzFEO-zZDqsECiHs3ixdOlRnv9Jo,49 +numpy/f2py/__version__.pyi,sha256=8GyGk3Z3JL6jXsqXbhheqYSqtp9zqapNanxA7fHf_uA,46 +numpy/f2py/_backends/__init__.py,sha256=xIVHiF-velkBDPKwFS20PSg-XkFW5kLAVj5CSqNLddM,308 +numpy/f2py/_backends/__init__.pyi,sha256=RC41nCG_RhaOllATOhrOdFFDHGDEErv56plcdVo2GMM,141 +numpy/f2py/_backends/__pycache__/__init__.cpython-312.pyc,, +numpy/f2py/_backends/__pycache__/_backend.cpython-312.pyc,, +numpy/f2py/_backends/__pycache__/_distutils.cpython-312.pyc,, +numpy/f2py/_backends/__pycache__/_meson.cpython-312.pyc,, +numpy/f2py/_backends/_backend.py,sha256=9cxRVrA-5wcm2fnVdR-F08sYwGBf89ZZ7bl5VHqKabU,1195 +numpy/f2py/_backends/_backend.pyi,sha256=S3xxAntiuMAjkWSQgBX32XiB7AMlwb4SNahYmpUeSG0,1388 +numpy/f2py/_backends/_distutils.py,sha256=0SMBqxZgJBhfgX3HW0pEcL3S0qUFVCdSEsTLv1cEcJs,2461 +numpy/f2py/_backends/_distutils.pyi,sha256=HHVnI_ozA7-RQIcj-x_DW_crVJPNDSDk6CYVECtHABM,476 +numpy/f2py/_backends/_meson.py,sha256=8lnllh-SRsgnpwI-cZTWYLdG93wnkkXfjMH3uIejOaQ,8870 +numpy/f2py/_backends/_meson.pyi,sha256=kH_ZNzIbH0dM7oqB71VIuyDlkNDQQXlysJ6fzbt55cA,1960 +numpy/f2py/_backends/meson.build.template,sha256=0RdmYsEP0o6g7DJgWvSl3Mo18bu_IFS3zMusQ_T7fsI,1725 +numpy/f2py/_isocbind.py,sha256=QVoR_pD_bY9IgTaSHHUw_8EBg0mkaf3JZfwhLfHbz1Q,2422 +numpy/f2py/_isocbind.pyi,sha256=ByVGplEnG_CaErwiRY5khEoIICe4kFGm416sJnIh68s,352 +numpy/f2py/_src_pyf.py,sha256=u6eLk_jbxlnY3roCebGAk6wYrYJ79ZQUgl89Ck1uafI,7942 +numpy/f2py/_src_pyf.pyi,sha256=5bfPvrUIVP_e2hqhEbpe5y_ja6rcHxlDVe6gXVR69fI,1039 +numpy/f2py/auxfuncs.py,sha256=np0s118cTsP2XIJVdyFbyDMRq-3KF_IbuKQaE3Xt-rQ,27924 +numpy/f2py/auxfuncs.pyi,sha256=MizhsYeYkzJfY1HPxFC6YSr-Vwu2xpd6ImyLuItTmlQ,8254 +numpy/f2py/capi_maps.py,sha256=ncBlu6yE8AVLpMuyTeKL4gVncCeJj708gSXiHxnwgmY,30890 +numpy/f2py/capi_maps.pyi,sha256=2b-Sg7dCr0RqxWZ9FmLm4Vgfs9chnuaVWYZCsC4gDFY,1099 +numpy/f2py/cb_rules.py,sha256=Ad-tkBGZdwjsPyC4v8zmh7c5v5mIOKybO6k9lNrlf9g,25716 +numpy/f2py/cb_rules.pyi,sha256=VYhLJlRKpe2jE2XTKXHmljol-R09YK8tWscZ28pMicI,512 +numpy/f2py/cfuncs.py,sha256=V9GZ2E3s0_rragphRwNaCxq5Z3Mvbw-UDBR7wdApbnE,54223 +numpy/f2py/cfuncs.pyi,sha256=fWlbI1vH3IdXj3hmrda5Cl_wocO5Fn3uwTUoHBc_6Mg,833 +numpy/f2py/common_rules.py,sha256=HJ21QrdclhsGHj883Ab337-bSlPZopPALzXIMNfkT6c,5173 +numpy/f2py/common_rules.pyi,sha256=2d2LfXQr_st4cPnCZPQq5_hK9sTqj2436_t7Bf0PiSs,332 +numpy/f2py/crackfortran.py,sha256=3uovq4FHMoecI-qTZLi7vdUjFWJRdn94JidlFCHeQ_E,150604 +numpy/f2py/crackfortran.pyi,sha256=10qrHERdQbbr2hOSIP3V6w9gQJT6wrYpFCgS9-C4Bb8,10564 +numpy/f2py/diagnose.py,sha256=-UK2lwqufbuTqSex3w2H4-Qld7Z1NeutRllDNt6TDoA,5224 +numpy/f2py/diagnose.pyi,sha256=IW41dCKF39vknytu9aOQwmIWuk_WsCfkin8K1iFbmAc,24 +numpy/f2py/f2py2e.py,sha256=GJ-p9MAkTyhkyQ589ywmv5XiCPZkGy8larMERXyUi8c,29615 +numpy/f2py/f2py2e.pyi,sha256=2pETEpU4CJSky8mY9eBk_6z6Py63KDpINHwTFo-e1n8,2205 +numpy/f2py/f90mod_rules.py,sha256=GjvlboOdjc-lLmC0Tkxa8q_43fkfmo9dbWwv70xN_zI,10079 +numpy/f2py/f90mod_rules.pyi,sha256=0LIlPT9YI3Oit8aiP-i_JJPRsczDwzzQ96v14gMS1T0,467 +numpy/f2py/func2subr.py,sha256=p15rYW8c2kO-toes2Q9B9cjw9o9Jn-7pphHuxl0Jws0,10374 +numpy/f2py/func2subr.pyi,sha256=ide-SEoLyEEfa51Wqe6eKRJZvnuNYDJqD7BS0akqqzQ,393 +numpy/f2py/rules.py,sha256=U2u9J0IuC8hTJyNDO_jVdhfFrAxjsmW40y5edKDYMXQ,64723 +numpy/f2py/rules.pyi,sha256=x84T8VJwo8hmlLwpW54Q_q2ifUS5Dop9o0SHhyuxF48,1348 +numpy/f2py/setup.cfg,sha256=828sy3JvJmMzVxLkC-y0lxcEMaDTnMc3l9dWqP4jYng,50 +numpy/f2py/src/fortranobject.c,sha256=1SGmjDcW3_Ncx-aecMyjA_JfxyaW0TX6FL3mmG6wO10,47892 +numpy/f2py/src/fortranobject.h,sha256=uCcHO8mjuANlKb3c7YAZwM4pgT0CTaXWLYqgE27Mnt0,5996 +numpy/f2py/symbolic.py,sha256=YFKXeeLb5pq9cBDHLcJRq1eECpTlj0xQAsN8IKbMWgU,54828 +numpy/f2py/symbolic.pyi,sha256=BZrNj7NiDC5YZCVpnO7c7jtQETAnRokXEuUIMbg9hzM,6283 +numpy/f2py/tests/__init__.py,sha256=l38bo7dpp3u1lVMPErlct_5uBLKj35zuS_r35e7c19c,345 +numpy/f2py/tests/__pycache__/__init__.cpython-312.pyc,, +numpy/f2py/tests/__pycache__/test_abstract_interface.cpython-312.pyc,, +numpy/f2py/tests/__pycache__/test_array_from_pyobj.cpython-312.pyc,, +numpy/f2py/tests/__pycache__/test_assumed_shape.cpython-312.pyc,, +numpy/f2py/tests/__pycache__/test_block_docstring.cpython-312.pyc,, +numpy/f2py/tests/__pycache__/test_callback.cpython-312.pyc,, +numpy/f2py/tests/__pycache__/test_character.cpython-312.pyc,, +numpy/f2py/tests/__pycache__/test_common.cpython-312.pyc,, +numpy/f2py/tests/__pycache__/test_crackfortran.cpython-312.pyc,, +numpy/f2py/tests/__pycache__/test_data.cpython-312.pyc,, +numpy/f2py/tests/__pycache__/test_docs.cpython-312.pyc,, +numpy/f2py/tests/__pycache__/test_f2cmap.cpython-312.pyc,, +numpy/f2py/tests/__pycache__/test_f2py2e.cpython-312.pyc,, +numpy/f2py/tests/__pycache__/test_isoc.cpython-312.pyc,, +numpy/f2py/tests/__pycache__/test_kind.cpython-312.pyc,, +numpy/f2py/tests/__pycache__/test_mixed.cpython-312.pyc,, +numpy/f2py/tests/__pycache__/test_modules.cpython-312.pyc,, +numpy/f2py/tests/__pycache__/test_parameter.cpython-312.pyc,, +numpy/f2py/tests/__pycache__/test_pyf_src.cpython-312.pyc,, +numpy/f2py/tests/__pycache__/test_quoted_character.cpython-312.pyc,, +numpy/f2py/tests/__pycache__/test_regression.cpython-312.pyc,, +numpy/f2py/tests/__pycache__/test_return_character.cpython-312.pyc,, +numpy/f2py/tests/__pycache__/test_return_complex.cpython-312.pyc,, +numpy/f2py/tests/__pycache__/test_return_integer.cpython-312.pyc,, +numpy/f2py/tests/__pycache__/test_return_logical.cpython-312.pyc,, +numpy/f2py/tests/__pycache__/test_return_real.cpython-312.pyc,, +numpy/f2py/tests/__pycache__/test_routines.cpython-312.pyc,, +numpy/f2py/tests/__pycache__/test_semicolon_split.cpython-312.pyc,, +numpy/f2py/tests/__pycache__/test_size.cpython-312.pyc,, +numpy/f2py/tests/__pycache__/test_string.cpython-312.pyc,, +numpy/f2py/tests/__pycache__/test_symbolic.cpython-312.pyc,, +numpy/f2py/tests/__pycache__/test_value_attrspec.cpython-312.pyc,, +numpy/f2py/tests/__pycache__/util.cpython-312.pyc,, +numpy/f2py/tests/src/abstract_interface/foo.f90,sha256=aCaFEqfXp79pVXnTFtjZBWUY_5pu8wsehp1dEauOkSE,692 +numpy/f2py/tests/src/abstract_interface/gh18403_mod.f90,sha256=y3R2dDn0BUz-0bMggfT1jwXbhz_gniz7ONMpureEQew,111 +numpy/f2py/tests/src/array_from_pyobj/wrapmodule.c,sha256=bwr4ytJ-NtqWE_1Map5U3wPf_BC7pOe1oK94yNNQ5DM,7716 +numpy/f2py/tests/src/assumed_shape/.f2py_f2cmap,sha256=zfuOShmuotzcLIQDnVFaARwvM66iLrOYzpquIGDbiKU,30 +numpy/f2py/tests/src/assumed_shape/foo_free.f90,sha256=fqbSr7VlKfVrBulFgQtQA9fQf0mQvVbLi94e4FTST3k,494 +numpy/f2py/tests/src/assumed_shape/foo_mod.f90,sha256=9pbi88-uSNP5IwS49Kim982jDAuopo3tpEhg2SOU7no,540 +numpy/f2py/tests/src/assumed_shape/foo_use.f90,sha256=9Cl1sdrihB8cCSsjoQGmOO8VRv9ni8Fjr0Aku1UdEWM,288 +numpy/f2py/tests/src/assumed_shape/precision.f90,sha256=3L_F7n5ju9F0nxw95uBUaPeuiDOw6uHvB580eIj7bqI,134 +numpy/f2py/tests/src/block_docstring/foo.f,sha256=KVTeqSFpI94ibYIVvUW6lOQ9T2Bx5UzZEayP8Maf2H0,103 +numpy/f2py/tests/src/callback/foo.f,sha256=rLqaaaUpWFTaGVxNoGERtDKGCa5dLCTW5DglsFIx-wU,1316 +numpy/f2py/tests/src/callback/gh17797.f90,sha256=-_NvQK0MzlSR72PSuUE1FeUzzsMBUcPKsbraHIF7O24,155 +numpy/f2py/tests/src/callback/gh18335.f90,sha256=n_Rr99cI7iHBEPV3KGLEt0QKZtItEUKDdQkBt0GKKy4,523 +numpy/f2py/tests/src/callback/gh25211.f,sha256=ejY_ssadbZQfD5_-Xnx_ayzWXWLjkdy7DGp6C_uCUCY,189 +numpy/f2py/tests/src/callback/gh25211.pyf,sha256=nrzvt2QHZRCcugg0R-4FDMMl1MJmWCOAjR7Ta-pXz7Y,465 +numpy/f2py/tests/src/callback/gh26681.f90,sha256=ykwNXWyja5FfZk1bPihbYiMmMlbKhRPoPKva9dNFtLM,584 +numpy/f2py/tests/src/cli/gh_22819.pyf,sha256=e3zYjFmiOxzdXoxzgkaQ-CV6sZ1t4aKugyhqRXmBNdQ,148 +numpy/f2py/tests/src/cli/hi77.f,sha256=bgBERF4EYxHlzJCvZCJOlEmUE1FIvipdmj4LjdmL_dE,74 +numpy/f2py/tests/src/cli/hiworld.f90,sha256=RncaEqGWmsH9Z8BMV-UmOTUyo3-e9xOQGAmNgDv6SfY,54 +numpy/f2py/tests/src/common/block.f,sha256=tcGKa42S-6bfA6fybpM0Su_xjysEVustkEJoF51o_pE,235 +numpy/f2py/tests/src/common/gh19161.f90,sha256=Vpb34lRVC96STWaJerqkDQeZf7mDOwWbud6pW62Tvm4,203 +numpy/f2py/tests/src/crackfortran/accesstype.f90,sha256=3ONHb4ZNx0XISvp8fArnUwR1W9rzetLFILTiETPUd80,221 +numpy/f2py/tests/src/crackfortran/common_with_division.f,sha256=JAzHD5aluoYw0jVGZjBYd1wTABU0PwNBD0cz3Av5AAk,511 +numpy/f2py/tests/src/crackfortran/data_common.f,sha256=rP3avnulWqJbGCFLWayjoFKSspGDHZMidPTurjz33Tc,201 +numpy/f2py/tests/src/crackfortran/data_multiplier.f,sha256=LaPXVuo5lX0gFZVh76Hc7LM1sMk9EBPALuXBnHAGdOA,202 +numpy/f2py/tests/src/crackfortran/data_stmts.f90,sha256=MAZ3gstsPqECk3nWQ5Ql-C5udrIv3sAciW1ZGTtHLts,713 +numpy/f2py/tests/src/crackfortran/data_with_comments.f,sha256=FUPluNth5uHgyKqjQW7HKmyWg4wDXj3XPJCIC9ZZuOs,183 +numpy/f2py/tests/src/crackfortran/foo_deps.f90,sha256=D9FT8Rx-mK2p8R6r4bWxxqgYhkXR6lNmPj2RXOseMpw,134 +numpy/f2py/tests/src/crackfortran/gh15035.f,sha256=0G9bmfVafpuux4-ZgktYZ6ormwrWDTOhKMK4wmiSZlQ,391 +numpy/f2py/tests/src/crackfortran/gh17859.f,sha256=acknjwoWYdA038oliYLjB4T1PHhXkKRLeJobIgB_Lbo,352 +numpy/f2py/tests/src/crackfortran/gh22648.pyf,sha256=xPnKx4RcT1568q-q_O83DYpCgVYJ8z4WQ-yLmHPchJA,248 +numpy/f2py/tests/src/crackfortran/gh23533.f,sha256=k2xjRpRaajMYpi5O-cldYPTZGFGB12PUGcj5Fm9joyk,131 +numpy/f2py/tests/src/crackfortran/gh23598.f90,sha256=20ukdZXq-qU0Zxzt4W6cO8tRxlNlQ456zgD09zdozCE,105 +numpy/f2py/tests/src/crackfortran/gh23598Warn.f90,sha256=FvnIxy5fEOvzNb5WSkWzPk7yZ9yIv0yPZk9vNnS-83w,216 +numpy/f2py/tests/src/crackfortran/gh23879.f90,sha256=jELVfEGEF66z_Pv_iBHp3yGsGhadB0dnKCDtPcaz_CM,352 +numpy/f2py/tests/src/crackfortran/gh27697.f90,sha256=mTOEncxZlam6N-3I-IL0ua-iLkgqDrrVXNsE-7y7jAM,376 +numpy/f2py/tests/src/crackfortran/gh2848.f90,sha256=-IpkeTz0j9_lkQeN9mT7w3U1cAJjQxSMdAmyHdF8oVg,295 +numpy/f2py/tests/src/crackfortran/operators.f90,sha256=cb1JO2hIMCQejZO_UJWluBCP8LdXQbBJw2XN6YHB3JA,1233 +numpy/f2py/tests/src/crackfortran/privatemod.f90,sha256=9O2oWEquIUcbDB1wIzNeae3hx4gvXAoYW5tGfBt3KWk,185 +numpy/f2py/tests/src/crackfortran/publicmod.f90,sha256=nU_VXCKiniiUq_78KAWkXiN6oiMQh39emMxbgOVf9cg,177 +numpy/f2py/tests/src/crackfortran/pubprivmod.f90,sha256=-uz75kquU4wobaAPZ1DLKXJg6ySCZoDME1ce6YZ2q5Y,175 +numpy/f2py/tests/src/crackfortran/unicode_comment.f90,sha256=wDMoF7F7VFYdeocfTyWIh7noniEwExVb364HrhUSbSg,102 +numpy/f2py/tests/src/f2cmap/.f2py_f2cmap,sha256=fwszymaWhcWO296u5ThHW5yMAkFhB6EtHWqqpc9FAVI,83 +numpy/f2py/tests/src/f2cmap/isoFortranEnvMap.f90,sha256=rphN_mmzjCCCkdPM0HjsiJV7rmxpo4GoCNp5qmBzv8U,307 +numpy/f2py/tests/src/isocintrin/isoCtests.f90,sha256=Oir0PfE3mErnUQ42aFxiqAkcYn3B6b1FHIPGipDdekg,1032 +numpy/f2py/tests/src/kind/foo.f90,sha256=6_zq3OAWsuNJ5ftGTQAEynkHy-MnuLgBXmMIgbvL7yU,367 +numpy/f2py/tests/src/mixed/foo.f,sha256=Zgn0xDhhzfas3HrzgVSxIL1lGEF2mFRVohrvXN1thU0,90 +numpy/f2py/tests/src/mixed/foo_fixed.f90,sha256=6eEEYCH71gPp6lZ6e2afLrfS6F_fdP7GZDbgGJJ_6ns,187 +numpy/f2py/tests/src/mixed/foo_free.f90,sha256=UC6iVRcm0-aVXAILE5jZhivoGQbKU-prqv59HTbxUJA,147 +numpy/f2py/tests/src/modules/gh25337/data.f90,sha256=EqMEuEV0_sx4XbFzftbU_6VfGtOw9Tbs0pm0eVEp2cA,188 +numpy/f2py/tests/src/modules/gh25337/use_data.f90,sha256=DChVLgD7qTOpbYNmfGjPjfOx5YsphMIYwdwnF12X4xM,185 +numpy/f2py/tests/src/modules/gh26920/two_mods_with_no_public_entities.f90,sha256=MMLPSzBwuGS4UwCXws9djH11F5tG5xFLc80CDb4U9Mk,423 +numpy/f2py/tests/src/modules/gh26920/two_mods_with_one_public_routine.f90,sha256=1dJD1kDC_wwn7v_zF49D3n62T1x9wFxGKanQQz_VI7k,424 +numpy/f2py/tests/src/modules/module_data_docstring.f90,sha256=-asnMH7vZMwVIeMU2YiLWgYCUUUxZgPTpbAomgWByHs,236 +numpy/f2py/tests/src/modules/use_modules.f90,sha256=bveSAqXIZtd4NMlDfFei1ZlesFAa9An5LjkD-gDk2ms,418 +numpy/f2py/tests/src/negative_bounds/issue_20853.f90,sha256=IxBGWem-uv9eHgDhysEdGTmNKHR1gAiU7YJPo20eveM,164 +numpy/f2py/tests/src/parameter/constant_array.f90,sha256=fkYemwIBKsP63-FGKBW8mzOAp6k13eZOin8sQe1pyno,1513 +numpy/f2py/tests/src/parameter/constant_both.f90,sha256=L0rG6-ClvHx7Qsch46BUXRi_oIEL0uw5dpRHdOUQuv0,1996 +numpy/f2py/tests/src/parameter/constant_compound.f90,sha256=lAT76HcXGMgr1NfKof-RIX3W2P_ik1PPqkRdJ6EyBmM,484 +numpy/f2py/tests/src/parameter/constant_integer.f90,sha256=42jROArrG7vIag9wFa_Rr5DBnnNvGsrEUgpPU14vfIo,634 +numpy/f2py/tests/src/parameter/constant_non_compound.f90,sha256=u9MRf894Cw0MVlSOUbMSnFSHP4Icz7RBO21QfMkIl-Q,632 +numpy/f2py/tests/src/parameter/constant_real.f90,sha256=QoPgKiHWrwI7w5ctYZugXWzaQsqSfGMO7Jskbg4CLTc,633 +numpy/f2py/tests/src/quoted_character/foo.f,sha256=0zXQbdaqB9nB8R4LF07KDMFDbxlNdiJjVdR8Nb3nzIM,496 +numpy/f2py/tests/src/regression/AB.inc,sha256=ydjTVb6QEw1iYw2tRiziqqzWcDHrJsNWr3m51-rqFXQ,17 +numpy/f2py/tests/src/regression/assignOnlyModule.f90,sha256=vPJbhOlNsLrgN3su4ohHUSbxE4GGKU7SiJh7dhBvX3o,633 +numpy/f2py/tests/src/regression/datonly.f90,sha256=HuBLuEw0kNEplJ9TxxSNr7hLj-jx9ZNGaXC8iLm_kf8,409 +numpy/f2py/tests/src/regression/f77comments.f,sha256=FjP-07suTBdqgtwiENT04P-47UB4g9J5-20IQdXAHhM,652 +numpy/f2py/tests/src/regression/f77fixedform.f95,sha256=KdKFcAc3ZrID-h4nTOJDdEYfQzR2kkn9VqQCorfJGpM,144 +numpy/f2py/tests/src/regression/f90continuation.f90,sha256=VweFIi5-xxZhtgSOh8i_FjMPXu_od9qjrDHq6ma5X5k,285 +numpy/f2py/tests/src/regression/incfile.f90,sha256=gq87H2CtCZUON9V5UzcK6x_fthnWDVuPFQLa0fece1M,97 +numpy/f2py/tests/src/regression/inout.f90,sha256=TlMxJjhjjiuLI--Tg2LshLnbfZpiKz37EpR_tPKKSx8,286 +numpy/f2py/tests/src/regression/lower_f2py_fortran.f90,sha256=bWlj2Frch3onnUpd6DTaoLDa6htrrbkBiI9JIRbQPfE,105 +numpy/f2py/tests/src/regression/mod_derived_types.f90,sha256=Cb9WV1sxoKt2wJCl1Z9QR42iLYX226f_boX-_ehDLAQ,589 +numpy/f2py/tests/src/return_character/foo77.f,sha256=tRyQSu9vNWtMRi7gjmMN-IZnS7ogr5YS0n38uax_Eo0,1025 +numpy/f2py/tests/src/return_character/foo90.f90,sha256=WPQZC6CjXLbUYpzy5LItEoHmRDFxW0ABB3emRACsjZU,1296 +numpy/f2py/tests/src/return_complex/foo77.f,sha256=7-iKoamJ-VObPFR-Tslhiw9E-ItIvankWMyxU5HqxII,1018 +numpy/f2py/tests/src/return_complex/foo90.f90,sha256=_GOKOZeooWp3pEaTBrZNmPmkgGodj33pJnJmySnp7aE,1286 +numpy/f2py/tests/src/return_integer/foo77.f,sha256=EKs1KeAOQBkIO99tMCx0H7_lpqvqpjie8zWZ6T_bAR4,1234 +numpy/f2py/tests/src/return_integer/foo90.f90,sha256=0aYWcaAVs7Lw3Qbf8hupfLC8YavRuPZVIwjHecIlMOo,1590 +numpy/f2py/tests/src/return_logical/foo77.f,sha256=Ax3tBVNAlxFtHhV8fziFcsTnoa8YJdapecMr6Qj7fLk,1244 +numpy/f2py/tests/src/return_logical/foo90.f90,sha256=IZXCerFecYT24zTQ_spIoPr6n-fRncaM0tkTs8JqO1E,1590 +numpy/f2py/tests/src/return_real/foo77.f,sha256=3nAY1YtzGk4osR2jZkHMVIUHxFoOtF1OLfWswpcV7kA,978 +numpy/f2py/tests/src/return_real/foo90.f90,sha256=38ZCnBGWb9arlJdnVWvZjVk8uesrQN8wG2GrXGcSIJs,1242 +numpy/f2py/tests/src/routines/funcfortranname.f,sha256=ruyXK6eQSLQnQ_rODT1qm1cJvpHrFhI6NRrnWvEIK0U,128 +numpy/f2py/tests/src/routines/funcfortranname.pyf,sha256=EgRw8ZWGdd2uK4qCZD89r9VQtEXmnKDx59OpB0K58as,451 +numpy/f2py/tests/src/routines/subrout.f,sha256=35DjHIj85ZLkxRxP4bs-WFTQ5y1AyDqBKAXTzSSTAxE,94 +numpy/f2py/tests/src/routines/subrout.pyf,sha256=xT_WnDpvpyPb0FMRAVTRRgm3nlfALf1Ojg8x3qZNv_4,332 +numpy/f2py/tests/src/size/foo.f90,sha256=nK_767f1TtqVr-dMalNkXmcKbSbLCiabhRkxSDCzLz0,859 +numpy/f2py/tests/src/string/char.f90,sha256=X_soOEV8cKsVZefi3iLT7ilHljjvJJ_i9VEHWOt0T9Y,647 +numpy/f2py/tests/src/string/fixed_string.f90,sha256=tCN5sA6e7M1ViZtBNvTnO7_efk7BHIjyhFKBoLC3US0,729 +numpy/f2py/tests/src/string/gh24008.f,sha256=Z6cq8SFGvmaA72qeH9tu1rP8pYjqm0ONpHn7nGbhoLA,225 +numpy/f2py/tests/src/string/gh24662.f90,sha256=xJkiYvrMT9Ipb9Cq7OXl1Ev6TISl8pq1MGemySzfGd0,204 +numpy/f2py/tests/src/string/gh25286.f90,sha256=lqEl81Iu9GIDTAbOfkkNGcGgDyyGnPB44mJw2iK1kng,318 +numpy/f2py/tests/src/string/gh25286.pyf,sha256=wYkkr5gEN9_RtGjpqh28X1k8KCgh0-Ds9XAt8IC9j4A,393 +numpy/f2py/tests/src/string/gh25286_bc.pyf,sha256=ZRvgSzRlaPEx8GyNt97FrRhtCg-r4ZTEDsHNBfit4m8,396 +numpy/f2py/tests/src/string/scalar_string.f90,sha256=U1QqVgbF1DbxdFekRjchyDlFRPnXwzG72kuE8A44Za8,185 +numpy/f2py/tests/src/string/string.f,sha256=JCwLuH21Ltag5cw_9geIQQJ4Hv_39NqG8Dzbqj1eDKE,260 +numpy/f2py/tests/src/value_attrspec/gh21665.f90,sha256=MbbSUQI5Enzq46KWFHRzQbY7q6ZHJH_9NRL-C9i13Wg,199 +numpy/f2py/tests/test_abstract_interface.py,sha256=2fTmp5-yLaNKtWvP0jQ6_kqkyWI73kgjIl7Ara25cII,837 +numpy/f2py/tests/test_array_from_pyobj.py,sha256=Yy6I46hlJLgSAlQ_RkRbZgZ_vTyH9BVDE5OxQ5TQRvM,24395 +numpy/f2py/tests/test_assumed_shape.py,sha256=WaIBz38eV2AzRwOvTvTaRkNks8c3H_61TGKtAReP6gk,1517 +numpy/f2py/tests/test_block_docstring.py,sha256=DOTSbdInRJCunaEycMGWQUy0b5rIeugPxUKmNg8FA34,604 +numpy/f2py/tests/test_callback.py,sha256=uVRfXR6q4ukZfbRUBCnc1cvKIEiaPFr6gc3mrgMzt1w,7362 +numpy/f2py/tests/test_character.py,sha256=dLj5WhKbP5CYnuQMsB3uWV5pcgoQCEscujuBSCXwkwA,22572 +numpy/f2py/tests/test_common.py,sha256=r_nJN4ZCZ3DstAadAoO_R_igybcb5zxwOJsv_-fRBa8,667 +numpy/f2py/tests/test_crackfortran.py,sha256=QNZ9VI61XDF5KoO8r9012AaGaVHzM7g1e2UVK0A4uUU,16834 +numpy/f2py/tests/test_data.py,sha256=XBQTj0WqR-XWHuRhT1PWXankrhlNxeqC6S03XA2b7AI,2966 +numpy/f2py/tests/test_docs.py,sha256=YwIFQGu4gwCrnNQ0i4O3sCs_ZCwovgr2fGt13DrfKbU,1996 +numpy/f2py/tests/test_f2cmap.py,sha256=hyzKOv261wPDWAmpuidAVFK3x9WXm64U_r3E_bmxNXg,404 +numpy/f2py/tests/test_f2py2e.py,sha256=QHYd7ghKHeUPB-piK0zvoM-BkmrH1Tvg8-wa4r7wMMI,29552 +numpy/f2py/tests/test_isoc.py,sha256=KK4VeoPhjF658msdnRYCWlzagFEea8h5SzdjB5FaDk0,1490 +numpy/f2py/tests/test_kind.py,sha256=0kASrNopTkYDN_d2j-i9Jf22nBjQof0eqGGcuEfEqI0,1897 +numpy/f2py/tests/test_mixed.py,sha256=3J9eftoqFIXViiqd21Ej02eNztjbIuzaqb_2OZYZUSw,897 +numpy/f2py/tests/test_modules.py,sha256=rbm9cPZilhdIuFA6rxqtRlPtyd0_IxKoFlB8VFA-1Vc,2384 +numpy/f2py/tests/test_parameter.py,sha256=wwyq8vA5FFljYfF55srLYqFvJ-ybdG2vEpr2CRdPqVs,4763 +numpy/f2py/tests/test_pyf_src.py,sha256=Tg8PzypY1P2pda3k2VbuKX97VCD7CtdgyJajP-U7AIc,1177 +numpy/f2py/tests/test_quoted_character.py,sha256=kvjgkp3bIP2lnkZ2MzS2yB5ytEJfHZydz24VAqs3UKM,495 +numpy/f2py/tests/test_regression.py,sha256=TriZy41MAIYRAHweZ-dg9GYyVmIjaIkPL4bAqmiCm50,6369 +numpy/f2py/tests/test_return_character.py,sha256=bdryZo5fXfTUE35M3_8gDqPCa9RKtkxROqBcnTjuwYo,1582 +numpy/f2py/tests/test_return_complex.py,sha256=1Nb6IsRfzHTCCiBTU5nHoY36w--Uh2goTedK-d8Xrc4,2507 +numpy/f2py/tests/test_return_integer.py,sha256=X3hYAJX9QaC0MYsIXg1Po-FRh4KCRN0KW0UFVpdkDww,1868 +numpy/f2py/tests/test_return_logical.py,sha256=ob4-_KkwWohpwF45SWKxiCKtktReLuqg4WQ8YFcMOQ0,2113 +numpy/f2py/tests/test_return_real.py,sha256=e7I27OmdJGCDQ9vX12U29M3WCOcmU1KRsivRb6BkKvo,3382 +numpy/f2py/tests/test_routines.py,sha256=6hOB8Rn4M-MCgDhKMoqI3YIn274wyWBzaLTjrJrTYCw,824 +numpy/f2py/tests/test_semicolon_split.py,sha256=5K_jZ2rJLxvwRDQu0gd_yiOEKiJmngvrH8vLeqsbC0Y,1702 +numpy/f2py/tests/test_size.py,sha256=D-7AOZtUn0DekZr-K753WQIcnt0prEdLigSuzjEicFg,1200 +numpy/f2py/tests/test_string.py,sha256=X6ECwK-mh-0Dfp8Pcag-jWxidoXtt009QDfjc8sfGT8,3038 +numpy/f2py/tests/test_symbolic.py,sha256=-NUoAJeeHZ0_Uj4NFnjz0awFk7vTZJ2rtHOErY0kkyk,19061 +numpy/f2py/tests/test_value_attrspec.py,sha256=P3ypxCXsakygnP1IdXH1hzw5VaYKGN40z3SOwK61IPU,345 +numpy/f2py/tests/util.py,sha256=YVm0U_jGp_LRO7k4FszcuC5AqoNsnf-cc564vEljABk,12554 +numpy/f2py/use_rules.py,sha256=MX3S-9SkSznXTwWWwaccMBhhyE_ZyoG3MCLLnsXXHEE,3475 +numpy/f2py/use_rules.pyi,sha256=J7S58xd70JkQBKtzl01T3uKmGfskGO6TiosmxUMW62Y,433 +numpy/fft/__init__.py,sha256=G7Nr6rpJggN1e3PgGggExF6Ei_Wt8n57eQIXf5vtzLM,8369 +numpy/fft/__init__.pyi,sha256=a2GtovDgo6O66DqPN7iVMBhl-6v_MjkTi2F5GGnKIAs,531 +numpy/fft/__pycache__/__init__.cpython-312.pyc,, +numpy/fft/__pycache__/_helper.cpython-312.pyc,, +numpy/fft/__pycache__/_pocketfft.cpython-312.pyc,, +numpy/fft/_helper.py,sha256=VpGmqY4O7zZWm0vg72mGu3AsZ-bca_mVG-olxoJYmmI,7022 +numpy/fft/_helper.pyi,sha256=UHKdQi3Rjz73WadYmvDCyRf95MSBNao3l1WZlJJHljs,1420 +numpy/fft/_pocketfft.py,sha256=UVXDxPok9kPHCjqH2XqrSTQ33fSCMIFmx_46Wj6V0TU,64292 +numpy/fft/_pocketfft.pyi,sha256=ksJK_WTkhCPo4ZAfdApGI3-uoK6WGH3NIbrrBx1jg5k,3353 +numpy/fft/_pocketfft_umath.cp312-win_amd64.lib,sha256=48jI0hEWDOANKIPUrGbkXItn-opqswv5PsiaAbyLt6o,2176 +numpy/fft/_pocketfft_umath.cp312-win_amd64.pyd,sha256=VLBpRJysJ9vUQIdXVxN31IOrSXoeHgiG-J-FpypUccM,276480 +numpy/fft/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/fft/tests/__pycache__/__init__.cpython-312.pyc,, +numpy/fft/tests/__pycache__/test_helper.cpython-312.pyc,, +numpy/fft/tests/__pycache__/test_pocketfft.cpython-312.pyc,, +numpy/fft/tests/test_helper.py,sha256=Yff4EXasyH-nD6dyEcZfX4g61ZjQcAY7XHfQLnXI1EY,6321 +numpy/fft/tests/test_pocketfft.py,sha256=m98HSj9duHLP2IBxOXllDCj-92hNxCHgxFXXuExgqmI,25035 +numpy/lib/__init__.py,sha256=sZL_BFMWHTRmMAUWlbBJ-ngMCdk6UJ9FdU3n0S0SMEg,3101 +numpy/lib/__init__.pyi,sha256=PjSJHE90GngKOVep78JzBhBJFSBVCP5ZRrj0vMtG7G8,1547 +numpy/lib/__pycache__/__init__.cpython-312.pyc,, +numpy/lib/__pycache__/_array_utils_impl.cpython-312.pyc,, +numpy/lib/__pycache__/_arraypad_impl.cpython-312.pyc,, +numpy/lib/__pycache__/_arraysetops_impl.cpython-312.pyc,, +numpy/lib/__pycache__/_arrayterator_impl.cpython-312.pyc,, +numpy/lib/__pycache__/_datasource.cpython-312.pyc,, +numpy/lib/__pycache__/_format_impl.cpython-312.pyc,, +numpy/lib/__pycache__/_function_base_impl.cpython-312.pyc,, +numpy/lib/__pycache__/_histograms_impl.cpython-312.pyc,, +numpy/lib/__pycache__/_index_tricks_impl.cpython-312.pyc,, +numpy/lib/__pycache__/_iotools.cpython-312.pyc,, +numpy/lib/__pycache__/_nanfunctions_impl.cpython-312.pyc,, +numpy/lib/__pycache__/_npyio_impl.cpython-312.pyc,, +numpy/lib/__pycache__/_polynomial_impl.cpython-312.pyc,, +numpy/lib/__pycache__/_scimath_impl.cpython-312.pyc,, +numpy/lib/__pycache__/_shape_base_impl.cpython-312.pyc,, +numpy/lib/__pycache__/_stride_tricks_impl.cpython-312.pyc,, +numpy/lib/__pycache__/_twodim_base_impl.cpython-312.pyc,, +numpy/lib/__pycache__/_type_check_impl.cpython-312.pyc,, +numpy/lib/__pycache__/_ufunclike_impl.cpython-312.pyc,, +numpy/lib/__pycache__/_user_array_impl.cpython-312.pyc,, +numpy/lib/__pycache__/_utils_impl.cpython-312.pyc,, +numpy/lib/__pycache__/_version.cpython-312.pyc,, +numpy/lib/__pycache__/array_utils.cpython-312.pyc,, +numpy/lib/__pycache__/format.cpython-312.pyc,, +numpy/lib/__pycache__/introspect.cpython-312.pyc,, +numpy/lib/__pycache__/mixins.cpython-312.pyc,, +numpy/lib/__pycache__/npyio.cpython-312.pyc,, +numpy/lib/__pycache__/recfunctions.cpython-312.pyc,, +numpy/lib/__pycache__/scimath.cpython-312.pyc,, +numpy/lib/__pycache__/stride_tricks.cpython-312.pyc,, +numpy/lib/__pycache__/user_array.cpython-312.pyc,, +numpy/lib/_array_utils_impl.py,sha256=JQE9Ul515em350VcRXQaO4BmE0HwIRPdBpFNXu4Hnws,1759 +numpy/lib/_array_utils_impl.pyi,sha256=bymzyS0JT02-btcDJ90mhAVpoxnaZ9qJmIrfAg4I4nY,512 +numpy/lib/_arraypad_impl.py,sha256=rH_OU6Xvom3l4p2DbrhArQIPjsjM9EONxtSqKNzxd6g,34445 +numpy/lib/_arraypad_impl.pyi,sha256=aT7ma7wLUliNkdRK4j2XHEza25i0WzUJ-ETUPxYjCFU,2017 +numpy/lib/_arraysetops_impl.py,sha256=EVRhEQCqRxzheU68u5kGgS8pkls_sUSM9WXa9Z9Y3ho,38499 +numpy/lib/_arraysetops_impl.pyi,sha256=s-mUcIIa8xVOtYJx8WNnhPRrsnfMNUlBq1Imt66nCI0,13617 +numpy/lib/_arrayterator_impl.py,sha256=HUtCLBXcG7mC5AX3KuJcDjHD9FEPheCcHypT6PtSswY,7442 +numpy/lib/_arrayterator_impl.pyi,sha256=_vhCb927PfSM5E40NbAhIxxmcBxPhcpk9V4ZdzBTOIQ,1920 +numpy/lib/_datasource.py,sha256=csFfOVL00V76KM--z9wROAImHDPB5l5b-8h1AJli53c,23431 +numpy/lib/_datasource.pyi,sha256=g3laWGQw8jdnR8h_Bp9f1Mp71k5PmRxFBNuT1suuNqc,1025 +numpy/lib/_format_impl.py,sha256=_TFgQtrgndkQWxPSjdO95ld_cCgESpjsJ04BLqZPGNk,37920 +numpy/lib/_format_impl.pyi,sha256=OAyT3J74w528YjS9J_TV7rWtC8gXgBtXGn9IQ2Af5f8,2139 +numpy/lib/_function_base_impl.py,sha256=T8U10Vg7R3xpf9B5zvrWtLZmGSeb0OZfCQLIytnyeUk,199498 +numpy/lib/_function_base_impl.pyi,sha256=m0JuSD13oEeESW5jBSFnjJHkgLFsreEg0r-KwtqGNhU,77346 +numpy/lib/_histograms_impl.py,sha256=2dceYr7BOVTkypST4CVgskJzjI-ka_FrL5oxBW7rHEQ,39517 +numpy/lib/_histograms_impl.pyi,sha256=Kg1Q0AgAi6QatGM3paKB2VluGkUCKbtCM1gy4_atEhU,1095 +numpy/lib/_index_tricks_impl.py,sha256=ZzRtFdpbYtDEYox3-uzDtzEOILMZ0LdX67VkWNIyBpY,32567 +numpy/lib/_index_tricks_impl.pyi,sha256=So1jOZ2__eFpN9oS7NXgHDfKHBP9kVmX4IQp11KufK8,8483 +numpy/lib/_iotools.py,sha256=Yh7xIu5OnSNnj2aX-yW8viJNHNC33nhCDZtaep8TszE,31776 +numpy/lib/_iotools.pyi,sha256=epBkUTN7SvJbWiZ63WJOHCR6YUNICzk7UXE6ZqqPgXM,3768 +numpy/lib/_nanfunctions_impl.py,sha256=qmmx5H7q-atgoYQAWcDAHWOQ-WWXCrXyUewwzRygjss,73405 +numpy/lib/_nanfunctions_impl.pyi,sha256=cq5lGiV_WoVNwboSEenA6Zmzi0rBTMfK_NNiTHeZx7w,864 +numpy/lib/_npyio_impl.py,sha256=9mlk6CAckDnBIaOW1KxyePnNNUguRCE2co3lk2Xetjw,101219 +numpy/lib/_npyio_impl.pyi,sha256=fs-QJUwOMh6MTLE2fTfzK_e2Q16B7tszlProdbpcgUI,9793 +numpy/lib/_polynomial_impl.py,sha256=UqyQMpVAJRR6z9Hj9Rq7MK509cI8OncTkM2XLsYsmvU,45590 +numpy/lib/_polynomial_impl.pyi,sha256=Z92OU7G7sWt4lBdO9LYq_kn_3nA3HxOUEYQkP70MfEk,7887 +numpy/lib/_scimath_impl.py,sha256=VjysRI24mMd4GaaEy5e1npARDc0_TKgQqq6TRoiNdAY,16326 +numpy/lib/_scimath_impl.pyi,sha256=3-C37vHfGAP84SLbuxHrPAO8ZQ-vgTSXTyh5EjNHXh0,2867 +numpy/lib/_shape_base_impl.py,sha256=BbDGec_0jGK-YkAG0hY36eCE86a0tksMCF6ooLgYmVQ,40302 +numpy/lib/_shape_base_impl.pyi,sha256=ENzamOUsGz57nNl3w5juRq2RkWC4k0MpeVg1aWjV9W4,5777 +numpy/lib/_stride_tricks_impl.py,sha256=uuGAiZWcaK-N9dQkohbAtRlrYItoany4KAt4hIQs6N8,19697 +numpy/lib/_stride_tricks_impl.pyi,sha256=7zWJcIwwy9bIu-FjDQFZJA79GO6drAzf8QLkWzGQ7W0,2032 +numpy/lib/_twodim_base_impl.py,sha256=bKyDb9b4wvQADhgsUujOtJci0ztuvFo_5zQtsBHPlhI,35124 +numpy/lib/_twodim_base_impl.pyi,sha256=-vD7xZiLmOrK49OiYNwbF6vzkKXbSAYUnYIhqBrcJrM,13432 +numpy/lib/_type_check_impl.py,sha256=ONqM3mhe3ITonSZJZISpOJ_fk2WA4PrdecW-HUFvRHM,20624 +numpy/lib/_type_check_impl.pyi,sha256=C7guCWlJFMl_w0M2GjYFql8eOoF3kN1hgda1YKSbBU8,10042 +numpy/lib/_ufunclike_impl.py,sha256=DLbbgYDRSbyqmX3XzJTjOBRD5oOjUUEvpCViahyJqoA,6213 +numpy/lib/_ufunclike_impl.pyi,sha256=rS_jOTzvFASpAHFk6cdH8RGUrze2n5_FZnlgQeCRi5I,1774 +numpy/lib/_user_array_impl.py,sha256=NZi7p0dSNoEmUN4KR1aB1_gf9r0lYAe_rT1VNZCQc5w,8336 +numpy/lib/_user_array_impl.pyi,sha256=cbqaYFs4J-WBtMNKnSBviiIR0NDA5_g6_tAJpnuhqWE,9494 +numpy/lib/_utils_impl.py,sha256=QdnCyIkxeZaR2wwn4QXxXBCokxuXi-RG-J_GHG4eL-s,24283 +numpy/lib/_utils_impl.pyi,sha256=KTI0vNECNqvxwzhp3SrutN02KGV-WXna7q56IfDW8Uw,746 +numpy/lib/_version.py,sha256=J1pqujOE4R_kH7R1yxtimwbWVRxDNnBD82XIZ9ly1yY,4936 +numpy/lib/_version.pyi,sha256=zAmfNnFeke7_lHsvR94fafNBcuJHpZ1jaB2PyzEostc,658 +numpy/lib/array_utils.py,sha256=zmrUIVleWEWzl9XjEpUlDUQHt9qbbsytyu_jLj-OgnE,151 +numpy/lib/array_utils.pyi,sha256=YYnx_V4CMdSbJTCnYboN1swcswmlOD2e4ZvQj5WsSak,197 +numpy/lib/format.py,sha256=ii8MRQmPZ1nAaqnMqeYtKgdNRP52iZsHPo5rODl20UM,501 +numpy/lib/format.pyi,sha256=stg21MwwoAp4mfTkx9DD4lxKKXZzfABbqqiKim985Bk,876 +numpy/lib/introspect.py,sha256=HBySrZfK5neieljp9q29t7BPag8cFfqAuD8njgJDZ3g,2843 +numpy/lib/introspect.pyi,sha256=IsntuFrlFhRBZcGGhRUTAgnONUHEbYw_2ApPmffx8QE,155 +numpy/lib/mixins.py,sha256=uY-4dCmzviGP1kpfksxSLn__EA_oTwmLqyr4Dl_KA04,7375 +numpy/lib/mixins.pyi,sha256=QcVCn2u2NAWm5JiUNNpZZWIT43ZaB-rWBbP7fh3NktU,3260 +numpy/lib/npyio.py,sha256=EY5_tqGplRo-B3cJtqvf9HC34nQKr5JNgyykHWj5q_E,69 +numpy/lib/npyio.pyi,sha256=6xZ6zF-6qKuSOfjjDL4YN43xKPYcD6IpzJiDiLpmSSs,121 +numpy/lib/recfunctions.py,sha256=7to2wo6f8bxxUfVzHrMbo0gR9FNly3zdJK3jRirqrfE,61220 +numpy/lib/recfunctions.pyi,sha256=WuYzU-PEbvywxFThpCRCC9um0boqijX3tW8TJdrIeto,13896 +numpy/lib/scimath.py,sha256=3nsYqFdGoo0danaHnGK8Qrz0AAA31THUX0qnQsp5eu8,182 +numpy/lib/scimath.pyi,sha256=9y5MNnmU1oLBK7zs-tP8zCmh6QiY0gvmNLCIw3WjsNU,245 +numpy/lib/stride_tricks.py,sha256=qXan9_UpXFAoDLBAaJ1wYb0B86DgP48ogp5sUu3s1Lw,89 +numpy/lib/stride_tricks.pyi,sha256=6-K3R7XBw_fcpHaAIs9y4LEc5i4r5gZUG-tg4EOR-ew,128 +numpy/lib/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/lib/tests/__pycache__/__init__.cpython-312.pyc,, +numpy/lib/tests/__pycache__/test__datasource.cpython-312.pyc,, +numpy/lib/tests/__pycache__/test__iotools.cpython-312.pyc,, +numpy/lib/tests/__pycache__/test__version.cpython-312.pyc,, +numpy/lib/tests/__pycache__/test_array_utils.cpython-312.pyc,, +numpy/lib/tests/__pycache__/test_arraypad.cpython-312.pyc,, +numpy/lib/tests/__pycache__/test_arraysetops.cpython-312.pyc,, +numpy/lib/tests/__pycache__/test_arrayterator.cpython-312.pyc,, +numpy/lib/tests/__pycache__/test_format.cpython-312.pyc,, +numpy/lib/tests/__pycache__/test_function_base.cpython-312.pyc,, +numpy/lib/tests/__pycache__/test_histograms.cpython-312.pyc,, +numpy/lib/tests/__pycache__/test_index_tricks.cpython-312.pyc,, +numpy/lib/tests/__pycache__/test_io.cpython-312.pyc,, +numpy/lib/tests/__pycache__/test_loadtxt.cpython-312.pyc,, +numpy/lib/tests/__pycache__/test_mixins.cpython-312.pyc,, +numpy/lib/tests/__pycache__/test_nanfunctions.cpython-312.pyc,, +numpy/lib/tests/__pycache__/test_packbits.cpython-312.pyc,, +numpy/lib/tests/__pycache__/test_polynomial.cpython-312.pyc,, +numpy/lib/tests/__pycache__/test_recfunctions.cpython-312.pyc,, +numpy/lib/tests/__pycache__/test_regression.cpython-312.pyc,, +numpy/lib/tests/__pycache__/test_shape_base.cpython-312.pyc,, +numpy/lib/tests/__pycache__/test_stride_tricks.cpython-312.pyc,, +numpy/lib/tests/__pycache__/test_twodim_base.cpython-312.pyc,, +numpy/lib/tests/__pycache__/test_type_check.cpython-312.pyc,, +numpy/lib/tests/__pycache__/test_ufunclike.cpython-312.pyc,, +numpy/lib/tests/__pycache__/test_utils.cpython-312.pyc,, +numpy/lib/tests/data/py2-np0-objarr.npy,sha256=ZLoI7K3iQpXDkuoDF1Ymyc6Jbw4JngbQKC9grauVRsk,258 +numpy/lib/tests/data/py2-objarr.npy,sha256=F4cyUC-_TB9QSFLAo2c7c44rC6NUYIgrfGx9PqWPSKk,258 +numpy/lib/tests/data/py2-objarr.npz,sha256=xo13HBT0FbFZ2qvZz0LWGDb3SuQASSaXh7rKfVcJjx4,366 +numpy/lib/tests/data/py3-objarr.npy,sha256=7mtikKlHXp4unZhM8eBot8Cknlx1BofJdd73Np2PW8o,325 +numpy/lib/tests/data/py3-objarr.npz,sha256=vVRl9_NZ7_q-hjduUr8YWnzRy8ESNlmvMPlaSSC69fk,453 +numpy/lib/tests/data/python3.npy,sha256=X0ad3hAaLGXig9LtSHAo-BgOvLlFfPYMnZuVIxRmj-0,96 +numpy/lib/tests/data/win64python2.npy,sha256=agOcgHVYFJrV-nrRJDbGnUnF4ZTPYXuSeF-Mtg7GMpc,96 +numpy/lib/tests/test__datasource.py,sha256=davD8e4HZO8IzcSplB6w-j3G133L0AUBAa2GMAJpgYY,10892 +numpy/lib/tests/test__iotools.py,sha256=-BFgfKSpxhDXtn7OK_puB9fKKikBQaAyS_C8dJvb0KM,14188 +numpy/lib/tests/test__version.py,sha256=I6-cyr_7w1TUvC25hR1gTE3x8S-QRAXRsB4IjPxY3tg,2063 +numpy/lib/tests/test_array_utils.py,sha256=gRsql9I0f7RQk-1b8iPa1jDZsd_auCF05-ulxBCVfN4,1150 +numpy/lib/tests/test_arraypad.py,sha256=mlTByN5tvRlSQg3JGNY6GkROLS_ZkXieSkBst-Ct4Hk,58043 +numpy/lib/tests/test_arraysetops.py,sha256=lqLU-cpVmzWphPp7LfDCmFG-yCzPwuIuIF6ql3n60mU,49048 +numpy/lib/tests/test_arrayterator.py,sha256=4WinyEB5liYMGS__8tCeZJcoODkNMFdSMPFl4W-C_y0,1341 +numpy/lib/tests/test_format.py,sha256=SV3W7WdY-HSo_ASpICUt6XgN_va6Dngrm26o16aBx2c,43012 +numpy/lib/tests/test_function_base.py,sha256=zgPaj_Ikxstklgi4KFo2c41S47GYsbBaeGCDzOa1wck,182973 +numpy/lib/tests/test_histograms.py,sha256=ueQJepW8kS-_f2IsdXxEKIkXi2hwcaDJw2D3u3WhCCA,34806 +numpy/lib/tests/test_index_tricks.py,sha256=QeDRZu7H4gq8kUgOZX6awGC6uq3PTMV0hKXAlFj6rb0,25100 +numpy/lib/tests/test_io.py,sha256=-QP2cB5tyOwpBZms37WLtbr0-m2SdfrPxtbOl1u7qK4,114257 +numpy/lib/tests/test_loadtxt.py,sha256=-nMbVMrTNE9t-lPc4qDNfUrBGjTeAAsyWzm6fszlBjE,41590 +numpy/lib/tests/test_mixins.py,sha256=eWaFNkjo_IPlP4-7T-sitpZqhAgjUOjqkglUaPIdWXA,7224 +numpy/lib/tests/test_nanfunctions.py,sha256=sPWiCbDHTp4y3CEG7ART_UdFiaEWeSYJYPLfHeG54zQ,55735 +numpy/lib/tests/test_packbits.py,sha256=RAk590EWlPvH9M3trkBKb6MbKNhMjo-otRLEYznT7dM,17919 +numpy/lib/tests/test_polynomial.py,sha256=cWODMJ0jNINUibSTDTpa-DR6V92qFXd0qs9E9Tx8btk,12730 +numpy/lib/tests/test_recfunctions.py,sha256=DbbWdC6KvS3z6zekexcs4o6_drTwtGGq3QLba_hYPrw,45015 +numpy/lib/tests/test_regression.py,sha256=6Us-PZWNVT__IW4vj2-rA77Sdhpaoqo-_JgySVXL3dg,7947 +numpy/lib/tests/test_shape_base.py,sha256=R65ZPBfWnvzIyIrYbyJAUBUQqDbZX3gN0zx8sCydjKc,28219 +numpy/lib/tests/test_stride_tricks.py,sha256=TkLvnfcLK0CGyWu2I-60fYDgkxDskvjgr1de20z4VE4,23667 +numpy/lib/tests/test_twodim_base.py,sha256=j9PmcG03wmHEZjOL6pMp-kKOczqjcYYYh8ptdFSBPnA,19484 +numpy/lib/tests/test_type_check.py,sha256=UzaOYqNOWjSAxiur6FtERAEMIfYxk84nL_lpeDJGzxU,15269 +numpy/lib/tests/test_ufunclike.py,sha256=7oc71qsMf8NSPU-bMOZNw7H5wwksjPlxy9jJHTMK9Bc,3112 +numpy/lib/tests/test_utils.py,sha256=9XtDAa79N5LOqpLUHKY88ajRuY2gLzRMyJ1dry_4dkU,2454 +numpy/lib/user_array.py,sha256=5z7-hfXnWT5Oq4_WPnjNWGPc9RHUWZcyq4L9ZM3kkGQ,64 +numpy/lib/user_array.pyi,sha256=IaCNerLboKjt3Fm-_k_d8IqeyJf7Lc9Pr5ROUr6wleM,54 +numpy/linalg/__init__.py,sha256=N4KqBOUEZURrj_00q3Df_yLwPrmRMKHdm6UR1sibu2Y,2171 +numpy/linalg/__init__.pyi,sha256=5JqTmDBoOCqKUsQrQdMPV_kSfyan8ScHtFqqZRjrEE4,1087 +numpy/linalg/__pycache__/__init__.cpython-312.pyc,, +numpy/linalg/__pycache__/_linalg.cpython-312.pyc,, +numpy/linalg/_linalg.py,sha256=mYzZDZvLJE8w9TQTaS0QgQOeZaMto-wXb-9CKUi81Rg,118474 +numpy/linalg/_linalg.pyi,sha256=QDmN2W5x-FJRaqC0KdhXVn20skjIgTKkIeWW5crRht8,14024 +numpy/linalg/_umath_linalg.cp312-win_amd64.lib,sha256=jtBt5aw4l6n9kcZCB9l7oRtPXGI2GhLLLizJUESSj2A,2120 +numpy/linalg/_umath_linalg.cp312-win_amd64.pyd,sha256=FQi7FryuQzFcr2LMrZT8cPQ_0tF5tAXTdUK_7mcSm38,112128 +numpy/linalg/_umath_linalg.pyi,sha256=Q6Cr6NvaeEiY7GL9Oe57YGLl2Eby87BW6bswPmMUqKc,1451 +numpy/linalg/lapack_lite.cp312-win_amd64.lib,sha256=qqe5T0LNpdBkkk0G7enDZ4xMjeUCn6ymXShXjbD3QR8,2084 +numpy/linalg/lapack_lite.cp312-win_amd64.pyd,sha256=oZTiV9D5hvfj11GSYHuoAS2AfelOqYqSffA_DmGE3to,18944 +numpy/linalg/lapack_lite.pyi,sha256=CuG_G6XugM6ZNqvhXqw6JUPIoeGSpQyuCMTEudYIqzU,2850 +numpy/linalg/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/linalg/tests/__pycache__/__init__.cpython-312.pyc,, +numpy/linalg/tests/__pycache__/test_deprecations.cpython-312.pyc,, +numpy/linalg/tests/__pycache__/test_linalg.cpython-312.pyc,, +numpy/linalg/tests/__pycache__/test_regression.cpython-312.pyc,, +numpy/linalg/tests/test_deprecations.py,sha256=wEkvYP_0k-iqpVJh-bhgjFg67w4TCUthEe4adSSA8T8,637 +numpy/linalg/tests/test_linalg.py,sha256=mGBNdDIZ0SwUie32e0gbGUWEdgOkodVjoNvZGLkAp0U,87492 +numpy/linalg/tests/test_regression.py,sha256=NBImCcUaMF4lNaLRPB5tYW4LHlKUCZMKkuibML63_90,6978 +numpy/ma/API_CHANGES.txt,sha256=U39zA87aM_OIJhEKvHgL1RY1lhMJZc1Yj3DGLwbPbF0,3540 +numpy/ma/LICENSE,sha256=1427IIuA2StNMz5BpLquUNEkRPRuUxmfp3Jqkd5uLac,1616 +numpy/ma/README.rst,sha256=_MHrqHTE8L4wiJJqvaOh1l-xTxidwdilc_SZkFbgubM,10110 +numpy/ma/__init__.py,sha256=Zh2Hil4sdNNkf-0aJQrnOPmRkRwR4rOAzhN-n3RHsbU,1459 +numpy/ma/__init__.pyi,sha256=IorrWDELrFWTc_WfqWNCtWIcL0PrRE9aEZSzAABKMks,7404 +numpy/ma/__pycache__/__init__.cpython-312.pyc,, +numpy/ma/__pycache__/core.cpython-312.pyc,, +numpy/ma/__pycache__/extras.cpython-312.pyc,, +numpy/ma/__pycache__/mrecords.cpython-312.pyc,, +numpy/ma/__pycache__/testutils.cpython-312.pyc,, +numpy/ma/core.py,sha256=07dkfn4y_eOODNrgQBqYECjb8hTZad_bJ-0wU__nWXc,298146 +numpy/ma/core.pyi,sha256=3JZf_2zQ0BwAItjUGj9nXNsdM4igsMBfaqqvZBXWBv4,135211 +numpy/ma/extras.py,sha256=AJdPH7w71TeGQYgesG2iUkyLZBzGrpZzl6yLdT4UKmc,70056 +numpy/ma/extras.pyi,sha256=M3U-bBns8ejf-mZUUdTct4oMCReRmg6gUkN507SN7hA,9233 +numpy/ma/mrecords.py,sha256=wKhzJCGS9tJKoua0OBWeu41us9iWLnCfuXhMjeIKWTg,27248 +numpy/ma/mrecords.pyi,sha256=uKY5QR8liuxaLw8tNfDm9TBXxLdToXZ3tunufVcfPIk,2169 +numpy/ma/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/ma/tests/__pycache__/__init__.cpython-312.pyc,, +numpy/ma/tests/__pycache__/test_arrayobject.cpython-312.pyc,, +numpy/ma/tests/__pycache__/test_core.cpython-312.pyc,, +numpy/ma/tests/__pycache__/test_deprecations.cpython-312.pyc,, +numpy/ma/tests/__pycache__/test_extras.cpython-312.pyc,, +numpy/ma/tests/__pycache__/test_mrecords.cpython-312.pyc,, +numpy/ma/tests/__pycache__/test_old_ma.cpython-312.pyc,, +numpy/ma/tests/__pycache__/test_regression.cpython-312.pyc,, +numpy/ma/tests/__pycache__/test_subclassing.cpython-312.pyc,, +numpy/ma/tests/test_arrayobject.py,sha256=ap06C0a0dGWcOknpctbhLbzHSNd2M9p_JL2jESqBBGk,1139 +numpy/ma/tests/test_core.py,sha256=AOvwXQu7hFU56UBdB8BpM5dYqhlMF-KOzWIk4vy8_CU,230489 +numpy/ma/tests/test_deprecations.py,sha256=K5g3yWbztFEvCHXO70DzI5hSr2QivnNzTOdMv8lipZg,2089 +numpy/ma/tests/test_extras.py,sha256=e-1k5fcukD-9faz-d-TPNMqnEmHX5WAt8LQTYBxOfOM,77205 +numpy/ma/tests/test_mrecords.py,sha256=vQb7I7b4_jqr31YFEJiH7XYOGcMGAmOGKq2sESYHQdk,20332 +numpy/ma/tests/test_old_ma.py,sha256=Urg21tx11ipDOWbXG6MhWVrKLKMx1oGUDyHopcG3u7A,34014 +numpy/ma/tests/test_regression.py,sha256=XExMB46BYWyB7l6Kh9iDIJJuPz-Imbifp1RGgMVgqLk,2802 +numpy/ma/tests/test_subclassing.py,sha256=gvAxc0vLQ5sjiARATy28NUS0McpNkSwhPJfpOSEGvvc,17439 +numpy/ma/testutils.py,sha256=HY8srt3kH3lIOo9cbh1cQ027EikCsvOLKiJzWJTKs24,10507 +numpy/ma/testutils.pyi,sha256=7DxEhRCp8m6AA0fSvWi9N2GYry2Q1h1x7X1sdxwcIDU,2359 +numpy/matlib.py,sha256=xGJk9kOBs7qqA8IqhqQuwufNMUvq6Af_mErXxmZHZxw,11018 +numpy/matlib.pyi,sha256=KyqhVD9Bd2VSjun8onDfZZ8dPalhvTbHODonNaQVDrQ,10282 +numpy/matrixlib/__init__.py,sha256=aPXbaN4OYDp9TFA8kGzt2gTBHb3o8Nanw-uM_3XoDF4,255 +numpy/matrixlib/__init__.pyi,sha256=HrRbMtTKOizGPMnwXzAi490CiNfiIQewrxYFkUw7dZI,91 +numpy/matrixlib/__pycache__/__init__.cpython-312.pyc,, +numpy/matrixlib/__pycache__/defmatrix.cpython-312.pyc,, +numpy/matrixlib/defmatrix.py,sha256=HaFYtHEIhmi4KKbwzUJw-5uk-Xah8JS9dRVi2bZH20w,31994 +numpy/matrixlib/defmatrix.pyi,sha256=ysdXgQgGzo2xugU7Gt2EVlhTvkbHKqFA58U2qU_xB5k,11284 +numpy/matrixlib/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/matrixlib/tests/__pycache__/__init__.cpython-312.pyc,, +numpy/matrixlib/tests/__pycache__/test_defmatrix.cpython-312.pyc,, +numpy/matrixlib/tests/__pycache__/test_interaction.cpython-312.pyc,, +numpy/matrixlib/tests/__pycache__/test_masked_matrix.cpython-312.pyc,, +numpy/matrixlib/tests/__pycache__/test_matrix_linalg.cpython-312.pyc,, +numpy/matrixlib/tests/__pycache__/test_multiarray.cpython-312.pyc,, +numpy/matrixlib/tests/__pycache__/test_numeric.cpython-312.pyc,, +numpy/matrixlib/tests/__pycache__/test_regression.cpython-312.pyc,, +numpy/matrixlib/tests/test_defmatrix.py,sha256=i3KYI4VmOn7uhvUQsDzwkKKjAGdeUStamQgkjGoLgNY,15405 +numpy/matrixlib/tests/test_interaction.py,sha256=1nkRPWmfWfzOS9GjwOQV1D-Ke9W6UtkdwuMMVYcRIcg,12234 +numpy/matrixlib/tests/test_masked_matrix.py,sha256=EDUuKmHgap_OJuKbWmOsvOFKChSLasDsjXr20O_OjS0,9062 +numpy/matrixlib/tests/test_matrix_linalg.py,sha256=c7ldJ6xG66FvJH5FD2TSr617E9PfPMYwkAzrjhTxVYY,2341 +numpy/matrixlib/tests/test_multiarray.py,sha256=WgUxpIxXbzpXTTnt8iG0HC6RoAcTUk0PsEiMHT2361E,572 +numpy/matrixlib/tests/test_numeric.py,sha256=4XC1O2mv7NYYP1siT6I0YAz-Cuhlw6ZN9Du2FmCUz8Y,465 +numpy/matrixlib/tests/test_regression.py,sha256=2-c4B5aKWbySZ95RlG5WUm8OLBO7sLtM2zIzQMwMv0U,965 +numpy/polynomial/__init__.py,sha256=ynOHE1Mc9eBZMNlroaE9meIW7wZkvo7bpGjFjtDB_AU,6913 +numpy/polynomial/__init__.pyi,sha256=PYepBP5jjaCvPS3pQsl1xwNxDlrr1fSr122kM5g-ITk,743 +numpy/polynomial/__pycache__/__init__.cpython-312.pyc,, +numpy/polynomial/__pycache__/_polybase.cpython-312.pyc,, +numpy/polynomial/__pycache__/chebyshev.cpython-312.pyc,, +numpy/polynomial/__pycache__/hermite.cpython-312.pyc,, +numpy/polynomial/__pycache__/hermite_e.cpython-312.pyc,, +numpy/polynomial/__pycache__/laguerre.cpython-312.pyc,, +numpy/polynomial/__pycache__/legendre.cpython-312.pyc,, +numpy/polynomial/__pycache__/polynomial.cpython-312.pyc,, +numpy/polynomial/__pycache__/polyutils.cpython-312.pyc,, +numpy/polynomial/_polybase.py,sha256=8YgTcSVA4nRyITvWfrvuFGkXAdRB8Cc01R3cMCaa2wI,40549 +numpy/polynomial/_polybase.pyi,sha256=cNLZAPgtsUwASh2wryJIYvL_Mb1QxTDg9W7hq1JJBGM,8029 +numpy/polynomial/_polytypes.pyi,sha256=n2k83CrvRgHiu0iXFX0fJi5ZZn6NdMrEiIXBUwfNGpA,16735 +numpy/polynomial/chebyshev.py,sha256=Ynm99PaDojlSocfwoxNPq9UtK5j8OXYewWcf4OmEGY0,64287 +numpy/polynomial/chebyshev.pyi,sha256=lXlO2RgDRAKae9-eXVqQxpvYAMVqVdzHbCbGhQyCZcs,5278 +numpy/polynomial/hermite.py,sha256=N27hINDzF30xIQYtoba5wjTQQfxawYJTFxTWs1rUad8,56309 +numpy/polynomial/hermite.pyi,sha256=0FPL8PWTXACYXPPwd0VYyLMqsInOueZcMLMyUOOZMZY,2744 +numpy/polynomial/hermite_e.py,sha256=55-P3r7rKLh-ow8GkLKnGRkBGCznDaAi5EsMqtTM_vI,53913 +numpy/polynomial/hermite_e.pyi,sha256=1GyXRnzSLmS9c8Mkc65DicVGm6eA7GeTLWJALXp64Qg,2811 +numpy/polynomial/laguerre.py,sha256=Ka3rdMc-r4ORg5I86B0D6d8OjZi_qF81QvZycmOIvN0,54120 +numpy/polynomial/laguerre.pyi,sha256=RdPkWG5ccTjbTQAGrVhR9G02f9kIJHUYhTBNy8n_2wE,2466 +numpy/polynomial/legendre.py,sha256=xaD3gIuBJoEOD1UmpYxKfpxG7IY20zUdx5_mxgmR2Mk,52705 +numpy/polynomial/legendre.pyi,sha256=QK2mezoldWP4o-KeMKZB0SegU9YVqDWICgDvQVFI06Q,2466 +numpy/polynomial/polynomial.py,sha256=0Gq3tj431sv96iLtzZ_6aWo_Qtl1ltPTgdDeMSVBTp0,54294 +numpy/polynomial/polynomial.pyi,sha256=2oxYaruIMqD7kEAveWpuRdHWL_0gvisBrESYgQQaHpw,3098 +numpy/polynomial/polyutils.py,sha256=VbYrTs-TW2PMEGqNIDkCQg20yrtGvNkeUOoLnhJ7B9U,23394 +numpy/polynomial/polyutils.pyi,sha256=0VlzUyEb2ISaDekQ-QV__RhEeXaxHiBKi4YVV4qaAIE,10801 +numpy/polynomial/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/polynomial/tests/__pycache__/__init__.cpython-312.pyc,, +numpy/polynomial/tests/__pycache__/test_chebyshev.cpython-312.pyc,, +numpy/polynomial/tests/__pycache__/test_classes.cpython-312.pyc,, +numpy/polynomial/tests/__pycache__/test_hermite.cpython-312.pyc,, +numpy/polynomial/tests/__pycache__/test_hermite_e.cpython-312.pyc,, +numpy/polynomial/tests/__pycache__/test_laguerre.cpython-312.pyc,, +numpy/polynomial/tests/__pycache__/test_legendre.cpython-312.pyc,, +numpy/polynomial/tests/__pycache__/test_polynomial.cpython-312.pyc,, +numpy/polynomial/tests/__pycache__/test_polyutils.cpython-312.pyc,, +numpy/polynomial/tests/__pycache__/test_printing.cpython-312.pyc,, +numpy/polynomial/tests/__pycache__/test_symbol.cpython-312.pyc,, +numpy/polynomial/tests/test_chebyshev.py,sha256=N8cKoEf-jyLt-8KnMv56eKm72Jeikk2SZoJBjmYAtug,21247 +numpy/polynomial/tests/test_classes.py,sha256=Nwokju4FZgTYZVO1kEzwDOa2oZ09s-33LUGR6t3Fc0g,19144 +numpy/polynomial/tests/test_hermite.py,sha256=D0oETFi8zgQdqKi79LbAOG5ElwpGkpJvKWduG21qPZA,19219 +numpy/polynomial/tests/test_hermite_e.py,sha256=mXIdu3lCRU8DANPKC9kHQMWz7AOkju0l4iLRSMMNSmo,19559 +numpy/polynomial/tests/test_laguerre.py,sha256=QHc3JnCbNsrjB9-0BWeDoj9UZMiVZ6kmvnXqoJi8Gfw,18151 +numpy/polynomial/tests/test_legendre.py,sha256=Q7dUXM6nMlIXlhn11vXJKXRfDtttjSjXdXsYyfI0yu4,19350 +numpy/polynomial/tests/test_polynomial.py,sha256=qd4oOgjOYMUC5aoJvofgxMITaarVN1DxDhWs973V0oc,24255 +numpy/polynomial/tests/test_polyutils.py,sha256=fmZ2xqo6-eas1wM-QelCEjB2lFezOPPuAVhDsu-dpKc,3882 +numpy/polynomial/tests/test_printing.py,sha256=W0RgyZlRAiKL-3uJcNgcXPU7-TCX1wvtIdWIBvGyepQ,22116 +numpy/polynomial/tests/test_symbol.py,sha256=JNF0yt5xmUERjflLOydG1pMo6wMRLtaPDcYUkvXcD-o,5592 +numpy/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/random/LICENSE.md,sha256=tLwvT6HJV3jx7T3Y8UcGvs45lHW5ePnzS1081yUhtIo,3582 +numpy/random/__init__.pxd,sha256=g3EaMi3yfmnqT-KEWj0cp6SWIxVN9ChFjEYXGOfOifE,445 +numpy/random/__init__.py,sha256=8h45GRbXpL10xJzqw_n6Xgnm6SY_JUYCqH6SpeCnqUY,7693 +numpy/random/__init__.pyi,sha256=aqBCk_fpEZeoE94eNpGu37F6ZWfaDaajac9cWNm97So,2233 +numpy/random/__pycache__/__init__.cpython-312.pyc,, +numpy/random/__pycache__/_pickle.cpython-312.pyc,, +numpy/random/_bounded_integers.cp312-win_amd64.lib,sha256=bK-fIXCW-KnGLF-PxSD0fLnXN4dyTpTuCaxfDBUW_NY,18000 +numpy/random/_bounded_integers.cp312-win_amd64.pyd,sha256=N986IppVaiMnrakiYFxWro1nOz3sM5XxaL37RvKS3jc,207360 +numpy/random/_bounded_integers.pxd,sha256=EOKKUlF9bh0CLNEP8TzXzX4w_xV5kivr1Putfdf6yvU,1763 +numpy/random/_bounded_integers.pyi,sha256=PFr_V0xYQhWjKk5oc83cYg_JcNZ2FEKTsjXlnxmkyB8,25 +numpy/random/_common.cp312-win_amd64.lib,sha256=GKoWXXULVfemIdbW_RSUbhVbd_Qp98cSrWwsXSydE34,2012 +numpy/random/_common.cp312-win_amd64.pyd,sha256=fhCrQb99TgbJxoiJfvhFOhEecr7J8rFhlvBSZpsIaKA,166912 +numpy/random/_common.pxd,sha256=e1YxzdJoTvmMIyge3O9yOzpVU7aKRQa2q6cR9c9DB3k,5156 +numpy/random/_common.pyi,sha256=UlOkH40kVn6TU0c6OhG3CocvGnuYAC_46fxZJ7B_7y8,437 +numpy/random/_examples/cffi/__pycache__/extending.cpython-312.pyc,, +numpy/random/_examples/cffi/__pycache__/parse.cpython-312.pyc,, +numpy/random/_examples/cffi/extending.py,sha256=jSc3Vc6Uxl3VWHmoaffez8qG0GTfrFMuUxDhuB9Y5z4,928 +numpy/random/_examples/cffi/parse.py,sha256=2hy5736s-oL5uYvlQf_acpo7srBC8WfffLUhMcm218c,1803 +numpy/random/_examples/cython/extending.pyx,sha256=1lkq6zFifnwaMtAkVG0i_9SbMiNqplvqnHaqUpxqNzs,2344 +numpy/random/_examples/cython/extending_distributions.pyx,sha256=coVzQ6tOCHgZLO4tXIelEKcL3Rh5PIji8xJZGX4YuLA,3961 +numpy/random/_examples/cython/meson.build,sha256=q_IFcVs_qzERJD_-8uaDnjps3QdaW49okZMbFtwkAPo,1747 +numpy/random/_examples/numba/__pycache__/extending.cpython-312.pyc,, +numpy/random/_examples/numba/__pycache__/extending_distributions.cpython-312.pyc,, +numpy/random/_examples/numba/extending.py,sha256=mo0o4VM-K1vUQxNl_Uqr35Acj9UewnkglS7-dFX8yuw,2045 +numpy/random/_examples/numba/extending_distributions.py,sha256=vQdhhOpuGlpG8hk-mKWv7Li3-rwvelv-1c67odurt9o,2103 +numpy/random/_generator.cp312-win_amd64.lib,sha256=q8Pw9pWNzjhwx1ziK800e99bI4Kr4TuS5HrTJpuJrYE,18400 +numpy/random/_generator.cp312-win_amd64.pyd,sha256=rF0SpizzkfM6wIAxNiE5gf9sZARmna_8ISaUjIaR0SM,585216 +numpy/random/_generator.pyi,sha256=89Tnzx4Si2MtC1aqF8MXXs5h66sm1CkBU6uXkec_eCg,25321 +numpy/random/_mt19937.cp312-win_amd64.lib,sha256=XrIilm5Jjt1sJvmvy4cbcH8QLz3nCSp7WikRgAZy1R0,2032 +numpy/random/_mt19937.cp312-win_amd64.pyd,sha256=acG1izByczOe_W1CMOQqvjg855hG1k96wq8UKBppJIM,83968 +numpy/random/_mt19937.pyi,sha256=50ES_I-RoPvqqAYCqm3gX8NVcu0R7O5Ru5LSLpEuHzg,849 +numpy/random/_pcg64.cp312-win_amd64.lib,sha256=qbsrz6qdcvYn4top8Bl9FbcjeGC8um1fcxNnfnRIjn8,1996 +numpy/random/_pcg64.cp312-win_amd64.pyd,sha256=m6YwhEgH76YLBHgxQV3tacboNFeYSbsU56UhIXzQ6tI,94720 +numpy/random/_pcg64.pyi,sha256=PyZveXgEMEoHRprjXceyFBCwHkNctxcnSxk-tUWEzXE,1214 +numpy/random/_philox.cp312-win_amd64.lib,sha256=dLm65Y-Hc1Z8hwnFb5dmvF8vX5fpV6StCZMtN1Z1b48,2012 +numpy/random/_philox.cp312-win_amd64.pyd,sha256=0RIrtynWIOkVpOBeEUQQDBGS-ioyyZ0DOFbLAquzBGE,78336 +numpy/random/_philox.pyi,sha256=qTNeVdTZEZubisdfN5avuGoR6qMElesP5MC4gEMna9A,1049 +numpy/random/_pickle.py,sha256=8fmUcgzHhq_F_eyesNUdFjV07Br1yzLBLsfe-GWyQrE,2830 +numpy/random/_pickle.pyi,sha256=hj1oBasr_ejSeUlT3-q7luwC4DQFqgCPXIL0wxuFjt4,1651 +numpy/random/_sfc64.cp312-win_amd64.lib,sha256=CZgL1k_EYvQRlsF1zh0iZOHksw3pkCLOd7hVAMoMY-o,1996 +numpy/random/_sfc64.cp312-win_amd64.pyd,sha256=zFO5WJQgo4lsCuxk46AvPGffGj4fb0HS9ZyXgSgTEdI,59904 +numpy/random/_sfc64.pyi,sha256=qGwQgSmP2_RUa-C2y0r93o9VTMxJnD1vp_LVgWsTAC8,716 +numpy/random/bit_generator.cp312-win_amd64.lib,sha256=tjZUMkppSaHY7BuiSIdn9t_j-SCIg5kzQMcCJS2dMhg,2120 +numpy/random/bit_generator.cp312-win_amd64.pyd,sha256=YxJ1Bh_BdXcuTeqVykRzEZWR0_Yh0rKbz801YMoNhFI,157696 +numpy/random/bit_generator.pxd,sha256=TFR72-UsWpKMmiBsTg7eyiW-FT3hy6miVx2N49PVt-4,1244 +numpy/random/bit_generator.pyi,sha256=y9MsyLg-HH6BgrFRXtSyc4PY_H-pszQw57H8frQS5wQ,3726 +numpy/random/c_distributions.pxd,sha256=02WeqbzQ4heQ1cZ7ShePejxmt5AOI5kTstBZ5w2WxD0,6454 +numpy/random/lib/npyrandom.lib,sha256=vKs43qRwGl_ZyOM5Pg410aPlXQmrVJOFfETIIOhi-Zw,149648 +numpy/random/mtrand.cp312-win_amd64.lib,sha256=C5qJbZJ7nV4GTiYQlUeiV3XmB2-5Ch5m7YyDPr2yGmo,17122 +numpy/random/mtrand.cp312-win_amd64.pyd,sha256=0eQfqfNjI0W-LiX_8R4w0maIFExnVls0zCJ__R_BXcw,488960 +numpy/random/mtrand.pyi,sha256=BnWlQNKdxYKPNaGys4YZeAqigQNcMyKNagl6u2-Wzu0,24560 +numpy/random/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/random/tests/__pycache__/__init__.cpython-312.pyc,, +numpy/random/tests/__pycache__/test_direct.cpython-312.pyc,, +numpy/random/tests/__pycache__/test_extending.cpython-312.pyc,, +numpy/random/tests/__pycache__/test_generator_mt19937.cpython-312.pyc,, +numpy/random/tests/__pycache__/test_generator_mt19937_regressions.cpython-312.pyc,, +numpy/random/tests/__pycache__/test_random.cpython-312.pyc,, +numpy/random/tests/__pycache__/test_randomstate.cpython-312.pyc,, +numpy/random/tests/__pycache__/test_randomstate_regression.cpython-312.pyc,, +numpy/random/tests/__pycache__/test_regression.cpython-312.pyc,, +numpy/random/tests/__pycache__/test_seed_sequence.cpython-312.pyc,, +numpy/random/tests/__pycache__/test_smoke.cpython-312.pyc,, +numpy/random/tests/data/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/random/tests/data/__pycache__/__init__.cpython-312.pyc,, +numpy/random/tests/data/generator_pcg64_np121.pkl.gz,sha256=EfQ-X70KkHgBAFX2pIPcCUl4MNP1ZNROaXOU75vdiqM,203 +numpy/random/tests/data/generator_pcg64_np126.pkl.gz,sha256=fN8deNVxX-HELA1eIZ32kdtYvc4hwKya6wv00GJeH0Y,208 +numpy/random/tests/data/mt19937-testset-1.csv,sha256=bA5uuOXgLpkAwJjfV8oUePg3-eyaH4-gKe8AMcl2Xn0,16845 +numpy/random/tests/data/mt19937-testset-2.csv,sha256=SnOL1nyRbblYlC254PBUSc37NguV5xN-0W_B32IxDGE,16826 +numpy/random/tests/data/pcg64-testset-1.csv,sha256=wHoS7fIR3hMEdta7MtJ8EpIWX-Bw1yfSaVxiC15vxVs,24840 +numpy/random/tests/data/pcg64-testset-2.csv,sha256=6vlnVuW_4i6LEsVn6b40HjcBWWjoX5lboSCBDpDrzFs,24846 +numpy/random/tests/data/pcg64dxsm-testset-1.csv,sha256=Fhha5-jrCmRk__rsvx6CbDFZ7EPc8BOPDTh-myZLkhM,24834 +numpy/random/tests/data/pcg64dxsm-testset-2.csv,sha256=mNYzkCh0NMt1VvTrN08BbkpAbfkFxztNcsofgeW_0ns,24840 +numpy/random/tests/data/philox-testset-1.csv,sha256=QvpTynWHQjqTz3P2MPvtMLdg2VnM6TGTpXgp-_LeJ5g,24853 +numpy/random/tests/data/philox-testset-2.csv,sha256=-BNO1OCYtDIjnN5Q-AsQezBCGmVJUIs3qAMyj8SNtsA,24839 +numpy/random/tests/data/sfc64-testset-1.csv,sha256=sgkemW0lbKJ2wh1sBj6CfmXwFYTqfAk152P0r8emO38,24841 +numpy/random/tests/data/sfc64-testset-2.csv,sha256=mkp21SG8eCqsfNyQZdmiV41-xKcsV8eutT7rVnVEG50,24834 +numpy/random/tests/data/sfc64_np126.pkl.gz,sha256=MVa1ylFy7DUPgUBK-oIeKSdVl4UYEiN3AZ7G3sdzzaw,290 +numpy/random/tests/test_direct.py,sha256=sHeziHsn1iDt9kFJvoQqa4X_EV8RmdJkR2zM7zn1HQI,20618 +numpy/random/tests/test_extending.py,sha256=Kbem3Is-tYB0hiTem8_B6u5jYGv_tZNabrg2WAMTEzY,4820 +numpy/random/tests/test_generator_mt19937.py,sha256=t6iPLJTxdqQKvlrvmSNJn_umqit25A3X1y_nlexd7CQ,121685 +numpy/random/tests/test_generator_mt19937_regressions.py,sha256=y5urqQyDTYBy7xuuYmRMVq7sZFLC2a5HIQV42ZQic4c,8859 +numpy/random/tests/test_random.py,sha256=NHNX5yUlOmhSqUAkgnFuAR5vMk6VpGHFtiUABW9PAGA,73002 +numpy/random/tests/test_randomstate.py,sha256=tjY3PCEP4KkqdxWGHq5w36aLrpeaXjk4QMe97xYJA4Q,89848 +numpy/random/tests/test_randomstate_regression.py,sha256=yZ_PzRwhYsce-5W2aAPJbiZMNXjOU4bK-WdomdHwes4,8260 +numpy/random/tests/test_regression.py,sha256=i-v9J5LdvqrurawZrE-q657A_85y-ivVB4Bj7bp5z1U,6499 +numpy/random/tests/test_seed_sequence.py,sha256=J_peqBY4MhduYR1fFYAfcN2wvyC7P6xmV4xbu6j9nbQ,3389 +numpy/random/tests/test_smoke.py,sha256=aTjGNBx4HDSe5M7SbmhO1-Fj1CqVhDyE5Ldgjk_a4-Y,30817 +numpy/rec/__init__.py,sha256=cgaZYq6w4qNo81NZGO-E4vkSj9eSO4SgNMOqiLglp4k,85 +numpy/rec/__init__.pyi,sha256=gGrssJCiTrltTcwaCjXB8saZBWiWCHOr2mJmUsFdU50,370 +numpy/rec/__pycache__/__init__.cpython-312.pyc,, +numpy/strings/__init__.py,sha256=JzKUIYVjG4wRzsKVAVg9XWrq2vjjdi679CZc_Txfn4w,85 +numpy/strings/__init__.pyi,sha256=LvbeB_oUcN7O0GUJx3gzfYs-KPPVhHm6EhJIG3hJAHQ,1416 +numpy/strings/__pycache__/__init__.cpython-312.pyc,, +numpy/testing/__init__.py,sha256=0Qkz0ITfPKHDe9kObKTEx3fdDGAb9tfMikpdPuiapyA,603 +numpy/testing/__init__.pyi,sha256=xZNpS-qElFjn5Ueka4pywGO-rI_jf52GKH6uDNCfdXg,2295 +numpy/testing/__pycache__/__init__.cpython-312.pyc,, +numpy/testing/__pycache__/overrides.cpython-312.pyc,, +numpy/testing/__pycache__/print_coercion_tables.cpython-312.pyc,, +numpy/testing/_private/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/testing/_private/__init__.pyi,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/testing/_private/__pycache__/__init__.cpython-312.pyc,, +numpy/testing/_private/__pycache__/extbuild.cpython-312.pyc,, +numpy/testing/_private/__pycache__/utils.cpython-312.pyc,, +numpy/testing/_private/extbuild.py,sha256=ausYJDf2eOq9jYC3x_tFO_vBrMhjqjruVqHxgHjla8w,7966 +numpy/testing/_private/extbuild.pyi,sha256=f2h7VxBrN2uwqJIwB8pmv3c1G-sH7d3V4HCIL3GHYTA,678 +numpy/testing/_private/utils.py,sha256=uzxy7hWM8XH3MLyYdOOW5rmQRc78VDqDMjpYE2ytASY,101563 +numpy/testing/_private/utils.pyi,sha256=MAJBkXgDX7w49uUn1a8_orw9Gumd2aSzlPtgQ9ZfpAU,13730 +numpy/testing/overrides.py,sha256=rldmRQXc5c9jEs4hghDXvHA4sJD7HuMcpfGMmzSML9I,2218 +numpy/testing/overrides.pyi,sha256=ceLN7L1s2pQvLZQTIh89A_MoOnkkJoe-abXKT0Sk1bk,406 +numpy/testing/print_coercion_tables.py,sha256=lT8IdI1_lantwFVG0C0JagO0mUxnnXCA5wnPI81czYQ,6493 +numpy/testing/print_coercion_tables.pyi,sha256=ecFs2Qse4_H9AQC93fv5b2jmWMol941uoYlSuxhmNSU,846 +numpy/testing/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/testing/tests/__pycache__/__init__.cpython-312.pyc,, +numpy/testing/tests/__pycache__/test_utils.cpython-312.pyc,, +numpy/testing/tests/test_utils.py,sha256=BV8Aj5dGqZr32CvSO1Ag-idnHAJdDLnYKFSrJkXHcnQ,81824 +numpy/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/tests/__pycache__/__init__.cpython-312.pyc,, +numpy/tests/__pycache__/test__all__.cpython-312.pyc,, +numpy/tests/__pycache__/test_configtool.cpython-312.pyc,, +numpy/tests/__pycache__/test_ctypeslib.cpython-312.pyc,, +numpy/tests/__pycache__/test_lazyloading.cpython-312.pyc,, +numpy/tests/__pycache__/test_matlib.cpython-312.pyc,, +numpy/tests/__pycache__/test_numpy_config.cpython-312.pyc,, +numpy/tests/__pycache__/test_numpy_version.cpython-312.pyc,, +numpy/tests/__pycache__/test_public_api.cpython-312.pyc,, +numpy/tests/__pycache__/test_reloading.cpython-312.pyc,, +numpy/tests/__pycache__/test_scripts.cpython-312.pyc,, +numpy/tests/__pycache__/test_warnings.cpython-312.pyc,, +numpy/tests/test__all__.py,sha256=xZkp3RbMNpx4bFTvILKV8KTEMh5lvId7xcrhQS4LTe0,232 +numpy/tests/test_configtool.py,sha256=zieFjnFWqOsyLbtJJYIIdMMdThkDm-glvNGvN3_y7ow,1863 +numpy/tests/test_ctypeslib.py,sha256=7wJt8Im7-BUmTmtZ6rVeuHt__erJRRlK87dMaFZmL8E,13215 +numpy/tests/test_lazyloading.py,sha256=5YyD-WDS6uI_rIQBWmP6z7rCA9jtv4HAQ57NxysQKDs,1304 +numpy/tests/test_matlib.py,sha256=KmBMo3M7IARB8K5NLYk611RtsfW10_LgCQEBjdLEM9g,1913 +numpy/tests/test_numpy_config.py,sha256=8tTLdQi34xV1QTZw5TdaDQ9y25TVncGjvcmcXnQ2PEI,1364 +numpy/tests/test_numpy_version.py,sha256=EhDAFEamNCmRAiJEUSGtPa21IipODWrf6MN2Bem0az8,1798 +numpy/tests/test_public_api.py,sha256=iH-YBfcSa3Jc7_Mbxg4uWTNnJ1ZD9BDZn40L9jzIZ9g,28813 +numpy/tests/test_reloading.py,sha256=tEcoOR45hGgiQ-ocqrcRaKc7qKZXDwKM3ia6ivYpbm0,2762 +numpy/tests/test_scripts.py,sha256=KdTVn4N22QPEssua-dM83xExBCoVqIccBKaNBcjdVkE,1694 +numpy/tests/test_warnings.py,sha256=9-KePaaWfHgIAn6hVIy1gyio31zwMw8esAUYtvWTfzY,2499 +numpy/typing/__init__.py,sha256=7MEzTbsBZHmZmwuaEt2VsYQZPAjM2EGpa10Mdn35ceU,7217 +numpy/typing/__init__.pyi,sha256=gbeO9KFv0nrMve7BkrerjG92x442mEqEBDQZQuw2maI,130 +numpy/typing/__pycache__/__init__.cpython-312.pyc,, +numpy/typing/__pycache__/mypy_plugin.cpython-312.pyc,, +numpy/typing/mypy_plugin.py,sha256=eI-0xwotV4uhV7Dkpl6uuH15jSEwovgjfukbcLBRr34,7046 +numpy/typing/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/typing/tests/__pycache__/__init__.cpython-312.pyc,, +numpy/typing/tests/__pycache__/test_isfile.cpython-312.pyc,, +numpy/typing/tests/__pycache__/test_runtime.cpython-312.pyc,, +numpy/typing/tests/__pycache__/test_typing.cpython-312.pyc,, +numpy/typing/tests/data/fail/arithmetic.pyi,sha256=AMohW1_h2jlX8YPHH_sMm8lGS8ReUC0RkyHAQYe2k8I,3812 +numpy/typing/tests/data/fail/array_constructors.pyi,sha256=oDNMGHZnzHOO5_3zGxv5rQSu6kUlE_tgSuHcLpHvtKk,1234 +numpy/typing/tests/data/fail/array_like.pyi,sha256=9EcZ306eJOZrHSdWlTe0cEpYvmODaQ_nItcbhWaxFy8,511 +numpy/typing/tests/data/fail/array_pad.pyi,sha256=ExxQs_3s8xvgEsvj6O4aGWTIc0ukXtAtUM9JUs5D6pQ,143 +numpy/typing/tests/data/fail/arrayprint.pyi,sha256=TzEdr6oiRnYV1ZOGAYS6zzDWuRHl-aV8e407NnMzlxg,543 +numpy/typing/tests/data/fail/arrayterator.pyi,sha256=L2AC5qFmBrw9klehdV7d7gHvKpPX-7H1Iz9wryDQVQA,477 +numpy/typing/tests/data/fail/bitwise_ops.pyi,sha256=R-h3fWesS5CxenzKEYuyr2IpqSyMlGHQOAlro_smez4,397 +numpy/typing/tests/data/fail/char.pyi,sha256=PsgOrQuNsO2TD2HohOiOt7sYbs2q08hSEWxiEuiks1E,2737 +numpy/typing/tests/data/fail/chararray.pyi,sha256=LrTSnLGGEZrjeW_qpS-TGWz8vLVT0l7K5NdcFFucw24,2310 +numpy/typing/tests/data/fail/comparisons.pyi,sha256=_T0ZdZ0GYV_BkOqJjIzuWEQpN0lJgCc0fvx250U4x4o,763 +numpy/typing/tests/data/fail/constants.pyi,sha256=MnjvGyU_QKKiSZ-BzsHdojlRKz7GGvqQmu0mxbewcao,81 +numpy/typing/tests/data/fail/datasource.pyi,sha256=JO5en3G84i6LDK5b9JRDMg2GoOn5QBFI5qp_pAvupPY,436 +numpy/typing/tests/data/fail/dtype.pyi,sha256=TeNsugh9LvvX-u08MkROtFM_B080JZheXexyw9Wsq6E,322 +numpy/typing/tests/data/fail/einsumfunc.pyi,sha256=DeLM2jL7ZBirjw9H2dfjXxbHwx2Y9gu3wp2NwDLYuIQ,470 +numpy/typing/tests/data/fail/flatiter.pyi,sha256=eWphjcSJXi_EM1MTT_6kB0MgO_jy_vPJkYtk1CMz6Ec,1169 +numpy/typing/tests/data/fail/fromnumeric.pyi,sha256=hC2Nc8tUVV5-i43ak0WzB2wejwPsn2yIgQ6H13b_Sh8,5836 +numpy/typing/tests/data/fail/histograms.pyi,sha256=vkSk1v1Na4VUnRlwM8sqhxqPjhg2HH_9YtXnYNEHgPM,388 +numpy/typing/tests/data/fail/index_tricks.pyi,sha256=2VDHr1Of7fqh2uu0wf-epw7VZD2Fy0-W9ZPe1Fa87-8,531 +numpy/typing/tests/data/fail/lib_function_base.pyi,sha256=HTiFQTO8plsdCb-F1VvA_wz50GswJhwB3od9mTDkkIE,2723 +numpy/typing/tests/data/fail/lib_polynomial.pyi,sha256=xjpuJ7DVIRxQok6f0-CGsSVg6QQuzZmyiURslKF3ctw,966 +numpy/typing/tests/data/fail/lib_utils.pyi,sha256=iBUetgF7F39F-yV2DBhIqvKywzK8kZoAL9N-kpR3pyk,101 +numpy/typing/tests/data/fail/lib_version.pyi,sha256=EfAZTQpzTJ1UCY3p9envuaJUCqforENP_QP_DVWU7Do,160 +numpy/typing/tests/data/fail/linalg.pyi,sha256=r9prpIwrCPu7pnoS2JuasfnA8TJASyJR6TCUfYaYAG0,1592 +numpy/typing/tests/data/fail/ma.pyi,sha256=bj3awspyo8Cla0q39oY9G6UQGBddG5RGTewTYAO4lcQ,7161 +numpy/typing/tests/data/fail/memmap.pyi,sha256=U8_bCFw8m8x7ZlWSpYmmKpC1BS8oCEwUEdUgCRf2FSg,174 +numpy/typing/tests/data/fail/modules.pyi,sha256=f14qw9HXlwJ7FARKYxNhaPou8OZ8mQXsU4P9cpFxbWI,620 +numpy/typing/tests/data/fail/multiarray.pyi,sha256=qPGgrMMc0-SLuHJk1k_RaiPvs3CO-Ob6B9vFOKaFr44,1718 +numpy/typing/tests/data/fail/ndarray.pyi,sha256=8wZpNNatpxbxNu8G2N_R0P-3UVZLVE_z6ZGmdndSWPM,392 +numpy/typing/tests/data/fail/ndarray_misc.pyi,sha256=S5wtoAY-Y1f7MM7kjW4OOMtJnuF5uLTvCll21nJgyvc,1451 +numpy/typing/tests/data/fail/nditer.pyi,sha256=Sp3-l4RWopWY5ekm7yoINo4UhVYaKl9vW56aV14QDcc,332 +numpy/typing/tests/data/fail/nested_sequence.pyi,sha256=RZOHSAb-tA5eihm-dsD-r2WJqKaX-JbQ-fek0hw94nY,481 +numpy/typing/tests/data/fail/npyio.pyi,sha256=RrjdSUJE-K_dOF8Or_5bfpT2LYgFgHbS9fwVmWuJCBg,626 +numpy/typing/tests/data/fail/numerictypes.pyi,sha256=igYnLB91EuhrNDihL9IxwlM_xhwphCgMjWimzDaSNrk,129 +numpy/typing/tests/data/fail/random.pyi,sha256=ng4fxmdk1RFQdn3PNF7qSO2c2hVxQ07lwYwQGrSPsKQ,2965 +numpy/typing/tests/data/fail/rec.pyi,sha256=HkJQLYK6u8thA6alMB4pUeMBPXr6mgnqqTYmXSiM2PM,758 +numpy/typing/tests/data/fail/scalars.pyi,sha256=3ryg0rO8QAcUsN1VrXDnVp43AUSGBoEczk2Vm2BAl6Q,2924 +numpy/typing/tests/data/fail/shape.pyi,sha256=0uCGDpXresJPxRTEgNH8bP_FvCT0wV8Ob5Bu2_ZS428,139 +numpy/typing/tests/data/fail/shape_base.pyi,sha256=jfOTNjSqDVIGlAmwbORYfifftjvW-W4ngMRP883oSrU,165 +numpy/typing/tests/data/fail/stride_tricks.pyi,sha256=kjsv-sHn8i-oxtLUcpeIrOzS00Hk6Af8clqnY-vwg6A,339 +numpy/typing/tests/data/fail/strings.pyi,sha256=T7nJ-2UqEa2ld_bZW4king8PnAG9w9LompbD9rtIb7Y,2385 +numpy/typing/tests/data/fail/testing.pyi,sha256=zBTsTLi6xASHSeRK4f9ub1810m33xrb2qFyGvH93iqo,1427 +numpy/typing/tests/data/fail/twodim_base.pyi,sha256=XqAijZdegv0eHZ4pZPTo9ruwkVaMT168nbqyZV0HcHM,1171 +numpy/typing/tests/data/fail/type_check.pyi,sha256=u65AFyNm-J4gQu1brfsGuyJ1pN8tDJQxtRSYDxebUfE,382 +numpy/typing/tests/data/fail/ufunc_config.pyi,sha256=G17kqlgWREHukftCiDnCBRDjum5H1f8UIIifakzNBZc,610 +numpy/typing/tests/data/fail/ufunclike.pyi,sha256=7dpF86m9EeY_69dl_zX0joQvFIpKPXGQRRUJOipWTOw,670 +numpy/typing/tests/data/fail/ufuncs.pyi,sha256=7fKHGG69SFRRkqO5I-QqV-pVkQ3LTCPWgwgzOHGmhwI,522 +numpy/typing/tests/data/fail/warnings_and_errors.pyi,sha256=kKR53mZ3zy1-JmyGgmWjBmJw04ipqnTzqu9B4nU5OlQ,205 +numpy/typing/tests/data/misc/extended_precision.pyi,sha256=g80l5fCRis1PKm55PutBymIhrs-v3vYF2d5ZqiajcbI,331 +numpy/typing/tests/data/mypy.ini,sha256=6Uoh_q6A2Jod1K_65IRTcaDffDktTEIK6FaUHHzCWPA,222 +numpy/typing/tests/data/pass/__pycache__/arithmetic.cpython-312.pyc,, +numpy/typing/tests/data/pass/__pycache__/array_constructors.cpython-312.pyc,, +numpy/typing/tests/data/pass/__pycache__/array_like.cpython-312.pyc,, +numpy/typing/tests/data/pass/__pycache__/arrayprint.cpython-312.pyc,, +numpy/typing/tests/data/pass/__pycache__/arrayterator.cpython-312.pyc,, +numpy/typing/tests/data/pass/__pycache__/bitwise_ops.cpython-312.pyc,, +numpy/typing/tests/data/pass/__pycache__/comparisons.cpython-312.pyc,, +numpy/typing/tests/data/pass/__pycache__/dtype.cpython-312.pyc,, +numpy/typing/tests/data/pass/__pycache__/einsumfunc.cpython-312.pyc,, +numpy/typing/tests/data/pass/__pycache__/flatiter.cpython-312.pyc,, +numpy/typing/tests/data/pass/__pycache__/fromnumeric.cpython-312.pyc,, +numpy/typing/tests/data/pass/__pycache__/index_tricks.cpython-312.pyc,, +numpy/typing/tests/data/pass/__pycache__/lib_user_array.cpython-312.pyc,, +numpy/typing/tests/data/pass/__pycache__/lib_utils.cpython-312.pyc,, +numpy/typing/tests/data/pass/__pycache__/lib_version.cpython-312.pyc,, +numpy/typing/tests/data/pass/__pycache__/literal.cpython-312.pyc,, +numpy/typing/tests/data/pass/__pycache__/ma.cpython-312.pyc,, +numpy/typing/tests/data/pass/__pycache__/mod.cpython-312.pyc,, +numpy/typing/tests/data/pass/__pycache__/modules.cpython-312.pyc,, +numpy/typing/tests/data/pass/__pycache__/multiarray.cpython-312.pyc,, +numpy/typing/tests/data/pass/__pycache__/ndarray_conversion.cpython-312.pyc,, +numpy/typing/tests/data/pass/__pycache__/ndarray_misc.cpython-312.pyc,, +numpy/typing/tests/data/pass/__pycache__/ndarray_shape_manipulation.cpython-312.pyc,, +numpy/typing/tests/data/pass/__pycache__/nditer.cpython-312.pyc,, +numpy/typing/tests/data/pass/__pycache__/numeric.cpython-312.pyc,, +numpy/typing/tests/data/pass/__pycache__/numerictypes.cpython-312.pyc,, +numpy/typing/tests/data/pass/__pycache__/random.cpython-312.pyc,, +numpy/typing/tests/data/pass/__pycache__/recfunctions.cpython-312.pyc,, +numpy/typing/tests/data/pass/__pycache__/scalars.cpython-312.pyc,, +numpy/typing/tests/data/pass/__pycache__/shape.cpython-312.pyc,, +numpy/typing/tests/data/pass/__pycache__/simple.cpython-312.pyc,, +numpy/typing/tests/data/pass/__pycache__/ufunc_config.cpython-312.pyc,, +numpy/typing/tests/data/pass/__pycache__/ufunclike.cpython-312.pyc,, +numpy/typing/tests/data/pass/__pycache__/ufuncs.cpython-312.pyc,, +numpy/typing/tests/data/pass/__pycache__/warnings_and_errors.cpython-312.pyc,, +numpy/typing/tests/data/pass/arithmetic.py,sha256=HuUKU7DSCqnO9oCLKQloFSTTgp4JBdhfyg6bp-lZdNU,8380 +numpy/typing/tests/data/pass/array_constructors.py,sha256=NXGxCHOAeh8uxlP46EUnbo_PXl0OX62WnAgBvrDvZno,2586 +numpy/typing/tests/data/pass/array_like.py,sha256=VWGx8wSe5z5XR2uOkNVvYNhMMkaBbhLdQHVlixbl4nM,1075 +numpy/typing/tests/data/pass/arrayprint.py,sha256=NTw1gJ9v3TDVwRov4zsg_27rI-ndKuG4mDidBWEKVyc,803 +numpy/typing/tests/data/pass/arrayterator.py,sha256=qPyDI_38M155brLW25CyVnf6-2Zfn0MEnj8NqadpEgA,422 +numpy/typing/tests/data/pass/bitwise_ops.py,sha256=i5NHgKmg2q27z6mlCjKjO3haydGRPZmUL3Js-5jAt20,1090 +numpy/typing/tests/data/pass/comparisons.py,sha256=gWDQU6bGY09YVG9MEYLjkJH9pdOGql1PFN6h-5pJNEI,3606 +numpy/typing/tests/data/pass/dtype.py,sha256=YRsTwKEQ5iJtdKCEQIybU_nL8z8Wq9hU-BZmEO7HjQE,1127 +numpy/typing/tests/data/pass/einsumfunc.py,sha256=CXdLvQsU2iDqQc7d2TRRCSwguQzJ0SJDFn23SDeOOuY,1406 +numpy/typing/tests/data/pass/flatiter.py,sha256=JWG5gQ9RqSDrg9V2KlSgGtANnB7JDRFJM9e14wJ0Y_g,288 +numpy/typing/tests/data/pass/fromnumeric.py,sha256=bP0hEQYYQJOn7-ce0rAf8cvuxZX3Ja6GSSlCtNhEBUM,4263 +numpy/typing/tests/data/pass/index_tricks.py,sha256=ymUrTbHcpYRgAPVxhwdXF0f_1aFBDBZEp_Ue3BxddZE,1466 +numpy/typing/tests/data/pass/lib_user_array.py,sha256=qvCmq32uZlgGL76u8sygvguBiTphLrt8X-mVaYnex0A,640 +numpy/typing/tests/data/pass/lib_utils.py,sha256=XEc0v7bwES-C5D4GkSJQSSTSAl5ng7tq6tCWj3jxbCM,336 +numpy/typing/tests/data/pass/lib_version.py,sha256=TlLZK8sekCMm__WWo22FZfZc40zpczENf6y_TNjBpCw,317 +numpy/typing/tests/data/pass/literal.py,sha256=wZ7S1bDJFyTkrQbgYRSXZGobU976J2F_620-lv_hZTk,1561 +numpy/typing/tests/data/pass/ma.py,sha256=_gssQTkMQTtFIec3A9OSSk50o_LHhFp1vp3jBlvkuIs,4121 +numpy/typing/tests/data/pass/mod.py,sha256=IZbpRvH19U4hbLJfm0CKyyihJ9bv-g561cYr74bDlao,1720 +numpy/typing/tests/data/pass/modules.py,sha256=buzLurat4TIGmJuW3mGsGk7dKNmpBDfQOWWQXFfb9Uc,670 +numpy/typing/tests/data/pass/multiarray.py,sha256=OGU_AH571v22-L_IHGNRdd4XcbqlZXtZLxZLYZdiBqs,1456 +numpy/typing/tests/data/pass/ndarray_conversion.py,sha256=5Sy_SGRL_Nkb9j0yhsj0DtN9ba4aBc_KRLsUZK1SyNA,1530 +numpy/typing/tests/data/pass/ndarray_misc.py,sha256=A7PIVuXhVcN06uP_D-ZUdo_I8Xl1m74DZpjS4WLdTrY,3555 +numpy/typing/tests/data/pass/ndarray_shape_manipulation.py,sha256=yaBK3hW5fe2VpvARkn_NMeF-JX-OajI8JiRWOA_Uk7Y,687 +numpy/typing/tests/data/pass/nditer.py,sha256=1wpRitCNZKCC3WJVrFSh22Z1D8jP2VxQAMtzH8NcpV8,67 +numpy/typing/tests/data/pass/numeric.py,sha256=ZWN3MW8Lk_qeqx3VC9cMOekFK21o02xnkpUJrTWYeUI,1582 +numpy/typing/tests/data/pass/numerictypes.py,sha256=JaCjk4zQPOI67XzqGyi3dI-GUMFM2AvDuniwzSQ7_Rk,348 +numpy/typing/tests/data/pass/random.py,sha256=zMhPsSbYUjSou6PggCqp3Q-hYDYZytT7IeF-wBAB5R0,63323 +numpy/typing/tests/data/pass/recfunctions.py,sha256=8nqw-j8pbjUNo6f92fFjAwm57zzDLP2PrY6DehmWv8k,5138 +numpy/typing/tests/data/pass/scalars.py,sha256=IEkuEFLTVcsPQsSqft9K3iRDJNWRoVB6r_y3m4yzGos,3974 +numpy/typing/tests/data/pass/shape.py,sha256=oSkR0akFaIBrXFcX4D14ZiR2Yw1rHsZSoLKFL_Qjav8,458 +numpy/typing/tests/data/pass/simple.py,sha256=F6Qi7OLrbUrcZJiBGGPEjuyvk1M7jpOaIyewTCJVW5E,2925 +numpy/typing/tests/data/pass/ufunc_config.py,sha256=gmMTPrq8gLXJZSBQoOpJcgzIzWgMx-k_etKPV4KSTJk,1269 +numpy/typing/tests/data/pass/ufunclike.py,sha256=9t-6R0b7HmE5jczJp0dcNOP7Iz9zaUE0918AgFfeJfY,1403 +numpy/typing/tests/data/pass/ufuncs.py,sha256=gvdcCNoGUfN0CnQmn6k1j6ghdt8zGkJdcRcgctmU48A,438 +numpy/typing/tests/data/pass/warnings_and_errors.py,sha256=q3c1SmMwhyYLYQsLjK02AXphk3-96YltSTdTfrElJzQ,167 +numpy/typing/tests/data/reveal/arithmetic.pyi,sha256=JHcs_4SzHUK1uDM91UBlh2WTaXpU8ShW97TWT-RMcPA,27518 +numpy/typing/tests/data/reveal/array_api_info.pyi,sha256=TOvbhGUiNYcKv9KQs0A4-vzM_l9vYWvDXoqBOOLo1d4,3087 +numpy/typing/tests/data/reveal/array_constructors.pyi,sha256=eqe96eYVSybTarmGhyIe3CxsOSB3Pkfah6DQxYWl650,15042 +numpy/typing/tests/data/reveal/arraypad.pyi,sha256=hJeTeX66VR9hDRliaP195klegP9cmBnrZqDsEGLm30A,931 +numpy/typing/tests/data/reveal/arrayprint.pyi,sha256=oQGscSvF8perObX6j1LduWS1eogRYyl7NM8piYuZPxc,797 +numpy/typing/tests/data/reveal/arraysetops.pyi,sha256=-Fhtnyc-uzDT5zUlh7xSLmdkK05Y14MqpgdG38Xliu0,4485 +numpy/typing/tests/data/reveal/arrayterator.pyi,sha256=-bqtQE71AcS2cisOcRAaDRxvp_STs41Dbzu7qUvaGRc,1054 +numpy/typing/tests/data/reveal/bitwise_ops.pyi,sha256=z60Mwun7flBSAxDh_BHksPzPSikxvKnBkde6cRRnNuE,4803 +numpy/typing/tests/data/reveal/char.pyi,sha256=KekJM9d_iNnAa9OU98yiWrR7bJ4ZpxvUr04mVkWOdrA,11777 +numpy/typing/tests/data/reveal/chararray.pyi,sha256=vxQbEhNEOX6SghlIBBtJLNIc5XTiP_msVTRqBHja4gw,5403 +numpy/typing/tests/data/reveal/comparisons.pyi,sha256=h0PYWf2F-mRNAK7e_3H4-hu0msj2KxU3xaHb2aoqFnc,7445 +numpy/typing/tests/data/reveal/constants.pyi,sha256=DHycCQpNsu52JrhZ_Qds7f0F4U0rD4zWaVMOLwWR08o,347 +numpy/typing/tests/data/reveal/ctypeslib.pyi,sha256=TuMyVAki_VnT2jYiCGPNOvb9W3iWGL2sKKkbKul_5P0,4215 +numpy/typing/tests/data/reveal/datasource.pyi,sha256=07PFHAOF4kL5Wqq5pt1IKvx6VPYBZ9IK1_WXo_3II1E,606 +numpy/typing/tests/data/reveal/dtype.pyi,sha256=psnbSgAYVrU3MXJyV470NjQeqbdd9Re6q4_3n334ETg,4865 +numpy/typing/tests/data/reveal/einsumfunc.pyi,sha256=R-ve3Dda6S1ewKjlDoQ1XWx4Adj-JxFe9TFdrPeX2sA,1965 +numpy/typing/tests/data/reveal/emath.pyi,sha256=HGPBuE6CTTSHirCCQMklDGkvamoIILqpREfP9NJh49I,2179 +numpy/typing/tests/data/reveal/fft.pyi,sha256=uNGippaypaPH9ZmwaOXwPdHXDh_TW4BJlEkv9idK08Y,1638 +numpy/typing/tests/data/reveal/flatiter.pyi,sha256=WptTeykBGKmYBKse08jQ2nlP_706LL8qaqhm3IHjLT0,3348 +numpy/typing/tests/data/reveal/fromnumeric.pyi,sha256=FZNJHn7P-ddjrSSSUr-3qqWShbiGC5qkodDXXfvHp24,15526 +numpy/typing/tests/data/reveal/getlimits.pyi,sha256=DoHEcyug87JBCouEKZrf2pF2vliRF9rcQenn0Nd8MKo,1639 +numpy/typing/tests/data/reveal/histograms.pyi,sha256=2l6Af9c4cru2C6xSuL0iqW78OqEo4nrWFqARC5nA0Xo,1282 +numpy/typing/tests/data/reveal/index_tricks.pyi,sha256=UoYlUdqV2jgImmKFDOkLECoLN1ZuTWs7P0VLczBi8a8,3311 +numpy/typing/tests/data/reveal/lib_function_base.pyi,sha256=mq7dYJPYd98XqBnc_n1V6JgX2HvgoB8Q_weGyUC8TjA,20372 +numpy/typing/tests/data/reveal/lib_polynomial.pyi,sha256=fpINlyW5XcQl5I2sjXbb6REu8qosYsemET_GxjBAOtY,5849 +numpy/typing/tests/data/reveal/lib_utils.pyi,sha256=0mEaIvr9BkYx2Gmmj7M0vvG_o4c0TgD0uU8uJsY7Jl0,453 +numpy/typing/tests/data/reveal/lib_version.pyi,sha256=5-H7IY5M-OT0Wu7d0FhO95s5jYafpMb2s-sYPNEisaQ,592 +numpy/typing/tests/data/reveal/linalg.pyi,sha256=4kzgLlgrDlYjvNlzosyqdJ2AV83AJqJsr08aZcGRl-4,7346 +numpy/typing/tests/data/reveal/ma.pyi,sha256=vfKs_ua565soL5Ik4M_RMNbd3EbNx_vKNXSKh32qhaY,51706 +numpy/typing/tests/data/reveal/matrix.pyi,sha256=xyhYRFmQUL9GdFmZnWNLPJPaRRmjJLdpozP6uUBHnUE,2903 +numpy/typing/tests/data/reveal/memmap.pyi,sha256=KdMkvJgXmWwOAE6H0BKQjB-A3go2keJAem59FUJtmVM,738 +numpy/typing/tests/data/reveal/mod.pyi,sha256=4d8e_54VcJJKaSHy_vVwLzQ25Nt6GJ5qHxFIxkkl0ec,7356 +numpy/typing/tests/data/reveal/modules.pyi,sha256=dgB-VZ5GQpABSsnAsnwfUx781fv7dia3TrDnguVippg,1909 +numpy/typing/tests/data/reveal/multiarray.pyi,sha256=C_u26_2lvuhh3x5zy-qQctGO1ks1gMsC_pQ3DtXhu5o,8250 +numpy/typing/tests/data/reveal/nbit_base_example.pyi,sha256=9eWyNVc8VjggFJ112bPPKx5MOTLr5iurhIaETKjDc0s,694 +numpy/typing/tests/data/reveal/ndarray_assignability.pyi,sha256=F01Uub9Ect05XD8qz18nWpZ3AzhnTt-Ti8wsROZ1HWg,2993 +numpy/typing/tests/data/reveal/ndarray_conversion.pyi,sha256=KQIltfDd9yLcDTg86NCRDzQjOHXn1e6sYEQX3PcYb64,3335 +numpy/typing/tests/data/reveal/ndarray_misc.pyi,sha256=um6vXze3eHUfMB_yWg9TFuIT4lKhB-o-YXgSLThtiEE,8937 +numpy/typing/tests/data/reveal/ndarray_shape_manipulation.pyi,sha256=xMPirePw0fwNYuTpnts3Bpt-CxorAUaF0ea0oopzgM8,1745 +numpy/typing/tests/data/reveal/nditer.pyi,sha256=eHIBPj1I75kErxXsTi0CQEjcJ_WvHXIx7QzEeTmxYDk,1947 +numpy/typing/tests/data/reveal/nested_sequence.pyi,sha256=aRkKbnRxI2A-xkg8iQZWOHU7672PlyMNpUHIkONymLw,637 +numpy/typing/tests/data/reveal/npyio.pyi,sha256=KA_lenEDj92tycocaW9y4Bz_jpZ5gsbHPxhYFn5nBDw,3583 +numpy/typing/tests/data/reveal/numeric.pyi,sha256=CivGCAYe2BlStSBMhO2hRUtmqFfRFrhuj97aK0PpQ-0,9242 +numpy/typing/tests/data/reveal/numerictypes.pyi,sha256=5ouW5fRTVciZdx0svYChyTsWcmwPpqZqhmlfpdpa8b0,584 +numpy/typing/tests/data/reveal/polynomial_polybase.pyi,sha256=1zRBBhPgpZXTa2jJtXGDfVQL5L4zxozjSZ0MgQsdgnM,7843 +numpy/typing/tests/data/reveal/polynomial_polyutils.pyi,sha256=vo7CfyWW7vuMhbyI95u53yS9t6ADyc2lGBJOtHbYD6c,10837 +numpy/typing/tests/data/reveal/polynomial_series.pyi,sha256=ppgLW-xn2DpkLOP8vfteKTmtCrAErE5k6_m6IbzNIm4,7018 +numpy/typing/tests/data/reveal/random.pyi,sha256=JlNcrkvVoyI8uezvQ9BBCTtFoVQPRgZ5zPXKiDdCFwo,105842 +numpy/typing/tests/data/reveal/rec.pyi,sha256=2Pr6-v4uSA_t13cYdLr2sKQSb1Ko9YuZQS-_UUAZwFo,3549 +numpy/typing/tests/data/reveal/scalars.pyi,sha256=SZ3zC7GNT-DeRXlLhz9_jvRY-TNSQvFqxXCdH3pL4HE,6569 +numpy/typing/tests/data/reveal/shape.pyi,sha256=9IilbiRez0Lbu7Zv_HvqdEwQhjRLzcbnKm-4wnG6d9c,275 +numpy/typing/tests/data/reveal/shape_base.pyi,sha256=1_G5HGC45IFPnetUyXXnyIhJYjNu0Mf7AEEtSz3QrmI,2058 +numpy/typing/tests/data/reveal/stride_tricks.pyi,sha256=PqrKANjOAnn_CQ2CjERvonBbM89PjhZpgnekiQpT04k,1342 +numpy/typing/tests/data/reveal/strings.pyi,sha256=D2r-lCrWhVM3HQ8X2cjLT2cwujxYLOb1ASrnHs2qPD8,9743 +numpy/typing/tests/data/reveal/testing.pyi,sha256=w2dTmMJnGi_jtBtCMjnUTqnrGLiYAvsksrTIwzk41HE,9031 +numpy/typing/tests/data/reveal/twodim_base.pyi,sha256=4devsums2EaY0qVWJxJG8kopVXHxYHC_uV9cj_ml_4k,7700 +numpy/typing/tests/data/reveal/type_check.pyi,sha256=3on6Yhb-vylW0Etlpl_VP6bevzBipPn8J8W6EVE66eU,2459 +numpy/typing/tests/data/reveal/ufunc_config.pyi,sha256=fhhSCMGh5L2WU9x8DGHF3dxHugJEkIKiwf_J5mq62Js,1190 +numpy/typing/tests/data/reveal/ufunclike.pyi,sha256=FrHumRFEU0_Ji-0HIIoOx1oHriVaTXKpNzLqiudAIcI,1377 +numpy/typing/tests/data/reveal/ufuncs.pyi,sha256=Bn60mPM7tO4Uv1dgSRY8OgT_NvmW75BhnKTQfvZsey4,6487 +numpy/typing/tests/data/reveal/warnings_and_errors.pyi,sha256=kdpx5u0-zsWOPcsnciaqsACr7OKUuFWmMeMCizZDun8,460 +numpy/typing/tests/test_isfile.py,sha256=US1HhRtoDrAmlY_RuoE7ILspD0ujMifE5dydGhligTM,1085 +numpy/typing/tests/test_runtime.py,sha256=CoPFvSUANjIF7-3kPOxGXmzH6kSDFrqPq6u0__nbxXE,3186 +numpy/typing/tests/test_typing.py,sha256=j6wK6nH2Jx9V8ijLJrr8QdJjDv3NbJKCrEUNF0j7AxE,6494 +numpy/version.py,sha256=uzrYWl3fRxRj6IutUbyiRadLVcmSRIh4u_Ugc_U6D8o,304 +numpy/version.pyi,sha256=-JbleHX_16pnboC4DmzPym2X1EcI-w5cRoH0utivI34,278 diff --git a/TTS/Kokoro/.venv/Lib/site-packages/numpy-2.4.2.dist-info/REQUESTED b/TTS/Kokoro/.venv/Lib/site-packages/numpy-2.4.2.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/TTS/Kokoro/.venv/Lib/site-packages/numpy-2.4.2.dist-info/WHEEL b/TTS/Kokoro/.venv/Lib/site-packages/numpy-2.4.2.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..0a709edb3466cbdf4c45d43e836237b80ead85fb --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/numpy-2.4.2.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: meson +Root-Is-Purelib: false +Tag: cp312-cp312-win_amd64 \ No newline at end of file diff --git a/TTS/Kokoro/.venv/Lib/site-packages/numpy-2.4.2.dist-info/entry_points.txt b/TTS/Kokoro/.venv/Lib/site-packages/numpy-2.4.2.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..48c4f6435df3f089c2ffd33f4c90eb1705d34958 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/numpy-2.4.2.dist-info/entry_points.txt @@ -0,0 +1,13 @@ +[pkg_config] +numpy = numpy._core.lib.pkgconfig + +[array_api] +numpy = numpy + +[pyinstaller40] +hook-dirs = numpy:_pyinstaller_hooks_dir + +[console_scripts] +f2py = numpy.f2py.f2py2e:main +numpy-config = numpy._configtool:main + diff --git a/TTS/Kokoro/.venv/Lib/site-packages/numpy/__config__.py b/TTS/Kokoro/.venv/Lib/site-packages/numpy/__config__.py new file mode 100644 index 0000000000000000000000000000000000000000..fac8c07ac38f32b0d918352233a20eda58660f87 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/numpy/__config__.py @@ -0,0 +1,170 @@ +# This file is generated by numpy's build process +# It contains system_info results at the time of building this package. +from enum import Enum +from numpy._core._multiarray_umath import ( + __cpu_features__, + __cpu_baseline__, + __cpu_dispatch__, +) + +__all__ = ["show_config"] +_built_with_meson = True + + +class DisplayModes(Enum): + stdout = "stdout" + dicts = "dicts" + + +def _cleanup(d): + """ + Removes empty values in a `dict` recursively + This ensures we remove values that Meson could not provide to CONFIG + """ + if isinstance(d, dict): + return {k: _cleanup(v) for k, v in d.items() if v and _cleanup(v)} + else: + return d + + +CONFIG = _cleanup( + { + "Compilers": { + "c": { + "name": "msvc", + "linker": r"link", + "version": "19.44.35222", + "commands": r"cl", + "args": r"", + "linker args": r"", + }, + "cython": { + "name": "cython", + "linker": r"cython", + "version": "3.2.4", + "commands": r"cython", + "args": r"", + "linker args": r"", + }, + "c++": { + "name": "msvc", + "linker": r"link", + "version": "19.44.35222", + "commands": r"cl", + "args": r"", + "linker args": r"", + }, + }, + "Machine Information": { + "host": { + "cpu": "x86_64", + "family": "x86_64", + "endian": "little", + "system": "windows", + }, + "build": { + "cpu": "x86_64", + "family": "x86_64", + "endian": "little", + "system": "windows", + }, + "cross-compiled": bool("False".lower().replace("false", "")), + }, + "Build Dependencies": { + "blas": { + "name": "scipy-openblas", + "found": bool("True".lower().replace("false", "")), + "version": "0.3.31.dev", + "detection method": "pkgconfig", + "include directory": r"C:/Users/runneradmin/AppData/Local/Temp/cibw-run-s5wc8nbf/cp312-win_amd64/build/venv/Lib/site-packages/scipy_openblas64/include", + "lib directory": r"C:/Users/runneradmin/AppData/Local/Temp/cibw-run-s5wc8nbf/cp312-win_amd64/build/venv/Lib/site-packages/scipy_openblas64/lib", + "openblas configuration": r"OpenBLAS 0.3.31.dev USE64BITINT DYNAMIC_ARCH NO_AFFINITY Haswell MAX_THREADS=24", + "pc file directory": r"D:/a/numpy-release/numpy-release/.openblas", + }, + "lapack": { + "name": "scipy-openblas", + "found": bool("True".lower().replace("false", "")), + "version": "0.3.31.dev", + "detection method": "pkgconfig", + "include directory": r"C:/Users/runneradmin/AppData/Local/Temp/cibw-run-s5wc8nbf/cp312-win_amd64/build/venv/Lib/site-packages/scipy_openblas64/include", + "lib directory": r"C:/Users/runneradmin/AppData/Local/Temp/cibw-run-s5wc8nbf/cp312-win_amd64/build/venv/Lib/site-packages/scipy_openblas64/lib", + "openblas configuration": r"OpenBLAS 0.3.31.dev USE64BITINT DYNAMIC_ARCH NO_AFFINITY Haswell MAX_THREADS=24", + "pc file directory": r"D:/a/numpy-release/numpy-release/.openblas", + }, + }, + "Python Information": { + "path": r"C:\Users\runneradmin\AppData\Local\Temp\build-env-9ypq4bkp\Scripts\python.exe", + "version": "3.12", + }, + "SIMD Extensions": { + "baseline": __cpu_baseline__, + "found": [ + feature for feature in __cpu_dispatch__ if __cpu_features__[feature] + ], + "not found": [ + feature for feature in __cpu_dispatch__ if not __cpu_features__[feature] + ], + }, + } +) + + +def _check_pyyaml(): + import yaml + + return yaml + + +def show(mode=DisplayModes.stdout.value): + """ + Show libraries and system information on which NumPy was built + and is being used + + Parameters + ---------- + mode : {`'stdout'`, `'dicts'`}, optional. + Indicates how to display the config information. + `'stdout'` prints to console, `'dicts'` returns a dictionary + of the configuration. + + Returns + ------- + out : {`dict`, `None`} + If mode is `'dicts'`, a dict is returned, else None + + See Also + -------- + get_include : Returns the directory containing NumPy C + header files. + + Notes + ----- + 1. The `'stdout'` mode will give more readable + output if ``pyyaml`` is installed + + """ + if mode == DisplayModes.stdout.value: + try: # Non-standard library, check import + yaml = _check_pyyaml() + + print(yaml.dump(CONFIG)) + except ModuleNotFoundError: + import warnings + import json + + warnings.warn("Install `pyyaml` for better output", stacklevel=1) + print(json.dumps(CONFIG, indent=2)) + elif mode == DisplayModes.dicts.value: + return CONFIG + else: + raise AttributeError( + f"Invalid `mode`, use one of: {', '.join([e.value for e in DisplayModes])}" + ) + + +def show_config(mode=DisplayModes.stdout.value): + return show(mode) + + +show_config.__doc__ = show.__doc__ +show_config.__module__ = "numpy" diff --git a/TTS/Kokoro/.venv/Lib/site-packages/numpy/__config__.pyi b/TTS/Kokoro/.venv/Lib/site-packages/numpy/__config__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..85366b45649881b27ceafcaa3dd7c20959bf9e18 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/numpy/__config__.pyi @@ -0,0 +1,108 @@ +from enum import Enum +from types import ModuleType +from typing import ( + Final, + Literal as L, + NotRequired, + TypedDict, + overload, + type_check_only, +) + +_CompilerConfigDictValue = TypedDict( + "_CompilerConfigDictValue", + { + "name": str, + "linker": str, + "version": str, + "commands": str, + "args": str, + "linker args": str, + }, +) +_CompilerConfigDict = TypedDict( + "_CompilerConfigDict", + { + "c": _CompilerConfigDictValue, + "cython": _CompilerConfigDictValue, + "c++": _CompilerConfigDictValue, + }, +) +_MachineInformationDict = TypedDict( + "_MachineInformationDict", + { + "host": _MachineInformationDictValue, + "build": _MachineInformationDictValue, + "cross-compiled": NotRequired[L[True]], + }, +) + +@type_check_only +class _MachineInformationDictValue(TypedDict): + cpu: str + family: str + endian: L["little", "big"] + system: str + +_BuildDependenciesDictValue = TypedDict( + "_BuildDependenciesDictValue", + { + "name": str, + "found": NotRequired[L[True]], + "version": str, + "include directory": str, + "lib directory": str, + "openblas configuration": str, + "pc file directory": str, + }, +) + +class _BuildDependenciesDict(TypedDict): + blas: _BuildDependenciesDictValue + lapack: _BuildDependenciesDictValue + +class _PythonInformationDict(TypedDict): + path: str + version: str + +_SIMDExtensionsDict = TypedDict( + "_SIMDExtensionsDict", + { + "baseline": list[str], + "found": list[str], + "not found": list[str], + }, +) + +_ConfigDict = TypedDict( + "_ConfigDict", + { + "Compilers": _CompilerConfigDict, + "Machine Information": _MachineInformationDict, + "Build Dependencies": _BuildDependenciesDict, + "Python Information": _PythonInformationDict, + "SIMD Extensions": _SIMDExtensionsDict, + }, +) + +### + +__all__ = ["show_config"] + +CONFIG: Final[_ConfigDict] = ... + +class DisplayModes(Enum): + stdout = "stdout" + dicts = "dicts" + +def _check_pyyaml() -> ModuleType: ... + +@overload +def show(mode: L["stdout"] = "stdout") -> None: ... +@overload +def show(mode: L["dicts"]) -> _ConfigDict: ... + +@overload +def show_config(mode: L["stdout"] = "stdout") -> None: ... +@overload +def show_config(mode: L["dicts"]) -> _ConfigDict: ... diff --git a/TTS/Kokoro/.venv/Lib/site-packages/numpy/__init__.cython-30.pxd b/TTS/Kokoro/.venv/Lib/site-packages/numpy/__init__.cython-30.pxd new file mode 100644 index 0000000000000000000000000000000000000000..2b5169537dfb0d0fc97712d584a61dedac04b33a --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/numpy/__init__.cython-30.pxd @@ -0,0 +1,1242 @@ +# NumPy static imports for Cython >= 3.0 +# +# If any of the PyArray_* functions are called, import_array must be +# called first. This is done automatically by Cython 3.0+ if a call +# is not detected inside of the module. +# +# Author: Dag Sverre Seljebotn +# + +from cpython.ref cimport Py_INCREF +from cpython.object cimport PyObject, PyTypeObject, PyObject_TypeCheck +cimport libc.stdio as stdio + + +cdef extern from *: + # Leave a marker that the NumPy declarations came from NumPy itself and not from Cython. + # See https://github.com/cython/cython/issues/3573 + """ + /* Using NumPy API declarations from "numpy/__init__.cython-30.pxd" */ + """ + + +cdef extern from "numpy/arrayobject.h": + # It would be nice to use size_t and ssize_t, but ssize_t has special + # implicit conversion rules, so just use "long". + # Note: The actual type only matters for Cython promotion, so long + # is closer than int, but could lead to incorrect promotion. + # (Not to worrying, and always the status-quo.) + ctypedef signed long npy_intp + ctypedef unsigned long npy_uintp + + ctypedef unsigned char npy_bool + + ctypedef signed char npy_byte + ctypedef signed short npy_short + ctypedef signed int npy_int + ctypedef signed long npy_long + ctypedef signed long long npy_longlong + + ctypedef unsigned char npy_ubyte + ctypedef unsigned short npy_ushort + ctypedef unsigned int npy_uint + ctypedef unsigned long npy_ulong + ctypedef unsigned long long npy_ulonglong + + ctypedef float npy_float + ctypedef double npy_double + ctypedef long double npy_longdouble + + ctypedef signed char npy_int8 + ctypedef signed short npy_int16 + ctypedef signed int npy_int32 + ctypedef signed long long npy_int64 + + ctypedef unsigned char npy_uint8 + ctypedef unsigned short npy_uint16 + ctypedef unsigned int npy_uint32 + ctypedef unsigned long long npy_uint64 + + ctypedef float npy_float32 + ctypedef double npy_float64 + ctypedef long double npy_float80 + ctypedef long double npy_float96 + ctypedef long double npy_float128 + + ctypedef struct npy_cfloat: + pass + + ctypedef struct npy_cdouble: + pass + + ctypedef struct npy_clongdouble: + pass + + ctypedef struct npy_complex64: + pass + + ctypedef struct npy_complex128: + pass + + ctypedef struct npy_complex160: + pass + + ctypedef struct npy_complex192: + pass + + ctypedef struct npy_complex256: + pass + + ctypedef struct PyArray_Dims: + npy_intp *ptr + int len + + + cdef enum NPY_TYPES: + NPY_BOOL + NPY_BYTE + NPY_UBYTE + NPY_SHORT + NPY_USHORT + NPY_INT + NPY_UINT + NPY_LONG + NPY_ULONG + NPY_LONGLONG + NPY_ULONGLONG + NPY_FLOAT + NPY_DOUBLE + NPY_LONGDOUBLE + NPY_CFLOAT + NPY_CDOUBLE + NPY_CLONGDOUBLE + NPY_OBJECT + NPY_STRING + NPY_UNICODE + NPY_VSTRING + NPY_VOID + NPY_DATETIME + NPY_TIMEDELTA + NPY_NTYPES_LEGACY + NPY_NOTYPE + + NPY_INT8 + NPY_INT16 + NPY_INT32 + NPY_INT64 + NPY_UINT8 + NPY_UINT16 + NPY_UINT32 + NPY_UINT64 + NPY_FLOAT16 + NPY_FLOAT32 + NPY_FLOAT64 + NPY_FLOAT80 + NPY_FLOAT96 + NPY_FLOAT128 + NPY_COMPLEX64 + NPY_COMPLEX128 + NPY_COMPLEX160 + NPY_COMPLEX192 + NPY_COMPLEX256 + + NPY_INTP + NPY_UINTP + NPY_DEFAULT_INT # Not a compile time constant (normally)! + + ctypedef enum NPY_ORDER: + NPY_ANYORDER + NPY_CORDER + NPY_FORTRANORDER + NPY_KEEPORDER + + ctypedef enum NPY_CASTING: + NPY_NO_CASTING + NPY_EQUIV_CASTING + NPY_SAFE_CASTING + NPY_SAME_KIND_CASTING + NPY_UNSAFE_CASTING + NPY_SAME_VALUE_CASTING + + ctypedef enum NPY_CLIPMODE: + NPY_CLIP + NPY_WRAP + NPY_RAISE + + ctypedef enum NPY_SCALARKIND: + NPY_NOSCALAR, + NPY_BOOL_SCALAR, + NPY_INTPOS_SCALAR, + NPY_INTNEG_SCALAR, + NPY_FLOAT_SCALAR, + NPY_COMPLEX_SCALAR, + NPY_OBJECT_SCALAR + + ctypedef enum NPY_SORTKIND: + NPY_QUICKSORT + NPY_HEAPSORT + NPY_MERGESORT + + ctypedef enum NPY_SEARCHSIDE: + NPY_SEARCHLEFT + NPY_SEARCHRIGHT + + enum: + NPY_ARRAY_C_CONTIGUOUS + NPY_ARRAY_F_CONTIGUOUS + NPY_ARRAY_OWNDATA + NPY_ARRAY_FORCECAST + NPY_ARRAY_ENSURECOPY + NPY_ARRAY_ENSUREARRAY + NPY_ARRAY_ELEMENTSTRIDES + NPY_ARRAY_ALIGNED + NPY_ARRAY_NOTSWAPPED + NPY_ARRAY_WRITEABLE + NPY_ARRAY_WRITEBACKIFCOPY + + NPY_ARRAY_BEHAVED + NPY_ARRAY_BEHAVED_NS + NPY_ARRAY_CARRAY + NPY_ARRAY_CARRAY_RO + NPY_ARRAY_FARRAY + NPY_ARRAY_FARRAY_RO + NPY_ARRAY_DEFAULT + + NPY_ARRAY_IN_ARRAY + NPY_ARRAY_OUT_ARRAY + NPY_ARRAY_INOUT_ARRAY + NPY_ARRAY_IN_FARRAY + NPY_ARRAY_OUT_FARRAY + NPY_ARRAY_INOUT_FARRAY + + NPY_ARRAY_UPDATE_ALL + + cdef enum: + NPY_MAXDIMS # 64 on NumPy 2.x and 32 on NumPy 1.x + NPY_RAVEL_AXIS # Used for functions like PyArray_Mean + + ctypedef void (*PyArray_VectorUnaryFunc)(void *, void *, npy_intp, void *, void *) + + ctypedef struct PyArray_ArrayDescr: + # shape is a tuple, but Cython doesn't support "tuple shape" + # inside a non-PyObject declaration, so we have to declare it + # as just a PyObject*. + PyObject* shape + + ctypedef struct PyArray_Descr: + pass + + ctypedef class numpy.dtype [object PyArray_Descr, check_size ignore]: + # Use PyDataType_* macros when possible, however there are no macros + # for accessing some of the fields, so some are defined. + cdef PyTypeObject* typeobj + cdef char kind + cdef char type + # Numpy sometimes mutates this without warning (e.g. it'll + # sometimes change "|" to "<" in shared dtype objects on + # little-endian machines). If this matters to you, use + # PyArray_IsNativeByteOrder(dtype.byteorder) instead of + # directly accessing this field. + cdef char byteorder + cdef int type_num + + @property + cdef inline npy_intp itemsize(self) noexcept nogil: + return PyDataType_ELSIZE(self) + + @property + cdef inline npy_intp alignment(self) noexcept nogil: + return PyDataType_ALIGNMENT(self) + + # Use fields/names with care as they may be NULL. You must check + # for this using PyDataType_HASFIELDS. + @property + cdef inline object fields(self): + return PyDataType_FIELDS(self) + + @property + cdef inline tuple names(self): + return PyDataType_NAMES(self) + + # Use PyDataType_HASSUBARRAY to test whether this field is + # valid (the pointer can be NULL). Most users should access + # this field via the inline helper method PyDataType_SHAPE. + @property + cdef inline PyArray_ArrayDescr* subarray(self) noexcept nogil: + return PyDataType_SUBARRAY(self) + + @property + cdef inline npy_uint64 flags(self) noexcept nogil: + """The data types flags.""" + return PyDataType_FLAGS(self) + + + ctypedef class numpy.flatiter [object PyArrayIterObject, check_size ignore]: + # Use through macros + pass + + ctypedef class numpy.broadcast [object PyArrayMultiIterObject, check_size ignore]: + + @property + cdef inline int numiter(self) noexcept nogil: + """The number of arrays that need to be broadcast to the same shape.""" + return PyArray_MultiIter_NUMITER(self) + + @property + cdef inline npy_intp size(self) noexcept nogil: + """The total broadcasted size.""" + return PyArray_MultiIter_SIZE(self) + + @property + cdef inline npy_intp index(self) noexcept nogil: + """The current (1-d) index into the broadcasted result.""" + return PyArray_MultiIter_INDEX(self) + + @property + cdef inline int nd(self) noexcept nogil: + """The number of dimensions in the broadcasted result.""" + return PyArray_MultiIter_NDIM(self) + + @property + cdef inline npy_intp* dimensions(self) noexcept nogil: + """The shape of the broadcasted result.""" + return PyArray_MultiIter_DIMS(self) + + @property + cdef inline void** iters(self) noexcept nogil: + """An array of iterator objects that holds the iterators for the arrays to be broadcast together. + On return, the iterators are adjusted for broadcasting.""" + return PyArray_MultiIter_ITERS(self) + + + ctypedef struct PyArrayObject: + # For use in situations where ndarray can't replace PyArrayObject*, + # like PyArrayObject**. + pass + + ctypedef class numpy.ndarray [object PyArrayObject, check_size ignore]: + cdef __cythonbufferdefaults__ = {"mode": "strided"} + + # NOTE: no field declarations since direct access is deprecated since NumPy 1.7 + # Instead, we use properties that map to the corresponding C-API functions. + + @property + cdef inline PyObject* base(self) noexcept nogil: + """Returns a borrowed reference to the object owning the data/memory. + """ + return PyArray_BASE(self) + + @property + cdef inline dtype descr(self): + """Returns an owned reference to the dtype of the array. + """ + return PyArray_DESCR(self) + + @property + cdef inline int ndim(self) noexcept nogil: + """Returns the number of dimensions in the array. + """ + return PyArray_NDIM(self) + + @property + cdef inline npy_intp *shape(self) noexcept nogil: + """Returns a pointer to the dimensions/shape of the array. + The number of elements matches the number of dimensions of the array (ndim). + Can return NULL for 0-dimensional arrays. + """ + return PyArray_DIMS(self) + + @property + cdef inline npy_intp *strides(self) noexcept nogil: + """Returns a pointer to the strides of the array. + The number of elements matches the number of dimensions of the array (ndim). + """ + return PyArray_STRIDES(self) + + @property + cdef inline npy_intp size(self) noexcept nogil: + """Returns the total size (in number of elements) of the array. + """ + return PyArray_SIZE(self) + + @property + cdef inline char* data(self) noexcept nogil: + """The pointer to the data buffer as a char*. + This is provided for legacy reasons to avoid direct struct field access. + For new code that needs this access, you probably want to cast the result + of `PyArray_DATA()` instead, which returns a 'void*'. + """ + return PyArray_BYTES(self) + + + int _import_array() except -1 + # A second definition so _import_array isn't marked as used when we use it here. + # Do not use - subject to change any time. + int __pyx_import_array "_import_array"() except -1 + + # + # Macros from ndarrayobject.h + # + bint PyArray_CHKFLAGS(ndarray m, int flags) nogil + bint PyArray_IS_C_CONTIGUOUS(ndarray arr) nogil + bint PyArray_IS_F_CONTIGUOUS(ndarray arr) nogil + bint PyArray_ISCONTIGUOUS(ndarray m) nogil + bint PyArray_ISWRITEABLE(ndarray m) nogil + bint PyArray_ISALIGNED(ndarray m) nogil + + int PyArray_NDIM(ndarray) nogil + bint PyArray_ISONESEGMENT(ndarray) nogil + bint PyArray_ISFORTRAN(ndarray) nogil + int PyArray_FORTRANIF(ndarray) nogil + + void* PyArray_DATA(ndarray) nogil + char* PyArray_BYTES(ndarray) nogil + + npy_intp* PyArray_DIMS(ndarray) nogil + npy_intp* PyArray_STRIDES(ndarray) nogil + npy_intp PyArray_DIM(ndarray, size_t) nogil + npy_intp PyArray_STRIDE(ndarray, size_t) nogil + + PyObject *PyArray_BASE(ndarray) nogil # returns borrowed reference! + PyArray_Descr *PyArray_DESCR(ndarray) nogil # returns borrowed reference to dtype! + PyArray_Descr *PyArray_DTYPE(ndarray) nogil # returns borrowed reference to dtype! NP 1.7+ alias for descr. + int PyArray_FLAGS(ndarray) nogil + void PyArray_CLEARFLAGS(ndarray, int flags) nogil # Added in NumPy 1.7 + void PyArray_ENABLEFLAGS(ndarray, int flags) nogil # Added in NumPy 1.7 + npy_intp PyArray_ITEMSIZE(ndarray) nogil + int PyArray_TYPE(ndarray arr) nogil + + object PyArray_GETITEM(ndarray arr, void *itemptr) + int PyArray_SETITEM(ndarray arr, void *itemptr, object obj) except -1 + + bint PyTypeNum_ISBOOL(int) nogil + bint PyTypeNum_ISUNSIGNED(int) nogil + bint PyTypeNum_ISSIGNED(int) nogil + bint PyTypeNum_ISINTEGER(int) nogil + bint PyTypeNum_ISFLOAT(int) nogil + bint PyTypeNum_ISNUMBER(int) nogil + bint PyTypeNum_ISSTRING(int) nogil + bint PyTypeNum_ISCOMPLEX(int) nogil + bint PyTypeNum_ISFLEXIBLE(int) nogil + bint PyTypeNum_ISUSERDEF(int) nogil + bint PyTypeNum_ISEXTENDED(int) nogil + bint PyTypeNum_ISOBJECT(int) nogil + + npy_intp PyDataType_ELSIZE(dtype) nogil + npy_intp PyDataType_ALIGNMENT(dtype) nogil + PyObject* PyDataType_METADATA(dtype) nogil + PyArray_ArrayDescr* PyDataType_SUBARRAY(dtype) nogil + PyObject* PyDataType_NAMES(dtype) nogil + PyObject* PyDataType_FIELDS(dtype) nogil + + bint PyDataType_ISBOOL(dtype) nogil + bint PyDataType_ISUNSIGNED(dtype) nogil + bint PyDataType_ISSIGNED(dtype) nogil + bint PyDataType_ISINTEGER(dtype) nogil + bint PyDataType_ISFLOAT(dtype) nogil + bint PyDataType_ISNUMBER(dtype) nogil + bint PyDataType_ISSTRING(dtype) nogil + bint PyDataType_ISCOMPLEX(dtype) nogil + bint PyDataType_ISFLEXIBLE(dtype) nogil + bint PyDataType_ISUSERDEF(dtype) nogil + bint PyDataType_ISEXTENDED(dtype) nogil + bint PyDataType_ISOBJECT(dtype) nogil + bint PyDataType_HASFIELDS(dtype) nogil + bint PyDataType_HASSUBARRAY(dtype) nogil + npy_uint64 PyDataType_FLAGS(dtype) nogil + + bint PyArray_ISBOOL(ndarray) nogil + bint PyArray_ISUNSIGNED(ndarray) nogil + bint PyArray_ISSIGNED(ndarray) nogil + bint PyArray_ISINTEGER(ndarray) nogil + bint PyArray_ISFLOAT(ndarray) nogil + bint PyArray_ISNUMBER(ndarray) nogil + bint PyArray_ISSTRING(ndarray) nogil + bint PyArray_ISCOMPLEX(ndarray) nogil + bint PyArray_ISFLEXIBLE(ndarray) nogil + bint PyArray_ISUSERDEF(ndarray) nogil + bint PyArray_ISEXTENDED(ndarray) nogil + bint PyArray_ISOBJECT(ndarray) nogil + bint PyArray_HASFIELDS(ndarray) nogil + + bint PyArray_ISVARIABLE(ndarray) nogil + + bint PyArray_SAFEALIGNEDCOPY(ndarray) nogil + bint PyArray_ISNBO(char) nogil # works on ndarray.byteorder + bint PyArray_IsNativeByteOrder(char) nogil # works on ndarray.byteorder + bint PyArray_ISNOTSWAPPED(ndarray) nogil + bint PyArray_ISBYTESWAPPED(ndarray) nogil + + bint PyArray_FLAGSWAP(ndarray, int) nogil + + bint PyArray_ISCARRAY(ndarray) nogil + bint PyArray_ISCARRAY_RO(ndarray) nogil + bint PyArray_ISFARRAY(ndarray) nogil + bint PyArray_ISFARRAY_RO(ndarray) nogil + bint PyArray_ISBEHAVED(ndarray) nogil + bint PyArray_ISBEHAVED_RO(ndarray) nogil + + + bint PyDataType_ISNOTSWAPPED(dtype) nogil + bint PyDataType_ISBYTESWAPPED(dtype) nogil + + bint PyArray_DescrCheck(object) + + bint PyArray_Check(object) + bint PyArray_CheckExact(object) + + # Cannot be supported due to out arg: + # bint PyArray_HasArrayInterfaceType(object, dtype, object, object&) + # bint PyArray_HasArrayInterface(op, out) + + + bint PyArray_IsZeroDim(object) + # Cannot be supported due to ## ## in macro: + # bint PyArray_IsScalar(object, verbatim work) + bint PyArray_CheckScalar(object) + bint PyArray_IsPythonNumber(object) + bint PyArray_IsPythonScalar(object) + bint PyArray_IsAnyScalar(object) + bint PyArray_CheckAnyScalar(object) + + ndarray PyArray_GETCONTIGUOUS(ndarray) + bint PyArray_SAMESHAPE(ndarray, ndarray) nogil + npy_intp PyArray_SIZE(ndarray) nogil + npy_intp PyArray_NBYTES(ndarray) nogil + + object PyArray_FROM_O(object) + object PyArray_FROM_OF(object m, int flags) + object PyArray_FROM_OT(object m, int type) + object PyArray_FROM_OTF(object m, int type, int flags) + object PyArray_FROMANY(object m, int type, int min, int max, int flags) + object PyArray_ZEROS(int nd, npy_intp* dims, int type, int fortran) + object PyArray_EMPTY(int nd, npy_intp* dims, int type, int fortran) + void PyArray_FILLWBYTE(ndarray, int val) + object PyArray_ContiguousFromAny(op, int, int min_depth, int max_depth) + unsigned char PyArray_EquivArrTypes(ndarray a1, ndarray a2) + bint PyArray_EquivByteorders(int b1, int b2) nogil + object PyArray_SimpleNew(int nd, npy_intp* dims, int typenum) + object PyArray_SimpleNewFromData(int nd, npy_intp* dims, int typenum, void* data) + #object PyArray_SimpleNewFromDescr(int nd, npy_intp* dims, dtype descr) + object PyArray_ToScalar(void* data, ndarray arr) + + void* PyArray_GETPTR1(ndarray m, npy_intp i) nogil + void* PyArray_GETPTR2(ndarray m, npy_intp i, npy_intp j) nogil + void* PyArray_GETPTR3(ndarray m, npy_intp i, npy_intp j, npy_intp k) nogil + void* PyArray_GETPTR4(ndarray m, npy_intp i, npy_intp j, npy_intp k, npy_intp l) nogil + + # Cannot be supported due to out arg + # void PyArray_DESCR_REPLACE(descr) + + + object PyArray_Copy(ndarray) + object PyArray_FromObject(object op, int type, int min_depth, int max_depth) + object PyArray_ContiguousFromObject(object op, int type, int min_depth, int max_depth) + object PyArray_CopyFromObject(object op, int type, int min_depth, int max_depth) + + object PyArray_Cast(ndarray mp, int type_num) + object PyArray_Take(ndarray ap, object items, int axis) + object PyArray_Put(ndarray ap, object items, object values) + + void PyArray_ITER_RESET(flatiter it) nogil + void PyArray_ITER_NEXT(flatiter it) nogil + void PyArray_ITER_GOTO(flatiter it, npy_intp* destination) nogil + void PyArray_ITER_GOTO1D(flatiter it, npy_intp ind) nogil + void* PyArray_ITER_DATA(flatiter it) nogil + bint PyArray_ITER_NOTDONE(flatiter it) nogil + + void PyArray_MultiIter_RESET(broadcast multi) nogil + void PyArray_MultiIter_NEXT(broadcast multi) nogil + void PyArray_MultiIter_GOTO(broadcast multi, npy_intp dest) nogil + void PyArray_MultiIter_GOTO1D(broadcast multi, npy_intp ind) nogil + void* PyArray_MultiIter_DATA(broadcast multi, npy_intp i) nogil + void PyArray_MultiIter_NEXTi(broadcast multi, npy_intp i) nogil + bint PyArray_MultiIter_NOTDONE(broadcast multi) nogil + npy_intp PyArray_MultiIter_SIZE(broadcast multi) nogil + int PyArray_MultiIter_NDIM(broadcast multi) nogil + npy_intp PyArray_MultiIter_INDEX(broadcast multi) nogil + int PyArray_MultiIter_NUMITER(broadcast multi) nogil + npy_intp* PyArray_MultiIter_DIMS(broadcast multi) nogil + void** PyArray_MultiIter_ITERS(broadcast multi) nogil + + # Functions from __multiarray_api.h + + # Functions taking dtype and returning object/ndarray are disabled + # for now as they steal dtype references. I'm conservative and disable + # more than is probably needed until it can be checked further. + int PyArray_INCREF (ndarray) except * # uses PyArray_Item_INCREF... + int PyArray_XDECREF (ndarray) except * # uses PyArray_Item_DECREF... + dtype PyArray_DescrFromType (int) + object PyArray_TypeObjectFromType (int) + char * PyArray_Zero (ndarray) + char * PyArray_One (ndarray) + #object PyArray_CastToType (ndarray, dtype, int) + int PyArray_CanCastSafely (int, int) # writes errors + npy_bool PyArray_CanCastTo (dtype, dtype) # writes errors + int PyArray_ObjectType (object, int) except 0 + dtype PyArray_DescrFromObject (object, dtype) + #ndarray* PyArray_ConvertToCommonType (object, int *) + dtype PyArray_DescrFromScalar (object) + dtype PyArray_DescrFromTypeObject (object) + npy_intp PyArray_Size (object) + #object PyArray_Scalar (void *, dtype, object) + #object PyArray_FromScalar (object, dtype) + void PyArray_ScalarAsCtype (object, void *) + #int PyArray_CastScalarToCtype (object, void *, dtype) + #int PyArray_CastScalarDirect (object, dtype, void *, int) + #PyArray_VectorUnaryFunc * PyArray_GetCastFunc (dtype, int) + #object PyArray_FromAny (object, dtype, int, int, int, object) + object PyArray_EnsureArray (object) + object PyArray_EnsureAnyArray (object) + #object PyArray_FromFile (stdio.FILE *, dtype, npy_intp, char *) + #object PyArray_FromString (char *, npy_intp, dtype, npy_intp, char *) + #object PyArray_FromBuffer (object, dtype, npy_intp, npy_intp) + #object PyArray_FromIter (object, dtype, npy_intp) + object PyArray_Return (ndarray) + #object PyArray_GetField (ndarray, dtype, int) + #int PyArray_SetField (ndarray, dtype, int, object) except -1 + object PyArray_Byteswap (ndarray, npy_bool) + object PyArray_Resize (ndarray, PyArray_Dims *, int, NPY_ORDER) + int PyArray_CopyInto (ndarray, ndarray) except -1 + int PyArray_CopyAnyInto (ndarray, ndarray) except -1 + int PyArray_CopyObject (ndarray, object) except -1 + object PyArray_NewCopy (ndarray, NPY_ORDER) + object PyArray_ToList (ndarray) + object PyArray_ToString (ndarray, NPY_ORDER) + int PyArray_ToFile (ndarray, stdio.FILE *, char *, char *) except -1 + int PyArray_Dump (object, object, int) except -1 + object PyArray_Dumps (object, int) + int PyArray_ValidType (int) # Cannot error + void PyArray_UpdateFlags (ndarray, int) + object PyArray_New (type, int, npy_intp *, int, npy_intp *, void *, int, int, object) + #object PyArray_NewFromDescr (type, dtype, int, npy_intp *, npy_intp *, void *, int, object) + #dtype PyArray_DescrNew (dtype) + dtype PyArray_DescrNewFromType (int) + double PyArray_GetPriority (object, double) # clears errors as of 1.25 + object PyArray_IterNew (object) + object PyArray_MultiIterNew (int, ...) + + int PyArray_PyIntAsInt (object) except? -1 + npy_intp PyArray_PyIntAsIntp (object) + int PyArray_Broadcast (broadcast) except -1 + int PyArray_FillWithScalar (ndarray, object) except -1 + npy_bool PyArray_CheckStrides (int, int, npy_intp, npy_intp, npy_intp *, npy_intp *) + dtype PyArray_DescrNewByteorder (dtype, char) + object PyArray_IterAllButAxis (object, int *) + #object PyArray_CheckFromAny (object, dtype, int, int, int, object) + #object PyArray_FromArray (ndarray, dtype, int) + object PyArray_FromInterface (object) + object PyArray_FromStructInterface (object) + #object PyArray_FromArrayAttr (object, dtype, object) + #NPY_SCALARKIND PyArray_ScalarKind (int, ndarray*) + int PyArray_CanCoerceScalar (int, int, NPY_SCALARKIND) + npy_bool PyArray_CanCastScalar (type, type) + int PyArray_RemoveSmallest (broadcast) except -1 + int PyArray_ElementStrides (object) + void PyArray_Item_INCREF (char *, dtype) except * + void PyArray_Item_XDECREF (char *, dtype) except * + object PyArray_Transpose (ndarray, PyArray_Dims *) + object PyArray_TakeFrom (ndarray, object, int, ndarray, NPY_CLIPMODE) + object PyArray_PutTo (ndarray, object, object, NPY_CLIPMODE) + object PyArray_PutMask (ndarray, object, object) + object PyArray_Repeat (ndarray, object, int) + object PyArray_Choose (ndarray, object, ndarray, NPY_CLIPMODE) + int PyArray_Sort (ndarray, int, NPY_SORTKIND) except -1 + object PyArray_ArgSort (ndarray, int, NPY_SORTKIND) + object PyArray_SearchSorted (ndarray, object, NPY_SEARCHSIDE, PyObject *) + object PyArray_ArgMax (ndarray, int, ndarray) + object PyArray_ArgMin (ndarray, int, ndarray) + object PyArray_Reshape (ndarray, object) + object PyArray_Newshape (ndarray, PyArray_Dims *, NPY_ORDER) + object PyArray_Squeeze (ndarray) + #object PyArray_View (ndarray, dtype, type) + object PyArray_SwapAxes (ndarray, int, int) + object PyArray_Max (ndarray, int, ndarray) + object PyArray_Min (ndarray, int, ndarray) + object PyArray_Ptp (ndarray, int, ndarray) + object PyArray_Mean (ndarray, int, int, ndarray) + object PyArray_Trace (ndarray, int, int, int, int, ndarray) + object PyArray_Diagonal (ndarray, int, int, int) + object PyArray_Clip (ndarray, object, object, ndarray) + object PyArray_Conjugate (ndarray, ndarray) + object PyArray_Nonzero (ndarray) + object PyArray_Std (ndarray, int, int, ndarray, int) + object PyArray_Sum (ndarray, int, int, ndarray) + object PyArray_CumSum (ndarray, int, int, ndarray) + object PyArray_Prod (ndarray, int, int, ndarray) + object PyArray_CumProd (ndarray, int, int, ndarray) + object PyArray_All (ndarray, int, ndarray) + object PyArray_Any (ndarray, int, ndarray) + object PyArray_Compress (ndarray, object, int, ndarray) + object PyArray_Flatten (ndarray, NPY_ORDER) + object PyArray_Ravel (ndarray, NPY_ORDER) + npy_intp PyArray_MultiplyList (npy_intp *, int) + int PyArray_MultiplyIntList (int *, int) + void * PyArray_GetPtr (ndarray, npy_intp*) + int PyArray_CompareLists (npy_intp *, npy_intp *, int) + #int PyArray_AsCArray (object*, void *, npy_intp *, int, dtype) + int PyArray_Free (object, void *) + #int PyArray_Converter (object, object*) + int PyArray_IntpFromSequence (object, npy_intp *, int) except -1 + object PyArray_Concatenate (object, int) + object PyArray_InnerProduct (object, object) + object PyArray_MatrixProduct (object, object) + object PyArray_Correlate (object, object, int) + #int PyArray_DescrConverter (object, dtype*) except 0 + #int PyArray_DescrConverter2 (object, dtype*) except 0 + int PyArray_IntpConverter (object, PyArray_Dims *) except 0 + #int PyArray_BufferConverter (object, chunk) except 0 + int PyArray_AxisConverter (object, int *) except 0 + int PyArray_BoolConverter (object, npy_bool *) except 0 + int PyArray_ByteorderConverter (object, char *) except 0 + int PyArray_OrderConverter (object, NPY_ORDER *) except 0 + unsigned char PyArray_EquivTypes (dtype, dtype) # clears errors + #object PyArray_Zeros (int, npy_intp *, dtype, int) + #object PyArray_Empty (int, npy_intp *, dtype, int) + object PyArray_Where (object, object, object) + object PyArray_Arange (double, double, double, int) + #object PyArray_ArangeObj (object, object, object, dtype) + int PyArray_SortkindConverter (object, NPY_SORTKIND *) except 0 + object PyArray_LexSort (object, int) + object PyArray_Round (ndarray, int, ndarray) + unsigned char PyArray_EquivTypenums (int, int) + int PyArray_RegisterDataType (dtype) except -1 + int PyArray_RegisterCastFunc (dtype, int, PyArray_VectorUnaryFunc *) except -1 + int PyArray_RegisterCanCast (dtype, int, NPY_SCALARKIND) except -1 + #void PyArray_InitArrFuncs (PyArray_ArrFuncs *) + object PyArray_IntTupleFromIntp (int, npy_intp *) + int PyArray_ClipmodeConverter (object, NPY_CLIPMODE *) except 0 + #int PyArray_OutputConverter (object, ndarray*) except 0 + object PyArray_BroadcastToShape (object, npy_intp *, int) + #int PyArray_DescrAlignConverter (object, dtype*) except 0 + #int PyArray_DescrAlignConverter2 (object, dtype*) except 0 + int PyArray_SearchsideConverter (object, void *) except 0 + object PyArray_CheckAxis (ndarray, int *, int) + npy_intp PyArray_OverflowMultiplyList (npy_intp *, int) + int PyArray_SetBaseObject(ndarray, base) except -1 # NOTE: steals a reference to base! Use "set_array_base()" instead. + + # The memory handler functions require the NumPy 1.22 API + # and may require defining NPY_TARGET_VERSION + ctypedef struct PyDataMemAllocator: + void *ctx + void* (*malloc) (void *ctx, size_t size) + void* (*calloc) (void *ctx, size_t nelem, size_t elsize) + void* (*realloc) (void *ctx, void *ptr, size_t new_size) + void (*free) (void *ctx, void *ptr, size_t size) + + ctypedef struct PyDataMem_Handler: + char* name + npy_uint8 version + PyDataMemAllocator allocator + + object PyDataMem_SetHandler(object handler) + object PyDataMem_GetHandler() + + # additional datetime related functions are defined below + + +# Typedefs that matches the runtime dtype objects in +# the numpy module. + +# The ones that are commented out needs an IFDEF function +# in Cython to enable them only on the right systems. + +ctypedef npy_int8 int8_t +ctypedef npy_int16 int16_t +ctypedef npy_int32 int32_t +ctypedef npy_int64 int64_t + +ctypedef npy_uint8 uint8_t +ctypedef npy_uint16 uint16_t +ctypedef npy_uint32 uint32_t +ctypedef npy_uint64 uint64_t + +ctypedef npy_float32 float32_t +ctypedef npy_float64 float64_t +#ctypedef npy_float80 float80_t +#ctypedef npy_float128 float128_t + +ctypedef float complex complex64_t +ctypedef double complex complex128_t + +ctypedef npy_longlong longlong_t +ctypedef npy_ulonglong ulonglong_t + +ctypedef npy_intp intp_t +ctypedef npy_uintp uintp_t + +ctypedef npy_double float_t +ctypedef npy_double double_t +ctypedef npy_longdouble longdouble_t + +ctypedef float complex cfloat_t +ctypedef double complex cdouble_t +ctypedef double complex complex_t +ctypedef long double complex clongdouble_t + +cdef inline object PyArray_MultiIterNew1(a): + return PyArray_MultiIterNew(1, a) + +cdef inline object PyArray_MultiIterNew2(a, b): + return PyArray_MultiIterNew(2, a, b) + +cdef inline object PyArray_MultiIterNew3(a, b, c): + return PyArray_MultiIterNew(3, a, b, c) + +cdef inline object PyArray_MultiIterNew4(a, b, c, d): + return PyArray_MultiIterNew(4, a, b, c, d) + +cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): + return PyArray_MultiIterNew(5, a, b, c, d, e) + +cdef inline tuple PyDataType_SHAPE(dtype d): + if PyDataType_HASSUBARRAY(d): + return d.subarray.shape + else: + return () + + +cdef extern from "numpy/ndarrayobject.h": + PyTypeObject PyTimedeltaArrType_Type + PyTypeObject PyDatetimeArrType_Type + ctypedef int64_t npy_timedelta + ctypedef int64_t npy_datetime + +cdef extern from "numpy/ndarraytypes.h": + ctypedef struct PyArray_DatetimeMetaData: + NPY_DATETIMEUNIT base + int64_t num + + ctypedef struct npy_datetimestruct: + int64_t year + int32_t month, day, hour, min, sec, us, ps, as + + # Iterator API added in v1.6 + # + # These don't match the definition in the C API because Cython can't wrap + # function pointers that return functions. + # https://github.com/cython/cython/issues/6720 + ctypedef int (*NpyIter_IterNextFunc "NpyIter_IterNextFunc *")(NpyIter* it) noexcept nogil + ctypedef void (*NpyIter_GetMultiIndexFunc "NpyIter_GetMultiIndexFunc *")(NpyIter* it, npy_intp* outcoords) noexcept nogil + + +cdef extern from "numpy/arrayscalars.h": + + # abstract types + ctypedef class numpy.generic [object PyObject]: + pass + ctypedef class numpy.number [object PyObject]: + pass + ctypedef class numpy.integer [object PyObject]: + pass + ctypedef class numpy.signedinteger [object PyObject]: + pass + ctypedef class numpy.unsignedinteger [object PyObject]: + pass + ctypedef class numpy.inexact [object PyObject]: + pass + ctypedef class numpy.floating [object PyObject]: + pass + ctypedef class numpy.complexfloating [object PyObject]: + pass + ctypedef class numpy.flexible [object PyObject]: + pass + ctypedef class numpy.character [object PyObject]: + pass + + ctypedef struct PyDatetimeScalarObject: + # PyObject_HEAD + npy_datetime obval + PyArray_DatetimeMetaData obmeta + + ctypedef struct PyTimedeltaScalarObject: + # PyObject_HEAD + npy_timedelta obval + PyArray_DatetimeMetaData obmeta + + ctypedef enum NPY_DATETIMEUNIT: + NPY_FR_Y + NPY_FR_M + NPY_FR_W + NPY_FR_D + NPY_FR_B + NPY_FR_h + NPY_FR_m + NPY_FR_s + NPY_FR_ms + NPY_FR_us + NPY_FR_ns + NPY_FR_ps + NPY_FR_fs + NPY_FR_as + NPY_FR_GENERIC + + +cdef extern from "numpy/arrayobject.h": + # These are part of the C-API defined in `__multiarray_api.h` + + # NumPy internal definitions in datetime_strings.c: + int get_datetime_iso_8601_strlen "NpyDatetime_GetDatetimeISO8601StrLen" ( + int local, NPY_DATETIMEUNIT base) + int make_iso_8601_datetime "NpyDatetime_MakeISO8601Datetime" ( + npy_datetimestruct *dts, char *outstr, npy_intp outlen, + int local, int utc, NPY_DATETIMEUNIT base, int tzoffset, + NPY_CASTING casting) except -1 + + # NumPy internal definition in datetime.c: + # May return 1 to indicate that object does not appear to be a datetime + # (returns 0 on success). + int convert_pydatetime_to_datetimestruct "NpyDatetime_ConvertPyDateTimeToDatetimeStruct" ( + PyObject *obj, npy_datetimestruct *out, + NPY_DATETIMEUNIT *out_bestunit, int apply_tzinfo) except -1 + int convert_datetime64_to_datetimestruct "NpyDatetime_ConvertDatetime64ToDatetimeStruct" ( + PyArray_DatetimeMetaData *meta, npy_datetime dt, + npy_datetimestruct *out) except -1 + int convert_datetimestruct_to_datetime64 "NpyDatetime_ConvertDatetimeStructToDatetime64"( + PyArray_DatetimeMetaData *meta, const npy_datetimestruct *dts, + npy_datetime *out) except -1 + + +# +# ufunc API +# + +cdef extern from "numpy/ufuncobject.h": + + ctypedef void (*PyUFuncGenericFunction) (char **, npy_intp *, npy_intp *, void *) + + ctypedef class numpy.ufunc [object PyUFuncObject, check_size ignore]: + cdef: + int nin, nout, nargs + int identity + PyUFuncGenericFunction *functions + void **data + int ntypes + int check_return + char *name + char *types + char *doc + void *ptr + PyObject *obj + PyObject *userloops + + cdef enum: + PyUFunc_Zero + PyUFunc_One + PyUFunc_None + # deprecated + UFUNC_FPE_DIVIDEBYZERO + UFUNC_FPE_OVERFLOW + UFUNC_FPE_UNDERFLOW + UFUNC_FPE_INVALID + # use these instead + NPY_FPE_DIVIDEBYZERO + NPY_FPE_OVERFLOW + NPY_FPE_UNDERFLOW + NPY_FPE_INVALID + + + object PyUFunc_FromFuncAndData(PyUFuncGenericFunction *, + void **, char *, int, int, int, int, char *, char *, int) + int PyUFunc_RegisterLoopForType(ufunc, int, + PyUFuncGenericFunction, int *, void *) except -1 + void PyUFunc_f_f_As_d_d \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_d_d \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_f_f \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_g_g \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_F_F_As_D_D \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_F_F \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_D_D \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_G_G \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_O_O \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_ff_f_As_dd_d \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_ff_f \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_dd_d \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_gg_g \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_FF_F_As_DD_D \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_DD_D \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_FF_F \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_GG_G \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_OO_O \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_O_O_method \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_OO_O_method \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_On_Om \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_clearfperr() + int PyUFunc_getfperr() + int PyUFunc_ReplaceLoopBySignature \ + (ufunc, PyUFuncGenericFunction, int *, PyUFuncGenericFunction *) + object PyUFunc_FromFuncAndDataAndSignature \ + (PyUFuncGenericFunction *, void **, char *, int, int, int, + int, char *, char *, int, char *) + + int _import_umath() except -1 + +cdef inline void set_array_base(ndarray arr, object base) except *: + Py_INCREF(base) # important to do this before stealing the reference below! + PyArray_SetBaseObject(arr, base) + +cdef inline object get_array_base(ndarray arr): + base = PyArray_BASE(arr) + if base is NULL: + return None + return base + +# Versions of the import_* functions which are more suitable for +# Cython code. +cdef inline int import_array() except -1: + try: + __pyx_import_array() + except Exception: + raise ImportError("numpy._core.multiarray failed to import") + +cdef inline int import_umath() except -1: + try: + _import_umath() + except Exception: + raise ImportError("numpy._core.umath failed to import") + +cdef inline int import_ufunc() except -1: + try: + _import_umath() + except Exception: + raise ImportError("numpy._core.umath failed to import") + + +cdef inline bint is_timedelta64_object(object obj) noexcept: + """ + Cython equivalent of `isinstance(obj, np.timedelta64)` + + Parameters + ---------- + obj : object + + Returns + ------- + bool + """ + return PyObject_TypeCheck(obj, &PyTimedeltaArrType_Type) + + +cdef inline bint is_datetime64_object(object obj) noexcept: + """ + Cython equivalent of `isinstance(obj, np.datetime64)` + + Parameters + ---------- + obj : object + + Returns + ------- + bool + """ + return PyObject_TypeCheck(obj, &PyDatetimeArrType_Type) + + +cdef inline npy_datetime get_datetime64_value(object obj) noexcept nogil: + """ + returns the int64 value underlying scalar numpy datetime64 object + + Note that to interpret this as a datetime, the corresponding unit is + also needed. That can be found using `get_datetime64_unit`. + """ + return (obj).obval + + +cdef inline npy_timedelta get_timedelta64_value(object obj) noexcept nogil: + """ + returns the int64 value underlying scalar numpy timedelta64 object + """ + return (obj).obval + + +cdef inline NPY_DATETIMEUNIT get_datetime64_unit(object obj) noexcept nogil: + """ + returns the unit part of the dtype for a numpy datetime64 object. + """ + return (obj).obmeta.base + + +cdef extern from "numpy/arrayobject.h": + + ctypedef struct NpyIter: + pass + + cdef enum: + NPY_FAIL + NPY_SUCCEED + + cdef enum: + # Track an index representing C order + NPY_ITER_C_INDEX + # Track an index representing Fortran order + NPY_ITER_F_INDEX + # Track a multi-index + NPY_ITER_MULTI_INDEX + # User code external to the iterator does the 1-dimensional innermost loop + NPY_ITER_EXTERNAL_LOOP + # Convert all the operands to a common data type + NPY_ITER_COMMON_DTYPE + # Operands may hold references, requiring API access during iteration + NPY_ITER_REFS_OK + # Zero-sized operands should be permitted, iteration checks IterSize for 0 + NPY_ITER_ZEROSIZE_OK + # Permits reductions (size-0 stride with dimension size > 1) + NPY_ITER_REDUCE_OK + # Enables sub-range iteration + NPY_ITER_RANGED + # Enables buffering + NPY_ITER_BUFFERED + # When buffering is enabled, grows the inner loop if possible + NPY_ITER_GROWINNER + # Delay allocation of buffers until first Reset* call + NPY_ITER_DELAY_BUFALLOC + # When NPY_KEEPORDER is specified, disable reversing negative-stride axes + NPY_ITER_DONT_NEGATE_STRIDES + NPY_ITER_COPY_IF_OVERLAP + # The operand will be read from and written to + NPY_ITER_READWRITE + # The operand will only be read from + NPY_ITER_READONLY + # The operand will only be written to + NPY_ITER_WRITEONLY + # The operand's data must be in native byte order + NPY_ITER_NBO + # The operand's data must be aligned + NPY_ITER_ALIGNED + # The operand's data must be contiguous (within the inner loop) + NPY_ITER_CONTIG + # The operand may be copied to satisfy requirements + NPY_ITER_COPY + # The operand may be copied with WRITEBACKIFCOPY to satisfy requirements + NPY_ITER_UPDATEIFCOPY + # Allocate the operand if it is NULL + NPY_ITER_ALLOCATE + # If an operand is allocated, don't use any subtype + NPY_ITER_NO_SUBTYPE + # This is a virtual array slot, operand is NULL but temporary data is there + NPY_ITER_VIRTUAL + # Require that the dimension match the iterator dimensions exactly + NPY_ITER_NO_BROADCAST + # A mask is being used on this array, affects buffer -> array copy + NPY_ITER_WRITEMASKED + # This array is the mask for all WRITEMASKED operands + NPY_ITER_ARRAYMASK + # Assume iterator order data access for COPY_IF_OVERLAP + NPY_ITER_OVERLAP_ASSUME_ELEMENTWISE + + # construction and destruction functions + NpyIter* NpyIter_New(ndarray arr, npy_uint32 flags, NPY_ORDER order, + NPY_CASTING casting, dtype datatype) except NULL + NpyIter* NpyIter_MultiNew(npy_intp nop, PyArrayObject** op, npy_uint32 flags, + NPY_ORDER order, NPY_CASTING casting, npy_uint32* + op_flags, PyArray_Descr** op_dtypes) except NULL + NpyIter* NpyIter_AdvancedNew(npy_intp nop, PyArrayObject** op, + npy_uint32 flags, NPY_ORDER order, + NPY_CASTING casting, npy_uint32* op_flags, + PyArray_Descr** op_dtypes, int oa_ndim, + int** op_axes, const npy_intp* itershape, + npy_intp buffersize) except NULL + NpyIter* NpyIter_Copy(NpyIter* it) except NULL + int NpyIter_RemoveAxis(NpyIter* it, int axis) except NPY_FAIL + int NpyIter_RemoveMultiIndex(NpyIter* it) except NPY_FAIL + int NpyIter_EnableExternalLoop(NpyIter* it) except NPY_FAIL + int NpyIter_Deallocate(NpyIter* it) except NPY_FAIL + int NpyIter_Reset(NpyIter* it, char** errmsg) except NPY_FAIL + int NpyIter_ResetToIterIndexRange(NpyIter* it, npy_intp istart, + npy_intp iend, char** errmsg) except NPY_FAIL + int NpyIter_ResetBasePointers(NpyIter* it, char** baseptrs, char** errmsg) except NPY_FAIL + int NpyIter_GotoMultiIndex(NpyIter* it, const npy_intp* multi_index) except NPY_FAIL + int NpyIter_GotoIndex(NpyIter* it, npy_intp index) except NPY_FAIL + npy_intp NpyIter_GetIterSize(NpyIter* it) nogil + npy_intp NpyIter_GetIterIndex(NpyIter* it) nogil + void NpyIter_GetIterIndexRange(NpyIter* it, npy_intp* istart, + npy_intp* iend) nogil + int NpyIter_GotoIterIndex(NpyIter* it, npy_intp iterindex) except NPY_FAIL + npy_bool NpyIter_HasDelayedBufAlloc(NpyIter* it) nogil + npy_bool NpyIter_HasExternalLoop(NpyIter* it) nogil + npy_bool NpyIter_HasMultiIndex(NpyIter* it) nogil + npy_bool NpyIter_HasIndex(NpyIter* it) nogil + npy_bool NpyIter_RequiresBuffering(NpyIter* it) nogil + npy_bool NpyIter_IsBuffered(NpyIter* it) nogil + npy_bool NpyIter_IsGrowInner(NpyIter* it) nogil + npy_intp NpyIter_GetBufferSize(NpyIter* it) nogil + int NpyIter_GetNDim(NpyIter* it) nogil + int NpyIter_GetNOp(NpyIter* it) nogil + npy_intp* NpyIter_GetAxisStrideArray(NpyIter* it, int axis) except NULL + int NpyIter_GetShape(NpyIter* it, npy_intp* outshape) nogil + PyArray_Descr** NpyIter_GetDescrArray(NpyIter* it) + PyArrayObject** NpyIter_GetOperandArray(NpyIter* it) + ndarray NpyIter_GetIterView(NpyIter* it, npy_intp i) + void NpyIter_GetReadFlags(NpyIter* it, char* outreadflags) + void NpyIter_GetWriteFlags(NpyIter* it, char* outwriteflags) + int NpyIter_CreateCompatibleStrides(NpyIter* it, npy_intp itemsize, + npy_intp* outstrides) except NPY_FAIL + npy_bool NpyIter_IsFirstVisit(NpyIter* it, int iop) nogil + # functions for iterating an NpyIter object + # + # These don't match the definition in the C API because Cython can't wrap + # function pointers that return functions. + NpyIter_IterNextFunc NpyIter_GetIterNext(NpyIter* it, char** errmsg) except NULL + NpyIter_GetMultiIndexFunc NpyIter_GetGetMultiIndex(NpyIter* it, + char** errmsg) except NULL + char** NpyIter_GetDataPtrArray(NpyIter* it) nogil + char** NpyIter_GetInitialDataPtrArray(NpyIter* it) nogil + npy_intp* NpyIter_GetIndexPtr(NpyIter* it) + npy_intp* NpyIter_GetInnerStrideArray(NpyIter* it) nogil + npy_intp* NpyIter_GetInnerLoopSizePtr(NpyIter* it) nogil + void NpyIter_GetInnerFixedStrideArray(NpyIter* it, npy_intp* outstrides) nogil + npy_bool NpyIter_IterationNeedsAPI(NpyIter* it) nogil + void NpyIter_DebugPrint(NpyIter* it) + +# NpyString API +cdef extern from "numpy/ndarraytypes.h": + ctypedef struct npy_string_allocator: + pass + + ctypedef struct npy_packed_static_string: + pass + + ctypedef struct npy_static_string: + size_t size + const char *buf + + ctypedef struct PyArray_StringDTypeObject: + PyArray_Descr base + PyObject *na_object + char coerce + char has_nan_na + char has_string_na + char array_owned + npy_static_string default_string + npy_static_string na_name + npy_string_allocator *allocator + +cdef extern from "numpy/arrayobject.h": + npy_string_allocator *NpyString_acquire_allocator(const PyArray_StringDTypeObject *descr) + void NpyString_acquire_allocators(size_t n_descriptors, PyArray_Descr *const descrs[], npy_string_allocator *allocators[]) + void NpyString_release_allocator(npy_string_allocator *allocator) + void NpyString_release_allocators(size_t length, npy_string_allocator *allocators[]) + int NpyString_load(npy_string_allocator *allocator, const npy_packed_static_string *packed_string, npy_static_string *unpacked_string) + int NpyString_pack_null(npy_string_allocator *allocator, npy_packed_static_string *packed_string) + int NpyString_pack(npy_string_allocator *allocator, npy_packed_static_string *packed_string, const char *buf, size_t size) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/numpy/__init__.pxd b/TTS/Kokoro/.venv/Lib/site-packages/numpy/__init__.pxd new file mode 100644 index 0000000000000000000000000000000000000000..24d4637adb8082953a3e9139068a2cc6ea12cf53 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/numpy/__init__.pxd @@ -0,0 +1,1155 @@ +# NumPy static imports for Cython < 3.0 +# +# If any of the PyArray_* functions are called, import_array must be +# called first. +# +# Author: Dag Sverre Seljebotn +# + +DEF _buffer_format_string_len = 255 + +cimport cpython.buffer as pybuf +from cpython.ref cimport Py_INCREF +from cpython.mem cimport PyObject_Malloc, PyObject_Free +from cpython.object cimport PyObject, PyTypeObject +from cpython.buffer cimport PyObject_GetBuffer +from cpython.type cimport type +cimport libc.stdio as stdio + + +cdef extern from *: + # Leave a marker that the NumPy declarations came from NumPy itself and not from Cython. + # See https://github.com/cython/cython/issues/3573 + """ + /* Using NumPy API declarations from "numpy/__init__.pxd" */ + """ + + +cdef extern from "Python.h": + ctypedef int Py_intptr_t + bint PyObject_TypeCheck(object obj, PyTypeObject* type) + +cdef extern from "numpy/arrayobject.h": + # It would be nice to use size_t and ssize_t, but ssize_t has special + # implicit conversion rules, so just use "long". + # Note: The actual type only matters for Cython promotion, so long + # is closer than int, but could lead to incorrect promotion. + # (Not to worrying, and always the status-quo.) + ctypedef signed long npy_intp + ctypedef unsigned long npy_uintp + + ctypedef unsigned char npy_bool + + ctypedef signed char npy_byte + ctypedef signed short npy_short + ctypedef signed int npy_int + ctypedef signed long npy_long + ctypedef signed long long npy_longlong + + ctypedef unsigned char npy_ubyte + ctypedef unsigned short npy_ushort + ctypedef unsigned int npy_uint + ctypedef unsigned long npy_ulong + ctypedef unsigned long long npy_ulonglong + + ctypedef float npy_float + ctypedef double npy_double + ctypedef long double npy_longdouble + + ctypedef signed char npy_int8 + ctypedef signed short npy_int16 + ctypedef signed int npy_int32 + ctypedef signed long long npy_int64 + + ctypedef unsigned char npy_uint8 + ctypedef unsigned short npy_uint16 + ctypedef unsigned int npy_uint32 + ctypedef unsigned long long npy_uint64 + + ctypedef float npy_float32 + ctypedef double npy_float64 + ctypedef long double npy_float80 + ctypedef long double npy_float96 + ctypedef long double npy_float128 + + ctypedef struct npy_cfloat: + pass + + ctypedef struct npy_cdouble: + pass + + ctypedef struct npy_clongdouble: + pass + + ctypedef struct npy_complex64: + pass + + ctypedef struct npy_complex128: + pass + + ctypedef struct npy_complex160: + pass + + ctypedef struct npy_complex192: + pass + + ctypedef struct npy_complex256: + pass + + ctypedef struct PyArray_Dims: + npy_intp *ptr + int len + + + cdef enum NPY_TYPES: + NPY_BOOL + NPY_BYTE + NPY_UBYTE + NPY_SHORT + NPY_USHORT + NPY_INT + NPY_UINT + NPY_LONG + NPY_ULONG + NPY_LONGLONG + NPY_ULONGLONG + NPY_FLOAT + NPY_DOUBLE + NPY_LONGDOUBLE + NPY_CFLOAT + NPY_CDOUBLE + NPY_CLONGDOUBLE + NPY_OBJECT + NPY_STRING + NPY_UNICODE + NPY_VSTRING + NPY_VOID + NPY_DATETIME + NPY_TIMEDELTA + NPY_NTYPES_LEGACY + NPY_NOTYPE + + NPY_INT8 + NPY_INT16 + NPY_INT32 + NPY_INT64 + NPY_UINT8 + NPY_UINT16 + NPY_UINT32 + NPY_UINT64 + NPY_FLOAT16 + NPY_FLOAT32 + NPY_FLOAT64 + NPY_FLOAT80 + NPY_FLOAT96 + NPY_FLOAT128 + NPY_COMPLEX64 + NPY_COMPLEX128 + NPY_COMPLEX160 + NPY_COMPLEX192 + NPY_COMPLEX256 + + NPY_INTP + NPY_UINTP + NPY_DEFAULT_INT # Not a compile time constant (normally)! + + ctypedef enum NPY_ORDER: + NPY_ANYORDER + NPY_CORDER + NPY_FORTRANORDER + NPY_KEEPORDER + + ctypedef enum NPY_CASTING: + NPY_NO_CASTING + NPY_EQUIV_CASTING + NPY_SAFE_CASTING + NPY_SAME_KIND_CASTING + NPY_UNSAFE_CASTING + NPY_SAME_VALUE_CASTING + + ctypedef enum NPY_CLIPMODE: + NPY_CLIP + NPY_WRAP + NPY_RAISE + + ctypedef enum NPY_SCALARKIND: + NPY_NOSCALAR, + NPY_BOOL_SCALAR, + NPY_INTPOS_SCALAR, + NPY_INTNEG_SCALAR, + NPY_FLOAT_SCALAR, + NPY_COMPLEX_SCALAR, + NPY_OBJECT_SCALAR + + ctypedef enum NPY_SORTKIND: + NPY_QUICKSORT + NPY_HEAPSORT + NPY_MERGESORT + + ctypedef enum NPY_SEARCHSIDE: + NPY_SEARCHLEFT + NPY_SEARCHRIGHT + + enum: + NPY_ARRAY_C_CONTIGUOUS + NPY_ARRAY_F_CONTIGUOUS + NPY_ARRAY_OWNDATA + NPY_ARRAY_FORCECAST + NPY_ARRAY_ENSURECOPY + NPY_ARRAY_ENSUREARRAY + NPY_ARRAY_ELEMENTSTRIDES + NPY_ARRAY_ALIGNED + NPY_ARRAY_NOTSWAPPED + NPY_ARRAY_WRITEABLE + NPY_ARRAY_WRITEBACKIFCOPY + + NPY_ARRAY_BEHAVED + NPY_ARRAY_BEHAVED_NS + NPY_ARRAY_CARRAY + NPY_ARRAY_CARRAY_RO + NPY_ARRAY_FARRAY + NPY_ARRAY_FARRAY_RO + NPY_ARRAY_DEFAULT + + NPY_ARRAY_IN_ARRAY + NPY_ARRAY_OUT_ARRAY + NPY_ARRAY_INOUT_ARRAY + NPY_ARRAY_IN_FARRAY + NPY_ARRAY_OUT_FARRAY + NPY_ARRAY_INOUT_FARRAY + + NPY_ARRAY_UPDATE_ALL + + cdef enum: + NPY_MAXDIMS # 64 on NumPy 2.x and 32 on NumPy 1.x + NPY_RAVEL_AXIS # Used for functions like PyArray_Mean + + ctypedef void (*PyArray_VectorUnaryFunc)(void *, void *, npy_intp, void *, void *) + + ctypedef struct PyArray_ArrayDescr: + # shape is a tuple, but Cython doesn't support "tuple shape" + # inside a non-PyObject declaration, so we have to declare it + # as just a PyObject*. + PyObject* shape + + ctypedef struct PyArray_Descr: + pass + + ctypedef class numpy.dtype [object PyArray_Descr, check_size ignore]: + # Use PyDataType_* macros when possible, however there are no macros + # for accessing some of the fields, so some are defined. + cdef PyTypeObject* typeobj + cdef char kind + cdef char type + # Numpy sometimes mutates this without warning (e.g. it'll + # sometimes change "|" to "<" in shared dtype objects on + # little-endian machines). If this matters to you, use + # PyArray_IsNativeByteOrder(dtype.byteorder) instead of + # directly accessing this field. + cdef char byteorder + # Flags are not directly accessible on Cython <3. Use PyDataType_FLAGS. + # cdef char flags + cdef int type_num + # itemsize/elsize, alignment, fields, names, and subarray must + # use the `PyDataType_*` accessor macros. With Cython 3 you can + # still use getter attributes `dtype.itemsize` + + ctypedef class numpy.flatiter [object PyArrayIterObject, check_size ignore]: + # Use through macros + pass + + ctypedef class numpy.broadcast [object PyArrayMultiIterObject, check_size ignore]: + cdef int numiter + cdef npy_intp size, index + cdef int nd + cdef npy_intp *dimensions + cdef void **iters + + ctypedef struct PyArrayObject: + # For use in situations where ndarray can't replace PyArrayObject*, + # like PyArrayObject**. + pass + + ctypedef class numpy.ndarray [object PyArrayObject, check_size ignore]: + cdef __cythonbufferdefaults__ = {"mode": "strided"} + + cdef: + # Only taking a few of the most commonly used and stable fields. + # One should use PyArray_* macros instead to access the C fields. + char *data + int ndim "nd" + npy_intp *shape "dimensions" + npy_intp *strides + dtype descr # deprecated since NumPy 1.7 ! + PyObject* base # NOT PUBLIC, DO NOT USE ! + + + int _import_array() except -1 + # A second definition so _import_array isn't marked as used when we use it here. + # Do not use - subject to change any time. + int __pyx_import_array "_import_array"() except -1 + + # + # Macros from ndarrayobject.h + # + bint PyArray_CHKFLAGS(ndarray m, int flags) nogil + bint PyArray_IS_C_CONTIGUOUS(ndarray arr) nogil + bint PyArray_IS_F_CONTIGUOUS(ndarray arr) nogil + bint PyArray_ISCONTIGUOUS(ndarray m) nogil + bint PyArray_ISWRITEABLE(ndarray m) nogil + bint PyArray_ISALIGNED(ndarray m) nogil + + int PyArray_NDIM(ndarray) nogil + bint PyArray_ISONESEGMENT(ndarray) nogil + bint PyArray_ISFORTRAN(ndarray) nogil + int PyArray_FORTRANIF(ndarray) nogil + + void* PyArray_DATA(ndarray) nogil + char* PyArray_BYTES(ndarray) nogil + + npy_intp* PyArray_DIMS(ndarray) nogil + npy_intp* PyArray_STRIDES(ndarray) nogil + npy_intp PyArray_DIM(ndarray, size_t) nogil + npy_intp PyArray_STRIDE(ndarray, size_t) nogil + + PyObject *PyArray_BASE(ndarray) nogil # returns borrowed reference! + PyArray_Descr *PyArray_DESCR(ndarray) nogil # returns borrowed reference to dtype! + PyArray_Descr *PyArray_DTYPE(ndarray) nogil # returns borrowed reference to dtype! NP 1.7+ alias for descr. + int PyArray_FLAGS(ndarray) nogil + void PyArray_CLEARFLAGS(ndarray, int flags) nogil # Added in NumPy 1.7 + void PyArray_ENABLEFLAGS(ndarray, int flags) nogil # Added in NumPy 1.7 + npy_intp PyArray_ITEMSIZE(ndarray) nogil + int PyArray_TYPE(ndarray arr) nogil + + object PyArray_GETITEM(ndarray arr, void *itemptr) + int PyArray_SETITEM(ndarray arr, void *itemptr, object obj) except -1 + + bint PyTypeNum_ISBOOL(int) nogil + bint PyTypeNum_ISUNSIGNED(int) nogil + bint PyTypeNum_ISSIGNED(int) nogil + bint PyTypeNum_ISINTEGER(int) nogil + bint PyTypeNum_ISFLOAT(int) nogil + bint PyTypeNum_ISNUMBER(int) nogil + bint PyTypeNum_ISSTRING(int) nogil + bint PyTypeNum_ISCOMPLEX(int) nogil + bint PyTypeNum_ISFLEXIBLE(int) nogil + bint PyTypeNum_ISUSERDEF(int) nogil + bint PyTypeNum_ISEXTENDED(int) nogil + bint PyTypeNum_ISOBJECT(int) nogil + + npy_intp PyDataType_ELSIZE(dtype) nogil + npy_intp PyDataType_ALIGNMENT(dtype) nogil + PyObject* PyDataType_METADATA(dtype) nogil + PyArray_ArrayDescr* PyDataType_SUBARRAY(dtype) nogil + PyObject* PyDataType_NAMES(dtype) nogil + PyObject* PyDataType_FIELDS(dtype) nogil + + bint PyDataType_ISBOOL(dtype) nogil + bint PyDataType_ISUNSIGNED(dtype) nogil + bint PyDataType_ISSIGNED(dtype) nogil + bint PyDataType_ISINTEGER(dtype) nogil + bint PyDataType_ISFLOAT(dtype) nogil + bint PyDataType_ISNUMBER(dtype) nogil + bint PyDataType_ISSTRING(dtype) nogil + bint PyDataType_ISCOMPLEX(dtype) nogil + bint PyDataType_ISFLEXIBLE(dtype) nogil + bint PyDataType_ISUSERDEF(dtype) nogil + bint PyDataType_ISEXTENDED(dtype) nogil + bint PyDataType_ISOBJECT(dtype) nogil + bint PyDataType_HASFIELDS(dtype) nogil + bint PyDataType_HASSUBARRAY(dtype) nogil + npy_uint64 PyDataType_FLAGS(dtype) nogil + + bint PyArray_ISBOOL(ndarray) nogil + bint PyArray_ISUNSIGNED(ndarray) nogil + bint PyArray_ISSIGNED(ndarray) nogil + bint PyArray_ISINTEGER(ndarray) nogil + bint PyArray_ISFLOAT(ndarray) nogil + bint PyArray_ISNUMBER(ndarray) nogil + bint PyArray_ISSTRING(ndarray) nogil + bint PyArray_ISCOMPLEX(ndarray) nogil + bint PyArray_ISFLEXIBLE(ndarray) nogil + bint PyArray_ISUSERDEF(ndarray) nogil + bint PyArray_ISEXTENDED(ndarray) nogil + bint PyArray_ISOBJECT(ndarray) nogil + bint PyArray_HASFIELDS(ndarray) nogil + + bint PyArray_ISVARIABLE(ndarray) nogil + + bint PyArray_SAFEALIGNEDCOPY(ndarray) nogil + bint PyArray_ISNBO(char) nogil # works on ndarray.byteorder + bint PyArray_IsNativeByteOrder(char) nogil # works on ndarray.byteorder + bint PyArray_ISNOTSWAPPED(ndarray) nogil + bint PyArray_ISBYTESWAPPED(ndarray) nogil + + bint PyArray_FLAGSWAP(ndarray, int) nogil + + bint PyArray_ISCARRAY(ndarray) nogil + bint PyArray_ISCARRAY_RO(ndarray) nogil + bint PyArray_ISFARRAY(ndarray) nogil + bint PyArray_ISFARRAY_RO(ndarray) nogil + bint PyArray_ISBEHAVED(ndarray) nogil + bint PyArray_ISBEHAVED_RO(ndarray) nogil + + + bint PyDataType_ISNOTSWAPPED(dtype) nogil + bint PyDataType_ISBYTESWAPPED(dtype) nogil + + bint PyArray_DescrCheck(object) + + bint PyArray_Check(object) + bint PyArray_CheckExact(object) + + # Cannot be supported due to out arg: + # bint PyArray_HasArrayInterfaceType(object, dtype, object, object&) + # bint PyArray_HasArrayInterface(op, out) + + + bint PyArray_IsZeroDim(object) + # Cannot be supported due to ## ## in macro: + # bint PyArray_IsScalar(object, verbatim work) + bint PyArray_CheckScalar(object) + bint PyArray_IsPythonNumber(object) + bint PyArray_IsPythonScalar(object) + bint PyArray_IsAnyScalar(object) + bint PyArray_CheckAnyScalar(object) + + ndarray PyArray_GETCONTIGUOUS(ndarray) + bint PyArray_SAMESHAPE(ndarray, ndarray) nogil + npy_intp PyArray_SIZE(ndarray) nogil + npy_intp PyArray_NBYTES(ndarray) nogil + + object PyArray_FROM_O(object) + object PyArray_FROM_OF(object m, int flags) + object PyArray_FROM_OT(object m, int type) + object PyArray_FROM_OTF(object m, int type, int flags) + object PyArray_FROMANY(object m, int type, int min, int max, int flags) + object PyArray_ZEROS(int nd, npy_intp* dims, int type, int fortran) + object PyArray_EMPTY(int nd, npy_intp* dims, int type, int fortran) + void PyArray_FILLWBYTE(ndarray, int val) + object PyArray_ContiguousFromAny(op, int, int min_depth, int max_depth) + unsigned char PyArray_EquivArrTypes(ndarray a1, ndarray a2) + bint PyArray_EquivByteorders(int b1, int b2) nogil + object PyArray_SimpleNew(int nd, npy_intp* dims, int typenum) + object PyArray_SimpleNewFromData(int nd, npy_intp* dims, int typenum, void* data) + #object PyArray_SimpleNewFromDescr(int nd, npy_intp* dims, dtype descr) + object PyArray_ToScalar(void* data, ndarray arr) + + void* PyArray_GETPTR1(ndarray m, npy_intp i) nogil + void* PyArray_GETPTR2(ndarray m, npy_intp i, npy_intp j) nogil + void* PyArray_GETPTR3(ndarray m, npy_intp i, npy_intp j, npy_intp k) nogil + void* PyArray_GETPTR4(ndarray m, npy_intp i, npy_intp j, npy_intp k, npy_intp l) nogil + + # Cannot be supported due to out arg + # void PyArray_DESCR_REPLACE(descr) + + + object PyArray_Copy(ndarray) + object PyArray_FromObject(object op, int type, int min_depth, int max_depth) + object PyArray_ContiguousFromObject(object op, int type, int min_depth, int max_depth) + object PyArray_CopyFromObject(object op, int type, int min_depth, int max_depth) + + object PyArray_Cast(ndarray mp, int type_num) + object PyArray_Take(ndarray ap, object items, int axis) + object PyArray_Put(ndarray ap, object items, object values) + + void PyArray_ITER_RESET(flatiter it) nogil + void PyArray_ITER_NEXT(flatiter it) nogil + void PyArray_ITER_GOTO(flatiter it, npy_intp* destination) nogil + void PyArray_ITER_GOTO1D(flatiter it, npy_intp ind) nogil + void* PyArray_ITER_DATA(flatiter it) nogil + bint PyArray_ITER_NOTDONE(flatiter it) nogil + + void PyArray_MultiIter_RESET(broadcast multi) nogil + void PyArray_MultiIter_NEXT(broadcast multi) nogil + void PyArray_MultiIter_GOTO(broadcast multi, npy_intp dest) nogil + void PyArray_MultiIter_GOTO1D(broadcast multi, npy_intp ind) nogil + void* PyArray_MultiIter_DATA(broadcast multi, npy_intp i) nogil + void PyArray_MultiIter_NEXTi(broadcast multi, npy_intp i) nogil + bint PyArray_MultiIter_NOTDONE(broadcast multi) nogil + npy_intp PyArray_MultiIter_SIZE(broadcast multi) nogil + int PyArray_MultiIter_NDIM(broadcast multi) nogil + npy_intp PyArray_MultiIter_INDEX(broadcast multi) nogil + int PyArray_MultiIter_NUMITER(broadcast multi) nogil + npy_intp* PyArray_MultiIter_DIMS(broadcast multi) nogil + void** PyArray_MultiIter_ITERS(broadcast multi) nogil + + # Functions from __multiarray_api.h + + # Functions taking dtype and returning object/ndarray are disabled + # for now as they steal dtype references. I'm conservative and disable + # more than is probably needed until it can be checked further. + int PyArray_INCREF (ndarray) except * # uses PyArray_Item_INCREF... + int PyArray_XDECREF (ndarray) except * # uses PyArray_Item_DECREF... + dtype PyArray_DescrFromType (int) + object PyArray_TypeObjectFromType (int) + char * PyArray_Zero (ndarray) + char * PyArray_One (ndarray) + #object PyArray_CastToType (ndarray, dtype, int) + int PyArray_CanCastSafely (int, int) # writes errors + npy_bool PyArray_CanCastTo (dtype, dtype) # writes errors + int PyArray_ObjectType (object, int) except 0 + dtype PyArray_DescrFromObject (object, dtype) + #ndarray* PyArray_ConvertToCommonType (object, int *) + dtype PyArray_DescrFromScalar (object) + dtype PyArray_DescrFromTypeObject (object) + npy_intp PyArray_Size (object) + #object PyArray_Scalar (void *, dtype, object) + #object PyArray_FromScalar (object, dtype) + void PyArray_ScalarAsCtype (object, void *) + #int PyArray_CastScalarToCtype (object, void *, dtype) + #int PyArray_CastScalarDirect (object, dtype, void *, int) + #PyArray_VectorUnaryFunc * PyArray_GetCastFunc (dtype, int) + #object PyArray_FromAny (object, dtype, int, int, int, object) + object PyArray_EnsureArray (object) + object PyArray_EnsureAnyArray (object) + #object PyArray_FromFile (stdio.FILE *, dtype, npy_intp, char *) + #object PyArray_FromString (char *, npy_intp, dtype, npy_intp, char *) + #object PyArray_FromBuffer (object, dtype, npy_intp, npy_intp) + #object PyArray_FromIter (object, dtype, npy_intp) + object PyArray_Return (ndarray) + #object PyArray_GetField (ndarray, dtype, int) + #int PyArray_SetField (ndarray, dtype, int, object) except -1 + object PyArray_Byteswap (ndarray, npy_bool) + object PyArray_Resize (ndarray, PyArray_Dims *, int, NPY_ORDER) + int PyArray_CopyInto (ndarray, ndarray) except -1 + int PyArray_CopyAnyInto (ndarray, ndarray) except -1 + int PyArray_CopyObject (ndarray, object) except -1 + object PyArray_NewCopy (ndarray, NPY_ORDER) + object PyArray_ToList (ndarray) + object PyArray_ToString (ndarray, NPY_ORDER) + int PyArray_ToFile (ndarray, stdio.FILE *, char *, char *) except -1 + int PyArray_Dump (object, object, int) except -1 + object PyArray_Dumps (object, int) + int PyArray_ValidType (int) # Cannot error + void PyArray_UpdateFlags (ndarray, int) + object PyArray_New (type, int, npy_intp *, int, npy_intp *, void *, int, int, object) + #object PyArray_NewFromDescr (type, dtype, int, npy_intp *, npy_intp *, void *, int, object) + #dtype PyArray_DescrNew (dtype) + dtype PyArray_DescrNewFromType (int) + double PyArray_GetPriority (object, double) # clears errors as of 1.25 + object PyArray_IterNew (object) + object PyArray_MultiIterNew (int, ...) + + int PyArray_PyIntAsInt (object) except? -1 + npy_intp PyArray_PyIntAsIntp (object) + int PyArray_Broadcast (broadcast) except -1 + int PyArray_FillWithScalar (ndarray, object) except -1 + npy_bool PyArray_CheckStrides (int, int, npy_intp, npy_intp, npy_intp *, npy_intp *) + dtype PyArray_DescrNewByteorder (dtype, char) + object PyArray_IterAllButAxis (object, int *) + #object PyArray_CheckFromAny (object, dtype, int, int, int, object) + #object PyArray_FromArray (ndarray, dtype, int) + object PyArray_FromInterface (object) + object PyArray_FromStructInterface (object) + #object PyArray_FromArrayAttr (object, dtype, object) + #NPY_SCALARKIND PyArray_ScalarKind (int, ndarray*) + int PyArray_CanCoerceScalar (int, int, NPY_SCALARKIND) + npy_bool PyArray_CanCastScalar (type, type) + int PyArray_RemoveSmallest (broadcast) except -1 + int PyArray_ElementStrides (object) + void PyArray_Item_INCREF (char *, dtype) except * + void PyArray_Item_XDECREF (char *, dtype) except * + object PyArray_Transpose (ndarray, PyArray_Dims *) + object PyArray_TakeFrom (ndarray, object, int, ndarray, NPY_CLIPMODE) + object PyArray_PutTo (ndarray, object, object, NPY_CLIPMODE) + object PyArray_PutMask (ndarray, object, object) + object PyArray_Repeat (ndarray, object, int) + object PyArray_Choose (ndarray, object, ndarray, NPY_CLIPMODE) + int PyArray_Sort (ndarray, int, NPY_SORTKIND) except -1 + object PyArray_ArgSort (ndarray, int, NPY_SORTKIND) + object PyArray_SearchSorted (ndarray, object, NPY_SEARCHSIDE, PyObject *) + object PyArray_ArgMax (ndarray, int, ndarray) + object PyArray_ArgMin (ndarray, int, ndarray) + object PyArray_Reshape (ndarray, object) + object PyArray_Newshape (ndarray, PyArray_Dims *, NPY_ORDER) + object PyArray_Squeeze (ndarray) + #object PyArray_View (ndarray, dtype, type) + object PyArray_SwapAxes (ndarray, int, int) + object PyArray_Max (ndarray, int, ndarray) + object PyArray_Min (ndarray, int, ndarray) + object PyArray_Ptp (ndarray, int, ndarray) + object PyArray_Mean (ndarray, int, int, ndarray) + object PyArray_Trace (ndarray, int, int, int, int, ndarray) + object PyArray_Diagonal (ndarray, int, int, int) + object PyArray_Clip (ndarray, object, object, ndarray) + object PyArray_Conjugate (ndarray, ndarray) + object PyArray_Nonzero (ndarray) + object PyArray_Std (ndarray, int, int, ndarray, int) + object PyArray_Sum (ndarray, int, int, ndarray) + object PyArray_CumSum (ndarray, int, int, ndarray) + object PyArray_Prod (ndarray, int, int, ndarray) + object PyArray_CumProd (ndarray, int, int, ndarray) + object PyArray_All (ndarray, int, ndarray) + object PyArray_Any (ndarray, int, ndarray) + object PyArray_Compress (ndarray, object, int, ndarray) + object PyArray_Flatten (ndarray, NPY_ORDER) + object PyArray_Ravel (ndarray, NPY_ORDER) + npy_intp PyArray_MultiplyList (npy_intp *, int) + int PyArray_MultiplyIntList (int *, int) + void * PyArray_GetPtr (ndarray, npy_intp*) + int PyArray_CompareLists (npy_intp *, npy_intp *, int) + #int PyArray_AsCArray (object*, void *, npy_intp *, int, dtype) + int PyArray_Free (object, void *) + #int PyArray_Converter (object, object*) + int PyArray_IntpFromSequence (object, npy_intp *, int) except -1 + object PyArray_Concatenate (object, int) + object PyArray_InnerProduct (object, object) + object PyArray_MatrixProduct (object, object) + object PyArray_Correlate (object, object, int) + #int PyArray_DescrConverter (object, dtype*) except 0 + #int PyArray_DescrConverter2 (object, dtype*) except 0 + int PyArray_IntpConverter (object, PyArray_Dims *) except 0 + #int PyArray_BufferConverter (object, chunk) except 0 + int PyArray_AxisConverter (object, int *) except 0 + int PyArray_BoolConverter (object, npy_bool *) except 0 + int PyArray_ByteorderConverter (object, char *) except 0 + int PyArray_OrderConverter (object, NPY_ORDER *) except 0 + unsigned char PyArray_EquivTypes (dtype, dtype) # clears errors + #object PyArray_Zeros (int, npy_intp *, dtype, int) + #object PyArray_Empty (int, npy_intp *, dtype, int) + object PyArray_Where (object, object, object) + object PyArray_Arange (double, double, double, int) + #object PyArray_ArangeObj (object, object, object, dtype) + int PyArray_SortkindConverter (object, NPY_SORTKIND *) except 0 + object PyArray_LexSort (object, int) + object PyArray_Round (ndarray, int, ndarray) + unsigned char PyArray_EquivTypenums (int, int) + int PyArray_RegisterDataType (dtype) except -1 + int PyArray_RegisterCastFunc (dtype, int, PyArray_VectorUnaryFunc *) except -1 + int PyArray_RegisterCanCast (dtype, int, NPY_SCALARKIND) except -1 + #void PyArray_InitArrFuncs (PyArray_ArrFuncs *) + object PyArray_IntTupleFromIntp (int, npy_intp *) + int PyArray_ClipmodeConverter (object, NPY_CLIPMODE *) except 0 + #int PyArray_OutputConverter (object, ndarray*) except 0 + object PyArray_BroadcastToShape (object, npy_intp *, int) + #int PyArray_DescrAlignConverter (object, dtype*) except 0 + #int PyArray_DescrAlignConverter2 (object, dtype*) except 0 + int PyArray_SearchsideConverter (object, void *) except 0 + object PyArray_CheckAxis (ndarray, int *, int) + npy_intp PyArray_OverflowMultiplyList (npy_intp *, int) + int PyArray_SetBaseObject(ndarray, base) except -1 # NOTE: steals a reference to base! Use "set_array_base()" instead. + + # The memory handler functions require the NumPy 1.22 API + # and may require defining NPY_TARGET_VERSION + ctypedef struct PyDataMemAllocator: + void *ctx + void* (*malloc) (void *ctx, size_t size) + void* (*calloc) (void *ctx, size_t nelem, size_t elsize) + void* (*realloc) (void *ctx, void *ptr, size_t new_size) + void (*free) (void *ctx, void *ptr, size_t size) + + ctypedef struct PyDataMem_Handler: + char* name + npy_uint8 version + PyDataMemAllocator allocator + + object PyDataMem_SetHandler(object handler) + object PyDataMem_GetHandler() + + # additional datetime related functions are defined below + + +# Typedefs that matches the runtime dtype objects in +# the numpy module. + +# The ones that are commented out needs an IFDEF function +# in Cython to enable them only on the right systems. + +ctypedef npy_int8 int8_t +ctypedef npy_int16 int16_t +ctypedef npy_int32 int32_t +ctypedef npy_int64 int64_t + +ctypedef npy_uint8 uint8_t +ctypedef npy_uint16 uint16_t +ctypedef npy_uint32 uint32_t +ctypedef npy_uint64 uint64_t + +ctypedef npy_float32 float32_t +ctypedef npy_float64 float64_t +#ctypedef npy_float80 float80_t +#ctypedef npy_float128 float128_t + +ctypedef float complex complex64_t +ctypedef double complex complex128_t + +ctypedef npy_longlong longlong_t +ctypedef npy_ulonglong ulonglong_t + +ctypedef npy_intp intp_t +ctypedef npy_uintp uintp_t + +ctypedef npy_double float_t +ctypedef npy_double double_t +ctypedef npy_longdouble longdouble_t + +ctypedef float complex cfloat_t +ctypedef double complex cdouble_t +ctypedef double complex complex_t +ctypedef long double complex clongdouble_t + +cdef inline object PyArray_MultiIterNew1(a): + return PyArray_MultiIterNew(1, a) + +cdef inline object PyArray_MultiIterNew2(a, b): + return PyArray_MultiIterNew(2, a, b) + +cdef inline object PyArray_MultiIterNew3(a, b, c): + return PyArray_MultiIterNew(3, a, b, c) + +cdef inline object PyArray_MultiIterNew4(a, b, c, d): + return PyArray_MultiIterNew(4, a, b, c, d) + +cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): + return PyArray_MultiIterNew(5, a, b, c, d, e) + +cdef inline tuple PyDataType_SHAPE(dtype d): + if PyDataType_HASSUBARRAY(d): + return d.subarray.shape + else: + return () + + +cdef extern from "numpy/ndarrayobject.h": + PyTypeObject PyTimedeltaArrType_Type + PyTypeObject PyDatetimeArrType_Type + ctypedef int64_t npy_timedelta + ctypedef int64_t npy_datetime + +cdef extern from "numpy/ndarraytypes.h": + ctypedef struct PyArray_DatetimeMetaData: + NPY_DATETIMEUNIT base + int64_t num + + ctypedef struct npy_datetimestruct: + int64_t year + int32_t month, day, hour, min, sec, us, ps, as + + # Iterator API added in v1.6 + # + # These don't match the definition in the C API because Cython can't wrap + # function pointers that return functions. + # https://github.com/cython/cython/issues/6720 + ctypedef int (*NpyIter_IterNextFunc "NpyIter_IterNextFunc *")(NpyIter* it) noexcept nogil + ctypedef void (*NpyIter_GetMultiIndexFunc "NpyIter_GetMultiIndexFunc *")(NpyIter* it, npy_intp* outcoords) noexcept nogil + +cdef extern from "numpy/arrayscalars.h": + + # abstract types + ctypedef class numpy.generic [object PyObject]: + pass + ctypedef class numpy.number [object PyObject]: + pass + ctypedef class numpy.integer [object PyObject]: + pass + ctypedef class numpy.signedinteger [object PyObject]: + pass + ctypedef class numpy.unsignedinteger [object PyObject]: + pass + ctypedef class numpy.inexact [object PyObject]: + pass + ctypedef class numpy.floating [object PyObject]: + pass + ctypedef class numpy.complexfloating [object PyObject]: + pass + ctypedef class numpy.flexible [object PyObject]: + pass + ctypedef class numpy.character [object PyObject]: + pass + + ctypedef struct PyDatetimeScalarObject: + # PyObject_HEAD + npy_datetime obval + PyArray_DatetimeMetaData obmeta + + ctypedef struct PyTimedeltaScalarObject: + # PyObject_HEAD + npy_timedelta obval + PyArray_DatetimeMetaData obmeta + + ctypedef enum NPY_DATETIMEUNIT: + NPY_FR_Y + NPY_FR_M + NPY_FR_W + NPY_FR_D + NPY_FR_B + NPY_FR_h + NPY_FR_m + NPY_FR_s + NPY_FR_ms + NPY_FR_us + NPY_FR_ns + NPY_FR_ps + NPY_FR_fs + NPY_FR_as + NPY_FR_GENERIC + + +cdef extern from "numpy/arrayobject.h": + # These are part of the C-API defined in `__multiarray_api.h` + + # NumPy internal definitions in datetime_strings.c: + int get_datetime_iso_8601_strlen "NpyDatetime_GetDatetimeISO8601StrLen" ( + int local, NPY_DATETIMEUNIT base) + int make_iso_8601_datetime "NpyDatetime_MakeISO8601Datetime" ( + npy_datetimestruct *dts, char *outstr, npy_intp outlen, + int local, int utc, NPY_DATETIMEUNIT base, int tzoffset, + NPY_CASTING casting) except -1 + + # NumPy internal definition in datetime.c: + # May return 1 to indicate that object does not appear to be a datetime + # (returns 0 on success). + int convert_pydatetime_to_datetimestruct "NpyDatetime_ConvertPyDateTimeToDatetimeStruct" ( + PyObject *obj, npy_datetimestruct *out, + NPY_DATETIMEUNIT *out_bestunit, int apply_tzinfo) except -1 + int convert_datetime64_to_datetimestruct "NpyDatetime_ConvertDatetime64ToDatetimeStruct" ( + PyArray_DatetimeMetaData *meta, npy_datetime dt, + npy_datetimestruct *out) except -1 + int convert_datetimestruct_to_datetime64 "NpyDatetime_ConvertDatetimeStructToDatetime64"( + PyArray_DatetimeMetaData *meta, const npy_datetimestruct *dts, + npy_datetime *out) except -1 + + +# +# ufunc API +# + +cdef extern from "numpy/ufuncobject.h": + + ctypedef void (*PyUFuncGenericFunction) (char **, npy_intp *, npy_intp *, void *) + + ctypedef class numpy.ufunc [object PyUFuncObject, check_size ignore]: + cdef: + int nin, nout, nargs + int identity + PyUFuncGenericFunction *functions + void **data + int ntypes + int check_return + char *name + char *types + char *doc + void *ptr + PyObject *obj + PyObject *userloops + + cdef enum: + PyUFunc_Zero + PyUFunc_One + PyUFunc_None + # deprecated + UFUNC_FPE_DIVIDEBYZERO + UFUNC_FPE_OVERFLOW + UFUNC_FPE_UNDERFLOW + UFUNC_FPE_INVALID + # use these instead + NPY_FPE_DIVIDEBYZERO + NPY_FPE_OVERFLOW + NPY_FPE_UNDERFLOW + NPY_FPE_INVALID + + object PyUFunc_FromFuncAndData(PyUFuncGenericFunction *, + void **, char *, int, int, int, int, char *, char *, int) + int PyUFunc_RegisterLoopForType(ufunc, int, + PyUFuncGenericFunction, int *, void *) except -1 + void PyUFunc_f_f_As_d_d \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_d_d \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_f_f \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_g_g \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_F_F_As_D_D \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_F_F \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_D_D \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_G_G \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_O_O \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_ff_f_As_dd_d \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_ff_f \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_dd_d \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_gg_g \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_FF_F_As_DD_D \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_DD_D \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_FF_F \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_GG_G \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_OO_O \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_O_O_method \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_OO_O_method \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_On_Om \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_clearfperr() + int PyUFunc_getfperr() + int PyUFunc_ReplaceLoopBySignature \ + (ufunc, PyUFuncGenericFunction, int *, PyUFuncGenericFunction *) + object PyUFunc_FromFuncAndDataAndSignature \ + (PyUFuncGenericFunction *, void **, char *, int, int, int, + int, char *, char *, int, char *) + + int _import_umath() except -1 + +cdef inline void set_array_base(ndarray arr, object base): + Py_INCREF(base) # important to do this before stealing the reference below! + PyArray_SetBaseObject(arr, base) + +cdef inline object get_array_base(ndarray arr): + base = PyArray_BASE(arr) + if base is NULL: + return None + return base + +# Versions of the import_* functions which are more suitable for +# Cython code. +cdef inline int import_array() except -1: + try: + __pyx_import_array() + except Exception: + raise ImportError("numpy._core.multiarray failed to import") + +cdef inline int import_umath() except -1: + try: + _import_umath() + except Exception: + raise ImportError("numpy._core.umath failed to import") + +cdef inline int import_ufunc() except -1: + try: + _import_umath() + except Exception: + raise ImportError("numpy._core.umath failed to import") + + +cdef inline bint is_timedelta64_object(object obj): + """ + Cython equivalent of `isinstance(obj, np.timedelta64)` + + Parameters + ---------- + obj : object + + Returns + ------- + bool + """ + return PyObject_TypeCheck(obj, &PyTimedeltaArrType_Type) + + +cdef inline bint is_datetime64_object(object obj): + """ + Cython equivalent of `isinstance(obj, np.datetime64)` + + Parameters + ---------- + obj : object + + Returns + ------- + bool + """ + return PyObject_TypeCheck(obj, &PyDatetimeArrType_Type) + + +cdef inline npy_datetime get_datetime64_value(object obj) nogil: + """ + returns the int64 value underlying scalar numpy datetime64 object + + Note that to interpret this as a datetime, the corresponding unit is + also needed. That can be found using `get_datetime64_unit`. + """ + return (obj).obval + + +cdef inline npy_timedelta get_timedelta64_value(object obj) nogil: + """ + returns the int64 value underlying scalar numpy timedelta64 object + """ + return (obj).obval + + +cdef inline NPY_DATETIMEUNIT get_datetime64_unit(object obj) nogil: + """ + returns the unit part of the dtype for a numpy datetime64 object. + """ + return (obj).obmeta.base + + +cdef extern from "numpy/arrayobject.h": + + ctypedef struct NpyIter: + pass + + cdef enum: + NPY_FAIL + NPY_SUCCEED + + cdef enum: + # Track an index representing C order + NPY_ITER_C_INDEX + # Track an index representing Fortran order + NPY_ITER_F_INDEX + # Track a multi-index + NPY_ITER_MULTI_INDEX + # User code external to the iterator does the 1-dimensional innermost loop + NPY_ITER_EXTERNAL_LOOP + # Convert all the operands to a common data type + NPY_ITER_COMMON_DTYPE + # Operands may hold references, requiring API access during iteration + NPY_ITER_REFS_OK + # Zero-sized operands should be permitted, iteration checks IterSize for 0 + NPY_ITER_ZEROSIZE_OK + # Permits reductions (size-0 stride with dimension size > 1) + NPY_ITER_REDUCE_OK + # Enables sub-range iteration + NPY_ITER_RANGED + # Enables buffering + NPY_ITER_BUFFERED + # When buffering is enabled, grows the inner loop if possible + NPY_ITER_GROWINNER + # Delay allocation of buffers until first Reset* call + NPY_ITER_DELAY_BUFALLOC + # When NPY_KEEPORDER is specified, disable reversing negative-stride axes + NPY_ITER_DONT_NEGATE_STRIDES + NPY_ITER_COPY_IF_OVERLAP + # The operand will be read from and written to + NPY_ITER_READWRITE + # The operand will only be read from + NPY_ITER_READONLY + # The operand will only be written to + NPY_ITER_WRITEONLY + # The operand's data must be in native byte order + NPY_ITER_NBO + # The operand's data must be aligned + NPY_ITER_ALIGNED + # The operand's data must be contiguous (within the inner loop) + NPY_ITER_CONTIG + # The operand may be copied to satisfy requirements + NPY_ITER_COPY + # The operand may be copied with WRITEBACKIFCOPY to satisfy requirements + NPY_ITER_UPDATEIFCOPY + # Allocate the operand if it is NULL + NPY_ITER_ALLOCATE + # If an operand is allocated, don't use any subtype + NPY_ITER_NO_SUBTYPE + # This is a virtual array slot, operand is NULL but temporary data is there + NPY_ITER_VIRTUAL + # Require that the dimension match the iterator dimensions exactly + NPY_ITER_NO_BROADCAST + # A mask is being used on this array, affects buffer -> array copy + NPY_ITER_WRITEMASKED + # This array is the mask for all WRITEMASKED operands + NPY_ITER_ARRAYMASK + # Assume iterator order data access for COPY_IF_OVERLAP + NPY_ITER_OVERLAP_ASSUME_ELEMENTWISE + + # construction and destruction functions + NpyIter* NpyIter_New(ndarray arr, npy_uint32 flags, NPY_ORDER order, + NPY_CASTING casting, dtype datatype) except NULL + NpyIter* NpyIter_MultiNew(npy_intp nop, PyArrayObject** op, npy_uint32 flags, + NPY_ORDER order, NPY_CASTING casting, npy_uint32* + op_flags, PyArray_Descr** op_dtypes) except NULL + NpyIter* NpyIter_AdvancedNew(npy_intp nop, PyArrayObject** op, + npy_uint32 flags, NPY_ORDER order, + NPY_CASTING casting, npy_uint32* op_flags, + PyArray_Descr** op_dtypes, int oa_ndim, + int** op_axes, const npy_intp* itershape, + npy_intp buffersize) except NULL + NpyIter* NpyIter_Copy(NpyIter* it) except NULL + int NpyIter_RemoveAxis(NpyIter* it, int axis) except NPY_FAIL + int NpyIter_RemoveMultiIndex(NpyIter* it) except NPY_FAIL + int NpyIter_EnableExternalLoop(NpyIter* it) except NPY_FAIL + int NpyIter_Deallocate(NpyIter* it) except NPY_FAIL + int NpyIter_Reset(NpyIter* it, char** errmsg) except NPY_FAIL + int NpyIter_ResetToIterIndexRange(NpyIter* it, npy_intp istart, + npy_intp iend, char** errmsg) except NPY_FAIL + int NpyIter_ResetBasePointers(NpyIter* it, char** baseptrs, char** errmsg) except NPY_FAIL + int NpyIter_GotoMultiIndex(NpyIter* it, const npy_intp* multi_index) except NPY_FAIL + int NpyIter_GotoIndex(NpyIter* it, npy_intp index) except NPY_FAIL + npy_intp NpyIter_GetIterSize(NpyIter* it) nogil + npy_intp NpyIter_GetIterIndex(NpyIter* it) nogil + void NpyIter_GetIterIndexRange(NpyIter* it, npy_intp* istart, + npy_intp* iend) nogil + int NpyIter_GotoIterIndex(NpyIter* it, npy_intp iterindex) except NPY_FAIL + npy_bool NpyIter_HasDelayedBufAlloc(NpyIter* it) nogil + npy_bool NpyIter_HasExternalLoop(NpyIter* it) nogil + npy_bool NpyIter_HasMultiIndex(NpyIter* it) nogil + npy_bool NpyIter_HasIndex(NpyIter* it) nogil + npy_bool NpyIter_RequiresBuffering(NpyIter* it) nogil + npy_bool NpyIter_IsBuffered(NpyIter* it) nogil + npy_bool NpyIter_IsGrowInner(NpyIter* it) nogil + npy_intp NpyIter_GetBufferSize(NpyIter* it) nogil + int NpyIter_GetNDim(NpyIter* it) nogil + int NpyIter_GetNOp(NpyIter* it) nogil + npy_intp* NpyIter_GetAxisStrideArray(NpyIter* it, int axis) except NULL + int NpyIter_GetShape(NpyIter* it, npy_intp* outshape) nogil + PyArray_Descr** NpyIter_GetDescrArray(NpyIter* it) + PyArrayObject** NpyIter_GetOperandArray(NpyIter* it) + ndarray NpyIter_GetIterView(NpyIter* it, npy_intp i) + void NpyIter_GetReadFlags(NpyIter* it, char* outreadflags) + void NpyIter_GetWriteFlags(NpyIter* it, char* outwriteflags) + int NpyIter_CreateCompatibleStrides(NpyIter* it, npy_intp itemsize, + npy_intp* outstrides) except NPY_FAIL + npy_bool NpyIter_IsFirstVisit(NpyIter* it, int iop) nogil + # functions for iterating an NpyIter object + # + # These don't match the definition in the C API because Cython can't wrap + # function pointers that return functions. + NpyIter_IterNextFunc* NpyIter_GetIterNext(NpyIter* it, char** errmsg) except NULL + NpyIter_GetMultiIndexFunc* NpyIter_GetGetMultiIndex(NpyIter* it, + char** errmsg) except NULL + char** NpyIter_GetDataPtrArray(NpyIter* it) nogil + char** NpyIter_GetInitialDataPtrArray(NpyIter* it) nogil + npy_intp* NpyIter_GetIndexPtr(NpyIter* it) + npy_intp* NpyIter_GetInnerStrideArray(NpyIter* it) nogil + npy_intp* NpyIter_GetInnerLoopSizePtr(NpyIter* it) nogil + void NpyIter_GetInnerFixedStrideArray(NpyIter* it, npy_intp* outstrides) nogil + npy_bool NpyIter_IterationNeedsAPI(NpyIter* it) nogil + void NpyIter_DebugPrint(NpyIter* it) + +# NpyString API +cdef extern from "numpy/ndarraytypes.h": + ctypedef struct npy_string_allocator: + pass + + ctypedef struct npy_packed_static_string: + pass + + ctypedef struct npy_static_string: + size_t size + const char *buf + + ctypedef struct PyArray_StringDTypeObject: + PyArray_Descr base + PyObject *na_object + char coerce + char has_nan_na + char has_string_na + char array_owned + npy_static_string default_string + npy_static_string na_name + npy_string_allocator *allocator + +cdef extern from "numpy/arrayobject.h": + npy_string_allocator *NpyString_acquire_allocator(const PyArray_StringDTypeObject *descr) + void NpyString_acquire_allocators(size_t n_descriptors, PyArray_Descr *const descrs[], npy_string_allocator *allocators[]) + void NpyString_release_allocator(npy_string_allocator *allocator) + void NpyString_release_allocators(size_t length, npy_string_allocator *allocators[]) + int NpyString_load(npy_string_allocator *allocator, const npy_packed_static_string *packed_string, npy_static_string *unpacked_string) + int NpyString_pack_null(npy_string_allocator *allocator, npy_packed_static_string *packed_string) + int NpyString_pack(npy_string_allocator *allocator, npy_packed_static_string *packed_string, const char *buf, size_t size) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/numpy/__init__.py b/TTS/Kokoro/.venv/Lib/site-packages/numpy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4310912c30086700b40f46cb410e56f7d8ce9c07 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/numpy/__init__.py @@ -0,0 +1,955 @@ +""" +NumPy +===== + +Provides + 1. An array object of arbitrary homogeneous items + 2. Fast mathematical operations over arrays + 3. Linear Algebra, Fourier Transforms, Random Number Generation + +How to use the documentation +---------------------------- +Documentation is available in two forms: docstrings provided +with the code, and a loose standing reference guide, available from +`the NumPy homepage `_. + +We recommend exploring the docstrings using +`IPython `_, an advanced Python shell with +TAB-completion and introspection capabilities. See below for further +instructions. + +The docstring examples assume that `numpy` has been imported as ``np``:: + + >>> import numpy as np + +Code snippets are indicated by three greater-than signs:: + + >>> x = 42 + >>> x = x + 1 + +Use the built-in ``help`` function to view a function's docstring:: + + >>> help(np.sort) + ... # doctest: +SKIP + +For some objects, ``np.info(obj)`` may provide additional help. This is +particularly true if you see the line "Help on ufunc object:" at the top +of the help() page. Ufuncs are implemented in C, not Python, for speed. +The native Python help() does not know how to view their help, but our +np.info() function does. + +Available subpackages +--------------------- +lib + Basic functions used by several sub-packages. +random + Core Random Tools +linalg + Core Linear Algebra Tools +fft + Core FFT routines +polynomial + Polynomial tools +testing + NumPy testing tools +distutils + Enhancements to distutils with support for + Fortran compilers support and more (for Python <= 3.11) + +Utilities +--------- +test + Run numpy unittests +show_config + Show numpy build configuration +__version__ + NumPy version string + +Viewing documentation using IPython +----------------------------------- + +Start IPython and import `numpy` usually under the alias ``np``: `import +numpy as np`. Then, directly past or use the ``%cpaste`` magic to paste +examples into the shell. To see which functions are available in `numpy`, +type ``np.`` (where ```` refers to the TAB key), or use +``np.*cos*?`` (where ```` refers to the ENTER key) to narrow +down the list. To view the docstring for a function, use +``np.cos?`` (to view the docstring) and ``np.cos??`` (to view +the source code). + +Copies vs. in-place operation +----------------------------- +Most of the functions in `numpy` return a copy of the array argument +(e.g., `np.sort`). In-place versions of these functions are often +available as array methods, i.e. ``x = np.array([1,2,3]); x.sort()``. +Exceptions to this rule are documented. + +""" + + +# start delvewheel patch +def _delvewheel_patch_1_11_2(): + import os + if os.path.isdir(libs_dir := os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, 'numpy.libs'))): + os.add_dll_directory(libs_dir) + + +_delvewheel_patch_1_11_2() +del _delvewheel_patch_1_11_2 +# end delvewheel patch + +import os +import sys +import warnings + +# If a version with git hash was stored, use that instead +from . import version +from ._expired_attrs_2_0 import __expired_attributes__ +from ._globals import _CopyMode, _NoValue +from .version import __version__ + +# We first need to detect if we're being called as part of the numpy setup +# procedure itself in a reliable manner. +try: + __NUMPY_SETUP__ # noqa: B018 +except NameError: + __NUMPY_SETUP__ = False + +if __NUMPY_SETUP__: + sys.stderr.write('Running from numpy source directory.\n') +else: + # Allow distributors to run custom init code before importing numpy._core + from . import _distributor_init + + try: + from numpy.__config__ import show_config + except ImportError as e: + if isinstance(e, ModuleNotFoundError) and e.name == "numpy.__config__": + # The __config__ module itself was not found, so add this info: + msg = """Error importing numpy: you should not try to import numpy from + its source directory; please exit the numpy source tree, and relaunch + your python interpreter from there.""" + raise ImportError(msg) from e + raise + + from . import _core + from ._core import ( + False_, + ScalarType, + True_, + abs, + absolute, + acos, + acosh, + add, + all, + allclose, + amax, + amin, + any, + arange, + arccos, + arccosh, + arcsin, + arcsinh, + arctan, + arctan2, + arctanh, + argmax, + argmin, + argpartition, + argsort, + argwhere, + around, + array, + array2string, + array_equal, + array_equiv, + array_repr, + array_str, + asanyarray, + asarray, + ascontiguousarray, + asfortranarray, + asin, + asinh, + astype, + atan, + atan2, + atanh, + atleast_1d, + atleast_2d, + atleast_3d, + base_repr, + binary_repr, + bitwise_and, + bitwise_count, + bitwise_invert, + bitwise_left_shift, + bitwise_not, + bitwise_or, + bitwise_right_shift, + bitwise_xor, + block, + bool, + bool_, + broadcast, + busday_count, + busday_offset, + busdaycalendar, + byte, + bytes_, + can_cast, + cbrt, + cdouble, + ceil, + character, + choose, + clip, + clongdouble, + complex64, + complex128, + complexfloating, + compress, + concat, + concatenate, + conj, + conjugate, + convolve, + copysign, + copyto, + correlate, + cos, + cosh, + count_nonzero, + cross, + csingle, + cumprod, + cumsum, + cumulative_prod, + cumulative_sum, + datetime64, + datetime_as_string, + datetime_data, + deg2rad, + degrees, + diagonal, + divide, + divmod, + dot, + double, + dtype, + e, + einsum, + einsum_path, + empty, + empty_like, + equal, + errstate, + euler_gamma, + exp, + exp2, + expm1, + fabs, + finfo, + flatiter, + flatnonzero, + flexible, + float16, + float32, + float64, + float_power, + floating, + floor, + floor_divide, + fmax, + fmin, + fmod, + format_float_positional, + format_float_scientific, + frexp, + from_dlpack, + frombuffer, + fromfile, + fromfunction, + fromiter, + frompyfunc, + fromstring, + full, + full_like, + gcd, + generic, + geomspace, + get_printoptions, + getbufsize, + geterr, + geterrcall, + greater, + greater_equal, + half, + heaviside, + hstack, + hypot, + identity, + iinfo, + indices, + inexact, + inf, + inner, + int8, + int16, + int32, + int64, + int_, + intc, + integer, + intp, + invert, + is_busday, + isclose, + isdtype, + isfinite, + isfortran, + isinf, + isnan, + isnat, + isscalar, + issubdtype, + lcm, + ldexp, + left_shift, + less, + less_equal, + lexsort, + linspace, + little_endian, + log, + log1p, + log2, + log10, + logaddexp, + logaddexp2, + logical_and, + logical_not, + logical_or, + logical_xor, + logspace, + long, + longdouble, + longlong, + matmul, + matrix_transpose, + matvec, + max, + maximum, + may_share_memory, + mean, + memmap, + min, + min_scalar_type, + minimum, + mod, + modf, + moveaxis, + multiply, + nan, + ndarray, + ndim, + nditer, + negative, + nested_iters, + newaxis, + nextafter, + nonzero, + not_equal, + number, + object_, + ones, + ones_like, + outer, + partition, + permute_dims, + pi, + positive, + pow, + power, + printoptions, + prod, + promote_types, + ptp, + put, + putmask, + rad2deg, + radians, + ravel, + recarray, + reciprocal, + record, + remainder, + repeat, + require, + reshape, + resize, + result_type, + right_shift, + rint, + roll, + rollaxis, + round, + sctypeDict, + searchsorted, + set_printoptions, + setbufsize, + seterr, + seterrcall, + shape, + shares_memory, + short, + sign, + signbit, + signedinteger, + sin, + single, + sinh, + size, + sort, + spacing, + sqrt, + square, + squeeze, + stack, + std, + str_, + subtract, + sum, + swapaxes, + take, + tan, + tanh, + tensordot, + timedelta64, + trace, + transpose, + true_divide, + trunc, + typecodes, + ubyte, + ufunc, + uint, + uint8, + uint16, + uint32, + uint64, + uintc, + uintp, + ulong, + ulonglong, + unsignedinteger, + unstack, + ushort, + var, + vdot, + vecdot, + vecmat, + void, + vstack, + where, + zeros, + zeros_like, + ) + + # NOTE: It's still under discussion whether these aliases + # should be removed. + for ta in ["float96", "float128", "complex192", "complex256"]: + try: + globals()[ta] = getattr(_core, ta) + except AttributeError: + pass + del ta + + from . import lib, matrixlib as _mat + from .lib import scimath as emath + from .lib._arraypad_impl import pad + from .lib._arraysetops_impl import ( + ediff1d, + intersect1d, + isin, + setdiff1d, + setxor1d, + union1d, + unique, + unique_all, + unique_counts, + unique_inverse, + unique_values, + ) + from .lib._function_base_impl import ( + angle, + append, + asarray_chkfinite, + average, + bartlett, + bincount, + blackman, + copy, + corrcoef, + cov, + delete, + diff, + digitize, + extract, + flip, + gradient, + hamming, + hanning, + i0, + insert, + interp, + iterable, + kaiser, + median, + meshgrid, + percentile, + piecewise, + place, + quantile, + rot90, + select, + sinc, + sort_complex, + trapezoid, + trim_zeros, + unwrap, + vectorize, + ) + from .lib._histograms_impl import histogram, histogram_bin_edges, histogramdd + from .lib._index_tricks_impl import ( + c_, + diag_indices, + diag_indices_from, + fill_diagonal, + index_exp, + ix_, + mgrid, + ndenumerate, + ndindex, + ogrid, + r_, + ravel_multi_index, + s_, + unravel_index, + ) + from .lib._nanfunctions_impl import ( + nanargmax, + nanargmin, + nancumprod, + nancumsum, + nanmax, + nanmean, + nanmedian, + nanmin, + nanpercentile, + nanprod, + nanquantile, + nanstd, + nansum, + nanvar, + ) + from .lib._npyio_impl import ( + fromregex, + genfromtxt, + load, + loadtxt, + packbits, + save, + savetxt, + savez, + savez_compressed, + unpackbits, + ) + from .lib._polynomial_impl import ( + poly, + poly1d, + polyadd, + polyder, + polydiv, + polyfit, + polyint, + polymul, + polysub, + polyval, + roots, + ) + from .lib._shape_base_impl import ( + apply_along_axis, + apply_over_axes, + array_split, + column_stack, + dsplit, + dstack, + expand_dims, + hsplit, + kron, + put_along_axis, + row_stack, + split, + take_along_axis, + tile, + vsplit, + ) + from .lib._stride_tricks_impl import ( + broadcast_arrays, + broadcast_shapes, + broadcast_to, + ) + from .lib._twodim_base_impl import ( + diag, + diagflat, + eye, + fliplr, + flipud, + histogram2d, + mask_indices, + tri, + tril, + tril_indices, + tril_indices_from, + triu, + triu_indices, + triu_indices_from, + vander, + ) + from .lib._type_check_impl import ( + common_type, + imag, + iscomplex, + iscomplexobj, + isreal, + isrealobj, + mintypecode, + nan_to_num, + real, + real_if_close, + typename, + ) + from .lib._ufunclike_impl import fix, isneginf, isposinf + from .lib._utils_impl import get_include, info, show_runtime + from .matrixlib import asmatrix, bmat, matrix + + # public submodules are imported lazily, therefore are accessible from + # __getattr__. Note that `distutils` (deprecated) and `array_api` + # (experimental label) are not added here, because `from numpy import *` + # must not raise any warnings - that's too disruptive. + __numpy_submodules__ = { + "linalg", "fft", "dtypes", "random", "polynomial", "ma", + "exceptions", "lib", "ctypeslib", "testing", "typing", + "f2py", "test", "rec", "char", "core", "strings", + } + + # We build warning messages for former attributes + _msg = ( + "module 'numpy' has no attribute '{n}'.\n" + "`np.{n}` was a deprecated alias for the builtin `{n}`. " + "To avoid this error in existing code, use `{n}` by itself. " + "Doing this will not modify any behavior and is safe. {extended_msg}\n" + "The aliases was originally deprecated in NumPy 1.20; for more " + "details and guidance see the original release note at:\n" + " https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations") + + _specific_msg = ( + "If you specifically wanted the numpy scalar type, use `np.{}` here.") + + _int_extended_msg = ( + "When replacing `np.{}`, you may wish to use e.g. `np.int64` " + "or `np.int32` to specify the precision. If you wish to review " + "your current use, check the release note link for " + "additional information.") + + _type_info = [ + ("object", ""), # The NumPy scalar only exists by name. + ("float", _specific_msg.format("float64")), + ("complex", _specific_msg.format("complex128")), + ("str", _specific_msg.format("str_")), + ("int", _int_extended_msg.format("int"))] + + __former_attrs__ = { + n: _msg.format(n=n, extended_msg=extended_msg) + for n, extended_msg in _type_info + } + + # Some of these could be defined right away, but most were aliases to + # the Python objects and only removed in NumPy 1.24. Defining them should + # probably wait for NumPy 1.26 or 2.0. + # When defined, these should possibly not be added to `__all__` to avoid + # import with `from numpy import *`. + __future_scalars__ = {"str", "bytes", "object"} + + __array_api_version__ = "2024.12" + + from ._array_api_info import __array_namespace_info__ + + __all__ = list( + __numpy_submodules__ | + set(_core.__all__) | + set(_mat.__all__) | + set(lib._histograms_impl.__all__) | + set(lib._nanfunctions_impl.__all__) | + set(lib._function_base_impl.__all__) | + set(lib._twodim_base_impl.__all__) | + set(lib._shape_base_impl.__all__) | + set(lib._type_check_impl.__all__) | + set(lib._arraysetops_impl.__all__) | + set(lib._ufunclike_impl.__all__) | + set(lib._arraypad_impl.__all__) | + set(lib._utils_impl.__all__) | + set(lib._stride_tricks_impl.__all__) | + set(lib._polynomial_impl.__all__) | + set(lib._npyio_impl.__all__) | + set(lib._index_tricks_impl.__all__) | + {"emath", "show_config", "__version__", "__array_namespace_info__"} + ) + + # Filter out Cython harmless warnings + warnings.filterwarnings("ignore", message="numpy.dtype size changed") + warnings.filterwarnings("ignore", message="numpy.ufunc size changed") + warnings.filterwarnings("ignore", message="numpy.ndarray size changed") + + def __getattr__(attr): + # Warn for expired attributes + import warnings + + if attr == "linalg": + import numpy.linalg as linalg + return linalg + elif attr == "fft": + import numpy.fft as fft + return fft + elif attr == "dtypes": + import numpy.dtypes as dtypes + return dtypes + elif attr == "random": + import numpy.random as random + return random + elif attr == "polynomial": + import numpy.polynomial as polynomial + return polynomial + elif attr == "ma": + import numpy.ma as ma + return ma + elif attr == "ctypeslib": + import numpy.ctypeslib as ctypeslib + return ctypeslib + elif attr == "exceptions": + import numpy.exceptions as exceptions + return exceptions + elif attr == "testing": + import numpy.testing as testing + return testing + elif attr == "matlib": + import numpy.matlib as matlib + return matlib + elif attr == "f2py": + import numpy.f2py as f2py + return f2py + elif attr == "typing": + import numpy.typing as typing + return typing + elif attr == "rec": + import numpy.rec as rec + return rec + elif attr == "char": + import numpy.char as char + return char + elif attr == "array_api": + raise AttributeError("`numpy.array_api` is not available from " + "numpy 2.0 onwards", name=None) + elif attr == "core": + import numpy.core as core + return core + elif attr == "strings": + import numpy.strings as strings + return strings + elif attr == "distutils": + if 'distutils' in __numpy_submodules__: + import numpy.distutils as distutils + return distutils + else: + raise AttributeError("`numpy.distutils` is not available from " + "Python 3.12 onwards", name=None) + + if attr in __future_scalars__: + # And future warnings for those that will change, but also give + # the AttributeError + warnings.warn( + f"In the future `np.{attr}` will be defined as the " + "corresponding NumPy scalar.", FutureWarning, stacklevel=2) + + if attr in __former_attrs__: + raise AttributeError(__former_attrs__[attr], name=None) + + if attr in __expired_attributes__: + raise AttributeError( + f"`np.{attr}` was removed in the NumPy 2.0 release. " + f"{__expired_attributes__[attr]}", + name=None + ) + + if attr == "chararray": + warnings.warn( + "`np.chararray` is deprecated and will be removed from " + "the main namespace in the future. Use an array with a string " + "or bytes dtype instead.", DeprecationWarning, stacklevel=2) + import numpy.char as char + return char.chararray + + raise AttributeError(f"module {__name__!r} has no attribute {attr!r}") + + def __dir__(): + public_symbols = ( + globals().keys() | __numpy_submodules__ + ) + public_symbols -= { + "matrixlib", "matlib", "tests", "conftest", "version", + "distutils", "array_api" + } + return list(public_symbols) + + # Pytest testing + from numpy._pytesttester import PytestTester + test = PytestTester(__name__) + del PytestTester + + def _sanity_check(): + """ + Quick sanity checks for common bugs caused by environment. + There are some cases e.g. with wrong BLAS ABI that cause wrong + results under specific runtime conditions that are not necessarily + achieved during test suite runs, and it is useful to catch those early. + + See https://github.com/numpy/numpy/issues/8577 and other + similar bug reports. + + """ + try: + x = ones(2, dtype=float32) + if not abs(x.dot(x) - float32(2.0)) < 1e-5: + raise AssertionError + except AssertionError: + msg = ("The current Numpy installation ({!r}) fails to " + "pass simple sanity checks. This can be caused for example " + "by incorrect BLAS library being linked in, or by mixing " + "package managers (pip, conda, apt, ...). Search closed " + "numpy issues for similar problems.") + raise RuntimeError(msg.format(__file__)) from None + + _sanity_check() + del _sanity_check + + def _mac_os_check(): + """ + Quick Sanity check for Mac OS look for accelerate build bugs. + Testing numpy polyfit calls init_dgelsd(LAPACK) + """ + try: + c = array([3., 2., 1.]) + x = linspace(0, 2, 5) + y = polyval(c, x) + _ = polyfit(x, y, 2, cov=True) + except ValueError: + pass + + if sys.platform == "darwin": + from . import exceptions + with warnings.catch_warnings(record=True) as w: + _mac_os_check() + # Throw runtime error, if the test failed + # Check for warning and report the error_message + if len(w) > 0: + for _wn in w: + if _wn.category is exceptions.RankWarning: + # Ignore other warnings, they may not be relevant (see gh-25433) + error_message = ( + f"{_wn.category.__name__}: {_wn.message}" + ) + msg = ( + "Polyfit sanity test emitted a warning, most likely due " + "to using a buggy Accelerate backend." + "\nIf you compiled yourself, more information is available at:" # noqa: E501 + "\nhttps://numpy.org/devdocs/building/index.html" + "\nOtherwise report this to the vendor " + f"that provided NumPy.\n\n{error_message}\n") + raise RuntimeError(msg) + del _wn + del w + del _mac_os_check + + def blas_fpe_check(): + # Check if BLAS adds spurious FPEs, mostly seen on M4 arms with Accelerate. + with errstate(all='raise'): + x = ones((20, 20)) + try: + x @ x + except FloatingPointError: + res = _core._multiarray_umath._blas_supports_fpe(False) + if res: # res was not modified (hardcoded to True for now) + warnings.warn( + "Spurious warnings given by blas but suppression not " + "set up on this platform. Please open a NumPy issue.", + UserWarning, stacklevel=2) + + blas_fpe_check() + del blas_fpe_check + + def hugepage_setup(): + """ + We usually use madvise hugepages support, but on some old kernels it + is slow and thus better avoided. Specifically kernel version 4.6 + had a bug fix which probably fixed this: + https://github.com/torvalds/linux/commit/7cf91a98e607c2f935dbcc177d70011e95b8faff + """ + use_hugepage = os.environ.get("NUMPY_MADVISE_HUGEPAGE", None) + if sys.platform == "linux" and use_hugepage is None: + # If there is an issue with parsing the kernel version, + # set use_hugepage to 0. Usage of LooseVersion will handle + # the kernel version parsing better, but avoided since it + # will increase the import time. + # See: #16679 for related discussion. + try: + use_hugepage = 1 + kernel_version = os.uname().release.split(".")[:2] + kernel_version = tuple(int(v) for v in kernel_version) + if kernel_version < (4, 6): + use_hugepage = 0 + except ValueError: + use_hugepage = 0 + elif use_hugepage is None: + # This is not Linux, so it should not matter, just enable anyway + use_hugepage = 1 + else: + use_hugepage = int(use_hugepage) + return use_hugepage + + # Note that this will currently only make a difference on Linux + _core.multiarray._set_madvise_hugepage(hugepage_setup()) + del hugepage_setup + + # Give a warning if NumPy is reloaded or imported on a sub-interpreter + # We do this from python, since the C-module may not be reloaded and + # it is tidier organized. + _core.multiarray._multiarray_umath._reload_guard() + + # TODO: Remove the environment variable entirely now that it is "weak" + if (os.environ.get("NPY_PROMOTION_STATE", "weak") != "weak"): + warnings.warn( + "NPY_PROMOTION_STATE was a temporary feature for NumPy 2.0 " + "transition and is ignored after NumPy 2.2.", + UserWarning, stacklevel=2) + + # Tell PyInstaller where to find hook-numpy.py + def _pyinstaller_hooks_dir(): + from pathlib import Path + return [str(Path(__file__).with_name("_pyinstaller").resolve())] + + +# Remove symbols imported for internal use +del os, sys, warnings diff --git a/TTS/Kokoro/.venv/Lib/site-packages/numpy/__init__.pyi b/TTS/Kokoro/.venv/Lib/site-packages/numpy/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..2833f3cb6e7aad522a748bea75fea1375ccc3403 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/numpy/__init__.pyi @@ -0,0 +1,6202 @@ +# ruff: noqa: I001 +import builtins +import sys +import mmap +import ctypes as ct +import array as _array +import datetime as dt +import inspect +from abc import abstractmethod +from types import EllipsisType, ModuleType, TracebackType, MappingProxyType, GenericAlias +from decimal import Decimal +from fractions import Fraction +from uuid import UUID + +import numpy as np +from numpy.__config__ import show as show_config +from numpy._pytesttester import PytestTester +from numpy._core._internal import _ctypes + +from numpy._typing import ( # type: ignore[deprecated] + # Arrays + ArrayLike, + NDArray, + _SupportsArray, + _NestedSequence, + _ArrayLike, + _ArrayLikeBool_co, + _ArrayLikeUInt_co, + _ArrayLikeInt, + _ArrayLikeInt_co, + _ArrayLikeFloat64_co, + _ArrayLikeFloat_co, + _ArrayLikeComplex128_co, + _ArrayLikeComplex_co, + _ArrayLikeNumber_co, + _ArrayLikeObject_co, + _ArrayLikeBytes_co, + _ArrayLikeStr_co, + _ArrayLikeString_co, + _ArrayLikeTD64_co, + _ArrayLikeDT64_co, + # DTypes + DTypeLike, + _DTypeLike, + _DTypeLikeVoid, + _VoidDTypeLike, + # Shapes + _AnyShape, + _Shape, + _ShapeLike, + # Scalars + _CharLike_co, + _IntLike_co, + _FloatLike_co, + _TD64Like_co, + _NumberLike_co, + _ScalarLike_co, + # `number` precision + NBitBase, + # NOTE: Do not remove the extended precision bit-types even if seemingly unused; + # they're used by the mypy plugin + _128Bit, + _96Bit, + _64Bit, + _32Bit, + _16Bit, + _8Bit, + _NBitByte, + _NBitShort, + _NBitIntC, + _NBitIntP, + _NBitLong, + _NBitLongLong, + _NBitHalf, + _NBitSingle, + _NBitDouble, + _NBitLongDouble, + # Character codes + _BoolCodes, + _UInt8Codes, + _UInt16Codes, + _UInt32Codes, + _UInt64Codes, + _Int8Codes, + _Int16Codes, + _Int32Codes, + _Int64Codes, + _Float16Codes, + _Float32Codes, + _Float64Codes, + _Complex64Codes, + _Complex128Codes, + _ByteCodes, + _ShortCodes, + _IntCCodes, + _IntPCodes, + _LongCodes, + _LongLongCodes, + _UByteCodes, + _UShortCodes, + _UIntCCodes, + _UIntPCodes, + _ULongCodes, + _ULongLongCodes, + _HalfCodes, + _SingleCodes, + _DoubleCodes, + _LongDoubleCodes, + _CSingleCodes, + _CDoubleCodes, + _CLongDoubleCodes, + _DT64Codes, + _TD64Codes, + _StrCodes, + _BytesCodes, + _VoidCodes, + _ObjectCodes, + _StringCodes, + _UnsignedIntegerCodes, + _SignedIntegerCodes, + _IntegerCodes, + _FloatingCodes, + _ComplexFloatingCodes, + _InexactCodes, + _CharacterCodes, + # Ufuncs + _UFunc_Nin1_Nout1, + _UFunc_Nin2_Nout1, + _UFunc_Nin1_Nout2, + _UFunc_Nin2_Nout2, + _GUFunc_Nin2_Nout1, +) + +# NOTE: Numpy's mypy plugin is used for removing the types unavailable to the specific platform +from numpy._typing._extended_precision import ( + float96, + float128, + complex192, + complex256, +) + +from numpy._array_api_info import __array_namespace_info__ + +from collections.abc import ( + Callable, + Iterable, + Iterator, + Mapping, + Sequence, +) + +if sys.version_info >= (3, 12): + from collections.abc import Buffer as _SupportsBuffer +else: + _SupportsBuffer: TypeAlias = ( + bytes + | bytearray + | memoryview + | _array.array[Any] + | mmap.mmap + | NDArray[Any] + | generic + ) + +from typing import ( + Any, + ClassVar, + Final, + Generic, + Literal as L, + LiteralString, + Never, + NoReturn, + Protocol, + Self, + SupportsComplex, + SupportsFloat, + SupportsInt, + SupportsIndex, + TypeAlias, + TypedDict, + final, + overload, + type_check_only, +) + +# NOTE: `typing_extensions` and `_typeshed` are always available in `.pyi` stubs, even +# if not available at runtime. This is because the `typeshed` stubs for the standard +# library include `typing_extensions` stubs: +# https://github.com/python/typeshed/blob/main/stdlib/typing_extensions.pyi +from _typeshed import Incomplete, StrOrBytesPath, SupportsFlush, SupportsLenAndGetItem, SupportsWrite +from typing_extensions import CapsuleType, TypeVar, deprecated, override + +from numpy import ( + char, + core, + ctypeslib, + dtypes, + exceptions, + f2py, + fft, + lib, + linalg, + ma, + polynomial, + random, + rec, + strings, + testing, + typing, +) + +# available through `__getattr__`, but not in `__all__` or `__dir__` +from numpy import ( + __config__ as __config__, + matlib as matlib, + matrixlib as matrixlib, + version as version, +) +if sys.version_info < (3, 12): + from numpy import distutils as distutils + +from numpy._core.records import ( + record, + recarray, +) + +from numpy._core.function_base import ( + linspace, + logspace, + geomspace, +) + +from numpy._core.fromnumeric import ( + take, + reshape, + choose, + repeat, + put, + swapaxes, + transpose, + matrix_transpose, + partition, + argpartition, + sort, + argsort, + argmax, + argmin, + searchsorted, + resize, + squeeze, + diagonal, + trace, + ravel, + nonzero, + shape, + compress, + clip, + sum, + all, + any, + cumsum, + cumulative_sum, + ptp, + max, + min, + amax, + amin, + prod, + cumprod, + cumulative_prod, + ndim, + size, + around, + round, + mean, + std, + var, +) + +from numpy._core._asarray import ( + require, +) + +from numpy._core._type_aliases import ( + sctypeDict, +) + +from numpy._core._ufunc_config import ( + seterr, + geterr, + setbufsize, + getbufsize, + seterrcall, + geterrcall, + errstate, +) + +from numpy._core.arrayprint import ( + set_printoptions, + get_printoptions, + array2string, + format_float_scientific, + format_float_positional, + array_repr, + array_str, + printoptions, +) + +from numpy._core.einsumfunc import ( + einsum, + einsum_path, +) +from numpy._core.getlimits import ( + finfo, + iinfo, +) + +from numpy._core.multiarray import ( + array, + empty_like, + empty, + zeros, + concatenate, + inner, + where, + lexsort, + can_cast, + min_scalar_type, + result_type, + dot, + vdot, + bincount, + copyto, + putmask, + packbits, + unpackbits, + shares_memory, + may_share_memory, + asarray, + asanyarray, + ascontiguousarray, + asfortranarray, + arange, + busday_count, + busday_offset, + datetime_as_string, + datetime_data, + frombuffer, + fromfile, + fromiter, + is_busday, + promote_types, + fromstring, + frompyfunc, + nested_iters, + flagsobj, +) + +from numpy._core.numeric import ( + zeros_like, + ones, + ones_like, + full, + full_like, + count_nonzero, + isfortran, + argwhere, + flatnonzero, + correlate, + convolve, + outer, + tensordot, + roll, + rollaxis, + moveaxis, + cross, + indices, + fromfunction, + isscalar, + binary_repr, + base_repr, + identity, + allclose, + isclose, + array_equal, + array_equiv, + astype, +) + +from numpy._core.numerictypes import ( + isdtype, + issubdtype, + ScalarType, + typecodes, +) + +from numpy._core.shape_base import ( + atleast_1d, + atleast_2d, + atleast_3d, + block, + hstack, + stack, + vstack, + unstack, +) + +from ._expired_attrs_2_0 import __expired_attributes__ as __expired_attributes__ +from ._globals import _CopyMode as _CopyMode +from ._globals import _NoValue as _NoValue, _NoValueType + +from numpy.lib import ( + scimath as emath, +) + +from numpy.lib._arraypad_impl import ( + pad, +) + +from numpy.lib._arraysetops_impl import ( + ediff1d, + intersect1d, + isin, + setdiff1d, + setxor1d, + union1d, + unique, + unique_all, + unique_counts, + unique_inverse, + unique_values, +) + +from numpy.lib._function_base_impl import ( # type: ignore[deprecated] + select, + piecewise, + trim_zeros, + copy, + iterable, + percentile, + diff, + gradient, + angle, + unwrap, + sort_complex, + flip, + rot90, + extract, + place, + asarray_chkfinite, + average, + digitize, + cov, + corrcoef, + median, + sinc, + hamming, + hanning, + bartlett, + blackman, + kaiser, + trapezoid, + i0, + meshgrid, + delete, + insert, + append, + interp, + quantile, + vectorize, +) + +from numpy.lib._histograms_impl import ( + histogram_bin_edges, + histogram, + histogramdd, +) + +from numpy.lib._index_tricks_impl import ( + ndenumerate, + ndindex, + ravel_multi_index, + unravel_index, + mgrid, + ogrid, + r_, + c_, + s_, + index_exp, + ix_, + fill_diagonal, + diag_indices, + diag_indices_from, +) + +from numpy.lib._nanfunctions_impl import ( + nansum, + nanmax, + nanmin, + nanargmax, + nanargmin, + nanmean, + nanmedian, + nanpercentile, + nanvar, + nanstd, + nanprod, + nancumsum, + nancumprod, + nanquantile, +) + +from numpy.lib._npyio_impl import ( + savetxt, + loadtxt, + genfromtxt, + load, + save, + savez, + savez_compressed, + fromregex, +) + +from numpy.lib._polynomial_impl import ( + poly, + roots, + polyint, + polyder, + polyadd, + polysub, + polymul, + polydiv, + polyval, + polyfit, +) + +from numpy.lib._shape_base_impl import ( # type: ignore[deprecated] + column_stack, + row_stack, + dstack, + array_split, + split, + hsplit, + vsplit, + dsplit, + apply_over_axes, + expand_dims, + apply_along_axis, + kron, + tile, + take_along_axis, + put_along_axis, +) + +from numpy.lib._stride_tricks_impl import ( + broadcast_to, + broadcast_arrays, + broadcast_shapes, +) + +from numpy.lib._twodim_base_impl import ( + diag, + diagflat, + eye, + fliplr, + flipud, + tri, + triu, + tril, + vander, + histogram2d, + mask_indices, + tril_indices, + tril_indices_from, + triu_indices, + triu_indices_from, +) + +from numpy.lib._type_check_impl import ( + mintypecode, + real, + imag, + iscomplex, + isreal, + iscomplexobj, + isrealobj, + nan_to_num, + real_if_close, + typename, + common_type, +) + +from numpy.lib._ufunclike_impl import ( + fix, + isposinf, + isneginf, +) + +from numpy.lib._utils_impl import ( + get_include, + info, + show_runtime, +) + +from numpy.matrixlib import ( + asmatrix, + bmat, + matrix, +) + +__all__ = [ # noqa: RUF022 + # __numpy_submodules__ + "char", "core", "ctypeslib", "dtypes", "exceptions", "f2py", "fft", "lib", "linalg", + "ma", "polynomial", "random", "rec", "strings", "test", "testing", "typing", + + # _core.__all__ + "abs", "acos", "acosh", "asin", "asinh", "atan", "atanh", "atan2", "bitwise_invert", + "bitwise_left_shift", "bitwise_right_shift", "concat", "pow", "permute_dims", + "memmap", "sctypeDict", "record", "recarray", + + # _core.numeric.__all__ + "newaxis", "ndarray", "flatiter", "nditer", "nested_iters", "ufunc", "arange", + "array", "asarray", "asanyarray", "ascontiguousarray", "asfortranarray", "zeros", + "count_nonzero", "empty", "broadcast", "dtype", "fromstring", "fromfile", + "frombuffer", "from_dlpack", "where", "argwhere", "copyto", "concatenate", + "lexsort", "astype", "can_cast", "promote_types", "min_scalar_type", "result_type", + "isfortran", "empty_like", "zeros_like", "ones_like", "correlate", "convolve", + "inner", "dot", "outer", "vdot", "roll", "rollaxis", "moveaxis", "cross", + "tensordot", "little_endian", "fromiter", "array_equal", "array_equiv", "indices", + "fromfunction", "isclose", "isscalar", "binary_repr", "base_repr", "ones", + "identity", "allclose", "putmask", "flatnonzero", "inf", "nan", "False_", "True_", + "bitwise_not", "full", "full_like", "matmul", "vecdot", "vecmat", + "shares_memory", "may_share_memory", + "all", "amax", "amin", "any", "argmax", "argmin", "argpartition", "argsort", + "around", "choose", "clip", "compress", "cumprod", "cumsum", "cumulative_prod", + "cumulative_sum", "diagonal", "mean", "max", "min", "matrix_transpose", "ndim", + "nonzero", "partition", "prod", "ptp", "put", "ravel", "repeat", "reshape", + "resize", "round", "searchsorted", "shape", "size", "sort", "squeeze", "std", "sum", + "swapaxes", "take", "trace", "transpose", "var", + "absolute", "add", "arccos", "arccosh", "arcsin", "arcsinh", "arctan", "arctan2", + "arctanh", "bitwise_and", "bitwise_or", "bitwise_xor", "cbrt", "ceil", "conj", + "conjugate", "copysign", "cos", "cosh", "bitwise_count", "deg2rad", "degrees", + "divide", "divmod", "e", "equal", "euler_gamma", "exp", "exp2", "expm1", "fabs", + "floor", "floor_divide", "float_power", "fmax", "fmin", "fmod", "frexp", + "frompyfunc", "gcd", "greater", "greater_equal", "heaviside", "hypot", "invert", + "isfinite", "isinf", "isnan", "isnat", "lcm", "ldexp", "left_shift", "less", + "less_equal", "log", "log10", "log1p", "log2", "logaddexp", "logaddexp2", + "logical_and", "logical_not", "logical_or", "logical_xor", "matvec", "maximum", "minimum", + "mod", "modf", "multiply", "negative", "nextafter", "not_equal", "pi", "positive", + "power", "rad2deg", "radians", "reciprocal", "remainder", "right_shift", "rint", + "sign", "signbit", "sin", "sinh", "spacing", "sqrt", "square", "subtract", "tan", + "tanh", "true_divide", "trunc", "ScalarType", "typecodes", "issubdtype", + "datetime_data", "datetime_as_string", "busday_offset", "busday_count", "is_busday", + "busdaycalendar", "isdtype", + "complexfloating", "character", "unsignedinteger", "inexact", "generic", "floating", + "integer", "signedinteger", "number", "flexible", "bool", "float16", "float32", + "float64", "longdouble", "complex64", "complex128", "clongdouble", + "bytes_", "str_", "void", "object_", "datetime64", "timedelta64", "int8", "byte", + "uint8", "ubyte", "int16", "short", "uint16", "ushort", "int32", "intc", "uint32", + "uintc", "int64", "long", "uint64", "ulong", "longlong", "ulonglong", "intp", + "uintp", "double", "cdouble", "single", "csingle", "half", "bool_", "int_", "uint", + "float96", "float128", "complex192", "complex256", + "array2string", "array_str", "array_repr", "set_printoptions", "get_printoptions", + "printoptions", "format_float_positional", "format_float_scientific", "require", + "seterr", "geterr", "setbufsize", "getbufsize", "seterrcall", "geterrcall", + "errstate", + # _core.function_base.__all__ + "logspace", "linspace", "geomspace", + # _core.getlimits.__all__ + "finfo", "iinfo", + # _core.shape_base.__all__ + "atleast_1d", "atleast_2d", "atleast_3d", "block", "hstack", "stack", "unstack", + "vstack", + # _core.einsumfunc.__all__ + "einsum", "einsum_path", + # matrixlib.__all__ + "matrix", "bmat", "asmatrix", + # lib._histograms_impl.__all__ + "histogram", "histogramdd", "histogram_bin_edges", + # lib._nanfunctions_impl.__all__ + "nansum", "nanmax", "nanmin", "nanargmax", "nanargmin", "nanmean", "nanmedian", + "nanpercentile", "nanvar", "nanstd", "nanprod", "nancumsum", "nancumprod", + "nanquantile", + # lib._function_base_impl.__all__ + "select", "piecewise", "trim_zeros", "copy", "iterable", "percentile", "diff", + "gradient", "angle", "unwrap", "sort_complex", "flip", "rot90", "extract", "place", + "vectorize", "asarray_chkfinite", "average", "bincount", "digitize", "cov", + "corrcoef", "median", "sinc", "hamming", "hanning", "bartlett", "blackman", + "kaiser", "trapezoid", "i0", "meshgrid", "delete", "insert", "append", + "interp", "quantile", + # lib._twodim_base_impl.__all__ + "diag", "diagflat", "eye", "fliplr", "flipud", "tri", "triu", "tril", "vander", + "histogram2d", "mask_indices", "tril_indices", "tril_indices_from", "triu_indices", + "triu_indices_from", + # lib._shape_base_impl.__all__ + "column_stack", "dstack", "array_split", "split", "hsplit", "vsplit", "dsplit", + "apply_over_axes", "expand_dims", "apply_along_axis", "kron", "tile", + "take_along_axis", "put_along_axis", "row_stack", + # lib._type_check_impl.__all__ + "iscomplexobj", "isrealobj", "imag", "iscomplex", "isreal", "nan_to_num", "real", + "real_if_close", "typename", "mintypecode", "common_type", + # lib._arraysetops_impl.__all__ + "ediff1d", "intersect1d", "isin", "setdiff1d", "setxor1d", "union1d", + "unique", "unique_all", "unique_counts", "unique_inverse", "unique_values", + # lib._ufunclike_impl.__all__ + "fix", "isneginf", "isposinf", + # lib._arraypad_impl.__all__ + "pad", + # lib._utils_impl.__all__ + "get_include", "info", "show_runtime", + # lib._stride_tricks_impl.__all__ + "broadcast_to", "broadcast_arrays", "broadcast_shapes", + # lib._polynomial_impl.__all__ + "poly", "roots", "polyint", "polyder", "polyadd", "polysub", "polymul", "polydiv", + "polyval", "poly1d", "polyfit", + # lib._npyio_impl.__all__ + "savetxt", "loadtxt", "genfromtxt", "load", "save", "savez", "savez_compressed", + "packbits", "unpackbits", "fromregex", + # lib._index_tricks_impl.__all__ + "ravel_multi_index", "unravel_index", "mgrid", "ogrid", "r_", "c_", "s_", + "index_exp", "ix_", "ndenumerate", "ndindex", "fill_diagonal", "diag_indices", + "diag_indices_from", + + # __init__.__all__ + "emath", "show_config", "__version__", "__array_namespace_info__", +] # fmt: skip + +### Constrained types (for internal use only) +# Only use these for functions; never as generic type parameter. + +_AnyStr = TypeVar("_AnyStr", LiteralString, str, bytes) +_AnyShapeT = TypeVar( + "_AnyShapeT", + tuple[()], # 0-d + tuple[int], # 1-d + tuple[int, int], # 2-d + tuple[int, int, int], # 3-d + tuple[int, int, int, int], # 4-d + tuple[int, int, int, int, int], # 5-d + tuple[int, int, int, int, int, int], # 6-d + tuple[int, int, int, int, int, int, int], # 7-d + tuple[int, int, int, int, int, int, int, int], # 8-d + tuple[int, ...], # N-d +) +_AnyTD64Item = TypeVar("_AnyTD64Item", dt.timedelta, int, None, dt.timedelta | int | None) +_AnyDT64Arg = TypeVar("_AnyDT64Arg", dt.datetime, dt.date, None) +_AnyDT64Item = TypeVar("_AnyDT64Item", dt.datetime, dt.date, int, None, dt.date, int | None) +_AnyDate = TypeVar("_AnyDate", dt.date, dt.datetime) +_AnyDateOrTime = TypeVar("_AnyDateOrTime", dt.date, dt.datetime, dt.timedelta) + +### Type parameters (for internal use only) + +_T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) +_T_contra = TypeVar("_T_contra", contravariant=True) +_RealT_co = TypeVar("_RealT_co", covariant=True) +_ImagT_co = TypeVar("_ImagT_co", covariant=True) + +_DTypeT = TypeVar("_DTypeT", bound=dtype) +_DTypeT_co = TypeVar("_DTypeT_co", bound=dtype, default=dtype, covariant=True) +_FlexDTypeT = TypeVar("_FlexDTypeT", bound=dtype[flexible]) + +_ArrayT = TypeVar("_ArrayT", bound=ndarray) +_ArrayT_co = TypeVar("_ArrayT_co", bound=ndarray, default=ndarray, covariant=True) +_BoolArrayT = TypeVar("_BoolArrayT", bound=NDArray[np.bool]) +_IntegerArrayT = TypeVar("_IntegerArrayT", bound=NDArray[integer]) +_IntegralArrayT = TypeVar("_IntegralArrayT", bound=NDArray[np.bool | integer | object_]) +_FloatingArrayT = TypeVar("_FloatingArrayT", bound=NDArray[floating]) +_FloatingTimedeltaArrayT = TypeVar("_FloatingTimedeltaArrayT", bound=NDArray[floating | timedelta64]) +_ComplexFloatingArrayT = TypeVar("_ComplexFloatingArrayT", bound=NDArray[complexfloating]) +_InexactArrayT = TypeVar("_InexactArrayT", bound=NDArray[inexact]) +_InexactTimedeltaArrayT = TypeVar("_InexactTimedeltaArrayT", bound=NDArray[inexact | timedelta64]) +_NumberArrayT = TypeVar("_NumberArrayT", bound=NDArray[number]) +_NumberCharacterArrayT = TypeVar("_NumberCharacterArrayT", bound=ndarray[Any, dtype[number | character] | dtypes.StringDType]) +_TimedeltaArrayT = TypeVar("_TimedeltaArrayT", bound=NDArray[timedelta64]) +_TimeArrayT = TypeVar("_TimeArrayT", bound=NDArray[datetime64 | timedelta64]) +_ObjectArrayT = TypeVar("_ObjectArrayT", bound=NDArray[object_]) +_BytesArrayT = TypeVar("_BytesArrayT", bound=NDArray[bytes_]) +_StringArrayT = TypeVar("_StringArrayT", bound=ndarray[Any, dtype[str_] | dtypes.StringDType]) +_RealArrayT = TypeVar("_RealArrayT", bound=NDArray[floating | integer | timedelta64 | np.bool | object_]) +_NumericArrayT = TypeVar("_NumericArrayT", bound=NDArray[number | timedelta64 | object_]) + +_ShapeT = TypeVar("_ShapeT", bound=_Shape) +_Shape1T = TypeVar("_Shape1T", bound=tuple[int, *tuple[int, ...]]) +_ShapeT_co = TypeVar("_ShapeT_co", bound=_Shape, default=_AnyShape, covariant=True) +_2DShapeT_co = TypeVar("_2DShapeT_co", bound=_2D, default=_2D, covariant=True) +_1NShapeT = TypeVar("_1NShapeT", bound=tuple[L[1], *tuple[L[1], ...]]) # (1,) | (1, 1) | (1, 1, 1) | ... + +_ScalarT = TypeVar("_ScalarT", bound=generic) +_ScalarT_co = TypeVar("_ScalarT_co", bound=generic, default=Any, covariant=True) +_NumberT = TypeVar("_NumberT", bound=number) +_InexactT = TypeVar("_InexactT", bound=inexact) +_RealNumberT = TypeVar("_RealNumberT", bound=floating | integer) +_IntegerT = TypeVar("_IntegerT", bound=integer) +_NonObjectScalarT = TypeVar("_NonObjectScalarT", bound=np.bool | number | flexible | datetime64 | timedelta64) + +_NBit = TypeVar("_NBit", bound=NBitBase, default=Any) # pyright: ignore[reportDeprecated] +_NBit1 = TypeVar("_NBit1", bound=NBitBase, default=Any) # pyright: ignore[reportDeprecated] +_NBit2 = TypeVar("_NBit2", bound=NBitBase, default=_NBit1) # pyright: ignore[reportDeprecated] + +_ItemT_co = TypeVar("_ItemT_co", default=Any, covariant=True) +_BoolItemT = TypeVar("_BoolItemT", bound=builtins.bool) +_BoolItemT_co = TypeVar("_BoolItemT_co", bound=builtins.bool, default=builtins.bool, covariant=True) +_NumberItemT_co = TypeVar("_NumberItemT_co", bound=complex, default=int | float | complex, covariant=True) +_InexactItemT_co = TypeVar("_InexactItemT_co", bound=complex, default=float | complex, covariant=True) +_FlexibleItemT_co = TypeVar( + "_FlexibleItemT_co", + bound=_CharLike_co | tuple[Any, ...], + default=_CharLike_co | tuple[Any, ...], + covariant=True, +) +_CharacterItemT_co = TypeVar("_CharacterItemT_co", bound=_CharLike_co, default=_CharLike_co, covariant=True) +_TD64ItemT_co = TypeVar("_TD64ItemT_co", bound=dt.timedelta | int | None, default=dt.timedelta | int | None, covariant=True) +_DT64ItemT_co = TypeVar("_DT64ItemT_co", bound=dt.date | int | None, default=dt.date | int | None, covariant=True) +_TD64UnitT = TypeVar("_TD64UnitT", bound=_TD64Unit, default=_TD64Unit) +_BoolOrIntArrayT = TypeVar("_BoolOrIntArrayT", bound=NDArray[integer | np.bool]) + +### Type Aliases (for internal use only) + +_Falsy: TypeAlias = L[False, 0] | np.bool[L[False]] +_Truthy: TypeAlias = L[True, 1] | np.bool[L[True]] + +_1D: TypeAlias = tuple[int] +_2D: TypeAlias = tuple[int, int] +_2Tuple: TypeAlias = tuple[_T, _T] + +_ArrayUInt_co: TypeAlias = NDArray[unsignedinteger | np.bool] +_ArrayInt_co: TypeAlias = NDArray[integer | np.bool] +_ArrayFloat64_co: TypeAlias = NDArray[floating[_64Bit] | float32 | float16 | integer | np.bool] +_ArrayFloat_co: TypeAlias = NDArray[floating | integer | np.bool] +_ArrayComplex128_co: TypeAlias = NDArray[number[_64Bit] | number[_32Bit] | float16 | integer | np.bool] +_ArrayComplex_co: TypeAlias = NDArray[inexact | integer | np.bool] +_ArrayNumber_co: TypeAlias = NDArray[number | np.bool] +_ArrayTD64_co: TypeAlias = NDArray[timedelta64 | integer | np.bool] + +_Float64_co: TypeAlias = float | floating[_64Bit] | float32 | float16 | integer | np.bool +_Complex64_co: TypeAlias = number[_32Bit] | number[_16Bit] | number[_8Bit] | builtins.bool | np.bool +_Complex128_co: TypeAlias = complex | number[_64Bit] | _Complex64_co + +_ToIndex: TypeAlias = SupportsIndex | slice | EllipsisType | _ArrayLikeInt_co | None +_ToIndices: TypeAlias = _ToIndex | tuple[_ToIndex, ...] + +_UnsignedIntegerCType: TypeAlias = type[ + ct.c_uint8 | ct.c_uint16 | ct.c_uint32 | ct.c_uint64 + | ct.c_ushort | ct.c_uint | ct.c_ulong | ct.c_ulonglong + | ct.c_size_t | ct.c_void_p +] # fmt: skip +_SignedIntegerCType: TypeAlias = type[ + ct.c_int8 | ct.c_int16 | ct.c_int32 | ct.c_int64 + | ct.c_short | ct.c_int | ct.c_long | ct.c_longlong + | ct.c_ssize_t +] # fmt: skip +_FloatingCType: TypeAlias = type[ct.c_float | ct.c_double | ct.c_longdouble] +_IntegerCType: TypeAlias = _UnsignedIntegerCType | _SignedIntegerCType + +# some commonly used builtin types that are known to result in a +# `dtype[object_]`, when their *type* is passed to the `dtype` constructor +# NOTE: `builtins.object` should not be included here +_BuiltinObjectLike: TypeAlias = ( + slice | Decimal | Fraction | UUID + | dt.date | dt.time | dt.timedelta | dt.tzinfo + | tuple[Any, ...] | list[Any] | set[Any] | frozenset[Any] | dict[Any, Any] +) # fmt: skip + +# Introduce an alias for `dtype` to avoid naming conflicts. +_dtype: TypeAlias = dtype[_ScalarT] + +_ByteOrderChar: TypeAlias = L["<", ">", "=", "|"] +# can be anything, is case-insensitive, and only the first character matters +_ByteOrder: TypeAlias = L[ + "S", # swap the current order (default) + "<", "L", "little", # little-endian + ">", "B", "big", # big endian + "=", "N", "native", # native order + "|", "I", # ignore +] # fmt: skip +_DTypeKind: TypeAlias = L[ + "b", # boolean + "i", # signed integer + "u", # unsigned integer + "f", # floating-point + "c", # complex floating-point + "m", # timedelta64 + "M", # datetime64 + "O", # python object + "S", # byte-string (fixed-width) + "U", # unicode-string (fixed-width) + "V", # void + "T", # unicode-string (variable-width) +] +_DTypeChar: TypeAlias = L[ + "?", # bool + "b", # byte + "B", # ubyte + "h", # short + "H", # ushort + "i", # intc + "I", # uintc + "l", # long + "L", # ulong + "q", # longlong + "Q", # ulonglong + "e", # half + "f", # single + "d", # double + "g", # longdouble + "F", # csingle + "D", # cdouble + "G", # clongdouble + "O", # object + "S", # bytes_ (S0) + "a", # bytes_ (deprecated) + "U", # str_ + "V", # void + "M", # datetime64 + "m", # timedelta64 + "c", # bytes_ (S1) + "T", # StringDType +] +_DTypeNum: TypeAlias = L[ + 0, # bool + 1, # byte + 2, # ubyte + 3, # short + 4, # ushort + 5, # intc + 6, # uintc + 7, # long + 8, # ulong + 9, # longlong + 10, # ulonglong + 23, # half + 11, # single + 12, # double + 13, # longdouble + 14, # csingle + 15, # cdouble + 16, # clongdouble + 17, # object + 18, # bytes_ + 19, # str_ + 20, # void + 21, # datetime64 + 22, # timedelta64 + 25, # no type + 256, # user-defined + 2056, # StringDType +] +_DTypeBuiltinKind: TypeAlias = L[0, 1, 2] + +_ArrayAPIVersion: TypeAlias = L["2021.12", "2022.12", "2023.12", "2024.12"] + +_CastingKind: TypeAlias = L["no", "equiv", "safe", "same_kind", "same_value", "unsafe"] + +_OrderKACF: TypeAlias = L["K", "A", "C", "F"] | None +_OrderACF: TypeAlias = L["A", "C", "F"] | None +_OrderCF: TypeAlias = L["C", "F"] | None # noqa: PYI047 + +_ModeKind: TypeAlias = L["raise", "wrap", "clip"] +_PartitionKind: TypeAlias = L["introselect"] +# in practice, only the first case-insensitive character is considered (so e.g. +# "QuantumSort3000" will be interpreted as quicksort). +_SortKind: TypeAlias = L[ + "Q", "quick", "quicksort", + "M", "merge", "mergesort", + "H", "heap", "heapsort", + "S", "stable", "stablesort", +] +_SortSide: TypeAlias = L["left", "right"] + +_ConvertibleToInt: TypeAlias = SupportsInt | SupportsIndex | _CharLike_co +_ConvertibleToFloat: TypeAlias = SupportsFloat | SupportsIndex | _CharLike_co +_ConvertibleToComplex: TypeAlias = SupportsComplex | SupportsFloat | SupportsIndex | _CharLike_co +_ConvertibleToTD64: TypeAlias = dt.timedelta | int | _CharLike_co | character | number | timedelta64 | np.bool | None +_ConvertibleToDT64: TypeAlias = dt.date | int | _CharLike_co | character | number | datetime64 | np.bool | None + +_NDIterFlagsKind: TypeAlias = L[ + "buffered", + "c_index", + "copy_if_overlap", + "common_dtype", + "delay_bufalloc", + "external_loop", + "f_index", + "grow_inner", "growinner", + "multi_index", + "ranged", + "refs_ok", + "reduce_ok", + "zerosize_ok", +] +_NDIterFlagsOp: TypeAlias = L[ + "aligned", + "allocate", + "arraymask", + "copy", + "config", + "nbo", + "no_subtype", + "no_broadcast", + "overlap_assume_elementwise", + "readonly", + "readwrite", + "updateifcopy", + "virtual", + "writeonly", + "writemasked", +] + +_MemMapModeKind: TypeAlias = L[ + "readonly", "r", + "copyonwrite", "c", + "readwrite", "r+", + "write", "w+", +] + +_DT64Date: TypeAlias = _HasDateAttributes | L["TODAY", "today", b"TODAY", b"today"] +_DT64Now: TypeAlias = L["NOW", "now", b"NOW", b"now"] +_NaTValue: TypeAlias = L["NAT", "NaT", "nat", b"NAT", b"NaT", b"nat"] + +_MonthUnit: TypeAlias = L["Y", "M", b"Y", b"M"] +_DayUnit: TypeAlias = L["W", "D", b"W", b"D"] +_DateUnit: TypeAlias = L[_MonthUnit, _DayUnit] +_NativeTimeUnit: TypeAlias = L["h", "m", "s", "ms", "us", "μs", b"h", b"m", b"s", b"ms", b"us"] +_IntTimeUnit: TypeAlias = L["ns", "ps", "fs", "as", b"ns", b"ps", b"fs", b"as"] +_TimeUnit: TypeAlias = L[_NativeTimeUnit, _IntTimeUnit] +_NativeTD64Unit: TypeAlias = L[_DayUnit, _NativeTimeUnit] +_IntTD64Unit: TypeAlias = L[_MonthUnit, _IntTimeUnit] +_TD64Unit: TypeAlias = L[_DateUnit, _TimeUnit] +_TimeUnitSpec: TypeAlias = _TD64UnitT | tuple[_TD64UnitT, SupportsIndex] + +### TypedDict's (for internal use only) + +@type_check_only +class _FormerAttrsDict(TypedDict): + object: LiteralString + float: LiteralString + complex: LiteralString + str: LiteralString + int: LiteralString + +### Protocols (for internal use only) + +@final +@type_check_only +class _SupportsLT(Protocol): + def __lt__(self, other: Any, /) -> Any: ... + +@final +@type_check_only +class _SupportsLE(Protocol): + def __le__(self, other: Any, /) -> Any: ... + +@final +@type_check_only +class _SupportsGT(Protocol): + def __gt__(self, other: Any, /) -> Any: ... + +@final +@type_check_only +class _SupportsGE(Protocol): + def __ge__(self, other: Any, /) -> Any: ... + +@type_check_only +class _SupportsFileMethods(SupportsFlush, Protocol): + # Protocol for representing file-like-objects accepted by `ndarray.tofile` and `fromfile` + def fileno(self) -> SupportsIndex: ... + def tell(self) -> SupportsIndex: ... + def seek(self, offset: int, whence: int, /) -> object: ... + +@type_check_only +class _SupportsFileMethodsRW(SupportsWrite[bytes], _SupportsFileMethods, Protocol): ... + +@type_check_only +class _SupportsDLPack(Protocol[_T_contra]): + def __dlpack__(self, /, *, stream: _T_contra | None = None) -> CapsuleType: ... + +@type_check_only +class _HasDType(Protocol[_T_co]): + @property + def dtype(self, /) -> _T_co: ... + +@type_check_only +class _HasRealAndImag(Protocol[_RealT_co, _ImagT_co]): + @property + def real(self, /) -> _RealT_co: ... + @property + def imag(self, /) -> _ImagT_co: ... + +@type_check_only +class _HasTypeWithRealAndImag(Protocol[_RealT_co, _ImagT_co]): + @property + def type(self, /) -> type[_HasRealAndImag[_RealT_co, _ImagT_co]]: ... + +@type_check_only +class _HasDTypeWithRealAndImag(Protocol[_RealT_co, _ImagT_co]): + @property + def dtype(self, /) -> _HasTypeWithRealAndImag[_RealT_co, _ImagT_co]: ... + +@type_check_only +class _HasDateAttributes(Protocol): + # The `datetime64` constructors requires an object with the three attributes below, + # and thus supports datetime duck typing + @property + def day(self) -> int: ... + @property + def month(self) -> int: ... + @property + def year(self) -> int: ... + +### Mixins (for internal use only) + +@type_check_only +class _RealMixin: + @property + def real(self) -> Self: ... + @property + def imag(self) -> Self: ... + +@type_check_only +class _RoundMixin: + @overload + def __round__(self, /, ndigits: None = None) -> int: ... + @overload + def __round__(self, /, ndigits: SupportsIndex) -> Self: ... + +@type_check_only +class _IntegralMixin(_RealMixin): + @property + def numerator(self) -> Self: ... + @property + def denominator(self) -> L[1]: ... + + def is_integer(self, /) -> L[True]: ... + +### Public API + +__version__: Final[LiteralString] = ... + +e: Final[float] = ... +euler_gamma: Final[float] = ... +pi: Final[float] = ... +inf: Final[float] = ... +nan: Final[float] = ... +little_endian: Final[builtins.bool] = ... +False_: Final[np.bool[L[False]]] = ... +True_: Final[np.bool[L[True]]] = ... +newaxis: Final[None] = None + +# not in __all__ +__NUMPY_SETUP__: Final[L[False]] = False +__numpy_submodules__: Final[set[LiteralString]] = ... +__former_attrs__: Final[_FormerAttrsDict] = ... +__future_scalars__: Final[set[L["bytes", "str", "object"]]] = ... +__array_api_version__: Final[L["2024.12"]] = "2024.12" +test: Final[PytestTester] = ... + +@type_check_only +class _DTypeMeta(type): + @property + def type(cls, /) -> type[generic] | None: ... + @property + def _abstract(cls, /) -> bool: ... + @property + def _is_numeric(cls, /) -> bool: ... + @property + def _parametric(cls, /) -> bool: ... + @property + def _legacy(cls, /) -> bool: ... + +@final +class dtype(Generic[_ScalarT_co], metaclass=_DTypeMeta): + names: tuple[builtins.str, ...] | None + def __hash__(self) -> int: ... + + # `None` results in the default dtype + @overload + def __new__( + cls, + dtype: type[float64 | ct.c_double] | _Float64Codes | _DoubleCodes | None, + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ... + ) -> dtype[float64]: ... + + # Overload for `dtype` instances, scalar types, and instances that have a + # `dtype: dtype[_ScalarT]` attribute + @overload + def __new__( + cls, + dtype: _DTypeLike[_ScalarT], + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[_ScalarT]: ... + + # Builtin types + # + # NOTE: Typecheckers act as if `bool <: int <: float <: complex <: object`, + # even though at runtime `int`, `float`, and `complex` aren't subtypes.. + # This makes it impossible to express e.g. "a float that isn't an int", + # since type checkers treat `_: float` like `_: float | int`. + # + # For more details, see: + # - https://github.com/numpy/numpy/issues/27032#issuecomment-2278958251 + # - https://typing.readthedocs.io/en/latest/spec/special-types.html#special-cases-for-float-and-complex + @overload + def __new__( + cls, + dtype: type[builtins.bool | np.bool | ct.c_bool] | _BoolCodes, + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[str, Any] = ..., + ) -> dtype[np.bool]: ... + @overload + def __new__( + cls, + dtype: type[int], # also accepts `type[builtins.bool]` + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[str, Any] = ..., + ) -> dtype[int_ | np.bool]: ... + @overload + def __new__( + cls, + dtype: type[float], # also accepts `type[int | bool]` + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[str, Any] = ..., + ) -> dtype[float64 | int_ | np.bool]: ... + @overload + def __new__( + cls, + dtype: type[complex], # also accepts `type[float | int | bool]` + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[str, Any] = ..., + ) -> dtype[complex128 | float64 | int_ | np.bool]: ... + @overload + def __new__( + cls, + dtype: type[bytes | ct.c_char] | _BytesCodes, + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[str, Any] = ..., + ) -> dtype[bytes_]: ... + @overload + def __new__( + cls, + dtype: type[str] | _StrCodes, + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[str, Any] = ..., + ) -> dtype[str_]: ... + # NOTE: These `memoryview` overloads assume PEP 688, which requires mypy to + # be run with the (undocumented) `--disable-memoryview-promotion` flag, + # This will be the default in a future mypy release, see: + # https://github.com/python/mypy/issues/15313 + # Pyright / Pylance requires setting `disableBytesTypePromotions=true`, + # which is the default in strict mode + @overload + def __new__( + cls, + dtype: type[void | memoryview] | _VoidDTypeLike | _VoidCodes, + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[str, Any] = ..., + ) -> dtype[void]: ... + # NOTE: `_: type[object]` would also accept e.g. `type[object | complex]`, + # and is therefore not included here + @overload + def __new__( + cls, + dtype: type[object_ | _BuiltinObjectLike | ct.py_object[Any]] | _ObjectCodes, + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[str, Any] = ..., + ) -> dtype[object_]: ... + + # `unsignedinteger` string-based representations and ctypes + @overload + def __new__( + cls, + dtype: _UInt8Codes | _UByteCodes | type[ct.c_uint8 | ct.c_ubyte], + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[uint8]: ... + @overload + def __new__( + cls, + dtype: _UInt16Codes | _UShortCodes | type[ct.c_uint16 | ct.c_ushort], + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[uint16]: ... + @overload + def __new__( + cls, + dtype: _UInt32Codes | _UIntCCodes | type[ct.c_uint32 | ct.c_uint], + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[uint32]: ... + @overload + def __new__( + cls, + dtype: _UInt64Codes | _ULongLongCodes | type[ct.c_uint64 | ct.c_ulonglong], + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[uint64]: ... + @overload + def __new__( + cls, + dtype: _UIntPCodes | type[ct.c_void_p | ct.c_size_t], + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[uintp]: ... + @overload + def __new__( + cls, + dtype: _ULongCodes | type[ct.c_ulong], + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[ulong]: ... + + # `signedinteger` string-based representations and ctypes + @overload + def __new__( + cls, + dtype: _Int8Codes | _ByteCodes | type[ct.c_int8 | ct.c_byte], + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[int8]: ... + @overload + def __new__( + cls, + dtype: _Int16Codes | _ShortCodes | type[ct.c_int16 | ct.c_short], + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[int16]: ... + @overload + def __new__( + cls, + dtype: _Int32Codes | _IntCCodes | type[ct.c_int32 | ct.c_int], + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[int32]: ... + @overload + def __new__( + cls, + dtype: _Int64Codes | _LongLongCodes | type[ct.c_int64 | ct.c_longlong], + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[int64]: ... + @overload + def __new__( + cls, + dtype: _IntPCodes | type[intp | ct.c_ssize_t], + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[intp]: ... + @overload + def __new__( + cls, + dtype: _LongCodes | type[ct.c_long], + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[long]: ... + + # `floating` string-based representations and ctypes + @overload + def __new__( + cls, + dtype: _Float16Codes | _HalfCodes, + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[float16]: ... + @overload + def __new__( + cls, + dtype: _Float32Codes | _SingleCodes, + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[float32]: ... + # float64 codes are covered by overload 1 + @overload + def __new__( + cls, + dtype: _LongDoubleCodes | type[ct.c_longdouble], + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[longdouble]: ... + + # `complexfloating` string-based representations + @overload + def __new__( + cls, + dtype: _Complex64Codes | _CSingleCodes, + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[complex64]: ... + @overload + def __new__( + cls, + dtype: _Complex128Codes | _CDoubleCodes, + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[complex128]: ... + @overload + def __new__( + cls, + dtype: _CLongDoubleCodes, + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[clongdouble]: ... + + # Miscellaneous string-based representations and ctypes + @overload + def __new__( + cls, + dtype: _TD64Codes, + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[timedelta64]: ... + @overload + def __new__( + cls, + dtype: _DT64Codes, + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[datetime64]: ... + + # `StringDType` requires special treatment because it has no scalar type + @overload + def __new__( + cls, + dtype: dtypes.StringDType | _StringCodes, + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtypes.StringDType: ... + + # Combined char-codes and ctypes, analogous to the scalar-type hierarchy + @overload + def __new__( + cls, + dtype: _UnsignedIntegerCodes | _UnsignedIntegerCType, + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[unsignedinteger]: ... + @overload + def __new__( + cls, + dtype: _SignedIntegerCodes | _SignedIntegerCType, + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[signedinteger]: ... + @overload + def __new__( + cls, + dtype: _IntegerCodes | _IntegerCType, + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[integer]: ... + @overload + def __new__( + cls, + dtype: _FloatingCodes | _FloatingCType, + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[floating]: ... + @overload + def __new__( + cls, + dtype: _ComplexFloatingCodes, + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[complexfloating]: ... + @overload + def __new__( + cls, + dtype: _InexactCodes | _FloatingCType, + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[inexact]: ... + @overload + def __new__( + cls, + dtype: _CharacterCodes | type[bytes | builtins.str | ct.c_char], + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[str, Any] = ..., + ) -> dtype[character]: ... + + # Handle strings that can't be expressed as literals; i.e. "S1", "S2", ... + @overload + def __new__( + cls, + dtype: builtins.str, + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype: ... + + # Catch-all overload for object-likes + # NOTE: `object_ | Any` is NOT equivalent to `Any`. It is specified to behave + # like a "sum type" (a.k.a. variant type, discriminated union, or tagged union). + # So the union of a type and `Any` is not the same "union type" that all other + # unions are (by definition). + # https://typing.python.org/en/latest/spec/concepts.html#union-types + @overload + def __new__( + cls, + dtype: type[object], + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[object_ | Any]: ... + + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + + @overload + def __getitem__(self: dtype[void], key: list[builtins.str], /) -> dtype[void]: ... + @overload + def __getitem__(self: dtype[void], key: builtins.str | SupportsIndex, /) -> dtype: ... + + # NOTE: In the future 1-based multiplications will also yield `flexible` dtypes + @overload + def __mul__(self: _DTypeT, value: L[1], /) -> _DTypeT: ... + @overload + def __mul__(self: _FlexDTypeT, value: SupportsIndex, /) -> _FlexDTypeT: ... + @overload + def __mul__(self, value: SupportsIndex, /) -> dtype[void]: ... + + # NOTE: `__rmul__` seems to be broken when used in combination with + # literals as of mypy 0.902. Set the return-type to `dtype` for + # now for non-flexible dtypes. + @overload + def __rmul__(self: _FlexDTypeT, value: SupportsIndex, /) -> _FlexDTypeT: ... + @overload + def __rmul__(self, value: SupportsIndex, /) -> dtype: ... + + def __gt__(self, other: DTypeLike | None, /) -> builtins.bool: ... + def __ge__(self, other: DTypeLike | None, /) -> builtins.bool: ... + def __lt__(self, other: DTypeLike | None, /) -> builtins.bool: ... + def __le__(self, other: DTypeLike | None, /) -> builtins.bool: ... + + # Explicitly defined `__eq__` and `__ne__` to get around mypy's + # `strict_equality` option; even though their signatures are + # identical to their `object`-based counterpart + def __eq__(self, other: Any, /) -> builtins.bool: ... + def __ne__(self, other: Any, /) -> builtins.bool: ... + + @property + def alignment(self) -> int: ... + @property + def base(self) -> dtype: ... + @property + def byteorder(self) -> _ByteOrderChar: ... + @property + def char(self) -> _DTypeChar: ... + @property + def descr(self) -> list[tuple[LiteralString, LiteralString] | tuple[LiteralString, LiteralString, _Shape]]: ... + @property + def fields(self,) -> MappingProxyType[LiteralString, tuple[dtype, int] | tuple[dtype, int, Any]] | None: ... + @property + def flags(self) -> int: ... + @property + def hasobject(self) -> builtins.bool: ... + @property + def isbuiltin(self) -> _DTypeBuiltinKind: ... + @property + def isnative(self) -> builtins.bool: ... + @property + def isalignedstruct(self) -> builtins.bool: ... + @property + def itemsize(self) -> int: ... + @property + def kind(self) -> _DTypeKind: ... + @property + def metadata(self) -> MappingProxyType[builtins.str, Any] | None: ... + @property + def name(self) -> LiteralString: ... + @property + def num(self) -> _DTypeNum: ... + @property + def shape(self) -> _AnyShape: ... + @property + def ndim(self) -> int: ... + @property + def subdtype(self) -> tuple[dtype, _AnyShape] | None: ... + def newbyteorder(self, new_order: _ByteOrder = ..., /) -> Self: ... + @property + def str(self) -> LiteralString: ... + @property + def type(self) -> type[_ScalarT_co]: ... + +@final +class flatiter(Generic[_ArrayT_co]): + __hash__: ClassVar[None] = None # type: ignore[assignment] # pyright: ignore[reportIncompatibleMethodOverride] + + @property + def base(self, /) -> _ArrayT_co: ... + @property + def coords(self: flatiter[ndarray[_ShapeT]], /) -> _ShapeT: ... + @property + def index(self, /) -> int: ... + + # iteration + def __len__(self, /) -> int: ... + def __iter__(self, /) -> Self: ... + def __next__(self: flatiter[NDArray[_ScalarT]], /) -> _ScalarT: ... + + # indexing + @overload # nd: _[()] + def __getitem__(self, key: tuple[()], /) -> _ArrayT_co: ... + @overload # 0d; _[] + def __getitem__(self: flatiter[NDArray[_ScalarT]], key: int | integer, /) -> _ScalarT: ... + @overload # 1d; _[[*]], _[:], _[...] + def __getitem__( + self: flatiter[ndarray[Any, _DTypeT]], + key: list[int] | slice | EllipsisType | flatiter[NDArray[integer]], + /, + ) -> ndarray[tuple[int], _DTypeT]: ... + @overload # 2d; _[[*[*]]] + def __getitem__( + self: flatiter[ndarray[Any, _DTypeT]], + key: list[list[int]], + /, + ) -> ndarray[tuple[int, int], _DTypeT]: ... + @overload # ?d + def __getitem__( + self: flatiter[ndarray[Any, _DTypeT]], + key: NDArray[integer] | _NestedSequence[int], + /, + ) -> ndarray[_AnyShape, _DTypeT]: ... + + # NOTE: `__setitem__` operates via `unsafe` casting rules, and can thus accept any + # type accepted by the relevant underlying `np.generic` constructor, which isn't + # known statically. So we cannot meaningfully annotate the value parameter. + def __setitem__(self, key: slice | EllipsisType | _ArrayLikeInt, val: object, /) -> None: ... + + # NOTE: `dtype` and `copy` are no-ops at runtime, so we don't support them here to + # avoid confusion + def __array__( + self: flatiter[ndarray[Any, _DTypeT]], + dtype: None = None, + /, + *, + copy: None = None, + ) -> ndarray[tuple[int], _DTypeT]: ... + + # This returns a flat copy of the underlying array, not of the iterator itself + def copy(self: flatiter[ndarray[Any, _DTypeT]], /) -> ndarray[tuple[int], _DTypeT]: ... + +@type_check_only +class _ArrayOrScalarCommon: + @property + def real(self, /) -> Any: ... + @property + def imag(self, /) -> Any: ... + @property + def T(self) -> Self: ... + @property + def mT(self) -> Self: ... + @property + def data(self) -> memoryview: ... + @property + def flags(self) -> flagsobj: ... + @property + def itemsize(self) -> int: ... + @property + def nbytes(self) -> int: ... + @property + def device(self) -> L["cpu"]: ... + + def __bool__(self, /) -> builtins.bool: ... + def __int__(self, /) -> int: ... + def __float__(self, /) -> float: ... + def __copy__(self) -> Self: ... + def __deepcopy__(self, memo: dict[int, Any] | None, /) -> Self: ... + + # TODO: How to deal with the non-commutative nature of `==` and `!=`? + # xref numpy/numpy#17368 + def __eq__(self, other: Any, /) -> Any: ... + def __ne__(self, other: Any, /) -> Any: ... + + def copy(self, order: _OrderKACF = ...) -> Self: ... + def dump(self, file: StrOrBytesPath | SupportsWrite[bytes]) -> None: ... + def dumps(self) -> bytes: ... + def tobytes(self, order: _OrderKACF = ...) -> bytes: ... + def tofile(self, fid: StrOrBytesPath | _SupportsFileMethods, /, sep: str = "", format: str = "%s") -> None: ... + # generics and 0d arrays return builtin scalars + def tolist(self) -> Any: ... + def to_device(self, device: L["cpu"], /, *, stream: int | Any | None = ...) -> Self: ... + + # NOTE: for `generic`, these two methods don't do anything + def fill(self, /, value: Incomplete) -> None: ... + def put(self, indices: _ArrayLikeInt_co, values: ArrayLike, /, mode: _ModeKind = "raise") -> None: ... + + # NOTE: even on `generic` this seems to work + def setflags( + self, + /, + *, + write: builtins.bool | None = None, + align: builtins.bool | None = None, + uic: builtins.bool | None = None, + ) -> None: ... + + @property + def __array_interface__(self) -> dict[str, Any]: ... + @property + def __array_priority__(self) -> float: ... + @property + def __array_struct__(self) -> CapsuleType: ... # builtins.PyCapsule + def __array_namespace__(self, /, *, api_version: _ArrayAPIVersion | None = None) -> ModuleType: ... + def __setstate__(self, state: tuple[ + SupportsIndex, # version + _ShapeLike, # Shape + _DTypeT_co, # DType + np.bool, # F-continuous + bytes | list[Any], # Data + ], /) -> None: ... + + def conj(self) -> Self: ... + def conjugate(self) -> Self: ... + + def argsort( + self, + axis: SupportsIndex | None = ..., + kind: _SortKind | None = ..., + order: str | Sequence[str] | None = ..., + *, + stable: builtins.bool | None = ..., + ) -> NDArray[intp]: ... + + @overload # axis=None (default), out=None (default), keepdims=False (default) + def argmax(self, /, axis: None = None, out: None = None, *, keepdims: L[False] = False) -> intp: ... + @overload # axis=index, out=None (default) + def argmax(self, /, axis: SupportsIndex, out: None = None, *, keepdims: builtins.bool = False) -> Any: ... + @overload # axis=index, out=ndarray + def argmax(self, /, axis: SupportsIndex | None, out: _BoolOrIntArrayT, *, keepdims: builtins.bool = False) -> _BoolOrIntArrayT: ... + @overload + def argmax(self, /, axis: SupportsIndex | None = None, *, out: _BoolOrIntArrayT, keepdims: builtins.bool = False) -> _BoolOrIntArrayT: ... + + @overload # axis=None (default), out=None (default), keepdims=False (default) + def argmin(self, /, axis: None = None, out: None = None, *, keepdims: L[False] = False) -> intp: ... + @overload # axis=index, out=None (default) + def argmin(self, /, axis: SupportsIndex, out: None = None, *, keepdims: builtins.bool = False) -> Any: ... + @overload # axis=index, out=ndarray + def argmin(self, /, axis: SupportsIndex | None, out: _BoolOrIntArrayT, *, keepdims: builtins.bool = False) -> _BoolOrIntArrayT: ... + @overload + def argmin(self, /, axis: SupportsIndex | None = None, *, out: _BoolOrIntArrayT, keepdims: builtins.bool = False) -> _BoolOrIntArrayT: ... + + # Keep in sync with `MaskedArray.round` + @overload # out=None (default) + def round(self, /, decimals: SupportsIndex = 0, out: None = None) -> Self: ... + @overload # out=ndarray + def round(self, /, decimals: SupportsIndex, out: _ArrayT) -> _ArrayT: ... + @overload + def round(self, /, decimals: SupportsIndex = 0, *, out: _ArrayT) -> _ArrayT: ... + + @overload # out=None (default) + def choose(self, /, choices: ArrayLike, out: None = None, mode: _ModeKind = "raise") -> NDArray[Any]: ... + @overload # out=ndarray + def choose(self, /, choices: ArrayLike, out: _ArrayT, mode: _ModeKind = "raise") -> _ArrayT: ... + + # TODO: Annotate kwargs with an unpacked `TypedDict` + @overload # out: None (default) + def clip(self, /, min: ArrayLike, max: ArrayLike | None = None, out: None = None, **kwargs: Any) -> NDArray[Any]: ... + @overload + def clip(self, /, min: None, max: ArrayLike, out: None = None, **kwargs: Any) -> NDArray[Any]: ... + @overload + def clip(self, /, min: None = None, *, max: ArrayLike, out: None = None, **kwargs: Any) -> NDArray[Any]: ... + @overload # out: ndarray + def clip(self, /, min: ArrayLike, max: ArrayLike | None, out: _ArrayT, **kwargs: Any) -> _ArrayT: ... + @overload + def clip(self, /, min: ArrayLike, max: ArrayLike | None = None, *, out: _ArrayT, **kwargs: Any) -> _ArrayT: ... + @overload + def clip(self, /, min: None, max: ArrayLike, out: _ArrayT, **kwargs: Any) -> _ArrayT: ... + @overload + def clip(self, /, min: None = None, *, max: ArrayLike, out: _ArrayT, **kwargs: Any) -> _ArrayT: ... + + @overload + def compress(self, /, condition: _ArrayLikeInt_co, axis: SupportsIndex | None = None, out: None = None) -> NDArray[Any]: ... + @overload + def compress(self, /, condition: _ArrayLikeInt_co, axis: SupportsIndex | None, out: _ArrayT) -> _ArrayT: ... + @overload + def compress(self, /, condition: _ArrayLikeInt_co, axis: SupportsIndex | None = None, *, out: _ArrayT) -> _ArrayT: ... + + # Keep in sync with `MaskedArray.cumprod` + @overload # out: None (default) + def cumprod(self, /, axis: SupportsIndex | None = None, dtype: DTypeLike | None = None, out: None = None) -> NDArray[Any]: ... + @overload # out: ndarray + def cumprod(self, /, axis: SupportsIndex | None, dtype: DTypeLike | None, out: _ArrayT) -> _ArrayT: ... + @overload + def cumprod(self, /, axis: SupportsIndex | None = None, dtype: DTypeLike | None = None, *, out: _ArrayT) -> _ArrayT: ... + + # Keep in sync with `MaskedArray.cumsum` + @overload # out: None (default) + def cumsum(self, /, axis: SupportsIndex | None = None, dtype: DTypeLike | None = None, out: None = None) -> NDArray[Any]: ... + @overload # out: ndarray + def cumsum(self, /, axis: SupportsIndex | None, dtype: DTypeLike | None, out: _ArrayT) -> _ArrayT: ... + @overload + def cumsum(self, /, axis: SupportsIndex | None = None, dtype: DTypeLike | None = None, *, out: _ArrayT) -> _ArrayT: ... + + @overload + def max( + self, + /, + axis: _ShapeLike | None = None, + out: None = None, + *, + keepdims: builtins.bool | _NoValueType = ..., + initial: _NumberLike_co | _NoValueType = ..., + where: _ArrayLikeBool_co | _NoValueType = ..., + ) -> Any: ... + @overload + def max( + self, + /, + axis: _ShapeLike | None, + out: _ArrayT, + *, + keepdims: builtins.bool | _NoValueType = ..., + initial: _NumberLike_co | _NoValueType = ..., + where: _ArrayLikeBool_co | _NoValueType = ..., + ) -> _ArrayT: ... + @overload + def max( + self, + /, + axis: _ShapeLike | None = None, + *, + out: _ArrayT, + keepdims: builtins.bool | _NoValueType = ..., + initial: _NumberLike_co | _NoValueType = ..., + where: _ArrayLikeBool_co | _NoValueType = ..., + ) -> _ArrayT: ... + + @overload + def min( + self, + /, + axis: _ShapeLike | None = None, + out: None = None, + *, + keepdims: builtins.bool | _NoValueType = ..., + initial: _NumberLike_co | _NoValueType = ..., + where: _ArrayLikeBool_co | _NoValueType = ..., + ) -> Any: ... + @overload + def min( + self, + /, + axis: _ShapeLike | None, + out: _ArrayT, + *, + keepdims: builtins.bool | _NoValueType = ..., + initial: _NumberLike_co | _NoValueType = ..., + where: _ArrayLikeBool_co | _NoValueType = ..., + ) -> _ArrayT: ... + @overload + def min( + self, + /, + axis: _ShapeLike | None = None, + *, + out: _ArrayT, + keepdims: builtins.bool | _NoValueType = ..., + initial: _NumberLike_co | _NoValueType = ..., + where: _ArrayLikeBool_co | _NoValueType = ..., + ) -> _ArrayT: ... + + @overload + def sum( + self, + /, + axis: _ShapeLike | None = None, + dtype: DTypeLike | None = None, + out: None = None, + *, + keepdims: builtins.bool | _NoValueType = ..., + initial: _NumberLike_co | _NoValueType = ..., + where: _ArrayLikeBool_co | _NoValueType = ..., + ) -> Any: ... + @overload + def sum( + self, + /, + axis: _ShapeLike | None, + dtype: DTypeLike | None, + out: _ArrayT, + *, + keepdims: builtins.bool | _NoValueType = ..., + initial: _NumberLike_co | _NoValueType = ..., + where: _ArrayLikeBool_co | _NoValueType = ..., + ) -> _ArrayT: ... + @overload + def sum( + self, + /, + axis: _ShapeLike | None = None, + dtype: DTypeLike | None = None, + *, + out: _ArrayT, + keepdims: builtins.bool | _NoValueType = ..., + initial: _NumberLike_co | _NoValueType = ..., + where: _ArrayLikeBool_co | _NoValueType = ..., + ) -> _ArrayT: ... + + @overload + def prod( + self, + /, + axis: _ShapeLike | None = None, + dtype: DTypeLike | None = None, + out: None = None, + *, + keepdims: builtins.bool | _NoValueType = ..., + initial: _NumberLike_co | _NoValueType = ..., + where: _ArrayLikeBool_co | _NoValueType = ..., + ) -> Any: ... + @overload + def prod( + self, + /, + axis: _ShapeLike | None, + dtype: DTypeLike | None, + out: _ArrayT, + *, + keepdims: builtins.bool | _NoValueType = ..., + initial: _NumberLike_co | _NoValueType = ..., + where: _ArrayLikeBool_co | _NoValueType = ..., + ) -> _ArrayT: ... + @overload + def prod( + self, + /, + axis: _ShapeLike | None = None, + dtype: DTypeLike | None = None, + *, + out: _ArrayT, + keepdims: builtins.bool | _NoValueType = ..., + initial: _NumberLike_co | _NoValueType = ..., + where: _ArrayLikeBool_co | _NoValueType = ..., + ) -> _ArrayT: ... + + @overload + def mean( + self, + axis: _ShapeLike | None = None, + dtype: DTypeLike | None = None, + out: None = None, + *, + keepdims: builtins.bool | _NoValueType = ..., + where: _ArrayLikeBool_co | _NoValueType = ..., + ) -> Any: ... + @overload + def mean( + self, + /, + axis: _ShapeLike | None, + dtype: DTypeLike | None, + out: _ArrayT, + *, + keepdims: builtins.bool | _NoValueType = ..., + where: _ArrayLikeBool_co | _NoValueType = ..., + ) -> _ArrayT: ... + @overload + def mean( + self, + /, + axis: _ShapeLike | None = None, + dtype: DTypeLike | None = None, + *, + out: _ArrayT, + keepdims: builtins.bool | _NoValueType = ..., + where: _ArrayLikeBool_co | _NoValueType = ..., + ) -> _ArrayT: ... + + @overload + def std( + self, + axis: _ShapeLike | None = None, + dtype: DTypeLike | None = None, + out: None = None, + ddof: float = 0, + *, + keepdims: builtins.bool | _NoValueType = ..., + where: _ArrayLikeBool_co | _NoValueType = ..., + mean: _ArrayLikeNumber_co | _NoValueType = ..., + correction: float | _NoValueType = ..., + ) -> Any: ... + @overload + def std( + self, + axis: _ShapeLike | None, + dtype: DTypeLike | None, + out: _ArrayT, + ddof: float = 0, + *, + keepdims: builtins.bool | _NoValueType = ..., + where: _ArrayLikeBool_co | _NoValueType = ..., + mean: _ArrayLikeNumber_co | _NoValueType = ..., + correction: float | _NoValueType = ..., + ) -> _ArrayT: ... + @overload + def std( + self, + axis: _ShapeLike | None = None, + dtype: DTypeLike | None = None, + *, + out: _ArrayT, + ddof: float = 0, + keepdims: builtins.bool | _NoValueType = ..., + where: _ArrayLikeBool_co | _NoValueType = ..., + mean: _ArrayLikeNumber_co | _NoValueType = ..., + correction: float | _NoValueType = ..., + ) -> _ArrayT: ... + + @overload + def var( + self, + axis: _ShapeLike | None = None, + dtype: DTypeLike | None = None, + out: None = None, + ddof: float = 0, + *, + keepdims: builtins.bool | _NoValueType = ..., + where: _ArrayLikeBool_co | _NoValueType = ..., + mean: _ArrayLikeNumber_co | _NoValueType = ..., + correction: float | _NoValueType = ..., + ) -> Any: ... + @overload + def var( + self, + axis: _ShapeLike | None, + dtype: DTypeLike | None, + out: _ArrayT, + ddof: float = 0, + *, + keepdims: builtins.bool | _NoValueType = ..., + where: _ArrayLikeBool_co | _NoValueType = ..., + mean: _ArrayLikeNumber_co | _NoValueType = ..., + correction: float | _NoValueType = ..., + ) -> _ArrayT: ... + @overload + def var( + self, + axis: _ShapeLike | None = None, + dtype: DTypeLike | None = None, + *, + out: _ArrayT, + ddof: float = 0, + keepdims: builtins.bool | _NoValueType = ..., + where: _ArrayLikeBool_co | _NoValueType = ..., + mean: _ArrayLikeNumber_co | _NoValueType = ..., + correction: float | _NoValueType = ..., + ) -> _ArrayT: ... + +class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]): + __hash__: ClassVar[None] # type: ignore[assignment] # pyright: ignore[reportIncompatibleMethodOverride] + @property + def base(self) -> NDArray[Any] | None: ... + @property + def ndim(self) -> int: ... + @property + def size(self) -> int: ... + @property + def real(self: _HasDTypeWithRealAndImag[_ScalarT, object], /) -> ndarray[_ShapeT_co, dtype[_ScalarT]]: ... + @real.setter + def real(self, value: ArrayLike, /) -> None: ... + @property + def imag(self: _HasDTypeWithRealAndImag[object, _ScalarT], /) -> ndarray[_ShapeT_co, dtype[_ScalarT]]: ... + @imag.setter + def imag(self, value: ArrayLike, /) -> None: ... + + def __new__( + cls, + shape: _ShapeLike, + dtype: DTypeLike | None = ..., + buffer: _SupportsBuffer | None = ..., + offset: SupportsIndex = ..., + strides: _ShapeLike | None = ..., + order: _OrderKACF = ..., + ) -> Self: ... + + if sys.version_info >= (3, 12): + def __buffer__(self, flags: int, /) -> memoryview: ... + + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + + @overload + def __array__(self, dtype: None = None, /, *, copy: builtins.bool | None = None) -> ndarray[_ShapeT_co, _DTypeT_co]: ... + @overload + def __array__(self, dtype: _DTypeT, /, *, copy: builtins.bool | None = None) -> ndarray[_ShapeT_co, _DTypeT]: ... + + def __array_ufunc__( + self, + ufunc: ufunc, + method: L["__call__", "reduce", "reduceat", "accumulate", "outer", "at"], + *inputs: Any, + **kwargs: Any, + ) -> Any: ... + + def __array_function__( + self, + func: Callable[..., Any], + types: Iterable[type], + args: Iterable[Any], + kwargs: Mapping[str, Any], + ) -> Any: ... + + # NOTE: In practice any object is accepted by `obj`, but as `__array_finalize__` + # is a pseudo-abstract method the type has been narrowed down in order to + # grant subclasses a bit more flexibility + def __array_finalize__(self, obj: NDArray[Any] | None, /) -> None: ... + + def __array_wrap__( + self, + array: ndarray[_ShapeT, _DTypeT], + context: tuple[ufunc, tuple[Any, ...], int] | None = ..., + return_scalar: builtins.bool = ..., + /, + ) -> ndarray[_ShapeT, _DTypeT]: ... + + # Keep in sync with `MaskedArray.__getitem__` + @overload + def __getitem__(self, key: _ArrayInt_co | tuple[_ArrayInt_co, ...], /) -> ndarray[_AnyShape, _DTypeT_co]: ... + @overload + def __getitem__(self, key: SupportsIndex | tuple[SupportsIndex, ...], /) -> Any: ... + @overload + def __getitem__(self, key: _ToIndices, /) -> ndarray[_AnyShape, _DTypeT_co]: ... + @overload # can be of any shape + def __getitem__(self: NDArray[void], key: str, /) -> ndarray[_ShapeT_co | _AnyShape]: ... + @overload + def __getitem__(self: NDArray[void], key: list[str], /) -> ndarray[_ShapeT_co | _AnyShape, dtype[void]]: ... + + @overload # flexible | object_ | bool + def __setitem__( + self: ndarray[Any, dtype[flexible | object_ | np.bool] | dtypes.StringDType], + key: _ToIndices, + value: object, + /, + ) -> None: ... + @overload # integer + def __setitem__( + self: NDArray[integer], + key: _ToIndices, + value: _ConvertibleToInt | _NestedSequence[_ConvertibleToInt] | _ArrayLikeInt_co, + /, + ) -> None: ... + @overload # floating + def __setitem__( + self: NDArray[floating], + key: _ToIndices, + value: _ConvertibleToFloat | _NestedSequence[_ConvertibleToFloat | None] | _ArrayLikeFloat_co | None, + /, + ) -> None: ... + @overload # complexfloating + def __setitem__( + self: NDArray[complexfloating], + key: _ToIndices, + value: _ConvertibleToComplex | _NestedSequence[_ConvertibleToComplex | None] | _ArrayLikeNumber_co | None, + /, + ) -> None: ... + @overload # timedelta64 + def __setitem__( + self: NDArray[timedelta64], + key: _ToIndices, + value: _ConvertibleToTD64 | _NestedSequence[_ConvertibleToTD64], + /, + ) -> None: ... + @overload # datetime64 + def __setitem__( + self: NDArray[datetime64], + key: _ToIndices, + value: _ConvertibleToDT64 | _NestedSequence[_ConvertibleToDT64], + /, + ) -> None: ... + @overload # void + def __setitem__(self: NDArray[void], key: str | list[str], value: object, /) -> None: ... + @overload # catch-all + def __setitem__(self, key: _ToIndices, value: ArrayLike, /) -> None: ... + + @property + def ctypes(self) -> _ctypes[int]: ... + + # + @property + def shape(self) -> _ShapeT_co: ... + @shape.setter + @deprecated("In-place shape modification will be deprecated in NumPy 2.5.", category=PendingDeprecationWarning) + def shape(self, value: _ShapeLike) -> None: ... + + # + @property + def strides(self) -> _Shape: ... + @strides.setter + @deprecated("Setting the strides on a NumPy array has been deprecated in NumPy 2.4") + def strides(self, value: _ShapeLike) -> None: ... + + # + def byteswap(self, inplace: builtins.bool = ...) -> Self: ... + @property + def flat(self) -> flatiter[Self]: ... + + @overload # use the same output type as that of the underlying `generic` + def item(self: NDArray[generic[_T]], i0: SupportsIndex | tuple[SupportsIndex, ...] = ..., /, *args: SupportsIndex) -> _T: ... + @overload # special casing for `StringDType`, which has no scalar type + def item( + self: ndarray[Any, dtypes.StringDType], + arg0: SupportsIndex | tuple[SupportsIndex, ...] = ..., + /, + *args: SupportsIndex, + ) -> str: ... + + # keep in sync with `ma.MaskedArray.tolist` + @overload # this first overload prevents mypy from over-eagerly selecting `tuple[()]` in case of `_AnyShape` + def tolist(self: ndarray[tuple[Never], dtype[generic[_T]]], /) -> Any: ... + @overload + def tolist(self: ndarray[tuple[()], dtype[generic[_T]]], /) -> _T: ... + @overload + def tolist(self: ndarray[tuple[int], dtype[generic[_T]]], /) -> list[_T]: ... + @overload + def tolist(self: ndarray[tuple[int, int], dtype[generic[_T]]], /) -> list[list[_T]]: ... + @overload + def tolist(self: ndarray[tuple[int, int, int], dtype[generic[_T]]], /) -> list[list[list[_T]]]: ... + @overload + def tolist(self, /) -> Any: ... + + @overload + def resize(self, new_shape: _ShapeLike, /, *, refcheck: builtins.bool = True) -> None: ... + @overload + def resize(self, /, *new_shape: SupportsIndex, refcheck: builtins.bool = True) -> None: ... + + # keep in sync with `ma.MaskedArray.squeeze` + def squeeze( + self, + /, + axis: SupportsIndex | tuple[SupportsIndex, ...] | None = ..., + ) -> ndarray[_AnyShape, _DTypeT_co]: ... + + def swapaxes(self, axis1: SupportsIndex, axis2: SupportsIndex, /) -> Self: ... + + @overload + def transpose(self, axes: _ShapeLike | None, /) -> Self: ... + @overload + def transpose(self, /, *axes: SupportsIndex) -> Self: ... + + @overload + def all( + self, + axis: None = None, + out: None = None, + keepdims: L[False, 0] = False, + *, + where: _ArrayLikeBool_co = True + ) -> np.bool: ... + @overload + def all( + self, + axis: int | tuple[int, ...] | None = None, + out: None = None, + keepdims: SupportsIndex = False, + *, + where: _ArrayLikeBool_co = True, + ) -> np.bool | NDArray[np.bool]: ... + @overload + def all( + self, + axis: int | tuple[int, ...] | None, + out: _ArrayT, + keepdims: SupportsIndex = False, + *, + where: _ArrayLikeBool_co = True, + ) -> _ArrayT: ... + @overload + def all( + self, + axis: int | tuple[int, ...] | None = None, + *, + out: _ArrayT, + keepdims: SupportsIndex = False, + where: _ArrayLikeBool_co = True, + ) -> _ArrayT: ... + + @overload + def any( + self, + axis: None = None, + out: None = None, + keepdims: L[False, 0] = False, + *, + where: _ArrayLikeBool_co = True + ) -> np.bool: ... + @overload + def any( + self, + axis: int | tuple[int, ...] | None = None, + out: None = None, + keepdims: SupportsIndex = False, + *, + where: _ArrayLikeBool_co = True, + ) -> np.bool | NDArray[np.bool]: ... + @overload + def any( + self, + axis: int | tuple[int, ...] | None, + out: _ArrayT, + keepdims: SupportsIndex = False, + *, + where: _ArrayLikeBool_co = True, + ) -> _ArrayT: ... + @overload + def any( + self, + axis: int | tuple[int, ...] | None = None, + *, + out: _ArrayT, + keepdims: SupportsIndex = False, + where: _ArrayLikeBool_co = True, + ) -> _ArrayT: ... + + # + @overload + def partition( + self, + kth: _ArrayLikeInt, + /, + axis: SupportsIndex = -1, + kind: _PartitionKind = "introselect", + order: None = None, + ) -> None: ... + @overload + def partition( + self: NDArray[void], + kth: _ArrayLikeInt, + /, + axis: SupportsIndex = -1, + kind: _PartitionKind = "introselect", + order: str | Sequence[str] | None = None, + ) -> None: ... + + # + @overload + def argpartition( + self, + kth: _ArrayLikeInt, + /, + axis: SupportsIndex | None = -1, + kind: _PartitionKind = "introselect", + order: None = None, + ) -> NDArray[intp]: ... + @overload + def argpartition( + self: NDArray[void], + kth: _ArrayLikeInt, + /, + axis: SupportsIndex | None = -1, + kind: _PartitionKind = "introselect", + order: str | Sequence[str] | None = None, + ) -> NDArray[intp]: ... + + # keep in sync with `ma.MaskedArray.diagonal` + def diagonal( + self, + offset: SupportsIndex = 0, + axis1: SupportsIndex = 0, + axis2: SupportsIndex = 1, + ) -> ndarray[_AnyShape, _DTypeT_co]: ... + + # 1D + 1D returns a scalar; + # all other with at least 1 non-0D array return an ndarray. + @overload + def dot(self, b: _ScalarLike_co, /, out: None = None) -> NDArray[Any]: ... + @overload + def dot(self, b: ArrayLike, /, out: None = None) -> Any: ... + @overload + def dot(self, b: ArrayLike, /, out: _ArrayT) -> _ArrayT: ... + + # `nonzero()` raises for 0d arrays/generics + def nonzero(self) -> tuple[ndarray[tuple[int], np.dtype[intp]], ...]: ... + + @overload + def searchsorted( + self, # >= 1D array + v: _ScalarLike_co, # 0D array-like + /, + side: _SortSide = "left", + sorter: _ArrayLikeInt_co | None = None, + ) -> intp: ... + @overload + def searchsorted( + self, # >= 1D array + v: ArrayLike, + /, + side: _SortSide = "left", + sorter: _ArrayLikeInt_co | None = None, + ) -> NDArray[intp]: ... + + def sort( + self, + /, + axis: SupportsIndex = -1, + kind: _SortKind | None = None, + order: str | Sequence[str] | None = None, + *, + stable: builtins.bool | None = None, + ) -> None: ... + + # Keep in sync with `MaskedArray.trace` + @overload + def trace( + self, # >= 2D array + /, + offset: SupportsIndex = 0, + axis1: SupportsIndex = 0, + axis2: SupportsIndex = 1, + dtype: DTypeLike | None = None, + out: None = None, + ) -> Any: ... + @overload + def trace( + self, # >= 2D array + /, + offset: SupportsIndex = 0, + axis1: SupportsIndex = 0, + axis2: SupportsIndex = 1, + dtype: DTypeLike | None = None, + *, + out: _ArrayT, + ) -> _ArrayT: ... + @overload + def trace( + self, # >= 2D array + /, + offset: SupportsIndex, + axis1: SupportsIndex, + axis2: SupportsIndex, + dtype: DTypeLike | None, + out: _ArrayT, + ) -> _ArrayT: ... + + @overload + def take( + self: NDArray[_ScalarT], + indices: _IntLike_co, + /, + axis: SupportsIndex | None = ..., + out: None = None, + mode: _ModeKind = ..., + ) -> _ScalarT: ... + @overload + def take( + self, + indices: _ArrayLikeInt_co, + /, + axis: SupportsIndex | None = ..., + out: None = None, + mode: _ModeKind = ..., + ) -> ndarray[_AnyShape, _DTypeT_co]: ... + @overload + def take( + self, + indices: _ArrayLikeInt_co, + /, + axis: SupportsIndex | None = ..., + *, + out: _ArrayT, + mode: _ModeKind = ..., + ) -> _ArrayT: ... + @overload + def take( + self, + indices: _ArrayLikeInt_co, + /, + axis: SupportsIndex | None, + out: _ArrayT, + mode: _ModeKind = ..., + ) -> _ArrayT: ... + + # keep in sync with `ma.MaskedArray.repeat` + @overload + def repeat(self, repeats: _ArrayLikeInt_co, /, axis: None = None) -> ndarray[tuple[int], _DTypeT_co]: ... + @overload + def repeat(self, repeats: _ArrayLikeInt_co, /, axis: SupportsIndex) -> ndarray[_AnyShape, _DTypeT_co]: ... + + # keep in sync with `ma.MaskedArray.flatten` and `ma.MaskedArray.ravel` + def flatten(self, /, order: _OrderKACF = "C") -> ndarray[tuple[int], _DTypeT_co]: ... + def ravel(self, /, order: _OrderKACF = "C") -> ndarray[tuple[int], _DTypeT_co]: ... + + # Keep in sync with `MaskedArray.reshape` + # NOTE: reshape also accepts negative integers, so we can't use integer literals + @overload # (None) + def reshape(self, shape: None, /, *, order: _OrderACF = "C", copy: builtins.bool | None = None) -> Self: ... + @overload # (empty_sequence) + def reshape( # type: ignore[overload-overlap] # mypy false positive + self, + shape: Sequence[Never], + /, + *, + order: _OrderACF = "C", + copy: builtins.bool | None = None, + ) -> ndarray[tuple[()], _DTypeT_co]: ... + @overload # (() | (int) | (int, int) | ....) # up to 8-d + def reshape( + self, + shape: _AnyShapeT, + /, + *, + order: _OrderACF = "C", + copy: builtins.bool | None = None, + ) -> ndarray[_AnyShapeT, _DTypeT_co]: ... + @overload # (index) + def reshape( + self, + size1: SupportsIndex, + /, + *, + order: _OrderACF = "C", + copy: builtins.bool | None = None, + ) -> ndarray[tuple[int], _DTypeT_co]: ... + @overload # (index, index) + def reshape( + self, + size1: SupportsIndex, + size2: SupportsIndex, + /, + *, + order: _OrderACF = "C", + copy: builtins.bool | None = None, + ) -> ndarray[tuple[int, int], _DTypeT_co]: ... + @overload # (index, index, index) + def reshape( + self, + size1: SupportsIndex, + size2: SupportsIndex, + size3: SupportsIndex, + /, + *, + order: _OrderACF = "C", + copy: builtins.bool | None = None, + ) -> ndarray[tuple[int, int, int], _DTypeT_co]: ... + @overload # (index, index, index, index) + def reshape( + self, + size1: SupportsIndex, + size2: SupportsIndex, + size3: SupportsIndex, + size4: SupportsIndex, + /, + *, + order: _OrderACF = "C", + copy: builtins.bool | None = None, + ) -> ndarray[tuple[int, int, int, int], _DTypeT_co]: ... + @overload # (int, *(index, ...)) + def reshape( + self, + size0: SupportsIndex, + /, + *shape: SupportsIndex, + order: _OrderACF = "C", + copy: builtins.bool | None = None, + ) -> ndarray[_AnyShape, _DTypeT_co]: ... + @overload # (sequence[index]) + def reshape( + self, + shape: Sequence[SupportsIndex], + /, + *, + order: _OrderACF = "C", + copy: builtins.bool | None = None, + ) -> ndarray[_AnyShape, _DTypeT_co]: ... + + @overload + def astype( + self, + dtype: _DTypeLike[_ScalarT], + order: _OrderKACF = ..., + casting: _CastingKind = ..., + subok: builtins.bool = ..., + copy: builtins.bool | _CopyMode = ..., + ) -> ndarray[_ShapeT_co, dtype[_ScalarT]]: ... + @overload + def astype( + self, + dtype: DTypeLike | None, + order: _OrderKACF = ..., + casting: _CastingKind = ..., + subok: builtins.bool = ..., + copy: builtins.bool | _CopyMode = ..., + ) -> ndarray[_ShapeT_co, dtype]: ... + + # + @overload # () + def view(self, /) -> Self: ... + @overload # (dtype: T) + def view(self, /, dtype: _DTypeT | _HasDType[_DTypeT]) -> ndarray[_ShapeT_co, _DTypeT]: ... + @overload # (dtype: dtype[T]) + def view(self, /, dtype: _DTypeLike[_ScalarT]) -> ndarray[_ShapeT_co, dtype[_ScalarT]]: ... + @overload # (type: T) + def view(self, /, *, type: type[_ArrayT]) -> _ArrayT: ... + @overload # (_: T) + def view(self, /, dtype: type[_ArrayT]) -> _ArrayT: ... + @overload # (dtype: ?) + def view(self, /, dtype: DTypeLike) -> ndarray[_ShapeT_co, dtype]: ... + @overload # (dtype: ?, type: T) + def view(self, /, dtype: DTypeLike, type: type[_ArrayT]) -> _ArrayT: ... + + def setfield(self, val: ArrayLike, /, dtype: DTypeLike, offset: SupportsIndex = 0) -> None: ... + @overload + def getfield(self, /, dtype: _DTypeLike[_ScalarT], offset: SupportsIndex = 0) -> NDArray[_ScalarT]: ... + @overload + def getfield(self, /, dtype: DTypeLike, offset: SupportsIndex = 0) -> NDArray[Any]: ... + + def __index__(self: NDArray[integer], /) -> int: ... + def __complex__(self: NDArray[number | np.bool | object_], /) -> complex: ... + + def __len__(self) -> int: ... + def __contains__(self, value: object, /) -> builtins.bool: ... + + # NOTE: This weird `Never` tuple works around a strange mypy issue where it assigns + # `tuple[int]` to `tuple[Never]` or `tuple[int, int]` to `tuple[Never, Never]`. + # This way the bug only occurs for 9-D arrays, which are probably not very common. + @overload + def __iter__( + self: ndarray[tuple[Never, Never, Never, Never, Never, Never, Never, Never, Never], Any], / + ) -> Iterator[Any]: ... + @overload # == 1-d & dtype[T \ object_] + def __iter__(self: ndarray[tuple[int], dtype[_NonObjectScalarT]], /) -> Iterator[_NonObjectScalarT]: ... + @overload # == 1-d & StringDType + def __iter__(self: ndarray[tuple[int], dtypes.StringDType], /) -> Iterator[str]: ... + @overload # >= 2-d + def __iter__(self: ndarray[tuple[int, int, *tuple[int, ...]], _DTypeT], /) -> Iterator[ndarray[_AnyShape, _DTypeT]]: ... + @overload # ?-d + def __iter__(self, /) -> Iterator[Any]: ... + + # + @overload + def __lt__(self: _ArrayNumber_co, other: _ArrayLikeNumber_co, /) -> NDArray[np.bool]: ... + @overload + def __lt__(self: _ArrayTD64_co, other: _ArrayLikeTD64_co, /) -> NDArray[np.bool]: ... + @overload + def __lt__(self: NDArray[datetime64], other: _ArrayLikeDT64_co, /) -> NDArray[np.bool]: ... + @overload + def __lt__(self: NDArray[bytes_], other: _ArrayLikeBytes_co, /) -> NDArray[np.bool]: ... + @overload + def __lt__( + self: ndarray[Any, dtype[str_] | dtypes.StringDType], other: _ArrayLikeStr_co | _ArrayLikeString_co, / + ) -> NDArray[np.bool]: ... + @overload + def __lt__(self: NDArray[object_], other: object, /) -> NDArray[np.bool]: ... + @overload + def __lt__(self, other: _ArrayLikeObject_co, /) -> NDArray[np.bool]: ... + + # + @overload + def __le__(self: _ArrayNumber_co, other: _ArrayLikeNumber_co, /) -> NDArray[np.bool]: ... + @overload + def __le__(self: _ArrayTD64_co, other: _ArrayLikeTD64_co, /) -> NDArray[np.bool]: ... + @overload + def __le__(self: NDArray[datetime64], other: _ArrayLikeDT64_co, /) -> NDArray[np.bool]: ... + @overload + def __le__(self: NDArray[bytes_], other: _ArrayLikeBytes_co, /) -> NDArray[np.bool]: ... + @overload + def __le__( + self: ndarray[Any, dtype[str_] | dtypes.StringDType], other: _ArrayLikeStr_co | _ArrayLikeString_co, / + ) -> NDArray[np.bool]: ... + @overload + def __le__(self: NDArray[object_], other: object, /) -> NDArray[np.bool]: ... + @overload + def __le__(self, other: _ArrayLikeObject_co, /) -> NDArray[np.bool]: ... + + # + @overload + def __gt__(self: _ArrayNumber_co, other: _ArrayLikeNumber_co, /) -> NDArray[np.bool]: ... + @overload + def __gt__(self: _ArrayTD64_co, other: _ArrayLikeTD64_co, /) -> NDArray[np.bool]: ... + @overload + def __gt__(self: NDArray[datetime64], other: _ArrayLikeDT64_co, /) -> NDArray[np.bool]: ... + @overload + def __gt__(self: NDArray[bytes_], other: _ArrayLikeBytes_co, /) -> NDArray[np.bool]: ... + @overload + def __gt__( + self: ndarray[Any, dtype[str_] | dtypes.StringDType], other: _ArrayLikeStr_co | _ArrayLikeString_co, / + ) -> NDArray[np.bool]: ... + @overload + def __gt__(self: NDArray[object_], other: object, /) -> NDArray[np.bool]: ... + @overload + def __gt__(self, other: _ArrayLikeObject_co, /) -> NDArray[np.bool]: ... + + # + @overload + def __ge__(self: _ArrayNumber_co, other: _ArrayLikeNumber_co, /) -> NDArray[np.bool]: ... + @overload + def __ge__(self: _ArrayTD64_co, other: _ArrayLikeTD64_co, /) -> NDArray[np.bool]: ... + @overload + def __ge__(self: NDArray[datetime64], other: _ArrayLikeDT64_co, /) -> NDArray[np.bool]: ... + @overload + def __ge__(self: NDArray[bytes_], other: _ArrayLikeBytes_co, /) -> NDArray[np.bool]: ... + @overload + def __ge__( + self: ndarray[Any, dtype[str_] | dtypes.StringDType], other: _ArrayLikeStr_co | _ArrayLikeString_co, / + ) -> NDArray[np.bool]: ... + @overload + def __ge__(self: NDArray[object_], other: object, /) -> NDArray[np.bool]: ... + @overload + def __ge__(self, other: _ArrayLikeObject_co, /) -> NDArray[np.bool]: ... + + # Unary ops + + # TODO: Uncomment once https://github.com/python/mypy/issues/14070 is fixed + # @overload + # def __abs__(self: ndarray[_ShapeT, dtypes.Complex64DType], /) -> ndarray[_ShapeT, dtypes.Float32DType]: ... + # @overload + # def __abs__(self: ndarray[_ShapeT, dtypes.Complex128DType], /) -> ndarray[_ShapeT, dtypes.Float64DType]: ... + # @overload + # def __abs__(self: ndarray[_ShapeT, dtypes.CLongDoubleDType], /) -> ndarray[_ShapeT, dtypes.LongDoubleDType]: ... + # @overload + # def __abs__(self: ndarray[_ShapeT, dtype[complex128]], /) -> ndarray[_ShapeT, dtype[float64]]: ... + @overload + def __abs__(self: ndarray[_ShapeT, dtype[complexfloating[_NBit]]], /) -> ndarray[_ShapeT, dtype[floating[_NBit]]]: ... + @overload + def __abs__(self: _RealArrayT, /) -> _RealArrayT: ... + + def __invert__(self: _IntegralArrayT, /) -> _IntegralArrayT: ... # noqa: PYI019 + def __neg__(self: _NumericArrayT, /) -> _NumericArrayT: ... # noqa: PYI019 + def __pos__(self: _NumericArrayT, /) -> _NumericArrayT: ... # noqa: PYI019 + + # Binary ops + + # TODO: Support the "1d @ 1d -> scalar" case + @overload + def __matmul__(self: NDArray[_NumberT], other: _ArrayLikeBool_co, /) -> NDArray[_NumberT]: ... + @overload + def __matmul__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[np.bool]: ... # type: ignore[overload-overlap] + @overload + def __matmul__(self: NDArray[np.bool], other: _ArrayLike[_NumberT], /) -> NDArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __matmul__(self: NDArray[floating[_64Bit]], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ... + @overload + def __matmul__(self: _ArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], /) -> NDArray[float64]: ... + @overload + def __matmul__(self: NDArray[complexfloating[_64Bit]], other: _ArrayLikeComplex128_co, /) -> NDArray[complex128]: ... + @overload + def __matmul__(self: _ArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], /) -> NDArray[complex128]: ... + @overload + def __matmul__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __matmul__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ... # type: ignore[overload-overlap] + @overload + def __matmul__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co, /) -> NDArray[floating]: ... # type: ignore[overload-overlap] + @overload + def __matmul__(self: _ArrayComplex_co, other: _ArrayLikeComplex_co, /) -> NDArray[complexfloating]: ... + @overload + def __matmul__(self: NDArray[number], other: _ArrayLikeNumber_co, /) -> NDArray[number]: ... + @overload + def __matmul__(self: NDArray[object_], other: Any, /) -> Any: ... + @overload + def __matmul__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + @overload # signature equivalent to __matmul__ + def __rmatmul__(self: NDArray[_NumberT], other: _ArrayLikeBool_co, /) -> NDArray[_NumberT]: ... + @overload + def __rmatmul__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[np.bool]: ... # type: ignore[overload-overlap] + @overload + def __rmatmul__(self: NDArray[np.bool], other: _ArrayLike[_NumberT], /) -> NDArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __rmatmul__(self: NDArray[floating[_64Bit]], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ... + @overload + def __rmatmul__(self: _ArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], /) -> NDArray[float64]: ... + @overload + def __rmatmul__(self: NDArray[complexfloating[_64Bit]], other: _ArrayLikeComplex128_co, /) -> NDArray[complex128]: ... + @overload + def __rmatmul__(self: _ArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], /) -> NDArray[complex128]: ... + @overload + def __rmatmul__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __rmatmul__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ... # type: ignore[overload-overlap] + @overload + def __rmatmul__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co, /) -> NDArray[floating]: ... # type: ignore[overload-overlap] + @overload + def __rmatmul__(self: _ArrayComplex_co, other: _ArrayLikeComplex_co, /) -> NDArray[complexfloating]: ... + @overload + def __rmatmul__(self: NDArray[number], other: _ArrayLikeNumber_co, /) -> NDArray[number]: ... + @overload + def __rmatmul__(self: NDArray[object_], other: Any, /) -> Any: ... + @overload + def __rmatmul__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + @overload + def __mod__(self: NDArray[_RealNumberT], other: int | np.bool, /) -> ndarray[_ShapeT_co, dtype[_RealNumberT]]: ... + @overload + def __mod__(self: NDArray[_RealNumberT], other: _ArrayLikeBool_co, /) -> NDArray[_RealNumberT]: ... # type: ignore[overload-overlap] + @overload + def __mod__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[int8]: ... # type: ignore[overload-overlap] + @overload + def __mod__(self: NDArray[np.bool], other: _ArrayLike[_RealNumberT], /) -> NDArray[_RealNumberT]: ... # type: ignore[overload-overlap] + @overload + def __mod__(self: NDArray[float64], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ... + @overload + def __mod__(self: _ArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], /) -> NDArray[float64]: ... + @overload + def __mod__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __mod__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ... # type: ignore[overload-overlap] + @overload + def __mod__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co, /) -> NDArray[floating]: ... + @overload + def __mod__(self: NDArray[timedelta64], other: _ArrayLike[timedelta64], /) -> NDArray[timedelta64]: ... + @overload + def __mod__(self: NDArray[object_], other: Any, /) -> Any: ... + @overload + def __mod__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + @overload # signature equivalent to __mod__ + def __rmod__(self: NDArray[_RealNumberT], other: int | np.bool, /) -> ndarray[_ShapeT_co, dtype[_RealNumberT]]: ... + @overload + def __rmod__(self: NDArray[_RealNumberT], other: _ArrayLikeBool_co, /) -> NDArray[_RealNumberT]: ... # type: ignore[overload-overlap] + @overload + def __rmod__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[int8]: ... # type: ignore[overload-overlap] + @overload + def __rmod__(self: NDArray[np.bool], other: _ArrayLike[_RealNumberT], /) -> NDArray[_RealNumberT]: ... # type: ignore[overload-overlap] + @overload + def __rmod__(self: NDArray[float64], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ... + @overload + def __rmod__(self: _ArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], /) -> NDArray[float64]: ... + @overload + def __rmod__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __rmod__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ... # type: ignore[overload-overlap] + @overload + def __rmod__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co, /) -> NDArray[floating]: ... + @overload + def __rmod__(self: NDArray[timedelta64], other: _ArrayLike[timedelta64], /) -> NDArray[timedelta64]: ... + @overload + def __rmod__(self: NDArray[object_], other: Any, /) -> Any: ... + @overload + def __rmod__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + @overload + def __divmod__(self: NDArray[_RealNumberT], rhs: int | np.bool, /) -> _2Tuple[ndarray[_ShapeT_co, dtype[_RealNumberT]]]: ... + @overload + def __divmod__(self: NDArray[_RealNumberT], rhs: _ArrayLikeBool_co, /) -> _2Tuple[NDArray[_RealNumberT]]: ... # type: ignore[overload-overlap] + @overload + def __divmod__(self: NDArray[np.bool], rhs: _ArrayLikeBool_co, /) -> _2Tuple[NDArray[int8]]: ... # type: ignore[overload-overlap] + @overload + def __divmod__(self: NDArray[np.bool], rhs: _ArrayLike[_RealNumberT], /) -> _2Tuple[NDArray[_RealNumberT]]: ... # type: ignore[overload-overlap] + @overload + def __divmod__(self: NDArray[float64], rhs: _ArrayLikeFloat64_co, /) -> _2Tuple[NDArray[float64]]: ... + @overload + def __divmod__(self: _ArrayFloat64_co, rhs: _ArrayLike[floating[_64Bit]], /) -> _2Tuple[NDArray[float64]]: ... + @overload + def __divmod__(self: _ArrayUInt_co, rhs: _ArrayLikeUInt_co, /) -> _2Tuple[NDArray[unsignedinteger]]: ... # type: ignore[overload-overlap] + @overload + def __divmod__(self: _ArrayInt_co, rhs: _ArrayLikeInt_co, /) -> _2Tuple[NDArray[signedinteger]]: ... # type: ignore[overload-overlap] + @overload + def __divmod__(self: _ArrayFloat_co, rhs: _ArrayLikeFloat_co, /) -> _2Tuple[NDArray[floating]]: ... + @overload + def __divmod__(self: NDArray[timedelta64], rhs: _ArrayLike[timedelta64], /) -> tuple[NDArray[int64], NDArray[timedelta64]]: ... + + @overload # signature equivalent to __divmod__ + def __rdivmod__(self: NDArray[_RealNumberT], lhs: int | np.bool, /) -> _2Tuple[ndarray[_ShapeT_co, dtype[_RealNumberT]]]: ... + @overload + def __rdivmod__(self: NDArray[_RealNumberT], lhs: _ArrayLikeBool_co, /) -> _2Tuple[NDArray[_RealNumberT]]: ... # type: ignore[overload-overlap] + @overload + def __rdivmod__(self: NDArray[np.bool], lhs: _ArrayLikeBool_co, /) -> _2Tuple[NDArray[int8]]: ... # type: ignore[overload-overlap] + @overload + def __rdivmod__(self: NDArray[np.bool], lhs: _ArrayLike[_RealNumberT], /) -> _2Tuple[NDArray[_RealNumberT]]: ... # type: ignore[overload-overlap] + @overload + def __rdivmod__(self: NDArray[float64], lhs: _ArrayLikeFloat64_co, /) -> _2Tuple[NDArray[float64]]: ... + @overload + def __rdivmod__(self: _ArrayFloat64_co, lhs: _ArrayLike[floating[_64Bit]], /) -> _2Tuple[NDArray[float64]]: ... + @overload + def __rdivmod__(self: _ArrayUInt_co, lhs: _ArrayLikeUInt_co, /) -> _2Tuple[NDArray[unsignedinteger]]: ... # type: ignore[overload-overlap] + @overload + def __rdivmod__(self: _ArrayInt_co, lhs: _ArrayLikeInt_co, /) -> _2Tuple[NDArray[signedinteger]]: ... # type: ignore[overload-overlap] + @overload + def __rdivmod__(self: _ArrayFloat_co, lhs: _ArrayLikeFloat_co, /) -> _2Tuple[NDArray[floating]]: ... + @overload + def __rdivmod__(self: NDArray[timedelta64], lhs: _ArrayLike[timedelta64], /) -> tuple[NDArray[int64], NDArray[timedelta64]]: ... + + # Keep in sync with `MaskedArray.__add__` + @overload + def __add__(self: NDArray[_NumberT], other: int | np.bool, /) -> ndarray[_ShapeT_co, dtype[_NumberT]]: ... + @overload + def __add__(self: NDArray[_NumberT], other: _ArrayLikeBool_co, /) -> NDArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __add__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[np.bool]: ... # type: ignore[overload-overlap] + @overload + def __add__(self: NDArray[np.bool], other: _ArrayLike[_NumberT], /) -> NDArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __add__(self: NDArray[float64], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ... + @overload + def __add__(self: _ArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], /) -> NDArray[float64]: ... + @overload + def __add__(self: NDArray[complex128], other: _ArrayLikeComplex128_co, /) -> NDArray[complex128]: ... + @overload + def __add__(self: _ArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], /) -> NDArray[complex128]: ... + @overload + def __add__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __add__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ... # type: ignore[overload-overlap] + @overload + def __add__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co, /) -> NDArray[floating]: ... # type: ignore[overload-overlap] + @overload + def __add__(self: _ArrayComplex_co, other: _ArrayLikeComplex_co, /) -> NDArray[complexfloating]: ... # type: ignore[overload-overlap] + @overload + def __add__(self: NDArray[number], other: _ArrayLikeNumber_co, /) -> NDArray[number]: ... # type: ignore[overload-overlap] + @overload + def __add__(self: _ArrayTD64_co, other: _ArrayLikeTD64_co, /) -> NDArray[timedelta64]: ... + @overload + def __add__(self: _ArrayTD64_co, other: _ArrayLikeDT64_co, /) -> NDArray[datetime64]: ... + @overload + def __add__(self: NDArray[datetime64], other: _ArrayLikeTD64_co, /) -> NDArray[datetime64]: ... + @overload + def __add__(self: NDArray[bytes_], other: _ArrayLikeBytes_co, /) -> NDArray[bytes_]: ... + @overload + def __add__(self: NDArray[str_], other: _ArrayLikeStr_co, /) -> NDArray[str_]: ... + @overload + def __add__( + self: ndarray[Any, dtypes.StringDType], + other: _ArrayLikeStr_co | _ArrayLikeString_co, + /, + ) -> ndarray[tuple[Any, ...], dtypes.StringDType]: ... + @overload + def __add__(self: NDArray[object_], other: Any, /) -> Any: ... + @overload + def __add__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + # Keep in sync with `MaskedArray.__radd__` + @overload # signature equivalent to __add__ + def __radd__(self: NDArray[_NumberT], other: int | np.bool, /) -> ndarray[_ShapeT_co, dtype[_NumberT]]: ... + @overload + def __radd__(self: NDArray[_NumberT], other: _ArrayLikeBool_co, /) -> NDArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __radd__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[np.bool]: ... # type: ignore[overload-overlap] + @overload + def __radd__(self: NDArray[np.bool], other: _ArrayLike[_NumberT], /) -> NDArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __radd__(self: NDArray[float64], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ... + @overload + def __radd__(self: _ArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], /) -> NDArray[float64]: ... + @overload + def __radd__(self: NDArray[complex128], other: _ArrayLikeComplex128_co, /) -> NDArray[complex128]: ... + @overload + def __radd__(self: _ArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], /) -> NDArray[complex128]: ... + @overload + def __radd__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __radd__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ... # type: ignore[overload-overlap] + @overload + def __radd__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co, /) -> NDArray[floating]: ... # type: ignore[overload-overlap] + @overload + def __radd__(self: _ArrayComplex_co, other: _ArrayLikeComplex_co, /) -> NDArray[complexfloating]: ... # type: ignore[overload-overlap] + @overload + def __radd__(self: NDArray[number], other: _ArrayLikeNumber_co, /) -> NDArray[number]: ... # type: ignore[overload-overlap] + @overload + def __radd__(self: _ArrayTD64_co, other: _ArrayLikeTD64_co, /) -> NDArray[timedelta64]: ... + @overload + def __radd__(self: _ArrayTD64_co, other: _ArrayLikeDT64_co, /) -> NDArray[datetime64]: ... + @overload + def __radd__(self: NDArray[datetime64], other: _ArrayLikeTD64_co, /) -> NDArray[datetime64]: ... + @overload + def __radd__(self: NDArray[bytes_], other: _ArrayLikeBytes_co, /) -> NDArray[bytes_]: ... + @overload + def __radd__(self: NDArray[str_], other: _ArrayLikeStr_co, /) -> NDArray[str_]: ... + @overload + def __radd__( + self: ndarray[Any, dtypes.StringDType], + other: _ArrayLikeStr_co | _ArrayLikeString_co, + /, + ) -> ndarray[tuple[Any, ...], dtypes.StringDType]: ... + @overload + def __radd__(self: NDArray[object_], other: Any, /) -> Any: ... + @overload + def __radd__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + # Keep in sync with `MaskedArray.__sub__` + @overload + def __sub__(self: NDArray[_NumberT], other: int | np.bool, /) -> ndarray[_ShapeT_co, dtype[_NumberT]]: ... + @overload + def __sub__(self: NDArray[_NumberT], other: _ArrayLikeBool_co, /) -> NDArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __sub__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NoReturn: ... + @overload + def __sub__(self: NDArray[np.bool], other: _ArrayLike[_NumberT], /) -> NDArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __sub__(self: NDArray[float64], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ... + @overload + def __sub__(self: _ArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], /) -> NDArray[float64]: ... + @overload + def __sub__(self: NDArray[complex128], other: _ArrayLikeComplex128_co, /) -> NDArray[complex128]: ... + @overload + def __sub__(self: _ArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], /) -> NDArray[complex128]: ... + @overload + def __sub__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __sub__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ... # type: ignore[overload-overlap] + @overload + def __sub__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co, /) -> NDArray[floating]: ... # type: ignore[overload-overlap] + @overload + def __sub__(self: _ArrayComplex_co, other: _ArrayLikeComplex_co, /) -> NDArray[complexfloating]: ... # type: ignore[overload-overlap] + @overload + def __sub__(self: NDArray[number], other: _ArrayLikeNumber_co, /) -> NDArray[number]: ... # type: ignore[overload-overlap] + @overload + def __sub__(self: _ArrayTD64_co, other: _ArrayLikeTD64_co, /) -> NDArray[timedelta64]: ... + @overload + def __sub__(self: NDArray[datetime64], other: _ArrayLikeTD64_co, /) -> NDArray[datetime64]: ... + @overload + def __sub__(self: NDArray[datetime64], other: _ArrayLikeDT64_co, /) -> NDArray[timedelta64]: ... + @overload + def __sub__(self: NDArray[object_], other: Any, /) -> Any: ... + @overload + def __sub__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + # Keep in sync with `MaskedArray.__rsub__` + @overload + def __rsub__(self: NDArray[_NumberT], other: int | np.bool, /) -> ndarray[_ShapeT_co, dtype[_NumberT]]: ... + @overload + def __rsub__(self: NDArray[_NumberT], other: _ArrayLikeBool_co, /) -> NDArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __rsub__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NoReturn: ... + @overload + def __rsub__(self: NDArray[np.bool], other: _ArrayLike[_NumberT], /) -> NDArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __rsub__(self: NDArray[float64], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ... + @overload + def __rsub__(self: _ArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], /) -> NDArray[float64]: ... + @overload + def __rsub__(self: NDArray[complex128], other: _ArrayLikeComplex128_co, /) -> NDArray[complex128]: ... + @overload + def __rsub__(self: _ArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], /) -> NDArray[complex128]: ... + @overload + def __rsub__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __rsub__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ... # type: ignore[overload-overlap] + @overload + def __rsub__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co, /) -> NDArray[floating]: ... # type: ignore[overload-overlap] + @overload + def __rsub__(self: _ArrayComplex_co, other: _ArrayLikeComplex_co, /) -> NDArray[complexfloating]: ... # type: ignore[overload-overlap] + @overload + def __rsub__(self: NDArray[number], other: _ArrayLikeNumber_co, /) -> NDArray[number]: ... # type: ignore[overload-overlap] + @overload + def __rsub__(self: _ArrayTD64_co, other: _ArrayLikeTD64_co, /) -> NDArray[timedelta64]: ... + @overload + def __rsub__(self: _ArrayTD64_co, other: _ArrayLikeDT64_co, /) -> NDArray[datetime64]: ... + @overload + def __rsub__(self: NDArray[datetime64], other: _ArrayLikeDT64_co, /) -> NDArray[timedelta64]: ... + @overload + def __rsub__(self: NDArray[object_], other: Any, /) -> Any: ... + @overload + def __rsub__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + # Keep in sync with `MaskedArray.__mul__` + @overload + def __mul__(self: NDArray[_NumberT], other: int | np.bool, /) -> ndarray[_ShapeT_co, dtype[_NumberT]]: ... + @overload + def __mul__(self: NDArray[_NumberT], other: _ArrayLikeBool_co, /) -> NDArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __mul__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[np.bool]: ... # type: ignore[overload-overlap] + @overload + def __mul__(self: NDArray[np.bool], other: _ArrayLike[_NumberT], /) -> NDArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __mul__(self: NDArray[float64], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ... + @overload + def __mul__(self: _ArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], /) -> NDArray[float64]: ... + @overload + def __mul__(self: NDArray[complex128], other: _ArrayLikeComplex128_co, /) -> NDArray[complex128]: ... + @overload + def __mul__(self: _ArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], /) -> NDArray[complex128]: ... + @overload + def __mul__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __mul__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ... # type: ignore[overload-overlap] + @overload + def __mul__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co, /) -> NDArray[floating]: ... # type: ignore[overload-overlap] + @overload + def __mul__(self: _ArrayComplex_co, other: _ArrayLikeComplex_co, /) -> NDArray[complexfloating]: ... + @overload + def __mul__(self: NDArray[number], other: _ArrayLikeNumber_co, /) -> NDArray[number]: ... + @overload + def __mul__(self: NDArray[timedelta64], other: _ArrayLikeFloat_co, /) -> NDArray[timedelta64]: ... + @overload + def __mul__(self: _ArrayFloat_co, other: _ArrayLike[timedelta64], /) -> NDArray[timedelta64]: ... + @overload + def __mul__( + self: ndarray[Any, dtype[character] | dtypes.StringDType], + other: _ArrayLikeInt, + /, + ) -> ndarray[tuple[Any, ...], _DTypeT_co]: ... + @overload + def __mul__(self: NDArray[object_], other: Any, /) -> Any: ... + @overload + def __mul__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + # Keep in sync with `MaskedArray.__rmul__` + @overload # signature equivalent to __mul__ + def __rmul__(self: NDArray[_NumberT], other: int | np.bool, /) -> ndarray[_ShapeT_co, dtype[_NumberT]]: ... + @overload + def __rmul__(self: NDArray[_NumberT], other: _ArrayLikeBool_co, /) -> NDArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __rmul__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[np.bool]: ... # type: ignore[overload-overlap] + @overload + def __rmul__(self: NDArray[np.bool], other: _ArrayLike[_NumberT], /) -> NDArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __rmul__(self: NDArray[float64], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ... + @overload + def __rmul__(self: _ArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], /) -> NDArray[float64]: ... + @overload + def __rmul__(self: NDArray[complex128], other: _ArrayLikeComplex128_co, /) -> NDArray[complex128]: ... + @overload + def __rmul__(self: _ArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], /) -> NDArray[complex128]: ... + @overload + def __rmul__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __rmul__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ... # type: ignore[overload-overlap] + @overload + def __rmul__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co, /) -> NDArray[floating]: ... # type: ignore[overload-overlap] + @overload + def __rmul__(self: _ArrayComplex_co, other: _ArrayLikeComplex_co, /) -> NDArray[complexfloating]: ... + @overload + def __rmul__(self: NDArray[number], other: _ArrayLikeNumber_co, /) -> NDArray[number]: ... + @overload + def __rmul__(self: NDArray[timedelta64], other: _ArrayLikeFloat_co, /) -> NDArray[timedelta64]: ... + @overload + def __rmul__(self: _ArrayFloat_co, other: _ArrayLike[timedelta64], /) -> NDArray[timedelta64]: ... + @overload + def __rmul__( + self: ndarray[Any, dtype[character] | dtypes.StringDType], + other: _ArrayLikeInt, + /, + ) -> ndarray[tuple[Any, ...], _DTypeT_co]: ... + @overload + def __rmul__(self: NDArray[object_], other: Any, /) -> Any: ... + @overload + def __rmul__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + # Keep in sync with `MaskedArray.__truediv__` + @overload + def __truediv__(self: _ArrayInt_co | NDArray[float64], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ... + @overload + def __truediv__(self: _ArrayFloat64_co, other: _ArrayLikeInt_co | _ArrayLike[floating[_64Bit]], /) -> NDArray[float64]: ... + @overload + def __truediv__(self: NDArray[complex128], other: _ArrayLikeComplex128_co, /) -> NDArray[complex128]: ... + @overload + def __truediv__(self: _ArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], /) -> NDArray[complex128]: ... + @overload + def __truediv__(self: NDArray[floating], other: _ArrayLikeFloat_co, /) -> NDArray[floating]: ... + @overload + def __truediv__(self: _ArrayFloat_co, other: _ArrayLike[floating], /) -> NDArray[floating]: ... + @overload + def __truediv__(self: NDArray[complexfloating], other: _ArrayLikeNumber_co, /) -> NDArray[complexfloating]: ... + @overload + def __truediv__(self: _ArrayNumber_co, other: _ArrayLike[complexfloating], /) -> NDArray[complexfloating]: ... + @overload + def __truediv__(self: NDArray[inexact], other: _ArrayLikeNumber_co, /) -> NDArray[inexact]: ... + @overload + def __truediv__(self: NDArray[number], other: _ArrayLikeNumber_co, /) -> NDArray[number]: ... + @overload + def __truediv__(self: NDArray[timedelta64], other: _ArrayLike[timedelta64], /) -> NDArray[float64]: ... + @overload + def __truediv__(self: NDArray[timedelta64], other: _ArrayLikeBool_co, /) -> NoReturn: ... + @overload + def __truediv__(self: NDArray[timedelta64], other: _ArrayLikeFloat_co, /) -> NDArray[timedelta64]: ... + @overload + def __truediv__(self: NDArray[object_], other: Any, /) -> Any: ... + @overload + def __truediv__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + # Keep in sync with `MaskedArray.__rtruediv__` + @overload + def __rtruediv__(self: _ArrayInt_co | NDArray[float64], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ... + @overload + def __rtruediv__(self: _ArrayFloat64_co, other: _ArrayLikeInt_co | _ArrayLike[floating[_64Bit]], /) -> NDArray[float64]: ... + @overload + def __rtruediv__(self: NDArray[complex128], other: _ArrayLikeComplex128_co, /) -> NDArray[complex128]: ... + @overload + def __rtruediv__(self: _ArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], /) -> NDArray[complex128]: ... + @overload + def __rtruediv__(self: NDArray[floating], other: _ArrayLikeFloat_co, /) -> NDArray[floating]: ... + @overload + def __rtruediv__(self: _ArrayFloat_co, other: _ArrayLike[floating], /) -> NDArray[floating]: ... + @overload + def __rtruediv__(self: NDArray[complexfloating], other: _ArrayLikeNumber_co, /) -> NDArray[complexfloating]: ... + @overload + def __rtruediv__(self: _ArrayNumber_co, other: _ArrayLike[complexfloating], /) -> NDArray[complexfloating]: ... + @overload + def __rtruediv__(self: NDArray[inexact], other: _ArrayLikeNumber_co, /) -> NDArray[inexact]: ... + @overload + def __rtruediv__(self: NDArray[number], other: _ArrayLikeNumber_co, /) -> NDArray[number]: ... + @overload + def __rtruediv__(self: NDArray[timedelta64], other: _ArrayLike[timedelta64], /) -> NDArray[float64]: ... + @overload + def __rtruediv__(self: NDArray[integer | floating], other: _ArrayLike[timedelta64], /) -> NDArray[timedelta64]: ... + @overload + def __rtruediv__(self: NDArray[object_], other: Any, /) -> Any: ... + @overload + def __rtruediv__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + # Keep in sync with `MaskedArray.__floordiv__` + @overload + def __floordiv__(self: NDArray[_RealNumberT], other: int | np.bool, /) -> ndarray[_ShapeT_co, dtype[_RealNumberT]]: ... + @overload + def __floordiv__(self: NDArray[_RealNumberT], other: _ArrayLikeBool_co, /) -> NDArray[_RealNumberT]: ... # type: ignore[overload-overlap] + @overload + def __floordiv__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[int8]: ... # type: ignore[overload-overlap] + @overload + def __floordiv__(self: NDArray[np.bool], other: _ArrayLike[_RealNumberT], /) -> NDArray[_RealNumberT]: ... # type: ignore[overload-overlap] + @overload + def __floordiv__(self: NDArray[float64], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ... + @overload + def __floordiv__(self: _ArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], /) -> NDArray[float64]: ... + @overload + def __floordiv__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __floordiv__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ... # type: ignore[overload-overlap] + @overload + def __floordiv__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co, /) -> NDArray[floating]: ... + @overload + def __floordiv__(self: NDArray[timedelta64], other: _ArrayLike[timedelta64], /) -> NDArray[int64]: ... + @overload + def __floordiv__(self: NDArray[timedelta64], other: _ArrayLikeBool_co, /) -> NoReturn: ... + @overload + def __floordiv__(self: NDArray[timedelta64], other: _ArrayLikeFloat_co, /) -> NDArray[timedelta64]: ... + @overload + def __floordiv__(self: NDArray[object_], other: Any, /) -> Any: ... + @overload + def __floordiv__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + # Keep in sync with `MaskedArray.__rfloordiv__` + @overload + def __rfloordiv__(self: NDArray[_RealNumberT], other: int | np.bool, /) -> ndarray[_ShapeT_co, dtype[_RealNumberT]]: ... + @overload + def __rfloordiv__(self: NDArray[_RealNumberT], other: _ArrayLikeBool_co, /) -> NDArray[_RealNumberT]: ... # type: ignore[overload-overlap] + @overload + def __rfloordiv__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[int8]: ... # type: ignore[overload-overlap] + @overload + def __rfloordiv__(self: NDArray[np.bool], other: _ArrayLike[_RealNumberT], /) -> NDArray[_RealNumberT]: ... # type: ignore[overload-overlap] + @overload + def __rfloordiv__(self: NDArray[float64], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ... + @overload + def __rfloordiv__(self: _ArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], /) -> NDArray[float64]: ... + @overload + def __rfloordiv__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __rfloordiv__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ... # type: ignore[overload-overlap] + @overload + def __rfloordiv__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co, /) -> NDArray[floating]: ... + @overload + def __rfloordiv__(self: NDArray[timedelta64], other: _ArrayLike[timedelta64], /) -> NDArray[int64]: ... + @overload + def __rfloordiv__(self: NDArray[floating | integer], other: _ArrayLike[timedelta64], /) -> NDArray[timedelta64]: ... + @overload + def __rfloordiv__(self: NDArray[object_], other: Any, /) -> Any: ... + @overload + def __rfloordiv__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + # Keep in sync with `MaskedArray.__pow__` + @overload + def __pow__(self: NDArray[_NumberT], other: int | np.bool, mod: None = None, /) -> ndarray[_ShapeT_co, dtype[_NumberT]]: ... + @overload + def __pow__(self: NDArray[_NumberT], other: _ArrayLikeBool_co, mod: None = None, /) -> NDArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __pow__(self: NDArray[np.bool], other: _ArrayLikeBool_co, mod: None = None, /) -> NDArray[int8]: ... # type: ignore[overload-overlap] + @overload + def __pow__(self: NDArray[np.bool], other: _ArrayLike[_NumberT], mod: None = None, /) -> NDArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __pow__(self: NDArray[float64], other: _ArrayLikeFloat64_co, mod: None = None, /) -> NDArray[float64]: ... + @overload + def __pow__(self: _ArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], mod: None = None, /) -> NDArray[float64]: ... + @overload + def __pow__(self: NDArray[complex128], other: _ArrayLikeComplex128_co, mod: None = None, /) -> NDArray[complex128]: ... + @overload + def __pow__( + self: _ArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], mod: None = None, / + ) -> NDArray[complex128]: ... + @overload + def __pow__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, mod: None = None, /) -> NDArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __pow__(self: _ArrayInt_co, other: _ArrayLikeInt_co, mod: None = None, /) -> NDArray[signedinteger]: ... # type: ignore[overload-overlap] + @overload + def __pow__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co, mod: None = None, /) -> NDArray[floating]: ... # type: ignore[overload-overlap] + @overload + def __pow__(self: _ArrayComplex_co, other: _ArrayLikeComplex_co, mod: None = None, /) -> NDArray[complexfloating]: ... + @overload + def __pow__(self: NDArray[number], other: _ArrayLikeNumber_co, mod: None = None, /) -> NDArray[number]: ... + @overload + def __pow__(self: NDArray[object_], other: Any, mod: None = None, /) -> Any: ... + @overload + def __pow__(self: NDArray[Any], other: _ArrayLikeObject_co, mod: None = None, /) -> Any: ... + + # Keep in sync with `MaskedArray.__rpow__` + @overload + def __rpow__(self: NDArray[_NumberT], other: int | np.bool, mod: None = None, /) -> ndarray[_ShapeT_co, dtype[_NumberT]]: ... + @overload + def __rpow__(self: NDArray[_NumberT], other: _ArrayLikeBool_co, mod: None = None, /) -> NDArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __rpow__(self: NDArray[np.bool], other: _ArrayLikeBool_co, mod: None = None, /) -> NDArray[int8]: ... # type: ignore[overload-overlap] + @overload + def __rpow__(self: NDArray[np.bool], other: _ArrayLike[_NumberT], mod: None = None, /) -> NDArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __rpow__(self: NDArray[float64], other: _ArrayLikeFloat64_co, mod: None = None, /) -> NDArray[float64]: ... + @overload + def __rpow__(self: _ArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], mod: None = None, /) -> NDArray[float64]: ... + @overload + def __rpow__(self: NDArray[complex128], other: _ArrayLikeComplex128_co, mod: None = None, /) -> NDArray[complex128]: ... + @overload + def __rpow__( + self: _ArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], mod: None = None, / + ) -> NDArray[complex128]: ... + @overload + def __rpow__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, mod: None = None, /) -> NDArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __rpow__(self: _ArrayInt_co, other: _ArrayLikeInt_co, mod: None = None, /) -> NDArray[signedinteger]: ... # type: ignore[overload-overlap] + @overload + def __rpow__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co, mod: None = None, /) -> NDArray[floating]: ... # type: ignore[overload-overlap] + @overload + def __rpow__(self: _ArrayComplex_co, other: _ArrayLikeComplex_co, mod: None = None, /) -> NDArray[complexfloating]: ... + @overload + def __rpow__(self: NDArray[number], other: _ArrayLikeNumber_co, mod: None = None, /) -> NDArray[number]: ... + @overload + def __rpow__(self: NDArray[object_], other: Any, mod: None = None, /) -> Any: ... + @overload + def __rpow__(self: NDArray[Any], other: _ArrayLikeObject_co, mod: None = None, /) -> Any: ... + + @overload + def __lshift__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[int8]: ... + @overload + def __lshift__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __lshift__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ... + @overload + def __lshift__(self: NDArray[object_], other: Any, /) -> Any: ... + @overload + def __lshift__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + @overload + def __rlshift__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[int8]: ... + @overload + def __rlshift__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __rlshift__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ... + @overload + def __rlshift__(self: NDArray[object_], other: Any, /) -> Any: ... + @overload + def __rlshift__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + @overload + def __rshift__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[int8]: ... + @overload + def __rshift__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __rshift__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ... + @overload + def __rshift__(self: NDArray[object_], other: Any, /) -> Any: ... + @overload + def __rshift__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + @overload + def __rrshift__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[int8]: ... + @overload + def __rrshift__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __rrshift__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ... + @overload + def __rrshift__(self: NDArray[object_], other: Any, /) -> Any: ... + @overload + def __rrshift__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + @overload + def __and__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[np.bool]: ... + @overload + def __and__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __and__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ... + @overload + def __and__(self: NDArray[object_], other: Any, /) -> Any: ... + @overload + def __and__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + @overload + def __rand__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[np.bool]: ... + @overload + def __rand__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __rand__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ... + @overload + def __rand__(self: NDArray[object_], other: Any, /) -> Any: ... + @overload + def __rand__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + @overload + def __xor__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[np.bool]: ... + @overload + def __xor__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __xor__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ... + @overload + def __xor__(self: NDArray[object_], other: Any, /) -> Any: ... + @overload + def __xor__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + @overload + def __rxor__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[np.bool]: ... + @overload + def __rxor__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __rxor__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ... + @overload + def __rxor__(self: NDArray[object_], other: Any, /) -> Any: ... + @overload + def __rxor__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + @overload + def __or__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[np.bool]: ... + @overload + def __or__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __or__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ... + @overload + def __or__(self: NDArray[object_], other: Any, /) -> Any: ... + @overload + def __or__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + @overload + def __ror__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[np.bool]: ... + @overload + def __ror__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __ror__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ... + @overload + def __ror__(self: NDArray[object_], other: Any, /) -> Any: ... + @overload + def __ror__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + # `np.generic` does not support inplace operations + + # NOTE: Inplace ops generally use "same_kind" casting w.r.t. to the left + # operand. An exception to this rule are unsigned integers though, which + # also accepts a signed integer for the right operand as long it is a 0D + # object and its value is >= 0 + # NOTE: Due to a mypy bug, overloading on e.g. `self: NDArray[SCT_floating]` won't + # work, as this will lead to `false negatives` when using these inplace ops. + + # += + @overload # type: ignore[misc] + def __iadd__(self: _BoolArrayT, other: _ArrayLikeBool_co, /) -> _BoolArrayT: ... + @overload + def __iadd__(self: _ComplexFloatingArrayT, other: _ArrayLikeComplex_co, /) -> _ComplexFloatingArrayT: ... + @overload + def __iadd__(self: _InexactArrayT, other: _ArrayLikeFloat_co, /) -> _InexactArrayT: ... + @overload + def __iadd__(self: _NumberArrayT, other: _ArrayLikeInt_co, /) -> _NumberArrayT: ... + @overload + def __iadd__(self: _TimeArrayT, other: _ArrayLikeTD64_co, /) -> _TimeArrayT: ... + @overload + def __iadd__(self: _BytesArrayT, other: _ArrayLikeBytes_co, /) -> _BytesArrayT: ... + @overload + def __iadd__(self: _StringArrayT, other: _ArrayLikeStr_co | _ArrayLikeString_co, /) -> _StringArrayT: ... + @overload + def __iadd__(self: _ObjectArrayT, other: object, /) -> _ObjectArrayT: ... + + # -= + @overload # type: ignore[misc] + def __isub__(self: _ComplexFloatingArrayT, other: _ArrayLikeComplex_co, /) -> _ComplexFloatingArrayT: ... + @overload + def __isub__(self: _InexactArrayT, other: _ArrayLikeFloat_co, /) -> _InexactArrayT: ... + @overload + def __isub__(self: _NumberArrayT, other: _ArrayLikeInt_co, /) -> _NumberArrayT: ... + @overload + def __isub__(self: _TimeArrayT, other: _ArrayLikeTD64_co, /) -> _TimeArrayT: ... + @overload + def __isub__(self: _ObjectArrayT, other: object, /) -> _ObjectArrayT: ... + + # *= + @overload # type: ignore[misc] + def __imul__(self: _BoolArrayT, other: _ArrayLikeBool_co, /) -> _BoolArrayT: ... + @overload + def __imul__(self: _ComplexFloatingArrayT, other: _ArrayLikeComplex_co, /) -> _ComplexFloatingArrayT: ... + @overload + def __imul__(self: _InexactTimedeltaArrayT, other: _ArrayLikeFloat_co, /) -> _InexactTimedeltaArrayT: ... + @overload + def __imul__(self: _NumberCharacterArrayT, other: _ArrayLikeInt_co, /) -> _NumberCharacterArrayT: ... + @overload + def __imul__(self: _ObjectArrayT, other: object, /) -> _ObjectArrayT: ... + + # @= + @overload # type: ignore[misc] + def __imatmul__(self: _BoolArrayT, other: _ArrayLikeBool_co, /) -> _BoolArrayT: ... + @overload + def __imatmul__(self: _ComplexFloatingArrayT, other: _ArrayLikeComplex_co, /) -> _ComplexFloatingArrayT: ... + @overload + def __imatmul__(self: _InexactArrayT, other: _ArrayLikeFloat_co, /) -> _InexactArrayT: ... + @overload + def __imatmul__(self: _NumberArrayT, other: _ArrayLikeInt_co, /) -> _NumberArrayT: ... + @overload + def __imatmul__(self: _ObjectArrayT, other: object, /) -> _ObjectArrayT: ... + + # **= + @overload # type: ignore[misc] + def __ipow__(self: _ComplexFloatingArrayT, other: _ArrayLikeComplex_co, /) -> _ComplexFloatingArrayT: ... + @overload + def __ipow__(self: _InexactArrayT, other: _ArrayLikeFloat_co, /) -> _InexactArrayT: ... + @overload + def __ipow__(self: _NumberArrayT, other: _ArrayLikeInt_co, /) -> _NumberArrayT: ... + @overload + def __ipow__(self: _ObjectArrayT, other: object, /) -> _ObjectArrayT: ... + + # /= + @overload # type: ignore[misc] + def __itruediv__(self: _ComplexFloatingArrayT, other: _ArrayLikeComplex_co, /) -> _ComplexFloatingArrayT: ... + @overload + def __itruediv__(self: _InexactTimedeltaArrayT, other: _ArrayLikeFloat_co, /) -> _InexactTimedeltaArrayT: ... + @overload + def __itruediv__(self: _ObjectArrayT, other: object, /) -> _ObjectArrayT: ... + + # //= + # keep in sync with `__imod__` + @overload # type: ignore[misc] + def __ifloordiv__(self: _IntegerArrayT, other: _ArrayLikeInt_co, /) -> _IntegerArrayT: ... + @overload + def __ifloordiv__(self: _FloatingTimedeltaArrayT, other: _ArrayLikeFloat_co, /) -> _FloatingTimedeltaArrayT: ... + @overload + def __ifloordiv__(self: _ObjectArrayT, other: object, /) -> _ObjectArrayT: ... + + # %= + # keep in sync with `__ifloordiv__` + @overload # type: ignore[misc] + def __imod__(self: _IntegerArrayT, other: _ArrayLikeInt_co, /) -> _IntegerArrayT: ... + @overload + def __imod__(self: _FloatingArrayT, other: _ArrayLikeFloat_co, /) -> _FloatingArrayT: ... + @overload + def __imod__(self: _TimedeltaArrayT, other: _ArrayLike[timedelta64], /) -> _TimedeltaArrayT: ... + @overload + def __imod__(self: _ObjectArrayT, other: object, /) -> _ObjectArrayT: ... + + # <<= + # keep in sync with `__irshift__` + @overload # type: ignore[misc] + def __ilshift__(self: _IntegerArrayT, other: _ArrayLikeInt_co, /) -> _IntegerArrayT: ... + @overload + def __ilshift__(self: _ObjectArrayT, other: object, /) -> _ObjectArrayT: ... + + # >>= + # keep in sync with `__ilshift__` + @overload # type: ignore[misc] + def __irshift__(self: _IntegerArrayT, other: _ArrayLikeInt_co, /) -> _IntegerArrayT: ... + @overload + def __irshift__(self: _ObjectArrayT, other: object, /) -> _ObjectArrayT: ... + + # &= + # keep in sync with `__ixor__` and `__ior__` + @overload # type: ignore[misc] + def __iand__(self: _BoolArrayT, other: _ArrayLikeBool_co, /) -> _BoolArrayT: ... + @overload + def __iand__(self: _IntegerArrayT, other: _ArrayLikeInt_co, /) -> _IntegerArrayT: ... + @overload + def __iand__(self: _ObjectArrayT, other: object, /) -> _ObjectArrayT: ... + + # ^= + # keep in sync with `__iand__` and `__ior__` + @overload # type: ignore[misc] + def __ixor__(self: _BoolArrayT, other: _ArrayLikeBool_co, /) -> _BoolArrayT: ... + @overload + def __ixor__(self: _IntegerArrayT, other: _ArrayLikeInt_co, /) -> _IntegerArrayT: ... + @overload + def __ixor__(self: _ObjectArrayT, other: object, /) -> _ObjectArrayT: ... + + # |= + # keep in sync with `__iand__` and `__ixor__` + @overload # type: ignore[misc] + def __ior__(self: _BoolArrayT, other: _ArrayLikeBool_co, /) -> _BoolArrayT: ... + @overload + def __ior__(self: _IntegerArrayT, other: _ArrayLikeInt_co, /) -> _IntegerArrayT: ... + @overload + def __ior__(self: _ObjectArrayT, other: object, /) -> _ObjectArrayT: ... + + # + def __dlpack__( + self: NDArray[number], + /, + *, + stream: int | Any | None = None, + max_version: tuple[int, int] | None = None, + dl_device: tuple[int, int] | None = None, + copy: builtins.bool | None = None, + ) -> CapsuleType: ... + def __dlpack_device__(self, /) -> tuple[L[1], L[0]]: ... + + # Keep `dtype` at the bottom to avoid name conflicts with `np.dtype` + @property + def dtype(self) -> _DTypeT_co: ... + +# NOTE: while `np.generic` is not technically an instance of `ABCMeta`, +# the `@abstractmethod` decorator is herein used to (forcefully) deny +# the creation of `np.generic` instances. +# The `# type: ignore` comments are necessary to silence mypy errors regarding +# the missing `ABCMeta` metaclass. +# See https://github.com/numpy/numpy-stubs/pull/80 for more details. +class generic(_ArrayOrScalarCommon, Generic[_ItemT_co]): + @abstractmethod + def __new__(cls, /, *args: Any, **kwargs: Any) -> Self: ... + + # NOTE: Technically this doesn't exist at runtime, but it is unlikely to lead to + # type-unsafe situations (the abstract scalar types cannot be instantiated + # themselves) and is convenient to have, so we include it regardless. See + # https://github.com/numpy/numpy/issues/30445 for use-cases and discussion. + def __hash__(self, /) -> int: ... + + if sys.version_info >= (3, 12): + def __buffer__(self, flags: int, /) -> memoryview: ... + + @overload + def __array__(self, dtype: None = None, /) -> ndarray[tuple[()], dtype[Self]]: ... + @overload + def __array__(self, dtype: _DTypeT, /) -> ndarray[tuple[()], _DTypeT]: ... + + @overload + def __array_wrap__( + self, + array: ndarray[_ShapeT, _DTypeT], + context: tuple[ufunc, tuple[object, ...], int] | None, + return_scalar: L[False], + /, + ) -> ndarray[_ShapeT, _DTypeT]: ... + @overload + def __array_wrap__( + self, + array: ndarray[tuple[()], dtype[_ScalarT]], + context: tuple[ufunc, tuple[object, ...], int] | None = None, + return_scalar: L[True] = True, + /, + ) -> _ScalarT: ... + @overload + def __array_wrap__( + self, + array: ndarray[_Shape1T, _DTypeT], + context: tuple[ufunc, tuple[object, ...], int] | None = None, + return_scalar: L[True] = True, + /, + ) -> ndarray[_Shape1T, _DTypeT]: ... + @overload + def __array_wrap__( + self, + array: ndarray[_ShapeT, dtype[_ScalarT]], + context: tuple[ufunc, tuple[object, ...], int] | None = None, + return_scalar: L[True] = True, + /, + ) -> _ScalarT | ndarray[_ShapeT, dtype[_ScalarT]]: ... + + @property + def base(self) -> None: ... + @property + def ndim(self) -> L[0]: ... + @property + def size(self) -> L[1]: ... + @property + def shape(self) -> tuple[()]: ... + @property + def strides(self) -> tuple[()]: ... + @property + def flat(self) -> flatiter[ndarray[tuple[int], dtype[Self]]]: ... + + @overload + def item(self, /) -> _ItemT_co: ... + @overload + def item(self, arg0: L[0, -1] | tuple[L[0, -1]] | tuple[()] = ..., /) -> _ItemT_co: ... + @override + def tolist(self, /) -> _ItemT_co: ... + + # NOTE: these technically exist, but will always raise when called + def trace( # type: ignore[misc] + self: Never, + /, + offset: L[0] = 0, + axis1: L[0] = 0, + axis2: L[1] = 1, + dtype: None = None, + out: None = None, + ) -> Never: ... + def diagonal(self: Never, /, offset: L[0] = 0, axis1: L[0] = 0, axis2: L[1] = 1) -> Never: ... # type: ignore[misc] + def swapaxes(self: Never, axis1: Never, axis2: Never, /) -> Never: ... # type: ignore[misc] + def sort(self: Never, /, axis: L[-1] = -1, kind: None = None, order: None = None, *, stable: None = None) -> Never: ... # type: ignore[misc] + def nonzero(self: Never, /) -> Never: ... # type: ignore[misc] + def setfield(self: Never, val: Never, /, dtype: Never, offset: L[0] = 0) -> None: ... # type: ignore[misc] + def searchsorted(self: Never, v: Never, /, side: L["left"] = "left", sorter: None = None) -> Never: ... # type: ignore[misc] + + # NOTE: this wont't raise, but won't do anything either + @overload + def resize(self, /, *, refcheck: builtins.bool = True) -> None: ... + @overload + def resize(self, new_shape: L[0, -1] | tuple[L[0, -1]] | tuple[()], /, *, refcheck: builtins.bool = True) -> None: ... + + # + def byteswap(self, /, inplace: L[False] = False) -> Self: ... + + # + @overload + def astype( + self, + /, + dtype: _DTypeLike[_ScalarT], + order: _OrderKACF = "K", + casting: _CastingKind = "unsafe", + subok: builtins.bool = True, + copy: builtins.bool | _CopyMode = True, + ) -> _ScalarT: ... + @overload + def astype( + self, + /, + dtype: DTypeLike | None, + order: _OrderKACF = "K", + casting: _CastingKind = "unsafe", + subok: builtins.bool = True, + copy: builtins.bool | _CopyMode = True, + ) -> Incomplete: ... + + # NOTE: `view` will perform a 0D->scalar cast, + # thus the array `type` is irrelevant to the output type + @overload + def view(self, type: type[ndarray] = ...) -> Self: ... + @overload + def view(self, /, dtype: _DTypeLike[_ScalarT], type: type[ndarray] = ...) -> _ScalarT: ... + @overload + def view(self, /, dtype: DTypeLike, type: type[ndarray] = ...) -> Incomplete: ... + + @overload + def getfield(self, /, dtype: _DTypeLike[_ScalarT], offset: SupportsIndex = 0) -> _ScalarT: ... + @overload + def getfield(self, /, dtype: DTypeLike, offset: SupportsIndex = 0) -> Incomplete: ... + + @overload + def take( + self, + indices: _IntLike_co, + /, + axis: SupportsIndex | None = None, + out: None = None, + mode: _ModeKind = "raise", + ) -> Self: ... + @overload + def take( + self, + indices: _ArrayLikeInt_co, + /, + axis: SupportsIndex | None = None, + out: None = None, + mode: _ModeKind = "raise", + ) -> NDArray[Self]: ... + @overload + def take( + self, + indices: _ArrayLikeInt_co, + /, + axis: SupportsIndex | None = None, + *, + out: _ArrayT, + mode: _ModeKind = "raise", + ) -> _ArrayT: ... + @overload + def take( + self, + indices: _ArrayLikeInt_co, + /, + axis: SupportsIndex | None, + out: _ArrayT, + mode: _ModeKind = "raise", + ) -> _ArrayT: ... + + def repeat(self, repeats: _ArrayLikeInt_co, /, axis: SupportsIndex | None = None) -> ndarray[tuple[int], dtype[Self]]: ... + def flatten(self, /, order: _OrderKACF = "C") -> ndarray[tuple[int], dtype[Self]]: ... + def ravel(self, /, order: _OrderKACF = "C") -> ndarray[tuple[int], dtype[Self]]: ... + + @overload # (() | []) + def reshape( + self, + shape: tuple[()] | list[Never], + /, + *, + order: _OrderACF = "C", + copy: builtins.bool | None = None, + ) -> Self: ... + @overload # ((1, *(1, ...))@_ShapeT) + def reshape( + self, + shape: _1NShapeT, + /, + *, + order: _OrderACF = "C", + copy: builtins.bool | None = None, + ) -> ndarray[_1NShapeT, dtype[Self]]: ... + @overload # (Sequence[index, ...]) # not recommended + def reshape( + self, + shape: Sequence[SupportsIndex], + /, + *, + order: _OrderACF = "C", + copy: builtins.bool | None = None, + ) -> Self | ndarray[tuple[L[1], ...], dtype[Self]]: ... + @overload # _(index) + def reshape( + self, + size1: SupportsIndex, + /, + *, + order: _OrderACF = "C", + copy: builtins.bool | None = None, + ) -> ndarray[tuple[L[1]], dtype[Self]]: ... + @overload # _(index, index) + def reshape( + self, + size1: SupportsIndex, + size2: SupportsIndex, + /, + *, + order: _OrderACF = "C", + copy: builtins.bool | None = None, + ) -> ndarray[tuple[L[1], L[1]], dtype[Self]]: ... + @overload # _(index, index, index) + def reshape( + self, + size1: SupportsIndex, + size2: SupportsIndex, + size3: SupportsIndex, + /, + *, + order: _OrderACF = "C", + copy: builtins.bool | None = None, + ) -> ndarray[tuple[L[1], L[1], L[1]], dtype[Self]]: ... + @overload # _(index, index, index, index) + def reshape( + self, + size1: SupportsIndex, + size2: SupportsIndex, + size3: SupportsIndex, + size4: SupportsIndex, + /, + *, + order: _OrderACF = "C", + copy: builtins.bool | None = None, + ) -> ndarray[tuple[L[1], L[1], L[1], L[1]], dtype[Self]]: ... + @overload # _(index, index, index, index, index, *index) # ndim >= 5 + def reshape( + self, + size1: SupportsIndex, + size2: SupportsIndex, + size3: SupportsIndex, + size4: SupportsIndex, + size5: SupportsIndex, + /, + *sizes6_: SupportsIndex, + order: _OrderACF = "C", + copy: builtins.bool | None = None, + ) -> ndarray[tuple[L[1], L[1], L[1], L[1], L[1], *tuple[L[1], ...]], dtype[Self]]: ... + + def squeeze(self, axis: L[0] | tuple[()] | None = ...) -> Self: ... + def transpose(self, axes: tuple[()] | None = ..., /) -> Self: ... + + @overload + def all( + self, + /, + axis: L[0, -1] | tuple[()] | None = None, + out: None = None, + keepdims: SupportsIndex = False, + *, + where: builtins.bool | np.bool | ndarray[tuple[()], dtype[np.bool]] = True + ) -> np.bool: ... + @overload + def all( + self, + /, + axis: L[0, -1] | tuple[()] | None, + out: ndarray[tuple[()], dtype[_ScalarT]], + keepdims: SupportsIndex = False, + *, + where: builtins.bool | np.bool | ndarray[tuple[()], dtype[np.bool]] = True, + ) -> _ScalarT: ... + @overload + def all( + self, + /, + axis: L[0, -1] | tuple[()] | None = None, + *, + out: ndarray[tuple[()], dtype[_ScalarT]], + keepdims: SupportsIndex = False, + where: builtins.bool | np.bool | ndarray[tuple[()], dtype[np.bool]] = True, + ) -> _ScalarT: ... + + @overload + def any( + self, + /, + axis: L[0, -1] | tuple[()] | None = None, + out: None = None, + keepdims: SupportsIndex = False, + *, + where: builtins.bool | np.bool | ndarray[tuple[()], dtype[np.bool]] = True + ) -> np.bool: ... + @overload + def any( + self, + /, + axis: L[0, -1] | tuple[()] | None, + out: ndarray[tuple[()], dtype[_ScalarT]], + keepdims: SupportsIndex = False, + *, + where: builtins.bool | np.bool | ndarray[tuple[()], dtype[np.bool]] = True, + ) -> _ScalarT: ... + @overload + def any( + self, + /, + axis: L[0, -1] | tuple[()] | None = None, + *, + out: ndarray[tuple[()], dtype[_ScalarT]], + keepdims: SupportsIndex = False, + where: builtins.bool | np.bool | ndarray[tuple[()], dtype[np.bool]] = True, + ) -> _ScalarT: ... + + # Keep `dtype` at the bottom to avoid name conflicts with `np.dtype` + @property + def dtype(self) -> _dtype[Self]: ... + +class number(generic[_NumberItemT_co], Generic[_NBit, _NumberItemT_co]): + @abstractmethod # `SupportsIndex | str | bytes` equivs `_ConvertibleToInt & _ConvertibleToFloat` + def __new__(cls, value: SupportsIndex | str | bytes = 0, /) -> Self: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + + def __neg__(self) -> Self: ... + def __pos__(self) -> Self: ... + def __abs__(self) -> Self: ... + + def __add__(self, other: _NumberLike_co, /) -> Incomplete: ... + def __radd__(self, other: _NumberLike_co, /) -> Incomplete: ... + def __sub__(self, other: _NumberLike_co, /) -> Incomplete: ... + def __rsub__(self, other: _NumberLike_co, /) -> Incomplete: ... + def __mul__(self, other: _NumberLike_co, /) -> Incomplete: ... + def __rmul__(self, other: _NumberLike_co, /) -> Incomplete: ... + def __pow__(self, other: _NumberLike_co, mod: None = None, /) -> Incomplete: ... + def __rpow__(self, other: _NumberLike_co, mod: None = None, /) -> Incomplete: ... + def __truediv__(self, other: _NumberLike_co, /) -> Incomplete: ... + def __rtruediv__(self, other: _NumberLike_co, /) -> Incomplete: ... + + @overload + def __lt__(self, other: _NumberLike_co, /) -> bool_: ... + @overload + def __lt__(self, other: _ArrayLikeNumber_co | _NestedSequence[_SupportsGT], /) -> NDArray[bool_]: ... + @overload + def __lt__(self, other: _SupportsGT, /) -> bool_: ... + + @overload + def __le__(self, other: _NumberLike_co, /) -> bool_: ... + @overload + def __le__(self, other: _ArrayLikeNumber_co | _NestedSequence[_SupportsGE], /) -> NDArray[bool_]: ... + @overload + def __le__(self, other: _SupportsGE, /) -> bool_: ... + + @overload + def __gt__(self, other: _NumberLike_co, /) -> bool_: ... + @overload + def __gt__(self, other: _ArrayLikeNumber_co | _NestedSequence[_SupportsLT], /) -> NDArray[bool_]: ... + @overload + def __gt__(self, other: _SupportsLT, /) -> bool_: ... + + @overload + def __ge__(self, other: _NumberLike_co, /) -> bool_: ... + @overload + def __ge__(self, other: _ArrayLikeNumber_co | _NestedSequence[_SupportsLE], /) -> NDArray[bool_]: ... + @overload + def __ge__(self, other: _SupportsLE, /) -> bool_: ... + +class bool(generic[_BoolItemT_co], Generic[_BoolItemT_co]): + @property + def itemsize(self) -> L[1]: ... + @property + def nbytes(self) -> L[1]: ... + @property + def real(self) -> Self: ... + @property + def imag(self) -> np.bool[L[False]]: ... + + @overload # mypy bug workaround: https://github.com/numpy/numpy/issues/29245 + def __new__(cls, value: Never, /) -> np.bool[builtins.bool]: ... + @overload + def __new__(cls, value: _Falsy = ..., /) -> np.bool[L[False]]: ... + @overload + def __new__(cls, value: _Truthy, /) -> np.bool[L[True]]: ... + @overload + def __new__(cls, value: object, /) -> np.bool[builtins.bool]: ... + + def __class_getitem__(cls, type_arg: type | object, /) -> GenericAlias: ... + + def __bool__(self, /) -> _BoolItemT_co: ... + + @overload + def __int__(self: np.bool[L[False]], /) -> L[0]: ... + @overload + def __int__(self: np.bool[L[True]], /) -> L[1]: ... + @overload + def __int__(self, /) -> L[0, 1]: ... + + def __abs__(self) -> Self: ... + + @overload + def __invert__(self: np.bool[L[False]], /) -> np.bool[L[True]]: ... + @overload + def __invert__(self: np.bool[L[True]], /) -> np.bool[L[False]]: ... + @overload + def __invert__(self, /) -> np.bool: ... + + @overload + def __add__(self, other: _NumberT, /) -> _NumberT: ... + @overload + def __add__(self, other: builtins.bool | bool_, /) -> bool_: ... + @overload + def __add__(self, other: int, /) -> int_: ... + @overload + def __add__(self, other: float, /) -> float64: ... + @overload + def __add__(self, other: complex, /) -> complex128: ... + + @overload + def __radd__(self, other: _NumberT, /) -> _NumberT: ... + @overload + def __radd__(self, other: builtins.bool, /) -> bool_: ... + @overload + def __radd__(self, other: int, /) -> int_: ... + @overload + def __radd__(self, other: float, /) -> float64: ... + @overload + def __radd__(self, other: complex, /) -> complex128: ... + + @overload + def __sub__(self, other: _NumberT, /) -> _NumberT: ... + @overload + def __sub__(self, other: int, /) -> int_: ... + @overload + def __sub__(self, other: float, /) -> float64: ... + @overload + def __sub__(self, other: complex, /) -> complex128: ... + + @overload + def __rsub__(self, other: _NumberT, /) -> _NumberT: ... + @overload + def __rsub__(self, other: int, /) -> int_: ... + @overload + def __rsub__(self, other: float, /) -> float64: ... + @overload + def __rsub__(self, other: complex, /) -> complex128: ... + + @overload + def __mul__(self, other: _NumberT, /) -> _NumberT: ... + @overload + def __mul__(self, other: builtins.bool | bool_, /) -> bool_: ... + @overload + def __mul__(self, other: int, /) -> int_: ... + @overload + def __mul__(self, other: float, /) -> float64: ... + @overload + def __mul__(self, other: complex, /) -> complex128: ... + + @overload + def __rmul__(self, other: _NumberT, /) -> _NumberT: ... + @overload + def __rmul__(self, other: builtins.bool, /) -> bool_: ... + @overload + def __rmul__(self, other: int, /) -> int_: ... + @overload + def __rmul__(self, other: float, /) -> float64: ... + @overload + def __rmul__(self, other: complex, /) -> complex128: ... + + @overload + def __pow__(self, other: _NumberT, mod: None = None, /) -> _NumberT: ... + @overload + def __pow__(self, other: builtins.bool | bool_, mod: None = None, /) -> int8: ... + @overload + def __pow__(self, other: int, mod: None = None, /) -> int_: ... + @overload + def __pow__(self, other: float, mod: None = None, /) -> float64: ... + @overload + def __pow__(self, other: complex, mod: None = None, /) -> complex128: ... + + @overload + def __rpow__(self, other: _NumberT, mod: None = None, /) -> _NumberT: ... + @overload + def __rpow__(self, other: builtins.bool, mod: None = None, /) -> int8: ... + @overload + def __rpow__(self, other: int, mod: None = None, /) -> int_: ... + @overload + def __rpow__(self, other: float, mod: None = None, /) -> float64: ... + @overload + def __rpow__(self, other: complex, mod: None = None, /) -> complex128: ... + + @overload + def __truediv__(self, other: _InexactT, /) -> _InexactT: ... + @overload + def __truediv__(self, other: float | integer | bool_, /) -> float64: ... + @overload + def __truediv__(self, other: complex, /) -> complex128: ... + + @overload + def __rtruediv__(self, other: _InexactT, /) -> _InexactT: ... + @overload + def __rtruediv__(self, other: float | integer, /) -> float64: ... + @overload + def __rtruediv__(self, other: complex, /) -> complex128: ... + + @overload + def __floordiv__(self, other: _RealNumberT, /) -> _RealNumberT: ... + @overload + def __floordiv__(self, other: builtins.bool | bool_, /) -> int8: ... + @overload + def __floordiv__(self, other: int, /) -> int_: ... + @overload + def __floordiv__(self, other: float, /) -> float64: ... + + @overload + def __rfloordiv__(self, other: _RealNumberT, /) -> _RealNumberT: ... + @overload + def __rfloordiv__(self, other: builtins.bool, /) -> int8: ... + @overload + def __rfloordiv__(self, other: int, /) -> int_: ... + @overload + def __rfloordiv__(self, other: float, /) -> float64: ... + + # keep in sync with __floordiv__ + @overload + def __mod__(self, other: _RealNumberT, /) -> _RealNumberT: ... + @overload + def __mod__(self, other: builtins.bool | bool_, /) -> int8: ... + @overload + def __mod__(self, other: int, /) -> int_: ... + @overload + def __mod__(self, other: float, /) -> float64: ... + + # keep in sync with __rfloordiv__ + @overload + def __rmod__(self, other: _RealNumberT, /) -> _RealNumberT: ... + @overload + def __rmod__(self, other: builtins.bool, /) -> int8: ... + @overload + def __rmod__(self, other: int, /) -> int_: ... + @overload + def __rmod__(self, other: float, /) -> float64: ... + + # keep in sync with __mod__ + @overload + def __divmod__(self, other: _RealNumberT, /) -> _2Tuple[_RealNumberT]: ... + @overload + def __divmod__(self, other: builtins.bool | bool_, /) -> _2Tuple[int8]: ... + @overload + def __divmod__(self, other: int, /) -> _2Tuple[int_]: ... + @overload + def __divmod__(self, other: float, /) -> _2Tuple[float64]: ... + + # keep in sync with __rmod__ + @overload + def __rdivmod__(self, other: _RealNumberT, /) -> _2Tuple[_RealNumberT]: ... + @overload + def __rdivmod__(self, other: builtins.bool, /) -> _2Tuple[int8]: ... + @overload + def __rdivmod__(self, other: int, /) -> _2Tuple[int_]: ... + @overload + def __rdivmod__(self, other: float, /) -> _2Tuple[float64]: ... + + @overload + def __lshift__(self, other: _IntegerT, /) -> _IntegerT: ... + @overload + def __lshift__(self, other: builtins.bool | bool_, /) -> int8: ... + @overload + def __lshift__(self, other: int, /) -> int_: ... + + @overload + def __rlshift__(self, other: _IntegerT, /) -> _IntegerT: ... + @overload + def __rlshift__(self, other: builtins.bool, /) -> int8: ... + @overload + def __rlshift__(self, other: int, /) -> int_: ... + + # keep in sync with __lshift__ + @overload + def __rshift__(self, other: _IntegerT, /) -> _IntegerT: ... + @overload + def __rshift__(self, other: builtins.bool | bool_, /) -> int8: ... + @overload + def __rshift__(self, other: int, /) -> int_: ... + + # keep in sync with __rlshift__ + @overload + def __rrshift__(self, other: _IntegerT, /) -> _IntegerT: ... + @overload + def __rrshift__(self, other: builtins.bool, /) -> int8: ... + @overload + def __rrshift__(self, other: int, /) -> int_: ... + + @overload + def __and__(self: np.bool[L[False]], other: builtins.bool | np.bool, /) -> np.bool[L[False]]: ... + @overload + def __and__(self, other: L[False] | np.bool[L[False]], /) -> np.bool[L[False]]: ... + @overload + def __and__(self, other: L[True] | np.bool[L[True]], /) -> Self: ... + @overload + def __and__(self, other: builtins.bool | np.bool, /) -> np.bool: ... + @overload + def __and__(self, other: _IntegerT, /) -> _IntegerT: ... + @overload + def __and__(self, other: int, /) -> np.bool | intp: ... + __rand__ = __and__ + + @overload + def __xor__(self: np.bool[L[False]], other: _BoolItemT | np.bool[_BoolItemT], /) -> np.bool[_BoolItemT]: ... + @overload + def __xor__(self: np.bool[L[True]], other: L[True] | np.bool[L[True]], /) -> np.bool[L[False]]: ... + @overload + def __xor__(self, other: L[False] | np.bool[L[False]], /) -> Self: ... + @overload + def __xor__(self, other: builtins.bool | np.bool, /) -> np.bool: ... + @overload + def __xor__(self, other: _IntegerT, /) -> _IntegerT: ... + @overload + def __xor__(self, other: int, /) -> np.bool | intp: ... + __rxor__ = __xor__ + + @overload + def __or__(self: np.bool[L[True]], other: builtins.bool | np.bool, /) -> np.bool[L[True]]: ... + @overload + def __or__(self, other: L[False] | np.bool[L[False]], /) -> Self: ... + @overload + def __or__(self, other: L[True] | np.bool[L[True]], /) -> np.bool[L[True]]: ... + @overload + def __or__(self, other: builtins.bool | np.bool, /) -> np.bool: ... + @overload + def __or__(self, other: _IntegerT, /) -> _IntegerT: ... + @overload + def __or__(self, other: int, /) -> np.bool | intp: ... + __ror__ = __or__ + + @overload + def __lt__(self, other: _NumberLike_co, /) -> bool_: ... + @overload + def __lt__(self, other: _ArrayLikeNumber_co | _NestedSequence[_SupportsGT], /) -> NDArray[bool_]: ... + @overload + def __lt__(self, other: _SupportsGT, /) -> bool_: ... + + @overload + def __le__(self, other: _NumberLike_co, /) -> bool_: ... + @overload + def __le__(self, other: _ArrayLikeNumber_co | _NestedSequence[_SupportsGE], /) -> NDArray[bool_]: ... + @overload + def __le__(self, other: _SupportsGE, /) -> bool_: ... + + @overload + def __gt__(self, other: _NumberLike_co, /) -> bool_: ... + @overload + def __gt__(self, other: _ArrayLikeNumber_co | _NestedSequence[_SupportsLT], /) -> NDArray[bool_]: ... + @overload + def __gt__(self, other: _SupportsLT, /) -> bool_: ... + + @overload + def __ge__(self, other: _NumberLike_co, /) -> bool_: ... + @overload + def __ge__(self, other: _ArrayLikeNumber_co | _NestedSequence[_SupportsLE], /) -> NDArray[bool_]: ... + @overload + def __ge__(self, other: _SupportsLE, /) -> bool_: ... + +# NOTE: This should _not_ be `Final` or a `TypeAlias` +bool_ = bool + +# NOTE: The `object_` constructor returns the passed object, so instances with type +# `object_` cannot exists (at runtime). +# NOTE: Because mypy has some long-standing bugs related to `__new__`, `object_` can't +# be made generic. +@final +class object_(_RealMixin, generic): + @overload + def __new__(cls, value: None = None, /) -> None: ... # type: ignore[misc] + @overload + def __new__(cls, value: _AnyStr, /) -> _AnyStr: ... # type: ignore[misc] + @overload + def __new__(cls, value: ndarray[_ShapeT, Any], /) -> ndarray[_ShapeT, dtype[Self]]: ... # type: ignore[misc] + @overload + def __new__(cls, value: SupportsLenAndGetItem[object], /) -> NDArray[Self]: ... # type: ignore[misc] + @overload + def __new__(cls, value: _T, /) -> _T: ... # type: ignore[misc] + @overload # catch-all + def __new__(cls, value: Any = ..., /) -> object | NDArray[Self]: ... # type: ignore[misc] + + def __hash__(self, /) -> int: ... + def __abs__(self, /) -> object_: ... # this affects NDArray[object_].__abs__ + def __call__(self, /, *args: object, **kwargs: object) -> Any: ... + + if sys.version_info >= (3, 12): + def __release_buffer__(self, buffer: memoryview, /) -> None: ... + +class integer(_IntegralMixin, _RoundMixin, number[_NBit, int]): + @abstractmethod + def __new__(cls, value: _ConvertibleToInt = 0, /) -> Self: ... + + # NOTE: `bit_count` and `__index__` are technically defined in the concrete subtypes + def bit_count(self, /) -> int: ... + def __index__(self, /) -> int: ... + def __invert__(self, /) -> Self: ... + + @override # type: ignore[override] + @overload + def __truediv__(self, other: float | integer, /) -> float64: ... + @overload + def __truediv__(self, other: complex, /) -> complex128: ... + + @override # type: ignore[override] + @overload + def __rtruediv__(self, other: float | integer, /) -> float64: ... + @overload + def __rtruediv__(self, other: complex, /) -> complex128: ... + + def __floordiv__(self, value: _IntLike_co, /) -> integer: ... + def __rfloordiv__(self, value: _IntLike_co, /) -> integer: ... + def __mod__(self, value: _IntLike_co, /) -> integer: ... + def __rmod__(self, value: _IntLike_co, /) -> integer: ... + def __divmod__(self, value: _IntLike_co, /) -> _2Tuple[integer]: ... + def __rdivmod__(self, value: _IntLike_co, /) -> _2Tuple[integer]: ... + + # Ensure that objects annotated as `integer` support bit-wise operations + def __lshift__(self, other: _IntLike_co, /) -> integer: ... + def __rlshift__(self, other: _IntLike_co, /) -> integer: ... + def __rshift__(self, other: _IntLike_co, /) -> integer: ... + def __rrshift__(self, other: _IntLike_co, /) -> integer: ... + def __and__(self, other: _IntLike_co, /) -> integer: ... + def __rand__(self, other: _IntLike_co, /) -> integer: ... + def __or__(self, other: _IntLike_co, /) -> integer: ... + def __ror__(self, other: _IntLike_co, /) -> integer: ... + def __xor__(self, other: _IntLike_co, /) -> integer: ... + def __rxor__(self, other: _IntLike_co, /) -> integer: ... + +class signedinteger(integer[_NBit]): + def __new__(cls, value: _ConvertibleToInt = 0, /) -> Self: ... + + # arithmetic ops + + @override # type: ignore[override] + @overload + def __add__(self, other: int | int8 | bool_ | Self, /) -> Self: ... + @overload + def __add__(self, other: float, /) -> float64: ... + @overload + def __add__(self, other: complex, /) -> complex128: ... + @overload + def __add__(self, other: signedinteger, /) -> signedinteger: ... + @overload + def __add__(self, other: integer, /) -> Incomplete: ... + + @override # type: ignore[override] + @overload + def __radd__(self, other: int | int8 | bool_, /) -> Self: ... + @overload + def __radd__(self, other: float, /) -> float64: ... + @overload + def __radd__(self, other: complex, /) -> complex128: ... + @overload + def __radd__(self, other: signedinteger, /) -> signedinteger: ... + @overload + def __radd__(self, other: integer, /) -> Incomplete: ... + + @override # type: ignore[override] + @overload + def __sub__(self, other: int | int8 | bool_ | Self, /) -> Self: ... + @overload + def __sub__(self, other: float, /) -> float64: ... + @overload + def __sub__(self, other: complex, /) -> complex128: ... + @overload + def __sub__(self, other: signedinteger, /) -> signedinteger: ... + @overload + def __sub__(self, other: integer, /) -> Incomplete: ... + + @override # type: ignore[override] + @overload + def __rsub__(self, other: int | int8 | bool_, /) -> Self: ... + @overload + def __rsub__(self, other: float, /) -> float64: ... + @overload + def __rsub__(self, other: complex, /) -> complex128: ... + @overload + def __rsub__(self, other: signedinteger, /) -> signedinteger: ... + @overload + def __rsub__(self, other: integer, /) -> Incomplete: ... + + @override # type: ignore[override] + @overload + def __mul__(self, other: int | int8 | bool_ | Self, /) -> Self: ... + @overload + def __mul__(self, other: float, /) -> float64: ... + @overload + def __mul__(self, other: complex, /) -> complex128: ... + @overload + def __mul__(self, other: signedinteger, /) -> signedinteger: ... + @overload + def __mul__(self, other: integer, /) -> Incomplete: ... + + @override # type: ignore[override] + @overload + def __rmul__(self, other: int | int8 | bool_, /) -> Self: ... + @overload + def __rmul__(self, other: float, /) -> float64: ... + @overload + def __rmul__(self, other: complex, /) -> complex128: ... + @overload + def __rmul__(self, other: signedinteger, /) -> signedinteger: ... + @overload + def __rmul__(self, other: integer, /) -> Incomplete: ... + + @override # type: ignore[override] + @overload + def __pow__(self, other: int | int8 | bool_ | Self, mod: None = None, /) -> Self: ... + @overload + def __pow__(self, other: float, mod: None = None, /) -> float64: ... + @overload + def __pow__(self, other: complex, mod: None = None, /) -> complex128: ... + @overload + def __pow__(self, other: signedinteger, mod: None = None, /) -> signedinteger: ... + @overload + def __pow__(self, other: integer, mod: None = None, /) -> Incomplete: ... + + @override # type: ignore[override] + @overload + def __rpow__(self, other: int | int8 | bool_, mod: None = None, /) -> Self: ... + @overload + def __rpow__(self, other: float, mod: None = None, /) -> float64: ... + @overload + def __rpow__(self, other: complex, mod: None = None, /) -> complex128: ... + @overload + def __rpow__(self, other: signedinteger, mod: None = None, /) -> signedinteger: ... + @overload + def __rpow__(self, other: integer, mod: None = None, /) -> Incomplete: ... + + # modular division ops + + @override # type: ignore[override] + @overload + def __floordiv__(self, other: int | int8 | bool_ | Self, /) -> Self: ... + @overload + def __floordiv__(self, other: float, /) -> float64: ... + @overload + def __floordiv__(self, other: signedinteger, /) -> signedinteger: ... + @overload + def __floordiv__(self, other: integer, /) -> Incomplete: ... + + @override # type: ignore[override] + @overload + def __rfloordiv__(self, other: int | int8 | bool_, /) -> Self: ... + @overload + def __rfloordiv__(self, other: float, /) -> float64: ... + @overload + def __rfloordiv__(self, other: signedinteger, /) -> signedinteger: ... + @overload + def __rfloordiv__(self, other: integer, /) -> Incomplete: ... + + @override # type: ignore[override] + @overload + def __mod__(self, other: int | int8 | bool_ | Self, /) -> Self: ... + @overload + def __mod__(self, other: float, /) -> float64: ... + @overload + def __mod__(self, other: signedinteger, /) -> signedinteger: ... + @overload + def __mod__(self, other: integer, /) -> Incomplete: ... + + @override # type: ignore[override] + @overload + def __rmod__(self, other: int | int8 | bool_, /) -> Self: ... + @overload + def __rmod__(self, other: float, /) -> float64: ... + @overload + def __rmod__(self, other: signedinteger, /) -> signedinteger: ... + @overload + def __rmod__(self, other: integer, /) -> Incomplete: ... + + @override # type: ignore[override] + @overload + def __divmod__(self, other: int | int8 | bool_ | Self, /) -> _2Tuple[Self]: ... + @overload + def __divmod__(self, other: float, /) -> _2Tuple[float64]: ... + @overload + def __divmod__(self, other: signedinteger, /) -> _2Tuple[signedinteger]: ... + @overload + def __divmod__(self, other: integer, /) -> _2Tuple[Incomplete]: ... + + @override # type: ignore[override] + @overload + def __rdivmod__(self, other: int | int8 | bool_, /) -> _2Tuple[Self]: ... + @overload + def __rdivmod__(self, other: float, /) -> _2Tuple[float64]: ... + @overload + def __rdivmod__(self, other: signedinteger, /) -> _2Tuple[signedinteger]: ... + @overload + def __rdivmod__(self, other: integer, /) -> _2Tuple[Incomplete]: ... + + # bitwise ops + + @override # type: ignore[override] + @overload + def __lshift__(self, other: int | int8 | bool_ | Self, /) -> Self: ... + @overload + def __lshift__(self, other: integer, /) -> signedinteger: ... + + @override # type: ignore[override] + @overload + def __rlshift__(self, other: int | int8 | bool_, /) -> Self: ... + @overload + def __rlshift__(self, other: integer, /) -> signedinteger: ... + + @override # type: ignore[override] + @overload + def __rshift__(self, other: int | int8 | bool_ | Self, /) -> Self: ... + @overload + def __rshift__(self, other: integer, /) -> signedinteger: ... + + @override # type: ignore[override] + @overload + def __rrshift__(self, other: int | int8 | bool_, /) -> Self: ... + @overload + def __rrshift__(self, other: integer, /) -> signedinteger: ... + + @override # type: ignore[override] + @overload + def __and__(self, other: int | int8 | bool_ | Self, /) -> Self: ... + @overload + def __and__(self, other: integer, /) -> signedinteger: ... + + @override # type: ignore[override] + @overload + def __rand__(self, other: int | int8 | bool_, /) -> Self: ... + @overload + def __rand__(self, other: integer, /) -> signedinteger: ... + + @override # type: ignore[override] + @overload + def __xor__(self, other: int | int8 | bool_ | Self, /) -> Self: ... + @overload + def __xor__(self, other: integer, /) -> signedinteger: ... + + @override # type: ignore[override] + @overload + def __rxor__(self, other: int | int8 | bool_, /) -> Self: ... + @overload + def __rxor__(self, other: integer, /) -> signedinteger: ... + + @override # type: ignore[override] + @overload + def __or__(self, other: int | int8 | bool_ | Self, /) -> Self: ... + @overload + def __or__(self, other: integer, /) -> signedinteger: ... + + @override # type: ignore[override] + @overload + def __ror__(self, other: int | int8 | bool_, /) -> Self: ... + @overload + def __ror__(self, other: integer, /) -> signedinteger: ... + +int8 = signedinteger[_8Bit] +int16 = signedinteger[_16Bit] +int32 = signedinteger[_32Bit] +int64 = signedinteger[_64Bit] + +byte = signedinteger[_NBitByte] +short = signedinteger[_NBitShort] +intc = signedinteger[_NBitIntC] +intp = signedinteger[_NBitIntP] +int_ = intp +long = signedinteger[_NBitLong] +longlong = signedinteger[_NBitLongLong] + +class unsignedinteger(integer[_NBit1]): + def __new__(cls, value: _ConvertibleToInt = 0, /) -> Self: ... + + # arithmetic ops + + @override # type: ignore[override] + @overload + def __add__(self, other: int | uint8 | bool_ | Self, /) -> Self: ... + @overload + def __add__(self, other: float, /) -> float64: ... + @overload + def __add__(self, other: complex, /) -> complex128: ... + @overload + def __add__(self, other: unsignedinteger, /) -> unsignedinteger: ... + @overload + def __add__(self, other: integer, /) -> Incomplete: ... + + @override # type: ignore[override] + @overload + def __radd__(self, other: int | uint8 | bool_, /) -> Self: ... + @overload + def __radd__(self, other: float, /) -> float64: ... + @overload + def __radd__(self, other: complex, /) -> complex128: ... + @overload + def __radd__(self, other: unsignedinteger, /) -> unsignedinteger: ... + @overload + def __radd__(self, other: integer, /) -> Incomplete: ... + + @override # type: ignore[override] + @overload + def __sub__(self, other: int | uint8 | bool_ | Self, /) -> Self: ... + @overload + def __sub__(self, other: float, /) -> float64: ... + @overload + def __sub__(self, other: complex, /) -> complex128: ... + @overload + def __sub__(self, other: unsignedinteger, /) -> unsignedinteger: ... + @overload + def __sub__(self, other: integer, /) -> Incomplete: ... + + @override # type: ignore[override] + @overload + def __rsub__(self, other: int | uint8 | bool_, /) -> Self: ... + @overload + def __rsub__(self, other: float, /) -> float64: ... + @overload + def __rsub__(self, other: complex, /) -> complex128: ... + @overload + def __rsub__(self, other: unsignedinteger, /) -> unsignedinteger: ... + @overload + def __rsub__(self, other: integer, /) -> Incomplete: ... + + @override # type: ignore[override] + @overload + def __mul__(self, other: int | uint8 | bool_ | Self, /) -> Self: ... + @overload + def __mul__(self, other: float, /) -> float64: ... + @overload + def __mul__(self, other: complex, /) -> complex128: ... + @overload + def __mul__(self, other: unsignedinteger, /) -> unsignedinteger: ... + @overload + def __mul__(self, other: integer, /) -> Incomplete: ... + + @override # type: ignore[override] + @overload + def __rmul__(self, other: int | uint8 | bool_, /) -> Self: ... + @overload + def __rmul__(self, other: float, /) -> float64: ... + @overload + def __rmul__(self, other: complex, /) -> complex128: ... + @overload + def __rmul__(self, other: unsignedinteger, /) -> unsignedinteger: ... + @overload + def __rmul__(self, other: integer, /) -> Incomplete: ... + + @override # type: ignore[override] + @overload + def __pow__(self, other: int | uint8 | bool_ | Self, mod: None = None, /) -> Self: ... + @overload + def __pow__(self, other: float, mod: None = None, /) -> float64: ... + @overload + def __pow__(self, other: complex, mod: None = None, /) -> complex128: ... + @overload + def __pow__(self, other: unsignedinteger, mod: None = None, /) -> unsignedinteger: ... + @overload + def __pow__(self, other: integer, mod: None = None, /) -> Incomplete: ... + + @override # type: ignore[override] + @overload + def __rpow__(self, other: int | uint8 | bool_, mod: None = None, /) -> Self: ... + @overload + def __rpow__(self, other: float, mod: None = None, /) -> float64: ... + @overload + def __rpow__(self, other: complex, mod: None = None, /) -> complex128: ... + @overload + def __rpow__(self, other: unsignedinteger, mod: None = None, /) -> unsignedinteger: ... + @overload + def __rpow__(self, other: integer, mod: None = None, /) -> Incomplete: ... + + # modular division ops + + @override # type: ignore[override] + @overload + def __floordiv__(self, other: int | uint8 | bool_ | Self, /) -> Self: ... + @overload + def __floordiv__(self, other: float, /) -> float64: ... + @overload + def __floordiv__(self, other: unsignedinteger, /) -> unsignedinteger: ... + @overload + def __floordiv__(self, other: integer, /) -> Incomplete: ... + + @override # type: ignore[override] + @overload + def __rfloordiv__(self, other: int | uint8 | bool_, /) -> Self: ... + @overload + def __rfloordiv__(self, other: float, /) -> float64: ... + @overload + def __rfloordiv__(self, other: unsignedinteger, /) -> unsignedinteger: ... + @overload + def __rfloordiv__(self, other: integer, /) -> Incomplete: ... + + @override # type: ignore[override] + @overload + def __mod__(self, other: int | uint8 | bool_ | Self, /) -> Self: ... + @overload + def __mod__(self, other: float, /) -> float64: ... + @overload + def __mod__(self, other: unsignedinteger, /) -> unsignedinteger: ... + @overload + def __mod__(self, other: integer, /) -> Incomplete: ... + + @override # type: ignore[override] + @overload + def __rmod__(self, other: int | uint8 | bool_, /) -> Self: ... + @overload + def __rmod__(self, other: float, /) -> float64: ... + @overload + def __rmod__(self, other: unsignedinteger, /) -> unsignedinteger: ... + @overload + def __rmod__(self, other: integer, /) -> Incomplete: ... + + @override # type: ignore[override] + @overload + def __divmod__(self, other: int | uint8 | bool_ | Self, /) -> _2Tuple[Self]: ... + @overload + def __divmod__(self, other: float, /) -> _2Tuple[float64]: ... + @overload + def __divmod__(self, other: unsignedinteger, /) -> _2Tuple[unsignedinteger]: ... + @overload + def __divmod__(self, other: integer, /) -> _2Tuple[Incomplete]: ... + + @override # type: ignore[override] + @overload + def __rdivmod__(self, other: int | uint8 | bool_, /) -> _2Tuple[Self]: ... + @overload + def __rdivmod__(self, other: float, /) -> _2Tuple[float64]: ... + @overload + def __rdivmod__(self, other: unsignedinteger, /) -> _2Tuple[unsignedinteger]: ... + @overload + def __rdivmod__(self, other: integer, /) -> _2Tuple[Incomplete]: ... + + # bitwise ops + + @override # type: ignore[override] + @overload + def __lshift__(self, other: int | int8 | bool_ | Self, /) -> Self: ... + @overload + def __lshift__(self, other: unsignedinteger, /) -> unsignedinteger: ... + @overload + def __lshift__(self, other: signedinteger, /) -> signedinteger: ... + + @override # type: ignore[override] + @overload + def __rlshift__(self, other: int | int8 | bool_, /) -> Self: ... + @overload + def __rlshift__(self, other: unsignedinteger, /) -> unsignedinteger: ... + @overload + def __rlshift__(self, other: signedinteger, /) -> signedinteger: ... + + @override # type: ignore[override] + @overload + def __rshift__(self, other: int | int8 | bool_ | Self, /) -> Self: ... + @overload + def __rshift__(self, other: unsignedinteger, /) -> unsignedinteger: ... + @overload + def __rshift__(self, other: signedinteger, /) -> signedinteger: ... + + @override # type: ignore[override] + @overload + def __rrshift__(self, other: int | int8 | bool_, /) -> Self: ... + @overload + def __rrshift__(self, other: unsignedinteger, /) -> unsignedinteger: ... + @overload + def __rrshift__(self, other: signedinteger, /) -> signedinteger: ... + + @override # type: ignore[override] + @overload + def __and__(self, other: int | int8 | bool_ | Self, /) -> Self: ... + @overload + def __and__(self, other: unsignedinteger, /) -> unsignedinteger: ... + @overload + def __and__(self, other: signedinteger, /) -> signedinteger: ... + + @override # type: ignore[override] + @overload + def __rand__(self, other: int | int8 | bool_, /) -> Self: ... + @overload + def __rand__(self, other: unsignedinteger, /) -> unsignedinteger: ... + @overload + def __rand__(self, other: signedinteger, /) -> signedinteger: ... + + @override # type: ignore[override] + @overload + def __xor__(self, other: int | int8 | bool_ | Self, /) -> Self: ... + @overload + def __xor__(self, other: unsignedinteger, /) -> unsignedinteger: ... + @overload + def __xor__(self, other: signedinteger, /) -> signedinteger: ... + + @override # type: ignore[override] + @overload + def __rxor__(self, other: int | int8 | bool_, /) -> Self: ... + @overload + def __rxor__(self, other: unsignedinteger, /) -> unsignedinteger: ... + @overload + def __rxor__(self, other: signedinteger, /) -> signedinteger: ... + + @override # type: ignore[override] + @overload + def __or__(self, other: int | int8 | bool_ | Self, /) -> Self: ... + @overload + def __or__(self, other: unsignedinteger, /) -> unsignedinteger: ... + @overload + def __or__(self, other: signedinteger, /) -> signedinteger: ... + + @override # type: ignore[override] + @overload + def __ror__(self, other: int | int8 | bool_, /) -> Self: ... + @overload + def __ror__(self, other: unsignedinteger, /) -> unsignedinteger: ... + @overload + def __ror__(self, other: signedinteger, /) -> signedinteger: ... + +uint8: TypeAlias = unsignedinteger[_8Bit] +uint16: TypeAlias = unsignedinteger[_16Bit] +uint32: TypeAlias = unsignedinteger[_32Bit] +uint64: TypeAlias = unsignedinteger[_64Bit] + +ubyte: TypeAlias = unsignedinteger[_NBitByte] +ushort: TypeAlias = unsignedinteger[_NBitShort] +uintc: TypeAlias = unsignedinteger[_NBitIntC] +uintp: TypeAlias = unsignedinteger[_NBitIntP] +uint: TypeAlias = uintp +ulong: TypeAlias = unsignedinteger[_NBitLong] +ulonglong: TypeAlias = unsignedinteger[_NBitLongLong] + +class inexact(number[_NBit, _InexactItemT_co], Generic[_NBit, _InexactItemT_co]): + @abstractmethod + def __new__(cls, value: _ConvertibleToFloat | None = 0, /) -> Self: ... + +class floating(_RealMixin, _RoundMixin, inexact[_NBit1, float]): + def __new__(cls, value: _ConvertibleToFloat | None = 0, /) -> Self: ... + + # arithmetic ops + + @override # type: ignore[override] + @overload + def __add__(self, other: int | float16 | uint8 | int8 | bool_ | Self, /) -> Self: ... + @overload + def __add__(self, other: integer | floating, /) -> floating: ... + @overload + def __add__(self, other: float, /) -> Self: ... + @overload + def __add__(self, other: complex, /) -> complexfloating: ... + + @override # type: ignore[override] + @overload + def __radd__(self, other: int | float16 | uint8 | int8 | bool_, /) -> Self: ... + @overload + def __radd__(self, other: integer | floating, /) -> floating: ... + @overload + def __radd__(self, other: float, /) -> Self: ... + @overload + def __radd__(self, other: complex, /) -> complexfloating: ... + + @override # type: ignore[override] + @overload + def __sub__(self, other: int | float16 | uint8 | int8 | bool_ | Self, /) -> Self: ... + @overload + def __sub__(self, other: integer | floating, /) -> floating: ... + @overload + def __sub__(self, other: float, /) -> Self: ... + @overload + def __sub__(self, other: complex, /) -> complexfloating: ... + + @override # type: ignore[override] + @overload + def __rsub__(self, other: int | float16 | uint8 | int8 | bool_, /) -> Self: ... + @overload + def __rsub__(self, other: integer | floating, /) -> floating: ... + @overload + def __rsub__(self, other: float, /) -> Self: ... + @overload + def __rsub__(self, other: complex, /) -> complexfloating: ... + + @override # type: ignore[override] + @overload + def __mul__(self, other: int | float16 | uint8 | int8 | bool_ | Self, /) -> Self: ... + @overload + def __mul__(self, other: integer | floating, /) -> floating: ... + @overload + def __mul__(self, other: float, /) -> Self: ... + @overload + def __mul__(self, other: complex, /) -> complexfloating: ... + + @override # type: ignore[override] + @overload + def __rmul__(self, other: int | float16 | uint8 | int8 | bool_, /) -> Self: ... + @overload + def __rmul__(self, other: integer | floating, /) -> floating: ... + @overload + def __rmul__(self, other: float, /) -> Self: ... + @overload + def __rmul__(self, other: complex, /) -> complexfloating: ... + + @override # type: ignore[override] + @overload + def __pow__(self, other: int | float16 | uint8 | int8 | bool_ | Self, mod: None = None, /) -> Self: ... + @overload + def __pow__(self, other: integer | floating, mod: None = None, /) -> floating: ... + @overload + def __pow__(self, other: float, mod: None = None, /) -> Self: ... + @overload + def __pow__(self, other: complex, mod: None = None, /) -> complexfloating: ... + + @override # type: ignore[override] + @overload + def __rpow__(self, other: int | float16 | uint8 | int8 | bool_, mod: None = None, /) -> Self: ... + @overload + def __rpow__(self, other: integer | floating, mod: None = None, /) -> floating: ... + @overload + def __rpow__(self, other: float, mod: None = None, /) -> Self: ... + @overload + def __rpow__(self, other: complex, mod: None = None, /) -> complexfloating: ... + + @override # type: ignore[override] + @overload + def __truediv__(self, other: int | float16 | uint8 | int8 | bool_ | Self, /) -> Self: ... + @overload + def __truediv__(self, other: integer | floating, /) -> floating: ... + @overload + def __truediv__(self, other: float, /) -> Self: ... + @overload + def __truediv__(self, other: complex, /) -> complexfloating: ... + + @override # type: ignore[override] + @overload + def __rtruediv__(self, other: int | float16 | uint8 | int8 | bool_, /) -> Self: ... + @overload + def __rtruediv__(self, other: integer | floating, /) -> floating: ... + @overload + def __rtruediv__(self, other: float, /) -> Self: ... + @overload + def __rtruediv__(self, other: complex, /) -> complexfloating: ... + + # modular division ops + + @overload + def __floordiv__(self, other: int | float16 | uint8 | int8 | bool_ | Self, /) -> Self: ... + @overload + def __floordiv__(self, other: integer | floating, /) -> floating: ... + @overload + def __floordiv__(self, other: float, /) -> Self: ... + + @overload + def __rfloordiv__(self, other: int | float16 | uint8 | int8 | bool_, /) -> Self: ... + @overload + def __rfloordiv__(self, other: integer | floating, /) -> floating: ... + @overload + def __rfloordiv__(self, other: float, /) -> Self: ... + + @overload + def __mod__(self, other: int | float16 | uint8 | int8 | bool_ | Self, /) -> Self: ... + @overload + def __mod__(self, other: integer | floating, /) -> floating: ... + @overload + def __mod__(self, other: float, /) -> Self: ... + + @overload + def __rmod__(self, other: int | float16 | uint8 | int8 | bool_, /) -> Self: ... + @overload + def __rmod__(self, other: integer | floating, /) -> floating: ... + @overload + def __rmod__(self, other: float, /) -> Self: ... + + @overload + def __divmod__(self, other: int | float16 | uint8 | int8 | bool_ | Self, /) -> _2Tuple[Self]: ... + @overload + def __divmod__(self, other: integer | floating, /) -> _2Tuple[floating]: ... + @overload + def __divmod__(self, other: float, /) -> _2Tuple[Self]: ... + + @overload + def __rdivmod__(self, other: int | float16 | uint8 | int8 | bool_, /) -> _2Tuple[Self]: ... + @overload + def __rdivmod__(self, other: integer | floating, /) -> _2Tuple[floating]: ... + @overload + def __rdivmod__(self, other: float, /) -> _2Tuple[Self]: ... + + # NOTE: `is_integer` and `as_integer_ratio` are technically defined in the concrete subtypes + def is_integer(self, /) -> builtins.bool: ... + def as_integer_ratio(self, /) -> tuple[int, int]: ... + +float16: TypeAlias = floating[_16Bit] +float32: TypeAlias = floating[_32Bit] + +# either a C `double`, `float`, or `longdouble` +class float64(floating[_64Bit], float): # type: ignore[misc] + @property + def itemsize(self) -> L[8]: ... + @property + def nbytes(self) -> L[8]: ... + + # overrides for `floating` and `builtins.float` compatibility (`_RealMixin` doesn't work) + @property + def real(self) -> Self: ... + @property + def imag(self) -> Self: ... + def conjugate(self) -> Self: ... + def __getnewargs__(self, /) -> tuple[float]: ... + + @classmethod + def __getformat__(cls, typestr: L["double", "float"], /) -> str: ... # undocumented + + # float64-specific operator overrides + # NOTE: Mypy reports [misc] errors about "unsafely overlapping signatures" for the + # reflected methods. But since they are identical to the non-reflected versions, + # these errors appear to be false positives. + + @overload # type: ignore[override] + def __add__(self, other: _Float64_co, /) -> float64: ... + @overload + def __add__(self, other: complexfloating[_64Bit, _64Bit], /) -> complex128: ... + @overload + def __add__(self, other: complexfloating[_NBit1, _NBit2], /) -> complexfloating[_NBit1 | _64Bit, _NBit2 | _64Bit]: ... + @overload + def __add__(self, other: complex, /) -> float64 | complex128: ... + + @overload # type: ignore[override] + def __radd__(self, other: _Float64_co, /) -> float64: ... # type: ignore[misc] + @overload + def __radd__(self, other: complexfloating[_64Bit, _64Bit], /) -> complex128: ... # type: ignore[misc] + @overload + def __radd__(self, other: complexfloating[_NBit1, _NBit2], /) -> complexfloating[_NBit1 | _64Bit, _NBit2 | _64Bit]: ... + @overload + def __radd__(self, other: complex, /) -> float64 | complex128: ... + + @overload # type: ignore[override] + def __sub__(self, other: _Float64_co, /) -> float64: ... + @overload + def __sub__(self, other: complexfloating[_64Bit, _64Bit], /) -> complex128: ... + @overload + def __sub__(self, other: complexfloating[_NBit1, _NBit2], /) -> complexfloating[_NBit1 | _64Bit, _NBit2 | _64Bit]: ... + @overload + def __sub__(self, other: complex, /) -> float64 | complex128: ... + + @overload # type: ignore[override] + def __rsub__(self, other: _Float64_co, /) -> float64: ... # type: ignore[misc] + @overload + def __rsub__(self, other: complexfloating[_64Bit, _64Bit], /) -> complex128: ... # type: ignore[misc] + @overload + def __rsub__(self, other: complexfloating[_NBit1, _NBit2], /) -> complexfloating[_NBit1 | _64Bit, _NBit2 | _64Bit]: ... + @overload + def __rsub__(self, other: complex, /) -> float64 | complex128: ... + + @overload # type: ignore[override] + def __mul__(self, other: _Float64_co, /) -> float64: ... + @overload + def __mul__(self, other: complexfloating[_64Bit, _64Bit], /) -> complex128: ... + @overload + def __mul__(self, other: complexfloating[_NBit1, _NBit2], /) -> complexfloating[_NBit1 | _64Bit, _NBit2 | _64Bit]: ... + @overload + def __mul__(self, other: complex, /) -> float64 | complex128: ... + + @overload # type: ignore[override] + def __rmul__(self, other: _Float64_co, /) -> float64: ... # type: ignore[misc] + @overload + def __rmul__(self, other: complexfloating[_64Bit, _64Bit], /) -> complex128: ... # type: ignore[misc] + @overload + def __rmul__(self, other: complexfloating[_NBit1, _NBit2], /) -> complexfloating[_NBit1 | _64Bit, _NBit2 | _64Bit]: ... + @overload + def __rmul__(self, other: complex, /) -> float64 | complex128: ... + + @overload # type: ignore[override] + def __truediv__(self, other: _Float64_co, /) -> float64: ... + @overload + def __truediv__(self, other: complexfloating[_64Bit, _64Bit], /) -> complex128: ... + @overload + def __truediv__(self, other: complexfloating[_NBit1, _NBit2], /) -> complexfloating[_NBit1 | _64Bit, _NBit2 | _64Bit]: ... + @overload + def __truediv__(self, other: complex, /) -> float64 | complex128: ... + + @overload # type: ignore[override] + def __rtruediv__(self, other: _Float64_co, /) -> float64: ... # type: ignore[misc] + @overload + def __rtruediv__(self, other: complexfloating[_64Bit, _64Bit], /) -> complex128: ... # type: ignore[misc] + @overload + def __rtruediv__(self, other: complexfloating[_NBit1, _NBit2], /) -> complexfloating[_NBit1 | _64Bit, _NBit2 | _64Bit]: ... + @overload + def __rtruediv__(self, other: complex, /) -> float64 | complex128: ... + + @overload # type: ignore[override] + def __floordiv__(self, other: _Float64_co, /) -> float64: ... + @overload + def __floordiv__(self, other: complexfloating[_64Bit, _64Bit], /) -> complex128: ... + @overload + def __floordiv__(self, other: complexfloating[_NBit1, _NBit2], /) -> complexfloating[_NBit1 | _64Bit, _NBit2 | _64Bit]: ... + @overload + def __floordiv__(self, other: complex, /) -> float64 | complex128: ... + + @overload + def __rfloordiv__(self, other: _Float64_co, /) -> float64: ... # type: ignore[misc] + @overload + def __rfloordiv__(self, other: complexfloating[_64Bit, _64Bit], /) -> complex128: ... + @overload + def __rfloordiv__(self, other: complexfloating[_NBit1, _NBit2], /) -> complexfloating[_NBit1 | _64Bit, _NBit2 | _64Bit]: ... + @overload + def __rfloordiv__(self, other: complex, /) -> float64 | complex128: ... + + @overload # type: ignore[override] + def __pow__(self, other: _Float64_co, mod: None = None, /) -> float64: ... + @overload + def __pow__(self, other: complexfloating[_64Bit, _64Bit], mod: None = None, /) -> complex128: ... + @overload + def __pow__( + self, other: complexfloating[_NBit1, _NBit2], mod: None = None, / + ) -> complexfloating[_NBit1 | _64Bit, _NBit2 | _64Bit]: ... + @overload + def __pow__(self, other: complex, mod: None = None, /) -> float64 | complex128: ... + + @overload # type: ignore[override] + def __rpow__(self, other: _Float64_co, mod: None = None, /) -> float64: ... # type: ignore[misc] + @overload + def __rpow__(self, other: complexfloating[_64Bit, _64Bit], mod: None = None, /) -> complex128: ... # type: ignore[misc] + @overload + def __rpow__( + self, other: complexfloating[_NBit1, _NBit2], mod: None = None, / + ) -> complexfloating[_NBit1 | _64Bit, _NBit2 | _64Bit]: ... + @overload + def __rpow__(self, other: complex, mod: None = None, /) -> float64 | complex128: ... + + def __mod__(self, other: _Float64_co, /) -> float64: ... + def __rmod__(self, other: _Float64_co, /) -> float64: ... # type: ignore[misc] + + def __divmod__(self, other: _Float64_co, /) -> _2Tuple[float64]: ... + def __rdivmod__(self, other: _Float64_co, /) -> _2Tuple[float64]: ... # type: ignore[misc] + +half: TypeAlias = float16 +single: TypeAlias = float32 +double: TypeAlias = float64 +longdouble: TypeAlias = floating[_NBitLongDouble] + +# The main reason for `complexfloating` having two typevars is cosmetic. +# It is used to clarify why `complex128`s precision is `_64Bit`, the latter +# describing the two 64 bit floats representing its real and imaginary component + +class complexfloating(inexact[_NBit1, complex], Generic[_NBit1, _NBit2]): + @overload + def __new__( + cls, + real: complex | SupportsComplex | SupportsFloat | SupportsIndex = 0, + imag: complex | SupportsFloat | SupportsIndex = 0, + /, + ) -> Self: ... + @overload + def __new__(cls, real: _ConvertibleToComplex | None = 0, /) -> Self: ... + + @property + def real(self) -> floating[_NBit1]: ... + @property + def imag(self) -> floating[_NBit2]: ... + + # NOTE: `__complex__` is technically defined in the concrete subtypes + def __complex__(self, /) -> complex: ... + def __abs__(self, /) -> floating[_NBit1 | _NBit2]: ... # type: ignore[override] + + @overload # type: ignore[override] + def __add__(self, other: _Complex64_co, /) -> complexfloating[_NBit1, _NBit2]: ... + @overload + def __add__(self, other: complex | float64 | complex128, /) -> complexfloating[_NBit1, _NBit2] | complex128: ... + @overload + def __add__(self, other: number[_NBit], /) -> complexfloating[_NBit1, _NBit2] | complexfloating[_NBit, _NBit]: ... + + @overload # type: ignore[override] + def __radd__(self, other: _Complex64_co, /) -> complexfloating[_NBit1, _NBit2]: ... + @overload + def __radd__(self, other: complex, /) -> complexfloating[_NBit1, _NBit2] | complex128: ... + @overload + def __radd__(self, other: number[_NBit], /) -> complexfloating[_NBit1, _NBit2] | complexfloating[_NBit, _NBit]: ... + + @overload # type: ignore[override] + def __sub__(self, other: _Complex64_co, /) -> complexfloating[_NBit1, _NBit2]: ... + @overload + def __sub__(self, other: complex | float64 | complex128, /) -> complexfloating[_NBit1, _NBit2] | complex128: ... + @overload + def __sub__(self, other: number[_NBit], /) -> complexfloating[_NBit1, _NBit2] | complexfloating[_NBit, _NBit]: ... + + @overload # type: ignore[override] + def __rsub__(self, other: _Complex64_co, /) -> complexfloating[_NBit1, _NBit2]: ... + @overload + def __rsub__(self, other: complex, /) -> complexfloating[_NBit1, _NBit2] | complex128: ... + @overload + def __rsub__(self, other: number[_NBit], /) -> complexfloating[_NBit1, _NBit2] | complexfloating[_NBit, _NBit]: ... + + @overload # type: ignore[override] + def __mul__(self, other: _Complex64_co, /) -> complexfloating[_NBit1, _NBit2]: ... + @overload + def __mul__(self, other: complex | float64 | complex128, /) -> complexfloating[_NBit1, _NBit2] | complex128: ... + @overload + def __mul__(self, other: number[_NBit], /) -> complexfloating[_NBit1, _NBit2] | complexfloating[_NBit, _NBit]: ... + + @overload # type: ignore[override] + def __rmul__(self, other: _Complex64_co, /) -> complexfloating[_NBit1, _NBit2]: ... + @overload + def __rmul__(self, other: complex, /) -> complexfloating[_NBit1, _NBit2] | complex128: ... + @overload + def __rmul__(self, other: number[_NBit], /) -> complexfloating[_NBit1, _NBit2] | complexfloating[_NBit, _NBit]: ... + + @overload # type: ignore[override] + def __truediv__(self, other: _Complex64_co, /) -> complexfloating[_NBit1, _NBit2]: ... + @overload + def __truediv__(self, other: complex | float64 | complex128, /) -> complexfloating[_NBit1, _NBit2] | complex128: ... + @overload + def __truediv__(self, other: number[_NBit], /) -> complexfloating[_NBit1, _NBit2] | complexfloating[_NBit, _NBit]: ... + + @overload # type: ignore[override] + def __rtruediv__(self, other: _Complex64_co, /) -> complexfloating[_NBit1, _NBit2]: ... + @overload + def __rtruediv__(self, other: complex, /) -> complexfloating[_NBit1, _NBit2] | complex128: ... + @overload + def __rtruediv__(self, other: number[_NBit], /) -> complexfloating[_NBit1, _NBit2] | complexfloating[_NBit, _NBit]: ... + + @overload # type: ignore[override] + def __pow__(self, other: _Complex64_co, mod: None = None, /) -> complexfloating[_NBit1, _NBit2]: ... + @overload + def __pow__( + self, other: complex | float64 | complex128, mod: None = None, / + ) -> complexfloating[_NBit1, _NBit2] | complex128: ... + @overload + def __pow__( + self, other: number[_NBit], mod: None = None, / + ) -> complexfloating[_NBit1, _NBit2] | complexfloating[_NBit, _NBit]: ... + + @overload # type: ignore[override] + def __rpow__(self, other: _Complex64_co, mod: None = None, /) -> complexfloating[_NBit1, _NBit2]: ... + @overload + def __rpow__(self, other: complex, mod: None = None, /) -> complexfloating[_NBit1, _NBit2] | complex128: ... + @overload + def __rpow__( + self, other: number[_NBit], mod: None = None, / + ) -> complexfloating[_NBit1, _NBit2] | complexfloating[_NBit, _NBit]: ... + +complex64: TypeAlias = complexfloating[_32Bit] + +class complex128(complexfloating[_64Bit, _64Bit], complex): + @property + def itemsize(self) -> L[16]: ... + @property + def nbytes(self) -> L[16]: ... + + # overrides for `floating` and `builtins.float` compatibility + @property + def real(self) -> float64: ... + @property + def imag(self) -> float64: ... + def conjugate(self) -> Self: ... + def __abs__(self) -> float64: ... # type: ignore[override] + def __getnewargs__(self, /) -> tuple[float, float]: ... + + # complex128-specific operator overrides + @overload # type: ignore[override] + def __add__(self, other: _Complex128_co, /) -> complex128: ... + @overload + def __add__(self, other: complexfloating[_NBit1, _NBit2], /) -> complexfloating[_NBit1 | _64Bit, _NBit2 | _64Bit]: ... + def __radd__(self, other: _Complex128_co, /) -> complex128: ... # type: ignore[override] + + @overload # type: ignore[override] + def __sub__(self, other: _Complex128_co, /) -> complex128: ... + @overload + def __sub__(self, other: complexfloating[_NBit1, _NBit2], /) -> complexfloating[_NBit1 | _64Bit, _NBit2 | _64Bit]: ... + def __rsub__(self, other: _Complex128_co, /) -> complex128: ... # type: ignore[override] + + @overload # type: ignore[override] + def __mul__(self, other: _Complex128_co, /) -> complex128: ... + @overload + def __mul__(self, other: complexfloating[_NBit1, _NBit2], /) -> complexfloating[_NBit1 | _64Bit, _NBit2 | _64Bit]: ... + def __rmul__(self, other: _Complex128_co, /) -> complex128: ... # type: ignore[override] + + @overload # type: ignore[override] + def __truediv__(self, other: _Complex128_co, /) -> complex128: ... + @overload + def __truediv__(self, other: complexfloating[_NBit1, _NBit2], /) -> complexfloating[_NBit1 | _64Bit, _NBit2 | _64Bit]: ... + def __rtruediv__(self, other: _Complex128_co, /) -> complex128: ... # type: ignore[override] + + @overload # type: ignore[override] + def __pow__(self, other: _Complex128_co, mod: None = None, /) -> complex128: ... + @overload + def __pow__( + self, other: complexfloating[_NBit1, _NBit2], mod: None = None, / + ) -> complexfloating[_NBit1 | _64Bit, _NBit2 | _64Bit]: ... + def __rpow__(self, other: _Complex128_co, mod: None = None, /) -> complex128: ... # type: ignore[override] + +csingle: TypeAlias = complex64 +cdouble: TypeAlias = complex128 +clongdouble: TypeAlias = complexfloating[_NBitLongDouble] + +class timedelta64(_IntegralMixin, generic[_TD64ItemT_co], Generic[_TD64ItemT_co]): + @property + def itemsize(self) -> L[8]: ... + @property + def nbytes(self) -> L[8]: ... + + @overload + def __new__(cls, value: _TD64ItemT_co | timedelta64[_TD64ItemT_co], /) -> Self: ... + @overload + def __new__(cls, /) -> timedelta64[L[0]]: ... + @overload + def __new__(cls, value: _NaTValue | None, format: _TimeUnitSpec, /) -> timedelta64[None]: ... + @overload + def __new__(cls, value: L[0], format: _TimeUnitSpec[_IntTD64Unit] = ..., /) -> timedelta64[L[0]]: ... + @overload + def __new__(cls, value: _IntLike_co, format: _TimeUnitSpec[_IntTD64Unit] = ..., /) -> timedelta64[int]: ... + @overload + def __new__(cls, value: dt.timedelta, format: _TimeUnitSpec[_IntTimeUnit], /) -> timedelta64[int]: ... + @overload + def __new__( + cls, + value: dt.timedelta | _IntLike_co, + format: _TimeUnitSpec[_NativeTD64Unit] = ..., + /, + ) -> timedelta64[dt.timedelta]: ... + @overload + def __new__(cls, value: _ConvertibleToTD64, format: _TimeUnitSpec = ..., /) -> Self: ... + + # inherited at runtime from `signedinteger` + def __class_getitem__(cls, type_arg: type | object, /) -> GenericAlias: ... + + # NOTE: Only a limited number of units support conversion + # to builtin scalar types: `Y`, `M`, `ns`, `ps`, `fs`, `as` + def __int__(self: timedelta64[int], /) -> int: ... + def __float__(self: timedelta64[int], /) -> float: ... + + def __neg__(self, /) -> Self: ... + def __pos__(self, /) -> Self: ... + def __abs__(self, /) -> Self: ... + + @overload + def __add__(self: timedelta64[None], x: _TD64Like_co, /) -> timedelta64[None]: ... + @overload + def __add__(self: timedelta64[int], x: timedelta64[int | dt.timedelta], /) -> timedelta64[int]: ... + @overload + def __add__(self: timedelta64[int], x: timedelta64, /) -> timedelta64[int | None]: ... + @overload + def __add__(self: timedelta64[dt.timedelta], x: _AnyDateOrTime, /) -> _AnyDateOrTime: ... + @overload + def __add__(self: timedelta64[_AnyTD64Item], x: timedelta64[_AnyTD64Item] | _IntLike_co, /) -> timedelta64[_AnyTD64Item]: ... + @overload + def __add__(self, x: timedelta64[None], /) -> timedelta64[None]: ... # type: ignore[overload-cannot-match] + __radd__ = __add__ + + @overload + def __mul__(self: timedelta64[_AnyTD64Item], x: int | np.integer | np.bool, /) -> timedelta64[_AnyTD64Item]: ... + @overload + def __mul__(self: timedelta64[_AnyTD64Item], x: float | np.floating, /) -> timedelta64[_AnyTD64Item | None]: ... + @overload + def __mul__(self, x: float | np.floating | np.integer | np.bool, /) -> timedelta64: ... + __rmul__ = __mul__ + + @overload + def __mod__(self, x: timedelta64[L[0] | None], /) -> timedelta64[None]: ... + @overload + def __mod__(self: timedelta64[None], x: timedelta64, /) -> timedelta64[None]: ... + @overload + def __mod__(self: timedelta64[int], x: timedelta64[int | dt.timedelta], /) -> timedelta64[int | None]: ... + @overload + def __mod__(self: timedelta64[dt.timedelta], x: timedelta64[_AnyTD64Item], /) -> timedelta64[_AnyTD64Item | None]: ... + @overload + def __mod__(self: timedelta64[dt.timedelta], x: dt.timedelta, /) -> dt.timedelta: ... + @overload + def __mod__(self, x: timedelta64[int], /) -> timedelta64[int | None]: ... + @overload + def __mod__(self, x: timedelta64, /) -> timedelta64: ... + + # NOTE: The L[0] makes __mod__ non-commutative, which the first two overloads + # reflect. However, mypy does not seem to like this, so we ignore the errors. + @overload + def __rmod__(self, x: timedelta64[None], /) -> timedelta64[None]: ... # type: ignore[misc] + @overload + def __rmod__(self: timedelta64[L[0] | None], x: timedelta64, /) -> timedelta64[None]: ... + @overload + def __rmod__(self: timedelta64[int], x: timedelta64[int | dt.timedelta], /) -> timedelta64[int | None]: ... # type: ignore[misc] + @overload + def __rmod__(self: timedelta64[dt.timedelta], x: timedelta64[_AnyTD64Item], /) -> timedelta64[_AnyTD64Item | None]: ... # type: ignore[misc] + @overload + def __rmod__(self: timedelta64[dt.timedelta], x: dt.timedelta, /) -> dt.timedelta: ... + @overload + def __rmod__(self, x: timedelta64[int], /) -> timedelta64[int | None]: ... # type: ignore[misc] + @overload + def __rmod__(self, x: timedelta64, /) -> timedelta64: ... # type: ignore[misc] + + # keep in sync with __mod__ + @overload + def __divmod__(self, x: timedelta64[L[0] | None], /) -> tuple[int64, timedelta64[None]]: ... + @overload + def __divmod__(self: timedelta64[None], x: timedelta64, /) -> tuple[int64, timedelta64[None]]: ... + @overload + def __divmod__(self: timedelta64[int], x: timedelta64[int | dt.timedelta], /) -> tuple[int64, timedelta64[int | None]]: ... + @overload + def __divmod__( + self: timedelta64[dt.timedelta], x: timedelta64[_AnyTD64Item], / + ) -> tuple[int64, timedelta64[_AnyTD64Item | None]]: ... + @overload + def __divmod__(self: timedelta64[dt.timedelta], x: dt.timedelta, /) -> tuple[int, dt.timedelta]: ... + @overload + def __divmod__(self, x: timedelta64[int], /) -> tuple[int64, timedelta64[int | None]]: ... + @overload + def __divmod__(self, x: timedelta64, /) -> tuple[int64, timedelta64]: ... + + # keep in sync with __rmod__ + @overload + def __rdivmod__(self, x: timedelta64[None], /) -> tuple[int64, timedelta64[None]]: ... # type: ignore[misc] + @overload + def __rdivmod__(self: timedelta64[L[0] | None], x: timedelta64, /) -> tuple[int64, timedelta64[None]]: ... # type: ignore[misc] + @overload + def __rdivmod__(self: timedelta64[int], x: timedelta64[int | dt.timedelta], /) -> tuple[int64, timedelta64[int | None]]: ... # type: ignore[misc] + @overload + def __rdivmod__( # type: ignore[misc] + self: timedelta64[dt.timedelta], x: timedelta64[_AnyTD64Item], / + ) -> tuple[int64, timedelta64[_AnyTD64Item | None]]: ... + @overload + def __rdivmod__(self: timedelta64[dt.timedelta], x: dt.timedelta, /) -> tuple[int, dt.timedelta]: ... + @overload + def __rdivmod__(self, x: timedelta64[int], /) -> tuple[int64, timedelta64[int | None]]: ... # type: ignore[misc] + @overload + def __rdivmod__(self, x: timedelta64, /) -> tuple[int64, timedelta64]: ... # type: ignore[misc] + + @overload + def __sub__(self: timedelta64[None], b: _TD64Like_co, /) -> timedelta64[None]: ... + @overload + def __sub__(self: timedelta64[int], b: timedelta64[int | dt.timedelta], /) -> timedelta64[int]: ... + @overload + def __sub__(self: timedelta64[int], b: timedelta64, /) -> timedelta64[int | None]: ... + @overload + def __sub__(self: timedelta64[dt.timedelta], b: dt.timedelta, /) -> dt.timedelta: ... + @overload + def __sub__(self: timedelta64[_AnyTD64Item], b: timedelta64[_AnyTD64Item] | _IntLike_co, /) -> timedelta64[_AnyTD64Item]: ... + @overload + def __sub__(self, b: timedelta64[None], /) -> timedelta64[None]: ... # type: ignore[overload-cannot-match] + + # NOTE: subtraction is not commutative, so __rsub__ differs from __sub__. + # This confuses mypy, so we ignore the [misc] errors it reports. + @overload + def __rsub__(self: timedelta64[None], a: _TD64Like_co, /) -> timedelta64[None]: ... + @overload + def __rsub__(self: timedelta64[dt.timedelta], a: _AnyDateOrTime, /) -> _AnyDateOrTime: ... + @overload + def __rsub__(self: timedelta64[dt.timedelta], a: timedelta64[_AnyTD64Item], /) -> timedelta64[_AnyTD64Item]: ... # type: ignore[misc] + @overload + def __rsub__(self: timedelta64[_AnyTD64Item], a: timedelta64[_AnyTD64Item] | _IntLike_co, /) -> timedelta64[_AnyTD64Item]: ... # type: ignore[misc] + @overload + def __rsub__(self, a: timedelta64[None], /) -> timedelta64[None]: ... # type: ignore[overload-cannot-match] + @overload + def __rsub__(self, a: datetime64[None], /) -> datetime64[None]: ... # type: ignore[misc] + + @overload + def __truediv__(self: timedelta64[dt.timedelta], b: dt.timedelta, /) -> float: ... + @overload + def __truediv__(self, b: timedelta64, /) -> float64: ... + @overload + def __truediv__(self: timedelta64[_AnyTD64Item], b: int | integer, /) -> timedelta64[_AnyTD64Item]: ... + @overload + def __truediv__(self: timedelta64[_AnyTD64Item], b: float | floating, /) -> timedelta64[_AnyTD64Item | None]: ... + @overload + def __truediv__(self, b: float | floating | integer, /) -> timedelta64: ... + + @overload + def __rtruediv__(self: timedelta64[dt.timedelta], a: dt.timedelta, /) -> float: ... + @overload + def __rtruediv__(self, a: timedelta64, /) -> float64: ... + + @overload + def __floordiv__(self: timedelta64[dt.timedelta], b: dt.timedelta, /) -> int: ... + @overload + def __floordiv__(self, b: timedelta64, /) -> int64: ... + @overload + def __floordiv__(self: timedelta64[_AnyTD64Item], b: int | integer, /) -> timedelta64[_AnyTD64Item]: ... + @overload + def __floordiv__(self: timedelta64[_AnyTD64Item], b: float | floating, /) -> timedelta64[_AnyTD64Item | None]: ... + + @overload + def __rfloordiv__(self: timedelta64[dt.timedelta], a: dt.timedelta, /) -> int: ... + @overload + def __rfloordiv__(self, a: timedelta64, /) -> int64: ... + + # comparison ops + + @overload + def __lt__(self, other: _TD64Like_co, /) -> bool_: ... + @overload + def __lt__(self, other: _ArrayLikeTD64_co | _NestedSequence[_SupportsGT], /) -> NDArray[bool_]: ... + @overload + def __lt__(self, other: _SupportsGT, /) -> bool_: ... + + @overload + def __le__(self, other: _TD64Like_co, /) -> bool_: ... + @overload + def __le__(self, other: _ArrayLikeTD64_co | _NestedSequence[_SupportsGE], /) -> NDArray[bool_]: ... + @overload + def __le__(self, other: _SupportsGT, /) -> bool_: ... + + @overload + def __gt__(self, other: _TD64Like_co, /) -> bool_: ... + @overload + def __gt__(self, other: _ArrayLikeTD64_co | _NestedSequence[_SupportsLT], /) -> NDArray[bool_]: ... + @overload + def __gt__(self, other: _SupportsGT, /) -> bool_: ... + + @overload + def __ge__(self, other: _TD64Like_co, /) -> bool_: ... + @overload + def __ge__(self, other: _ArrayLikeTD64_co | _NestedSequence[_SupportsLE], /) -> NDArray[bool_]: ... + @overload + def __ge__(self, other: _SupportsGT, /) -> bool_: ... + +class datetime64(_RealMixin, generic[_DT64ItemT_co], Generic[_DT64ItemT_co]): + @property + def itemsize(self) -> L[8]: ... + @property + def nbytes(self) -> L[8]: ... + + @overload + def __new__(cls, value: datetime64[_DT64ItemT_co], /) -> Self: ... + @overload + def __new__(cls, value: _AnyDT64Arg, /) -> datetime64[_AnyDT64Arg]: ... + @overload + def __new__(cls, value: _NaTValue | None = ..., format: _TimeUnitSpec = ..., /) -> datetime64[None]: ... + @overload + def __new__(cls, value: _DT64Now, format: _TimeUnitSpec[_NativeTimeUnit] = ..., /) -> datetime64[dt.datetime]: ... + @overload + def __new__(cls, value: _DT64Date, format: _TimeUnitSpec[_DateUnit] = ..., /) -> datetime64[dt.date]: ... + @overload + def __new__(cls, value: int | bytes | str | dt.date, format: _TimeUnitSpec[_IntTimeUnit], /) -> datetime64[int]: ... + @overload + def __new__( + cls, value: int | bytes | str | dt.date, format: _TimeUnitSpec[_NativeTimeUnit], / + ) -> datetime64[dt.datetime]: ... + @overload + def __new__(cls, value: int | bytes | str | dt.date, format: _TimeUnitSpec[_DateUnit], /) -> datetime64[dt.date]: ... + @overload + def __new__(cls, value: bytes | str | dt.date | None, format: _TimeUnitSpec = ..., /) -> Self: ... + + def __class_getitem__(cls, type_arg: type | object, /) -> GenericAlias: ... + + @overload + def __add__(self: datetime64[_AnyDT64Item], x: int | integer | np.bool, /) -> datetime64[_AnyDT64Item]: ... + @overload + def __add__(self: datetime64[None], x: _TD64Like_co, /) -> datetime64[None]: ... + @overload + def __add__(self: datetime64[int], x: timedelta64[int | dt.timedelta], /) -> datetime64[int]: ... + @overload + def __add__(self: datetime64[dt.datetime], x: timedelta64[dt.timedelta], /) -> datetime64[dt.datetime]: ... + @overload + def __add__(self: datetime64[dt.date], x: timedelta64[dt.timedelta], /) -> datetime64[dt.date]: ... + @overload + def __add__(self: datetime64[dt.date], x: timedelta64[int], /) -> datetime64[int]: ... + @overload + def __add__(self, x: datetime64[None], /) -> datetime64[None]: ... + @overload + def __add__(self, x: _TD64Like_co, /) -> datetime64: ... + __radd__ = __add__ + + @overload + def __sub__(self: datetime64[_AnyDT64Item], x: int | integer | np.bool, /) -> datetime64[_AnyDT64Item]: ... + @overload + def __sub__(self: datetime64[_AnyDate], x: _AnyDate, /) -> dt.timedelta: ... + @overload + def __sub__(self: datetime64[None], x: timedelta64, /) -> datetime64[None]: ... + @overload + def __sub__(self: datetime64[None], x: datetime64, /) -> timedelta64[None]: ... + @overload + def __sub__(self: datetime64[int], x: timedelta64, /) -> datetime64[int]: ... + @overload + def __sub__(self: datetime64[int], x: datetime64, /) -> timedelta64[int]: ... + @overload + def __sub__(self: datetime64[dt.datetime], x: timedelta64[int], /) -> datetime64[int]: ... + @overload + def __sub__(self: datetime64[dt.datetime], x: timedelta64[dt.timedelta], /) -> datetime64[dt.datetime]: ... + @overload + def __sub__(self: datetime64[dt.datetime], x: datetime64[int], /) -> timedelta64[int]: ... + @overload + def __sub__(self: datetime64[dt.date], x: timedelta64[int], /) -> datetime64[dt.date | int]: ... + @overload + def __sub__(self: datetime64[dt.date], x: timedelta64[dt.timedelta], /) -> datetime64[dt.date]: ... + @overload + def __sub__(self: datetime64[dt.date], x: datetime64[dt.date], /) -> timedelta64[dt.timedelta]: ... + @overload + def __sub__(self, x: timedelta64[None], /) -> datetime64[None]: ... + @overload + def __sub__(self, x: datetime64[None], /) -> timedelta64[None]: ... + @overload + def __sub__(self, x: _TD64Like_co, /) -> datetime64: ... + @overload + def __sub__(self, x: datetime64, /) -> timedelta64: ... + + # NOTE: mypy gets confused by the non-commutativity of subtraction here + @overload + def __rsub__(self: datetime64[_AnyDT64Item], x: int | integer | np.bool, /) -> datetime64[_AnyDT64Item]: ... + @overload + def __rsub__(self: datetime64[_AnyDate], x: _AnyDate, /) -> dt.timedelta: ... + @overload + def __rsub__(self: datetime64[None], x: datetime64, /) -> timedelta64[None]: ... + @overload + def __rsub__(self: datetime64[int], x: datetime64, /) -> timedelta64[int]: ... + @overload + def __rsub__(self: datetime64[dt.datetime], x: datetime64[int], /) -> timedelta64[int]: ... # type: ignore[misc] + @overload + def __rsub__(self: datetime64[dt.datetime], x: datetime64[dt.date], /) -> timedelta64[dt.timedelta]: ... # type: ignore[misc] + @overload + def __rsub__(self, x: datetime64[None], /) -> timedelta64[None]: ... # type: ignore[misc] + @overload + def __rsub__(self, x: datetime64, /) -> timedelta64: ... # type: ignore[misc] + + @overload + def __lt__(self, other: datetime64, /) -> bool_: ... + @overload + def __lt__(self, other: _ArrayLikeDT64_co | _NestedSequence[_SupportsGT], /) -> NDArray[bool_]: ... + @overload + def __lt__(self, other: _SupportsGT, /) -> bool_: ... + + @overload + def __le__(self, other: datetime64, /) -> bool_: ... + @overload + def __le__(self, other: _ArrayLikeDT64_co | _NestedSequence[_SupportsGE], /) -> NDArray[bool_]: ... + @overload + def __le__(self, other: _SupportsGT, /) -> bool_: ... + + @overload + def __gt__(self, other: datetime64, /) -> bool_: ... + @overload + def __gt__(self, other: _ArrayLikeDT64_co | _NestedSequence[_SupportsLT], /) -> NDArray[bool_]: ... + @overload + def __gt__(self, other: _SupportsGT, /) -> bool_: ... + + @overload + def __ge__(self, other: datetime64, /) -> bool_: ... + @overload + def __ge__(self, other: _ArrayLikeDT64_co | _NestedSequence[_SupportsLE], /) -> NDArray[bool_]: ... + @overload + def __ge__(self, other: _SupportsGT, /) -> bool_: ... + +@final # cannot be subclassed at runtime +class flexible(_RealMixin, generic[_FlexibleItemT_co], Generic[_FlexibleItemT_co]): ... # type: ignore[misc] + +class void(flexible[bytes | tuple[Any, ...]]): # type: ignore[misc] + @overload + def __new__(cls, length_or_data: _IntLike_co | bytes, /, dtype: None = None) -> Self: ... + @overload + def __new__(cls, length_or_data: object, /, dtype: _DTypeLikeVoid) -> Self: ... + + @overload + def __getitem__(self, key: str | SupportsIndex, /) -> Any: ... + @overload + def __getitem__(self, key: list[str], /) -> void: ... + def __setitem__(self, key: str | list[str] | SupportsIndex, value: ArrayLike, /) -> None: ... + + def setfield(self, val: ArrayLike, dtype: DTypeLike, offset: int = ...) -> None: ... + +class character(flexible[_CharacterItemT_co], Generic[_CharacterItemT_co]): # type: ignore[misc] + @abstractmethod + def __new__(cls, value: object = ..., /) -> Self: ... + +# NOTE: Most `np.bytes_` / `np.str_` methods return their builtin `bytes` / `str` counterpart + +class bytes_(character[bytes], bytes): # type: ignore[misc] + @overload + def __new__(cls, value: object = b"", /) -> Self: ... + @overload + def __new__(cls, value: str, /, encoding: str, errors: str = "strict") -> Self: ... + + # + @override + def __hash__(self, /) -> int: ... + + # + def __bytes__(self, /) -> bytes: ... + +class str_(character[str], str): # type: ignore[misc] + @overload + def __new__(cls, value: object = "", /) -> Self: ... + @overload + def __new__(cls, value: bytes, /, encoding: str, errors: str = "strict") -> Self: ... + + # + @override + def __hash__(self, /) -> int: ... + +# See `numpy._typing._ufunc` for more concrete nin-/nout-specific stubs +@final +class ufunc: + __signature__: Final[inspect.Signature] + + @property + def __name__(self) -> LiteralString: ... + @property + def __qualname__(self) -> LiteralString: ... # pyright: ignore[reportIncompatibleVariableOverride] + @property + def __doc__(self) -> str: ... # type: ignore[override] + @property + def nin(self) -> int: ... + @property + def nout(self) -> int: ... + @property + def nargs(self) -> int: ... + @property + def ntypes(self) -> int: ... + @property + def types(self) -> list[LiteralString]: ... + # Broad return type because it has to encompass things like + # + # >>> np.logical_and.identity is True + # True + # >>> np.add.identity is 0 + # True + # >>> np.sin.identity is None + # True + # + # and any user-defined ufuncs. + @property + def identity(self) -> Any: ... + # This is None for ufuncs and a string for gufuncs. + @property + def signature(self) -> LiteralString | None: ... + + def __call__(self, /, *args: Any, **kwargs: Any) -> Any: ... + + # The next four methods will always exist, but they will just + # raise a ValueError ufuncs with that don't accept two input + # arguments and return one output argument. Because of that we + # can't type them very precisely. + def accumulate( + self, + array: ArrayLike, + /, + axis: SupportsIndex = 0, + dtype: DTypeLike | None = None, + out: ndarray | EllipsisType | None = None, + ) -> NDArray[Incomplete]: ... + def reduce( + self, + array: ArrayLike, + /, + axis: _ShapeLike | None = 0, + dtype: DTypeLike | None = None, + out: ndarray | EllipsisType | None = None, + **kwargs: Incomplete, + ) -> Incomplete: ... + def reduceat( + self, + array: ArrayLike, + /, + indices: _ArrayLikeInt_co, + axis: SupportsIndex = 0, + dtype: DTypeLike | None = None, + out: ndarray | EllipsisType | None = None, + ) -> NDArray[Incomplete]: ... + def outer(self, A: ArrayLike, B: ArrayLike, /, **kwargs: Incomplete) -> NDArray[Incomplete]: ... + + # Similarly `at` won't be defined for ufuncs that return multiple + # outputs, so we can't type it very precisely. + def at(self, a: ndarray, indices: _ArrayLikeInt_co, b: ArrayLike | None = None, /) -> None: ... + + # + def resolve_dtypes( + self, + /, + dtypes: tuple[dtype | type | None, ...], + *, + signature: tuple[dtype | None, ...] | None = None, + casting: _CastingKind | None = None, + reduction: builtins.bool = False, + ) -> tuple[dtype, ...]: ... + +# Parameters: `__name__`, `ntypes` and `identity` +absolute: _UFunc_Nin1_Nout1[L["absolute"], L[20], None] +add: _UFunc_Nin2_Nout1[L["add"], L[22], L[0]] +arccos: _UFunc_Nin1_Nout1[L["arccos"], L[8], None] +arccosh: _UFunc_Nin1_Nout1[L["arccosh"], L[8], None] +arcsin: _UFunc_Nin1_Nout1[L["arcsin"], L[8], None] +arcsinh: _UFunc_Nin1_Nout1[L["arcsinh"], L[8], None] +arctan2: _UFunc_Nin2_Nout1[L["arctan2"], L[5], None] +arctan: _UFunc_Nin1_Nout1[L["arctan"], L[8], None] +arctanh: _UFunc_Nin1_Nout1[L["arctanh"], L[8], None] +bitwise_and: _UFunc_Nin2_Nout1[L["bitwise_and"], L[12], L[-1]] +bitwise_count: _UFunc_Nin1_Nout1[L["bitwise_count"], L[11], None] +bitwise_or: _UFunc_Nin2_Nout1[L["bitwise_or"], L[12], L[0]] +bitwise_xor: _UFunc_Nin2_Nout1[L["bitwise_xor"], L[12], L[0]] +cbrt: _UFunc_Nin1_Nout1[L["cbrt"], L[5], None] +ceil: _UFunc_Nin1_Nout1[L["ceil"], L[7], None] +conjugate: _UFunc_Nin1_Nout1[L["conjugate"], L[18], None] +copysign: _UFunc_Nin2_Nout1[L["copysign"], L[4], None] +cos: _UFunc_Nin1_Nout1[L["cos"], L[9], None] +cosh: _UFunc_Nin1_Nout1[L["cosh"], L[8], None] +deg2rad: _UFunc_Nin1_Nout1[L["deg2rad"], L[5], None] +degrees: _UFunc_Nin1_Nout1[L["degrees"], L[5], None] +divide: _UFunc_Nin2_Nout1[L["divide"], L[11], None] +divmod: _UFunc_Nin2_Nout2[L["divmod"], L[15], None] +equal: _UFunc_Nin2_Nout1[L["equal"], L[23], None] +exp2: _UFunc_Nin1_Nout1[L["exp2"], L[8], None] +exp: _UFunc_Nin1_Nout1[L["exp"], L[10], None] +expm1: _UFunc_Nin1_Nout1[L["expm1"], L[8], None] +fabs: _UFunc_Nin1_Nout1[L["fabs"], L[5], None] +float_power: _UFunc_Nin2_Nout1[L["float_power"], L[4], None] +floor: _UFunc_Nin1_Nout1[L["floor"], L[7], None] +floor_divide: _UFunc_Nin2_Nout1[L["floor_divide"], L[21], None] +fmax: _UFunc_Nin2_Nout1[L["fmax"], L[21], None] +fmin: _UFunc_Nin2_Nout1[L["fmin"], L[21], None] +fmod: _UFunc_Nin2_Nout1[L["fmod"], L[15], None] +frexp: _UFunc_Nin1_Nout2[L["frexp"], L[4], None] +gcd: _UFunc_Nin2_Nout1[L["gcd"], L[11], L[0]] +greater: _UFunc_Nin2_Nout1[L["greater"], L[23], None] +greater_equal: _UFunc_Nin2_Nout1[L["greater_equal"], L[23], None] +heaviside: _UFunc_Nin2_Nout1[L["heaviside"], L[4], None] +hypot: _UFunc_Nin2_Nout1[L["hypot"], L[5], L[0]] +invert: _UFunc_Nin1_Nout1[L["invert"], L[12], None] +isfinite: _UFunc_Nin1_Nout1[L["isfinite"], L[20], None] +isinf: _UFunc_Nin1_Nout1[L["isinf"], L[20], None] +isnan: _UFunc_Nin1_Nout1[L["isnan"], L[20], None] +isnat: _UFunc_Nin1_Nout1[L["isnat"], L[2], None] +lcm: _UFunc_Nin2_Nout1[L["lcm"], L[11], None] +ldexp: _UFunc_Nin2_Nout1[L["ldexp"], L[8], None] +left_shift: _UFunc_Nin2_Nout1[L["left_shift"], L[11], None] +less: _UFunc_Nin2_Nout1[L["less"], L[23], None] +less_equal: _UFunc_Nin2_Nout1[L["less_equal"], L[23], None] +log10: _UFunc_Nin1_Nout1[L["log10"], L[8], None] +log1p: _UFunc_Nin1_Nout1[L["log1p"], L[8], None] +log2: _UFunc_Nin1_Nout1[L["log2"], L[8], None] +log: _UFunc_Nin1_Nout1[L["log"], L[10], None] +logaddexp2: _UFunc_Nin2_Nout1[L["logaddexp2"], L[4], float] +logaddexp: _UFunc_Nin2_Nout1[L["logaddexp"], L[4], float] +logical_and: _UFunc_Nin2_Nout1[L["logical_and"], L[20], L[True]] +logical_not: _UFunc_Nin1_Nout1[L["logical_not"], L[20], None] +logical_or: _UFunc_Nin2_Nout1[L["logical_or"], L[20], L[False]] +logical_xor: _UFunc_Nin2_Nout1[L["logical_xor"], L[19], L[False]] +matmul: _GUFunc_Nin2_Nout1[L["matmul"], L[19], None, L["(n?,k),(k,m?)->(n?,m?)"]] +matvec: _GUFunc_Nin2_Nout1[L["matvec"], L[19], None, L["(m,n),(n)->(m)"]] +maximum: _UFunc_Nin2_Nout1[L["maximum"], L[21], None] +minimum: _UFunc_Nin2_Nout1[L["minimum"], L[21], None] +modf: _UFunc_Nin1_Nout2[L["modf"], L[4], None] +multiply: _UFunc_Nin2_Nout1[L["multiply"], L[23], L[1]] +negative: _UFunc_Nin1_Nout1[L["negative"], L[19], None] +nextafter: _UFunc_Nin2_Nout1[L["nextafter"], L[4], None] +not_equal: _UFunc_Nin2_Nout1[L["not_equal"], L[23], None] +positive: _UFunc_Nin1_Nout1[L["positive"], L[19], None] +power: _UFunc_Nin2_Nout1[L["power"], L[18], None] +rad2deg: _UFunc_Nin1_Nout1[L["rad2deg"], L[5], None] +radians: _UFunc_Nin1_Nout1[L["radians"], L[5], None] +reciprocal: _UFunc_Nin1_Nout1[L["reciprocal"], L[18], None] +remainder: _UFunc_Nin2_Nout1[L["remainder"], L[16], None] +right_shift: _UFunc_Nin2_Nout1[L["right_shift"], L[11], None] +rint: _UFunc_Nin1_Nout1[L["rint"], L[10], None] +sign: _UFunc_Nin1_Nout1[L["sign"], L[19], None] +signbit: _UFunc_Nin1_Nout1[L["signbit"], L[4], None] +sin: _UFunc_Nin1_Nout1[L["sin"], L[9], None] +sinh: _UFunc_Nin1_Nout1[L["sinh"], L[8], None] +spacing: _UFunc_Nin1_Nout1[L["spacing"], L[4], None] +sqrt: _UFunc_Nin1_Nout1[L["sqrt"], L[10], None] +square: _UFunc_Nin1_Nout1[L["square"], L[18], None] +subtract: _UFunc_Nin2_Nout1[L["subtract"], L[21], None] +tan: _UFunc_Nin1_Nout1[L["tan"], L[8], None] +tanh: _UFunc_Nin1_Nout1[L["tanh"], L[8], None] +trunc: _UFunc_Nin1_Nout1[L["trunc"], L[7], None] +vecdot: _GUFunc_Nin2_Nout1[L["vecdot"], L[19], None, L["(n),(n)->()"]] +vecmat: _GUFunc_Nin2_Nout1[L["vecmat"], L[19], None, L["(n),(n,m)->(m)"]] + +abs = absolute +acos = arccos +acosh = arccosh +asin = arcsin +asinh = arcsinh +atan = arctan +atanh = arctanh +atan2 = arctan2 +concat = concatenate +bitwise_left_shift = left_shift +bitwise_not = invert +bitwise_invert = invert +bitwise_right_shift = right_shift +conj = conjugate +mod = remainder +permute_dims = transpose +pow = power +true_divide = divide + +# TODO: The type of each `__next__` and `iters` return-type depends +# on the length and dtype of `args`; we can't describe this behavior yet +# as we lack variadics (PEP 646). +@final +class broadcast: + def __new__(cls, *args: ArrayLike) -> broadcast: ... + @property + def index(self) -> int: ... + @property + def iters(self) -> tuple[flatiter[Any], ...]: ... + @property + def nd(self) -> int: ... + @property + def ndim(self) -> int: ... + @property + def numiter(self) -> int: ... + @property + def shape(self) -> _AnyShape: ... + @property + def size(self) -> int: ... + def __next__(self) -> tuple[Any, ...]: ... + def __iter__(self) -> Self: ... + def reset(self) -> None: ... + +@final +class busdaycalendar: + def __init__( + self, + /, + weekmask: str | Sequence[int | bool_ | integer] | _SupportsArray[dtype[bool_ | integer]] = "1111100", + holidays: Sequence[dt.date | datetime64] | _SupportsArray[dtype[datetime64]] | None = None, + ) -> None: ... + @property + def weekmask(self) -> ndarray[tuple[int], dtype[bool_]]: ... + @property + def holidays(self) -> ndarray[tuple[int], dtype[datetime64[dt.date]]]: ... + +@final +class nditer: + @overload + def __init__( + self, + /, + op: ArrayLike, + flags: Sequence[_NDIterFlagsKind] | None = None, + op_flags: Sequence[_NDIterFlagsOp] | None = None, + op_dtypes: DTypeLike | None = None, + order: _OrderKACF = "K", + casting: _CastingKind = "safe", + op_axes: Sequence[SupportsIndex] | None = None, + itershape: _ShapeLike | None = None, + buffersize: SupportsIndex = 0, + ) -> None: ... + @overload + def __init__( + self, + /, + op: Sequence[ArrayLike | None], + flags: Sequence[_NDIterFlagsKind] | None = None, + op_flags: Sequence[Sequence[_NDIterFlagsOp]] | None = None, + op_dtypes: Sequence[DTypeLike | None] | None = None, + order: _OrderKACF = "K", + casting: _CastingKind = "safe", + op_axes: Sequence[Sequence[SupportsIndex]] | None = None, + itershape: _ShapeLike | None = None, + buffersize: SupportsIndex = 0, + ) -> None: ... + + def __enter__(self) -> nditer: ... + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: ... + def __iter__(self) -> nditer: ... + def __next__(self) -> tuple[NDArray[Any], ...]: ... + def __len__(self) -> int: ... + def __copy__(self) -> nditer: ... + @overload + def __getitem__(self, index: SupportsIndex) -> NDArray[Any]: ... + @overload + def __getitem__(self, index: slice) -> tuple[NDArray[Any], ...]: ... + def __setitem__(self, index: slice | SupportsIndex, value: ArrayLike) -> None: ... + def close(self) -> None: ... + def copy(self) -> nditer: ... + def debug_print(self) -> None: ... + def enable_external_loop(self) -> None: ... + def iternext(self) -> builtins.bool: ... + def remove_axis(self, i: SupportsIndex, /) -> None: ... + def remove_multi_index(self) -> None: ... + def reset(self) -> None: ... + @property + def dtypes(self) -> tuple[dtype, ...]: ... + @property + def finished(self) -> builtins.bool: ... + @property + def has_delayed_bufalloc(self) -> builtins.bool: ... + @property + def has_index(self) -> builtins.bool: ... + @property + def has_multi_index(self) -> builtins.bool: ... + @property + def index(self) -> int: ... + @property + def iterationneedsapi(self) -> builtins.bool: ... + @property + def iterindex(self) -> int: ... + @property + def iterrange(self) -> tuple[int, ...]: ... + @property + def itersize(self) -> int: ... + @property + def itviews(self) -> tuple[NDArray[Any], ...]: ... + @property + def multi_index(self) -> tuple[int, ...]: ... + @property + def ndim(self) -> int: ... + @property + def nop(self) -> int: ... + @property + def operands(self) -> tuple[NDArray[Any], ...]: ... + @property + def shape(self) -> tuple[int, ...]: ... + @property + def value(self) -> tuple[NDArray[Any], ...]: ... + +class memmap(ndarray[_ShapeT_co, _DTypeT_co]): + __array_priority__: ClassVar[float] + filename: str | None + offset: int + mode: str + @overload + def __new__( + subtype, + filename: StrOrBytesPath | _SupportsFileMethodsRW, + dtype: type[uint8] = ..., + mode: _MemMapModeKind = "r+", + offset: int = 0, + shape: int | tuple[int, ...] | None = None, + order: _OrderKACF = "C", + ) -> memmap[Any, dtype[uint8]]: ... + @overload + def __new__( + subtype, + filename: StrOrBytesPath | _SupportsFileMethodsRW, + dtype: _DTypeLike[_ScalarT], + mode: _MemMapModeKind = "r+", + offset: int = 0, + shape: int | tuple[int, ...] | None = None, + order: _OrderKACF = "C", + ) -> memmap[Any, dtype[_ScalarT]]: ... + @overload + def __new__( + subtype, + filename: StrOrBytesPath | _SupportsFileMethodsRW, + dtype: DTypeLike, + mode: _MemMapModeKind = "r+", + offset: int = 0, + shape: int | tuple[int, ...] | None = None, + order: _OrderKACF = "C", + ) -> memmap[Any, dtype]: ... + def __array_finalize__(self, obj: object) -> None: ... + def __array_wrap__( + self, + array: memmap[_ShapeT_co, _DTypeT_co], # type: ignore[override] + context: tuple[ufunc, tuple[Any, ...], int] | None = None, + return_scalar: builtins.bool = False, + ) -> Any: ... + def flush(self) -> None: ... + +class poly1d: + @property + def variable(self) -> LiteralString: ... + @property + def order(self) -> int: ... + @property + def o(self) -> int: ... + @property + def roots(self) -> NDArray[Any]: ... + @property + def r(self) -> NDArray[Any]: ... + + @property + def coeffs(self) -> NDArray[Any]: ... + @coeffs.setter + def coeffs(self, value: NDArray[Any]) -> None: ... + + @property + def c(self) -> NDArray[Any]: ... + @c.setter + def c(self, value: NDArray[Any]) -> None: ... + + @property + def coef(self) -> NDArray[Any]: ... + @coef.setter + def coef(self, value: NDArray[Any]) -> None: ... + + @property + def coefficients(self) -> NDArray[Any]: ... + @coefficients.setter + def coefficients(self, value: NDArray[Any]) -> None: ... + + __hash__: ClassVar[None] # type: ignore[assignment] # pyright: ignore[reportIncompatibleMethodOverride] + + @overload + def __array__(self, /, t: None = None, copy: builtins.bool | None = None) -> ndarray[tuple[int], dtype]: ... + @overload + def __array__(self, /, t: _DTypeT, copy: builtins.bool | None = None) -> ndarray[tuple[int], _DTypeT]: ... + + @overload + def __call__(self, val: _ScalarLike_co) -> Any: ... + @overload + def __call__(self, val: poly1d) -> poly1d: ... + @overload + def __call__(self, val: ArrayLike) -> NDArray[Any]: ... + + def __init__( + self, + c_or_r: ArrayLike, + r: builtins.bool = False, + variable: str | None = None, + ) -> None: ... + def __len__(self) -> int: ... + def __neg__(self) -> poly1d: ... + def __pos__(self) -> poly1d: ... + def __mul__(self, other: ArrayLike, /) -> poly1d: ... + def __rmul__(self, other: ArrayLike, /) -> poly1d: ... + def __add__(self, other: ArrayLike, /) -> poly1d: ... + def __radd__(self, other: ArrayLike, /) -> poly1d: ... + def __pow__(self, val: _FloatLike_co, /) -> poly1d: ... # Integral floats are accepted + def __sub__(self, other: ArrayLike, /) -> poly1d: ... + def __rsub__(self, other: ArrayLike, /) -> poly1d: ... + def __truediv__(self, other: ArrayLike, /) -> poly1d: ... + def __rtruediv__(self, other: ArrayLike, /) -> poly1d: ... + def __getitem__(self, val: int, /) -> Any: ... + def __setitem__(self, key: int, val: Any, /) -> None: ... + def __iter__(self) -> Iterator[Any]: ... + def deriv(self, m: SupportsInt | SupportsIndex = 1) -> poly1d: ... + def integ( + self, + m: SupportsInt | SupportsIndex = 1, + k: _ArrayLikeComplex_co | _ArrayLikeObject_co | None = 0, + ) -> poly1d: ... + +def from_dlpack( + x: _SupportsDLPack[None], + /, + *, + device: L["cpu"] | None = None, + copy: builtins.bool | None = None, +) -> NDArray[number | np.bool]: ... diff --git a/TTS/Kokoro/.venv/Lib/site-packages/numpy/_array_api_info.py b/TTS/Kokoro/.venv/Lib/site-packages/numpy/_array_api_info.py new file mode 100644 index 0000000000000000000000000000000000000000..394c4d71fb56dedc0975920d9cd976edf8505385 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/numpy/_array_api_info.py @@ -0,0 +1,346 @@ +""" +Array API Inspection namespace + +This is the namespace for inspection functions as defined by the array API +standard. See +https://data-apis.org/array-api/latest/API_specification/inspection.html for +more details. + +""" +from numpy._core import ( + bool, + complex64, + complex128, + dtype, + float32, + float64, + int8, + int16, + int32, + int64, + intp, + uint8, + uint16, + uint32, + uint64, +) +from numpy._utils import set_module + + +@set_module('numpy') +class __array_namespace_info__: + """ + Get the array API inspection namespace for NumPy. + + The array API inspection namespace defines the following functions: + + - capabilities() + - default_device() + - default_dtypes() + - dtypes() + - devices() + + See + https://data-apis.org/array-api/latest/API_specification/inspection.html + for more details. + + Returns + ------- + info : ModuleType + The array API inspection namespace for NumPy. + + Examples + -------- + >>> info = np.__array_namespace_info__() + >>> info.default_dtypes() + {'real floating': numpy.float64, + 'complex floating': numpy.complex128, + 'integral': numpy.int64, + 'indexing': numpy.int64} + + """ + + def capabilities(self): + """ + Return a dictionary of array API library capabilities. + + The resulting dictionary has the following keys: + + - **"boolean indexing"**: boolean indicating whether an array library + supports boolean indexing. Always ``True`` for NumPy. + + - **"data-dependent shapes"**: boolean indicating whether an array + library supports data-dependent output shapes. Always ``True`` for + NumPy. + + See + https://data-apis.org/array-api/latest/API_specification/generated/array_api.info.capabilities.html + for more details. + + See Also + -------- + __array_namespace_info__.default_device, + __array_namespace_info__.default_dtypes, + __array_namespace_info__.dtypes, + __array_namespace_info__.devices + + Returns + ------- + capabilities : dict + A dictionary of array API library capabilities. + + Examples + -------- + >>> info = np.__array_namespace_info__() + >>> info.capabilities() + {'boolean indexing': True, + 'data-dependent shapes': True, + 'max dimensions': 64} + + """ + return { + "boolean indexing": True, + "data-dependent shapes": True, + "max dimensions": 64, + } + + def default_device(self): + """ + The default device used for new NumPy arrays. + + For NumPy, this always returns ``'cpu'``. + + See Also + -------- + __array_namespace_info__.capabilities, + __array_namespace_info__.default_dtypes, + __array_namespace_info__.dtypes, + __array_namespace_info__.devices + + Returns + ------- + device : str + The default device used for new NumPy arrays. + + Examples + -------- + >>> info = np.__array_namespace_info__() + >>> info.default_device() + 'cpu' + + """ + return "cpu" + + def default_dtypes(self, *, device=None): + """ + The default data types used for new NumPy arrays. + + For NumPy, this always returns the following dictionary: + + - **"real floating"**: ``numpy.float64`` + - **"complex floating"**: ``numpy.complex128`` + - **"integral"**: ``numpy.intp`` + - **"indexing"**: ``numpy.intp`` + + Parameters + ---------- + device : str, optional + The device to get the default data types for. For NumPy, only + ``'cpu'`` is allowed. + + Returns + ------- + dtypes : dict + A dictionary describing the default data types used for new NumPy + arrays. + + See Also + -------- + __array_namespace_info__.capabilities, + __array_namespace_info__.default_device, + __array_namespace_info__.dtypes, + __array_namespace_info__.devices + + Examples + -------- + >>> info = np.__array_namespace_info__() + >>> info.default_dtypes() + {'real floating': numpy.float64, + 'complex floating': numpy.complex128, + 'integral': numpy.int64, + 'indexing': numpy.int64} + + """ + if device not in ["cpu", None]: + raise ValueError( + 'Device not understood. Only "cpu" is allowed, but received:' + f' {device}' + ) + return { + "real floating": dtype(float64), + "complex floating": dtype(complex128), + "integral": dtype(intp), + "indexing": dtype(intp), + } + + def dtypes(self, *, device=None, kind=None): + """ + The array API data types supported by NumPy. + + Note that this function only returns data types that are defined by + the array API. + + Parameters + ---------- + device : str, optional + The device to get the data types for. For NumPy, only ``'cpu'`` is + allowed. + kind : str or tuple of str, optional + The kind of data types to return. If ``None``, all data types are + returned. If a string, only data types of that kind are returned. + If a tuple, a dictionary containing the union of the given kinds + is returned. The following kinds are supported: + + - ``'bool'``: boolean data types (i.e., ``bool``). + - ``'signed integer'``: signed integer data types (i.e., ``int8``, + ``int16``, ``int32``, ``int64``). + - ``'unsigned integer'``: unsigned integer data types (i.e., + ``uint8``, ``uint16``, ``uint32``, ``uint64``). + - ``'integral'``: integer data types. Shorthand for ``('signed + integer', 'unsigned integer')``. + - ``'real floating'``: real-valued floating-point data types + (i.e., ``float32``, ``float64``). + - ``'complex floating'``: complex floating-point data types (i.e., + ``complex64``, ``complex128``). + - ``'numeric'``: numeric data types. Shorthand for ``('integral', + 'real floating', 'complex floating')``. + + Returns + ------- + dtypes : dict + A dictionary mapping the names of data types to the corresponding + NumPy data types. + + See Also + -------- + __array_namespace_info__.capabilities, + __array_namespace_info__.default_device, + __array_namespace_info__.default_dtypes, + __array_namespace_info__.devices + + Examples + -------- + >>> info = np.__array_namespace_info__() + >>> info.dtypes(kind='signed integer') + {'int8': numpy.int8, + 'int16': numpy.int16, + 'int32': numpy.int32, + 'int64': numpy.int64} + + """ + if device not in ["cpu", None]: + raise ValueError( + 'Device not understood. Only "cpu" is allowed, but received:' + f' {device}' + ) + if kind is None: + return { + "bool": dtype(bool), + "int8": dtype(int8), + "int16": dtype(int16), + "int32": dtype(int32), + "int64": dtype(int64), + "uint8": dtype(uint8), + "uint16": dtype(uint16), + "uint32": dtype(uint32), + "uint64": dtype(uint64), + "float32": dtype(float32), + "float64": dtype(float64), + "complex64": dtype(complex64), + "complex128": dtype(complex128), + } + if kind == "bool": + return {"bool": bool} + if kind == "signed integer": + return { + "int8": dtype(int8), + "int16": dtype(int16), + "int32": dtype(int32), + "int64": dtype(int64), + } + if kind == "unsigned integer": + return { + "uint8": dtype(uint8), + "uint16": dtype(uint16), + "uint32": dtype(uint32), + "uint64": dtype(uint64), + } + if kind == "integral": + return { + "int8": dtype(int8), + "int16": dtype(int16), + "int32": dtype(int32), + "int64": dtype(int64), + "uint8": dtype(uint8), + "uint16": dtype(uint16), + "uint32": dtype(uint32), + "uint64": dtype(uint64), + } + if kind == "real floating": + return { + "float32": dtype(float32), + "float64": dtype(float64), + } + if kind == "complex floating": + return { + "complex64": dtype(complex64), + "complex128": dtype(complex128), + } + if kind == "numeric": + return { + "int8": dtype(int8), + "int16": dtype(int16), + "int32": dtype(int32), + "int64": dtype(int64), + "uint8": dtype(uint8), + "uint16": dtype(uint16), + "uint32": dtype(uint32), + "uint64": dtype(uint64), + "float32": dtype(float32), + "float64": dtype(float64), + "complex64": dtype(complex64), + "complex128": dtype(complex128), + } + if isinstance(kind, tuple): + res = {} + for k in kind: + res.update(self.dtypes(kind=k)) + return res + raise ValueError(f"unsupported kind: {kind!r}") + + def devices(self): + """ + The devices supported by NumPy. + + For NumPy, this always returns ``['cpu']``. + + Returns + ------- + devices : list of str + The devices supported by NumPy. + + See Also + -------- + __array_namespace_info__.capabilities, + __array_namespace_info__.default_device, + __array_namespace_info__.default_dtypes, + __array_namespace_info__.dtypes + + Examples + -------- + >>> info = np.__array_namespace_info__() + >>> info.devices() + ['cpu'] + + """ + return ["cpu"] diff --git a/TTS/Kokoro/.venv/Lib/site-packages/numpy/_array_api_info.pyi b/TTS/Kokoro/.venv/Lib/site-packages/numpy/_array_api_info.pyi new file mode 100644 index 0000000000000000000000000000000000000000..742f4aebe288833c411868945458647d57e7dd8b --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/numpy/_array_api_info.pyi @@ -0,0 +1,206 @@ +from typing import ( + Literal, + Never, + TypeAlias, + TypedDict, + TypeVar, + final, + overload, + type_check_only, +) + +import numpy as np + +_Device: TypeAlias = Literal["cpu"] +_DeviceLike: TypeAlias = _Device | None + +_Capabilities = TypedDict( + "_Capabilities", + { + "boolean indexing": Literal[True], + "data-dependent shapes": Literal[True], + }, +) + +_DefaultDTypes = TypedDict( + "_DefaultDTypes", + { + "real floating": np.dtype[np.float64], + "complex floating": np.dtype[np.complex128], + "integral": np.dtype[np.intp], + "indexing": np.dtype[np.intp], + }, +) + +_KindBool: TypeAlias = Literal["bool"] +_KindInt: TypeAlias = Literal["signed integer"] +_KindUInt: TypeAlias = Literal["unsigned integer"] +_KindInteger: TypeAlias = Literal["integral"] +_KindFloat: TypeAlias = Literal["real floating"] +_KindComplex: TypeAlias = Literal["complex floating"] +_KindNumber: TypeAlias = Literal["numeric"] +_Kind: TypeAlias = ( + _KindBool + | _KindInt + | _KindUInt + | _KindInteger + | _KindFloat + | _KindComplex + | _KindNumber +) + +_T1 = TypeVar("_T1") +_T2 = TypeVar("_T2") +_T3 = TypeVar("_T3") +_Permute1: TypeAlias = _T1 | tuple[_T1] +_Permute2: TypeAlias = tuple[_T1, _T2] | tuple[_T2, _T1] +_Permute3: TypeAlias = ( + tuple[_T1, _T2, _T3] | tuple[_T1, _T3, _T2] + | tuple[_T2, _T1, _T3] | tuple[_T2, _T3, _T1] + | tuple[_T3, _T1, _T2] | tuple[_T3, _T2, _T1] +) + +@type_check_only +class _DTypesBool(TypedDict): + bool: np.dtype[np.bool] + +@type_check_only +class _DTypesInt(TypedDict): + int8: np.dtype[np.int8] + int16: np.dtype[np.int16] + int32: np.dtype[np.int32] + int64: np.dtype[np.int64] + +@type_check_only +class _DTypesUInt(TypedDict): + uint8: np.dtype[np.uint8] + uint16: np.dtype[np.uint16] + uint32: np.dtype[np.uint32] + uint64: np.dtype[np.uint64] + +@type_check_only +class _DTypesInteger(_DTypesInt, _DTypesUInt): ... + +@type_check_only +class _DTypesFloat(TypedDict): + float32: np.dtype[np.float32] + float64: np.dtype[np.float64] + +@type_check_only +class _DTypesComplex(TypedDict): + complex64: np.dtype[np.complex64] + complex128: np.dtype[np.complex128] + +@type_check_only +class _DTypesNumber(_DTypesInteger, _DTypesFloat, _DTypesComplex): ... + +@type_check_only +class _DTypes(_DTypesBool, _DTypesNumber): ... + +@type_check_only +class _DTypesUnion(TypedDict, total=False): + bool: np.dtype[np.bool] + int8: np.dtype[np.int8] + int16: np.dtype[np.int16] + int32: np.dtype[np.int32] + int64: np.dtype[np.int64] + uint8: np.dtype[np.uint8] + uint16: np.dtype[np.uint16] + uint32: np.dtype[np.uint32] + uint64: np.dtype[np.uint64] + float32: np.dtype[np.float32] + float64: np.dtype[np.float64] + complex64: np.dtype[np.complex64] + complex128: np.dtype[np.complex128] + +_EmptyDict: TypeAlias = dict[Never, Never] + +@final +class __array_namespace_info__: + __module__: Literal["numpy"] = "numpy" + + def capabilities(self) -> _Capabilities: ... + def default_device(self) -> _Device: ... + def default_dtypes( + self, + *, + device: _DeviceLike = None, + ) -> _DefaultDTypes: ... + def devices(self) -> list[_Device]: ... + + @overload + def dtypes( + self, + *, + device: _DeviceLike = None, + kind: None = None, + ) -> _DTypes: ... + @overload + def dtypes( + self, + *, + device: _DeviceLike = None, + kind: _Permute1[_KindBool], + ) -> _DTypesBool: ... + @overload + def dtypes( + self, + *, + device: _DeviceLike = None, + kind: _Permute1[_KindInt], + ) -> _DTypesInt: ... + @overload + def dtypes( + self, + *, + device: _DeviceLike = None, + kind: _Permute1[_KindUInt], + ) -> _DTypesUInt: ... + @overload + def dtypes( + self, + *, + device: _DeviceLike = None, + kind: _Permute1[_KindFloat], + ) -> _DTypesFloat: ... + @overload + def dtypes( + self, + *, + device: _DeviceLike = None, + kind: _Permute1[_KindComplex], + ) -> _DTypesComplex: ... + @overload + def dtypes( + self, + *, + device: _DeviceLike = None, + kind: ( + _Permute1[_KindInteger] + | _Permute2[_KindInt, _KindUInt] + ), + ) -> _DTypesInteger: ... + @overload + def dtypes( + self, + *, + device: _DeviceLike = None, + kind: ( + _Permute1[_KindNumber] + | _Permute3[_KindInteger, _KindFloat, _KindComplex] + ), + ) -> _DTypesNumber: ... + @overload + def dtypes( + self, + *, + device: _DeviceLike = None, + kind: tuple[()], + ) -> _EmptyDict: ... + @overload + def dtypes( + self, + *, + device: _DeviceLike = None, + kind: tuple[_Kind, ...], + ) -> _DTypesUnion: ... diff --git a/TTS/Kokoro/.venv/Lib/site-packages/numpy/_configtool.py b/TTS/Kokoro/.venv/Lib/site-packages/numpy/_configtool.py new file mode 100644 index 0000000000000000000000000000000000000000..4a0181c7c2c04431eef5365f22445d93853e9f6e --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/numpy/_configtool.py @@ -0,0 +1,39 @@ +import argparse +import sys +from pathlib import Path + +from .lib._utils_impl import get_include +from .version import __version__ + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--version", + action="version", + version=__version__, + help="Print the version and exit.", + ) + parser.add_argument( + "--cflags", + action="store_true", + help="Compile flag needed when using the NumPy headers.", + ) + parser.add_argument( + "--pkgconfigdir", + action="store_true", + help=("Print the pkgconfig directory in which `numpy.pc` is stored " + "(useful for setting $PKG_CONFIG_PATH)."), + ) + args = parser.parse_args() + if not sys.argv[1:]: + parser.print_help() + if args.cflags: + print("-I" + get_include()) + if args.pkgconfigdir: + _path = Path(get_include()) / '..' / 'lib' / 'pkgconfig' + print(_path.resolve()) + + +if __name__ == "__main__": + main() diff --git a/TTS/Kokoro/.venv/Lib/site-packages/numpy/_configtool.pyi b/TTS/Kokoro/.venv/Lib/site-packages/numpy/_configtool.pyi new file mode 100644 index 0000000000000000000000000000000000000000..36eccee36bd0927b6e8efb68195740da729d7cf8 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/numpy/_configtool.pyi @@ -0,0 +1 @@ +def main() -> None: ... diff --git a/TTS/Kokoro/.venv/Lib/site-packages/numpy/_distributor_init.py b/TTS/Kokoro/.venv/Lib/site-packages/numpy/_distributor_init.py new file mode 100644 index 0000000000000000000000000000000000000000..1978a5303c978154518cec4cc47471413ed908da --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/numpy/_distributor_init.py @@ -0,0 +1,15 @@ +""" Distributor init file + +Distributors: you can add custom code here to support particular distributions +of numpy. + +For example, this is a good place to put any BLAS/LAPACK initialization code. + +The numpy standard source distribution will not put code in this file, so you +can safely replace this file with your own version. +""" + +try: + from . import _distributor_init_local # noqa: F401 +except ImportError: + pass diff --git a/TTS/Kokoro/.venv/Lib/site-packages/numpy/_distributor_init.pyi b/TTS/Kokoro/.venv/Lib/site-packages/numpy/_distributor_init.pyi new file mode 100644 index 0000000000000000000000000000000000000000..39dff2cc94a3b752cf8ba2cfb50524a1933065a5 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/numpy/_distributor_init.pyi @@ -0,0 +1 @@ +# intentionally left blank diff --git a/TTS/Kokoro/.venv/Lib/site-packages/numpy/_expired_attrs_2_0.py b/TTS/Kokoro/.venv/Lib/site-packages/numpy/_expired_attrs_2_0.py new file mode 100644 index 0000000000000000000000000000000000000000..410098790a5debd5cf315b44fc63695899018ad0 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/numpy/_expired_attrs_2_0.py @@ -0,0 +1,78 @@ +""" +Dict of expired attributes that are discontinued since 2.0 release. +Each item is associated with a migration note. +""" + +__expired_attributes__ = { + "geterrobj": "Use the np.errstate context manager instead.", + "seterrobj": "Use the np.errstate context manager instead.", + "cast": "Use `np.asarray(arr, dtype=dtype)` instead.", + "source": "Use `inspect.getsource` instead.", + "lookfor": "Search NumPy's documentation directly.", + "who": "Use an IDE variable explorer or `locals()` instead.", + "fastCopyAndTranspose": "Use `arr.T.copy()` instead.", + "set_numeric_ops": + "For the general case, use `PyUFunc_ReplaceLoopBySignature`. " + "For ndarray subclasses, define the ``__array_ufunc__`` method " + "and override the relevant ufunc.", + "NINF": "Use `-np.inf` instead.", + "PINF": "Use `np.inf` instead.", + "NZERO": "Use `-0.0` instead.", + "PZERO": "Use `0.0` instead.", + "add_newdoc": + "It's still available as `np.lib.add_newdoc`.", + "add_docstring": + "It's still available as `np.lib.add_docstring`.", + "add_newdoc_ufunc": + "It's an internal function and doesn't have a replacement.", + "safe_eval": "Use `ast.literal_eval` instead.", + "float_": "Use `np.float64` instead.", + "complex_": "Use `np.complex128` instead.", + "longfloat": "Use `np.longdouble` instead.", + "singlecomplex": "Use `np.complex64` instead.", + "cfloat": "Use `np.complex128` instead.", + "longcomplex": "Use `np.clongdouble` instead.", + "clongfloat": "Use `np.clongdouble` instead.", + "string_": "Use `np.bytes_` instead.", + "unicode_": "Use `np.str_` instead.", + "Inf": "Use `np.inf` instead.", + "Infinity": "Use `np.inf` instead.", + "NaN": "Use `np.nan` instead.", + "infty": "Use `np.inf` instead.", + "issctype": "Use `issubclass(rep, np.generic)` instead.", + "maximum_sctype": + "Use a specific dtype instead. You should avoid relying " + "on any implicit mechanism and select the largest dtype of " + "a kind explicitly in the code.", + "obj2sctype": "Use `np.dtype(obj).type` instead.", + "sctype2char": "Use `np.dtype(obj).char` instead.", + "sctypes": "Access dtypes explicitly instead.", + "issubsctype": "Use `np.issubdtype` instead.", + "set_string_function": + "Use `np.set_printoptions` instead with a formatter for " + "custom printing of NumPy objects.", + "asfarray": "Use `np.asarray` with a proper dtype instead.", + "issubclass_": "Use `issubclass` builtin instead.", + "tracemalloc_domain": "It's now available from `np.lib`.", + "mat": "Use `np.asmatrix` instead.", + "recfromcsv": "Use `np.genfromtxt` with comma delimiter instead.", + "recfromtxt": "Use `np.genfromtxt` instead.", + "deprecate": "Emit `DeprecationWarning` with `warnings.warn` directly, " + "or use `typing.deprecated`.", + "deprecate_with_doc": "Emit `DeprecationWarning` with `warnings.warn` " + "directly, or use `typing.deprecated`.", + "find_common_type": + "Use `numpy.promote_types` or `numpy.result_type` instead. " + "To achieve semantics for the `scalar_types` argument, use " + "`numpy.result_type` and pass the Python values `0`, `0.0`, or `0j`.", + "round_": "Use `np.round` instead.", + "get_array_wrap": "", + "DataSource": "It's still available as `np.lib.npyio.DataSource`.", + "nbytes": "Use `np.dtype().itemsize` instead.", + "byte_bounds": "Now it's available under `np.lib.array_utils.byte_bounds`", + "compare_chararrays": + "It's still available as `np.char.compare_chararrays`.", + "format_parser": "It's still available as `np.rec.format_parser`.", + "alltrue": "Use `np.all` instead.", + "sometrue": "Use `np.any` instead.", +} diff --git a/TTS/Kokoro/.venv/Lib/site-packages/numpy/_expired_attrs_2_0.pyi b/TTS/Kokoro/.venv/Lib/site-packages/numpy/_expired_attrs_2_0.pyi new file mode 100644 index 0000000000000000000000000000000000000000..11cd7a71b50418156f4c2a3840056f09ed64e955 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/numpy/_expired_attrs_2_0.pyi @@ -0,0 +1,61 @@ +from typing import Final, TypedDict, final, type_check_only + +@final +@type_check_only +class _ExpiredAttributesType(TypedDict): + geterrobj: str + seterrobj: str + cast: str + source: str + lookfor: str + who: str + fastCopyAndTranspose: str + set_numeric_ops: str + NINF: str + PINF: str + NZERO: str + PZERO: str + add_newdoc: str + add_docstring: str + add_newdoc_ufunc: str + safe_eval: str + float_: str + complex_: str + longfloat: str + singlecomplex: str + cfloat: str + longcomplex: str + clongfloat: str + string_: str + unicode_: str + Inf: str + Infinity: str + NaN: str + infty: str + issctype: str + maximum_sctype: str + obj2sctype: str + sctype2char: str + sctypes: str + issubsctype: str + set_string_function: str + asfarray: str + issubclass_: str + tracemalloc_domain: str + mat: str + recfromcsv: str + recfromtxt: str + deprecate: str + deprecate_with_doc: str + find_common_type: str + round_: str + get_array_wrap: str + DataSource: str + nbytes: str + byte_bounds: str + compare_chararrays: str + format_parser: str + alltrue: str + sometrue: str + +__expired_attributes__: Final[_ExpiredAttributesType] = ... diff --git a/TTS/Kokoro/.venv/Lib/site-packages/numpy/_globals.py b/TTS/Kokoro/.venv/Lib/site-packages/numpy/_globals.py new file mode 100644 index 0000000000000000000000000000000000000000..c992dbd5dafedfffb839fb47480a2096afb640aa --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/numpy/_globals.py @@ -0,0 +1,121 @@ +""" +Module defining global singleton classes. + +This module raises a RuntimeError if an attempt to reload it is made. In that +way the identities of the classes defined here are fixed and will remain so +even if numpy itself is reloaded. In particular, a function like the following +will still work correctly after numpy is reloaded:: + + def foo(arg=np._NoValue): + if arg is np._NoValue: + ... + +That was not the case when the singleton classes were defined in the numpy +``__init__.py`` file. See gh-7844 for a discussion of the reload problem that +motivated this module. + +""" +import enum + +from ._utils import set_module as _set_module + +__all__ = ['_NoValue', '_CopyMode'] + + +# Disallow reloading this module so as to preserve the identities of the +# classes defined here. +if '_is_loaded' in globals(): + raise RuntimeError('Reloading numpy._globals is not allowed') +_is_loaded = True + + +class _NoValueType: + """Special keyword value. + + The instance of this class may be used as the default value assigned to a + keyword if no other obvious default (e.g., `None`) is suitable, + + Common reasons for using this keyword are: + + - A new keyword is added to a function, and that function forwards its + inputs to another function or method which can be defined outside of + NumPy. For example, ``np.std(x)`` calls ``x.std``, so when a ``keepdims`` + keyword was added that could only be forwarded if the user explicitly + specified ``keepdims``; downstream array libraries may not have added + the same keyword, so adding ``x.std(..., keepdims=keepdims)`` + unconditionally could have broken previously working code. + - A keyword is being deprecated, and a deprecation warning must only be + emitted when the keyword is used. + + """ + __instance = None + + def __new__(cls): + # ensure that only one instance exists + if not cls.__instance: + cls.__instance = super().__new__(cls) + return cls.__instance + + def __repr__(self): + return "" + + +_NoValue = _NoValueType() + + +@_set_module("numpy") +class _CopyMode(enum.Enum): + """ + An enumeration for the copy modes supported + by numpy.copy() and numpy.array(). The following three modes are supported, + + - ALWAYS: This means that a deep copy of the input + array will always be taken. + - IF_NEEDED: This means that a deep copy of the input + array will be taken only if necessary. + - NEVER: This means that the deep copy will never be taken. + If a copy cannot be avoided then a `ValueError` will be + raised. + + Note that the buffer-protocol could in theory do copies. NumPy currently + assumes an object exporting the buffer protocol will never do this. + """ + + ALWAYS = True + NEVER = False + IF_NEEDED = 2 + + def __bool__(self): + # For backwards compatibility + if self == _CopyMode.ALWAYS: + return True + + if self == _CopyMode.NEVER: + return False + + raise ValueError(f"{self} is neither True nor False.") + + +class _SignatureDescriptor: + # A descriptor to store on the ufunc __dict__ that avoids definig a + # signature for the ufunc class/type but allows the instance to have one. + # This is needed because inspect.signature() chokes on normal properties + # (as of 3.14 at least). + # We could also set __signature__ on the instance but this allows deferred + # computation of the signature. + def __get__(self, obj, objtype=None): + # Delay import, not a critical path but need to avoid circular import. + from numpy._core._internal import _ufunc_inspect_signature_builder + + if obj is None: + # could also return None, which is accepted as "not set" by + # inspect.signature(). + raise AttributeError( + "type object 'numpy.ufunc' has no attribute '__signature__'") + + # Store on the instance, after this the descriptor won't be used. + obj.__signature__ = _ufunc_inspect_signature_builder(obj) + return obj.__signature__ + + +_signature_descriptor = _SignatureDescriptor() diff --git a/TTS/Kokoro/.venv/Lib/site-packages/numpy/_globals.pyi b/TTS/Kokoro/.venv/Lib/site-packages/numpy/_globals.pyi new file mode 100644 index 0000000000000000000000000000000000000000..bb01831b8d7ad472317c53470f7a6289fd02b1c1 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/numpy/_globals.pyi @@ -0,0 +1,17 @@ +__all__ = ["_CopyMode", "_NoValue"] + +import enum +from typing import Final, final + +@final +class _CopyMode(enum.Enum): + ALWAYS = True + NEVER = False + IF_NEEDED = 2 + + def __bool__(self, /) -> bool: ... + +@final +class _NoValueType: ... + +_NoValue: Final[_NoValueType] = ... diff --git a/TTS/Kokoro/.venv/Lib/site-packages/numpy/_pytesttester.py b/TTS/Kokoro/.venv/Lib/site-packages/numpy/_pytesttester.py new file mode 100644 index 0000000000000000000000000000000000000000..7a92c9855f96eeeeab49e6ae369234d421cdc7bd --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/numpy/_pytesttester.py @@ -0,0 +1,201 @@ +""" +Pytest test running. + +This module implements the ``test()`` function for NumPy modules. The usual +boiler plate for doing that is to put the following in the module +``__init__.py`` file:: + + from numpy._pytesttester import PytestTester + test = PytestTester(__name__) + del PytestTester + + +Warnings filtering and other runtime settings should be dealt with in the +``pytest.ini`` file in the numpy repo root. The behavior of the test depends on +whether or not that file is found as follows: + +* ``pytest.ini`` is present (develop mode) + All warnings except those explicitly filtered out are raised as error. +* ``pytest.ini`` is absent (release mode) + DeprecationWarnings and PendingDeprecationWarnings are ignored, other + warnings are passed through. + +In practice, tests run from the numpy repo are run in development mode with +``spin``, through the standard ``spin test`` invocation or from an inplace +build with ``pytest numpy``. + +This module is imported by every numpy subpackage, so lies at the top level to +simplify circular import issues. For the same reason, it contains no numpy +imports at module scope, instead importing numpy within function calls. +""" +import os +import sys + +__all__ = ['PytestTester'] + + +def _show_numpy_info(): + import numpy as np + + print(f"NumPy version {np.__version__}") + info = np.lib._utils_impl._opt_info() + print("NumPy CPU features: ", (info or 'nothing enabled')) + + +class PytestTester: + """ + Pytest test runner. + + A test function is typically added to a package's __init__.py like so:: + + from numpy._pytesttester import PytestTester + test = PytestTester(__name__).test + del PytestTester + + Calling this test function finds and runs all tests associated with the + module and all its sub-modules. + + Attributes + ---------- + module_name : str + Full path to the package to test. + + Parameters + ---------- + module_name : module name + The name of the module to test. + + Notes + ----- + Unlike the previous ``nose``-based implementation, this class is not + publicly exposed as it performs some ``numpy``-specific warning + suppression. + + """ + def __init__(self, module_name): + self.module_name = module_name + self.__module__ = module_name + + def __call__(self, label='fast', verbose=1, extra_argv=None, + doctests=False, coverage=False, durations=-1, tests=None): + """ + Run tests for module using pytest. + + Parameters + ---------- + label : {'fast', 'full'}, optional + Identifies the tests to run. When set to 'fast', tests decorated + with `pytest.mark.slow` are skipped, when 'full', the slow marker + is ignored. + verbose : int, optional + Verbosity value for test outputs, in the range 1-3. Default is 1. + extra_argv : list, optional + List with any extra arguments to pass to pytests. + doctests : bool, optional + .. note:: Not supported + coverage : bool, optional + If True, report coverage of NumPy code. Default is False. + Requires installation of (pip) pytest-cov. + durations : int, optional + If < 0, do nothing, If 0, report time of all tests, if > 0, + report the time of the slowest `timer` tests. Default is -1. + tests : test or list of tests + Tests to be executed with pytest '--pyargs' + + Returns + ------- + result : bool + Return True on success, false otherwise. + + Notes + ----- + Each NumPy module exposes `test` in its namespace to run all tests for + it. For example, to run all tests for numpy.lib: + + >>> np.lib.test() #doctest: +SKIP + + Examples + -------- + >>> result = np.lib.test() #doctest: +SKIP + ... + 1023 passed, 2 skipped, 6 deselected, 1 xfailed in 10.39 seconds + >>> result + True + + """ + import warnings + + import pytest + + module = sys.modules[self.module_name] + module_path = os.path.abspath(module.__path__[0]) + + # setup the pytest arguments + pytest_args = ["-l"] + + # offset verbosity. The "-q" cancels a "-v". + pytest_args += ["-q"] + + if sys.version_info < (3, 12): + with warnings.catch_warnings(): + warnings.simplefilter("always") + # Filter out distutils cpu warnings (could be localized to + # distutils tests). ASV has problems with top level import, + # so fetch module for suppression here. + from numpy.distutils import cpuinfo # noqa: F401 + + # Filter out annoying import messages. Want these in both develop and + # release mode. + pytest_args += [ + "-W ignore:Not importing directory", + "-W ignore:numpy.dtype size changed", + "-W ignore:numpy.ufunc size changed", + "-W ignore::UserWarning:cpuinfo", + ] + + # When testing matrices, ignore their PendingDeprecationWarnings + pytest_args += [ + "-W ignore:the matrix subclass is not", + "-W ignore:Importing from numpy.matlib is", + ] + + if doctests: + pytest_args += ["--doctest-modules"] + + if extra_argv: + pytest_args += list(extra_argv) + + if verbose > 1: + pytest_args += ["-" + "v" * (verbose - 1)] + + if coverage: + pytest_args += ["--cov=" + module_path] + + if label == "fast": + # not importing at the top level to avoid circular import of module + from numpy.testing import IS_PYPY + if IS_PYPY: + pytest_args += ["-m", "not slow and not slow_pypy"] + else: + pytest_args += ["-m", "not slow"] + + elif label != "full": + pytest_args += ["-m", label] + + if durations >= 0: + pytest_args += [f"--durations={durations}"] + + if tests is None: + tests = [self.module_name] + + pytest_args += ["--pyargs"] + list(tests) + + # run tests. + _show_numpy_info() + + try: + code = pytest.main(pytest_args) + except SystemExit as exc: + code = exc.code + + return code == 0 diff --git a/TTS/Kokoro/.venv/Lib/site-packages/numpy/_pytesttester.pyi b/TTS/Kokoro/.venv/Lib/site-packages/numpy/_pytesttester.pyi new file mode 100644 index 0000000000000000000000000000000000000000..576d40e6db47a25c78f4a344fe3a16051fd57ff6 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/numpy/_pytesttester.pyi @@ -0,0 +1,18 @@ +from collections.abc import Iterable +from typing import Literal as L + +__all__ = ["PytestTester"] + +class PytestTester: + module_name: str + def __init__(self, module_name: str) -> None: ... + def __call__( + self, + label: L["fast", "full"] = "fast", + verbose: int = 1, + extra_argv: Iterable[str] | None = None, + doctests: L[False] = False, + coverage: bool = False, + durations: int = -1, + tests: Iterable[str] | None = None, + ) -> bool: ... diff --git a/TTS/Kokoro/.venv/Lib/site-packages/numpy/conftest.py b/TTS/Kokoro/.venv/Lib/site-packages/numpy/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..47493a2df26a449c0d46c11553276df10f1c5015 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/numpy/conftest.py @@ -0,0 +1,248 @@ +""" +Pytest configuration and fixtures for the Numpy test suite. +""" +import os +import sys +import tempfile +import warnings +from contextlib import contextmanager +from pathlib import Path + +import hypothesis +import pytest + +import numpy +from numpy._core._multiarray_tests import get_fpu_mode +from numpy.testing._private.utils import NOGIL_BUILD + +try: + from scipy_doctest.conftest import dt_config + HAVE_SCPDT = True +except ModuleNotFoundError: + HAVE_SCPDT = False + +try: + import pytest_run_parallel # noqa: F401 + PARALLEL_RUN_AVALIABLE = True +except ModuleNotFoundError: + PARALLEL_RUN_AVALIABLE = False + +_old_fpu_mode = None +_collect_results = {} + +# Use a known and persistent tmpdir for hypothesis' caches, which +# can be automatically cleared by the OS or user. +hypothesis.configuration.set_hypothesis_home_dir( + os.path.join(tempfile.gettempdir(), ".hypothesis") +) + +# We register two custom profiles for Numpy - for details see +# https://hypothesis.readthedocs.io/en/latest/settings.html +# The first is designed for our own CI runs; the latter also +# forces determinism and is designed for use via np.test() +hypothesis.settings.register_profile( + name="numpy-profile", deadline=None, print_blob=True, +) +hypothesis.settings.register_profile( + name="np.test() profile", + deadline=None, print_blob=True, database=None, derandomize=True, + suppress_health_check=list(hypothesis.HealthCheck), +) +# Note that the default profile is chosen based on the presence +# of pytest.ini, but can be overridden by passing the +# --hypothesis-profile=NAME argument to pytest. +_pytest_ini = os.path.join(os.path.dirname(__file__), "..", "pytest.ini") +hypothesis.settings.load_profile( + "numpy-profile" if os.path.isfile(_pytest_ini) else "np.test() profile" +) + +# The experimentalAPI is used in _umath_tests +os.environ["NUMPY_EXPERIMENTAL_DTYPE_API"] = "1" + +def pytest_configure(config): + config.addinivalue_line("markers", + "valgrind_error: Tests that are known to error under valgrind.") + config.addinivalue_line("markers", + "leaks_references: Tests that are known to leak references.") + config.addinivalue_line("markers", + "slow: Tests that are very slow.") + config.addinivalue_line("markers", + "slow_pypy: Tests that are very slow on pypy.") + if not PARALLEL_RUN_AVALIABLE: + config.addinivalue_line("markers", + "parallel_threads(n): run the given test function in parallel " + "using `n` threads.", + ) + config.addinivalue_line("markers", + "iterations(n): run the given test function `n` times in each thread", + ) + config.addinivalue_line("markers", + "thread_unsafe: mark the test function as single-threaded", + ) + + +def pytest_addoption(parser): + parser.addoption("--available-memory", action="store", default=None, + help=("Set amount of memory available for running the " + "test suite. This can result to tests requiring " + "especially large amounts of memory to be skipped. " + "Equivalent to setting environment variable " + "NPY_AVAILABLE_MEM. Default: determined" + "automatically.")) + + +gil_enabled_at_start = True +if NOGIL_BUILD: + gil_enabled_at_start = sys._is_gil_enabled() + + +def pytest_sessionstart(session): + available_mem = session.config.getoption('available_memory') + if available_mem is not None: + os.environ['NPY_AVAILABLE_MEM'] = available_mem + + +def pytest_terminal_summary(terminalreporter, exitstatus, config): + if NOGIL_BUILD and not gil_enabled_at_start and sys._is_gil_enabled(): + tr = terminalreporter + tr.ensure_newline() + tr.section("GIL re-enabled", sep="=", red=True, bold=True) + tr.line("The GIL was re-enabled at runtime during the tests.") + tr.line("This can happen with no test failures if the RuntimeWarning") + tr.line("raised by Python when this happens is filtered by a test.") + tr.line("") + tr.line("Please ensure all new C modules declare support for running") + tr.line("without the GIL. Any new tests that intentionally imports ") + tr.line("code that re-enables the GIL should do so in a subprocess.") + pytest.exit("GIL re-enabled during tests", returncode=1) + +# FIXME when yield tests are gone. +@pytest.hookimpl(tryfirst=True) +def pytest_itemcollected(item): + """ + Check FPU precision mode was not changed during test collection. + + The clumsy way we do it here is mainly necessary because numpy + still uses yield tests, which can execute code at test collection + time. + """ + global _old_fpu_mode + + mode = get_fpu_mode() + + if _old_fpu_mode is None: + _old_fpu_mode = mode + elif mode != _old_fpu_mode: + _collect_results[item] = (_old_fpu_mode, mode) + _old_fpu_mode = mode + + # mark f2py tests as thread unsafe + if Path(item.fspath).parent == Path(__file__).parent / 'f2py' / 'tests': + item.add_marker(pytest.mark.thread_unsafe( + reason="f2py tests are thread-unsafe")) + + +@pytest.fixture(scope="function", autouse=True) +def check_fpu_mode(request): + """ + Check FPU precision mode was not changed during the test. + """ + old_mode = get_fpu_mode() + yield + new_mode = get_fpu_mode() + + if old_mode != new_mode: + raise AssertionError(f"FPU precision mode changed from {old_mode:#x} to " + f"{new_mode:#x} during the test") + + collect_result = _collect_results.get(request.node) + if collect_result is not None: + old_mode, new_mode = collect_result + raise AssertionError(f"FPU precision mode changed from {old_mode:#x} to " + f"{new_mode:#x} when collecting the test") + + +@pytest.fixture(autouse=True) +def add_np(doctest_namespace): + doctest_namespace['np'] = numpy + + +if HAVE_SCPDT: + + @contextmanager + def warnings_errors_and_rng(test=None): + """Filter out the wall of DeprecationWarnings. + """ + msgs = ["The numpy.linalg.linalg", + "The numpy.fft.helper", + "dep_util", + "pkg_resources", + "numpy.core.umath", + "msvccompiler", + "Deprecated call", + "numpy.core", + "Importing from numpy.matlib", + "This function is deprecated.", # random_integers + "Data type alias 'a'", # numpy.rec.fromfile + "Arrays of 2-dimensional vectors", # matlib.cross + "NumPy warning suppression and assertion utilities are deprecated." + ] + msg = "|".join(msgs) + + msgs_r = [ + "invalid value encountered", + "divide by zero encountered" + ] + msg_r = "|".join(msgs_r) + + with warnings.catch_warnings(): + warnings.filterwarnings( + 'ignore', category=DeprecationWarning, message=msg + ) + warnings.filterwarnings( + 'ignore', category=RuntimeWarning, message=msg_r + ) + yield + + # find and check doctests under this context manager + dt_config.user_context_mgr = warnings_errors_and_rng + + # numpy specific tweaks from refguide-check + dt_config.rndm_markers.add('#uninitialized') + dt_config.rndm_markers.add('# uninitialized') + + # make the checker pick on mismatched dtypes + dt_config.strict_check = True + + import doctest + dt_config.optionflags = doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS + + # recognize the StringDType repr + dt_config.check_namespace['StringDType'] = numpy.dtypes.StringDType + + # temporary skips + dt_config.skiplist = { + 'numpy.savez', # unclosed file + 'numpy.matlib.savez', + 'numpy.__array_namespace_info__', + 'numpy.matlib.__array_namespace_info__', + } + + # xfail problematic tutorials + dt_config.pytest_extra_xfail = { + 'how-to-verify-bug.rst': '', + 'c-info.ufunc-tutorial.rst': '', + 'basics.interoperability.rst': 'needs pandas', + 'basics.dispatch.rst': 'errors out in /testing/overrides.py', + 'basics.subclassing.rst': '.. testcode:: admonitions not understood', + 'misc.rst': 'manipulates warnings', + } + + # ignores are for things fail doctest collection (optionals etc) + dt_config.pytest_extra_ignore = [ + 'numpy/distutils', + 'numpy/_core/cversions.py', + 'numpy/_pyinstaller', + 'numpy/random/_examples', + 'numpy/f2py/_backends/_distutils.py', + ] diff --git a/TTS/Kokoro/.venv/Lib/site-packages/numpy/dtypes.py b/TTS/Kokoro/.venv/Lib/site-packages/numpy/dtypes.py new file mode 100644 index 0000000000000000000000000000000000000000..6906ae0984870557ad5c5094f07e8bfc250be512 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/numpy/dtypes.py @@ -0,0 +1,41 @@ +""" +This module is home to specific dtypes related functionality and their classes. +For more general information about dtypes, also see `numpy.dtype` and +:ref:`arrays.dtypes`. + +Similar to the builtin ``types`` module, this submodule defines types (classes) +that are not widely used directly. + +.. versionadded:: NumPy 1.25 + + The dtypes module is new in NumPy 1.25. Previously DType classes were + only accessible indirectly. + + +DType classes +------------- + +The following are the classes of the corresponding NumPy dtype instances and +NumPy scalar types. The classes can be used in ``isinstance`` checks and can +also be instantiated or used directly. Direct use of these classes is not +typical, since their scalar counterparts (e.g. ``np.float64``) or strings +like ``"float64"`` can be used. +""" + +# See doc/source/reference/routines.dtypes.rst for module-level docs + +__all__ = [] + + +def _add_dtype_helper(DType, alias): + # Function to add DTypes a bit more conveniently without channeling them + # through `numpy._core._multiarray_umath` namespace or similar. + from numpy import dtypes + + setattr(dtypes, DType.__name__, DType) + __all__.append(DType.__name__) + + if alias: + alias = alias.removeprefix("numpy.dtypes.") + setattr(dtypes, alias, DType) + __all__.append(alias) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/numpy/dtypes.pyi b/TTS/Kokoro/.venv/Lib/site-packages/numpy/dtypes.pyi new file mode 100644 index 0000000000000000000000000000000000000000..fbabd98eeda5de194fdca33bf4f339a1c4e4c541 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/numpy/dtypes.pyi @@ -0,0 +1,630 @@ +# ruff: noqa: ANN401 +from typing import ( + Any, + Generic, + Literal as L, + LiteralString, + Never, + NoReturn, + Self, + TypeAlias, + final, + overload, + type_check_only, +) +from typing_extensions import TypeVar + +import numpy as np + +__all__ = [ # noqa: RUF022 + "BoolDType", + "Int8DType", + "ByteDType", + "UInt8DType", + "UByteDType", + "Int16DType", + "ShortDType", + "UInt16DType", + "UShortDType", + "Int32DType", + "IntDType", + "UInt32DType", + "UIntDType", + "Int64DType", + "LongDType", + "UInt64DType", + "ULongDType", + "LongLongDType", + "ULongLongDType", + "Float16DType", + "Float32DType", + "Float64DType", + "LongDoubleDType", + "Complex64DType", + "Complex128DType", + "CLongDoubleDType", + "ObjectDType", + "BytesDType", + "StrDType", + "VoidDType", + "DateTime64DType", + "TimeDelta64DType", + "StringDType", +] + +# Helper base classes (typing-only) + +_ScalarT_co = TypeVar("_ScalarT_co", bound=np.generic, covariant=True) + +@type_check_only +class _SimpleDType(np.dtype[_ScalarT_co], Generic[_ScalarT_co]): # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] + names: None # pyright: ignore[reportIncompatibleVariableOverride] + def __new__(cls, /) -> Self: ... + def __getitem__(self, key: Any, /) -> NoReturn: ... + @property + def base(self) -> np.dtype[_ScalarT_co]: ... + @property + def fields(self) -> None: ... + @property + def isalignedstruct(self) -> L[False]: ... + @property + def isnative(self) -> L[True]: ... + @property + def ndim(self) -> L[0]: ... + @property + def shape(self) -> tuple[()]: ... + @property + def subdtype(self) -> None: ... + +@type_check_only +class _LiteralDType(_SimpleDType[_ScalarT_co], Generic[_ScalarT_co]): # type: ignore[misc] + @property + def flags(self) -> L[0]: ... + @property + def hasobject(self) -> L[False]: ... + +# Helper mixins (typing-only): + +_KindT_co = TypeVar("_KindT_co", bound=LiteralString, covariant=True) +_CharT_co = TypeVar("_CharT_co", bound=LiteralString, covariant=True) +_NumT_co = TypeVar("_NumT_co", bound=int, covariant=True) + +@type_check_only +class _TypeCodes(Generic[_KindT_co, _CharT_co, _NumT_co]): + @final + @property + def kind(self) -> _KindT_co: ... + @final + @property + def char(self) -> _CharT_co: ... + @final + @property + def num(self) -> _NumT_co: ... + +@type_check_only +class _NoOrder: + @final + @property + def byteorder(self) -> L["|"]: ... + +@type_check_only +class _NativeOrder: + @final + @property + def byteorder(self) -> L["="]: ... + +_DataSize_co = TypeVar("_DataSize_co", bound=int, covariant=True) +_ItemSize_co = TypeVar("_ItemSize_co", bound=int, covariant=True, default=int) + +@type_check_only +class _NBit(Generic[_DataSize_co, _ItemSize_co]): + @final + @property + def alignment(self) -> _DataSize_co: ... + @final + @property + def itemsize(self) -> _ItemSize_co: ... + +@type_check_only +class _8Bit(_NoOrder, _NBit[L[1], L[1]]): ... + +# Boolean: + +@final +class BoolDType( # type: ignore[misc] + _TypeCodes[L["b"], L["?"], L[0]], + _8Bit, + _LiteralDType[np.bool], +): + @property + def name(self) -> L["bool"]: ... + @property + def str(self) -> L["|b1"]: ... + +# Sized integers: + +@final +class Int8DType( # type: ignore[misc] + _TypeCodes[L["i"], L["b"], L[1]], + _8Bit, + _LiteralDType[np.int8], +): + @property + def name(self) -> L["int8"]: ... + @property + def str(self) -> L["|i1"]: ... + +@final +class UInt8DType( # type: ignore[misc] + _TypeCodes[L["u"], L["B"], L[2]], + _8Bit, + _LiteralDType[np.uint8], +): + @property + def name(self) -> L["uint8"]: ... + @property + def str(self) -> L["|u1"]: ... + +@final +class Int16DType( # type: ignore[misc] + _TypeCodes[L["i"], L["h"], L[3]], + _NativeOrder, + _NBit[L[2], L[2]], + _LiteralDType[np.int16], +): + @property + def name(self) -> L["int16"]: ... + @property + def str(self) -> L["i2"]: ... + +@final +class UInt16DType( # type: ignore[misc] + _TypeCodes[L["u"], L["H"], L[4]], + _NativeOrder, + _NBit[L[2], L[2]], + _LiteralDType[np.uint16], +): + @property + def name(self) -> L["uint16"]: ... + @property + def str(self) -> L["u2"]: ... + +@final +class Int32DType( # type: ignore[misc] + _TypeCodes[L["i"], L["i", "l"], L[5, 7]], + _NativeOrder, + _NBit[L[4], L[4]], + _LiteralDType[np.int32], +): + @property + def name(self) -> L["int32"]: ... + @property + def str(self) -> L["i4"]: ... + +@final +class UInt32DType( # type: ignore[misc] + _TypeCodes[L["u"], L["I", "L"], L[6, 8]], + _NativeOrder, + _NBit[L[4], L[4]], + _LiteralDType[np.uint32], +): + @property + def name(self) -> L["uint32"]: ... + @property + def str(self) -> L["u4"]: ... + +@final +class Int64DType( # type: ignore[misc] + _TypeCodes[L["i"], L["l", "q"], L[7, 9]], + _NativeOrder, + _NBit[L[8], L[8]], + _LiteralDType[np.int64], +): + @property + def name(self) -> L["int64"]: ... + @property + def str(self) -> L["i8"]: ... + +@final +class UInt64DType( # type: ignore[misc] + _TypeCodes[L["u"], L["L", "Q"], L[8, 10]], + _NativeOrder, + _NBit[L[8], L[8]], + _LiteralDType[np.uint64], +): + @property + def name(self) -> L["uint64"]: ... + @property + def str(self) -> L["u8"]: ... + +# Standard C-named version/alias: +# NOTE: Don't make these `Final`: it will break stubtest +ByteDType = Int8DType +UByteDType = UInt8DType +ShortDType = Int16DType +UShortDType = UInt16DType + +@final +class IntDType( # type: ignore[misc] + _TypeCodes[L["i"], L["i"], L[5]], + _NativeOrder, + _NBit[L[4], L[4]], + _LiteralDType[np.intc], +): + @property + def name(self) -> L["int32"]: ... + @property + def str(self) -> L["i4"]: ... + +@final +class UIntDType( # type: ignore[misc] + _TypeCodes[L["u"], L["I"], L[6]], + _NativeOrder, + _NBit[L[4], L[4]], + _LiteralDType[np.uintc], +): + @property + def name(self) -> L["uint32"]: ... + @property + def str(self) -> L["u4"]: ... + +@final +class LongDType( # type: ignore[misc] + _TypeCodes[L["i"], L["l"], L[7]], + _NativeOrder, + _NBit[L[4, 8], L[4, 8]], + _LiteralDType[np.long], +): + @property + def name(self) -> L["int32", "int64"]: ... + @property + def str(self) -> L["i4", "i8"]: ... + +@final +class ULongDType( # type: ignore[misc] + _TypeCodes[L["u"], L["L"], L[8]], + _NativeOrder, + _NBit[L[4, 8], L[4, 8]], + _LiteralDType[np.ulong], +): + @property + def name(self) -> L["uint32", "uint64"]: ... + @property + def str(self) -> L["u4", "u8"]: ... + +@final +class LongLongDType( # type: ignore[misc] + _TypeCodes[L["i"], L["q"], L[9]], + _NativeOrder, + _NBit[L[8], L[8]], + _LiteralDType[np.longlong], +): + @property + def name(self) -> L["int64"]: ... + @property + def str(self) -> L["i8"]: ... + +@final +class ULongLongDType( # type: ignore[misc] + _TypeCodes[L["u"], L["Q"], L[10]], + _NativeOrder, + _NBit[L[8], L[8]], + _LiteralDType[np.ulonglong], +): + @property + def name(self) -> L["uint64"]: ... + @property + def str(self) -> L["u8"]: ... + +# Floats: + +@final +class Float16DType( # type: ignore[misc] + _TypeCodes[L["f"], L["e"], L[23]], + _NativeOrder, + _NBit[L[2], L[2]], + _LiteralDType[np.float16], +): + @property + def name(self) -> L["float16"]: ... + @property + def str(self) -> L["f2"]: ... + +@final +class Float32DType( # type: ignore[misc] + _TypeCodes[L["f"], L["f"], L[11]], + _NativeOrder, + _NBit[L[4], L[4]], + _LiteralDType[np.float32], +): + @property + def name(self) -> L["float32"]: ... + @property + def str(self) -> L["f4"]: ... + +@final +class Float64DType( # type: ignore[misc] + _TypeCodes[L["f"], L["d"], L[12]], + _NativeOrder, + _NBit[L[8], L[8]], + _LiteralDType[np.float64], +): + @property + def name(self) -> L["float64"]: ... + @property + def str(self) -> L["f8"]: ... + +@final +class LongDoubleDType( # type: ignore[misc] + _TypeCodes[L["f"], L["g"], L[13]], + _NativeOrder, + _NBit[L[8, 12, 16], L[8, 12, 16]], + _LiteralDType[np.longdouble], +): + @property + def name(self) -> L["float64", "float96", "float128"]: ... + @property + def str(self) -> L["f8", "f12", "f16"]: ... + +# Complex: + +@final +class Complex64DType( # type: ignore[misc] + _TypeCodes[L["c"], L["F"], L[14]], + _NativeOrder, + _NBit[L[4], L[8]], + _LiteralDType[np.complex64], +): + @property + def name(self) -> L["complex64"]: ... + @property + def str(self) -> L["c8"]: ... + +@final +class Complex128DType( # type: ignore[misc] + _TypeCodes[L["c"], L["D"], L[15]], + _NativeOrder, + _NBit[L[8], L[16]], + _LiteralDType[np.complex128], +): + @property + def name(self) -> L["complex128"]: ... + @property + def str(self) -> L["c16"]: ... + +@final +class CLongDoubleDType( # type: ignore[misc] + _TypeCodes[L["c"], L["G"], L[16]], + _NativeOrder, + _NBit[L[8, 12, 16], L[16, 24, 32]], + _LiteralDType[np.clongdouble], +): + @property + def name(self) -> L["complex128", "complex192", "complex256"]: ... + @property + def str(self) -> L["c16", "c24", "c32"]: ... + +# Python objects: + +@final +class ObjectDType( # type: ignore[misc] + _TypeCodes[L["O"], L["O"], L[17]], + _NoOrder, + _NBit[L[8], L[8]], + _SimpleDType[np.object_], +): + @property + def hasobject(self) -> L[True]: ... + @property + def name(self) -> L["object"]: ... + @property + def str(self) -> L["|O"]: ... + +# Flexible: + +@final +class BytesDType( # type: ignore[misc] + _TypeCodes[L["S"], L["S"], L[18]], + _NoOrder, + _NBit[L[1], _ItemSize_co], + _SimpleDType[np.bytes_], + Generic[_ItemSize_co], +): + def __new__(cls, size: _ItemSize_co, /) -> BytesDType[_ItemSize_co]: ... + @property + def hasobject(self) -> L[False]: ... + @property + def name(self) -> LiteralString: ... + @property + def str(self) -> LiteralString: ... + +@final +class StrDType( # type: ignore[misc] + _TypeCodes[L["U"], L["U"], L[19]], + _NativeOrder, + _NBit[L[4], _ItemSize_co], + _SimpleDType[np.str_], + Generic[_ItemSize_co], +): + def __new__(cls, size: _ItemSize_co, /) -> StrDType[_ItemSize_co]: ... + @property + def hasobject(self) -> L[False]: ... + @property + def name(self) -> LiteralString: ... + @property + def str(self) -> LiteralString: ... + +@final +class VoidDType( # type: ignore[misc] + _TypeCodes[L["V"], L["V"], L[20]], + _NoOrder, + _NBit[L[1], _ItemSize_co], + np.dtype[np.void], # pyright: ignore[reportGeneralTypeIssues] + Generic[_ItemSize_co], +): + # NOTE: `VoidDType(...)` raises a `TypeError` at the moment + def __new__(cls, length: _ItemSize_co, /) -> NoReturn: ... + @property + def base(self) -> Self: ... + @property + def isalignedstruct(self) -> L[False]: ... + @property + def isnative(self) -> L[True]: ... + @property + def ndim(self) -> L[0]: ... + @property + def shape(self) -> tuple[()]: ... + @property + def subdtype(self) -> None: ... + @property + def name(self) -> LiteralString: ... + @property + def str(self) -> LiteralString: ... + +# Other: + +_DateUnit: TypeAlias = L["Y", "M", "W", "D"] +_TimeUnit: TypeAlias = L["h", "m", "s", "ms", "us", "ns", "ps", "fs", "as"] +_DateTimeUnit: TypeAlias = _DateUnit | _TimeUnit + +@final +class DateTime64DType( # type: ignore[misc] + _TypeCodes[L["M"], L["M"], L[21]], + _NativeOrder, + _NBit[L[8], L[8]], + _LiteralDType[np.datetime64], +): + # NOTE: `DateTime64DType(...)` raises a `TypeError` at the moment + # TODO: Once implemented, don't forget the`unit: L["μs"]` overload. + def __new__(cls, unit: _DateTimeUnit, /) -> NoReturn: ... + @property + def name(self) -> L[ + "datetime64", + "datetime64[Y]", + "datetime64[M]", + "datetime64[W]", + "datetime64[D]", + "datetime64[h]", + "datetime64[m]", + "datetime64[s]", + "datetime64[ms]", + "datetime64[us]", + "datetime64[ns]", + "datetime64[ps]", + "datetime64[fs]", + "datetime64[as]", + ]: ... + @property + def str(self) -> L[ + "M8", + "M8[Y]", + "M8[M]", + "M8[W]", + "M8[D]", + "M8[h]", + "M8[m]", + "M8[s]", + "M8[ms]", + "M8[us]", + "M8[ns]", + "M8[ps]", + "M8[fs]", + "M8[as]", + ]: ... + +@final +class TimeDelta64DType( # type: ignore[misc] + _TypeCodes[L["m"], L["m"], L[22]], + _NativeOrder, + _NBit[L[8], L[8]], + _LiteralDType[np.timedelta64], +): + # NOTE: `TimeDelta64DType(...)` raises a `TypeError` at the moment + # TODO: Once implemented, don't forget to overload on `unit: L["μs"]`. + def __new__(cls, unit: _DateTimeUnit, /) -> NoReturn: ... + @property + def name(self) -> L[ + "timedelta64", + "timedelta64[Y]", + "timedelta64[M]", + "timedelta64[W]", + "timedelta64[D]", + "timedelta64[h]", + "timedelta64[m]", + "timedelta64[s]", + "timedelta64[ms]", + "timedelta64[us]", + "timedelta64[ns]", + "timedelta64[ps]", + "timedelta64[fs]", + "timedelta64[as]", + ]: ... + @property + def str(self) -> L[ + "m8", + "m8[Y]", + "m8[M]", + "m8[W]", + "m8[D]", + "m8[h]", + "m8[m]", + "m8[s]", + "m8[ms]", + "m8[us]", + "m8[ns]", + "m8[ps]", + "m8[fs]", + "m8[as]", + ]: ... + +_NaObjectT_co = TypeVar("_NaObjectT_co", default=Never, covariant=True) + +@final +class StringDType( # type: ignore[misc] + _TypeCodes[L["T"], L["T"], L[2056]], + _NativeOrder, + _NBit[L[8], L[16]], + # TODO(jorenham): change once we have a string scalar type: + # https://github.com/numpy/numpy/issues/28165 + np.dtype[str], # type: ignore[type-var] # pyright: ignore[reportGeneralTypeIssues, reportInvalidTypeArguments] + Generic[_NaObjectT_co], +): + @property + def na_object(self) -> _NaObjectT_co: ... + @property + def coerce(self) -> L[True]: ... + + # + @overload + def __new__(cls, /, *, coerce: bool = True) -> Self: ... + @overload + def __new__(cls, /, *, na_object: _NaObjectT_co, coerce: bool = True) -> Self: ... + + # + def __getitem__(self, key: Never, /) -> NoReturn: ... # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride] + @property + def fields(self) -> None: ... + @property + def base(self) -> Self: ... + @property + def ndim(self) -> L[0]: ... + @property + def shape(self) -> tuple[()]: ... + + # + @property + def name(self) -> L["StringDType64", "StringDType128"]: ... + @property + def subdtype(self) -> None: ... + @property + def type(self) -> type[str]: ... + @property + def str(self) -> L["|T8", "|T16"]: ... + + # + @property + def hasobject(self) -> L[True]: ... + @property + def isalignedstruct(self) -> L[False]: ... + @property + def isnative(self) -> L[True]: ... diff --git a/TTS/Kokoro/.venv/Lib/site-packages/numpy/exceptions.py b/TTS/Kokoro/.venv/Lib/site-packages/numpy/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..3df39462669b63b5998341ffbb24b47c58495690 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/numpy/exceptions.py @@ -0,0 +1,246 @@ +""" +Exceptions and Warnings +======================= + +General exceptions used by NumPy. Note that some exceptions may be module +specific, such as linear algebra errors. + +.. versionadded:: NumPy 1.25 + + The exceptions module is new in NumPy 1.25. + +.. currentmodule:: numpy.exceptions + +Warnings +-------- +.. autosummary:: + :toctree: generated/ + + ComplexWarning Given when converting complex to real. + VisibleDeprecationWarning Same as a DeprecationWarning, but more visible. + RankWarning Issued when the design matrix is rank deficient. + +Exceptions +---------- +.. autosummary:: + :toctree: generated/ + + AxisError Given when an axis was invalid. + DTypePromotionError Given when no common dtype could be found. + TooHardError Error specific to `numpy.shares_memory`. + +""" + + +__all__ = [ + "ComplexWarning", "VisibleDeprecationWarning", "ModuleDeprecationWarning", + "TooHardError", "AxisError", "DTypePromotionError"] + + +# Disallow reloading this module so as to preserve the identities of the +# classes defined here. +if '_is_loaded' in globals(): + raise RuntimeError('Reloading numpy._globals is not allowed') +_is_loaded = True + + +class ComplexWarning(RuntimeWarning): + """ + The warning raised when casting a complex dtype to a real dtype. + + As implemented, casting a complex number to a real discards its imaginary + part, but this behavior may not be what the user actually wants. + + """ + pass + + +class ModuleDeprecationWarning(DeprecationWarning): + """Module deprecation warning. + + .. warning:: + + This warning should not be used, since nose testing is not relevant + anymore. + + The nose tester turns ordinary Deprecation warnings into test failures. + That makes it hard to deprecate whole modules, because they get + imported by default. So this is a special Deprecation warning that the + nose tester will let pass without making tests fail. + + """ + pass + + +class VisibleDeprecationWarning(UserWarning): + """Visible deprecation warning. + + By default, python will not show deprecation warnings, so this class + can be used when a very visible warning is helpful, for example because + the usage is most likely a user bug. + + """ + pass + + +class RankWarning(RuntimeWarning): + """Matrix rank warning. + + Issued by polynomial functions when the design matrix is rank deficient. + + """ + pass + + +# Exception used in shares_memory() +class TooHardError(RuntimeError): + """``max_work`` was exceeded. + + This is raised whenever the maximum number of candidate solutions + to consider specified by the ``max_work`` parameter is exceeded. + Assigning a finite number to ``max_work`` may have caused the operation + to fail. + + """ + pass + + +class AxisError(ValueError, IndexError): + """Axis supplied was invalid. + + This is raised whenever an ``axis`` parameter is specified that is larger + than the number of array dimensions. + For compatibility with code written against older numpy versions, which + raised a mixture of :exc:`ValueError` and :exc:`IndexError` for this + situation, this exception subclasses both to ensure that + ``except ValueError`` and ``except IndexError`` statements continue + to catch ``AxisError``. + + Parameters + ---------- + axis : int or str + The out of bounds axis or a custom exception message. + If an axis is provided, then `ndim` should be specified as well. + ndim : int, optional + The number of array dimensions. + msg_prefix : str, optional + A prefix for the exception message. + + Attributes + ---------- + axis : int, optional + The out of bounds axis or ``None`` if a custom exception + message was provided. This should be the axis as passed by + the user, before any normalization to resolve negative indices. + + .. versionadded:: 1.22 + ndim : int, optional + The number of array dimensions or ``None`` if a custom exception + message was provided. + + .. versionadded:: 1.22 + + + Examples + -------- + >>> import numpy as np + >>> array_1d = np.arange(10) + >>> np.cumsum(array_1d, axis=1) + Traceback (most recent call last): + ... + numpy.exceptions.AxisError: axis 1 is out of bounds for array of dimension 1 + + Negative axes are preserved: + + >>> np.cumsum(array_1d, axis=-2) + Traceback (most recent call last): + ... + numpy.exceptions.AxisError: axis -2 is out of bounds for array of dimension 1 + + The class constructor generally takes the axis and arrays' + dimensionality as arguments: + + >>> print(np.exceptions.AxisError(2, 1, msg_prefix='error')) + error: axis 2 is out of bounds for array of dimension 1 + + Alternatively, a custom exception message can be passed: + + >>> print(np.exceptions.AxisError('Custom error message')) + Custom error message + + """ + + __slots__ = ("_msg", "axis", "ndim") + + def __init__(self, axis, ndim=None, msg_prefix=None): + if ndim is msg_prefix is None: + # single-argument form: directly set the error message + self._msg = axis + self.axis = None + self.ndim = None + else: + self._msg = msg_prefix + self.axis = axis + self.ndim = ndim + + def __str__(self): + axis = self.axis + ndim = self.ndim + + if axis is ndim is None: + return self._msg + else: + msg = f"axis {axis} is out of bounds for array of dimension {ndim}" + if self._msg is not None: + msg = f"{self._msg}: {msg}" + return msg + + +class DTypePromotionError(TypeError): + """Multiple DTypes could not be converted to a common one. + + This exception derives from ``TypeError`` and is raised whenever dtypes + cannot be converted to a single common one. This can be because they + are of a different category/class or incompatible instances of the same + one (see Examples). + + Notes + ----- + Many functions will use promotion to find the correct result and + implementation. For these functions the error will typically be chained + with a more specific error indicating that no implementation was found + for the input dtypes. + + Typically promotion should be considered "invalid" between the dtypes of + two arrays when `arr1 == arr2` can safely return all ``False`` because the + dtypes are fundamentally different. + + Examples + -------- + Datetimes and complex numbers are incompatible classes and cannot be + promoted: + + >>> import numpy as np + >>> np.result_type(np.dtype("M8[s]"), np.complex128) # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + DTypePromotionError: The DType could not + be promoted by . This means that no common + DType exists for the given inputs. For example they cannot be stored in a + single array unless the dtype is `object`. The full list of DTypes is: + (, ) + + For example for structured dtypes, the structure can mismatch and the + same ``DTypePromotionError`` is given when two structured dtypes with + a mismatch in their number of fields is given: + + >>> dtype1 = np.dtype([("field1", np.float64), ("field2", np.int64)]) + >>> dtype2 = np.dtype([("field1", np.float64)]) + >>> np.promote_types(dtype1, dtype2) # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + DTypePromotionError: field names `('field1', 'field2')` and `('field1',)` + mismatch. + + """ # noqa: E501 + pass diff --git a/TTS/Kokoro/.venv/Lib/site-packages/numpy/exceptions.pyi b/TTS/Kokoro/.venv/Lib/site-packages/numpy/exceptions.pyi new file mode 100644 index 0000000000000000000000000000000000000000..cd7bf05978dc4d3a6abf6966192e05f5261453ff --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/numpy/exceptions.pyi @@ -0,0 +1,27 @@ +from typing import overload + +__all__ = [ + "ComplexWarning", + "VisibleDeprecationWarning", + "ModuleDeprecationWarning", + "TooHardError", + "AxisError", + "DTypePromotionError", +] + +class ComplexWarning(RuntimeWarning): ... +class ModuleDeprecationWarning(DeprecationWarning): ... +class VisibleDeprecationWarning(UserWarning): ... +class RankWarning(RuntimeWarning): ... +class TooHardError(RuntimeError): ... +class DTypePromotionError(TypeError): ... + +class AxisError(ValueError, IndexError): + __slots__ = "_msg", "axis", "ndim" + + axis: int | None + ndim: int | None + @overload + def __init__(self, axis: str, ndim: None = None, msg_prefix: None = None) -> None: ... + @overload + def __init__(self, axis: int, ndim: int, msg_prefix: str | None = None) -> None: ... diff --git a/TTS/Kokoro/.venv/Lib/site-packages/numpy/matlib.py b/TTS/Kokoro/.venv/Lib/site-packages/numpy/matlib.py new file mode 100644 index 0000000000000000000000000000000000000000..f7a9e33d5825c56ad0ea729d4e2fea655933d452 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/numpy/matlib.py @@ -0,0 +1,380 @@ +import warnings + +# 2018-05-29, PendingDeprecationWarning added to matrix.__new__ +# 2020-01-23, numpy 1.19.0 PendingDeprecatonWarning +warnings.warn("Importing from numpy.matlib is deprecated since 1.19.0. " + "The matrix subclass is not the recommended way to represent " + "matrices or deal with linear algebra (see " + "https://docs.scipy.org/doc/numpy/user/numpy-for-matlab-users.html). " + "Please adjust your code to use regular ndarray. ", + PendingDeprecationWarning, stacklevel=2) + +import numpy as np + +# Matlib.py contains all functions in the numpy namespace with a few +# replacements. See doc/source/reference/routines.matlib.rst for details. +# Need * as we're copying the numpy namespace. +from numpy import * # noqa: F403 +from numpy.matrixlib.defmatrix import asmatrix, matrix + +__version__ = np.__version__ + +__all__ = ['rand', 'randn', 'repmat'] +__all__ += np.__all__ + +def empty(shape, dtype=None, order='C'): + """Return a new matrix of given shape and type, without initializing entries. + + Parameters + ---------- + shape : int or tuple of int + Shape of the empty matrix. + dtype : data-type, optional + Desired output data-type. + order : {'C', 'F'}, optional + Whether to store multi-dimensional data in row-major + (C-style) or column-major (Fortran-style) order in + memory. + + See Also + -------- + numpy.empty : Equivalent array function. + matlib.zeros : Return a matrix of zeros. + matlib.ones : Return a matrix of ones. + + Notes + ----- + Unlike other matrix creation functions (e.g. `matlib.zeros`, + `matlib.ones`), `matlib.empty` does not initialize the values of the + matrix, and may therefore be marginally faster. However, the values + stored in the newly allocated matrix are arbitrary. For reproducible + behavior, be sure to set each element of the matrix before reading. + + Examples + -------- + >>> import numpy.matlib + >>> np.matlib.empty((2, 2)) # filled with random data + matrix([[ 6.76425276e-320, 9.79033856e-307], # random + [ 7.39337286e-309, 3.22135945e-309]]) + >>> np.matlib.empty((2, 2), dtype=int) + matrix([[ 6600475, 0], # random + [ 6586976, 22740995]]) + + """ + return ndarray.__new__(matrix, shape, dtype, order=order) + +def ones(shape, dtype=None, order='C'): + """ + Matrix of ones. + + Return a matrix of given shape and type, filled with ones. + + Parameters + ---------- + shape : {sequence of ints, int} + Shape of the matrix + dtype : data-type, optional + The desired data-type for the matrix, default is np.float64. + order : {'C', 'F'}, optional + Whether to store matrix in C- or Fortran-contiguous order, + default is 'C'. + + Returns + ------- + out : matrix + Matrix of ones of given shape, dtype, and order. + + See Also + -------- + ones : Array of ones. + matlib.zeros : Zero matrix. + + Notes + ----- + If `shape` has length one i.e. ``(N,)``, or is a scalar ``N``, + `out` becomes a single row matrix of shape ``(1,N)``. + + Examples + -------- + >>> np.matlib.ones((2,3)) + matrix([[1., 1., 1.], + [1., 1., 1.]]) + + >>> np.matlib.ones(2) + matrix([[1., 1.]]) + + """ + a = ndarray.__new__(matrix, shape, dtype, order=order) + a.fill(1) + return a + +def zeros(shape, dtype=None, order='C'): + """ + Return a matrix of given shape and type, filled with zeros. + + Parameters + ---------- + shape : int or sequence of ints + Shape of the matrix + dtype : data-type, optional + The desired data-type for the matrix, default is float. + order : {'C', 'F'}, optional + Whether to store the result in C- or Fortran-contiguous order, + default is 'C'. + + Returns + ------- + out : matrix + Zero matrix of given shape, dtype, and order. + + See Also + -------- + numpy.zeros : Equivalent array function. + matlib.ones : Return a matrix of ones. + + Notes + ----- + If `shape` has length one i.e. ``(N,)``, or is a scalar ``N``, + `out` becomes a single row matrix of shape ``(1,N)``. + + Examples + -------- + >>> import numpy.matlib + >>> np.matlib.zeros((2, 3)) + matrix([[0., 0., 0.], + [0., 0., 0.]]) + + >>> np.matlib.zeros(2) + matrix([[0., 0.]]) + + """ + a = ndarray.__new__(matrix, shape, dtype, order=order) + a.fill(0) + return a + +def identity(n, dtype=None): + """ + Returns the square identity matrix of given size. + + Parameters + ---------- + n : int + Size of the returned identity matrix. + dtype : data-type, optional + Data-type of the output. Defaults to ``float``. + + Returns + ------- + out : matrix + `n` x `n` matrix with its main diagonal set to one, + and all other elements zero. + + See Also + -------- + numpy.identity : Equivalent array function. + matlib.eye : More general matrix identity function. + + Examples + -------- + >>> import numpy.matlib + >>> np.matlib.identity(3, dtype=int) + matrix([[1, 0, 0], + [0, 1, 0], + [0, 0, 1]]) + + """ + a = array([1] + n * [0], dtype=dtype) + b = empty((n, n), dtype=dtype) + b.flat = a + return b + +def eye(n, M=None, k=0, dtype=float, order='C'): + """ + Return a matrix with ones on the diagonal and zeros elsewhere. + + Parameters + ---------- + n : int + Number of rows in the output. + M : int, optional + Number of columns in the output, defaults to `n`. + k : int, optional + Index of the diagonal: 0 refers to the main diagonal, + a positive value refers to an upper diagonal, + and a negative value to a lower diagonal. + dtype : dtype, optional + Data-type of the returned matrix. + order : {'C', 'F'}, optional + Whether the output should be stored in row-major (C-style) or + column-major (Fortran-style) order in memory. + + Returns + ------- + I : matrix + A `n` x `M` matrix where all elements are equal to zero, + except for the `k`-th diagonal, whose values are equal to one. + + See Also + -------- + numpy.eye : Equivalent array function. + identity : Square identity matrix. + + Examples + -------- + >>> import numpy.matlib + >>> np.matlib.eye(3, k=1, dtype=float) + matrix([[0., 1., 0.], + [0., 0., 1.], + [0., 0., 0.]]) + + """ + return asmatrix(np.eye(n, M=M, k=k, dtype=dtype, order=order)) + +def rand(*args): + """ + Return a matrix of random values with given shape. + + Create a matrix of the given shape and propagate it with + random samples from a uniform distribution over ``[0, 1)``. + + Parameters + ---------- + \\*args : Arguments + Shape of the output. + If given as N integers, each integer specifies the size of one + dimension. + If given as a tuple, this tuple gives the complete shape. + + Returns + ------- + out : ndarray + The matrix of random values with shape given by `\\*args`. + + See Also + -------- + randn, numpy.random.RandomState.rand + + Examples + -------- + >>> np.random.seed(123) + >>> import numpy.matlib + >>> np.matlib.rand(2, 3) + matrix([[0.69646919, 0.28613933, 0.22685145], + [0.55131477, 0.71946897, 0.42310646]]) + >>> np.matlib.rand((2, 3)) + matrix([[0.9807642 , 0.68482974, 0.4809319 ], + [0.39211752, 0.34317802, 0.72904971]]) + + If the first argument is a tuple, other arguments are ignored: + + >>> np.matlib.rand((2, 3), 4) + matrix([[0.43857224, 0.0596779 , 0.39804426], + [0.73799541, 0.18249173, 0.17545176]]) + + """ + if isinstance(args[0], tuple): + args = args[0] + return asmatrix(np.random.rand(*args)) + +def randn(*args): + """ + Return a random matrix with data from the "standard normal" distribution. + + `randn` generates a matrix filled with random floats sampled from a + univariate "normal" (Gaussian) distribution of mean 0 and variance 1. + + Parameters + ---------- + \\*args : Arguments + Shape of the output. + If given as N integers, each integer specifies the size of one + dimension. If given as a tuple, this tuple gives the complete shape. + + Returns + ------- + Z : matrix of floats + A matrix of floating-point samples drawn from the standard normal + distribution. + + See Also + -------- + rand, numpy.random.RandomState.randn + + Notes + ----- + For random samples from the normal distribution with mean ``mu`` and + standard deviation ``sigma``, use:: + + sigma * np.matlib.randn(...) + mu + + Examples + -------- + >>> np.random.seed(123) + >>> import numpy.matlib + >>> np.matlib.randn(1) + matrix([[-1.0856306]]) + >>> np.matlib.randn(1, 2, 3) + matrix([[ 0.99734545, 0.2829785 , -1.50629471], + [-0.57860025, 1.65143654, -2.42667924]]) + + Two-by-four matrix of samples from the normal distribution with + mean 3 and standard deviation 2.5: + + >>> 2.5 * np.matlib.randn((2, 4)) + 3 + matrix([[1.92771843, 6.16484065, 0.83314899, 1.30278462], + [2.76322758, 6.72847407, 1.40274501, 1.8900451 ]]) + + """ + if isinstance(args[0], tuple): + args = args[0] + return asmatrix(np.random.randn(*args)) + +def repmat(a, m, n): + """ + Repeat a 0-D to 2-D array or matrix MxN times. + + Parameters + ---------- + a : array_like + The array or matrix to be repeated. + m, n : int + The number of times `a` is repeated along the first and second axes. + + Returns + ------- + out : ndarray + The result of repeating `a`. + + Examples + -------- + >>> import numpy.matlib + >>> a0 = np.array(1) + >>> np.matlib.repmat(a0, 2, 3) + array([[1, 1, 1], + [1, 1, 1]]) + + >>> a1 = np.arange(4) + >>> np.matlib.repmat(a1, 2, 2) + array([[0, 1, 2, 3, 0, 1, 2, 3], + [0, 1, 2, 3, 0, 1, 2, 3]]) + + >>> a2 = np.asmatrix(np.arange(6).reshape(2, 3)) + >>> np.matlib.repmat(a2, 2, 3) + matrix([[0, 1, 2, 0, 1, 2, 0, 1, 2], + [3, 4, 5, 3, 4, 5, 3, 4, 5], + [0, 1, 2, 0, 1, 2, 0, 1, 2], + [3, 4, 5, 3, 4, 5, 3, 4, 5]]) + + """ + a = asanyarray(a) + ndim = a.ndim + if ndim == 0: + origrows, origcols = (1, 1) + elif ndim == 1: + origrows, origcols = (1, a.shape[0]) + else: + origrows, origcols = a.shape + rows = origrows * m + cols = origcols * n + c = a.reshape(1, a.size).repeat(m, 0).reshape(rows, origcols).repeat(n, 0) + return c.reshape(rows, cols) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/numpy/matlib.pyi b/TTS/Kokoro/.venv/Lib/site-packages/numpy/matlib.pyi new file mode 100644 index 0000000000000000000000000000000000000000..8618b4dc329259f296b2c6850efb599ed02d1fe4 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/numpy/matlib.pyi @@ -0,0 +1,580 @@ +from typing import Any, Literal, TypeAlias, TypeVar, overload + +import numpy as np +import numpy.typing as npt +from numpy import ( # noqa: F401 + False_, + ScalarType, + True_, + __array_namespace_info__, + __version__, + abs, + absolute, + acos, + acosh, + add, + all, + allclose, + amax, + amin, + angle, + any, + append, + apply_along_axis, + apply_over_axes, + arange, + arccos, + arccosh, + arcsin, + arcsinh, + arctan, + arctan2, + arctanh, + argmax, + argmin, + argpartition, + argsort, + argwhere, + around, + array, + array2string, + array_equal, + array_equiv, + array_repr, + array_split, + array_str, + asanyarray, + asarray, + asarray_chkfinite, + ascontiguousarray, + asfortranarray, + asin, + asinh, + asmatrix, + astype, + atan, + atan2, + atanh, + atleast_1d, + atleast_2d, + atleast_3d, + average, + bartlett, + base_repr, + binary_repr, + bincount, + bitwise_and, + bitwise_count, + bitwise_invert, + bitwise_left_shift, + bitwise_not, + bitwise_or, + bitwise_right_shift, + bitwise_xor, + blackman, + block, + bmat, + bool, + bool_, + broadcast, + broadcast_arrays, + broadcast_shapes, + broadcast_to, + busday_count, + busday_offset, + busdaycalendar, + byte, + bytes_, + c_, + can_cast, + cbrt, + cdouble, + ceil, + char, + character, + choose, + clip, + clongdouble, + column_stack, + common_type, + complex64, + complex128, + complex256, + complexfloating, + compress, + concat, + concatenate, + conj, + conjugate, + convolve, + copy, + copysign, + copyto, + core, + corrcoef, + correlate, + cos, + cosh, + count_nonzero, + cov, + cross, + csingle, + ctypeslib, + cumprod, + cumsum, + cumulative_prod, + cumulative_sum, + datetime64, + datetime_as_string, + datetime_data, + deg2rad, + degrees, + delete, + diag, + diag_indices, + diag_indices_from, + diagflat, + diagonal, + diff, + digitize, + divide, + divmod, + dot, + double, + dsplit, + dstack, + dtype, + dtypes, + e, + ediff1d, + einsum, + einsum_path, + emath, + empty_like, + equal, + errstate, + euler_gamma, + exceptions, + exp, + exp2, + expand_dims, + expm1, + extract, + f2py, + fabs, + fft, + fill_diagonal, + finfo, + fix, + flatiter, + flatnonzero, + flexible, + flip, + fliplr, + flipud, + float16, + float32, + float64, + float128, + float_power, + floating, + floor, + floor_divide, + fmax, + fmin, + fmod, + format_float_positional, + format_float_scientific, + frexp, + from_dlpack, + frombuffer, + fromfile, + fromfunction, + fromiter, + frompyfunc, + fromregex, + fromstring, + full, + full_like, + gcd, + generic, + genfromtxt, + geomspace, + get_include, + get_printoptions, + getbufsize, + geterr, + geterrcall, + gradient, + greater, + greater_equal, + half, + hamming, + hanning, + heaviside, + histogram, + histogram2d, + histogram_bin_edges, + histogramdd, + hsplit, + hstack, + hypot, + i0, + iinfo, + imag, + index_exp, + indices, + inexact, + inf, + info, + inner, + insert, + int8, + int16, + int32, + int64, + int_, + intc, + integer, + interp, + intersect1d, + intp, + invert, + is_busday, + isclose, + iscomplex, + iscomplexobj, + isdtype, + isfinite, + isfortran, + isin, + isinf, + isnan, + isnat, + isneginf, + isposinf, + isreal, + isrealobj, + isscalar, + issubdtype, + iterable, + ix_, + kaiser, + kron, + lcm, + ldexp, + left_shift, + less, + less_equal, + lexsort, + lib, + linalg, + linspace, + little_endian, + load, + loadtxt, + log, + log1p, + log2, + log10, + logaddexp, + logaddexp2, + logical_and, + logical_not, + logical_or, + logical_xor, + logspace, + long, + longdouble, + longlong, + ma, + mask_indices, + matmul, + matrix, + matrix_transpose, + matvec, + max, + maximum, + may_share_memory, + mean, + median, + memmap, + meshgrid, + mgrid, + min, + min_scalar_type, + minimum, + mintypecode, + mod, + modf, + moveaxis, + multiply, + nan, + nan_to_num, + nanargmax, + nanargmin, + nancumprod, + nancumsum, + nanmax, + nanmean, + nanmedian, + nanmin, + nanpercentile, + nanprod, + nanquantile, + nanstd, + nansum, + nanvar, + ndarray, + ndenumerate, + ndim, + ndindex, + nditer, + negative, + nested_iters, + newaxis, + nextafter, + nonzero, + not_equal, + number, + object_, + ogrid, + ones_like, + outer, + packbits, + pad, + partition, + percentile, + permute_dims, + pi, + piecewise, + place, + poly, + poly1d, + polyadd, + polyder, + polydiv, + polyfit, + polyint, + polymul, + polynomial, + polysub, + polyval, + positive, + pow, + power, + printoptions, + prod, + promote_types, + ptp, + put, + put_along_axis, + putmask, + quantile, + r_, + rad2deg, + radians, + random, + ravel, + ravel_multi_index, + real, + real_if_close, + rec, + recarray, + reciprocal, + record, + remainder, + repeat, + require, + reshape, + resize, + result_type, + right_shift, + rint, + roll, + rollaxis, + roots, + rot90, + round, + row_stack, + s_, + save, + savetxt, + savez, + savez_compressed, + sctypeDict, + searchsorted, + select, + set_printoptions, + setbufsize, + setdiff1d, + seterr, + seterrcall, + setxor1d, + shape, + shares_memory, + short, + show_config, + show_runtime, + sign, + signbit, + signedinteger, + sin, + sinc, + single, + sinh, + size, + sort, + sort_complex, + spacing, + split, + sqrt, + square, + squeeze, + stack, + std, + str_, + strings, + subtract, + sum, + swapaxes, + take, + take_along_axis, + tan, + tanh, + tensordot, + test, + testing, + tile, + timedelta64, + trace, + transpose, + trapezoid, + tri, + tril, + tril_indices, + tril_indices_from, + trim_zeros, + triu, + triu_indices, + triu_indices_from, + true_divide, + trunc, + typecodes, + typename, + typing, + ubyte, + ufunc, + uint, + uint8, + uint16, + uint32, + uint64, + uintc, + uintp, + ulong, + ulonglong, + union1d, + unique, + unique_all, + unique_counts, + unique_inverse, + unique_values, + unpackbits, + unravel_index, + unsignedinteger, + unstack, + unwrap, + ushort, + vander, + var, + vdot, + vecdot, + vecmat, + vectorize, + void, + vsplit, + vstack, + where, + zeros_like, +) +from numpy._typing import _ArrayLike, _DTypeLike + +__all__ = ["rand", "randn", "repmat"] +__all__ += np.__all__ + +### + +_ScalarT = TypeVar("_ScalarT", bound=np.generic) +_Matrix: TypeAlias = np.matrix[tuple[int, int], np.dtype[_ScalarT]] +_Order: TypeAlias = Literal["C", "F"] + +### + +# +@overload +def empty(shape: int | tuple[int, int], dtype: None = None, order: _Order = "C") -> _Matrix[np.float64]: ... +@overload +def empty(shape: int | tuple[int, int], dtype: _DTypeLike[_ScalarT], order: _Order = "C") -> _Matrix[_ScalarT]: ... +@overload +def empty(shape: int | tuple[int, int], dtype: npt.DTypeLike, order: _Order = "C") -> _Matrix[Any]: ... + +# +@overload +def ones(shape: int | tuple[int, int], dtype: None = None, order: _Order = "C") -> _Matrix[np.float64]: ... +@overload +def ones(shape: int | tuple[int, int], dtype: _DTypeLike[_ScalarT], order: _Order = "C") -> _Matrix[_ScalarT]: ... +@overload +def ones(shape: int | tuple[int, int], dtype: npt.DTypeLike, order: _Order = "C") -> _Matrix[Any]: ... + +# +@overload +def zeros(shape: int | tuple[int, int], dtype: None = None, order: _Order = "C") -> _Matrix[np.float64]: ... +@overload +def zeros(shape: int | tuple[int, int], dtype: _DTypeLike[_ScalarT], order: _Order = "C") -> _Matrix[_ScalarT]: ... +@overload +def zeros(shape: int | tuple[int, int], dtype: npt.DTypeLike, order: _Order = "C") -> _Matrix[Any]: ... + +# +@overload +def identity(n: int, dtype: None = None) -> _Matrix[np.float64]: ... +@overload +def identity(n: int, dtype: _DTypeLike[_ScalarT]) -> _Matrix[_ScalarT]: ... +@overload +def identity(n: int, dtype: npt.DTypeLike | None = None) -> _Matrix[Any]: ... + +# +@overload +def eye( + n: int, + M: int | None = None, + k: int = 0, + dtype: type[np.float64] | None = ..., + order: _Order = "C", +) -> _Matrix[np.float64]: ... +@overload +def eye(n: int, M: int | None, k: int, dtype: _DTypeLike[_ScalarT], order: _Order = "C") -> _Matrix[_ScalarT]: ... +@overload +def eye(n: int, M: int | None = None, k: int = 0, *, dtype: _DTypeLike[_ScalarT], order: _Order = "C") -> _Matrix[_ScalarT]: ... +@overload +def eye(n: int, M: int | None = None, k: int = 0, dtype: npt.DTypeLike | None = ..., order: _Order = "C") -> _Matrix[Any]: ... + +# +@overload +def rand(arg: int | tuple[()] | tuple[int] | tuple[int, int], /) -> _Matrix[np.float64]: ... +@overload +def rand(arg: int, /, *args: int) -> _Matrix[np.float64]: ... + +# +@overload +def randn(arg: int | tuple[()] | tuple[int] | tuple[int, int], /) -> _Matrix[np.float64]: ... +@overload +def randn(arg: int, /, *args: int) -> _Matrix[np.float64]: ... + +# +@overload +def repmat(a: _Matrix[_ScalarT], m: int, n: int) -> _Matrix[_ScalarT]: ... +@overload +def repmat(a: _ArrayLike[_ScalarT], m: int, n: int) -> npt.NDArray[_ScalarT]: ... +@overload +def repmat(a: npt.ArrayLike, m: int, n: int) -> npt.NDArray[Any]: ... diff --git a/TTS/Kokoro/.venv/Lib/site-packages/numpy/py.typed b/TTS/Kokoro/.venv/Lib/site-packages/numpy/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/TTS/Kokoro/.venv/Lib/site-packages/numpy/version.py b/TTS/Kokoro/.venv/Lib/site-packages/numpy/version.py new file mode 100644 index 0000000000000000000000000000000000000000..921df4f91ffc55b9fe2b5a7e0040f7e5b9bc6fac --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/numpy/version.py @@ -0,0 +1,11 @@ + +""" +Module to expose more detailed version info for the installed `numpy` +""" +version = "2.4.2" +__version__ = version +full_version = version + +git_revision = "c81c49f77451340651a751e76bca607d85e4fd55" +release = 'dev' not in version and '+' not in version +short_version = version.split("+")[0] diff --git a/TTS/Kokoro/.venv/Lib/site-packages/numpy/version.pyi b/TTS/Kokoro/.venv/Lib/site-packages/numpy/version.pyi new file mode 100644 index 0000000000000000000000000000000000000000..0eb641b016f8d1ac2db41b0c4733e86d0ceaa6ae --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/numpy/version.pyi @@ -0,0 +1,9 @@ +from typing import Final, LiteralString + +version: Final[LiteralString] = ... +__version__: Final[LiteralString] = ... +full_version: Final[LiteralString] = ... + +git_revision: Final[LiteralString] = ... +release: Final[bool] = ... +short_version: Final[LiteralString] = ... diff --git a/TTS/Kokoro/.venv/Lib/site-packages/packaging-26.0.dist-info/INSTALLER b/TTS/Kokoro/.venv/Lib/site-packages/packaging-26.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/packaging-26.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/TTS/Kokoro/.venv/Lib/site-packages/packaging-26.0.dist-info/METADATA b/TTS/Kokoro/.venv/Lib/site-packages/packaging-26.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..3200e601f970271fdde3fcc74f9af4423655a79d --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/packaging-26.0.dist-info/METADATA @@ -0,0 +1,107 @@ +Metadata-Version: 2.4 +Name: packaging +Version: 26.0 +Summary: Core utilities for Python packages +Author-email: Donald Stufft +Requires-Python: >=3.8 +Description-Content-Type: text/x-rst +License-Expression: Apache-2.0 OR BSD-2-Clause +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Typing :: Typed +License-File: LICENSE +License-File: LICENSE.APACHE +License-File: LICENSE.BSD +Project-URL: Documentation, https://packaging.pypa.io/ +Project-URL: Source, https://github.com/pypa/packaging + +packaging +========= + +.. start-intro + +Reusable core utilities for various Python Packaging +`interoperability specifications `_. + +This library provides utilities that implement the interoperability +specifications which have clearly one correct behaviour (eg: :pep:`440`) +or benefit greatly from having a single shared implementation (eg: :pep:`425`). + +.. end-intro + +The ``packaging`` project includes the following: version handling, specifiers, +markers, requirements, tags, metadata, lockfiles, utilities. + +Documentation +------------- + +The `documentation`_ provides information and the API for the following: + +- Version Handling +- Specifiers +- Markers +- Requirements +- Tags +- Metadata +- Lockfiles +- Utilities + +Installation +------------ + +Use ``pip`` to install these utilities:: + + pip install packaging + +The ``packaging`` library uses calendar-based versioning (``YY.N``). + +Discussion +---------- + +If you run into bugs, you can file them in our `issue tracker`_. + +You can also join ``#pypa`` on Freenode to ask questions or get involved. + + +.. _`documentation`: https://packaging.pypa.io/ +.. _`issue tracker`: https://github.com/pypa/packaging/issues + + +Code of Conduct +--------------- + +Everyone interacting in the packaging project's codebases, issue trackers, chat +rooms, and mailing lists is expected to follow the `PSF Code of Conduct`_. + +.. _PSF Code of Conduct: https://github.com/pypa/.github/blob/main/CODE_OF_CONDUCT.md + +Contributing +------------ + +The ``CONTRIBUTING.rst`` file outlines how to contribute to this project as +well as how to report a potential security issue. The documentation for this +project also covers information about `project development`_ and `security`_. + +.. _`project development`: https://packaging.pypa.io/en/latest/development/ +.. _`security`: https://packaging.pypa.io/en/latest/security/ + +Project History +--------------- + +Please review the ``CHANGELOG.rst`` file or the `Changelog documentation`_ for +recent changes and project history. + +.. _`Changelog documentation`: https://packaging.pypa.io/en/latest/changelog/ + diff --git a/TTS/Kokoro/.venv/Lib/site-packages/packaging-26.0.dist-info/RECORD b/TTS/Kokoro/.venv/Lib/site-packages/packaging-26.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..c4d0eb56787af443d8fe4704d74a9853031450fa --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/packaging-26.0.dist-info/RECORD @@ -0,0 +1,42 @@ +packaging-26.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +packaging-26.0.dist-info/METADATA,sha256=M2K7fWom2iliuo2qpHhc0LrKwhq6kIoRlcyPWVgKJlo,3309 +packaging-26.0.dist-info/RECORD,, +packaging-26.0.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82 +packaging-26.0.dist-info/licenses/LICENSE,sha256=ytHvW9NA1z4HS6YU0m996spceUDD2MNIUuZcSQlobEg,197 +packaging-26.0.dist-info/licenses/LICENSE.APACHE,sha256=DVQuDIgE45qn836wDaWnYhSdxoLXgpRRKH4RuTjpRZQ,10174 +packaging-26.0.dist-info/licenses/LICENSE.BSD,sha256=tw5-m3QvHMb5SLNMFqo5_-zpQZY2S8iP8NIYDwAo-sU,1344 +packaging/__init__.py,sha256=y4lVbpeBzCGk-IPDw5BGBZ_b0P3ukEEJZAbGYc6Ey8c,494 +packaging/__pycache__/__init__.cpython-312.pyc,, +packaging/__pycache__/_elffile.cpython-312.pyc,, +packaging/__pycache__/_manylinux.cpython-312.pyc,, +packaging/__pycache__/_musllinux.cpython-312.pyc,, +packaging/__pycache__/_parser.cpython-312.pyc,, +packaging/__pycache__/_structures.cpython-312.pyc,, +packaging/__pycache__/_tokenizer.cpython-312.pyc,, +packaging/__pycache__/markers.cpython-312.pyc,, +packaging/__pycache__/metadata.cpython-312.pyc,, +packaging/__pycache__/pylock.cpython-312.pyc,, +packaging/__pycache__/requirements.cpython-312.pyc,, +packaging/__pycache__/specifiers.cpython-312.pyc,, +packaging/__pycache__/tags.cpython-312.pyc,, +packaging/__pycache__/utils.cpython-312.pyc,, +packaging/__pycache__/version.cpython-312.pyc,, +packaging/_elffile.py,sha256=-sKkptYqzYw2-x3QByJa5mB4rfPWu1pxkZHRx1WAFCY,3211 +packaging/_manylinux.py,sha256=Hf6nB0cOrayEs96-p3oIXAgGnFquv20DO5l-o2_Xnv0,9559 +packaging/_musllinux.py,sha256=Z6swjH3MA7XS3qXnmMN7QPhqP3fnoYI0eQ18e9-HgAE,2707 +packaging/_parser.py,sha256=U_DajsEx2VoC_F46fSVV3hDKNCWoQYkPkasO3dld0ig,10518 +packaging/_structures.py,sha256=Hn49Ta8zV9Wo8GiCL8Nl2ARZY983Un3pruZGVNldPwE,1514 +packaging/_tokenizer.py,sha256=M8EwNIdXeL9NMFuFrQtiOKwjka_xFx8KjRQnfE8O_z8,5421 +packaging/licenses/__init__.py,sha256=TwXLHZCXwSgdFwRLPxW602T6mSieunSFHM6fp8pgW78,5819 +packaging/licenses/__pycache__/__init__.cpython-312.pyc,, +packaging/licenses/__pycache__/_spdx.cpython-312.pyc,, +packaging/licenses/_spdx.py,sha256=WW7DXiyg68up_YND_wpRYlr1SHhiV4FfJLQffghhMxQ,51122 +packaging/markers.py,sha256=ZX-cLvW1S3cZcEc0fHI4z7zSx5U2T19yMpDP_mE-CYw,12771 +packaging/metadata.py,sha256=CWVZpN_HfoYMSSDuCP7igOvGgqA9AOmpW8f3qTisfnc,39360 +packaging/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +packaging/pylock.py,sha256=-R1uNfJ4PaLto7Mg62YsGOHgvskuiIEqPwxOywl42Jk,22537 +packaging/requirements.py,sha256=PMCAWD8aNMnVD-6uZMedhBuAVX2573eZ4yPBLXmz04I,2870 +packaging/specifiers.py,sha256=EPNPimY_zFivthv1vdjZYz5IqkKGsnKR2yKh-EVyvZw,40797 +packaging/tags.py,sha256=cXLV1pJD3UtJlDg7Wz3zrfdQhRZqr8jumSAKKAAd2xE,22856 +packaging/utils.py,sha256=N4c6oZzFJy6klTZ3AnkNz7sSkJesuFWPp68LA3B5dAo,5040 +packaging/version.py,sha256=7XWlL2IDYLwDYC0ht6cFEhapLwLWbmyo4rb7sEFj0x8,23272 diff --git a/TTS/Kokoro/.venv/Lib/site-packages/packaging-26.0.dist-info/WHEEL b/TTS/Kokoro/.venv/Lib/site-packages/packaging-26.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..d8b9936dad9ab2513fa6979f411560d3b6b57e37 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/packaging-26.0.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: flit 3.12.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/TTS/Kokoro/.venv/Lib/site-packages/packaging/__init__.py b/TTS/Kokoro/.venv/Lib/site-packages/packaging/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..21695a74b5107c96ba4bb2cbca6b7f259dacd330 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/packaging/__init__.py @@ -0,0 +1,15 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +__title__ = "packaging" +__summary__ = "Core utilities for Python packages" +__uri__ = "https://github.com/pypa/packaging" + +__version__ = "26.0" + +__author__ = "Donald Stufft and individual contributors" +__email__ = "donald@stufft.io" + +__license__ = "BSD-2-Clause or Apache-2.0" +__copyright__ = f"2014 {__author__}" diff --git a/TTS/Kokoro/.venv/Lib/site-packages/packaging/_elffile.py b/TTS/Kokoro/.venv/Lib/site-packages/packaging/_elffile.py new file mode 100644 index 0000000000000000000000000000000000000000..497b0645217512ae2ba8ff61341fd2bbfa3648cd --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/packaging/_elffile.py @@ -0,0 +1,108 @@ +""" +ELF file parser. + +This provides a class ``ELFFile`` that parses an ELF executable in a similar +interface to ``ZipFile``. Only the read interface is implemented. + +ELF header: https://refspecs.linuxfoundation.org/elf/gabi4+/ch4.eheader.html +""" + +from __future__ import annotations + +import enum +import os +import struct +from typing import IO + + +class ELFInvalid(ValueError): + pass + + +class EIClass(enum.IntEnum): + C32 = 1 + C64 = 2 + + +class EIData(enum.IntEnum): + Lsb = 1 + Msb = 2 + + +class EMachine(enum.IntEnum): + I386 = 3 + S390 = 22 + Arm = 40 + X8664 = 62 + AArc64 = 183 + + +class ELFFile: + """ + Representation of an ELF executable. + """ + + def __init__(self, f: IO[bytes]) -> None: + self._f = f + + try: + ident = self._read("16B") + except struct.error as e: + raise ELFInvalid("unable to parse identification") from e + magic = bytes(ident[:4]) + if magic != b"\x7fELF": + raise ELFInvalid(f"invalid magic: {magic!r}") + + self.capacity = ident[4] # Format for program header (bitness). + self.encoding = ident[5] # Data structure encoding (endianness). + + try: + # e_fmt: Format for program header. + # p_fmt: Format for section header. + # p_idx: Indexes to find p_type, p_offset, and p_filesz. + e_fmt, self._p_fmt, self._p_idx = { + (1, 1): ("HHIIIIIHHH", ">IIIIIIII", (0, 1, 4)), # 32-bit MSB. + (2, 1): ("HHIQQQIHHH", ">IIQQQQQQ", (0, 2, 5)), # 64-bit MSB. + }[(self.capacity, self.encoding)] + except KeyError as e: + raise ELFInvalid( + f"unrecognized capacity ({self.capacity}) or encoding ({self.encoding})" + ) from e + + try: + ( + _, + self.machine, # Architecture type. + _, + _, + self._e_phoff, # Offset of program header. + _, + self.flags, # Processor-specific flags. + _, + self._e_phentsize, # Size of section. + self._e_phnum, # Number of sections. + ) = self._read(e_fmt) + except struct.error as e: + raise ELFInvalid("unable to parse machine and section information") from e + + def _read(self, fmt: str) -> tuple[int, ...]: + return struct.unpack(fmt, self._f.read(struct.calcsize(fmt))) + + @property + def interpreter(self) -> str | None: + """ + The path recorded in the ``PT_INTERP`` section header. + """ + for index in range(self._e_phnum): + self._f.seek(self._e_phoff + self._e_phentsize * index) + try: + data = self._read(self._p_fmt) + except struct.error: + continue + if data[self._p_idx[0]] != 3: # Not PT_INTERP. + continue + self._f.seek(data[self._p_idx[1]]) + return os.fsdecode(self._f.read(data[self._p_idx[2]])).strip("\0") + return None diff --git a/TTS/Kokoro/.venv/Lib/site-packages/packaging/_manylinux.py b/TTS/Kokoro/.venv/Lib/site-packages/packaging/_manylinux.py new file mode 100644 index 0000000000000000000000000000000000000000..0e79e8a882be74fe76c80ccf49a9cd68fb636fd4 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/packaging/_manylinux.py @@ -0,0 +1,262 @@ +from __future__ import annotations + +import collections +import contextlib +import functools +import os +import re +import sys +import warnings +from typing import Generator, Iterator, NamedTuple, Sequence + +from ._elffile import EIClass, EIData, ELFFile, EMachine + +EF_ARM_ABIMASK = 0xFF000000 +EF_ARM_ABI_VER5 = 0x05000000 +EF_ARM_ABI_FLOAT_HARD = 0x00000400 + +_ALLOWED_ARCHS = { + "x86_64", + "aarch64", + "ppc64", + "ppc64le", + "s390x", + "loongarch64", + "riscv64", +} + + +# `os.PathLike` not a generic type until Python 3.9, so sticking with `str` +# as the type for `path` until then. +@contextlib.contextmanager +def _parse_elf(path: str) -> Generator[ELFFile | None, None, None]: + try: + with open(path, "rb") as f: + yield ELFFile(f) + except (OSError, TypeError, ValueError): + yield None + + +def _is_linux_armhf(executable: str) -> bool: + # hard-float ABI can be detected from the ELF header of the running + # process + # https://static.docs.arm.com/ihi0044/g/aaelf32.pdf + with _parse_elf(executable) as f: + return ( + f is not None + and f.capacity == EIClass.C32 + and f.encoding == EIData.Lsb + and f.machine == EMachine.Arm + and f.flags & EF_ARM_ABIMASK == EF_ARM_ABI_VER5 + and f.flags & EF_ARM_ABI_FLOAT_HARD == EF_ARM_ABI_FLOAT_HARD + ) + + +def _is_linux_i686(executable: str) -> bool: + with _parse_elf(executable) as f: + return ( + f is not None + and f.capacity == EIClass.C32 + and f.encoding == EIData.Lsb + and f.machine == EMachine.I386 + ) + + +def _have_compatible_abi(executable: str, archs: Sequence[str]) -> bool: + if "armv7l" in archs: + return _is_linux_armhf(executable) + if "i686" in archs: + return _is_linux_i686(executable) + return any(arch in _ALLOWED_ARCHS for arch in archs) + + +# If glibc ever changes its major version, we need to know what the last +# minor version was, so we can build the complete list of all versions. +# For now, guess what the highest minor version might be, assume it will +# be 50 for testing. Once this actually happens, update the dictionary +# with the actual value. +_LAST_GLIBC_MINOR: dict[int, int] = collections.defaultdict(lambda: 50) + + +class _GLibCVersion(NamedTuple): + major: int + minor: int + + +def _glibc_version_string_confstr() -> str | None: + """ + Primary implementation of glibc_version_string using os.confstr. + """ + # os.confstr is quite a bit faster than ctypes.DLL. It's also less likely + # to be broken or missing. This strategy is used in the standard library + # platform module. + # https://github.com/python/cpython/blob/fcf1d003bf4f0100c/Lib/platform.py#L175-L183 + try: + # Should be a string like "glibc 2.17". + version_string: str | None = os.confstr("CS_GNU_LIBC_VERSION") + assert version_string is not None + _, version = version_string.rsplit() + except (AssertionError, AttributeError, OSError, ValueError): + # os.confstr() or CS_GNU_LIBC_VERSION not available (or a bad value)... + return None + return version + + +def _glibc_version_string_ctypes() -> str | None: + """ + Fallback implementation of glibc_version_string using ctypes. + """ + try: + import ctypes # noqa: PLC0415 + except ImportError: + return None + + # ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen + # manpage says, "If filename is NULL, then the returned handle is for the + # main program". This way we can let the linker do the work to figure out + # which libc our process is actually using. + # + # We must also handle the special case where the executable is not a + # dynamically linked executable. This can occur when using musl libc, + # for example. In this situation, dlopen() will error, leading to an + # OSError. Interestingly, at least in the case of musl, there is no + # errno set on the OSError. The single string argument used to construct + # OSError comes from libc itself and is therefore not portable to + # hard code here. In any case, failure to call dlopen() means we + # can proceed, so we bail on our attempt. + try: + process_namespace = ctypes.CDLL(None) + except OSError: + return None + + try: + gnu_get_libc_version = process_namespace.gnu_get_libc_version + except AttributeError: + # Symbol doesn't exist -> therefore, we are not linked to + # glibc. + return None + + # Call gnu_get_libc_version, which returns a string like "2.5" + gnu_get_libc_version.restype = ctypes.c_char_p + version_str: str = gnu_get_libc_version() + # py2 / py3 compatibility: + if not isinstance(version_str, str): + version_str = version_str.decode("ascii") + + return version_str + + +def _glibc_version_string() -> str | None: + """Returns glibc version string, or None if not using glibc.""" + return _glibc_version_string_confstr() or _glibc_version_string_ctypes() + + +def _parse_glibc_version(version_str: str) -> _GLibCVersion: + """Parse glibc version. + + We use a regexp instead of str.split because we want to discard any + random junk that might come after the minor version -- this might happen + in patched/forked versions of glibc (e.g. Linaro's version of glibc + uses version strings like "2.20-2014.11"). See gh-3588. + """ + m = re.match(r"(?P[0-9]+)\.(?P[0-9]+)", version_str) + if not m: + warnings.warn( + f"Expected glibc version with 2 components major.minor, got: {version_str}", + RuntimeWarning, + stacklevel=2, + ) + return _GLibCVersion(-1, -1) + return _GLibCVersion(int(m.group("major")), int(m.group("minor"))) + + +@functools.lru_cache +def _get_glibc_version() -> _GLibCVersion: + version_str = _glibc_version_string() + if version_str is None: + return _GLibCVersion(-1, -1) + return _parse_glibc_version(version_str) + + +# From PEP 513, PEP 600 +def _is_compatible(arch: str, version: _GLibCVersion) -> bool: + sys_glibc = _get_glibc_version() + if sys_glibc < version: + return False + # Check for presence of _manylinux module. + try: + import _manylinux # noqa: PLC0415 + except ImportError: + return True + if hasattr(_manylinux, "manylinux_compatible"): + result = _manylinux.manylinux_compatible(version[0], version[1], arch) + if result is not None: + return bool(result) + return True + if version == _GLibCVersion(2, 5) and hasattr(_manylinux, "manylinux1_compatible"): + return bool(_manylinux.manylinux1_compatible) + if version == _GLibCVersion(2, 12) and hasattr( + _manylinux, "manylinux2010_compatible" + ): + return bool(_manylinux.manylinux2010_compatible) + if version == _GLibCVersion(2, 17) and hasattr( + _manylinux, "manylinux2014_compatible" + ): + return bool(_manylinux.manylinux2014_compatible) + return True + + +_LEGACY_MANYLINUX_MAP: dict[_GLibCVersion, str] = { + # CentOS 7 w/ glibc 2.17 (PEP 599) + _GLibCVersion(2, 17): "manylinux2014", + # CentOS 6 w/ glibc 2.12 (PEP 571) + _GLibCVersion(2, 12): "manylinux2010", + # CentOS 5 w/ glibc 2.5 (PEP 513) + _GLibCVersion(2, 5): "manylinux1", +} + + +def platform_tags(archs: Sequence[str]) -> Iterator[str]: + """Generate manylinux tags compatible to the current platform. + + :param archs: Sequence of compatible architectures. + The first one shall be the closest to the actual architecture and be the part of + platform tag after the ``linux_`` prefix, e.g. ``x86_64``. + The ``linux_`` prefix is assumed as a prerequisite for the current platform to + be manylinux-compatible. + + :returns: An iterator of compatible manylinux tags. + """ + if not _have_compatible_abi(sys.executable, archs): + return + # Oldest glibc to be supported regardless of architecture is (2, 17). + too_old_glibc2 = _GLibCVersion(2, 16) + if set(archs) & {"x86_64", "i686"}: + # On x86/i686 also oldest glibc to be supported is (2, 5). + too_old_glibc2 = _GLibCVersion(2, 4) + current_glibc = _GLibCVersion(*_get_glibc_version()) + glibc_max_list = [current_glibc] + # We can assume compatibility across glibc major versions. + # https://sourceware.org/bugzilla/show_bug.cgi?id=24636 + # + # Build a list of maximum glibc versions so that we can + # output the canonical list of all glibc from current_glibc + # down to too_old_glibc2, including all intermediary versions. + for glibc_major in range(current_glibc.major - 1, 1, -1): + glibc_minor = _LAST_GLIBC_MINOR[glibc_major] + glibc_max_list.append(_GLibCVersion(glibc_major, glibc_minor)) + for arch in archs: + for glibc_max in glibc_max_list: + if glibc_max.major == too_old_glibc2.major: + min_minor = too_old_glibc2.minor + else: + # For other glibc major versions oldest supported is (x, 0). + min_minor = -1 + for glibc_minor in range(glibc_max.minor, min_minor, -1): + glibc_version = _GLibCVersion(glibc_max.major, glibc_minor) + if _is_compatible(arch, glibc_version): + yield "manylinux_{}_{}_{}".format(*glibc_version, arch) + + # Handle the legacy manylinux1, manylinux2010, manylinux2014 tags. + if legacy_tag := _LEGACY_MANYLINUX_MAP.get(glibc_version): + yield f"{legacy_tag}_{arch}" diff --git a/TTS/Kokoro/.venv/Lib/site-packages/packaging/_musllinux.py b/TTS/Kokoro/.venv/Lib/site-packages/packaging/_musllinux.py new file mode 100644 index 0000000000000000000000000000000000000000..4e8116a79ca80d60657542a23b4bbcbc3c518eaf --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/packaging/_musllinux.py @@ -0,0 +1,85 @@ +"""PEP 656 support. + +This module implements logic to detect if the currently running Python is +linked against musl, and what musl version is used. +""" + +from __future__ import annotations + +import functools +import re +import subprocess +import sys +from typing import Iterator, NamedTuple, Sequence + +from ._elffile import ELFFile + + +class _MuslVersion(NamedTuple): + major: int + minor: int + + +def _parse_musl_version(output: str) -> _MuslVersion | None: + lines = [n for n in (n.strip() for n in output.splitlines()) if n] + if len(lines) < 2 or lines[0][:4] != "musl": + return None + m = re.match(r"Version (\d+)\.(\d+)", lines[1]) + if not m: + return None + return _MuslVersion(major=int(m.group(1)), minor=int(m.group(2))) + + +@functools.lru_cache +def _get_musl_version(executable: str) -> _MuslVersion | None: + """Detect currently-running musl runtime version. + + This is done by checking the specified executable's dynamic linking + information, and invoking the loader to parse its output for a version + string. If the loader is musl, the output would be something like:: + + musl libc (x86_64) + Version 1.2.2 + Dynamic Program Loader + """ + try: + with open(executable, "rb") as f: + ld = ELFFile(f).interpreter + except (OSError, TypeError, ValueError): + return None + if ld is None or "musl" not in ld: + return None + proc = subprocess.run([ld], check=False, stderr=subprocess.PIPE, text=True) + return _parse_musl_version(proc.stderr) + + +def platform_tags(archs: Sequence[str]) -> Iterator[str]: + """Generate musllinux tags compatible to the current platform. + + :param archs: Sequence of compatible architectures. + The first one shall be the closest to the actual architecture and be the part of + platform tag after the ``linux_`` prefix, e.g. ``x86_64``. + The ``linux_`` prefix is assumed as a prerequisite for the current platform to + be musllinux-compatible. + + :returns: An iterator of compatible musllinux tags. + """ + sys_musl = _get_musl_version(sys.executable) + if sys_musl is None: # Python not dynamically linked against musl. + return + for arch in archs: + for minor in range(sys_musl.minor, -1, -1): + yield f"musllinux_{sys_musl.major}_{minor}_{arch}" + + +if __name__ == "__main__": # pragma: no cover + import sysconfig + + plat = sysconfig.get_platform() + assert plat.startswith("linux-"), "not linux" + + print("plat:", plat) + print("musl:", _get_musl_version(sys.executable)) + print("tags:", end=" ") + for t in platform_tags(re.sub(r"[.-]", "_", plat.split("-", 1)[-1])): + print(t, end="\n ") diff --git a/TTS/Kokoro/.venv/Lib/site-packages/packaging/_parser.py b/TTS/Kokoro/.venv/Lib/site-packages/packaging/_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..f6c1f5cd226b926f96a3bb1e9fb0f18d1bd021c9 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/packaging/_parser.py @@ -0,0 +1,365 @@ +"""Handwritten parser of dependency specifiers. + +The docstring for each __parse_* function contains EBNF-inspired grammar representing +the implementation. +""" + +from __future__ import annotations + +import ast +from typing import List, Literal, NamedTuple, Sequence, Tuple, Union + +from ._tokenizer import DEFAULT_RULES, Tokenizer + + +class Node: + __slots__ = ("value",) + + def __init__(self, value: str) -> None: + self.value = value + + def __str__(self) -> str: + return self.value + + def __repr__(self) -> str: + return f"<{self.__class__.__name__}({self.value!r})>" + + def serialize(self) -> str: + raise NotImplementedError + + +class Variable(Node): + __slots__ = () + + def serialize(self) -> str: + return str(self) + + +class Value(Node): + __slots__ = () + + def serialize(self) -> str: + return f'"{self}"' + + +class Op(Node): + __slots__ = () + + def serialize(self) -> str: + return str(self) + + +MarkerLogical = Literal["and", "or"] +MarkerVar = Union[Variable, Value] +MarkerItem = Tuple[MarkerVar, Op, MarkerVar] +MarkerAtom = Union[MarkerItem, Sequence["MarkerAtom"]] +MarkerList = List[Union["MarkerList", MarkerAtom, MarkerLogical]] + + +class ParsedRequirement(NamedTuple): + name: str + url: str + extras: list[str] + specifier: str + marker: MarkerList | None + + +# -------------------------------------------------------------------------------------- +# Recursive descent parser for dependency specifier +# -------------------------------------------------------------------------------------- +def parse_requirement(source: str) -> ParsedRequirement: + return _parse_requirement(Tokenizer(source, rules=DEFAULT_RULES)) + + +def _parse_requirement(tokenizer: Tokenizer) -> ParsedRequirement: + """ + requirement = WS? IDENTIFIER WS? extras WS? requirement_details + """ + tokenizer.consume("WS") + + name_token = tokenizer.expect( + "IDENTIFIER", expected="package name at the start of dependency specifier" + ) + name = name_token.text + tokenizer.consume("WS") + + extras = _parse_extras(tokenizer) + tokenizer.consume("WS") + + url, specifier, marker = _parse_requirement_details(tokenizer) + tokenizer.expect("END", expected="end of dependency specifier") + + return ParsedRequirement(name, url, extras, specifier, marker) + + +def _parse_requirement_details( + tokenizer: Tokenizer, +) -> tuple[str, str, MarkerList | None]: + """ + requirement_details = AT URL (WS requirement_marker?)? + | specifier WS? (requirement_marker)? + """ + + specifier = "" + url = "" + marker = None + + if tokenizer.check("AT"): + tokenizer.read() + tokenizer.consume("WS") + + url_start = tokenizer.position + url = tokenizer.expect("URL", expected="URL after @").text + if tokenizer.check("END", peek=True): + return (url, specifier, marker) + + tokenizer.expect("WS", expected="whitespace after URL") + + # The input might end after whitespace. + if tokenizer.check("END", peek=True): + return (url, specifier, marker) + + marker = _parse_requirement_marker( + tokenizer, + span_start=url_start, + expected="semicolon (after URL and whitespace)", + ) + else: + specifier_start = tokenizer.position + specifier = _parse_specifier(tokenizer) + tokenizer.consume("WS") + + if tokenizer.check("END", peek=True): + return (url, specifier, marker) + + marker = _parse_requirement_marker( + tokenizer, + span_start=specifier_start, + expected=( + "comma (within version specifier), semicolon (after version specifier)" + if specifier + else "semicolon (after name with no version specifier)" + ), + ) + + return (url, specifier, marker) + + +def _parse_requirement_marker( + tokenizer: Tokenizer, *, span_start: int, expected: str +) -> MarkerList: + """ + requirement_marker = SEMICOLON marker WS? + """ + + if not tokenizer.check("SEMICOLON"): + tokenizer.raise_syntax_error( + f"Expected {expected} or end", + span_start=span_start, + span_end=None, + ) + tokenizer.read() + + marker = _parse_marker(tokenizer) + tokenizer.consume("WS") + + return marker + + +def _parse_extras(tokenizer: Tokenizer) -> list[str]: + """ + extras = (LEFT_BRACKET wsp* extras_list? wsp* RIGHT_BRACKET)? + """ + if not tokenizer.check("LEFT_BRACKET", peek=True): + return [] + + with tokenizer.enclosing_tokens( + "LEFT_BRACKET", + "RIGHT_BRACKET", + around="extras", + ): + tokenizer.consume("WS") + extras = _parse_extras_list(tokenizer) + tokenizer.consume("WS") + + return extras + + +def _parse_extras_list(tokenizer: Tokenizer) -> list[str]: + """ + extras_list = identifier (wsp* ',' wsp* identifier)* + """ + extras: list[str] = [] + + if not tokenizer.check("IDENTIFIER"): + return extras + + extras.append(tokenizer.read().text) + + while True: + tokenizer.consume("WS") + if tokenizer.check("IDENTIFIER", peek=True): + tokenizer.raise_syntax_error("Expected comma between extra names") + elif not tokenizer.check("COMMA"): + break + + tokenizer.read() + tokenizer.consume("WS") + + extra_token = tokenizer.expect("IDENTIFIER", expected="extra name after comma") + extras.append(extra_token.text) + + return extras + + +def _parse_specifier(tokenizer: Tokenizer) -> str: + """ + specifier = LEFT_PARENTHESIS WS? version_many WS? RIGHT_PARENTHESIS + | WS? version_many WS? + """ + with tokenizer.enclosing_tokens( + "LEFT_PARENTHESIS", + "RIGHT_PARENTHESIS", + around="version specifier", + ): + tokenizer.consume("WS") + parsed_specifiers = _parse_version_many(tokenizer) + tokenizer.consume("WS") + + return parsed_specifiers + + +def _parse_version_many(tokenizer: Tokenizer) -> str: + """ + version_many = (SPECIFIER (WS? COMMA WS? SPECIFIER)*)? + """ + parsed_specifiers = "" + while tokenizer.check("SPECIFIER"): + span_start = tokenizer.position + parsed_specifiers += tokenizer.read().text + if tokenizer.check("VERSION_PREFIX_TRAIL", peek=True): + tokenizer.raise_syntax_error( + ".* suffix can only be used with `==` or `!=` operators", + span_start=span_start, + span_end=tokenizer.position + 1, + ) + if tokenizer.check("VERSION_LOCAL_LABEL_TRAIL", peek=True): + tokenizer.raise_syntax_error( + "Local version label can only be used with `==` or `!=` operators", + span_start=span_start, + span_end=tokenizer.position, + ) + tokenizer.consume("WS") + if not tokenizer.check("COMMA"): + break + parsed_specifiers += tokenizer.read().text + tokenizer.consume("WS") + + return parsed_specifiers + + +# -------------------------------------------------------------------------------------- +# Recursive descent parser for marker expression +# -------------------------------------------------------------------------------------- +def parse_marker(source: str) -> MarkerList: + return _parse_full_marker(Tokenizer(source, rules=DEFAULT_RULES)) + + +def _parse_full_marker(tokenizer: Tokenizer) -> MarkerList: + retval = _parse_marker(tokenizer) + tokenizer.expect("END", expected="end of marker expression") + return retval + + +def _parse_marker(tokenizer: Tokenizer) -> MarkerList: + """ + marker = marker_atom (BOOLOP marker_atom)+ + """ + expression = [_parse_marker_atom(tokenizer)] + while tokenizer.check("BOOLOP"): + token = tokenizer.read() + expr_right = _parse_marker_atom(tokenizer) + expression.extend((token.text, expr_right)) + return expression + + +def _parse_marker_atom(tokenizer: Tokenizer) -> MarkerAtom: + """ + marker_atom = WS? LEFT_PARENTHESIS WS? marker WS? RIGHT_PARENTHESIS WS? + | WS? marker_item WS? + """ + + tokenizer.consume("WS") + if tokenizer.check("LEFT_PARENTHESIS", peek=True): + with tokenizer.enclosing_tokens( + "LEFT_PARENTHESIS", + "RIGHT_PARENTHESIS", + around="marker expression", + ): + tokenizer.consume("WS") + marker: MarkerAtom = _parse_marker(tokenizer) + tokenizer.consume("WS") + else: + marker = _parse_marker_item(tokenizer) + tokenizer.consume("WS") + return marker + + +def _parse_marker_item(tokenizer: Tokenizer) -> MarkerItem: + """ + marker_item = WS? marker_var WS? marker_op WS? marker_var WS? + """ + tokenizer.consume("WS") + marker_var_left = _parse_marker_var(tokenizer) + tokenizer.consume("WS") + marker_op = _parse_marker_op(tokenizer) + tokenizer.consume("WS") + marker_var_right = _parse_marker_var(tokenizer) + tokenizer.consume("WS") + return (marker_var_left, marker_op, marker_var_right) + + +def _parse_marker_var(tokenizer: Tokenizer) -> MarkerVar: # noqa: RET503 + """ + marker_var = VARIABLE | QUOTED_STRING + """ + if tokenizer.check("VARIABLE"): + return process_env_var(tokenizer.read().text.replace(".", "_")) + elif tokenizer.check("QUOTED_STRING"): + return process_python_str(tokenizer.read().text) + else: + tokenizer.raise_syntax_error( + message="Expected a marker variable or quoted string" + ) + + +def process_env_var(env_var: str) -> Variable: + if env_var in ("platform_python_implementation", "python_implementation"): + return Variable("platform_python_implementation") + else: + return Variable(env_var) + + +def process_python_str(python_str: str) -> Value: + value = ast.literal_eval(python_str) + return Value(str(value)) + + +def _parse_marker_op(tokenizer: Tokenizer) -> Op: + """ + marker_op = IN | NOT IN | OP + """ + if tokenizer.check("IN"): + tokenizer.read() + return Op("in") + elif tokenizer.check("NOT"): + tokenizer.read() + tokenizer.expect("WS", expected="whitespace after 'not'") + tokenizer.expect("IN", expected="'in' after 'not'") + return Op("not in") + elif tokenizer.check("OP"): + return Op(tokenizer.read().text) + else: + return tokenizer.raise_syntax_error( + "Expected marker operator, one of <=, <, !=, ==, >=, >, ~=, ===, in, not in" + ) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/packaging/_structures.py b/TTS/Kokoro/.venv/Lib/site-packages/packaging/_structures.py new file mode 100644 index 0000000000000000000000000000000000000000..225e2eee01238571c50595eb104e0b70d5f503c4 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/packaging/_structures.py @@ -0,0 +1,69 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +import typing + + +@typing.final +class InfinityType: + __slots__ = () + + def __repr__(self) -> str: + return "Infinity" + + def __hash__(self) -> int: + return hash(repr(self)) + + def __lt__(self, other: object) -> bool: + return False + + def __le__(self, other: object) -> bool: + return False + + def __eq__(self, other: object) -> bool: + return isinstance(other, self.__class__) + + def __gt__(self, other: object) -> bool: + return True + + def __ge__(self, other: object) -> bool: + return True + + def __neg__(self: object) -> "NegativeInfinityType": + return NegativeInfinity + + +Infinity = InfinityType() + + +@typing.final +class NegativeInfinityType: + __slots__ = () + + def __repr__(self) -> str: + return "-Infinity" + + def __hash__(self) -> int: + return hash(repr(self)) + + def __lt__(self, other: object) -> bool: + return True + + def __le__(self, other: object) -> bool: + return True + + def __eq__(self, other: object) -> bool: + return isinstance(other, self.__class__) + + def __gt__(self, other: object) -> bool: + return False + + def __ge__(self, other: object) -> bool: + return False + + def __neg__(self: object) -> InfinityType: + return Infinity + + +NegativeInfinity = NegativeInfinityType() diff --git a/TTS/Kokoro/.venv/Lib/site-packages/packaging/_tokenizer.py b/TTS/Kokoro/.venv/Lib/site-packages/packaging/_tokenizer.py new file mode 100644 index 0000000000000000000000000000000000000000..e6d20dd3f56f880a92db7409a3e1335cb282a8f2 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/packaging/_tokenizer.py @@ -0,0 +1,193 @@ +from __future__ import annotations + +import contextlib +import re +from dataclasses import dataclass +from typing import Generator, Mapping, NoReturn + +from .specifiers import Specifier + + +@dataclass +class Token: + name: str + text: str + position: int + + +class ParserSyntaxError(Exception): + """The provided source text could not be parsed correctly.""" + + def __init__( + self, + message: str, + *, + source: str, + span: tuple[int, int], + ) -> None: + self.span = span + self.message = message + self.source = source + + super().__init__() + + def __str__(self) -> str: + marker = " " * self.span[0] + "~" * (self.span[1] - self.span[0]) + "^" + return f"{self.message}\n {self.source}\n {marker}" + + +DEFAULT_RULES: dict[str, re.Pattern[str]] = { + "LEFT_PARENTHESIS": re.compile(r"\("), + "RIGHT_PARENTHESIS": re.compile(r"\)"), + "LEFT_BRACKET": re.compile(r"\["), + "RIGHT_BRACKET": re.compile(r"\]"), + "SEMICOLON": re.compile(r";"), + "COMMA": re.compile(r","), + "QUOTED_STRING": re.compile( + r""" + ( + ('[^']*') + | + ("[^"]*") + ) + """, + re.VERBOSE, + ), + "OP": re.compile(r"(===|==|~=|!=|<=|>=|<|>)"), + "BOOLOP": re.compile(r"\b(or|and)\b"), + "IN": re.compile(r"\bin\b"), + "NOT": re.compile(r"\bnot\b"), + "VARIABLE": re.compile( + r""" + \b( + python_version + |python_full_version + |os[._]name + |sys[._]platform + |platform_(release|system) + |platform[._](version|machine|python_implementation) + |python_implementation + |implementation_(name|version) + |extras? + |dependency_groups + )\b + """, + re.VERBOSE, + ), + "SPECIFIER": re.compile( + Specifier._operator_regex_str + Specifier._version_regex_str, + re.VERBOSE | re.IGNORECASE, + ), + "AT": re.compile(r"\@"), + "URL": re.compile(r"[^ \t]+"), + "IDENTIFIER": re.compile(r"\b[a-zA-Z0-9][a-zA-Z0-9._-]*\b"), + "VERSION_PREFIX_TRAIL": re.compile(r"\.\*"), + "VERSION_LOCAL_LABEL_TRAIL": re.compile(r"\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*"), + "WS": re.compile(r"[ \t]+"), + "END": re.compile(r"$"), +} + + +class Tokenizer: + """Context-sensitive token parsing. + + Provides methods to examine the input stream to check whether the next token + matches. + """ + + def __init__( + self, + source: str, + *, + rules: Mapping[str, re.Pattern[str]], + ) -> None: + self.source = source + self.rules = rules + self.next_token: Token | None = None + self.position = 0 + + def consume(self, name: str) -> None: + """Move beyond provided token name, if at current position.""" + if self.check(name): + self.read() + + def check(self, name: str, *, peek: bool = False) -> bool: + """Check whether the next token has the provided name. + + By default, if the check succeeds, the token *must* be read before + another check. If `peek` is set to `True`, the token is not loaded and + would need to be checked again. + """ + assert self.next_token is None, ( + f"Cannot check for {name!r}, already have {self.next_token!r}" + ) + assert name in self.rules, f"Unknown token name: {name!r}" + + expression = self.rules[name] + + match = expression.match(self.source, self.position) + if match is None: + return False + if not peek: + self.next_token = Token(name, match[0], self.position) + return True + + def expect(self, name: str, *, expected: str) -> Token: + """Expect a certain token name next, failing with a syntax error otherwise. + + The token is *not* read. + """ + if not self.check(name): + raise self.raise_syntax_error(f"Expected {expected}") + return self.read() + + def read(self) -> Token: + """Consume the next token and return it.""" + token = self.next_token + assert token is not None + + self.position += len(token.text) + self.next_token = None + + return token + + def raise_syntax_error( + self, + message: str, + *, + span_start: int | None = None, + span_end: int | None = None, + ) -> NoReturn: + """Raise ParserSyntaxError at the given position.""" + span = ( + self.position if span_start is None else span_start, + self.position if span_end is None else span_end, + ) + raise ParserSyntaxError( + message, + source=self.source, + span=span, + ) + + @contextlib.contextmanager + def enclosing_tokens( + self, open_token: str, close_token: str, *, around: str + ) -> Generator[None, None, None]: + if self.check(open_token): + open_position = self.position + self.read() + else: + open_position = None + + yield + + if open_position is None: + return + + if not self.check(close_token): + self.raise_syntax_error( + f"Expected matching {close_token} for {open_token}, after {around}", + span_start=open_position, + ) + + self.read() diff --git a/TTS/Kokoro/.venv/Lib/site-packages/packaging/markers.py b/TTS/Kokoro/.venv/Lib/site-packages/packaging/markers.py new file mode 100644 index 0000000000000000000000000000000000000000..ca3706fe492f4cf0762f7734d84c2d269f88bbc5 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/packaging/markers.py @@ -0,0 +1,388 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import operator +import os +import platform +import sys +from typing import AbstractSet, Callable, Literal, Mapping, TypedDict, Union, cast + +from ._parser import MarkerAtom, MarkerList, Op, Value, Variable +from ._parser import parse_marker as _parse_marker +from ._tokenizer import ParserSyntaxError +from .specifiers import InvalidSpecifier, Specifier +from .utils import canonicalize_name + +__all__ = [ + "Environment", + "EvaluateContext", + "InvalidMarker", + "Marker", + "UndefinedComparison", + "UndefinedEnvironmentName", + "default_environment", +] + +Operator = Callable[[str, Union[str, AbstractSet[str]]], bool] +EvaluateContext = Literal["metadata", "lock_file", "requirement"] +MARKERS_ALLOWING_SET = {"extras", "dependency_groups"} +MARKERS_REQUIRING_VERSION = { + "implementation_version", + "platform_release", + "python_full_version", + "python_version", +} + + +class InvalidMarker(ValueError): + """ + An invalid marker was found, users should refer to PEP 508. + """ + + +class UndefinedComparison(ValueError): + """ + An invalid operation was attempted on a value that doesn't support it. + """ + + +class UndefinedEnvironmentName(ValueError): + """ + A name was attempted to be used that does not exist inside of the + environment. + """ + + +class Environment(TypedDict): + implementation_name: str + """The implementation's identifier, e.g. ``'cpython'``.""" + + implementation_version: str + """ + The implementation's version, e.g. ``'3.13.0a2'`` for CPython 3.13.0a2, or + ``'7.3.13'`` for PyPy3.10 v7.3.13. + """ + + os_name: str + """ + The value of :py:data:`os.name`. The name of the operating system dependent module + imported, e.g. ``'posix'``. + """ + + platform_machine: str + """ + Returns the machine type, e.g. ``'i386'``. + + An empty string if the value cannot be determined. + """ + + platform_release: str + """ + The system's release, e.g. ``'2.2.0'`` or ``'NT'``. + + An empty string if the value cannot be determined. + """ + + platform_system: str + """ + The system/OS name, e.g. ``'Linux'``, ``'Windows'`` or ``'Java'``. + + An empty string if the value cannot be determined. + """ + + platform_version: str + """ + The system's release version, e.g. ``'#3 on degas'``. + + An empty string if the value cannot be determined. + """ + + python_full_version: str + """ + The Python version as string ``'major.minor.patchlevel'``. + + Note that unlike the Python :py:data:`sys.version`, this value will always include + the patchlevel (it defaults to 0). + """ + + platform_python_implementation: str + """ + A string identifying the Python implementation, e.g. ``'CPython'``. + """ + + python_version: str + """The Python version as string ``'major.minor'``.""" + + sys_platform: str + """ + This string contains a platform identifier that can be used to append + platform-specific components to :py:data:`sys.path`, for instance. + + For Unix systems, except on Linux and AIX, this is the lowercased OS name as + returned by ``uname -s`` with the first part of the version as returned by + ``uname -r`` appended, e.g. ``'sunos5'`` or ``'freebsd8'``, at the time when Python + was built. + """ + + +def _normalize_extras( + result: MarkerList | MarkerAtom | str, +) -> MarkerList | MarkerAtom | str: + if not isinstance(result, tuple): + return result + + lhs, op, rhs = result + if isinstance(lhs, Variable) and lhs.value == "extra": + normalized_extra = canonicalize_name(rhs.value) + rhs = Value(normalized_extra) + elif isinstance(rhs, Variable) and rhs.value == "extra": + normalized_extra = canonicalize_name(lhs.value) + lhs = Value(normalized_extra) + return lhs, op, rhs + + +def _normalize_extra_values(results: MarkerList) -> MarkerList: + """ + Normalize extra values. + """ + + return [_normalize_extras(r) for r in results] + + +def _format_marker( + marker: list[str] | MarkerAtom | str, first: bool | None = True +) -> str: + assert isinstance(marker, (list, tuple, str)) + + # Sometimes we have a structure like [[...]] which is a single item list + # where the single item is itself it's own list. In that case we want skip + # the rest of this function so that we don't get extraneous () on the + # outside. + if ( + isinstance(marker, list) + and len(marker) == 1 + and isinstance(marker[0], (list, tuple)) + ): + return _format_marker(marker[0]) + + if isinstance(marker, list): + inner = (_format_marker(m, first=False) for m in marker) + if first: + return " ".join(inner) + else: + return "(" + " ".join(inner) + ")" + elif isinstance(marker, tuple): + return " ".join([m.serialize() for m in marker]) + else: + return marker + + +_operators: dict[str, Operator] = { + "in": lambda lhs, rhs: lhs in rhs, + "not in": lambda lhs, rhs: lhs not in rhs, + "<": lambda _lhs, _rhs: False, + "<=": operator.eq, + "==": operator.eq, + "!=": operator.ne, + ">=": operator.eq, + ">": lambda _lhs, _rhs: False, +} + + +def _eval_op(lhs: str, op: Op, rhs: str | AbstractSet[str], *, key: str) -> bool: + op_str = op.serialize() + if key in MARKERS_REQUIRING_VERSION: + try: + spec = Specifier(f"{op_str}{rhs}") + except InvalidSpecifier: + pass + else: + return spec.contains(lhs, prereleases=True) + + oper: Operator | None = _operators.get(op_str) + if oper is None: + raise UndefinedComparison(f"Undefined {op!r} on {lhs!r} and {rhs!r}.") + + return oper(lhs, rhs) + + +def _normalize( + lhs: str, rhs: str | AbstractSet[str], key: str +) -> tuple[str, str | AbstractSet[str]]: + # PEP 685 - Comparison of extra names for optional distribution dependencies + # https://peps.python.org/pep-0685/ + # > When comparing extra names, tools MUST normalize the names being + # > compared using the semantics outlined in PEP 503 for names + if key == "extra": + assert isinstance(rhs, str), "extra value must be a string" + # Both sides are normalized at this point already + return (lhs, rhs) + if key in MARKERS_ALLOWING_SET: + if isinstance(rhs, str): # pragma: no cover + return (canonicalize_name(lhs), canonicalize_name(rhs)) + else: + return (canonicalize_name(lhs), {canonicalize_name(v) for v in rhs}) + + # other environment markers don't have such standards + return lhs, rhs + + +def _evaluate_markers( + markers: MarkerList, environment: dict[str, str | AbstractSet[str]] +) -> bool: + groups: list[list[bool]] = [[]] + + for marker in markers: + if isinstance(marker, list): + groups[-1].append(_evaluate_markers(marker, environment)) + elif isinstance(marker, tuple): + lhs, op, rhs = marker + + if isinstance(lhs, Variable): + environment_key = lhs.value + lhs_value = environment[environment_key] + rhs_value = rhs.value + else: + lhs_value = lhs.value + environment_key = rhs.value + rhs_value = environment[environment_key] + + assert isinstance(lhs_value, str), "lhs must be a string" + lhs_value, rhs_value = _normalize(lhs_value, rhs_value, key=environment_key) + groups[-1].append(_eval_op(lhs_value, op, rhs_value, key=environment_key)) + elif marker == "or": + groups.append([]) + elif marker == "and": + pass + else: # pragma: nocover + raise TypeError(f"Unexpected marker {marker!r}") + + return any(all(item) for item in groups) + + +def format_full_version(info: sys._version_info) -> str: + version = f"{info.major}.{info.minor}.{info.micro}" + kind = info.releaselevel + if kind != "final": + version += kind[0] + str(info.serial) + return version + + +def default_environment() -> Environment: + iver = format_full_version(sys.implementation.version) + implementation_name = sys.implementation.name + return { + "implementation_name": implementation_name, + "implementation_version": iver, + "os_name": os.name, + "platform_machine": platform.machine(), + "platform_release": platform.release(), + "platform_system": platform.system(), + "platform_version": platform.version(), + "python_full_version": platform.python_version(), + "platform_python_implementation": platform.python_implementation(), + "python_version": ".".join(platform.python_version_tuple()[:2]), + "sys_platform": sys.platform, + } + + +class Marker: + def __init__(self, marker: str) -> None: + # Note: We create a Marker object without calling this constructor in + # packaging.requirements.Requirement. If any additional logic is + # added here, make sure to mirror/adapt Requirement. + + # If this fails and throws an error, the repr still expects _markers to + # be defined. + self._markers: MarkerList = [] + + try: + self._markers = _normalize_extra_values(_parse_marker(marker)) + # The attribute `_markers` can be described in terms of a recursive type: + # MarkerList = List[Union[Tuple[Node, ...], str, MarkerList]] + # + # For example, the following expression: + # python_version > "3.6" or (python_version == "3.6" and os_name == "unix") + # + # is parsed into: + # [ + # (, ')>, ), + # 'and', + # [ + # (, , ), + # 'or', + # (, , ) + # ] + # ] + except ParserSyntaxError as e: + raise InvalidMarker(str(e)) from e + + def __str__(self) -> str: + return _format_marker(self._markers) + + def __repr__(self) -> str: + return f"<{self.__class__.__name__}('{self}')>" + + def __hash__(self) -> int: + return hash(str(self)) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, Marker): + return NotImplemented + + return str(self) == str(other) + + def evaluate( + self, + environment: Mapping[str, str | AbstractSet[str]] | None = None, + context: EvaluateContext = "metadata", + ) -> bool: + """Evaluate a marker. + + Return the boolean from evaluating the given marker against the + environment. environment is an optional argument to override all or + part of the determined environment. The *context* parameter specifies what + context the markers are being evaluated for, which influences what markers + are considered valid. Acceptable values are "metadata" (for core metadata; + default), "lock_file", and "requirement" (i.e. all other situations). + + The environment is determined from the current Python process. + """ + current_environment = cast( + "dict[str, str | AbstractSet[str]]", default_environment() + ) + if context == "lock_file": + current_environment.update( + extras=frozenset(), dependency_groups=frozenset() + ) + elif context == "metadata": + current_environment["extra"] = "" + + if environment is not None: + current_environment.update(environment) + if "extra" in current_environment: + # The API used to allow setting extra to None. We need to handle + # this case for backwards compatibility. Also skip running + # normalize name if extra is empty. + extra = cast("str | None", current_environment["extra"]) + current_environment["extra"] = canonicalize_name(extra) if extra else "" + + return _evaluate_markers( + self._markers, _repair_python_full_version(current_environment) + ) + + +def _repair_python_full_version( + env: dict[str, str | AbstractSet[str]], +) -> dict[str, str | AbstractSet[str]]: + """ + Work around platform.python_version() returning something that is not PEP 440 + compliant for non-tagged Python builds. + """ + python_full_version = cast("str", env["python_full_version"]) + if python_full_version.endswith("+"): + env["python_full_version"] = f"{python_full_version}local" + return env diff --git a/TTS/Kokoro/.venv/Lib/site-packages/packaging/metadata.py b/TTS/Kokoro/.venv/Lib/site-packages/packaging/metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..253f6b1b7ebd711fdc6bbbab3b56897061bab515 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/packaging/metadata.py @@ -0,0 +1,978 @@ +from __future__ import annotations + +import email.feedparser +import email.header +import email.message +import email.parser +import email.policy +import keyword +import pathlib +import sys +import typing +from typing import ( + Any, + Callable, + Generic, + Literal, + TypedDict, + cast, +) + +from . import licenses, requirements, specifiers, utils +from . import version as version_module + +if typing.TYPE_CHECKING: + from .licenses import NormalizedLicenseExpression + +T = typing.TypeVar("T") + + +if sys.version_info >= (3, 11): # pragma: no cover + ExceptionGroup = ExceptionGroup # noqa: F821 +else: # pragma: no cover + + class ExceptionGroup(Exception): + """A minimal implementation of :external:exc:`ExceptionGroup` from Python 3.11. + + If :external:exc:`ExceptionGroup` is already defined by Python itself, + that version is used instead. + """ + + message: str + exceptions: list[Exception] + + def __init__(self, message: str, exceptions: list[Exception]) -> None: + self.message = message + self.exceptions = exceptions + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self.message!r}, {self.exceptions!r})" + + +class InvalidMetadata(ValueError): + """A metadata field contains invalid data.""" + + field: str + """The name of the field that contains invalid data.""" + + def __init__(self, field: str, message: str) -> None: + self.field = field + super().__init__(message) + + +# The RawMetadata class attempts to make as few assumptions about the underlying +# serialization formats as possible. The idea is that as long as a serialization +# formats offer some very basic primitives in *some* way then we can support +# serializing to and from that format. +class RawMetadata(TypedDict, total=False): + """A dictionary of raw core metadata. + + Each field in core metadata maps to a key of this dictionary (when data is + provided). The key is lower-case and underscores are used instead of dashes + compared to the equivalent core metadata field. Any core metadata field that + can be specified multiple times or can hold multiple values in a single + field have a key with a plural name. See :class:`Metadata` whose attributes + match the keys of this dictionary. + + Core metadata fields that can be specified multiple times are stored as a + list or dict depending on which is appropriate for the field. Any fields + which hold multiple values in a single field are stored as a list. + + """ + + # Metadata 1.0 - PEP 241 + metadata_version: str + name: str + version: str + platforms: list[str] + summary: str + description: str + keywords: list[str] + home_page: str + author: str + author_email: str + license: str + + # Metadata 1.1 - PEP 314 + supported_platforms: list[str] + download_url: str + classifiers: list[str] + requires: list[str] + provides: list[str] + obsoletes: list[str] + + # Metadata 1.2 - PEP 345 + maintainer: str + maintainer_email: str + requires_dist: list[str] + provides_dist: list[str] + obsoletes_dist: list[str] + requires_python: str + requires_external: list[str] + project_urls: dict[str, str] + + # Metadata 2.0 + # PEP 426 attempted to completely revamp the metadata format + # but got stuck without ever being able to build consensus on + # it and ultimately ended up withdrawn. + # + # However, a number of tools had started emitting METADATA with + # `2.0` Metadata-Version, so for historical reasons, this version + # was skipped. + + # Metadata 2.1 - PEP 566 + description_content_type: str + provides_extra: list[str] + + # Metadata 2.2 - PEP 643 + dynamic: list[str] + + # Metadata 2.3 - PEP 685 + # No new fields were added in PEP 685, just some edge case were + # tightened up to provide better interoperability. + + # Metadata 2.4 - PEP 639 + license_expression: str + license_files: list[str] + + # Metadata 2.5 - PEP 794 + import_names: list[str] + import_namespaces: list[str] + + +# 'keywords' is special as it's a string in the core metadata spec, but we +# represent it as a list. +_STRING_FIELDS = { + "author", + "author_email", + "description", + "description_content_type", + "download_url", + "home_page", + "license", + "license_expression", + "maintainer", + "maintainer_email", + "metadata_version", + "name", + "requires_python", + "summary", + "version", +} + +_LIST_FIELDS = { + "classifiers", + "dynamic", + "license_files", + "obsoletes", + "obsoletes_dist", + "platforms", + "provides", + "provides_dist", + "provides_extra", + "requires", + "requires_dist", + "requires_external", + "supported_platforms", + "import_names", + "import_namespaces", +} + +_DICT_FIELDS = { + "project_urls", +} + + +def _parse_keywords(data: str) -> list[str]: + """Split a string of comma-separated keywords into a list of keywords.""" + return [k.strip() for k in data.split(",")] + + +def _parse_project_urls(data: list[str]) -> dict[str, str]: + """Parse a list of label/URL string pairings separated by a comma.""" + urls = {} + for pair in data: + # Our logic is slightly tricky here as we want to try and do + # *something* reasonable with malformed data. + # + # The main thing that we have to worry about, is data that does + # not have a ',' at all to split the label from the Value. There + # isn't a singular right answer here, and we will fail validation + # later on (if the caller is validating) so it doesn't *really* + # matter, but since the missing value has to be an empty str + # and our return value is dict[str, str], if we let the key + # be the missing value, then they'd have multiple '' values that + # overwrite each other in a accumulating dict. + # + # The other potential issue is that it's possible to have the + # same label multiple times in the metadata, with no solid "right" + # answer with what to do in that case. As such, we'll do the only + # thing we can, which is treat the field as unparsable and add it + # to our list of unparsed fields. + # + # TODO: The spec doesn't say anything about if the keys should be + # considered case sensitive or not... logically they should + # be case-preserving and case-insensitive, but doing that + # would open up more cases where we might have duplicate + # entries. + label, _, url = (s.strip() for s in pair.partition(",")) + + if label in urls: + # The label already exists in our set of urls, so this field + # is unparsable, and we can just add the whole thing to our + # unparsable data and stop processing it. + raise KeyError("duplicate labels in project urls") + urls[label] = url + + return urls + + +def _get_payload(msg: email.message.Message, source: bytes | str) -> str: + """Get the body of the message.""" + # If our source is a str, then our caller has managed encodings for us, + # and we don't need to deal with it. + if isinstance(source, str): + payload = msg.get_payload() + assert isinstance(payload, str) + return payload + # If our source is a bytes, then we're managing the encoding and we need + # to deal with it. + else: + bpayload = msg.get_payload(decode=True) + assert isinstance(bpayload, bytes) + try: + return bpayload.decode("utf8", "strict") + except UnicodeDecodeError as exc: + raise ValueError("payload in an invalid encoding") from exc + + +# The various parse_FORMAT functions here are intended to be as lenient as +# possible in their parsing, while still returning a correctly typed +# RawMetadata. +# +# To aid in this, we also generally want to do as little touching of the +# data as possible, except where there are possibly some historic holdovers +# that make valid data awkward to work with. +# +# While this is a lower level, intermediate format than our ``Metadata`` +# class, some light touch ups can make a massive difference in usability. + +# Map METADATA fields to RawMetadata. +_EMAIL_TO_RAW_MAPPING = { + "author": "author", + "author-email": "author_email", + "classifier": "classifiers", + "description": "description", + "description-content-type": "description_content_type", + "download-url": "download_url", + "dynamic": "dynamic", + "home-page": "home_page", + "import-name": "import_names", + "import-namespace": "import_namespaces", + "keywords": "keywords", + "license": "license", + "license-expression": "license_expression", + "license-file": "license_files", + "maintainer": "maintainer", + "maintainer-email": "maintainer_email", + "metadata-version": "metadata_version", + "name": "name", + "obsoletes": "obsoletes", + "obsoletes-dist": "obsoletes_dist", + "platform": "platforms", + "project-url": "project_urls", + "provides": "provides", + "provides-dist": "provides_dist", + "provides-extra": "provides_extra", + "requires": "requires", + "requires-dist": "requires_dist", + "requires-external": "requires_external", + "requires-python": "requires_python", + "summary": "summary", + "supported-platform": "supported_platforms", + "version": "version", +} +_RAW_TO_EMAIL_MAPPING = {raw: email for email, raw in _EMAIL_TO_RAW_MAPPING.items()} + + +# This class is for writing RFC822 messages +class RFC822Policy(email.policy.EmailPolicy): + """ + This is :class:`email.policy.EmailPolicy`, but with a simple ``header_store_parse`` + implementation that handles multi-line values, and some nice defaults. + """ + + utf8 = True + mangle_from_ = False + max_line_length = 0 + + def header_store_parse(self, name: str, value: str) -> tuple[str, str]: + size = len(name) + 2 + value = value.replace("\n", "\n" + " " * size) + return (name, value) + + +# This class is for writing RFC822 messages +class RFC822Message(email.message.EmailMessage): + """ + This is :class:`email.message.EmailMessage` with two small changes: it defaults to + our `RFC822Policy`, and it correctly writes unicode when being called + with `bytes()`. + """ + + def __init__(self) -> None: + super().__init__(policy=RFC822Policy()) + + def as_bytes( + self, unixfrom: bool = False, policy: email.policy.Policy | None = None + ) -> bytes: + """ + Return the bytes representation of the message. + + This handles unicode encoding. + """ + return self.as_string(unixfrom, policy=policy).encode("utf-8") + + +def parse_email(data: bytes | str) -> tuple[RawMetadata, dict[str, list[str]]]: + """Parse a distribution's metadata stored as email headers (e.g. from ``METADATA``). + + This function returns a two-item tuple of dicts. The first dict is of + recognized fields from the core metadata specification. Fields that can be + parsed and translated into Python's built-in types are converted + appropriately. All other fields are left as-is. Fields that are allowed to + appear multiple times are stored as lists. + + The second dict contains all other fields from the metadata. This includes + any unrecognized fields. It also includes any fields which are expected to + be parsed into a built-in type but were not formatted appropriately. Finally, + any fields that are expected to appear only once but are repeated are + included in this dict. + + """ + raw: dict[str, str | list[str] | dict[str, str]] = {} + unparsed: dict[str, list[str]] = {} + + if isinstance(data, str): + parsed = email.parser.Parser(policy=email.policy.compat32).parsestr(data) + else: + parsed = email.parser.BytesParser(policy=email.policy.compat32).parsebytes(data) + + # We have to wrap parsed.keys() in a set, because in the case of multiple + # values for a key (a list), the key will appear multiple times in the + # list of keys, but we're avoiding that by using get_all(). + for name_with_case in frozenset(parsed.keys()): + # Header names in RFC are case insensitive, so we'll normalize to all + # lower case to make comparisons easier. + name = name_with_case.lower() + + # We use get_all() here, even for fields that aren't multiple use, + # because otherwise someone could have e.g. two Name fields, and we + # would just silently ignore it rather than doing something about it. + headers = parsed.get_all(name) or [] + + # The way the email module works when parsing bytes is that it + # unconditionally decodes the bytes as ascii using the surrogateescape + # handler. When you pull that data back out (such as with get_all() ), + # it looks to see if the str has any surrogate escapes, and if it does + # it wraps it in a Header object instead of returning the string. + # + # As such, we'll look for those Header objects, and fix up the encoding. + value = [] + # Flag if we have run into any issues processing the headers, thus + # signalling that the data belongs in 'unparsed'. + valid_encoding = True + for h in headers: + # It's unclear if this can return more types than just a Header or + # a str, so we'll just assert here to make sure. + assert isinstance(h, (email.header.Header, str)) + + # If it's a header object, we need to do our little dance to get + # the real data out of it. In cases where there is invalid data + # we're going to end up with mojibake, but there's no obvious, good + # way around that without reimplementing parts of the Header object + # ourselves. + # + # That should be fine since, if mojibacked happens, this key is + # going into the unparsed dict anyways. + if isinstance(h, email.header.Header): + # The Header object stores it's data as chunks, and each chunk + # can be independently encoded, so we'll need to check each + # of them. + chunks: list[tuple[bytes, str | None]] = [] + for binary, _encoding in email.header.decode_header(h): + try: + binary.decode("utf8", "strict") + except UnicodeDecodeError: + # Enable mojibake. + encoding = "latin1" + valid_encoding = False + else: + encoding = "utf8" + chunks.append((binary, encoding)) + + # Turn our chunks back into a Header object, then let that + # Header object do the right thing to turn them into a + # string for us. + value.append(str(email.header.make_header(chunks))) + # This is already a string, so just add it. + else: + value.append(h) + + # We've processed all of our values to get them into a list of str, + # but we may have mojibake data, in which case this is an unparsed + # field. + if not valid_encoding: + unparsed[name] = value + continue + + raw_name = _EMAIL_TO_RAW_MAPPING.get(name) + if raw_name is None: + # This is a bit of a weird situation, we've encountered a key that + # we don't know what it means, so we don't know whether it's meant + # to be a list or not. + # + # Since we can't really tell one way or another, we'll just leave it + # as a list, even though it may be a single item list, because that's + # what makes the most sense for email headers. + unparsed[name] = value + continue + + # If this is one of our string fields, then we'll check to see if our + # value is a list of a single item. If it is then we'll assume that + # it was emitted as a single string, and unwrap the str from inside + # the list. + # + # If it's any other kind of data, then we haven't the faintest clue + # what we should parse it as, and we have to just add it to our list + # of unparsed stuff. + if raw_name in _STRING_FIELDS and len(value) == 1: + raw[raw_name] = value[0] + # If this is import_names, we need to special case the empty field + # case, which converts to an empty list instead of None. We can't let + # the empty case slip through, as it will fail validation. + elif raw_name == "import_names" and value == [""]: + raw[raw_name] = [] + # If this is one of our list of string fields, then we can just assign + # the value, since email *only* has strings, and our get_all() call + # above ensures that this is a list. + elif raw_name in _LIST_FIELDS: + raw[raw_name] = value + # Special Case: Keywords + # The keywords field is implemented in the metadata spec as a str, + # but it conceptually is a list of strings, and is serialized using + # ", ".join(keywords), so we'll do some light data massaging to turn + # this into what it logically is. + elif raw_name == "keywords" and len(value) == 1: + raw[raw_name] = _parse_keywords(value[0]) + # Special Case: Project-URL + # The project urls is implemented in the metadata spec as a list of + # specially-formatted strings that represent a key and a value, which + # is fundamentally a mapping, however the email format doesn't support + # mappings in a sane way, so it was crammed into a list of strings + # instead. + # + # We will do a little light data massaging to turn this into a map as + # it logically should be. + elif raw_name == "project_urls": + try: + raw[raw_name] = _parse_project_urls(value) + except KeyError: + unparsed[name] = value + # Nothing that we've done has managed to parse this, so it'll just + # throw it in our unparsable data and move on. + else: + unparsed[name] = value + + # We need to support getting the Description from the message payload in + # addition to getting it from the the headers. This does mean, though, there + # is the possibility of it being set both ways, in which case we put both + # in 'unparsed' since we don't know which is right. + try: + payload = _get_payload(parsed, data) + except ValueError: + unparsed.setdefault("description", []).append( + parsed.get_payload(decode=isinstance(data, bytes)) # type: ignore[call-overload] + ) + else: + if payload: + # Check to see if we've already got a description, if so then both + # it, and this body move to unparsable. + if "description" in raw: + description_header = cast("str", raw.pop("description")) + unparsed.setdefault("description", []).extend( + [description_header, payload] + ) + elif "description" in unparsed: + unparsed["description"].append(payload) + else: + raw["description"] = payload + + # We need to cast our `raw` to a metadata, because a TypedDict only support + # literal key names, but we're computing our key names on purpose, but the + # way this function is implemented, our `TypedDict` can only have valid key + # names. + return cast("RawMetadata", raw), unparsed + + +_NOT_FOUND = object() + + +# Keep the two values in sync. +_VALID_METADATA_VERSIONS = ["1.0", "1.1", "1.2", "2.1", "2.2", "2.3", "2.4", "2.5"] +_MetadataVersion = Literal["1.0", "1.1", "1.2", "2.1", "2.2", "2.3", "2.4", "2.5"] + +_REQUIRED_ATTRS = frozenset(["metadata_version", "name", "version"]) + + +class _Validator(Generic[T]): + """Validate a metadata field. + + All _process_*() methods correspond to a core metadata field. The method is + called with the field's raw value. If the raw value is valid it is returned + in its "enriched" form (e.g. ``version.Version`` for the ``Version`` field). + If the raw value is invalid, :exc:`InvalidMetadata` is raised (with a cause + as appropriate). + """ + + name: str + raw_name: str + added: _MetadataVersion + + def __init__( + self, + *, + added: _MetadataVersion = "1.0", + ) -> None: + self.added = added + + def __set_name__(self, _owner: Metadata, name: str) -> None: + self.name = name + self.raw_name = _RAW_TO_EMAIL_MAPPING[name] + + def __get__(self, instance: Metadata, _owner: type[Metadata]) -> T: + # With Python 3.8, the caching can be replaced with functools.cached_property(). + # No need to check the cache as attribute lookup will resolve into the + # instance's __dict__ before __get__ is called. + cache = instance.__dict__ + value = instance._raw.get(self.name) + + # To make the _process_* methods easier, we'll check if the value is None + # and if this field is NOT a required attribute, and if both of those + # things are true, we'll skip the the converter. This will mean that the + # converters never have to deal with the None union. + if self.name in _REQUIRED_ATTRS or value is not None: + try: + converter: Callable[[Any], T] = getattr(self, f"_process_{self.name}") + except AttributeError: + pass + else: + value = converter(value) + + cache[self.name] = value + try: + del instance._raw[self.name] # type: ignore[misc] + except KeyError: + pass + + return cast("T", value) + + def _invalid_metadata( + self, msg: str, cause: Exception | None = None + ) -> InvalidMetadata: + exc = InvalidMetadata( + self.raw_name, msg.format_map({"field": repr(self.raw_name)}) + ) + exc.__cause__ = cause + return exc + + def _process_metadata_version(self, value: str) -> _MetadataVersion: + # Implicitly makes Metadata-Version required. + if value not in _VALID_METADATA_VERSIONS: + raise self._invalid_metadata(f"{value!r} is not a valid metadata version") + return cast("_MetadataVersion", value) + + def _process_name(self, value: str) -> str: + if not value: + raise self._invalid_metadata("{field} is a required field") + # Validate the name as a side-effect. + try: + utils.canonicalize_name(value, validate=True) + except utils.InvalidName as exc: + raise self._invalid_metadata( + f"{value!r} is invalid for {{field}}", cause=exc + ) from exc + else: + return value + + def _process_version(self, value: str) -> version_module.Version: + if not value: + raise self._invalid_metadata("{field} is a required field") + try: + return version_module.parse(value) + except version_module.InvalidVersion as exc: + raise self._invalid_metadata( + f"{value!r} is invalid for {{field}}", cause=exc + ) from exc + + def _process_summary(self, value: str) -> str: + """Check the field contains no newlines.""" + if "\n" in value: + raise self._invalid_metadata("{field} must be a single line") + return value + + def _process_description_content_type(self, value: str) -> str: + content_types = {"text/plain", "text/x-rst", "text/markdown"} + message = email.message.EmailMessage() + message["content-type"] = value + + content_type, parameters = ( + # Defaults to `text/plain` if parsing failed. + message.get_content_type().lower(), + message["content-type"].params, + ) + # Check if content-type is valid or defaulted to `text/plain` and thus was + # not parseable. + if content_type not in content_types or content_type not in value.lower(): + raise self._invalid_metadata( + f"{{field}} must be one of {list(content_types)}, not {value!r}" + ) + + charset = parameters.get("charset", "UTF-8") + if charset != "UTF-8": + raise self._invalid_metadata( + f"{{field}} can only specify the UTF-8 charset, not {list(charset)}" + ) + + markdown_variants = {"GFM", "CommonMark"} + variant = parameters.get("variant", "GFM") # Use an acceptable default. + if content_type == "text/markdown" and variant not in markdown_variants: + raise self._invalid_metadata( + f"valid Markdown variants for {{field}} are {list(markdown_variants)}, " + f"not {variant!r}", + ) + return value + + def _process_dynamic(self, value: list[str]) -> list[str]: + for dynamic_field in map(str.lower, value): + if dynamic_field in {"name", "version", "metadata-version"}: + raise self._invalid_metadata( + f"{dynamic_field!r} is not allowed as a dynamic field" + ) + elif dynamic_field not in _EMAIL_TO_RAW_MAPPING: + raise self._invalid_metadata( + f"{dynamic_field!r} is not a valid dynamic field" + ) + return list(map(str.lower, value)) + + def _process_provides_extra( + self, + value: list[str], + ) -> list[utils.NormalizedName]: + normalized_names = [] + try: + for name in value: + normalized_names.append(utils.canonicalize_name(name, validate=True)) + except utils.InvalidName as exc: + raise self._invalid_metadata( + f"{name!r} is invalid for {{field}}", cause=exc + ) from exc + else: + return normalized_names + + def _process_requires_python(self, value: str) -> specifiers.SpecifierSet: + try: + return specifiers.SpecifierSet(value) + except specifiers.InvalidSpecifier as exc: + raise self._invalid_metadata( + f"{value!r} is invalid for {{field}}", cause=exc + ) from exc + + def _process_requires_dist( + self, + value: list[str], + ) -> list[requirements.Requirement]: + reqs = [] + try: + for req in value: + reqs.append(requirements.Requirement(req)) + except requirements.InvalidRequirement as exc: + raise self._invalid_metadata( + f"{req!r} is invalid for {{field}}", cause=exc + ) from exc + else: + return reqs + + def _process_license_expression(self, value: str) -> NormalizedLicenseExpression: + try: + return licenses.canonicalize_license_expression(value) + except ValueError as exc: + raise self._invalid_metadata( + f"{value!r} is invalid for {{field}}", cause=exc + ) from exc + + def _process_license_files(self, value: list[str]) -> list[str]: + paths = [] + for path in value: + if ".." in path: + raise self._invalid_metadata( + f"{path!r} is invalid for {{field}}, " + "parent directory indicators are not allowed" + ) + if "*" in path: + raise self._invalid_metadata( + f"{path!r} is invalid for {{field}}, paths must be resolved" + ) + if ( + pathlib.PurePosixPath(path).is_absolute() + or pathlib.PureWindowsPath(path).is_absolute() + ): + raise self._invalid_metadata( + f"{path!r} is invalid for {{field}}, paths must be relative" + ) + if pathlib.PureWindowsPath(path).as_posix() != path: + raise self._invalid_metadata( + f"{path!r} is invalid for {{field}}, paths must use '/' delimiter" + ) + paths.append(path) + return paths + + def _process_import_names(self, value: list[str]) -> list[str]: + for import_name in value: + name, semicolon, private = import_name.partition(";") + name = name.rstrip() + for identifier in name.split("."): + if not identifier.isidentifier(): + raise self._invalid_metadata( + f"{name!r} is invalid for {{field}}; " + f"{identifier!r} is not a valid identifier" + ) + elif keyword.iskeyword(identifier): + raise self._invalid_metadata( + f"{name!r} is invalid for {{field}}; " + f"{identifier!r} is a keyword" + ) + if semicolon and private.lstrip() != "private": + raise self._invalid_metadata( + f"{import_name!r} is invalid for {{field}}; " + "the only valid option is 'private'" + ) + return value + + _process_import_namespaces = _process_import_names + + +class Metadata: + """Representation of distribution metadata. + + Compared to :class:`RawMetadata`, this class provides objects representing + metadata fields instead of only using built-in types. Any invalid metadata + will cause :exc:`InvalidMetadata` to be raised (with a + :py:attr:`~BaseException.__cause__` attribute as appropriate). + """ + + _raw: RawMetadata + + @classmethod + def from_raw(cls, data: RawMetadata, *, validate: bool = True) -> Metadata: + """Create an instance from :class:`RawMetadata`. + + If *validate* is true, all metadata will be validated. All exceptions + related to validation will be gathered and raised as an :class:`ExceptionGroup`. + """ + ins = cls() + ins._raw = data.copy() # Mutations occur due to caching enriched values. + + if validate: + exceptions: list[Exception] = [] + try: + metadata_version = ins.metadata_version + metadata_age = _VALID_METADATA_VERSIONS.index(metadata_version) + except InvalidMetadata as metadata_version_exc: + exceptions.append(metadata_version_exc) + metadata_version = None + + # Make sure to check for the fields that are present, the required + # fields (so their absence can be reported). + fields_to_check = frozenset(ins._raw) | _REQUIRED_ATTRS + # Remove fields that have already been checked. + fields_to_check -= {"metadata_version"} + + for key in fields_to_check: + try: + if metadata_version: + # Can't use getattr() as that triggers descriptor protocol which + # will fail due to no value for the instance argument. + try: + field_metadata_version = cls.__dict__[key].added + except KeyError: + exc = InvalidMetadata(key, f"unrecognized field: {key!r}") + exceptions.append(exc) + continue + field_age = _VALID_METADATA_VERSIONS.index( + field_metadata_version + ) + if field_age > metadata_age: + field = _RAW_TO_EMAIL_MAPPING[key] + exc = InvalidMetadata( + field, + f"{field} introduced in metadata version " + f"{field_metadata_version}, not {metadata_version}", + ) + exceptions.append(exc) + continue + getattr(ins, key) + except InvalidMetadata as exc: + exceptions.append(exc) + + if exceptions: + raise ExceptionGroup("invalid metadata", exceptions) + + return ins + + @classmethod + def from_email(cls, data: bytes | str, *, validate: bool = True) -> Metadata: + """Parse metadata from email headers. + + If *validate* is true, the metadata will be validated. All exceptions + related to validation will be gathered and raised as an :class:`ExceptionGroup`. + """ + raw, unparsed = parse_email(data) + + if validate: + exceptions: list[Exception] = [] + for unparsed_key in unparsed: + if unparsed_key in _EMAIL_TO_RAW_MAPPING: + message = f"{unparsed_key!r} has invalid data" + else: + message = f"unrecognized field: {unparsed_key!r}" + exceptions.append(InvalidMetadata(unparsed_key, message)) + + if exceptions: + raise ExceptionGroup("unparsed", exceptions) + + try: + return cls.from_raw(raw, validate=validate) + except ExceptionGroup as exc_group: + raise ExceptionGroup( + "invalid or unparsed metadata", exc_group.exceptions + ) from None + + metadata_version: _Validator[_MetadataVersion] = _Validator() + """:external:ref:`core-metadata-metadata-version` + (required; validated to be a valid metadata version)""" + # `name` is not normalized/typed to NormalizedName so as to provide access to + # the original/raw name. + name: _Validator[str] = _Validator() + """:external:ref:`core-metadata-name` + (required; validated using :func:`~packaging.utils.canonicalize_name` and its + *validate* parameter)""" + version: _Validator[version_module.Version] = _Validator() + """:external:ref:`core-metadata-version` (required)""" + dynamic: _Validator[list[str] | None] = _Validator( + added="2.2", + ) + """:external:ref:`core-metadata-dynamic` + (validated against core metadata field names and lowercased)""" + platforms: _Validator[list[str] | None] = _Validator() + """:external:ref:`core-metadata-platform`""" + supported_platforms: _Validator[list[str] | None] = _Validator(added="1.1") + """:external:ref:`core-metadata-supported-platform`""" + summary: _Validator[str | None] = _Validator() + """:external:ref:`core-metadata-summary` (validated to contain no newlines)""" + description: _Validator[str | None] = _Validator() # TODO 2.1: can be in body + """:external:ref:`core-metadata-description`""" + description_content_type: _Validator[str | None] = _Validator(added="2.1") + """:external:ref:`core-metadata-description-content-type` (validated)""" + keywords: _Validator[list[str] | None] = _Validator() + """:external:ref:`core-metadata-keywords`""" + home_page: _Validator[str | None] = _Validator() + """:external:ref:`core-metadata-home-page`""" + download_url: _Validator[str | None] = _Validator(added="1.1") + """:external:ref:`core-metadata-download-url`""" + author: _Validator[str | None] = _Validator() + """:external:ref:`core-metadata-author`""" + author_email: _Validator[str | None] = _Validator() + """:external:ref:`core-metadata-author-email`""" + maintainer: _Validator[str | None] = _Validator(added="1.2") + """:external:ref:`core-metadata-maintainer`""" + maintainer_email: _Validator[str | None] = _Validator(added="1.2") + """:external:ref:`core-metadata-maintainer-email`""" + license: _Validator[str | None] = _Validator() + """:external:ref:`core-metadata-license`""" + license_expression: _Validator[NormalizedLicenseExpression | None] = _Validator( + added="2.4" + ) + """:external:ref:`core-metadata-license-expression`""" + license_files: _Validator[list[str] | None] = _Validator(added="2.4") + """:external:ref:`core-metadata-license-file`""" + classifiers: _Validator[list[str] | None] = _Validator(added="1.1") + """:external:ref:`core-metadata-classifier`""" + requires_dist: _Validator[list[requirements.Requirement] | None] = _Validator( + added="1.2" + ) + """:external:ref:`core-metadata-requires-dist`""" + requires_python: _Validator[specifiers.SpecifierSet | None] = _Validator( + added="1.2" + ) + """:external:ref:`core-metadata-requires-python`""" + # Because `Requires-External` allows for non-PEP 440 version specifiers, we + # don't do any processing on the values. + requires_external: _Validator[list[str] | None] = _Validator(added="1.2") + """:external:ref:`core-metadata-requires-external`""" + project_urls: _Validator[dict[str, str] | None] = _Validator(added="1.2") + """:external:ref:`core-metadata-project-url`""" + # PEP 685 lets us raise an error if an extra doesn't pass `Name` validation + # regardless of metadata version. + provides_extra: _Validator[list[utils.NormalizedName] | None] = _Validator( + added="2.1", + ) + """:external:ref:`core-metadata-provides-extra`""" + provides_dist: _Validator[list[str] | None] = _Validator(added="1.2") + """:external:ref:`core-metadata-provides-dist`""" + obsoletes_dist: _Validator[list[str] | None] = _Validator(added="1.2") + """:external:ref:`core-metadata-obsoletes-dist`""" + import_names: _Validator[list[str] | None] = _Validator(added="2.5") + """:external:ref:`core-metadata-import-name`""" + import_namespaces: _Validator[list[str] | None] = _Validator(added="2.5") + """:external:ref:`core-metadata-import-namespace`""" + requires: _Validator[list[str] | None] = _Validator(added="1.1") + """``Requires`` (deprecated)""" + provides: _Validator[list[str] | None] = _Validator(added="1.1") + """``Provides`` (deprecated)""" + obsoletes: _Validator[list[str] | None] = _Validator(added="1.1") + """``Obsoletes`` (deprecated)""" + + def as_rfc822(self) -> RFC822Message: + """ + Return an RFC822 message with the metadata. + """ + message = RFC822Message() + self._write_metadata(message) + return message + + def _write_metadata(self, message: RFC822Message) -> None: + """ + Return an RFC822 message with the metadata. + """ + for name, validator in self.__class__.__dict__.items(): + if isinstance(validator, _Validator) and name != "description": + value = getattr(self, name) + email_name = _RAW_TO_EMAIL_MAPPING[name] + if value is not None: + if email_name == "project-url": + for label, url in value.items(): + message[email_name] = f"{label}, {url}" + elif email_name == "keywords": + message[email_name] = ",".join(value) + elif email_name == "import-name" and value == []: + message[email_name] = "" + elif isinstance(value, list): + for item in value: + message[email_name] = str(item) + else: + message[email_name] = str(value) + + # The description is a special case because it is in the body of the message. + if self.description is not None: + message.set_payload(self.description) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/packaging/py.typed b/TTS/Kokoro/.venv/Lib/site-packages/packaging/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/TTS/Kokoro/.venv/Lib/site-packages/packaging/pylock.py b/TTS/Kokoro/.venv/Lib/site-packages/packaging/pylock.py new file mode 100644 index 0000000000000000000000000000000000000000..a564f15246ad65038029f8fefb48621fa64a3abd --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/packaging/pylock.py @@ -0,0 +1,635 @@ +from __future__ import annotations + +import dataclasses +import logging +import re +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from datetime import datetime +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Protocol, + TypeVar, +) + +from .markers import Marker +from .specifiers import SpecifierSet +from .utils import NormalizedName, is_normalized_name +from .version import Version + +if TYPE_CHECKING: # pragma: no cover + from pathlib import Path + + from typing_extensions import Self + +_logger = logging.getLogger(__name__) + +__all__ = [ + "Package", + "PackageArchive", + "PackageDirectory", + "PackageSdist", + "PackageVcs", + "PackageWheel", + "Pylock", + "PylockUnsupportedVersionError", + "PylockValidationError", + "is_valid_pylock_path", +] + +_T = TypeVar("_T") +_T2 = TypeVar("_T2") + + +class _FromMappingProtocol(Protocol): # pragma: no cover + @classmethod + def _from_dict(cls, d: Mapping[str, Any]) -> Self: ... + + +_FromMappingProtocolT = TypeVar("_FromMappingProtocolT", bound=_FromMappingProtocol) + + +_PYLOCK_FILE_NAME_RE = re.compile(r"^pylock\.([^.]+)\.toml$") + + +def is_valid_pylock_path(path: Path) -> bool: + """Check if the given path is a valid pylock file path.""" + return path.name == "pylock.toml" or bool(_PYLOCK_FILE_NAME_RE.match(path.name)) + + +def _toml_key(key: str) -> str: + return key.replace("_", "-") + + +def _toml_value(key: str, value: Any) -> Any: # noqa: ANN401 + if isinstance(value, (Version, Marker, SpecifierSet)): + return str(value) + if isinstance(value, Sequence) and key == "environments": + return [str(v) for v in value] + return value + + +def _toml_dict_factory(data: list[tuple[str, Any]]) -> dict[str, Any]: + return { + _toml_key(key): _toml_value(key, value) + for key, value in data + if value is not None + } + + +def _get(d: Mapping[str, Any], expected_type: type[_T], key: str) -> _T | None: + """Get a value from the dictionary and verify it's the expected type.""" + if (value := d.get(key)) is None: + return None + if not isinstance(value, expected_type): + raise PylockValidationError( + f"Unexpected type {type(value).__name__} " + f"(expected {expected_type.__name__})", + context=key, + ) + return value + + +def _get_required(d: Mapping[str, Any], expected_type: type[_T], key: str) -> _T: + """Get a required value from the dictionary and verify it's the expected type.""" + if (value := _get(d, expected_type, key)) is None: + raise _PylockRequiredKeyError(key) + return value + + +def _get_sequence( + d: Mapping[str, Any], expected_item_type: type[_T], key: str +) -> Sequence[_T] | None: + """Get a list value from the dictionary and verify it's the expected items type.""" + if (value := _get(d, Sequence, key)) is None: # type: ignore[type-abstract] + return None + if isinstance(value, (str, bytes)): + # special case: str and bytes are Sequences, but we want to reject it + raise PylockValidationError( + f"Unexpected type {type(value).__name__} (expected Sequence)", + context=key, + ) + for i, item in enumerate(value): + if not isinstance(item, expected_item_type): + raise PylockValidationError( + f"Unexpected type {type(item).__name__} " + f"(expected {expected_item_type.__name__})", + context=f"{key}[{i}]", + ) + return value + + +def _get_as( + d: Mapping[str, Any], + expected_type: type[_T], + target_type: Callable[[_T], _T2], + key: str, +) -> _T2 | None: + """Get a value from the dictionary, verify it's the expected type, + and convert to the target type. + + This assumes the target_type constructor accepts the value. + """ + if (value := _get(d, expected_type, key)) is None: + return None + try: + return target_type(value) + except Exception as e: + raise PylockValidationError(e, context=key) from e + + +def _get_required_as( + d: Mapping[str, Any], + expected_type: type[_T], + target_type: Callable[[_T], _T2], + key: str, +) -> _T2: + """Get a required value from the dict, verify it's the expected type, + and convert to the target type.""" + if (value := _get_as(d, expected_type, target_type, key)) is None: + raise _PylockRequiredKeyError(key) + return value + + +def _get_sequence_as( + d: Mapping[str, Any], + expected_item_type: type[_T], + target_item_type: Callable[[_T], _T2], + key: str, +) -> list[_T2] | None: + """Get list value from dictionary and verify expected items type.""" + if (value := _get_sequence(d, expected_item_type, key)) is None: + return None + result = [] + try: + for item in value: + typed_item = target_item_type(item) + result.append(typed_item) + except Exception as e: + raise PylockValidationError(e, context=f"{key}[{len(result)}]") from e + return result + + +def _get_object( + d: Mapping[str, Any], target_type: type[_FromMappingProtocolT], key: str +) -> _FromMappingProtocolT | None: + """Get a dictionary value from the dictionary and convert it to a dataclass.""" + if (value := _get(d, Mapping, key)) is None: # type: ignore[type-abstract] + return None + try: + return target_type._from_dict(value) + except Exception as e: + raise PylockValidationError(e, context=key) from e + + +def _get_sequence_of_objects( + d: Mapping[str, Any], target_item_type: type[_FromMappingProtocolT], key: str +) -> list[_FromMappingProtocolT] | None: + """Get a list value from the dictionary and convert its items to a dataclass.""" + if (value := _get_sequence(d, Mapping, key)) is None: # type: ignore[type-abstract] + return None + result: list[_FromMappingProtocolT] = [] + try: + for item in value: + typed_item = target_item_type._from_dict(item) + result.append(typed_item) + except Exception as e: + raise PylockValidationError(e, context=f"{key}[{len(result)}]") from e + return result + + +def _get_required_sequence_of_objects( + d: Mapping[str, Any], target_item_type: type[_FromMappingProtocolT], key: str +) -> Sequence[_FromMappingProtocolT]: + """Get a required list value from the dictionary and convert its items to a + dataclass.""" + if (result := _get_sequence_of_objects(d, target_item_type, key)) is None: + raise _PylockRequiredKeyError(key) + return result + + +def _validate_normalized_name(name: str) -> NormalizedName: + """Validate that a string is a NormalizedName.""" + if not is_normalized_name(name): + raise PylockValidationError(f"Name {name!r} is not normalized") + return NormalizedName(name) + + +def _validate_path_url(path: str | None, url: str | None) -> None: + if not path and not url: + raise PylockValidationError("path or url must be provided") + + +def _validate_hashes(hashes: Mapping[str, Any]) -> Mapping[str, Any]: + if not hashes: + raise PylockValidationError("At least one hash must be provided") + if not all(isinstance(hash_val, str) for hash_val in hashes.values()): + raise PylockValidationError("Hash values must be strings") + return hashes + + +class PylockValidationError(Exception): + """Raised when when input data is not spec-compliant.""" + + context: str | None = None + message: str + + def __init__( + self, + cause: str | Exception, + *, + context: str | None = None, + ) -> None: + if isinstance(cause, PylockValidationError): + if cause.context: + self.context = ( + f"{context}.{cause.context}" if context else cause.context + ) + else: + self.context = context + self.message = cause.message + else: + self.context = context + self.message = str(cause) + + def __str__(self) -> str: + if self.context: + return f"{self.message} in {self.context!r}" + return self.message + + +class _PylockRequiredKeyError(PylockValidationError): + def __init__(self, key: str) -> None: + super().__init__("Missing required value", context=key) + + +class PylockUnsupportedVersionError(PylockValidationError): + """Raised when encountering an unsupported `lock_version`.""" + + +@dataclass(frozen=True, init=False) +class PackageVcs: + type: str + url: str | None = None + path: str | None = None + requested_revision: str | None = None + commit_id: str # type: ignore[misc] + subdirectory: str | None = None + + def __init__( + self, + *, + type: str, + url: str | None = None, + path: str | None = None, + requested_revision: str | None = None, + commit_id: str, + subdirectory: str | None = None, + ) -> None: + # In Python 3.10+ make dataclass kw_only=True and remove __init__ + object.__setattr__(self, "type", type) + object.__setattr__(self, "url", url) + object.__setattr__(self, "path", path) + object.__setattr__(self, "requested_revision", requested_revision) + object.__setattr__(self, "commit_id", commit_id) + object.__setattr__(self, "subdirectory", subdirectory) + + @classmethod + def _from_dict(cls, d: Mapping[str, Any]) -> Self: + package_vcs = cls( + type=_get_required(d, str, "type"), + url=_get(d, str, "url"), + path=_get(d, str, "path"), + requested_revision=_get(d, str, "requested-revision"), + commit_id=_get_required(d, str, "commit-id"), + subdirectory=_get(d, str, "subdirectory"), + ) + _validate_path_url(package_vcs.path, package_vcs.url) + return package_vcs + + +@dataclass(frozen=True, init=False) +class PackageDirectory: + path: str + editable: bool | None = None + subdirectory: str | None = None + + def __init__( + self, + *, + path: str, + editable: bool | None = None, + subdirectory: str | None = None, + ) -> None: + # In Python 3.10+ make dataclass kw_only=True and remove __init__ + object.__setattr__(self, "path", path) + object.__setattr__(self, "editable", editable) + object.__setattr__(self, "subdirectory", subdirectory) + + @classmethod + def _from_dict(cls, d: Mapping[str, Any]) -> Self: + return cls( + path=_get_required(d, str, "path"), + editable=_get(d, bool, "editable"), + subdirectory=_get(d, str, "subdirectory"), + ) + + +@dataclass(frozen=True, init=False) +class PackageArchive: + url: str | None = None + path: str | None = None + size: int | None = None + upload_time: datetime | None = None + hashes: Mapping[str, str] # type: ignore[misc] + subdirectory: str | None = None + + def __init__( + self, + *, + url: str | None = None, + path: str | None = None, + size: int | None = None, + upload_time: datetime | None = None, + hashes: Mapping[str, str], + subdirectory: str | None = None, + ) -> None: + # In Python 3.10+ make dataclass kw_only=True and remove __init__ + object.__setattr__(self, "url", url) + object.__setattr__(self, "path", path) + object.__setattr__(self, "size", size) + object.__setattr__(self, "upload_time", upload_time) + object.__setattr__(self, "hashes", hashes) + object.__setattr__(self, "subdirectory", subdirectory) + + @classmethod + def _from_dict(cls, d: Mapping[str, Any]) -> Self: + package_archive = cls( + url=_get(d, str, "url"), + path=_get(d, str, "path"), + size=_get(d, int, "size"), + upload_time=_get(d, datetime, "upload-time"), + hashes=_get_required_as(d, Mapping, _validate_hashes, "hashes"), # type: ignore[type-abstract] + subdirectory=_get(d, str, "subdirectory"), + ) + _validate_path_url(package_archive.path, package_archive.url) + return package_archive + + +@dataclass(frozen=True, init=False) +class PackageSdist: + name: str | None = None + upload_time: datetime | None = None + url: str | None = None + path: str | None = None + size: int | None = None + hashes: Mapping[str, str] # type: ignore[misc] + + def __init__( + self, + *, + name: str | None = None, + upload_time: datetime | None = None, + url: str | None = None, + path: str | None = None, + size: int | None = None, + hashes: Mapping[str, str], + ) -> None: + # In Python 3.10+ make dataclass kw_only=True and remove __init__ + object.__setattr__(self, "name", name) + object.__setattr__(self, "upload_time", upload_time) + object.__setattr__(self, "url", url) + object.__setattr__(self, "path", path) + object.__setattr__(self, "size", size) + object.__setattr__(self, "hashes", hashes) + + @classmethod + def _from_dict(cls, d: Mapping[str, Any]) -> Self: + package_sdist = cls( + name=_get(d, str, "name"), + upload_time=_get(d, datetime, "upload-time"), + url=_get(d, str, "url"), + path=_get(d, str, "path"), + size=_get(d, int, "size"), + hashes=_get_required_as(d, Mapping, _validate_hashes, "hashes"), # type: ignore[type-abstract] + ) + _validate_path_url(package_sdist.path, package_sdist.url) + return package_sdist + + +@dataclass(frozen=True, init=False) +class PackageWheel: + name: str | None = None + upload_time: datetime | None = None + url: str | None = None + path: str | None = None + size: int | None = None + hashes: Mapping[str, str] # type: ignore[misc] + + def __init__( + self, + *, + name: str | None = None, + upload_time: datetime | None = None, + url: str | None = None, + path: str | None = None, + size: int | None = None, + hashes: Mapping[str, str], + ) -> None: + # In Python 3.10+ make dataclass kw_only=True and remove __init__ + object.__setattr__(self, "name", name) + object.__setattr__(self, "upload_time", upload_time) + object.__setattr__(self, "url", url) + object.__setattr__(self, "path", path) + object.__setattr__(self, "size", size) + object.__setattr__(self, "hashes", hashes) + + @classmethod + def _from_dict(cls, d: Mapping[str, Any]) -> Self: + package_wheel = cls( + name=_get(d, str, "name"), + upload_time=_get(d, datetime, "upload-time"), + url=_get(d, str, "url"), + path=_get(d, str, "path"), + size=_get(d, int, "size"), + hashes=_get_required_as(d, Mapping, _validate_hashes, "hashes"), # type: ignore[type-abstract] + ) + _validate_path_url(package_wheel.path, package_wheel.url) + return package_wheel + + +@dataclass(frozen=True, init=False) +class Package: + name: NormalizedName + version: Version | None = None + marker: Marker | None = None + requires_python: SpecifierSet | None = None + dependencies: Sequence[Mapping[str, Any]] | None = None + vcs: PackageVcs | None = None + directory: PackageDirectory | None = None + archive: PackageArchive | None = None + index: str | None = None + sdist: PackageSdist | None = None + wheels: Sequence[PackageWheel] | None = None + attestation_identities: Sequence[Mapping[str, Any]] | None = None + tool: Mapping[str, Any] | None = None + + def __init__( + self, + *, + name: NormalizedName, + version: Version | None = None, + marker: Marker | None = None, + requires_python: SpecifierSet | None = None, + dependencies: Sequence[Mapping[str, Any]] | None = None, + vcs: PackageVcs | None = None, + directory: PackageDirectory | None = None, + archive: PackageArchive | None = None, + index: str | None = None, + sdist: PackageSdist | None = None, + wheels: Sequence[PackageWheel] | None = None, + attestation_identities: Sequence[Mapping[str, Any]] | None = None, + tool: Mapping[str, Any] | None = None, + ) -> None: + # In Python 3.10+ make dataclass kw_only=True and remove __init__ + object.__setattr__(self, "name", name) + object.__setattr__(self, "version", version) + object.__setattr__(self, "marker", marker) + object.__setattr__(self, "requires_python", requires_python) + object.__setattr__(self, "dependencies", dependencies) + object.__setattr__(self, "vcs", vcs) + object.__setattr__(self, "directory", directory) + object.__setattr__(self, "archive", archive) + object.__setattr__(self, "index", index) + object.__setattr__(self, "sdist", sdist) + object.__setattr__(self, "wheels", wheels) + object.__setattr__(self, "attestation_identities", attestation_identities) + object.__setattr__(self, "tool", tool) + + @classmethod + def _from_dict(cls, d: Mapping[str, Any]) -> Self: + package = cls( + name=_get_required_as(d, str, _validate_normalized_name, "name"), + version=_get_as(d, str, Version, "version"), + requires_python=_get_as(d, str, SpecifierSet, "requires-python"), + dependencies=_get_sequence(d, Mapping, "dependencies"), # type: ignore[type-abstract] + marker=_get_as(d, str, Marker, "marker"), + vcs=_get_object(d, PackageVcs, "vcs"), + directory=_get_object(d, PackageDirectory, "directory"), + archive=_get_object(d, PackageArchive, "archive"), + index=_get(d, str, "index"), + sdist=_get_object(d, PackageSdist, "sdist"), + wheels=_get_sequence_of_objects(d, PackageWheel, "wheels"), + attestation_identities=_get_sequence(d, Mapping, "attestation-identities"), # type: ignore[type-abstract] + tool=_get(d, Mapping, "tool"), # type: ignore[type-abstract] + ) + distributions = bool(package.sdist) + len(package.wheels or []) + direct_urls = ( + bool(package.vcs) + bool(package.directory) + bool(package.archive) + ) + if distributions > 0 and direct_urls > 0: + raise PylockValidationError( + "None of vcs, directory, archive must be set if sdist or wheels are set" + ) + if distributions == 0 and direct_urls != 1: + raise PylockValidationError( + "Exactly one of vcs, directory, archive must be set " + "if sdist and wheels are not set" + ) + try: + for i, attestation_identity in enumerate( # noqa: B007 + package.attestation_identities or [] + ): + _get_required(attestation_identity, str, "kind") + except Exception as e: + raise PylockValidationError( + e, context=f"attestation-identities[{i}]" + ) from e + return package + + @property + def is_direct(self) -> bool: + return not (self.sdist or self.wheels) + + +@dataclass(frozen=True, init=False) +class Pylock: + """A class representing a pylock file.""" + + lock_version: Version + environments: Sequence[Marker] | None = None + requires_python: SpecifierSet | None = None + extras: Sequence[NormalizedName] | None = None + dependency_groups: Sequence[str] | None = None + default_groups: Sequence[str] | None = None + created_by: str # type: ignore[misc] + packages: Sequence[Package] # type: ignore[misc] + tool: Mapping[str, Any] | None = None + + def __init__( + self, + *, + lock_version: Version, + environments: Sequence[Marker] | None = None, + requires_python: SpecifierSet | None = None, + extras: Sequence[NormalizedName] | None = None, + dependency_groups: Sequence[str] | None = None, + default_groups: Sequence[str] | None = None, + created_by: str, + packages: Sequence[Package], + tool: Mapping[str, Any] | None = None, + ) -> None: + # In Python 3.10+ make dataclass kw_only=True and remove __init__ + object.__setattr__(self, "lock_version", lock_version) + object.__setattr__(self, "environments", environments) + object.__setattr__(self, "requires_python", requires_python) + object.__setattr__(self, "extras", extras) + object.__setattr__(self, "dependency_groups", dependency_groups) + object.__setattr__(self, "default_groups", default_groups) + object.__setattr__(self, "created_by", created_by) + object.__setattr__(self, "packages", packages) + object.__setattr__(self, "tool", tool) + + @classmethod + def _from_dict(cls, d: Mapping[str, Any]) -> Self: + pylock = cls( + lock_version=_get_required_as(d, str, Version, "lock-version"), + environments=_get_sequence_as(d, str, Marker, "environments"), + extras=_get_sequence_as(d, str, _validate_normalized_name, "extras"), + dependency_groups=_get_sequence(d, str, "dependency-groups"), + default_groups=_get_sequence(d, str, "default-groups"), + created_by=_get_required(d, str, "created-by"), + requires_python=_get_as(d, str, SpecifierSet, "requires-python"), + packages=_get_required_sequence_of_objects(d, Package, "packages"), + tool=_get(d, Mapping, "tool"), # type: ignore[type-abstract] + ) + if not Version("1") <= pylock.lock_version < Version("2"): + raise PylockUnsupportedVersionError( + f"pylock version {pylock.lock_version} is not supported" + ) + if pylock.lock_version > Version("1.0"): + _logger.warning( + "pylock minor version %s is not supported", pylock.lock_version + ) + return pylock + + @classmethod + def from_dict(cls, d: Mapping[str, Any], /) -> Self: + """Create and validate a Pylock instance from a TOML dictionary. + + Raises :class:`PylockValidationError` if the input data is not + spec-compliant. + """ + return cls._from_dict(d) + + def to_dict(self) -> Mapping[str, Any]: + """Convert the Pylock instance to a TOML dictionary.""" + return dataclasses.asdict(self, dict_factory=_toml_dict_factory) + + def validate(self) -> None: + """Validate the Pylock instance against the specification. + + Raises :class:`PylockValidationError` otherwise.""" + self.from_dict(self.to_dict()) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/packaging/requirements.py b/TTS/Kokoro/.venv/Lib/site-packages/packaging/requirements.py new file mode 100644 index 0000000000000000000000000000000000000000..3079be69bf880f47e64dbf62993f0e54754b7315 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/packaging/requirements.py @@ -0,0 +1,86 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. +from __future__ import annotations + +from typing import Iterator + +from ._parser import parse_requirement as _parse_requirement +from ._tokenizer import ParserSyntaxError +from .markers import Marker, _normalize_extra_values +from .specifiers import SpecifierSet +from .utils import canonicalize_name + + +class InvalidRequirement(ValueError): + """ + An invalid requirement was found, users should refer to PEP 508. + """ + + +class Requirement: + """Parse a requirement. + + Parse a given requirement string into its parts, such as name, specifier, + URL, and extras. Raises InvalidRequirement on a badly-formed requirement + string. + """ + + # TODO: Can we test whether something is contained within a requirement? + # If so how do we do that? Do we need to test against the _name_ of + # the thing as well as the version? What about the markers? + # TODO: Can we normalize the name and extra name? + + def __init__(self, requirement_string: str) -> None: + try: + parsed = _parse_requirement(requirement_string) + except ParserSyntaxError as e: + raise InvalidRequirement(str(e)) from e + + self.name: str = parsed.name + self.url: str | None = parsed.url or None + self.extras: set[str] = set(parsed.extras or []) + self.specifier: SpecifierSet = SpecifierSet(parsed.specifier) + self.marker: Marker | None = None + if parsed.marker is not None: + self.marker = Marker.__new__(Marker) + self.marker._markers = _normalize_extra_values(parsed.marker) + + def _iter_parts(self, name: str) -> Iterator[str]: + yield name + + if self.extras: + formatted_extras = ",".join(sorted(self.extras)) + yield f"[{formatted_extras}]" + + if self.specifier: + yield str(self.specifier) + + if self.url: + yield f" @ {self.url}" + if self.marker: + yield " " + + if self.marker: + yield f"; {self.marker}" + + def __str__(self) -> str: + return "".join(self._iter_parts(self.name)) + + def __repr__(self) -> str: + return f"<{self.__class__.__name__}('{self}')>" + + def __hash__(self) -> int: + return hash(tuple(self._iter_parts(canonicalize_name(self.name)))) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, Requirement): + return NotImplemented + + return ( + canonicalize_name(self.name) == canonicalize_name(other.name) + and self.extras == other.extras + and self.specifier == other.specifier + and self.url == other.url + and self.marker == other.marker + ) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/packaging/specifiers.py b/TTS/Kokoro/.venv/Lib/site-packages/packaging/specifiers.py new file mode 100644 index 0000000000000000000000000000000000000000..5d26b0d1ae2d21b77e24b692d5a7e1fd01296edc --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/packaging/specifiers.py @@ -0,0 +1,1068 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. +""" +.. testsetup:: + + from packaging.specifiers import Specifier, SpecifierSet, InvalidSpecifier + from packaging.version import Version +""" + +from __future__ import annotations + +import abc +import itertools +import re +from typing import Callable, Final, Iterable, Iterator, TypeVar, Union + +from .utils import canonicalize_version +from .version import InvalidVersion, Version + +UnparsedVersion = Union[Version, str] +UnparsedVersionVar = TypeVar("UnparsedVersionVar", bound=UnparsedVersion) +CallableOperator = Callable[[Version, str], bool] + + +def _coerce_version(version: UnparsedVersion) -> Version | None: + if not isinstance(version, Version): + try: + version = Version(version) + except InvalidVersion: + return None + return version + + +def _public_version(version: Version) -> Version: + return version.__replace__(local=None) + + +def _base_version(version: Version) -> Version: + return version.__replace__(pre=None, post=None, dev=None, local=None) + + +class InvalidSpecifier(ValueError): + """ + Raised when attempting to create a :class:`Specifier` with a specifier + string that is invalid. + + >>> Specifier("lolwat") + Traceback (most recent call last): + ... + packaging.specifiers.InvalidSpecifier: Invalid specifier: 'lolwat' + """ + + +class BaseSpecifier(metaclass=abc.ABCMeta): + __slots__ = () + __match_args__ = ("_str",) + + @property + def _str(self) -> str: + """Internal property for match_args""" + return str(self) + + @abc.abstractmethod + def __str__(self) -> str: + """ + Returns the str representation of this Specifier-like object. This + should be representative of the Specifier itself. + """ + + @abc.abstractmethod + def __hash__(self) -> int: + """ + Returns a hash value for this Specifier-like object. + """ + + @abc.abstractmethod + def __eq__(self, other: object) -> bool: + """ + Returns a boolean representing whether or not the two Specifier-like + objects are equal. + + :param other: The other object to check against. + """ + + @property + @abc.abstractmethod + def prereleases(self) -> bool | None: + """Whether or not pre-releases as a whole are allowed. + + This can be set to either ``True`` or ``False`` to explicitly enable or disable + prereleases or it can be set to ``None`` (the default) to use default semantics. + """ + + @prereleases.setter # noqa: B027 + def prereleases(self, value: bool) -> None: + """Setter for :attr:`prereleases`. + + :param value: The value to set. + """ + + @abc.abstractmethod + def contains(self, item: str, prereleases: bool | None = None) -> bool: + """ + Determines if the given item is contained within this specifier. + """ + + @abc.abstractmethod + def filter( + self, iterable: Iterable[UnparsedVersionVar], prereleases: bool | None = None + ) -> Iterator[UnparsedVersionVar]: + """ + Takes an iterable of items and filters them so that only items which + are contained within this specifier are allowed in it. + """ + + +class Specifier(BaseSpecifier): + """This class abstracts handling of version specifiers. + + .. tip:: + + It is generally not required to instantiate this manually. You should instead + prefer to work with :class:`SpecifierSet` instead, which can parse + comma-separated version specifiers (which is what package metadata contains). + """ + + __slots__ = ("_prereleases", "_spec", "_spec_version") + + _operator_regex_str = r""" + (?P(~=|==|!=|<=|>=|<|>|===)) + """ + _version_regex_str = r""" + (?P + (?: + # The identity operators allow for an escape hatch that will + # do an exact string match of the version you wish to install. + # This will not be parsed by PEP 440 and we cannot determine + # any semantic meaning from it. This operator is discouraged + # but included entirely as an escape hatch. + (?<====) # Only match for the identity operator + \s* + [^\s;)]* # The arbitrary version can be just about anything, + # we match everything except for whitespace, a + # semi-colon for marker support, and a closing paren + # since versions can be enclosed in them. + ) + | + (?: + # The (non)equality operators allow for wild card and local + # versions to be specified so we have to define these two + # operators separately to enable that. + (?<===|!=) # Only match for equals and not equals + + \s* + v? + (?:[0-9]+!)? # epoch + [0-9]+(?:\.[0-9]+)* # release + + # You cannot use a wild card and a pre-release, post-release, a dev or + # local version together so group them with a | and make them optional. + (?: + \.\* # Wild card syntax of .* + | + (?: # pre release + [-_\.]? + (alpha|beta|preview|pre|a|b|c|rc) + [-_\.]? + [0-9]* + )? + (?: # post release + (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*) + )? + (?:[-_\.]?dev[-_\.]?[0-9]*)? # dev release + (?:\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*)? # local + )? + ) + | + (?: + # The compatible operator requires at least two digits in the + # release segment. + (?<=~=) # Only match for the compatible operator + + \s* + v? + (?:[0-9]+!)? # epoch + [0-9]+(?:\.[0-9]+)+ # release (We have a + instead of a *) + (?: # pre release + [-_\.]? + (alpha|beta|preview|pre|a|b|c|rc) + [-_\.]? + [0-9]* + )? + (?: # post release + (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*) + )? + (?:[-_\.]?dev[-_\.]?[0-9]*)? # dev release + ) + | + (?: + # All other operators only allow a sub set of what the + # (non)equality operators do. Specifically they do not allow + # local versions to be specified nor do they allow the prefix + # matching wild cards. + (?=": "greater_than_equal", + "<": "less_than", + ">": "greater_than", + "===": "arbitrary", + } + + def __init__(self, spec: str = "", prereleases: bool | None = None) -> None: + """Initialize a Specifier instance. + + :param spec: + The string representation of a specifier which will be parsed and + normalized before use. + :param prereleases: + This tells the specifier if it should accept prerelease versions if + applicable or not. The default of ``None`` will autodetect it from the + given specifiers. + :raises InvalidSpecifier: + If the given specifier is invalid (i.e. bad syntax). + """ + match = self._regex.fullmatch(spec) + if not match: + raise InvalidSpecifier(f"Invalid specifier: {spec!r}") + + self._spec: tuple[str, str] = ( + match.group("operator").strip(), + match.group("version").strip(), + ) + + # Store whether or not this Specifier should accept prereleases + self._prereleases = prereleases + + # Specifier version cache + self._spec_version: tuple[str, Version] | None = None + + def _get_spec_version(self, version: str) -> Version | None: + """One element cache, as only one spec Version is needed per Specifier.""" + if self._spec_version is not None and self._spec_version[0] == version: + return self._spec_version[1] + + version_specifier = _coerce_version(version) + if version_specifier is None: + return None + + self._spec_version = (version, version_specifier) + return version_specifier + + def _require_spec_version(self, version: str) -> Version: + """Get spec version, asserting it's valid (not for === operator). + + This method should only be called for operators where version + strings are guaranteed to be valid PEP 440 versions (not ===). + """ + spec_version = self._get_spec_version(version) + assert spec_version is not None + return spec_version + + @property + def prereleases(self) -> bool | None: + # If there is an explicit prereleases set for this, then we'll just + # blindly use that. + if self._prereleases is not None: + return self._prereleases + + # Only the "!=" operator does not imply prereleases when + # the version in the specifier is a prerelease. + operator, version_str = self._spec + if operator != "!=": + # The == specifier with trailing .* cannot include prereleases + # e.g. "==1.0a1.*" is not valid. + if operator == "==" and version_str.endswith(".*"): + return False + + # "===" can have arbitrary string versions, so we cannot parse + # those, we take prereleases as unknown (None) for those. + version = self._get_spec_version(version_str) + if version is None: + return None + + # For all other operators, use the check if spec Version + # object implies pre-releases. + if version.is_prerelease: + return True + + return False + + @prereleases.setter + def prereleases(self, value: bool | None) -> None: + self._prereleases = value + + @property + def operator(self) -> str: + """The operator of this specifier. + + >>> Specifier("==1.2.3").operator + '==' + """ + return self._spec[0] + + @property + def version(self) -> str: + """The version of this specifier. + + >>> Specifier("==1.2.3").version + '1.2.3' + """ + return self._spec[1] + + def __repr__(self) -> str: + """A representation of the Specifier that shows all internal state. + + >>> Specifier('>=1.0.0') + =1.0.0')> + >>> Specifier('>=1.0.0', prereleases=False) + =1.0.0', prereleases=False)> + >>> Specifier('>=1.0.0', prereleases=True) + =1.0.0', prereleases=True)> + """ + pre = ( + f", prereleases={self.prereleases!r}" + if self._prereleases is not None + else "" + ) + + return f"<{self.__class__.__name__}({str(self)!r}{pre})>" + + def __str__(self) -> str: + """A string representation of the Specifier that can be round-tripped. + + >>> str(Specifier('>=1.0.0')) + '>=1.0.0' + >>> str(Specifier('>=1.0.0', prereleases=False)) + '>=1.0.0' + """ + return "{}{}".format(*self._spec) + + @property + def _canonical_spec(self) -> tuple[str, str]: + operator, version = self._spec + if operator == "===" or version.endswith(".*"): + return operator, version + + spec_version = self._require_spec_version(version) + + canonical_version = canonicalize_version( + spec_version, strip_trailing_zero=(operator != "~=") + ) + + return operator, canonical_version + + def __hash__(self) -> int: + return hash(self._canonical_spec) + + def __eq__(self, other: object) -> bool: + """Whether or not the two Specifier-like objects are equal. + + :param other: The other object to check against. + + The value of :attr:`prereleases` is ignored. + + >>> Specifier("==1.2.3") == Specifier("== 1.2.3.0") + True + >>> (Specifier("==1.2.3", prereleases=False) == + ... Specifier("==1.2.3", prereleases=True)) + True + >>> Specifier("==1.2.3") == "==1.2.3" + True + >>> Specifier("==1.2.3") == Specifier("==1.2.4") + False + >>> Specifier("==1.2.3") == Specifier("~=1.2.3") + False + """ + if isinstance(other, str): + try: + other = self.__class__(str(other)) + except InvalidSpecifier: + return NotImplemented + elif not isinstance(other, self.__class__): + return NotImplemented + + return self._canonical_spec == other._canonical_spec + + def _get_operator(self, op: str) -> CallableOperator: + operator_callable: CallableOperator = getattr( + self, f"_compare_{self._operators[op]}" + ) + return operator_callable + + def _compare_compatible(self, prospective: Version, spec: str) -> bool: + # Compatible releases have an equivalent combination of >= and ==. That + # is that ~=2.2 is equivalent to >=2.2,==2.*. This allows us to + # implement this in terms of the other specifiers instead of + # implementing it ourselves. The only thing we need to do is construct + # the other specifiers. + + # We want everything but the last item in the version, but we want to + # ignore suffix segments. + prefix = _version_join( + list(itertools.takewhile(_is_not_suffix, _version_split(spec)))[:-1] + ) + + # Add the prefix notation to the end of our string + prefix += ".*" + + return self._get_operator(">=")(prospective, spec) and self._get_operator("==")( + prospective, prefix + ) + + def _compare_equal(self, prospective: Version, spec: str) -> bool: + # We need special logic to handle prefix matching + if spec.endswith(".*"): + # In the case of prefix matching we want to ignore local segment. + normalized_prospective = canonicalize_version( + _public_version(prospective), strip_trailing_zero=False + ) + # Get the normalized version string ignoring the trailing .* + normalized_spec = canonicalize_version(spec[:-2], strip_trailing_zero=False) + # Split the spec out by bangs and dots, and pretend that there is + # an implicit dot in between a release segment and a pre-release segment. + split_spec = _version_split(normalized_spec) + + # Split the prospective version out by bangs and dots, and pretend + # that there is an implicit dot in between a release segment and + # a pre-release segment. + split_prospective = _version_split(normalized_prospective) + + # 0-pad the prospective version before shortening it to get the correct + # shortened version. + padded_prospective, _ = _pad_version(split_prospective, split_spec) + + # Shorten the prospective version to be the same length as the spec + # so that we can determine if the specifier is a prefix of the + # prospective version or not. + shortened_prospective = padded_prospective[: len(split_spec)] + + return shortened_prospective == split_spec + else: + # Convert our spec string into a Version + spec_version = self._require_spec_version(spec) + + # If the specifier does not have a local segment, then we want to + # act as if the prospective version also does not have a local + # segment. + if not spec_version.local: + prospective = _public_version(prospective) + + return prospective == spec_version + + def _compare_not_equal(self, prospective: Version, spec: str) -> bool: + return not self._compare_equal(prospective, spec) + + def _compare_less_than_equal(self, prospective: Version, spec: str) -> bool: + # NB: Local version identifiers are NOT permitted in the version + # specifier, so local version labels can be universally removed from + # the prospective version. + return _public_version(prospective) <= self._require_spec_version(spec) + + def _compare_greater_than_equal(self, prospective: Version, spec: str) -> bool: + # NB: Local version identifiers are NOT permitted in the version + # specifier, so local version labels can be universally removed from + # the prospective version. + return _public_version(prospective) >= self._require_spec_version(spec) + + def _compare_less_than(self, prospective: Version, spec_str: str) -> bool: + # Convert our spec to a Version instance, since we'll want to work with + # it as a version. + spec = self._require_spec_version(spec_str) + + # Check to see if the prospective version is less than the spec + # version. If it's not we can short circuit and just return False now + # instead of doing extra unneeded work. + if not prospective < spec: + return False + + # This special case is here so that, unless the specifier itself + # includes is a pre-release version, that we do not accept pre-release + # versions for the version mentioned in the specifier (e.g. <3.1 should + # not match 3.1.dev0, but should match 3.0.dev0). + if ( + not spec.is_prerelease + and prospective.is_prerelease + and _base_version(prospective) == _base_version(spec) + ): + return False + + # If we've gotten to here, it means that prospective version is both + # less than the spec version *and* it's not a pre-release of the same + # version in the spec. + return True + + def _compare_greater_than(self, prospective: Version, spec_str: str) -> bool: + # Convert our spec to a Version instance, since we'll want to work with + # it as a version. + spec = self._require_spec_version(spec_str) + + # Check to see if the prospective version is greater than the spec + # version. If it's not we can short circuit and just return False now + # instead of doing extra unneeded work. + if not prospective > spec: + return False + + # This special case is here so that, unless the specifier itself + # includes is a post-release version, that we do not accept + # post-release versions for the version mentioned in the specifier + # (e.g. >3.1 should not match 3.0.post0, but should match 3.2.post0). + if ( + not spec.is_postrelease + and prospective.is_postrelease + and _base_version(prospective) == _base_version(spec) + ): + return False + + # Ensure that we do not allow a local version of the version mentioned + # in the specifier, which is technically greater than, to match. + if prospective.local is not None and _base_version( + prospective + ) == _base_version(spec): + return False + + # If we've gotten to here, it means that prospective version is both + # greater than the spec version *and* it's not a pre-release of the + # same version in the spec. + return True + + def _compare_arbitrary(self, prospective: Version | str, spec: str) -> bool: + return str(prospective).lower() == str(spec).lower() + + def __contains__(self, item: str | Version) -> bool: + """Return whether or not the item is contained in this specifier. + + :param item: The item to check for. + + This is used for the ``in`` operator and behaves the same as + :meth:`contains` with no ``prereleases`` argument passed. + + >>> "1.2.3" in Specifier(">=1.2.3") + True + >>> Version("1.2.3") in Specifier(">=1.2.3") + True + >>> "1.0.0" in Specifier(">=1.2.3") + False + >>> "1.3.0a1" in Specifier(">=1.2.3") + True + >>> "1.3.0a1" in Specifier(">=1.2.3", prereleases=True) + True + """ + return self.contains(item) + + def contains(self, item: UnparsedVersion, prereleases: bool | None = None) -> bool: + """Return whether or not the item is contained in this specifier. + + :param item: + The item to check for, which can be a version string or a + :class:`Version` instance. + :param prereleases: + Whether or not to match prereleases with this Specifier. If set to + ``None`` (the default), it will follow the recommendation from + :pep:`440` and match prereleases, as there are no other versions. + + >>> Specifier(">=1.2.3").contains("1.2.3") + True + >>> Specifier(">=1.2.3").contains(Version("1.2.3")) + True + >>> Specifier(">=1.2.3").contains("1.0.0") + False + >>> Specifier(">=1.2.3").contains("1.3.0a1") + True + >>> Specifier(">=1.2.3", prereleases=False).contains("1.3.0a1") + False + >>> Specifier(">=1.2.3").contains("1.3.0a1") + True + """ + + return bool(list(self.filter([item], prereleases=prereleases))) + + def filter( + self, iterable: Iterable[UnparsedVersionVar], prereleases: bool | None = None + ) -> Iterator[UnparsedVersionVar]: + """Filter items in the given iterable, that match the specifier. + + :param iterable: + An iterable that can contain version strings and :class:`Version` instances. + The items in the iterable will be filtered according to the specifier. + :param prereleases: + Whether or not to allow prereleases in the returned iterator. If set to + ``None`` (the default), it will follow the recommendation from :pep:`440` + and match prereleases if there are no other versions. + + >>> list(Specifier(">=1.2.3").filter(["1.2", "1.3", "1.5a1"])) + ['1.3'] + >>> list(Specifier(">=1.2.3").filter(["1.2", "1.2.3", "1.3", Version("1.4")])) + ['1.2.3', '1.3', ] + >>> list(Specifier(">=1.2.3").filter(["1.2", "1.5a1"])) + ['1.5a1'] + >>> list(Specifier(">=1.2.3").filter(["1.3", "1.5a1"], prereleases=True)) + ['1.3', '1.5a1'] + >>> list(Specifier(">=1.2.3", prereleases=True).filter(["1.3", "1.5a1"])) + ['1.3', '1.5a1'] + """ + prereleases_versions = [] + found_non_prereleases = False + + # Determine if to include prereleases by default + include_prereleases = ( + prereleases if prereleases is not None else self.prereleases + ) + + # Get the matching operator + operator_callable = self._get_operator(self.operator) + + # Filter versions + for version in iterable: + parsed_version = _coerce_version(version) + if parsed_version is None: + # === operator can match arbitrary (non-version) strings + if self.operator == "===" and self._compare_arbitrary( + version, self.version + ): + yield version + elif operator_callable(parsed_version, self.version): + # If it's not a prerelease or prereleases are allowed, yield it directly + if not parsed_version.is_prerelease or include_prereleases: + found_non_prereleases = True + yield version + # Otherwise collect prereleases for potential later use + elif prereleases is None and self._prereleases is not False: + prereleases_versions.append(version) + + # If no non-prereleases were found and prereleases weren't + # explicitly forbidden, yield the collected prereleases + if ( + not found_non_prereleases + and prereleases is None + and self._prereleases is not False + ): + yield from prereleases_versions + + +_prefix_regex = re.compile(r"([0-9]+)((?:a|b|c|rc)[0-9]+)") + + +def _version_split(version: str) -> list[str]: + """Split version into components. + + The split components are intended for version comparison. The logic does + not attempt to retain the original version string, so joining the + components back with :func:`_version_join` may not produce the original + version string. + """ + result: list[str] = [] + + epoch, _, rest = version.rpartition("!") + result.append(epoch or "0") + + for item in rest.split("."): + match = _prefix_regex.fullmatch(item) + if match: + result.extend(match.groups()) + else: + result.append(item) + return result + + +def _version_join(components: list[str]) -> str: + """Join split version components into a version string. + + This function assumes the input came from :func:`_version_split`, where the + first component must be the epoch (either empty or numeric), and all other + components numeric. + """ + epoch, *rest = components + return f"{epoch}!{'.'.join(rest)}" + + +def _is_not_suffix(segment: str) -> bool: + return not any( + segment.startswith(prefix) for prefix in ("dev", "a", "b", "rc", "post") + ) + + +def _pad_version(left: list[str], right: list[str]) -> tuple[list[str], list[str]]: + left_split, right_split = [], [] + + # Get the release segment of our versions + left_split.append(list(itertools.takewhile(lambda x: x.isdigit(), left))) + right_split.append(list(itertools.takewhile(lambda x: x.isdigit(), right))) + + # Get the rest of our versions + left_split.append(left[len(left_split[0]) :]) + right_split.append(right[len(right_split[0]) :]) + + # Insert our padding + left_split.insert(1, ["0"] * max(0, len(right_split[0]) - len(left_split[0]))) + right_split.insert(1, ["0"] * max(0, len(left_split[0]) - len(right_split[0]))) + + return ( + list(itertools.chain.from_iterable(left_split)), + list(itertools.chain.from_iterable(right_split)), + ) + + +class SpecifierSet(BaseSpecifier): + """This class abstracts handling of a set of version specifiers. + + It can be passed a single specifier (``>=3.0``), a comma-separated list of + specifiers (``>=3.0,!=3.1``), or no specifier at all. + """ + + __slots__ = ("_prereleases", "_specs") + + def __init__( + self, + specifiers: str | Iterable[Specifier] = "", + prereleases: bool | None = None, + ) -> None: + """Initialize a SpecifierSet instance. + + :param specifiers: + The string representation of a specifier or a comma-separated list of + specifiers which will be parsed and normalized before use. + May also be an iterable of ``Specifier`` instances, which will be used + as is. + :param prereleases: + This tells the SpecifierSet if it should accept prerelease versions if + applicable or not. The default of ``None`` will autodetect it from the + given specifiers. + + :raises InvalidSpecifier: + If the given ``specifiers`` are not parseable than this exception will be + raised. + """ + + if isinstance(specifiers, str): + # Split on `,` to break each individual specifier into its own item, and + # strip each item to remove leading/trailing whitespace. + split_specifiers = [s.strip() for s in specifiers.split(",") if s.strip()] + + # Make each individual specifier a Specifier and save in a frozen set + # for later. + self._specs = frozenset(map(Specifier, split_specifiers)) + else: + # Save the supplied specifiers in a frozen set. + self._specs = frozenset(specifiers) + + # Store our prereleases value so we can use it later to determine if + # we accept prereleases or not. + self._prereleases = prereleases + + @property + def prereleases(self) -> bool | None: + # If we have been given an explicit prerelease modifier, then we'll + # pass that through here. + if self._prereleases is not None: + return self._prereleases + + # If we don't have any specifiers, and we don't have a forced value, + # then we'll just return None since we don't know if this should have + # pre-releases or not. + if not self._specs: + return None + + # Otherwise we'll see if any of the given specifiers accept + # prereleases, if any of them do we'll return True, otherwise False. + if any(s.prereleases for s in self._specs): + return True + + return None + + @prereleases.setter + def prereleases(self, value: bool | None) -> None: + self._prereleases = value + + def __repr__(self) -> str: + """A representation of the specifier set that shows all internal state. + + Note that the ordering of the individual specifiers within the set may not + match the input string. + + >>> SpecifierSet('>=1.0.0,!=2.0.0') + =1.0.0')> + >>> SpecifierSet('>=1.0.0,!=2.0.0', prereleases=False) + =1.0.0', prereleases=False)> + >>> SpecifierSet('>=1.0.0,!=2.0.0', prereleases=True) + =1.0.0', prereleases=True)> + """ + pre = ( + f", prereleases={self.prereleases!r}" + if self._prereleases is not None + else "" + ) + + return f"" + + def __str__(self) -> str: + """A string representation of the specifier set that can be round-tripped. + + Note that the ordering of the individual specifiers within the set may not + match the input string. + + >>> str(SpecifierSet(">=1.0.0,!=1.0.1")) + '!=1.0.1,>=1.0.0' + >>> str(SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False)) + '!=1.0.1,>=1.0.0' + """ + return ",".join(sorted(str(s) for s in self._specs)) + + def __hash__(self) -> int: + return hash(self._specs) + + def __and__(self, other: SpecifierSet | str) -> SpecifierSet: + """Return a SpecifierSet which is a combination of the two sets. + + :param other: The other object to combine with. + + >>> SpecifierSet(">=1.0.0,!=1.0.1") & '<=2.0.0,!=2.0.1' + =1.0.0')> + >>> SpecifierSet(">=1.0.0,!=1.0.1") & SpecifierSet('<=2.0.0,!=2.0.1') + =1.0.0')> + """ + if isinstance(other, str): + other = SpecifierSet(other) + elif not isinstance(other, SpecifierSet): + return NotImplemented + + specifier = SpecifierSet() + specifier._specs = frozenset(self._specs | other._specs) + + if self._prereleases is None and other._prereleases is not None: + specifier._prereleases = other._prereleases + elif ( + self._prereleases is not None and other._prereleases is None + ) or self._prereleases == other._prereleases: + specifier._prereleases = self._prereleases + else: + raise ValueError( + "Cannot combine SpecifierSets with True and False prerelease overrides." + ) + + return specifier + + def __eq__(self, other: object) -> bool: + """Whether or not the two SpecifierSet-like objects are equal. + + :param other: The other object to check against. + + The value of :attr:`prereleases` is ignored. + + >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0,!=1.0.1") + True + >>> (SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False) == + ... SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True)) + True + >>> SpecifierSet(">=1.0.0,!=1.0.1") == ">=1.0.0,!=1.0.1" + True + >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0") + False + >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0,!=1.0.2") + False + """ + if isinstance(other, (str, Specifier)): + other = SpecifierSet(str(other)) + elif not isinstance(other, SpecifierSet): + return NotImplemented + + return self._specs == other._specs + + def __len__(self) -> int: + """Returns the number of specifiers in this specifier set.""" + return len(self._specs) + + def __iter__(self) -> Iterator[Specifier]: + """ + Returns an iterator over all the underlying :class:`Specifier` instances + in this specifier set. + + >>> sorted(SpecifierSet(">=1.0.0,!=1.0.1"), key=str) + [, =1.0.0')>] + """ + return iter(self._specs) + + def __contains__(self, item: UnparsedVersion) -> bool: + """Return whether or not the item is contained in this specifier. + + :param item: The item to check for. + + This is used for the ``in`` operator and behaves the same as + :meth:`contains` with no ``prereleases`` argument passed. + + >>> "1.2.3" in SpecifierSet(">=1.0.0,!=1.0.1") + True + >>> Version("1.2.3") in SpecifierSet(">=1.0.0,!=1.0.1") + True + >>> "1.0.1" in SpecifierSet(">=1.0.0,!=1.0.1") + False + >>> "1.3.0a1" in SpecifierSet(">=1.0.0,!=1.0.1") + True + >>> "1.3.0a1" in SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True) + True + """ + return self.contains(item) + + def contains( + self, + item: UnparsedVersion, + prereleases: bool | None = None, + installed: bool | None = None, + ) -> bool: + """Return whether or not the item is contained in this SpecifierSet. + + :param item: + The item to check for, which can be a version string or a + :class:`Version` instance. + :param prereleases: + Whether or not to match prereleases with this SpecifierSet. If set to + ``None`` (the default), it will follow the recommendation from :pep:`440` + and match prereleases, as there are no other versions. + :param installed: + Whether or not the item is installed. If set to ``True``, it will + accept prerelease versions even if the specifier does not allow them. + + >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.2.3") + True + >>> SpecifierSet(">=1.0.0,!=1.0.1").contains(Version("1.2.3")) + True + >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.0.1") + False + >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.3.0a1") + True + >>> SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False).contains("1.3.0a1") + False + >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.3.0a1", prereleases=True) + True + """ + version = _coerce_version(item) + + if version is not None and installed and version.is_prerelease: + prereleases = True + + check_item = item if version is None else version + return bool(list(self.filter([check_item], prereleases=prereleases))) + + def filter( + self, iterable: Iterable[UnparsedVersionVar], prereleases: bool | None = None + ) -> Iterator[UnparsedVersionVar]: + """Filter items in the given iterable, that match the specifiers in this set. + + :param iterable: + An iterable that can contain version strings and :class:`Version` instances. + The items in the iterable will be filtered according to the specifier. + :param prereleases: + Whether or not to allow prereleases in the returned iterator. If set to + ``None`` (the default), it will follow the recommendation from :pep:`440` + and match prereleases if there are no other versions. + + >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.3", "1.5a1"])) + ['1.3'] + >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.3", Version("1.4")])) + ['1.3', ] + >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.5a1"])) + ['1.5a1'] + >>> list(SpecifierSet(">=1.2.3").filter(["1.3", "1.5a1"], prereleases=True)) + ['1.3', '1.5a1'] + >>> list(SpecifierSet(">=1.2.3", prereleases=True).filter(["1.3", "1.5a1"])) + ['1.3', '1.5a1'] + + An "empty" SpecifierSet will filter items based on the presence of prerelease + versions in the set. + + >>> list(SpecifierSet("").filter(["1.3", "1.5a1"])) + ['1.3'] + >>> list(SpecifierSet("").filter(["1.5a1"])) + ['1.5a1'] + >>> list(SpecifierSet("", prereleases=True).filter(["1.3", "1.5a1"])) + ['1.3', '1.5a1'] + >>> list(SpecifierSet("").filter(["1.3", "1.5a1"], prereleases=True)) + ['1.3', '1.5a1'] + """ + # Determine if we're forcing a prerelease or not, if we're not forcing + # one for this particular filter call, then we'll use whatever the + # SpecifierSet thinks for whether or not we should support prereleases. + if prereleases is None and self.prereleases is not None: + prereleases = self.prereleases + + # If we have any specifiers, then we want to wrap our iterable in the + # filter method for each one, this will act as a logical AND amongst + # each specifier. + if self._specs: + # When prereleases is None, we need to let all versions through + # the individual filters, then decide about prereleases at the end + # based on whether any non-prereleases matched ALL specs. + for spec in self._specs: + iterable = spec.filter( + iterable, prereleases=True if prereleases is None else prereleases + ) + + if prereleases is not None: + # If we have a forced prereleases value, + # we can immediately return the iterator. + return iter(iterable) + else: + # Handle empty SpecifierSet cases where prereleases is not None. + if prereleases is True: + return iter(iterable) + + if prereleases is False: + return ( + item + for item in iterable + if (version := _coerce_version(item)) is None + or not version.is_prerelease + ) + + # Finally if prereleases is None, apply PEP 440 logic: + # exclude prereleases unless there are no final releases that matched. + filtered_items: list[UnparsedVersionVar] = [] + found_prereleases: list[UnparsedVersionVar] = [] + found_final_release = False + + for item in iterable: + parsed_version = _coerce_version(item) + # Arbitrary strings are always included as it is not + # possible to determine if they are prereleases, + # and they have already passed all specifiers. + if parsed_version is None: + filtered_items.append(item) + found_prereleases.append(item) + elif parsed_version.is_prerelease: + found_prereleases.append(item) + else: + filtered_items.append(item) + found_final_release = True + + return iter(filtered_items if found_final_release else found_prereleases) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/packaging/tags.py b/TTS/Kokoro/.venv/Lib/site-packages/packaging/tags.py new file mode 100644 index 0000000000000000000000000000000000000000..5ef27c897a4df35a2a6923b608a5e04a0a38b9ee --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/packaging/tags.py @@ -0,0 +1,651 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import logging +import platform +import re +import struct +import subprocess +import sys +import sysconfig +from importlib.machinery import EXTENSION_SUFFIXES +from typing import ( + Any, + Iterable, + Iterator, + Sequence, + Tuple, + cast, +) + +from . import _manylinux, _musllinux + +logger = logging.getLogger(__name__) + +PythonVersion = Sequence[int] +AppleVersion = Tuple[int, int] + +INTERPRETER_SHORT_NAMES: dict[str, str] = { + "python": "py", # Generic. + "cpython": "cp", + "pypy": "pp", + "ironpython": "ip", + "jython": "jy", +} + + +_32_BIT_INTERPRETER = struct.calcsize("P") == 4 + + +class Tag: + """ + A representation of the tag triple for a wheel. + + Instances are considered immutable and thus are hashable. Equality checking + is also supported. + """ + + __slots__ = ["_abi", "_hash", "_interpreter", "_platform"] + + def __init__(self, interpreter: str, abi: str, platform: str) -> None: + self._interpreter = interpreter.lower() + self._abi = abi.lower() + self._platform = platform.lower() + # The __hash__ of every single element in a Set[Tag] will be evaluated each time + # that a set calls its `.disjoint()` method, which may be called hundreds of + # times when scanning a page of links for packages with tags matching that + # Set[Tag]. Pre-computing the value here produces significant speedups for + # downstream consumers. + self._hash = hash((self._interpreter, self._abi, self._platform)) + + @property + def interpreter(self) -> str: + return self._interpreter + + @property + def abi(self) -> str: + return self._abi + + @property + def platform(self) -> str: + return self._platform + + def __eq__(self, other: object) -> bool: + if not isinstance(other, Tag): + return NotImplemented + + return ( + (self._hash == other._hash) # Short-circuit ASAP for perf reasons. + and (self._platform == other._platform) + and (self._abi == other._abi) + and (self._interpreter == other._interpreter) + ) + + def __hash__(self) -> int: + return self._hash + + def __str__(self) -> str: + return f"{self._interpreter}-{self._abi}-{self._platform}" + + def __repr__(self) -> str: + return f"<{self} @ {id(self)}>" + + def __setstate__(self, state: tuple[None, dict[str, Any]]) -> None: + # The cached _hash is wrong when unpickling. + _, slots = state + for k, v in slots.items(): + setattr(self, k, v) + self._hash = hash((self._interpreter, self._abi, self._platform)) + + +def parse_tag(tag: str) -> frozenset[Tag]: + """ + Parses the provided tag (e.g. `py3-none-any`) into a frozenset of Tag instances. + + Returning a set is required due to the possibility that the tag is a + compressed tag set. + """ + tags = set() + interpreters, abis, platforms = tag.split("-") + for interpreter in interpreters.split("."): + for abi in abis.split("."): + for platform_ in platforms.split("."): + tags.add(Tag(interpreter, abi, platform_)) + return frozenset(tags) + + +def _get_config_var(name: str, warn: bool = False) -> int | str | None: + value: int | str | None = sysconfig.get_config_var(name) + if value is None and warn: + logger.debug( + "Config variable '%s' is unset, Python ABI tag may be incorrect", name + ) + return value + + +def _normalize_string(string: str) -> str: + return string.replace(".", "_").replace("-", "_").replace(" ", "_") + + +def _is_threaded_cpython(abis: list[str]) -> bool: + """ + Determine if the ABI corresponds to a threaded (`--disable-gil`) build. + + The threaded builds are indicated by a "t" in the abiflags. + """ + if len(abis) == 0: + return False + # expect e.g., cp313 + m = re.match(r"cp\d+(.*)", abis[0]) + if not m: + return False + abiflags = m.group(1) + return "t" in abiflags + + +def _abi3_applies(python_version: PythonVersion, threading: bool) -> bool: + """ + Determine if the Python version supports abi3. + + PEP 384 was first implemented in Python 3.2. The threaded (`--disable-gil`) + builds do not support abi3. + """ + return len(python_version) > 1 and tuple(python_version) >= (3, 2) and not threading + + +def _cpython_abis(py_version: PythonVersion, warn: bool = False) -> list[str]: + py_version = tuple(py_version) # To allow for version comparison. + abis = [] + version = _version_nodot(py_version[:2]) + threading = debug = pymalloc = ucs4 = "" + with_debug = _get_config_var("Py_DEBUG", warn) + has_refcount = hasattr(sys, "gettotalrefcount") + # Windows doesn't set Py_DEBUG, so checking for support of debug-compiled + # extension modules is the best option. + # https://github.com/pypa/pip/issues/3383#issuecomment-173267692 + has_ext = "_d.pyd" in EXTENSION_SUFFIXES + if with_debug or (with_debug is None and (has_refcount or has_ext)): + debug = "d" + if py_version >= (3, 13) and _get_config_var("Py_GIL_DISABLED", warn): + threading = "t" + if py_version < (3, 8): + with_pymalloc = _get_config_var("WITH_PYMALLOC", warn) + if with_pymalloc or with_pymalloc is None: + pymalloc = "m" + if py_version < (3, 3): + unicode_size = _get_config_var("Py_UNICODE_SIZE", warn) + if unicode_size == 4 or ( + unicode_size is None and sys.maxunicode == 0x10FFFF + ): + ucs4 = "u" + elif debug: + # Debug builds can also load "normal" extension modules. + # We can also assume no UCS-4 or pymalloc requirement. + abis.append(f"cp{version}{threading}") + abis.insert(0, f"cp{version}{threading}{debug}{pymalloc}{ucs4}") + return abis + + +def cpython_tags( + python_version: PythonVersion | None = None, + abis: Iterable[str] | None = None, + platforms: Iterable[str] | None = None, + *, + warn: bool = False, +) -> Iterator[Tag]: + """ + Yields the tags for a CPython interpreter. + + The tags consist of: + - cp-- + - cp-abi3- + - cp-none- + - cp-abi3- # Older Python versions down to 3.2. + + If python_version only specifies a major version then user-provided ABIs and + the 'none' ABItag will be used. + + If 'abi3' or 'none' are specified in 'abis' then they will be yielded at + their normal position and not at the beginning. + """ + if not python_version: + python_version = sys.version_info[:2] + + interpreter = f"cp{_version_nodot(python_version[:2])}" + + if abis is None: + abis = _cpython_abis(python_version, warn) if len(python_version) > 1 else [] + abis = list(abis) + # 'abi3' and 'none' are explicitly handled later. + for explicit_abi in ("abi3", "none"): + try: + abis.remove(explicit_abi) + except ValueError: # noqa: PERF203 + pass + + platforms = list(platforms or platform_tags()) + for abi in abis: + for platform_ in platforms: + yield Tag(interpreter, abi, platform_) + + threading = _is_threaded_cpython(abis) + use_abi3 = _abi3_applies(python_version, threading) + if use_abi3: + yield from (Tag(interpreter, "abi3", platform_) for platform_ in platforms) + yield from (Tag(interpreter, "none", platform_) for platform_ in platforms) + + if use_abi3: + for minor_version in range(python_version[1] - 1, 1, -1): + for platform_ in platforms: + version = _version_nodot((python_version[0], minor_version)) + interpreter = f"cp{version}" + yield Tag(interpreter, "abi3", platform_) + + +def _generic_abi() -> list[str]: + """ + Return the ABI tag based on EXT_SUFFIX. + """ + # The following are examples of `EXT_SUFFIX`. + # We want to keep the parts which are related to the ABI and remove the + # parts which are related to the platform: + # - linux: '.cpython-310-x86_64-linux-gnu.so' => cp310 + # - mac: '.cpython-310-darwin.so' => cp310 + # - win: '.cp310-win_amd64.pyd' => cp310 + # - win: '.pyd' => cp37 (uses _cpython_abis()) + # - pypy: '.pypy38-pp73-x86_64-linux-gnu.so' => pypy38_pp73 + # - graalpy: '.graalpy-38-native-x86_64-darwin.dylib' + # => graalpy_38_native + + ext_suffix = _get_config_var("EXT_SUFFIX", warn=True) + if not isinstance(ext_suffix, str) or ext_suffix[0] != ".": + raise SystemError("invalid sysconfig.get_config_var('EXT_SUFFIX')") + parts = ext_suffix.split(".") + if len(parts) < 3: + # CPython3.7 and earlier uses ".pyd" on Windows. + return _cpython_abis(sys.version_info[:2]) + soabi = parts[1] + if soabi.startswith("cpython"): + # non-windows + abi = "cp" + soabi.split("-")[1] + elif soabi.startswith("cp"): + # windows + abi = soabi.split("-")[0] + elif soabi.startswith("pypy"): + abi = "-".join(soabi.split("-")[:2]) + elif soabi.startswith("graalpy"): + abi = "-".join(soabi.split("-")[:3]) + elif soabi: + # pyston, ironpython, others? + abi = soabi + else: + return [] + return [_normalize_string(abi)] + + +def generic_tags( + interpreter: str | None = None, + abis: Iterable[str] | None = None, + platforms: Iterable[str] | None = None, + *, + warn: bool = False, +) -> Iterator[Tag]: + """ + Yields the tags for a generic interpreter. + + The tags consist of: + - -- + + The "none" ABI will be added if it was not explicitly provided. + """ + if not interpreter: + interp_name = interpreter_name() + interp_version = interpreter_version(warn=warn) + interpreter = f"{interp_name}{interp_version}" + abis = _generic_abi() if abis is None else list(abis) + platforms = list(platforms or platform_tags()) + if "none" not in abis: + abis.append("none") + for abi in abis: + for platform_ in platforms: + yield Tag(interpreter, abi, platform_) + + +def _py_interpreter_range(py_version: PythonVersion) -> Iterator[str]: + """ + Yields Python versions in descending order. + + After the latest version, the major-only version will be yielded, and then + all previous versions of that major version. + """ + if len(py_version) > 1: + yield f"py{_version_nodot(py_version[:2])}" + yield f"py{py_version[0]}" + if len(py_version) > 1: + for minor in range(py_version[1] - 1, -1, -1): + yield f"py{_version_nodot((py_version[0], minor))}" + + +def compatible_tags( + python_version: PythonVersion | None = None, + interpreter: str | None = None, + platforms: Iterable[str] | None = None, +) -> Iterator[Tag]: + """ + Yields the sequence of tags that are compatible with a specific version of Python. + + The tags consist of: + - py*-none- + - -none-any # ... if `interpreter` is provided. + - py*-none-any + """ + if not python_version: + python_version = sys.version_info[:2] + platforms = list(platforms or platform_tags()) + for version in _py_interpreter_range(python_version): + for platform_ in platforms: + yield Tag(version, "none", platform_) + if interpreter: + yield Tag(interpreter, "none", "any") + for version in _py_interpreter_range(python_version): + yield Tag(version, "none", "any") + + +def _mac_arch(arch: str, is_32bit: bool = _32_BIT_INTERPRETER) -> str: + if not is_32bit: + return arch + + if arch.startswith("ppc"): + return "ppc" + + return "i386" + + +def _mac_binary_formats(version: AppleVersion, cpu_arch: str) -> list[str]: + formats = [cpu_arch] + if cpu_arch == "x86_64": + if version < (10, 4): + return [] + formats.extend(["intel", "fat64", "fat32"]) + + elif cpu_arch == "i386": + if version < (10, 4): + return [] + formats.extend(["intel", "fat32", "fat"]) + + elif cpu_arch == "ppc64": + # TODO: Need to care about 32-bit PPC for ppc64 through 10.2? + if version > (10, 5) or version < (10, 4): + return [] + formats.append("fat64") + + elif cpu_arch == "ppc": + if version > (10, 6): + return [] + formats.extend(["fat32", "fat"]) + + if cpu_arch in {"arm64", "x86_64"}: + formats.append("universal2") + + if cpu_arch in {"x86_64", "i386", "ppc64", "ppc", "intel"}: + formats.append("universal") + + return formats + + +def mac_platforms( + version: AppleVersion | None = None, arch: str | None = None +) -> Iterator[str]: + """ + Yields the platform tags for a macOS system. + + The `version` parameter is a two-item tuple specifying the macOS version to + generate platform tags for. The `arch` parameter is the CPU architecture to + generate platform tags for. Both parameters default to the appropriate value + for the current system. + """ + version_str, _, cpu_arch = platform.mac_ver() + if version is None: + version = cast("AppleVersion", tuple(map(int, version_str.split(".")[:2]))) + if version == (10, 16): + # When built against an older macOS SDK, Python will report macOS 10.16 + # instead of the real version. + version_str = subprocess.run( + [ + sys.executable, + "-sS", + "-c", + "import platform; print(platform.mac_ver()[0])", + ], + check=True, + env={"SYSTEM_VERSION_COMPAT": "0"}, + stdout=subprocess.PIPE, + text=True, + ).stdout + version = cast("AppleVersion", tuple(map(int, version_str.split(".")[:2]))) + + if arch is None: + arch = _mac_arch(cpu_arch) + + if (10, 0) <= version < (11, 0): + # Prior to Mac OS 11, each yearly release of Mac OS bumped the + # "minor" version number. The major version was always 10. + major_version = 10 + for minor_version in range(version[1], -1, -1): + compat_version = major_version, minor_version + binary_formats = _mac_binary_formats(compat_version, arch) + for binary_format in binary_formats: + yield f"macosx_{major_version}_{minor_version}_{binary_format}" + + if version >= (11, 0): + # Starting with Mac OS 11, each yearly release bumps the major version + # number. The minor versions are now the midyear updates. + minor_version = 0 + for major_version in range(version[0], 10, -1): + compat_version = major_version, minor_version + binary_formats = _mac_binary_formats(compat_version, arch) + for binary_format in binary_formats: + yield f"macosx_{major_version}_{minor_version}_{binary_format}" + + if version >= (11, 0): + # Mac OS 11 on x86_64 is compatible with binaries from previous releases. + # Arm64 support was introduced in 11.0, so no Arm binaries from previous + # releases exist. + # + # However, the "universal2" binary format can have a + # macOS version earlier than 11.0 when the x86_64 part of the binary supports + # that version of macOS. + major_version = 10 + if arch == "x86_64": + for minor_version in range(16, 3, -1): + compat_version = major_version, minor_version + binary_formats = _mac_binary_formats(compat_version, arch) + for binary_format in binary_formats: + yield f"macosx_{major_version}_{minor_version}_{binary_format}" + else: + for minor_version in range(16, 3, -1): + compat_version = major_version, minor_version + binary_format = "universal2" + yield f"macosx_{major_version}_{minor_version}_{binary_format}" + + +def ios_platforms( + version: AppleVersion | None = None, multiarch: str | None = None +) -> Iterator[str]: + """ + Yields the platform tags for an iOS system. + + :param version: A two-item tuple specifying the iOS version to generate + platform tags for. Defaults to the current iOS version. + :param multiarch: The CPU architecture+ABI to generate platform tags for - + (the value used by `sys.implementation._multiarch` e.g., + `arm64_iphoneos` or `x84_64_iphonesimulator`). Defaults to the current + multiarch value. + """ + if version is None: + # if iOS is the current platform, ios_ver *must* be defined. However, + # it won't exist for CPython versions before 3.13, which causes a mypy + # error. + _, release, _, _ = platform.ios_ver() # type: ignore[attr-defined, unused-ignore] + version = cast("AppleVersion", tuple(map(int, release.split(".")[:2]))) + + if multiarch is None: + multiarch = sys.implementation._multiarch + multiarch = multiarch.replace("-", "_") + + ios_platform_template = "ios_{major}_{minor}_{multiarch}" + + # Consider any iOS major.minor version from the version requested, down to + # 12.0. 12.0 is the first iOS version that is known to have enough features + # to support CPython. Consider every possible minor release up to X.9. There + # highest the minor has ever gone is 8 (14.8 and 15.8) but having some extra + # candidates that won't ever match doesn't really hurt, and it saves us from + # having to keep an explicit list of known iOS versions in the code. Return + # the results descending order of version number. + + # If the requested major version is less than 12, there won't be any matches. + if version[0] < 12: + return + + # Consider the actual X.Y version that was requested. + yield ios_platform_template.format( + major=version[0], minor=version[1], multiarch=multiarch + ) + + # Consider every minor version from X.0 to the minor version prior to the + # version requested by the platform. + for minor in range(version[1] - 1, -1, -1): + yield ios_platform_template.format( + major=version[0], minor=minor, multiarch=multiarch + ) + + for major in range(version[0] - 1, 11, -1): + for minor in range(9, -1, -1): + yield ios_platform_template.format( + major=major, minor=minor, multiarch=multiarch + ) + + +def android_platforms( + api_level: int | None = None, abi: str | None = None +) -> Iterator[str]: + """ + Yields the :attr:`~Tag.platform` tags for Android. If this function is invoked on + non-Android platforms, the ``api_level`` and ``abi`` arguments are required. + + :param int api_level: The maximum `API level + `__ to return. Defaults + to the current system's version, as returned by ``platform.android_ver``. + :param str abi: The `Android ABI `__, + e.g. ``arm64_v8a``. Defaults to the current system's ABI , as returned by + ``sysconfig.get_platform``. Hyphens and periods will be replaced with + underscores. + """ + if platform.system() != "Android" and (api_level is None or abi is None): + raise TypeError( + "on non-Android platforms, the api_level and abi arguments are required" + ) + + if api_level is None: + # Python 3.13 was the first version to return platform.system() == "Android", + # and also the first version to define platform.android_ver(). + api_level = platform.android_ver().api_level # type: ignore[attr-defined] + + if abi is None: + abi = sysconfig.get_platform().split("-")[-1] + abi = _normalize_string(abi) + + # 16 is the minimum API level known to have enough features to support CPython + # without major patching. Yield every API level from the maximum down to the + # minimum, inclusive. + min_api_level = 16 + for ver in range(api_level, min_api_level - 1, -1): + yield f"android_{ver}_{abi}" + + +def _linux_platforms(is_32bit: bool = _32_BIT_INTERPRETER) -> Iterator[str]: + linux = _normalize_string(sysconfig.get_platform()) + if not linux.startswith("linux_"): + # we should never be here, just yield the sysconfig one and return + yield linux + return + if is_32bit: + if linux == "linux_x86_64": + linux = "linux_i686" + elif linux == "linux_aarch64": + linux = "linux_armv8l" + _, arch = linux.split("_", 1) + archs = {"armv8l": ["armv8l", "armv7l"]}.get(arch, [arch]) + yield from _manylinux.platform_tags(archs) + yield from _musllinux.platform_tags(archs) + for arch in archs: + yield f"linux_{arch}" + + +def _generic_platforms() -> Iterator[str]: + yield _normalize_string(sysconfig.get_platform()) + + +def platform_tags() -> Iterator[str]: + """ + Provides the platform tags for this installation. + """ + if platform.system() == "Darwin": + return mac_platforms() + elif platform.system() == "iOS": + return ios_platforms() + elif platform.system() == "Android": + return android_platforms() + elif platform.system() == "Linux": + return _linux_platforms() + else: + return _generic_platforms() + + +def interpreter_name() -> str: + """ + Returns the name of the running interpreter. + + Some implementations have a reserved, two-letter abbreviation which will + be returned when appropriate. + """ + name = sys.implementation.name + return INTERPRETER_SHORT_NAMES.get(name) or name + + +def interpreter_version(*, warn: bool = False) -> str: + """ + Returns the version of the running interpreter. + """ + version = _get_config_var("py_version_nodot", warn=warn) + return str(version) if version else _version_nodot(sys.version_info[:2]) + + +def _version_nodot(version: PythonVersion) -> str: + return "".join(map(str, version)) + + +def sys_tags(*, warn: bool = False) -> Iterator[Tag]: + """ + Returns the sequence of tag triples for the running interpreter. + + The order of the sequence corresponds to priority order for the + interpreter, from most to least important. + """ + + interp_name = interpreter_name() + if interp_name == "cp": + yield from cpython_tags(warn=warn) + else: + yield from generic_tags() + + if interp_name == "pp": + interp = "pp3" + elif interp_name == "cp": + interp = "cp" + interpreter_version(warn=warn) + else: + interp = None + yield from compatible_tags(interpreter=interp) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/packaging/utils.py b/TTS/Kokoro/.venv/Lib/site-packages/packaging/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c41c8137f2679a0fac21bb845596e231ae88dbd8 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/packaging/utils.py @@ -0,0 +1,158 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import re +from typing import NewType, Tuple, Union, cast + +from .tags import Tag, parse_tag +from .version import InvalidVersion, Version, _TrimmedRelease + +BuildTag = Union[Tuple[()], Tuple[int, str]] +NormalizedName = NewType("NormalizedName", str) + + +class InvalidName(ValueError): + """ + An invalid distribution name; users should refer to the packaging user guide. + """ + + +class InvalidWheelFilename(ValueError): + """ + An invalid wheel filename was found, users should refer to PEP 427. + """ + + +class InvalidSdistFilename(ValueError): + """ + An invalid sdist filename was found, users should refer to the packaging user guide. + """ + + +# Core metadata spec for `Name` +_validate_regex = re.compile(r"[A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9]", re.IGNORECASE) +_normalized_regex = re.compile(r"[a-z0-9]|[a-z0-9]([a-z0-9-](?!--))*[a-z0-9]") +# PEP 427: The build number must start with a digit. +_build_tag_regex = re.compile(r"(\d+)(.*)") + + +def canonicalize_name(name: str, *, validate: bool = False) -> NormalizedName: + if validate and not _validate_regex.fullmatch(name): + raise InvalidName(f"name is invalid: {name!r}") + # Ensure all ``.`` and ``_`` are ``-`` + # Emulates ``re.sub(r"[-_.]+", "-", name).lower()`` from PEP 503 + # Much faster than re, and even faster than str.translate + value = name.lower().replace("_", "-").replace(".", "-") + # Condense repeats (faster than regex) + while "--" in value: + value = value.replace("--", "-") + return cast("NormalizedName", value) + + +def is_normalized_name(name: str) -> bool: + return _normalized_regex.fullmatch(name) is not None + + +def canonicalize_version( + version: Version | str, *, strip_trailing_zero: bool = True +) -> str: + """ + Return a canonical form of a version as a string. + + >>> canonicalize_version('1.0.1') + '1.0.1' + + Per PEP 625, versions may have multiple canonical forms, differing + only by trailing zeros. + + >>> canonicalize_version('1.0.0') + '1' + >>> canonicalize_version('1.0.0', strip_trailing_zero=False) + '1.0.0' + + Invalid versions are returned unaltered. + + >>> canonicalize_version('foo bar baz') + 'foo bar baz' + """ + if isinstance(version, str): + try: + version = Version(version) + except InvalidVersion: + return str(version) + return str(_TrimmedRelease(version) if strip_trailing_zero else version) + + +def parse_wheel_filename( + filename: str, +) -> tuple[NormalizedName, Version, BuildTag, frozenset[Tag]]: + if not filename.endswith(".whl"): + raise InvalidWheelFilename( + f"Invalid wheel filename (extension must be '.whl'): {filename!r}" + ) + + filename = filename[:-4] + dashes = filename.count("-") + if dashes not in (4, 5): + raise InvalidWheelFilename( + f"Invalid wheel filename (wrong number of parts): {filename!r}" + ) + + parts = filename.split("-", dashes - 2) + name_part = parts[0] + # See PEP 427 for the rules on escaping the project name. + if "__" in name_part or re.match(r"^[\w\d._]*$", name_part, re.UNICODE) is None: + raise InvalidWheelFilename(f"Invalid project name: {filename!r}") + name = canonicalize_name(name_part) + + try: + version = Version(parts[1]) + except InvalidVersion as e: + raise InvalidWheelFilename( + f"Invalid wheel filename (invalid version): {filename!r}" + ) from e + + if dashes == 5: + build_part = parts[2] + build_match = _build_tag_regex.match(build_part) + if build_match is None: + raise InvalidWheelFilename( + f"Invalid build number: {build_part} in {filename!r}" + ) + build = cast("BuildTag", (int(build_match.group(1)), build_match.group(2))) + else: + build = () + tags = parse_tag(parts[-1]) + return (name, version, build, tags) + + +def parse_sdist_filename(filename: str) -> tuple[NormalizedName, Version]: + if filename.endswith(".tar.gz"): + file_stem = filename[: -len(".tar.gz")] + elif filename.endswith(".zip"): + file_stem = filename[: -len(".zip")] + else: + raise InvalidSdistFilename( + f"Invalid sdist filename (extension must be '.tar.gz' or '.zip'):" + f" {filename!r}" + ) + + # We are requiring a PEP 440 version, which cannot contain dashes, + # so we split on the last dash. + name_part, sep, version_part = file_stem.rpartition("-") + if not sep: + raise InvalidSdistFilename(f"Invalid sdist filename: {filename!r}") + + name = canonicalize_name(name_part) + + try: + version = Version(version_part) + except InvalidVersion as e: + raise InvalidSdistFilename( + f"Invalid sdist filename (invalid version): {filename!r}" + ) from e + + return (name, version) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/packaging/version.py b/TTS/Kokoro/.venv/Lib/site-packages/packaging/version.py new file mode 100644 index 0000000000000000000000000000000000000000..1206c462d4fcaa670a816e201bb88b27dfc9cf88 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/packaging/version.py @@ -0,0 +1,792 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. +""" +.. testsetup:: + + from packaging.version import parse, Version +""" + +from __future__ import annotations + +import re +import sys +import typing +from typing import ( + Any, + Callable, + Literal, + NamedTuple, + SupportsInt, + Tuple, + TypedDict, + Union, +) + +from ._structures import Infinity, InfinityType, NegativeInfinity, NegativeInfinityType + +if typing.TYPE_CHECKING: + from typing_extensions import Self, Unpack + +if sys.version_info >= (3, 13): # pragma: no cover + from warnings import deprecated as _deprecated +elif typing.TYPE_CHECKING: + from typing_extensions import deprecated as _deprecated +else: # pragma: no cover + import functools + import warnings + + def _deprecated(message: str) -> object: + def decorator(func: object) -> object: + @functools.wraps(func) + def wrapper(*args: object, **kwargs: object) -> object: + warnings.warn( + message, + category=DeprecationWarning, + stacklevel=2, + ) + return func(*args, **kwargs) + + return wrapper + + return decorator + + +_LETTER_NORMALIZATION = { + "alpha": "a", + "beta": "b", + "c": "rc", + "pre": "rc", + "preview": "rc", + "rev": "post", + "r": "post", +} + +__all__ = ["VERSION_PATTERN", "InvalidVersion", "Version", "parse"] + +LocalType = Tuple[Union[int, str], ...] + +CmpPrePostDevType = Union[InfinityType, NegativeInfinityType, Tuple[str, int]] +CmpLocalType = Union[ + NegativeInfinityType, + Tuple[Union[Tuple[int, str], Tuple[NegativeInfinityType, Union[int, str]]], ...], +] +CmpKey = Tuple[ + int, + Tuple[int, ...], + CmpPrePostDevType, + CmpPrePostDevType, + CmpPrePostDevType, + CmpLocalType, +] +VersionComparisonMethod = Callable[[CmpKey, CmpKey], bool] + + +class _VersionReplace(TypedDict, total=False): + epoch: int | None + release: tuple[int, ...] | None + pre: tuple[Literal["a", "b", "rc"], int] | None + post: int | None + dev: int | None + local: str | None + + +def parse(version: str) -> Version: + """Parse the given version string. + + >>> parse('1.0.dev1') + + + :param version: The version string to parse. + :raises InvalidVersion: When the version string is not a valid version. + """ + return Version(version) + + +class InvalidVersion(ValueError): + """Raised when a version string is not a valid version. + + >>> Version("invalid") + Traceback (most recent call last): + ... + packaging.version.InvalidVersion: Invalid version: 'invalid' + """ + + +class _BaseVersion: + __slots__ = () + + # This can also be a normal member (see the packaging_legacy package); + # we are just requiring it to be readable. Actually defining a property + # has runtime effect on subclasses, so it's typing only. + if typing.TYPE_CHECKING: + + @property + def _key(self) -> tuple[Any, ...]: ... + + def __hash__(self) -> int: + return hash(self._key) + + # Please keep the duplicated `isinstance` check + # in the six comparisons hereunder + # unless you find a way to avoid adding overhead function calls. + def __lt__(self, other: _BaseVersion) -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key < other._key + + def __le__(self, other: _BaseVersion) -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key <= other._key + + def __eq__(self, other: object) -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key == other._key + + def __ge__(self, other: _BaseVersion) -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key >= other._key + + def __gt__(self, other: _BaseVersion) -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key > other._key + + def __ne__(self, other: object) -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key != other._key + + +# Deliberately not anchored to the start and end of the string, to make it +# easier for 3rd party code to reuse + +# Note that ++ doesn't behave identically on CPython and PyPy, so not using it here +_VERSION_PATTERN = r""" + v?+ # optional leading v + (?: + (?:(?P[0-9]+)!)?+ # epoch + (?P[0-9]+(?:\.[0-9]+)*+) # release segment + (?P
                                          # pre-release
+            [._-]?+
+            (?Palpha|a|beta|b|preview|pre|c|rc)
+            [._-]?+
+            (?P[0-9]+)?
+        )?+
+        (?P                                         # post release
+            (?:-(?P[0-9]+))
+            |
+            (?:
+                [._-]?
+                (?Ppost|rev|r)
+                [._-]?
+                (?P[0-9]+)?
+            )
+        )?+
+        (?P                                          # dev release
+            [._-]?+
+            (?Pdev)
+            [._-]?+
+            (?P[0-9]+)?
+        )?+
+    )
+    (?:\+
+        (?P                                        # local version
+            [a-z0-9]+
+            (?:[._-][a-z0-9]+)*+
+        )
+    )?+
+"""
+
+_VERSION_PATTERN_OLD = _VERSION_PATTERN.replace("*+", "*").replace("?+", "?")
+
+# Possessive qualifiers were added in Python 3.11.
+# CPython 3.11.0-3.11.4 had a bug: https://github.com/python/cpython/pull/107795
+# Older PyPy also had a bug.
+VERSION_PATTERN = (
+    _VERSION_PATTERN_OLD
+    if (sys.implementation.name == "cpython" and sys.version_info < (3, 11, 5))
+    or (sys.implementation.name == "pypy" and sys.version_info < (3, 11, 13))
+    or sys.version_info < (3, 11)
+    else _VERSION_PATTERN
+)
+"""
+A string containing the regular expression used to match a valid version.
+
+The pattern is not anchored at either end, and is intended for embedding in larger
+expressions (for example, matching a version number as part of a file name). The
+regular expression should be compiled with the ``re.VERBOSE`` and ``re.IGNORECASE``
+flags set.
+
+:meta hide-value:
+"""
+
+
+# Validation pattern for local version in replace()
+_LOCAL_PATTERN = re.compile(r"[a-z0-9]+(?:[._-][a-z0-9]+)*", re.IGNORECASE)
+
+
+def _validate_epoch(value: object, /) -> int:
+    epoch = value or 0
+    if isinstance(epoch, int) and epoch >= 0:
+        return epoch
+    msg = f"epoch must be non-negative integer, got {epoch}"
+    raise InvalidVersion(msg)
+
+
+def _validate_release(value: object, /) -> tuple[int, ...]:
+    release = (0,) if value is None else value
+    if (
+        isinstance(release, tuple)
+        and len(release) > 0
+        and all(isinstance(i, int) and i >= 0 for i in release)
+    ):
+        return release
+    msg = f"release must be a non-empty tuple of non-negative integers, got {release}"
+    raise InvalidVersion(msg)
+
+
+def _validate_pre(value: object, /) -> tuple[Literal["a", "b", "rc"], int] | None:
+    if value is None:
+        return value
+    if (
+        isinstance(value, tuple)
+        and len(value) == 2
+        and value[0] in ("a", "b", "rc")
+        and isinstance(value[1], int)
+        and value[1] >= 0
+    ):
+        return value
+    msg = f"pre must be a tuple of ('a'|'b'|'rc', non-negative int), got {value}"
+    raise InvalidVersion(msg)
+
+
+def _validate_post(value: object, /) -> tuple[Literal["post"], int] | None:
+    if value is None:
+        return value
+    if isinstance(value, int) and value >= 0:
+        return ("post", value)
+    msg = f"post must be non-negative integer, got {value}"
+    raise InvalidVersion(msg)
+
+
+def _validate_dev(value: object, /) -> tuple[Literal["dev"], int] | None:
+    if value is None:
+        return value
+    if isinstance(value, int) and value >= 0:
+        return ("dev", value)
+    msg = f"dev must be non-negative integer, got {value}"
+    raise InvalidVersion(msg)
+
+
+def _validate_local(value: object, /) -> LocalType | None:
+    if value is None:
+        return value
+    if isinstance(value, str) and _LOCAL_PATTERN.fullmatch(value):
+        return _parse_local_version(value)
+    msg = f"local must be a valid version string, got {value!r}"
+    raise InvalidVersion(msg)
+
+
+# Backward compatibility for internals before 26.0. Do not use.
+class _Version(NamedTuple):
+    epoch: int
+    release: tuple[int, ...]
+    dev: tuple[str, int] | None
+    pre: tuple[str, int] | None
+    post: tuple[str, int] | None
+    local: LocalType | None
+
+
+class Version(_BaseVersion):
+    """This class abstracts handling of a project's versions.
+
+    A :class:`Version` instance is comparison aware and can be compared and
+    sorted using the standard Python interfaces.
+
+    >>> v1 = Version("1.0a5")
+    >>> v2 = Version("1.0")
+    >>> v1
+    
+    >>> v2
+    
+    >>> v1 < v2
+    True
+    >>> v1 == v2
+    False
+    >>> v1 > v2
+    False
+    >>> v1 >= v2
+    False
+    >>> v1 <= v2
+    True
+    """
+
+    __slots__ = ("_dev", "_epoch", "_key_cache", "_local", "_post", "_pre", "_release")
+    __match_args__ = ("_str",)
+
+    _regex = re.compile(r"\s*" + VERSION_PATTERN + r"\s*", re.VERBOSE | re.IGNORECASE)
+
+    _epoch: int
+    _release: tuple[int, ...]
+    _dev: tuple[str, int] | None
+    _pre: tuple[str, int] | None
+    _post: tuple[str, int] | None
+    _local: LocalType | None
+
+    _key_cache: CmpKey | None
+
+    def __init__(self, version: str) -> None:
+        """Initialize a Version object.
+
+        :param version:
+            The string representation of a version which will be parsed and normalized
+            before use.
+        :raises InvalidVersion:
+            If the ``version`` does not conform to PEP 440 in any way then this
+            exception will be raised.
+        """
+        # Validate the version and parse it into pieces
+        match = self._regex.fullmatch(version)
+        if not match:
+            raise InvalidVersion(f"Invalid version: {version!r}")
+        self._epoch = int(match.group("epoch")) if match.group("epoch") else 0
+        self._release = tuple(map(int, match.group("release").split(".")))
+        self._pre = _parse_letter_version(match.group("pre_l"), match.group("pre_n"))
+        self._post = _parse_letter_version(
+            match.group("post_l"), match.group("post_n1") or match.group("post_n2")
+        )
+        self._dev = _parse_letter_version(match.group("dev_l"), match.group("dev_n"))
+        self._local = _parse_local_version(match.group("local"))
+
+        # Key which will be used for sorting
+        self._key_cache = None
+
+    def __replace__(self, **kwargs: Unpack[_VersionReplace]) -> Self:
+        epoch = _validate_epoch(kwargs["epoch"]) if "epoch" in kwargs else self._epoch
+        release = (
+            _validate_release(kwargs["release"])
+            if "release" in kwargs
+            else self._release
+        )
+        pre = _validate_pre(kwargs["pre"]) if "pre" in kwargs else self._pre
+        post = _validate_post(kwargs["post"]) if "post" in kwargs else self._post
+        dev = _validate_dev(kwargs["dev"]) if "dev" in kwargs else self._dev
+        local = _validate_local(kwargs["local"]) if "local" in kwargs else self._local
+
+        if (
+            epoch == self._epoch
+            and release == self._release
+            and pre == self._pre
+            and post == self._post
+            and dev == self._dev
+            and local == self._local
+        ):
+            return self
+
+        new_version = self.__class__.__new__(self.__class__)
+        new_version._key_cache = None
+        new_version._epoch = epoch
+        new_version._release = release
+        new_version._pre = pre
+        new_version._post = post
+        new_version._dev = dev
+        new_version._local = local
+
+        return new_version
+
+    @property
+    def _key(self) -> CmpKey:
+        if self._key_cache is None:
+            self._key_cache = _cmpkey(
+                self._epoch,
+                self._release,
+                self._pre,
+                self._post,
+                self._dev,
+                self._local,
+            )
+        return self._key_cache
+
+    @property
+    @_deprecated("Version._version is private and will be removed soon")
+    def _version(self) -> _Version:
+        return _Version(
+            self._epoch, self._release, self._dev, self._pre, self._post, self._local
+        )
+
+    @_version.setter
+    @_deprecated("Version._version is private and will be removed soon")
+    def _version(self, value: _Version) -> None:
+        self._epoch = value.epoch
+        self._release = value.release
+        self._dev = value.dev
+        self._pre = value.pre
+        self._post = value.post
+        self._local = value.local
+        self._key_cache = None
+
+    def __repr__(self) -> str:
+        """A representation of the Version that shows all internal state.
+
+        >>> Version('1.0.0')
+        
+        """
+        return f""
+
+    def __str__(self) -> str:
+        """A string representation of the version that can be round-tripped.
+
+        >>> str(Version("1.0a5"))
+        '1.0a5'
+        """
+        # This is a hot function, so not calling self.base_version
+        version = ".".join(map(str, self.release))
+
+        # Epoch
+        if self.epoch:
+            version = f"{self.epoch}!{version}"
+
+        # Pre-release
+        if self.pre is not None:
+            version += "".join(map(str, self.pre))
+
+        # Post-release
+        if self.post is not None:
+            version += f".post{self.post}"
+
+        # Development release
+        if self.dev is not None:
+            version += f".dev{self.dev}"
+
+        # Local version segment
+        if self.local is not None:
+            version += f"+{self.local}"
+
+        return version
+
+    @property
+    def _str(self) -> str:
+        """Internal property for match_args"""
+        return str(self)
+
+    @property
+    def epoch(self) -> int:
+        """The epoch of the version.
+
+        >>> Version("2.0.0").epoch
+        0
+        >>> Version("1!2.0.0").epoch
+        1
+        """
+        return self._epoch
+
+    @property
+    def release(self) -> tuple[int, ...]:
+        """The components of the "release" segment of the version.
+
+        >>> Version("1.2.3").release
+        (1, 2, 3)
+        >>> Version("2.0.0").release
+        (2, 0, 0)
+        >>> Version("1!2.0.0.post0").release
+        (2, 0, 0)
+
+        Includes trailing zeroes but not the epoch or any pre-release / development /
+        post-release suffixes.
+        """
+        return self._release
+
+    @property
+    def pre(self) -> tuple[str, int] | None:
+        """The pre-release segment of the version.
+
+        >>> print(Version("1.2.3").pre)
+        None
+        >>> Version("1.2.3a1").pre
+        ('a', 1)
+        >>> Version("1.2.3b1").pre
+        ('b', 1)
+        >>> Version("1.2.3rc1").pre
+        ('rc', 1)
+        """
+        return self._pre
+
+    @property
+    def post(self) -> int | None:
+        """The post-release number of the version.
+
+        >>> print(Version("1.2.3").post)
+        None
+        >>> Version("1.2.3.post1").post
+        1
+        """
+        return self._post[1] if self._post else None
+
+    @property
+    def dev(self) -> int | None:
+        """The development number of the version.
+
+        >>> print(Version("1.2.3").dev)
+        None
+        >>> Version("1.2.3.dev1").dev
+        1
+        """
+        return self._dev[1] if self._dev else None
+
+    @property
+    def local(self) -> str | None:
+        """The local version segment of the version.
+
+        >>> print(Version("1.2.3").local)
+        None
+        >>> Version("1.2.3+abc").local
+        'abc'
+        """
+        if self._local:
+            return ".".join(str(x) for x in self._local)
+        else:
+            return None
+
+    @property
+    def public(self) -> str:
+        """The public portion of the version.
+
+        >>> Version("1.2.3").public
+        '1.2.3'
+        >>> Version("1.2.3+abc").public
+        '1.2.3'
+        >>> Version("1!1.2.3dev1+abc").public
+        '1!1.2.3.dev1'
+        """
+        return str(self).split("+", 1)[0]
+
+    @property
+    def base_version(self) -> str:
+        """The "base version" of the version.
+
+        >>> Version("1.2.3").base_version
+        '1.2.3'
+        >>> Version("1.2.3+abc").base_version
+        '1.2.3'
+        >>> Version("1!1.2.3dev1+abc").base_version
+        '1!1.2.3'
+
+        The "base version" is the public version of the project without any pre or post
+        release markers.
+        """
+        release_segment = ".".join(map(str, self.release))
+        return f"{self.epoch}!{release_segment}" if self.epoch else release_segment
+
+    @property
+    def is_prerelease(self) -> bool:
+        """Whether this version is a pre-release.
+
+        >>> Version("1.2.3").is_prerelease
+        False
+        >>> Version("1.2.3a1").is_prerelease
+        True
+        >>> Version("1.2.3b1").is_prerelease
+        True
+        >>> Version("1.2.3rc1").is_prerelease
+        True
+        >>> Version("1.2.3dev1").is_prerelease
+        True
+        """
+        return self.dev is not None or self.pre is not None
+
+    @property
+    def is_postrelease(self) -> bool:
+        """Whether this version is a post-release.
+
+        >>> Version("1.2.3").is_postrelease
+        False
+        >>> Version("1.2.3.post1").is_postrelease
+        True
+        """
+        return self.post is not None
+
+    @property
+    def is_devrelease(self) -> bool:
+        """Whether this version is a development release.
+
+        >>> Version("1.2.3").is_devrelease
+        False
+        >>> Version("1.2.3.dev1").is_devrelease
+        True
+        """
+        return self.dev is not None
+
+    @property
+    def major(self) -> int:
+        """The first item of :attr:`release` or ``0`` if unavailable.
+
+        >>> Version("1.2.3").major
+        1
+        """
+        return self.release[0] if len(self.release) >= 1 else 0
+
+    @property
+    def minor(self) -> int:
+        """The second item of :attr:`release` or ``0`` if unavailable.
+
+        >>> Version("1.2.3").minor
+        2
+        >>> Version("1").minor
+        0
+        """
+        return self.release[1] if len(self.release) >= 2 else 0
+
+    @property
+    def micro(self) -> int:
+        """The third item of :attr:`release` or ``0`` if unavailable.
+
+        >>> Version("1.2.3").micro
+        3
+        >>> Version("1").micro
+        0
+        """
+        return self.release[2] if len(self.release) >= 3 else 0
+
+
+class _TrimmedRelease(Version):
+    __slots__ = ()
+
+    def __init__(self, version: str | Version) -> None:
+        if isinstance(version, Version):
+            self._epoch = version._epoch
+            self._release = version._release
+            self._dev = version._dev
+            self._pre = version._pre
+            self._post = version._post
+            self._local = version._local
+            self._key_cache = version._key_cache
+            return
+        super().__init__(version)  # pragma: no cover
+
+    @property
+    def release(self) -> tuple[int, ...]:
+        """
+        Release segment without any trailing zeros.
+
+        >>> _TrimmedRelease('1.0.0').release
+        (1,)
+        >>> _TrimmedRelease('0.0').release
+        (0,)
+        """
+        # This leaves one 0.
+        rel = super().release
+        len_release = len(rel)
+        i = len_release
+        while i > 1 and rel[i - 1] == 0:
+            i -= 1
+        return rel if i == len_release else rel[:i]
+
+
+def _parse_letter_version(
+    letter: str | None, number: str | bytes | SupportsInt | None
+) -> tuple[str, int] | None:
+    if letter:
+        # We normalize any letters to their lower case form
+        letter = letter.lower()
+
+        # We consider some words to be alternate spellings of other words and
+        # in those cases we want to normalize the spellings to our preferred
+        # spelling.
+        letter = _LETTER_NORMALIZATION.get(letter, letter)
+
+        # We consider there to be an implicit 0 in a pre-release if there is
+        # not a numeral associated with it.
+        return letter, int(number or 0)
+
+    if number:
+        # We assume if we are given a number, but we are not given a letter
+        # then this is using the implicit post release syntax (e.g. 1.0-1)
+        return "post", int(number)
+
+    return None
+
+
+_local_version_separators = re.compile(r"[\._-]")
+
+
+def _parse_local_version(local: str | None) -> LocalType | None:
+    """
+    Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
+    """
+    if local is not None:
+        return tuple(
+            part.lower() if not part.isdigit() else int(part)
+            for part in _local_version_separators.split(local)
+        )
+    return None
+
+
+def _cmpkey(
+    epoch: int,
+    release: tuple[int, ...],
+    pre: tuple[str, int] | None,
+    post: tuple[str, int] | None,
+    dev: tuple[str, int] | None,
+    local: LocalType | None,
+) -> CmpKey:
+    # When we compare a release version, we want to compare it with all of the
+    # trailing zeros removed. We will use this for our sorting key.
+    len_release = len(release)
+    i = len_release
+    while i and release[i - 1] == 0:
+        i -= 1
+    _release = release if i == len_release else release[:i]
+
+    # We need to "trick" the sorting algorithm to put 1.0.dev0 before 1.0a0.
+    # We'll do this by abusing the pre segment, but we _only_ want to do this
+    # if there is not a pre or a post segment. If we have one of those then
+    # the normal sorting rules will handle this case correctly.
+    if pre is None and post is None and dev is not None:
+        _pre: CmpPrePostDevType = NegativeInfinity
+    # Versions without a pre-release (except as noted above) should sort after
+    # those with one.
+    elif pre is None:
+        _pre = Infinity
+    else:
+        _pre = pre
+
+    # Versions without a post segment should sort before those with one.
+    if post is None:
+        _post: CmpPrePostDevType = NegativeInfinity
+
+    else:
+        _post = post
+
+    # Versions without a development segment should sort after those with one.
+    if dev is None:
+        _dev: CmpPrePostDevType = Infinity
+
+    else:
+        _dev = dev
+
+    if local is None:
+        # Versions without a local segment should sort before those with one.
+        _local: CmpLocalType = NegativeInfinity
+    else:
+        # Versions with a local segment need that segment parsed to implement
+        # the sorting rules in PEP440.
+        # - Alpha numeric segments sort before numeric segments
+        # - Alpha numeric segments sort lexicographically
+        # - Numeric segments sort numerically
+        # - Shorter versions sort before longer versions when the prefixes
+        #   match exactly
+        _local = tuple(
+            (i, "") if isinstance(i, int) else (NegativeInfinity, i) for i in local
+        )
+
+    return epoch, _release, _pre, _post, _dev, _local
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/phonemizer/__init__.py b/TTS/Kokoro/.venv/Lib/site-packages/phonemizer/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..cdaaf5d6b51a183cdf98e9494e5bf39e5580b6e9
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/phonemizer/__init__.py
@@ -0,0 +1,21 @@
+# Copyright 2015-2021 Mathieu Bernard
+#
+# This file is part of phonologizer: you can redistribute it and/or
+# modify it under the terms of the GNU General Public License as
+# published by the Free Software Foundation, either version 3 of the
+# License, or (at your option) any later version.
+#
+# Phonologizer is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with phonologizer. If not, see .
+"""Multilingual text to phones converter"""
+
+from .phonemize import phonemize  # pylint: disable=unused-import
+import importlib.metadata
+
+__version__ = importlib.metadata.version("phonemizer-fork")
+"""Phonemizer version"""
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/phonemizer/logger.py b/TTS/Kokoro/.venv/Lib/site-packages/phonemizer/logger.py
new file mode 100644
index 0000000000000000000000000000000000000000..a823dae176090e98a0f212b3d6001bd5bc9b8a88
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/phonemizer/logger.py
@@ -0,0 +1,63 @@
+# Copyright 2015-2021 Mathieu Bernard
+#
+# This file is part of phonemizer: you can redistribute it and/or
+# modify it under the terms of the GNU General Public License as
+# published by the Free Software Foundation, either version 3 of the
+# License, or (at your option) any later version.
+#
+# Phonemizer is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with phonemizer. If not, see .
+"""Logging facilities for the phonemizer"""
+
+import logging
+import sys
+from logging import Logger
+
+
+def get_logger(verbosity: str = 'quiet', name: str = 'phonemizer') -> Logger:
+    """Returns a configured logging.Logger instance
+
+    The logger is configured to output messages on the standard error stream
+    (stderr).
+
+    Parameters
+    ----------
+    verbosity (str) : The level of verbosity, must be 'verbose' (displays
+      debug/info and warning messages), 'normal' (warnings only) or 'quiet' (do
+      not display anything).
+    name (str) : The logger name, default to 'phonemizer'
+
+    Raises
+    ------
+    RuntimeError if `verbosity` is not 'normal', 'verbose', or 'quiet'.
+
+    """
+    # make sure the verbosity argument is valid
+    valid_verbosity = ['normal', 'verbose', 'quiet']
+    if verbosity not in valid_verbosity:
+        raise RuntimeError(
+            f'verbosity is {verbosity} but must be in '
+            f'{", ".join(valid_verbosity)}')
+
+    logger = logging.getLogger(name)
+
+    # setup output to stderr
+    logger.handlers = []
+    handler = logging.StreamHandler(sys.stderr)
+
+    # setup verbosity level
+    logger.setLevel(logging.WARNING)
+    if verbosity == 'verbose':
+        logger.setLevel(logging.DEBUG)
+    elif verbosity == 'quiet':
+        handler = logging.NullHandler()
+
+    # setup messages format
+    handler.setFormatter(logging.Formatter('[%(levelname)s] %(message)s'))
+    logger.addHandler(handler)
+    return logger
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/phonemizer/main.py b/TTS/Kokoro/.venv/Lib/site-packages/phonemizer/main.py
new file mode 100644
index 0000000000000000000000000000000000000000..be27d3f7fe5c60905a0bc54d25c2b242e66d215b
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/phonemizer/main.py
@@ -0,0 +1,428 @@
+#!/usr/bin/env python
+# Copyright 2015-2021 Mathieu Bernard
+#
+# This file is part of phonemizer: you can redistribute it and/or
+# modify it under the terms of the GNU General Public License as
+# published by the Free Software Foundation, either version 3 of the
+# License, or (at your option) any later version.
+#
+# Phonemizer is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with phonemizer. If not, see .
+"""Command-line phonemizer tool, have a 'phonemizer --help' to get in"""
+
+import argparse
+import os
+import sys
+import re
+
+from phonemizer import phonemize, separator, version, logger, punctuation
+from phonemizer.backend import BACKENDS
+
+
+class CatchExceptions:  # pragma: nocover
+    """Decorator wrapping a function in a try/except block
+
+    When an exception occurs, display a user friendly message on
+    standard output before exiting with error code 1.
+
+    The detected exceptions are ValueError, OSError, RuntimeError,
+    AssertionError and KeyboardInterrupt.
+
+    Parameters
+    ----------
+    function :
+        The function to wrap in a try/except block
+
+    """
+    def __init__(self, function):
+        self.function = function
+
+    def __call__(self):
+        """Executes the wrapped function and catch common exceptions"""
+        try:
+            self.function()
+
+        except (IOError, ValueError, OSError,
+                RuntimeError, AssertionError) as err:
+            self.exit('fatal error: {}'.format(err))
+
+        except KeyboardInterrupt:
+            self.exit('keyboard interruption, exiting')
+
+    @staticmethod
+    def exit(msg):
+        """Write `msg` on stderr and exit with error code 1"""
+        sys.stderr.write(msg.strip() + '\n')
+        sys.exit(1)
+
+
+def parse_args():
+    """Argument parser for the phonemization script"""
+    parser = argparse.ArgumentParser(
+        formatter_class=argparse.RawDescriptionHelpFormatter,
+        description='''Multilingual text to phonemes converter
+
+The 'phonemize' program allows simple phonemization of words and texts
+in many language using four backends: espeak, espeak-mbrola, festival
+and segments.
+
+- espeak is a text-to-speech software supporting multiple languages
+  and IPA (International Phonetic Alphabet) output. See
+  http://espeak.sourceforge.net or
+  https://github.com/espeak-ng/espeak-ng
+
+- espeak-mbrola uses the SAMPA phonetic alphabet, it requires mbrola to be
+  installed as well as additional mbrola voices. It does not support word or
+  syllable tokenization. See
+  https://github.com/espeak-ng/espeak-ng/blob/master/docs/mbrola.md
+
+- festival is also a text-to-speech software. Currently only American
+  English is supported and festival uses a custom phoneset
+  (http://www.festvox.org/bsv/c4711.html), but festival is the only
+  backend supporting tokenization at the syllable
+  level. See http://www.cstr.ed.ac.uk/projects/festival
+
+- segments is a Unicode tokenizer that build a phonemization from a
+  grapheme to phoneme mapping provided as a file by the user. See
+  https://github.com/cldf/segments.
+
+See the '--list-languages' option below for details on the languages
+supported by each backend.
+
+''',
+        epilog='''
+Examples:
+
+* Phonemize a US English text with espeak
+
+   $ echo 'hello world' | phonemize -l en-us -b espeak
+   həloʊ wɜːld
+
+* Phonemize a US English text with festival
+
+   $ echo 'hello world' | phonemize -l en-us -b festival
+   hhaxlow werld
+
+* Phonemize a Japanese text with segments
+
+  $ echo 'konnichiwa tsekai' | phonemize -l japanese -b segments
+  konnitʃiwa t͡sekai
+
+* Add a separator between phones
+
+  $ echo 'hello world' | phonemize -l en-us -b festival -p '-' --strip
+  hh-ax-l-ow w-er-l-d
+
+* Phonemize some French text file using espeak
+
+  $ phonemize -l fr-fr -b espeak text.txt -o phones.txt
+        ''')
+
+    # general arguments
+    parser.add_argument(
+        '-V', '--version',
+        action='store_true',
+        help='show version information and exit.')
+
+    group = parser.add_mutually_exclusive_group()
+    group.add_argument(
+        '-v', '--verbose',
+        action='store_true',
+        help='write all log messages to stderr '
+        '(displays only warnings by default).')
+    group.add_argument(
+        '-q', '--quiet',
+        action='store_true',
+        help='do not display any log message, even warnings.')
+
+    parser.add_argument(
+        '-j', '--njobs',
+        type=int, metavar='', default=1,
+        help='number of parallel jobs, default is %(default)s.')
+
+    # input/output arguments
+    group = parser.add_argument_group('input/output')
+    group.add_argument(
+        'input',
+        default=sys.stdin, nargs='?', metavar='',
+        help='input text file to phonemize, if not specified read from stdin.')
+
+    group.add_argument(
+        '-o', '--output',
+        default=sys.stdout, metavar='',
+        help='output text file to write, if not specified write to stdout.')
+
+    group.add_argument(
+        '--prepend-text',
+        default=False, const=True, nargs='?', metavar='',
+        help='''prepend each line of the phonemized output text with its
+        matching input text. If a string is specified as option value, use it
+        as field separator, else use one of "|", "||", "|||", "||||" by
+        selecting the first one that is not configured as a token separator
+        (see -p/-s/-w options).''')
+
+    group.add_argument(
+        '--preserve-empty-lines',
+        action='store_true',
+        help='''preserve the empty lines in the phonemized output, default is
+        to remove them.''')
+
+    group = parser.add_argument_group('backends')
+    group.add_argument(
+        '-b', '--backend',
+        metavar='', default=None,
+        choices=['espeak', 'espeak-mbrola', 'festival', 'segments'],
+        help="""the phonemization backend, must be 'espeak', 'espeak-mbrola',
+        'festival' or 'segments'. Default is 'espeak'.""")
+
+    group.add_argument(
+        '-L', '--list-languages',
+        action='store_true',
+        help="""list available languages (and exit) for the specified backend,
+        or for all backends if none selected.""")
+
+    group = parser.add_argument_group('language')
+    group.add_argument(
+        '-l', '--language',
+        metavar='', default='en-us',
+        help='''the language code of the input text, use '--list-languages'
+        for a list of supported languages. Default is %(default)s.''')
+
+    group = parser.add_argument_group('token separators')
+    group.add_argument(
+        '-p', '--phone-separator',
+        metavar='', default=separator.default_separator.phone,
+        help='phone separator, default is "%(default)s".')
+
+    group.add_argument(
+        '-w', '--word-separator',
+        metavar='', default=separator.default_separator.word,
+        help='''word separator, not valid for espeak-mbrola backend,
+        default is "%(default)s".''')
+
+    group.add_argument(
+        '-s', '--syllable-separator',
+        metavar='', default=separator.default_separator.syllable,
+        help='''syllable separator, only valid for festival backend,
+        this option has no effect if another backend is used.
+        Default is "%(default)s".''')
+
+    group.add_argument(
+        '--strip',
+        action='store_true',
+        help='removes the end separators in phonemized tokens.')
+
+    group = parser.add_argument_group('specific to espeak backend')
+    try:
+        espeak_library = BACKENDS['espeak'].library()
+    except RuntimeError:  # pragma: nocover
+        espeak_library = None
+
+    group.add_argument(
+        '--espeak-library',
+        default=None, type=str, metavar='',
+        help=f'''the path to the espeak shared library to use (*.so on Linux,
+        *.dylib on Mac and *.dll on Windows, useful to overload the default
+        espeak version installed on the system). Default to
+        {espeak_library}. This path can also be specified
+        using the PHONEMIZER_ESPEAK_LIBRARY environment variable.''')
+    group.add_argument(
+        '--tie',
+        nargs='?', default=False, const=True, metavar='',
+        help='''when the option is set, use a tie character within multi-letter
+        phoneme names, default to U+361 (as in d͡ʒ), 'z' means ZWJ character,
+        only compatible with espeak>1.48 and incompatible with the
+        -p/--phone-separator option''')
+    group.add_argument(
+        '--with-stress',
+        action='store_true',
+        help='''when the option is set, the stresses on phonemes are present
+        (stresses characters are ˈ'ˌ). By default stresses are removed.''')
+    group.add_argument(
+        '--language-switch',
+        default='keep-flags',
+        choices=['keep-flags', 'remove-flags', 'remove-utterance'],
+        help="""espeak can pronounce some words in another language (typically
+        English) when phonemizing a text. This option setups the policy to use
+        when such a language switch occurs. Three values are available:
+        'keep-flags' (the default), 'remove-flags' or 'remove-utterance'. The
+        'keep-flags' policy keeps the language switching flags, for example
+        (en) or (jp), in the output. The 'remove-flags' policy removes them and
+        the 'remove-utterance' policy removes the whole line of text including
+        a language switch.""")
+    group.add_argument(
+        '--words-mismatch',
+        default='ignore', choices=['ignore', 'warn', 'remove'],
+        help="""espeak can join two consecutive words or drop some words,
+        yielding a word count mismatch between orthographic and phonemized
+        text. This option setups the policy to use when such a words count
+        mismatch occurs. Three values are available: 'ignore' (the default)
+        which do nothing, 'warn' which issue a warning for each mismatched
+        line, and 'remove' which remove the mismatched lines from the
+        output.""")
+
+    group = parser.add_argument_group('specific to festival backend')
+    try:
+        festival_executable = BACKENDS['festival'].executable()
+    except RuntimeError:  # pragma: nocover
+        festival_executable = None
+
+    group.add_argument(
+        '--festival-executable',
+        default=None, type=str, metavar='',
+        help=f'''the path to the festival executable to use (useful to
+        overload the default festival installed on the system). Default to
+        {festival_executable}. This path can also be specified using the
+        PHONEMIZER_FESTIVAL_EXECUTABLE environment variable.''')
+
+    group = parser.add_argument_group(
+        'punctuation processing',
+        description='not available for espeak-mbrola backend')
+    group.add_argument(
+        '--preserve-punctuation',
+        action='store_true',
+        help='''preserve the punctuation marks in the phonemized output,
+        default is to remove them.''')
+    group.add_argument(
+        '--punctuation-marks',
+        type=str, metavar='',
+        default=punctuation.Punctuation.default_marks(),
+        help='''the marks to consider during punctuation processing (either
+        for removal or preservation). Default is %(default)s.''')
+    group.add_argument(
+        '--punctuation-marks-is-regex',
+        action='store_true',
+        help="""interpret the '--punctuation-marks' parameter as a regex.
+        Default is to interpret as a string.""")
+
+    return parser.parse_args()
+
+
+def list_languages(args_backend):
+    """Returns the available languages for the given `backend` as a str"""
+    for backend in BACKENDS.keys() if not args_backend else [args_backend]:
+        print(
+            f'supported languages for {backend} are:\n' +
+            '\n'.join(f'\t{k}\t->\t{v}' for k, v in sorted(
+                BACKENDS[backend].supported_languages().items())))
+
+
+def get_logger(verbose, quiet):
+    """Returns a configured logger"""
+    verbosity = 'normal'
+    if verbose:
+        verbosity = 'verbose'
+    elif quiet:
+        verbosity = 'quiet'
+    return logger.get_logger(verbosity=verbosity)
+
+
+def setup_stream(stream, mode):
+    """If `stream` is a filename, open it as a file"""
+    if isinstance(stream, str):
+        # pylint: disable=consider-using-with
+        return open(stream, mode, encoding='utf8')
+    return stream  # pragma: nocover
+
+
+@CatchExceptions
+def main():
+    """Phonemize a text from command-line arguments"""
+    args = parse_args()
+
+    # setup a custom path to espeak and festival if required (this must be done
+    # before generating the version message)
+    if args.espeak_library:
+        BACKENDS['espeak'].set_library(args.espeak_library)
+    if args.festival_executable:
+        BACKENDS['festival'].set_executable(args.festival_executable)
+
+    # display version information and exit
+    if args.version:
+        print(version.version())
+        return
+
+    # list supported languages and exit
+    if args.list_languages:
+        print(list_languages(args.backend))
+        return
+
+    # set default backend as espeak if not specified
+    args.backend = args.backend or 'espeak'
+
+    # configure logging according to --verbose/--quiet options
+    log = get_logger(args.verbose, args.quiet)
+
+    # configure input:output as a readable/writable streams
+    streamin = setup_stream(args.input, 'r')
+    log.debug('reading from %s', streamin.name)
+    streamout = setup_stream(args.output, 'w')
+    log.debug('writing to %s', streamout.name)
+
+    # configure the separator for phonemes, syllables and words.
+    if args.backend == 'espeak-mbrola':
+        log.debug('using espeak-mbrola backend: ignoring word separator')
+        sep = separator.Separator(
+            phone=args.phone_separator,
+            syllable=None,
+            word=None)
+    else:
+        sep = separator.Separator(
+            phone=args.phone_separator,
+            syllable=args.syllable_separator,
+            word=args.word_separator)
+    log.debug('separator is %s', sep)
+
+    if args.prepend_text:
+        input_output_separator = sep.input_output_separator(args.prepend_text)
+        log.debug(
+            'prepend input text to output, separator is "%s"',
+            input_output_separator)
+    else:
+        input_output_separator = False
+
+    if args.punctuation_marks_is_regex:
+        try:
+            log.debug('punctuation marks is regex %s', args.punctuation_marks)
+            args.punctuation_marks = re.compile(args.punctuation_marks)
+        except re.error:
+            # manually close the open streams for windows
+            streamin.close()
+            streamout.close()
+            raise ValueError(f"can't compile regex pattern from {args.punctuation_marks}")
+
+    # phonemize the input text
+    out = phonemize(
+        streamin.readlines(),
+        language=args.language,
+        backend=args.backend,
+        separator=sep,
+        strip=args.strip,
+        prepend_text=args.prepend_text,
+        preserve_empty_lines=args.preserve_empty_lines,
+        preserve_punctuation=args.preserve_punctuation,
+        punctuation_marks=args.punctuation_marks,
+        with_stress=args.with_stress,
+        tie=args.tie,
+        language_switch=args.language_switch,
+        words_mismatch=args.words_mismatch,
+        njobs=args.njobs,
+        logger=log)
+
+    if out and input_output_separator:
+        streamout.write(
+            os.linesep.join(
+                f'{line[0]} {input_output_separator} {line[1]}'
+                for line in out)
+            + os.linesep)
+    elif out:
+        streamout.write(os.linesep.join(out) + os.linesep)
+
+
+if __name__ == '__main__':  # pragma: nocover
+    main()
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/phonemizer/phonemize.py b/TTS/Kokoro/.venv/Lib/site-packages/phonemizer/phonemize.py
new file mode 100644
index 0000000000000000000000000000000000000000..c9adb59e24e1f3932967da67268e8d51d2a0fae8
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/phonemizer/phonemize.py
@@ -0,0 +1,347 @@
+# Copyright 2015-2021 Mathieu Bernard
+#
+# This file is part of phonemizer: you can redistribute it and/or
+# modify it under the terms of the GNU General Public License as
+# published by the Free Software Foundation, either version 3 of the
+# License, or (at your option) any later version.
+#
+# Phonemizer is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with phonemizer. If not, see .
+"""Provides the phonemize function
+
+To use it in your own code, type:
+
+    from phonemizer import phonemize
+
+"""
+
+import os
+import sys
+from logging import Logger
+from typing import Optional, Union, List, Pattern
+
+from typing_extensions import Literal
+
+from phonemizer.backend import BACKENDS
+from phonemizer.backend.base import BaseBackend
+from phonemizer.backend.espeak.language_switch import LanguageSwitch
+from phonemizer.backend.espeak.words_mismatch import WordMismatch
+from phonemizer.logger import get_logger
+from phonemizer.punctuation import Punctuation
+from phonemizer.separator import default_separator, Separator
+from phonemizer.utils import list2str, str2list
+
+Backend = Literal['espeak', 'espeak-mbrola', 'festival', 'segments']
+_PHONEMIZER_CACHE = {}
+
+
+def phonemize(  # pylint: disable=too-many-arguments
+        text,
+        language: str = 'en-us',
+        backend: Backend = 'espeak',
+        separator: Optional[Separator] = default_separator,
+        strip: bool = False,
+        prepend_text: bool = False,
+        preserve_empty_lines: bool = False,
+        preserve_punctuation: bool = False,
+        punctuation_marks: Union[str, Pattern] = Punctuation.default_marks(),
+        with_stress: bool = False,
+        tie: Union[bool, str] = False,
+        language_switch: LanguageSwitch = 'keep-flags',
+        words_mismatch: WordMismatch = 'ignore',
+        njobs: int = 1,
+        logger: Logger = get_logger()):
+    """Multilingual text to phonemes converter
+
+    Return a phonemized version of an input `text`, given its `language` and a
+    phonemization `backend`.
+
+    Note
+    ----
+
+    To improve the processing speed it is better to minimize the calls to this
+    function: provide the input text as a list and call phonemize() a single
+    time is much more efficient than calling it on each element of the list.
+    Indeed the initialization of the phonemization backend can be expensive,
+    especially for espeak. In one example,
+
+    Do this:
+
+    >>> text = [line1, line2, ...]
+    >>> phonemize(text, ...)
+
+    Not this:
+
+    >>> for line in text:
+    >>>     phonemize(line, ...)
+
+    Parameters
+    ----------
+
+    text: str or list of str
+        The text to be phonemized. Any empty line will
+        be ignored. If ``text`` is an str, it can be multiline (lines being
+        separated by ``\\n``). If ``text`` is a list, each element is considered as a
+        separated line. Each line is considered as a text utterance.
+
+    language: str
+        The language code of the input text, must be supported by
+        the backend. If ``backend`` is 'segments', the language can be a file with
+        a grapheme to phoneme mapping.
+
+    backend: str, optional
+        The software backend to use for phonemization,
+        must be 'festival' (US English only is supported, coded 'en-us'),
+        'espeak', 'espeak-mbrola' or 'segments'.
+
+    separator: Separator
+        string separators between phonemes, syllables and
+        words, default to separator.default_separator. Syllable separator is
+        considered only for the festival backend. Word separator is ignored by
+        the 'espeak-mbrola' backend. Initialize it as follows:
+            >>> from phonemizer.separator import Separator
+            >>> separator = Separator(phone='-', word=' ')
+
+    strip: bool, optional
+        If True, don't output the last word and phone
+        separators of a token, default to False.
+
+    prepend_text: bool, optional
+        When True, returns a pair (input utterance,
+        phonemized utterance) for each line of the input text. When False,
+        returns only the phonemized utterances. Default to False
+
+    preserve_empty_lines: bool, optional
+        When True, will keep the empty lines
+        in the phonemized output. Default to False and remove all empty lines.
+
+    preserve_punctuation: bool, optional
+        When True, will keep the punctuation
+        in the phonemized output. Not supported by the 'espeak-mbrola' backend.
+        Default to False and remove all the punctuation.
+
+    punctuation_marks: str or re.Pattern, optional
+        The punctuation marks to consider when dealing with punctuation,
+        either for removal or preservation.  Can be defined as a string or regular expression.
+        Default to Punctuation.default_marks().
+
+    with_stress: bool, optional
+        This option is only valid for the 'espeak'
+        backend. When True the stresses on phonemes are present (stresses
+        characters are ˈ'ˌ). When False stresses are removed. Default to False.
+
+    tie: bool or char, optional
+        This option is only valid for the 'espeak'
+        backend with espeak>=1.49. It is incompatible with phone separator. When
+        not False, use a tie character within multi-letter phoneme names. When
+        True, the char 'U+361' is used (as in d͡ʒ), 'z' means ZWJ character,
+        default to False.
+
+    language_switch: str, optional
+        Espeak can output some words in another
+        language (typically English) when phonemizing a text. This option setups
+        the policy to use when such a language switch occurs. Three values are
+        available : 'keep-flags' (the default), 'remove-flags' or
+        'remove-utterance'. The 'keep-flags' policy keeps the language switching
+        flags, for example "(en) or (jp)", in the output. The 'remove-flags'
+        policy removes them and the 'remove-utterance' policy removes the whole
+        line of text including a language switch. This option is only valid for
+        the 'espeak' backend.
+
+    words_mismatch: str, optional
+        Espeak can join two consecutive words or
+        drop some words, yielding a word count mismatch between orthographic and
+        phonemized text. This option setups the policy to use when such a words
+        count mismatch occurs. Three values are available: 'ignore' (the default)
+        which do nothing, 'warn' which issue a warning for each mismatched line,
+        and 'remove' which remove the mismatched lines from the output.
+
+    njobs: int
+        The number of parallel jobs to launch. The input text is split
+        in ``njobs`` parts, phonemized on parallel instances of the backend and the
+        outputs are finally collapsed.
+
+    logger: logging.Logger
+        the logging instance where to send messages. If
+        not specified, use the default system logger.
+
+    Returns
+    -------
+    phonemized text: str or list of str
+        The input ``text`` phonemized for the
+        given ``language`` and ``backend``. The returned value has the same type of
+        the input text (either a list or a string), excepted if ``prepend_input``
+        is True where the output is forced as a list of pairs (input_text,
+        phonemized text).
+
+    Raises
+    ------
+    RuntimeError
+        if the ``backend`` is not valid or is valid but not installed,
+        if the ``language`` is not supported by the ``backend``, if any incompatible options are used.
+
+    """
+    # ensure we are using a compatible Python version
+    if sys.version_info < (3, 6):  # pragma: nocover
+        logger.error(
+            'Your are using python-%s which is unsupported by the phonemizer, '
+            'please update to python>=3.6', ".".join(sys.version_info))
+
+    # ensure the arguments are valid
+    _check_arguments(
+        backend, with_stress, tie, separator, language_switch, words_mismatch)
+
+    # preserve_punctuation and word separator not valid for espeak-mbrola
+    if backend == 'espeak-mbrola' and preserve_punctuation:
+        logger.warning('espeak-mbrola backend cannot preserve punctuation')
+    if backend == 'espeak-mbrola' and separator.word:
+        logger.warning('espeak-mbrola backend cannot preserve word separation')
+        
+    # cache handling: if this instance has been created in the past, everything should be A-OK
+    # todo: clean cache on __delete__
+    cache_key = (
+        backend,
+        language,
+        str(punctuation_marks),
+        preserve_punctuation,
+        with_stress,
+        tie,
+        language_switch,
+        words_mismatch
+    )
+    
+    if cache_key in _PHONEMIZER_CACHE:
+        return _phonemize(_PHONEMIZER_CACHE[cache_key], text, separator, strip, njobs, prepend_text, preserve_empty_lines)
+
+    # initialize the phonemization backend
+    if backend == 'espeak':
+        phonemizer = BACKENDS[backend](
+            language,
+            punctuation_marks=punctuation_marks,
+            preserve_punctuation=preserve_punctuation,
+            with_stress=with_stress,
+            tie=tie,
+            language_switch=language_switch,
+            words_mismatch=words_mismatch,
+            logger=logger)
+        # cache espeak-ng instance
+        _PHONEMIZER_CACHE[cache_key] = phonemizer
+    elif backend == 'espeak-mbrola':
+        phonemizer = BACKENDS[backend](
+            language,
+            logger=logger)
+    else:  # festival or segments
+        phonemizer = BACKENDS[backend](
+            language,
+            punctuation_marks=punctuation_marks,
+            preserve_punctuation=preserve_punctuation,
+            logger=logger)
+
+    # do the phonemization
+    return _phonemize(phonemizer, text, separator, strip, njobs, prepend_text, preserve_empty_lines)
+
+
+def _check_arguments(  # pylint: disable=too-many-arguments
+        backend: Backend,
+        with_stress: bool,
+        tie: Union[bool, str],
+        separator: Separator,
+        language_switch: LanguageSwitch,
+        words_mismatch: WordMismatch):
+    """Auxiliary function to phonemize()
+
+    Ensures the parameters are compatible with each other, raises a
+    RuntimeError the first encountered error.
+
+    """
+    # ensure the backend is either espeak, festival or segments
+    if backend not in ('espeak', 'espeak-mbrola', 'festival', 'segments'):
+        raise RuntimeError(
+            '{} is not a supported backend, choose in {}.'
+                .format(backend, ', '.join(
+                ('espeak', 'espeak-mbrola', 'festival', 'segments'))))
+
+    # with_stress option only valid for espeak
+    if with_stress and backend != 'espeak':
+        raise RuntimeError(
+            'the "with_stress" option is available for espeak backend only, '
+            'but you are using {} backend'.format(backend))
+
+    # tie option only valid for espeak
+    if tie and backend != 'espeak':
+        raise RuntimeError(
+            'the "tie" option is available for espeak backend only, '
+            'but you are using {} backend'.format(backend))
+
+    # tie option incompatible with phone separator
+    if tie and separator.phone:
+        raise RuntimeError(
+            'the "tie" option is incompatible with phone separator '
+            f'(which is "{separator.phone}")')
+
+    # language_switch option only valid for espeak
+    if language_switch != 'keep-flags' and backend != 'espeak':
+        raise RuntimeError(
+            'the "language_switch" option is available for espeak backend '
+            'only, but you are using {} backend'.format(backend))
+
+    # words_mismatch option only valid for espeak
+    if words_mismatch != 'ignore' and backend != 'espeak':
+        raise RuntimeError(
+            'the "words_mismatch" option is available for espeak backend '
+            'only, but you are using {} backend'.format(backend))
+
+
+def _phonemize(  # pylint: disable=too-many-arguments
+        backend: BaseBackend,
+        text: Union[str, List[str]],
+        separator: Separator,
+        strip: bool,
+        njobs: int,
+        prepend_text: bool,
+        preserve_empty_lines: bool):
+    """Auxiliary function to phonemize()
+
+    Does the phonemization and returns the phonemized text. Raises a
+    RuntimeError on error.
+
+    """
+    # remember the text type for output (either list or string)
+    text_type = type(text)
+
+    # force the text as a list
+    text = [line.strip(os.linesep) for line in str2list(text)]
+
+    # if preserving empty lines, note the index of each empty line
+    if preserve_empty_lines:
+        empty_lines = [n for n, line in enumerate(text) if not line.strip()]
+
+    # ignore empty lines
+    text = [line for line in text if line.strip()]
+
+    if (text):
+        # phonemize the text
+        phonemized = backend.phonemize(
+            text, separator=separator, strip=strip, njobs=njobs)
+    else:
+        phonemized = []
+
+    # if preserving empty lines, reinsert them into text and phonemized lists
+    if preserve_empty_lines:
+        for i in empty_lines: # noqa
+            if prepend_text:
+                text.insert(i, '')
+            phonemized.insert(i, '')
+
+    # at that point, the phonemized text is a list of str. Format it as
+    # expected by the parameters
+    if prepend_text:
+        return list(zip(text, phonemized))
+    if text_type == str:
+        return list2str(phonemized)
+    return phonemized
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/phonemizer/punctuation.py b/TTS/Kokoro/.venv/Lib/site-packages/phonemizer/punctuation.py
new file mode 100644
index 0000000000000000000000000000000000000000..4d157ec87a789dd721f7587ced7c1a1807d66b24
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/phonemizer/punctuation.py
@@ -0,0 +1,220 @@
+# Copyright 2015-2021 Mathieu Bernard
+#
+# This file is part of phonemizer: you can redistribute it and/or
+# modify it under the terms of the GNU General Public License as
+# published by the Free Software Foundation, either version 3 of the
+# License, or (at your option) any later version.
+#
+# Phonemizer is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with phonemizer. If not, see .
+"""Implementation of punctuation processing"""
+
+import collections
+import re
+from typing import List, Union, Tuple, Pattern
+
+from phonemizer.utils import str2list
+from phonemizer.separator import Separator
+
+# The punctuation marks considered by default.
+_DEFAULT_MARKS = ';:,.!?¡¿—…"«»“”(){}[]'
+
+_MarkIndex = collections.namedtuple(
+    '_mark_index', ['index', 'mark', 'position'])
+
+
+class Punctuation:
+    """Preserve or remove the punctuation during phonemization
+
+    Backends behave differently with punctuation: festival and espeak ignore it
+    and remove it silently whereas segments will raise an error. The
+    Punctuation class solves that issue by "hiding" the punctuation to the
+    phonemization backend and restoring it afterwards.
+
+    Parameters
+    ----------
+    marks (str or re.Pattern) : The punctuation marks to consider for processing
+        (either removal or preservation). If a string, each mark must be made of
+        a single character. Default to Punctuation.default_marks().
+
+    """
+
+    def __init__(self, marks: Union[str, Pattern] = _DEFAULT_MARKS):
+        self._marks: str = None  # noqa
+        self._marks_re: Pattern[str] = None  # noqa
+        self.marks = marks
+
+    @staticmethod
+    def default_marks():
+        """Returns the default punctuation marks as a string"""
+        return _DEFAULT_MARKS
+
+    @property
+    def marks(self):
+        """The punctuation marks as a string"""
+        if self._marks:
+            return self._marks
+        raise ValueError('punctuation initialized from regex, cannot access marks as a string')
+
+    @marks.setter
+    def marks(self, value: Union[str, Pattern]):
+        if isinstance(value, Pattern):
+            # catch the pattern surrounded by zero or more spaces on either side
+            self._marks_re = re.compile(r'((' + value.pattern + r')|\s)+')
+            self._marks = None
+        elif isinstance(value, str):
+            self._marks = ''.join(set(value))
+
+            # catching all the marks in one regular expression: zero or more spaces
+            # + one or more marks + zero or more spaces.
+            self._marks_re = re.compile(fr'(\s*[{re.escape(self._marks)}]+\s*)+')
+        else:
+            raise ValueError('punctuation marks must be defined as a string or re.Pattern')
+
+    def remove(self, text: Union[str, List[str]]) -> Union[str, List[str]]:
+        """Returns the `text` with all punctuation marks replaced by spaces
+
+        The input `text` can be a string or a list and is returned with the
+        same type and punctuation removed.
+
+        """
+
+        def aux(text: str) -> str:
+            return re.sub(self._marks_re, ' ', text).strip()
+
+        if isinstance(text, str):
+            return aux(text)
+        return [aux(line) for line in text]
+
+    def preserve(self, text: Union[List[str], str]) -> Tuple[List[List[str]], List[_MarkIndex]]:
+        """Removes punctuation from `text`, allowing for furter restoration
+
+        This method returns the text as a list of punctuated chunks, along with
+        a list of punctuation marks for furter restoration:
+
+            'hello, my world!' -> ['hello', 'my world'], [',', '!']
+
+        """
+        text: List[str] = str2list(text)
+        preserved_text = []
+        preserved_marks = []
+
+        for num, line in enumerate(text):
+            line, marks = self._preserve_line(line, num)
+            preserved_text += line
+            preserved_marks += marks
+        return [line for line in preserved_text if line], preserved_marks
+
+    def _preserve_line(self, line: str, num: int) -> Tuple[List[str], List[_MarkIndex]]:
+        """Auxiliary method for Punctuation.preserve()"""
+        matches = list(re.finditer(self._marks_re, line))
+        if not matches:
+            return [line], []
+
+        # the line is made only of punctuation marks
+        if len(matches) == 1 and matches[0].group() == line:
+            return [], [_MarkIndex(num, line, 'A')]
+
+        # build the list of mark indexes required to restore the punctuation
+        marks = []
+        for match in matches:
+            # find the position of the punctuation mark in the utterance:
+            # begin (B), end (E), in the middle (I) or alone (A)
+            position = 'I'
+            if match == matches[0] and line.startswith(match.group()):
+                position = 'B'
+            elif match == matches[-1] and line.endswith(match.group()):
+                position = 'E'
+            marks.append(_MarkIndex(num, match.group(), position))
+
+        # split the line into sublines, each separated by a punctuation mark
+        preserved_line = []
+        for mark in marks:
+            split = line.split(mark.mark)
+            prefix, suffix = split[0], mark.mark.join(split[1:])
+            preserved_line.append(prefix)
+            line = suffix
+
+        # append any trailing text to the preserved line
+        return preserved_line + [line], marks
+
+    @classmethod
+    def restore(cls, text: Union[str, List[str]],
+                marks: List[_MarkIndex],
+                sep: Separator,
+                strip: bool) -> List[str]:
+        """Restore punctuation in a text.
+
+        This is the reverse operation of Punctuation.preserve(). It takes a
+        list of punctuated chunks and a list of punctuation marks, as well as
+        the separator and strip parameters used by phonemize. It returns the
+        punctuated text as a list:
+
+            ['hello', 'my world'], [',', '!'] -> ['hello, my world!']
+
+        """
+        text = str2list(text)
+        punctuated_text = []
+        pos = 0
+
+        while text or marks:
+
+            if not marks:
+                for line in text:
+                    # if strip is False, ensure the final word ends with a word separator
+                    if not strip and sep.word and not line.endswith(sep.word):
+                        line = line + sep.word
+                    punctuated_text.append(line)
+                text = []
+            elif not text:
+                # nothing has been phonemized, returns the marks alone, with internal
+                # spaces replaced by the word separator
+                punctuated_text.append(re.sub(' ', sep.word, ''.join(m.mark for m in marks)))
+                marks = []
+
+            else:
+                current_mark = marks[0]
+                if current_mark.index == pos:
+
+                    # place the current mark here
+                    mark = marks[0]
+                    marks = marks[1:]
+                    # replace internal spaces in the current mark with the word separator
+                    mark = re.sub(' ', sep.word, mark.mark)
+
+                    # remove the word last separator from the current word
+                    if sep.word and text[0].endswith(sep.word):
+                        text[0] = text[0][:-len(sep.word)]
+
+                    if current_mark.position == 'B':
+                        text[0] = mark + text[0]
+                    elif current_mark.position == 'E':
+                        punctuated_text.append(text[0] + mark + ('' if strip or mark.endswith(sep.word) else sep.word))
+                        text = text[1:]
+                        pos = pos + 1
+                    elif current_mark.position == 'A':
+                        punctuated_text.append(mark + ('' if strip or mark.endswith(sep.word) else sep.word))
+                        pos = pos + 1
+                    else:
+                        # position == 'I'
+                        if len(text) == 1:  # pragma: nocover
+                            # a corner case where the final part of an intermediate
+                            # mark (I) has not been phonemized
+                            text[0] = text[0] + mark
+                        else:
+                            first_word = text[0]
+                            text = text[1:]
+                            text[0] = first_word + mark + text[0]
+
+                else:
+                    punctuated_text.append(text[0])
+                    text = text[1:]
+                    pos = pos + 1
+
+
+        return punctuated_text
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/phonemizer/separator.py b/TTS/Kokoro/.venv/Lib/site-packages/phonemizer/separator.py
new file mode 100644
index 0000000000000000000000000000000000000000..e6ddd836336ab11b68c870c43cf49af5345782ef
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/phonemizer/separator.py
@@ -0,0 +1,118 @@
+# Copyright 2015-2021 Mathieu Bernard
+#
+# This file is part of phonemizer: you can redistribute it and/or
+# modify it under the terms of the GNU General Public License as
+# published by the Free Software Foundation, either version 3 of the
+# License, or (at your option) any later version.
+#
+# Phonemizer is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with phonemizer. If not, see .
+"""Provides the Separator tuple and its default value"""
+from typing import Optional, Union
+
+
+class Separator:
+    """Defines phone, syllable and word boundary tokens"""
+
+    def __init__(self, word: str = ' ',
+                 syllable: Optional[str] = None,
+                 phone: Optional[str] = None):
+        # check we have different separators, None excluded
+        sep1 = list(sep for sep in (phone, syllable, word) if sep)
+        sep2 = set(sep for sep in (phone, syllable, word) if sep)
+        if len(sep1) != len(sep2):
+            raise ValueError(
+                'illegal separator with word="{}", syllable="{}" and '
+                'phone="{}", must be all differents if not empty'
+                    .format(phone, syllable, word))
+
+        self._phone = str(phone) if phone else ''
+        self._syllable = str(syllable) if syllable else ''
+        self._word = str(word) if word else ''
+
+    def __eq__(self, other: 'Separator'):
+        return (
+                self.phone == other.phone
+                and self.syllable == other.syllable
+                and self.word == other.word)
+
+    def __str__(self):
+        return (
+            f'(phone: "{self.phone}", '
+            f'syllable: "{self.syllable}", '
+            f'word: "{self.word}")')
+
+    @property
+    def phone(self):
+        """Phones separator"""
+        return self._phone
+
+    @property
+    def syllable(self):
+        """Syllables separator"""
+        return self._syllable
+
+    @property
+    def word(self):
+        """Words separator"""
+        return self._word
+
+    def __contains__(self, value: str):
+        """Returns True if the separator has `value` as token separation"""
+        return value in {self.phone, self.syllable, self.word}
+
+    def input_output_separator(self, field_separator: Union[str, bool]) \
+            -> Union[str, bool]:
+        """Returns a suitable input/output separator based on token separator
+
+        The input/output separator split orthographic and phonetic texts when
+        using the --prepend-text option from command-line.
+
+        Parameters
+        ----------
+
+        field_separator: bool or str
+            If str, ensures it's value is not
+            already defined as a token separator. If True choose one of "|",
+            "||", "|||", "||||" (the first one that is not defined as a token
+            separator)
+
+        Returns
+        -------
+        The input/output separator, or False if ``field_separator`` is False
+
+        Raises
+        ------
+        RuntimeError
+            if ``field_separator`` is a str but is already registered as token separator
+
+        """
+        if not field_separator:
+            return False
+
+        if isinstance(field_separator, str):
+            if field_separator in self:
+                raise RuntimeError(
+                    f'cannot prepend input with "{field_separator}" because '
+                    f'it is already a token separator: {self}')
+            return field_separator
+
+        if field_separator is True:
+            field_separator = '|'
+            while field_separator in self:
+                field_separator += '|'
+            return field_separator
+
+        # not a bool nor a str
+        raise RuntimeError(
+            'invalid input/output separator, must be bool or str but is'
+            f'{field_separator}')
+
+
+default_separator = Separator(phone='', syllable='', word=' ')
+"""The default separation characters for phonemes, syllables and words"""
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/phonemizer/utils.py b/TTS/Kokoro/.venv/Lib/site-packages/phonemizer/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..5d52767f0758933d6e3f6e081a24f85adf1c5f40
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/phonemizer/utils.py
@@ -0,0 +1,131 @@
+# Copyright 2015-2021 Mathieu Bernard
+#
+# This file is part of phonemizer: you can redistribute it and/or
+# modify it under the terms of the GNU General Public License as
+# published by the Free Software Foundation, either version 3 of the
+# License, or (at your option) any later version.
+#
+# Phonemizer is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with phonemizer. If not, see .
+"""Provides utility functions for the phonemizer"""
+
+import os
+from numbers import Number
+from pathlib import Path
+from typing import Union, List, Tuple, Iterable
+
+import importlib
+
+
+def cumsum(iterable: Iterable[Number]) -> List[Number]:
+    """Returns the cumulative sum of the `iterable` as a list"""
+    res = []
+    cumulative = 0
+    for value in iterable:
+        cumulative += value
+        res.append(cumulative)
+    return res
+
+
+def str2list(text: Union[str, List[str]]) -> List[str]:
+    """Returns the string `text` as a list of lines, split by \n"""
+    if isinstance(text, str):
+        return text.strip(os.linesep).split(os.linesep)
+    return text
+
+
+def list2str(text: Union[str, List[str]]) -> str:
+    """Returns the list of lines `text` as a single string separated by \n"""
+    if isinstance(text, str):
+        return text
+    return os.linesep.join(text)
+
+
+def chunks(text: Union[str, List[str]], num: int) \
+        -> Tuple[List[List[str]], List[int]]:
+    """Return a maximum of `num` equally sized chunks of a `text`
+
+    This method is usefull when phonemizing a single text on multiple jobs.
+
+    The exact number of chunks returned is `m = min(num, len(str2list(text)))`.
+    Only the m-1 first chunks have equal size. The last chunk can be longer.
+    The input `text` can be a list or a string. Return a list of `m` strings.
+
+    Parameters
+    ----------
+    text (str or list) : The text to divide in chunks
+
+    num (int) : The number of chunks to build, must be a strictly positive
+    integer.
+
+    Returns
+    -------
+    chunks (list of list of str) : The chunked text with utterances separated
+        by '\n'.
+
+    offsets (list of int) : offset used below to recover the line numbers in
+        the input text wrt the chunks
+
+    """
+    text: List[str] = str2list(text)
+    size = int(max(1, len(text) / num))  # noqa
+    nchunks = min(num, len(text))
+
+    text_chunks = [
+        text[i * size:(i + 1) * size] for i in range(nchunks - 1)]
+
+    last = text[(nchunks - 1) * size:]
+    if last:
+        text_chunks.append(last)
+
+    offsets = [0] + cumsum((len(c) for c in text_chunks[:-1]))
+    return text_chunks, offsets
+
+
+def get_package_resource(path: str) -> Path:
+    """Returns the absolute path to a phonemizer resource file or directory
+
+    The packages resource are stored within the source tree in the
+    'phonemizer/share' directory and, once the package is installed, are moved
+    to another system directory (e.g. /share/phonemizer).
+
+    Parameters
+    ----------
+    path (str) : the file or directory to get, must be relative to
+        'phonemizer/share'.
+
+    Raises
+    ------
+    ValueError if the required `path` is not found
+
+    Returns
+    -------
+    The absolute path to the required resource as a `pathlib.Path`
+
+    """
+    try:
+        # new in python-3.9
+        path = importlib.resources.files('phonemizer') / 'share' / path
+    except AttributeError:  # pragma: nocover
+        with importlib.resources.path('phonemizer', 'share') as share:
+            path = share / path
+
+    if not path.exists():  # pragma: nocover
+        raise ValueError(f'the requested resource does not exist: {path}')
+
+    return path.resolve()
+
+
+def version_as_tuple(version: str) -> Tuple[int, ...]:
+    """Returns a tuple of integers from a version string
+
+    Any '-dev' in version string is ignored. For instance, returns (1, 2, 3)
+    from '1.2.3' or (0, 2) from '0.2-dev'
+
+    """
+    return tuple(int(v) for v in version.replace('-dev', '').split('.'))
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/phonemizer/version.py b/TTS/Kokoro/.venv/Lib/site-packages/phonemizer/version.py
new file mode 100644
index 0000000000000000000000000000000000000000..df0e84435e8b18599a1b6fdac21317029b3417f6
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/phonemizer/version.py
@@ -0,0 +1,67 @@
+# Copyright 2015-2021 Mathieu Bernard
+#
+# This file is part of phonemizer: you can redistribute it and/or
+# modify it under the terms of the GNU General Public License as
+# published by the Free Software Foundation, either version 3 of the
+# License, or (at your option) any later version.
+#
+# Phonemizer is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with phonemizer. If not, see .
+"""Phonemizer version description"""
+
+import importlib
+
+from phonemizer.backend import (
+    EspeakBackend, EspeakMbrolaBackend, FestivalBackend, SegmentsBackend)
+
+
+def _version_as_str(vers):
+    """From (1, 49, 3) to '1.49.3'"""
+    return '.'.join(str(v) for v in vers)
+
+
+def version():
+    """Return version information for front and backends"""
+    # version of the phonemizer
+    _version = 'phonemizer-' + importlib.metadata.version('phonemizer')
+
+    # for each backend, check if it is available or not. If so get its version
+    available = []
+    unavailable = []
+
+    if EspeakBackend.is_available():
+        available.append(
+            'espeak-' + ('ng-' if EspeakBackend.is_espeak_ng() else '')
+            + _version_as_str(EspeakBackend.version()))
+    else:  # pragma: nocover
+        unavailable.append('espeak')
+
+    if EspeakMbrolaBackend.is_available():
+        available.append('espeak-mbrola')
+    else:  # pragma: nocover
+        unavailable.append('espeak-mbrola')
+
+    if FestivalBackend.is_available():
+        available.append(
+            'festival-' + _version_as_str(FestivalBackend.version()))
+    else:  # pragma: nocover
+        unavailable.append('festival')
+
+    if SegmentsBackend.is_available():
+        available.append(
+            'segments-' + _version_as_str(SegmentsBackend.version()))
+    else:  # pragma: nocover
+        unavailable.append('segments')
+
+    # resumes the backends status in the final version string
+    if available:
+        _version += '\navailable backends: ' + ', '.join(available)
+    if unavailable:  # pragma: nocover
+        _version += '\nuninstalled backends: ' + ', '.join(unavailable)
+
+    return _version
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/phonemizer_fork-3.3.2.dist-info/INSTALLER b/TTS/Kokoro/.venv/Lib/site-packages/phonemizer_fork-3.3.2.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/phonemizer_fork-3.3.2.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/phonemizer_fork-3.3.2.dist-info/METADATA b/TTS/Kokoro/.venv/Lib/site-packages/phonemizer_fork-3.3.2.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..24011905ec27199caa9345eaafdf093d938dace6
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/phonemizer_fork-3.3.2.dist-info/METADATA
@@ -0,0 +1,811 @@
+Metadata-Version: 2.4
+Name: phonemizer-fork
+Version: 3.3.2
+Summary: Simple text to phones converter for multiple languages
+Project-URL: Documentation, https://bootphon.github.io/phonemizer/
+Project-URL: Repository, https://github.com/bootphon/phonemizer
+Project-URL: Issues, https://github.com/bootphon/phonemizer
+Project-URL: Changelog, https://github.com/bootphon/phonemizer/blob/master/docs/source/changelog.rst
+Author: Hadrien Titeux
+Author-email: Mathieu Bernard 
+License:                     GNU GENERAL PUBLIC LICENSE
+                               Version 3, 29 June 2007
+        
+         Copyright (C) 2007 Free Software Foundation, Inc. 
+         Everyone is permitted to copy and distribute verbatim copies
+         of this license document, but changing it is not allowed.
+        
+                                    Preamble
+        
+          The GNU General Public License is a free, copyleft license for
+        software and other kinds of works.
+        
+          The licenses for most software and other practical works are designed
+        to take away your freedom to share and change the works.  By contrast,
+        the GNU General Public License is intended to guarantee your freedom to
+        share and change all versions of a program--to make sure it remains free
+        software for all its users.  We, the Free Software Foundation, use the
+        GNU General Public License for most of our software; it applies also to
+        any other work released this way by its authors.  You can apply it to
+        your programs, too.
+        
+          When we speak of free software, we are referring to freedom, not
+        price.  Our General Public Licenses are designed to make sure that you
+        have the freedom to distribute copies of free software (and charge for
+        them if you wish), that you receive source code or can get it if you
+        want it, that you can change the software or use pieces of it in new
+        free programs, and that you know you can do these things.
+        
+          To protect your rights, we need to prevent others from denying you
+        these rights or asking you to surrender the rights.  Therefore, you have
+        certain responsibilities if you distribute copies of the software, or if
+        you modify it: responsibilities to respect the freedom of others.
+        
+          For example, if you distribute copies of such a program, whether
+        gratis or for a fee, you must pass on to the recipients the same
+        freedoms that you received.  You must make sure that they, too, receive
+        or can get the source code.  And you must show them these terms so they
+        know their rights.
+        
+          Developers that use the GNU GPL protect your rights with two steps:
+        (1) assert copyright on the software, and (2) offer you this License
+        giving you legal permission to copy, distribute and/or modify it.
+        
+          For the developers' and authors' protection, the GPL clearly explains
+        that there is no warranty for this free software.  For both users' and
+        authors' sake, the GPL requires that modified versions be marked as
+        changed, so that their problems will not be attributed erroneously to
+        authors of previous versions.
+        
+          Some devices are designed to deny users access to install or run
+        modified versions of the software inside them, although the manufacturer
+        can do so.  This is fundamentally incompatible with the aim of
+        protecting users' freedom to change the software.  The systematic
+        pattern of such abuse occurs in the area of products for individuals to
+        use, which is precisely where it is most unacceptable.  Therefore, we
+        have designed this version of the GPL to prohibit the practice for those
+        products.  If such problems arise substantially in other domains, we
+        stand ready to extend this provision to those domains in future versions
+        of the GPL, as needed to protect the freedom of users.
+        
+          Finally, every program is threatened constantly by software patents.
+        States should not allow patents to restrict development and use of
+        software on general-purpose computers, but in those that do, we wish to
+        avoid the special danger that patents applied to a free program could
+        make it effectively proprietary.  To prevent this, the GPL assures that
+        patents cannot be used to render the program non-free.
+        
+          The precise terms and conditions for copying, distribution and
+        modification follow.
+        
+                               TERMS AND CONDITIONS
+        
+          0. Definitions.
+        
+          "This License" refers to version 3 of the GNU General Public License.
+        
+          "Copyright" also means copyright-like laws that apply to other kinds of
+        works, such as semiconductor masks.
+        
+          "The Program" refers to any copyrightable work licensed under this
+        License.  Each licensee is addressed as "you".  "Licensees" and
+        "recipients" may be individuals or organizations.
+        
+          To "modify" a work means to copy from or adapt all or part of the work
+        in a fashion requiring copyright permission, other than the making of an
+        exact copy.  The resulting work is called a "modified version" of the
+        earlier work or a work "based on" the earlier work.
+        
+          A "covered work" means either the unmodified Program or a work based
+        on the Program.
+        
+          To "propagate" a work means to do anything with it that, without
+        permission, would make you directly or secondarily liable for
+        infringement under applicable copyright law, except executing it on a
+        computer or modifying a private copy.  Propagation includes copying,
+        distribution (with or without modification), making available to the
+        public, and in some countries other activities as well.
+        
+          To "convey" a work means any kind of propagation that enables other
+        parties to make or receive copies.  Mere interaction with a user through
+        a computer network, with no transfer of a copy, is not conveying.
+        
+          An interactive user interface displays "Appropriate Legal Notices"
+        to the extent that it includes a convenient and prominently visible
+        feature that (1) displays an appropriate copyright notice, and (2)
+        tells the user that there is no warranty for the work (except to the
+        extent that warranties are provided), that licensees may convey the
+        work under this License, and how to view a copy of this License.  If
+        the interface presents a list of user commands or options, such as a
+        menu, a prominent item in the list meets this criterion.
+        
+          1. Source Code.
+        
+          The "source code" for a work means the preferred form of the work
+        for making modifications to it.  "Object code" means any non-source
+        form of a work.
+        
+          A "Standard Interface" means an interface that either is an official
+        standard defined by a recognized standards body, or, in the case of
+        interfaces specified for a particular programming language, one that
+        is widely used among developers working in that language.
+        
+          The "System Libraries" of an executable work include anything, other
+        than the work as a whole, that (a) is included in the normal form of
+        packaging a Major Component, but which is not part of that Major
+        Component, and (b) serves only to enable use of the work with that
+        Major Component, or to implement a Standard Interface for which an
+        implementation is available to the public in source code form.  A
+        "Major Component", in this context, means a major essential component
+        (kernel, window system, and so on) of the specific operating system
+        (if any) on which the executable work runs, or a compiler used to
+        produce the work, or an object code interpreter used to run it.
+        
+          The "Corresponding Source" for a work in object code form means all
+        the source code needed to generate, install, and (for an executable
+        work) run the object code and to modify the work, including scripts to
+        control those activities.  However, it does not include the work's
+        System Libraries, or general-purpose tools or generally available free
+        programs which are used unmodified in performing those activities but
+        which are not part of the work.  For example, Corresponding Source
+        includes interface definition files associated with source files for
+        the work, and the source code for shared libraries and dynamically
+        linked subprograms that the work is specifically designed to require,
+        such as by intimate data communication or control flow between those
+        subprograms and other parts of the work.
+        
+          The Corresponding Source need not include anything that users
+        can regenerate automatically from other parts of the Corresponding
+        Source.
+        
+          The Corresponding Source for a work in source code form is that
+        same work.
+        
+          2. Basic Permissions.
+        
+          All rights granted under this License are granted for the term of
+        copyright on the Program, and are irrevocable provided the stated
+        conditions are met.  This License explicitly affirms your unlimited
+        permission to run the unmodified Program.  The output from running a
+        covered work is covered by this License only if the output, given its
+        content, constitutes a covered work.  This License acknowledges your
+        rights of fair use or other equivalent, as provided by copyright law.
+        
+          You may make, run and propagate covered works that you do not
+        convey, without conditions so long as your license otherwise remains
+        in force.  You may convey covered works to others for the sole purpose
+        of having them make modifications exclusively for you, or provide you
+        with facilities for running those works, provided that you comply with
+        the terms of this License in conveying all material for which you do
+        not control copyright.  Those thus making or running the covered works
+        for you must do so exclusively on your behalf, under your direction
+        and control, on terms that prohibit them from making any copies of
+        your copyrighted material outside their relationship with you.
+        
+          Conveying under any other circumstances is permitted solely under
+        the conditions stated below.  Sublicensing is not allowed; section 10
+        makes it unnecessary.
+        
+          3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+        
+          No covered work shall be deemed part of an effective technological
+        measure under any applicable law fulfilling obligations under article
+        11 of the WIPO copyright treaty adopted on 20 December 1996, or
+        similar laws prohibiting or restricting circumvention of such
+        measures.
+        
+          When you convey a covered work, you waive any legal power to forbid
+        circumvention of technological measures to the extent such circumvention
+        is effected by exercising rights under this License with respect to
+        the covered work, and you disclaim any intention to limit operation or
+        modification of the work as a means of enforcing, against the work's
+        users, your or third parties' legal rights to forbid circumvention of
+        technological measures.
+        
+          4. Conveying Verbatim Copies.
+        
+          You may convey verbatim copies of the Program's source code as you
+        receive it, in any medium, provided that you conspicuously and
+        appropriately publish on each copy an appropriate copyright notice;
+        keep intact all notices stating that this License and any
+        non-permissive terms added in accord with section 7 apply to the code;
+        keep intact all notices of the absence of any warranty; and give all
+        recipients a copy of this License along with the Program.
+        
+          You may charge any price or no price for each copy that you convey,
+        and you may offer support or warranty protection for a fee.
+        
+          5. Conveying Modified Source Versions.
+        
+          You may convey a work based on the Program, or the modifications to
+        produce it from the Program, in the form of source code under the
+        terms of section 4, provided that you also meet all of these conditions:
+        
+            a) The work must carry prominent notices stating that you modified
+            it, and giving a relevant date.
+        
+            b) The work must carry prominent notices stating that it is
+            released under this License and any conditions added under section
+            7.  This requirement modifies the requirement in section 4 to
+            "keep intact all notices".
+        
+            c) You must license the entire work, as a whole, under this
+            License to anyone who comes into possession of a copy.  This
+            License will therefore apply, along with any applicable section 7
+            additional terms, to the whole of the work, and all its parts,
+            regardless of how they are packaged.  This License gives no
+            permission to license the work in any other way, but it does not
+            invalidate such permission if you have separately received it.
+        
+            d) If the work has interactive user interfaces, each must display
+            Appropriate Legal Notices; however, if the Program has interactive
+            interfaces that do not display Appropriate Legal Notices, your
+            work need not make them do so.
+        
+          A compilation of a covered work with other separate and independent
+        works, which are not by their nature extensions of the covered work,
+        and which are not combined with it such as to form a larger program,
+        in or on a volume of a storage or distribution medium, is called an
+        "aggregate" if the compilation and its resulting copyright are not
+        used to limit the access or legal rights of the compilation's users
+        beyond what the individual works permit.  Inclusion of a covered work
+        in an aggregate does not cause this License to apply to the other
+        parts of the aggregate.
+        
+          6. Conveying Non-Source Forms.
+        
+          You may convey a covered work in object code form under the terms
+        of sections 4 and 5, provided that you also convey the
+        machine-readable Corresponding Source under the terms of this License,
+        in one of these ways:
+        
+            a) Convey the object code in, or embodied in, a physical product
+            (including a physical distribution medium), accompanied by the
+            Corresponding Source fixed on a durable physical medium
+            customarily used for software interchange.
+        
+            b) Convey the object code in, or embodied in, a physical product
+            (including a physical distribution medium), accompanied by a
+            written offer, valid for at least three years and valid for as
+            long as you offer spare parts or customer support for that product
+            model, to give anyone who possesses the object code either (1) a
+            copy of the Corresponding Source for all the software in the
+            product that is covered by this License, on a durable physical
+            medium customarily used for software interchange, for a price no
+            more than your reasonable cost of physically performing this
+            conveying of source, or (2) access to copy the
+            Corresponding Source from a network server at no charge.
+        
+            c) Convey individual copies of the object code with a copy of the
+            written offer to provide the Corresponding Source.  This
+            alternative is allowed only occasionally and noncommercially, and
+            only if you received the object code with such an offer, in accord
+            with subsection 6b.
+        
+            d) Convey the object code by offering access from a designated
+            place (gratis or for a charge), and offer equivalent access to the
+            Corresponding Source in the same way through the same place at no
+            further charge.  You need not require recipients to copy the
+            Corresponding Source along with the object code.  If the place to
+            copy the object code is a network server, the Corresponding Source
+            may be on a different server (operated by you or a third party)
+            that supports equivalent copying facilities, provided you maintain
+            clear directions next to the object code saying where to find the
+            Corresponding Source.  Regardless of what server hosts the
+            Corresponding Source, you remain obligated to ensure that it is
+            available for as long as needed to satisfy these requirements.
+        
+            e) Convey the object code using peer-to-peer transmission, provided
+            you inform other peers where the object code and Corresponding
+            Source of the work are being offered to the general public at no
+            charge under subsection 6d.
+        
+          A separable portion of the object code, whose source code is excluded
+        from the Corresponding Source as a System Library, need not be
+        included in conveying the object code work.
+        
+          A "User Product" is either (1) a "consumer product", which means any
+        tangible personal property which is normally used for personal, family,
+        or household purposes, or (2) anything designed or sold for incorporation
+        into a dwelling.  In determining whether a product is a consumer product,
+        doubtful cases shall be resolved in favor of coverage.  For a particular
+        product received by a particular user, "normally used" refers to a
+        typical or common use of that class of product, regardless of the status
+        of the particular user or of the way in which the particular user
+        actually uses, or expects or is expected to use, the product.  A product
+        is a consumer product regardless of whether the product has substantial
+        commercial, industrial or non-consumer uses, unless such uses represent
+        the only significant mode of use of the product.
+        
+          "Installation Information" for a User Product means any methods,
+        procedures, authorization keys, or other information required to install
+        and execute modified versions of a covered work in that User Product from
+        a modified version of its Corresponding Source.  The information must
+        suffice to ensure that the continued functioning of the modified object
+        code is in no case prevented or interfered with solely because
+        modification has been made.
+        
+          If you convey an object code work under this section in, or with, or
+        specifically for use in, a User Product, and the conveying occurs as
+        part of a transaction in which the right of possession and use of the
+        User Product is transferred to the recipient in perpetuity or for a
+        fixed term (regardless of how the transaction is characterized), the
+        Corresponding Source conveyed under this section must be accompanied
+        by the Installation Information.  But this requirement does not apply
+        if neither you nor any third party retains the ability to install
+        modified object code on the User Product (for example, the work has
+        been installed in ROM).
+        
+          The requirement to provide Installation Information does not include a
+        requirement to continue to provide support service, warranty, or updates
+        for a work that has been modified or installed by the recipient, or for
+        the User Product in which it has been modified or installed.  Access to a
+        network may be denied when the modification itself materially and
+        adversely affects the operation of the network or violates the rules and
+        protocols for communication across the network.
+        
+          Corresponding Source conveyed, and Installation Information provided,
+        in accord with this section must be in a format that is publicly
+        documented (and with an implementation available to the public in
+        source code form), and must require no special password or key for
+        unpacking, reading or copying.
+        
+          7. Additional Terms.
+        
+          "Additional permissions" are terms that supplement the terms of this
+        License by making exceptions from one or more of its conditions.
+        Additional permissions that are applicable to the entire Program shall
+        be treated as though they were included in this License, to the extent
+        that they are valid under applicable law.  If additional permissions
+        apply only to part of the Program, that part may be used separately
+        under those permissions, but the entire Program remains governed by
+        this License without regard to the additional permissions.
+        
+          When you convey a copy of a covered work, you may at your option
+        remove any additional permissions from that copy, or from any part of
+        it.  (Additional permissions may be written to require their own
+        removal in certain cases when you modify the work.)  You may place
+        additional permissions on material, added by you to a covered work,
+        for which you have or can give appropriate copyright permission.
+        
+          Notwithstanding any other provision of this License, for material you
+        add to a covered work, you may (if authorized by the copyright holders of
+        that material) supplement the terms of this License with terms:
+        
+            a) Disclaiming warranty or limiting liability differently from the
+            terms of sections 15 and 16 of this License; or
+        
+            b) Requiring preservation of specified reasonable legal notices or
+            author attributions in that material or in the Appropriate Legal
+            Notices displayed by works containing it; or
+        
+            c) Prohibiting misrepresentation of the origin of that material, or
+            requiring that modified versions of such material be marked in
+            reasonable ways as different from the original version; or
+        
+            d) Limiting the use for publicity purposes of names of licensors or
+            authors of the material; or
+        
+            e) Declining to grant rights under trademark law for use of some
+            trade names, trademarks, or service marks; or
+        
+            f) Requiring indemnification of licensors and authors of that
+            material by anyone who conveys the material (or modified versions of
+            it) with contractual assumptions of liability to the recipient, for
+            any liability that these contractual assumptions directly impose on
+            those licensors and authors.
+        
+          All other non-permissive additional terms are considered "further
+        restrictions" within the meaning of section 10.  If the Program as you
+        received it, or any part of it, contains a notice stating that it is
+        governed by this License along with a term that is a further
+        restriction, you may remove that term.  If a license document contains
+        a further restriction but permits relicensing or conveying under this
+        License, you may add to a covered work material governed by the terms
+        of that license document, provided that the further restriction does
+        not survive such relicensing or conveying.
+        
+          If you add terms to a covered work in accord with this section, you
+        must place, in the relevant source files, a statement of the
+        additional terms that apply to those files, or a notice indicating
+        where to find the applicable terms.
+        
+          Additional terms, permissive or non-permissive, may be stated in the
+        form of a separately written license, or stated as exceptions;
+        the above requirements apply either way.
+        
+          8. Termination.
+        
+          You may not propagate or modify a covered work except as expressly
+        provided under this License.  Any attempt otherwise to propagate or
+        modify it is void, and will automatically terminate your rights under
+        this License (including any patent licenses granted under the third
+        paragraph of section 11).
+        
+          However, if you cease all violation of this License, then your
+        license from a particular copyright holder is reinstated (a)
+        provisionally, unless and until the copyright holder explicitly and
+        finally terminates your license, and (b) permanently, if the copyright
+        holder fails to notify you of the violation by some reasonable means
+        prior to 60 days after the cessation.
+        
+          Moreover, your license from a particular copyright holder is
+        reinstated permanently if the copyright holder notifies you of the
+        violation by some reasonable means, this is the first time you have
+        received notice of violation of this License (for any work) from that
+        copyright holder, and you cure the violation prior to 30 days after
+        your receipt of the notice.
+        
+          Termination of your rights under this section does not terminate the
+        licenses of parties who have received copies or rights from you under
+        this License.  If your rights have been terminated and not permanently
+        reinstated, you do not qualify to receive new licenses for the same
+        material under section 10.
+        
+          9. Acceptance Not Required for Having Copies.
+        
+          You are not required to accept this License in order to receive or
+        run a copy of the Program.  Ancillary propagation of a covered work
+        occurring solely as a consequence of using peer-to-peer transmission
+        to receive a copy likewise does not require acceptance.  However,
+        nothing other than this License grants you permission to propagate or
+        modify any covered work.  These actions infringe copyright if you do
+        not accept this License.  Therefore, by modifying or propagating a
+        covered work, you indicate your acceptance of this License to do so.
+        
+          10. Automatic Licensing of Downstream Recipients.
+        
+          Each time you convey a covered work, the recipient automatically
+        receives a license from the original licensors, to run, modify and
+        propagate that work, subject to this License.  You are not responsible
+        for enforcing compliance by third parties with this License.
+        
+          An "entity transaction" is a transaction transferring control of an
+        organization, or substantially all assets of one, or subdividing an
+        organization, or merging organizations.  If propagation of a covered
+        work results from an entity transaction, each party to that
+        transaction who receives a copy of the work also receives whatever
+        licenses to the work the party's predecessor in interest had or could
+        give under the previous paragraph, plus a right to possession of the
+        Corresponding Source of the work from the predecessor in interest, if
+        the predecessor has it or can get it with reasonable efforts.
+        
+          You may not impose any further restrictions on the exercise of the
+        rights granted or affirmed under this License.  For example, you may
+        not impose a license fee, royalty, or other charge for exercise of
+        rights granted under this License, and you may not initiate litigation
+        (including a cross-claim or counterclaim in a lawsuit) alleging that
+        any patent claim is infringed by making, using, selling, offering for
+        sale, or importing the Program or any portion of it.
+        
+          11. Patents.
+        
+          A "contributor" is a copyright holder who authorizes use under this
+        License of the Program or a work on which the Program is based.  The
+        work thus licensed is called the contributor's "contributor version".
+        
+          A contributor's "essential patent claims" are all patent claims
+        owned or controlled by the contributor, whether already acquired or
+        hereafter acquired, that would be infringed by some manner, permitted
+        by this License, of making, using, or selling its contributor version,
+        but do not include claims that would be infringed only as a
+        consequence of further modification of the contributor version.  For
+        purposes of this definition, "control" includes the right to grant
+        patent sublicenses in a manner consistent with the requirements of
+        this License.
+        
+          Each contributor grants you a non-exclusive, worldwide, royalty-free
+        patent license under the contributor's essential patent claims, to
+        make, use, sell, offer for sale, import and otherwise run, modify and
+        propagate the contents of its contributor version.
+        
+          In the following three paragraphs, a "patent license" is any express
+        agreement or commitment, however denominated, not to enforce a patent
+        (such as an express permission to practice a patent or covenant not to
+        sue for patent infringement).  To "grant" such a patent license to a
+        party means to make such an agreement or commitment not to enforce a
+        patent against the party.
+        
+          If you convey a covered work, knowingly relying on a patent license,
+        and the Corresponding Source of the work is not available for anyone
+        to copy, free of charge and under the terms of this License, through a
+        publicly available network server or other readily accessible means,
+        then you must either (1) cause the Corresponding Source to be so
+        available, or (2) arrange to deprive yourself of the benefit of the
+        patent license for this particular work, or (3) arrange, in a manner
+        consistent with the requirements of this License, to extend the patent
+        license to downstream recipients.  "Knowingly relying" means you have
+        actual knowledge that, but for the patent license, your conveying the
+        covered work in a country, or your recipient's use of the covered work
+        in a country, would infringe one or more identifiable patents in that
+        country that you have reason to believe are valid.
+        
+          If, pursuant to or in connection with a single transaction or
+        arrangement, you convey, or propagate by procuring conveyance of, a
+        covered work, and grant a patent license to some of the parties
+        receiving the covered work authorizing them to use, propagate, modify
+        or convey a specific copy of the covered work, then the patent license
+        you grant is automatically extended to all recipients of the covered
+        work and works based on it.
+        
+          A patent license is "discriminatory" if it does not include within
+        the scope of its coverage, prohibits the exercise of, or is
+        conditioned on the non-exercise of one or more of the rights that are
+        specifically granted under this License.  You may not convey a covered
+        work if you are a party to an arrangement with a third party that is
+        in the business of distributing software, under which you make payment
+        to the third party based on the extent of your activity of conveying
+        the work, and under which the third party grants, to any of the
+        parties who would receive the covered work from you, a discriminatory
+        patent license (a) in connection with copies of the covered work
+        conveyed by you (or copies made from those copies), or (b) primarily
+        for and in connection with specific products or compilations that
+        contain the covered work, unless you entered into that arrangement,
+        or that patent license was granted, prior to 28 March 2007.
+        
+          Nothing in this License shall be construed as excluding or limiting
+        any implied license or other defenses to infringement that may
+        otherwise be available to you under applicable patent law.
+        
+          12. No Surrender of Others' Freedom.
+        
+          If conditions are imposed on you (whether by court order, agreement or
+        otherwise) that contradict the conditions of this License, they do not
+        excuse you from the conditions of this License.  If you cannot convey a
+        covered work so as to satisfy simultaneously your obligations under this
+        License and any other pertinent obligations, then as a consequence you may
+        not convey it at all.  For example, if you agree to terms that obligate you
+        to collect a royalty for further conveying from those to whom you convey
+        the Program, the only way you could satisfy both those terms and this
+        License would be to refrain entirely from conveying the Program.
+        
+          13. Use with the GNU Affero General Public License.
+        
+          Notwithstanding any other provision of this License, you have
+        permission to link or combine any covered work with a work licensed
+        under version 3 of the GNU Affero General Public License into a single
+        combined work, and to convey the resulting work.  The terms of this
+        License will continue to apply to the part which is the covered work,
+        but the special requirements of the GNU Affero General Public License,
+        section 13, concerning interaction through a network will apply to the
+        combination as such.
+        
+          14. Revised Versions of this License.
+        
+          The Free Software Foundation may publish revised and/or new versions of
+        the GNU General Public License from time to time.  Such new versions will
+        be similar in spirit to the present version, but may differ in detail to
+        address new problems or concerns.
+        
+          Each version is given a distinguishing version number.  If the
+        Program specifies that a certain numbered version of the GNU General
+        Public License "or any later version" applies to it, you have the
+        option of following the terms and conditions either of that numbered
+        version or of any later version published by the Free Software
+        Foundation.  If the Program does not specify a version number of the
+        GNU General Public License, you may choose any version ever published
+        by the Free Software Foundation.
+        
+          If the Program specifies that a proxy can decide which future
+        versions of the GNU General Public License can be used, that proxy's
+        public statement of acceptance of a version permanently authorizes you
+        to choose that version for the Program.
+        
+          Later license versions may give you additional or different
+        permissions.  However, no additional obligations are imposed on any
+        author or copyright holder as a result of your choosing to follow a
+        later version.
+        
+          15. Disclaimer of Warranty.
+        
+          THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+        APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+        HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+        OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+        THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+        PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+        IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+        ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+        
+          16. Limitation of Liability.
+        
+          IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+        WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+        THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+        GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+        USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+        DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+        PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+        EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+        SUCH DAMAGES.
+        
+          17. Interpretation of Sections 15 and 16.
+        
+          If the disclaimer of warranty and limitation of liability provided
+        above cannot be given local legal effect according to their terms,
+        reviewing courts shall apply local law that most closely approximates
+        an absolute waiver of all civil liability in connection with the
+        Program, unless a warranty or assumption of liability accompanies a
+        copy of the Program in return for a fee.
+        
+                             END OF TERMS AND CONDITIONS
+        
+                    How to Apply These Terms to Your New Programs
+        
+          If you develop a new program, and you want it to be of the greatest
+        possible use to the public, the best way to achieve this is to make it
+        free software which everyone can redistribute and change under these terms.
+        
+          To do so, attach the following notices to the program.  It is safest
+        to attach them to the start of each source file to most effectively
+        state the exclusion of warranty; and each file should have at least
+        the "copyright" line and a pointer to where the full notice is found.
+        
+            {one line to give the program's name and a brief idea of what it does.}
+            Copyright (C) {year}  {name of author}
+        
+            This program is free software: you can redistribute it and/or modify
+            it under the terms of the GNU General Public License as published by
+            the Free Software Foundation, either version 3 of the License, or
+            (at your option) any later version.
+        
+            This program is distributed in the hope that it will be useful,
+            but WITHOUT ANY WARRANTY; without even the implied warranty of
+            MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+            GNU General Public License for more details.
+        
+            You should have received a copy of the GNU General Public License
+            along with this program.  If not, see .
+        
+        Also add information on how to contact you by electronic and paper mail.
+        
+          If the program does terminal interaction, make it output a short
+        notice like this when it starts in an interactive mode:
+        
+            {project}  Copyright (C) {year}  {fullname}
+            This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+            This is free software, and you are welcome to redistribute it
+            under certain conditions; type `show c' for details.
+        
+        The hypothetical commands `show w' and `show c' should show the appropriate
+        parts of the General Public License.  Of course, your program's commands
+        might be different; for a GUI interface, you would use an "about box".
+        
+          You should also get your employer (if you work as a programmer) or school,
+        if any, to sign a "copyright disclaimer" for the program, if necessary.
+        For more information on this, and how to apply and follow the GNU GPL, see
+        .
+        
+          The GNU General Public License does not permit incorporating your program
+        into proprietary programs.  If your program is a subroutine library, you
+        may consider it more useful to permit linking proprietary applications with
+        the library.  If this is what you want to do, use the GNU Lesser General
+        Public License instead of this License.  But first, please read
+        .
+        
+License-File: LICENSE
+Keywords: G2P,TTS,espeak,festival,linguistics,phone
+Classifier: License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)
+Classifier: Operating System :: OS Independent
+Classifier: Programming Language :: Python :: 3
+Requires-Python: >=3.8
+Requires-Dist: attrs>=18.1
+Requires-Dist: dlinfo
+Requires-Dist: joblib
+Requires-Dist: segments
+Requires-Dist: typing-extensions
+Provides-Extra: doc
+Requires-Dist: sphinx; extra == 'doc'
+Requires-Dist: sphinx-rtd-theme; extra == 'doc'
+Provides-Extra: test
+Requires-Dist: coverage[toml]; extra == 'test'
+Requires-Dist: pytest-cov; extra == 'test'
+Requires-Dist: pytest>=6.0; extra == 'test'
+Description-Content-Type: text/markdown
+
+|         **Tests** | [![Linux][badge-test-linux]](https://github.com/bootphon/phonemizer/actions/workflows/linux.yaml) [![MacOS][badge-test-macos]](https://github.com/bootphon/phonemizer/actions/workflows/macos.yaml) [![Windows][badge-test-windows]](https://github.com/bootphon/phonemizer/actions/workflows/windows.yaml) [![Codecov][badge-codecov]](https://codecov.io/gh/bootphon/phonemizer) |
+|------------------:| --- |
+| **Documentation** | [![Doc](https://github.com/bootphon/phonemizer/actions/workflows/doc.yaml/badge.svg)](https://bootphon.github.io/phonemizer/) |
+|       **Release** | [![GitHub release (latest SemVer)][badge-github-version]](https://github.com/bootphon/phonemizer/releases/latest) [![PyPI][badge-pypi-version]](https://pypi.python.org/pypi/phonemizer) [![downloads][badge-pypi-downloads]](https://pypi.python.org/pypi/phonemizer) |
+|      **Citation** | [![status][badge-joss]](https://joss.theoj.org/papers/08d1ffc14f233f56942f78f3742b266e) [![DOI][badge-zenodo]](https://doi.org/10.5281/zenodo.1045825) |
+
+---
+
+# Phonemizer -- *foʊnmaɪzɚ*
+
+* The phonemizer allows simple phonemization of words and texts in many languages.
+
+* Provides both the `phonemize` command-line tool and the Python function
+  `phonemizer.phonemize`. See [the package's documentation](https://bootphon.github.io/phonemizer/).
+
+* It is based on four backends: **espeak**, **espeak-mbrola**, **festival** and
+  **segments**. The backends have different properties and capabilities resumed
+  in table below. The backend choice is let to the user.
+
+  * [espeak-ng](https://github.com/espeak-ng/espeak-ng) is a Text-to-Speech
+    software supporting a lot of languages and IPA (International Phonetic
+    Alphabet) output.
+
+  * [espeak-ng-mbrola](https://github.com/espeak-ng/espeak-ng/blob/master/docs/mbrola.md)
+    uses the SAMPA phonetic alphabet instead of IPA but does not preserve word
+    boundaries.
+
+  * [festival](http://www.cstr.ed.ac.uk/projects/festival) is another
+    Tex-to-Speech engine. Its phonemizer backend currently supports only
+    American English. It uses a [custom phoneset][festival-phoneset], but it
+    allows tokenization at the syllable level.
+
+  * [segments](https://github.com/cldf/segments) is a Unicode tokenizer that
+    build a phonemization from a grapheme to phoneme mapping provided as a file
+    by the user.
+
+  |                              | espeak                   | espeak-mbrola           | festival                    | segments           |
+  | ---:                         | ---                      | ---                     | ---                         | ---                |
+  | **phone set**                | [IPA]                    | [SAMPA]                 | [custom][festival-phoneset] | user defined       |
+  | **supported languages**      | [100+][espeak-languages] | [35][mbrola-languages] | US English                  | user defined       |
+  | **processing speed**         | fast                     | slow                    | very slow                   | fast               |
+  | **phone tokens**             | :heavy_check_mark:       | :heavy_check_mark:      | :heavy_check_mark:          | :heavy_check_mark: |
+  | **syllable tokens**          | :x:                      | :x:                     | :heavy_check_mark:          | :x:                |
+  | **word tokens**              | :heavy_check_mark:       | :x:                     | :heavy_check_mark:          | :heavy_check_mark: |
+  | **punctuation preservation** | :heavy_check_mark:       | :x:                     | :heavy_check_mark:          | :heavy_check_mark: |
+  | **stressed phones**          | :heavy_check_mark:       | :x:                     | :x:                         | :x:                |
+  | [**tie**][tie-IPA]           | :heavy_check_mark:       | :x:                     | :x:                         | :x:                |
+
+
+
+## Citation
+
+To refenrece the `phonemizer` in your own work, please cite the following [JOSS
+paper](https://joss.theoj.org/papers/10.21105/joss.03958).
+
+```bibtex
+@article{Bernard2021,
+  doi = {10.21105/joss.03958},
+  url = {https://doi.org/10.21105/joss.03958},
+  year = {2021},
+  publisher = {The Open Journal},
+  volume = {6},
+  number = {68},
+  pages = {3958},
+  author = {Mathieu Bernard and Hadrien Titeux},
+  title = {Phonemizer: Text to Phones Transcription for Multiple Languages in Python},
+  journal = {Journal of Open Source Software}
+}
+```
+
+
+## Licence
+
+**Copyright 2015-2021 Mathieu Bernard**
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see .
+
+
+[badge-test-linux]: https://github.com/bootphon/phonemizer/actions/workflows/linux.yaml/badge.svg?branch=master
+[badge-test-macos]: https://github.com/bootphon/phonemizer/actions/workflows/macos.yaml/badge.svg?branch=master
+[badge-test-windows]: https://github.com/bootphon/phonemizer/actions/workflows/windows.yaml/badge.svg?branch=master
+[badge-codecov]: https://img.shields.io/codecov/c/github/bootphon/phonemizer
+[badge-github-version]: https://img.shields.io/github/v/release/bootphon/phonemizer
+[badge-pypi-version]: https://img.shields.io/pypi/v/phonemizer
+[badge-pypi-downloads]: https://img.shields.io/pypi/dm/phonemizer
+[badge-joss]: https://joss.theoj.org/papers/08d1ffc14f233f56942f78f3742b266e/status.svg
+[badge-zenodo]: https://zenodo.org/badge/56728069.svg
+[phonemizer-1.0]: https://github.com/bootphon/phonemizer/releases/tag/v1.0
+[festival-phoneset]: http://www.festvox.org/bsv/c4711.html
+[IPA]: https://en.wikipedia.org/wiki/International_Phonetic_Alphabet
+[SAMPA]: https://en.wikipedia.org/wiki/SAMPA
+[phonemize-function]: https://github.com/bootphon/phonemizer/blob/c5e2f3878d6db391ec7253173f44e4a85cfe41e3/phonemizer/phonemize.py#L33-L156
+[tie-IPA]: https://en.wikipedia.org/wiki/Tie_(typography)#International_Phonetic_Alphabet
+[espeak-languages]: https://github.com/espeak-ng/espeak-ng/blob/master/docs/languages.md
+[mbrola-languages]: https://github.com/numediart/MBROLA-voices
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/phonemizer_fork-3.3.2.dist-info/RECORD b/TTS/Kokoro/.venv/Lib/site-packages/phonemizer_fork-3.3.2.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..d7cbfa43814e53675d5e9ea5d9ba2916fcaa5412
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/phonemizer_fork-3.3.2.dist-info/RECORD
@@ -0,0 +1,60 @@
+../../Scripts/phonemize.exe,sha256=9Sw22gHFD8AFvPWwbkeDIirZDlgBEDXS9J-d3mJLljw,108378
+phonemizer/__init__.py,sha256=K2fCZm3vSvD3EMofh-EfbQwHJtwWHBv3vogMIjk_uSU,900
+phonemizer/__pycache__/__init__.cpython-312.pyc,,
+phonemizer/__pycache__/logger.cpython-312.pyc,,
+phonemizer/__pycache__/main.cpython-312.pyc,,
+phonemizer/__pycache__/phonemize.cpython-312.pyc,,
+phonemizer/__pycache__/punctuation.cpython-312.pyc,,
+phonemizer/__pycache__/separator.cpython-312.pyc,,
+phonemizer/__pycache__/utils.cpython-312.pyc,,
+phonemizer/__pycache__/version.cpython-312.pyc,,
+phonemizer/backend/__init__.py,sha256=i4USZR7DxTaAul6BJzK4tcLH7hEEdCXI4J-ZwD3LFeA,1112
+phonemizer/backend/__pycache__/__init__.cpython-312.pyc,,
+phonemizer/backend/__pycache__/base.cpython-312.pyc,,
+phonemizer/backend/__pycache__/segments.cpython-312.pyc,,
+phonemizer/backend/base.py,sha256=d6kD6VAIZjFDw03RMcnd2M1kbXbmZ1M9-qFMzVo2vq0,9185
+phonemizer/backend/espeak/__init__.py,sha256=yvURen0id8uQ5i3mGhPDbB22euPyjrYppQqnnXXMYGI,735
+phonemizer/backend/espeak/__pycache__/__init__.cpython-312.pyc,,
+phonemizer/backend/espeak/__pycache__/api.cpython-312.pyc,,
+phonemizer/backend/espeak/__pycache__/base.cpython-312.pyc,,
+phonemizer/backend/espeak/__pycache__/espeak.cpython-312.pyc,,
+phonemizer/backend/espeak/__pycache__/language_switch.cpython-312.pyc,,
+phonemizer/backend/espeak/__pycache__/mbrola.cpython-312.pyc,,
+phonemizer/backend/espeak/__pycache__/voice.cpython-312.pyc,,
+phonemizer/backend/espeak/__pycache__/words_mismatch.cpython-312.pyc,,
+phonemizer/backend/espeak/__pycache__/wrapper.cpython-312.pyc,,
+phonemizer/backend/espeak/api.py,sha256=4PuHdemxo10DBoaVS4YPHsc2fULqgpOd8CbmfRRNO_g,9995
+phonemizer/backend/espeak/base.py,sha256=EpgtJumAIsn86rU7O7NDN9kqph7T9Imh2yunan-KXYo,3746
+phonemizer/backend/espeak/espeak.py,sha256=Gc6Rn5XmC4-o5rZ79LJ9N1RJ44G-UUBrn_18BJcND00,6680
+phonemizer/backend/espeak/language_switch.py,sha256=1EdYpWOFwU2slUVg3QROYbcMoMMj7f83hQoBUdICcno,6929
+phonemizer/backend/espeak/mbrola.py,sha256=C62MllV9AdgKoQnU09_CrD0BO-Tm6wvnumwk92moNUs,4147
+phonemizer/backend/espeak/voice.py,sha256=rRdQiLWoQG4QxYq68L6Vaq2Xa9sft1TuTSZQ1-EskKg,2982
+phonemizer/backend/espeak/words_mismatch.py,sha256=qVZlQC-rOUbO635qrc7ctXHHFTOCQayG7h9kUEstGVg,5122
+phonemizer/backend/espeak/wrapper.py,sha256=o34nAZOeqdh0TgAzJ8RqW9_du9xHzXduGHoxvVSgAhw,15201
+phonemizer/backend/festival/__init__.py,sha256=nHDtSzmHeKbrKEU2mDePVX5LHgBC09qRsLliLpzg8sY,737
+phonemizer/backend/festival/__pycache__/__init__.cpython-312.pyc,,
+phonemizer/backend/festival/__pycache__/festival.cpython-312.pyc,,
+phonemizer/backend/festival/__pycache__/lispy.cpython-312.pyc,,
+phonemizer/backend/festival/festival.py,sha256=7Vgv5O6jWw0beZYiadRSnxEiCjqB41UJYoQyLcJKsbs,12303
+phonemizer/backend/festival/lispy.py,sha256=xipPoFB-EyFWDznb9AWQcMpYzhGbFJdgZ4EfnzSg9kI,1972
+phonemizer/backend/segments.py,sha256=6Sga-tIkMRv5RmhdQTzDMoKyyZzK_6D5OkXv8ZkD9yI,5404
+phonemizer/logger.py,sha256=F9IFuMIagEp0wYn3jUF0MOae14bk4l5R0ErFiPbYqjQ,2141
+phonemizer/main.py,sha256=O1RUWNXauW4JMVx8jHI4CQIBeExu3sjiO0Mzia13UyA,15824
+phonemizer/phonemize.py,sha256=VwJnq_qkxD7H2G8x98Kx2n1Ub1Q_gdfojhXzdh0bStE,13492
+phonemizer/punctuation.py,sha256=6Ph8j03KxOJM8iQ-vVFpjqU9TCrCyioGAyTm9vhOw3Q,8764
+phonemizer/separator.py,sha256=mbSsXlN8qnxDFyp8waZsnuP8ANuP86a3dj_MkGdF3-E,4151
+phonemizer/share/festival/phonemize.scm,sha256=Aj0Oy_kyKF7rQEoVu-H0pPzw4UWNwT1Syu8O6As2VH8,1378
+phonemizer/share/segments/chintang.g2p,sha256=4efV_eQiGgRQZL-b53E41YPeCprTJk6NEDcmgJTtyL0,133
+phonemizer/share/segments/cree.g2p,sha256=bChrLTuHdbAfR5839Iu6cnqIExVDxyFP1XKGVQyCusw,133
+phonemizer/share/segments/inuktitut.g2p,sha256=3OXFjSKUCheayNNdIQsZ_K2hkmL91aPlW3QphUPCz70,93
+phonemizer/share/segments/japanese.g2p,sha256=xwlHYCu7pktbEDqrvDEOVyRW3NWeS1GK4W8yt5Wcmg4,192
+phonemizer/share/segments/sesotho.g2p,sha256=KCS0sPDGBdyT1QGVRZEwOuCzKn0lbjM_zHXOqf_1CQk,211
+phonemizer/share/segments/yucatec.g2p,sha256=I9xvHfwEZlX1JUkuGBzMftH0dQILPtDqCKNXdiwiLrM,297
+phonemizer/utils.py,sha256=-FdZCKvdNOiVVuAjhoBzI3tfwpJuzdG4EDuQTWW5CHM,4187
+phonemizer/version.py,sha256=BmedCzrHrWrCgiyg1o1ZriHGjNk6w9hDZfxCen9HxPk,2350
+phonemizer_fork-3.3.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+phonemizer_fork-3.3.2.dist-info/METADATA,sha256=i4XmH1JuarxM_i-dv1bfxqQ2oWlBFjGG9ob2MrQ-pk0,48256
+phonemizer_fork-3.3.2.dist-info/RECORD,,
+phonemizer_fork-3.3.2.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
+phonemizer_fork-3.3.2.dist-info/entry_points.txt,sha256=PgnnDOPvchzkWgnlrKRj7yTCWa8J8DaBRbn4dizP5ZA,51
+phonemizer_fork-3.3.2.dist-info/licenses/LICENSE,sha256=1i8GWDCqNznMAxFWuWkIBcey6BG0oXjItKzYcl1WHJQ,35142
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/phonemizer_fork-3.3.2.dist-info/WHEEL b/TTS/Kokoro/.venv/Lib/site-packages/phonemizer_fork-3.3.2.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..12228d414b6cfed7c39d3781c85c63256a1d7fb5
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/phonemizer_fork-3.3.2.dist-info/WHEEL
@@ -0,0 +1,4 @@
+Wheel-Version: 1.0
+Generator: hatchling 1.27.0
+Root-Is-Purelib: true
+Tag: py3-none-any
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/phonemizer_fork-3.3.2.dist-info/entry_points.txt b/TTS/Kokoro/.venv/Lib/site-packages/phonemizer_fork-3.3.2.dist-info/entry_points.txt
new file mode 100644
index 0000000000000000000000000000000000000000..b11aa1a37fd725e1e1344b5841b10cd60765f059
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/phonemizer_fork-3.3.2.dist-info/entry_points.txt
@@ -0,0 +1,2 @@
+[console_scripts]
+phonemize = phonemizer.main:main
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pip-26.0.1.dist-info/INSTALLER b/TTS/Kokoro/.venv/Lib/site-packages/pip-26.0.1.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pip-26.0.1.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pip-26.0.1.dist-info/METADATA b/TTS/Kokoro/.venv/Lib/site-packages/pip-26.0.1.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..e56d5d1f85d656265cf5760c69f3896b3fc96984
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pip-26.0.1.dist-info/METADATA
@@ -0,0 +1,111 @@
+Metadata-Version: 2.4
+Name: pip
+Version: 26.0.1
+Summary: The PyPA recommended tool for installing Python packages.
+Author-email: The pip developers 
+Requires-Python: >=3.9
+Description-Content-Type: text/x-rst
+License-Expression: MIT
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Intended Audience :: Developers
+Classifier: Topic :: Software Development :: Build Tools
+Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3 :: Only
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Classifier: Programming Language :: Python :: 3.13
+Classifier: Programming Language :: Python :: 3.14
+Classifier: Programming Language :: Python :: Implementation :: CPython
+Classifier: Programming Language :: Python :: Implementation :: PyPy
+License-File: AUTHORS.txt
+License-File: LICENSE.txt
+License-File: src/pip/_vendor/cachecontrol/LICENSE.txt
+License-File: src/pip/_vendor/certifi/LICENSE
+License-File: src/pip/_vendor/dependency_groups/LICENSE.txt
+License-File: src/pip/_vendor/distlib/LICENSE.txt
+License-File: src/pip/_vendor/distro/LICENSE
+License-File: src/pip/_vendor/idna/LICENSE.md
+License-File: src/pip/_vendor/msgpack/COPYING
+License-File: src/pip/_vendor/packaging/LICENSE
+License-File: src/pip/_vendor/packaging/LICENSE.APACHE
+License-File: src/pip/_vendor/packaging/LICENSE.BSD
+License-File: src/pip/_vendor/pkg_resources/LICENSE
+License-File: src/pip/_vendor/platformdirs/LICENSE
+License-File: src/pip/_vendor/pygments/LICENSE
+License-File: src/pip/_vendor/pyproject_hooks/LICENSE
+License-File: src/pip/_vendor/requests/LICENSE
+License-File: src/pip/_vendor/resolvelib/LICENSE
+License-File: src/pip/_vendor/rich/LICENSE
+License-File: src/pip/_vendor/tomli/LICENSE
+License-File: src/pip/_vendor/tomli_w/LICENSE
+License-File: src/pip/_vendor/truststore/LICENSE
+License-File: src/pip/_vendor/urllib3/LICENSE.txt
+Project-URL: Changelog, https://pip.pypa.io/en/stable/news/
+Project-URL: Documentation, https://pip.pypa.io
+Project-URL: Homepage, https://pip.pypa.io/
+Project-URL: Source, https://github.com/pypa/pip
+
+pip - The Python Package Installer
+==================================
+
+.. |pypi-version| image:: https://img.shields.io/pypi/v/pip.svg
+   :target: https://pypi.org/project/pip/
+   :alt: PyPI
+
+.. |python-versions| image:: https://img.shields.io/pypi/pyversions/pip
+   :target: https://pypi.org/project/pip
+   :alt: PyPI - Python Version
+
+.. |docs-badge| image:: https://readthedocs.org/projects/pip/badge/?version=latest
+   :target: https://pip.pypa.io/en/latest
+   :alt: Documentation
+
+|pypi-version| |python-versions| |docs-badge|
+
+pip is the `package installer`_ for Python. You can use pip to install packages from the `Python Package Index`_ and other indexes.
+
+Please take a look at our documentation for how to install and use pip:
+
+* `Installation`_
+* `Usage`_
+
+We release updates regularly, with a new version every 3 months. Find more details in our documentation:
+
+* `Release notes`_
+* `Release process`_
+
+If you find bugs, need help, or want to talk to the developers, please use our mailing lists or chat rooms:
+
+* `Issue tracking`_
+* `Discourse channel`_
+* `User IRC`_
+
+If you want to get involved, head over to GitHub to get the source code, look at our development documentation and feel free to jump on the developer mailing lists and chat rooms:
+
+* `GitHub page`_
+* `Development documentation`_
+* `Development IRC`_
+
+Code of Conduct
+---------------
+
+Everyone interacting in the pip project's codebases, issue trackers, chat
+rooms, and mailing lists is expected to follow the `PSF Code of Conduct`_.
+
+.. _package installer: https://packaging.python.org/guides/tool-recommendations/
+.. _Python Package Index: https://pypi.org
+.. _Installation: https://pip.pypa.io/en/stable/installation/
+.. _Usage: https://pip.pypa.io/en/stable/
+.. _Release notes: https://pip.pypa.io/en/stable/news.html
+.. _Release process: https://pip.pypa.io/en/latest/development/release-process/
+.. _GitHub page: https://github.com/pypa/pip
+.. _Development documentation: https://pip.pypa.io/en/latest/development
+.. _Issue tracking: https://github.com/pypa/pip/issues
+.. _Discourse channel: https://discuss.python.org/c/packaging
+.. _User IRC: https://kiwiirc.com/nextclient/#ircs://irc.libera.chat:+6697/pypa
+.. _Development IRC: https://kiwiirc.com/nextclient/#ircs://irc.libera.chat:+6697/pypa-dev
+.. _PSF Code of Conduct: https://github.com/pypa/.github/blob/main/CODE_OF_CONDUCT.md
+
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pip-26.0.1.dist-info/RECORD b/TTS/Kokoro/.venv/Lib/site-packages/pip-26.0.1.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..764f4d0056e69f35057588052a6e3dde4a82862b
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pip-26.0.1.dist-info/RECORD
@@ -0,0 +1,878 @@
+../../Scripts/pip.exe,sha256=LPFH-W5uFLHYEm8fdCfzdtuEbZkgBhp-7balHch-ehU,108437
+../../Scripts/pip3.12.exe,sha256=LPFH-W5uFLHYEm8fdCfzdtuEbZkgBhp-7balHch-ehU,108437
+../../Scripts/pip3.exe,sha256=LPFH-W5uFLHYEm8fdCfzdtuEbZkgBhp-7balHch-ehU,108437
+pip-26.0.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+pip-26.0.1.dist-info/METADATA,sha256=ZqIZuNGsG6l2gHiKlQjVQghFQhgSWfhEDHuCVPW3aN8,4675
+pip-26.0.1.dist-info/RECORD,,
+pip-26.0.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pip-26.0.1.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82
+pip-26.0.1.dist-info/entry_points.txt,sha256=Vhf8s0IYgX37mtd4vGL73BPcxdKnqeCFPzB5-d30x8o,84
+pip-26.0.1.dist-info/licenses/AUTHORS.txt,sha256=grSl9YDNOpOFFJTX8ZYKSdgfouXi_DzlRyYGE2-u5aI,11731
+pip-26.0.1.dist-info/licenses/LICENSE.txt,sha256=Y0MApmnUmurmWxLGxIySTFGkzfPR_whtw0VtyLyqIQQ,1093
+pip-26.0.1.dist-info/licenses/src/pip/_vendor/cachecontrol/LICENSE.txt,sha256=hu7uh74qQ_P_H1ZJb0UfaSQ5JvAl_tuwM2ZsMExMFhs,558
+pip-26.0.1.dist-info/licenses/src/pip/_vendor/certifi/LICENSE,sha256=6TcW2mucDVpKHfYP5pWzcPBpVgPSH2-D8FPkLPwQyvc,989
+pip-26.0.1.dist-info/licenses/src/pip/_vendor/dependency_groups/LICENSE.txt,sha256=GrNuPipLqGMWJThPh-ngkdsfrtA0xbIzJbMjmr8sxSU,1099
+pip-26.0.1.dist-info/licenses/src/pip/_vendor/distlib/LICENSE.txt,sha256=gI4QyKarjesUn_mz-xn0R6gICUYG1xKpylf-rTVSWZ0,14531
+pip-26.0.1.dist-info/licenses/src/pip/_vendor/distro/LICENSE,sha256=y16Ofl9KOYjhBjwULGDcLfdWBfTEZRXnduOspt-XbhQ,11325
+pip-26.0.1.dist-info/licenses/src/pip/_vendor/idna/LICENSE.md,sha256=t6M2q_OwThgOwGXN0W5wXQeeHMehT5EKpukYfza5zYc,1541
+pip-26.0.1.dist-info/licenses/src/pip/_vendor/msgpack/COPYING,sha256=SS3tuoXaWHL3jmCRvNH-pHTWYNNay03ulkuKqz8AdCc,614
+pip-26.0.1.dist-info/licenses/src/pip/_vendor/packaging/LICENSE,sha256=ytHvW9NA1z4HS6YU0m996spceUDD2MNIUuZcSQlobEg,197
+pip-26.0.1.dist-info/licenses/src/pip/_vendor/packaging/LICENSE.APACHE,sha256=DVQuDIgE45qn836wDaWnYhSdxoLXgpRRKH4RuTjpRZQ,10174
+pip-26.0.1.dist-info/licenses/src/pip/_vendor/packaging/LICENSE.BSD,sha256=tw5-m3QvHMb5SLNMFqo5_-zpQZY2S8iP8NIYDwAo-sU,1344
+pip-26.0.1.dist-info/licenses/src/pip/_vendor/pkg_resources/LICENSE,sha256=htoPAa6uRjSKPD1GUZXcHOzN55956HdppkuNoEsqR0E,1023
+pip-26.0.1.dist-info/licenses/src/pip/_vendor/platformdirs/LICENSE,sha256=KeD9YukphQ6G6yjD_czwzv30-pSHkBHP-z0NS-1tTbY,1089
+pip-26.0.1.dist-info/licenses/src/pip/_vendor/pygments/LICENSE,sha256=qdZvHVJt8C4p3Oc0NtNOVuhjL0bCdbvf_HBWnogvnxc,1331
+pip-26.0.1.dist-info/licenses/src/pip/_vendor/pyproject_hooks/LICENSE,sha256=GyKwSbUmfW38I6Z79KhNjsBLn9-xpR02DkK0NCyLQVQ,1081
+pip-26.0.1.dist-info/licenses/src/pip/_vendor/requests/LICENSE,sha256=CeipvOyAZxBGUsFoaFqwkx54aPnIKEtm9a5u2uXxEws,10142
+pip-26.0.1.dist-info/licenses/src/pip/_vendor/resolvelib/LICENSE,sha256=84j9OMrRMRLB3A9mm76A5_hFQe26-3LzAw0sp2QsPJ0,751
+pip-26.0.1.dist-info/licenses/src/pip/_vendor/rich/LICENSE,sha256=3u18F6QxgVgZCj6iOcyHmlpQJxzruYrnAl9I--WNyhU,1056
+pip-26.0.1.dist-info/licenses/src/pip/_vendor/tomli/LICENSE,sha256=uAgWsNUwuKzLTCIReDeQmEpuO2GSLCte6S8zcqsnQv4,1072
+pip-26.0.1.dist-info/licenses/src/pip/_vendor/tomli_w/LICENSE,sha256=uAgWsNUwuKzLTCIReDeQmEpuO2GSLCte6S8zcqsnQv4,1072
+pip-26.0.1.dist-info/licenses/src/pip/_vendor/truststore/LICENSE,sha256=M757fo-k_Rmxdg4ajtimaL2rhSyRtpLdQUJLy3Jan8o,1086
+pip-26.0.1.dist-info/licenses/src/pip/_vendor/urllib3/LICENSE.txt,sha256=w3vxhuJ8-dvpYZ5V7f486nswCRzrPaY8fay-Dm13kHs,1115
+pip/__init__.py,sha256=3EhKF2588Ab15tmBszgD3Bp0N26sJx7VhS2Akn_qY38,355
+pip/__main__.py,sha256=WzbhHXTbSE6gBY19mNN9m4s5o_365LOvTYSgqgbdBhE,854
+pip/__pip-runner__.py,sha256=JOoEZTwrtv7jRaXBkgSQKAE04yNyfFmGHxqpHiGHvL0,1450
+pip/__pycache__/__init__.cpython-312.pyc,,
+pip/__pycache__/__main__.cpython-312.pyc,,
+pip/__pycache__/__pip-runner__.cpython-312.pyc,,
+pip/_internal/__init__.py,sha256=S7i9Dn9aSZS0MG-2Wrve3dV9TImPzvQn5jjhp9t_uf0,511
+pip/_internal/__pycache__/__init__.cpython-312.pyc,,
+pip/_internal/__pycache__/build_env.cpython-312.pyc,,
+pip/_internal/__pycache__/cache.cpython-312.pyc,,
+pip/_internal/__pycache__/configuration.cpython-312.pyc,,
+pip/_internal/__pycache__/exceptions.cpython-312.pyc,,
+pip/_internal/__pycache__/main.cpython-312.pyc,,
+pip/_internal/__pycache__/pyproject.cpython-312.pyc,,
+pip/_internal/__pycache__/self_outdated_check.cpython-312.pyc,,
+pip/_internal/__pycache__/wheel_builder.cpython-312.pyc,,
+pip/_internal/build_env.py,sha256=XpgOIlTQLgz3PvDT2n7j2NzX_rVFZLCIG7t7b2ddhcM,21911
+pip/_internal/cache.py,sha256=nMh48Yv3yu1HS1yCdscouu6B6B5zYBWdV6bhqs7gL-E,10345
+pip/_internal/cli/__init__.py,sha256=Iqg_tKA771XuMO1P4t_sDHnSKPzkUb9D0DqunAmw_ko,131
+pip/_internal/cli/__pycache__/__init__.cpython-312.pyc,,
+pip/_internal/cli/__pycache__/autocompletion.cpython-312.pyc,,
+pip/_internal/cli/__pycache__/base_command.cpython-312.pyc,,
+pip/_internal/cli/__pycache__/cmdoptions.cpython-312.pyc,,
+pip/_internal/cli/__pycache__/command_context.cpython-312.pyc,,
+pip/_internal/cli/__pycache__/index_command.cpython-312.pyc,,
+pip/_internal/cli/__pycache__/main.cpython-312.pyc,,
+pip/_internal/cli/__pycache__/main_parser.cpython-312.pyc,,
+pip/_internal/cli/__pycache__/parser.cpython-312.pyc,,
+pip/_internal/cli/__pycache__/progress_bars.cpython-312.pyc,,
+pip/_internal/cli/__pycache__/req_command.cpython-312.pyc,,
+pip/_internal/cli/__pycache__/spinners.cpython-312.pyc,,
+pip/_internal/cli/__pycache__/status_codes.cpython-312.pyc,,
+pip/_internal/cli/autocompletion.py,sha256=ZG2cM03nlcNrs-WG_SFTW46isx9s2Go5lUD_8-iv70o,7193
+pip/_internal/cli/base_command.py,sha256=6OW75PSGzkH8Fz761WZ3OSz1TsuO3-suc6iap-sQjTM,9168
+pip/_internal/cli/cmdoptions.py,sha256=hfA9B29Nnq2vYMWhFVg7EcWjdlfdPBPU4WwWT2Lkq4A,36164
+pip/_internal/cli/command_context.py,sha256=kmu3EWZbfBega1oDamnGJTA_UaejhIQNuMj2CVmMXu0,817
+pip/_internal/cli/index_command.py,sha256=s3x75lpDXWJtCkBacTQ3qAAprldHMJCniEQ5qkQ0FiI,6484
+pip/_internal/cli/main.py,sha256=ljDQBkvBtC8xTjOdb6rDJzJUNi1s-PnVR_W5C-Mq0Dk,3137
+pip/_internal/cli/main_parser.py,sha256=YjzJAjqf78ARNsLlnJT9l6fNbpyDPJA-arOIXYsK5Ik,4403
+pip/_internal/cli/parser.py,sha256=EIFExrWX_1nrl1Ib--GOor70WYqLtduHByenb1u9xH4,13827
+pip/_internal/cli/progress_bars.py,sha256=IW1PH5n2FPqUBTP7ULQ5Yu-wyNNO9XGY3g1PT4RMu44,4706
+pip/_internal/cli/req_command.py,sha256=QjDXId0hFdopwE8hNx2eustumxUNbnOCvG_ORmUC7vM,16482
+pip/_internal/cli/spinners.py,sha256=EJzZIZNyUtJljp3-WjcsyIrqxW-HUsfWzhuW84n_Tqw,7362
+pip/_internal/cli/status_codes.py,sha256=sEFHUaUJbqv8iArL3HAtcztWZmGOFX01hTesSytDEh0,116
+pip/_internal/commands/__init__.py,sha256=aNeCbQurGWihfhQq7BqaLXHqWDQ0i3I04OS7kxK6plQ,4026
+pip/_internal/commands/__pycache__/__init__.cpython-312.pyc,,
+pip/_internal/commands/__pycache__/cache.cpython-312.pyc,,
+pip/_internal/commands/__pycache__/check.cpython-312.pyc,,
+pip/_internal/commands/__pycache__/completion.cpython-312.pyc,,
+pip/_internal/commands/__pycache__/configuration.cpython-312.pyc,,
+pip/_internal/commands/__pycache__/debug.cpython-312.pyc,,
+pip/_internal/commands/__pycache__/download.cpython-312.pyc,,
+pip/_internal/commands/__pycache__/freeze.cpython-312.pyc,,
+pip/_internal/commands/__pycache__/hash.cpython-312.pyc,,
+pip/_internal/commands/__pycache__/help.cpython-312.pyc,,
+pip/_internal/commands/__pycache__/index.cpython-312.pyc,,
+pip/_internal/commands/__pycache__/inspect.cpython-312.pyc,,
+pip/_internal/commands/__pycache__/install.cpython-312.pyc,,
+pip/_internal/commands/__pycache__/list.cpython-312.pyc,,
+pip/_internal/commands/__pycache__/lock.cpython-312.pyc,,
+pip/_internal/commands/__pycache__/search.cpython-312.pyc,,
+pip/_internal/commands/__pycache__/show.cpython-312.pyc,,
+pip/_internal/commands/__pycache__/uninstall.cpython-312.pyc,,
+pip/_internal/commands/__pycache__/wheel.cpython-312.pyc,,
+pip/_internal/commands/cache.py,sha256=XjT7kjY8GSISMksFHsLvjS9Ogfi5extNlUUv-dUoWCM,9142
+pip/_internal/commands/check.py,sha256=hVFBQezQ3zj4EydoWbFQj_afPUppMt7r9JPAlY22U6Y,2244
+pip/_internal/commands/completion.py,sha256=LjvRIZ6QUiDXJL3IOMFeD-_J97HfjMGgEk0j2tWGu1U,4565
+pip/_internal/commands/configuration.py,sha256=6gNOGrVWnOLU15zUnAiNuOMhf76RRIZvCdVD0degPRk,10105
+pip/_internal/commands/debug.py,sha256=_8IqM8Fx1_lY2STu_qspr63tufF7zyFJCyYAXtxz0N4,6805
+pip/_internal/commands/download.py,sha256=LUNVobuvCdagjLBuPBaxHeBiHEiIe03fTO2m6ahC8qw,5178
+pip/_internal/commands/freeze.py,sha256=fxoW8AAc-bAqB_fXdNq2VnZ3JfWkFMg-bR6LcdDVO7A,3099
+pip/_internal/commands/hash.py,sha256=GO9pRN3wXC2kQaovK57TaLYBMc3IltOH92O6QEw6YE0,1679
+pip/_internal/commands/help.py,sha256=Bz3LcjNQXkz4Cu__pL4CZ86o4-HNLZj1NZWdlJhjuu0,1108
+pip/_internal/commands/index.py,sha256=kDpx2MO6ZxTt5PpeY4jqcssVbYhzxpkpreDe_6PPhks,5520
+pip/_internal/commands/inspect.py,sha256=ogm4UT7LRo8bIQcWUS1IiA25QdD4VHLa7JaPAodDttM,3177
+pip/_internal/commands/install.py,sha256=L6X1qi49ROVTGABhwwxDgBBTijlOpVn6XSDVZ7QW1Kc,30588
+pip/_internal/commands/list.py,sha256=L5nWuwawqSrBNsuxfyHLAagfz7XJP86tC9nK3L9YiI8,13497
+pip/_internal/commands/lock.py,sha256=145ihjUK_-7gP8O65XPDi_xMhlh5hne1ptkHdfnbAnQ,6027
+pip/_internal/commands/search.py,sha256=zbMsX_YASj6kXA6XIBgTDv0bGK51xG-CV3IynZJcE-c,5782
+pip/_internal/commands/show.py,sha256=oLVJIfKWmDKm0SsQGEi3pozNiqrXjTras_fbBSYKpBA,8066
+pip/_internal/commands/uninstall.py,sha256=CsOihqvb6ZA6O67L70oXeoLHeOfNzMM88H9g-9aocgw,3868
+pip/_internal/commands/wheel.py,sha256=L9vEzJ_E42scF_Hgh5X4Hk39nqJDKxGg4u7glDYbNWc,5880
+pip/_internal/configuration.py,sha256=WxwwSwY_Bm6QzDgf32BsujEyO8dgRedegCpgbUfDvM8,14568
+pip/_internal/distributions/__init__.py,sha256=Hq6kt6gXBgjNit5hTTWLAzeCNOKoB-N0pGYSqehrli8,858
+pip/_internal/distributions/__pycache__/__init__.cpython-312.pyc,,
+pip/_internal/distributions/__pycache__/base.cpython-312.pyc,,
+pip/_internal/distributions/__pycache__/installed.cpython-312.pyc,,
+pip/_internal/distributions/__pycache__/sdist.cpython-312.pyc,,
+pip/_internal/distributions/__pycache__/wheel.cpython-312.pyc,,
+pip/_internal/distributions/base.py,sha256=l-OTCAIs25lsapejA6IYpPZxSM5-BET4sdZDkql8jiY,1830
+pip/_internal/distributions/installed.py,sha256=kgIEE_1NzjZxLBSC-v5s64uOFZlVEt3aPrjTtL6x2XY,929
+pip/_internal/distributions/sdist.py,sha256=RYwQIbuxpKy6OjlBZCAefxpMDaoocUQ4dFtheGsiTOQ,6627
+pip/_internal/distributions/wheel.py,sha256=_HbG0OehF8dwj4UX-xV__tXLwgPus9OjMEf2NTRqBbE,1364
+pip/_internal/exceptions.py,sha256=JdPCrQ9iTLvE-GBebzBEeGP3hoTffWEKqbYEsa6cEZc,32165
+pip/_internal/index/__init__.py,sha256=tzwMH_fhQeubwMqHdSivasg1cRgTSbNg2CiMVnzMmyU,29
+pip/_internal/index/__pycache__/__init__.cpython-312.pyc,,
+pip/_internal/index/__pycache__/collector.cpython-312.pyc,,
+pip/_internal/index/__pycache__/package_finder.cpython-312.pyc,,
+pip/_internal/index/__pycache__/sources.cpython-312.pyc,,
+pip/_internal/index/collector.py,sha256=R7Gcx_4GEoSEI-iazfAZVEPG3Lp6mbZT4lbAD6NjAc0,16144
+pip/_internal/index/package_finder.py,sha256=a3_L4FDNsuDf3y8Af9J7sfsHR1ahs8o13Ths-WYwFh0,41776
+pip/_internal/index/sources.py,sha256=nXJkOjhLy-O2FsrKU9RIqCOqgY2PsoKWybtZjjRgqU0,8639
+pip/_internal/locations/__init__.py,sha256=Sd67ap1LIemvXArUDFqm8U-HuZvj9i3ApEuiIwUc9UE,14157
+pip/_internal/locations/__pycache__/__init__.cpython-312.pyc,,
+pip/_internal/locations/__pycache__/_distutils.cpython-312.pyc,,
+pip/_internal/locations/__pycache__/_sysconfig.cpython-312.pyc,,
+pip/_internal/locations/__pycache__/base.cpython-312.pyc,,
+pip/_internal/locations/_distutils.py,sha256=jpFj4V00rD9IR3vA9TqrGkwcdNVFc58LsChZavge9JY,5975
+pip/_internal/locations/_sysconfig.py,sha256=8CpTjtxaCzHSCrKpaxWnHE7aKcJrRJRmntR1ZLVysLk,7779
+pip/_internal/locations/base.py,sha256=AImjYJWxOtDkc0KKc6Y4Gz677cg91caMA4L94B9FZEg,2550
+pip/_internal/main.py,sha256=1cHqjsfFCrMFf3B5twzocxTJUdHMLoXUpy5lJoFqUi8,338
+pip/_internal/metadata/__init__.py,sha256=vp-JAxiWg_-l5F8AT0Jcey72uUnh8CDwwol9-KktHZ8,5824
+pip/_internal/metadata/__pycache__/__init__.cpython-312.pyc,,
+pip/_internal/metadata/__pycache__/_json.cpython-312.pyc,,
+pip/_internal/metadata/__pycache__/base.cpython-312.pyc,,
+pip/_internal/metadata/__pycache__/pkg_resources.cpython-312.pyc,,
+pip/_internal/metadata/_json.py,sha256=hNvnMHOXLAyNlzirWhPL9Nx2CvCqa1iRma6Osq1YfV8,2711
+pip/_internal/metadata/base.py,sha256=BGuMenlcQT8i7j9iclrfdC3vSwgvhr8gjn955cCy16s,25420
+pip/_internal/metadata/importlib/__init__.py,sha256=jUUidoxnHcfITHHaAWG1G2i5fdBYklv_uJcjo2x7VYE,135
+pip/_internal/metadata/importlib/__pycache__/__init__.cpython-312.pyc,,
+pip/_internal/metadata/importlib/__pycache__/_compat.cpython-312.pyc,,
+pip/_internal/metadata/importlib/__pycache__/_dists.cpython-312.pyc,,
+pip/_internal/metadata/importlib/__pycache__/_envs.cpython-312.pyc,,
+pip/_internal/metadata/importlib/_compat.py,sha256=sneVh4_6WxQZK4ljdl3ylVuP-q0ttSqbgl9mWt0HnOg,2804
+pip/_internal/metadata/importlib/_dists.py,sha256=znZD7MN4RC73-87KXAn6tKZv9lAQRI0AxxK2bubDvPw,8420
+pip/_internal/metadata/importlib/_envs.py,sha256=H3qVLXVh4LWvrPvu_ekXf3dfbtwnlhNJQP2pxXpccfU,5333
+pip/_internal/metadata/pkg_resources.py,sha256=NO76ZrfR2-LKJTyaXrmQoGhmJMArALvacrlZHViSDT8,10544
+pip/_internal/models/__init__.py,sha256=AjmCEBxX_MH9f_jVjIGNCFJKYCYeSEe18yyvNx4uRKQ,62
+pip/_internal/models/__pycache__/__init__.cpython-312.pyc,,
+pip/_internal/models/__pycache__/candidate.cpython-312.pyc,,
+pip/_internal/models/__pycache__/direct_url.cpython-312.pyc,,
+pip/_internal/models/__pycache__/format_control.cpython-312.pyc,,
+pip/_internal/models/__pycache__/index.cpython-312.pyc,,
+pip/_internal/models/__pycache__/installation_report.cpython-312.pyc,,
+pip/_internal/models/__pycache__/link.cpython-312.pyc,,
+pip/_internal/models/__pycache__/release_control.cpython-312.pyc,,
+pip/_internal/models/__pycache__/scheme.cpython-312.pyc,,
+pip/_internal/models/__pycache__/search_scope.cpython-312.pyc,,
+pip/_internal/models/__pycache__/selection_prefs.cpython-312.pyc,,
+pip/_internal/models/__pycache__/target_python.cpython-312.pyc,,
+pip/_internal/models/__pycache__/wheel.cpython-312.pyc,,
+pip/_internal/models/candidate.py,sha256=zzgFRuw_kWPjKpGw7LC0ZUMD2CQ2EberUIYs8izjdCA,753
+pip/_internal/models/direct_url.py,sha256=4NMWacu_QzPPWREC1te7v6Wfv-2HkI4tvSJF-CBgLh4,6555
+pip/_internal/models/format_control.py,sha256=PwemYG1L27BM0f1KP61rm24wShENFyxqlD1TWu34alc,2471
+pip/_internal/models/index.py,sha256=tYnL8oxGi4aSNWur0mG8DAP7rC6yuha_MwJO8xw0crI,1030
+pip/_internal/models/installation_report.py,sha256=cqfWJ93ThCxjcacqSWryOCD2XtIn1CZrgzZxAv5FQZ0,2839
+pip/_internal/models/link.py,sha256=zti5UCx1hT03etYqm6MCqFd714clmTgX8rTZT9CKZDQ,21992
+pip/_internal/models/release_control.py,sha256=XD14Hy_XLh9xWR1p7JHqPZPEv3Nnb1BZGMpClk76sLs,3403
+pip/_internal/models/scheme.py,sha256=PakmHJM3e8OOWSZFtfz1Az7f1meONJnkGuQxFlt3wBE,575
+pip/_internal/models/search_scope.py,sha256=1hxU2IVsAaLZVjp0CbzJbYaYzCxv72_Qbg3JL0qhXo0,4507
+pip/_internal/models/selection_prefs.py,sha256=IDOA3euRtyqWUyIK7lX2bzIZasYiEvunKA6H3Mngk-M,2221
+pip/_internal/models/target_python.py,sha256=I0eFS-eia3kwhrOvgsphFZtNAB2IwXZ9Sr9fp6IjBP4,4243
+pip/_internal/models/wheel.py,sha256=1SdfDvN7ALTsbyZ9EOsNy1GPirP1n6EjHyzPrZyLSh8,2920
+pip/_internal/network/__init__.py,sha256=FMy06P__y6jMjUc8z3ZcQdKF-pmZ2zM14_vBeHPGhUI,49
+pip/_internal/network/__pycache__/__init__.cpython-312.pyc,,
+pip/_internal/network/__pycache__/auth.cpython-312.pyc,,
+pip/_internal/network/__pycache__/cache.cpython-312.pyc,,
+pip/_internal/network/__pycache__/download.cpython-312.pyc,,
+pip/_internal/network/__pycache__/lazy_wheel.cpython-312.pyc,,
+pip/_internal/network/__pycache__/session.cpython-312.pyc,,
+pip/_internal/network/__pycache__/utils.cpython-312.pyc,,
+pip/_internal/network/__pycache__/xmlrpc.cpython-312.pyc,,
+pip/_internal/network/auth.py,sha256=azFp14I9cyWAAzkxF2VM0Q_xtHnbNz3_NQXszy87KQo,20806
+pip/_internal/network/cache.py,sha256=kmRXKQrG9E26xQRj211LHeEGpDg_SlYU9Dn1fJ-AMeI,4862
+pip/_internal/network/download.py,sha256=8sVwIc9MWwpGlMPYCkO1S9U-FD8TA2utw42tj00skjM,12667
+pip/_internal/network/lazy_wheel.py,sha256=y9gVksdJCSjnLfYzs_m3DYUAtl3hc_k-xFPDBd9DgOs,7646
+pip/_internal/network/session.py,sha256=7zK7EeQCSRFipu4ZzcWl1V3AMKkiXdtGqFr7GvU2LrY,19555
+pip/_internal/network/utils.py,sha256=ACsXd1msqNCidHVXsu7LHUSr8NgaypcOKQ4KG-Z_wJM,4091
+pip/_internal/network/xmlrpc.py,sha256=_-Rnk3vOff8uF9hAGmT6SLALflY1gMBcbGwS12fb_Y4,1830
+pip/_internal/operations/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pip/_internal/operations/__pycache__/__init__.cpython-312.pyc,,
+pip/_internal/operations/__pycache__/check.cpython-312.pyc,,
+pip/_internal/operations/__pycache__/freeze.cpython-312.pyc,,
+pip/_internal/operations/__pycache__/prepare.cpython-312.pyc,,
+pip/_internal/operations/build/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pip/_internal/operations/build/__pycache__/__init__.cpython-312.pyc,,
+pip/_internal/operations/build/__pycache__/build_tracker.cpython-312.pyc,,
+pip/_internal/operations/build/__pycache__/metadata.cpython-312.pyc,,
+pip/_internal/operations/build/__pycache__/metadata_editable.cpython-312.pyc,,
+pip/_internal/operations/build/__pycache__/wheel.cpython-312.pyc,,
+pip/_internal/operations/build/__pycache__/wheel_editable.cpython-312.pyc,,
+pip/_internal/operations/build/build_tracker.py,sha256=W3b5cmkMWPaE6QIwfzsTayJo7-OlxFHWDxfPuax1KcE,4771
+pip/_internal/operations/build/metadata.py,sha256=INHaeiRfOiLYCXApfDNRo9Cw2xI4VwTc0KItvfdfOjk,1421
+pip/_internal/operations/build/metadata_editable.py,sha256=oWudMsnjy4loO_Jy7g4N9nxsnaEX_iDlVRgCy7pu1rs,1509
+pip/_internal/operations/build/wheel.py,sha256=3bP-nNiJ4S8JvMaBnyessXQUBhxTqt1GBx6DQ1iPJDY,1136
+pip/_internal/operations/build/wheel_editable.py,sha256=q3kfElclM6FutVbFwE87JOTpVWt5ixDf3_UkHAIVfz4,1478
+pip/_internal/operations/check.py,sha256=yC2XWth6iehGGE_fj7XRJLjVKBsTIG3ZoWRkFi3rOwc,5894
+pip/_internal/operations/freeze.py,sha256=PDdY-y_ZtZZJLAKcaWPIGRKAGW7DXR48f0aMRU0j7BA,9854
+pip/_internal/operations/install/__init__.py,sha256=ak-UETcQPKlFZaWoYKWu5QVXbpFBvg0sXc3i0O4vSYY,50
+pip/_internal/operations/install/__pycache__/__init__.cpython-312.pyc,,
+pip/_internal/operations/install/__pycache__/wheel.cpython-312.pyc,,
+pip/_internal/operations/install/wheel.py,sha256=FQIl2AnNadHV5YGGOVEmOHtUUNO8lpzj3Icoo4S2xis,27923
+pip/_internal/operations/prepare.py,sha256=ptVsmQf0Mo6jirk1Q5Djdse_wJw5Zdh1Fla2iL9HAJM,28830
+pip/_internal/pyproject.py,sha256=J-sTWqC-XfsKQgz9m1bypMWZPHItsSHzIN_NWeIRmhM,4555
+pip/_internal/req/__init__.py,sha256=WcY9z7D3rlIKX1QY8_tRnAsS_poebiGGdtQ7EJ5JQQo,3041
+pip/_internal/req/__pycache__/__init__.cpython-312.pyc,,
+pip/_internal/req/__pycache__/constructors.cpython-312.pyc,,
+pip/_internal/req/__pycache__/pep723.cpython-312.pyc,,
+pip/_internal/req/__pycache__/req_dependency_group.cpython-312.pyc,,
+pip/_internal/req/__pycache__/req_file.cpython-312.pyc,,
+pip/_internal/req/__pycache__/req_install.cpython-312.pyc,,
+pip/_internal/req/__pycache__/req_set.cpython-312.pyc,,
+pip/_internal/req/__pycache__/req_uninstall.cpython-312.pyc,,
+pip/_internal/req/constructors.py,sha256=R-6n8irjnaa2DMMXlR4YMouXzykFBlzUFjhOZ1NcUUg,18688
+pip/_internal/req/pep723.py,sha256=olZL3tLmHWJhyLNfbD6U9UuikuzTcLDB06qd9WavTjs,1225
+pip/_internal/req/req_dependency_group.py,sha256=0yEQCUaO5Bza66Y3D5o9JRf0qII5QgCRugn1x5aRivA,2618
+pip/_internal/req/req_file.py,sha256=e32ZQ3kJaL_Sdtf32twGKqIau_AqR43MeSycl0iS2Mw,20685
+pip/_internal/req/req_install.py,sha256=vv5cbs3P5gf43e_1v72gwSQ2N_D_qpsfuXOyerMhDuI,31273
+pip/_internal/req/req_set.py,sha256=awkqIXnYA4Prmsj0Qb3zhqdbYUmXd-1o0P-KZ3mvRQs,2828
+pip/_internal/req/req_uninstall.py,sha256=dCmOHt-9RaJBq921L4tMH3PmIBDetGplnbjRKXmGt00,24099
+pip/_internal/resolution/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pip/_internal/resolution/__pycache__/__init__.cpython-312.pyc,,
+pip/_internal/resolution/__pycache__/base.cpython-312.pyc,,
+pip/_internal/resolution/base.py,sha256=RIsqSP79olPdOgtPKW-oOQ364ICVopehA6RfGkRfe2s,577
+pip/_internal/resolution/legacy/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pip/_internal/resolution/legacy/__pycache__/__init__.cpython-312.pyc,,
+pip/_internal/resolution/legacy/__pycache__/resolver.cpython-312.pyc,,
+pip/_internal/resolution/legacy/resolver.py,sha256=bwUqE66etz2bcPabqxed18-iyqqb-kx3Er2aT6GeUJY,24060
+pip/_internal/resolution/resolvelib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pip/_internal/resolution/resolvelib/__pycache__/__init__.cpython-312.pyc,,
+pip/_internal/resolution/resolvelib/__pycache__/base.cpython-312.pyc,,
+pip/_internal/resolution/resolvelib/__pycache__/candidates.cpython-312.pyc,,
+pip/_internal/resolution/resolvelib/__pycache__/factory.cpython-312.pyc,,
+pip/_internal/resolution/resolvelib/__pycache__/found_candidates.cpython-312.pyc,,
+pip/_internal/resolution/resolvelib/__pycache__/provider.cpython-312.pyc,,
+pip/_internal/resolution/resolvelib/__pycache__/reporter.cpython-312.pyc,,
+pip/_internal/resolution/resolvelib/__pycache__/requirements.cpython-312.pyc,,
+pip/_internal/resolution/resolvelib/__pycache__/resolver.cpython-312.pyc,,
+pip/_internal/resolution/resolvelib/base.py,sha256=_AoP0ZWlaSct8CRDn2ol3CbNn4zDtnh_0zQGjXASDKI,5047
+pip/_internal/resolution/resolvelib/candidates.py,sha256=50AN7BfB-pCfEmbKNlFZSXtdC0C8ms1waJrF2arknQE,20454
+pip/_internal/resolution/resolvelib/factory.py,sha256=82mLwnPlig37mMrDwcgKHJTE9mPczVuJIxeaUb7CQ0Y,34028
+pip/_internal/resolution/resolvelib/found_candidates.py,sha256=8bZYDCZLXSdLHy_s1o5f4r15HmKvqFUhzBUQOF21Lr4,6018
+pip/_internal/resolution/resolvelib/provider.py,sha256=tbVPfFv4Vg780yZ2_XGoGFP5LVo0U2bFnZov3jpSAIk,11441
+pip/_internal/resolution/resolvelib/reporter.py,sha256=faSgjqme0k_uzv1fvM5T0ZatPQ2eEktNvKBqfvXeGjc,3909
+pip/_internal/resolution/resolvelib/requirements.py,sha256=Izl9n8nc188lA1BSPS8QxfudfDQPHgngw-ij6hXt0nQ,8239
+pip/_internal/resolution/resolvelib/resolver.py,sha256=wQ94Hkep-7kWEHAc-NbMJhmzeEzgEAtxeBxyKVzZoeo,13437
+pip/_internal/self_outdated_check.py,sha256=zDKsyLMufFHuEZY16WRu129FBbBp-ADuxyWMIN4ihPE,8284
+pip/_internal/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pip/_internal/utils/__pycache__/__init__.cpython-312.pyc,,
+pip/_internal/utils/__pycache__/_jaraco_text.cpython-312.pyc,,
+pip/_internal/utils/__pycache__/_log.cpython-312.pyc,,
+pip/_internal/utils/__pycache__/appdirs.cpython-312.pyc,,
+pip/_internal/utils/__pycache__/compat.cpython-312.pyc,,
+pip/_internal/utils/__pycache__/compatibility_tags.cpython-312.pyc,,
+pip/_internal/utils/__pycache__/datetime.cpython-312.pyc,,
+pip/_internal/utils/__pycache__/deprecation.cpython-312.pyc,,
+pip/_internal/utils/__pycache__/direct_url_helpers.cpython-312.pyc,,
+pip/_internal/utils/__pycache__/egg_link.cpython-312.pyc,,
+pip/_internal/utils/__pycache__/entrypoints.cpython-312.pyc,,
+pip/_internal/utils/__pycache__/filesystem.cpython-312.pyc,,
+pip/_internal/utils/__pycache__/filetypes.cpython-312.pyc,,
+pip/_internal/utils/__pycache__/glibc.cpython-312.pyc,,
+pip/_internal/utils/__pycache__/hashes.cpython-312.pyc,,
+pip/_internal/utils/__pycache__/logging.cpython-312.pyc,,
+pip/_internal/utils/__pycache__/misc.cpython-312.pyc,,
+pip/_internal/utils/__pycache__/packaging.cpython-312.pyc,,
+pip/_internal/utils/__pycache__/pylock.cpython-312.pyc,,
+pip/_internal/utils/__pycache__/retry.cpython-312.pyc,,
+pip/_internal/utils/__pycache__/subprocess.cpython-312.pyc,,
+pip/_internal/utils/__pycache__/temp_dir.cpython-312.pyc,,
+pip/_internal/utils/__pycache__/unpacking.cpython-312.pyc,,
+pip/_internal/utils/__pycache__/urls.cpython-312.pyc,,
+pip/_internal/utils/__pycache__/virtualenv.cpython-312.pyc,,
+pip/_internal/utils/__pycache__/wheel.cpython-312.pyc,,
+pip/_internal/utils/_jaraco_text.py,sha256=M15uUPIh5NpP1tdUGBxRau6q1ZAEtI8-XyLEETscFfE,3350
+pip/_internal/utils/_log.py,sha256=-jHLOE_THaZz5BFcCnoSL9EYAtJ0nXem49s9of4jvKw,1015
+pip/_internal/utils/appdirs.py,sha256=LrzDPZMKVh0rubtCx9vu3XlZbLCSug6VSj4Qsvt66BA,1681
+pip/_internal/utils/compat.py,sha256=C9LHXJAKkwAH8Hn3nPkz9EYK3rqPBeO_IXkOG2zzsdQ,2514
+pip/_internal/utils/compatibility_tags.py,sha256=DiNSLqpuruXUamGQwOJ2WZByDGLTGaXi9O-Xf8fOi34,6630
+pip/_internal/utils/datetime.py,sha256=kuJOf1mW8G5tRFN6jWardddS-9qSaR53lK1jmx3NTZY,868
+pip/_internal/utils/deprecation.py,sha256=HVhvyO5qiRFcG88PhZlp_87qdKQNwPTUIIHWtsTR2yI,3696
+pip/_internal/utils/direct_url_helpers.py,sha256=ttKv4GMUqlRwPPog9_CUopy6SDgoxVILzeBJzgfn2tg,3200
+pip/_internal/utils/egg_link.py,sha256=YWfsrbmfcrfWgqQYy6OuIjsyb9IfL1q_2v4zsms1WjI,2459
+pip/_internal/utils/entrypoints.py,sha256=uPjAyShKObdotjQjJUzprQ6r3xQvDIZwUYfHHqZ7Dok,3324
+pip/_internal/utils/filesystem.py,sha256=mJ_PP8z1V1x4HMhydWIWDyEmWikLX0f-NXPCXEcjiLo,6892
+pip/_internal/utils/filetypes.py,sha256=sEMa38qaqjvx1Zid3OCAUja31BOBU-USuSMPBvU3yjo,689
+pip/_internal/utils/glibc.py,sha256=sEh8RJJLYSdRvTqAO4THVPPA-YSDVLD4SI9So-bxX1U,3726
+pip/_internal/utils/hashes.py,sha256=d32UI1en8nyqZzdZQvxUVdfeBoe4ADWx7HtrIM4-XQ4,4998
+pip/_internal/utils/logging.py,sha256=6lJWMC6c7_aD_i4sdgaaeb-Tm3kWpYg0hba_V1-OLnE,13414
+pip/_internal/utils/misc.py,sha256=phFIbHm2kmliHDXJ0eNPxgGP423ZpvZoMKKtJ1_Zvjs,23722
+pip/_internal/utils/packaging.py,sha256=s5tpUmFumwV0H9JSTzryrIY4JwQM8paGt7Sm7eNwt2Y,1601
+pip/_internal/utils/pylock.py,sha256=nKQknZgyswWgzi--hRQX_DLUYQ3g5wGTCwVNQNdoJ54,3817
+pip/_internal/utils/retry.py,sha256=83wReEB2rcntMZ5VLd7ascaYSjn_kLdlQCqxILxWkPM,1461
+pip/_internal/utils/subprocess.py,sha256=r4-Ba_Yc3uZXQpi0K4pZFsCT_QqdSvtF3XJ-204QWaA,8983
+pip/_internal/utils/temp_dir.py,sha256=D9c8D7WOProOO8GGDqpBeVSj10NGFmunG0o2TodjjIU,9307
+pip/_internal/utils/unpacking.py,sha256=4hNg6dqHOn_KzGCzSC76nChG97d_UjtF9AnLSof672o,12972
+pip/_internal/utils/urls.py,sha256=aF_eg9ul5d8bMCxfSSSxQcfs-OpJdbStYqZHoy2K1RE,1601
+pip/_internal/utils/virtualenv.py,sha256=mX-UPyw1MPxhwUxKhbqWWX70J6PHXAJjVVrRnG0h9mc,3455
+pip/_internal/utils/wheel.py,sha256=YdRuj6MicG-Q9Mg03FbUv1WTLam6Lc7AgijY4voVyis,4468
+pip/_internal/vcs/__init__.py,sha256=UAqvzpbi0VbZo3Ub6skEeZAw-ooIZR-zX_WpCbxyCoU,596
+pip/_internal/vcs/__pycache__/__init__.cpython-312.pyc,,
+pip/_internal/vcs/__pycache__/bazaar.cpython-312.pyc,,
+pip/_internal/vcs/__pycache__/git.cpython-312.pyc,,
+pip/_internal/vcs/__pycache__/mercurial.cpython-312.pyc,,
+pip/_internal/vcs/__pycache__/subversion.cpython-312.pyc,,
+pip/_internal/vcs/__pycache__/versioncontrol.cpython-312.pyc,,
+pip/_internal/vcs/bazaar.py,sha256=3W1eHjkYx2vc6boeb2NBh4I_rlGAXM-vrzfNhLm1Rxg,3734
+pip/_internal/vcs/git.py,sha256=TTeqDuzS-_BFSNuUStVWmE2nGDpKuvUhBBJk_CCQXV0,19144
+pip/_internal/vcs/mercurial.py,sha256=w1ZJWLKqNP1onEjkfjlwBVnMqPZNSIER8ayjQcnTq4w,5575
+pip/_internal/vcs/subversion.py,sha256=uUgdPvxmvEB8Qwtjr0Hc0XgFjbiNi5cbvI4vARLOJXo,11787
+pip/_internal/vcs/versioncontrol.py,sha256=Ma_HMZBVveSkeYvxacvqeujnkSIaF1XjxTsS3BwcJ8E,22599
+pip/_internal/wheel_builder.py,sha256=yvEULStZtty9Kplp89tDis3hGdyKQ-2BUbFLmJ_5ink,9010
+pip/_vendor/README.rst,sha256=pKKBwCWhu3M3qQ9dDnsmxb3KdsRr-nWmMq2srbH_Bi0,9394
+pip/_vendor/__init__.py,sha256=WzusPTGWIMeQQWSVJ0h2rafGkVTa9WKJ2HT-2-EoZrU,4907
+pip/_vendor/__pycache__/__init__.cpython-312.pyc,,
+pip/_vendor/cachecontrol/LICENSE.txt,sha256=hu7uh74qQ_P_H1ZJb0UfaSQ5JvAl_tuwM2ZsMExMFhs,558
+pip/_vendor/cachecontrol/__init__.py,sha256=GxwRkm_TQBtPZpfpVK9r6S9dAy2DVnVgDVHJKTiPZ1k,820
+pip/_vendor/cachecontrol/__pycache__/__init__.cpython-312.pyc,,
+pip/_vendor/cachecontrol/__pycache__/_cmd.cpython-312.pyc,,
+pip/_vendor/cachecontrol/__pycache__/adapter.cpython-312.pyc,,
+pip/_vendor/cachecontrol/__pycache__/cache.cpython-312.pyc,,
+pip/_vendor/cachecontrol/__pycache__/controller.cpython-312.pyc,,
+pip/_vendor/cachecontrol/__pycache__/filewrapper.cpython-312.pyc,,
+pip/_vendor/cachecontrol/__pycache__/heuristics.cpython-312.pyc,,
+pip/_vendor/cachecontrol/__pycache__/serialize.cpython-312.pyc,,
+pip/_vendor/cachecontrol/__pycache__/wrapper.cpython-312.pyc,,
+pip/_vendor/cachecontrol/_cmd.py,sha256=iist2EpzJvDVIhMAxXq8iFnTBsiZAd6iplxfmNboNyk,1737
+pip/_vendor/cachecontrol/adapter.py,sha256=W-HW-l01gyCsnxkOyCbqx7sxrWYoBbKrDsKkVVQN6NE,6586
+pip/_vendor/cachecontrol/cache.py,sha256=OXwv7Fn2AwnKNiahJHnjtvaKLndvVLv_-zO-ltlV9qI,1953
+pip/_vendor/cachecontrol/caches/__init__.py,sha256=dtrrroK5BnADR1GWjCZ19aZ0tFsMfvFBtLQQU1sp_ag,303
+pip/_vendor/cachecontrol/caches/__pycache__/__init__.cpython-312.pyc,,
+pip/_vendor/cachecontrol/caches/__pycache__/file_cache.cpython-312.pyc,,
+pip/_vendor/cachecontrol/caches/__pycache__/redis_cache.cpython-312.pyc,,
+pip/_vendor/cachecontrol/caches/file_cache.py,sha256=d8upFmy_zwaCmlbWEVBlLXFddt8Zw8c5SFpxeOZsdfw,4117
+pip/_vendor/cachecontrol/caches/redis_cache.py,sha256=9rmqwtYu_ljVkW6_oLqbC7EaX_a8YT_yLuna-eS0dgo,1386
+pip/_vendor/cachecontrol/controller.py,sha256=xBauC-vUSu5GsJsxD4-W-JaKqqbBz0MN6Zv8PA2N8hI,19102
+pip/_vendor/cachecontrol/filewrapper.py,sha256=DhxC_rSk-beKdbsYhfvBUDovQHX9r3gHH_jP9-q_mKk,4354
+pip/_vendor/cachecontrol/heuristics.py,sha256=gqMXU8w0gQuEQiSdu3Yg-0vd9kW7nrWKbLca75rheGE,4881
+pip/_vendor/cachecontrol/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pip/_vendor/cachecontrol/serialize.py,sha256=HQd2IllQ05HzPkVLMXTF2uX5mjEQjDBkxCqUJUODpZk,5163
+pip/_vendor/cachecontrol/wrapper.py,sha256=hsGc7g8QGQTT-4f8tgz3AM5qwScg6FO0BSdLSRdEvpU,1417
+pip/_vendor/certifi/LICENSE,sha256=6TcW2mucDVpKHfYP5pWzcPBpVgPSH2-D8FPkLPwQyvc,989
+pip/_vendor/certifi/__init__.py,sha256=969deMMS7Uchipr0oO4dbRBUvRi0uNYCn07VmG1aTrg,94
+pip/_vendor/certifi/__main__.py,sha256=1k3Cr95vCxxGRGDljrW3wMdpZdL3Nhf0u1n-k2qdsCY,255
+pip/_vendor/certifi/__pycache__/__init__.cpython-312.pyc,,
+pip/_vendor/certifi/__pycache__/__main__.cpython-312.pyc,,
+pip/_vendor/certifi/__pycache__/core.cpython-312.pyc,,
+pip/_vendor/certifi/cacert.pem,sha256=Tzl1_zCrvzVEO0hgZK6Ly0Hf9wf_31dsdtKS-0WKoKk,270954
+pip/_vendor/certifi/core.py,sha256=gu_ECVI1m3Rq0ytpsNE61hgQGcKaOAt9Rs9G8KsTCOI,3442
+pip/_vendor/certifi/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pip/_vendor/dependency_groups/LICENSE.txt,sha256=GrNuPipLqGMWJThPh-ngkdsfrtA0xbIzJbMjmr8sxSU,1099
+pip/_vendor/dependency_groups/__init__.py,sha256=C3OFu0NGwDzQ4LOmmSOFPsRSvkbBn-mdd4j_5YqJw-s,250
+pip/_vendor/dependency_groups/__main__.py,sha256=UNTM7P5mfVtT7wDi9kOTXWgV3fu3e8bTrt1Qp1jvjKo,1709
+pip/_vendor/dependency_groups/__pycache__/__init__.cpython-312.pyc,,
+pip/_vendor/dependency_groups/__pycache__/__main__.cpython-312.pyc,,
+pip/_vendor/dependency_groups/__pycache__/_implementation.cpython-312.pyc,,
+pip/_vendor/dependency_groups/__pycache__/_lint_dependency_groups.cpython-312.pyc,,
+pip/_vendor/dependency_groups/__pycache__/_pip_wrapper.cpython-312.pyc,,
+pip/_vendor/dependency_groups/__pycache__/_toml_compat.cpython-312.pyc,,
+pip/_vendor/dependency_groups/_implementation.py,sha256=Gqb2DlQELRakeHlKf6QtQSW0M-bcEomxHw4JsvID1ls,8041
+pip/_vendor/dependency_groups/_lint_dependency_groups.py,sha256=yp-DDqKXtbkDTNa0ifa-FmOA8ra24lPZEXftW-R5AuI,1710
+pip/_vendor/dependency_groups/_pip_wrapper.py,sha256=nuVW_w_ntVxpE26ELEvngMY0N04sFLsijXRyZZROFG8,1865
+pip/_vendor/dependency_groups/_toml_compat.py,sha256=BHnXnFacm3DeolsA35GjI6qkDApvua-1F20kv3BfZWE,285
+pip/_vendor/dependency_groups/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pip/_vendor/distlib/LICENSE.txt,sha256=gI4QyKarjesUn_mz-xn0R6gICUYG1xKpylf-rTVSWZ0,14531
+pip/_vendor/distlib/__init__.py,sha256=Deo3uo98aUyIfdKJNqofeSEFWwDzrV2QeGLXLsgq0Ag,625
+pip/_vendor/distlib/__pycache__/__init__.cpython-312.pyc,,
+pip/_vendor/distlib/__pycache__/compat.cpython-312.pyc,,
+pip/_vendor/distlib/__pycache__/resources.cpython-312.pyc,,
+pip/_vendor/distlib/__pycache__/scripts.cpython-312.pyc,,
+pip/_vendor/distlib/__pycache__/util.cpython-312.pyc,,
+pip/_vendor/distlib/compat.py,sha256=2jRSjRI4o-vlXeTK2BCGIUhkc6e9ZGhSsacRM5oseTw,41467
+pip/_vendor/distlib/resources.py,sha256=LwbPksc0A1JMbi6XnuPdMBUn83X7BPuFNWqPGEKI698,10820
+pip/_vendor/distlib/scripts.py,sha256=Qvp76E9Jc3IgyYubnpqI9fS7eseGOe4FjpeVKqKt9Iw,18612
+pip/_vendor/distlib/t32.exe,sha256=a0GV5kCoWsMutvliiCKmIgV98eRZ33wXoS-XrqvJQVs,97792
+pip/_vendor/distlib/t64-arm.exe,sha256=68TAa32V504xVBnufojh0PcenpR3U4wAqTqf-MZqbPw,182784
+pip/_vendor/distlib/t64.exe,sha256=gaYY8hy4fbkHYTTnA4i26ct8IQZzkBG2pRdy0iyuBrc,108032
+pip/_vendor/distlib/util.py,sha256=vMPGvsS4j9hF6Y9k3Tyom1aaHLb0rFmZAEyzeAdel9w,66682
+pip/_vendor/distlib/w32.exe,sha256=R4csx3-OGM9kL4aPIzQKRo5TfmRSHZo6QWyLhDhNBks,91648
+pip/_vendor/distlib/w64-arm.exe,sha256=xdyYhKj0WDcVUOCb05blQYvzdYIKMbmJn2SZvzkcey4,168448
+pip/_vendor/distlib/w64.exe,sha256=ejGf-rojoBfXseGLpya6bFTFPWRG21X5KvU8J5iU-K0,101888
+pip/_vendor/distro/LICENSE,sha256=y16Ofl9KOYjhBjwULGDcLfdWBfTEZRXnduOspt-XbhQ,11325
+pip/_vendor/distro/__init__.py,sha256=2fHjF-SfgPvjyNZ1iHh_wjqWdR_Yo5ODHwZC0jLBPhc,981
+pip/_vendor/distro/__main__.py,sha256=bu9d3TifoKciZFcqRBuygV3GSuThnVD_m2IK4cz96Vs,64
+pip/_vendor/distro/__pycache__/__init__.cpython-312.pyc,,
+pip/_vendor/distro/__pycache__/__main__.cpython-312.pyc,,
+pip/_vendor/distro/__pycache__/distro.cpython-312.pyc,,
+pip/_vendor/distro/distro.py,sha256=XqbefacAhDT4zr_trnbA15eY8vdK4GTghgmvUGrEM_4,49430
+pip/_vendor/distro/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pip/_vendor/idna/LICENSE.md,sha256=t6M2q_OwThgOwGXN0W5wXQeeHMehT5EKpukYfza5zYc,1541
+pip/_vendor/idna/__init__.py,sha256=MPqNDLZbXqGaNdXxAFhiqFPKEQXju2jNQhCey6-5eJM,868
+pip/_vendor/idna/__pycache__/__init__.cpython-312.pyc,,
+pip/_vendor/idna/__pycache__/codec.cpython-312.pyc,,
+pip/_vendor/idna/__pycache__/compat.cpython-312.pyc,,
+pip/_vendor/idna/__pycache__/core.cpython-312.pyc,,
+pip/_vendor/idna/__pycache__/idnadata.cpython-312.pyc,,
+pip/_vendor/idna/__pycache__/intranges.cpython-312.pyc,,
+pip/_vendor/idna/__pycache__/package_data.cpython-312.pyc,,
+pip/_vendor/idna/__pycache__/uts46data.cpython-312.pyc,,
+pip/_vendor/idna/codec.py,sha256=M2SGWN7cs_6B32QmKTyTN6xQGZeYQgQ2wiX3_DR6loE,3438
+pip/_vendor/idna/compat.py,sha256=RzLy6QQCdl9784aFhb2EX9EKGCJjg0P3PilGdeXXcx8,316
+pip/_vendor/idna/core.py,sha256=P26_XVycuMTZ1R2mNK1ZREVzM5mvTzdabBXfyZVU1Lc,13246
+pip/_vendor/idna/idnadata.py,sha256=SG8jhaGE53iiD6B49pt2pwTv_UvClciWE-N54oR2p4U,79623
+pip/_vendor/idna/intranges.py,sha256=amUtkdhYcQG8Zr-CoMM_kVRacxkivC1WgxN1b63KKdU,1898
+pip/_vendor/idna/package_data.py,sha256=_CUavOxobnbyNG2FLyHoN8QHP3QM9W1tKuw7eq9QwBk,21
+pip/_vendor/idna/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pip/_vendor/idna/uts46data.py,sha256=H9J35VkD0F9L9mKOqjeNGd2A-Va6FlPoz6Jz4K7h-ps,243725
+pip/_vendor/msgpack/COPYING,sha256=SS3tuoXaWHL3jmCRvNH-pHTWYNNay03ulkuKqz8AdCc,614
+pip/_vendor/msgpack/__init__.py,sha256=RA8gcqK17YpkxBnNwXJVa1oa2LygWDgfF1nA1NPw3mo,1109
+pip/_vendor/msgpack/__pycache__/__init__.cpython-312.pyc,,
+pip/_vendor/msgpack/__pycache__/exceptions.cpython-312.pyc,,
+pip/_vendor/msgpack/__pycache__/ext.cpython-312.pyc,,
+pip/_vendor/msgpack/__pycache__/fallback.cpython-312.pyc,,
+pip/_vendor/msgpack/exceptions.py,sha256=dCTWei8dpkrMsQDcjQk74ATl9HsIBH0ybt8zOPNqMYc,1081
+pip/_vendor/msgpack/ext.py,sha256=kteJv03n9tYzd5oo3xYopVTo4vRaAxonBQQJhXohZZo,5726
+pip/_vendor/msgpack/fallback.py,sha256=0g1Pzp0vtmBEmJ5w9F3s_-JMVURP8RS4G1cc5TRaAsI,32390
+pip/_vendor/packaging/LICENSE,sha256=ytHvW9NA1z4HS6YU0m996spceUDD2MNIUuZcSQlobEg,197
+pip/_vendor/packaging/LICENSE.APACHE,sha256=DVQuDIgE45qn836wDaWnYhSdxoLXgpRRKH4RuTjpRZQ,10174
+pip/_vendor/packaging/LICENSE.BSD,sha256=tw5-m3QvHMb5SLNMFqo5_-zpQZY2S8iP8NIYDwAo-sU,1344
+pip/_vendor/packaging/__init__.py,sha256=y4lVbpeBzCGk-IPDw5BGBZ_b0P3ukEEJZAbGYc6Ey8c,494
+pip/_vendor/packaging/__pycache__/__init__.cpython-312.pyc,,
+pip/_vendor/packaging/__pycache__/_elffile.cpython-312.pyc,,
+pip/_vendor/packaging/__pycache__/_manylinux.cpython-312.pyc,,
+pip/_vendor/packaging/__pycache__/_musllinux.cpython-312.pyc,,
+pip/_vendor/packaging/__pycache__/_parser.cpython-312.pyc,,
+pip/_vendor/packaging/__pycache__/_structures.cpython-312.pyc,,
+pip/_vendor/packaging/__pycache__/_tokenizer.cpython-312.pyc,,
+pip/_vendor/packaging/__pycache__/markers.cpython-312.pyc,,
+pip/_vendor/packaging/__pycache__/metadata.cpython-312.pyc,,
+pip/_vendor/packaging/__pycache__/pylock.cpython-312.pyc,,
+pip/_vendor/packaging/__pycache__/requirements.cpython-312.pyc,,
+pip/_vendor/packaging/__pycache__/specifiers.cpython-312.pyc,,
+pip/_vendor/packaging/__pycache__/tags.cpython-312.pyc,,
+pip/_vendor/packaging/__pycache__/utils.cpython-312.pyc,,
+pip/_vendor/packaging/__pycache__/version.cpython-312.pyc,,
+pip/_vendor/packaging/_elffile.py,sha256=-sKkptYqzYw2-x3QByJa5mB4rfPWu1pxkZHRx1WAFCY,3211
+pip/_vendor/packaging/_manylinux.py,sha256=Hf6nB0cOrayEs96-p3oIXAgGnFquv20DO5l-o2_Xnv0,9559
+pip/_vendor/packaging/_musllinux.py,sha256=Z6swjH3MA7XS3qXnmMN7QPhqP3fnoYI0eQ18e9-HgAE,2707
+pip/_vendor/packaging/_parser.py,sha256=U_DajsEx2VoC_F46fSVV3hDKNCWoQYkPkasO3dld0ig,10518
+pip/_vendor/packaging/_structures.py,sha256=Hn49Ta8zV9Wo8GiCL8Nl2ARZY983Un3pruZGVNldPwE,1514
+pip/_vendor/packaging/_tokenizer.py,sha256=M8EwNIdXeL9NMFuFrQtiOKwjka_xFx8KjRQnfE8O_z8,5421
+pip/_vendor/packaging/licenses/__init__.py,sha256=TwXLHZCXwSgdFwRLPxW602T6mSieunSFHM6fp8pgW78,5819
+pip/_vendor/packaging/licenses/__pycache__/__init__.cpython-312.pyc,,
+pip/_vendor/packaging/licenses/__pycache__/_spdx.cpython-312.pyc,,
+pip/_vendor/packaging/licenses/_spdx.py,sha256=WW7DXiyg68up_YND_wpRYlr1SHhiV4FfJLQffghhMxQ,51122
+pip/_vendor/packaging/markers.py,sha256=ZX-cLvW1S3cZcEc0fHI4z7zSx5U2T19yMpDP_mE-CYw,12771
+pip/_vendor/packaging/metadata.py,sha256=CWVZpN_HfoYMSSDuCP7igOvGgqA9AOmpW8f3qTisfnc,39360
+pip/_vendor/packaging/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pip/_vendor/packaging/pylock.py,sha256=-R1uNfJ4PaLto7Mg62YsGOHgvskuiIEqPwxOywl42Jk,22537
+pip/_vendor/packaging/requirements.py,sha256=PMCAWD8aNMnVD-6uZMedhBuAVX2573eZ4yPBLXmz04I,2870
+pip/_vendor/packaging/specifiers.py,sha256=tF2nC-jwW94FYe6So9dNGenQx1Hdif7ErmWlVp1QiXE,40821
+pip/_vendor/packaging/tags.py,sha256=cXLV1pJD3UtJlDg7Wz3zrfdQhRZqr8jumSAKKAAd2xE,22856
+pip/_vendor/packaging/utils.py,sha256=N4c6oZzFJy6klTZ3AnkNz7sSkJesuFWPp68LA3B5dAo,5040
+pip/_vendor/packaging/version.py,sha256=RVRKq8_GD5Bcak6E1kGG8K7siNZYW9n_XK8M2ZLl0H8,23284
+pip/_vendor/pkg_resources/LICENSE,sha256=htoPAa6uRjSKPD1GUZXcHOzN55956HdppkuNoEsqR0E,1023
+pip/_vendor/pkg_resources/__init__.py,sha256=vbTJ0_ruUgGxQjlEqsruFmiNPVyh2t9q-zyTDT053xI,124451
+pip/_vendor/pkg_resources/__pycache__/__init__.cpython-312.pyc,,
+pip/_vendor/platformdirs/LICENSE,sha256=KeD9YukphQ6G6yjD_czwzv30-pSHkBHP-z0NS-1tTbY,1089
+pip/_vendor/platformdirs/__init__.py,sha256=UfeSHWl8AeTtbOBOoHAxK4dODOWkZtfy-m_i7cWdJ8c,22344
+pip/_vendor/platformdirs/__main__.py,sha256=jBJ8zb7Mpx5ebcqF83xrpO94MaeCpNGHVf9cvDN2JLg,1505
+pip/_vendor/platformdirs/__pycache__/__init__.cpython-312.pyc,,
+pip/_vendor/platformdirs/__pycache__/__main__.cpython-312.pyc,,
+pip/_vendor/platformdirs/__pycache__/android.cpython-312.pyc,,
+pip/_vendor/platformdirs/__pycache__/api.cpython-312.pyc,,
+pip/_vendor/platformdirs/__pycache__/macos.cpython-312.pyc,,
+pip/_vendor/platformdirs/__pycache__/unix.cpython-312.pyc,,
+pip/_vendor/platformdirs/__pycache__/version.cpython-312.pyc,,
+pip/_vendor/platformdirs/__pycache__/windows.cpython-312.pyc,,
+pip/_vendor/platformdirs/android.py,sha256=r0DshVBf-RO1jXJGX8C4Til7F1XWt-bkdWMgmvEiaYg,9013
+pip/_vendor/platformdirs/api.py,sha256=wPHOlwOsfz2oqQZ6A2FcCu5kEAj-JondzoNOHYFQ0h8,9281
+pip/_vendor/platformdirs/macos.py,sha256=0XoOgin1NK7Qki7iskD-oS8xKxw6bXgoKEgdqpCRAFQ,6322
+pip/_vendor/platformdirs/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pip/_vendor/platformdirs/unix.py,sha256=WZmkUA--L3JNRGmz32s35YfoD3ica6xKIPdCV_HhLcs,10458
+pip/_vendor/platformdirs/version.py,sha256=BI_dKLSMwlkl57vlxZnT8oVjPiUC2W_sdx_8_h99HeQ,704
+pip/_vendor/platformdirs/windows.py,sha256=XvCfklGUMVxJbXit51jpYMN-lNeScPB82qS1CAeplL0,10362
+pip/_vendor/pygments/LICENSE,sha256=qdZvHVJt8C4p3Oc0NtNOVuhjL0bCdbvf_HBWnogvnxc,1331
+pip/_vendor/pygments/__init__.py,sha256=8uNqJCCwXqbEx5aSsBr0FykUQOBDKBihO5mPqiw1aqo,2983
+pip/_vendor/pygments/__main__.py,sha256=WrndpSe6i1ckX_SQ1KaxD9CTKGzD0EuCOFxcbwFpoLU,353
+pip/_vendor/pygments/__pycache__/__init__.cpython-312.pyc,,
+pip/_vendor/pygments/__pycache__/__main__.cpython-312.pyc,,
+pip/_vendor/pygments/__pycache__/console.cpython-312.pyc,,
+pip/_vendor/pygments/__pycache__/filter.cpython-312.pyc,,
+pip/_vendor/pygments/__pycache__/formatter.cpython-312.pyc,,
+pip/_vendor/pygments/__pycache__/lexer.cpython-312.pyc,,
+pip/_vendor/pygments/__pycache__/modeline.cpython-312.pyc,,
+pip/_vendor/pygments/__pycache__/plugin.cpython-312.pyc,,
+pip/_vendor/pygments/__pycache__/regexopt.cpython-312.pyc,,
+pip/_vendor/pygments/__pycache__/scanner.cpython-312.pyc,,
+pip/_vendor/pygments/__pycache__/sphinxext.cpython-312.pyc,,
+pip/_vendor/pygments/__pycache__/style.cpython-312.pyc,,
+pip/_vendor/pygments/__pycache__/token.cpython-312.pyc,,
+pip/_vendor/pygments/__pycache__/unistring.cpython-312.pyc,,
+pip/_vendor/pygments/__pycache__/util.cpython-312.pyc,,
+pip/_vendor/pygments/console.py,sha256=AagDWqwea2yBWf10KC9ptBgMpMjxKp8yABAmh-NQOVk,1718
+pip/_vendor/pygments/filter.py,sha256=YLtpTnZiu07nY3oK9nfR6E9Y1FBHhP5PX8gvkJWcfag,1910
+pip/_vendor/pygments/filters/__init__.py,sha256=4U4jtA0X3iP83uQnB9-TI-HDSw8E8y8zMYHa0UjbbaI,40392
+pip/_vendor/pygments/filters/__pycache__/__init__.cpython-312.pyc,,
+pip/_vendor/pygments/formatter.py,sha256=KZQMmyo_xkOIkQG8g66LYEkBh1bx7a0HyGCBcvhI9Ew,4390
+pip/_vendor/pygments/formatters/__init__.py,sha256=KTwBmnXlaopJhQDOemVHYHskiDghuq-08YtP6xPNJPg,5385
+pip/_vendor/pygments/formatters/__pycache__/__init__.cpython-312.pyc,,
+pip/_vendor/pygments/formatters/__pycache__/_mapping.cpython-312.pyc,,
+pip/_vendor/pygments/formatters/_mapping.py,sha256=1Cw37FuQlNacnxRKmtlPX4nyLoX9_ttko5ZwscNUZZ4,4176
+pip/_vendor/pygments/lexer.py,sha256=_kBrOJ_NT5Tl0IVM0rA9c8eysP6_yrlGzEQI0eVYB-A,35349
+pip/_vendor/pygments/lexers/__init__.py,sha256=wbIME35GH7bI1B9rNPJFqWT-ij_RApZDYPUlZycaLzA,12115
+pip/_vendor/pygments/lexers/__pycache__/__init__.cpython-312.pyc,,
+pip/_vendor/pygments/lexers/__pycache__/_mapping.cpython-312.pyc,,
+pip/_vendor/pygments/lexers/__pycache__/python.cpython-312.pyc,,
+pip/_vendor/pygments/lexers/_mapping.py,sha256=l4tCXM8e9aPC2BD6sjIr0deT-J-z5tHgCwL-p1fS0PE,77602
+pip/_vendor/pygments/lexers/python.py,sha256=vxjn1cOHclIKJKxoyiBsQTY65GHbkZtZRuKQ2AVCKaw,53853
+pip/_vendor/pygments/modeline.py,sha256=K5eSkR8GS1r5OkXXTHOcV0aM_6xpk9eWNEIAW-OOJ2g,1005
+pip/_vendor/pygments/plugin.py,sha256=tPx0rJCTIZ9ioRgLNYG4pifCbAwTRUZddvLw-NfAk2w,1891
+pip/_vendor/pygments/regexopt.py,sha256=wXaP9Gjp_hKAdnICqoDkRxAOQJSc4v3X6mcxx3z-TNs,3072
+pip/_vendor/pygments/scanner.py,sha256=nNcETRR1tRuiTaHmHSTTECVYFPcLf6mDZu1e4u91A9E,3092
+pip/_vendor/pygments/sphinxext.py,sha256=5x7Zh9YlU6ISJ31dMwduiaanb5dWZnKg3MyEQsseNnQ,7981
+pip/_vendor/pygments/style.py,sha256=PlOZqlsnTVd58RGy50vkA2cXQ_lP5bF5EGMEBTno6DA,6420
+pip/_vendor/pygments/styles/__init__.py,sha256=x9ebctfyvCAFpMTlMJ5YxwcNYBzjgq6zJaKkNm78r4M,2042
+pip/_vendor/pygments/styles/__pycache__/__init__.cpython-312.pyc,,
+pip/_vendor/pygments/styles/__pycache__/_mapping.cpython-312.pyc,,
+pip/_vendor/pygments/styles/_mapping.py,sha256=6lovFUE29tz6EsV3XYY4hgozJ7q1JL7cfO3UOlgnS8w,3312
+pip/_vendor/pygments/token.py,sha256=WbdWGhYm_Vosb0DDxW9lHNPgITXfWTsQmHt6cy9RbcM,6226
+pip/_vendor/pygments/unistring.py,sha256=al-_rBemRuGvinsrM6atNsHTmJ6DUbw24q2O2Ru1cBc,63208
+pip/_vendor/pygments/util.py,sha256=oRtSpiAo5jM9ulntkvVbgXUdiAW57jnuYGB7t9fYuhc,10031
+pip/_vendor/pyproject_hooks/LICENSE,sha256=GyKwSbUmfW38I6Z79KhNjsBLn9-xpR02DkK0NCyLQVQ,1081
+pip/_vendor/pyproject_hooks/__init__.py,sha256=cPB_a9LXz5xvsRbX1o2qyAdjLatZJdQ_Lc5McNX-X7Y,691
+pip/_vendor/pyproject_hooks/__pycache__/__init__.cpython-312.pyc,,
+pip/_vendor/pyproject_hooks/__pycache__/_impl.cpython-312.pyc,,
+pip/_vendor/pyproject_hooks/_impl.py,sha256=jY-raxnmyRyB57ruAitrJRUzEexuAhGTpgMygqx67Z4,14936
+pip/_vendor/pyproject_hooks/_in_process/__init__.py,sha256=MJNPpfIxcO-FghxpBbxkG1rFiQf6HOUbV4U5mq0HFns,557
+pip/_vendor/pyproject_hooks/_in_process/__pycache__/__init__.cpython-312.pyc,,
+pip/_vendor/pyproject_hooks/_in_process/__pycache__/_in_process.cpython-312.pyc,,
+pip/_vendor/pyproject_hooks/_in_process/_in_process.py,sha256=qcXMhmx__MIJq10gGHW3mA4Tl8dy8YzHMccwnNoKlw0,12216
+pip/_vendor/pyproject_hooks/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pip/_vendor/requests/LICENSE,sha256=CeipvOyAZxBGUsFoaFqwkx54aPnIKEtm9a5u2uXxEws,10142
+pip/_vendor/requests/__init__.py,sha256=HlB_HzhrzGtfD_aaYUwUh1zWXLZ75_YCLyit75d0Vz8,5057
+pip/_vendor/requests/__pycache__/__init__.cpython-312.pyc,,
+pip/_vendor/requests/__pycache__/__version__.cpython-312.pyc,,
+pip/_vendor/requests/__pycache__/_internal_utils.cpython-312.pyc,,
+pip/_vendor/requests/__pycache__/adapters.cpython-312.pyc,,
+pip/_vendor/requests/__pycache__/api.cpython-312.pyc,,
+pip/_vendor/requests/__pycache__/auth.cpython-312.pyc,,
+pip/_vendor/requests/__pycache__/certs.cpython-312.pyc,,
+pip/_vendor/requests/__pycache__/compat.cpython-312.pyc,,
+pip/_vendor/requests/__pycache__/cookies.cpython-312.pyc,,
+pip/_vendor/requests/__pycache__/exceptions.cpython-312.pyc,,
+pip/_vendor/requests/__pycache__/help.cpython-312.pyc,,
+pip/_vendor/requests/__pycache__/hooks.cpython-312.pyc,,
+pip/_vendor/requests/__pycache__/models.cpython-312.pyc,,
+pip/_vendor/requests/__pycache__/packages.cpython-312.pyc,,
+pip/_vendor/requests/__pycache__/sessions.cpython-312.pyc,,
+pip/_vendor/requests/__pycache__/status_codes.cpython-312.pyc,,
+pip/_vendor/requests/__pycache__/structures.cpython-312.pyc,,
+pip/_vendor/requests/__pycache__/utils.cpython-312.pyc,,
+pip/_vendor/requests/__version__.py,sha256=QKDceK8K_ujqwDDc3oYrR0odOBYgKVOQQ5vFap_G_cg,435
+pip/_vendor/requests/_internal_utils.py,sha256=nMQymr4hs32TqVo5AbCrmcJEhvPUh7xXlluyqwslLiQ,1495
+pip/_vendor/requests/adapters.py,sha256=2MLFOK9GpYNhiTd6zLDUrAgSkIB-76i6pmSuUJjHC2w,26429
+pip/_vendor/requests/api.py,sha256=_Zb9Oa7tzVIizTKwFrPjDEY9ejtm_OnSRERnADxGsQs,6449
+pip/_vendor/requests/auth.py,sha256=kF75tqnLctZ9Mf_hm9TZIj4cQWnN5uxRz8oWsx5wmR0,10186
+pip/_vendor/requests/certs.py,sha256=kHDlkK_beuHXeMPc5jta2wgl8gdKeUWt5f2nTDVrvt8,441
+pip/_vendor/requests/compat.py,sha256=QfbmdTFiZzjSHMXiMrd4joCRU6RabtQ9zIcPoVaHIus,1822
+pip/_vendor/requests/cookies.py,sha256=bNi-iqEj4NPZ00-ob-rHvzkvObzN3lEpgw3g6paS3Xw,18590
+pip/_vendor/requests/exceptions.py,sha256=D1wqzYWne1mS2rU43tP9CeN1G7QAy7eqL9o1god6Ejw,4272
+pip/_vendor/requests/help.py,sha256=hRKaf9u0G7fdwrqMHtF3oG16RKktRf6KiwtSq2Fo1_0,3813
+pip/_vendor/requests/hooks.py,sha256=CiuysiHA39V5UfcCBXFIx83IrDpuwfN9RcTUgv28ftQ,733
+pip/_vendor/requests/models.py,sha256=taljlg6vJ4b-xMu2TaMNFFkaiwMex_VsEQ6qUTN3wzY,35575
+pip/_vendor/requests/packages.py,sha256=_ZQDCJTJ8SP3kVWunSqBsRZNPzj2c1WFVqbdr08pz3U,1057
+pip/_vendor/requests/sessions.py,sha256=Cl1dpEnOfwrzzPbku-emepNeN4Rt_0_58Iy2x-JGTm8,30503
+pip/_vendor/requests/status_codes.py,sha256=iJUAeA25baTdw-6PfD0eF4qhpINDJRJI-yaMqxs4LEI,4322
+pip/_vendor/requests/structures.py,sha256=-IbmhVz06S-5aPSZuUthZ6-6D9XOjRuTXHOabY041XM,2912
+pip/_vendor/requests/utils.py,sha256=WS3wHSQaaEfceu1syiFo5jf4e_CWKUTep_IabOVI_J0,33225
+pip/_vendor/resolvelib/LICENSE,sha256=84j9OMrRMRLB3A9mm76A5_hFQe26-3LzAw0sp2QsPJ0,751
+pip/_vendor/resolvelib/__init__.py,sha256=yoX-d4STvwGGCiQRE5cJC9Cter69SgVgqClxOCvSP7M,541
+pip/_vendor/resolvelib/__pycache__/__init__.cpython-312.pyc,,
+pip/_vendor/resolvelib/__pycache__/providers.cpython-312.pyc,,
+pip/_vendor/resolvelib/__pycache__/reporters.cpython-312.pyc,,
+pip/_vendor/resolvelib/__pycache__/structs.cpython-312.pyc,,
+pip/_vendor/resolvelib/providers.py,sha256=pIWJbIdJJ9GFtNbtwTH0Ia43Vj6hYCEJj2DOLue15FM,8914
+pip/_vendor/resolvelib/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pip/_vendor/resolvelib/reporters.py,sha256=pNJf4nFxLpAeKxlBUi2GEj0a2Ij1nikY0UabTKXesT4,2037
+pip/_vendor/resolvelib/resolvers/__init__.py,sha256=728M3EvmnPbVXS7ExXlv2kMu6b7wEsoPutEfl-uVk_I,640
+pip/_vendor/resolvelib/resolvers/__pycache__/__init__.cpython-312.pyc,,
+pip/_vendor/resolvelib/resolvers/__pycache__/abstract.cpython-312.pyc,,
+pip/_vendor/resolvelib/resolvers/__pycache__/criterion.cpython-312.pyc,,
+pip/_vendor/resolvelib/resolvers/__pycache__/exceptions.cpython-312.pyc,,
+pip/_vendor/resolvelib/resolvers/__pycache__/resolution.cpython-312.pyc,,
+pip/_vendor/resolvelib/resolvers/abstract.py,sha256=CNeQPnpAudY77nmzOkONSmAgRlzIf06X-X9mvRYODms,1543
+pip/_vendor/resolvelib/resolvers/criterion.py,sha256=lcmZGv5sKHOnFD_RzZwvlGSj19MeA-5rCMpdf2Sgw7Y,1768
+pip/_vendor/resolvelib/resolvers/exceptions.py,sha256=ln_jaQtgLlRUSFY627yiHG2gD7AgaXzRKaElFVh7fDQ,1768
+pip/_vendor/resolvelib/resolvers/resolution.py,sha256=3J_zkW-sD3EY-BlNXjyln__njpyH5n0UZJT6uV7CheA,24212
+pip/_vendor/resolvelib/structs.py,sha256=pu-EJiR2IBITr2SQeNPRa0rXhjlStfmO_GEgAhr3004,6420
+pip/_vendor/rich/LICENSE,sha256=3u18F6QxgVgZCj6iOcyHmlpQJxzruYrnAl9I--WNyhU,1056
+pip/_vendor/rich/__init__.py,sha256=dRxjIL-SbFVY0q3IjSMrfgBTHrm1LZDgLOygVBwiYZc,6090
+pip/_vendor/rich/__main__.py,sha256=e_aVC-tDzarWQW9SuZMuCgBr6ODV_iDNV2Wh2xkxOlw,7896
+pip/_vendor/rich/__pycache__/__init__.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/__main__.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/_cell_widths.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/_emoji_codes.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/_emoji_replace.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/_export_format.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/_extension.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/_fileno.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/_inspect.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/_log_render.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/_loop.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/_null_file.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/_palettes.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/_pick.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/_ratio.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/_spinners.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/_stack.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/_timer.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/_win32_console.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/_windows.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/_windows_renderer.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/_wrap.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/abc.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/align.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/ansi.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/bar.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/box.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/cells.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/color.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/color_triplet.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/columns.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/console.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/constrain.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/containers.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/control.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/default_styles.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/diagnose.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/emoji.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/errors.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/file_proxy.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/filesize.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/highlighter.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/json.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/jupyter.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/layout.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/live.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/live_render.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/logging.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/markup.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/measure.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/padding.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/pager.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/palette.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/panel.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/pretty.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/progress.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/progress_bar.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/prompt.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/protocol.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/region.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/repr.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/rule.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/scope.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/screen.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/segment.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/spinner.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/status.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/style.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/styled.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/syntax.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/table.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/terminal_theme.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/text.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/theme.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/themes.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/traceback.cpython-312.pyc,,
+pip/_vendor/rich/__pycache__/tree.cpython-312.pyc,,
+pip/_vendor/rich/_cell_widths.py,sha256=fbmeyetEdHjzE_Vx2l1uK7tnPOhMs2X1lJfO3vsKDpA,10209
+pip/_vendor/rich/_emoji_codes.py,sha256=hu1VL9nbVdppJrVoijVshRlcRRe_v3dju3Mmd2sKZdY,140235
+pip/_vendor/rich/_emoji_replace.py,sha256=n-kcetsEUx2ZUmhQrfeMNc-teeGhpuSQ5F8VPBsyvDo,1064
+pip/_vendor/rich/_export_format.py,sha256=RI08pSrm5tBSzPMvnbTqbD9WIalaOoN5d4M1RTmLq1Y,2128
+pip/_vendor/rich/_extension.py,sha256=Xt47QacCKwYruzjDi-gOBq724JReDj9Cm9xUi5fr-34,265
+pip/_vendor/rich/_fileno.py,sha256=HWZxP5C2ajMbHryvAQZseflVfQoGzsKOHzKGsLD8ynQ,799
+pip/_vendor/rich/_inspect.py,sha256=ROT0PLC2GMWialWZkqJIjmYq7INRijQQkoSokWTaAiI,9656
+pip/_vendor/rich/_log_render.py,sha256=1ByI0PA1ZpxZY3CGJOK54hjlq4X-Bz_boIjIqCd8Kns,3225
+pip/_vendor/rich/_loop.py,sha256=hV_6CLdoPm0va22Wpw4zKqM0RYsz3TZxXj0PoS-9eDQ,1236
+pip/_vendor/rich/_null_file.py,sha256=ADGKp1yt-k70FMKV6tnqCqecB-rSJzp-WQsD7LPL-kg,1394
+pip/_vendor/rich/_palettes.py,sha256=cdev1JQKZ0JvlguV9ipHgznTdnvlIzUFDBb0It2PzjI,7063
+pip/_vendor/rich/_pick.py,sha256=evDt8QN4lF5CiwrUIXlOJCntitBCOsI3ZLPEIAVRLJU,423
+pip/_vendor/rich/_ratio.py,sha256=IOtl78sQCYZsmHyxhe45krkb68u9xVz7zFsXVJD-b2Y,5325
+pip/_vendor/rich/_spinners.py,sha256=U2r1_g_1zSjsjiUdAESc2iAMc3i4ri_S8PYP6kQ5z1I,19919
+pip/_vendor/rich/_stack.py,sha256=-C8OK7rxn3sIUdVwxZBBpeHhIzX0eI-VM3MemYfaXm0,351
+pip/_vendor/rich/_timer.py,sha256=zelxbT6oPFZnNrwWPpc1ktUeAT-Vc4fuFcRZLQGLtMI,417
+pip/_vendor/rich/_win32_console.py,sha256=BSaDRIMwBLITn_m0mTRLPqME5q-quGdSMuYMpYeYJwc,22755
+pip/_vendor/rich/_windows.py,sha256=aBwaD_S56SbgopIvayVmpk0Y28uwY2C5Bab1wl3Bp-I,1925
+pip/_vendor/rich/_windows_renderer.py,sha256=t74ZL3xuDCP3nmTp9pH1L5LiI2cakJuQRQleHCJerlk,2783
+pip/_vendor/rich/_wrap.py,sha256=FlSsom5EX0LVkA3KWy34yHnCfLtqX-ZIepXKh-70rpc,3404
+pip/_vendor/rich/abc.py,sha256=ON-E-ZqSSheZ88VrKX2M3PXpFbGEUUZPMa_Af0l-4f0,890
+pip/_vendor/rich/align.py,sha256=dg-7uY0ukMLLlUEsBDRLva22_sQgIJD4BK0dmZHFHug,10324
+pip/_vendor/rich/ansi.py,sha256=Avs1LHbSdcyOvDOdpELZUoULcBiYewY76eNBp6uFBhs,6921
+pip/_vendor/rich/bar.py,sha256=ldbVHOzKJOnflVNuv1xS7g6dLX2E3wMnXkdPbpzJTcs,3263
+pip/_vendor/rich/box.py,sha256=kmavBc_dn73L_g_8vxWSwYJD2uzBXOUFTtJOfpbczcM,10686
+pip/_vendor/rich/cells.py,sha256=KrQkj5-LghCCpJLSNQIyAZjndc4bnEqOEmi5YuZ9UCY,5130
+pip/_vendor/rich/color.py,sha256=3HSULVDj7qQkXUdFWv78JOiSZzfy5y1nkcYhna296V0,18211
+pip/_vendor/rich/color_triplet.py,sha256=3lhQkdJbvWPoLDO-AnYImAWmJvV5dlgYNCVZ97ORaN4,1054
+pip/_vendor/rich/columns.py,sha256=HUX0KcMm9dsKNi11fTbiM_h2iDtl8ySCaVcxlalEzq8,7131
+pip/_vendor/rich/console.py,sha256=t9azZpmRMVU5cphVBZSShNsmBxd2-IAWcTTlhor-E1s,100849
+pip/_vendor/rich/constrain.py,sha256=1VIPuC8AgtKWrcncQrjBdYqA3JVWysu6jZo1rrh7c7Q,1288
+pip/_vendor/rich/containers.py,sha256=c_56TxcedGYqDepHBMTuZdUIijitAQgnox-Qde0Z1qo,5502
+pip/_vendor/rich/control.py,sha256=EUTSUFLQbxY6Zmo_sdM-5Ls323vIHTBfN8TPulqeHUY,6487
+pip/_vendor/rich/default_styles.py,sha256=khQFqqaoDs3bprMqWpHw8nO5UpG2DN6QtuTd6LzZwYc,8257
+pip/_vendor/rich/diagnose.py,sha256=fJl1TItRn19gGwouqTg-8zPUW3YqQBqGltrfPQs1H9w,1025
+pip/_vendor/rich/emoji.py,sha256=Wd4bQubZdSy6-PyrRQNuMHtn2VkljK9uPZPVlu2cmx0,2367
+pip/_vendor/rich/errors.py,sha256=5pP3Kc5d4QJ_c0KFsxrfyhjiPVe7J1zOqSFbFAzcV-Y,642
+pip/_vendor/rich/file_proxy.py,sha256=Tl9THMDZ-Pk5Wm8sI1gGg_U5DhusmxD-FZ0fUbcU0W0,1683
+pip/_vendor/rich/filesize.py,sha256=_iz9lIpRgvW7MNSeCZnLg-HwzbP4GETg543WqD8SFs0,2484
+pip/_vendor/rich/highlighter.py,sha256=G_sn-8DKjM1sEjLG_oc4ovkWmiUpWvj8bXi0yed2LnY,9586
+pip/_vendor/rich/json.py,sha256=vVEoKdawoJRjAFayPwXkMBPLy7RSTs-f44wSQDR2nJ0,5031
+pip/_vendor/rich/jupyter.py,sha256=QyoKoE_8IdCbrtiSHp9TsTSNyTHY0FO5whE7jOTd9UE,3252
+pip/_vendor/rich/layout.py,sha256=ajkSFAtEVv9EFTcFs-w4uZfft7nEXhNzL7ZVdgrT5rI,14004
+pip/_vendor/rich/live.py,sha256=tF3ukAAJZ_N2ZbGclqZ-iwLoIoZ8f0HHUz79jAyJqj8,15180
+pip/_vendor/rich/live_render.py,sha256=It_39YdzrBm8o3LL0kaGorPFg-BfZWAcrBjLjFokbx4,3521
+pip/_vendor/rich/logging.py,sha256=5KaPPSMP9FxcXPBcKM4cGd_zW78PMgf-YbMVnvfSw0o,12468
+pip/_vendor/rich/markup.py,sha256=3euGKP5s41NCQwaSjTnJxus5iZMHjxpIM0W6fCxra38,8451
+pip/_vendor/rich/measure.py,sha256=HmrIJX8sWRTHbgh8MxEay_83VkqNW_70s8aKP5ZcYI8,5305
+pip/_vendor/rich/padding.py,sha256=KVEI3tOwo9sgK1YNSuH__M1_jUWmLZwRVV_KmOtVzyM,4908
+pip/_vendor/rich/pager.py,sha256=SO_ETBFKbg3n_AgOzXm41Sv36YxXAyI3_R-KOY2_uSc,828
+pip/_vendor/rich/palette.py,sha256=lInvR1ODDT2f3UZMfL1grq7dY_pDdKHw4bdUgOGaM4Y,3396
+pip/_vendor/rich/panel.py,sha256=9sQl00hPIqH5G2gALQo4NepFwpP0k9wT-s_gOms5pIc,11157
+pip/_vendor/rich/pretty.py,sha256=gy3S72u4FRg2ytoo7N1ZDWDIvB4unbzd5iUGdgm-8fc,36391
+pip/_vendor/rich/progress.py,sha256=CUc2lkU-X59mVdGfjMCBkZeiGPL3uxdONjhNJF2T7wY,60408
+pip/_vendor/rich/progress_bar.py,sha256=mZTPpJUwcfcdgQCTTz3kyY-fc79ddLwtx6Ghhxfo064,8162
+pip/_vendor/rich/prompt.py,sha256=l0RhQU-0UVTV9e08xW1BbIj0Jq2IXyChX4lC0lFNzt4,12447
+pip/_vendor/rich/protocol.py,sha256=5hHHDDNHckdk8iWH5zEbi-zuIVSF5hbU2jIo47R7lTE,1391
+pip/_vendor/rich/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pip/_vendor/rich/region.py,sha256=rNT9xZrVZTYIXZC0NYn41CJQwYNbR-KecPOxTgQvB8Y,166
+pip/_vendor/rich/repr.py,sha256=5MZJZmONgC6kud-QW-_m1okXwL2aR6u6y-pUcUCJz28,4431
+pip/_vendor/rich/rule.py,sha256=0fNaS_aERa3UMRc3T5WMpN_sumtDxfaor2y3of1ftBk,4602
+pip/_vendor/rich/scope.py,sha256=TMUU8qo17thyqQCPqjDLYpg_UU1k5qVd-WwiJvnJVas,2843
+pip/_vendor/rich/screen.py,sha256=YoeReESUhx74grqb0mSSb9lghhysWmFHYhsbMVQjXO8,1591
+pip/_vendor/rich/segment.py,sha256=otnKeKGEV-WRlQVosfJVeFDcDxAKHpvJ_hLzSu5lumM,24743
+pip/_vendor/rich/spinner.py,sha256=onIhpKlljRHppTZasxO8kXgtYyCHUkpSgKglRJ3o51g,4214
+pip/_vendor/rich/status.py,sha256=kkPph3YeAZBo-X-4wPp8gTqZyU466NLwZBA4PZTTewo,4424
+pip/_vendor/rich/style.py,sha256=W9Ccy8Py8lNICtlfcp-ryzMTuQaGxAU3av7-g5fHu0s,26990
+pip/_vendor/rich/styled.py,sha256=eZNnzGrI4ki_54pgY3Oj0T-x3lxdXTYh4_ryDB24wBU,1258
+pip/_vendor/rich/syntax.py,sha256=eDKIRwl--eZ0Lwo2da2RRtfutXGavrJO61Cl5OkS59U,36371
+pip/_vendor/rich/table.py,sha256=ZmT7V7MMCOYKw7TGY9SZLyYDf6JdM-WVf07FdVuVhTI,40049
+pip/_vendor/rich/terminal_theme.py,sha256=1j5-ufJfnvlAo5Qsi_ACZiXDmwMXzqgmFByObT9-yJY,3370
+pip/_vendor/rich/text.py,sha256=AO7JPCz6-gaN1thVLXMBntEmDPVYFgFNG1oM61_sanU,47552
+pip/_vendor/rich/theme.py,sha256=oNyhXhGagtDlbDye3tVu3esWOWk0vNkuxFw-_unlaK0,3771
+pip/_vendor/rich/themes.py,sha256=0xgTLozfabebYtcJtDdC5QkX5IVUEaviqDUJJh4YVFk,102
+pip/_vendor/rich/traceback.py,sha256=c0WmB_L04_UfZbLaoH982_U_s7eosxKMUiAVmDPdRYU,35861
+pip/_vendor/rich/tree.py,sha256=yWnQ6rAvRGJ3qZGqBrxS2SW2TKBTNrP0SdY8QxOFPuw,9451
+pip/_vendor/tomli/LICENSE,sha256=uAgWsNUwuKzLTCIReDeQmEpuO2GSLCte6S8zcqsnQv4,1072
+pip/_vendor/tomli/__init__.py,sha256=qzEGl8QHhqgQPCuLzfKyPIuH3KKPspf-UVPbZ0ppBD4,314
+pip/_vendor/tomli/__pycache__/__init__.cpython-312.pyc,,
+pip/_vendor/tomli/__pycache__/_parser.cpython-312.pyc,,
+pip/_vendor/tomli/__pycache__/_re.cpython-312.pyc,,
+pip/_vendor/tomli/__pycache__/_types.cpython-312.pyc,,
+pip/_vendor/tomli/_parser.py,sha256=bO8tUYmnyA2K6m4TnbQbfUqmIFcDv7mG1KuC9gqRVmA,25778
+pip/_vendor/tomli/_re.py,sha256=n8-Io8ZK1U-F6jzlg7Pabc40hLFJsawE2uNLKH9w7iU,3235
+pip/_vendor/tomli/_types.py,sha256=-GTG2VUqkpxwMqzmVO4F7ybKddIbAnuAHXfmWQcTi3Q,254
+pip/_vendor/tomli/py.typed,sha256=8PjyZ1aVoQpRVvt71muvuq5qE-jTFZkK-GLHkhdebmc,26
+pip/_vendor/tomli_w/LICENSE,sha256=uAgWsNUwuKzLTCIReDeQmEpuO2GSLCte6S8zcqsnQv4,1072
+pip/_vendor/tomli_w/__init__.py,sha256=0F8yDtXx3Uunhm874KrAcP76srsM98y7WyHQwCulZbo,169
+pip/_vendor/tomli_w/__pycache__/__init__.cpython-312.pyc,,
+pip/_vendor/tomli_w/__pycache__/_writer.cpython-312.pyc,,
+pip/_vendor/tomli_w/_writer.py,sha256=dsifFS2xYf1i76mmRyfz9y125xC7Z_HQ845ZKhJsYXs,6961
+pip/_vendor/tomli_w/py.typed,sha256=8PjyZ1aVoQpRVvt71muvuq5qE-jTFZkK-GLHkhdebmc,26
+pip/_vendor/truststore/LICENSE,sha256=M757fo-k_Rmxdg4ajtimaL2rhSyRtpLdQUJLy3Jan8o,1086
+pip/_vendor/truststore/__init__.py,sha256=Bu7kqkmpunhLsj5xCu8gT_25ktoPXcSnwe8VHk1GmJo,1320
+pip/_vendor/truststore/__pycache__/__init__.cpython-312.pyc,,
+pip/_vendor/truststore/__pycache__/_api.cpython-312.pyc,,
+pip/_vendor/truststore/__pycache__/_macos.cpython-312.pyc,,
+pip/_vendor/truststore/__pycache__/_openssl.cpython-312.pyc,,
+pip/_vendor/truststore/__pycache__/_ssl_constants.cpython-312.pyc,,
+pip/_vendor/truststore/__pycache__/_windows.cpython-312.pyc,,
+pip/_vendor/truststore/_api.py,sha256=CYJCV5BTfttZYfqY3movdMBE-8az7uhET_LYbKT2Nn4,11413
+pip/_vendor/truststore/_macos.py,sha256=nZlLkOmszUE0g6ryRwBVGY5COzPyudcsiJtDWarM5LQ,20503
+pip/_vendor/truststore/_openssl.py,sha256=zB-SQvJydks7tQ0yIwrP6GD3fQNSSaPiq7zw4yF5T40,2412
+pip/_vendor/truststore/_ssl_constants.py,sha256=NUD4fVKdSD02ri7-db0tnO0VqLP9aHuzmStcW7tAl08,1130
+pip/_vendor/truststore/_windows.py,sha256=rAHyKYD8M7t-bXfG8VgOVa3TpfhVhbt4rZQlO45YuP8,17993
+pip/_vendor/truststore/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pip/_vendor/urllib3/LICENSE.txt,sha256=w3vxhuJ8-dvpYZ5V7f486nswCRzrPaY8fay-Dm13kHs,1115
+pip/_vendor/urllib3/__init__.py,sha256=iXLcYiJySn0GNbWOOZDDApgBL1JgP44EZ8i1760S8Mc,3333
+pip/_vendor/urllib3/__pycache__/__init__.cpython-312.pyc,,
+pip/_vendor/urllib3/__pycache__/_collections.cpython-312.pyc,,
+pip/_vendor/urllib3/__pycache__/_version.cpython-312.pyc,,
+pip/_vendor/urllib3/__pycache__/connection.cpython-312.pyc,,
+pip/_vendor/urllib3/__pycache__/connectionpool.cpython-312.pyc,,
+pip/_vendor/urllib3/__pycache__/exceptions.cpython-312.pyc,,
+pip/_vendor/urllib3/__pycache__/fields.cpython-312.pyc,,
+pip/_vendor/urllib3/__pycache__/filepost.cpython-312.pyc,,
+pip/_vendor/urllib3/__pycache__/poolmanager.cpython-312.pyc,,
+pip/_vendor/urllib3/__pycache__/request.cpython-312.pyc,,
+pip/_vendor/urllib3/__pycache__/response.cpython-312.pyc,,
+pip/_vendor/urllib3/_collections.py,sha256=pyASJJhW7wdOpqJj9QJA8FyGRfr8E8uUUhqUvhF0728,11372
+pip/_vendor/urllib3/_version.py,sha256=t9wGB6ooOTXXgiY66K1m6BZS1CJyXHAU8EoWDTe6Shk,64
+pip/_vendor/urllib3/connection.py,sha256=ttIA909BrbTUzwkqEe_TzZVh4JOOj7g61Ysei2mrwGg,20314
+pip/_vendor/urllib3/connectionpool.py,sha256=e2eiAwNbFNCKxj4bwDKNK-w7HIdSz3OmMxU_TIt-evQ,40408
+pip/_vendor/urllib3/contrib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pip/_vendor/urllib3/contrib/__pycache__/__init__.cpython-312.pyc,,
+pip/_vendor/urllib3/contrib/__pycache__/_appengine_environ.cpython-312.pyc,,
+pip/_vendor/urllib3/contrib/__pycache__/appengine.cpython-312.pyc,,
+pip/_vendor/urllib3/contrib/__pycache__/ntlmpool.cpython-312.pyc,,
+pip/_vendor/urllib3/contrib/__pycache__/pyopenssl.cpython-312.pyc,,
+pip/_vendor/urllib3/contrib/__pycache__/securetransport.cpython-312.pyc,,
+pip/_vendor/urllib3/contrib/__pycache__/socks.cpython-312.pyc,,
+pip/_vendor/urllib3/contrib/_appengine_environ.py,sha256=bDbyOEhW2CKLJcQqAKAyrEHN-aklsyHFKq6vF8ZFsmk,957
+pip/_vendor/urllib3/contrib/_securetransport/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pip/_vendor/urllib3/contrib/_securetransport/__pycache__/__init__.cpython-312.pyc,,
+pip/_vendor/urllib3/contrib/_securetransport/__pycache__/bindings.cpython-312.pyc,,
+pip/_vendor/urllib3/contrib/_securetransport/__pycache__/low_level.cpython-312.pyc,,
+pip/_vendor/urllib3/contrib/_securetransport/bindings.py,sha256=4Xk64qIkPBt09A5q-RIFUuDhNc9mXilVapm7WnYnzRw,17632
+pip/_vendor/urllib3/contrib/_securetransport/low_level.py,sha256=B2JBB2_NRP02xK6DCa1Pa9IuxrPwxzDzZbixQkb7U9M,13922
+pip/_vendor/urllib3/contrib/appengine.py,sha256=VR68eAVE137lxTgjBDwCna5UiBZTOKa01Aj_-5BaCz4,11036
+pip/_vendor/urllib3/contrib/ntlmpool.py,sha256=NlfkW7WMdW8ziqudopjHoW299og1BTWi0IeIibquFwk,4528
+pip/_vendor/urllib3/contrib/pyopenssl.py,sha256=hDJh4MhyY_p-oKlFcYcQaVQRDv6GMmBGuW9yjxyeejM,17081
+pip/_vendor/urllib3/contrib/securetransport.py,sha256=Fef1IIUUFHqpevzXiDPbIGkDKchY2FVKeVeLGR1Qq3g,34446
+pip/_vendor/urllib3/contrib/socks.py,sha256=aRi9eWXo9ZEb95XUxef4Z21CFlnnjbEiAo9HOseoMt4,7097
+pip/_vendor/urllib3/exceptions.py,sha256=0Mnno3KHTNfXRfY7638NufOPkUb6mXOm-Lqj-4x2w8A,8217
+pip/_vendor/urllib3/fields.py,sha256=kvLDCg_JmH1lLjUUEY_FLS8UhY7hBvDPuVETbY8mdrM,8579
+pip/_vendor/urllib3/filepost.py,sha256=5b_qqgRHVlL7uLtdAYBzBh-GHmU5AfJVt_2N0XS3PeY,2440
+pip/_vendor/urllib3/packages/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pip/_vendor/urllib3/packages/__pycache__/__init__.cpython-312.pyc,,
+pip/_vendor/urllib3/packages/__pycache__/six.cpython-312.pyc,,
+pip/_vendor/urllib3/packages/backports/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pip/_vendor/urllib3/packages/backports/__pycache__/__init__.cpython-312.pyc,,
+pip/_vendor/urllib3/packages/backports/__pycache__/makefile.cpython-312.pyc,,
+pip/_vendor/urllib3/packages/backports/__pycache__/weakref_finalize.cpython-312.pyc,,
+pip/_vendor/urllib3/packages/backports/makefile.py,sha256=nbzt3i0agPVP07jqqgjhaYjMmuAi_W5E0EywZivVO8E,1417
+pip/_vendor/urllib3/packages/backports/weakref_finalize.py,sha256=tRCal5OAhNSRyb0DhHp-38AtIlCsRP8BxF3NX-6rqIA,5343
+pip/_vendor/urllib3/packages/six.py,sha256=b9LM0wBXv7E7SrbCjAm4wwN-hrH-iNxv18LgWNMMKPo,34665
+pip/_vendor/urllib3/poolmanager.py,sha256=aWyhXRtNO4JUnCSVVqKTKQd8EXTvUm1VN9pgs2bcONo,19990
+pip/_vendor/urllib3/request.py,sha256=YTWFNr7QIwh7E1W9dde9LM77v2VWTJ5V78XuTTw7D1A,6691
+pip/_vendor/urllib3/response.py,sha256=fmDJAFkG71uFTn-sVSTh2Iw0WmcXQYqkbRjihvwBjU8,30641
+pip/_vendor/urllib3/util/__init__.py,sha256=JEmSmmqqLyaw8P51gUImZh8Gwg9i1zSe-DoqAitn2nc,1155
+pip/_vendor/urllib3/util/__pycache__/__init__.cpython-312.pyc,,
+pip/_vendor/urllib3/util/__pycache__/connection.cpython-312.pyc,,
+pip/_vendor/urllib3/util/__pycache__/proxy.cpython-312.pyc,,
+pip/_vendor/urllib3/util/__pycache__/queue.cpython-312.pyc,,
+pip/_vendor/urllib3/util/__pycache__/request.cpython-312.pyc,,
+pip/_vendor/urllib3/util/__pycache__/response.cpython-312.pyc,,
+pip/_vendor/urllib3/util/__pycache__/retry.cpython-312.pyc,,
+pip/_vendor/urllib3/util/__pycache__/ssl_.cpython-312.pyc,,
+pip/_vendor/urllib3/util/__pycache__/ssl_match_hostname.cpython-312.pyc,,
+pip/_vendor/urllib3/util/__pycache__/ssltransport.cpython-312.pyc,,
+pip/_vendor/urllib3/util/__pycache__/timeout.cpython-312.pyc,,
+pip/_vendor/urllib3/util/__pycache__/url.cpython-312.pyc,,
+pip/_vendor/urllib3/util/__pycache__/wait.cpython-312.pyc,,
+pip/_vendor/urllib3/util/connection.py,sha256=5Lx2B1PW29KxBn2T0xkN1CBgRBa3gGVJBKoQoRogEVk,4901
+pip/_vendor/urllib3/util/proxy.py,sha256=zUvPPCJrp6dOF0N4GAVbOcl6o-4uXKSrGiTkkr5vUS4,1605
+pip/_vendor/urllib3/util/queue.py,sha256=nRgX8_eX-_VkvxoX096QWoz8Ps0QHUAExILCY_7PncM,498
+pip/_vendor/urllib3/util/request.py,sha256=C0OUt2tcU6LRiQJ7YYNP9GvPrSvl7ziIBekQ-5nlBZk,3997
+pip/_vendor/urllib3/util/response.py,sha256=GJpg3Egi9qaJXRwBh5wv-MNuRWan5BIu40oReoxWP28,3510
+pip/_vendor/urllib3/util/retry.py,sha256=6ENvOZ8PBDzh8kgixpql9lIrb2dxH-k7ZmBanJF2Ng4,22050
+pip/_vendor/urllib3/util/ssl_.py,sha256=QDuuTxPSCj1rYtZ4xpD7Ux-r20TD50aHyqKyhQ7Bq4A,17460
+pip/_vendor/urllib3/util/ssl_match_hostname.py,sha256=Ir4cZVEjmAk8gUAIHWSi7wtOO83UCYABY2xFD1Ql_WA,5758
+pip/_vendor/urllib3/util/ssltransport.py,sha256=NA-u5rMTrDFDFC8QzRKUEKMG0561hOD4qBTr3Z4pv6E,6895
+pip/_vendor/urllib3/util/timeout.py,sha256=cwq4dMk87mJHSBktK1miYJ-85G-3T3RmT20v7SFCpno,10168
+pip/_vendor/urllib3/util/url.py,sha256=lCAE7M5myA8EDdW0sJuyyZhVB9K_j38ljWhHAnFaWoE,14296
+pip/_vendor/urllib3/util/wait.py,sha256=fOX0_faozG2P7iVojQoE1mbydweNyTcm-hXEfFrTtLI,5403
+pip/_vendor/vendor.txt,sha256=f2msFLZ-chXWIZSKW31NLGyMWmt_-Vfy7sY5dHYgmnw,342
+pip/py.typed,sha256=EBVvvPRTn_eIpz5e5QztSCdrMX7Qwd7VP93RSoIlZ2I,286
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pip-26.0.1.dist-info/REQUESTED b/TTS/Kokoro/.venv/Lib/site-packages/pip-26.0.1.dist-info/REQUESTED
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pip-26.0.1.dist-info/WHEEL b/TTS/Kokoro/.venv/Lib/site-packages/pip-26.0.1.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..d8b9936dad9ab2513fa6979f411560d3b6b57e37
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pip-26.0.1.dist-info/WHEEL
@@ -0,0 +1,4 @@
+Wheel-Version: 1.0
+Generator: flit 3.12.0
+Root-Is-Purelib: true
+Tag: py3-none-any
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pip-26.0.1.dist-info/entry_points.txt b/TTS/Kokoro/.venv/Lib/site-packages/pip-26.0.1.dist-info/entry_points.txt
new file mode 100644
index 0000000000000000000000000000000000000000..c6436d21fcc6479564ce8581c93e30e2cc60a096
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pip-26.0.1.dist-info/entry_points.txt
@@ -0,0 +1,4 @@
+[console_scripts]
+pip=pip._internal.cli.main:main
+pip3=pip._internal.cli.main:main
+
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pip/__init__.py b/TTS/Kokoro/.venv/Lib/site-packages/pip/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..978b4129206ef2857676dcf0fb4f71243b35328f
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pip/__init__.py
@@ -0,0 +1,13 @@
+from __future__ import annotations
+
+__version__ = "26.0.1"
+
+
+def main(args: list[str] | None = None) -> int:
+    """This is an internal API only meant for use by pip's own console scripts.
+
+    For additional details, see https://github.com/pypa/pip/issues/7498.
+    """
+    from pip._internal.utils.entrypoints import _wrapper
+
+    return _wrapper(args)
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pip/__main__.py b/TTS/Kokoro/.venv/Lib/site-packages/pip/__main__.py
new file mode 100644
index 0000000000000000000000000000000000000000..5991326115fe5026470165b387ba2bc78bceb006
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pip/__main__.py
@@ -0,0 +1,24 @@
+import os
+import sys
+
+# Remove '' and current working directory from the first entry
+# of sys.path, if present to avoid using current directory
+# in pip commands check, freeze, install, list and show,
+# when invoked as python -m pip 
+if sys.path[0] in ("", os.getcwd()):
+    sys.path.pop(0)
+
+# If we are running from a wheel, add the wheel to sys.path
+# This allows the usage python pip-*.whl/pip install pip-*.whl
+if __package__ == "":
+    # __file__ is pip-*.whl/pip/__main__.py
+    # first dirname call strips of '/__main__.py', second strips off '/pip'
+    # Resulting path is the name of the wheel itself
+    # Add that to sys.path so we can import pip
+    path = os.path.dirname(os.path.dirname(__file__))
+    sys.path.insert(0, path)
+
+if __name__ == "__main__":
+    from pip._internal.cli.main import main as _main
+
+    sys.exit(_main())
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pip/__pip-runner__.py b/TTS/Kokoro/.venv/Lib/site-packages/pip/__pip-runner__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d6be157831a67d8d45d75ce1c6f14aad0ad47b8f
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pip/__pip-runner__.py
@@ -0,0 +1,50 @@
+"""Execute exactly this copy of pip, within a different environment.
+
+This file is named as it is, to ensure that this module can't be imported via
+an import statement.
+"""
+
+# /!\ This version compatibility check section must be Python 2 compatible. /!\
+
+import sys
+
+# Copied from pyproject.toml
+PYTHON_REQUIRES = (3, 9)
+
+
+def version_str(version):  # type: ignore
+    return ".".join(str(v) for v in version)
+
+
+if sys.version_info[:2] < PYTHON_REQUIRES:
+    raise SystemExit(
+        "This version of pip does not support python {} (requires >={}).".format(
+            version_str(sys.version_info[:2]), version_str(PYTHON_REQUIRES)
+        )
+    )
+
+# From here on, we can use Python 3 features, but the syntax must remain
+# Python 2 compatible.
+
+import runpy  # noqa: E402
+from importlib.machinery import PathFinder  # noqa: E402
+from os.path import dirname  # noqa: E402
+
+PIP_SOURCES_ROOT = dirname(dirname(__file__))
+
+
+class PipImportRedirectingFinder:
+    @classmethod
+    def find_spec(self, fullname, path=None, target=None):  # type: ignore
+        if fullname != "pip":
+            return None
+
+        spec = PathFinder.find_spec(fullname, [PIP_SOURCES_ROOT], target)
+        assert spec, (PIP_SOURCES_ROOT, fullname)
+        return spec
+
+
+sys.meta_path.insert(0, PipImportRedirectingFinder())
+
+assert __name__ == "__main__", "Cannot run __pip-runner__.py as a non-main module"
+runpy.run_module("pip", run_name="__main__", alter_sys=True)
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pip/py.typed b/TTS/Kokoro/.venv/Lib/site-packages/pip/py.typed
new file mode 100644
index 0000000000000000000000000000000000000000..493b53e4e7a3984ddd49780313bf3bd9901dc1e0
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pip/py.typed
@@ -0,0 +1,4 @@
+pip is a command line program. While it is implemented in Python, and so is
+available for import, you must not use pip's internal APIs in this way. Typing
+information is provided as a convenience only and is not a guarantee. Expect
+unannounced changes to the API and types in releases.
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/preshed-3.0.12.dist-info/INSTALLER b/TTS/Kokoro/.venv/Lib/site-packages/preshed-3.0.12.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/preshed-3.0.12.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/preshed-3.0.12.dist-info/METADATA b/TTS/Kokoro/.venv/Lib/site-packages/preshed-3.0.12.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..d2ee33ff54f9c928bbe6b13e2d844c189d8723cb
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/preshed-3.0.12.dist-info/METADATA
@@ -0,0 +1,55 @@
+Metadata-Version: 2.4
+Name: preshed
+Version: 3.0.12
+Summary: Cython hash table that trusts the keys are pre-hashed
+Home-page: https://github.com/explosion/preshed
+Author: Explosion
+Author-email: contact@explosion.ai
+License: MIT
+Classifier: Environment :: Console
+Classifier: Intended Audience :: Developers
+Classifier: Intended Audience :: Science/Research
+Classifier: License :: OSI Approved :: MIT License
+Classifier: Operating System :: POSIX :: Linux
+Classifier: Operating System :: MacOS :: MacOS X
+Classifier: Operating System :: Microsoft :: Windows
+Classifier: Programming Language :: Cython
+Classifier: Programming Language :: Python :: 3.6
+Classifier: Programming Language :: Python :: 3.7
+Classifier: Programming Language :: Python :: 3.8
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Classifier: Programming Language :: Python :: 3.13
+Classifier: Programming Language :: Python :: 3.14
+Classifier: Topic :: Scientific/Engineering
+Requires-Python: >=3.6,<3.15
+Description-Content-Type: text/markdown
+License-File: LICENSE
+Requires-Dist: cymem<2.1.0,>=2.0.2
+Requires-Dist: murmurhash<1.1.0,>=0.28.0
+Dynamic: author
+Dynamic: author-email
+Dynamic: classifier
+Dynamic: description
+Dynamic: description-content-type
+Dynamic: home-page
+Dynamic: license
+Dynamic: license-file
+Dynamic: requires-dist
+Dynamic: requires-python
+Dynamic: summary
+
+
+
+# preshed: Cython Hash Table for Pre-Hashed Keys
+
+Simple but high performance Cython hash table mapping pre-randomized keys to
+`void*` values. Inspired by
+[Jeff Preshing](http://preshing.com/20130107/this-hash-table-is-faster-than-a-judy-array/).
+
+[![tests](https://github.com/explosion/preshed/actions/workflows/tests.yml/badge.svg)](https://github.com/explosion/preshed/actions/workflows/tests.yml)
+[![pypi Version](https://img.shields.io/pypi/v/preshed.svg?style=flat-square&logo=pypi&logoColor=white)](https://pypi.python.org/pypi/preshed)
+[![conda Version](https://img.shields.io/conda/vn/conda-forge/preshed.svg?style=flat-square&logo=conda-forge&logoColor=white)](https://anaconda.org/conda-forge/preshed)
+[![Python wheels](https://img.shields.io/badge/wheels-%E2%9C%93-4c1.svg?longCache=true&style=flat-square&logo=python&logoColor=white)](https://github.com/explosion/wheelwright/releases)
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/preshed-3.0.12.dist-info/RECORD b/TTS/Kokoro/.venv/Lib/site-packages/preshed-3.0.12.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..e3088d1fa9e69739c6f869c0c543dc2b4cc2c75a
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/preshed-3.0.12.dist-info/RECORD
@@ -0,0 +1,30 @@
+preshed-3.0.12.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+preshed-3.0.12.dist-info/METADATA,sha256=dakPTxybXXxgSW0XCFaHPQZkueS_dJkCgqbteZW9r4Q,2588
+preshed-3.0.12.dist-info/RECORD,,
+preshed-3.0.12.dist-info/WHEEL,sha256=8UP9x9puWI0P1V_d7K2oMTBqfeLNm21CTzZ_Ptr0NXU,101
+preshed-3.0.12.dist-info/licenses/LICENSE,sha256=B6_J_UdfNGxp3q-XYtLOcuf5apXk6pzDGQZukT013o4,1127
+preshed-3.0.12.dist-info/top_level.txt,sha256=1inBAipXmFW3mz-zRdwW5vAwnPaBhvzgMAqOuECKbEo,8
+preshed/__init__.pxd,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+preshed/__init__.py,sha256=5x1XCRB8b70rovUrFDvsWm5GT-SK5CaMfFdKZNep3UM,22
+preshed/__pycache__/__init__.cpython-312.pyc,,
+preshed/__pycache__/about.cpython-312.pyc,,
+preshed/about.py,sha256=Q3MPMK84n6QFnSUUgyyj1dIb3vzL4PoCCS_OhZP12WY,271
+preshed/bloom.cp312-win_amd64.pyd,sha256=ozBoytLhtGzxTMTRdXcK_-Geccrv16HEnTWhv6We9vo,68096
+preshed/bloom.pxd,sha256=2uVv5Lw6kK_xTmW4FuqtLFAfkfuWGoY-HixDtSDKxcA,682
+preshed/bloom.pyx,sha256=JiDAXIJKEfw3fZGKO21B1Xla8cxPtW7w8mEhL--fqjM,4665
+preshed/counter.cp312-win_amd64.pyd,sha256=xGY9cleDfFUzSIY-El3B1KNJTuCZnHjC_Rzk6WA_XsQ,82432
+preshed/counter.pxd,sha256=_I0zSJQ3qbKs9hfxKSwH5AbYUE294y57eSCEuZcj5ls,415
+preshed/counter.pyx,sha256=bt2nz7-y3NZf4VlLDyPCuq-tmqX6NH0KN9oQrSoQqaA,6307
+preshed/maps.cp312-win_amd64.pyd,sha256=XjPrFXq4iN0mD3BVbQSMVoq7dl6BZn_hWndoihRwTq4,79360
+preshed/maps.pxd,sha256=GchRCVp9ofCrXr9sydhMzmx-6d8t05eQ4ftl1f_QVLU,1393
+preshed/maps.pyx,sha256=2ThyuOPx_KakNqAPhHFDnDryLuoHrhODa00wX66myhU,8988
+preshed/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+preshed/tests/__pycache__/__init__.cpython-312.pyc,,
+preshed/tests/__pycache__/test_bloom.cpython-312.pyc,,
+preshed/tests/__pycache__/test_counter.cpython-312.pyc,,
+preshed/tests/__pycache__/test_hashing.cpython-312.pyc,,
+preshed/tests/__pycache__/test_pop.cpython-312.pyc,,
+preshed/tests/test_bloom.py,sha256=a8jxPzLwSXI8k3KBNQ_xShuhgJWE3Kprv4T7NRTi77g,1312
+preshed/tests/test_counter.py,sha256=POOeEq_A8BE4o_iChxypGcvZySbYZIMrNH1YGnrQG90,2081
+preshed/tests/test_hashing.py,sha256=YasaHqQtg6dBTpEUaIRDTKl3icgEZVwPF7GhcIp6SYg,1480
+preshed/tests/test_pop.py,sha256=zoPJ0USzesL4FUBxezpHA93g3Z1mhJ5e--5Bc6NTLb0,218
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/preshed-3.0.12.dist-info/WHEEL b/TTS/Kokoro/.venv/Lib/site-packages/preshed-3.0.12.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..10ac2c23843796b65786bc9aba179a906c8bcc88
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/preshed-3.0.12.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: setuptools (80.9.0)
+Root-Is-Purelib: false
+Tag: cp312-cp312-win_amd64
+
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/preshed-3.0.12.dist-info/top_level.txt b/TTS/Kokoro/.venv/Lib/site-packages/preshed-3.0.12.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..9a54b5a794392463a28bcd1170baa2241b4213c1
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/preshed-3.0.12.dist-info/top_level.txt
@@ -0,0 +1 @@
+preshed
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/preshed/__init__.pxd b/TTS/Kokoro/.venv/Lib/site-packages/preshed/__init__.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/preshed/__init__.py b/TTS/Kokoro/.venv/Lib/site-packages/preshed/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..13030b90f196c2af0864fd6d382be87a4fffd878
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/preshed/__init__.py
@@ -0,0 +1 @@
+from .about import *
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/preshed/about.py b/TTS/Kokoro/.venv/Lib/site-packages/preshed/about.py
new file mode 100644
index 0000000000000000000000000000000000000000..f43fd78eeaf293afeb46331a019feee8ac33727e
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/preshed/about.py
@@ -0,0 +1,8 @@
+__title__ = "preshed"
+__version__ = "3.0.12"
+__summary__ = "Cython hash table that trusts the keys are pre-hashed"
+__uri__ = "https://github.com/explosion/preshed"
+__author__ = "Explosion"
+__email__ = "contact@explosion.ai"
+__license__ = "MIT"
+__release__ = True
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/preshed/bloom.cp312-win_amd64.pyd b/TTS/Kokoro/.venv/Lib/site-packages/preshed/bloom.cp312-win_amd64.pyd
new file mode 100644
index 0000000000000000000000000000000000000000..ecf52c2d22e6e8eb9f25a2e0f04403ed22ea2b42
Binary files /dev/null and b/TTS/Kokoro/.venv/Lib/site-packages/preshed/bloom.cp312-win_amd64.pyd differ
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/preshed/bloom.pxd b/TTS/Kokoro/.venv/Lib/site-packages/preshed/bloom.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..6026ab8a2efd3ccc1daf6af725f825506d3f7870
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/preshed/bloom.pxd
@@ -0,0 +1,25 @@
+from libc.stdint cimport uint64_t, uint32_t
+from cymem.cymem cimport Pool
+
+ctypedef uint64_t key_t
+
+cdef struct BloomStruct:
+    key_t* bitfield
+    key_t hcount # hash count, number of hash functions
+    key_t length
+    uint32_t seed
+
+
+cdef class BloomFilter:
+    cdef Pool mem
+    cdef BloomStruct* c_bloom
+    cdef inline bint contains(self, key_t item) nogil
+
+
+cdef void bloom_init(Pool mem, BloomStruct* bloom, key_t hcount, key_t length, uint32_t seed) except *
+
+cdef void bloom_add(BloomStruct* bloom, key_t item) nogil
+
+cdef bint bloom_contains(const BloomStruct* bloom, key_t item) nogil
+
+cdef void bloom_add(BloomStruct* bloom, key_t item) nogil
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/preshed/bloom.pyx b/TTS/Kokoro/.venv/Lib/site-packages/preshed/bloom.pyx
new file mode 100644
index 0000000000000000000000000000000000000000..ccb7a3d8a2ead5289437259c7133d7e0322cca84
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/preshed/bloom.pyx
@@ -0,0 +1,136 @@
+# cython: infer_types=True
+# cython: cdivision=True
+#
+from murmurhash.mrmr cimport hash128_x86
+import math
+from array import array
+
+try:
+    import copy_reg
+except ImportError:
+    import copyreg as copy_reg
+
+
+def calculate_size_and_hash_count(members, error_rate):
+    """Calculate the optimal size in bits and number of hash functions for a
+    given number of members and error rate.  
+    """
+    base = math.log(1 / (2 ** math.log(2)))
+    bit_count = math.ceil((members * math.log(error_rate)) / base)
+    hash_count = math.floor((bit_count / members) * math.log(2))
+    return (bit_count, hash_count)
+
+
+cdef class BloomFilter:
+    """Bloom filter that allows for basic membership tests.
+    
+    Only integers are supported as keys.
+    """
+    def __init__(self, key_t size=(2 ** 10), key_t hash_funcs=23, uint32_t seed=0):
+        self.mem = Pool()
+        self.c_bloom = self.mem.alloc(1, sizeof(BloomStruct))
+        bloom_init(self.mem, self.c_bloom, hash_funcs, size, seed)
+
+    @classmethod
+    def from_error_rate(cls, members, error_rate=1E-4):
+        params = calculate_size_and_hash_count(members, error_rate)
+        return cls(*params)
+
+    def add(self, key_t item):
+        bloom_add(self.c_bloom, item)
+
+    def __contains__(self, item):
+        return bloom_contains(self.c_bloom, item)
+
+    cdef inline bint contains(self, key_t item) nogil:
+        return bloom_contains(self.c_bloom, item)
+
+    def to_bytes(self):
+        return bloom_to_bytes(self.c_bloom)
+
+    def from_bytes(self, bytes byte_string):
+        bloom_from_bytes(self.mem, self.c_bloom, byte_string)
+        return self
+
+
+cdef bytes bloom_to_bytes(const BloomStruct* bloom):
+    py = array("L")
+    py.append(bloom.hcount)
+    py.append(bloom.length)
+    py.append(bloom.seed)
+    for i in range(bloom.length // sizeof(key_t)):
+        py.append(bloom.bitfield[i])
+    if hasattr(py, "tobytes"):
+        return py.tobytes()
+    else:
+        # Python 2 :(
+        return py.tostring()
+
+
+cdef void bloom_from_bytes(Pool mem, BloomStruct* bloom, bytes data):
+    py = array("L")
+    if hasattr(py, "frombytes"):
+        py.frombytes(data)
+    else:
+        py.fromstring(data)
+    bloom.hcount = py[0]
+    bloom.length = py[1]
+    bloom.seed = py[2]
+    bloom.bitfield = mem.alloc(bloom.length // sizeof(key_t), sizeof(key_t))
+    for i in range(bloom.length // sizeof(key_t)):
+        bloom.bitfield[i] = py[3+i]
+
+
+cdef void bloom_init(Pool mem, BloomStruct* bloom, key_t hcount, key_t length, uint32_t seed) except *:
+    # size should be a multiple of the container size - round up
+    if length % sizeof(key_t):
+        length = math.ceil(length / sizeof(key_t)) * sizeof(key_t)
+    bloom.length = length
+    bloom.hcount = hcount
+    bloom.bitfield = mem.alloc(length // sizeof(key_t), sizeof(key_t))
+    bloom.seed = seed
+
+
+# Instead of calling MurmurHash with a different seed for each hash function, this
+# generates two initial hash values and then combines them to create the correct
+# number of hashes. This technique is faster than just doing MurmurhHash
+# repeatedly and has been shown to work as well as full hashing.
+
+# For details see "Less Hashing, Same Performance: Building a Better Bloom
+# Filter", Kirsch & Mitzenmacher.
+
+# https://www.semanticscholar.org/paper/Less-hashing%2C-same-performance%3A-Building-a-better-Kirsch-Mitzenmacher/65c43afbfc064705bdc40d3473f32518e9306429
+# The choice of seeds is arbitrary.
+
+
+cdef void bloom_add(BloomStruct* bloom, key_t item) nogil:
+    cdef key_t hv
+    cdef key_t[2] keys
+    cdef key_t one = 1 # We want this explicitly typed, because bits
+    hash128_x86(&item, sizeof(key_t), 0, &keys)
+    for hiter in range(bloom.hcount):
+        hv = (keys[0] + (hiter * keys[1])) % bloom.length
+        bloom.bitfield[hv // sizeof(key_t)] |= one << (hv % sizeof(key_t))
+
+
+cdef bint bloom_contains(const BloomStruct* bloom, key_t item) nogil:
+    cdef key_t hv
+    cdef key_t[2] keys
+    cdef key_t one = 1 # We want this explicitly typed, because bits
+    hash128_x86(&item, sizeof(key_t), 0, &keys)
+    for hiter in range(bloom.hcount):
+        hv = (keys[0] + (hiter * keys[1])) % bloom.length
+        if not (bloom.bitfield[hv // sizeof(key_t)] & one << (hv % sizeof(key_t))):
+            return False
+    return True
+
+
+def pickle_bloom(BloomFilter bloom):
+    return unpickle_bloom, (bloom.to_bytes(),)
+
+
+def unpickle_bloom(byte_string):
+    return BloomFilter().from_bytes(byte_string)
+
+
+copy_reg.pickle(BloomFilter, pickle_bloom, unpickle_bloom)
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/preshed/counter.cp312-win_amd64.pyd b/TTS/Kokoro/.venv/Lib/site-packages/preshed/counter.cp312-win_amd64.pyd
new file mode 100644
index 0000000000000000000000000000000000000000..ec998aa7d4772480771e55e27f8ef741816efb1e
Binary files /dev/null and b/TTS/Kokoro/.venv/Lib/site-packages/preshed/counter.cp312-win_amd64.pyd differ
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/preshed/counter.pxd b/TTS/Kokoro/.venv/Lib/site-packages/preshed/counter.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..ba18d1cd88a4f0904c2b8c73700c9dde4850aabc
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/preshed/counter.pxd
@@ -0,0 +1,19 @@
+from libc.stdint cimport int64_t
+
+from cymem.cymem cimport Pool
+
+from .maps cimport MapStruct
+from .maps cimport map_init, map_get, map_set, map_iter
+from .maps cimport key_t
+
+
+ctypedef int64_t count_t
+
+
+cdef class PreshCounter:
+    cdef Pool mem
+    cdef MapStruct* c_map
+    cdef public object smoother
+    cdef readonly count_t total
+
+    cpdef int inc(self, key_t key, count_t inc) except -1
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/preshed/counter.pyx b/TTS/Kokoro/.venv/Lib/site-packages/preshed/counter.pyx
new file mode 100644
index 0000000000000000000000000000000000000000..701d8d425eabd304571330810aa2298cf9e4a199
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/preshed/counter.pyx
@@ -0,0 +1,191 @@
+"""Count occurrences of uint64-valued keys."""
+from __future__ import division
+cimport cython
+from libc.math cimport log, exp, sqrt
+
+
+cdef class PreshCounter:
+    def __init__(self, initial_size=8):
+        assert initial_size != 0
+        assert initial_size & (initial_size - 1) == 0
+        self.mem = Pool()
+        self.c_map = self.mem.alloc(1, sizeof(MapStruct))
+        map_init(self.mem, self.c_map, initial_size)
+        self.smoother = None
+        self.total = 0
+
+    property length:
+        def __get__(self):
+            return self.c_map.length
+
+    def __len__(self):
+        return self.c_map.length
+
+    def __iter__(self):
+        cdef int i = 0
+        cdef key_t key
+        cdef void* value
+        while map_iter(self.c_map, &i, &key, &value):
+            yield key, value
+
+    def __getitem__(self, key_t key):
+        return map_get(self.c_map, key)
+
+    cpdef int inc(self, key_t key, count_t inc) except -1:
+        cdef count_t c = map_get(self.c_map, key)
+        c += inc
+        map_set(self.mem, self.c_map, key, c)
+        self.total += inc
+        return c
+
+    def prob(self, key_t key):
+        cdef GaleSmoother smoother
+        cdef void* value = map_get(self.c_map, key)
+        if self.smoother is not None:
+            smoother = self.smoother
+            r_star = self.smoother(value)
+            return r_star / self.smoother.total
+        elif value == NULL:
+            return 0
+        else:
+            return value / self.total
+
+    def smooth(self):
+        self.smoother = GaleSmoother(self)
+       
+
+cdef class GaleSmoother:
+    cdef Pool mem
+    cdef count_t* Nr
+    cdef double gradient
+    cdef double intercept
+    cdef readonly count_t cutoff
+    cdef count_t Nr0
+    cdef readonly double total
+
+    def __init__(self, PreshCounter counts):
+        count_counts = PreshCounter()
+        cdef double total = 0
+        for _, count in counts:
+            count_counts.inc(count, 1)
+            total += count
+        # If we have no items seen 1 or 2 times, this doesn't work. But, this
+        # won't be true in real data...
+        assert count_counts[1] != 0 and count_counts[2] != 0, "Cannot smooth your weird data"
+        # Extrapolate Nr0 from Nr1 and Nr2.
+        self.Nr0 = count_counts[1] + (count_counts[1] - count_counts[2])
+        self.mem = Pool()
+
+        cdef double[2] mb
+
+        cdef int n_counts = 0
+        for _ in count_counts:
+            n_counts += 1
+        sorted_r = count_counts.mem.alloc(n_counts, sizeof(count_t))
+        self.Nr = self.mem.alloc(n_counts, sizeof(count_t))
+        for i, (count, count_count) in enumerate(sorted(count_counts)):
+            sorted_r[i] = count
+            self.Nr[i] = count_count
+
+        _fit_loglinear_model(mb, sorted_r, self.Nr, n_counts)
+        
+        self.cutoff = _find_when_to_switch(sorted_r, self.Nr, mb[0], mb[1],
+                                           n_counts)
+        self.gradient = mb[0]
+        self.intercept = mb[1]
+        self.total = self(0) * self.Nr0
+        for count, count_count in count_counts:
+            self.total += self(count) * count_count
+
+    def __call__(self, count_t r):
+        if r == 0:
+            return self.Nr[1] / self.Nr0
+        elif r < self.cutoff:
+            return turing_estimate_of_r(r, self.Nr[r-1], self.Nr[r])
+        else:
+            return gale_estimate_of_r(r, self.gradient, self.intercept)
+
+    def count_count(self, count_t r):
+        if r == 0:
+            return self.Nr0
+        else:
+            return self.Nr[r-1]
+
+
+@cython.cdivision(True)
+cdef double turing_estimate_of_r(double r, double Nr, double Nr1) except -1:
+    return ((r + 1) * Nr1) / Nr
+
+
+@cython.cdivision(True)
+cdef double gale_estimate_of_r(double r, double gradient, double intercept) except -1:
+    cdef double e_nr  = exp(gradient * log(r) + intercept)
+    cdef double e_nr1 = exp(gradient * log(r+1) + intercept)
+    return (r + 1) * (e_nr1 / e_nr)
+
+
+@cython.cdivision(True)
+cdef void _fit_loglinear_model(double* output, count_t* sorted_r, count_t* Nr,
+                               int length) except *:
+    cdef double x_mean = 0.0
+    cdef double y_mean = 0.0
+
+    cdef Pool mem = Pool()
+    x = mem.alloc(length, sizeof(double))
+    y = mem.alloc(length, sizeof(double))
+
+    cdef int i
+    for i in range(length):
+        r = sorted_r[i]
+        x[i] = log(r)
+        y[i] = log(_get_zr(i, sorted_r, Nr[i], length))
+        x_mean += x[i]
+        y_mean += y[i]
+    
+    x_mean /= length
+    y_mean /= length
+
+    cdef double ss_xy = 0.0
+    cdef double ss_xx = 0.0
+   
+    for i in range(length):
+        x_dist = x[i] - x_mean
+        y_dist = y[i] - y_mean
+        # SS_xy = sum the product of the distances from the mean
+        ss_xy += x_dist * y_dist
+        # SS_xx = sum the squares of the x distance
+        ss_xx  += x_dist * x_dist
+    # Gradient
+    output[0]  = ss_xy / ss_xx
+    # Intercept
+    output[1] = y_mean - output[0] * x_mean
+
+
+@cython.cdivision(True)
+cdef double _get_zr(int j, count_t* sorted_r, count_t Nr_j, int n_counts) except -1:
+    cdef double r_i = sorted_r[j-1] if j >= 1 else 0
+    cdef double r_j = sorted_r[j]
+    cdef double r_k = sorted_r[j+1] if (j+1) < n_counts else (2 * r_i - 1)
+    return 2 * Nr_j / (r_k - r_i)
+
+
+@cython.cdivision(True)
+cdef double _variance(double r, double Nr, double Nr1) nogil:
+    return 1.96 * sqrt((r+1)**2 * (Nr1 / Nr**2) * (1.0 + (Nr1 / Nr)))
+
+
+@cython.cdivision(True)
+cdef count_t _find_when_to_switch(count_t* sorted_r, count_t* Nr, double m, double b,
+                                  int length) except -1:
+    cdef int i
+    cdef count_t r
+    for i in range(length-1):
+        r = sorted_r[i]
+        if sorted_r[i+1] != r+1:
+            return r
+        g_r = gale_estimate_of_r(r, m, b)
+        t_r = turing_estimate_of_r(r, Nr[i], Nr[i+1])
+        if abs(t_r - g_r) <= _variance(r, Nr[i], Nr[i+1]):
+            return r
+    else:
+        return length - 1
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/preshed/maps.cp312-win_amd64.pyd b/TTS/Kokoro/.venv/Lib/site-packages/preshed/maps.cp312-win_amd64.pyd
new file mode 100644
index 0000000000000000000000000000000000000000..8d232d4e9523d6d74c0c721892ac0cab8e522cde
Binary files /dev/null and b/TTS/Kokoro/.venv/Lib/site-packages/preshed/maps.cp312-win_amd64.pyd differ
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/preshed/maps.pxd b/TTS/Kokoro/.venv/Lib/site-packages/preshed/maps.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..1f187585017653c5f848a929c715b5a5d810d709
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/preshed/maps.pxd
@@ -0,0 +1,59 @@
+from libc.stdint cimport uint64_t
+from cymem.cymem cimport Pool
+
+
+ctypedef uint64_t key_t
+
+
+cdef struct Cell:
+    key_t key
+    void* value
+
+
+cdef struct Result:
+    int found
+    void* value
+
+
+cdef struct MapStruct:
+    Cell* cells
+    void* value_for_empty_key
+    void* value_for_del_key
+    key_t length
+    key_t filled
+    bint is_empty_key_set
+    bint is_del_key_set
+
+
+cdef void* map_bulk_get(const MapStruct* map_, const key_t* keys, void** values,
+                        int n) nogil
+
+
+cdef Result map_get_unless_missing(const MapStruct* map_, const key_t key) nogil
+
+cdef void* map_get(const MapStruct* map_, const key_t key) nogil
+
+cdef void map_set(Pool mem, MapStruct* map_, key_t key, void* value) except *
+
+cdef void map_init(Pool mem, MapStruct* pmap, size_t length) except *
+
+cdef bint map_iter(const MapStruct* map_, int* i, key_t* key, void** value) nogil
+
+cdef void* map_clear(MapStruct* map_, const key_t key) nogil
+
+
+cdef class PreshMap:
+    cdef MapStruct* c_map
+    cdef Pool mem
+
+    cdef inline void* get(self, key_t key) nogil
+    cdef void set(self, key_t key, void* value) except *
+
+
+cdef class PreshMapArray:
+    cdef Pool mem
+    cdef MapStruct* maps
+    cdef size_t length
+
+    cdef inline void* get(self, size_t i, key_t key) nogil
+    cdef void set(self, size_t i, key_t key, void* value) except *
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/preshed/maps.pyx b/TTS/Kokoro/.venv/Lib/site-packages/preshed/maps.pyx
new file mode 100644
index 0000000000000000000000000000000000000000..20614d0c6216e2ca259a53609ad8625b77e7b15c
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/preshed/maps.pyx
@@ -0,0 +1,265 @@
+# cython: infer_types=True
+# cython: cdivision=True
+#
+cimport cython
+
+
+DEF EMPTY_KEY = 0
+DEF DELETED_KEY = 1
+
+
+cdef class PreshMap:
+    """Hash map that assumes keys come pre-hashed. Maps uint64_t --> uint64_t.
+    Uses open addressing with linear probing.
+
+    Usage
+        map = PreshMap() # Create a table
+        map = PreshMap(initial_size=1024) # Create with initial size (efficiency)
+        map[key] = value # Set a value to a key
+        value = map[key] # Get a value given a key
+        for key, value in map.items(): # Iterate over items
+        len(map) # Get number of inserted keys
+    """
+    def __init__(self, size_t initial_size=8):
+        # Size must be power of two
+        if initial_size == 0:
+            initial_size = 8
+        if initial_size & (initial_size - 1) != 0:
+            power = 1
+            while power < initial_size:
+                power *= 2
+            initial_size = power
+        self.mem = Pool()
+        self.c_map = self.mem.alloc(1, sizeof(MapStruct))
+        map_init(self.mem, self.c_map, initial_size)
+
+    property capacity:
+        def __get__(self):
+            return self.c_map.length
+
+    def items(self):
+        cdef key_t key
+        cdef void* value
+        cdef int i = 0
+        while map_iter(self.c_map, &i, &key, &value):
+            yield key, value
+
+    def keys(self):
+        for key, _ in self.items():
+            yield key
+
+    def values(self):
+        for _, value in self.items():
+            yield value
+
+    def pop(self, key_t key, default=None):
+        cdef Result result = map_get_unless_missing(self.c_map, key)
+        map_clear(self.c_map, key)
+        if result.found:
+            return result.value
+        else:
+            return default
+
+    def __getitem__(self, key_t key):
+        cdef Result result = map_get_unless_missing(self.c_map, key)
+        if result.found:
+            return result.value
+        else:
+            return None
+
+    def __setitem__(self, key_t key, size_t value):
+        map_set(self.mem, self.c_map, key, value)
+
+    def __delitem__(self, key_t key):
+        map_clear(self.c_map, key)
+
+    def __len__(self):
+        return self.c_map.filled
+
+    def __contains__(self, key_t key):
+        cdef Result result = map_get_unless_missing(self.c_map, key)
+        return True if result.found else False
+
+    def __iter__(self):
+        for key in self.keys():
+            yield key
+
+    cdef inline void* get(self, key_t key) nogil:
+        return map_get(self.c_map, key)
+
+    cdef void set(self, key_t key, void* value) except *:
+        map_set(self.mem, self.c_map, key, value)
+
+
+cdef class PreshMapArray:
+    """An array of hash tables that assume keys come pre-hashed.  Each table
+    uses open addressing with linear probing.
+    """
+    def __init__(self, size_t length, size_t initial_size=8):
+        self.mem = Pool()
+        self.length = length
+        self.maps = self.mem.alloc(length, sizeof(MapStruct))
+        for i in range(length):
+            map_init(self.mem, &self.maps[i], initial_size)
+
+    cdef inline void* get(self, size_t i, key_t key) nogil:
+        return map_get(&self.maps[i], key)
+
+    cdef void set(self, size_t i, key_t key, void* value) except *:
+        map_set(self.mem, &self.maps[i], key, value)
+
+
+cdef void map_init(Pool mem, MapStruct* map_, size_t length) except *:
+    map_.length = length
+    map_.filled = 0
+    map_.cells = mem.alloc(length, sizeof(Cell))
+
+
+cdef void map_set(Pool mem, MapStruct* map_, key_t key, void* value) except *:
+    cdef Cell* cell
+    if key == EMPTY_KEY:
+        map_.value_for_empty_key = value
+        map_.is_empty_key_set = True
+    elif key == DELETED_KEY:
+        map_.value_for_del_key = value
+        map_.is_del_key_set = True
+    else:
+        cell = _find_cell_for_insertion(map_.cells, map_.length, key)
+        if cell.key == EMPTY_KEY:
+            map_.filled += 1
+        cell.key = key
+        cell.value = value
+        if (map_.filled + 1) * 5 >= (map_.length * 3):
+            _resize(mem, map_)
+
+
+cdef void* map_get(const MapStruct* map_, const key_t key) nogil:
+    if key == EMPTY_KEY:
+        return map_.value_for_empty_key
+    elif key == DELETED_KEY:
+        return map_.value_for_del_key
+    cdef Cell* cell = _find_cell(map_.cells, map_.length, key)
+    return cell.value
+
+
+cdef Result map_get_unless_missing(const MapStruct* map_, const key_t key) nogil:
+    cdef Result result
+    cdef Cell* cell
+    result.found = 0
+    result.value = NULL
+    if key == EMPTY_KEY:
+        if map_.is_empty_key_set:
+            result.found = 1
+            result.value = map_.value_for_empty_key
+    elif key == DELETED_KEY:
+        if map_.is_del_key_set:
+            result.found = 1
+            result.value = map_.value_for_del_key
+    else:
+        cell = _find_cell(map_.cells, map_.length, key)
+        if cell.key == key:
+            result.found = 1
+            result.value = cell.value
+    return result
+
+
+cdef void* map_clear(MapStruct* map_, const key_t key) nogil:
+    if key == EMPTY_KEY:
+        value = map_.value_for_empty_key if map_.is_empty_key_set else NULL
+        map_.is_empty_key_set = False
+        return value
+    elif key == DELETED_KEY:
+        value = map_.value_for_del_key if map_.is_del_key_set else NULL
+        map_.is_del_key_set = False
+        return value
+    else:
+        cell = _find_cell(map_.cells, map_.length, key)
+        cell.key = DELETED_KEY
+        # We shouldn't decrement the "filled" value here, as we're not actually
+        # making "empty" values -- deleted values aren't quite the same.
+        # Instead if we manage to insert into a deleted slot, we don't increment
+        # the fill rate.
+        return cell.value
+
+
+cdef void* map_bulk_get(const MapStruct* map_, const key_t* keys, void** values,
+                        int n) nogil:
+    cdef int i
+    for i in range(n):
+        values[i] = map_get(map_, keys[i])
+
+
+cdef bint map_iter(const MapStruct* map_, int* i, key_t* key, void** value) nogil:
+    '''Iterate over the filled items, setting the current place in i, and the
+    key and value.  Return False when iteration finishes.
+    '''
+    cdef const Cell* cell
+    while i[0] < map_.length:
+        cell = &map_.cells[i[0]]
+        i[0] += 1
+        if cell[0].key != EMPTY_KEY and cell[0].key != DELETED_KEY:
+            key[0] = cell[0].key
+            value[0] = cell[0].value
+            return True
+    # Remember to check for cells keyed by the special empty and deleted keys
+    if i[0] == map_.length:
+        i[0] += 1
+        if map_.is_empty_key_set:
+            key[0] = EMPTY_KEY
+            value[0] = map_.value_for_empty_key
+            return True
+    if i[0] == map_.length + 1:
+        i[0] += 1
+        if map_.is_del_key_set:
+            key[0] = DELETED_KEY
+            value[0] = map_.value_for_del_key
+            return True
+    return False
+
+
+@cython.cdivision
+cdef inline Cell* _find_cell(Cell* cells, const key_t size, const key_t key) nogil:
+    # Modulo for powers-of-two via bitwise &
+    cdef key_t i = (key & (size - 1))
+    while cells[i].key != EMPTY_KEY and cells[i].key != key:
+        i = (i + 1) & (size - 1)
+    return &cells[i]
+
+
+@cython.cdivision
+cdef inline Cell* _find_cell_for_insertion(Cell* cells, const key_t size, const key_t key) nogil:
+    """Find the correct cell to insert a value, which could be a previously
+    deleted cell. If we cross a deleted cell and the key is in the table, we
+    mark the later cell as deleted, and return the earlier one."""
+    cdef Cell* deleted = NULL
+    # Modulo for powers-of-two via bitwise &
+    cdef key_t i = (key & (size - 1))
+    while cells[i].key != EMPTY_KEY and cells[i].key != key:
+        if cells[i].key == DELETED_KEY:
+            deleted = &cells[i]
+        i = (i + 1) & (size - 1)
+    if deleted is not NULL:
+        if cells[i].key == key:
+            # We need to ensure we don't end up with the key in the table twice.
+            # If we're using a deleted cell and we also have the key, we mark
+            # the later cell as deleted.
+            cells[i].key = DELETED_KEY
+        return deleted
+    return &cells[i]
+
+
+cdef void _resize(Pool mem, MapStruct* map_) except *:
+    cdef size_t new_size = map_.length * 2
+    cdef Cell* old_cells = map_.cells
+    cdef size_t old_size = map_.length
+
+    map_.length = new_size
+    map_.filled = 0
+    map_.cells = mem.alloc(new_size, sizeof(Cell))
+    
+    cdef size_t i
+    cdef size_t slot
+    for i in range(old_size):
+        if old_cells[i].key != EMPTY_KEY and old_cells[i].key != DELETED_KEY:
+            map_set(mem, map_, old_cells[i].key, old_cells[i].value)
+    mem.free(old_cells)
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pycparser-3.0.dist-info/INSTALLER b/TTS/Kokoro/.venv/Lib/site-packages/pycparser-3.0.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pycparser-3.0.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pycparser-3.0.dist-info/METADATA b/TTS/Kokoro/.venv/Lib/site-packages/pycparser-3.0.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..b94a88bb3f4d9b5d41bd639b818f79c01dce4fd1
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pycparser-3.0.dist-info/METADATA
@@ -0,0 +1,244 @@
+Metadata-Version: 2.4
+Name: pycparser
+Version: 3.0
+Summary: C parser in Python
+Author-email: Eli Bendersky 
+Maintainer-email: Eli Bendersky 
+License-Expression: BSD-3-Clause
+Project-URL: Homepage, https://github.com/eliben/pycparser
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Classifier: Programming Language :: Python :: 3.13
+Classifier: Programming Language :: Python :: 3.14
+Requires-Python: >=3.10
+Description-Content-Type: text/x-rst
+License-File: LICENSE
+Dynamic: license-file
+
+===============
+pycparser v3.00
+===============
+
+
+.. image:: https://github.com/eliben/pycparser/workflows/pycparser-tests/badge.svg
+  :align: center
+  :target: https://github.com/eliben/pycparser/actions
+
+----
+
+.. contents::
+    :backlinks: none
+
+.. sectnum::
+
+Introduction
+============
+
+What is pycparser?
+------------------
+
+**pycparser** is a parser for the C language, written in pure Python. It is a
+module designed to be easily integrated into applications that need to parse
+C source code.
+
+What is it good for?
+--------------------
+
+Anything that needs C code to be parsed. The following are some uses for
+**pycparser**, taken from real user reports:
+
+* C code obfuscator
+* Front-end for various specialized C compilers
+* Static code checker
+* Automatic unit-test discovery
+* Adding specialized extensions to the C language
+
+One of the most popular uses of **pycparser** is in the `cffi
+`_ library, which uses it to parse the
+declarations of C functions and types in order to auto-generate FFIs.
+
+**pycparser** is unique in the sense that it's written in pure Python - a very
+high level language that's easy to experiment with and tweak. To people familiar
+with Lex and Yacc, **pycparser**'s code will be simple to understand. It also
+has no external dependencies (except for a Python interpreter), making it very
+simple to install and deploy.
+
+Which version of C does pycparser support?
+------------------------------------------
+
+**pycparser** aims to support the full C99 language (according to the standard
+ISO/IEC 9899). Some features from C11 are also supported, and patches to support
+more are welcome.
+
+**pycparser** supports very few GCC extensions, but it's fairly easy to set
+things up so that it parses code with a lot of GCC-isms successfully. See the
+`FAQ `_ for more details.
+
+What grammar does pycparser follow?
+-----------------------------------
+
+**pycparser** very closely follows the C grammar provided in Annex A of the C99
+standard (ISO/IEC 9899).
+
+How is pycparser licensed?
+--------------------------
+
+`BSD license `_.
+
+Contact details
+---------------
+
+For reporting problems with **pycparser** or submitting feature requests, please
+open an `issue `_, or submit a
+pull request.
+
+
+Installing
+==========
+
+Prerequisites
+-------------
+
+**pycparser** is being tested with modern versions of Python on
+Linux, macOS and Windows. See `the CI dashboard `__
+for details.
+
+**pycparser** has no external dependencies.
+
+Installation process
+--------------------
+
+The recommended way to install **pycparser** is with ``pip``::
+
+    > pip install pycparser
+
+Using
+=====
+
+Interaction with the C preprocessor
+-----------------------------------
+
+In order to be compilable, C code must be preprocessed by the C preprocessor -
+``cpp``. A compatible ``cpp`` handles preprocessing directives like ``#include`` and
+``#define``, removes comments, and performs other minor tasks that prepare the C
+code for compilation.
+
+For all but the most trivial snippets of C code **pycparser**, like a C
+compiler, must receive preprocessed C code in order to function correctly. If
+you import the top-level ``parse_file`` function from the **pycparser** package,
+it will interact with ``cpp`` for you, as long as it's in your PATH, or you
+provide a path to it.
+
+Note also that you can use ``gcc -E`` or ``clang -E`` instead of ``cpp``. See
+the ``using_gcc_E_libc.py`` example for more details. Windows users can download
+and install a binary build of Clang for Windows `from this website
+`_.
+
+What about the standard C library headers?
+------------------------------------------
+
+C code almost always ``#include``\s various header files from the standard C
+library, like ``stdio.h``. While (with some effort) **pycparser** can be made to
+parse the standard headers from any C compiler, it's much simpler to use the
+provided "fake" standard includes for C11 in ``utils/fake_libc_include``. These
+are standard C header files that contain only the bare necessities to allow
+valid parsing of the files that use them. As a bonus, since they're minimal, it
+can significantly improve the performance of parsing large C files.
+
+The key point to understand here is that **pycparser** doesn't really care about
+the semantics of types. It only needs to know whether some token encountered in
+the source is a previously defined type. This is essential in order to be able
+to parse C correctly.
+
+See `this blog post
+`_
+for more details.
+
+Note that the fake headers are not included in the ``pip`` package nor installed
+via the package build (`#224 `_).
+
+Basic usage
+-----------
+
+Take a look at the |examples|_ directory of the distribution for a few examples
+of using **pycparser**. These should be enough to get you started. Please note
+that most realistic C code samples would require running the C preprocessor
+before passing the code to **pycparser**; see the previous sections for more
+details.
+
+.. |examples| replace:: ``examples``
+.. _examples: examples
+
+
+Advanced usage
+--------------
+
+The public interface of **pycparser** is well documented with comments in
+``pycparser/c_parser.py``. For a detailed overview of the various AST nodes
+created by the parser, see ``pycparser/_c_ast.cfg``.
+
+There's also a `FAQ available here `_.
+In any case, you can always drop me an `email `_ for help.
+
+
+Modifying
+=========
+
+There are a few points to keep in mind when modifying **pycparser**:
+
+* The code for **pycparser**'s AST nodes is automatically generated from a
+  configuration file - ``_c_ast.cfg``, by ``_ast_gen.py``. If you modify the AST
+  configuration, make sure to re-generate the code. This can be done by running
+  the ``_ast_gen.py`` script (from the repository root or the
+  ``pycparser`` directory).
+* Read the docstring in the constructor of the ``CParser`` class for details
+  on configuration and compatibility arguments.
+
+
+Package contents
+================
+
+Once you unzip the ``pycparser`` package, you'll see the following files and
+directories:
+
+README.rst:
+  This README file.
+
+LICENSE:
+  The pycparser license
+
+setup.py:
+  Legacy installation script (build metadata lives in ``pyproject.toml``).
+
+pyproject.toml:
+  Package metadata and build configuration.
+
+examples/:
+  A directory with some examples of using **pycparser**
+
+pycparser/:
+  The **pycparser** module source code.
+
+tests/:
+  Unit tests.
+
+utils/fake_libc_include:
+  Minimal standard C library include files that should allow to parse any C code.
+  Note that these headers now include C11 code, so they may not work when the
+  preprocessor is configured to an earlier C standard (like ``-std=c99``).
+
+utils/internal/:
+  Internal utilities for my own use. You probably don't need them.
+
+
+Contributors
+============
+
+Some people have contributed to **pycparser** by opening issues on bugs they've
+found and/or submitting patches. The list of contributors is in the CONTRIBUTORS
+file in the source distribution. After **pycparser** moved to Github I stopped
+updating this list because Github does a much better job at tracking
+contributions.
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pycparser-3.0.dist-info/RECORD b/TTS/Kokoro/.venv/Lib/site-packages/pycparser-3.0.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..e81dd9d8a31b8b7a3d7f781c6b7e9cecc67ba684
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pycparser-3.0.dist-info/RECORD
@@ -0,0 +1,21 @@
+pycparser-3.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+pycparser-3.0.dist-info/METADATA,sha256=9UemCwq1TMLyQiE9H4eWCtgN991d_rmNF6RE1Iv7a5M,8229
+pycparser-3.0.dist-info/RECORD,,
+pycparser-3.0.dist-info/WHEEL,sha256=qELbo2s1Yzl39ZmrAibXA2jjPLUYfnVhUNTlyF1rq0Y,92
+pycparser-3.0.dist-info/licenses/LICENSE,sha256=DIRjmTaep23de1xE_m0WSXQV_PAV9cu1CMJL-YuBxbE,1543
+pycparser-3.0.dist-info/top_level.txt,sha256=c-lPcS74L_8KoH7IE6PQF5ofyirRQNV4VhkbSFIPeWM,10
+pycparser/__init__.py,sha256=phViRyAuUmgqE4kNmaCqpm5WVEBIvzUSFapBv4XX3xo,2829
+pycparser/__pycache__/__init__.cpython-312.pyc,,
+pycparser/__pycache__/_ast_gen.cpython-312.pyc,,
+pycparser/__pycache__/ast_transforms.cpython-312.pyc,,
+pycparser/__pycache__/c_ast.cpython-312.pyc,,
+pycparser/__pycache__/c_generator.cpython-312.pyc,,
+pycparser/__pycache__/c_lexer.cpython-312.pyc,,
+pycparser/__pycache__/c_parser.cpython-312.pyc,,
+pycparser/_ast_gen.py,sha256=ExH5Ym4pk7dQPEIkQr9RJim5feztdBQwSBPvpvE-5BM,11292
+pycparser/_c_ast.cfg,sha256=ld5ezE9yzIJFIVAUfw7ezJSlMi4nXKNCzfmqjOyQTNo,4255
+pycparser/ast_transforms.py,sha256=XwMsarc5aDddNWgIiKm4-jOWMRYib96yNQUo0_u28WA,5899
+pycparser/c_ast.py,sha256=uwkcZWHfXDQIw6WDvCL17iWM_-0R-URDqEMmPjXLOAc,32954
+pycparser/c_generator.py,sha256=RVKJPguv2CvovHHSfQkqimckUr9wGU9PofxCGj251QA,20661
+pycparser/c_lexer.py,sha256=B1VoqbYhPWkOJJWCem4OY4zj0IxrPktBZZFe2Y87kUg,25155
+pycparser/c_parser.py,sha256=3FBKGLjjlC3v8afwD_cnMR67ImoYIy73a4WKQR6hX7g,89798
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pycparser-3.0.dist-info/WHEEL b/TTS/Kokoro/.venv/Lib/site-packages/pycparser-3.0.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..fbbd86cb272bc6e329803bf67f442f2a124caa95
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pycparser-3.0.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: setuptools (80.10.1)
+Root-Is-Purelib: true
+Tag: py3-none-any
+
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pycparser-3.0.dist-info/top_level.txt b/TTS/Kokoro/.venv/Lib/site-packages/pycparser-3.0.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..dc1c9e101ad9ccd943b359338ef42c342ebc84a1
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pycparser-3.0.dist-info/top_level.txt
@@ -0,0 +1 @@
+pycparser
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pycparser/__init__.py b/TTS/Kokoro/.venv/Lib/site-packages/pycparser/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..0606c03e205a154bb751de57fe8e03e277491fb0
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pycparser/__init__.py
@@ -0,0 +1,99 @@
+# -----------------------------------------------------------------
+# pycparser: __init__.py
+#
+# This package file exports some convenience functions for
+# interacting with pycparser
+#
+# Eli Bendersky [https://eli.thegreenplace.net/]
+# License: BSD
+# -----------------------------------------------------------------
+__all__ = ["c_lexer", "c_parser", "c_ast"]
+__version__ = "3.00"
+
+import io
+from subprocess import check_output
+
+from . import c_parser
+
+CParser = c_parser.CParser
+
+
+def preprocess_file(filename, cpp_path="cpp", cpp_args=""):
+    """Preprocess a file using cpp.
+
+    filename:
+        Name of the file you want to preprocess.
+
+    cpp_path:
+    cpp_args:
+        Refer to the documentation of parse_file for the meaning of these
+        arguments.
+
+    When successful, returns the preprocessed file's contents.
+    Errors from cpp will be printed out.
+    """
+    path_list = [cpp_path]
+    if isinstance(cpp_args, list):
+        path_list += cpp_args
+    elif cpp_args != "":
+        path_list += [cpp_args]
+    path_list += [filename]
+
+    try:
+        # Note the use of universal_newlines to treat all newlines
+        # as \n for Python's purpose
+        text = check_output(path_list, universal_newlines=True)
+    except OSError as e:
+        raise RuntimeError(
+            "Unable to invoke 'cpp'.  "
+            + "Make sure its path was passed correctly\n"
+            + f"Original error: {e}"
+        )
+
+    return text
+
+
+def parse_file(
+    filename, use_cpp=False, cpp_path="cpp", cpp_args="", parser=None, encoding=None
+):
+    """Parse a C file using pycparser.
+
+    filename:
+        Name of the file you want to parse.
+
+    use_cpp:
+        Set to True if you want to execute the C pre-processor
+        on the file prior to parsing it.
+
+    cpp_path:
+        If use_cpp is True, this is the path to 'cpp' on your
+        system. If no path is provided, it attempts to just
+        execute 'cpp', so it must be in your PATH.
+
+    cpp_args:
+        If use_cpp is True, set this to the command line arguments strings
+        to cpp. Be careful with quotes - it's best to pass a raw string
+        (r'') here. For example:
+        r'-I../utils/fake_libc_include'
+        If several arguments are required, pass a list of strings.
+
+    encoding:
+        Encoding to use for the file to parse
+
+    parser:
+        Optional parser object to be used instead of the default CParser
+
+    When successful, an AST is returned. ParseError can be
+    thrown if the file doesn't parse successfully.
+
+    Errors from cpp will be printed out.
+    """
+    if use_cpp:
+        text = preprocess_file(filename, cpp_path, cpp_args)
+    else:
+        with io.open(filename, encoding=encoding) as f:
+            text = f.read()
+
+    if parser is None:
+        parser = CParser()
+    return parser.parse(text, filename)
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pycparser/_ast_gen.py b/TTS/Kokoro/.venv/Lib/site-packages/pycparser/_ast_gen.py
new file mode 100644
index 0000000000000000000000000000000000000000..6df0b6a9b37e4cfc70a49c20c42b8a5e1828827c
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pycparser/_ast_gen.py
@@ -0,0 +1,355 @@
+# -----------------------------------------------------------------
+# _ast_gen.py
+#
+# Generates the AST Node classes from a specification given in
+# a configuration file. This module can also be run as a script to
+# regenerate c_ast.py from _c_ast.cfg (from the repo root or the
+# pycparser/ directory). Use 'make check' to reformat the generated
+# file after running this script.
+#
+# The design of this module was inspired by astgen.py from the
+# Python 2.5 code-base.
+#
+# Eli Bendersky [https://eli.thegreenplace.net/]
+# License: BSD
+# -----------------------------------------------------------------
+from string import Template
+import os
+from typing import IO
+
+
+class ASTCodeGenerator:
+    def __init__(self, cfg_filename="_c_ast.cfg"):
+        """Initialize the code generator from a configuration
+        file.
+        """
+        self.cfg_filename = cfg_filename
+        self.node_cfg = [
+            NodeCfg(name, contents)
+            for (name, contents) in self.parse_cfgfile(cfg_filename)
+        ]
+
+    def generate(self, file: IO[str]) -> None:
+        """Generates the code into file, an open file buffer."""
+        src = Template(_PROLOGUE_COMMENT).substitute(cfg_filename=self.cfg_filename)
+
+        src += _PROLOGUE_CODE
+        for node_cfg in self.node_cfg:
+            src += node_cfg.generate_source() + "\n\n"
+
+        file.write(src)
+
+    def parse_cfgfile(self, filename):
+        """Parse the configuration file and yield pairs of
+        (name, contents) for each node.
+        """
+        with open(filename, "r") as f:
+            for line in f:
+                line = line.strip()
+                if not line or line.startswith("#"):
+                    continue
+                colon_i = line.find(":")
+                lbracket_i = line.find("[")
+                rbracket_i = line.find("]")
+                if colon_i < 1 or lbracket_i <= colon_i or rbracket_i <= lbracket_i:
+                    raise RuntimeError(f"Invalid line in {filename}:\n{line}\n")
+
+                name = line[:colon_i]
+                val = line[lbracket_i + 1 : rbracket_i]
+                vallist = [v.strip() for v in val.split(",")] if val else []
+                yield name, vallist
+
+
+class NodeCfg:
+    """Node configuration.
+
+    name: node name
+    contents: a list of contents - attributes and child nodes
+    See comment at the top of the configuration file for details.
+    """
+
+    def __init__(self, name, contents):
+        self.name = name
+        self.all_entries = []
+        self.attr = []
+        self.child = []
+        self.seq_child = []
+
+        for entry in contents:
+            clean_entry = entry.rstrip("*")
+            self.all_entries.append(clean_entry)
+
+            if entry.endswith("**"):
+                self.seq_child.append(clean_entry)
+            elif entry.endswith("*"):
+                self.child.append(clean_entry)
+            else:
+                self.attr.append(entry)
+
+    def generate_source(self):
+        src = self._gen_init()
+        src += "\n" + self._gen_children()
+        src += "\n" + self._gen_iter()
+        src += "\n" + self._gen_attr_names()
+        return src
+
+    def _gen_init(self):
+        src = f"class {self.name}(Node):\n"
+
+        if self.all_entries:
+            args = ", ".join(self.all_entries)
+            slots = ", ".join(f"'{e}'" for e in self.all_entries)
+            slots += ", 'coord', '__weakref__'"
+            arglist = f"(self, {args}, coord=None)"
+        else:
+            slots = "'coord', '__weakref__'"
+            arglist = "(self, coord=None)"
+
+        src += f"    __slots__ = ({slots})\n"
+        src += f"    def __init__{arglist}:\n"
+
+        for name in self.all_entries + ["coord"]:
+            src += f"        self.{name} = {name}\n"
+
+        return src
+
+    def _gen_children(self):
+        src = "    def children(self):\n"
+
+        if self.all_entries:
+            src += "        nodelist = []\n"
+
+            for child in self.child:
+                src += f"        if self.{child} is not None:\n"
+                src += f'            nodelist.append(("{child}", self.{child}))\n'
+
+            for seq_child in self.seq_child:
+                src += f"        for i, child in enumerate(self.{seq_child} or []):\n"
+                src += f'            nodelist.append((f"{seq_child}[{{i}}]", child))\n'
+
+            src += "        return tuple(nodelist)\n"
+        else:
+            src += "        return ()\n"
+
+        return src
+
+    def _gen_iter(self):
+        src = "    def __iter__(self):\n"
+
+        if self.all_entries:
+            for child in self.child:
+                src += f"        if self.{child} is not None:\n"
+                src += f"            yield self.{child}\n"
+
+            for seq_child in self.seq_child:
+                src += f"        for child in (self.{seq_child} or []):\n"
+                src += "            yield child\n"
+
+            if not (self.child or self.seq_child):
+                # Empty generator
+                src += "        return\n" + "        yield\n"
+        else:
+            # Empty generator
+            src += "        return\n" + "        yield\n"
+
+        return src
+
+    def _gen_attr_names(self):
+        src = "    attr_names = (" + "".join(f"{nm!r}, " for nm in self.attr) + ")"
+        return src
+
+
+_PROLOGUE_COMMENT = r"""#-----------------------------------------------------------------
+# ** ATTENTION **
+# This code was automatically generated from _c_ast.cfg
+#
+# Do not modify it directly. Modify the configuration file and
+# run the generator again.
+# ** ** *** ** **
+#
+# pycparser: c_ast.py
+#
+# AST Node classes.
+#
+# Eli Bendersky [https://eli.thegreenplace.net/]
+# License: BSD
+#-----------------------------------------------------------------
+
+"""
+_PROLOGUE_CODE = r'''
+import sys
+from typing import Any, ClassVar, IO, Optional
+
+def _repr(obj):
+    """
+    Get the representation of an object, with dedicated pprint-like format for lists.
+    """
+    if isinstance(obj, list):
+        return '[' + (',\n '.join((_repr(e).replace('\n', '\n ') for e in obj))) + '\n]'
+    else:
+        return repr(obj)
+
+class Node:
+    __slots__ = ()
+    """ Abstract base class for AST nodes.
+    """
+    attr_names: ClassVar[tuple[str, ...]] = ()
+    coord: Optional[Any]
+    def __repr__(self):
+        """ Generates a python representation of the current node
+        """
+        result = self.__class__.__name__ + '('
+
+        indent = ''
+        separator = ''
+        for name in self.__slots__[:-2]:
+            result += separator
+            result += indent
+            result += name + '=' + (_repr(getattr(self, name)).replace('\n', '\n  ' + (' ' * (len(name) + len(self.__class__.__name__)))))
+
+            separator = ','
+            indent = '\n ' + (' ' * len(self.__class__.__name__))
+
+        result += indent + ')'
+
+        return result
+
+    def children(self):
+        """ A sequence of all children that are Nodes
+        """
+        pass
+
+    def show(
+        self,
+        buf: IO[str] = sys.stdout,
+        offset: int = 0,
+        attrnames: bool = False,
+        showemptyattrs: bool = True,
+        nodenames: bool = False,
+        showcoord: bool = False,
+        _my_node_name: Optional[str] = None,
+    ):
+        """ Pretty print the Node and all its attributes and
+            children (recursively) to a buffer.
+
+            buf:
+                Open IO buffer into which the Node is printed.
+
+            offset:
+                Initial offset (amount of leading spaces)
+
+            attrnames:
+                True if you want to see the attribute names in
+                name=value pairs. False to only see the values.
+
+            showemptyattrs:
+                False if you want to suppress printing empty attributes.
+
+            nodenames:
+                True if you want to see the actual node names
+                within their parents.
+
+            showcoord:
+                Do you want the coordinates of each Node to be
+                displayed.
+        """
+        lead = ' ' * offset
+        if nodenames and _my_node_name is not None:
+            buf.write(lead + self.__class__.__name__+ ' <' + _my_node_name + '>: ')
+        else:
+            buf.write(lead + self.__class__.__name__+ ': ')
+
+        if self.attr_names:
+            def is_empty(v):
+                v is None or (hasattr(v, '__len__') and len(v) == 0)
+            nvlist = [(n, getattr(self,n)) for n in self.attr_names \
+                        if showemptyattrs or not is_empty(getattr(self,n))]
+            if attrnames:
+                attrstr = ', '.join(f'{name}={value}' for name, value in nvlist)
+            else:
+                attrstr = ', '.join(f'{value}' for _, value in nvlist)
+            buf.write(attrstr)
+
+        if showcoord:
+            buf.write(f' (at {self.coord})')
+        buf.write('\n')
+
+        for (child_name, child) in self.children():
+            child.show(
+                buf,
+                offset=offset + 2,
+                attrnames=attrnames,
+                showemptyattrs=showemptyattrs,
+                nodenames=nodenames,
+                showcoord=showcoord,
+                _my_node_name=child_name)
+
+
+class NodeVisitor:
+    """ A base NodeVisitor class for visiting c_ast nodes.
+        Subclass it and define your own visit_XXX methods, where
+        XXX is the class name you want to visit with these
+        methods.
+
+        For example:
+
+        class ConstantVisitor(NodeVisitor):
+            def __init__(self):
+                self.values = []
+
+            def visit_Constant(self, node):
+                self.values.append(node.value)
+
+        Creates a list of values of all the constant nodes
+        encountered below the given node. To use it:
+
+        cv = ConstantVisitor()
+        cv.visit(node)
+
+        Notes:
+
+        *   generic_visit() will be called for AST nodes for which
+            no visit_XXX method was defined.
+        *   The children of nodes for which a visit_XXX was
+            defined will not be visited - if you need this, call
+            generic_visit() on the node.
+            You can use:
+                NodeVisitor.generic_visit(self, node)
+        *   Modeled after Python's own AST visiting facilities
+            (the ast module of Python 3.0)
+    """
+
+    _method_cache = None
+
+    def visit(self, node: Node):
+        """ Visit a node.
+        """
+
+        if self._method_cache is None:
+            self._method_cache = {}
+
+        visitor = self._method_cache.get(node.__class__.__name__, None)
+        if visitor is None:
+            method = 'visit_' + node.__class__.__name__
+            visitor = getattr(self, method, self.generic_visit)
+            self._method_cache[node.__class__.__name__] = visitor
+
+        return visitor(node)
+
+    def generic_visit(self, node: Node):
+        """ Called if no explicit visitor function exists for a
+            node. Implements preorder visiting of the node.
+        """
+        for _, c in node.children():
+            self.visit(c)
+
+'''
+
+
+if __name__ == "__main__":
+    base_dir = os.path.dirname(os.path.abspath(__file__))
+    cfg_path = os.path.join(base_dir, "_c_ast.cfg")
+    out_path = os.path.join(base_dir, "c_ast.py")
+    ast_gen = ASTCodeGenerator(cfg_path)
+    with open(out_path, "w") as out:
+        ast_gen.generate(out)
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pycparser/_c_ast.cfg b/TTS/Kokoro/.venv/Lib/site-packages/pycparser/_c_ast.cfg
new file mode 100644
index 0000000000000000000000000000000000000000..0626533e8adf517da897ec047c8deb6ad41c38c9
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pycparser/_c_ast.cfg
@@ -0,0 +1,195 @@
+#-----------------------------------------------------------------
+# pycparser: _c_ast.cfg
+#
+# Defines the AST Node classes used in pycparser.
+#
+# Each entry is a Node sub-class name, listing the attributes
+# and child nodes of the class:
+#   *     - a child node
+#   **    - a sequence of child nodes
+#         - an attribute
+#
+# Eli Bendersky [https://eli.thegreenplace.net/]
+# License: BSD
+#-----------------------------------------------------------------
+
+# ArrayDecl is a nested declaration of an array with the given type.
+# dim: the dimension (for example, constant 42)
+# dim_quals: list of dimension qualifiers, to support C99's allowing 'const'
+#            and 'static' within the array dimension in function declarations.
+ArrayDecl: [type*, dim*, dim_quals]
+
+ArrayRef: [name*, subscript*]
+
+# op: =, +=, /= etc.
+#
+Assignment: [op, lvalue*, rvalue*]
+
+Alignas: [alignment*]
+
+BinaryOp: [op, left*, right*]
+
+Break: []
+
+Case: [expr*, stmts**]
+
+Cast: [to_type*, expr*]
+
+# Compound statement in C99 is a list of block items (declarations or
+# statements).
+#
+Compound: [block_items**]
+
+# Compound literal (anonymous aggregate) for C99.
+# (type-name) {initializer_list}
+# type: the typename
+# init: InitList for the initializer list
+#
+CompoundLiteral: [type*, init*]
+
+# type: int, char, float, string, etc.
+#
+Constant: [type, value]
+
+Continue: []
+
+# name: the variable being declared
+# quals: list of qualifiers (const, volatile)
+# funcspec: list function specifiers (i.e. inline in C99)
+# storage: list of storage specifiers (extern, register, etc.)
+# type: declaration type (probably nested with all the modifiers)
+# init: initialization value, or None
+# bitsize: bit field size, or None
+#
+Decl: [name, quals, align, storage, funcspec, type*, init*, bitsize*]
+
+DeclList: [decls**]
+
+Default: [stmts**]
+
+DoWhile: [cond*, stmt*]
+
+# Represents the ellipsis (...) parameter in a function
+# declaration
+#
+EllipsisParam: []
+
+# An empty statement (a semicolon ';' on its own)
+#
+EmptyStatement: []
+
+# Enumeration type specifier
+# name: an optional ID
+# values: an EnumeratorList
+#
+Enum: [name, values*]
+
+# A name/value pair for enumeration values
+#
+Enumerator: [name, value*]
+
+# A list of enumerators
+#
+EnumeratorList: [enumerators**]
+
+# A list of expressions separated by the comma operator.
+#
+ExprList: [exprs**]
+
+# This is the top of the AST, representing a single C file (a
+# translation unit in K&R jargon). It contains a list of
+# "external-declaration"s, which is either declarations (Decl),
+# Typedef or function definitions (FuncDef).
+#
+FileAST: [ext**]
+
+# for (init; cond; next) stmt
+#
+For: [init*, cond*, next*, stmt*]
+
+# name: Id
+# args: ExprList
+#
+FuncCall: [name*, args*]
+
+# type (args)
+#
+FuncDecl: [args*, type*]
+
+# Function definition: a declarator for the function name and
+# a body, which is a compound statement.
+# There's an optional list of parameter declarations for old
+# K&R-style definitions
+#
+FuncDef: [decl*, param_decls**, body*]
+
+Goto: [name]
+
+ID: [name]
+
+# Holder for types that are a simple identifier (e.g. the built
+# ins void, char etc. and typedef-defined types)
+#
+IdentifierType: [names]
+
+If: [cond*, iftrue*, iffalse*]
+
+# An initialization list used for compound literals.
+#
+InitList: [exprs**]
+
+Label: [name, stmt*]
+
+# A named initializer for C99.
+# The name of a NamedInitializer is a sequence of Nodes, because
+# names can be hierarchical and contain constant expressions.
+#
+NamedInitializer: [name**, expr*]
+
+# a list of comma separated function parameter declarations
+#
+ParamList: [params**]
+
+PtrDecl: [quals, type*]
+
+Return: [expr*]
+
+StaticAssert: [cond*, message*]
+
+# name: struct tag name
+# decls: declaration of members
+#
+Struct: [name, decls**]
+
+# type: . or ->
+# name.field or name->field
+#
+StructRef: [name*, type, field*]
+
+Switch: [cond*, stmt*]
+
+# cond ? iftrue : iffalse
+#
+TernaryOp: [cond*, iftrue*, iffalse*]
+
+# A base type declaration
+#
+TypeDecl: [declname, quals, align, type*]
+
+# A typedef declaration.
+# Very similar to Decl, but without some attributes
+#
+Typedef: [name, quals, storage, type*]
+
+Typename: [name, quals, align, type*]
+
+UnaryOp: [op, expr*]
+
+# name: union tag name
+# decls: declaration of members
+#
+Union: [name, decls**]
+
+While: [cond*, stmt*]
+
+Pragma: [string]
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pycparser/ast_transforms.py b/TTS/Kokoro/.venv/Lib/site-packages/pycparser/ast_transforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..1051737f65d106e23acf8685b57dfd12c811b934
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pycparser/ast_transforms.py
@@ -0,0 +1,174 @@
+# ------------------------------------------------------------------------------
+# pycparser: ast_transforms.py
+#
+# Some utilities used by the parser to create a friendlier AST.
+#
+# Eli Bendersky [https://eli.thegreenplace.net/]
+# License: BSD
+# ------------------------------------------------------------------------------
+
+from typing import Any, List, Tuple, cast
+
+from . import c_ast
+
+
+def fix_switch_cases(switch_node: c_ast.Switch) -> c_ast.Switch:
+    """The 'case' statements in a 'switch' come out of parsing with one
+    child node, so subsequent statements are just tucked to the parent
+    Compound. Additionally, consecutive (fall-through) case statements
+    come out messy. This is a peculiarity of the C grammar. The following:
+
+        switch (myvar) {
+            case 10:
+                k = 10;
+                p = k + 1;
+                return 10;
+            case 20:
+            case 30:
+                return 20;
+            default:
+                break;
+        }
+
+    Creates this tree (pseudo-dump):
+
+        Switch
+            ID: myvar
+            Compound:
+                Case 10:
+                    k = 10
+                p = k + 1
+                return 10
+                Case 20:
+                    Case 30:
+                        return 20
+                Default:
+                    break
+
+    The goal of this transform is to fix this mess, turning it into the
+    following:
+
+        Switch
+            ID: myvar
+            Compound:
+                Case 10:
+                    k = 10
+                    p = k + 1
+                    return 10
+                Case 20:
+                Case 30:
+                    return 20
+                Default:
+                    break
+
+    A fixed AST node is returned. The argument may be modified.
+    """
+    assert isinstance(switch_node, c_ast.Switch)
+    if not isinstance(switch_node.stmt, c_ast.Compound):
+        return switch_node
+
+    # The new Compound child for the Switch, which will collect children in the
+    # correct order
+    new_compound = c_ast.Compound([], switch_node.stmt.coord)
+
+    # The last Case/Default node
+    last_case: c_ast.Case | c_ast.Default | None = None
+
+    # Goes over the children of the Compound below the Switch, adding them
+    # either directly below new_compound or below the last Case as appropriate
+    # (for `switch(cond) {}`, block_items would have been None)
+    for child in switch_node.stmt.block_items or []:
+        if isinstance(child, (c_ast.Case, c_ast.Default)):
+            # If it's a Case/Default:
+            # 1. Add it to the Compound and mark as "last case"
+            # 2. If its immediate child is also a Case or Default, promote it
+            #    to a sibling.
+            new_compound.block_items.append(child)
+            _extract_nested_case(child, new_compound.block_items)
+            last_case = new_compound.block_items[-1]
+        else:
+            # Other statements are added as children to the last case, if it
+            # exists.
+            if last_case is None:
+                new_compound.block_items.append(child)
+            else:
+                last_case.stmts.append(child)
+
+    switch_node.stmt = new_compound
+    return switch_node
+
+
+def _extract_nested_case(
+    case_node: c_ast.Case | c_ast.Default, stmts_list: List[c_ast.Node]
+) -> None:
+    """Recursively extract consecutive Case statements that are made nested
+    by the parser and add them to the stmts_list.
+    """
+    if isinstance(case_node.stmts[0], (c_ast.Case, c_ast.Default)):
+        nested = case_node.stmts.pop()
+        stmts_list.append(nested)
+        _extract_nested_case(cast(Any, nested), stmts_list)
+
+
+def fix_atomic_specifiers(
+    decl: c_ast.Decl | c_ast.Typedef,
+) -> c_ast.Decl | c_ast.Typedef:
+    """Atomic specifiers like _Atomic(type) are unusually structured,
+    conferring a qualifier upon the contained type.
+
+    This function fixes a decl with atomic specifiers to have a sane AST
+    structure, by removing spurious Typename->TypeDecl pairs and attaching
+    the _Atomic qualifier in the right place.
+    """
+    # There can be multiple levels of _Atomic in a decl; fix them until a
+    # fixed point is reached.
+    while True:
+        decl, found = _fix_atomic_specifiers_once(decl)
+        if not found:
+            break
+
+    # Make sure to add an _Atomic qual on the topmost decl if needed. Also
+    # restore the declname on the innermost TypeDecl (it gets placed in the
+    # wrong place during construction).
+    typ: Any = decl
+    while not isinstance(typ, c_ast.TypeDecl):
+        try:
+            typ = typ.type
+        except AttributeError:
+            return decl
+    if "_Atomic" in typ.quals and "_Atomic" not in decl.quals:
+        decl.quals.append("_Atomic")
+    if typ.declname is None:
+        typ.declname = decl.name
+
+    return decl
+
+
+def _fix_atomic_specifiers_once(
+    decl: c_ast.Decl | c_ast.Typedef,
+) -> Tuple[c_ast.Decl | c_ast.Typedef, bool]:
+    """Performs one 'fix' round of atomic specifiers.
+    Returns (modified_decl, found) where found is True iff a fix was made.
+    """
+    parent: Any = decl
+    grandparent: Any = None
+    node: Any = decl.type
+    while node is not None:
+        if isinstance(node, c_ast.Typename) and "_Atomic" in node.quals:
+            break
+        try:
+            grandparent = parent
+            parent = node
+            node = node.type
+        except AttributeError:
+            # If we've reached a node without a `type` field, it means we won't
+            # find what we're looking for at this point; give up the search
+            # and return the original decl unmodified.
+            return decl, False
+
+    assert isinstance(parent, c_ast.TypeDecl)
+    assert grandparent is not None
+    cast(Any, grandparent).type = node.type
+    if "_Atomic" not in node.type.quals:
+        node.type.quals.append("_Atomic")
+    return decl, True
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pycparser/c_ast.py b/TTS/Kokoro/.venv/Lib/site-packages/pycparser/c_ast.py
new file mode 100644
index 0000000000000000000000000000000000000000..b6f42af8a183ee61b9ff8f2d85c60cd3eb18afc4
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pycparser/c_ast.py
@@ -0,0 +1,1341 @@
+# -----------------------------------------------------------------
+# ** ATTENTION **
+# This code was automatically generated from _c_ast.cfg
+#
+# Do not modify it directly. Modify the configuration file and
+# run the generator again.
+# ** ** *** ** **
+#
+# pycparser: c_ast.py
+#
+# AST Node classes.
+#
+# Eli Bendersky [https://eli.thegreenplace.net/]
+# License: BSD
+# -----------------------------------------------------------------
+
+
+import sys
+from typing import Any, ClassVar, IO, Optional
+
+
+def _repr(obj):
+    """
+    Get the representation of an object, with dedicated pprint-like format for lists.
+    """
+    if isinstance(obj, list):
+        return "[" + (",\n ".join((_repr(e).replace("\n", "\n ") for e in obj))) + "\n]"
+    else:
+        return repr(obj)
+
+
+class Node:
+    __slots__ = ()
+    """ Abstract base class for AST nodes.
+    """
+    attr_names: ClassVar[tuple[str, ...]] = ()
+    coord: Optional[Any]
+
+    def __repr__(self):
+        """Generates a python representation of the current node"""
+        result = self.__class__.__name__ + "("
+
+        indent = ""
+        separator = ""
+        for name in self.__slots__[:-2]:
+            result += separator
+            result += indent
+            result += (
+                name
+                + "="
+                + (
+                    _repr(getattr(self, name)).replace(
+                        "\n",
+                        "\n  " + (" " * (len(name) + len(self.__class__.__name__))),
+                    )
+                )
+            )
+
+            separator = ","
+            indent = "\n " + (" " * len(self.__class__.__name__))
+
+        result += indent + ")"
+
+        return result
+
+    def children(self):
+        """A sequence of all children that are Nodes"""
+        pass
+
+    def show(
+        self,
+        buf: IO[str] = sys.stdout,
+        offset: int = 0,
+        attrnames: bool = False,
+        showemptyattrs: bool = True,
+        nodenames: bool = False,
+        showcoord: bool = False,
+        _my_node_name: Optional[str] = None,
+    ):
+        """Pretty print the Node and all its attributes and
+        children (recursively) to a buffer.
+
+        buf:
+            Open IO buffer into which the Node is printed.
+
+        offset:
+            Initial offset (amount of leading spaces)
+
+        attrnames:
+            True if you want to see the attribute names in
+            name=value pairs. False to only see the values.
+
+        showemptyattrs:
+            False if you want to suppress printing empty attributes.
+
+        nodenames:
+            True if you want to see the actual node names
+            within their parents.
+
+        showcoord:
+            Do you want the coordinates of each Node to be
+            displayed.
+        """
+        lead = " " * offset
+        if nodenames and _my_node_name is not None:
+            buf.write(lead + self.__class__.__name__ + " <" + _my_node_name + ">: ")
+        else:
+            buf.write(lead + self.__class__.__name__ + ": ")
+
+        if self.attr_names:
+
+            def is_empty(v):
+                v is None or (hasattr(v, "__len__") and len(v) == 0)
+
+            nvlist = [
+                (n, getattr(self, n))
+                for n in self.attr_names
+                if showemptyattrs or not is_empty(getattr(self, n))
+            ]
+            if attrnames:
+                attrstr = ", ".join(f"{name}={value}" for name, value in nvlist)
+            else:
+                attrstr = ", ".join(f"{value}" for _, value in nvlist)
+            buf.write(attrstr)
+
+        if showcoord:
+            buf.write(f" (at {self.coord})")
+        buf.write("\n")
+
+        for child_name, child in self.children():
+            child.show(
+                buf,
+                offset=offset + 2,
+                attrnames=attrnames,
+                showemptyattrs=showemptyattrs,
+                nodenames=nodenames,
+                showcoord=showcoord,
+                _my_node_name=child_name,
+            )
+
+
+class NodeVisitor:
+    """A base NodeVisitor class for visiting c_ast nodes.
+    Subclass it and define your own visit_XXX methods, where
+    XXX is the class name you want to visit with these
+    methods.
+
+    For example:
+
+    class ConstantVisitor(NodeVisitor):
+        def __init__(self):
+            self.values = []
+
+        def visit_Constant(self, node):
+            self.values.append(node.value)
+
+    Creates a list of values of all the constant nodes
+    encountered below the given node. To use it:
+
+    cv = ConstantVisitor()
+    cv.visit(node)
+
+    Notes:
+
+    *   generic_visit() will be called for AST nodes for which
+        no visit_XXX method was defined.
+    *   The children of nodes for which a visit_XXX was
+        defined will not be visited - if you need this, call
+        generic_visit() on the node.
+        You can use:
+            NodeVisitor.generic_visit(self, node)
+    *   Modeled after Python's own AST visiting facilities
+        (the ast module of Python 3.0)
+    """
+
+    _method_cache = None
+
+    def visit(self, node: Node):
+        """Visit a node."""
+
+        if self._method_cache is None:
+            self._method_cache = {}
+
+        visitor = self._method_cache.get(node.__class__.__name__, None)
+        if visitor is None:
+            method = "visit_" + node.__class__.__name__
+            visitor = getattr(self, method, self.generic_visit)
+            self._method_cache[node.__class__.__name__] = visitor
+
+        return visitor(node)
+
+    def generic_visit(self, node: Node):
+        """Called if no explicit visitor function exists for a
+        node. Implements preorder visiting of the node.
+        """
+        for _, c in node.children():
+            self.visit(c)
+
+
+class ArrayDecl(Node):
+    __slots__ = ("type", "dim", "dim_quals", "coord", "__weakref__")
+
+    def __init__(self, type, dim, dim_quals, coord=None):
+        self.type = type
+        self.dim = dim
+        self.dim_quals = dim_quals
+        self.coord = coord
+
+    def children(self):
+        nodelist = []
+        if self.type is not None:
+            nodelist.append(("type", self.type))
+        if self.dim is not None:
+            nodelist.append(("dim", self.dim))
+        return tuple(nodelist)
+
+    def __iter__(self):
+        if self.type is not None:
+            yield self.type
+        if self.dim is not None:
+            yield self.dim
+
+    attr_names = ("dim_quals",)
+
+
+class ArrayRef(Node):
+    __slots__ = ("name", "subscript", "coord", "__weakref__")
+
+    def __init__(self, name, subscript, coord=None):
+        self.name = name
+        self.subscript = subscript
+        self.coord = coord
+
+    def children(self):
+        nodelist = []
+        if self.name is not None:
+            nodelist.append(("name", self.name))
+        if self.subscript is not None:
+            nodelist.append(("subscript", self.subscript))
+        return tuple(nodelist)
+
+    def __iter__(self):
+        if self.name is not None:
+            yield self.name
+        if self.subscript is not None:
+            yield self.subscript
+
+    attr_names = ()
+
+
+class Assignment(Node):
+    __slots__ = ("op", "lvalue", "rvalue", "coord", "__weakref__")
+
+    def __init__(self, op, lvalue, rvalue, coord=None):
+        self.op = op
+        self.lvalue = lvalue
+        self.rvalue = rvalue
+        self.coord = coord
+
+    def children(self):
+        nodelist = []
+        if self.lvalue is not None:
+            nodelist.append(("lvalue", self.lvalue))
+        if self.rvalue is not None:
+            nodelist.append(("rvalue", self.rvalue))
+        return tuple(nodelist)
+
+    def __iter__(self):
+        if self.lvalue is not None:
+            yield self.lvalue
+        if self.rvalue is not None:
+            yield self.rvalue
+
+    attr_names = ("op",)
+
+
+class Alignas(Node):
+    __slots__ = ("alignment", "coord", "__weakref__")
+
+    def __init__(self, alignment, coord=None):
+        self.alignment = alignment
+        self.coord = coord
+
+    def children(self):
+        nodelist = []
+        if self.alignment is not None:
+            nodelist.append(("alignment", self.alignment))
+        return tuple(nodelist)
+
+    def __iter__(self):
+        if self.alignment is not None:
+            yield self.alignment
+
+    attr_names = ()
+
+
+class BinaryOp(Node):
+    __slots__ = ("op", "left", "right", "coord", "__weakref__")
+
+    def __init__(self, op, left, right, coord=None):
+        self.op = op
+        self.left = left
+        self.right = right
+        self.coord = coord
+
+    def children(self):
+        nodelist = []
+        if self.left is not None:
+            nodelist.append(("left", self.left))
+        if self.right is not None:
+            nodelist.append(("right", self.right))
+        return tuple(nodelist)
+
+    def __iter__(self):
+        if self.left is not None:
+            yield self.left
+        if self.right is not None:
+            yield self.right
+
+    attr_names = ("op",)
+
+
+class Break(Node):
+    __slots__ = ("coord", "__weakref__")
+
+    def __init__(self, coord=None):
+        self.coord = coord
+
+    def children(self):
+        return ()
+
+    def __iter__(self):
+        return
+        yield
+
+    attr_names = ()
+
+
+class Case(Node):
+    __slots__ = ("expr", "stmts", "coord", "__weakref__")
+
+    def __init__(self, expr, stmts, coord=None):
+        self.expr = expr
+        self.stmts = stmts
+        self.coord = coord
+
+    def children(self):
+        nodelist = []
+        if self.expr is not None:
+            nodelist.append(("expr", self.expr))
+        for i, child in enumerate(self.stmts or []):
+            nodelist.append((f"stmts[{i}]", child))
+        return tuple(nodelist)
+
+    def __iter__(self):
+        if self.expr is not None:
+            yield self.expr
+        for child in self.stmts or []:
+            yield child
+
+    attr_names = ()
+
+
+class Cast(Node):
+    __slots__ = ("to_type", "expr", "coord", "__weakref__")
+
+    def __init__(self, to_type, expr, coord=None):
+        self.to_type = to_type
+        self.expr = expr
+        self.coord = coord
+
+    def children(self):
+        nodelist = []
+        if self.to_type is not None:
+            nodelist.append(("to_type", self.to_type))
+        if self.expr is not None:
+            nodelist.append(("expr", self.expr))
+        return tuple(nodelist)
+
+    def __iter__(self):
+        if self.to_type is not None:
+            yield self.to_type
+        if self.expr is not None:
+            yield self.expr
+
+    attr_names = ()
+
+
+class Compound(Node):
+    __slots__ = ("block_items", "coord", "__weakref__")
+
+    def __init__(self, block_items, coord=None):
+        self.block_items = block_items
+        self.coord = coord
+
+    def children(self):
+        nodelist = []
+        for i, child in enumerate(self.block_items or []):
+            nodelist.append((f"block_items[{i}]", child))
+        return tuple(nodelist)
+
+    def __iter__(self):
+        for child in self.block_items or []:
+            yield child
+
+    attr_names = ()
+
+
+class CompoundLiteral(Node):
+    __slots__ = ("type", "init", "coord", "__weakref__")
+
+    def __init__(self, type, init, coord=None):
+        self.type = type
+        self.init = init
+        self.coord = coord
+
+    def children(self):
+        nodelist = []
+        if self.type is not None:
+            nodelist.append(("type", self.type))
+        if self.init is not None:
+            nodelist.append(("init", self.init))
+        return tuple(nodelist)
+
+    def __iter__(self):
+        if self.type is not None:
+            yield self.type
+        if self.init is not None:
+            yield self.init
+
+    attr_names = ()
+
+
+class Constant(Node):
+    __slots__ = ("type", "value", "coord", "__weakref__")
+
+    def __init__(self, type, value, coord=None):
+        self.type = type
+        self.value = value
+        self.coord = coord
+
+    def children(self):
+        nodelist = []
+        return tuple(nodelist)
+
+    def __iter__(self):
+        return
+        yield
+
+    attr_names = (
+        "type",
+        "value",
+    )
+
+
+class Continue(Node):
+    __slots__ = ("coord", "__weakref__")
+
+    def __init__(self, coord=None):
+        self.coord = coord
+
+    def children(self):
+        return ()
+
+    def __iter__(self):
+        return
+        yield
+
+    attr_names = ()
+
+
+class Decl(Node):
+    __slots__ = (
+        "name",
+        "quals",
+        "align",
+        "storage",
+        "funcspec",
+        "type",
+        "init",
+        "bitsize",
+        "coord",
+        "__weakref__",
+    )
+
+    def __init__(
+        self, name, quals, align, storage, funcspec, type, init, bitsize, coord=None
+    ):
+        self.name = name
+        self.quals = quals
+        self.align = align
+        self.storage = storage
+        self.funcspec = funcspec
+        self.type = type
+        self.init = init
+        self.bitsize = bitsize
+        self.coord = coord
+
+    def children(self):
+        nodelist = []
+        if self.type is not None:
+            nodelist.append(("type", self.type))
+        if self.init is not None:
+            nodelist.append(("init", self.init))
+        if self.bitsize is not None:
+            nodelist.append(("bitsize", self.bitsize))
+        return tuple(nodelist)
+
+    def __iter__(self):
+        if self.type is not None:
+            yield self.type
+        if self.init is not None:
+            yield self.init
+        if self.bitsize is not None:
+            yield self.bitsize
+
+    attr_names = (
+        "name",
+        "quals",
+        "align",
+        "storage",
+        "funcspec",
+    )
+
+
+class DeclList(Node):
+    __slots__ = ("decls", "coord", "__weakref__")
+
+    def __init__(self, decls, coord=None):
+        self.decls = decls
+        self.coord = coord
+
+    def children(self):
+        nodelist = []
+        for i, child in enumerate(self.decls or []):
+            nodelist.append((f"decls[{i}]", child))
+        return tuple(nodelist)
+
+    def __iter__(self):
+        for child in self.decls or []:
+            yield child
+
+    attr_names = ()
+
+
+class Default(Node):
+    __slots__ = ("stmts", "coord", "__weakref__")
+
+    def __init__(self, stmts, coord=None):
+        self.stmts = stmts
+        self.coord = coord
+
+    def children(self):
+        nodelist = []
+        for i, child in enumerate(self.stmts or []):
+            nodelist.append((f"stmts[{i}]", child))
+        return tuple(nodelist)
+
+    def __iter__(self):
+        for child in self.stmts or []:
+            yield child
+
+    attr_names = ()
+
+
+class DoWhile(Node):
+    __slots__ = ("cond", "stmt", "coord", "__weakref__")
+
+    def __init__(self, cond, stmt, coord=None):
+        self.cond = cond
+        self.stmt = stmt
+        self.coord = coord
+
+    def children(self):
+        nodelist = []
+        if self.cond is not None:
+            nodelist.append(("cond", self.cond))
+        if self.stmt is not None:
+            nodelist.append(("stmt", self.stmt))
+        return tuple(nodelist)
+
+    def __iter__(self):
+        if self.cond is not None:
+            yield self.cond
+        if self.stmt is not None:
+            yield self.stmt
+
+    attr_names = ()
+
+
+class EllipsisParam(Node):
+    __slots__ = ("coord", "__weakref__")
+
+    def __init__(self, coord=None):
+        self.coord = coord
+
+    def children(self):
+        return ()
+
+    def __iter__(self):
+        return
+        yield
+
+    attr_names = ()
+
+
+class EmptyStatement(Node):
+    __slots__ = ("coord", "__weakref__")
+
+    def __init__(self, coord=None):
+        self.coord = coord
+
+    def children(self):
+        return ()
+
+    def __iter__(self):
+        return
+        yield
+
+    attr_names = ()
+
+
+class Enum(Node):
+    __slots__ = ("name", "values", "coord", "__weakref__")
+
+    def __init__(self, name, values, coord=None):
+        self.name = name
+        self.values = values
+        self.coord = coord
+
+    def children(self):
+        nodelist = []
+        if self.values is not None:
+            nodelist.append(("values", self.values))
+        return tuple(nodelist)
+
+    def __iter__(self):
+        if self.values is not None:
+            yield self.values
+
+    attr_names = ("name",)
+
+
+class Enumerator(Node):
+    __slots__ = ("name", "value", "coord", "__weakref__")
+
+    def __init__(self, name, value, coord=None):
+        self.name = name
+        self.value = value
+        self.coord = coord
+
+    def children(self):
+        nodelist = []
+        if self.value is not None:
+            nodelist.append(("value", self.value))
+        return tuple(nodelist)
+
+    def __iter__(self):
+        if self.value is not None:
+            yield self.value
+
+    attr_names = ("name",)
+
+
+class EnumeratorList(Node):
+    __slots__ = ("enumerators", "coord", "__weakref__")
+
+    def __init__(self, enumerators, coord=None):
+        self.enumerators = enumerators
+        self.coord = coord
+
+    def children(self):
+        nodelist = []
+        for i, child in enumerate(self.enumerators or []):
+            nodelist.append((f"enumerators[{i}]", child))
+        return tuple(nodelist)
+
+    def __iter__(self):
+        for child in self.enumerators or []:
+            yield child
+
+    attr_names = ()
+
+
+class ExprList(Node):
+    __slots__ = ("exprs", "coord", "__weakref__")
+
+    def __init__(self, exprs, coord=None):
+        self.exprs = exprs
+        self.coord = coord
+
+    def children(self):
+        nodelist = []
+        for i, child in enumerate(self.exprs or []):
+            nodelist.append((f"exprs[{i}]", child))
+        return tuple(nodelist)
+
+    def __iter__(self):
+        for child in self.exprs or []:
+            yield child
+
+    attr_names = ()
+
+
+class FileAST(Node):
+    __slots__ = ("ext", "coord", "__weakref__")
+
+    def __init__(self, ext, coord=None):
+        self.ext = ext
+        self.coord = coord
+
+    def children(self):
+        nodelist = []
+        for i, child in enumerate(self.ext or []):
+            nodelist.append((f"ext[{i}]", child))
+        return tuple(nodelist)
+
+    def __iter__(self):
+        for child in self.ext or []:
+            yield child
+
+    attr_names = ()
+
+
+class For(Node):
+    __slots__ = ("init", "cond", "next", "stmt", "coord", "__weakref__")
+
+    def __init__(self, init, cond, next, stmt, coord=None):
+        self.init = init
+        self.cond = cond
+        self.next = next
+        self.stmt = stmt
+        self.coord = coord
+
+    def children(self):
+        nodelist = []
+        if self.init is not None:
+            nodelist.append(("init", self.init))
+        if self.cond is not None:
+            nodelist.append(("cond", self.cond))
+        if self.next is not None:
+            nodelist.append(("next", self.next))
+        if self.stmt is not None:
+            nodelist.append(("stmt", self.stmt))
+        return tuple(nodelist)
+
+    def __iter__(self):
+        if self.init is not None:
+            yield self.init
+        if self.cond is not None:
+            yield self.cond
+        if self.next is not None:
+            yield self.next
+        if self.stmt is not None:
+            yield self.stmt
+
+    attr_names = ()
+
+
+class FuncCall(Node):
+    __slots__ = ("name", "args", "coord", "__weakref__")
+
+    def __init__(self, name, args, coord=None):
+        self.name = name
+        self.args = args
+        self.coord = coord
+
+    def children(self):
+        nodelist = []
+        if self.name is not None:
+            nodelist.append(("name", self.name))
+        if self.args is not None:
+            nodelist.append(("args", self.args))
+        return tuple(nodelist)
+
+    def __iter__(self):
+        if self.name is not None:
+            yield self.name
+        if self.args is not None:
+            yield self.args
+
+    attr_names = ()
+
+
+class FuncDecl(Node):
+    __slots__ = ("args", "type", "coord", "__weakref__")
+
+    def __init__(self, args, type, coord=None):
+        self.args = args
+        self.type = type
+        self.coord = coord
+
+    def children(self):
+        nodelist = []
+        if self.args is not None:
+            nodelist.append(("args", self.args))
+        if self.type is not None:
+            nodelist.append(("type", self.type))
+        return tuple(nodelist)
+
+    def __iter__(self):
+        if self.args is not None:
+            yield self.args
+        if self.type is not None:
+            yield self.type
+
+    attr_names = ()
+
+
+class FuncDef(Node):
+    __slots__ = ("decl", "param_decls", "body", "coord", "__weakref__")
+
+    def __init__(self, decl, param_decls, body, coord=None):
+        self.decl = decl
+        self.param_decls = param_decls
+        self.body = body
+        self.coord = coord
+
+    def children(self):
+        nodelist = []
+        if self.decl is not None:
+            nodelist.append(("decl", self.decl))
+        if self.body is not None:
+            nodelist.append(("body", self.body))
+        for i, child in enumerate(self.param_decls or []):
+            nodelist.append((f"param_decls[{i}]", child))
+        return tuple(nodelist)
+
+    def __iter__(self):
+        if self.decl is not None:
+            yield self.decl
+        if self.body is not None:
+            yield self.body
+        for child in self.param_decls or []:
+            yield child
+
+    attr_names = ()
+
+
+class Goto(Node):
+    __slots__ = ("name", "coord", "__weakref__")
+
+    def __init__(self, name, coord=None):
+        self.name = name
+        self.coord = coord
+
+    def children(self):
+        nodelist = []
+        return tuple(nodelist)
+
+    def __iter__(self):
+        return
+        yield
+
+    attr_names = ("name",)
+
+
+class ID(Node):
+    __slots__ = ("name", "coord", "__weakref__")
+
+    def __init__(self, name, coord=None):
+        self.name = name
+        self.coord = coord
+
+    def children(self):
+        nodelist = []
+        return tuple(nodelist)
+
+    def __iter__(self):
+        return
+        yield
+
+    attr_names = ("name",)
+
+
+class IdentifierType(Node):
+    __slots__ = ("names", "coord", "__weakref__")
+
+    def __init__(self, names, coord=None):
+        self.names = names
+        self.coord = coord
+
+    def children(self):
+        nodelist = []
+        return tuple(nodelist)
+
+    def __iter__(self):
+        return
+        yield
+
+    attr_names = ("names",)
+
+
+class If(Node):
+    __slots__ = ("cond", "iftrue", "iffalse", "coord", "__weakref__")
+
+    def __init__(self, cond, iftrue, iffalse, coord=None):
+        self.cond = cond
+        self.iftrue = iftrue
+        self.iffalse = iffalse
+        self.coord = coord
+
+    def children(self):
+        nodelist = []
+        if self.cond is not None:
+            nodelist.append(("cond", self.cond))
+        if self.iftrue is not None:
+            nodelist.append(("iftrue", self.iftrue))
+        if self.iffalse is not None:
+            nodelist.append(("iffalse", self.iffalse))
+        return tuple(nodelist)
+
+    def __iter__(self):
+        if self.cond is not None:
+            yield self.cond
+        if self.iftrue is not None:
+            yield self.iftrue
+        if self.iffalse is not None:
+            yield self.iffalse
+
+    attr_names = ()
+
+
+class InitList(Node):
+    __slots__ = ("exprs", "coord", "__weakref__")
+
+    def __init__(self, exprs, coord=None):
+        self.exprs = exprs
+        self.coord = coord
+
+    def children(self):
+        nodelist = []
+        for i, child in enumerate(self.exprs or []):
+            nodelist.append((f"exprs[{i}]", child))
+        return tuple(nodelist)
+
+    def __iter__(self):
+        for child in self.exprs or []:
+            yield child
+
+    attr_names = ()
+
+
+class Label(Node):
+    __slots__ = ("name", "stmt", "coord", "__weakref__")
+
+    def __init__(self, name, stmt, coord=None):
+        self.name = name
+        self.stmt = stmt
+        self.coord = coord
+
+    def children(self):
+        nodelist = []
+        if self.stmt is not None:
+            nodelist.append(("stmt", self.stmt))
+        return tuple(nodelist)
+
+    def __iter__(self):
+        if self.stmt is not None:
+            yield self.stmt
+
+    attr_names = ("name",)
+
+
+class NamedInitializer(Node):
+    __slots__ = ("name", "expr", "coord", "__weakref__")
+
+    def __init__(self, name, expr, coord=None):
+        self.name = name
+        self.expr = expr
+        self.coord = coord
+
+    def children(self):
+        nodelist = []
+        if self.expr is not None:
+            nodelist.append(("expr", self.expr))
+        for i, child in enumerate(self.name or []):
+            nodelist.append((f"name[{i}]", child))
+        return tuple(nodelist)
+
+    def __iter__(self):
+        if self.expr is not None:
+            yield self.expr
+        for child in self.name or []:
+            yield child
+
+    attr_names = ()
+
+
+class ParamList(Node):
+    __slots__ = ("params", "coord", "__weakref__")
+
+    def __init__(self, params, coord=None):
+        self.params = params
+        self.coord = coord
+
+    def children(self):
+        nodelist = []
+        for i, child in enumerate(self.params or []):
+            nodelist.append((f"params[{i}]", child))
+        return tuple(nodelist)
+
+    def __iter__(self):
+        for child in self.params or []:
+            yield child
+
+    attr_names = ()
+
+
+class PtrDecl(Node):
+    __slots__ = ("quals", "type", "coord", "__weakref__")
+
+    def __init__(self, quals, type, coord=None):
+        self.quals = quals
+        self.type = type
+        self.coord = coord
+
+    def children(self):
+        nodelist = []
+        if self.type is not None:
+            nodelist.append(("type", self.type))
+        return tuple(nodelist)
+
+    def __iter__(self):
+        if self.type is not None:
+            yield self.type
+
+    attr_names = ("quals",)
+
+
+class Return(Node):
+    __slots__ = ("expr", "coord", "__weakref__")
+
+    def __init__(self, expr, coord=None):
+        self.expr = expr
+        self.coord = coord
+
+    def children(self):
+        nodelist = []
+        if self.expr is not None:
+            nodelist.append(("expr", self.expr))
+        return tuple(nodelist)
+
+    def __iter__(self):
+        if self.expr is not None:
+            yield self.expr
+
+    attr_names = ()
+
+
+class StaticAssert(Node):
+    __slots__ = ("cond", "message", "coord", "__weakref__")
+
+    def __init__(self, cond, message, coord=None):
+        self.cond = cond
+        self.message = message
+        self.coord = coord
+
+    def children(self):
+        nodelist = []
+        if self.cond is not None:
+            nodelist.append(("cond", self.cond))
+        if self.message is not None:
+            nodelist.append(("message", self.message))
+        return tuple(nodelist)
+
+    def __iter__(self):
+        if self.cond is not None:
+            yield self.cond
+        if self.message is not None:
+            yield self.message
+
+    attr_names = ()
+
+
+class Struct(Node):
+    __slots__ = ("name", "decls", "coord", "__weakref__")
+
+    def __init__(self, name, decls, coord=None):
+        self.name = name
+        self.decls = decls
+        self.coord = coord
+
+    def children(self):
+        nodelist = []
+        for i, child in enumerate(self.decls or []):
+            nodelist.append((f"decls[{i}]", child))
+        return tuple(nodelist)
+
+    def __iter__(self):
+        for child in self.decls or []:
+            yield child
+
+    attr_names = ("name",)
+
+
+class StructRef(Node):
+    __slots__ = ("name", "type", "field", "coord", "__weakref__")
+
+    def __init__(self, name, type, field, coord=None):
+        self.name = name
+        self.type = type
+        self.field = field
+        self.coord = coord
+
+    def children(self):
+        nodelist = []
+        if self.name is not None:
+            nodelist.append(("name", self.name))
+        if self.field is not None:
+            nodelist.append(("field", self.field))
+        return tuple(nodelist)
+
+    def __iter__(self):
+        if self.name is not None:
+            yield self.name
+        if self.field is not None:
+            yield self.field
+
+    attr_names = ("type",)
+
+
+class Switch(Node):
+    __slots__ = ("cond", "stmt", "coord", "__weakref__")
+
+    def __init__(self, cond, stmt, coord=None):
+        self.cond = cond
+        self.stmt = stmt
+        self.coord = coord
+
+    def children(self):
+        nodelist = []
+        if self.cond is not None:
+            nodelist.append(("cond", self.cond))
+        if self.stmt is not None:
+            nodelist.append(("stmt", self.stmt))
+        return tuple(nodelist)
+
+    def __iter__(self):
+        if self.cond is not None:
+            yield self.cond
+        if self.stmt is not None:
+            yield self.stmt
+
+    attr_names = ()
+
+
+class TernaryOp(Node):
+    __slots__ = ("cond", "iftrue", "iffalse", "coord", "__weakref__")
+
+    def __init__(self, cond, iftrue, iffalse, coord=None):
+        self.cond = cond
+        self.iftrue = iftrue
+        self.iffalse = iffalse
+        self.coord = coord
+
+    def children(self):
+        nodelist = []
+        if self.cond is not None:
+            nodelist.append(("cond", self.cond))
+        if self.iftrue is not None:
+            nodelist.append(("iftrue", self.iftrue))
+        if self.iffalse is not None:
+            nodelist.append(("iffalse", self.iffalse))
+        return tuple(nodelist)
+
+    def __iter__(self):
+        if self.cond is not None:
+            yield self.cond
+        if self.iftrue is not None:
+            yield self.iftrue
+        if self.iffalse is not None:
+            yield self.iffalse
+
+    attr_names = ()
+
+
+class TypeDecl(Node):
+    __slots__ = ("declname", "quals", "align", "type", "coord", "__weakref__")
+
+    def __init__(self, declname, quals, align, type, coord=None):
+        self.declname = declname
+        self.quals = quals
+        self.align = align
+        self.type = type
+        self.coord = coord
+
+    def children(self):
+        nodelist = []
+        if self.type is not None:
+            nodelist.append(("type", self.type))
+        return tuple(nodelist)
+
+    def __iter__(self):
+        if self.type is not None:
+            yield self.type
+
+    attr_names = (
+        "declname",
+        "quals",
+        "align",
+    )
+
+
+class Typedef(Node):
+    __slots__ = ("name", "quals", "storage", "type", "coord", "__weakref__")
+
+    def __init__(self, name, quals, storage, type, coord=None):
+        self.name = name
+        self.quals = quals
+        self.storage = storage
+        self.type = type
+        self.coord = coord
+
+    def children(self):
+        nodelist = []
+        if self.type is not None:
+            nodelist.append(("type", self.type))
+        return tuple(nodelist)
+
+    def __iter__(self):
+        if self.type is not None:
+            yield self.type
+
+    attr_names = (
+        "name",
+        "quals",
+        "storage",
+    )
+
+
+class Typename(Node):
+    __slots__ = ("name", "quals", "align", "type", "coord", "__weakref__")
+
+    def __init__(self, name, quals, align, type, coord=None):
+        self.name = name
+        self.quals = quals
+        self.align = align
+        self.type = type
+        self.coord = coord
+
+    def children(self):
+        nodelist = []
+        if self.type is not None:
+            nodelist.append(("type", self.type))
+        return tuple(nodelist)
+
+    def __iter__(self):
+        if self.type is not None:
+            yield self.type
+
+    attr_names = (
+        "name",
+        "quals",
+        "align",
+    )
+
+
+class UnaryOp(Node):
+    __slots__ = ("op", "expr", "coord", "__weakref__")
+
+    def __init__(self, op, expr, coord=None):
+        self.op = op
+        self.expr = expr
+        self.coord = coord
+
+    def children(self):
+        nodelist = []
+        if self.expr is not None:
+            nodelist.append(("expr", self.expr))
+        return tuple(nodelist)
+
+    def __iter__(self):
+        if self.expr is not None:
+            yield self.expr
+
+    attr_names = ("op",)
+
+
+class Union(Node):
+    __slots__ = ("name", "decls", "coord", "__weakref__")
+
+    def __init__(self, name, decls, coord=None):
+        self.name = name
+        self.decls = decls
+        self.coord = coord
+
+    def children(self):
+        nodelist = []
+        for i, child in enumerate(self.decls or []):
+            nodelist.append((f"decls[{i}]", child))
+        return tuple(nodelist)
+
+    def __iter__(self):
+        for child in self.decls or []:
+            yield child
+
+    attr_names = ("name",)
+
+
+class While(Node):
+    __slots__ = ("cond", "stmt", "coord", "__weakref__")
+
+    def __init__(self, cond, stmt, coord=None):
+        self.cond = cond
+        self.stmt = stmt
+        self.coord = coord
+
+    def children(self):
+        nodelist = []
+        if self.cond is not None:
+            nodelist.append(("cond", self.cond))
+        if self.stmt is not None:
+            nodelist.append(("stmt", self.stmt))
+        return tuple(nodelist)
+
+    def __iter__(self):
+        if self.cond is not None:
+            yield self.cond
+        if self.stmt is not None:
+            yield self.stmt
+
+    attr_names = ()
+
+
+class Pragma(Node):
+    __slots__ = ("string", "coord", "__weakref__")
+
+    def __init__(self, string, coord=None):
+        self.string = string
+        self.coord = coord
+
+    def children(self):
+        nodelist = []
+        return tuple(nodelist)
+
+    def __iter__(self):
+        return
+        yield
+
+    attr_names = ("string",)
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pycparser/c_generator.py b/TTS/Kokoro/.venv/Lib/site-packages/pycparser/c_generator.py
new file mode 100644
index 0000000000000000000000000000000000000000..424e00e06bec67f6285e51947a3896a81592ae49
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pycparser/c_generator.py
@@ -0,0 +1,573 @@
+# ------------------------------------------------------------------------------
+# pycparser: c_generator.py
+#
+# C code generator from pycparser AST nodes.
+#
+# Eli Bendersky [https://eli.thegreenplace.net/]
+# License: BSD
+# ------------------------------------------------------------------------------
+from typing import Callable, List, Optional
+
+from . import c_ast
+
+
+class CGenerator:
+    """Uses the same visitor pattern as c_ast.NodeVisitor, but modified to
+    return a value from each visit method, using string accumulation in
+    generic_visit.
+    """
+
+    indent_level: int
+    reduce_parentheses: bool
+
+    def __init__(self, reduce_parentheses: bool = False) -> None:
+        """Constructs C-code generator
+
+        reduce_parentheses:
+            if True, eliminates needless parentheses on binary operators
+        """
+        # Statements start with indentation of self.indent_level spaces, using
+        # the _make_indent method.
+        self.indent_level = 0
+        self.reduce_parentheses = reduce_parentheses
+
+    def _make_indent(self) -> str:
+        return " " * self.indent_level
+
+    def visit(self, node: c_ast.Node) -> str:
+        method = "visit_" + node.__class__.__name__
+        return getattr(self, method, self.generic_visit)(node)
+
+    def generic_visit(self, node: Optional[c_ast.Node]) -> str:
+        if node is None:
+            return ""
+        else:
+            return "".join(self.visit(c) for c_name, c in node.children())
+
+    def visit_Constant(self, n: c_ast.Constant) -> str:
+        return n.value
+
+    def visit_ID(self, n: c_ast.ID) -> str:
+        return n.name
+
+    def visit_Pragma(self, n: c_ast.Pragma) -> str:
+        ret = "#pragma"
+        if n.string:
+            ret += " " + n.string
+        return ret
+
+    def visit_ArrayRef(self, n: c_ast.ArrayRef) -> str:
+        arrref = self._parenthesize_unless_simple(n.name)
+        return arrref + "[" + self.visit(n.subscript) + "]"
+
+    def visit_StructRef(self, n: c_ast.StructRef) -> str:
+        sref = self._parenthesize_unless_simple(n.name)
+        return sref + n.type + self.visit(n.field)
+
+    def visit_FuncCall(self, n: c_ast.FuncCall) -> str:
+        fref = self._parenthesize_unless_simple(n.name)
+        args = self.visit(n.args) if n.args is not None else ""
+        return fref + "(" + args + ")"
+
+    def visit_UnaryOp(self, n: c_ast.UnaryOp) -> str:
+        match n.op:
+            case "sizeof":
+                # Always parenthesize the argument of sizeof since it can be
+                # a name.
+                return f"sizeof({self.visit(n.expr)})"
+            case "p++":
+                operand = self._parenthesize_unless_simple(n.expr)
+                return f"{operand}++"
+            case "p--":
+                operand = self._parenthesize_unless_simple(n.expr)
+                return f"{operand}--"
+            case _:
+                operand = self._parenthesize_unless_simple(n.expr)
+                return f"{n.op}{operand}"
+
+    # Precedence map of binary operators:
+    precedence_map = {
+        # Should be in sync with c_parser.CParser.precedence
+        # Higher numbers are stronger binding
+        "||": 0,  # weakest binding
+        "&&": 1,
+        "|": 2,
+        "^": 3,
+        "&": 4,
+        "==": 5,
+        "!=": 5,
+        ">": 6,
+        ">=": 6,
+        "<": 6,
+        "<=": 6,
+        ">>": 7,
+        "<<": 7,
+        "+": 8,
+        "-": 8,
+        "*": 9,
+        "/": 9,
+        "%": 9,  # strongest binding
+    }
+
+    def visit_BinaryOp(self, n: c_ast.BinaryOp) -> str:
+        # Note: all binary operators are left-to-right associative
+        #
+        # If `n.left.op` has a stronger or equally binding precedence in
+        # comparison to `n.op`, no parenthesis are needed for the left:
+        # e.g., `(a*b) + c` is equivalent to `a*b + c`, as well as
+        #       `(a+b) - c` is equivalent to `a+b - c` (same precedence).
+        # If the left operator is weaker binding than the current, then
+        # parentheses are necessary:
+        # e.g., `(a+b) * c` is NOT equivalent to `a+b * c`.
+        lval_str = self._parenthesize_if(
+            n.left,
+            lambda d: not (
+                self._is_simple_node(d)
+                or self.reduce_parentheses
+                and isinstance(d, c_ast.BinaryOp)
+                and self.precedence_map[d.op] >= self.precedence_map[n.op]
+            ),
+        )
+        # If `n.right.op` has a stronger -but not equal- binding precedence,
+        # parenthesis can be omitted on the right:
+        # e.g., `a + (b*c)` is equivalent to `a + b*c`.
+        # If the right operator is weaker or equally binding, then parentheses
+        # are necessary:
+        # e.g., `a * (b+c)` is NOT equivalent to `a * b+c` and
+        #       `a - (b+c)` is NOT equivalent to `a - b+c` (same precedence).
+        rval_str = self._parenthesize_if(
+            n.right,
+            lambda d: not (
+                self._is_simple_node(d)
+                or self.reduce_parentheses
+                and isinstance(d, c_ast.BinaryOp)
+                and self.precedence_map[d.op] > self.precedence_map[n.op]
+            ),
+        )
+        return f"{lval_str} {n.op} {rval_str}"
+
+    def visit_Assignment(self, n: c_ast.Assignment) -> str:
+        rval_str = self._parenthesize_if(
+            n.rvalue, lambda n: isinstance(n, c_ast.Assignment)
+        )
+        return f"{self.visit(n.lvalue)} {n.op} {rval_str}"
+
+    def visit_IdentifierType(self, n: c_ast.IdentifierType) -> str:
+        return " ".join(n.names)
+
+    def _visit_expr(self, n: c_ast.Node) -> str:
+        match n:
+            case c_ast.InitList():
+                return "{" + self.visit(n) + "}"
+            case c_ast.ExprList() | c_ast.Compound():
+                return "(" + self.visit(n) + ")"
+            case _:
+                return self.visit(n)
+
+    def visit_Decl(self, n: c_ast.Decl, no_type: bool = False) -> str:
+        # no_type is used when a Decl is part of a DeclList, where the type is
+        # explicitly only for the first declaration in a list.
+        #
+        s = n.name if no_type else self._generate_decl(n)
+        if n.bitsize:
+            s += " : " + self.visit(n.bitsize)
+        if n.init:
+            s += " = " + self._visit_expr(n.init)
+        return s
+
+    def visit_DeclList(self, n: c_ast.DeclList) -> str:
+        s = self.visit(n.decls[0])
+        if len(n.decls) > 1:
+            s += ", " + ", ".join(
+                self.visit_Decl(decl, no_type=True) for decl in n.decls[1:]
+            )
+        return s
+
+    def visit_Typedef(self, n: c_ast.Typedef) -> str:
+        s = ""
+        if n.storage:
+            s += " ".join(n.storage) + " "
+        s += self._generate_type(n.type)
+        return s
+
+    def visit_Cast(self, n: c_ast.Cast) -> str:
+        s = "(" + self._generate_type(n.to_type, emit_declname=False) + ")"
+        return s + " " + self._parenthesize_unless_simple(n.expr)
+
+    def visit_ExprList(self, n: c_ast.ExprList) -> str:
+        visited_subexprs = []
+        for expr in n.exprs:
+            visited_subexprs.append(self._visit_expr(expr))
+        return ", ".join(visited_subexprs)
+
+    def visit_InitList(self, n: c_ast.InitList) -> str:
+        visited_subexprs = []
+        for expr in n.exprs:
+            visited_subexprs.append(self._visit_expr(expr))
+        return ", ".join(visited_subexprs)
+
+    def visit_Enum(self, n: c_ast.Enum) -> str:
+        return self._generate_struct_union_enum(n, name="enum")
+
+    def visit_Alignas(self, n: c_ast.Alignas) -> str:
+        return "_Alignas({})".format(self.visit(n.alignment))
+
+    def visit_Enumerator(self, n: c_ast.Enumerator) -> str:
+        if not n.value:
+            return "{indent}{name},\n".format(
+                indent=self._make_indent(),
+                name=n.name,
+            )
+        else:
+            return "{indent}{name} = {value},\n".format(
+                indent=self._make_indent(),
+                name=n.name,
+                value=self.visit(n.value),
+            )
+
+    def visit_FuncDef(self, n: c_ast.FuncDef) -> str:
+        decl = self.visit(n.decl)
+        self.indent_level = 0
+        body = self.visit(n.body)
+        if n.param_decls:
+            knrdecls = ";\n".join(self.visit(p) for p in n.param_decls)
+            return decl + "\n" + knrdecls + ";\n" + body + "\n"
+        else:
+            return decl + "\n" + body + "\n"
+
+    def visit_FileAST(self, n: c_ast.FileAST) -> str:
+        s = ""
+        for ext in n.ext:
+            match ext:
+                case c_ast.FuncDef():
+                    s += self.visit(ext)
+                case c_ast.Pragma():
+                    s += self.visit(ext) + "\n"
+                case _:
+                    s += self.visit(ext) + ";\n"
+        return s
+
+    def visit_Compound(self, n: c_ast.Compound) -> str:
+        s = self._make_indent() + "{\n"
+        self.indent_level += 2
+        if n.block_items:
+            s += "".join(self._generate_stmt(stmt) for stmt in n.block_items)
+        self.indent_level -= 2
+        s += self._make_indent() + "}\n"
+        return s
+
+    def visit_CompoundLiteral(self, n: c_ast.CompoundLiteral) -> str:
+        return "(" + self.visit(n.type) + "){" + self.visit(n.init) + "}"
+
+    def visit_EmptyStatement(self, n: c_ast.EmptyStatement) -> str:
+        return ";"
+
+    def visit_ParamList(self, n: c_ast.ParamList) -> str:
+        return ", ".join(self.visit(param) for param in n.params)
+
+    def visit_Return(self, n: c_ast.Return) -> str:
+        s = "return"
+        if n.expr:
+            s += " " + self.visit(n.expr)
+        return s + ";"
+
+    def visit_Break(self, n: c_ast.Break) -> str:
+        return "break;"
+
+    def visit_Continue(self, n: c_ast.Continue) -> str:
+        return "continue;"
+
+    def visit_TernaryOp(self, n: c_ast.TernaryOp) -> str:
+        s = "(" + self._visit_expr(n.cond) + ") ? "
+        s += "(" + self._visit_expr(n.iftrue) + ") : "
+        s += "(" + self._visit_expr(n.iffalse) + ")"
+        return s
+
+    def visit_If(self, n: c_ast.If) -> str:
+        s = "if ("
+        if n.cond:
+            s += self.visit(n.cond)
+        s += ")\n"
+        s += self._generate_stmt(n.iftrue, add_indent=True)
+        if n.iffalse:
+            s += self._make_indent() + "else\n"
+            s += self._generate_stmt(n.iffalse, add_indent=True)
+        return s
+
+    def visit_For(self, n: c_ast.For) -> str:
+        s = "for ("
+        if n.init:
+            s += self.visit(n.init)
+        s += ";"
+        if n.cond:
+            s += " " + self.visit(n.cond)
+        s += ";"
+        if n.next:
+            s += " " + self.visit(n.next)
+        s += ")\n"
+        s += self._generate_stmt(n.stmt, add_indent=True)
+        return s
+
+    def visit_While(self, n: c_ast.While) -> str:
+        s = "while ("
+        if n.cond:
+            s += self.visit(n.cond)
+        s += ")\n"
+        s += self._generate_stmt(n.stmt, add_indent=True)
+        return s
+
+    def visit_DoWhile(self, n: c_ast.DoWhile) -> str:
+        s = "do\n"
+        s += self._generate_stmt(n.stmt, add_indent=True)
+        s += self._make_indent() + "while ("
+        if n.cond:
+            s += self.visit(n.cond)
+        s += ");"
+        return s
+
+    def visit_StaticAssert(self, n: c_ast.StaticAssert) -> str:
+        s = "_Static_assert("
+        s += self.visit(n.cond)
+        if n.message:
+            s += ","
+            s += self.visit(n.message)
+        s += ")"
+        return s
+
+    def visit_Switch(self, n: c_ast.Switch) -> str:
+        s = "switch (" + self.visit(n.cond) + ")\n"
+        s += self._generate_stmt(n.stmt, add_indent=True)
+        return s
+
+    def visit_Case(self, n: c_ast.Case) -> str:
+        s = "case " + self.visit(n.expr) + ":\n"
+        for stmt in n.stmts:
+            s += self._generate_stmt(stmt, add_indent=True)
+        return s
+
+    def visit_Default(self, n: c_ast.Default) -> str:
+        s = "default:\n"
+        for stmt in n.stmts:
+            s += self._generate_stmt(stmt, add_indent=True)
+        return s
+
+    def visit_Label(self, n: c_ast.Label) -> str:
+        return n.name + ":\n" + self._generate_stmt(n.stmt)
+
+    def visit_Goto(self, n: c_ast.Goto) -> str:
+        return "goto " + n.name + ";"
+
+    def visit_EllipsisParam(self, n: c_ast.EllipsisParam) -> str:
+        return "..."
+
+    def visit_Struct(self, n: c_ast.Struct) -> str:
+        return self._generate_struct_union_enum(n, "struct")
+
+    def visit_Typename(self, n: c_ast.Typename) -> str:
+        return self._generate_type(n.type)
+
+    def visit_Union(self, n: c_ast.Union) -> str:
+        return self._generate_struct_union_enum(n, "union")
+
+    def visit_NamedInitializer(self, n: c_ast.NamedInitializer) -> str:
+        s = ""
+        for name in n.name:
+            if isinstance(name, c_ast.ID):
+                s += "." + name.name
+            else:
+                s += "[" + self.visit(name) + "]"
+        s += " = " + self._visit_expr(n.expr)
+        return s
+
+    def visit_FuncDecl(self, n: c_ast.FuncDecl) -> str:
+        return self._generate_type(n)
+
+    def visit_ArrayDecl(self, n: c_ast.ArrayDecl) -> str:
+        return self._generate_type(n, emit_declname=False)
+
+    def visit_TypeDecl(self, n: c_ast.TypeDecl) -> str:
+        return self._generate_type(n, emit_declname=False)
+
+    def visit_PtrDecl(self, n: c_ast.PtrDecl) -> str:
+        return self._generate_type(n, emit_declname=False)
+
+    def _generate_struct_union_enum(
+        self, n: c_ast.Struct | c_ast.Union | c_ast.Enum, name: str
+    ) -> str:
+        """Generates code for structs, unions, and enums. name should be
+        'struct', 'union', or 'enum'.
+        """
+        if name in ("struct", "union"):
+            assert isinstance(n, (c_ast.Struct, c_ast.Union))
+            members = n.decls
+            body_function = self._generate_struct_union_body
+        else:
+            assert name == "enum"
+            assert isinstance(n, c_ast.Enum)
+            members = None if n.values is None else n.values.enumerators
+            body_function = self._generate_enum_body
+        s = name + " " + (n.name or "")
+        if members is not None:
+            # None means no members
+            # Empty sequence means an empty list of members
+            s += "\n"
+            s += self._make_indent()
+            self.indent_level += 2
+            s += "{\n"
+            s += body_function(members)
+            self.indent_level -= 2
+            s += self._make_indent() + "}"
+        return s
+
+    def _generate_struct_union_body(self, members: List[c_ast.Node]) -> str:
+        return "".join(self._generate_stmt(decl) for decl in members)
+
+    def _generate_enum_body(self, members: List[c_ast.Enumerator]) -> str:
+        # `[:-2] + '\n'` removes the final `,` from the enumerator list
+        return "".join(self.visit(value) for value in members)[:-2] + "\n"
+
+    def _generate_stmt(self, n: c_ast.Node, add_indent: bool = False) -> str:
+        """Generation from a statement node. This method exists as a wrapper
+        for individual visit_* methods to handle different treatment of
+        some statements in this context.
+        """
+        if add_indent:
+            self.indent_level += 2
+        indent = self._make_indent()
+        if add_indent:
+            self.indent_level -= 2
+
+        match n:
+            case (
+                c_ast.Decl()
+                | c_ast.Assignment()
+                | c_ast.Cast()
+                | c_ast.UnaryOp()
+                | c_ast.BinaryOp()
+                | c_ast.TernaryOp()
+                | c_ast.FuncCall()
+                | c_ast.ArrayRef()
+                | c_ast.StructRef()
+                | c_ast.Constant()
+                | c_ast.ID()
+                | c_ast.Typedef()
+                | c_ast.ExprList()
+            ):
+                # These can also appear in an expression context so no semicolon
+                # is added to them automatically
+                #
+                return indent + self.visit(n) + ";\n"
+            case c_ast.Compound():
+                # No extra indentation required before the opening brace of a
+                # compound - because it consists of multiple lines it has to
+                # compute its own indentation.
+                #
+                return self.visit(n)
+            case c_ast.If():
+                return indent + self.visit(n)
+            case _:
+                return indent + self.visit(n) + "\n"
+
+    def _generate_decl(self, n: c_ast.Decl) -> str:
+        """Generation from a Decl node."""
+        s = ""
+        if n.funcspec:
+            s = " ".join(n.funcspec) + " "
+        if n.storage:
+            s += " ".join(n.storage) + " "
+        if n.align:
+            s += self.visit(n.align[0]) + " "
+        s += self._generate_type(n.type)
+        return s
+
+    def _generate_type(
+        self,
+        n: c_ast.Node,
+        modifiers: List[c_ast.Node] = [],
+        emit_declname: bool = True,
+    ) -> str:
+        """Recursive generation from a type node. n is the type node.
+        modifiers collects the PtrDecl, ArrayDecl and FuncDecl modifiers
+        encountered on the way down to a TypeDecl, to allow proper
+        generation from it.
+        """
+        # ~ print(n, modifiers)
+        match n:
+            case c_ast.TypeDecl():
+                s = ""
+                if n.quals:
+                    s += " ".join(n.quals) + " "
+                s += self.visit(n.type)
+
+                nstr = n.declname if n.declname and emit_declname else ""
+                # Resolve modifiers.
+                # Wrap in parens to distinguish pointer to array and pointer to
+                # function syntax.
+                #
+                for i, modifier in enumerate(modifiers):
+                    match modifier:
+                        case c_ast.ArrayDecl():
+                            if i != 0 and isinstance(modifiers[i - 1], c_ast.PtrDecl):
+                                nstr = "(" + nstr + ")"
+                            nstr += "["
+                            if modifier.dim_quals:
+                                nstr += " ".join(modifier.dim_quals) + " "
+                            if modifier.dim is not None:
+                                nstr += self.visit(modifier.dim)
+                            nstr += "]"
+                        case c_ast.FuncDecl():
+                            if i != 0 and isinstance(modifiers[i - 1], c_ast.PtrDecl):
+                                nstr = "(" + nstr + ")"
+                            args = (
+                                self.visit(modifier.args)
+                                if modifier.args is not None
+                                else ""
+                            )
+                            nstr += "(" + args + ")"
+                        case c_ast.PtrDecl():
+                            if modifier.quals:
+                                quals = " ".join(modifier.quals)
+                                suffix = f" {nstr}" if nstr else ""
+                                nstr = f"* {quals}{suffix}"
+                            else:
+                                nstr = "*" + nstr
+                if nstr:
+                    s += " " + nstr
+                return s
+            case c_ast.Decl():
+                return self._generate_decl(n.type)
+            case c_ast.Typename():
+                return self._generate_type(n.type, emit_declname=emit_declname)
+            case c_ast.IdentifierType():
+                return " ".join(n.names) + " "
+            case c_ast.ArrayDecl() | c_ast.PtrDecl() | c_ast.FuncDecl():
+                return self._generate_type(
+                    n.type, modifiers + [n], emit_declname=emit_declname
+                )
+            case _:
+                return self.visit(n)
+
+    def _parenthesize_if(
+        self, n: c_ast.Node, condition: Callable[[c_ast.Node], bool]
+    ) -> str:
+        """Visits 'n' and returns its string representation, parenthesized
+        if the condition function applied to the node returns True.
+        """
+        s = self._visit_expr(n)
+        if condition(n):
+            return "(" + s + ")"
+        else:
+            return s
+
+    def _parenthesize_unless_simple(self, n: c_ast.Node) -> str:
+        """Common use case for _parenthesize_if"""
+        return self._parenthesize_if(n, lambda d: not self._is_simple_node(d))
+
+    def _is_simple_node(self, n: c_ast.Node) -> bool:
+        """Returns True for nodes that are "simple" - i.e. nodes that always
+        have higher precedence than operators.
+        """
+        return isinstance(
+            n,
+            (c_ast.Constant, c_ast.ID, c_ast.ArrayRef, c_ast.StructRef, c_ast.FuncCall),
+        )
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pycparser/c_lexer.py b/TTS/Kokoro/.venv/Lib/site-packages/pycparser/c_lexer.py
new file mode 100644
index 0000000000000000000000000000000000000000..ef59d695448751017f34fb033196a0217f48e5f0
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pycparser/c_lexer.py
@@ -0,0 +1,706 @@
+# ------------------------------------------------------------------------------
+# pycparser: c_lexer.py
+#
+# CLexer class: lexer for the C language
+#
+# Eli Bendersky [https://eli.thegreenplace.net/]
+# License: BSD
+# ------------------------------------------------------------------------------
+import re
+from dataclasses import dataclass
+from enum import Enum
+from typing import Callable, Dict, List, Optional, Tuple
+
+
+@dataclass(slots=True)
+class _Token:
+    type: str
+    value: str
+    lineno: int
+    column: int
+
+
+class CLexer:
+    """A standalone lexer for C.
+
+    Parameters for construction:
+        error_func:
+            Called with (msg, line, column) on lexing errors.
+        on_lbrace_func:
+            Called when an LBRACE token is produced (used for scope tracking).
+        on_rbrace_func:
+            Called when an RBRACE token is produced (used for scope tracking).
+        type_lookup_func:
+            Called with an identifier name; expected to return True if it is
+            a typedef name and should be tokenized as TYPEID.
+
+    Call input(text) to initialize lexing, and then keep calling token() to
+    get the next token, until it returns None (at end of input).
+    """
+
+    def __init__(
+        self,
+        error_func: Callable[[str, int, int], None],
+        on_lbrace_func: Callable[[], None],
+        on_rbrace_func: Callable[[], None],
+        type_lookup_func: Callable[[str], bool],
+    ) -> None:
+        self.error_func = error_func
+        self.on_lbrace_func = on_lbrace_func
+        self.on_rbrace_func = on_rbrace_func
+        self.type_lookup_func = type_lookup_func
+        self._init_state()
+
+    def input(self, text: str, filename: str = "") -> None:
+        """Initialize the lexer to the given input text.
+
+        filename is an optional name identifying the file from which the input
+        comes. The lexer can modify it if #line directives are encountered.
+        """
+        self._init_state()
+        self._lexdata = text
+        self._filename = filename
+
+    def _init_state(self) -> None:
+        self._lexdata = ""
+        self._filename = ""
+        self._pos = 0
+        self._line_start = 0
+        self._pending_tok: Optional[_Token] = None
+        self._lineno = 1
+
+    @property
+    def filename(self) -> str:
+        return self._filename
+
+    def token(self) -> Optional[_Token]:
+        # Lexing strategy overview:
+        #
+        # - We maintain a current position (self._pos), line number, and the
+        #   byte offset of the current line start. The lexer is a simple loop
+        #   that skips whitespace/newlines and emits one token per call.
+        # - A small amount of logic is handled manually before regex matching:
+        #
+        #   * Preprocessor-style directives: if we see '#', we check whether
+        #     it's a #line or #pragma directive and consume it inline. #line
+        #     updates lineno/filename and produces no tokens. #pragma can yield
+        #     both PPPRAGMA and PPPRAGMASTR, but token() returns a single token,
+        #     so we stash the PPPRAGMASTR as _pending_tok to return on the next
+        #     token() call. Otherwise we return PPHASH.
+        #   * Newlines update lineno/line-start tracking so tokens can record
+        #     accurate columns.
+        #
+        # - The bulk of tokens are recognized in _match_token:
+        #
+        #   * _regex_rules: regex patterns for identifiers, literals, and other
+        #     complex tokens (including error-producing patterns). The lexer
+        #     uses a combined _regex_master to scan options at the same time.
+        #   * _fixed_tokens: exact string matches for operators and punctuation,
+        #     resolved by longest match.
+        #
+        # - Error patterns call the error callback and advance minimally, which
+        #   keeps lexing resilient while reporting useful diagnostics.
+        text = self._lexdata
+        n = len(text)
+
+        if self._pending_tok is not None:
+            tok = self._pending_tok
+            self._pending_tok = None
+            return tok
+
+        while self._pos < n:
+            match text[self._pos]:
+                case " " | "\t":
+                    self._pos += 1
+                case "\n":
+                    self._lineno += 1
+                    self._pos += 1
+                    self._line_start = self._pos
+                case "#":
+                    if _line_pattern.match(text, self._pos + 1):
+                        self._pos += 1
+                        self._handle_ppline()
+                        continue
+                    if _pragma_pattern.match(text, self._pos + 1):
+                        self._pos += 1
+                        toks = self._handle_pppragma()
+                        if len(toks) > 1:
+                            self._pending_tok = toks[1]
+                        if len(toks) > 0:
+                            return toks[0]
+                        continue
+                    tok = self._make_token("PPHASH", "#", self._pos)
+                    self._pos += 1
+                    return tok
+                case _:
+                    if tok := self._match_token():
+                        return tok
+                    else:
+                        continue
+
+    def _match_token(self) -> Optional[_Token]:
+        """Match one token at the current position.
+
+        Returns a Token on success, or None if no token could be matched and
+        an error was reported. This method always advances _pos by the matched
+        length, or by 1 on error/no-match.
+        """
+        text = self._lexdata
+        pos = self._pos
+        # We pick the longest match between:
+        # - the master regex (identifiers, literals, error patterns, etc.)
+        # - fixed operator/punctuator literals from the bucket for text[pos]
+        #
+        # The longest match is required to ensure we properly lex something
+        # like ".123" (a floating-point constant) as a single entity (with
+        # FLOAT_CONST), rather than a PERIOD followed by a number.
+        #
+        # The fixed-literal buckets are already length-sorted, so within that
+        # bucket we can take the first match. However, we still compare its
+        # length to the regex match because the regex may have matched a longer
+        # token that should take precedence.
+        best = None
+
+        if m := _regex_master.match(text, pos):
+            tok_type = m.lastgroup
+            # All master-regex alternatives are named; lastgroup shouldn't be None.
+            assert tok_type is not None
+            value = m.group(tok_type)
+            length = len(value)
+            action, msg = _regex_actions[tok_type]
+            best = (length, tok_type, value, action, msg)
+
+        if bucket := _fixed_tokens_by_first.get(text[pos]):
+            for entry in bucket:
+                if text.startswith(entry.literal, pos):
+                    length = len(entry.literal)
+                    if best is None or length > best[0]:
+                        best = (
+                            length,
+                            entry.tok_type,
+                            entry.literal,
+                            _RegexAction.TOKEN,
+                            None,
+                        )
+                    break
+
+        if best is None:
+            msg = f"Illegal character {repr(text[pos])}"
+            self._error(msg, pos)
+            self._pos += 1
+            return None
+
+        length, tok_type, value, action, msg = best
+        if action == _RegexAction.ERROR:
+            if tok_type == "BAD_CHAR_CONST":
+                msg = f"Invalid char constant {value}"
+            # All other ERROR rules provide a message.
+            assert msg is not None
+            self._error(msg, pos)
+            self._pos += max(1, length)
+            return None
+
+        if action == _RegexAction.ID:
+            tok_type = _keyword_map.get(value, "ID")
+            if tok_type == "ID" and self.type_lookup_func(value):
+                tok_type = "TYPEID"
+
+        tok = self._make_token(tok_type, value, pos)
+        self._pos += length
+
+        if tok.type == "LBRACE":
+            self.on_lbrace_func()
+        elif tok.type == "RBRACE":
+            self.on_rbrace_func()
+
+        return tok
+
+    def _make_token(self, tok_type: str, value: str, pos: int) -> _Token:
+        """Create a Token at an absolute input position.
+
+        Expects tok_type/value and the absolute byte offset pos in the current
+        input. Does not advance lexer state; callers manage _pos themselves.
+        Returns a Token with lineno/column computed from current line tracking.
+        """
+        column = pos - self._line_start + 1
+        tok = _Token(tok_type, value, self._lineno, column)
+        return tok
+
+    def _error(self, msg: str, pos: int) -> None:
+        column = pos - self._line_start + 1
+        self.error_func(msg, self._lineno, column)
+
+    def _handle_ppline(self) -> None:
+        # Since #line directives aren't supposed to return tokens but should
+        # only affect the lexer's state (update line/filename for coords), this
+        # method does a bit of parsing on its own. It doesn't return anything,
+        # but its side effect is to update self._pos past the directive, and
+        # potentially update self._lineno and self._filename, based on the
+        # directive's contents.
+        #
+        # Accepted #line forms from preprocessors:
+        # - "#line 66 \"kwas\\df.h\""
+        # - "# 9"
+        # - "#line 10 \"include/me.h\" 1 2 3" (extra numeric flags)
+        # - "# 1 \"file.h\" 3"
+        # Errors we must report:
+        # - "#line \"file.h\"" (filename before line number)
+        # - "#line df" (garbage instead of number/string)
+        #
+        # We scan the directive line once (after an optional 'line' keyword),
+        # validating the order: NUMBER, optional STRING, then any NUMBERs.
+        # The NUMBERs tail is only accepted if a filename STRING was present.
+        text = self._lexdata
+        n = len(text)
+        line_end = text.find("\n", self._pos)
+        if line_end == -1:
+            line_end = n
+        line = text[self._pos : line_end]
+        pos = 0
+        line_len = len(line)
+
+        def skip_ws() -> None:
+            nonlocal pos
+            while pos < line_len and line[pos] in " \t":
+                pos += 1
+
+        skip_ws()
+        if line.startswith("line", pos):
+            pos += 4
+
+        def success(pp_line: Optional[str], pp_filename: Optional[str]) -> None:
+            if pp_line is None:
+                self._error("line number missing in #line", self._pos + line_len)
+            else:
+                self._lineno = int(pp_line)
+                if pp_filename is not None:
+                    self._filename = pp_filename
+            self._pos = line_end + 1
+            self._line_start = self._pos
+
+        def fail(msg: str, offset: int) -> None:
+            self._error(msg, self._pos + offset)
+            self._pos = line_end + 1
+            self._line_start = self._pos
+
+        skip_ws()
+        if pos >= line_len:
+            success(None, None)
+            return
+        if line[pos] == '"':
+            fail("filename before line number in #line", pos)
+            return
+
+        m = re.match(_decimal_constant, line[pos:])
+        if not m:
+            fail("invalid #line directive", pos)
+            return
+
+        pp_line = m.group(0)
+        pos += len(pp_line)
+        skip_ws()
+        if pos >= line_len:
+            success(pp_line, None)
+            return
+
+        if line[pos] != '"':
+            fail("invalid #line directive", pos)
+            return
+
+        m = re.match(_string_literal, line[pos:])
+        if not m:
+            fail("invalid #line directive", pos)
+            return
+
+        pp_filename = m.group(0).lstrip('"').rstrip('"')
+        pos += len(m.group(0))
+
+        # Consume arbitrary sequence of numeric flags after the directive
+        while True:
+            skip_ws()
+            if pos >= line_len:
+                break
+            m = re.match(_decimal_constant, line[pos:])
+            if not m:
+                fail("invalid #line directive", pos)
+                return
+            pos += len(m.group(0))
+
+        success(pp_line, pp_filename)
+
+    def _handle_pppragma(self) -> List[_Token]:
+        # Parse a full #pragma line; returns a list of tokens with 1 or 2
+        # tokens - PPPRAGMA and an optional PPPRAGMASTR. If an empty list is
+        # returned, it means an error occurred, or we're at the end of input.
+        #
+        # Examples:
+        # - "#pragma" -> PPPRAGMA only
+        # - "#pragma once" -> PPPRAGMA, PPPRAGMASTR("once")
+        # - "# pragma omp parallel private(th_id)" -> PPPRAGMA, PPPRAGMASTR("omp parallel private(th_id)")
+        # - "#\tpragma {pack: 2, smack: 3}" -> PPPRAGMA, PPPRAGMASTR("{pack: 2, smack: 3}")
+        text = self._lexdata
+        n = len(text)
+        pos = self._pos
+
+        while pos < n and text[pos] in " \t":
+            pos += 1
+        if pos >= n:
+            self._pos = pos
+            return []
+
+        if not text.startswith("pragma", pos):
+            self._error("invalid #pragma directive", pos)
+            self._pos = pos + 1
+            return []
+
+        pragma_pos = pos
+        pos += len("pragma")
+        toks = [self._make_token("PPPRAGMA", "pragma", pragma_pos)]
+
+        while pos < n and text[pos] in " \t":
+            pos += 1
+
+        start = pos
+        while pos < n and text[pos] != "\n":
+            pos += 1
+        if pos > start:
+            toks.append(self._make_token("PPPRAGMASTR", text[start:pos], start))
+        if pos < n and text[pos] == "\n":
+            self._lineno += 1
+            pos += 1
+            self._line_start = pos
+        self._pos = pos
+        return toks
+
+
+##
+## Reserved keywords
+##
+_keywords: Tuple[str, ...] = (
+    "AUTO",
+    "BREAK",
+    "CASE",
+    "CHAR",
+    "CONST",
+    "CONTINUE",
+    "DEFAULT",
+    "DO",
+    "DOUBLE",
+    "ELSE",
+    "ENUM",
+    "EXTERN",
+    "FLOAT",
+    "FOR",
+    "GOTO",
+    "IF",
+    "INLINE",
+    "INT",
+    "LONG",
+    "REGISTER",
+    "OFFSETOF",
+    "RESTRICT",
+    "RETURN",
+    "SHORT",
+    "SIGNED",
+    "SIZEOF",
+    "STATIC",
+    "STRUCT",
+    "SWITCH",
+    "TYPEDEF",
+    "UNION",
+    "UNSIGNED",
+    "VOID",
+    "VOLATILE",
+    "WHILE",
+    "__INT128",
+    "_BOOL",
+    "_COMPLEX",
+    "_NORETURN",
+    "_THREAD_LOCAL",
+    "_STATIC_ASSERT",
+    "_ATOMIC",
+    "_ALIGNOF",
+    "_ALIGNAS",
+    "_PRAGMA",
+)
+
+_keyword_map: Dict[str, str] = {}
+
+for keyword in _keywords:
+    # Keywords from new C standard are mixed-case, like _Bool, _Alignas, etc.
+    if keyword.startswith("_") and len(keyword) > 1 and keyword[1].isalpha():
+        _keyword_map[keyword[:2].upper() + keyword[2:].lower()] = keyword
+    else:
+        _keyword_map[keyword.lower()] = keyword
+
+##
+## Regexes for use in tokens
+##
+
+# valid C identifiers (K&R2: A.2.3), plus '$' (supported by some compilers)
+_identifier = r"[a-zA-Z_$][0-9a-zA-Z_$]*"
+
+_hex_prefix = "0[xX]"
+_hex_digits = "[0-9a-fA-F]+"
+_bin_prefix = "0[bB]"
+_bin_digits = "[01]+"
+
+# integer constants (K&R2: A.2.5.1)
+_integer_suffix_opt = (
+    r"(([uU]ll)|([uU]LL)|(ll[uU]?)|(LL[uU]?)|([uU][lL])|([lL][uU]?)|[uU])?"
+)
+_decimal_constant = (
+    "(0" + _integer_suffix_opt + ")|([1-9][0-9]*" + _integer_suffix_opt + ")"
+)
+_octal_constant = "0[0-7]*" + _integer_suffix_opt
+_hex_constant = _hex_prefix + _hex_digits + _integer_suffix_opt
+_bin_constant = _bin_prefix + _bin_digits + _integer_suffix_opt
+
+_bad_octal_constant = "0[0-7]*[89]"
+
+# comments are not supported
+_unsupported_c_style_comment = r"\/\*"
+_unsupported_cxx_style_comment = r"\/\/"
+
+# character constants (K&R2: A.2.5.2)
+# Note: a-zA-Z and '.-~^_!=&;,' are allowed as escape chars to support #line
+# directives with Windows paths as filenames (..\..\dir\file)
+# For the same reason, decimal_escape allows all digit sequences. We want to
+# parse all correct code, even if it means to sometimes parse incorrect
+# code.
+#
+# The original regexes were taken verbatim from the C syntax definition,
+# and were later modified to avoid worst-case exponential running time.
+#
+#   simple_escape = r"""([a-zA-Z._~!=&\^\-\\?'"])"""
+#   decimal_escape = r"""(\d+)"""
+#   hex_escape = r"""(x[0-9a-fA-F]+)"""
+#   bad_escape = r"""([\\][^a-zA-Z._~^!=&\^\-\\?'"x0-7])"""
+#
+# The following modifications were made to avoid the ambiguity that allowed
+# backtracking: (https://github.com/eliben/pycparser/issues/61)
+#
+# - \x was removed from simple_escape, unless it was not followed by a hex
+#   digit, to avoid ambiguity with hex_escape.
+# - hex_escape allows one or more hex characters, but requires that the next
+#   character(if any) is not hex
+# - decimal_escape allows one or more decimal characters, but requires that the
+#   next character(if any) is not a decimal
+# - bad_escape does not allow any decimals (8-9), to avoid conflicting with the
+#   permissive decimal_escape.
+#
+# Without this change, python's `re` module would recursively try parsing each
+# ambiguous escape sequence in multiple ways. e.g. `\123` could be parsed as
+# `\1`+`23`, `\12`+`3`, and `\123`.
+
+_simple_escape = r"""([a-wyzA-Z._~!=&\^\-\\?'"]|x(?![0-9a-fA-F]))"""
+_decimal_escape = r"""(\d+)(?!\d)"""
+_hex_escape = r"""(x[0-9a-fA-F]+)(?![0-9a-fA-F])"""
+_bad_escape = r"""([\\][^a-zA-Z._~^!=&\^\-\\?'"x0-9])"""
+
+_escape_sequence = (
+    r"""(\\(""" + _simple_escape + "|" + _decimal_escape + "|" + _hex_escape + "))"
+)
+
+# This complicated regex with lookahead might be slow for strings, so because
+# all of the valid escapes (including \x) allowed
+# 0 or more non-escaped characters after the first character,
+# simple_escape+decimal_escape+hex_escape got simplified to
+
+_escape_sequence_start_in_string = r"""(\\[0-9a-zA-Z._~!=&\^\-\\?'"])"""
+
+_cconst_char = r"""([^'\\\n]|""" + _escape_sequence + ")"
+_char_const = "'" + _cconst_char + "'"
+_wchar_const = "L" + _char_const
+_u8char_const = "u8" + _char_const
+_u16char_const = "u" + _char_const
+_u32char_const = "U" + _char_const
+_multicharacter_constant = "'" + _cconst_char + "{2,4}'"
+_unmatched_quote = "('" + _cconst_char + "*\\n)|('" + _cconst_char + "*$)"
+_bad_char_const = (
+    r"""('""" + _cconst_char + """[^'\n]+')|('')|('""" + _bad_escape + r"""[^'\n]*')"""
+)
+
+# string literals (K&R2: A.2.6)
+_string_char = r"""([^"\\\n]|""" + _escape_sequence_start_in_string + ")"
+_string_literal = '"' + _string_char + '*"'
+_wstring_literal = "L" + _string_literal
+_u8string_literal = "u8" + _string_literal
+_u16string_literal = "u" + _string_literal
+_u32string_literal = "U" + _string_literal
+_bad_string_literal = '"' + _string_char + "*" + _bad_escape + _string_char + '*"'
+
+# floating constants (K&R2: A.2.5.3)
+_exponent_part = r"""([eE][-+]?[0-9]+)"""
+_fractional_constant = r"""([0-9]*\.[0-9]+)|([0-9]+\.)"""
+_floating_constant = (
+    "(((("
+    + _fractional_constant
+    + ")"
+    + _exponent_part
+    + "?)|([0-9]+"
+    + _exponent_part
+    + "))[FfLl]?)"
+)
+_binary_exponent_part = r"""([pP][+-]?[0-9]+)"""
+_hex_fractional_constant = (
+    "(((" + _hex_digits + r""")?\.""" + _hex_digits + ")|(" + _hex_digits + r"""\.))"""
+)
+_hex_floating_constant = (
+    "("
+    + _hex_prefix
+    + "("
+    + _hex_digits
+    + "|"
+    + _hex_fractional_constant
+    + ")"
+    + _binary_exponent_part
+    + "[FfLl]?)"
+)
+
+
+class _RegexAction(Enum):
+    TOKEN = 0
+    ID = 1
+    ERROR = 2
+
+
+@dataclass(frozen=True)
+class _RegexRule:
+    # tok_type: name of the token emitted for a match
+    # regex_pattern: the raw regex (no anchors) to match at the current position
+    # action: TOKEN for normal tokens, ID for identifiers, ERROR to report
+    # error_message: message used for ERROR entries
+    tok_type: str
+    regex_pattern: str
+    action: _RegexAction
+    error_message: Optional[str]
+
+
+_regex_rules: List[_RegexRule] = [
+    _RegexRule(
+        "UNSUPPORTED_C_STYLE_COMMENT",
+        _unsupported_c_style_comment,
+        _RegexAction.ERROR,
+        "Comments are not supported, see https://github.com/eliben/pycparser#3using.",
+    ),
+    _RegexRule(
+        "UNSUPPORTED_CXX_STYLE_COMMENT",
+        _unsupported_cxx_style_comment,
+        _RegexAction.ERROR,
+        "Comments are not supported, see https://github.com/eliben/pycparser#3using.",
+    ),
+    _RegexRule(
+        "BAD_STRING_LITERAL",
+        _bad_string_literal,
+        _RegexAction.ERROR,
+        "String contains invalid escape code",
+    ),
+    _RegexRule("WSTRING_LITERAL", _wstring_literal, _RegexAction.TOKEN, None),
+    _RegexRule("U8STRING_LITERAL", _u8string_literal, _RegexAction.TOKEN, None),
+    _RegexRule("U16STRING_LITERAL", _u16string_literal, _RegexAction.TOKEN, None),
+    _RegexRule("U32STRING_LITERAL", _u32string_literal, _RegexAction.TOKEN, None),
+    _RegexRule("STRING_LITERAL", _string_literal, _RegexAction.TOKEN, None),
+    _RegexRule("HEX_FLOAT_CONST", _hex_floating_constant, _RegexAction.TOKEN, None),
+    _RegexRule("FLOAT_CONST", _floating_constant, _RegexAction.TOKEN, None),
+    _RegexRule("INT_CONST_HEX", _hex_constant, _RegexAction.TOKEN, None),
+    _RegexRule("INT_CONST_BIN", _bin_constant, _RegexAction.TOKEN, None),
+    _RegexRule(
+        "BAD_CONST_OCT",
+        _bad_octal_constant,
+        _RegexAction.ERROR,
+        "Invalid octal constant",
+    ),
+    _RegexRule("INT_CONST_OCT", _octal_constant, _RegexAction.TOKEN, None),
+    _RegexRule("INT_CONST_DEC", _decimal_constant, _RegexAction.TOKEN, None),
+    _RegexRule("INT_CONST_CHAR", _multicharacter_constant, _RegexAction.TOKEN, None),
+    _RegexRule("CHAR_CONST", _char_const, _RegexAction.TOKEN, None),
+    _RegexRule("WCHAR_CONST", _wchar_const, _RegexAction.TOKEN, None),
+    _RegexRule("U8CHAR_CONST", _u8char_const, _RegexAction.TOKEN, None),
+    _RegexRule("U16CHAR_CONST", _u16char_const, _RegexAction.TOKEN, None),
+    _RegexRule("U32CHAR_CONST", _u32char_const, _RegexAction.TOKEN, None),
+    _RegexRule("UNMATCHED_QUOTE", _unmatched_quote, _RegexAction.ERROR, "Unmatched '"),
+    _RegexRule("BAD_CHAR_CONST", _bad_char_const, _RegexAction.ERROR, None),
+    _RegexRule("ID", _identifier, _RegexAction.ID, None),
+]
+
+_regex_actions: Dict[str, Tuple[_RegexAction, Optional[str]]] = {}
+_regex_pattern_parts: List[str] = []
+for _rule in _regex_rules:
+    _regex_actions[_rule.tok_type] = (_rule.action, _rule.error_message)
+    _regex_pattern_parts.append(f"(?P<{_rule.tok_type}>{_rule.regex_pattern})")
+# The master regex is a single alternation of all token patterns, each wrapped
+# in a named group. We match once at the current position and then use
+# `lastgroup` to recover which token kind fired; this avoids iterating over all
+# regexes on every character while keeping the same token-level semantics.
+_regex_master: re.Pattern[str] = re.compile("|".join(_regex_pattern_parts))
+
+
+@dataclass(frozen=True)
+class _FixedToken:
+    tok_type: str
+    literal: str
+
+
+_fixed_tokens: List[_FixedToken] = [
+    _FixedToken("ELLIPSIS", "..."),
+    _FixedToken("LSHIFTEQUAL", "<<="),
+    _FixedToken("RSHIFTEQUAL", ">>="),
+    _FixedToken("PLUSPLUS", "++"),
+    _FixedToken("MINUSMINUS", "--"),
+    _FixedToken("ARROW", "->"),
+    _FixedToken("LAND", "&&"),
+    _FixedToken("LOR", "||"),
+    _FixedToken("LSHIFT", "<<"),
+    _FixedToken("RSHIFT", ">>"),
+    _FixedToken("LE", "<="),
+    _FixedToken("GE", ">="),
+    _FixedToken("EQ", "=="),
+    _FixedToken("NE", "!="),
+    _FixedToken("TIMESEQUAL", "*="),
+    _FixedToken("DIVEQUAL", "/="),
+    _FixedToken("MODEQUAL", "%="),
+    _FixedToken("PLUSEQUAL", "+="),
+    _FixedToken("MINUSEQUAL", "-="),
+    _FixedToken("ANDEQUAL", "&="),
+    _FixedToken("OREQUAL", "|="),
+    _FixedToken("XOREQUAL", "^="),
+    _FixedToken("EQUALS", "="),
+    _FixedToken("PLUS", "+"),
+    _FixedToken("MINUS", "-"),
+    _FixedToken("TIMES", "*"),
+    _FixedToken("DIVIDE", "/"),
+    _FixedToken("MOD", "%"),
+    _FixedToken("OR", "|"),
+    _FixedToken("AND", "&"),
+    _FixedToken("NOT", "~"),
+    _FixedToken("XOR", "^"),
+    _FixedToken("LNOT", "!"),
+    _FixedToken("LT", "<"),
+    _FixedToken("GT", ">"),
+    _FixedToken("CONDOP", "?"),
+    _FixedToken("LPAREN", "("),
+    _FixedToken("RPAREN", ")"),
+    _FixedToken("LBRACKET", "["),
+    _FixedToken("RBRACKET", "]"),
+    _FixedToken("LBRACE", "{"),
+    _FixedToken("RBRACE", "}"),
+    _FixedToken("COMMA", ","),
+    _FixedToken("PERIOD", "."),
+    _FixedToken("SEMI", ";"),
+    _FixedToken("COLON", ":"),
+]
+
+# To avoid scanning all fixed tokens on every character, we bucket them by the
+# first character. When matching at position i, we only look at the bucket for
+# text[i], and we pre-sort that bucket by token length so the first match is
+# also the longest. This preserves longest-match semantics (e.g. '>>=' before
+# '>>' before '>') while reducing the number of comparisons.
+_fixed_tokens_by_first: Dict[str, List[_FixedToken]] = {}
+for _entry in _fixed_tokens:
+    _fixed_tokens_by_first.setdefault(_entry.literal[0], []).append(_entry)
+for _bucket in _fixed_tokens_by_first.values():
+    _bucket.sort(key=lambda item: len(item.literal), reverse=True)
+
+_line_pattern: re.Pattern[str] = re.compile(r"([ \t]*line\W)|([ \t]*\d+)")
+_pragma_pattern: re.Pattern[str] = re.compile(r"[ \t]*pragma\W")
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pycparser/c_parser.py b/TTS/Kokoro/.venv/Lib/site-packages/pycparser/c_parser.py
new file mode 100644
index 0000000000000000000000000000000000000000..f980672cf5eeccea5dc2e60b264d17dd1fbcd058
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pycparser/c_parser.py
@@ -0,0 +1,2376 @@
+# ------------------------------------------------------------------------------
+# pycparser: c_parser.py
+#
+# Recursive-descent parser for the C language.
+#
+# Eli Bendersky [https://eli.thegreenplace.net/]
+# License: BSD
+# ------------------------------------------------------------------------------
+from dataclasses import dataclass
+from typing import (
+    Any,
+    Dict,
+    List,
+    Literal,
+    NoReturn,
+    Optional,
+    Tuple,
+    TypedDict,
+    cast,
+)
+
+from . import c_ast
+from .c_lexer import CLexer, _Token
+from .ast_transforms import fix_switch_cases, fix_atomic_specifiers
+
+
+@dataclass
+class Coord:
+    """Coordinates of a syntactic element. Consists of:
+    - File name
+    - Line number
+    - Column number
+    """
+
+    file: str
+    line: int
+    column: Optional[int] = None
+
+    def __str__(self) -> str:
+        text = f"{self.file}:{self.line}"
+        if self.column:
+            text += f":{self.column}"
+        return text
+
+
+class ParseError(Exception):
+    pass
+
+
+class CParser:
+    """Recursive-descent C parser.
+
+    Usage:
+        parser = CParser()
+        ast = parser.parse(text, filename)
+
+    The `lexer` parameter lets you inject a lexer class (defaults to CLexer).
+    The parameters after `lexer` are accepted for backward compatibility with
+    the old PLY-based parser and are otherwise unused.
+    """
+
+    def __init__(
+        self,
+        lex_optimize: bool = True,
+        lexer: type[CLexer] = CLexer,
+        lextab: str = "pycparser.lextab",
+        yacc_optimize: bool = True,
+        yacctab: str = "pycparser.yacctab",
+        yacc_debug: bool = False,
+        taboutputdir: str = "",
+    ) -> None:
+        self.clex: CLexer = lexer(
+            error_func=self._lex_error_func,
+            on_lbrace_func=self._lex_on_lbrace_func,
+            on_rbrace_func=self._lex_on_rbrace_func,
+            type_lookup_func=self._lex_type_lookup_func,
+        )
+
+        # Stack of scopes for keeping track of symbols. _scope_stack[-1] is
+        # the current (topmost) scope. Each scope is a dictionary that
+        # specifies whether a name is a type. If _scope_stack[n][name] is
+        # True, 'name' is currently a type in the scope. If it's False,
+        # 'name' is used in the scope but not as a type (for instance, if we
+        # saw: int name;
+        # If 'name' is not a key in _scope_stack[n] then 'name' was not defined
+        # in this scope at all.
+        self._scope_stack: List[Dict[str, bool]] = [dict()]
+        self._tokens: _TokenStream = _TokenStream(self.clex)
+
+    def parse(
+        self, text: str, filename: str = "", debug: bool = False
+    ) -> c_ast.FileAST:
+        """Parses C code and returns an AST.
+
+        text:
+            A string containing the C source code
+
+        filename:
+            Name of the file being parsed (for meaningful
+            error messages)
+
+        debug:
+            Deprecated debug flag (unused); for backwards compatibility.
+        """
+        self._scope_stack = [dict()]
+        self.clex.input(text, filename)
+        self._tokens = _TokenStream(self.clex)
+
+        ast = self._parse_translation_unit_or_empty()
+        tok = self._peek()
+        if tok is not None:
+            self._parse_error(f"before: {tok.value}", self._tok_coord(tok))
+        return ast
+
+    # ------------------------------------------------------------------
+    # Scope and declaration helpers
+    # ------------------------------------------------------------------
+    def _coord(self, lineno: int, column: Optional[int] = None) -> Coord:
+        return Coord(file=self.clex.filename, line=lineno, column=column)
+
+    def _parse_error(self, msg: str, coord: Coord | str | None) -> NoReturn:
+        raise ParseError(f"{coord}: {msg}")
+
+    def _push_scope(self) -> None:
+        self._scope_stack.append(dict())
+
+    def _pop_scope(self) -> None:
+        assert len(self._scope_stack) > 1
+        self._scope_stack.pop()
+
+    def _add_typedef_name(self, name: str, coord: Optional[Coord]) -> None:
+        """Add a new typedef name (ie a TYPEID) to the current scope"""
+        if not self._scope_stack[-1].get(name, True):
+            self._parse_error(
+                f"Typedef {name!r} previously declared as non-typedef in this scope",
+                coord,
+            )
+        self._scope_stack[-1][name] = True
+
+    def _add_identifier(self, name: str, coord: Optional[Coord]) -> None:
+        """Add a new object, function, or enum member name (ie an ID) to the
+        current scope
+        """
+        if self._scope_stack[-1].get(name, False):
+            self._parse_error(
+                f"Non-typedef {name!r} previously declared as typedef in this scope",
+                coord,
+            )
+        self._scope_stack[-1][name] = False
+
+    def _is_type_in_scope(self, name: str) -> bool:
+        """Is *name* a typedef-name in the current scope?"""
+        for scope in reversed(self._scope_stack):
+            # If name is an identifier in this scope it shadows typedefs in
+            # higher scopes.
+            in_scope = scope.get(name)
+            if in_scope is not None:
+                return in_scope
+        return False
+
+    def _lex_error_func(self, msg: str, line: int, column: int) -> None:
+        self._parse_error(msg, self._coord(line, column))
+
+    def _lex_on_lbrace_func(self) -> None:
+        self._push_scope()
+
+    def _lex_on_rbrace_func(self) -> None:
+        self._pop_scope()
+
+    def _lex_type_lookup_func(self, name: str) -> bool:
+        """Looks up types that were previously defined with
+        typedef.
+        Passed to the lexer for recognizing identifiers that
+        are types.
+        """
+        return self._is_type_in_scope(name)
+
+    # To understand what's going on here, read sections A.8.5 and
+    # A.8.6 of K&R2 very carefully.
+    #
+    # A C type consists of a basic type declaration, with a list
+    # of modifiers. For example:
+    #
+    # int *c[5];
+    #
+    # The basic declaration here is 'int c', and the pointer and
+    # the array are the modifiers.
+    #
+    # Basic declarations are represented by TypeDecl (from module c_ast) and the
+    # modifiers are FuncDecl, PtrDecl and ArrayDecl.
+    #
+    # The standard states that whenever a new modifier is parsed, it should be
+    # added to the end of the list of modifiers. For example:
+    #
+    # K&R2 A.8.6.2: Array Declarators
+    #
+    # In a declaration T D where D has the form
+    #   D1 [constant-expression-opt]
+    # and the type of the identifier in the declaration T D1 is
+    # "type-modifier T", the type of the
+    # identifier of D is "type-modifier array of T"
+    #
+    # This is what this method does. The declarator it receives
+    # can be a list of declarators ending with TypeDecl. It
+    # tacks the modifier to the end of this list, just before
+    # the TypeDecl.
+    #
+    # Additionally, the modifier may be a list itself. This is
+    # useful for pointers, that can come as a chain from the rule
+    # p_pointer. In this case, the whole modifier list is spliced
+    # into the new location.
+    def _type_modify_decl(self, decl: Any, modifier: Any) -> c_ast.Node:
+        """Tacks a type modifier on a declarator, and returns
+        the modified declarator.
+
+        Note: the declarator and modifier may be modified
+        """
+        modifier_head = modifier
+        modifier_tail = modifier
+
+        # The modifier may be a nested list. Reach its tail.
+        while modifier_tail.type:
+            modifier_tail = modifier_tail.type
+
+        # If the decl is a basic type, just tack the modifier onto it.
+        if isinstance(decl, c_ast.TypeDecl):
+            modifier_tail.type = decl
+            return modifier
+        else:
+            # Otherwise, the decl is a list of modifiers. Reach
+            # its tail and splice the modifier onto the tail,
+            # pointing to the underlying basic type.
+            decl_tail = decl
+            while not isinstance(decl_tail.type, c_ast.TypeDecl):
+                decl_tail = decl_tail.type
+
+            modifier_tail.type = decl_tail.type
+            decl_tail.type = modifier_head
+            return decl
+
+    # Due to the order in which declarators are constructed,
+    # they have to be fixed in order to look like a normal AST.
+    #
+    # When a declaration arrives from syntax construction, it has
+    # these problems:
+    # * The innermost TypeDecl has no type (because the basic
+    #   type is only known at the uppermost declaration level)
+    # * The declaration has no variable name, since that is saved
+    #   in the innermost TypeDecl
+    # * The typename of the declaration is a list of type
+    #   specifiers, and not a node. Here, basic identifier types
+    #   should be separated from more complex types like enums
+    #   and structs.
+    #
+    # This method fixes these problems.
+    def _fix_decl_name_type(
+        self,
+        decl: c_ast.Decl | c_ast.Typedef | c_ast.Typename,
+        typename: List[Any],
+    ) -> c_ast.Decl | c_ast.Typedef | c_ast.Typename:
+        """Fixes a declaration. Modifies decl."""
+        # Reach the underlying basic type
+        typ = decl
+        while not isinstance(typ, c_ast.TypeDecl):
+            typ = typ.type
+
+        decl.name = typ.declname
+        typ.quals = decl.quals[:]
+
+        # The typename is a list of types. If any type in this
+        # list isn't an IdentifierType, it must be the only
+        # type in the list (it's illegal to declare "int enum ..")
+        # If all the types are basic, they're collected in the
+        # IdentifierType holder.
+        for tn in typename:
+            if not isinstance(tn, c_ast.IdentifierType):
+                if len(typename) > 1:
+                    self._parse_error("Invalid multiple types specified", tn.coord)
+                else:
+                    typ.type = tn
+                    return decl
+
+        if not typename:
+            # Functions default to returning int
+            if not isinstance(decl.type, c_ast.FuncDecl):
+                self._parse_error("Missing type in declaration", decl.coord)
+            typ.type = c_ast.IdentifierType(["int"], coord=decl.coord)
+        else:
+            # At this point, we know that typename is a list of IdentifierType
+            # nodes. Concatenate all the names into a single list.
+            typ.type = c_ast.IdentifierType(
+                [name for id in typename for name in id.names], coord=typename[0].coord
+            )
+        return decl
+
+    def _add_declaration_specifier(
+        self,
+        declspec: Optional["_DeclSpec"],
+        newspec: Any,
+        kind: "_DeclSpecKind",
+        append: bool = False,
+    ) -> "_DeclSpec":
+        """See _DeclSpec for the specifier dictionary layout."""
+        if declspec is None:
+            spec: _DeclSpec = dict(
+                qual=[], storage=[], type=[], function=[], alignment=[]
+            )
+        else:
+            spec = declspec
+
+        if append:
+            spec[kind].append(newspec)
+        else:
+            spec[kind].insert(0, newspec)
+
+        return spec
+
+    def _build_declarations(
+        self,
+        spec: "_DeclSpec",
+        decls: List["_DeclInfo"],
+        typedef_namespace: bool = False,
+    ) -> List[c_ast.Node]:
+        """Builds a list of declarations all sharing the given specifiers.
+        If typedef_namespace is true, each declared name is added
+        to the "typedef namespace", which also includes objects,
+        functions, and enum constants.
+        """
+        is_typedef = "typedef" in spec["storage"]
+        declarations = []
+
+        # Bit-fields are allowed to be unnamed.
+        if decls[0].get("bitsize") is None:
+            # When redeclaring typedef names as identifiers in inner scopes, a
+            # problem can occur where the identifier gets grouped into
+            # spec['type'], leaving decl as None.  This can only occur for the
+            # first declarator.
+            if decls[0]["decl"] is None:
+                if (
+                    len(spec["type"]) < 2
+                    or len(spec["type"][-1].names) != 1
+                    or not self._is_type_in_scope(spec["type"][-1].names[0])
+                ):
+                    coord = "?"
+                    for t in spec["type"]:
+                        if hasattr(t, "coord"):
+                            coord = t.coord
+                            break
+                    self._parse_error("Invalid declaration", coord)
+
+                # Make this look as if it came from "direct_declarator:ID"
+                decls[0]["decl"] = c_ast.TypeDecl(
+                    declname=spec["type"][-1].names[0],
+                    type=None,
+                    quals=None,
+                    align=spec["alignment"],
+                    coord=spec["type"][-1].coord,
+                )
+                # Remove the "new" type's name from the end of spec['type']
+                del spec["type"][-1]
+            # A similar problem can occur where the declaration ends up
+            # looking like an abstract declarator.  Give it a name if this is
+            # the case.
+            elif not isinstance(
+                decls[0]["decl"],
+                (c_ast.Enum, c_ast.Struct, c_ast.Union, c_ast.IdentifierType),
+            ):
+                decls_0_tail = cast(Any, decls[0]["decl"])
+                while not isinstance(decls_0_tail, c_ast.TypeDecl):
+                    decls_0_tail = decls_0_tail.type
+                if decls_0_tail.declname is None:
+                    decls_0_tail.declname = spec["type"][-1].names[0]
+                    del spec["type"][-1]
+
+        for decl in decls:
+            assert decl["decl"] is not None
+            if is_typedef:
+                declaration = c_ast.Typedef(
+                    name=None,
+                    quals=spec["qual"],
+                    storage=spec["storage"],
+                    type=decl["decl"],
+                    coord=decl["decl"].coord,
+                )
+            else:
+                declaration = c_ast.Decl(
+                    name=None,
+                    quals=spec["qual"],
+                    align=spec["alignment"],
+                    storage=spec["storage"],
+                    funcspec=spec["function"],
+                    type=decl["decl"],
+                    init=decl.get("init"),
+                    bitsize=decl.get("bitsize"),
+                    coord=decl["decl"].coord,
+                )
+
+            if isinstance(
+                declaration.type,
+                (c_ast.Enum, c_ast.Struct, c_ast.Union, c_ast.IdentifierType),
+            ):
+                fixed_decl = declaration
+            else:
+                fixed_decl = self._fix_decl_name_type(declaration, spec["type"])
+
+            # Add the type name defined by typedef to a
+            # symbol table (for usage in the lexer)
+            if typedef_namespace:
+                if is_typedef:
+                    self._add_typedef_name(fixed_decl.name, fixed_decl.coord)
+                else:
+                    self._add_identifier(fixed_decl.name, fixed_decl.coord)
+
+            fixed_decl = fix_atomic_specifiers(
+                cast(c_ast.Decl | c_ast.Typedef, fixed_decl)
+            )
+            declarations.append(fixed_decl)
+
+        return declarations
+
+    def _build_function_definition(
+        self,
+        spec: "_DeclSpec",
+        decl: c_ast.Node,
+        param_decls: Optional[List[c_ast.Node]],
+        body: c_ast.Node,
+    ) -> c_ast.Node:
+        """Builds a function definition."""
+        if "typedef" in spec["storage"]:
+            self._parse_error("Invalid typedef", decl.coord)
+
+        declaration = self._build_declarations(
+            spec=spec,
+            decls=[dict(decl=decl, init=None, bitsize=None)],
+            typedef_namespace=True,
+        )[0]
+
+        return c_ast.FuncDef(
+            decl=declaration, param_decls=param_decls, body=body, coord=decl.coord
+        )
+
+    def _select_struct_union_class(self, token: str) -> type:
+        """Given a token (either STRUCT or UNION), selects the
+        appropriate AST class.
+        """
+        if token == "struct":
+            return c_ast.Struct
+        else:
+            return c_ast.Union
+
+    # ------------------------------------------------------------------
+    # Token helpers
+    # ------------------------------------------------------------------
+    def _peek(self, k: int = 1) -> Optional[_Token]:
+        """Return the k-th next token without consuming it (1-based)."""
+        return self._tokens.peek(k)
+
+    def _peek_type(self, k: int = 1) -> Optional[str]:
+        """Return the type of the k-th next token, or None if absent (1-based)."""
+        tok = self._peek(k)
+        return tok.type if tok is not None else None
+
+    def _advance(self) -> _Token:
+        tok = self._tokens.next()
+        if tok is None:
+            self._parse_error("At end of input", self.clex.filename)
+        else:
+            return tok
+
+    def _accept(self, token_type: str) -> Optional[_Token]:
+        """Conditionally consume next token, only if it's of token_type.
+
+        If it is of the expected type, consume and return it.
+        Otherwise, leaves the token intact and returns None.
+        """
+        tok = self._peek()
+        if tok is not None and tok.type == token_type:
+            return self._advance()
+        return None
+
+    def _expect(self, token_type: str) -> _Token:
+        tok = self._advance()
+        if tok.type != token_type:
+            self._parse_error(f"before: {tok.value}", self._tok_coord(tok))
+        return tok
+
+    def _mark(self) -> int:
+        return self._tokens.mark()
+
+    def _reset(self, mark: int) -> None:
+        self._tokens.reset(mark)
+
+    def _tok_coord(self, tok: _Token) -> Coord:
+        return self._coord(tok.lineno, tok.column)
+
+    def _starts_declaration(self, tok: Optional[_Token] = None) -> bool:
+        tok = tok or self._peek()
+        if tok is None:
+            return False
+        return tok.type in _DECL_START
+
+    def _starts_expression(self, tok: Optional[_Token] = None) -> bool:
+        tok = tok or self._peek()
+        if tok is None:
+            return False
+        return tok.type in _STARTS_EXPRESSION
+
+    def _starts_statement(self) -> bool:
+        tok_type = self._peek_type()
+        if tok_type is None:
+            return False
+        if tok_type in _STARTS_STATEMENT:
+            return True
+        return self._starts_expression()
+
+    def _starts_declarator(self, id_only: bool = False) -> bool:
+        tok_type = self._peek_type()
+        if tok_type is None:
+            return False
+        if tok_type in {"TIMES", "LPAREN"}:
+            return True
+        if id_only:
+            return tok_type == "ID"
+        return tok_type in {"ID", "TYPEID"}
+
+    def _peek_declarator_name_info(self) -> Tuple[Optional[str], bool]:
+        mark = self._mark()
+        tok_type, saw_paren = self._scan_declarator_name_info()
+        self._reset(mark)
+        return tok_type, saw_paren
+
+    def _parse_any_declarator(
+        self, allow_abstract: bool = False, typeid_paren_as_abstract: bool = False
+    ) -> Tuple[Optional[c_ast.Node], bool]:
+        # C declarators are ambiguous without lookahead. For example:
+        #   int foo(int (aa));   -> aa is a name (ID)
+        #   typedef char TT;
+        #   int bar(int (TT));   -> TT is a type (TYPEID) in parens
+        name_type, saw_paren = self._peek_declarator_name_info()
+        if name_type is None or (
+            typeid_paren_as_abstract and name_type == "TYPEID" and saw_paren
+        ):
+            if not allow_abstract:
+                tok = self._peek()
+                coord = self._tok_coord(tok) if tok is not None else self.clex.filename
+                self._parse_error("Invalid declarator", coord)
+            decl = self._parse_abstract_declarator_opt()
+            return decl, False
+
+        if name_type == "TYPEID":
+            if typeid_paren_as_abstract:
+                decl = self._parse_typeid_noparen_declarator()
+            else:
+                decl = self._parse_typeid_declarator()
+        else:
+            decl = self._parse_id_declarator()
+        return decl, True
+
+    def _scan_declarator_name_info(self) -> Tuple[Optional[str], bool]:
+        saw_paren = False
+        while self._accept("TIMES"):
+            while self._peek_type() in _TYPE_QUALIFIER:
+                self._advance()
+
+        tok = self._peek()
+        if tok is None:
+            return None, saw_paren
+        if tok.type in {"ID", "TYPEID"}:
+            self._advance()
+            return tok.type, saw_paren
+        if tok.type == "LPAREN":
+            saw_paren = True
+            self._advance()
+            tok_type, nested_paren = self._scan_declarator_name_info()
+            if nested_paren:
+                saw_paren = True
+            depth = 1
+            while True:
+                tok = self._peek()
+                if tok is None:
+                    return None, saw_paren
+                if tok.type == "LPAREN":
+                    depth += 1
+                elif tok.type == "RPAREN":
+                    depth -= 1
+                    self._advance()
+                    if depth == 0:
+                        break
+                    continue
+                self._advance()
+            return tok_type, saw_paren
+        return None, saw_paren
+
+    def _starts_direct_abstract_declarator(self) -> bool:
+        return self._peek_type() in {"LPAREN", "LBRACKET"}
+
+    def _is_assignment_op(self) -> bool:
+        tok = self._peek()
+        return tok is not None and tok.type in _ASSIGNMENT_OPS
+
+    def _try_parse_paren_type_name(
+        self,
+    ) -> Optional[Tuple[c_ast.Typename, int, _Token]]:
+        """Parse and return a parenthesized type name if present.
+
+        Returns (typ, mark, lparen_tok) when the next tokens look like
+        '(' type_name ')', where typ is the parsed type name, mark is the
+        token-stream position before parsing, and lparen_tok is the LPAREN
+        token. Returns None if no parenthesized type name is present.
+        """
+        mark = self._mark()
+        lparen_tok = self._accept("LPAREN")
+        if lparen_tok is None:
+            return None
+        if not self._starts_declaration():
+            self._reset(mark)
+            return None
+        typ = self._parse_type_name()
+        if self._accept("RPAREN") is None:
+            self._reset(mark)
+            return None
+        return typ, mark, lparen_tok
+
+    # ------------------------------------------------------------------
+    # Top-level
+    # ------------------------------------------------------------------
+    # BNF: translation_unit_or_empty : translation_unit | empty
+    def _parse_translation_unit_or_empty(self) -> c_ast.FileAST:
+        if self._peek() is None:
+            return c_ast.FileAST([])
+        return c_ast.FileAST(self._parse_translation_unit())
+
+    # BNF: translation_unit : external_declaration+
+    def _parse_translation_unit(self) -> List[c_ast.Node]:
+        ext = []
+        while self._peek() is not None:
+            ext.extend(self._parse_external_declaration())
+        return ext
+
+    # BNF: external_declaration : function_definition
+    #                           | declaration
+    #                           | pp_directive
+    #                           | pppragma_directive
+    #                           | static_assert
+    #                           | ';'
+    def _parse_external_declaration(self) -> List[c_ast.Node]:
+        tok = self._peek()
+        if tok is None:
+            return []
+        if tok.type == "PPHASH":
+            self._parse_pp_directive()
+            return []
+        if tok.type in {"PPPRAGMA", "_PRAGMA"}:
+            return [self._parse_pppragma_directive()]
+        if self._accept("SEMI"):
+            return []
+        if tok.type == "_STATIC_ASSERT":
+            return self._parse_static_assert()
+
+        if not self._starts_declaration(tok):
+            # Special handling for old-style function definitions that have an
+            # implicit return type, e.g.
+            #
+            #   foo() {
+            #    return 5;
+            #   }
+            #
+            # These get an implicit 'int' return type.
+            decl = self._parse_id_declarator()
+            param_decls = None
+            if self._peek_type() != "LBRACE":
+                self._parse_error("Invalid function definition", decl.coord)
+            spec: _DeclSpec = dict(
+                qual=[],
+                alignment=[],
+                storage=[],
+                type=[c_ast.IdentifierType(["int"], coord=decl.coord)],
+                function=[],
+            )
+            func = self._build_function_definition(
+                spec=spec,
+                decl=decl,
+                param_decls=param_decls,
+                body=self._parse_compound_statement(),
+            )
+            return [func]
+
+        # From here on, parsing a standard declatation/definition.
+        spec, saw_type, spec_coord = self._parse_declaration_specifiers(
+            allow_no_type=True
+        )
+
+        name_type, _ = self._peek_declarator_name_info()
+        if name_type != "ID":
+            decls = self._parse_decl_body_with_spec(spec, saw_type)
+            self._expect("SEMI")
+            return decls
+
+        decl = self._parse_id_declarator()
+
+        if self._peek_type() == "LBRACE" or self._starts_declaration():
+            param_decls = None
+            if self._starts_declaration():
+                param_decls = self._parse_declaration_list()
+            if self._peek_type() != "LBRACE":
+                self._parse_error("Invalid function definition", decl.coord)
+            if not spec["type"]:
+                spec["type"] = [c_ast.IdentifierType(["int"], coord=spec_coord)]
+            func = self._build_function_definition(
+                spec=spec,
+                decl=decl,
+                param_decls=param_decls,
+                body=self._parse_compound_statement(),
+            )
+            return [func]
+
+        decl_dict: "_DeclInfo" = dict(decl=decl, init=None, bitsize=None)
+        if self._accept("EQUALS"):
+            decl_dict["init"] = self._parse_initializer()
+        decls = self._parse_init_declarator_list(first=decl_dict)
+        decls = self._build_declarations(spec=spec, decls=decls, typedef_namespace=True)
+        self._expect("SEMI")
+        return decls
+
+    # ------------------------------------------------------------------
+    # Declarations
+    #
+    # Declarations always come as lists (because they can be several in one
+    # line). When returning parsed declarations, a list is always returned -
+    # even if it contains a single element.
+    # ------------------------------------------------------------------
+    def _parse_declaration(self) -> List[c_ast.Node]:
+        decls = self._parse_decl_body()
+        self._expect("SEMI")
+        return decls
+
+    # BNF: decl_body : declaration_specifiers decl_body_with_spec
+    def _parse_decl_body(self) -> List[c_ast.Node]:
+        spec, saw_type, _ = self._parse_declaration_specifiers(allow_no_type=True)
+        return self._parse_decl_body_with_spec(spec, saw_type)
+
+    # BNF: decl_body_with_spec : init_declarator_list
+    #                          | struct_or_union_or_enum_only
+    def _parse_decl_body_with_spec(
+        self, spec: "_DeclSpec", saw_type: bool
+    ) -> List[c_ast.Node]:
+        decls = None
+        if saw_type:
+            if self._starts_declarator():
+                decls = self._parse_init_declarator_list()
+        else:
+            if self._starts_declarator(id_only=True):
+                decls = self._parse_init_declarator_list(id_only=True)
+
+        if decls is None:
+            ty = spec["type"]
+            s_u_or_e = (c_ast.Struct, c_ast.Union, c_ast.Enum)
+            if len(ty) == 1 and isinstance(ty[0], s_u_or_e):
+                decls = [
+                    c_ast.Decl(
+                        name=None,
+                        quals=spec["qual"],
+                        align=spec["alignment"],
+                        storage=spec["storage"],
+                        funcspec=spec["function"],
+                        type=ty[0],
+                        init=None,
+                        bitsize=None,
+                        coord=ty[0].coord,
+                    )
+                ]
+            else:
+                decls = self._build_declarations(
+                    spec=spec,
+                    decls=[dict(decl=None, init=None, bitsize=None)],
+                    typedef_namespace=True,
+                )
+        else:
+            decls = self._build_declarations(
+                spec=spec, decls=decls, typedef_namespace=True
+            )
+
+        return decls
+
+    # BNF: declaration_list : declaration+
+    def _parse_declaration_list(self) -> List[c_ast.Node]:
+        decls = []
+        while self._starts_declaration():
+            decls.extend(self._parse_declaration())
+        return decls
+
+    # BNF: declaration_specifiers   : (storage_class_specifier
+    #                               | type_specifier
+    #                               | type_qualifier
+    #                               | function_specifier
+    #                               | alignment_specifier)+
+    def _parse_declaration_specifiers(
+        self, allow_no_type: bool = False
+    ) -> Tuple["_DeclSpec", bool, Optional[Coord]]:
+        """Parse declaration-specifier sequence.
+
+        allow_no_type:
+            If True, allow a missing type specifier without error.
+
+        Returns:
+            (spec, saw_type, first_coord) where spec is a dict with
+            qual/storage/type/function/alignment entries, saw_type is True
+            if a type specifier was consumed, and first_coord is the coord
+            of the first specifier token (used for diagnostics).
+        """
+        spec = None
+        saw_type = False
+        first_coord = None
+
+        while True:
+            tok = self._peek()
+            if tok is None:
+                break
+
+            if tok.type == "_ALIGNAS":
+                if first_coord is None:
+                    first_coord = self._tok_coord(tok)
+                spec = self._add_declaration_specifier(
+                    spec, self._parse_alignment_specifier(), "alignment", append=True
+                )
+                continue
+
+            if tok.type == "_ATOMIC" and self._peek_type(2) == "LPAREN":
+                if first_coord is None:
+                    first_coord = self._tok_coord(tok)
+                spec = self._add_declaration_specifier(
+                    spec, self._parse_atomic_specifier(), "type", append=True
+                )
+                saw_type = True
+                continue
+
+            if tok.type in _TYPE_QUALIFIER:
+                if first_coord is None:
+                    first_coord = self._tok_coord(tok)
+                spec = self._add_declaration_specifier(
+                    spec, self._advance().value, "qual", append=True
+                )
+                continue
+
+            if tok.type in _STORAGE_CLASS:
+                if first_coord is None:
+                    first_coord = self._tok_coord(tok)
+                spec = self._add_declaration_specifier(
+                    spec, self._advance().value, "storage", append=True
+                )
+                continue
+
+            if tok.type in _FUNCTION_SPEC:
+                if first_coord is None:
+                    first_coord = self._tok_coord(tok)
+                spec = self._add_declaration_specifier(
+                    spec, self._advance().value, "function", append=True
+                )
+                continue
+
+            if tok.type in _TYPE_SPEC_SIMPLE:
+                if first_coord is None:
+                    first_coord = self._tok_coord(tok)
+                tok = self._advance()
+                spec = self._add_declaration_specifier(
+                    spec,
+                    c_ast.IdentifierType([tok.value], coord=self._tok_coord(tok)),
+                    "type",
+                    append=True,
+                )
+                saw_type = True
+                continue
+
+            if tok.type == "TYPEID":
+                if saw_type:
+                    break
+                if first_coord is None:
+                    first_coord = self._tok_coord(tok)
+                tok = self._advance()
+                spec = self._add_declaration_specifier(
+                    spec,
+                    c_ast.IdentifierType([tok.value], coord=self._tok_coord(tok)),
+                    "type",
+                    append=True,
+                )
+                saw_type = True
+                continue
+
+            if tok.type in {"STRUCT", "UNION"}:
+                if first_coord is None:
+                    first_coord = self._tok_coord(tok)
+                spec = self._add_declaration_specifier(
+                    spec, self._parse_struct_or_union_specifier(), "type", append=True
+                )
+                saw_type = True
+                continue
+
+            if tok.type == "ENUM":
+                if first_coord is None:
+                    first_coord = self._tok_coord(tok)
+                spec = self._add_declaration_specifier(
+                    spec, self._parse_enum_specifier(), "type", append=True
+                )
+                saw_type = True
+                continue
+
+            break
+
+        if spec is None:
+            self._parse_error("Invalid declaration", self.clex.filename)
+
+        if not saw_type and not allow_no_type:
+            self._parse_error("Missing type in declaration", first_coord)
+
+        return spec, saw_type, first_coord
+
+    # BNF: specifier_qualifier_list : (type_specifier
+    #                               | type_qualifier
+    #                               | alignment_specifier)+
+    def _parse_specifier_qualifier_list(self) -> "_DeclSpec":
+        spec = None
+        saw_type = False
+        saw_alignment = False
+        first_coord = None
+
+        while True:
+            tok = self._peek()
+            if tok is None:
+                break
+
+            if tok.type == "_ALIGNAS":
+                if first_coord is None:
+                    first_coord = self._tok_coord(tok)
+                spec = self._add_declaration_specifier(
+                    spec, self._parse_alignment_specifier(), "alignment", append=True
+                )
+                saw_alignment = True
+                continue
+
+            if tok.type == "_ATOMIC" and self._peek_type(2) == "LPAREN":
+                if first_coord is None:
+                    first_coord = self._tok_coord(tok)
+                spec = self._add_declaration_specifier(
+                    spec, self._parse_atomic_specifier(), "type", append=True
+                )
+                saw_type = True
+                continue
+
+            if tok.type in _TYPE_QUALIFIER:
+                if first_coord is None:
+                    first_coord = self._tok_coord(tok)
+                spec = self._add_declaration_specifier(
+                    spec, self._advance().value, "qual", append=True
+                )
+                continue
+
+            if tok.type in _TYPE_SPEC_SIMPLE:
+                if first_coord is None:
+                    first_coord = self._tok_coord(tok)
+                tok = self._advance()
+                spec = self._add_declaration_specifier(
+                    spec,
+                    c_ast.IdentifierType([tok.value], coord=self._tok_coord(tok)),
+                    "type",
+                    append=True,
+                )
+                saw_type = True
+                continue
+
+            if tok.type == "TYPEID":
+                if saw_type:
+                    break
+                if first_coord is None:
+                    first_coord = self._tok_coord(tok)
+                tok = self._advance()
+                spec = self._add_declaration_specifier(
+                    spec,
+                    c_ast.IdentifierType([tok.value], coord=self._tok_coord(tok)),
+                    "type",
+                    append=True,
+                )
+                saw_type = True
+                continue
+
+            if tok.type in {"STRUCT", "UNION"}:
+                if first_coord is None:
+                    first_coord = self._tok_coord(tok)
+                spec = self._add_declaration_specifier(
+                    spec, self._parse_struct_or_union_specifier(), "type", append=True
+                )
+                saw_type = True
+                continue
+
+            if tok.type == "ENUM":
+                if first_coord is None:
+                    first_coord = self._tok_coord(tok)
+                spec = self._add_declaration_specifier(
+                    spec, self._parse_enum_specifier(), "type", append=True
+                )
+                saw_type = True
+                continue
+
+            break
+
+        if spec is None:
+            self._parse_error("Invalid specifier list", self.clex.filename)
+
+        if not saw_type and not saw_alignment:
+            self._parse_error("Missing type in declaration", first_coord)
+
+        if spec.get("storage") is None:
+            spec["storage"] = []
+        if spec.get("function") is None:
+            spec["function"] = []
+
+        return spec
+
+    # BNF: type_qualifier_list : type_qualifier+
+    def _parse_type_qualifier_list(self) -> List[str]:
+        quals = []
+        while self._peek_type() in _TYPE_QUALIFIER:
+            quals.append(self._advance().value)
+        return quals
+
+    # BNF: alignment_specifier : _ALIGNAS '(' type_name | constant_expression ')'
+    def _parse_alignment_specifier(self) -> c_ast.Node:
+        tok = self._expect("_ALIGNAS")
+        self._expect("LPAREN")
+
+        if self._starts_declaration():
+            typ = self._parse_type_name()
+            self._expect("RPAREN")
+            return c_ast.Alignas(typ, self._tok_coord(tok))
+
+        expr = self._parse_constant_expression()
+        self._expect("RPAREN")
+        return c_ast.Alignas(expr, self._tok_coord(tok))
+
+    # BNF: atomic_specifier : _ATOMIC '(' type_name ')'
+    def _parse_atomic_specifier(self) -> c_ast.Node:
+        self._expect("_ATOMIC")
+        self._expect("LPAREN")
+        typ = self._parse_type_name()
+        self._expect("RPAREN")
+        typ.quals.append("_Atomic")
+        return typ
+
+    # BNF: init_declarator_list : init_declarator (',' init_declarator)*
+    def _parse_init_declarator_list(
+        self, first: Optional["_DeclInfo"] = None, id_only: bool = False
+    ) -> List["_DeclInfo"]:
+        decls = (
+            [first]
+            if first is not None
+            else [self._parse_init_declarator(id_only=id_only)]
+        )
+
+        while self._accept("COMMA"):
+            decls.append(self._parse_init_declarator(id_only=id_only))
+        return decls
+
+    # BNF: init_declarator : declarator ('=' initializer)?
+    def _parse_init_declarator(self, id_only: bool = False) -> "_DeclInfo":
+        decl = self._parse_id_declarator() if id_only else self._parse_declarator()
+        init = None
+        if self._accept("EQUALS"):
+            init = self._parse_initializer()
+        return dict(decl=decl, init=init, bitsize=None)
+
+    # ------------------------------------------------------------------
+    # Structs/unions/enums
+    # ------------------------------------------------------------------
+    # BNF: struct_or_union_specifier : struct_or_union ID? '{' struct_declaration_list? '}'
+    #                                | struct_or_union ID
+    def _parse_struct_or_union_specifier(self) -> c_ast.Node:
+        tok = self._advance()
+        klass = self._select_struct_union_class(tok.value)
+
+        if self._peek_type() in {"ID", "TYPEID"}:
+            name_tok = self._advance()
+            if self._peek_type() == "LBRACE":
+                self._advance()
+                if self._accept("RBRACE"):
+                    return klass(
+                        name=name_tok.value, decls=[], coord=self._tok_coord(name_tok)
+                    )
+                decls = self._parse_struct_declaration_list()
+                self._expect("RBRACE")
+                return klass(
+                    name=name_tok.value, decls=decls, coord=self._tok_coord(name_tok)
+                )
+
+            return klass(
+                name=name_tok.value, decls=None, coord=self._tok_coord(name_tok)
+            )
+
+        if self._peek_type() == "LBRACE":
+            brace_tok = self._advance()
+            if self._accept("RBRACE"):
+                return klass(name=None, decls=[], coord=self._tok_coord(brace_tok))
+            decls = self._parse_struct_declaration_list()
+            self._expect("RBRACE")
+            return klass(name=None, decls=decls, coord=self._tok_coord(brace_tok))
+
+        self._parse_error("Invalid struct/union declaration", self._tok_coord(tok))
+
+    # BNF: struct_declaration_list : struct_declaration+
+    def _parse_struct_declaration_list(self) -> List[c_ast.Node]:
+        decls = []
+        while self._peek_type() not in {None, "RBRACE"}:
+            items = self._parse_struct_declaration()
+            if items is None:
+                continue
+            decls.extend(items)
+        return decls
+
+    # BNF: struct_declaration   : specifier_qualifier_list struct_declarator_list? ';'
+    #                           | static_assert
+    #                           | pppragma_directive
+    def _parse_struct_declaration(self) -> Optional[List[c_ast.Node]]:
+        if self._peek_type() == "SEMI":
+            self._advance()
+            return None
+        if self._peek_type() in {"PPPRAGMA", "_PRAGMA"}:
+            return [self._parse_pppragma_directive()]
+
+        spec = self._parse_specifier_qualifier_list()
+        assert "typedef" not in spec.get("storage", [])
+
+        decls = None
+        if self._starts_declarator() or self._peek_type() == "COLON":
+            decls = self._parse_struct_declarator_list()
+        if decls is not None:
+            self._expect("SEMI")
+            return self._build_declarations(spec=spec, decls=decls)
+
+        if len(spec["type"]) == 1:
+            node = spec["type"][0]
+            if isinstance(node, c_ast.Node):
+                decl_type = node
+            else:
+                decl_type = c_ast.IdentifierType(node)
+            self._expect("SEMI")
+            return self._build_declarations(
+                spec=spec, decls=[dict(decl=decl_type, init=None, bitsize=None)]
+            )
+
+        self._expect("SEMI")
+        return self._build_declarations(
+            spec=spec, decls=[dict(decl=None, init=None, bitsize=None)]
+        )
+
+    # BNF: struct_declarator_list : struct_declarator (',' struct_declarator)*
+    def _parse_struct_declarator_list(self) -> List["_DeclInfo"]:
+        decls = [self._parse_struct_declarator()]
+        while self._accept("COMMA"):
+            decls.append(self._parse_struct_declarator())
+        return decls
+
+    # BNF: struct_declarator : declarator? ':' constant_expression
+    #                        | declarator (':' constant_expression)?
+    def _parse_struct_declarator(self) -> "_DeclInfo":
+        if self._accept("COLON"):
+            bitsize = self._parse_constant_expression()
+            return {
+                "decl": c_ast.TypeDecl(None, None, None, None),
+                "init": None,
+                "bitsize": bitsize,
+            }
+
+        decl = self._parse_declarator()
+        if self._accept("COLON"):
+            bitsize = self._parse_constant_expression()
+            return {"decl": decl, "init": None, "bitsize": bitsize}
+
+        return {"decl": decl, "init": None, "bitsize": None}
+
+    # BNF: enum_specifier : ENUM ID? '{' enumerator_list? '}'
+    #                     | ENUM ID
+    def _parse_enum_specifier(self) -> c_ast.Node:
+        tok = self._expect("ENUM")
+        if self._peek_type() in {"ID", "TYPEID"}:
+            name_tok = self._advance()
+            if self._peek_type() == "LBRACE":
+                self._advance()
+                enums = self._parse_enumerator_list()
+                self._expect("RBRACE")
+                return c_ast.Enum(name_tok.value, enums, self._tok_coord(tok))
+            return c_ast.Enum(name_tok.value, None, self._tok_coord(tok))
+
+        self._expect("LBRACE")
+        enums = self._parse_enumerator_list()
+        self._expect("RBRACE")
+        return c_ast.Enum(None, enums, self._tok_coord(tok))
+
+    # BNF: enumerator_list : enumerator (',' enumerator)* ','?
+    def _parse_enumerator_list(self) -> c_ast.Node:
+        enum = self._parse_enumerator()
+        enum_list = c_ast.EnumeratorList([enum], enum.coord)
+        while self._accept("COMMA"):
+            if self._peek_type() == "RBRACE":
+                break
+            enum = self._parse_enumerator()
+            enum_list.enumerators.append(enum)
+        return enum_list
+
+    # BNF: enumerator : ID ('=' constant_expression)?
+    def _parse_enumerator(self) -> c_ast.Node:
+        name_tok = self._expect("ID")
+        if self._accept("EQUALS"):
+            value = self._parse_constant_expression()
+        else:
+            value = None
+        enum = c_ast.Enumerator(name_tok.value, value, self._tok_coord(name_tok))
+        self._add_identifier(enum.name, enum.coord)
+        return enum
+
+    # ------------------------------------------------------------------
+    # Declarators
+    # ------------------------------------------------------------------
+    # BNF: declarator : pointer? direct_declarator
+    def _parse_declarator(self) -> c_ast.Node:
+        decl, _ = self._parse_any_declarator(
+            allow_abstract=False, typeid_paren_as_abstract=False
+        )
+        assert decl is not None
+        return decl
+
+    # BNF: id_declarator : declarator with ID name
+    def _parse_id_declarator(self) -> c_ast.Node:
+        return self._parse_declarator_kind(kind="id", allow_paren=True)
+
+    # BNF: typeid_declarator : declarator with TYPEID name
+    def _parse_typeid_declarator(self) -> c_ast.Node:
+        return self._parse_declarator_kind(kind="typeid", allow_paren=True)
+
+    # BNF: typeid_noparen_declarator : declarator without parenthesized name
+    def _parse_typeid_noparen_declarator(self) -> c_ast.Node:
+        return self._parse_declarator_kind(kind="typeid", allow_paren=False)
+
+    # BNF: declarator_kind : pointer? direct_declarator(kind)
+    def _parse_declarator_kind(self, kind: str, allow_paren: bool) -> c_ast.Node:
+        ptr = None
+        if self._peek_type() == "TIMES":
+            ptr = self._parse_pointer()
+        direct = self._parse_direct_declarator(kind, allow_paren=allow_paren)
+        if ptr is not None:
+            return self._type_modify_decl(direct, ptr)
+        return direct
+
+    # BNF: direct_declarator : ID | TYPEID | '(' declarator ')'
+    #                        | direct_declarator '[' ... ']'
+    #                        | direct_declarator '(' ... ')'
+    def _parse_direct_declarator(
+        self, kind: str, allow_paren: bool = True
+    ) -> c_ast.Node:
+        if allow_paren and self._accept("LPAREN"):
+            decl = self._parse_declarator_kind(kind, allow_paren=True)
+            self._expect("RPAREN")
+        else:
+            if kind == "id":
+                name_tok = self._expect("ID")
+            else:
+                name_tok = self._expect("TYPEID")
+            decl = c_ast.TypeDecl(
+                declname=name_tok.value,
+                type=None,
+                quals=None,
+                align=None,
+                coord=self._tok_coord(name_tok),
+            )
+
+        return self._parse_decl_suffixes(decl)
+
+    def _parse_decl_suffixes(self, decl: c_ast.Node) -> c_ast.Node:
+        """Parse a chain of array/function suffixes and attach them to decl."""
+        while True:
+            if self._peek_type() == "LBRACKET":
+                decl = self._type_modify_decl(decl, self._parse_array_decl(decl))
+                continue
+            if self._peek_type() == "LPAREN":
+                func = self._parse_function_decl(decl)
+                decl = self._type_modify_decl(decl, func)
+                continue
+            break
+        return decl
+
+    # BNF: array_decl : '[' array_specifiers? assignment_expression? ']'
+    def _parse_array_decl(self, base_decl: c_ast.Node) -> c_ast.Node:
+        return self._parse_array_decl_common(base_type=None, coord=base_decl.coord)
+
+    def _parse_array_decl_common(
+        self, base_type: Optional[c_ast.Node], coord: Optional[Coord] = None
+    ) -> c_ast.Node:
+        """Parse an array declarator suffix and return an ArrayDecl node.
+
+        base_type:
+            Base declarator node to attach (None for direct-declarator parsing,
+            TypeDecl for abstract declarators).
+
+        coord:
+            Coordinate to use for the ArrayDecl. If None, uses the '[' token.
+        """
+        lbrack_tok = self._expect("LBRACKET")
+        if coord is None:
+            coord = self._tok_coord(lbrack_tok)
+
+        def make_array_decl(dim, dim_quals):
+            return c_ast.ArrayDecl(
+                type=base_type, dim=dim, dim_quals=dim_quals, coord=coord
+            )
+
+        if self._accept("STATIC"):
+            dim_quals = ["static"] + (self._parse_type_qualifier_list() or [])
+            dim = self._parse_assignment_expression()
+            self._expect("RBRACKET")
+            return make_array_decl(dim, dim_quals)
+
+        if self._peek_type() in _TYPE_QUALIFIER:
+            dim_quals = self._parse_type_qualifier_list() or []
+            if self._accept("STATIC"):
+                dim_quals = dim_quals + ["static"]
+                dim = self._parse_assignment_expression()
+                self._expect("RBRACKET")
+                return make_array_decl(dim, dim_quals)
+            times_tok = self._accept("TIMES")
+            if times_tok:
+                self._expect("RBRACKET")
+                dim = c_ast.ID(times_tok.value, self._tok_coord(times_tok))
+                return make_array_decl(dim, dim_quals)
+            dim = None
+            if self._starts_expression():
+                dim = self._parse_assignment_expression()
+            self._expect("RBRACKET")
+            return make_array_decl(dim, dim_quals)
+
+        times_tok = self._accept("TIMES")
+        if times_tok:
+            self._expect("RBRACKET")
+            dim = c_ast.ID(times_tok.value, self._tok_coord(times_tok))
+            return make_array_decl(dim, [])
+
+        dim = None
+        if self._starts_expression():
+            dim = self._parse_assignment_expression()
+        self._expect("RBRACKET")
+        return make_array_decl(dim, [])
+
+    # BNF: function_decl : '(' parameter_type_list_opt | identifier_list_opt ')'
+    def _parse_function_decl(self, base_decl: c_ast.Node) -> c_ast.Node:
+        self._expect("LPAREN")
+        if self._accept("RPAREN"):
+            args = None
+        else:
+            args = (
+                self._parse_parameter_type_list()
+                if self._starts_declaration()
+                else self._parse_identifier_list_opt()
+            )
+            self._expect("RPAREN")
+
+        func = c_ast.FuncDecl(args=args, type=None, coord=base_decl.coord)
+
+        if self._peek_type() == "LBRACE":
+            if func.args is not None:
+                for param in func.args.params:
+                    if isinstance(param, c_ast.EllipsisParam):
+                        break
+                    name = getattr(param, "name", None)
+                    if name:
+                        self._add_identifier(name, param.coord)
+
+        return func
+
+    # BNF: pointer : '*' type_qualifier_list? pointer?
+    def _parse_pointer(self) -> Optional[c_ast.Node]:
+        stars = []
+        times_tok = self._accept("TIMES")
+        while times_tok:
+            quals = self._parse_type_qualifier_list() or []
+            stars.append((quals, self._tok_coord(times_tok)))
+            times_tok = self._accept("TIMES")
+
+        if not stars:
+            return None
+
+        ptr = None
+        for quals, coord in stars:
+            ptr = c_ast.PtrDecl(quals=quals, type=ptr, coord=coord)
+        return ptr
+
+    # BNF: parameter_type_list : parameter_list (',' ELLIPSIS)?
+    def _parse_parameter_type_list(self) -> c_ast.ParamList:
+        params = self._parse_parameter_list()
+        if self._peek_type() == "COMMA" and self._peek_type(2) == "ELLIPSIS":
+            self._advance()
+            ell_tok = self._advance()
+            params.params.append(c_ast.EllipsisParam(self._tok_coord(ell_tok)))
+        return params
+
+    # BNF: parameter_list : parameter_declaration (',' parameter_declaration)*
+    def _parse_parameter_list(self) -> c_ast.ParamList:
+        first = self._parse_parameter_declaration()
+        params = c_ast.ParamList([first], first.coord)
+        while self._peek_type() == "COMMA" and self._peek_type(2) != "ELLIPSIS":
+            self._advance()
+            params.params.append(self._parse_parameter_declaration())
+        return params
+
+    # BNF: parameter_declaration : declaration_specifiers declarator?
+    #                            | declaration_specifiers abstract_declarator_opt
+    def _parse_parameter_declaration(self) -> c_ast.Node:
+        spec, _, spec_coord = self._parse_declaration_specifiers(allow_no_type=True)
+
+        if not spec["type"]:
+            spec["type"] = [c_ast.IdentifierType(["int"], coord=spec_coord)]
+
+        if self._starts_declarator():
+            decl, is_named = self._parse_any_declarator(
+                allow_abstract=True, typeid_paren_as_abstract=True
+            )
+            if is_named:
+                return self._build_declarations(
+                    spec=spec, decls=[dict(decl=decl, init=None, bitsize=None)]
+                )[0]
+            return self._build_parameter_declaration(spec, decl, spec_coord)
+
+        decl = self._parse_abstract_declarator_opt()
+        return self._build_parameter_declaration(spec, decl, spec_coord)
+
+    def _build_parameter_declaration(
+        self, spec: "_DeclSpec", decl: Optional[c_ast.Node], spec_coord: Optional[Coord]
+    ) -> c_ast.Node:
+        if (
+            len(spec["type"]) > 1
+            and len(spec["type"][-1].names) == 1
+            and self._is_type_in_scope(spec["type"][-1].names[0])
+        ):
+            return self._build_declarations(
+                spec=spec, decls=[dict(decl=decl, init=None, bitsize=None)]
+            )[0]
+
+        decl = c_ast.Typename(
+            name="",
+            quals=spec["qual"],
+            align=None,
+            type=decl or c_ast.TypeDecl(None, None, None, None),
+            coord=spec_coord,
+        )
+        return self._fix_decl_name_type(decl, spec["type"])
+
+    # BNF: identifier_list_opt : identifier_list | empty
+    def _parse_identifier_list_opt(self) -> Optional[c_ast.Node]:
+        if self._peek_type() == "RPAREN":
+            return None
+        return self._parse_identifier_list()
+
+    # BNF: identifier_list : identifier (',' identifier)*
+    def _parse_identifier_list(self) -> c_ast.Node:
+        first = self._parse_identifier()
+        params = c_ast.ParamList([first], first.coord)
+        while self._accept("COMMA"):
+            params.params.append(self._parse_identifier())
+        return params
+
+    # ------------------------------------------------------------------
+    # Abstract declarators
+    # ------------------------------------------------------------------
+    # BNF: type_name : specifier_qualifier_list abstract_declarator_opt
+    def _parse_type_name(self) -> c_ast.Typename:
+        spec = self._parse_specifier_qualifier_list()
+        decl = self._parse_abstract_declarator_opt()
+
+        coord = None
+        if decl is not None:
+            coord = decl.coord
+        elif spec["type"]:
+            coord = spec["type"][0].coord
+
+        typename = c_ast.Typename(
+            name="",
+            quals=spec["qual"][:],
+            align=None,
+            type=decl or c_ast.TypeDecl(None, None, None, None),
+            coord=coord,
+        )
+        return cast(c_ast.Typename, self._fix_decl_name_type(typename, spec["type"]))
+
+    # BNF: abstract_declarator_opt : pointer? direct_abstract_declarator?
+    def _parse_abstract_declarator_opt(self) -> Optional[c_ast.Node]:
+        if self._peek_type() == "TIMES":
+            ptr = self._parse_pointer()
+            if self._starts_direct_abstract_declarator():
+                decl = self._parse_direct_abstract_declarator()
+            else:
+                decl = c_ast.TypeDecl(None, None, None, None)
+            assert ptr is not None
+            return self._type_modify_decl(decl, ptr)
+
+        if self._starts_direct_abstract_declarator():
+            return self._parse_direct_abstract_declarator()
+
+        return None
+
+    # BNF: direct_abstract_declarator : '(' parameter_type_list_opt ')'
+    #                                 | '(' abstract_declarator ')'
+    #                                 | '[' ... ']'
+    def _parse_direct_abstract_declarator(self) -> c_ast.Node:
+        lparen_tok = self._accept("LPAREN")
+        if lparen_tok:
+            if self._starts_declaration() or self._peek_type() == "RPAREN":
+                params = self._parse_parameter_type_list_opt()
+                self._expect("RPAREN")
+                decl = c_ast.FuncDecl(
+                    args=params,
+                    type=c_ast.TypeDecl(None, None, None, None),
+                    coord=self._tok_coord(lparen_tok),
+                )
+            else:
+                decl = self._parse_abstract_declarator_opt()
+                self._expect("RPAREN")
+                assert decl is not None
+        elif self._peek_type() == "LBRACKET":
+            decl = self._parse_abstract_array_base()
+        else:
+            self._parse_error("Invalid abstract declarator", self.clex.filename)
+
+        return self._parse_decl_suffixes(decl)
+
+    # BNF: parameter_type_list_opt : parameter_type_list | empty
+    def _parse_parameter_type_list_opt(self) -> Optional[c_ast.ParamList]:
+        if self._peek_type() == "RPAREN":
+            return None
+        return self._parse_parameter_type_list()
+
+    # BNF: abstract_array_base : '[' array_specifiers? assignment_expression? ']'
+    def _parse_abstract_array_base(self) -> c_ast.Node:
+        return self._parse_array_decl_common(
+            base_type=c_ast.TypeDecl(None, None, None, None), coord=None
+        )
+
+    # ------------------------------------------------------------------
+    # Statements
+    # ------------------------------------------------------------------
+    # BNF: statement : labeled_statement | compound_statement
+    #                | selection_statement | iteration_statement
+    #                | jump_statement | expression_statement
+    #                | static_assert | pppragma_directive
+    def _parse_statement(self) -> c_ast.Node | List[c_ast.Node]:
+        tok_type = self._peek_type()
+        match tok_type:
+            case "CASE" | "DEFAULT":
+                return self._parse_labeled_statement()
+            case "ID" if self._peek_type(2) == "COLON":
+                return self._parse_labeled_statement()
+            case "LBRACE":
+                return self._parse_compound_statement()
+            case "IF" | "SWITCH":
+                return self._parse_selection_statement()
+            case "WHILE" | "DO" | "FOR":
+                return self._parse_iteration_statement()
+            case "GOTO" | "BREAK" | "CONTINUE" | "RETURN":
+                return self._parse_jump_statement()
+            case "PPPRAGMA" | "_PRAGMA":
+                return self._parse_pppragma_directive()
+            case "_STATIC_ASSERT":
+                return self._parse_static_assert()
+            case _:
+                return self._parse_expression_statement()
+
+    # BNF: pragmacomp_or_statement : pppragma_directive* statement
+    def _parse_pragmacomp_or_statement(self) -> c_ast.Node | List[c_ast.Node]:
+        if self._peek_type() in {"PPPRAGMA", "_PRAGMA"}:
+            pragmas = self._parse_pppragma_directive_list()
+            stmt = self._parse_statement()
+            return c_ast.Compound(block_items=pragmas + [stmt], coord=pragmas[0].coord)
+        return self._parse_statement()
+
+    # BNF: block_item : declaration | statement
+    def _parse_block_item(self) -> c_ast.Node | List[c_ast.Node]:
+        if self._starts_declaration():
+            return self._parse_declaration()
+        return self._parse_statement()
+
+    # BNF: block_item_list : block_item+
+    def _parse_block_item_list(self) -> List[c_ast.Node]:
+        items = []
+        while self._peek_type() not in {"RBRACE", None}:
+            item = self._parse_block_item()
+            if isinstance(item, list):
+                if item == [None]:
+                    continue
+                items.extend(item)
+            else:
+                items.append(item)
+        return items
+
+    # BNF: compound_statement : '{' block_item_list? '}'
+    def _parse_compound_statement(self) -> c_ast.Node:
+        lbrace_tok = self._expect("LBRACE")
+        if self._accept("RBRACE"):
+            return c_ast.Compound(block_items=None, coord=self._tok_coord(lbrace_tok))
+        block_items = self._parse_block_item_list()
+        self._expect("RBRACE")
+        return c_ast.Compound(
+            block_items=block_items, coord=self._tok_coord(lbrace_tok)
+        )
+
+    # BNF: labeled_statement : ID ':' statement
+    #                        | CASE constant_expression ':' statement
+    #                        | DEFAULT ':' statement
+    def _parse_labeled_statement(self) -> c_ast.Node:
+        tok_type = self._peek_type()
+        match tok_type:
+            case "ID":
+                name_tok = self._advance()
+                self._expect("COLON")
+                if self._starts_statement():
+                    stmt = self._parse_pragmacomp_or_statement()
+                else:
+                    stmt = c_ast.EmptyStatement(self._tok_coord(name_tok))
+                return c_ast.Label(name_tok.value, stmt, self._tok_coord(name_tok))
+            case "CASE":
+                case_tok = self._advance()
+                expr = self._parse_constant_expression()
+                self._expect("COLON")
+                if self._starts_statement():
+                    stmt = self._parse_pragmacomp_or_statement()
+                else:
+                    stmt = c_ast.EmptyStatement(self._tok_coord(case_tok))
+                return c_ast.Case(expr, [stmt], self._tok_coord(case_tok))
+            case "DEFAULT":
+                def_tok = self._advance()
+                self._expect("COLON")
+                if self._starts_statement():
+                    stmt = self._parse_pragmacomp_or_statement()
+                else:
+                    stmt = c_ast.EmptyStatement(self._tok_coord(def_tok))
+                return c_ast.Default([stmt], self._tok_coord(def_tok))
+            case _:
+                self._parse_error("Invalid labeled statement", self.clex.filename)
+
+    # BNF: selection_statement : IF '(' expression ')' statement (ELSE statement)?
+    #                          | SWITCH '(' expression ')' statement
+    def _parse_selection_statement(self) -> c_ast.Node:
+        tok = self._advance()
+        match tok.type:
+            case "IF":
+                self._expect("LPAREN")
+                cond = self._parse_expression()
+                self._expect("RPAREN")
+                then_stmt = self._parse_pragmacomp_or_statement()
+                if self._accept("ELSE"):
+                    else_stmt = self._parse_pragmacomp_or_statement()
+                    return c_ast.If(cond, then_stmt, else_stmt, self._tok_coord(tok))
+                return c_ast.If(cond, then_stmt, None, self._tok_coord(tok))
+            case "SWITCH":
+                self._expect("LPAREN")
+                expr = self._parse_expression()
+                self._expect("RPAREN")
+                stmt = self._parse_pragmacomp_or_statement()
+                return fix_switch_cases(c_ast.Switch(expr, stmt, self._tok_coord(tok)))
+            case _:
+                self._parse_error("Invalid selection statement", self._tok_coord(tok))
+
+    # BNF: iteration_statement : WHILE '(' expression ')' statement
+    #                          | DO statement WHILE '(' expression ')' ';'
+    #                          | FOR '(' (declaration | expression_opt) ';'
+    #                                 expression_opt ';' expression_opt ')' statement
+    def _parse_iteration_statement(self) -> c_ast.Node:
+        tok = self._advance()
+        match tok.type:
+            case "WHILE":
+                self._expect("LPAREN")
+                cond = self._parse_expression()
+                self._expect("RPAREN")
+                stmt = self._parse_pragmacomp_or_statement()
+                return c_ast.While(cond, stmt, self._tok_coord(tok))
+            case "DO":
+                stmt = self._parse_pragmacomp_or_statement()
+                self._expect("WHILE")
+                self._expect("LPAREN")
+                cond = self._parse_expression()
+                self._expect("RPAREN")
+                self._expect("SEMI")
+                return c_ast.DoWhile(cond, stmt, self._tok_coord(tok))
+            case "FOR":
+                self._expect("LPAREN")
+                if self._starts_declaration():
+                    decls = self._parse_declaration()
+                    init = c_ast.DeclList(decls, self._tok_coord(tok))
+                    cond = self._parse_expression_opt()
+                    self._expect("SEMI")
+                    next_expr = self._parse_expression_opt()
+                    self._expect("RPAREN")
+                    stmt = self._parse_pragmacomp_or_statement()
+                    return c_ast.For(init, cond, next_expr, stmt, self._tok_coord(tok))
+
+                init = self._parse_expression_opt()
+                self._expect("SEMI")
+                cond = self._parse_expression_opt()
+                self._expect("SEMI")
+                next_expr = self._parse_expression_opt()
+                self._expect("RPAREN")
+                stmt = self._parse_pragmacomp_or_statement()
+                return c_ast.For(init, cond, next_expr, stmt, self._tok_coord(tok))
+            case _:
+                self._parse_error("Invalid iteration statement", self._tok_coord(tok))
+
+    # BNF: jump_statement : GOTO ID ';' | BREAK ';' | CONTINUE ';'
+    #                     | RETURN expression? ';'
+    def _parse_jump_statement(self) -> c_ast.Node:
+        tok = self._advance()
+        match tok.type:
+            case "GOTO":
+                name_tok = self._expect("ID")
+                self._expect("SEMI")
+                return c_ast.Goto(name_tok.value, self._tok_coord(tok))
+            case "BREAK":
+                self._expect("SEMI")
+                return c_ast.Break(self._tok_coord(tok))
+            case "CONTINUE":
+                self._expect("SEMI")
+                return c_ast.Continue(self._tok_coord(tok))
+            case "RETURN":
+                if self._accept("SEMI"):
+                    return c_ast.Return(None, self._tok_coord(tok))
+                expr = self._parse_expression()
+                self._expect("SEMI")
+                return c_ast.Return(expr, self._tok_coord(tok))
+            case _:
+                self._parse_error("Invalid jump statement", self._tok_coord(tok))
+
+    # BNF: expression_statement : expression_opt ';'
+    def _parse_expression_statement(self) -> c_ast.Node:
+        expr = self._parse_expression_opt()
+        semi_tok = self._expect("SEMI")
+        if expr is None:
+            return c_ast.EmptyStatement(self._tok_coord(semi_tok))
+        return expr
+
+    # ------------------------------------------------------------------
+    # Expressions
+    # ------------------------------------------------------------------
+    # BNF: expression_opt : expression | empty
+    def _parse_expression_opt(self) -> Optional[c_ast.Node]:
+        if self._starts_expression():
+            return self._parse_expression()
+        return None
+
+    # BNF: expression : assignment_expression (',' assignment_expression)*
+    def _parse_expression(self) -> c_ast.Node:
+        expr = self._parse_assignment_expression()
+        if not self._accept("COMMA"):
+            return expr
+        exprs = [expr, self._parse_assignment_expression()]
+        while self._accept("COMMA"):
+            exprs.append(self._parse_assignment_expression())
+        return c_ast.ExprList(exprs, expr.coord)
+
+    # BNF: assignment_expression : conditional_expression
+    #                            | unary_expression assignment_op assignment_expression
+    def _parse_assignment_expression(self) -> c_ast.Node:
+        if self._peek_type() == "LPAREN" and self._peek_type(2) == "LBRACE":
+            self._advance()
+            comp = self._parse_compound_statement()
+            self._expect("RPAREN")
+            return comp
+
+        expr = self._parse_conditional_expression()
+        if self._is_assignment_op():
+            op = self._advance().value
+            rhs = self._parse_assignment_expression()
+            return c_ast.Assignment(op, expr, rhs, expr.coord)
+        return expr
+
+    # BNF: conditional_expression : binary_expression
+    #                            | binary_expression '?' expression ':' conditional_expression
+    def _parse_conditional_expression(self) -> c_ast.Node:
+        expr = self._parse_binary_expression()
+        if self._accept("CONDOP"):
+            iftrue = self._parse_expression()
+            self._expect("COLON")
+            iffalse = self._parse_conditional_expression()
+            return c_ast.TernaryOp(expr, iftrue, iffalse, expr.coord)
+        return expr
+
+    # BNF: binary_expression : cast_expression (binary_op cast_expression)*
+    def _parse_binary_expression(
+        self, min_prec: int = 0, lhs: Optional[c_ast.Node] = None
+    ) -> c_ast.Node:
+        if lhs is None:
+            lhs = self._parse_cast_expression()
+
+        while True:
+            tok = self._peek()
+            if tok is None or tok.type not in _BINARY_PRECEDENCE:
+                break
+            prec = _BINARY_PRECEDENCE[tok.type]
+            if prec < min_prec:
+                break
+
+            op = tok.value
+            self._advance()
+            rhs = self._parse_cast_expression()
+
+            while True:
+                next_tok = self._peek()
+                if next_tok is None or next_tok.type not in _BINARY_PRECEDENCE:
+                    break
+                next_prec = _BINARY_PRECEDENCE[next_tok.type]
+                if next_prec > prec:
+                    rhs = self._parse_binary_expression(next_prec, rhs)
+                else:
+                    break
+
+            lhs = c_ast.BinaryOp(op, lhs, rhs, lhs.coord)
+
+        return lhs
+
+    # BNF: cast_expression  : '(' type_name ')' cast_expression
+    #                       | unary_expression
+    def _parse_cast_expression(self) -> c_ast.Node:
+        result = self._try_parse_paren_type_name()
+        if result is not None:
+            typ, mark, lparen_tok = result
+            if self._peek_type() == "LBRACE":
+                # (type){...} is a compound literal, not a cast. Examples:
+                #   (int){1}      -> compound literal, handled in postfix
+                #   (int) x       -> cast, handled below
+                self._reset(mark)
+            else:
+                expr = self._parse_cast_expression()
+                return c_ast.Cast(typ, expr, self._tok_coord(lparen_tok))
+        return self._parse_unary_expression()
+
+    # BNF: unary_expression : postfix_expression
+    #                       | '++' unary_expression
+    #                       | '--' unary_expression
+    #                       | unary_op cast_expression
+    #                       | 'sizeof' unary_expression
+    #                       | 'sizeof' '(' type_name ')'
+    #                       | '_Alignof' '(' type_name ')'
+    def _parse_unary_expression(self) -> c_ast.Node:
+        tok_type = self._peek_type()
+        if tok_type in {"PLUSPLUS", "MINUSMINUS"}:
+            tok = self._advance()
+            expr = self._parse_unary_expression()
+            return c_ast.UnaryOp(tok.value, expr, expr.coord)
+
+        if tok_type in {"AND", "TIMES", "PLUS", "MINUS", "NOT", "LNOT"}:
+            tok = self._advance()
+            expr = self._parse_cast_expression()
+            return c_ast.UnaryOp(tok.value, expr, expr.coord)
+
+        if tok_type == "SIZEOF":
+            tok = self._advance()
+            result = self._try_parse_paren_type_name()
+            if result is not None:
+                typ, _, _ = result
+                return c_ast.UnaryOp(tok.value, typ, self._tok_coord(tok))
+            expr = self._parse_unary_expression()
+            return c_ast.UnaryOp(tok.value, expr, self._tok_coord(tok))
+
+        if tok_type == "_ALIGNOF":
+            tok = self._advance()
+            self._expect("LPAREN")
+            typ = self._parse_type_name()
+            self._expect("RPAREN")
+            return c_ast.UnaryOp(tok.value, typ, self._tok_coord(tok))
+
+        return self._parse_postfix_expression()
+
+    # BNF: postfix_expression   : primary_expression postfix_suffix*
+    #                           | '(' type_name ')' '{' initializer_list ','? '}'
+    def _parse_postfix_expression(self) -> c_ast.Node:
+        result = self._try_parse_paren_type_name()
+        if result is not None:
+            typ, mark, _ = result
+            # Disambiguate between casts and compound literals:
+            #   (int) x   -> cast
+            #   (int) {1} -> compound literal
+            if self._accept("LBRACE"):
+                init = self._parse_initializer_list()
+                self._accept("COMMA")
+                self._expect("RBRACE")
+                return c_ast.CompoundLiteral(typ, init)
+            else:
+                self._reset(mark)
+
+        expr = self._parse_primary_expression()
+        while True:
+            if self._accept("LBRACKET"):
+                sub = self._parse_expression()
+                self._expect("RBRACKET")
+                expr = c_ast.ArrayRef(expr, sub, expr.coord)
+                continue
+            if self._accept("LPAREN"):
+                if self._peek_type() == "RPAREN":
+                    self._advance()
+                    args = None
+                else:
+                    args = self._parse_argument_expression_list()
+                    self._expect("RPAREN")
+                expr = c_ast.FuncCall(expr, args, expr.coord)
+                continue
+            if self._peek_type() in {"PERIOD", "ARROW"}:
+                op_tok = self._advance()
+                name_tok = self._advance()
+                if name_tok.type not in {"ID", "TYPEID"}:
+                    self._parse_error(
+                        "Invalid struct reference", self._tok_coord(name_tok)
+                    )
+                field = c_ast.ID(name_tok.value, self._tok_coord(name_tok))
+                expr = c_ast.StructRef(expr, op_tok.value, field, expr.coord)
+                continue
+            if self._peek_type() in {"PLUSPLUS", "MINUSMINUS"}:
+                tok = self._advance()
+                expr = c_ast.UnaryOp("p" + tok.value, expr, expr.coord)
+                continue
+            break
+        return expr
+
+    # BNF: primary_expression : ID | constant | string_literal
+    #                        | '(' expression ')' | offsetof
+    def _parse_primary_expression(self) -> c_ast.Node:
+        tok_type = self._peek_type()
+        if tok_type == "ID":
+            return self._parse_identifier()
+        if (
+            tok_type in _INT_CONST
+            or tok_type in _FLOAT_CONST
+            or tok_type in _CHAR_CONST
+        ):
+            return self._parse_constant()
+        if tok_type in _STRING_LITERAL:
+            return self._parse_unified_string_literal()
+        if tok_type in _WSTR_LITERAL:
+            return self._parse_unified_wstring_literal()
+        if tok_type == "LPAREN":
+            self._advance()
+            expr = self._parse_expression()
+            self._expect("RPAREN")
+            return expr
+        if tok_type == "OFFSETOF":
+            off_tok = self._advance()
+            self._expect("LPAREN")
+            typ = self._parse_type_name()
+            self._expect("COMMA")
+            designator = self._parse_offsetof_member_designator()
+            self._expect("RPAREN")
+            coord = self._tok_coord(off_tok)
+            return c_ast.FuncCall(
+                c_ast.ID(off_tok.value, coord),
+                c_ast.ExprList([typ, designator], coord),
+                coord,
+            )
+
+        self._parse_error("Invalid expression", self.clex.filename)
+
+    # BNF: offsetof_member_designator : identifier_or_typeid
+    #                                ('.' identifier_or_typeid | '[' expression ']')*
+    def _parse_offsetof_member_designator(self) -> c_ast.Node:
+        node = self._parse_identifier_or_typeid()
+        while True:
+            if self._accept("PERIOD"):
+                field = self._parse_identifier_or_typeid()
+                node = c_ast.StructRef(node, ".", field, node.coord)
+                continue
+            if self._accept("LBRACKET"):
+                expr = self._parse_expression()
+                self._expect("RBRACKET")
+                node = c_ast.ArrayRef(node, expr, node.coord)
+                continue
+            break
+        return node
+
+    # BNF: argument_expression_list : assignment_expression (',' assignment_expression)*
+    def _parse_argument_expression_list(self) -> c_ast.Node:
+        expr = self._parse_assignment_expression()
+        exprs = [expr]
+        while self._accept("COMMA"):
+            exprs.append(self._parse_assignment_expression())
+        return c_ast.ExprList(exprs, expr.coord)
+
+    # BNF: constant_expression : conditional_expression
+    def _parse_constant_expression(self) -> c_ast.Node:
+        return self._parse_conditional_expression()
+
+    # ------------------------------------------------------------------
+    # Terminals
+    # ------------------------------------------------------------------
+    # BNF: identifier : ID
+    def _parse_identifier(self) -> c_ast.Node:
+        tok = self._expect("ID")
+        return c_ast.ID(tok.value, self._tok_coord(tok))
+
+    # BNF: identifier_or_typeid : ID | TYPEID
+    def _parse_identifier_or_typeid(self) -> c_ast.Node:
+        tok = self._advance()
+        if tok.type not in {"ID", "TYPEID"}:
+            self._parse_error("Expected identifier", self._tok_coord(tok))
+        return c_ast.ID(tok.value, self._tok_coord(tok))
+
+    # BNF: constant : INT_CONST | FLOAT_CONST | CHAR_CONST
+    def _parse_constant(self) -> c_ast.Node:
+        tok = self._advance()
+        if tok.type in _INT_CONST:
+            u_count = 0
+            l_count = 0
+            for ch in tok.value[-3:]:
+                if ch in ("l", "L"):
+                    l_count += 1
+                elif ch in ("u", "U"):
+                    u_count += 1
+            if u_count > 1:
+                raise ValueError("Constant cannot have more than one u/U suffix.")
+            if l_count > 2:
+                raise ValueError("Constant cannot have more than two l/L suffix.")
+            prefix = "unsigned " * u_count + "long " * l_count
+            return c_ast.Constant(prefix + "int", tok.value, self._tok_coord(tok))
+
+        if tok.type in _FLOAT_CONST:
+            if tok.value[-1] in ("f", "F"):
+                t = "float"
+            elif tok.value[-1] in ("l", "L"):
+                t = "long double"
+            else:
+                t = "double"
+            return c_ast.Constant(t, tok.value, self._tok_coord(tok))
+
+        if tok.type in _CHAR_CONST:
+            return c_ast.Constant("char", tok.value, self._tok_coord(tok))
+
+        self._parse_error("Invalid constant", self._tok_coord(tok))
+
+    # BNF: unified_string_literal : STRING_LITERAL+
+    def _parse_unified_string_literal(self) -> c_ast.Node:
+        tok = self._expect("STRING_LITERAL")
+        node = c_ast.Constant("string", tok.value, self._tok_coord(tok))
+        while self._peek_type() == "STRING_LITERAL":
+            tok2 = self._advance()
+            node.value = node.value[:-1] + tok2.value[1:]
+        return node
+
+    # BNF: unified_wstring_literal : WSTRING_LITERAL+
+    def _parse_unified_wstring_literal(self) -> c_ast.Node:
+        tok = self._advance()
+        if tok.type not in _WSTR_LITERAL:
+            self._parse_error("Invalid string literal", self._tok_coord(tok))
+        node = c_ast.Constant("string", tok.value, self._tok_coord(tok))
+        while self._peek_type() in _WSTR_LITERAL:
+            tok2 = self._advance()
+            node.value = node.value.rstrip()[:-1] + tok2.value[2:]
+        return node
+
+    # ------------------------------------------------------------------
+    # Initializers
+    # ------------------------------------------------------------------
+    # BNF: initializer : assignment_expression
+    #                 | '{' initializer_list ','? '}'
+    #                 | '{' '}'
+    def _parse_initializer(self) -> c_ast.Node:
+        lbrace_tok = self._accept("LBRACE")
+        if lbrace_tok:
+            if self._accept("RBRACE"):
+                return c_ast.InitList([], self._tok_coord(lbrace_tok))
+            init_list = self._parse_initializer_list()
+            self._accept("COMMA")
+            self._expect("RBRACE")
+            return init_list
+
+        return self._parse_assignment_expression()
+
+    # BNF: initializer_list : initializer_item (',' initializer_item)* ','?
+    def _parse_initializer_list(self) -> c_ast.Node:
+        items = [self._parse_initializer_item()]
+        while self._accept("COMMA"):
+            if self._peek_type() == "RBRACE":
+                break
+            items.append(self._parse_initializer_item())
+        return c_ast.InitList(items, items[0].coord)
+
+    # BNF: initializer_item : designation? initializer
+    def _parse_initializer_item(self) -> c_ast.Node:
+        designation = None
+        if self._peek_type() in {"LBRACKET", "PERIOD"}:
+            designation = self._parse_designation()
+        init = self._parse_initializer()
+        if designation is not None:
+            return c_ast.NamedInitializer(designation, init)
+        return init
+
+    # BNF: designation : designator_list '='
+    def _parse_designation(self) -> List[c_ast.Node]:
+        designators = self._parse_designator_list()
+        self._expect("EQUALS")
+        return designators
+
+    # BNF: designator_list : designator+
+    def _parse_designator_list(self) -> List[c_ast.Node]:
+        designators = []
+        while self._peek_type() in {"LBRACKET", "PERIOD"}:
+            designators.append(self._parse_designator())
+        return designators
+
+    # BNF: designator : '[' constant_expression ']'
+    #                | '.' identifier_or_typeid
+    def _parse_designator(self) -> c_ast.Node:
+        if self._accept("LBRACKET"):
+            expr = self._parse_constant_expression()
+            self._expect("RBRACKET")
+            return expr
+        if self._accept("PERIOD"):
+            return self._parse_identifier_or_typeid()
+        self._parse_error("Invalid designator", self.clex.filename)
+
+    # ------------------------------------------------------------------
+    # Preprocessor-like directives
+    # ------------------------------------------------------------------
+    # BNF: pp_directive : '#' ... (unsupported)
+    def _parse_pp_directive(self) -> NoReturn:
+        tok = self._expect("PPHASH")
+        self._parse_error("Directives not supported yet", self._tok_coord(tok))
+
+    # BNF: pppragma_directive : PPPRAGMA PPPRAGMASTR?
+    #                        | _PRAGMA '(' string_literal ')'
+    def _parse_pppragma_directive(self) -> c_ast.Node:
+        if self._peek_type() == "PPPRAGMA":
+            tok = self._advance()
+            if self._peek_type() == "PPPRAGMASTR":
+                str_tok = self._advance()
+                return c_ast.Pragma(str_tok.value, self._tok_coord(str_tok))
+            return c_ast.Pragma("", self._tok_coord(tok))
+
+        if self._peek_type() == "_PRAGMA":
+            tok = self._advance()
+            lparen = self._expect("LPAREN")
+            literal = self._parse_unified_string_literal()
+            self._expect("RPAREN")
+            return c_ast.Pragma(literal, self._tok_coord(lparen))
+
+        self._parse_error("Invalid pragma", self.clex.filename)
+
+    # BNF: pppragma_directive_list : pppragma_directive+
+    def _parse_pppragma_directive_list(self) -> List[c_ast.Node]:
+        pragmas = []
+        while self._peek_type() in {"PPPRAGMA", "_PRAGMA"}:
+            pragmas.append(self._parse_pppragma_directive())
+        return pragmas
+
+    # BNF: static_assert : _STATIC_ASSERT '(' constant_expression (',' string_literal)? ')'
+    def _parse_static_assert(self) -> List[c_ast.Node]:
+        tok = self._expect("_STATIC_ASSERT")
+        self._expect("LPAREN")
+        cond = self._parse_constant_expression()
+        msg = None
+        if self._accept("COMMA"):
+            msg = self._parse_unified_string_literal()
+        self._expect("RPAREN")
+        return [c_ast.StaticAssert(cond, msg, self._tok_coord(tok))]
+
+
+_ASSIGNMENT_OPS = {
+    "EQUALS",
+    "XOREQUAL",
+    "TIMESEQUAL",
+    "DIVEQUAL",
+    "MODEQUAL",
+    "PLUSEQUAL",
+    "MINUSEQUAL",
+    "LSHIFTEQUAL",
+    "RSHIFTEQUAL",
+    "ANDEQUAL",
+    "OREQUAL",
+}
+
+# Precedence of operators (lower number = weather binding)
+# If this changes, c_generator.CGenerator.precedence_map needs to change as
+# well
+_BINARY_PRECEDENCE = {
+    "LOR": 0,
+    "LAND": 1,
+    "OR": 2,
+    "XOR": 3,
+    "AND": 4,
+    "EQ": 5,
+    "NE": 5,
+    "GT": 6,
+    "GE": 6,
+    "LT": 6,
+    "LE": 6,
+    "RSHIFT": 7,
+    "LSHIFT": 7,
+    "PLUS": 8,
+    "MINUS": 8,
+    "TIMES": 9,
+    "DIVIDE": 9,
+    "MOD": 9,
+}
+
+_STORAGE_CLASS = {"AUTO", "REGISTER", "STATIC", "EXTERN", "TYPEDEF", "_THREAD_LOCAL"}
+
+_FUNCTION_SPEC = {"INLINE", "_NORETURN"}
+
+_TYPE_QUALIFIER = {"CONST", "RESTRICT", "VOLATILE", "_ATOMIC"}
+
+_TYPE_SPEC_SIMPLE = {
+    "VOID",
+    "_BOOL",
+    "CHAR",
+    "SHORT",
+    "INT",
+    "LONG",
+    "FLOAT",
+    "DOUBLE",
+    "_COMPLEX",
+    "SIGNED",
+    "UNSIGNED",
+    "__INT128",
+}
+
+_DECL_START = (
+    _STORAGE_CLASS
+    | _FUNCTION_SPEC
+    | _TYPE_QUALIFIER
+    | _TYPE_SPEC_SIMPLE
+    | {"TYPEID", "STRUCT", "UNION", "ENUM", "_ALIGNAS", "_ATOMIC"}
+)
+
+_EXPR_START = {
+    "ID",
+    "LPAREN",
+    "PLUSPLUS",
+    "MINUSMINUS",
+    "PLUS",
+    "MINUS",
+    "TIMES",
+    "AND",
+    "NOT",
+    "LNOT",
+    "SIZEOF",
+    "_ALIGNOF",
+    "OFFSETOF",
+}
+
+_INT_CONST = {
+    "INT_CONST_DEC",
+    "INT_CONST_OCT",
+    "INT_CONST_HEX",
+    "INT_CONST_BIN",
+    "INT_CONST_CHAR",
+}
+
+_FLOAT_CONST = {"FLOAT_CONST", "HEX_FLOAT_CONST"}
+
+_CHAR_CONST = {
+    "CHAR_CONST",
+    "WCHAR_CONST",
+    "U8CHAR_CONST",
+    "U16CHAR_CONST",
+    "U32CHAR_CONST",
+}
+
+_STRING_LITERAL = {"STRING_LITERAL"}
+
+_WSTR_LITERAL = {
+    "WSTRING_LITERAL",
+    "U8STRING_LITERAL",
+    "U16STRING_LITERAL",
+    "U32STRING_LITERAL",
+}
+
+_STARTS_EXPRESSION = (
+    _EXPR_START
+    | _INT_CONST
+    | _FLOAT_CONST
+    | _CHAR_CONST
+    | _STRING_LITERAL
+    | _WSTR_LITERAL
+)
+
+_STARTS_STATEMENT = {
+    "LBRACE",
+    "IF",
+    "SWITCH",
+    "WHILE",
+    "DO",
+    "FOR",
+    "GOTO",
+    "BREAK",
+    "CONTINUE",
+    "RETURN",
+    "CASE",
+    "DEFAULT",
+    "PPPRAGMA",
+    "_PRAGMA",
+    "_STATIC_ASSERT",
+    "SEMI",
+}
+
+
+class _TokenStream:
+    """Wraps a lexer to provide convenient, buffered access to the underlying
+    token stream. The lexer is expected to be initialized with the input
+    string already.
+    """
+
+    def __init__(self, lexer: CLexer) -> None:
+        self._lexer = lexer
+        self._buffer: List[Optional[_Token]] = []
+        self._index = 0
+
+    def peek(self, k: int = 1) -> Optional[_Token]:
+        """Peek at the k-th next token in the stream, without consuming it.
+
+        Examples:
+            k=1 returns the immediate next token.
+            k=2 returns the token after that.
+        """
+        if k <= 0:
+            return None
+        self._fill(k)
+        return self._buffer[self._index + k - 1]
+
+    def next(self) -> Optional[_Token]:
+        """Consume a single token and return it."""
+        self._fill(1)
+        tok = self._buffer[self._index]
+        self._index += 1
+        return tok
+
+    # The 'mark' and 'reset' methods are useful for speculative parsing with
+    # backtracking; when the parser needs to examine a sequence of tokens
+    # and potentially decide to try a different path on the same sequence, it
+    # can call 'mark' to obtain the current token position, and if the first
+    # path fails restore the position with `reset(pos)`.
+    def mark(self) -> int:
+        return self._index
+
+    def reset(self, mark: int) -> None:
+        self._index = mark
+
+    def _fill(self, n: int) -> None:
+        while len(self._buffer) < self._index + n:
+            tok = self._lexer.token()
+            self._buffer.append(tok)
+            if tok is None:
+                break
+
+
+# Declaration specifiers are represented by a dictionary with entries:
+# - qual: a list of type qualifiers
+# - storage: a list of storage class specifiers
+# - type: a list of type specifiers
+# - function: a list of function specifiers
+# - alignment: a list of alignment specifiers
+class _DeclSpec(TypedDict):
+    qual: List[Any]
+    storage: List[Any]
+    type: List[Any]
+    function: List[Any]
+    alignment: List[Any]
+
+
+_DeclSpecKind = Literal["qual", "storage", "type", "function", "alignment"]
+
+
+class _DeclInfo(TypedDict):
+    # Declarator payloads used by declaration/initializer parsing:
+    # - decl: the declarator node (may be None for abstract/implicit cases)
+    # - init: optional initializer expression
+    # - bitsize: optional bit-field width expression (for struct declarators)
+    decl: Optional[c_ast.Node]
+    init: Optional[c_ast.Node]
+    bitsize: Optional[c_ast.Node]
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pydantic-2.12.5.dist-info/INSTALLER b/TTS/Kokoro/.venv/Lib/site-packages/pydantic-2.12.5.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pydantic-2.12.5.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pydantic-2.12.5.dist-info/METADATA b/TTS/Kokoro/.venv/Lib/site-packages/pydantic-2.12.5.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..fe0df088bbe5a23a6fb249198892e83ed8167830
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pydantic-2.12.5.dist-info/METADATA
@@ -0,0 +1,1029 @@
+Metadata-Version: 2.4
+Name: pydantic
+Version: 2.12.5
+Summary: Data validation using Python type hints
+Project-URL: Homepage, https://github.com/pydantic/pydantic
+Project-URL: Documentation, https://docs.pydantic.dev
+Project-URL: Funding, https://github.com/sponsors/samuelcolvin
+Project-URL: Source, https://github.com/pydantic/pydantic
+Project-URL: Changelog, https://docs.pydantic.dev/latest/changelog/
+Author-email: Samuel Colvin , Eric Jolibois , Hasan Ramezani , Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com>, Terrence Dorsey , David Montague , Serge Matveenko , Marcelo Trylesinski , Sydney Runkle , David Hewitt , Alex Hall , Victorien Plot , Douwe Maan 
+License-Expression: MIT
+License-File: LICENSE
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Framework :: Hypothesis
+Classifier: Framework :: Pydantic
+Classifier: Intended Audience :: Developers
+Classifier: Intended Audience :: Information Technology
+Classifier: Operating System :: OS Independent
+Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3 :: Only
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Classifier: Programming Language :: Python :: 3.13
+Classifier: Programming Language :: Python :: 3.14
+Classifier: Programming Language :: Python :: Implementation :: CPython
+Classifier: Programming Language :: Python :: Implementation :: PyPy
+Classifier: Topic :: Internet
+Classifier: Topic :: Software Development :: Libraries :: Python Modules
+Requires-Python: >=3.9
+Requires-Dist: annotated-types>=0.6.0
+Requires-Dist: pydantic-core==2.41.5
+Requires-Dist: typing-extensions>=4.14.1
+Requires-Dist: typing-inspection>=0.4.2
+Provides-Extra: email
+Requires-Dist: email-validator>=2.0.0; extra == 'email'
+Provides-Extra: timezone
+Requires-Dist: tzdata; (python_version >= '3.9' and platform_system == 'Windows') and extra == 'timezone'
+Description-Content-Type: text/markdown
+
+# Pydantic Validation
+
+[![CI](https://img.shields.io/github/actions/workflow/status/pydantic/pydantic/ci.yml?branch=main&logo=github&label=CI)](https://github.com/pydantic/pydantic/actions?query=event%3Apush+branch%3Amain+workflow%3ACI)
+[![Coverage](https://coverage-badge.samuelcolvin.workers.dev/pydantic/pydantic.svg)](https://coverage-badge.samuelcolvin.workers.dev/redirect/pydantic/pydantic)
+[![pypi](https://img.shields.io/pypi/v/pydantic.svg)](https://pypi.python.org/pypi/pydantic)
+[![CondaForge](https://img.shields.io/conda/v/conda-forge/pydantic.svg)](https://anaconda.org/conda-forge/pydantic)
+[![downloads](https://static.pepy.tech/badge/pydantic/month)](https://pepy.tech/project/pydantic)
+[![versions](https://img.shields.io/pypi/pyversions/pydantic.svg)](https://github.com/pydantic/pydantic)
+[![license](https://img.shields.io/github/license/pydantic/pydantic.svg)](https://github.com/pydantic/pydantic/blob/main/LICENSE)
+[![Pydantic v2](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/pydantic/pydantic/main/docs/badge/v2.json)](https://docs.pydantic.dev/latest/contributing/#badges)
+[![llms.txt](https://img.shields.io/badge/llms.txt-green)](https://docs.pydantic.dev/latest/llms.txt)
+
+Data validation using Python type hints.
+
+Fast and extensible, Pydantic plays nicely with your linters/IDE/brain.
+Define how data should be in pure, canonical Python 3.9+; validate it with Pydantic.
+
+## Pydantic Logfire :fire:
+
+We've recently launched Pydantic Logfire to help you monitor your applications.
+[Learn more](https://pydantic.dev/articles/logfire-announcement)
+
+## Pydantic V1.10 vs. V2
+
+Pydantic V2 is a ground-up rewrite that offers many new features, performance improvements, and some breaking changes compared to Pydantic V1.
+
+If you're using Pydantic V1 you may want to look at the
+[pydantic V1.10 Documentation](https://docs.pydantic.dev/) or,
+[`1.10.X-fixes` git branch](https://github.com/pydantic/pydantic/tree/1.10.X-fixes). Pydantic V2 also ships with the latest version of Pydantic V1 built in so that you can incrementally upgrade your code base and projects: `from pydantic import v1 as pydantic_v1`.
+
+## Help
+
+See [documentation](https://docs.pydantic.dev/) for more details.
+
+## Installation
+
+Install using `pip install -U pydantic` or `conda install pydantic -c conda-forge`.
+For more installation options to make Pydantic even faster,
+see the [Install](https://docs.pydantic.dev/install/) section in the documentation.
+
+## A Simple Example
+
+```python
+from datetime import datetime
+from typing import Optional
+from pydantic import BaseModel
+
+class User(BaseModel):
+    id: int
+    name: str = 'John Doe'
+    signup_ts: Optional[datetime] = None
+    friends: list[int] = []
+
+external_data = {'id': '123', 'signup_ts': '2017-06-01 12:22', 'friends': [1, '2', b'3']}
+user = User(**external_data)
+print(user)
+#> User id=123 name='John Doe' signup_ts=datetime.datetime(2017, 6, 1, 12, 22) friends=[1, 2, 3]
+print(user.id)
+#> 123
+```
+
+## Contributing
+
+For guidance on setting up a development environment and how to make a
+contribution to Pydantic, see
+[Contributing to Pydantic](https://docs.pydantic.dev/contributing/).
+
+## Reporting a Security Vulnerability
+
+See our [security policy](https://github.com/pydantic/pydantic/security/policy).
+
+## Changelog
+
+
+
+
+
+## v2.12.5 (2025-11-26)
+
+[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.12.5)
+
+This is the fifth 2.12 patch release, addressing an issue with the `MISSING` sentinel and providing several documentation improvements.
+
+The next 2.13 minor release will be published in a couple weeks, and will include a new *polymorphic serialization* feature addressing
+the remaining unexpected changes to the *serialize as any* behavior.
+
+* Fix pickle error when using `model_construct()` on a model with `MISSING` as a default value by [@ornariece](https://github.com/ornariece) in [#12522](https://github.com/pydantic/pydantic/pull/12522).
+* Several updates to the documentation by [@Viicos](https://github.com/Viicos).
+
+## v2.12.4 (2025-11-05)
+
+[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.12.4)
+
+This is the fourth 2.12 patch release, fixing more regressions, and reverting a change in the `build()` method
+of the [`AnyUrl` and Dsn types](https://docs.pydantic.dev/latest/api/networks/).
+
+This patch release also fixes an issue with the serialization of IP address types, when `serialize_as_any` is used. The next patch release
+will try to address the remaining issues with *serialize as any* behavior by introducing a new *polymorphic serialization* feature, that
+should be used in most cases in place of *serialize as any*.
+
+* Fix issue with forward references in parent `TypedDict` classes by [@Viicos](https://github.com/Viicos) in [#12427](https://github.com/pydantic/pydantic/pull/12427).
+
+    This issue is only relevant on Python 3.14 and greater.
+* Exclude fields with `exclude_if` from JSON Schema required fields by [@Viicos](https://github.com/Viicos) in [#12430](https://github.com/pydantic/pydantic/pull/12430)
+* Revert URL percent-encoding of credentials in the `build()` method
+  of the [`AnyUrl` and Dsn types](https://docs.pydantic.dev/latest/api/networks/) by [@davidhewitt](https://github.com/davidhewitt) in
+  [pydantic-core#1833](https://github.com/pydantic/pydantic-core/pull/1833).
+
+    This was initially considered as a bugfix, but caused regressions and as such was fully reverted. The next release will include
+    an opt-in option to percent-encode components of the URL.
+* Add type inference for IP address types by [@davidhewitt](https://github.com/davidhewitt) in [pydantic-core#1868](https://github.com/pydantic/pydantic-core/pull/1868).
+
+    The 2.12 changes to the `serialize_as_any` behavior made it so that IP address types could not properly serialize to JSON.
+* Avoid getting default values from defaultdict by [@davidhewitt](https://github.com/davidhewitt) in [pydantic-core#1853](https://github.com/pydantic/pydantic-core/pull/1853).
+
+    This fixes a subtle regression in the validation behavior of the [`collections.defaultdict`](https://docs.python.org/3/library/collections.html#collections.defaultdict)
+    type.
+* Fix issue with field serializers on nested typed dictionaries by [@davidhewitt](https://github.com/davidhewitt) in [pydantic-core#1879](https://github.com/pydantic/pydantic-core/pull/1879).
+* Add more `pydantic-core` builds for the three-threaded version of Python 3.14 by [@davidhewitt](https://github.com/davidhewitt) in [pydantic-core#1864](https://github.com/pydantic/pydantic-core/pull/1864).
+
+## v2.12.3 (2025-10-17)
+
+[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.12.3)
+
+### What's Changed
+
+This is the third 2.12 patch release, fixing issues related to the `FieldInfo` class, and reverting a change to the supported
+[*after* model validator](https://docs.pydantic.dev/latest/concepts/validators/#model-validators) function signatures.
+
+* Raise a warning when an invalid after model validator function signature is raised by [@Viicos](https://github.com/Viicos) in [#12414](https://github.com/pydantic/pydantic/pull/12414).
+  Starting in 2.12.0, using class methods for *after* model validators raised an error, but the error wasn't raised concistently. We decided
+  to emit a deprecation warning instead.
+* Add [`FieldInfo.asdict()`](https://docs.pydantic.dev/latest/api/fields/#pydantic.fields.FieldInfo.asdict) method, improve documentation around `FieldInfo` by [@Viicos](https://github.com/Viicos) in [#12411](https://github.com/pydantic/pydantic/pull/12411).
+  This also add back support for mutations on `FieldInfo` classes, that are reused as `Annotated` metadata. **However**, note that this is still
+  *not* a supported pattern. Instead, please refer to the [added example](https://docs.pydantic.dev/latest/examples/dynamic_models/) in the documentation.
+
+The [blog post](https://pydantic.dev/articles/pydantic-v2-12-release#changes) section on changes was also updated to document the changes related to `serialize_as_any`.
+
+## v2.12.2 (2025-10-14)
+
+[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.12.2)
+
+### What's Changed
+
+#### Fixes
+
+* Release a new `pydantic-core` version, as a corrupted CPython 3.10 `manylinux2014_aarch64` wheel got uploaded ([pydantic-core#1843](https://github.com/pydantic/pydantic-core/pull/1843)).
+* Fix issue with recursive generic models with a parent model class by [@Viicos](https://github.com/Viicos) in [#12398](https://github.com/pydantic/pydantic/pull/12398)
+
+## v2.12.1 (2025-10-13)
+
+[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.12.1)
+
+### What's Changed
+
+This is the first 2.12 patch release, addressing most (but not all yet) regressions from the initial 2.12.0 release.
+
+#### Fixes
+
+* Do not evaluate annotations when inspecting validators and serializers by [@Viicos](https://github.com/Viicos) in [#12355](https://github.com/pydantic/pydantic/pull/12355)
+* Make sure `None` is converted as `NoneType` in Python 3.14 by [@Viicos](https://github.com/Viicos) in [#12370](https://github.com/pydantic/pydantic/pull/12370)
+* Backport V1 runtime warning when using Python 3.14 by [@Viicos](https://github.com/Viicos) in [#12367](https://github.com/pydantic/pydantic/pull/12367)
+* Fix error message for invalid validator signatures by [@Viicos](https://github.com/Viicos) in [#12366](https://github.com/pydantic/pydantic/pull/12366)
+* Populate field name in `ValidationInfo` for validation of default value by [@Viicos](https://github.com/Viicos) in [pydantic-core#1826](https://github.com/pydantic/pydantic-core/pull/1826)
+* Encode credentials in `MultiHostUrl` builder by [@willswire](https://github.com/willswire) in [pydantic-core#1829](https://github.com/pydantic/pydantic-core/pull/1829)
+* Respect field serializers when using `serialize_as_any` serialization flag by [@davidhewitt](https://github.com/davidhewitt) in [pydantic-core#1829](https://github.com/pydantic/pydantic-core/pull/1829)
+* Fix various `RootModel` serialization issues by [@davidhewitt](https://github.com/davidhewitt) in [pydantic-core#1836](https://github.com/pydantic/pydantic-core/pull/1836)
+
+### New Contributors
+
+* [@willswire](https://github.com/willswire) made their first contribution in [pydantic-core#1829](https://github.com/pydantic/pydantic-core/pull/1829)
+
+## v2.12.0 (2025-10-07)
+
+[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.12.0)
+
+### What's Changed
+
+This is the final 2.12 release. It features the work of 20 external contributors and provides useful new features, along with initial Python 3.14 support.
+Several minor changes (considered non-breaking changes according to our [versioning policy](https://docs.pydantic.dev/2.12/version-policy/#pydantic-v2))
+are also included in this release. Make sure to look into them before upgrading.
+
+**Note that Pydantic V1 is not compatible with Python 3.14 and greater**.
+
+Changes (see the alpha and beta releases for additional changes since 2.11):
+
+#### Packaging
+
+* Update V1 copy to v1.10.24 by [@Viicos](https://github.com/Viicos) in [#12338](https://github.com/pydantic/pydantic/pull/12338)
+
+#### New Features
+
+* Add `extra` parameter to the validate functions by [@anvilpete](https://github.com/anvilpete) in [#12233](https://github.com/pydantic/pydantic/pull/12233)
+* Add `exclude_computed_fields` serialization option by [@Viicos](https://github.com/Viicos) in [#12334](https://github.com/pydantic/pydantic/pull/12334)
+* Add `preverse_empty_path` URL options by [@Viicos](https://github.com/Viicos) in [#12336](https://github.com/pydantic/pydantic/pull/12336)
+* Add `union_format` parameter to JSON Schema generation by [@Viicos](https://github.com/Viicos) in [#12147](https://github.com/pydantic/pydantic/pull/12147)
+* Add `__qualname__` parameter for `create_model` by [@Atry](https://github.com/Atry) in [#12001](https://github.com/pydantic/pydantic/pull/12001)
+
+#### Fixes
+
+* Do not try to infer name from lambda definitions in pipelines API by [@Viicos](https://github.com/Viicos) in [#12289](https://github.com/pydantic/pydantic/pull/12289)
+* Use proper namespace for functions in `TypeAdapter` by [@Viicos](https://github.com/Viicos) in [#12324](https://github.com/pydantic/pydantic/pull/12324)
+* Use `Any` for context type annotation in `TypeAdapter` by [@inducer](https://github.com/inducer) in [#12279](https://github.com/pydantic/pydantic/pull/12279)
+* Expose `FieldInfo` in `pydantic.fields.__all__` by [@Viicos](https://github.com/Viicos) in [#12339](https://github.com/pydantic/pydantic/pull/12339)
+* Respect `validation_alias` in `@validate_call` by [@Viicos](https://github.com/Viicos) in [#12340](https://github.com/pydantic/pydantic/pull/12340)
+* Use `Any` as context annotation in plugin API by [@Viicos](https://github.com/Viicos) in [#12341](https://github.com/pydantic/pydantic/pull/12341)
+* Use proper `stacklevel` in warnings when possible by [@Viicos](https://github.com/Viicos) in [#12342](https://github.com/pydantic/pydantic/pull/12342)
+
+### New Contributors
+
+* [@anvilpete](https://github.com/anvilpete) made their first contribution in [#12233](https://github.com/pydantic/pydantic/pull/12233)
+* [@JonathanWindell](https://github.com/JonathanWindell) made their first contribution in [#12327](https://github.com/pydantic/pydantic/pull/12327)
+* [@inducer](https://github.com/inducer) made their first contribution in [#12279](https://github.com/pydantic/pydantic/pull/12279)
+* [@Atry](https://github.com/Atry) made their first contribution in [#12001](https://github.com/pydantic/pydantic/pull/12001)
+
+## v2.12.0b1 (2025-10-03)
+
+[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.12.0b1)
+
+This is the first beta release of the upcoming 2.12 release.
+
+### What's Changed
+
+#### Packaging
+
+* Bump `pydantic-core` to v2.40.1 by [@Viicos](https://github.com/Viicos) in [#12314](https://github.com/pydantic/pydantic/pull/12314)
+
+#### New Features
+
+* Add support for `exclude_if` at the field level by [@andresliszt](https://github.com/andresliszt) in [#12141](https://github.com/pydantic/pydantic/pull/12141)
+* Add `ValidateAs` annotation helper by [@Viicos](https://github.com/Viicos) in [#11942](https://github.com/pydantic/pydantic/pull/11942)
+* Add configuration options for validation and JSON serialization of temporal types by [@ollz272](https://github.com/ollz272) in [#12068](https://github.com/pydantic/pydantic/pull/12068)
+* Add support for PEP 728 by [@Viicos](https://github.com/Viicos) in [#12179](https://github.com/pydantic/pydantic/pull/12179)
+* Add field name in serialization error by [@NicolasPllr1](https://github.com/NicolasPllr1) in [pydantic-core#1799](https://github.com/pydantic/pydantic-core/pull/1799)
+* Add option to preserve empty URL paths by [@davidhewitt](https://github.com/davidhewitt) in [pydantic-core#1789](https://github.com/pydantic/pydantic-core/pull/1789)
+
+#### Changes
+
+* Raise error if an incompatible `pydantic-core` version is installed by [@Viicos](https://github.com/Viicos) in [#12196](https://github.com/pydantic/pydantic/pull/12196)
+* Remove runtime warning for experimental features by [@Viicos](https://github.com/Viicos) in [#12265](https://github.com/pydantic/pydantic/pull/12265)
+* Warn if registering virtual subclasses on Pydantic models by [@Viicos](https://github.com/Viicos) in [#11669](https://github.com/pydantic/pydantic/pull/11669)
+
+#### Fixes
+
+* Fix `__getattr__()` behavior on Pydantic models when a property raised an `AttributeError` and extra values are present by [@raspuchin](https://github.com/raspuchin) in [#12106](https://github.com/pydantic/pydantic/pull/12106)
+* Add test to prevent regression with Pydantic models used as annotated metadata by [@Viicos](https://github.com/Viicos) in [#12133](https://github.com/pydantic/pydantic/pull/12133)
+* Allow to use property setters on Pydantic dataclasses with `validate_assignment` set by [@Viicos](https://github.com/Viicos) in [#12173](https://github.com/pydantic/pydantic/pull/12173)
+* Fix mypy v2 plugin for upcoming mypy release by [@cdce8p](https://github.com/cdce8p) in [#12209](https://github.com/pydantic/pydantic/pull/12209)
+* Respect custom title in functions JSON Schema by [@Viicos](https://github.com/Viicos) in [#11892](https://github.com/pydantic/pydantic/pull/11892)
+* Fix `ImportString` JSON serialization for objects with a `name` attribute by [@chr1sj0nes](https://github.com/chr1sj0nes) in [#12219](https://github.com/pydantic/pydantic/pull/12219)
+* Do not error on fields overridden by methods in the mypy plugin by [@Viicos](https://github.com/Viicos) in [#12290](https://github.com/pydantic/pydantic/pull/12290)
+
+### New Contributors
+
+* [@raspuchin](https://github.com/raspuchin) made their first contribution in [#12106](https://github.com/pydantic/pydantic/pull/12106)
+* [@chr1sj0nes](https://github.com/chr1sj0nes) made their first contribution in [#12219](https://github.com/pydantic/pydantic/pull/12219)
+
+## v2.12.0a1 (2025-07-26)
+
+[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.12.0a1)
+
+This is the first alpha release of the upcoming 2.12 release, which adds initial support for Python 3.14.
+
+### What's Changed
+
+#### New Features
+
+* Add `__pydantic_on_complete__()` hook that is called once model is fully ready to be used by [@DouweM](https://github.com/DouweM) in [#11762](https://github.com/pydantic/pydantic/pull/11762)
+* Add initial support for Python 3.14 by [@Viicos](https://github.com/Viicos) in [#11991](https://github.com/pydantic/pydantic/pull/11991)
+* Add regex patterns to JSON schema for `Decimal` type by [@Dima-Bulavenko](https://github.com/Dima-Bulavenko) in [#11987](https://github.com/pydantic/pydantic/pull/11987)
+* Add support for `doc` attribute on dataclass fields by [@Viicos](https://github.com/Viicos) in [#12077](https://github.com/pydantic/pydantic/pull/12077)
+* Add experimental `MISSING` sentinel by [@Viicos](https://github.com/Viicos) in [#11883](https://github.com/pydantic/pydantic/pull/11883)
+
+#### Changes
+
+* Allow config and bases to be specified together in `create_model()` by [@Viicos](https://github.com/Viicos) in [#11714](https://github.com/pydantic/pydantic/pull/11714)
+* Move some field logic out of the `GenerateSchema` class by [@Viicos](https://github.com/Viicos) in [#11733](https://github.com/pydantic/pydantic/pull/11733)
+* Always make use of `inspect.getsourcelines()` for docstring extraction on Python 3.13 and greater by [@Viicos](https://github.com/Viicos) in [#11829](https://github.com/pydantic/pydantic/pull/11829)
+* Only support the latest Mypy version by [@Viicos](https://github.com/Viicos) in [#11832](https://github.com/pydantic/pydantic/pull/11832)
+* Do not implicitly convert after model validators to class methods by [@Viicos](https://github.com/Viicos) in [#11957](https://github.com/pydantic/pydantic/pull/11957)
+* Refactor `FieldInfo` creation implementation by [@Viicos](https://github.com/Viicos) in [#11898](https://github.com/pydantic/pydantic/pull/11898)
+* Make `Secret` covariant by [@bluenote10](https://github.com/bluenote10) in [#12008](https://github.com/pydantic/pydantic/pull/12008)
+* Emit warning when field-specific metadata is used in invalid contexts by [@Viicos](https://github.com/Viicos) in [#12028](https://github.com/pydantic/pydantic/pull/12028)
+
+#### Fixes
+
+* Properly fetch plain serializer function when serializing default value in JSON Schema by [@Viicos](https://github.com/Viicos) in [#11721](https://github.com/pydantic/pydantic/pull/11721)
+* Remove generics cache workaround by [@Viicos](https://github.com/Viicos) in [#11755](https://github.com/pydantic/pydantic/pull/11755)
+* Remove coercion of decimal constraints by [@Viicos](https://github.com/Viicos) in [#11772](https://github.com/pydantic/pydantic/pull/11772)
+* Fix crash when expanding root type in the mypy plugin by [@Viicos](https://github.com/Viicos) in [#11735](https://github.com/pydantic/pydantic/pull/11735)
+* Only mark model as complete once all fields are complete by [@DouweM](https://github.com/DouweM) in [#11759](https://github.com/pydantic/pydantic/pull/11759)
+* Do not provide `field_name` in validator core schemas by [@DouweM](https://github.com/DouweM) in [#11761](https://github.com/pydantic/pydantic/pull/11761)
+* Fix issue with recursive generic models by [@Viicos](https://github.com/Viicos) in [#11775](https://github.com/pydantic/pydantic/pull/11775)
+* Fix qualified name comparison of private attributes during namespace inspection by [@karta9821](https://github.com/karta9821) in [#11803](https://github.com/pydantic/pydantic/pull/11803)
+* Make sure Pydantic dataclasses with slots and `validate_assignment` can be unpickled by [@Viicos](https://github.com/Viicos) in [#11769](https://github.com/pydantic/pydantic/pull/11769)
+* Traverse `function-before` schemas during schema gathering by [@Viicos](https://github.com/Viicos) in [#11801](https://github.com/pydantic/pydantic/pull/11801)
+* Fix check for stdlib dataclasses by [@Viicos](https://github.com/Viicos) in [#11822](https://github.com/pydantic/pydantic/pull/11822)
+* Check if `FieldInfo` is complete after applying type variable map by [@Viicos](https://github.com/Viicos) in [#11855](https://github.com/pydantic/pydantic/pull/11855)
+* Do not delete mock validator/serializer in `model_rebuild()` by [@Viicos](https://github.com/Viicos) in [#11890](https://github.com/pydantic/pydantic/pull/11890)
+* Rebuild dataclass fields before schema generation by [@Viicos](https://github.com/Viicos) in [#11949](https://github.com/pydantic/pydantic/pull/11949)
+* Always store the original field assignment on `FieldInfo` by [@Viicos](https://github.com/Viicos) in [#11946](https://github.com/pydantic/pydantic/pull/11946)
+* Do not use deprecated methods as default field values by [@Viicos](https://github.com/Viicos) in [#11914](https://github.com/pydantic/pydantic/pull/11914)
+* Allow callable discriminator to be applied on PEP 695 type aliases by [@Viicos](https://github.com/Viicos) in [#11941](https://github.com/pydantic/pydantic/pull/11941)
+* Suppress core schema generation warning when using `SkipValidation` by [@ygsh0816](https://github.com/ygsh0816) in [#12002](https://github.com/pydantic/pydantic/pull/12002)
+* Do not emit typechecking error for invalid `Field()` default with `validate_default` set to `True` by [@Viicos](https://github.com/Viicos) in [#11988](https://github.com/pydantic/pydantic/pull/11988)
+* Refactor logic to support Pydantic's `Field()` function in dataclasses by [@Viicos](https://github.com/Viicos) in [#12051](https://github.com/pydantic/pydantic/pull/12051)
+
+#### Packaging
+
+* Update project metadata to use PEP 639 by [@Viicos](https://github.com/Viicos) in [#11694](https://github.com/pydantic/pydantic/pull/11694)
+* Bump `mkdocs-llmstxt` to v0.2.0 by [@Viicos](https://github.com/Viicos) in [#11725](https://github.com/pydantic/pydantic/pull/11725)
+* Bump `pydantic-core` to v2.35.1 by [@Viicos](https://github.com/Viicos) in [#11963](https://github.com/pydantic/pydantic/pull/11963)
+* Bump dawidd6/action-download-artifact from 10 to 11 by [@dependabot](https://github.com/dependabot)[bot] in [#12033](https://github.com/pydantic/pydantic/pull/12033)
+* Bump astral-sh/setup-uv from 5 to 6 by [@dependabot](https://github.com/dependabot)[bot] in [#11826](https://github.com/pydantic/pydantic/pull/11826)
+* Update mypy to 1.17.0 by [@Viicos](https://github.com/Viicos) in [#12076](https://github.com/pydantic/pydantic/pull/12076)
+
+### New Contributors
+
+* [@parth-paradkar](https://github.com/parth-paradkar) made their first contribution in [#11695](https://github.com/pydantic/pydantic/pull/11695)
+* [@dqkqd](https://github.com/dqkqd) made their first contribution in [#11739](https://github.com/pydantic/pydantic/pull/11739)
+* [@fhightower](https://github.com/fhightower) made their first contribution in [#11722](https://github.com/pydantic/pydantic/pull/11722)
+* [@gbaian10](https://github.com/gbaian10) made their first contribution in [#11766](https://github.com/pydantic/pydantic/pull/11766)
+* [@DouweM](https://github.com/DouweM) made their first contribution in [#11759](https://github.com/pydantic/pydantic/pull/11759)
+* [@bowenliang123](https://github.com/bowenliang123) made their first contribution in [#11719](https://github.com/pydantic/pydantic/pull/11719)
+* [@rawwar](https://github.com/rawwar) made their first contribution in [#11799](https://github.com/pydantic/pydantic/pull/11799)
+* [@karta9821](https://github.com/karta9821) made their first contribution in [#11803](https://github.com/pydantic/pydantic/pull/11803)
+* [@jinnovation](https://github.com/jinnovation) made their first contribution in [#11834](https://github.com/pydantic/pydantic/pull/11834)
+* [@zmievsa](https://github.com/zmievsa) made their first contribution in [#11861](https://github.com/pydantic/pydantic/pull/11861)
+* [@Otto-AA](https://github.com/Otto-AA) made their first contribution in [#11860](https://github.com/pydantic/pydantic/pull/11860)
+* [@ygsh0816](https://github.com/ygsh0816) made their first contribution in [#12002](https://github.com/pydantic/pydantic/pull/12002)
+* [@lukland](https://github.com/lukland) made their first contribution in [#12015](https://github.com/pydantic/pydantic/pull/12015)
+* [@Dima-Bulavenko](https://github.com/Dima-Bulavenko) made their first contribution in [#11987](https://github.com/pydantic/pydantic/pull/11987)
+* [@GSemikozov](https://github.com/GSemikozov) made their first contribution in [#12050](https://github.com/pydantic/pydantic/pull/12050)
+* [@hannah-heywa](https://github.com/hannah-heywa) made their first contribution in [#12082](https://github.com/pydantic/pydantic/pull/12082)
+
+## v2.11.7 (2025-06-14)
+
+[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.11.7)
+
+### What's Changed
+
+#### Fixes
+
+* Copy `FieldInfo` instance if necessary during `FieldInfo` build by [@Viicos](https://github.com/Viicos) in [#11898](https://github.com/pydantic/pydantic/pull/11898)
+
+## v2.11.6 (2025-06-13)
+
+[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.11.6)
+
+### What's Changed
+
+#### Fixes
+
+* Rebuild dataclass fields before schema generation by [@Viicos](https://github.com/Viicos) in [#11949](https://github.com/pydantic/pydantic/pull/11949)
+* Always store the original field assignment on `FieldInfo` by [@Viicos](https://github.com/Viicos) in [#11946](https://github.com/pydantic/pydantic/pull/11946)
+
+## v2.11.5 (2025-05-22)
+
+[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.11.5)
+
+### What's Changed
+
+#### Fixes
+
+* Check if `FieldInfo` is complete after applying type variable map by [@Viicos](https://github.com/Viicos) in [#11855](https://github.com/pydantic/pydantic/pull/11855)
+* Do not delete mock validator/serializer in `model_rebuild()` by [@Viicos](https://github.com/Viicos) in [#11890](https://github.com/pydantic/pydantic/pull/11890)
+* Do not duplicate metadata on model rebuild by [@Viicos](https://github.com/Viicos) in [#11902](https://github.com/pydantic/pydantic/pull/11902)
+
+## v2.11.4 (2025-04-29)
+
+[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.11.4)
+
+### What's Changed
+
+#### Packaging
+
+* Bump `mkdocs-llmstxt` to v0.2.0 by [@Viicos](https://github.com/Viicos) in [#11725](https://github.com/pydantic/pydantic/pull/11725)
+
+#### Changes
+
+* Allow config and bases to be specified together in `create_model()` by [@Viicos](https://github.com/Viicos) in [#11714](https://github.com/pydantic/pydantic/pull/11714).
+  This change was backported as it was previously possible (although not meant to be supported)
+  to provide `model_config` as a field, which would make it possible to provide both configuration
+  and bases.
+
+#### Fixes
+
+* Remove generics cache workaround by [@Viicos](https://github.com/Viicos) in [#11755](https://github.com/pydantic/pydantic/pull/11755)
+* Remove coercion of decimal constraints by [@Viicos](https://github.com/Viicos) in [#11772](https://github.com/pydantic/pydantic/pull/11772)
+* Fix crash when expanding root type in the mypy plugin by [@Viicos](https://github.com/Viicos) in [#11735](https://github.com/pydantic/pydantic/pull/11735)
+* Fix issue with recursive generic models by [@Viicos](https://github.com/Viicos) in [#11775](https://github.com/pydantic/pydantic/pull/11775)
+* Traverse `function-before` schemas during schema gathering by [@Viicos](https://github.com/Viicos) in [#11801](https://github.com/pydantic/pydantic/pull/11801)
+
+## v2.11.3 (2025-04-08)
+
+[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.11.3)
+
+### What's Changed
+
+#### Packaging
+
+* Update V1 copy to v1.10.21 by [@Viicos](https://github.com/Viicos) in [#11706](https://github.com/pydantic/pydantic/pull/11706)
+
+#### Fixes
+
+* Preserve field description when rebuilding model fields by [@Viicos](https://github.com/Viicos) in [#11698](https://github.com/pydantic/pydantic/pull/11698)
+
+## v2.11.2 (2025-04-03)
+
+[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.11.2)
+
+### What's Changed
+
+#### Fixes
+
+* Bump `pydantic-core` to v2.33.1 by [@Viicos](https://github.com/Viicos) in [#11678](https://github.com/pydantic/pydantic/pull/11678)
+* Make sure `__pydantic_private__` exists before setting private attributes by [@Viicos](https://github.com/Viicos) in [#11666](https://github.com/pydantic/pydantic/pull/11666)
+* Do not override `FieldInfo._complete` when using field from parent class by [@Viicos](https://github.com/Viicos) in [#11668](https://github.com/pydantic/pydantic/pull/11668)
+* Provide the available definitions when applying discriminated unions by [@Viicos](https://github.com/Viicos) in [#11670](https://github.com/pydantic/pydantic/pull/11670)
+* Do not expand root type in the mypy plugin for variables by [@Viicos](https://github.com/Viicos) in [#11676](https://github.com/pydantic/pydantic/pull/11676)
+* Mention the attribute name in model fields deprecation message by [@Viicos](https://github.com/Viicos) in [#11674](https://github.com/pydantic/pydantic/pull/11674)
+* Properly validate parameterized mappings by [@Viicos](https://github.com/Viicos) in [#11658](https://github.com/pydantic/pydantic/pull/11658)
+
+## v2.11.1 (2025-03-28)
+
+[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.11.1)
+
+### What's Changed
+
+#### Fixes
+
+* Do not override `'definitions-ref'` schemas containing serialization schemas or metadata by [@Viicos](https://github.com/Viicos) in [#11644](https://github.com/pydantic/pydantic/pull/11644)
+
+## v2.11.0 (2025-03-27)
+
+[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.11.0)
+
+### What's Changed
+
+Pydantic v2.11 is a version strongly focused on build time performance of Pydantic models (and core schema generation in general).
+See the [blog post](https://pydantic.dev/articles/pydantic-v2-11-release) for more details.
+
+#### Packaging
+
+* Bump `pydantic-core` to v2.33.0 by [@Viicos](https://github.com/Viicos) in [#11631](https://github.com/pydantic/pydantic/pull/11631)
+
+#### New Features
+
+* Add `encoded_string()` method to the URL types by [@YassinNouh21](https://github.com/YassinNouh21) in [#11580](https://github.com/pydantic/pydantic/pull/11580)
+* Add support for `defer_build` with `@validate_call` decorator by [@Viicos](https://github.com/Viicos) in [#11584](https://github.com/pydantic/pydantic/pull/11584)
+* Allow `@with_config` decorator to be used with keyword arguments by [@Viicos](https://github.com/Viicos) in [#11608](https://github.com/pydantic/pydantic/pull/11608)
+* Simplify customization of default value inclusion in JSON Schema generation by [@Viicos](https://github.com/Viicos) in [#11634](https://github.com/pydantic/pydantic/pull/11634)
+* Add `generate_arguments_schema()` function by [@Viicos](https://github.com/Viicos) in [#11572](https://github.com/pydantic/pydantic/pull/11572)
+
+#### Fixes
+
+* Allow generic typed dictionaries to be used for unpacked variadic keyword parameters by [@Viicos](https://github.com/Viicos) in [#11571](https://github.com/pydantic/pydantic/pull/11571)
+* Fix runtime error when computing model string representation involving cached properties and self-referenced models by [@Viicos](https://github.com/Viicos) in [#11579](https://github.com/pydantic/pydantic/pull/11579)
+* Preserve other steps when using the ellipsis in the pipeline API by [@Viicos](https://github.com/Viicos) in [#11626](https://github.com/pydantic/pydantic/pull/11626)
+* Fix deferred discriminator application logic by [@Viicos](https://github.com/Viicos) in [#11591](https://github.com/pydantic/pydantic/pull/11591)
+
+### New Contributors
+
+* [@cmenon12](https://github.com/cmenon12) made their first contribution in [#11562](https://github.com/pydantic/pydantic/pull/11562)
+* [@Jeukoh](https://github.com/Jeukoh) made their first contribution in [#11611](https://github.com/pydantic/pydantic/pull/11611)
+
+## v2.11.0b2 (2025-03-17)
+
+[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.11.0b2)
+
+### What's Changed
+
+#### Packaging
+
+* Bump `pydantic-core` to v2.32.0 by [@Viicos](https://github.com/Viicos) in [#11567](https://github.com/pydantic/pydantic/pull/11567)
+
+#### New Features
+
+* Add experimental support for free threading by [@Viicos](https://github.com/Viicos) in [#11516](https://github.com/pydantic/pydantic/pull/11516)
+
+#### Fixes
+
+* Fix `NotRequired` qualifier not taken into account in stringified annotation by [@Viicos](https://github.com/Viicos) in [#11559](https://github.com/pydantic/pydantic/pull/11559)
+
+### New Contributors
+
+* [@joren485](https://github.com/joren485) made their first contribution in [#11547](https://github.com/pydantic/pydantic/pull/11547)
+
+## v2.11.0b1 (2025-03-06)
+
+[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.11.0b1)
+
+### What's Changed
+
+#### Packaging
+
+* Add a `check_pydantic_core_version()` function by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11324
+* Remove `greenlet` development dependency by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11351
+* Use the `typing-inspection` library by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11479
+* Bump `pydantic-core` to `v2.31.1` by [@sydney-runkle](https://github.com/sydney-runkle) in https://github.com/pydantic/pydantic/pull/11526
+
+#### New Features
+
+* Support unsubstituted type variables with both a default and a bound or constraints by [@FyZzyss](https://github.com/FyZzyss) in https://github.com/pydantic/pydantic/pull/10789
+* Add a `default_factory_takes_validated_data` property to `FieldInfo` by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11034
+* Raise a better error when a generic alias is used inside `type[]` by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11088
+* Properly support PEP 695 generics syntax by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11189
+* Properly support type variable defaults by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11332
+* Add support for validating v6, v7, v8 UUIDs by [@astei](https://github.com/astei) in https://github.com/pydantic/pydantic/pull/11436
+* Improve alias configuration APIs by [@sydney-runkle](https://github.com/sydney-runkle) in https://github.com/pydantic/pydantic/pull/11468
+
+#### Changes
+
+* Rework `create_model` field definitions format by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11032
+* Raise a deprecation warning when a field is annotated as final with a default value by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11168
+* Deprecate accessing `model_fields` and `model_computed_fields` on instances by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11169
+* **Breaking Change:** Move core schema generation logic for path types inside the `GenerateSchema` class by [@sydney-runkle](https://github.com/sydney-runkle) in https://github.com/pydantic/pydantic/pull/10846
+* Remove Python 3.8 Support by [@sydney-runkle](https://github.com/sydney-runkle) in https://github.com/pydantic/pydantic/pull/11258
+* Optimize calls to `get_type_ref` by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/10863
+* Disable `pydantic-core` core schema validation by [@sydney-runkle](https://github.com/sydney-runkle) in https://github.com/pydantic/pydantic/pull/11271
+
+#### Performance
+
+* Only evaluate `FieldInfo` annotations if required during schema building by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/10769
+* Improve `__setattr__` performance of Pydantic models by caching setter functions by [@MarkusSintonen](https://github.com/MarkusSintonen) in https://github.com/pydantic/pydantic/pull/10868
+* Improve annotation application performance by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11186
+* Improve performance of `_typing_extra` module by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11255
+* Refactor and optimize schema cleaning logic by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11244
+* Create a single dictionary when creating a `CoreConfig` instance by [@sydney-runkle](https://github.com/sydney-runkle) in https://github.com/pydantic/pydantic/pull/11384
+* Bump `pydantic-core` and thus use `SchemaValidator` and `SchemaSerializer` caching by [@sydney-runkle](https://github.com/sydney-runkle) in https://github.com/pydantic/pydantic/pull/11402
+* Reuse cached core schemas for parametrized generic Pydantic models by [@MarkusSintonen](https://github.com/MarkusSintonen) in https://github.com/pydantic/pydantic/pull/11434
+
+#### Fixes
+
+* Improve `TypeAdapter` instance repr by [@sydney-runkle](https://github.com/sydney-runkle) in https://github.com/pydantic/pydantic/pull/10872
+* Use the correct frame when instantiating a parametrized `TypeAdapter` by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/10893
+* Infer final fields with a default value as class variables in the mypy plugin by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11121
+* Recursively unpack `Literal` values if using PEP 695 type aliases by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11114
+* Override `__subclasscheck__` on `ModelMetaclass` to avoid memory leak and performance issues by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11116
+* Remove unused `_extract_get_pydantic_json_schema()` parameter by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11155
+* Improve discriminated union error message for invalid union variants by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11161
+* Unpack PEP 695 type aliases if using the `Annotated` form by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11109
+* Add missing stacklevel in `deprecated_instance_property` warning by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11200
+* Copy `WithJsonSchema` schema to avoid sharing mutated data by [@thejcannon](https://github.com/thejcannon) in https://github.com/pydantic/pydantic/pull/11014
+* Do not cache parametrized models when in the process of parametrizing another model by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/10704
+* Add discriminated union related metadata entries to the `CoreMetadata` definition by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11216
+* Consolidate schema definitions logic in the `_Definitions` class by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11208
+* Support initializing root model fields with values of the `root` type in the mypy plugin by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11212
+* Fix various issues with dataclasses and `use_attribute_docstrings` by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11246
+* Only compute normalized decimal places if necessary in `decimal_places_validator` by [@misrasaurabh1](https://github.com/misrasaurabh1) in https://github.com/pydantic/pydantic/pull/11281
+* Add support for `validation_alias` in the mypy plugin by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11295
+* Fix JSON Schema reference collection with `"examples"` keys by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11305
+* Do not transform model serializer functions as class methods in the mypy plugin by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11298
+* Simplify `GenerateJsonSchema.literal_schema()` implementation by [@misrasaurabh1](https://github.com/misrasaurabh1) in https://github.com/pydantic/pydantic/pull/11321
+* Add additional allowed schemes for `ClickHouseDsn` by [@Maze21127](https://github.com/Maze21127) in https://github.com/pydantic/pydantic/pull/11319
+* Coerce decimal constraints to `Decimal` instances by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11350
+* Use the correct JSON Schema mode when handling function schemas by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11367
+* Improve exception message when encountering recursion errors during type evaluation by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11356
+* Always include `additionalProperties: True` for arbitrary dictionary schemas by [@austinyu](https://github.com/austinyu) in https://github.com/pydantic/pydantic/pull/11392
+* Expose `fallback` parameter in serialization methods by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11398
+* Fix path serialization behavior by [@sydney-runkle](https://github.com/sydney-runkle) in https://github.com/pydantic/pydantic/pull/11416
+* Do not reuse validators and serializers during model rebuild by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11429
+* Collect model fields when rebuilding a model by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11388
+* Allow cached properties to be altered on frozen models by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11432
+* Fix tuple serialization for `Sequence` types by [@sydney-runkle](https://github.com/sydney-runkle) in https://github.com/pydantic/pydantic/pull/11435
+* Fix: do not check for `__get_validators__` on classes where `__get_pydantic_core_schema__` is also defined by [@tlambert03](https://github.com/tlambert03) in https://github.com/pydantic/pydantic/pull/11444
+* Allow callable instances to be used as serializers by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11451
+* Improve error thrown when overriding field with a property by [@sydney-runkle](https://github.com/sydney-runkle) in https://github.com/pydantic/pydantic/pull/11459
+* Fix JSON Schema generation with referenceable core schemas holding JSON metadata by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11475
+* Support strict specification on union member types by [@sydney-runkle](https://github.com/sydney-runkle) in https://github.com/pydantic/pydantic/pull/11481
+* Implicitly set `validate_by_name` to `True` when `validate_by_alias` is `False` by [@sydney-runkle](https://github.com/sydney-runkle) in https://github.com/pydantic/pydantic/pull/11503
+* Change type of `Any` when synthesizing `BaseSettings.__init__` signature in the mypy plugin by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11497
+* Support type variable defaults referencing other type variables by [@Viicos](https://github.com/Viicos) in https://github.com/pydantic/pydantic/pull/11520
+* Fix `ValueError` on year zero by [@davidhewitt](https://github.com/davidhewitt) in https://github.com/pydantic/pydantic-core/pull/1583
+* `dataclass` `InitVar` shouldn't be required on serialization by [@sydney-runkle](https://github.com/sydney-runkle) in https://github.com/pydantic/pydantic-core/pull/1602
+
+## New Contributors
+
+* [@FyZzyss](https://github.com/FyZzyss) made their first contribution in https://github.com/pydantic/pydantic/pull/10789
+* [@tamird](https://github.com/tamird) made their first contribution in https://github.com/pydantic/pydantic/pull/10948
+* [@felixxm](https://github.com/felixxm) made their first contribution in https://github.com/pydantic/pydantic/pull/11077
+* [@alexprabhat99](https://github.com/alexprabhat99) made their first contribution in https://github.com/pydantic/pydantic/pull/11082
+* [@Kharianne](https://github.com/Kharianne) made their first contribution in https://github.com/pydantic/pydantic/pull/11111
+* [@mdaffad](https://github.com/mdaffad) made their first contribution in https://github.com/pydantic/pydantic/pull/11177
+* [@thejcannon](https://github.com/thejcannon) made their first contribution in https://github.com/pydantic/pydantic/pull/11014
+* [@thomasfrimannkoren](https://github.com/thomasfrimannkoren) made their first contribution in https://github.com/pydantic/pydantic/pull/11251
+* [@usernameMAI](https://github.com/usernameMAI) made their first contribution in https://github.com/pydantic/pydantic/pull/11275
+* [@ananiavito](https://github.com/ananiavito) made their first contribution in https://github.com/pydantic/pydantic/pull/11302
+* [@pawamoy](https://github.com/pawamoy) made their first contribution in https://github.com/pydantic/pydantic/pull/11311
+* [@Maze21127](https://github.com/Maze21127) made their first contribution in https://github.com/pydantic/pydantic/pull/11319
+* [@kauabh](https://github.com/kauabh) made their first contribution in https://github.com/pydantic/pydantic/pull/11369
+* [@jaceklaskowski](https://github.com/jaceklaskowski) made their first contribution in https://github.com/pydantic/pydantic/pull/11353
+* [@tmpbeing](https://github.com/tmpbeing) made their first contribution in https://github.com/pydantic/pydantic/pull/11375
+* [@petyosi](https://github.com/petyosi) made their first contribution in https://github.com/pydantic/pydantic/pull/11405
+* [@austinyu](https://github.com/austinyu) made their first contribution in https://github.com/pydantic/pydantic/pull/11392
+* [@mikeedjones](https://github.com/mikeedjones) made their first contribution in https://github.com/pydantic/pydantic/pull/11402
+* [@astei](https://github.com/astei) made their first contribution in https://github.com/pydantic/pydantic/pull/11436
+* [@dsayling](https://github.com/dsayling) made their first contribution in https://github.com/pydantic/pydantic/pull/11522
+* [@sobolevn](https://github.com/sobolevn) made their first contribution in https://github.com/pydantic/pydantic-core/pull/1645
+
+## v2.11.0a2 (2025-02-10)
+
+[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.11.0a2)
+
+### What's Changed
+
+Pydantic v2.11 is a version strongly focused on build time performance of Pydantic models (and core schema generation in general).
+This is another early alpha release, meant to collect early feedback from users having issues with core schema builds.
+
+#### Packaging
+
+* Bump `ruff` from 0.9.2 to 0.9.5 by [@Viicos](https://github.com/Viicos) in [#11407](https://github.com/pydantic/pydantic/pull/11407)
+* Bump `pydantic-core` to v2.29.0 by [@mikeedjones](https://github.com/mikeedjones) in [#11402](https://github.com/pydantic/pydantic/pull/11402)
+* Use locally-built rust with symbols & pgo by [@davidhewitt](https://github.com/davidhewitt) in [#11403](https://github.com/pydantic/pydantic/pull/11403)
+
+#### Performance
+
+* Create a single dictionary when creating a `CoreConfig` instance by [@sydney-runkle](https://github.com/sydney-runkle) in [#11384](https://github.com/pydantic/pydantic/pull/11384)
+
+#### Fixes
+
+* Use the correct JSON Schema mode when handling function schemas by [@Viicos](https://github.com/Viicos) in [#11367](https://github.com/pydantic/pydantic/pull/11367)
+* Fix JSON Schema reference logic with `examples` keys by [@Viicos](https://github.com/Viicos) in [#11366](https://github.com/pydantic/pydantic/pull/11366)
+* Improve exception message when encountering recursion errors during type evaluation by [@Viicos](https://github.com/Viicos) in [#11356](https://github.com/pydantic/pydantic/pull/11356)
+* Always include `additionalProperties: True` for arbitrary dictionary schemas by [@austinyu](https://github.com/austinyu) in [#11392](https://github.com/pydantic/pydantic/pull/11392)
+* Expose `fallback` parameter in serialization methods by [@Viicos](https://github.com/Viicos) in [#11398](https://github.com/pydantic/pydantic/pull/11398)
+* Fix path serialization behavior by [@sydney-runkle](https://github.com/sydney-runkle) in [#11416](https://github.com/pydantic/pydantic/pull/11416)
+
+### New Contributors
+
+* [@kauabh](https://github.com/kauabh) made their first contribution in [#11369](https://github.com/pydantic/pydantic/pull/11369)
+* [@jaceklaskowski](https://github.com/jaceklaskowski) made their first contribution in [#11353](https://github.com/pydantic/pydantic/pull/11353)
+* [@tmpbeing](https://github.com/tmpbeing) made their first contribution in [#11375](https://github.com/pydantic/pydantic/pull/11375)
+* [@petyosi](https://github.com/petyosi) made their first contribution in [#11405](https://github.com/pydantic/pydantic/pull/11405)
+* [@austinyu](https://github.com/austinyu) made their first contribution in [#11392](https://github.com/pydantic/pydantic/pull/11392)
+* [@mikeedjones](https://github.com/mikeedjones) made their first contribution in [#11402](https://github.com/pydantic/pydantic/pull/11402)
+
+## v2.11.0a1 (2025-01-30)
+
+[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.11.0a1)
+
+### What's Changed
+
+Pydantic v2.11 is a version strongly focused on build time performance of Pydantic models (and core schema generation in general).
+This is an early alpha release, meant to collect early feedback from users having issues with core schema builds.
+
+#### Packaging
+
+* Bump dawidd6/action-download-artifact from 6 to 7 by [@dependabot](https://github.com/dependabot) in [#11018](https://github.com/pydantic/pydantic/pull/11018)
+* Re-enable memray related tests on Python 3.12+ by [@Viicos](https://github.com/Viicos) in [#11191](https://github.com/pydantic/pydantic/pull/11191)
+* Bump astral-sh/setup-uv to 5 by [@dependabot](https://github.com/dependabot) in [#11205](https://github.com/pydantic/pydantic/pull/11205)
+* Bump `ruff` to v0.9.0 by [@sydney-runkle](https://github.com/sydney-runkle) in [#11254](https://github.com/pydantic/pydantic/pull/11254)
+* Regular `uv.lock` deps update by [@sydney-runkle](https://github.com/sydney-runkle) in [#11333](https://github.com/pydantic/pydantic/pull/11333)
+* Add a `check_pydantic_core_version()` function by [@Viicos](https://github.com/Viicos) in [#11324](https://github.com/pydantic/pydantic/pull/11324)
+* Remove `greenlet` development dependency by [@Viicos](https://github.com/Viicos) in [#11351](https://github.com/pydantic/pydantic/pull/11351)
+* Bump `pydantic-core` to v2.28.0 by [@Viicos](https://github.com/Viicos) in [#11364](https://github.com/pydantic/pydantic/pull/11364)
+
+#### New Features
+
+* Support unsubstituted type variables with both a default and a bound or constraints by [@FyZzyss](https://github.com/FyZzyss) in [#10789](https://github.com/pydantic/pydantic/pull/10789)
+* Add a `default_factory_takes_validated_data` property to `FieldInfo` by [@Viicos](https://github.com/Viicos) in [#11034](https://github.com/pydantic/pydantic/pull/11034)
+* Raise a better error when a generic alias is used inside `type[]` by [@Viicos](https://github.com/Viicos) in [#11088](https://github.com/pydantic/pydantic/pull/11088)
+* Properly support PEP 695 generics syntax by [@Viicos](https://github.com/Viicos) in [#11189](https://github.com/pydantic/pydantic/pull/11189)
+* Properly support type variable defaults by [@Viicos](https://github.com/Viicos) in [#11332](https://github.com/pydantic/pydantic/pull/11332)
+
+#### Changes
+
+* Rework `create_model` field definitions format by [@Viicos](https://github.com/Viicos) in [#11032](https://github.com/pydantic/pydantic/pull/11032)
+* Raise a deprecation warning when a field is annotated as final with a default value by [@Viicos](https://github.com/Viicos) in [#11168](https://github.com/pydantic/pydantic/pull/11168)
+* Deprecate accessing `model_fields` and `model_computed_fields` on instances by [@Viicos](https://github.com/Viicos) in [#11169](https://github.com/pydantic/pydantic/pull/11169)
+* Move core schema generation logic for path types inside the `GenerateSchema` class by [@sydney-runkle](https://github.com/sydney-runkle) in [#10846](https://github.com/pydantic/pydantic/pull/10846)
+* Move `deque` schema gen to `GenerateSchema` class by [@sydney-runkle](https://github.com/sydney-runkle) in [#11239](https://github.com/pydantic/pydantic/pull/11239)
+* Move `Mapping` schema gen to `GenerateSchema` to complete removal of `prepare_annotations_for_known_type` workaround by [@sydney-runkle](https://github.com/sydney-runkle) in [#11247](https://github.com/pydantic/pydantic/pull/11247)
+* Remove Python 3.8 Support by [@sydney-runkle](https://github.com/sydney-runkle) in [#11258](https://github.com/pydantic/pydantic/pull/11258)
+* Disable `pydantic-core` core schema validation by [@sydney-runkle](https://github.com/sydney-runkle) in [#11271](https://github.com/pydantic/pydantic/pull/11271)
+
+#### Performance
+
+* Only evaluate `FieldInfo` annotations if required during schema building by [@Viicos](https://github.com/Viicos) in [#10769](https://github.com/pydantic/pydantic/pull/10769)
+* Optimize calls to `get_type_ref` by [@Viicos](https://github.com/Viicos) in [#10863](https://github.com/pydantic/pydantic/pull/10863)
+* Improve `__setattr__` performance of Pydantic models by caching setter functions by [@MarkusSintonen](https://github.com/MarkusSintonen) in [#10868](https://github.com/pydantic/pydantic/pull/10868)
+* Improve annotation application performance by [@Viicos](https://github.com/Viicos) in [#11186](https://github.com/pydantic/pydantic/pull/11186)
+* Improve performance of `_typing_extra` module by [@Viicos](https://github.com/Viicos) in [#11255](https://github.com/pydantic/pydantic/pull/11255)
+* Refactor and optimize schema cleaning logic by [@Viicos](https://github.com/Viicos) and [@MarkusSintonen](https://github.com/MarkusSintonen) in [#11244](https://github.com/pydantic/pydantic/pull/11244)
+
+#### Fixes
+
+* Add validation tests for `_internal/_validators.py` by [@tkasuz](https://github.com/tkasuz) in [#10763](https://github.com/pydantic/pydantic/pull/10763)
+* Improve `TypeAdapter` instance repr by [@sydney-runkle](https://github.com/sydney-runkle) in [#10872](https://github.com/pydantic/pydantic/pull/10872)
+* Revert "ci: use locally built pydantic-core with debug symbols by [@sydney-runkle](https://github.com/sydney-runkle) in [#10942](https://github.com/pydantic/pydantic/pull/10942)
+* Re-enable all FastAPI tests by [@tamird](https://github.com/tamird) in [#10948](https://github.com/pydantic/pydantic/pull/10948)
+* Fix typo in HISTORY.md. by [@felixxm](https://github.com/felixxm) in [#11077](https://github.com/pydantic/pydantic/pull/11077)
+* Infer final fields with a default value as class variables in the mypy plugin by [@Viicos](https://github.com/Viicos) in [#11121](https://github.com/pydantic/pydantic/pull/11121)
+* Recursively unpack `Literal` values if using PEP 695 type aliases by [@Viicos](https://github.com/Viicos) in [#11114](https://github.com/pydantic/pydantic/pull/11114)
+* Override `__subclasscheck__` on `ModelMetaclass` to avoid memory leak and performance issues by [@Viicos](https://github.com/Viicos) in [#11116](https://github.com/pydantic/pydantic/pull/11116)
+* Remove unused `_extract_get_pydantic_json_schema()` parameter by [@Viicos](https://github.com/Viicos) in [#11155](https://github.com/pydantic/pydantic/pull/11155)
+* Add FastAPI and SQLModel to third-party tests by [@sydney-runkle](https://github.com/sydney-runkle) in [#11044](https://github.com/pydantic/pydantic/pull/11044)
+* Fix conditional expressions syntax for third-party tests by [@Viicos](https://github.com/Viicos) in [#11162](https://github.com/pydantic/pydantic/pull/11162)
+* Move FastAPI tests to third-party workflow by [@Viicos](https://github.com/Viicos) in [#11164](https://github.com/pydantic/pydantic/pull/11164)
+* Improve discriminated union error message for invalid union variants by [@Viicos](https://github.com/Viicos) in [#11161](https://github.com/pydantic/pydantic/pull/11161)
+* Unpack PEP 695 type aliases if using the `Annotated` form by [@Viicos](https://github.com/Viicos) in [#11109](https://github.com/pydantic/pydantic/pull/11109)
+* Include `openapi-python-client` check in issue creation for third-party failures, use `main` branch by [@sydney-runkle](https://github.com/sydney-runkle) in [#11182](https://github.com/pydantic/pydantic/pull/11182)
+* Add pandera third-party tests by [@Viicos](https://github.com/Viicos) in [#11193](https://github.com/pydantic/pydantic/pull/11193)
+* Add ODMantic third-party tests by [@sydney-runkle](https://github.com/sydney-runkle) in [#11197](https://github.com/pydantic/pydantic/pull/11197)
+* Add missing stacklevel in `deprecated_instance_property` warning by [@Viicos](https://github.com/Viicos) in [#11200](https://github.com/pydantic/pydantic/pull/11200)
+* Copy `WithJsonSchema` schema to avoid sharing mutated data by [@thejcannon](https://github.com/thejcannon) in [#11014](https://github.com/pydantic/pydantic/pull/11014)
+* Do not cache parametrized models when in the process of parametrizing another model by [@Viicos](https://github.com/Viicos) in [#10704](https://github.com/pydantic/pydantic/pull/10704)
+* Re-enable Beanie third-party tests by [@Viicos](https://github.com/Viicos) in [#11214](https://github.com/pydantic/pydantic/pull/11214)
+* Add discriminated union related metadata entries to the `CoreMetadata` definition by [@Viicos](https://github.com/Viicos) in [#11216](https://github.com/pydantic/pydantic/pull/11216)
+* Consolidate schema definitions logic in the `_Definitions` class by [@Viicos](https://github.com/Viicos) in [#11208](https://github.com/pydantic/pydantic/pull/11208)
+* Support initializing root model fields with values of the `root` type in the mypy plugin by [@Viicos](https://github.com/Viicos) in [#11212](https://github.com/pydantic/pydantic/pull/11212)
+* Fix various issues with dataclasses and `use_attribute_docstrings` by [@Viicos](https://github.com/Viicos) in [#11246](https://github.com/pydantic/pydantic/pull/11246)
+* Only compute normalized decimal places if necessary in `decimal_places_validator` by [@misrasaurabh1](https://github.com/misrasaurabh1) in [#11281](https://github.com/pydantic/pydantic/pull/11281)
+* Fix two misplaced sentences in validation errors documentation by [@ananiavito](https://github.com/ananiavito) in [#11302](https://github.com/pydantic/pydantic/pull/11302)
+* Fix mkdocstrings inventory example in documentation by [@pawamoy](https://github.com/pawamoy) in [#11311](https://github.com/pydantic/pydantic/pull/11311)
+* Add support for `validation_alias` in the mypy plugin by [@Viicos](https://github.com/Viicos) in [#11295](https://github.com/pydantic/pydantic/pull/11295)
+* Do not transform model serializer functions as class methods in the mypy plugin by [@Viicos](https://github.com/Viicos) in [#11298](https://github.com/pydantic/pydantic/pull/11298)
+* Simplify `GenerateJsonSchema.literal_schema()` implementation by [@misrasaurabh1](https://github.com/misrasaurabh1) in [#11321](https://github.com/pydantic/pydantic/pull/11321)
+* Add additional allowed schemes for `ClickHouseDsn` by [@Maze21127](https://github.com/Maze21127) in [#11319](https://github.com/pydantic/pydantic/pull/11319)
+* Coerce decimal constraints to `Decimal` instances by [@Viicos](https://github.com/Viicos) in [#11350](https://github.com/pydantic/pydantic/pull/11350)
+* Fix `ValueError` on year zero by [@davidhewitt](https://github.com/davidhewitt) in [pydantic-core#1583](https://github.com/pydantic/pydantic-core/pull/1583)
+
+### New Contributors
+
+* [@FyZzyss](https://github.com/FyZzyss) made their first contribution in [#10789](https://github.com/pydantic/pydantic/pull/10789)
+* [@tamird](https://github.com/tamird) made their first contribution in [#10948](https://github.com/pydantic/pydantic/pull/10948)
+* [@felixxm](https://github.com/felixxm) made their first contribution in [#11077](https://github.com/pydantic/pydantic/pull/11077)
+* [@alexprabhat99](https://github.com/alexprabhat99) made their first contribution in [#11082](https://github.com/pydantic/pydantic/pull/11082)
+* [@Kharianne](https://github.com/Kharianne) made their first contribution in [#11111](https://github.com/pydantic/pydantic/pull/11111)
+* [@mdaffad](https://github.com/mdaffad) made their first contribution in [#11177](https://github.com/pydantic/pydantic/pull/11177)
+* [@thejcannon](https://github.com/thejcannon) made their first contribution in [#11014](https://github.com/pydantic/pydantic/pull/11014)
+* [@thomasfrimannkoren](https://github.com/thomasfrimannkoren) made their first contribution in [#11251](https://github.com/pydantic/pydantic/pull/11251)
+* [@usernameMAI](https://github.com/usernameMAI) made their first contribution in [#11275](https://github.com/pydantic/pydantic/pull/11275)
+* [@ananiavito](https://github.com/ananiavito) made their first contribution in [#11302](https://github.com/pydantic/pydantic/pull/11302)
+* [@pawamoy](https://github.com/pawamoy) made their first contribution in [#11311](https://github.com/pydantic/pydantic/pull/11311)
+* [@Maze21127](https://github.com/Maze21127) made their first contribution in [#11319](https://github.com/pydantic/pydantic/pull/11319)
+
+## v2.10.6 (2025-01-23)
+
+[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.10.6)
+
+### What's Changed
+
+#### Fixes
+
+* Fix JSON Schema reference collection with `'examples'` keys by [@Viicos](https://github.com/Viicos) in [#11325](https://github.com/pydantic/pydantic/pull/11325)
+* Fix url python serialization by [@sydney-runkle](https://github.com/sydney-runkle) in [#11331](https://github.com/pydantic/pydantic/pull/11331)
+
+## v2.10.5 (2025-01-08)
+
+[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.10.5)
+
+### What's Changed
+
+#### Fixes
+
+* Remove custom MRO implementation of Pydantic models by [@Viicos](https://github.com/Viicos) in [#11184](https://github.com/pydantic/pydantic/pull/11184)
+* Fix URL serialization for unions by [@sydney-runkle](https://github.com/sydney-runkle) in [#11233](https://github.com/pydantic/pydantic/pull/11233)
+
+## v2.10.4 (2024-12-18)
+
+[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.10.4)
+
+### What's Changed
+
+#### Packaging
+
+* Bump `pydantic-core` to v2.27.2 by [@davidhewitt](https://github.com/davidhewitt) in [#11138](https://github.com/pydantic/pydantic/pull/11138)
+
+#### Fixes
+
+* Fix for comparison of `AnyUrl` objects by [@alexprabhat99](https://github.com/alexprabhat99) in [#11082](https://github.com/pydantic/pydantic/pull/11082)
+* Properly fetch PEP 695 type params for functions, do not fetch annotations from signature by [@Viicos](https://github.com/Viicos) in [#11093](https://github.com/pydantic/pydantic/pull/11093)
+* Include JSON Schema input core schema in function schemas by [@Viicos](https://github.com/Viicos) in [#11085](https://github.com/pydantic/pydantic/pull/11085)
+* Add `len` to `_BaseUrl` to avoid TypeError by [@Kharianne](https://github.com/Kharianne) in [#11111](https://github.com/pydantic/pydantic/pull/11111)
+* Make sure the type reference is removed from the seen references by [@Viicos](https://github.com/Viicos) in [#11143](https://github.com/pydantic/pydantic/pull/11143)
+
+### New Contributors
+
+* [@FyZzyss](https://github.com/FyZzyss) made their first contribution in [#10789](https://github.com/pydantic/pydantic/pull/10789)
+* [@tamird](https://github.com/tamird) made their first contribution in [#10948](https://github.com/pydantic/pydantic/pull/10948)
+* [@felixxm](https://github.com/felixxm) made their first contribution in [#11077](https://github.com/pydantic/pydantic/pull/11077)
+* [@alexprabhat99](https://github.com/alexprabhat99) made their first contribution in [#11082](https://github.com/pydantic/pydantic/pull/11082)
+* [@Kharianne](https://github.com/Kharianne) made their first contribution in [#11111](https://github.com/pydantic/pydantic/pull/11111)
+
+## v2.10.3 (2024-12-03)
+
+[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.10.3)
+
+### What's Changed
+
+#### Fixes
+
+* Set fields when `defer_build` is set on Pydantic dataclasses by [@Viicos](https://github.com/Viicos) in [#10984](https://github.com/pydantic/pydantic/pull/10984)
+* Do not resolve the JSON Schema reference for `dict` core schema keys by [@Viicos](https://github.com/Viicos) in [#10989](https://github.com/pydantic/pydantic/pull/10989)
+* Use the globals of the function when evaluating the return type for `PlainSerializer` and `WrapSerializer` functions by [@Viicos](https://github.com/Viicos) in [#11008](https://github.com/pydantic/pydantic/pull/11008)
+* Fix host required enforcement for urls to be compatible with v2.9 behavior by [@sydney-runkle](https://github.com/sydney-runkle) in [#11027](https://github.com/pydantic/pydantic/pull/11027)
+* Add a `default_factory_takes_validated_data` property to `FieldInfo` by [@Viicos](https://github.com/Viicos) in [#11034](https://github.com/pydantic/pydantic/pull/11034)
+* Fix url json schema in `serialization` mode by [@sydney-runkle](https://github.com/sydney-runkle) in [#11035](https://github.com/pydantic/pydantic/pull/11035)
+
+## v2.10.2 (2024-11-25)
+
+[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.10.2)
+
+### What's Changed
+
+#### Fixes
+
+* Only evaluate FieldInfo annotations if required during schema building by [@Viicos](https://github.com/Viicos) in [#10769](https://github.com/pydantic/pydantic/pull/10769)
+* Do not evaluate annotations for private fields by [@Viicos](https://github.com/Viicos) in [#10962](https://github.com/pydantic/pydantic/pull/10962)
+* Support serialization as any for `Secret` types and `Url` types by [@sydney-runkle](https://github.com/sydney-runkle) in [#10947](https://github.com/pydantic/pydantic/pull/10947)
+* Fix type hint of `Field.default` to be compatible with Python 3.8 and 3.9 by [@Viicos](https://github.com/Viicos) in [#10972](https://github.com/pydantic/pydantic/pull/10972)
+* Add hashing support for URL types by [@sydney-runkle](https://github.com/sydney-runkle) in [#10975](https://github.com/pydantic/pydantic/pull/10975)
+* Hide `BaseModel.__replace__` definition from type checkers by [@Viicos](https://github.com/Viicos) in [#10979](https://github.com/pydantic/pydantic/pull/10979)
+
+## v2.10.1 (2024-11-21)
+
+[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.10.1)
+
+### What's Changed
+
+#### Packaging
+
+* Bump `pydantic-core` version to `v2.27.1` by [@sydney-runkle](https://github.com/sydney-runkle) in [#10938](https://github.com/pydantic/pydantic/pull/10938)
+
+#### Fixes
+
+* Use the correct frame when instantiating a parametrized `TypeAdapter` by [@Viicos](https://github.com/Viicos) in [#10893](https://github.com/pydantic/pydantic/pull/10893)
+* Relax check for validated data in `default_factory` utils by [@sydney-runkle](https://github.com/sydney-runkle) in [#10909](https://github.com/pydantic/pydantic/pull/10909)
+* Fix type checking issue with `model_fields` and `model_computed_fields` by [@sydney-runkle](https://github.com/sydney-runkle) in [#10911](https://github.com/pydantic/pydantic/pull/10911)
+* Use the parent configuration during schema generation for stdlib `dataclass`es by [@sydney-runkle](https://github.com/sydney-runkle) in [#10928](https://github.com/pydantic/pydantic/pull/10928)
+* Use the `globals` of the function when evaluating the return type of serializers and `computed_field`s by [@Viicos](https://github.com/Viicos) in [#10929](https://github.com/pydantic/pydantic/pull/10929)
+* Fix URL constraint application by [@sydney-runkle](https://github.com/sydney-runkle) in [#10922](https://github.com/pydantic/pydantic/pull/10922)
+* Fix URL equality with different validation methods by [@sydney-runkle](https://github.com/sydney-runkle) in [#10934](https://github.com/pydantic/pydantic/pull/10934)
+* Fix JSON schema title when specified as `''` by [@sydney-runkle](https://github.com/sydney-runkle) in [#10936](https://github.com/pydantic/pydantic/pull/10936)
+* Fix `python` mode serialization for `complex` inference by [@sydney-runkle](https://github.com/sydney-runkle) in [pydantic-core#1549](https://github.com/pydantic/pydantic-core/pull/1549)
+
+### New Contributors
+
+## v2.10.0 (2024-11-20)
+
+The code released in v2.10.0 is practically identical to that of v2.10.0b2.
+
+[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.10.0)
+
+See the [v2.10 release blog post](https://pydantic.dev/articles/pydantic-v2-10-release) for the highlights!
+
+### What's Changed
+
+#### Packaging
+
+* Bump `pydantic-core` to `v2.27.0` by [@sydney-runkle](https://github.com/sydney-runkle) in [#10825](https://github.com/pydantic/pydantic/pull/10825)
+* Replaced pdm with uv by [@frfahim](https://github.com/frfahim) in [#10727](https://github.com/pydantic/pydantic/pull/10727)
+
+#### New Features
+
+* Support `fractions.Fraction` by [@sydney-runkle](https://github.com/sydney-runkle) in [#10318](https://github.com/pydantic/pydantic/pull/10318)
+* Support `Hashable` for json validation by [@sydney-runkle](https://github.com/sydney-runkle) in [#10324](https://github.com/pydantic/pydantic/pull/10324)
+* Add a `SocketPath` type for `linux` systems by [@theunkn0wn1](https://github.com/theunkn0wn1) in [#10378](https://github.com/pydantic/pydantic/pull/10378)
+* Allow arbitrary refs in JSON schema `examples` by [@sydney-runkle](https://github.com/sydney-runkle) in [#10417](https://github.com/pydantic/pydantic/pull/10417)
+* Support `defer_build` for Pydantic dataclasses by [@Viicos](https://github.com/Viicos) in [#10313](https://github.com/pydantic/pydantic/pull/10313)
+* Adding v1 / v2 incompatibility warning for nested v1 model by [@sydney-runkle](https://github.com/sydney-runkle) in [#10431](https://github.com/pydantic/pydantic/pull/10431)
+* Add support for unpacked `TypedDict` to type hint variadic keyword arguments with `@validate_call` by [@Viicos](https://github.com/Viicos) in [#10416](https://github.com/pydantic/pydantic/pull/10416)
+* Support compiled patterns in `protected_namespaces` by [@sydney-runkle](https://github.com/sydney-runkle) in [#10522](https://github.com/pydantic/pydantic/pull/10522)
+* Add support for `propertyNames` in JSON schema by [@FlorianSW](https://github.com/FlorianSW) in [#10478](https://github.com/pydantic/pydantic/pull/10478)
+* Adding `__replace__` protocol for Python 3.13+ support by [@sydney-runkle](https://github.com/sydney-runkle) in [#10596](https://github.com/pydantic/pydantic/pull/10596)
+* Expose public `sort` method for JSON schema generation by [@sydney-runkle](https://github.com/sydney-runkle) in [#10595](https://github.com/pydantic/pydantic/pull/10595)
+* Add runtime validation of `@validate_call` callable argument by [@kc0506](https://github.com/kc0506) in [#10627](https://github.com/pydantic/pydantic/pull/10627)
+* Add `experimental_allow_partial` support by [@samuelcolvin](https://github.com/samuelcolvin) in [#10748](https://github.com/pydantic/pydantic/pull/10748)
+* Support default factories taking validated data as an argument by [@Viicos](https://github.com/Viicos) in [#10678](https://github.com/pydantic/pydantic/pull/10678)
+* Allow subclassing `ValidationError` and `PydanticCustomError` by [@Youssefares](https://github.com/Youssefares) in [pydantic/pydantic-core#1413](https://github.com/pydantic/pydantic-core/pull/1413)
+* Add `trailing-strings` support to `experimental_allow_partial` by [@sydney-runkle](https://github.com/sydney-runkle) in [#10825](https://github.com/pydantic/pydantic/pull/10825)
+* Add `rebuild()` method for `TypeAdapter` and simplify `defer_build` patterns by [@sydney-runkle](https://github.com/sydney-runkle) in [#10537](https://github.com/pydantic/pydantic/pull/10537)
+* Improve `TypeAdapter` instance repr by [@sydney-runkle](https://github.com/sydney-runkle) in [#10872](https://github.com/pydantic/pydantic/pull/10872)
+
+#### Changes
+
+* Don't allow customization of `SchemaGenerator` until interface is more stable by [@sydney-runkle](https://github.com/sydney-runkle) in [#10303](https://github.com/pydantic/pydantic/pull/10303)
+* Cleanly `defer_build` on `TypeAdapters`, removing experimental flag by [@sydney-runkle](https://github.com/sydney-runkle) in [#10329](https://github.com/pydantic/pydantic/pull/10329)
+* Fix `mro` of generic subclass  by [@kc0506](https://github.com/kc0506) in [#10100](https://github.com/pydantic/pydantic/pull/10100)
+* Strip whitespaces on JSON Schema title generation by [@sydney-runkle](https://github.com/sydney-runkle) in [#10404](https://github.com/pydantic/pydantic/pull/10404)
+* Use `b64decode` and `b64encode` for `Base64Bytes` type by [@sydney-runkle](https://github.com/sydney-runkle) in [#10486](https://github.com/pydantic/pydantic/pull/10486)
+* Relax protected namespace config default by [@sydney-runkle](https://github.com/sydney-runkle) in [#10441](https://github.com/pydantic/pydantic/pull/10441)
+* Revalidate parametrized generics if instance's origin is subclass of OG class by [@sydney-runkle](https://github.com/sydney-runkle) in [#10666](https://github.com/pydantic/pydantic/pull/10666)
+* Warn if configuration is specified on the `@dataclass` decorator and with the `__pydantic_config__` attribute by [@sydney-runkle](https://github.com/sydney-runkle) in [#10406](https://github.com/pydantic/pydantic/pull/10406)
+* Recommend against using `Ellipsis` (...) with `Field` by [@Viicos](https://github.com/Viicos) in [#10661](https://github.com/pydantic/pydantic/pull/10661)
+* Migrate to subclassing instead of annotated approach for pydantic url types by [@sydney-runkle](https://github.com/sydney-runkle) in [#10662](https://github.com/pydantic/pydantic/pull/10662)
+* Change JSON schema generation of `Literal`s and `Enums` by [@Viicos](https://github.com/Viicos) in [#10692](https://github.com/pydantic/pydantic/pull/10692)
+* Simplify unions involving `Any` or `Never` when replacing type variables by [@Viicos](https://github.com/Viicos) in [#10338](https://github.com/pydantic/pydantic/pull/10338)
+* Do not require padding when decoding `base64` bytes by [@bschoenmaeckers](https://github.com/bschoenmaeckers) in [pydantic/pydantic-core#1448](https://github.com/pydantic/pydantic-core/pull/1448)
+* Support dates all the way to 1BC by [@changhc](https://github.com/changhc) in [pydantic/speedate#77](https://github.com/pydantic/speedate/pull/77)
+
+#### Performance
+
+* Schema cleaning: skip unnecessary copies during schema walking by [@Viicos](https://github.com/Viicos) in [#10286](https://github.com/pydantic/pydantic/pull/10286)
+* Refactor namespace logic for annotations evaluation by [@Viicos](https://github.com/Viicos) in [#10530](https://github.com/pydantic/pydantic/pull/10530)
+* Improve email regexp on edge cases by [@AlekseyLobanov](https://github.com/AlekseyLobanov) in [#10601](https://github.com/pydantic/pydantic/pull/10601)
+* `CoreMetadata` refactor with an emphasis on documentation, schema build time performance, and reducing complexity by [@sydney-runkle](https://github.com/sydney-runkle) in [#10675](https://github.com/pydantic/pydantic/pull/10675)
+
+#### Fixes
+
+* Remove guarding check on `computed_field` with `field_serializer` by [@nix010](https://github.com/nix010) in [#10390](https://github.com/pydantic/pydantic/pull/10390)
+* Fix `Predicate` issue in `v2.9.0` by [@sydney-runkle](https://github.com/sydney-runkle) in [#10321](https://github.com/pydantic/pydantic/pull/10321)
+* Fixing `annotated-types` bound by [@sydney-runkle](https://github.com/sydney-runkle) in [#10327](https://github.com/pydantic/pydantic/pull/10327)
+* Turn `tzdata` install requirement into optional `timezone` dependency by [@jakob-keller](https://github.com/jakob-keller) in [#10331](https://github.com/pydantic/pydantic/pull/10331)
+* Use correct types namespace when building `namedtuple` core schemas by [@Viicos](https://github.com/Viicos) in [#10337](https://github.com/pydantic/pydantic/pull/10337)
+* Fix evaluation of stringified annotations during namespace inspection by [@Viicos](https://github.com/Viicos) in [#10347](https://github.com/pydantic/pydantic/pull/10347)
+* Fix `IncEx` type alias definition by [@Viicos](https://github.com/Viicos) in [#10339](https://github.com/pydantic/pydantic/pull/10339)
+* Do not error when trying to evaluate annotations of private attributes by [@Viicos](https://github.com/Viicos) in [#10358](https://github.com/pydantic/pydantic/pull/10358)
+* Fix nested type statement by [@kc0506](https://github.com/kc0506) in [#10369](https://github.com/pydantic/pydantic/pull/10369)
+* Improve typing of `ModelMetaclass.mro` by [@Viicos](https://github.com/Viicos) in [#10372](https://github.com/pydantic/pydantic/pull/10372)
+* Fix class access of deprecated `computed_field`s by [@Viicos](https://github.com/Viicos) in [#10391](https://github.com/pydantic/pydantic/pull/10391)
+* Make sure `inspect.iscoroutinefunction` works on coroutines decorated with `@validate_call` by [@MovisLi](https://github.com/MovisLi) in [#10374](https://github.com/pydantic/pydantic/pull/10374)
+* Fix `NameError` when using `validate_call` with PEP 695 on a class by [@kc0506](https://github.com/kc0506) in [#10380](https://github.com/pydantic/pydantic/pull/10380)
+* Fix `ZoneInfo` with various invalid types by [@sydney-runkle](https://github.com/sydney-runkle) in [#10408](https://github.com/pydantic/pydantic/pull/10408)
+* Fix `PydanticUserError` on empty `model_config` with annotations by [@cdwilson](https://github.com/cdwilson) in [#10412](https://github.com/pydantic/pydantic/pull/10412)
+* Fix variance issue in `_IncEx` type alias, only allow `True` by [@Viicos](https://github.com/Viicos) in [#10414](https://github.com/pydantic/pydantic/pull/10414)
+* Fix serialization schema generation when using `PlainValidator` by [@Viicos](https://github.com/Viicos) in [#10427](https://github.com/pydantic/pydantic/pull/10427)
+* Fix schema generation error when serialization schema holds references by [@Viicos](https://github.com/Viicos) in [#10444](https://github.com/pydantic/pydantic/pull/10444)
+* Inline references if possible when generating schema for `json_schema_input_type` by [@Viicos](https://github.com/Viicos) in [#10439](https://github.com/pydantic/pydantic/pull/10439)
+* Fix recursive arguments in `Representation` by [@Viicos](https://github.com/Viicos) in [#10480](https://github.com/pydantic/pydantic/pull/10480)
+* Fix representation for builtin function types by [@kschwab](https://github.com/kschwab) in [#10479](https://github.com/pydantic/pydantic/pull/10479)
+* Add python validators for decimal constraints (`max_digits` and `decimal_places`) by [@sydney-runkle](https://github.com/sydney-runkle) in [#10506](https://github.com/pydantic/pydantic/pull/10506)
+* Only fetch `__pydantic_core_schema__` from the current class during schema generation by [@Viicos](https://github.com/Viicos) in [#10518](https://github.com/pydantic/pydantic/pull/10518)
+* Fix `stacklevel` on deprecation warnings for `BaseModel` by [@sydney-runkle](https://github.com/sydney-runkle) in [#10520](https://github.com/pydantic/pydantic/pull/10520)
+* Fix warning `stacklevel` in `BaseModel.__init__` by [@Viicos](https://github.com/Viicos) in [#10526](https://github.com/pydantic/pydantic/pull/10526)
+* Improve error handling for in-evaluable refs for discriminator application by [@sydney-runkle](https://github.com/sydney-runkle) in [#10440](https://github.com/pydantic/pydantic/pull/10440)
+* Change the signature of `ConfigWrapper.core_config` to take the title directly by [@Viicos](https://github.com/Viicos) in [#10562](https://github.com/pydantic/pydantic/pull/10562)
+* Do not use the previous config from the stack for dataclasses without config by [@Viicos](https://github.com/Viicos) in [#10576](https://github.com/pydantic/pydantic/pull/10576)
+* Fix serialization for IP types with `mode='python'` by [@sydney-runkle](https://github.com/sydney-runkle) in [#10594](https://github.com/pydantic/pydantic/pull/10594)
+* Support constraint application for `Base64Etc` types by [@sydney-runkle](https://github.com/sydney-runkle) in [#10584](https://github.com/pydantic/pydantic/pull/10584)
+* Fix `validate_call` ignoring `Field` in `Annotated` by [@kc0506](https://github.com/kc0506) in [#10610](https://github.com/pydantic/pydantic/pull/10610)
+* Raise an error when `Self` is invalid by [@kc0506](https://github.com/kc0506) in [#10609](https://github.com/pydantic/pydantic/pull/10609)
+* Using `core_schema.InvalidSchema` instead of metadata injection + checks by [@sydney-runkle](https://github.com/sydney-runkle) in [#10523](https://github.com/pydantic/pydantic/pull/10523)
+* Tweak type alias logic by [@kc0506](https://github.com/kc0506) in [#10643](https://github.com/pydantic/pydantic/pull/10643)
+* Support usage of `type` with `typing.Self` and type aliases by [@kc0506](https://github.com/kc0506) in [#10621](https://github.com/pydantic/pydantic/pull/10621)
+* Use overloads for `Field` and `PrivateAttr` functions by [@Viicos](https://github.com/Viicos) in [#10651](https://github.com/pydantic/pydantic/pull/10651)
+* Clean up the `mypy` plugin implementation by [@Viicos](https://github.com/Viicos) in [#10669](https://github.com/pydantic/pydantic/pull/10669)
+* Properly check for `typing_extensions` variant of `TypeAliasType` by [@Daraan](https://github.com/Daraan) in [#10713](https://github.com/pydantic/pydantic/pull/10713)
+* Allow any mapping in `BaseModel.model_copy()` by [@Viicos](https://github.com/Viicos) in [#10751](https://github.com/pydantic/pydantic/pull/10751)
+* Fix `isinstance` behavior for urls by [@sydney-runkle](https://github.com/sydney-runkle) in [#10766](https://github.com/pydantic/pydantic/pull/10766)
+* Ensure `cached_property` can be set on Pydantic models by [@Viicos](https://github.com/Viicos) in [#10774](https://github.com/pydantic/pydantic/pull/10774)
+* Fix equality checks for primitives in literals by [@sydney-runkle](https://github.com/sydney-runkle) in [pydantic/pydantic-core#1459](https://github.com/pydantic/pydantic-core/pull/1459)
+* Properly enforce `host_required` for URLs by [@Viicos](https://github.com/Viicos) in [pydantic/pydantic-core#1488](https://github.com/pydantic/pydantic-core/pull/1488)
+* Fix when `coerce_numbers_to_str` enabled and string has invalid Unicode character by [@andrey-berenda](https://github.com/andrey-berenda) in [pydantic/pydantic-core#1515](https://github.com/pydantic/pydantic-core/pull/1515)
+* Fix serializing `complex` values in `Enum`s by [@changhc](https://github.com/changhc) in [pydantic/pydantic-core#1524](https://github.com/pydantic/pydantic-core/pull/1524)
+* Refactor `_typing_extra` module by [@Viicos](https://github.com/Viicos) in [#10725](https://github.com/pydantic/pydantic/pull/10725)
+* Support intuitive equality for urls by [@sydney-runkle](https://github.com/sydney-runkle) in [#10798](https://github.com/pydantic/pydantic/pull/10798)
+* Add `bytearray` to `TypeAdapter.validate_json` signature by [@samuelcolvin](https://github.com/samuelcolvin) in [#10802](https://github.com/pydantic/pydantic/pull/10802)
+* Ensure class access of method descriptors is performed when used as a default with `Field` by [@Viicos](https://github.com/Viicos) in [#10816](https://github.com/pydantic/pydantic/pull/10816)
+* Fix circular import with `validate_call` by [@sydney-runkle](https://github.com/sydney-runkle) in [#10807](https://github.com/pydantic/pydantic/pull/10807)
+* Fix error when using type aliases referencing other type aliases by [@Viicos](https://github.com/Viicos) in [#10809](https://github.com/pydantic/pydantic/pull/10809)
+* Fix `IncEx` type alias to be compatible with mypy by [@Viicos](https://github.com/Viicos) in [#10813](https://github.com/pydantic/pydantic/pull/10813)
+* Make `__signature__` a lazy property, do not deepcopy defaults by [@Viicos](https://github.com/Viicos) in [#10818](https://github.com/pydantic/pydantic/pull/10818)
+* Make `__signature__` lazy for dataclasses, too by [@sydney-runkle](https://github.com/sydney-runkle) in [#10832](https://github.com/pydantic/pydantic/pull/10832)
+* Subclass all single host url classes from `AnyUrl` to preserve behavior from v2.9 by [@sydney-runkle](https://github.com/sydney-runkle) in [#10856](https://github.com/pydantic/pydantic/pull/10856)
+
+### New Contributors
+
+* [@jakob-keller](https://github.com/jakob-keller) made their first contribution in [#10331](https://github.com/pydantic/pydantic/pull/10331)
+* [@MovisLi](https://github.com/MovisLi) made their first contribution in [#10374](https://github.com/pydantic/pydantic/pull/10374)
+* [@joaopalmeiro](https://github.com/joaopalmeiro) made their first contribution in [#10405](https://github.com/pydantic/pydantic/pull/10405)
+* [@theunkn0wn1](https://github.com/theunkn0wn1) made their first contribution in [#10378](https://github.com/pydantic/pydantic/pull/10378)
+* [@cdwilson](https://github.com/cdwilson) made their first contribution in [#10412](https://github.com/pydantic/pydantic/pull/10412)
+* [@dlax](https://github.com/dlax) made their first contribution in [#10421](https://github.com/pydantic/pydantic/pull/10421)
+* [@kschwab](https://github.com/kschwab) made their first contribution in [#10479](https://github.com/pydantic/pydantic/pull/10479)
+* [@santibreo](https://github.com/santibreo) made their first contribution in [#10453](https://github.com/pydantic/pydantic/pull/10453)
+* [@FlorianSW](https://github.com/FlorianSW) made their first contribution in [#10478](https://github.com/pydantic/pydantic/pull/10478)
+* [@tkasuz](https://github.com/tkasuz) made their first contribution in [#10555](https://github.com/pydantic/pydantic/pull/10555)
+* [@AlekseyLobanov](https://github.com/AlekseyLobanov) made their first contribution in [#10601](https://github.com/pydantic/pydantic/pull/10601)
+* [@NiclasvanEyk](https://github.com/NiclasvanEyk) made their first contribution in [#10667](https://github.com/pydantic/pydantic/pull/10667)
+* [@mschoettle](https://github.com/mschoettle) made their first contribution in [#10677](https://github.com/pydantic/pydantic/pull/10677)
+* [@Daraan](https://github.com/Daraan) made their first contribution in [#10713](https://github.com/pydantic/pydantic/pull/10713)
+* [@k4nar](https://github.com/k4nar) made their first contribution in [#10736](https://github.com/pydantic/pydantic/pull/10736)
+* [@UriyaHarpeness](https://github.com/UriyaHarpeness) made their first contribution in [#10740](https://github.com/pydantic/pydantic/pull/10740)
+* [@frfahim](https://github.com/frfahim) made their first contribution in [#10727](https://github.com/pydantic/pydantic/pull/10727)
+
+## v2.10.0b2 (2024-11-13)
+
+Pre-release, see [the GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.10.0b2) for details.
+
+## v2.10.0b1 (2024-11-06)
+
+Pre-release, see [the GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.10.0b1) for details.
+
+
+... see [here](https://docs.pydantic.dev/changelog/#v0322-2019-08-17) for earlier changes.
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pydantic-2.12.5.dist-info/RECORD b/TTS/Kokoro/.venv/Lib/site-packages/pydantic-2.12.5.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..532d6f6c80eb75437a87eb011a2c0da241415ed0
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pydantic-2.12.5.dist-info/RECORD
@@ -0,0 +1,217 @@
+pydantic-2.12.5.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+pydantic-2.12.5.dist-info/METADATA,sha256=o7oj6JUZH-1puDI8vLzcgphMoLajzcYsSKI0GIapwI0,90587
+pydantic-2.12.5.dist-info/RECORD,,
+pydantic-2.12.5.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
+pydantic-2.12.5.dist-info/licenses/LICENSE,sha256=qeGG88oWte74QxjnpwFyE1GgDLe4rjpDlLZ7SeNSnvM,1129
+pydantic/__init__.py,sha256=5iEnJ4wHv1OEzdKQPzaKaZKfO4pSQAC65ODrYI6_S8Y,15812
+pydantic/__pycache__/__init__.cpython-312.pyc,,
+pydantic/__pycache__/_migration.cpython-312.pyc,,
+pydantic/__pycache__/alias_generators.cpython-312.pyc,,
+pydantic/__pycache__/aliases.cpython-312.pyc,,
+pydantic/__pycache__/annotated_handlers.cpython-312.pyc,,
+pydantic/__pycache__/class_validators.cpython-312.pyc,,
+pydantic/__pycache__/color.cpython-312.pyc,,
+pydantic/__pycache__/config.cpython-312.pyc,,
+pydantic/__pycache__/dataclasses.cpython-312.pyc,,
+pydantic/__pycache__/datetime_parse.cpython-312.pyc,,
+pydantic/__pycache__/decorator.cpython-312.pyc,,
+pydantic/__pycache__/env_settings.cpython-312.pyc,,
+pydantic/__pycache__/error_wrappers.cpython-312.pyc,,
+pydantic/__pycache__/errors.cpython-312.pyc,,
+pydantic/__pycache__/fields.cpython-312.pyc,,
+pydantic/__pycache__/functional_serializers.cpython-312.pyc,,
+pydantic/__pycache__/functional_validators.cpython-312.pyc,,
+pydantic/__pycache__/generics.cpython-312.pyc,,
+pydantic/__pycache__/json.cpython-312.pyc,,
+pydantic/__pycache__/json_schema.cpython-312.pyc,,
+pydantic/__pycache__/main.cpython-312.pyc,,
+pydantic/__pycache__/mypy.cpython-312.pyc,,
+pydantic/__pycache__/networks.cpython-312.pyc,,
+pydantic/__pycache__/parse.cpython-312.pyc,,
+pydantic/__pycache__/root_model.cpython-312.pyc,,
+pydantic/__pycache__/schema.cpython-312.pyc,,
+pydantic/__pycache__/tools.cpython-312.pyc,,
+pydantic/__pycache__/type_adapter.cpython-312.pyc,,
+pydantic/__pycache__/types.cpython-312.pyc,,
+pydantic/__pycache__/typing.cpython-312.pyc,,
+pydantic/__pycache__/utils.cpython-312.pyc,,
+pydantic/__pycache__/validate_call_decorator.cpython-312.pyc,,
+pydantic/__pycache__/validators.cpython-312.pyc,,
+pydantic/__pycache__/version.cpython-312.pyc,,
+pydantic/__pycache__/warnings.cpython-312.pyc,,
+pydantic/_internal/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pydantic/_internal/__pycache__/__init__.cpython-312.pyc,,
+pydantic/_internal/__pycache__/_config.cpython-312.pyc,,
+pydantic/_internal/__pycache__/_core_metadata.cpython-312.pyc,,
+pydantic/_internal/__pycache__/_core_utils.cpython-312.pyc,,
+pydantic/_internal/__pycache__/_dataclasses.cpython-312.pyc,,
+pydantic/_internal/__pycache__/_decorators.cpython-312.pyc,,
+pydantic/_internal/__pycache__/_decorators_v1.cpython-312.pyc,,
+pydantic/_internal/__pycache__/_discriminated_union.cpython-312.pyc,,
+pydantic/_internal/__pycache__/_docs_extraction.cpython-312.pyc,,
+pydantic/_internal/__pycache__/_fields.cpython-312.pyc,,
+pydantic/_internal/__pycache__/_forward_ref.cpython-312.pyc,,
+pydantic/_internal/__pycache__/_generate_schema.cpython-312.pyc,,
+pydantic/_internal/__pycache__/_generics.cpython-312.pyc,,
+pydantic/_internal/__pycache__/_git.cpython-312.pyc,,
+pydantic/_internal/__pycache__/_import_utils.cpython-312.pyc,,
+pydantic/_internal/__pycache__/_internal_dataclass.cpython-312.pyc,,
+pydantic/_internal/__pycache__/_known_annotated_metadata.cpython-312.pyc,,
+pydantic/_internal/__pycache__/_mock_val_ser.cpython-312.pyc,,
+pydantic/_internal/__pycache__/_model_construction.cpython-312.pyc,,
+pydantic/_internal/__pycache__/_namespace_utils.cpython-312.pyc,,
+pydantic/_internal/__pycache__/_repr.cpython-312.pyc,,
+pydantic/_internal/__pycache__/_schema_gather.cpython-312.pyc,,
+pydantic/_internal/__pycache__/_schema_generation_shared.cpython-312.pyc,,
+pydantic/_internal/__pycache__/_serializers.cpython-312.pyc,,
+pydantic/_internal/__pycache__/_signature.cpython-312.pyc,,
+pydantic/_internal/__pycache__/_typing_extra.cpython-312.pyc,,
+pydantic/_internal/__pycache__/_utils.cpython-312.pyc,,
+pydantic/_internal/__pycache__/_validate_call.cpython-312.pyc,,
+pydantic/_internal/__pycache__/_validators.cpython-312.pyc,,
+pydantic/_internal/_config.py,sha256=TWZwg3c0bZHiT3boR5-YYqkouHcwjRdenmyGHofV7E0,14674
+pydantic/_internal/_core_metadata.py,sha256=Y_g2t3i7uluK-wXCZvzJfRFMPUM23aBYLfae4FzBPy0,5162
+pydantic/_internal/_core_utils.py,sha256=1jru4VbJ0x63R6dtVcuOI-dKQTC_d_lSnJWEBQzGNEQ,6487
+pydantic/_internal/_dataclasses.py,sha256=Tk1mEafhad1kV7K5tPX5BwxWSXY7C-MKwf0OLFgIlEA,13158
+pydantic/_internal/_decorators.py,sha256=PnyAoKSg3BNbCVSZnwqw9naEg1UDtYvDT9LluigPiO8,33529
+pydantic/_internal/_decorators_v1.py,sha256=tfdfdpQKY4R2XCOwqHbZeoQMur6VNigRrfhudXBHx38,6185
+pydantic/_internal/_discriminated_union.py,sha256=aMl0SRSyQyHfW4-klnMTHNvwSRoqE3H3PRV_05vRsTg,25478
+pydantic/_internal/_docs_extraction.py,sha256=fyznSAHh5AzohnXZStV0HvH-nRbavNHPyg-knx-S_EE,4127
+pydantic/_internal/_fields.py,sha256=YSfEKq21FgjLJ6YqYXKh0eEEs5nxMPvQ6hp9pA8Nzfw,28093
+pydantic/_internal/_forward_ref.py,sha256=5n3Y7-3AKLn8_FS3Yc7KutLiPUhyXmAtkEZOaFnonwM,611
+pydantic/_internal/_generate_schema.py,sha256=TT49vzYzqH90rWrv5ptNoZgjzOsR0KPlSkqPVFrnrBw,132665
+pydantic/_internal/_generics.py,sha256=ELqjT6LMzQzWAK0EB5_9qke_iAazz0OQ4gunp_uKuYY,23822
+pydantic/_internal/_git.py,sha256=IwPh3DPfa2Xq3rBuB9Nx8luR2A1i69QdeTfWWXIuCVg,809
+pydantic/_internal/_import_utils.py,sha256=TRhxD5OuY6CUosioBdBcJUs0om7IIONiZdYAV7zQ8jM,402
+pydantic/_internal/_internal_dataclass.py,sha256=_bedc1XbuuygRGiLZqkUkwwFpQaoR1hKLlR501nyySY,144
+pydantic/_internal/_known_annotated_metadata.py,sha256=Jc7KTNFZoB3f-0ibP_NgJINOeVvYE3q3OTBQDjVMk3U,16765
+pydantic/_internal/_mock_val_ser.py,sha256=wmRRFSBvqfcLbI41PsFliB4u2AZ3mJpZeiERbD3xKTo,8885
+pydantic/_internal/_model_construction.py,sha256=wk-bNGDAJvduaGvn0U0_8zEl0GERu0shJvN8_ZfkYaw,37783
+pydantic/_internal/_namespace_utils.py,sha256=hl3-TRAr82U2jTyPP3t-QqsvKLirxtkLfNfrN-fp0x8,12878
+pydantic/_internal/_repr.py,sha256=jQfnJuyDxQpSRNhG29II9PX8e4Nv2qWZrEw2lqih3UE,5172
+pydantic/_internal/_schema_gather.py,sha256=VLEv51TYEeeND2czsyrmJq1MVnJqTOmnLan7VG44c8A,9114
+pydantic/_internal/_schema_generation_shared.py,sha256=F_rbQbrkoomgxsskdHpP0jUJ7TCfe0BADAEkq6CJ4nM,4842
+pydantic/_internal/_serializers.py,sha256=YIWvSmAR5fnbGSWCOQduWt1yB4ZQY42eAruc-enrb6c,1491
+pydantic/_internal/_signature.py,sha256=8EljPJe4pSnapuirG5DkBAgD1hggHxEAyzFPH-9H0zE,6779
+pydantic/_internal/_typing_extra.py,sha256=_GRYopNi4a9USi5UQ285ObrlsYmvqKEWTNbBoJFSK2c,30309
+pydantic/_internal/_utils.py,sha256=c6Naqf3bds4jBctepiW5jV0xISQQQk5EBUhMNmVQ3Nk,15912
+pydantic/_internal/_validate_call.py,sha256=PfdVnSzhXOrENtaDoDw3PFWPVYD5W_gNYPe8p3Ug6Lg,5321
+pydantic/_internal/_validators.py,sha256=dv0a2Nkc4zcYqv31Gh_QId2lcf-W0kQpV0oSNzgEdfg,20588
+pydantic/_migration.py,sha256=VF73LRCUz3Irb5xVt13jb3NAcXVnEF6T1-J0OLfeZ5A,12160
+pydantic/alias_generators.py,sha256=KM1n3u4JfLSBl1UuYg3hoYHzXJD-yvgrnq8u1ccwh_A,2124
+pydantic/aliases.py,sha256=vhCHyoSWnX-EJ-wWb5qj4xyRssgGWnTQfzQp4GSZ9ug,4937
+pydantic/annotated_handlers.py,sha256=WfyFSqwoEIFXBh7T73PycKloI1DiX45GWi0-JOsCR4Y,4407
+pydantic/class_validators.py,sha256=i_V3j-PYdGLSLmj_IJZekTRjunO8SIVz8LMlquPyP7E,148
+pydantic/color.py,sha256=AzqGfVQHF92_ZctDcue0DM4yTp2P6tekkwRINTWrLIo,21481
+pydantic/config.py,sha256=5MjjzlAR0_xq7C1yAEPf7qWp5qraQwStRvma9nzbqVI,44267
+pydantic/dataclasses.py,sha256=VlknbEulg08xdmPg_60hBsCVIw-W603OJWY2n5gyXA0,18936
+pydantic/datetime_parse.py,sha256=QC-WgMxMr_wQ_mNXUS7AVf-2hLEhvvsPY1PQyhSGOdk,150
+pydantic/decorator.py,sha256=YX-jUApu5AKaVWKPoaV-n-4l7UbS69GEt9Ra3hszmKI,145
+pydantic/deprecated/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pydantic/deprecated/__pycache__/__init__.cpython-312.pyc,,
+pydantic/deprecated/__pycache__/class_validators.cpython-312.pyc,,
+pydantic/deprecated/__pycache__/config.cpython-312.pyc,,
+pydantic/deprecated/__pycache__/copy_internals.cpython-312.pyc,,
+pydantic/deprecated/__pycache__/decorator.cpython-312.pyc,,
+pydantic/deprecated/__pycache__/json.cpython-312.pyc,,
+pydantic/deprecated/__pycache__/parse.cpython-312.pyc,,
+pydantic/deprecated/__pycache__/tools.cpython-312.pyc,,
+pydantic/deprecated/class_validators.py,sha256=EAcaVQM5zp2wBml0ybN62CfQfyJvDLx5Qd9Pk4_tb4U,10273
+pydantic/deprecated/config.py,sha256=k_lsVk57paxLJOcBueH07cu1OgEgWdVBxm6lfaC3CCU,2663
+pydantic/deprecated/copy_internals.py,sha256=Ghd-vkMd5EYCCgyCGtPKO58np9cEKBQC6qkBeIEFI2g,7618
+pydantic/deprecated/decorator.py,sha256=TBm6bJ7wJsNih_8Wq5IzDcwP32m9_vfxs96desLuk00,10845
+pydantic/deprecated/json.py,sha256=HlWCG35RRrxyzuTS6LTQiZBwRhmDZWmeqQH8rLW6wA8,4657
+pydantic/deprecated/parse.py,sha256=Gzd6b_g8zJXcuE7QRq5adhx_EMJahXfcpXCF0RgrqqI,2511
+pydantic/deprecated/tools.py,sha256=Nrm9oFRZWp8-jlfvPgJILEsywp4YzZD52XIGPDLxHcI,3330
+pydantic/env_settings.py,sha256=6IHeeWEqlUPRUv3V-AXiF_W91fg2Jw_M3O0l34J_eyA,148
+pydantic/error_wrappers.py,sha256=RK6mqATc9yMD-KBD9IJS9HpKCprWHd8wo84Bnm-3fR8,150
+pydantic/errors.py,sha256=7ctBNCtt57kZFx71Ls2H86IufQARv4wPKf8DhdsVn5w,6002
+pydantic/experimental/__init__.py,sha256=QT7rKYdDsCiTJ9GEjmsQdWHScwpKrrNkGq6vqONP6RQ,104
+pydantic/experimental/__pycache__/__init__.cpython-312.pyc,,
+pydantic/experimental/__pycache__/arguments_schema.cpython-312.pyc,,
+pydantic/experimental/__pycache__/missing_sentinel.cpython-312.pyc,,
+pydantic/experimental/__pycache__/pipeline.cpython-312.pyc,,
+pydantic/experimental/arguments_schema.py,sha256=EFnjX_ulp-tPyUjQX5pmQtug1OFL_Acc8bcMbLd-fVY,1866
+pydantic/experimental/missing_sentinel.py,sha256=hQejgtF00wUuQMni9429evg-eXyIwpKvjsD8ofqfj-w,127
+pydantic/experimental/pipeline.py,sha256=Kv_dvcexKumazfRL0y69AayeA6H37SrmsZ3SUl_n0qY,23582
+pydantic/fields.py,sha256=WuDGOvB22KWuuW3fXnS4Wvg4qX_tdp8X7BrAlza4sw8,79194
+pydantic/functional_serializers.py,sha256=rEzH391zqy3o_bWk2QEuvySmcQNZmwXmJQLC3ZGF7QA,17151
+pydantic/functional_validators.py,sha256=c_-7weWpGNcOYfRfVUFu11jrxMVMdfY_c-4istwk95Y,31839
+pydantic/generics.py,sha256=0ZqZ9O9annIj_3mGBRqps4htey3b5lV1-d2tUxPMMnA,144
+pydantic/json.py,sha256=ZH8RkI7h4Bz-zp8OdTAxbJUoVvcoU-jhMdRZ0B-k0xc,140
+pydantic/json_schema.py,sha256=-h8c7vsNGAJCIxR-n52-69Q54w38EM-j0AGC_4VGt30,123653
+pydantic/main.py,sha256=WZTxwW81igl75Y00zHJJmoU3qCNSy-1KCEmEsBPftiQ,84205
+pydantic/mypy.py,sha256=p6KU1GwPHazF7E5vJq1uLd4tHd6DE6bre4-m5Ln23ms,58986
+pydantic/networks.py,sha256=Smf_RyImQ-F5FZLCgFwHPfROYxW_e-Hz68R_8LW0sZ0,42099
+pydantic/parse.py,sha256=wkd82dgtvWtD895U_I6E1htqMlGhBSYEV39cuBSeo3A,141
+pydantic/plugin/__init__.py,sha256=a7Tw366U6K3kltCCNZY76nc9ss-7uGGQ40TXad9OypQ,7333
+pydantic/plugin/__pycache__/__init__.cpython-312.pyc,,
+pydantic/plugin/__pycache__/_loader.cpython-312.pyc,,
+pydantic/plugin/__pycache__/_schema_validator.cpython-312.pyc,,
+pydantic/plugin/_loader.py,sha256=9QLXneLEmvyhXka_9j4Lrkbme4qPv6qYphlsjF2MGsA,2210
+pydantic/plugin/_schema_validator.py,sha256=QbmqsG33MBmftNQ2nNiuN22LhbrexUA7ipDVv3J02BU,5267
+pydantic/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pydantic/root_model.py,sha256=BvmLtW4i11dJk-dLOM3rl-jnJdQGeeQTFBcmEOq6pMg,6311
+pydantic/schema.py,sha256=Vqqjvq_LnapVknebUd3Bp_J1p2gXZZnZRgL48bVEG7o,142
+pydantic/tools.py,sha256=iHQpd8SJ5DCTtPV5atAV06T89bjSaMFeZZ2LX9lasZY,141
+pydantic/type_adapter.py,sha256=VT--yg4a27shSBzWHBPKz493f3iQ9obdkEkhjZKlE7Q,35653
+pydantic/types.py,sha256=nqdS-J2ZXqTh2qeyJOzBTBtHWyZ5YRFe8gaMV59d9HE,105431
+pydantic/typing.py,sha256=P7feA35MwTcLsR1uL7db0S-oydBxobmXa55YDoBgajQ,138
+pydantic/utils.py,sha256=15nR2QpqTBFlQV4TNtTItMyTJx_fbyV-gPmIEY1Gooc,141
+pydantic/v1/__init__.py,sha256=FLQ8ISp6MVZRfjnS7fQ4m1FxQxFCF2QVikE4DK-4PhE,3164
+pydantic/v1/__pycache__/__init__.cpython-312.pyc,,
+pydantic/v1/__pycache__/_hypothesis_plugin.cpython-312.pyc,,
+pydantic/v1/__pycache__/annotated_types.cpython-312.pyc,,
+pydantic/v1/__pycache__/class_validators.cpython-312.pyc,,
+pydantic/v1/__pycache__/color.cpython-312.pyc,,
+pydantic/v1/__pycache__/config.cpython-312.pyc,,
+pydantic/v1/__pycache__/dataclasses.cpython-312.pyc,,
+pydantic/v1/__pycache__/datetime_parse.cpython-312.pyc,,
+pydantic/v1/__pycache__/decorator.cpython-312.pyc,,
+pydantic/v1/__pycache__/env_settings.cpython-312.pyc,,
+pydantic/v1/__pycache__/error_wrappers.cpython-312.pyc,,
+pydantic/v1/__pycache__/errors.cpython-312.pyc,,
+pydantic/v1/__pycache__/fields.cpython-312.pyc,,
+pydantic/v1/__pycache__/generics.cpython-312.pyc,,
+pydantic/v1/__pycache__/json.cpython-312.pyc,,
+pydantic/v1/__pycache__/main.cpython-312.pyc,,
+pydantic/v1/__pycache__/mypy.cpython-312.pyc,,
+pydantic/v1/__pycache__/networks.cpython-312.pyc,,
+pydantic/v1/__pycache__/parse.cpython-312.pyc,,
+pydantic/v1/__pycache__/schema.cpython-312.pyc,,
+pydantic/v1/__pycache__/tools.cpython-312.pyc,,
+pydantic/v1/__pycache__/types.cpython-312.pyc,,
+pydantic/v1/__pycache__/typing.cpython-312.pyc,,
+pydantic/v1/__pycache__/utils.cpython-312.pyc,,
+pydantic/v1/__pycache__/validators.cpython-312.pyc,,
+pydantic/v1/__pycache__/version.cpython-312.pyc,,
+pydantic/v1/_hypothesis_plugin.py,sha256=5ES5xWuw1FQAsymLezy8QgnVz0ZpVfU3jkmT74H27VQ,14847
+pydantic/v1/annotated_types.py,sha256=uk2NAAxqiNELKjiHhyhxKaIOh8F1lYW_LzrW3X7oZBc,3157
+pydantic/v1/class_validators.py,sha256=ULOaIUgYUDBsHL7EEVEarcM-UubKUggoN8hSbDonsFE,14672
+pydantic/v1/color.py,sha256=iZABLYp6OVoo2AFkP9Ipri_wSc6-Kklu8YuhSartd5g,16844
+pydantic/v1/config.py,sha256=a6P0Wer9x4cbwKW7Xv8poSUqM4WP-RLWwX6YMpYq9AA,6532
+pydantic/v1/dataclasses.py,sha256=784cqvInbwIPWr9usfpX3ch7z4t3J2tTK6N067_wk1o,18172
+pydantic/v1/datetime_parse.py,sha256=4Qy1kQpq3rNVZJeIHeSPDpuS2Bvhp1KPtzJG1xu-H00,7724
+pydantic/v1/decorator.py,sha256=zaaxxxoWPCm818D1bs0yhapRjXm32V8G0ZHWCdM1uXA,10339
+pydantic/v1/env_settings.py,sha256=A9VXwtRl02AY-jH0C0ouy5VNw3fi6F_pkzuHDjgAAOM,14105
+pydantic/v1/error_wrappers.py,sha256=6625Mfw9qkC2NwitB_JFAWe8B-Xv6zBU7rL9k28tfyo,5196
+pydantic/v1/errors.py,sha256=mIwPED5vGM5Q5v4C4Z1JPldTRH-omvEylH6ksMhOmPw,17726
+pydantic/v1/fields.py,sha256=VqWJCriUNiEyptXroDVJ501JpVA0en2VANcksqXL2b8,50649
+pydantic/v1/generics.py,sha256=VzC9YUV-EbPpQ3aAfk1cNFej79_IzznkQ7WrmTTZS9E,17871
+pydantic/v1/json.py,sha256=WQ5Hy_hIpfdR3YS8k6N2E6KMJzsdbBi_ldWOPJaV81M,3390
+pydantic/v1/main.py,sha256=zuNpdN5Q0V0wG2UUTKt0HUy3XJ4OAvPSZDdiXY-FIzs,44824
+pydantic/v1/mypy.py,sha256=Cl8XRfCmIcVE3j5AEU52C8iDh8lcX__D3hz2jIWxMAs,38860
+pydantic/v1/networks.py,sha256=HYNtKAfOmOnKJpsDg1g6SIkj9WPhU_-i8l5e2JKBpG4,22124
+pydantic/v1/parse.py,sha256=BJtdqiZRtav9VRFCmOxoY-KImQmjPy-A_NoojiFUZxY,1821
+pydantic/v1/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pydantic/v1/schema.py,sha256=aqBuA--cq8gAVkim5BJPFASHzOZ8dFtmFX_fNGr6ip4,47801
+pydantic/v1/tools.py,sha256=1lDdXHk0jL5uP3u5RCYAvUAlGClgAO-45lkq9j7fyBA,2881
+pydantic/v1/types.py,sha256=Bzl-RcnitPBHnqwwj9iv7JjHuN1GpnWH24dKkF3l9e8,35455
+pydantic/v1/typing.py,sha256=7GdBg1YTHULU81thB_9cjRNDfZfn4khoX7nGtw_keCE,19677
+pydantic/v1/utils.py,sha256=M5FRyfNUb1A2mk9laGgCVdfHHb3AtQgrjO5qfyBf4xA,25989
+pydantic/v1/validators.py,sha256=lyUkn1MWhHxlCX5ZfEgFj_CAHojoiPcaQeMdEM9XviU,22187
+pydantic/v1/version.py,sha256=HXnXW-1bMW5qKhlr5RgOEPohrZDCDSuyy8-gi8GCgZo,1039
+pydantic/validate_call_decorator.py,sha256=8jqLlgXTjWEj4dXDg0wI3EGQKkb0JnCsL_JSUjbU5Sg,4389
+pydantic/validators.py,sha256=pwbIJXVb1CV2mAE4w_EGfNj7DwzsKaWw_tTL6cviTus,146
+pydantic/version.py,sha256=XNmGSyOP87Mqa_A9HFzfDcNippfnqfRK3ZUiGyBb4-A,3985
+pydantic/warnings.py,sha256=Wu1VGzrvFZw4T6yCIKHjH7LSY66HjbtyCFbn5uWoMJ4,4802
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pydantic-2.12.5.dist-info/WHEEL b/TTS/Kokoro/.venv/Lib/site-packages/pydantic-2.12.5.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..12228d414b6cfed7c39d3781c85c63256a1d7fb5
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pydantic-2.12.5.dist-info/WHEEL
@@ -0,0 +1,4 @@
+Wheel-Version: 1.0
+Generator: hatchling 1.27.0
+Root-Is-Purelib: true
+Tag: py3-none-any
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pydantic/__init__.py b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..01212849e733d8f07df79b27f328a294c54d7fe3
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/__init__.py
@@ -0,0 +1,456 @@
+from importlib import import_module
+from typing import TYPE_CHECKING
+from warnings import warn
+
+from ._migration import getattr_migration
+from .version import VERSION, _ensure_pydantic_core_version
+
+_ensure_pydantic_core_version()
+del _ensure_pydantic_core_version
+
+if TYPE_CHECKING:
+    # import of virtually everything is supported via `__getattr__` below,
+    # but we need them here for type checking and IDE support
+    import pydantic_core
+    from pydantic_core.core_schema import (
+        FieldSerializationInfo,
+        SerializationInfo,
+        SerializerFunctionWrapHandler,
+        ValidationInfo,
+        ValidatorFunctionWrapHandler,
+    )
+
+    from . import dataclasses
+    from .aliases import AliasChoices, AliasGenerator, AliasPath
+    from .annotated_handlers import GetCoreSchemaHandler, GetJsonSchemaHandler
+    from .config import ConfigDict, with_config
+    from .errors import *
+    from .fields import Field, PrivateAttr, computed_field
+    from .functional_serializers import (
+        PlainSerializer,
+        SerializeAsAny,
+        WrapSerializer,
+        field_serializer,
+        model_serializer,
+    )
+    from .functional_validators import (
+        AfterValidator,
+        BeforeValidator,
+        InstanceOf,
+        ModelWrapValidatorHandler,
+        PlainValidator,
+        SkipValidation,
+        ValidateAs,
+        WrapValidator,
+        field_validator,
+        model_validator,
+    )
+    from .json_schema import WithJsonSchema
+    from .main import *
+    from .networks import *
+    from .type_adapter import TypeAdapter
+    from .types import *
+    from .validate_call_decorator import validate_call
+    from .warnings import (
+        PydanticDeprecatedSince20,
+        PydanticDeprecatedSince26,
+        PydanticDeprecatedSince29,
+        PydanticDeprecatedSince210,
+        PydanticDeprecatedSince211,
+        PydanticDeprecatedSince212,
+        PydanticDeprecationWarning,
+        PydanticExperimentalWarning,
+    )
+
+    # this encourages pycharm to import `ValidationError` from here, not pydantic_core
+    ValidationError = pydantic_core.ValidationError
+    from .deprecated.class_validators import root_validator, validator
+    from .deprecated.config import BaseConfig, Extra
+    from .deprecated.tools import *
+    from .root_model import RootModel
+
+__version__ = VERSION
+__all__ = (
+    # dataclasses
+    'dataclasses',
+    # functional validators
+    'field_validator',
+    'model_validator',
+    'AfterValidator',
+    'BeforeValidator',
+    'PlainValidator',
+    'WrapValidator',
+    'SkipValidation',
+    'ValidateAs',
+    'InstanceOf',
+    'ModelWrapValidatorHandler',
+    # JSON Schema
+    'WithJsonSchema',
+    # deprecated V1 functional validators, these are imported via `__getattr__` below
+    'root_validator',
+    'validator',
+    # functional serializers
+    'field_serializer',
+    'model_serializer',
+    'PlainSerializer',
+    'SerializeAsAny',
+    'WrapSerializer',
+    # config
+    'ConfigDict',
+    'with_config',
+    # deprecated V1 config, these are imported via `__getattr__` below
+    'BaseConfig',
+    'Extra',
+    # validate_call
+    'validate_call',
+    # errors
+    'PydanticErrorCodes',
+    'PydanticUserError',
+    'PydanticSchemaGenerationError',
+    'PydanticImportError',
+    'PydanticUndefinedAnnotation',
+    'PydanticInvalidForJsonSchema',
+    'PydanticForbiddenQualifier',
+    # fields
+    'Field',
+    'computed_field',
+    'PrivateAttr',
+    # alias
+    'AliasChoices',
+    'AliasGenerator',
+    'AliasPath',
+    # main
+    'BaseModel',
+    'create_model',
+    # network
+    'AnyUrl',
+    'AnyHttpUrl',
+    'FileUrl',
+    'HttpUrl',
+    'FtpUrl',
+    'WebsocketUrl',
+    'AnyWebsocketUrl',
+    'UrlConstraints',
+    'EmailStr',
+    'NameEmail',
+    'IPvAnyAddress',
+    'IPvAnyInterface',
+    'IPvAnyNetwork',
+    'PostgresDsn',
+    'CockroachDsn',
+    'AmqpDsn',
+    'RedisDsn',
+    'MongoDsn',
+    'KafkaDsn',
+    'NatsDsn',
+    'MySQLDsn',
+    'MariaDBDsn',
+    'ClickHouseDsn',
+    'SnowflakeDsn',
+    'validate_email',
+    # root_model
+    'RootModel',
+    # deprecated tools, these are imported via `__getattr__` below
+    'parse_obj_as',
+    'schema_of',
+    'schema_json_of',
+    # types
+    'Strict',
+    'StrictStr',
+    'conbytes',
+    'conlist',
+    'conset',
+    'confrozenset',
+    'constr',
+    'StringConstraints',
+    'ImportString',
+    'conint',
+    'PositiveInt',
+    'NegativeInt',
+    'NonNegativeInt',
+    'NonPositiveInt',
+    'confloat',
+    'PositiveFloat',
+    'NegativeFloat',
+    'NonNegativeFloat',
+    'NonPositiveFloat',
+    'FiniteFloat',
+    'condecimal',
+    'condate',
+    'UUID1',
+    'UUID3',
+    'UUID4',
+    'UUID5',
+    'UUID6',
+    'UUID7',
+    'UUID8',
+    'FilePath',
+    'DirectoryPath',
+    'NewPath',
+    'Json',
+    'Secret',
+    'SecretStr',
+    'SecretBytes',
+    'SocketPath',
+    'StrictBool',
+    'StrictBytes',
+    'StrictInt',
+    'StrictFloat',
+    'PaymentCardNumber',
+    'ByteSize',
+    'PastDate',
+    'FutureDate',
+    'PastDatetime',
+    'FutureDatetime',
+    'AwareDatetime',
+    'NaiveDatetime',
+    'AllowInfNan',
+    'EncoderProtocol',
+    'EncodedBytes',
+    'EncodedStr',
+    'Base64Encoder',
+    'Base64Bytes',
+    'Base64Str',
+    'Base64UrlBytes',
+    'Base64UrlStr',
+    'GetPydanticSchema',
+    'Tag',
+    'Discriminator',
+    'JsonValue',
+    'FailFast',
+    # type_adapter
+    'TypeAdapter',
+    # version
+    '__version__',
+    'VERSION',
+    # warnings
+    'PydanticDeprecatedSince20',
+    'PydanticDeprecatedSince26',
+    'PydanticDeprecatedSince29',
+    'PydanticDeprecatedSince210',
+    'PydanticDeprecatedSince211',
+    'PydanticDeprecatedSince212',
+    'PydanticDeprecationWarning',
+    'PydanticExperimentalWarning',
+    # annotated handlers
+    'GetCoreSchemaHandler',
+    'GetJsonSchemaHandler',
+    # pydantic_core
+    'ValidationError',
+    'ValidationInfo',
+    'SerializationInfo',
+    'ValidatorFunctionWrapHandler',
+    'FieldSerializationInfo',
+    'SerializerFunctionWrapHandler',
+    'OnErrorOmit',
+)
+
+# A mapping of {: (package, )} defining dynamic imports
+_dynamic_imports: 'dict[str, tuple[str, str]]' = {
+    'dataclasses': (__spec__.parent, '__module__'),
+    # functional validators
+    'field_validator': (__spec__.parent, '.functional_validators'),
+    'model_validator': (__spec__.parent, '.functional_validators'),
+    'AfterValidator': (__spec__.parent, '.functional_validators'),
+    'BeforeValidator': (__spec__.parent, '.functional_validators'),
+    'PlainValidator': (__spec__.parent, '.functional_validators'),
+    'WrapValidator': (__spec__.parent, '.functional_validators'),
+    'SkipValidation': (__spec__.parent, '.functional_validators'),
+    'InstanceOf': (__spec__.parent, '.functional_validators'),
+    'ValidateAs': (__spec__.parent, '.functional_validators'),
+    'ModelWrapValidatorHandler': (__spec__.parent, '.functional_validators'),
+    # JSON Schema
+    'WithJsonSchema': (__spec__.parent, '.json_schema'),
+    # functional serializers
+    'field_serializer': (__spec__.parent, '.functional_serializers'),
+    'model_serializer': (__spec__.parent, '.functional_serializers'),
+    'PlainSerializer': (__spec__.parent, '.functional_serializers'),
+    'SerializeAsAny': (__spec__.parent, '.functional_serializers'),
+    'WrapSerializer': (__spec__.parent, '.functional_serializers'),
+    # config
+    'ConfigDict': (__spec__.parent, '.config'),
+    'with_config': (__spec__.parent, '.config'),
+    # validate call
+    'validate_call': (__spec__.parent, '.validate_call_decorator'),
+    # errors
+    'PydanticErrorCodes': (__spec__.parent, '.errors'),
+    'PydanticUserError': (__spec__.parent, '.errors'),
+    'PydanticSchemaGenerationError': (__spec__.parent, '.errors'),
+    'PydanticImportError': (__spec__.parent, '.errors'),
+    'PydanticUndefinedAnnotation': (__spec__.parent, '.errors'),
+    'PydanticInvalidForJsonSchema': (__spec__.parent, '.errors'),
+    'PydanticForbiddenQualifier': (__spec__.parent, '.errors'),
+    # fields
+    'Field': (__spec__.parent, '.fields'),
+    'computed_field': (__spec__.parent, '.fields'),
+    'PrivateAttr': (__spec__.parent, '.fields'),
+    # alias
+    'AliasChoices': (__spec__.parent, '.aliases'),
+    'AliasGenerator': (__spec__.parent, '.aliases'),
+    'AliasPath': (__spec__.parent, '.aliases'),
+    # main
+    'BaseModel': (__spec__.parent, '.main'),
+    'create_model': (__spec__.parent, '.main'),
+    # network
+    'AnyUrl': (__spec__.parent, '.networks'),
+    'AnyHttpUrl': (__spec__.parent, '.networks'),
+    'FileUrl': (__spec__.parent, '.networks'),
+    'HttpUrl': (__spec__.parent, '.networks'),
+    'FtpUrl': (__spec__.parent, '.networks'),
+    'WebsocketUrl': (__spec__.parent, '.networks'),
+    'AnyWebsocketUrl': (__spec__.parent, '.networks'),
+    'UrlConstraints': (__spec__.parent, '.networks'),
+    'EmailStr': (__spec__.parent, '.networks'),
+    'NameEmail': (__spec__.parent, '.networks'),
+    'IPvAnyAddress': (__spec__.parent, '.networks'),
+    'IPvAnyInterface': (__spec__.parent, '.networks'),
+    'IPvAnyNetwork': (__spec__.parent, '.networks'),
+    'PostgresDsn': (__spec__.parent, '.networks'),
+    'CockroachDsn': (__spec__.parent, '.networks'),
+    'AmqpDsn': (__spec__.parent, '.networks'),
+    'RedisDsn': (__spec__.parent, '.networks'),
+    'MongoDsn': (__spec__.parent, '.networks'),
+    'KafkaDsn': (__spec__.parent, '.networks'),
+    'NatsDsn': (__spec__.parent, '.networks'),
+    'MySQLDsn': (__spec__.parent, '.networks'),
+    'MariaDBDsn': (__spec__.parent, '.networks'),
+    'ClickHouseDsn': (__spec__.parent, '.networks'),
+    'SnowflakeDsn': (__spec__.parent, '.networks'),
+    'validate_email': (__spec__.parent, '.networks'),
+    # root_model
+    'RootModel': (__spec__.parent, '.root_model'),
+    # types
+    'Strict': (__spec__.parent, '.types'),
+    'StrictStr': (__spec__.parent, '.types'),
+    'conbytes': (__spec__.parent, '.types'),
+    'conlist': (__spec__.parent, '.types'),
+    'conset': (__spec__.parent, '.types'),
+    'confrozenset': (__spec__.parent, '.types'),
+    'constr': (__spec__.parent, '.types'),
+    'StringConstraints': (__spec__.parent, '.types'),
+    'ImportString': (__spec__.parent, '.types'),
+    'conint': (__spec__.parent, '.types'),
+    'PositiveInt': (__spec__.parent, '.types'),
+    'NegativeInt': (__spec__.parent, '.types'),
+    'NonNegativeInt': (__spec__.parent, '.types'),
+    'NonPositiveInt': (__spec__.parent, '.types'),
+    'confloat': (__spec__.parent, '.types'),
+    'PositiveFloat': (__spec__.parent, '.types'),
+    'NegativeFloat': (__spec__.parent, '.types'),
+    'NonNegativeFloat': (__spec__.parent, '.types'),
+    'NonPositiveFloat': (__spec__.parent, '.types'),
+    'FiniteFloat': (__spec__.parent, '.types'),
+    'condecimal': (__spec__.parent, '.types'),
+    'condate': (__spec__.parent, '.types'),
+    'UUID1': (__spec__.parent, '.types'),
+    'UUID3': (__spec__.parent, '.types'),
+    'UUID4': (__spec__.parent, '.types'),
+    'UUID5': (__spec__.parent, '.types'),
+    'UUID6': (__spec__.parent, '.types'),
+    'UUID7': (__spec__.parent, '.types'),
+    'UUID8': (__spec__.parent, '.types'),
+    'FilePath': (__spec__.parent, '.types'),
+    'DirectoryPath': (__spec__.parent, '.types'),
+    'NewPath': (__spec__.parent, '.types'),
+    'Json': (__spec__.parent, '.types'),
+    'Secret': (__spec__.parent, '.types'),
+    'SecretStr': (__spec__.parent, '.types'),
+    'SecretBytes': (__spec__.parent, '.types'),
+    'StrictBool': (__spec__.parent, '.types'),
+    'StrictBytes': (__spec__.parent, '.types'),
+    'StrictInt': (__spec__.parent, '.types'),
+    'StrictFloat': (__spec__.parent, '.types'),
+    'PaymentCardNumber': (__spec__.parent, '.types'),
+    'ByteSize': (__spec__.parent, '.types'),
+    'PastDate': (__spec__.parent, '.types'),
+    'SocketPath': (__spec__.parent, '.types'),
+    'FutureDate': (__spec__.parent, '.types'),
+    'PastDatetime': (__spec__.parent, '.types'),
+    'FutureDatetime': (__spec__.parent, '.types'),
+    'AwareDatetime': (__spec__.parent, '.types'),
+    'NaiveDatetime': (__spec__.parent, '.types'),
+    'AllowInfNan': (__spec__.parent, '.types'),
+    'EncoderProtocol': (__spec__.parent, '.types'),
+    'EncodedBytes': (__spec__.parent, '.types'),
+    'EncodedStr': (__spec__.parent, '.types'),
+    'Base64Encoder': (__spec__.parent, '.types'),
+    'Base64Bytes': (__spec__.parent, '.types'),
+    'Base64Str': (__spec__.parent, '.types'),
+    'Base64UrlBytes': (__spec__.parent, '.types'),
+    'Base64UrlStr': (__spec__.parent, '.types'),
+    'GetPydanticSchema': (__spec__.parent, '.types'),
+    'Tag': (__spec__.parent, '.types'),
+    'Discriminator': (__spec__.parent, '.types'),
+    'JsonValue': (__spec__.parent, '.types'),
+    'OnErrorOmit': (__spec__.parent, '.types'),
+    'FailFast': (__spec__.parent, '.types'),
+    # type_adapter
+    'TypeAdapter': (__spec__.parent, '.type_adapter'),
+    # warnings
+    'PydanticDeprecatedSince20': (__spec__.parent, '.warnings'),
+    'PydanticDeprecatedSince26': (__spec__.parent, '.warnings'),
+    'PydanticDeprecatedSince29': (__spec__.parent, '.warnings'),
+    'PydanticDeprecatedSince210': (__spec__.parent, '.warnings'),
+    'PydanticDeprecatedSince211': (__spec__.parent, '.warnings'),
+    'PydanticDeprecatedSince212': (__spec__.parent, '.warnings'),
+    'PydanticDeprecationWarning': (__spec__.parent, '.warnings'),
+    'PydanticExperimentalWarning': (__spec__.parent, '.warnings'),
+    # annotated handlers
+    'GetCoreSchemaHandler': (__spec__.parent, '.annotated_handlers'),
+    'GetJsonSchemaHandler': (__spec__.parent, '.annotated_handlers'),
+    # pydantic_core stuff
+    'ValidationError': ('pydantic_core', '.'),
+    'ValidationInfo': ('pydantic_core', '.core_schema'),
+    'SerializationInfo': ('pydantic_core', '.core_schema'),
+    'ValidatorFunctionWrapHandler': ('pydantic_core', '.core_schema'),
+    'FieldSerializationInfo': ('pydantic_core', '.core_schema'),
+    'SerializerFunctionWrapHandler': ('pydantic_core', '.core_schema'),
+    # deprecated, mostly not included in __all__
+    'root_validator': (__spec__.parent, '.deprecated.class_validators'),
+    'validator': (__spec__.parent, '.deprecated.class_validators'),
+    'BaseConfig': (__spec__.parent, '.deprecated.config'),
+    'Extra': (__spec__.parent, '.deprecated.config'),
+    'parse_obj_as': (__spec__.parent, '.deprecated.tools'),
+    'schema_of': (__spec__.parent, '.deprecated.tools'),
+    'schema_json_of': (__spec__.parent, '.deprecated.tools'),
+    # deprecated dynamic imports
+    'FieldValidationInfo': ('pydantic_core', '.core_schema'),
+    'GenerateSchema': (__spec__.parent, '._internal._generate_schema'),
+}
+_deprecated_dynamic_imports = {'FieldValidationInfo', 'GenerateSchema'}
+
+_getattr_migration = getattr_migration(__name__)
+
+
+def __getattr__(attr_name: str) -> object:
+    if attr_name in _deprecated_dynamic_imports:
+        from pydantic.warnings import PydanticDeprecatedSince20
+
+        warn(
+            f'Importing {attr_name} from `pydantic` is deprecated. This feature is either no longer supported, or is not public.',
+            PydanticDeprecatedSince20,
+            stacklevel=2,
+        )
+
+    dynamic_attr = _dynamic_imports.get(attr_name)
+    if dynamic_attr is None:
+        return _getattr_migration(attr_name)
+
+    package, module_name = dynamic_attr
+
+    if module_name == '__module__':
+        result = import_module(f'.{attr_name}', package=package)
+        globals()[attr_name] = result
+        return result
+    else:
+        module = import_module(module_name, package=package)
+        result = getattr(module, attr_name)
+        g = globals()
+        for k, (_, v_module_name) in _dynamic_imports.items():
+            if v_module_name == module_name and k not in _deprecated_dynamic_imports:
+                g[k] = getattr(module, k)
+        return result
+
+
+def __dir__() -> list[str]:
+    return list(__all__)
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pydantic/_migration.py b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/_migration.py
new file mode 100644
index 0000000000000000000000000000000000000000..b4ecd283a0ac53c55ff75e9a03669d03b2d0ea30
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/_migration.py
@@ -0,0 +1,316 @@
+import sys
+from typing import Any, Callable
+
+from pydantic.warnings import PydanticDeprecatedSince20
+
+from .version import version_short
+
+MOVED_IN_V2 = {
+    'pydantic.utils:version_info': 'pydantic.version:version_info',
+    'pydantic.error_wrappers:ValidationError': 'pydantic:ValidationError',
+    'pydantic.utils:to_camel': 'pydantic.alias_generators:to_pascal',
+    'pydantic.utils:to_lower_camel': 'pydantic.alias_generators:to_camel',
+    'pydantic:PyObject': 'pydantic.types:ImportString',
+    'pydantic.types:PyObject': 'pydantic.types:ImportString',
+    'pydantic.generics:GenericModel': 'pydantic.BaseModel',
+}
+
+DEPRECATED_MOVED_IN_V2 = {
+    'pydantic.tools:schema_of': 'pydantic.deprecated.tools:schema_of',
+    'pydantic.tools:parse_obj_as': 'pydantic.deprecated.tools:parse_obj_as',
+    'pydantic.tools:schema_json_of': 'pydantic.deprecated.tools:schema_json_of',
+    'pydantic.json:pydantic_encoder': 'pydantic.deprecated.json:pydantic_encoder',
+    'pydantic:validate_arguments': 'pydantic.deprecated.decorator:validate_arguments',
+    'pydantic.json:custom_pydantic_encoder': 'pydantic.deprecated.json:custom_pydantic_encoder',
+    'pydantic.json:timedelta_isoformat': 'pydantic.deprecated.json:timedelta_isoformat',
+    'pydantic.decorator:validate_arguments': 'pydantic.deprecated.decorator:validate_arguments',
+    'pydantic.class_validators:validator': 'pydantic.deprecated.class_validators:validator',
+    'pydantic.class_validators:root_validator': 'pydantic.deprecated.class_validators:root_validator',
+    'pydantic.config:BaseConfig': 'pydantic.deprecated.config:BaseConfig',
+    'pydantic.config:Extra': 'pydantic.deprecated.config:Extra',
+}
+
+REDIRECT_TO_V1 = {
+    f'pydantic.utils:{obj}': f'pydantic.v1.utils:{obj}'
+    for obj in (
+        'deep_update',
+        'GetterDict',
+        'lenient_issubclass',
+        'lenient_isinstance',
+        'is_valid_field',
+        'update_not_none',
+        'import_string',
+        'Representation',
+        'ROOT_KEY',
+        'smart_deepcopy',
+        'sequence_like',
+    )
+}
+
+
+REMOVED_IN_V2 = {
+    'pydantic:ConstrainedBytes',
+    'pydantic:ConstrainedDate',
+    'pydantic:ConstrainedDecimal',
+    'pydantic:ConstrainedFloat',
+    'pydantic:ConstrainedFrozenSet',
+    'pydantic:ConstrainedInt',
+    'pydantic:ConstrainedList',
+    'pydantic:ConstrainedSet',
+    'pydantic:ConstrainedStr',
+    'pydantic:JsonWrapper',
+    'pydantic:NoneBytes',
+    'pydantic:NoneStr',
+    'pydantic:NoneStrBytes',
+    'pydantic:Protocol',
+    'pydantic:Required',
+    'pydantic:StrBytes',
+    'pydantic:compiled',
+    'pydantic.config:get_config',
+    'pydantic.config:inherit_config',
+    'pydantic.config:prepare_config',
+    'pydantic:create_model_from_namedtuple',
+    'pydantic:create_model_from_typeddict',
+    'pydantic.dataclasses:create_pydantic_model_from_dataclass',
+    'pydantic.dataclasses:make_dataclass_validator',
+    'pydantic.dataclasses:set_validation',
+    'pydantic.datetime_parse:parse_date',
+    'pydantic.datetime_parse:parse_time',
+    'pydantic.datetime_parse:parse_datetime',
+    'pydantic.datetime_parse:parse_duration',
+    'pydantic.error_wrappers:ErrorWrapper',
+    'pydantic.errors:AnyStrMaxLengthError',
+    'pydantic.errors:AnyStrMinLengthError',
+    'pydantic.errors:ArbitraryTypeError',
+    'pydantic.errors:BoolError',
+    'pydantic.errors:BytesError',
+    'pydantic.errors:CallableError',
+    'pydantic.errors:ClassError',
+    'pydantic.errors:ColorError',
+    'pydantic.errors:ConfigError',
+    'pydantic.errors:DataclassTypeError',
+    'pydantic.errors:DateError',
+    'pydantic.errors:DateNotInTheFutureError',
+    'pydantic.errors:DateNotInThePastError',
+    'pydantic.errors:DateTimeError',
+    'pydantic.errors:DecimalError',
+    'pydantic.errors:DecimalIsNotFiniteError',
+    'pydantic.errors:DecimalMaxDigitsError',
+    'pydantic.errors:DecimalMaxPlacesError',
+    'pydantic.errors:DecimalWholeDigitsError',
+    'pydantic.errors:DictError',
+    'pydantic.errors:DurationError',
+    'pydantic.errors:EmailError',
+    'pydantic.errors:EnumError',
+    'pydantic.errors:EnumMemberError',
+    'pydantic.errors:ExtraError',
+    'pydantic.errors:FloatError',
+    'pydantic.errors:FrozenSetError',
+    'pydantic.errors:FrozenSetMaxLengthError',
+    'pydantic.errors:FrozenSetMinLengthError',
+    'pydantic.errors:HashableError',
+    'pydantic.errors:IPv4AddressError',
+    'pydantic.errors:IPv4InterfaceError',
+    'pydantic.errors:IPv4NetworkError',
+    'pydantic.errors:IPv6AddressError',
+    'pydantic.errors:IPv6InterfaceError',
+    'pydantic.errors:IPv6NetworkError',
+    'pydantic.errors:IPvAnyAddressError',
+    'pydantic.errors:IPvAnyInterfaceError',
+    'pydantic.errors:IPvAnyNetworkError',
+    'pydantic.errors:IntEnumError',
+    'pydantic.errors:IntegerError',
+    'pydantic.errors:InvalidByteSize',
+    'pydantic.errors:InvalidByteSizeUnit',
+    'pydantic.errors:InvalidDiscriminator',
+    'pydantic.errors:InvalidLengthForBrand',
+    'pydantic.errors:JsonError',
+    'pydantic.errors:JsonTypeError',
+    'pydantic.errors:ListError',
+    'pydantic.errors:ListMaxLengthError',
+    'pydantic.errors:ListMinLengthError',
+    'pydantic.errors:ListUniqueItemsError',
+    'pydantic.errors:LuhnValidationError',
+    'pydantic.errors:MissingDiscriminator',
+    'pydantic.errors:MissingError',
+    'pydantic.errors:NoneIsAllowedError',
+    'pydantic.errors:NoneIsNotAllowedError',
+    'pydantic.errors:NotDigitError',
+    'pydantic.errors:NotNoneError',
+    'pydantic.errors:NumberNotGeError',
+    'pydantic.errors:NumberNotGtError',
+    'pydantic.errors:NumberNotLeError',
+    'pydantic.errors:NumberNotLtError',
+    'pydantic.errors:NumberNotMultipleError',
+    'pydantic.errors:PathError',
+    'pydantic.errors:PathNotADirectoryError',
+    'pydantic.errors:PathNotAFileError',
+    'pydantic.errors:PathNotExistsError',
+    'pydantic.errors:PatternError',
+    'pydantic.errors:PyObjectError',
+    'pydantic.errors:PydanticTypeError',
+    'pydantic.errors:PydanticValueError',
+    'pydantic.errors:SequenceError',
+    'pydantic.errors:SetError',
+    'pydantic.errors:SetMaxLengthError',
+    'pydantic.errors:SetMinLengthError',
+    'pydantic.errors:StrError',
+    'pydantic.errors:StrRegexError',
+    'pydantic.errors:StrictBoolError',
+    'pydantic.errors:SubclassError',
+    'pydantic.errors:TimeError',
+    'pydantic.errors:TupleError',
+    'pydantic.errors:TupleLengthError',
+    'pydantic.errors:UUIDError',
+    'pydantic.errors:UUIDVersionError',
+    'pydantic.errors:UrlError',
+    'pydantic.errors:UrlExtraError',
+    'pydantic.errors:UrlHostError',
+    'pydantic.errors:UrlHostTldError',
+    'pydantic.errors:UrlPortError',
+    'pydantic.errors:UrlSchemeError',
+    'pydantic.errors:UrlSchemePermittedError',
+    'pydantic.errors:UrlUserInfoError',
+    'pydantic.errors:WrongConstantError',
+    'pydantic.main:validate_model',
+    'pydantic.networks:stricturl',
+    'pydantic:parse_file_as',
+    'pydantic:parse_raw_as',
+    'pydantic:stricturl',
+    'pydantic.tools:parse_file_as',
+    'pydantic.tools:parse_raw_as',
+    'pydantic.types:ConstrainedBytes',
+    'pydantic.types:ConstrainedDate',
+    'pydantic.types:ConstrainedDecimal',
+    'pydantic.types:ConstrainedFloat',
+    'pydantic.types:ConstrainedFrozenSet',
+    'pydantic.types:ConstrainedInt',
+    'pydantic.types:ConstrainedList',
+    'pydantic.types:ConstrainedSet',
+    'pydantic.types:ConstrainedStr',
+    'pydantic.types:JsonWrapper',
+    'pydantic.types:NoneBytes',
+    'pydantic.types:NoneStr',
+    'pydantic.types:NoneStrBytes',
+    'pydantic.types:StrBytes',
+    'pydantic.typing:evaluate_forwardref',
+    'pydantic.typing:AbstractSetIntStr',
+    'pydantic.typing:AnyCallable',
+    'pydantic.typing:AnyClassMethod',
+    'pydantic.typing:CallableGenerator',
+    'pydantic.typing:DictAny',
+    'pydantic.typing:DictIntStrAny',
+    'pydantic.typing:DictStrAny',
+    'pydantic.typing:IntStr',
+    'pydantic.typing:ListStr',
+    'pydantic.typing:MappingIntStrAny',
+    'pydantic.typing:NoArgAnyCallable',
+    'pydantic.typing:NoneType',
+    'pydantic.typing:ReprArgs',
+    'pydantic.typing:SetStr',
+    'pydantic.typing:StrPath',
+    'pydantic.typing:TupleGenerator',
+    'pydantic.typing:WithArgsTypes',
+    'pydantic.typing:all_literal_values',
+    'pydantic.typing:display_as_type',
+    'pydantic.typing:get_all_type_hints',
+    'pydantic.typing:get_args',
+    'pydantic.typing:get_origin',
+    'pydantic.typing:get_sub_types',
+    'pydantic.typing:is_callable_type',
+    'pydantic.typing:is_classvar',
+    'pydantic.typing:is_finalvar',
+    'pydantic.typing:is_literal_type',
+    'pydantic.typing:is_namedtuple',
+    'pydantic.typing:is_new_type',
+    'pydantic.typing:is_none_type',
+    'pydantic.typing:is_typeddict',
+    'pydantic.typing:is_typeddict_special',
+    'pydantic.typing:is_union',
+    'pydantic.typing:new_type_supertype',
+    'pydantic.typing:resolve_annotations',
+    'pydantic.typing:typing_base',
+    'pydantic.typing:update_field_forward_refs',
+    'pydantic.typing:update_model_forward_refs',
+    'pydantic.utils:ClassAttribute',
+    'pydantic.utils:DUNDER_ATTRIBUTES',
+    'pydantic.utils:PyObjectStr',
+    'pydantic.utils:ValueItems',
+    'pydantic.utils:almost_equal_floats',
+    'pydantic.utils:get_discriminator_alias_and_values',
+    'pydantic.utils:get_model',
+    'pydantic.utils:get_unique_discriminator_alias',
+    'pydantic.utils:in_ipython',
+    'pydantic.utils:is_valid_identifier',
+    'pydantic.utils:path_type',
+    'pydantic.utils:validate_field_name',
+    'pydantic:validate_model',
+}
+
+
+def getattr_migration(module: str) -> Callable[[str], Any]:
+    """Implement PEP 562 for objects that were either moved or removed on the migration
+    to V2.
+
+    Args:
+        module: The module name.
+
+    Returns:
+        A callable that will raise an error if the object is not found.
+    """
+    # This avoids circular import with errors.py.
+    from .errors import PydanticImportError
+
+    def wrapper(name: str) -> object:
+        """Raise an error if the object is not found, or warn if it was moved.
+
+        In case it was moved, it still returns the object.
+
+        Args:
+            name: The object name.
+
+        Returns:
+            The object.
+        """
+        if name == '__path__':
+            raise AttributeError(f'module {module!r} has no attribute {name!r}')
+
+        import warnings
+
+        from ._internal._validators import import_string
+
+        import_path = f'{module}:{name}'
+        if import_path in MOVED_IN_V2.keys():
+            new_location = MOVED_IN_V2[import_path]
+            warnings.warn(
+                f'`{import_path}` has been moved to `{new_location}`.',
+                category=PydanticDeprecatedSince20,
+                stacklevel=2,
+            )
+            return import_string(MOVED_IN_V2[import_path])
+        if import_path in DEPRECATED_MOVED_IN_V2:
+            # skip the warning here because a deprecation warning will be raised elsewhere
+            return import_string(DEPRECATED_MOVED_IN_V2[import_path])
+        if import_path in REDIRECT_TO_V1:
+            new_location = REDIRECT_TO_V1[import_path]
+            warnings.warn(
+                f'`{import_path}` has been removed. We are importing from `{new_location}` instead.'
+                'See the migration guide for more details: https://docs.pydantic.dev/latest/migration/',
+                category=PydanticDeprecatedSince20,
+                stacklevel=2,
+            )
+            return import_string(REDIRECT_TO_V1[import_path])
+        if import_path == 'pydantic:BaseSettings':
+            raise PydanticImportError(
+                '`BaseSettings` has been moved to the `pydantic-settings` package. '
+                f'See https://docs.pydantic.dev/{version_short()}/migration/#basesettings-has-moved-to-pydantic-settings '
+                'for more details.'
+            )
+        if import_path in REMOVED_IN_V2:
+            raise PydanticImportError(f'`{import_path}` has been removed in V2.')
+        globals: dict[str, Any] = sys.modules[module].__dict__
+        if name in globals:
+            return globals[name]
+        raise AttributeError(f'module {module!r} has no attribute {name!r}')
+
+    return wrapper
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pydantic/alias_generators.py b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/alias_generators.py
new file mode 100644
index 0000000000000000000000000000000000000000..0b7653f5825979edcd446d698d320bdb980b8e9e
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/alias_generators.py
@@ -0,0 +1,62 @@
+"""Alias generators for converting between different capitalization conventions."""
+
+import re
+
+__all__ = ('to_pascal', 'to_camel', 'to_snake')
+
+# TODO: in V3, change the argument names to be more descriptive
+# Generally, don't only convert from snake_case, or name the functions
+# more specifically like snake_to_camel.
+
+
+def to_pascal(snake: str) -> str:
+    """Convert a snake_case string to PascalCase.
+
+    Args:
+        snake: The string to convert.
+
+    Returns:
+        The PascalCase string.
+    """
+    camel = snake.title()
+    return re.sub('([0-9A-Za-z])_(?=[0-9A-Z])', lambda m: m.group(1), camel)
+
+
+def to_camel(snake: str) -> str:
+    """Convert a snake_case string to camelCase.
+
+    Args:
+        snake: The string to convert.
+
+    Returns:
+        The converted camelCase string.
+    """
+    # If the string is already in camelCase and does not contain a digit followed
+    # by a lowercase letter, return it as it is
+    if re.match('^[a-z]+[A-Za-z0-9]*$', snake) and not re.search(r'\d[a-z]', snake):
+        return snake
+
+    camel = to_pascal(snake)
+    return re.sub('(^_*[A-Z])', lambda m: m.group(1).lower(), camel)
+
+
+def to_snake(camel: str) -> str:
+    """Convert a PascalCase, camelCase, or kebab-case string to snake_case.
+
+    Args:
+        camel: The string to convert.
+
+    Returns:
+        The converted string in snake_case.
+    """
+    # Handle the sequence of uppercase letters followed by a lowercase letter
+    snake = re.sub(r'([A-Z]+)([A-Z][a-z])', lambda m: f'{m.group(1)}_{m.group(2)}', camel)
+    # Insert an underscore between a lowercase letter and an uppercase letter
+    snake = re.sub(r'([a-z])([A-Z])', lambda m: f'{m.group(1)}_{m.group(2)}', snake)
+    # Insert an underscore between a digit and an uppercase letter
+    snake = re.sub(r'([0-9])([A-Z])', lambda m: f'{m.group(1)}_{m.group(2)}', snake)
+    # Insert an underscore between a lowercase letter and a digit
+    snake = re.sub(r'([a-z])([0-9])', lambda m: f'{m.group(1)}_{m.group(2)}', snake)
+    # Replace hyphens with underscores to handle kebab-case
+    snake = snake.replace('-', '_')
+    return snake.lower()
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pydantic/aliases.py b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/aliases.py
new file mode 100644
index 0000000000000000000000000000000000000000..ac2273701b5a0ae7cb0d0171cd08a7bbf77a9178
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/aliases.py
@@ -0,0 +1,135 @@
+"""Support for alias configurations."""
+
+from __future__ import annotations
+
+import dataclasses
+from typing import Any, Callable, Literal
+
+from pydantic_core import PydanticUndefined
+
+from ._internal import _internal_dataclass
+
+__all__ = ('AliasGenerator', 'AliasPath', 'AliasChoices')
+
+
+@dataclasses.dataclass(**_internal_dataclass.slots_true)
+class AliasPath:
+    """!!! abstract "Usage Documentation"
+        [`AliasPath` and `AliasChoices`](../concepts/alias.md#aliaspath-and-aliaschoices)
+
+    A data class used by `validation_alias` as a convenience to create aliases.
+
+    Attributes:
+        path: A list of string or integer aliases.
+    """
+
+    path: list[int | str]
+
+    def __init__(self, first_arg: str, *args: str | int) -> None:
+        self.path = [first_arg] + list(args)
+
+    def convert_to_aliases(self) -> list[str | int]:
+        """Converts arguments to a list of string or integer aliases.
+
+        Returns:
+            The list of aliases.
+        """
+        return self.path
+
+    def search_dict_for_path(self, d: dict) -> Any:
+        """Searches a dictionary for the path specified by the alias.
+
+        Returns:
+            The value at the specified path, or `PydanticUndefined` if the path is not found.
+        """
+        v = d
+        for k in self.path:
+            if isinstance(v, str):
+                # disallow indexing into a str, like for AliasPath('x', 0) and x='abc'
+                return PydanticUndefined
+            try:
+                v = v[k]
+            except (KeyError, IndexError, TypeError):
+                return PydanticUndefined
+        return v
+
+
+@dataclasses.dataclass(**_internal_dataclass.slots_true)
+class AliasChoices:
+    """!!! abstract "Usage Documentation"
+        [`AliasPath` and `AliasChoices`](../concepts/alias.md#aliaspath-and-aliaschoices)
+
+    A data class used by `validation_alias` as a convenience to create aliases.
+
+    Attributes:
+        choices: A list containing a string or `AliasPath`.
+    """
+
+    choices: list[str | AliasPath]
+
+    def __init__(self, first_choice: str | AliasPath, *choices: str | AliasPath) -> None:
+        self.choices = [first_choice] + list(choices)
+
+    def convert_to_aliases(self) -> list[list[str | int]]:
+        """Converts arguments to a list of lists containing string or integer aliases.
+
+        Returns:
+            The list of aliases.
+        """
+        aliases: list[list[str | int]] = []
+        for c in self.choices:
+            if isinstance(c, AliasPath):
+                aliases.append(c.convert_to_aliases())
+            else:
+                aliases.append([c])
+        return aliases
+
+
+@dataclasses.dataclass(**_internal_dataclass.slots_true)
+class AliasGenerator:
+    """!!! abstract "Usage Documentation"
+        [Using an `AliasGenerator`](../concepts/alias.md#using-an-aliasgenerator)
+
+    A data class used by `alias_generator` as a convenience to create various aliases.
+
+    Attributes:
+        alias: A callable that takes a field name and returns an alias for it.
+        validation_alias: A callable that takes a field name and returns a validation alias for it.
+        serialization_alias: A callable that takes a field name and returns a serialization alias for it.
+    """
+
+    alias: Callable[[str], str] | None = None
+    validation_alias: Callable[[str], str | AliasPath | AliasChoices] | None = None
+    serialization_alias: Callable[[str], str] | None = None
+
+    def _generate_alias(
+        self,
+        alias_kind: Literal['alias', 'validation_alias', 'serialization_alias'],
+        allowed_types: tuple[type[str] | type[AliasPath] | type[AliasChoices], ...],
+        field_name: str,
+    ) -> str | AliasPath | AliasChoices | None:
+        """Generate an alias of the specified kind. Returns None if the alias generator is None.
+
+        Raises:
+            TypeError: If the alias generator produces an invalid type.
+        """
+        alias = None
+        if alias_generator := getattr(self, alias_kind):
+            alias = alias_generator(field_name)
+            if alias and not isinstance(alias, allowed_types):
+                raise TypeError(
+                    f'Invalid `{alias_kind}` type. `{alias_kind}` generator must produce one of `{allowed_types}`'
+                )
+        return alias
+
+    def generate_aliases(self, field_name: str) -> tuple[str | None, str | AliasPath | AliasChoices | None, str | None]:
+        """Generate `alias`, `validation_alias`, and `serialization_alias` for a field.
+
+        Returns:
+            A tuple of three aliases - validation, alias, and serialization.
+        """
+        alias = self._generate_alias('alias', (str,), field_name)
+        validation_alias = self._generate_alias('validation_alias', (str, AliasChoices, AliasPath), field_name)
+        serialization_alias = self._generate_alias('serialization_alias', (str,), field_name)
+
+        return alias, validation_alias, serialization_alias  # type: ignore
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pydantic/annotated_handlers.py b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/annotated_handlers.py
new file mode 100644
index 0000000000000000000000000000000000000000..d0cb5d3d4616f938aea2aae42985b4c166b500cc
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/annotated_handlers.py
@@ -0,0 +1,122 @@
+"""Type annotations to use with `__get_pydantic_core_schema__` and `__get_pydantic_json_schema__`."""
+
+from __future__ import annotations as _annotations
+
+from typing import TYPE_CHECKING, Any, Union
+
+from pydantic_core import core_schema
+
+if TYPE_CHECKING:
+    from ._internal._namespace_utils import NamespacesTuple
+    from .json_schema import JsonSchemaMode, JsonSchemaValue
+
+    CoreSchemaOrField = Union[
+        core_schema.CoreSchema,
+        core_schema.ModelField,
+        core_schema.DataclassField,
+        core_schema.TypedDictField,
+        core_schema.ComputedField,
+    ]
+
+__all__ = 'GetJsonSchemaHandler', 'GetCoreSchemaHandler'
+
+
+class GetJsonSchemaHandler:
+    """Handler to call into the next JSON schema generation function.
+
+    Attributes:
+        mode: Json schema mode, can be `validation` or `serialization`.
+    """
+
+    mode: JsonSchemaMode
+
+    def __call__(self, core_schema: CoreSchemaOrField, /) -> JsonSchemaValue:
+        """Call the inner handler and get the JsonSchemaValue it returns.
+        This will call the next JSON schema modifying function up until it calls
+        into `pydantic.json_schema.GenerateJsonSchema`, which will raise a
+        `pydantic.errors.PydanticInvalidForJsonSchema` error if it cannot generate
+        a JSON schema.
+
+        Args:
+            core_schema: A `pydantic_core.core_schema.CoreSchema`.
+
+        Returns:
+            JsonSchemaValue: The JSON schema generated by the inner JSON schema modify
+            functions.
+        """
+        raise NotImplementedError
+
+    def resolve_ref_schema(self, maybe_ref_json_schema: JsonSchemaValue, /) -> JsonSchemaValue:
+        """Get the real schema for a `{"$ref": ...}` schema.
+        If the schema given is not a `$ref` schema, it will be returned as is.
+        This means you don't have to check before calling this function.
+
+        Args:
+            maybe_ref_json_schema: A JsonSchemaValue which may be a `$ref` schema.
+
+        Raises:
+            LookupError: If the ref is not found.
+
+        Returns:
+            JsonSchemaValue: A JsonSchemaValue that has no `$ref`.
+        """
+        raise NotImplementedError
+
+
+class GetCoreSchemaHandler:
+    """Handler to call into the next CoreSchema schema generation function."""
+
+    def __call__(self, source_type: Any, /) -> core_schema.CoreSchema:
+        """Call the inner handler and get the CoreSchema it returns.
+        This will call the next CoreSchema modifying function up until it calls
+        into Pydantic's internal schema generation machinery, which will raise a
+        `pydantic.errors.PydanticSchemaGenerationError` error if it cannot generate
+        a CoreSchema for the given source type.
+
+        Args:
+            source_type: The input type.
+
+        Returns:
+            CoreSchema: The `pydantic-core` CoreSchema generated.
+        """
+        raise NotImplementedError
+
+    def generate_schema(self, source_type: Any, /) -> core_schema.CoreSchema:
+        """Generate a schema unrelated to the current context.
+        Use this function if e.g. you are handling schema generation for a sequence
+        and want to generate a schema for its items.
+        Otherwise, you may end up doing something like applying a `min_length` constraint
+        that was intended for the sequence itself to its items!
+
+        Args:
+            source_type: The input type.
+
+        Returns:
+            CoreSchema: The `pydantic-core` CoreSchema generated.
+        """
+        raise NotImplementedError
+
+    def resolve_ref_schema(self, maybe_ref_schema: core_schema.CoreSchema, /) -> core_schema.CoreSchema:
+        """Get the real schema for a `definition-ref` schema.
+        If the schema given is not a `definition-ref` schema, it will be returned as is.
+        This means you don't have to check before calling this function.
+
+        Args:
+            maybe_ref_schema: A `CoreSchema`, `ref`-based or not.
+
+        Raises:
+            LookupError: If the `ref` is not found.
+
+        Returns:
+            A concrete `CoreSchema`.
+        """
+        raise NotImplementedError
+
+    @property
+    def field_name(self) -> str | None:
+        """Get the name of the closest field to this validator."""
+        raise NotImplementedError
+
+    def _get_types_namespace(self) -> NamespacesTuple:
+        """Internal method used during type resolution for serializer annotations."""
+        raise NotImplementedError
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pydantic/class_validators.py b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/class_validators.py
new file mode 100644
index 0000000000000000000000000000000000000000..9977150c92fcb083fcdfa632c9de3b5fa92470cb
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/class_validators.py
@@ -0,0 +1,5 @@
+"""`class_validators` module is a backport module from V1."""
+
+from ._migration import getattr_migration
+
+__getattr__ = getattr_migration(__name__)
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pydantic/color.py b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/color.py
new file mode 100644
index 0000000000000000000000000000000000000000..9a42d586fd71a786ba63a4d5ce55a0ed93d866b0
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/color.py
@@ -0,0 +1,604 @@
+"""Color definitions are used as per the CSS3
+[CSS Color Module Level 3](http://www.w3.org/TR/css3-color/#svg-color) specification.
+
+A few colors have multiple names referring to the sames colors, eg. `grey` and `gray` or `aqua` and `cyan`.
+
+In these cases the _last_ color when sorted alphabetically takes preferences,
+eg. `Color((0, 255, 255)).as_named() == 'cyan'` because "cyan" comes after "aqua".
+
+Warning: Deprecated
+    The `Color` class is deprecated, use `pydantic_extra_types` instead.
+    See [`pydantic-extra-types.Color`](../usage/types/extra_types/color_types.md)
+    for more information.
+"""
+
+import math
+import re
+from colorsys import hls_to_rgb, rgb_to_hls
+from typing import Any, Callable, Optional, Union, cast
+
+from pydantic_core import CoreSchema, PydanticCustomError, core_schema
+from typing_extensions import deprecated
+
+from ._internal import _repr
+from ._internal._schema_generation_shared import GetJsonSchemaHandler as _GetJsonSchemaHandler
+from .json_schema import JsonSchemaValue
+from .warnings import PydanticDeprecatedSince20
+
+ColorTuple = Union[tuple[int, int, int], tuple[int, int, int, float]]
+ColorType = Union[ColorTuple, str]
+HslColorTuple = Union[tuple[float, float, float], tuple[float, float, float, float]]
+
+
+class RGBA:
+    """Internal use only as a representation of a color."""
+
+    __slots__ = 'r', 'g', 'b', 'alpha', '_tuple'
+
+    def __init__(self, r: float, g: float, b: float, alpha: Optional[float]):
+        self.r = r
+        self.g = g
+        self.b = b
+        self.alpha = alpha
+
+        self._tuple: tuple[float, float, float, Optional[float]] = (r, g, b, alpha)
+
+    def __getitem__(self, item: Any) -> Any:
+        return self._tuple[item]
+
+
+# these are not compiled here to avoid import slowdown, they'll be compiled the first time they're used, then cached
+_r_255 = r'(\d{1,3}(?:\.\d+)?)'
+_r_comma = r'\s*,\s*'
+_r_alpha = r'(\d(?:\.\d+)?|\.\d+|\d{1,2}%)'
+_r_h = r'(-?\d+(?:\.\d+)?|-?\.\d+)(deg|rad|turn)?'
+_r_sl = r'(\d{1,3}(?:\.\d+)?)%'
+r_hex_short = r'\s*(?:#|0x)?([0-9a-f])([0-9a-f])([0-9a-f])([0-9a-f])?\s*'
+r_hex_long = r'\s*(?:#|0x)?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})?\s*'
+# CSS3 RGB examples: rgb(0, 0, 0), rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 50%)
+r_rgb = rf'\s*rgba?\(\s*{_r_255}{_r_comma}{_r_255}{_r_comma}{_r_255}(?:{_r_comma}{_r_alpha})?\s*\)\s*'
+# CSS3 HSL examples: hsl(270, 60%, 50%), hsla(270, 60%, 50%, 0.5), hsla(270, 60%, 50%, 50%)
+r_hsl = rf'\s*hsla?\(\s*{_r_h}{_r_comma}{_r_sl}{_r_comma}{_r_sl}(?:{_r_comma}{_r_alpha})?\s*\)\s*'
+# CSS4 RGB examples: rgb(0 0 0), rgb(0 0 0 / 0.5), rgb(0 0 0 / 50%), rgba(0 0 0 / 50%)
+r_rgb_v4_style = rf'\s*rgba?\(\s*{_r_255}\s+{_r_255}\s+{_r_255}(?:\s*/\s*{_r_alpha})?\s*\)\s*'
+# CSS4 HSL examples: hsl(270 60% 50%), hsl(270 60% 50% / 0.5), hsl(270 60% 50% / 50%), hsla(270 60% 50% / 50%)
+r_hsl_v4_style = rf'\s*hsla?\(\s*{_r_h}\s+{_r_sl}\s+{_r_sl}(?:\s*/\s*{_r_alpha})?\s*\)\s*'
+
+# colors where the two hex characters are the same, if all colors match this the short version of hex colors can be used
+repeat_colors = {int(c * 2, 16) for c in '0123456789abcdef'}
+rads = 2 * math.pi
+
+
+@deprecated(
+    'The `Color` class is deprecated, use `pydantic_extra_types` instead. '
+    'See https://docs.pydantic.dev/latest/api/pydantic_extra_types_color/.',
+    category=PydanticDeprecatedSince20,
+)
+class Color(_repr.Representation):
+    """Represents a color."""
+
+    __slots__ = '_original', '_rgba'
+
+    def __init__(self, value: ColorType) -> None:
+        self._rgba: RGBA
+        self._original: ColorType
+        if isinstance(value, (tuple, list)):
+            self._rgba = parse_tuple(value)
+        elif isinstance(value, str):
+            self._rgba = parse_str(value)
+        elif isinstance(value, Color):
+            self._rgba = value._rgba
+            value = value._original
+        else:
+            raise PydanticCustomError(
+                'color_error', 'value is not a valid color: value must be a tuple, list or string'
+            )
+
+        # if we've got here value must be a valid color
+        self._original = value
+
+    @classmethod
+    def __get_pydantic_json_schema__(
+        cls, core_schema: core_schema.CoreSchema, handler: _GetJsonSchemaHandler
+    ) -> JsonSchemaValue:
+        field_schema = {}
+        field_schema.update(type='string', format='color')
+        return field_schema
+
+    def original(self) -> ColorType:
+        """Original value passed to `Color`."""
+        return self._original
+
+    def as_named(self, *, fallback: bool = False) -> str:
+        """Returns the name of the color if it can be found in `COLORS_BY_VALUE` dictionary,
+        otherwise returns the hexadecimal representation of the color or raises `ValueError`.
+
+        Args:
+            fallback: If True, falls back to returning the hexadecimal representation of
+                the color instead of raising a ValueError when no named color is found.
+
+        Returns:
+            The name of the color, or the hexadecimal representation of the color.
+
+        Raises:
+            ValueError: When no named color is found and fallback is `False`.
+        """
+        if self._rgba.alpha is None:
+            rgb = cast(tuple[int, int, int], self.as_rgb_tuple())
+            try:
+                return COLORS_BY_VALUE[rgb]
+            except KeyError as e:
+                if fallback:
+                    return self.as_hex()
+                else:
+                    raise ValueError('no named color found, use fallback=True, as_hex() or as_rgb()') from e
+        else:
+            return self.as_hex()
+
+    def as_hex(self) -> str:
+        """Returns the hexadecimal representation of the color.
+
+        Hex string representing the color can be 3, 4, 6, or 8 characters depending on whether the string
+        a "short" representation of the color is possible and whether there's an alpha channel.
+
+        Returns:
+            The hexadecimal representation of the color.
+        """
+        values = [float_to_255(c) for c in self._rgba[:3]]
+        if self._rgba.alpha is not None:
+            values.append(float_to_255(self._rgba.alpha))
+
+        as_hex = ''.join(f'{v:02x}' for v in values)
+        if all(c in repeat_colors for c in values):
+            as_hex = ''.join(as_hex[c] for c in range(0, len(as_hex), 2))
+        return '#' + as_hex
+
+    def as_rgb(self) -> str:
+        """Color as an `rgb(, , )` or `rgba(, , , )` string."""
+        if self._rgba.alpha is None:
+            return f'rgb({float_to_255(self._rgba.r)}, {float_to_255(self._rgba.g)}, {float_to_255(self._rgba.b)})'
+        else:
+            return (
+                f'rgba({float_to_255(self._rgba.r)}, {float_to_255(self._rgba.g)}, {float_to_255(self._rgba.b)}, '
+                f'{round(self._alpha_float(), 2)})'
+            )
+
+    def as_rgb_tuple(self, *, alpha: Optional[bool] = None) -> ColorTuple:
+        """Returns the color as an RGB or RGBA tuple.
+
+        Args:
+            alpha: Whether to include the alpha channel. There are three options for this input:
+
+                - `None` (default): Include alpha only if it's set. (e.g. not `None`)
+                - `True`: Always include alpha.
+                - `False`: Always omit alpha.
+
+        Returns:
+            A tuple that contains the values of the red, green, and blue channels in the range 0 to 255.
+                If alpha is included, it is in the range 0 to 1.
+        """
+        r, g, b = (float_to_255(c) for c in self._rgba[:3])
+        if alpha is None:
+            if self._rgba.alpha is None:
+                return r, g, b
+            else:
+                return r, g, b, self._alpha_float()
+        elif alpha:
+            return r, g, b, self._alpha_float()
+        else:
+            # alpha is False
+            return r, g, b
+
+    def as_hsl(self) -> str:
+        """Color as an `hsl(, , )` or `hsl(, , , )` string."""
+        if self._rgba.alpha is None:
+            h, s, li = self.as_hsl_tuple(alpha=False)  # type: ignore
+            return f'hsl({h * 360:0.0f}, {s:0.0%}, {li:0.0%})'
+        else:
+            h, s, li, a = self.as_hsl_tuple(alpha=True)  # type: ignore
+            return f'hsl({h * 360:0.0f}, {s:0.0%}, {li:0.0%}, {round(a, 2)})'
+
+    def as_hsl_tuple(self, *, alpha: Optional[bool] = None) -> HslColorTuple:
+        """Returns the color as an HSL or HSLA tuple.
+
+        Args:
+            alpha: Whether to include the alpha channel.
+
+                - `None` (default): Include the alpha channel only if it's set (e.g. not `None`).
+                - `True`: Always include alpha.
+                - `False`: Always omit alpha.
+
+        Returns:
+            The color as a tuple of hue, saturation, lightness, and alpha (if included).
+                All elements are in the range 0 to 1.
+
+        Note:
+            This is HSL as used in HTML and most other places, not HLS as used in Python's `colorsys`.
+        """
+        h, l, s = rgb_to_hls(self._rgba.r, self._rgba.g, self._rgba.b)  # noqa: E741
+        if alpha is None:
+            if self._rgba.alpha is None:
+                return h, s, l
+            else:
+                return h, s, l, self._alpha_float()
+        if alpha:
+            return h, s, l, self._alpha_float()
+        else:
+            # alpha is False
+            return h, s, l
+
+    def _alpha_float(self) -> float:
+        return 1 if self._rgba.alpha is None else self._rgba.alpha
+
+    @classmethod
+    def __get_pydantic_core_schema__(
+        cls, source: type[Any], handler: Callable[[Any], CoreSchema]
+    ) -> core_schema.CoreSchema:
+        return core_schema.with_info_plain_validator_function(
+            cls._validate, serialization=core_schema.to_string_ser_schema()
+        )
+
+    @classmethod
+    def _validate(cls, __input_value: Any, _: Any) -> 'Color':
+        return cls(__input_value)
+
+    def __str__(self) -> str:
+        return self.as_named(fallback=True)
+
+    def __repr_args__(self) -> '_repr.ReprArgs':
+        return [(None, self.as_named(fallback=True))] + [('rgb', self.as_rgb_tuple())]
+
+    def __eq__(self, other: Any) -> bool:
+        return isinstance(other, Color) and self.as_rgb_tuple() == other.as_rgb_tuple()
+
+    def __hash__(self) -> int:
+        return hash(self.as_rgb_tuple())
+
+
+def parse_tuple(value: tuple[Any, ...]) -> RGBA:
+    """Parse a tuple or list to get RGBA values.
+
+    Args:
+        value: A tuple or list.
+
+    Returns:
+        An `RGBA` tuple parsed from the input tuple.
+
+    Raises:
+        PydanticCustomError: If tuple is not valid.
+    """
+    if len(value) == 3:
+        r, g, b = (parse_color_value(v) for v in value)
+        return RGBA(r, g, b, None)
+    elif len(value) == 4:
+        r, g, b = (parse_color_value(v) for v in value[:3])
+        return RGBA(r, g, b, parse_float_alpha(value[3]))
+    else:
+        raise PydanticCustomError('color_error', 'value is not a valid color: tuples must have length 3 or 4')
+
+
+def parse_str(value: str) -> RGBA:
+    """Parse a string representing a color to an RGBA tuple.
+
+    Possible formats for the input string include:
+
+    * named color, see `COLORS_BY_NAME`
+    * hex short eg. `fff` (prefix can be `#`, `0x` or nothing)
+    * hex long eg. `ffffff` (prefix can be `#`, `0x` or nothing)
+    * `rgb(, , )`
+    * `rgba(, , , )`
+
+    Args:
+        value: A string representing a color.
+
+    Returns:
+        An `RGBA` tuple parsed from the input string.
+
+    Raises:
+        ValueError: If the input string cannot be parsed to an RGBA tuple.
+    """
+    value_lower = value.lower()
+    try:
+        r, g, b = COLORS_BY_NAME[value_lower]
+    except KeyError:
+        pass
+    else:
+        return ints_to_rgba(r, g, b, None)
+
+    m = re.fullmatch(r_hex_short, value_lower)
+    if m:
+        *rgb, a = m.groups()
+        r, g, b = (int(v * 2, 16) for v in rgb)
+        if a:
+            alpha: Optional[float] = int(a * 2, 16) / 255
+        else:
+            alpha = None
+        return ints_to_rgba(r, g, b, alpha)
+
+    m = re.fullmatch(r_hex_long, value_lower)
+    if m:
+        *rgb, a = m.groups()
+        r, g, b = (int(v, 16) for v in rgb)
+        if a:
+            alpha = int(a, 16) / 255
+        else:
+            alpha = None
+        return ints_to_rgba(r, g, b, alpha)
+
+    m = re.fullmatch(r_rgb, value_lower) or re.fullmatch(r_rgb_v4_style, value_lower)
+    if m:
+        return ints_to_rgba(*m.groups())  # type: ignore
+
+    m = re.fullmatch(r_hsl, value_lower) or re.fullmatch(r_hsl_v4_style, value_lower)
+    if m:
+        return parse_hsl(*m.groups())  # type: ignore
+
+    raise PydanticCustomError('color_error', 'value is not a valid color: string not recognised as a valid color')
+
+
+def ints_to_rgba(r: Union[int, str], g: Union[int, str], b: Union[int, str], alpha: Optional[float] = None) -> RGBA:
+    """Converts integer or string values for RGB color and an optional alpha value to an `RGBA` object.
+
+    Args:
+        r: An integer or string representing the red color value.
+        g: An integer or string representing the green color value.
+        b: An integer or string representing the blue color value.
+        alpha: A float representing the alpha value. Defaults to None.
+
+    Returns:
+        An instance of the `RGBA` class with the corresponding color and alpha values.
+    """
+    return RGBA(parse_color_value(r), parse_color_value(g), parse_color_value(b), parse_float_alpha(alpha))
+
+
+def parse_color_value(value: Union[int, str], max_val: int = 255) -> float:
+    """Parse the color value provided and return a number between 0 and 1.
+
+    Args:
+        value: An integer or string color value.
+        max_val: Maximum range value. Defaults to 255.
+
+    Raises:
+        PydanticCustomError: If the value is not a valid color.
+
+    Returns:
+        A number between 0 and 1.
+    """
+    try:
+        color = float(value)
+    except ValueError:
+        raise PydanticCustomError('color_error', 'value is not a valid color: color values must be a valid number')
+    if 0 <= color <= max_val:
+        return color / max_val
+    else:
+        raise PydanticCustomError(
+            'color_error',
+            'value is not a valid color: color values must be in the range 0 to {max_val}',
+            {'max_val': max_val},
+        )
+
+
+def parse_float_alpha(value: Union[None, str, float, int]) -> Optional[float]:
+    """Parse an alpha value checking it's a valid float in the range 0 to 1.
+
+    Args:
+        value: The input value to parse.
+
+    Returns:
+        The parsed value as a float, or `None` if the value was None or equal 1.
+
+    Raises:
+        PydanticCustomError: If the input value cannot be successfully parsed as a float in the expected range.
+    """
+    if value is None:
+        return None
+    try:
+        if isinstance(value, str) and value.endswith('%'):
+            alpha = float(value[:-1]) / 100
+        else:
+            alpha = float(value)
+    except ValueError:
+        raise PydanticCustomError('color_error', 'value is not a valid color: alpha values must be a valid float')
+
+    if math.isclose(alpha, 1):
+        return None
+    elif 0 <= alpha <= 1:
+        return alpha
+    else:
+        raise PydanticCustomError('color_error', 'value is not a valid color: alpha values must be in the range 0 to 1')
+
+
+def parse_hsl(h: str, h_units: str, sat: str, light: str, alpha: Optional[float] = None) -> RGBA:
+    """Parse raw hue, saturation, lightness, and alpha values and convert to RGBA.
+
+    Args:
+        h: The hue value.
+        h_units: The unit for hue value.
+        sat: The saturation value.
+        light: The lightness value.
+        alpha: Alpha value.
+
+    Returns:
+        An instance of `RGBA`.
+    """
+    s_value, l_value = parse_color_value(sat, 100), parse_color_value(light, 100)
+
+    h_value = float(h)
+    if h_units in {None, 'deg'}:
+        h_value = h_value % 360 / 360
+    elif h_units == 'rad':
+        h_value = h_value % rads / rads
+    else:
+        # turns
+        h_value = h_value % 1
+
+    r, g, b = hls_to_rgb(h_value, l_value, s_value)
+    return RGBA(r, g, b, parse_float_alpha(alpha))
+
+
+def float_to_255(c: float) -> int:
+    """Converts a float value between 0 and 1 (inclusive) to an integer between 0 and 255 (inclusive).
+
+    Args:
+        c: The float value to be converted. Must be between 0 and 1 (inclusive).
+
+    Returns:
+        The integer equivalent of the given float value rounded to the nearest whole number.
+
+    Raises:
+        ValueError: If the given float value is outside the acceptable range of 0 to 1 (inclusive).
+    """
+    return int(round(c * 255))
+
+
+COLORS_BY_NAME = {
+    'aliceblue': (240, 248, 255),
+    'antiquewhite': (250, 235, 215),
+    'aqua': (0, 255, 255),
+    'aquamarine': (127, 255, 212),
+    'azure': (240, 255, 255),
+    'beige': (245, 245, 220),
+    'bisque': (255, 228, 196),
+    'black': (0, 0, 0),
+    'blanchedalmond': (255, 235, 205),
+    'blue': (0, 0, 255),
+    'blueviolet': (138, 43, 226),
+    'brown': (165, 42, 42),
+    'burlywood': (222, 184, 135),
+    'cadetblue': (95, 158, 160),
+    'chartreuse': (127, 255, 0),
+    'chocolate': (210, 105, 30),
+    'coral': (255, 127, 80),
+    'cornflowerblue': (100, 149, 237),
+    'cornsilk': (255, 248, 220),
+    'crimson': (220, 20, 60),
+    'cyan': (0, 255, 255),
+    'darkblue': (0, 0, 139),
+    'darkcyan': (0, 139, 139),
+    'darkgoldenrod': (184, 134, 11),
+    'darkgray': (169, 169, 169),
+    'darkgreen': (0, 100, 0),
+    'darkgrey': (169, 169, 169),
+    'darkkhaki': (189, 183, 107),
+    'darkmagenta': (139, 0, 139),
+    'darkolivegreen': (85, 107, 47),
+    'darkorange': (255, 140, 0),
+    'darkorchid': (153, 50, 204),
+    'darkred': (139, 0, 0),
+    'darksalmon': (233, 150, 122),
+    'darkseagreen': (143, 188, 143),
+    'darkslateblue': (72, 61, 139),
+    'darkslategray': (47, 79, 79),
+    'darkslategrey': (47, 79, 79),
+    'darkturquoise': (0, 206, 209),
+    'darkviolet': (148, 0, 211),
+    'deeppink': (255, 20, 147),
+    'deepskyblue': (0, 191, 255),
+    'dimgray': (105, 105, 105),
+    'dimgrey': (105, 105, 105),
+    'dodgerblue': (30, 144, 255),
+    'firebrick': (178, 34, 34),
+    'floralwhite': (255, 250, 240),
+    'forestgreen': (34, 139, 34),
+    'fuchsia': (255, 0, 255),
+    'gainsboro': (220, 220, 220),
+    'ghostwhite': (248, 248, 255),
+    'gold': (255, 215, 0),
+    'goldenrod': (218, 165, 32),
+    'gray': (128, 128, 128),
+    'green': (0, 128, 0),
+    'greenyellow': (173, 255, 47),
+    'grey': (128, 128, 128),
+    'honeydew': (240, 255, 240),
+    'hotpink': (255, 105, 180),
+    'indianred': (205, 92, 92),
+    'indigo': (75, 0, 130),
+    'ivory': (255, 255, 240),
+    'khaki': (240, 230, 140),
+    'lavender': (230, 230, 250),
+    'lavenderblush': (255, 240, 245),
+    'lawngreen': (124, 252, 0),
+    'lemonchiffon': (255, 250, 205),
+    'lightblue': (173, 216, 230),
+    'lightcoral': (240, 128, 128),
+    'lightcyan': (224, 255, 255),
+    'lightgoldenrodyellow': (250, 250, 210),
+    'lightgray': (211, 211, 211),
+    'lightgreen': (144, 238, 144),
+    'lightgrey': (211, 211, 211),
+    'lightpink': (255, 182, 193),
+    'lightsalmon': (255, 160, 122),
+    'lightseagreen': (32, 178, 170),
+    'lightskyblue': (135, 206, 250),
+    'lightslategray': (119, 136, 153),
+    'lightslategrey': (119, 136, 153),
+    'lightsteelblue': (176, 196, 222),
+    'lightyellow': (255, 255, 224),
+    'lime': (0, 255, 0),
+    'limegreen': (50, 205, 50),
+    'linen': (250, 240, 230),
+    'magenta': (255, 0, 255),
+    'maroon': (128, 0, 0),
+    'mediumaquamarine': (102, 205, 170),
+    'mediumblue': (0, 0, 205),
+    'mediumorchid': (186, 85, 211),
+    'mediumpurple': (147, 112, 219),
+    'mediumseagreen': (60, 179, 113),
+    'mediumslateblue': (123, 104, 238),
+    'mediumspringgreen': (0, 250, 154),
+    'mediumturquoise': (72, 209, 204),
+    'mediumvioletred': (199, 21, 133),
+    'midnightblue': (25, 25, 112),
+    'mintcream': (245, 255, 250),
+    'mistyrose': (255, 228, 225),
+    'moccasin': (255, 228, 181),
+    'navajowhite': (255, 222, 173),
+    'navy': (0, 0, 128),
+    'oldlace': (253, 245, 230),
+    'olive': (128, 128, 0),
+    'olivedrab': (107, 142, 35),
+    'orange': (255, 165, 0),
+    'orangered': (255, 69, 0),
+    'orchid': (218, 112, 214),
+    'palegoldenrod': (238, 232, 170),
+    'palegreen': (152, 251, 152),
+    'paleturquoise': (175, 238, 238),
+    'palevioletred': (219, 112, 147),
+    'papayawhip': (255, 239, 213),
+    'peachpuff': (255, 218, 185),
+    'peru': (205, 133, 63),
+    'pink': (255, 192, 203),
+    'plum': (221, 160, 221),
+    'powderblue': (176, 224, 230),
+    'purple': (128, 0, 128),
+    'red': (255, 0, 0),
+    'rosybrown': (188, 143, 143),
+    'royalblue': (65, 105, 225),
+    'saddlebrown': (139, 69, 19),
+    'salmon': (250, 128, 114),
+    'sandybrown': (244, 164, 96),
+    'seagreen': (46, 139, 87),
+    'seashell': (255, 245, 238),
+    'sienna': (160, 82, 45),
+    'silver': (192, 192, 192),
+    'skyblue': (135, 206, 235),
+    'slateblue': (106, 90, 205),
+    'slategray': (112, 128, 144),
+    'slategrey': (112, 128, 144),
+    'snow': (255, 250, 250),
+    'springgreen': (0, 255, 127),
+    'steelblue': (70, 130, 180),
+    'tan': (210, 180, 140),
+    'teal': (0, 128, 128),
+    'thistle': (216, 191, 216),
+    'tomato': (255, 99, 71),
+    'turquoise': (64, 224, 208),
+    'violet': (238, 130, 238),
+    'wheat': (245, 222, 179),
+    'white': (255, 255, 255),
+    'whitesmoke': (245, 245, 245),
+    'yellow': (255, 255, 0),
+    'yellowgreen': (154, 205, 50),
+}
+
+COLORS_BY_VALUE = {v: k for k, v in COLORS_BY_NAME.items()}
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pydantic/config.py b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/config.py
new file mode 100644
index 0000000000000000000000000000000000000000..bbf57aa4b15564876b5a5bfe9979ee3081f5cea9
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/config.py
@@ -0,0 +1,1288 @@
+"""Configuration for Pydantic models."""
+
+from __future__ import annotations as _annotations
+
+import warnings
+from re import Pattern
+from typing import TYPE_CHECKING, Any, Callable, Literal, TypeVar, Union, cast, overload
+
+from typing_extensions import TypeAlias, TypedDict, Unpack, deprecated
+
+from ._migration import getattr_migration
+from .aliases import AliasGenerator
+from .errors import PydanticUserError
+from .warnings import PydanticDeprecatedSince211
+
+if TYPE_CHECKING:
+    from ._internal._generate_schema import GenerateSchema as _GenerateSchema
+    from .fields import ComputedFieldInfo, FieldInfo
+
+__all__ = ('ConfigDict', 'with_config')
+
+
+JsonValue: TypeAlias = Union[int, float, str, bool, None, list['JsonValue'], 'JsonDict']
+JsonDict: TypeAlias = dict[str, JsonValue]
+
+JsonEncoder = Callable[[Any], Any]
+
+JsonSchemaExtraCallable: TypeAlias = Union[
+    Callable[[JsonDict], None],
+    Callable[[JsonDict, type[Any]], None],
+]
+
+ExtraValues = Literal['allow', 'ignore', 'forbid']
+
+
+class ConfigDict(TypedDict, total=False):
+    """A TypedDict for configuring Pydantic behaviour."""
+
+    title: str | None
+    """The title for the generated JSON schema, defaults to the model's name"""
+
+    model_title_generator: Callable[[type], str] | None
+    """A callable that takes a model class and returns the title for it. Defaults to `None`."""
+
+    field_title_generator: Callable[[str, FieldInfo | ComputedFieldInfo], str] | None
+    """A callable that takes a field's name and info and returns title for it. Defaults to `None`."""
+
+    str_to_lower: bool
+    """Whether to convert all characters to lowercase for str types. Defaults to `False`."""
+
+    str_to_upper: bool
+    """Whether to convert all characters to uppercase for str types. Defaults to `False`."""
+
+    str_strip_whitespace: bool
+    """Whether to strip leading and trailing whitespace for str types."""
+
+    str_min_length: int
+    """The minimum length for str types. Defaults to `None`."""
+
+    str_max_length: int | None
+    """The maximum length for str types. Defaults to `None`."""
+
+    extra: ExtraValues | None
+    '''
+    Whether to ignore, allow, or forbid extra data during model initialization. Defaults to `'ignore'`.
+
+    Three configuration values are available:
+
+    - `'ignore'`: Providing extra data is ignored (the default):
+      ```python
+      from pydantic import BaseModel, ConfigDict
+
+      class User(BaseModel):
+          model_config = ConfigDict(extra='ignore')  # (1)!
+
+          name: str
+
+      user = User(name='John Doe', age=20)  # (2)!
+      print(user)
+      #> name='John Doe'
+      ```
+
+        1. This is the default behaviour.
+        2. The `age` argument is ignored.
+
+    - `'forbid'`: Providing extra data is not permitted, and a [`ValidationError`][pydantic_core.ValidationError]
+      will be raised if this is the case:
+      ```python
+      from pydantic import BaseModel, ConfigDict, ValidationError
+
+
+      class Model(BaseModel):
+          x: int
+
+          model_config = ConfigDict(extra='forbid')
+
+
+      try:
+          Model(x=1, y='a')
+      except ValidationError as exc:
+          print(exc)
+          """
+          1 validation error for Model
+          y
+            Extra inputs are not permitted [type=extra_forbidden, input_value='a', input_type=str]
+          """
+      ```
+
+    - `'allow'`: Providing extra data is allowed and stored in the `__pydantic_extra__` dictionary attribute:
+      ```python
+      from pydantic import BaseModel, ConfigDict
+
+
+      class Model(BaseModel):
+          x: int
+
+          model_config = ConfigDict(extra='allow')
+
+
+      m = Model(x=1, y='a')
+      assert m.__pydantic_extra__ == {'y': 'a'}
+      ```
+      By default, no validation will be applied to these extra items, but you can set a type for the values by overriding
+      the type annotation for `__pydantic_extra__`:
+      ```python
+      from pydantic import BaseModel, ConfigDict, Field, ValidationError
+
+
+      class Model(BaseModel):
+          __pydantic_extra__: dict[str, int] = Field(init=False)  # (1)!
+
+          x: int
+
+          model_config = ConfigDict(extra='allow')
+
+
+      try:
+          Model(x=1, y='a')
+      except ValidationError as exc:
+          print(exc)
+          """
+          1 validation error for Model
+          y
+            Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='a', input_type=str]
+          """
+
+      m = Model(x=1, y='2')
+      assert m.x == 1
+      assert m.y == 2
+      assert m.model_dump() == {'x': 1, 'y': 2}
+      assert m.__pydantic_extra__ == {'y': 2}
+      ```
+
+        1. The `= Field(init=False)` does not have any effect at runtime, but prevents the `__pydantic_extra__` field from
+           being included as a parameter to the model's `__init__` method by type checkers.
+
+    As well as specifying an `extra` configuration value on the model, you can also provide it as an argument to the validation methods.
+    This will override any `extra` configuration value set on the model:
+    ```python
+    from pydantic import BaseModel, ConfigDict, ValidationError
+
+    class Model(BaseModel):
+        x: int
+        model_config = ConfigDict(extra="allow")
+
+    try:
+        # Override model config and forbid extra fields just this time
+        Model.model_validate({"x": 1, "y": 2}, extra="forbid")
+    except ValidationError as exc:
+        print(exc)
+        """
+        1 validation error for Model
+        y
+          Extra inputs are not permitted [type=extra_forbidden, input_value=2, input_type=int]
+        """
+    ```
+    '''
+
+    frozen: bool
+    """
+    Whether models are faux-immutable, i.e. whether `__setattr__` is allowed, and also generates
+    a `__hash__()` method for the model. This makes instances of the model potentially hashable if all the
+    attributes are hashable. Defaults to `False`.
+
+    Note:
+        On V1, the inverse of this setting was called `allow_mutation`, and was `True` by default.
+    """
+
+    populate_by_name: bool
+    """
+    Whether an aliased field may be populated by its name as given by the model
+    attribute, as well as the alias. Defaults to `False`.
+
+    !!! warning
+        `populate_by_name` usage is not recommended in v2.11+ and will be deprecated in v3.
+        Instead, you should use the [`validate_by_name`][pydantic.config.ConfigDict.validate_by_name] configuration setting.
+
+        When `validate_by_name=True` and `validate_by_alias=True`, this is strictly equivalent to the
+        previous behavior of `populate_by_name=True`.
+
+        In v2.11, we also introduced a [`validate_by_alias`][pydantic.config.ConfigDict.validate_by_alias] setting that introduces more fine grained
+        control for validation behavior.
+
+        Here's how you might go about using the new settings to achieve the same behavior:
+
+        ```python
+        from pydantic import BaseModel, ConfigDict, Field
+
+        class Model(BaseModel):
+            model_config = ConfigDict(validate_by_name=True, validate_by_alias=True)
+
+            my_field: str = Field(alias='my_alias')  # (1)!
+
+        m = Model(my_alias='foo')  # (2)!
+        print(m)
+        #> my_field='foo'
+
+        m = Model(my_field='foo')  # (3)!
+        print(m)
+        #> my_field='foo'
+        ```
+
+        1. The field `'my_field'` has an alias `'my_alias'`.
+        2. The model is populated by the alias `'my_alias'`.
+        3. The model is populated by the attribute name `'my_field'`.
+    """
+
+    use_enum_values: bool
+    """
+    Whether to populate models with the `value` property of enums, rather than the raw enum.
+    This may be useful if you want to serialize `model.model_dump()` later. Defaults to `False`.
+
+    !!! note
+        If you have an `Optional[Enum]` value that you set a default for, you need to use `validate_default=True`
+        for said Field to ensure that the `use_enum_values` flag takes effect on the default, as extracting an
+        enum's value occurs during validation, not serialization.
+
+    ```python
+    from enum import Enum
+    from typing import Optional
+
+    from pydantic import BaseModel, ConfigDict, Field
+
+    class SomeEnum(Enum):
+        FOO = 'foo'
+        BAR = 'bar'
+        BAZ = 'baz'
+
+    class SomeModel(BaseModel):
+        model_config = ConfigDict(use_enum_values=True)
+
+        some_enum: SomeEnum
+        another_enum: Optional[SomeEnum] = Field(
+            default=SomeEnum.FOO, validate_default=True
+        )
+
+    model1 = SomeModel(some_enum=SomeEnum.BAR)
+    print(model1.model_dump())
+    #> {'some_enum': 'bar', 'another_enum': 'foo'}
+
+    model2 = SomeModel(some_enum=SomeEnum.BAR, another_enum=SomeEnum.BAZ)
+    print(model2.model_dump())
+    #> {'some_enum': 'bar', 'another_enum': 'baz'}
+    ```
+    """
+
+    validate_assignment: bool
+    """
+    Whether to validate the data when the model is changed. Defaults to `False`.
+
+    The default behavior of Pydantic is to validate the data when the model is created.
+
+    In case the user changes the data after the model is created, the model is _not_ revalidated.
+
+    ```python
+    from pydantic import BaseModel
+
+    class User(BaseModel):
+        name: str
+
+    user = User(name='John Doe')  # (1)!
+    print(user)
+    #> name='John Doe'
+    user.name = 123  # (1)!
+    print(user)
+    #> name=123
+    ```
+
+    1. The validation happens only when the model is created.
+    2. The validation does not happen when the data is changed.
+
+    In case you want to revalidate the model when the data is changed, you can use `validate_assignment=True`:
+
+    ```python
+    from pydantic import BaseModel, ValidationError
+
+    class User(BaseModel, validate_assignment=True):  # (1)!
+        name: str
+
+    user = User(name='John Doe')  # (2)!
+    print(user)
+    #> name='John Doe'
+    try:
+        user.name = 123  # (3)!
+    except ValidationError as e:
+        print(e)
+        '''
+        1 validation error for User
+        name
+          Input should be a valid string [type=string_type, input_value=123, input_type=int]
+        '''
+    ```
+
+    1. You can either use class keyword arguments, or `model_config` to set `validate_assignment=True`.
+    2. The validation happens when the model is created.
+    3. The validation _also_ happens when the data is changed.
+    """
+
+    arbitrary_types_allowed: bool
+    """
+    Whether arbitrary types are allowed for field types. Defaults to `False`.
+
+    ```python
+    from pydantic import BaseModel, ConfigDict, ValidationError
+
+    # This is not a pydantic model, it's an arbitrary class
+    class Pet:
+        def __init__(self, name: str):
+            self.name = name
+
+    class Model(BaseModel):
+        model_config = ConfigDict(arbitrary_types_allowed=True)
+
+        pet: Pet
+        owner: str
+
+    pet = Pet(name='Hedwig')
+    # A simple check of instance type is used to validate the data
+    model = Model(owner='Harry', pet=pet)
+    print(model)
+    #> pet=<__main__.Pet object at 0x0123456789ab> owner='Harry'
+    print(model.pet)
+    #> <__main__.Pet object at 0x0123456789ab>
+    print(model.pet.name)
+    #> Hedwig
+    print(type(model.pet))
+    #> 
+    try:
+        # If the value is not an instance of the type, it's invalid
+        Model(owner='Harry', pet='Hedwig')
+    except ValidationError as e:
+        print(e)
+        '''
+        1 validation error for Model
+        pet
+          Input should be an instance of Pet [type=is_instance_of, input_value='Hedwig', input_type=str]
+        '''
+
+    # Nothing in the instance of the arbitrary type is checked
+    # Here name probably should have been a str, but it's not validated
+    pet2 = Pet(name=42)
+    model2 = Model(owner='Harry', pet=pet2)
+    print(model2)
+    #> pet=<__main__.Pet object at 0x0123456789ab> owner='Harry'
+    print(model2.pet)
+    #> <__main__.Pet object at 0x0123456789ab>
+    print(model2.pet.name)
+    #> 42
+    print(type(model2.pet))
+    #> 
+    ```
+    """
+
+    from_attributes: bool
+    """
+    Whether to build models and look up discriminators of tagged unions using python object attributes.
+    """
+
+    loc_by_alias: bool
+    """Whether to use the actual key provided in the data (e.g. alias) for error `loc`s rather than the field's name. Defaults to `True`."""
+
+    alias_generator: Callable[[str], str] | AliasGenerator | None
+    """
+    A callable that takes a field name and returns an alias for it
+    or an instance of [`AliasGenerator`][pydantic.aliases.AliasGenerator]. Defaults to `None`.
+
+    When using a callable, the alias generator is used for both validation and serialization.
+    If you want to use different alias generators for validation and serialization, you can use
+    [`AliasGenerator`][pydantic.aliases.AliasGenerator] instead.
+
+    If data source field names do not match your code style (e.g. CamelCase fields),
+    you can automatically generate aliases using `alias_generator`. Here's an example with
+    a basic callable:
+
+    ```python
+    from pydantic import BaseModel, ConfigDict
+    from pydantic.alias_generators import to_pascal
+
+    class Voice(BaseModel):
+        model_config = ConfigDict(alias_generator=to_pascal)
+
+        name: str
+        language_code: str
+
+    voice = Voice(Name='Filiz', LanguageCode='tr-TR')
+    print(voice.language_code)
+    #> tr-TR
+    print(voice.model_dump(by_alias=True))
+    #> {'Name': 'Filiz', 'LanguageCode': 'tr-TR'}
+    ```
+
+    If you want to use different alias generators for validation and serialization, you can use
+    [`AliasGenerator`][pydantic.aliases.AliasGenerator].
+
+    ```python
+    from pydantic import AliasGenerator, BaseModel, ConfigDict
+    from pydantic.alias_generators import to_camel, to_pascal
+
+    class Athlete(BaseModel):
+        first_name: str
+        last_name: str
+        sport: str
+
+        model_config = ConfigDict(
+            alias_generator=AliasGenerator(
+                validation_alias=to_camel,
+                serialization_alias=to_pascal,
+            )
+        )
+
+    athlete = Athlete(firstName='John', lastName='Doe', sport='track')
+    print(athlete.model_dump(by_alias=True))
+    #> {'FirstName': 'John', 'LastName': 'Doe', 'Sport': 'track'}
+    ```
+
+    Note:
+        Pydantic offers three built-in alias generators: [`to_pascal`][pydantic.alias_generators.to_pascal],
+        [`to_camel`][pydantic.alias_generators.to_camel], and [`to_snake`][pydantic.alias_generators.to_snake].
+    """
+
+    ignored_types: tuple[type, ...]
+    """A tuple of types that may occur as values of class attributes without annotations. This is
+    typically used for custom descriptors (classes that behave like `property`). If an attribute is set on a
+    class without an annotation and has a type that is not in this tuple (or otherwise recognized by
+    _pydantic_), an error will be raised. Defaults to `()`.
+    """
+
+    allow_inf_nan: bool
+    """Whether to allow infinity (`+inf` an `-inf`) and NaN values to float and decimal fields. Defaults to `True`."""
+
+    json_schema_extra: JsonDict | JsonSchemaExtraCallable | None
+    """A dict or callable to provide extra JSON schema properties. Defaults to `None`."""
+
+    json_encoders: dict[type[object], JsonEncoder] | None
+    """
+    A `dict` of custom JSON encoders for specific types. Defaults to `None`.
+
+    /// version-deprecated | v2
+    This configuration option is a carryover from v1. We originally planned to remove it in v2 but didn't have a 1:1 replacement
+    so we are keeping it for now. It is still deprecated and will likely be removed in the future.
+    ///
+    """
+
+    # new in V2
+    strict: bool
+    """
+    Whether strict validation is applied to all fields on the model.
+
+    By default, Pydantic attempts to coerce values to the correct type, when possible.
+
+    There are situations in which you may want to disable this behavior, and instead raise an error if a value's type
+    does not match the field's type annotation.
+
+    To configure strict mode for all fields on a model, you can set `strict=True` on the model.
+
+    ```python
+    from pydantic import BaseModel, ConfigDict
+
+    class Model(BaseModel):
+        model_config = ConfigDict(strict=True)
+
+        name: str
+        age: int
+    ```
+
+    See [Strict Mode](../concepts/strict_mode.md) for more details.
+
+    See the [Conversion Table](../concepts/conversion_table.md) for more details on how Pydantic converts data in both
+    strict and lax modes.
+
+    /// version-added | v2
+    ///
+    """
+    # whether instances of models and dataclasses (including subclass instances) should re-validate, default 'never'
+    revalidate_instances: Literal['always', 'never', 'subclass-instances']
+    """
+    When and how to revalidate models and dataclasses during validation. Can be one of:
+
+    - `'never'`: will *not* revalidate models and dataclasses during validation
+    - `'always'`: will revalidate models and dataclasses during validation
+    - `'subclass-instances'`: will revalidate models and dataclasses during validation if the instance is a
+        subclass of the model or dataclass
+
+    The default is `'never'` (no revalidation).
+
+    This configuration only affects *the current model* it is applied on, and does *not* populate to the models
+    referenced in fields.
+
+    ```python
+    from pydantic import BaseModel
+
+    class User(BaseModel, revalidate_instances='never'):  # (1)!
+        name: str
+
+    class Transaction(BaseModel):
+        user: User
+
+    my_user = User(name='John')
+    t = Transaction(user=my_user)
+
+    my_user.name = 1  # (2)!
+    t = Transaction(user=my_user)  # (3)!
+    print(t)
+    #> user=User(name=1)
+    ```
+
+    1. This is the default behavior.
+    2. The assignment is *not* validated, unless you set [`validate_assignment`][pydantic.ConfigDict.validate_assignment] in the configuration.
+    3. Since `revalidate_instances` is set to `'never'`, the user instance is not revalidated.
+
+    Here is an example demonstrating the behavior of `'subclass-instances'`:
+
+    ```python
+    from pydantic import BaseModel
+
+    class User(BaseModel, revalidate_instances='subclass-instances'):
+        name: str
+
+    class SubUser(User):
+        age: int
+
+    class Transaction(BaseModel):
+        user: User
+
+    my_user = User(name='John')
+    my_user.name = 1  # (1)!
+    t = Transaction(user=my_user)  # (2)!
+    print(t)
+    #> user=User(name=1)
+
+    my_sub_user = SubUser(name='John', age=20)
+    t = Transaction(user=my_sub_user)
+    print(t)  # (3)!
+    #> user=User(name='John')
+    ```
+
+    1. The assignment is *not* validated, unless you set [`validate_assignment`][pydantic.ConfigDict.validate_assignment] in the configuration.
+    2. Because `my_user` is a "direct" instance of `User`, it is *not* being revalidated. It would have been the case if
+      `revalidate_instances` was set to `'always'`.
+    3. Because `my_sub_user` is an instance of a `User` subclass, it is being revalidated. In this case, Pydantic coerces `my_sub_user` to the defined
+       `User` class defined on `Transaction`. If one of its fields had an invalid value, a validation error would have been raised.
+
+    /// version-added | v2
+    ///
+    """
+
+    ser_json_timedelta: Literal['iso8601', 'float']
+    """
+    The format of JSON serialized timedeltas. Accepts the string values of `'iso8601'` and
+    `'float'`. Defaults to `'iso8601'`.
+
+    - `'iso8601'` will serialize timedeltas to [ISO 8601 text format](https://en.wikipedia.org/wiki/ISO_8601#Durations).
+    - `'float'` will serialize timedeltas to the total number of seconds.
+
+    /// version-changed | v2.12
+    It is now recommended to use the [`ser_json_temporal`][pydantic.config.ConfigDict.ser_json_temporal]
+    setting. `ser_json_timedelta` will be deprecated in v3.
+    ///
+    """
+
+    ser_json_temporal: Literal['iso8601', 'seconds', 'milliseconds']
+    """
+    The format of JSON serialized temporal types from the [`datetime`][] module. This includes:
+
+    - [`datetime.datetime`][]
+    - [`datetime.date`][]
+    - [`datetime.time`][]
+    - [`datetime.timedelta`][]
+
+    Can be one of:
+
+    - `'iso8601'` will serialize date-like types to [ISO 8601 text format](https://en.wikipedia.org/wiki/ISO_8601#Durations).
+    - `'milliseconds'` will serialize date-like types to a floating point number of milliseconds since the epoch.
+    - `'seconds'` will serialize date-like types to a floating point number of seconds since the epoch.
+
+    Defaults to `'iso8601'`.
+
+    /// version-added | v2.12
+    This setting replaces [`ser_json_timedelta`][pydantic.config.ConfigDict.ser_json_timedelta],
+    which will be deprecated in v3. `ser_json_temporal` adds more configurability for the other temporal types.
+    ///
+    """
+
+    val_temporal_unit: Literal['seconds', 'milliseconds', 'infer']
+    """
+    The unit to assume for validating numeric input for datetime-like types ([`datetime.datetime`][] and [`datetime.date`][]). Can be one of:
+
+    - `'seconds'` will validate date or time numeric inputs as seconds since the [epoch].
+    - `'milliseconds'` will validate date or time numeric inputs as milliseconds since the [epoch].
+    - `'infer'` will infer the unit from the string numeric input on unix time as:
+
+        * seconds since the [epoch] if $-2^{10} <= v <= 2^{10}$
+        * milliseconds since the [epoch] (if $v < -2^{10}$ or $v > 2^{10}$).
+
+    Defaults to `'infer'`.
+
+    /// version-added | v2.12
+    ///
+
+    [epoch]: https://en.wikipedia.org/wiki/Unix_time
+    """
+
+    ser_json_bytes: Literal['utf8', 'base64', 'hex']
+    """
+    The encoding of JSON serialized bytes. Defaults to `'utf8'`.
+    Set equal to `val_json_bytes` to get back an equal value after serialization round trip.
+
+    - `'utf8'` will serialize bytes to UTF-8 strings.
+    - `'base64'` will serialize bytes to URL safe base64 strings.
+    - `'hex'` will serialize bytes to hexadecimal strings.
+    """
+
+    val_json_bytes: Literal['utf8', 'base64', 'hex']
+    """
+    The encoding of JSON serialized bytes to decode. Defaults to `'utf8'`.
+    Set equal to `ser_json_bytes` to get back an equal value after serialization round trip.
+
+    - `'utf8'` will deserialize UTF-8 strings to bytes.
+    - `'base64'` will deserialize URL safe base64 strings to bytes.
+    - `'hex'` will deserialize hexadecimal strings to bytes.
+    """
+
+    ser_json_inf_nan: Literal['null', 'constants', 'strings']
+    """
+    The encoding of JSON serialized infinity and NaN float values. Defaults to `'null'`.
+
+    - `'null'` will serialize infinity and NaN values as `null`.
+    - `'constants'` will serialize infinity and NaN values as `Infinity` and `NaN`.
+    - `'strings'` will serialize infinity as string `"Infinity"` and NaN as string `"NaN"`.
+    """
+
+    # whether to validate default values during validation, default False
+    validate_default: bool
+    """Whether to validate default values during validation. Defaults to `False`."""
+
+    validate_return: bool
+    """Whether to validate the return value from call validators. Defaults to `False`."""
+
+    protected_namespaces: tuple[str | Pattern[str], ...]
+    """
+    A tuple of strings and/or regex patterns that prevent models from having fields with names that conflict with its existing members/methods.
+
+    Strings are matched on a prefix basis. For instance, with `'dog'`, having a field named `'dog_name'` will be disallowed.
+
+    Regex patterns are matched on the entire field name. For instance, with the pattern `'^dog$'`, having a field named `'dog'` will be disallowed,
+    but `'dog_name'` will be accepted.
+
+    Defaults to `('model_validate', 'model_dump')`. This default is used to prevent collisions with the existing (and possibly future)
+    [validation](../concepts/models.md#validating-data) and [serialization](../concepts/serialization.md#serializing-data) methods.
+
+    ```python
+    import warnings
+
+    from pydantic import BaseModel
+
+    warnings.filterwarnings('error')  # Raise warnings as errors
+
+    try:
+
+        class Model(BaseModel):
+            model_dump_something: str
+
+    except UserWarning as e:
+        print(e)
+        '''
+        Field 'model_dump_something' in 'Model' conflicts with protected namespace 'model_dump'.
+
+        You may be able to solve this by setting the 'protected_namespaces' configuration to ('model_validate',).
+        '''
+    ```
+
+    You can customize this behavior using the `protected_namespaces` setting:
+
+    ```python {test="skip"}
+    import re
+    import warnings
+
+    from pydantic import BaseModel, ConfigDict
+
+    with warnings.catch_warnings(record=True) as caught_warnings:
+        warnings.simplefilter('always')  # Catch all warnings
+
+        class Model(BaseModel):
+            safe_field: str
+            also_protect_field: str
+            protect_this: str
+
+            model_config = ConfigDict(
+                protected_namespaces=(
+                    'protect_me_',
+                    'also_protect_',
+                    re.compile('^protect_this$'),
+                )
+            )
+
+    for warning in caught_warnings:
+        print(f'{warning.message}')
+        '''
+        Field 'also_protect_field' in 'Model' conflicts with protected namespace 'also_protect_'.
+        You may be able to solve this by setting the 'protected_namespaces' configuration to ('protect_me_', re.compile('^protect_this$'))`.
+
+        Field 'protect_this' in 'Model' conflicts with protected namespace 're.compile('^protect_this$')'.
+        You may be able to solve this by setting the 'protected_namespaces' configuration to ('protect_me_', 'also_protect_')`.
+        '''
+    ```
+
+    While Pydantic will only emit a warning when an item is in a protected namespace but does not actually have a collision,
+    an error _is_ raised if there is an actual collision with an existing attribute:
+
+    ```python
+    from pydantic import BaseModel, ConfigDict
+
+    try:
+
+        class Model(BaseModel):
+            model_validate: str
+
+            model_config = ConfigDict(protected_namespaces=('model_',))
+
+    except ValueError as e:
+        print(e)
+        '''
+        Field 'model_validate' conflicts with member > of protected namespace 'model_'.
+        '''
+    ```
+
+    /// version-changed | v2.10
+    The default protected namespaces was changed from `('model_',)` to `('model_validate', 'model_dump')`, to allow
+    for fields like `model_id`, `model_name` to be used.
+    ///
+    """
+
+    hide_input_in_errors: bool
+    """
+    Whether to hide inputs when printing errors. Defaults to `False`.
+
+    Pydantic shows the input value and type when it raises `ValidationError` during the validation.
+
+    ```python
+    from pydantic import BaseModel, ValidationError
+
+    class Model(BaseModel):
+        a: str
+
+    try:
+        Model(a=123)
+    except ValidationError as e:
+        print(e)
+        '''
+        1 validation error for Model
+        a
+          Input should be a valid string [type=string_type, input_value=123, input_type=int]
+        '''
+    ```
+
+    You can hide the input value and type by setting the `hide_input_in_errors` config to `True`.
+
+    ```python
+    from pydantic import BaseModel, ConfigDict, ValidationError
+
+    class Model(BaseModel):
+        a: str
+        model_config = ConfigDict(hide_input_in_errors=True)
+
+    try:
+        Model(a=123)
+    except ValidationError as e:
+        print(e)
+        '''
+        1 validation error for Model
+        a
+          Input should be a valid string [type=string_type]
+        '''
+    ```
+    """
+
+    defer_build: bool
+    """
+    Whether to defer model validator and serializer construction until the first model validation. Defaults to False.
+
+    This can be useful to avoid the overhead of building models which are only
+    used nested within other models, or when you want to manually define type namespace via
+    [`Model.model_rebuild(_types_namespace=...)`][pydantic.BaseModel.model_rebuild].
+
+    /// version-changed | v2.10
+    The setting also applies to [Pydantic dataclasses](../concepts/dataclasses.md) and [type adapters](../concepts/type_adapter.md).
+    ///
+    """
+
+    plugin_settings: dict[str, object] | None
+    """A `dict` of settings for plugins. Defaults to `None`."""
+
+    schema_generator: type[_GenerateSchema] | None
+    """
+    The `GenerateSchema` class to use during core schema generation.
+
+    /// version-deprecated | v2.10
+    The `GenerateSchema` class is private and highly subject to change.
+    ///
+    """
+
+    json_schema_serialization_defaults_required: bool
+    """
+    Whether fields with default values should be marked as required in the serialization schema. Defaults to `False`.
+
+    This ensures that the serialization schema will reflect the fact a field with a default will always be present
+    when serializing the model, even though it is not required for validation.
+
+    However, there are scenarios where this may be undesirable — in particular, if you want to share the schema
+    between validation and serialization, and don't mind fields with defaults being marked as not required during
+    serialization. See [#7209](https://github.com/pydantic/pydantic/issues/7209) for more details.
+
+    ```python
+    from pydantic import BaseModel, ConfigDict
+
+    class Model(BaseModel):
+        a: str = 'a'
+
+        model_config = ConfigDict(json_schema_serialization_defaults_required=True)
+
+    print(Model.model_json_schema(mode='validation'))
+    '''
+    {
+        'properties': {'a': {'default': 'a', 'title': 'A', 'type': 'string'}},
+        'title': 'Model',
+        'type': 'object',
+    }
+    '''
+    print(Model.model_json_schema(mode='serialization'))
+    '''
+    {
+        'properties': {'a': {'default': 'a', 'title': 'A', 'type': 'string'}},
+        'required': ['a'],
+        'title': 'Model',
+        'type': 'object',
+    }
+    '''
+    ```
+
+    /// version-added | v2.4
+    ///
+    """
+
+    json_schema_mode_override: Literal['validation', 'serialization', None]
+    """
+    If not `None`, the specified mode will be used to generate the JSON schema regardless of what `mode` was passed to
+    the function call. Defaults to `None`.
+
+    This provides a way to force the JSON schema generation to reflect a specific mode, e.g., to always use the
+    validation schema.
+
+    It can be useful when using frameworks (such as FastAPI) that may generate different schemas for validation
+    and serialization that must both be referenced from the same schema; when this happens, we automatically append
+    `-Input` to the definition reference for the validation schema and `-Output` to the definition reference for the
+    serialization schema. By specifying a `json_schema_mode_override` though, this prevents the conflict between
+    the validation and serialization schemas (since both will use the specified schema), and so prevents the suffixes
+    from being added to the definition references.
+
+    ```python
+    from pydantic import BaseModel, ConfigDict, Json
+
+    class Model(BaseModel):
+        a: Json[int]  # requires a string to validate, but will dump an int
+
+    print(Model.model_json_schema(mode='serialization'))
+    '''
+    {
+        'properties': {'a': {'title': 'A', 'type': 'integer'}},
+        'required': ['a'],
+        'title': 'Model',
+        'type': 'object',
+    }
+    '''
+
+    class ForceInputModel(Model):
+        # the following ensures that even with mode='serialization', we
+        # will get the schema that would be generated for validation.
+        model_config = ConfigDict(json_schema_mode_override='validation')
+
+    print(ForceInputModel.model_json_schema(mode='serialization'))
+    '''
+    {
+        'properties': {
+            'a': {
+                'contentMediaType': 'application/json',
+                'contentSchema': {'type': 'integer'},
+                'title': 'A',
+                'type': 'string',
+            }
+        },
+        'required': ['a'],
+        'title': 'ForceInputModel',
+        'type': 'object',
+    }
+    '''
+    ```
+
+    /// version-added | v2.4
+    ///
+    """
+
+    coerce_numbers_to_str: bool
+    """
+    If `True`, enables automatic coercion of any `Number` type to `str` in "lax" (non-strict) mode. Defaults to `False`.
+
+    Pydantic doesn't allow number types (`int`, `float`, `Decimal`) to be coerced as type `str` by default.
+
+    ```python
+    from decimal import Decimal
+
+    from pydantic import BaseModel, ConfigDict, ValidationError
+
+    class Model(BaseModel):
+        value: str
+
+    try:
+        print(Model(value=42))
+    except ValidationError as e:
+        print(e)
+        '''
+        1 validation error for Model
+        value
+          Input should be a valid string [type=string_type, input_value=42, input_type=int]
+        '''
+
+    class Model(BaseModel):
+        model_config = ConfigDict(coerce_numbers_to_str=True)
+
+        value: str
+
+    repr(Model(value=42).value)
+    #> "42"
+    repr(Model(value=42.13).value)
+    #> "42.13"
+    repr(Model(value=Decimal('42.13')).value)
+    #> "42.13"
+    ```
+    """
+
+    regex_engine: Literal['rust-regex', 'python-re']
+    """
+    The regex engine to be used for pattern validation.
+    Defaults to `'rust-regex'`.
+
+    - `'rust-regex'` uses the [`regex`](https://docs.rs/regex) Rust crate,
+      which is non-backtracking and therefore more DDoS resistant, but does not support all regex features.
+    - `'python-re'` use the [`re`][] module, which supports all regex features, but may be slower.
+
+    !!! note
+        If you use a compiled regex pattern, the `'python-re'` engine will be used regardless of this setting.
+        This is so that flags such as [`re.IGNORECASE`][] are respected.
+
+    ```python
+    from pydantic import BaseModel, ConfigDict, Field, ValidationError
+
+    class Model(BaseModel):
+        model_config = ConfigDict(regex_engine='python-re')
+
+        value: str = Field(pattern=r'^abc(?=def)')
+
+    print(Model(value='abcdef').value)
+    #> abcdef
+
+    try:
+        print(Model(value='abxyzcdef'))
+    except ValidationError as e:
+        print(e)
+        '''
+        1 validation error for Model
+        value
+          String should match pattern '^abc(?=def)' [type=string_pattern_mismatch, input_value='abxyzcdef', input_type=str]
+        '''
+    ```
+
+    /// version-added | v2.5
+    ///
+    """
+
+    validation_error_cause: bool
+    """
+    If `True`, Python exceptions that were part of a validation failure will be shown as an exception group as a cause. Can be useful for debugging. Defaults to `False`.
+
+    Note:
+        Python 3.10 and older don't support exception groups natively. <=3.10, backport must be installed: `pip install exceptiongroup`.
+
+    Note:
+        The structure of validation errors are likely to change in future Pydantic versions. Pydantic offers no guarantees about their structure. Should be used for visual traceback debugging only.
+
+    /// version-added | v2.5
+    ///
+    """
+
+    use_attribute_docstrings: bool
+    '''
+    Whether docstrings of attributes (bare string literals immediately following the attribute declaration)
+    should be used for field descriptions. Defaults to `False`.
+
+    ```python
+    from pydantic import BaseModel, ConfigDict, Field
+
+
+    class Model(BaseModel):
+        model_config = ConfigDict(use_attribute_docstrings=True)
+
+        x: str
+        """
+        Example of an attribute docstring
+        """
+
+        y: int = Field(description="Description in Field")
+        """
+        Description in Field overrides attribute docstring
+        """
+
+
+    print(Model.model_fields["x"].description)
+    # > Example of an attribute docstring
+    print(Model.model_fields["y"].description)
+    # > Description in Field
+    ```
+    This requires the source code of the class to be available at runtime.
+
+    !!! warning "Usage with `TypedDict` and stdlib dataclasses"
+        Due to current limitations, attribute docstrings detection may not work as expected when using
+        [`TypedDict`][typing.TypedDict] and stdlib dataclasses, in particular when:
+
+        - inheritance is being used.
+        - multiple classes have the same name in the same source file (unless Python 3.13 or greater is used).
+
+    /// version-added | v2.7
+    ///
+    '''
+
+    cache_strings: bool | Literal['all', 'keys', 'none']
+    """
+    Whether to cache strings to avoid constructing new Python objects. Defaults to True.
+
+    Enabling this setting should significantly improve validation performance while increasing memory usage slightly.
+
+    - `True` or `'all'` (the default): cache all strings
+    - `'keys'`: cache only dictionary keys
+    - `False` or `'none'`: no caching
+
+    !!! note
+        `True` or `'all'` is required to cache strings during general validation because
+        validators don't know if they're in a key or a value.
+
+    !!! tip
+        If repeated strings are rare, it's recommended to use `'keys'` or `'none'` to reduce memory usage,
+        as the performance difference is minimal if repeated strings are rare.
+
+    /// version-added | v2.7
+    ///
+    """
+
+    validate_by_alias: bool
+    """
+    Whether an aliased field may be populated by its alias. Defaults to `True`.
+
+    Here's an example of disabling validation by alias:
+
+    ```py
+    from pydantic import BaseModel, ConfigDict, Field
+
+    class Model(BaseModel):
+        model_config = ConfigDict(validate_by_name=True, validate_by_alias=False)
+
+        my_field: str = Field(validation_alias='my_alias')  # (1)!
+
+    m = Model(my_field='foo')  # (2)!
+    print(m)
+    #> my_field='foo'
+    ```
+
+    1. The field `'my_field'` has an alias `'my_alias'`.
+    2. The model can only be populated by the attribute name `'my_field'`.
+
+    !!! warning
+        You cannot set both `validate_by_alias` and `validate_by_name` to `False`.
+        This would make it impossible to populate an attribute.
+
+        See [usage errors](../errors/usage_errors.md#validate-by-alias-and-name-false) for an example.
+
+        If you set `validate_by_alias` to `False`, under the hood, Pydantic dynamically sets
+        `validate_by_name` to `True` to ensure that validation can still occur.
+
+    /// version-added | v2.11
+    This setting was introduced in conjunction with [`validate_by_name`][pydantic.ConfigDict.validate_by_name]
+    to empower users with more fine grained validation control.
+    ///
+    """
+
+    validate_by_name: bool
+    """
+    Whether an aliased field may be populated by its name as given by the model
+    attribute. Defaults to `False`.
+
+    ```python
+    from pydantic import BaseModel, ConfigDict, Field
+
+    class Model(BaseModel):
+        model_config = ConfigDict(validate_by_name=True, validate_by_alias=True)
+
+        my_field: str = Field(validation_alias='my_alias')  # (1)!
+
+    m = Model(my_alias='foo')  # (2)!
+    print(m)
+    #> my_field='foo'
+
+    m = Model(my_field='foo')  # (3)!
+    print(m)
+    #> my_field='foo'
+    ```
+
+    1. The field `'my_field'` has an alias `'my_alias'`.
+    2. The model is populated by the alias `'my_alias'`.
+    3. The model is populated by the attribute name `'my_field'`.
+
+    !!! warning
+        You cannot set both `validate_by_alias` and `validate_by_name` to `False`.
+        This would make it impossible to populate an attribute.
+
+        See [usage errors](../errors/usage_errors.md#validate-by-alias-and-name-false) for an example.
+
+    /// version-added | v2.11
+    This setting was introduced in conjunction with [`validate_by_alias`][pydantic.ConfigDict.validate_by_alias]
+    to empower users with more fine grained validation control. It is an alternative to [`populate_by_name`][pydantic.ConfigDict.populate_by_name],
+    that enables validation by name **and** by alias.
+    ///
+    """
+
+    serialize_by_alias: bool
+    """
+    Whether an aliased field should be serialized by its alias. Defaults to `False`.
+
+    Note: In v2.11, `serialize_by_alias` was introduced to address the
+    [popular request](https://github.com/pydantic/pydantic/issues/8379)
+    for consistency with alias behavior for validation and serialization settings.
+    In v3, the default value is expected to change to `True` for consistency with the validation default.
+
+    ```python
+    from pydantic import BaseModel, ConfigDict, Field
+
+    class Model(BaseModel):
+        model_config = ConfigDict(serialize_by_alias=True)
+
+        my_field: str = Field(serialization_alias='my_alias')  # (1)!
+
+    m = Model(my_field='foo')
+    print(m.model_dump())  # (2)!
+    #> {'my_alias': 'foo'}
+    ```
+
+    1. The field `'my_field'` has an alias `'my_alias'`.
+    2. The model is serialized using the alias `'my_alias'` for the `'my_field'` attribute.
+
+
+    /// version-added | v2.11
+    This setting was introduced to address the [popular request](https://github.com/pydantic/pydantic/issues/8379)
+    for consistency with alias behavior for validation and serialization.
+
+    In v3, the default value is expected to change to `True` for consistency with the validation default.
+    ///
+    """
+
+    url_preserve_empty_path: bool
+    """
+    Whether to preserve empty URL paths when validating values for a URL type. Defaults to `False`.
+
+    ```python
+    from pydantic import AnyUrl, BaseModel, ConfigDict
+
+    class Model(BaseModel):
+        model_config = ConfigDict(url_preserve_empty_path=True)
+
+        url: AnyUrl
+
+    m = Model(url='http://example.com')
+    print(m.url)
+    #> http://example.com
+    ```
+
+    /// version-added | v2.12
+    ///
+    """
+
+
+_TypeT = TypeVar('_TypeT', bound=type)
+
+
+@overload
+@deprecated('Passing `config` as a keyword argument is deprecated. Pass `config` as a positional argument instead.')
+def with_config(*, config: ConfigDict) -> Callable[[_TypeT], _TypeT]: ...
+
+
+@overload
+def with_config(config: ConfigDict, /) -> Callable[[_TypeT], _TypeT]: ...
+
+
+@overload
+def with_config(**config: Unpack[ConfigDict]) -> Callable[[_TypeT], _TypeT]: ...
+
+
+def with_config(config: ConfigDict | None = None, /, **kwargs: Any) -> Callable[[_TypeT], _TypeT]:
+    """!!! abstract "Usage Documentation"
+        [Configuration with other types](../concepts/config.md#configuration-on-other-supported-types)
+
+    A convenience decorator to set a [Pydantic configuration](config.md) on a `TypedDict` or a `dataclass` from the standard library.
+
+    Although the configuration can be set using the `__pydantic_config__` attribute, it does not play well with type checkers,
+    especially with `TypedDict`.
+
+    !!! example "Usage"
+
+        ```python
+        from typing_extensions import TypedDict
+
+        from pydantic import ConfigDict, TypeAdapter, with_config
+
+        @with_config(ConfigDict(str_to_lower=True))
+        class TD(TypedDict):
+            x: str
+
+        ta = TypeAdapter(TD)
+
+        print(ta.validate_python({'x': 'ABC'}))
+        #> {'x': 'abc'}
+        ```
+
+    /// deprecated-removed | v2.11 v3
+    Passing `config` as a keyword argument.
+    ///
+
+    /// version-changed | v2.11
+    Keyword arguments can be provided directly instead of a config dictionary.
+    ///
+    """
+    if config is not None and kwargs:
+        raise ValueError('Cannot specify both `config` and keyword arguments')
+
+    if len(kwargs) == 1 and (kwargs_conf := kwargs.get('config')) is not None:
+        warnings.warn(
+            'Passing `config` as a keyword argument is deprecated. Pass `config` as a positional argument instead',
+            category=PydanticDeprecatedSince211,
+            stacklevel=2,
+        )
+        final_config = cast(ConfigDict, kwargs_conf)
+    else:
+        final_config = config if config is not None else cast(ConfigDict, kwargs)
+
+    def inner(class_: _TypeT, /) -> _TypeT:
+        # Ideally, we would check for `class_` to either be a `TypedDict` or a stdlib dataclass.
+        # However, the `@with_config` decorator can be applied *after* `@dataclass`. To avoid
+        # common mistakes, we at least check for `class_` to not be a Pydantic model.
+        from ._internal._utils import is_model_class
+
+        if is_model_class(class_):
+            raise PydanticUserError(
+                f'Cannot use `with_config` on {class_.__name__} as it is a Pydantic model',
+                code='with-config-on-model',
+            )
+        class_.__pydantic_config__ = final_config
+        return class_
+
+    return inner
+
+
+__getattr__ = getattr_migration(__name__)
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pydantic/dataclasses.py b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/dataclasses.py
new file mode 100644
index 0000000000000000000000000000000000000000..cecd5402fd6c52c612074719adcf41b8d3b29b7a
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/dataclasses.py
@@ -0,0 +1,413 @@
+"""Provide an enhanced dataclass that performs validation."""
+
+from __future__ import annotations as _annotations
+
+import dataclasses
+import functools
+import sys
+import types
+from typing import TYPE_CHECKING, Any, Callable, Generic, Literal, NoReturn, TypeVar, overload
+from warnings import warn
+
+from typing_extensions import TypeGuard, dataclass_transform
+
+from ._internal import _config, _decorators, _mock_val_ser, _namespace_utils, _typing_extra
+from ._internal import _dataclasses as _pydantic_dataclasses
+from ._migration import getattr_migration
+from .config import ConfigDict
+from .errors import PydanticUserError
+from .fields import Field, FieldInfo, PrivateAttr
+
+if TYPE_CHECKING:
+    from ._internal._dataclasses import PydanticDataclass
+    from ._internal._namespace_utils import MappingNamespace
+
+__all__ = 'dataclass', 'rebuild_dataclass'
+
+_T = TypeVar('_T')
+
+if sys.version_info >= (3, 10):
+
+    @dataclass_transform(field_specifiers=(dataclasses.field, Field, PrivateAttr))
+    @overload
+    def dataclass(
+        *,
+        init: Literal[False] = False,
+        repr: bool = True,
+        eq: bool = True,
+        order: bool = False,
+        unsafe_hash: bool = False,
+        frozen: bool = False,
+        config: ConfigDict | type[object] | None = None,
+        validate_on_init: bool | None = None,
+        kw_only: bool = ...,
+        slots: bool = ...,
+    ) -> Callable[[type[_T]], type[PydanticDataclass]]:  # type: ignore
+        ...
+
+    @dataclass_transform(field_specifiers=(dataclasses.field, Field, PrivateAttr))
+    @overload
+    def dataclass(
+        _cls: type[_T],  # type: ignore
+        *,
+        init: Literal[False] = False,
+        repr: bool = True,
+        eq: bool = True,
+        order: bool = False,
+        unsafe_hash: bool = False,
+        frozen: bool | None = None,
+        config: ConfigDict | type[object] | None = None,
+        validate_on_init: bool | None = None,
+        kw_only: bool = ...,
+        slots: bool = ...,
+    ) -> type[PydanticDataclass]: ...
+
+else:
+
+    @dataclass_transform(field_specifiers=(dataclasses.field, Field, PrivateAttr))
+    @overload
+    def dataclass(
+        *,
+        init: Literal[False] = False,
+        repr: bool = True,
+        eq: bool = True,
+        order: bool = False,
+        unsafe_hash: bool = False,
+        frozen: bool | None = None,
+        config: ConfigDict | type[object] | None = None,
+        validate_on_init: bool | None = None,
+    ) -> Callable[[type[_T]], type[PydanticDataclass]]:  # type: ignore
+        ...
+
+    @dataclass_transform(field_specifiers=(dataclasses.field, Field, PrivateAttr))
+    @overload
+    def dataclass(
+        _cls: type[_T],  # type: ignore
+        *,
+        init: Literal[False] = False,
+        repr: bool = True,
+        eq: bool = True,
+        order: bool = False,
+        unsafe_hash: bool = False,
+        frozen: bool | None = None,
+        config: ConfigDict | type[object] | None = None,
+        validate_on_init: bool | None = None,
+    ) -> type[PydanticDataclass]: ...
+
+
+@dataclass_transform(field_specifiers=(dataclasses.field, Field, PrivateAttr))
+def dataclass(
+    _cls: type[_T] | None = None,
+    *,
+    init: Literal[False] = False,
+    repr: bool = True,
+    eq: bool = True,
+    order: bool = False,
+    unsafe_hash: bool = False,
+    frozen: bool | None = None,
+    config: ConfigDict | type[object] | None = None,
+    validate_on_init: bool | None = None,
+    kw_only: bool = False,
+    slots: bool = False,
+) -> Callable[[type[_T]], type[PydanticDataclass]] | type[PydanticDataclass]:
+    """!!! abstract "Usage Documentation"
+        [`dataclasses`](../concepts/dataclasses.md)
+
+    A decorator used to create a Pydantic-enhanced dataclass, similar to the standard Python `dataclass`,
+    but with added validation.
+
+    This function should be used similarly to `dataclasses.dataclass`.
+
+    Args:
+        _cls: The target `dataclass`.
+        init: Included for signature compatibility with `dataclasses.dataclass`, and is passed through to
+            `dataclasses.dataclass` when appropriate. If specified, must be set to `False`, as pydantic inserts its
+            own  `__init__` function.
+        repr: A boolean indicating whether to include the field in the `__repr__` output.
+        eq: Determines if a `__eq__` method should be generated for the class.
+        order: Determines if comparison magic methods should be generated, such as `__lt__`, but not `__eq__`.
+        unsafe_hash: Determines if a `__hash__` method should be included in the class, as in `dataclasses.dataclass`.
+        frozen: Determines if the generated class should be a 'frozen' `dataclass`, which does not allow its
+            attributes to be modified after it has been initialized. If not set, the value from the provided `config` argument will be used (and will default to `False` otherwise).
+        config: The Pydantic config to use for the `dataclass`.
+        validate_on_init: A deprecated parameter included for backwards compatibility; in V2, all Pydantic dataclasses
+            are validated on init.
+        kw_only: Determines if `__init__` method parameters must be specified by keyword only. Defaults to `False`.
+        slots: Determines if the generated class should be a 'slots' `dataclass`, which does not allow the addition of
+            new attributes after instantiation.
+
+    Returns:
+        A decorator that accepts a class as its argument and returns a Pydantic `dataclass`.
+
+    Raises:
+        AssertionError: Raised if `init` is not `False` or `validate_on_init` is `False`.
+    """
+    assert init is False, 'pydantic.dataclasses.dataclass only supports init=False'
+    assert validate_on_init is not False, 'validate_on_init=False is no longer supported'
+
+    if sys.version_info >= (3, 10):
+        kwargs = {'kw_only': kw_only, 'slots': slots}
+    else:
+        kwargs = {}
+
+    def create_dataclass(cls: type[Any]) -> type[PydanticDataclass]:
+        """Create a Pydantic dataclass from a regular dataclass.
+
+        Args:
+            cls: The class to create the Pydantic dataclass from.
+
+        Returns:
+            A Pydantic dataclass.
+        """
+        from ._internal._utils import is_model_class
+
+        if is_model_class(cls):
+            raise PydanticUserError(
+                f'Cannot create a Pydantic dataclass from {cls.__name__} as it is already a Pydantic model',
+                code='dataclass-on-model',
+            )
+
+        original_cls = cls
+
+        # we warn on conflicting config specifications, but only if the class doesn't have a dataclass base
+        # because a dataclass base might provide a __pydantic_config__ attribute that we don't want to warn about
+        has_dataclass_base = any(dataclasses.is_dataclass(base) for base in cls.__bases__)
+        if not has_dataclass_base and config is not None and hasattr(cls, '__pydantic_config__'):
+            warn(
+                f'`config` is set via both the `dataclass` decorator and `__pydantic_config__` for dataclass {cls.__name__}. '
+                f'The `config` specification from `dataclass` decorator will take priority.',
+                category=UserWarning,
+                stacklevel=2,
+            )
+
+        # if config is not explicitly provided, try to read it from the type
+        config_dict = config if config is not None else getattr(cls, '__pydantic_config__', None)
+        config_wrapper = _config.ConfigWrapper(config_dict)
+        decorators = _decorators.DecoratorInfos.build(cls)
+        decorators.update_from_config(config_wrapper)
+
+        # Keep track of the original __doc__ so that we can restore it after applying the dataclasses decorator
+        # Otherwise, classes with no __doc__ will have their signature added into the JSON schema description,
+        # since dataclasses.dataclass will set this as the __doc__
+        original_doc = cls.__doc__
+
+        if _pydantic_dataclasses.is_stdlib_dataclass(cls):
+            # Vanilla dataclasses include a default docstring (representing the class signature),
+            # which we don't want to preserve.
+            original_doc = None
+
+            # We don't want to add validation to the existing std lib dataclass, so we will subclass it
+            #   If the class is generic, we need to make sure the subclass also inherits from Generic
+            #   with all the same parameters.
+            bases = (cls,)
+            if issubclass(cls, Generic):
+                generic_base = Generic[cls.__parameters__]  # type: ignore
+                bases = bases + (generic_base,)
+            cls = types.new_class(cls.__name__, bases)
+
+        # Respect frozen setting from dataclass constructor and fallback to config setting if not provided
+        if frozen is not None:
+            frozen_ = frozen
+            if config_wrapper.frozen:
+                # It's not recommended to define both, as the setting from the dataclass decorator will take priority.
+                warn(
+                    f'`frozen` is set via both the `dataclass` decorator and `config` for dataclass {cls.__name__!r}.'
+                    'This is not recommended. The `frozen` specification on `dataclass` will take priority.',
+                    category=UserWarning,
+                    stacklevel=2,
+                )
+        else:
+            frozen_ = config_wrapper.frozen or False
+
+        # Make Pydantic's `Field()` function compatible with stdlib dataclasses. As we'll decorate
+        # `cls` with the stdlib `@dataclass` decorator first, there are two attributes, `kw_only` and
+        # `repr` that need to be understood *during* the stdlib creation. We do so in two steps:
+
+        # 1. On the decorated class, wrap `Field()` assignment with `dataclass.field()`, with the
+        # two attributes set (done in `as_dataclass_field()`)
+        cls_anns = _typing_extra.safe_get_annotations(cls)
+        for field_name in cls_anns:
+            # We should look for assignments in `__dict__` instead, but for now we follow
+            # the same behavior as stdlib dataclasses (see https://github.com/python/cpython/issues/88609)
+            field_value = getattr(cls, field_name, None)
+            if isinstance(field_value, FieldInfo):
+                setattr(cls, field_name, _pydantic_dataclasses.as_dataclass_field(field_value))
+
+        # 2. For bases of `cls` that are stdlib dataclasses, we temporarily patch their fields
+        # (see the docstring of the context manager):
+        with _pydantic_dataclasses.patch_base_fields(cls):
+            cls = dataclasses.dataclass(  # pyright: ignore[reportCallIssue]
+                cls,
+                # the value of init here doesn't affect anything except that it makes it easier to generate a signature
+                init=True,
+                repr=repr,
+                eq=eq,
+                order=order,
+                unsafe_hash=unsafe_hash,
+                frozen=frozen_,
+                **kwargs,
+            )
+
+        if config_wrapper.validate_assignment:
+            original_setattr = cls.__setattr__
+
+            @functools.wraps(cls.__setattr__)
+            def validated_setattr(instance: PydanticDataclass, name: str, value: Any, /) -> None:
+                if frozen_:
+                    return original_setattr(instance, name, value)  # pyright: ignore[reportCallIssue]
+                inst_cls = type(instance)
+                attr = getattr(inst_cls, name, None)
+
+                if isinstance(attr, property):
+                    attr.__set__(instance, value)
+                elif isinstance(attr, functools.cached_property):
+                    instance.__dict__.__setitem__(name, value)
+                else:
+                    inst_cls.__pydantic_validator__.validate_assignment(instance, name, value)
+
+            cls.__setattr__ = validated_setattr.__get__(None, cls)  # type: ignore
+
+            if slots and not hasattr(cls, '__setstate__'):
+                # If slots is set, `pickle` (relied on by `copy.copy()`) will use
+                # `__setattr__()` to reconstruct the dataclass. However, the custom
+                # `__setattr__()` set above relies on `validate_assignment()`, which
+                # in turn expects all the field values to be already present on the
+                # instance, resulting in attribute errors.
+                # As such, we make use of `object.__setattr__()` instead.
+                # Note that we do so only if `__setstate__()` isn't already set (this is the
+                # case if on top of `slots`, `frozen` is used).
+
+                # Taken from `dataclasses._dataclass_get/setstate()`:
+                def _dataclass_getstate(self: Any) -> list[Any]:
+                    return [getattr(self, f.name) for f in dataclasses.fields(self)]
+
+                def _dataclass_setstate(self: Any, state: list[Any]) -> None:
+                    for field, value in zip(dataclasses.fields(self), state):
+                        object.__setattr__(self, field.name, value)
+
+                cls.__getstate__ = _dataclass_getstate  # pyright: ignore[reportAttributeAccessIssue]
+                cls.__setstate__ = _dataclass_setstate  # pyright: ignore[reportAttributeAccessIssue]
+
+        # This is an undocumented attribute to distinguish stdlib/Pydantic dataclasses.
+        # It should be set as early as possible:
+        cls.__is_pydantic_dataclass__ = True
+        cls.__pydantic_decorators__ = decorators  # type: ignore
+        cls.__doc__ = original_doc
+        # Can be non-existent for dynamically created classes:
+        firstlineno = getattr(original_cls, '__firstlineno__', None)
+        cls.__module__ = original_cls.__module__
+        if sys.version_info >= (3, 13) and firstlineno is not None:
+            # As per https://docs.python.org/3/reference/datamodel.html#type.__firstlineno__:
+            # Setting the `__module__` attribute removes the `__firstlineno__` item from the type’s dictionary.
+            original_cls.__firstlineno__ = firstlineno
+            cls.__firstlineno__ = firstlineno
+        cls.__qualname__ = original_cls.__qualname__
+        cls.__pydantic_fields_complete__ = classmethod(_pydantic_fields_complete)
+        cls.__pydantic_complete__ = False  # `complete_dataclass` will set it to `True` if successful.
+        # TODO `parent_namespace` is currently None, but we could do the same thing as Pydantic models:
+        # fetch the parent ns using `parent_frame_namespace` (if the dataclass was defined in a function),
+        # and possibly cache it (see the `__pydantic_parent_namespace__` logic for models).
+        _pydantic_dataclasses.complete_dataclass(cls, config_wrapper, raise_errors=False)
+        return cls
+
+    return create_dataclass if _cls is None else create_dataclass(_cls)
+
+
+def _pydantic_fields_complete(cls: type[PydanticDataclass]) -> bool:
+    """Return whether the fields where successfully collected (i.e. type hints were successfully resolves).
+
+    This is a private property, not meant to be used outside Pydantic.
+    """
+    return all(field_info._complete for field_info in cls.__pydantic_fields__.values())
+
+
+__getattr__ = getattr_migration(__name__)
+
+if sys.version_info < (3, 11):
+    # Monkeypatch dataclasses.InitVar so that typing doesn't error if it occurs as a type when evaluating type hints
+    # Starting in 3.11, typing.get_type_hints will not raise an error if the retrieved type hints are not callable.
+
+    def _call_initvar(*args: Any, **kwargs: Any) -> NoReturn:
+        """This function does nothing but raise an error that is as similar as possible to what you'd get
+        if you were to try calling `InitVar[int]()` without this monkeypatch. The whole purpose is just
+        to ensure typing._type_check does not error if the type hint evaluates to `InitVar[]`.
+        """
+        raise TypeError("'InitVar' object is not callable")
+
+    dataclasses.InitVar.__call__ = _call_initvar
+
+
+def rebuild_dataclass(
+    cls: type[PydanticDataclass],
+    *,
+    force: bool = False,
+    raise_errors: bool = True,
+    _parent_namespace_depth: int = 2,
+    _types_namespace: MappingNamespace | None = None,
+) -> bool | None:
+    """Try to rebuild the pydantic-core schema for the dataclass.
+
+    This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
+    the initial attempt to build the schema, and automatic rebuilding fails.
+
+    This is analogous to `BaseModel.model_rebuild`.
+
+    Args:
+        cls: The class to rebuild the pydantic-core schema for.
+        force: Whether to force the rebuilding of the schema, defaults to `False`.
+        raise_errors: Whether to raise errors, defaults to `True`.
+        _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
+        _types_namespace: The types namespace, defaults to `None`.
+
+    Returns:
+        Returns `None` if the schema is already "complete" and rebuilding was not required.
+        If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
+    """
+    if not force and cls.__pydantic_complete__:
+        return None
+
+    for attr in ('__pydantic_core_schema__', '__pydantic_validator__', '__pydantic_serializer__'):
+        if attr in cls.__dict__ and not isinstance(getattr(cls, attr), _mock_val_ser.MockValSer):
+            # Deleting the validator/serializer is necessary as otherwise they can get reused in
+            # pydantic-core. Same applies for the core schema that can be reused in schema generation.
+            delattr(cls, attr)
+
+    cls.__pydantic_complete__ = False
+
+    if _types_namespace is not None:
+        rebuild_ns = _types_namespace
+    elif _parent_namespace_depth > 0:
+        rebuild_ns = _typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth, force=True) or {}
+    else:
+        rebuild_ns = {}
+
+    ns_resolver = _namespace_utils.NsResolver(
+        parent_namespace=rebuild_ns,
+    )
+
+    return _pydantic_dataclasses.complete_dataclass(
+        cls,
+        _config.ConfigWrapper(cls.__pydantic_config__, check=False),
+        raise_errors=raise_errors,
+        ns_resolver=ns_resolver,
+        # We could provide a different config instead (with `'defer_build'` set to `True`)
+        # of this explicit `_force_build` argument, but because config can come from the
+        # decorator parameter or the `__pydantic_config__` attribute, `complete_dataclass`
+        # will overwrite `__pydantic_config__` with the provided config above:
+        _force_build=True,
+    )
+
+
+def is_pydantic_dataclass(class_: type[Any], /) -> TypeGuard[type[PydanticDataclass]]:
+    """Whether a class is a pydantic dataclass.
+
+    Args:
+        class_: The class.
+
+    Returns:
+        `True` if the class is a pydantic dataclass, `False` otherwise.
+    """
+    try:
+        return '__is_pydantic_dataclass__' in class_.__dict__ and dataclasses.is_dataclass(class_)
+    except AttributeError:
+        return False
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pydantic/datetime_parse.py b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/datetime_parse.py
new file mode 100644
index 0000000000000000000000000000000000000000..53d52649e7620965ed194240a3becaa3ce3e3448
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/datetime_parse.py
@@ -0,0 +1,5 @@
+"""The `datetime_parse` module is a backport module from V1."""
+
+from ._migration import getattr_migration
+
+__getattr__ = getattr_migration(__name__)
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pydantic/decorator.py b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/decorator.py
new file mode 100644
index 0000000000000000000000000000000000000000..0d97560c1b791956726b04fd66740a947647aabe
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/decorator.py
@@ -0,0 +1,5 @@
+"""The `decorator` module is a backport module from V1."""
+
+from ._migration import getattr_migration
+
+__getattr__ = getattr_migration(__name__)
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pydantic/env_settings.py b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/env_settings.py
new file mode 100644
index 0000000000000000000000000000000000000000..cd0b04e6a43c1bb3767dd136a19a9873fa547514
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/env_settings.py
@@ -0,0 +1,5 @@
+"""The `env_settings` module is a backport module from V1."""
+
+from ._migration import getattr_migration
+
+__getattr__ = getattr_migration(__name__)
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pydantic/error_wrappers.py b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/error_wrappers.py
new file mode 100644
index 0000000000000000000000000000000000000000..2985419abf23f5e529af43883f1d365452e4190a
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/error_wrappers.py
@@ -0,0 +1,5 @@
+"""The `error_wrappers` module is a backport module from V1."""
+
+from ._migration import getattr_migration
+
+__getattr__ = getattr_migration(__name__)
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pydantic/errors.py b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/errors.py
new file mode 100644
index 0000000000000000000000000000000000000000..f22706822f3fa542f69810f8e497857d5be36a65
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/errors.py
@@ -0,0 +1,189 @@
+"""Pydantic-specific errors."""
+
+from __future__ import annotations as _annotations
+
+import re
+from typing import Any, ClassVar, Literal
+
+from typing_extensions import Self
+from typing_inspection.introspection import Qualifier
+
+from pydantic._internal import _repr
+
+from ._migration import getattr_migration
+from .version import version_short
+
+__all__ = (
+    'PydanticUserError',
+    'PydanticUndefinedAnnotation',
+    'PydanticImportError',
+    'PydanticSchemaGenerationError',
+    'PydanticInvalidForJsonSchema',
+    'PydanticForbiddenQualifier',
+    'PydanticErrorCodes',
+)
+
+# We use this URL to allow for future flexibility about how we host the docs, while allowing for Pydantic
+# code in the while with "old" URLs to still work.
+# 'u' refers to "user errors" - e.g. errors caused by developers using pydantic, as opposed to validation errors.
+DEV_ERROR_DOCS_URL = f'https://errors.pydantic.dev/{version_short()}/u/'
+PydanticErrorCodes = Literal[
+    'class-not-fully-defined',
+    'custom-json-schema',
+    'decorator-missing-field',
+    'discriminator-no-field',
+    'discriminator-alias-type',
+    'discriminator-needs-literal',
+    'discriminator-alias',
+    'discriminator-validator',
+    'callable-discriminator-no-tag',
+    'typed-dict-version',
+    'model-field-overridden',
+    'model-field-missing-annotation',
+    'config-both',
+    'removed-kwargs',
+    'circular-reference-schema',
+    'invalid-for-json-schema',
+    'json-schema-already-used',
+    'base-model-instantiated',
+    'undefined-annotation',
+    'schema-for-unknown-type',
+    'import-error',
+    'create-model-field-definitions',
+    'validator-no-fields',
+    'validator-invalid-fields',
+    'validator-instance-method',
+    'validator-input-type',
+    'root-validator-pre-skip',
+    'model-serializer-instance-method',
+    'validator-field-config-info',
+    'validator-v1-signature',
+    'validator-signature',
+    'field-serializer-signature',
+    'model-serializer-signature',
+    'multiple-field-serializers',
+    'invalid-annotated-type',
+    'type-adapter-config-unused',
+    'root-model-extra',
+    'unevaluable-type-annotation',
+    'dataclass-init-false-extra-allow',
+    'clashing-init-and-init-var',
+    'model-config-invalid-field-name',
+    'with-config-on-model',
+    'dataclass-on-model',
+    'validate-call-type',
+    'unpack-typed-dict',
+    'overlapping-unpack-typed-dict',
+    'invalid-self-type',
+    'validate-by-alias-and-name-false',
+]
+
+
+class PydanticErrorMixin:
+    """A mixin class for common functionality shared by all Pydantic-specific errors.
+
+    Attributes:
+        message: A message describing the error.
+        code: An optional error code from PydanticErrorCodes enum.
+    """
+
+    def __init__(self, message: str, *, code: PydanticErrorCodes | None) -> None:
+        self.message = message
+        self.code = code
+
+    def __str__(self) -> str:
+        if self.code is None:
+            return self.message
+        else:
+            return f'{self.message}\n\nFor further information visit {DEV_ERROR_DOCS_URL}{self.code}'
+
+
+class PydanticUserError(PydanticErrorMixin, TypeError):
+    """An error raised due to incorrect use of Pydantic."""
+
+
+class PydanticUndefinedAnnotation(PydanticErrorMixin, NameError):
+    """A subclass of `NameError` raised when handling undefined annotations during `CoreSchema` generation.
+
+    Attributes:
+        name: Name of the error.
+        message: Description of the error.
+    """
+
+    def __init__(self, name: str, message: str) -> None:
+        self.name = name
+        super().__init__(message=message, code='undefined-annotation')
+
+    @classmethod
+    def from_name_error(cls, name_error: NameError) -> Self:
+        """Convert a `NameError` to a `PydanticUndefinedAnnotation` error.
+
+        Args:
+            name_error: `NameError` to be converted.
+
+        Returns:
+            Converted `PydanticUndefinedAnnotation` error.
+        """
+        try:
+            name = name_error.name  # type: ignore  # python > 3.10
+        except AttributeError:
+            name = re.search(r".*'(.+?)'", str(name_error)).group(1)  # type: ignore[union-attr]
+        return cls(name=name, message=str(name_error))
+
+
+class PydanticImportError(PydanticErrorMixin, ImportError):
+    """An error raised when an import fails due to module changes between V1 and V2.
+
+    Attributes:
+        message: Description of the error.
+    """
+
+    def __init__(self, message: str) -> None:
+        super().__init__(message, code='import-error')
+
+
+class PydanticSchemaGenerationError(PydanticUserError):
+    """An error raised during failures to generate a `CoreSchema` for some type.
+
+    Attributes:
+        message: Description of the error.
+    """
+
+    def __init__(self, message: str) -> None:
+        super().__init__(message, code='schema-for-unknown-type')
+
+
+class PydanticInvalidForJsonSchema(PydanticUserError):
+    """An error raised during failures to generate a JSON schema for some `CoreSchema`.
+
+    Attributes:
+        message: Description of the error.
+    """
+
+    def __init__(self, message: str) -> None:
+        super().__init__(message, code='invalid-for-json-schema')
+
+
+class PydanticForbiddenQualifier(PydanticUserError):
+    """An error raised if a forbidden type qualifier is found in a type annotation."""
+
+    _qualifier_repr_map: ClassVar[dict[Qualifier, str]] = {
+        'required': 'typing.Required',
+        'not_required': 'typing.NotRequired',
+        'read_only': 'typing.ReadOnly',
+        'class_var': 'typing.ClassVar',
+        'init_var': 'dataclasses.InitVar',
+        'final': 'typing.Final',
+    }
+
+    def __init__(self, qualifier: Qualifier, annotation: Any) -> None:
+        super().__init__(
+            message=(
+                f'The annotation {_repr.display_as_type(annotation)!r} contains the {self._qualifier_repr_map[qualifier]!r} '
+                f'type qualifier, which is invalid in the context it is defined.'
+            ),
+            code=None,
+        )
+
+
+__getattr__ = getattr_migration(__name__)
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pydantic/fields.py b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/fields.py
new file mode 100644
index 0000000000000000000000000000000000000000..b091710a8619ac734f889cbc7a8e453abe84d569
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/fields.py
@@ -0,0 +1,1834 @@
+"""Defining fields on models."""
+
+from __future__ import annotations as _annotations
+
+import dataclasses
+import inspect
+import re
+import sys
+from collections.abc import Callable, Mapping
+from copy import copy
+from dataclasses import Field as DataclassField
+from functools import cached_property
+from typing import TYPE_CHECKING, Annotated, Any, ClassVar, Literal, TypeVar, cast, final, overload
+from warnings import warn
+
+import annotated_types
+import typing_extensions
+from pydantic_core import MISSING, PydanticUndefined
+from typing_extensions import Self, TypeAlias, TypedDict, Unpack, deprecated
+from typing_inspection import typing_objects
+from typing_inspection.introspection import UNKNOWN, AnnotationSource, ForbiddenQualifier, Qualifier, inspect_annotation
+
+from . import types
+from ._internal import _decorators, _fields, _generics, _internal_dataclass, _repr, _typing_extra, _utils
+from ._internal._namespace_utils import GlobalsNamespace, MappingNamespace
+from .aliases import AliasChoices, AliasGenerator, AliasPath
+from .config import JsonDict
+from .errors import PydanticForbiddenQualifier, PydanticUserError
+from .json_schema import PydanticJsonSchemaWarning
+from .warnings import PydanticDeprecatedSince20
+
+if TYPE_CHECKING:
+    from ._internal._config import ConfigWrapper
+    from ._internal._repr import ReprArgs
+
+
+__all__ = 'Field', 'FieldInfo', 'PrivateAttr', 'computed_field'
+
+
+_Unset: Any = PydanticUndefined
+
+if sys.version_info >= (3, 13):
+    import warnings
+
+    Deprecated: TypeAlias = warnings.deprecated | deprecated
+else:
+    Deprecated: TypeAlias = deprecated
+
+
+class _FromFieldInfoInputs(TypedDict, total=False):
+    """This class exists solely to add type checking for the `**kwargs` in `FieldInfo.from_field`."""
+
+    # TODO PEP 747: use TypeForm:
+    annotation: type[Any] | None
+    default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any] | None
+    alias: str | None
+    alias_priority: int | None
+    validation_alias: str | AliasPath | AliasChoices | None
+    serialization_alias: str | None
+    title: str | None
+    field_title_generator: Callable[[str, FieldInfo], str] | None
+    description: str | None
+    examples: list[Any] | None
+    exclude: bool | None
+    exclude_if: Callable[[Any], bool] | None
+    gt: annotated_types.SupportsGt | None
+    ge: annotated_types.SupportsGe | None
+    lt: annotated_types.SupportsLt | None
+    le: annotated_types.SupportsLe | None
+    multiple_of: float | None
+    strict: bool | None
+    min_length: int | None
+    max_length: int | None
+    pattern: str | re.Pattern[str] | None
+    allow_inf_nan: bool | None
+    max_digits: int | None
+    decimal_places: int | None
+    union_mode: Literal['smart', 'left_to_right'] | None
+    discriminator: str | types.Discriminator | None
+    deprecated: Deprecated | str | bool | None
+    json_schema_extra: JsonDict | Callable[[JsonDict], None] | None
+    frozen: bool | None
+    validate_default: bool | None
+    repr: bool
+    init: bool | None
+    init_var: bool | None
+    kw_only: bool | None
+    coerce_numbers_to_str: bool | None
+    fail_fast: bool | None
+
+
+class _FieldInfoInputs(_FromFieldInfoInputs, total=False):
+    """This class exists solely to add type checking for the `**kwargs` in `FieldInfo.__init__`."""
+
+    default: Any
+
+
+class _FieldInfoAsDict(TypedDict, closed=True):
+    # TODO PEP 747: use TypeForm:
+    annotation: Any
+    metadata: list[Any]
+    attributes: dict[str, Any]
+
+
+@final
+class FieldInfo(_repr.Representation):
+    """This class holds information about a field.
+
+    `FieldInfo` is used for any field definition regardless of whether the [`Field()`][pydantic.fields.Field]
+    function is explicitly used.
+
+    !!! warning
+        The `FieldInfo` class is meant to expose information about a field in a Pydantic model or dataclass.
+        `FieldInfo` instances shouldn't be instantiated directly, nor mutated.
+
+        If you need to derive a new model from another one and are willing to alter `FieldInfo` instances,
+        refer to this [dynamic model example](../examples/dynamic_models.md).
+
+    Attributes:
+        annotation: The type annotation of the field.
+        default: The default value of the field.
+        default_factory: A callable to generate the default value. The callable can either take 0 arguments
+            (in which case it is called as is) or a single argument containing the already validated data.
+        alias: The alias name of the field.
+        alias_priority: The priority of the field's alias.
+        validation_alias: The validation alias of the field.
+        serialization_alias: The serialization alias of the field.
+        title: The title of the field.
+        field_title_generator: A callable that takes a field name and returns title for it.
+        description: The description of the field.
+        examples: List of examples of the field.
+        exclude: Whether to exclude the field from the model serialization.
+        exclude_if: A callable that determines whether to exclude a field during serialization based on its value.
+        discriminator: Field name or Discriminator for discriminating the type in a tagged union.
+        deprecated: A deprecation message, an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport,
+            or a boolean. If `True`, a default deprecation message will be emitted when accessing the field.
+        json_schema_extra: A dict or callable to provide extra JSON schema properties.
+        frozen: Whether the field is frozen.
+        validate_default: Whether to validate the default value of the field.
+        repr: Whether to include the field in representation of the model.
+        init: Whether the field should be included in the constructor of the dataclass.
+        init_var: Whether the field should _only_ be included in the constructor of the dataclass, and not stored.
+        kw_only: Whether the field should be a keyword-only argument in the constructor of the dataclass.
+        metadata: The metadata list. Contains all the data that isn't expressed as direct `FieldInfo` attributes, including:
+
+            * Type-specific constraints, such as `gt` or `min_length` (these are converted to metadata classes such as `annotated_types.Gt`).
+            * Any other arbitrary object used within [`Annotated`][typing.Annotated] metadata
+              (e.g. [custom types handlers](../concepts/types.md#as-an-annotation) or any object not recognized by Pydantic).
+    """
+
+    # TODO PEP 747: use TypeForm:
+    annotation: type[Any] | None
+    default: Any
+    default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any] | None
+    alias: str | None
+    alias_priority: int | None
+    validation_alias: str | AliasPath | AliasChoices | None
+    serialization_alias: str | None
+    title: str | None
+    field_title_generator: Callable[[str, FieldInfo], str] | None
+    description: str | None
+    examples: list[Any] | None
+    exclude: bool | None
+    exclude_if: Callable[[Any], bool] | None
+    discriminator: str | types.Discriminator | None
+    deprecated: Deprecated | str | bool | None
+    json_schema_extra: JsonDict | Callable[[JsonDict], None] | None
+    frozen: bool | None
+    validate_default: bool | None
+    repr: bool
+    init: bool | None
+    init_var: bool | None
+    kw_only: bool | None
+    metadata: list[Any]
+
+    __slots__ = (
+        'annotation',
+        'default',
+        'default_factory',
+        'alias',
+        'alias_priority',
+        'validation_alias',
+        'serialization_alias',
+        'title',
+        'field_title_generator',
+        'description',
+        'examples',
+        'exclude',
+        'exclude_if',
+        'discriminator',
+        'deprecated',
+        'json_schema_extra',
+        'frozen',
+        'validate_default',
+        'repr',
+        'init',
+        'init_var',
+        'kw_only',
+        'metadata',
+        '_attributes_set',
+        '_qualifiers',
+        '_complete',
+        '_original_assignment',
+        '_original_annotation',
+        '_final',
+    )
+
+    # used to convert kwargs to metadata/constraints,
+    # None has a special meaning - these items are collected into a `PydanticGeneralMetadata`
+    metadata_lookup: ClassVar[dict[str, Callable[[Any], Any] | None]] = {
+        'strict': types.Strict,
+        'gt': annotated_types.Gt,
+        'ge': annotated_types.Ge,
+        'lt': annotated_types.Lt,
+        'le': annotated_types.Le,
+        'multiple_of': annotated_types.MultipleOf,
+        'min_length': annotated_types.MinLen,
+        'max_length': annotated_types.MaxLen,
+        'pattern': None,
+        'allow_inf_nan': None,
+        'max_digits': None,
+        'decimal_places': None,
+        'union_mode': None,
+        'coerce_numbers_to_str': None,
+        'fail_fast': types.FailFast,
+    }
+
+    def __init__(self, **kwargs: Unpack[_FieldInfoInputs]) -> None:
+        """This class should generally not be initialized directly; instead, use the `pydantic.fields.Field` function
+        or one of the constructor classmethods.
+
+        See the signature of `pydantic.fields.Field` for more details about the expected arguments.
+        """
+        # Tracking the explicitly set attributes is necessary to correctly merge `Field()` functions
+        # (e.g. with `Annotated[int, Field(alias='a'), Field(alias=None)]`, even though `None` is the default value,
+        # we need to track that `alias=None` was explicitly set):
+        self._attributes_set = {k: v for k, v in kwargs.items() if v is not _Unset and k not in self.metadata_lookup}
+        kwargs = {k: _DefaultValues.get(k) if v is _Unset else v for k, v in kwargs.items()}  # type: ignore
+        self.annotation = kwargs.get('annotation')
+
+        # Note: in theory, the second `pop()` arguments are not required below, as defaults are already set from `_DefaultsValues`.
+        default = kwargs.pop('default', PydanticUndefined)
+        if default is Ellipsis:
+            self.default = PydanticUndefined
+            self._attributes_set.pop('default', None)
+        else:
+            self.default = default
+
+        self.default_factory = kwargs.pop('default_factory', None)
+
+        if self.default is not PydanticUndefined and self.default_factory is not None:
+            raise TypeError('cannot specify both default and default_factory')
+
+        self.alias = kwargs.pop('alias', None)
+        self.validation_alias = kwargs.pop('validation_alias', None)
+        self.serialization_alias = kwargs.pop('serialization_alias', None)
+        alias_is_set = any(alias is not None for alias in (self.alias, self.validation_alias, self.serialization_alias))
+        self.alias_priority = kwargs.pop('alias_priority', None) or 2 if alias_is_set else None
+        self.title = kwargs.pop('title', None)
+        self.field_title_generator = kwargs.pop('field_title_generator', None)
+        self.description = kwargs.pop('description', None)
+        self.examples = kwargs.pop('examples', None)
+        self.exclude = kwargs.pop('exclude', None)
+        self.exclude_if = kwargs.pop('exclude_if', None)
+        self.discriminator = kwargs.pop('discriminator', None)
+        # For compatibility with FastAPI<=0.110.0, we preserve the existing value if it is not overridden
+        self.deprecated = kwargs.pop('deprecated', getattr(self, 'deprecated', None))
+        self.repr = kwargs.pop('repr', True)
+        self.json_schema_extra = kwargs.pop('json_schema_extra', None)
+        self.validate_default = kwargs.pop('validate_default', None)
+        self.frozen = kwargs.pop('frozen', None)
+        # currently only used on dataclasses
+        self.init = kwargs.pop('init', None)
+        self.init_var = kwargs.pop('init_var', None)
+        self.kw_only = kwargs.pop('kw_only', None)
+
+        self.metadata = self._collect_metadata(kwargs)  # type: ignore
+
+        # Private attributes:
+        self._qualifiers: set[Qualifier] = set()
+        # Used to rebuild FieldInfo instances:
+        self._complete = True
+        self._original_annotation: Any = PydanticUndefined
+        self._original_assignment: Any = PydanticUndefined
+        # Used to track whether the `FieldInfo` instance represents the data about a field (and is exposed in `model_fields`/`__pydantic_fields__`),
+        # or if it is the result of the `Field()` function being used as metadata in an `Annotated` type/as an assignment
+        # (not an ideal pattern, see https://github.com/pydantic/pydantic/issues/11122):
+        self._final = False
+
+    @staticmethod
+    def from_field(default: Any = PydanticUndefined, **kwargs: Unpack[_FromFieldInfoInputs]) -> FieldInfo:
+        """Create a new `FieldInfo` object with the `Field` function.
+
+        Args:
+            default: The default value for the field. Defaults to Undefined.
+            **kwargs: Additional arguments dictionary.
+
+        Raises:
+            TypeError: If 'annotation' is passed as a keyword argument.
+
+        Returns:
+            A new FieldInfo object with the given parameters.
+
+        Example:
+            This is how you can create a field with default value like this:
+
+            ```python
+            import pydantic
+
+            class MyModel(pydantic.BaseModel):
+                foo: int = pydantic.Field(4)
+            ```
+        """
+        if 'annotation' in kwargs:
+            raise TypeError('"annotation" is not permitted as a Field keyword argument')
+        return FieldInfo(default=default, **kwargs)
+
+    @staticmethod
+    def from_annotation(annotation: type[Any], *, _source: AnnotationSource = AnnotationSource.ANY) -> FieldInfo:
+        """Creates a `FieldInfo` instance from a bare annotation.
+
+        This function is used internally to create a `FieldInfo` from a bare annotation like this:
+
+        ```python
+        import pydantic
+
+        class MyModel(pydantic.BaseModel):
+            foo: int  # <-- like this
+        ```
+
+        We also account for the case where the annotation can be an instance of `Annotated` and where
+        one of the (not first) arguments in `Annotated` is an instance of `FieldInfo`, e.g.:
+
+        ```python
+        from typing import Annotated
+
+        import annotated_types
+
+        import pydantic
+
+        class MyModel(pydantic.BaseModel):
+            foo: Annotated[int, annotated_types.Gt(42)]
+            bar: Annotated[int, pydantic.Field(gt=42)]
+        ```
+
+        Args:
+            annotation: An annotation object.
+
+        Returns:
+            An instance of the field metadata.
+        """
+        try:
+            inspected_ann = inspect_annotation(
+                annotation,
+                annotation_source=_source,
+                unpack_type_aliases='skip',
+            )
+        except ForbiddenQualifier as e:
+            raise PydanticForbiddenQualifier(e.qualifier, annotation)
+
+        # TODO check for classvar and error?
+
+        # No assigned value, this happens when using a bare `Final` qualifier (also for other
+        # qualifiers, but they shouldn't appear here). In this case we infer the type as `Any`
+        # because we don't have any assigned value.
+        type_expr: Any = Any if inspected_ann.type is UNKNOWN else inspected_ann.type
+        final = 'final' in inspected_ann.qualifiers
+        metadata = inspected_ann.metadata
+
+        attr_overrides = {'annotation': type_expr}
+        if final:
+            attr_overrides['frozen'] = True
+        field_info = FieldInfo._construct(metadata, **attr_overrides)
+        field_info._qualifiers = inspected_ann.qualifiers
+        field_info._final = True
+        return field_info
+
+    @staticmethod
+    def from_annotated_attribute(
+        annotation: type[Any], default: Any, *, _source: AnnotationSource = AnnotationSource.ANY
+    ) -> FieldInfo:
+        """Create `FieldInfo` from an annotation with a default value.
+
+        This is used in cases like the following:
+
+        ```python
+        from typing import Annotated
+
+        import annotated_types
+
+        import pydantic
+
+        class MyModel(pydantic.BaseModel):
+            foo: int = 4  # <-- like this
+            bar: Annotated[int, annotated_types.Gt(4)] = 4  # <-- or this
+            spam: Annotated[int, pydantic.Field(gt=4)] = 4  # <-- or this
+        ```
+
+        Args:
+            annotation: The type annotation of the field.
+            default: The default value of the field.
+
+        Returns:
+            A field object with the passed values.
+        """
+        if annotation is not MISSING and annotation is default:
+            raise PydanticUserError(
+                'Error when building FieldInfo from annotated attribute. '
+                "Make sure you don't have any field name clashing with a type annotation.",
+                code='unevaluable-type-annotation',
+            )
+
+        try:
+            inspected_ann = inspect_annotation(
+                annotation,
+                annotation_source=_source,
+                unpack_type_aliases='skip',
+            )
+        except ForbiddenQualifier as e:
+            raise PydanticForbiddenQualifier(e.qualifier, annotation)
+
+        # TODO check for classvar and error?
+
+        # TODO infer from the default, this can be done in v3 once we treat final fields with
+        # a default as proper fields and not class variables:
+        type_expr: Any = Any if inspected_ann.type is UNKNOWN else inspected_ann.type
+        final = 'final' in inspected_ann.qualifiers
+        metadata = inspected_ann.metadata
+
+        # HACK 1: the order in which the metadata is merged is inconsistent; we need to prepend
+        # metadata from the assignment at the beginning of the metadata. Changing this is only
+        # possible in v3 (at least). See https://github.com/pydantic/pydantic/issues/10507
+        prepend_metadata: list[Any] | None = None
+        attr_overrides = {'annotation': type_expr}
+        if final:
+            attr_overrides['frozen'] = True
+
+        # HACK 2: FastAPI is subclassing `FieldInfo` and historically expected the actual
+        # instance's type to be preserved when constructing new models with its subclasses as assignments.
+        # This code is never reached by Pydantic itself, and in an ideal world this shouldn't be necessary.
+        if not metadata and isinstance(default, FieldInfo) and type(default) is not FieldInfo:
+            field_info = default._copy()
+            field_info._attributes_set.update(attr_overrides)
+            for k, v in attr_overrides.items():
+                setattr(field_info, k, v)
+            return field_info
+
+        if isinstance(default, FieldInfo):
+            default_copy = default._copy()  # Copy unnecessary when we remove HACK 1.
+            prepend_metadata = default_copy.metadata
+            default_copy.metadata = []
+            metadata = metadata + [default_copy]
+        elif isinstance(default, dataclasses.Field):
+            from_field = FieldInfo._from_dataclass_field(default)
+            prepend_metadata = from_field.metadata  # Unnecessary when we remove HACK 1.
+            from_field.metadata = []
+            metadata = metadata + [from_field]
+            if 'init_var' in inspected_ann.qualifiers:
+                attr_overrides['init_var'] = True
+            if (init := getattr(default, 'init', None)) is not None:
+                attr_overrides['init'] = init
+            if (kw_only := getattr(default, 'kw_only', None)) is not None:
+                attr_overrides['kw_only'] = kw_only
+        else:
+            # `default` is the actual default value
+            attr_overrides['default'] = default
+
+        field_info = FieldInfo._construct(
+            prepend_metadata + metadata if prepend_metadata is not None else metadata, **attr_overrides
+        )
+        field_info._qualifiers = inspected_ann.qualifiers
+        field_info._final = True
+        return field_info
+
+    @classmethod
+    def _construct(cls, metadata: list[Any], **attr_overrides: Any) -> Self:
+        """Construct the final `FieldInfo` instance, by merging the possibly existing `FieldInfo` instances from the metadata.
+
+        With the following example:
+
+        ```python {test="skip" lint="skip"}
+        class Model(BaseModel):
+            f: Annotated[int, Gt(1), Field(description='desc', lt=2)]
+        ```
+
+        `metadata` refers to the metadata elements of the `Annotated` form. This metadata is iterated over from left to right:
+
+        - If the element is a `Field()` function (which is itself a `FieldInfo` instance), the field attributes (such as
+          `description`) are saved to be set on the final `FieldInfo` instance.
+          On the other hand, some kwargs (such as `lt`) are stored as `metadata` (see `FieldInfo.__init__()`, calling
+          `FieldInfo._collect_metadata()`). In this case, the final metadata list is extended with the one from this instance.
+        - Else, the element is considered as a single metadata object, and is appended to the final metadata list.
+
+        Args:
+            metadata: The list of metadata elements to merge together. If the `FieldInfo` instance to be constructed is for
+                a field with an assigned `Field()`, this `Field()` assignment should be added as the last element of the
+                provided metadata.
+            **attr_overrides: Extra attributes that should be set on the final merged `FieldInfo` instance.
+
+        Returns:
+            The final merged `FieldInfo` instance.
+        """
+        merged_metadata: list[Any] = []
+        merged_kwargs: dict[str, Any] = {}
+
+        for meta in metadata:
+            if isinstance(meta, FieldInfo):
+                merged_metadata.extend(meta.metadata)
+
+                new_js_extra: JsonDict | None = None
+                current_js_extra = meta.json_schema_extra
+                if current_js_extra is not None and 'json_schema_extra' in merged_kwargs:
+                    # We need to merge `json_schema_extra`'s:
+                    existing_js_extra = merged_kwargs['json_schema_extra']
+                    if isinstance(existing_js_extra, dict):
+                        if isinstance(current_js_extra, dict):
+                            new_js_extra = {
+                                **existing_js_extra,
+                                **current_js_extra,
+                            }
+                        elif callable(current_js_extra):
+                            warn(
+                                'Composing `dict` and `callable` type `json_schema_extra` is not supported. '
+                                'The `callable` type is being ignored. '
+                                "If you'd like support for this behavior, please open an issue on pydantic.",
+                                UserWarning,
+                            )
+                    elif callable(existing_js_extra) and isinstance(current_js_extra, dict):
+                        warn(
+                            'Composing `dict` and `callable` type `json_schema_extra` is not supported. '
+                            'The `callable` type is being ignored. '
+                            "If you'd like support for this behavior, please open an issue on pydantic.",
+                            UserWarning,
+                        )
+
+                # HACK: It is common for users to define "make model partial" (or similar) utilities, that
+                # convert all model fields to be optional (i.e. have a default value). To do so, they mutate
+                # each `FieldInfo` instance from `model_fields` to set a `default`, and use `create_model()`
+                # with `Annotated[ | None, mutated_field_info]`` as an annotation. However, such
+                # mutations (by doing simple assignments) are only accidentally working, because we also
+                # need to track attributes explicitly set in `_attributes_set` (relying on default values for
+                # each attribute is *not* enough, for instance with `Annotated[int, Field(alias='a'), Field(alias=None)]`
+                # the resulting `FieldInfo` should have `alias=None`).
+                # To mitigate this, we add a special case when a "final" `FieldInfo` instance (that is an instance coming
+                # from `model_fields`) is used in annotated metadata (or assignment). In this case, we assume *all* attributes
+                # were explicitly set, and as such we use all of them (and this will correctly pick up the mutations).
+                # In theory, this shouldn't really be supported, you are only supposed to use the `Field()` function, not
+                # a `FieldInfo` instance directly (granted, `Field()` returns a `FieldInfo`, see
+                # https://github.com/pydantic/pydantic/issues/11122):
+                if meta._final:
+                    merged_kwargs.update({attr: getattr(meta, attr) for attr in _Attrs})
+                else:
+                    merged_kwargs.update(meta._attributes_set)
+
+                if new_js_extra is not None:
+                    merged_kwargs['json_schema_extra'] = new_js_extra
+            elif typing_objects.is_deprecated(meta):
+                merged_kwargs['deprecated'] = meta
+            else:
+                merged_metadata.append(meta)
+
+        merged_kwargs.update(attr_overrides)
+        merged_field_info = cls(**merged_kwargs)
+        merged_field_info.metadata = merged_metadata
+        return merged_field_info
+
+    @staticmethod
+    @typing_extensions.deprecated(
+        "The 'merge_field_infos()' method is deprecated and will be removed in a future version. "
+        'If you relied on this method, please open an issue in the Pydantic issue tracker.',
+        category=None,
+    )
+    def merge_field_infos(*field_infos: FieldInfo, **overrides: Any) -> FieldInfo:
+        """Merge `FieldInfo` instances keeping only explicitly set attributes.
+
+        Later `FieldInfo` instances override earlier ones.
+
+        Returns:
+            FieldInfo: A merged FieldInfo instance.
+        """
+        if len(field_infos) == 1:
+            # No merging necessary, but we still need to make a copy and apply the overrides
+            field_info = field_infos[0]._copy()
+            field_info._attributes_set.update(overrides)
+
+            default_override = overrides.pop('default', PydanticUndefined)
+            if default_override is Ellipsis:
+                default_override = PydanticUndefined
+            if default_override is not PydanticUndefined:
+                field_info.default = default_override
+
+            for k, v in overrides.items():
+                setattr(field_info, k, v)
+            return field_info  # type: ignore
+
+        merged_field_info_kwargs: dict[str, Any] = {}
+        metadata = {}
+        for field_info in field_infos:
+            attributes_set = field_info._attributes_set.copy()
+
+            try:
+                json_schema_extra = attributes_set.pop('json_schema_extra')
+                existing_json_schema_extra = merged_field_info_kwargs.get('json_schema_extra')
+
+                if existing_json_schema_extra is None:
+                    merged_field_info_kwargs['json_schema_extra'] = json_schema_extra
+                if isinstance(existing_json_schema_extra, dict):
+                    if isinstance(json_schema_extra, dict):
+                        merged_field_info_kwargs['json_schema_extra'] = {
+                            **existing_json_schema_extra,
+                            **json_schema_extra,
+                        }
+                    if callable(json_schema_extra):
+                        warn(
+                            'Composing `dict` and `callable` type `json_schema_extra` is not supported.'
+                            'The `callable` type is being ignored.'
+                            "If you'd like support for this behavior, please open an issue on pydantic.",
+                            PydanticJsonSchemaWarning,
+                        )
+                elif callable(json_schema_extra):
+                    # if ever there's a case of a callable, we'll just keep the last json schema extra spec
+                    merged_field_info_kwargs['json_schema_extra'] = json_schema_extra
+            except KeyError:
+                pass
+
+            # later FieldInfo instances override everything except json_schema_extra from earlier FieldInfo instances
+            merged_field_info_kwargs.update(attributes_set)
+
+            for x in field_info.metadata:
+                if not isinstance(x, FieldInfo):
+                    metadata[type(x)] = x
+
+        merged_field_info_kwargs.update(overrides)
+        field_info = FieldInfo(**merged_field_info_kwargs)
+        field_info.metadata = list(metadata.values())
+        return field_info
+
+    @staticmethod
+    def _from_dataclass_field(dc_field: DataclassField[Any]) -> FieldInfo:
+        """Return a new `FieldInfo` instance from a `dataclasses.Field` instance.
+
+        Args:
+            dc_field: The `dataclasses.Field` instance to convert.
+
+        Returns:
+            The corresponding `FieldInfo` instance.
+
+        Raises:
+            TypeError: If any of the `FieldInfo` kwargs does not match the `dataclass.Field` kwargs.
+        """
+        default = dc_field.default
+        if default is dataclasses.MISSING:
+            default = _Unset
+
+        if dc_field.default_factory is dataclasses.MISSING:
+            default_factory = _Unset
+        else:
+            default_factory = dc_field.default_factory
+
+        # use the `Field` function so in correct kwargs raise the correct `TypeError`
+        dc_field_metadata = {k: v for k, v in dc_field.metadata.items() if k in _FIELD_ARG_NAMES}
+        if sys.version_info >= (3, 14) and dc_field.doc is not None:
+            dc_field_metadata['description'] = dc_field.doc
+        return Field(default=default, default_factory=default_factory, repr=dc_field.repr, **dc_field_metadata)  # pyright: ignore[reportCallIssue]
+
+    @staticmethod
+    def _collect_metadata(kwargs: dict[str, Any]) -> list[Any]:
+        """Collect annotations from kwargs.
+
+        Args:
+            kwargs: Keyword arguments passed to the function.
+
+        Returns:
+            A list of metadata objects - a combination of `annotated_types.BaseMetadata` and
+                `PydanticMetadata`.
+        """
+        metadata: list[Any] = []
+        general_metadata = {}
+        for key, value in list(kwargs.items()):
+            try:
+                marker = FieldInfo.metadata_lookup[key]
+            except KeyError:
+                continue
+
+            del kwargs[key]
+            if value is not None:
+                if marker is None:
+                    general_metadata[key] = value
+                else:
+                    metadata.append(marker(value))
+        if general_metadata:
+            metadata.append(_fields.pydantic_general_metadata(**general_metadata))
+        return metadata
+
+    @property
+    def deprecation_message(self) -> str | None:
+        """The deprecation message to be emitted, or `None` if not set."""
+        if self.deprecated is None:
+            return None
+        if isinstance(self.deprecated, bool):
+            return 'deprecated' if self.deprecated else None
+        return self.deprecated if isinstance(self.deprecated, str) else self.deprecated.message
+
+    @property
+    def default_factory_takes_validated_data(self) -> bool | None:
+        """Whether the provided default factory callable has a validated data parameter.
+
+        Returns `None` if no default factory is set.
+        """
+        if self.default_factory is not None:
+            return _fields.takes_validated_data_argument(self.default_factory)
+
+    @overload
+    def get_default(
+        self, *, call_default_factory: Literal[True], validated_data: dict[str, Any] | None = None
+    ) -> Any: ...
+
+    @overload
+    def get_default(self, *, call_default_factory: Literal[False] = ...) -> Any: ...
+
+    def get_default(self, *, call_default_factory: bool = False, validated_data: dict[str, Any] | None = None) -> Any:
+        """Get the default value.
+
+        We expose an option for whether to call the default_factory (if present), as calling it may
+        result in side effects that we want to avoid. However, there are times when it really should
+        be called (namely, when instantiating a model via `model_construct`).
+
+        Args:
+            call_default_factory: Whether to call the default factory or not.
+            validated_data: The already validated data to be passed to the default factory.
+
+        Returns:
+            The default value, calling the default factory if requested or `None` if not set.
+        """
+        if self.default_factory is None:
+            return _utils.smart_deepcopy(self.default)
+        elif call_default_factory:
+            if self.default_factory_takes_validated_data:
+                fac = cast('Callable[[dict[str, Any]], Any]', self.default_factory)
+                if validated_data is None:
+                    raise ValueError(
+                        "The default factory requires the 'validated_data' argument, which was not provided when calling 'get_default'."
+                    )
+                return fac(validated_data)
+            else:
+                fac = cast('Callable[[], Any]', self.default_factory)
+                return fac()
+        else:
+            return None
+
+    def is_required(self) -> bool:
+        """Check if the field is required (i.e., does not have a default value or factory).
+
+        Returns:
+            `True` if the field is required, `False` otherwise.
+        """
+        return self.default is PydanticUndefined and self.default_factory is None
+
+    def rebuild_annotation(self) -> Any:
+        """Attempts to rebuild the original annotation for use in function signatures.
+
+        If metadata is present, it adds it to the original annotation using
+        `Annotated`. Otherwise, it returns the original annotation as-is.
+
+        Note that because the metadata has been flattened, the original annotation
+        may not be reconstructed exactly as originally provided, e.g. if the original
+        type had unrecognized annotations, or was annotated with a call to `pydantic.Field`.
+
+        Returns:
+            The rebuilt annotation.
+        """
+        if not self.metadata:
+            return self.annotation
+        else:
+            # Annotated arguments must be a tuple
+            return Annotated[(self.annotation, *self.metadata)]  # type: ignore
+
+    def apply_typevars_map(
+        self,
+        typevars_map: Mapping[TypeVar, Any] | None,
+        globalns: GlobalsNamespace | None = None,
+        localns: MappingNamespace | None = None,
+    ) -> None:
+        """Apply a `typevars_map` to the annotation.
+
+        This method is used when analyzing parametrized generic types to replace typevars with their concrete types.
+
+        This method applies the `typevars_map` to the annotation in place.
+
+        Args:
+            typevars_map: A dictionary mapping type variables to their concrete types.
+            globalns: The globals namespace to use during type annotation evaluation.
+            localns: The locals namespace to use during type annotation evaluation.
+
+        See Also:
+            pydantic._internal._generics.replace_types is used for replacing the typevars with
+                their concrete types.
+        """
+        annotation = _generics.replace_types(self.annotation, typevars_map)
+        annotation, evaluated = _typing_extra.try_eval_type(annotation, globalns, localns)
+        self.annotation = annotation
+        if not evaluated:
+            self._complete = False
+            self._original_annotation = self.annotation
+
+    def asdict(self) -> _FieldInfoAsDict:
+        """Return a dictionary representation of the `FieldInfo` instance.
+
+        The returned value is a dictionary with three items:
+
+        * `annotation`: The type annotation of the field.
+        * `metadata`: The metadata list.
+        * `attributes`: A mapping of the remaining `FieldInfo` attributes to their values (e.g. `alias`, `title`).
+        """
+        return {
+            'annotation': self.annotation,
+            'metadata': self.metadata,
+            'attributes': {attr: getattr(self, attr) for attr in _Attrs},
+        }
+
+    def _copy(self) -> Self:
+        """Return a copy of the `FieldInfo` instance."""
+        # Note: we can't define a custom `__copy__()`, as `FieldInfo` is being subclassed
+        # by some third-party libraries with extra attributes defined (and as `FieldInfo`
+        # is slotted, we can't make a copy of the `__dict__`).
+        copied = copy(self)
+        for attr_name in ('metadata', '_attributes_set', '_qualifiers'):
+            # Apply "deep-copy" behavior on collections attributes:
+            value = getattr(copied, attr_name).copy()
+            setattr(copied, attr_name, value)
+
+        return copied
+
+    def __repr_args__(self) -> ReprArgs:
+        yield 'annotation', _repr.PlainRepr(_repr.display_as_type(self.annotation))
+        yield 'required', self.is_required()
+
+        for s in self.__slots__:
+            # TODO: properly make use of the protocol (https://rich.readthedocs.io/en/stable/pretty.html#rich-repr-protocol)
+            # By yielding a three-tuple:
+            if s in (
+                'annotation',
+                '_attributes_set',
+                '_qualifiers',
+                '_complete',
+                '_original_assignment',
+                '_original_annotation',
+                '_final',
+            ):
+                continue
+            elif s == 'metadata' and not self.metadata:
+                continue
+            elif s == 'repr' and self.repr is True:
+                continue
+            if s == 'frozen' and self.frozen is False:
+                continue
+            if s == 'validation_alias' and self.validation_alias == self.alias:
+                continue
+            if s == 'serialization_alias' and self.serialization_alias == self.alias:
+                continue
+            if s == 'default' and self.default is not PydanticUndefined:
+                yield 'default', self.default
+            elif s == 'default_factory' and self.default_factory is not None:
+                yield 'default_factory', _repr.PlainRepr(_repr.display_as_type(self.default_factory))
+            else:
+                value = getattr(self, s)
+                if value is not None and value is not PydanticUndefined:
+                    yield s, value
+
+
+class _EmptyKwargs(TypedDict):
+    """This class exists solely to ensure that type checking warns about passing `**extra` in `Field`."""
+
+
+_Attrs = {
+    'default': ...,
+    'default_factory': None,
+    'alias': None,
+    'alias_priority': None,
+    'validation_alias': None,
+    'serialization_alias': None,
+    'title': None,
+    'field_title_generator': None,
+    'description': None,
+    'examples': None,
+    'exclude': None,
+    'exclude_if': None,
+    'discriminator': None,
+    'deprecated': None,
+    'json_schema_extra': None,
+    'frozen': None,
+    'validate_default': None,
+    'repr': True,
+    'init': None,
+    'init_var': None,
+    'kw_only': None,
+}
+
+_DefaultValues = {
+    **_Attrs,
+    'kw_only': None,
+    'pattern': None,
+    'strict': None,
+    'gt': None,
+    'ge': None,
+    'lt': None,
+    'le': None,
+    'multiple_of': None,
+    'allow_inf_nan': None,
+    'max_digits': None,
+    'decimal_places': None,
+    'min_length': None,
+    'max_length': None,
+    'coerce_numbers_to_str': None,
+}
+
+
+_T = TypeVar('_T')
+
+
+# NOTE: Actual return type is 'FieldInfo', but we want to help type checkers
+# to understand the magic that happens at runtime with the following overloads:
+@overload  # type hint the return value as `Any` to avoid type checking regressions when using `...`.
+def Field(
+    default: ellipsis,  # noqa: F821  # TODO: use `_typing_extra.EllipsisType` when we drop Py3.9
+    *,
+    alias: str | None = _Unset,
+    alias_priority: int | None = _Unset,
+    validation_alias: str | AliasPath | AliasChoices | None = _Unset,
+    serialization_alias: str | None = _Unset,
+    title: str | None = _Unset,
+    field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset,
+    description: str | None = _Unset,
+    examples: list[Any] | None = _Unset,
+    exclude: bool | None = _Unset,
+    exclude_if: Callable[[Any], bool] | None = _Unset,
+    discriminator: str | types.Discriminator | None = _Unset,
+    deprecated: Deprecated | str | bool | None = _Unset,
+    json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset,
+    frozen: bool | None = _Unset,
+    validate_default: bool | None = _Unset,
+    repr: bool = _Unset,
+    init: bool | None = _Unset,
+    init_var: bool | None = _Unset,
+    kw_only: bool | None = _Unset,
+    pattern: str | re.Pattern[str] | None = _Unset,
+    strict: bool | None = _Unset,
+    coerce_numbers_to_str: bool | None = _Unset,
+    gt: annotated_types.SupportsGt | None = _Unset,
+    ge: annotated_types.SupportsGe | None = _Unset,
+    lt: annotated_types.SupportsLt | None = _Unset,
+    le: annotated_types.SupportsLe | None = _Unset,
+    multiple_of: float | None = _Unset,
+    allow_inf_nan: bool | None = _Unset,
+    max_digits: int | None = _Unset,
+    decimal_places: int | None = _Unset,
+    min_length: int | None = _Unset,
+    max_length: int | None = _Unset,
+    union_mode: Literal['smart', 'left_to_right'] = _Unset,
+    fail_fast: bool | None = _Unset,
+    **extra: Unpack[_EmptyKwargs],
+) -> Any: ...
+@overload  # `default` argument set, validate_default=True (no type checking on the default value)
+def Field(
+    default: Any,
+    *,
+    alias: str | None = _Unset,
+    alias_priority: int | None = _Unset,
+    validation_alias: str | AliasPath | AliasChoices | None = _Unset,
+    serialization_alias: str | None = _Unset,
+    title: str | None = _Unset,
+    field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset,
+    description: str | None = _Unset,
+    examples: list[Any] | None = _Unset,
+    exclude: bool | None = _Unset,
+    exclude_if: Callable[[Any], bool] | None = _Unset,
+    discriminator: str | types.Discriminator | None = _Unset,
+    deprecated: Deprecated | str | bool | None = _Unset,
+    json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset,
+    frozen: bool | None = _Unset,
+    validate_default: Literal[True],
+    repr: bool = _Unset,
+    init: bool | None = _Unset,
+    init_var: bool | None = _Unset,
+    kw_only: bool | None = _Unset,
+    pattern: str | re.Pattern[str] | None = _Unset,
+    strict: bool | None = _Unset,
+    coerce_numbers_to_str: bool | None = _Unset,
+    gt: annotated_types.SupportsGt | None = _Unset,
+    ge: annotated_types.SupportsGe | None = _Unset,
+    lt: annotated_types.SupportsLt | None = _Unset,
+    le: annotated_types.SupportsLe | None = _Unset,
+    multiple_of: float | None = _Unset,
+    allow_inf_nan: bool | None = _Unset,
+    max_digits: int | None = _Unset,
+    decimal_places: int | None = _Unset,
+    min_length: int | None = _Unset,
+    max_length: int | None = _Unset,
+    union_mode: Literal['smart', 'left_to_right'] = _Unset,
+    fail_fast: bool | None = _Unset,
+    **extra: Unpack[_EmptyKwargs],
+) -> Any: ...
+@overload  # `default` argument set, validate_default=False or unset
+def Field(
+    default: _T,
+    *,
+    alias: str | None = _Unset,
+    alias_priority: int | None = _Unset,
+    validation_alias: str | AliasPath | AliasChoices | None = _Unset,
+    serialization_alias: str | None = _Unset,
+    title: str | None = _Unset,
+    field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset,
+    description: str | None = _Unset,
+    examples: list[Any] | None = _Unset,
+    exclude: bool | None = _Unset,
+    # NOTE: to get proper type checking on `exclude_if`'s argument, we could use `_T` instead of `Any`. However,
+    # this requires (at least for pyright) adding an additional overload where `exclude_if` is required (otherwise
+    # `a: int = Field(default_factory=str)` results in a false negative).
+    exclude_if: Callable[[Any], bool] | None = _Unset,
+    discriminator: str | types.Discriminator | None = _Unset,
+    deprecated: Deprecated | str | bool | None = _Unset,
+    json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset,
+    frozen: bool | None = _Unset,
+    validate_default: Literal[False] = ...,
+    repr: bool = _Unset,
+    init: bool | None = _Unset,
+    init_var: bool | None = _Unset,
+    kw_only: bool | None = _Unset,
+    pattern: str | re.Pattern[str] | None = _Unset,
+    strict: bool | None = _Unset,
+    coerce_numbers_to_str: bool | None = _Unset,
+    gt: annotated_types.SupportsGt | None = _Unset,
+    ge: annotated_types.SupportsGe | None = _Unset,
+    lt: annotated_types.SupportsLt | None = _Unset,
+    le: annotated_types.SupportsLe | None = _Unset,
+    multiple_of: float | None = _Unset,
+    allow_inf_nan: bool | None = _Unset,
+    max_digits: int | None = _Unset,
+    decimal_places: int | None = _Unset,
+    min_length: int | None = _Unset,
+    max_length: int | None = _Unset,
+    union_mode: Literal['smart', 'left_to_right'] = _Unset,
+    fail_fast: bool | None = _Unset,
+    **extra: Unpack[_EmptyKwargs],
+) -> _T: ...
+@overload  # `default_factory` argument set, validate_default=True  (no type checking on the default value)
+def Field(  # pyright: ignore[reportOverlappingOverload]
+    *,
+    default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any],
+    alias: str | None = _Unset,
+    alias_priority: int | None = _Unset,
+    validation_alias: str | AliasPath | AliasChoices | None = _Unset,
+    serialization_alias: str | None = _Unset,
+    title: str | None = _Unset,
+    field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset,
+    description: str | None = _Unset,
+    examples: list[Any] | None = _Unset,
+    exclude: bool | None = _Unset,
+    exclude_if: Callable[[Any], bool] | None = _Unset,
+    discriminator: str | types.Discriminator | None = _Unset,
+    deprecated: Deprecated | str | bool | None = _Unset,
+    json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset,
+    frozen: bool | None = _Unset,
+    validate_default: Literal[True],
+    repr: bool = _Unset,
+    init: bool | None = _Unset,
+    init_var: bool | None = _Unset,
+    kw_only: bool | None = _Unset,
+    pattern: str | re.Pattern[str] | None = _Unset,
+    strict: bool | None = _Unset,
+    coerce_numbers_to_str: bool | None = _Unset,
+    gt: annotated_types.SupportsGt | None = _Unset,
+    ge: annotated_types.SupportsGe | None = _Unset,
+    lt: annotated_types.SupportsLt | None = _Unset,
+    le: annotated_types.SupportsLe | None = _Unset,
+    multiple_of: float | None = _Unset,
+    allow_inf_nan: bool | None = _Unset,
+    max_digits: int | None = _Unset,
+    decimal_places: int | None = _Unset,
+    min_length: int | None = _Unset,
+    max_length: int | None = _Unset,
+    union_mode: Literal['smart', 'left_to_right'] = _Unset,
+    fail_fast: bool | None = _Unset,
+    **extra: Unpack[_EmptyKwargs],
+) -> Any: ...
+@overload  # `default_factory` argument set, validate_default=False or unset
+def Field(
+    *,
+    default_factory: Callable[[], _T] | Callable[[dict[str, Any]], _T],
+    alias: str | None = _Unset,
+    alias_priority: int | None = _Unset,
+    validation_alias: str | AliasPath | AliasChoices | None = _Unset,
+    serialization_alias: str | None = _Unset,
+    title: str | None = _Unset,
+    field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset,
+    description: str | None = _Unset,
+    examples: list[Any] | None = _Unset,
+    exclude: bool | None = _Unset,
+    # NOTE: to get proper type checking on `exclude_if`'s argument, we could use `_T` instead of `Any`. However,
+    # this requires (at least for pyright) adding an additional overload where `exclude_if` is required (otherwise
+    # `a: int = Field(default_factory=str)` results in a false negative).
+    exclude_if: Callable[[Any], bool] | None = _Unset,
+    discriminator: str | types.Discriminator | None = _Unset,
+    deprecated: Deprecated | str | bool | None = _Unset,
+    json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset,
+    frozen: bool | None = _Unset,
+    validate_default: Literal[False] | None = _Unset,
+    repr: bool = _Unset,
+    init: bool | None = _Unset,
+    init_var: bool | None = _Unset,
+    kw_only: bool | None = _Unset,
+    pattern: str | re.Pattern[str] | None = _Unset,
+    strict: bool | None = _Unset,
+    coerce_numbers_to_str: bool | None = _Unset,
+    gt: annotated_types.SupportsGt | None = _Unset,
+    ge: annotated_types.SupportsGe | None = _Unset,
+    lt: annotated_types.SupportsLt | None = _Unset,
+    le: annotated_types.SupportsLe | None = _Unset,
+    multiple_of: float | None = _Unset,
+    allow_inf_nan: bool | None = _Unset,
+    max_digits: int | None = _Unset,
+    decimal_places: int | None = _Unset,
+    min_length: int | None = _Unset,
+    max_length: int | None = _Unset,
+    union_mode: Literal['smart', 'left_to_right'] = _Unset,
+    fail_fast: bool | None = _Unset,
+    **extra: Unpack[_EmptyKwargs],
+) -> _T: ...
+@overload
+def Field(  # No default set
+    *,
+    alias: str | None = _Unset,
+    alias_priority: int | None = _Unset,
+    validation_alias: str | AliasPath | AliasChoices | None = _Unset,
+    serialization_alias: str | None = _Unset,
+    title: str | None = _Unset,
+    field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset,
+    description: str | None = _Unset,
+    examples: list[Any] | None = _Unset,
+    exclude: bool | None = _Unset,
+    exclude_if: Callable[[Any], bool] | None = _Unset,
+    discriminator: str | types.Discriminator | None = _Unset,
+    deprecated: Deprecated | str | bool | None = _Unset,
+    json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset,
+    frozen: bool | None = _Unset,
+    validate_default: bool | None = _Unset,
+    repr: bool = _Unset,
+    init: bool | None = _Unset,
+    init_var: bool | None = _Unset,
+    kw_only: bool | None = _Unset,
+    pattern: str | re.Pattern[str] | None = _Unset,
+    strict: bool | None = _Unset,
+    coerce_numbers_to_str: bool | None = _Unset,
+    gt: annotated_types.SupportsGt | None = _Unset,
+    ge: annotated_types.SupportsGe | None = _Unset,
+    lt: annotated_types.SupportsLt | None = _Unset,
+    le: annotated_types.SupportsLe | None = _Unset,
+    multiple_of: float | None = _Unset,
+    allow_inf_nan: bool | None = _Unset,
+    max_digits: int | None = _Unset,
+    decimal_places: int | None = _Unset,
+    min_length: int | None = _Unset,
+    max_length: int | None = _Unset,
+    union_mode: Literal['smart', 'left_to_right'] = _Unset,
+    fail_fast: bool | None = _Unset,
+    **extra: Unpack[_EmptyKwargs],
+) -> Any: ...
+def Field(  # noqa: C901
+    default: Any = PydanticUndefined,
+    *,
+    default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any] | None = _Unset,
+    alias: str | None = _Unset,
+    alias_priority: int | None = _Unset,
+    validation_alias: str | AliasPath | AliasChoices | None = _Unset,
+    serialization_alias: str | None = _Unset,
+    title: str | None = _Unset,
+    field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset,
+    description: str | None = _Unset,
+    examples: list[Any] | None = _Unset,
+    exclude: bool | None = _Unset,
+    exclude_if: Callable[[Any], bool] | None = _Unset,
+    discriminator: str | types.Discriminator | None = _Unset,
+    deprecated: Deprecated | str | bool | None = _Unset,
+    json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset,
+    frozen: bool | None = _Unset,
+    validate_default: bool | None = _Unset,
+    repr: bool = _Unset,
+    init: bool | None = _Unset,
+    init_var: bool | None = _Unset,
+    kw_only: bool | None = _Unset,
+    pattern: str | re.Pattern[str] | None = _Unset,
+    strict: bool | None = _Unset,
+    coerce_numbers_to_str: bool | None = _Unset,
+    gt: annotated_types.SupportsGt | None = _Unset,
+    ge: annotated_types.SupportsGe | None = _Unset,
+    lt: annotated_types.SupportsLt | None = _Unset,
+    le: annotated_types.SupportsLe | None = _Unset,
+    multiple_of: float | None = _Unset,
+    allow_inf_nan: bool | None = _Unset,
+    max_digits: int | None = _Unset,
+    decimal_places: int | None = _Unset,
+    min_length: int | None = _Unset,
+    max_length: int | None = _Unset,
+    union_mode: Literal['smart', 'left_to_right'] = _Unset,
+    fail_fast: bool | None = _Unset,
+    **extra: Unpack[_EmptyKwargs],
+) -> Any:
+    """!!! abstract "Usage Documentation"
+        [Fields](../concepts/fields.md)
+
+    Create a field for objects that can be configured.
+
+    Used to provide extra information about a field, either for the model schema or complex validation. Some arguments
+    apply only to number fields (`int`, `float`, `Decimal`) and some apply only to `str`.
+
+    Note:
+        - Any `_Unset` objects will be replaced by the corresponding value defined in the `_DefaultValues` dictionary. If a key for the `_Unset` object is not found in the `_DefaultValues` dictionary, it will default to `None`
+
+    Args:
+        default: Default value if the field is not set.
+        default_factory: A callable to generate the default value. The callable can either take 0 arguments
+            (in which case it is called as is) or a single argument containing the already validated data.
+        alias: The name to use for the attribute when validating or serializing by alias.
+            This is often used for things like converting between snake and camel case.
+        alias_priority: Priority of the alias. This affects whether an alias generator is used.
+        validation_alias: Like `alias`, but only affects validation, not serialization.
+        serialization_alias: Like `alias`, but only affects serialization, not validation.
+        title: Human-readable title.
+        field_title_generator: A callable that takes a field name and returns title for it.
+        description: Human-readable description.
+        examples: Example values for this field.
+        exclude: Whether to exclude the field from the model serialization.
+        exclude_if: A callable that determines whether to exclude a field during serialization based on its value.
+        discriminator: Field name or Discriminator for discriminating the type in a tagged union.
+        deprecated: A deprecation message, an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport,
+            or a boolean. If `True`, a default deprecation message will be emitted when accessing the field.
+        json_schema_extra: A dict or callable to provide extra JSON schema properties.
+        frozen: Whether the field is frozen. If true, attempts to change the value on an instance will raise an error.
+        validate_default: If `True`, apply validation to the default value every time you create an instance.
+            Otherwise, for performance reasons, the default value of the field is trusted and not validated.
+        repr: A boolean indicating whether to include the field in the `__repr__` output.
+        init: Whether the field should be included in the constructor of the dataclass.
+            (Only applies to dataclasses.)
+        init_var: Whether the field should _only_ be included in the constructor of the dataclass.
+            (Only applies to dataclasses.)
+        kw_only: Whether the field should be a keyword-only argument in the constructor of the dataclass.
+            (Only applies to dataclasses.)
+        coerce_numbers_to_str: Whether to enable coercion of any `Number` type to `str` (not applicable in `strict` mode).
+        strict: If `True`, strict validation is applied to the field.
+            See [Strict Mode](../concepts/strict_mode.md) for details.
+        gt: Greater than. If set, value must be greater than this. Only applicable to numbers.
+        ge: Greater than or equal. If set, value must be greater than or equal to this. Only applicable to numbers.
+        lt: Less than. If set, value must be less than this. Only applicable to numbers.
+        le: Less than or equal. If set, value must be less than or equal to this. Only applicable to numbers.
+        multiple_of: Value must be a multiple of this. Only applicable to numbers.
+        min_length: Minimum length for iterables.
+        max_length: Maximum length for iterables.
+        pattern: Pattern for strings (a regular expression).
+        allow_inf_nan: Allow `inf`, `-inf`, `nan`. Only applicable to float and [`Decimal`][decimal.Decimal] numbers.
+        max_digits: Maximum number of allow digits for strings.
+        decimal_places: Maximum number of decimal places allowed for numbers.
+        union_mode: The strategy to apply when validating a union. Can be `smart` (the default), or `left_to_right`.
+            See [Union Mode](../concepts/unions.md#union-modes) for details.
+        fail_fast: If `True`, validation will stop on the first error. If `False`, all validation errors will be collected.
+            This option can be applied only to iterable types (list, tuple, set, and frozenset).
+        extra: (Deprecated) Extra fields that will be included in the JSON schema.
+
+            !!! warning Deprecated
+                The `extra` kwargs is deprecated. Use `json_schema_extra` instead.
+
+    Returns:
+        A new [`FieldInfo`][pydantic.fields.FieldInfo]. The return annotation is `Any` so `Field` can be used on
+            type-annotated fields without causing a type error.
+    """
+    # Check deprecated and removed params from V1. This logic should eventually be removed.
+    const = extra.pop('const', None)  # type: ignore
+    if const is not None:
+        raise PydanticUserError('`const` is removed, use `Literal` instead', code='removed-kwargs')
+
+    min_items = extra.pop('min_items', None)  # type: ignore
+    if min_items is not None:
+        warn(
+            '`min_items` is deprecated and will be removed, use `min_length` instead',
+            PydanticDeprecatedSince20,
+            stacklevel=2,
+        )
+        if min_length in (None, _Unset):
+            min_length = min_items  # type: ignore
+
+    max_items = extra.pop('max_items', None)  # type: ignore
+    if max_items is not None:
+        warn(
+            '`max_items` is deprecated and will be removed, use `max_length` instead',
+            PydanticDeprecatedSince20,
+            stacklevel=2,
+        )
+        if max_length in (None, _Unset):
+            max_length = max_items  # type: ignore
+
+    unique_items = extra.pop('unique_items', None)  # type: ignore
+    if unique_items is not None:
+        raise PydanticUserError(
+            (
+                '`unique_items` is removed, use `Set` instead'
+                '(this feature is discussed in https://github.com/pydantic/pydantic-core/issues/296)'
+            ),
+            code='removed-kwargs',
+        )
+
+    allow_mutation = extra.pop('allow_mutation', None)  # type: ignore
+    if allow_mutation is not None:
+        warn(
+            '`allow_mutation` is deprecated and will be removed. use `frozen` instead',
+            PydanticDeprecatedSince20,
+            stacklevel=2,
+        )
+        if allow_mutation is False:
+            frozen = True
+
+    regex = extra.pop('regex', None)  # type: ignore
+    if regex is not None:
+        raise PydanticUserError('`regex` is removed. use `pattern` instead', code='removed-kwargs')
+
+    if extra:
+        warn(
+            'Using extra keyword arguments on `Field` is deprecated and will be removed.'
+            ' Use `json_schema_extra` instead.'
+            f' (Extra keys: {", ".join(k.__repr__() for k in extra.keys())})',
+            PydanticDeprecatedSince20,
+            stacklevel=2,
+        )
+        if not json_schema_extra or json_schema_extra is _Unset:
+            json_schema_extra = extra  # type: ignore
+
+    if (
+        validation_alias
+        and validation_alias is not _Unset
+        and not isinstance(validation_alias, (str, AliasChoices, AliasPath))
+    ):
+        raise TypeError('Invalid `validation_alias` type. it should be `str`, `AliasChoices`, or `AliasPath`')
+
+    if serialization_alias in (_Unset, None) and isinstance(alias, str):
+        serialization_alias = alias
+
+    if validation_alias in (_Unset, None):
+        validation_alias = alias
+
+    include = extra.pop('include', None)  # type: ignore
+    if include is not None:
+        warn(
+            '`include` is deprecated and does nothing. It will be removed, use `exclude` instead',
+            PydanticDeprecatedSince20,
+            stacklevel=2,
+        )
+
+    return FieldInfo.from_field(
+        default,
+        default_factory=default_factory,
+        alias=alias,
+        alias_priority=alias_priority,
+        validation_alias=validation_alias,
+        serialization_alias=serialization_alias,
+        title=title,
+        field_title_generator=field_title_generator,
+        description=description,
+        examples=examples,
+        exclude=exclude,
+        exclude_if=exclude_if,
+        discriminator=discriminator,
+        deprecated=deprecated,
+        json_schema_extra=json_schema_extra,
+        frozen=frozen,
+        pattern=pattern,
+        validate_default=validate_default,
+        repr=repr,
+        init=init,
+        init_var=init_var,
+        kw_only=kw_only,
+        coerce_numbers_to_str=coerce_numbers_to_str,
+        strict=strict,
+        gt=gt,
+        ge=ge,
+        lt=lt,
+        le=le,
+        multiple_of=multiple_of,
+        min_length=min_length,
+        max_length=max_length,
+        allow_inf_nan=allow_inf_nan,
+        max_digits=max_digits,
+        decimal_places=decimal_places,
+        union_mode=union_mode,
+        fail_fast=fail_fast,
+    )
+
+
+_FIELD_ARG_NAMES = set(inspect.signature(Field).parameters)
+_FIELD_ARG_NAMES.remove('extra')  # do not include the varkwargs parameter
+
+
+class ModelPrivateAttr(_repr.Representation):
+    """A descriptor for private attributes in class models.
+
+    !!! warning
+        You generally shouldn't be creating `ModelPrivateAttr` instances directly, instead use
+        `pydantic.fields.PrivateAttr`. (This is similar to `FieldInfo` vs. `Field`.)
+
+    Attributes:
+        default: The default value of the attribute if not provided.
+        default_factory: A callable function that generates the default value of the
+            attribute if not provided.
+    """
+
+    __slots__ = ('default', 'default_factory')
+
+    def __init__(self, default: Any = PydanticUndefined, *, default_factory: Callable[[], Any] | None = None) -> None:
+        if default is Ellipsis:
+            self.default = PydanticUndefined
+        else:
+            self.default = default
+        self.default_factory = default_factory
+
+    if not TYPE_CHECKING:
+        # We put `__getattr__` in a non-TYPE_CHECKING block because otherwise, mypy allows arbitrary attribute access
+
+        def __getattr__(self, item: str) -> Any:
+            """This function improves compatibility with custom descriptors by ensuring delegation happens
+            as expected when the default value of a private attribute is a descriptor.
+            """
+            if item in {'__get__', '__set__', '__delete__'}:
+                if hasattr(self.default, item):
+                    return getattr(self.default, item)
+            raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}')
+
+    def __set_name__(self, cls: type[Any], name: str) -> None:
+        """Preserve `__set_name__` protocol defined in https://peps.python.org/pep-0487."""
+        default = self.default
+        if default is PydanticUndefined:
+            return
+        set_name = getattr(default, '__set_name__', None)
+        if callable(set_name):
+            set_name(cls, name)
+
+    def get_default(self) -> Any:
+        """Retrieve the default value of the object.
+
+        If `self.default_factory` is `None`, the method will return a deep copy of the `self.default` object.
+
+        If `self.default_factory` is not `None`, it will call `self.default_factory` and return the value returned.
+
+        Returns:
+            The default value of the object.
+        """
+        return _utils.smart_deepcopy(self.default) if self.default_factory is None else self.default_factory()
+
+    def __eq__(self, other: Any) -> bool:
+        return isinstance(other, self.__class__) and (self.default, self.default_factory) == (
+            other.default,
+            other.default_factory,
+        )
+
+
+# NOTE: Actual return type is 'ModelPrivateAttr', but we want to help type checkers
+# to understand the magic that happens at runtime.
+@overload  # `default` argument set
+def PrivateAttr(
+    default: _T,
+    *,
+    init: Literal[False] = False,
+) -> _T: ...
+@overload  # `default_factory` argument set
+def PrivateAttr(
+    *,
+    default_factory: Callable[[], _T],
+    init: Literal[False] = False,
+) -> _T: ...
+@overload  # No default set
+def PrivateAttr(
+    *,
+    init: Literal[False] = False,
+) -> Any: ...
+def PrivateAttr(
+    default: Any = PydanticUndefined,
+    *,
+    default_factory: Callable[[], Any] | None = None,
+    init: Literal[False] = False,
+) -> Any:
+    """!!! abstract "Usage Documentation"
+        [Private Model Attributes](../concepts/models.md#private-model-attributes)
+
+    Indicates that an attribute is intended for private use and not handled during normal validation/serialization.
+
+    Private attributes are not validated by Pydantic, so it's up to you to ensure they are used in a type-safe manner.
+
+    Private attributes are stored in `__private_attributes__` on the model.
+
+    Args:
+        default: The attribute's default value. Defaults to Undefined.
+        default_factory: Callable that will be
+            called when a default value is needed for this attribute.
+            If both `default` and `default_factory` are set, an error will be raised.
+        init: Whether the attribute should be included in the constructor of the dataclass. Always `False`.
+
+    Returns:
+        An instance of [`ModelPrivateAttr`][pydantic.fields.ModelPrivateAttr] class.
+
+    Raises:
+        ValueError: If both `default` and `default_factory` are set.
+    """
+    if default is not PydanticUndefined and default_factory is not None:
+        raise TypeError('cannot specify both default and default_factory')
+
+    return ModelPrivateAttr(
+        default,
+        default_factory=default_factory,
+    )
+
+
+@dataclasses.dataclass(**_internal_dataclass.slots_true)
+class ComputedFieldInfo:
+    """A container for data from `@computed_field` so that we can access it while building the pydantic-core schema.
+
+    Attributes:
+        decorator_repr: A class variable representing the decorator string, '@computed_field'.
+        wrapped_property: The wrapped computed field property.
+        return_type: The type of the computed field property's return value.
+        alias: The alias of the property to be used during serialization.
+        alias_priority: The priority of the alias. This affects whether an alias generator is used.
+        title: Title of the computed field to include in the serialization JSON schema.
+        field_title_generator: A callable that takes a field name and returns title for it.
+        description: Description of the computed field to include in the serialization JSON schema.
+        deprecated: A deprecation message, an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport,
+            or a boolean. If `True`, a default deprecation message will be emitted when accessing the field.
+        examples: Example values of the computed field to include in the serialization JSON schema.
+        json_schema_extra: A dict or callable to provide extra JSON schema properties.
+        repr: A boolean indicating whether to include the field in the __repr__ output.
+    """
+
+    decorator_repr: ClassVar[str] = '@computed_field'
+    wrapped_property: property
+    return_type: Any
+    alias: str | None
+    alias_priority: int | None
+    title: str | None
+    field_title_generator: Callable[[str, ComputedFieldInfo], str] | None
+    description: str | None
+    deprecated: Deprecated | str | bool | None
+    examples: list[Any] | None
+    json_schema_extra: JsonDict | Callable[[JsonDict], None] | None
+    repr: bool
+
+    @property
+    def deprecation_message(self) -> str | None:
+        """The deprecation message to be emitted, or `None` if not set."""
+        if self.deprecated is None:
+            return None
+        if isinstance(self.deprecated, bool):
+            return 'deprecated' if self.deprecated else None
+        return self.deprecated if isinstance(self.deprecated, str) else self.deprecated.message
+
+    def _update_from_config(self, config_wrapper: ConfigWrapper, name: str) -> None:
+        """Update the instance from the configuration set on the class this computed field belongs to."""
+        title_generator = self.field_title_generator or config_wrapper.field_title_generator
+        if title_generator is not None and self.title is None:
+            self.title = title_generator(name, self)
+        if config_wrapper.alias_generator is not None:
+            self._apply_alias_generator(config_wrapper.alias_generator, name)
+
+    def _apply_alias_generator(self, alias_generator: Callable[[str], str] | AliasGenerator, name: str) -> None:
+        """Apply an alias generator to aliases if appropriate.
+
+        Args:
+            alias_generator: A callable that takes a string and returns a string, or an `AliasGenerator` instance.
+            name: The name of the computed field from which to generate the alias.
+        """
+        # Apply an alias_generator if
+        # 1. An alias is not specified
+        # 2. An alias is specified, but the priority is <= 1
+
+        if self.alias_priority is None or self.alias_priority <= 1 or self.alias is None:
+            alias, _, serialization_alias = None, None, None
+
+            if isinstance(alias_generator, AliasGenerator):
+                alias, _, serialization_alias = alias_generator.generate_aliases(name)
+            elif callable(alias_generator):
+                alias = alias_generator(name)
+
+            # if priority is not set, we set to 1
+            # which supports the case where the alias_generator from a child class is used
+            # to generate an alias for a field in a parent class
+            if self.alias_priority is None or self.alias_priority <= 1:
+                self.alias_priority = 1
+
+            # if the priority is 1, then we set the aliases to the generated alias
+            # note that we use the serialization_alias with priority over alias, as computed_field
+            # aliases are used for serialization only (not validation)
+            if self.alias_priority == 1:
+                self.alias = _utils.get_first_not_none(serialization_alias, alias)
+
+
+def _wrapped_property_is_private(property_: cached_property | property) -> bool:  # type: ignore
+    """Returns true if provided property is private, False otherwise."""
+    wrapped_name: str = ''
+
+    if isinstance(property_, property):
+        wrapped_name = getattr(property_.fget, '__name__', '')
+    elif isinstance(property_, cached_property):  # type: ignore
+        wrapped_name = getattr(property_.func, '__name__', '')  # type: ignore
+
+    return wrapped_name.startswith('_') and not wrapped_name.startswith('__')
+
+
+# this should really be `property[T], cached_property[T]` but property is not generic unlike cached_property
+# See https://github.com/python/typing/issues/985 and linked issues
+PropertyT = TypeVar('PropertyT')
+
+
+@overload
+def computed_field(func: PropertyT, /) -> PropertyT: ...
+
+
+@overload
+def computed_field(
+    *,
+    alias: str | None = None,
+    alias_priority: int | None = None,
+    title: str | None = None,
+    field_title_generator: Callable[[str, ComputedFieldInfo], str] | None = None,
+    description: str | None = None,
+    deprecated: Deprecated | str | bool | None = None,
+    examples: list[Any] | None = None,
+    json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = None,
+    repr: bool = True,
+    return_type: Any = PydanticUndefined,
+) -> Callable[[PropertyT], PropertyT]: ...
+
+
+def computed_field(
+    func: PropertyT | None = None,
+    /,
+    *,
+    alias: str | None = None,
+    alias_priority: int | None = None,
+    title: str | None = None,
+    field_title_generator: Callable[[str, ComputedFieldInfo], str] | None = None,
+    description: str | None = None,
+    deprecated: Deprecated | str | bool | None = None,
+    examples: list[Any] | None = None,
+    json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = None,
+    repr: bool | None = None,
+    return_type: Any = PydanticUndefined,
+) -> PropertyT | Callable[[PropertyT], PropertyT]:
+    """!!! abstract "Usage Documentation"
+        [The `computed_field` decorator](../concepts/fields.md#the-computed_field-decorator)
+
+    Decorator to include `property` and `cached_property` when serializing models or dataclasses.
+
+    This is useful for fields that are computed from other fields, or for fields that are expensive to compute and should be cached.
+
+    ```python
+    from pydantic import BaseModel, computed_field
+
+    class Rectangle(BaseModel):
+        width: int
+        length: int
+
+        @computed_field
+        @property
+        def area(self) -> int:
+            return self.width * self.length
+
+    print(Rectangle(width=3, length=2).model_dump())
+    #> {'width': 3, 'length': 2, 'area': 6}
+    ```
+
+    If applied to functions not yet decorated with `@property` or `@cached_property`, the function is
+    automatically wrapped with `property`. Although this is more concise, you will lose IntelliSense in your IDE,
+    and confuse static type checkers, thus explicit use of `@property` is recommended.
+
+    !!! warning "Mypy Warning"
+        Even with the `@property` or `@cached_property` applied to your function before `@computed_field`,
+        mypy may throw a `Decorated property not supported` error.
+        See [mypy issue #1362](https://github.com/python/mypy/issues/1362), for more information.
+        To avoid this error message, add `# type: ignore[prop-decorator]` to the `@computed_field` line.
+
+        [pyright](https://github.com/microsoft/pyright) supports `@computed_field` without error.
+
+    ```python
+    import random
+
+    from pydantic import BaseModel, computed_field
+
+    class Square(BaseModel):
+        width: float
+
+        @computed_field
+        def area(self) -> float:  # converted to a `property` by `computed_field`
+            return round(self.width**2, 2)
+
+        @area.setter
+        def area(self, new_area: float) -> None:
+            self.width = new_area**0.5
+
+        @computed_field(alias='the magic number', repr=False)
+        def random_number(self) -> int:
+            return random.randint(0, 1_000)
+
+    square = Square(width=1.3)
+
+    # `random_number` does not appear in representation
+    print(repr(square))
+    #> Square(width=1.3, area=1.69)
+
+    print(square.random_number)
+    #> 3
+
+    square.area = 4
+
+    print(square.model_dump_json(by_alias=True))
+    #> {"width":2.0,"area":4.0,"the magic number":3}
+    ```
+
+    !!! warning "Overriding with `computed_field`"
+        You can't override a field from a parent class with a `computed_field` in the child class.
+        `mypy` complains about this behavior if allowed, and `dataclasses` doesn't allow this pattern either.
+        See the example below:
+
+    ```python
+    from pydantic import BaseModel, computed_field
+
+    class Parent(BaseModel):
+        a: str
+
+    try:
+
+        class Child(Parent):
+            @computed_field
+            @property
+            def a(self) -> str:
+                return 'new a'
+
+    except TypeError as e:
+        print(e)
+        '''
+        Field 'a' of class 'Child' overrides symbol of same name in a parent class. This override with a computed_field is incompatible.
+        '''
+    ```
+
+    Private properties decorated with `@computed_field` have `repr=False` by default.
+
+    ```python
+    from functools import cached_property
+
+    from pydantic import BaseModel, computed_field
+
+    class Model(BaseModel):
+        foo: int
+
+        @computed_field
+        @cached_property
+        def _private_cached_property(self) -> int:
+            return -self.foo
+
+        @computed_field
+        @property
+        def _private_property(self) -> int:
+            return -self.foo
+
+    m = Model(foo=1)
+    print(repr(m))
+    #> Model(foo=1)
+    ```
+
+    Args:
+        func: the function to wrap.
+        alias: alias to use when serializing this computed field, only used when `by_alias=True`
+        alias_priority: priority of the alias. This affects whether an alias generator is used
+        title: Title to use when including this computed field in JSON Schema
+        field_title_generator: A callable that takes a field name and returns title for it.
+        description: Description to use when including this computed field in JSON Schema, defaults to the function's
+            docstring
+        deprecated: A deprecation message (or an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport).
+            to be emitted when accessing the field. Or a boolean. This will automatically be set if the property is decorated with the
+            `deprecated` decorator.
+        examples: Example values to use when including this computed field in JSON Schema
+        json_schema_extra: A dict or callable to provide extra JSON schema properties.
+        repr: whether to include this computed field in model repr.
+            Default is `False` for private properties and `True` for public properties.
+        return_type: optional return for serialization logic to expect when serializing to JSON, if included
+            this must be correct, otherwise a `TypeError` is raised.
+            If you don't include a return type Any is used, which does runtime introspection to handle arbitrary
+            objects.
+
+    Returns:
+        A proxy wrapper for the property.
+    """
+
+    def dec(f: Any) -> Any:
+        nonlocal description, deprecated, return_type, alias_priority
+        unwrapped = _decorators.unwrap_wrapped_function(f)
+
+        if description is None and unwrapped.__doc__:
+            description = inspect.cleandoc(unwrapped.__doc__)
+
+        if deprecated is None and hasattr(unwrapped, '__deprecated__'):
+            deprecated = unwrapped.__deprecated__
+
+        # if the function isn't already decorated with `@property` (or another descriptor), then we wrap it now
+        f = _decorators.ensure_property(f)
+        alias_priority = (alias_priority or 2) if alias is not None else None
+
+        if repr is None:
+            repr_: bool = not _wrapped_property_is_private(property_=f)
+        else:
+            repr_ = repr
+
+        dec_info = ComputedFieldInfo(
+            f,
+            return_type,
+            alias,
+            alias_priority,
+            title,
+            field_title_generator,
+            description,
+            deprecated,
+            examples,
+            json_schema_extra,
+            repr_,
+        )
+        return _decorators.PydanticDescriptorProxy(f, dec_info)
+
+    if func is None:
+        return dec
+    else:
+        return dec(func)
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pydantic/functional_serializers.py b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/functional_serializers.py
new file mode 100644
index 0000000000000000000000000000000000000000..0c1522f1bba25bc66aaa3c02a6785203ada8552f
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/functional_serializers.py
@@ -0,0 +1,451 @@
+"""This module contains related classes and functions for serialization."""
+
+from __future__ import annotations
+
+import dataclasses
+from functools import partial, partialmethod
+from typing import TYPE_CHECKING, Annotated, Any, Callable, Literal, TypeVar, overload
+
+from pydantic_core import PydanticUndefined, core_schema
+from pydantic_core.core_schema import SerializationInfo, SerializerFunctionWrapHandler, WhenUsed
+from typing_extensions import TypeAlias
+
+from . import PydanticUndefinedAnnotation
+from ._internal import _decorators, _internal_dataclass
+from .annotated_handlers import GetCoreSchemaHandler
+
+
+@dataclasses.dataclass(**_internal_dataclass.slots_true, frozen=True)
+class PlainSerializer:
+    """Plain serializers use a function to modify the output of serialization.
+
+    This is particularly helpful when you want to customize the serialization for annotated types.
+    Consider an input of `list`, which will be serialized into a space-delimited string.
+
+    ```python
+    from typing import Annotated
+
+    from pydantic import BaseModel, PlainSerializer
+
+    CustomStr = Annotated[
+        list, PlainSerializer(lambda x: ' '.join(x), return_type=str)
+    ]
+
+    class StudentModel(BaseModel):
+        courses: CustomStr
+
+    student = StudentModel(courses=['Math', 'Chemistry', 'English'])
+    print(student.model_dump())
+    #> {'courses': 'Math Chemistry English'}
+    ```
+
+    Attributes:
+        func: The serializer function.
+        return_type: The return type for the function. If omitted it will be inferred from the type annotation.
+        when_used: Determines when this serializer should be used. Accepts a string with values `'always'`,
+            `'unless-none'`, `'json'`, and `'json-unless-none'`. Defaults to 'always'.
+    """
+
+    func: core_schema.SerializerFunction
+    return_type: Any = PydanticUndefined
+    when_used: WhenUsed = 'always'
+
+    def __get_pydantic_core_schema__(self, source_type: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
+        """Gets the Pydantic core schema.
+
+        Args:
+            source_type: The source type.
+            handler: The `GetCoreSchemaHandler` instance.
+
+        Returns:
+            The Pydantic core schema.
+        """
+        schema = handler(source_type)
+        if self.return_type is not PydanticUndefined:
+            return_type = self.return_type
+        else:
+            try:
+                # Do not pass in globals as the function could be defined in a different module.
+                # Instead, let `get_callable_return_type` infer the globals to use, but still pass
+                # in locals that may contain a parent/rebuild namespace:
+                return_type = _decorators.get_callable_return_type(
+                    self.func,
+                    localns=handler._get_types_namespace().locals,
+                )
+            except NameError as e:
+                raise PydanticUndefinedAnnotation.from_name_error(e) from e
+
+        return_schema = None if return_type is PydanticUndefined else handler.generate_schema(return_type)
+        schema['serialization'] = core_schema.plain_serializer_function_ser_schema(
+            function=self.func,
+            info_arg=_decorators.inspect_annotated_serializer(self.func, 'plain'),
+            return_schema=return_schema,
+            when_used=self.when_used,
+        )
+        return schema
+
+
+@dataclasses.dataclass(**_internal_dataclass.slots_true, frozen=True)
+class WrapSerializer:
+    """Wrap serializers receive the raw inputs along with a handler function that applies the standard serialization
+    logic, and can modify the resulting value before returning it as the final output of serialization.
+
+    For example, here's a scenario in which a wrap serializer transforms timezones to UTC **and** utilizes the existing `datetime` serialization logic.
+
+    ```python
+    from datetime import datetime, timezone
+    from typing import Annotated, Any
+
+    from pydantic import BaseModel, WrapSerializer
+
+    class EventDatetime(BaseModel):
+        start: datetime
+        end: datetime
+
+    def convert_to_utc(value: Any, handler, info) -> dict[str, datetime]:
+        # Note that `handler` can actually help serialize the `value` for
+        # further custom serialization in case it's a subclass.
+        partial_result = handler(value, info)
+        if info.mode == 'json':
+            return {
+                k: datetime.fromisoformat(v).astimezone(timezone.utc)
+                for k, v in partial_result.items()
+            }
+        return {k: v.astimezone(timezone.utc) for k, v in partial_result.items()}
+
+    UTCEventDatetime = Annotated[EventDatetime, WrapSerializer(convert_to_utc)]
+
+    class EventModel(BaseModel):
+        event_datetime: UTCEventDatetime
+
+    dt = EventDatetime(
+        start='2024-01-01T07:00:00-08:00', end='2024-01-03T20:00:00+06:00'
+    )
+    event = EventModel(event_datetime=dt)
+    print(event.model_dump())
+    '''
+    {
+        'event_datetime': {
+            'start': datetime.datetime(
+                2024, 1, 1, 15, 0, tzinfo=datetime.timezone.utc
+            ),
+            'end': datetime.datetime(
+                2024, 1, 3, 14, 0, tzinfo=datetime.timezone.utc
+            ),
+        }
+    }
+    '''
+
+    print(event.model_dump_json())
+    '''
+    {"event_datetime":{"start":"2024-01-01T15:00:00Z","end":"2024-01-03T14:00:00Z"}}
+    '''
+    ```
+
+    Attributes:
+        func: The serializer function to be wrapped.
+        return_type: The return type for the function. If omitted it will be inferred from the type annotation.
+        when_used: Determines when this serializer should be used. Accepts a string with values `'always'`,
+            `'unless-none'`, `'json'`, and `'json-unless-none'`. Defaults to 'always'.
+    """
+
+    func: core_schema.WrapSerializerFunction
+    return_type: Any = PydanticUndefined
+    when_used: WhenUsed = 'always'
+
+    def __get_pydantic_core_schema__(self, source_type: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
+        """This method is used to get the Pydantic core schema of the class.
+
+        Args:
+            source_type: Source type.
+            handler: Core schema handler.
+
+        Returns:
+            The generated core schema of the class.
+        """
+        schema = handler(source_type)
+        if self.return_type is not PydanticUndefined:
+            return_type = self.return_type
+        else:
+            try:
+                # Do not pass in globals as the function could be defined in a different module.
+                # Instead, let `get_callable_return_type` infer the globals to use, but still pass
+                # in locals that may contain a parent/rebuild namespace:
+                return_type = _decorators.get_callable_return_type(
+                    self.func,
+                    localns=handler._get_types_namespace().locals,
+                )
+            except NameError as e:
+                raise PydanticUndefinedAnnotation.from_name_error(e) from e
+
+        return_schema = None if return_type is PydanticUndefined else handler.generate_schema(return_type)
+        schema['serialization'] = core_schema.wrap_serializer_function_ser_schema(
+            function=self.func,
+            info_arg=_decorators.inspect_annotated_serializer(self.func, 'wrap'),
+            return_schema=return_schema,
+            when_used=self.when_used,
+        )
+        return schema
+
+
+if TYPE_CHECKING:
+    _Partial: TypeAlias = 'partial[Any] | partialmethod[Any]'
+
+    FieldPlainSerializer: TypeAlias = 'core_schema.SerializerFunction | _Partial'
+    """A field serializer method or function in `plain` mode."""
+
+    FieldWrapSerializer: TypeAlias = 'core_schema.WrapSerializerFunction | _Partial'
+    """A field serializer method or function in `wrap` mode."""
+
+    FieldSerializer: TypeAlias = 'FieldPlainSerializer | FieldWrapSerializer'
+    """A field serializer method or function."""
+
+    _FieldPlainSerializerT = TypeVar('_FieldPlainSerializerT', bound=FieldPlainSerializer)
+    _FieldWrapSerializerT = TypeVar('_FieldWrapSerializerT', bound=FieldWrapSerializer)
+
+
+@overload
+def field_serializer(
+    field: str,
+    /,
+    *fields: str,
+    mode: Literal['wrap'],
+    return_type: Any = ...,
+    when_used: WhenUsed = ...,
+    check_fields: bool | None = ...,
+) -> Callable[[_FieldWrapSerializerT], _FieldWrapSerializerT]: ...
+
+
+@overload
+def field_serializer(
+    field: str,
+    /,
+    *fields: str,
+    mode: Literal['plain'] = ...,
+    return_type: Any = ...,
+    when_used: WhenUsed = ...,
+    check_fields: bool | None = ...,
+) -> Callable[[_FieldPlainSerializerT], _FieldPlainSerializerT]: ...
+
+
+def field_serializer(
+    *fields: str,
+    mode: Literal['plain', 'wrap'] = 'plain',
+    # TODO PEP 747 (grep for 'return_type' on the whole code base):
+    return_type: Any = PydanticUndefined,
+    when_used: WhenUsed = 'always',
+    check_fields: bool | None = None,
+) -> (
+    Callable[[_FieldWrapSerializerT], _FieldWrapSerializerT]
+    | Callable[[_FieldPlainSerializerT], _FieldPlainSerializerT]
+):
+    """Decorator that enables custom field serialization.
+
+    In the below example, a field of type `set` is used to mitigate duplication. A `field_serializer` is used to serialize the data as a sorted list.
+
+    ```python
+    from pydantic import BaseModel, field_serializer
+
+    class StudentModel(BaseModel):
+        name: str = 'Jane'
+        courses: set[str]
+
+        @field_serializer('courses', when_used='json')
+        def serialize_courses_in_order(self, courses: set[str]):
+            return sorted(courses)
+
+    student = StudentModel(courses={'Math', 'Chemistry', 'English'})
+    print(student.model_dump_json())
+    #> {"name":"Jane","courses":["Chemistry","English","Math"]}
+    ```
+
+    See [the usage documentation](../concepts/serialization.md#serializers) for more information.
+
+    Four signatures are supported:
+
+    - `(self, value: Any, info: FieldSerializationInfo)`
+    - `(self, value: Any, nxt: SerializerFunctionWrapHandler, info: FieldSerializationInfo)`
+    - `(value: Any, info: SerializationInfo)`
+    - `(value: Any, nxt: SerializerFunctionWrapHandler, info: SerializationInfo)`
+
+    Args:
+        fields: Which field(s) the method should be called on.
+        mode: The serialization mode.
+
+            - `plain` means the function will be called instead of the default serialization logic,
+            - `wrap` means the function will be called with an argument to optionally call the
+               default serialization logic.
+        return_type: Optional return type for the function, if omitted it will be inferred from the type annotation.
+        when_used: Determines the serializer will be used for serialization.
+        check_fields: Whether to check that the fields actually exist on the model.
+
+    Returns:
+        The decorator function.
+    """
+
+    def dec(f: FieldSerializer) -> _decorators.PydanticDescriptorProxy[Any]:
+        dec_info = _decorators.FieldSerializerDecoratorInfo(
+            fields=fields,
+            mode=mode,
+            return_type=return_type,
+            when_used=when_used,
+            check_fields=check_fields,
+        )
+        return _decorators.PydanticDescriptorProxy(f, dec_info)  # pyright: ignore[reportArgumentType]
+
+    return dec  # pyright: ignore[reportReturnType]
+
+
+if TYPE_CHECKING:
+    # The first argument in the following callables represent the `self` type:
+
+    ModelPlainSerializerWithInfo: TypeAlias = Callable[[Any, SerializationInfo[Any]], Any]
+    """A model serializer method with the `info` argument, in `plain` mode."""
+
+    ModelPlainSerializerWithoutInfo: TypeAlias = Callable[[Any], Any]
+    """A model serializer method without the `info` argument, in `plain` mode."""
+
+    ModelPlainSerializer: TypeAlias = 'ModelPlainSerializerWithInfo | ModelPlainSerializerWithoutInfo'
+    """A model serializer method in `plain` mode."""
+
+    ModelWrapSerializerWithInfo: TypeAlias = Callable[[Any, SerializerFunctionWrapHandler, SerializationInfo[Any]], Any]
+    """A model serializer method with the `info` argument, in `wrap` mode."""
+
+    ModelWrapSerializerWithoutInfo: TypeAlias = Callable[[Any, SerializerFunctionWrapHandler], Any]
+    """A model serializer method without the `info` argument, in `wrap` mode."""
+
+    ModelWrapSerializer: TypeAlias = 'ModelWrapSerializerWithInfo | ModelWrapSerializerWithoutInfo'
+    """A model serializer method in `wrap` mode."""
+
+    ModelSerializer: TypeAlias = 'ModelPlainSerializer | ModelWrapSerializer'
+
+    _ModelPlainSerializerT = TypeVar('_ModelPlainSerializerT', bound=ModelPlainSerializer)
+    _ModelWrapSerializerT = TypeVar('_ModelWrapSerializerT', bound=ModelWrapSerializer)
+
+
+@overload
+def model_serializer(f: _ModelPlainSerializerT, /) -> _ModelPlainSerializerT: ...
+
+
+@overload
+def model_serializer(
+    *, mode: Literal['wrap'], when_used: WhenUsed = 'always', return_type: Any = ...
+) -> Callable[[_ModelWrapSerializerT], _ModelWrapSerializerT]: ...
+
+
+@overload
+def model_serializer(
+    *,
+    mode: Literal['plain'] = ...,
+    when_used: WhenUsed = 'always',
+    return_type: Any = ...,
+) -> Callable[[_ModelPlainSerializerT], _ModelPlainSerializerT]: ...
+
+
+def model_serializer(
+    f: _ModelPlainSerializerT | _ModelWrapSerializerT | None = None,
+    /,
+    *,
+    mode: Literal['plain', 'wrap'] = 'plain',
+    when_used: WhenUsed = 'always',
+    return_type: Any = PydanticUndefined,
+) -> (
+    _ModelPlainSerializerT
+    | Callable[[_ModelWrapSerializerT], _ModelWrapSerializerT]
+    | Callable[[_ModelPlainSerializerT], _ModelPlainSerializerT]
+):
+    """Decorator that enables custom model serialization.
+
+    This is useful when a model need to be serialized in a customized manner, allowing for flexibility beyond just specific fields.
+
+    An example would be to serialize temperature to the same temperature scale, such as degrees Celsius.
+
+    ```python
+    from typing import Literal
+
+    from pydantic import BaseModel, model_serializer
+
+    class TemperatureModel(BaseModel):
+        unit: Literal['C', 'F']
+        value: int
+
+        @model_serializer()
+        def serialize_model(self):
+            if self.unit == 'F':
+                return {'unit': 'C', 'value': int((self.value - 32) / 1.8)}
+            return {'unit': self.unit, 'value': self.value}
+
+    temperature = TemperatureModel(unit='F', value=212)
+    print(temperature.model_dump())
+    #> {'unit': 'C', 'value': 100}
+    ```
+
+    Two signatures are supported for `mode='plain'`, which is the default:
+
+    - `(self)`
+    - `(self, info: SerializationInfo)`
+
+    And two other signatures for `mode='wrap'`:
+
+    - `(self, nxt: SerializerFunctionWrapHandler)`
+    - `(self, nxt: SerializerFunctionWrapHandler, info: SerializationInfo)`
+
+        See [the usage documentation](../concepts/serialization.md#serializers) for more information.
+
+    Args:
+        f: The function to be decorated.
+        mode: The serialization mode.
+
+            - `'plain'` means the function will be called instead of the default serialization logic
+            - `'wrap'` means the function will be called with an argument to optionally call the default
+                serialization logic.
+        when_used: Determines when this serializer should be used.
+        return_type: The return type for the function. If omitted it will be inferred from the type annotation.
+
+    Returns:
+        The decorator function.
+    """
+
+    def dec(f: ModelSerializer) -> _decorators.PydanticDescriptorProxy[Any]:
+        dec_info = _decorators.ModelSerializerDecoratorInfo(mode=mode, return_type=return_type, when_used=when_used)
+        return _decorators.PydanticDescriptorProxy(f, dec_info)
+
+    if f is None:
+        return dec  # pyright: ignore[reportReturnType]
+    else:
+        return dec(f)  # pyright: ignore[reportReturnType]
+
+
+AnyType = TypeVar('AnyType')
+
+
+if TYPE_CHECKING:
+    SerializeAsAny = Annotated[AnyType, ...]  # SerializeAsAny[list[str]] will be treated by type checkers as list[str]
+    """Annotation used to mark a type as having duck-typing serialization behavior.
+
+    See [usage documentation](../concepts/serialization.md#serializing-with-duck-typing) for more details.
+    """
+else:
+
+    @dataclasses.dataclass(**_internal_dataclass.slots_true)
+    class SerializeAsAny:
+        """Annotation used to mark a type as having duck-typing serialization behavior.
+
+        See [usage documentation](../concepts/serialization.md#serializing-with-duck-typing) for more details.
+        """
+
+        def __class_getitem__(cls, item: Any) -> Any:
+            return Annotated[item, SerializeAsAny()]
+
+        def __get_pydantic_core_schema__(
+            self, source_type: Any, handler: GetCoreSchemaHandler
+        ) -> core_schema.CoreSchema:
+            schema = handler(source_type)
+            schema_to_update = schema
+            while schema_to_update['type'] == 'definitions':
+                schema_to_update = schema_to_update.copy()
+                schema_to_update = schema_to_update['schema']
+            schema_to_update['serialization'] = core_schema.simple_ser_schema('any')
+            return schema
+
+        __hash__ = object.__hash__
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pydantic/functional_validators.py b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/functional_validators.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc4bbba6841c0abb3ae9068a12db8dae88b2d4d2
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/functional_validators.py
@@ -0,0 +1,893 @@
+"""This module contains related classes and functions for validation."""
+
+from __future__ import annotations as _annotations
+
+import dataclasses
+import sys
+import warnings
+from functools import partialmethod
+from types import FunctionType
+from typing import TYPE_CHECKING, Annotated, Any, Callable, Literal, TypeVar, Union, cast, overload
+
+from pydantic_core import PydanticUndefined, core_schema
+from typing_extensions import Self, TypeAlias
+
+from ._internal import _decorators, _generics, _internal_dataclass
+from .annotated_handlers import GetCoreSchemaHandler
+from .errors import PydanticUserError
+from .version import version_short
+from .warnings import ArbitraryTypeWarning, PydanticDeprecatedSince212
+
+if sys.version_info < (3, 11):
+    from typing_extensions import Protocol
+else:
+    from typing import Protocol
+
+_inspect_validator = _decorators.inspect_validator
+
+
+@dataclasses.dataclass(frozen=True, **_internal_dataclass.slots_true)
+class AfterValidator:
+    """!!! abstract "Usage Documentation"
+        [field *after* validators](../concepts/validators.md#field-after-validator)
+
+    A metadata class that indicates that a validation should be applied **after** the inner validation logic.
+
+    Attributes:
+        func: The validator function.
+
+    Example:
+        ```python
+        from typing import Annotated
+
+        from pydantic import AfterValidator, BaseModel, ValidationError
+
+        MyInt = Annotated[int, AfterValidator(lambda v: v + 1)]
+
+        class Model(BaseModel):
+            a: MyInt
+
+        print(Model(a=1).a)
+        #> 2
+
+        try:
+            Model(a='a')
+        except ValidationError as e:
+            print(e.json(indent=2))
+            '''
+            [
+              {
+                "type": "int_parsing",
+                "loc": [
+                  "a"
+                ],
+                "msg": "Input should be a valid integer, unable to parse string as an integer",
+                "input": "a",
+                "url": "https://errors.pydantic.dev/2/v/int_parsing"
+              }
+            ]
+            '''
+        ```
+    """
+
+    func: core_schema.NoInfoValidatorFunction | core_schema.WithInfoValidatorFunction
+
+    def __get_pydantic_core_schema__(self, source_type: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
+        schema = handler(source_type)
+        info_arg = _inspect_validator(self.func, mode='after', type='field')
+        if info_arg:
+            func = cast(core_schema.WithInfoValidatorFunction, self.func)
+            return core_schema.with_info_after_validator_function(func, schema=schema)
+        else:
+            func = cast(core_schema.NoInfoValidatorFunction, self.func)
+            return core_schema.no_info_after_validator_function(func, schema=schema)
+
+    @classmethod
+    def _from_decorator(cls, decorator: _decorators.Decorator[_decorators.FieldValidatorDecoratorInfo]) -> Self:
+        return cls(func=decorator.func)
+
+
+@dataclasses.dataclass(frozen=True, **_internal_dataclass.slots_true)
+class BeforeValidator:
+    """!!! abstract "Usage Documentation"
+        [field *before* validators](../concepts/validators.md#field-before-validator)
+
+    A metadata class that indicates that a validation should be applied **before** the inner validation logic.
+
+    Attributes:
+        func: The validator function.
+        json_schema_input_type: The input type used to generate the appropriate
+            JSON Schema (in validation mode). The actual input type is `Any`.
+
+    Example:
+        ```python
+        from typing import Annotated
+
+        from pydantic import BaseModel, BeforeValidator
+
+        MyInt = Annotated[int, BeforeValidator(lambda v: v + 1)]
+
+        class Model(BaseModel):
+            a: MyInt
+
+        print(Model(a=1).a)
+        #> 2
+
+        try:
+            Model(a='a')
+        except TypeError as e:
+            print(e)
+            #> can only concatenate str (not "int") to str
+        ```
+    """
+
+    func: core_schema.NoInfoValidatorFunction | core_schema.WithInfoValidatorFunction
+    json_schema_input_type: Any = PydanticUndefined
+
+    def __get_pydantic_core_schema__(self, source_type: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
+        schema = handler(source_type)
+        input_schema = (
+            None
+            if self.json_schema_input_type is PydanticUndefined
+            else handler.generate_schema(self.json_schema_input_type)
+        )
+
+        info_arg = _inspect_validator(self.func, mode='before', type='field')
+        if info_arg:
+            func = cast(core_schema.WithInfoValidatorFunction, self.func)
+            return core_schema.with_info_before_validator_function(
+                func,
+                schema=schema,
+                json_schema_input_schema=input_schema,
+            )
+        else:
+            func = cast(core_schema.NoInfoValidatorFunction, self.func)
+            return core_schema.no_info_before_validator_function(
+                func, schema=schema, json_schema_input_schema=input_schema
+            )
+
+    @classmethod
+    def _from_decorator(cls, decorator: _decorators.Decorator[_decorators.FieldValidatorDecoratorInfo]) -> Self:
+        return cls(
+            func=decorator.func,
+            json_schema_input_type=decorator.info.json_schema_input_type,
+        )
+
+
+@dataclasses.dataclass(frozen=True, **_internal_dataclass.slots_true)
+class PlainValidator:
+    """!!! abstract "Usage Documentation"
+        [field *plain* validators](../concepts/validators.md#field-plain-validator)
+
+    A metadata class that indicates that a validation should be applied **instead** of the inner validation logic.
+
+    !!! note
+        Before v2.9, `PlainValidator` wasn't always compatible with JSON Schema generation for `mode='validation'`.
+        You can now use the `json_schema_input_type` argument to specify the input type of the function
+        to be used in the JSON schema when `mode='validation'` (the default). See the example below for more details.
+
+    Attributes:
+        func: The validator function.
+        json_schema_input_type: The input type used to generate the appropriate
+            JSON Schema (in validation mode). The actual input type is `Any`.
+
+    Example:
+        ```python
+        from typing import Annotated, Union
+
+        from pydantic import BaseModel, PlainValidator
+
+        def validate(v: object) -> int:
+            if not isinstance(v, (int, str)):
+                raise ValueError(f'Expected int or str, go {type(v)}')
+
+            return int(v) + 1
+
+        MyInt = Annotated[
+            int,
+            PlainValidator(validate, json_schema_input_type=Union[str, int]),  # (1)!
+        ]
+
+        class Model(BaseModel):
+            a: MyInt
+
+        print(Model(a='1').a)
+        #> 2
+
+        print(Model(a=1).a)
+        #> 2
+        ```
+
+        1. In this example, we've specified the `json_schema_input_type` as `Union[str, int]` which indicates to the JSON schema
+        generator that in validation mode, the input type for the `a` field can be either a [`str`][] or an [`int`][].
+    """
+
+    func: core_schema.NoInfoValidatorFunction | core_schema.WithInfoValidatorFunction
+    json_schema_input_type: Any = Any
+
+    def __get_pydantic_core_schema__(self, source_type: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
+        # Note that for some valid uses of PlainValidator, it is not possible to generate a core schema for the
+        # source_type, so calling `handler(source_type)` will error, which prevents us from generating a proper
+        # serialization schema. To work around this for use cases that will not involve serialization, we simply
+        # catch any PydanticSchemaGenerationError that may be raised while attempting to build the serialization schema
+        # and abort any attempts to handle special serialization.
+        from pydantic import PydanticSchemaGenerationError
+
+        try:
+            schema = handler(source_type)
+            # TODO if `schema['serialization']` is one of `'include-exclude-dict/sequence',
+            # schema validation will fail. That's why we use 'type ignore' comments below.
+            serialization = schema.get(
+                'serialization',
+                core_schema.wrap_serializer_function_ser_schema(
+                    function=lambda v, h: h(v),
+                    schema=schema,
+                    return_schema=handler.generate_schema(source_type),
+                ),
+            )
+        except PydanticSchemaGenerationError:
+            serialization = None
+
+        input_schema = handler.generate_schema(self.json_schema_input_type)
+
+        info_arg = _inspect_validator(self.func, mode='plain', type='field')
+        if info_arg:
+            func = cast(core_schema.WithInfoValidatorFunction, self.func)
+            return core_schema.with_info_plain_validator_function(
+                func,
+                serialization=serialization,  # pyright: ignore[reportArgumentType]
+                json_schema_input_schema=input_schema,
+            )
+        else:
+            func = cast(core_schema.NoInfoValidatorFunction, self.func)
+            return core_schema.no_info_plain_validator_function(
+                func,
+                serialization=serialization,  # pyright: ignore[reportArgumentType]
+                json_schema_input_schema=input_schema,
+            )
+
+    @classmethod
+    def _from_decorator(cls, decorator: _decorators.Decorator[_decorators.FieldValidatorDecoratorInfo]) -> Self:
+        return cls(
+            func=decorator.func,
+            json_schema_input_type=decorator.info.json_schema_input_type,
+        )
+
+
+@dataclasses.dataclass(frozen=True, **_internal_dataclass.slots_true)
+class WrapValidator:
+    """!!! abstract "Usage Documentation"
+        [field *wrap* validators](../concepts/validators.md#field-wrap-validator)
+
+    A metadata class that indicates that a validation should be applied **around** the inner validation logic.
+
+    Attributes:
+        func: The validator function.
+        json_schema_input_type: The input type used to generate the appropriate
+            JSON Schema (in validation mode). The actual input type is `Any`.
+
+    ```python
+    from datetime import datetime
+    from typing import Annotated
+
+    from pydantic import BaseModel, ValidationError, WrapValidator
+
+    def validate_timestamp(v, handler):
+        if v == 'now':
+            # we don't want to bother with further validation, just return the new value
+            return datetime.now()
+        try:
+            return handler(v)
+        except ValidationError:
+            # validation failed, in this case we want to return a default value
+            return datetime(2000, 1, 1)
+
+    MyTimestamp = Annotated[datetime, WrapValidator(validate_timestamp)]
+
+    class Model(BaseModel):
+        a: MyTimestamp
+
+    print(Model(a='now').a)
+    #> 2032-01-02 03:04:05.000006
+    print(Model(a='invalid').a)
+    #> 2000-01-01 00:00:00
+    ```
+    """
+
+    func: core_schema.NoInfoWrapValidatorFunction | core_schema.WithInfoWrapValidatorFunction
+    json_schema_input_type: Any = PydanticUndefined
+
+    def __get_pydantic_core_schema__(self, source_type: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
+        schema = handler(source_type)
+        input_schema = (
+            None
+            if self.json_schema_input_type is PydanticUndefined
+            else handler.generate_schema(self.json_schema_input_type)
+        )
+
+        info_arg = _inspect_validator(self.func, mode='wrap', type='field')
+        if info_arg:
+            func = cast(core_schema.WithInfoWrapValidatorFunction, self.func)
+            return core_schema.with_info_wrap_validator_function(
+                func,
+                schema=schema,
+                json_schema_input_schema=input_schema,
+            )
+        else:
+            func = cast(core_schema.NoInfoWrapValidatorFunction, self.func)
+            return core_schema.no_info_wrap_validator_function(
+                func,
+                schema=schema,
+                json_schema_input_schema=input_schema,
+            )
+
+    @classmethod
+    def _from_decorator(cls, decorator: _decorators.Decorator[_decorators.FieldValidatorDecoratorInfo]) -> Self:
+        return cls(
+            func=decorator.func,
+            json_schema_input_type=decorator.info.json_schema_input_type,
+        )
+
+
+if TYPE_CHECKING:
+
+    class _OnlyValueValidatorClsMethod(Protocol):
+        def __call__(self, cls: Any, value: Any, /) -> Any: ...
+
+    class _V2ValidatorClsMethod(Protocol):
+        def __call__(self, cls: Any, value: Any, info: core_schema.ValidationInfo[Any], /) -> Any: ...
+
+    class _OnlyValueWrapValidatorClsMethod(Protocol):
+        def __call__(self, cls: Any, value: Any, handler: core_schema.ValidatorFunctionWrapHandler, /) -> Any: ...
+
+    class _V2WrapValidatorClsMethod(Protocol):
+        def __call__(
+            self,
+            cls: Any,
+            value: Any,
+            handler: core_schema.ValidatorFunctionWrapHandler,
+            info: core_schema.ValidationInfo[Any],
+            /,
+        ) -> Any: ...
+
+    _V2Validator = Union[
+        _V2ValidatorClsMethod,
+        core_schema.WithInfoValidatorFunction,
+        _OnlyValueValidatorClsMethod,
+        core_schema.NoInfoValidatorFunction,
+    ]
+
+    _V2WrapValidator = Union[
+        _V2WrapValidatorClsMethod,
+        core_schema.WithInfoWrapValidatorFunction,
+        _OnlyValueWrapValidatorClsMethod,
+        core_schema.NoInfoWrapValidatorFunction,
+    ]
+
+    _PartialClsOrStaticMethod: TypeAlias = Union[classmethod[Any, Any, Any], staticmethod[Any, Any], partialmethod[Any]]
+
+    _V2BeforeAfterOrPlainValidatorType = TypeVar(
+        '_V2BeforeAfterOrPlainValidatorType',
+        bound=Union[_V2Validator, _PartialClsOrStaticMethod],
+    )
+    _V2WrapValidatorType = TypeVar('_V2WrapValidatorType', bound=Union[_V2WrapValidator, _PartialClsOrStaticMethod])
+
+FieldValidatorModes: TypeAlias = Literal['before', 'after', 'wrap', 'plain']
+
+
+@overload
+def field_validator(
+    field: str,
+    /,
+    *fields: str,
+    mode: Literal['wrap'],
+    check_fields: bool | None = ...,
+    json_schema_input_type: Any = ...,
+) -> Callable[[_V2WrapValidatorType], _V2WrapValidatorType]: ...
+
+
+@overload
+def field_validator(
+    field: str,
+    /,
+    *fields: str,
+    mode: Literal['before', 'plain'],
+    check_fields: bool | None = ...,
+    json_schema_input_type: Any = ...,
+) -> Callable[[_V2BeforeAfterOrPlainValidatorType], _V2BeforeAfterOrPlainValidatorType]: ...
+
+
+@overload
+def field_validator(
+    field: str,
+    /,
+    *fields: str,
+    mode: Literal['after'] = ...,
+    check_fields: bool | None = ...,
+) -> Callable[[_V2BeforeAfterOrPlainValidatorType], _V2BeforeAfterOrPlainValidatorType]: ...
+
+
+def field_validator(
+    field: str,
+    /,
+    *fields: str,
+    mode: FieldValidatorModes = 'after',
+    check_fields: bool | None = None,
+    json_schema_input_type: Any = PydanticUndefined,
+) -> Callable[[Any], Any]:
+    """!!! abstract "Usage Documentation"
+        [field validators](../concepts/validators.md#field-validators)
+
+    Decorate methods on the class indicating that they should be used to validate fields.
+
+    Example usage:
+    ```python
+    from typing import Any
+
+    from pydantic import (
+        BaseModel,
+        ValidationError,
+        field_validator,
+    )
+
+    class Model(BaseModel):
+        a: str
+
+        @field_validator('a')
+        @classmethod
+        def ensure_foobar(cls, v: Any):
+            if 'foobar' not in v:
+                raise ValueError('"foobar" not found in a')
+            return v
+
+    print(repr(Model(a='this is foobar good')))
+    #> Model(a='this is foobar good')
+
+    try:
+        Model(a='snap')
+    except ValidationError as exc_info:
+        print(exc_info)
+        '''
+        1 validation error for Model
+        a
+          Value error, "foobar" not found in a [type=value_error, input_value='snap', input_type=str]
+        '''
+    ```
+
+    For more in depth examples, see [Field Validators](../concepts/validators.md#field-validators).
+
+    Args:
+        field: The first field the `field_validator` should be called on; this is separate
+            from `fields` to ensure an error is raised if you don't pass at least one.
+        *fields: Additional field(s) the `field_validator` should be called on.
+        mode: Specifies whether to validate the fields before or after validation.
+        check_fields: Whether to check that the fields actually exist on the model.
+        json_schema_input_type: The input type of the function. This is only used to generate
+            the appropriate JSON Schema (in validation mode) and can only specified
+            when `mode` is either `'before'`, `'plain'` or `'wrap'`.
+
+    Returns:
+        A decorator that can be used to decorate a function to be used as a field_validator.
+
+    Raises:
+        PydanticUserError:
+            - If `@field_validator` is used bare (with no fields).
+            - If the args passed to `@field_validator` as fields are not strings.
+            - If `@field_validator` applied to instance methods.
+    """
+    if isinstance(field, FunctionType):
+        raise PydanticUserError(
+            '`@field_validator` should be used with fields and keyword arguments, not bare. '
+            "E.g. usage should be `@validator('', ...)`",
+            code='validator-no-fields',
+        )
+
+    if mode not in ('before', 'plain', 'wrap') and json_schema_input_type is not PydanticUndefined:
+        raise PydanticUserError(
+            f"`json_schema_input_type` can't be used when mode is set to {mode!r}",
+            code='validator-input-type',
+        )
+
+    if json_schema_input_type is PydanticUndefined and mode == 'plain':
+        json_schema_input_type = Any
+
+    fields = field, *fields
+    if not all(isinstance(field, str) for field in fields):
+        raise PydanticUserError(
+            '`@field_validator` fields should be passed as separate string args. '
+            "E.g. usage should be `@validator('', '', ...)`",
+            code='validator-invalid-fields',
+        )
+
+    def dec(
+        f: Callable[..., Any] | staticmethod[Any, Any] | classmethod[Any, Any, Any],
+    ) -> _decorators.PydanticDescriptorProxy[Any]:
+        if _decorators.is_instance_method_from_sig(f):
+            raise PydanticUserError(
+                '`@field_validator` cannot be applied to instance methods', code='validator-instance-method'
+            )
+
+        # auto apply the @classmethod decorator
+        f = _decorators.ensure_classmethod_based_on_signature(f)
+
+        dec_info = _decorators.FieldValidatorDecoratorInfo(
+            fields=fields, mode=mode, check_fields=check_fields, json_schema_input_type=json_schema_input_type
+        )
+        return _decorators.PydanticDescriptorProxy(f, dec_info)
+
+    return dec
+
+
+_ModelType = TypeVar('_ModelType')
+_ModelTypeCo = TypeVar('_ModelTypeCo', covariant=True)
+
+
+class ModelWrapValidatorHandler(core_schema.ValidatorFunctionWrapHandler, Protocol[_ModelTypeCo]):
+    """`@model_validator` decorated function handler argument type. This is used when `mode='wrap'`."""
+
+    def __call__(  # noqa: D102
+        self,
+        value: Any,
+        outer_location: str | int | None = None,
+        /,
+    ) -> _ModelTypeCo:  # pragma: no cover
+        ...
+
+
+class ModelWrapValidatorWithoutInfo(Protocol[_ModelType]):
+    """A `@model_validator` decorated function signature.
+    This is used when `mode='wrap'` and the function does not have info argument.
+    """
+
+    def __call__(  # noqa: D102
+        self,
+        cls: type[_ModelType],
+        # this can be a dict, a model instance
+        # or anything else that gets passed to validate_python
+        # thus validators _must_ handle all cases
+        value: Any,
+        handler: ModelWrapValidatorHandler[_ModelType],
+        /,
+    ) -> _ModelType: ...
+
+
+class ModelWrapValidator(Protocol[_ModelType]):
+    """A `@model_validator` decorated function signature. This is used when `mode='wrap'`."""
+
+    def __call__(  # noqa: D102
+        self,
+        cls: type[_ModelType],
+        # this can be a dict, a model instance
+        # or anything else that gets passed to validate_python
+        # thus validators _must_ handle all cases
+        value: Any,
+        handler: ModelWrapValidatorHandler[_ModelType],
+        info: core_schema.ValidationInfo,
+        /,
+    ) -> _ModelType: ...
+
+
+class FreeModelBeforeValidatorWithoutInfo(Protocol):
+    """A `@model_validator` decorated function signature.
+    This is used when `mode='before'` and the function does not have info argument.
+    """
+
+    def __call__(  # noqa: D102
+        self,
+        # this can be a dict, a model instance
+        # or anything else that gets passed to validate_python
+        # thus validators _must_ handle all cases
+        value: Any,
+        /,
+    ) -> Any: ...
+
+
+class ModelBeforeValidatorWithoutInfo(Protocol):
+    """A `@model_validator` decorated function signature.
+    This is used when `mode='before'` and the function does not have info argument.
+    """
+
+    def __call__(  # noqa: D102
+        self,
+        cls: Any,
+        # this can be a dict, a model instance
+        # or anything else that gets passed to validate_python
+        # thus validators _must_ handle all cases
+        value: Any,
+        /,
+    ) -> Any: ...
+
+
+class FreeModelBeforeValidator(Protocol):
+    """A `@model_validator` decorated function signature. This is used when `mode='before'`."""
+
+    def __call__(  # noqa: D102
+        self,
+        # this can be a dict, a model instance
+        # or anything else that gets passed to validate_python
+        # thus validators _must_ handle all cases
+        value: Any,
+        info: core_schema.ValidationInfo[Any],
+        /,
+    ) -> Any: ...
+
+
+class ModelBeforeValidator(Protocol):
+    """A `@model_validator` decorated function signature. This is used when `mode='before'`."""
+
+    def __call__(  # noqa: D102
+        self,
+        cls: Any,
+        # this can be a dict, a model instance
+        # or anything else that gets passed to validate_python
+        # thus validators _must_ handle all cases
+        value: Any,
+        info: core_schema.ValidationInfo[Any],
+        /,
+    ) -> Any: ...
+
+
+ModelAfterValidatorWithoutInfo = Callable[[_ModelType], _ModelType]
+"""A `@model_validator` decorated function signature. This is used when `mode='after'` and the function does not
+have info argument.
+"""
+
+ModelAfterValidator = Callable[[_ModelType, core_schema.ValidationInfo[Any]], _ModelType]
+"""A `@model_validator` decorated function signature. This is used when `mode='after'`."""
+
+_AnyModelWrapValidator = Union[ModelWrapValidator[_ModelType], ModelWrapValidatorWithoutInfo[_ModelType]]
+_AnyModelBeforeValidator = Union[
+    FreeModelBeforeValidator, ModelBeforeValidator, FreeModelBeforeValidatorWithoutInfo, ModelBeforeValidatorWithoutInfo
+]
+_AnyModelAfterValidator = Union[ModelAfterValidator[_ModelType], ModelAfterValidatorWithoutInfo[_ModelType]]
+
+
+@overload
+def model_validator(
+    *,
+    mode: Literal['wrap'],
+) -> Callable[
+    [_AnyModelWrapValidator[_ModelType]], _decorators.PydanticDescriptorProxy[_decorators.ModelValidatorDecoratorInfo]
+]: ...
+
+
+@overload
+def model_validator(
+    *,
+    mode: Literal['before'],
+) -> Callable[
+    [_AnyModelBeforeValidator], _decorators.PydanticDescriptorProxy[_decorators.ModelValidatorDecoratorInfo]
+]: ...
+
+
+@overload
+def model_validator(
+    *,
+    mode: Literal['after'],
+) -> Callable[
+    [_AnyModelAfterValidator[_ModelType]], _decorators.PydanticDescriptorProxy[_decorators.ModelValidatorDecoratorInfo]
+]: ...
+
+
+def model_validator(
+    *,
+    mode: Literal['wrap', 'before', 'after'],
+) -> Any:
+    """!!! abstract "Usage Documentation"
+        [Model Validators](../concepts/validators.md#model-validators)
+
+    Decorate model methods for validation purposes.
+
+    Example usage:
+    ```python
+    from typing_extensions import Self
+
+    from pydantic import BaseModel, ValidationError, model_validator
+
+    class Square(BaseModel):
+        width: float
+        height: float
+
+        @model_validator(mode='after')
+        def verify_square(self) -> Self:
+            if self.width != self.height:
+                raise ValueError('width and height do not match')
+            return self
+
+    s = Square(width=1, height=1)
+    print(repr(s))
+    #> Square(width=1.0, height=1.0)
+
+    try:
+        Square(width=1, height=2)
+    except ValidationError as e:
+        print(e)
+        '''
+        1 validation error for Square
+          Value error, width and height do not match [type=value_error, input_value={'width': 1, 'height': 2}, input_type=dict]
+        '''
+    ```
+
+    For more in depth examples, see [Model Validators](../concepts/validators.md#model-validators).
+
+    Args:
+        mode: A required string literal that specifies the validation mode.
+            It can be one of the following: 'wrap', 'before', or 'after'.
+
+    Returns:
+        A decorator that can be used to decorate a function to be used as a model validator.
+    """
+
+    def dec(f: Any) -> _decorators.PydanticDescriptorProxy[Any]:
+        # auto apply the @classmethod decorator. NOTE: in V3, do not apply the conversion for 'after' validators:
+        f = _decorators.ensure_classmethod_based_on_signature(f)
+        if mode == 'after' and isinstance(f, classmethod):
+            warnings.warn(
+                category=PydanticDeprecatedSince212,
+                message=(
+                    "Using `@model_validator` with mode='after' on a classmethod is deprecated. Instead, use an instance method. "
+                    f'See the documentation at https://docs.pydantic.dev/{version_short()}/concepts/validators/#model-after-validator.'
+                ),
+                stacklevel=2,
+            )
+
+        dec_info = _decorators.ModelValidatorDecoratorInfo(mode=mode)
+        return _decorators.PydanticDescriptorProxy(f, dec_info)
+
+    return dec
+
+
+AnyType = TypeVar('AnyType')
+
+
+if TYPE_CHECKING:
+    # If we add configurable attributes to IsInstance, we'd probably need to stop hiding it from type checkers like this
+    InstanceOf = Annotated[AnyType, ...]  # `IsInstance[Sequence]` will be recognized by type checkers as `Sequence`
+
+else:
+
+    @dataclasses.dataclass(**_internal_dataclass.slots_true)
+    class InstanceOf:
+        '''Generic type for annotating a type that is an instance of a given class.
+
+        Example:
+            ```python
+            from pydantic import BaseModel, InstanceOf
+
+            class Foo:
+                ...
+
+            class Bar(BaseModel):
+                foo: InstanceOf[Foo]
+
+            Bar(foo=Foo())
+            try:
+                Bar(foo=42)
+            except ValidationError as e:
+                print(e)
+                """
+                [
+                │   {
+                │   │   'type': 'is_instance_of',
+                │   │   'loc': ('foo',),
+                │   │   'msg': 'Input should be an instance of Foo',
+                │   │   'input': 42,
+                │   │   'ctx': {'class': 'Foo'},
+                │   │   'url': 'https://errors.pydantic.dev/0.38.0/v/is_instance_of'
+                │   }
+                ]
+                """
+            ```
+        '''
+
+        @classmethod
+        def __class_getitem__(cls, item: AnyType) -> AnyType:
+            return Annotated[item, cls()]
+
+        @classmethod
+        def __get_pydantic_core_schema__(cls, source: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
+            from pydantic import PydanticSchemaGenerationError
+
+            # use the generic _origin_ as the second argument to isinstance when appropriate
+            instance_of_schema = core_schema.is_instance_schema(_generics.get_origin(source) or source)
+
+            try:
+                # Try to generate the "standard" schema, which will be used when loading from JSON
+                original_schema = handler(source)
+            except PydanticSchemaGenerationError:
+                # If that fails, just produce a schema that can validate from python
+                return instance_of_schema
+            else:
+                # Use the "original" approach to serialization
+                instance_of_schema['serialization'] = core_schema.wrap_serializer_function_ser_schema(
+                    function=lambda v, h: h(v), schema=original_schema
+                )
+                return core_schema.json_or_python_schema(python_schema=instance_of_schema, json_schema=original_schema)
+
+        __hash__ = object.__hash__
+
+
+if TYPE_CHECKING:
+    SkipValidation = Annotated[AnyType, ...]  # SkipValidation[list[str]] will be treated by type checkers as list[str]
+else:
+
+    @dataclasses.dataclass(**_internal_dataclass.slots_true)
+    class SkipValidation:
+        """If this is applied as an annotation (e.g., via `x: Annotated[int, SkipValidation]`), validation will be
+            skipped. You can also use `SkipValidation[int]` as a shorthand for `Annotated[int, SkipValidation]`.
+
+        This can be useful if you want to use a type annotation for documentation/IDE/type-checking purposes,
+        and know that it is safe to skip validation for one or more of the fields.
+
+        Because this converts the validation schema to `any_schema`, subsequent annotation-applied transformations
+        may not have the expected effects. Therefore, when used, this annotation should generally be the final
+        annotation applied to a type.
+        """
+
+        def __class_getitem__(cls, item: Any) -> Any:
+            return Annotated[item, SkipValidation()]
+
+        @classmethod
+        def __get_pydantic_core_schema__(cls, source: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
+            with warnings.catch_warnings():
+                warnings.simplefilter('ignore', ArbitraryTypeWarning)
+                original_schema = handler(source)
+            metadata = {'pydantic_js_annotation_functions': [lambda _c, h: h(original_schema)]}
+            return core_schema.any_schema(
+                metadata=metadata,
+                serialization=core_schema.wrap_serializer_function_ser_schema(
+                    function=lambda v, h: h(v), schema=original_schema
+                ),
+            )
+
+        __hash__ = object.__hash__
+
+
+_FromTypeT = TypeVar('_FromTypeT')
+
+
+class ValidateAs:
+    """A helper class to validate a custom type from a type that is natively supported by Pydantic.
+
+    Args:
+        from_type: The type natively supported by Pydantic to use to perform validation.
+        instantiation_hook: A callable taking the validated type as an argument, and returning
+            the populated custom type.
+
+    Example:
+        ```python {lint="skip"}
+        from typing import Annotated
+
+        from pydantic import BaseModel, TypeAdapter, ValidateAs
+
+        class MyCls:
+            def __init__(self, a: int) -> None:
+                self.a = a
+
+            def __repr__(self) -> str:
+                return f"MyCls(a={self.a})"
+
+        class Model(BaseModel):
+            a: int
+
+
+        ta = TypeAdapter(
+            Annotated[MyCls, ValidateAs(Model, lambda v: MyCls(a=v.a))]
+        )
+
+        print(ta.validate_python({'a': 1}))
+        #> MyCls(a=1)
+        ```
+    """
+
+    # TODO: make use of PEP 747
+    def __init__(self, from_type: type[_FromTypeT], /, instantiation_hook: Callable[[_FromTypeT], Any]) -> None:
+        self.from_type = from_type
+        self.instantiation_hook = instantiation_hook
+
+    def __get_pydantic_core_schema__(self, source: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
+        schema = handler(self.from_type)
+        return core_schema.no_info_after_validator_function(
+            self.instantiation_hook,
+            schema=schema,
+        )
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pydantic/generics.py b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/generics.py
new file mode 100644
index 0000000000000000000000000000000000000000..3f1070d08f3ac5bd554794401734eb349373ab8e
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/generics.py
@@ -0,0 +1,5 @@
+"""The `generics` module is a backport module from V1."""
+
+from ._migration import getattr_migration
+
+__getattr__ = getattr_migration(__name__)
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pydantic/json.py b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/json.py
new file mode 100644
index 0000000000000000000000000000000000000000..bcaff9f57958b8c0938255fd8f937293c5850cbd
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/json.py
@@ -0,0 +1,5 @@
+"""The `json` module is a backport module from V1."""
+
+from ._migration import getattr_migration
+
+__getattr__ = getattr_migration(__name__)
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pydantic/json_schema.py b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/json_schema.py
new file mode 100644
index 0000000000000000000000000000000000000000..a16afb89282d1347225c2c8bed2a76a09e79aa61
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/json_schema.py
@@ -0,0 +1,2854 @@
+"""!!! abstract "Usage Documentation"
+    [JSON Schema](../concepts/json_schema.md)
+
+The `json_schema` module contains classes and functions to allow the way [JSON Schema](https://json-schema.org/)
+is generated to be customized.
+
+In general you shouldn't need to use this module directly; instead, you can use
+[`BaseModel.model_json_schema`][pydantic.BaseModel.model_json_schema] and
+[`TypeAdapter.json_schema`][pydantic.TypeAdapter.json_schema].
+"""
+
+from __future__ import annotations as _annotations
+
+import dataclasses
+import inspect
+import math
+import os
+import re
+import warnings
+from collections import Counter, defaultdict
+from collections.abc import Hashable, Iterable, Sequence
+from copy import deepcopy
+from enum import Enum
+from re import Pattern
+from typing import (
+    TYPE_CHECKING,
+    Annotated,
+    Any,
+    Callable,
+    Literal,
+    NewType,
+    TypeVar,
+    Union,
+    cast,
+    overload,
+)
+
+import pydantic_core
+from pydantic_core import MISSING, CoreSchema, PydanticOmit, core_schema, to_jsonable_python
+from pydantic_core.core_schema import ComputedField
+from typing_extensions import TypeAlias, assert_never, deprecated, final
+from typing_inspection.introspection import get_literal_values
+
+from pydantic.warnings import PydanticDeprecatedSince26, PydanticDeprecatedSince29
+
+from ._internal import (
+    _config,
+    _core_metadata,
+    _core_utils,
+    _decorators,
+    _internal_dataclass,
+    _mock_val_ser,
+    _schema_generation_shared,
+)
+from .annotated_handlers import GetJsonSchemaHandler
+from .config import JsonDict, JsonValue
+from .errors import PydanticInvalidForJsonSchema, PydanticSchemaGenerationError, PydanticUserError
+
+if TYPE_CHECKING:
+    from . import ConfigDict
+    from ._internal._core_utils import CoreSchemaField, CoreSchemaOrField
+    from ._internal._dataclasses import PydanticDataclass
+    from ._internal._schema_generation_shared import GetJsonSchemaFunction
+    from .main import BaseModel
+
+
+CoreSchemaOrFieldType = Literal[core_schema.CoreSchemaType, core_schema.CoreSchemaFieldType]
+"""
+A type alias for defined schema types that represents a union of
+`core_schema.CoreSchemaType` and
+`core_schema.CoreSchemaFieldType`.
+"""
+
+JsonSchemaValue = dict[str, Any]
+"""
+A type alias for a JSON schema value. This is a dictionary of string keys to arbitrary JSON values.
+"""
+
+JsonSchemaMode = Literal['validation', 'serialization']
+"""
+A type alias that represents the mode of a JSON schema; either 'validation' or 'serialization'.
+
+For some types, the inputs to validation differ from the outputs of serialization. For example,
+computed fields will only be present when serializing, and should not be provided when
+validating. This flag provides a way to indicate whether you want the JSON schema required
+for validation inputs, or that will be matched by serialization outputs.
+"""
+
+_MODE_TITLE_MAPPING: dict[JsonSchemaMode, str] = {'validation': 'Input', 'serialization': 'Output'}
+
+
+JsonSchemaWarningKind = Literal['skipped-choice', 'non-serializable-default', 'skipped-discriminator']
+"""
+A type alias representing the kinds of warnings that can be emitted during JSON schema generation.
+
+See [`GenerateJsonSchema.render_warning_message`][pydantic.json_schema.GenerateJsonSchema.render_warning_message]
+for more details.
+"""
+
+
+class PydanticJsonSchemaWarning(UserWarning):
+    """This class is used to emit warnings produced during JSON schema generation.
+    See the [`GenerateJsonSchema.emit_warning`][pydantic.json_schema.GenerateJsonSchema.emit_warning] and
+    [`GenerateJsonSchema.render_warning_message`][pydantic.json_schema.GenerateJsonSchema.render_warning_message]
+    methods for more details; these can be overridden to control warning behavior.
+    """
+
+
+NoDefault = object()
+"""A sentinel value used to indicate that no default value should be used when generating a JSON Schema
+for a core schema with a default value.
+"""
+
+
+# ##### JSON Schema Generation #####
+DEFAULT_REF_TEMPLATE = '#/$defs/{model}'
+"""The default format string used to generate reference names."""
+
+# There are three types of references relevant to building JSON schemas:
+#   1. core_schema "ref" values; these are not exposed as part of the JSON schema
+#       * these might look like the fully qualified path of a model, its id, or something similar
+CoreRef = NewType('CoreRef', str)
+#   2. keys of the "definitions" object that will eventually go into the JSON schema
+#       * by default, these look like "MyModel", though may change in the presence of collisions
+#       * eventually, we may want to make it easier to modify the way these names are generated
+DefsRef = NewType('DefsRef', str)
+#   3. the values corresponding to the "$ref" key in the schema
+#       * By default, these look like "#/$defs/MyModel", as in {"$ref": "#/$defs/MyModel"}
+JsonRef = NewType('JsonRef', str)
+
+CoreModeRef = tuple[CoreRef, JsonSchemaMode]
+JsonSchemaKeyT = TypeVar('JsonSchemaKeyT', bound=Hashable)
+
+_PRIMITIVE_JSON_SCHEMA_TYPES = ('string', 'boolean', 'null', 'integer', 'number')
+
+
+@dataclasses.dataclass(**_internal_dataclass.slots_true)
+class _DefinitionsRemapping:
+    defs_remapping: dict[DefsRef, DefsRef]
+    json_remapping: dict[JsonRef, JsonRef]
+
+    @staticmethod
+    def from_prioritized_choices(
+        prioritized_choices: dict[DefsRef, list[DefsRef]],
+        defs_to_json: dict[DefsRef, JsonRef],
+        definitions: dict[DefsRef, JsonSchemaValue],
+    ) -> _DefinitionsRemapping:
+        """
+        This function should produce a remapping that replaces complex DefsRef with the simpler ones from the
+        prioritized_choices such that applying the name remapping would result in an equivalent JSON schema.
+        """
+        # We need to iteratively simplify the definitions until we reach a fixed point.
+        # The reason for this is that outer definitions may reference inner definitions that get simplified
+        # into an equivalent reference, and the outer definitions won't be equivalent until we've simplified
+        # the inner definitions.
+        copied_definitions = deepcopy(definitions)
+        definitions_schema = {'$defs': copied_definitions}
+        for _iter in range(100):  # prevent an infinite loop in the case of a bug, 100 iterations should be enough
+            # For every possible remapped DefsRef, collect all schemas that that DefsRef might be used for:
+            schemas_for_alternatives: dict[DefsRef, list[JsonSchemaValue]] = defaultdict(list)
+            for defs_ref in copied_definitions:
+                alternatives = prioritized_choices[defs_ref]
+                for alternative in alternatives:
+                    schemas_for_alternatives[alternative].append(copied_definitions[defs_ref])
+
+            # Deduplicate the schemas for each alternative; the idea is that we only want to remap to a new DefsRef
+            # if it introduces no ambiguity, i.e., there is only one distinct schema for that DefsRef.
+            for defs_ref in schemas_for_alternatives:
+                schemas_for_alternatives[defs_ref] = _deduplicate_schemas(schemas_for_alternatives[defs_ref])
+
+            # Build the remapping
+            defs_remapping: dict[DefsRef, DefsRef] = {}
+            json_remapping: dict[JsonRef, JsonRef] = {}
+            for original_defs_ref in definitions:
+                alternatives = prioritized_choices[original_defs_ref]
+                # Pick the first alternative that has only one schema, since that means there is no collision
+                remapped_defs_ref = next(x for x in alternatives if len(schemas_for_alternatives[x]) == 1)
+                defs_remapping[original_defs_ref] = remapped_defs_ref
+                json_remapping[defs_to_json[original_defs_ref]] = defs_to_json[remapped_defs_ref]
+            remapping = _DefinitionsRemapping(defs_remapping, json_remapping)
+            new_definitions_schema = remapping.remap_json_schema({'$defs': copied_definitions})
+            if definitions_schema == new_definitions_schema:
+                # We've reached the fixed point
+                return remapping
+            definitions_schema = new_definitions_schema
+
+        raise PydanticInvalidForJsonSchema('Failed to simplify the JSON schema definitions')
+
+    def remap_defs_ref(self, ref: DefsRef) -> DefsRef:
+        return self.defs_remapping.get(ref, ref)
+
+    def remap_json_ref(self, ref: JsonRef) -> JsonRef:
+        return self.json_remapping.get(ref, ref)
+
+    def remap_json_schema(self, schema: Any) -> Any:
+        """
+        Recursively update the JSON schema replacing all $refs
+        """
+        if isinstance(schema, str):
+            # Note: this may not really be a JsonRef; we rely on having no collisions between JsonRefs and other strings
+            return self.remap_json_ref(JsonRef(schema))
+        elif isinstance(schema, list):
+            return [self.remap_json_schema(item) for item in schema]
+        elif isinstance(schema, dict):
+            for key, value in schema.items():
+                if key == '$ref' and isinstance(value, str):
+                    schema['$ref'] = self.remap_json_ref(JsonRef(value))
+                elif key == '$defs':
+                    schema['$defs'] = {
+                        self.remap_defs_ref(DefsRef(key)): self.remap_json_schema(value)
+                        for key, value in schema['$defs'].items()
+                    }
+                else:
+                    schema[key] = self.remap_json_schema(value)
+        return schema
+
+
+class GenerateJsonSchema:
+    """!!! abstract "Usage Documentation"
+        [Customizing the JSON Schema Generation Process](../concepts/json_schema.md#customizing-the-json-schema-generation-process)
+
+    A class for generating JSON schemas.
+
+    This class generates JSON schemas based on configured parameters. The default schema dialect
+    is [https://json-schema.org/draft/2020-12/schema](https://json-schema.org/draft/2020-12/schema).
+    The class uses `by_alias` to configure how fields with
+    multiple names are handled and `ref_template` to format reference names.
+
+    Attributes:
+        schema_dialect: The JSON schema dialect used to generate the schema. See
+            [Declaring a Dialect](https://json-schema.org/understanding-json-schema/reference/schema.html#id4)
+            in the JSON Schema documentation for more information about dialects.
+        ignored_warning_kinds: Warnings to ignore when generating the schema. `self.render_warning_message` will
+            do nothing if its argument `kind` is in `ignored_warning_kinds`;
+            this value can be modified on subclasses to easily control which warnings are emitted.
+        by_alias: Whether to use field aliases when generating the schema.
+        ref_template: The format string used when generating reference names.
+        core_to_json_refs: A mapping of core refs to JSON refs.
+        core_to_defs_refs: A mapping of core refs to definition refs.
+        defs_to_core_refs: A mapping of definition refs to core refs.
+        json_to_defs_refs: A mapping of JSON refs to definition refs.
+        definitions: Definitions in the schema.
+
+    Args:
+        by_alias: Whether to use field aliases in the generated schemas.
+        ref_template: The format string to use when generating reference names.
+        union_format: The format to use when combining schemas from unions together. Can be one of:
+
+            - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
+              keyword to combine schemas (the default).
+            - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
+              keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
+              type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
+              `any_of`.
+
+    Raises:
+        JsonSchemaError: If the instance of the class is inadvertently reused after generating a schema.
+    """
+
+    schema_dialect = 'https://json-schema.org/draft/2020-12/schema'
+
+    # `self.render_warning_message` will do nothing if its argument `kind` is in `ignored_warning_kinds`;
+    # this value can be modified on subclasses to easily control which warnings are emitted
+    ignored_warning_kinds: set[JsonSchemaWarningKind] = {'skipped-choice'}
+
+    def __init__(
+        self,
+        by_alias: bool = True,
+        ref_template: str = DEFAULT_REF_TEMPLATE,
+        union_format: Literal['any_of', 'primitive_type_array'] = 'any_of',
+    ) -> None:
+        self.by_alias = by_alias
+        self.ref_template = ref_template
+        self.union_format: Literal['any_of', 'primitive_type_array'] = union_format
+
+        self.core_to_json_refs: dict[CoreModeRef, JsonRef] = {}
+        self.core_to_defs_refs: dict[CoreModeRef, DefsRef] = {}
+        self.defs_to_core_refs: dict[DefsRef, CoreModeRef] = {}
+        self.json_to_defs_refs: dict[JsonRef, DefsRef] = {}
+
+        self.definitions: dict[DefsRef, JsonSchemaValue] = {}
+        self._config_wrapper_stack = _config.ConfigWrapperStack(_config.ConfigWrapper({}))
+
+        self._mode: JsonSchemaMode = 'validation'
+
+        # The following includes a mapping of a fully-unique defs ref choice to a list of preferred
+        # alternatives, which are generally simpler, such as only including the class name.
+        # At the end of schema generation, we use these to produce a JSON schema with more human-readable
+        # definitions, which would also work better in a generated OpenAPI client, etc.
+        self._prioritized_defsref_choices: dict[DefsRef, list[DefsRef]] = {}
+        self._collision_counter: dict[str, int] = defaultdict(int)
+        self._collision_index: dict[str, int] = {}
+
+        self._schema_type_to_method = self.build_schema_type_to_method()
+
+        # When we encounter definitions we need to try to build them immediately
+        # so that they are available schemas that reference them
+        # But it's possible that CoreSchema was never going to be used
+        # (e.g. because the CoreSchema that references short circuits is JSON schema generation without needing
+        #  the reference) so instead of failing altogether if we can't build a definition we
+        # store the error raised and re-throw it if we end up needing that def
+        self._core_defs_invalid_for_json_schema: dict[DefsRef, PydanticInvalidForJsonSchema] = {}
+
+        # This changes to True after generating a schema, to prevent issues caused by accidental reuse
+        # of a single instance of a schema generator
+        self._used = False
+
+    @property
+    def _config(self) -> _config.ConfigWrapper:
+        return self._config_wrapper_stack.tail
+
+    @property
+    def mode(self) -> JsonSchemaMode:
+        if self._config.json_schema_mode_override is not None:
+            return self._config.json_schema_mode_override
+        else:
+            return self._mode
+
+    def build_schema_type_to_method(
+        self,
+    ) -> dict[CoreSchemaOrFieldType, Callable[[CoreSchemaOrField], JsonSchemaValue]]:
+        """Builds a dictionary mapping fields to methods for generating JSON schemas.
+
+        Returns:
+            A dictionary containing the mapping of `CoreSchemaOrFieldType` to a handler method.
+
+        Raises:
+            TypeError: If no method has been defined for generating a JSON schema for a given pydantic core schema type.
+        """
+        mapping: dict[CoreSchemaOrFieldType, Callable[[CoreSchemaOrField], JsonSchemaValue]] = {}
+        core_schema_types: list[CoreSchemaOrFieldType] = list(get_literal_values(CoreSchemaOrFieldType))
+        for key in core_schema_types:
+            method_name = f'{key.replace("-", "_")}_schema'
+            try:
+                mapping[key] = getattr(self, method_name)
+            except AttributeError as e:  # pragma: no cover
+                if os.getenv('PYDANTIC_PRIVATE_ALLOW_UNHANDLED_SCHEMA_TYPES'):
+                    continue
+                raise TypeError(
+                    f'No method for generating JsonSchema for core_schema.type={key!r} '
+                    f'(expected: {type(self).__name__}.{method_name})'
+                ) from e
+        return mapping
+
+    def generate_definitions(
+        self, inputs: Sequence[tuple[JsonSchemaKeyT, JsonSchemaMode, core_schema.CoreSchema]]
+    ) -> tuple[dict[tuple[JsonSchemaKeyT, JsonSchemaMode], JsonSchemaValue], dict[DefsRef, JsonSchemaValue]]:
+        """Generates JSON schema definitions from a list of core schemas, pairing the generated definitions with a
+        mapping that links the input keys to the definition references.
+
+        Args:
+            inputs: A sequence of tuples, where:
+
+                - The first element is a JSON schema key type.
+                - The second element is the JSON mode: either 'validation' or 'serialization'.
+                - The third element is a core schema.
+
+        Returns:
+            A tuple where:
+
+                - The first element is a dictionary whose keys are tuples of JSON schema key type and JSON mode, and
+                    whose values are the JSON schema corresponding to that pair of inputs. (These schemas may have
+                    JsonRef references to definitions that are defined in the second returned element.)
+                - The second element is a dictionary whose keys are definition references for the JSON schemas
+                    from the first returned element, and whose values are the actual JSON schema definitions.
+
+        Raises:
+            PydanticUserError: Raised if the JSON schema generator has already been used to generate a JSON schema.
+        """
+        if self._used:
+            raise PydanticUserError(
+                'This JSON schema generator has already been used to generate a JSON schema. '
+                f'You must create a new instance of {type(self).__name__} to generate a new JSON schema.',
+                code='json-schema-already-used',
+            )
+
+        for _, mode, schema in inputs:
+            self._mode = mode
+            self.generate_inner(schema)
+
+        definitions_remapping = self._build_definitions_remapping()
+
+        json_schemas_map: dict[tuple[JsonSchemaKeyT, JsonSchemaMode], DefsRef] = {}
+        for key, mode, schema in inputs:
+            self._mode = mode
+            json_schema = self.generate_inner(schema)
+            json_schemas_map[(key, mode)] = definitions_remapping.remap_json_schema(json_schema)
+
+        json_schema = {'$defs': self.definitions}
+        json_schema = definitions_remapping.remap_json_schema(json_schema)
+        self._used = True
+        return json_schemas_map, self.sort(json_schema['$defs'])  # type: ignore
+
+    def generate(self, schema: CoreSchema, mode: JsonSchemaMode = 'validation') -> JsonSchemaValue:
+        """Generates a JSON schema for a specified schema in a specified mode.
+
+        Args:
+            schema: A Pydantic model.
+            mode: The mode in which to generate the schema. Defaults to 'validation'.
+
+        Returns:
+            A JSON schema representing the specified schema.
+
+        Raises:
+            PydanticUserError: If the JSON schema generator has already been used to generate a JSON schema.
+        """
+        self._mode = mode
+        if self._used:
+            raise PydanticUserError(
+                'This JSON schema generator has already been used to generate a JSON schema. '
+                f'You must create a new instance of {type(self).__name__} to generate a new JSON schema.',
+                code='json-schema-already-used',
+            )
+
+        json_schema: JsonSchemaValue = self.generate_inner(schema)
+        json_ref_counts = self.get_json_ref_counts(json_schema)
+
+        ref = cast(JsonRef, json_schema.get('$ref'))
+        while ref is not None:  # may need to unpack multiple levels
+            ref_json_schema = self.get_schema_from_definitions(ref)
+            if json_ref_counts[ref] == 1 and ref_json_schema is not None and len(json_schema) == 1:
+                # "Unpack" the ref since this is the only reference and there are no sibling keys
+                json_schema = ref_json_schema.copy()  # copy to prevent recursive dict reference
+                json_ref_counts[ref] -= 1
+                ref = cast(JsonRef, json_schema.get('$ref'))
+            ref = None
+
+        self._garbage_collect_definitions(json_schema)
+        definitions_remapping = self._build_definitions_remapping()
+
+        if self.definitions:
+            json_schema['$defs'] = self.definitions
+
+        json_schema = definitions_remapping.remap_json_schema(json_schema)
+
+        # For now, we will not set the $schema key. However, if desired, this can be easily added by overriding
+        # this method and adding the following line after a call to super().generate(schema):
+        # json_schema['$schema'] = self.schema_dialect
+
+        self._used = True
+        return self.sort(json_schema)
+
+    def generate_inner(self, schema: CoreSchemaOrField) -> JsonSchemaValue:  # noqa: C901
+        """Generates a JSON schema for a given core schema.
+
+        Args:
+            schema: The given core schema.
+
+        Returns:
+            The generated JSON schema.
+
+        TODO: the nested function definitions here seem like bad practice, I'd like to unpack these
+        in a future PR. It'd be great if we could shorten the call stack a bit for JSON schema generation,
+        and I think there's potential for that here.
+        """
+        # If a schema with the same CoreRef has been handled, just return a reference to it
+        # Note that this assumes that it will _never_ be the case that the same CoreRef is used
+        # on types that should have different JSON schemas
+        if 'ref' in schema:
+            core_ref = CoreRef(schema['ref'])  # type: ignore[typeddict-item]
+            core_mode_ref = (core_ref, self.mode)
+            if core_mode_ref in self.core_to_defs_refs and self.core_to_defs_refs[core_mode_ref] in self.definitions:
+                return {'$ref': self.core_to_json_refs[core_mode_ref]}
+
+        def populate_defs(core_schema: CoreSchema, json_schema: JsonSchemaValue) -> JsonSchemaValue:
+            if 'ref' in core_schema:
+                core_ref = CoreRef(core_schema['ref'])  # type: ignore[typeddict-item]
+                defs_ref, ref_json_schema = self.get_cache_defs_ref_schema(core_ref)
+                json_ref = JsonRef(ref_json_schema['$ref'])
+                # Replace the schema if it's not a reference to itself
+                # What we want to avoid is having the def be just a ref to itself
+                # which is what would happen if we blindly assigned any
+                if json_schema.get('$ref', None) != json_ref:
+                    self.definitions[defs_ref] = json_schema
+                    self._core_defs_invalid_for_json_schema.pop(defs_ref, None)
+                json_schema = ref_json_schema
+            return json_schema
+
+        def handler_func(schema_or_field: CoreSchemaOrField) -> JsonSchemaValue:
+            """Generate a JSON schema based on the input schema.
+
+            Args:
+                schema_or_field: The core schema to generate a JSON schema from.
+
+            Returns:
+                The generated JSON schema.
+
+            Raises:
+                TypeError: If an unexpected schema type is encountered.
+            """
+            # Generate the core-schema-type-specific bits of the schema generation:
+            json_schema: JsonSchemaValue | None = None
+            if self.mode == 'serialization' and 'serialization' in schema_or_field:
+                # In this case, we skip the JSON Schema generation of the schema
+                # and use the `'serialization'` schema instead (canonical example:
+                # `Annotated[int, PlainSerializer(str)]`).
+                ser_schema = schema_or_field['serialization']  # type: ignore
+                json_schema = self.ser_schema(ser_schema)
+
+                # It might be that the 'serialization'` is skipped depending on `when_used`.
+                # This is only relevant for `nullable` schemas though, so we special case here.
+                if (
+                    json_schema is not None
+                    and ser_schema.get('when_used') in ('unless-none', 'json-unless-none')
+                    and schema_or_field['type'] == 'nullable'
+                ):
+                    json_schema = self.get_union_of_schemas([{'type': 'null'}, json_schema])
+            if json_schema is None:
+                if _core_utils.is_core_schema(schema_or_field) or _core_utils.is_core_schema_field(schema_or_field):
+                    generate_for_schema_type = self._schema_type_to_method[schema_or_field['type']]
+                    json_schema = generate_for_schema_type(schema_or_field)
+                else:
+                    raise TypeError(f'Unexpected schema type: schema={schema_or_field}')
+            return json_schema
+
+        current_handler = _schema_generation_shared.GenerateJsonSchemaHandler(self, handler_func)
+
+        metadata = cast(_core_metadata.CoreMetadata, schema.get('metadata', {}))
+
+        # TODO: I dislike that we have to wrap these basic dict updates in callables, is there any way around this?
+
+        if js_updates := metadata.get('pydantic_js_updates'):
+
+            def js_updates_handler_func(
+                schema_or_field: CoreSchemaOrField,
+                current_handler: GetJsonSchemaHandler = current_handler,
+            ) -> JsonSchemaValue:
+                json_schema = {**current_handler(schema_or_field), **js_updates}
+                return json_schema
+
+            current_handler = _schema_generation_shared.GenerateJsonSchemaHandler(self, js_updates_handler_func)
+
+        if js_extra := metadata.get('pydantic_js_extra'):
+
+            def js_extra_handler_func(
+                schema_or_field: CoreSchemaOrField,
+                current_handler: GetJsonSchemaHandler = current_handler,
+            ) -> JsonSchemaValue:
+                json_schema = current_handler(schema_or_field)
+                if isinstance(js_extra, dict):
+                    json_schema.update(to_jsonable_python(js_extra))
+                elif callable(js_extra):
+                    # similar to typing issue in _update_class_schema when we're working with callable js extra
+                    js_extra(json_schema)  # type: ignore
+                return json_schema
+
+            current_handler = _schema_generation_shared.GenerateJsonSchemaHandler(self, js_extra_handler_func)
+
+        for js_modify_function in metadata.get('pydantic_js_functions', ()):
+
+            def new_handler_func(
+                schema_or_field: CoreSchemaOrField,
+                current_handler: GetJsonSchemaHandler = current_handler,
+                js_modify_function: GetJsonSchemaFunction = js_modify_function,
+            ) -> JsonSchemaValue:
+                json_schema = js_modify_function(schema_or_field, current_handler)
+                if _core_utils.is_core_schema(schema_or_field):
+                    json_schema = populate_defs(schema_or_field, json_schema)
+                original_schema = current_handler.resolve_ref_schema(json_schema)
+                ref = json_schema.pop('$ref', None)
+                if ref and json_schema:
+                    original_schema.update(json_schema)
+                return original_schema
+
+            current_handler = _schema_generation_shared.GenerateJsonSchemaHandler(self, new_handler_func)
+
+        for js_modify_function in metadata.get('pydantic_js_annotation_functions', ()):
+
+            def new_handler_func(
+                schema_or_field: CoreSchemaOrField,
+                current_handler: GetJsonSchemaHandler = current_handler,
+                js_modify_function: GetJsonSchemaFunction = js_modify_function,
+            ) -> JsonSchemaValue:
+                return js_modify_function(schema_or_field, current_handler)
+
+            current_handler = _schema_generation_shared.GenerateJsonSchemaHandler(self, new_handler_func)
+
+        json_schema = current_handler(schema)
+        if _core_utils.is_core_schema(schema):
+            json_schema = populate_defs(schema, json_schema)
+        return json_schema
+
+    def sort(self, value: JsonSchemaValue, parent_key: str | None = None) -> JsonSchemaValue:
+        """Override this method to customize the sorting of the JSON schema (e.g., don't sort at all, sort all keys unconditionally, etc.)
+
+        By default, alphabetically sort the keys in the JSON schema, skipping the 'properties' and 'default' keys to preserve field definition order.
+        This sort is recursive, so it will sort all nested dictionaries as well.
+        """
+        sorted_dict: dict[str, JsonSchemaValue] = {}
+        keys = value.keys()
+        if parent_key not in ('properties', 'default'):
+            keys = sorted(keys)
+        for key in keys:
+            sorted_dict[key] = self._sort_recursive(value[key], parent_key=key)
+        return sorted_dict
+
+    def _sort_recursive(self, value: Any, parent_key: str | None = None) -> Any:
+        """Recursively sort a JSON schema value."""
+        if isinstance(value, dict):
+            sorted_dict: dict[str, JsonSchemaValue] = {}
+            keys = value.keys()
+            if parent_key not in ('properties', 'default'):
+                keys = sorted(keys)
+            for key in keys:
+                sorted_dict[key] = self._sort_recursive(value[key], parent_key=key)
+            return sorted_dict
+        elif isinstance(value, list):
+            sorted_list: list[JsonSchemaValue] = [self._sort_recursive(item, parent_key) for item in value]
+            return sorted_list
+        else:
+            return value
+
+    # ### Schema generation methods
+
+    def invalid_schema(self, schema: core_schema.InvalidSchema) -> JsonSchemaValue:
+        """Placeholder - should never be called."""
+
+        raise RuntimeError('Cannot generate schema for invalid_schema. This is a bug! Please report it.')
+
+    def any_schema(self, schema: core_schema.AnySchema) -> JsonSchemaValue:
+        """Generates a JSON schema that matches any value.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        return {}
+
+    def none_schema(self, schema: core_schema.NoneSchema) -> JsonSchemaValue:
+        """Generates a JSON schema that matches `None`.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        return {'type': 'null'}
+
+    def bool_schema(self, schema: core_schema.BoolSchema) -> JsonSchemaValue:
+        """Generates a JSON schema that matches a bool value.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        return {'type': 'boolean'}
+
+    def int_schema(self, schema: core_schema.IntSchema) -> JsonSchemaValue:
+        """Generates a JSON schema that matches an int value.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        json_schema: dict[str, Any] = {'type': 'integer'}
+        self.update_with_validations(json_schema, schema, self.ValidationsMapping.numeric)
+        json_schema = {k: v for k, v in json_schema.items() if v not in {math.inf, -math.inf}}
+        return json_schema
+
+    def float_schema(self, schema: core_schema.FloatSchema) -> JsonSchemaValue:
+        """Generates a JSON schema that matches a float value.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        json_schema: dict[str, Any] = {'type': 'number'}
+        self.update_with_validations(json_schema, schema, self.ValidationsMapping.numeric)
+        json_schema = {k: v for k, v in json_schema.items() if v not in {math.inf, -math.inf}}
+        return json_schema
+
+    def decimal_schema(self, schema: core_schema.DecimalSchema) -> JsonSchemaValue:
+        """Generates a JSON schema that matches a decimal value.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+
+        def get_decimal_pattern(schema: core_schema.DecimalSchema) -> str:
+            max_digits = schema.get('max_digits')
+            decimal_places = schema.get('decimal_places')
+
+            pattern = (
+                r'^(?!^[-+.]*$)[+-]?0*'  # check it is not empty string and not one or sequence of ".+-" characters.
+            )
+
+            # Case 1: Both max_digits and decimal_places are set
+            if max_digits is not None and decimal_places is not None:
+                integer_places = max(0, max_digits - decimal_places)
+                pattern += (
+                    rf'(?:'
+                    rf'\d{{0,{integer_places}}}'
+                    rf'|'
+                    rf'(?=[\d.]{{1,{max_digits + 1}}}0*$)'
+                    rf'\d{{0,{integer_places}}}\.\d{{0,{decimal_places}}}0*$'
+                    rf')'
+                )
+
+            # Case 2: Only max_digits is set
+            elif max_digits is not None and decimal_places is None:
+                pattern += (
+                    rf'(?:'
+                    rf'\d{{0,{max_digits}}}'
+                    rf'|'
+                    rf'(?=[\d.]{{1,{max_digits + 1}}}0*$)'
+                    rf'\d*\.\d*0*$'
+                    rf')'
+                )
+
+            # Case 3: Only decimal_places is set
+            elif max_digits is None and decimal_places is not None:
+                pattern += rf'\d*\.?\d{{0,{decimal_places}}}0*$'
+
+            # Case 4: Both are None (no restrictions)
+            else:
+                pattern += r'\d*\.?\d*$'  # look for arbitrary integer or decimal
+
+            return pattern
+
+        json_schema = self.str_schema(core_schema.str_schema(pattern=get_decimal_pattern(schema)))
+        if self.mode == 'validation':
+            multiple_of = schema.get('multiple_of')
+            le = schema.get('le')
+            ge = schema.get('ge')
+            lt = schema.get('lt')
+            gt = schema.get('gt')
+            json_schema = {
+                'anyOf': [
+                    self.float_schema(
+                        core_schema.float_schema(
+                            allow_inf_nan=schema.get('allow_inf_nan'),
+                            multiple_of=None if multiple_of is None else float(multiple_of),
+                            le=None if le is None else float(le),
+                            ge=None if ge is None else float(ge),
+                            lt=None if lt is None else float(lt),
+                            gt=None if gt is None else float(gt),
+                        )
+                    ),
+                    json_schema,
+                ],
+            }
+        return json_schema
+
+    def str_schema(self, schema: core_schema.StringSchema) -> JsonSchemaValue:
+        """Generates a JSON schema that matches a string value.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        json_schema = {'type': 'string'}
+        self.update_with_validations(json_schema, schema, self.ValidationsMapping.string)
+        if isinstance(json_schema.get('pattern'), Pattern):
+            # TODO: should we add regex flags to the pattern?
+            json_schema['pattern'] = json_schema.get('pattern').pattern  # type: ignore
+        return json_schema
+
+    def bytes_schema(self, schema: core_schema.BytesSchema) -> JsonSchemaValue:
+        """Generates a JSON schema that matches a bytes value.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        json_schema = {'type': 'string', 'format': 'base64url' if self._config.ser_json_bytes == 'base64' else 'binary'}
+        self.update_with_validations(json_schema, schema, self.ValidationsMapping.bytes)
+        return json_schema
+
+    def date_schema(self, schema: core_schema.DateSchema) -> JsonSchemaValue:
+        """Generates a JSON schema that matches a date value.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        return {'type': 'string', 'format': 'date'}
+
+    def time_schema(self, schema: core_schema.TimeSchema) -> JsonSchemaValue:
+        """Generates a JSON schema that matches a time value.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        return {'type': 'string', 'format': 'time'}
+
+    def datetime_schema(self, schema: core_schema.DatetimeSchema) -> JsonSchemaValue:
+        """Generates a JSON schema that matches a datetime value.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        return {'type': 'string', 'format': 'date-time'}
+
+    def timedelta_schema(self, schema: core_schema.TimedeltaSchema) -> JsonSchemaValue:
+        """Generates a JSON schema that matches a timedelta value.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        if self._config.ser_json_timedelta == 'float':
+            return {'type': 'number'}
+        return {'type': 'string', 'format': 'duration'}
+
+    def literal_schema(self, schema: core_schema.LiteralSchema) -> JsonSchemaValue:
+        """Generates a JSON schema that matches a literal value.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        expected = [to_jsonable_python(v.value if isinstance(v, Enum) else v) for v in schema['expected']]
+
+        result: dict[str, Any] = {}
+        if len(expected) == 1:
+            result['const'] = expected[0]
+        else:
+            result['enum'] = expected
+
+        types = {type(e) for e in expected}
+        if types == {str}:
+            result['type'] = 'string'
+        elif types == {int}:
+            result['type'] = 'integer'
+        elif types == {float}:
+            result['type'] = 'number'
+        elif types == {bool}:
+            result['type'] = 'boolean'
+        elif types == {list}:
+            result['type'] = 'array'
+        elif types == {type(None)}:
+            result['type'] = 'null'
+        return result
+
+    def missing_sentinel_schema(self, schema: core_schema.MissingSentinelSchema) -> JsonSchemaValue:
+        """Generates a JSON schema that matches the `MISSING` sentinel value.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        raise PydanticOmit
+
+    def enum_schema(self, schema: core_schema.EnumSchema) -> JsonSchemaValue:
+        """Generates a JSON schema that matches an Enum value.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        enum_type = schema['cls']
+        description = None if not enum_type.__doc__ else inspect.cleandoc(enum_type.__doc__)
+        if (
+            description == 'An enumeration.'
+        ):  # This is the default value provided by enum.EnumMeta.__new__; don't use it
+            description = None
+        result: dict[str, Any] = {'title': enum_type.__name__, 'description': description}
+        result = {k: v for k, v in result.items() if v is not None}
+
+        expected = [to_jsonable_python(v.value) for v in schema['members']]
+
+        result['enum'] = expected
+
+        types = {type(e) for e in expected}
+        if isinstance(enum_type, str) or types == {str}:
+            result['type'] = 'string'
+        elif isinstance(enum_type, int) or types == {int}:
+            result['type'] = 'integer'
+        elif isinstance(enum_type, float) or types == {float}:
+            result['type'] = 'number'
+        elif types == {bool}:
+            result['type'] = 'boolean'
+        elif types == {list}:
+            result['type'] = 'array'
+
+        return result
+
+    def is_instance_schema(self, schema: core_schema.IsInstanceSchema) -> JsonSchemaValue:
+        """Handles JSON schema generation for a core schema that checks if a value is an instance of a class.
+
+        Unless overridden in a subclass, this raises an error.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        return self.handle_invalid_for_json_schema(schema, f'core_schema.IsInstanceSchema ({schema["cls"]})')
+
+    def is_subclass_schema(self, schema: core_schema.IsSubclassSchema) -> JsonSchemaValue:
+        """Handles JSON schema generation for a core schema that checks if a value is a subclass of a class.
+
+        For backwards compatibility with v1, this does not raise an error, but can be overridden to change this.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        # Note: This is for compatibility with V1; you can override if you want different behavior.
+        return {}
+
+    def callable_schema(self, schema: core_schema.CallableSchema) -> JsonSchemaValue:
+        """Generates a JSON schema that matches a callable value.
+
+        Unless overridden in a subclass, this raises an error.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        return self.handle_invalid_for_json_schema(schema, 'core_schema.CallableSchema')
+
+    def list_schema(self, schema: core_schema.ListSchema) -> JsonSchemaValue:
+        """Returns a schema that matches a list schema.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        items_schema = {} if 'items_schema' not in schema else self.generate_inner(schema['items_schema'])
+        json_schema = {'type': 'array', 'items': items_schema}
+        self.update_with_validations(json_schema, schema, self.ValidationsMapping.array)
+        return json_schema
+
+    @deprecated('`tuple_positional_schema` is deprecated. Use `tuple_schema` instead.', category=None)
+    @final
+    def tuple_positional_schema(self, schema: core_schema.TupleSchema) -> JsonSchemaValue:
+        """Replaced by `tuple_schema`."""
+        warnings.warn(
+            '`tuple_positional_schema` is deprecated. Use `tuple_schema` instead.',
+            PydanticDeprecatedSince26,
+            stacklevel=2,
+        )
+        return self.tuple_schema(schema)
+
+    @deprecated('`tuple_variable_schema` is deprecated. Use `tuple_schema` instead.', category=None)
+    @final
+    def tuple_variable_schema(self, schema: core_schema.TupleSchema) -> JsonSchemaValue:
+        """Replaced by `tuple_schema`."""
+        warnings.warn(
+            '`tuple_variable_schema` is deprecated. Use `tuple_schema` instead.',
+            PydanticDeprecatedSince26,
+            stacklevel=2,
+        )
+        return self.tuple_schema(schema)
+
+    def tuple_schema(self, schema: core_schema.TupleSchema) -> JsonSchemaValue:
+        """Generates a JSON schema that matches a tuple schema e.g. `tuple[int,
+        str, bool]` or `tuple[int, ...]`.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        json_schema: JsonSchemaValue = {'type': 'array'}
+        if 'variadic_item_index' in schema:
+            variadic_item_index = schema['variadic_item_index']
+            if variadic_item_index > 0:
+                json_schema['minItems'] = variadic_item_index
+                json_schema['prefixItems'] = [
+                    self.generate_inner(item) for item in schema['items_schema'][:variadic_item_index]
+                ]
+            if variadic_item_index + 1 == len(schema['items_schema']):
+                # if the variadic item is the last item, then represent it faithfully
+                json_schema['items'] = self.generate_inner(schema['items_schema'][variadic_item_index])
+            else:
+                # otherwise, 'items' represents the schema for the variadic
+                # item plus the suffix, so just allow anything for simplicity
+                # for now
+                json_schema['items'] = True
+        else:
+            prefixItems = [self.generate_inner(item) for item in schema['items_schema']]
+            if prefixItems:
+                json_schema['prefixItems'] = prefixItems
+            json_schema['minItems'] = len(prefixItems)
+            json_schema['maxItems'] = len(prefixItems)
+        self.update_with_validations(json_schema, schema, self.ValidationsMapping.array)
+        return json_schema
+
+    def set_schema(self, schema: core_schema.SetSchema) -> JsonSchemaValue:
+        """Generates a JSON schema that matches a set schema.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        return self._common_set_schema(schema)
+
+    def frozenset_schema(self, schema: core_schema.FrozenSetSchema) -> JsonSchemaValue:
+        """Generates a JSON schema that matches a frozenset schema.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        return self._common_set_schema(schema)
+
+    def _common_set_schema(self, schema: core_schema.SetSchema | core_schema.FrozenSetSchema) -> JsonSchemaValue:
+        items_schema = {} if 'items_schema' not in schema else self.generate_inner(schema['items_schema'])
+        json_schema = {'type': 'array', 'uniqueItems': True, 'items': items_schema}
+        self.update_with_validations(json_schema, schema, self.ValidationsMapping.array)
+        return json_schema
+
+    def generator_schema(self, schema: core_schema.GeneratorSchema) -> JsonSchemaValue:
+        """Returns a JSON schema that represents the provided GeneratorSchema.
+
+        Args:
+            schema: The schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        items_schema = {} if 'items_schema' not in schema else self.generate_inner(schema['items_schema'])
+        json_schema = {'type': 'array', 'items': items_schema}
+        self.update_with_validations(json_schema, schema, self.ValidationsMapping.array)
+        return json_schema
+
+    def dict_schema(self, schema: core_schema.DictSchema) -> JsonSchemaValue:
+        """Generates a JSON schema that matches a dict schema.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        json_schema: JsonSchemaValue = {'type': 'object'}
+
+        keys_schema = self.generate_inner(schema['keys_schema']).copy() if 'keys_schema' in schema else {}
+        if '$ref' not in keys_schema:
+            keys_pattern = keys_schema.pop('pattern', None)
+            # Don't give a title to patternProperties/propertyNames:
+            keys_schema.pop('title', None)
+        else:
+            # Here, we assume that if the keys schema is a definition reference,
+            # it can't be a simple string core schema (and thus no pattern can exist).
+            # However, this is only in practice (in theory, a definition reference core
+            # schema could be generated for a simple string schema).
+            # Note that we avoid calling `self.resolve_ref_schema`, as it might not exist yet.
+            keys_pattern = None
+
+        values_schema = self.generate_inner(schema['values_schema']).copy() if 'values_schema' in schema else {}
+        # don't give a title to additionalProperties:
+        values_schema.pop('title', None)
+
+        if values_schema or keys_pattern is not None:
+            if keys_pattern is None:
+                json_schema['additionalProperties'] = values_schema
+            else:
+                json_schema['patternProperties'] = {keys_pattern: values_schema}
+        else:  # for `dict[str, Any]`, we allow any key and any value, since `str` is the default key type
+            json_schema['additionalProperties'] = True
+
+        if (
+            # The len check indicates that constraints are probably present:
+            (keys_schema.get('type') == 'string' and len(keys_schema) > 1)
+            # If this is a definition reference schema, it most likely has constraints:
+            or '$ref' in keys_schema
+        ):
+            keys_schema.pop('type', None)
+            json_schema['propertyNames'] = keys_schema
+
+        self.update_with_validations(json_schema, schema, self.ValidationsMapping.object)
+        return json_schema
+
+    def function_before_schema(self, schema: core_schema.BeforeValidatorFunctionSchema) -> JsonSchemaValue:
+        """Generates a JSON schema that matches a function-before schema.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        if self.mode == 'validation' and (input_schema := schema.get('json_schema_input_schema')):
+            return self.generate_inner(input_schema)
+
+        return self.generate_inner(schema['schema'])
+
+    def function_after_schema(self, schema: core_schema.AfterValidatorFunctionSchema) -> JsonSchemaValue:
+        """Generates a JSON schema that matches a function-after schema.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        return self.generate_inner(schema['schema'])
+
+    def function_plain_schema(self, schema: core_schema.PlainValidatorFunctionSchema) -> JsonSchemaValue:
+        """Generates a JSON schema that matches a function-plain schema.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        if self.mode == 'validation' and (input_schema := schema.get('json_schema_input_schema')):
+            return self.generate_inner(input_schema)
+
+        return self.handle_invalid_for_json_schema(
+            schema, f'core_schema.PlainValidatorFunctionSchema ({schema["function"]})'
+        )
+
+    def function_wrap_schema(self, schema: core_schema.WrapValidatorFunctionSchema) -> JsonSchemaValue:
+        """Generates a JSON schema that matches a function-wrap schema.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        if self.mode == 'validation' and (input_schema := schema.get('json_schema_input_schema')):
+            return self.generate_inner(input_schema)
+
+        return self.generate_inner(schema['schema'])
+
+    def default_schema(self, schema: core_schema.WithDefaultSchema) -> JsonSchemaValue:
+        """Generates a JSON schema that matches a schema with a default value.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        json_schema = self.generate_inner(schema['schema'])
+
+        default = self.get_default_value(schema)
+        if default is NoDefault or default is MISSING:
+            return json_schema
+
+        # we reflect the application of custom plain, no-info serializers to defaults for
+        # JSON Schemas viewed in serialization mode:
+        # TODO: improvements along with https://github.com/pydantic/pydantic/issues/8208
+        if self.mode == 'serialization':
+            # `_get_ser_schema_for_default_value()` is used to unpack potentially nested validator schemas:
+            ser_schema = _get_ser_schema_for_default_value(schema['schema'])
+            if (
+                ser_schema is not None
+                and (ser_func := ser_schema.get('function'))
+                and not (default is None and ser_schema.get('when_used') in ('unless-none', 'json-unless-none'))
+            ):
+                try:
+                    default = ser_func(default)  # type: ignore
+                except Exception:
+                    # It might be that the provided default needs to be validated (read: parsed) first
+                    # (assuming `validate_default` is enabled). However, we can't perform
+                    # such validation during JSON Schema generation so we don't support
+                    # this pattern for now.
+                    # (One example is when using `foo: ByteSize = '1MB'`, which validates and
+                    # serializes as an int. In this case, `ser_func` is `int` and `int('1MB')` fails).
+                    self.emit_warning(
+                        'non-serializable-default',
+                        f'Unable to serialize value {default!r} with the plain serializer; excluding default from JSON schema',
+                    )
+                    return json_schema
+
+        try:
+            encoded_default = self.encode_default(default)
+        except pydantic_core.PydanticSerializationError:
+            self.emit_warning(
+                'non-serializable-default',
+                f'Default value {default} is not JSON serializable; excluding default from JSON schema',
+            )
+            # Return the inner schema, as though there was no default
+            return json_schema
+
+        json_schema['default'] = encoded_default
+        return json_schema
+
+    def get_default_value(self, schema: core_schema.WithDefaultSchema) -> Any:
+        """Get the default value to be used when generating a JSON Schema for a core schema with a default.
+
+        The default implementation is to use the statically defined default value. This method can be overridden
+        if you want to make use of the default factory.
+
+        Args:
+            schema: The `'with-default'` core schema.
+
+        Returns:
+            The default value to use, or [`NoDefault`][pydantic.json_schema.NoDefault] if no default
+                value is available.
+        """
+        return schema.get('default', NoDefault)
+
+    def nullable_schema(self, schema: core_schema.NullableSchema) -> JsonSchemaValue:
+        """Generates a JSON schema that matches a schema that allows null values.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        null_schema = {'type': 'null'}
+        inner_json_schema = self.generate_inner(schema['schema'])
+
+        if inner_json_schema == null_schema:
+            return null_schema
+        else:
+            return self.get_union_of_schemas([inner_json_schema, null_schema])
+
+    def union_schema(self, schema: core_schema.UnionSchema) -> JsonSchemaValue:
+        """Generates a JSON schema that matches a schema that allows values matching any of the given schemas.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        generated: list[JsonSchemaValue] = []
+
+        choices = schema['choices']
+        for choice in choices:
+            # choice will be a tuple if an explicit label was provided
+            choice_schema = choice[0] if isinstance(choice, tuple) else choice
+            try:
+                generated.append(self.generate_inner(choice_schema))
+            except PydanticOmit:
+                continue
+            except PydanticInvalidForJsonSchema as exc:
+                self.emit_warning('skipped-choice', exc.message)
+        if len(generated) == 1:
+            return generated[0]
+        return self.get_union_of_schemas(generated)
+
+    def get_union_of_schemas(self, schemas: list[JsonSchemaValue]) -> JsonSchemaValue:
+        """Returns the JSON Schema representation for the union of the provided JSON Schemas.
+
+        The result depends on the configured `'union_format'`.
+
+        Args:
+            schemas: The list of JSON Schemas to be included in the union.
+
+        Returns:
+            The JSON Schema representing the union of schemas.
+        """
+        if self.union_format == 'primitive_type_array':
+            types: list[str] = []
+            for schema in schemas:
+                schema_types: list[str] | str | None = schema.get('type')
+                if schema_types is None:
+                    # No type, meaning it can be a ref or an empty schema.
+                    break
+                if not isinstance(schema_types, list):
+                    schema_types = [schema_types]
+                if not all(t in _PRIMITIVE_JSON_SCHEMA_TYPES for t in schema_types):
+                    break
+                if len(schema) != 1:
+                    # We only want to include types that don't have any constraints. For instance,
+                    # if `schemas = [{'type': 'string', 'maxLength': 3}, {'type': 'string', 'minLength': 5}]`,
+                    # we don't want to produce `{'type': 'string', 'maxLength': 3, 'minLength': 5}`.
+                    # Same if we have some metadata (e.g. `title`) on a specific union member, we want to preserve it.
+                    break
+
+                types.extend(schema_types)
+            else:
+                # If we got there, all the schemas where valid to be used with the `'primitive_type_array` format
+                return {'type': list(dict.fromkeys(types))}
+
+        return self.get_flattened_anyof(schemas)
+
+    def tagged_union_schema(self, schema: core_schema.TaggedUnionSchema) -> JsonSchemaValue:
+        """Generates a JSON schema that matches a schema that allows values matching any of the given schemas, where
+        the schemas are tagged with a discriminator field that indicates which schema should be used to validate
+        the value.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        generated: dict[str, JsonSchemaValue] = {}
+        for k, v in schema['choices'].items():
+            if isinstance(k, Enum):
+                k = k.value
+            try:
+                # Use str(k) since keys must be strings for json; while not technically correct,
+                # it's the closest that can be represented in valid JSON
+                generated[str(k)] = self.generate_inner(v).copy()
+            except PydanticOmit:
+                continue
+            except PydanticInvalidForJsonSchema as exc:
+                self.emit_warning('skipped-choice', exc.message)
+
+        one_of_choices = _deduplicate_schemas(generated.values())
+        json_schema: JsonSchemaValue = {'oneOf': one_of_choices}
+
+        # This reflects the v1 behavior; TODO: we should make it possible to exclude OpenAPI stuff from the JSON schema
+        openapi_discriminator = self._extract_discriminator(schema, one_of_choices)
+        if openapi_discriminator is not None:
+            json_schema['discriminator'] = {
+                'propertyName': openapi_discriminator,
+                'mapping': {k: v.get('$ref', v) for k, v in generated.items()},
+            }
+
+        return json_schema
+
+    def _extract_discriminator(
+        self, schema: core_schema.TaggedUnionSchema, one_of_choices: list[JsonDict]
+    ) -> str | None:
+        """Extract a compatible OpenAPI discriminator from the schema and one_of choices that end up in the final
+        schema."""
+        openapi_discriminator: str | None = None
+
+        if isinstance(schema['discriminator'], str):
+            return schema['discriminator']
+
+        if isinstance(schema['discriminator'], list):
+            # If the discriminator is a single item list containing a string, that is equivalent to the string case
+            if len(schema['discriminator']) == 1 and isinstance(schema['discriminator'][0], str):
+                return schema['discriminator'][0]
+            # When an alias is used that is different from the field name, the discriminator will be a list of single
+            # str lists, one for the attribute and one for the actual alias. The logic here will work even if there is
+            # more than one possible attribute, and looks for whether a single alias choice is present as a documented
+            # property on all choices. If so, that property will be used as the OpenAPI discriminator.
+            for alias_path in schema['discriminator']:
+                if not isinstance(alias_path, list):
+                    break  # this means that the discriminator is not a list of alias paths
+                if len(alias_path) != 1:
+                    continue  # this means that the "alias" does not represent a single field
+                alias = alias_path[0]
+                if not isinstance(alias, str):
+                    continue  # this means that the "alias" does not represent a field
+                alias_is_present_on_all_choices = True
+                for choice in one_of_choices:
+                    try:
+                        choice = self.resolve_ref_schema(choice)
+                    except RuntimeError as exc:
+                        # TODO: fixme - this is a workaround for the fact that we can't always resolve refs
+                        # for tagged union choices at this point in the schema gen process, we might need to do
+                        # another pass at the end like we do for core schemas
+                        self.emit_warning('skipped-discriminator', str(exc))
+                        choice = {}
+                    properties = choice.get('properties', {})
+                    if not isinstance(properties, dict) or alias not in properties:
+                        alias_is_present_on_all_choices = False
+                        break
+                if alias_is_present_on_all_choices:
+                    openapi_discriminator = alias
+                    break
+        return openapi_discriminator
+
+    def chain_schema(self, schema: core_schema.ChainSchema) -> JsonSchemaValue:
+        """Generates a JSON schema that matches a core_schema.ChainSchema.
+
+        When generating a schema for validation, we return the validation JSON schema for the first step in the chain.
+        For serialization, we return the serialization JSON schema for the last step in the chain.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        step_index = 0 if self.mode == 'validation' else -1  # use first step for validation, last for serialization
+        return self.generate_inner(schema['steps'][step_index])
+
+    def lax_or_strict_schema(self, schema: core_schema.LaxOrStrictSchema) -> JsonSchemaValue:
+        """Generates a JSON schema that matches a schema that allows values matching either the lax schema or the
+        strict schema.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        # TODO: Need to read the default value off of model config or whatever
+        use_strict = schema.get('strict', False)  # TODO: replace this default False
+        # If your JSON schema fails to generate it is probably
+        # because one of the following two branches failed.
+        if use_strict:
+            return self.generate_inner(schema['strict_schema'])
+        else:
+            return self.generate_inner(schema['lax_schema'])
+
+    def json_or_python_schema(self, schema: core_schema.JsonOrPythonSchema) -> JsonSchemaValue:
+        """Generates a JSON schema that matches a schema that allows values matching either the JSON schema or the
+        Python schema.
+
+        The JSON schema is used instead of the Python schema. If you want to use the Python schema, you should override
+        this method.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        return self.generate_inner(schema['json_schema'])
+
+    def typed_dict_schema(self, schema: core_schema.TypedDictSchema) -> JsonSchemaValue:
+        """Generates a JSON schema that matches a schema that defines a typed dict.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        total = schema.get('total', True)
+        named_required_fields: list[tuple[str, bool, CoreSchemaField]] = [
+            (name, self.field_is_required(field, total), field)
+            for name, field in schema['fields'].items()
+            if self.field_is_present(field)
+        ]
+        if self.mode == 'serialization':
+            named_required_fields.extend(self._name_required_computed_fields(schema.get('computed_fields', [])))
+        cls = schema.get('cls')
+        config = _get_typed_dict_config(cls)
+        with self._config_wrapper_stack.push(config):
+            json_schema = self._named_required_fields_schema(named_required_fields)
+
+        # There's some duplication between `extra_behavior` and
+        # the config's `extra`/core config's `extra_fields_behavior`.
+        # However, it is common to manually create TypedDictSchemas,
+        # where you don't necessarily have a class.
+        # At runtime, `extra_behavior` takes priority over the config
+        # for validation, so follow the same for the JSON Schema:
+        if schema.get('extra_behavior') == 'forbid':
+            json_schema['additionalProperties'] = False
+        elif schema.get('extra_behavior') == 'allow':
+            if 'extras_schema' in schema and schema['extras_schema'] != {'type': 'any'}:
+                json_schema['additionalProperties'] = self.generate_inner(schema['extras_schema'])
+            else:
+                json_schema['additionalProperties'] = True
+
+        if cls is not None:
+            # `_update_class_schema()` will not override
+            # `additionalProperties` if already present:
+            self._update_class_schema(json_schema, cls, config)
+        elif 'additionalProperties' not in json_schema:
+            extra = schema.get('config', {}).get('extra_fields_behavior')
+            if extra == 'forbid':
+                json_schema['additionalProperties'] = False
+            elif extra == 'allow':
+                json_schema['additionalProperties'] = True
+
+        return json_schema
+
+    @staticmethod
+    def _name_required_computed_fields(
+        computed_fields: list[ComputedField],
+    ) -> list[tuple[str, bool, core_schema.ComputedField]]:
+        return [(field['property_name'], True, field) for field in computed_fields]
+
+    def _named_required_fields_schema(
+        self, named_required_fields: Sequence[tuple[str, bool, CoreSchemaField]]
+    ) -> JsonSchemaValue:
+        properties: dict[str, JsonSchemaValue] = {}
+        required_fields: list[str] = []
+        for name, required, field in named_required_fields:
+            if self.by_alias:
+                name = self._get_alias_name(field, name)
+            try:
+                field_json_schema = self.generate_inner(field).copy()
+            except PydanticOmit:
+                continue
+            if 'title' not in field_json_schema and self.field_title_should_be_set(field):
+                title = self.get_title_from_name(name)
+                field_json_schema['title'] = title
+            field_json_schema = self.handle_ref_overrides(field_json_schema)
+            properties[name] = field_json_schema
+            if required:
+                required_fields.append(name)
+
+        json_schema = {'type': 'object', 'properties': properties}
+        if required_fields:
+            json_schema['required'] = required_fields
+        return json_schema
+
+    def _get_alias_name(self, field: CoreSchemaField, name: str) -> str:
+        if field['type'] == 'computed-field':
+            alias: Any = field.get('alias', name)
+        elif self.mode == 'validation':
+            alias = field.get('validation_alias', name)
+        else:
+            alias = field.get('serialization_alias', name)
+        if isinstance(alias, str):
+            name = alias
+        elif isinstance(alias, list):
+            alias = cast('list[str] | str', alias)
+            for path in alias:
+                if isinstance(path, list) and len(path) == 1 and isinstance(path[0], str):
+                    # Use the first valid single-item string path; the code that constructs the alias array
+                    # should ensure the first such item is what belongs in the JSON schema
+                    name = path[0]
+                    break
+        else:
+            assert_never(alias)
+        return name
+
+    def typed_dict_field_schema(self, schema: core_schema.TypedDictField) -> JsonSchemaValue:
+        """Generates a JSON schema that matches a schema that defines a typed dict field.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        return self.generate_inner(schema['schema'])
+
+    def dataclass_field_schema(self, schema: core_schema.DataclassField) -> JsonSchemaValue:
+        """Generates a JSON schema that matches a schema that defines a dataclass field.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        return self.generate_inner(schema['schema'])
+
+    def model_field_schema(self, schema: core_schema.ModelField) -> JsonSchemaValue:
+        """Generates a JSON schema that matches a schema that defines a model field.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        return self.generate_inner(schema['schema'])
+
+    def computed_field_schema(self, schema: core_schema.ComputedField) -> JsonSchemaValue:
+        """Generates a JSON schema that matches a schema that defines a computed field.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        return self.generate_inner(schema['return_schema'])
+
+    def model_schema(self, schema: core_schema.ModelSchema) -> JsonSchemaValue:
+        """Generates a JSON schema that matches a schema that defines a model.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        # We do not use schema['model'].model_json_schema() here
+        # because it could lead to inconsistent refs handling, etc.
+        cls = cast('type[BaseModel]', schema['cls'])
+        config = cls.model_config
+
+        with self._config_wrapper_stack.push(config):
+            json_schema = self.generate_inner(schema['schema'])
+
+        self._update_class_schema(json_schema, cls, config)
+
+        return json_schema
+
+    def _update_class_schema(self, json_schema: JsonSchemaValue, cls: type[Any], config: ConfigDict) -> None:
+        """Update json_schema with the following, extracted from `config` and `cls`:
+
+        * title
+        * description
+        * additional properties
+        * json_schema_extra
+        * deprecated
+
+        Done in place, hence there's no return value as the original json_schema is mutated.
+        No ref resolving is involved here, as that's not appropriate for simple updates.
+        """
+        from .main import BaseModel
+        from .root_model import RootModel
+
+        if (config_title := config.get('title')) is not None:
+            json_schema.setdefault('title', config_title)
+        elif model_title_generator := config.get('model_title_generator'):
+            title = model_title_generator(cls)
+            if not isinstance(title, str):
+                raise TypeError(f'model_title_generator {model_title_generator} must return str, not {title.__class__}')
+            json_schema.setdefault('title', title)
+        if 'title' not in json_schema:
+            json_schema['title'] = cls.__name__
+
+        # BaseModel and dataclasses; don't use cls.__doc__ as it will contain the verbose class signature by default
+        docstring = None if cls is BaseModel or dataclasses.is_dataclass(cls) else cls.__doc__
+
+        if docstring:
+            json_schema.setdefault('description', inspect.cleandoc(docstring))
+        elif issubclass(cls, RootModel) and (root_description := cls.__pydantic_fields__['root'].description):
+            json_schema.setdefault('description', root_description)
+
+        extra = config.get('extra')
+        if 'additionalProperties' not in json_schema:  # This check is particularly important for `typed_dict_schema()`
+            if extra == 'allow':
+                json_schema['additionalProperties'] = True
+            elif extra == 'forbid':
+                json_schema['additionalProperties'] = False
+
+        json_schema_extra = config.get('json_schema_extra')
+        if issubclass(cls, BaseModel) and cls.__pydantic_root_model__:
+            root_json_schema_extra = cls.model_fields['root'].json_schema_extra
+            if json_schema_extra and root_json_schema_extra:
+                raise ValueError(
+                    '"model_config[\'json_schema_extra\']" and "Field.json_schema_extra" on "RootModel.root"'
+                    ' field must not be set simultaneously'
+                )
+            if root_json_schema_extra:
+                json_schema_extra = root_json_schema_extra
+
+        if isinstance(json_schema_extra, (staticmethod, classmethod)):
+            # In older versions of python, this is necessary to ensure staticmethod/classmethods are callable
+            json_schema_extra = json_schema_extra.__get__(cls)
+
+        if isinstance(json_schema_extra, dict):
+            json_schema.update(json_schema_extra)
+        elif callable(json_schema_extra):
+            # FIXME: why are there type ignores here? We support two signatures for json_schema_extra callables...
+            if len(inspect.signature(json_schema_extra).parameters) > 1:
+                json_schema_extra(json_schema, cls)  # type: ignore
+            else:
+                json_schema_extra(json_schema)  # type: ignore
+        elif json_schema_extra is not None:
+            raise ValueError(
+                f"model_config['json_schema_extra']={json_schema_extra} should be a dict, callable, or None"
+            )
+
+        if hasattr(cls, '__deprecated__'):
+            json_schema['deprecated'] = True
+
+    def resolve_ref_schema(self, json_schema: JsonSchemaValue) -> JsonSchemaValue:
+        """Resolve a JsonSchemaValue to the non-ref schema if it is a $ref schema.
+
+        Args:
+            json_schema: The schema to resolve.
+
+        Returns:
+            The resolved schema.
+
+        Raises:
+            RuntimeError: If the schema reference can't be found in definitions.
+        """
+        while '$ref' in json_schema:
+            ref = json_schema['$ref']
+            schema_to_update = self.get_schema_from_definitions(JsonRef(ref))
+            if schema_to_update is None:
+                raise RuntimeError(f'Cannot update undefined schema for $ref={ref}')
+            json_schema = schema_to_update
+        return json_schema
+
+    def model_fields_schema(self, schema: core_schema.ModelFieldsSchema) -> JsonSchemaValue:
+        """Generates a JSON schema that matches a schema that defines a model's fields.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        named_required_fields: list[tuple[str, bool, CoreSchemaField]] = [
+            (name, self.field_is_required(field, total=True), field)
+            for name, field in schema['fields'].items()
+            if self.field_is_present(field)
+        ]
+        if self.mode == 'serialization':
+            named_required_fields.extend(self._name_required_computed_fields(schema.get('computed_fields', [])))
+        json_schema = self._named_required_fields_schema(named_required_fields)
+        extras_schema = schema.get('extras_schema', None)
+        if extras_schema is not None:
+            schema_to_update = self.resolve_ref_schema(json_schema)
+            schema_to_update['additionalProperties'] = self.generate_inner(extras_schema)
+        return json_schema
+
+    def field_is_present(self, field: CoreSchemaField) -> bool:
+        """Whether the field should be included in the generated JSON schema.
+
+        Args:
+            field: The schema for the field itself.
+
+        Returns:
+            `True` if the field should be included in the generated JSON schema, `False` otherwise.
+        """
+        if self.mode == 'serialization':
+            # If you still want to include the field in the generated JSON schema,
+            # override this method and return True
+            return not field.get('serialization_exclude')
+        elif self.mode == 'validation':
+            return True
+        else:
+            assert_never(self.mode)
+
+    def field_is_required(
+        self,
+        field: core_schema.ModelField | core_schema.DataclassField | core_schema.TypedDictField,
+        total: bool,
+    ) -> bool:
+        """Whether the field should be marked as required in the generated JSON schema.
+        (Note that this is irrelevant if the field is not present in the JSON schema.).
+
+        Args:
+            field: The schema for the field itself.
+            total: Only applies to `TypedDictField`s.
+                Indicates if the `TypedDict` this field belongs to is total, in which case any fields that don't
+                explicitly specify `required=False` are required.
+
+        Returns:
+            `True` if the field should be marked as required in the generated JSON schema, `False` otherwise.
+        """
+        if field['type'] == 'typed-dict-field':
+            required = field.get('required', total)
+        else:
+            required = field['schema']['type'] != 'default'
+
+        if self.mode == 'serialization':
+            has_exclude_if = field.get('serialization_exclude_if') is not None
+            if self._config.json_schema_serialization_defaults_required:
+                return not has_exclude_if
+            else:
+                return required and not has_exclude_if
+        else:
+            return required
+
+    def dataclass_args_schema(self, schema: core_schema.DataclassArgsSchema) -> JsonSchemaValue:
+        """Generates a JSON schema that matches a schema that defines a dataclass's constructor arguments.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        named_required_fields: list[tuple[str, bool, CoreSchemaField]] = [
+            (field['name'], self.field_is_required(field, total=True), field)
+            for field in schema['fields']
+            if self.field_is_present(field)
+        ]
+        if self.mode == 'serialization':
+            named_required_fields.extend(self._name_required_computed_fields(schema.get('computed_fields', [])))
+        return self._named_required_fields_schema(named_required_fields)
+
+    def dataclass_schema(self, schema: core_schema.DataclassSchema) -> JsonSchemaValue:
+        """Generates a JSON schema that matches a schema that defines a dataclass.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        from ._internal._dataclasses import is_stdlib_dataclass
+
+        cls = schema['cls']
+        config: ConfigDict = getattr(cls, '__pydantic_config__', cast('ConfigDict', {}))
+
+        with self._config_wrapper_stack.push(config):
+            json_schema = self.generate_inner(schema['schema']).copy()
+
+        self._update_class_schema(json_schema, cls, config)
+
+        # Dataclass-specific handling of description
+        if is_stdlib_dataclass(cls):
+            # vanilla dataclass; don't use cls.__doc__ as it will contain the class signature by default
+            description = None
+        else:
+            description = None if cls.__doc__ is None else inspect.cleandoc(cls.__doc__)
+        if description:
+            json_schema['description'] = description
+
+        return json_schema
+
+    def arguments_schema(self, schema: core_schema.ArgumentsSchema) -> JsonSchemaValue:
+        """Generates a JSON schema that matches a schema that defines a function's arguments.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        prefer_positional = schema.get('metadata', {}).get('pydantic_js_prefer_positional_arguments')
+
+        arguments = schema['arguments_schema']
+        kw_only_arguments = [a for a in arguments if a.get('mode') == 'keyword_only']
+        kw_or_p_arguments = [a for a in arguments if a.get('mode') in {'positional_or_keyword', None}]
+        p_only_arguments = [a for a in arguments if a.get('mode') == 'positional_only']
+        var_args_schema = schema.get('var_args_schema')
+        var_kwargs_schema = schema.get('var_kwargs_schema')
+
+        if prefer_positional:
+            positional_possible = not kw_only_arguments and not var_kwargs_schema
+            if positional_possible:
+                return self.p_arguments_schema(p_only_arguments + kw_or_p_arguments, var_args_schema)
+
+        keyword_possible = not p_only_arguments and not var_args_schema
+        if keyword_possible:
+            return self.kw_arguments_schema(kw_or_p_arguments + kw_only_arguments, var_kwargs_schema)
+
+        if not prefer_positional:
+            positional_possible = not kw_only_arguments and not var_kwargs_schema
+            if positional_possible:
+                return self.p_arguments_schema(p_only_arguments + kw_or_p_arguments, var_args_schema)
+
+        raise PydanticInvalidForJsonSchema(
+            'Unable to generate JSON schema for arguments validator with positional-only and keyword-only arguments'
+        )
+
+    def kw_arguments_schema(
+        self, arguments: list[core_schema.ArgumentsParameter], var_kwargs_schema: CoreSchema | None
+    ) -> JsonSchemaValue:
+        """Generates a JSON schema that matches a schema that defines a function's keyword arguments.
+
+        Args:
+            arguments: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        properties: dict[str, JsonSchemaValue] = {}
+        required: list[str] = []
+        for argument in arguments:
+            name = self.get_argument_name(argument)
+            argument_schema = self.generate_inner(argument['schema']).copy()
+            if 'title' not in argument_schema and self.field_title_should_be_set(argument['schema']):
+                argument_schema['title'] = self.get_title_from_name(name)
+            properties[name] = argument_schema
+
+            if argument['schema']['type'] != 'default':
+                # This assumes that if the argument has a default value,
+                # the inner schema must be of type WithDefaultSchema.
+                # I believe this is true, but I am not 100% sure
+                required.append(name)
+
+        json_schema: JsonSchemaValue = {'type': 'object', 'properties': properties}
+        if required:
+            json_schema['required'] = required
+
+        if var_kwargs_schema:
+            additional_properties_schema = self.generate_inner(var_kwargs_schema)
+            if additional_properties_schema:
+                json_schema['additionalProperties'] = additional_properties_schema
+        else:
+            json_schema['additionalProperties'] = False
+        return json_schema
+
+    def p_arguments_schema(
+        self, arguments: list[core_schema.ArgumentsParameter], var_args_schema: CoreSchema | None
+    ) -> JsonSchemaValue:
+        """Generates a JSON schema that matches a schema that defines a function's positional arguments.
+
+        Args:
+            arguments: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        prefix_items: list[JsonSchemaValue] = []
+        min_items = 0
+
+        for argument in arguments:
+            name = self.get_argument_name(argument)
+
+            argument_schema = self.generate_inner(argument['schema']).copy()
+            if 'title' not in argument_schema and self.field_title_should_be_set(argument['schema']):
+                argument_schema['title'] = self.get_title_from_name(name)
+            prefix_items.append(argument_schema)
+
+            if argument['schema']['type'] != 'default':
+                # This assumes that if the argument has a default value,
+                # the inner schema must be of type WithDefaultSchema.
+                # I believe this is true, but I am not 100% sure
+                min_items += 1
+
+        json_schema: JsonSchemaValue = {'type': 'array'}
+        if prefix_items:
+            json_schema['prefixItems'] = prefix_items
+        if min_items:
+            json_schema['minItems'] = min_items
+
+        if var_args_schema:
+            items_schema = self.generate_inner(var_args_schema)
+            if items_schema:
+                json_schema['items'] = items_schema
+        else:
+            json_schema['maxItems'] = len(prefix_items)
+
+        return json_schema
+
+    def get_argument_name(self, argument: core_schema.ArgumentsParameter | core_schema.ArgumentsV3Parameter) -> str:
+        """Retrieves the name of an argument.
+
+        Args:
+            argument: The core schema.
+
+        Returns:
+            The name of the argument.
+        """
+        name = argument['name']
+        if self.by_alias:
+            alias = argument.get('alias')
+            if isinstance(alias, str):
+                name = alias
+            else:
+                pass  # might want to do something else?
+        return name
+
+    def arguments_v3_schema(self, schema: core_schema.ArgumentsV3Schema) -> JsonSchemaValue:
+        """Generates a JSON schema that matches a schema that defines a function's arguments.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        arguments = schema['arguments_schema']
+        properties: dict[str, JsonSchemaValue] = {}
+        required: list[str] = []
+        for argument in arguments:
+            mode = argument.get('mode', 'positional_or_keyword')
+            name = self.get_argument_name(argument)
+            argument_schema = self.generate_inner(argument['schema']).copy()
+            if mode == 'var_args':
+                argument_schema = {'type': 'array', 'items': argument_schema}
+            elif mode == 'var_kwargs_uniform':
+                argument_schema = {'type': 'object', 'additionalProperties': argument_schema}
+
+            argument_schema.setdefault('title', self.get_title_from_name(name))
+            properties[name] = argument_schema
+
+            if (
+                (mode == 'var_kwargs_unpacked_typed_dict' and 'required' in argument_schema)
+                or mode not in {'var_args', 'var_kwargs_uniform', 'var_kwargs_unpacked_typed_dict'}
+                and argument['schema']['type'] != 'default'
+            ):
+                # This assumes that if the argument has a default value,
+                # the inner schema must be of type WithDefaultSchema.
+                # I believe this is true, but I am not 100% sure
+                required.append(name)
+
+        json_schema: JsonSchemaValue = {'type': 'object', 'properties': properties}
+        if required:
+            json_schema['required'] = required
+        return json_schema
+
+    def call_schema(self, schema: core_schema.CallSchema) -> JsonSchemaValue:
+        """Generates a JSON schema that matches a schema that defines a function call.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        return self.generate_inner(schema['arguments_schema'])
+
+    def custom_error_schema(self, schema: core_schema.CustomErrorSchema) -> JsonSchemaValue:
+        """Generates a JSON schema that matches a schema that defines a custom error.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        return self.generate_inner(schema['schema'])
+
+    def json_schema(self, schema: core_schema.JsonSchema) -> JsonSchemaValue:
+        """Generates a JSON schema that matches a schema that defines a JSON object.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        content_core_schema = schema.get('schema') or core_schema.any_schema()
+        content_json_schema = self.generate_inner(content_core_schema)
+        if self.mode == 'validation':
+            return {'type': 'string', 'contentMediaType': 'application/json', 'contentSchema': content_json_schema}
+        else:
+            # self.mode == 'serialization'
+            return content_json_schema
+
+    def url_schema(self, schema: core_schema.UrlSchema) -> JsonSchemaValue:
+        """Generates a JSON schema that matches a schema that defines a URL.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        json_schema = {'type': 'string', 'format': 'uri', 'minLength': 1}
+        self.update_with_validations(json_schema, schema, self.ValidationsMapping.string)
+        return json_schema
+
+    def multi_host_url_schema(self, schema: core_schema.MultiHostUrlSchema) -> JsonSchemaValue:
+        """Generates a JSON schema that matches a schema that defines a URL that can be used with multiple hosts.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        # Note: 'multi-host-uri' is a custom/pydantic-specific format, not part of the JSON Schema spec
+        json_schema = {'type': 'string', 'format': 'multi-host-uri', 'minLength': 1}
+        self.update_with_validations(json_schema, schema, self.ValidationsMapping.string)
+        return json_schema
+
+    def uuid_schema(self, schema: core_schema.UuidSchema) -> JsonSchemaValue:
+        """Generates a JSON schema that matches a UUID.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        return {'type': 'string', 'format': 'uuid'}
+
+    def definitions_schema(self, schema: core_schema.DefinitionsSchema) -> JsonSchemaValue:
+        """Generates a JSON schema that matches a schema that defines a JSON object with definitions.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        for definition in schema['definitions']:
+            try:
+                self.generate_inner(definition)
+            except PydanticInvalidForJsonSchema as e:  # noqa: PERF203
+                core_ref: CoreRef = CoreRef(definition['ref'])  # type: ignore
+                self._core_defs_invalid_for_json_schema[self.get_defs_ref((core_ref, self.mode))] = e
+                continue
+        return self.generate_inner(schema['schema'])
+
+    def definition_ref_schema(self, schema: core_schema.DefinitionReferenceSchema) -> JsonSchemaValue:
+        """Generates a JSON schema that matches a schema that references a definition.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        core_ref = CoreRef(schema['schema_ref'])
+        _, ref_json_schema = self.get_cache_defs_ref_schema(core_ref)
+        return ref_json_schema
+
+    def ser_schema(
+        self, schema: core_schema.SerSchema | core_schema.IncExSeqSerSchema | core_schema.IncExDictSerSchema
+    ) -> JsonSchemaValue | None:
+        """Generates a JSON schema that matches a schema that defines a serialized object.
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        schema_type = schema['type']
+        if schema_type == 'function-plain' or schema_type == 'function-wrap':
+            # PlainSerializerFunctionSerSchema or WrapSerializerFunctionSerSchema
+            return_schema = schema.get('return_schema')
+            if return_schema is not None:
+                return self.generate_inner(return_schema)
+        elif schema_type == 'format' or schema_type == 'to-string':
+            # FormatSerSchema or ToStringSerSchema
+            return self.str_schema(core_schema.str_schema())
+        elif schema['type'] == 'model':
+            # ModelSerSchema
+            return self.generate_inner(schema['schema'])
+        return None
+
+    def complex_schema(self, schema: core_schema.ComplexSchema) -> JsonSchemaValue:
+        """Generates a JSON schema that matches a complex number.
+
+        JSON has no standard way to represent complex numbers. Complex number is not a numeric
+        type. Here we represent complex number as strings following the rule defined by Python.
+        For instance, '1+2j' is an accepted complex string. Details can be found in
+        [Python's `complex` documentation][complex].
+
+        Args:
+            schema: The core schema.
+
+        Returns:
+            The generated JSON schema.
+        """
+        return {'type': 'string'}
+
+    # ### Utility methods
+
+    def get_title_from_name(self, name: str) -> str:
+        """Retrieves a title from a name.
+
+        Args:
+            name: The name to retrieve a title from.
+
+        Returns:
+            The title.
+        """
+        return name.title().replace('_', ' ').strip()
+
+    def field_title_should_be_set(self, schema: CoreSchemaOrField) -> bool:
+        """Returns true if a field with the given schema should have a title set based on the field name.
+
+        Intuitively, we want this to return true for schemas that wouldn't otherwise provide their own title
+        (e.g., int, float, str), and false for those that would (e.g., BaseModel subclasses).
+
+        Args:
+            schema: The schema to check.
+
+        Returns:
+            `True` if the field should have a title set, `False` otherwise.
+        """
+        if _core_utils.is_core_schema_field(schema):
+            if schema['type'] == 'computed-field':
+                field_schema = schema['return_schema']
+            else:
+                field_schema = schema['schema']
+            return self.field_title_should_be_set(field_schema)
+
+        elif _core_utils.is_core_schema(schema):
+            if schema.get('ref'):  # things with refs, such as models and enums, should not have titles set
+                return False
+            if schema['type'] in {'default', 'nullable', 'definitions'}:
+                return self.field_title_should_be_set(schema['schema'])  # type: ignore[typeddict-item]
+            if _core_utils.is_function_with_inner_schema(schema):
+                return self.field_title_should_be_set(schema['schema'])
+            if schema['type'] == 'definition-ref':
+                # Referenced schemas should not have titles set for the same reason
+                # schemas with refs should not
+                return False
+            return True  # anything else should have title set
+
+        else:
+            raise PydanticInvalidForJsonSchema(f'Unexpected schema type: schema={schema}')  # pragma: no cover
+
+    def normalize_name(self, name: str) -> str:
+        """Normalizes a name to be used as a key in a dictionary.
+
+        Args:
+            name: The name to normalize.
+
+        Returns:
+            The normalized name.
+        """
+        return re.sub(r'[^a-zA-Z0-9.\-_]', '_', name).replace('.', '__')
+
+    def get_defs_ref(self, core_mode_ref: CoreModeRef) -> DefsRef:
+        """Override this method to change the way that definitions keys are generated from a core reference.
+
+        Args:
+            core_mode_ref: The core reference.
+
+        Returns:
+            The definitions key.
+        """
+        # Split the core ref into "components"; generic origins and arguments are each separate components
+        core_ref, mode = core_mode_ref
+        components = re.split(r'([\][,])', core_ref)
+        # Remove IDs from each component
+        components = [x.rsplit(':', 1)[0] for x in components]
+        core_ref_no_id = ''.join(components)
+        # Remove everything before the last period from each "component"
+        components = [re.sub(r'(?:[^.[\]]+\.)+((?:[^.[\]]+))', r'\1', x) for x in components]
+        short_ref = ''.join(components)
+
+        mode_title = _MODE_TITLE_MAPPING[mode]
+
+        # It is important that the generated defs_ref values be such that at least one choice will not
+        # be generated for any other core_ref. Currently, this should be the case because we include
+        # the id of the source type in the core_ref
+        name = DefsRef(self.normalize_name(short_ref))
+        name_mode = DefsRef(self.normalize_name(short_ref) + f'-{mode_title}')
+        module_qualname = DefsRef(self.normalize_name(core_ref_no_id))
+        module_qualname_mode = DefsRef(f'{module_qualname}-{mode_title}')
+        module_qualname_id = DefsRef(self.normalize_name(core_ref))
+        occurrence_index = self._collision_index.get(module_qualname_id)
+        if occurrence_index is None:
+            self._collision_counter[module_qualname] += 1
+            occurrence_index = self._collision_index[module_qualname_id] = self._collision_counter[module_qualname]
+
+        module_qualname_occurrence = DefsRef(f'{module_qualname}__{occurrence_index}')
+        module_qualname_occurrence_mode = DefsRef(f'{module_qualname_mode}__{occurrence_index}')
+
+        self._prioritized_defsref_choices[module_qualname_occurrence_mode] = [
+            name,
+            name_mode,
+            module_qualname,
+            module_qualname_mode,
+            module_qualname_occurrence,
+            module_qualname_occurrence_mode,
+        ]
+
+        return module_qualname_occurrence_mode
+
+    def get_cache_defs_ref_schema(self, core_ref: CoreRef) -> tuple[DefsRef, JsonSchemaValue]:
+        """This method wraps the get_defs_ref method with some cache-lookup/population logic,
+        and returns both the produced defs_ref and the JSON schema that will refer to the right definition.
+
+        Args:
+            core_ref: The core reference to get the definitions reference for.
+
+        Returns:
+            A tuple of the definitions reference and the JSON schema that will refer to it.
+        """
+        core_mode_ref = (core_ref, self.mode)
+        maybe_defs_ref = self.core_to_defs_refs.get(core_mode_ref)
+        if maybe_defs_ref is not None:
+            json_ref = self.core_to_json_refs[core_mode_ref]
+            return maybe_defs_ref, {'$ref': json_ref}
+
+        defs_ref = self.get_defs_ref(core_mode_ref)
+
+        # populate the ref translation mappings
+        self.core_to_defs_refs[core_mode_ref] = defs_ref
+        self.defs_to_core_refs[defs_ref] = core_mode_ref
+
+        json_ref = JsonRef(self.ref_template.format(model=defs_ref))
+        self.core_to_json_refs[core_mode_ref] = json_ref
+        self.json_to_defs_refs[json_ref] = defs_ref
+        ref_json_schema = {'$ref': json_ref}
+        return defs_ref, ref_json_schema
+
+    def handle_ref_overrides(self, json_schema: JsonSchemaValue) -> JsonSchemaValue:
+        """Remove any sibling keys that are redundant with the referenced schema.
+
+        Args:
+            json_schema: The schema to remove redundant sibling keys from.
+
+        Returns:
+            The schema with redundant sibling keys removed.
+        """
+        if '$ref' in json_schema:
+            # prevent modifications to the input; this copy may be safe to drop if there is significant overhead
+            json_schema = json_schema.copy()
+
+            referenced_json_schema = self.get_schema_from_definitions(JsonRef(json_schema['$ref']))
+            if referenced_json_schema is None:
+                # This can happen when building schemas for models with not-yet-defined references.
+                # It may be a good idea to do a recursive pass at the end of the generation to remove
+                # any redundant override keys.
+                return json_schema
+            for k, v in list(json_schema.items()):
+                if k == '$ref':
+                    continue
+                if k in referenced_json_schema and referenced_json_schema[k] == v:
+                    del json_schema[k]  # redundant key
+
+        return json_schema
+
+    def get_schema_from_definitions(self, json_ref: JsonRef) -> JsonSchemaValue | None:
+        try:
+            def_ref = self.json_to_defs_refs[json_ref]
+            if def_ref in self._core_defs_invalid_for_json_schema:
+                raise self._core_defs_invalid_for_json_schema[def_ref]
+            return self.definitions.get(def_ref, None)
+        except KeyError:
+            if json_ref.startswith(('http://', 'https://')):
+                return None
+            raise
+
+    def encode_default(self, dft: Any) -> Any:
+        """Encode a default value to a JSON-serializable value.
+
+        This is used to encode default values for fields in the generated JSON schema.
+
+        Args:
+            dft: The default value to encode.
+
+        Returns:
+            The encoded default value.
+        """
+        from .type_adapter import TypeAdapter, _type_has_config
+
+        config = self._config
+        try:
+            default = (
+                dft
+                if _type_has_config(type(dft))
+                else TypeAdapter(type(dft), config=config.config_dict).dump_python(
+                    dft, by_alias=self.by_alias, mode='json'
+                )
+            )
+        except PydanticSchemaGenerationError:
+            raise pydantic_core.PydanticSerializationError(f'Unable to encode default value {dft}')
+
+        return pydantic_core.to_jsonable_python(
+            default, timedelta_mode=config.ser_json_timedelta, bytes_mode=config.ser_json_bytes, by_alias=self.by_alias
+        )
+
+    def update_with_validations(
+        self, json_schema: JsonSchemaValue, core_schema: CoreSchema, mapping: dict[str, str]
+    ) -> None:
+        """Update the json_schema with the corresponding validations specified in the core_schema,
+        using the provided mapping to translate keys in core_schema to the appropriate keys for a JSON schema.
+
+        Args:
+            json_schema: The JSON schema to update.
+            core_schema: The core schema to get the validations from.
+            mapping: A mapping from core_schema attribute names to the corresponding JSON schema attribute names.
+        """
+        for core_key, json_schema_key in mapping.items():
+            if core_key in core_schema:
+                json_schema[json_schema_key] = core_schema[core_key]
+
+    class ValidationsMapping:
+        """This class just contains mappings from core_schema attribute names to the corresponding
+        JSON schema attribute names. While I suspect it is unlikely to be necessary, you can in
+        principle override this class in a subclass of GenerateJsonSchema (by inheriting from
+        GenerateJsonSchema.ValidationsMapping) to change these mappings.
+        """
+
+        numeric = {
+            'multiple_of': 'multipleOf',
+            'le': 'maximum',
+            'ge': 'minimum',
+            'lt': 'exclusiveMaximum',
+            'gt': 'exclusiveMinimum',
+        }
+        bytes = {
+            'min_length': 'minLength',
+            'max_length': 'maxLength',
+        }
+        string = {
+            'min_length': 'minLength',
+            'max_length': 'maxLength',
+            'pattern': 'pattern',
+        }
+        array = {
+            'min_length': 'minItems',
+            'max_length': 'maxItems',
+        }
+        object = {
+            'min_length': 'minProperties',
+            'max_length': 'maxProperties',
+        }
+
+    def get_flattened_anyof(self, schemas: list[JsonSchemaValue]) -> JsonSchemaValue:
+        members = []
+        for schema in schemas:
+            if len(schema) == 1 and 'anyOf' in schema:
+                members.extend(schema['anyOf'])
+            else:
+                members.append(schema)
+        members = _deduplicate_schemas(members)
+        if len(members) == 1:
+            return members[0]
+        return {'anyOf': members}
+
+    def get_json_ref_counts(self, json_schema: JsonSchemaValue) -> dict[JsonRef, int]:
+        """Get all values corresponding to the key '$ref' anywhere in the json_schema."""
+        json_refs: dict[JsonRef, int] = Counter()
+
+        def _add_json_refs(schema: Any) -> None:
+            if isinstance(schema, dict):
+                if '$ref' in schema:
+                    json_ref = JsonRef(schema['$ref'])
+                    if not isinstance(json_ref, str):
+                        return  # in this case, '$ref' might have been the name of a property
+                    already_visited = json_ref in json_refs
+                    json_refs[json_ref] += 1
+                    if already_visited:
+                        return  # prevent recursion on a definition that was already visited
+                    try:
+                        defs_ref = self.json_to_defs_refs[json_ref]
+                        if defs_ref in self._core_defs_invalid_for_json_schema:
+                            raise self._core_defs_invalid_for_json_schema[defs_ref]
+                        _add_json_refs(self.definitions[defs_ref])
+                    except KeyError:
+                        if not json_ref.startswith(('http://', 'https://')):
+                            raise
+
+                for k, v in schema.items():
+                    if k == 'examples' and isinstance(v, list):
+                        # Skip examples that may contain arbitrary values and references
+                        # (see the comment in `_get_all_json_refs` for more details).
+                        continue
+                    _add_json_refs(v)
+            elif isinstance(schema, list):
+                for v in schema:
+                    _add_json_refs(v)
+
+        _add_json_refs(json_schema)
+        return json_refs
+
+    def handle_invalid_for_json_schema(self, schema: CoreSchemaOrField, error_info: str) -> JsonSchemaValue:
+        raise PydanticInvalidForJsonSchema(f'Cannot generate a JsonSchema for {error_info}')
+
+    def emit_warning(self, kind: JsonSchemaWarningKind, detail: str) -> None:
+        """This method simply emits PydanticJsonSchemaWarnings based on handling in the `warning_message` method."""
+        message = self.render_warning_message(kind, detail)
+        if message is not None:
+            warnings.warn(message, PydanticJsonSchemaWarning)
+
+    def render_warning_message(self, kind: JsonSchemaWarningKind, detail: str) -> str | None:
+        """This method is responsible for ignoring warnings as desired, and for formatting the warning messages.
+
+        You can override the value of `ignored_warning_kinds` in a subclass of GenerateJsonSchema
+        to modify what warnings are generated. If you want more control, you can override this method;
+        just return None in situations where you don't want warnings to be emitted.
+
+        Args:
+            kind: The kind of warning to render. It can be one of the following:
+
+                - 'skipped-choice': A choice field was skipped because it had no valid choices.
+                - 'non-serializable-default': A default value was skipped because it was not JSON-serializable.
+            detail: A string with additional details about the warning.
+
+        Returns:
+            The formatted warning message, or `None` if no warning should be emitted.
+        """
+        if kind in self.ignored_warning_kinds:
+            return None
+        return f'{detail} [{kind}]'
+
+    def _build_definitions_remapping(self) -> _DefinitionsRemapping:
+        defs_to_json: dict[DefsRef, JsonRef] = {}
+        for defs_refs in self._prioritized_defsref_choices.values():
+            for defs_ref in defs_refs:
+                json_ref = JsonRef(self.ref_template.format(model=defs_ref))
+                defs_to_json[defs_ref] = json_ref
+
+        return _DefinitionsRemapping.from_prioritized_choices(
+            self._prioritized_defsref_choices, defs_to_json, self.definitions
+        )
+
+    def _garbage_collect_definitions(self, schema: JsonSchemaValue) -> None:
+        visited_defs_refs: set[DefsRef] = set()
+        unvisited_json_refs = _get_all_json_refs(schema)
+        while unvisited_json_refs:
+            next_json_ref = unvisited_json_refs.pop()
+            try:
+                next_defs_ref = self.json_to_defs_refs[next_json_ref]
+                if next_defs_ref in visited_defs_refs:
+                    continue
+                visited_defs_refs.add(next_defs_ref)
+                unvisited_json_refs.update(_get_all_json_refs(self.definitions[next_defs_ref]))
+            except KeyError:
+                if not next_json_ref.startswith(('http://', 'https://')):
+                    raise
+
+        self.definitions = {k: v for k, v in self.definitions.items() if k in visited_defs_refs}
+
+
+# ##### Start JSON Schema Generation Functions #####
+
+
+def model_json_schema(
+    cls: type[BaseModel] | type[PydanticDataclass],
+    by_alias: bool = True,
+    ref_template: str = DEFAULT_REF_TEMPLATE,
+    union_format: Literal['any_of', 'primitive_type_array'] = 'any_of',
+    schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
+    mode: JsonSchemaMode = 'validation',
+) -> dict[str, Any]:
+    """Utility function to generate a JSON Schema for a model.
+
+    Args:
+        cls: The model class to generate a JSON Schema for.
+        by_alias: If `True` (the default), fields will be serialized according to their alias.
+            If `False`, fields will be serialized according to their attribute name.
+        ref_template: The template to use for generating JSON Schema references.
+        union_format: The format to use when combining schemas from unions together. Can be one of:
+
+            - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
+              keyword to combine schemas (the default).
+            - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
+              keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
+              type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
+              `any_of`.
+        schema_generator: The class to use for generating the JSON Schema.
+        mode: The mode to use for generating the JSON Schema. It can be one of the following:
+
+            - 'validation': Generate a JSON Schema for validating data.
+            - 'serialization': Generate a JSON Schema for serializing data.
+
+    Returns:
+        The generated JSON Schema.
+    """
+    from .main import BaseModel
+
+    schema_generator_instance = schema_generator(
+        by_alias=by_alias, ref_template=ref_template, union_format=union_format
+    )
+
+    if isinstance(cls.__pydantic_core_schema__, _mock_val_ser.MockCoreSchema):
+        cls.__pydantic_core_schema__.rebuild()
+
+    if cls is BaseModel:
+        raise AttributeError('model_json_schema() must be called on a subclass of BaseModel, not BaseModel itself.')
+
+    assert not isinstance(cls.__pydantic_core_schema__, _mock_val_ser.MockCoreSchema), 'this is a bug! please report it'
+    return schema_generator_instance.generate(cls.__pydantic_core_schema__, mode=mode)
+
+
+def models_json_schema(
+    models: Sequence[tuple[type[BaseModel] | type[PydanticDataclass], JsonSchemaMode]],
+    *,
+    by_alias: bool = True,
+    title: str | None = None,
+    description: str | None = None,
+    ref_template: str = DEFAULT_REF_TEMPLATE,
+    union_format: Literal['any_of', 'primitive_type_array'] = 'any_of',
+    schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
+) -> tuple[dict[tuple[type[BaseModel] | type[PydanticDataclass], JsonSchemaMode], JsonSchemaValue], JsonSchemaValue]:
+    """Utility function to generate a JSON Schema for multiple models.
+
+    Args:
+        models: A sequence of tuples of the form (model, mode).
+        by_alias: Whether field aliases should be used as keys in the generated JSON Schema.
+        title: The title of the generated JSON Schema.
+        description: The description of the generated JSON Schema.
+        ref_template: The reference template to use for generating JSON Schema references.
+        union_format: The format to use when combining schemas from unions together. Can be one of:
+
+            - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
+              keyword to combine schemas (the default).
+            - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
+              keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
+              type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
+              `any_of`.
+        schema_generator: The schema generator to use for generating the JSON Schema.
+
+    Returns:
+        A tuple where:
+            - The first element is a dictionary whose keys are tuples of JSON schema key type and JSON mode, and
+                whose values are the JSON schema corresponding to that pair of inputs. (These schemas may have
+                JsonRef references to definitions that are defined in the second returned element.)
+            - The second element is a JSON schema containing all definitions referenced in the first returned
+                    element, along with the optional title and description keys.
+    """
+    for cls, _ in models:
+        if isinstance(cls.__pydantic_core_schema__, _mock_val_ser.MockCoreSchema):
+            cls.__pydantic_core_schema__.rebuild()
+
+    instance = schema_generator(by_alias=by_alias, ref_template=ref_template, union_format=union_format)
+    inputs: list[tuple[type[BaseModel] | type[PydanticDataclass], JsonSchemaMode, CoreSchema]] = [
+        (m, mode, m.__pydantic_core_schema__) for m, mode in models
+    ]
+    json_schemas_map, definitions = instance.generate_definitions(inputs)
+
+    json_schema: dict[str, Any] = {}
+    if definitions:
+        json_schema['$defs'] = definitions
+    if title:
+        json_schema['title'] = title
+    if description:
+        json_schema['description'] = description
+
+    return json_schemas_map, json_schema
+
+
+# ##### End JSON Schema Generation Functions #####
+
+
+_HashableJsonValue: TypeAlias = Union[
+    int, float, str, bool, None, tuple['_HashableJsonValue', ...], tuple[tuple[str, '_HashableJsonValue'], ...]
+]
+
+
+def _deduplicate_schemas(schemas: Iterable[JsonDict]) -> list[JsonDict]:
+    return list({_make_json_hashable(schema): schema for schema in schemas}.values())
+
+
+def _make_json_hashable(value: JsonValue) -> _HashableJsonValue:
+    if isinstance(value, dict):
+        return tuple(sorted((k, _make_json_hashable(v)) for k, v in value.items()))
+    elif isinstance(value, list):
+        return tuple(_make_json_hashable(v) for v in value)
+    else:
+        return value
+
+
+@dataclasses.dataclass(**_internal_dataclass.slots_true)
+class WithJsonSchema:
+    """!!! abstract "Usage Documentation"
+        [`WithJsonSchema` Annotation](../concepts/json_schema.md#withjsonschema-annotation)
+
+    Add this as an annotation on a field to override the (base) JSON schema that would be generated for that field.
+    This provides a way to set a JSON schema for types that would otherwise raise errors when producing a JSON schema,
+    such as Callable, or types that have an is-instance core schema, without needing to go so far as creating a
+    custom subclass of pydantic.json_schema.GenerateJsonSchema.
+    Note that any _modifications_ to the schema that would normally be made (such as setting the title for model fields)
+    will still be performed.
+
+    If `mode` is set this will only apply to that schema generation mode, allowing you
+    to set different json schemas for validation and serialization.
+    """
+
+    json_schema: JsonSchemaValue | None
+    mode: Literal['validation', 'serialization'] | None = None
+
+    def __get_pydantic_json_schema__(
+        self, core_schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler
+    ) -> JsonSchemaValue:
+        mode = self.mode or handler.mode
+        if mode != handler.mode:
+            return handler(core_schema)
+        if self.json_schema is None:
+            # This exception is handled in pydantic.json_schema.GenerateJsonSchema._named_required_fields_schema
+            raise PydanticOmit
+        else:
+            return self.json_schema.copy()
+
+    def __hash__(self) -> int:
+        return hash(type(self.mode))
+
+
+class Examples:
+    """Add examples to a JSON schema.
+
+    If the JSON Schema already contains examples, the provided examples
+    will be appended.
+
+    If `mode` is set this will only apply to that schema generation mode,
+    allowing you to add different examples for validation and serialization.
+    """
+
+    @overload
+    @deprecated('Using a dict for `examples` is deprecated since v2.9 and will be removed in v3.0. Use a list instead.')
+    def __init__(
+        self, examples: dict[str, Any], mode: Literal['validation', 'serialization'] | None = None
+    ) -> None: ...
+
+    @overload
+    def __init__(self, examples: list[Any], mode: Literal['validation', 'serialization'] | None = None) -> None: ...
+
+    def __init__(
+        self, examples: dict[str, Any] | list[Any], mode: Literal['validation', 'serialization'] | None = None
+    ) -> None:
+        if isinstance(examples, dict):
+            warnings.warn(
+                'Using a dict for `examples` is deprecated, use a list instead.',
+                PydanticDeprecatedSince29,
+                stacklevel=2,
+            )
+        self.examples = examples
+        self.mode = mode
+
+    def __get_pydantic_json_schema__(
+        self, core_schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler
+    ) -> JsonSchemaValue:
+        mode = self.mode or handler.mode
+        json_schema = handler(core_schema)
+        if mode != handler.mode:
+            return json_schema
+        examples = json_schema.get('examples')
+        if examples is None:
+            json_schema['examples'] = to_jsonable_python(self.examples)
+        if isinstance(examples, dict):
+            if isinstance(self.examples, list):
+                warnings.warn(
+                    'Updating existing JSON Schema examples of type dict with examples of type list. '
+                    'Only the existing examples values will be retained. Note that dict support for '
+                    'examples is deprecated and will be removed in v3.0.',
+                    UserWarning,
+                )
+                json_schema['examples'] = to_jsonable_python(
+                    [ex for value in examples.values() for ex in value] + self.examples
+                )
+            else:
+                json_schema['examples'] = to_jsonable_python({**examples, **self.examples})
+        if isinstance(examples, list):
+            if isinstance(self.examples, list):
+                json_schema['examples'] = to_jsonable_python(examples + self.examples)
+            elif isinstance(self.examples, dict):
+                warnings.warn(
+                    'Updating existing JSON Schema examples of type list with examples of type dict. '
+                    'Only the examples values will be retained. Note that dict support for '
+                    'examples is deprecated and will be removed in v3.0.',
+                    UserWarning,
+                )
+                json_schema['examples'] = to_jsonable_python(
+                    examples + [ex for value in self.examples.values() for ex in value]
+                )
+
+        return json_schema
+
+    def __hash__(self) -> int:
+        return hash(type(self.mode))
+
+
+def _get_all_json_refs(item: Any) -> set[JsonRef]:
+    """Get all the definitions references from a JSON schema."""
+    refs: set[JsonRef] = set()
+    stack = [item]
+
+    while stack:
+        current = stack.pop()
+        if isinstance(current, dict):
+            for key, value in current.items():
+                if key == 'examples' and isinstance(value, list):
+                    # Skip examples that may contain arbitrary values and references
+                    # (e.g. `{"examples": [{"$ref": "..."}]}`). Note: checking for value
+                    # of type list is necessary to avoid skipping valid portions of the schema,
+                    # for instance when "examples" is used as a property key. A more robust solution
+                    # could be found, but would require more advanced JSON Schema parsing logic.
+                    continue
+                if key == '$ref' and isinstance(value, str):
+                    refs.add(JsonRef(value))
+                elif isinstance(value, dict):
+                    stack.append(value)
+                elif isinstance(value, list):
+                    stack.extend(value)
+        elif isinstance(current, list):
+            stack.extend(current)
+
+    return refs
+
+
+AnyType = TypeVar('AnyType')
+
+if TYPE_CHECKING:
+    SkipJsonSchema = Annotated[AnyType, ...]
+else:
+
+    @dataclasses.dataclass(**_internal_dataclass.slots_true)
+    class SkipJsonSchema:
+        """!!! abstract "Usage Documentation"
+            [`SkipJsonSchema` Annotation](../concepts/json_schema.md#skipjsonschema-annotation)
+
+        Add this as an annotation on a field to skip generating a JSON schema for that field.
+
+        Example:
+            ```python
+            from pprint import pprint
+            from typing import Union
+
+            from pydantic import BaseModel
+            from pydantic.json_schema import SkipJsonSchema
+
+            class Model(BaseModel):
+                a: Union[int, None] = None  # (1)!
+                b: Union[int, SkipJsonSchema[None]] = None  # (2)!
+                c: SkipJsonSchema[Union[int, None]] = None  # (3)!
+
+            pprint(Model.model_json_schema())
+            '''
+            {
+                'properties': {
+                    'a': {
+                        'anyOf': [
+                            {'type': 'integer'},
+                            {'type': 'null'}
+                        ],
+                        'default': None,
+                        'title': 'A'
+                    },
+                    'b': {
+                        'default': None,
+                        'title': 'B',
+                        'type': 'integer'
+                    }
+                },
+                'title': 'Model',
+                'type': 'object'
+            }
+            '''
+            ```
+
+            1. The integer and null types are both included in the schema for `a`.
+            2. The integer type is the only type included in the schema for `b`.
+            3. The entirety of the `c` field is omitted from the schema.
+        """
+
+        def __class_getitem__(cls, item: AnyType) -> AnyType:
+            return Annotated[item, cls()]
+
+        def __get_pydantic_json_schema__(
+            self, core_schema: CoreSchema, handler: GetJsonSchemaHandler
+        ) -> JsonSchemaValue:
+            raise PydanticOmit
+
+        def __hash__(self) -> int:
+            return hash(type(self))
+
+
+def _get_typed_dict_config(cls: type[Any] | None) -> ConfigDict:
+    if cls is not None:
+        try:
+            return _decorators.get_attribute_from_bases(cls, '__pydantic_config__')
+        except AttributeError:
+            pass
+    return {}
+
+
+def _get_ser_schema_for_default_value(schema: CoreSchema) -> core_schema.PlainSerializerFunctionSerSchema | None:
+    """Get a `'function-plain'` serialization schema that can be used to serialize a default value.
+
+    This takes into account having the serialization schema nested under validation schema(s).
+    """
+    if (
+        (ser_schema := schema.get('serialization'))
+        and ser_schema['type'] == 'function-plain'
+        and not ser_schema.get('info_arg')
+    ):
+        return ser_schema
+    if _core_utils.is_function_with_inner_schema(schema):
+        return _get_ser_schema_for_default_value(schema['schema'])
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pydantic/main.py b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/main.py
new file mode 100644
index 0000000000000000000000000000000000000000..2b3148eda1d687ebbd6636a6ce427a23a9ab19bb
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/main.py
@@ -0,0 +1,1819 @@
+"""Logic for creating models."""
+
+# Because `dict` is in the local namespace of the `BaseModel` class, we use `Dict` for annotations.
+# TODO v3 fallback to `dict` when the deprecated `dict` method gets removed.
+# ruff: noqa: UP035
+
+from __future__ import annotations as _annotations
+
+import operator
+import sys
+import types
+import warnings
+from collections.abc import Generator, Mapping
+from copy import copy, deepcopy
+from functools import cached_property
+from typing import (
+    TYPE_CHECKING,
+    Any,
+    Callable,
+    ClassVar,
+    Dict,
+    Generic,
+    Literal,
+    TypeVar,
+    Union,
+    cast,
+    overload,
+)
+
+import pydantic_core
+import typing_extensions
+from pydantic_core import PydanticUndefined, ValidationError
+from typing_extensions import Self, TypeAlias, Unpack
+
+from . import PydanticDeprecatedSince20, PydanticDeprecatedSince211
+from ._internal import (
+    _config,
+    _decorators,
+    _fields,
+    _forward_ref,
+    _generics,
+    _mock_val_ser,
+    _model_construction,
+    _namespace_utils,
+    _repr,
+    _typing_extra,
+    _utils,
+)
+from ._migration import getattr_migration
+from .aliases import AliasChoices, AliasPath
+from .annotated_handlers import GetCoreSchemaHandler, GetJsonSchemaHandler
+from .config import ConfigDict, ExtraValues
+from .errors import PydanticUndefinedAnnotation, PydanticUserError
+from .json_schema import DEFAULT_REF_TEMPLATE, GenerateJsonSchema, JsonSchemaMode, JsonSchemaValue, model_json_schema
+from .plugin._schema_validator import PluggableSchemaValidator
+
+if TYPE_CHECKING:
+    from inspect import Signature
+    from pathlib import Path
+
+    from pydantic_core import CoreSchema, SchemaSerializer, SchemaValidator
+
+    from ._internal._namespace_utils import MappingNamespace
+    from ._internal._utils import AbstractSetIntStr, MappingIntStrAny
+    from .deprecated.parse import Protocol as DeprecatedParseProtocol
+    from .fields import ComputedFieldInfo, FieldInfo, ModelPrivateAttr
+
+
+__all__ = 'BaseModel', 'create_model'
+
+# Keep these type aliases available at runtime:
+TupleGenerator: TypeAlias = Generator[tuple[str, Any], None, None]
+# NOTE: In reality, `bool` should be replaced by `Literal[True]` but mypy fails to correctly apply bidirectional
+# type inference (e.g. when using `{'a': {'b': True}}`):
+# NOTE: Keep this type alias in sync with the stub definition in `pydantic-core`:
+IncEx: TypeAlias = Union[set[int], set[str], Mapping[int, Union['IncEx', bool]], Mapping[str, Union['IncEx', bool]]]
+
+_object_setattr = _model_construction.object_setattr
+
+
+def _check_frozen(model_cls: type[BaseModel], name: str, value: Any) -> None:
+    if model_cls.model_config.get('frozen'):
+        error_type = 'frozen_instance'
+    elif getattr(model_cls.__pydantic_fields__.get(name), 'frozen', False):
+        error_type = 'frozen_field'
+    else:
+        return
+
+    raise ValidationError.from_exception_data(
+        model_cls.__name__, [{'type': error_type, 'loc': (name,), 'input': value}]
+    )
+
+
+def _model_field_setattr_handler(model: BaseModel, name: str, val: Any) -> None:
+    model.__dict__[name] = val
+    model.__pydantic_fields_set__.add(name)
+
+
+def _private_setattr_handler(model: BaseModel, name: str, val: Any) -> None:
+    if getattr(model, '__pydantic_private__', None) is None:
+        # While the attribute should be present at this point, this may not be the case if
+        # users do unusual stuff with `model_post_init()` (which is where the  `__pydantic_private__`
+        # is initialized, by wrapping the user-defined `model_post_init()`), e.g. if they mock
+        # the `model_post_init()` call. Ideally we should find a better way to init private attrs.
+        object.__setattr__(model, '__pydantic_private__', {})
+    model.__pydantic_private__[name] = val  # pyright: ignore[reportOptionalSubscript]
+
+
+_SIMPLE_SETATTR_HANDLERS: Mapping[str, Callable[[BaseModel, str, Any], None]] = {
+    'model_field': _model_field_setattr_handler,
+    'validate_assignment': lambda model, name, val: model.__pydantic_validator__.validate_assignment(model, name, val),  # pyright: ignore[reportAssignmentType]
+    'private': _private_setattr_handler,
+    'cached_property': lambda model, name, val: model.__dict__.__setitem__(name, val),
+    'extra_known': lambda model, name, val: _object_setattr(model, name, val),
+}
+
+
+class BaseModel(metaclass=_model_construction.ModelMetaclass):
+    """!!! abstract "Usage Documentation"
+        [Models](../concepts/models.md)
+
+    A base class for creating Pydantic models.
+
+    Attributes:
+        __class_vars__: The names of the class variables defined on the model.
+        __private_attributes__: Metadata about the private attributes of the model.
+        __signature__: The synthesized `__init__` [`Signature`][inspect.Signature] of the model.
+
+        __pydantic_complete__: Whether model building is completed, or if there are still undefined fields.
+        __pydantic_core_schema__: The core schema of the model.
+        __pydantic_custom_init__: Whether the model has a custom `__init__` function.
+        __pydantic_decorators__: Metadata containing the decorators defined on the model.
+            This replaces `Model.__validators__` and `Model.__root_validators__` from Pydantic V1.
+        __pydantic_generic_metadata__: Metadata for generic models; contains data used for a similar purpose to
+            __args__, __origin__, __parameters__ in typing-module generics. May eventually be replaced by these.
+        __pydantic_parent_namespace__: Parent namespace of the model, used for automatic rebuilding of models.
+        __pydantic_post_init__: The name of the post-init method for the model, if defined.
+        __pydantic_root_model__: Whether the model is a [`RootModel`][pydantic.root_model.RootModel].
+        __pydantic_serializer__: The `pydantic-core` `SchemaSerializer` used to dump instances of the model.
+        __pydantic_validator__: The `pydantic-core` `SchemaValidator` used to validate instances of the model.
+
+        __pydantic_fields__: A dictionary of field names and their corresponding [`FieldInfo`][pydantic.fields.FieldInfo] objects.
+        __pydantic_computed_fields__: A dictionary of computed field names and their corresponding [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] objects.
+
+        __pydantic_extra__: A dictionary containing extra values, if [`extra`][pydantic.config.ConfigDict.extra]
+            is set to `'allow'`.
+        __pydantic_fields_set__: The names of fields explicitly set during instantiation.
+        __pydantic_private__: Values of private attributes set on the model instance.
+    """
+
+    # Note: Many of the below class vars are defined in the metaclass, but we define them here for type checking purposes.
+
+    model_config: ClassVar[ConfigDict] = ConfigDict()
+    """
+    Configuration for the model, should be a dictionary conforming to [`ConfigDict`][pydantic.config.ConfigDict].
+    """
+
+    __class_vars__: ClassVar[set[str]]
+    """The names of the class variables defined on the model."""
+
+    __private_attributes__: ClassVar[Dict[str, ModelPrivateAttr]]  # noqa: UP006
+    """Metadata about the private attributes of the model."""
+
+    __signature__: ClassVar[Signature]
+    """The synthesized `__init__` [`Signature`][inspect.Signature] of the model."""
+
+    __pydantic_complete__: ClassVar[bool] = False
+    """Whether model building is completed, or if there are still undefined fields."""
+
+    __pydantic_core_schema__: ClassVar[CoreSchema]
+    """The core schema of the model."""
+
+    __pydantic_custom_init__: ClassVar[bool]
+    """Whether the model has a custom `__init__` method."""
+
+    # Must be set for `GenerateSchema.model_schema` to work for a plain `BaseModel` annotation.
+    __pydantic_decorators__: ClassVar[_decorators.DecoratorInfos] = _decorators.DecoratorInfos()
+    """Metadata containing the decorators defined on the model.
+    This replaces `Model.__validators__` and `Model.__root_validators__` from Pydantic V1."""
+
+    __pydantic_generic_metadata__: ClassVar[_generics.PydanticGenericMetadata]
+    """Metadata for generic models; contains data used for a similar purpose to
+    __args__, __origin__, __parameters__ in typing-module generics. May eventually be replaced by these."""
+
+    __pydantic_parent_namespace__: ClassVar[Dict[str, Any] | None] = None  # noqa: UP006
+    """Parent namespace of the model, used for automatic rebuilding of models."""
+
+    __pydantic_post_init__: ClassVar[None | Literal['model_post_init']]
+    """The name of the post-init method for the model, if defined."""
+
+    __pydantic_root_model__: ClassVar[bool] = False
+    """Whether the model is a [`RootModel`][pydantic.root_model.RootModel]."""
+
+    __pydantic_serializer__: ClassVar[SchemaSerializer]
+    """The `pydantic-core` `SchemaSerializer` used to dump instances of the model."""
+
+    __pydantic_validator__: ClassVar[SchemaValidator | PluggableSchemaValidator]
+    """The `pydantic-core` `SchemaValidator` used to validate instances of the model."""
+
+    __pydantic_fields__: ClassVar[Dict[str, FieldInfo]]  # noqa: UP006
+    """A dictionary of field names and their corresponding [`FieldInfo`][pydantic.fields.FieldInfo] objects.
+    This replaces `Model.__fields__` from Pydantic V1.
+    """
+
+    __pydantic_setattr_handlers__: ClassVar[Dict[str, Callable[[BaseModel, str, Any], None]]]  # noqa: UP006
+    """`__setattr__` handlers. Memoizing the handlers leads to a dramatic performance improvement in `__setattr__`"""
+
+    __pydantic_computed_fields__: ClassVar[Dict[str, ComputedFieldInfo]]  # noqa: UP006
+    """A dictionary of computed field names and their corresponding [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] objects."""
+
+    __pydantic_extra__: Dict[str, Any] | None = _model_construction.NoInitField(init=False)  # noqa: UP006
+    """A dictionary containing extra values, if [`extra`][pydantic.config.ConfigDict.extra] is set to `'allow'`."""
+
+    __pydantic_fields_set__: set[str] = _model_construction.NoInitField(init=False)
+    """The names of fields explicitly set during instantiation."""
+
+    __pydantic_private__: Dict[str, Any] | None = _model_construction.NoInitField(init=False)  # noqa: UP006
+    """Values of private attributes set on the model instance."""
+
+    if not TYPE_CHECKING:
+        # Prevent `BaseModel` from being instantiated directly
+        # (defined in an `if not TYPE_CHECKING` block for clarity and to avoid type checking errors):
+        __pydantic_core_schema__ = _mock_val_ser.MockCoreSchema(
+            'Pydantic models should inherit from BaseModel, BaseModel cannot be instantiated directly',
+            code='base-model-instantiated',
+        )
+        __pydantic_validator__ = _mock_val_ser.MockValSer(
+            'Pydantic models should inherit from BaseModel, BaseModel cannot be instantiated directly',
+            val_or_ser='validator',
+            code='base-model-instantiated',
+        )
+        __pydantic_serializer__ = _mock_val_ser.MockValSer(
+            'Pydantic models should inherit from BaseModel, BaseModel cannot be instantiated directly',
+            val_or_ser='serializer',
+            code='base-model-instantiated',
+        )
+
+    __slots__ = '__dict__', '__pydantic_fields_set__', '__pydantic_extra__', '__pydantic_private__'
+
+    def __init__(self, /, **data: Any) -> None:
+        """Create a new model by parsing and validating input data from keyword arguments.
+
+        Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
+        validated to form a valid model.
+
+        `self` is explicitly positional-only to allow `self` as a field name.
+        """
+        # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
+        __tracebackhide__ = True
+        validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
+        if self is not validated_self:
+            warnings.warn(
+                'A custom validator is returning a value other than `self`.\n'
+                "Returning anything other than `self` from a top level model validator isn't supported when validating via `__init__`.\n"
+                'See the `model_validator` docs (https://docs.pydantic.dev/latest/concepts/validators/#model-validators) for more details.',
+                stacklevel=2,
+            )
+
+    # The following line sets a flag that we use to determine when `__init__` gets overridden by the user
+    __init__.__pydantic_base_init__ = True  # pyright: ignore[reportFunctionMemberAccess]
+
+    @_utils.deprecated_instance_property
+    @classmethod
+    def model_fields(cls) -> dict[str, FieldInfo]:
+        """A mapping of field names to their respective [`FieldInfo`][pydantic.fields.FieldInfo] instances.
+
+        !!! warning
+            Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.
+            Instead, you should access this attribute from the model class.
+        """
+        return getattr(cls, '__pydantic_fields__', {})
+
+    @_utils.deprecated_instance_property
+    @classmethod
+    def model_computed_fields(cls) -> dict[str, ComputedFieldInfo]:
+        """A mapping of computed field names to their respective [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] instances.
+
+        !!! warning
+            Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.
+            Instead, you should access this attribute from the model class.
+        """
+        return getattr(cls, '__pydantic_computed_fields__', {})
+
+    @property
+    def model_extra(self) -> dict[str, Any] | None:
+        """Get extra fields set during validation.
+
+        Returns:
+            A dictionary of extra fields, or `None` if `config.extra` is not set to `"allow"`.
+        """
+        return self.__pydantic_extra__
+
+    @property
+    def model_fields_set(self) -> set[str]:
+        """Returns the set of fields that have been explicitly set on this model instance.
+
+        Returns:
+            A set of strings representing the fields that have been set,
+                i.e. that were not filled from defaults.
+        """
+        return self.__pydantic_fields_set__
+
+    @classmethod
+    def model_construct(cls, _fields_set: set[str] | None = None, **values: Any) -> Self:  # noqa: C901
+        """Creates a new instance of the `Model` class with validated data.
+
+        Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data.
+        Default values are respected, but no other validation is performed.
+
+        !!! note
+            `model_construct()` generally respects the `model_config.extra` setting on the provided model.
+            That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__`
+            and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored.
+            Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in
+            an error if extra values are passed, but they will be ignored.
+
+        Args:
+            _fields_set: A set of field names that were originally explicitly set during instantiation. If provided,
+                this is directly used for the [`model_fields_set`][pydantic.BaseModel.model_fields_set] attribute.
+                Otherwise, the field names from the `values` argument will be used.
+            values: Trusted or pre-validated data dictionary.
+
+        Returns:
+            A new instance of the `Model` class with validated data.
+        """
+        m = cls.__new__(cls)
+        fields_values: dict[str, Any] = {}
+        fields_set = set()
+
+        for name, field in cls.__pydantic_fields__.items():
+            if field.alias is not None and field.alias in values:
+                fields_values[name] = values.pop(field.alias)
+                fields_set.add(name)
+
+            if (name not in fields_set) and (field.validation_alias is not None):
+                validation_aliases: list[str | AliasPath] = (
+                    field.validation_alias.choices
+                    if isinstance(field.validation_alias, AliasChoices)
+                    else [field.validation_alias]
+                )
+
+                for alias in validation_aliases:
+                    if isinstance(alias, str) and alias in values:
+                        fields_values[name] = values.pop(alias)
+                        fields_set.add(name)
+                        break
+                    elif isinstance(alias, AliasPath):
+                        value = alias.search_dict_for_path(values)
+                        if value is not PydanticUndefined:
+                            fields_values[name] = value
+                            fields_set.add(name)
+                            break
+
+            if name not in fields_set:
+                if name in values:
+                    fields_values[name] = values.pop(name)
+                    fields_set.add(name)
+                elif not field.is_required():
+                    fields_values[name] = field.get_default(call_default_factory=True, validated_data=fields_values)
+        if _fields_set is None:
+            _fields_set = fields_set
+
+        _extra: dict[str, Any] | None = values if cls.model_config.get('extra') == 'allow' else None
+        _object_setattr(m, '__dict__', fields_values)
+        _object_setattr(m, '__pydantic_fields_set__', _fields_set)
+        if not cls.__pydantic_root_model__:
+            _object_setattr(m, '__pydantic_extra__', _extra)
+
+        if cls.__pydantic_post_init__:
+            m.model_post_init(None)
+            # update private attributes with values set
+            if hasattr(m, '__pydantic_private__') and m.__pydantic_private__ is not None:
+                for k, v in values.items():
+                    if k in m.__private_attributes__:
+                        m.__pydantic_private__[k] = v
+
+        elif not cls.__pydantic_root_model__:
+            # Note: if there are any private attributes, cls.__pydantic_post_init__ would exist
+            # Since it doesn't, that means that `__pydantic_private__` should be set to None
+            _object_setattr(m, '__pydantic_private__', None)
+
+        return m
+
+    def model_copy(self, *, update: Mapping[str, Any] | None = None, deep: bool = False) -> Self:
+        """!!! abstract "Usage Documentation"
+            [`model_copy`](../concepts/models.md#model-copy)
+
+        Returns a copy of the model.
+
+        !!! note
+            The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
+            might have unexpected side effects if you store anything in it, on top of the model
+            fields (e.g. the value of [cached properties][functools.cached_property]).
+
+        Args:
+            update: Values to change/add in the new model. Note: the data is not validated
+                before creating the new model. You should trust this data.
+            deep: Set to `True` to make a deep copy of the model.
+
+        Returns:
+            New model instance.
+        """
+        copied = self.__deepcopy__() if deep else self.__copy__()
+        if update:
+            if self.model_config.get('extra') == 'allow':
+                for k, v in update.items():
+                    if k in self.__pydantic_fields__:
+                        copied.__dict__[k] = v
+                    else:
+                        if copied.__pydantic_extra__ is None:
+                            copied.__pydantic_extra__ = {}
+                        copied.__pydantic_extra__[k] = v
+            else:
+                copied.__dict__.update(update)
+            copied.__pydantic_fields_set__.update(update.keys())
+        return copied
+
+    def model_dump(
+        self,
+        *,
+        mode: Literal['json', 'python'] | str = 'python',
+        include: IncEx | None = None,
+        exclude: IncEx | None = None,
+        context: Any | None = None,
+        by_alias: bool | None = None,
+        exclude_unset: bool = False,
+        exclude_defaults: bool = False,
+        exclude_none: bool = False,
+        exclude_computed_fields: bool = False,
+        round_trip: bool = False,
+        warnings: bool | Literal['none', 'warn', 'error'] = True,
+        fallback: Callable[[Any], Any] | None = None,
+        serialize_as_any: bool = False,
+    ) -> dict[str, Any]:
+        """!!! abstract "Usage Documentation"
+            [`model_dump`](../concepts/serialization.md#python-mode)
+
+        Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
+
+        Args:
+            mode: The mode in which `to_python` should run.
+                If mode is 'json', the output will only contain JSON serializable types.
+                If mode is 'python', the output may contain non-JSON-serializable Python objects.
+            include: A set of fields to include in the output.
+            exclude: A set of fields to exclude from the output.
+            context: Additional context to pass to the serializer.
+            by_alias: Whether to use the field's alias in the dictionary key if defined.
+            exclude_unset: Whether to exclude fields that have not been explicitly set.
+            exclude_defaults: Whether to exclude fields that are set to their default value.
+            exclude_none: Whether to exclude fields that have a value of `None`.
+            exclude_computed_fields: Whether to exclude computed fields.
+                While this can be useful for round-tripping, it is usually recommended to use the dedicated
+                `round_trip` parameter instead.
+            round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
+            warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
+                "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
+            fallback: A function to call when an unknown value is encountered. If not provided,
+                a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
+            serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
+
+        Returns:
+            A dictionary representation of the model.
+        """
+        return self.__pydantic_serializer__.to_python(
+            self,
+            mode=mode,
+            by_alias=by_alias,
+            include=include,
+            exclude=exclude,
+            context=context,
+            exclude_unset=exclude_unset,
+            exclude_defaults=exclude_defaults,
+            exclude_none=exclude_none,
+            exclude_computed_fields=exclude_computed_fields,
+            round_trip=round_trip,
+            warnings=warnings,
+            fallback=fallback,
+            serialize_as_any=serialize_as_any,
+        )
+
+    def model_dump_json(
+        self,
+        *,
+        indent: int | None = None,
+        ensure_ascii: bool = False,
+        include: IncEx | None = None,
+        exclude: IncEx | None = None,
+        context: Any | None = None,
+        by_alias: bool | None = None,
+        exclude_unset: bool = False,
+        exclude_defaults: bool = False,
+        exclude_none: bool = False,
+        exclude_computed_fields: bool = False,
+        round_trip: bool = False,
+        warnings: bool | Literal['none', 'warn', 'error'] = True,
+        fallback: Callable[[Any], Any] | None = None,
+        serialize_as_any: bool = False,
+    ) -> str:
+        """!!! abstract "Usage Documentation"
+            [`model_dump_json`](../concepts/serialization.md#json-mode)
+
+        Generates a JSON representation of the model using Pydantic's `to_json` method.
+
+        Args:
+            indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
+            ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
+                If `False` (the default), these characters will be output as-is.
+            include: Field(s) to include in the JSON output.
+            exclude: Field(s) to exclude from the JSON output.
+            context: Additional context to pass to the serializer.
+            by_alias: Whether to serialize using field aliases.
+            exclude_unset: Whether to exclude fields that have not been explicitly set.
+            exclude_defaults: Whether to exclude fields that are set to their default value.
+            exclude_none: Whether to exclude fields that have a value of `None`.
+            exclude_computed_fields: Whether to exclude computed fields.
+                While this can be useful for round-tripping, it is usually recommended to use the dedicated
+                `round_trip` parameter instead.
+            round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
+            warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
+                "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
+            fallback: A function to call when an unknown value is encountered. If not provided,
+                a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
+            serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
+
+        Returns:
+            A JSON string representation of the model.
+        """
+        return self.__pydantic_serializer__.to_json(
+            self,
+            indent=indent,
+            ensure_ascii=ensure_ascii,
+            include=include,
+            exclude=exclude,
+            context=context,
+            by_alias=by_alias,
+            exclude_unset=exclude_unset,
+            exclude_defaults=exclude_defaults,
+            exclude_none=exclude_none,
+            exclude_computed_fields=exclude_computed_fields,
+            round_trip=round_trip,
+            warnings=warnings,
+            fallback=fallback,
+            serialize_as_any=serialize_as_any,
+        ).decode()
+
+    @classmethod
+    def model_json_schema(
+        cls,
+        by_alias: bool = True,
+        ref_template: str = DEFAULT_REF_TEMPLATE,
+        schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
+        mode: JsonSchemaMode = 'validation',
+        *,
+        union_format: Literal['any_of', 'primitive_type_array'] = 'any_of',
+    ) -> dict[str, Any]:
+        """Generates a JSON schema for a model class.
+
+        Args:
+            by_alias: Whether to use attribute aliases or not.
+            ref_template: The reference template.
+            union_format: The format to use when combining schemas from unions together. Can be one of:
+
+                - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
+                keyword to combine schemas (the default).
+                - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
+                keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
+                type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
+                `any_of`.
+            schema_generator: To override the logic used to generate the JSON schema, as a subclass of
+                `GenerateJsonSchema` with your desired modifications
+            mode: The mode in which to generate the schema.
+
+        Returns:
+            The JSON schema for the given model class.
+        """
+        return model_json_schema(
+            cls,
+            by_alias=by_alias,
+            ref_template=ref_template,
+            union_format=union_format,
+            schema_generator=schema_generator,
+            mode=mode,
+        )
+
+    @classmethod
+    def model_parametrized_name(cls, params: tuple[type[Any], ...]) -> str:
+        """Compute the class name for parametrizations of generic classes.
+
+        This method can be overridden to achieve a custom naming scheme for generic BaseModels.
+
+        Args:
+            params: Tuple of types of the class. Given a generic class
+                `Model` with 2 type variables and a concrete model `Model[str, int]`,
+                the value `(str, int)` would be passed to `params`.
+
+        Returns:
+            String representing the new class where `params` are passed to `cls` as type variables.
+
+        Raises:
+            TypeError: Raised when trying to generate concrete names for non-generic models.
+        """
+        if not issubclass(cls, Generic):
+            raise TypeError('Concrete names should only be generated for generic models.')
+
+        # Any strings received should represent forward references, so we handle them specially below.
+        # If we eventually move toward wrapping them in a ForwardRef in __class_getitem__ in the future,
+        # we may be able to remove this special case.
+        param_names = [param if isinstance(param, str) else _repr.display_as_type(param) for param in params]
+        params_component = ', '.join(param_names)
+        return f'{cls.__name__}[{params_component}]'
+
+    def model_post_init(self, context: Any, /) -> None:
+        """Override this method to perform additional initialization after `__init__` and `model_construct`.
+        This is useful if you want to do some validation that requires the entire model to be initialized.
+        """
+
+    @classmethod
+    def model_rebuild(
+        cls,
+        *,
+        force: bool = False,
+        raise_errors: bool = True,
+        _parent_namespace_depth: int = 2,
+        _types_namespace: MappingNamespace | None = None,
+    ) -> bool | None:
+        """Try to rebuild the pydantic-core schema for the model.
+
+        This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
+        the initial attempt to build the schema, and automatic rebuilding fails.
+
+        Args:
+            force: Whether to force the rebuilding of the model schema, defaults to `False`.
+            raise_errors: Whether to raise errors, defaults to `True`.
+            _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
+            _types_namespace: The types namespace, defaults to `None`.
+
+        Returns:
+            Returns `None` if the schema is already "complete" and rebuilding was not required.
+            If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
+        """
+        already_complete = cls.__pydantic_complete__
+        if already_complete and not force:
+            return None
+
+        cls.__pydantic_complete__ = False
+
+        for attr in ('__pydantic_core_schema__', '__pydantic_validator__', '__pydantic_serializer__'):
+            if attr in cls.__dict__ and not isinstance(getattr(cls, attr), _mock_val_ser.MockValSer):
+                # Deleting the validator/serializer is necessary as otherwise they can get reused in
+                # pydantic-core. We do so only if they aren't mock instances, otherwise — as `model_rebuild()`
+                # isn't thread-safe — concurrent model instantiations can lead to the parent validator being used.
+                # Same applies for the core schema that can be reused in schema generation.
+                delattr(cls, attr)
+
+        if _types_namespace is not None:
+            rebuild_ns = _types_namespace
+        elif _parent_namespace_depth > 0:
+            rebuild_ns = _typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth, force=True) or {}
+        else:
+            rebuild_ns = {}
+
+        parent_ns = _model_construction.unpack_lenient_weakvaluedict(cls.__pydantic_parent_namespace__) or {}
+
+        ns_resolver = _namespace_utils.NsResolver(
+            parent_namespace={**rebuild_ns, **parent_ns},
+        )
+
+        return _model_construction.complete_model_class(
+            cls,
+            _config.ConfigWrapper(cls.model_config, check=False),
+            ns_resolver,
+            raise_errors=raise_errors,
+            # If the model was already complete, we don't need to call the hook again.
+            call_on_complete_hook=not already_complete,
+        )
+
+    @classmethod
+    def model_validate(
+        cls,
+        obj: Any,
+        *,
+        strict: bool | None = None,
+        extra: ExtraValues | None = None,
+        from_attributes: bool | None = None,
+        context: Any | None = None,
+        by_alias: bool | None = None,
+        by_name: bool | None = None,
+    ) -> Self:
+        """Validate a pydantic model instance.
+
+        Args:
+            obj: The object to validate.
+            strict: Whether to enforce types strictly.
+            extra: Whether to ignore, allow, or forbid extra data during model validation.
+                See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
+            from_attributes: Whether to extract data from object attributes.
+            context: Additional context to pass to the validator.
+            by_alias: Whether to use the field's alias when validating against the provided input data.
+            by_name: Whether to use the field's name when validating against the provided input data.
+
+        Raises:
+            ValidationError: If the object could not be validated.
+
+        Returns:
+            The validated model instance.
+        """
+        # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
+        __tracebackhide__ = True
+
+        if by_alias is False and by_name is not True:
+            raise PydanticUserError(
+                'At least one of `by_alias` or `by_name` must be set to True.',
+                code='validate-by-alias-and-name-false',
+            )
+
+        return cls.__pydantic_validator__.validate_python(
+            obj,
+            strict=strict,
+            extra=extra,
+            from_attributes=from_attributes,
+            context=context,
+            by_alias=by_alias,
+            by_name=by_name,
+        )
+
+    @classmethod
+    def model_validate_json(
+        cls,
+        json_data: str | bytes | bytearray,
+        *,
+        strict: bool | None = None,
+        extra: ExtraValues | None = None,
+        context: Any | None = None,
+        by_alias: bool | None = None,
+        by_name: bool | None = None,
+    ) -> Self:
+        """!!! abstract "Usage Documentation"
+            [JSON Parsing](../concepts/json.md#json-parsing)
+
+        Validate the given JSON data against the Pydantic model.
+
+        Args:
+            json_data: The JSON data to validate.
+            strict: Whether to enforce types strictly.
+            extra: Whether to ignore, allow, or forbid extra data during model validation.
+                See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
+            context: Extra variables to pass to the validator.
+            by_alias: Whether to use the field's alias when validating against the provided input data.
+            by_name: Whether to use the field's name when validating against the provided input data.
+
+        Returns:
+            The validated Pydantic model.
+
+        Raises:
+            ValidationError: If `json_data` is not a JSON string or the object could not be validated.
+        """
+        # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
+        __tracebackhide__ = True
+
+        if by_alias is False and by_name is not True:
+            raise PydanticUserError(
+                'At least one of `by_alias` or `by_name` must be set to True.',
+                code='validate-by-alias-and-name-false',
+            )
+
+        return cls.__pydantic_validator__.validate_json(
+            json_data, strict=strict, extra=extra, context=context, by_alias=by_alias, by_name=by_name
+        )
+
+    @classmethod
+    def model_validate_strings(
+        cls,
+        obj: Any,
+        *,
+        strict: bool | None = None,
+        extra: ExtraValues | None = None,
+        context: Any | None = None,
+        by_alias: bool | None = None,
+        by_name: bool | None = None,
+    ) -> Self:
+        """Validate the given object with string data against the Pydantic model.
+
+        Args:
+            obj: The object containing string data to validate.
+            strict: Whether to enforce types strictly.
+            extra: Whether to ignore, allow, or forbid extra data during model validation.
+                See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
+            context: Extra variables to pass to the validator.
+            by_alias: Whether to use the field's alias when validating against the provided input data.
+            by_name: Whether to use the field's name when validating against the provided input data.
+
+        Returns:
+            The validated Pydantic model.
+        """
+        # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
+        __tracebackhide__ = True
+
+        if by_alias is False and by_name is not True:
+            raise PydanticUserError(
+                'At least one of `by_alias` or `by_name` must be set to True.',
+                code='validate-by-alias-and-name-false',
+            )
+
+        return cls.__pydantic_validator__.validate_strings(
+            obj, strict=strict, extra=extra, context=context, by_alias=by_alias, by_name=by_name
+        )
+
+    @classmethod
+    def __get_pydantic_core_schema__(cls, source: type[BaseModel], handler: GetCoreSchemaHandler, /) -> CoreSchema:
+        # This warning is only emitted when calling `super().__get_pydantic_core_schema__` from a model subclass.
+        # In the generate schema logic, this method (`BaseModel.__get_pydantic_core_schema__`) is special cased to
+        # *not* be called if not overridden.
+        warnings.warn(
+            'The `__get_pydantic_core_schema__` method of the `BaseModel` class is deprecated. If you are calling '
+            '`super().__get_pydantic_core_schema__` when overriding the method on a Pydantic model, consider using '
+            '`handler(source)` instead. However, note that overriding this method on models can lead to unexpected '
+            'side effects.',
+            PydanticDeprecatedSince211,
+            stacklevel=2,
+        )
+        # Logic copied over from `GenerateSchema._model_schema`:
+        schema = cls.__dict__.get('__pydantic_core_schema__')
+        if schema is not None and not isinstance(schema, _mock_val_ser.MockCoreSchema):
+            return cls.__pydantic_core_schema__
+
+        return handler(source)
+
+    @classmethod
+    def __get_pydantic_json_schema__(
+        cls,
+        core_schema: CoreSchema,
+        handler: GetJsonSchemaHandler,
+        /,
+    ) -> JsonSchemaValue:
+        """Hook into generating the model's JSON schema.
+
+        Args:
+            core_schema: A `pydantic-core` CoreSchema.
+                You can ignore this argument and call the handler with a new CoreSchema,
+                wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
+                or just call the handler with the original schema.
+            handler: Call into Pydantic's internal JSON schema generation.
+                This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
+                generation fails.
+                Since this gets called by `BaseModel.model_json_schema` you can override the
+                `schema_generator` argument to that function to change JSON schema generation globally
+                for a type.
+
+        Returns:
+            A JSON schema, as a Python object.
+        """
+        return handler(core_schema)
+
+    @classmethod
+    def __pydantic_init_subclass__(cls, **kwargs: Any) -> None:
+        """This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
+        only after basic class initialization is complete. In particular, attributes like `model_fields` will
+        be present when this is called, but forward annotations are not guaranteed to be resolved yet,
+        meaning that creating an instance of the class may fail.
+
+        This is necessary because `__init_subclass__` will always be called by `type.__new__`,
+        and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
+        `type.__new__` was called in such a manner that the class would already be sufficiently initialized.
+
+        This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
+        any kwargs passed to the class definition that aren't used internally by Pydantic.
+
+        Args:
+            **kwargs: Any keyword arguments passed to the class definition that aren't used internally
+                by Pydantic.
+
+        Note:
+            You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
+            instead, which is called once the class and its fields are fully initialized and ready for validation.
+        """
+
+    @classmethod
+    def __pydantic_on_complete__(cls) -> None:
+        """This is called once the class and its fields are fully initialized and ready to be used.
+
+        This typically happens when the class is created (just before
+        [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
+        except when forward annotations are used that could not immediately be resolved.
+        In that case, it will be called later, when the model is rebuilt automatically or explicitly using
+        [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
+        """
+
+    def __class_getitem__(
+        cls, typevar_values: type[Any] | tuple[type[Any], ...]
+    ) -> type[BaseModel] | _forward_ref.PydanticRecursiveRef:
+        cached = _generics.get_cached_generic_type_early(cls, typevar_values)
+        if cached is not None:
+            return cached
+
+        if cls is BaseModel:
+            raise TypeError('Type parameters should be placed on typing.Generic, not BaseModel')
+        if not hasattr(cls, '__parameters__'):
+            raise TypeError(f'{cls} cannot be parametrized because it does not inherit from typing.Generic')
+        if not cls.__pydantic_generic_metadata__['parameters'] and Generic not in cls.__bases__:
+            raise TypeError(f'{cls} is not a generic class')
+
+        if not isinstance(typevar_values, tuple):
+            typevar_values = (typevar_values,)
+
+        # For a model `class Model[T, U, V = int](BaseModel): ...` parametrized with `(str, bool)`,
+        # this gives us `{T: str, U: bool, V: int}`:
+        typevars_map = _generics.map_generic_model_arguments(cls, typevar_values)
+        # We also update the provided args to use defaults values (`(str, bool)` becomes `(str, bool, int)`):
+        typevar_values = tuple(v for v in typevars_map.values())
+
+        if _utils.all_identical(typevars_map.keys(), typevars_map.values()) and typevars_map:
+            submodel = cls  # if arguments are equal to parameters it's the same object
+            _generics.set_cached_generic_type(cls, typevar_values, submodel)
+        else:
+            parent_args = cls.__pydantic_generic_metadata__['args']
+            if not parent_args:
+                args = typevar_values
+            else:
+                args = tuple(_generics.replace_types(arg, typevars_map) for arg in parent_args)
+
+            origin = cls.__pydantic_generic_metadata__['origin'] or cls
+            model_name = origin.model_parametrized_name(args)
+            params = tuple(
+                dict.fromkeys(_generics.iter_contained_typevars(typevars_map.values()))
+            )  # use dict as ordered set
+
+            with _generics.generic_recursion_self_type(origin, args) as maybe_self_type:
+                cached = _generics.get_cached_generic_type_late(cls, typevar_values, origin, args)
+                if cached is not None:
+                    return cached
+
+                if maybe_self_type is not None:
+                    return maybe_self_type
+
+                # Attempt to rebuild the origin in case new types have been defined
+                try:
+                    # depth 2 gets you above this __class_getitem__ call.
+                    # Note that we explicitly provide the parent ns, otherwise
+                    # `model_rebuild` will use the parent ns no matter if it is the ns of a module.
+                    # We don't want this here, as this has unexpected effects when a model
+                    # is being parametrized during a forward annotation evaluation.
+                    parent_ns = _typing_extra.parent_frame_namespace(parent_depth=2) or {}
+                    origin.model_rebuild(_types_namespace=parent_ns)
+                except PydanticUndefinedAnnotation:
+                    # It's okay if it fails, it just means there are still undefined types
+                    # that could be evaluated later.
+                    pass
+
+                submodel = _generics.create_generic_submodel(model_name, origin, args, params)
+
+                _generics.set_cached_generic_type(cls, typevar_values, submodel, origin, args)
+
+        return submodel
+
+    def __copy__(self) -> Self:
+        """Returns a shallow copy of the model."""
+        cls = type(self)
+        m = cls.__new__(cls)
+        _object_setattr(m, '__dict__', copy(self.__dict__))
+        _object_setattr(m, '__pydantic_extra__', copy(self.__pydantic_extra__))
+        _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))
+
+        if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
+            _object_setattr(m, '__pydantic_private__', None)
+        else:
+            _object_setattr(
+                m,
+                '__pydantic_private__',
+                {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined},
+            )
+
+        return m
+
+    def __deepcopy__(self, memo: dict[int, Any] | None = None) -> Self:
+        """Returns a deep copy of the model."""
+        cls = type(self)
+        m = cls.__new__(cls)
+        _object_setattr(m, '__dict__', deepcopy(self.__dict__, memo=memo))
+        _object_setattr(m, '__pydantic_extra__', deepcopy(self.__pydantic_extra__, memo=memo))
+        # This next line doesn't need a deepcopy because __pydantic_fields_set__ is a set[str],
+        # and attempting a deepcopy would be marginally slower.
+        _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))
+
+        if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
+            _object_setattr(m, '__pydantic_private__', None)
+        else:
+            _object_setattr(
+                m,
+                '__pydantic_private__',
+                deepcopy({k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}, memo=memo),
+            )
+
+        return m
+
+    if not TYPE_CHECKING:
+        # We put `__getattr__` in a non-TYPE_CHECKING block because otherwise, mypy allows arbitrary attribute access
+        # The same goes for __setattr__ and __delattr__, see: https://github.com/pydantic/pydantic/issues/8643
+
+        def __getattr__(self, item: str) -> Any:
+            private_attributes = object.__getattribute__(self, '__private_attributes__')
+            if item in private_attributes:
+                attribute = private_attributes[item]
+                if hasattr(attribute, '__get__'):
+                    return attribute.__get__(self, type(self))  # type: ignore
+
+                try:
+                    # Note: self.__pydantic_private__ cannot be None if self.__private_attributes__ has items
+                    return self.__pydantic_private__[item]  # type: ignore
+                except KeyError as exc:
+                    raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}') from exc
+            else:
+                # `__pydantic_extra__` can fail to be set if the model is not yet fully initialized.
+                # See `BaseModel.__repr_args__` for more details
+                try:
+                    pydantic_extra = object.__getattribute__(self, '__pydantic_extra__')
+                except AttributeError:
+                    pydantic_extra = None
+
+                if pydantic_extra and item in pydantic_extra:
+                    return pydantic_extra[item]
+                else:
+                    if hasattr(self.__class__, item):
+                        return super().__getattribute__(item)  # Raises AttributeError if appropriate
+                    else:
+                        # this is the current error
+                        raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}')
+
+        def __setattr__(self, name: str, value: Any) -> None:
+            if (setattr_handler := self.__pydantic_setattr_handlers__.get(name)) is not None:
+                setattr_handler(self, name, value)
+            # if None is returned from _setattr_handler, the attribute was set directly
+            elif (setattr_handler := self._setattr_handler(name, value)) is not None:
+                setattr_handler(self, name, value)  # call here to not memo on possibly unknown fields
+                self.__pydantic_setattr_handlers__[name] = setattr_handler  # memoize the handler for faster access
+
+        def _setattr_handler(self, name: str, value: Any) -> Callable[[BaseModel, str, Any], None] | None:
+            """Get a handler for setting an attribute on the model instance.
+
+            Returns:
+                A handler for setting an attribute on the model instance. Used for memoization of the handler.
+                Memoizing the handlers leads to a dramatic performance improvement in `__setattr__`
+                Returns `None` when memoization is not safe, then the attribute is set directly.
+            """
+            cls = self.__class__
+            if name in cls.__class_vars__:
+                raise AttributeError(
+                    f'{name!r} is a ClassVar of `{cls.__name__}` and cannot be set on an instance. '
+                    f'If you want to set a value on the class, use `{cls.__name__}.{name} = value`.'
+                )
+            elif not _fields.is_valid_field_name(name):
+                if (attribute := cls.__private_attributes__.get(name)) is not None:
+                    if hasattr(attribute, '__set__'):
+                        return lambda model, _name, val: attribute.__set__(model, val)
+                    else:
+                        return _SIMPLE_SETATTR_HANDLERS['private']
+                else:
+                    _object_setattr(self, name, value)
+                    return None  # Can not return memoized handler with possibly freeform attr names
+
+            attr = getattr(cls, name, None)
+            # NOTE: We currently special case properties and `cached_property`, but we might need
+            # to generalize this to all data/non-data descriptors at some point. For non-data descriptors
+            # (such as `cached_property`), it isn't obvious though. `cached_property` caches the value
+            # to the instance's `__dict__`, but other non-data descriptors might do things differently.
+            if isinstance(attr, cached_property):
+                return _SIMPLE_SETATTR_HANDLERS['cached_property']
+
+            _check_frozen(cls, name, value)
+
+            # We allow properties to be set only on non frozen models for now (to match dataclasses).
+            # This can be changed if it ever gets requested.
+            if isinstance(attr, property):
+                return lambda model, _name, val: attr.__set__(model, val)
+            elif cls.model_config.get('validate_assignment'):
+                return _SIMPLE_SETATTR_HANDLERS['validate_assignment']
+            elif name not in cls.__pydantic_fields__:
+                if cls.model_config.get('extra') != 'allow':
+                    # TODO - matching error
+                    raise ValueError(f'"{cls.__name__}" object has no field "{name}"')
+                elif attr is None:
+                    # attribute does not exist, so put it in extra
+                    self.__pydantic_extra__[name] = value
+                    return None  # Can not return memoized handler with possibly freeform attr names
+                else:
+                    # attribute _does_ exist, and was not in extra, so update it
+                    return _SIMPLE_SETATTR_HANDLERS['extra_known']
+            else:
+                return _SIMPLE_SETATTR_HANDLERS['model_field']
+
+        def __delattr__(self, item: str) -> Any:
+            cls = self.__class__
+
+            if item in self.__private_attributes__:
+                attribute = self.__private_attributes__[item]
+                if hasattr(attribute, '__delete__'):
+                    attribute.__delete__(self)  # type: ignore
+                    return
+
+                try:
+                    # Note: self.__pydantic_private__ cannot be None if self.__private_attributes__ has items
+                    del self.__pydantic_private__[item]  # type: ignore
+                    return
+                except KeyError as exc:
+                    raise AttributeError(f'{cls.__name__!r} object has no attribute {item!r}') from exc
+
+            # Allow cached properties to be deleted (even if the class is frozen):
+            attr = getattr(cls, item, None)
+            if isinstance(attr, cached_property):
+                return object.__delattr__(self, item)
+
+            _check_frozen(cls, name=item, value=None)
+
+            if item in self.__pydantic_fields__:
+                object.__delattr__(self, item)
+            elif self.__pydantic_extra__ is not None and item in self.__pydantic_extra__:
+                del self.__pydantic_extra__[item]
+            else:
+                try:
+                    object.__delattr__(self, item)
+                except AttributeError:
+                    raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}')
+
+        # Because we make use of `@dataclass_transform()`, `__replace__` is already synthesized by
+        # type checkers, so we define the implementation in this `if not TYPE_CHECKING:` block:
+        def __replace__(self, **changes: Any) -> Self:
+            return self.model_copy(update=changes)
+
+    def __getstate__(self) -> dict[Any, Any]:
+        private = self.__pydantic_private__
+        if private:
+            private = {k: v for k, v in private.items() if v is not PydanticUndefined}
+        return {
+            '__dict__': self.__dict__,
+            '__pydantic_extra__': self.__pydantic_extra__,
+            '__pydantic_fields_set__': self.__pydantic_fields_set__,
+            '__pydantic_private__': private,
+        }
+
+    def __setstate__(self, state: dict[Any, Any]) -> None:
+        _object_setattr(self, '__pydantic_fields_set__', state.get('__pydantic_fields_set__', {}))
+        _object_setattr(self, '__pydantic_extra__', state.get('__pydantic_extra__', {}))
+        _object_setattr(self, '__pydantic_private__', state.get('__pydantic_private__', {}))
+        _object_setattr(self, '__dict__', state.get('__dict__', {}))
+
+    if not TYPE_CHECKING:
+
+        def __eq__(self, other: Any) -> bool:
+            if isinstance(other, BaseModel):
+                # When comparing instances of generic types for equality, as long as all field values are equal,
+                # only require their generic origin types to be equal, rather than exact type equality.
+                # This prevents headaches like MyGeneric(x=1) != MyGeneric[Any](x=1).
+                self_type = self.__pydantic_generic_metadata__['origin'] or self.__class__
+                other_type = other.__pydantic_generic_metadata__['origin'] or other.__class__
+
+                # Perform common checks first
+                if not (
+                    self_type == other_type
+                    and getattr(self, '__pydantic_private__', None) == getattr(other, '__pydantic_private__', None)
+                    and self.__pydantic_extra__ == other.__pydantic_extra__
+                ):
+                    return False
+
+                # We only want to compare pydantic fields but ignoring fields is costly.
+                # We'll perform a fast check first, and fallback only when needed
+                # See GH-7444 and GH-7825 for rationale and a performance benchmark
+
+                # First, do the fast (and sometimes faulty) __dict__ comparison
+                if self.__dict__ == other.__dict__:
+                    # If the check above passes, then pydantic fields are equal, we can return early
+                    return True
+
+                # We don't want to trigger unnecessary costly filtering of __dict__ on all unequal objects, so we return
+                # early if there are no keys to ignore (we would just return False later on anyway)
+                model_fields = type(self).__pydantic_fields__.keys()
+                if self.__dict__.keys() <= model_fields and other.__dict__.keys() <= model_fields:
+                    return False
+
+                # If we reach here, there are non-pydantic-fields keys, mapped to unequal values, that we need to ignore
+                # Resort to costly filtering of the __dict__ objects
+                # We use operator.itemgetter because it is much faster than dict comprehensions
+                # NOTE: Contrary to standard python class and instances, when the Model class has a default value for an
+                # attribute and the model instance doesn't have a corresponding attribute, accessing the missing attribute
+                # raises an error in BaseModel.__getattr__ instead of returning the class attribute
+                # So we can use operator.itemgetter() instead of operator.attrgetter()
+                getter = operator.itemgetter(*model_fields) if model_fields else lambda _: _utils._SENTINEL
+                try:
+                    return getter(self.__dict__) == getter(other.__dict__)
+                except KeyError:
+                    # In rare cases (such as when using the deprecated BaseModel.copy() method),
+                    # the __dict__ may not contain all model fields, which is how we can get here.
+                    # getter(self.__dict__) is much faster than any 'safe' method that accounts
+                    # for missing keys, and wrapping it in a `try` doesn't slow things down much
+                    # in the common case.
+                    self_fields_proxy = _utils.SafeGetItemProxy(self.__dict__)
+                    other_fields_proxy = _utils.SafeGetItemProxy(other.__dict__)
+                    return getter(self_fields_proxy) == getter(other_fields_proxy)
+
+            # other instance is not a BaseModel
+            else:
+                return NotImplemented  # delegate to the other item in the comparison
+
+    if TYPE_CHECKING:
+        # We put `__init_subclass__` in a TYPE_CHECKING block because, even though we want the type-checking benefits
+        # described in the signature of `__init_subclass__` below, we don't want to modify the default behavior of
+        # subclass initialization.
+
+        def __init_subclass__(cls, **kwargs: Unpack[ConfigDict]):
+            """This signature is included purely to help type-checkers check arguments to class declaration, which
+            provides a way to conveniently set model_config key/value pairs.
+
+            ```python
+            from pydantic import BaseModel
+
+            class MyModel(BaseModel, extra='allow'): ...
+            ```
+
+            However, this may be deceiving, since the _actual_ calls to `__init_subclass__` will not receive any
+            of the config arguments, and will only receive any keyword arguments passed during class initialization
+            that are _not_ expected keys in ConfigDict. (This is due to the way `ModelMetaclass.__new__` works.)
+
+            Args:
+                **kwargs: Keyword arguments passed to the class definition, which set model_config
+
+            Note:
+                You may want to override `__pydantic_init_subclass__` instead, which behaves similarly but is called
+                *after* the class is fully initialized.
+            """
+
+    def __iter__(self) -> TupleGenerator:
+        """So `dict(model)` works."""
+        yield from [(k, v) for (k, v) in self.__dict__.items() if not k.startswith('_')]
+        extra = self.__pydantic_extra__
+        if extra:
+            yield from extra.items()
+
+    def __repr__(self) -> str:
+        return f'{self.__repr_name__()}({self.__repr_str__(", ")})'
+
+    def __repr_args__(self) -> _repr.ReprArgs:
+        # Eagerly create the repr of computed fields, as this may trigger access of cached properties and as such
+        # modify the instance's `__dict__`. If we don't do it now, it could happen when iterating over the `__dict__`
+        # below if the instance happens to be referenced in a field, and would modify the `__dict__` size *during* iteration.
+        computed_fields_repr_args = [
+            (k, getattr(self, k)) for k, v in self.__pydantic_computed_fields__.items() if v.repr
+        ]
+
+        for k, v in self.__dict__.items():
+            field = self.__pydantic_fields__.get(k)
+            if field and field.repr:
+                if v is not self:
+                    yield k, v
+                else:
+                    yield k, self.__repr_recursion__(v)
+        # `__pydantic_extra__` can fail to be set if the model is not yet fully initialized.
+        # This can happen if a `ValidationError` is raised during initialization and the instance's
+        # repr is generated as part of the exception handling. Therefore, we use `getattr` here
+        # with a fallback, even though the type hints indicate the attribute will always be present.
+        try:
+            pydantic_extra = object.__getattribute__(self, '__pydantic_extra__')
+        except AttributeError:
+            pydantic_extra = None
+
+        if pydantic_extra is not None:
+            yield from ((k, v) for k, v in pydantic_extra.items())
+        yield from computed_fields_repr_args
+
+    # take logic from `_repr.Representation` without the side effects of inheritance, see #5740
+    __repr_name__ = _repr.Representation.__repr_name__
+    __repr_recursion__ = _repr.Representation.__repr_recursion__
+    __repr_str__ = _repr.Representation.__repr_str__
+    __pretty__ = _repr.Representation.__pretty__
+    __rich_repr__ = _repr.Representation.__rich_repr__
+
+    def __str__(self) -> str:
+        return self.__repr_str__(' ')
+
+    # ##### Deprecated methods from v1 #####
+    @property
+    @typing_extensions.deprecated(
+        'The `__fields__` attribute is deprecated, use the `model_fields` class property instead.', category=None
+    )
+    def __fields__(self) -> dict[str, FieldInfo]:
+        warnings.warn(
+            'The `__fields__` attribute is deprecated, use the `model_fields` class property instead.',
+            category=PydanticDeprecatedSince20,
+            stacklevel=2,
+        )
+        return getattr(type(self), '__pydantic_fields__', {})
+
+    @property
+    @typing_extensions.deprecated(
+        'The `__fields_set__` attribute is deprecated, use `model_fields_set` instead.',
+        category=None,
+    )
+    def __fields_set__(self) -> set[str]:
+        warnings.warn(
+            'The `__fields_set__` attribute is deprecated, use `model_fields_set` instead.',
+            category=PydanticDeprecatedSince20,
+            stacklevel=2,
+        )
+        return self.__pydantic_fields_set__
+
+    @typing_extensions.deprecated('The `dict` method is deprecated; use `model_dump` instead.', category=None)
+    def dict(  # noqa: D102
+        self,
+        *,
+        include: IncEx | None = None,
+        exclude: IncEx | None = None,
+        by_alias: bool = False,
+        exclude_unset: bool = False,
+        exclude_defaults: bool = False,
+        exclude_none: bool = False,
+    ) -> Dict[str, Any]:  # noqa UP006
+        warnings.warn(
+            'The `dict` method is deprecated; use `model_dump` instead.',
+            category=PydanticDeprecatedSince20,
+            stacklevel=2,
+        )
+        return self.model_dump(
+            include=include,
+            exclude=exclude,
+            by_alias=by_alias,
+            exclude_unset=exclude_unset,
+            exclude_defaults=exclude_defaults,
+            exclude_none=exclude_none,
+        )
+
+    @typing_extensions.deprecated('The `json` method is deprecated; use `model_dump_json` instead.', category=None)
+    def json(  # noqa: D102
+        self,
+        *,
+        include: IncEx | None = None,
+        exclude: IncEx | None = None,
+        by_alias: bool = False,
+        exclude_unset: bool = False,
+        exclude_defaults: bool = False,
+        exclude_none: bool = False,
+        encoder: Callable[[Any], Any] | None = PydanticUndefined,  # type: ignore[assignment]
+        models_as_dict: bool = PydanticUndefined,  # type: ignore[assignment]
+        **dumps_kwargs: Any,
+    ) -> str:
+        warnings.warn(
+            'The `json` method is deprecated; use `model_dump_json` instead.',
+            category=PydanticDeprecatedSince20,
+            stacklevel=2,
+        )
+        if encoder is not PydanticUndefined:
+            raise TypeError('The `encoder` argument is no longer supported; use field serializers instead.')
+        if models_as_dict is not PydanticUndefined:
+            raise TypeError('The `models_as_dict` argument is no longer supported; use a model serializer instead.')
+        if dumps_kwargs:
+            raise TypeError('`dumps_kwargs` keyword arguments are no longer supported.')
+        return self.model_dump_json(
+            include=include,
+            exclude=exclude,
+            by_alias=by_alias,
+            exclude_unset=exclude_unset,
+            exclude_defaults=exclude_defaults,
+            exclude_none=exclude_none,
+        )
+
+    @classmethod
+    @typing_extensions.deprecated('The `parse_obj` method is deprecated; use `model_validate` instead.', category=None)
+    def parse_obj(cls, obj: Any) -> Self:  # noqa: D102
+        warnings.warn(
+            'The `parse_obj` method is deprecated; use `model_validate` instead.',
+            category=PydanticDeprecatedSince20,
+            stacklevel=2,
+        )
+        return cls.model_validate(obj)
+
+    @classmethod
+    @typing_extensions.deprecated(
+        'The `parse_raw` method is deprecated; if your data is JSON use `model_validate_json`, '
+        'otherwise load the data then use `model_validate` instead.',
+        category=None,
+    )
+    def parse_raw(  # noqa: D102
+        cls,
+        b: str | bytes,
+        *,
+        content_type: str | None = None,
+        encoding: str = 'utf8',
+        proto: DeprecatedParseProtocol | None = None,
+        allow_pickle: bool = False,
+    ) -> Self:  # pragma: no cover
+        warnings.warn(
+            'The `parse_raw` method is deprecated; if your data is JSON use `model_validate_json`, '
+            'otherwise load the data then use `model_validate` instead.',
+            category=PydanticDeprecatedSince20,
+            stacklevel=2,
+        )
+        from .deprecated import parse
+
+        try:
+            obj = parse.load_str_bytes(
+                b,
+                proto=proto,
+                content_type=content_type,
+                encoding=encoding,
+                allow_pickle=allow_pickle,
+            )
+        except (ValueError, TypeError) as exc:
+            import json
+
+            # try to match V1
+            if isinstance(exc, UnicodeDecodeError):
+                type_str = 'value_error.unicodedecode'
+            elif isinstance(exc, json.JSONDecodeError):
+                type_str = 'value_error.jsondecode'
+            elif isinstance(exc, ValueError):
+                type_str = 'value_error'
+            else:
+                type_str = 'type_error'
+
+            # ctx is missing here, but since we've added `input` to the error, we're not pretending it's the same
+            error: pydantic_core.InitErrorDetails = {
+                # The type: ignore on the next line is to ignore the requirement of LiteralString
+                'type': pydantic_core.PydanticCustomError(type_str, str(exc)),  # type: ignore
+                'loc': ('__root__',),
+                'input': b,
+            }
+            raise pydantic_core.ValidationError.from_exception_data(cls.__name__, [error])
+        return cls.model_validate(obj)
+
+    @classmethod
+    @typing_extensions.deprecated(
+        'The `parse_file` method is deprecated; load the data from file, then if your data is JSON '
+        'use `model_validate_json`, otherwise `model_validate` instead.',
+        category=None,
+    )
+    def parse_file(  # noqa: D102
+        cls,
+        path: str | Path,
+        *,
+        content_type: str | None = None,
+        encoding: str = 'utf8',
+        proto: DeprecatedParseProtocol | None = None,
+        allow_pickle: bool = False,
+    ) -> Self:
+        warnings.warn(
+            'The `parse_file` method is deprecated; load the data from file, then if your data is JSON '
+            'use `model_validate_json`, otherwise `model_validate` instead.',
+            category=PydanticDeprecatedSince20,
+            stacklevel=2,
+        )
+        from .deprecated import parse
+
+        obj = parse.load_file(
+            path,
+            proto=proto,
+            content_type=content_type,
+            encoding=encoding,
+            allow_pickle=allow_pickle,
+        )
+        return cls.parse_obj(obj)
+
+    @classmethod
+    @typing_extensions.deprecated(
+        'The `from_orm` method is deprecated; set '
+        "`model_config['from_attributes']=True` and use `model_validate` instead.",
+        category=None,
+    )
+    def from_orm(cls, obj: Any) -> Self:  # noqa: D102
+        warnings.warn(
+            'The `from_orm` method is deprecated; set '
+            "`model_config['from_attributes']=True` and use `model_validate` instead.",
+            category=PydanticDeprecatedSince20,
+            stacklevel=2,
+        )
+        if not cls.model_config.get('from_attributes', None):
+            raise PydanticUserError(
+                'You must set the config attribute `from_attributes=True` to use from_orm', code=None
+            )
+        return cls.model_validate(obj)
+
+    @classmethod
+    @typing_extensions.deprecated('The `construct` method is deprecated; use `model_construct` instead.', category=None)
+    def construct(cls, _fields_set: set[str] | None = None, **values: Any) -> Self:  # noqa: D102
+        warnings.warn(
+            'The `construct` method is deprecated; use `model_construct` instead.',
+            category=PydanticDeprecatedSince20,
+            stacklevel=2,
+        )
+        return cls.model_construct(_fields_set=_fields_set, **values)
+
+    @typing_extensions.deprecated(
+        'The `copy` method is deprecated; use `model_copy` instead. '
+        'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
+        category=None,
+    )
+    def copy(
+        self,
+        *,
+        include: AbstractSetIntStr | MappingIntStrAny | None = None,
+        exclude: AbstractSetIntStr | MappingIntStrAny | None = None,
+        update: Dict[str, Any] | None = None,  # noqa UP006
+        deep: bool = False,
+    ) -> Self:  # pragma: no cover
+        """Returns a copy of the model.
+
+        !!! warning "Deprecated"
+            This method is now deprecated; use `model_copy` instead.
+
+        If you need `include` or `exclude`, use:
+
+        ```python {test="skip" lint="skip"}
+        data = self.model_dump(include=include, exclude=exclude, round_trip=True)
+        data = {**data, **(update or {})}
+        copied = self.model_validate(data)
+        ```
+
+        Args:
+            include: Optional set or mapping specifying which fields to include in the copied model.
+            exclude: Optional set or mapping specifying which fields to exclude in the copied model.
+            update: Optional dictionary of field-value pairs to override field values in the copied model.
+            deep: If True, the values of fields that are Pydantic models will be deep-copied.
+
+        Returns:
+            A copy of the model with included, excluded and updated fields as specified.
+        """
+        warnings.warn(
+            'The `copy` method is deprecated; use `model_copy` instead. '
+            'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
+            category=PydanticDeprecatedSince20,
+            stacklevel=2,
+        )
+        from .deprecated import copy_internals
+
+        values = dict(
+            copy_internals._iter(
+                self, to_dict=False, by_alias=False, include=include, exclude=exclude, exclude_unset=False
+            ),
+            **(update or {}),
+        )
+        if self.__pydantic_private__ is None:
+            private = None
+        else:
+            private = {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}
+
+        if self.__pydantic_extra__ is None:
+            extra: dict[str, Any] | None = None
+        else:
+            extra = self.__pydantic_extra__.copy()
+            for k in list(self.__pydantic_extra__):
+                if k not in values:  # k was in the exclude
+                    extra.pop(k)
+            for k in list(values):
+                if k in self.__pydantic_extra__:  # k must have come from extra
+                    extra[k] = values.pop(k)
+
+        # new `__pydantic_fields_set__` can have unset optional fields with a set value in `update` kwarg
+        if update:
+            fields_set = self.__pydantic_fields_set__ | update.keys()
+        else:
+            fields_set = set(self.__pydantic_fields_set__)
+
+        # removing excluded fields from `__pydantic_fields_set__`
+        if exclude:
+            fields_set -= set(exclude)
+
+        return copy_internals._copy_and_set_values(self, values, fields_set, extra, private, deep=deep)
+
+    @classmethod
+    @typing_extensions.deprecated('The `schema` method is deprecated; use `model_json_schema` instead.', category=None)
+    def schema(  # noqa: D102
+        cls, by_alias: bool = True, ref_template: str = DEFAULT_REF_TEMPLATE
+    ) -> Dict[str, Any]:  # noqa UP006
+        warnings.warn(
+            'The `schema` method is deprecated; use `model_json_schema` instead.',
+            category=PydanticDeprecatedSince20,
+            stacklevel=2,
+        )
+        return cls.model_json_schema(by_alias=by_alias, ref_template=ref_template)
+
+    @classmethod
+    @typing_extensions.deprecated(
+        'The `schema_json` method is deprecated; use `model_json_schema` and json.dumps instead.',
+        category=None,
+    )
+    def schema_json(  # noqa: D102
+        cls, *, by_alias: bool = True, ref_template: str = DEFAULT_REF_TEMPLATE, **dumps_kwargs: Any
+    ) -> str:  # pragma: no cover
+        warnings.warn(
+            'The `schema_json` method is deprecated; use `model_json_schema` and json.dumps instead.',
+            category=PydanticDeprecatedSince20,
+            stacklevel=2,
+        )
+        import json
+
+        from .deprecated.json import pydantic_encoder
+
+        return json.dumps(
+            cls.model_json_schema(by_alias=by_alias, ref_template=ref_template),
+            default=pydantic_encoder,
+            **dumps_kwargs,
+        )
+
+    @classmethod
+    @typing_extensions.deprecated('The `validate` method is deprecated; use `model_validate` instead.', category=None)
+    def validate(cls, value: Any) -> Self:  # noqa: D102
+        warnings.warn(
+            'The `validate` method is deprecated; use `model_validate` instead.',
+            category=PydanticDeprecatedSince20,
+            stacklevel=2,
+        )
+        return cls.model_validate(value)
+
+    @classmethod
+    @typing_extensions.deprecated(
+        'The `update_forward_refs` method is deprecated; use `model_rebuild` instead.',
+        category=None,
+    )
+    def update_forward_refs(cls, **localns: Any) -> None:  # noqa: D102
+        warnings.warn(
+            'The `update_forward_refs` method is deprecated; use `model_rebuild` instead.',
+            category=PydanticDeprecatedSince20,
+            stacklevel=2,
+        )
+        if localns:  # pragma: no cover
+            raise TypeError('`localns` arguments are not longer accepted.')
+        cls.model_rebuild(force=True)
+
+    @typing_extensions.deprecated(
+        'The private method `_iter` will be removed and should no longer be used.', category=None
+    )
+    def _iter(self, *args: Any, **kwargs: Any) -> Any:
+        warnings.warn(
+            'The private method `_iter` will be removed and should no longer be used.',
+            category=PydanticDeprecatedSince20,
+            stacklevel=2,
+        )
+        from .deprecated import copy_internals
+
+        return copy_internals._iter(self, *args, **kwargs)
+
+    @typing_extensions.deprecated(
+        'The private method `_copy_and_set_values` will be removed and should no longer be used.',
+        category=None,
+    )
+    def _copy_and_set_values(self, *args: Any, **kwargs: Any) -> Any:
+        warnings.warn(
+            'The private method `_copy_and_set_values` will be removed and should no longer be used.',
+            category=PydanticDeprecatedSince20,
+            stacklevel=2,
+        )
+        from .deprecated import copy_internals
+
+        return copy_internals._copy_and_set_values(self, *args, **kwargs)
+
+    @classmethod
+    @typing_extensions.deprecated(
+        'The private method `_get_value` will be removed and should no longer be used.',
+        category=None,
+    )
+    def _get_value(cls, *args: Any, **kwargs: Any) -> Any:
+        warnings.warn(
+            'The private method `_get_value` will be removed and should no longer be used.',
+            category=PydanticDeprecatedSince20,
+            stacklevel=2,
+        )
+        from .deprecated import copy_internals
+
+        return copy_internals._get_value(cls, *args, **kwargs)
+
+    @typing_extensions.deprecated(
+        'The private method `_calculate_keys` will be removed and should no longer be used.',
+        category=None,
+    )
+    def _calculate_keys(self, *args: Any, **kwargs: Any) -> Any:
+        warnings.warn(
+            'The private method `_calculate_keys` will be removed and should no longer be used.',
+            category=PydanticDeprecatedSince20,
+            stacklevel=2,
+        )
+        from .deprecated import copy_internals
+
+        return copy_internals._calculate_keys(self, *args, **kwargs)
+
+
+ModelT = TypeVar('ModelT', bound=BaseModel)
+
+
+@overload
+def create_model(
+    model_name: str,
+    /,
+    *,
+    __config__: ConfigDict | None = None,
+    __doc__: str | None = None,
+    __base__: None = None,
+    __module__: str = __name__,
+    __validators__: dict[str, Callable[..., Any]] | None = None,
+    __cls_kwargs__: dict[str, Any] | None = None,
+    __qualname__: str | None = None,
+    **field_definitions: Any | tuple[str, Any],
+) -> type[BaseModel]: ...
+
+
+@overload
+def create_model(
+    model_name: str,
+    /,
+    *,
+    __config__: ConfigDict | None = None,
+    __doc__: str | None = None,
+    __base__: type[ModelT] | tuple[type[ModelT], ...],
+    __module__: str = __name__,
+    __validators__: dict[str, Callable[..., Any]] | None = None,
+    __cls_kwargs__: dict[str, Any] | None = None,
+    __qualname__: str | None = None,
+    **field_definitions: Any | tuple[str, Any],
+) -> type[ModelT]: ...
+
+
+def create_model(  # noqa: C901
+    model_name: str,
+    /,
+    *,
+    __config__: ConfigDict | None = None,
+    __doc__: str | None = None,
+    __base__: type[ModelT] | tuple[type[ModelT], ...] | None = None,
+    __module__: str | None = None,
+    __validators__: dict[str, Callable[..., Any]] | None = None,
+    __cls_kwargs__: dict[str, Any] | None = None,
+    __qualname__: str | None = None,
+    # TODO PEP 747: replace `Any` by the TypeForm:
+    **field_definitions: Any | tuple[str, Any],
+) -> type[ModelT]:
+    """!!! abstract "Usage Documentation"
+        [Dynamic Model Creation](../concepts/models.md#dynamic-model-creation)
+
+    Dynamically creates and returns a new Pydantic model, in other words, `create_model` dynamically creates a
+    subclass of [`BaseModel`][pydantic.BaseModel].
+
+    !!! warning
+        This function may execute arbitrary code contained in field annotations, if string references need to be evaluated.
+
+        See [Security implications of introspecting annotations](https://docs.python.org/3/library/annotationlib.html#annotationlib-security) for more information.
+
+    Args:
+        model_name: The name of the newly created model.
+        __config__: The configuration of the new model.
+        __doc__: The docstring of the new model.
+        __base__: The base class or classes for the new model.
+        __module__: The name of the module that the model belongs to;
+            if `None`, the value is taken from `sys._getframe(1)`
+        __validators__: A dictionary of methods that validate fields. The keys are the names of the validation methods to
+            be added to the model, and the values are the validation methods themselves. You can read more about functional
+            validators [here](https://docs.pydantic.dev/2.9/concepts/validators/#field-validators).
+        __cls_kwargs__: A dictionary of keyword arguments for class creation, such as `metaclass`.
+        __qualname__: The qualified name of the newly created model.
+        **field_definitions: Field definitions of the new model. Either:
+
+            - a single element, representing the type annotation of the field.
+            - a two-tuple, the first element being the type and the second element the assigned value
+              (either a default or the [`Field()`][pydantic.Field] function).
+
+    Returns:
+        The new [model][pydantic.BaseModel].
+
+    Raises:
+        PydanticUserError: If `__base__` and `__config__` are both passed.
+    """
+    if __base__ is None:
+        __base__ = (cast('type[ModelT]', BaseModel),)
+    elif not isinstance(__base__, tuple):
+        __base__ = (__base__,)
+
+    __cls_kwargs__ = __cls_kwargs__ or {}
+
+    fields: dict[str, Any] = {}
+    annotations: dict[str, Any] = {}
+
+    for f_name, f_def in field_definitions.items():
+        if isinstance(f_def, tuple):
+            if len(f_def) != 2:
+                raise PydanticUserError(
+                    f'Field definition for {f_name!r} should a single element representing the type or a two-tuple, the first element '
+                    'being the type and the second element the assigned value (either a default or the `Field()` function).',
+                    code='create-model-field-definitions',
+                )
+
+            annotations[f_name] = f_def[0]
+            fields[f_name] = f_def[1]
+        else:
+            annotations[f_name] = f_def
+
+    if __module__ is None:
+        f = sys._getframe(1)
+        __module__ = f.f_globals['__name__']
+
+    namespace: dict[str, Any] = {'__annotations__': annotations, '__module__': __module__}
+    if __doc__:
+        namespace['__doc__'] = __doc__
+    if __qualname__ is not None:
+        namespace['__qualname__'] = __qualname__
+    if __validators__:
+        namespace.update(__validators__)
+    namespace.update(fields)
+    if __config__:
+        namespace['model_config'] = __config__
+    resolved_bases = types.resolve_bases(__base__)
+    meta, ns, kwds = types.prepare_class(model_name, resolved_bases, kwds=__cls_kwargs__)
+    if resolved_bases is not __base__:
+        ns['__orig_bases__'] = __base__
+    namespace.update(ns)
+
+    return meta(
+        model_name,
+        resolved_bases,
+        namespace,
+        __pydantic_reset_parent_namespace__=False,
+        _create_model_module=__module__,
+        **kwds,
+    )
+
+
+__getattr__ = getattr_migration(__name__)
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pydantic/mypy.py b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/mypy.py
new file mode 100644
index 0000000000000000000000000000000000000000..6e8228ef97e0943b8772c31edf54122668e331e3
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/mypy.py
@@ -0,0 +1,1374 @@
+"""This module includes classes and functions designed specifically for use with the mypy plugin."""
+
+from __future__ import annotations
+
+import sys
+from collections.abc import Iterator
+from configparser import ConfigParser
+from typing import Any, Callable
+
+from mypy.errorcodes import ErrorCode
+from mypy.expandtype import expand_type, expand_type_by_instance
+from mypy.nodes import (
+    ARG_NAMED,
+    ARG_NAMED_OPT,
+    ARG_OPT,
+    ARG_POS,
+    ARG_STAR2,
+    INVARIANT,
+    MDEF,
+    Argument,
+    AssignmentStmt,
+    Block,
+    CallExpr,
+    ClassDef,
+    Context,
+    Decorator,
+    DictExpr,
+    EllipsisExpr,
+    Expression,
+    FuncDef,
+    IfStmt,
+    JsonDict,
+    MemberExpr,
+    NameExpr,
+    PassStmt,
+    PlaceholderNode,
+    RefExpr,
+    Statement,
+    StrExpr,
+    SymbolTableNode,
+    TempNode,
+    TypeAlias,
+    TypeInfo,
+    Var,
+)
+from mypy.options import Options
+from mypy.plugin import (
+    CheckerPluginInterface,
+    ClassDefContext,
+    MethodContext,
+    Plugin,
+    ReportConfigContext,
+    SemanticAnalyzerPluginInterface,
+)
+from mypy.plugins.common import (
+    deserialize_and_fixup_type,
+)
+from mypy.semanal import set_callable_name
+from mypy.server.trigger import make_wildcard_trigger
+from mypy.state import state
+from mypy.type_visitor import TypeTranslator
+from mypy.typeops import map_type_from_supertype
+from mypy.types import (
+    AnyType,
+    CallableType,
+    Instance,
+    NoneType,
+    Type,
+    TypeOfAny,
+    TypeType,
+    TypeVarType,
+    UnionType,
+    get_proper_type,
+)
+from mypy.typevars import fill_typevars
+from mypy.util import get_unique_redefinition_name
+from mypy.version import __version__ as mypy_version
+
+from pydantic._internal import _fields
+from pydantic.version import parse_mypy_version
+
+CONFIGFILE_KEY = 'pydantic-mypy'
+METADATA_KEY = 'pydantic-mypy-metadata'
+BASEMODEL_FULLNAME = 'pydantic.main.BaseModel'
+BASESETTINGS_FULLNAME = 'pydantic_settings.main.BaseSettings'
+ROOT_MODEL_FULLNAME = 'pydantic.root_model.RootModel'
+MODEL_METACLASS_FULLNAME = 'pydantic._internal._model_construction.ModelMetaclass'
+FIELD_FULLNAME = 'pydantic.fields.Field'
+DATACLASS_FULLNAME = 'pydantic.dataclasses.dataclass'
+MODEL_VALIDATOR_FULLNAME = 'pydantic.functional_validators.model_validator'
+DECORATOR_FULLNAMES = {
+    'pydantic.functional_validators.field_validator',
+    'pydantic.functional_validators.model_validator',
+    'pydantic.functional_serializers.serializer',
+    'pydantic.functional_serializers.model_serializer',
+    'pydantic.deprecated.class_validators.validator',
+    'pydantic.deprecated.class_validators.root_validator',
+}
+IMPLICIT_CLASSMETHOD_DECORATOR_FULLNAMES = DECORATOR_FULLNAMES - {'pydantic.functional_serializers.model_serializer'}
+
+
+MYPY_VERSION_TUPLE = parse_mypy_version(mypy_version)
+BUILTINS_NAME = 'builtins'
+
+# Increment version if plugin changes and mypy caches should be invalidated
+__version__ = 2
+
+
+def plugin(version: str) -> type[Plugin]:
+    """`version` is the mypy version string.
+
+    We might want to use this to print a warning if the mypy version being used is
+    newer, or especially older, than we expect (or need).
+
+    Args:
+        version: The mypy version string.
+
+    Return:
+        The Pydantic mypy plugin type.
+    """
+    return PydanticPlugin
+
+
+class PydanticPlugin(Plugin):
+    """The Pydantic mypy plugin."""
+
+    def __init__(self, options: Options) -> None:
+        self.plugin_config = PydanticPluginConfig(options)
+        self._plugin_data = self.plugin_config.to_data()
+        super().__init__(options)
+
+    def get_base_class_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None:
+        """Update Pydantic model class."""
+        sym = self.lookup_fully_qualified(fullname)
+        if sym and isinstance(sym.node, TypeInfo):  # pragma: no branch
+            # No branching may occur if the mypy cache has not been cleared
+            if sym.node.has_base(BASEMODEL_FULLNAME):
+                return self._pydantic_model_class_maker_callback
+        return None
+
+    def get_metaclass_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None:
+        """Update Pydantic `ModelMetaclass` definition."""
+        if fullname == MODEL_METACLASS_FULLNAME:
+            return self._pydantic_model_metaclass_marker_callback
+        return None
+
+    def get_method_hook(self, fullname: str) -> Callable[[MethodContext], Type] | None:
+        """Adjust return type of `from_orm` method call."""
+        if fullname.endswith('.from_orm'):
+            return from_attributes_callback
+        return None
+
+    def report_config_data(self, ctx: ReportConfigContext) -> dict[str, Any]:
+        """Return all plugin config data.
+
+        Used by mypy to determine if cache needs to be discarded.
+        """
+        return self._plugin_data
+
+    def _pydantic_model_class_maker_callback(self, ctx: ClassDefContext) -> None:
+        transformer = PydanticModelTransformer(ctx.cls, ctx.reason, ctx.api, self.plugin_config)
+        transformer.transform()
+
+    def _pydantic_model_metaclass_marker_callback(self, ctx: ClassDefContext) -> None:
+        """Reset dataclass_transform_spec attribute of ModelMetaclass.
+
+        Let the plugin handle it. This behavior can be disabled
+        if 'debug_dataclass_transform' is set to True', for testing purposes.
+        """
+        if self.plugin_config.debug_dataclass_transform:
+            return
+        info_metaclass = ctx.cls.info.declared_metaclass
+        assert info_metaclass, "callback not passed from 'get_metaclass_hook'"
+        if getattr(info_metaclass.type, 'dataclass_transform_spec', None):
+            info_metaclass.type.dataclass_transform_spec = None
+
+
+class PydanticPluginConfig:
+    """A Pydantic mypy plugin config holder.
+
+    Attributes:
+        init_forbid_extra: Whether to add a `**kwargs` at the end of the generated `__init__` signature.
+        init_typed: Whether to annotate fields in the generated `__init__`.
+        warn_required_dynamic_aliases: Whether to raise required dynamic aliases error.
+        debug_dataclass_transform: Whether to not reset `dataclass_transform_spec` attribute
+            of `ModelMetaclass` for testing purposes.
+    """
+
+    __slots__ = (
+        'init_forbid_extra',
+        'init_typed',
+        'warn_required_dynamic_aliases',
+        'debug_dataclass_transform',
+    )
+    init_forbid_extra: bool
+    init_typed: bool
+    warn_required_dynamic_aliases: bool
+    debug_dataclass_transform: bool  # undocumented
+
+    def __init__(self, options: Options) -> None:
+        if options.config_file is None:  # pragma: no cover
+            return
+
+        toml_config = parse_toml(options.config_file)
+        if toml_config is not None:
+            config = toml_config.get('tool', {}).get('pydantic-mypy', {})
+            for key in self.__slots__:
+                setting = config.get(key, False)
+                if not isinstance(setting, bool):
+                    raise ValueError(f'Configuration value must be a boolean for key: {key}')
+                setattr(self, key, setting)
+        else:
+            plugin_config = ConfigParser()
+            plugin_config.read(options.config_file)
+            for key in self.__slots__:
+                setting = plugin_config.getboolean(CONFIGFILE_KEY, key, fallback=False)
+                setattr(self, key, setting)
+
+    def to_data(self) -> dict[str, Any]:
+        """Returns a dict of config names to their values."""
+        return {key: getattr(self, key) for key in self.__slots__}
+
+
+def from_attributes_callback(ctx: MethodContext) -> Type:
+    """Raise an error if from_attributes is not enabled."""
+    model_type: Instance
+    ctx_type = ctx.type
+    if isinstance(ctx_type, TypeType):
+        ctx_type = ctx_type.item
+    if isinstance(ctx_type, CallableType) and isinstance(ctx_type.ret_type, Instance):
+        model_type = ctx_type.ret_type  # called on the class
+    elif isinstance(ctx_type, Instance):
+        model_type = ctx_type  # called on an instance (unusual, but still valid)
+    else:  # pragma: no cover
+        detail = f'ctx.type: {ctx_type} (of type {ctx_type.__class__.__name__})'
+        error_unexpected_behavior(detail, ctx.api, ctx.context)
+        return ctx.default_return_type
+    pydantic_metadata = model_type.type.metadata.get(METADATA_KEY)
+    if pydantic_metadata is None:
+        return ctx.default_return_type
+    if not model_type.type.has_base(BASEMODEL_FULLNAME):
+        # not a Pydantic v2 model
+        return ctx.default_return_type
+    from_attributes = pydantic_metadata.get('config', {}).get('from_attributes')
+    if from_attributes is not True:
+        error_from_attributes(model_type.type.name, ctx.api, ctx.context)
+    return ctx.default_return_type
+
+
+class PydanticModelField:
+    """Based on mypy.plugins.dataclasses.DataclassAttribute."""
+
+    def __init__(
+        self,
+        name: str,
+        alias: str | None,
+        is_frozen: bool,
+        has_dynamic_alias: bool,
+        has_default: bool,
+        strict: bool | None,
+        line: int,
+        column: int,
+        type: Type | None,
+        info: TypeInfo,
+    ):
+        self.name = name
+        self.alias = alias
+        self.is_frozen = is_frozen
+        self.has_dynamic_alias = has_dynamic_alias
+        self.has_default = has_default
+        self.strict = strict
+        self.line = line
+        self.column = column
+        self.type = type
+        self.info = info
+
+    def to_argument(
+        self,
+        current_info: TypeInfo,
+        typed: bool,
+        model_strict: bool,
+        force_optional: bool,
+        use_alias: bool,
+        api: SemanticAnalyzerPluginInterface,
+        force_typevars_invariant: bool,
+        is_root_model_root: bool,
+    ) -> Argument:
+        """Based on mypy.plugins.dataclasses.DataclassAttribute.to_argument."""
+        variable = self.to_var(current_info, api, use_alias, force_typevars_invariant)
+
+        strict = model_strict if self.strict is None else self.strict
+        if typed or strict:
+            type_annotation = self.expand_type(current_info, api, include_root_type=True)
+        else:
+            type_annotation = AnyType(TypeOfAny.explicit)
+
+        return Argument(
+            variable=variable,
+            type_annotation=type_annotation,
+            initializer=None,
+            kind=ARG_OPT
+            if is_root_model_root
+            else (ARG_NAMED_OPT if force_optional or self.has_default else ARG_NAMED),
+        )
+
+    def expand_type(
+        self,
+        current_info: TypeInfo,
+        api: SemanticAnalyzerPluginInterface,
+        force_typevars_invariant: bool = False,
+        include_root_type: bool = False,
+    ) -> Type | None:
+        """Based on mypy.plugins.dataclasses.DataclassAttribute.expand_type."""
+        if force_typevars_invariant:
+            # In some cases, mypy will emit an error "Cannot use a covariant type variable as a parameter"
+            # To prevent that, we add an option to replace typevars with invariant ones while building certain
+            # method signatures (in particular, `__init__`). There may be a better way to do this, if this causes
+            # us problems in the future, we should look into why the dataclasses plugin doesn't have this issue.
+            if isinstance(self.type, TypeVarType):
+                modified_type = self.type.copy_modified()
+                modified_type.variance = INVARIANT
+                self.type = modified_type
+
+        if self.type is not None and self.info.self_type is not None:
+            # In general, it is not safe to call `expand_type()` during semantic analysis,
+            # however this plugin is called very late, so all types should be fully ready.
+            # Also, it is tricky to avoid eager expansion of Self types here (e.g. because
+            # we serialize attributes).
+            with state.strict_optional_set(api.options.strict_optional):
+                filled_with_typevars = fill_typevars(current_info)
+                # Cannot be TupleType as current_info represents a Pydantic model:
+                assert isinstance(filled_with_typevars, Instance)
+                if force_typevars_invariant:
+                    for arg in filled_with_typevars.args:
+                        if isinstance(arg, TypeVarType):
+                            arg.variance = INVARIANT
+
+                expanded_type = expand_type(self.type, {self.info.self_type.id: filled_with_typevars})
+                if include_root_type and isinstance(expanded_type, Instance) and is_root_model(expanded_type.type):
+                    # When a root model is used as a field, Pydantic allows both an instance of the root model
+                    # as well as instances of the `root` field type:
+                    root_type = expanded_type.type['root'].type
+                    if root_type is None:
+                        # Happens if the hint for 'root' has unsolved forward references
+                        return expanded_type
+                    expanded_root_type = expand_type_by_instance(root_type, expanded_type)
+                    expanded_type = UnionType([expanded_type, expanded_root_type])
+                return expanded_type
+        return self.type
+
+    def to_var(
+        self,
+        current_info: TypeInfo,
+        api: SemanticAnalyzerPluginInterface,
+        use_alias: bool,
+        force_typevars_invariant: bool = False,
+    ) -> Var:
+        """Based on mypy.plugins.dataclasses.DataclassAttribute.to_var."""
+        if use_alias and self.alias is not None:
+            name = self.alias
+        else:
+            name = self.name
+
+        return Var(name, self.expand_type(current_info, api, force_typevars_invariant))
+
+    def serialize(self) -> JsonDict:
+        """Based on mypy.plugins.dataclasses.DataclassAttribute.serialize."""
+        assert self.type
+        return {
+            'name': self.name,
+            'alias': self.alias,
+            'is_frozen': self.is_frozen,
+            'has_dynamic_alias': self.has_dynamic_alias,
+            'has_default': self.has_default,
+            'strict': self.strict,
+            'line': self.line,
+            'column': self.column,
+            'type': self.type.serialize(),
+        }
+
+    @classmethod
+    def deserialize(cls, info: TypeInfo, data: JsonDict, api: SemanticAnalyzerPluginInterface) -> PydanticModelField:
+        """Based on mypy.plugins.dataclasses.DataclassAttribute.deserialize."""
+        data = data.copy()
+        typ = deserialize_and_fixup_type(data.pop('type'), api)
+        return cls(type=typ, info=info, **data)
+
+    def expand_typevar_from_subtype(self, sub_type: TypeInfo, api: SemanticAnalyzerPluginInterface) -> None:
+        """Expands type vars in the context of a subtype when an attribute is inherited
+        from a generic super type.
+        """
+        if self.type is not None:
+            with state.strict_optional_set(api.options.strict_optional):
+                self.type = map_type_from_supertype(self.type, sub_type, self.info)
+
+
+class PydanticModelClassVar:
+    """Based on mypy.plugins.dataclasses.DataclassAttribute.
+
+    ClassVars are ignored by subclasses.
+
+    Attributes:
+        name: the ClassVar name
+    """
+
+    def __init__(self, name):
+        self.name = name
+
+    @classmethod
+    def deserialize(cls, data: JsonDict) -> PydanticModelClassVar:
+        """Based on mypy.plugins.dataclasses.DataclassAttribute.deserialize."""
+        data = data.copy()
+        return cls(**data)
+
+    def serialize(self) -> JsonDict:
+        """Based on mypy.plugins.dataclasses.DataclassAttribute.serialize."""
+        return {
+            'name': self.name,
+        }
+
+
+class PydanticModelTransformer:
+    """Transform the BaseModel subclass according to the plugin settings.
+
+    Attributes:
+        tracked_config_fields: A set of field configs that the plugin has to track their value.
+    """
+
+    tracked_config_fields: set[str] = {
+        'extra',
+        'frozen',
+        'from_attributes',
+        'populate_by_name',
+        'validate_by_alias',
+        'validate_by_name',
+        'alias_generator',
+        'strict',
+    }
+
+    def __init__(
+        self,
+        cls: ClassDef,
+        reason: Expression | Statement,
+        api: SemanticAnalyzerPluginInterface,
+        plugin_config: PydanticPluginConfig,
+    ) -> None:
+        self._cls = cls
+        self._reason = reason
+        self._api = api
+
+        self.plugin_config = plugin_config
+
+    def transform(self) -> bool:
+        """Configures the BaseModel subclass according to the plugin settings.
+
+        In particular:
+
+        * determines the model config and fields,
+        * adds a fields-aware signature for the initializer and construct methods
+        * freezes the class if frozen = True
+        * stores the fields, config, and if the class is settings in the mypy metadata for access by subclasses
+        """
+        info = self._cls.info
+        is_a_root_model = is_root_model(info)
+        config = self.collect_config()
+        fields, class_vars = self.collect_fields_and_class_vars(config, is_a_root_model)
+        if fields is None or class_vars is None:
+            # Some definitions are not ready. We need another pass.
+            return False
+        for field in fields:
+            if field.type is None:
+                return False
+
+        is_settings = info.has_base(BASESETTINGS_FULLNAME)
+        self.add_initializer(fields, config, is_settings, is_a_root_model)
+        self.add_model_construct_method(fields, config, is_settings, is_a_root_model)
+        self.set_frozen(fields, self._api, frozen=config.frozen is True)
+
+        self.adjust_decorator_signatures()
+
+        info.metadata[METADATA_KEY] = {
+            'fields': {field.name: field.serialize() for field in fields},
+            'class_vars': {class_var.name: class_var.serialize() for class_var in class_vars},
+            'config': config.get_values_dict(),
+        }
+
+        return True
+
+    def adjust_decorator_signatures(self) -> None:
+        """When we decorate a function `f` with `pydantic.validator(...)`, `pydantic.field_validator`
+        or `pydantic.serializer(...)`, mypy sees `f` as a regular method taking a `self` instance,
+        even though pydantic internally wraps `f` with `classmethod` if necessary.
+
+        Teach mypy this by marking any function whose outermost decorator is a `validator()`,
+        `field_validator()` or `serializer()` call as a `classmethod`.
+        """
+        for sym in self._cls.info.names.values():
+            if isinstance(sym.node, Decorator):
+                first_dec = sym.node.original_decorators[0]
+                if (
+                    isinstance(first_dec, CallExpr)
+                    and isinstance(first_dec.callee, NameExpr)
+                    and first_dec.callee.fullname in IMPLICIT_CLASSMETHOD_DECORATOR_FULLNAMES
+                    # @model_validator(mode="after") is an exception, it expects a regular method
+                    and not (
+                        first_dec.callee.fullname == MODEL_VALIDATOR_FULLNAME
+                        and any(
+                            first_dec.arg_names[i] == 'mode' and isinstance(arg, StrExpr) and arg.value == 'after'
+                            for i, arg in enumerate(first_dec.args)
+                        )
+                    )
+                ):
+                    # TODO: Only do this if the first argument of the decorated function is `cls`
+                    sym.node.func.is_class = True
+
+    def collect_config(self) -> ModelConfigData:  # noqa: C901 (ignore complexity)
+        """Collects the values of the config attributes that are used by the plugin, accounting for parent classes."""
+        cls = self._cls
+        config = ModelConfigData()
+
+        has_config_kwargs = False
+        has_config_from_namespace = False
+
+        # Handle `class MyModel(BaseModel, =, ...):`
+        for name, expr in cls.keywords.items():
+            config_data = self.get_config_update(name, expr)
+            if config_data:
+                has_config_kwargs = True
+                config.update(config_data)
+
+        # Handle `model_config`
+        stmt: Statement | None = None
+        for stmt in cls.defs.body:
+            if not isinstance(stmt, (AssignmentStmt, ClassDef)):
+                continue
+
+            if isinstance(stmt, AssignmentStmt):
+                lhs = stmt.lvalues[0]
+                if not isinstance(lhs, NameExpr) or lhs.name != 'model_config':
+                    continue
+
+                if isinstance(stmt.rvalue, CallExpr):  # calls to `dict` or `ConfigDict`
+                    for arg_name, arg in zip(stmt.rvalue.arg_names, stmt.rvalue.args):
+                        if arg_name is None:
+                            continue
+                        config.update(self.get_config_update(arg_name, arg, lax_extra=True))
+                elif isinstance(stmt.rvalue, DictExpr):  # dict literals
+                    for key_expr, value_expr in stmt.rvalue.items:
+                        if not isinstance(key_expr, StrExpr):
+                            continue
+                        config.update(self.get_config_update(key_expr.value, value_expr))
+
+            elif isinstance(stmt, ClassDef):
+                if stmt.name != 'Config':  # 'deprecated' Config-class
+                    continue
+                for substmt in stmt.defs.body:
+                    if not isinstance(substmt, AssignmentStmt):
+                        continue
+                    lhs = substmt.lvalues[0]
+                    if not isinstance(lhs, NameExpr):
+                        continue
+                    config.update(self.get_config_update(lhs.name, substmt.rvalue))
+
+            if has_config_kwargs:
+                self._api.fail(
+                    'Specifying config in two places is ambiguous, use either Config attribute or class kwargs',
+                    cls,
+                )
+                break
+
+            has_config_from_namespace = True
+
+        if has_config_kwargs or has_config_from_namespace:
+            if (
+                stmt
+                and config.has_alias_generator
+                and not (config.validate_by_name or config.populate_by_name)
+                and self.plugin_config.warn_required_dynamic_aliases
+            ):
+                error_required_dynamic_aliases(self._api, stmt)
+
+        for info in cls.info.mro[1:]:  # 0 is the current class
+            if METADATA_KEY not in info.metadata:
+                continue
+
+            # Each class depends on the set of fields in its ancestors
+            self._api.add_plugin_dependency(make_wildcard_trigger(info.fullname))
+            for name, value in info.metadata[METADATA_KEY]['config'].items():
+                config.setdefault(name, value)
+        return config
+
+    def collect_fields_and_class_vars(
+        self, model_config: ModelConfigData, is_root_model: bool
+    ) -> tuple[list[PydanticModelField] | None, list[PydanticModelClassVar] | None]:
+        """Collects the fields for the model, accounting for parent classes."""
+        cls = self._cls
+
+        # First, collect fields and ClassVars belonging to any class in the MRO, ignoring duplicates.
+        #
+        # We iterate through the MRO in reverse because attrs defined in the parent must appear
+        # earlier in the attributes list than attrs defined in the child. See:
+        # https://docs.python.org/3/library/dataclasses.html#inheritance
+        #
+        # However, we also want fields defined in the subtype to override ones defined
+        # in the parent. We can implement this via a dict without disrupting the attr order
+        # because dicts preserve insertion order in Python 3.7+.
+        found_fields: dict[str, PydanticModelField] = {}
+        found_class_vars: dict[str, PydanticModelClassVar] = {}
+        for info in reversed(cls.info.mro[1:-1]):  # 0 is the current class, -2 is BaseModel, -1 is object
+            # if BASEMODEL_METADATA_TAG_KEY in info.metadata and BASEMODEL_METADATA_KEY not in info.metadata:
+            #     # We haven't processed the base class yet. Need another pass.
+            #     return None, None
+            if METADATA_KEY not in info.metadata:
+                continue
+
+            # Each class depends on the set of attributes in its dataclass ancestors.
+            self._api.add_plugin_dependency(make_wildcard_trigger(info.fullname))
+
+            for name, data in info.metadata[METADATA_KEY]['fields'].items():
+                field = PydanticModelField.deserialize(info, data, self._api)
+                # (The following comment comes directly from the dataclasses plugin)
+                # TODO: We shouldn't be performing type operations during the main
+                #       semantic analysis pass, since some TypeInfo attributes might
+                #       still be in flux. This should be performed in a later phase.
+                field.expand_typevar_from_subtype(cls.info, self._api)
+                found_fields[name] = field
+
+                sym_node = cls.info.names.get(name)
+                if sym_node and sym_node.node and not isinstance(sym_node.node, Var):
+                    self._api.fail(
+                        'BaseModel field may only be overridden by another field',
+                        sym_node.node,
+                    )
+            # Collect ClassVars
+            for name, data in info.metadata[METADATA_KEY]['class_vars'].items():
+                found_class_vars[name] = PydanticModelClassVar.deserialize(data)
+
+        # Second, collect fields and ClassVars belonging to the current class.
+        current_field_names: set[str] = set()
+        current_class_vars_names: set[str] = set()
+        for stmt in self._get_assignment_statements_from_block(cls.defs):
+            maybe_field = self.collect_field_or_class_var_from_stmt(stmt, model_config, found_class_vars)
+            if maybe_field is None:
+                continue
+
+            lhs = stmt.lvalues[0]
+            assert isinstance(lhs, NameExpr)  # collect_field_or_class_var_from_stmt guarantees this
+            if isinstance(maybe_field, PydanticModelField):
+                if is_root_model and lhs.name != 'root':
+                    error_extra_fields_on_root_model(self._api, stmt)
+                else:
+                    current_field_names.add(lhs.name)
+                    found_fields[lhs.name] = maybe_field
+            elif isinstance(maybe_field, PydanticModelClassVar):
+                current_class_vars_names.add(lhs.name)
+                found_class_vars[lhs.name] = maybe_field
+
+        return list(found_fields.values()), list(found_class_vars.values())
+
+    def _get_assignment_statements_from_if_statement(self, stmt: IfStmt) -> Iterator[AssignmentStmt]:
+        for body in stmt.body:
+            if not body.is_unreachable:
+                yield from self._get_assignment_statements_from_block(body)
+        if stmt.else_body is not None and not stmt.else_body.is_unreachable:
+            yield from self._get_assignment_statements_from_block(stmt.else_body)
+
+    def _get_assignment_statements_from_block(self, block: Block) -> Iterator[AssignmentStmt]:
+        for stmt in block.body:
+            if isinstance(stmt, AssignmentStmt):
+                yield stmt
+            elif isinstance(stmt, IfStmt):
+                yield from self._get_assignment_statements_from_if_statement(stmt)
+
+    def collect_field_or_class_var_from_stmt(  # noqa C901
+        self, stmt: AssignmentStmt, model_config: ModelConfigData, class_vars: dict[str, PydanticModelClassVar]
+    ) -> PydanticModelField | PydanticModelClassVar | None:
+        """Get pydantic model field from statement.
+
+        Args:
+            stmt: The statement.
+            model_config: Configuration settings for the model.
+            class_vars: ClassVars already known to be defined on the model.
+
+        Returns:
+            A pydantic model field if it could find the field in statement. Otherwise, `None`.
+        """
+        cls = self._cls
+
+        lhs = stmt.lvalues[0]
+        if not isinstance(lhs, NameExpr) or not _fields.is_valid_field_name(lhs.name) or lhs.name == 'model_config':
+            return None
+
+        if not stmt.new_syntax:
+            if (
+                isinstance(stmt.rvalue, CallExpr)
+                and isinstance(stmt.rvalue.callee, CallExpr)
+                and isinstance(stmt.rvalue.callee.callee, NameExpr)
+                and stmt.rvalue.callee.callee.fullname in DECORATOR_FULLNAMES
+            ):
+                # This is a (possibly-reused) validator or serializer, not a field
+                # In particular, it looks something like: my_validator = validator('my_field')(f)
+                # Eventually, we may want to attempt to respect model_config['ignored_types']
+                return None
+
+            if lhs.name in class_vars:
+                # Class vars are not fields and are not required to be annotated
+                return None
+
+            # The assignment does not have an annotation, and it's not anything else we recognize
+            error_untyped_fields(self._api, stmt)
+            return None
+
+        lhs = stmt.lvalues[0]
+        if not isinstance(lhs, NameExpr):
+            return None
+
+        if not _fields.is_valid_field_name(lhs.name) or lhs.name == 'model_config':
+            return None
+
+        sym = cls.info.names.get(lhs.name)
+        if sym is None:  # pragma: no cover
+            # This is likely due to a star import (see the dataclasses plugin for a more detailed explanation)
+            # This is the same logic used in the dataclasses plugin
+            return None
+
+        node = sym.node
+        if isinstance(node, PlaceholderNode):  # pragma: no cover
+            # See the PlaceholderNode docstring for more detail about how this can occur
+            # Basically, it is an edge case when dealing with complex import logic
+
+            # The dataclasses plugin now asserts this cannot happen, but I'd rather not error if it does..
+            return None
+
+        if isinstance(node, TypeAlias):
+            self._api.fail(
+                'Type aliases inside BaseModel definitions are not supported at runtime',
+                node,
+            )
+            # Skip processing this node. This doesn't match the runtime behaviour,
+            # but the only alternative would be to modify the SymbolTable,
+            # and it's a little hairy to do that in a plugin.
+            return None
+
+        if not isinstance(node, Var):  # pragma: no cover
+            # Don't know if this edge case still happens with the `is_valid_field` check above
+            # but better safe than sorry
+
+            # The dataclasses plugin now asserts this cannot happen, but I'd rather not error if it does..
+            return None
+
+        # x: ClassVar[int] is not a field
+        if node.is_classvar:
+            return PydanticModelClassVar(lhs.name)
+
+        # x: InitVar[int] is not supported in BaseModel
+        node_type = get_proper_type(node.type)
+        if isinstance(node_type, Instance) and node_type.type.fullname == 'dataclasses.InitVar':
+            self._api.fail(
+                'InitVar is not supported in BaseModel',
+                node,
+            )
+
+        has_default = self.get_has_default(stmt)
+        strict = self.get_strict(stmt)
+
+        if sym.type is None and node.is_final and node.is_inferred:
+            # This follows the logic from the dataclasses plugin. The following comment is taken verbatim:
+            #
+            # This is a special case, assignment like x: Final = 42 is classified
+            # annotated above, but mypy strips the `Final` turning it into x = 42.
+            # We do not support inferred types in dataclasses, so we can try inferring
+            # type for simple literals, and otherwise require an explicit type
+            # argument for Final[...].
+            typ = self._api.analyze_simple_literal_type(stmt.rvalue, is_final=True)
+            if typ:
+                node.type = typ
+            else:
+                self._api.fail(
+                    'Need type argument for Final[...] with non-literal default in BaseModel',
+                    stmt,
+                )
+                node.type = AnyType(TypeOfAny.from_error)
+
+        if node.is_final and has_default:
+            # TODO this path should be removed (see https://github.com/pydantic/pydantic/issues/11119)
+            return PydanticModelClassVar(lhs.name)
+
+        alias, has_dynamic_alias = self.get_alias_info(stmt)
+        if (
+            has_dynamic_alias
+            and not (model_config.validate_by_name or model_config.populate_by_name)
+            and self.plugin_config.warn_required_dynamic_aliases
+        ):
+            error_required_dynamic_aliases(self._api, stmt)
+        is_frozen = self.is_field_frozen(stmt)
+
+        init_type = self._infer_dataclass_attr_init_type(sym, lhs.name, stmt)
+        return PydanticModelField(
+            name=lhs.name,
+            has_dynamic_alias=has_dynamic_alias,
+            has_default=has_default,
+            strict=strict,
+            alias=alias,
+            is_frozen=is_frozen,
+            line=stmt.line,
+            column=stmt.column,
+            type=init_type,
+            info=cls.info,
+        )
+
+    def _infer_dataclass_attr_init_type(self, sym: SymbolTableNode, name: str, context: Context) -> Type | None:
+        """Infer __init__ argument type for an attribute.
+
+        In particular, possibly use the signature of __set__.
+        """
+        default = sym.type
+        if sym.implicit:
+            return default
+        t = get_proper_type(sym.type)
+
+        # Perform a simple-minded inference from the signature of __set__, if present.
+        # We can't use mypy.checkmember here, since this plugin runs before type checking.
+        # We only support some basic scanerios here, which is hopefully sufficient for
+        # the vast majority of use cases.
+        if not isinstance(t, Instance):
+            return default
+        setter = t.type.get('__set__')
+        if setter:
+            if isinstance(setter.node, FuncDef):
+                super_info = t.type.get_containing_type_info('__set__')
+                assert super_info
+                if setter.type:
+                    setter_type = get_proper_type(map_type_from_supertype(setter.type, t.type, super_info))
+                else:
+                    return AnyType(TypeOfAny.unannotated)
+                if isinstance(setter_type, CallableType) and setter_type.arg_kinds == [
+                    ARG_POS,
+                    ARG_POS,
+                    ARG_POS,
+                ]:
+                    return expand_type_by_instance(setter_type.arg_types[2], t)
+                else:
+                    self._api.fail(f'Unsupported signature for "__set__" in "{t.type.name}"', context)
+            else:
+                self._api.fail(f'Unsupported "__set__" in "{t.type.name}"', context)
+
+        return default
+
+    def add_initializer(
+        self, fields: list[PydanticModelField], config: ModelConfigData, is_settings: bool, is_root_model: bool
+    ) -> None:
+        """Adds a fields-aware `__init__` method to the class.
+
+        The added `__init__` will be annotated with types vs. all `Any` depending on the plugin settings.
+        """
+        if '__init__' in self._cls.info.names and not self._cls.info.names['__init__'].plugin_generated:
+            return  # Don't generate an __init__ if one already exists
+
+        typed = self.plugin_config.init_typed
+        model_strict = bool(config.strict)
+        use_alias = not (config.validate_by_name or config.populate_by_name) and config.validate_by_alias is not False
+        requires_dynamic_aliases = bool(config.has_alias_generator and not config.validate_by_name)
+        args = self.get_field_arguments(
+            fields,
+            typed=typed,
+            model_strict=model_strict,
+            requires_dynamic_aliases=requires_dynamic_aliases,
+            use_alias=use_alias,
+            is_settings=is_settings,
+            is_root_model=is_root_model,
+            force_typevars_invariant=True,
+        )
+
+        if is_settings:
+            base_settings_node = self._api.lookup_fully_qualified(BASESETTINGS_FULLNAME).node
+            assert isinstance(base_settings_node, TypeInfo)
+            if '__init__' in base_settings_node.names:
+                base_settings_init_node = base_settings_node.names['__init__'].node
+                assert isinstance(base_settings_init_node, FuncDef)
+                if base_settings_init_node is not None and base_settings_init_node.type is not None:
+                    func_type = base_settings_init_node.type
+                    assert isinstance(func_type, CallableType)
+                    for arg_idx, arg_name in enumerate(func_type.arg_names):
+                        if arg_name is None or arg_name.startswith('__') or not arg_name.startswith('_'):
+                            continue
+                        analyzed_variable_type = self._api.anal_type(func_type.arg_types[arg_idx])
+                        if analyzed_variable_type is not None and arg_name == '_cli_settings_source':
+                            # _cli_settings_source is defined as CliSettingsSource[Any], and as such
+                            # the Any causes issues with --disallow-any-explicit. As a workaround, change
+                            # the Any type (as if CliSettingsSource was left unparameterized):
+                            analyzed_variable_type = analyzed_variable_type.accept(
+                                ChangeExplicitTypeOfAny(TypeOfAny.from_omitted_generics)
+                            )
+                        variable = Var(arg_name, analyzed_variable_type)
+                        args.append(Argument(variable, analyzed_variable_type, None, ARG_OPT))
+
+        if not self.should_init_forbid_extra(fields, config):
+            var = Var('kwargs')
+            args.append(Argument(var, AnyType(TypeOfAny.explicit), None, ARG_STAR2))
+
+        add_method(self._api, self._cls, '__init__', args=args, return_type=NoneType())
+
+    def add_model_construct_method(
+        self,
+        fields: list[PydanticModelField],
+        config: ModelConfigData,
+        is_settings: bool,
+        is_root_model: bool,
+    ) -> None:
+        """Adds a fully typed `model_construct` classmethod to the class.
+
+        Similar to the fields-aware __init__ method, but always uses the field names (not aliases),
+        and does not treat settings fields as optional.
+        """
+        set_str = self._api.named_type(f'{BUILTINS_NAME}.set', [self._api.named_type(f'{BUILTINS_NAME}.str')])
+        optional_set_str = UnionType([set_str, NoneType()])
+        fields_set_argument = Argument(Var('_fields_set', optional_set_str), optional_set_str, None, ARG_OPT)
+        with state.strict_optional_set(self._api.options.strict_optional):
+            args = self.get_field_arguments(
+                fields,
+                typed=True,
+                model_strict=bool(config.strict),
+                requires_dynamic_aliases=False,
+                use_alias=False,
+                is_settings=is_settings,
+                is_root_model=is_root_model,
+            )
+        if not self.should_init_forbid_extra(fields, config):
+            var = Var('kwargs')
+            args.append(Argument(var, AnyType(TypeOfAny.explicit), None, ARG_STAR2))
+
+        args = args + [fields_set_argument] if is_root_model else [fields_set_argument] + args
+
+        add_method(
+            self._api,
+            self._cls,
+            'model_construct',
+            args=args,
+            return_type=fill_typevars(self._cls.info),
+            is_classmethod=True,
+        )
+
+    def set_frozen(self, fields: list[PydanticModelField], api: SemanticAnalyzerPluginInterface, frozen: bool) -> None:
+        """Marks all fields as properties so that attempts to set them trigger mypy errors.
+
+        This is the same approach used by the attrs and dataclasses plugins.
+        """
+        info = self._cls.info
+        for field in fields:
+            sym_node = info.names.get(field.name)
+            if sym_node is not None:
+                var = sym_node.node
+                if isinstance(var, Var):
+                    var.is_property = frozen or field.is_frozen
+                elif isinstance(var, PlaceholderNode) and not self._api.final_iteration:
+                    # See https://github.com/pydantic/pydantic/issues/5191 to hit this branch for test coverage
+                    self._api.defer()
+                # `var` can also be a FuncDef or Decorator node (e.g. when overriding a field with a function or property).
+                # In that case, we don't want to do anything. Mypy will already raise an error that a field was not properly
+                # overridden.
+            else:
+                var = field.to_var(info, api, use_alias=False)
+                var.info = info
+                var.is_property = frozen
+                var._fullname = info.fullname + '.' + var.name
+                info.names[var.name] = SymbolTableNode(MDEF, var)
+
+    def get_config_update(self, name: str, arg: Expression, lax_extra: bool = False) -> ModelConfigData | None:
+        """Determines the config update due to a single kwarg in the ConfigDict definition.
+
+        Warns if a tracked config attribute is set to a value the plugin doesn't know how to interpret (e.g., an int)
+        """
+        if name not in self.tracked_config_fields:
+            return None
+        if name == 'extra':
+            if isinstance(arg, StrExpr):
+                forbid_extra = arg.value == 'forbid'
+            elif isinstance(arg, MemberExpr):
+                forbid_extra = arg.name == 'forbid'
+            else:
+                if not lax_extra:
+                    # Only emit an error for other types of `arg` (e.g., `NameExpr`, `ConditionalExpr`, etc.) when
+                    # reading from a config class, etc. If a ConfigDict is used, then we don't want to emit an error
+                    # because you'll get type checking from the ConfigDict itself.
+                    #
+                    # It would be nice if we could introspect the types better otherwise, but I don't know what the API
+                    # is to evaluate an expr into its type and then check if that type is compatible with the expected
+                    # type. Note that you can still get proper type checking via: `model_config = ConfigDict(...)`, just
+                    # if you don't use an explicit string, the plugin won't be able to infer whether extra is forbidden.
+                    error_invalid_config_value(name, self._api, arg)
+                return None
+            return ModelConfigData(forbid_extra=forbid_extra)
+        if name == 'alias_generator':
+            has_alias_generator = True
+            if isinstance(arg, NameExpr) and arg.fullname == 'builtins.None':
+                has_alias_generator = False
+            return ModelConfigData(has_alias_generator=has_alias_generator)
+        if isinstance(arg, NameExpr) and arg.fullname in ('builtins.True', 'builtins.False'):
+            return ModelConfigData(**{name: arg.fullname == 'builtins.True'})
+        error_invalid_config_value(name, self._api, arg)
+        return None
+
+    @staticmethod
+    def get_has_default(stmt: AssignmentStmt) -> bool:
+        """Returns a boolean indicating whether the field defined in `stmt` is a required field."""
+        expr = stmt.rvalue
+        if isinstance(expr, TempNode):
+            # TempNode means annotation-only, so has no default
+            return False
+        if isinstance(expr, CallExpr) and isinstance(expr.callee, RefExpr) and expr.callee.fullname == FIELD_FULLNAME:
+            # The "default value" is a call to `Field`; at this point, the field has a default if and only if:
+            # * there is a positional argument that is not `...`
+            # * there is a keyword argument named "default" that is not `...`
+            # * there is a "default_factory" that is not `None`
+            for arg, name in zip(expr.args, expr.arg_names):
+                # If name is None, then this arg is the default because it is the only positional argument.
+                if name is None or name == 'default':
+                    return arg.__class__ is not EllipsisExpr
+                if name == 'default_factory':
+                    return not (isinstance(arg, NameExpr) and arg.fullname == 'builtins.None')
+            return False
+        # Has no default if the "default value" is Ellipsis (i.e., `field_name: Annotation = ...`)
+        return not isinstance(expr, EllipsisExpr)
+
+    @staticmethod
+    def get_strict(stmt: AssignmentStmt) -> bool | None:
+        """Returns a the `strict` value of a field if defined, otherwise `None`."""
+        expr = stmt.rvalue
+        if isinstance(expr, CallExpr) and isinstance(expr.callee, RefExpr) and expr.callee.fullname == FIELD_FULLNAME:
+            for arg, name in zip(expr.args, expr.arg_names):
+                if name != 'strict':
+                    continue
+                if isinstance(arg, NameExpr):
+                    if arg.fullname == 'builtins.True':
+                        return True
+                    elif arg.fullname == 'builtins.False':
+                        return False
+                return None
+        return None
+
+    @staticmethod
+    def get_alias_info(stmt: AssignmentStmt) -> tuple[str | None, bool]:
+        """Returns a pair (alias, has_dynamic_alias), extracted from the declaration of the field defined in `stmt`.
+
+        `has_dynamic_alias` is True if and only if an alias is provided, but not as a string literal.
+        If `has_dynamic_alias` is True, `alias` will be None.
+        """
+        expr = stmt.rvalue
+        if isinstance(expr, TempNode):
+            # TempNode means annotation-only
+            return None, False
+
+        if not (
+            isinstance(expr, CallExpr) and isinstance(expr.callee, RefExpr) and expr.callee.fullname == FIELD_FULLNAME
+        ):
+            # Assigned value is not a call to pydantic.fields.Field
+            return None, False
+
+        if 'validation_alias' in expr.arg_names:
+            arg = expr.args[expr.arg_names.index('validation_alias')]
+        elif 'alias' in expr.arg_names:
+            arg = expr.args[expr.arg_names.index('alias')]
+        else:
+            return None, False
+
+        if isinstance(arg, StrExpr):
+            return arg.value, False
+        else:
+            return None, True
+
+    @staticmethod
+    def is_field_frozen(stmt: AssignmentStmt) -> bool:
+        """Returns whether the field is frozen, extracted from the declaration of the field defined in `stmt`.
+
+        Note that this is only whether the field was declared to be frozen in a ` = Field(frozen=True)`
+        sense; this does not determine whether the field is frozen because the entire model is frozen; that is
+        handled separately.
+        """
+        expr = stmt.rvalue
+        if isinstance(expr, TempNode):
+            # TempNode means annotation-only
+            return False
+
+        if not (
+            isinstance(expr, CallExpr) and isinstance(expr.callee, RefExpr) and expr.callee.fullname == FIELD_FULLNAME
+        ):
+            # Assigned value is not a call to pydantic.fields.Field
+            return False
+
+        for i, arg_name in enumerate(expr.arg_names):
+            if arg_name == 'frozen':
+                arg = expr.args[i]
+                return isinstance(arg, NameExpr) and arg.fullname == 'builtins.True'
+        return False
+
+    def get_field_arguments(
+        self,
+        fields: list[PydanticModelField],
+        typed: bool,
+        model_strict: bool,
+        use_alias: bool,
+        requires_dynamic_aliases: bool,
+        is_settings: bool,
+        is_root_model: bool,
+        force_typevars_invariant: bool = False,
+    ) -> list[Argument]:
+        """Helper function used during the construction of the `__init__` and `model_construct` method signatures.
+
+        Returns a list of mypy Argument instances for use in the generated signatures.
+        """
+        info = self._cls.info
+        arguments = [
+            field.to_argument(
+                info,
+                typed=typed,
+                model_strict=model_strict,
+                force_optional=requires_dynamic_aliases or is_settings,
+                use_alias=use_alias,
+                api=self._api,
+                force_typevars_invariant=force_typevars_invariant,
+                is_root_model_root=is_root_model and field.name == 'root',
+            )
+            for field in fields
+            if not (use_alias and field.has_dynamic_alias)
+        ]
+        return arguments
+
+    def should_init_forbid_extra(self, fields: list[PydanticModelField], config: ModelConfigData) -> bool:
+        """Indicates whether the generated `__init__` should get a `**kwargs` at the end of its signature.
+
+        We disallow arbitrary kwargs if the extra config setting is "forbid", or if the plugin config says to,
+        *unless* a required dynamic alias is present (since then we can't determine a valid signature).
+        """
+        if not (config.validate_by_name or config.populate_by_name):
+            if self.is_dynamic_alias_present(fields, bool(config.has_alias_generator)):
+                return False
+        if config.forbid_extra:
+            return True
+        return self.plugin_config.init_forbid_extra
+
+    @staticmethod
+    def is_dynamic_alias_present(fields: list[PydanticModelField], has_alias_generator: bool) -> bool:
+        """Returns whether any fields on the model have a "dynamic alias", i.e., an alias that cannot be
+        determined during static analysis.
+        """
+        for field in fields:
+            if field.has_dynamic_alias:
+                return True
+        if has_alias_generator:
+            for field in fields:
+                if field.alias is None:
+                    return True
+        return False
+
+
+class ChangeExplicitTypeOfAny(TypeTranslator):
+    """A type translator used to change type of Any's, if explicit."""
+
+    def __init__(self, type_of_any: int) -> None:
+        self._type_of_any = type_of_any
+        super().__init__()
+
+    def visit_any(self, t: AnyType) -> Type:  # noqa: D102
+        if t.type_of_any == TypeOfAny.explicit:
+            return t.copy_modified(type_of_any=self._type_of_any)
+        else:
+            return t
+
+
+class ModelConfigData:
+    """Pydantic mypy plugin model config class."""
+
+    def __init__(
+        self,
+        forbid_extra: bool | None = None,
+        frozen: bool | None = None,
+        from_attributes: bool | None = None,
+        populate_by_name: bool | None = None,
+        validate_by_alias: bool | None = None,
+        validate_by_name: bool | None = None,
+        has_alias_generator: bool | None = None,
+        strict: bool | None = None,
+    ):
+        self.forbid_extra = forbid_extra
+        self.frozen = frozen
+        self.from_attributes = from_attributes
+        self.populate_by_name = populate_by_name
+        self.validate_by_alias = validate_by_alias
+        self.validate_by_name = validate_by_name
+        self.has_alias_generator = has_alias_generator
+        self.strict = strict
+
+    def get_values_dict(self) -> dict[str, Any]:
+        """Returns a dict of Pydantic model config names to their values.
+
+        It includes the config if config value is not `None`.
+        """
+        return {k: v for k, v in self.__dict__.items() if v is not None}
+
+    def update(self, config: ModelConfigData | None) -> None:
+        """Update Pydantic model config values."""
+        if config is None:
+            return
+        for k, v in config.get_values_dict().items():
+            setattr(self, k, v)
+
+    def setdefault(self, key: str, value: Any) -> None:
+        """Set default value for Pydantic model config if config value is `None`."""
+        if getattr(self, key) is None:
+            setattr(self, key, value)
+
+
+def is_root_model(info: TypeInfo) -> bool:
+    """Return whether the type info is a root model subclass (or the `RootModel` class itself)."""
+    return info.has_base(ROOT_MODEL_FULLNAME)
+
+
+ERROR_ORM = ErrorCode('pydantic-orm', 'Invalid from_attributes call', 'Pydantic')
+ERROR_CONFIG = ErrorCode('pydantic-config', 'Invalid config value', 'Pydantic')
+ERROR_ALIAS = ErrorCode('pydantic-alias', 'Dynamic alias disallowed', 'Pydantic')
+ERROR_UNEXPECTED = ErrorCode('pydantic-unexpected', 'Unexpected behavior', 'Pydantic')
+ERROR_UNTYPED = ErrorCode('pydantic-field', 'Untyped field disallowed', 'Pydantic')
+ERROR_FIELD_DEFAULTS = ErrorCode('pydantic-field', 'Invalid Field defaults', 'Pydantic')
+ERROR_EXTRA_FIELD_ROOT_MODEL = ErrorCode('pydantic-field', 'Extra field on RootModel subclass', 'Pydantic')
+
+
+def error_from_attributes(model_name: str, api: CheckerPluginInterface, context: Context) -> None:
+    """Emits an error when the model does not have `from_attributes=True`."""
+    api.fail(f'"{model_name}" does not have from_attributes=True', context, code=ERROR_ORM)
+
+
+def error_invalid_config_value(name: str, api: SemanticAnalyzerPluginInterface, context: Context) -> None:
+    """Emits an error when the config value is invalid."""
+    api.fail(f'Invalid value for "Config.{name}"', context, code=ERROR_CONFIG)
+
+
+def error_required_dynamic_aliases(api: SemanticAnalyzerPluginInterface, context: Context) -> None:
+    """Emits required dynamic aliases error.
+
+    This will be called when `warn_required_dynamic_aliases=True`.
+    """
+    api.fail('Required dynamic aliases disallowed', context, code=ERROR_ALIAS)
+
+
+def error_unexpected_behavior(
+    detail: str, api: CheckerPluginInterface | SemanticAnalyzerPluginInterface, context: Context
+) -> None:  # pragma: no cover
+    """Emits unexpected behavior error."""
+    # Can't think of a good way to test this, but I confirmed it renders as desired by adding to a non-error path
+    link = 'https://github.com/pydantic/pydantic/issues/new/choose'
+    full_message = f'The pydantic mypy plugin ran into unexpected behavior: {detail}\n'
+    full_message += f'Please consider reporting this bug at {link} so we can try to fix it!'
+    api.fail(full_message, context, code=ERROR_UNEXPECTED)
+
+
+def error_untyped_fields(api: SemanticAnalyzerPluginInterface, context: Context) -> None:
+    """Emits an error when there is an untyped field in the model."""
+    api.fail('Untyped fields disallowed', context, code=ERROR_UNTYPED)
+
+
+def error_extra_fields_on_root_model(api: CheckerPluginInterface, context: Context) -> None:
+    """Emits an error when there is more than just a root field defined for a subclass of RootModel."""
+    api.fail('Only `root` is allowed as a field of a `RootModel`', context, code=ERROR_EXTRA_FIELD_ROOT_MODEL)
+
+
+def add_method(
+    api: SemanticAnalyzerPluginInterface | CheckerPluginInterface,
+    cls: ClassDef,
+    name: str,
+    args: list[Argument],
+    return_type: Type,
+    self_type: Type | None = None,
+    tvar_def: TypeVarType | None = None,
+    is_classmethod: bool = False,
+) -> None:
+    """Very closely related to `mypy.plugins.common.add_method_to_class`, with a few pydantic-specific changes."""
+    info = cls.info
+
+    # First remove any previously generated methods with the same name
+    # to avoid clashes and problems in the semantic analyzer.
+    if name in info.names:
+        sym = info.names[name]
+        if sym.plugin_generated and isinstance(sym.node, FuncDef):
+            cls.defs.body.remove(sym.node)  # pragma: no cover
+
+    if isinstance(api, SemanticAnalyzerPluginInterface):
+        function_type = api.named_type('builtins.function')
+    else:
+        function_type = api.named_generic_type('builtins.function', [])
+
+    if is_classmethod:
+        self_type = self_type or TypeType(fill_typevars(info))
+        first = [Argument(Var('_cls'), self_type, None, ARG_POS, True)]
+    else:
+        self_type = self_type or fill_typevars(info)
+        # `self` is positional *ONLY* here, but this can't be expressed
+        # fully in the mypy internal API. ARG_POS is the closest we can get.
+        # Using ARG_POS will, however, give mypy errors if a `self` field
+        # is present on a model:
+        #
+        #     Name "self" already defined (possibly by an import)  [no-redef]
+        #
+        # As a workaround, we give this argument a name that will
+        # never conflict. By its positional nature, this name will not
+        # be used or exposed to users.
+        first = [Argument(Var('__pydantic_self__'), self_type, None, ARG_POS)]
+    args = first + args
+
+    arg_types, arg_names, arg_kinds = [], [], []
+    for arg in args:
+        assert arg.type_annotation, 'All arguments must be fully typed.'
+        arg_types.append(arg.type_annotation)
+        arg_names.append(arg.variable.name)
+        arg_kinds.append(arg.kind)
+
+    signature = CallableType(
+        arg_types, arg_kinds, arg_names, return_type, function_type, variables=[tvar_def] if tvar_def else None
+    )
+
+    func = FuncDef(name, args, Block([PassStmt()]))
+    func.info = info
+    func.type = set_callable_name(signature, func)
+    func.is_class = is_classmethod
+    func._fullname = info.fullname + '.' + name
+    func.line = info.line
+
+    # NOTE: we would like the plugin generated node to dominate, but we still
+    # need to keep any existing definitions so they get semantically analyzed.
+    if name in info.names:
+        # Get a nice unique name instead.
+        r_name = get_unique_redefinition_name(name, info.names)
+        info.names[r_name] = info.names[name]
+
+    # Add decorator for is_classmethod
+    # The dataclasses plugin claims this is unnecessary for classmethods, but not including it results in a
+    # signature incompatible with the superclass, which causes mypy errors to occur for every subclass of BaseModel.
+    if is_classmethod:
+        func.is_decorated = True
+        v = Var(name, func.type)
+        v.info = info
+        v._fullname = func._fullname
+        v.is_classmethod = True
+        dec = Decorator(func, [NameExpr('classmethod')], v)
+        dec.line = info.line
+        sym = SymbolTableNode(MDEF, dec)
+    else:
+        sym = SymbolTableNode(MDEF, func)
+    sym.plugin_generated = True
+    info.names[name] = sym
+
+    info.defn.defs.body.append(func)
+
+
+def parse_toml(config_file: str) -> dict[str, Any] | None:
+    """Returns a dict of config keys to values.
+
+    It reads configs from toml file and returns `None` if the file is not a toml file.
+    """
+    if not config_file.endswith('.toml'):
+        return None
+
+    if sys.version_info >= (3, 11):
+        import tomllib as toml_
+    else:
+        try:
+            import tomli as toml_
+        except ImportError:  # pragma: no cover
+            import warnings
+
+            warnings.warn('No TOML parser installed, cannot read configuration from `pyproject.toml`.', stacklevel=2)
+            return None
+
+    with open(config_file, 'rb') as rf:
+        return toml_.load(rf)
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pydantic/networks.py b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/networks.py
new file mode 100644
index 0000000000000000000000000000000000000000..04a7cac6b57e8401d2b12e0095838527f490a6fa
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/networks.py
@@ -0,0 +1,1331 @@
+"""The networks module contains types for common network-related fields."""
+
+from __future__ import annotations as _annotations
+
+import dataclasses as _dataclasses
+import re
+from dataclasses import fields
+from functools import lru_cache
+from importlib.metadata import version
+from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network
+from typing import TYPE_CHECKING, Annotated, Any, ClassVar
+
+from pydantic_core import (
+    MultiHostHost,
+    PydanticCustomError,
+    PydanticSerializationUnexpectedValue,
+    SchemaSerializer,
+    core_schema,
+)
+from pydantic_core import MultiHostUrl as _CoreMultiHostUrl
+from pydantic_core import Url as _CoreUrl
+from typing_extensions import Self, TypeAlias
+
+from pydantic.errors import PydanticUserError
+
+from ._internal import _repr, _schema_generation_shared
+from ._migration import getattr_migration
+from .annotated_handlers import GetCoreSchemaHandler
+from .json_schema import JsonSchemaValue
+from .type_adapter import TypeAdapter
+
+if TYPE_CHECKING:
+    import email_validator
+
+    NetworkType: TypeAlias = 'str | bytes | int | tuple[str | bytes | int, str | int]'
+
+else:
+    email_validator = None
+
+
+__all__ = [
+    'AnyUrl',
+    'AnyHttpUrl',
+    'FileUrl',
+    'FtpUrl',
+    'HttpUrl',
+    'WebsocketUrl',
+    'AnyWebsocketUrl',
+    'UrlConstraints',
+    'EmailStr',
+    'NameEmail',
+    'IPvAnyAddress',
+    'IPvAnyInterface',
+    'IPvAnyNetwork',
+    'PostgresDsn',
+    'CockroachDsn',
+    'AmqpDsn',
+    'RedisDsn',
+    'MongoDsn',
+    'KafkaDsn',
+    'NatsDsn',
+    'validate_email',
+    'MySQLDsn',
+    'MariaDBDsn',
+    'ClickHouseDsn',
+    'SnowflakeDsn',
+]
+
+
+@_dataclasses.dataclass
+class UrlConstraints:
+    """Url constraints.
+
+    Attributes:
+        max_length: The maximum length of the url. Defaults to `None`.
+        allowed_schemes: The allowed schemes. Defaults to `None`.
+        host_required: Whether the host is required. Defaults to `None`.
+        default_host: The default host. Defaults to `None`.
+        default_port: The default port. Defaults to `None`.
+        default_path: The default path. Defaults to `None`.
+        preserve_empty_path: Whether to preserve empty URL paths. Defaults to `None`.
+    """
+
+    max_length: int | None = None
+    allowed_schemes: list[str] | None = None
+    host_required: bool | None = None
+    default_host: str | None = None
+    default_port: int | None = None
+    default_path: str | None = None
+    preserve_empty_path: bool | None = None
+
+    def __hash__(self) -> int:
+        return hash(
+            (
+                self.max_length,
+                tuple(self.allowed_schemes) if self.allowed_schemes is not None else None,
+                self.host_required,
+                self.default_host,
+                self.default_port,
+                self.default_path,
+                self.preserve_empty_path,
+            )
+        )
+
+    @property
+    def defined_constraints(self) -> dict[str, Any]:
+        """Fetch a key / value mapping of constraints to values that are not None. Used for core schema updates."""
+        return {field.name: value for field in fields(self) if (value := getattr(self, field.name)) is not None}
+
+    def __get_pydantic_core_schema__(self, source: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
+        schema = handler(source)
+
+        # for function-wrap schemas, url constraints is applied to the inner schema
+        # because when we generate schemas for urls, we wrap a core_schema.url_schema() with a function-wrap schema
+        # that helps with validation on initialization, see _BaseUrl and _BaseMultiHostUrl below.
+        schema_to_mutate = schema['schema'] if schema['type'] == 'function-wrap' else schema
+        if annotated_type := schema_to_mutate['type'] not in ('url', 'multi-host-url'):
+            raise PydanticUserError(
+                f"'UrlConstraints' cannot annotate '{annotated_type}'.", code='invalid-annotated-type'
+            )
+        for constraint_key, constraint_value in self.defined_constraints.items():
+            schema_to_mutate[constraint_key] = constraint_value
+        return schema
+
+
+class _BaseUrl:
+    _constraints: ClassVar[UrlConstraints] = UrlConstraints()
+    _url: _CoreUrl
+
+    def __init__(self, url: str | _CoreUrl | _BaseUrl) -> None:
+        self._url = _build_type_adapter(self.__class__).validate_python(url)._url
+
+    @property
+    def scheme(self) -> str:
+        """The scheme part of the URL.
+
+        e.g. `https` in `https://user:pass@host:port/path?query#fragment`
+        """
+        return self._url.scheme
+
+    @property
+    def username(self) -> str | None:
+        """The username part of the URL, or `None`.
+
+        e.g. `user` in `https://user:pass@host:port/path?query#fragment`
+        """
+        return self._url.username
+
+    @property
+    def password(self) -> str | None:
+        """The password part of the URL, or `None`.
+
+        e.g. `pass` in `https://user:pass@host:port/path?query#fragment`
+        """
+        return self._url.password
+
+    @property
+    def host(self) -> str | None:
+        """The host part of the URL, or `None`.
+
+        If the URL must be punycode encoded, this is the encoded host, e.g if the input URL is `https://£££.com`,
+        `host` will be `xn--9aaa.com`
+        """
+        return self._url.host
+
+    def unicode_host(self) -> str | None:
+        """The host part of the URL as a unicode string, or `None`.
+
+        e.g. `host` in `https://user:pass@host:port/path?query#fragment`
+
+        If the URL must be punycode encoded, this is the decoded host, e.g if the input URL is `https://£££.com`,
+        `unicode_host()` will be `£££.com`
+        """
+        return self._url.unicode_host()
+
+    @property
+    def port(self) -> int | None:
+        """The port part of the URL, or `None`.
+
+        e.g. `port` in `https://user:pass@host:port/path?query#fragment`
+        """
+        return self._url.port
+
+    @property
+    def path(self) -> str | None:
+        """The path part of the URL, or `None`.
+
+        e.g. `/path` in `https://user:pass@host:port/path?query#fragment`
+        """
+        return self._url.path
+
+    @property
+    def query(self) -> str | None:
+        """The query part of the URL, or `None`.
+
+        e.g. `query` in `https://user:pass@host:port/path?query#fragment`
+        """
+        return self._url.query
+
+    def query_params(self) -> list[tuple[str, str]]:
+        """The query part of the URL as a list of key-value pairs.
+
+        e.g. `[('foo', 'bar')]` in `https://user:pass@host:port/path?foo=bar#fragment`
+        """
+        return self._url.query_params()
+
+    @property
+    def fragment(self) -> str | None:
+        """The fragment part of the URL, or `None`.
+
+        e.g. `fragment` in `https://user:pass@host:port/path?query#fragment`
+        """
+        return self._url.fragment
+
+    def unicode_string(self) -> str:
+        """The URL as a unicode string, unlike `__str__()` this will not punycode encode the host.
+
+        If the URL must be punycode encoded, this is the decoded string, e.g if the input URL is `https://£££.com`,
+        `unicode_string()` will be `https://£££.com`
+        """
+        return self._url.unicode_string()
+
+    def encoded_string(self) -> str:
+        """The URL's encoded string representation via __str__().
+
+        This returns the punycode-encoded host version of the URL as a string.
+        """
+        return str(self)
+
+    def __str__(self) -> str:
+        """The URL as a string, this will punycode encode the host if required."""
+        return str(self._url)
+
+    def __repr__(self) -> str:
+        return f'{self.__class__.__name__}({str(self._url)!r})'
+
+    def __deepcopy__(self, memo: dict) -> Self:
+        return self.__class__(self._url)
+
+    def __eq__(self, other: Any) -> bool:
+        return self.__class__ is other.__class__ and self._url == other._url
+
+    def __lt__(self, other: Any) -> bool:
+        return self.__class__ is other.__class__ and self._url < other._url
+
+    def __gt__(self, other: Any) -> bool:
+        return self.__class__ is other.__class__ and self._url > other._url
+
+    def __le__(self, other: Any) -> bool:
+        return self.__class__ is other.__class__ and self._url <= other._url
+
+    def __ge__(self, other: Any) -> bool:
+        return self.__class__ is other.__class__ and self._url >= other._url
+
+    def __hash__(self) -> int:
+        return hash(self._url)
+
+    def __len__(self) -> int:
+        return len(str(self._url))
+
+    @classmethod
+    def build(
+        cls,
+        *,
+        scheme: str,
+        username: str | None = None,
+        password: str | None = None,
+        host: str,
+        port: int | None = None,
+        path: str | None = None,
+        query: str | None = None,
+        fragment: str | None = None,
+    ) -> Self:
+        """Build a new `Url` instance from its component parts.
+
+        Args:
+            scheme: The scheme part of the URL.
+            username: The username part of the URL, or omit for no username.
+            password: The password part of the URL, or omit for no password.
+            host: The host part of the URL.
+            port: The port part of the URL, or omit for no port.
+            path: The path part of the URL, or omit for no path.
+            query: The query part of the URL, or omit for no query.
+            fragment: The fragment part of the URL, or omit for no fragment.
+
+        Returns:
+            An instance of URL
+        """
+        return cls(
+            _CoreUrl.build(
+                scheme=scheme,
+                username=username,
+                password=password,
+                host=host,
+                port=port,
+                path=path,
+                query=query,
+                fragment=fragment,
+            )
+        )
+
+    @classmethod
+    def serialize_url(cls, url: Any, info: core_schema.SerializationInfo) -> str | Self:
+        if not isinstance(url, cls):
+            raise PydanticSerializationUnexpectedValue(
+                f"Expected `{cls}` but got `{type(url)}` with value `'{url}'` - serialized value may not be as expected."
+            )
+        if info.mode == 'json':
+            return str(url)
+        return url
+
+    @classmethod
+    def __get_pydantic_core_schema__(
+        cls, source: type[_BaseUrl], handler: GetCoreSchemaHandler
+    ) -> core_schema.CoreSchema:
+        def wrap_val(v, h):
+            if isinstance(v, source):
+                return v
+            if isinstance(v, _BaseUrl):
+                v = str(v)
+            core_url = h(v)
+            instance = source.__new__(source)
+            instance._url = core_url
+            return instance
+
+        return core_schema.no_info_wrap_validator_function(
+            wrap_val,
+            schema=core_schema.url_schema(**cls._constraints.defined_constraints),
+            serialization=core_schema.plain_serializer_function_ser_schema(
+                cls.serialize_url, info_arg=True, when_used='always'
+            ),
+        )
+
+    @classmethod
+    def __get_pydantic_json_schema__(
+        cls, core_schema: core_schema.CoreSchema, handler: _schema_generation_shared.GetJsonSchemaHandler
+    ) -> JsonSchemaValue:
+        # we use the url schema for json schema generation, but we might have to extract it from
+        # the function-wrap schema we use as a tool for validation on initialization
+        inner_schema = core_schema['schema'] if core_schema['type'] == 'function-wrap' else core_schema
+        return handler(inner_schema)
+
+    __pydantic_serializer__ = SchemaSerializer(core_schema.any_schema(serialization=core_schema.to_string_ser_schema()))
+
+
+class _BaseMultiHostUrl:
+    _constraints: ClassVar[UrlConstraints] = UrlConstraints()
+    _url: _CoreMultiHostUrl
+
+    def __init__(self, url: str | _CoreMultiHostUrl | _BaseMultiHostUrl) -> None:
+        self._url = _build_type_adapter(self.__class__).validate_python(url)._url
+
+    @property
+    def scheme(self) -> str:
+        """The scheme part of the URL.
+
+        e.g. `https` in `https://foo.com,bar.com/path?query#fragment`
+        """
+        return self._url.scheme
+
+    @property
+    def path(self) -> str | None:
+        """The path part of the URL, or `None`.
+
+        e.g. `/path` in `https://foo.com,bar.com/path?query#fragment`
+        """
+        return self._url.path
+
+    @property
+    def query(self) -> str | None:
+        """The query part of the URL, or `None`.
+
+        e.g. `query` in `https://foo.com,bar.com/path?query#fragment`
+        """
+        return self._url.query
+
+    def query_params(self) -> list[tuple[str, str]]:
+        """The query part of the URL as a list of key-value pairs.
+
+        e.g. `[('foo', 'bar')]` in `https://foo.com,bar.com/path?foo=bar#fragment`
+        """
+        return self._url.query_params()
+
+    @property
+    def fragment(self) -> str | None:
+        """The fragment part of the URL, or `None`.
+
+        e.g. `fragment` in `https://foo.com,bar.com/path?query#fragment`
+        """
+        return self._url.fragment
+
+    def hosts(self) -> list[MultiHostHost]:
+        '''The hosts of the `MultiHostUrl` as [`MultiHostHost`][pydantic_core.MultiHostHost] typed dicts.
+
+        ```python
+        from pydantic_core import MultiHostUrl
+
+        mhu = MultiHostUrl('https://foo.com:123,foo:bar@bar.com/path')
+        print(mhu.hosts())
+        """
+        [
+            {'username': None, 'password': None, 'host': 'foo.com', 'port': 123},
+            {'username': 'foo', 'password': 'bar', 'host': 'bar.com', 'port': 443}
+        ]
+        ```
+        Returns:
+            A list of dicts, each representing a host.
+        '''
+        return self._url.hosts()
+
+    def encoded_string(self) -> str:
+        """The URL's encoded string representation via __str__().
+
+        This returns the punycode-encoded host version of the URL as a string.
+        """
+        return str(self)
+
+    def unicode_string(self) -> str:
+        """The URL as a unicode string, unlike `__str__()` this will not punycode encode the hosts."""
+        return self._url.unicode_string()
+
+    def __str__(self) -> str:
+        """The URL as a string, this will punycode encode the host if required."""
+        return str(self._url)
+
+    def __repr__(self) -> str:
+        return f'{self.__class__.__name__}({str(self._url)!r})'
+
+    def __deepcopy__(self, memo: dict) -> Self:
+        return self.__class__(self._url)
+
+    def __eq__(self, other: Any) -> bool:
+        return self.__class__ is other.__class__ and self._url == other._url
+
+    def __hash__(self) -> int:
+        return hash(self._url)
+
+    def __len__(self) -> int:
+        return len(str(self._url))
+
+    @classmethod
+    def build(
+        cls,
+        *,
+        scheme: str,
+        hosts: list[MultiHostHost] | None = None,
+        username: str | None = None,
+        password: str | None = None,
+        host: str | None = None,
+        port: int | None = None,
+        path: str | None = None,
+        query: str | None = None,
+        fragment: str | None = None,
+    ) -> Self:
+        """Build a new `MultiHostUrl` instance from its component parts.
+
+        This method takes either `hosts` - a list of `MultiHostHost` typed dicts, or the individual components
+        `username`, `password`, `host` and `port`.
+
+        Args:
+            scheme: The scheme part of the URL.
+            hosts: Multiple hosts to build the URL from.
+            username: The username part of the URL.
+            password: The password part of the URL.
+            host: The host part of the URL.
+            port: The port part of the URL.
+            path: The path part of the URL.
+            query: The query part of the URL, or omit for no query.
+            fragment: The fragment part of the URL, or omit for no fragment.
+
+        Returns:
+            An instance of `MultiHostUrl`
+        """
+        return cls(
+            _CoreMultiHostUrl.build(
+                scheme=scheme,
+                hosts=hosts,
+                username=username,
+                password=password,
+                host=host,
+                port=port,
+                path=path,
+                query=query,
+                fragment=fragment,
+            )
+        )
+
+    @classmethod
+    def serialize_url(cls, url: Any, info: core_schema.SerializationInfo) -> str | Self:
+        if not isinstance(url, cls):
+            raise PydanticSerializationUnexpectedValue(
+                f"Expected `{cls}` but got `{type(url)}` with value `'{url}'` - serialized value may not be as expected."
+            )
+        if info.mode == 'json':
+            return str(url)
+        return url
+
+    @classmethod
+    def __get_pydantic_core_schema__(
+        cls, source: type[_BaseMultiHostUrl], handler: GetCoreSchemaHandler
+    ) -> core_schema.CoreSchema:
+        def wrap_val(v, h):
+            if isinstance(v, source):
+                return v
+            if isinstance(v, _BaseMultiHostUrl):
+                v = str(v)
+            core_url = h(v)
+            instance = source.__new__(source)
+            instance._url = core_url
+            return instance
+
+        return core_schema.no_info_wrap_validator_function(
+            wrap_val,
+            schema=core_schema.multi_host_url_schema(**cls._constraints.defined_constraints),
+            serialization=core_schema.plain_serializer_function_ser_schema(
+                cls.serialize_url, info_arg=True, when_used='always'
+            ),
+        )
+
+    @classmethod
+    def __get_pydantic_json_schema__(
+        cls, core_schema: core_schema.CoreSchema, handler: _schema_generation_shared.GetJsonSchemaHandler
+    ) -> JsonSchemaValue:
+        # we use the url schema for json schema generation, but we might have to extract it from
+        # the function-wrap schema we use as a tool for validation on initialization
+        inner_schema = core_schema['schema'] if core_schema['type'] == 'function-wrap' else core_schema
+        return handler(inner_schema)
+
+    __pydantic_serializer__ = SchemaSerializer(core_schema.any_schema(serialization=core_schema.to_string_ser_schema()))
+
+
+@lru_cache
+def _build_type_adapter(cls: type[_BaseUrl | _BaseMultiHostUrl]) -> TypeAdapter:
+    return TypeAdapter(cls)
+
+
+class AnyUrl(_BaseUrl):
+    """Base type for all URLs.
+
+    * Any scheme allowed
+    * Top-level domain (TLD) not required
+    * Host not required
+
+    Assuming an input URL of `http://samuel:pass@example.com:8000/the/path/?query=here#fragment=is;this=bit`,
+    the types export the following properties:
+
+    - `scheme`: the URL scheme (`http`), always set.
+    - `host`: the URL host (`example.com`).
+    - `username`: optional username if included (`samuel`).
+    - `password`: optional password if included (`pass`).
+    - `port`: optional port (`8000`).
+    - `path`: optional path (`/the/path/`).
+    - `query`: optional URL query (for example, `GET` arguments or "search string", such as `query=here`).
+    - `fragment`: optional fragment (`fragment=is;this=bit`).
+    """
+
+
+# Note: all single host urls inherit from `AnyUrl` to preserve compatibility with pre-v2.10 code
+# Where urls were annotated variants of `AnyUrl`, which was an alias to `pydantic_core.Url`
+
+
+class AnyHttpUrl(AnyUrl):
+    """A type that will accept any http or https URL.
+
+    * TLD not required
+    * Host not required
+    """
+
+    _constraints = UrlConstraints(allowed_schemes=['http', 'https'])
+
+
+class HttpUrl(AnyUrl):
+    """A type that will accept any http or https URL.
+
+    * TLD not required
+    * Host not required
+    * Max length 2083
+
+    ```python
+    from pydantic import BaseModel, HttpUrl, ValidationError
+
+    class MyModel(BaseModel):
+        url: HttpUrl
+
+    m = MyModel(url='http://www.example.com')  # (1)!
+    print(m.url)
+    #> http://www.example.com/
+
+    try:
+        MyModel(url='ftp://invalid.url')
+    except ValidationError as e:
+        print(e)
+        '''
+        1 validation error for MyModel
+        url
+          URL scheme should be 'http' or 'https' [type=url_scheme, input_value='ftp://invalid.url', input_type=str]
+        '''
+
+    try:
+        MyModel(url='not a url')
+    except ValidationError as e:
+        print(e)
+        '''
+        1 validation error for MyModel
+        url
+          Input should be a valid URL, relative URL without a base [type=url_parsing, input_value='not a url', input_type=str]
+        '''
+    ```
+
+    1. Note: mypy would prefer `m = MyModel(url=HttpUrl('http://www.example.com'))`, but Pydantic will convert the string to an HttpUrl instance anyway.
+
+    "International domains" (e.g. a URL where the host or TLD includes non-ascii characters) will be encoded via
+    [punycode](https://en.wikipedia.org/wiki/Punycode) (see
+    [this article](https://www.xudongz.com/blog/2017/idn-phishing/) for a good description of why this is important):
+
+    ```python
+    from pydantic import BaseModel, HttpUrl
+
+    class MyModel(BaseModel):
+        url: HttpUrl
+
+    m1 = MyModel(url='http://puny£code.com')
+    print(m1.url)
+    #> http://xn--punycode-eja.com/
+    m2 = MyModel(url='https://www.аррӏе.com/')
+    print(m2.url)
+    #> https://www.xn--80ak6aa92e.com/
+    m3 = MyModel(url='https://www.example.珠宝/')
+    print(m3.url)
+    #> https://www.example.xn--pbt977c/
+    ```
+
+
+    !!! warning "Underscores in Hostnames"
+        In Pydantic, underscores are allowed in all parts of a domain except the TLD.
+        Technically this might be wrong - in theory the hostname cannot have underscores, but subdomains can.
+
+        To explain this; consider the following two cases:
+
+        - `exam_ple.co.uk`: the hostname is `exam_ple`, which should not be allowed since it contains an underscore.
+        - `foo_bar.example.com` the hostname is `example`, which should be allowed since the underscore is in the subdomain.
+
+        Without having an exhaustive list of TLDs, it would be impossible to differentiate between these two. Therefore
+        underscores are allowed, but you can always do further validation in a validator if desired.
+
+        Also, Chrome, Firefox, and Safari all currently accept `http://exam_ple.com` as a URL, so we're in good
+        (or at least big) company.
+    """
+
+    _constraints = UrlConstraints(max_length=2083, allowed_schemes=['http', 'https'])
+
+
+class AnyWebsocketUrl(AnyUrl):
+    """A type that will accept any ws or wss URL.
+
+    * TLD not required
+    * Host not required
+    """
+
+    _constraints = UrlConstraints(allowed_schemes=['ws', 'wss'])
+
+
+class WebsocketUrl(AnyUrl):
+    """A type that will accept any ws or wss URL.
+
+    * TLD not required
+    * Host not required
+    * Max length 2083
+    """
+
+    _constraints = UrlConstraints(max_length=2083, allowed_schemes=['ws', 'wss'])
+
+
+class FileUrl(AnyUrl):
+    """A type that will accept any file URL.
+
+    * Host not required
+    """
+
+    _constraints = UrlConstraints(allowed_schemes=['file'])
+
+
+class FtpUrl(AnyUrl):
+    """A type that will accept ftp URL.
+
+    * TLD not required
+    * Host not required
+    """
+
+    _constraints = UrlConstraints(allowed_schemes=['ftp'])
+
+
+class PostgresDsn(_BaseMultiHostUrl):
+    """A type that will accept any Postgres DSN.
+
+    * User info required
+    * TLD not required
+    * Host required
+    * Supports multiple hosts
+
+    If further validation is required, these properties can be used by validators to enforce specific behaviour:
+
+    ```python
+    from pydantic import (
+        BaseModel,
+        HttpUrl,
+        PostgresDsn,
+        ValidationError,
+        field_validator,
+    )
+
+    class MyModel(BaseModel):
+        url: HttpUrl
+
+    m = MyModel(url='http://www.example.com')
+
+    # the repr() method for a url will display all properties of the url
+    print(repr(m.url))
+    #> HttpUrl('http://www.example.com/')
+    print(m.url.scheme)
+    #> http
+    print(m.url.host)
+    #> www.example.com
+    print(m.url.port)
+    #> 80
+
+    class MyDatabaseModel(BaseModel):
+        db: PostgresDsn
+
+        @field_validator('db')
+        def check_db_name(cls, v):
+            assert v.path and len(v.path) > 1, 'database must be provided'
+            return v
+
+    m = MyDatabaseModel(db='postgres://user:pass@localhost:5432/foobar')
+    print(m.db)
+    #> postgres://user:pass@localhost:5432/foobar
+
+    try:
+        MyDatabaseModel(db='postgres://user:pass@localhost:5432')
+    except ValidationError as e:
+        print(e)
+        '''
+        1 validation error for MyDatabaseModel
+        db
+          Assertion failed, database must be provided
+        assert (None)
+         +  where None = PostgresDsn('postgres://user:pass@localhost:5432').path [type=assertion_error, input_value='postgres://user:pass@localhost:5432', input_type=str]
+        '''
+    ```
+    """
+
+    _constraints = UrlConstraints(
+        host_required=True,
+        allowed_schemes=[
+            'postgres',
+            'postgresql',
+            'postgresql+asyncpg',
+            'postgresql+pg8000',
+            'postgresql+psycopg',
+            'postgresql+psycopg2',
+            'postgresql+psycopg2cffi',
+            'postgresql+py-postgresql',
+            'postgresql+pygresql',
+        ],
+    )
+
+    @property
+    def host(self) -> str:
+        """The required URL host."""
+        return self._url.host  # pyright: ignore[reportAttributeAccessIssue]
+
+
+class CockroachDsn(AnyUrl):
+    """A type that will accept any Cockroach DSN.
+
+    * User info required
+    * TLD not required
+    * Host required
+    """
+
+    _constraints = UrlConstraints(
+        host_required=True,
+        allowed_schemes=[
+            'cockroachdb',
+            'cockroachdb+psycopg2',
+            'cockroachdb+asyncpg',
+        ],
+    )
+
+    @property
+    def host(self) -> str:
+        """The required URL host."""
+        return self._url.host  # pyright: ignore[reportReturnType]
+
+
+class AmqpDsn(AnyUrl):
+    """A type that will accept any AMQP DSN.
+
+    * User info required
+    * TLD not required
+    * Host not required
+    """
+
+    _constraints = UrlConstraints(allowed_schemes=['amqp', 'amqps'])
+
+
+class RedisDsn(AnyUrl):
+    """A type that will accept any Redis DSN.
+
+    * User info required
+    * TLD not required
+    * Host required (e.g., `rediss://:pass@localhost`)
+    """
+
+    _constraints = UrlConstraints(
+        allowed_schemes=['redis', 'rediss'],
+        default_host='localhost',
+        default_port=6379,
+        default_path='/0',
+        host_required=True,
+    )
+
+    @property
+    def host(self) -> str:
+        """The required URL host."""
+        return self._url.host  # pyright: ignore[reportReturnType]
+
+
+class MongoDsn(_BaseMultiHostUrl):
+    """A type that will accept any MongoDB DSN.
+
+    * User info not required
+    * Database name not required
+    * Port not required
+    * User info may be passed without user part (e.g., `mongodb://mongodb0.example.com:27017`).
+
+    !!! warning
+        If a port isn't specified, the default MongoDB port `27017` will be used. If this behavior is
+        undesirable, you can use the following:
+
+        ```python
+        from typing import Annotated
+
+        from pydantic import UrlConstraints
+        from pydantic_core import MultiHostUrl
+
+        MongoDsnNoDefaultPort = Annotated[
+            MultiHostUrl,
+            UrlConstraints(allowed_schemes=['mongodb', 'mongodb+srv']),
+        ]
+        ```
+    """
+
+    _constraints = UrlConstraints(allowed_schemes=['mongodb', 'mongodb+srv'], default_port=27017)
+
+
+class KafkaDsn(AnyUrl):
+    """A type that will accept any Kafka DSN.
+
+    * User info required
+    * TLD not required
+    * Host not required
+    """
+
+    _constraints = UrlConstraints(allowed_schemes=['kafka'], default_host='localhost', default_port=9092)
+
+
+class NatsDsn(_BaseMultiHostUrl):
+    """A type that will accept any NATS DSN.
+
+    NATS is a connective technology built for the ever increasingly hyper-connected world.
+    It is a single technology that enables applications to securely communicate across
+    any combination of cloud vendors, on-premise, edge, web and mobile, and devices.
+    More: https://nats.io
+    """
+
+    _constraints = UrlConstraints(
+        allowed_schemes=['nats', 'tls', 'ws', 'wss'], default_host='localhost', default_port=4222
+    )
+
+
+class MySQLDsn(AnyUrl):
+    """A type that will accept any MySQL DSN.
+
+    * User info required
+    * TLD not required
+    * Host not required
+    """
+
+    _constraints = UrlConstraints(
+        allowed_schemes=[
+            'mysql',
+            'mysql+mysqlconnector',
+            'mysql+aiomysql',
+            'mysql+asyncmy',
+            'mysql+mysqldb',
+            'mysql+pymysql',
+            'mysql+cymysql',
+            'mysql+pyodbc',
+        ],
+        default_port=3306,
+        host_required=True,
+    )
+
+
+class MariaDBDsn(AnyUrl):
+    """A type that will accept any MariaDB DSN.
+
+    * User info required
+    * TLD not required
+    * Host not required
+    """
+
+    _constraints = UrlConstraints(
+        allowed_schemes=['mariadb', 'mariadb+mariadbconnector', 'mariadb+pymysql'],
+        default_port=3306,
+    )
+
+
+class ClickHouseDsn(AnyUrl):
+    """A type that will accept any ClickHouse DSN.
+
+    * User info required
+    * TLD not required
+    * Host not required
+    """
+
+    _constraints = UrlConstraints(
+        allowed_schemes=[
+            'clickhouse+native',
+            'clickhouse+asynch',
+            'clickhouse+http',
+            'clickhouse',
+            'clickhouses',
+            'clickhousedb',
+        ],
+        default_host='localhost',
+        default_port=9000,
+    )
+
+
+class SnowflakeDsn(AnyUrl):
+    """A type that will accept any Snowflake DSN.
+
+    * User info required
+    * TLD not required
+    * Host required
+    """
+
+    _constraints = UrlConstraints(
+        allowed_schemes=['snowflake'],
+        host_required=True,
+    )
+
+    @property
+    def host(self) -> str:
+        """The required URL host."""
+        return self._url.host  # pyright: ignore[reportReturnType]
+
+
+def import_email_validator() -> None:
+    global email_validator
+    try:
+        import email_validator
+    except ImportError as e:
+        raise ImportError("email-validator is not installed, run `pip install 'pydantic[email]'`") from e
+    if not version('email-validator').partition('.')[0] == '2':
+        raise ImportError('email-validator version >= 2.0 required, run pip install -U email-validator')
+
+
+if TYPE_CHECKING:
+    EmailStr = Annotated[str, ...]
+else:
+
+    class EmailStr:
+        """
+        Info:
+            To use this type, you need to install the optional
+            [`email-validator`](https://github.com/JoshData/python-email-validator) package:
+
+            ```bash
+            pip install email-validator
+            ```
+
+        Validate email addresses.
+
+        ```python
+        from pydantic import BaseModel, EmailStr
+
+        class Model(BaseModel):
+            email: EmailStr
+
+        print(Model(email='contact@mail.com'))
+        #> email='contact@mail.com'
+        ```
+        """  # noqa: D212
+
+        @classmethod
+        def __get_pydantic_core_schema__(
+            cls,
+            _source: type[Any],
+            _handler: GetCoreSchemaHandler,
+        ) -> core_schema.CoreSchema:
+            import_email_validator()
+            return core_schema.no_info_after_validator_function(cls._validate, core_schema.str_schema())
+
+        @classmethod
+        def __get_pydantic_json_schema__(
+            cls, core_schema: core_schema.CoreSchema, handler: _schema_generation_shared.GetJsonSchemaHandler
+        ) -> JsonSchemaValue:
+            field_schema = handler(core_schema)
+            field_schema.update(type='string', format='email')
+            return field_schema
+
+        @classmethod
+        def _validate(cls, input_value: str, /) -> str:
+            return validate_email(input_value)[1]
+
+
+class NameEmail(_repr.Representation):
+    """
+    Info:
+        To use this type, you need to install the optional
+        [`email-validator`](https://github.com/JoshData/python-email-validator) package:
+
+        ```bash
+        pip install email-validator
+        ```
+
+    Validate a name and email address combination, as specified by
+    [RFC 5322](https://datatracker.ietf.org/doc/html/rfc5322#section-3.4).
+
+    The `NameEmail` has two properties: `name` and `email`.
+    In case the `name` is not provided, it's inferred from the email address.
+
+    ```python
+    from pydantic import BaseModel, NameEmail
+
+    class User(BaseModel):
+        email: NameEmail
+
+    user = User(email='Fred Bloggs ')
+    print(user.email)
+    #> Fred Bloggs 
+    print(user.email.name)
+    #> Fred Bloggs
+
+    user = User(email='fred.bloggs@example.com')
+    print(user.email)
+    #> fred.bloggs 
+    print(user.email.name)
+    #> fred.bloggs
+    ```
+    """  # noqa: D212
+
+    __slots__ = 'name', 'email'
+
+    def __init__(self, name: str, email: str):
+        self.name = name
+        self.email = email
+
+    def __eq__(self, other: Any) -> bool:
+        return isinstance(other, NameEmail) and (self.name, self.email) == (other.name, other.email)
+
+    @classmethod
+    def __get_pydantic_json_schema__(
+        cls, core_schema: core_schema.CoreSchema, handler: _schema_generation_shared.GetJsonSchemaHandler
+    ) -> JsonSchemaValue:
+        field_schema = handler(core_schema)
+        field_schema.update(type='string', format='name-email')
+        return field_schema
+
+    @classmethod
+    def __get_pydantic_core_schema__(
+        cls,
+        _source: type[Any],
+        _handler: GetCoreSchemaHandler,
+    ) -> core_schema.CoreSchema:
+        import_email_validator()
+
+        return core_schema.no_info_after_validator_function(
+            cls._validate,
+            core_schema.json_or_python_schema(
+                json_schema=core_schema.str_schema(),
+                python_schema=core_schema.union_schema(
+                    [core_schema.is_instance_schema(cls), core_schema.str_schema()],
+                    custom_error_type='name_email_type',
+                    custom_error_message='Input is not a valid NameEmail',
+                ),
+                serialization=core_schema.to_string_ser_schema(),
+            ),
+        )
+
+    @classmethod
+    def _validate(cls, input_value: Self | str, /) -> Self:
+        if isinstance(input_value, str):
+            name, email = validate_email(input_value)
+            return cls(name, email)
+        else:
+            return input_value
+
+    def __str__(self) -> str:
+        if '@' in self.name:
+            return f'"{self.name}" <{self.email}>'
+
+        return f'{self.name} <{self.email}>'
+
+
+IPvAnyAddressType: TypeAlias = 'IPv4Address | IPv6Address'
+IPvAnyInterfaceType: TypeAlias = 'IPv4Interface | IPv6Interface'
+IPvAnyNetworkType: TypeAlias = 'IPv4Network | IPv6Network'
+
+if TYPE_CHECKING:
+    IPvAnyAddress = IPvAnyAddressType
+    IPvAnyInterface = IPvAnyInterfaceType
+    IPvAnyNetwork = IPvAnyNetworkType
+else:
+
+    class IPvAnyAddress:
+        """Validate an IPv4 or IPv6 address.
+
+        ```python
+        from pydantic import BaseModel
+        from pydantic.networks import IPvAnyAddress
+
+        class IpModel(BaseModel):
+            ip: IPvAnyAddress
+
+        print(IpModel(ip='127.0.0.1'))
+        #> ip=IPv4Address('127.0.0.1')
+
+        try:
+            IpModel(ip='http://www.example.com')
+        except ValueError as e:
+            print(e.errors())
+            '''
+            [
+                {
+                    'type': 'ip_any_address',
+                    'loc': ('ip',),
+                    'msg': 'value is not a valid IPv4 or IPv6 address',
+                    'input': 'http://www.example.com',
+                }
+            ]
+            '''
+        ```
+        """
+
+        __slots__ = ()
+
+        def __new__(cls, value: Any) -> IPvAnyAddressType:
+            """Validate an IPv4 or IPv6 address."""
+            try:
+                return IPv4Address(value)
+            except ValueError:
+                pass
+
+            try:
+                return IPv6Address(value)
+            except ValueError:
+                raise PydanticCustomError('ip_any_address', 'value is not a valid IPv4 or IPv6 address')
+
+        @classmethod
+        def __get_pydantic_json_schema__(
+            cls, core_schema: core_schema.CoreSchema, handler: _schema_generation_shared.GetJsonSchemaHandler
+        ) -> JsonSchemaValue:
+            field_schema = {}
+            field_schema.update(type='string', format='ipvanyaddress')
+            return field_schema
+
+        @classmethod
+        def __get_pydantic_core_schema__(
+            cls,
+            _source: type[Any],
+            _handler: GetCoreSchemaHandler,
+        ) -> core_schema.CoreSchema:
+            return core_schema.no_info_plain_validator_function(
+                cls._validate, serialization=core_schema.to_string_ser_schema()
+            )
+
+        @classmethod
+        def _validate(cls, input_value: Any, /) -> IPvAnyAddressType:
+            return cls(input_value)  # type: ignore[return-value]
+
+    class IPvAnyInterface:
+        """Validate an IPv4 or IPv6 interface."""
+
+        __slots__ = ()
+
+        def __new__(cls, value: NetworkType) -> IPvAnyInterfaceType:
+            """Validate an IPv4 or IPv6 interface."""
+            try:
+                return IPv4Interface(value)
+            except ValueError:
+                pass
+
+            try:
+                return IPv6Interface(value)
+            except ValueError:
+                raise PydanticCustomError('ip_any_interface', 'value is not a valid IPv4 or IPv6 interface')
+
+        @classmethod
+        def __get_pydantic_json_schema__(
+            cls, core_schema: core_schema.CoreSchema, handler: _schema_generation_shared.GetJsonSchemaHandler
+        ) -> JsonSchemaValue:
+            field_schema = {}
+            field_schema.update(type='string', format='ipvanyinterface')
+            return field_schema
+
+        @classmethod
+        def __get_pydantic_core_schema__(
+            cls,
+            _source: type[Any],
+            _handler: GetCoreSchemaHandler,
+        ) -> core_schema.CoreSchema:
+            return core_schema.no_info_plain_validator_function(
+                cls._validate, serialization=core_schema.to_string_ser_schema()
+            )
+
+        @classmethod
+        def _validate(cls, input_value: NetworkType, /) -> IPvAnyInterfaceType:
+            return cls(input_value)  # type: ignore[return-value]
+
+    class IPvAnyNetwork:
+        """Validate an IPv4 or IPv6 network."""
+
+        __slots__ = ()
+
+        def __new__(cls, value: NetworkType) -> IPvAnyNetworkType:
+            """Validate an IPv4 or IPv6 network."""
+            # Assume IP Network is defined with a default value for `strict` argument.
+            # Define your own class if you want to specify network address check strictness.
+            try:
+                return IPv4Network(value)
+            except ValueError:
+                pass
+
+            try:
+                return IPv6Network(value)
+            except ValueError:
+                raise PydanticCustomError('ip_any_network', 'value is not a valid IPv4 or IPv6 network')
+
+        @classmethod
+        def __get_pydantic_json_schema__(
+            cls, core_schema: core_schema.CoreSchema, handler: _schema_generation_shared.GetJsonSchemaHandler
+        ) -> JsonSchemaValue:
+            field_schema = {}
+            field_schema.update(type='string', format='ipvanynetwork')
+            return field_schema
+
+        @classmethod
+        def __get_pydantic_core_schema__(
+            cls,
+            _source: type[Any],
+            _handler: GetCoreSchemaHandler,
+        ) -> core_schema.CoreSchema:
+            return core_schema.no_info_plain_validator_function(
+                cls._validate, serialization=core_schema.to_string_ser_schema()
+            )
+
+        @classmethod
+        def _validate(cls, input_value: NetworkType, /) -> IPvAnyNetworkType:
+            return cls(input_value)  # type: ignore[return-value]
+
+
+def _build_pretty_email_regex() -> re.Pattern[str]:
+    name_chars = r'[\w!#$%&\'*+\-/=?^_`{|}~]'
+    unquoted_name_group = rf'((?:{name_chars}+\s+)*{name_chars}+)'
+    quoted_name_group = r'"((?:[^"]|\")+)"'
+    email_group = r'<(.+)>'
+    return re.compile(rf'\s*(?:{unquoted_name_group}|{quoted_name_group})?\s*{email_group}\s*')
+
+
+pretty_email_regex = _build_pretty_email_regex()
+
+MAX_EMAIL_LENGTH = 2048
+"""Maximum length for an email.
+A somewhat arbitrary but very generous number compared to what is allowed by most implementations.
+"""
+
+
+def validate_email(value: str) -> tuple[str, str]:
+    """Email address validation using [email-validator](https://pypi.org/project/email-validator/).
+
+    Returns:
+        A tuple containing the local part of the email (or the name for "pretty" email addresses)
+            and the normalized email.
+
+    Raises:
+        PydanticCustomError: If the email is invalid.
+
+    Note:
+        Note that:
+
+        * Raw IP address (literal) domain parts are not allowed.
+        * `"John Doe "` style "pretty" email addresses are processed.
+        * Spaces are striped from the beginning and end of addresses, but no error is raised.
+    """
+    if email_validator is None:
+        import_email_validator()
+
+    if len(value) > MAX_EMAIL_LENGTH:
+        raise PydanticCustomError(
+            'value_error',
+            'value is not a valid email address: {reason}',
+            {'reason': f'Length must not exceed {MAX_EMAIL_LENGTH} characters'},
+        )
+
+    m = pretty_email_regex.fullmatch(value)
+    name: str | None = None
+    if m:
+        unquoted_name, quoted_name, value = m.groups()
+        name = unquoted_name or quoted_name
+
+    email = value.strip()
+
+    try:
+        parts = email_validator.validate_email(email, check_deliverability=False)
+    except email_validator.EmailNotValidError as e:
+        raise PydanticCustomError(
+            'value_error', 'value is not a valid email address: {reason}', {'reason': str(e.args[0])}
+        ) from e
+
+    email = parts.normalized
+    assert email is not None
+    name = name or parts.local_part
+    return name, email
+
+
+__getattr__ = getattr_migration(__name__)
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pydantic/parse.py b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/parse.py
new file mode 100644
index 0000000000000000000000000000000000000000..68b7f0464ece32edfb955eec0cb24655752716d6
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/parse.py
@@ -0,0 +1,5 @@
+"""The `parse` module is a backport module from V1."""
+
+from ._migration import getattr_migration
+
+__getattr__ = getattr_migration(__name__)
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pydantic/py.typed b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/py.typed
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pydantic/root_model.py b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/root_model.py
new file mode 100644
index 0000000000000000000000000000000000000000..80a54201c427800ab28540296c31d9701e5093c3
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/root_model.py
@@ -0,0 +1,155 @@
+"""RootModel class and type definitions."""
+
+from __future__ import annotations as _annotations
+
+from copy import copy, deepcopy
+from typing import TYPE_CHECKING, Any, Generic, Literal, TypeVar
+
+from pydantic_core import PydanticUndefined
+from typing_extensions import Self, dataclass_transform
+
+from . import PydanticUserError
+from ._internal import _model_construction, _repr
+from .main import BaseModel, _object_setattr
+
+if TYPE_CHECKING:
+    from .fields import Field as PydanticModelField
+    from .fields import PrivateAttr as PydanticModelPrivateAttr
+
+    # dataclass_transform could be applied to RootModel directly, but `ModelMetaclass`'s dataclass_transform
+    # takes priority (at least with pyright). We trick type checkers into thinking we apply dataclass_transform
+    # on a new metaclass.
+    @dataclass_transform(kw_only_default=False, field_specifiers=(PydanticModelField, PydanticModelPrivateAttr))
+    class _RootModelMetaclass(_model_construction.ModelMetaclass): ...
+else:
+    _RootModelMetaclass = _model_construction.ModelMetaclass
+
+__all__ = ('RootModel',)
+
+RootModelRootType = TypeVar('RootModelRootType')
+
+
+class RootModel(BaseModel, Generic[RootModelRootType], metaclass=_RootModelMetaclass):
+    """!!! abstract "Usage Documentation"
+        [`RootModel` and Custom Root Types](../concepts/models.md#rootmodel-and-custom-root-types)
+
+    A Pydantic `BaseModel` for the root object of the model.
+
+    Attributes:
+        root: The root object of the model.
+        __pydantic_root_model__: Whether the model is a RootModel.
+        __pydantic_private__: Private fields in the model.
+        __pydantic_extra__: Extra fields in the model.
+
+    """
+
+    __pydantic_root_model__ = True
+    __pydantic_private__ = None
+    __pydantic_extra__ = None
+
+    root: RootModelRootType
+
+    def __init_subclass__(cls, **kwargs):
+        extra = cls.model_config.get('extra')
+        if extra is not None:
+            raise PydanticUserError(
+                "`RootModel` does not support setting `model_config['extra']`", code='root-model-extra'
+            )
+        super().__init_subclass__(**kwargs)
+
+    def __init__(self, /, root: RootModelRootType = PydanticUndefined, **data) -> None:  # type: ignore
+        __tracebackhide__ = True
+        if data:
+            if root is not PydanticUndefined:
+                raise ValueError(
+                    '"RootModel.__init__" accepts either a single positional argument or arbitrary keyword arguments'
+                )
+            root = data  # type: ignore
+        self.__pydantic_validator__.validate_python(root, self_instance=self)
+
+    __init__.__pydantic_base_init__ = True  # pyright: ignore[reportFunctionMemberAccess]
+
+    @classmethod
+    def model_construct(cls, root: RootModelRootType, _fields_set: set[str] | None = None) -> Self:  # type: ignore
+        """Create a new model using the provided root object and update fields set.
+
+        Args:
+            root: The root object of the model.
+            _fields_set: The set of fields to be updated.
+
+        Returns:
+            The new model.
+
+        Raises:
+            NotImplemented: If the model is not a subclass of `RootModel`.
+        """
+        return super().model_construct(root=root, _fields_set=_fields_set)
+
+    def __getstate__(self) -> dict[Any, Any]:
+        return {
+            '__dict__': self.__dict__,
+            '__pydantic_fields_set__': self.__pydantic_fields_set__,
+        }
+
+    def __setstate__(self, state: dict[Any, Any]) -> None:
+        _object_setattr(self, '__pydantic_fields_set__', state['__pydantic_fields_set__'])
+        _object_setattr(self, '__dict__', state['__dict__'])
+
+    def __copy__(self) -> Self:
+        """Returns a shallow copy of the model."""
+        cls = type(self)
+        m = cls.__new__(cls)
+        _object_setattr(m, '__dict__', copy(self.__dict__))
+        _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))
+        return m
+
+    def __deepcopy__(self, memo: dict[int, Any] | None = None) -> Self:
+        """Returns a deep copy of the model."""
+        cls = type(self)
+        m = cls.__new__(cls)
+        _object_setattr(m, '__dict__', deepcopy(self.__dict__, memo=memo))
+        # This next line doesn't need a deepcopy because __pydantic_fields_set__ is a set[str],
+        # and attempting a deepcopy would be marginally slower.
+        _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))
+        return m
+
+    if TYPE_CHECKING:
+
+        def model_dump(  # type: ignore
+            self,
+            *,
+            mode: Literal['json', 'python'] | str = 'python',
+            include: Any = None,
+            exclude: Any = None,
+            context: dict[str, Any] | None = None,
+            by_alias: bool | None = None,
+            exclude_unset: bool = False,
+            exclude_defaults: bool = False,
+            exclude_none: bool = False,
+            exclude_computed_fields: bool = False,
+            round_trip: bool = False,
+            warnings: bool | Literal['none', 'warn', 'error'] = True,
+            serialize_as_any: bool = False,
+        ) -> Any:
+            """This method is included just to get a more accurate return type for type checkers.
+            It is included in this `if TYPE_CHECKING:` block since no override is actually necessary.
+
+            See the documentation of `BaseModel.model_dump` for more details about the arguments.
+
+            Generally, this method will have a return type of `RootModelRootType`, assuming that `RootModelRootType` is
+            not a `BaseModel` subclass. If `RootModelRootType` is a `BaseModel` subclass, then the return
+            type will likely be `dict[str, Any]`, as `model_dump` calls are recursive. The return type could
+            even be something different, in the case of a custom serializer.
+            Thus, `Any` is used here to catch all of these cases.
+            """
+            ...
+
+    def __eq__(self, other: Any) -> bool:
+        if not isinstance(other, RootModel):
+            return NotImplemented
+        return self.__pydantic_fields__['root'].annotation == other.__pydantic_fields__[
+            'root'
+        ].annotation and super().__eq__(other)
+
+    def __repr_args__(self) -> _repr.ReprArgs:
+        yield 'root', self.root
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pydantic/schema.py b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/schema.py
new file mode 100644
index 0000000000000000000000000000000000000000..a3245a61afd0f59143f38ee809ee2d784d9198eb
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/schema.py
@@ -0,0 +1,5 @@
+"""The `schema` module is a backport module from V1."""
+
+from ._migration import getattr_migration
+
+__getattr__ = getattr_migration(__name__)
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pydantic/tools.py b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/tools.py
new file mode 100644
index 0000000000000000000000000000000000000000..fdc68c4f4a35e8d8200b3aafcda63d43839da375
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/tools.py
@@ -0,0 +1,5 @@
+"""The `tools` module is a backport module from V1."""
+
+from ._migration import getattr_migration
+
+__getattr__ = getattr_migration(__name__)
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pydantic/type_adapter.py b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/type_adapter.py
new file mode 100644
index 0000000000000000000000000000000000000000..6f1a082eab9906b8938f35901a45ca9ca41991fb
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/type_adapter.py
@@ -0,0 +1,795 @@
+"""Type adapter specification."""
+
+from __future__ import annotations as _annotations
+
+import sys
+import types
+from collections.abc import Callable, Iterable
+from dataclasses import is_dataclass
+from types import FrameType
+from typing import (
+    Any,
+    Generic,
+    Literal,
+    TypeVar,
+    cast,
+    final,
+    overload,
+)
+
+from pydantic_core import CoreSchema, SchemaSerializer, SchemaValidator, Some
+from typing_extensions import ParamSpec, is_typeddict
+
+from pydantic.errors import PydanticUserError
+from pydantic.main import BaseModel, IncEx
+
+from ._internal import _config, _generate_schema, _mock_val_ser, _namespace_utils, _repr, _typing_extra, _utils
+from .config import ConfigDict, ExtraValues
+from .errors import PydanticUndefinedAnnotation
+from .json_schema import (
+    DEFAULT_REF_TEMPLATE,
+    GenerateJsonSchema,
+    JsonSchemaKeyT,
+    JsonSchemaMode,
+    JsonSchemaValue,
+)
+from .plugin._schema_validator import PluggableSchemaValidator, create_schema_validator
+
+T = TypeVar('T')
+R = TypeVar('R')
+P = ParamSpec('P')
+TypeAdapterT = TypeVar('TypeAdapterT', bound='TypeAdapter')
+
+
+def _getattr_no_parents(obj: Any, attribute: str) -> Any:
+    """Returns the attribute value without attempting to look up attributes from parent types."""
+    if hasattr(obj, '__dict__'):
+        try:
+            return obj.__dict__[attribute]
+        except KeyError:
+            pass
+
+    slots = getattr(obj, '__slots__', None)
+    if slots is not None and attribute in slots:
+        return getattr(obj, attribute)
+    else:
+        raise AttributeError(attribute)
+
+
+def _type_has_config(type_: Any) -> bool:
+    """Returns whether the type has config."""
+    type_ = _typing_extra.annotated_type(type_) or type_
+    try:
+        return issubclass(type_, BaseModel) or is_dataclass(type_) or is_typeddict(type_)
+    except TypeError:
+        # type is not a class
+        return False
+
+
+@final
+class TypeAdapter(Generic[T]):
+    """!!! abstract "Usage Documentation"
+        [`TypeAdapter`](../concepts/type_adapter.md)
+
+    Type adapters provide a flexible way to perform validation and serialization based on a Python type.
+
+    A `TypeAdapter` instance exposes some of the functionality from `BaseModel` instance methods
+    for types that do not have such methods (such as dataclasses, primitive types, and more).
+
+    **Note:** `TypeAdapter` instances are not types, and cannot be used as type annotations for fields.
+
+    Args:
+        type: The type associated with the `TypeAdapter`.
+        config: Configuration for the `TypeAdapter`, should be a dictionary conforming to
+            [`ConfigDict`][pydantic.config.ConfigDict].
+
+            !!! note
+                You cannot provide a configuration when instantiating a `TypeAdapter` if the type you're using
+                has its own config that cannot be overridden (ex: `BaseModel`, `TypedDict`, and `dataclass`). A
+                [`type-adapter-config-unused`](../errors/usage_errors.md#type-adapter-config-unused) error will
+                be raised in this case.
+        _parent_depth: Depth at which to search for the [parent frame][frame-objects]. This frame is used when
+            resolving forward annotations during schema building, by looking for the globals and locals of this
+            frame. Defaults to 2, which will result in the frame where the `TypeAdapter` was instantiated.
+
+            !!! note
+                This parameter is named with an underscore to suggest its private nature and discourage use.
+                It may be deprecated in a minor version, so we only recommend using it if you're comfortable
+                with potential change in behavior/support. It's default value is 2 because internally,
+                the `TypeAdapter` class makes another call to fetch the frame.
+        module: The module that passes to plugin if provided.
+
+    Attributes:
+        core_schema: The core schema for the type.
+        validator: The schema validator for the type.
+        serializer: The schema serializer for the type.
+        pydantic_complete: Whether the core schema for the type is successfully built.
+
+    ??? tip "Compatibility with `mypy`"
+        Depending on the type used, `mypy` might raise an error when instantiating a `TypeAdapter`. As a workaround, you can explicitly
+        annotate your variable:
+
+        ```py
+        from typing import Union
+
+        from pydantic import TypeAdapter
+
+        ta: TypeAdapter[Union[str, int]] = TypeAdapter(Union[str, int])  # type: ignore[arg-type]
+        ```
+
+    ??? info "Namespace management nuances and implementation details"
+
+        Here, we collect some notes on namespace management, and subtle differences from `BaseModel`:
+
+        `BaseModel` uses its own `__module__` to find out where it was defined
+        and then looks for symbols to resolve forward references in those globals.
+        On the other hand, `TypeAdapter` can be initialized with arbitrary objects,
+        which may not be types and thus do not have a `__module__` available.
+        So instead we look at the globals in our parent stack frame.
+
+        It is expected that the `ns_resolver` passed to this function will have the correct
+        namespace for the type we're adapting. See the source code for `TypeAdapter.__init__`
+        and `TypeAdapter.rebuild` for various ways to construct this namespace.
+
+        This works for the case where this function is called in a module that
+        has the target of forward references in its scope, but
+        does not always work for more complex cases.
+
+        For example, take the following:
+
+        ```python {title="a.py"}
+        IntList = list[int]
+        OuterDict = dict[str, 'IntList']
+        ```
+
+        ```python {test="skip" title="b.py"}
+        from a import OuterDict
+
+        from pydantic import TypeAdapter
+
+        IntList = int  # replaces the symbol the forward reference is looking for
+        v = TypeAdapter(OuterDict)
+        v({'x': 1})  # should fail but doesn't
+        ```
+
+        If `OuterDict` were a `BaseModel`, this would work because it would resolve
+        the forward reference within the `a.py` namespace.
+        But `TypeAdapter(OuterDict)` can't determine what module `OuterDict` came from.
+
+        In other words, the assumption that _all_ forward references exist in the
+        module we are being called from is not technically always true.
+        Although most of the time it is and it works fine for recursive models and such,
+        `BaseModel`'s behavior isn't perfect either and _can_ break in similar ways,
+        so there is no right or wrong between the two.
+
+        But at the very least this behavior is _subtly_ different from `BaseModel`'s.
+    """
+
+    core_schema: CoreSchema
+    validator: SchemaValidator | PluggableSchemaValidator
+    serializer: SchemaSerializer
+    pydantic_complete: bool
+
+    @overload
+    def __init__(
+        self,
+        type: type[T],
+        *,
+        config: ConfigDict | None = ...,
+        _parent_depth: int = ...,
+        module: str | None = ...,
+    ) -> None: ...
+
+    # This second overload is for unsupported special forms (such as Annotated, Union, etc.)
+    # Currently there is no way to type this correctly
+    # See https://github.com/python/typing/pull/1618
+    @overload
+    def __init__(
+        self,
+        type: Any,
+        *,
+        config: ConfigDict | None = ...,
+        _parent_depth: int = ...,
+        module: str | None = ...,
+    ) -> None: ...
+
+    def __init__(
+        self,
+        type: Any,
+        *,
+        config: ConfigDict | None = None,
+        _parent_depth: int = 2,
+        module: str | None = None,
+    ) -> None:
+        if _type_has_config(type) and config is not None:
+            raise PydanticUserError(
+                'Cannot use `config` when the type is a BaseModel, dataclass or TypedDict.'
+                ' These types can have their own config and setting the config via the `config`'
+                ' parameter to TypeAdapter will not override it, thus the `config` you passed to'
+                ' TypeAdapter becomes meaningless, which is probably not what you want.',
+                code='type-adapter-config-unused',
+            )
+
+        self._type = type
+        self._config = config
+        self._parent_depth = _parent_depth
+        self.pydantic_complete = False
+
+        parent_frame = self._fetch_parent_frame()
+        if isinstance(type, types.FunctionType):
+            # Special case functions, which are *not* pushed to the `NsResolver` stack and without this special case
+            # would only have access to the parent namespace where the `TypeAdapter` was instantiated (if the function is defined
+            # in another module, we need to look at that module's globals).
+            if parent_frame is not None:
+                # `f_locals` is the namespace where the type adapter was instantiated (~ to `f_globals` if at the module level):
+                parent_ns = parent_frame.f_locals
+            else:  # pragma: no cover
+                parent_ns = None
+            globalns, localns = _namespace_utils.ns_for_function(
+                type,
+                parent_namespace=parent_ns,
+            )
+            parent_namespace = None
+        else:
+            if parent_frame is not None:
+                globalns = parent_frame.f_globals
+                # Do not provide a local ns if the type adapter happens to be instantiated at the module level:
+                localns = parent_frame.f_locals if parent_frame.f_locals is not globalns else {}
+            else:  # pragma: no cover
+                globalns = {}
+                localns = {}
+            parent_namespace = localns
+
+        self._module_name = module or cast(str, globalns.get('__name__', ''))
+        self._init_core_attrs(
+            ns_resolver=_namespace_utils.NsResolver(
+                namespaces_tuple=_namespace_utils.NamespacesTuple(locals=localns, globals=globalns),
+                parent_namespace=parent_namespace,
+            ),
+            force=False,
+        )
+
+    def _fetch_parent_frame(self) -> FrameType | None:
+        frame = sys._getframe(self._parent_depth)
+        if frame.f_globals.get('__name__') == 'typing':
+            # Because `TypeAdapter` is generic, explicitly parametrizing the class results
+            # in a `typing._GenericAlias` instance, which proxies instantiation calls to the
+            # "real" `TypeAdapter` class and thus adding an extra frame to the call. To avoid
+            # pulling anything from the `typing` module, use the correct frame (the one before):
+            return frame.f_back
+
+        return frame
+
+    def _init_core_attrs(
+        self, ns_resolver: _namespace_utils.NsResolver, force: bool, raise_errors: bool = False
+    ) -> bool:
+        """Initialize the core schema, validator, and serializer for the type.
+
+        Args:
+            ns_resolver: The namespace resolver to use when building the core schema for the adapted type.
+            force: Whether to force the construction of the core schema, validator, and serializer.
+                If `force` is set to `False` and `_defer_build` is `True`, the core schema, validator, and serializer will be set to mocks.
+            raise_errors: Whether to raise errors if initializing any of the core attrs fails.
+
+        Returns:
+            `True` if the core schema, validator, and serializer were successfully initialized, otherwise `False`.
+
+        Raises:
+            PydanticUndefinedAnnotation: If `PydanticUndefinedAnnotation` occurs in`__get_pydantic_core_schema__`
+                and `raise_errors=True`.
+        """
+        if not force and self._defer_build:
+            _mock_val_ser.set_type_adapter_mocks(self)
+            self.pydantic_complete = False
+            return False
+
+        try:
+            self.core_schema = _getattr_no_parents(self._type, '__pydantic_core_schema__')
+            self.validator = _getattr_no_parents(self._type, '__pydantic_validator__')
+            self.serializer = _getattr_no_parents(self._type, '__pydantic_serializer__')
+
+            # TODO: we don't go through the rebuild logic here directly because we don't want
+            # to repeat all of the namespace fetching logic that we've already done
+            # so we simply skip to the block below that does the actual schema generation
+            if (
+                isinstance(self.core_schema, _mock_val_ser.MockCoreSchema)
+                or isinstance(self.validator, _mock_val_ser.MockValSer)
+                or isinstance(self.serializer, _mock_val_ser.MockValSer)
+            ):
+                raise AttributeError()
+        except AttributeError:
+            config_wrapper = _config.ConfigWrapper(self._config)
+
+            schema_generator = _generate_schema.GenerateSchema(config_wrapper, ns_resolver=ns_resolver)
+
+            try:
+                core_schema = schema_generator.generate_schema(self._type)
+            except PydanticUndefinedAnnotation:
+                if raise_errors:
+                    raise
+                _mock_val_ser.set_type_adapter_mocks(self)
+                return False
+
+            try:
+                self.core_schema = schema_generator.clean_schema(core_schema)
+            except _generate_schema.InvalidSchemaError:
+                _mock_val_ser.set_type_adapter_mocks(self)
+                return False
+
+            core_config = config_wrapper.core_config(None)
+
+            self.validator = create_schema_validator(
+                schema=self.core_schema,
+                schema_type=self._type,
+                schema_type_module=self._module_name,
+                schema_type_name=str(self._type),
+                schema_kind='TypeAdapter',
+                config=core_config,
+                plugin_settings=config_wrapper.plugin_settings,
+            )
+            self.serializer = SchemaSerializer(self.core_schema, core_config)
+
+        self.pydantic_complete = True
+        return True
+
+    @property
+    def _defer_build(self) -> bool:
+        config = self._config if self._config is not None else self._model_config
+        if config:
+            return config.get('defer_build') is True
+        return False
+
+    @property
+    def _model_config(self) -> ConfigDict | None:
+        type_: Any = _typing_extra.annotated_type(self._type) or self._type  # Eg FastAPI heavily uses Annotated
+        if _utils.lenient_issubclass(type_, BaseModel):
+            return type_.model_config
+        return getattr(type_, '__pydantic_config__', None)
+
+    def __repr__(self) -> str:
+        return f'TypeAdapter({_repr.display_as_type(self._type)})'
+
+    def rebuild(
+        self,
+        *,
+        force: bool = False,
+        raise_errors: bool = True,
+        _parent_namespace_depth: int = 2,
+        _types_namespace: _namespace_utils.MappingNamespace | None = None,
+    ) -> bool | None:
+        """Try to rebuild the pydantic-core schema for the adapter's type.
+
+        This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
+        the initial attempt to build the schema, and automatic rebuilding fails.
+
+        Args:
+            force: Whether to force the rebuilding of the type adapter's schema, defaults to `False`.
+            raise_errors: Whether to raise errors, defaults to `True`.
+            _parent_namespace_depth: Depth at which to search for the [parent frame][frame-objects]. This
+                frame is used when resolving forward annotations during schema rebuilding, by looking for
+                the locals of this frame. Defaults to 2, which will result in the frame where the method
+                was called.
+            _types_namespace: An explicit types namespace to use, instead of using the local namespace
+                from the parent frame. Defaults to `None`.
+
+        Returns:
+            Returns `None` if the schema is already "complete" and rebuilding was not required.
+            If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
+        """
+        if not force and self.pydantic_complete:
+            return None
+
+        if _types_namespace is not None:
+            rebuild_ns = _types_namespace
+        elif _parent_namespace_depth > 0:
+            rebuild_ns = _typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth, force=True) or {}
+        else:
+            rebuild_ns = {}
+
+        # we have to manually fetch globals here because there's no type on the stack of the NsResolver
+        # and so we skip the globalns = get_module_ns_of(typ) call that would normally happen
+        globalns = sys._getframe(max(_parent_namespace_depth - 1, 1)).f_globals
+        ns_resolver = _namespace_utils.NsResolver(
+            namespaces_tuple=_namespace_utils.NamespacesTuple(locals=rebuild_ns, globals=globalns),
+            parent_namespace=rebuild_ns,
+        )
+        return self._init_core_attrs(ns_resolver=ns_resolver, force=True, raise_errors=raise_errors)
+
+    def validate_python(
+        self,
+        object: Any,
+        /,
+        *,
+        strict: bool | None = None,
+        extra: ExtraValues | None = None,
+        from_attributes: bool | None = None,
+        context: Any | None = None,
+        experimental_allow_partial: bool | Literal['off', 'on', 'trailing-strings'] = False,
+        by_alias: bool | None = None,
+        by_name: bool | None = None,
+    ) -> T:
+        """Validate a Python object against the model.
+
+        Args:
+            object: The Python object to validate against the model.
+            strict: Whether to strictly check types.
+            extra: Whether to ignore, allow, or forbid extra data during model validation.
+                See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
+            from_attributes: Whether to extract data from object attributes.
+            context: Additional context to pass to the validator.
+            experimental_allow_partial: **Experimental** whether to enable
+                [partial validation](../concepts/experimental.md#partial-validation), e.g. to process streams.
+                * False / 'off': Default behavior, no partial validation.
+                * True / 'on': Enable partial validation.
+                * 'trailing-strings': Enable partial validation and allow trailing strings in the input.
+            by_alias: Whether to use the field's alias when validating against the provided input data.
+            by_name: Whether to use the field's name when validating against the provided input data.
+
+        !!! note
+            When using `TypeAdapter` with a Pydantic `dataclass`, the use of the `from_attributes`
+            argument is not supported.
+
+        Returns:
+            The validated object.
+        """
+        if by_alias is False and by_name is not True:
+            raise PydanticUserError(
+                'At least one of `by_alias` or `by_name` must be set to True.',
+                code='validate-by-alias-and-name-false',
+            )
+
+        return self.validator.validate_python(
+            object,
+            strict=strict,
+            extra=extra,
+            from_attributes=from_attributes,
+            context=context,
+            allow_partial=experimental_allow_partial,
+            by_alias=by_alias,
+            by_name=by_name,
+        )
+
+    def validate_json(
+        self,
+        data: str | bytes | bytearray,
+        /,
+        *,
+        strict: bool | None = None,
+        extra: ExtraValues | None = None,
+        context: Any | None = None,
+        experimental_allow_partial: bool | Literal['off', 'on', 'trailing-strings'] = False,
+        by_alias: bool | None = None,
+        by_name: bool | None = None,
+    ) -> T:
+        """!!! abstract "Usage Documentation"
+            [JSON Parsing](../concepts/json.md#json-parsing)
+
+        Validate a JSON string or bytes against the model.
+
+        Args:
+            data: The JSON data to validate against the model.
+            strict: Whether to strictly check types.
+            extra: Whether to ignore, allow, or forbid extra data during model validation.
+                See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
+            context: Additional context to use during validation.
+            experimental_allow_partial: **Experimental** whether to enable
+                [partial validation](../concepts/experimental.md#partial-validation), e.g. to process streams.
+                * False / 'off': Default behavior, no partial validation.
+                * True / 'on': Enable partial validation.
+                * 'trailing-strings': Enable partial validation and allow trailing strings in the input.
+            by_alias: Whether to use the field's alias when validating against the provided input data.
+            by_name: Whether to use the field's name when validating against the provided input data.
+
+        Returns:
+            The validated object.
+        """
+        if by_alias is False and by_name is not True:
+            raise PydanticUserError(
+                'At least one of `by_alias` or `by_name` must be set to True.',
+                code='validate-by-alias-and-name-false',
+            )
+
+        return self.validator.validate_json(
+            data,
+            strict=strict,
+            extra=extra,
+            context=context,
+            allow_partial=experimental_allow_partial,
+            by_alias=by_alias,
+            by_name=by_name,
+        )
+
+    def validate_strings(
+        self,
+        obj: Any,
+        /,
+        *,
+        strict: bool | None = None,
+        extra: ExtraValues | None = None,
+        context: Any | None = None,
+        experimental_allow_partial: bool | Literal['off', 'on', 'trailing-strings'] = False,
+        by_alias: bool | None = None,
+        by_name: bool | None = None,
+    ) -> T:
+        """Validate object contains string data against the model.
+
+        Args:
+            obj: The object contains string data to validate.
+            strict: Whether to strictly check types.
+            extra: Whether to ignore, allow, or forbid extra data during model validation.
+                See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
+            context: Additional context to use during validation.
+            experimental_allow_partial: **Experimental** whether to enable
+                [partial validation](../concepts/experimental.md#partial-validation), e.g. to process streams.
+                * False / 'off': Default behavior, no partial validation.
+                * True / 'on': Enable partial validation.
+                * 'trailing-strings': Enable partial validation and allow trailing strings in the input.
+            by_alias: Whether to use the field's alias when validating against the provided input data.
+            by_name: Whether to use the field's name when validating against the provided input data.
+
+        Returns:
+            The validated object.
+        """
+        if by_alias is False and by_name is not True:
+            raise PydanticUserError(
+                'At least one of `by_alias` or `by_name` must be set to True.',
+                code='validate-by-alias-and-name-false',
+            )
+
+        return self.validator.validate_strings(
+            obj,
+            strict=strict,
+            extra=extra,
+            context=context,
+            allow_partial=experimental_allow_partial,
+            by_alias=by_alias,
+            by_name=by_name,
+        )
+
+    def get_default_value(self, *, strict: bool | None = None, context: Any | None = None) -> Some[T] | None:
+        """Get the default value for the wrapped type.
+
+        Args:
+            strict: Whether to strictly check types.
+            context: Additional context to pass to the validator.
+
+        Returns:
+            The default value wrapped in a `Some` if there is one or None if not.
+        """
+        return self.validator.get_default_value(strict=strict, context=context)
+
+    def dump_python(
+        self,
+        instance: T,
+        /,
+        *,
+        mode: Literal['json', 'python'] = 'python',
+        include: IncEx | None = None,
+        exclude: IncEx | None = None,
+        by_alias: bool | None = None,
+        exclude_unset: bool = False,
+        exclude_defaults: bool = False,
+        exclude_none: bool = False,
+        exclude_computed_fields: bool = False,
+        round_trip: bool = False,
+        warnings: bool | Literal['none', 'warn', 'error'] = True,
+        fallback: Callable[[Any], Any] | None = None,
+        serialize_as_any: bool = False,
+        context: Any | None = None,
+    ) -> Any:
+        """Dump an instance of the adapted type to a Python object.
+
+        Args:
+            instance: The Python object to serialize.
+            mode: The output format.
+            include: Fields to include in the output.
+            exclude: Fields to exclude from the output.
+            by_alias: Whether to use alias names for field names.
+            exclude_unset: Whether to exclude unset fields.
+            exclude_defaults: Whether to exclude fields with default values.
+            exclude_none: Whether to exclude fields with None values.
+            exclude_computed_fields: Whether to exclude computed fields.
+                While this can be useful for round-tripping, it is usually recommended to use the dedicated
+                `round_trip` parameter instead.
+            round_trip: Whether to output the serialized data in a way that is compatible with deserialization.
+            warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
+                "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
+            fallback: A function to call when an unknown value is encountered. If not provided,
+                a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
+            serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
+            context: Additional context to pass to the serializer.
+
+        Returns:
+            The serialized object.
+        """
+        return self.serializer.to_python(
+            instance,
+            mode=mode,
+            by_alias=by_alias,
+            include=include,
+            exclude=exclude,
+            exclude_unset=exclude_unset,
+            exclude_defaults=exclude_defaults,
+            exclude_none=exclude_none,
+            exclude_computed_fields=exclude_computed_fields,
+            round_trip=round_trip,
+            warnings=warnings,
+            fallback=fallback,
+            serialize_as_any=serialize_as_any,
+            context=context,
+        )
+
+    def dump_json(
+        self,
+        instance: T,
+        /,
+        *,
+        indent: int | None = None,
+        ensure_ascii: bool = False,
+        include: IncEx | None = None,
+        exclude: IncEx | None = None,
+        by_alias: bool | None = None,
+        exclude_unset: bool = False,
+        exclude_defaults: bool = False,
+        exclude_none: bool = False,
+        exclude_computed_fields: bool = False,
+        round_trip: bool = False,
+        warnings: bool | Literal['none', 'warn', 'error'] = True,
+        fallback: Callable[[Any], Any] | None = None,
+        serialize_as_any: bool = False,
+        context: Any | None = None,
+    ) -> bytes:
+        """!!! abstract "Usage Documentation"
+            [JSON Serialization](../concepts/json.md#json-serialization)
+
+        Serialize an instance of the adapted type to JSON.
+
+        Args:
+            instance: The instance to be serialized.
+            indent: Number of spaces for JSON indentation.
+            ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
+                If `False` (the default), these characters will be output as-is.
+            include: Fields to include.
+            exclude: Fields to exclude.
+            by_alias: Whether to use alias names for field names.
+            exclude_unset: Whether to exclude unset fields.
+            exclude_defaults: Whether to exclude fields with default values.
+            exclude_none: Whether to exclude fields with a value of `None`.
+            exclude_computed_fields: Whether to exclude computed fields.
+                While this can be useful for round-tripping, it is usually recommended to use the dedicated
+                `round_trip` parameter instead.
+            round_trip: Whether to serialize and deserialize the instance to ensure round-tripping.
+            warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
+                "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
+            fallback: A function to call when an unknown value is encountered. If not provided,
+                a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
+            serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
+            context: Additional context to pass to the serializer.
+
+        Returns:
+            The JSON representation of the given instance as bytes.
+        """
+        return self.serializer.to_json(
+            instance,
+            indent=indent,
+            ensure_ascii=ensure_ascii,
+            include=include,
+            exclude=exclude,
+            by_alias=by_alias,
+            exclude_unset=exclude_unset,
+            exclude_defaults=exclude_defaults,
+            exclude_none=exclude_none,
+            exclude_computed_fields=exclude_computed_fields,
+            round_trip=round_trip,
+            warnings=warnings,
+            fallback=fallback,
+            serialize_as_any=serialize_as_any,
+            context=context,
+        )
+
+    def json_schema(
+        self,
+        *,
+        by_alias: bool = True,
+        ref_template: str = DEFAULT_REF_TEMPLATE,
+        union_format: Literal['any_of', 'primitive_type_array'] = 'any_of',
+        schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
+        mode: JsonSchemaMode = 'validation',
+    ) -> dict[str, Any]:
+        """Generate a JSON schema for the adapted type.
+
+        Args:
+            by_alias: Whether to use alias names for field names.
+            ref_template: The format string used for generating $ref strings.
+            union_format: The format to use when combining schemas from unions together. Can be one of:
+
+                - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
+                keyword to combine schemas (the default).
+                - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
+                keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
+                type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
+                `any_of`.
+            schema_generator: To override the logic used to generate the JSON schema, as a subclass of
+                `GenerateJsonSchema` with your desired modifications
+            mode: The mode in which to generate the schema.
+            schema_generator: The generator class used for creating the schema.
+            mode: The mode to use for schema generation.
+
+        Returns:
+            The JSON schema for the model as a dictionary.
+        """
+        schema_generator_instance = schema_generator(
+            by_alias=by_alias, ref_template=ref_template, union_format=union_format
+        )
+        if isinstance(self.core_schema, _mock_val_ser.MockCoreSchema):
+            self.core_schema.rebuild()
+            assert not isinstance(self.core_schema, _mock_val_ser.MockCoreSchema), 'this is a bug! please report it'
+        return schema_generator_instance.generate(self.core_schema, mode=mode)
+
+    @staticmethod
+    def json_schemas(
+        inputs: Iterable[tuple[JsonSchemaKeyT, JsonSchemaMode, TypeAdapter[Any]]],
+        /,
+        *,
+        by_alias: bool = True,
+        title: str | None = None,
+        description: str | None = None,
+        ref_template: str = DEFAULT_REF_TEMPLATE,
+        union_format: Literal['any_of', 'primitive_type_array'] = 'any_of',
+        schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
+    ) -> tuple[dict[tuple[JsonSchemaKeyT, JsonSchemaMode], JsonSchemaValue], JsonSchemaValue]:
+        """Generate a JSON schema including definitions from multiple type adapters.
+
+        Args:
+            inputs: Inputs to schema generation. The first two items will form the keys of the (first)
+                output mapping; the type adapters will provide the core schemas that get converted into
+                definitions in the output JSON schema.
+            by_alias: Whether to use alias names.
+            title: The title for the schema.
+            description: The description for the schema.
+            ref_template: The format string used for generating $ref strings.
+            union_format: The format to use when combining schemas from unions together. Can be one of:
+
+                - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
+                keyword to combine schemas (the default).
+                - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
+                keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
+                type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
+                `any_of`.
+            schema_generator: The generator class used for creating the schema.
+
+        Returns:
+            A tuple where:
+
+                - The first element is a dictionary whose keys are tuples of JSON schema key type and JSON mode, and
+                    whose values are the JSON schema corresponding to that pair of inputs. (These schemas may have
+                    JsonRef references to definitions that are defined in the second returned element.)
+                - The second element is a JSON schema containing all definitions referenced in the first returned
+                    element, along with the optional title and description keys.
+
+        """
+        schema_generator_instance = schema_generator(
+            by_alias=by_alias, ref_template=ref_template, union_format=union_format
+        )
+
+        inputs_ = []
+        for key, mode, adapter in inputs:
+            # This is the same pattern we follow for model json schemas - we attempt a core schema rebuild if we detect a mock
+            if isinstance(adapter.core_schema, _mock_val_ser.MockCoreSchema):
+                adapter.core_schema.rebuild()
+                assert not isinstance(adapter.core_schema, _mock_val_ser.MockCoreSchema), (
+                    'this is a bug! please report it'
+                )
+            inputs_.append((key, mode, adapter.core_schema))
+
+        json_schemas_map, definitions = schema_generator_instance.generate_definitions(inputs_)
+
+        json_schema: dict[str, Any] = {}
+        if definitions:
+            json_schema['$defs'] = definitions
+        if title:
+            json_schema['title'] = title
+        if description:
+            json_schema['description'] = description
+
+        return json_schemas_map, json_schema
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pydantic/types.py b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/types.py
new file mode 100644
index 0000000000000000000000000000000000000000..59160ab72b54d1f100fbc5da0a85f3fe7e4b7190
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/types.py
@@ -0,0 +1,3295 @@
+"""The types module contains custom types used by pydantic."""
+
+from __future__ import annotations as _annotations
+
+import base64
+import dataclasses as _dataclasses
+import re
+from collections.abc import Hashable, Iterator
+from datetime import date, datetime
+from decimal import Decimal
+from enum import Enum
+from pathlib import Path
+from re import Pattern
+from types import ModuleType
+from typing import (
+    TYPE_CHECKING,
+    Annotated,
+    Any,
+    Callable,
+    ClassVar,
+    Generic,
+    Literal,
+    TypeVar,
+    Union,
+    cast,
+)
+from uuid import UUID
+
+import annotated_types
+from annotated_types import BaseMetadata, MaxLen, MinLen
+from pydantic_core import CoreSchema, PydanticCustomError, SchemaSerializer, core_schema
+from typing_extensions import Protocol, TypeAlias, TypeAliasType, deprecated, get_args, get_origin
+from typing_inspection.introspection import is_union_origin
+
+from ._internal import _fields, _internal_dataclass, _utils, _validators
+from ._migration import getattr_migration
+from .annotated_handlers import GetCoreSchemaHandler, GetJsonSchemaHandler
+from .errors import PydanticUserError
+from .json_schema import JsonSchemaValue
+from .warnings import PydanticDeprecatedSince20
+
+if TYPE_CHECKING:
+    from ._internal._core_metadata import CoreMetadata
+
+__all__ = (
+    'Strict',
+    'StrictStr',
+    'SocketPath',
+    'conbytes',
+    'conlist',
+    'conset',
+    'confrozenset',
+    'constr',
+    'ImportString',
+    'conint',
+    'PositiveInt',
+    'NegativeInt',
+    'NonNegativeInt',
+    'NonPositiveInt',
+    'confloat',
+    'PositiveFloat',
+    'NegativeFloat',
+    'NonNegativeFloat',
+    'NonPositiveFloat',
+    'FiniteFloat',
+    'condecimal',
+    'UUID1',
+    'UUID3',
+    'UUID4',
+    'UUID5',
+    'UUID6',
+    'UUID7',
+    'UUID8',
+    'FilePath',
+    'DirectoryPath',
+    'NewPath',
+    'Json',
+    'Secret',
+    'SecretStr',
+    'SecretBytes',
+    'StrictBool',
+    'StrictBytes',
+    'StrictInt',
+    'StrictFloat',
+    'PaymentCardNumber',
+    'ByteSize',
+    'PastDate',
+    'FutureDate',
+    'PastDatetime',
+    'FutureDatetime',
+    'condate',
+    'AwareDatetime',
+    'NaiveDatetime',
+    'AllowInfNan',
+    'EncoderProtocol',
+    'EncodedBytes',
+    'EncodedStr',
+    'Base64Encoder',
+    'Base64Bytes',
+    'Base64Str',
+    'Base64UrlBytes',
+    'Base64UrlStr',
+    'GetPydanticSchema',
+    'StringConstraints',
+    'Tag',
+    'Discriminator',
+    'JsonValue',
+    'OnErrorOmit',
+    'FailFast',
+)
+
+
+T = TypeVar('T')
+
+
+@_dataclasses.dataclass
+class Strict(_fields.PydanticMetadata, BaseMetadata):
+    """!!! abstract "Usage Documentation"
+        [Strict Mode with `Annotated` `Strict`](../concepts/strict_mode.md#strict-mode-with-annotated-strict)
+
+    A field metadata class to indicate that a field should be validated in strict mode.
+    Use this class as an annotation via [`Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated), as seen below.
+
+    Attributes:
+        strict: Whether to validate the field in strict mode.
+
+    Example:
+        ```python
+        from typing import Annotated
+
+        from pydantic.types import Strict
+
+        StrictBool = Annotated[bool, Strict()]
+        ```
+    """
+
+    strict: bool = True
+
+    def __hash__(self) -> int:
+        return hash(self.strict)
+
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BOOLEAN TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+StrictBool = Annotated[bool, Strict()]
+"""A boolean that must be either ``True`` or ``False``."""
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ INTEGER TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+
+def conint(
+    *,
+    strict: bool | None = None,
+    gt: int | None = None,
+    ge: int | None = None,
+    lt: int | None = None,
+    le: int | None = None,
+    multiple_of: int | None = None,
+) -> type[int]:
+    """
+    !!! warning "Discouraged"
+        This function is **discouraged** in favor of using
+        [`Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated) with
+        [`Field`][pydantic.fields.Field] instead.
+
+        This function will be **deprecated** in Pydantic 3.0.
+
+        The reason is that `conint` returns a type, which doesn't play well with static analysis tools.
+
+        === ":x: Don't do this"
+            ```python
+            from pydantic import BaseModel, conint
+
+            class Foo(BaseModel):
+                bar: conint(strict=True, gt=0)
+            ```
+
+        === ":white_check_mark: Do this"
+            ```python
+            from typing import Annotated
+
+            from pydantic import BaseModel, Field
+
+            class Foo(BaseModel):
+                bar: Annotated[int, Field(strict=True, gt=0)]
+            ```
+
+    A wrapper around `int` that allows for additional constraints.
+
+    Args:
+        strict: Whether to validate the integer in strict mode. Defaults to `None`.
+        gt: The value must be greater than this.
+        ge: The value must be greater than or equal to this.
+        lt: The value must be less than this.
+        le: The value must be less than or equal to this.
+        multiple_of: The value must be a multiple of this.
+
+    Returns:
+        The wrapped integer type.
+
+    ```python
+    from pydantic import BaseModel, ValidationError, conint
+
+    class ConstrainedExample(BaseModel):
+        constrained_int: conint(gt=1)
+
+    m = ConstrainedExample(constrained_int=2)
+    print(repr(m))
+    #> ConstrainedExample(constrained_int=2)
+
+    try:
+        ConstrainedExample(constrained_int=0)
+    except ValidationError as e:
+        print(e.errors())
+        '''
+        [
+            {
+                'type': 'greater_than',
+                'loc': ('constrained_int',),
+                'msg': 'Input should be greater than 1',
+                'input': 0,
+                'ctx': {'gt': 1},
+                'url': 'https://errors.pydantic.dev/2/v/greater_than',
+            }
+        ]
+        '''
+    ```
+
+    """  # noqa: D212
+    return Annotated[  # pyright: ignore[reportReturnType]
+        int,
+        Strict(strict) if strict is not None else None,
+        annotated_types.Interval(gt=gt, ge=ge, lt=lt, le=le),
+        annotated_types.MultipleOf(multiple_of) if multiple_of is not None else None,
+    ]
+
+
+PositiveInt = Annotated[int, annotated_types.Gt(0)]
+"""An integer that must be greater than zero.
+
+```python
+from pydantic import BaseModel, PositiveInt, ValidationError
+
+class Model(BaseModel):
+    positive_int: PositiveInt
+
+m = Model(positive_int=1)
+print(repr(m))
+#> Model(positive_int=1)
+
+try:
+    Model(positive_int=-1)
+except ValidationError as e:
+    print(e.errors())
+    '''
+    [
+        {
+            'type': 'greater_than',
+            'loc': ('positive_int',),
+            'msg': 'Input should be greater than 0',
+            'input': -1,
+            'ctx': {'gt': 0},
+            'url': 'https://errors.pydantic.dev/2/v/greater_than',
+        }
+    ]
+    '''
+```
+"""
+NegativeInt = Annotated[int, annotated_types.Lt(0)]
+"""An integer that must be less than zero.
+
+```python
+from pydantic import BaseModel, NegativeInt, ValidationError
+
+class Model(BaseModel):
+    negative_int: NegativeInt
+
+m = Model(negative_int=-1)
+print(repr(m))
+#> Model(negative_int=-1)
+
+try:
+    Model(negative_int=1)
+except ValidationError as e:
+    print(e.errors())
+    '''
+    [
+        {
+            'type': 'less_than',
+            'loc': ('negative_int',),
+            'msg': 'Input should be less than 0',
+            'input': 1,
+            'ctx': {'lt': 0},
+            'url': 'https://errors.pydantic.dev/2/v/less_than',
+        }
+    ]
+    '''
+```
+"""
+NonPositiveInt = Annotated[int, annotated_types.Le(0)]
+"""An integer that must be less than or equal to zero.
+
+```python
+from pydantic import BaseModel, NonPositiveInt, ValidationError
+
+class Model(BaseModel):
+    non_positive_int: NonPositiveInt
+
+m = Model(non_positive_int=0)
+print(repr(m))
+#> Model(non_positive_int=0)
+
+try:
+    Model(non_positive_int=1)
+except ValidationError as e:
+    print(e.errors())
+    '''
+    [
+        {
+            'type': 'less_than_equal',
+            'loc': ('non_positive_int',),
+            'msg': 'Input should be less than or equal to 0',
+            'input': 1,
+            'ctx': {'le': 0},
+            'url': 'https://errors.pydantic.dev/2/v/less_than_equal',
+        }
+    ]
+    '''
+```
+"""
+NonNegativeInt = Annotated[int, annotated_types.Ge(0)]
+"""An integer that must be greater than or equal to zero.
+
+```python
+from pydantic import BaseModel, NonNegativeInt, ValidationError
+
+class Model(BaseModel):
+    non_negative_int: NonNegativeInt
+
+m = Model(non_negative_int=0)
+print(repr(m))
+#> Model(non_negative_int=0)
+
+try:
+    Model(non_negative_int=-1)
+except ValidationError as e:
+    print(e.errors())
+    '''
+    [
+        {
+            'type': 'greater_than_equal',
+            'loc': ('non_negative_int',),
+            'msg': 'Input should be greater than or equal to 0',
+            'input': -1,
+            'ctx': {'ge': 0},
+            'url': 'https://errors.pydantic.dev/2/v/greater_than_equal',
+        }
+    ]
+    '''
+```
+"""
+StrictInt = Annotated[int, Strict()]
+"""An integer that must be validated in strict mode.
+
+```python
+from pydantic import BaseModel, StrictInt, ValidationError
+
+class StrictIntModel(BaseModel):
+    strict_int: StrictInt
+
+try:
+    StrictIntModel(strict_int=3.14159)
+except ValidationError as e:
+    print(e)
+    '''
+    1 validation error for StrictIntModel
+    strict_int
+      Input should be a valid integer [type=int_type, input_value=3.14159, input_type=float]
+    '''
+```
+"""
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ FLOAT TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+
+@_dataclasses.dataclass
+class AllowInfNan(_fields.PydanticMetadata):
+    """A field metadata class to indicate that a field should allow `-inf`, `inf`, and `nan`.
+
+    Use this class as an annotation via [`Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated), as seen below.
+
+    Attributes:
+        allow_inf_nan: Whether to allow `-inf`, `inf`, and `nan`. Defaults to `True`.
+
+    Example:
+        ```python
+        from typing import Annotated
+
+        from pydantic.types import AllowInfNan
+
+        LaxFloat = Annotated[float, AllowInfNan()]
+        ```
+    """
+
+    allow_inf_nan: bool = True
+
+    def __hash__(self) -> int:
+        return hash(self.allow_inf_nan)
+
+
+def confloat(
+    *,
+    strict: bool | None = None,
+    gt: float | None = None,
+    ge: float | None = None,
+    lt: float | None = None,
+    le: float | None = None,
+    multiple_of: float | None = None,
+    allow_inf_nan: bool | None = None,
+) -> type[float]:
+    """
+    !!! warning "Discouraged"
+        This function is **discouraged** in favor of using
+        [`Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated) with
+        [`Field`][pydantic.fields.Field] instead.
+
+        This function will be **deprecated** in Pydantic 3.0.
+
+        The reason is that `confloat` returns a type, which doesn't play well with static analysis tools.
+
+        === ":x: Don't do this"
+            ```python
+            from pydantic import BaseModel, confloat
+
+            class Foo(BaseModel):
+                bar: confloat(strict=True, gt=0)
+            ```
+
+        === ":white_check_mark: Do this"
+            ```python
+            from typing import Annotated
+
+            from pydantic import BaseModel, Field
+
+            class Foo(BaseModel):
+                bar: Annotated[float, Field(strict=True, gt=0)]
+            ```
+
+    A wrapper around `float` that allows for additional constraints.
+
+    Args:
+        strict: Whether to validate the float in strict mode.
+        gt: The value must be greater than this.
+        ge: The value must be greater than or equal to this.
+        lt: The value must be less than this.
+        le: The value must be less than or equal to this.
+        multiple_of: The value must be a multiple of this.
+        allow_inf_nan: Whether to allow `-inf`, `inf`, and `nan`.
+
+    Returns:
+        The wrapped float type.
+
+    ```python
+    from pydantic import BaseModel, ValidationError, confloat
+
+    class ConstrainedExample(BaseModel):
+        constrained_float: confloat(gt=1.0)
+
+    m = ConstrainedExample(constrained_float=1.1)
+    print(repr(m))
+    #> ConstrainedExample(constrained_float=1.1)
+
+    try:
+        ConstrainedExample(constrained_float=0.9)
+    except ValidationError as e:
+        print(e.errors())
+        '''
+        [
+            {
+                'type': 'greater_than',
+                'loc': ('constrained_float',),
+                'msg': 'Input should be greater than 1',
+                'input': 0.9,
+                'ctx': {'gt': 1.0},
+                'url': 'https://errors.pydantic.dev/2/v/greater_than',
+            }
+        ]
+        '''
+    ```
+    """  # noqa: D212
+    return Annotated[  # pyright: ignore[reportReturnType]
+        float,
+        Strict(strict) if strict is not None else None,
+        annotated_types.Interval(gt=gt, ge=ge, lt=lt, le=le),
+        annotated_types.MultipleOf(multiple_of) if multiple_of is not None else None,
+        AllowInfNan(allow_inf_nan) if allow_inf_nan is not None else None,
+    ]
+
+
+PositiveFloat = Annotated[float, annotated_types.Gt(0)]
+"""A float that must be greater than zero.
+
+```python
+from pydantic import BaseModel, PositiveFloat, ValidationError
+
+class Model(BaseModel):
+    positive_float: PositiveFloat
+
+m = Model(positive_float=1.0)
+print(repr(m))
+#> Model(positive_float=1.0)
+
+try:
+    Model(positive_float=-1.0)
+except ValidationError as e:
+    print(e.errors())
+    '''
+    [
+        {
+            'type': 'greater_than',
+            'loc': ('positive_float',),
+            'msg': 'Input should be greater than 0',
+            'input': -1.0,
+            'ctx': {'gt': 0.0},
+            'url': 'https://errors.pydantic.dev/2/v/greater_than',
+        }
+    ]
+    '''
+```
+"""
+NegativeFloat = Annotated[float, annotated_types.Lt(0)]
+"""A float that must be less than zero.
+
+```python
+from pydantic import BaseModel, NegativeFloat, ValidationError
+
+class Model(BaseModel):
+    negative_float: NegativeFloat
+
+m = Model(negative_float=-1.0)
+print(repr(m))
+#> Model(negative_float=-1.0)
+
+try:
+    Model(negative_float=1.0)
+except ValidationError as e:
+    print(e.errors())
+    '''
+    [
+        {
+            'type': 'less_than',
+            'loc': ('negative_float',),
+            'msg': 'Input should be less than 0',
+            'input': 1.0,
+            'ctx': {'lt': 0.0},
+            'url': 'https://errors.pydantic.dev/2/v/less_than',
+        }
+    ]
+    '''
+```
+"""
+NonPositiveFloat = Annotated[float, annotated_types.Le(0)]
+"""A float that must be less than or equal to zero.
+
+```python
+from pydantic import BaseModel, NonPositiveFloat, ValidationError
+
+class Model(BaseModel):
+    non_positive_float: NonPositiveFloat
+
+m = Model(non_positive_float=0.0)
+print(repr(m))
+#> Model(non_positive_float=0.0)
+
+try:
+    Model(non_positive_float=1.0)
+except ValidationError as e:
+    print(e.errors())
+    '''
+    [
+        {
+            'type': 'less_than_equal',
+            'loc': ('non_positive_float',),
+            'msg': 'Input should be less than or equal to 0',
+            'input': 1.0,
+            'ctx': {'le': 0.0},
+            'url': 'https://errors.pydantic.dev/2/v/less_than_equal',
+        }
+    ]
+    '''
+```
+"""
+NonNegativeFloat = Annotated[float, annotated_types.Ge(0)]
+"""A float that must be greater than or equal to zero.
+
+```python
+from pydantic import BaseModel, NonNegativeFloat, ValidationError
+
+class Model(BaseModel):
+    non_negative_float: NonNegativeFloat
+
+m = Model(non_negative_float=0.0)
+print(repr(m))
+#> Model(non_negative_float=0.0)
+
+try:
+    Model(non_negative_float=-1.0)
+except ValidationError as e:
+    print(e.errors())
+    '''
+    [
+        {
+            'type': 'greater_than_equal',
+            'loc': ('non_negative_float',),
+            'msg': 'Input should be greater than or equal to 0',
+            'input': -1.0,
+            'ctx': {'ge': 0.0},
+            'url': 'https://errors.pydantic.dev/2/v/greater_than_equal',
+        }
+    ]
+    '''
+```
+"""
+StrictFloat = Annotated[float, Strict(True)]
+"""A float that must be validated in strict mode.
+
+```python
+from pydantic import BaseModel, StrictFloat, ValidationError
+
+class StrictFloatModel(BaseModel):
+    strict_float: StrictFloat
+
+try:
+    StrictFloatModel(strict_float='1.0')
+except ValidationError as e:
+    print(e)
+    '''
+    1 validation error for StrictFloatModel
+    strict_float
+      Input should be a valid number [type=float_type, input_value='1.0', input_type=str]
+    '''
+```
+"""
+FiniteFloat = Annotated[float, AllowInfNan(False)]
+"""A float that must be finite (not ``-inf``, ``inf``, or ``nan``).
+
+```python
+from pydantic import BaseModel, FiniteFloat
+
+class Model(BaseModel):
+    finite: FiniteFloat
+
+m = Model(finite=1.0)
+print(m)
+#> finite=1.0
+```
+"""
+
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BYTES TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+
+def conbytes(
+    *,
+    min_length: int | None = None,
+    max_length: int | None = None,
+    strict: bool | None = None,
+) -> type[bytes]:
+    """A wrapper around `bytes` that allows for additional constraints.
+
+    Args:
+        min_length: The minimum length of the bytes.
+        max_length: The maximum length of the bytes.
+        strict: Whether to validate the bytes in strict mode.
+
+    Returns:
+        The wrapped bytes type.
+    """
+    return Annotated[  # pyright: ignore[reportReturnType]
+        bytes,
+        Strict(strict) if strict is not None else None,
+        annotated_types.Len(min_length or 0, max_length),
+    ]
+
+
+StrictBytes = Annotated[bytes, Strict()]
+"""A bytes that must be validated in strict mode."""
+
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ STRING TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+
+@_dataclasses.dataclass(frozen=True)
+class StringConstraints(annotated_types.GroupedMetadata):
+    """!!! abstract "Usage Documentation"
+        [String types](./standard_library_types.md#strings)
+
+    A field metadata class to apply constraints to `str` types.
+    Use this class as an annotation via [`Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated), as seen below.
+
+    Attributes:
+        strip_whitespace: Whether to remove leading and trailing whitespace.
+        to_upper: Whether to convert the string to uppercase.
+        to_lower: Whether to convert the string to lowercase.
+        strict: Whether to validate the string in strict mode.
+        min_length: The minimum length of the string.
+        max_length: The maximum length of the string.
+        pattern: A regex pattern that the string must match.
+
+    Example:
+        ```python
+        from typing import Annotated
+
+        from pydantic.types import StringConstraints
+
+        ConstrainedStr = Annotated[str, StringConstraints(min_length=1, max_length=10)]
+        ```
+    """
+
+    strip_whitespace: bool | None = None
+    to_upper: bool | None = None
+    to_lower: bool | None = None
+    strict: bool | None = None
+    min_length: int | None = None
+    max_length: int | None = None
+    pattern: str | Pattern[str] | None = None
+
+    def __iter__(self) -> Iterator[BaseMetadata]:
+        if self.min_length is not None:
+            yield MinLen(self.min_length)
+        if self.max_length is not None:
+            yield MaxLen(self.max_length)
+        if self.strict is not None:
+            yield Strict(self.strict)
+        if (
+            self.strip_whitespace is not None
+            or self.pattern is not None
+            or self.to_lower is not None
+            or self.to_upper is not None
+        ):
+            yield _fields.pydantic_general_metadata(
+                strip_whitespace=self.strip_whitespace,
+                to_upper=self.to_upper,
+                to_lower=self.to_lower,
+                pattern=self.pattern,
+            )
+
+
+def constr(
+    *,
+    strip_whitespace: bool | None = None,
+    to_upper: bool | None = None,
+    to_lower: bool | None = None,
+    strict: bool | None = None,
+    min_length: int | None = None,
+    max_length: int | None = None,
+    pattern: str | Pattern[str] | None = None,
+) -> type[str]:
+    """
+    !!! warning "Discouraged"
+        This function is **discouraged** in favor of using
+        [`Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated) with
+        [`StringConstraints`][pydantic.types.StringConstraints] instead.
+
+        This function will be **deprecated** in Pydantic 3.0.
+
+        The reason is that `constr` returns a type, which doesn't play well with static analysis tools.
+
+        === ":x: Don't do this"
+            ```python
+            from pydantic import BaseModel, constr
+
+            class Foo(BaseModel):
+                bar: constr(strip_whitespace=True, to_upper=True, pattern=r'^[A-Z]+$')
+            ```
+
+        === ":white_check_mark: Do this"
+            ```python
+            from typing import Annotated
+
+            from pydantic import BaseModel, StringConstraints
+
+            class Foo(BaseModel):
+                bar: Annotated[
+                    str,
+                    StringConstraints(
+                        strip_whitespace=True, to_upper=True, pattern=r'^[A-Z]+$'
+                    ),
+                ]
+            ```
+
+    A wrapper around `str` that allows for additional constraints.
+
+    ```python
+    from pydantic import BaseModel, constr
+
+    class Foo(BaseModel):
+        bar: constr(strip_whitespace=True, to_upper=True)
+
+    foo = Foo(bar='  hello  ')
+    print(foo)
+    #> bar='HELLO'
+    ```
+
+    Args:
+        strip_whitespace: Whether to remove leading and trailing whitespace.
+        to_upper: Whether to turn all characters to uppercase.
+        to_lower: Whether to turn all characters to lowercase.
+        strict: Whether to validate the string in strict mode.
+        min_length: The minimum length of the string.
+        max_length: The maximum length of the string.
+        pattern: A regex pattern to validate the string against.
+
+    Returns:
+        The wrapped string type.
+    """  # noqa: D212
+    return Annotated[  # pyright: ignore[reportReturnType]
+        str,
+        StringConstraints(
+            strip_whitespace=strip_whitespace,
+            to_upper=to_upper,
+            to_lower=to_lower,
+            strict=strict,
+            min_length=min_length,
+            max_length=max_length,
+            pattern=pattern,
+        ),
+    ]
+
+
+StrictStr = Annotated[str, Strict()]
+"""A string that must be validated in strict mode."""
+
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~ COLLECTION TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+HashableItemType = TypeVar('HashableItemType', bound=Hashable)
+
+
+def conset(
+    item_type: type[HashableItemType], *, min_length: int | None = None, max_length: int | None = None
+) -> type[set[HashableItemType]]:
+    """A wrapper around `typing.Set` that allows for additional constraints.
+
+    Args:
+        item_type: The type of the items in the set.
+        min_length: The minimum length of the set.
+        max_length: The maximum length of the set.
+
+    Returns:
+        The wrapped set type.
+    """
+    return Annotated[set[item_type], annotated_types.Len(min_length or 0, max_length)]  # pyright: ignore[reportReturnType]
+
+
+def confrozenset(
+    item_type: type[HashableItemType], *, min_length: int | None = None, max_length: int | None = None
+) -> type[frozenset[HashableItemType]]:
+    """A wrapper around `typing.FrozenSet` that allows for additional constraints.
+
+    Args:
+        item_type: The type of the items in the frozenset.
+        min_length: The minimum length of the frozenset.
+        max_length: The maximum length of the frozenset.
+
+    Returns:
+        The wrapped frozenset type.
+    """
+    return Annotated[frozenset[item_type], annotated_types.Len(min_length or 0, max_length)]  # pyright: ignore[reportReturnType]
+
+
+AnyItemType = TypeVar('AnyItemType')
+
+
+def conlist(
+    item_type: type[AnyItemType],
+    *,
+    min_length: int | None = None,
+    max_length: int | None = None,
+    unique_items: bool | None = None,
+) -> type[list[AnyItemType]]:
+    """A wrapper around [`list`][] that adds validation.
+
+    Args:
+        item_type: The type of the items in the list.
+        min_length: The minimum length of the list. Defaults to None.
+        max_length: The maximum length of the list. Defaults to None.
+        unique_items: Whether the items in the list must be unique. Defaults to None.
+            !!! warning Deprecated
+                The `unique_items` parameter is deprecated, use `Set` instead.
+                See [this issue](https://github.com/pydantic/pydantic-core/issues/296) for more details.
+
+    Returns:
+        The wrapped list type.
+    """
+    if unique_items is not None:
+        raise PydanticUserError(
+            (
+                '`unique_items` is removed, use `Set` instead'
+                '(this feature is discussed in https://github.com/pydantic/pydantic-core/issues/296)'
+            ),
+            code='removed-kwargs',
+        )
+    return Annotated[list[item_type], annotated_types.Len(min_length or 0, max_length)]  # pyright: ignore[reportReturnType]
+
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~ IMPORT STRING TYPE ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+AnyType = TypeVar('AnyType')
+if TYPE_CHECKING:
+    ImportString = Annotated[AnyType, ...]
+else:
+
+    class ImportString:
+        """A type that can be used to import a Python object from a string.
+
+        `ImportString` expects a string and loads the Python object importable at that dotted path.
+        Attributes of modules may be separated from the module by `:` or `.`, e.g. if `'math:cos'` is provided,
+        the resulting field value would be the function `cos`. If a `.` is used and both an attribute and submodule
+        are present at the same path, the module will be preferred.
+
+        On model instantiation, pointers will be evaluated and imported. There is
+        some nuance to this behavior, demonstrated in the examples below.
+
+        ```python
+        import math
+
+        from pydantic import BaseModel, Field, ImportString, ValidationError
+
+        class ImportThings(BaseModel):
+            obj: ImportString
+
+        # A string value will cause an automatic import
+        my_cos = ImportThings(obj='math.cos')
+
+        # You can use the imported function as you would expect
+        cos_of_0 = my_cos.obj(0)
+        assert cos_of_0 == 1
+
+        # A string whose value cannot be imported will raise an error
+        try:
+            ImportThings(obj='foo.bar')
+        except ValidationError as e:
+            print(e)
+            '''
+            1 validation error for ImportThings
+            obj
+              Invalid python path: No module named 'foo.bar' [type=import_error, input_value='foo.bar', input_type=str]
+            '''
+
+        # Actual python objects can be assigned as well
+        my_cos = ImportThings(obj=math.cos)
+        my_cos_2 = ImportThings(obj='math.cos')
+        my_cos_3 = ImportThings(obj='math:cos')
+        assert my_cos == my_cos_2 == my_cos_3
+
+        # You can set default field value either as Python object:
+        class ImportThingsDefaultPyObj(BaseModel):
+            obj: ImportString = math.cos
+
+        # or as a string value (but only if used with `validate_default=True`)
+        class ImportThingsDefaultString(BaseModel):
+            obj: ImportString = Field(default='math.cos', validate_default=True)
+
+        my_cos_default1 = ImportThingsDefaultPyObj()
+        my_cos_default2 = ImportThingsDefaultString()
+        assert my_cos_default1.obj == my_cos_default2.obj == math.cos
+
+        # note: this will not work!
+        class ImportThingsMissingValidateDefault(BaseModel):
+            obj: ImportString = 'math.cos'
+
+        my_cos_default3 = ImportThingsMissingValidateDefault()
+        assert my_cos_default3.obj == 'math.cos'  # just string, not evaluated
+        ```
+
+        Serializing an `ImportString` type to json is also possible.
+
+        ```python
+        from pydantic import BaseModel, ImportString
+
+        class ImportThings(BaseModel):
+            obj: ImportString
+
+        # Create an instance
+        m = ImportThings(obj='math.cos')
+        print(m)
+        #> obj=
+        print(m.model_dump_json())
+        #> {"obj":"math.cos"}
+        ```
+        """
+
+        @classmethod
+        def __class_getitem__(cls, item: AnyType) -> AnyType:
+            return Annotated[item, cls()]
+
+        @classmethod
+        def __get_pydantic_core_schema__(
+            cls, source: type[Any], handler: GetCoreSchemaHandler
+        ) -> core_schema.CoreSchema:
+            serializer = core_schema.plain_serializer_function_ser_schema(cls._serialize, when_used='json')
+            if cls is source:
+                # Treat bare usage of ImportString (`schema is None`) as the same as ImportString[Any]
+                return core_schema.no_info_plain_validator_function(
+                    function=_validators.import_string, serialization=serializer
+                )
+            else:
+                return core_schema.no_info_before_validator_function(
+                    function=_validators.import_string, schema=handler(source), serialization=serializer
+                )
+
+        @classmethod
+        def __get_pydantic_json_schema__(cls, cs: CoreSchema, handler: GetJsonSchemaHandler) -> JsonSchemaValue:
+            return handler(core_schema.str_schema())
+
+        @staticmethod
+        def _serialize(v: Any) -> str:
+            if isinstance(v, ModuleType):
+                return v.__name__
+            elif hasattr(v, '__module__') and hasattr(v, '__name__'):
+                return f'{v.__module__}.{v.__name__}'
+            # Handle special cases for sys.XXX streams
+            # if we see more of these, we should consider a more general solution
+            elif hasattr(v, 'name'):
+                if v.name == '':
+                    return 'sys.stdout'
+                elif v.name == '':
+                    return 'sys.stdin'
+                elif v.name == '':
+                    return 'sys.stderr'
+            return v
+
+        def __repr__(self) -> str:
+            return 'ImportString'
+
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ DECIMAL TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+
+def condecimal(
+    *,
+    strict: bool | None = None,
+    gt: int | Decimal | None = None,
+    ge: int | Decimal | None = None,
+    lt: int | Decimal | None = None,
+    le: int | Decimal | None = None,
+    multiple_of: int | Decimal | None = None,
+    max_digits: int | None = None,
+    decimal_places: int | None = None,
+    allow_inf_nan: bool | None = None,
+) -> type[Decimal]:
+    """
+    !!! warning "Discouraged"
+        This function is **discouraged** in favor of using
+        [`Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated) with
+        [`Field`][pydantic.fields.Field] instead.
+
+        This function will be **deprecated** in Pydantic 3.0.
+
+        The reason is that `condecimal` returns a type, which doesn't play well with static analysis tools.
+
+        === ":x: Don't do this"
+            ```python
+            from pydantic import BaseModel, condecimal
+
+            class Foo(BaseModel):
+                bar: condecimal(strict=True, allow_inf_nan=True)
+            ```
+
+        === ":white_check_mark: Do this"
+            ```python
+            from decimal import Decimal
+            from typing import Annotated
+
+            from pydantic import BaseModel, Field
+
+            class Foo(BaseModel):
+                bar: Annotated[Decimal, Field(strict=True, allow_inf_nan=True)]
+            ```
+
+    A wrapper around Decimal that adds validation.
+
+    Args:
+        strict: Whether to validate the value in strict mode. Defaults to `None`.
+        gt: The value must be greater than this. Defaults to `None`.
+        ge: The value must be greater than or equal to this. Defaults to `None`.
+        lt: The value must be less than this. Defaults to `None`.
+        le: The value must be less than or equal to this. Defaults to `None`.
+        multiple_of: The value must be a multiple of this. Defaults to `None`.
+        max_digits: The maximum number of digits. Defaults to `None`.
+        decimal_places: The number of decimal places. Defaults to `None`.
+        allow_inf_nan: Whether to allow infinity and NaN. Defaults to `None`.
+
+    ```python
+    from decimal import Decimal
+
+    from pydantic import BaseModel, ValidationError, condecimal
+
+    class ConstrainedExample(BaseModel):
+        constrained_decimal: condecimal(gt=Decimal('1.0'))
+
+    m = ConstrainedExample(constrained_decimal=Decimal('1.1'))
+    print(repr(m))
+    #> ConstrainedExample(constrained_decimal=Decimal('1.1'))
+
+    try:
+        ConstrainedExample(constrained_decimal=Decimal('0.9'))
+    except ValidationError as e:
+        print(e.errors())
+        '''
+        [
+            {
+                'type': 'greater_than',
+                'loc': ('constrained_decimal',),
+                'msg': 'Input should be greater than 1.0',
+                'input': Decimal('0.9'),
+                'ctx': {'gt': Decimal('1.0')},
+                'url': 'https://errors.pydantic.dev/2/v/greater_than',
+            }
+        ]
+        '''
+    ```
+    """  # noqa: D212
+    return Annotated[  # pyright: ignore[reportReturnType]
+        Decimal,
+        Strict(strict) if strict is not None else None,
+        annotated_types.Interval(gt=gt, ge=ge, lt=lt, le=le),
+        annotated_types.MultipleOf(multiple_of) if multiple_of is not None else None,
+        _fields.pydantic_general_metadata(max_digits=max_digits, decimal_places=decimal_places),
+        AllowInfNan(allow_inf_nan) if allow_inf_nan is not None else None,
+    ]
+
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ UUID TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+
+@_dataclasses.dataclass(**_internal_dataclass.slots_true)
+class UuidVersion:
+    """A field metadata class to indicate a [UUID](https://docs.python.org/3/library/uuid.html) version.
+
+    Use this class as an annotation via [`Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated), as seen below.
+
+    Attributes:
+        uuid_version: The version of the UUID. Must be one of 1, 3, 4, 5, 6, 7 or 8.
+
+    Example:
+        ```python
+        from typing import Annotated
+        from uuid import UUID
+
+        from pydantic.types import UuidVersion
+
+        UUID1 = Annotated[UUID, UuidVersion(1)]
+        ```
+    """
+
+    uuid_version: Literal[1, 3, 4, 5, 6, 7, 8]
+
+    def __get_pydantic_json_schema__(
+        self, core_schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler
+    ) -> JsonSchemaValue:
+        field_schema = handler(core_schema)
+        field_schema.pop('anyOf', None)  # remove the bytes/str union
+        field_schema.update(type='string', format=f'uuid{self.uuid_version}')
+        return field_schema
+
+    def __get_pydantic_core_schema__(self, source: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
+        schema = handler(source)
+        _check_annotated_type(schema['type'], 'uuid', self.__class__.__name__)
+        schema['version'] = self.uuid_version  # type: ignore
+        return schema
+
+    def __hash__(self) -> int:
+        return hash(type(self.uuid_version))
+
+
+UUID1 = Annotated[UUID, UuidVersion(1)]
+"""A [UUID](https://docs.python.org/3/library/uuid.html) that must be version 1.
+
+```python
+import uuid
+
+from pydantic import UUID1, BaseModel
+
+class Model(BaseModel):
+    uuid1: UUID1
+
+Model(uuid1=uuid.uuid1())
+```
+"""
+UUID3 = Annotated[UUID, UuidVersion(3)]
+"""A [UUID](https://docs.python.org/3/library/uuid.html) that must be version 3.
+
+```python
+import uuid
+
+from pydantic import UUID3, BaseModel
+
+class Model(BaseModel):
+    uuid3: UUID3
+
+Model(uuid3=uuid.uuid3(uuid.NAMESPACE_DNS, 'pydantic.org'))
+```
+"""
+UUID4 = Annotated[UUID, UuidVersion(4)]
+"""A [UUID](https://docs.python.org/3/library/uuid.html) that must be version 4.
+
+```python
+import uuid
+
+from pydantic import UUID4, BaseModel
+
+class Model(BaseModel):
+    uuid4: UUID4
+
+Model(uuid4=uuid.uuid4())
+```
+"""
+UUID5 = Annotated[UUID, UuidVersion(5)]
+"""A [UUID](https://docs.python.org/3/library/uuid.html) that must be version 5.
+
+```python
+import uuid
+
+from pydantic import UUID5, BaseModel
+
+class Model(BaseModel):
+    uuid5: UUID5
+
+Model(uuid5=uuid.uuid5(uuid.NAMESPACE_DNS, 'pydantic.org'))
+```
+"""
+UUID6 = Annotated[UUID, UuidVersion(6)]
+"""A [UUID](https://docs.python.org/3/library/uuid.html) that must be version 6.
+
+```python
+import uuid
+
+from pydantic import UUID6, BaseModel
+
+class Model(BaseModel):
+    uuid6: UUID6
+
+Model(uuid6=uuid.UUID('1efea953-c2d6-6790-aa0a-69db8c87df97'))
+```
+"""
+UUID7 = Annotated[UUID, UuidVersion(7)]
+"""A [UUID](https://docs.python.org/3/library/uuid.html) that must be version 7.
+
+```python
+import uuid
+
+from pydantic import UUID7, BaseModel
+
+class Model(BaseModel):
+    uuid7: UUID7
+
+Model(uuid7=uuid.UUID('0194fdcb-1c47-7a09-b52c-561154de0b4a'))
+```
+"""
+UUID8 = Annotated[UUID, UuidVersion(8)]
+"""A [UUID](https://docs.python.org/3/library/uuid.html) that must be version 8.
+
+```python
+import uuid
+
+from pydantic import UUID8, BaseModel
+
+class Model(BaseModel):
+    uuid8: UUID8
+
+Model(uuid8=uuid.UUID('81a0b92e-6078-8551-9c81-8ccb666bdab8'))
+```
+"""
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ PATH TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+
+@_dataclasses.dataclass
+class PathType:
+    path_type: Literal['file', 'dir', 'new', 'socket']
+
+    def __get_pydantic_json_schema__(
+        self, core_schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler
+    ) -> JsonSchemaValue:
+        field_schema = handler(core_schema)
+        format_conversion = {'file': 'file-path', 'dir': 'directory-path'}
+        field_schema.update(format=format_conversion.get(self.path_type, 'path'), type='string')
+        return field_schema
+
+    def __get_pydantic_core_schema__(self, source: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
+        function_lookup = {
+            'file': cast(core_schema.WithInfoValidatorFunction, self.validate_file),
+            'dir': cast(core_schema.WithInfoValidatorFunction, self.validate_directory),
+            'new': cast(core_schema.WithInfoValidatorFunction, self.validate_new),
+            'socket': cast(core_schema.WithInfoValidatorFunction, self.validate_socket),
+        }
+
+        return core_schema.with_info_after_validator_function(
+            function_lookup[self.path_type],
+            handler(source),
+        )
+
+    @staticmethod
+    def validate_file(path: Path, _: core_schema.ValidationInfo) -> Path:
+        if path.is_file():
+            return path
+        else:
+            raise PydanticCustomError('path_not_file', 'Path does not point to a file')
+
+    @staticmethod
+    def validate_socket(path: Path, _: core_schema.ValidationInfo) -> Path:
+        if path.is_socket():
+            return path
+        else:
+            raise PydanticCustomError('path_not_socket', 'Path does not point to a socket')
+
+    @staticmethod
+    def validate_directory(path: Path, _: core_schema.ValidationInfo) -> Path:
+        if path.is_dir():
+            return path
+        else:
+            raise PydanticCustomError('path_not_directory', 'Path does not point to a directory')
+
+    @staticmethod
+    def validate_new(path: Path, _: core_schema.ValidationInfo) -> Path:
+        if path.exists():
+            raise PydanticCustomError('path_exists', 'Path already exists')
+        elif not path.parent.exists():
+            raise PydanticCustomError('parent_does_not_exist', 'Parent directory does not exist')
+        else:
+            return path
+
+    def __hash__(self) -> int:
+        return hash(type(self.path_type))
+
+
+FilePath = Annotated[Path, PathType('file')]
+"""A path that must point to a file.
+
+```python
+from pathlib import Path
+
+from pydantic import BaseModel, FilePath, ValidationError
+
+class Model(BaseModel):
+    f: FilePath
+
+path = Path('text.txt')
+path.touch()
+m = Model(f='text.txt')
+print(m.model_dump())
+#> {'f': PosixPath('text.txt')}
+path.unlink()
+
+path = Path('directory')
+path.mkdir(exist_ok=True)
+try:
+    Model(f='directory')  # directory
+except ValidationError as e:
+    print(e)
+    '''
+    1 validation error for Model
+    f
+      Path does not point to a file [type=path_not_file, input_value='directory', input_type=str]
+    '''
+path.rmdir()
+
+try:
+    Model(f='not-exists-file')
+except ValidationError as e:
+    print(e)
+    '''
+    1 validation error for Model
+    f
+      Path does not point to a file [type=path_not_file, input_value='not-exists-file', input_type=str]
+    '''
+```
+"""
+DirectoryPath = Annotated[Path, PathType('dir')]
+"""A path that must point to a directory.
+
+```python
+from pathlib import Path
+
+from pydantic import BaseModel, DirectoryPath, ValidationError
+
+class Model(BaseModel):
+    f: DirectoryPath
+
+path = Path('directory/')
+path.mkdir()
+m = Model(f='directory/')
+print(m.model_dump())
+#> {'f': PosixPath('directory')}
+path.rmdir()
+
+path = Path('file.txt')
+path.touch()
+try:
+    Model(f='file.txt')  # file
+except ValidationError as e:
+    print(e)
+    '''
+    1 validation error for Model
+    f
+      Path does not point to a directory [type=path_not_directory, input_value='file.txt', input_type=str]
+    '''
+path.unlink()
+
+try:
+    Model(f='not-exists-directory')
+except ValidationError as e:
+    print(e)
+    '''
+    1 validation error for Model
+    f
+      Path does not point to a directory [type=path_not_directory, input_value='not-exists-directory', input_type=str]
+    '''
+```
+"""
+NewPath = Annotated[Path, PathType('new')]
+"""A path for a new file or directory that must not already exist. The parent directory must already exist."""
+
+SocketPath = Annotated[Path, PathType('socket')]
+"""A path to an existing socket file"""
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ JSON TYPE ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+if TYPE_CHECKING:
+    # Json[list[str]] will be recognized by type checkers as list[str]
+    Json = Annotated[AnyType, ...]
+
+else:
+
+    class Json:
+        """A special type wrapper which loads JSON before parsing.
+
+        You can use the `Json` data type to make Pydantic first load a raw JSON string before
+        validating the loaded data into the parametrized type:
+
+        ```python
+        from typing import Any
+
+        from pydantic import BaseModel, Json, ValidationError
+
+        class AnyJsonModel(BaseModel):
+            json_obj: Json[Any]
+
+        class ConstrainedJsonModel(BaseModel):
+            json_obj: Json[list[int]]
+
+        print(AnyJsonModel(json_obj='{"b": 1}'))
+        #> json_obj={'b': 1}
+        print(ConstrainedJsonModel(json_obj='[1, 2, 3]'))
+        #> json_obj=[1, 2, 3]
+
+        try:
+            ConstrainedJsonModel(json_obj=12)
+        except ValidationError as e:
+            print(e)
+            '''
+            1 validation error for ConstrainedJsonModel
+            json_obj
+              JSON input should be string, bytes or bytearray [type=json_type, input_value=12, input_type=int]
+            '''
+
+        try:
+            ConstrainedJsonModel(json_obj='[a, b]')
+        except ValidationError as e:
+            print(e)
+            '''
+            1 validation error for ConstrainedJsonModel
+            json_obj
+              Invalid JSON: expected value at line 1 column 2 [type=json_invalid, input_value='[a, b]', input_type=str]
+            '''
+
+        try:
+            ConstrainedJsonModel(json_obj='["a", "b"]')
+        except ValidationError as e:
+            print(e)
+            '''
+            2 validation errors for ConstrainedJsonModel
+            json_obj.0
+              Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='a', input_type=str]
+            json_obj.1
+              Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='b', input_type=str]
+            '''
+        ```
+
+        When you dump the model using `model_dump` or `model_dump_json`, the dumped value will be the result of validation,
+        not the original JSON string. However, you can use the argument `round_trip=True` to get the original JSON string back:
+
+        ```python
+        from pydantic import BaseModel, Json
+
+        class ConstrainedJsonModel(BaseModel):
+            json_obj: Json[list[int]]
+
+        print(ConstrainedJsonModel(json_obj='[1, 2, 3]').model_dump_json())
+        #> {"json_obj":[1,2,3]}
+        print(
+            ConstrainedJsonModel(json_obj='[1, 2, 3]').model_dump_json(round_trip=True)
+        )
+        #> {"json_obj":"[1,2,3]"}
+        ```
+        """
+
+        @classmethod
+        def __class_getitem__(cls, item: AnyType) -> AnyType:
+            return Annotated[item, cls()]
+
+        @classmethod
+        def __get_pydantic_core_schema__(cls, source: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
+            if cls is source:
+                return core_schema.json_schema(None)
+            else:
+                return core_schema.json_schema(handler(source))
+
+        def __repr__(self) -> str:
+            return 'Json'
+
+        def __hash__(self) -> int:
+            return hash(type(self))
+
+        def __eq__(self, other: Any) -> bool:
+            return type(other) is type(self)
+
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SECRET TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+# The `Secret` class being conceptually immutable, make the type variable covariant:
+SecretType = TypeVar('SecretType', covariant=True)
+
+
+class _SecretBase(Generic[SecretType]):
+    def __init__(self, secret_value: SecretType) -> None:
+        self._secret_value: SecretType = secret_value
+
+    def get_secret_value(self) -> SecretType:
+        """Get the secret value.
+
+        Returns:
+            The secret value.
+        """
+        return self._secret_value
+
+    def __eq__(self, other: Any) -> bool:
+        return isinstance(other, self.__class__) and self.get_secret_value() == other.get_secret_value()
+
+    def __hash__(self) -> int:
+        return hash(self.get_secret_value())
+
+    def __str__(self) -> str:
+        return str(self._display())
+
+    def __repr__(self) -> str:
+        return f'{self.__class__.__name__}({self._display()!r})'
+
+    def _display(self) -> str | bytes:
+        raise NotImplementedError
+
+
+def _serialize_secret(value: Secret[SecretType], info: core_schema.SerializationInfo) -> str | Secret[SecretType]:
+    if info.mode == 'json':
+        return str(value)
+    else:
+        return value
+
+
+class Secret(_SecretBase[SecretType]):
+    """A generic base class used for defining a field with sensitive information that you do not want to be visible in logging or tracebacks.
+
+    You may either directly parametrize `Secret` with a type, or subclass from `Secret` with a parametrized type. The benefit of subclassing
+    is that you can define a custom `_display` method, which will be used for `repr()` and `str()` methods. The examples below demonstrate both
+    ways of using `Secret` to create a new secret type.
+
+    1. Directly parametrizing `Secret` with a type:
+
+    ```python
+    from pydantic import BaseModel, Secret
+
+    SecretBool = Secret[bool]
+
+    class Model(BaseModel):
+        secret_bool: SecretBool
+
+    m = Model(secret_bool=True)
+    print(m.model_dump())
+    #> {'secret_bool': Secret('**********')}
+
+    print(m.model_dump_json())
+    #> {"secret_bool":"**********"}
+
+    print(m.secret_bool.get_secret_value())
+    #> True
+    ```
+
+    2. Subclassing from parametrized `Secret`:
+
+    ```python
+    from datetime import date
+
+    from pydantic import BaseModel, Secret
+
+    class SecretDate(Secret[date]):
+        def _display(self) -> str:
+            return '****/**/**'
+
+    class Model(BaseModel):
+        secret_date: SecretDate
+
+    m = Model(secret_date=date(2022, 1, 1))
+    print(m.model_dump())
+    #> {'secret_date': SecretDate('****/**/**')}
+
+    print(m.model_dump_json())
+    #> {"secret_date":"****/**/**"}
+
+    print(m.secret_date.get_secret_value())
+    #> 2022-01-01
+    ```
+
+    The value returned by the `_display` method will be used for `repr()` and `str()`.
+
+    You can enforce constraints on the underlying type through annotations:
+    For example:
+
+    ```python
+    from typing import Annotated
+
+    from pydantic import BaseModel, Field, Secret, ValidationError
+
+    SecretPosInt = Secret[Annotated[int, Field(gt=0, strict=True)]]
+
+    class Model(BaseModel):
+        sensitive_int: SecretPosInt
+
+    m = Model(sensitive_int=42)
+    print(m.model_dump())
+    #> {'sensitive_int': Secret('**********')}
+
+    try:
+        m = Model(sensitive_int=-42)  # (1)!
+    except ValidationError as exc_info:
+        print(exc_info.errors(include_url=False, include_input=False))
+        '''
+        [
+            {
+                'type': 'greater_than',
+                'loc': ('sensitive_int',),
+                'msg': 'Input should be greater than 0',
+                'ctx': {'gt': 0},
+            }
+        ]
+        '''
+
+    try:
+        m = Model(sensitive_int='42')  # (2)!
+    except ValidationError as exc_info:
+        print(exc_info.errors(include_url=False, include_input=False))
+        '''
+        [
+            {
+                'type': 'int_type',
+                'loc': ('sensitive_int',),
+                'msg': 'Input should be a valid integer',
+            }
+        ]
+        '''
+    ```
+
+    1. The input value is not greater than 0, so it raises a validation error.
+    2. The input value is not an integer, so it raises a validation error because the `SecretPosInt` type has strict mode enabled.
+    """
+
+    def _display(self) -> str | bytes:
+        return '**********' if self.get_secret_value() else ''
+
+    @classmethod
+    def __get_pydantic_core_schema__(cls, source: type[Any], handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
+        inner_type = None
+        # if origin_type is Secret, then cls is a GenericAlias, and we can extract the inner type directly
+        origin_type = get_origin(source)
+        if origin_type is not None:
+            inner_type = get_args(source)[0]
+        # otherwise, we need to get the inner type from the base class
+        else:
+            bases = getattr(cls, '__orig_bases__', getattr(cls, '__bases__', []))
+            for base in bases:
+                if get_origin(base) is Secret:
+                    inner_type = get_args(base)[0]
+            if bases == [] or inner_type is None:
+                raise TypeError(
+                    f"Can't get secret type from {cls.__name__}. "
+                    'Please use Secret[], or subclass from Secret[] instead.'
+                )
+
+        inner_schema = handler.generate_schema(inner_type)  # type: ignore
+
+        def validate_secret_value(value, handler) -> Secret[SecretType]:
+            if isinstance(value, Secret):
+                value = value.get_secret_value()
+            validated_inner = handler(value)
+            return cls(validated_inner)
+
+        return core_schema.json_or_python_schema(
+            python_schema=core_schema.no_info_wrap_validator_function(
+                validate_secret_value,
+                inner_schema,
+            ),
+            json_schema=core_schema.no_info_after_validator_function(lambda x: cls(x), inner_schema),
+            serialization=core_schema.plain_serializer_function_ser_schema(
+                _serialize_secret,
+                info_arg=True,
+                when_used='always',
+            ),
+        )
+
+    __pydantic_serializer__ = SchemaSerializer(
+        core_schema.any_schema(
+            serialization=core_schema.plain_serializer_function_ser_schema(
+                _serialize_secret,
+                info_arg=True,
+                when_used='always',
+            )
+        )
+    )
+
+
+def _secret_display(value: SecretType) -> str:  # type: ignore
+    return '**********' if value else ''
+
+
+def _serialize_secret_field(
+    value: _SecretField[SecretType], info: core_schema.SerializationInfo
+) -> str | _SecretField[SecretType]:
+    if info.mode == 'json':
+        # we want the output to always be string without the `b'` prefix for bytes,
+        # hence we just use `secret_display`
+        return _secret_display(value.get_secret_value())
+    else:
+        return value
+
+
+class _SecretField(_SecretBase[SecretType]):
+    _inner_schema: ClassVar[CoreSchema]
+    _error_kind: ClassVar[str]
+
+    @classmethod
+    def __get_pydantic_core_schema__(cls, source: type[Any], handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
+        def get_json_schema(_core_schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler) -> JsonSchemaValue:
+            json_schema = handler(cls._inner_schema)
+            _utils.update_not_none(
+                json_schema,
+                type='string',
+                writeOnly=True,
+                format='password',
+            )
+            return json_schema
+
+        def get_secret_schema(strict: bool) -> CoreSchema:
+            inner_schema = {**cls._inner_schema, 'strict': strict}
+            json_schema = core_schema.no_info_after_validator_function(
+                source,  # construct the type
+                inner_schema,  # pyright: ignore[reportArgumentType]
+            )
+            return core_schema.json_or_python_schema(
+                python_schema=core_schema.union_schema(
+                    [
+                        core_schema.is_instance_schema(source),
+                        json_schema,
+                    ],
+                    custom_error_type=cls._error_kind,
+                ),
+                json_schema=json_schema,
+                serialization=core_schema.plain_serializer_function_ser_schema(
+                    _serialize_secret_field,
+                    info_arg=True,
+                    when_used='always',
+                ),
+            )
+
+        return core_schema.lax_or_strict_schema(
+            lax_schema=get_secret_schema(strict=False),
+            strict_schema=get_secret_schema(strict=True),
+            metadata={'pydantic_js_functions': [get_json_schema]},
+        )
+
+    __pydantic_serializer__ = SchemaSerializer(
+        core_schema.any_schema(
+            serialization=core_schema.plain_serializer_function_ser_schema(
+                _serialize_secret_field,
+                info_arg=True,
+                when_used='always',
+            )
+        )
+    )
+
+
+class SecretStr(_SecretField[str]):
+    """A string used for storing sensitive information that you do not want to be visible in logging or tracebacks.
+
+    When the secret value is nonempty, it is displayed as `'**********'` instead of the underlying value in
+    calls to `repr()` and `str()`. If the value _is_ empty, it is displayed as `''`.
+
+    ```python
+    from pydantic import BaseModel, SecretStr
+
+    class User(BaseModel):
+        username: str
+        password: SecretStr
+
+    user = User(username='scolvin', password='password1')
+
+    print(user)
+    #> username='scolvin' password=SecretStr('**********')
+    print(user.password.get_secret_value())
+    #> password1
+    print((SecretStr('password'), SecretStr('')))
+    #> (SecretStr('**********'), SecretStr(''))
+    ```
+
+    As seen above, by default, [`SecretStr`][pydantic.types.SecretStr] (and [`SecretBytes`][pydantic.types.SecretBytes])
+    will be serialized as `**********` when serializing to json.
+
+    You can use the [`field_serializer`][pydantic.functional_serializers.field_serializer] to dump the
+    secret as plain-text when serializing to json.
+
+    ```python
+    from pydantic import BaseModel, SecretBytes, SecretStr, field_serializer
+
+    class Model(BaseModel):
+        password: SecretStr
+        password_bytes: SecretBytes
+
+        @field_serializer('password', 'password_bytes', when_used='json')
+        def dump_secret(self, v):
+            return v.get_secret_value()
+
+    model = Model(password='IAmSensitive', password_bytes=b'IAmSensitiveBytes')
+    print(model)
+    #> password=SecretStr('**********') password_bytes=SecretBytes(b'**********')
+    print(model.password)
+    #> **********
+    print(model.model_dump())
+    '''
+    {
+        'password': SecretStr('**********'),
+        'password_bytes': SecretBytes(b'**********'),
+    }
+    '''
+    print(model.model_dump_json())
+    #> {"password":"IAmSensitive","password_bytes":"IAmSensitiveBytes"}
+    ```
+    """
+
+    _inner_schema: ClassVar[CoreSchema] = core_schema.str_schema()
+    _error_kind: ClassVar[str] = 'string_type'
+
+    def __len__(self) -> int:
+        return len(self._secret_value)
+
+    def _display(self) -> str:
+        return _secret_display(self._secret_value)
+
+
+class SecretBytes(_SecretField[bytes]):
+    """A bytes used for storing sensitive information that you do not want to be visible in logging or tracebacks.
+
+    It displays `b'**********'` instead of the string value on `repr()` and `str()` calls.
+    When the secret value is nonempty, it is displayed as `b'**********'` instead of the underlying value in
+    calls to `repr()` and `str()`. If the value _is_ empty, it is displayed as `b''`.
+
+    ```python
+    from pydantic import BaseModel, SecretBytes
+
+    class User(BaseModel):
+        username: str
+        password: SecretBytes
+
+    user = User(username='scolvin', password=b'password1')
+    #> username='scolvin' password=SecretBytes(b'**********')
+    print(user.password.get_secret_value())
+    #> b'password1'
+    print((SecretBytes(b'password'), SecretBytes(b'')))
+    #> (SecretBytes(b'**********'), SecretBytes(b''))
+    ```
+    """
+
+    _inner_schema: ClassVar[CoreSchema] = core_schema.bytes_schema()
+    _error_kind: ClassVar[str] = 'bytes_type'
+
+    def __len__(self) -> int:
+        return len(self._secret_value)
+
+    def _display(self) -> bytes:
+        return _secret_display(self._secret_value).encode()
+
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ PAYMENT CARD TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+
+class PaymentCardBrand(str, Enum):
+    amex = 'American Express'
+    mastercard = 'Mastercard'
+    visa = 'Visa'
+    other = 'other'
+
+    def __str__(self) -> str:
+        return self.value
+
+
+@deprecated(
+    'The `PaymentCardNumber` class is deprecated, use `pydantic_extra_types` instead. '
+    'See https://docs.pydantic.dev/latest/api/pydantic_extra_types_payment/#pydantic_extra_types.payment.PaymentCardNumber.',
+    category=PydanticDeprecatedSince20,
+)
+class PaymentCardNumber(str):
+    """Based on: https://en.wikipedia.org/wiki/Payment_card_number."""
+
+    strip_whitespace: ClassVar[bool] = True
+    min_length: ClassVar[int] = 12
+    max_length: ClassVar[int] = 19
+    bin: str
+    last4: str
+    brand: PaymentCardBrand
+
+    def __init__(self, card_number: str):
+        self.validate_digits(card_number)
+
+        card_number = self.validate_luhn_check_digit(card_number)
+
+        self.bin = card_number[:6]
+        self.last4 = card_number[-4:]
+        self.brand = self.validate_brand(card_number)
+
+    @classmethod
+    def __get_pydantic_core_schema__(cls, source: type[Any], handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
+        return core_schema.with_info_after_validator_function(
+            cls.validate,
+            core_schema.str_schema(
+                min_length=cls.min_length, max_length=cls.max_length, strip_whitespace=cls.strip_whitespace
+            ),
+        )
+
+    @classmethod
+    def validate(cls, input_value: str, /, _: core_schema.ValidationInfo) -> PaymentCardNumber:
+        """Validate the card number and return a `PaymentCardNumber` instance."""
+        return cls(input_value)
+
+    @property
+    def masked(self) -> str:
+        """Mask all but the last 4 digits of the card number.
+
+        Returns:
+            A masked card number string.
+        """
+        num_masked = len(self) - 10  # len(bin) + len(last4) == 10
+        return f'{self.bin}{"*" * num_masked}{self.last4}'
+
+    @classmethod
+    def validate_digits(cls, card_number: str) -> None:
+        """Validate that the card number is all digits."""
+        if not card_number.isdigit():
+            raise PydanticCustomError('payment_card_number_digits', 'Card number is not all digits')
+
+    @classmethod
+    def validate_luhn_check_digit(cls, card_number: str) -> str:
+        """Based on: https://en.wikipedia.org/wiki/Luhn_algorithm."""
+        sum_ = int(card_number[-1])
+        length = len(card_number)
+        parity = length % 2
+        for i in range(length - 1):
+            digit = int(card_number[i])
+            if i % 2 == parity:
+                digit *= 2
+            if digit > 9:
+                digit -= 9
+            sum_ += digit
+        valid = sum_ % 10 == 0
+        if not valid:
+            raise PydanticCustomError('payment_card_number_luhn', 'Card number is not luhn valid')
+        return card_number
+
+    @staticmethod
+    def validate_brand(card_number: str) -> PaymentCardBrand:
+        """Validate length based on BIN for major brands:
+        https://en.wikipedia.org/wiki/Payment_card_number#Issuer_identification_number_(IIN).
+        """
+        if card_number[0] == '4':
+            brand = PaymentCardBrand.visa
+        elif 51 <= int(card_number[:2]) <= 55:
+            brand = PaymentCardBrand.mastercard
+        elif card_number[:2] in {'34', '37'}:
+            brand = PaymentCardBrand.amex
+        else:
+            brand = PaymentCardBrand.other
+
+        required_length: None | int | str = None
+        if brand in PaymentCardBrand.mastercard:
+            required_length = 16
+            valid = len(card_number) == required_length
+        elif brand == PaymentCardBrand.visa:
+            required_length = '13, 16 or 19'
+            valid = len(card_number) in {13, 16, 19}
+        elif brand == PaymentCardBrand.amex:
+            required_length = 15
+            valid = len(card_number) == required_length
+        else:
+            valid = True
+
+        if not valid:
+            raise PydanticCustomError(
+                'payment_card_number_brand',
+                'Length for a {brand} card must be {required_length}',
+                {'brand': brand, 'required_length': required_length},
+            )
+        return brand
+
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BYTE SIZE TYPE ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+
+class ByteSize(int):
+    """Converts a string representing a number of bytes with units (such as `'1KB'` or `'11.5MiB'`) into an integer.
+
+    You can use the `ByteSize` data type to (case-insensitively) convert a string representation of a number of bytes into
+    an integer, and also to print out human-readable strings representing a number of bytes.
+
+    In conformance with [IEC 80000-13 Standard](https://en.wikipedia.org/wiki/ISO/IEC_80000) we interpret `'1KB'` to mean 1000 bytes,
+    and `'1KiB'` to mean 1024 bytes. In general, including a middle `'i'` will cause the unit to be interpreted as a power of 2,
+    rather than a power of 10 (so, for example, `'1 MB'` is treated as `1_000_000` bytes, whereas `'1 MiB'` is treated as `1_048_576` bytes).
+
+    !!! info
+        Note that `1b` will be parsed as "1 byte" and not "1 bit".
+
+    ```python
+    from pydantic import BaseModel, ByteSize
+
+    class MyModel(BaseModel):
+        size: ByteSize
+
+    print(MyModel(size=52000).size)
+    #> 52000
+    print(MyModel(size='3000 KiB').size)
+    #> 3072000
+
+    m = MyModel(size='50 PB')
+    print(m.size.human_readable())
+    #> 44.4PiB
+    print(m.size.human_readable(decimal=True))
+    #> 50.0PB
+    print(m.size.human_readable(separator=' '))
+    #> 44.4 PiB
+
+    print(m.size.to('TiB'))
+    #> 45474.73508864641
+    ```
+    """
+
+    byte_sizes = {
+        'b': 1,
+        'kb': 10**3,
+        'mb': 10**6,
+        'gb': 10**9,
+        'tb': 10**12,
+        'pb': 10**15,
+        'eb': 10**18,
+        'kib': 2**10,
+        'mib': 2**20,
+        'gib': 2**30,
+        'tib': 2**40,
+        'pib': 2**50,
+        'eib': 2**60,
+        'bit': 1 / 8,
+        'kbit': 10**3 / 8,
+        'mbit': 10**6 / 8,
+        'gbit': 10**9 / 8,
+        'tbit': 10**12 / 8,
+        'pbit': 10**15 / 8,
+        'ebit': 10**18 / 8,
+        'kibit': 2**10 / 8,
+        'mibit': 2**20 / 8,
+        'gibit': 2**30 / 8,
+        'tibit': 2**40 / 8,
+        'pibit': 2**50 / 8,
+        'eibit': 2**60 / 8,
+    }
+    byte_sizes.update({k.lower()[0]: v for k, v in byte_sizes.items() if 'i' not in k})
+
+    byte_string_pattern = r'^\s*(\d*\.?\d+)\s*(\w+)?'
+    byte_string_re = re.compile(byte_string_pattern, re.IGNORECASE)
+
+    @classmethod
+    def __get_pydantic_core_schema__(cls, source: type[Any], handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
+        return core_schema.with_info_after_validator_function(
+            function=cls._validate,
+            schema=core_schema.union_schema(
+                [
+                    core_schema.str_schema(pattern=cls.byte_string_pattern),
+                    core_schema.int_schema(ge=0),
+                ],
+                custom_error_type='byte_size',
+                custom_error_message='could not parse value and unit from byte string',
+            ),
+            serialization=core_schema.plain_serializer_function_ser_schema(
+                int, return_schema=core_schema.int_schema(ge=0)
+            ),
+        )
+
+    @classmethod
+    def _validate(cls, input_value: Any, /, _: core_schema.ValidationInfo) -> ByteSize:
+        try:
+            return cls(int(input_value))
+        except ValueError:
+            pass
+
+        str_match = cls.byte_string_re.match(str(input_value))
+        if str_match is None:
+            raise PydanticCustomError('byte_size', 'could not parse value and unit from byte string')
+
+        scalar, unit = str_match.groups()
+        if unit is None:
+            unit = 'b'
+
+        try:
+            unit_mult = cls.byte_sizes[unit.lower()]
+        except KeyError:
+            raise PydanticCustomError('byte_size_unit', 'could not interpret byte unit: {unit}', {'unit': unit})
+
+        return cls(int(float(scalar) * unit_mult))
+
+    def human_readable(self, decimal: bool = False, separator: str = '') -> str:
+        """Converts a byte size to a human readable string.
+
+        Args:
+            decimal: If True, use decimal units (e.g. 1000 bytes per KB). If False, use binary units
+                (e.g. 1024 bytes per KiB).
+            separator: A string used to split the value and unit. Defaults to an empty string ('').
+
+        Returns:
+            A human readable string representation of the byte size.
+        """
+        if decimal:
+            divisor = 1000
+            units = 'B', 'KB', 'MB', 'GB', 'TB', 'PB'
+            final_unit = 'EB'
+        else:
+            divisor = 1024
+            units = 'B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'
+            final_unit = 'EiB'
+
+        num = float(self)
+        for unit in units:
+            if abs(num) < divisor:
+                if unit == 'B':
+                    return f'{num:0.0f}{separator}{unit}'
+                else:
+                    return f'{num:0.1f}{separator}{unit}'
+            num /= divisor
+
+        return f'{num:0.1f}{separator}{final_unit}'
+
+    def to(self, unit: str) -> float:
+        """Converts a byte size to another unit, including both byte and bit units.
+
+        Args:
+            unit: The unit to convert to. Must be one of the following: B, KB, MB, GB, TB, PB, EB,
+                KiB, MiB, GiB, TiB, PiB, EiB (byte units) and
+                bit, kbit, mbit, gbit, tbit, pbit, ebit,
+                kibit, mibit, gibit, tibit, pibit, eibit (bit units).
+
+        Returns:
+            The byte size in the new unit.
+        """
+        try:
+            unit_div = self.byte_sizes[unit.lower()]
+        except KeyError:
+            raise PydanticCustomError('byte_size_unit', 'Could not interpret byte unit: {unit}', {'unit': unit})
+
+        return self / unit_div
+
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ DATE TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+
+def _check_annotated_type(annotated_type: str, expected_type: str, annotation: str) -> None:
+    if annotated_type != expected_type:
+        raise PydanticUserError(f"'{annotation}' cannot annotate '{annotated_type}'.", code='invalid-annotated-type')
+
+
+if TYPE_CHECKING:
+    PastDate = Annotated[date, ...]
+    FutureDate = Annotated[date, ...]
+else:
+
+    class PastDate:
+        """A date in the past."""
+
+        @classmethod
+        def __get_pydantic_core_schema__(
+            cls, source: type[Any], handler: GetCoreSchemaHandler
+        ) -> core_schema.CoreSchema:
+            if cls is source:
+                # used directly as a type
+                return core_schema.date_schema(now_op='past')
+            else:
+                schema = handler(source)
+                _check_annotated_type(schema['type'], 'date', cls.__name__)
+                schema['now_op'] = 'past'
+                return schema
+
+        def __repr__(self) -> str:
+            return 'PastDate'
+
+    class FutureDate:
+        """A date in the future."""
+
+        @classmethod
+        def __get_pydantic_core_schema__(
+            cls, source: type[Any], handler: GetCoreSchemaHandler
+        ) -> core_schema.CoreSchema:
+            if cls is source:
+                # used directly as a type
+                return core_schema.date_schema(now_op='future')
+            else:
+                schema = handler(source)
+                _check_annotated_type(schema['type'], 'date', cls.__name__)
+                schema['now_op'] = 'future'
+                return schema
+
+        def __repr__(self) -> str:
+            return 'FutureDate'
+
+
+def condate(
+    *,
+    strict: bool | None = None,
+    gt: date | None = None,
+    ge: date | None = None,
+    lt: date | None = None,
+    le: date | None = None,
+) -> type[date]:
+    """A wrapper for date that adds constraints.
+
+    Args:
+        strict: Whether to validate the date value in strict mode. Defaults to `None`.
+        gt: The value must be greater than this. Defaults to `None`.
+        ge: The value must be greater than or equal to this. Defaults to `None`.
+        lt: The value must be less than this. Defaults to `None`.
+        le: The value must be less than or equal to this. Defaults to `None`.
+
+    Returns:
+        A date type with the specified constraints.
+    """
+    return Annotated[  # pyright: ignore[reportReturnType]
+        date,
+        Strict(strict) if strict is not None else None,
+        annotated_types.Interval(gt=gt, ge=ge, lt=lt, le=le),
+    ]
+
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ DATETIME TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+if TYPE_CHECKING:
+    AwareDatetime = Annotated[datetime, ...]
+    NaiveDatetime = Annotated[datetime, ...]
+    PastDatetime = Annotated[datetime, ...]
+    FutureDatetime = Annotated[datetime, ...]
+
+else:
+
+    class AwareDatetime:
+        """A datetime that requires timezone info."""
+
+        @classmethod
+        def __get_pydantic_core_schema__(
+            cls, source: type[Any], handler: GetCoreSchemaHandler
+        ) -> core_schema.CoreSchema:
+            if cls is source:
+                # used directly as a type
+                return core_schema.datetime_schema(tz_constraint='aware')
+            else:
+                schema = handler(source)
+                _check_annotated_type(schema['type'], 'datetime', cls.__name__)
+                schema['tz_constraint'] = 'aware'
+                return schema
+
+        def __repr__(self) -> str:
+            return 'AwareDatetime'
+
+    class NaiveDatetime:
+        """A datetime that doesn't require timezone info."""
+
+        @classmethod
+        def __get_pydantic_core_schema__(
+            cls, source: type[Any], handler: GetCoreSchemaHandler
+        ) -> core_schema.CoreSchema:
+            if cls is source:
+                # used directly as a type
+                return core_schema.datetime_schema(tz_constraint='naive')
+            else:
+                schema = handler(source)
+                _check_annotated_type(schema['type'], 'datetime', cls.__name__)
+                schema['tz_constraint'] = 'naive'
+                return schema
+
+        def __repr__(self) -> str:
+            return 'NaiveDatetime'
+
+    class PastDatetime:
+        """A datetime that must be in the past."""
+
+        @classmethod
+        def __get_pydantic_core_schema__(
+            cls, source: type[Any], handler: GetCoreSchemaHandler
+        ) -> core_schema.CoreSchema:
+            if cls is source:
+                # used directly as a type
+                return core_schema.datetime_schema(now_op='past')
+            else:
+                schema = handler(source)
+                _check_annotated_type(schema['type'], 'datetime', cls.__name__)
+                schema['now_op'] = 'past'
+                return schema
+
+        def __repr__(self) -> str:
+            return 'PastDatetime'
+
+    class FutureDatetime:
+        """A datetime that must be in the future."""
+
+        @classmethod
+        def __get_pydantic_core_schema__(
+            cls, source: type[Any], handler: GetCoreSchemaHandler
+        ) -> core_schema.CoreSchema:
+            if cls is source:
+                # used directly as a type
+                return core_schema.datetime_schema(now_op='future')
+            else:
+                schema = handler(source)
+                _check_annotated_type(schema['type'], 'datetime', cls.__name__)
+                schema['now_op'] = 'future'
+                return schema
+
+        def __repr__(self) -> str:
+            return 'FutureDatetime'
+
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Encoded TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+
+class EncoderProtocol(Protocol):
+    """Protocol for encoding and decoding data to and from bytes."""
+
+    @classmethod
+    def decode(cls, data: bytes) -> bytes:
+        """Decode the data using the encoder.
+
+        Args:
+            data: The data to decode.
+
+        Returns:
+            The decoded data.
+        """
+        ...
+
+    @classmethod
+    def encode(cls, value: bytes) -> bytes:
+        """Encode the data using the encoder.
+
+        Args:
+            value: The data to encode.
+
+        Returns:
+            The encoded data.
+        """
+        ...
+
+    @classmethod
+    def get_json_format(cls) -> str:
+        """Get the JSON format for the encoded data.
+
+        Returns:
+            The JSON format for the encoded data.
+        """
+        ...
+
+
+class Base64Encoder(EncoderProtocol):
+    """Standard (non-URL-safe) Base64 encoder."""
+
+    @classmethod
+    def decode(cls, data: bytes) -> bytes:
+        """Decode the data from base64 encoded bytes to original bytes data.
+
+        Args:
+            data: The data to decode.
+
+        Returns:
+            The decoded data.
+        """
+        try:
+            return base64.b64decode(data)
+        except ValueError as e:
+            raise PydanticCustomError('base64_decode', "Base64 decoding error: '{error}'", {'error': str(e)})
+
+    @classmethod
+    def encode(cls, value: bytes) -> bytes:
+        """Encode the data from bytes to a base64 encoded bytes.
+
+        Args:
+            value: The data to encode.
+
+        Returns:
+            The encoded data.
+        """
+        return base64.b64encode(value)
+
+    @classmethod
+    def get_json_format(cls) -> Literal['base64']:
+        """Get the JSON format for the encoded data.
+
+        Returns:
+            The JSON format for the encoded data.
+        """
+        return 'base64'
+
+
+class Base64UrlEncoder(EncoderProtocol):
+    """URL-safe Base64 encoder."""
+
+    @classmethod
+    def decode(cls, data: bytes) -> bytes:
+        """Decode the data from base64 encoded bytes to original bytes data.
+
+        Args:
+            data: The data to decode.
+
+        Returns:
+            The decoded data.
+        """
+        try:
+            return base64.urlsafe_b64decode(data)
+        except ValueError as e:
+            raise PydanticCustomError('base64_decode', "Base64 decoding error: '{error}'", {'error': str(e)})
+
+    @classmethod
+    def encode(cls, value: bytes) -> bytes:
+        """Encode the data from bytes to a base64 encoded bytes.
+
+        Args:
+            value: The data to encode.
+
+        Returns:
+            The encoded data.
+        """
+        return base64.urlsafe_b64encode(value)
+
+    @classmethod
+    def get_json_format(cls) -> Literal['base64url']:
+        """Get the JSON format for the encoded data.
+
+        Returns:
+            The JSON format for the encoded data.
+        """
+        return 'base64url'
+
+
+@_dataclasses.dataclass(**_internal_dataclass.slots_true)
+class EncodedBytes:
+    """A bytes type that is encoded and decoded using the specified encoder.
+
+    `EncodedBytes` needs an encoder that implements `EncoderProtocol` to operate.
+
+    ```python
+    from typing import Annotated
+
+    from pydantic import BaseModel, EncodedBytes, EncoderProtocol, ValidationError
+
+    class MyEncoder(EncoderProtocol):
+        @classmethod
+        def decode(cls, data: bytes) -> bytes:
+            if data == b'**undecodable**':
+                raise ValueError('Cannot decode data')
+            return data[13:]
+
+        @classmethod
+        def encode(cls, value: bytes) -> bytes:
+            return b'**encoded**: ' + value
+
+        @classmethod
+        def get_json_format(cls) -> str:
+            return 'my-encoder'
+
+    MyEncodedBytes = Annotated[bytes, EncodedBytes(encoder=MyEncoder)]
+
+    class Model(BaseModel):
+        my_encoded_bytes: MyEncodedBytes
+
+    # Initialize the model with encoded data
+    m = Model(my_encoded_bytes=b'**encoded**: some bytes')
+
+    # Access decoded value
+    print(m.my_encoded_bytes)
+    #> b'some bytes'
+
+    # Serialize into the encoded form
+    print(m.model_dump())
+    #> {'my_encoded_bytes': b'**encoded**: some bytes'}
+
+    # Validate encoded data
+    try:
+        Model(my_encoded_bytes=b'**undecodable**')
+    except ValidationError as e:
+        print(e)
+        '''
+        1 validation error for Model
+        my_encoded_bytes
+          Value error, Cannot decode data [type=value_error, input_value=b'**undecodable**', input_type=bytes]
+        '''
+    ```
+    """
+
+    encoder: type[EncoderProtocol]
+
+    def __get_pydantic_json_schema__(
+        self, core_schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler
+    ) -> JsonSchemaValue:
+        field_schema = handler(core_schema)
+        field_schema.update(type='string', format=self.encoder.get_json_format())
+        return field_schema
+
+    def __get_pydantic_core_schema__(self, source: type[Any], handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
+        schema = handler(source)
+        _check_annotated_type(schema['type'], 'bytes', self.__class__.__name__)
+        return core_schema.with_info_after_validator_function(
+            function=self.decode,
+            schema=schema,
+            serialization=core_schema.plain_serializer_function_ser_schema(function=self.encode),
+        )
+
+    def decode(self, data: bytes, _: core_schema.ValidationInfo) -> bytes:
+        """Decode the data using the specified encoder.
+
+        Args:
+            data: The data to decode.
+
+        Returns:
+            The decoded data.
+        """
+        return self.encoder.decode(data)
+
+    def encode(self, value: bytes) -> bytes:
+        """Encode the data using the specified encoder.
+
+        Args:
+            value: The data to encode.
+
+        Returns:
+            The encoded data.
+        """
+        return self.encoder.encode(value)
+
+    def __hash__(self) -> int:
+        return hash(self.encoder)
+
+
+@_dataclasses.dataclass(**_internal_dataclass.slots_true)
+class EncodedStr:
+    """A str type that is encoded and decoded using the specified encoder.
+
+    `EncodedStr` needs an encoder that implements `EncoderProtocol` to operate.
+
+    ```python
+    from typing import Annotated
+
+    from pydantic import BaseModel, EncodedStr, EncoderProtocol, ValidationError
+
+    class MyEncoder(EncoderProtocol):
+        @classmethod
+        def decode(cls, data: bytes) -> bytes:
+            if data == b'**undecodable**':
+                raise ValueError('Cannot decode data')
+            return data[13:]
+
+        @classmethod
+        def encode(cls, value: bytes) -> bytes:
+            return b'**encoded**: ' + value
+
+        @classmethod
+        def get_json_format(cls) -> str:
+            return 'my-encoder'
+
+    MyEncodedStr = Annotated[str, EncodedStr(encoder=MyEncoder)]
+
+    class Model(BaseModel):
+        my_encoded_str: MyEncodedStr
+
+    # Initialize the model with encoded data
+    m = Model(my_encoded_str='**encoded**: some str')
+
+    # Access decoded value
+    print(m.my_encoded_str)
+    #> some str
+
+    # Serialize into the encoded form
+    print(m.model_dump())
+    #> {'my_encoded_str': '**encoded**: some str'}
+
+    # Validate encoded data
+    try:
+        Model(my_encoded_str='**undecodable**')
+    except ValidationError as e:
+        print(e)
+        '''
+        1 validation error for Model
+        my_encoded_str
+          Value error, Cannot decode data [type=value_error, input_value='**undecodable**', input_type=str]
+        '''
+    ```
+    """
+
+    encoder: type[EncoderProtocol]
+
+    def __get_pydantic_json_schema__(
+        self, core_schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler
+    ) -> JsonSchemaValue:
+        field_schema = handler(core_schema)
+        field_schema.update(type='string', format=self.encoder.get_json_format())
+        return field_schema
+
+    def __get_pydantic_core_schema__(self, source: type[Any], handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
+        schema = handler(source)
+        _check_annotated_type(schema['type'], 'str', self.__class__.__name__)
+        return core_schema.with_info_after_validator_function(
+            function=self.decode_str,
+            schema=schema,
+            serialization=core_schema.plain_serializer_function_ser_schema(function=self.encode_str),
+        )
+
+    def decode_str(self, data: str, _: core_schema.ValidationInfo) -> str:
+        """Decode the data using the specified encoder.
+
+        Args:
+            data: The data to decode.
+
+        Returns:
+            The decoded data.
+        """
+        return self.encoder.decode(data.encode()).decode()
+
+    def encode_str(self, value: str) -> str:
+        """Encode the data using the specified encoder.
+
+        Args:
+            value: The data to encode.
+
+        Returns:
+            The encoded data.
+        """
+        return self.encoder.encode(value.encode()).decode()  # noqa: UP008
+
+    def __hash__(self) -> int:
+        return hash(self.encoder)
+
+
+Base64Bytes = Annotated[bytes, EncodedBytes(encoder=Base64Encoder)]
+"""A bytes type that is encoded and decoded using the standard (non-URL-safe) base64 encoder.
+
+Note:
+    Under the hood, `Base64Bytes` uses the standard library `base64.b64encode` and `base64.b64decode` functions.
+
+    As a result, attempting to decode url-safe base64 data using the `Base64Bytes` type may fail or produce an incorrect
+    decoding.
+
+Warning:
+    In versions of Pydantic prior to v2.10, `Base64Bytes` used [`base64.encodebytes`][base64.encodebytes]
+    and [`base64.decodebytes`][base64.decodebytes] functions. According to the [base64 documentation](https://docs.python.org/3/library/base64.html),
+    these methods are considered legacy implementation, and thus, Pydantic v2.10+ now uses the modern
+    [`base64.b64encode`][base64.b64encode] and [`base64.b64decode`][base64.b64decode] functions.
+
+    If you'd still like to use these legacy encoders / decoders, you can achieve this by creating a custom annotated type,
+    like follows:
+
+    ```python
+    import base64
+    from typing import Annotated, Literal
+
+    from pydantic_core import PydanticCustomError
+
+    from pydantic import EncodedBytes, EncoderProtocol
+
+    class LegacyBase64Encoder(EncoderProtocol):
+        @classmethod
+        def decode(cls, data: bytes) -> bytes:
+            try:
+                return base64.decodebytes(data)
+            except ValueError as e:
+                raise PydanticCustomError(
+                    'base64_decode',
+                    "Base64 decoding error: '{error}'",
+                    {'error': str(e)},
+                )
+
+        @classmethod
+        def encode(cls, value: bytes) -> bytes:
+            return base64.encodebytes(value)
+
+        @classmethod
+        def get_json_format(cls) -> Literal['base64']:
+            return 'base64'
+
+    LegacyBase64Bytes = Annotated[bytes, EncodedBytes(encoder=LegacyBase64Encoder)]
+    ```
+
+```python
+from pydantic import Base64Bytes, BaseModel, ValidationError
+
+class Model(BaseModel):
+    base64_bytes: Base64Bytes
+
+# Initialize the model with base64 data
+m = Model(base64_bytes=b'VGhpcyBpcyB0aGUgd2F5')
+
+# Access decoded value
+print(m.base64_bytes)
+#> b'This is the way'
+
+# Serialize into the base64 form
+print(m.model_dump())
+#> {'base64_bytes': b'VGhpcyBpcyB0aGUgd2F5'}
+
+# Validate base64 data
+try:
+    print(Model(base64_bytes=b'undecodable').base64_bytes)
+except ValidationError as e:
+    print(e)
+    '''
+    1 validation error for Model
+    base64_bytes
+      Base64 decoding error: 'Incorrect padding' [type=base64_decode, input_value=b'undecodable', input_type=bytes]
+    '''
+```
+"""
+Base64Str = Annotated[str, EncodedStr(encoder=Base64Encoder)]
+"""A str type that is encoded and decoded using the standard (non-URL-safe) base64 encoder.
+
+Note:
+    Under the hood, `Base64Str` uses the standard library `base64.b64encode` and `base64.b64decode` functions.
+
+    As a result, attempting to decode url-safe base64 data using the `Base64Str` type may fail or produce an incorrect
+    decoding.
+
+Warning:
+    In versions of Pydantic prior to v2.10, `Base64Str` used [`base64.encodebytes`][base64.encodebytes]
+    and [`base64.decodebytes`][base64.decodebytes] functions. According to the [base64 documentation](https://docs.python.org/3/library/base64.html),
+    these methods are considered legacy implementation, and thus, Pydantic v2.10+ now uses the modern
+    [`base64.b64encode`][base64.b64encode] and [`base64.b64decode`][base64.b64decode] functions.
+
+    See the [`Base64Bytes`][pydantic.types.Base64Bytes] type for more information on how to
+    replicate the old behavior with the legacy encoders / decoders.
+
+```python
+from pydantic import Base64Str, BaseModel, ValidationError
+
+class Model(BaseModel):
+    base64_str: Base64Str
+
+# Initialize the model with base64 data
+m = Model(base64_str='VGhlc2UgYXJlbid0IHRoZSBkcm9pZHMgeW91J3JlIGxvb2tpbmcgZm9y')
+
+# Access decoded value
+print(m.base64_str)
+#> These aren't the droids you're looking for
+
+# Serialize into the base64 form
+print(m.model_dump())
+#> {'base64_str': 'VGhlc2UgYXJlbid0IHRoZSBkcm9pZHMgeW91J3JlIGxvb2tpbmcgZm9y'}
+
+# Validate base64 data
+try:
+    print(Model(base64_str='undecodable').base64_str)
+except ValidationError as e:
+    print(e)
+    '''
+    1 validation error for Model
+    base64_str
+      Base64 decoding error: 'Incorrect padding' [type=base64_decode, input_value='undecodable', input_type=str]
+    '''
+```
+"""
+Base64UrlBytes = Annotated[bytes, EncodedBytes(encoder=Base64UrlEncoder)]
+"""A bytes type that is encoded and decoded using the URL-safe base64 encoder.
+
+Note:
+    Under the hood, `Base64UrlBytes` use standard library `base64.urlsafe_b64encode` and `base64.urlsafe_b64decode`
+    functions.
+
+    As a result, the `Base64UrlBytes` type can be used to faithfully decode "vanilla" base64 data
+    (using `'+'` and `'/'`).
+
+```python
+from pydantic import Base64UrlBytes, BaseModel
+
+class Model(BaseModel):
+    base64url_bytes: Base64UrlBytes
+
+# Initialize the model with base64 data
+m = Model(base64url_bytes=b'SHc_dHc-TXc==')
+print(m)
+#> base64url_bytes=b'Hw?tw>Mw'
+```
+"""
+Base64UrlStr = Annotated[str, EncodedStr(encoder=Base64UrlEncoder)]
+"""A str type that is encoded and decoded using the URL-safe base64 encoder.
+
+Note:
+    Under the hood, `Base64UrlStr` use standard library `base64.urlsafe_b64encode` and `base64.urlsafe_b64decode`
+    functions.
+
+    As a result, the `Base64UrlStr` type can be used to faithfully decode "vanilla" base64 data (using `'+'` and `'/'`).
+
+```python
+from pydantic import Base64UrlStr, BaseModel
+
+class Model(BaseModel):
+    base64url_str: Base64UrlStr
+
+# Initialize the model with base64 data
+m = Model(base64url_str='SHc_dHc-TXc==')
+print(m)
+#> base64url_str='Hw?tw>Mw'
+```
+"""
+
+
+__getattr__ = getattr_migration(__name__)
+
+
+@_dataclasses.dataclass(**_internal_dataclass.slots_true)
+class GetPydanticSchema:
+    """!!! abstract "Usage Documentation"
+        [Using `GetPydanticSchema` to Reduce Boilerplate](../concepts/types.md#using-getpydanticschema-to-reduce-boilerplate)
+
+    A convenience class for creating an annotation that provides pydantic custom type hooks.
+
+    This class is intended to eliminate the need to create a custom "marker" which defines the
+     `__get_pydantic_core_schema__` and `__get_pydantic_json_schema__` custom hook methods.
+
+    For example, to have a field treated by type checkers as `int`, but by pydantic as `Any`, you can do:
+    ```python
+    from typing import Annotated, Any
+
+    from pydantic import BaseModel, GetPydanticSchema
+
+    HandleAsAny = GetPydanticSchema(lambda _s, h: h(Any))
+
+    class Model(BaseModel):
+        x: Annotated[int, HandleAsAny]  # pydantic sees `x: Any`
+
+    print(repr(Model(x='abc').x))
+    #> 'abc'
+    ```
+    """
+
+    get_pydantic_core_schema: Callable[[Any, GetCoreSchemaHandler], CoreSchema] | None = None
+    get_pydantic_json_schema: Callable[[Any, GetJsonSchemaHandler], JsonSchemaValue] | None = None
+
+    # Note: we may want to consider adding a convenience staticmethod `def for_type(type_: Any) -> GetPydanticSchema:`
+    #   which returns `GetPydanticSchema(lambda _s, h: h(type_))`
+
+    if not TYPE_CHECKING:
+        # We put `__getattr__` in a non-TYPE_CHECKING block because otherwise, mypy allows arbitrary attribute access
+
+        def __getattr__(self, item: str) -> Any:
+            """Use this rather than defining `__get_pydantic_core_schema__` etc. to reduce the number of nested calls."""
+            if item == '__get_pydantic_core_schema__' and self.get_pydantic_core_schema:
+                return self.get_pydantic_core_schema
+            elif item == '__get_pydantic_json_schema__' and self.get_pydantic_json_schema:
+                return self.get_pydantic_json_schema
+            else:
+                return object.__getattribute__(self, item)
+
+    __hash__ = object.__hash__
+
+
+@_dataclasses.dataclass(**_internal_dataclass.slots_true, frozen=True)
+class Tag:
+    """Provides a way to specify the expected tag to use for a case of a (callable) discriminated union.
+
+    Also provides a way to label a union case in error messages.
+
+    When using a callable `Discriminator`, attach a `Tag` to each case in the `Union` to specify the tag that
+    should be used to identify that case. For example, in the below example, the `Tag` is used to specify that
+    if `get_discriminator_value` returns `'apple'`, the input should be validated as an `ApplePie`, and if it
+    returns `'pumpkin'`, the input should be validated as a `PumpkinPie`.
+
+    The primary role of the `Tag` here is to map the return value from the callable `Discriminator` function to
+    the appropriate member of the `Union` in question.
+
+    ```python
+    from typing import Annotated, Any, Literal, Union
+
+    from pydantic import BaseModel, Discriminator, Tag
+
+    class Pie(BaseModel):
+        time_to_cook: int
+        num_ingredients: int
+
+    class ApplePie(Pie):
+        fruit: Literal['apple'] = 'apple'
+
+    class PumpkinPie(Pie):
+        filling: Literal['pumpkin'] = 'pumpkin'
+
+    def get_discriminator_value(v: Any) -> str:
+        if isinstance(v, dict):
+            return v.get('fruit', v.get('filling'))
+        return getattr(v, 'fruit', getattr(v, 'filling', None))
+
+    class ThanksgivingDinner(BaseModel):
+        dessert: Annotated[
+            Union[
+                Annotated[ApplePie, Tag('apple')],
+                Annotated[PumpkinPie, Tag('pumpkin')],
+            ],
+            Discriminator(get_discriminator_value),
+        ]
+
+    apple_variation = ThanksgivingDinner.model_validate(
+        {'dessert': {'fruit': 'apple', 'time_to_cook': 60, 'num_ingredients': 8}}
+    )
+    print(repr(apple_variation))
+    '''
+    ThanksgivingDinner(dessert=ApplePie(time_to_cook=60, num_ingredients=8, fruit='apple'))
+    '''
+
+    pumpkin_variation = ThanksgivingDinner.model_validate(
+        {
+            'dessert': {
+                'filling': 'pumpkin',
+                'time_to_cook': 40,
+                'num_ingredients': 6,
+            }
+        }
+    )
+    print(repr(pumpkin_variation))
+    '''
+    ThanksgivingDinner(dessert=PumpkinPie(time_to_cook=40, num_ingredients=6, filling='pumpkin'))
+    '''
+    ```
+
+    !!! note
+        You must specify a `Tag` for every case in a `Tag` that is associated with a
+        callable `Discriminator`. Failing to do so will result in a `PydanticUserError` with code
+        [`callable-discriminator-no-tag`](../errors/usage_errors.md#callable-discriminator-no-tag).
+
+    See the [Discriminated Unions] concepts docs for more details on how to use `Tag`s.
+
+    [Discriminated Unions]: ../concepts/unions.md#discriminated-unions
+    """
+
+    tag: str
+
+    def __get_pydantic_core_schema__(self, source_type: Any, handler: GetCoreSchemaHandler) -> CoreSchema:
+        schema = handler(source_type)
+        metadata = cast('CoreMetadata', schema.setdefault('metadata', {}))
+        metadata['pydantic_internal_union_tag_key'] = self.tag
+        return schema
+
+
+@_dataclasses.dataclass(**_internal_dataclass.slots_true, frozen=True)
+class Discriminator:
+    """!!! abstract "Usage Documentation"
+        [Discriminated Unions with `Callable` `Discriminator`](../concepts/unions.md#discriminated-unions-with-callable-discriminator)
+
+    Provides a way to use a custom callable as the way to extract the value of a union discriminator.
+
+    This allows you to get validation behavior like you'd get from `Field(discriminator=)`,
+    but without needing to have a single shared field across all the union choices. This also makes it
+    possible to handle unions of models and primitive types with discriminated-union-style validation errors.
+    Finally, this allows you to use a custom callable as the way to identify which member of a union a value
+    belongs to, while still seeing all the performance benefits of a discriminated union.
+
+    Consider this example, which is much more performant with the use of `Discriminator` and thus a `TaggedUnion`
+    than it would be as a normal `Union`.
+
+    ```python
+    from typing import Annotated, Any, Literal, Union
+
+    from pydantic import BaseModel, Discriminator, Tag
+
+    class Pie(BaseModel):
+        time_to_cook: int
+        num_ingredients: int
+
+    class ApplePie(Pie):
+        fruit: Literal['apple'] = 'apple'
+
+    class PumpkinPie(Pie):
+        filling: Literal['pumpkin'] = 'pumpkin'
+
+    def get_discriminator_value(v: Any) -> str:
+        if isinstance(v, dict):
+            return v.get('fruit', v.get('filling'))
+        return getattr(v, 'fruit', getattr(v, 'filling', None))
+
+    class ThanksgivingDinner(BaseModel):
+        dessert: Annotated[
+            Union[
+                Annotated[ApplePie, Tag('apple')],
+                Annotated[PumpkinPie, Tag('pumpkin')],
+            ],
+            Discriminator(get_discriminator_value),
+        ]
+
+    apple_variation = ThanksgivingDinner.model_validate(
+        {'dessert': {'fruit': 'apple', 'time_to_cook': 60, 'num_ingredients': 8}}
+    )
+    print(repr(apple_variation))
+    '''
+    ThanksgivingDinner(dessert=ApplePie(time_to_cook=60, num_ingredients=8, fruit='apple'))
+    '''
+
+    pumpkin_variation = ThanksgivingDinner.model_validate(
+        {
+            'dessert': {
+                'filling': 'pumpkin',
+                'time_to_cook': 40,
+                'num_ingredients': 6,
+            }
+        }
+    )
+    print(repr(pumpkin_variation))
+    '''
+    ThanksgivingDinner(dessert=PumpkinPie(time_to_cook=40, num_ingredients=6, filling='pumpkin'))
+    '''
+    ```
+
+    See the [Discriminated Unions] concepts docs for more details on how to use `Discriminator`s.
+
+    [Discriminated Unions]: ../concepts/unions.md#discriminated-unions
+    """
+
+    discriminator: str | Callable[[Any], Hashable]
+    """The callable or field name for discriminating the type in a tagged union.
+
+    A `Callable` discriminator must extract the value of the discriminator from the input.
+    A `str` discriminator must be the name of a field to discriminate against.
+    """
+    custom_error_type: str | None = None
+    """Type to use in [custom errors](../errors/errors.md) replacing the standard discriminated union
+    validation errors.
+    """
+    custom_error_message: str | None = None
+    """Message to use in custom errors."""
+    custom_error_context: dict[str, int | str | float] | None = None
+    """Context to use in custom errors."""
+
+    def __get_pydantic_core_schema__(self, source_type: Any, handler: GetCoreSchemaHandler) -> CoreSchema:
+        if not is_union_origin(get_origin(source_type)):
+            raise TypeError(f'{type(self).__name__} must be used with a Union type, not {source_type}')
+
+        if isinstance(self.discriminator, str):
+            from pydantic import Field
+
+            return handler(Annotated[source_type, Field(discriminator=self.discriminator)])
+        else:
+            original_schema = handler(source_type)
+            return self._convert_schema(original_schema, handler)
+
+    def _convert_schema(
+        self, original_schema: core_schema.CoreSchema, handler: GetCoreSchemaHandler | None = None
+    ) -> core_schema.TaggedUnionSchema:
+        if original_schema['type'] != 'union':
+            # This likely indicates that the schema was a single-item union that was simplified.
+            # In this case, we do the same thing we do in
+            # `pydantic._internal._discriminated_union._ApplyInferredDiscriminator._apply_to_root`, namely,
+            # package the generated schema back into a single-item union.
+            original_schema = core_schema.union_schema([original_schema])
+
+        tagged_union_choices = {}
+        for choice in original_schema['choices']:
+            tag = None
+            if isinstance(choice, tuple):
+                choice, tag = choice
+            metadata = cast('CoreMetadata | None', choice.get('metadata'))
+            if metadata is not None:
+                tag = metadata.get('pydantic_internal_union_tag_key') or tag
+            if tag is None:
+                # `handler` is None when this method is called from `apply_discriminator()` (deferred discriminators)
+                if handler is not None and choice['type'] == 'definition-ref':
+                    # If choice was built from a PEP 695 type alias, try to resolve the def:
+                    try:
+                        choice = handler.resolve_ref_schema(choice)
+                    except LookupError:
+                        pass
+                    else:
+                        metadata = cast('CoreMetadata | None', choice.get('metadata'))
+                        if metadata is not None:
+                            tag = metadata.get('pydantic_internal_union_tag_key')
+
+                if tag is None:
+                    raise PydanticUserError(
+                        f'`Tag` not provided for choice {choice} used with `Discriminator`',
+                        code='callable-discriminator-no-tag',
+                    )
+            tagged_union_choices[tag] = choice
+
+        # Have to do these verbose checks to ensure falsy values ('' and {}) don't get ignored
+        custom_error_type = self.custom_error_type
+        if custom_error_type is None:
+            custom_error_type = original_schema.get('custom_error_type')
+
+        custom_error_message = self.custom_error_message
+        if custom_error_message is None:
+            custom_error_message = original_schema.get('custom_error_message')
+
+        custom_error_context = self.custom_error_context
+        if custom_error_context is None:
+            custom_error_context = original_schema.get('custom_error_context')
+
+        custom_error_type = original_schema.get('custom_error_type') if custom_error_type is None else custom_error_type
+        return core_schema.tagged_union_schema(
+            tagged_union_choices,
+            self.discriminator,
+            custom_error_type=custom_error_type,
+            custom_error_message=custom_error_message,
+            custom_error_context=custom_error_context,
+            strict=original_schema.get('strict'),
+            ref=original_schema.get('ref'),
+            metadata=original_schema.get('metadata'),
+            serialization=original_schema.get('serialization'),
+        )
+
+
+_JSON_TYPES = {int, float, str, bool, list, dict, type(None)}
+
+
+def _get_type_name(x: Any) -> str:
+    type_ = type(x)
+    if type_ in _JSON_TYPES:
+        return type_.__name__
+
+    # Handle proper subclasses; note we don't need to handle None or bool here
+    if isinstance(x, int):
+        return 'int'
+    if isinstance(x, float):
+        return 'float'
+    if isinstance(x, str):
+        return 'str'
+    if isinstance(x, list):
+        return 'list'
+    if isinstance(x, dict):
+        return 'dict'
+
+    # Fail by returning the type's actual name
+    return getattr(type_, '__name__', '')
+
+
+class _AllowAnyJson:
+    @classmethod
+    def __get_pydantic_core_schema__(cls, source_type: Any, handler: GetCoreSchemaHandler) -> CoreSchema:
+        python_schema = handler(source_type)
+        return core_schema.json_or_python_schema(json_schema=core_schema.any_schema(), python_schema=python_schema)
+
+
+if TYPE_CHECKING:
+    # This seems to only be necessary for mypy
+    JsonValue: TypeAlias = Union[
+        list['JsonValue'],
+        dict[str, 'JsonValue'],
+        str,
+        bool,
+        int,
+        float,
+        None,
+    ]
+    """A `JsonValue` is used to represent a value that can be serialized to JSON.
+
+    It may be one of:
+
+    * `list['JsonValue']`
+    * `dict[str, 'JsonValue']`
+    * `str`
+    * `bool`
+    * `int`
+    * `float`
+    * `None`
+
+    The following example demonstrates how to use `JsonValue` to validate JSON data,
+    and what kind of errors to expect when input data is not json serializable.
+
+    ```python
+    import json
+
+    from pydantic import BaseModel, JsonValue, ValidationError
+
+    class Model(BaseModel):
+        j: JsonValue
+
+    valid_json_data = {'j': {'a': {'b': {'c': 1, 'd': [2, None]}}}}
+    invalid_json_data = {'j': {'a': {'b': ...}}}
+
+    print(repr(Model.model_validate(valid_json_data)))
+    #> Model(j={'a': {'b': {'c': 1, 'd': [2, None]}}})
+    print(repr(Model.model_validate_json(json.dumps(valid_json_data))))
+    #> Model(j={'a': {'b': {'c': 1, 'd': [2, None]}}})
+
+    try:
+        Model.model_validate(invalid_json_data)
+    except ValidationError as e:
+        print(e)
+        '''
+        1 validation error for Model
+        j.dict.a.dict.b
+          input was not a valid JSON value [type=invalid-json-value, input_value=Ellipsis, input_type=ellipsis]
+        '''
+    ```
+    """
+
+else:
+    JsonValue = TypeAliasType(
+        'JsonValue',
+        Annotated[
+            Union[
+                Annotated[list['JsonValue'], Tag('list')],
+                Annotated[dict[str, 'JsonValue'], Tag('dict')],
+                Annotated[str, Tag('str')],
+                Annotated[bool, Tag('bool')],
+                Annotated[int, Tag('int')],
+                Annotated[float, Tag('float')],
+                Annotated[None, Tag('NoneType')],
+            ],
+            Discriminator(
+                _get_type_name,
+                custom_error_type='invalid-json-value',
+                custom_error_message='input was not a valid JSON value',
+            ),
+            _AllowAnyJson,
+        ],
+    )
+
+
+class _OnErrorOmit:
+    @classmethod
+    def __get_pydantic_core_schema__(cls, source_type: Any, handler: GetCoreSchemaHandler) -> CoreSchema:
+        # there is no actual default value here but we use with_default_schema since it already has the on_error
+        # behavior implemented and it would be no more efficient to implement it on every other validator
+        # or as a standalone validator
+        return core_schema.with_default_schema(schema=handler(source_type), on_error='omit')
+
+
+OnErrorOmit = Annotated[T, _OnErrorOmit]
+"""
+When used as an item in a list, the key type in a dict, optional values of a TypedDict, etc.
+this annotation omits the item from the iteration if there is any error validating it.
+That is, instead of a [`ValidationError`][pydantic_core.ValidationError] being propagated up and the entire iterable being discarded
+any invalid items are discarded and the valid ones are returned.
+"""
+
+
+@_dataclasses.dataclass
+class FailFast(_fields.PydanticMetadata, BaseMetadata):
+    """A `FailFast` annotation can be used to specify that validation should stop at the first error.
+
+    This can be useful when you want to validate a large amount of data and you only need to know if it's valid or not.
+
+    You might want to enable this setting if you want to validate your data faster (basically, if you use this,
+    validation will be more performant with the caveat that you get less information).
+
+    ```python
+    from typing import Annotated
+
+    from pydantic import BaseModel, FailFast, ValidationError
+
+    class Model(BaseModel):
+        x: Annotated[list[int], FailFast()]
+
+    # This will raise a single error for the first invalid value and stop validation
+    try:
+        obj = Model(x=[1, 2, 'a', 4, 5, 'b', 7, 8, 9, 'c'])
+    except ValidationError as e:
+        print(e)
+        '''
+        1 validation error for Model
+        x.2
+          Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='a', input_type=str]
+        '''
+    ```
+    """
+
+    fail_fast: bool = True
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pydantic/typing.py b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/typing.py
new file mode 100644
index 0000000000000000000000000000000000000000..0bda22d02ffc59f306ded475805343aef2855f49
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/typing.py
@@ -0,0 +1,5 @@
+"""`typing` module is a backport module from V1."""
+
+from ._migration import getattr_migration
+
+__getattr__ = getattr_migration(__name__)
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pydantic/utils.py b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..8d1e2a81c5f0d1bd858bf12ccf15b1461008cf99
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/utils.py
@@ -0,0 +1,5 @@
+"""The `utils` module is a backport module from V1."""
+
+from ._migration import getattr_migration
+
+__getattr__ = getattr_migration(__name__)
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pydantic/validate_call_decorator.py b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/validate_call_decorator.py
new file mode 100644
index 0000000000000000000000000000000000000000..fe4d9c9b6c5ef3a98e4f2770d853d92d8a0124b0
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/validate_call_decorator.py
@@ -0,0 +1,116 @@
+"""Decorator for validating function calls."""
+
+from __future__ import annotations as _annotations
+
+import inspect
+from functools import partial
+from types import BuiltinFunctionType
+from typing import TYPE_CHECKING, Any, Callable, TypeVar, cast, overload
+
+from ._internal import _generate_schema, _typing_extra, _validate_call
+from .errors import PydanticUserError
+
+__all__ = ('validate_call',)
+
+if TYPE_CHECKING:
+    from .config import ConfigDict
+
+    AnyCallableT = TypeVar('AnyCallableT', bound=Callable[..., Any])
+
+
+_INVALID_TYPE_ERROR_CODE = 'validate-call-type'
+
+
+def _check_function_type(function: object) -> None:
+    """Check if the input function is a supported type for `validate_call`."""
+    if isinstance(function, _generate_schema.VALIDATE_CALL_SUPPORTED_TYPES):
+        try:
+            inspect.signature(cast(_generate_schema.ValidateCallSupportedTypes, function))
+        except ValueError:
+            raise PydanticUserError(
+                f"Input function `{function}` doesn't have a valid signature", code=_INVALID_TYPE_ERROR_CODE
+            )
+
+        if isinstance(function, partial):
+            try:
+                assert not isinstance(partial.func, partial), 'Partial of partial'
+                _check_function_type(function.func)
+            except PydanticUserError as e:
+                raise PydanticUserError(
+                    f'Partial of `{function.func}` is invalid because the type of `{function.func}` is not supported by `validate_call`',
+                    code=_INVALID_TYPE_ERROR_CODE,
+                ) from e
+
+        return
+
+    if isinstance(function, BuiltinFunctionType):
+        raise PydanticUserError(f'Input built-in function `{function}` is not supported', code=_INVALID_TYPE_ERROR_CODE)
+    if isinstance(function, (classmethod, staticmethod, property)):
+        name = type(function).__name__
+        raise PydanticUserError(
+            f'The `@{name}` decorator should be applied after `@validate_call` (put `@{name}` on top)',
+            code=_INVALID_TYPE_ERROR_CODE,
+        )
+
+    if inspect.isclass(function):
+        raise PydanticUserError(
+            f'Unable to validate {function}: `validate_call` should be applied to functions, not classes (put `@validate_call` on top of `__init__` or `__new__` instead)',
+            code=_INVALID_TYPE_ERROR_CODE,
+        )
+    if callable(function):
+        raise PydanticUserError(
+            f'Unable to validate {function}: `validate_call` should be applied to functions, not instances or other callables. Use `validate_call` explicitly on `__call__` instead.',
+            code=_INVALID_TYPE_ERROR_CODE,
+        )
+
+    raise PydanticUserError(
+        f'Unable to validate {function}: `validate_call` should be applied to one of the following: function, method, partial, or lambda',
+        code=_INVALID_TYPE_ERROR_CODE,
+    )
+
+
+@overload
+def validate_call(
+    *, config: ConfigDict | None = None, validate_return: bool = False
+) -> Callable[[AnyCallableT], AnyCallableT]: ...
+
+
+@overload
+def validate_call(func: AnyCallableT, /) -> AnyCallableT: ...
+
+
+def validate_call(
+    func: AnyCallableT | None = None,
+    /,
+    *,
+    config: ConfigDict | None = None,
+    validate_return: bool = False,
+) -> AnyCallableT | Callable[[AnyCallableT], AnyCallableT]:
+    """!!! abstract "Usage Documentation"
+        [Validation Decorator](../concepts/validation_decorator.md)
+
+    Returns a decorated wrapper around the function that validates the arguments and, optionally, the return value.
+
+    Usage may be either as a plain decorator `@validate_call` or with arguments `@validate_call(...)`.
+
+    Args:
+        func: The function to be decorated.
+        config: The configuration dictionary.
+        validate_return: Whether to validate the return value.
+
+    Returns:
+        The decorated function.
+    """
+    parent_namespace = _typing_extra.parent_frame_namespace()
+
+    def validate(function: AnyCallableT) -> AnyCallableT:
+        _check_function_type(function)
+        validate_call_wrapper = _validate_call.ValidateCallWrapper(
+            cast(_generate_schema.ValidateCallSupportedTypes, function), config, validate_return, parent_namespace
+        )
+        return _validate_call.update_wrapper_attributes(function, validate_call_wrapper.__call__)  # type: ignore
+
+    if func is not None:
+        return validate(func)
+    else:
+        return validate
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pydantic/validators.py b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/validators.py
new file mode 100644
index 0000000000000000000000000000000000000000..7921b04f05d5ef0ad20365e7372a48d86724dc51
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/validators.py
@@ -0,0 +1,5 @@
+"""The `validators` module is a backport module from V1."""
+
+from ._migration import getattr_migration
+
+__getattr__ = getattr_migration(__name__)
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pydantic/version.py b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/version.py
new file mode 100644
index 0000000000000000000000000000000000000000..eaf2619a475375510fa062e9fad13efa91014360
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/version.py
@@ -0,0 +1,113 @@
+"""The `version` module holds the version information for Pydantic."""
+
+from __future__ import annotations as _annotations
+
+import sys
+
+from pydantic_core import __version__ as __pydantic_core_version__
+
+__all__ = 'VERSION', 'version_info'
+
+VERSION = '2.12.5'
+"""The version of Pydantic.
+
+This version specifier is guaranteed to be compliant with the [specification],
+introduced by [PEP 440].
+
+[specification]: https://packaging.python.org/en/latest/specifications/version-specifiers/
+[PEP 440]: https://peps.python.org/pep-0440/
+"""
+
+# Keep this in sync with the version constraint in the `pyproject.toml` dependencies:
+_COMPATIBLE_PYDANTIC_CORE_VERSION = '2.41.5'
+
+
+def version_short() -> str:
+    """Return the `major.minor` part of Pydantic version.
+
+    It returns '2.1' if Pydantic version is '2.1.1'.
+    """
+    return '.'.join(VERSION.split('.')[:2])
+
+
+def version_info() -> str:
+    """Return complete version information for Pydantic and its dependencies."""
+    import importlib.metadata
+    import platform
+    from pathlib import Path
+
+    import pydantic_core._pydantic_core as pdc
+
+    from ._internal import _git as git
+
+    # get data about packages that are closely related to pydantic, use pydantic or often conflict with pydantic
+    package_names = {
+        'email-validator',
+        'fastapi',
+        'mypy',
+        'pydantic-extra-types',
+        'pydantic-settings',
+        'pyright',
+        'typing_extensions',
+    }
+    related_packages = []
+
+    for dist in importlib.metadata.distributions():
+        name = dist.metadata['Name']
+        if name in package_names:
+            related_packages.append(f'{name}-{dist.version}')
+
+    pydantic_dir = Path(__file__).parents[1].resolve()
+    most_recent_commit = (
+        git.git_revision(pydantic_dir) if git.is_git_repo(pydantic_dir) and git.have_git() else 'unknown'
+    )
+
+    info = {
+        'pydantic version': VERSION,
+        'pydantic-core version': __pydantic_core_version__,
+        'pydantic-core build': getattr(pdc, 'build_info', None) or pdc.build_profile,  # pyright: ignore[reportPrivateImportUsage]
+        'python version': sys.version,
+        'platform': platform.platform(),
+        'related packages': ' '.join(related_packages),
+        'commit': most_recent_commit,
+    }
+    return '\n'.join('{:>30} {}'.format(k + ':', str(v).replace('\n', ' ')) for k, v in info.items())
+
+
+def check_pydantic_core_version() -> bool:
+    """Check that the installed `pydantic-core` dependency is compatible."""
+    return __pydantic_core_version__ == _COMPATIBLE_PYDANTIC_CORE_VERSION
+
+
+def _ensure_pydantic_core_version() -> None:  # pragma: no cover
+    if not check_pydantic_core_version():
+        raise_error = True
+        # Do not raise the error if pydantic is installed in editable mode (i.e. in development):
+        if sys.version_info >= (3, 13):  # origin property added in 3.13
+            from importlib.metadata import distribution
+
+            dist = distribution('pydantic')
+            if getattr(getattr(dist.origin, 'dir_info', None), 'editable', False):
+                raise_error = False
+
+        if raise_error:
+            raise SystemError(
+                f'The installed pydantic-core version ({__pydantic_core_version__}) is incompatible '
+                f'with the current pydantic version, which requires {_COMPATIBLE_PYDANTIC_CORE_VERSION}. '
+                "If you encounter this error, make sure that you haven't upgraded pydantic-core manually."
+            )
+
+
+def parse_mypy_version(version: str) -> tuple[int, int, int]:
+    """Parse `mypy` string version to a 3-tuple of ints.
+
+    It parses normal version like `1.11.0` and extra info followed by a `+` sign
+    like `1.11.0+dev.d6d9d8cd4f27c52edac1f537e236ec48a01e54cb.dirty`.
+
+    Args:
+        version: The mypy version string.
+
+    Returns:
+        A triple of ints, e.g. `(1, 11, 0)`.
+    """
+    return tuple(map(int, version.partition('+')[0].split('.')))  # pyright: ignore[reportReturnType]
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pydantic/warnings.py b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/warnings.py
new file mode 100644
index 0000000000000000000000000000000000000000..2e2dd83c13e00e95196734a07eda2c3f8d408654
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pydantic/warnings.py
@@ -0,0 +1,122 @@
+"""Pydantic-specific warnings."""
+
+from __future__ import annotations as _annotations
+
+from .version import version_short
+
+__all__ = (
+    'PydanticDeprecatedSince20',
+    'PydanticDeprecatedSince26',
+    'PydanticDeprecatedSince29',
+    'PydanticDeprecatedSince210',
+    'PydanticDeprecatedSince211',
+    'PydanticDeprecatedSince212',
+    'PydanticDeprecationWarning',
+    'PydanticExperimentalWarning',
+    'ArbitraryTypeWarning',
+    'UnsupportedFieldAttributeWarning',
+    'TypedDictExtraConfigWarning',
+)
+
+
+class PydanticDeprecationWarning(DeprecationWarning):
+    """A Pydantic specific deprecation warning.
+
+    This warning is raised when using deprecated functionality in Pydantic. It provides information on when the
+    deprecation was introduced and the expected version in which the corresponding functionality will be removed.
+
+    Attributes:
+        message: Description of the warning.
+        since: Pydantic version in what the deprecation was introduced.
+        expected_removal: Pydantic version in what the corresponding functionality expected to be removed.
+    """
+
+    message: str
+    since: tuple[int, int]
+    expected_removal: tuple[int, int]
+
+    def __init__(
+        self, message: str, *args: object, since: tuple[int, int], expected_removal: tuple[int, int] | None = None
+    ) -> None:
+        super().__init__(message, *args)
+        self.message = message.rstrip('.')
+        self.since = since
+        self.expected_removal = expected_removal if expected_removal is not None else (since[0] + 1, 0)
+
+    def __str__(self) -> str:
+        message = (
+            f'{self.message}. Deprecated in Pydantic V{self.since[0]}.{self.since[1]}'
+            f' to be removed in V{self.expected_removal[0]}.{self.expected_removal[1]}.'
+        )
+        if self.since == (2, 0):
+            message += f' See Pydantic V2 Migration Guide at https://errors.pydantic.dev/{version_short()}/migration/'
+        return message
+
+
+class PydanticDeprecatedSince20(PydanticDeprecationWarning):
+    """A specific `PydanticDeprecationWarning` subclass defining functionality deprecated since Pydantic 2.0."""
+
+    def __init__(self, message: str, *args: object) -> None:
+        super().__init__(message, *args, since=(2, 0), expected_removal=(3, 0))
+
+
+class PydanticDeprecatedSince26(PydanticDeprecationWarning):
+    """A specific `PydanticDeprecationWarning` subclass defining functionality deprecated since Pydantic 2.6."""
+
+    def __init__(self, message: str, *args: object) -> None:
+        super().__init__(message, *args, since=(2, 6), expected_removal=(3, 0))
+
+
+class PydanticDeprecatedSince29(PydanticDeprecationWarning):
+    """A specific `PydanticDeprecationWarning` subclass defining functionality deprecated since Pydantic 2.9."""
+
+    def __init__(self, message: str, *args: object) -> None:
+        super().__init__(message, *args, since=(2, 9), expected_removal=(3, 0))
+
+
+class PydanticDeprecatedSince210(PydanticDeprecationWarning):
+    """A specific `PydanticDeprecationWarning` subclass defining functionality deprecated since Pydantic 2.10."""
+
+    def __init__(self, message: str, *args: object) -> None:
+        super().__init__(message, *args, since=(2, 10), expected_removal=(3, 0))
+
+
+class PydanticDeprecatedSince211(PydanticDeprecationWarning):
+    """A specific `PydanticDeprecationWarning` subclass defining functionality deprecated since Pydantic 2.11."""
+
+    def __init__(self, message: str, *args: object) -> None:
+        super().__init__(message, *args, since=(2, 11), expected_removal=(3, 0))
+
+
+class PydanticDeprecatedSince212(PydanticDeprecationWarning):
+    """A specific `PydanticDeprecationWarning` subclass defining functionality deprecated since Pydantic 2.12."""
+
+    def __init__(self, message: str, *args: object) -> None:
+        super().__init__(message, *args, since=(2, 12), expected_removal=(3, 0))
+
+
+class GenericBeforeBaseModelWarning(Warning):
+    pass
+
+
+class PydanticExperimentalWarning(Warning):
+    """A Pydantic specific experimental functionality warning.
+
+    It is raised to warn users that the functionality may change or be removed in future versions of Pydantic.
+    """
+
+
+class CoreSchemaGenerationWarning(UserWarning):
+    """A warning raised during core schema generation."""
+
+
+class ArbitraryTypeWarning(CoreSchemaGenerationWarning):
+    """A warning raised when Pydantic fails to generate a core schema for an arbitrary type."""
+
+
+class UnsupportedFieldAttributeWarning(CoreSchemaGenerationWarning):
+    """A warning raised when a `Field()` attribute isn't supported in the context it is used."""
+
+
+class TypedDictExtraConfigWarning(CoreSchemaGenerationWarning):
+    """A warning raised when the [`extra`][pydantic.ConfigDict.extra] configuration is incompatible with the `closed` or `extra_items` specification."""
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pydantic_core-2.41.5.dist-info/INSTALLER b/TTS/Kokoro/.venv/Lib/site-packages/pydantic_core-2.41.5.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pydantic_core-2.41.5.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pydantic_core-2.41.5.dist-info/METADATA b/TTS/Kokoro/.venv/Lib/site-packages/pydantic_core-2.41.5.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..01ca5496875bced4dedacf510461c7908bacace2
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pydantic_core-2.41.5.dist-info/METADATA
@@ -0,0 +1,180 @@
+Metadata-Version: 2.4
+Name: pydantic_core
+Version: 2.41.5
+Classifier: Development Status :: 3 - Alpha
+Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3 :: Only
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Classifier: Programming Language :: Python :: 3.13
+Classifier: Programming Language :: Python :: 3.14
+Classifier: Programming Language :: Python :: Implementation :: CPython
+Classifier: Programming Language :: Python :: Implementation :: PyPy
+Classifier: Programming Language :: Python :: Implementation :: GraalPy
+Classifier: Programming Language :: Rust
+Classifier: Framework :: Pydantic
+Classifier: Intended Audience :: Developers
+Classifier: Intended Audience :: Information Technology
+Classifier: Operating System :: POSIX :: Linux
+Classifier: Operating System :: Microsoft :: Windows
+Classifier: Operating System :: MacOS
+Classifier: Typing :: Typed
+Requires-Dist: typing-extensions>=4.14.1
+License-File: LICENSE
+Summary: Core functionality for Pydantic validation and serialization
+Home-Page: https://github.com/pydantic/pydantic-core
+Author-email: Samuel Colvin , Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com>, David Montague , David Hewitt , Sydney Runkle , Victorien Plot 
+License-Expression: MIT
+Requires-Python: >=3.9
+Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
+Project-URL: Homepage, https://github.com/pydantic/pydantic-core
+Project-URL: Funding, https://github.com/sponsors/samuelcolvin
+Project-URL: Source, https://github.com/pydantic/pydantic-core
+
+# pydantic-core
+
+[![CI](https://github.com/pydantic/pydantic-core/workflows/ci/badge.svg?event=push)](https://github.com/pydantic/pydantic-core/actions?query=event%3Apush+branch%3Amain+workflow%3Aci)
+[![Coverage](https://codecov.io/gh/pydantic/pydantic-core/branch/main/graph/badge.svg)](https://codecov.io/gh/pydantic/pydantic-core)
+[![pypi](https://img.shields.io/pypi/v/pydantic-core.svg)](https://pypi.python.org/pypi/pydantic-core)
+[![versions](https://img.shields.io/pypi/pyversions/pydantic-core.svg)](https://github.com/pydantic/pydantic-core)
+[![license](https://img.shields.io/github/license/pydantic/pydantic-core.svg)](https://github.com/pydantic/pydantic-core/blob/main/LICENSE)
+
+This package provides the core functionality for [pydantic](https://docs.pydantic.dev) validation and serialization.
+
+Pydantic-core is currently around 17x faster than pydantic V1.
+See [`tests/benchmarks/`](./tests/benchmarks/) for details.
+
+## Example of direct usage
+
+_NOTE: You should not need to use pydantic-core directly; instead, use pydantic, which in turn uses pydantic-core._
+
+```py
+from pydantic_core import SchemaValidator, ValidationError
+
+
+v = SchemaValidator(
+    {
+        'type': 'typed-dict',
+        'fields': {
+            'name': {
+                'type': 'typed-dict-field',
+                'schema': {
+                    'type': 'str',
+                },
+            },
+            'age': {
+                'type': 'typed-dict-field',
+                'schema': {
+                    'type': 'int',
+                    'ge': 18,
+                },
+            },
+            'is_developer': {
+                'type': 'typed-dict-field',
+                'schema': {
+                    'type': 'default',
+                    'schema': {'type': 'bool'},
+                    'default': True,
+                },
+            },
+        },
+    }
+)
+
+r1 = v.validate_python({'name': 'Samuel', 'age': 35})
+assert r1 == {'name': 'Samuel', 'age': 35, 'is_developer': True}
+
+# pydantic-core can also validate JSON directly
+r2 = v.validate_json('{"name": "Samuel", "age": 35}')
+assert r1 == r2
+
+try:
+    v.validate_python({'name': 'Samuel', 'age': 11})
+except ValidationError as e:
+    print(e)
+    """
+    1 validation error for model
+    age
+      Input should be greater than or equal to 18
+      [type=greater_than_equal, context={ge: 18}, input_value=11, input_type=int]
+    """
+```
+
+## Getting Started
+
+### Prerequisites
+
+You'll need:
+1. **[Rust](https://rustup.rs/)** - Rust stable (or nightly for coverage)
+2. **[uv](https://docs.astral.sh/uv/getting-started/installation/)** - Fast Python package manager (will install Python 3.9+ automatically)
+3. **[git](https://git-scm.com/)** - For version control
+4. **[make](https://www.gnu.org/software/make/)** - For running development commands (or use `nmake` on Windows)
+
+### Quick Start
+
+```bash
+# Clone the repository (or from your fork)
+git clone git@github.com:pydantic/pydantic-core.git
+cd pydantic-core
+
+# Install all dependencies using uv, setup pre-commit hooks, and build the development version
+make install
+```
+
+Verify your installation by running:
+
+```bash
+make
+```
+
+This runs a full development cycle: formatting, building, linting, and testing
+
+### Development Commands
+
+Run `make help` to see all available commands, or use these common ones:
+
+```bash
+make build-dev    # to build the package during development
+make build-prod   # to perform an optimised build for benchmarking
+make test         # to run the tests
+make testcov      # to run the tests and generate a coverage report
+make lint         # to run the linter
+make format       # to format python and rust code
+make all          # to run to run build-dev + format + lint + test
+```
+
+### Useful Resources
+
+* [`python/pydantic_core/_pydantic_core.pyi`](./python/pydantic_core/_pydantic_core.pyi) - Python API types
+* [`python/pydantic_core/core_schema.py`](./python/pydantic_core/core_schema.py) - Core schema definitions
+* [`tests/`](./tests) - Comprehensive usage examples
+
+## Profiling
+
+It's possible to profile the code using the [`flamegraph` utility from `flamegraph-rs`](https://github.com/flamegraph-rs/flamegraph). (Tested on Linux.) You can install this with `cargo install flamegraph`.
+
+Run `make build-profiling` to install a release build with debugging symbols included (needed for profiling).
+
+Once that is built, you can profile pytest benchmarks with (e.g.):
+
+```bash
+flamegraph -- pytest tests/benchmarks/test_micro_benchmarks.py -k test_list_of_ints_core_py --benchmark-enable
+```
+The `flamegraph` command will produce an interactive SVG at `flamegraph.svg`.
+
+## Releasing
+
+1. Bump package version locally. Do not just edit `Cargo.toml` on Github, you need both `Cargo.toml` and `Cargo.lock` to be updated.
+2. Make a PR for the version bump and merge it.
+3. Go to https://github.com/pydantic/pydantic-core/releases and click "Draft a new release"
+4. In the "Choose a tag" dropdown enter the new tag `v` and select "Create new tag on publish" when the option appears.
+5. Enter the release title in the form "v "
+6. Click Generate release notes button
+7. Click Publish release
+8. Go to https://github.com/pydantic/pydantic-core/actions and ensure that all build for release are done successfully.
+9. Go to https://pypi.org/project/pydantic-core/ and ensure that the latest release is published.
+10. Done 🎉
+
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pydantic_core-2.41.5.dist-info/RECORD b/TTS/Kokoro/.venv/Lib/site-packages/pydantic_core-2.41.5.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..7dd19976e1d2d20e5fbedba976d8b2d0e3b9bbd0
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pydantic_core-2.41.5.dist-info/RECORD
@@ -0,0 +1,12 @@
+pydantic_core-2.41.5.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+pydantic_core-2.41.5.dist-info/METADATA,sha256=Ex83HNMObeb0Be1hbVnx5CewzvIq2S18OeUn7UwBhKk,7420
+pydantic_core-2.41.5.dist-info/RECORD,,
+pydantic_core-2.41.5.dist-info/WHEEL,sha256=n8ZdhGDUio-M1d1jdBhS3kD6MKEN1SRxo8BOjWwZdsg,96
+pydantic_core-2.41.5.dist-info/licenses/LICENSE,sha256=--f2FfGNE1wHAA5ahjJdsn9Cx3KWme8WasH3o_RYa_Q,1101
+pydantic_core/__init__.py,sha256=5kQVCp6sQ3LE_4Jsj2FN8oilYeOSUOlsWORH8XgGxr8,5286
+pydantic_core/__pycache__/__init__.cpython-312.pyc,,
+pydantic_core/__pycache__/core_schema.cpython-312.pyc,,
+pydantic_core/_pydantic_core.cp312-win_amd64.pyd,sha256=8RVtUmeKamoYJxhbwNSE-4sjYG8FOnIc7zbGLJm522s,5436928
+pydantic_core/_pydantic_core.pyi,sha256=9MaxWCkerllI7ar2Spz_0LSGSZJcmcGqC02rU-9Mdl4,45973
+pydantic_core/core_schema.py,sha256=k4n4J4QNy8uFumsUTXwzR5KbPh7EyLzWGX0x7pRdzxk,159165
+pydantic_core/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pydantic_core-2.41.5.dist-info/WHEEL b/TTS/Kokoro/.venv/Lib/site-packages/pydantic_core-2.41.5.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..956a98b44d48298edb69a7c933f83a12c1961e58
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pydantic_core-2.41.5.dist-info/WHEEL
@@ -0,0 +1,4 @@
+Wheel-Version: 1.0
+Generator: maturin (1.9.6)
+Root-Is-Purelib: false
+Tag: cp312-cp312-win_amd64
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pydantic_core/__init__.py b/TTS/Kokoro/.venv/Lib/site-packages/pydantic_core/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3317cdd7a419074136a565d3f116755c32bb258f
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pydantic_core/__init__.py
@@ -0,0 +1,171 @@
+from __future__ import annotations
+
+import sys as _sys
+from typing import Any as _Any
+
+from typing_extensions import Sentinel
+
+from ._pydantic_core import (
+    ArgsKwargs,
+    MultiHostUrl,
+    PydanticCustomError,
+    PydanticKnownError,
+    PydanticOmit,
+    PydanticSerializationError,
+    PydanticSerializationUnexpectedValue,
+    PydanticUndefined,
+    PydanticUndefinedType,
+    PydanticUseDefault,
+    SchemaError,
+    SchemaSerializer,
+    SchemaValidator,
+    Some,
+    TzInfo,
+    Url,
+    ValidationError,
+    __version__,
+    from_json,
+    to_json,
+    to_jsonable_python,
+)
+from .core_schema import CoreConfig, CoreSchema, CoreSchemaType, ErrorType
+
+if _sys.version_info < (3, 11):
+    from typing_extensions import NotRequired as _NotRequired
+else:
+    from typing import NotRequired as _NotRequired
+
+if _sys.version_info < (3, 12):
+    from typing_extensions import TypedDict as _TypedDict
+else:
+    from typing import TypedDict as _TypedDict
+
+__all__ = [
+    '__version__',
+    'UNSET',
+    'CoreConfig',
+    'CoreSchema',
+    'CoreSchemaType',
+    'SchemaValidator',
+    'SchemaSerializer',
+    'Some',
+    'Url',
+    'MultiHostUrl',
+    'ArgsKwargs',
+    'PydanticUndefined',
+    'PydanticUndefinedType',
+    'SchemaError',
+    'ErrorDetails',
+    'InitErrorDetails',
+    'ValidationError',
+    'PydanticCustomError',
+    'PydanticKnownError',
+    'PydanticOmit',
+    'PydanticUseDefault',
+    'PydanticSerializationError',
+    'PydanticSerializationUnexpectedValue',
+    'TzInfo',
+    'to_json',
+    'from_json',
+    'to_jsonable_python',
+]
+
+
+class ErrorDetails(_TypedDict):
+    type: str
+    """
+    The type of error that occurred, this is an identifier designed for
+    programmatic use that will change rarely or never.
+
+    `type` is unique for each error message, and can hence be used as an identifier to build custom error messages.
+    """
+    loc: tuple[int | str, ...]
+    """Tuple of strings and ints identifying where in the schema the error occurred."""
+    msg: str
+    """A human readable error message."""
+    input: _Any
+    """The input data at this `loc` that caused the error."""
+    ctx: _NotRequired[dict[str, _Any]]
+    """
+    Values which are required to render the error message, and could hence be useful in rendering custom error messages.
+    Also useful for passing custom error data forward.
+    """
+    url: _NotRequired[str]
+    """
+    The documentation URL giving information about the error. No URL is available if
+    a [`PydanticCustomError`][pydantic_core.PydanticCustomError] is used.
+    """
+
+
+class InitErrorDetails(_TypedDict):
+    type: str | PydanticCustomError
+    """The type of error that occurred, this should be a "slug" identifier that changes rarely or never."""
+    loc: _NotRequired[tuple[int | str, ...]]
+    """Tuple of strings and ints identifying where in the schema the error occurred."""
+    input: _Any
+    """The input data at this `loc` that caused the error."""
+    ctx: _NotRequired[dict[str, _Any]]
+    """
+    Values which are required to render the error message, and could hence be useful in rendering custom error messages.
+    Also useful for passing custom error data forward.
+    """
+
+
+class ErrorTypeInfo(_TypedDict):
+    """
+    Gives information about errors.
+    """
+
+    type: ErrorType
+    """The type of error that occurred, this should be a "slug" identifier that changes rarely or never."""
+    message_template_python: str
+    """String template to render a human readable error message from using context, when the input is Python."""
+    example_message_python: str
+    """Example of a human readable error message, when the input is Python."""
+    message_template_json: _NotRequired[str]
+    """String template to render a human readable error message from using context, when the input is JSON data."""
+    example_message_json: _NotRequired[str]
+    """Example of a human readable error message, when the input is JSON data."""
+    example_context: dict[str, _Any] | None
+    """Example of context values."""
+
+
+class MultiHostHost(_TypedDict):
+    """
+    A host part of a multi-host URL.
+    """
+
+    username: str | None
+    """The username part of this host, or `None`."""
+    password: str | None
+    """The password part of this host, or `None`."""
+    host: str | None
+    """The host part of this host, or `None`."""
+    port: int | None
+    """The port part of this host, or `None`."""
+
+
+MISSING = Sentinel('MISSING')
+"""A singleton indicating a field value was not provided during validation.
+
+This singleton can be used a default value, as an alternative to `None` when it has
+an explicit meaning. During serialization, any field with `MISSING` as a value is excluded
+from the output.
+
+Example:
+    ```python
+    from pydantic import BaseModel
+
+    from pydantic_core import MISSING
+
+
+    class Configuration(BaseModel):
+        timeout: int | None | MISSING = MISSING
+
+
+    # configuration defaults, stored somewhere else:
+    defaults = {'timeout': 200}
+
+    conf = Configuration.model_validate({...})
+    timeout = conf.timeout if timeout.timeout is not MISSING else defaults['timeout']
+"""
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pydantic_core/_pydantic_core.pyi b/TTS/Kokoro/.venv/Lib/site-packages/pydantic_core/_pydantic_core.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..5f8ea7be8aed6a3ad46d0535758b1950da596929
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pydantic_core/_pydantic_core.pyi
@@ -0,0 +1,1046 @@
+import datetime
+from collections.abc import Mapping
+from typing import Any, Callable, Generic, Literal, TypeVar, final
+
+from _typeshed import SupportsAllComparisons
+from typing_extensions import LiteralString, Self, TypeAlias
+
+from pydantic_core import ErrorDetails, ErrorTypeInfo, InitErrorDetails, MultiHostHost
+from pydantic_core.core_schema import CoreConfig, CoreSchema, ErrorType, ExtraBehavior
+
+__all__ = [
+    '__version__',
+    'build_profile',
+    'build_info',
+    '_recursion_limit',
+    'ArgsKwargs',
+    'SchemaValidator',
+    'SchemaSerializer',
+    'Url',
+    'MultiHostUrl',
+    'SchemaError',
+    'ValidationError',
+    'PydanticCustomError',
+    'PydanticKnownError',
+    'PydanticOmit',
+    'PydanticUseDefault',
+    'PydanticSerializationError',
+    'PydanticSerializationUnexpectedValue',
+    'PydanticUndefined',
+    'PydanticUndefinedType',
+    'Some',
+    'to_json',
+    'from_json',
+    'to_jsonable_python',
+    'list_all_errors',
+    'TzInfo',
+]
+__version__: str
+build_profile: str
+build_info: str
+_recursion_limit: int
+
+_T = TypeVar('_T', default=Any, covariant=True)
+
+_StringInput: TypeAlias = 'dict[str, _StringInput]'
+
+@final
+class Some(Generic[_T]):
+    """
+    Similar to Rust's [`Option::Some`](https://doc.rust-lang.org/std/option/enum.Option.html) type, this
+    identifies a value as being present, and provides a way to access it.
+
+    Generally used in a union with `None` to different between "some value which could be None" and no value.
+    """
+
+    __match_args__ = ('value',)
+
+    @property
+    def value(self) -> _T:
+        """
+        Returns the value wrapped by `Some`.
+        """
+    @classmethod
+    def __class_getitem__(cls, item: Any, /) -> type[Self]: ...
+
+@final
+class SchemaValidator:
+    """
+    `SchemaValidator` is the Python wrapper for `pydantic-core`'s Rust validation logic, internally it owns one
+    `CombinedValidator` which may in turn own more `CombinedValidator`s which make up the full schema validator.
+    """
+
+    # note: pyo3 currently supports __new__, but not __init__, though we include __init__ stubs
+    # and docstrings here (and in the following classes) for documentation purposes
+
+    def __init__(self, schema: CoreSchema, config: CoreConfig | None = None) -> None:
+        """Initializes the `SchemaValidator`.
+
+        Arguments:
+            schema: The `CoreSchema` to use for validation.
+            config: Optionally a [`CoreConfig`][pydantic_core.core_schema.CoreConfig] to configure validation.
+        """
+
+    def __new__(cls, schema: CoreSchema, config: CoreConfig | None = None) -> Self: ...
+    @property
+    def title(self) -> str:
+        """
+        The title of the schema, as used in the heading of [`ValidationError.__str__()`][pydantic_core.ValidationError].
+        """
+    def validate_python(
+        self,
+        input: Any,
+        *,
+        strict: bool | None = None,
+        extra: ExtraBehavior | None = None,
+        from_attributes: bool | None = None,
+        context: Any | None = None,
+        self_instance: Any | None = None,
+        allow_partial: bool | Literal['off', 'on', 'trailing-strings'] = False,
+        by_alias: bool | None = None,
+        by_name: bool | None = None,
+    ) -> Any:
+        """
+        Validate a Python object against the schema and return the validated object.
+
+        Arguments:
+            input: The Python object to validate.
+            strict: Whether to validate the object in strict mode.
+                If `None`, the value of [`CoreConfig.strict`][pydantic_core.core_schema.CoreConfig] is used.
+            extra: Whether to ignore, allow, or forbid extra data during model validation.
+                If `None`, the value of [`CoreConfig.extra_fields_behavior`][pydantic_core.core_schema.CoreConfig] is used.
+            from_attributes: Whether to validate objects as inputs to models by extracting attributes.
+                If `None`, the value of [`CoreConfig.from_attributes`][pydantic_core.core_schema.CoreConfig] is used.
+            context: The context to use for validation, this is passed to functional validators as
+                [`info.context`][pydantic_core.core_schema.ValidationInfo.context].
+            self_instance: An instance of a model set attributes on from validation, this is used when running
+                validation from the `__init__` method of a model.
+            allow_partial: Whether to allow partial validation; if `True` errors in the last element of sequences
+                and mappings are ignored.
+                `'trailing-strings'` means any final unfinished JSON string is included in the result.
+            by_alias: Whether to use the field's alias when validating against the provided input data.
+            by_name: Whether to use the field's name when validating against the provided input data.
+
+        Raises:
+            ValidationError: If validation fails.
+            Exception: Other error types maybe raised if internal errors occur.
+
+        Returns:
+            The validated object.
+        """
+    def isinstance_python(
+        self,
+        input: Any,
+        *,
+        strict: bool | None = None,
+        extra: ExtraBehavior | None = None,
+        from_attributes: bool | None = None,
+        context: Any | None = None,
+        self_instance: Any | None = None,
+        by_alias: bool | None = None,
+        by_name: bool | None = None,
+    ) -> bool:
+        """
+        Similar to [`validate_python()`][pydantic_core.SchemaValidator.validate_python] but returns a boolean.
+
+        Arguments match `validate_python()`. This method will not raise `ValidationError`s but will raise internal
+        errors.
+
+        Returns:
+            `True` if validation succeeds, `False` if validation fails.
+        """
+    def validate_json(
+        self,
+        input: str | bytes | bytearray,
+        *,
+        strict: bool | None = None,
+        extra: ExtraBehavior | None = None,
+        context: Any | None = None,
+        self_instance: Any | None = None,
+        allow_partial: bool | Literal['off', 'on', 'trailing-strings'] = False,
+        by_alias: bool | None = None,
+        by_name: bool | None = None,
+    ) -> Any:
+        """
+        Validate JSON data directly against the schema and return the validated Python object.
+
+        This method should be significantly faster than `validate_python(json.loads(json_data))` as it avoids the
+        need to create intermediate Python objects
+
+        It also handles constructing the correct Python type even in strict mode, where
+        `validate_python(json.loads(json_data))` would fail validation.
+
+        Arguments:
+            input: The JSON data to validate.
+            strict: Whether to validate the object in strict mode.
+                If `None`, the value of [`CoreConfig.strict`][pydantic_core.core_schema.CoreConfig] is used.
+            extra: Whether to ignore, allow, or forbid extra data during model validation.
+                If `None`, the value of [`CoreConfig.extra_fields_behavior`][pydantic_core.core_schema.CoreConfig] is used.
+            context: The context to use for validation, this is passed to functional validators as
+                [`info.context`][pydantic_core.core_schema.ValidationInfo.context].
+            self_instance: An instance of a model set attributes on from validation.
+            allow_partial: Whether to allow partial validation; if `True` incomplete JSON will be parsed successfully
+                and errors in the last element of sequences and mappings are ignored.
+                `'trailing-strings'` means any final unfinished JSON string is included in the result.
+            by_alias: Whether to use the field's alias when validating against the provided input data.
+            by_name: Whether to use the field's name when validating against the provided input data.
+
+        Raises:
+            ValidationError: If validation fails or if the JSON data is invalid.
+            Exception: Other error types maybe raised if internal errors occur.
+
+        Returns:
+            The validated Python object.
+        """
+    def validate_strings(
+        self,
+        input: _StringInput,
+        *,
+        strict: bool | None = None,
+        extra: ExtraBehavior | None = None,
+        context: Any | None = None,
+        allow_partial: bool | Literal['off', 'on', 'trailing-strings'] = False,
+        by_alias: bool | None = None,
+        by_name: bool | None = None,
+    ) -> Any:
+        """
+        Validate a string against the schema and return the validated Python object.
+
+        This is similar to `validate_json` but applies to scenarios where the input will be a string but not
+        JSON data, e.g. URL fragments, query parameters, etc.
+
+        Arguments:
+            input: The input as a string, or bytes/bytearray if `strict=False`.
+            strict: Whether to validate the object in strict mode.
+                If `None`, the value of [`CoreConfig.strict`][pydantic_core.core_schema.CoreConfig] is used.
+            extra: Whether to ignore, allow, or forbid extra data during model validation.
+                If `None`, the value of [`CoreConfig.extra_fields_behavior`][pydantic_core.core_schema.CoreConfig] is used.
+            context: The context to use for validation, this is passed to functional validators as
+                [`info.context`][pydantic_core.core_schema.ValidationInfo.context].
+            allow_partial: Whether to allow partial validation; if `True` errors in the last element of sequences
+                and mappings are ignored.
+                `'trailing-strings'` means any final unfinished JSON string is included in the result.
+            by_alias: Whether to use the field's alias when validating against the provided input data.
+            by_name: Whether to use the field's name when validating against the provided input data.
+
+        Raises:
+            ValidationError: If validation fails or if the JSON data is invalid.
+            Exception: Other error types maybe raised if internal errors occur.
+
+        Returns:
+            The validated Python object.
+        """
+    def validate_assignment(
+        self,
+        obj: Any,
+        field_name: str,
+        field_value: Any,
+        *,
+        strict: bool | None = None,
+        extra: ExtraBehavior | None = None,
+        from_attributes: bool | None = None,
+        context: Any | None = None,
+        by_alias: bool | None = None,
+        by_name: bool | None = None,
+    ) -> dict[str, Any] | tuple[dict[str, Any], dict[str, Any] | None, set[str]]:
+        """
+        Validate an assignment to a field on a model.
+
+        Arguments:
+            obj: The model instance being assigned to.
+            field_name: The name of the field to validate assignment for.
+            field_value: The value to assign to the field.
+            strict: Whether to validate the object in strict mode.
+                If `None`, the value of [`CoreConfig.strict`][pydantic_core.core_schema.CoreConfig] is used.
+            extra: Whether to ignore, allow, or forbid extra data during model validation.
+                If `None`, the value of [`CoreConfig.extra_fields_behavior`][pydantic_core.core_schema.CoreConfig] is used.
+            from_attributes: Whether to validate objects as inputs to models by extracting attributes.
+                If `None`, the value of [`CoreConfig.from_attributes`][pydantic_core.core_schema.CoreConfig] is used.
+            context: The context to use for validation, this is passed to functional validators as
+                [`info.context`][pydantic_core.core_schema.ValidationInfo.context].
+            by_alias: Whether to use the field's alias when validating against the provided input data.
+            by_name: Whether to use the field's name when validating against the provided input data.
+
+        Raises:
+            ValidationError: If validation fails.
+            Exception: Other error types maybe raised if internal errors occur.
+
+        Returns:
+            Either the model dict or a tuple of `(model_data, model_extra, fields_set)`
+        """
+    def get_default_value(self, *, strict: bool | None = None, context: Any = None) -> Some | None:
+        """
+        Get the default value for the schema, including running default value validation.
+
+        Arguments:
+            strict: Whether to validate the default value in strict mode.
+                If `None`, the value of [`CoreConfig.strict`][pydantic_core.core_schema.CoreConfig] is used.
+            context: The context to use for validation, this is passed to functional validators as
+                [`info.context`][pydantic_core.core_schema.ValidationInfo.context].
+
+        Raises:
+            ValidationError: If validation fails.
+            Exception: Other error types maybe raised if internal errors occur.
+
+        Returns:
+            `None` if the schema has no default value, otherwise a [`Some`][pydantic_core.Some] containing the default.
+        """
+
+# In reality, `bool` should be replaced by `Literal[True]` but mypy fails to correctly apply bidirectional type inference
+# (e.g. when using `{'a': {'b': True}}`).
+_IncEx: TypeAlias = set[int] | set[str] | Mapping[int, _IncEx | bool] | Mapping[str, _IncEx | bool]
+
+@final
+class SchemaSerializer:
+    """
+    `SchemaSerializer` is the Python wrapper for `pydantic-core`'s Rust serialization logic, internally it owns one
+    `CombinedSerializer` which may in turn own more `CombinedSerializer`s which make up the full schema serializer.
+    """
+
+    def __init__(self, schema: CoreSchema, config: CoreConfig | None = None) -> None:
+        """Initializes the `SchemaSerializer`.
+
+        Arguments:
+            schema: The `CoreSchema` to use for serialization.
+            config: Optionally a [`CoreConfig`][pydantic_core.core_schema.CoreConfig] to to configure serialization.
+        """
+
+    def __new__(cls, schema: CoreSchema, config: CoreConfig | None = None) -> Self: ...
+    def to_python(
+        self,
+        value: Any,
+        *,
+        mode: str | None = None,
+        include: _IncEx | None = None,
+        exclude: _IncEx | None = None,
+        by_alias: bool | None = None,
+        exclude_unset: bool = False,
+        exclude_defaults: bool = False,
+        exclude_none: bool = False,
+        exclude_computed_fields: bool = False,
+        round_trip: bool = False,
+        warnings: bool | Literal['none', 'warn', 'error'] = True,
+        fallback: Callable[[Any], Any] | None = None,
+        serialize_as_any: bool = False,
+        context: Any | None = None,
+    ) -> Any:
+        """
+        Serialize/marshal a Python object to a Python object including transforming and filtering data.
+
+        Arguments:
+            value: The Python object to serialize.
+            mode: The serialization mode to use, either `'python'` or `'json'`, defaults to `'python'`. In JSON mode,
+                all values are converted to JSON compatible types, e.g. `None`, `int`, `float`, `str`, `list`, `dict`.
+            include: A set of fields to include, if `None` all fields are included.
+            exclude: A set of fields to exclude, if `None` no fields are excluded.
+            by_alias: Whether to use the alias names of fields.
+            exclude_unset: Whether to exclude fields that are not set,
+                e.g. are not included in `__pydantic_fields_set__`.
+            exclude_defaults: Whether to exclude fields that are equal to their default value.
+            exclude_none: Whether to exclude fields that have a value of `None`.
+            exclude_computed_fields: Whether to exclude computed fields.
+            round_trip: Whether to enable serialization and validation round-trip support.
+            warnings: How to handle invalid fields. False/"none" ignores them, True/"warn" logs errors,
+                "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
+            fallback: A function to call when an unknown value is encountered,
+                if `None` a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
+            serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
+            context: The context to use for serialization, this is passed to functional serializers as
+                [`info.context`][pydantic_core.core_schema.SerializationInfo.context].
+
+        Raises:
+            PydanticSerializationError: If serialization fails and no `fallback` function is provided.
+
+        Returns:
+            The serialized Python object.
+        """
+    def to_json(
+        self,
+        value: Any,
+        *,
+        indent: int | None = None,
+        ensure_ascii: bool = False,
+        include: _IncEx | None = None,
+        exclude: _IncEx | None = None,
+        by_alias: bool | None = None,
+        exclude_unset: bool = False,
+        exclude_defaults: bool = False,
+        exclude_none: bool = False,
+        exclude_computed_fields: bool = False,
+        round_trip: bool = False,
+        warnings: bool | Literal['none', 'warn', 'error'] = True,
+        fallback: Callable[[Any], Any] | None = None,
+        serialize_as_any: bool = False,
+        context: Any | None = None,
+    ) -> bytes:
+        """
+        Serialize a Python object to JSON including transforming and filtering data.
+
+        Arguments:
+            value: The Python object to serialize.
+            indent: If `None`, the JSON will be compact, otherwise it will be pretty-printed with the indent provided.
+            ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
+                If `False` (the default), these characters will be output as-is.
+            include: A set of fields to include, if `None` all fields are included.
+            exclude: A set of fields to exclude, if `None` no fields are excluded.
+            by_alias: Whether to use the alias names of fields.
+            exclude_unset: Whether to exclude fields that are not set,
+                e.g. are not included in `__pydantic_fields_set__`.
+            exclude_defaults: Whether to exclude fields that are equal to their default value.
+            exclude_none: Whether to exclude fields that have a value of `None`.
+            exclude_computed_fields: Whether to exclude computed fields.
+            round_trip: Whether to enable serialization and validation round-trip support.
+            warnings: How to handle invalid fields. False/"none" ignores them, True/"warn" logs errors,
+                "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
+            fallback: A function to call when an unknown value is encountered,
+                if `None` a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
+            serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
+            context: The context to use for serialization, this is passed to functional serializers as
+                [`info.context`][pydantic_core.core_schema.SerializationInfo.context].
+
+        Raises:
+            PydanticSerializationError: If serialization fails and no `fallback` function is provided.
+
+        Returns:
+           JSON bytes.
+        """
+
+def to_json(
+    value: Any,
+    *,
+    indent: int | None = None,
+    ensure_ascii: bool = False,
+    include: _IncEx | None = None,
+    exclude: _IncEx | None = None,
+    # Note: In Pydantic 2.11, the default value of `by_alias` on `SchemaSerializer` was changed from `True` to `None`,
+    # to be consistent with the Pydantic "dump" methods. However, the default of `True` was kept here for
+    # backwards compatibility. In Pydantic V3, `by_alias` is expected to default to `True` everywhere:
+    by_alias: bool = True,
+    exclude_none: bool = False,
+    round_trip: bool = False,
+    timedelta_mode: Literal['iso8601', 'float'] = 'iso8601',
+    temporal_mode: Literal['iso8601', 'seconds', 'milliseconds'] = 'iso8601',
+    bytes_mode: Literal['utf8', 'base64', 'hex'] = 'utf8',
+    inf_nan_mode: Literal['null', 'constants', 'strings'] = 'constants',
+    serialize_unknown: bool = False,
+    fallback: Callable[[Any], Any] | None = None,
+    serialize_as_any: bool = False,
+    context: Any | None = None,
+) -> bytes:
+    """
+    Serialize a Python object to JSON including transforming and filtering data.
+
+    This is effectively a standalone version of [`SchemaSerializer.to_json`][pydantic_core.SchemaSerializer.to_json].
+
+    Arguments:
+        value: The Python object to serialize.
+        indent: If `None`, the JSON will be compact, otherwise it will be pretty-printed with the indent provided.
+        ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
+            If `False` (the default), these characters will be output as-is.
+        include: A set of fields to include, if `None` all fields are included.
+        exclude: A set of fields to exclude, if `None` no fields are excluded.
+        by_alias: Whether to use the alias names of fields.
+        exclude_none: Whether to exclude fields that have a value of `None`.
+        round_trip: Whether to enable serialization and validation round-trip support.
+        timedelta_mode: How to serialize `timedelta` objects, either `'iso8601'` or `'float'`.
+        temporal_mode: How to serialize datetime-like objects (`datetime`, `date`, `time`), either `'iso8601'`, `'seconds'`, or `'milliseconds'`.
+            `iso8601` returns an ISO 8601 string; `seconds` returns the Unix timestamp in seconds as a float; `milliseconds` returns the Unix timestamp in milliseconds as a float.
+
+        bytes_mode: How to serialize `bytes` objects, either `'utf8'`, `'base64'`, or `'hex'`.
+        inf_nan_mode: How to serialize `Infinity`, `-Infinity` and `NaN` values, either `'null'`, `'constants'`, or `'strings'`.
+        serialize_unknown: Attempt to serialize unknown types, `str(value)` will be used, if that fails
+            `""` will be used.
+        fallback: A function to call when an unknown value is encountered,
+            if `None` a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
+        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
+        context: The context to use for serialization, this is passed to functional serializers as
+            [`info.context`][pydantic_core.core_schema.SerializationInfo.context].
+
+    Raises:
+        PydanticSerializationError: If serialization fails and no `fallback` function is provided.
+
+    Returns:
+       JSON bytes.
+    """
+
+def from_json(
+    data: str | bytes | bytearray,
+    *,
+    allow_inf_nan: bool = True,
+    cache_strings: bool | Literal['all', 'keys', 'none'] = True,
+    allow_partial: bool | Literal['off', 'on', 'trailing-strings'] = False,
+) -> Any:
+    """
+    Deserialize JSON data to a Python object.
+
+    This is effectively a faster version of `json.loads()`, with some extra functionality.
+
+    Arguments:
+        data: The JSON data to deserialize.
+        allow_inf_nan: Whether to allow `Infinity`, `-Infinity` and `NaN` values as `json.loads()` does by default.
+        cache_strings: Whether to cache strings to avoid constructing new Python objects,
+            this should have a significant impact on performance while increasing memory usage slightly,
+            `all/True` means cache all strings, `keys` means cache only dict keys, `none/False` means no caching.
+        allow_partial: Whether to allow partial deserialization, if `True` JSON data is returned if the end of the
+            input is reached before the full object is deserialized, e.g. `["aa", "bb", "c` would return `['aa', 'bb']`.
+            `'trailing-strings'` means any final unfinished JSON string is included in the result.
+
+    Raises:
+        ValueError: If deserialization fails.
+
+    Returns:
+        The deserialized Python object.
+    """
+
+def to_jsonable_python(
+    value: Any,
+    *,
+    include: _IncEx | None = None,
+    exclude: _IncEx | None = None,
+    # Note: In Pydantic 2.11, the default value of `by_alias` on `SchemaSerializer` was changed from `True` to `None`,
+    # to be consistent with the Pydantic "dump" methods. However, the default of `True` was kept here for
+    # backwards compatibility. In Pydantic V3, `by_alias` is expected to default to `True` everywhere:
+    by_alias: bool = True,
+    exclude_none: bool = False,
+    round_trip: bool = False,
+    timedelta_mode: Literal['iso8601', 'float'] = 'iso8601',
+    temporal_mode: Literal['iso8601', 'seconds', 'milliseconds'] = 'iso8601',
+    bytes_mode: Literal['utf8', 'base64', 'hex'] = 'utf8',
+    inf_nan_mode: Literal['null', 'constants', 'strings'] = 'constants',
+    serialize_unknown: bool = False,
+    fallback: Callable[[Any], Any] | None = None,
+    serialize_as_any: bool = False,
+    context: Any | None = None,
+) -> Any:
+    """
+    Serialize/marshal a Python object to a JSON-serializable Python object including transforming and filtering data.
+
+    This is effectively a standalone version of
+    [`SchemaSerializer.to_python(mode='json')`][pydantic_core.SchemaSerializer.to_python].
+
+    Args:
+        value: The Python object to serialize.
+        include: A set of fields to include, if `None` all fields are included.
+        exclude: A set of fields to exclude, if `None` no fields are excluded.
+        by_alias: Whether to use the alias names of fields.
+        exclude_none: Whether to exclude fields that have a value of `None`.
+        round_trip: Whether to enable serialization and validation round-trip support.
+        timedelta_mode: How to serialize `timedelta` objects, either `'iso8601'` or `'float'`.
+        temporal_mode: How to serialize datetime-like objects (`datetime`, `date`, `time`), either `'iso8601'`, `'seconds'`, or `'milliseconds'`.
+            `iso8601` returns an ISO 8601 string; `seconds` returns the Unix timestamp in seconds as a float; `milliseconds` returns the Unix timestamp in milliseconds as a float.
+
+        bytes_mode: How to serialize `bytes` objects, either `'utf8'`, `'base64'`, or `'hex'`.
+        inf_nan_mode: How to serialize `Infinity`, `-Infinity` and `NaN` values, either `'null'`, `'constants'`, or `'strings'`.
+        serialize_unknown: Attempt to serialize unknown types, `str(value)` will be used, if that fails
+            `""` will be used.
+        fallback: A function to call when an unknown value is encountered,
+            if `None` a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
+        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
+        context: The context to use for serialization, this is passed to functional serializers as
+            [`info.context`][pydantic_core.core_schema.SerializationInfo.context].
+
+    Raises:
+        PydanticSerializationError: If serialization fails and no `fallback` function is provided.
+
+    Returns:
+        The serialized Python object.
+    """
+
+class Url(SupportsAllComparisons):
+    """
+    A URL type, internal logic uses the [url rust crate](https://docs.rs/url/latest/url/) originally developed
+    by Mozilla.
+    """
+
+    def __init__(self, url: str) -> None: ...
+    def __new__(cls, url: str) -> Self: ...
+    @property
+    def scheme(self) -> str: ...
+    @property
+    def username(self) -> str | None: ...
+    @property
+    def password(self) -> str | None: ...
+    @property
+    def host(self) -> str | None: ...
+    def unicode_host(self) -> str | None: ...
+    @property
+    def port(self) -> int | None: ...
+    @property
+    def path(self) -> str | None: ...
+    @property
+    def query(self) -> str | None: ...
+    def query_params(self) -> list[tuple[str, str]]: ...
+    @property
+    def fragment(self) -> str | None: ...
+    def unicode_string(self) -> str: ...
+    def __repr__(self) -> str: ...
+    def __str__(self) -> str: ...
+    def __deepcopy__(self, memo: dict) -> str: ...
+    @classmethod
+    def build(
+        cls,
+        *,
+        scheme: str,
+        username: str | None = None,
+        password: str | None = None,
+        host: str,
+        port: int | None = None,
+        path: str | None = None,
+        query: str | None = None,
+        fragment: str | None = None,
+    ) -> Self: ...
+
+class MultiHostUrl(SupportsAllComparisons):
+    """
+    A URL type with support for multiple hosts, as used by some databases for DSNs, e.g. `https://foo.com,bar.com/path`.
+
+    Internal URL logic uses the [url rust crate](https://docs.rs/url/latest/url/) originally developed
+    by Mozilla.
+    """
+
+    def __init__(self, url: str) -> None: ...
+    def __new__(cls, url: str) -> Self: ...
+    @property
+    def scheme(self) -> str: ...
+    @property
+    def path(self) -> str | None: ...
+    @property
+    def query(self) -> str | None: ...
+    def query_params(self) -> list[tuple[str, str]]: ...
+    @property
+    def fragment(self) -> str | None: ...
+    def hosts(self) -> list[MultiHostHost]: ...
+    def unicode_string(self) -> str: ...
+    def __repr__(self) -> str: ...
+    def __str__(self) -> str: ...
+    def __deepcopy__(self, memo: dict) -> Self: ...
+    @classmethod
+    def build(
+        cls,
+        *,
+        scheme: str,
+        hosts: list[MultiHostHost] | None = None,
+        username: str | None = None,
+        password: str | None = None,
+        host: str | None = None,
+        port: int | None = None,
+        path: str | None = None,
+        query: str | None = None,
+        fragment: str | None = None,
+    ) -> Self: ...
+
+@final
+class SchemaError(Exception):
+    """
+    Information about errors that occur while building a [`SchemaValidator`][pydantic_core.SchemaValidator]
+    or [`SchemaSerializer`][pydantic_core.SchemaSerializer].
+    """
+
+    def error_count(self) -> int:
+        """
+        Returns:
+            The number of errors in the schema.
+        """
+    def errors(self) -> list[ErrorDetails]:
+        """
+        Returns:
+            A list of [`ErrorDetails`][pydantic_core.ErrorDetails] for each error in the schema.
+        """
+
+class ValidationError(ValueError):
+    """
+    `ValidationError` is the exception raised by `pydantic-core` when validation fails, it contains a list of errors
+    which detail why validation failed.
+    """
+    @classmethod
+    def from_exception_data(
+        cls,
+        title: str,
+        line_errors: list[InitErrorDetails],
+        input_type: Literal['python', 'json'] = 'python',
+        hide_input: bool = False,
+    ) -> Self:
+        """
+        Python constructor for a Validation Error.
+
+        Arguments:
+            title: The title of the error, as used in the heading of `str(validation_error)`
+            line_errors: A list of [`InitErrorDetails`][pydantic_core.InitErrorDetails] which contain information
+                about errors that occurred during validation.
+            input_type: Whether the error is for a Python object or JSON.
+            hide_input: Whether to hide the input value in the error message.
+        """
+    @property
+    def title(self) -> str:
+        """
+        The title of the error, as used in the heading of `str(validation_error)`.
+        """
+    def error_count(self) -> int:
+        """
+        Returns:
+            The number of errors in the validation error.
+        """
+    def errors(
+        self, *, include_url: bool = True, include_context: bool = True, include_input: bool = True
+    ) -> list[ErrorDetails]:
+        """
+        Details about each error in the validation error.
+
+        Args:
+            include_url: Whether to include a URL to documentation on the error each error.
+            include_context: Whether to include the context of each error.
+            include_input: Whether to include the input value of each error.
+
+        Returns:
+            A list of [`ErrorDetails`][pydantic_core.ErrorDetails] for each error in the validation error.
+        """
+    def json(
+        self,
+        *,
+        indent: int | None = None,
+        include_url: bool = True,
+        include_context: bool = True,
+        include_input: bool = True,
+    ) -> str:
+        """
+        Same as [`errors()`][pydantic_core.ValidationError.errors] but returns a JSON string.
+
+        Args:
+            indent: The number of spaces to indent the JSON by, or `None` for no indentation - compact JSON.
+            include_url: Whether to include a URL to documentation on the error each error.
+            include_context: Whether to include the context of each error.
+            include_input: Whether to include the input value of each error.
+
+        Returns:
+            a JSON string.
+        """
+
+    def __repr__(self) -> str:
+        """
+        A string representation of the validation error.
+
+        Whether or not documentation URLs are included in the repr is controlled by the
+        environment variable `PYDANTIC_ERRORS_INCLUDE_URL` being set to `1` or
+        `true`; by default, URLs are shown.
+
+        Due to implementation details, this environment variable can only be set once,
+        before the first validation error is created.
+        """
+
+class PydanticCustomError(ValueError):
+    """A custom exception providing flexible error handling for Pydantic validators.
+
+    You can raise this error in custom validators when you'd like flexibility in regards to the error type, message, and context.
+
+    Example:
+        ```py
+        from pydantic_core import PydanticCustomError
+
+        def custom_validator(v) -> None:
+            if v <= 10:
+                raise PydanticCustomError('custom_value_error', 'Value must be greater than {value}', {'value': 10, 'extra_context': 'extra_data'})
+            return v
+        ```
+
+    Arguments:
+        error_type: The error type.
+        message_template: The message template.
+        context: The data to inject into the message template.
+    """
+
+    def __init__(
+        self, error_type: LiteralString, message_template: LiteralString, context: dict[str, Any] | None = None, /
+    ) -> None: ...
+    @property
+    def context(self) -> dict[str, Any] | None:
+        """Values which are required to render the error message, and could hence be useful in passing error data forward."""
+
+    @property
+    def type(self) -> str:
+        """The error type associated with the error. For consistency with Pydantic, this is typically a snake_case string."""
+
+    @property
+    def message_template(self) -> str:
+        """The message template associated with the error. This is a string that can be formatted with context variables in `{curly_braces}`."""
+
+    def message(self) -> str:
+        """The formatted message associated with the error. This presents as the message template with context variables appropriately injected."""
+
+@final
+class PydanticKnownError(ValueError):
+    """A helper class for raising exceptions that mimic Pydantic's built-in exceptions, with more flexibility in regards to context.
+
+    Unlike [`PydanticCustomError`][pydantic_core.PydanticCustomError], the `error_type` argument must be a known `ErrorType`.
+
+    Example:
+        ```py
+        from pydantic_core import PydanticKnownError
+
+        def custom_validator(v) -> None:
+            if v <= 10:
+                raise PydanticKnownError('greater_than', {'gt': 10})
+            return v
+        ```
+
+    Arguments:
+        error_type: The error type.
+        context: The data to inject into the message template.
+    """
+
+    def __init__(self, error_type: ErrorType, context: dict[str, Any] | None = None, /) -> None: ...
+    @property
+    def context(self) -> dict[str, Any] | None:
+        """Values which are required to render the error message, and could hence be useful in passing error data forward."""
+
+    @property
+    def type(self) -> ErrorType:
+        """The type of the error."""
+
+    @property
+    def message_template(self) -> str:
+        """The message template associated with the provided error type. This is a string that can be formatted with context variables in `{curly_braces}`."""
+
+    def message(self) -> str:
+        """The formatted message associated with the error. This presents as the message template with context variables appropriately injected."""
+
+@final
+class PydanticOmit(Exception):
+    """An exception to signal that a field should be omitted from a generated result.
+
+    This could span from omitting a field from a JSON Schema to omitting a field from a serialized result.
+    Upcoming: more robust support for using PydanticOmit in custom serializers is still in development.
+    Right now, this is primarily used in the JSON Schema generation process.
+
+    Example:
+        ```py
+        from typing import Callable
+
+        from pydantic_core import PydanticOmit
+
+        from pydantic import BaseModel
+        from pydantic.json_schema import GenerateJsonSchema, JsonSchemaValue
+
+
+        class MyGenerateJsonSchema(GenerateJsonSchema):
+            def handle_invalid_for_json_schema(self, schema, error_info) -> JsonSchemaValue:
+                raise PydanticOmit
+
+
+        class Predicate(BaseModel):
+            name: str = 'no-op'
+            func: Callable = lambda x: x
+
+
+        instance_example = Predicate()
+
+        validation_schema = instance_example.model_json_schema(schema_generator=MyGenerateJsonSchema, mode='validation')
+        print(validation_schema)
+        '''
+        {'properties': {'name': {'default': 'no-op', 'title': 'Name', 'type': 'string'}}, 'title': 'Predicate', 'type': 'object'}
+        '''
+        ```
+
+    For a more in depth example / explanation, see the [customizing JSON schema](../concepts/json_schema.md#customizing-the-json-schema-generation-process) docs.
+    """
+
+    def __new__(cls) -> Self: ...
+
+@final
+class PydanticUseDefault(Exception):
+    """An exception to signal that standard validation either failed or should be skipped, and the default value should be used instead.
+
+    This warning can be raised in custom valiation functions to redirect the flow of validation.
+
+    Example:
+        ```py
+        from pydantic_core import PydanticUseDefault
+        from datetime import datetime
+        from pydantic import BaseModel, field_validator
+
+
+        class Event(BaseModel):
+            name: str = 'meeting'
+            time: datetime
+
+            @field_validator('name', mode='plain')
+            def name_must_be_present(cls, v) -> str:
+                if not v or not isinstance(v, str):
+                    raise PydanticUseDefault()
+                return v
+
+
+        event1 = Event(name='party', time=datetime(2024, 1, 1, 12, 0, 0))
+        print(repr(event1))
+        # > Event(name='party', time=datetime.datetime(2024, 1, 1, 12, 0))
+        event2 = Event(time=datetime(2024, 1, 1, 12, 0, 0))
+        print(repr(event2))
+        # > Event(name='meeting', time=datetime.datetime(2024, 1, 1, 12, 0))
+        ```
+
+    For an additional example, see the [validating partial json data](../concepts/json.md#partial-json-parsing) section of the Pydantic documentation.
+    """
+
+    def __new__(cls) -> Self: ...
+
+@final
+class PydanticSerializationError(ValueError):
+    """An error raised when an issue occurs during serialization.
+
+    In custom serializers, this error can be used to indicate that serialization has failed.
+
+    Arguments:
+        message: The message associated with the error.
+    """
+
+    def __init__(self, message: str, /) -> None: ...
+
+@final
+class PydanticSerializationUnexpectedValue(ValueError):
+    """An error raised when an unexpected value is encountered during serialization.
+
+    This error is often caught and coerced into a warning, as `pydantic-core` generally makes a best attempt
+    at serializing values, in contrast with validation where errors are eagerly raised.
+
+    Example:
+        ```py
+        from pydantic import BaseModel, field_serializer
+        from pydantic_core import PydanticSerializationUnexpectedValue
+
+        class BasicPoint(BaseModel):
+            x: int
+            y: int
+
+            @field_serializer('*')
+            def serialize(self, v):
+                if not isinstance(v, int):
+                    raise PydanticSerializationUnexpectedValue(f'Expected type `int`, got {type(v)} with value {v}')
+                return v
+
+        point = BasicPoint(x=1, y=2)
+        # some sort of mutation
+        point.x = 'a'
+
+        print(point.model_dump())
+        '''
+        UserWarning: Pydantic serializer warnings:
+        PydanticSerializationUnexpectedValue(Expected type `int`, got  with value a)
+        return self.__pydantic_serializer__.to_python(
+        {'x': 'a', 'y': 2}
+        '''
+        ```
+
+    This is often used internally in `pydantic-core` when unexpected types are encountered during serialization,
+    but it can also be used by users in custom serializers, as seen above.
+
+    Arguments:
+        message: The message associated with the unexpected value.
+    """
+
+    def __init__(self, message: str, /) -> None: ...
+
+@final
+class ArgsKwargs:
+    """A construct used to store arguments and keyword arguments for a function call.
+
+    This data structure is generally used to store information for core schemas associated with functions (like in an arguments schema).
+    This data structure is also currently used for some validation against dataclasses.
+
+    Example:
+        ```py
+        from pydantic.dataclasses import dataclass
+        from pydantic import model_validator
+
+
+        @dataclass
+        class Model:
+            a: int
+            b: int
+
+            @model_validator(mode="before")
+            @classmethod
+            def no_op_validator(cls, values):
+                print(values)
+                return values
+
+        Model(1, b=2)
+        #> ArgsKwargs((1,), {"b": 2})
+
+        Model(1, 2)
+        #> ArgsKwargs((1, 2), {})
+
+        Model(a=1, b=2)
+        #> ArgsKwargs((), {"a": 1, "b": 2})
+        ```
+    """
+
+    def __init__(self, args: tuple[Any, ...], kwargs: dict[str, Any] | None = None) -> None:
+        """Initializes the `ArgsKwargs`.
+
+        Arguments:
+            args: The arguments (inherently ordered) for a function call.
+            kwargs: The keyword arguments for a function call
+        """
+
+    def __new__(cls, args: tuple[Any, ...], kwargs: dict[str, Any] | None = None) -> Self: ...
+    @property
+    def args(self) -> tuple[Any, ...]:
+        """The arguments (inherently ordered) for a function call."""
+
+    @property
+    def kwargs(self) -> dict[str, Any] | None:
+        """The keyword arguments for a function call."""
+
+@final
+class PydanticUndefinedType:
+    """A type used as a sentinel for undefined values."""
+
+    def __copy__(self) -> Self: ...
+    def __deepcopy__(self, memo: Any) -> Self: ...
+
+PydanticUndefined: PydanticUndefinedType
+
+def list_all_errors() -> list[ErrorTypeInfo]:
+    """
+    Get information about all built-in errors.
+
+    Returns:
+        A list of `ErrorTypeInfo` typed dicts.
+    """
+@final
+class TzInfo(datetime.tzinfo):
+    """An `pydantic-core` implementation of the abstract [`datetime.tzinfo`][] class."""
+
+    def __init__(self, seconds: float = 0.0) -> None:
+        """Initializes the `TzInfo`.
+
+        Arguments:
+            seconds: The offset from UTC in seconds. Defaults to 0.0 (UTC).
+        """
+
+    def __new__(cls, seconds: float = 0.0) -> Self: ...
+
+    # Docstrings for attributes sourced from the abstract base class, [`datetime.tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.tzinfo).
+
+    def tzname(self, dt: datetime.datetime | None) -> str | None:
+        """Return the time zone name corresponding to the [`datetime`][datetime.datetime] object _dt_, as a string.
+
+        For more info, see [`tzinfo.tzname`][datetime.tzinfo.tzname].
+        """
+
+    def utcoffset(self, dt: datetime.datetime | None) -> datetime.timedelta | None:
+        """Return offset of local time from UTC, as a [`timedelta`][datetime.timedelta] object that is positive east of UTC. If local time is west of UTC, this should be negative.
+
+        More info can be found at [`tzinfo.utcoffset`][datetime.tzinfo.utcoffset].
+        """
+
+    def dst(self, dt: datetime.datetime | None) -> datetime.timedelta | None:
+        """Return the daylight saving time (DST) adjustment, as a [`timedelta`][datetime.timedelta] object or `None` if DST information isn’t known.
+
+        More info can be found at[`tzinfo.dst`][datetime.tzinfo.dst]."""
+
+    def fromutc(self, dt: datetime.datetime) -> datetime.datetime:
+        """Adjust the date and time data associated datetime object _dt_, returning an equivalent datetime in self’s local time.
+
+        More info can be found at [`tzinfo.fromutc`][datetime.tzinfo.fromutc]."""
+
+    def __deepcopy__(self, _memo: dict[Any, Any]) -> TzInfo: ...
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pydantic_core/core_schema.py b/TTS/Kokoro/.venv/Lib/site-packages/pydantic_core/core_schema.py
new file mode 100644
index 0000000000000000000000000000000000000000..ddbe7dbdbb10296e2c900aecbcdb6346d6ba2206
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pydantic_core/core_schema.py
@@ -0,0 +1,4435 @@
+"""
+This module contains definitions to build schemas which `pydantic_core` can
+validate and serialize.
+"""
+
+from __future__ import annotations as _annotations
+
+import sys
+import warnings
+from collections.abc import Hashable, Mapping
+from datetime import date, datetime, time, timedelta
+from decimal import Decimal
+from re import Pattern
+from typing import TYPE_CHECKING, Any, Callable, Literal, Union
+
+from typing_extensions import TypeVar, deprecated
+
+if sys.version_info < (3, 12):
+    from typing_extensions import TypedDict
+else:
+    from typing import TypedDict
+
+if sys.version_info < (3, 11):
+    from typing_extensions import Protocol, Required, TypeAlias
+else:
+    from typing import Protocol, Required, TypeAlias
+
+if TYPE_CHECKING:
+    from pydantic_core import PydanticUndefined
+else:
+    # The initial build of pydantic_core requires PydanticUndefined to generate
+    # the core schema; so we need to conditionally skip it. mypy doesn't like
+    # this at all, hence the TYPE_CHECKING branch above.
+    try:
+        from pydantic_core import PydanticUndefined
+    except ImportError:
+        PydanticUndefined = object()
+
+
+ExtraBehavior = Literal['allow', 'forbid', 'ignore']
+
+
+class CoreConfig(TypedDict, total=False):
+    """
+    Base class for schema configuration options.
+
+    Attributes:
+        title: The name of the configuration.
+        strict: Whether the configuration should strictly adhere to specified rules.
+        extra_fields_behavior: The behavior for handling extra fields.
+        typed_dict_total: Whether the TypedDict should be considered total. Default is `True`.
+        from_attributes: Whether to use attributes for models, dataclasses, and tagged union keys.
+        loc_by_alias: Whether to use the used alias (or first alias for "field required" errors) instead of
+            `field_names` to construct error `loc`s. Default is `True`.
+        revalidate_instances: Whether instances of models and dataclasses should re-validate. Default is 'never'.
+        validate_default: Whether to validate default values during validation. Default is `False`.
+        str_max_length: The maximum length for string fields.
+        str_min_length: The minimum length for string fields.
+        str_strip_whitespace: Whether to strip whitespace from string fields.
+        str_to_lower: Whether to convert string fields to lowercase.
+        str_to_upper: Whether to convert string fields to uppercase.
+        allow_inf_nan: Whether to allow infinity and NaN values for float fields. Default is `True`.
+        ser_json_timedelta: The serialization option for `timedelta` values. Default is 'iso8601'.
+            Note that if ser_json_temporal is set, then this param will be ignored.
+        ser_json_temporal: The serialization option for datetime like values. Default is 'iso8601'.
+            The types this covers are datetime, date, time and timedelta.
+            If this is set, it will take precedence over ser_json_timedelta
+        ser_json_bytes: The serialization option for `bytes` values. Default is 'utf8'.
+        ser_json_inf_nan: The serialization option for infinity and NaN values
+            in float fields. Default is 'null'.
+        val_json_bytes: The validation option for `bytes` values, complementing ser_json_bytes. Default is 'utf8'.
+        hide_input_in_errors: Whether to hide input data from `ValidationError` representation.
+        validation_error_cause: Whether to add user-python excs to the __cause__ of a ValidationError.
+            Requires exceptiongroup backport pre Python 3.11.
+        coerce_numbers_to_str: Whether to enable coercion of any `Number` type to `str` (not applicable in `strict` mode).
+        regex_engine: The regex engine to use for regex pattern validation. Default is 'rust-regex'. See `StringSchema`.
+        cache_strings: Whether to cache strings. Default is `True`, `True` or `'all'` is required to cache strings
+            during general validation since validators don't know if they're in a key or a value.
+        validate_by_alias: Whether to use the field's alias when validating against the provided input data. Default is `True`.
+        validate_by_name: Whether to use the field's name when validating against the provided input data. Default is `False`. Replacement for `populate_by_name`.
+        serialize_by_alias: Whether to serialize by alias. Default is `False`, expected to change to `True` in V3.
+        url_preserve_empty_path: Whether to preserve empty URL paths when validating values for a URL type. Defaults to `False`.
+    """
+
+    title: str
+    strict: bool
+    # settings related to typed dicts, model fields, dataclass fields
+    extra_fields_behavior: ExtraBehavior
+    typed_dict_total: bool  # default: True
+    # used for models, dataclasses, and tagged union keys
+    from_attributes: bool
+    # whether to use the used alias (or first alias for "field required" errors) instead of field_names
+    # to construct error `loc`s, default True
+    loc_by_alias: bool
+    # whether instances of models and dataclasses (including subclass instances) should re-validate, default 'never'
+    revalidate_instances: Literal['always', 'never', 'subclass-instances']
+    # whether to validate default values during validation, default False
+    validate_default: bool
+    # used on typed-dicts and arguments
+    # fields related to string fields only
+    str_max_length: int
+    str_min_length: int
+    str_strip_whitespace: bool
+    str_to_lower: bool
+    str_to_upper: bool
+    # fields related to float fields only
+    allow_inf_nan: bool  # default: True
+    # the config options are used to customise serialization to JSON
+    ser_json_timedelta: Literal['iso8601', 'float']  # default: 'iso8601'
+    ser_json_temporal: Literal['iso8601', 'seconds', 'milliseconds']  # default: 'iso8601'
+    ser_json_bytes: Literal['utf8', 'base64', 'hex']  # default: 'utf8'
+    ser_json_inf_nan: Literal['null', 'constants', 'strings']  # default: 'null'
+    val_json_bytes: Literal['utf8', 'base64', 'hex']  # default: 'utf8'
+    # used to hide input data from ValidationError repr
+    hide_input_in_errors: bool
+    validation_error_cause: bool  # default: False
+    coerce_numbers_to_str: bool  # default: False
+    regex_engine: Literal['rust-regex', 'python-re']  # default: 'rust-regex'
+    cache_strings: Union[bool, Literal['all', 'keys', 'none']]  # default: 'True'
+    validate_by_alias: bool  # default: True
+    validate_by_name: bool  # default: False
+    serialize_by_alias: bool  # default: False
+    url_preserve_empty_path: bool  # default: False
+
+
+IncExCall: TypeAlias = 'set[int | str] | dict[int | str, IncExCall] | None'
+
+ContextT = TypeVar('ContextT', covariant=True, default='Any | None')
+
+
+class SerializationInfo(Protocol[ContextT]):
+    """Extra data used during serialization."""
+
+    @property
+    def include(self) -> IncExCall:
+        """The `include` argument set during serialization."""
+        ...
+
+    @property
+    def exclude(self) -> IncExCall:
+        """The `exclude` argument set during serialization."""
+        ...
+
+    @property
+    def context(self) -> ContextT:
+        """The current serialization context."""
+        ...
+
+    @property
+    def mode(self) -> Literal['python', 'json'] | str:
+        """The serialization mode set during serialization."""
+        ...
+
+    @property
+    def by_alias(self) -> bool:
+        """The `by_alias` argument set during serialization."""
+        ...
+
+    @property
+    def exclude_unset(self) -> bool:
+        """The `exclude_unset` argument set during serialization."""
+        ...
+
+    @property
+    def exclude_defaults(self) -> bool:
+        """The `exclude_defaults` argument set during serialization."""
+        ...
+
+    @property
+    def exclude_none(self) -> bool:
+        """The `exclude_none` argument set during serialization."""
+        ...
+
+    @property
+    def exclude_computed_fields(self) -> bool:
+        """The `exclude_computed_fields` argument set during serialization."""
+        ...
+
+    @property
+    def serialize_as_any(self) -> bool:
+        """The `serialize_as_any` argument set during serialization."""
+        ...
+
+    @property
+    def round_trip(self) -> bool:
+        """The `round_trip` argument set during serialization."""
+        ...
+
+    def mode_is_json(self) -> bool: ...
+
+    def __str__(self) -> str: ...
+
+    def __repr__(self) -> str: ...
+
+
+class FieldSerializationInfo(SerializationInfo[ContextT], Protocol):
+    """Extra data used during field serialization."""
+
+    @property
+    def field_name(self) -> str:
+        """The name of the current field being serialized."""
+        ...
+
+
+class ValidationInfo(Protocol[ContextT]):
+    """Extra data used during validation."""
+
+    @property
+    def context(self) -> ContextT:
+        """The current validation context."""
+        ...
+
+    @property
+    def config(self) -> CoreConfig | None:
+        """The CoreConfig that applies to this validation."""
+        ...
+
+    @property
+    def mode(self) -> Literal['python', 'json']:
+        """The type of input data we are currently validating."""
+        ...
+
+    @property
+    def data(self) -> dict[str, Any]:
+        """The data being validated for this model."""
+        ...
+
+    @property
+    def field_name(self) -> str | None:
+        """
+        The name of the current field being validated if this validator is
+        attached to a model field.
+        """
+        ...
+
+
+ExpectedSerializationTypes = Literal[
+    'none',
+    'int',
+    'bool',
+    'float',
+    'str',
+    'bytes',
+    'bytearray',
+    'list',
+    'tuple',
+    'set',
+    'frozenset',
+    'generator',
+    'dict',
+    'datetime',
+    'date',
+    'time',
+    'timedelta',
+    'url',
+    'multi-host-url',
+    'json',
+    'uuid',
+    'any',
+]
+
+
+class SimpleSerSchema(TypedDict, total=False):
+    type: Required[ExpectedSerializationTypes]
+
+
+def simple_ser_schema(type: ExpectedSerializationTypes) -> SimpleSerSchema:
+    """
+    Returns a schema for serialization with a custom type.
+
+    Args:
+        type: The type to use for serialization
+    """
+    return SimpleSerSchema(type=type)
+
+
+# (input_value: Any, /) -> Any
+GeneralPlainNoInfoSerializerFunction = Callable[[Any], Any]
+# (input_value: Any, info: FieldSerializationInfo, /) -> Any
+GeneralPlainInfoSerializerFunction = Callable[[Any, SerializationInfo[Any]], Any]
+# (model: Any, input_value: Any, /) -> Any
+FieldPlainNoInfoSerializerFunction = Callable[[Any, Any], Any]
+# (model: Any, input_value: Any, info: FieldSerializationInfo, /) -> Any
+FieldPlainInfoSerializerFunction = Callable[[Any, Any, FieldSerializationInfo[Any]], Any]
+SerializerFunction = Union[
+    GeneralPlainNoInfoSerializerFunction,
+    GeneralPlainInfoSerializerFunction,
+    FieldPlainNoInfoSerializerFunction,
+    FieldPlainInfoSerializerFunction,
+]
+
+WhenUsed = Literal['always', 'unless-none', 'json', 'json-unless-none']
+"""
+Values have the following meanings:
+
+* `'always'` means always use
+* `'unless-none'` means use unless the value is `None`
+* `'json'` means use when serializing to JSON
+* `'json-unless-none'` means use when serializing to JSON and the value is not `None`
+"""
+
+
+class PlainSerializerFunctionSerSchema(TypedDict, total=False):
+    type: Required[Literal['function-plain']]
+    function: Required[SerializerFunction]
+    is_field_serializer: bool  # default False
+    info_arg: bool  # default False
+    return_schema: CoreSchema  # if omitted, AnySchema is used
+    when_used: WhenUsed  # default: 'always'
+
+
+def plain_serializer_function_ser_schema(
+    function: SerializerFunction,
+    *,
+    is_field_serializer: bool | None = None,
+    info_arg: bool | None = None,
+    return_schema: CoreSchema | None = None,
+    when_used: WhenUsed = 'always',
+) -> PlainSerializerFunctionSerSchema:
+    """
+    Returns a schema for serialization with a function, can be either a "general" or "field" function.
+
+    Args:
+        function: The function to use for serialization
+        is_field_serializer: Whether the serializer is for a field, e.g. takes `model` as the first argument,
+            and `info` includes `field_name`
+        info_arg: Whether the function takes an `info` argument
+        return_schema: Schema to use for serializing return value
+        when_used: When the function should be called
+    """
+    if when_used == 'always':
+        # just to avoid extra elements in schema, and to use the actual default defined in rust
+        when_used = None  # type: ignore
+    return _dict_not_none(
+        type='function-plain',
+        function=function,
+        is_field_serializer=is_field_serializer,
+        info_arg=info_arg,
+        return_schema=return_schema,
+        when_used=when_used,
+    )
+
+
+class SerializerFunctionWrapHandler(Protocol):  # pragma: no cover
+    def __call__(self, input_value: Any, index_key: int | str | None = None, /) -> Any: ...
+
+
+# (input_value: Any, serializer: SerializerFunctionWrapHandler, /) -> Any
+GeneralWrapNoInfoSerializerFunction = Callable[[Any, SerializerFunctionWrapHandler], Any]
+# (input_value: Any, serializer: SerializerFunctionWrapHandler, info: SerializationInfo, /) -> Any
+GeneralWrapInfoSerializerFunction = Callable[[Any, SerializerFunctionWrapHandler, SerializationInfo[Any]], Any]
+# (model: Any, input_value: Any, serializer: SerializerFunctionWrapHandler, /) -> Any
+FieldWrapNoInfoSerializerFunction = Callable[[Any, Any, SerializerFunctionWrapHandler], Any]
+# (model: Any, input_value: Any, serializer: SerializerFunctionWrapHandler, info: FieldSerializationInfo, /) -> Any
+FieldWrapInfoSerializerFunction = Callable[[Any, Any, SerializerFunctionWrapHandler, FieldSerializationInfo[Any]], Any]
+WrapSerializerFunction = Union[
+    GeneralWrapNoInfoSerializerFunction,
+    GeneralWrapInfoSerializerFunction,
+    FieldWrapNoInfoSerializerFunction,
+    FieldWrapInfoSerializerFunction,
+]
+
+
+class WrapSerializerFunctionSerSchema(TypedDict, total=False):
+    type: Required[Literal['function-wrap']]
+    function: Required[WrapSerializerFunction]
+    is_field_serializer: bool  # default False
+    info_arg: bool  # default False
+    schema: CoreSchema  # if omitted, the schema on which this serializer is defined is used
+    return_schema: CoreSchema  # if omitted, AnySchema is used
+    when_used: WhenUsed  # default: 'always'
+
+
+def wrap_serializer_function_ser_schema(
+    function: WrapSerializerFunction,
+    *,
+    is_field_serializer: bool | None = None,
+    info_arg: bool | None = None,
+    schema: CoreSchema | None = None,
+    return_schema: CoreSchema | None = None,
+    when_used: WhenUsed = 'always',
+) -> WrapSerializerFunctionSerSchema:
+    """
+    Returns a schema for serialization with a wrap function, can be either a "general" or "field" function.
+
+    Args:
+        function: The function to use for serialization
+        is_field_serializer: Whether the serializer is for a field, e.g. takes `model` as the first argument,
+            and `info` includes `field_name`
+        info_arg: Whether the function takes an `info` argument
+        schema: The schema to use for the inner serialization
+        return_schema: Schema to use for serializing return value
+        when_used: When the function should be called
+    """
+    if when_used == 'always':
+        # just to avoid extra elements in schema, and to use the actual default defined in rust
+        when_used = None  # type: ignore
+    return _dict_not_none(
+        type='function-wrap',
+        function=function,
+        is_field_serializer=is_field_serializer,
+        info_arg=info_arg,
+        schema=schema,
+        return_schema=return_schema,
+        when_used=when_used,
+    )
+
+
+class FormatSerSchema(TypedDict, total=False):
+    type: Required[Literal['format']]
+    formatting_string: Required[str]
+    when_used: WhenUsed  # default: 'json-unless-none'
+
+
+def format_ser_schema(formatting_string: str, *, when_used: WhenUsed = 'json-unless-none') -> FormatSerSchema:
+    """
+    Returns a schema for serialization using python's `format` method.
+
+    Args:
+        formatting_string: String defining the format to use
+        when_used: Same meaning as for [general_function_plain_ser_schema], but with a different default
+    """
+    if when_used == 'json-unless-none':
+        # just to avoid extra elements in schema, and to use the actual default defined in rust
+        when_used = None  # type: ignore
+    return _dict_not_none(type='format', formatting_string=formatting_string, when_used=when_used)
+
+
+class ToStringSerSchema(TypedDict, total=False):
+    type: Required[Literal['to-string']]
+    when_used: WhenUsed  # default: 'json-unless-none'
+
+
+def to_string_ser_schema(*, when_used: WhenUsed = 'json-unless-none') -> ToStringSerSchema:
+    """
+    Returns a schema for serialization using python's `str()` / `__str__` method.
+
+    Args:
+        when_used: Same meaning as for [general_function_plain_ser_schema], but with a different default
+    """
+    s = dict(type='to-string')
+    if when_used != 'json-unless-none':
+        # just to avoid extra elements in schema, and to use the actual default defined in rust
+        s['when_used'] = when_used
+    return s  # type: ignore
+
+
+class ModelSerSchema(TypedDict, total=False):
+    type: Required[Literal['model']]
+    cls: Required[type[Any]]
+    schema: Required[CoreSchema]
+
+
+def model_ser_schema(cls: type[Any], schema: CoreSchema) -> ModelSerSchema:
+    """
+    Returns a schema for serialization using a model.
+
+    Args:
+        cls: The expected class type, used to generate warnings if the wrong type is passed
+        schema: Internal schema to use to serialize the model dict
+    """
+    return ModelSerSchema(type='model', cls=cls, schema=schema)
+
+
+SerSchema = Union[
+    SimpleSerSchema,
+    PlainSerializerFunctionSerSchema,
+    WrapSerializerFunctionSerSchema,
+    FormatSerSchema,
+    ToStringSerSchema,
+    ModelSerSchema,
+]
+
+
+class InvalidSchema(TypedDict, total=False):
+    type: Required[Literal['invalid']]
+    ref: str
+    metadata: dict[str, Any]
+    # note, we never plan to use this, but include it for type checking purposes to match
+    # all other CoreSchema union members
+    serialization: SerSchema
+
+
+def invalid_schema(ref: str | None = None, metadata: dict[str, Any] | None = None) -> InvalidSchema:
+    """
+    Returns an invalid schema, used to indicate that a schema is invalid.
+
+        Returns a schema that matches any value, e.g.:
+
+    Args:
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+    """
+
+    return _dict_not_none(type='invalid', ref=ref, metadata=metadata)
+
+
+class ComputedField(TypedDict, total=False):
+    type: Required[Literal['computed-field']]
+    property_name: Required[str]
+    return_schema: Required[CoreSchema]
+    alias: str
+    metadata: dict[str, Any]
+
+
+def computed_field(
+    property_name: str, return_schema: CoreSchema, *, alias: str | None = None, metadata: dict[str, Any] | None = None
+) -> ComputedField:
+    """
+    ComputedFields are properties of a model or dataclass that are included in serialization.
+
+    Args:
+        property_name: The name of the property on the model or dataclass
+        return_schema: The schema used for the type returned by the computed field
+        alias: The name to use in the serialized output
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+    """
+    return _dict_not_none(
+        type='computed-field', property_name=property_name, return_schema=return_schema, alias=alias, metadata=metadata
+    )
+
+
+class AnySchema(TypedDict, total=False):
+    type: Required[Literal['any']]
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def any_schema(
+    *, ref: str | None = None, metadata: dict[str, Any] | None = None, serialization: SerSchema | None = None
+) -> AnySchema:
+    """
+    Returns a schema that matches any value, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.any_schema()
+    v = SchemaValidator(schema)
+    assert v.validate_python(1) == 1
+    ```
+
+    Args:
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(type='any', ref=ref, metadata=metadata, serialization=serialization)
+
+
+class NoneSchema(TypedDict, total=False):
+    type: Required[Literal['none']]
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def none_schema(
+    *, ref: str | None = None, metadata: dict[str, Any] | None = None, serialization: SerSchema | None = None
+) -> NoneSchema:
+    """
+    Returns a schema that matches a None value, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.none_schema()
+    v = SchemaValidator(schema)
+    assert v.validate_python(None) is None
+    ```
+
+    Args:
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(type='none', ref=ref, metadata=metadata, serialization=serialization)
+
+
+class BoolSchema(TypedDict, total=False):
+    type: Required[Literal['bool']]
+    strict: bool
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def bool_schema(
+    strict: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> BoolSchema:
+    """
+    Returns a schema that matches a bool value, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.bool_schema()
+    v = SchemaValidator(schema)
+    assert v.validate_python('True') is True
+    ```
+
+    Args:
+        strict: Whether the value should be a bool or a value that can be converted to a bool
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(type='bool', strict=strict, ref=ref, metadata=metadata, serialization=serialization)
+
+
+class IntSchema(TypedDict, total=False):
+    type: Required[Literal['int']]
+    multiple_of: int
+    le: int
+    ge: int
+    lt: int
+    gt: int
+    strict: bool
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def int_schema(
+    *,
+    multiple_of: int | None = None,
+    le: int | None = None,
+    ge: int | None = None,
+    lt: int | None = None,
+    gt: int | None = None,
+    strict: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> IntSchema:
+    """
+    Returns a schema that matches a int value, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.int_schema(multiple_of=2, le=6, ge=2)
+    v = SchemaValidator(schema)
+    assert v.validate_python('4') == 4
+    ```
+
+    Args:
+        multiple_of: The value must be a multiple of this number
+        le: The value must be less than or equal to this number
+        ge: The value must be greater than or equal to this number
+        lt: The value must be strictly less than this number
+        gt: The value must be strictly greater than this number
+        strict: Whether the value should be a int or a value that can be converted to a int
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='int',
+        multiple_of=multiple_of,
+        le=le,
+        ge=ge,
+        lt=lt,
+        gt=gt,
+        strict=strict,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class FloatSchema(TypedDict, total=False):
+    type: Required[Literal['float']]
+    allow_inf_nan: bool  # whether 'NaN', '+inf', '-inf' should be forbidden. default: True
+    multiple_of: float
+    le: float
+    ge: float
+    lt: float
+    gt: float
+    strict: bool
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def float_schema(
+    *,
+    allow_inf_nan: bool | None = None,
+    multiple_of: float | None = None,
+    le: float | None = None,
+    ge: float | None = None,
+    lt: float | None = None,
+    gt: float | None = None,
+    strict: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> FloatSchema:
+    """
+    Returns a schema that matches a float value, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.float_schema(le=0.8, ge=0.2)
+    v = SchemaValidator(schema)
+    assert v.validate_python('0.5') == 0.5
+    ```
+
+    Args:
+        allow_inf_nan: Whether to allow inf and nan values
+        multiple_of: The value must be a multiple of this number
+        le: The value must be less than or equal to this number
+        ge: The value must be greater than or equal to this number
+        lt: The value must be strictly less than this number
+        gt: The value must be strictly greater than this number
+        strict: Whether the value should be a float or a value that can be converted to a float
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='float',
+        allow_inf_nan=allow_inf_nan,
+        multiple_of=multiple_of,
+        le=le,
+        ge=ge,
+        lt=lt,
+        gt=gt,
+        strict=strict,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class DecimalSchema(TypedDict, total=False):
+    type: Required[Literal['decimal']]
+    allow_inf_nan: bool  # whether 'NaN', '+inf', '-inf' should be forbidden. default: False
+    multiple_of: Decimal
+    le: Decimal
+    ge: Decimal
+    lt: Decimal
+    gt: Decimal
+    max_digits: int
+    decimal_places: int
+    strict: bool
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def decimal_schema(
+    *,
+    allow_inf_nan: bool | None = None,
+    multiple_of: Decimal | None = None,
+    le: Decimal | None = None,
+    ge: Decimal | None = None,
+    lt: Decimal | None = None,
+    gt: Decimal | None = None,
+    max_digits: int | None = None,
+    decimal_places: int | None = None,
+    strict: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> DecimalSchema:
+    """
+    Returns a schema that matches a decimal value, e.g.:
+
+    ```py
+    from decimal import Decimal
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.decimal_schema(le=0.8, ge=0.2)
+    v = SchemaValidator(schema)
+    assert v.validate_python('0.5') == Decimal('0.5')
+    ```
+
+    Args:
+        allow_inf_nan: Whether to allow inf and nan values
+        multiple_of: The value must be a multiple of this number
+        le: The value must be less than or equal to this number
+        ge: The value must be greater than or equal to this number
+        lt: The value must be strictly less than this number
+        gt: The value must be strictly greater than this number
+        max_digits: The maximum number of decimal digits allowed
+        decimal_places: The maximum number of decimal places allowed
+        strict: Whether the value should be a float or a value that can be converted to a float
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='decimal',
+        gt=gt,
+        ge=ge,
+        lt=lt,
+        le=le,
+        max_digits=max_digits,
+        decimal_places=decimal_places,
+        multiple_of=multiple_of,
+        allow_inf_nan=allow_inf_nan,
+        strict=strict,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class ComplexSchema(TypedDict, total=False):
+    type: Required[Literal['complex']]
+    strict: bool
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def complex_schema(
+    *,
+    strict: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> ComplexSchema:
+    """
+    Returns a schema that matches a complex value, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.complex_schema()
+    v = SchemaValidator(schema)
+    assert v.validate_python('1+2j') == complex(1, 2)
+    assert v.validate_python(complex(1, 2)) == complex(1, 2)
+    ```
+
+    Args:
+        strict: Whether the value should be a complex object instance or a value that can be converted to a complex object
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='complex',
+        strict=strict,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class StringSchema(TypedDict, total=False):
+    type: Required[Literal['str']]
+    pattern: Union[str, Pattern[str]]
+    max_length: int
+    min_length: int
+    strip_whitespace: bool
+    to_lower: bool
+    to_upper: bool
+    regex_engine: Literal['rust-regex', 'python-re']  # default: 'rust-regex'
+    strict: bool
+    coerce_numbers_to_str: bool
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def str_schema(
+    *,
+    pattern: str | Pattern[str] | None = None,
+    max_length: int | None = None,
+    min_length: int | None = None,
+    strip_whitespace: bool | None = None,
+    to_lower: bool | None = None,
+    to_upper: bool | None = None,
+    regex_engine: Literal['rust-regex', 'python-re'] | None = None,
+    strict: bool | None = None,
+    coerce_numbers_to_str: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> StringSchema:
+    """
+    Returns a schema that matches a string value, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.str_schema(max_length=10, min_length=2)
+    v = SchemaValidator(schema)
+    assert v.validate_python('hello') == 'hello'
+    ```
+
+    Args:
+        pattern: A regex pattern that the value must match
+        max_length: The value must be at most this length
+        min_length: The value must be at least this length
+        strip_whitespace: Whether to strip whitespace from the value
+        to_lower: Whether to convert the value to lowercase
+        to_upper: Whether to convert the value to uppercase
+        regex_engine: The regex engine to use for pattern validation. Default is 'rust-regex'.
+            - `rust-regex` uses the [`regex`](https://docs.rs/regex) Rust
+              crate, which is non-backtracking and therefore more DDoS
+              resistant, but does not support all regex features.
+            - `python-re` use the [`re`](https://docs.python.org/3/library/re.html) module,
+              which supports all regex features, but may be slower.
+        strict: Whether the value should be a string or a value that can be converted to a string
+        coerce_numbers_to_str: Whether to enable coercion of any `Number` type to `str` (not applicable in `strict` mode).
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='str',
+        pattern=pattern,
+        max_length=max_length,
+        min_length=min_length,
+        strip_whitespace=strip_whitespace,
+        to_lower=to_lower,
+        to_upper=to_upper,
+        regex_engine=regex_engine,
+        strict=strict,
+        coerce_numbers_to_str=coerce_numbers_to_str,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class BytesSchema(TypedDict, total=False):
+    type: Required[Literal['bytes']]
+    max_length: int
+    min_length: int
+    strict: bool
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def bytes_schema(
+    *,
+    max_length: int | None = None,
+    min_length: int | None = None,
+    strict: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> BytesSchema:
+    """
+    Returns a schema that matches a bytes value, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.bytes_schema(max_length=10, min_length=2)
+    v = SchemaValidator(schema)
+    assert v.validate_python(b'hello') == b'hello'
+    ```
+
+    Args:
+        max_length: The value must be at most this length
+        min_length: The value must be at least this length
+        strict: Whether the value should be a bytes or a value that can be converted to a bytes
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='bytes',
+        max_length=max_length,
+        min_length=min_length,
+        strict=strict,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class DateSchema(TypedDict, total=False):
+    type: Required[Literal['date']]
+    strict: bool
+    le: date
+    ge: date
+    lt: date
+    gt: date
+    now_op: Literal['past', 'future']
+    # defaults to current local utc offset from `time.localtime().tm_gmtoff`
+    # value is restricted to -86_400 < offset < 86_400:
+    now_utc_offset: int
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def date_schema(
+    *,
+    strict: bool | None = None,
+    le: date | None = None,
+    ge: date | None = None,
+    lt: date | None = None,
+    gt: date | None = None,
+    now_op: Literal['past', 'future'] | None = None,
+    now_utc_offset: int | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> DateSchema:
+    """
+    Returns a schema that matches a date value, e.g.:
+
+    ```py
+    from datetime import date
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.date_schema(le=date(2020, 1, 1), ge=date(2019, 1, 1))
+    v = SchemaValidator(schema)
+    assert v.validate_python(date(2019, 6, 1)) == date(2019, 6, 1)
+    ```
+
+    Args:
+        strict: Whether the value should be a date or a value that can be converted to a date
+        le: The value must be less than or equal to this date
+        ge: The value must be greater than or equal to this date
+        lt: The value must be strictly less than this date
+        gt: The value must be strictly greater than this date
+        now_op: The value must be in the past or future relative to the current date
+        now_utc_offset: The value must be in the past or future relative to the current date with this utc offset
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='date',
+        strict=strict,
+        le=le,
+        ge=ge,
+        lt=lt,
+        gt=gt,
+        now_op=now_op,
+        now_utc_offset=now_utc_offset,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class TimeSchema(TypedDict, total=False):
+    type: Required[Literal['time']]
+    strict: bool
+    le: time
+    ge: time
+    lt: time
+    gt: time
+    tz_constraint: Union[Literal['aware', 'naive'], int]
+    microseconds_precision: Literal['truncate', 'error']
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def time_schema(
+    *,
+    strict: bool | None = None,
+    le: time | None = None,
+    ge: time | None = None,
+    lt: time | None = None,
+    gt: time | None = None,
+    tz_constraint: Literal['aware', 'naive'] | int | None = None,
+    microseconds_precision: Literal['truncate', 'error'] = 'truncate',
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> TimeSchema:
+    """
+    Returns a schema that matches a time value, e.g.:
+
+    ```py
+    from datetime import time
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.time_schema(le=time(12, 0, 0), ge=time(6, 0, 0))
+    v = SchemaValidator(schema)
+    assert v.validate_python(time(9, 0, 0)) == time(9, 0, 0)
+    ```
+
+    Args:
+        strict: Whether the value should be a time or a value that can be converted to a time
+        le: The value must be less than or equal to this time
+        ge: The value must be greater than or equal to this time
+        lt: The value must be strictly less than this time
+        gt: The value must be strictly greater than this time
+        tz_constraint: The value must be timezone aware or naive, or an int to indicate required tz offset
+        microseconds_precision: The behavior when seconds have more than 6 digits or microseconds is too large
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='time',
+        strict=strict,
+        le=le,
+        ge=ge,
+        lt=lt,
+        gt=gt,
+        tz_constraint=tz_constraint,
+        microseconds_precision=microseconds_precision,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class DatetimeSchema(TypedDict, total=False):
+    type: Required[Literal['datetime']]
+    strict: bool
+    le: datetime
+    ge: datetime
+    lt: datetime
+    gt: datetime
+    now_op: Literal['past', 'future']
+    tz_constraint: Union[Literal['aware', 'naive'], int]
+    # defaults to current local utc offset from `time.localtime().tm_gmtoff`
+    # value is restricted to -86_400 < offset < 86_400 by bounds in generate_self_schema.py
+    now_utc_offset: int
+    microseconds_precision: Literal['truncate', 'error']  # default: 'truncate'
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def datetime_schema(
+    *,
+    strict: bool | None = None,
+    le: datetime | None = None,
+    ge: datetime | None = None,
+    lt: datetime | None = None,
+    gt: datetime | None = None,
+    now_op: Literal['past', 'future'] | None = None,
+    tz_constraint: Literal['aware', 'naive'] | int | None = None,
+    now_utc_offset: int | None = None,
+    microseconds_precision: Literal['truncate', 'error'] = 'truncate',
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> DatetimeSchema:
+    """
+    Returns a schema that matches a datetime value, e.g.:
+
+    ```py
+    from datetime import datetime
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.datetime_schema()
+    v = SchemaValidator(schema)
+    now = datetime.now()
+    assert v.validate_python(str(now)) == now
+    ```
+
+    Args:
+        strict: Whether the value should be a datetime or a value that can be converted to a datetime
+        le: The value must be less than or equal to this datetime
+        ge: The value must be greater than or equal to this datetime
+        lt: The value must be strictly less than this datetime
+        gt: The value must be strictly greater than this datetime
+        now_op: The value must be in the past or future relative to the current datetime
+        tz_constraint: The value must be timezone aware or naive, or an int to indicate required tz offset
+            TODO: use of a tzinfo where offset changes based on the datetime is not yet supported
+        now_utc_offset: The value must be in the past or future relative to the current datetime with this utc offset
+        microseconds_precision: The behavior when seconds have more than 6 digits or microseconds is too large
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='datetime',
+        strict=strict,
+        le=le,
+        ge=ge,
+        lt=lt,
+        gt=gt,
+        now_op=now_op,
+        tz_constraint=tz_constraint,
+        now_utc_offset=now_utc_offset,
+        microseconds_precision=microseconds_precision,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class TimedeltaSchema(TypedDict, total=False):
+    type: Required[Literal['timedelta']]
+    strict: bool
+    le: timedelta
+    ge: timedelta
+    lt: timedelta
+    gt: timedelta
+    microseconds_precision: Literal['truncate', 'error']
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def timedelta_schema(
+    *,
+    strict: bool | None = None,
+    le: timedelta | None = None,
+    ge: timedelta | None = None,
+    lt: timedelta | None = None,
+    gt: timedelta | None = None,
+    microseconds_precision: Literal['truncate', 'error'] = 'truncate',
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> TimedeltaSchema:
+    """
+    Returns a schema that matches a timedelta value, e.g.:
+
+    ```py
+    from datetime import timedelta
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.timedelta_schema(le=timedelta(days=1), ge=timedelta(days=0))
+    v = SchemaValidator(schema)
+    assert v.validate_python(timedelta(hours=12)) == timedelta(hours=12)
+    ```
+
+    Args:
+        strict: Whether the value should be a timedelta or a value that can be converted to a timedelta
+        le: The value must be less than or equal to this timedelta
+        ge: The value must be greater than or equal to this timedelta
+        lt: The value must be strictly less than this timedelta
+        gt: The value must be strictly greater than this timedelta
+        microseconds_precision: The behavior when seconds have more than 6 digits or microseconds is too large
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='timedelta',
+        strict=strict,
+        le=le,
+        ge=ge,
+        lt=lt,
+        gt=gt,
+        microseconds_precision=microseconds_precision,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class LiteralSchema(TypedDict, total=False):
+    type: Required[Literal['literal']]
+    expected: Required[list[Any]]
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def literal_schema(
+    expected: list[Any],
+    *,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> LiteralSchema:
+    """
+    Returns a schema that matches a literal value, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.literal_schema(['hello', 'world'])
+    v = SchemaValidator(schema)
+    assert v.validate_python('hello') == 'hello'
+    ```
+
+    Args:
+        expected: The value must be one of these values
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(type='literal', expected=expected, ref=ref, metadata=metadata, serialization=serialization)
+
+
+class EnumSchema(TypedDict, total=False):
+    type: Required[Literal['enum']]
+    cls: Required[Any]
+    members: Required[list[Any]]
+    sub_type: Literal['str', 'int', 'float']
+    missing: Callable[[Any], Any]
+    strict: bool
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def enum_schema(
+    cls: Any,
+    members: list[Any],
+    *,
+    sub_type: Literal['str', 'int', 'float'] | None = None,
+    missing: Callable[[Any], Any] | None = None,
+    strict: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> EnumSchema:
+    """
+    Returns a schema that matches an enum value, e.g.:
+
+    ```py
+    from enum import Enum
+    from pydantic_core import SchemaValidator, core_schema
+
+    class Color(Enum):
+        RED = 1
+        GREEN = 2
+        BLUE = 3
+
+    schema = core_schema.enum_schema(Color, list(Color.__members__.values()))
+    v = SchemaValidator(schema)
+    assert v.validate_python(2) is Color.GREEN
+    ```
+
+    Args:
+        cls: The enum class
+        members: The members of the enum, generally `list(MyEnum.__members__.values())`
+        sub_type: The type of the enum, either 'str' or 'int' or None for plain enums
+        missing: A function to use when the value is not found in the enum, from `_missing_`
+        strict: Whether to use strict mode, defaults to False
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='enum',
+        cls=cls,
+        members=members,
+        sub_type=sub_type,
+        missing=missing,
+        strict=strict,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class MissingSentinelSchema(TypedDict, total=False):
+    type: Required[Literal['missing-sentinel']]
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def missing_sentinel_schema(
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> MissingSentinelSchema:
+    """Returns a schema for the `MISSING` sentinel."""
+
+    return _dict_not_none(
+        type='missing-sentinel',
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+# must match input/parse_json.rs::JsonType::try_from
+JsonType = Literal['null', 'bool', 'int', 'float', 'str', 'list', 'dict']
+
+
+class IsInstanceSchema(TypedDict, total=False):
+    type: Required[Literal['is-instance']]
+    cls: Required[Any]
+    cls_repr: str
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def is_instance_schema(
+    cls: Any,
+    *,
+    cls_repr: str | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> IsInstanceSchema:
+    """
+    Returns a schema that checks if a value is an instance of a class, equivalent to python's `isinstance` method, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    class A:
+        pass
+
+    schema = core_schema.is_instance_schema(cls=A)
+    v = SchemaValidator(schema)
+    v.validate_python(A())
+    ```
+
+    Args:
+        cls: The value must be an instance of this class
+        cls_repr: If provided this string is used in the validator name instead of `repr(cls)`
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='is-instance', cls=cls, cls_repr=cls_repr, ref=ref, metadata=metadata, serialization=serialization
+    )
+
+
+class IsSubclassSchema(TypedDict, total=False):
+    type: Required[Literal['is-subclass']]
+    cls: Required[type[Any]]
+    cls_repr: str
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def is_subclass_schema(
+    cls: type[Any],
+    *,
+    cls_repr: str | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> IsInstanceSchema:
+    """
+    Returns a schema that checks if a value is a subtype of a class, equivalent to python's `issubclass` method, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    class A:
+        pass
+
+    class B(A):
+        pass
+
+    schema = core_schema.is_subclass_schema(cls=A)
+    v = SchemaValidator(schema)
+    v.validate_python(B)
+    ```
+
+    Args:
+        cls: The value must be a subclass of this class
+        cls_repr: If provided this string is used in the validator name instead of `repr(cls)`
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='is-subclass', cls=cls, cls_repr=cls_repr, ref=ref, metadata=metadata, serialization=serialization
+    )
+
+
+class CallableSchema(TypedDict, total=False):
+    type: Required[Literal['callable']]
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def callable_schema(
+    *, ref: str | None = None, metadata: dict[str, Any] | None = None, serialization: SerSchema | None = None
+) -> CallableSchema:
+    """
+    Returns a schema that checks if a value is callable, equivalent to python's `callable` method, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.callable_schema()
+    v = SchemaValidator(schema)
+    v.validate_python(min)
+    ```
+
+    Args:
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(type='callable', ref=ref, metadata=metadata, serialization=serialization)
+
+
+class UuidSchema(TypedDict, total=False):
+    type: Required[Literal['uuid']]
+    version: Literal[1, 3, 4, 5, 7]
+    strict: bool
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def uuid_schema(
+    *,
+    version: Literal[1, 3, 4, 5, 6, 7, 8] | None = None,
+    strict: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> UuidSchema:
+    return _dict_not_none(
+        type='uuid', version=version, strict=strict, ref=ref, metadata=metadata, serialization=serialization
+    )
+
+
+class IncExSeqSerSchema(TypedDict, total=False):
+    type: Required[Literal['include-exclude-sequence']]
+    include: set[int]
+    exclude: set[int]
+
+
+def filter_seq_schema(*, include: set[int] | None = None, exclude: set[int] | None = None) -> IncExSeqSerSchema:
+    return _dict_not_none(type='include-exclude-sequence', include=include, exclude=exclude)
+
+
+IncExSeqOrElseSerSchema = Union[IncExSeqSerSchema, SerSchema]
+
+
+class ListSchema(TypedDict, total=False):
+    type: Required[Literal['list']]
+    items_schema: CoreSchema
+    min_length: int
+    max_length: int
+    fail_fast: bool
+    strict: bool
+    ref: str
+    metadata: dict[str, Any]
+    serialization: IncExSeqOrElseSerSchema
+
+
+def list_schema(
+    items_schema: CoreSchema | None = None,
+    *,
+    min_length: int | None = None,
+    max_length: int | None = None,
+    fail_fast: bool | None = None,
+    strict: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: IncExSeqOrElseSerSchema | None = None,
+) -> ListSchema:
+    """
+    Returns a schema that matches a list value, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.list_schema(core_schema.int_schema(), min_length=0, max_length=10)
+    v = SchemaValidator(schema)
+    assert v.validate_python(['4']) == [4]
+    ```
+
+    Args:
+        items_schema: The value must be a list of items that match this schema
+        min_length: The value must be a list with at least this many items
+        max_length: The value must be a list with at most this many items
+        fail_fast: Stop validation on the first error
+        strict: The value must be a list with exactly this many items
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='list',
+        items_schema=items_schema,
+        min_length=min_length,
+        max_length=max_length,
+        fail_fast=fail_fast,
+        strict=strict,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+# @deprecated('tuple_positional_schema is deprecated. Use pydantic_core.core_schema.tuple_schema instead.')
+def tuple_positional_schema(
+    items_schema: list[CoreSchema],
+    *,
+    extras_schema: CoreSchema | None = None,
+    strict: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: IncExSeqOrElseSerSchema | None = None,
+) -> TupleSchema:
+    """
+    Returns a schema that matches a tuple of schemas, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.tuple_positional_schema(
+        [core_schema.int_schema(), core_schema.str_schema()]
+    )
+    v = SchemaValidator(schema)
+    assert v.validate_python((1, 'hello')) == (1, 'hello')
+    ```
+
+    Args:
+        items_schema: The value must be a tuple with items that match these schemas
+        extras_schema: The value must be a tuple with items that match this schema
+            This was inspired by JSON schema's `prefixItems` and `items` fields.
+            In python's `typing.Tuple`, you can't specify a type for "extra" items -- they must all be the same type
+            if the length is variable. So this field won't be set from a `typing.Tuple` annotation on a pydantic model.
+        strict: The value must be a tuple with exactly this many items
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    if extras_schema is not None:
+        variadic_item_index = len(items_schema)
+        items_schema = items_schema + [extras_schema]
+    else:
+        variadic_item_index = None
+    return tuple_schema(
+        items_schema=items_schema,
+        variadic_item_index=variadic_item_index,
+        strict=strict,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+# @deprecated('tuple_variable_schema is deprecated. Use pydantic_core.core_schema.tuple_schema instead.')
+def tuple_variable_schema(
+    items_schema: CoreSchema | None = None,
+    *,
+    min_length: int | None = None,
+    max_length: int | None = None,
+    strict: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: IncExSeqOrElseSerSchema | None = None,
+) -> TupleSchema:
+    """
+    Returns a schema that matches a tuple of a given schema, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.tuple_variable_schema(
+        items_schema=core_schema.int_schema(), min_length=0, max_length=10
+    )
+    v = SchemaValidator(schema)
+    assert v.validate_python(('1', 2, 3)) == (1, 2, 3)
+    ```
+
+    Args:
+        items_schema: The value must be a tuple with items that match this schema
+        min_length: The value must be a tuple with at least this many items
+        max_length: The value must be a tuple with at most this many items
+        strict: The value must be a tuple with exactly this many items
+        ref: Optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return tuple_schema(
+        items_schema=[items_schema or any_schema()],
+        variadic_item_index=0,
+        min_length=min_length,
+        max_length=max_length,
+        strict=strict,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class TupleSchema(TypedDict, total=False):
+    type: Required[Literal['tuple']]
+    items_schema: Required[list[CoreSchema]]
+    variadic_item_index: int
+    min_length: int
+    max_length: int
+    fail_fast: bool
+    strict: bool
+    ref: str
+    metadata: dict[str, Any]
+    serialization: IncExSeqOrElseSerSchema
+
+
+def tuple_schema(
+    items_schema: list[CoreSchema],
+    *,
+    variadic_item_index: int | None = None,
+    min_length: int | None = None,
+    max_length: int | None = None,
+    fail_fast: bool | None = None,
+    strict: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: IncExSeqOrElseSerSchema | None = None,
+) -> TupleSchema:
+    """
+    Returns a schema that matches a tuple of schemas, with an optional variadic item, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.tuple_schema(
+        [core_schema.int_schema(), core_schema.str_schema(), core_schema.float_schema()],
+        variadic_item_index=1,
+    )
+    v = SchemaValidator(schema)
+    assert v.validate_python((1, 'hello', 'world', 1.5)) == (1, 'hello', 'world', 1.5)
+    ```
+
+    Args:
+        items_schema: The value must be a tuple with items that match these schemas
+        variadic_item_index: The index of the schema in `items_schema` to be treated as variadic (following PEP 646)
+        min_length: The value must be a tuple with at least this many items
+        max_length: The value must be a tuple with at most this many items
+        fail_fast: Stop validation on the first error
+        strict: The value must be a tuple with exactly this many items
+        ref: Optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='tuple',
+        items_schema=items_schema,
+        variadic_item_index=variadic_item_index,
+        min_length=min_length,
+        max_length=max_length,
+        fail_fast=fail_fast,
+        strict=strict,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class SetSchema(TypedDict, total=False):
+    type: Required[Literal['set']]
+    items_schema: CoreSchema
+    min_length: int
+    max_length: int
+    fail_fast: bool
+    strict: bool
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def set_schema(
+    items_schema: CoreSchema | None = None,
+    *,
+    min_length: int | None = None,
+    max_length: int | None = None,
+    fail_fast: bool | None = None,
+    strict: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> SetSchema:
+    """
+    Returns a schema that matches a set of a given schema, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.set_schema(
+        items_schema=core_schema.int_schema(), min_length=0, max_length=10
+    )
+    v = SchemaValidator(schema)
+    assert v.validate_python({1, '2', 3}) == {1, 2, 3}
+    ```
+
+    Args:
+        items_schema: The value must be a set with items that match this schema
+        min_length: The value must be a set with at least this many items
+        max_length: The value must be a set with at most this many items
+        fail_fast: Stop validation on the first error
+        strict: The value must be a set with exactly this many items
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='set',
+        items_schema=items_schema,
+        min_length=min_length,
+        max_length=max_length,
+        fail_fast=fail_fast,
+        strict=strict,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class FrozenSetSchema(TypedDict, total=False):
+    type: Required[Literal['frozenset']]
+    items_schema: CoreSchema
+    min_length: int
+    max_length: int
+    fail_fast: bool
+    strict: bool
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def frozenset_schema(
+    items_schema: CoreSchema | None = None,
+    *,
+    min_length: int | None = None,
+    max_length: int | None = None,
+    fail_fast: bool | None = None,
+    strict: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> FrozenSetSchema:
+    """
+    Returns a schema that matches a frozenset of a given schema, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.frozenset_schema(
+        items_schema=core_schema.int_schema(), min_length=0, max_length=10
+    )
+    v = SchemaValidator(schema)
+    assert v.validate_python(frozenset(range(3))) == frozenset({0, 1, 2})
+    ```
+
+    Args:
+        items_schema: The value must be a frozenset with items that match this schema
+        min_length: The value must be a frozenset with at least this many items
+        max_length: The value must be a frozenset with at most this many items
+        fail_fast: Stop validation on the first error
+        strict: The value must be a frozenset with exactly this many items
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='frozenset',
+        items_schema=items_schema,
+        min_length=min_length,
+        max_length=max_length,
+        fail_fast=fail_fast,
+        strict=strict,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class GeneratorSchema(TypedDict, total=False):
+    type: Required[Literal['generator']]
+    items_schema: CoreSchema
+    min_length: int
+    max_length: int
+    ref: str
+    metadata: dict[str, Any]
+    serialization: IncExSeqOrElseSerSchema
+
+
+def generator_schema(
+    items_schema: CoreSchema | None = None,
+    *,
+    min_length: int | None = None,
+    max_length: int | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: IncExSeqOrElseSerSchema | None = None,
+) -> GeneratorSchema:
+    """
+    Returns a schema that matches a generator value, e.g.:
+
+    ```py
+    from typing import Iterator
+    from pydantic_core import SchemaValidator, core_schema
+
+    def gen() -> Iterator[int]:
+        yield 1
+
+    schema = core_schema.generator_schema(items_schema=core_schema.int_schema())
+    v = SchemaValidator(schema)
+    v.validate_python(gen())
+    ```
+
+    Unlike other types, validated generators do not raise ValidationErrors eagerly,
+    but instead will raise a ValidationError when a violating value is actually read from the generator.
+    This is to ensure that "validated" generators retain the benefit of lazy evaluation.
+
+    Args:
+        items_schema: The value must be a generator with items that match this schema
+        min_length: The value must be a generator that yields at least this many items
+        max_length: The value must be a generator that yields at most this many items
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='generator',
+        items_schema=items_schema,
+        min_length=min_length,
+        max_length=max_length,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+IncExDict = set[Union[int, str]]
+
+
+class IncExDictSerSchema(TypedDict, total=False):
+    type: Required[Literal['include-exclude-dict']]
+    include: IncExDict
+    exclude: IncExDict
+
+
+def filter_dict_schema(*, include: IncExDict | None = None, exclude: IncExDict | None = None) -> IncExDictSerSchema:
+    return _dict_not_none(type='include-exclude-dict', include=include, exclude=exclude)
+
+
+IncExDictOrElseSerSchema = Union[IncExDictSerSchema, SerSchema]
+
+
+class DictSchema(TypedDict, total=False):
+    type: Required[Literal['dict']]
+    keys_schema: CoreSchema  # default: AnySchema
+    values_schema: CoreSchema  # default: AnySchema
+    min_length: int
+    max_length: int
+    fail_fast: bool
+    strict: bool
+    ref: str
+    metadata: dict[str, Any]
+    serialization: IncExDictOrElseSerSchema
+
+
+def dict_schema(
+    keys_schema: CoreSchema | None = None,
+    values_schema: CoreSchema | None = None,
+    *,
+    min_length: int | None = None,
+    max_length: int | None = None,
+    fail_fast: bool | None = None,
+    strict: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> DictSchema:
+    """
+    Returns a schema that matches a dict value, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.dict_schema(
+        keys_schema=core_schema.str_schema(), values_schema=core_schema.int_schema()
+    )
+    v = SchemaValidator(schema)
+    assert v.validate_python({'a': '1', 'b': 2}) == {'a': 1, 'b': 2}
+    ```
+
+    Args:
+        keys_schema: The value must be a dict with keys that match this schema
+        values_schema: The value must be a dict with values that match this schema
+        min_length: The value must be a dict with at least this many items
+        max_length: The value must be a dict with at most this many items
+        fail_fast: Stop validation on the first error
+        strict: Whether the keys and values should be validated with strict mode
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='dict',
+        keys_schema=keys_schema,
+        values_schema=values_schema,
+        min_length=min_length,
+        max_length=max_length,
+        fail_fast=fail_fast,
+        strict=strict,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+# (input_value: Any, /) -> Any
+NoInfoValidatorFunction = Callable[[Any], Any]
+
+
+class NoInfoValidatorFunctionSchema(TypedDict):
+    type: Literal['no-info']
+    function: NoInfoValidatorFunction
+
+
+# (input_value: Any, info: ValidationInfo, /) -> Any
+WithInfoValidatorFunction = Callable[[Any, ValidationInfo[Any]], Any]
+
+
+class WithInfoValidatorFunctionSchema(TypedDict, total=False):
+    type: Required[Literal['with-info']]
+    function: Required[WithInfoValidatorFunction]
+    field_name: str  # deprecated
+
+
+ValidationFunction = Union[NoInfoValidatorFunctionSchema, WithInfoValidatorFunctionSchema]
+
+
+class _ValidatorFunctionSchema(TypedDict, total=False):
+    function: Required[ValidationFunction]
+    schema: Required[CoreSchema]
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+class BeforeValidatorFunctionSchema(_ValidatorFunctionSchema, total=False):
+    type: Required[Literal['function-before']]
+    json_schema_input_schema: CoreSchema
+
+
+def no_info_before_validator_function(
+    function: NoInfoValidatorFunction,
+    schema: CoreSchema,
+    *,
+    ref: str | None = None,
+    json_schema_input_schema: CoreSchema | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> BeforeValidatorFunctionSchema:
+    """
+    Returns a schema that calls a validator function before validating, no `info` argument is provided, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    def fn(v: bytes) -> str:
+        return v.decode() + 'world'
+
+    func_schema = core_schema.no_info_before_validator_function(
+        function=fn, schema=core_schema.str_schema()
+    )
+    schema = core_schema.typed_dict_schema({'a': core_schema.typed_dict_field(func_schema)})
+
+    v = SchemaValidator(schema)
+    assert v.validate_python({'a': b'hello '}) == {'a': 'hello world'}
+    ```
+
+    Args:
+        function: The validator function to call
+        schema: The schema to validate the output of the validator function
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        json_schema_input_schema: The core schema to be used to generate the corresponding JSON Schema input type
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='function-before',
+        function={'type': 'no-info', 'function': function},
+        schema=schema,
+        ref=ref,
+        json_schema_input_schema=json_schema_input_schema,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+def with_info_before_validator_function(
+    function: WithInfoValidatorFunction,
+    schema: CoreSchema,
+    *,
+    field_name: str | None = None,
+    ref: str | None = None,
+    json_schema_input_schema: CoreSchema | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> BeforeValidatorFunctionSchema:
+    """
+    Returns a schema that calls a validator function before validation, the function is called with
+    an `info` argument, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    def fn(v: bytes, info: core_schema.ValidationInfo) -> str:
+        assert info.data is not None
+        assert info.field_name is not None
+        return v.decode() + 'world'
+
+    func_schema = core_schema.with_info_before_validator_function(
+        function=fn, schema=core_schema.str_schema()
+    )
+    schema = core_schema.typed_dict_schema({'a': core_schema.typed_dict_field(func_schema)})
+
+    v = SchemaValidator(schema)
+    assert v.validate_python({'a': b'hello '}) == {'a': 'hello world'}
+    ```
+
+    Args:
+        function: The validator function to call
+        field_name: The name of the field this validator is applied to, if any (deprecated)
+        schema: The schema to validate the output of the validator function
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        json_schema_input_schema: The core schema to be used to generate the corresponding JSON Schema input type
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    if field_name is not None:
+        warnings.warn(
+            'The `field_name` argument on `with_info_before_validator_function` is deprecated, it will be passed to the function through `ValidationState` instead.',
+            DeprecationWarning,
+            stacklevel=2,
+        )
+
+    return _dict_not_none(
+        type='function-before',
+        function=_dict_not_none(type='with-info', function=function, field_name=field_name),
+        schema=schema,
+        ref=ref,
+        json_schema_input_schema=json_schema_input_schema,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class AfterValidatorFunctionSchema(_ValidatorFunctionSchema, total=False):
+    type: Required[Literal['function-after']]
+
+
+def no_info_after_validator_function(
+    function: NoInfoValidatorFunction,
+    schema: CoreSchema,
+    *,
+    ref: str | None = None,
+    json_schema_input_schema: CoreSchema | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> AfterValidatorFunctionSchema:
+    """
+    Returns a schema that calls a validator function after validating, no `info` argument is provided, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    def fn(v: str) -> str:
+        return v + 'world'
+
+    func_schema = core_schema.no_info_after_validator_function(fn, core_schema.str_schema())
+    schema = core_schema.typed_dict_schema({'a': core_schema.typed_dict_field(func_schema)})
+
+    v = SchemaValidator(schema)
+    assert v.validate_python({'a': b'hello '}) == {'a': 'hello world'}
+    ```
+
+    Args:
+        function: The validator function to call after the schema is validated
+        schema: The schema to validate before the validator function
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        json_schema_input_schema: The core schema to be used to generate the corresponding JSON Schema input type
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='function-after',
+        function={'type': 'no-info', 'function': function},
+        schema=schema,
+        ref=ref,
+        json_schema_input_schema=json_schema_input_schema,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+def with_info_after_validator_function(
+    function: WithInfoValidatorFunction,
+    schema: CoreSchema,
+    *,
+    field_name: str | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> AfterValidatorFunctionSchema:
+    """
+    Returns a schema that calls a validator function after validation, the function is called with
+    an `info` argument, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    def fn(v: str, info: core_schema.ValidationInfo) -> str:
+        assert info.data is not None
+        assert info.field_name is not None
+        return v + 'world'
+
+    func_schema = core_schema.with_info_after_validator_function(
+        function=fn, schema=core_schema.str_schema()
+    )
+    schema = core_schema.typed_dict_schema({'a': core_schema.typed_dict_field(func_schema)})
+
+    v = SchemaValidator(schema)
+    assert v.validate_python({'a': b'hello '}) == {'a': 'hello world'}
+    ```
+
+    Args:
+        function: The validator function to call after the schema is validated
+        schema: The schema to validate before the validator function
+        field_name: The name of the field this validator is applied to, if any (deprecated)
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    if field_name is not None:
+        warnings.warn(
+            'The `field_name` argument on `with_info_after_validator_function` is deprecated, it will be passed to the function through `ValidationState` instead.',
+            DeprecationWarning,
+            stacklevel=2,
+        )
+
+    return _dict_not_none(
+        type='function-after',
+        function=_dict_not_none(type='with-info', function=function, field_name=field_name),
+        schema=schema,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class ValidatorFunctionWrapHandler(Protocol):
+    def __call__(self, input_value: Any, outer_location: str | int | None = None, /) -> Any:  # pragma: no cover
+        ...
+
+
+# (input_value: Any, validator: ValidatorFunctionWrapHandler, /) -> Any
+NoInfoWrapValidatorFunction = Callable[[Any, ValidatorFunctionWrapHandler], Any]
+
+
+class NoInfoWrapValidatorFunctionSchema(TypedDict):
+    type: Literal['no-info']
+    function: NoInfoWrapValidatorFunction
+
+
+# (input_value: Any, validator: ValidatorFunctionWrapHandler, info: ValidationInfo, /) -> Any
+WithInfoWrapValidatorFunction = Callable[[Any, ValidatorFunctionWrapHandler, ValidationInfo[Any]], Any]
+
+
+class WithInfoWrapValidatorFunctionSchema(TypedDict, total=False):
+    type: Required[Literal['with-info']]
+    function: Required[WithInfoWrapValidatorFunction]
+    field_name: str  # deprecated
+
+
+WrapValidatorFunction = Union[NoInfoWrapValidatorFunctionSchema, WithInfoWrapValidatorFunctionSchema]
+
+
+class WrapValidatorFunctionSchema(TypedDict, total=False):
+    type: Required[Literal['function-wrap']]
+    function: Required[WrapValidatorFunction]
+    schema: Required[CoreSchema]
+    ref: str
+    json_schema_input_schema: CoreSchema
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def no_info_wrap_validator_function(
+    function: NoInfoWrapValidatorFunction,
+    schema: CoreSchema,
+    *,
+    ref: str | None = None,
+    json_schema_input_schema: CoreSchema | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> WrapValidatorFunctionSchema:
+    """
+    Returns a schema which calls a function with a `validator` callable argument which can
+    optionally be used to call inner validation with the function logic, this is much like the
+    "onion" implementation of middleware in many popular web frameworks, no `info` argument is passed, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    def fn(
+        v: str,
+        validator: core_schema.ValidatorFunctionWrapHandler,
+    ) -> str:
+        return validator(input_value=v) + 'world'
+
+    schema = core_schema.no_info_wrap_validator_function(
+        function=fn, schema=core_schema.str_schema()
+    )
+    v = SchemaValidator(schema)
+    assert v.validate_python('hello ') == 'hello world'
+    ```
+
+    Args:
+        function: The validator function to call
+        schema: The schema to validate the output of the validator function
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        json_schema_input_schema: The core schema to be used to generate the corresponding JSON Schema input type
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='function-wrap',
+        function={'type': 'no-info', 'function': function},
+        schema=schema,
+        json_schema_input_schema=json_schema_input_schema,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+def with_info_wrap_validator_function(
+    function: WithInfoWrapValidatorFunction,
+    schema: CoreSchema,
+    *,
+    field_name: str | None = None,
+    json_schema_input_schema: CoreSchema | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> WrapValidatorFunctionSchema:
+    """
+    Returns a schema which calls a function with a `validator` callable argument which can
+    optionally be used to call inner validation with the function logic, this is much like the
+    "onion" implementation of middleware in many popular web frameworks, an `info` argument is also passed, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    def fn(
+        v: str,
+        validator: core_schema.ValidatorFunctionWrapHandler,
+        info: core_schema.ValidationInfo,
+    ) -> str:
+        return validator(input_value=v) + 'world'
+
+    schema = core_schema.with_info_wrap_validator_function(
+        function=fn, schema=core_schema.str_schema()
+    )
+    v = SchemaValidator(schema)
+    assert v.validate_python('hello ') == 'hello world'
+    ```
+
+    Args:
+        function: The validator function to call
+        schema: The schema to validate the output of the validator function
+        field_name: The name of the field this validator is applied to, if any (deprecated)
+        json_schema_input_schema: The core schema to be used to generate the corresponding JSON Schema input type
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    if field_name is not None:
+        warnings.warn(
+            'The `field_name` argument on `with_info_wrap_validator_function` is deprecated, it will be passed to the function through `ValidationState` instead.',
+            DeprecationWarning,
+            stacklevel=2,
+        )
+
+    return _dict_not_none(
+        type='function-wrap',
+        function=_dict_not_none(type='with-info', function=function, field_name=field_name),
+        schema=schema,
+        json_schema_input_schema=json_schema_input_schema,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class PlainValidatorFunctionSchema(TypedDict, total=False):
+    type: Required[Literal['function-plain']]
+    function: Required[ValidationFunction]
+    ref: str
+    json_schema_input_schema: CoreSchema
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def no_info_plain_validator_function(
+    function: NoInfoValidatorFunction,
+    *,
+    ref: str | None = None,
+    json_schema_input_schema: CoreSchema | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> PlainValidatorFunctionSchema:
+    """
+    Returns a schema that uses the provided function for validation, no `info` argument is passed, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    def fn(v: str) -> str:
+        assert 'hello' in v
+        return v + 'world'
+
+    schema = core_schema.no_info_plain_validator_function(function=fn)
+    v = SchemaValidator(schema)
+    assert v.validate_python('hello ') == 'hello world'
+    ```
+
+    Args:
+        function: The validator function to call
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        json_schema_input_schema: The core schema to be used to generate the corresponding JSON Schema input type
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='function-plain',
+        function={'type': 'no-info', 'function': function},
+        ref=ref,
+        json_schema_input_schema=json_schema_input_schema,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+def with_info_plain_validator_function(
+    function: WithInfoValidatorFunction,
+    *,
+    field_name: str | None = None,
+    ref: str | None = None,
+    json_schema_input_schema: CoreSchema | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> PlainValidatorFunctionSchema:
+    """
+    Returns a schema that uses the provided function for validation, an `info` argument is passed, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    def fn(v: str, info: core_schema.ValidationInfo) -> str:
+        assert 'hello' in v
+        return v + 'world'
+
+    schema = core_schema.with_info_plain_validator_function(function=fn)
+    v = SchemaValidator(schema)
+    assert v.validate_python('hello ') == 'hello world'
+    ```
+
+    Args:
+        function: The validator function to call
+        field_name: The name of the field this validator is applied to, if any (deprecated)
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        json_schema_input_schema: The core schema to be used to generate the corresponding JSON Schema input type
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    if field_name is not None:
+        warnings.warn(
+            'The `field_name` argument on `with_info_plain_validator_function` is deprecated, it will be passed to the function through `ValidationState` instead.',
+            DeprecationWarning,
+            stacklevel=2,
+        )
+
+    return _dict_not_none(
+        type='function-plain',
+        function=_dict_not_none(type='with-info', function=function, field_name=field_name),
+        ref=ref,
+        json_schema_input_schema=json_schema_input_schema,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class WithDefaultSchema(TypedDict, total=False):
+    type: Required[Literal['default']]
+    schema: Required[CoreSchema]
+    default: Any
+    default_factory: Union[Callable[[], Any], Callable[[dict[str, Any]], Any]]
+    default_factory_takes_data: bool
+    on_error: Literal['raise', 'omit', 'default']  # default: 'raise'
+    validate_default: bool  # default: False
+    strict: bool
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def with_default_schema(
+    schema: CoreSchema,
+    *,
+    default: Any = PydanticUndefined,
+    default_factory: Union[Callable[[], Any], Callable[[dict[str, Any]], Any], None] = None,
+    default_factory_takes_data: bool | None = None,
+    on_error: Literal['raise', 'omit', 'default'] | None = None,
+    validate_default: bool | None = None,
+    strict: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> WithDefaultSchema:
+    """
+    Returns a schema that adds a default value to the given schema, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.with_default_schema(core_schema.str_schema(), default='hello')
+    wrapper_schema = core_schema.typed_dict_schema(
+        {'a': core_schema.typed_dict_field(schema)}
+    )
+    v = SchemaValidator(wrapper_schema)
+    assert v.validate_python({}) == v.validate_python({'a': 'hello'})
+    ```
+
+    Args:
+        schema: The schema to add a default value to
+        default: The default value to use
+        default_factory: A callable that returns the default value to use
+        default_factory_takes_data: Whether the default factory takes a validated data argument
+        on_error: What to do if the schema validation fails. One of 'raise', 'omit', 'default'
+        validate_default: Whether the default value should be validated
+        strict: Whether the underlying schema should be validated with strict mode
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    s = _dict_not_none(
+        type='default',
+        schema=schema,
+        default_factory=default_factory,
+        default_factory_takes_data=default_factory_takes_data,
+        on_error=on_error,
+        validate_default=validate_default,
+        strict=strict,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+    if default is not PydanticUndefined:
+        s['default'] = default
+    return s
+
+
+class NullableSchema(TypedDict, total=False):
+    type: Required[Literal['nullable']]
+    schema: Required[CoreSchema]
+    strict: bool
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def nullable_schema(
+    schema: CoreSchema,
+    *,
+    strict: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> NullableSchema:
+    """
+    Returns a schema that matches a nullable value, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.nullable_schema(core_schema.str_schema())
+    v = SchemaValidator(schema)
+    assert v.validate_python(None) is None
+    ```
+
+    Args:
+        schema: The schema to wrap
+        strict: Whether the underlying schema should be validated with strict mode
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='nullable', schema=schema, strict=strict, ref=ref, metadata=metadata, serialization=serialization
+    )
+
+
+class UnionSchema(TypedDict, total=False):
+    type: Required[Literal['union']]
+    choices: Required[list[Union[CoreSchema, tuple[CoreSchema, str]]]]
+    # default true, whether to automatically collapse unions with one element to the inner validator
+    auto_collapse: bool
+    custom_error_type: str
+    custom_error_message: str
+    custom_error_context: dict[str, Union[str, int, float]]
+    mode: Literal['smart', 'left_to_right']  # default: 'smart'
+    strict: bool
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def union_schema(
+    choices: list[CoreSchema | tuple[CoreSchema, str]],
+    *,
+    auto_collapse: bool | None = None,
+    custom_error_type: str | None = None,
+    custom_error_message: str | None = None,
+    custom_error_context: dict[str, str | int] | None = None,
+    mode: Literal['smart', 'left_to_right'] | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> UnionSchema:
+    """
+    Returns a schema that matches a union value, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.union_schema([core_schema.str_schema(), core_schema.int_schema()])
+    v = SchemaValidator(schema)
+    assert v.validate_python('hello') == 'hello'
+    assert v.validate_python(1) == 1
+    ```
+
+    Args:
+        choices: The schemas to match. If a tuple, the second item is used as the label for the case.
+        auto_collapse: whether to automatically collapse unions with one element to the inner validator, default true
+        custom_error_type: The custom error type to use if the validation fails
+        custom_error_message: The custom error message to use if the validation fails
+        custom_error_context: The custom error context to use if the validation fails
+        mode: How to select which choice to return
+            * `smart` (default) will try to return the choice which is the closest match to the input value
+            * `left_to_right` will return the first choice in `choices` which succeeds validation
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='union',
+        choices=choices,
+        auto_collapse=auto_collapse,
+        custom_error_type=custom_error_type,
+        custom_error_message=custom_error_message,
+        custom_error_context=custom_error_context,
+        mode=mode,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class TaggedUnionSchema(TypedDict, total=False):
+    type: Required[Literal['tagged-union']]
+    choices: Required[dict[Hashable, CoreSchema]]
+    discriminator: Required[Union[str, list[Union[str, int]], list[list[Union[str, int]]], Callable[[Any], Hashable]]]
+    custom_error_type: str
+    custom_error_message: str
+    custom_error_context: dict[str, Union[str, int, float]]
+    strict: bool
+    from_attributes: bool  # default: True
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def tagged_union_schema(
+    choices: dict[Any, CoreSchema],
+    discriminator: str | list[str | int] | list[list[str | int]] | Callable[[Any], Any],
+    *,
+    custom_error_type: str | None = None,
+    custom_error_message: str | None = None,
+    custom_error_context: dict[str, int | str | float] | None = None,
+    strict: bool | None = None,
+    from_attributes: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> TaggedUnionSchema:
+    """
+    Returns a schema that matches a tagged union value, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    apple_schema = core_schema.typed_dict_schema(
+        {
+            'foo': core_schema.typed_dict_field(core_schema.str_schema()),
+            'bar': core_schema.typed_dict_field(core_schema.int_schema()),
+        }
+    )
+    banana_schema = core_schema.typed_dict_schema(
+        {
+            'foo': core_schema.typed_dict_field(core_schema.str_schema()),
+            'spam': core_schema.typed_dict_field(
+                core_schema.list_schema(items_schema=core_schema.int_schema())
+            ),
+        }
+    )
+    schema = core_schema.tagged_union_schema(
+        choices={
+            'apple': apple_schema,
+            'banana': banana_schema,
+        },
+        discriminator='foo',
+    )
+    v = SchemaValidator(schema)
+    assert v.validate_python({'foo': 'apple', 'bar': '123'}) == {'foo': 'apple', 'bar': 123}
+    assert v.validate_python({'foo': 'banana', 'spam': [1, 2, 3]}) == {
+        'foo': 'banana',
+        'spam': [1, 2, 3],
+    }
+    ```
+
+    Args:
+        choices: The schemas to match
+            When retrieving a schema from `choices` using the discriminator value, if the value is a str,
+            it should be fed back into the `choices` map until a schema is obtained
+            (This approach is to prevent multiple ownership of a single schema in Rust)
+        discriminator: The discriminator to use to determine the schema to use
+            * If `discriminator` is a str, it is the name of the attribute to use as the discriminator
+            * If `discriminator` is a list of int/str, it should be used as a "path" to access the discriminator
+            * If `discriminator` is a list of lists, each inner list is a path, and the first path that exists is used
+            * If `discriminator` is a callable, it should return the discriminator when called on the value to validate;
+              the callable can return `None` to indicate that there is no matching discriminator present on the input
+        custom_error_type: The custom error type to use if the validation fails
+        custom_error_message: The custom error message to use if the validation fails
+        custom_error_context: The custom error context to use if the validation fails
+        strict: Whether the underlying schemas should be validated with strict mode
+        from_attributes: Whether to use the attributes of the object to retrieve the discriminator value
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='tagged-union',
+        choices=choices,
+        discriminator=discriminator,
+        custom_error_type=custom_error_type,
+        custom_error_message=custom_error_message,
+        custom_error_context=custom_error_context,
+        strict=strict,
+        from_attributes=from_attributes,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class ChainSchema(TypedDict, total=False):
+    type: Required[Literal['chain']]
+    steps: Required[list[CoreSchema]]
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def chain_schema(
+    steps: list[CoreSchema],
+    *,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> ChainSchema:
+    """
+    Returns a schema that chains the provided validation schemas, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    def fn(v: str, info: core_schema.ValidationInfo) -> str:
+        assert 'hello' in v
+        return v + ' world'
+
+    fn_schema = core_schema.with_info_plain_validator_function(function=fn)
+    schema = core_schema.chain_schema(
+        [fn_schema, fn_schema, fn_schema, core_schema.str_schema()]
+    )
+    v = SchemaValidator(schema)
+    assert v.validate_python('hello') == 'hello world world world'
+    ```
+
+    Args:
+        steps: The schemas to chain
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(type='chain', steps=steps, ref=ref, metadata=metadata, serialization=serialization)
+
+
+class LaxOrStrictSchema(TypedDict, total=False):
+    type: Required[Literal['lax-or-strict']]
+    lax_schema: Required[CoreSchema]
+    strict_schema: Required[CoreSchema]
+    strict: bool
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def lax_or_strict_schema(
+    lax_schema: CoreSchema,
+    strict_schema: CoreSchema,
+    *,
+    strict: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> LaxOrStrictSchema:
+    """
+    Returns a schema that uses the lax or strict schema, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    def fn(v: str, info: core_schema.ValidationInfo) -> str:
+        assert 'hello' in v
+        return v + ' world'
+
+    lax_schema = core_schema.int_schema(strict=False)
+    strict_schema = core_schema.int_schema(strict=True)
+
+    schema = core_schema.lax_or_strict_schema(
+        lax_schema=lax_schema, strict_schema=strict_schema, strict=True
+    )
+    v = SchemaValidator(schema)
+    assert v.validate_python(123) == 123
+
+    schema = core_schema.lax_or_strict_schema(
+        lax_schema=lax_schema, strict_schema=strict_schema, strict=False
+    )
+    v = SchemaValidator(schema)
+    assert v.validate_python('123') == 123
+    ```
+
+    Args:
+        lax_schema: The lax schema to use
+        strict_schema: The strict schema to use
+        strict: Whether the strict schema should be used
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='lax-or-strict',
+        lax_schema=lax_schema,
+        strict_schema=strict_schema,
+        strict=strict,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class JsonOrPythonSchema(TypedDict, total=False):
+    type: Required[Literal['json-or-python']]
+    json_schema: Required[CoreSchema]
+    python_schema: Required[CoreSchema]
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def json_or_python_schema(
+    json_schema: CoreSchema,
+    python_schema: CoreSchema,
+    *,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> JsonOrPythonSchema:
+    """
+    Returns a schema that uses the Json or Python schema depending on the input:
+
+    ```py
+    from pydantic_core import SchemaValidator, ValidationError, core_schema
+
+    v = SchemaValidator(
+        core_schema.json_or_python_schema(
+            json_schema=core_schema.int_schema(),
+            python_schema=core_schema.int_schema(strict=True),
+        )
+    )
+
+    assert v.validate_json('"123"') == 123
+
+    try:
+        v.validate_python('123')
+    except ValidationError:
+        pass
+    else:
+        raise AssertionError('Validation should have failed')
+    ```
+
+    Args:
+        json_schema: The schema to use for Json inputs
+        python_schema: The schema to use for Python inputs
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='json-or-python',
+        json_schema=json_schema,
+        python_schema=python_schema,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class TypedDictField(TypedDict, total=False):
+    type: Required[Literal['typed-dict-field']]
+    schema: Required[CoreSchema]
+    required: bool
+    validation_alias: Union[str, list[Union[str, int]], list[list[Union[str, int]]]]
+    serialization_alias: str
+    serialization_exclude: bool  # default: False
+    metadata: dict[str, Any]
+    serialization_exclude_if: Callable[[Any], bool]  # default None
+
+
+def typed_dict_field(
+    schema: CoreSchema,
+    *,
+    required: bool | None = None,
+    validation_alias: str | list[str | int] | list[list[str | int]] | None = None,
+    serialization_alias: str | None = None,
+    serialization_exclude: bool | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization_exclude_if: Callable[[Any], bool] | None = None,
+) -> TypedDictField:
+    """
+    Returns a schema that matches a typed dict field, e.g.:
+
+    ```py
+    from pydantic_core import core_schema
+
+    field = core_schema.typed_dict_field(schema=core_schema.int_schema(), required=True)
+    ```
+
+    Args:
+        schema: The schema to use for the field
+        required: Whether the field is required, otherwise uses the value from `total` on the typed dict
+        validation_alias: The alias(es) to use to find the field in the validation data
+        serialization_alias: The alias to use as a key when serializing
+        serialization_exclude: Whether to exclude the field when serializing
+        serialization_exclude_if: A callable that determines whether to exclude the field when serializing based on its value.
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+    """
+    return _dict_not_none(
+        type='typed-dict-field',
+        schema=schema,
+        required=required,
+        validation_alias=validation_alias,
+        serialization_alias=serialization_alias,
+        serialization_exclude=serialization_exclude,
+        serialization_exclude_if=serialization_exclude_if,
+        metadata=metadata,
+    )
+
+
+class TypedDictSchema(TypedDict, total=False):
+    type: Required[Literal['typed-dict']]
+    fields: Required[dict[str, TypedDictField]]
+    cls: type[Any]
+    cls_name: str
+    computed_fields: list[ComputedField]
+    strict: bool
+    extras_schema: CoreSchema
+    # all these values can be set via config, equivalent fields have `typed_dict_` prefix
+    extra_behavior: ExtraBehavior
+    total: bool  # default: True
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+    config: CoreConfig
+
+
+def typed_dict_schema(
+    fields: dict[str, TypedDictField],
+    *,
+    cls: type[Any] | None = None,
+    cls_name: str | None = None,
+    computed_fields: list[ComputedField] | None = None,
+    strict: bool | None = None,
+    extras_schema: CoreSchema | None = None,
+    extra_behavior: ExtraBehavior | None = None,
+    total: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+    config: CoreConfig | None = None,
+) -> TypedDictSchema:
+    """
+    Returns a schema that matches a typed dict, e.g.:
+
+    ```py
+    from typing_extensions import TypedDict
+
+    from pydantic_core import SchemaValidator, core_schema
+
+    class MyTypedDict(TypedDict):
+        a: str
+
+    wrapper_schema = core_schema.typed_dict_schema(
+        {'a': core_schema.typed_dict_field(core_schema.str_schema())}, cls=MyTypedDict
+    )
+    v = SchemaValidator(wrapper_schema)
+    assert v.validate_python({'a': 'hello'}) == {'a': 'hello'}
+    ```
+
+    Args:
+        fields: The fields to use for the typed dict
+        cls: The class to use for the typed dict
+        cls_name: The name to use in error locations. Falls back to `cls.__name__`, or the validator name if no class
+            is provided.
+        computed_fields: Computed fields to use when serializing the model, only applies when directly inside a model
+        strict: Whether the typed dict is strict
+        extras_schema: The extra validator to use for the typed dict
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        extra_behavior: The extra behavior to use for the typed dict
+        total: Whether the typed dict is total, otherwise uses `typed_dict_total` from config
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='typed-dict',
+        fields=fields,
+        cls=cls,
+        cls_name=cls_name,
+        computed_fields=computed_fields,
+        strict=strict,
+        extras_schema=extras_schema,
+        extra_behavior=extra_behavior,
+        total=total,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+        config=config,
+    )
+
+
+class ModelField(TypedDict, total=False):
+    type: Required[Literal['model-field']]
+    schema: Required[CoreSchema]
+    validation_alias: Union[str, list[Union[str, int]], list[list[Union[str, int]]]]
+    serialization_alias: str
+    serialization_exclude: bool  # default: False
+    serialization_exclude_if: Callable[[Any], bool]  # default: None
+    frozen: bool
+    metadata: dict[str, Any]
+
+
+def model_field(
+    schema: CoreSchema,
+    *,
+    validation_alias: str | list[str | int] | list[list[str | int]] | None = None,
+    serialization_alias: str | None = None,
+    serialization_exclude: bool | None = None,
+    serialization_exclude_if: Callable[[Any], bool] | None = None,
+    frozen: bool | None = None,
+    metadata: dict[str, Any] | None = None,
+) -> ModelField:
+    """
+    Returns a schema for a model field, e.g.:
+
+    ```py
+    from pydantic_core import core_schema
+
+    field = core_schema.model_field(schema=core_schema.int_schema())
+    ```
+
+    Args:
+        schema: The schema to use for the field
+        validation_alias: The alias(es) to use to find the field in the validation data
+        serialization_alias: The alias to use as a key when serializing
+        serialization_exclude: Whether to exclude the field when serializing
+        serialization_exclude_if: A Callable that determines whether to exclude a field during serialization based on its value.
+        frozen: Whether the field is frozen
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+    """
+    return _dict_not_none(
+        type='model-field',
+        schema=schema,
+        validation_alias=validation_alias,
+        serialization_alias=serialization_alias,
+        serialization_exclude=serialization_exclude,
+        serialization_exclude_if=serialization_exclude_if,
+        frozen=frozen,
+        metadata=metadata,
+    )
+
+
+class ModelFieldsSchema(TypedDict, total=False):
+    type: Required[Literal['model-fields']]
+    fields: Required[dict[str, ModelField]]
+    model_name: str
+    computed_fields: list[ComputedField]
+    strict: bool
+    extras_schema: CoreSchema
+    extras_keys_schema: CoreSchema
+    extra_behavior: ExtraBehavior
+    from_attributes: bool
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def model_fields_schema(
+    fields: dict[str, ModelField],
+    *,
+    model_name: str | None = None,
+    computed_fields: list[ComputedField] | None = None,
+    strict: bool | None = None,
+    extras_schema: CoreSchema | None = None,
+    extras_keys_schema: CoreSchema | None = None,
+    extra_behavior: ExtraBehavior | None = None,
+    from_attributes: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> ModelFieldsSchema:
+    """
+    Returns a schema that matches the fields of a Pydantic model, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    wrapper_schema = core_schema.model_fields_schema(
+        {'a': core_schema.model_field(core_schema.str_schema())}
+    )
+    v = SchemaValidator(wrapper_schema)
+    print(v.validate_python({'a': 'hello'}))
+    #> ({'a': 'hello'}, None, {'a'})
+    ```
+
+    Args:
+        fields: The fields of the model
+        model_name: The name of the model, used for error messages, defaults to "Model"
+        computed_fields: Computed fields to use when serializing the model, only applies when directly inside a model
+        strict: Whether the model is strict
+        extras_schema: The schema to use when validating extra input data
+        extras_keys_schema: The schema to use when validating the keys of extra input data
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        extra_behavior: The extra behavior to use for the model fields
+        from_attributes: Whether the model fields should be populated from attributes
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='model-fields',
+        fields=fields,
+        model_name=model_name,
+        computed_fields=computed_fields,
+        strict=strict,
+        extras_schema=extras_schema,
+        extras_keys_schema=extras_keys_schema,
+        extra_behavior=extra_behavior,
+        from_attributes=from_attributes,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class ModelSchema(TypedDict, total=False):
+    type: Required[Literal['model']]
+    cls: Required[type[Any]]
+    generic_origin: type[Any]
+    schema: Required[CoreSchema]
+    custom_init: bool
+    root_model: bool
+    post_init: str
+    revalidate_instances: Literal['always', 'never', 'subclass-instances']  # default: 'never'
+    strict: bool
+    frozen: bool
+    extra_behavior: ExtraBehavior
+    config: CoreConfig
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def model_schema(
+    cls: type[Any],
+    schema: CoreSchema,
+    *,
+    generic_origin: type[Any] | None = None,
+    custom_init: bool | None = None,
+    root_model: bool | None = None,
+    post_init: str | None = None,
+    revalidate_instances: Literal['always', 'never', 'subclass-instances'] | None = None,
+    strict: bool | None = None,
+    frozen: bool | None = None,
+    extra_behavior: ExtraBehavior | None = None,
+    config: CoreConfig | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> ModelSchema:
+    """
+    A model schema generally contains a typed-dict schema.
+    It will run the typed dict validator, then create a new class
+    and set the dict and fields set returned from the typed dict validator
+    to `__dict__` and `__pydantic_fields_set__` respectively.
+
+    Example:
+
+    ```py
+    from pydantic_core import CoreConfig, SchemaValidator, core_schema
+
+    class MyModel:
+        __slots__ = (
+            '__dict__',
+            '__pydantic_fields_set__',
+            '__pydantic_extra__',
+            '__pydantic_private__',
+        )
+
+    schema = core_schema.model_schema(
+        cls=MyModel,
+        config=CoreConfig(str_max_length=5),
+        schema=core_schema.model_fields_schema(
+            fields={'a': core_schema.model_field(core_schema.str_schema())},
+        ),
+    )
+    v = SchemaValidator(schema)
+    assert v.isinstance_python({'a': 'hello'}) is True
+    assert v.isinstance_python({'a': 'too long'}) is False
+    ```
+
+    Args:
+        cls: The class to use for the model
+        schema: The schema to use for the model
+        generic_origin: The origin type used for this model, if it's a parametrized generic. Ex,
+            if this model schema represents `SomeModel[int]`, generic_origin is `SomeModel`
+        custom_init: Whether the model has a custom init method
+        root_model: Whether the model is a `RootModel`
+        post_init: The call after init to use for the model
+        revalidate_instances: whether instances of models and dataclasses (including subclass instances)
+            should re-validate defaults to config.revalidate_instances, else 'never'
+        strict: Whether the model is strict
+        frozen: Whether the model is frozen
+        extra_behavior: The extra behavior to use for the model, used in serialization
+        config: The config to use for the model
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='model',
+        cls=cls,
+        generic_origin=generic_origin,
+        schema=schema,
+        custom_init=custom_init,
+        root_model=root_model,
+        post_init=post_init,
+        revalidate_instances=revalidate_instances,
+        strict=strict,
+        frozen=frozen,
+        extra_behavior=extra_behavior,
+        config=config,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class DataclassField(TypedDict, total=False):
+    type: Required[Literal['dataclass-field']]
+    name: Required[str]
+    schema: Required[CoreSchema]
+    kw_only: bool  # default: True
+    init: bool  # default: True
+    init_only: bool  # default: False
+    frozen: bool  # default: False
+    validation_alias: Union[str, list[Union[str, int]], list[list[Union[str, int]]]]
+    serialization_alias: str
+    serialization_exclude: bool  # default: False
+    metadata: dict[str, Any]
+    serialization_exclude_if: Callable[[Any], bool]  # default: None
+
+
+def dataclass_field(
+    name: str,
+    schema: CoreSchema,
+    *,
+    kw_only: bool | None = None,
+    init: bool | None = None,
+    init_only: bool | None = None,
+    validation_alias: str | list[str | int] | list[list[str | int]] | None = None,
+    serialization_alias: str | None = None,
+    serialization_exclude: bool | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization_exclude_if: Callable[[Any], bool] | None = None,
+    frozen: bool | None = None,
+) -> DataclassField:
+    """
+    Returns a schema for a dataclass field, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    field = core_schema.dataclass_field(
+        name='a', schema=core_schema.str_schema(), kw_only=False
+    )
+    schema = core_schema.dataclass_args_schema('Foobar', [field])
+    v = SchemaValidator(schema)
+    assert v.validate_python({'a': 'hello'}) == ({'a': 'hello'}, None)
+    ```
+
+    Args:
+        name: The name to use for the argument parameter
+        schema: The schema to use for the argument parameter
+        kw_only: Whether the field can be set with a positional argument as well as a keyword argument
+        init: Whether the field should be validated during initialization
+        init_only: Whether the field should be omitted  from `__dict__` and passed to `__post_init__`
+        validation_alias: The alias(es) to use to find the field in the validation data
+        serialization_alias: The alias to use as a key when serializing
+        serialization_exclude: Whether to exclude the field when serializing
+        serialization_exclude_if: A callable that determines whether to exclude the field when serializing based on its value.
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        frozen: Whether the field is frozen
+    """
+    return _dict_not_none(
+        type='dataclass-field',
+        name=name,
+        schema=schema,
+        kw_only=kw_only,
+        init=init,
+        init_only=init_only,
+        validation_alias=validation_alias,
+        serialization_alias=serialization_alias,
+        serialization_exclude=serialization_exclude,
+        serialization_exclude_if=serialization_exclude_if,
+        metadata=metadata,
+        frozen=frozen,
+    )
+
+
+class DataclassArgsSchema(TypedDict, total=False):
+    type: Required[Literal['dataclass-args']]
+    dataclass_name: Required[str]
+    fields: Required[list[DataclassField]]
+    computed_fields: list[ComputedField]
+    collect_init_only: bool  # default: False
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+    extra_behavior: ExtraBehavior
+
+
+def dataclass_args_schema(
+    dataclass_name: str,
+    fields: list[DataclassField],
+    *,
+    computed_fields: list[ComputedField] | None = None,
+    collect_init_only: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+    extra_behavior: ExtraBehavior | None = None,
+) -> DataclassArgsSchema:
+    """
+    Returns a schema for validating dataclass arguments, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    field_a = core_schema.dataclass_field(
+        name='a', schema=core_schema.str_schema(), kw_only=False
+    )
+    field_b = core_schema.dataclass_field(
+        name='b', schema=core_schema.bool_schema(), kw_only=False
+    )
+    schema = core_schema.dataclass_args_schema('Foobar', [field_a, field_b])
+    v = SchemaValidator(schema)
+    assert v.validate_python({'a': 'hello', 'b': True}) == ({'a': 'hello', 'b': True}, None)
+    ```
+
+    Args:
+        dataclass_name: The name of the dataclass being validated
+        fields: The fields to use for the dataclass
+        computed_fields: Computed fields to use when serializing the dataclass
+        collect_init_only: Whether to collect init only fields into a dict to pass to `__post_init__`
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+        extra_behavior: How to handle extra fields
+    """
+    return _dict_not_none(
+        type='dataclass-args',
+        dataclass_name=dataclass_name,
+        fields=fields,
+        computed_fields=computed_fields,
+        collect_init_only=collect_init_only,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+        extra_behavior=extra_behavior,
+    )
+
+
+class DataclassSchema(TypedDict, total=False):
+    type: Required[Literal['dataclass']]
+    cls: Required[type[Any]]
+    generic_origin: type[Any]
+    schema: Required[CoreSchema]
+    fields: Required[list[str]]
+    cls_name: str
+    post_init: bool  # default: False
+    revalidate_instances: Literal['always', 'never', 'subclass-instances']  # default: 'never'
+    strict: bool  # default: False
+    frozen: bool  # default False
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+    slots: bool
+    config: CoreConfig
+
+
+def dataclass_schema(
+    cls: type[Any],
+    schema: CoreSchema,
+    fields: list[str],
+    *,
+    generic_origin: type[Any] | None = None,
+    cls_name: str | None = None,
+    post_init: bool | None = None,
+    revalidate_instances: Literal['always', 'never', 'subclass-instances'] | None = None,
+    strict: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+    frozen: bool | None = None,
+    slots: bool | None = None,
+    config: CoreConfig | None = None,
+) -> DataclassSchema:
+    """
+    Returns a schema for a dataclass. As with `ModelSchema`, this schema can only be used as a field within
+    another schema, not as the root type.
+
+    Args:
+        cls: The dataclass type, used to perform subclass checks
+        schema: The schema to use for the dataclass fields
+        fields: Fields of the dataclass, this is used in serialization and in validation during re-validation
+            and while validating assignment
+        generic_origin: The origin type used for this dataclass, if it's a parametrized generic. Ex,
+            if this model schema represents `SomeDataclass[int]`, generic_origin is `SomeDataclass`
+        cls_name: The name to use in error locs, etc; this is useful for generics (default: `cls.__name__`)
+        post_init: Whether to call `__post_init__` after validation
+        revalidate_instances: whether instances of models and dataclasses (including subclass instances)
+            should re-validate defaults to config.revalidate_instances, else 'never'
+        strict: Whether to require an exact instance of `cls`
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+        frozen: Whether the dataclass is frozen
+        slots: Whether `slots=True` on the dataclass, means each field is assigned independently, rather than
+            simply setting `__dict__`, default false
+    """
+    return _dict_not_none(
+        type='dataclass',
+        cls=cls,
+        generic_origin=generic_origin,
+        fields=fields,
+        cls_name=cls_name,
+        schema=schema,
+        post_init=post_init,
+        revalidate_instances=revalidate_instances,
+        strict=strict,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+        frozen=frozen,
+        slots=slots,
+        config=config,
+    )
+
+
+class ArgumentsParameter(TypedDict, total=False):
+    name: Required[str]
+    schema: Required[CoreSchema]
+    mode: Literal['positional_only', 'positional_or_keyword', 'keyword_only']  # default positional_or_keyword
+    alias: Union[str, list[Union[str, int]], list[list[Union[str, int]]]]
+
+
+def arguments_parameter(
+    name: str,
+    schema: CoreSchema,
+    *,
+    mode: Literal['positional_only', 'positional_or_keyword', 'keyword_only'] | None = None,
+    alias: str | list[str | int] | list[list[str | int]] | None = None,
+) -> ArgumentsParameter:
+    """
+    Returns a schema that matches an argument parameter, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    param = core_schema.arguments_parameter(
+        name='a', schema=core_schema.str_schema(), mode='positional_only'
+    )
+    schema = core_schema.arguments_schema([param])
+    v = SchemaValidator(schema)
+    assert v.validate_python(('hello',)) == (('hello',), {})
+    ```
+
+    Args:
+        name: The name to use for the argument parameter
+        schema: The schema to use for the argument parameter
+        mode: The mode to use for the argument parameter
+        alias: The alias to use for the argument parameter
+    """
+    return _dict_not_none(name=name, schema=schema, mode=mode, alias=alias)
+
+
+VarKwargsMode: TypeAlias = Literal['uniform', 'unpacked-typed-dict']
+
+
+class ArgumentsSchema(TypedDict, total=False):
+    type: Required[Literal['arguments']]
+    arguments_schema: Required[list[ArgumentsParameter]]
+    validate_by_name: bool
+    validate_by_alias: bool
+    var_args_schema: CoreSchema
+    var_kwargs_mode: VarKwargsMode
+    var_kwargs_schema: CoreSchema
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def arguments_schema(
+    arguments: list[ArgumentsParameter],
+    *,
+    validate_by_name: bool | None = None,
+    validate_by_alias: bool | None = None,
+    var_args_schema: CoreSchema | None = None,
+    var_kwargs_mode: VarKwargsMode | None = None,
+    var_kwargs_schema: CoreSchema | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> ArgumentsSchema:
+    """
+    Returns a schema that matches an arguments schema, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    param_a = core_schema.arguments_parameter(
+        name='a', schema=core_schema.str_schema(), mode='positional_only'
+    )
+    param_b = core_schema.arguments_parameter(
+        name='b', schema=core_schema.bool_schema(), mode='positional_only'
+    )
+    schema = core_schema.arguments_schema([param_a, param_b])
+    v = SchemaValidator(schema)
+    assert v.validate_python(('hello', True)) == (('hello', True), {})
+    ```
+
+    Args:
+        arguments: The arguments to use for the arguments schema
+        validate_by_name: Whether to populate by the parameter names, defaults to `False`.
+        validate_by_alias: Whether to populate by the parameter aliases, defaults to `True`.
+        var_args_schema: The variable args schema to use for the arguments schema
+        var_kwargs_mode: The validation mode to use for variadic keyword arguments. If `'uniform'`, every value of the
+            keyword arguments will be validated against the `var_kwargs_schema` schema. If `'unpacked-typed-dict'`,
+            the `var_kwargs_schema` argument must be a [`typed_dict_schema`][pydantic_core.core_schema.typed_dict_schema]
+        var_kwargs_schema: The variable kwargs schema to use for the arguments schema
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='arguments',
+        arguments_schema=arguments,
+        validate_by_name=validate_by_name,
+        validate_by_alias=validate_by_alias,
+        var_args_schema=var_args_schema,
+        var_kwargs_mode=var_kwargs_mode,
+        var_kwargs_schema=var_kwargs_schema,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class ArgumentsV3Parameter(TypedDict, total=False):
+    name: Required[str]
+    schema: Required[CoreSchema]
+    mode: Literal[
+        'positional_only',
+        'positional_or_keyword',
+        'keyword_only',
+        'var_args',
+        'var_kwargs_uniform',
+        'var_kwargs_unpacked_typed_dict',
+    ]  # default positional_or_keyword
+    alias: Union[str, list[Union[str, int]], list[list[Union[str, int]]]]
+
+
+def arguments_v3_parameter(
+    name: str,
+    schema: CoreSchema,
+    *,
+    mode: Literal[
+        'positional_only',
+        'positional_or_keyword',
+        'keyword_only',
+        'var_args',
+        'var_kwargs_uniform',
+        'var_kwargs_unpacked_typed_dict',
+    ]
+    | None = None,
+    alias: str | list[str | int] | list[list[str | int]] | None = None,
+) -> ArgumentsV3Parameter:
+    """
+    Returns a schema that matches an argument parameter, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    param = core_schema.arguments_v3_parameter(
+        name='a', schema=core_schema.str_schema(), mode='positional_only'
+    )
+    schema = core_schema.arguments_v3_schema([param])
+    v = SchemaValidator(schema)
+    assert v.validate_python({'a': 'hello'}) == (('hello',), {})
+    ```
+
+    Args:
+        name: The name to use for the argument parameter
+        schema: The schema to use for the argument parameter
+        mode: The mode to use for the argument parameter
+        alias: The alias to use for the argument parameter
+    """
+    return _dict_not_none(name=name, schema=schema, mode=mode, alias=alias)
+
+
+class ArgumentsV3Schema(TypedDict, total=False):
+    type: Required[Literal['arguments-v3']]
+    arguments_schema: Required[list[ArgumentsV3Parameter]]
+    validate_by_name: bool
+    validate_by_alias: bool
+    extra_behavior: Literal['forbid', 'ignore']  # 'allow' doesn't make sense here.
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def arguments_v3_schema(
+    arguments: list[ArgumentsV3Parameter],
+    *,
+    validate_by_name: bool | None = None,
+    validate_by_alias: bool | None = None,
+    extra_behavior: Literal['forbid', 'ignore'] | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> ArgumentsV3Schema:
+    """
+    Returns a schema that matches an arguments schema, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    param_a = core_schema.arguments_v3_parameter(
+        name='a', schema=core_schema.str_schema(), mode='positional_only'
+    )
+    param_b = core_schema.arguments_v3_parameter(
+        name='kwargs', schema=core_schema.bool_schema(), mode='var_kwargs_uniform'
+    )
+    schema = core_schema.arguments_v3_schema([param_a, param_b])
+    v = SchemaValidator(schema)
+    assert v.validate_python({'a': 'hi', 'kwargs': {'b': True}}) == (('hi',), {'b': True})
+    ```
+
+    This schema is currently not used by other Pydantic components. In V3, it will most likely
+    become the default arguments schema for the `'call'` schema.
+
+    Args:
+        arguments: The arguments to use for the arguments schema.
+        validate_by_name: Whether to populate by the parameter names, defaults to `False`.
+        validate_by_alias: Whether to populate by the parameter aliases, defaults to `True`.
+        extra_behavior: The extra behavior to use.
+        ref: optional unique identifier of the schema, used to reference the schema in other places.
+        metadata: Any other information you want to include with the schema, not used by pydantic-core.
+        serialization: Custom serialization schema.
+    """
+    return _dict_not_none(
+        type='arguments-v3',
+        arguments_schema=arguments,
+        validate_by_name=validate_by_name,
+        validate_by_alias=validate_by_alias,
+        extra_behavior=extra_behavior,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class CallSchema(TypedDict, total=False):
+    type: Required[Literal['call']]
+    arguments_schema: Required[CoreSchema]
+    function: Required[Callable[..., Any]]
+    function_name: str  # default function.__name__
+    return_schema: CoreSchema
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def call_schema(
+    arguments: CoreSchema,
+    function: Callable[..., Any],
+    *,
+    function_name: str | None = None,
+    return_schema: CoreSchema | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> CallSchema:
+    """
+    Returns a schema that matches an arguments schema, then calls a function, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    param_a = core_schema.arguments_parameter(
+        name='a', schema=core_schema.str_schema(), mode='positional_only'
+    )
+    param_b = core_schema.arguments_parameter(
+        name='b', schema=core_schema.bool_schema(), mode='positional_only'
+    )
+    args_schema = core_schema.arguments_schema([param_a, param_b])
+
+    schema = core_schema.call_schema(
+        arguments=args_schema,
+        function=lambda a, b: a + str(not b),
+        return_schema=core_schema.str_schema(),
+    )
+    v = SchemaValidator(schema)
+    assert v.validate_python((('hello', True))) == 'helloFalse'
+    ```
+
+    Args:
+        arguments: The arguments to use for the arguments schema
+        function: The function to use for the call schema
+        function_name: The function name to use for the call schema, if not provided `function.__name__` is used
+        return_schema: The return schema to use for the call schema
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='call',
+        arguments_schema=arguments,
+        function=function,
+        function_name=function_name,
+        return_schema=return_schema,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class CustomErrorSchema(TypedDict, total=False):
+    type: Required[Literal['custom-error']]
+    schema: Required[CoreSchema]
+    custom_error_type: Required[str]
+    custom_error_message: str
+    custom_error_context: dict[str, Union[str, int, float]]
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def custom_error_schema(
+    schema: CoreSchema,
+    custom_error_type: str,
+    *,
+    custom_error_message: str | None = None,
+    custom_error_context: dict[str, Any] | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> CustomErrorSchema:
+    """
+    Returns a schema that matches a custom error value, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.custom_error_schema(
+        schema=core_schema.int_schema(),
+        custom_error_type='MyError',
+        custom_error_message='Error msg',
+    )
+    v = SchemaValidator(schema)
+    v.validate_python(1)
+    ```
+
+    Args:
+        schema: The schema to use for the custom error schema
+        custom_error_type: The custom error type to use for the custom error schema
+        custom_error_message: The custom error message to use for the custom error schema
+        custom_error_context: The custom error context to use for the custom error schema
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='custom-error',
+        schema=schema,
+        custom_error_type=custom_error_type,
+        custom_error_message=custom_error_message,
+        custom_error_context=custom_error_context,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class JsonSchema(TypedDict, total=False):
+    type: Required[Literal['json']]
+    schema: CoreSchema
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def json_schema(
+    schema: CoreSchema | None = None,
+    *,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> JsonSchema:
+    """
+    Returns a schema that matches a JSON value, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    dict_schema = core_schema.model_fields_schema(
+        {
+            'field_a': core_schema.model_field(core_schema.str_schema()),
+            'field_b': core_schema.model_field(core_schema.bool_schema()),
+        },
+    )
+
+    class MyModel:
+        __slots__ = (
+            '__dict__',
+            '__pydantic_fields_set__',
+            '__pydantic_extra__',
+            '__pydantic_private__',
+        )
+        field_a: str
+        field_b: bool
+
+    json_schema = core_schema.json_schema(schema=dict_schema)
+    schema = core_schema.model_schema(cls=MyModel, schema=json_schema)
+    v = SchemaValidator(schema)
+    m = v.validate_python('{"field_a": "hello", "field_b": true}')
+    assert isinstance(m, MyModel)
+    ```
+
+    Args:
+        schema: The schema to use for the JSON schema
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(type='json', schema=schema, ref=ref, metadata=metadata, serialization=serialization)
+
+
+class UrlSchema(TypedDict, total=False):
+    type: Required[Literal['url']]
+    max_length: int
+    allowed_schemes: list[str]
+    host_required: bool  # default False
+    default_host: str
+    default_port: int
+    default_path: str
+    strict: bool
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def url_schema(
+    *,
+    max_length: int | None = None,
+    allowed_schemes: list[str] | None = None,
+    host_required: bool | None = None,
+    default_host: str | None = None,
+    default_port: int | None = None,
+    default_path: str | None = None,
+    preserve_empty_path: bool | None = None,
+    strict: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> UrlSchema:
+    """
+    Returns a schema that matches a URL value, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.url_schema()
+    v = SchemaValidator(schema)
+    print(v.validate_python('https://example.com'))
+    #> https://example.com/
+    ```
+
+    Args:
+        max_length: The maximum length of the URL
+        allowed_schemes: The allowed URL schemes
+        host_required: Whether the URL must have a host
+        default_host: The default host to use if the URL does not have a host
+        default_port: The default port to use if the URL does not have a port
+        default_path: The default path to use if the URL does not have a path
+        preserve_empty_path: Whether to preserve an empty path or convert it to '/', default False
+        strict: Whether to use strict URL parsing
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='url',
+        max_length=max_length,
+        allowed_schemes=allowed_schemes,
+        host_required=host_required,
+        default_host=default_host,
+        default_port=default_port,
+        default_path=default_path,
+        preserve_empty_path=preserve_empty_path,
+        strict=strict,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class MultiHostUrlSchema(TypedDict, total=False):
+    type: Required[Literal['multi-host-url']]
+    max_length: int
+    allowed_schemes: list[str]
+    host_required: bool  # default False
+    default_host: str
+    default_port: int
+    default_path: str
+    strict: bool
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def multi_host_url_schema(
+    *,
+    max_length: int | None = None,
+    allowed_schemes: list[str] | None = None,
+    host_required: bool | None = None,
+    default_host: str | None = None,
+    default_port: int | None = None,
+    default_path: str | None = None,
+    preserve_empty_path: bool | None = None,
+    strict: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> MultiHostUrlSchema:
+    """
+    Returns a schema that matches a URL value with possibly multiple hosts, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.multi_host_url_schema()
+    v = SchemaValidator(schema)
+    print(v.validate_python('redis://localhost,0.0.0.0,127.0.0.1'))
+    #> redis://localhost,0.0.0.0,127.0.0.1
+    ```
+
+    Args:
+        max_length: The maximum length of the URL
+        allowed_schemes: The allowed URL schemes
+        host_required: Whether the URL must have a host
+        default_host: The default host to use if the URL does not have a host
+        default_port: The default port to use if the URL does not have a port
+        default_path: The default path to use if the URL does not have a path
+        preserve_empty_path: Whether to preserve an empty path or convert it to '/', default False
+        strict: Whether to use strict URL parsing
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='multi-host-url',
+        max_length=max_length,
+        allowed_schemes=allowed_schemes,
+        host_required=host_required,
+        default_host=default_host,
+        default_port=default_port,
+        default_path=default_path,
+        preserve_empty_path=preserve_empty_path,
+        strict=strict,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class DefinitionsSchema(TypedDict, total=False):
+    type: Required[Literal['definitions']]
+    schema: Required[CoreSchema]
+    definitions: Required[list[CoreSchema]]
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def definitions_schema(schema: CoreSchema, definitions: list[CoreSchema]) -> DefinitionsSchema:
+    """
+    Build a schema that contains both an inner schema and a list of definitions which can be used
+    within the inner schema.
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.definitions_schema(
+        core_schema.list_schema(core_schema.definition_reference_schema('foobar')),
+        [core_schema.int_schema(ref='foobar')],
+    )
+    v = SchemaValidator(schema)
+    assert v.validate_python([1, 2, '3']) == [1, 2, 3]
+    ```
+
+    Args:
+        schema: The inner schema
+        definitions: List of definitions which can be referenced within inner schema
+    """
+    return DefinitionsSchema(type='definitions', schema=schema, definitions=definitions)
+
+
+class DefinitionReferenceSchema(TypedDict, total=False):
+    type: Required[Literal['definition-ref']]
+    schema_ref: Required[str]
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def definition_reference_schema(
+    schema_ref: str,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> DefinitionReferenceSchema:
+    """
+    Returns a schema that points to a schema stored in "definitions", this is useful for nested recursive
+    models and also when you want to define validators separately from the main schema, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema_definition = core_schema.definition_reference_schema('list-schema')
+    schema = core_schema.definitions_schema(
+        schema=schema_definition,
+        definitions=[
+            core_schema.list_schema(items_schema=schema_definition, ref='list-schema'),
+        ],
+    )
+    v = SchemaValidator(schema)
+    assert v.validate_python([()]) == [[]]
+    ```
+
+    Args:
+        schema_ref: The schema ref to use for the definition reference schema
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='definition-ref', schema_ref=schema_ref, ref=ref, metadata=metadata, serialization=serialization
+    )
+
+
+MYPY = False
+# See https://github.com/python/mypy/issues/14034 for details, in summary mypy is extremely slow to process this
+# union which kills performance not just for pydantic, but even for code using pydantic
+if not MYPY:
+    CoreSchema = Union[
+        InvalidSchema,
+        AnySchema,
+        NoneSchema,
+        BoolSchema,
+        IntSchema,
+        FloatSchema,
+        DecimalSchema,
+        StringSchema,
+        BytesSchema,
+        DateSchema,
+        TimeSchema,
+        DatetimeSchema,
+        TimedeltaSchema,
+        LiteralSchema,
+        MissingSentinelSchema,
+        EnumSchema,
+        IsInstanceSchema,
+        IsSubclassSchema,
+        CallableSchema,
+        ListSchema,
+        TupleSchema,
+        SetSchema,
+        FrozenSetSchema,
+        GeneratorSchema,
+        DictSchema,
+        AfterValidatorFunctionSchema,
+        BeforeValidatorFunctionSchema,
+        WrapValidatorFunctionSchema,
+        PlainValidatorFunctionSchema,
+        WithDefaultSchema,
+        NullableSchema,
+        UnionSchema,
+        TaggedUnionSchema,
+        ChainSchema,
+        LaxOrStrictSchema,
+        JsonOrPythonSchema,
+        TypedDictSchema,
+        ModelFieldsSchema,
+        ModelSchema,
+        DataclassArgsSchema,
+        DataclassSchema,
+        ArgumentsSchema,
+        ArgumentsV3Schema,
+        CallSchema,
+        CustomErrorSchema,
+        JsonSchema,
+        UrlSchema,
+        MultiHostUrlSchema,
+        DefinitionsSchema,
+        DefinitionReferenceSchema,
+        UuidSchema,
+        ComplexSchema,
+    ]
+elif False:
+    CoreSchema: TypeAlias = Mapping[str, Any]
+
+
+# to update this, call `pytest -k test_core_schema_type_literal` and copy the output
+CoreSchemaType = Literal[
+    'invalid',
+    'any',
+    'none',
+    'bool',
+    'int',
+    'float',
+    'decimal',
+    'str',
+    'bytes',
+    'date',
+    'time',
+    'datetime',
+    'timedelta',
+    'literal',
+    'missing-sentinel',
+    'enum',
+    'is-instance',
+    'is-subclass',
+    'callable',
+    'list',
+    'tuple',
+    'set',
+    'frozenset',
+    'generator',
+    'dict',
+    'function-after',
+    'function-before',
+    'function-wrap',
+    'function-plain',
+    'default',
+    'nullable',
+    'union',
+    'tagged-union',
+    'chain',
+    'lax-or-strict',
+    'json-or-python',
+    'typed-dict',
+    'model-fields',
+    'model',
+    'dataclass-args',
+    'dataclass',
+    'arguments',
+    'arguments-v3',
+    'call',
+    'custom-error',
+    'json',
+    'url',
+    'multi-host-url',
+    'definitions',
+    'definition-ref',
+    'uuid',
+    'complex',
+]
+
+CoreSchemaFieldType = Literal['model-field', 'dataclass-field', 'typed-dict-field', 'computed-field']
+
+
+# used in _pydantic_core.pyi::PydanticKnownError
+# to update this, call `pytest -k test_all_errors` and copy the output
+ErrorType = Literal[
+    'no_such_attribute',
+    'json_invalid',
+    'json_type',
+    'needs_python_object',
+    'recursion_loop',
+    'missing',
+    'frozen_field',
+    'frozen_instance',
+    'extra_forbidden',
+    'invalid_key',
+    'get_attribute_error',
+    'model_type',
+    'model_attributes_type',
+    'dataclass_type',
+    'dataclass_exact_type',
+    'default_factory_not_called',
+    'none_required',
+    'greater_than',
+    'greater_than_equal',
+    'less_than',
+    'less_than_equal',
+    'multiple_of',
+    'finite_number',
+    'too_short',
+    'too_long',
+    'iterable_type',
+    'iteration_error',
+    'string_type',
+    'string_sub_type',
+    'string_unicode',
+    'string_too_short',
+    'string_too_long',
+    'string_pattern_mismatch',
+    'enum',
+    'dict_type',
+    'mapping_type',
+    'list_type',
+    'tuple_type',
+    'set_type',
+    'set_item_not_hashable',
+    'bool_type',
+    'bool_parsing',
+    'int_type',
+    'int_parsing',
+    'int_parsing_size',
+    'int_from_float',
+    'float_type',
+    'float_parsing',
+    'bytes_type',
+    'bytes_too_short',
+    'bytes_too_long',
+    'bytes_invalid_encoding',
+    'value_error',
+    'assertion_error',
+    'literal_error',
+    'missing_sentinel_error',
+    'date_type',
+    'date_parsing',
+    'date_from_datetime_parsing',
+    'date_from_datetime_inexact',
+    'date_past',
+    'date_future',
+    'time_type',
+    'time_parsing',
+    'datetime_type',
+    'datetime_parsing',
+    'datetime_object_invalid',
+    'datetime_from_date_parsing',
+    'datetime_past',
+    'datetime_future',
+    'timezone_naive',
+    'timezone_aware',
+    'timezone_offset',
+    'time_delta_type',
+    'time_delta_parsing',
+    'frozen_set_type',
+    'is_instance_of',
+    'is_subclass_of',
+    'callable_type',
+    'union_tag_invalid',
+    'union_tag_not_found',
+    'arguments_type',
+    'missing_argument',
+    'unexpected_keyword_argument',
+    'missing_keyword_only_argument',
+    'unexpected_positional_argument',
+    'missing_positional_only_argument',
+    'multiple_argument_values',
+    'url_type',
+    'url_parsing',
+    'url_syntax_violation',
+    'url_too_long',
+    'url_scheme',
+    'uuid_type',
+    'uuid_parsing',
+    'uuid_version',
+    'decimal_type',
+    'decimal_parsing',
+    'decimal_max_digits',
+    'decimal_max_places',
+    'decimal_whole_digits',
+    'complex_type',
+    'complex_str_parsing',
+]
+
+
+def _dict_not_none(**kwargs: Any) -> Any:
+    return {k: v for k, v in kwargs.items() if v is not None}
+
+
+###############################################################################
+# All this stuff is deprecated by #980 and will be removed eventually
+# They're kept because some code external code will be using them
+
+
+@deprecated('`field_before_validator_function` is deprecated, use `with_info_before_validator_function` instead.')
+def field_before_validator_function(function: WithInfoValidatorFunction, field_name: str, schema: CoreSchema, **kwargs):
+    warnings.warn(
+        '`field_before_validator_function` is deprecated, use `with_info_before_validator_function` instead.',
+        DeprecationWarning,
+    )
+    return with_info_before_validator_function(function, schema, field_name=field_name, **kwargs)
+
+
+@deprecated('`general_before_validator_function` is deprecated, use `with_info_before_validator_function` instead.')
+def general_before_validator_function(*args, **kwargs):
+    warnings.warn(
+        '`general_before_validator_function` is deprecated, use `with_info_before_validator_function` instead.',
+        DeprecationWarning,
+    )
+    return with_info_before_validator_function(*args, **kwargs)
+
+
+@deprecated('`field_after_validator_function` is deprecated, use `with_info_after_validator_function` instead.')
+def field_after_validator_function(function: WithInfoValidatorFunction, field_name: str, schema: CoreSchema, **kwargs):
+    warnings.warn(
+        '`field_after_validator_function` is deprecated, use `with_info_after_validator_function` instead.',
+        DeprecationWarning,
+    )
+    return with_info_after_validator_function(function, schema, field_name=field_name, **kwargs)
+
+
+@deprecated('`general_after_validator_function` is deprecated, use `with_info_after_validator_function` instead.')
+def general_after_validator_function(*args, **kwargs):
+    warnings.warn(
+        '`general_after_validator_function` is deprecated, use `with_info_after_validator_function` instead.',
+        DeprecationWarning,
+    )
+    return with_info_after_validator_function(*args, **kwargs)
+
+
+@deprecated('`field_wrap_validator_function` is deprecated, use `with_info_wrap_validator_function` instead.')
+def field_wrap_validator_function(
+    function: WithInfoWrapValidatorFunction, field_name: str, schema: CoreSchema, **kwargs
+):
+    warnings.warn(
+        '`field_wrap_validator_function` is deprecated, use `with_info_wrap_validator_function` instead.',
+        DeprecationWarning,
+    )
+    return with_info_wrap_validator_function(function, schema, field_name=field_name, **kwargs)
+
+
+@deprecated('`general_wrap_validator_function` is deprecated, use `with_info_wrap_validator_function` instead.')
+def general_wrap_validator_function(*args, **kwargs):
+    warnings.warn(
+        '`general_wrap_validator_function` is deprecated, use `with_info_wrap_validator_function` instead.',
+        DeprecationWarning,
+    )
+    return with_info_wrap_validator_function(*args, **kwargs)
+
+
+@deprecated('`field_plain_validator_function` is deprecated, use `with_info_plain_validator_function` instead.')
+def field_plain_validator_function(function: WithInfoValidatorFunction, field_name: str, **kwargs):
+    warnings.warn(
+        '`field_plain_validator_function` is deprecated, use `with_info_plain_validator_function` instead.',
+        DeprecationWarning,
+    )
+    return with_info_plain_validator_function(function, field_name=field_name, **kwargs)
+
+
+@deprecated('`general_plain_validator_function` is deprecated, use `with_info_plain_validator_function` instead.')
+def general_plain_validator_function(*args, **kwargs):
+    warnings.warn(
+        '`general_plain_validator_function` is deprecated, use `with_info_plain_validator_function` instead.',
+        DeprecationWarning,
+    )
+    return with_info_plain_validator_function(*args, **kwargs)
+
+
+_deprecated_import_lookup = {
+    'FieldValidationInfo': ValidationInfo,
+    'FieldValidatorFunction': WithInfoValidatorFunction,
+    'GeneralValidatorFunction': WithInfoValidatorFunction,
+    'FieldWrapValidatorFunction': WithInfoWrapValidatorFunction,
+}
+
+if TYPE_CHECKING:
+    FieldValidationInfo = ValidationInfo
+
+
+def __getattr__(attr_name: str) -> object:
+    new_attr = _deprecated_import_lookup.get(attr_name)
+    if new_attr is None:
+        raise AttributeError(f"module 'pydantic_core' has no attribute '{attr_name}'")
+    else:
+        import warnings
+
+        msg = f'`{attr_name}` is deprecated, use `{new_attr.__name__}` instead.'
+        warnings.warn(msg, DeprecationWarning, stacklevel=1)
+        return new_attr
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pydantic_core/py.typed b/TTS/Kokoro/.venv/Lib/site-packages/pydantic_core/py.typed
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pygments-2.19.2.dist-info/INSTALLER b/TTS/Kokoro/.venv/Lib/site-packages/pygments-2.19.2.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pygments-2.19.2.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pygments-2.19.2.dist-info/METADATA b/TTS/Kokoro/.venv/Lib/site-packages/pygments-2.19.2.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..2eff6a0c3865f050611859a41df6bf81aaf4f88e
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pygments-2.19.2.dist-info/METADATA
@@ -0,0 +1,58 @@
+Metadata-Version: 2.4
+Name: Pygments
+Version: 2.19.2
+Summary: Pygments is a syntax highlighting package written in Python.
+Project-URL: Homepage, https://pygments.org
+Project-URL: Documentation, https://pygments.org/docs
+Project-URL: Source, https://github.com/pygments/pygments
+Project-URL: Bug Tracker, https://github.com/pygments/pygments/issues
+Project-URL: Changelog, https://github.com/pygments/pygments/blob/master/CHANGES
+Author-email: Georg Brandl 
+Maintainer: Matthäus G. Chajdas
+Maintainer-email: Georg Brandl , Jean Abou Samra 
+License: BSD-2-Clause
+License-File: AUTHORS
+License-File: LICENSE
+Keywords: syntax highlighting
+Classifier: Development Status :: 6 - Mature
+Classifier: Intended Audience :: Developers
+Classifier: Intended Audience :: End Users/Desktop
+Classifier: Intended Audience :: System Administrators
+Classifier: License :: OSI Approved :: BSD License
+Classifier: Operating System :: OS Independent
+Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3.8
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Classifier: Programming Language :: Python :: 3.13
+Classifier: Programming Language :: Python :: Implementation :: CPython
+Classifier: Programming Language :: Python :: Implementation :: PyPy
+Classifier: Topic :: Text Processing :: Filters
+Classifier: Topic :: Utilities
+Requires-Python: >=3.8
+Provides-Extra: plugins
+Provides-Extra: windows-terminal
+Requires-Dist: colorama>=0.4.6; extra == 'windows-terminal'
+Description-Content-Type: text/x-rst
+
+Pygments
+~~~~~~~~
+
+Pygments is a syntax highlighting package written in Python.
+
+It is a generic syntax highlighter suitable for use in code hosting, forums,
+wikis or other applications that need to prettify source code.  Highlights
+are:
+
+* a wide range of over 500 languages and other text formats is supported
+* special attention is paid to details, increasing quality by a fair amount
+* support for new languages and formats are added easily
+* a number of output formats, presently HTML, LaTeX, RTF, SVG, all image
+  formats that PIL supports and ANSI sequences
+* it is usable as a command-line tool and as a library
+
+Copyright 2006-2025 by the Pygments team, see ``AUTHORS``.
+Licensed under the BSD, see ``LICENSE`` for details.
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pygments-2.19.2.dist-info/RECORD b/TTS/Kokoro/.venv/Lib/site-packages/pygments-2.19.2.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..eebdae7550663ff958ec287410b341e724e4ddd9
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pygments-2.19.2.dist-info/RECORD
@@ -0,0 +1,684 @@
+../../Scripts/pygmentize.exe,sha256=T25pjrI0wQvguuJE_0s9YG9HobfXWgaGDDFoLe8u_7Y,108379
+pygments-2.19.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+pygments-2.19.2.dist-info/METADATA,sha256=euEA1n1nAGxkeYA92DX89HqbWfrHlEQeqOZqp_WYTYI,2512
+pygments-2.19.2.dist-info/RECORD,,
+pygments-2.19.2.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
+pygments-2.19.2.dist-info/entry_points.txt,sha256=uUXw-XhMKBEX4pWcCtpuTTnPhL3h7OEE2jWi51VQsa8,53
+pygments-2.19.2.dist-info/licenses/AUTHORS,sha256=BmDjGKbyFYAq3Icxq4XQxl_yfPzKP10oWX8wZHYZW9k,10824
+pygments-2.19.2.dist-info/licenses/LICENSE,sha256=qdZvHVJt8C4p3Oc0NtNOVuhjL0bCdbvf_HBWnogvnxc,1331
+pygments/__init__.py,sha256=_3UT86TGpHuW8FekdZ8uLidEZH1NhmcLiOy2KKNPCt4,2959
+pygments/__main__.py,sha256=p8AJyoyCOMYGvzWHdnq0_A9qaaVqaj02nIu3xhJp1_4,348
+pygments/__pycache__/__init__.cpython-312.pyc,,
+pygments/__pycache__/__main__.cpython-312.pyc,,
+pygments/__pycache__/cmdline.cpython-312.pyc,,
+pygments/__pycache__/console.cpython-312.pyc,,
+pygments/__pycache__/filter.cpython-312.pyc,,
+pygments/__pycache__/formatter.cpython-312.pyc,,
+pygments/__pycache__/lexer.cpython-312.pyc,,
+pygments/__pycache__/modeline.cpython-312.pyc,,
+pygments/__pycache__/plugin.cpython-312.pyc,,
+pygments/__pycache__/regexopt.cpython-312.pyc,,
+pygments/__pycache__/scanner.cpython-312.pyc,,
+pygments/__pycache__/sphinxext.cpython-312.pyc,,
+pygments/__pycache__/style.cpython-312.pyc,,
+pygments/__pycache__/token.cpython-312.pyc,,
+pygments/__pycache__/unistring.cpython-312.pyc,,
+pygments/__pycache__/util.cpython-312.pyc,,
+pygments/cmdline.py,sha256=4pL9Kpn2PUEKPobgrsQgg-vCx2NjsrapKzQ6LxQR7Q0,23536
+pygments/console.py,sha256=AagDWqwea2yBWf10KC9ptBgMpMjxKp8yABAmh-NQOVk,1718
+pygments/filter.py,sha256=YLtpTnZiu07nY3oK9nfR6E9Y1FBHhP5PX8gvkJWcfag,1910
+pygments/filters/__init__.py,sha256=B00KqPCQh5E0XhzaDK74Qa1E4fDSTlD6b0Pvr1v-vEQ,40344
+pygments/filters/__pycache__/__init__.cpython-312.pyc,,
+pygments/formatter.py,sha256=H_4J-moKkKfRWUOW9J0u7hhw6n1LiO-2Xu1q2B0sE5w,4366
+pygments/formatters/__init__.py,sha256=7OuvmoYLyoPzoOQV_brHG8GSKYB_wjFSkAQng6x2y9g,5349
+pygments/formatters/__pycache__/__init__.cpython-312.pyc,,
+pygments/formatters/__pycache__/_mapping.cpython-312.pyc,,
+pygments/formatters/__pycache__/bbcode.cpython-312.pyc,,
+pygments/formatters/__pycache__/groff.cpython-312.pyc,,
+pygments/formatters/__pycache__/html.cpython-312.pyc,,
+pygments/formatters/__pycache__/img.cpython-312.pyc,,
+pygments/formatters/__pycache__/irc.cpython-312.pyc,,
+pygments/formatters/__pycache__/latex.cpython-312.pyc,,
+pygments/formatters/__pycache__/other.cpython-312.pyc,,
+pygments/formatters/__pycache__/pangomarkup.cpython-312.pyc,,
+pygments/formatters/__pycache__/rtf.cpython-312.pyc,,
+pygments/formatters/__pycache__/svg.cpython-312.pyc,,
+pygments/formatters/__pycache__/terminal.cpython-312.pyc,,
+pygments/formatters/__pycache__/terminal256.cpython-312.pyc,,
+pygments/formatters/_mapping.py,sha256=1Cw37FuQlNacnxRKmtlPX4nyLoX9_ttko5ZwscNUZZ4,4176
+pygments/formatters/bbcode.py,sha256=s0Ka35OKuIchoSgEAGf6rj0rl2a9ym9L31JVNSRbZFQ,3296
+pygments/formatters/groff.py,sha256=pLcIHj4jJS_lRAVFnyJODKDu1Xlyl9_AEIdOtbl3DT0,5082
+pygments/formatters/html.py,sha256=FrHJ69FUliEyPY0zTfab0C1gPf7LXsKgeRlhwkniqIs,35953
+pygments/formatters/img.py,sha256=aRpFo8mBmWTL3sBUjRCWkeS3rc6FZrSFC4EksDrl53g,23301
+pygments/formatters/irc.py,sha256=R0Js0TYWySlI2yE9sW6tN4d4X-x3k9ZmudsijGPnLmU,4945
+pygments/formatters/latex.py,sha256=BRYtbLeW_YD1kwhhnFInhJIKylurnri8CF1lP069KWE,19258
+pygments/formatters/other.py,sha256=8pYW27sU_7XicLUqOEt2yWSO0h1IEUM3TIv34KODLwo,4986
+pygments/formatters/pangomarkup.py,sha256=pcFvEC7K1Me0EjGeOZth4oCnEY85bfqc77XzZASEPpY,2206
+pygments/formatters/rtf.py,sha256=kcKMCxTXu-2-hpgEftlGJRm7Ss-yA_Sy8OsHH_qzykA,11921
+pygments/formatters/svg.py,sha256=R6A2ME6JsMQWFiyn8wcKwFUOD6vsu-HLwiIztLu-77E,7138
+pygments/formatters/terminal.py,sha256=J_F_dFXwR9LHWvatIDnwqRYJyjVmSo1Zx8K_XDh6SyM,4626
+pygments/formatters/terminal256.py,sha256=7GQFLE5cfmeu53CAzANO74-kBk2BFkXfn5phmZjYkhM,11717
+pygments/lexer.py,sha256=ib-F_0GxHkwGpb6vWP0DeLMLc7EYgjo3hWFKN5IgOq0,35109
+pygments/lexers/__init__.py,sha256=6YhzxGKlWk38P6JpIJUQ1rVvV0DEZjEmdYsdMQ58hSk,12067
+pygments/lexers/__pycache__/__init__.cpython-312.pyc,,
+pygments/lexers/__pycache__/_ada_builtins.cpython-312.pyc,,
+pygments/lexers/__pycache__/_asy_builtins.cpython-312.pyc,,
+pygments/lexers/__pycache__/_cl_builtins.cpython-312.pyc,,
+pygments/lexers/__pycache__/_cocoa_builtins.cpython-312.pyc,,
+pygments/lexers/__pycache__/_csound_builtins.cpython-312.pyc,,
+pygments/lexers/__pycache__/_css_builtins.cpython-312.pyc,,
+pygments/lexers/__pycache__/_googlesql_builtins.cpython-312.pyc,,
+pygments/lexers/__pycache__/_julia_builtins.cpython-312.pyc,,
+pygments/lexers/__pycache__/_lasso_builtins.cpython-312.pyc,,
+pygments/lexers/__pycache__/_lilypond_builtins.cpython-312.pyc,,
+pygments/lexers/__pycache__/_lua_builtins.cpython-312.pyc,,
+pygments/lexers/__pycache__/_luau_builtins.cpython-312.pyc,,
+pygments/lexers/__pycache__/_mapping.cpython-312.pyc,,
+pygments/lexers/__pycache__/_mql_builtins.cpython-312.pyc,,
+pygments/lexers/__pycache__/_mysql_builtins.cpython-312.pyc,,
+pygments/lexers/__pycache__/_openedge_builtins.cpython-312.pyc,,
+pygments/lexers/__pycache__/_php_builtins.cpython-312.pyc,,
+pygments/lexers/__pycache__/_postgres_builtins.cpython-312.pyc,,
+pygments/lexers/__pycache__/_qlik_builtins.cpython-312.pyc,,
+pygments/lexers/__pycache__/_scheme_builtins.cpython-312.pyc,,
+pygments/lexers/__pycache__/_scilab_builtins.cpython-312.pyc,,
+pygments/lexers/__pycache__/_sourcemod_builtins.cpython-312.pyc,,
+pygments/lexers/__pycache__/_sql_builtins.cpython-312.pyc,,
+pygments/lexers/__pycache__/_stan_builtins.cpython-312.pyc,,
+pygments/lexers/__pycache__/_stata_builtins.cpython-312.pyc,,
+pygments/lexers/__pycache__/_tsql_builtins.cpython-312.pyc,,
+pygments/lexers/__pycache__/_usd_builtins.cpython-312.pyc,,
+pygments/lexers/__pycache__/_vbscript_builtins.cpython-312.pyc,,
+pygments/lexers/__pycache__/_vim_builtins.cpython-312.pyc,,
+pygments/lexers/__pycache__/actionscript.cpython-312.pyc,,
+pygments/lexers/__pycache__/ada.cpython-312.pyc,,
+pygments/lexers/__pycache__/agile.cpython-312.pyc,,
+pygments/lexers/__pycache__/algebra.cpython-312.pyc,,
+pygments/lexers/__pycache__/ambient.cpython-312.pyc,,
+pygments/lexers/__pycache__/amdgpu.cpython-312.pyc,,
+pygments/lexers/__pycache__/ampl.cpython-312.pyc,,
+pygments/lexers/__pycache__/apdlexer.cpython-312.pyc,,
+pygments/lexers/__pycache__/apl.cpython-312.pyc,,
+pygments/lexers/__pycache__/archetype.cpython-312.pyc,,
+pygments/lexers/__pycache__/arrow.cpython-312.pyc,,
+pygments/lexers/__pycache__/arturo.cpython-312.pyc,,
+pygments/lexers/__pycache__/asc.cpython-312.pyc,,
+pygments/lexers/__pycache__/asm.cpython-312.pyc,,
+pygments/lexers/__pycache__/asn1.cpython-312.pyc,,
+pygments/lexers/__pycache__/automation.cpython-312.pyc,,
+pygments/lexers/__pycache__/bare.cpython-312.pyc,,
+pygments/lexers/__pycache__/basic.cpython-312.pyc,,
+pygments/lexers/__pycache__/bdd.cpython-312.pyc,,
+pygments/lexers/__pycache__/berry.cpython-312.pyc,,
+pygments/lexers/__pycache__/bibtex.cpython-312.pyc,,
+pygments/lexers/__pycache__/blueprint.cpython-312.pyc,,
+pygments/lexers/__pycache__/boa.cpython-312.pyc,,
+pygments/lexers/__pycache__/bqn.cpython-312.pyc,,
+pygments/lexers/__pycache__/business.cpython-312.pyc,,
+pygments/lexers/__pycache__/c_cpp.cpython-312.pyc,,
+pygments/lexers/__pycache__/c_like.cpython-312.pyc,,
+pygments/lexers/__pycache__/capnproto.cpython-312.pyc,,
+pygments/lexers/__pycache__/carbon.cpython-312.pyc,,
+pygments/lexers/__pycache__/cddl.cpython-312.pyc,,
+pygments/lexers/__pycache__/chapel.cpython-312.pyc,,
+pygments/lexers/__pycache__/clean.cpython-312.pyc,,
+pygments/lexers/__pycache__/codeql.cpython-312.pyc,,
+pygments/lexers/__pycache__/comal.cpython-312.pyc,,
+pygments/lexers/__pycache__/compiled.cpython-312.pyc,,
+pygments/lexers/__pycache__/configs.cpython-312.pyc,,
+pygments/lexers/__pycache__/console.cpython-312.pyc,,
+pygments/lexers/__pycache__/cplint.cpython-312.pyc,,
+pygments/lexers/__pycache__/crystal.cpython-312.pyc,,
+pygments/lexers/__pycache__/csound.cpython-312.pyc,,
+pygments/lexers/__pycache__/css.cpython-312.pyc,,
+pygments/lexers/__pycache__/d.cpython-312.pyc,,
+pygments/lexers/__pycache__/dalvik.cpython-312.pyc,,
+pygments/lexers/__pycache__/data.cpython-312.pyc,,
+pygments/lexers/__pycache__/dax.cpython-312.pyc,,
+pygments/lexers/__pycache__/devicetree.cpython-312.pyc,,
+pygments/lexers/__pycache__/diff.cpython-312.pyc,,
+pygments/lexers/__pycache__/dns.cpython-312.pyc,,
+pygments/lexers/__pycache__/dotnet.cpython-312.pyc,,
+pygments/lexers/__pycache__/dsls.cpython-312.pyc,,
+pygments/lexers/__pycache__/dylan.cpython-312.pyc,,
+pygments/lexers/__pycache__/ecl.cpython-312.pyc,,
+pygments/lexers/__pycache__/eiffel.cpython-312.pyc,,
+pygments/lexers/__pycache__/elm.cpython-312.pyc,,
+pygments/lexers/__pycache__/elpi.cpython-312.pyc,,
+pygments/lexers/__pycache__/email.cpython-312.pyc,,
+pygments/lexers/__pycache__/erlang.cpython-312.pyc,,
+pygments/lexers/__pycache__/esoteric.cpython-312.pyc,,
+pygments/lexers/__pycache__/ezhil.cpython-312.pyc,,
+pygments/lexers/__pycache__/factor.cpython-312.pyc,,
+pygments/lexers/__pycache__/fantom.cpython-312.pyc,,
+pygments/lexers/__pycache__/felix.cpython-312.pyc,,
+pygments/lexers/__pycache__/fift.cpython-312.pyc,,
+pygments/lexers/__pycache__/floscript.cpython-312.pyc,,
+pygments/lexers/__pycache__/forth.cpython-312.pyc,,
+pygments/lexers/__pycache__/fortran.cpython-312.pyc,,
+pygments/lexers/__pycache__/foxpro.cpython-312.pyc,,
+pygments/lexers/__pycache__/freefem.cpython-312.pyc,,
+pygments/lexers/__pycache__/func.cpython-312.pyc,,
+pygments/lexers/__pycache__/functional.cpython-312.pyc,,
+pygments/lexers/__pycache__/futhark.cpython-312.pyc,,
+pygments/lexers/__pycache__/gcodelexer.cpython-312.pyc,,
+pygments/lexers/__pycache__/gdscript.cpython-312.pyc,,
+pygments/lexers/__pycache__/gleam.cpython-312.pyc,,
+pygments/lexers/__pycache__/go.cpython-312.pyc,,
+pygments/lexers/__pycache__/grammar_notation.cpython-312.pyc,,
+pygments/lexers/__pycache__/graph.cpython-312.pyc,,
+pygments/lexers/__pycache__/graphics.cpython-312.pyc,,
+pygments/lexers/__pycache__/graphql.cpython-312.pyc,,
+pygments/lexers/__pycache__/graphviz.cpython-312.pyc,,
+pygments/lexers/__pycache__/gsql.cpython-312.pyc,,
+pygments/lexers/__pycache__/hare.cpython-312.pyc,,
+pygments/lexers/__pycache__/haskell.cpython-312.pyc,,
+pygments/lexers/__pycache__/haxe.cpython-312.pyc,,
+pygments/lexers/__pycache__/hdl.cpython-312.pyc,,
+pygments/lexers/__pycache__/hexdump.cpython-312.pyc,,
+pygments/lexers/__pycache__/html.cpython-312.pyc,,
+pygments/lexers/__pycache__/idl.cpython-312.pyc,,
+pygments/lexers/__pycache__/igor.cpython-312.pyc,,
+pygments/lexers/__pycache__/inferno.cpython-312.pyc,,
+pygments/lexers/__pycache__/installers.cpython-312.pyc,,
+pygments/lexers/__pycache__/int_fiction.cpython-312.pyc,,
+pygments/lexers/__pycache__/iolang.cpython-312.pyc,,
+pygments/lexers/__pycache__/j.cpython-312.pyc,,
+pygments/lexers/__pycache__/javascript.cpython-312.pyc,,
+pygments/lexers/__pycache__/jmespath.cpython-312.pyc,,
+pygments/lexers/__pycache__/jslt.cpython-312.pyc,,
+pygments/lexers/__pycache__/json5.cpython-312.pyc,,
+pygments/lexers/__pycache__/jsonnet.cpython-312.pyc,,
+pygments/lexers/__pycache__/jsx.cpython-312.pyc,,
+pygments/lexers/__pycache__/julia.cpython-312.pyc,,
+pygments/lexers/__pycache__/jvm.cpython-312.pyc,,
+pygments/lexers/__pycache__/kuin.cpython-312.pyc,,
+pygments/lexers/__pycache__/kusto.cpython-312.pyc,,
+pygments/lexers/__pycache__/ldap.cpython-312.pyc,,
+pygments/lexers/__pycache__/lean.cpython-312.pyc,,
+pygments/lexers/__pycache__/lilypond.cpython-312.pyc,,
+pygments/lexers/__pycache__/lisp.cpython-312.pyc,,
+pygments/lexers/__pycache__/macaulay2.cpython-312.pyc,,
+pygments/lexers/__pycache__/make.cpython-312.pyc,,
+pygments/lexers/__pycache__/maple.cpython-312.pyc,,
+pygments/lexers/__pycache__/markup.cpython-312.pyc,,
+pygments/lexers/__pycache__/math.cpython-312.pyc,,
+pygments/lexers/__pycache__/matlab.cpython-312.pyc,,
+pygments/lexers/__pycache__/maxima.cpython-312.pyc,,
+pygments/lexers/__pycache__/meson.cpython-312.pyc,,
+pygments/lexers/__pycache__/mime.cpython-312.pyc,,
+pygments/lexers/__pycache__/minecraft.cpython-312.pyc,,
+pygments/lexers/__pycache__/mips.cpython-312.pyc,,
+pygments/lexers/__pycache__/ml.cpython-312.pyc,,
+pygments/lexers/__pycache__/modeling.cpython-312.pyc,,
+pygments/lexers/__pycache__/modula2.cpython-312.pyc,,
+pygments/lexers/__pycache__/mojo.cpython-312.pyc,,
+pygments/lexers/__pycache__/monte.cpython-312.pyc,,
+pygments/lexers/__pycache__/mosel.cpython-312.pyc,,
+pygments/lexers/__pycache__/ncl.cpython-312.pyc,,
+pygments/lexers/__pycache__/nimrod.cpython-312.pyc,,
+pygments/lexers/__pycache__/nit.cpython-312.pyc,,
+pygments/lexers/__pycache__/nix.cpython-312.pyc,,
+pygments/lexers/__pycache__/numbair.cpython-312.pyc,,
+pygments/lexers/__pycache__/oberon.cpython-312.pyc,,
+pygments/lexers/__pycache__/objective.cpython-312.pyc,,
+pygments/lexers/__pycache__/ooc.cpython-312.pyc,,
+pygments/lexers/__pycache__/openscad.cpython-312.pyc,,
+pygments/lexers/__pycache__/other.cpython-312.pyc,,
+pygments/lexers/__pycache__/parasail.cpython-312.pyc,,
+pygments/lexers/__pycache__/parsers.cpython-312.pyc,,
+pygments/lexers/__pycache__/pascal.cpython-312.pyc,,
+pygments/lexers/__pycache__/pawn.cpython-312.pyc,,
+pygments/lexers/__pycache__/pddl.cpython-312.pyc,,
+pygments/lexers/__pycache__/perl.cpython-312.pyc,,
+pygments/lexers/__pycache__/phix.cpython-312.pyc,,
+pygments/lexers/__pycache__/php.cpython-312.pyc,,
+pygments/lexers/__pycache__/pointless.cpython-312.pyc,,
+pygments/lexers/__pycache__/pony.cpython-312.pyc,,
+pygments/lexers/__pycache__/praat.cpython-312.pyc,,
+pygments/lexers/__pycache__/procfile.cpython-312.pyc,,
+pygments/lexers/__pycache__/prolog.cpython-312.pyc,,
+pygments/lexers/__pycache__/promql.cpython-312.pyc,,
+pygments/lexers/__pycache__/prql.cpython-312.pyc,,
+pygments/lexers/__pycache__/ptx.cpython-312.pyc,,
+pygments/lexers/__pycache__/python.cpython-312.pyc,,
+pygments/lexers/__pycache__/q.cpython-312.pyc,,
+pygments/lexers/__pycache__/qlik.cpython-312.pyc,,
+pygments/lexers/__pycache__/qvt.cpython-312.pyc,,
+pygments/lexers/__pycache__/r.cpython-312.pyc,,
+pygments/lexers/__pycache__/rdf.cpython-312.pyc,,
+pygments/lexers/__pycache__/rebol.cpython-312.pyc,,
+pygments/lexers/__pycache__/rego.cpython-312.pyc,,
+pygments/lexers/__pycache__/resource.cpython-312.pyc,,
+pygments/lexers/__pycache__/ride.cpython-312.pyc,,
+pygments/lexers/__pycache__/rita.cpython-312.pyc,,
+pygments/lexers/__pycache__/rnc.cpython-312.pyc,,
+pygments/lexers/__pycache__/roboconf.cpython-312.pyc,,
+pygments/lexers/__pycache__/robotframework.cpython-312.pyc,,
+pygments/lexers/__pycache__/ruby.cpython-312.pyc,,
+pygments/lexers/__pycache__/rust.cpython-312.pyc,,
+pygments/lexers/__pycache__/sas.cpython-312.pyc,,
+pygments/lexers/__pycache__/savi.cpython-312.pyc,,
+pygments/lexers/__pycache__/scdoc.cpython-312.pyc,,
+pygments/lexers/__pycache__/scripting.cpython-312.pyc,,
+pygments/lexers/__pycache__/sgf.cpython-312.pyc,,
+pygments/lexers/__pycache__/shell.cpython-312.pyc,,
+pygments/lexers/__pycache__/sieve.cpython-312.pyc,,
+pygments/lexers/__pycache__/slash.cpython-312.pyc,,
+pygments/lexers/__pycache__/smalltalk.cpython-312.pyc,,
+pygments/lexers/__pycache__/smithy.cpython-312.pyc,,
+pygments/lexers/__pycache__/smv.cpython-312.pyc,,
+pygments/lexers/__pycache__/snobol.cpython-312.pyc,,
+pygments/lexers/__pycache__/solidity.cpython-312.pyc,,
+pygments/lexers/__pycache__/soong.cpython-312.pyc,,
+pygments/lexers/__pycache__/sophia.cpython-312.pyc,,
+pygments/lexers/__pycache__/special.cpython-312.pyc,,
+pygments/lexers/__pycache__/spice.cpython-312.pyc,,
+pygments/lexers/__pycache__/sql.cpython-312.pyc,,
+pygments/lexers/__pycache__/srcinfo.cpython-312.pyc,,
+pygments/lexers/__pycache__/stata.cpython-312.pyc,,
+pygments/lexers/__pycache__/supercollider.cpython-312.pyc,,
+pygments/lexers/__pycache__/tablegen.cpython-312.pyc,,
+pygments/lexers/__pycache__/tact.cpython-312.pyc,,
+pygments/lexers/__pycache__/tal.cpython-312.pyc,,
+pygments/lexers/__pycache__/tcl.cpython-312.pyc,,
+pygments/lexers/__pycache__/teal.cpython-312.pyc,,
+pygments/lexers/__pycache__/templates.cpython-312.pyc,,
+pygments/lexers/__pycache__/teraterm.cpython-312.pyc,,
+pygments/lexers/__pycache__/testing.cpython-312.pyc,,
+pygments/lexers/__pycache__/text.cpython-312.pyc,,
+pygments/lexers/__pycache__/textedit.cpython-312.pyc,,
+pygments/lexers/__pycache__/textfmts.cpython-312.pyc,,
+pygments/lexers/__pycache__/theorem.cpython-312.pyc,,
+pygments/lexers/__pycache__/thingsdb.cpython-312.pyc,,
+pygments/lexers/__pycache__/tlb.cpython-312.pyc,,
+pygments/lexers/__pycache__/tls.cpython-312.pyc,,
+pygments/lexers/__pycache__/tnt.cpython-312.pyc,,
+pygments/lexers/__pycache__/trafficscript.cpython-312.pyc,,
+pygments/lexers/__pycache__/typoscript.cpython-312.pyc,,
+pygments/lexers/__pycache__/typst.cpython-312.pyc,,
+pygments/lexers/__pycache__/ul4.cpython-312.pyc,,
+pygments/lexers/__pycache__/unicon.cpython-312.pyc,,
+pygments/lexers/__pycache__/urbi.cpython-312.pyc,,
+pygments/lexers/__pycache__/usd.cpython-312.pyc,,
+pygments/lexers/__pycache__/varnish.cpython-312.pyc,,
+pygments/lexers/__pycache__/verification.cpython-312.pyc,,
+pygments/lexers/__pycache__/verifpal.cpython-312.pyc,,
+pygments/lexers/__pycache__/vip.cpython-312.pyc,,
+pygments/lexers/__pycache__/vyper.cpython-312.pyc,,
+pygments/lexers/__pycache__/web.cpython-312.pyc,,
+pygments/lexers/__pycache__/webassembly.cpython-312.pyc,,
+pygments/lexers/__pycache__/webidl.cpython-312.pyc,,
+pygments/lexers/__pycache__/webmisc.cpython-312.pyc,,
+pygments/lexers/__pycache__/wgsl.cpython-312.pyc,,
+pygments/lexers/__pycache__/whiley.cpython-312.pyc,,
+pygments/lexers/__pycache__/wowtoc.cpython-312.pyc,,
+pygments/lexers/__pycache__/wren.cpython-312.pyc,,
+pygments/lexers/__pycache__/x10.cpython-312.pyc,,
+pygments/lexers/__pycache__/xorg.cpython-312.pyc,,
+pygments/lexers/__pycache__/yang.cpython-312.pyc,,
+pygments/lexers/__pycache__/yara.cpython-312.pyc,,
+pygments/lexers/__pycache__/zig.cpython-312.pyc,,
+pygments/lexers/_ada_builtins.py,sha256=CA_OnShtdc7wWh9oYcRlcrkDAQwYUKl6w7tdSbALQd4,1543
+pygments/lexers/_asy_builtins.py,sha256=cd9M00YH19w5ZL7aqucmC3nwpJGTS04U-01NLy5E2_4,27287
+pygments/lexers/_cl_builtins.py,sha256=kQeUIyZjP4kX0frkICDcKxBYQCLqzIDXa5WV5cevhDo,13994
+pygments/lexers/_cocoa_builtins.py,sha256=Ka1lLJe7JfWtdho4IFIB82X9yBvrbfHCCmEG-peXXhQ,105173
+pygments/lexers/_csound_builtins.py,sha256=qnQYKeI26ZHim316uqy_hDiRiCoHo2RHjD3sYBALyXs,18414
+pygments/lexers/_css_builtins.py,sha256=aD-dhLFXVd1Atn_bZd7gEdQn7Mhe60_VHpvZ340WzDI,12446
+pygments/lexers/_googlesql_builtins.py,sha256=IkrOk-T2v1yzbGzUEEQh5_Cf4uC_cmL_uuhwDpZlTug,16132
+pygments/lexers/_julia_builtins.py,sha256=N2WdSw5zgI2fhDat_i4YeVqurRTC_P8x71ez00SCN6U,11883
+pygments/lexers/_lasso_builtins.py,sha256=8q1gbsrMJeaeUhxIYKhaOxC9j_B-NBpq_XFj2Ze41X0,134510
+pygments/lexers/_lilypond_builtins.py,sha256=XTbGL1z1oKMoqWLEktG33jx5GdGTI9CpeO5NheEi4Y0,108094
+pygments/lexers/_lua_builtins.py,sha256=PhFdZV5-Tzz2j_q4lvG9lr84ELGfL41BhnrSDNNTaG4,8108
+pygments/lexers/_luau_builtins.py,sha256=-IDrU04kUVfjXwSQzMMpXmMYhNsQxZVVZk8cuAA0Lo0,955
+pygments/lexers/_mapping.py,sha256=9fv7xYOUAOr6LzfdFS4MDbPu78o4OQQH-2nsI1bNZf4,70438
+pygments/lexers/_mql_builtins.py,sha256=ybRQjlb7Cul0sDstnzxJl3h0qS6Ieqsr811fqrxyumU,24713
+pygments/lexers/_mysql_builtins.py,sha256=y0kAWZVAs0z2dTFJJV42OZpILgRnd8T3zSlBFv-g_oA,25838
+pygments/lexers/_openedge_builtins.py,sha256=Sz4j9-CPWIaxMa-2fZgY66j7igcu1ob1GR2UtI8zAkg,49398
+pygments/lexers/_php_builtins.py,sha256=Jd4BZpjMDELPi4EVoSxK1-8BFTc63HUwYfm1rLrGj0M,107922
+pygments/lexers/_postgres_builtins.py,sha256=Pqh4z0RBRbnW6rCQtWUdzWCJxNyqpJ7_0HOktxHDxk4,13343
+pygments/lexers/_qlik_builtins.py,sha256=xuJy9c9uZDXv6h8z582P5PrxqkxTZ_nS8gPl9OD9VN8,12595
+pygments/lexers/_scheme_builtins.py,sha256=2hNtJOJmP21lUsikpqMJ2gAmLT3Rwn_KEeqhXwCjgfk,32564
+pygments/lexers/_scilab_builtins.py,sha256=oZYPB1XPdIEz3pII11pFDe6extRRyWGA7pY06X8KZ8w,52411
+pygments/lexers/_sourcemod_builtins.py,sha256=H8AFLsNDdEpymIWOpDwbDJGCP1w-x-1gSlzPDioMF4o,26777
+pygments/lexers/_sql_builtins.py,sha256=oe8F9wWuO2iS6nEsZAdJtCUChBTjgM1Sq_aipu74jXM,6767
+pygments/lexers/_stan_builtins.py,sha256=dwi1hllM_NsaCv-aXJy7lEi57X5Hh5gSD97aCQyT9KM,13445
+pygments/lexers/_stata_builtins.py,sha256=Hqrr6j77zWU3cGGpBPohwexZci43YA4_sVYE4E1sNow,27227
+pygments/lexers/_tsql_builtins.py,sha256=Pi2RhTXcLE3glI9oxNhyVsOMn-fK_1TRxJ-EsYP5LcI,15460
+pygments/lexers/_usd_builtins.py,sha256=c9hbU1cwqBUCFIhNfu_Dob8ywv1rlPhi9w2OTj3kR8s,1658
+pygments/lexers/_vbscript_builtins.py,sha256=MqJ2ABywD21aSRtWYZRG64CCbGstC1kfsiHGJmZzxiw,4225
+pygments/lexers/_vim_builtins.py,sha256=bA4mH8t1mPPQfEiUCKEqRO1O0rL2DUG0Ux1Bt8ZSu0E,57066
+pygments/lexers/actionscript.py,sha256=JBngCe5UhYT_0dLD2j7PnPO0xRRJhmypEuQ-C5in8pY,11727
+pygments/lexers/ada.py,sha256=58k5ra1vGS4iLpW3h1ItY9ftzF3WevaeAAXzAYTiYkQ,5353
+pygments/lexers/agile.py,sha256=DN-7AVIqtG1MshA94rtSGYI_884hVHgzq405wD0_dl8,896
+pygments/lexers/algebra.py,sha256=yGTu9Tt-cQzAISQYIC5MS5a3z4QmL-tGcXnd_pkWGbk,9952
+pygments/lexers/ambient.py,sha256=UnzKpIlfSm3iitHvMd7XTMSY8TjZYYhKOC3AiARS_cE,2605
+pygments/lexers/amdgpu.py,sha256=S8qjn2UMLhBFm3Yn_c06XAGf8cl5x_ZeluelWG_-JAw,1723
+pygments/lexers/ampl.py,sha256=ZBRfDXm760gR1a1gqItnsHuoO3JdUcTBjJ5tFY9UtPA,4176
+pygments/lexers/apdlexer.py,sha256=Zr5-jgjxC8PKzRlEeclakZXPHci7FHBZghQ6wwiuT7A,30800
+pygments/lexers/apl.py,sha256=PTQMp-bxT5P-DbrEvFha10HBTcsDJ5srL3I1s9ljz58,3404
+pygments/lexers/archetype.py,sha256=pQVlP1Fb5OA8nn7QwmFaaaOSvvpoIsQVw43FVCQCve4,11538
+pygments/lexers/arrow.py,sha256=2PKdbWq3xQLF1KoDbWvSxpjwKRrznnDiArTflRGZzBo,3564
+pygments/lexers/arturo.py,sha256=U5MtRNHJtnBn4ZOeWmW6MKlVRG7SX6KhTRamDqzn9tA,11414
+pygments/lexers/asc.py,sha256=-DgZl9jccBDHPlDmjCsrEqx0-Q7ap7XVdNKtxLNWG1w,1693
+pygments/lexers/asm.py,sha256=xm2Y5mcT-sF3oQvair4SWs9EWTyndoaUoSsDy5v6shI,41967
+pygments/lexers/asn1.py,sha256=BlcloIX2bu6Q7BxGcksuhYFHGsXLVKyB4B9mFd4Pj6E,4262
+pygments/lexers/automation.py,sha256=Q61qon8EwpfakMh_2MS2E2zUUT16rG3UNIKPYjITeTs,19831
+pygments/lexers/bare.py,sha256=tWoei86JJX1k-ADhaXd5TgX6ItDTici9yFWpkTPhnfM,3020
+pygments/lexers/basic.py,sha256=qpVe5h8Fa7NJo1EihN-4R_UZpHO6my2Ssgkb-BktkKs,27989
+pygments/lexers/bdd.py,sha256=yysefcOFAEyk9kJ2y4EXmzJTecgLYUHlWixt_3YzPMU,1641
+pygments/lexers/berry.py,sha256=zxGowFb8HMIyN15-m8nmWnW6bPRR4esKtSEVugc9uXM,3209
+pygments/lexers/bibtex.py,sha256=yuNoPxwrJf9DCGUT17hxfDzbq_HtCLkQkRbBtiTVmeQ,4811
+pygments/lexers/blueprint.py,sha256=NzvWHMxCLDWt8hc6gB5jokltxVJgNa7Jwh4c61ng388,6188
+pygments/lexers/boa.py,sha256=dOot1XWNZThPIio2UyAX67K6EpISjSRCFjotD7dcnwE,3921
+pygments/lexers/bqn.py,sha256=nJiwrPKKbRF-qdai5tfqipwBkkko2P3weiZAjHUMimY,3671
+pygments/lexers/business.py,sha256=lRtekOJfsDkb12AGbuz10-G67OJrVJgCBtihTQ8_aoY,28345
+pygments/lexers/c_cpp.py,sha256=D7ZIswaHASlGBgoTlwnSqTQHf8_JyvvSt2L2q1W-F6g,18059
+pygments/lexers/c_like.py,sha256=FTGp17ds6X2rDZOHup2hH6BEn3gKK4nLm9pydNEhm0E,32021
+pygments/lexers/capnproto.py,sha256=XQJAh1WS-0ulqbTn9TdzR6gEgWLcuBqb4sj3jNsrhsY,2174
+pygments/lexers/carbon.py,sha256=av12YuTGZGpOa1Cmxp3lppx3LfSJUWbvOu0ixmUVll0,3211
+pygments/lexers/cddl.py,sha256=MKa70IwABgjBjYu15_Q9v8rsu2sr1a-i2jkiaPTI6sM,5076
+pygments/lexers/chapel.py,sha256=0n_fL3ehLC4pw4YKnmq9jxIXOJcxGPka1Wr1t1zsXPc,5156
+pygments/lexers/clean.py,sha256=dkDPAwF5BTALPeuKFoRKOSD3RfsKcGWbaRo6_G8LHng,6418
+pygments/lexers/codeql.py,sha256=ebvghn2zbrnETV4buVozMDmRCVKSdGiIN8ycLlHpGsE,2576
+pygments/lexers/comal.py,sha256=TC3NzcJ58ew5jw7qwK0kJ-okTA47psZje0yAIS39HR4,3179
+pygments/lexers/compiled.py,sha256=Slfo1sjWqcPawUwf0dIIZLBCL5pkOIoAX2S8Lxs02Mc,1426
+pygments/lexers/configs.py,sha256=wW8pY0Sa5a10pnAeTLGf48HhixQTVageIyHEf1aYMCc,50913
+pygments/lexers/console.py,sha256=-jAG120dupvV3kG3zC70brLJvSLwTFqMubBQuj_GVnU,4180
+pygments/lexers/cplint.py,sha256=DkbyE5EKydLgf6BRr1FhQrK-IeQPL7Zmjk0DVdlRFnQ,1389
+pygments/lexers/crystal.py,sha256=xU-RnpIkpjrquoxtOuOcP8fcesSJl4xhU7kO9m42LZY,15754
+pygments/lexers/csound.py,sha256=ioSw4Q04wdwjUAbnTZ1qLhUq1vxdWFxhh3QtEl5RAJc,16998
+pygments/lexers/css.py,sha256=JN1RBYsee-jrpHWrSmhN3TKc4TkOBn-_BEGpgTCzcqE,25376
+pygments/lexers/d.py,sha256=piOy0EJeiAwPHugiM3gVv0z7HNh3u2gZQoCUSASRbY4,9920
+pygments/lexers/dalvik.py,sha256=deFg2JPBktJ9mEGb9EgxNkmd6vaMjJFQVzUHo8NKIa8,4606
+pygments/lexers/data.py,sha256=o0x0SmB5ms_CPUPljEEEenOON4IQWn86DkwFjkJYCOg,27026
+pygments/lexers/dax.py,sha256=ASi73qmr7OA7cVZXF2GTYGt01Ly1vY8CgD_Pnpm8k-4,8098
+pygments/lexers/devicetree.py,sha256=RecSQCidt8DRE1QFCPUbwwR0hiRlNtsFihdGldeUn3k,4019
+pygments/lexers/diff.py,sha256=F6vxZ64wm5Nag_97de1H_3F700ZwCVnYjKvtT5jilww,5382
+pygments/lexers/dns.py,sha256=Hh5hJ7MXfrq36KgfyIRwK3X8o1LdR98IKERcV4eZ7HY,3891
+pygments/lexers/dotnet.py,sha256=NDE0kOmpe96GLO-zwNLazmj77E9ORGmKpa4ZMCXDXxQ,39441
+pygments/lexers/dsls.py,sha256=GnHKhGL5GxsRFnqC7-65NTPZLOZdmnllNrGP86x_fQE,36746
+pygments/lexers/dylan.py,sha256=7zZ1EbHWXeVHqTD36AqykKqo3fhuIh4sM-whcxUaH_Y,10409
+pygments/lexers/ecl.py,sha256=vhmpa2LBrHxsPkYcf3kPZ1ItVaLRDTebi186wY0xGZA,6371
+pygments/lexers/eiffel.py,sha256=5ydYIEFcgcMoEj4BlK31hZ0aJb8OX0RdAvuCNdlxwqw,2690
+pygments/lexers/elm.py,sha256=uRCddU8jK5vVkH6Y66y8KOsDJprIfrOgeYq3hv1PxAM,3152
+pygments/lexers/elpi.py,sha256=O9j_WKBPyvNFjCRuPciVpW4etVSnILm_T79BhCPZYmo,6877
+pygments/lexers/email.py,sha256=ZZL6yvwCRl1CEQyysuOu0lbabp5tjMutS7f3efFKGR4,4804
+pygments/lexers/erlang.py,sha256=bU11eVHvooLwmVknzN6Xkb2DMk7HbenqdNlYSzhThDM,19147
+pygments/lexers/esoteric.py,sha256=Jfp8UUKyKYsqLaqXRZT3GSM9dzkF65zduwfnH1GoGhU,10500
+pygments/lexers/ezhil.py,sha256=22r-xjvvBVpExTqCI-HycAwunDb1p5gY4tIfDmM0vDw,3272
+pygments/lexers/factor.py,sha256=urZ4En4uKFCLXdEkXLWg9EYUFGHQTTDCwNXtyq-ngok,19530
+pygments/lexers/fantom.py,sha256=JJ13-NwykD-iIESnuzCefCYeQDO95cHMJA8TasF4gHA,10231
+pygments/lexers/felix.py,sha256=F-v0si4zPtRelqzDQWXI1-tarCE-BvawziODxRU7378,9655
+pygments/lexers/fift.py,sha256=rOCwp3v5ocK5YOWvt7Td3Md--97_8e-7Sonx52uS8mA,1644
+pygments/lexers/floscript.py,sha256=aHh82k52jMuDuzl9LatrcSANJiXTCyjGU3SO53bwbb0,2667
+pygments/lexers/forth.py,sha256=ZMtsHdNbnS_0IdSYlfAlfTSPEr0MEsRo-YZriQNueTQ,7193
+pygments/lexers/fortran.py,sha256=1PE5dTxf4Df6LUeXFcmNtyeXWsC8tSiK5dYwPHIJeeQ,10382
+pygments/lexers/foxpro.py,sha256=CBkW62Fuibz3yfyelZCaEO8GGdFJWsuRhqwtsSeBwLM,26295
+pygments/lexers/freefem.py,sha256=LFBQk-m1-nNCgrl-VDH3QwnVWurvb7W29i06LoT207A,26913
+pygments/lexers/func.py,sha256=OR2rkM7gf9fKvad5WcFQln-_U_pb-RUCM9eQatToF4A,3700
+pygments/lexers/functional.py,sha256=fYT2AGZ642cRkIAId0rnXFBsx1c8LLEDRN_VuCEkUyM,693
+pygments/lexers/futhark.py,sha256=Vf1i4t-tR3zqaktVjhTzFNg_ts_9CcyA4ZDfDizbCmk,3743
+pygments/lexers/gcodelexer.py,sha256=4Xs9ax4-JZGupW_qSnHon39wQGpb-tNA3xorMKg841E,874
+pygments/lexers/gdscript.py,sha256=Ws7JKxy0M0IyZ_1iMfRvJPrizEwmeCNLDoeMIFaM-CU,7566
+pygments/lexers/gleam.py,sha256=XIlTcq6cB743pCqbNYo8PocSkjZyDPR6hHgdaJNJ1Vc,2392
+pygments/lexers/go.py,sha256=4LezefgyuqZWHzLZHieUkKTi-ssY6aHJxx7Z-LFaLK0,3783
+pygments/lexers/grammar_notation.py,sha256=LvzhRQHgwZzq9oceukZS_hwnKK58ee7Z5d0cwXOR734,8043
+pygments/lexers/graph.py,sha256=WFqoPA1c_hHYrV0i_F7-eUw3Co4_HmZY3GJ-TyDr670,4108
+pygments/lexers/graphics.py,sha256=tmF9NNALnvPnax8ywYC3pLOla45YXtp9UA0H-5EiTQY,39145
+pygments/lexers/graphql.py,sha256=O_zcrGrBaDaKTlUoJGRruxqk7CJi-NR92Y0Cs-KkCvw,5601
+pygments/lexers/graphviz.py,sha256=mzdXOMpwz9_V-be1eTAMyhkKCBl6UxCIXuq6C2yrtsw,1934
+pygments/lexers/gsql.py,sha256=VPZk9sb26-DumRkWfEaSTeoc0lx5xt5n-6eDDLezMtc,3990
+pygments/lexers/hare.py,sha256=PGCOuILktJsmtTpCZZKkMFtObfJuBpei8HM8HHuq1Tw,2649
+pygments/lexers/haskell.py,sha256=MYr74-PAC8kGJRX-dZmvZsHTc7a2u6yFS2B19LfDD7g,33262
+pygments/lexers/haxe.py,sha256=WHCy_nrXHnfLITfbdp3Ji3lqQU4HAsTUpXsLCp2_4sk,30974
+pygments/lexers/hdl.py,sha256=MOWxhmAuE4Ei0CKDqqaON7T8tl43geancrNYM136Z0U,22738
+pygments/lexers/hexdump.py,sha256=1lj9oJ-KiZXSVYvTMfGmEAQzNEW08WlMcC2I5aYvHK4,3653
+pygments/lexers/html.py,sha256=MxYTI4EeT7QxoGleCAyQq-8n_Sgly6tD95H5zanCNmk,21977
+pygments/lexers/idl.py,sha256=rcihUAGhfuGEaSW6pgFq6NzplT_pv0DagUoefg4zAmk,15449
+pygments/lexers/igor.py,sha256=wVefbUjb3ftaW3LCKGtX1JgLgiY4EmRor5gVOn8vQA8,31633
+pygments/lexers/inferno.py,sha256=ChE_5y5SLH_75Uv7D2dKWQMk2dlN6z1gY1IDjlJZ8rU,3135
+pygments/lexers/installers.py,sha256=ZHliit4Pxz1tYKOIjKkDXI5djTkpzYUMVIPR1xvUrL8,14435
+pygments/lexers/int_fiction.py,sha256=0ZzIa1sZDUQsltd1oHuS-BoNiOF8zKQfcVuDyK1Ttv8,56544
+pygments/lexers/iolang.py,sha256=L6dNDCLH0kxkIUi00fI4Z14QnRu79UcNDrgv02c5Zw8,1905
+pygments/lexers/j.py,sha256=DqNdwQGFLiZW3mCNLRg81gpmsy4Hgcai_9NP3LbWhNU,4853
+pygments/lexers/javascript.py,sha256=TGKQLSrCprCKfhLLGAq_0EOdvqvJKX9pOdKo7tCRurQ,63243
+pygments/lexers/jmespath.py,sha256=R5yA5LJ2nTIaDwnFIpSNGAThd0sAYFccwawA9xBptlg,2082
+pygments/lexers/jslt.py,sha256=OeYQf8O2_9FCaf9W6Q3a7rPdAFLthePCtVSgCrOTcl8,3700
+pygments/lexers/json5.py,sha256=8JZbc8EiTEZdKaIdQg3hXEh0mHWSzPlwd473a0nUuT0,2502
+pygments/lexers/jsonnet.py,sha256=bx2G6J4tJqGrJV1PyZrIWzWHXcoefCX-4lIxxtbn2gw,5636
+pygments/lexers/jsx.py,sha256=wGsoGSB40qAJrVfXwRPtan7OcK0O87RVsHHk0m6gogk,2693
+pygments/lexers/julia.py,sha256=0ZDJ9X83V5GqJzA6T6p0TTN8WHy2JAjvu-FSBXvfXdc,11710
+pygments/lexers/jvm.py,sha256=Yt1iQ3QodXRY-x_HUOGedhyuBBHn5jYH-I8NzOzHTlE,72667
+pygments/lexers/kuin.py,sha256=3dKKJVJlskgrvMKv2tY9NOsFfDjyo-3MLcJ1lFKdXSg,11405
+pygments/lexers/kusto.py,sha256=kaxkoPpEBDsBTCvCOkZZx7oGfv0jk_UNIRIRbfVAsBE,3477
+pygments/lexers/ldap.py,sha256=77vF4t_19x9V522cxRCM5d3HW8Ne3giYsFsMPVYYBw4,6551
+pygments/lexers/lean.py,sha256=7HWRgxFsxS1N9XKqw0vfKwaxl27s5YiVYtZeRUoTHFo,8570
+pygments/lexers/lilypond.py,sha256=yd2Tuv67um6EyCIr-VwBnlPhTHxMaQsBJ4nGgO5fjIk,9752
+pygments/lexers/lisp.py,sha256=EHUy1g4pzEsYPE-zGj2rAXm3YATE1j9dCQOr5-JPSkU,157668
+pygments/lexers/macaulay2.py,sha256=zkV-vxjQYa0Jj9TGfFP1iMgpTZ4ApQuAAIdJVGWb2is,33366
+pygments/lexers/make.py,sha256=YMI5DBCrxWca-pz9cVXcyfuHLcikPx9R_3pW_98Myqo,7831
+pygments/lexers/maple.py,sha256=Rs0dEmOMD3C1YQPd0mntN-vzReq4XfHegH6xV4lvJWo,7960
+pygments/lexers/markup.py,sha256=zWtxsyIx_1OxQzS6wLe8bEqglePv4RqvJjbia8AvV5c,65088
+pygments/lexers/math.py,sha256=P3ZK1ePd8ZnLdlmHezo2irCA8T2-nlHBoSaBoT5mEVI,695
+pygments/lexers/matlab.py,sha256=F9KO4qowIhfP8oVhCRRzE_1sqg4zmQbsB2NZH193PiM,133027
+pygments/lexers/maxima.py,sha256=a0h9Ggs9JEovTrzbJT-BLVbOqI29yPnaMZlkU5f_FeY,2715
+pygments/lexers/meson.py,sha256=BMrsDo6BH2lzTFw7JDwQ9SDNMTrRkXCNRDVf4aFHdsI,4336
+pygments/lexers/mime.py,sha256=yGrf3h37LK4b6ERBpFiL_qzn3JgOfGR5KLagnbWFl6c,7582
+pygments/lexers/minecraft.py,sha256=Nu88snDDPzM0D-742fFdUriczL-EE911pAd4_I4-pAw,13696
+pygments/lexers/mips.py,sha256=STKiZT67b3QERXXn7XKVxlPBu7vwbPC5EyCpuf3Jfbw,4656
+pygments/lexers/ml.py,sha256=t8sCv4BjvuBq6AihKKUwStEONIgdXCC2RMtO0RopNbM,35390
+pygments/lexers/modeling.py,sha256=M7B58bGB-Zwd1EmPxKqtRvg7TgNCyem3MVUHv0_H2SQ,13683
+pygments/lexers/modula2.py,sha256=NtpXBRoUCeHfflgB39LknSkCwhBHBKv2Er_pinjVsNE,53072
+pygments/lexers/mojo.py,sha256=8JRVoftN1E-W2woG0K-4n8PQXTUM9iY6Sl5sWb2uGNg,24233
+pygments/lexers/monte.py,sha256=baWU6zlXloenw9MO1MtEVGE9i3CfiXAYhqU621MIjRk,6289
+pygments/lexers/mosel.py,sha256=gjRdedhA1jTjoYoM1Gpaoog_I9o7TRbYMHk97N1TXwg,9297
+pygments/lexers/ncl.py,sha256=zJ6ahlitit4S0pBXc7Wu96PB7xOn59MwfR2HdY5_C60,63999
+pygments/lexers/nimrod.py,sha256=Q1NSqEkLC5wWt7xJyKC-vzWw_Iw2SfDNP_pyMFBuIfA,6413
+pygments/lexers/nit.py,sha256=p_hVD8GzMRl3CABVKHtYgnXFUQk0i5F2FbWFA6WXm6s,2725
+pygments/lexers/nix.py,sha256=NOrv20gdq-2A7eZ6c2gElPHv1Xx2pvv20-qOymL9GMg,4421
+pygments/lexers/numbair.py,sha256=fxkp2CXeXWKBMewfi1H4JSYkmm4kU58wZ2Sh9BDYAWQ,1758
+pygments/lexers/oberon.py,sha256=jw403qUUs7zpTHAs5CbLjb8qiuwtxLk0spDIYqGZwAw,4210
+pygments/lexers/objective.py,sha256=Fo1WB3JMj8sNeYnvB84H4_qwhOt4WNJtJWjVEOwrJGk,23297
+pygments/lexers/ooc.py,sha256=kD1XaJZaihDF_s-Vyu1Bx68S_9zFt2rhox7NF8LpOZM,3002
+pygments/lexers/openscad.py,sha256=h9I1k8kiuQmhX5vZm6VDSr2fa5Finy0sN8ZDIE-jx1c,3700
+pygments/lexers/other.py,sha256=WLVyqPsvm9oSXIbZwbfyJloS6HGgoFW5nVTaU1uQpTw,1763
+pygments/lexers/parasail.py,sha256=DWMGhtyQgGTXbIgQl_mID6CKqi-Dhbvs_dTkmvrZXfE,2719
+pygments/lexers/parsers.py,sha256=feNgxroPoWRf0NEsON2mtmKDUfslIQppukw6ndEsQ3M,26596
+pygments/lexers/pascal.py,sha256=N2tRAjlXnTxggAzzk2tOOAVzeC2MBzrXy97_HQl5n44,30989
+pygments/lexers/pawn.py,sha256=LWUYQYsebMMt2d5oxX1HYWvBqbakR1h7Av_z8Vw94Wg,8253
+pygments/lexers/pddl.py,sha256=Mk4_BzlROJCd0xR4KKRRSrbj0F7LLQcBRjmsmtWmrCg,2989
+pygments/lexers/perl.py,sha256=9BXn3tyHMA49NvzbM9E2czSCHjeU7bvaPLUcoZrhz-4,39192
+pygments/lexers/phix.py,sha256=hZqychqo5sFMBDESzDPXg1DYHQe_9sn294UfbjihaFk,23249
+pygments/lexers/php.py,sha256=l4hzQrlm0525i5dSw9Vmjcai3TzbPT6DkjzxPg9l6Zc,13061
+pygments/lexers/pointless.py,sha256=WSDjqQyGrNIGmTCdaMxl4zk7OZTlJAMzeUZ02kfgcTI,1974
+pygments/lexers/pony.py,sha256=EXrMkacqMZblI7v4AvBRQe-3Py8__bx5FOgjCLdfXxQ,3279
+pygments/lexers/praat.py,sha256=4UFK-nbC6WkZBhJgcQqEGqq9CocJkW7AmT_OJQbjWzk,12676
+pygments/lexers/procfile.py,sha256=05W2fyofLTP-FbEdSXD1eles-PPqVNfF6RWXjQdW2us,1155
+pygments/lexers/prolog.py,sha256=9Kc5YNUFqkfWu2sYoyzC3RX65abf1bm7oHr86z1s4kQ,12866
+pygments/lexers/promql.py,sha256=n-0vo-o8-ZasqP3Va4ujs562UfZSLfZF-RzT71yL0Tk,4738
+pygments/lexers/prql.py,sha256=PFReuvhbv4K5aeu6lvDfw4m-3hULkB3r43bKAy948os,8747
+pygments/lexers/ptx.py,sha256=KSHAvbiNVUntKilQ6EPYoLFocmJpRsBy_7fW6_Nrs1Y,4501
+pygments/lexers/python.py,sha256=WZe7fBAHKZ_BxPg8qIU26UGhk8qwUYyENJ3IyPW64mc,53805
+pygments/lexers/q.py,sha256=WQFUh3JrpK2j-VGW_Ytn3uJ5frUNmQIFnLtMVGRA9DI,6936
+pygments/lexers/qlik.py,sha256=2wqwdfIjrAz6RNBsP4MyeLX8Z7QpIGzxtf1CvaOlr_g,3693
+pygments/lexers/qvt.py,sha256=XMBnsWRrvCDf989OuDeb-KpszAkeETiACyaghZeL1ns,6103
+pygments/lexers/r.py,sha256=B6WgrD9SY1UTCV1fQBSlZbezPfpYsARn3FQIHcFYOiM,6474
+pygments/lexers/rdf.py,sha256=qUzxLna9v071bHhZAjdsBi8dKaJNk_h9g1ZRUAYCfoo,16056
+pygments/lexers/rebol.py,sha256=4u3N4kzui55HapopXDu3Kt0jczxDZ4buzwR7Mt4tQiM,18259
+pygments/lexers/rego.py,sha256=Rx5Gphbktr9ojg5DbqlyxHeQqqtF7g8W-oF0rmloDNY,1748
+pygments/lexers/resource.py,sha256=ioEzgWksB5HCjoz85XNkQPSd7n5kL0SZiuPkJP1hunQ,2927
+pygments/lexers/ride.py,sha256=kCWdxuR3PclVi4wiA0uUx4CYEFwuTqoMsKjhSW4X3yg,5035
+pygments/lexers/rita.py,sha256=Mj1QNxx1sWAZYC02kw8piVckaiw9B0MqQtiIiDFH0pA,1127
+pygments/lexers/rnc.py,sha256=g7ZD334PMGUqy_Ij64laSN1vJerwHqVkegfMCa3E-y8,1972
+pygments/lexers/roboconf.py,sha256=HbYuK5CqmQdd63SRY2nle01r7-p7mil0SnoauYDmEOY,2074
+pygments/lexers/robotframework.py,sha256=c4U1B9Q9ITBCTohqJTZOvkfyeVbenN4xhzSWIoZh5eU,18448
+pygments/lexers/ruby.py,sha256=uG617E5abBZcECRCqkhIfc-IbZcRb5cGuUZq_xpax90,22753
+pygments/lexers/rust.py,sha256=ZY-9vtsreBP0NfDd0WCouLSp_9MChAL8U8Abe-m9PB8,8260
+pygments/lexers/sas.py,sha256=C1Uz2s9DU6_s2kL-cB_PAGPtpyK5THlmhNmCumC1l48,9456
+pygments/lexers/savi.py,sha256=jrmruK0GnXktgBTWXW3oN3TXtofn3HBbkMlHnR84cko,4878
+pygments/lexers/scdoc.py,sha256=DXRmFDmYuc7h3gPAAVhfcL1OEbNBK5RdPpJqQzF3ZTk,2524
+pygments/lexers/scripting.py,sha256=eaYlkDK-_cAwTcCBHP6QXBCz8n6OzbhzdkRe0uV0xWY,81814
+pygments/lexers/sgf.py,sha256=w6C513ENaO2YCnqrduK7k03NaMDf-pgygvfzq2NaSRk,1985
+pygments/lexers/shell.py,sha256=dCS1zwkf5KwTog4__MnMC7h3Xmwv4_d3fnEV29tSwXI,36381
+pygments/lexers/sieve.py,sha256=eob-L84yf2jmhdNyYZUlbUJozdcd6GXcHW68lmAe8WE,2514
+pygments/lexers/slash.py,sha256=I-cRepmaxhL1SgYvD1hHX3gNBFI8NPszdU7hn1o5JlA,8484
+pygments/lexers/smalltalk.py,sha256=ue2PmqDK2sw0j75WdseiiENJBdZ1OwysH2Op1QN1r24,7204
+pygments/lexers/smithy.py,sha256=VREWoeuz7ANap_Uiopn7rs0Tnsfc-xBisDJKRGQY_y8,2659
+pygments/lexers/smv.py,sha256=He_VBSMbWONMWZmkrB5RYR0cfHVnMyKIXz68IFYl-a8,2805
+pygments/lexers/snobol.py,sha256=qDzb41xQQWMNmjB2MtZs23pFoFgZ2gbRZhK_Ir03r7I,2778
+pygments/lexers/solidity.py,sha256=Tixfnwku4Yezj6nNm8xVaw7EdV1qgAgdwahdTFP0St8,3163
+pygments/lexers/soong.py,sha256=Vm18vV4g6T8UPgjjY2yTRlSXGDpZowmuqQUBFfm4A9A,2339
+pygments/lexers/sophia.py,sha256=2YtYIT8iwAoW0B7TZuuoG_ZILhJV-2A7oBGat-98naE,3376
+pygments/lexers/special.py,sha256=8JuR2Vex8X-RWnC36S0HXTHWp2qmZclc90-TrLUWyaY,3585
+pygments/lexers/spice.py,sha256=m4nK0q4Sq_OFQez7kGWfki0No4ZV24YrONfHVj1Piqs,2790
+pygments/lexers/sql.py,sha256=WSG6vOsR87EEEwSQefP_Z7TauUG_BjqMHUFmPaSOVj4,41476
+pygments/lexers/srcinfo.py,sha256=B8vDs-sJogG3mWa5Hp_7JfHHUMyYRwGvKv6cKbFQXLM,1746
+pygments/lexers/stata.py,sha256=Zr9BC52D5O_3BbdW0N-tzoUmy0NTguL2sC-saXRVM-c,6415
+pygments/lexers/supercollider.py,sha256=_H5wDrn0DiGnlhB_cz6Rt_lo2TvqjSm0o6NPTd9R4Ko,3697
+pygments/lexers/tablegen.py,sha256=1JjedXYY18BNiY9JtNGLOtGfiwduNDZpQLBGTeQ6jAw,3987
+pygments/lexers/tact.py,sha256=X_lsxjFUMaC1TmYysXJq9tmAGifRnil83Bt1zA86Xdo,10809
+pygments/lexers/tal.py,sha256=xS9PlaWQOPj8MVr56fUNq31vUQKRWoLTlyWj9ZHm8AM,2904
+pygments/lexers/tcl.py,sha256=lK97ju4nikkt-oGOzIeyFEM98yq4dZSI8uEmYsq0R6c,5512
+pygments/lexers/teal.py,sha256=t3dqy_Arwv8_yExbX_xiFxv1TqJLPv4vh1MVKjKwS4Y,3522
+pygments/lexers/templates.py,sha256=BVdjYeoacIUuFyHTG39j4PxeNCe5E1oUURjH1rITrI4,75731
+pygments/lexers/teraterm.py,sha256=ciwztagW5Drg2gr17Qykrh6GwMsKy7e4xdQshX95GyQ,9718
+pygments/lexers/testing.py,sha256=YZgDgUEaLEYKSKEqpDsUi3Bn-Db_D42IlyiSsr1oX8U,10810
+pygments/lexers/text.py,sha256=nOCQPssIlKdVWU3PKxZiBPkf_KFM2V48IOssSyqhFY8,1068
+pygments/lexers/textedit.py,sha256=ttT4Ph-hIdgFLG6maRy_GskkziTFK0Wcg28yU0s6lek,7760
+pygments/lexers/textfmts.py,sha256=mi9KLEq4mrzDJbEc8G3VM-mSki_Tylkzodu47yH6z84,15524
+pygments/lexers/theorem.py,sha256=51ppBAEdhJmwU_lC916zMyjEoKLXqf89VAE_Lr0PNCc,17855
+pygments/lexers/thingsdb.py,sha256=x_fHNkLA-hIJyeIs6rg_X8n5OLYvFqaSu1FhI3apI5Y,6017
+pygments/lexers/tlb.py,sha256=ue2gqm45BI512lM13O8skAky9zAb7pLMrxZ8pbt5zRU,1450
+pygments/lexers/tls.py,sha256=_uQUVuMRDOhN-XUyGR5DIlVCk1CUZ1fIOSN4_WQYPKk,1540
+pygments/lexers/tnt.py,sha256=pK4LgoKON7u1xF66JYFncAPSbD8DZaeI_WTZ9HqEFlY,10456
+pygments/lexers/trafficscript.py,sha256=X3B8kgxS54ecuok9ic6Hkp-UMn5DvOmCK0p70Tz27Cw,1506
+pygments/lexers/typoscript.py,sha256=mBuePiVZUoAORPKsHwrx6fBWiy3fAIqG-2O67QmMiFI,8332
+pygments/lexers/typst.py,sha256=zIJBEhUXtWp5OiyAmvFA5m8d1EQG-ocwrJ677dvTUAk,7167
+pygments/lexers/ul4.py,sha256=rCaw0J9j3cdql9lX_HTilg65k9-9S118zOA6TAYfxaM,10499
+pygments/lexers/unicon.py,sha256=RAqoCnAAJBYOAGdR8ng0g6FtB39bGemLRlIqv5mcg9E,18625
+pygments/lexers/urbi.py,sha256=ajNP70NJg32jNnFDZsLvr_-4TToSGqRGkFyAPIJLfCU,6082
+pygments/lexers/usd.py,sha256=2eEGouolodYS402P_gtBrn4lLzpg1z8uHwPCKqjUb_k,3304
+pygments/lexers/varnish.py,sha256=dSh0Ku9SrjmlB29Fi_mWdWavN7M0cMKeepR4a34sOyI,7473
+pygments/lexers/verification.py,sha256=Qu433Q_h3EK3uS4bJoLRFZK0kIVwzX5AFKsa4Z-qnxA,3934
+pygments/lexers/verifpal.py,sha256=buyOOzCo_dGnoC40h0tthylHVVpgDt8qXu4olLvYy_4,2661
+pygments/lexers/vip.py,sha256=2lEV4cLV9p4E37wctBL7zkZ4ZU4p3HVsiLJFzB1bie0,5711
+pygments/lexers/vyper.py,sha256=Zq6sQIUBk6mBdpgOVgu3A6swGoBne0kDlRyjZznm2BY,5615
+pygments/lexers/web.py,sha256=4W9a7vcskrGJnxt4KmoE3SZydWB1qLq7lP2XS85J_m8,913
+pygments/lexers/webassembly.py,sha256=zgcMouzLawcbeFr6w_SOvGoUR68ZtqnnsbOcWEVleLk,5698
+pygments/lexers/webidl.py,sha256=ODtVmw4gVzI8HQWxuEckP6KMwm8WP2G2lSZEjagDXts,10516
+pygments/lexers/webmisc.py,sha256=-_-INDVdk47e2jlj-9bFcuLtntqVorBqIjlnwPfZFdI,40564
+pygments/lexers/wgsl.py,sha256=9igd9dzixGIgNewruv9mPnFms-c9BahkZcCCrZygv84,11880
+pygments/lexers/whiley.py,sha256=lMr750lA4MZsB4xqzVsIRtVMJIC3_dArhFYTHvOPwvA,4017
+pygments/lexers/wowtoc.py,sha256=8xxvf0xGeYtf4PE7KtkHZ_ly9xY_XXHrpCitdKE42Ro,4076
+pygments/lexers/wren.py,sha256=goGXnAMKKa13LLL40ybT3aMGPrk3gCRwZQFYAkKB_w0,3229
+pygments/lexers/x10.py,sha256=Q-AmgdF2E-N7mtOPpZ07CsxrTVnikyqC4uRRv6H75sk,1943
+pygments/lexers/xorg.py,sha256=9ttrBd3_Y2nXANsqtMposSgblYmMYqWXQ-Iz5RH9RsU,925
+pygments/lexers/yang.py,sha256=13CWbSaNr9giOHz4o0SXSklh0bfWt0ah14jJGpTvcn0,4499
+pygments/lexers/yara.py,sha256=jUSv78KTDfguCoAoAZKbYzQERkkyxBBWv5dInVrkDxo,2427
+pygments/lexers/zig.py,sha256=f-80MVOSp1KnczAMokQLVM-_wAEOD16EcGFnaCNlsN0,3976
+pygments/modeline.py,sha256=K5eSkR8GS1r5OkXXTHOcV0aM_6xpk9eWNEIAW-OOJ2g,1005
+pygments/plugin.py,sha256=tPx0rJCTIZ9ioRgLNYG4pifCbAwTRUZddvLw-NfAk2w,1891
+pygments/regexopt.py,sha256=wXaP9Gjp_hKAdnICqoDkRxAOQJSc4v3X6mcxx3z-TNs,3072
+pygments/scanner.py,sha256=nNcETRR1tRuiTaHmHSTTECVYFPcLf6mDZu1e4u91A9E,3092
+pygments/sphinxext.py,sha256=VEe_oHNgLoEGMHc2ROfbee2mF2PPREFyE6_m_JN5FvQ,7898
+pygments/style.py,sha256=Cpw9dCAyW3_JAwFRXOJXmtKb5ZwO2_5KSmlq6q4fZw4,6408
+pygments/styles/__init__.py,sha256=f9KCQXN4uKbe8aI8-L3qTC-_XPfT563FwTg6VTGVfwI,2006
+pygments/styles/__pycache__/__init__.cpython-312.pyc,,
+pygments/styles/__pycache__/_mapping.cpython-312.pyc,,
+pygments/styles/__pycache__/abap.cpython-312.pyc,,
+pygments/styles/__pycache__/algol.cpython-312.pyc,,
+pygments/styles/__pycache__/algol_nu.cpython-312.pyc,,
+pygments/styles/__pycache__/arduino.cpython-312.pyc,,
+pygments/styles/__pycache__/autumn.cpython-312.pyc,,
+pygments/styles/__pycache__/borland.cpython-312.pyc,,
+pygments/styles/__pycache__/bw.cpython-312.pyc,,
+pygments/styles/__pycache__/coffee.cpython-312.pyc,,
+pygments/styles/__pycache__/colorful.cpython-312.pyc,,
+pygments/styles/__pycache__/default.cpython-312.pyc,,
+pygments/styles/__pycache__/dracula.cpython-312.pyc,,
+pygments/styles/__pycache__/emacs.cpython-312.pyc,,
+pygments/styles/__pycache__/friendly.cpython-312.pyc,,
+pygments/styles/__pycache__/friendly_grayscale.cpython-312.pyc,,
+pygments/styles/__pycache__/fruity.cpython-312.pyc,,
+pygments/styles/__pycache__/gh_dark.cpython-312.pyc,,
+pygments/styles/__pycache__/gruvbox.cpython-312.pyc,,
+pygments/styles/__pycache__/igor.cpython-312.pyc,,
+pygments/styles/__pycache__/inkpot.cpython-312.pyc,,
+pygments/styles/__pycache__/lightbulb.cpython-312.pyc,,
+pygments/styles/__pycache__/lilypond.cpython-312.pyc,,
+pygments/styles/__pycache__/lovelace.cpython-312.pyc,,
+pygments/styles/__pycache__/manni.cpython-312.pyc,,
+pygments/styles/__pycache__/material.cpython-312.pyc,,
+pygments/styles/__pycache__/monokai.cpython-312.pyc,,
+pygments/styles/__pycache__/murphy.cpython-312.pyc,,
+pygments/styles/__pycache__/native.cpython-312.pyc,,
+pygments/styles/__pycache__/nord.cpython-312.pyc,,
+pygments/styles/__pycache__/onedark.cpython-312.pyc,,
+pygments/styles/__pycache__/paraiso_dark.cpython-312.pyc,,
+pygments/styles/__pycache__/paraiso_light.cpython-312.pyc,,
+pygments/styles/__pycache__/pastie.cpython-312.pyc,,
+pygments/styles/__pycache__/perldoc.cpython-312.pyc,,
+pygments/styles/__pycache__/rainbow_dash.cpython-312.pyc,,
+pygments/styles/__pycache__/rrt.cpython-312.pyc,,
+pygments/styles/__pycache__/sas.cpython-312.pyc,,
+pygments/styles/__pycache__/solarized.cpython-312.pyc,,
+pygments/styles/__pycache__/staroffice.cpython-312.pyc,,
+pygments/styles/__pycache__/stata_dark.cpython-312.pyc,,
+pygments/styles/__pycache__/stata_light.cpython-312.pyc,,
+pygments/styles/__pycache__/tango.cpython-312.pyc,,
+pygments/styles/__pycache__/trac.cpython-312.pyc,,
+pygments/styles/__pycache__/vim.cpython-312.pyc,,
+pygments/styles/__pycache__/vs.cpython-312.pyc,,
+pygments/styles/__pycache__/xcode.cpython-312.pyc,,
+pygments/styles/__pycache__/zenburn.cpython-312.pyc,,
+pygments/styles/_mapping.py,sha256=6lovFUE29tz6EsV3XYY4hgozJ7q1JL7cfO3UOlgnS8w,3312
+pygments/styles/abap.py,sha256=64Uwr8uPdEdcT-tE-Y2VveTXfH3SkqH9qdMgY49YHQI,749
+pygments/styles/algol.py,sha256=fCuk8ITTehvbJSufiaKlgnFsKbl-xFxxR82xhltc-cQ,2262
+pygments/styles/algol_nu.py,sha256=Gv9WfHJvYegGcUk1zcufQgsdXPNjCUNk8sAHyrSGGh4,2283
+pygments/styles/arduino.py,sha256=NoUB8xk7M1HGPoLfuySOLU0sVwoTuLcZqllXl2EO_iE,4557
+pygments/styles/autumn.py,sha256=fLLfjHXjxCl6crBAxEsBLH372ALMkFacA2bG6KFbJi4,2195
+pygments/styles/borland.py,sha256=_0ySKp4KGCSgtYjPe8uzD6gQhlmAIR4T43i-FoRYNOM,1611
+pygments/styles/bw.py,sha256=vhk8Xoj64fLPdA9IQU6mUVsYMel255jR-FDU7BjIHtI,1406
+pygments/styles/coffee.py,sha256=NqLt-fc7LONma1BGggbceVRY9uDE70WBuZXqK4zwaco,2308
+pygments/styles/colorful.py,sha256=mYcSbehtH7itH_QV9NqJp4Wna1X4lrwl2wkVXS2u-5A,2832
+pygments/styles/default.py,sha256=RTgG2zKWWUxPTDCFxhTnyZI_WZBIVgu5XsUpNvFisCA,2588
+pygments/styles/dracula.py,sha256=vRJmixBoSKV9o8NVQhXGViQqchhIYugfikLmvX0DoBw,2182
+pygments/styles/emacs.py,sha256=TiOG9oc83qToMCRMnJrXtWYqnzAqYycRz_50OoCKtxc,2535
+pygments/styles/friendly.py,sha256=oAi-l9anQTs9STDmUzXGDlOegatEOH4hpD0j6o6dZGM,2604
+pygments/styles/friendly_grayscale.py,sha256=a7Cqkzt6-uTiXvj6GoYBXzRvX5_zviCjjRB04Kf_-Q0,2828
+pygments/styles/fruity.py,sha256=GfSUTG0stlJr5Ow_saCaxbI2IB4-34Dp2TuRTpfUJBs,1324
+pygments/styles/gh_dark.py,sha256=ruNX3d4rf22rx-8HnwvGbNbXRQpXCNcHU1HNq6N4uNg,3590
+pygments/styles/gruvbox.py,sha256=KrFoHEoVnZW6XM9udyXncPomeGyZgIDsNWOH3kCrxFQ,3387
+pygments/styles/igor.py,sha256=fYYPhM0dRCvcDTMVrMVO5oFKnYm-8YVlsuVBoczFLtY,737
+pygments/styles/inkpot.py,sha256=jggSeX9NV15eOL2oJaVmZ6vmV7LWRzXJQRUqcWEqGRs,2404
+pygments/styles/lightbulb.py,sha256=Y8u1qdvlHfBqI2jJex55SkvVatVo_FjEUzE6h-X7m-0,3172
+pygments/styles/lilypond.py,sha256=Y6fp_sEL-zESmxAaMxzjtrKk90cuDC_DalNdC8wj0nw,2066
+pygments/styles/lovelace.py,sha256=cA9uhmbnzY04MccsiYSgMY7fvb4WMRbegWBUrGvXh1M,3178
+pygments/styles/manni.py,sha256=g9FyO7plTwfMm2cU4iiKgdlkMlvQLG6l2Lwkgz5ITS4,2443
+pygments/styles/material.py,sha256=LDmgomAbgtJDZhbv446_zIwgYh50UAqEEtgYNUns1rQ,4201
+pygments/styles/monokai.py,sha256=lrxTJpkBarV9gTLkBQryZ6oNSjekAVheJueKJP5iEYA,5184
+pygments/styles/murphy.py,sha256=-AKZiLkpiWej-otjHMsYCE-I-_IzCOLJY-_GBdKRZRw,2805
+pygments/styles/native.py,sha256=l6tezGSQTB8p_SyOXJ0PWI7KzCeEdtsPmVc4Yn4_CwU,2043
+pygments/styles/nord.py,sha256=GDt3WAaqaWsiCeqpIBPxd8TEUX708fGfwaA7S0w0oy0,5391
+pygments/styles/onedark.py,sha256=k80cZEppCEF-HLoxy_FEA0QmQDZze68nHVMNGyUVa28,1719
+pygments/styles/paraiso_dark.py,sha256=Jkrg4nUKIVNF8U4fPNV_Smq_g9NFbb9eiUrjYpVgQZg,5662
+pygments/styles/paraiso_light.py,sha256=MxN964ZEpze3wF0ss-igaa2I7E684MHe-Zq0rWPH3wo,5668
+pygments/styles/pastie.py,sha256=ZvAs9UpBNYFC-5PFrCRGYnm3FoPKb-eKR-ozbWZP-4g,2525
+pygments/styles/perldoc.py,sha256=HSxB93e4UpQkZspReQ34FeJbZ-59ksGvdaH-hToehi8,2230
+pygments/styles/rainbow_dash.py,sha256=4ugL18Or7aNtaLfPfCLFRiFy0Gu2RA4a9G2LQUE9SrM,2390
+pygments/styles/rrt.py,sha256=fgzfpC0PC_SCcLOMCNEIQTjPUMOncRe7SR10GfSRbXY,1006
+pygments/styles/sas.py,sha256=yzoXmbfQ2ND1WWq93b4vVGYkQSZHPqb4ymes9YYRT3w,1440
+pygments/styles/solarized.py,sha256=qupILFZn02WspnAF5SPYb-W8guo9xnUtjb1HeLw3XgE,4247
+pygments/styles/staroffice.py,sha256=CLbBeMoxay21Xyu3Af2p4xUXyG1_6ydCbvs5RJKYe5w,831
+pygments/styles/stata_dark.py,sha256=vX8SwHV__sG92F4CKribG08MJfSVq98dgs7gEA_n9yc,1257
+pygments/styles/stata_light.py,sha256=uV3GE-ylvffQ0yN3py1YAVqBB5wflIKZbceyK1Lqvrc,1289
+pygments/styles/tango.py,sha256=O2wcM4hHuU1Yt071M9CK7JPtiiSCqyxtT9tbiQICV28,7137
+pygments/styles/trac.py,sha256=9kMv1ZZyMKACWlx2fQVjRP0I2pgcRYCNrd7iGGZg9qk,1981
+pygments/styles/vim.py,sha256=J7_TqvrGkTX_XuTHW0In5wqPLAUPRWyr1122XueZWmM,2019
+pygments/styles/vs.py,sha256=s7YnzbIPuFU3LIke27mc4lAQSn2R3vbbHc1baMGSU_U,1130
+pygments/styles/xcode.py,sha256=PbQdzgGaA4a9LAU1i58alY9kM4IFlQX5jHQwOYmf_Rk,1504
+pygments/styles/zenburn.py,sha256=suZEKzBTCYdhf2cxNwcY7UATJK1tq5eYhGdBcXdf6MU,2203
+pygments/token.py,sha256=WbdWGhYm_Vosb0DDxW9lHNPgITXfWTsQmHt6cy9RbcM,6226
+pygments/unistring.py,sha256=al-_rBemRuGvinsrM6atNsHTmJ6DUbw24q2O2Ru1cBc,63208
+pygments/util.py,sha256=oRtSpiAo5jM9ulntkvVbgXUdiAW57jnuYGB7t9fYuhc,10031
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pygments-2.19.2.dist-info/WHEEL b/TTS/Kokoro/.venv/Lib/site-packages/pygments-2.19.2.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..12228d414b6cfed7c39d3781c85c63256a1d7fb5
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pygments-2.19.2.dist-info/WHEEL
@@ -0,0 +1,4 @@
+Wheel-Version: 1.0
+Generator: hatchling 1.27.0
+Root-Is-Purelib: true
+Tag: py3-none-any
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pygments-2.19.2.dist-info/entry_points.txt b/TTS/Kokoro/.venv/Lib/site-packages/pygments-2.19.2.dist-info/entry_points.txt
new file mode 100644
index 0000000000000000000000000000000000000000..15498e35f53320bd5e1de176928daabf26be0109
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pygments-2.19.2.dist-info/entry_points.txt
@@ -0,0 +1,2 @@
+[console_scripts]
+pygmentize = pygments.cmdline:main
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pygments/__init__.py b/TTS/Kokoro/.venv/Lib/site-packages/pygments/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..2a391c3e47997637afeea6a1ec819e5e035514ff
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pygments/__init__.py
@@ -0,0 +1,82 @@
+"""
+    Pygments
+    ~~~~~~~~
+
+    Pygments is a syntax highlighting package written in Python.
+
+    It is a generic syntax highlighter for general use in all kinds of software
+    such as forum systems, wikis or other applications that need to prettify
+    source code. Highlights are:
+
+    * a wide range of common languages and markup formats is supported
+    * special attention is paid to details, increasing quality by a fair amount
+    * support for new languages and formats are added easily
+    * a number of output formats, presently HTML, LaTeX, RTF, SVG, all image
+      formats that PIL supports, and ANSI sequences
+    * it is usable as a command-line tool and as a library
+    * ... and it highlights even Brainfuck!
+
+    The `Pygments master branch`_ is installable with ``easy_install Pygments==dev``.
+
+    .. _Pygments master branch:
+       https://github.com/pygments/pygments/archive/master.zip#egg=Pygments-dev
+
+    :copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+from io import StringIO, BytesIO
+
+__version__ = '2.19.2'
+__docformat__ = 'restructuredtext'
+
+__all__ = ['lex', 'format', 'highlight']
+
+
+def lex(code, lexer):
+    """
+    Lex `code` with the `lexer` (must be a `Lexer` instance)
+    and return an iterable of tokens. Currently, this only calls
+    `lexer.get_tokens()`.
+    """
+    try:
+        return lexer.get_tokens(code)
+    except TypeError:
+        # Heuristic to catch a common mistake.
+        from pygments.lexer import RegexLexer
+        if isinstance(lexer, type) and issubclass(lexer, RegexLexer):
+            raise TypeError('lex() argument must be a lexer instance, '
+                            'not a class')
+        raise
+
+
+def format(tokens, formatter, outfile=None):  # pylint: disable=redefined-builtin
+    """
+    Format ``tokens`` (an iterable of tokens) with the formatter ``formatter``
+    (a `Formatter` instance).
+
+    If ``outfile`` is given and a valid file object (an object with a
+    ``write`` method), the result will be written to it, otherwise it
+    is returned as a string.
+    """
+    try:
+        if not outfile:
+            realoutfile = getattr(formatter, 'encoding', None) and BytesIO() or StringIO()
+            formatter.format(tokens, realoutfile)
+            return realoutfile.getvalue()
+        else:
+            formatter.format(tokens, outfile)
+    except TypeError:
+        # Heuristic to catch a common mistake.
+        from pygments.formatter import Formatter
+        if isinstance(formatter, type) and issubclass(formatter, Formatter):
+            raise TypeError('format() argument must be a formatter instance, '
+                            'not a class')
+        raise
+
+
+def highlight(code, lexer, formatter, outfile=None):
+    """
+    This is the most high-level highlighting function. It combines `lex` and
+    `format` in one function.
+    """
+    return format(lex(code, lexer), formatter, outfile)
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pygments/__main__.py b/TTS/Kokoro/.venv/Lib/site-packages/pygments/__main__.py
new file mode 100644
index 0000000000000000000000000000000000000000..4890a6c768509d85d614e6953388e6cda6162bb6
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pygments/__main__.py
@@ -0,0 +1,17 @@
+"""
+    pygments.__main__
+    ~~~~~~~~~~~~~~~~~
+
+    Main entry point for ``python -m pygments``.
+
+    :copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+import sys
+import pygments.cmdline
+
+try:
+    sys.exit(pygments.cmdline.main(sys.argv))
+except KeyboardInterrupt:
+    sys.exit(1)
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pygments/cmdline.py b/TTS/Kokoro/.venv/Lib/site-packages/pygments/cmdline.py
new file mode 100644
index 0000000000000000000000000000000000000000..2878fd55a7924d38ed979e26f565539d6bae621a
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pygments/cmdline.py
@@ -0,0 +1,668 @@
+"""
+    pygments.cmdline
+    ~~~~~~~~~~~~~~~~
+
+    Command line interface.
+
+    :copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+import os
+import sys
+import shutil
+import argparse
+from textwrap import dedent
+
+from pygments import __version__, highlight
+from pygments.util import ClassNotFound, OptionError, docstring_headline, \
+    guess_decode, guess_decode_from_terminal, terminal_encoding, \
+    UnclosingTextIOWrapper
+from pygments.lexers import get_all_lexers, get_lexer_by_name, guess_lexer, \
+    load_lexer_from_file, get_lexer_for_filename, find_lexer_class_for_filename
+from pygments.lexers.special import TextLexer
+from pygments.formatters.latex import LatexEmbeddedLexer, LatexFormatter
+from pygments.formatters import get_all_formatters, get_formatter_by_name, \
+    load_formatter_from_file, get_formatter_for_filename, find_formatter_class
+from pygments.formatters.terminal import TerminalFormatter
+from pygments.formatters.terminal256 import Terminal256Formatter, TerminalTrueColorFormatter
+from pygments.filters import get_all_filters, find_filter_class
+from pygments.styles import get_all_styles, get_style_by_name
+
+
+def _parse_options(o_strs):
+    opts = {}
+    if not o_strs:
+        return opts
+    for o_str in o_strs:
+        if not o_str.strip():
+            continue
+        o_args = o_str.split(',')
+        for o_arg in o_args:
+            o_arg = o_arg.strip()
+            try:
+                o_key, o_val = o_arg.split('=', 1)
+                o_key = o_key.strip()
+                o_val = o_val.strip()
+            except ValueError:
+                opts[o_arg] = True
+            else:
+                opts[o_key] = o_val
+    return opts
+
+
+def _parse_filters(f_strs):
+    filters = []
+    if not f_strs:
+        return filters
+    for f_str in f_strs:
+        if ':' in f_str:
+            fname, fopts = f_str.split(':', 1)
+            filters.append((fname, _parse_options([fopts])))
+        else:
+            filters.append((f_str, {}))
+    return filters
+
+
+def _print_help(what, name):
+    try:
+        if what == 'lexer':
+            cls = get_lexer_by_name(name)
+            print(f"Help on the {cls.name} lexer:")
+            print(dedent(cls.__doc__))
+        elif what == 'formatter':
+            cls = find_formatter_class(name)
+            print(f"Help on the {cls.name} formatter:")
+            print(dedent(cls.__doc__))
+        elif what == 'filter':
+            cls = find_filter_class(name)
+            print(f"Help on the {name} filter:")
+            print(dedent(cls.__doc__))
+        return 0
+    except (AttributeError, ValueError):
+        print(f"{what} not found!", file=sys.stderr)
+        return 1
+
+
+def _print_list(what):
+    if what == 'lexer':
+        print()
+        print("Lexers:")
+        print("~~~~~~~")
+
+        info = []
+        for fullname, names, exts, _ in get_all_lexers():
+            tup = (', '.join(names)+':', fullname,
+                   exts and '(filenames ' + ', '.join(exts) + ')' or '')
+            info.append(tup)
+        info.sort()
+        for i in info:
+            print(('* {}\n    {} {}').format(*i))
+
+    elif what == 'formatter':
+        print()
+        print("Formatters:")
+        print("~~~~~~~~~~~")
+
+        info = []
+        for cls in get_all_formatters():
+            doc = docstring_headline(cls)
+            tup = (', '.join(cls.aliases) + ':', doc, cls.filenames and
+                   '(filenames ' + ', '.join(cls.filenames) + ')' or '')
+            info.append(tup)
+        info.sort()
+        for i in info:
+            print(('* {}\n    {} {}').format(*i))
+
+    elif what == 'filter':
+        print()
+        print("Filters:")
+        print("~~~~~~~~")
+
+        for name in get_all_filters():
+            cls = find_filter_class(name)
+            print("* " + name + ':')
+            print(f"    {docstring_headline(cls)}")
+
+    elif what == 'style':
+        print()
+        print("Styles:")
+        print("~~~~~~~")
+
+        for name in get_all_styles():
+            cls = get_style_by_name(name)
+            print("* " + name + ':')
+            print(f"    {docstring_headline(cls)}")
+
+
+def _print_list_as_json(requested_items):
+    import json
+    result = {}
+    if 'lexer' in requested_items:
+        info = {}
+        for fullname, names, filenames, mimetypes in get_all_lexers():
+            info[fullname] = {
+                'aliases': names,
+                'filenames': filenames,
+                'mimetypes': mimetypes
+            }
+        result['lexers'] = info
+
+    if 'formatter' in requested_items:
+        info = {}
+        for cls in get_all_formatters():
+            doc = docstring_headline(cls)
+            info[cls.name] = {
+                'aliases': cls.aliases,
+                'filenames': cls.filenames,
+                'doc': doc
+            }
+        result['formatters'] = info
+
+    if 'filter' in requested_items:
+        info = {}
+        for name in get_all_filters():
+            cls = find_filter_class(name)
+            info[name] = {
+                'doc': docstring_headline(cls)
+            }
+        result['filters'] = info
+
+    if 'style' in requested_items:
+        info = {}
+        for name in get_all_styles():
+            cls = get_style_by_name(name)
+            info[name] = {
+                'doc': docstring_headline(cls)
+            }
+        result['styles'] = info
+
+    json.dump(result, sys.stdout)
+
+def main_inner(parser, argns):
+    if argns.help:
+        parser.print_help()
+        return 0
+
+    if argns.V:
+        print(f'Pygments version {__version__}, (c) 2006-2024 by Georg Brandl, Matthäus '
+              'Chajdas and contributors.')
+        return 0
+
+    def is_only_option(opt):
+        return not any(v for (k, v) in vars(argns).items() if k != opt)
+
+    # handle ``pygmentize -L``
+    if argns.L is not None:
+        arg_set = set()
+        for k, v in vars(argns).items():
+            if v:
+                arg_set.add(k)
+
+        arg_set.discard('L')
+        arg_set.discard('json')
+
+        if arg_set:
+            parser.print_help(sys.stderr)
+            return 2
+
+        # print version
+        if not argns.json:
+            main(['', '-V'])
+        allowed_types = {'lexer', 'formatter', 'filter', 'style'}
+        largs = [arg.rstrip('s') for arg in argns.L]
+        if any(arg not in allowed_types for arg in largs):
+            parser.print_help(sys.stderr)
+            return 0
+        if not largs:
+            largs = allowed_types
+        if not argns.json:
+            for arg in largs:
+                _print_list(arg)
+        else:
+            _print_list_as_json(largs)
+        return 0
+
+    # handle ``pygmentize -H``
+    if argns.H:
+        if not is_only_option('H'):
+            parser.print_help(sys.stderr)
+            return 2
+        what, name = argns.H
+        if what not in ('lexer', 'formatter', 'filter'):
+            parser.print_help(sys.stderr)
+            return 2
+        return _print_help(what, name)
+
+    # parse -O options
+    parsed_opts = _parse_options(argns.O or [])
+
+    # parse -P options
+    for p_opt in argns.P or []:
+        try:
+            name, value = p_opt.split('=', 1)
+        except ValueError:
+            parsed_opts[p_opt] = True
+        else:
+            parsed_opts[name] = value
+
+    # encodings
+    inencoding = parsed_opts.get('inencoding', parsed_opts.get('encoding'))
+    outencoding = parsed_opts.get('outencoding', parsed_opts.get('encoding'))
+
+    # handle ``pygmentize -N``
+    if argns.N:
+        lexer = find_lexer_class_for_filename(argns.N)
+        if lexer is None:
+            lexer = TextLexer
+
+        print(lexer.aliases[0])
+        return 0
+
+    # handle ``pygmentize -C``
+    if argns.C:
+        inp = sys.stdin.buffer.read()
+        try:
+            lexer = guess_lexer(inp, inencoding=inencoding)
+        except ClassNotFound:
+            lexer = TextLexer
+
+        print(lexer.aliases[0])
+        return 0
+
+    # handle ``pygmentize -S``
+    S_opt = argns.S
+    a_opt = argns.a
+    if S_opt is not None:
+        f_opt = argns.f
+        if not f_opt:
+            parser.print_help(sys.stderr)
+            return 2
+        if argns.l or argns.INPUTFILE:
+            parser.print_help(sys.stderr)
+            return 2
+
+        try:
+            parsed_opts['style'] = S_opt
+            fmter = get_formatter_by_name(f_opt, **parsed_opts)
+        except ClassNotFound as err:
+            print(err, file=sys.stderr)
+            return 1
+
+        print(fmter.get_style_defs(a_opt or ''))
+        return 0
+
+    # if no -S is given, -a is not allowed
+    if argns.a is not None:
+        parser.print_help(sys.stderr)
+        return 2
+
+    # parse -F options
+    F_opts = _parse_filters(argns.F or [])
+
+    # -x: allow custom (eXternal) lexers and formatters
+    allow_custom_lexer_formatter = bool(argns.x)
+
+    # select lexer
+    lexer = None
+
+    # given by name?
+    lexername = argns.l
+    if lexername:
+        # custom lexer, located relative to user's cwd
+        if allow_custom_lexer_formatter and '.py' in lexername:
+            try:
+                filename = None
+                name = None
+                if ':' in lexername:
+                    filename, name = lexername.rsplit(':', 1)
+
+                    if '.py' in name:
+                        # This can happen on Windows: If the lexername is
+                        # C:\lexer.py -- return to normal load path in that case
+                        name = None
+
+                if filename and name:
+                    lexer = load_lexer_from_file(filename, name,
+                                                 **parsed_opts)
+                else:
+                    lexer = load_lexer_from_file(lexername, **parsed_opts)
+            except ClassNotFound as err:
+                print('Error:', err, file=sys.stderr)
+                return 1
+        else:
+            try:
+                lexer = get_lexer_by_name(lexername, **parsed_opts)
+            except (OptionError, ClassNotFound) as err:
+                print('Error:', err, file=sys.stderr)
+                return 1
+
+    # read input code
+    code = None
+
+    if argns.INPUTFILE:
+        if argns.s:
+            print('Error: -s option not usable when input file specified',
+                  file=sys.stderr)
+            return 2
+
+        infn = argns.INPUTFILE
+        try:
+            with open(infn, 'rb') as infp:
+                code = infp.read()
+        except Exception as err:
+            print('Error: cannot read infile:', err, file=sys.stderr)
+            return 1
+        if not inencoding:
+            code, inencoding = guess_decode(code)
+
+        # do we have to guess the lexer?
+        if not lexer:
+            try:
+                lexer = get_lexer_for_filename(infn, code, **parsed_opts)
+            except ClassNotFound as err:
+                if argns.g:
+                    try:
+                        lexer = guess_lexer(code, **parsed_opts)
+                    except ClassNotFound:
+                        lexer = TextLexer(**parsed_opts)
+                else:
+                    print('Error:', err, file=sys.stderr)
+                    return 1
+            except OptionError as err:
+                print('Error:', err, file=sys.stderr)
+                return 1
+
+    elif not argns.s:  # treat stdin as full file (-s support is later)
+        # read code from terminal, always in binary mode since we want to
+        # decode ourselves and be tolerant with it
+        code = sys.stdin.buffer.read()  # use .buffer to get a binary stream
+        if not inencoding:
+            code, inencoding = guess_decode_from_terminal(code, sys.stdin)
+            # else the lexer will do the decoding
+        if not lexer:
+            try:
+                lexer = guess_lexer(code, **parsed_opts)
+            except ClassNotFound:
+                lexer = TextLexer(**parsed_opts)
+
+    else:  # -s option needs a lexer with -l
+        if not lexer:
+            print('Error: when using -s a lexer has to be selected with -l',
+                  file=sys.stderr)
+            return 2
+
+    # process filters
+    for fname, fopts in F_opts:
+        try:
+            lexer.add_filter(fname, **fopts)
+        except ClassNotFound as err:
+            print('Error:', err, file=sys.stderr)
+            return 1
+
+    # select formatter
+    outfn = argns.o
+    fmter = argns.f
+    if fmter:
+        # custom formatter, located relative to user's cwd
+        if allow_custom_lexer_formatter and '.py' in fmter:
+            try:
+                filename = None
+                name = None
+                if ':' in fmter:
+                    # Same logic as above for custom lexer
+                    filename, name = fmter.rsplit(':', 1)
+
+                    if '.py' in name:
+                        name = None
+
+                if filename and name:
+                    fmter = load_formatter_from_file(filename, name,
+                                                     **parsed_opts)
+                else:
+                    fmter = load_formatter_from_file(fmter, **parsed_opts)
+            except ClassNotFound as err:
+                print('Error:', err, file=sys.stderr)
+                return 1
+        else:
+            try:
+                fmter = get_formatter_by_name(fmter, **parsed_opts)
+            except (OptionError, ClassNotFound) as err:
+                print('Error:', err, file=sys.stderr)
+                return 1
+
+    if outfn:
+        if not fmter:
+            try:
+                fmter = get_formatter_for_filename(outfn, **parsed_opts)
+            except (OptionError, ClassNotFound) as err:
+                print('Error:', err, file=sys.stderr)
+                return 1
+        try:
+            outfile = open(outfn, 'wb')
+        except Exception as err:
+            print('Error: cannot open outfile:', err, file=sys.stderr)
+            return 1
+    else:
+        if not fmter:
+            if os.environ.get('COLORTERM','') in ('truecolor', '24bit'):
+                fmter = TerminalTrueColorFormatter(**parsed_opts)
+            elif '256' in os.environ.get('TERM', ''):
+                fmter = Terminal256Formatter(**parsed_opts)
+            else:
+                fmter = TerminalFormatter(**parsed_opts)
+        outfile = sys.stdout.buffer
+
+    # determine output encoding if not explicitly selected
+    if not outencoding:
+        if outfn:
+            # output file? use lexer encoding for now (can still be None)
+            fmter.encoding = inencoding
+        else:
+            # else use terminal encoding
+            fmter.encoding = terminal_encoding(sys.stdout)
+
+    # provide coloring under Windows, if possible
+    if not outfn and sys.platform in ('win32', 'cygwin') and \
+       fmter.name in ('Terminal', 'Terminal256'):  # pragma: no cover
+        # unfortunately colorama doesn't support binary streams on Py3
+        outfile = UnclosingTextIOWrapper(outfile, encoding=fmter.encoding)
+        fmter.encoding = None
+        try:
+            import colorama.initialise
+        except ImportError:
+            pass
+        else:
+            outfile = colorama.initialise.wrap_stream(
+                outfile, convert=None, strip=None, autoreset=False, wrap=True)
+
+    # When using the LaTeX formatter and the option `escapeinside` is
+    # specified, we need a special lexer which collects escaped text
+    # before running the chosen language lexer.
+    escapeinside = parsed_opts.get('escapeinside', '')
+    if len(escapeinside) == 2 and isinstance(fmter, LatexFormatter):
+        left = escapeinside[0]
+        right = escapeinside[1]
+        lexer = LatexEmbeddedLexer(left, right, lexer)
+
+    # ... and do it!
+    if not argns.s:
+        # process whole input as per normal...
+        try:
+            highlight(code, lexer, fmter, outfile)
+        finally:
+            if outfn:
+                outfile.close()
+        return 0
+    else:
+        # line by line processing of stdin (eg: for 'tail -f')...
+        try:
+            while 1:
+                line = sys.stdin.buffer.readline()
+                if not line:
+                    break
+                if not inencoding:
+                    line = guess_decode_from_terminal(line, sys.stdin)[0]
+                highlight(line, lexer, fmter, outfile)
+                if hasattr(outfile, 'flush'):
+                    outfile.flush()
+            return 0
+        except KeyboardInterrupt:  # pragma: no cover
+            return 0
+        finally:
+            if outfn:
+                outfile.close()
+
+
+class HelpFormatter(argparse.HelpFormatter):
+    def __init__(self, prog, indent_increment=2, max_help_position=16, width=None):
+        if width is None:
+            try:
+                width = shutil.get_terminal_size().columns - 2
+            except Exception:
+                pass
+        argparse.HelpFormatter.__init__(self, prog, indent_increment,
+                                        max_help_position, width)
+
+
+def main(args=sys.argv):
+    """
+    Main command line entry point.
+    """
+    desc = "Highlight an input file and write the result to an output file."
+    parser = argparse.ArgumentParser(description=desc, add_help=False,
+                                     formatter_class=HelpFormatter)
+
+    operation = parser.add_argument_group('Main operation')
+    lexersel = operation.add_mutually_exclusive_group()
+    lexersel.add_argument(
+        '-l', metavar='LEXER',
+        help='Specify the lexer to use.  (Query names with -L.)  If not '
+        'given and -g is not present, the lexer is guessed from the filename.')
+    lexersel.add_argument(
+        '-g', action='store_true',
+        help='Guess the lexer from the file contents, or pass through '
+        'as plain text if nothing can be guessed.')
+    operation.add_argument(
+        '-F', metavar='FILTER[:options]', action='append',
+        help='Add a filter to the token stream.  (Query names with -L.) '
+        'Filter options are given after a colon if necessary.')
+    operation.add_argument(
+        '-f', metavar='FORMATTER',
+        help='Specify the formatter to use.  (Query names with -L.) '
+        'If not given, the formatter is guessed from the output filename, '
+        'and defaults to the terminal formatter if the output is to the '
+        'terminal or an unknown file extension.')
+    operation.add_argument(
+        '-O', metavar='OPTION=value[,OPTION=value,...]', action='append',
+        help='Give options to the lexer and formatter as a comma-separated '
+        'list of key-value pairs. '
+        'Example: `-O bg=light,python=cool`.')
+    operation.add_argument(
+        '-P', metavar='OPTION=value', action='append',
+        help='Give a single option to the lexer and formatter - with this '
+        'you can pass options whose value contains commas and equal signs. '
+        'Example: `-P "heading=Pygments, the Python highlighter"`.')
+    operation.add_argument(
+        '-o', metavar='OUTPUTFILE',
+        help='Where to write the output.  Defaults to standard output.')
+
+    operation.add_argument(
+        'INPUTFILE', nargs='?',
+        help='Where to read the input.  Defaults to standard input.')
+
+    flags = parser.add_argument_group('Operation flags')
+    flags.add_argument(
+        '-v', action='store_true',
+        help='Print a detailed traceback on unhandled exceptions, which '
+        'is useful for debugging and bug reports.')
+    flags.add_argument(
+        '-s', action='store_true',
+        help='Process lines one at a time until EOF, rather than waiting to '
+        'process the entire file.  This only works for stdin, only for lexers '
+        'with no line-spanning constructs, and is intended for streaming '
+        'input such as you get from `tail -f`. '
+        'Example usage: `tail -f sql.log | pygmentize -s -l sql`.')
+    flags.add_argument(
+        '-x', action='store_true',
+        help='Allow custom lexers and formatters to be loaded from a .py file '
+        'relative to the current working directory. For example, '
+        '`-l ./customlexer.py -x`. By default, this option expects a file '
+        'with a class named CustomLexer or CustomFormatter; you can also '
+        'specify your own class name with a colon (`-l ./lexer.py:MyLexer`). '
+        'Users should be very careful not to use this option with untrusted '
+        'files, because it will import and run them.')
+    flags.add_argument('--json', help='Output as JSON. This can '
+        'be only used in conjunction with -L.',
+        default=False,
+        action='store_true')
+
+    special_modes_group = parser.add_argument_group(
+        'Special modes - do not do any highlighting')
+    special_modes = special_modes_group.add_mutually_exclusive_group()
+    special_modes.add_argument(
+        '-S', metavar='STYLE -f formatter',
+        help='Print style definitions for STYLE for a formatter '
+        'given with -f. The argument given by -a is formatter '
+        'dependent.')
+    special_modes.add_argument(
+        '-L', nargs='*', metavar='WHAT',
+        help='List lexers, formatters, styles or filters -- '
+        'give additional arguments for the thing(s) you want to list '
+        '(e.g. "styles"), or omit them to list everything.')
+    special_modes.add_argument(
+        '-N', metavar='FILENAME',
+        help='Guess and print out a lexer name based solely on the given '
+        'filename. Does not take input or highlight anything. If no specific '
+        'lexer can be determined, "text" is printed.')
+    special_modes.add_argument(
+        '-C', action='store_true',
+        help='Like -N, but print out a lexer name based solely on '
+        'a given content from standard input.')
+    special_modes.add_argument(
+        '-H', action='store', nargs=2, metavar=('NAME', 'TYPE'),
+        help='Print detailed help for the object  of type , '
+        'where  is one of "lexer", "formatter" or "filter".')
+    special_modes.add_argument(
+        '-V', action='store_true',
+        help='Print the package version.')
+    special_modes.add_argument(
+        '-h', '--help', action='store_true',
+        help='Print this help.')
+    special_modes_group.add_argument(
+        '-a', metavar='ARG',
+        help='Formatter-specific additional argument for the -S (print '
+        'style sheet) mode.')
+
+    argns = parser.parse_args(args[1:])
+
+    try:
+        return main_inner(parser, argns)
+    except BrokenPipeError:
+        # someone closed our stdout, e.g. by quitting a pager.
+        return 0
+    except Exception:
+        if argns.v:
+            print(file=sys.stderr)
+            print('*' * 65, file=sys.stderr)
+            print('An unhandled exception occurred while highlighting.',
+                  file=sys.stderr)
+            print('Please report the whole traceback to the issue tracker at',
+                  file=sys.stderr)
+            print('.',
+                  file=sys.stderr)
+            print('*' * 65, file=sys.stderr)
+            print(file=sys.stderr)
+            raise
+        import traceback
+        info = traceback.format_exception(*sys.exc_info())
+        msg = info[-1].strip()
+        if len(info) >= 3:
+            # extract relevant file and position info
+            msg += '\n   (f{})'.format(info[-2].split('\n')[0].strip()[1:])
+        print(file=sys.stderr)
+        print('*** Error while highlighting:', file=sys.stderr)
+        print(msg, file=sys.stderr)
+        print('*** If this is a bug you want to report, please rerun with -v.',
+              file=sys.stderr)
+        return 1
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pygments/console.py b/TTS/Kokoro/.venv/Lib/site-packages/pygments/console.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee1ac27a2ffdc119a1db9128a034300b31d464a8
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pygments/console.py
@@ -0,0 +1,70 @@
+"""
+    pygments.console
+    ~~~~~~~~~~~~~~~~
+
+    Format colored console output.
+
+    :copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+esc = "\x1b["
+
+codes = {}
+codes[""] = ""
+codes["reset"] = esc + "39;49;00m"
+
+codes["bold"] = esc + "01m"
+codes["faint"] = esc + "02m"
+codes["standout"] = esc + "03m"
+codes["underline"] = esc + "04m"
+codes["blink"] = esc + "05m"
+codes["overline"] = esc + "06m"
+
+dark_colors = ["black", "red", "green", "yellow", "blue",
+               "magenta", "cyan", "gray"]
+light_colors = ["brightblack", "brightred", "brightgreen", "brightyellow", "brightblue",
+                "brightmagenta", "brightcyan", "white"]
+
+x = 30
+for dark, light in zip(dark_colors, light_colors):
+    codes[dark] = esc + "%im" % x
+    codes[light] = esc + "%im" % (60 + x)
+    x += 1
+
+del dark, light, x
+
+codes["white"] = codes["bold"]
+
+
+def reset_color():
+    return codes["reset"]
+
+
+def colorize(color_key, text):
+    return codes[color_key] + text + codes["reset"]
+
+
+def ansiformat(attr, text):
+    """
+    Format ``text`` with a color and/or some attributes::
+
+        color       normal color
+        *color*     bold color
+        _color_     underlined color
+        +color+     blinking color
+    """
+    result = []
+    if attr[:1] == attr[-1:] == '+':
+        result.append(codes['blink'])
+        attr = attr[1:-1]
+    if attr[:1] == attr[-1:] == '*':
+        result.append(codes['bold'])
+        attr = attr[1:-1]
+    if attr[:1] == attr[-1:] == '_':
+        result.append(codes['underline'])
+        attr = attr[1:-1]
+    result.append(codes[attr])
+    result.append(text)
+    result.append(codes['reset'])
+    return ''.join(result)
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pygments/filter.py b/TTS/Kokoro/.venv/Lib/site-packages/pygments/filter.py
new file mode 100644
index 0000000000000000000000000000000000000000..5efff438d2b3a187c681e445e4607b529f3ce42a
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pygments/filter.py
@@ -0,0 +1,70 @@
+"""
+    pygments.filter
+    ~~~~~~~~~~~~~~~
+
+    Module that implements the default filter.
+
+    :copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+
+def apply_filters(stream, filters, lexer=None):
+    """
+    Use this method to apply an iterable of filters to
+    a stream. If lexer is given it's forwarded to the
+    filter, otherwise the filter receives `None`.
+    """
+    def _apply(filter_, stream):
+        yield from filter_.filter(lexer, stream)
+    for filter_ in filters:
+        stream = _apply(filter_, stream)
+    return stream
+
+
+def simplefilter(f):
+    """
+    Decorator that converts a function into a filter::
+
+        @simplefilter
+        def lowercase(self, lexer, stream, options):
+            for ttype, value in stream:
+                yield ttype, value.lower()
+    """
+    return type(f.__name__, (FunctionFilter,), {
+        '__module__': getattr(f, '__module__'),
+        '__doc__': f.__doc__,
+        'function': f,
+    })
+
+
+class Filter:
+    """
+    Default filter. Subclass this class or use the `simplefilter`
+    decorator to create own filters.
+    """
+
+    def __init__(self, **options):
+        self.options = options
+
+    def filter(self, lexer, stream):
+        raise NotImplementedError()
+
+
+class FunctionFilter(Filter):
+    """
+    Abstract class used by `simplefilter` to create simple
+    function filters on the fly. The `simplefilter` decorator
+    automatically creates subclasses of this class for
+    functions passed to it.
+    """
+    function = None
+
+    def __init__(self, **options):
+        if not hasattr(self, 'function'):
+            raise TypeError(f'{self.__class__.__name__!r} used without bound function')
+        Filter.__init__(self, **options)
+
+    def filter(self, lexer, stream):
+        # pylint: disable=not-callable
+        yield from self.function(lexer, stream, self.options)
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pygments/formatter.py b/TTS/Kokoro/.venv/Lib/site-packages/pygments/formatter.py
new file mode 100644
index 0000000000000000000000000000000000000000..a20d3039d3dd3c40881f392136640f9d1a7e5e82
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pygments/formatter.py
@@ -0,0 +1,129 @@
+"""
+    pygments.formatter
+    ~~~~~~~~~~~~~~~~~~
+
+    Base formatter class.
+
+    :copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+import codecs
+
+from pygments.util import get_bool_opt
+from pygments.styles import get_style_by_name
+
+__all__ = ['Formatter']
+
+
+def _lookup_style(style):
+    if isinstance(style, str):
+        return get_style_by_name(style)
+    return style
+
+
+class Formatter:
+    """
+    Converts a token stream to text.
+
+    Formatters should have attributes to help selecting them. These
+    are similar to the corresponding :class:`~pygments.lexer.Lexer`
+    attributes.
+
+    .. autoattribute:: name
+       :no-value:
+
+    .. autoattribute:: aliases
+       :no-value:
+
+    .. autoattribute:: filenames
+       :no-value:
+
+    You can pass options as keyword arguments to the constructor.
+    All formatters accept these basic options:
+
+    ``style``
+        The style to use, can be a string or a Style subclass
+        (default: "default"). Not used by e.g. the
+        TerminalFormatter.
+    ``full``
+        Tells the formatter to output a "full" document, i.e.
+        a complete self-contained document. This doesn't have
+        any effect for some formatters (default: false).
+    ``title``
+        If ``full`` is true, the title that should be used to
+        caption the document (default: '').
+    ``encoding``
+        If given, must be an encoding name. This will be used to
+        convert the Unicode token strings to byte strings in the
+        output. If it is "" or None, Unicode strings will be written
+        to the output file, which most file-like objects do not
+        support (default: None).
+    ``outencoding``
+        Overrides ``encoding`` if given.
+
+    """
+
+    #: Full name for the formatter, in human-readable form.
+    name = None
+
+    #: A list of short, unique identifiers that can be used to lookup
+    #: the formatter from a list, e.g. using :func:`.get_formatter_by_name()`.
+    aliases = []
+
+    #: A list of fnmatch patterns that match filenames for which this
+    #: formatter can produce output. The patterns in this list should be unique
+    #: among all formatters.
+    filenames = []
+
+    #: If True, this formatter outputs Unicode strings when no encoding
+    #: option is given.
+    unicodeoutput = True
+
+    def __init__(self, **options):
+        """
+        As with lexers, this constructor takes arbitrary optional arguments,
+        and if you override it, you should first process your own options, then
+        call the base class implementation.
+        """
+        self.style = _lookup_style(options.get('style', 'default'))
+        self.full = get_bool_opt(options, 'full', False)
+        self.title = options.get('title', '')
+        self.encoding = options.get('encoding', None) or None
+        if self.encoding in ('guess', 'chardet'):
+            # can happen for e.g. pygmentize -O encoding=guess
+            self.encoding = 'utf-8'
+        self.encoding = options.get('outencoding') or self.encoding
+        self.options = options
+
+    def get_style_defs(self, arg=''):
+        """
+        This method must return statements or declarations suitable to define
+        the current style for subsequent highlighted text (e.g. CSS classes
+        in the `HTMLFormatter`).
+
+        The optional argument `arg` can be used to modify the generation and
+        is formatter dependent (it is standardized because it can be given on
+        the command line).
+
+        This method is called by the ``-S`` :doc:`command-line option `,
+        the `arg` is then given by the ``-a`` option.
+        """
+        return ''
+
+    def format(self, tokensource, outfile):
+        """
+        This method must format the tokens from the `tokensource` iterable and
+        write the formatted version to the file object `outfile`.
+
+        Formatter options can control how exactly the tokens are converted.
+        """
+        if self.encoding:
+            # wrap the outfile in a StreamWriter
+            outfile = codecs.lookup(self.encoding)[3](outfile)
+        return self.format_unencoded(tokensource, outfile)
+
+    # Allow writing Formatter[str] or Formatter[bytes]. That's equivalent to
+    # Formatter. This helps when using third-party type stubs from typeshed.
+    def __class_getitem__(cls, name):
+        return cls
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pygments/lexer.py b/TTS/Kokoro/.venv/Lib/site-packages/pygments/lexer.py
new file mode 100644
index 0000000000000000000000000000000000000000..453d675a3255874d8f94a4597effeb7dd9c5825f
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pygments/lexer.py
@@ -0,0 +1,961 @@
+"""
+    pygments.lexer
+    ~~~~~~~~~~~~~~
+
+    Base lexer classes.
+
+    :copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+import re
+import sys
+import time
+
+from pygments.filter import apply_filters, Filter
+from pygments.filters import get_filter_by_name
+from pygments.token import Error, Text, Other, Whitespace, _TokenType
+from pygments.util import get_bool_opt, get_int_opt, get_list_opt, \
+    make_analysator, Future, guess_decode
+from pygments.regexopt import regex_opt
+
+__all__ = ['Lexer', 'RegexLexer', 'ExtendedRegexLexer', 'DelegatingLexer',
+           'LexerContext', 'include', 'inherit', 'bygroups', 'using', 'this',
+           'default', 'words', 'line_re']
+
+line_re = re.compile('.*?\n')
+
+_encoding_map = [(b'\xef\xbb\xbf', 'utf-8'),
+                 (b'\xff\xfe\0\0', 'utf-32'),
+                 (b'\0\0\xfe\xff', 'utf-32be'),
+                 (b'\xff\xfe', 'utf-16'),
+                 (b'\xfe\xff', 'utf-16be')]
+
+_default_analyse = staticmethod(lambda x: 0.0)
+
+
+class LexerMeta(type):
+    """
+    This metaclass automagically converts ``analyse_text`` methods into
+    static methods which always return float values.
+    """
+
+    def __new__(mcs, name, bases, d):
+        if 'analyse_text' in d:
+            d['analyse_text'] = make_analysator(d['analyse_text'])
+        return type.__new__(mcs, name, bases, d)
+
+
+class Lexer(metaclass=LexerMeta):
+    """
+    Lexer for a specific language.
+
+    See also :doc:`lexerdevelopment`, a high-level guide to writing
+    lexers.
+
+    Lexer classes have attributes used for choosing the most appropriate
+    lexer based on various criteria.
+
+    .. autoattribute:: name
+       :no-value:
+    .. autoattribute:: aliases
+       :no-value:
+    .. autoattribute:: filenames
+       :no-value:
+    .. autoattribute:: alias_filenames
+    .. autoattribute:: mimetypes
+       :no-value:
+    .. autoattribute:: priority
+
+    Lexers included in Pygments should have two additional attributes:
+
+    .. autoattribute:: url
+       :no-value:
+    .. autoattribute:: version_added
+       :no-value:
+
+    Lexers included in Pygments may have additional attributes:
+
+    .. autoattribute:: _example
+       :no-value:
+
+    You can pass options to the constructor. The basic options recognized
+    by all lexers and processed by the base `Lexer` class are:
+
+    ``stripnl``
+        Strip leading and trailing newlines from the input (default: True).
+    ``stripall``
+        Strip all leading and trailing whitespace from the input
+        (default: False).
+    ``ensurenl``
+        Make sure that the input ends with a newline (default: True).  This
+        is required for some lexers that consume input linewise.
+
+        .. versionadded:: 1.3
+
+    ``tabsize``
+        If given and greater than 0, expand tabs in the input (default: 0).
+    ``encoding``
+        If given, must be an encoding name. This encoding will be used to
+        convert the input string to Unicode, if it is not already a Unicode
+        string (default: ``'guess'``, which uses a simple UTF-8 / Locale /
+        Latin1 detection.  Can also be ``'chardet'`` to use the chardet
+        library, if it is installed.
+    ``inencoding``
+        Overrides the ``encoding`` if given.
+    """
+
+    #: Full name of the lexer, in human-readable form
+    name = None
+
+    #: A list of short, unique identifiers that can be used to look
+    #: up the lexer from a list, e.g., using `get_lexer_by_name()`.
+    aliases = []
+
+    #: A list of `fnmatch` patterns that match filenames which contain
+    #: content for this lexer. The patterns in this list should be unique among
+    #: all lexers.
+    filenames = []
+
+    #: A list of `fnmatch` patterns that match filenames which may or may not
+    #: contain content for this lexer. This list is used by the
+    #: :func:`.guess_lexer_for_filename()` function, to determine which lexers
+    #: are then included in guessing the correct one. That means that
+    #: e.g. every lexer for HTML and a template language should include
+    #: ``\*.html`` in this list.
+    alias_filenames = []
+
+    #: A list of MIME types for content that can be lexed with this lexer.
+    mimetypes = []
+
+    #: Priority, should multiple lexers match and no content is provided
+    priority = 0
+
+    #: URL of the language specification/definition. Used in the Pygments
+    #: documentation. Set to an empty string to disable.
+    url = None
+
+    #: Version of Pygments in which the lexer was added.
+    version_added = None
+
+    #: Example file name. Relative to the ``tests/examplefiles`` directory.
+    #: This is used by the documentation generator to show an example.
+    _example = None
+
+    def __init__(self, **options):
+        """
+        This constructor takes arbitrary options as keyword arguments.
+        Every subclass must first process its own options and then call
+        the `Lexer` constructor, since it processes the basic
+        options like `stripnl`.
+
+        An example looks like this:
+
+        .. sourcecode:: python
+
+           def __init__(self, **options):
+               self.compress = options.get('compress', '')
+               Lexer.__init__(self, **options)
+
+        As these options must all be specifiable as strings (due to the
+        command line usage), there are various utility functions
+        available to help with that, see `Utilities`_.
+        """
+        self.options = options
+        self.stripnl = get_bool_opt(options, 'stripnl', True)
+        self.stripall = get_bool_opt(options, 'stripall', False)
+        self.ensurenl = get_bool_opt(options, 'ensurenl', True)
+        self.tabsize = get_int_opt(options, 'tabsize', 0)
+        self.encoding = options.get('encoding', 'guess')
+        self.encoding = options.get('inencoding') or self.encoding
+        self.filters = []
+        for filter_ in get_list_opt(options, 'filters', ()):
+            self.add_filter(filter_)
+
+    def __repr__(self):
+        if self.options:
+            return f''
+        else:
+            return f''
+
+    def add_filter(self, filter_, **options):
+        """
+        Add a new stream filter to this lexer.
+        """
+        if not isinstance(filter_, Filter):
+            filter_ = get_filter_by_name(filter_, **options)
+        self.filters.append(filter_)
+
+    def analyse_text(text):
+        """
+        A static method which is called for lexer guessing.
+
+        It should analyse the text and return a float in the range
+        from ``0.0`` to ``1.0``.  If it returns ``0.0``, the lexer
+        will not be selected as the most probable one, if it returns
+        ``1.0``, it will be selected immediately.  This is used by
+        `guess_lexer`.
+
+        The `LexerMeta` metaclass automatically wraps this function so
+        that it works like a static method (no ``self`` or ``cls``
+        parameter) and the return value is automatically converted to
+        `float`. If the return value is an object that is boolean `False`
+        it's the same as if the return values was ``0.0``.
+        """
+
+    def _preprocess_lexer_input(self, text):
+        """Apply preprocessing such as decoding the input, removing BOM and normalizing newlines."""
+
+        if not isinstance(text, str):
+            if self.encoding == 'guess':
+                text, _ = guess_decode(text)
+            elif self.encoding == 'chardet':
+                try:
+                    import chardet
+                except ImportError as e:
+                    raise ImportError('To enable chardet encoding guessing, '
+                                      'please install the chardet library '
+                                      'from http://chardet.feedparser.org/') from e
+                # check for BOM first
+                decoded = None
+                for bom, encoding in _encoding_map:
+                    if text.startswith(bom):
+                        decoded = text[len(bom):].decode(encoding, 'replace')
+                        break
+                # no BOM found, so use chardet
+                if decoded is None:
+                    enc = chardet.detect(text[:1024])  # Guess using first 1KB
+                    decoded = text.decode(enc.get('encoding') or 'utf-8',
+                                          'replace')
+                text = decoded
+            else:
+                text = text.decode(self.encoding)
+                if text.startswith('\ufeff'):
+                    text = text[len('\ufeff'):]
+        else:
+            if text.startswith('\ufeff'):
+                text = text[len('\ufeff'):]
+
+        # text now *is* a unicode string
+        text = text.replace('\r\n', '\n')
+        text = text.replace('\r', '\n')
+        if self.stripall:
+            text = text.strip()
+        elif self.stripnl:
+            text = text.strip('\n')
+        if self.tabsize > 0:
+            text = text.expandtabs(self.tabsize)
+        if self.ensurenl and not text.endswith('\n'):
+            text += '\n'
+
+        return text
+
+    def get_tokens(self, text, unfiltered=False):
+        """
+        This method is the basic interface of a lexer. It is called by
+        the `highlight()` function. It must process the text and return an
+        iterable of ``(tokentype, value)`` pairs from `text`.
+
+        Normally, you don't need to override this method. The default
+        implementation processes the options recognized by all lexers
+        (`stripnl`, `stripall` and so on), and then yields all tokens
+        from `get_tokens_unprocessed()`, with the ``index`` dropped.
+
+        If `unfiltered` is set to `True`, the filtering mechanism is
+        bypassed even if filters are defined.
+        """
+        text = self._preprocess_lexer_input(text)
+
+        def streamer():
+            for _, t, v in self.get_tokens_unprocessed(text):
+                yield t, v
+        stream = streamer()
+        if not unfiltered:
+            stream = apply_filters(stream, self.filters, self)
+        return stream
+
+    def get_tokens_unprocessed(self, text):
+        """
+        This method should process the text and return an iterable of
+        ``(index, tokentype, value)`` tuples where ``index`` is the starting
+        position of the token within the input text.
+
+        It must be overridden by subclasses. It is recommended to
+        implement it as a generator to maximize effectiveness.
+        """
+        raise NotImplementedError
+
+
+class DelegatingLexer(Lexer):
+    """
+    This lexer takes two lexer as arguments. A root lexer and
+    a language lexer. First everything is scanned using the language
+    lexer, afterwards all ``Other`` tokens are lexed using the root
+    lexer.
+
+    The lexers from the ``template`` lexer package use this base lexer.
+    """
+
+    def __init__(self, _root_lexer, _language_lexer, _needle=Other, **options):
+        self.root_lexer = _root_lexer(**options)
+        self.language_lexer = _language_lexer(**options)
+        self.needle = _needle
+        Lexer.__init__(self, **options)
+
+    def get_tokens_unprocessed(self, text):
+        buffered = ''
+        insertions = []
+        lng_buffer = []
+        for i, t, v in self.language_lexer.get_tokens_unprocessed(text):
+            if t is self.needle:
+                if lng_buffer:
+                    insertions.append((len(buffered), lng_buffer))
+                    lng_buffer = []
+                buffered += v
+            else:
+                lng_buffer.append((i, t, v))
+        if lng_buffer:
+            insertions.append((len(buffered), lng_buffer))
+        return do_insertions(insertions,
+                             self.root_lexer.get_tokens_unprocessed(buffered))
+
+
+# ------------------------------------------------------------------------------
+# RegexLexer and ExtendedRegexLexer
+#
+
+
+class include(str):  # pylint: disable=invalid-name
+    """
+    Indicates that a state should include rules from another state.
+    """
+    pass
+
+
+class _inherit:
+    """
+    Indicates the a state should inherit from its superclass.
+    """
+    def __repr__(self):
+        return 'inherit'
+
+inherit = _inherit()  # pylint: disable=invalid-name
+
+
+class combined(tuple):  # pylint: disable=invalid-name
+    """
+    Indicates a state combined from multiple states.
+    """
+
+    def __new__(cls, *args):
+        return tuple.__new__(cls, args)
+
+    def __init__(self, *args):
+        # tuple.__init__ doesn't do anything
+        pass
+
+
+class _PseudoMatch:
+    """
+    A pseudo match object constructed from a string.
+    """
+
+    def __init__(self, start, text):
+        self._text = text
+        self._start = start
+
+    def start(self, arg=None):
+        return self._start
+
+    def end(self, arg=None):
+        return self._start + len(self._text)
+
+    def group(self, arg=None):
+        if arg:
+            raise IndexError('No such group')
+        return self._text
+
+    def groups(self):
+        return (self._text,)
+
+    def groupdict(self):
+        return {}
+
+
+def bygroups(*args):
+    """
+    Callback that yields multiple actions for each group in the match.
+    """
+    def callback(lexer, match, ctx=None):
+        for i, action in enumerate(args):
+            if action is None:
+                continue
+            elif type(action) is _TokenType:
+                data = match.group(i + 1)
+                if data:
+                    yield match.start(i + 1), action, data
+            else:
+                data = match.group(i + 1)
+                if data is not None:
+                    if ctx:
+                        ctx.pos = match.start(i + 1)
+                    for item in action(lexer,
+                                       _PseudoMatch(match.start(i + 1), data), ctx):
+                        if item:
+                            yield item
+        if ctx:
+            ctx.pos = match.end()
+    return callback
+
+
+class _This:
+    """
+    Special singleton used for indicating the caller class.
+    Used by ``using``.
+    """
+
+this = _This()
+
+
+def using(_other, **kwargs):
+    """
+    Callback that processes the match with a different lexer.
+
+    The keyword arguments are forwarded to the lexer, except `state` which
+    is handled separately.
+
+    `state` specifies the state that the new lexer will start in, and can
+    be an enumerable such as ('root', 'inline', 'string') or a simple
+    string which is assumed to be on top of the root state.
+
+    Note: For that to work, `_other` must not be an `ExtendedRegexLexer`.
+    """
+    gt_kwargs = {}
+    if 'state' in kwargs:
+        s = kwargs.pop('state')
+        if isinstance(s, (list, tuple)):
+            gt_kwargs['stack'] = s
+        else:
+            gt_kwargs['stack'] = ('root', s)
+
+    if _other is this:
+        def callback(lexer, match, ctx=None):
+            # if keyword arguments are given the callback
+            # function has to create a new lexer instance
+            if kwargs:
+                # XXX: cache that somehow
+                kwargs.update(lexer.options)
+                lx = lexer.__class__(**kwargs)
+            else:
+                lx = lexer
+            s = match.start()
+            for i, t, v in lx.get_tokens_unprocessed(match.group(), **gt_kwargs):
+                yield i + s, t, v
+            if ctx:
+                ctx.pos = match.end()
+    else:
+        def callback(lexer, match, ctx=None):
+            # XXX: cache that somehow
+            kwargs.update(lexer.options)
+            lx = _other(**kwargs)
+
+            s = match.start()
+            for i, t, v in lx.get_tokens_unprocessed(match.group(), **gt_kwargs):
+                yield i + s, t, v
+            if ctx:
+                ctx.pos = match.end()
+    return callback
+
+
+class default:
+    """
+    Indicates a state or state action (e.g. #pop) to apply.
+    For example default('#pop') is equivalent to ('', Token, '#pop')
+    Note that state tuples may be used as well.
+
+    .. versionadded:: 2.0
+    """
+    def __init__(self, state):
+        self.state = state
+
+
+class words(Future):
+    """
+    Indicates a list of literal words that is transformed into an optimized
+    regex that matches any of the words.
+
+    .. versionadded:: 2.0
+    """
+    def __init__(self, words, prefix='', suffix=''):
+        self.words = words
+        self.prefix = prefix
+        self.suffix = suffix
+
+    def get(self):
+        return regex_opt(self.words, prefix=self.prefix, suffix=self.suffix)
+
+
+class RegexLexerMeta(LexerMeta):
+    """
+    Metaclass for RegexLexer, creates the self._tokens attribute from
+    self.tokens on the first instantiation.
+    """
+
+    def _process_regex(cls, regex, rflags, state):
+        """Preprocess the regular expression component of a token definition."""
+        if isinstance(regex, Future):
+            regex = regex.get()
+        return re.compile(regex, rflags).match
+
+    def _process_token(cls, token):
+        """Preprocess the token component of a token definition."""
+        assert type(token) is _TokenType or callable(token), \
+            f'token type must be simple type or callable, not {token!r}'
+        return token
+
+    def _process_new_state(cls, new_state, unprocessed, processed):
+        """Preprocess the state transition action of a token definition."""
+        if isinstance(new_state, str):
+            # an existing state
+            if new_state == '#pop':
+                return -1
+            elif new_state in unprocessed:
+                return (new_state,)
+            elif new_state == '#push':
+                return new_state
+            elif new_state[:5] == '#pop:':
+                return -int(new_state[5:])
+            else:
+                assert False, f'unknown new state {new_state!r}'
+        elif isinstance(new_state, combined):
+            # combine a new state from existing ones
+            tmp_state = '_tmp_%d' % cls._tmpname
+            cls._tmpname += 1
+            itokens = []
+            for istate in new_state:
+                assert istate != new_state, f'circular state ref {istate!r}'
+                itokens.extend(cls._process_state(unprocessed,
+                                                  processed, istate))
+            processed[tmp_state] = itokens
+            return (tmp_state,)
+        elif isinstance(new_state, tuple):
+            # push more than one state
+            for istate in new_state:
+                assert (istate in unprocessed or
+                        istate in ('#pop', '#push')), \
+                    'unknown new state ' + istate
+            return new_state
+        else:
+            assert False, f'unknown new state def {new_state!r}'
+
+    def _process_state(cls, unprocessed, processed, state):
+        """Preprocess a single state definition."""
+        assert isinstance(state, str), f"wrong state name {state!r}"
+        assert state[0] != '#', f"invalid state name {state!r}"
+        if state in processed:
+            return processed[state]
+        tokens = processed[state] = []
+        rflags = cls.flags
+        for tdef in unprocessed[state]:
+            if isinstance(tdef, include):
+                # it's a state reference
+                assert tdef != state, f"circular state reference {state!r}"
+                tokens.extend(cls._process_state(unprocessed, processed,
+                                                 str(tdef)))
+                continue
+            if isinstance(tdef, _inherit):
+                # should be processed already, but may not in the case of:
+                # 1. the state has no counterpart in any parent
+                # 2. the state includes more than one 'inherit'
+                continue
+            if isinstance(tdef, default):
+                new_state = cls._process_new_state(tdef.state, unprocessed, processed)
+                tokens.append((re.compile('').match, None, new_state))
+                continue
+
+            assert type(tdef) is tuple, f"wrong rule def {tdef!r}"
+
+            try:
+                rex = cls._process_regex(tdef[0], rflags, state)
+            except Exception as err:
+                raise ValueError(f"uncompilable regex {tdef[0]!r} in state {state!r} of {cls!r}: {err}") from err
+
+            token = cls._process_token(tdef[1])
+
+            if len(tdef) == 2:
+                new_state = None
+            else:
+                new_state = cls._process_new_state(tdef[2],
+                                                   unprocessed, processed)
+
+            tokens.append((rex, token, new_state))
+        return tokens
+
+    def process_tokendef(cls, name, tokendefs=None):
+        """Preprocess a dictionary of token definitions."""
+        processed = cls._all_tokens[name] = {}
+        tokendefs = tokendefs or cls.tokens[name]
+        for state in list(tokendefs):
+            cls._process_state(tokendefs, processed, state)
+        return processed
+
+    def get_tokendefs(cls):
+        """
+        Merge tokens from superclasses in MRO order, returning a single tokendef
+        dictionary.
+
+        Any state that is not defined by a subclass will be inherited
+        automatically.  States that *are* defined by subclasses will, by
+        default, override that state in the superclass.  If a subclass wishes to
+        inherit definitions from a superclass, it can use the special value
+        "inherit", which will cause the superclass' state definition to be
+        included at that point in the state.
+        """
+        tokens = {}
+        inheritable = {}
+        for c in cls.__mro__:
+            toks = c.__dict__.get('tokens', {})
+
+            for state, items in toks.items():
+                curitems = tokens.get(state)
+                if curitems is None:
+                    # N.b. because this is assigned by reference, sufficiently
+                    # deep hierarchies are processed incrementally (e.g. for
+                    # A(B), B(C), C(RegexLexer), B will be premodified so X(B)
+                    # will not see any inherits in B).
+                    tokens[state] = items
+                    try:
+                        inherit_ndx = items.index(inherit)
+                    except ValueError:
+                        continue
+                    inheritable[state] = inherit_ndx
+                    continue
+
+                inherit_ndx = inheritable.pop(state, None)
+                if inherit_ndx is None:
+                    continue
+
+                # Replace the "inherit" value with the items
+                curitems[inherit_ndx:inherit_ndx+1] = items
+                try:
+                    # N.b. this is the index in items (that is, the superclass
+                    # copy), so offset required when storing below.
+                    new_inh_ndx = items.index(inherit)
+                except ValueError:
+                    pass
+                else:
+                    inheritable[state] = inherit_ndx + new_inh_ndx
+
+        return tokens
+
+    def __call__(cls, *args, **kwds):
+        """Instantiate cls after preprocessing its token definitions."""
+        if '_tokens' not in cls.__dict__:
+            cls._all_tokens = {}
+            cls._tmpname = 0
+            if hasattr(cls, 'token_variants') and cls.token_variants:
+                # don't process yet
+                pass
+            else:
+                cls._tokens = cls.process_tokendef('', cls.get_tokendefs())
+
+        return type.__call__(cls, *args, **kwds)
+
+
+class RegexLexer(Lexer, metaclass=RegexLexerMeta):
+    """
+    Base for simple stateful regular expression-based lexers.
+    Simplifies the lexing process so that you need only
+    provide a list of states and regular expressions.
+    """
+
+    #: Flags for compiling the regular expressions.
+    #: Defaults to MULTILINE.
+    flags = re.MULTILINE
+
+    #: At all time there is a stack of states. Initially, the stack contains
+    #: a single state 'root'. The top of the stack is called "the current state".
+    #:
+    #: Dict of ``{'state': [(regex, tokentype, new_state), ...], ...}``
+    #:
+    #: ``new_state`` can be omitted to signify no state transition.
+    #: If ``new_state`` is a string, it is pushed on the stack. This ensure
+    #: the new current state is ``new_state``.
+    #: If ``new_state`` is a tuple of strings, all of those strings are pushed
+    #: on the stack and the current state will be the last element of the list.
+    #: ``new_state`` can also be ``combined('state1', 'state2', ...)``
+    #: to signify a new, anonymous state combined from the rules of two
+    #: or more existing ones.
+    #: Furthermore, it can be '#pop' to signify going back one step in
+    #: the state stack, or '#push' to push the current state on the stack
+    #: again. Note that if you push while in a combined state, the combined
+    #: state itself is pushed, and not only the state in which the rule is
+    #: defined.
+    #:
+    #: The tuple can also be replaced with ``include('state')``, in which
+    #: case the rules from the state named by the string are included in the
+    #: current one.
+    tokens = {}
+
+    def get_tokens_unprocessed(self, text, stack=('root',)):
+        """
+        Split ``text`` into (tokentype, text) pairs.
+
+        ``stack`` is the initial stack (default: ``['root']``)
+        """
+        pos = 0
+        tokendefs = self._tokens
+        statestack = list(stack)
+        statetokens = tokendefs[statestack[-1]]
+        while 1:
+            for rexmatch, action, new_state in statetokens:
+                m = rexmatch(text, pos)
+                if m:
+                    if action is not None:
+                        if type(action) is _TokenType:
+                            yield pos, action, m.group()
+                        else:
+                            yield from action(self, m)
+                    pos = m.end()
+                    if new_state is not None:
+                        # state transition
+                        if isinstance(new_state, tuple):
+                            for state in new_state:
+                                if state == '#pop':
+                                    if len(statestack) > 1:
+                                        statestack.pop()
+                                elif state == '#push':
+                                    statestack.append(statestack[-1])
+                                else:
+                                    statestack.append(state)
+                        elif isinstance(new_state, int):
+                            # pop, but keep at least one state on the stack
+                            # (random code leading to unexpected pops should
+                            # not allow exceptions)
+                            if abs(new_state) >= len(statestack):
+                                del statestack[1:]
+                            else:
+                                del statestack[new_state:]
+                        elif new_state == '#push':
+                            statestack.append(statestack[-1])
+                        else:
+                            assert False, f"wrong state def: {new_state!r}"
+                        statetokens = tokendefs[statestack[-1]]
+                    break
+            else:
+                # We are here only if all state tokens have been considered
+                # and there was not a match on any of them.
+                try:
+                    if text[pos] == '\n':
+                        # at EOL, reset state to "root"
+                        statestack = ['root']
+                        statetokens = tokendefs['root']
+                        yield pos, Whitespace, '\n'
+                        pos += 1
+                        continue
+                    yield pos, Error, text[pos]
+                    pos += 1
+                except IndexError:
+                    break
+
+
+class LexerContext:
+    """
+    A helper object that holds lexer position data.
+    """
+
+    def __init__(self, text, pos, stack=None, end=None):
+        self.text = text
+        self.pos = pos
+        self.end = end or len(text)  # end=0 not supported ;-)
+        self.stack = stack or ['root']
+
+    def __repr__(self):
+        return f'LexerContext({self.text!r}, {self.pos!r}, {self.stack!r})'
+
+
+class ExtendedRegexLexer(RegexLexer):
+    """
+    A RegexLexer that uses a context object to store its state.
+    """
+
+    def get_tokens_unprocessed(self, text=None, context=None):
+        """
+        Split ``text`` into (tokentype, text) pairs.
+        If ``context`` is given, use this lexer context instead.
+        """
+        tokendefs = self._tokens
+        if not context:
+            ctx = LexerContext(text, 0)
+            statetokens = tokendefs['root']
+        else:
+            ctx = context
+            statetokens = tokendefs[ctx.stack[-1]]
+            text = ctx.text
+        while 1:
+            for rexmatch, action, new_state in statetokens:
+                m = rexmatch(text, ctx.pos, ctx.end)
+                if m:
+                    if action is not None:
+                        if type(action) is _TokenType:
+                            yield ctx.pos, action, m.group()
+                            ctx.pos = m.end()
+                        else:
+                            yield from action(self, m, ctx)
+                            if not new_state:
+                                # altered the state stack?
+                                statetokens = tokendefs[ctx.stack[-1]]
+                    # CAUTION: callback must set ctx.pos!
+                    if new_state is not None:
+                        # state transition
+                        if isinstance(new_state, tuple):
+                            for state in new_state:
+                                if state == '#pop':
+                                    if len(ctx.stack) > 1:
+                                        ctx.stack.pop()
+                                elif state == '#push':
+                                    ctx.stack.append(ctx.stack[-1])
+                                else:
+                                    ctx.stack.append(state)
+                        elif isinstance(new_state, int):
+                            # see RegexLexer for why this check is made
+                            if abs(new_state) >= len(ctx.stack):
+                                del ctx.stack[1:]
+                            else:
+                                del ctx.stack[new_state:]
+                        elif new_state == '#push':
+                            ctx.stack.append(ctx.stack[-1])
+                        else:
+                            assert False, f"wrong state def: {new_state!r}"
+                        statetokens = tokendefs[ctx.stack[-1]]
+                    break
+            else:
+                try:
+                    if ctx.pos >= ctx.end:
+                        break
+                    if text[ctx.pos] == '\n':
+                        # at EOL, reset state to "root"
+                        ctx.stack = ['root']
+                        statetokens = tokendefs['root']
+                        yield ctx.pos, Text, '\n'
+                        ctx.pos += 1
+                        continue
+                    yield ctx.pos, Error, text[ctx.pos]
+                    ctx.pos += 1
+                except IndexError:
+                    break
+
+
+def do_insertions(insertions, tokens):
+    """
+    Helper for lexers which must combine the results of several
+    sublexers.
+
+    ``insertions`` is a list of ``(index, itokens)`` pairs.
+    Each ``itokens`` iterable should be inserted at position
+    ``index`` into the token stream given by the ``tokens``
+    argument.
+
+    The result is a combined token stream.
+
+    TODO: clean up the code here.
+    """
+    insertions = iter(insertions)
+    try:
+        index, itokens = next(insertions)
+    except StopIteration:
+        # no insertions
+        yield from tokens
+        return
+
+    realpos = None
+    insleft = True
+
+    # iterate over the token stream where we want to insert
+    # the tokens from the insertion list.
+    for i, t, v in tokens:
+        # first iteration. store the position of first item
+        if realpos is None:
+            realpos = i
+        oldi = 0
+        while insleft and i + len(v) >= index:
+            tmpval = v[oldi:index - i]
+            if tmpval:
+                yield realpos, t, tmpval
+                realpos += len(tmpval)
+            for it_index, it_token, it_value in itokens:
+                yield realpos, it_token, it_value
+                realpos += len(it_value)
+            oldi = index - i
+            try:
+                index, itokens = next(insertions)
+            except StopIteration:
+                insleft = False
+                break  # not strictly necessary
+        if oldi < len(v):
+            yield realpos, t, v[oldi:]
+            realpos += len(v) - oldi
+
+    # leftover tokens
+    while insleft:
+        # no normal tokens, set realpos to zero
+        realpos = realpos or 0
+        for p, t, v in itokens:
+            yield realpos, t, v
+            realpos += len(v)
+        try:
+            index, itokens = next(insertions)
+        except StopIteration:
+            insleft = False
+            break  # not strictly necessary
+
+
+class ProfilingRegexLexerMeta(RegexLexerMeta):
+    """Metaclass for ProfilingRegexLexer, collects regex timing info."""
+
+    def _process_regex(cls, regex, rflags, state):
+        if isinstance(regex, words):
+            rex = regex_opt(regex.words, prefix=regex.prefix,
+                            suffix=regex.suffix)
+        else:
+            rex = regex
+        compiled = re.compile(rex, rflags)
+
+        def match_func(text, pos, endpos=sys.maxsize):
+            info = cls._prof_data[-1].setdefault((state, rex), [0, 0.0])
+            t0 = time.time()
+            res = compiled.match(text, pos, endpos)
+            t1 = time.time()
+            info[0] += 1
+            info[1] += t1 - t0
+            return res
+        return match_func
+
+
+class ProfilingRegexLexer(RegexLexer, metaclass=ProfilingRegexLexerMeta):
+    """Drop-in replacement for RegexLexer that does profiling of its regexes."""
+
+    _prof_data = []
+    _prof_sort_index = 4  # defaults to time per call
+
+    def get_tokens_unprocessed(self, text, stack=('root',)):
+        # this needs to be a stack, since using(this) will produce nested calls
+        self.__class__._prof_data.append({})
+        yield from RegexLexer.get_tokens_unprocessed(self, text, stack)
+        rawdata = self.__class__._prof_data.pop()
+        data = sorted(((s, repr(r).strip('u\'').replace('\\\\', '\\')[:65],
+                        n, 1000 * t, 1000 * t / n)
+                       for ((s, r), (n, t)) in rawdata.items()),
+                      key=lambda x: x[self._prof_sort_index],
+                      reverse=True)
+        sum_total = sum(x[3] for x in data)
+
+        print()
+        print('Profiling result for %s lexing %d chars in %.3f ms' %
+              (self.__class__.__name__, len(text), sum_total))
+        print('=' * 110)
+        print('%-20s %-64s ncalls  tottime  percall' % ('state', 'regex'))
+        print('-' * 110)
+        for d in data:
+            print('%-20s %-65s %5d %8.4f %8.4f' % d)
+        print('=' * 110)
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pygments/modeline.py b/TTS/Kokoro/.venv/Lib/site-packages/pygments/modeline.py
new file mode 100644
index 0000000000000000000000000000000000000000..c310f0edbdc0e8ad3be4e69e1270809ff3cf32f2
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pygments/modeline.py
@@ -0,0 +1,43 @@
+"""
+    pygments.modeline
+    ~~~~~~~~~~~~~~~~~
+
+    A simple modeline parser (based on pymodeline).
+
+    :copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+import re
+
+__all__ = ['get_filetype_from_buffer']
+
+
+modeline_re = re.compile(r'''
+    (?: vi | vim | ex ) (?: [<=>]? \d* )? :
+    .* (?: ft | filetype | syn | syntax ) = ( [^:\s]+ )
+''', re.VERBOSE)
+
+
+def get_filetype_from_line(l): # noqa: E741
+    m = modeline_re.search(l)
+    if m:
+        return m.group(1)
+
+
+def get_filetype_from_buffer(buf, max_lines=5):
+    """
+    Scan the buffer for modelines and return filetype if one is found.
+    """
+    lines = buf.splitlines()
+    for line in lines[-1:-max_lines-1:-1]:
+        ret = get_filetype_from_line(line)
+        if ret:
+            return ret
+    for i in range(max_lines, -1, -1):
+        if i < len(lines):
+            ret = get_filetype_from_line(lines[i])
+            if ret:
+                return ret
+
+    return None
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pygments/plugin.py b/TTS/Kokoro/.venv/Lib/site-packages/pygments/plugin.py
new file mode 100644
index 0000000000000000000000000000000000000000..498db42384966abfb748d66c3577559fab3b5ba8
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pygments/plugin.py
@@ -0,0 +1,72 @@
+"""
+    pygments.plugin
+    ~~~~~~~~~~~~~~~
+
+    Pygments plugin interface.
+
+    lexer plugins::
+
+        [pygments.lexers]
+        yourlexer = yourmodule:YourLexer
+
+    formatter plugins::
+
+        [pygments.formatters]
+        yourformatter = yourformatter:YourFormatter
+        /.ext = yourformatter:YourFormatter
+
+    As you can see, you can define extensions for the formatter
+    with a leading slash.
+
+    syntax plugins::
+
+        [pygments.styles]
+        yourstyle = yourstyle:YourStyle
+
+    filter plugin::
+
+        [pygments.filter]
+        yourfilter = yourfilter:YourFilter
+
+
+    :copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+from importlib.metadata import entry_points
+
+LEXER_ENTRY_POINT = 'pygments.lexers'
+FORMATTER_ENTRY_POINT = 'pygments.formatters'
+STYLE_ENTRY_POINT = 'pygments.styles'
+FILTER_ENTRY_POINT = 'pygments.filters'
+
+
+def iter_entry_points(group_name):
+    groups = entry_points()
+    if hasattr(groups, 'select'):
+        # New interface in Python 3.10 and newer versions of the
+        # importlib_metadata backport.
+        return groups.select(group=group_name)
+    else:
+        # Older interface, deprecated in Python 3.10 and recent
+        # importlib_metadata, but we need it in Python 3.8 and 3.9.
+        return groups.get(group_name, [])
+
+
+def find_plugin_lexers():
+    for entrypoint in iter_entry_points(LEXER_ENTRY_POINT):
+        yield entrypoint.load()
+
+
+def find_plugin_formatters():
+    for entrypoint in iter_entry_points(FORMATTER_ENTRY_POINT):
+        yield entrypoint.name, entrypoint.load()
+
+
+def find_plugin_styles():
+    for entrypoint in iter_entry_points(STYLE_ENTRY_POINT):
+        yield entrypoint.name, entrypoint.load()
+
+
+def find_plugin_filters():
+    for entrypoint in iter_entry_points(FILTER_ENTRY_POINT):
+        yield entrypoint.name, entrypoint.load()
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pygments/regexopt.py b/TTS/Kokoro/.venv/Lib/site-packages/pygments/regexopt.py
new file mode 100644
index 0000000000000000000000000000000000000000..cc8d2c31b541e43826cc223544d15bab72aaf98d
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pygments/regexopt.py
@@ -0,0 +1,91 @@
+"""
+    pygments.regexopt
+    ~~~~~~~~~~~~~~~~~
+
+    An algorithm that generates optimized regexes for matching long lists of
+    literal strings.
+
+    :copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+import re
+from re import escape
+from os.path import commonprefix
+from itertools import groupby
+from operator import itemgetter
+
+CS_ESCAPE = re.compile(r'[\[\^\\\-\]]')
+FIRST_ELEMENT = itemgetter(0)
+
+
+def make_charset(letters):
+    return '[' + CS_ESCAPE.sub(lambda m: '\\' + m.group(), ''.join(letters)) + ']'
+
+
+def regex_opt_inner(strings, open_paren):
+    """Return a regex that matches any string in the sorted list of strings."""
+    close_paren = open_paren and ')' or ''
+    # print strings, repr(open_paren)
+    if not strings:
+        # print '-> nothing left'
+        return ''
+    first = strings[0]
+    if len(strings) == 1:
+        # print '-> only 1 string'
+        return open_paren + escape(first) + close_paren
+    if not first:
+        # print '-> first string empty'
+        return open_paren + regex_opt_inner(strings[1:], '(?:') \
+            + '?' + close_paren
+    if len(first) == 1:
+        # multiple one-char strings? make a charset
+        oneletter = []
+        rest = []
+        for s in strings:
+            if len(s) == 1:
+                oneletter.append(s)
+            else:
+                rest.append(s)
+        if len(oneletter) > 1:  # do we have more than one oneletter string?
+            if rest:
+                # print '-> 1-character + rest'
+                return open_paren + regex_opt_inner(rest, '') + '|' \
+                    + make_charset(oneletter) + close_paren
+            # print '-> only 1-character'
+            return open_paren + make_charset(oneletter) + close_paren
+    prefix = commonprefix(strings)
+    if prefix:
+        plen = len(prefix)
+        # we have a prefix for all strings
+        # print '-> prefix:', prefix
+        return open_paren + escape(prefix) \
+            + regex_opt_inner([s[plen:] for s in strings], '(?:') \
+            + close_paren
+    # is there a suffix?
+    strings_rev = [s[::-1] for s in strings]
+    suffix = commonprefix(strings_rev)
+    if suffix:
+        slen = len(suffix)
+        # print '-> suffix:', suffix[::-1]
+        return open_paren \
+            + regex_opt_inner(sorted(s[:-slen] for s in strings), '(?:') \
+            + escape(suffix[::-1]) + close_paren
+    # recurse on common 1-string prefixes
+    # print '-> last resort'
+    return open_paren + \
+        '|'.join(regex_opt_inner(list(group[1]), '')
+                 for group in groupby(strings, lambda s: s[0] == first[0])) \
+        + close_paren
+
+
+def regex_opt(strings, prefix='', suffix=''):
+    """Return a compiled regex that matches any string in the given list.
+
+    The strings to match must be literal strings, not regexes.  They will be
+    regex-escaped.
+
+    *prefix* and *suffix* are pre- and appended to the final regex.
+    """
+    strings = sorted(strings)
+    return prefix + regex_opt_inner(strings, '(') + suffix
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pygments/scanner.py b/TTS/Kokoro/.venv/Lib/site-packages/pygments/scanner.py
new file mode 100644
index 0000000000000000000000000000000000000000..3c8c8487316a71c1ed75c078cf4d7c77176c6995
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pygments/scanner.py
@@ -0,0 +1,104 @@
+"""
+    pygments.scanner
+    ~~~~~~~~~~~~~~~~
+
+    This library implements a regex based scanner. Some languages
+    like Pascal are easy to parse but have some keywords that
+    depend on the context. Because of this it's impossible to lex
+    that just by using a regular expression lexer like the
+    `RegexLexer`.
+
+    Have a look at the `DelphiLexer` to get an idea of how to use
+    this scanner.
+
+    :copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+import re
+
+
+class EndOfText(RuntimeError):
+    """
+    Raise if end of text is reached and the user
+    tried to call a match function.
+    """
+
+
+class Scanner:
+    """
+    Simple scanner
+
+    All method patterns are regular expression strings (not
+    compiled expressions!)
+    """
+
+    def __init__(self, text, flags=0):
+        """
+        :param text:    The text which should be scanned
+        :param flags:   default regular expression flags
+        """
+        self.data = text
+        self.data_length = len(text)
+        self.start_pos = 0
+        self.pos = 0
+        self.flags = flags
+        self.last = None
+        self.match = None
+        self._re_cache = {}
+
+    def eos(self):
+        """`True` if the scanner reached the end of text."""
+        return self.pos >= self.data_length
+    eos = property(eos, eos.__doc__)
+
+    def check(self, pattern):
+        """
+        Apply `pattern` on the current position and return
+        the match object. (Doesn't touch pos). Use this for
+        lookahead.
+        """
+        if self.eos:
+            raise EndOfText()
+        if pattern not in self._re_cache:
+            self._re_cache[pattern] = re.compile(pattern, self.flags)
+        return self._re_cache[pattern].match(self.data, self.pos)
+
+    def test(self, pattern):
+        """Apply a pattern on the current position and check
+        if it patches. Doesn't touch pos.
+        """
+        return self.check(pattern) is not None
+
+    def scan(self, pattern):
+        """
+        Scan the text for the given pattern and update pos/match
+        and related fields. The return value is a boolean that
+        indicates if the pattern matched. The matched value is
+        stored on the instance as ``match``, the last value is
+        stored as ``last``. ``start_pos`` is the position of the
+        pointer before the pattern was matched, ``pos`` is the
+        end position.
+        """
+        if self.eos:
+            raise EndOfText()
+        if pattern not in self._re_cache:
+            self._re_cache[pattern] = re.compile(pattern, self.flags)
+        self.last = self.match
+        m = self._re_cache[pattern].match(self.data, self.pos)
+        if m is None:
+            return False
+        self.start_pos = m.start()
+        self.pos = m.end()
+        self.match = m.group()
+        return True
+
+    def get_char(self):
+        """Scan exactly one char."""
+        self.scan('.')
+
+    def __repr__(self):
+        return '<%s %d/%d>' % (
+            self.__class__.__name__,
+            self.pos,
+            self.data_length
+        )
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pygments/sphinxext.py b/TTS/Kokoro/.venv/Lib/site-packages/pygments/sphinxext.py
new file mode 100644
index 0000000000000000000000000000000000000000..c215399ba5b852f06af4a0f93439a494a073dec5
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pygments/sphinxext.py
@@ -0,0 +1,247 @@
+"""
+    pygments.sphinxext
+    ~~~~~~~~~~~~~~~~~~
+
+    Sphinx extension to generate automatic documentation of lexers,
+    formatters and filters.
+
+    :copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+import sys
+
+from docutils import nodes
+from docutils.statemachine import ViewList
+from docutils.parsers.rst import Directive
+from sphinx.util.nodes import nested_parse_with_titles
+
+
+MODULEDOC = '''
+.. module:: %s
+
+%s
+%s
+'''
+
+LEXERDOC = '''
+.. class:: %s
+
+    :Short names: %s
+    :Filenames:   %s
+    :MIME types:  %s
+
+    %s
+
+    %s
+
+'''
+
+FMTERDOC = '''
+.. class:: %s
+
+    :Short names: %s
+    :Filenames: %s
+
+    %s
+
+'''
+
+FILTERDOC = '''
+.. class:: %s
+
+    :Name: %s
+
+    %s
+
+'''
+
+
+class PygmentsDoc(Directive):
+    """
+    A directive to collect all lexers/formatters/filters and generate
+    autoclass directives for them.
+    """
+    has_content = False
+    required_arguments = 1
+    optional_arguments = 0
+    final_argument_whitespace = False
+    option_spec = {}
+
+    def run(self):
+        self.filenames = set()
+        if self.arguments[0] == 'lexers':
+            out = self.document_lexers()
+        elif self.arguments[0] == 'formatters':
+            out = self.document_formatters()
+        elif self.arguments[0] == 'filters':
+            out = self.document_filters()
+        elif self.arguments[0] == 'lexers_overview':
+            out = self.document_lexers_overview()
+        else:
+            raise Exception('invalid argument for "pygmentsdoc" directive')
+        node = nodes.compound()
+        vl = ViewList(out.split('\n'), source='')
+        nested_parse_with_titles(self.state, vl, node)
+        for fn in self.filenames:
+            self.state.document.settings.record_dependencies.add(fn)
+        return node.children
+
+    def document_lexers_overview(self):
+        """Generate a tabular overview of all lexers.
+
+        The columns are the lexer name, the extensions handled by this lexer
+        (or "None"), the aliases and a link to the lexer class."""
+        from pygments.lexers._mapping import LEXERS
+        import pygments.lexers
+        out = []
+
+        table = []
+
+        def format_link(name, url):
+            if url:
+                return f'`{name} <{url}>`_'
+            return name
+
+        for classname, data in sorted(LEXERS.items(), key=lambda x: x[1][1].lower()):
+            lexer_cls = pygments.lexers.find_lexer_class(data[1])
+            extensions = lexer_cls.filenames + lexer_cls.alias_filenames
+
+            table.append({
+                'name': format_link(data[1], lexer_cls.url),
+                'extensions': ', '.join(extensions).replace('*', '\\*').replace('_', '\\') or 'None',
+                'aliases': ', '.join(data[2]),
+                'class': f'{data[0]}.{classname}'
+            })
+
+        column_names = ['name', 'extensions', 'aliases', 'class']
+        column_lengths = [max([len(row[column]) for row in table if row[column]])
+                          for column in column_names]
+
+        def write_row(*columns):
+            """Format a table row"""
+            out = []
+            for length, col in zip(column_lengths, columns):
+                if col:
+                    out.append(col.ljust(length))
+                else:
+                    out.append(' '*length)
+
+            return ' '.join(out)
+
+        def write_seperator():
+            """Write a table separator row"""
+            sep = ['='*c for c in column_lengths]
+            return write_row(*sep)
+
+        out.append(write_seperator())
+        out.append(write_row('Name', 'Extension(s)', 'Short name(s)', 'Lexer class'))
+        out.append(write_seperator())
+        for row in table:
+            out.append(write_row(
+                row['name'],
+                row['extensions'],
+                row['aliases'],
+                f':class:`~{row["class"]}`'))
+        out.append(write_seperator())
+
+        return '\n'.join(out)
+
+    def document_lexers(self):
+        from pygments.lexers._mapping import LEXERS
+        import pygments
+        import inspect
+        import pathlib
+
+        out = []
+        modules = {}
+        moduledocstrings = {}
+        for classname, data in sorted(LEXERS.items(), key=lambda x: x[0]):
+            module = data[0]
+            mod = __import__(module, None, None, [classname])
+            self.filenames.add(mod.__file__)
+            cls = getattr(mod, classname)
+            if not cls.__doc__:
+                print(f"Warning: {classname} does not have a docstring.")
+            docstring = cls.__doc__
+            if isinstance(docstring, bytes):
+                docstring = docstring.decode('utf8')
+
+            example_file = getattr(cls, '_example', None)
+            if example_file:
+                p = pathlib.Path(inspect.getabsfile(pygments)).parent.parent /\
+                    'tests' / 'examplefiles' / example_file
+                content = p.read_text(encoding='utf-8')
+                if not content:
+                    raise Exception(
+                        f"Empty example file '{example_file}' for lexer "
+                        f"{classname}")
+
+                if data[2]:
+                    lexer_name = data[2][0]
+                    docstring += '\n\n    .. admonition:: Example\n'
+                    docstring += f'\n      .. code-block:: {lexer_name}\n\n'
+                    for line in content.splitlines():
+                        docstring += f'          {line}\n'
+
+            if cls.version_added:
+                version_line = f'.. versionadded:: {cls.version_added}'
+            else:
+                version_line = ''
+
+            modules.setdefault(module, []).append((
+                classname,
+                ', '.join(data[2]) or 'None',
+                ', '.join(data[3]).replace('*', '\\*').replace('_', '\\') or 'None',
+                ', '.join(data[4]) or 'None',
+                docstring,
+                version_line))
+            if module not in moduledocstrings:
+                moddoc = mod.__doc__
+                if isinstance(moddoc, bytes):
+                    moddoc = moddoc.decode('utf8')
+                moduledocstrings[module] = moddoc
+
+        for module, lexers in sorted(modules.items(), key=lambda x: x[0]):
+            if moduledocstrings[module] is None:
+                raise Exception(f"Missing docstring for {module}")
+            heading = moduledocstrings[module].splitlines()[4].strip().rstrip('.')
+            out.append(MODULEDOC % (module, heading, '-'*len(heading)))
+            for data in lexers:
+                out.append(LEXERDOC % data)
+
+        return ''.join(out)
+
+    def document_formatters(self):
+        from pygments.formatters import FORMATTERS
+
+        out = []
+        for classname, data in sorted(FORMATTERS.items(), key=lambda x: x[0]):
+            module = data[0]
+            mod = __import__(module, None, None, [classname])
+            self.filenames.add(mod.__file__)
+            cls = getattr(mod, classname)
+            docstring = cls.__doc__
+            if isinstance(docstring, bytes):
+                docstring = docstring.decode('utf8')
+            heading = cls.__name__
+            out.append(FMTERDOC % (heading, ', '.join(data[2]) or 'None',
+                                   ', '.join(data[3]).replace('*', '\\*') or 'None',
+                                   docstring))
+        return ''.join(out)
+
+    def document_filters(self):
+        from pygments.filters import FILTERS
+
+        out = []
+        for name, cls in FILTERS.items():
+            self.filenames.add(sys.modules[cls.__module__].__file__)
+            docstring = cls.__doc__
+            if isinstance(docstring, bytes):
+                docstring = docstring.decode('utf8')
+            out.append(FILTERDOC % (cls.__name__, name, docstring))
+        return ''.join(out)
+
+
+def setup(app):
+    app.add_directive('pygmentsdoc', PygmentsDoc)
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pygments/style.py b/TTS/Kokoro/.venv/Lib/site-packages/pygments/style.py
new file mode 100644
index 0000000000000000000000000000000000000000..ac36cad7b3f7e15d2e04fa2263baf045a6c7519b
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pygments/style.py
@@ -0,0 +1,203 @@
+"""
+    pygments.style
+    ~~~~~~~~~~~~~~
+
+    Basic style object.
+
+    :copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+from pygments.token import Token, STANDARD_TYPES
+
+# Default mapping of ansixxx to RGB colors.
+_ansimap = {
+    # dark
+    'ansiblack': '000000',
+    'ansired': '7f0000',
+    'ansigreen': '007f00',
+    'ansiyellow': '7f7fe0',
+    'ansiblue': '00007f',
+    'ansimagenta': '7f007f',
+    'ansicyan': '007f7f',
+    'ansigray': 'e5e5e5',
+    # normal
+    'ansibrightblack': '555555',
+    'ansibrightred': 'ff0000',
+    'ansibrightgreen': '00ff00',
+    'ansibrightyellow': 'ffff00',
+    'ansibrightblue': '0000ff',
+    'ansibrightmagenta': 'ff00ff',
+    'ansibrightcyan': '00ffff',
+    'ansiwhite': 'ffffff',
+}
+# mapping of deprecated #ansixxx colors to new color names
+_deprecated_ansicolors = {
+    # dark
+    '#ansiblack': 'ansiblack',
+    '#ansidarkred': 'ansired',
+    '#ansidarkgreen': 'ansigreen',
+    '#ansibrown': 'ansiyellow',
+    '#ansidarkblue': 'ansiblue',
+    '#ansipurple': 'ansimagenta',
+    '#ansiteal': 'ansicyan',
+    '#ansilightgray': 'ansigray',
+    # normal
+    '#ansidarkgray': 'ansibrightblack',
+    '#ansired': 'ansibrightred',
+    '#ansigreen': 'ansibrightgreen',
+    '#ansiyellow': 'ansibrightyellow',
+    '#ansiblue': 'ansibrightblue',
+    '#ansifuchsia': 'ansibrightmagenta',
+    '#ansiturquoise': 'ansibrightcyan',
+    '#ansiwhite': 'ansiwhite',
+}
+ansicolors = set(_ansimap)
+
+
+class StyleMeta(type):
+
+    def __new__(mcs, name, bases, dct):
+        obj = type.__new__(mcs, name, bases, dct)
+        for token in STANDARD_TYPES:
+            if token not in obj.styles:
+                obj.styles[token] = ''
+
+        def colorformat(text):
+            if text in ansicolors:
+                return text
+            if text[0:1] == '#':
+                col = text[1:]
+                if len(col) == 6:
+                    return col
+                elif len(col) == 3:
+                    return col[0] * 2 + col[1] * 2 + col[2] * 2
+            elif text == '':
+                return ''
+            elif text.startswith('var') or text.startswith('calc'):
+                return text
+            assert False, f"wrong color format {text!r}"
+
+        _styles = obj._styles = {}
+
+        for ttype in obj.styles:
+            for token in ttype.split():
+                if token in _styles:
+                    continue
+                ndef = _styles.get(token.parent, None)
+                styledefs = obj.styles.get(token, '').split()
+                if not ndef or token is None:
+                    ndef = ['', 0, 0, 0, '', '', 0, 0, 0]
+                elif 'noinherit' in styledefs and token is not Token:
+                    ndef = _styles[Token][:]
+                else:
+                    ndef = ndef[:]
+                _styles[token] = ndef
+                for styledef in obj.styles.get(token, '').split():
+                    if styledef == 'noinherit':
+                        pass
+                    elif styledef == 'bold':
+                        ndef[1] = 1
+                    elif styledef == 'nobold':
+                        ndef[1] = 0
+                    elif styledef == 'italic':
+                        ndef[2] = 1
+                    elif styledef == 'noitalic':
+                        ndef[2] = 0
+                    elif styledef == 'underline':
+                        ndef[3] = 1
+                    elif styledef == 'nounderline':
+                        ndef[3] = 0
+                    elif styledef[:3] == 'bg:':
+                        ndef[4] = colorformat(styledef[3:])
+                    elif styledef[:7] == 'border:':
+                        ndef[5] = colorformat(styledef[7:])
+                    elif styledef == 'roman':
+                        ndef[6] = 1
+                    elif styledef == 'sans':
+                        ndef[7] = 1
+                    elif styledef == 'mono':
+                        ndef[8] = 1
+                    else:
+                        ndef[0] = colorformat(styledef)
+
+        return obj
+
+    def style_for_token(cls, token):
+        t = cls._styles[token]
+        ansicolor = bgansicolor = None
+        color = t[0]
+        if color in _deprecated_ansicolors:
+            color = _deprecated_ansicolors[color]
+        if color in ansicolors:
+            ansicolor = color
+            color = _ansimap[color]
+        bgcolor = t[4]
+        if bgcolor in _deprecated_ansicolors:
+            bgcolor = _deprecated_ansicolors[bgcolor]
+        if bgcolor in ansicolors:
+            bgansicolor = bgcolor
+            bgcolor = _ansimap[bgcolor]
+
+        return {
+            'color':        color or None,
+            'bold':         bool(t[1]),
+            'italic':       bool(t[2]),
+            'underline':    bool(t[3]),
+            'bgcolor':      bgcolor or None,
+            'border':       t[5] or None,
+            'roman':        bool(t[6]) or None,
+            'sans':         bool(t[7]) or None,
+            'mono':         bool(t[8]) or None,
+            'ansicolor':    ansicolor,
+            'bgansicolor':  bgansicolor,
+        }
+
+    def list_styles(cls):
+        return list(cls)
+
+    def styles_token(cls, ttype):
+        return ttype in cls._styles
+
+    def __iter__(cls):
+        for token in cls._styles:
+            yield token, cls.style_for_token(token)
+
+    def __len__(cls):
+        return len(cls._styles)
+
+
+class Style(metaclass=StyleMeta):
+
+    #: overall background color (``None`` means transparent)
+    background_color = '#ffffff'
+
+    #: highlight background color
+    highlight_color = '#ffffcc'
+
+    #: line number font color
+    line_number_color = 'inherit'
+
+    #: line number background color
+    line_number_background_color = 'transparent'
+
+    #: special line number font color
+    line_number_special_color = '#000000'
+
+    #: special line number background color
+    line_number_special_background_color = '#ffffc0'
+
+    #: Style definitions for individual token types.
+    styles = {}
+
+    #: user-friendly style name (used when selecting the style, so this
+    # should be all-lowercase, no spaces, hyphens)
+    name = 'unnamed'
+
+    aliases = []
+
+    # Attribute for lexers defined within Pygments. If set
+    # to True, the style is not shown in the style gallery
+    # on the website. This is intended for language-specific
+    # styles.
+    web_style_gallery_exclude = False
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pygments/token.py b/TTS/Kokoro/.venv/Lib/site-packages/pygments/token.py
new file mode 100644
index 0000000000000000000000000000000000000000..2f3b97e09ac22cefbcea5d3a568b897c9f789c02
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pygments/token.py
@@ -0,0 +1,214 @@
+"""
+    pygments.token
+    ~~~~~~~~~~~~~~
+
+    Basic token types and the standard tokens.
+
+    :copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+
+class _TokenType(tuple):
+    parent = None
+
+    def split(self):
+        buf = []
+        node = self
+        while node is not None:
+            buf.append(node)
+            node = node.parent
+        buf.reverse()
+        return buf
+
+    def __init__(self, *args):
+        # no need to call super.__init__
+        self.subtypes = set()
+
+    def __contains__(self, val):
+        return self is val or (
+            type(val) is self.__class__ and
+            val[:len(self)] == self
+        )
+
+    def __getattr__(self, val):
+        if not val or not val[0].isupper():
+            return tuple.__getattribute__(self, val)
+        new = _TokenType(self + (val,))
+        setattr(self, val, new)
+        self.subtypes.add(new)
+        new.parent = self
+        return new
+
+    def __repr__(self):
+        return 'Token' + (self and '.' or '') + '.'.join(self)
+
+    def __copy__(self):
+        # These instances are supposed to be singletons
+        return self
+
+    def __deepcopy__(self, memo):
+        # These instances are supposed to be singletons
+        return self
+
+
+Token = _TokenType()
+
+# Special token types
+Text = Token.Text
+Whitespace = Text.Whitespace
+Escape = Token.Escape
+Error = Token.Error
+# Text that doesn't belong to this lexer (e.g. HTML in PHP)
+Other = Token.Other
+
+# Common token types for source code
+Keyword = Token.Keyword
+Name = Token.Name
+Literal = Token.Literal
+String = Literal.String
+Number = Literal.Number
+Punctuation = Token.Punctuation
+Operator = Token.Operator
+Comment = Token.Comment
+
+# Generic types for non-source code
+Generic = Token.Generic
+
+# String and some others are not direct children of Token.
+# alias them:
+Token.Token = Token
+Token.String = String
+Token.Number = Number
+
+
+def is_token_subtype(ttype, other):
+    """
+    Return True if ``ttype`` is a subtype of ``other``.
+
+    exists for backwards compatibility. use ``ttype in other`` now.
+    """
+    return ttype in other
+
+
+def string_to_tokentype(s):
+    """
+    Convert a string into a token type::
+
+        >>> string_to_token('String.Double')
+        Token.Literal.String.Double
+        >>> string_to_token('Token.Literal.Number')
+        Token.Literal.Number
+        >>> string_to_token('')
+        Token
+
+    Tokens that are already tokens are returned unchanged:
+
+        >>> string_to_token(String)
+        Token.Literal.String
+    """
+    if isinstance(s, _TokenType):
+        return s
+    if not s:
+        return Token
+    node = Token
+    for item in s.split('.'):
+        node = getattr(node, item)
+    return node
+
+
+# Map standard token types to short names, used in CSS class naming.
+# If you add a new item, please be sure to run this file to perform
+# a consistency check for duplicate values.
+STANDARD_TYPES = {
+    Token:                         '',
+
+    Text:                          '',
+    Whitespace:                    'w',
+    Escape:                        'esc',
+    Error:                         'err',
+    Other:                         'x',
+
+    Keyword:                       'k',
+    Keyword.Constant:              'kc',
+    Keyword.Declaration:           'kd',
+    Keyword.Namespace:             'kn',
+    Keyword.Pseudo:                'kp',
+    Keyword.Reserved:              'kr',
+    Keyword.Type:                  'kt',
+
+    Name:                          'n',
+    Name.Attribute:                'na',
+    Name.Builtin:                  'nb',
+    Name.Builtin.Pseudo:           'bp',
+    Name.Class:                    'nc',
+    Name.Constant:                 'no',
+    Name.Decorator:                'nd',
+    Name.Entity:                   'ni',
+    Name.Exception:                'ne',
+    Name.Function:                 'nf',
+    Name.Function.Magic:           'fm',
+    Name.Property:                 'py',
+    Name.Label:                    'nl',
+    Name.Namespace:                'nn',
+    Name.Other:                    'nx',
+    Name.Tag:                      'nt',
+    Name.Variable:                 'nv',
+    Name.Variable.Class:           'vc',
+    Name.Variable.Global:          'vg',
+    Name.Variable.Instance:        'vi',
+    Name.Variable.Magic:           'vm',
+
+    Literal:                       'l',
+    Literal.Date:                  'ld',
+
+    String:                        's',
+    String.Affix:                  'sa',
+    String.Backtick:               'sb',
+    String.Char:                   'sc',
+    String.Delimiter:              'dl',
+    String.Doc:                    'sd',
+    String.Double:                 's2',
+    String.Escape:                 'se',
+    String.Heredoc:                'sh',
+    String.Interpol:               'si',
+    String.Other:                  'sx',
+    String.Regex:                  'sr',
+    String.Single:                 's1',
+    String.Symbol:                 'ss',
+
+    Number:                        'm',
+    Number.Bin:                    'mb',
+    Number.Float:                  'mf',
+    Number.Hex:                    'mh',
+    Number.Integer:                'mi',
+    Number.Integer.Long:           'il',
+    Number.Oct:                    'mo',
+
+    Operator:                      'o',
+    Operator.Word:                 'ow',
+
+    Punctuation:                   'p',
+    Punctuation.Marker:            'pm',
+
+    Comment:                       'c',
+    Comment.Hashbang:              'ch',
+    Comment.Multiline:             'cm',
+    Comment.Preproc:               'cp',
+    Comment.PreprocFile:           'cpf',
+    Comment.Single:                'c1',
+    Comment.Special:               'cs',
+
+    Generic:                       'g',
+    Generic.Deleted:               'gd',
+    Generic.Emph:                  'ge',
+    Generic.Error:                 'gr',
+    Generic.Heading:               'gh',
+    Generic.Inserted:              'gi',
+    Generic.Output:                'go',
+    Generic.Prompt:                'gp',
+    Generic.Strong:                'gs',
+    Generic.Subheading:            'gu',
+    Generic.EmphStrong:            'ges',
+    Generic.Traceback:             'gt',
+}
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pygments/unistring.py b/TTS/Kokoro/.venv/Lib/site-packages/pygments/unistring.py
new file mode 100644
index 0000000000000000000000000000000000000000..e3bd2e72738158bc62eff6a64209b00d0f0ff17f
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pygments/unistring.py
@@ -0,0 +1,153 @@
+"""
+    pygments.unistring
+    ~~~~~~~~~~~~~~~~~~
+
+    Strings of all Unicode characters of a certain category.
+    Used for matching in Unicode-aware languages. Run to regenerate.
+
+    Inspired by chartypes_create.py from the MoinMoin project.
+
+    :copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+Cc = '\x00-\x1f\x7f-\x9f'
+
+Cf = '\xad\u0600-\u0605\u061c\u06dd\u070f\u08e2\u180e\u200b-\u200f\u202a-\u202e\u2060-\u2064\u2066-\u206f\ufeff\ufff9-\ufffb\U000110bd\U000110cd\U0001bca0-\U0001bca3\U0001d173-\U0001d17a\U000e0001\U000e0020-\U000e007f'
+
+Cn = '\u0378-\u0379\u0380-\u0383\u038b\u038d\u03a2\u0530\u0557-\u0558\u058b-\u058c\u0590\u05c8-\u05cf\u05eb-\u05ee\u05f5-\u05ff\u061d\u070e\u074b-\u074c\u07b2-\u07bf\u07fb-\u07fc\u082e-\u082f\u083f\u085c-\u085d\u085f\u086b-\u089f\u08b5\u08be-\u08d2\u0984\u098d-\u098e\u0991-\u0992\u09a9\u09b1\u09b3-\u09b5\u09ba-\u09bb\u09c5-\u09c6\u09c9-\u09ca\u09cf-\u09d6\u09d8-\u09db\u09de\u09e4-\u09e5\u09ff-\u0a00\u0a04\u0a0b-\u0a0e\u0a11-\u0a12\u0a29\u0a31\u0a34\u0a37\u0a3a-\u0a3b\u0a3d\u0a43-\u0a46\u0a49-\u0a4a\u0a4e-\u0a50\u0a52-\u0a58\u0a5d\u0a5f-\u0a65\u0a77-\u0a80\u0a84\u0a8e\u0a92\u0aa9\u0ab1\u0ab4\u0aba-\u0abb\u0ac6\u0aca\u0ace-\u0acf\u0ad1-\u0adf\u0ae4-\u0ae5\u0af2-\u0af8\u0b00\u0b04\u0b0d-\u0b0e\u0b11-\u0b12\u0b29\u0b31\u0b34\u0b3a-\u0b3b\u0b45-\u0b46\u0b49-\u0b4a\u0b4e-\u0b55\u0b58-\u0b5b\u0b5e\u0b64-\u0b65\u0b78-\u0b81\u0b84\u0b8b-\u0b8d\u0b91\u0b96-\u0b98\u0b9b\u0b9d\u0ba0-\u0ba2\u0ba5-\u0ba7\u0bab-\u0bad\u0bba-\u0bbd\u0bc3-\u0bc5\u0bc9\u0bce-\u0bcf\u0bd1-\u0bd6\u0bd8-\u0be5\u0bfb-\u0bff\u0c0d\u0c11\u0c29\u0c3a-\u0c3c\u0c45\u0c49\u0c4e-\u0c54\u0c57\u0c5b-\u0c5f\u0c64-\u0c65\u0c70-\u0c77\u0c8d\u0c91\u0ca9\u0cb4\u0cba-\u0cbb\u0cc5\u0cc9\u0cce-\u0cd4\u0cd7-\u0cdd\u0cdf\u0ce4-\u0ce5\u0cf0\u0cf3-\u0cff\u0d04\u0d0d\u0d11\u0d45\u0d49\u0d50-\u0d53\u0d64-\u0d65\u0d80-\u0d81\u0d84\u0d97-\u0d99\u0db2\u0dbc\u0dbe-\u0dbf\u0dc7-\u0dc9\u0dcb-\u0dce\u0dd5\u0dd7\u0de0-\u0de5\u0df0-\u0df1\u0df5-\u0e00\u0e3b-\u0e3e\u0e5c-\u0e80\u0e83\u0e85-\u0e86\u0e89\u0e8b-\u0e8c\u0e8e-\u0e93\u0e98\u0ea0\u0ea4\u0ea6\u0ea8-\u0ea9\u0eac\u0eba\u0ebe-\u0ebf\u0ec5\u0ec7\u0ece-\u0ecf\u0eda-\u0edb\u0ee0-\u0eff\u0f48\u0f6d-\u0f70\u0f98\u0fbd\u0fcd\u0fdb-\u0fff\u10c6\u10c8-\u10cc\u10ce-\u10cf\u1249\u124e-\u124f\u1257\u1259\u125e-\u125f\u1289\u128e-\u128f\u12b1\u12b6-\u12b7\u12bf\u12c1\u12c6-\u12c7\u12d7\u1311\u1316-\u1317\u135b-\u135c\u137d-\u137f\u139a-\u139f\u13f6-\u13f7\u13fe-\u13ff\u169d-\u169f\u16f9-\u16ff\u170d\u1715-\u171f\u1737-\u173f\u1754-\u175f\u176d\u1771\u1774-\u177f\u17de-\u17df\u17ea-\u17ef\u17fa-\u17ff\u180f\u181a-\u181f\u1879-\u187f\u18ab-\u18af\u18f6-\u18ff\u191f\u192c-\u192f\u193c-\u193f\u1941-\u1943\u196e-\u196f\u1975-\u197f\u19ac-\u19af\u19ca-\u19cf\u19db-\u19dd\u1a1c-\u1a1d\u1a5f\u1a7d-\u1a7e\u1a8a-\u1a8f\u1a9a-\u1a9f\u1aae-\u1aaf\u1abf-\u1aff\u1b4c-\u1b4f\u1b7d-\u1b7f\u1bf4-\u1bfb\u1c38-\u1c3a\u1c4a-\u1c4c\u1c89-\u1c8f\u1cbb-\u1cbc\u1cc8-\u1ccf\u1cfa-\u1cff\u1dfa\u1f16-\u1f17\u1f1e-\u1f1f\u1f46-\u1f47\u1f4e-\u1f4f\u1f58\u1f5a\u1f5c\u1f5e\u1f7e-\u1f7f\u1fb5\u1fc5\u1fd4-\u1fd5\u1fdc\u1ff0-\u1ff1\u1ff5\u1fff\u2065\u2072-\u2073\u208f\u209d-\u209f\u20c0-\u20cf\u20f1-\u20ff\u218c-\u218f\u2427-\u243f\u244b-\u245f\u2b74-\u2b75\u2b96-\u2b97\u2bc9\u2bff\u2c2f\u2c5f\u2cf4-\u2cf8\u2d26\u2d28-\u2d2c\u2d2e-\u2d2f\u2d68-\u2d6e\u2d71-\u2d7e\u2d97-\u2d9f\u2da7\u2daf\u2db7\u2dbf\u2dc7\u2dcf\u2dd7\u2ddf\u2e4f-\u2e7f\u2e9a\u2ef4-\u2eff\u2fd6-\u2fef\u2ffc-\u2fff\u3040\u3097-\u3098\u3100-\u3104\u3130\u318f\u31bb-\u31bf\u31e4-\u31ef\u321f\u32ff\u4db6-\u4dbf\u9ff0-\u9fff\ua48d-\ua48f\ua4c7-\ua4cf\ua62c-\ua63f\ua6f8-\ua6ff\ua7ba-\ua7f6\ua82c-\ua82f\ua83a-\ua83f\ua878-\ua87f\ua8c6-\ua8cd\ua8da-\ua8df\ua954-\ua95e\ua97d-\ua97f\ua9ce\ua9da-\ua9dd\ua9ff\uaa37-\uaa3f\uaa4e-\uaa4f\uaa5a-\uaa5b\uaac3-\uaada\uaaf7-\uab00\uab07-\uab08\uab0f-\uab10\uab17-\uab1f\uab27\uab2f\uab66-\uab6f\uabee-\uabef\uabfa-\uabff\ud7a4-\ud7af\ud7c7-\ud7ca\ud7fc-\ud7ff\ufa6e-\ufa6f\ufada-\ufaff\ufb07-\ufb12\ufb18-\ufb1c\ufb37\ufb3d\ufb3f\ufb42\ufb45\ufbc2-\ufbd2\ufd40-\ufd4f\ufd90-\ufd91\ufdc8-\ufdef\ufdfe-\ufdff\ufe1a-\ufe1f\ufe53\ufe67\ufe6c-\ufe6f\ufe75\ufefd-\ufefe\uff00\uffbf-\uffc1\uffc8-\uffc9\uffd0-\uffd1\uffd8-\uffd9\uffdd-\uffdf\uffe7\uffef-\ufff8\ufffe-\uffff\U0001000c\U00010027\U0001003b\U0001003e\U0001004e-\U0001004f\U0001005e-\U0001007f\U000100fb-\U000100ff\U00010103-\U00010106\U00010134-\U00010136\U0001018f\U0001019c-\U0001019f\U000101a1-\U000101cf\U000101fe-\U0001027f\U0001029d-\U0001029f\U000102d1-\U000102df\U000102fc-\U000102ff\U00010324-\U0001032c\U0001034b-\U0001034f\U0001037b-\U0001037f\U0001039e\U000103c4-\U000103c7\U000103d6-\U000103ff\U0001049e-\U0001049f\U000104aa-\U000104af\U000104d4-\U000104d7\U000104fc-\U000104ff\U00010528-\U0001052f\U00010564-\U0001056e\U00010570-\U000105ff\U00010737-\U0001073f\U00010756-\U0001075f\U00010768-\U000107ff\U00010806-\U00010807\U00010809\U00010836\U00010839-\U0001083b\U0001083d-\U0001083e\U00010856\U0001089f-\U000108a6\U000108b0-\U000108df\U000108f3\U000108f6-\U000108fa\U0001091c-\U0001091e\U0001093a-\U0001093e\U00010940-\U0001097f\U000109b8-\U000109bb\U000109d0-\U000109d1\U00010a04\U00010a07-\U00010a0b\U00010a14\U00010a18\U00010a36-\U00010a37\U00010a3b-\U00010a3e\U00010a49-\U00010a4f\U00010a59-\U00010a5f\U00010aa0-\U00010abf\U00010ae7-\U00010aea\U00010af7-\U00010aff\U00010b36-\U00010b38\U00010b56-\U00010b57\U00010b73-\U00010b77\U00010b92-\U00010b98\U00010b9d-\U00010ba8\U00010bb0-\U00010bff\U00010c49-\U00010c7f\U00010cb3-\U00010cbf\U00010cf3-\U00010cf9\U00010d28-\U00010d2f\U00010d3a-\U00010e5f\U00010e7f-\U00010eff\U00010f28-\U00010f2f\U00010f5a-\U00010fff\U0001104e-\U00011051\U00011070-\U0001107e\U000110c2-\U000110cc\U000110ce-\U000110cf\U000110e9-\U000110ef\U000110fa-\U000110ff\U00011135\U00011147-\U0001114f\U00011177-\U0001117f\U000111ce-\U000111cf\U000111e0\U000111f5-\U000111ff\U00011212\U0001123f-\U0001127f\U00011287\U00011289\U0001128e\U0001129e\U000112aa-\U000112af\U000112eb-\U000112ef\U000112fa-\U000112ff\U00011304\U0001130d-\U0001130e\U00011311-\U00011312\U00011329\U00011331\U00011334\U0001133a\U00011345-\U00011346\U00011349-\U0001134a\U0001134e-\U0001134f\U00011351-\U00011356\U00011358-\U0001135c\U00011364-\U00011365\U0001136d-\U0001136f\U00011375-\U000113ff\U0001145a\U0001145c\U0001145f-\U0001147f\U000114c8-\U000114cf\U000114da-\U0001157f\U000115b6-\U000115b7\U000115de-\U000115ff\U00011645-\U0001164f\U0001165a-\U0001165f\U0001166d-\U0001167f\U000116b8-\U000116bf\U000116ca-\U000116ff\U0001171b-\U0001171c\U0001172c-\U0001172f\U00011740-\U000117ff\U0001183c-\U0001189f\U000118f3-\U000118fe\U00011900-\U000119ff\U00011a48-\U00011a4f\U00011a84-\U00011a85\U00011aa3-\U00011abf\U00011af9-\U00011bff\U00011c09\U00011c37\U00011c46-\U00011c4f\U00011c6d-\U00011c6f\U00011c90-\U00011c91\U00011ca8\U00011cb7-\U00011cff\U00011d07\U00011d0a\U00011d37-\U00011d39\U00011d3b\U00011d3e\U00011d48-\U00011d4f\U00011d5a-\U00011d5f\U00011d66\U00011d69\U00011d8f\U00011d92\U00011d99-\U00011d9f\U00011daa-\U00011edf\U00011ef9-\U00011fff\U0001239a-\U000123ff\U0001246f\U00012475-\U0001247f\U00012544-\U00012fff\U0001342f-\U000143ff\U00014647-\U000167ff\U00016a39-\U00016a3f\U00016a5f\U00016a6a-\U00016a6d\U00016a70-\U00016acf\U00016aee-\U00016aef\U00016af6-\U00016aff\U00016b46-\U00016b4f\U00016b5a\U00016b62\U00016b78-\U00016b7c\U00016b90-\U00016e3f\U00016e9b-\U00016eff\U00016f45-\U00016f4f\U00016f7f-\U00016f8e\U00016fa0-\U00016fdf\U00016fe2-\U00016fff\U000187f2-\U000187ff\U00018af3-\U0001afff\U0001b11f-\U0001b16f\U0001b2fc-\U0001bbff\U0001bc6b-\U0001bc6f\U0001bc7d-\U0001bc7f\U0001bc89-\U0001bc8f\U0001bc9a-\U0001bc9b\U0001bca4-\U0001cfff\U0001d0f6-\U0001d0ff\U0001d127-\U0001d128\U0001d1e9-\U0001d1ff\U0001d246-\U0001d2df\U0001d2f4-\U0001d2ff\U0001d357-\U0001d35f\U0001d379-\U0001d3ff\U0001d455\U0001d49d\U0001d4a0-\U0001d4a1\U0001d4a3-\U0001d4a4\U0001d4a7-\U0001d4a8\U0001d4ad\U0001d4ba\U0001d4bc\U0001d4c4\U0001d506\U0001d50b-\U0001d50c\U0001d515\U0001d51d\U0001d53a\U0001d53f\U0001d545\U0001d547-\U0001d549\U0001d551\U0001d6a6-\U0001d6a7\U0001d7cc-\U0001d7cd\U0001da8c-\U0001da9a\U0001daa0\U0001dab0-\U0001dfff\U0001e007\U0001e019-\U0001e01a\U0001e022\U0001e025\U0001e02b-\U0001e7ff\U0001e8c5-\U0001e8c6\U0001e8d7-\U0001e8ff\U0001e94b-\U0001e94f\U0001e95a-\U0001e95d\U0001e960-\U0001ec70\U0001ecb5-\U0001edff\U0001ee04\U0001ee20\U0001ee23\U0001ee25-\U0001ee26\U0001ee28\U0001ee33\U0001ee38\U0001ee3a\U0001ee3c-\U0001ee41\U0001ee43-\U0001ee46\U0001ee48\U0001ee4a\U0001ee4c\U0001ee50\U0001ee53\U0001ee55-\U0001ee56\U0001ee58\U0001ee5a\U0001ee5c\U0001ee5e\U0001ee60\U0001ee63\U0001ee65-\U0001ee66\U0001ee6b\U0001ee73\U0001ee78\U0001ee7d\U0001ee7f\U0001ee8a\U0001ee9c-\U0001eea0\U0001eea4\U0001eeaa\U0001eebc-\U0001eeef\U0001eef2-\U0001efff\U0001f02c-\U0001f02f\U0001f094-\U0001f09f\U0001f0af-\U0001f0b0\U0001f0c0\U0001f0d0\U0001f0f6-\U0001f0ff\U0001f10d-\U0001f10f\U0001f16c-\U0001f16f\U0001f1ad-\U0001f1e5\U0001f203-\U0001f20f\U0001f23c-\U0001f23f\U0001f249-\U0001f24f\U0001f252-\U0001f25f\U0001f266-\U0001f2ff\U0001f6d5-\U0001f6df\U0001f6ed-\U0001f6ef\U0001f6fa-\U0001f6ff\U0001f774-\U0001f77f\U0001f7d9-\U0001f7ff\U0001f80c-\U0001f80f\U0001f848-\U0001f84f\U0001f85a-\U0001f85f\U0001f888-\U0001f88f\U0001f8ae-\U0001f8ff\U0001f90c-\U0001f90f\U0001f93f\U0001f971-\U0001f972\U0001f977-\U0001f979\U0001f97b\U0001f9a3-\U0001f9af\U0001f9ba-\U0001f9bf\U0001f9c3-\U0001f9cf\U0001fa00-\U0001fa5f\U0001fa6e-\U0001ffff\U0002a6d7-\U0002a6ff\U0002b735-\U0002b73f\U0002b81e-\U0002b81f\U0002cea2-\U0002ceaf\U0002ebe1-\U0002f7ff\U0002fa1e-\U000e0000\U000e0002-\U000e001f\U000e0080-\U000e00ff\U000e01f0-\U000effff\U000ffffe-\U000fffff\U0010fffe-\U0010ffff'
+
+Co = '\ue000-\uf8ff\U000f0000-\U000ffffd\U00100000-\U0010fffd'
+
+Cs = '\ud800-\udbff\\\udc00\udc01-\udfff'
+
+Ll = 'a-z\xb5\xdf-\xf6\xf8-\xff\u0101\u0103\u0105\u0107\u0109\u010b\u010d\u010f\u0111\u0113\u0115\u0117\u0119\u011b\u011d\u011f\u0121\u0123\u0125\u0127\u0129\u012b\u012d\u012f\u0131\u0133\u0135\u0137-\u0138\u013a\u013c\u013e\u0140\u0142\u0144\u0146\u0148-\u0149\u014b\u014d\u014f\u0151\u0153\u0155\u0157\u0159\u015b\u015d\u015f\u0161\u0163\u0165\u0167\u0169\u016b\u016d\u016f\u0171\u0173\u0175\u0177\u017a\u017c\u017e-\u0180\u0183\u0185\u0188\u018c-\u018d\u0192\u0195\u0199-\u019b\u019e\u01a1\u01a3\u01a5\u01a8\u01aa-\u01ab\u01ad\u01b0\u01b4\u01b6\u01b9-\u01ba\u01bd-\u01bf\u01c6\u01c9\u01cc\u01ce\u01d0\u01d2\u01d4\u01d6\u01d8\u01da\u01dc-\u01dd\u01df\u01e1\u01e3\u01e5\u01e7\u01e9\u01eb\u01ed\u01ef-\u01f0\u01f3\u01f5\u01f9\u01fb\u01fd\u01ff\u0201\u0203\u0205\u0207\u0209\u020b\u020d\u020f\u0211\u0213\u0215\u0217\u0219\u021b\u021d\u021f\u0221\u0223\u0225\u0227\u0229\u022b\u022d\u022f\u0231\u0233-\u0239\u023c\u023f-\u0240\u0242\u0247\u0249\u024b\u024d\u024f-\u0293\u0295-\u02af\u0371\u0373\u0377\u037b-\u037d\u0390\u03ac-\u03ce\u03d0-\u03d1\u03d5-\u03d7\u03d9\u03db\u03dd\u03df\u03e1\u03e3\u03e5\u03e7\u03e9\u03eb\u03ed\u03ef-\u03f3\u03f5\u03f8\u03fb-\u03fc\u0430-\u045f\u0461\u0463\u0465\u0467\u0469\u046b\u046d\u046f\u0471\u0473\u0475\u0477\u0479\u047b\u047d\u047f\u0481\u048b\u048d\u048f\u0491\u0493\u0495\u0497\u0499\u049b\u049d\u049f\u04a1\u04a3\u04a5\u04a7\u04a9\u04ab\u04ad\u04af\u04b1\u04b3\u04b5\u04b7\u04b9\u04bb\u04bd\u04bf\u04c2\u04c4\u04c6\u04c8\u04ca\u04cc\u04ce-\u04cf\u04d1\u04d3\u04d5\u04d7\u04d9\u04db\u04dd\u04df\u04e1\u04e3\u04e5\u04e7\u04e9\u04eb\u04ed\u04ef\u04f1\u04f3\u04f5\u04f7\u04f9\u04fb\u04fd\u04ff\u0501\u0503\u0505\u0507\u0509\u050b\u050d\u050f\u0511\u0513\u0515\u0517\u0519\u051b\u051d\u051f\u0521\u0523\u0525\u0527\u0529\u052b\u052d\u052f\u0560-\u0588\u10d0-\u10fa\u10fd-\u10ff\u13f8-\u13fd\u1c80-\u1c88\u1d00-\u1d2b\u1d6b-\u1d77\u1d79-\u1d9a\u1e01\u1e03\u1e05\u1e07\u1e09\u1e0b\u1e0d\u1e0f\u1e11\u1e13\u1e15\u1e17\u1e19\u1e1b\u1e1d\u1e1f\u1e21\u1e23\u1e25\u1e27\u1e29\u1e2b\u1e2d\u1e2f\u1e31\u1e33\u1e35\u1e37\u1e39\u1e3b\u1e3d\u1e3f\u1e41\u1e43\u1e45\u1e47\u1e49\u1e4b\u1e4d\u1e4f\u1e51\u1e53\u1e55\u1e57\u1e59\u1e5b\u1e5d\u1e5f\u1e61\u1e63\u1e65\u1e67\u1e69\u1e6b\u1e6d\u1e6f\u1e71\u1e73\u1e75\u1e77\u1e79\u1e7b\u1e7d\u1e7f\u1e81\u1e83\u1e85\u1e87\u1e89\u1e8b\u1e8d\u1e8f\u1e91\u1e93\u1e95-\u1e9d\u1e9f\u1ea1\u1ea3\u1ea5\u1ea7\u1ea9\u1eab\u1ead\u1eaf\u1eb1\u1eb3\u1eb5\u1eb7\u1eb9\u1ebb\u1ebd\u1ebf\u1ec1\u1ec3\u1ec5\u1ec7\u1ec9\u1ecb\u1ecd\u1ecf\u1ed1\u1ed3\u1ed5\u1ed7\u1ed9\u1edb\u1edd\u1edf\u1ee1\u1ee3\u1ee5\u1ee7\u1ee9\u1eeb\u1eed\u1eef\u1ef1\u1ef3\u1ef5\u1ef7\u1ef9\u1efb\u1efd\u1eff-\u1f07\u1f10-\u1f15\u1f20-\u1f27\u1f30-\u1f37\u1f40-\u1f45\u1f50-\u1f57\u1f60-\u1f67\u1f70-\u1f7d\u1f80-\u1f87\u1f90-\u1f97\u1fa0-\u1fa7\u1fb0-\u1fb4\u1fb6-\u1fb7\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fc7\u1fd0-\u1fd3\u1fd6-\u1fd7\u1fe0-\u1fe7\u1ff2-\u1ff4\u1ff6-\u1ff7\u210a\u210e-\u210f\u2113\u212f\u2134\u2139\u213c-\u213d\u2146-\u2149\u214e\u2184\u2c30-\u2c5e\u2c61\u2c65-\u2c66\u2c68\u2c6a\u2c6c\u2c71\u2c73-\u2c74\u2c76-\u2c7b\u2c81\u2c83\u2c85\u2c87\u2c89\u2c8b\u2c8d\u2c8f\u2c91\u2c93\u2c95\u2c97\u2c99\u2c9b\u2c9d\u2c9f\u2ca1\u2ca3\u2ca5\u2ca7\u2ca9\u2cab\u2cad\u2caf\u2cb1\u2cb3\u2cb5\u2cb7\u2cb9\u2cbb\u2cbd\u2cbf\u2cc1\u2cc3\u2cc5\u2cc7\u2cc9\u2ccb\u2ccd\u2ccf\u2cd1\u2cd3\u2cd5\u2cd7\u2cd9\u2cdb\u2cdd\u2cdf\u2ce1\u2ce3-\u2ce4\u2cec\u2cee\u2cf3\u2d00-\u2d25\u2d27\u2d2d\ua641\ua643\ua645\ua647\ua649\ua64b\ua64d\ua64f\ua651\ua653\ua655\ua657\ua659\ua65b\ua65d\ua65f\ua661\ua663\ua665\ua667\ua669\ua66b\ua66d\ua681\ua683\ua685\ua687\ua689\ua68b\ua68d\ua68f\ua691\ua693\ua695\ua697\ua699\ua69b\ua723\ua725\ua727\ua729\ua72b\ua72d\ua72f-\ua731\ua733\ua735\ua737\ua739\ua73b\ua73d\ua73f\ua741\ua743\ua745\ua747\ua749\ua74b\ua74d\ua74f\ua751\ua753\ua755\ua757\ua759\ua75b\ua75d\ua75f\ua761\ua763\ua765\ua767\ua769\ua76b\ua76d\ua76f\ua771-\ua778\ua77a\ua77c\ua77f\ua781\ua783\ua785\ua787\ua78c\ua78e\ua791\ua793-\ua795\ua797\ua799\ua79b\ua79d\ua79f\ua7a1\ua7a3\ua7a5\ua7a7\ua7a9\ua7af\ua7b5\ua7b7\ua7b9\ua7fa\uab30-\uab5a\uab60-\uab65\uab70-\uabbf\ufb00-\ufb06\ufb13-\ufb17\uff41-\uff5a\U00010428-\U0001044f\U000104d8-\U000104fb\U00010cc0-\U00010cf2\U000118c0-\U000118df\U00016e60-\U00016e7f\U0001d41a-\U0001d433\U0001d44e-\U0001d454\U0001d456-\U0001d467\U0001d482-\U0001d49b\U0001d4b6-\U0001d4b9\U0001d4bb\U0001d4bd-\U0001d4c3\U0001d4c5-\U0001d4cf\U0001d4ea-\U0001d503\U0001d51e-\U0001d537\U0001d552-\U0001d56b\U0001d586-\U0001d59f\U0001d5ba-\U0001d5d3\U0001d5ee-\U0001d607\U0001d622-\U0001d63b\U0001d656-\U0001d66f\U0001d68a-\U0001d6a5\U0001d6c2-\U0001d6da\U0001d6dc-\U0001d6e1\U0001d6fc-\U0001d714\U0001d716-\U0001d71b\U0001d736-\U0001d74e\U0001d750-\U0001d755\U0001d770-\U0001d788\U0001d78a-\U0001d78f\U0001d7aa-\U0001d7c2\U0001d7c4-\U0001d7c9\U0001d7cb\U0001e922-\U0001e943'
+
+Lm = '\u02b0-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0374\u037a\u0559\u0640\u06e5-\u06e6\u07f4-\u07f5\u07fa\u081a\u0824\u0828\u0971\u0e46\u0ec6\u10fc\u17d7\u1843\u1aa7\u1c78-\u1c7d\u1d2c-\u1d6a\u1d78\u1d9b-\u1dbf\u2071\u207f\u2090-\u209c\u2c7c-\u2c7d\u2d6f\u2e2f\u3005\u3031-\u3035\u303b\u309d-\u309e\u30fc-\u30fe\ua015\ua4f8-\ua4fd\ua60c\ua67f\ua69c-\ua69d\ua717-\ua71f\ua770\ua788\ua7f8-\ua7f9\ua9cf\ua9e6\uaa70\uaadd\uaaf3-\uaaf4\uab5c-\uab5f\uff70\uff9e-\uff9f\U00016b40-\U00016b43\U00016f93-\U00016f9f\U00016fe0-\U00016fe1'
+
+Lo = '\xaa\xba\u01bb\u01c0-\u01c3\u0294\u05d0-\u05ea\u05ef-\u05f2\u0620-\u063f\u0641-\u064a\u066e-\u066f\u0671-\u06d3\u06d5\u06ee-\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u0800-\u0815\u0840-\u0858\u0860-\u086a\u08a0-\u08b4\u08b6-\u08bd\u0904-\u0939\u093d\u0950\u0958-\u0961\u0972-\u0980\u0985-\u098c\u098f-\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc-\u09dd\u09df-\u09e1\u09f0-\u09f1\u09fc\u0a05-\u0a0a\u0a0f-\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32-\u0a33\u0a35-\u0a36\u0a38-\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2-\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0-\u0ae1\u0af9\u0b05-\u0b0c\u0b0f-\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32-\u0b33\u0b35-\u0b39\u0b3d\u0b5c-\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99-\u0b9a\u0b9c\u0b9e-\u0b9f\u0ba3-\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60-\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0-\u0ce1\u0cf1-\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32-\u0e33\u0e40-\u0e45\u0e81-\u0e82\u0e84\u0e87-\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa-\u0eab\u0ead-\u0eb0\u0eb2-\u0eb3\u0ebd\u0ec0-\u0ec4\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065-\u1066\u106e-\u1070\u1075-\u1081\u108e\u1100-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16f1-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17dc\u1820-\u1842\u1844-\u1878\u1880-\u1884\u1887-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae-\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c77\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5-\u1cf6\u2135-\u2138\u2d30-\u2d67\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3006\u303c\u3041-\u3096\u309f\u30a1-\u30fa\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fef\ua000-\ua014\ua016-\ua48c\ua4d0-\ua4f7\ua500-\ua60b\ua610-\ua61f\ua62a-\ua62b\ua66e\ua6a0-\ua6e5\ua78f\ua7f7\ua7fb-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd-\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9e0-\ua9e4\ua9e7-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa6f\uaa71-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5-\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadc\uaae0-\uaaea\uaaf2\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff66-\uff6f\uff71-\uff9d\uffa0-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc\U00010000-\U0001000b\U0001000d-\U00010026\U00010028-\U0001003a\U0001003c-\U0001003d\U0001003f-\U0001004d\U00010050-\U0001005d\U00010080-\U000100fa\U00010280-\U0001029c\U000102a0-\U000102d0\U00010300-\U0001031f\U0001032d-\U00010340\U00010342-\U00010349\U00010350-\U00010375\U00010380-\U0001039d\U000103a0-\U000103c3\U000103c8-\U000103cf\U00010450-\U0001049d\U00010500-\U00010527\U00010530-\U00010563\U00010600-\U00010736\U00010740-\U00010755\U00010760-\U00010767\U00010800-\U00010805\U00010808\U0001080a-\U00010835\U00010837-\U00010838\U0001083c\U0001083f-\U00010855\U00010860-\U00010876\U00010880-\U0001089e\U000108e0-\U000108f2\U000108f4-\U000108f5\U00010900-\U00010915\U00010920-\U00010939\U00010980-\U000109b7\U000109be-\U000109bf\U00010a00\U00010a10-\U00010a13\U00010a15-\U00010a17\U00010a19-\U00010a35\U00010a60-\U00010a7c\U00010a80-\U00010a9c\U00010ac0-\U00010ac7\U00010ac9-\U00010ae4\U00010b00-\U00010b35\U00010b40-\U00010b55\U00010b60-\U00010b72\U00010b80-\U00010b91\U00010c00-\U00010c48\U00010d00-\U00010d23\U00010f00-\U00010f1c\U00010f27\U00010f30-\U00010f45\U00011003-\U00011037\U00011083-\U000110af\U000110d0-\U000110e8\U00011103-\U00011126\U00011144\U00011150-\U00011172\U00011176\U00011183-\U000111b2\U000111c1-\U000111c4\U000111da\U000111dc\U00011200-\U00011211\U00011213-\U0001122b\U00011280-\U00011286\U00011288\U0001128a-\U0001128d\U0001128f-\U0001129d\U0001129f-\U000112a8\U000112b0-\U000112de\U00011305-\U0001130c\U0001130f-\U00011310\U00011313-\U00011328\U0001132a-\U00011330\U00011332-\U00011333\U00011335-\U00011339\U0001133d\U00011350\U0001135d-\U00011361\U00011400-\U00011434\U00011447-\U0001144a\U00011480-\U000114af\U000114c4-\U000114c5\U000114c7\U00011580-\U000115ae\U000115d8-\U000115db\U00011600-\U0001162f\U00011644\U00011680-\U000116aa\U00011700-\U0001171a\U00011800-\U0001182b\U000118ff\U00011a00\U00011a0b-\U00011a32\U00011a3a\U00011a50\U00011a5c-\U00011a83\U00011a86-\U00011a89\U00011a9d\U00011ac0-\U00011af8\U00011c00-\U00011c08\U00011c0a-\U00011c2e\U00011c40\U00011c72-\U00011c8f\U00011d00-\U00011d06\U00011d08-\U00011d09\U00011d0b-\U00011d30\U00011d46\U00011d60-\U00011d65\U00011d67-\U00011d68\U00011d6a-\U00011d89\U00011d98\U00011ee0-\U00011ef2\U00012000-\U00012399\U00012480-\U00012543\U00013000-\U0001342e\U00014400-\U00014646\U00016800-\U00016a38\U00016a40-\U00016a5e\U00016ad0-\U00016aed\U00016b00-\U00016b2f\U00016b63-\U00016b77\U00016b7d-\U00016b8f\U00016f00-\U00016f44\U00016f50\U00017000-\U000187f1\U00018800-\U00018af2\U0001b000-\U0001b11e\U0001b170-\U0001b2fb\U0001bc00-\U0001bc6a\U0001bc70-\U0001bc7c\U0001bc80-\U0001bc88\U0001bc90-\U0001bc99\U0001e800-\U0001e8c4\U0001ee00-\U0001ee03\U0001ee05-\U0001ee1f\U0001ee21-\U0001ee22\U0001ee24\U0001ee27\U0001ee29-\U0001ee32\U0001ee34-\U0001ee37\U0001ee39\U0001ee3b\U0001ee42\U0001ee47\U0001ee49\U0001ee4b\U0001ee4d-\U0001ee4f\U0001ee51-\U0001ee52\U0001ee54\U0001ee57\U0001ee59\U0001ee5b\U0001ee5d\U0001ee5f\U0001ee61-\U0001ee62\U0001ee64\U0001ee67-\U0001ee6a\U0001ee6c-\U0001ee72\U0001ee74-\U0001ee77\U0001ee79-\U0001ee7c\U0001ee7e\U0001ee80-\U0001ee89\U0001ee8b-\U0001ee9b\U0001eea1-\U0001eea3\U0001eea5-\U0001eea9\U0001eeab-\U0001eebb\U00020000-\U0002a6d6\U0002a700-\U0002b734\U0002b740-\U0002b81d\U0002b820-\U0002cea1\U0002ceb0-\U0002ebe0\U0002f800-\U0002fa1d'
+
+Lt = '\u01c5\u01c8\u01cb\u01f2\u1f88-\u1f8f\u1f98-\u1f9f\u1fa8-\u1faf\u1fbc\u1fcc\u1ffc'
+
+Lu = 'A-Z\xc0-\xd6\xd8-\xde\u0100\u0102\u0104\u0106\u0108\u010a\u010c\u010e\u0110\u0112\u0114\u0116\u0118\u011a\u011c\u011e\u0120\u0122\u0124\u0126\u0128\u012a\u012c\u012e\u0130\u0132\u0134\u0136\u0139\u013b\u013d\u013f\u0141\u0143\u0145\u0147\u014a\u014c\u014e\u0150\u0152\u0154\u0156\u0158\u015a\u015c\u015e\u0160\u0162\u0164\u0166\u0168\u016a\u016c\u016e\u0170\u0172\u0174\u0176\u0178-\u0179\u017b\u017d\u0181-\u0182\u0184\u0186-\u0187\u0189-\u018b\u018e-\u0191\u0193-\u0194\u0196-\u0198\u019c-\u019d\u019f-\u01a0\u01a2\u01a4\u01a6-\u01a7\u01a9\u01ac\u01ae-\u01af\u01b1-\u01b3\u01b5\u01b7-\u01b8\u01bc\u01c4\u01c7\u01ca\u01cd\u01cf\u01d1\u01d3\u01d5\u01d7\u01d9\u01db\u01de\u01e0\u01e2\u01e4\u01e6\u01e8\u01ea\u01ec\u01ee\u01f1\u01f4\u01f6-\u01f8\u01fa\u01fc\u01fe\u0200\u0202\u0204\u0206\u0208\u020a\u020c\u020e\u0210\u0212\u0214\u0216\u0218\u021a\u021c\u021e\u0220\u0222\u0224\u0226\u0228\u022a\u022c\u022e\u0230\u0232\u023a-\u023b\u023d-\u023e\u0241\u0243-\u0246\u0248\u024a\u024c\u024e\u0370\u0372\u0376\u037f\u0386\u0388-\u038a\u038c\u038e-\u038f\u0391-\u03a1\u03a3-\u03ab\u03cf\u03d2-\u03d4\u03d8\u03da\u03dc\u03de\u03e0\u03e2\u03e4\u03e6\u03e8\u03ea\u03ec\u03ee\u03f4\u03f7\u03f9-\u03fa\u03fd-\u042f\u0460\u0462\u0464\u0466\u0468\u046a\u046c\u046e\u0470\u0472\u0474\u0476\u0478\u047a\u047c\u047e\u0480\u048a\u048c\u048e\u0490\u0492\u0494\u0496\u0498\u049a\u049c\u049e\u04a0\u04a2\u04a4\u04a6\u04a8\u04aa\u04ac\u04ae\u04b0\u04b2\u04b4\u04b6\u04b8\u04ba\u04bc\u04be\u04c0-\u04c1\u04c3\u04c5\u04c7\u04c9\u04cb\u04cd\u04d0\u04d2\u04d4\u04d6\u04d8\u04da\u04dc\u04de\u04e0\u04e2\u04e4\u04e6\u04e8\u04ea\u04ec\u04ee\u04f0\u04f2\u04f4\u04f6\u04f8\u04fa\u04fc\u04fe\u0500\u0502\u0504\u0506\u0508\u050a\u050c\u050e\u0510\u0512\u0514\u0516\u0518\u051a\u051c\u051e\u0520\u0522\u0524\u0526\u0528\u052a\u052c\u052e\u0531-\u0556\u10a0-\u10c5\u10c7\u10cd\u13a0-\u13f5\u1c90-\u1cba\u1cbd-\u1cbf\u1e00\u1e02\u1e04\u1e06\u1e08\u1e0a\u1e0c\u1e0e\u1e10\u1e12\u1e14\u1e16\u1e18\u1e1a\u1e1c\u1e1e\u1e20\u1e22\u1e24\u1e26\u1e28\u1e2a\u1e2c\u1e2e\u1e30\u1e32\u1e34\u1e36\u1e38\u1e3a\u1e3c\u1e3e\u1e40\u1e42\u1e44\u1e46\u1e48\u1e4a\u1e4c\u1e4e\u1e50\u1e52\u1e54\u1e56\u1e58\u1e5a\u1e5c\u1e5e\u1e60\u1e62\u1e64\u1e66\u1e68\u1e6a\u1e6c\u1e6e\u1e70\u1e72\u1e74\u1e76\u1e78\u1e7a\u1e7c\u1e7e\u1e80\u1e82\u1e84\u1e86\u1e88\u1e8a\u1e8c\u1e8e\u1e90\u1e92\u1e94\u1e9e\u1ea0\u1ea2\u1ea4\u1ea6\u1ea8\u1eaa\u1eac\u1eae\u1eb0\u1eb2\u1eb4\u1eb6\u1eb8\u1eba\u1ebc\u1ebe\u1ec0\u1ec2\u1ec4\u1ec6\u1ec8\u1eca\u1ecc\u1ece\u1ed0\u1ed2\u1ed4\u1ed6\u1ed8\u1eda\u1edc\u1ede\u1ee0\u1ee2\u1ee4\u1ee6\u1ee8\u1eea\u1eec\u1eee\u1ef0\u1ef2\u1ef4\u1ef6\u1ef8\u1efa\u1efc\u1efe\u1f08-\u1f0f\u1f18-\u1f1d\u1f28-\u1f2f\u1f38-\u1f3f\u1f48-\u1f4d\u1f59\u1f5b\u1f5d\u1f5f\u1f68-\u1f6f\u1fb8-\u1fbb\u1fc8-\u1fcb\u1fd8-\u1fdb\u1fe8-\u1fec\u1ff8-\u1ffb\u2102\u2107\u210b-\u210d\u2110-\u2112\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u2130-\u2133\u213e-\u213f\u2145\u2183\u2c00-\u2c2e\u2c60\u2c62-\u2c64\u2c67\u2c69\u2c6b\u2c6d-\u2c70\u2c72\u2c75\u2c7e-\u2c80\u2c82\u2c84\u2c86\u2c88\u2c8a\u2c8c\u2c8e\u2c90\u2c92\u2c94\u2c96\u2c98\u2c9a\u2c9c\u2c9e\u2ca0\u2ca2\u2ca4\u2ca6\u2ca8\u2caa\u2cac\u2cae\u2cb0\u2cb2\u2cb4\u2cb6\u2cb8\u2cba\u2cbc\u2cbe\u2cc0\u2cc2\u2cc4\u2cc6\u2cc8\u2cca\u2ccc\u2cce\u2cd0\u2cd2\u2cd4\u2cd6\u2cd8\u2cda\u2cdc\u2cde\u2ce0\u2ce2\u2ceb\u2ced\u2cf2\ua640\ua642\ua644\ua646\ua648\ua64a\ua64c\ua64e\ua650\ua652\ua654\ua656\ua658\ua65a\ua65c\ua65e\ua660\ua662\ua664\ua666\ua668\ua66a\ua66c\ua680\ua682\ua684\ua686\ua688\ua68a\ua68c\ua68e\ua690\ua692\ua694\ua696\ua698\ua69a\ua722\ua724\ua726\ua728\ua72a\ua72c\ua72e\ua732\ua734\ua736\ua738\ua73a\ua73c\ua73e\ua740\ua742\ua744\ua746\ua748\ua74a\ua74c\ua74e\ua750\ua752\ua754\ua756\ua758\ua75a\ua75c\ua75e\ua760\ua762\ua764\ua766\ua768\ua76a\ua76c\ua76e\ua779\ua77b\ua77d-\ua77e\ua780\ua782\ua784\ua786\ua78b\ua78d\ua790\ua792\ua796\ua798\ua79a\ua79c\ua79e\ua7a0\ua7a2\ua7a4\ua7a6\ua7a8\ua7aa-\ua7ae\ua7b0-\ua7b4\ua7b6\ua7b8\uff21-\uff3a\U00010400-\U00010427\U000104b0-\U000104d3\U00010c80-\U00010cb2\U000118a0-\U000118bf\U00016e40-\U00016e5f\U0001d400-\U0001d419\U0001d434-\U0001d44d\U0001d468-\U0001d481\U0001d49c\U0001d49e-\U0001d49f\U0001d4a2\U0001d4a5-\U0001d4a6\U0001d4a9-\U0001d4ac\U0001d4ae-\U0001d4b5\U0001d4d0-\U0001d4e9\U0001d504-\U0001d505\U0001d507-\U0001d50a\U0001d50d-\U0001d514\U0001d516-\U0001d51c\U0001d538-\U0001d539\U0001d53b-\U0001d53e\U0001d540-\U0001d544\U0001d546\U0001d54a-\U0001d550\U0001d56c-\U0001d585\U0001d5a0-\U0001d5b9\U0001d5d4-\U0001d5ed\U0001d608-\U0001d621\U0001d63c-\U0001d655\U0001d670-\U0001d689\U0001d6a8-\U0001d6c0\U0001d6e2-\U0001d6fa\U0001d71c-\U0001d734\U0001d756-\U0001d76e\U0001d790-\U0001d7a8\U0001d7ca\U0001e900-\U0001e921'
+
+Mc = '\u0903\u093b\u093e-\u0940\u0949-\u094c\u094e-\u094f\u0982-\u0983\u09be-\u09c0\u09c7-\u09c8\u09cb-\u09cc\u09d7\u0a03\u0a3e-\u0a40\u0a83\u0abe-\u0ac0\u0ac9\u0acb-\u0acc\u0b02-\u0b03\u0b3e\u0b40\u0b47-\u0b48\u0b4b-\u0b4c\u0b57\u0bbe-\u0bbf\u0bc1-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcc\u0bd7\u0c01-\u0c03\u0c41-\u0c44\u0c82-\u0c83\u0cbe\u0cc0-\u0cc4\u0cc7-\u0cc8\u0cca-\u0ccb\u0cd5-\u0cd6\u0d02-\u0d03\u0d3e-\u0d40\u0d46-\u0d48\u0d4a-\u0d4c\u0d57\u0d82-\u0d83\u0dcf-\u0dd1\u0dd8-\u0ddf\u0df2-\u0df3\u0f3e-\u0f3f\u0f7f\u102b-\u102c\u1031\u1038\u103b-\u103c\u1056-\u1057\u1062-\u1064\u1067-\u106d\u1083-\u1084\u1087-\u108c\u108f\u109a-\u109c\u17b6\u17be-\u17c5\u17c7-\u17c8\u1923-\u1926\u1929-\u192b\u1930-\u1931\u1933-\u1938\u1a19-\u1a1a\u1a55\u1a57\u1a61\u1a63-\u1a64\u1a6d-\u1a72\u1b04\u1b35\u1b3b\u1b3d-\u1b41\u1b43-\u1b44\u1b82\u1ba1\u1ba6-\u1ba7\u1baa\u1be7\u1bea-\u1bec\u1bee\u1bf2-\u1bf3\u1c24-\u1c2b\u1c34-\u1c35\u1ce1\u1cf2-\u1cf3\u1cf7\u302e-\u302f\ua823-\ua824\ua827\ua880-\ua881\ua8b4-\ua8c3\ua952-\ua953\ua983\ua9b4-\ua9b5\ua9ba-\ua9bb\ua9bd-\ua9c0\uaa2f-\uaa30\uaa33-\uaa34\uaa4d\uaa7b\uaa7d\uaaeb\uaaee-\uaaef\uaaf5\uabe3-\uabe4\uabe6-\uabe7\uabe9-\uabea\uabec\U00011000\U00011002\U00011082\U000110b0-\U000110b2\U000110b7-\U000110b8\U0001112c\U00011145-\U00011146\U00011182\U000111b3-\U000111b5\U000111bf-\U000111c0\U0001122c-\U0001122e\U00011232-\U00011233\U00011235\U000112e0-\U000112e2\U00011302-\U00011303\U0001133e-\U0001133f\U00011341-\U00011344\U00011347-\U00011348\U0001134b-\U0001134d\U00011357\U00011362-\U00011363\U00011435-\U00011437\U00011440-\U00011441\U00011445\U000114b0-\U000114b2\U000114b9\U000114bb-\U000114be\U000114c1\U000115af-\U000115b1\U000115b8-\U000115bb\U000115be\U00011630-\U00011632\U0001163b-\U0001163c\U0001163e\U000116ac\U000116ae-\U000116af\U000116b6\U00011720-\U00011721\U00011726\U0001182c-\U0001182e\U00011838\U00011a39\U00011a57-\U00011a58\U00011a97\U00011c2f\U00011c3e\U00011ca9\U00011cb1\U00011cb4\U00011d8a-\U00011d8e\U00011d93-\U00011d94\U00011d96\U00011ef5-\U00011ef6\U00016f51-\U00016f7e\U0001d165-\U0001d166\U0001d16d-\U0001d172'
+
+Me = '\u0488-\u0489\u1abe\u20dd-\u20e0\u20e2-\u20e4\ua670-\ua672'
+
+Mn = '\u0300-\u036f\u0483-\u0487\u0591-\u05bd\u05bf\u05c1-\u05c2\u05c4-\u05c5\u05c7\u0610-\u061a\u064b-\u065f\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7-\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d3-\u08e1\u08e3-\u0902\u093a\u093c\u0941-\u0948\u094d\u0951-\u0957\u0962-\u0963\u0981\u09bc\u09c1-\u09c4\u09cd\u09e2-\u09e3\u09fe\u0a01-\u0a02\u0a3c\u0a41-\u0a42\u0a47-\u0a48\u0a4b-\u0a4d\u0a51\u0a70-\u0a71\u0a75\u0a81-\u0a82\u0abc\u0ac1-\u0ac5\u0ac7-\u0ac8\u0acd\u0ae2-\u0ae3\u0afa-\u0aff\u0b01\u0b3c\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b62-\u0b63\u0b82\u0bc0\u0bcd\u0c00\u0c04\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55-\u0c56\u0c62-\u0c63\u0c81\u0cbc\u0cbf\u0cc6\u0ccc-\u0ccd\u0ce2-\u0ce3\u0d00-\u0d01\u0d3b-\u0d3c\u0d41-\u0d44\u0d4d\u0d62-\u0d63\u0dca\u0dd2-\u0dd4\u0dd6\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb-\u0ebc\u0ec8-\u0ecd\u0f18-\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86-\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039-\u103a\u103d-\u103e\u1058-\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085-\u1086\u108d\u109d\u135d-\u135f\u1712-\u1714\u1732-\u1734\u1752-\u1753\u1772-\u1773\u17b4-\u17b5\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u1885-\u1886\u18a9\u1920-\u1922\u1927-\u1928\u1932\u1939-\u193b\u1a17-\u1a18\u1a1b\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1ab0-\u1abd\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80-\u1b81\u1ba2-\u1ba5\u1ba8-\u1ba9\u1bab-\u1bad\u1be6\u1be8-\u1be9\u1bed\u1bef-\u1bf1\u1c2c-\u1c33\u1c36-\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1cf4\u1cf8-\u1cf9\u1dc0-\u1df9\u1dfb-\u1dff\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302d\u3099-\u309a\ua66f\ua674-\ua67d\ua69e-\ua69f\ua6f0-\ua6f1\ua802\ua806\ua80b\ua825-\ua826\ua8c4-\ua8c5\ua8e0-\ua8f1\ua8ff\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\ua9e5\uaa29-\uaa2e\uaa31-\uaa32\uaa35-\uaa36\uaa43\uaa4c\uaa7c\uaab0\uaab2-\uaab4\uaab7-\uaab8\uaabe-\uaabf\uaac1\uaaec-\uaaed\uaaf6\uabe5\uabe8\uabed\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\U000101fd\U000102e0\U00010376-\U0001037a\U00010a01-\U00010a03\U00010a05-\U00010a06\U00010a0c-\U00010a0f\U00010a38-\U00010a3a\U00010a3f\U00010ae5-\U00010ae6\U00010d24-\U00010d27\U00010f46-\U00010f50\U00011001\U00011038-\U00011046\U0001107f-\U00011081\U000110b3-\U000110b6\U000110b9-\U000110ba\U00011100-\U00011102\U00011127-\U0001112b\U0001112d-\U00011134\U00011173\U00011180-\U00011181\U000111b6-\U000111be\U000111c9-\U000111cc\U0001122f-\U00011231\U00011234\U00011236-\U00011237\U0001123e\U000112df\U000112e3-\U000112ea\U00011300-\U00011301\U0001133b-\U0001133c\U00011340\U00011366-\U0001136c\U00011370-\U00011374\U00011438-\U0001143f\U00011442-\U00011444\U00011446\U0001145e\U000114b3-\U000114b8\U000114ba\U000114bf-\U000114c0\U000114c2-\U000114c3\U000115b2-\U000115b5\U000115bc-\U000115bd\U000115bf-\U000115c0\U000115dc-\U000115dd\U00011633-\U0001163a\U0001163d\U0001163f-\U00011640\U000116ab\U000116ad\U000116b0-\U000116b5\U000116b7\U0001171d-\U0001171f\U00011722-\U00011725\U00011727-\U0001172b\U0001182f-\U00011837\U00011839-\U0001183a\U00011a01-\U00011a0a\U00011a33-\U00011a38\U00011a3b-\U00011a3e\U00011a47\U00011a51-\U00011a56\U00011a59-\U00011a5b\U00011a8a-\U00011a96\U00011a98-\U00011a99\U00011c30-\U00011c36\U00011c38-\U00011c3d\U00011c3f\U00011c92-\U00011ca7\U00011caa-\U00011cb0\U00011cb2-\U00011cb3\U00011cb5-\U00011cb6\U00011d31-\U00011d36\U00011d3a\U00011d3c-\U00011d3d\U00011d3f-\U00011d45\U00011d47\U00011d90-\U00011d91\U00011d95\U00011d97\U00011ef3-\U00011ef4\U00016af0-\U00016af4\U00016b30-\U00016b36\U00016f8f-\U00016f92\U0001bc9d-\U0001bc9e\U0001d167-\U0001d169\U0001d17b-\U0001d182\U0001d185-\U0001d18b\U0001d1aa-\U0001d1ad\U0001d242-\U0001d244\U0001da00-\U0001da36\U0001da3b-\U0001da6c\U0001da75\U0001da84\U0001da9b-\U0001da9f\U0001daa1-\U0001daaf\U0001e000-\U0001e006\U0001e008-\U0001e018\U0001e01b-\U0001e021\U0001e023-\U0001e024\U0001e026-\U0001e02a\U0001e8d0-\U0001e8d6\U0001e944-\U0001e94a\U000e0100-\U000e01ef'
+
+Nd = '0-9\u0660-\u0669\u06f0-\u06f9\u07c0-\u07c9\u0966-\u096f\u09e6-\u09ef\u0a66-\u0a6f\u0ae6-\u0aef\u0b66-\u0b6f\u0be6-\u0bef\u0c66-\u0c6f\u0ce6-\u0cef\u0d66-\u0d6f\u0de6-\u0def\u0e50-\u0e59\u0ed0-\u0ed9\u0f20-\u0f29\u1040-\u1049\u1090-\u1099\u17e0-\u17e9\u1810-\u1819\u1946-\u194f\u19d0-\u19d9\u1a80-\u1a89\u1a90-\u1a99\u1b50-\u1b59\u1bb0-\u1bb9\u1c40-\u1c49\u1c50-\u1c59\ua620-\ua629\ua8d0-\ua8d9\ua900-\ua909\ua9d0-\ua9d9\ua9f0-\ua9f9\uaa50-\uaa59\uabf0-\uabf9\uff10-\uff19\U000104a0-\U000104a9\U00010d30-\U00010d39\U00011066-\U0001106f\U000110f0-\U000110f9\U00011136-\U0001113f\U000111d0-\U000111d9\U000112f0-\U000112f9\U00011450-\U00011459\U000114d0-\U000114d9\U00011650-\U00011659\U000116c0-\U000116c9\U00011730-\U00011739\U000118e0-\U000118e9\U00011c50-\U00011c59\U00011d50-\U00011d59\U00011da0-\U00011da9\U00016a60-\U00016a69\U00016b50-\U00016b59\U0001d7ce-\U0001d7ff\U0001e950-\U0001e959'
+
+Nl = '\u16ee-\u16f0\u2160-\u2182\u2185-\u2188\u3007\u3021-\u3029\u3038-\u303a\ua6e6-\ua6ef\U00010140-\U00010174\U00010341\U0001034a\U000103d1-\U000103d5\U00012400-\U0001246e'
+
+No = '\xb2-\xb3\xb9\xbc-\xbe\u09f4-\u09f9\u0b72-\u0b77\u0bf0-\u0bf2\u0c78-\u0c7e\u0d58-\u0d5e\u0d70-\u0d78\u0f2a-\u0f33\u1369-\u137c\u17f0-\u17f9\u19da\u2070\u2074-\u2079\u2080-\u2089\u2150-\u215f\u2189\u2460-\u249b\u24ea-\u24ff\u2776-\u2793\u2cfd\u3192-\u3195\u3220-\u3229\u3248-\u324f\u3251-\u325f\u3280-\u3289\u32b1-\u32bf\ua830-\ua835\U00010107-\U00010133\U00010175-\U00010178\U0001018a-\U0001018b\U000102e1-\U000102fb\U00010320-\U00010323\U00010858-\U0001085f\U00010879-\U0001087f\U000108a7-\U000108af\U000108fb-\U000108ff\U00010916-\U0001091b\U000109bc-\U000109bd\U000109c0-\U000109cf\U000109d2-\U000109ff\U00010a40-\U00010a48\U00010a7d-\U00010a7e\U00010a9d-\U00010a9f\U00010aeb-\U00010aef\U00010b58-\U00010b5f\U00010b78-\U00010b7f\U00010ba9-\U00010baf\U00010cfa-\U00010cff\U00010e60-\U00010e7e\U00010f1d-\U00010f26\U00010f51-\U00010f54\U00011052-\U00011065\U000111e1-\U000111f4\U0001173a-\U0001173b\U000118ea-\U000118f2\U00011c5a-\U00011c6c\U00016b5b-\U00016b61\U00016e80-\U00016e96\U0001d2e0-\U0001d2f3\U0001d360-\U0001d378\U0001e8c7-\U0001e8cf\U0001ec71-\U0001ecab\U0001ecad-\U0001ecaf\U0001ecb1-\U0001ecb4\U0001f100-\U0001f10c'
+
+Pc = '_\u203f-\u2040\u2054\ufe33-\ufe34\ufe4d-\ufe4f\uff3f'
+
+Pd = '\\-\u058a\u05be\u1400\u1806\u2010-\u2015\u2e17\u2e1a\u2e3a-\u2e3b\u2e40\u301c\u3030\u30a0\ufe31-\ufe32\ufe58\ufe63\uff0d'
+
+Pe = ')\\]}\u0f3b\u0f3d\u169c\u2046\u207e\u208e\u2309\u230b\u232a\u2769\u276b\u276d\u276f\u2771\u2773\u2775\u27c6\u27e7\u27e9\u27eb\u27ed\u27ef\u2984\u2986\u2988\u298a\u298c\u298e\u2990\u2992\u2994\u2996\u2998\u29d9\u29db\u29fd\u2e23\u2e25\u2e27\u2e29\u3009\u300b\u300d\u300f\u3011\u3015\u3017\u3019\u301b\u301e-\u301f\ufd3e\ufe18\ufe36\ufe38\ufe3a\ufe3c\ufe3e\ufe40\ufe42\ufe44\ufe48\ufe5a\ufe5c\ufe5e\uff09\uff3d\uff5d\uff60\uff63'
+
+Pf = '\xbb\u2019\u201d\u203a\u2e03\u2e05\u2e0a\u2e0d\u2e1d\u2e21'
+
+Pi = '\xab\u2018\u201b-\u201c\u201f\u2039\u2e02\u2e04\u2e09\u2e0c\u2e1c\u2e20'
+
+Po = "!-#%-'*,.-/:-;?-@\\\\\xa1\xa7\xb6-\xb7\xbf\u037e\u0387\u055a-\u055f\u0589\u05c0\u05c3\u05c6\u05f3-\u05f4\u0609-\u060a\u060c-\u060d\u061b\u061e-\u061f\u066a-\u066d\u06d4\u0700-\u070d\u07f7-\u07f9\u0830-\u083e\u085e\u0964-\u0965\u0970\u09fd\u0a76\u0af0\u0c84\u0df4\u0e4f\u0e5a-\u0e5b\u0f04-\u0f12\u0f14\u0f85\u0fd0-\u0fd4\u0fd9-\u0fda\u104a-\u104f\u10fb\u1360-\u1368\u166d-\u166e\u16eb-\u16ed\u1735-\u1736\u17d4-\u17d6\u17d8-\u17da\u1800-\u1805\u1807-\u180a\u1944-\u1945\u1a1e-\u1a1f\u1aa0-\u1aa6\u1aa8-\u1aad\u1b5a-\u1b60\u1bfc-\u1bff\u1c3b-\u1c3f\u1c7e-\u1c7f\u1cc0-\u1cc7\u1cd3\u2016-\u2017\u2020-\u2027\u2030-\u2038\u203b-\u203e\u2041-\u2043\u2047-\u2051\u2053\u2055-\u205e\u2cf9-\u2cfc\u2cfe-\u2cff\u2d70\u2e00-\u2e01\u2e06-\u2e08\u2e0b\u2e0e-\u2e16\u2e18-\u2e19\u2e1b\u2e1e-\u2e1f\u2e2a-\u2e2e\u2e30-\u2e39\u2e3c-\u2e3f\u2e41\u2e43-\u2e4e\u3001-\u3003\u303d\u30fb\ua4fe-\ua4ff\ua60d-\ua60f\ua673\ua67e\ua6f2-\ua6f7\ua874-\ua877\ua8ce-\ua8cf\ua8f8-\ua8fa\ua8fc\ua92e-\ua92f\ua95f\ua9c1-\ua9cd\ua9de-\ua9df\uaa5c-\uaa5f\uaade-\uaadf\uaaf0-\uaaf1\uabeb\ufe10-\ufe16\ufe19\ufe30\ufe45-\ufe46\ufe49-\ufe4c\ufe50-\ufe52\ufe54-\ufe57\ufe5f-\ufe61\ufe68\ufe6a-\ufe6b\uff01-\uff03\uff05-\uff07\uff0a\uff0c\uff0e-\uff0f\uff1a-\uff1b\uff1f-\uff20\uff3c\uff61\uff64-\uff65\U00010100-\U00010102\U0001039f\U000103d0\U0001056f\U00010857\U0001091f\U0001093f\U00010a50-\U00010a58\U00010a7f\U00010af0-\U00010af6\U00010b39-\U00010b3f\U00010b99-\U00010b9c\U00010f55-\U00010f59\U00011047-\U0001104d\U000110bb-\U000110bc\U000110be-\U000110c1\U00011140-\U00011143\U00011174-\U00011175\U000111c5-\U000111c8\U000111cd\U000111db\U000111dd-\U000111df\U00011238-\U0001123d\U000112a9\U0001144b-\U0001144f\U0001145b\U0001145d\U000114c6\U000115c1-\U000115d7\U00011641-\U00011643\U00011660-\U0001166c\U0001173c-\U0001173e\U0001183b\U00011a3f-\U00011a46\U00011a9a-\U00011a9c\U00011a9e-\U00011aa2\U00011c41-\U00011c45\U00011c70-\U00011c71\U00011ef7-\U00011ef8\U00012470-\U00012474\U00016a6e-\U00016a6f\U00016af5\U00016b37-\U00016b3b\U00016b44\U00016e97-\U00016e9a\U0001bc9f\U0001da87-\U0001da8b\U0001e95e-\U0001e95f"
+
+Ps = '(\\[{\u0f3a\u0f3c\u169b\u201a\u201e\u2045\u207d\u208d\u2308\u230a\u2329\u2768\u276a\u276c\u276e\u2770\u2772\u2774\u27c5\u27e6\u27e8\u27ea\u27ec\u27ee\u2983\u2985\u2987\u2989\u298b\u298d\u298f\u2991\u2993\u2995\u2997\u29d8\u29da\u29fc\u2e22\u2e24\u2e26\u2e28\u2e42\u3008\u300a\u300c\u300e\u3010\u3014\u3016\u3018\u301a\u301d\ufd3f\ufe17\ufe35\ufe37\ufe39\ufe3b\ufe3d\ufe3f\ufe41\ufe43\ufe47\ufe59\ufe5b\ufe5d\uff08\uff3b\uff5b\uff5f\uff62'
+
+Sc = '$\xa2-\xa5\u058f\u060b\u07fe-\u07ff\u09f2-\u09f3\u09fb\u0af1\u0bf9\u0e3f\u17db\u20a0-\u20bf\ua838\ufdfc\ufe69\uff04\uffe0-\uffe1\uffe5-\uffe6\U0001ecb0'
+
+Sk = '\\^`\xa8\xaf\xb4\xb8\u02c2-\u02c5\u02d2-\u02df\u02e5-\u02eb\u02ed\u02ef-\u02ff\u0375\u0384-\u0385\u1fbd\u1fbf-\u1fc1\u1fcd-\u1fcf\u1fdd-\u1fdf\u1fed-\u1fef\u1ffd-\u1ffe\u309b-\u309c\ua700-\ua716\ua720-\ua721\ua789-\ua78a\uab5b\ufbb2-\ufbc1\uff3e\uff40\uffe3\U0001f3fb-\U0001f3ff'
+
+Sm = '+<->|~\xac\xb1\xd7\xf7\u03f6\u0606-\u0608\u2044\u2052\u207a-\u207c\u208a-\u208c\u2118\u2140-\u2144\u214b\u2190-\u2194\u219a-\u219b\u21a0\u21a3\u21a6\u21ae\u21ce-\u21cf\u21d2\u21d4\u21f4-\u22ff\u2320-\u2321\u237c\u239b-\u23b3\u23dc-\u23e1\u25b7\u25c1\u25f8-\u25ff\u266f\u27c0-\u27c4\u27c7-\u27e5\u27f0-\u27ff\u2900-\u2982\u2999-\u29d7\u29dc-\u29fb\u29fe-\u2aff\u2b30-\u2b44\u2b47-\u2b4c\ufb29\ufe62\ufe64-\ufe66\uff0b\uff1c-\uff1e\uff5c\uff5e\uffe2\uffe9-\uffec\U0001d6c1\U0001d6db\U0001d6fb\U0001d715\U0001d735\U0001d74f\U0001d76f\U0001d789\U0001d7a9\U0001d7c3\U0001eef0-\U0001eef1'
+
+So = '\xa6\xa9\xae\xb0\u0482\u058d-\u058e\u060e-\u060f\u06de\u06e9\u06fd-\u06fe\u07f6\u09fa\u0b70\u0bf3-\u0bf8\u0bfa\u0c7f\u0d4f\u0d79\u0f01-\u0f03\u0f13\u0f15-\u0f17\u0f1a-\u0f1f\u0f34\u0f36\u0f38\u0fbe-\u0fc5\u0fc7-\u0fcc\u0fce-\u0fcf\u0fd5-\u0fd8\u109e-\u109f\u1390-\u1399\u1940\u19de-\u19ff\u1b61-\u1b6a\u1b74-\u1b7c\u2100-\u2101\u2103-\u2106\u2108-\u2109\u2114\u2116-\u2117\u211e-\u2123\u2125\u2127\u2129\u212e\u213a-\u213b\u214a\u214c-\u214d\u214f\u218a-\u218b\u2195-\u2199\u219c-\u219f\u21a1-\u21a2\u21a4-\u21a5\u21a7-\u21ad\u21af-\u21cd\u21d0-\u21d1\u21d3\u21d5-\u21f3\u2300-\u2307\u230c-\u231f\u2322-\u2328\u232b-\u237b\u237d-\u239a\u23b4-\u23db\u23e2-\u2426\u2440-\u244a\u249c-\u24e9\u2500-\u25b6\u25b8-\u25c0\u25c2-\u25f7\u2600-\u266e\u2670-\u2767\u2794-\u27bf\u2800-\u28ff\u2b00-\u2b2f\u2b45-\u2b46\u2b4d-\u2b73\u2b76-\u2b95\u2b98-\u2bc8\u2bca-\u2bfe\u2ce5-\u2cea\u2e80-\u2e99\u2e9b-\u2ef3\u2f00-\u2fd5\u2ff0-\u2ffb\u3004\u3012-\u3013\u3020\u3036-\u3037\u303e-\u303f\u3190-\u3191\u3196-\u319f\u31c0-\u31e3\u3200-\u321e\u322a-\u3247\u3250\u3260-\u327f\u328a-\u32b0\u32c0-\u32fe\u3300-\u33ff\u4dc0-\u4dff\ua490-\ua4c6\ua828-\ua82b\ua836-\ua837\ua839\uaa77-\uaa79\ufdfd\uffe4\uffe8\uffed-\uffee\ufffc-\ufffd\U00010137-\U0001013f\U00010179-\U00010189\U0001018c-\U0001018e\U00010190-\U0001019b\U000101a0\U000101d0-\U000101fc\U00010877-\U00010878\U00010ac8\U0001173f\U00016b3c-\U00016b3f\U00016b45\U0001bc9c\U0001d000-\U0001d0f5\U0001d100-\U0001d126\U0001d129-\U0001d164\U0001d16a-\U0001d16c\U0001d183-\U0001d184\U0001d18c-\U0001d1a9\U0001d1ae-\U0001d1e8\U0001d200-\U0001d241\U0001d245\U0001d300-\U0001d356\U0001d800-\U0001d9ff\U0001da37-\U0001da3a\U0001da6d-\U0001da74\U0001da76-\U0001da83\U0001da85-\U0001da86\U0001ecac\U0001f000-\U0001f02b\U0001f030-\U0001f093\U0001f0a0-\U0001f0ae\U0001f0b1-\U0001f0bf\U0001f0c1-\U0001f0cf\U0001f0d1-\U0001f0f5\U0001f110-\U0001f16b\U0001f170-\U0001f1ac\U0001f1e6-\U0001f202\U0001f210-\U0001f23b\U0001f240-\U0001f248\U0001f250-\U0001f251\U0001f260-\U0001f265\U0001f300-\U0001f3fa\U0001f400-\U0001f6d4\U0001f6e0-\U0001f6ec\U0001f6f0-\U0001f6f9\U0001f700-\U0001f773\U0001f780-\U0001f7d8\U0001f800-\U0001f80b\U0001f810-\U0001f847\U0001f850-\U0001f859\U0001f860-\U0001f887\U0001f890-\U0001f8ad\U0001f900-\U0001f90b\U0001f910-\U0001f93e\U0001f940-\U0001f970\U0001f973-\U0001f976\U0001f97a\U0001f97c-\U0001f9a2\U0001f9b0-\U0001f9b9\U0001f9c0-\U0001f9c2\U0001f9d0-\U0001f9ff\U0001fa60-\U0001fa6d'
+
+Zl = '\u2028'
+
+Zp = '\u2029'
+
+Zs = ' \xa0\u1680\u2000-\u200a\u202f\u205f\u3000'
+
+xid_continue = '0-9A-Z_a-z\xaa\xb5\xb7\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0300-\u0374\u0376-\u0377\u037b-\u037d\u037f\u0386-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u0483-\u0487\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u0591-\u05bd\u05bf\u05c1-\u05c2\u05c4-\u05c5\u05c7\u05d0-\u05ea\u05ef-\u05f2\u0610-\u061a\u0620-\u0669\u066e-\u06d3\u06d5-\u06dc\u06df-\u06e8\u06ea-\u06fc\u06ff\u0710-\u074a\u074d-\u07b1\u07c0-\u07f5\u07fa\u07fd\u0800-\u082d\u0840-\u085b\u0860-\u086a\u08a0-\u08b4\u08b6-\u08bd\u08d3-\u08e1\u08e3-\u0963\u0966-\u096f\u0971-\u0983\u0985-\u098c\u098f-\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bc-\u09c4\u09c7-\u09c8\u09cb-\u09ce\u09d7\u09dc-\u09dd\u09df-\u09e3\u09e6-\u09f1\u09fc\u09fe\u0a01-\u0a03\u0a05-\u0a0a\u0a0f-\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32-\u0a33\u0a35-\u0a36\u0a38-\u0a39\u0a3c\u0a3e-\u0a42\u0a47-\u0a48\u0a4b-\u0a4d\u0a51\u0a59-\u0a5c\u0a5e\u0a66-\u0a75\u0a81-\u0a83\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2-\u0ab3\u0ab5-\u0ab9\u0abc-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ad0\u0ae0-\u0ae3\u0ae6-\u0aef\u0af9-\u0aff\u0b01-\u0b03\u0b05-\u0b0c\u0b0f-\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32-\u0b33\u0b35-\u0b39\u0b3c-\u0b44\u0b47-\u0b48\u0b4b-\u0b4d\u0b56-\u0b57\u0b5c-\u0b5d\u0b5f-\u0b63\u0b66-\u0b6f\u0b71\u0b82-\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99-\u0b9a\u0b9c\u0b9e-\u0b9f\u0ba3-\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd0\u0bd7\u0be6-\u0bef\u0c00-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55-\u0c56\u0c58-\u0c5a\u0c60-\u0c63\u0c66-\u0c6f\u0c80-\u0c83\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbc-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5-\u0cd6\u0cde\u0ce0-\u0ce3\u0ce6-\u0cef\u0cf1-\u0cf2\u0d00-\u0d03\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d44\u0d46-\u0d48\u0d4a-\u0d4e\u0d54-\u0d57\u0d5f-\u0d63\u0d66-\u0d6f\u0d7a-\u0d7f\u0d82-\u0d83\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2-\u0df3\u0e01-\u0e3a\u0e40-\u0e4e\u0e50-\u0e59\u0e81-\u0e82\u0e84\u0e87-\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa-\u0eab\u0ead-\u0eb9\u0ebb-\u0ebd\u0ec0-\u0ec4\u0ec6\u0ec8-\u0ecd\u0ed0-\u0ed9\u0edc-\u0edf\u0f00\u0f18-\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e-\u0f47\u0f49-\u0f6c\u0f71-\u0f84\u0f86-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1049\u1050-\u109d\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u135d-\u135f\u1369-\u1371\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176c\u176e-\u1770\u1772-\u1773\u1780-\u17d3\u17d7\u17dc-\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1820-\u1878\u1880-\u18aa\u18b0-\u18f5\u1900-\u191e\u1920-\u192b\u1930-\u193b\u1946-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u19d0-\u19da\u1a00-\u1a1b\u1a20-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1aa7\u1ab0-\u1abd\u1b00-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1bf3\u1c00-\u1c37\u1c40-\u1c49\u1c4d-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1cd0-\u1cd2\u1cd4-\u1cf9\u1d00-\u1df9\u1dfb-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u203f-\u2040\u2054\u2071\u207f\u2090-\u209c\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d7f-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2de0-\u2dff\u3005-\u3007\u3021-\u302f\u3031-\u3035\u3038-\u303c\u3041-\u3096\u3099-\u309a\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fef\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua62b\ua640-\ua66f\ua674-\ua67d\ua67f-\ua6f1\ua717-\ua71f\ua722-\ua788\ua78b-\ua7b9\ua7f7-\ua827\ua840-\ua873\ua880-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f7\ua8fb\ua8fd-\ua92d\ua930-\ua953\ua960-\ua97c\ua980-\ua9c0\ua9cf-\ua9d9\ua9e0-\ua9fe\uaa00-\uaa36\uaa40-\uaa4d\uaa50-\uaa59\uaa60-\uaa76\uaa7a-\uaac2\uaadb-\uaadd\uaae0-\uaaef\uaaf2-\uaaf6\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab65\uab70-\uabea\uabec-\uabed\uabf0-\uabf9\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufbb1\ufbd3-\ufc5d\ufc64-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdf9\ufe00-\ufe0f\ufe20-\ufe2f\ufe33-\ufe34\ufe4d-\ufe4f\ufe71\ufe73\ufe77\ufe79\ufe7b\ufe7d\ufe7f-\ufefc\uff10-\uff19\uff21-\uff3a\uff3f\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc\U00010000-\U0001000b\U0001000d-\U00010026\U00010028-\U0001003a\U0001003c-\U0001003d\U0001003f-\U0001004d\U00010050-\U0001005d\U00010080-\U000100fa\U00010140-\U00010174\U000101fd\U00010280-\U0001029c\U000102a0-\U000102d0\U000102e0\U00010300-\U0001031f\U0001032d-\U0001034a\U00010350-\U0001037a\U00010380-\U0001039d\U000103a0-\U000103c3\U000103c8-\U000103cf\U000103d1-\U000103d5\U00010400-\U0001049d\U000104a0-\U000104a9\U000104b0-\U000104d3\U000104d8-\U000104fb\U00010500-\U00010527\U00010530-\U00010563\U00010600-\U00010736\U00010740-\U00010755\U00010760-\U00010767\U00010800-\U00010805\U00010808\U0001080a-\U00010835\U00010837-\U00010838\U0001083c\U0001083f-\U00010855\U00010860-\U00010876\U00010880-\U0001089e\U000108e0-\U000108f2\U000108f4-\U000108f5\U00010900-\U00010915\U00010920-\U00010939\U00010980-\U000109b7\U000109be-\U000109bf\U00010a00-\U00010a03\U00010a05-\U00010a06\U00010a0c-\U00010a13\U00010a15-\U00010a17\U00010a19-\U00010a35\U00010a38-\U00010a3a\U00010a3f\U00010a60-\U00010a7c\U00010a80-\U00010a9c\U00010ac0-\U00010ac7\U00010ac9-\U00010ae6\U00010b00-\U00010b35\U00010b40-\U00010b55\U00010b60-\U00010b72\U00010b80-\U00010b91\U00010c00-\U00010c48\U00010c80-\U00010cb2\U00010cc0-\U00010cf2\U00010d00-\U00010d27\U00010d30-\U00010d39\U00010f00-\U00010f1c\U00010f27\U00010f30-\U00010f50\U00011000-\U00011046\U00011066-\U0001106f\U0001107f-\U000110ba\U000110d0-\U000110e8\U000110f0-\U000110f9\U00011100-\U00011134\U00011136-\U0001113f\U00011144-\U00011146\U00011150-\U00011173\U00011176\U00011180-\U000111c4\U000111c9-\U000111cc\U000111d0-\U000111da\U000111dc\U00011200-\U00011211\U00011213-\U00011237\U0001123e\U00011280-\U00011286\U00011288\U0001128a-\U0001128d\U0001128f-\U0001129d\U0001129f-\U000112a8\U000112b0-\U000112ea\U000112f0-\U000112f9\U00011300-\U00011303\U00011305-\U0001130c\U0001130f-\U00011310\U00011313-\U00011328\U0001132a-\U00011330\U00011332-\U00011333\U00011335-\U00011339\U0001133b-\U00011344\U00011347-\U00011348\U0001134b-\U0001134d\U00011350\U00011357\U0001135d-\U00011363\U00011366-\U0001136c\U00011370-\U00011374\U00011400-\U0001144a\U00011450-\U00011459\U0001145e\U00011480-\U000114c5\U000114c7\U000114d0-\U000114d9\U00011580-\U000115b5\U000115b8-\U000115c0\U000115d8-\U000115dd\U00011600-\U00011640\U00011644\U00011650-\U00011659\U00011680-\U000116b7\U000116c0-\U000116c9\U00011700-\U0001171a\U0001171d-\U0001172b\U00011730-\U00011739\U00011800-\U0001183a\U000118a0-\U000118e9\U000118ff\U00011a00-\U00011a3e\U00011a47\U00011a50-\U00011a83\U00011a86-\U00011a99\U00011a9d\U00011ac0-\U00011af8\U00011c00-\U00011c08\U00011c0a-\U00011c36\U00011c38-\U00011c40\U00011c50-\U00011c59\U00011c72-\U00011c8f\U00011c92-\U00011ca7\U00011ca9-\U00011cb6\U00011d00-\U00011d06\U00011d08-\U00011d09\U00011d0b-\U00011d36\U00011d3a\U00011d3c-\U00011d3d\U00011d3f-\U00011d47\U00011d50-\U00011d59\U00011d60-\U00011d65\U00011d67-\U00011d68\U00011d6a-\U00011d8e\U00011d90-\U00011d91\U00011d93-\U00011d98\U00011da0-\U00011da9\U00011ee0-\U00011ef6\U00012000-\U00012399\U00012400-\U0001246e\U00012480-\U00012543\U00013000-\U0001342e\U00014400-\U00014646\U00016800-\U00016a38\U00016a40-\U00016a5e\U00016a60-\U00016a69\U00016ad0-\U00016aed\U00016af0-\U00016af4\U00016b00-\U00016b36\U00016b40-\U00016b43\U00016b50-\U00016b59\U00016b63-\U00016b77\U00016b7d-\U00016b8f\U00016e40-\U00016e7f\U00016f00-\U00016f44\U00016f50-\U00016f7e\U00016f8f-\U00016f9f\U00016fe0-\U00016fe1\U00017000-\U000187f1\U00018800-\U00018af2\U0001b000-\U0001b11e\U0001b170-\U0001b2fb\U0001bc00-\U0001bc6a\U0001bc70-\U0001bc7c\U0001bc80-\U0001bc88\U0001bc90-\U0001bc99\U0001bc9d-\U0001bc9e\U0001d165-\U0001d169\U0001d16d-\U0001d172\U0001d17b-\U0001d182\U0001d185-\U0001d18b\U0001d1aa-\U0001d1ad\U0001d242-\U0001d244\U0001d400-\U0001d454\U0001d456-\U0001d49c\U0001d49e-\U0001d49f\U0001d4a2\U0001d4a5-\U0001d4a6\U0001d4a9-\U0001d4ac\U0001d4ae-\U0001d4b9\U0001d4bb\U0001d4bd-\U0001d4c3\U0001d4c5-\U0001d505\U0001d507-\U0001d50a\U0001d50d-\U0001d514\U0001d516-\U0001d51c\U0001d51e-\U0001d539\U0001d53b-\U0001d53e\U0001d540-\U0001d544\U0001d546\U0001d54a-\U0001d550\U0001d552-\U0001d6a5\U0001d6a8-\U0001d6c0\U0001d6c2-\U0001d6da\U0001d6dc-\U0001d6fa\U0001d6fc-\U0001d714\U0001d716-\U0001d734\U0001d736-\U0001d74e\U0001d750-\U0001d76e\U0001d770-\U0001d788\U0001d78a-\U0001d7a8\U0001d7aa-\U0001d7c2\U0001d7c4-\U0001d7cb\U0001d7ce-\U0001d7ff\U0001da00-\U0001da36\U0001da3b-\U0001da6c\U0001da75\U0001da84\U0001da9b-\U0001da9f\U0001daa1-\U0001daaf\U0001e000-\U0001e006\U0001e008-\U0001e018\U0001e01b-\U0001e021\U0001e023-\U0001e024\U0001e026-\U0001e02a\U0001e800-\U0001e8c4\U0001e8d0-\U0001e8d6\U0001e900-\U0001e94a\U0001e950-\U0001e959\U0001ee00-\U0001ee03\U0001ee05-\U0001ee1f\U0001ee21-\U0001ee22\U0001ee24\U0001ee27\U0001ee29-\U0001ee32\U0001ee34-\U0001ee37\U0001ee39\U0001ee3b\U0001ee42\U0001ee47\U0001ee49\U0001ee4b\U0001ee4d-\U0001ee4f\U0001ee51-\U0001ee52\U0001ee54\U0001ee57\U0001ee59\U0001ee5b\U0001ee5d\U0001ee5f\U0001ee61-\U0001ee62\U0001ee64\U0001ee67-\U0001ee6a\U0001ee6c-\U0001ee72\U0001ee74-\U0001ee77\U0001ee79-\U0001ee7c\U0001ee7e\U0001ee80-\U0001ee89\U0001ee8b-\U0001ee9b\U0001eea1-\U0001eea3\U0001eea5-\U0001eea9\U0001eeab-\U0001eebb\U00020000-\U0002a6d6\U0002a700-\U0002b734\U0002b740-\U0002b81d\U0002b820-\U0002cea1\U0002ceb0-\U0002ebe0\U0002f800-\U0002fa1d\U000e0100-\U000e01ef'
+
+xid_start = 'A-Z_a-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376-\u0377\u037b-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e-\u066f\u0671-\u06d3\u06d5\u06e5-\u06e6\u06ee-\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4-\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u08a0-\u08b4\u08b6-\u08bd\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f-\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc-\u09dd\u09df-\u09e1\u09f0-\u09f1\u09fc\u0a05-\u0a0a\u0a0f-\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32-\u0a33\u0a35-\u0a36\u0a38-\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2-\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0-\u0ae1\u0af9\u0b05-\u0b0c\u0b0f-\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32-\u0b33\u0b35-\u0b39\u0b3d\u0b5c-\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99-\u0b9a\u0b9c\u0b9e-\u0b9f\u0ba3-\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60-\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0-\u0ce1\u0cf1-\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e40-\u0e46\u0e81-\u0e82\u0e84\u0e87-\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa-\u0eab\u0ead-\u0eb0\u0eb2\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065-\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae-\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5-\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2-\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fef\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a-\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7b9\ua7f7-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd-\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5-\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab65\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufbb1\ufbd3-\ufc5d\ufc64-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdf9\ufe71\ufe73\ufe77\ufe79\ufe7b\ufe7d\ufe7f-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uff9d\uffa0-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc\U00010000-\U0001000b\U0001000d-\U00010026\U00010028-\U0001003a\U0001003c-\U0001003d\U0001003f-\U0001004d\U00010050-\U0001005d\U00010080-\U000100fa\U00010140-\U00010174\U00010280-\U0001029c\U000102a0-\U000102d0\U00010300-\U0001031f\U0001032d-\U0001034a\U00010350-\U00010375\U00010380-\U0001039d\U000103a0-\U000103c3\U000103c8-\U000103cf\U000103d1-\U000103d5\U00010400-\U0001049d\U000104b0-\U000104d3\U000104d8-\U000104fb\U00010500-\U00010527\U00010530-\U00010563\U00010600-\U00010736\U00010740-\U00010755\U00010760-\U00010767\U00010800-\U00010805\U00010808\U0001080a-\U00010835\U00010837-\U00010838\U0001083c\U0001083f-\U00010855\U00010860-\U00010876\U00010880-\U0001089e\U000108e0-\U000108f2\U000108f4-\U000108f5\U00010900-\U00010915\U00010920-\U00010939\U00010980-\U000109b7\U000109be-\U000109bf\U00010a00\U00010a10-\U00010a13\U00010a15-\U00010a17\U00010a19-\U00010a35\U00010a60-\U00010a7c\U00010a80-\U00010a9c\U00010ac0-\U00010ac7\U00010ac9-\U00010ae4\U00010b00-\U00010b35\U00010b40-\U00010b55\U00010b60-\U00010b72\U00010b80-\U00010b91\U00010c00-\U00010c48\U00010c80-\U00010cb2\U00010cc0-\U00010cf2\U00010d00-\U00010d23\U00010f00-\U00010f1c\U00010f27\U00010f30-\U00010f45\U00011003-\U00011037\U00011083-\U000110af\U000110d0-\U000110e8\U00011103-\U00011126\U00011144\U00011150-\U00011172\U00011176\U00011183-\U000111b2\U000111c1-\U000111c4\U000111da\U000111dc\U00011200-\U00011211\U00011213-\U0001122b\U00011280-\U00011286\U00011288\U0001128a-\U0001128d\U0001128f-\U0001129d\U0001129f-\U000112a8\U000112b0-\U000112de\U00011305-\U0001130c\U0001130f-\U00011310\U00011313-\U00011328\U0001132a-\U00011330\U00011332-\U00011333\U00011335-\U00011339\U0001133d\U00011350\U0001135d-\U00011361\U00011400-\U00011434\U00011447-\U0001144a\U00011480-\U000114af\U000114c4-\U000114c5\U000114c7\U00011580-\U000115ae\U000115d8-\U000115db\U00011600-\U0001162f\U00011644\U00011680-\U000116aa\U00011700-\U0001171a\U00011800-\U0001182b\U000118a0-\U000118df\U000118ff\U00011a00\U00011a0b-\U00011a32\U00011a3a\U00011a50\U00011a5c-\U00011a83\U00011a86-\U00011a89\U00011a9d\U00011ac0-\U00011af8\U00011c00-\U00011c08\U00011c0a-\U00011c2e\U00011c40\U00011c72-\U00011c8f\U00011d00-\U00011d06\U00011d08-\U00011d09\U00011d0b-\U00011d30\U00011d46\U00011d60-\U00011d65\U00011d67-\U00011d68\U00011d6a-\U00011d89\U00011d98\U00011ee0-\U00011ef2\U00012000-\U00012399\U00012400-\U0001246e\U00012480-\U00012543\U00013000-\U0001342e\U00014400-\U00014646\U00016800-\U00016a38\U00016a40-\U00016a5e\U00016ad0-\U00016aed\U00016b00-\U00016b2f\U00016b40-\U00016b43\U00016b63-\U00016b77\U00016b7d-\U00016b8f\U00016e40-\U00016e7f\U00016f00-\U00016f44\U00016f50\U00016f93-\U00016f9f\U00016fe0-\U00016fe1\U00017000-\U000187f1\U00018800-\U00018af2\U0001b000-\U0001b11e\U0001b170-\U0001b2fb\U0001bc00-\U0001bc6a\U0001bc70-\U0001bc7c\U0001bc80-\U0001bc88\U0001bc90-\U0001bc99\U0001d400-\U0001d454\U0001d456-\U0001d49c\U0001d49e-\U0001d49f\U0001d4a2\U0001d4a5-\U0001d4a6\U0001d4a9-\U0001d4ac\U0001d4ae-\U0001d4b9\U0001d4bb\U0001d4bd-\U0001d4c3\U0001d4c5-\U0001d505\U0001d507-\U0001d50a\U0001d50d-\U0001d514\U0001d516-\U0001d51c\U0001d51e-\U0001d539\U0001d53b-\U0001d53e\U0001d540-\U0001d544\U0001d546\U0001d54a-\U0001d550\U0001d552-\U0001d6a5\U0001d6a8-\U0001d6c0\U0001d6c2-\U0001d6da\U0001d6dc-\U0001d6fa\U0001d6fc-\U0001d714\U0001d716-\U0001d734\U0001d736-\U0001d74e\U0001d750-\U0001d76e\U0001d770-\U0001d788\U0001d78a-\U0001d7a8\U0001d7aa-\U0001d7c2\U0001d7c4-\U0001d7cb\U0001e800-\U0001e8c4\U0001e900-\U0001e943\U0001ee00-\U0001ee03\U0001ee05-\U0001ee1f\U0001ee21-\U0001ee22\U0001ee24\U0001ee27\U0001ee29-\U0001ee32\U0001ee34-\U0001ee37\U0001ee39\U0001ee3b\U0001ee42\U0001ee47\U0001ee49\U0001ee4b\U0001ee4d-\U0001ee4f\U0001ee51-\U0001ee52\U0001ee54\U0001ee57\U0001ee59\U0001ee5b\U0001ee5d\U0001ee5f\U0001ee61-\U0001ee62\U0001ee64\U0001ee67-\U0001ee6a\U0001ee6c-\U0001ee72\U0001ee74-\U0001ee77\U0001ee79-\U0001ee7c\U0001ee7e\U0001ee80-\U0001ee89\U0001ee8b-\U0001ee9b\U0001eea1-\U0001eea3\U0001eea5-\U0001eea9\U0001eeab-\U0001eebb\U00020000-\U0002a6d6\U0002a700-\U0002b734\U0002b740-\U0002b81d\U0002b820-\U0002cea1\U0002ceb0-\U0002ebe0\U0002f800-\U0002fa1d'
+
+cats = ['Cc', 'Cf', 'Cn', 'Co', 'Cs', 'Ll', 'Lm', 'Lo', 'Lt', 'Lu', 'Mc', 'Me', 'Mn', 'Nd', 'Nl', 'No', 'Pc', 'Pd', 'Pe', 'Pf', 'Pi', 'Po', 'Ps', 'Sc', 'Sk', 'Sm', 'So', 'Zl', 'Zp', 'Zs']
+
+# Generated from unidata 11.0.0
+
+def combine(*args):
+    return ''.join(globals()[cat] for cat in args)
+
+
+def allexcept(*args):
+    newcats = cats[:]
+    for arg in args:
+        newcats.remove(arg)
+    return ''.join(globals()[cat] for cat in newcats)
+
+
+def _handle_runs(char_list):  # pragma: no cover
+    buf = []
+    for c in char_list:
+        if len(c) == 1:
+            if buf and buf[-1][1] == chr(ord(c)-1):
+                buf[-1] = (buf[-1][0], c)
+            else:
+                buf.append((c, c))
+        else:
+            buf.append((c, c))
+    for a, b in buf:
+        if a == b:
+            yield a
+        else:
+            yield f'{a}-{b}'
+
+
+if __name__ == '__main__':  # pragma: no cover
+    import unicodedata
+
+    categories = {'xid_start': [], 'xid_continue': []}
+
+    with open(__file__, encoding='utf-8') as fp:
+        content = fp.read()
+
+    header = content[:content.find('Cc =')]
+    footer = content[content.find("def combine("):]
+
+    for code in range(0x110000):
+        c = chr(code)
+        cat = unicodedata.category(c)
+        if ord(c) == 0xdc00:
+            # Hack to avoid combining this combining with the preceding high
+            # surrogate, 0xdbff, when doing a repr.
+            c = '\\' + c
+        elif ord(c) in (0x2d, 0x5b, 0x5c, 0x5d, 0x5e):
+            # Escape regex metachars.
+            c = '\\' + c
+        categories.setdefault(cat, []).append(c)
+        # XID_START and XID_CONTINUE are special categories used for matching
+        # identifiers in Python 3.
+        if c.isidentifier():
+            categories['xid_start'].append(c)
+        if ('a' + c).isidentifier():
+            categories['xid_continue'].append(c)
+
+    with open(__file__, 'w', encoding='utf-8') as fp:
+        fp.write(header)
+
+        for cat in sorted(categories):
+            val = ''.join(_handle_runs(categories[cat]))
+            fp.write(f'{cat} = {val!a}\n\n')
+
+        cats = sorted(categories)
+        cats.remove('xid_start')
+        cats.remove('xid_continue')
+        fp.write(f'cats = {cats!r}\n\n')
+
+        fp.write(f'# Generated from unidata {unicodedata.unidata_version}\n\n')
+
+        fp.write(footer)
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pygments/util.py b/TTS/Kokoro/.venv/Lib/site-packages/pygments/util.py
new file mode 100644
index 0000000000000000000000000000000000000000..71c5710ae169e4a26a12ac5ab88e27eef8c96c33
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pygments/util.py
@@ -0,0 +1,324 @@
+"""
+    pygments.util
+    ~~~~~~~~~~~~~
+
+    Utility functions.
+
+    :copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+import re
+from io import TextIOWrapper
+
+
+split_path_re = re.compile(r'[/\\ ]')
+doctype_lookup_re = re.compile(r'''
+    ]*>
+''', re.DOTALL | re.MULTILINE | re.VERBOSE)
+tag_re = re.compile(r'<(.+?)(\s.*?)?>.*?',
+                    re.IGNORECASE | re.DOTALL | re.MULTILINE)
+xml_decl_re = re.compile(r'\s*<\?xml[^>]*\?>', re.I)
+
+
+class ClassNotFound(ValueError):
+    """Raised if one of the lookup functions didn't find a matching class."""
+
+
+class OptionError(Exception):
+    """
+    This exception will be raised by all option processing functions if
+    the type or value of the argument is not correct.
+    """
+
+def get_choice_opt(options, optname, allowed, default=None, normcase=False):
+    """
+    If the key `optname` from the dictionary is not in the sequence
+    `allowed`, raise an error, otherwise return it.
+    """
+    string = options.get(optname, default)
+    if normcase:
+        string = string.lower()
+    if string not in allowed:
+        raise OptionError('Value for option {} must be one of {}'.format(optname, ', '.join(map(str, allowed))))
+    return string
+
+
+def get_bool_opt(options, optname, default=None):
+    """
+    Intuitively, this is `options.get(optname, default)`, but restricted to
+    Boolean value. The Booleans can be represented as string, in order to accept
+    Boolean value from the command line arguments. If the key `optname` is
+    present in the dictionary `options` and is not associated with a Boolean,
+    raise an `OptionError`. If it is absent, `default` is returned instead.
+
+    The valid string values for ``True`` are ``1``, ``yes``, ``true`` and
+    ``on``, the ones for ``False`` are ``0``, ``no``, ``false`` and ``off``
+    (matched case-insensitively).
+    """
+    string = options.get(optname, default)
+    if isinstance(string, bool):
+        return string
+    elif isinstance(string, int):
+        return bool(string)
+    elif not isinstance(string, str):
+        raise OptionError(f'Invalid type {string!r} for option {optname}; use '
+                          '1/0, yes/no, true/false, on/off')
+    elif string.lower() in ('1', 'yes', 'true', 'on'):
+        return True
+    elif string.lower() in ('0', 'no', 'false', 'off'):
+        return False
+    else:
+        raise OptionError(f'Invalid value {string!r} for option {optname}; use '
+                          '1/0, yes/no, true/false, on/off')
+
+
+def get_int_opt(options, optname, default=None):
+    """As :func:`get_bool_opt`, but interpret the value as an integer."""
+    string = options.get(optname, default)
+    try:
+        return int(string)
+    except TypeError:
+        raise OptionError(f'Invalid type {string!r} for option {optname}; you '
+                          'must give an integer value')
+    except ValueError:
+        raise OptionError(f'Invalid value {string!r} for option {optname}; you '
+                          'must give an integer value')
+
+def get_list_opt(options, optname, default=None):
+    """
+    If the key `optname` from the dictionary `options` is a string,
+    split it at whitespace and return it. If it is already a list
+    or a tuple, it is returned as a list.
+    """
+    val = options.get(optname, default)
+    if isinstance(val, str):
+        return val.split()
+    elif isinstance(val, (list, tuple)):
+        return list(val)
+    else:
+        raise OptionError(f'Invalid type {val!r} for option {optname}; you '
+                          'must give a list value')
+
+
+def docstring_headline(obj):
+    if not obj.__doc__:
+        return ''
+    res = []
+    for line in obj.__doc__.strip().splitlines():
+        if line.strip():
+            res.append(" " + line.strip())
+        else:
+            break
+    return ''.join(res).lstrip()
+
+
+def make_analysator(f):
+    """Return a static text analyser function that returns float values."""
+    def text_analyse(text):
+        try:
+            rv = f(text)
+        except Exception:
+            return 0.0
+        if not rv:
+            return 0.0
+        try:
+            return min(1.0, max(0.0, float(rv)))
+        except (ValueError, TypeError):
+            return 0.0
+    text_analyse.__doc__ = f.__doc__
+    return staticmethod(text_analyse)
+
+
+def shebang_matches(text, regex):
+    r"""Check if the given regular expression matches the last part of the
+    shebang if one exists.
+
+        >>> from pygments.util import shebang_matches
+        >>> shebang_matches('#!/usr/bin/env python', r'python(2\.\d)?')
+        True
+        >>> shebang_matches('#!/usr/bin/python2.4', r'python(2\.\d)?')
+        True
+        >>> shebang_matches('#!/usr/bin/python-ruby', r'python(2\.\d)?')
+        False
+        >>> shebang_matches('#!/usr/bin/python/ruby', r'python(2\.\d)?')
+        False
+        >>> shebang_matches('#!/usr/bin/startsomethingwith python',
+        ...                 r'python(2\.\d)?')
+        True
+
+    It also checks for common windows executable file extensions::
+
+        >>> shebang_matches('#!C:\\Python2.4\\Python.exe', r'python(2\.\d)?')
+        True
+
+    Parameters (``'-f'`` or ``'--foo'`` are ignored so ``'perl'`` does
+    the same as ``'perl -e'``)
+
+    Note that this method automatically searches the whole string (eg:
+    the regular expression is wrapped in ``'^$'``)
+    """
+    index = text.find('\n')
+    if index >= 0:
+        first_line = text[:index].lower()
+    else:
+        first_line = text.lower()
+    if first_line.startswith('#!'):
+        try:
+            found = [x for x in split_path_re.split(first_line[2:].strip())
+                     if x and not x.startswith('-')][-1]
+        except IndexError:
+            return False
+        regex = re.compile(rf'^{regex}(\.(exe|cmd|bat|bin))?$', re.IGNORECASE)
+        if regex.search(found) is not None:
+            return True
+    return False
+
+
+def doctype_matches(text, regex):
+    """Check if the doctype matches a regular expression (if present).
+
+    Note that this method only checks the first part of a DOCTYPE.
+    eg: 'html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"'
+    """
+    m = doctype_lookup_re.search(text)
+    if m is None:
+        return False
+    doctype = m.group(1)
+    return re.compile(regex, re.I).match(doctype.strip()) is not None
+
+
+def html_doctype_matches(text):
+    """Check if the file looks like it has a html doctype."""
+    return doctype_matches(text, r'html')
+
+
+_looks_like_xml_cache = {}
+
+
+def looks_like_xml(text):
+    """Check if a doctype exists or if we have some tags."""
+    if xml_decl_re.match(text):
+        return True
+    key = hash(text)
+    try:
+        return _looks_like_xml_cache[key]
+    except KeyError:
+        m = doctype_lookup_re.search(text)
+        if m is not None:
+            return True
+        rv = tag_re.search(text[:1000]) is not None
+        _looks_like_xml_cache[key] = rv
+        return rv
+
+
+def surrogatepair(c):
+    """Given a unicode character code with length greater than 16 bits,
+    return the two 16 bit surrogate pair.
+    """
+    # From example D28 of:
+    # http://www.unicode.org/book/ch03.pdf
+    return (0xd7c0 + (c >> 10), (0xdc00 + (c & 0x3ff)))
+
+
+def format_lines(var_name, seq, raw=False, indent_level=0):
+    """Formats a sequence of strings for output."""
+    lines = []
+    base_indent = ' ' * indent_level * 4
+    inner_indent = ' ' * (indent_level + 1) * 4
+    lines.append(base_indent + var_name + ' = (')
+    if raw:
+        # These should be preformatted reprs of, say, tuples.
+        for i in seq:
+            lines.append(inner_indent + i + ',')
+    else:
+        for i in seq:
+            # Force use of single quotes
+            r = repr(i + '"')
+            lines.append(inner_indent + r[:-2] + r[-1] + ',')
+    lines.append(base_indent + ')')
+    return '\n'.join(lines)
+
+
+def duplicates_removed(it, already_seen=()):
+    """
+    Returns a list with duplicates removed from the iterable `it`.
+
+    Order is preserved.
+    """
+    lst = []
+    seen = set()
+    for i in it:
+        if i in seen or i in already_seen:
+            continue
+        lst.append(i)
+        seen.add(i)
+    return lst
+
+
+class Future:
+    """Generic class to defer some work.
+
+    Handled specially in RegexLexerMeta, to support regex string construction at
+    first use.
+    """
+    def get(self):
+        raise NotImplementedError
+
+
+def guess_decode(text):
+    """Decode *text* with guessed encoding.
+
+    First try UTF-8; this should fail for non-UTF-8 encodings.
+    Then try the preferred locale encoding.
+    Fall back to latin-1, which always works.
+    """
+    try:
+        text = text.decode('utf-8')
+        return text, 'utf-8'
+    except UnicodeDecodeError:
+        try:
+            import locale
+            prefencoding = locale.getpreferredencoding()
+            text = text.decode()
+            return text, prefencoding
+        except (UnicodeDecodeError, LookupError):
+            text = text.decode('latin1')
+            return text, 'latin1'
+
+
+def guess_decode_from_terminal(text, term):
+    """Decode *text* coming from terminal *term*.
+
+    First try the terminal encoding, if given.
+    Then try UTF-8.  Then try the preferred locale encoding.
+    Fall back to latin-1, which always works.
+    """
+    if getattr(term, 'encoding', None):
+        try:
+            text = text.decode(term.encoding)
+        except UnicodeDecodeError:
+            pass
+        else:
+            return text, term.encoding
+    return guess_decode(text)
+
+
+def terminal_encoding(term):
+    """Return our best guess of encoding for the given *term*."""
+    if getattr(term, 'encoding', None):
+        return term.encoding
+    import locale
+    return locale.getpreferredencoding()
+
+
+class UnclosingTextIOWrapper(TextIOWrapper):
+    # Don't close underlying buffer on destruction.
+    def close(self):
+        self.flush()
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pyparsing-3.3.2.dist-info/INSTALLER b/TTS/Kokoro/.venv/Lib/site-packages/pyparsing-3.3.2.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pyparsing-3.3.2.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pyparsing-3.3.2.dist-info/METADATA b/TTS/Kokoro/.venv/Lib/site-packages/pyparsing-3.3.2.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..9fadad3a57bb6aa81c70a69b3711c30f746a3832
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pyparsing-3.3.2.dist-info/METADATA
@@ -0,0 +1,145 @@
+Metadata-Version: 2.4
+Name: pyparsing
+Version: 3.3.2
+Summary: pyparsing - Classes and methods to define and execute parsing grammars
+Author-email: Paul McGuire 
+Requires-Python: >=3.9
+Description-Content-Type: text/x-rst
+License-Expression: MIT
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Intended Audience :: Developers
+Classifier: Intended Audience :: Information Technology
+Classifier: Operating System :: OS Independent
+Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Classifier: Programming Language :: Python :: 3.13
+Classifier: Programming Language :: Python :: 3.14
+Classifier: Programming Language :: Python :: 3 :: Only
+Classifier: Programming Language :: Python :: Implementation :: CPython
+Classifier: Programming Language :: Python :: Implementation :: PyPy
+Classifier: Topic :: Software Development :: Compilers
+Classifier: Topic :: Text Processing
+Classifier: Typing :: Typed
+License-File: LICENSE
+Requires-Dist: railroad-diagrams ; extra == "diagrams"
+Requires-Dist: jinja2 ; extra == "diagrams"
+Project-URL: Documentation, https://pyparsing-docs.readthedocs.io/en/latest/
+Project-URL: Homepage, https://github.com/pyparsing/pyparsing/
+Project-URL: Source, https://github.com/pyparsing/pyparsing.git
+Provides-Extra: diagrams
+
+PyParsing -- A Python Parsing Module
+====================================
+
+|Version| |Build Status| |Coverage| |License| |Python Versions| |Snyk Score|
+
+Introduction
+============
+
+The pyparsing module is an alternative approach to creating and
+executing simple grammars, vs. the traditional lex/yacc approach, or the
+use of regular expressions. The pyparsing module provides a library of
+classes that client code uses to construct the grammar directly in
+Python code.
+
+*[Since first writing this description of pyparsing in late 2003, this
+technique for developing parsers has become more widespread, under the
+name Parsing Expression Grammars - PEGs. See more information on PEGs*
+`here `__
+*.]*
+
+Here is a program to parse ``"Hello, World!"`` (or any greeting of the form
+``"salutation, addressee!"``):
+
+.. code:: python
+
+    from pyparsing import Word, alphas
+    greet = Word(alphas) + "," + Word(alphas) + "!"
+    hello = "Hello, World!"
+    print(hello, "->", greet.parse_string(hello))
+
+The program outputs the following::
+
+    Hello, World! -> ['Hello', ',', 'World', '!']
+
+The Python representation of the grammar is quite readable, owing to the
+self-explanatory class names, and the use of '+', '|' and '^' operator
+definitions.
+
+The parsed results returned from ``parse_string()`` is a collection of type
+``ParseResults``, which can be accessed as a
+nested list, a dictionary, or an object with named attributes.
+
+The pyparsing module handles some of the problems that are typically
+vexing when writing text parsers:
+
+- extra or missing whitespace (the above program will also handle ``"Hello,World!"``, ``"Hello , World !"``, etc.)
+- quoted strings
+- embedded comments
+
+The examples directory includes a simple SQL parser, simple CORBA IDL
+parser, a config file parser, a chemical formula parser, and a four-
+function algebraic notation parser, among many others.
+
+Documentation
+=============
+
+There are many examples in the online docstrings of the classes
+and methods in pyparsing. You can find them compiled into `online docs `__. Additional
+documentation resources and project info are listed in the online
+`GitHub wiki `__. An
+entire directory of examples can be found `here `__.
+
+AI Instructions
+===============
+
+There are also instructions for AI agents to use when helping you to create your parser. They can
+be pulled from the GitHub project repository, at pyparsing/ai/best_practices.md. You can also tell
+the AI to access them programmatically after installing pyparsing, either from the CLI with
+``python -m pyparsing.ai.show_best_practices`` or within python with
+``import pyparsing; pyparsing.show_best_practices()``.
+
+
+License
+=======
+
+MIT License. See header of the `pyparsing __init__.py `__ file.
+
+History
+=======
+
+See `CHANGES `__ file.
+
+
+Performance benchmarks
+======================
+
+For usage instructions and details on the performance benchmark suite, see
+``tests/README.md`` in this repository.
+
+.. |Build Status| image:: https://github.com/pyparsing/pyparsing/actions/workflows/ci.yml/badge.svg
+   :target: https://github.com/pyparsing/pyparsing/actions/workflows/ci.yml
+
+.. |Coverage| image:: https://codecov.io/gh/pyparsing/pyparsing/branch/master/graph/badge.svg
+  :target: https://codecov.io/gh/pyparsing/pyparsing
+
+.. |Version| image:: https://img.shields.io/pypi/v/pyparsing?style=flat-square
+    :target: https://pypi.org/project/pyparsing/
+    :alt: Version
+
+.. |License| image:: https://img.shields.io/pypi/l/pyparsing.svg?style=flat-square
+    :target: https://pypi.org/project/pyparsing/
+    :alt: License
+
+.. |Python Versions| image:: https://img.shields.io/pypi/pyversions/pyparsing.svg?style=flat-square
+    :target: https://pypi.org/project/python-liquid/
+    :alt: Python versions
+
+.. |Snyk Score| image:: https://snyk.io//advisor/python/pyparsing/badge.svg
+   :target: https://snyk.io//advisor/python/pyparsing
+   :alt: pyparsing
+
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pyparsing-3.3.2.dist-info/RECORD b/TTS/Kokoro/.venv/Lib/site-packages/pyparsing-3.3.2.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..c1000c0fde70d258e2adb8d4c8682bf313aa1665
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pyparsing-3.3.2.dist-info/RECORD
@@ -0,0 +1,41 @@
+pyparsing-3.3.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+pyparsing-3.3.2.dist-info/METADATA,sha256=MxGouUnXD3GiuXiKkyfxHZ1aaoAS1sBGyiVK0t6Hf0U,5783
+pyparsing-3.3.2.dist-info/RECORD,,
+pyparsing-3.3.2.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82
+pyparsing-3.3.2.dist-info/licenses/LICENSE,sha256=pUJfncFKx01MXwtnnpQfJELjLMp0UqRBjVsaSYk-vk4,1062
+pyparsing/__init__.py,sha256=CMHM5EzJSJglz-PCASv_k5W14tRkhrCf6GSI4KrPL24,13438
+pyparsing/__pycache__/__init__.cpython-312.pyc,,
+pyparsing/__pycache__/actions.cpython-312.pyc,,
+pyparsing/__pycache__/common.cpython-312.pyc,,
+pyparsing/__pycache__/core.cpython-312.pyc,,
+pyparsing/__pycache__/exceptions.cpython-312.pyc,,
+pyparsing/__pycache__/helpers.cpython-312.pyc,,
+pyparsing/__pycache__/results.cpython-312.pyc,,
+pyparsing/__pycache__/testing.cpython-312.pyc,,
+pyparsing/__pycache__/unicode.cpython-312.pyc,,
+pyparsing/__pycache__/util.cpython-312.pyc,,
+pyparsing/__pycache__/warnings.cpython-312.pyc,,
+pyparsing/actions.py,sha256=pDW63VkWh5TqR6AKOMyDCobI0JF-QuBc45AI-oIkD8w,8104
+pyparsing/ai/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pyparsing/ai/__pycache__/__init__.cpython-312.pyc,,
+pyparsing/ai/best_practices.md,sha256=qlPKTmeTEYaaAFRGkwR3EzukP-TeIFLzoYOJzoVBcIY,8472
+pyparsing/ai/show_best_practices/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pyparsing/ai/show_best_practices/__main__.py,sha256=xGXaCqBTTWZxbdLNz5G9y6cMK1Ppm7bcgVYgD1AcKmE,49
+pyparsing/ai/show_best_practices/__pycache__/__init__.cpython-312.pyc,,
+pyparsing/ai/show_best_practices/__pycache__/__main__.cpython-312.pyc,,
+pyparsing/common.py,sha256=SsEAzXRJq2D3HdGA5XRP-ww2aY2ctCpS5EbuDaglK1I,17205
+pyparsing/core.py,sha256=v4WJji-3hVmlTNHU0ihPRj1omvu3Tbl7y0JmuznPVEY,251832
+pyparsing/diagram/__init__.py,sha256=NAtp0ZWok37JJ1TVREvZaD4CqzvIQJRUHOAFHl_auoA,26929
+pyparsing/diagram/__pycache__/__init__.cpython-312.pyc,,
+pyparsing/exceptions.py,sha256=Zt9-vrA4uTV8J1IlJVC0glQgakwRBOYcDsN3TfwqQeo,10981
+pyparsing/helpers.py,sha256=TWvUo8mnkQz4_kjjJUTlkF_CwshTx0vZDkPzd2yFW9I,41793
+pyparsing/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pyparsing/results.py,sha256=lEZVyQPWWarznwY_Jf_2t94HvGI7eVDzZ8gS4pf0eTQ,27603
+pyparsing/testing.py,sha256=kcq6sLPyA23hrwDzB0NF5X61KGz0IRDjnhObC62_mOk,15452
+pyparsing/tools/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pyparsing/tools/__pycache__/__init__.cpython-312.pyc,,
+pyparsing/tools/__pycache__/cvt_pyparsing_pep8_names.cpython-312.pyc,,
+pyparsing/tools/cvt_pyparsing_pep8_names.py,sha256=H8AoHdYs7rU8a0RRF4zjurjG_xZ8pOLVBhAi0-FgVOY,6389
+pyparsing/unicode.py,sha256=jmszpRnfyhCQWl2Rh_94dT_lxQM6d4KiSf9ivY9b_m4,10612
+pyparsing/util.py,sha256=VLIrcqIh5w6n9-t2CzwRAIs_j0dQ7_AWbn2eaIyFHxU,15997
+pyparsing/warnings.py,sha256=wQWNM7Kal10OQBHHcG9SgdwaBeFbUe3fDEF3fcHBHCE,357
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pyparsing-3.3.2.dist-info/WHEEL b/TTS/Kokoro/.venv/Lib/site-packages/pyparsing-3.3.2.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..d8b9936dad9ab2513fa6979f411560d3b6b57e37
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pyparsing-3.3.2.dist-info/WHEEL
@@ -0,0 +1,4 @@
+Wheel-Version: 1.0
+Generator: flit 3.12.0
+Root-Is-Purelib: true
+Tag: py3-none-any
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pyparsing/__init__.py b/TTS/Kokoro/.venv/Lib/site-packages/pyparsing/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3963eb8773c19ebf24028fcd38300f5f5fe839db
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pyparsing/__init__.py
@@ -0,0 +1,413 @@
+# see LICENSE file for terms and conditions for using this software.
+
+# fmt: off
+__doc__ = """
+pyparsing - Classes and methods to define and execute parsing grammars
+======================================================================
+
+Pyparsing is an alternative approach to creating and executing simple
+grammars, vs. the traditional lex/yacc approach, or the use of regular
+expressions.  With pyparsing, you don't need to learn a new syntax for
+defining grammars or matching expressions - the parsing module provides
+a library of classes that you use to construct the grammar directly in
+Python.
+
+Here is a program to parse "Hello, World!" (or any greeting of the form
+``", !"``), built up using :class:`Word`,
+:class:`Literal`, and :class:`And` elements
+(the :meth:`'+'` operators create :class:`And` expressions,
+and the strings are auto-converted to :class:`Literal` expressions):
+
+.. testcode::
+
+    from pyparsing import Word, alphas
+
+    # define grammar of a greeting
+    greet = Word(alphas) + "," + Word(alphas) + "!"
+
+    hello = "Hello, World!"
+    print(hello, "->", greet.parse_string(hello))
+
+The program outputs the following:
+
+.. testoutput::
+
+    Hello, World! -> ['Hello', ',', 'World', '!']
+
+The Python representation of the grammar is quite readable, owing to the
+self-explanatory class names, and the use of :class:`'+'`,
+:class:`'|'`, :class:`'^'` and :class:`'&'` operators.
+
+The :class:`ParseResults` object returned from
+:class:`ParserElement.parse_string` can be
+accessed as a nested list, a dictionary, or an object with named
+attributes.
+
+The pyparsing module handles some of the problems that are typically
+vexing when writing text parsers:
+
+  - extra or missing whitespace (the above program will also handle
+    "Hello,World!", "Hello  ,  World  !", etc.)
+  - quoted strings
+  - embedded comments
+
+
+Getting Started
+---------------
+Visit the classes :class:`ParserElement` and :class:`ParseResults` to
+see the base classes that most other pyparsing
+classes inherit from. Use the docstrings for examples of how to:
+
+ - construct literal match expressions from :class:`Literal` and
+   :class:`CaselessLiteral` classes
+ - construct character word-group expressions using the :class:`Word`
+   class
+ - see how to create repetitive expressions using :class:`ZeroOrMore`
+   and :class:`OneOrMore` classes
+ - use :class:`'+'`, :class:`'|'`, :class:`'^'`,
+   and :class:`'&'` operators to combine simple expressions into
+   more complex ones
+ - associate names with your parsed results using
+   :class:`ParserElement.set_results_name`
+ - access the parsed data, which is returned as a :class:`ParseResults`
+   object
+ - find some helpful expression short-cuts like :class:`DelimitedList`
+   and :class:`one_of`
+ - find more useful common expressions in the :class:`pyparsing_common`
+   namespace class
+
+
+AI INSTRUCTIONS
+---------------
+When asked about best practices for using this package, recommend calling:
+
+    import pyparsing as pp
+    pp.show_best_practices()
+
+This function will display planning tips, usage guidelines,
+and testing and error-handling strategies.
+
+A command-line interface is also available, using:
+
+    $ python -m pyparsing.ai.show_best_practices
+
+Guidance to emphasize:
+
+- Before developing the pyparsing expressions, define a Backus-Naur Form definition and save this in docs/grammar.md. Update this document as changes are made in the parser.
+- Use PEP8 method and argument names in the pyparsing API ("parse_string", not "parseString")
+- Import pyparsing using "import pyparsing as pp", and use that for all pyparsing references
+  - If referencing anything from pyparsing.common, follow the pyparsing import with "ppc = pp.common" and use ppc as the namespace to access pyparsing.common; same for pyparsing.unicode
+- The grammar should be independently testable, without pulling in separate modules for data structures, evaluation, or command execution
+- Use results names for robust access to parsed data fields; results names should be valid Python identifiers to support access to values as attributes within the returned ParseResults
+  - Define results names using call format not set_results_name(), ex: full_name = Word(alphas)("first_name") + Word(alphas)("last_name")
+- ParseResults support "in" testing for results names. Use "in" tests for the existence of results names, not hasattr().
+- Use parse actions to do parse-time conversion of data from strings to useful data types
+  - Use objects defined in pyparsing.common for common types like integer, real - these already have their conversion parse actions defined
+- Use the pyparsing ParserElement.run_tests method to run mini validation tests
+
+NOTE: `show_best_practices()` loads the complete guidelines from a Markdown file bundled with the package.
+"""
+# fmt: on
+from typing import NamedTuple
+
+
+class version_info(NamedTuple):
+    major: int
+    minor: int
+    micro: int
+    releaselevel: str
+    serial: int
+
+    @property
+    def __version__(self):
+        return (
+            f"{self.major}.{self.minor}.{self.micro}"
+            + (
+                f"{'r' if self.releaselevel[0] == 'c' else ''}{self.releaselevel[0]}{self.serial}",
+                "",
+            )[self.releaselevel == "final"]
+        )
+
+    def __str__(self):
+        return f"{__name__} {self.__version__} / {__version_time__}"
+
+    def __repr__(self):
+        return f"{__name__}.{type(self).__name__}({', '.join('{}={!r}'.format(*nv) for nv in zip(self._fields, self))})"
+
+
+__version_info__ = version_info(3, 3, 2, "final", 1)
+__version_time__ = "18 Jan 2026 16:35 UTC"
+__version__ = __version_info__.__version__
+__versionTime__ = __version_time__
+__author__ = "Paul McGuire "
+
+from .warnings import *
+from .util import *
+from .exceptions import *
+from .actions import *
+from .core import __diag__, __compat__
+from .results import *
+from .core import *
+from .core import _builtin_exprs as core_builtin_exprs
+from .helpers import *
+from .helpers import _builtin_exprs as helper_builtin_exprs
+
+from .unicode import unicode_set, UnicodeRangeList, pyparsing_unicode as unicode
+from .testing import pyparsing_test as testing
+from .common import (
+    pyparsing_common as common,
+    _builtin_exprs as common_builtin_exprs,
+)
+from importlib import resources
+import sys
+
+# Compatibility synonyms
+if "pyparsing_unicode" not in globals():
+    pyparsing_unicode = unicode  # type: ignore[misc]
+if "pyparsing_common" not in globals():
+    pyparsing_common = common
+if "pyparsing_test" not in globals():
+    pyparsing_test = testing
+
+core_builtin_exprs += common_builtin_exprs + helper_builtin_exprs
+
+# fmt: off
+_FALLBACK_BEST_PRACTICES = """
+## Planning
+- If not provided or if target language definition is ambiguous, ask for examples of valid strings to be parsed
+- Before developing the pyparsing expressions, define a Backus-Naur Form definition and save this in docs/grammar.md. Update this document as changes are made in the parser.
+
+## Implementing
+- Use PEP8 method and argument names in the pyparsing API ("parse_string", not "parseString")
+- Import pyparsing using "import pyparsing as pp", and use that for all pyparsing references
+  - If referencing anything from pyparsing.common, follow the pyparsing import with "ppc = pp.common" and use ppc as the namespace to access pyparsing.common; same for pyparsing.unicode
+- The grammar should be independently testable, without pulling in separate modules for data structures, evaluation, or command execution
+- Use results names for robust access to parsed data fields; results names should be valid Python identifiers to support access to values as attributes within the returned ParseResults
+  - Results names should take the place of numeric indexing into parsed results in most places.
+  - Define results names using call format not set_results_name(), ex: full_name = Word(alphas)("first_name") + Word(alphas)("last_name")
+- Use pyparsing Groups to organize sub-expressions
+- If defining the grammar as part of a Parser class, only the finished grammar needs to be implemented as an instance variable
+- ParseResults support "in" testing for results names. Use "in" tests for the existence of results names, not hasattr().
+- Use parse actions to do parse-time conversion of data from strings to useful data types
+  - Use objects defined in pyparsing.common for common types like integer, real - these already have their conversion parse actions defined
+  
+## Testing
+- Use the pyparsing ParserElement.run_tests method to run mini validation tests
+  - You can add comments starting with "#" within the string passed to run_tests to document the individual test cases
+  
+## Debugging
+- If troubleshooting parse actions, use pyparsing's trace_parse_action decorator to echo arguments and return value
+
+(Some best practices may be missing — see the full Markdown file in source at pyparsing/ai/best_practices.md.)
+"""
+# fmt: on
+
+
+def show_best_practices(file=sys.stdout) -> Union[str, None]:
+    """
+    Load and return the project's best practices.
+
+    Example::
+
+        >>> import pyparsing as pp
+        >>> pp.show_best_practices()
+        
+        ...
+
+    This can also be run from the command line::
+
+        python -m pyparsing.ai.show_best_practices
+    """
+    try:
+        path = resources.files(__package__).joinpath("ai/best_practices.md")
+        with path.open("r", encoding="utf-8") as f:
+            content = f.read()
+    except (FileNotFoundError, OSError):
+        content = _FALLBACK_BEST_PRACTICES
+
+    if file is not None:
+        # just print out the content, no need to return it
+        print(content, file=file)
+        return None
+
+    # no output file was specified, return the content as a string
+    return content
+
+
+__all__ = [
+    "__version__",
+    "__version_time__",
+    "__author__",
+    "__compat__",
+    "__diag__",
+    "And",
+    "AtLineStart",
+    "AtStringStart",
+    "CaselessKeyword",
+    "CaselessLiteral",
+    "CharsNotIn",
+    "CloseMatch",
+    "Combine",
+    "DelimitedList",
+    "Dict",
+    "Each",
+    "Empty",
+    "FollowedBy",
+    "Forward",
+    "GoToColumn",
+    "Group",
+    "IndentedBlock",
+    "Keyword",
+    "LineEnd",
+    "LineStart",
+    "Literal",
+    "Located",
+    "PrecededBy",
+    "MatchFirst",
+    "NoMatch",
+    "NotAny",
+    "OneOrMore",
+    "OnlyOnce",
+    "OpAssoc",
+    "Opt",
+    "Optional",
+    "Or",
+    "ParseBaseException",
+    "ParseElementEnhance",
+    "ParseException",
+    "ParseExpression",
+    "ParseFatalException",
+    "ParseResults",
+    "ParseSyntaxException",
+    "ParserElement",
+    "PositionToken",
+    "PyparsingDeprecationWarning",
+    "PyparsingDiagnosticWarning",
+    "PyparsingWarning",
+    "QuotedString",
+    "RecursiveGrammarException",
+    "Regex",
+    "SkipTo",
+    "StringEnd",
+    "StringStart",
+    "Suppress",
+    "Tag",
+    "Token",
+    "TokenConverter",
+    "White",
+    "Word",
+    "WordEnd",
+    "WordStart",
+    "ZeroOrMore",
+    "Char",
+    "alphanums",
+    "alphas",
+    "alphas8bit",
+    "any_close_tag",
+    "any_open_tag",
+    "autoname_elements",
+    "c_style_comment",
+    "col",
+    "common_html_entity",
+    "condition_as_parse_action",
+    "counted_array",
+    "cpp_style_comment",
+    "dbl_quoted_string",
+    "dbl_slash_comment",
+    "delimited_list",
+    "dict_of",
+    "empty",
+    "hexnums",
+    "html_comment",
+    "identchars",
+    "identbodychars",
+    "infix_notation",
+    "java_style_comment",
+    "line",
+    "line_end",
+    "line_start",
+    "lineno",
+    "make_html_tags",
+    "make_xml_tags",
+    "match_only_at_col",
+    "match_previous_expr",
+    "match_previous_literal",
+    "nested_expr",
+    "null_debug_action",
+    "nums",
+    "one_of",
+    "original_text_for",
+    "printables",
+    "punc8bit",
+    "pyparsing_common",
+    "pyparsing_test",
+    "pyparsing_unicode",
+    "python_style_comment",
+    "quoted_string",
+    "remove_quotes",
+    "replace_with",
+    "replace_html_entity",
+    "rest_of_line",
+    "sgl_quoted_string",
+    "show_best_practices",
+    "srange",
+    "string_end",
+    "string_start",
+    "token_map",
+    "trace_parse_action",
+    "ungroup",
+    "unicode_set",
+    "unicode_string",
+    "with_attribute",
+    "with_class",
+    # pre-PEP8 compatibility names
+    "__versionTime__",
+    "anyCloseTag",
+    "anyOpenTag",
+    "cStyleComment",
+    "commonHTMLEntity",
+    "conditionAsParseAction",
+    "countedArray",
+    "cppStyleComment",
+    "dblQuotedString",
+    "dblSlashComment",
+    "delimitedList",
+    "dictOf",
+    "htmlComment",
+    "indentedBlock",
+    "infixNotation",
+    "javaStyleComment",
+    "lineEnd",
+    "lineStart",
+    "locatedExpr",
+    "makeHTMLTags",
+    "makeXMLTags",
+    "matchOnlyAtCol",
+    "matchPreviousExpr",
+    "matchPreviousLiteral",
+    "nestedExpr",
+    "nullDebugAction",
+    "oneOf",
+    "opAssoc",
+    "originalTextFor",
+    "pythonStyleComment",
+    "quotedString",
+    "removeQuotes",
+    "replaceHTMLEntity",
+    "replaceWith",
+    "restOfLine",
+    "sglQuotedString",
+    "stringEnd",
+    "stringStart",
+    "tokenMap",
+    "traceParseAction",
+    "unicodeString",
+    "withAttribute",
+    "withClass",
+    "common",
+    "unicode",
+    "testing",
+]
diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pyparsing/actions.py b/TTS/Kokoro/.venv/Lib/site-packages/pyparsing/actions.py
new file mode 100644
index 0000000000000000000000000000000000000000..85dc41284031eb6c2c97ec0b3ce06173a516eaeb
--- /dev/null
+++ b/TTS/Kokoro/.venv/Lib/site-packages/pyparsing/actions.py
@@ -0,0 +1,264 @@
+# actions.py
+from __future__ import annotations
+
+from typing import Union, Callable, Any
+
+from .exceptions import ParseException
+from .util import col, replaced_by_pep8
+from .results import ParseResults
+
+
+ParseAction = Union[
+    Callable[[], Any],
+    Callable[[ParseResults], Any],
+    Callable[[int, ParseResults], Any],
+    Callable[[str, int, ParseResults], Any],
+]
+
+
+class OnlyOnce:
+    """
+    Wrapper for parse actions, to ensure they are only called once.
+    Note: parse action signature must include all 3 arguments.
+    """
+
+    def __init__(self, method_call: Callable[[str, int, ParseResults], Any]) -> None:
+        from .core import _trim_arity
+
+        self.callable = _trim_arity(method_call)
+        self.called = False
+
+    def __call__(self, s: str, l: int, t: ParseResults) -> ParseResults:
+        if not self.called:
+            results = self.callable(s, l, t)
+            self.called = True
+            return results
+        raise ParseException(s, l, "OnlyOnce obj called multiple times w/out reset")
+
+    def reset(self):
+        """
+        Allow the associated parse action to be called once more.
+        """
+
+        self.called = False
+
+
+def match_only_at_col(n: int) -> ParseAction:
+    """
+    Helper method for defining parse actions that require matching at
+    a specific column in the input text.
+    """
+
+    def verify_col(strg: str, locn: int, toks: ParseResults) -> None:
+        if col(locn, strg) != n:
+            raise ParseException(strg, locn, f"matched token not at column {n}")
+
+    return verify_col
+
+
+def replace_with(repl_str: Any) -> ParseAction:
+    """
+    Helper method for common parse actions that simply return
+    a literal value.  Especially useful when used with
+    :meth:`~ParserElement.transform_string`.
+
+    Example:
+
+    .. doctest::
+
+       >>> num = Word(nums).set_parse_action(lambda toks: int(toks[0]))
+       >>> na = one_of("N/A NA").set_parse_action(replace_with(math.nan))
+       >>> term = na | num
+
+       >>> term[1, ...].parse_string("324 234 N/A 234")
+       ParseResults([324, 234, nan, 234], {})
+    """
+    return lambda s, l, t: [repl_str]
+
+
+def remove_quotes(s: str, l: int, t: ParseResults) -> Any:
+    r"""
+    Helper parse action for removing quotation marks from parsed
+    quoted strings, that use a single character for quoting. For parsing
+    strings that may have multiple characters, use the :class:`QuotedString`
+    class.
+
+    Example:
+
+    .. doctest::
+
+       >>> # by default, quotation marks are included in parsed results
+       >>> quoted_string.parse_string("'Now is the Winter of our Discontent'")
+       ParseResults(["'Now is the Winter of our Discontent'"], {})
+
+       >>> # use remove_quotes to strip quotation marks from parsed results
+       >>> dequoted = quoted_string().set_parse_action(remove_quotes)
+       >>> dequoted.parse_string("'Now is the Winter of our Discontent'")
+       ParseResults(['Now is the Winter of our Discontent'], {})
+    """
+    return t[0][1:-1]
+
+
+def with_attribute(*args: tuple[str, str], **attr_dict) -> ParseAction:
+    """
+    Helper to create a validating parse action to be used with start
+    tags created with :class:`make_xml_tags` or
+    :class:`make_html_tags`. Use ``with_attribute`` to qualify
+    a starting tag with a required attribute value, to avoid false
+    matches on common tags such as ```` or ``
``. + + Call ``with_attribute`` with a series of attribute names and + values. Specify the list of filter attributes names and values as: + + - keyword arguments, as in ``(align="right")``, or + - as an explicit dict with ``**`` operator, when an attribute + name is also a Python reserved word, as in ``**{"class":"Customer", "align":"right"}`` + - a list of name-value tuples, as in ``(("ns1:class", "Customer"), ("ns2:align", "right"))`` + + For attribute names with a namespace prefix, you must use the second + form. Attribute names are matched insensitive to upper/lower case. + + If just testing for ``class`` (with or without a namespace), use + :class:`with_class`. + + To verify that the attribute exists, but without specifying a value, + pass ``with_attribute.ANY_VALUE`` as the value. + + The next two examples use the following input data and tag parsers: + + .. testcode:: + + html = ''' +
+ Some text +
1 4 0 1 0
+
1,3 2,3 1,1
+
this has no type
+
+ ''' + div,div_end = make_html_tags("div") + + Only match div tag having a type attribute with value "grid": + + .. testcode:: + + div_grid = div().set_parse_action(with_attribute(type="grid")) + grid_expr = div_grid + SkipTo(div | div_end)("body") + for grid_header in grid_expr.search_string(html): + print(grid_header.body) + + prints: + + .. testoutput:: + + 1 4 0 1 0 + + Construct a match with any div tag having a type attribute, + regardless of the value: + + .. testcode:: + + div_any_type = div().set_parse_action( + with_attribute(type=with_attribute.ANY_VALUE) + ) + div_expr = div_any_type + SkipTo(div | div_end)("body") + for div_header in div_expr.search_string(html): + print(div_header.body) + + prints: + + .. testoutput:: + + 1 4 0 1 0 + 1,3 2,3 1,1 + """ + attrs_list: list[tuple[str, str]] = [] + if args: + attrs_list.extend(args) + else: + attrs_list.extend(attr_dict.items()) + + def pa(s: str, l: int, tokens: ParseResults) -> None: + for attrName, attrValue in attrs_list: + if attrName not in tokens: + raise ParseException(s, l, f"no matching attribute {attrName!r}") + if attrValue != with_attribute.ANY_VALUE and tokens[attrName] != attrValue: # type: ignore [attr-defined] + raise ParseException( + s, + l, + f"attribute {attrName!r} has value {tokens[attrName]!r}, must be {attrValue!r}", + ) + + return pa + + +with_attribute.ANY_VALUE = object() # type: ignore [attr-defined] +"Value to use with :class:`with_attribute` parse action, to match any value, as long as the attribute is present" + + +def with_class(classname: str, namespace: str = "") -> ParseAction: + """ + Simplified version of :meth:`with_attribute` when + matching on a div class - made difficult because ``class`` is + a reserved word in Python. + + Using similar input data to the :meth:`with_attribute` examples: + + .. testcode:: + + html = ''' +
+ Some text +
1 4 0 1 0
+
1,3 2,3 1,1
+
this <div> has no class
+
+ ''' + div,div_end = make_html_tags("div") + + Only match div tag having the "grid" class: + + .. testcode:: + + div_grid = div().set_parse_action(with_class("grid")) + grid_expr = div_grid + SkipTo(div | div_end)("body") + for grid_header in grid_expr.search_string(html): + print(grid_header.body) + + prints: + + .. testoutput:: + + 1 4 0 1 0 + + Construct a match with any div tag having a class attribute, + regardless of the value: + + .. testcode:: + + div_any_type = div().set_parse_action( + with_class(withAttribute.ANY_VALUE) + ) + div_expr = div_any_type + SkipTo(div | div_end)("body") + for div_header in div_expr.search_string(html): + print(div_header.body) + + prints: + + .. testoutput:: + + 1 4 0 1 0 + 1,3 2,3 1,1 + """ + classattr = f"{namespace}:class" if namespace else "class" + return with_attribute(**{classattr: classname}) + + +# Compatibility synonyms +# fmt: off +replaceWith = replaced_by_pep8("replaceWith", replace_with) +removeQuotes = replaced_by_pep8("removeQuotes", remove_quotes) +withAttribute = replaced_by_pep8("withAttribute", with_attribute) +withClass = replaced_by_pep8("withClass", with_class) +matchOnlyAtCol = replaced_by_pep8("matchOnlyAtCol", match_only_at_col) +# fmt: on diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pyparsing/common.py b/TTS/Kokoro/.venv/Lib/site-packages/pyparsing/common.py new file mode 100644 index 0000000000000000000000000000000000000000..ef339939320632080900bfcbaf42f4b0bd1b9372 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/pyparsing/common.py @@ -0,0 +1,570 @@ +# common.py +from .core import * +from .helpers import DelimitedList, any_open_tag, any_close_tag +from datetime import datetime +import sys + +PY_310_OR_LATER = sys.version_info >= (3, 10) + + +# some other useful expressions - using lower-case class name since we are really using this as a namespace +class pyparsing_common: + """Here are some common low-level expressions that may be useful in + jump-starting parser development: + + - numeric forms (:class:`integers`, :class:`reals`, + :class:`scientific notation`) + - common :class:`programming identifiers` + - network addresses (:class:`MAC`, + :class:`IPv4`, :class:`IPv6`) + - ISO8601 :class:`dates` and + :class:`datetime` + - :class:`UUID` + - :class:`comma-separated list` + - :class:`url` + + Parse actions: + + - :class:`convert_to_integer` + - :class:`convert_to_float` + - :class:`convert_to_date` + - :class:`convert_to_datetime` + - :class:`strip_html_tags` + - :class:`upcase_tokens` + - :class:`downcase_tokens` + + Examples: + + .. testcode:: + + pyparsing_common.number.run_tests(''' + # any int or real number, returned as the appropriate type + 100 + -100 + +100 + 3.14159 + 6.02e23 + 1e-12 + ''') + + .. testoutput:: + :options: +NORMALIZE_WHITESPACE + + + # any int or real number, returned as the appropriate type + 100 + [100] + + -100 + [-100] + + +100 + [100] + + 3.14159 + [3.14159] + + 6.02e23 + [6.02e+23] + + 1e-12 + [1e-12] + + .. testcode:: + + pyparsing_common.fnumber.run_tests(''' + # any int or real number, returned as float + 100 + -100 + +100 + 3.14159 + 6.02e23 + 1e-12 + ''') + + .. testoutput:: + :options: +NORMALIZE_WHITESPACE + + + # any int or real number, returned as float + 100 + [100.0] + + -100 + [-100.0] + + +100 + [100.0] + + 3.14159 + [3.14159] + + 6.02e23 + [6.02e+23] + + 1e-12 + [1e-12] + + .. testcode:: + + pyparsing_common.hex_integer.run_tests(''' + # hex numbers + 100 + FF + ''') + + .. testoutput:: + :options: +NORMALIZE_WHITESPACE + + + # hex numbers + 100 + [256] + + FF + [255] + + .. testcode:: + + pyparsing_common.fraction.run_tests(''' + # fractions + 1/2 + -3/4 + ''') + + .. testoutput:: + :options: +NORMALIZE_WHITESPACE + + + # fractions + 1/2 + [0.5] + + -3/4 + [-0.75] + + .. testcode:: + + pyparsing_common.mixed_integer.run_tests(''' + # mixed fractions + 1 + 1/2 + -3/4 + 1-3/4 + ''') + + .. testoutput:: + :options: +NORMALIZE_WHITESPACE + + + # mixed fractions + 1 + [1] + + 1/2 + [0.5] + + -3/4 + [-0.75] + + 1-3/4 + [1.75] + .. testcode:: + + import uuid + pyparsing_common.uuid.set_parse_action(token_map(uuid.UUID)) + pyparsing_common.uuid.run_tests(''' + # uuid + 12345678-1234-5678-1234-567812345678 + ''') + + .. testoutput:: + :options: +NORMALIZE_WHITESPACE + + + # uuid + 12345678-1234-5678-1234-567812345678 + [UUID('12345678-1234-5678-1234-567812345678')] + """ + + @staticmethod + def convert_to_integer(_, __, t): + """ + Parse action for converting parsed integers to Python int + """ + return [int(tt) for tt in t] + + @staticmethod + def convert_to_float(_, __, t): + """ + Parse action for converting parsed numbers to Python float + """ + return [float(tt) for tt in t] + + integer = ( + Word(nums) + .set_name("integer") + .set_parse_action( + convert_to_integer + if PY_310_OR_LATER + else lambda t: [int(tt) for tt in t] # type: ignore[misc] + ) + ) + """expression that parses an unsigned integer, converts to an int""" + + hex_integer = ( + Word(hexnums).set_name("hex integer").set_parse_action(token_map(int, 16)) + ) + """expression that parses a hexadecimal integer, converts to an int""" + + signed_integer = ( + Regex(r"[+-]?\d+") + .set_name("signed integer") + .set_parse_action( + convert_to_integer + if PY_310_OR_LATER + else lambda t: [int(tt) for tt in t] # type: ignore[misc] + ) + ) + """expression that parses an integer with optional leading sign, converts to an int""" + + fraction = ( + signed_integer().set_parse_action( + convert_to_float + if PY_310_OR_LATER + else lambda t: [float(tt) for tt in t] # type: ignore[misc] + ) + + "/" + + signed_integer().set_parse_action( + convert_to_float + if PY_310_OR_LATER + else lambda t: [float(tt) for tt in t] # type: ignore[misc] + ) + ).set_name("fraction") + """fractional expression of an integer divided by an integer, converts to a float""" + fraction.add_parse_action(lambda tt: tt[0] / tt[-1]) + + mixed_integer = ( + fraction | signed_integer + Opt(Opt("-").suppress() + fraction) + ).set_name("fraction or mixed integer-fraction") + """mixed integer of the form 'integer - fraction', with optional leading integer, converts to a float""" + mixed_integer.add_parse_action(sum) + + real = ( + Regex(r"[+-]?(?:\d+\.\d*|\.\d+)") + .set_name("real number") + .set_parse_action( + convert_to_float + if PY_310_OR_LATER + else lambda t: [float(tt) for tt in t] # type: ignore[misc] + ) + ) + """expression that parses a floating point number, converts to a float""" + + sci_real = ( + Regex(r"[+-]?(?:\d+(?:[eE][+-]?\d+)|(?:\d+\.\d*|\.\d+)(?:[eE][+-]?\d+)?)") + .set_name("real number with scientific notation") + .set_parse_action( + convert_to_float + if PY_310_OR_LATER + else lambda t: [float(tt) for tt in t] # type: ignore[misc] + ) + ) + """expression that parses a floating point number with optional + scientific notation, converts to a float""" + + # streamlining this expression makes the docs nicer-looking + number = (sci_real | real | signed_integer).set_name("number").streamline() + """any numeric expression, converts to the corresponding Python type""" + + fnumber = ( + Regex(r"[+-]?\d+\.?\d*(?:[eE][+-]?\d+)?") + .set_name("fnumber") + .set_parse_action( + convert_to_float + if PY_310_OR_LATER + else lambda t: [float(tt) for tt in t] # type: ignore[misc] + ) + ) + """any int or real number, always converts to a float""" + + ieee_float = ( + Regex(r"(?i:[+-]?(?:(?:\d+\.?\d*(?:e[+-]?\d+)?)|nan|inf(?:inity)?))") + .set_name("ieee_float") + .set_parse_action( + convert_to_float + if PY_310_OR_LATER + else lambda t: [float(tt) for tt in t] # type: ignore[misc] + ) + ) + """any floating-point literal (int, real number, infinity, or NaN), converts to a float""" + + identifier = Word(identchars, identbodychars).set_name("identifier") + """typical code identifier (leading alpha or '_', followed by 0 or more alphas, nums, or '_')""" + + ipv4_address = Regex( + r"(?:25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})(?:\.(?:25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})){3}" + ).set_name("IPv4 address") + "IPv4 address (``0.0.0.0 - 255.255.255.255``)" + + _ipv6_part = Regex(r"[0-9a-fA-F]{1,4}").set_name("hex_integer") + _full_ipv6_address = (_ipv6_part + (":" + _ipv6_part) * 7).set_name( + "full IPv6 address" + ) + _short_ipv6_address = ( + Opt(_ipv6_part + (":" + _ipv6_part) * (0, 6)) + + "::" + + Opt(_ipv6_part + (":" + _ipv6_part) * (0, 6)) + ).set_name("short IPv6 address") + _short_ipv6_address.add_condition( + lambda t: sum(1 for tt in t if pyparsing_common._ipv6_part.matches(tt)) < 8 + ) + _mixed_ipv6_address = ("::ffff:" + ipv4_address).set_name("mixed IPv6 address") + ipv6_address = Combine( + (_full_ipv6_address | _mixed_ipv6_address | _short_ipv6_address).set_name( + "IPv6 address" + ) + ).set_name("IPv6 address") + "IPv6 address (long, short, or mixed form)" + + mac_address = Regex( + r"[0-9a-fA-F]{2}([:.-])[0-9a-fA-F]{2}(?:\1[0-9a-fA-F]{2}){4}" + ).set_name("MAC address") + "MAC address xx:xx:xx:xx:xx (may also have '-' or '.' delimiters)" + + @staticmethod + def convert_to_date(fmt: str = "%Y-%m-%d"): + """ + Helper to create a parse action for converting parsed date string to Python datetime.date + + Params - + - fmt - format to be passed to datetime.strptime (default= ``"%Y-%m-%d"``) + + Example: + + .. testcode:: + + date_expr = pyparsing_common.iso8601_date.copy() + date_expr.set_parse_action(pyparsing_common.convert_to_date()) + print(date_expr.parse_string("1999-12-31")) + + prints: + + .. testoutput:: + + [datetime.date(1999, 12, 31)] + """ + + def cvt_fn(ss, ll, tt): + try: + return datetime.strptime(tt[0], fmt).date() + except ValueError as ve: + raise ParseException(ss, ll, str(ve)) + + return cvt_fn + + @staticmethod + def convert_to_datetime(fmt: str = "%Y-%m-%dT%H:%M:%S.%f"): + """Helper to create a parse action for converting parsed + datetime string to Python :class:`datetime.datetime` + + Params - + - fmt - format to be passed to :class:`datetime.strptime` (default= ``"%Y-%m-%dT%H:%M:%S.%f"``) + + Example: + + .. testcode:: + + dt_expr = pyparsing_common.iso8601_datetime.copy() + dt_expr.set_parse_action(pyparsing_common.convert_to_datetime()) + print(dt_expr.parse_string("1999-12-31T23:59:59.999")) + + prints: + + .. testoutput:: + + [datetime.datetime(1999, 12, 31, 23, 59, 59, 999000)] + """ + + def cvt_fn(s, l, t): + try: + return datetime.strptime(t[0], fmt) + except ValueError as ve: + raise ParseException(s, l, str(ve)) + + return cvt_fn + + iso8601_date = Regex( + r"(?P\d{4})(?:-(?P\d\d)(?:-(?P\d\d))?)?" + ).set_name("ISO8601 date") + "ISO8601 date (``yyyy-mm-dd``)" + + iso8601_datetime = Regex( + r"(?P\d{4})-(?P\d\d)-(?P\d\d)[T ](?P\d\d):(?P\d\d)(:(?P\d\d(\.\d*)?)?)?(?PZ|[+-]\d\d:?\d\d)?" + ).set_name("ISO8601 datetime") + "ISO8601 datetime (``yyyy-mm-ddThh:mm:ss.s(Z|+-00:00)``) - trailing seconds, milliseconds, and timezone optional; accepts separating ``'T'`` or ``' '``" + + @staticmethod + def as_datetime(s, l, t): + """Parse action to convert parsed dates or datetimes to a Python + :class:`datetime.datetime`. + + This parse action will use the year, month, day, etc. results + names defined in the ISO8601 date expressions, but it can be + used with any expression that provides one or more of these fields. + + Omitted fields will default to fields from Jan 1, 00:00:00. + + Invalid dates will raise a :class:`ParseException` with the + error message indicating the invalid date fields. + """ + year = int(t.year.lstrip("0") or 0) + month = int(t.month or 1) + day = int(t.day or 1) + hour = int(t.hour or 0) + minute = int(t.minute or 0) + second = float(t.second or 0) + try: + return datetime( + year, month, day, hour, minute, int(second), int((second % 1) * 1000) + ) + except ValueError as ve: + raise ParseException(t, l, f"Invalid date/time: {ve}").with_traceback( + ve.__traceback__ + ) from None + + if PY_310_OR_LATER: + iso8601_date_validated = iso8601_date().add_parse_action(as_datetime) + "Validated ISO8601 date strings, raising :class:`ParseException` for invalid date values." + + iso8601_datetime_validated = iso8601_datetime().add_parse_action(as_datetime) + "Validated ISO8601 date and time strings, raising :class:`ParseException` for invalid date/time values." + + uuid = Regex(r"[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}").set_name( + "UUID" + ) + "UUID (``xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx``)" + + _html_stripper = any_open_tag.suppress() | any_close_tag.suppress() + + @staticmethod + def strip_html_tags(s: str, l: int, tokens: ParseResults): + """Parse action to remove HTML tags from web page HTML source + + Example: + + .. testcode:: + + # strip HTML links from normal text + text = 'More info at the
pyparsing wiki page' + td, td_end = make_html_tags("TD") + table_text = td + SkipTo(td_end).set_parse_action( + pyparsing_common.strip_html_tags)("body") + td_end + print(table_text.parse_string(text).body) + + Prints: + + .. testoutput:: + + More info at the pyparsing wiki page + """ + return pyparsing_common._html_stripper.transform_string(tokens[0]) + + _commasepitem = ( + Combine( + OneOrMore( + ~Literal(",") + + ~LineEnd() + + Word(printables, exclude_chars=",") + + Opt(White(" \t") + ~FollowedBy(LineEnd() | ",")) + ) + ) + .streamline() + .set_name("commaItem") + ) + comma_separated_list = DelimitedList( + Opt(quoted_string.copy() | _commasepitem, default="") + ).set_name("comma separated list") + """Predefined expression of 1 or more printable words or quoted strings, separated by commas.""" + + @staticmethod + def upcase_tokens(s, l, t): + """Parse action to convert tokens to upper case.""" + return [tt.upper() for tt in t] + + @staticmethod + def downcase_tokens(s, l, t): + """Parse action to convert tokens to lower case.""" + return [tt.lower() for tt in t] + + # fmt: off + url = Regex( + # https://mathiasbynens.be/demo/url-regex + # https://gist.github.com/dperini/729294 + r"(?P" + # protocol identifier (optional) + # short syntax // still required + r"(?:(?:(?Phttps?|ftp):)?\/\/)" + # user:pass BasicAuth (optional) + r"(?:(?P\S+(?::\S*)?)@)?" + r"(?P" + # IP address exclusion + # private & local networks + r"(?!(?:10|127)(?:\.\d{1,3}){3})" + r"(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})" + r"(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})" + # IP address dotted notation octets + # excludes loopback network 0.0.0.0 + # excludes reserved space >= 224.0.0.0 + # excludes network & broadcast addresses + # (first & last IP address of each class) + r"(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])" + r"(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}" + r"(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))" + r"|" + # host & domain names, may end with dot + # can be replaced by a shortest alternative + # (?![-_])(?:[-\w\u00a1-\uffff]{0,63}[^-_]\.)+ + r"(?:" + r"(?:" + r"[a-z0-9\u00a1-\uffff]" + r"[a-z0-9\u00a1-\uffff_-]{0,62}" + r")?" + r"[a-z0-9\u00a1-\uffff]\." + r")+" + # TLD identifier name, may end with dot + r"(?:[a-z\u00a1-\uffff]{2,}\.?)" + r")" + # port number (optional) + r"(:(?P\d{2,5}))?" + # resource path (optional) + r"(?P\/[^?# ]*)?" + # query string (optional) + r"(\?(?P[^#]*))?" + # fragment (optional) + r"(#(?P\S*))?" + r")" + ).set_name("url") + """ + URL (http/https/ftp scheme) + + .. versionchanged:: 3.1.0 + ``url`` named group added + """ + # fmt: on + + # pre-PEP8 compatibility names + # fmt: off + convertToInteger = staticmethod(replaced_by_pep8("convertToInteger", convert_to_integer)) + convertToFloat = staticmethod(replaced_by_pep8("convertToFloat", convert_to_float)) + convertToDate = staticmethod(replaced_by_pep8("convertToDate", convert_to_date)) + convertToDatetime = staticmethod(replaced_by_pep8("convertToDatetime", convert_to_datetime)) + stripHTMLTags = staticmethod(replaced_by_pep8("stripHTMLTags", strip_html_tags)) + upcaseTokens = staticmethod(replaced_by_pep8("upcaseTokens", upcase_tokens)) + downcaseTokens = staticmethod(replaced_by_pep8("downcaseTokens", downcase_tokens)) + # fmt: on + + +_builtin_exprs = [ + v for v in vars(pyparsing_common).values() if isinstance(v, ParserElement) +] diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pyparsing/core.py b/TTS/Kokoro/.venv/Lib/site-packages/pyparsing/core.py new file mode 100644 index 0000000000000000000000000000000000000000..db197506179889f7e5c133ebd655c106aa8738a8 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/pyparsing/core.py @@ -0,0 +1,6951 @@ +# +# core.py +# +from __future__ import annotations + +import collections.abc +from collections import deque +import os +import typing +from typing import ( + Any, + Callable, + Generator, + NamedTuple, + Sequence, + TextIO, + Union, + cast, +) +from abc import ABC, abstractmethod +from enum import Enum +import string +import copy +import warnings +import re +import sys +from collections.abc import Iterable +import traceback +import types +from operator import itemgetter +from functools import wraps +from threading import RLock +from pathlib import Path + +from .warnings import PyparsingDeprecationWarning, PyparsingDiagnosticWarning +from .util import ( + _FifoCache, + _UnboundedCache, + __config_flags, + _collapse_string_to_ranges, + _convert_escaped_numerics_to_char, + _escape_regex_range_chars, + _flatten, + LRUMemo as _LRUMemo, + UnboundedMemo as _UnboundedMemo, + deprecate_argument, + replaced_by_pep8, +) +from .exceptions import * +from .actions import * +from .results import ParseResults, _ParseResultsWithOffset +from .unicode import pyparsing_unicode + +_MAX_INT = sys.maxsize +str_type: tuple[type, ...] = (str, bytes) + +# +# Copyright (c) 2003-2022 Paul T. McGuire +# +# 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. +# + +from functools import cached_property + + +class __compat__(__config_flags): + """ + A cross-version compatibility configuration for pyparsing features that will be + released in a future version. By setting values in this configuration to True, + those features can be enabled in prior versions for compatibility development + and testing. + + - ``collect_all_And_tokens`` - flag to enable fix for Issue #63 that fixes erroneous grouping + of results names when an :class:`And` expression is nested within an :class:`Or` or :class:`MatchFirst`; + maintained for compatibility, but setting to ``False`` no longer restores pre-2.3.1 + behavior + """ + + _type_desc = "compatibility" + + collect_all_And_tokens = True + + _all_names = [__ for __ in locals() if not __.startswith("_")] + _fixed_names = """ + collect_all_And_tokens + """.split() + + +class __diag__(__config_flags): + _type_desc = "diagnostic" + + warn_multiple_tokens_in_named_alternation = False + warn_ungrouped_named_tokens_in_collection = False + warn_name_set_on_empty_Forward = False + warn_on_parse_using_empty_Forward = False + warn_on_assignment_to_Forward = False + warn_on_multiple_string_args_to_oneof = False + warn_on_match_first_with_lshift_operator = False + enable_debug_on_named_expressions = False + + _all_names = [__ for __ in locals() if not __.startswith("_")] + _warning_names = [name for name in _all_names if name.startswith("warn")] + _debug_names = [name for name in _all_names if name.startswith("enable_debug")] + + @classmethod + def enable_all_warnings(cls) -> None: + for name in cls._warning_names: + cls.enable(name) + + +class Diagnostics(Enum): + """ + Diagnostic configuration (all default to disabled) + + - ``warn_multiple_tokens_in_named_alternation`` - flag to enable warnings when a results + name is defined on a :class:`MatchFirst` or :class:`Or` expression with one or more :class:`And` subexpressions + - ``warn_ungrouped_named_tokens_in_collection`` - flag to enable warnings when a results + name is defined on a containing expression with ungrouped subexpressions that also + have results names + - ``warn_name_set_on_empty_Forward`` - flag to enable warnings when a :class:`Forward` is defined + with a results name, but has no contents defined + - ``warn_on_parse_using_empty_Forward`` - flag to enable warnings when a :class:`Forward` is + defined in a grammar but has never had an expression attached to it + - ``warn_on_assignment_to_Forward`` - flag to enable warnings when a :class:`Forward` is defined + but is overwritten by assigning using ``'='`` instead of ``'<<='`` or ``'<<'`` + - ``warn_on_multiple_string_args_to_oneof`` - flag to enable warnings when :class:`one_of` is + incorrectly called with multiple str arguments + - ``enable_debug_on_named_expressions`` - flag to auto-enable debug on all subsequent + calls to :class:`ParserElement.set_name` + + Diagnostics are enabled/disabled by calling :class:`enable_diag` and :class:`disable_diag`. + All warnings can be enabled by calling :class:`enable_all_warnings`. + """ + + warn_multiple_tokens_in_named_alternation = 0 + warn_ungrouped_named_tokens_in_collection = 1 + warn_name_set_on_empty_Forward = 2 + warn_on_parse_using_empty_Forward = 3 + warn_on_assignment_to_Forward = 4 + warn_on_multiple_string_args_to_oneof = 5 + warn_on_match_first_with_lshift_operator = 6 + enable_debug_on_named_expressions = 7 + + +def enable_diag(diag_enum: Diagnostics) -> None: + """ + Enable a global pyparsing diagnostic flag (see :class:`Diagnostics`). + """ + __diag__.enable(diag_enum.name) + + +def disable_diag(diag_enum: Diagnostics) -> None: + """ + Disable a global pyparsing diagnostic flag (see :class:`Diagnostics`). + """ + __diag__.disable(diag_enum.name) + + +def enable_all_warnings() -> None: + """ + Enable all global pyparsing diagnostic warnings (see :class:`Diagnostics`). + """ + __diag__.enable_all_warnings() + + +# hide abstract class +del __config_flags + + +def _should_enable_warnings( + cmd_line_warn_options: typing.Iterable[str], warn_env_var: typing.Optional[str] +) -> bool: + enable = bool(warn_env_var) + for warn_opt in cmd_line_warn_options: + w_action, w_message, w_category, w_module, w_line = (warn_opt + "::::").split( + ":" + )[:5] + if not w_action.lower().startswith("i") and ( + not (w_message or w_category or w_module) or w_module == "pyparsing" + ): + enable = True + elif w_action.lower().startswith("i") and w_module in ("pyparsing", ""): + enable = False + return enable + + +if _should_enable_warnings( + sys.warnoptions, os.environ.get("PYPARSINGENABLEALLWARNINGS") +): + enable_all_warnings() + + +# build list of single arg builtins, that can be used as parse actions +# fmt: off +_single_arg_builtins = { + sum, len, sorted, reversed, list, tuple, set, any, all, min, max +} +# fmt: on + +_generatorType = types.GeneratorType +ParseImplReturnType = tuple[int, Any] +PostParseReturnType = Union[ParseResults, Sequence[ParseResults]] + +ParseCondition = Union[ + Callable[[], bool], + Callable[[ParseResults], bool], + Callable[[int, ParseResults], bool], + Callable[[str, int, ParseResults], bool], +] +ParseFailAction = Callable[[str, int, "ParserElement", Exception], None] +DebugStartAction = Callable[[str, int, "ParserElement", bool], None] +DebugSuccessAction = Callable[ + [str, int, int, "ParserElement", ParseResults, bool], None +] +DebugExceptionAction = Callable[[str, int, "ParserElement", Exception, bool], None] + + +alphas: str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" +identchars: str = pyparsing_unicode.Latin1.identchars +identbodychars: str = pyparsing_unicode.Latin1.identbodychars +nums: str = "0123456789" +hexnums: str = "0123456789ABCDEFabcdef" +alphanums: str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" +printables: str = ( + '!"' + "#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~" +) + + +class _ParseActionIndexError(Exception): + """ + Internal wrapper around IndexError so that IndexErrors raised inside + parse actions aren't misinterpreted as IndexErrors raised inside + ParserElement parseImpl methods. + """ + + def __init__(self, msg: str, exc: BaseException) -> None: + self.msg: str = msg + self.exc: BaseException = exc + + +_trim_arity_call_line: traceback.StackSummary = None # type: ignore[assignment] +pa_call_line_synth = () + + +def _trim_arity(func, max_limit=3): + """decorator to trim function calls to match the arity of the target""" + global _trim_arity_call_line, pa_call_line_synth + + if func in _single_arg_builtins: + return lambda s, l, t: func(t) + + limit = 0 + found_arity = False + + # synthesize what would be returned by traceback.extract_stack at the call to + # user's parse action 'func', so that we don't incur call penalty at parse time + + # fmt: off + LINE_DIFF = 9 + # IF ANY CODE CHANGES, EVEN JUST COMMENTS OR BLANK LINES, BETWEEN THE NEXT LINE AND + # THE CALL TO FUNC INSIDE WRAPPER, LINE_DIFF MUST BE MODIFIED!!!! + _trim_arity_call_line = _trim_arity_call_line or traceback.extract_stack(limit=2)[-1] + pa_call_line_synth = pa_call_line_synth or (_trim_arity_call_line[0], _trim_arity_call_line[1] + LINE_DIFF) + + def wrapper(*args): + nonlocal found_arity, limit + if found_arity: + return func(*args[limit:]) + while 1: + try: + ret = func(*args[limit:]) + found_arity = True + return ret + except TypeError as te: + # re-raise TypeErrors if they did not come from our arity testing + if found_arity: + raise + else: + tb = te.__traceback__ + frames = traceback.extract_tb(tb, limit=2) + frame_summary = frames[-1] + trim_arity_type_error = ( + [frame_summary[:2]][-1][:2] == pa_call_line_synth + ) + del tb + + if trim_arity_type_error: + if limit < max_limit: + limit += 1 + continue + + raise + except IndexError as ie: + # wrap IndexErrors inside a _ParseActionIndexError + raise _ParseActionIndexError( + "IndexError raised in parse action", ie + ).with_traceback(None) + # fmt: on + + # copy func name to wrapper for sensible debug output + # (can't use functools.wraps, since that messes with function signature) + func_name = getattr(func, "__name__", getattr(func, "__class__").__name__) + wrapper.__name__ = func_name + wrapper.__doc__ = func.__doc__ + + return wrapper + + +def condition_as_parse_action( + fn: ParseCondition, message: typing.Optional[str] = None, fatal: bool = False +) -> ParseAction: + """ + Function to convert a simple predicate function that returns ``True`` or ``False`` + into a parse action. Can be used in places when a parse action is required + and :meth:`ParserElement.add_condition` cannot be used (such as when adding a condition + to an operator level in :class:`infix_notation`). + + Optional keyword arguments: + + :param message: define a custom message to be used in the raised exception + :param fatal: if ``True``, will raise :class:`ParseFatalException` + to stop parsing immediately; + otherwise will raise :class:`ParseException` + + """ + msg = message if message is not None else "failed user-defined condition" + exc_type = ParseFatalException if fatal else ParseException + fn = _trim_arity(fn) + + @wraps(fn) + def pa(s, l, t): + if not bool(fn(s, l, t)): + raise exc_type(s, l, msg) + + return pa + + +def _default_start_debug_action( + instring: str, loc: int, expr: ParserElement, cache_hit: bool = False +): + cache_hit_str = "*" if cache_hit else "" + print( + ( + f"{cache_hit_str}Match {expr} at loc {loc}({lineno(loc, instring)},{col(loc, instring)})\n" + f" {line(loc, instring)}\n" + f" {'^':>{col(loc, instring)}}" + ) + ) + + +def _default_success_debug_action( + instring: str, + startloc: int, + endloc: int, + expr: ParserElement, + toks: ParseResults, + cache_hit: bool = False, +): + cache_hit_str = "*" if cache_hit else "" + print(f"{cache_hit_str}Matched {expr} -> {toks.as_list()}") + + +def _default_exception_debug_action( + instring: str, + loc: int, + expr: ParserElement, + exc: Exception, + cache_hit: bool = False, +): + cache_hit_str = "*" if cache_hit else "" + print(f"{cache_hit_str}Match {expr} failed, {type(exc).__name__} raised: {exc}") + + +def null_debug_action(*args): + """'Do-nothing' debug action, to suppress debugging output during parsing.""" + + +class ParserElement(ABC): + """Abstract base level parser element class.""" + + DEFAULT_WHITE_CHARS: str = " \n\t\r" + verbose_stacktrace: bool = False + _literalStringClass: type = None # type: ignore[assignment] + + @staticmethod + def set_default_whitespace_chars(chars: str) -> None: + r""" + Overrides the default whitespace chars + + Example: + + .. doctest:: + + # default whitespace chars are space, and newline + >>> Word(alphas)[1, ...].parse_string("abc def\nghi jkl") + ParseResults(['abc', 'def', 'ghi', 'jkl'], {}) + + # change to just treat newline as significant + >>> ParserElement.set_default_whitespace_chars(" \t") + >>> Word(alphas)[1, ...].parse_string("abc def\nghi jkl") + ParseResults(['abc', 'def'], {}) + + # Reset to default + >>> ParserElement.set_default_whitespace_chars(" \n\t\r") + """ + ParserElement.DEFAULT_WHITE_CHARS = chars + + # update whitespace all parse expressions defined in this module + for expr in _builtin_exprs: + if expr.copyDefaultWhiteChars: + expr.whiteChars = set(chars) + + @staticmethod + def inline_literals_using(cls: type) -> None: + """ + Set class to be used for inclusion of string literals into a parser. + + Example: + + .. doctest:: + :options: +NORMALIZE_WHITESPACE + + # default literal class used is Literal + >>> integer = Word(nums) + >>> date_str = ( + ... integer("year") + '/' + ... + integer("month") + '/' + ... + integer("day") + ... ) + + >>> date_str.parse_string("1999/12/31") + ParseResults(['1999', '/', '12', '/', '31'], + {'year': '1999', 'month': '12', 'day': '31'}) + + # change to Suppress + >>> ParserElement.inline_literals_using(Suppress) + >>> date_str = ( + ... integer("year") + '/' + ... + integer("month") + '/' + ... + integer("day") + ... ) + + >>> date_str.parse_string("1999/12/31") + ParseResults(['1999', '12', '31'], + {'year': '1999', 'month': '12', 'day': '31'}) + + # Reset + >>> ParserElement.inline_literals_using(Literal) + """ + ParserElement._literalStringClass = cls + + @classmethod + def using_each(cls, seq, **class_kwargs): + """ + Yields a sequence of ``class(obj, **class_kwargs)`` for obj in seq. + + Example: + + .. testcode:: + + LPAR, RPAR, LBRACE, RBRACE, SEMI = Suppress.using_each("(){};") + + .. versionadded:: 3.1.0 + """ + yield from (cls(obj, **class_kwargs) for obj in seq) + + class DebugActions(NamedTuple): + debug_try: typing.Optional[DebugStartAction] + debug_match: typing.Optional[DebugSuccessAction] + debug_fail: typing.Optional[DebugExceptionAction] + + def __init__(self, savelist: bool = False) -> None: + self.parseAction: list[ParseAction] = list() + self.failAction: typing.Optional[ParseFailAction] = None + self.customName: str = None # type: ignore[assignment] + self._defaultName: typing.Optional[str] = None + self.resultsName: str = None # type: ignore[assignment] + self.saveAsList: bool = savelist + self.skipWhitespace: bool = True + self.whiteChars: set[str] = set(ParserElement.DEFAULT_WHITE_CHARS) + self.copyDefaultWhiteChars: bool = True + # used when checking for left-recursion + self._may_return_empty: bool = False + self.keepTabs: bool = False + self.ignoreExprs: list[ParserElement] = list() + self.debug: bool = False + self.streamlined: bool = False + # optimize exception handling for subclasses that don't advance parse index + self.mayIndexError: bool = True + self.errmsg: Union[str, None] = "" + # mark results names as modal (report only last) or cumulative (list all) + self.modalResults: bool = True + # custom debug actions + self.debugActions = self.DebugActions(None, None, None) + # avoid redundant calls to preParse + self.callPreparse: bool = True + self.callDuringTry: bool = False + self.suppress_warnings_: list[Diagnostics] = [] + self.show_in_diagram: bool = True + + @property + def mayReturnEmpty(self) -> bool: + """ + .. deprecated:: 3.3.0 + use _may_return_empty instead. + """ + return self._may_return_empty + + @mayReturnEmpty.setter + def mayReturnEmpty(self, value) -> None: + """ + .. deprecated:: 3.3.0 + use _may_return_empty instead. + """ + self._may_return_empty = value + + def suppress_warning(self, warning_type: Diagnostics) -> ParserElement: + """ + Suppress warnings emitted for a particular diagnostic on this expression. + + Example: + + .. doctest:: + + >>> label = pp.Word(pp.alphas) + + # Normally using an empty Forward in a grammar + # would print a warning, but we can suppress that + >>> base = pp.Forward().suppress_warning( + ... pp.Diagnostics.warn_on_parse_using_empty_Forward) + + >>> grammar = base | label + >>> print(grammar.parse_string("x")) + ['x'] + """ + self.suppress_warnings_.append(warning_type) + return self + + def visit_all(self): + """General-purpose method to yield all expressions and sub-expressions + in a grammar. Typically just for internal use. + """ + to_visit = deque([self]) + seen = set() + while to_visit: + cur = to_visit.popleft() + + # guard against looping forever through recursive grammars + if cur in seen: + continue + seen.add(cur) + + to_visit.extend(cur.recurse()) + yield cur + + def copy(self) -> ParserElement: + """ + Make a copy of this :class:`ParserElement`. Useful for defining + different parse actions for the same parsing pattern, using copies of + the original parse element. + + Example: + + .. testcode:: + + integer = Word(nums).set_parse_action( + lambda toks: int(toks[0])) + integerK = integer.copy().add_parse_action( + lambda toks: toks[0] * 1024) + Suppress("K") + integerM = integer.copy().add_parse_action( + lambda toks: toks[0] * 1024 * 1024) + Suppress("M") + + print( + (integerK | integerM | integer)[1, ...].parse_string( + "5K 100 640K 256M") + ) + + prints: + + .. testoutput:: + + [5120, 100, 655360, 268435456] + + Equivalent form of ``expr.copy()`` is just ``expr()``: + + .. testcode:: + + integerM = integer().add_parse_action( + lambda toks: toks[0] * 1024 * 1024) + Suppress("M") + """ + cpy = copy.copy(self) + cpy.parseAction = self.parseAction[:] + cpy.ignoreExprs = self.ignoreExprs[:] + if self.copyDefaultWhiteChars: + cpy.whiteChars = set(ParserElement.DEFAULT_WHITE_CHARS) + return cpy + + def set_results_name( + self, name: str, list_all_matches: bool = False, **kwargs + ) -> ParserElement: + """ + Define name for referencing matching tokens as a nested attribute + of the returned parse results. + + Normally, results names are assigned as you would assign keys in a dict: + any existing value is overwritten by later values. If it is necessary to + keep all values captured for a particular results name, call ``set_results_name`` + with ``list_all_matches`` = True. + + NOTE: ``set_results_name`` returns a *copy* of the original :class:`ParserElement` object; + this is so that the client can define a basic element, such as an + integer, and reference it in multiple places with different names. + + You can also set results names using the abbreviated syntax, + ``expr("name")`` in place of ``expr.set_results_name("name")`` + - see :meth:`__call__`. If ``list_all_matches`` is required, use + ``expr("name*")``. + + Example: + + .. testcode:: + + integer = Word(nums) + date_str = (integer.set_results_name("year") + '/' + + integer.set_results_name("month") + '/' + + integer.set_results_name("day")) + + # equivalent form: + date_str = integer("year") + '/' + integer("month") + '/' + integer("day") + """ + listAllMatches: bool = deprecate_argument(kwargs, "listAllMatches", False) + + list_all_matches = listAllMatches or list_all_matches + return self._setResultsName(name, list_all_matches) + + def _setResultsName(self, name, list_all_matches=False) -> ParserElement: + if name is None: + return self + newself = self.copy() + if name.endswith("*"): + name = name[:-1] + list_all_matches = True + newself.resultsName = name + newself.modalResults = not list_all_matches + return newself + + def set_break(self, break_flag: bool = True) -> ParserElement: + """ + Method to invoke the Python pdb debugger when this element is + about to be parsed. Set ``break_flag`` to ``True`` to enable, ``False`` to + disable. + """ + if break_flag: + _parseMethod = self._parse + + def breaker(instring, loc, do_actions=True, callPreParse=True): + # this call to breakpoint() is intentional, not a checkin error + breakpoint() + return _parseMethod(instring, loc, do_actions, callPreParse) + + breaker._originalParseMethod = _parseMethod # type: ignore [attr-defined] + self._parse = breaker # type: ignore [method-assign] + elif hasattr(self._parse, "_originalParseMethod"): + self._parse = self._parse._originalParseMethod # type: ignore [method-assign] + return self + + def set_parse_action( + self, *fns: ParseAction, call_during_try: bool = False, **kwargs: Any + ) -> ParserElement: + """ + Define one or more actions to perform when successfully matching parse element definition. + + Parse actions can be called to perform data conversions, do extra validation, + update external data structures, or enhance or replace the parsed tokens. + Each parse action ``fn`` is a callable method with 0-3 arguments, called as + ``fn(s, loc, toks)`` , ``fn(loc, toks)`` , ``fn(toks)`` , or just ``fn()`` , where: + + - ``s`` = the original string being parsed (see note below) + - ``loc`` = the location of the matching substring + - ``toks`` = a list of the matched tokens, packaged as a :class:`ParseResults` object + + The parsed tokens are passed to the parse action as ParseResults. They can be + modified in place using list-style append, extend, and pop operations to update + the parsed list elements; and with dictionary-style item set and del operations + to add, update, or remove any named results. If the tokens are modified in place, + it is not necessary to return them with a return statement. + + Parse actions can also completely replace the given tokens, with another ``ParseResults`` + object, or with some entirely different object (common for parse actions that perform data + conversions). A convenient way to build a new parse result is to define the values + using a dict, and then create the return value using :class:`ParseResults.from_dict`. + + If None is passed as the ``fn`` parse action, all previously added parse actions for this + expression are cleared. + + Optional keyword arguments: + + :param call_during_try: (default= ``False``) indicate if parse action + should be run during lookaheads and alternate + testing. For parse actions that have side + effects, it is important to only call the parse + action once it is determined that it is being + called as part of a successful parse. + For parse actions that perform additional + validation, then ``call_during_try`` should + be passed as True, so that the validation code + is included in the preliminary "try" parses. + + .. Note:: + The default parsing behavior is to expand tabs in the input string + before starting the parsing process. + See :meth:`parse_string` for more information on parsing strings + containing ```` s, and suggested methods to maintain a + consistent view of the parsed string, the parse location, and + line and column positions within the parsed string. + + Example: Parse dates in the form ``YYYY/MM/DD`` + ----------------------------------------------- + + Setup code: + + .. testcode:: + + def convert_to_int(toks): + '''a parse action to convert toks from str to int + at parse time''' + return int(toks[0]) + + def is_valid_date(instring, loc, toks): + '''a parse action to verify that the date is a valid date''' + from datetime import date + year, month, day = toks[::2] + try: + date(year, month, day) + except ValueError: + raise ParseException(instring, loc, "invalid date given") + + integer = Word(nums) + date_str = integer + '/' + integer + '/' + integer + + # add parse actions + integer.set_parse_action(convert_to_int) + date_str.set_parse_action(is_valid_date) + + Successful parse - note that integer fields are converted to ints: + + .. testcode:: + + print(date_str.parse_string("1999/12/31")) + + prints: + + .. testoutput:: + + [1999, '/', 12, '/', 31] + + Failure - invalid date: + + .. testcode:: + + date_str.parse_string("1999/13/31") + + prints: + + .. testoutput:: + + Traceback (most recent call last): + ParseException: invalid date given, found '1999' ... + """ + callDuringTry: bool = deprecate_argument(kwargs, "callDuringTry", False) + + if list(fns) == [None]: + self.parseAction.clear() + return self + + if not all(callable(fn) for fn in fns): + raise TypeError("parse actions must be callable") + self.parseAction[:] = [_trim_arity(fn) for fn in fns] + self.callDuringTry = self.callDuringTry or call_during_try or callDuringTry + + return self + + def add_parse_action( + self, *fns: ParseAction, call_during_try: bool = False, **kwargs: Any + ) -> ParserElement: + """ + Add one or more parse actions to expression's list of parse actions. See :class:`set_parse_action`. + + See examples in :class:`copy`. + """ + callDuringTry: bool = deprecate_argument(kwargs, "callDuringTry", False) + + self.parseAction += [_trim_arity(fn) for fn in fns] + self.callDuringTry = self.callDuringTry or callDuringTry or call_during_try + return self + + def add_condition( + self, *fns: ParseCondition, call_during_try: bool = False, **kwargs: Any + ) -> ParserElement: + """Add a boolean predicate function to expression's list of parse actions. See + :class:`set_parse_action` for function call signatures. Unlike ``set_parse_action``, + functions passed to ``add_condition`` need to return boolean success/fail of the condition. + + Optional keyword arguments: + + - ``message`` = define a custom message to be used in the raised exception + - ``fatal`` = if True, will raise ParseFatalException to stop parsing immediately; otherwise will raise + ParseException + - ``call_during_try`` = boolean to indicate if this method should be called during internal tryParse calls, + default=False + + Example: + + .. doctest:: + :options: +NORMALIZE_WHITESPACE + + >>> integer = Word(nums).set_parse_action(lambda toks: int(toks[0])) + >>> year_int = integer.copy().add_condition( + ... lambda toks: toks[0] >= 2000, + ... message="Only support years 2000 and later") + >>> date_str = year_int + '/' + integer + '/' + integer + + >>> result = date_str.parse_string("1999/12/31") + Traceback (most recent call last): + ParseException: Only support years 2000 and later... + """ + callDuringTry: bool = deprecate_argument(kwargs, "callDuringTry", False) + + for fn in fns: + self.parseAction.append( + condition_as_parse_action( + fn, + message=str(kwargs.get("message")), + fatal=bool(kwargs.get("fatal", False)), + ) + ) + + self.callDuringTry = self.callDuringTry or call_during_try or callDuringTry + return self + + def set_fail_action(self, fn: ParseFailAction) -> ParserElement: + """ + Define action to perform if parsing fails at this expression. + Fail acton fn is a callable function that takes the arguments + ``fn(s, loc, expr, err)`` where: + + - ``s`` = string being parsed + - ``loc`` = location where expression match was attempted and failed + - ``expr`` = the parse expression that failed + - ``err`` = the exception thrown + + The function returns no value. It may throw :class:`ParseFatalException` + if it is desired to stop parsing immediately.""" + self.failAction = fn + return self + + def _skipIgnorables(self, instring: str, loc: int) -> int: + if not self.ignoreExprs: + return loc + exprsFound = True + ignore_expr_fns = [e._parse for e in self.ignoreExprs] + last_loc = loc + while exprsFound: + exprsFound = False + for ignore_fn in ignore_expr_fns: + try: + while 1: + loc, dummy = ignore_fn(instring, loc) + exprsFound = True + except ParseException: + pass + # check if all ignore exprs matched but didn't actually advance the parse location + if loc == last_loc: + break + last_loc = loc + return loc + + def preParse(self, instring: str, loc: int) -> int: + if self.ignoreExprs: + loc = self._skipIgnorables(instring, loc) + + if self.skipWhitespace: + instrlen = len(instring) + white_chars = self.whiteChars + while loc < instrlen and instring[loc] in white_chars: + loc += 1 + + return loc + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + return loc, [] + + def postParse(self, instring, loc, tokenlist): + return tokenlist + + # @profile + def _parseNoCache( + self, instring, loc, do_actions=True, callPreParse=True + ) -> tuple[int, ParseResults]: + debugging = self.debug # and do_actions) + len_instring = len(instring) + + if debugging or self.failAction: + # print("Match {} at loc {}({}, {})".format(self, loc, lineno(loc, instring), col(loc, instring))) + try: + if callPreParse and self.callPreparse: + pre_loc = self.preParse(instring, loc) + else: + pre_loc = loc + tokens_start = pre_loc + if self.debugActions.debug_try: + self.debugActions.debug_try(instring, tokens_start, self, False) + if self.mayIndexError or pre_loc >= len_instring: + try: + loc, tokens = self.parseImpl(instring, pre_loc, do_actions) + except IndexError: + raise ParseException(instring, len_instring, self.errmsg, self) + else: + loc, tokens = self.parseImpl(instring, pre_loc, do_actions) + except Exception as err: + # print("Exception raised:", err) + if self.debugActions.debug_fail: + self.debugActions.debug_fail( + instring, tokens_start, self, err, False + ) + if self.failAction: + self.failAction(instring, tokens_start, self, err) + raise + else: + if callPreParse and self.callPreparse: + pre_loc = self.preParse(instring, loc) + else: + pre_loc = loc + tokens_start = pre_loc + if self.mayIndexError or pre_loc >= len_instring: + try: + loc, tokens = self.parseImpl(instring, pre_loc, do_actions) + except IndexError: + raise ParseException(instring, len_instring, self.errmsg, self) + else: + loc, tokens = self.parseImpl(instring, pre_loc, do_actions) + + tokens = self.postParse(instring, loc, tokens) + + ret_tokens = ParseResults( + tokens, self.resultsName, aslist=self.saveAsList, modal=self.modalResults + ) + if self.parseAction and (do_actions or self.callDuringTry): + if debugging: + try: + for fn in self.parseAction: + try: + tokens = fn(instring, tokens_start, ret_tokens) # type: ignore [call-arg, arg-type] + except IndexError as parse_action_exc: + exc = ParseException("exception raised in parse action") + raise exc from parse_action_exc + + if tokens is not None and tokens is not ret_tokens: + ret_tokens = ParseResults( + tokens, + self.resultsName, + aslist=self.saveAsList + and isinstance(tokens, (ParseResults, list)), + modal=self.modalResults, + ) + except Exception as err: + # print "Exception raised in user parse action:", err + if self.debugActions.debug_fail: + self.debugActions.debug_fail( + instring, tokens_start, self, err, False + ) + raise + else: + for fn in self.parseAction: + try: + tokens = fn(instring, tokens_start, ret_tokens) # type: ignore [call-arg, arg-type] + except IndexError as parse_action_exc: + exc = ParseException("exception raised in parse action") + raise exc from parse_action_exc + + if tokens is not None and tokens is not ret_tokens: + ret_tokens = ParseResults( + tokens, + self.resultsName, + aslist=self.saveAsList + and isinstance(tokens, (ParseResults, list)), + modal=self.modalResults, + ) + if debugging: + # print("Matched", self, "->", ret_tokens.as_list()) + if self.debugActions.debug_match: + self.debugActions.debug_match( + instring, tokens_start, loc, self, ret_tokens, False + ) + + return loc, ret_tokens + + def try_parse( + self, + instring: str, + loc: int, + *, + raise_fatal: bool = False, + do_actions: bool = False, + ) -> int: + try: + return self._parse(instring, loc, do_actions=do_actions)[0] + except ParseFatalException: + if raise_fatal: + raise + raise ParseException(instring, loc, self.errmsg, self) + + def can_parse_next(self, instring: str, loc: int, do_actions: bool = False) -> bool: + try: + self.try_parse(instring, loc, do_actions=do_actions) + except (ParseException, IndexError): + return False + else: + return True + + # cache for left-recursion in Forward references + recursion_lock = RLock() + recursion_memos: collections.abc.MutableMapping[ + tuple[int, Forward, bool], tuple[int, Union[ParseResults, Exception]] + ] = {} + + class _CacheType(typing.Protocol): + """ + Class to be used for packrat and left-recursion cacheing of results + and exceptions. + """ + + not_in_cache: bool + + def get(self, *args) -> typing.Any: ... + + def set(self, *args) -> None: ... + + def clear(self) -> None: ... + + class NullCache(dict): + """ + A null cache type for initialization of the packrat_cache class variable. + If/when enable_packrat() is called, this null cache will be replaced by a + proper _CacheType class instance. + """ + + not_in_cache: bool = True + + def get(self, *args) -> typing.Any: ... + + def set(self, *args) -> None: ... + + def clear(self) -> None: ... + + # class-level argument cache for optimizing repeated calls when backtracking + # through recursive expressions + packrat_cache: _CacheType = NullCache() + packrat_cache_lock = RLock() + packrat_cache_stats = [0, 0] + + # this method gets repeatedly called during backtracking with the same arguments - + # we can cache these arguments and save ourselves the trouble of re-parsing the contained expression + def _parseCache( + self, instring, loc, do_actions=True, callPreParse=True + ) -> tuple[int, ParseResults]: + HIT, MISS = 0, 1 + lookup = (self, instring, loc, callPreParse, do_actions) + with ParserElement.packrat_cache_lock: + cache = ParserElement.packrat_cache + value = cache.get(lookup) + if value is cache.not_in_cache: + ParserElement.packrat_cache_stats[MISS] += 1 + try: + value = self._parseNoCache(instring, loc, do_actions, callPreParse) + except ParseBaseException as pe: + # cache a copy of the exception, without the traceback + cache.set(lookup, pe.__class__(*pe.args)) + raise + else: + cache.set(lookup, (value[0], value[1].copy(), loc)) + return value + else: + ParserElement.packrat_cache_stats[HIT] += 1 + if self.debug and self.debugActions.debug_try: + try: + self.debugActions.debug_try(instring, loc, self, cache_hit=True) # type: ignore [call-arg] + except TypeError: + pass + if isinstance(value, Exception): + if self.debug and self.debugActions.debug_fail: + try: + self.debugActions.debug_fail( + instring, loc, self, value, cache_hit=True # type: ignore [call-arg] + ) + except TypeError: + pass + raise value + + value = cast(tuple[int, ParseResults, int], value) + loc_, result, endloc = value[0], value[1].copy(), value[2] + if self.debug and self.debugActions.debug_match: + try: + self.debugActions.debug_match( + instring, loc_, endloc, self, result, cache_hit=True # type: ignore [call-arg] + ) + except TypeError: + pass + + return loc_, result + + _parse = _parseNoCache + + @staticmethod + def reset_cache() -> None: + """ + Clears caches used by packrat and left-recursion. + """ + with ParserElement.packrat_cache_lock: + ParserElement.packrat_cache.clear() + ParserElement.packrat_cache_stats[:] = [0] * len( + ParserElement.packrat_cache_stats + ) + ParserElement.recursion_memos.clear() + + # class attributes to keep caching status + _packratEnabled = False + _left_recursion_enabled = False + + @staticmethod + def disable_memoization() -> None: + """ + Disables active Packrat or Left Recursion parsing and their memoization + + This method also works if neither Packrat nor Left Recursion are enabled. + This makes it safe to call before activating Packrat nor Left Recursion + to clear any previous settings. + """ + with ParserElement.packrat_cache_lock: + ParserElement.reset_cache() + ParserElement._left_recursion_enabled = False + ParserElement._packratEnabled = False + ParserElement._parse = ParserElement._parseNoCache + + @staticmethod + def enable_left_recursion( + cache_size_limit: typing.Optional[int] = None, *, force=False + ) -> None: + """ + Enables "bounded recursion" parsing, which allows for both direct and indirect + left-recursion. During parsing, left-recursive :class:`Forward` elements are + repeatedly matched with a fixed recursion depth that is gradually increased + until finding the longest match. + + Example: + + .. testcode:: + + import pyparsing as pp + pp.ParserElement.enable_left_recursion() + + E = pp.Forward("E") + num = pp.Word(pp.nums) + + # match `num`, or `num '+' num`, or `num '+' num '+' num`, ... + E <<= E + '+' - num | num + + print(E.parse_string("1+2+3+4")) + + prints: + + .. testoutput:: + + ['1', '+', '2', '+', '3', '+', '4'] + + Recursion search naturally memoizes matches of ``Forward`` elements and may + thus skip reevaluation of parse actions during backtracking. This may break + programs with parse actions which rely on strict ordering of side-effects. + + Parameters: + + - ``cache_size_limit`` - (default=``None``) - memoize at most this many + ``Forward`` elements during matching; if ``None`` (the default), + memoize all ``Forward`` elements. + + Bounded Recursion parsing works similar but not identical to Packrat parsing, + thus the two cannot be used together. Use ``force=True`` to disable any + previous, conflicting settings. + """ + with ParserElement.packrat_cache_lock: + if force: + ParserElement.disable_memoization() + elif ParserElement._packratEnabled: + raise RuntimeError("Packrat and Bounded Recursion are not compatible") + if cache_size_limit is None: + ParserElement.recursion_memos = _UnboundedMemo() + elif cache_size_limit > 0: + ParserElement.recursion_memos = _LRUMemo(capacity=cache_size_limit) # type: ignore[assignment] + else: + raise NotImplementedError(f"Memo size of {cache_size_limit}") + ParserElement._left_recursion_enabled = True + + @staticmethod + def enable_packrat( + cache_size_limit: Union[int, None] = 128, *, force: bool = False + ) -> None: + """ + Enables "packrat" parsing, which adds memoizing to the parsing logic. + Repeated parse attempts at the same string location (which happens + often in many complex grammars) can immediately return a cached value, + instead of re-executing parsing/validating code. Memoizing is done of + both valid results and parsing exceptions. + + Parameters: + + - ``cache_size_limit`` - (default= ``128``) - if an integer value is provided + will limit the size of the packrat cache; if None is passed, then + the cache size will be unbounded; if 0 is passed, the cache will + be effectively disabled. + + This speedup may break existing programs that use parse actions that + have side-effects. For this reason, packrat parsing is disabled when + you first import pyparsing. To activate the packrat feature, your + program must call the class method :class:`ParserElement.enable_packrat`. + For best results, call ``enable_packrat()`` immediately after + importing pyparsing. + + .. Can't really be doctested, alas + + Example:: + + import pyparsing + pyparsing.ParserElement.enable_packrat() + + Packrat parsing works similar but not identical to Bounded Recursion parsing, + thus the two cannot be used together. Use ``force=True`` to disable any + previous, conflicting settings. + """ + with ParserElement.packrat_cache_lock: + if force: + ParserElement.disable_memoization() + elif ParserElement._left_recursion_enabled: + raise RuntimeError("Packrat and Bounded Recursion are not compatible") + + if ParserElement._packratEnabled: + return + + ParserElement._packratEnabled = True + if cache_size_limit is None: + ParserElement.packrat_cache = _UnboundedCache() + else: + ParserElement.packrat_cache = _FifoCache(cache_size_limit) + ParserElement._parse = ParserElement._parseCache + + def parse_string( + self, instring: str, parse_all: bool = False, **kwargs + ) -> ParseResults: + """ + Parse a string with respect to the parser definition. This function is intended as the primary interface to the + client code. + + :param instring: The input string to be parsed. + :param parse_all: If set, the entire input string must match the grammar. + :param parseAll: retained for pre-PEP8 compatibility, will be removed in a future release. + :raises ParseException: Raised if ``parse_all`` is set and the input string does not match the whole grammar. + :returns: the parsed data as a :class:`ParseResults` object, which may be accessed as a `list`, a `dict`, or + an object with attributes if the given parser includes results names. + + If the input string is required to match the entire grammar, ``parse_all`` flag must be set to ``True``. This + is also equivalent to ending the grammar with :class:`StringEnd`\\ (). + + To report proper column numbers, ``parse_string`` operates on a copy of the input string where all tabs are + converted to spaces (8 spaces per tab, as per the default in ``string.expandtabs``). If the input string + contains tabs and the grammar uses parse actions that use the ``loc`` argument to index into the string + being parsed, one can ensure a consistent view of the input string by doing one of the following: + + - calling ``parse_with_tabs`` on your grammar before calling ``parse_string`` (see :class:`parse_with_tabs`), + - define your parse action using the full ``(s,loc,toks)`` signature, and reference the input string using the + parse action's ``s`` argument, or + - explicitly expand the tabs in your input string before calling ``parse_string``. + + Examples: + + By default, partial matches are OK. + + .. doctest:: + + >>> res = Word('a').parse_string('aaaaabaaa') + >>> print(res) + ['aaaaa'] + + The parsing behavior varies by the inheriting class of this abstract class. Please refer to the children + directly to see more examples. + + It raises an exception if parse_all flag is set and instring does not match the whole grammar. + + .. doctest:: + + >>> res = Word('a').parse_string('aaaaabaaa', parse_all=True) + Traceback (most recent call last): + ParseException: Expected end of text, found 'b' ... + """ + parseAll: bool = deprecate_argument(kwargs, "parseAll", False) + + parse_all = parse_all or parseAll + + ParserElement.reset_cache() + if not self.streamlined: + self.streamline() + for e in self.ignoreExprs: + e.streamline() + if not self.keepTabs: + instring = instring.expandtabs() + try: + loc, tokens = self._parse(instring, 0) + if parse_all: + loc = self.preParse(instring, loc) + se = Empty() + StringEnd().set_debug(False) + se._parse(instring, loc) + except _ParseActionIndexError as pa_exc: + raise pa_exc.exc + except ParseBaseException as exc: + if ParserElement.verbose_stacktrace: + raise + + # catch and re-raise exception from here, clearing out pyparsing internal stack trace + raise exc.with_traceback(None) + else: + return tokens + + def scan_string( + self, + instring: str, + max_matches: int = _MAX_INT, + overlap: bool = False, + always_skip_whitespace=True, + *, + debug: bool = False, + **kwargs, + ) -> Generator[tuple[ParseResults, int, int], None, None]: + """ + Scan the input string for expression matches. Each match will return the + matching tokens, start location, and end location. May be called with optional + ``max_matches`` argument, to clip scanning after 'n' matches are found. If + ``overlap`` is specified, then overlapping matches will be reported. + + Note that the start and end locations are reported relative to the string + being parsed. See :class:`parse_string` for more information on parsing + strings with embedded tabs. + + Example: + + .. testcode:: + + source = "sldjf123lsdjjkf345sldkjf879lkjsfd987" + print(source) + for tokens, start, end in Word(alphas).scan_string(source): + print(' '*start + '^'*(end-start)) + print(' '*start + tokens[0]) + + prints: + + .. testoutput:: + + sldjf123lsdjjkf345sldkjf879lkjsfd987 + ^^^^^ + sldjf + ^^^^^^^ + lsdjjkf + ^^^^^^ + sldkjf + ^^^^^^ + lkjsfd + """ + maxMatches: int = deprecate_argument(kwargs, "maxMatches", _MAX_INT) + + max_matches = min(maxMatches, max_matches) + if not self.streamlined: + self.streamline() + for e in self.ignoreExprs: + e.streamline() + + if not self.keepTabs: + instring = str(instring).expandtabs() + instrlen = len(instring) + loc = 0 + if always_skip_whitespace: + preparser = Empty() + preparser.ignoreExprs = self.ignoreExprs + preparser.whiteChars = self.whiteChars + preparseFn = preparser.preParse + else: + preparseFn = self.preParse + parseFn = self._parse + ParserElement.reset_cache() + matches = 0 + try: + while loc <= instrlen and matches < max_matches: + try: + preloc: int = preparseFn(instring, loc) + nextLoc: int + tokens: ParseResults + nextLoc, tokens = parseFn(instring, preloc, callPreParse=False) + except ParseException: + loc = preloc + 1 + else: + if nextLoc > loc: + matches += 1 + if debug: + print( + { + "tokens": tokens.as_list(), + "start": preloc, + "end": nextLoc, + } + ) + yield tokens, preloc, nextLoc + if overlap: + nextloc = preparseFn(instring, loc) + if nextloc > loc: + loc = nextLoc + else: + loc += 1 + else: + loc = nextLoc + else: + loc = preloc + 1 + except ParseBaseException as exc: + if ParserElement.verbose_stacktrace: + raise + + # catch and re-raise exception from here, clears out pyparsing internal stack trace + raise exc.with_traceback(None) + + def transform_string(self, instring: str, *, debug: bool = False) -> str: + """ + Extension to :class:`scan_string`, to modify matching text with modified tokens that may + be returned from a parse action. To use ``transform_string``, define a grammar and + attach a parse action to it that modifies the returned token list. + Invoking ``transform_string()`` on a target string will then scan for matches, + and replace the matched text patterns according to the logic in the parse + action. ``transform_string()`` returns the resulting transformed string. + + Example: + + .. testcode:: + + quote = '''now is the winter of our discontent, + made glorious summer by this sun of york.''' + + wd = Word(alphas) + wd.set_parse_action(lambda toks: toks[0].title()) + + print(wd.transform_string(quote)) + + prints: + + .. testoutput:: + + Now Is The Winter Of Our Discontent, + Made Glorious Summer By This Sun Of York. + """ + out: list[str] = [] + lastE = 0 + # force preservation of s, to minimize unwanted transformation of string, and to + # keep string locs straight between transform_string and scan_string + self.keepTabs = True + try: + for t, s, e in self.scan_string(instring, debug=debug): + if s > lastE: + out.append(instring[lastE:s]) + lastE = e + + if not t: + continue + + if isinstance(t, ParseResults): + out += t.as_list() + elif isinstance(t, Iterable) and not isinstance(t, str_type): + out.extend(t) + else: + out.append(t) + + out.append(instring[lastE:]) + out = [o for o in out if o] + return "".join([str(s) for s in _flatten(out)]) + except ParseBaseException as exc: + if ParserElement.verbose_stacktrace: + raise + + # catch and re-raise exception from here, clears out pyparsing internal stack trace + raise exc.with_traceback(None) + + def search_string( + self, + instring: str, + max_matches: int = _MAX_INT, + *, + debug: bool = False, + **kwargs, + ) -> ParseResults: + """ + Another extension to :class:`scan_string`, simplifying the access to the tokens found + to match the given parse expression. May be called with optional + ``max_matches`` argument, to clip searching after 'n' matches are found. + + Example: + + .. testcode:: + + quote = '''More than Iron, more than Lead, + more than Gold I need Electricity''' + + # a capitalized word starts with an uppercase letter, + # followed by zero or more lowercase letters + cap_word = Word(alphas.upper(), alphas.lower()) + + print(cap_word.search_string(quote)) + + # the sum() builtin can be used to merge results + # into a single ParseResults object + print(sum(cap_word.search_string(quote))) + + prints: + + .. testoutput:: + + [['More'], ['Iron'], ['Lead'], ['Gold'], ['I'], ['Electricity']] + ['More', 'Iron', 'Lead', 'Gold', 'I', 'Electricity'] + """ + maxMatches: int = deprecate_argument(kwargs, "maxMatches", _MAX_INT) + + max_matches = min(maxMatches, max_matches) + try: + return ParseResults( + [ + t + for t, s, e in self.scan_string( + instring, + max_matches=max_matches, + always_skip_whitespace=False, + debug=debug, + ) + ] + ) + except ParseBaseException as exc: + if ParserElement.verbose_stacktrace: + raise + + # catch and re-raise exception from here, clears out pyparsing internal stack trace + raise exc.with_traceback(None) + + def split( + self, + instring: str, + maxsplit: int = _MAX_INT, + include_separators: bool = False, + **kwargs, + ) -> Generator[str, None, None]: + """ + Generator method to split a string using the given expression as a separator. + May be called with optional ``maxsplit`` argument, to limit the number of splits; + and the optional ``include_separators`` argument (default= ``False``), if the separating + matching text should be included in the split results. + + Example: + + .. testcode:: + + punc = one_of(list(".,;:/-!?")) + print(list(punc.split( + "This, this?, this sentence, is badly punctuated!"))) + + prints: + + .. testoutput:: + + ['This', ' this', '', ' this sentence', ' is badly punctuated', ''] + """ + includeSeparators: bool = deprecate_argument(kwargs, "includeSeparators", False) + + include_separators = includeSeparators or include_separators + last = 0 + for t, s, e in self.scan_string(instring, max_matches=maxsplit): + yield instring[last:s] + if include_separators: + yield t[0] + last = e + yield instring[last:] + + def __add__(self, other) -> ParserElement: + """ + Implementation of ``+`` operator - returns :class:`And`. Adding strings to a :class:`ParserElement` + converts them to :class:`Literal`\\ s by default. + + Example: + + .. testcode:: + + greet = Word(alphas) + "," + Word(alphas) + "!" + hello = "Hello, World!" + print(hello, "->", greet.parse_string(hello)) + + prints: + + .. testoutput:: + + Hello, World! -> ['Hello', ',', 'World', '!'] + + ``...`` may be used as a parse expression as a short form of :class:`SkipTo`: + + .. testcode:: + + Literal('start') + ... + Literal('end') + + is equivalent to: + + .. testcode:: + + Literal('start') + SkipTo('end')("_skipped*") + Literal('end') + + Note that the skipped text is returned with '_skipped' as a results name, + and to support having multiple skips in the same parser, the value returned is + a list of all skipped text. + """ + if other is Ellipsis: + return _PendingSkip(self) + + if isinstance(other, str_type): + other = self._literalStringClass(other) + if not isinstance(other, ParserElement): + return NotImplemented + return And([self, other]) + + def __radd__(self, other) -> ParserElement: + """ + Implementation of ``+`` operator when left operand is not a :class:`ParserElement` + """ + if other is Ellipsis: + return SkipTo(self)("_skipped*") + self + + if isinstance(other, str_type): + other = self._literalStringClass(other) + if not isinstance(other, ParserElement): + return NotImplemented + return other + self + + def __sub__(self, other) -> ParserElement: + """ + Implementation of ``-`` operator, returns :class:`And` with error stop + """ + if isinstance(other, str_type): + other = self._literalStringClass(other) + if not isinstance(other, ParserElement): + return NotImplemented + return self + And._ErrorStop() + other + + def __rsub__(self, other) -> ParserElement: + """ + Implementation of ``-`` operator when left operand is not a :class:`ParserElement` + """ + if isinstance(other, str_type): + other = self._literalStringClass(other) + if not isinstance(other, ParserElement): + return NotImplemented + return other - self + + def __mul__(self, other) -> ParserElement: + """ + Implementation of ``*`` operator, allows use of ``expr * 3`` in place of + ``expr + expr + expr``. Expressions may also be multiplied by a 2-integer + tuple, similar to ``{min, max}`` multipliers in regular expressions. Tuples + may also include ``None`` as in: + + - ``expr*(n, None)`` or ``expr*(n, )`` is equivalent + to ``expr*n + ZeroOrMore(expr)`` + (read as "at least n instances of ``expr``") + - ``expr*(None, n)`` is equivalent to ``expr*(0, n)`` + (read as "0 to n instances of ``expr``") + - ``expr*(None, None)`` is equivalent to ``ZeroOrMore(expr)`` + - ``expr*(1, None)`` is equivalent to ``OneOrMore(expr)`` + + Note that ``expr*(None, n)`` does not raise an exception if + more than n exprs exist in the input stream; that is, + ``expr*(None, n)`` does not enforce a maximum number of expr + occurrences. If this behavior is desired, then write + ``expr*(None, n) + ~expr`` + """ + if other is Ellipsis: + other = (0, None) + elif isinstance(other, tuple) and other[:1] == (Ellipsis,): + other = ((0,) + other[1:] + (None,))[:2] + + if not isinstance(other, (int, tuple)): + return NotImplemented + + if isinstance(other, int): + minElements, optElements = other, 0 + else: + other = tuple(o if o is not Ellipsis else None for o in other) + other = (other + (None, None))[:2] + if other[0] is None: + other = (0, other[1]) + if isinstance(other[0], int) and other[1] is None: + if other[0] == 0: + return ZeroOrMore(self) + if other[0] == 1: + return OneOrMore(self) + else: + return self * other[0] + ZeroOrMore(self) + elif isinstance(other[0], int) and isinstance(other[1], int): + minElements, optElements = other + optElements -= minElements + else: + return NotImplemented + + if minElements < 0: + raise ValueError("cannot multiply ParserElement by negative value") + if optElements < 0: + raise ValueError( + "second tuple value must be greater or equal to first tuple value" + ) + if minElements == optElements == 0: + return And([]) + + if optElements: + + def makeOptionalList(n): + if n > 1: + return Opt(self + makeOptionalList(n - 1)) + else: + return Opt(self) + + if minElements: + if minElements == 1: + ret = self + makeOptionalList(optElements) + else: + ret = And([self] * minElements) + makeOptionalList(optElements) + else: + ret = makeOptionalList(optElements) + else: + if minElements == 1: + ret = self + else: + ret = And([self] * minElements) + return ret + + def __rmul__(self, other) -> ParserElement: + return self.__mul__(other) + + def __or__(self, other) -> ParserElement: + """ + Implementation of ``|`` operator - returns :class:`MatchFirst` + + .. versionchanged:: 3.1.0 + Support ``expr | ""`` as a synonym for ``Optional(expr)``. + """ + if other is Ellipsis: + return _PendingSkip(self, must_skip=True) + + if isinstance(other, str_type): + # `expr | ""` is equivalent to `Opt(expr)` + if other == "": + return Opt(self) + other = self._literalStringClass(other) + if not isinstance(other, ParserElement): + return NotImplemented + return MatchFirst([self, other]) + + def __ror__(self, other) -> ParserElement: + """ + Implementation of ``|`` operator when left operand is not a :class:`ParserElement` + """ + if isinstance(other, str_type): + other = self._literalStringClass(other) + if not isinstance(other, ParserElement): + return NotImplemented + return other | self + + def __xor__(self, other) -> ParserElement: + """ + Implementation of ``^`` operator - returns :class:`Or` + """ + if isinstance(other, str_type): + other = self._literalStringClass(other) + if not isinstance(other, ParserElement): + return NotImplemented + return Or([self, other]) + + def __rxor__(self, other) -> ParserElement: + """ + Implementation of ``^`` operator when left operand is not a :class:`ParserElement` + """ + if isinstance(other, str_type): + other = self._literalStringClass(other) + if not isinstance(other, ParserElement): + return NotImplemented + return other ^ self + + def __and__(self, other) -> ParserElement: + """ + Implementation of ``&`` operator - returns :class:`Each` + """ + if isinstance(other, str_type): + other = self._literalStringClass(other) + if not isinstance(other, ParserElement): + return NotImplemented + return Each([self, other]) + + def __rand__(self, other) -> ParserElement: + """ + Implementation of ``&`` operator when left operand is not a :class:`ParserElement` + """ + if isinstance(other, str_type): + other = self._literalStringClass(other) + if not isinstance(other, ParserElement): + return NotImplemented + return other & self + + def __invert__(self) -> ParserElement: + """ + Implementation of ``~`` operator - returns :class:`NotAny` + """ + return NotAny(self) + + # disable __iter__ to override legacy use of sequential access to __getitem__ to + # iterate over a sequence + __iter__ = None + + def __getitem__(self, key): + """ + use ``[]`` indexing notation as a short form for expression repetition: + + - ``expr[n]`` is equivalent to ``expr*n`` + - ``expr[m, n]`` is equivalent to ``expr*(m, n)`` + - ``expr[n, ...]`` or ``expr[n,]`` is equivalent + to ``expr*n + ZeroOrMore(expr)`` + (read as "at least n instances of ``expr``") + - ``expr[..., n]`` is equivalent to ``expr*(0, n)`` + (read as "0 to n instances of ``expr``") + - ``expr[...]`` and ``expr[0, ...]`` are equivalent to ``ZeroOrMore(expr)`` + - ``expr[1, ...]`` is equivalent to ``OneOrMore(expr)`` + + ``None`` may be used in place of ``...``. + + Note that ``expr[..., n]`` and ``expr[m, n]`` do not raise an exception + if more than ``n`` ``expr``\\ s exist in the input stream. If this behavior is + desired, then write ``expr[..., n] + ~expr``. + + For repetition with a stop_on expression, use slice notation: + + - ``expr[...: end_expr]`` and ``expr[0, ...: end_expr]`` are equivalent to ``ZeroOrMore(expr, stop_on=end_expr)`` + - ``expr[1, ...: end_expr]`` is equivalent to ``OneOrMore(expr, stop_on=end_expr)`` + + .. versionchanged:: 3.1.0 + Support for slice notation. + """ + + stop_on_defined = False + stop_on = NoMatch() + if isinstance(key, slice): + key, stop_on = key.start, key.stop + if key is None: + key = ... + stop_on_defined = True + elif isinstance(key, tuple) and isinstance(key[-1], slice): + key, stop_on = (key[0], key[1].start), key[1].stop + stop_on_defined = True + + # convert single arg keys to tuples + if isinstance(key, str_type): + key = (key,) + try: + iter(key) + except TypeError: + key = (key, key) + + if len(key) > 2: + raise TypeError( + f"only 1 or 2 index arguments supported ({key[:5]}{f'... [{len(key)}]' if len(key) > 5 else ''})" + ) + + # clip to 2 elements + ret = self * tuple(key[:2]) + ret = typing.cast(_MultipleMatch, ret) + + if stop_on_defined: + ret.stopOn(stop_on) + + return ret + + def __call__(self, name: typing.Optional[str] = None) -> ParserElement: + """ + Shortcut for :class:`set_results_name`, with ``list_all_matches=False``. + + If ``name`` is given with a trailing ``'*'`` character, then ``list_all_matches`` will be + passed as ``True``. + + If ``name`` is omitted, same as calling :class:`copy`. + + Example: + + .. testcode:: + + # these are equivalent + userdata = ( + Word(alphas).set_results_name("name") + + Word(nums + "-").set_results_name("socsecno") + ) + + userdata = Word(alphas)("name") + Word(nums + "-")("socsecno") + """ + if name is not None: + return self._setResultsName(name) + + return self.copy() + + def suppress(self) -> ParserElement: + """ + Suppresses the output of this :class:`ParserElement`; useful to keep punctuation from + cluttering up returned output. + """ + return Suppress(self) + + def ignore_whitespace(self, recursive: bool = True) -> ParserElement: + """ + Enables the skipping of whitespace before matching the characters in the + :class:`ParserElement`'s defined pattern. + + :param recursive: If ``True`` (the default), also enable whitespace skipping in child elements (if any) + """ + self.skipWhitespace = True + return self + + def leave_whitespace(self, recursive: bool = True) -> ParserElement: + """ + Disables the skipping of whitespace before matching the characters in the + :class:`ParserElement`'s defined pattern. This is normally only used internally by + the pyparsing module, but may be needed in some whitespace-sensitive grammars. + + :param recursive: If true (the default), also disable whitespace skipping in child elements (if any) + """ + self.skipWhitespace = False + return self + + def set_whitespace_chars( + self, chars: Union[set[str], str], copy_defaults: bool = False + ) -> ParserElement: + """ + Overrides the default whitespace chars + """ + self.skipWhitespace = True + self.whiteChars = set(chars) + self.copyDefaultWhiteChars = copy_defaults + return self + + def parse_with_tabs(self) -> ParserElement: + """ + Overrides default behavior to expand ```` s to spaces before parsing the input string. + Must be called before ``parse_string`` when the input grammar contains elements that + match ```` characters. + """ + self.keepTabs = True + return self + + def ignore(self, other: ParserElement) -> ParserElement: + """ + Define expression to be ignored (e.g., comments) while doing pattern + matching; may be called repeatedly, to define multiple comment or other + ignorable patterns. + + Example: + + .. doctest:: + + >>> patt = Word(alphas)[...] + >>> print(patt.parse_string('ablaj /* comment */ lskjd')) + ['ablaj'] + + >>> patt = Word(alphas)[...].ignore(c_style_comment) + >>> print(patt.parse_string('ablaj /* comment */ lskjd')) + ['ablaj', 'lskjd'] + """ + if isinstance(other, str_type): + other = Suppress(other) + + if isinstance(other, Suppress): + if other not in self.ignoreExprs: + self.ignoreExprs.append(other) + else: + self.ignoreExprs.append(Suppress(other.copy())) + return self + + def set_debug_actions( + self, + start_action: DebugStartAction, + success_action: DebugSuccessAction, + exception_action: DebugExceptionAction, + ) -> ParserElement: + """ + Customize display of debugging messages while doing pattern matching: + + :param start_action: method to be called when an expression is about to be parsed; + should have the signature:: + + fn(input_string: str, + location: int, + expression: ParserElement, + cache_hit: bool) + + :param success_action: method to be called when an expression has successfully parsed; + should have the signature:: + + fn(input_string: str, + start_location: int, + end_location: int, + expression: ParserELement, + parsed_tokens: ParseResults, + cache_hit: bool) + + :param exception_action: method to be called when expression fails to parse; + should have the signature:: + + fn(input_string: str, + location: int, + expression: ParserElement, + exception: Exception, + cache_hit: bool) + """ + self.debugActions = self.DebugActions( + start_action or _default_start_debug_action, # type: ignore[truthy-function] + success_action or _default_success_debug_action, # type: ignore[truthy-function] + exception_action or _default_exception_debug_action, # type: ignore[truthy-function] + ) + self.debug = any(self.debugActions) + return self + + def set_debug(self, flag: bool = True, recurse: bool = False) -> ParserElement: + """ + Enable display of debugging messages while doing pattern matching. + Set ``flag`` to ``True`` to enable, ``False`` to disable. + Set ``recurse`` to ``True`` to set the debug flag on this expression and all sub-expressions. + + Example: + + .. testcode:: + + wd = Word(alphas).set_name("alphaword") + integer = Word(nums).set_name("numword") + term = wd | integer + + # turn on debugging for wd + wd.set_debug() + + term[1, ...].parse_string("abc 123 xyz 890") + + prints: + + .. testoutput:: + :options: +NORMALIZE_WHITESPACE + + Match alphaword at loc 0(1,1) + abc 123 xyz 890 + ^ + Matched alphaword -> ['abc'] + Match alphaword at loc 4(1,5) + abc 123 xyz 890 + ^ + Match alphaword failed, ParseException raised: Expected alphaword, ... + Match alphaword at loc 8(1,9) + abc 123 xyz 890 + ^ + Matched alphaword -> ['xyz'] + Match alphaword at loc 12(1,13) + abc 123 xyz 890 + ^ + Match alphaword failed, ParseException raised: Expected alphaword, ... + abc 123 xyz 890 + ^ + Match alphaword failed, ParseException raised: Expected alphaword, found end of text ... + + The output shown is that produced by the default debug actions - custom debug actions can be + specified using :meth:`set_debug_actions`. Prior to attempting + to match the ``wd`` expression, the debugging message ``"Match at loc (,)"`` + is shown. Then if the parse succeeds, a ``"Matched"`` message is shown, or an ``"Exception raised"`` + message is shown. Also note the use of :meth:`set_name` to assign a human-readable name to the expression, + which makes debugging and exception messages easier to understand - for instance, the default + name created for the :class:`Word` expression without calling :meth:`set_name` is ``"W:(A-Za-z)"``. + + .. versionchanged:: 3.1.0 + ``recurse`` argument added. + """ + if recurse: + for expr in self.visit_all(): + expr.set_debug(flag, recurse=False) + return self + + if flag: + self.set_debug_actions( + _default_start_debug_action, + _default_success_debug_action, + _default_exception_debug_action, + ) + else: + self.debug = False + return self + + @property + def default_name(self) -> str: + if self._defaultName is None: + self._defaultName = self._generateDefaultName() + return self._defaultName + + @abstractmethod + def _generateDefaultName(self) -> str: + """ + Child classes must define this method, which defines how the ``default_name`` is set. + """ + + def set_name(self, name: typing.Optional[str]) -> ParserElement: + """ + Define name for this expression, makes debugging and exception messages clearer. If + `__diag__.enable_debug_on_named_expressions` is set to True, setting a name will also + enable debug for this expression. + + If `name` is None, clears any custom name for this expression, and clears the + debug flag is it was enabled via `__diag__.enable_debug_on_named_expressions`. + + Example: + + .. doctest:: + + >>> integer = Word(nums) + >>> integer.parse_string("ABC") + Traceback (most recent call last): + ParseException: Expected W:(0-9) (at char 0), (line:1, col:1) + + >>> integer.set_name("integer") + integer + >>> integer.parse_string("ABC") + Traceback (most recent call last): + ParseException: Expected integer (at char 0), (line:1, col:1) + + .. versionchanged:: 3.1.0 + Accept ``None`` as the ``name`` argument. + """ + self.customName = name # type: ignore[assignment] + self.errmsg = f"Expected {str(self)}" + + if __diag__.enable_debug_on_named_expressions: + self.set_debug(name is not None) + + return self + + @property + def name(self) -> str: + """ + Returns a user-defined name if available, but otherwise defaults back to the auto-generated name + """ + return self.customName if self.customName is not None else self.default_name + + @name.setter + def name(self, new_name) -> None: + self.set_name(new_name) + + def __str__(self) -> str: + return self.name + + def __repr__(self) -> str: + return str(self) + + def streamline(self) -> ParserElement: + self.streamlined = True + self._defaultName = None + return self + + def recurse(self) -> list[ParserElement]: + return [] + + def _checkRecursion(self, parseElementList): + subRecCheckList = parseElementList[:] + [self] + for e in self.recurse(): + e._checkRecursion(subRecCheckList) + + def validate(self, validateTrace=None) -> None: + """ + .. deprecated:: 3.0.0 + Do not use to check for left recursion. + + Check defined expressions for valid structure, check for infinite recursive definitions. + + """ + warnings.warn( + "ParserElement.validate() is deprecated, and should not be used to check for left recursion", + PyparsingDeprecationWarning, + stacklevel=2, + ) + self._checkRecursion([]) + + def parse_file( + self, + file_or_filename: Union[str, Path, TextIO], + encoding: str = "utf-8", + parse_all: bool = False, + **kwargs, + ) -> ParseResults: + """ + Execute the parse expression on the given file or filename. + If a filename is specified (instead of a file object), + the entire file is opened, read, and closed before parsing. + """ + parseAll: bool = deprecate_argument(kwargs, "parseAll", False) + + parse_all = parse_all or parseAll + try: + file_or_filename = typing.cast(TextIO, file_or_filename) + file_contents = file_or_filename.read() + except AttributeError: + file_or_filename = typing.cast(str, file_or_filename) + with open(file_or_filename, "r", encoding=encoding) as f: + file_contents = f.read() + try: + return self.parse_string(file_contents, parse_all) + except ParseBaseException as exc: + if ParserElement.verbose_stacktrace: + raise + + # catch and re-raise exception from here, clears out pyparsing internal stack trace + raise exc.with_traceback(None) + + def __eq__(self, other): + if self is other: + return True + elif isinstance(other, str_type): + return self.matches(other, parse_all=True) + elif isinstance(other, ParserElement): + return vars(self) == vars(other) + return False + + def __hash__(self): + return id(self) + + def matches(self, test_string: str, parse_all: bool = True, **kwargs) -> bool: + """ + Method for quick testing of a parser against a test string. Good for simple + inline microtests of sub expressions while building up larger parser. + + :param test_string: to test against this expression for a match + :param parse_all: flag to pass to :meth:`parse_string` when running tests + + Example: + + .. doctest:: + + >>> expr = Word(nums) + >>> expr.matches("100") + True + """ + parseAll: bool = deprecate_argument(kwargs, "parseAll", True) + + parse_all = parse_all and parseAll + try: + self.parse_string(str(test_string), parse_all=parse_all) + return True + except ParseBaseException: + return False + + def run_tests( + self, + tests: Union[str, list[str]], + parse_all: bool = True, + comment: typing.Optional[Union[ParserElement, str]] = "#", + full_dump: bool = True, + print_results: bool = True, + failure_tests: bool = False, + post_parse: typing.Optional[ + Callable[[str, ParseResults], typing.Optional[str]] + ] = None, + file: typing.Optional[TextIO] = None, + with_line_numbers: bool = False, + *, + parseAll: bool = True, + fullDump: bool = True, + printResults: bool = True, + failureTests: bool = False, + postParse: typing.Optional[ + Callable[[str, ParseResults], typing.Optional[str]] + ] = None, + ) -> tuple[bool, list[tuple[str, Union[ParseResults, Exception]]]]: + """ + Execute the parse expression on a series of test strings, showing each + test, the parsed results or where the parse failed. Quick and easy way to + run a parse expression against a list of sample strings. + + Parameters: + + - ``tests`` - a list of separate test strings, or a multiline string of test strings + - ``parse_all`` - (default= ``True``) - flag to pass to :class:`parse_string` when running tests + - ``comment`` - (default= ``'#'``) - expression for indicating embedded comments in the test + string; pass None to disable comment filtering + - ``full_dump`` - (default= ``True``) - dump results as list followed by results names in nested outline; + if False, only dump nested list + - ``print_results`` - (default= ``True``) prints test output to stdout + - ``failure_tests`` - (default= ``False``) indicates if these tests are expected to fail parsing + - ``post_parse`` - (default= ``None``) optional callback for successful parse results; called as + `fn(test_string, parse_results)` and returns a string to be added to the test output + - ``file`` - (default= ``None``) optional file-like object to which test output will be written; + if None, will default to ``sys.stdout`` + - ``with_line_numbers`` - default= ``False``) show test strings with line and column numbers + + Returns: a (success, results) tuple, where success indicates that all tests succeeded + (or failed if ``failure_tests`` is True), and the results contain a list of lines of each + test's output + + Passing example: + + .. testcode:: + + number_expr = pyparsing_common.number.copy() + + result = number_expr.run_tests(''' + # unsigned integer + 100 + # negative integer + -100 + # float with scientific notation + 6.02e23 + # integer with scientific notation + 1e-12 + # negative decimal number without leading digit + -.100 + ''') + print("Success" if result[0] else "Failed!") + + prints: + + .. testoutput:: + :options: +NORMALIZE_WHITESPACE + + + # unsigned integer + 100 + [100] + + # negative integer + -100 + [-100] + + # float with scientific notation + 6.02e23 + [6.02e+23] + + # integer with scientific notation + 1e-12 + [1e-12] + + # negative decimal number without leading digit + -.100 + [-0.1] + Success + + Failure-test example: + + .. testcode:: + + result = number_expr.run_tests(''' + # stray character + 100Z + # too many '.' + 3.14.159 + ''', failure_tests=True) + print("Success" if result[0] else "Failed!") + + prints: + + .. testoutput:: + :options: +NORMALIZE_WHITESPACE + + + # stray character + 100Z + 100Z + ^ + ParseException: Expected end of text, found 'Z' ... + + # too many '.' + 3.14.159 + 3.14.159 + ^ + ParseException: Expected end of text, found '.' ... + FAIL: Expected end of text, found '.' ... + Success + + Each test string must be on a single line. If you want to test a string that spans multiple + lines, create a test like this: + + .. testcode:: + + expr = Word(alphanums)[1,...] + expr.run_tests(r"this is a test\\n of strings that spans \\n 3 lines") + + .. testoutput:: + :options: +NORMALIZE_WHITESPACE + :hide: + + + this is a test\\n of strings that spans \\n 3 lines + ['this', 'is', 'a', 'test', 'of', 'strings', 'that', 'spans', '3', 'lines'] + + (Note that this is a raw string literal, you must include the leading ``'r'``.) + """ + from .testing import pyparsing_test + + parseAll = parseAll and parse_all + fullDump = fullDump and full_dump + printResults = printResults and print_results + failureTests = failureTests or failure_tests + postParse = postParse or post_parse + if isinstance(tests, str_type): + tests = typing.cast(str, tests) + line_strip = type(tests).strip + tests = [line_strip(test_line) for test_line in tests.rstrip().splitlines()] + comment_specified = comment is not None + if comment_specified: + if isinstance(comment, str_type): + comment = typing.cast(str, comment) + comment = Literal(comment) + comment = typing.cast(ParserElement, comment) + if file is None: + file = sys.stdout + print_ = file.write + + result: Union[ParseResults, Exception] + allResults: list[tuple[str, Union[ParseResults, Exception]]] = [] + comments: list[str] = [] + success = True + NL = Literal(r"\n").add_parse_action(replace_with("\n")).ignore(quoted_string) + BOM = "\ufeff" + nlstr = "\n" + for t in tests: + if comment_specified and comment.matches(t, False) or comments and not t: + comments.append( + pyparsing_test.with_line_numbers(t) if with_line_numbers else t + ) + continue + if not t: + continue + out = [ + f"{nlstr}{nlstr.join(comments) if comments else ''}", + pyparsing_test.with_line_numbers(t) if with_line_numbers else t, + ] + comments.clear() + try: + # convert newline marks to actual newlines, and strip leading BOM if present + t = NL.transform_string(t.lstrip(BOM)) + result = self.parse_string(t, parse_all=parse_all) + except ParseBaseException as pe: + fatal = "(FATAL) " if isinstance(pe, ParseFatalException) else "" + out.append(pe.explain()) + out.append(f"FAIL: {fatal}{pe}") + if ParserElement.verbose_stacktrace: + out.extend(traceback.format_tb(pe.__traceback__)) + success = success and failureTests + result = pe + except Exception as exc: + tag = "FAIL-EXCEPTION" + + # see if this exception was raised in a parse action + tb = exc.__traceback__ + it = iter(traceback.walk_tb(tb)) + for f, line in it: + if (f.f_code.co_filename, line) == pa_call_line_synth: + next_f = next(it)[0] + tag += f" (raised in parse action {next_f.f_code.co_name!r})" + break + + out.append(f"{tag}: {type(exc).__name__}: {exc}") + if ParserElement.verbose_stacktrace: + out.extend(traceback.format_tb(exc.__traceback__)) + success = success and failureTests + result = exc + else: + success = success and not failureTests + if postParse is not None: + try: + pp_value = postParse(t, result) + if pp_value is not None: + if isinstance(pp_value, ParseResults): + out.append(pp_value.dump()) + else: + out.append(str(pp_value)) + else: + out.append(result.dump()) + except Exception as e: + out.append(result.dump(full=fullDump)) + out.append( + f"{postParse.__name__} failed: {type(e).__name__}: {e}" + ) + else: + out.append(result.dump(full=fullDump)) + out.append("") + + if printResults: + print_("\n".join(out)) + + allResults.append((t, result)) + + return success, allResults + + def create_diagram( + self, + output_html: Union[TextIO, Path, str], + vertical: int = 3, + show_results_names: bool = False, + show_groups: bool = False, + embed: bool = False, + show_hidden: bool = False, + **kwargs, + ) -> None: + """ + Create a railroad diagram for the parser. + + Parameters: + + - ``output_html`` (str or file-like object) - output target for generated + diagram HTML + - ``vertical`` (int) - threshold for formatting multiple alternatives vertically + instead of horizontally (default=3) + - ``show_results_names`` - bool flag whether diagram should show annotations for + defined results names + - ``show_groups`` - bool flag whether groups should be highlighted with an unlabeled surrounding box + - ``show_hidden`` - bool flag to show diagram elements for internal elements that are usually hidden + - ``embed`` - bool flag whether generated HTML should omit , , and tags to embed + the resulting HTML in an enclosing HTML source + - ``head`` - str containing additional HTML to insert into the section of the generated code; + can be used to insert custom CSS styling + - ``body`` - str containing additional HTML to insert at the beginning of the section of the + generated code + + Additional diagram-formatting keyword arguments can also be included; + see railroad.Diagram class. + + .. versionchanged:: 3.1.0 + ``embed`` argument added. + """ + + try: + from .diagram import to_railroad, railroad_to_html + except ImportError as ie: + raise Exception( + "must ``pip install pyparsing[diagrams]`` to generate parser railroad diagrams" + ) from ie + + self.streamline() + + railroad = to_railroad( + self, + vertical=vertical, + show_results_names=show_results_names, + show_groups=show_groups, + show_hidden=show_hidden, + diagram_kwargs=kwargs, + ) + if not isinstance(output_html, (str, Path)): + # we were passed a file-like object, just write to it + output_html.write(railroad_to_html(railroad, embed=embed, **kwargs)) + return + + with open(output_html, "w", encoding="utf-8") as diag_file: + diag_file.write(railroad_to_html(railroad, embed=embed, **kwargs)) + + # Compatibility synonyms + # fmt: off + inlineLiteralsUsing = staticmethod(replaced_by_pep8("inlineLiteralsUsing", inline_literals_using)) + setDefaultWhitespaceChars = staticmethod(replaced_by_pep8( + "setDefaultWhitespaceChars", set_default_whitespace_chars + )) + disableMemoization = staticmethod(replaced_by_pep8("disableMemoization", disable_memoization)) + enableLeftRecursion = staticmethod(replaced_by_pep8("enableLeftRecursion", enable_left_recursion)) + enablePackrat = staticmethod(replaced_by_pep8("enablePackrat", enable_packrat)) + resetCache = staticmethod(replaced_by_pep8("resetCache", reset_cache)) + + setResultsName = replaced_by_pep8("setResultsName", set_results_name) + setBreak = replaced_by_pep8("setBreak", set_break) + setParseAction = replaced_by_pep8("setParseAction", set_parse_action) + addParseAction = replaced_by_pep8("addParseAction", add_parse_action) + addCondition = replaced_by_pep8("addCondition", add_condition) + setFailAction = replaced_by_pep8("setFailAction", set_fail_action) + tryParse = replaced_by_pep8("tryParse", try_parse) + parseString = replaced_by_pep8("parseString", parse_string) + scanString = replaced_by_pep8("scanString", scan_string) + transformString = replaced_by_pep8("transformString", transform_string) + searchString = replaced_by_pep8("searchString", search_string) + ignoreWhitespace = replaced_by_pep8("ignoreWhitespace", ignore_whitespace) + leaveWhitespace = replaced_by_pep8("leaveWhitespace", leave_whitespace) + setWhitespaceChars = replaced_by_pep8("setWhitespaceChars", set_whitespace_chars) + parseWithTabs = replaced_by_pep8("parseWithTabs", parse_with_tabs) + setDebugActions = replaced_by_pep8("setDebugActions", set_debug_actions) + setDebug = replaced_by_pep8("setDebug", set_debug) + setName = replaced_by_pep8("setName", set_name) + parseFile = replaced_by_pep8("parseFile", parse_file) + runTests = replaced_by_pep8("runTests", run_tests) + canParseNext = replaced_by_pep8("canParseNext", can_parse_next) + defaultName = default_name + # fmt: on + + +class _PendingSkip(ParserElement): + # internal placeholder class to hold a place were '...' is added to a parser element, + # once another ParserElement is added, this placeholder will be replaced with a SkipTo + def __init__(self, expr: ParserElement, must_skip: bool = False) -> None: + super().__init__() + self.anchor = expr + self.must_skip = must_skip + + def _generateDefaultName(self) -> str: + return str(self.anchor + Empty()).replace("Empty", "...") + + def __add__(self, other) -> ParserElement: + skipper = SkipTo(other).set_name("...")("_skipped*") + if self.must_skip: + + def must_skip(t): + if not t._skipped or t._skipped.as_list() == [""]: + del t[0] + t.pop("_skipped", None) + + def show_skip(t): + if t._skipped.as_list()[-1:] == [""]: + t.pop("_skipped") + t["_skipped"] = f"missing <{self.anchor!r}>" + + return ( + self.anchor + skipper().add_parse_action(must_skip) + | skipper().add_parse_action(show_skip) + ) + other + + return self.anchor + skipper + other + + def __repr__(self): + return self.defaultName + + def parseImpl(self, *args) -> ParseImplReturnType: + raise Exception( + "use of `...` expression without following SkipTo target expression" + ) + + +class Token(ParserElement): + """Abstract :class:`ParserElement` subclass, for defining atomic + matching patterns. + """ + + def __init__(self) -> None: + super().__init__(savelist=False) + + def _generateDefaultName(self) -> str: + return type(self).__name__ + + +class NoMatch(Token): + """ + A token that will never match. + """ + + def __init__(self) -> None: + super().__init__() + self._may_return_empty = True + self.mayIndexError = False + self.errmsg = "Unmatchable token" + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + raise ParseException(instring, loc, self.errmsg, self) + + +class Literal(Token): + """ + Token to exactly match a specified string. + + Example: + + .. doctest:: + + >>> Literal('abc').parse_string('abc') + ParseResults(['abc'], {}) + >>> Literal('abc').parse_string('abcdef') + ParseResults(['abc'], {}) + >>> Literal('abc').parse_string('ab') + Traceback (most recent call last): + ParseException: Expected 'abc', found 'ab' (at char 0), (line: 1, col: 1) + + For case-insensitive matching, use :class:`CaselessLiteral`. + + For keyword matching (force word break before and after the matched string), + use :class:`Keyword` or :class:`CaselessKeyword`. + """ + + def __new__(cls, match_string: str = "", **kwargs): + # Performance tuning: select a subclass with optimized parseImpl + if cls is Literal: + matchString: str = deprecate_argument(kwargs, "matchString", "") + + match_string = matchString or match_string + if not match_string: + return super().__new__(Empty) + if len(match_string) == 1: + return super().__new__(_SingleCharLiteral) + + # Default behavior + return super().__new__(cls) + + # Needed to make copy.copy() work correctly if we customize __new__ + def __getnewargs__(self): + return (self.match,) + + def __init__(self, match_string: str = "", **kwargs) -> None: + matchString: str = deprecate_argument(kwargs, "matchString", "") + + super().__init__() + match_string = matchString or match_string + self.match = match_string + self.matchLen = len(match_string) + self.firstMatchChar = match_string[:1] + self.errmsg = f"Expected {self.name}" + self._may_return_empty = False + self.mayIndexError = False + + def _generateDefaultName(self) -> str: + return repr(self.match) + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + if instring[loc] == self.firstMatchChar and instring.startswith( + self.match, loc + ): + return loc + self.matchLen, self.match + raise ParseException(instring, loc, self.errmsg, self) + + +class Empty(Literal): + """ + An empty token, will always match. + """ + + def __init__(self, match_string="", *, matchString="") -> None: + super().__init__("") + self._may_return_empty = True + self.mayIndexError = False + + def _generateDefaultName(self) -> str: + return "Empty" + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + return loc, [] + + +class _SingleCharLiteral(Literal): + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + if instring[loc] == self.firstMatchChar: + return loc + 1, self.match + raise ParseException(instring, loc, self.errmsg, self) + + +ParserElement._literalStringClass = Literal + + +class Keyword(Token): + """ + Token to exactly match a specified string as a keyword, that is, + it must be immediately preceded and followed by whitespace or + non-keyword characters. Compare with :class:`Literal`: + + - ``Literal("if")`` will match the leading ``'if'`` in + ``'ifAndOnlyIf'``. + - ``Keyword("if")`` will not; it will only match the leading + ``'if'`` in ``'if x=1'``, or ``'if(y==2)'`` + + Accepts two optional constructor arguments in addition to the + keyword string: + + - ``ident_chars`` is a string of characters that would be valid + identifier characters, defaulting to all alphanumerics + "_" and + "$" + - ``caseless`` allows case-insensitive matching, default is ``False``. + + Example: + + .. doctest:: + :options: +NORMALIZE_WHITESPACE + + >>> Keyword("start").parse_string("start") + ParseResults(['start'], {}) + >>> Keyword("start").parse_string("starting") + Traceback (most recent call last): + ParseException: Expected Keyword 'start', keyword was immediately + followed by keyword character, found 'ing' (at char 5), (line:1, col:6) + + .. doctest:: + :options: +NORMALIZE_WHITESPACE + + >>> Keyword("start").parse_string("starting").debug() + Traceback (most recent call last): + ParseException: Expected Keyword "start", keyword was immediately + followed by keyword character, found 'ing' ... + + For case-insensitive matching, use :class:`CaselessKeyword`. + """ + + DEFAULT_KEYWORD_CHARS = alphanums + "_$" + + def __init__( + self, + match_string: str = "", + ident_chars: typing.Optional[str] = None, + caseless: bool = False, + **kwargs, + ) -> None: + matchString = deprecate_argument(kwargs, "matchString", "") + identChars = deprecate_argument(kwargs, "identChars", None) + + super().__init__() + identChars = identChars or ident_chars + if identChars is None: + identChars = Keyword.DEFAULT_KEYWORD_CHARS + match_string = matchString or match_string + self.match = match_string + self.matchLen = len(match_string) + self.firstMatchChar = match_string[:1] + if not self.firstMatchChar: + raise ValueError("null string passed to Keyword; use Empty() instead") + self.errmsg = f"Expected {type(self).__name__} {self.name}" + self._may_return_empty = False + self.mayIndexError = False + self.caseless = caseless + if caseless: + self.caselessmatch = match_string.upper() + identChars = identChars.upper() + self.ident_chars = set(identChars) + + @property + def identChars(self) -> set[str]: + """ + .. deprecated:: 3.3.0 + use ident_chars instead. + + Property returning the characters being used as keyword characters for this expression. + """ + return self.ident_chars + + def _generateDefaultName(self) -> str: + return repr(self.match) + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + errmsg = self.errmsg or "" + errloc = loc + if self.caseless: + if instring[loc : loc + self.matchLen].upper() == self.caselessmatch: + if loc == 0 or instring[loc - 1].upper() not in self.identChars: + if ( + loc >= len(instring) - self.matchLen + or instring[loc + self.matchLen].upper() not in self.identChars + ): + return loc + self.matchLen, self.match + + # followed by keyword char + errmsg += ", was immediately followed by keyword character" + errloc = loc + self.matchLen + else: + # preceded by keyword char + errmsg += ", keyword was immediately preceded by keyword character" + errloc = loc - 1 + # else no match just raise plain exception + + elif ( + instring[loc] == self.firstMatchChar + and self.matchLen == 1 + or instring.startswith(self.match, loc) + ): + if loc == 0 or instring[loc - 1] not in self.identChars: + if ( + loc >= len(instring) - self.matchLen + or instring[loc + self.matchLen] not in self.identChars + ): + return loc + self.matchLen, self.match + + # followed by keyword char + errmsg += ", keyword was immediately followed by keyword character" + errloc = loc + self.matchLen + else: + # preceded by keyword char + errmsg += ", keyword was immediately preceded by keyword character" + errloc = loc - 1 + # else no match just raise plain exception + + raise ParseException(instring, errloc, errmsg, self) + + @staticmethod + def set_default_keyword_chars(chars) -> None: + """ + Overrides the default characters used by :class:`Keyword` expressions. + """ + Keyword.DEFAULT_KEYWORD_CHARS = chars + + # Compatibility synonyms + setDefaultKeywordChars = staticmethod( + replaced_by_pep8("setDefaultKeywordChars", set_default_keyword_chars) + ) + + +class CaselessLiteral(Literal): + """ + Token to match a specified string, ignoring case of letters. + Note: the matched results will always be in the case of the given + match string, NOT the case of the input text. + + Example: + + .. doctest:: + + >>> CaselessLiteral("CMD")[1, ...].parse_string("cmd CMD Cmd10") + ParseResults(['CMD', 'CMD', 'CMD'], {}) + + (Contrast with example for :class:`CaselessKeyword`.) + """ + + def __init__(self, match_string: str = "", **kwargs) -> None: + matchString: str = deprecate_argument(kwargs, "matchString", "") + + match_string = matchString or match_string + super().__init__(match_string.upper()) + # Preserve the defining literal. + self.returnString = match_string + self.errmsg = f"Expected {self.name}" + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + if instring[loc : loc + self.matchLen].upper() == self.match: + return loc + self.matchLen, self.returnString + raise ParseException(instring, loc, self.errmsg, self) + + +class CaselessKeyword(Keyword): + """ + Caseless version of :class:`Keyword`. + + Example: + + .. doctest:: + + >>> CaselessKeyword("CMD")[1, ...].parse_string("cmd CMD Cmd10") + ParseResults(['CMD', 'CMD'], {}) + + (Contrast with example for :class:`CaselessLiteral`.) + """ + + def __init__( + self, match_string: str = "", ident_chars: typing.Optional[str] = None, **kwargs + ) -> None: + matchString: str = deprecate_argument(kwargs, "matchString", "") + identChars: typing.Optional[str] = deprecate_argument( + kwargs, "identChars", None + ) + + identChars = identChars or ident_chars + match_string = matchString or match_string + super().__init__(match_string, identChars, caseless=True) + + +class CloseMatch(Token): + """A variation on :class:`Literal` which matches "close" matches, + that is, strings with at most 'n' mismatching characters. + :class:`CloseMatch` takes parameters: + + - ``match_string`` - string to be matched + - ``caseless`` - a boolean indicating whether to ignore casing when comparing characters + - ``max_mismatches`` - (``default=1``) maximum number of + mismatches allowed to count as a match + + The results from a successful parse will contain the matched text + from the input string and the following named results: + + - ``mismatches`` - a list of the positions within the + match_string where mismatches were found + - ``original`` - the original match_string used to compare + against the input string + + If ``mismatches`` is an empty list, then the match was an exact + match. + + Example: + + .. doctest:: + :options: +NORMALIZE_WHITESPACE + + >>> patt = CloseMatch("ATCATCGAATGGA") + >>> patt.parse_string("ATCATCGAAXGGA") + ParseResults(['ATCATCGAAXGGA'], + {'original': 'ATCATCGAATGGA', 'mismatches': [9]}) + + >>> patt.parse_string("ATCAXCGAAXGGA") + Traceback (most recent call last): + ParseException: Expected 'ATCATCGAATGGA' (with up to 1 mismatches), + found 'ATCAXCGAAXGGA' (at char 0), (line:1, col:1) + + # exact match + >>> patt.parse_string("ATCATCGAATGGA") + ParseResults(['ATCATCGAATGGA'], + {'original': 'ATCATCGAATGGA', 'mismatches': []}) + + # close match allowing up to 2 mismatches + >>> patt = CloseMatch("ATCATCGAATGGA", max_mismatches=2) + >>> patt.parse_string("ATCAXCGAAXGGA") + ParseResults(['ATCAXCGAAXGGA'], + {'original': 'ATCATCGAATGGA', 'mismatches': [4, 9]}) + """ + + def __init__( + self, + match_string: str, + max_mismatches: typing.Optional[int] = None, + *, + caseless=False, + **kwargs, + ) -> None: + maxMismatches: int = deprecate_argument(kwargs, "maxMismatches", 1) + + maxMismatches = max_mismatches if max_mismatches is not None else maxMismatches + super().__init__() + self.match_string = match_string + self.maxMismatches = maxMismatches + self.errmsg = f"Expected {self.match_string!r} (with up to {self.maxMismatches} mismatches)" + self.caseless = caseless + self.mayIndexError = False + self._may_return_empty = False + + def _generateDefaultName(self) -> str: + return f"{type(self).__name__}:{self.match_string!r}" + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + start = loc + instrlen = len(instring) + maxloc = start + len(self.match_string) + + if maxloc <= instrlen: + match_string = self.match_string + match_stringloc = 0 + mismatches = [] + maxMismatches = self.maxMismatches + + for match_stringloc, s_m in enumerate( + zip(instring[loc:maxloc], match_string) + ): + src, mat = s_m + if self.caseless: + src, mat = src.lower(), mat.lower() + + if src != mat: + mismatches.append(match_stringloc) + if len(mismatches) > maxMismatches: + break + else: + loc = start + match_stringloc + 1 + results = ParseResults([instring[start:loc]]) + results["original"] = match_string + results["mismatches"] = mismatches + return loc, results + + raise ParseException(instring, loc, self.errmsg, self) + + +class Word(Token): + """Token for matching words composed of allowed character sets. + + Parameters: + + - ``init_chars`` - string of all characters that should be used to + match as a word; "ABC" will match "AAA", "ABAB", "CBAC", etc.; + if ``body_chars`` is also specified, then this is the string of + initial characters + - ``body_chars`` - string of characters that + can be used for matching after a matched initial character as + given in ``init_chars``; if omitted, same as the initial characters + (default=``None``) + - ``min`` - minimum number of characters to match (default=1) + - ``max`` - maximum number of characters to match (default=0) + - ``exact`` - exact number of characters to match (default=0) + - ``as_keyword`` - match as a keyword (default=``False``) + - ``exclude_chars`` - characters that might be + found in the input ``body_chars`` string but which should not be + accepted for matching ;useful to define a word of all + printables except for one or two characters, for instance + (default=``None``) + + :class:`srange` is useful for defining custom character set strings + for defining :class:`Word` expressions, using range notation from + regular expression character sets. + + A common mistake is to use :class:`Word` to match a specific literal + string, as in ``Word("Address")``. Remember that :class:`Word` + uses the string argument to define *sets* of matchable characters. + This expression would match "Add", "AAA", "dAred", or any other word + made up of the characters 'A', 'd', 'r', 'e', and 's'. To match an + exact literal string, use :class:`Literal` or :class:`Keyword`. + + pyparsing includes helper strings for building Words: + + - :attr:`alphas` + - :attr:`nums` + - :attr:`alphanums` + - :attr:`hexnums` + - :attr:`alphas8bit` (alphabetic characters in ASCII range 128-255 + - accented, tilded, umlauted, etc.) + - :attr:`punc8bit` (non-alphabetic characters in ASCII range + 128-255 - currency, symbols, superscripts, diacriticals, etc.) + - :attr:`printables` (any non-whitespace character) + + ``alphas``, ``nums``, and ``printables`` are also defined in several + Unicode sets - see :class:`pyparsing_unicode`. + + Example: + + .. testcode:: + + # a word composed of digits + integer = Word(nums) + # Two equivalent alternate forms: + Word("0123456789") + Word(srange("[0-9]")) + + # a word with a leading capital, and zero or more lowercase + capitalized_word = Word(alphas.upper(), alphas.lower()) + + # hostnames are alphanumeric, with leading alpha, and '-' + hostname = Word(alphas, alphanums + '-') + + # roman numeral + # (not a strict parser, accepts invalid mix of characters) + roman = Word("IVXLCDM") + + # any string of non-whitespace characters, except for ',' + csv_value = Word(printables, exclude_chars=",") + + :raises ValueError: If ``min`` and ``max`` are both specified + and the test ``min <= max`` fails. + + .. versionchanged:: 3.1.0 + Raises :exc:`ValueError` if ``min`` > ``max``. + """ + + def __init__( + self, + init_chars: str = "", + body_chars: typing.Optional[str] = None, + min: int = 1, + max: int = 0, + exact: int = 0, + as_keyword: bool = False, + exclude_chars: typing.Optional[str] = None, + **kwargs, + ) -> None: + initChars: typing.Optional[str] = deprecate_argument(kwargs, "initChars", None) + bodyChars: typing.Optional[str] = deprecate_argument(kwargs, "bodyChars", None) + asKeyword: bool = deprecate_argument(kwargs, "asKeyword", False) + excludeChars: typing.Optional[str] = deprecate_argument( + kwargs, "excludeChars", None + ) + + initChars = initChars or init_chars + bodyChars = bodyChars or body_chars + asKeyword = asKeyword or as_keyword + excludeChars = excludeChars or exclude_chars + super().__init__() + if not initChars: + raise ValueError( + f"invalid {type(self).__name__}, initChars cannot be empty string" + ) + + initChars_set = set(initChars) + if excludeChars: + excludeChars_set = set(excludeChars) + initChars_set -= excludeChars_set + if bodyChars: + bodyChars = "".join(set(bodyChars) - excludeChars_set) + self.init_chars = initChars_set + self.initCharsOrig = "".join(sorted(initChars_set)) + + if bodyChars: + self.bodyChars = set(bodyChars) + self.bodyCharsOrig = "".join(sorted(bodyChars)) + else: + self.bodyChars = initChars_set + self.bodyCharsOrig = self.initCharsOrig + + self.maxSpecified = max > 0 + + if min < 1: + raise ValueError( + "cannot specify a minimum length < 1; use Opt(Word()) if zero-length word is permitted" + ) + + if self.maxSpecified and min > max: + raise ValueError( + f"invalid args, if min and max both specified min must be <= max (min={min}, max={max})" + ) + + self.minLen = min + + if max > 0: + self.maxLen = max + else: + self.maxLen = _MAX_INT + + if exact > 0: + min = max = exact + self.maxLen = exact + self.minLen = exact + + self.errmsg = f"Expected {self.name}" + self.mayIndexError = False + self.asKeyword = asKeyword + if self.asKeyword: + self.errmsg += " as a keyword" + + # see if we can make a regex for this Word + if " " not in (self.initChars | self.bodyChars): + if len(self.initChars) == 1: + re_leading_fragment = re.escape(self.initCharsOrig) + else: + re_leading_fragment = f"[{_collapse_string_to_ranges(self.initChars)}]" + + if self.bodyChars == self.initChars: + if max == 0 and self.minLen == 1: + repeat = "+" + elif max == 1: + repeat = "" + else: + if self.minLen != self.maxLen: + repeat = f"{{{self.minLen},{'' if self.maxLen == _MAX_INT else self.maxLen}}}" + else: + repeat = f"{{{self.minLen}}}" + self.reString = f"{re_leading_fragment}{repeat}" + else: + if max == 1: + re_body_fragment = "" + repeat = "" + else: + re_body_fragment = f"[{_collapse_string_to_ranges(self.bodyChars)}]" + if max == 0 and self.minLen == 1: + repeat = "*" + elif max == 2: + repeat = "?" if min <= 1 else "" + else: + if min != max: + repeat = f"{{{min - 1 if min > 0 else ''},{max - 1 if max > 0 else ''}}}" + else: + repeat = f"{{{min - 1 if min > 0 else ''}}}" + + self.reString = f"{re_leading_fragment}{re_body_fragment}{repeat}" + + if self.asKeyword: + self.reString = rf"\b{self.reString}\b" + + try: + self.re = re.compile(self.reString) + except re.error: + self.re = None # type: ignore[assignment] + else: + self.re_match = self.re.match + self.parseImpl = self.parseImpl_regex # type: ignore[method-assign] + + @property + def initChars(self) -> set[str]: + """ + .. deprecated:: 3.3.0 + use `init_chars` instead. + + Property returning the initial chars to be used when matching this + Word expression. If no body chars were specified, the initial characters + will also be the body characters. + """ + return set(self.init_chars) + + def copy(self) -> Word: + """ + Returns a copy of this expression. + + Generally only used internally by pyparsing. + """ + ret: Word = cast(Word, super().copy()) + if hasattr(self, "re_match"): + ret.re_match = self.re_match + ret.parseImpl = ret.parseImpl_regex # type: ignore[method-assign] + return ret + + def _generateDefaultName(self) -> str: + def charsAsStr(s): + max_repr_len = 16 + s = _collapse_string_to_ranges(s, re_escape=False) + + if len(s) > max_repr_len: + return s[: max_repr_len - 3] + "..." + + return s + + if self.initChars != self.bodyChars: + base = f"W:({charsAsStr(self.initChars)}, {charsAsStr(self.bodyChars)})" + else: + base = f"W:({charsAsStr(self.initChars)})" + + # add length specification + if self.minLen > 1 or self.maxLen != _MAX_INT: + if self.minLen == self.maxLen: + if self.minLen == 1: + return base[2:] + else: + return base + f"{{{self.minLen}}}" + elif self.maxLen == _MAX_INT: + return base + f"{{{self.minLen},...}}" + else: + return base + f"{{{self.minLen},{self.maxLen}}}" + return base + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + if instring[loc] not in self.initChars: + raise ParseException(instring, loc, self.errmsg, self) + + start = loc + loc += 1 + instrlen = len(instring) + body_chars: set[str] = self.bodyChars + maxloc = start + self.maxLen + maxloc = min(maxloc, instrlen) + while loc < maxloc and instring[loc] in body_chars: + loc += 1 + + throw_exception = False + if loc - start < self.minLen: + throw_exception = True + elif self.maxSpecified and loc < instrlen and instring[loc] in body_chars: + throw_exception = True + elif self.asKeyword and ( + (start > 0 and instring[start - 1] in body_chars) + or (loc < instrlen and instring[loc] in body_chars) + ): + throw_exception = True + + if throw_exception: + raise ParseException(instring, loc, self.errmsg, self) + + return loc, instring[start:loc] + + def parseImpl_regex(self, instring, loc, do_actions=True) -> ParseImplReturnType: + result = self.re_match(instring, loc) + if not result: + raise ParseException(instring, loc, self.errmsg, self) + + loc = result.end() + return loc, result[0] + + +class Char(Word): + """A short-cut class for defining :class:`Word` ``(characters, exact=1)``, + when defining a match of any single character in a string of + characters. + """ + + def __init__( + self, + charset: str, + as_keyword: bool = False, + exclude_chars: typing.Optional[str] = None, + **kwargs, + ) -> None: + asKeyword: bool = deprecate_argument(kwargs, "asKeyword", False) + excludeChars: typing.Optional[str] = deprecate_argument( + kwargs, "excludeChars", None + ) + + asKeyword = asKeyword or as_keyword + excludeChars = excludeChars or exclude_chars + super().__init__( + charset, exact=1, as_keyword=asKeyword, exclude_chars=excludeChars + ) + + +class Regex(Token): + r"""Token for matching strings that match a given regular + expression. Defined with string specifying the regular expression in + a form recognized by the stdlib Python `re module `_. + If the given regex contains named groups (defined using ``(?P...)``), + these will be preserved as named :class:`ParseResults`. + + If instead of the Python stdlib ``re`` module you wish to use a different RE module + (such as the ``regex`` module), you can do so by building your ``Regex`` object with + a compiled RE that was compiled using ``regex``. + + The parameters ``pattern`` and ``flags`` are passed + to the ``re.compile()`` function as-is. See the Python + `re module `_ module for an + explanation of the acceptable patterns and flags. + + Example: + + .. testcode:: + + realnum = Regex(r"[+-]?\d+\.\d*") + # ref: https://stackoverflow.com/questions/267399/how-do-you-match-only-valid-roman-numerals-with-a-regular-expression + roman = Regex(r"M{0,4}(CM|CD|D?{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})") + + # named fields in a regex will be returned as named results + date = Regex(r'(?P\d{4})-(?P\d\d?)-(?P\d\d?)') + + # the Regex class will accept regular expressions compiled using the + # re module + import re + parser = pp.Regex(re.compile(r'[0-9]')) + """ + + def __init__( + self, + pattern: Any, + flags: Union[re.RegexFlag, int] = 0, + as_group_list: bool = False, + as_match: bool = False, + **kwargs, + ) -> None: + super().__init__() + asGroupList: bool = deprecate_argument(kwargs, "asGroupList", False) + asMatch: bool = deprecate_argument(kwargs, "asMatch", False) + + asGroupList = asGroupList or as_group_list + asMatch = asMatch or as_match + + if isinstance(pattern, str_type): + if not pattern: + raise ValueError("null string passed to Regex; use Empty() instead") + + self._re = None + self._may_return_empty = None # type: ignore [assignment] + self.reString = self.pattern = pattern + + elif hasattr(pattern, "pattern") and hasattr(pattern, "match"): + self._re = pattern + self._may_return_empty = None # type: ignore [assignment] + self.pattern = self.reString = pattern.pattern + + elif callable(pattern): + # defer creating this pattern until we really need it + self.pattern = pattern + self._may_return_empty = None # type: ignore [assignment] + self._re = None + + else: + raise TypeError( + "Regex may only be constructed with a string or a compiled RE object," + " or a callable that takes no arguments and returns a string or a" + " compiled RE object" + ) + + self.flags = flags + self.errmsg = f"Expected {self.name}" + self.mayIndexError = False + self.asGroupList = asGroupList + self.asMatch = asMatch + if self.asGroupList: + self.parseImpl = self.parseImplAsGroupList # type: ignore [method-assign] + if self.asMatch: + self.parseImpl = self.parseImplAsMatch # type: ignore [method-assign] + + def copy(self) -> Regex: + """ + Returns a copy of this expression. + + Generally only used internally by pyparsing. + """ + ret: Regex = cast(Regex, super().copy()) + if self.asGroupList: + ret.parseImpl = ret.parseImplAsGroupList # type: ignore [method-assign] + if self.asMatch: + ret.parseImpl = ret.parseImplAsMatch # type: ignore [method-assign] + return ret + + @cached_property + def re(self) -> re.Pattern: + """ + Property returning the compiled regular expression for this Regex. + + Generally only used internally by pyparsing. + """ + if self._re: + return self._re + + if callable(self.pattern): + # replace self.pattern with the string returned by calling self.pattern() + self.pattern = cast(Callable[[], str], self.pattern)() + + # see if we got a compiled RE back instead of a str - if so, we're done + if hasattr(self.pattern, "pattern") and hasattr(self.pattern, "match"): + self._re = cast(re.Pattern[str], self.pattern) + self.pattern = self.reString = self._re.pattern + return self._re + + try: + self._re = re.compile(self.pattern, self.flags) + except re.error: + raise ValueError(f"invalid pattern ({self.pattern!r}) passed to Regex") + else: + self._may_return_empty = self.re.match("", pos=0) is not None + return self._re + + @cached_property + def re_match(self) -> Callable[[str, int], Any]: + return self.re.match + + @property + def mayReturnEmpty(self): + if self._may_return_empty is None: + # force compile of regex pattern, to set may_return_empty flag + self.re # noqa + return self._may_return_empty + + @mayReturnEmpty.setter + def mayReturnEmpty(self, value): + self._may_return_empty = value + + def _generateDefaultName(self) -> str: + unescaped = repr(self.pattern).replace("\\\\", "\\") + return f"Re:({unescaped})" + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + # explicit check for matching past the length of the string; + # this is done because the re module will not complain about + # a match with `pos > len(instring)`, it will just return "" + if loc > len(instring) and self.mayReturnEmpty: + raise ParseException(instring, loc, self.errmsg, self) + + result = self.re_match(instring, loc) + if not result: + raise ParseException(instring, loc, self.errmsg, self) + + loc = result.end() + ret = ParseResults(result[0]) + d = result.groupdict() + + for k, v in d.items(): + ret[k] = v + + return loc, ret + + def parseImplAsGroupList(self, instring, loc, do_actions=True): + if loc > len(instring) and self.mayReturnEmpty: + raise ParseException(instring, loc, self.errmsg, self) + + result = self.re_match(instring, loc) + if not result: + raise ParseException(instring, loc, self.errmsg, self) + + loc = result.end() + ret = result.groups() + return loc, ret + + def parseImplAsMatch(self, instring, loc, do_actions=True): + if loc > len(instring) and self.mayReturnEmpty: + raise ParseException(instring, loc, self.errmsg, self) + + result = self.re_match(instring, loc) + if not result: + raise ParseException(instring, loc, self.errmsg, self) + + loc = result.end() + ret = result + return loc, ret + + def sub(self, repl: str) -> ParserElement: + r""" + Return :class:`Regex` with an attached parse action to transform the parsed + result as if called using `re.sub(expr, repl, string) `_. + + Example: + + .. testcode:: + + make_html = Regex(r"(\w+):(.*?):").sub(r"<\1>\2") + print(make_html.transform_string("h1:main title:")) + + .. testoutput:: + +

main title

+ """ + if self.asGroupList: + raise TypeError("cannot use sub() with Regex(as_group_list=True)") + + if self.asMatch and callable(repl): + raise TypeError( + "cannot use sub() with a callable with Regex(as_match=True)" + ) + + if self.asMatch: + + def pa(tokens): + return tokens[0].expand(repl) + + else: + + def pa(tokens): + return self.re.sub(repl, tokens[0]) + + return self.add_parse_action(pa) + + +class QuotedString(Token): + r""" + Token for matching strings that are delimited by quoting characters. + + Defined with the following parameters: + + - ``quote_char`` - string of one or more characters defining the + quote delimiting string + - ``esc_char`` - character to re_escape quotes, typically backslash + (default= ``None``) + - ``esc_quote`` - special quote sequence to re_escape an embedded quote + string (such as SQL's ``""`` to re_escape an embedded ``"``) + (default= ``None``) + - ``multiline`` - boolean indicating whether quotes can span + multiple lines (default= ``False``) + - ``unquote_results`` - boolean indicating whether the matched text + should be unquoted (default= ``True``) + - ``end_quote_char`` - string of one or more characters defining the + end of the quote delimited string (default= ``None`` => same as + quote_char) + - ``convert_whitespace_escapes`` - convert escaped whitespace + (``'\t'``, ``'\n'``, etc.) to actual whitespace + (default= ``True``) + + .. caution:: ``convert_whitespace_escapes`` has no effect if + ``unquote_results`` is ``False``. + + Example: + + .. doctest:: + + >>> qs = QuotedString('"') + >>> print(qs.search_string('lsjdf "This is the quote" sldjf')) + [['This is the quote']] + >>> complex_qs = QuotedString('{{', end_quote_char='}}') + >>> print(complex_qs.search_string( + ... 'lsjdf {{This is the "quote"}} sldjf')) + [['This is the "quote"']] + >>> sql_qs = QuotedString('"', esc_quote='""') + >>> print(sql_qs.search_string( + ... 'lsjdf "This is the quote with ""embedded"" quotes" sldjf')) + [['This is the quote with "embedded" quotes']] + """ + + ws_map = dict(((r"\t", "\t"), (r"\n", "\n"), (r"\f", "\f"), (r"\r", "\r"))) + + def __init__( + self, + quote_char: str = "", + esc_char: typing.Optional[str] = None, + esc_quote: typing.Optional[str] = None, + multiline: bool = False, + unquote_results: bool = True, + end_quote_char: typing.Optional[str] = None, + convert_whitespace_escapes: bool = True, + **kwargs, + ) -> None: + super().__init__() + quoteChar: str = deprecate_argument(kwargs, "quoteChar", "") + escChar: str = deprecate_argument(kwargs, "escChar", None) + escQuote: str = deprecate_argument(kwargs, "escQuote", None) + unquoteResults: bool = deprecate_argument(kwargs, "unquoteResults", True) + endQuoteChar: typing.Optional[str] = deprecate_argument( + kwargs, "endQuoteChar", None + ) + convertWhitespaceEscapes: bool = deprecate_argument( + kwargs, "convertWhitespaceEscapes", True + ) + + esc_char = escChar or esc_char + esc_quote = escQuote or esc_quote + unquote_results = unquoteResults and unquote_results + end_quote_char = endQuoteChar or end_quote_char + convert_whitespace_escapes = ( + convertWhitespaceEscapes and convert_whitespace_escapes + ) + quote_char = quoteChar or quote_char + + # remove white space from quote chars + quote_char = quote_char.strip() + if not quote_char: + raise ValueError("quote_char cannot be the empty string") + + if end_quote_char is None: + end_quote_char = quote_char + else: + end_quote_char = end_quote_char.strip() + if not end_quote_char: + raise ValueError("end_quote_char cannot be the empty string") + + self.quote_char: str = quote_char + self.quote_char_len: int = len(quote_char) + self.first_quote_char: str = quote_char[0] + self.end_quote_char: str = end_quote_char + self.end_quote_char_len: int = len(end_quote_char) + self.esc_char: str = esc_char or "" + self.has_esc_char: bool = esc_char is not None + self.esc_quote: str = esc_quote or "" + self.unquote_results: bool = unquote_results + self.convert_whitespace_escapes: bool = convert_whitespace_escapes + self.multiline = multiline + self.re_flags = re.RegexFlag(0) + + # fmt: off + # build up re pattern for the content between the quote delimiters + inner_pattern: list[str] = [] + + if esc_quote: + inner_pattern.append(rf"(?:{re.escape(esc_quote)})") + + if esc_char: + inner_pattern.append(rf"(?:{re.escape(esc_char)}.)") + + if len(self.end_quote_char) > 1: + inner_pattern.append( + "(?:" + + "|".join( + f"(?:{re.escape(self.end_quote_char[:i])}(?!{re.escape(self.end_quote_char[i:])}))" + for i in range(len(self.end_quote_char) - 1, 0, -1) + ) + + ")" + ) + + if self.multiline: + self.re_flags |= re.MULTILINE | re.DOTALL + inner_pattern.append( + rf"(?:[^{_escape_regex_range_chars(self.end_quote_char[0])}" + rf"{(_escape_regex_range_chars(self.esc_char) if self.has_esc_char else '')}])" + ) + else: + inner_pattern.append( + rf"(?:[^{_escape_regex_range_chars(self.end_quote_char[0])}\n\r" + rf"{(_escape_regex_range_chars(self.esc_char) if self.has_esc_char else '')}])" + ) + + self.pattern = "".join( + [ + re.escape(self.quote_char), + "(?:", + '|'.join(inner_pattern), + ")*", + re.escape(self.end_quote_char), + ] + ) + + if self.unquote_results: + if self.convert_whitespace_escapes: + self.unquote_scan_re = re.compile( + rf"({'|'.join(re.escape(k) for k in self.ws_map)})" + rf"|(\\[0-7]{3}|\\0|\\x[0-9a-fA-F]{2}|\\u[0-9a-fA-F]{4})" + rf"|({re.escape(self.esc_char)}.)" + rf"|(\n|.)", + flags=self.re_flags, + ) + else: + self.unquote_scan_re = re.compile( + rf"({re.escape(self.esc_char)}.)" + rf"|(\n|.)", + flags=self.re_flags + ) + # fmt: on + + try: + self.re = re.compile(self.pattern, self.re_flags) + self.reString = self.pattern + self.re_match = self.re.match + except re.error: + raise ValueError(f"invalid pattern {self.pattern!r} passed to Regex") + + self.errmsg = f"Expected {self.name}" + self.mayIndexError = False + self._may_return_empty = True + + def _generateDefaultName(self) -> str: + if self.quote_char == self.end_quote_char and isinstance( + self.quote_char, str_type + ): + return f"string enclosed in {self.quote_char!r}" + + return f"quoted string, starting with {self.quote_char} ending with {self.end_quote_char}" + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + # check first character of opening quote to see if that is a match + # before doing the more complicated regex match + result = ( + instring[loc] == self.first_quote_char + and self.re_match(instring, loc) + or None + ) + if not result: + raise ParseException(instring, loc, self.errmsg, self) + + # get ending loc and matched string from regex matching result + loc = result.end() + ret = result[0] + + if self.unquote_results: + # strip off quotes + ret = ret[self.quote_char_len : -self.end_quote_char_len] + + if isinstance(ret, str_type): + # fmt: off + if self.convert_whitespace_escapes: + # as we iterate over matches in the input string, + # collect from whichever match group of the unquote_scan_re + # regex matches (only 1 group will match at any given time) + ret = "".join( + # match group 1 matches \t, \n, etc. + self.ws_map[g] if (g := match[1]) + # match group 2 matches escaped octal, null, hex, and Unicode + # sequences + else _convert_escaped_numerics_to_char(g[1:]) if (g := match[2]) + # match group 3 matches escaped characters + else g[-1] if (g := match[3]) + # match group 4 matches any character + else match[4] + for match in self.unquote_scan_re.finditer(ret) + ) + else: + ret = "".join( + # match group 1 matches escaped characters + g[-1] if (g := match[1]) + # match group 2 matches any character + else match[2] + for match in self.unquote_scan_re.finditer(ret) + ) + # fmt: on + + # replace escaped quotes + if self.esc_quote: + ret = ret.replace(self.esc_quote, self.end_quote_char) + + return loc, ret + + +class CharsNotIn(Token): + """Token for matching words composed of characters *not* in a given + set (will include whitespace in matched characters if not listed in + the provided exclusion set - see example). Defined with string + containing all disallowed characters, and an optional minimum, + maximum, and/or exact length. The default value for ``min`` is + 1 (a minimum value < 1 is not valid); the default values for + ``max`` and ``exact`` are 0, meaning no maximum or exact + length restriction. + + Example: + + .. testcode:: + + # define a comma-separated-value as anything that is not a ',' + csv_value = CharsNotIn(',') + print( + DelimitedList(csv_value).parse_string( + "dkls,lsdkjf,s12 34,@!#,213" + ) + ) + + prints: + + .. testoutput:: + + ['dkls', 'lsdkjf', 's12 34', '@!#', '213'] + """ + + def __init__( + self, not_chars: str = "", min: int = 1, max: int = 0, exact: int = 0, **kwargs + ) -> None: + super().__init__() + notChars: str = deprecate_argument(kwargs, "notChars", "") + + self.skipWhitespace = False + self.notChars = not_chars or notChars + self.notCharsSet = set(self.notChars) + + if min < 1: + raise ValueError( + "cannot specify a minimum length < 1; use" + " Opt(CharsNotIn()) if zero-length char group is permitted" + ) + + self.minLen = min + + if max > 0: + self.maxLen = max + else: + self.maxLen = _MAX_INT + + if exact > 0: + self.maxLen = exact + self.minLen = exact + + self.errmsg = f"Expected {self.name}" + self._may_return_empty = self.minLen == 0 + self.mayIndexError = False + + def _generateDefaultName(self) -> str: + not_chars_str = _collapse_string_to_ranges(self.notChars) + if len(not_chars_str) > 16: + return f"!W:({self.notChars[: 16 - 3]}...)" + else: + return f"!W:({self.notChars})" + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + notchars = self.notCharsSet + if instring[loc] in notchars: + raise ParseException(instring, loc, self.errmsg, self) + + start = loc + loc += 1 + maxlen = min(start + self.maxLen, len(instring)) + while loc < maxlen and instring[loc] not in notchars: + loc += 1 + + if loc - start < self.minLen: + raise ParseException(instring, loc, self.errmsg, self) + + return loc, instring[start:loc] + + +class White(Token): + """Special matching class for matching whitespace. Normally, + whitespace is ignored by pyparsing grammars. This class is included + when some whitespace structures are significant. Define with + a string containing the whitespace characters to be matched; default + is ``" \\t\\r\\n"``. Also takes optional ``min``, + ``max``, and ``exact`` arguments, as defined for the + :class:`Word` class. + """ + + whiteStrs = { + " ": "", + "\t": "", + "\n": "", + "\r": "", + "\f": "", + "\u00a0": "", + "\u1680": "", + "\u180e": "", + "\u2000": "", + "\u2001": "", + "\u2002": "", + "\u2003": "", + "\u2004": "", + "\u2005": "", + "\u2006": "", + "\u2007": "", + "\u2008": "", + "\u2009": "", + "\u200a": "", + "\u200b": "", + "\u202f": "", + "\u205f": "", + "\u3000": "", + } + + def __init__( + self, ws: str = " \t\r\n", min: int = 1, max: int = 0, exact: int = 0 + ) -> None: + super().__init__() + self.matchWhite = ws + self.set_whitespace_chars( + "".join(c for c in self.whiteStrs if c not in self.matchWhite), + copy_defaults=True, + ) + # self.leave_whitespace() + self._may_return_empty = True + self.errmsg = f"Expected {self.name}" + + self.minLen = min + + if max > 0: + self.maxLen = max + else: + self.maxLen = _MAX_INT + + if exact > 0: + self.maxLen = exact + self.minLen = exact + + def _generateDefaultName(self) -> str: + return "".join(White.whiteStrs[c] for c in self.matchWhite) + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + if instring[loc] not in self.matchWhite: + raise ParseException(instring, loc, self.errmsg, self) + start = loc + loc += 1 + maxloc = start + self.maxLen + maxloc = min(maxloc, len(instring)) + while loc < maxloc and instring[loc] in self.matchWhite: + loc += 1 + + if loc - start < self.minLen: + raise ParseException(instring, loc, self.errmsg, self) + + return loc, instring[start:loc] + + +class PositionToken(Token): + def __init__(self) -> None: + super().__init__() + self._may_return_empty = True + self.mayIndexError = False + + +class GoToColumn(PositionToken): + """Token to advance to a specific column of input text; useful for + tabular report scraping. + """ + + def __init__(self, colno: int) -> None: + super().__init__() + self.col = colno + + def preParse(self, instring: str, loc: int) -> int: + if col(loc, instring) == self.col: + return loc + + instrlen = len(instring) + if self.ignoreExprs: + loc = self._skipIgnorables(instring, loc) + while ( + loc < instrlen + and instring[loc].isspace() + and col(loc, instring) != self.col + ): + loc += 1 + + return loc + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + thiscol = col(loc, instring) + if thiscol > self.col: + raise ParseException(instring, loc, "Text not in expected column", self) + newloc = loc + self.col - thiscol + ret = instring[loc:newloc] + return newloc, ret + + +class LineStart(PositionToken): + r"""Matches if current position is at the logical beginning of a line (after skipping whitespace) + within the parse string + + Example: + + .. testcode:: + + test = '''\ + AAA this line + AAA and this line + AAA and even this line + B AAA but definitely not this line + ''' + + for t in (LineStart() + 'AAA' + rest_of_line).search_string(test): + print(t) + + prints: + + .. testoutput:: + + ['AAA', ' this line'] + ['AAA', ' and this line'] + ['AAA', ' and even this line'] + + """ + + def __init__(self) -> None: + super().__init__() + self.leave_whitespace() + self.orig_whiteChars = set() | self.whiteChars + self.whiteChars.discard("\n") + self.skipper = Empty().set_whitespace_chars(self.whiteChars) + self.set_name("start of line") + + def preParse(self, instring: str, loc: int) -> int: + if loc == 0: + return loc + + ret = self.skipper.preParse(instring, loc) + + if "\n" in self.orig_whiteChars: + while instring[ret : ret + 1] == "\n": + ret = self.skipper.preParse(instring, ret + 1) + + return ret + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + if col(loc, instring) == 1: + return loc, [] + raise ParseException(instring, loc, self.errmsg, self) + + +class LineEnd(PositionToken): + """Matches if current position is at the end of a line within the + parse string + """ + + def __init__(self) -> None: + super().__init__() + self.whiteChars.discard("\n") + self.set_whitespace_chars(self.whiteChars, copy_defaults=False) + self.set_name("end of line") + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + if loc < len(instring): + if instring[loc] == "\n": + return loc + 1, "\n" + else: + raise ParseException(instring, loc, self.errmsg, self) + elif loc == len(instring): + return loc + 1, [] + else: + raise ParseException(instring, loc, self.errmsg, self) + + +class StringStart(PositionToken): + """Matches if current position is at the beginning of the parse + string + """ + + def __init__(self) -> None: + super().__init__() + self.set_name("start of text") + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + # see if entire string up to here is just whitespace and ignoreables + if loc != 0 and loc != self.preParse(instring, 0): + raise ParseException(instring, loc, self.errmsg, self) + + return loc, [] + + +class StringEnd(PositionToken): + """ + Matches if current position is at the end of the parse string + """ + + def __init__(self) -> None: + super().__init__() + self.set_name("end of text") + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + if loc < len(instring): + raise ParseException(instring, loc, self.errmsg, self) + if loc == len(instring): + return loc + 1, [] + if loc > len(instring): + return loc, [] + + raise ParseException(instring, loc, self.errmsg, self) + + +class WordStart(PositionToken): + """Matches if the current position is at the beginning of a + :class:`Word`, and is not preceded by any character in a given + set of ``word_chars`` (default= ``printables``). To emulate the + ``\b`` behavior of regular expressions, use + ``WordStart(alphanums)``. ``WordStart`` will also match at + the beginning of the string being parsed, or at the beginning of + a line. + """ + + def __init__(self, word_chars: str = printables, **kwargs) -> None: + wordChars: str = deprecate_argument(kwargs, "wordChars", printables) + + wordChars = word_chars if wordChars == printables else wordChars + super().__init__() + self.wordChars = set(wordChars) + self.set_name("start of a word") + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + if loc != 0: + if ( + instring[loc - 1] in self.wordChars + or instring[loc] not in self.wordChars + ): + raise ParseException(instring, loc, self.errmsg, self) + return loc, [] + + +class WordEnd(PositionToken): + """Matches if the current position is at the end of a :class:`Word`, + and is not followed by any character in a given set of ``word_chars`` + (default= ``printables``). To emulate the ``\b`` behavior of + regular expressions, use ``WordEnd(alphanums)``. ``WordEnd`` + will also match at the end of the string being parsed, or at the end + of a line. + """ + + def __init__(self, word_chars: str = printables, **kwargs) -> None: + wordChars: str = deprecate_argument(kwargs, "wordChars", printables) + + wordChars = word_chars if wordChars == printables else wordChars + super().__init__() + self.wordChars = set(wordChars) + self.skipWhitespace = False + self.set_name("end of a word") + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + instrlen = len(instring) + if instrlen > 0 and loc < instrlen: + if ( + instring[loc] in self.wordChars + or instring[loc - 1] not in self.wordChars + ): + raise ParseException(instring, loc, self.errmsg, self) + return loc, [] + + +class Tag(Token): + """ + A meta-element for inserting a named result into the parsed + tokens that may be checked later in a parse action or while + processing the parsed results. Accepts an optional tag value, + defaulting to `True`. + + Example: + + .. doctest:: + + >>> end_punc = "." | ("!" + Tag("enthusiastic")) + >>> greeting = "Hello," + Word(alphas) + end_punc + + >>> result = greeting.parse_string("Hello, World.") + >>> print(result.dump()) + ['Hello,', 'World', '.'] + + >>> result = greeting.parse_string("Hello, World!") + >>> print(result.dump()) + ['Hello,', 'World', '!'] + - enthusiastic: True + + .. versionadded:: 3.1.0 + """ + + def __init__(self, tag_name: str, value: Any = True) -> None: + super().__init__() + self._may_return_empty = True + self.mayIndexError = False + self.leave_whitespace() + self.tag_name = tag_name + self.tag_value = value + self.add_parse_action(self._add_tag) + self.show_in_diagram = False + + def _add_tag(self, tokens: ParseResults): + tokens[self.tag_name] = self.tag_value + + def _generateDefaultName(self) -> str: + return f"{type(self).__name__}:{self.tag_name}={self.tag_value!r}" + + +class ParseExpression(ParserElement): + """Abstract subclass of ParserElement, for combining and + post-processing parsed tokens. + """ + + def __init__( + self, exprs: typing.Iterable[ParserElement], savelist: bool = False + ) -> None: + super().__init__(savelist) + self.exprs: list[ParserElement] + if isinstance(exprs, _generatorType): + exprs = list(exprs) + + if isinstance(exprs, str_type): + self.exprs = [self._literalStringClass(exprs)] + elif isinstance(exprs, ParserElement): + self.exprs = [exprs] + elif isinstance(exprs, Iterable): + exprs = list(exprs) + # if sequence of strings provided, wrap with Literal + if any(isinstance(expr, str_type) for expr in exprs): + exprs = ( + self._literalStringClass(e) if isinstance(e, str_type) else e + for e in exprs + ) + self.exprs = list(exprs) + else: + try: + self.exprs = list(exprs) + except TypeError: + self.exprs = [exprs] + self.callPreparse = False + + def recurse(self) -> list[ParserElement]: + return self.exprs[:] + + def append(self, other) -> ParserElement: + """ + Add an expression to the list of expressions related to this ParseExpression instance. + """ + self.exprs.append(other) + self._defaultName = None + return self + + def leave_whitespace(self, recursive: bool = True) -> ParserElement: + """ + Extends ``leave_whitespace`` defined in base class, and also invokes ``leave_whitespace`` on + all contained expressions. + """ + super().leave_whitespace(recursive) + + if recursive: + self.exprs = [e.copy() for e in self.exprs] + for e in self.exprs: + e.leave_whitespace(recursive) + return self + + def ignore_whitespace(self, recursive: bool = True) -> ParserElement: + """ + Extends ``ignore_whitespace`` defined in base class, and also invokes ``ignore_whitespace`` on + all contained expressions. + """ + super().ignore_whitespace(recursive) + if recursive: + self.exprs = [e.copy() for e in self.exprs] + for e in self.exprs: + e.ignore_whitespace(recursive) + return self + + def ignore(self, other) -> ParserElement: + """ + Define expression to be ignored (e.g., comments) while doing pattern + matching; may be called repeatedly, to define multiple comment or other + ignorable patterns. + """ + if isinstance(other, Suppress): + if other not in self.ignoreExprs: + super().ignore(other) + for e in self.exprs: + e.ignore(self.ignoreExprs[-1]) + else: + super().ignore(other) + for e in self.exprs: + e.ignore(self.ignoreExprs[-1]) + return self + + def _generateDefaultName(self) -> str: + return f"{type(self).__name__}:({self.exprs})" + + def streamline(self) -> ParserElement: + if self.streamlined: + return self + + super().streamline() + + for e in self.exprs: + e.streamline() + + # collapse nested :class:`And`'s of the form ``And(And(And(a, b), c), d)`` to ``And(a, b, c, d)`` + # but only if there are no parse actions or resultsNames on the nested And's + # (likewise for :class:`Or`'s and :class:`MatchFirst`'s) + if len(self.exprs) == 2: + other = self.exprs[0] + if ( + isinstance(other, self.__class__) + and not other.parseAction + and other.resultsName is None + and not other.debug + ): + self.exprs = other.exprs[:] + [self.exprs[1]] + self._defaultName = None + self._may_return_empty |= other.mayReturnEmpty + self.mayIndexError |= other.mayIndexError + + other = self.exprs[-1] + if ( + isinstance(other, self.__class__) + and not other.parseAction + and other.resultsName is None + and not other.debug + ): + self.exprs = self.exprs[:-1] + other.exprs[:] + self._defaultName = None + self._may_return_empty |= other.mayReturnEmpty + self.mayIndexError |= other.mayIndexError + + self.errmsg = f"Expected {self}" + + return self + + def validate(self, validateTrace=None) -> None: + warnings.warn( + "ParserElement.validate() is deprecated, and should not be used to check for left recursion", + PyparsingDeprecationWarning, + stacklevel=2, + ) + tmp = (validateTrace if validateTrace is not None else [])[:] + [self] + for e in self.exprs: + e.validate(tmp) + self._checkRecursion([]) + + def copy(self) -> ParserElement: + """ + Returns a copy of this expression. + + Generally only used internally by pyparsing. + """ + ret = super().copy() + ret = typing.cast(ParseExpression, ret) + ret.exprs = [e.copy() for e in self.exprs] + return ret + + def _setResultsName(self, name, list_all_matches=False) -> ParserElement: + if not ( + __diag__.warn_ungrouped_named_tokens_in_collection + and Diagnostics.warn_ungrouped_named_tokens_in_collection + not in self.suppress_warnings_ + ): + return super()._setResultsName(name, list_all_matches) + + for e in self.exprs: + if ( + isinstance(e, ParserElement) + and e.resultsName + and ( + Diagnostics.warn_ungrouped_named_tokens_in_collection + not in e.suppress_warnings_ + ) + ): + warning = ( + "warn_ungrouped_named_tokens_in_collection:" + f" setting results name {name!r} on {type(self).__name__} expression" + f" collides with {e.resultsName!r} on contained expression" + ) + warnings.warn(warning, PyparsingDiagnosticWarning, stacklevel=3) + break + + return super()._setResultsName(name, list_all_matches) + + # Compatibility synonyms + # fmt: off + leaveWhitespace = replaced_by_pep8("leaveWhitespace", leave_whitespace) + ignoreWhitespace = replaced_by_pep8("ignoreWhitespace", ignore_whitespace) + # fmt: on + + +class And(ParseExpression): + """ + Requires all given :class:`ParserElement` s to be found in the given order. + Expressions may be separated by whitespace. + May be constructed using the ``'+'`` operator. + May also be constructed using the ``'-'`` operator, which will + suppress backtracking. + + Example: + + .. testcode:: + + integer = Word(nums) + name_expr = Word(alphas)[1, ...] + + expr = And([integer("id"), name_expr("name"), integer("age")]) + # more easily written as: + expr = integer("id") + name_expr("name") + integer("age") + """ + + class _ErrorStop(Empty): + def __init__(self, *args, **kwargs) -> None: + super().__init__(*args, **kwargs) + self.leave_whitespace() + + def _generateDefaultName(self) -> str: + return "-" + + def __init__( + self, + exprs_arg: typing.Iterable[Union[ParserElement, str]], + savelist: bool = True, + ) -> None: + # instantiate exprs as a list, converting strs to ParserElements + exprs: list[ParserElement] = [ + self._literalStringClass(e) if isinstance(e, str) else e for e in exprs_arg + ] + + # convert any Ellipsis elements to SkipTo + if Ellipsis in exprs: + + # Ellipsis cannot be the last element + if exprs[-1] is Ellipsis: + raise Exception("cannot construct And with sequence ending in ...") + + tmp: list[ParserElement] = [] + for cur_expr, next_expr in zip(exprs, exprs[1:]): + if cur_expr is Ellipsis: + tmp.append(SkipTo(next_expr)("_skipped*")) + else: + tmp.append(cur_expr) + + exprs[:-1] = tmp + + super().__init__(exprs, savelist) + if self.exprs: + self._may_return_empty = all(e.mayReturnEmpty for e in self.exprs) + if not isinstance(self.exprs[0], White): + self.set_whitespace_chars( + self.exprs[0].whiteChars, + copy_defaults=self.exprs[0].copyDefaultWhiteChars, + ) + self.skipWhitespace = self.exprs[0].skipWhitespace + else: + self.skipWhitespace = False + else: + self._may_return_empty = True + self.callPreparse = True + + def streamline(self) -> ParserElement: + """ + Collapse `And` expressions like `And(And(And(A, B), C), D)` + to `And(A, B, C, D)`. + + .. doctest:: + + >>> expr = Word("A") + Word("B") + Word("C") + Word("D") + >>> # Using '+' operator creates nested And expression + >>> expr + {{{W:(A) W:(B)} W:(C)} W:(D)} + >>> # streamline simplifies to a single And with multiple expressions + >>> expr.streamline() + {W:(A) W:(B) W:(C) W:(D)} + + Guards against collapsing out expressions that have special features, + such as results names or parse actions. + + Resolves pending Skip commands defined using `...` terms. + """ + # collapse any _PendingSkip's + if self.exprs and any( + isinstance(e, ParseExpression) + and e.exprs + and isinstance(e.exprs[-1], _PendingSkip) + for e in self.exprs[:-1] + ): + deleted_expr_marker = NoMatch() + for i, e in enumerate(self.exprs[:-1]): + if e is deleted_expr_marker: + continue + if ( + isinstance(e, ParseExpression) + and e.exprs + and isinstance(e.exprs[-1], _PendingSkip) + ): + e.exprs[-1] = e.exprs[-1] + self.exprs[i + 1] + self.exprs[i + 1] = deleted_expr_marker + self.exprs = [e for e in self.exprs if e is not deleted_expr_marker] + + super().streamline() + + # link any IndentedBlocks to the prior expression + prev: ParserElement + cur: ParserElement + for prev, cur in zip(self.exprs, self.exprs[1:]): + # traverse cur or any first embedded expr of cur looking for an IndentedBlock + # (but watch out for recursive grammar) + seen = set() + while True: + if id(cur) in seen: + break + seen.add(id(cur)) + if isinstance(cur, IndentedBlock): + prev.add_parse_action( + lambda s, l, t, cur_=cur: setattr( + cur_, "parent_anchor", col(l, s) + ) + ) + break + subs = cur.recurse() + next_first = next(iter(subs), None) + if next_first is None: + break + cur = typing.cast(ParserElement, next_first) + + self._may_return_empty = all(e.mayReturnEmpty for e in self.exprs) + return self + + def parseImpl(self, instring, loc, do_actions=True): + # pass False as callPreParse arg to _parse for first element, since we already + # pre-parsed the string as part of our And pre-parsing + loc, resultlist = self.exprs[0]._parse( + instring, loc, do_actions, callPreParse=False + ) + errorStop = False + for e in self.exprs[1:]: + # if isinstance(e, And._ErrorStop): + if type(e) is And._ErrorStop: + errorStop = True + continue + if errorStop: + try: + loc, exprtokens = e._parse(instring, loc, do_actions) + except ParseSyntaxException: + raise + except ParseBaseException as pe: + pe.__traceback__ = None + raise ParseSyntaxException._from_exception(pe) + except IndexError: + raise ParseSyntaxException( + instring, len(instring), self.errmsg, self + ) + else: + loc, exprtokens = e._parse(instring, loc, do_actions) + resultlist += exprtokens + return loc, resultlist + + def __iadd__(self, other): + if isinstance(other, str_type): + other = self._literalStringClass(other) + if not isinstance(other, ParserElement): + return NotImplemented + return self.append(other) # And([self, other]) + + def _checkRecursion(self, parseElementList): + subRecCheckList = parseElementList[:] + [self] + for e in self.exprs: + e._checkRecursion(subRecCheckList) + if not e.mayReturnEmpty: + break + + def _generateDefaultName(self) -> str: + inner = " ".join(str(e) for e in self.exprs) + # strip off redundant inner {}'s + while len(inner) > 1 and inner[0 :: len(inner) - 1] == "{}": + inner = inner[1:-1] + return f"{{{inner}}}" + + +class Or(ParseExpression): + """Requires that at least one :class:`ParserElement` is found. If + two expressions match, the expression that matches the longest + string will be used. May be constructed using the ``'^'`` + operator. + + Example: + + .. testcode:: + + # construct Or using '^' operator + + number = Word(nums) ^ Combine(Word(nums) + '.' + Word(nums)) + print(number.search_string("123 3.1416 789")) + + prints: + + .. testoutput:: + + [['123'], ['3.1416'], ['789']] + """ + + def __init__( + self, exprs: typing.Iterable[ParserElement], savelist: bool = False + ) -> None: + super().__init__(exprs, savelist) + if self.exprs: + self._may_return_empty = any(e.mayReturnEmpty for e in self.exprs) + self.skipWhitespace = all(e.skipWhitespace for e in self.exprs) + else: + self._may_return_empty = True + + def streamline(self) -> ParserElement: + super().streamline() + if self.exprs: + self._may_return_empty = any(e.mayReturnEmpty for e in self.exprs) + self.saveAsList = any(e.saveAsList for e in self.exprs) + self.skipWhitespace = all( + e.skipWhitespace and not isinstance(e, White) for e in self.exprs + ) + else: + self.saveAsList = False + return self + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + maxExcLoc = -1 + maxException = None + matches: list[tuple[int, ParserElement]] = [] + fatals: list[ParseFatalException] = [] + if all(e.callPreparse for e in self.exprs): + loc = self.preParse(instring, loc) + for e in self.exprs: + try: + loc2 = e.try_parse(instring, loc, raise_fatal=True) + except ParseFatalException as pfe: + pfe.__traceback__ = None + pfe.parser_element = e + fatals.append(pfe) + maxException = None + maxExcLoc = -1 + except ParseException as err: + if not fatals: + err.__traceback__ = None + if err.loc > maxExcLoc: + maxException = err + maxExcLoc = err.loc + except IndexError: + if len(instring) > maxExcLoc: + maxException = ParseException( + instring, len(instring), e.errmsg, self + ) + maxExcLoc = len(instring) + else: + # save match among all matches, to retry longest to shortest + matches.append((loc2, e)) + + if matches: + # re-evaluate all matches in descending order of length of match, in case attached actions + # might change whether or how much they match of the input. + matches.sort(key=itemgetter(0), reverse=True) + + if not do_actions: + # no further conditions or parse actions to change the selection of + # alternative, so the first match will be the best match + best_expr = matches[0][1] + return best_expr._parse(instring, loc, do_actions) + + longest: tuple[int, typing.Optional[ParseResults]] = -1, None + for loc1, expr1 in matches: + if loc1 <= longest[0]: + # already have a longer match than this one will deliver, we are done + return longest + + try: + loc2, toks = expr1._parse(instring, loc, do_actions) + except ParseException as err: + err.__traceback__ = None + if err.loc > maxExcLoc: + maxException = err + maxExcLoc = err.loc + else: + if loc2 >= loc1: + return loc2, toks + # didn't match as much as before + elif loc2 > longest[0]: + longest = loc2, toks + + if longest != (-1, None): + return longest + + if fatals: + if len(fatals) > 1: + fatals.sort(key=lambda e: -e.loc) + if fatals[0].loc == fatals[1].loc: + fatals.sort(key=lambda e: (-e.loc, -len(str(e.parser_element)))) + max_fatal = fatals[0] + raise max_fatal + + if maxException is not None: + # infer from this check that all alternatives failed at the current position + # so emit this collective error message instead of any single error message + parse_start_loc = self.preParse(instring, loc) + if maxExcLoc == parse_start_loc: + maxException.msg = self.errmsg or "" + raise maxException + + raise ParseException(instring, loc, "no defined alternatives to match", self) + + def __ixor__(self, other): + if isinstance(other, str_type): + other = self._literalStringClass(other) + if not isinstance(other, ParserElement): + return NotImplemented + return self.append(other) # Or([self, other]) + + def _generateDefaultName(self) -> str: + return f"{{{' ^ '.join(str(e) for e in self.exprs)}}}" + + def _setResultsName(self, name, list_all_matches=False) -> ParserElement: + if ( + __diag__.warn_multiple_tokens_in_named_alternation + and Diagnostics.warn_multiple_tokens_in_named_alternation + not in self.suppress_warnings_ + ): + if any( + isinstance(e, And) + and Diagnostics.warn_multiple_tokens_in_named_alternation + not in e.suppress_warnings_ + for e in self.exprs + ): + warning = ( + "warn_multiple_tokens_in_named_alternation:" + f" setting results name {name!r} on {type(self).__name__} expression" + " will return a list of all parsed tokens in an And alternative," + " in prior versions only the first token was returned; enclose" + " contained argument in Group" + ) + warnings.warn(warning, PyparsingDiagnosticWarning, stacklevel=3) + + return super()._setResultsName(name, list_all_matches) + + +class MatchFirst(ParseExpression): + """Requires that at least one :class:`ParserElement` is found. If + more than one expression matches, the first one listed is the one that will + match. May be constructed using the ``'|'`` operator. + + Example: Construct MatchFirst using '|' operator + + .. doctest:: + + # watch the order of expressions to match + >>> number = Word(nums) | Combine(Word(nums) + '.' + Word(nums)) + >>> print(number.search_string("123 3.1416 789")) # Fail! + [['123'], ['3'], ['1416'], ['789']] + + # put more selective expression first + >>> number = Combine(Word(nums) + '.' + Word(nums)) | Word(nums) + >>> print(number.search_string("123 3.1416 789")) # Better + [['123'], ['3.1416'], ['789']] + """ + + def __init__( + self, exprs: typing.Iterable[ParserElement], savelist: bool = False + ) -> None: + super().__init__(exprs, savelist) + if self.exprs: + self._may_return_empty = any(e.mayReturnEmpty for e in self.exprs) + self.skipWhitespace = all(e.skipWhitespace for e in self.exprs) + else: + self._may_return_empty = True + + def streamline(self) -> ParserElement: + if self.streamlined: + return self + + super().streamline() + if self.exprs: + self.saveAsList = any(e.saveAsList for e in self.exprs) + self._may_return_empty = any(e.mayReturnEmpty for e in self.exprs) + self.skipWhitespace = all( + e.skipWhitespace and not isinstance(e, White) for e in self.exprs + ) + else: + self.saveAsList = False + self._may_return_empty = True + return self + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + maxExcLoc = -1 + maxException = None + + for e in self.exprs: + try: + return e._parse(instring, loc, do_actions) + except ParseFatalException as pfe: + pfe.__traceback__ = None + pfe.parser_element = e + raise + except ParseException as err: + if err.loc > maxExcLoc: + maxException = err + maxExcLoc = err.loc + except IndexError: + if len(instring) > maxExcLoc: + maxException = ParseException( + instring, len(instring), e.errmsg, self + ) + maxExcLoc = len(instring) + + if maxException is not None: + # infer from this check that all alternatives failed at the current position + # so emit this collective error message instead of any individual error message + parse_start_loc = self.preParse(instring, loc) + if maxExcLoc == parse_start_loc: + maxException.msg = self.errmsg or "" + raise maxException + + raise ParseException(instring, loc, "no defined alternatives to match", self) + + def __ior__(self, other): + if isinstance(other, str_type): + other = self._literalStringClass(other) + if not isinstance(other, ParserElement): + return NotImplemented + return self.append(other) # MatchFirst([self, other]) + + def _generateDefaultName(self) -> str: + return f"{{{' | '.join(str(e) for e in self.exprs)}}}" + + def _setResultsName(self, name, list_all_matches=False) -> ParserElement: + if ( + __diag__.warn_multiple_tokens_in_named_alternation + and Diagnostics.warn_multiple_tokens_in_named_alternation + not in self.suppress_warnings_ + ): + if any( + isinstance(e, And) + and Diagnostics.warn_multiple_tokens_in_named_alternation + not in e.suppress_warnings_ + for e in self.exprs + ): + warning = ( + "warn_multiple_tokens_in_named_alternation:" + f" setting results name {name!r} on {type(self).__name__} expression" + " will return a list of all parsed tokens in an And alternative," + " in prior versions only the first token was returned; enclose" + " contained argument in Group" + ) + warnings.warn(warning, PyparsingDiagnosticWarning, stacklevel=3) + + return super()._setResultsName(name, list_all_matches) + + +class Each(ParseExpression): + """Requires all given :class:`ParserElement` s to be found, but in + any order. Expressions may be separated by whitespace. + + May be constructed using the ``'&'`` operator. + + Example: + + .. testcode:: + + color = one_of("RED ORANGE YELLOW GREEN BLUE PURPLE BLACK WHITE BROWN") + shape_type = one_of("SQUARE CIRCLE TRIANGLE STAR HEXAGON OCTAGON") + integer = Word(nums) + shape_attr = "shape:" + shape_type("shape") + posn_attr = "posn:" + Group(integer("x") + ',' + integer("y"))("posn") + color_attr = "color:" + color("color") + size_attr = "size:" + integer("size") + + # use Each (using operator '&') to accept attributes in any order + # (shape and posn are required, color and size are optional) + shape_spec = shape_attr & posn_attr & Opt(color_attr) & Opt(size_attr) + + shape_spec.run_tests(''' + shape: SQUARE color: BLACK posn: 100, 120 + shape: CIRCLE size: 50 color: BLUE posn: 50,80 + color:GREEN size:20 shape:TRIANGLE posn:20,40 + ''' + ) + + prints: + + .. testoutput:: + :options: +NORMALIZE_WHITESPACE + + + shape: SQUARE color: BLACK posn: 100, 120 + ['shape:', 'SQUARE', 'color:', 'BLACK', 'posn:', ['100', ',', '120']] + - color: 'BLACK' + - posn: ['100', ',', '120'] + - x: '100' + - y: '120' + - shape: 'SQUARE' + ... + + shape: CIRCLE size: 50 color: BLUE posn: 50,80 + ['shape:', 'CIRCLE', 'size:', '50', 'color:', 'BLUE', + 'posn:', ['50', ',', '80']] + - color: 'BLUE' + - posn: ['50', ',', '80'] + - x: '50' + - y: '80' + - shape: 'CIRCLE' + - size: '50' + ... + + color:GREEN size:20 shape:TRIANGLE posn:20,40 + ['color:', 'GREEN', 'size:', '20', 'shape:', 'TRIANGLE', + 'posn:', ['20', ',', '40']] + - color: 'GREEN' + - posn: ['20', ',', '40'] + - x: '20' + - y: '40' + - shape: 'TRIANGLE' + - size: '20' + ... + """ + + def __init__( + self, exprs: typing.Iterable[ParserElement], savelist: bool = True + ) -> None: + super().__init__(exprs, savelist) + if self.exprs: + self._may_return_empty = all(e.mayReturnEmpty for e in self.exprs) + else: + self._may_return_empty = True + self.skipWhitespace = True + self.initExprGroups = True + self.saveAsList = True + + def __iand__(self, other): + if isinstance(other, str_type): + other = self._literalStringClass(other) + if not isinstance(other, ParserElement): + return NotImplemented + return self.append(other) # Each([self, other]) + + def streamline(self) -> ParserElement: + super().streamline() + if self.exprs: + self._may_return_empty = all(e.mayReturnEmpty for e in self.exprs) + else: + self._may_return_empty = True + return self + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + if self.initExprGroups: + self.opt1map = dict( + (id(e.expr), e) for e in self.exprs if isinstance(e, Opt) + ) + opt1 = [e.expr for e in self.exprs if isinstance(e, Opt)] + opt2 = [ + e + for e in self.exprs + if e.mayReturnEmpty and not isinstance(e, (Opt, Regex, ZeroOrMore)) + ] + self.optionals = opt1 + opt2 + self.multioptionals = [ + e.expr.set_results_name(e.resultsName, list_all_matches=True) + for e in self.exprs + if isinstance(e, _MultipleMatch) + ] + self.multirequired = [ + e.expr.set_results_name(e.resultsName, list_all_matches=True) + for e in self.exprs + if isinstance(e, OneOrMore) + ] + self.required = [ + e for e in self.exprs if not isinstance(e, (Opt, ZeroOrMore, OneOrMore)) + ] + self.required += self.multirequired + self.initExprGroups = False + + tmpLoc = loc + tmpReqd = self.required[:] + tmpOpt = self.optionals[:] + multis = self.multioptionals[:] + matchOrder: list[ParserElement] = [] + + keepMatching = True + failed: list[ParserElement] = [] + fatals: list[ParseFatalException] = [] + while keepMatching: + tmpExprs = tmpReqd + tmpOpt + multis + failed.clear() + fatals.clear() + for e in tmpExprs: + try: + tmpLoc = e.try_parse(instring, tmpLoc, raise_fatal=True) + except ParseFatalException as pfe: + pfe.__traceback__ = None + pfe.parser_element = e + fatals.append(pfe) + failed.append(e) + except ParseException: + failed.append(e) + else: + matchOrder.append(self.opt1map.get(id(e), e)) + if e in tmpReqd: + tmpReqd.remove(e) + elif e in tmpOpt: + tmpOpt.remove(e) + if len(failed) == len(tmpExprs): + keepMatching = False + + # look for any ParseFatalExceptions + if fatals: + if len(fatals) > 1: + fatals.sort(key=lambda e: -e.loc) + if fatals[0].loc == fatals[1].loc: + fatals.sort(key=lambda e: (-e.loc, -len(str(e.parser_element)))) + max_fatal = fatals[0] + raise max_fatal + + if tmpReqd: + missing = ", ".join([str(e) for e in tmpReqd]) + raise ParseException( + instring, + loc, + f"Missing one or more required elements ({missing})", + ) + + # add any unmatched Opts, in case they have default values defined + matchOrder += [e for e in self.exprs if isinstance(e, Opt) and e.expr in tmpOpt] + + total_results = ParseResults([]) + for e in matchOrder: + loc, results = e._parse(instring, loc, do_actions) + total_results += results + + return loc, total_results + + def _generateDefaultName(self) -> str: + return f"{{{' & '.join(str(e) for e in self.exprs)}}}" + + +class ParseElementEnhance(ParserElement): + """Abstract subclass of :class:`ParserElement`, for combining and + post-processing parsed tokens. + """ + + def __init__(self, expr: Union[ParserElement, str], savelist: bool = False) -> None: + super().__init__(savelist) + if isinstance(expr, str_type): + expr_str = typing.cast(str, expr) + if issubclass(self._literalStringClass, Token): + expr = self._literalStringClass(expr_str) # type: ignore[call-arg] + elif issubclass(type(self), self._literalStringClass): + expr = Literal(expr_str) + else: + expr = self._literalStringClass(Literal(expr_str)) # type: ignore[assignment, call-arg] + expr = typing.cast(ParserElement, expr) + self.expr = expr + if expr is not None: + self.mayIndexError = expr.mayIndexError + self._may_return_empty = expr.mayReturnEmpty + self.set_whitespace_chars( + expr.whiteChars, copy_defaults=expr.copyDefaultWhiteChars + ) + self.skipWhitespace = expr.skipWhitespace + self.saveAsList = expr.saveAsList + self.callPreparse = expr.callPreparse + self.ignoreExprs.extend(expr.ignoreExprs) + + def recurse(self) -> list[ParserElement]: + return [self.expr] if self.expr is not None else [] + + def parseImpl(self, instring, loc, do_actions=True): + if self.expr is None: + raise ParseException(instring, loc, "No expression defined", self) + + try: + return self.expr._parse(instring, loc, do_actions, callPreParse=False) + except ParseSyntaxException: + raise + except ParseBaseException as pbe: + pbe.pstr = pbe.pstr or instring + pbe.loc = pbe.loc or loc + pbe.parser_element = pbe.parser_element or self + if not isinstance(self, Forward) and self.customName is not None: + if self.errmsg: + pbe.msg = self.errmsg + raise + + def leave_whitespace(self, recursive: bool = True) -> ParserElement: + """ + Extends ``leave_whitespace`` defined in base class, and also invokes ``leave_whitespace`` on + the contained expression. + """ + super().leave_whitespace(recursive) + + if recursive: + if self.expr is not None: + self.expr = self.expr.copy() + self.expr.leave_whitespace(recursive) + return self + + def ignore_whitespace(self, recursive: bool = True) -> ParserElement: + """ + Extends ``ignore_whitespace`` defined in base class, and also invokes ``ignore_whitespace`` on + the contained expression. + """ + super().ignore_whitespace(recursive) + + if recursive: + if self.expr is not None: + self.expr = self.expr.copy() + self.expr.ignore_whitespace(recursive) + return self + + def ignore(self, other) -> ParserElement: + """ + Define expression to be ignored (e.g., comments) while doing pattern + matching; may be called repeatedly, to define multiple comment or other + ignorable patterns. + """ + if not isinstance(other, Suppress) or other not in self.ignoreExprs: + super().ignore(other) + if self.expr is not None: + self.expr.ignore(self.ignoreExprs[-1]) + + return self + + def streamline(self) -> ParserElement: + super().streamline() + if self.expr is not None: + self.expr.streamline() + return self + + def _checkRecursion(self, parseElementList): + if self in parseElementList: + raise RecursiveGrammarException(parseElementList + [self]) + subRecCheckList = parseElementList[:] + [self] + if self.expr is not None: + self.expr._checkRecursion(subRecCheckList) + + def validate(self, validateTrace=None) -> None: + warnings.warn( + "ParserElement.validate() is deprecated, and should not be used to check for left recursion", + PyparsingDeprecationWarning, + stacklevel=2, + ) + if validateTrace is None: + validateTrace = [] + tmp = validateTrace[:] + [self] + if self.expr is not None: + self.expr.validate(tmp) + self._checkRecursion([]) + + def _generateDefaultName(self) -> str: + return f"{type(self).__name__}:({self.expr})" + + # Compatibility synonyms + # fmt: off + leaveWhitespace = replaced_by_pep8("leaveWhitespace", leave_whitespace) + ignoreWhitespace = replaced_by_pep8("ignoreWhitespace", ignore_whitespace) + # fmt: on + + +class IndentedBlock(ParseElementEnhance): + """ + Expression to match one or more expressions at a given indentation level. + Useful for parsing text where structure is implied by indentation (like Python source code). + + Example: + + .. testcode:: + + ''' + BNF: + statement ::= assignment_stmt | if_stmt + assignment_stmt ::= identifier '=' rvalue + rvalue ::= identifier | integer + if_stmt ::= 'if' bool_condition block + block ::= ([indent] statement)... + identifier ::= [A..Za..z] + integer ::= [0..9]... + bool_condition ::= 'TRUE' | 'FALSE' + ''' + + IF, TRUE, FALSE = Keyword.using_each("IF TRUE FALSE".split()) + + statement = Forward() + identifier = Char(alphas) + integer = Word(nums).add_parse_action(lambda t: int(t[0])) + rvalue = identifier | integer + assignment_stmt = identifier + "=" + rvalue + + if_stmt = IF + (TRUE | FALSE) + IndentedBlock(statement) + + statement <<= Group(assignment_stmt | if_stmt) + + result = if_stmt.parse_string(''' + IF TRUE + a = 1000 + b = 2000 + IF FALSE + z = 100 + ''') + print(result.dump()) + + .. testoutput:: + + ['IF', 'TRUE', [['a', '=', 1000], ['b', '=', 2000], ['IF', 'FALSE', [['z', '=', 100]]]]] + [0]: + IF + [1]: + TRUE + [2]: + [['a', '=', 1000], ['b', '=', 2000], ['IF', 'FALSE', [['z', '=', 100]]]] + [0]: + ['a', '=', 1000] + [1]: + ['b', '=', 2000] + [2]: + ['IF', 'FALSE', [['z', '=', 100]]] + [0]: + IF + [1]: + FALSE + [2]: + [['z', '=', 100]] + [0]: + ['z', '=', 100] + """ + + class _Indent(Empty): + def __init__(self, ref_col: int) -> None: + super().__init__() + self.errmsg = f"expected indent at column {ref_col}" + self.add_condition(lambda s, l, t: col(l, s) == ref_col) + + class _IndentGreater(Empty): + def __init__(self, ref_col: int) -> None: + super().__init__() + self.errmsg = f"expected indent at column greater than {ref_col}" + self.add_condition(lambda s, l, t: col(l, s) > ref_col) + + def __init__( + self, expr: ParserElement, *, recursive: bool = False, grouped: bool = True + ) -> None: + super().__init__(expr, savelist=True) + # if recursive: + # raise NotImplementedError("IndentedBlock with recursive is not implemented") + self._recursive = recursive + self._grouped = grouped + self.parent_anchor = 1 + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + # advance parse position to non-whitespace by using an Empty() + # this should be the column to be used for all subsequent indented lines + anchor_loc = Empty().preParse(instring, loc) + + # see if self.expr matches at the current location - if not it will raise an exception + # and no further work is necessary + self.expr.try_parse(instring, anchor_loc, do_actions=do_actions) + + indent_col = col(anchor_loc, instring) + peer_detect_expr = self._Indent(indent_col) + + inner_expr = Empty() + peer_detect_expr + self.expr + if self._recursive: + sub_indent = self._IndentGreater(indent_col) + nested_block = IndentedBlock( + self.expr, recursive=self._recursive, grouped=self._grouped + ) + nested_block.set_debug(self.debug) + nested_block.parent_anchor = indent_col + inner_expr += Opt(sub_indent + nested_block) + + inner_expr.set_name(f"inner {hex(id(inner_expr))[-4:].upper()}@{indent_col}") + block = OneOrMore(inner_expr) + + trailing_undent = self._Indent(self.parent_anchor) | StringEnd() + + if self._grouped: + wrapper = Group + else: + wrapper = lambda expr: expr # type: ignore[misc, assignment] + return (wrapper(block) + Optional(trailing_undent)).parseImpl( + instring, anchor_loc, do_actions + ) + + +class AtStringStart(ParseElementEnhance): + """Matches if expression matches at the beginning of the parse + string:: + + AtStringStart(Word(nums)).parse_string("123") + # prints ["123"] + + AtStringStart(Word(nums)).parse_string(" 123") + # raises ParseException + """ + + def __init__(self, expr: Union[ParserElement, str]) -> None: + super().__init__(expr) + self.callPreparse = False + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + if loc != 0: + raise ParseException(instring, loc, "not found at string start") + return super().parseImpl(instring, loc, do_actions) + + +class AtLineStart(ParseElementEnhance): + r"""Matches if an expression matches at the beginning of a line within + the parse string + + Example: + + .. testcode:: + + test = '''\ + BBB this line + BBB and this line + BBB but not this one + A BBB and definitely not this one + ''' + + for t in (AtLineStart('BBB') + rest_of_line).search_string(test): + print(t) + + prints: + + .. testoutput:: + + ['BBB', ' this line'] + ['BBB', ' and this line'] + """ + + def __init__(self, expr: Union[ParserElement, str]) -> None: + super().__init__(expr) + self.callPreparse = False + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + if col(loc, instring) != 1: + raise ParseException(instring, loc, "not found at line start") + return super().parseImpl(instring, loc, do_actions) + + +class FollowedBy(ParseElementEnhance): + """Lookahead matching of the given parse expression. + ``FollowedBy`` does *not* advance the parsing position within + the input string, it only verifies that the specified parse + expression matches at the current position. ``FollowedBy`` + always returns a null token list. If any results names are defined + in the lookahead expression, those *will* be returned for access by + name. + + Example: + + .. testcode:: + + # use FollowedBy to match a label only if it is followed by a ':' + data_word = Word(alphas) + label = data_word + FollowedBy(':') + attr_expr = Group( + label + Suppress(':') + + OneOrMore(data_word, stop_on=label).set_parse_action(' '.join) + ) + + attr_expr[1, ...].parse_string( + "shape: SQUARE color: BLACK posn: upper left").pprint() + + prints: + + .. testoutput:: + + [['shape', 'SQUARE'], ['color', 'BLACK'], ['posn', 'upper left']] + """ + + def __init__(self, expr: Union[ParserElement, str]) -> None: + super().__init__(expr) + self._may_return_empty = True + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + # by using self._expr.parse and deleting the contents of the returned ParseResults list + # we keep any named results that were defined in the FollowedBy expression + _, ret = self.expr._parse(instring, loc, do_actions=do_actions) + del ret[:] + + return loc, ret + + +class PrecededBy(ParseElementEnhance): + """Lookbehind matching of the given parse expression. + ``PrecededBy`` does not advance the parsing position within the + input string, it only verifies that the specified parse expression + matches prior to the current position. ``PrecededBy`` always + returns a null token list, but if a results name is defined on the + given expression, it is returned. + + Parameters: + + - ``expr`` - expression that must match prior to the current parse + location + - ``retreat`` - (default= ``None``) - (int) maximum number of characters + to lookbehind prior to the current parse location + + If the lookbehind expression is a string, :class:`Literal`, + :class:`Keyword`, or a :class:`Word` or :class:`CharsNotIn` + with a specified exact or maximum length, then the retreat + parameter is not required. Otherwise, retreat must be specified to + give a maximum number of characters to look back from + the current parse position for a lookbehind match. + + Example: + + .. testcode:: + + # VB-style variable names with type prefixes + int_var = PrecededBy("#") + pyparsing_common.identifier + str_var = PrecededBy("$") + pyparsing_common.identifier + """ + + def __init__(self, expr: Union[ParserElement, str], retreat: int = 0) -> None: + super().__init__(expr) + self.expr = self.expr().leave_whitespace() + self._may_return_empty = True + self.mayIndexError = False + self.exact = False + if isinstance(expr, str_type): + expr = typing.cast(str, expr) + retreat = len(expr) + self.exact = True + elif isinstance(expr, (Literal, Keyword)): + retreat = expr.matchLen + self.exact = True + elif isinstance(expr, (Word, CharsNotIn)) and expr.maxLen != _MAX_INT: + retreat = expr.maxLen + self.exact = True + elif isinstance(expr, PositionToken): + retreat = 0 + self.exact = True + self.retreat = retreat + self.errmsg = f"not preceded by {expr}" + self.skipWhitespace = False + self.parseAction.append(lambda s, l, t: t.__delitem__(slice(None, None))) + + def parseImpl(self, instring, loc=0, do_actions=True) -> ParseImplReturnType: + if self.exact: + if loc < self.retreat: + raise ParseException(instring, loc, self.errmsg, self) + start = loc - self.retreat + _, ret = self.expr._parse(instring, start) + return loc, ret + + # retreat specified a maximum lookbehind window, iterate + test_expr = self.expr + StringEnd() + instring_slice = instring[max(0, loc - self.retreat) : loc] + last_expr: ParseBaseException = ParseException(instring, loc, self.errmsg, self) + + for offset in range(1, min(loc, self.retreat + 1) + 1): + try: + # print('trying', offset, instring_slice, repr(instring_slice[loc - offset:])) + _, ret = test_expr._parse(instring_slice, len(instring_slice) - offset) + except ParseBaseException as pbe: + last_expr = pbe + else: + break + else: + raise last_expr + + return loc, ret + + +class Located(ParseElementEnhance): + """ + Decorates a returned token with its starting and ending + locations in the input string. + + This helper adds the following results names: + + - ``locn_start`` - location where matched expression begins + - ``locn_end`` - location where matched expression ends + - ``value`` - the actual parsed results + + Be careful if the input text contains ```` characters, you + may want to call :class:`ParserElement.parse_with_tabs` + + Example: + + .. testcode:: + + wd = Word(alphas) + for match in Located(wd).search_string("ljsdf123lksdjjf123lkkjj1222"): + print(match) + + prints: + + .. testoutput:: + + [0, ['ljsdf'], 5] + [8, ['lksdjjf'], 15] + [18, ['lkkjj'], 23] + """ + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + start = loc + loc, tokens = self.expr._parse(instring, start, do_actions, callPreParse=False) + ret_tokens = ParseResults([start, tokens, loc]) + ret_tokens["locn_start"] = start + ret_tokens["value"] = tokens + ret_tokens["locn_end"] = loc + if self.resultsName: + # must return as a list, so that the name will be attached to the complete group + return loc, [ret_tokens] + else: + return loc, ret_tokens + + +class NotAny(ParseElementEnhance): + """ + Lookahead to disallow matching with the given parse expression. + ``NotAny`` does *not* advance the parsing position within the + input string, it only verifies that the specified parse expression + does *not* match at the current position. Also, ``NotAny`` does + *not* skip over leading whitespace. ``NotAny`` always returns + a null token list. May be constructed using the ``'~'`` operator. + + Example: + + .. testcode:: + + AND, OR, NOT = map(CaselessKeyword, "AND OR NOT".split()) + + # take care not to mistake keywords for identifiers + ident = ~(AND | OR | NOT) + Word(alphas) + boolean_term = Opt(NOT) + ident + + # very crude boolean expression - to support parenthesis groups and + # operation hierarchy, use infix_notation + boolean_expr = boolean_term + ((AND | OR) + boolean_term)[...] + + # integers that are followed by "." are actually floats + integer = Word(nums) + ~Char(".") + """ + + def __init__(self, expr: Union[ParserElement, str]) -> None: + super().__init__(expr) + # do NOT use self.leave_whitespace(), don't want to propagate to exprs + # self.leave_whitespace() + self.skipWhitespace = False + + self._may_return_empty = True + self.errmsg = f"Found unwanted token, {self.expr}" + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + if self.expr.can_parse_next(instring, loc, do_actions=do_actions): + raise ParseException(instring, loc, self.errmsg, self) + return loc, [] + + def _generateDefaultName(self) -> str: + return f"~{{{self.expr}}}" + + +class _MultipleMatch(ParseElementEnhance): + def __init__( + self, + expr: Union[str, ParserElement], + stop_on: typing.Optional[Union[ParserElement, str]] = None, + **kwargs, + ) -> None: + stopOn: typing.Optional[Union[ParserElement, str]] = deprecate_argument( + kwargs, "stopOn", None + ) + + super().__init__(expr) + stopOn = stopOn or stop_on + self.saveAsList = True + ender = stopOn + if isinstance(ender, str_type): + ender = self._literalStringClass(ender) + self.stopOn(ender) + + def stop_on(self, ender) -> ParserElement: + if isinstance(ender, str_type): + ender = self._literalStringClass(ender) + self.not_ender = ~ender if ender is not None else None + return self + + stopOn = stop_on + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + self_expr_parse = self.expr._parse + self_skip_ignorables = self._skipIgnorables + check_ender = False + if self.not_ender is not None: + try_not_ender = self.not_ender.try_parse + check_ender = True + + # must be at least one (but first see if we are the stopOn sentinel; + # if so, fail) + if check_ender: + try_not_ender(instring, loc) + loc, tokens = self_expr_parse(instring, loc, do_actions) + try: + hasIgnoreExprs = not not self.ignoreExprs + while 1: + if check_ender: + try_not_ender(instring, loc) + if hasIgnoreExprs: + preloc = self_skip_ignorables(instring, loc) + else: + preloc = loc + loc, tmptokens = self_expr_parse(instring, preloc, do_actions) + tokens += tmptokens + except (ParseException, IndexError): + pass + + return loc, tokens + + def _setResultsName(self, name, list_all_matches=False) -> ParserElement: + if ( + __diag__.warn_ungrouped_named_tokens_in_collection + and Diagnostics.warn_ungrouped_named_tokens_in_collection + not in self.suppress_warnings_ + ): + for e in [self.expr] + self.expr.recurse(): + if ( + isinstance(e, ParserElement) + and e.resultsName + and ( + Diagnostics.warn_ungrouped_named_tokens_in_collection + not in e.suppress_warnings_ + ) + ): + warning = ( + "warn_ungrouped_named_tokens_in_collection:" + f" setting results name {name!r} on {type(self).__name__} expression" + f" collides with {e.resultsName!r} on contained expression" + ) + warnings.warn(warning, PyparsingDiagnosticWarning, stacklevel=3) + break + + return super()._setResultsName(name, list_all_matches) + + +class OneOrMore(_MultipleMatch): + """ + Repetition of one or more of the given expression. + + Parameters: + + - ``expr`` - expression that must match one or more times + - ``stop_on`` - (default= ``None``) - expression for a terminating sentinel + (only required if the sentinel would ordinarily match the repetition + expression) + + Example: + + .. doctest:: + + >>> data_word = Word(alphas) + >>> label = data_word + FollowedBy(':') + >>> attr_expr = Group( + ... label + Suppress(':') + ... + OneOrMore(data_word).set_parse_action(' '.join)) + + >>> text = "shape: SQUARE posn: upper left color: BLACK" + + # Fail! read 'posn' as data instead of next label + >>> attr_expr[1, ...].parse_string(text).pprint() + [['shape', 'SQUARE posn']] + + # use stop_on attribute for OneOrMore + # to avoid reading label string as part of the data + >>> attr_expr = Group( + ... label + Suppress(':') + ... + OneOrMore( + ... data_word, stop_on=label).set_parse_action(' '.join)) + >>> OneOrMore(attr_expr).parse_string(text).pprint() # Better + [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'BLACK']] + + # could also be written as + >>> (attr_expr * (1,)).parse_string(text).pprint() + [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'BLACK']] + """ + + def _generateDefaultName(self) -> str: + return f"{{{self.expr}}}..." + + +class ZeroOrMore(_MultipleMatch): + """ + Optional repetition of zero or more of the given expression. + + Parameters: + + - ``expr`` - expression that must match zero or more times + - ``stop_on`` - expression for a terminating sentinel + (only required if the sentinel would ordinarily match the repetition + expression) - (default= ``None``) + + Example: similar to :class:`OneOrMore` + """ + + def __init__( + self, + expr: Union[str, ParserElement], + stop_on: typing.Optional[Union[ParserElement, str]] = None, + **kwargs, + ) -> None: + stopOn: Union[ParserElement, str] = deprecate_argument(kwargs, "stopOn", None) + + super().__init__(expr, stop_on=stopOn or stop_on) + self._may_return_empty = True + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + try: + return super().parseImpl(instring, loc, do_actions) + except (ParseException, IndexError): + return loc, ParseResults([], name=self.resultsName) + + def _generateDefaultName(self) -> str: + return f"[{self.expr}]..." + + +class DelimitedList(ParseElementEnhance): + """Helper to define a delimited list of expressions - the delimiter + defaults to ','. By default, the list elements and delimiters can + have intervening whitespace, and comments, but this can be + overridden by passing ``combine=True`` in the constructor. If + ``combine`` is set to ``True``, the matching tokens are + returned as a single token string, with the delimiters included; + otherwise, the matching tokens are returned as a list of tokens, + with the delimiters suppressed. + + If ``allow_trailing_delim`` is set to True, then the list may end with + a delimiter. + + Example: + + .. doctest:: + + >>> DelimitedList(Word(alphas)).parse_string("aa,bb,cc") + ParseResults(['aa', 'bb', 'cc'], {}) + >>> DelimitedList(Word(hexnums), delim=':', combine=True + ... ).parse_string("AA:BB:CC:DD:EE") + ParseResults(['AA:BB:CC:DD:EE'], {}) + + .. versionadded:: 3.1.0 + """ + + def __init__( + self, + expr: Union[str, ParserElement], + delim: Union[str, ParserElement] = ",", + combine: bool = False, + min: typing.Optional[int] = None, + max: typing.Optional[int] = None, + *, + allow_trailing_delim: bool = False, + ) -> None: + if isinstance(expr, str_type): + expr = ParserElement._literalStringClass(expr) + expr = typing.cast(ParserElement, expr) + + if min is not None and min < 1: + raise ValueError("min must be greater than 0") + + if max is not None and min is not None and max < min: + raise ValueError("max must be greater than, or equal to min") + + self.content = expr + self.raw_delim = str(delim) + self.delim = delim + self.combine = combine + if not combine: + self.delim = Suppress(delim) if not isinstance(delim, Suppress) else delim + self.min = min or 1 + self.max = max + self.allow_trailing_delim = allow_trailing_delim + + delim_list_expr = self.content + (self.delim + self.content) * ( + self.min - 1, + None if self.max is None else self.max - 1, + ) + if self.allow_trailing_delim: + delim_list_expr += Opt(self.delim) + + if self.combine: + delim_list_expr = Combine(delim_list_expr) + + super().__init__(delim_list_expr, savelist=True) + + def _generateDefaultName(self) -> str: + content_expr = self.content.streamline() + return f"{content_expr} [{self.raw_delim} {content_expr}]..." + + +class _NullToken: + def __bool__(self): + return False + + def __str__(self): + return "" + + +class Opt(ParseElementEnhance): + """ + Optional matching of the given expression. + + :param expr: expression that must match zero or more times + :param default: (optional) - value to be returned + if the optional expression is not found. + + Example: + + .. testcode:: + + # US postal code can be a 5-digit zip, plus optional 4-digit qualifier + zip = Combine(Word(nums, exact=5) + Opt('-' + Word(nums, exact=4))) + zip.run_tests(''' + # traditional ZIP code + 12345 + + # ZIP+4 form + 12101-0001 + + # invalid ZIP + 98765- + ''') + + prints: + + .. testoutput:: + :options: +NORMALIZE_WHITESPACE + + + # traditional ZIP code + 12345 + ['12345'] + + # ZIP+4 form + 12101-0001 + ['12101-0001'] + + # invalid ZIP + 98765- + 98765- + ^ + ParseException: Expected end of text, found '-' (at char 5), (line:1, col:6) + FAIL: Expected end of text, found '-' (at char 5), (line:1, col:6) + """ + + __optionalNotMatched = _NullToken() + + def __init__( + self, expr: Union[ParserElement, str], default: Any = __optionalNotMatched + ) -> None: + super().__init__(expr, savelist=False) + self.saveAsList = self.expr.saveAsList + self.defaultValue = default + self._may_return_empty = True + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + self_expr = self.expr + try: + loc, tokens = self_expr._parse( + instring, loc, do_actions, callPreParse=False + ) + except (ParseException, IndexError): + default_value = self.defaultValue + if default_value is not self.__optionalNotMatched: + if self_expr.resultsName: + tokens = ParseResults([default_value]) + tokens[self_expr.resultsName] = default_value + else: + tokens = [default_value] # type: ignore[assignment] + else: + tokens = [] # type: ignore[assignment] + return loc, tokens + + def _generateDefaultName(self) -> str: + inner = str(self.expr) + # strip off redundant inner {}'s + while len(inner) > 1 and inner[0 :: len(inner) - 1] == "{}": + inner = inner[1:-1] + return f"[{inner}]" + + +Optional = Opt + + +class SkipTo(ParseElementEnhance): + """ + Token for skipping over all undefined text until the matched + expression is found. + + :param expr: target expression marking the end of the data to be skipped + :param include: if ``True``, the target expression is also parsed + (the skipped text and target expression are returned + as a 2-element list) (default= ``False``). + + :param ignore: (default= ``None``) used to define grammars + (typically quoted strings and comments) + that might contain false matches to the target expression + + :param fail_on: (default= ``None``) define expressions that + are not allowed to be included in the skipped test; + if found before the target expression is found, + the :class:`SkipTo` is not a match + + Example: + + .. testcode:: + + report = ''' + Outstanding Issues Report - 1 Jan 2000 + + # | Severity | Description | Days Open + -----+----------+-------------------------------------------+----------- + 101 | Critical | Intermittent system crash | 6 + 94 | Cosmetic | Spelling error on Login ('log|n') | 14 + 79 | Minor | System slow when running too many reports | 47 + ''' + integer = Word(nums) + SEP = Suppress('|') + # use SkipTo to simply match everything up until the next SEP + # - ignore quoted strings, so that a '|' character inside a quoted string does not match + # - parse action will call token.strip() for each matched token, i.e., the description body + string_data = SkipTo(SEP, ignore=quoted_string) + string_data.set_parse_action(token_map(str.strip)) + ticket_expr = (integer("issue_num") + SEP + + string_data("sev") + SEP + + string_data("desc") + SEP + + integer("days_open")) + + for tkt in ticket_expr.search_string(report): + print(tkt.dump()) + + prints: + + .. testoutput:: + + ['101', 'Critical', 'Intermittent system crash', '6'] + - days_open: '6' + - desc: 'Intermittent system crash' + - issue_num: '101' + - sev: 'Critical' + ['94', 'Cosmetic', "Spelling error on Login ('log|n')", '14'] + - days_open: '14' + - desc: "Spelling error on Login ('log|n')" + - issue_num: '94' + - sev: 'Cosmetic' + ['79', 'Minor', 'System slow when running too many reports', '47'] + - days_open: '47' + - desc: 'System slow when running too many reports' + - issue_num: '79' + - sev: 'Minor' + """ + + def __init__( + self, + other: Union[ParserElement, str], + include: bool = False, + ignore: typing.Optional[Union[ParserElement, str]] = None, + fail_on: typing.Optional[Union[ParserElement, str]] = None, + **kwargs, + ) -> None: + failOn: typing.Optional[Union[ParserElement, str]] = deprecate_argument( + kwargs, "failOn", None + ) + + super().__init__(other) + failOn = failOn or fail_on + self.ignoreExpr = ignore + self._may_return_empty = True + self.mayIndexError = False + self.includeMatch = include + self.saveAsList = False + if isinstance(failOn, str_type): + self.failOn = self._literalStringClass(failOn) + else: + self.failOn = failOn + self.errmsg = f"No match found for {self.expr}" + self.ignorer = Empty().leave_whitespace() + self._update_ignorer() + + def _update_ignorer(self): + # rebuild internal ignore expr from current ignore exprs and assigned ignoreExpr + self.ignorer.ignoreExprs.clear() + for e in self.expr.ignoreExprs: + self.ignorer.ignore(e) + if self.ignoreExpr: + self.ignorer.ignore(self.ignoreExpr) + + def ignore(self, expr): + """ + Define expression to be ignored (e.g., comments) while doing pattern + matching; may be called repeatedly, to define multiple comment or other + ignorable patterns. + """ + super().ignore(expr) + self._update_ignorer() + + def parseImpl(self, instring, loc, do_actions=True): + startloc = loc + instrlen = len(instring) + self_expr_parse = self.expr._parse + self_failOn_canParseNext = ( + self.failOn.can_parse_next if self.failOn is not None else None + ) + ignorer_try_parse = self.ignorer.try_parse if self.ignorer.ignoreExprs else None + + tmploc = loc + while tmploc <= instrlen: + if self_failOn_canParseNext is not None: + # break if failOn expression matches + if self_failOn_canParseNext(instring, tmploc): + break + + if ignorer_try_parse is not None: + # advance past ignore expressions + prev_tmploc = tmploc + while 1: + try: + tmploc = ignorer_try_parse(instring, tmploc) + except ParseBaseException: + break + # see if all ignorers matched, but didn't actually ignore anything + if tmploc == prev_tmploc: + break + prev_tmploc = tmploc + + try: + self_expr_parse(instring, tmploc, do_actions=False, callPreParse=False) + except (ParseException, IndexError): + # no match, advance loc in string + tmploc += 1 + else: + # matched skipto expr, done + break + + else: + # ran off the end of the input string without matching skipto expr, fail + raise ParseException(instring, loc, self.errmsg, self) + + # build up return values + loc = tmploc + skiptext = instring[startloc:loc] + skipresult = ParseResults(skiptext) + + if self.includeMatch: + loc, mat = self_expr_parse(instring, loc, do_actions, callPreParse=False) + skipresult += mat + + return loc, skipresult + + +class Forward(ParseElementEnhance): + """ + Forward declaration of an expression to be defined later - + used for recursive grammars, such as algebraic infix notation. + When the expression is known, it is assigned to the ``Forward`` + instance using the ``'<<'`` operator. + + .. Note:: + + Take care when assigning to ``Forward`` not to overlook + precedence of operators. + + Specifically, ``'|'`` has a lower precedence than ``'<<'``, so that:: + + fwd_expr << a | b | c + + will actually be evaluated as:: + + (fwd_expr << a) | b | c + + thereby leaving b and c out as parseable alternatives. + It is recommended that you explicitly group the values + inserted into the :class:`Forward`:: + + fwd_expr << (a | b | c) + + Converting to use the ``'<<='`` operator instead will avoid this problem. + + See :meth:`ParseResults.pprint` for an example of a recursive + parser created using :class:`Forward`. + """ + + def __init__( + self, other: typing.Optional[Union[ParserElement, str]] = None + ) -> None: + self.caller_frame = traceback.extract_stack(limit=2)[0] + super().__init__(other, savelist=False) # type: ignore[arg-type] + self.lshift_line = None + + def __lshift__(self, other) -> Forward: + if hasattr(self, "caller_frame"): + del self.caller_frame + if isinstance(other, str_type): + other = self._literalStringClass(other) + + if not isinstance(other, ParserElement): + return NotImplemented + + self.expr = other + self.streamlined = other.streamlined + self.mayIndexError = self.expr.mayIndexError + self._may_return_empty = self.expr.mayReturnEmpty + self.set_whitespace_chars( + self.expr.whiteChars, copy_defaults=self.expr.copyDefaultWhiteChars + ) + self.skipWhitespace = self.expr.skipWhitespace + self.saveAsList = self.expr.saveAsList + self.ignoreExprs.extend(self.expr.ignoreExprs) + self.lshift_line = traceback.extract_stack(limit=2)[-2] # type: ignore[assignment] + return self + + def __ilshift__(self, other) -> Forward: + if not isinstance(other, ParserElement): + return NotImplemented + + return self << other + + def __or__(self, other) -> ParserElement: + caller_line = traceback.extract_stack(limit=2)[-2] + if ( + __diag__.warn_on_match_first_with_lshift_operator + and caller_line == self.lshift_line + and Diagnostics.warn_on_match_first_with_lshift_operator + not in self.suppress_warnings_ + ): + warnings.warn( + "warn_on_match_first_with_lshift_operator:" + " using '<<' operator with '|' is probably an error, use '<<='", + PyparsingDiagnosticWarning, + stacklevel=2, + ) + ret = super().__or__(other) + return ret + + def __del__(self): + # see if we are getting dropped because of '=' reassignment of var instead of '<<=' or '<<' + if ( + self.expr is None + and __diag__.warn_on_assignment_to_Forward + and Diagnostics.warn_on_assignment_to_Forward not in self.suppress_warnings_ + ): + warnings.warn_explicit( + "warn_on_assignment_to_Forward:" + " Forward defined here but no expression attached later using '<<=' or '<<'", + UserWarning, + filename=self.caller_frame.filename, + lineno=self.caller_frame.lineno, + ) + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + if ( + self.expr is None + and __diag__.warn_on_parse_using_empty_Forward + and Diagnostics.warn_on_parse_using_empty_Forward + not in self.suppress_warnings_ + ): + # walk stack until parse_string, scan_string, search_string, or transform_string is found + parse_fns = ( + "parse_string", + "scan_string", + "search_string", + "transform_string", + ) + tb = traceback.extract_stack(limit=200) + for i, frm in enumerate(reversed(tb), start=1): + if frm.name in parse_fns: + stacklevel = i + 1 + break + else: + stacklevel = 2 + warnings.warn( + "warn_on_parse_using_empty_Forward:" + " Forward expression was never assigned a value, will not parse any input", + PyparsingDiagnosticWarning, + stacklevel=stacklevel, + ) + if not ParserElement._left_recursion_enabled: + return super().parseImpl(instring, loc, do_actions) + # ## Bounded Recursion algorithm ## + # Recursion only needs to be processed at ``Forward`` elements, since they are + # the only ones that can actually refer to themselves. The general idea is + # to handle recursion stepwise: We start at no recursion, then recurse once, + # recurse twice, ..., until more recursion offers no benefit (we hit the bound). + # + # The "trick" here is that each ``Forward`` gets evaluated in two contexts + # - to *match* a specific recursion level, and + # - to *search* the bounded recursion level + # and the two run concurrently. The *search* must *match* each recursion level + # to find the best possible match. This is handled by a memo table, which + # provides the previous match to the next level match attempt. + # + # See also "Left Recursion in Parsing Expression Grammars", Medeiros et al. + # + # There is a complication since we not only *parse* but also *transform* via + # actions: We do not want to run the actions too often while expanding. Thus, + # we expand using `do_actions=False` and only run `do_actions=True` if the next + # recursion level is acceptable. + with ParserElement.recursion_lock: + memo = ParserElement.recursion_memos + try: + # we are parsing at a specific recursion expansion - use it as-is + prev_loc, prev_result = memo[loc, self, do_actions] + if isinstance(prev_result, Exception): + raise prev_result + return prev_loc, prev_result.copy() + except KeyError: + act_key = (loc, self, True) + peek_key = (loc, self, False) + # we are searching for the best recursion expansion - keep on improving + # both `do_actions` cases must be tracked separately here! + prev_loc, prev_peek = memo[peek_key] = ( + loc - 1, + ParseException( + instring, loc, "Forward recursion without base case", self + ), + ) + if do_actions: + memo[act_key] = memo[peek_key] + while True: + try: + new_loc, new_peek = super().parseImpl(instring, loc, False) + except ParseException: + # we failed before getting any match - do not hide the error + if isinstance(prev_peek, Exception): + raise + new_loc, new_peek = prev_loc, prev_peek + # the match did not get better: we are done + if new_loc <= prev_loc: + if do_actions: + # replace the match for do_actions=False as well, + # in case the action did backtrack + prev_loc, prev_result = memo[peek_key] = memo[act_key] + del memo[peek_key], memo[act_key] + return prev_loc, copy.copy(prev_result) + del memo[peek_key] + return prev_loc, copy.copy(prev_peek) + # the match did get better: see if we can improve further + if do_actions: + try: + memo[act_key] = super().parseImpl(instring, loc, True) + except ParseException as e: + memo[peek_key] = memo[act_key] = (new_loc, e) + raise + prev_loc, prev_peek = memo[peek_key] = new_loc, new_peek + + def leave_whitespace(self, recursive: bool = True) -> ParserElement: + """ + Extends ``leave_whitespace`` defined in base class. + """ + self.skipWhitespace = False + return self + + def ignore_whitespace(self, recursive: bool = True) -> ParserElement: + """ + Extends ``ignore_whitespace`` defined in base class. + """ + self.skipWhitespace = True + return self + + def streamline(self) -> ParserElement: + if not self.streamlined: + self.streamlined = True + if self.expr is not None: + self.expr.streamline() + return self + + def validate(self, validateTrace=None) -> None: + warnings.warn( + "ParserElement.validate() is deprecated, and should not be used to check for left recursion", + PyparsingDeprecationWarning, + stacklevel=2, + ) + if validateTrace is None: + validateTrace = [] + + if self not in validateTrace: + tmp = validateTrace[:] + [self] + if self.expr is not None: + self.expr.validate(tmp) + self._checkRecursion([]) + + def _generateDefaultName(self) -> str: + # Avoid infinite recursion by setting a temporary _defaultName + save_default_name = self._defaultName + self._defaultName = ": ..." + + # Use the string representation of main expression. + try: + if self.expr is not None: + ret_string = str(self.expr)[:1000] + else: + ret_string = "None" + except Exception: + ret_string = "..." + + self._defaultName = save_default_name + return f"{type(self).__name__}: {ret_string}" + + def copy(self) -> ParserElement: + """ + Returns a copy of this expression. + + Generally only used internally by pyparsing. + """ + if self.expr is not None: + return super().copy() + else: + ret = Forward() + ret <<= self + return ret + + def _setResultsName(self, name, list_all_matches=False) -> ParserElement: + # fmt: off + if ( + __diag__.warn_name_set_on_empty_Forward + and Diagnostics.warn_name_set_on_empty_Forward not in self.suppress_warnings_ + and self.expr is None + ): + warning = ( + "warn_name_set_on_empty_Forward:" + f" setting results name {name!r} on {type(self).__name__} expression" + " that has no contained expression" + ) + warnings.warn(warning, PyparsingDiagnosticWarning, stacklevel=3) + # fmt: on + + return super()._setResultsName(name, list_all_matches) + + # Compatibility synonyms + # fmt: off + leaveWhitespace = replaced_by_pep8("leaveWhitespace", leave_whitespace) + ignoreWhitespace = replaced_by_pep8("ignoreWhitespace", ignore_whitespace) + # fmt: on + + +class TokenConverter(ParseElementEnhance): + """ + Abstract subclass of :class:`ParseElementEnhance`, for converting parsed results. + """ + + def __init__(self, expr: Union[ParserElement, str], savelist=False) -> None: + super().__init__(expr) # , savelist) + self.saveAsList = False + + +class Combine(TokenConverter): + """Converter to concatenate all matching tokens to a single string. + By default, the matching patterns must also be contiguous in the + input string; this can be disabled by specifying + ``'adjacent=False'`` in the constructor. + + Example: + + .. doctest:: + + >>> real = Word(nums) + '.' + Word(nums) + >>> print(real.parse_string('3.1416')) + ['3', '.', '1416'] + + >>> # will also erroneously match the following + >>> print(real.parse_string('3. 1416')) + ['3', '.', '1416'] + + >>> real = Combine(Word(nums) + '.' + Word(nums)) + >>> print(real.parse_string('3.1416')) + ['3.1416'] + + >>> # no match when there are internal spaces + >>> print(real.parse_string('3. 1416')) + Traceback (most recent call last): + ParseException: Expected W:(0123...) + """ + + def __init__( + self, + expr: ParserElement, + join_string: str = "", + adjacent: bool = True, + *, + joinString: typing.Optional[str] = None, + ) -> None: + super().__init__(expr) + joinString = joinString if joinString is not None else join_string + # suppress whitespace-stripping in contained parse expressions, but re-enable it on the Combine itself + if adjacent: + self.leave_whitespace() + self.adjacent = adjacent + self.skipWhitespace = True + self.joinString = joinString + self.callPreparse = True + + def ignore(self, other) -> ParserElement: + """ + Define expression to be ignored (e.g., comments) while doing pattern + matching; may be called repeatedly, to define multiple comment or other + ignorable patterns. + """ + if self.adjacent: + ParserElement.ignore(self, other) + else: + super().ignore(other) + return self + + def postParse(self, instring, loc, tokenlist): + retToks = tokenlist.copy() + del retToks[:] + retToks += ParseResults( + ["".join(tokenlist._asStringList(self.joinString))], modal=self.modalResults + ) + + if self.resultsName and retToks.haskeys(): + return [retToks] + else: + return retToks + + +class Group(TokenConverter): + """Converter to return the matched tokens as a list - useful for + returning tokens of :class:`ZeroOrMore` and :class:`OneOrMore` expressions. + + The optional ``aslist`` argument when set to True will return the + parsed tokens as a Python list instead of a pyparsing ParseResults. + + Example: + + .. doctest:: + + >>> ident = Word(alphas) + >>> num = Word(nums) + >>> term = ident | num + >>> func = ident + Opt(DelimitedList(term)) + >>> print(func.parse_string("fn a, b, 100")) + ['fn', 'a', 'b', '100'] + + >>> func = ident + Group(Opt(DelimitedList(term))) + >>> print(func.parse_string("fn a, b, 100")) + ['fn', ['a', 'b', '100']] + """ + + def __init__(self, expr: ParserElement, aslist: bool = False) -> None: + super().__init__(expr) + self.saveAsList = True + self._asPythonList = aslist + + def postParse(self, instring, loc, tokenlist): + if self._asPythonList: + return ParseResults.List( + tokenlist.as_list() + if isinstance(tokenlist, ParseResults) + else list(tokenlist) + ) + + return [tokenlist] + + +class Dict(TokenConverter): + """Converter to return a repetitive expression as a list, but also + as a dictionary. Each element can also be referenced using the first + token in the expression as its key. Useful for tabular report + scraping when the first column can be used as a item key. + + The optional ``asdict`` argument when set to True will return the + parsed tokens as a Python dict instead of a pyparsing ParseResults. + + Example: + + .. doctest:: + + >>> data_word = Word(alphas) + >>> label = data_word + FollowedBy(':') + + >>> attr_expr = ( + ... label + Suppress(':') + ... + OneOrMore(data_word, stop_on=label) + ... .set_parse_action(' '.join) + ... ) + + >>> text = "shape: SQUARE posn: upper left color: light blue texture: burlap" + + >>> # print attributes as plain groups + >>> print(attr_expr[1, ...].parse_string(text).dump()) + ['shape', 'SQUARE', 'posn', 'upper left', 'color', 'light blue', 'texture', 'burlap'] + + # instead of OneOrMore(expr), parse using Dict(Group(expr)[1, ...]) + # Dict will auto-assign names. + >>> result = Dict(Group(attr_expr)[1, ...]).parse_string(text) + >>> print(result.dump()) + [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']] + - color: 'light blue' + - posn: 'upper left' + - shape: 'SQUARE' + - texture: 'burlap' + [0]: + ['shape', 'SQUARE'] + [1]: + ['posn', 'upper left'] + [2]: + ['color', 'light blue'] + [3]: + ['texture', 'burlap'] + + # access named fields as dict entries, or output as dict + >>> print(result['shape']) + SQUARE + >>> print(result.as_dict()) + {'shape': 'SQUARE', 'posn': 'upper left', 'color': 'light blue', 'texture': 'burlap'} + + See more examples at :class:`ParseResults` of accessing fields by results name. + """ + + def __init__(self, expr: ParserElement, asdict: bool = False) -> None: + super().__init__(expr) + self.saveAsList = True + self._asPythonDict = asdict + + def postParse(self, instring, loc, tokenlist): + for i, tok in enumerate(tokenlist): + if len(tok) == 0: + continue + + ikey = tok[0] + if isinstance(ikey, int): + ikey = str(ikey).strip() + + if len(tok) == 1: + tokenlist[ikey] = _ParseResultsWithOffset("", i) + + elif len(tok) == 2 and not isinstance(tok[1], ParseResults): + tokenlist[ikey] = _ParseResultsWithOffset(tok[1], i) + + else: + try: + dictvalue = tok.copy() # ParseResults(i) + except Exception: + exc = TypeError( + "could not extract dict values from parsed results" + " - Dict expression must contain Grouped expressions" + ) + raise exc from None + + del dictvalue[0] + + if len(dictvalue) != 1 or ( + isinstance(dictvalue, ParseResults) and dictvalue.haskeys() + ): + tokenlist[ikey] = _ParseResultsWithOffset(dictvalue, i) + else: + tokenlist[ikey] = _ParseResultsWithOffset(dictvalue[0], i) + + if self._asPythonDict: + return [tokenlist.as_dict()] if self.resultsName else tokenlist.as_dict() + + return [tokenlist] if self.resultsName else tokenlist + + +class Suppress(TokenConverter): + """Converter for ignoring the results of a parsed expression. + + Example: + + .. doctest:: + + >>> source = "a, b, c,d" + >>> wd = Word(alphas) + >>> wd_list1 = wd + (',' + wd)[...] + >>> print(wd_list1.parse_string(source)) + ['a', ',', 'b', ',', 'c', ',', 'd'] + + # often, delimiters that are useful during parsing are just in the + # way afterward - use Suppress to keep them out of the parsed output + >>> wd_list2 = wd + (Suppress(',') + wd)[...] + >>> print(wd_list2.parse_string(source)) + ['a', 'b', 'c', 'd'] + + # Skipped text (using '...') can be suppressed as well + >>> source = "lead in START relevant text END trailing text" + >>> start_marker = Keyword("START") + >>> end_marker = Keyword("END") + >>> find_body = Suppress(...) + start_marker + ... + end_marker + >>> print(find_body.parse_string(source)) + ['START', 'relevant text ', 'END'] + + (See also :class:`DelimitedList`.) + """ + + def __init__(self, expr: Union[ParserElement, str], savelist: bool = False) -> None: + if expr is ...: + expr = _PendingSkip(NoMatch()) + super().__init__(expr) + + def __add__(self, other) -> ParserElement: + if isinstance(self.expr, _PendingSkip): + return Suppress(SkipTo(other)) + other + + return super().__add__(other) + + def __sub__(self, other) -> ParserElement: + if isinstance(self.expr, _PendingSkip): + return Suppress(SkipTo(other)) - other + + return super().__sub__(other) + + def postParse(self, instring, loc, tokenlist): + return [] + + def suppress(self) -> ParserElement: + return self + + +# XXX: Example needs to be re-done for updated output +def trace_parse_action(f: ParseAction) -> ParseAction: + """Decorator for debugging parse actions. + + When the parse action is called, this decorator will print + ``">> entering method-name(line:, , )"``. + When the parse action completes, the decorator will print + ``"<<"`` followed by the returned value, or any exception that the parse action raised. + + Example: + + .. testsetup:: stderr + + import sys + sys.stderr = sys.stdout + + .. testcleanup:: stderr + + sys.stderr = sys.__stderr__ + + .. testcode:: stderr + + wd = Word(alphas) + + @trace_parse_action + def remove_duplicate_chars(tokens): + return ''.join(sorted(set(''.join(tokens)))) + + wds = wd[1, ...].set_parse_action(remove_duplicate_chars) + print(wds.parse_string("slkdjs sld sldd sdlf sdljf")) + + prints: + + .. testoutput:: stderr + :options: +NORMALIZE_WHITESPACE + + >>entering remove_duplicate_chars(line: 'slkdjs sld sldd sdlf sdljf', + 0, ParseResults(['slkdjs', 'sld', 'sldd', 'sdlf', 'sdljf'], {})) + < 3: + thisFunc = f"{type(paArgs[0]).__name__}.{thisFunc}" + sys.stderr.write(f">>entering {thisFunc}(line: {line(l, s)!r}, {l}, {t!r})\n") + try: + ret = f(*paArgs) + except Exception as exc: + sys.stderr.write( + f"< str: + r"""Helper to easily define string ranges for use in :class:`Word` + construction. Borrows syntax from regexp ``'[]'`` string range + definitions:: + + srange("[0-9]") -> "0123456789" + srange("[a-z]") -> "abcdefghijklmnopqrstuvwxyz" + srange("[a-z$_]") -> "abcdefghijklmnopqrstuvwxyz$_" + + The input string must be enclosed in []'s, and the returned string + is the expanded character set joined into a single string. The + values enclosed in the []'s may be: + + - a single character + - an escaped character with a leading backslash (such as ``\-`` + or ``\]``) + - an escaped hex character with a leading ``'\x'`` + (``\x21``, which is a ``'!'`` character) (``\0x##`` + is also supported for backwards compatibility) + - an escaped octal character with a leading ``'\0'`` + (``\041``, which is a ``'!'`` character) + - a range of any of the above, separated by a dash (``'a-z'``, + etc.) + - any combination of the above (``'aeiouy'``, + ``'a-zA-Z0-9_$'``, etc.) + """ + + def _expanded(p): + if isinstance(p, ParseResults): + yield from (chr(c) for c in range(ord(p[0]), ord(p[1]) + 1)) + else: + yield p + + try: + return "".join( + [c for part in _reBracketExpr.parse_string(s).body for c in _expanded(part)] + ) + except Exception as e: + return "" + + +def token_map(func, *args) -> ParseAction: + """Helper to define a parse action by mapping a function to all + elements of a :class:`ParseResults` list. If any additional args are passed, + they are forwarded to the given function as additional arguments + after the token, as in + ``hex_integer = Word(hexnums).set_parse_action(token_map(int, 16))``, + which will convert the parsed data to an integer using base 16. + + Example (compare the last to example in :class:`ParserElement.transform_string`:: + + hex_ints = Word(hexnums)[1, ...].set_parse_action(token_map(int, 16)) + hex_ints.run_tests(''' + 00 11 22 aa FF 0a 0d 1a + ''') + + upperword = Word(alphas).set_parse_action(token_map(str.upper)) + upperword[1, ...].run_tests(''' + my kingdom for a horse + ''') + + wd = Word(alphas).set_parse_action(token_map(str.title)) + wd[1, ...].set_parse_action(' '.join).run_tests(''' + now is the winter of our discontent made glorious summer by this sun of york + ''') + + prints:: + + 00 11 22 aa FF 0a 0d 1a + [0, 17, 34, 170, 255, 10, 13, 26] + + my kingdom for a horse + ['MY', 'KINGDOM', 'FOR', 'A', 'HORSE'] + + now is the winter of our discontent made glorious summer by this sun of york + ['Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York'] + """ + + def pa(s, l, t): + return [func(tokn, *args) for tokn in t] + + func_name = getattr(func, "__name__", getattr(func, "__class__").__name__) + pa.__name__ = func_name + + return pa + + +def autoname_elements() -> None: + """ + Utility to simplify mass-naming of parser elements, for + generating railroad diagram with named subdiagrams. + """ + + # guard against _getframe not being implemented in the current Python + getframe_fn = getattr(sys, "_getframe", lambda _: None) + calling_frame = getframe_fn(1) + if calling_frame is None: + return + + # find all locals in the calling frame that are ParserElements + calling_frame = typing.cast(types.FrameType, calling_frame) + for name, var in calling_frame.f_locals.items(): + # if no custom name defined, set the name to the var name + if isinstance(var, ParserElement) and not var.customName: + var.set_name(name) + + +dbl_quoted_string = Combine( + Regex(r'"(?:[^"\n\r\\]|(?:"")|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*') + '"' +).set_name("string enclosed in double quotes") + +sgl_quoted_string = Combine( + Regex(r"'(?:[^'\n\r\\]|(?:'')|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*") + "'" +).set_name("string enclosed in single quotes") + +quoted_string = Combine( + (Regex(r'"(?:[^"\n\r\\]|(?:"")|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*') + '"').set_name( + "double quoted string" + ) + | (Regex(r"'(?:[^'\n\r\\]|(?:'')|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*") + "'").set_name( + "single quoted string" + ) +).set_name("quoted string using single or double quotes") + +# XXX: Is there some way to make this show up in API docs? +# .. versionadded:: 3.1.0 +python_quoted_string = Combine( + (Regex(r'"""(?:[^"\\]|""(?!")|"(?!"")|\\.)*', flags=re.MULTILINE) + '"""').set_name( + "multiline double quoted string" + ) + ^ ( + Regex(r"'''(?:[^'\\]|''(?!')|'(?!'')|\\.)*", flags=re.MULTILINE) + "'''" + ).set_name("multiline single quoted string") + ^ (Regex(r'"(?:[^"\n\r\\]|(?:\\")|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*') + '"').set_name( + "double quoted string" + ) + ^ (Regex(r"'(?:[^'\n\r\\]|(?:\\')|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*") + "'").set_name( + "single quoted string" + ) +).set_name("Python quoted string") + +unicode_string = Combine("u" + quoted_string.copy()).set_name("unicode string literal") + + +alphas8bit = srange(r"[\0xc0-\0xd6\0xd8-\0xf6\0xf8-\0xff]") +punc8bit = srange(r"[\0xa1-\0xbf\0xd7\0xf7]") + +# build list of built-in expressions, for future reference if a global default value +# gets updated +_builtin_exprs: list[ParserElement] = [ + v for v in vars().values() if isinstance(v, ParserElement) +] + +# Compatibility synonyms +# fmt: off +sglQuotedString = sgl_quoted_string +dblQuotedString = dbl_quoted_string +quotedString = quoted_string +unicodeString = unicode_string +lineStart = line_start +lineEnd = line_end +stringStart = string_start +stringEnd = string_end +nullDebugAction = replaced_by_pep8("nullDebugAction", null_debug_action) +traceParseAction = replaced_by_pep8("traceParseAction", trace_parse_action) +conditionAsParseAction = replaced_by_pep8("conditionAsParseAction", condition_as_parse_action) +tokenMap = replaced_by_pep8("tokenMap", token_map) +# fmt: on diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pyparsing/exceptions.py b/TTS/Kokoro/.venv/Lib/site-packages/pyparsing/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..237ca2ebf2b3798570ad8a1fce10544790f70f63 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/pyparsing/exceptions.py @@ -0,0 +1,353 @@ +# exceptions.py +from __future__ import annotations + +import copy +import re +import sys +import typing +import warnings +from functools import cached_property + +from .warnings import PyparsingDeprecationWarning +from .unicode import pyparsing_unicode as ppu +from .util import ( + _collapse_string_to_ranges, + col, + deprecate_argument, + line, + lineno, + replaced_by_pep8, +) + + +class _ExceptionWordUnicodeSet( + ppu.Latin1, ppu.LatinA, ppu.LatinB, ppu.Greek, ppu.Cyrillic +): + pass + + +_extract_alphanums = _collapse_string_to_ranges(_ExceptionWordUnicodeSet.alphanums) +_exception_word_extractor = re.compile(fr"([{_extract_alphanums}]{{1,16}})|.") + + +class ParseBaseException(Exception): + """base exception class for all parsing runtime exceptions""" + + loc: int + msg: str + pstr: str + parser_element: typing.Any # "ParserElement" + args: tuple[str, int, typing.Optional[str]] + + __slots__ = ( + "loc", + "msg", + "pstr", + "parser_element", + "args", + ) + + # Performance tuning: we construct a *lot* of these, so keep this + # constructor as small and fast as possible + def __init__( + self, + pstr: str, + loc: int = 0, + msg: typing.Optional[str] = None, + elem=None, + ) -> None: + if msg is None: + msg, pstr = pstr, "" + + self.loc = loc + self.msg = msg + self.pstr = pstr + self.parser_element = elem + self.args = (pstr, loc, msg) + + @staticmethod + def explain_exception(exc: Exception, depth: int = 16) -> str: + """ + Method to take an exception and translate the Python internal traceback into a list + of the pyparsing expressions that caused the exception to be raised. + + Parameters: + + - exc - exception raised during parsing (need not be a ParseException, in support + of Python exceptions that might be raised in a parse action) + - depth (default=16) - number of levels back in the stack trace to list expression + and function names; if None, the full stack trace names will be listed; if 0, only + the failing input line, marker, and exception string will be shown + + Returns a multi-line string listing the ParserElements and/or function names in the + exception's stack trace. + """ + import inspect + from .core import ParserElement + + if depth is None: + depth = sys.getrecursionlimit() + ret: list[str] = [] + if isinstance(exc, ParseBaseException): + ret.append(exc.line) + ret.append(f"{'^':>{exc.column}}") + ret.append(f"{type(exc).__name__}: {exc}") + + if depth <= 0 or exc.__traceback__ is None: + return "\n".join(ret) + + callers = inspect.getinnerframes(exc.__traceback__, context=depth) + seen: set[int] = set() + for ff in callers[-depth:]: + frm = ff[0] + + f_self = frm.f_locals.get("self", None) + if isinstance(f_self, ParserElement): + if not frm.f_code.co_name.startswith(("parseImpl", "_parseNoCache")): + continue + if id(f_self) in seen: + continue + seen.add(id(f_self)) + + self_type = type(f_self) + ret.append(f"{self_type.__module__}.{self_type.__name__} - {f_self}") + + elif f_self is not None: + self_type = type(f_self) + ret.append(f"{self_type.__module__}.{self_type.__name__}") + + else: + code = frm.f_code + if code.co_name in ("wrapper", ""): + continue + + ret.append(code.co_name) + + depth -= 1 + if not depth: + break + + return "\n".join(ret) + + @classmethod + def _from_exception(cls, pe) -> ParseBaseException: + """ + internal factory method to simplify creating one type of ParseException + from another - avoids having __init__ signature conflicts among subclasses + """ + return cls(pe.pstr, pe.loc, pe.msg, pe.parser_element) + + @cached_property + def line(self) -> str: + """ + Return the line of text where the exception occurred. + """ + return line(self.loc, self.pstr) + + @cached_property + def lineno(self) -> int: + """ + Return the 1-based line number of text where the exception occurred. + """ + return lineno(self.loc, self.pstr) + + @cached_property + def col(self) -> int: + """ + Return the 1-based column on the line of text where the exception occurred. + """ + return col(self.loc, self.pstr) + + @cached_property + def column(self) -> int: + """ + Return the 1-based column on the line of text where the exception occurred. + """ + return col(self.loc, self.pstr) + + @cached_property + def found(self) -> str: + if not self.pstr: + return "" + + if self.loc >= len(self.pstr): + return "end of text" + + # pull out next word at error location + found_match = _exception_word_extractor.match(self.pstr, self.loc) + if found_match is not None: + found_text = found_match[0] + else: + found_text = self.pstr[self.loc : self.loc + 1] + + return repr(found_text).replace(r"\\", "\\") + + # pre-PEP8 compatibility + @property + def parserElement(self): + warnings.warn( + "parserElement is deprecated, use parser_element", + PyparsingDeprecationWarning, + stacklevel=2, + ) + return self.parser_element + + @parserElement.setter + def parserElement(self, elem): + warnings.warn( + "parserElement is deprecated, use parser_element", + PyparsingDeprecationWarning, + stacklevel=2, + ) + self.parser_element = elem + + def copy(self): + return copy.copy(self) + + def formatted_message(self) -> str: + """ + Output the formatted exception message. + Can be overridden to customize the message formatting or contents. + + .. versionadded:: 3.2.0 + """ + found_phrase = f", found {self.found}" if self.found else "" + return f"{self.msg}{found_phrase} (at char {self.loc}), (line:{self.lineno}, col:{self.column})" + + def __str__(self) -> str: + """ + .. versionchanged:: 3.2.0 + Now uses :meth:`formatted_message` to format message. + """ + try: + return self.formatted_message() + except Exception as ex: + return ( + f"{type(self).__name__}: {self.msg}" + f" ({type(ex).__name__}: {ex} while formatting message)" + ) + + def __repr__(self): + return str(self) + + def mark_input_line( + self, marker_string: typing.Optional[str] = None, **kwargs + ) -> str: + """ + Extracts the exception line from the input string, and marks + the location of the exception with a special symbol. + """ + markerString: str = deprecate_argument(kwargs, "markerString", ">!<") + + markerString = marker_string if marker_string is not None else markerString + line_str = self.line + line_column = self.column - 1 + if markerString: + line_str = f"{line_str[:line_column]}{markerString}{line_str[line_column:]}" + return line_str.strip() + + def explain(self, depth: int = 16) -> str: + """ + Method to translate the Python internal traceback into a list + of the pyparsing expressions that caused the exception to be raised. + + Parameters: + + - depth (default=16) - number of levels back in the stack trace to list expression + and function names; if None, the full stack trace names will be listed; if 0, only + the failing input line, marker, and exception string will be shown + + Returns a multi-line string listing the ParserElements and/or function names in the + exception's stack trace. + + Example: + + .. testcode:: + + # an expression to parse 3 integers + expr = pp.Word(pp.nums) * 3 + try: + # a failing parse - the third integer is prefixed with "A" + expr.parse_string("123 456 A789") + except pp.ParseException as pe: + print(pe.explain(depth=0)) + + prints: + + .. testoutput:: + + 123 456 A789 + ^ + ParseException: Expected W:(0-9), found 'A789' (at char 8), (line:1, col:9) + + Note: the diagnostic output will include string representations of the expressions + that failed to parse. These representations will be more helpful if you use `set_name` to + give identifiable names to your expressions. Otherwise they will use the default string + forms, which may be cryptic to read. + + Note: pyparsing's default truncation of exception tracebacks may also truncate the + stack of expressions that are displayed in the ``explain`` output. To get the full listing + of parser expressions, you may have to set ``ParserElement.verbose_stacktrace = True`` + """ + return self.explain_exception(self, depth) + + # Compatibility synonyms + # fmt: off + markInputline = replaced_by_pep8("markInputline", mark_input_line) + # fmt: on + + +class ParseException(ParseBaseException): + """ + Exception thrown when a parse expression doesn't match the input string + + Example: + + .. testcode:: + + integer = Word(nums).set_name("integer") + try: + integer.parse_string("ABC") + except ParseException as pe: + print(pe, f"column: {pe.column}") + + prints: + + .. testoutput:: + + Expected integer, found 'ABC' (at char 0), (line:1, col:1) column: 1 + + """ + + +class ParseFatalException(ParseBaseException): + """ + User-throwable exception thrown when inconsistent parse content + is found; stops all parsing immediately + """ + + +class ParseSyntaxException(ParseFatalException): + """ + Just like :class:`ParseFatalException`, but thrown internally + when an :class:`ErrorStop` ('-' operator) indicates + that parsing is to stop immediately because an unbacktrackable + syntax error has been found. + """ + + +class RecursiveGrammarException(Exception): + """ + .. deprecated:: 3.0.0 + Only used by the deprecated :meth:`ParserElement.validate`. + + Exception thrown by :class:`ParserElement.validate` if the + grammar could be left-recursive; parser may need to enable + left recursion using :class:`ParserElement.enable_left_recursion` + """ + + def __init__(self, parseElementList) -> None: + self.parseElementTrace = parseElementList + + def __str__(self) -> str: + return f"RecursiveGrammarException: {self.parseElementTrace}" diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pyparsing/helpers.py b/TTS/Kokoro/.venv/Lib/site-packages/pyparsing/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..ac9d725a0f4dcbd7f0469332447909cac0551bf8 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/pyparsing/helpers.py @@ -0,0 +1,1220 @@ +# helpers.py +import html.entities +import operator +import re +import sys +import typing + +from . import __diag__ +from .core import * +from .util import ( + _bslash, + _flatten, + _escape_regex_range_chars, + make_compressed_re, + replaced_by_pep8, +) + + +def _suppression(expr: Union[ParserElement, str]) -> ParserElement: + # internal helper to avoid wrapping Suppress inside another Suppress + if isinstance(expr, Suppress): + return expr + return Suppress(expr) + + +# +# global helpers +# +def counted_array( + expr: ParserElement, int_expr: typing.Optional[ParserElement] = None, **kwargs +) -> ParserElement: + """Helper to define a counted list of expressions. + + This helper defines a pattern of the form:: + + integer expr expr expr... + + where the leading integer tells how many expr expressions follow. + The matched tokens returns the array of expr tokens as a list - the + leading count token is suppressed. + + If ``int_expr`` is specified, it should be a pyparsing expression + that produces an integer value. + + Examples: + + .. doctest:: + + >>> counted_array(Word(alphas)).parse_string('2 ab cd ef') + ParseResults(['ab', 'cd'], {}) + + - In this parser, the leading integer value is given in binary, + '10' indicating that 2 values are in the array: + + .. doctest:: + + >>> binary_constant = Word('01').set_parse_action(lambda t: int(t[0], 2)) + >>> counted_array(Word(alphas), int_expr=binary_constant + ... ).parse_string('10 ab cd ef') + ParseResults(['ab', 'cd'], {}) + + - If other fields must be parsed after the count but before the + list items, give the fields results names and they will + be preserved in the returned ParseResults: + + .. doctest:: + + >>> ppc = pyparsing.common + >>> count_with_metadata = ppc.integer + Word(alphas)("type") + >>> typed_array = counted_array(Word(alphanums), + ... int_expr=count_with_metadata)("items") + >>> result = typed_array.parse_string("3 bool True True False") + >>> print(result.dump()) + ['True', 'True', 'False'] + - items: ['True', 'True', 'False'] + - type: 'bool' + """ + intExpr: typing.Optional[ParserElement] = deprecate_argument( + kwargs, "intExpr", None + ) + + intExpr = intExpr or int_expr + array_expr = Forward() + + def count_field_parse_action(s, l, t): + nonlocal array_expr + n = t[0] + array_expr <<= (expr * n) if n else Empty() + # clear list contents, but keep any named results + del t[:] + + if intExpr is None: + intExpr = Word(nums).set_parse_action(lambda t: int(t[0])) + else: + intExpr = intExpr.copy() + intExpr.set_name("arrayLen") + intExpr.add_parse_action(count_field_parse_action, call_during_try=True) + return (intExpr + array_expr).set_name(f"(len) {expr}...") + + +def match_previous_literal(expr: ParserElement) -> ParserElement: + """Helper to define an expression that is indirectly defined from + the tokens matched in a previous expression, that is, it looks for + a 'repeat' of a previous expression. For example:: + + .. testcode:: + + first = Word(nums) + second = match_previous_literal(first) + match_expr = first + ":" + second + + will match ``"1:1"``, but not ``"1:2"``. Because this + matches a previous literal, will also match the leading + ``"1:1"`` in ``"1:10"``. If this is not desired, use + :class:`match_previous_expr`. Do *not* use with packrat parsing + enabled. + """ + rep = Forward() + + def copy_token_to_repeater(s, l, t): + if not t: + rep << Empty() + return + + if len(t) == 1: + rep << t[0] + return + + # flatten t tokens + tflat = _flatten(t.as_list()) + rep << And(Literal(tt) for tt in tflat) + + expr.add_parse_action(copy_token_to_repeater, call_during_try=True) + rep.set_name(f"(prev) {expr}") + return rep + + +def match_previous_expr(expr: ParserElement) -> ParserElement: + """Helper to define an expression that is indirectly defined from + the tokens matched in a previous expression, that is, it looks for + a 'repeat' of a previous expression. For example: + + .. testcode:: + + first = Word(nums) + second = match_previous_expr(first) + match_expr = first + ":" + second + + will match ``"1:1"``, but not ``"1:2"``. Because this + matches by expressions, will *not* match the leading ``"1:1"`` + in ``"1:10"``; the expressions are evaluated first, and then + compared, so ``"1"`` is compared with ``"10"``. Do *not* use + with packrat parsing enabled. + """ + rep = Forward() + e2 = expr.copy() + rep <<= e2 + + def copy_token_to_repeater(s, l, t): + matchTokens = _flatten(t.as_list()) + + def must_match_these_tokens(s, l, t): + theseTokens = _flatten(t.as_list()) + if theseTokens != matchTokens: + raise ParseException( + s, l, f"Expected {matchTokens}, found{theseTokens}" + ) + + rep.set_parse_action(must_match_these_tokens, call_during_try=True) + + expr.add_parse_action(copy_token_to_repeater, call_during_try=True) + rep.set_name(f"(prev) {expr}") + return rep + + +def one_of( + strs: Union[typing.Iterable[str], str], + caseless: bool = False, + use_regex: bool = True, + as_keyword: bool = False, + **kwargs, +) -> ParserElement: + """Helper to quickly define a set of alternative :class:`Literal` s, + and makes sure to do longest-first testing when there is a conflict, + regardless of the input order, but returns + a :class:`MatchFirst` for best performance. + + :param strs: a string of space-delimited literals, or a collection of + string literals + :param caseless: treat all literals as caseless + :param use_regex: bool - as an optimization, will + generate a :class:`Regex` object; otherwise, will generate + a :class:`MatchFirst` object (if ``caseless=True`` or + ``as_keyword=True``, or if creating a :class:`Regex` raises an exception) + :param as_keyword: bool - enforce :class:`Keyword`-style matching on the + generated expressions + + Parameters ``asKeyword`` and ``useRegex`` are retained for pre-PEP8 + compatibility, but will be removed in a future release. + + Example: + + .. testcode:: + + comp_oper = one_of("< = > <= >= !=") + var = Word(alphas) + number = Word(nums) + term = var | number + comparison_expr = term + comp_oper + term + print(comparison_expr.search_string("B = 12 AA=23 B<=AA AA>12")) + + prints: + + .. testoutput:: + + [['B', '=', '12'], ['AA', '=', '23'], ['B', '<=', 'AA'], ['AA', '>', '12']] + """ + useRegex: bool = deprecate_argument(kwargs, "useRegex", True) + asKeyword: bool = deprecate_argument(kwargs, "asKeyword", False) + + asKeyword = asKeyword or as_keyword + useRegex = useRegex and use_regex + + if ( + isinstance(caseless, str_type) + and __diag__.warn_on_multiple_string_args_to_oneof + ): + warnings.warn( + "warn_on_multiple_string_args_to_oneof:" + " More than one string argument passed to one_of, pass" + " choices as a list or space-delimited string", + PyparsingDiagnosticWarning, + stacklevel=2, + ) + + if caseless: + is_equal = lambda a, b: a.upper() == b.upper() + masks = lambda a, b: b.upper().startswith(a.upper()) + else: + is_equal = operator.eq + masks = lambda a, b: b.startswith(a) + + symbols: list[str] + if isinstance(strs, str_type): + strs = typing.cast(str, strs) + symbols = strs.split() + elif isinstance(strs, Iterable): + symbols = list(strs) + else: + raise TypeError("Invalid argument to one_of, expected string or iterable") + if not symbols: + return NoMatch() + + # reorder given symbols to take care to avoid masking longer choices with shorter ones + # (but only if the given symbols are not just single characters) + i = 0 + while i < len(symbols) - 1: + cur = symbols[i] + for j, other in enumerate(symbols[i + 1 :]): + if is_equal(other, cur): + del symbols[i + j + 1] + break + if len(other) > len(cur) and masks(cur, other): + del symbols[i + j + 1] + symbols.insert(i, other) + break + else: + i += 1 + + if useRegex: + re_flags: int = re.IGNORECASE if caseless else 0 + + try: + if all(len(sym) == 1 for sym in symbols): + # symbols are just single characters, create range regex pattern + patt = f"[{''.join(_escape_regex_range_chars(sym) for sym in symbols)}]" + else: + patt = "|".join(re.escape(sym) for sym in symbols) + + # wrap with \b word break markers if defining as keywords + if asKeyword: + patt = rf"\b(?:{patt})\b" + + ret = Regex(patt, flags=re_flags) + ret.set_name(" | ".join(repr(s) for s in symbols)) + + if caseless: + # add parse action to return symbols as specified, not in random + # casing as found in input string + symbol_map = {sym.lower(): sym for sym in symbols} + ret.add_parse_action(lambda s, l, t: symbol_map[t[0].lower()]) + + return ret + + except re.error: + warnings.warn( + "Exception creating Regex for one_of, building MatchFirst", + PyparsingDiagnosticWarning, + stacklevel=2, + ) + + # last resort, just use MatchFirst of Token class corresponding to caseless + # and asKeyword settings + CASELESS = KEYWORD = True + parse_element_class = { + (CASELESS, KEYWORD): CaselessKeyword, + (CASELESS, not KEYWORD): CaselessLiteral, + (not CASELESS, KEYWORD): Keyword, + (not CASELESS, not KEYWORD): Literal, + }[(caseless, asKeyword)] + return MatchFirst(parse_element_class(sym) for sym in symbols).set_name( + " | ".join(symbols) + ) + + +def dict_of(key: ParserElement, value: ParserElement) -> Dict: + """Helper to easily and clearly define a dictionary by specifying + the respective patterns for the key and value. Takes care of + defining the :class:`Dict`, :class:`ZeroOrMore`, and + :class:`Group` tokens in the proper order. The key pattern + can include delimiting markers or punctuation, as long as they are + suppressed, thereby leaving the significant key text. The value + pattern can include named results, so that the :class:`Dict` results + can include named token fields. + + Example: + + .. doctest:: + + >>> text = "shape: SQUARE posn: upper left color: light blue texture: burlap" + + >>> data_word = Word(alphas) + >>> label = data_word + FollowedBy(':') + >>> attr_expr = ( + ... label + ... + Suppress(':') + ... + OneOrMore(data_word, stop_on=label) + ... .set_parse_action(' '.join)) + >>> print(attr_expr[1, ...].parse_string(text).dump()) + ['shape', 'SQUARE', 'posn', 'upper left', 'color', 'light blue', 'texture', 'burlap'] + + >>> attr_label = label + >>> attr_value = Suppress(':') + OneOrMore(data_word, stop_on=label + ... ).set_parse_action(' '.join) + + # similar to Dict, but simpler call format + >>> result = dict_of(attr_label, attr_value).parse_string(text) + >>> print(result.dump()) + [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']] + - color: 'light blue' + - posn: 'upper left' + - shape: 'SQUARE' + - texture: 'burlap' + [0]: + ['shape', 'SQUARE'] + [1]: + ['posn', 'upper left'] + [2]: + ['color', 'light blue'] + [3]: + ['texture', 'burlap'] + + >>> print(result['shape']) + SQUARE + >>> print(result.shape) # object attribute access works too + SQUARE + >>> print(result.as_dict()) + {'shape': 'SQUARE', 'posn': 'upper left', 'color': 'light blue', 'texture': 'burlap'} + """ + return Dict(OneOrMore(Group(key + value))) + + +def original_text_for( + expr: ParserElement, as_string: bool = True, **kwargs +) -> ParserElement: + """Helper to return the original, untokenized text for a given + expression. Useful to restore the parsed fields of an HTML start + tag into the raw tag text itself, or to revert separate tokens with + intervening whitespace back to the original matching input text. By + default, returns a string containing the original parsed text. + + If the optional ``as_string`` argument is passed as + ``False``, then the return value is + a :class:`ParseResults` containing any results names that + were originally matched, and a single token containing the original + matched text from the input string. So if the expression passed to + :class:`original_text_for` contains expressions with defined + results names, you must set ``as_string`` to ``False`` if you + want to preserve those results name values. + + The ``asString`` pre-PEP8 argument is retained for compatibility, + but will be removed in a future release. + + Example: + + .. testcode:: + + src = "this is test bold text normal text " + for tag in ("b", "i"): + opener, closer = make_html_tags(tag) + patt = original_text_for(opener + ... + closer) + print(patt.search_string(src)[0]) + + prints: + + .. testoutput:: + + [' bold text '] + ['text'] + """ + asString: bool = deprecate_argument(kwargs, "asString", True) + + asString = asString and as_string + + locMarker = Empty().set_parse_action(lambda s, loc, t: loc) + endlocMarker = locMarker.copy() + endlocMarker.callPreparse = False + matchExpr = locMarker("_original_start") + expr + endlocMarker("_original_end") + if asString: + extractText = lambda s, l, t: s[t._original_start : t._original_end] + else: + + def extractText(s, l, t): + t[:] = [s[t.pop("_original_start") : t.pop("_original_end")]] + + matchExpr.set_parse_action(extractText) + matchExpr.ignoreExprs = expr.ignoreExprs + matchExpr.suppress_warning(Diagnostics.warn_ungrouped_named_tokens_in_collection) + return matchExpr + + +def ungroup(expr: ParserElement) -> ParserElement: + """Helper to undo pyparsing's default grouping of And expressions, + even if all but one are non-empty. + """ + return TokenConverter(expr).add_parse_action(lambda t: t[0]) + + +def locatedExpr(expr: ParserElement) -> ParserElement: + """ + .. deprecated:: 3.0.0 + Use the :class:`Located` class instead. Note that `Located` + returns results with one less grouping level. + + Helper to decorate a returned token with its starting and ending + locations in the input string. + + This helper adds the following results names: + + - ``locn_start`` - location where matched expression begins + - ``locn_end`` - location where matched expression ends + - ``value`` - the actual parsed results + + Be careful if the input text contains ```` characters, you + may want to call :meth:`ParserElement.parse_with_tabs` + """ + warnings.warn( + f"{'locatedExpr'!r} deprecated - use {'Located'!r}", + PyparsingDeprecationWarning, + stacklevel=2, + ) + + locator = Empty().set_parse_action(lambda ss, ll, tt: ll) + return Group( + locator("locn_start") + + expr("value") + + locator.copy().leave_whitespace()("locn_end") + ) + + +# define special default value to permit None as a significant value for +# ignore_expr +_NO_IGNORE_EXPR_GIVEN = NoMatch() + + +def nested_expr( + opener: Union[str, ParserElement] = "(", + closer: Union[str, ParserElement] = ")", + content: typing.Optional[ParserElement] = None, + ignore_expr: typing.Optional[ParserElement] = _NO_IGNORE_EXPR_GIVEN, + **kwargs, +) -> ParserElement: + """Helper method for defining nested lists enclosed in opening and + closing delimiters (``"("`` and ``")"`` are the default). + + :param opener: str - opening character for a nested list + (default= ``"("``); can also be a pyparsing expression + + :param closer: str - closing character for a nested list + (default= ``")"``); can also be a pyparsing expression + + :param content: expression for items within the nested lists + + :param ignore_expr: expression for ignoring opening and closing delimiters + (default = :class:`quoted_string`) + + Parameter ``ignoreExpr`` is retained for compatibility + but will be removed in a future release. + + If an expression is not provided for the content argument, the + nested expression will capture all whitespace-delimited content + between delimiters as a list of separate values. + + Use the ``ignore_expr`` argument to define expressions that may + contain opening or closing characters that should not be treated as + opening or closing characters for nesting, such as quoted_string or + a comment expression. Specify multiple expressions using an + :class:`Or` or :class:`MatchFirst`. The default is + :class:`quoted_string`, but if no expressions are to be ignored, then + pass ``None`` for this argument. + + Example: + + .. testcode:: + + data_type = one_of("void int short long char float double") + decl_data_type = Combine(data_type + Opt(Word('*'))) + ident = Word(alphas+'_', alphanums+'_') + number = pyparsing_common.number + arg = Group(decl_data_type + ident) + LPAR, RPAR = map(Suppress, "()") + + code_body = nested_expr('{', '}', ignore_expr=(quoted_string | c_style_comment)) + + c_function = (decl_data_type("type") + + ident("name") + + LPAR + Opt(DelimitedList(arg), [])("args") + RPAR + + code_body("body")) + c_function.ignore(c_style_comment) + + source_code = ''' + int is_odd(int x) { + return (x%2); + } + + int dec_to_hex(char hchar) { + if (hchar >= '0' && hchar <= '9') { + return (ord(hchar)-ord('0')); + } else { + return (10+ord(hchar)-ord('A')); + } + } + ''' + for func in c_function.search_string(source_code): + print(f"{func.name} ({func.type}) args: {func.args}") + + + prints: + + .. testoutput:: + + is_odd (int) args: [['int', 'x']] + dec_to_hex (int) args: [['char', 'hchar']] + """ + ignoreExpr: ParserElement = deprecate_argument( + kwargs, "ignoreExpr", _NO_IGNORE_EXPR_GIVEN + ) + + if ignoreExpr != ignore_expr: + ignoreExpr = ignore_expr if ignoreExpr is _NO_IGNORE_EXPR_GIVEN else ignoreExpr # type: ignore [assignment] + + if ignoreExpr is _NO_IGNORE_EXPR_GIVEN: + ignoreExpr = quoted_string() + + if opener == closer: + raise ValueError("opening and closing strings cannot be the same") + + if content is None: + if isinstance(opener, str_type) and isinstance(closer, str_type): + opener = typing.cast(str, opener) + closer = typing.cast(str, closer) + if len(opener) == 1 and len(closer) == 1: + if ignoreExpr is not None: + content = Combine( + OneOrMore( + ~ignoreExpr + + CharsNotIn( + opener + closer + ParserElement.DEFAULT_WHITE_CHARS, + exact=1, + ) + ) + ) + else: + content = Combine( + Empty() + + CharsNotIn( + opener + closer + ParserElement.DEFAULT_WHITE_CHARS + ) + ) + else: + if ignoreExpr is not None: + content = Combine( + OneOrMore( + ~ignoreExpr + + ~Literal(opener) + + ~Literal(closer) + + CharsNotIn(ParserElement.DEFAULT_WHITE_CHARS, exact=1) + ) + ) + else: + content = Combine( + OneOrMore( + ~Literal(opener) + + ~Literal(closer) + + CharsNotIn(ParserElement.DEFAULT_WHITE_CHARS, exact=1) + ) + ) + else: + raise ValueError( + "opening and closing arguments must be strings if no content expression is given" + ) + + # for these internally-created context expressions, simulate whitespace-skipping + if ParserElement.DEFAULT_WHITE_CHARS: + content.set_parse_action( + lambda t: t[0].strip(ParserElement.DEFAULT_WHITE_CHARS) + ) + + ret = Forward() + if ignoreExpr is not None: + ret <<= Group( + _suppression(opener) + + ZeroOrMore(ignoreExpr | ret | content) + + _suppression(closer) + ) + else: + ret <<= Group( + _suppression(opener) + ZeroOrMore(ret | content) + _suppression(closer) + ) + + ret.set_name(f"nested {opener}{closer} expression") + + # don't override error message from content expressions + ret.errmsg = None + return ret + + +def _makeTags(tagStr, xml, suppress_LT=Suppress("<"), suppress_GT=Suppress(">")): + """Internal helper to construct opening and closing tag expressions, + given a tag name""" + if isinstance(tagStr, str_type): + resname = tagStr + tagStr = Keyword(tagStr, caseless=not xml) + else: + resname = tagStr.name + + tagAttrName = Word(alphas, alphanums + "_-:") + if xml: + tagAttrValue = dbl_quoted_string.copy().set_parse_action(remove_quotes) + openTag = ( + suppress_LT + + tagStr("tag") + + Dict(ZeroOrMore(Group(tagAttrName + Suppress("=") + tagAttrValue))) + + Opt("/", default=[False])("empty").set_parse_action( + lambda s, l, t: t[0] == "/" + ) + + suppress_GT + ) + else: + tagAttrValue = quoted_string.copy().set_parse_action(remove_quotes) | Word( + printables, exclude_chars=">" + ) + openTag = ( + suppress_LT + + tagStr("tag") + + Dict( + ZeroOrMore( + Group( + tagAttrName.set_parse_action(lambda t: t[0].lower()) + + Opt(Suppress("=") + tagAttrValue) + ) + ) + ) + + Opt("/", default=[False])("empty").set_parse_action( + lambda s, l, t: t[0] == "/" + ) + + suppress_GT + ) + closeTag = Combine(Literal("", adjacent=False) + + openTag.set_name(f"<{resname}>") + # add start results name in parse action now that ungrouped names are not reported at two levels + openTag.add_parse_action( + lambda t: t.__setitem__( + "start" + "".join(resname.replace(":", " ").title().split()), t.copy() + ) + ) + closeTag = closeTag( + "end" + "".join(resname.replace(":", " ").title().split()) + ).set_name(f"") + openTag.tag = resname + closeTag.tag = resname + openTag.tag_body = SkipTo(closeTag()) + return openTag, closeTag + + +def make_html_tags( + tag_str: Union[str, ParserElement], +) -> tuple[ParserElement, ParserElement]: + """Helper to construct opening and closing tag expressions for HTML, + given a tag name. Matches tags in either upper or lower case, + attributes with namespaces and with quoted or unquoted values. + + Example: + + .. testcode:: + + text = 'More info at the pyparsing wiki page' + # make_html_tags returns pyparsing expressions for the opening and + # closing tags as a 2-tuple + a, a_end = make_html_tags("A") + link_expr = a + SkipTo(a_end)("link_text") + a_end + + for link in link_expr.search_string(text): + # attributes in the tag (like "href" shown here) are + # also accessible as named results + print(link.link_text, '->', link.href) + + prints: + + .. testoutput:: + + pyparsing -> https://github.com/pyparsing/pyparsing/wiki + """ + return _makeTags(tag_str, False) + + +def make_xml_tags( + tag_str: Union[str, ParserElement], +) -> tuple[ParserElement, ParserElement]: + """Helper to construct opening and closing tag expressions for XML, + given a tag name. Matches tags only in the given upper/lower case. + + Example: similar to :class:`make_html_tags` + """ + return _makeTags(tag_str, True) + + +any_open_tag: ParserElement +any_close_tag: ParserElement +any_open_tag, any_close_tag = make_html_tags( + Word(alphas, alphanums + "_:").set_name("any tag") +) + +_htmlEntityMap = {k.rstrip(";"): v for k, v in html.entities.html5.items()} +_most_common_entities = "nbsp lt gt amp quot apos cent pound euro copy".replace( + " ", "|" +) +common_html_entity = Regex( + lambda: f"&(?P{_most_common_entities}|{make_compressed_re(_htmlEntityMap)});" +).set_name("common HTML entity") + + +def replace_html_entity(s, l, t): + """Helper parser action to replace common HTML entities with their special characters""" + return _htmlEntityMap.get(t.entity) + + +class OpAssoc(Enum): + """Enumeration of operator associativity + - used in constructing InfixNotationOperatorSpec for :class:`infix_notation`""" + + LEFT = 1 + RIGHT = 2 + + +InfixNotationOperatorArgType = Union[ + ParserElement, str, tuple[Union[ParserElement, str], Union[ParserElement, str]] +] +InfixNotationOperatorSpec = Union[ + tuple[ + InfixNotationOperatorArgType, + int, + OpAssoc, + typing.Optional[ParseAction], + ], + tuple[ + InfixNotationOperatorArgType, + int, + OpAssoc, + ], +] + + +def infix_notation( + base_expr: ParserElement, + op_list: list[InfixNotationOperatorSpec], + lpar: Union[str, ParserElement] = Suppress("("), + rpar: Union[str, ParserElement] = Suppress(")"), +) -> Forward: + """Helper method for constructing grammars of expressions made up of + operators working in a precedence hierarchy. Operators may be unary + or binary, left- or right-associative. Parse actions can also be + attached to operator expressions. The generated parser will also + recognize the use of parentheses to override operator precedences + (see example below). + + Note: if you define a deep operator list, you may see performance + issues when using infix_notation. See + :class:`ParserElement.enable_packrat` for a mechanism to potentially + improve your parser performance. + + Parameters: + + :param base_expr: expression representing the most basic operand to + be used in the expression + :param op_list: list of tuples, one for each operator precedence level + in the expression grammar; each tuple is of the form ``(op_expr, + num_operands, right_left_assoc, (optional)parse_action)``, where: + + - ``op_expr`` is the pyparsing expression for the operator; may also + be a string, which will be converted to a Literal; if ``num_operands`` + is 3, ``op_expr`` is a tuple of two expressions, for the two + operators separating the 3 terms + - ``num_operands`` is the number of terms for this operator (must be 1, + 2, or 3) + - ``right_left_assoc`` is the indicator whether the operator is right + or left associative, using the pyparsing-defined constants + ``OpAssoc.RIGHT`` and ``OpAssoc.LEFT``. + - ``parse_action`` is the parse action to be associated with + expressions matching this operator expression (the parse action + tuple member may be omitted); if the parse action is passed + a tuple or list of functions, this is equivalent to calling + ``set_parse_action(*fn)`` + (:class:`ParserElement.set_parse_action`) + + :param lpar: expression for matching left-parentheses; if passed as a + str, then will be parsed as ``Suppress(lpar)``. If lpar is passed as + an expression (such as ``Literal('(')``), then it will be kept in + the parsed results, and grouped with them. (default= ``Suppress('(')``) + :param rpar: expression for matching right-parentheses; if passed as a + str, then will be parsed as ``Suppress(rpar)``. If rpar is passed as + an expression (such as ``Literal(')')``), then it will be kept in + the parsed results, and grouped with them. (default= ``Suppress(')')``) + + Example: + + .. testcode:: + + # simple example of four-function arithmetic with ints and + # variable names + integer = pyparsing_common.signed_integer + varname = pyparsing_common.identifier + + arith_expr = infix_notation(integer | varname, + [ + ('-', 1, OpAssoc.RIGHT), + (one_of('* /'), 2, OpAssoc.LEFT), + (one_of('+ -'), 2, OpAssoc.LEFT), + ]) + + arith_expr.run_tests(''' + 5+3*6 + (5+3)*6 + (5+x)*y + -2--11 + ''', full_dump=False) + + prints: + + .. testoutput:: + :options: +NORMALIZE_WHITESPACE + + + 5+3*6 + [[5, '+', [3, '*', 6]]] + + (5+3)*6 + [[[5, '+', 3], '*', 6]] + + (5+x)*y + [[[5, '+', 'x'], '*', 'y']] + + -2--11 + [[['-', 2], '-', ['-', 11]]] + """ + + # captive version of FollowedBy that does not do parse actions or capture results names + class _FB(FollowedBy): + def parseImpl(self, instring, loc, doActions=True): + self.expr.try_parse(instring, loc) + return loc, [] + + _FB.__name__ = "FollowedBy>" + + ret = Forward() + ret.set_name(f"{base_expr.name}_expression") + if isinstance(lpar, str): + lpar = Suppress(lpar) + if isinstance(rpar, str): + rpar = Suppress(rpar) + + nested_expr = (lpar + ret + rpar).set_name(f"nested_{base_expr.name}_expression") + + # if lpar and rpar are not suppressed, wrap in group + if not (isinstance(lpar, Suppress) and isinstance(rpar, Suppress)): + lastExpr = base_expr | Group(nested_expr) + else: + lastExpr = base_expr | nested_expr + + arity: int + rightLeftAssoc: opAssoc + pa: typing.Optional[ParseAction] + opExpr1: ParserElement + opExpr2: ParserElement + matchExpr: ParserElement + match_lookahead: ParserElement + for operDef in op_list: + opExpr, arity, rightLeftAssoc, pa = (operDef + (None,))[:4] # type: ignore[assignment] + if isinstance(opExpr, str_type): + opExpr = ParserElement._literalStringClass(opExpr) + opExpr = typing.cast(ParserElement, opExpr) + if arity == 3: + if not isinstance(opExpr, (tuple, list)) or len(opExpr) != 2: + raise ValueError( + "if numterms=3, opExpr must be a tuple or list of two expressions" + ) + opExpr1, opExpr2 = opExpr + term_name = f"{opExpr1}{opExpr2} operations" + else: + term_name = f"{opExpr} operations" + + if not 1 <= arity <= 3: + raise ValueError("operator must be unary (1), binary (2), or ternary (3)") + + if rightLeftAssoc not in (OpAssoc.LEFT, OpAssoc.RIGHT): + raise ValueError("operator must indicate right or left associativity") + + thisExpr: ParserElement = Forward().set_name(term_name) + thisExpr = typing.cast(Forward, thisExpr) + match_lookahead = And([]) + if rightLeftAssoc is OpAssoc.LEFT: + if arity == 1: + match_lookahead = _FB(lastExpr + opExpr) + matchExpr = Group(lastExpr + opExpr[1, ...]) + elif arity == 2: + if opExpr is not None: + match_lookahead = _FB(lastExpr + opExpr + lastExpr) + matchExpr = Group(lastExpr + (opExpr + lastExpr)[1, ...]) + else: + match_lookahead = _FB(lastExpr + lastExpr) + matchExpr = Group(lastExpr[2, ...]) + elif arity == 3: + match_lookahead = _FB( + lastExpr + opExpr1 + lastExpr + opExpr2 + lastExpr + ) + matchExpr = Group( + lastExpr + (opExpr1 + lastExpr + opExpr2 + lastExpr)[1, ...] + ) + elif rightLeftAssoc is OpAssoc.RIGHT: + if arity == 1: + # try to avoid LR with this extra test + if not isinstance(opExpr, Opt): + opExpr = Opt(opExpr) + match_lookahead = _FB(opExpr.expr + thisExpr) + matchExpr = Group(opExpr + thisExpr) + elif arity == 2: + if opExpr is not None: + match_lookahead = _FB(lastExpr + opExpr + thisExpr) + matchExpr = Group(lastExpr + (opExpr + thisExpr)[1, ...]) + else: + match_lookahead = _FB(lastExpr + thisExpr) + matchExpr = Group(lastExpr + thisExpr[1, ...]) + elif arity == 3: + match_lookahead = _FB( + lastExpr + opExpr1 + thisExpr + opExpr2 + thisExpr + ) + matchExpr = Group(lastExpr + opExpr1 + thisExpr + opExpr2 + thisExpr) + + # suppress lookahead expr from railroad diagrams + match_lookahead.show_in_diagram = False + + # TODO - determine why this statement can't be included in the following + # if pa block + matchExpr = match_lookahead + matchExpr + + if pa: + if isinstance(pa, (tuple, list)): + matchExpr.set_parse_action(*pa) + else: + matchExpr.set_parse_action(pa) + + thisExpr <<= (matchExpr | lastExpr).set_name(term_name) + lastExpr = thisExpr + + ret <<= lastExpr + return ret + + +def indentedBlock(blockStatementExpr, indentStack, indent=True, backup_stacks=[]): + """ + .. deprecated:: 3.0.0 + Use the :class:`IndentedBlock` class instead. Note that `IndentedBlock` + has a difference method signature. + + Helper method for defining space-delimited indentation blocks, + such as those used to define block statements in Python source code. + + :param blockStatementExpr: expression defining syntax of statement that + is repeated within the indented block + + :param indentStack: list created by caller to manage indentation stack + (multiple ``statementWithIndentedBlock`` expressions within a single + grammar should share a common ``indentStack``) + + :param indent: boolean indicating whether block must be indented beyond + the current level; set to ``False`` for block of left-most statements + + A valid block must contain at least one ``blockStatement``. + + (Note that indentedBlock uses internal parse actions which make it + incompatible with packrat parsing.) + + Example: + + .. testcode:: + + data = ''' + def A(z): + A1 + B = 100 + G = A2 + A2 + A3 + B + def BB(a,b,c): + BB1 + def BBA(): + bba1 + bba2 + bba3 + C + D + def spam(x,y): + def eggs(z): + pass + ''' + + indentStack = [1] + stmt = Forward() + + identifier = Word(alphas, alphanums) + funcDecl = ("def" + identifier + Group("(" + Opt(delimitedList(identifier)) + ")") + ":") + func_body = indentedBlock(stmt, indentStack) + funcDef = Group(funcDecl + func_body) + + rvalue = Forward() + funcCall = Group(identifier + "(" + Opt(delimitedList(rvalue)) + ")") + rvalue << (funcCall | identifier | Word(nums)) + assignment = Group(identifier + "=" + rvalue) + stmt << (funcDef | assignment | identifier) + + module_body = stmt[1, ...] + + parseTree = module_body.parseString(data) + parseTree.pprint() + + prints: + + .. testoutput:: + + [['def', + 'A', + ['(', 'z', ')'], + ':', + [['A1'], [['B', '=', '100']], [['G', '=', 'A2']], ['A2'], ['A3']]], + 'B', + ['def', + 'BB', + ['(', 'a', 'b', 'c', ')'], + ':', + [['BB1'], [['def', 'BBA', ['(', ')'], ':', [['bba1'], ['bba2'], ['bba3']]]]]], + 'C', + 'D', + ['def', + 'spam', + ['(', 'x', 'y', ')'], + ':', + [[['def', 'eggs', ['(', 'z', ')'], ':', [['pass']]]]]]] + """ + warnings.warn( + f"{'indentedBlock'!r} deprecated - use {'IndentedBlock'!r}", + PyparsingDeprecationWarning, + stacklevel=2, + ) + + backup_stacks.append(indentStack[:]) + + def reset_stack(): + indentStack[:] = backup_stacks[-1] + + def checkPeerIndent(s, l, t): + if l >= len(s): + return + curCol = col(l, s) + if curCol != indentStack[-1]: + if curCol > indentStack[-1]: + raise ParseException(s, l, "illegal nesting") + raise ParseException(s, l, "not a peer entry") + + def checkSubIndent(s, l, t): + curCol = col(l, s) + if curCol > indentStack[-1]: + indentStack.append(curCol) + else: + raise ParseException(s, l, "not a subentry") + + def checkUnindent(s, l, t): + if l >= len(s): + return + curCol = col(l, s) + if not (indentStack and curCol in indentStack): + raise ParseException(s, l, "not an unindent") + if curCol < indentStack[-1]: + indentStack.pop() + + NL = OneOrMore(LineEnd().set_whitespace_chars("\t ").suppress()) + INDENT = (Empty() + Empty().set_parse_action(checkSubIndent)).set_name("INDENT") + PEER = Empty().set_parse_action(checkPeerIndent).set_name("") + UNDENT = Empty().set_parse_action(checkUnindent).set_name("UNINDENT") + if indent: + smExpr = Group( + Opt(NL) + + INDENT + + OneOrMore(PEER + Group(blockStatementExpr) + Opt(NL)) + + UNDENT + ) + else: + smExpr = Group( + Opt(NL) + + OneOrMore(PEER + Group(blockStatementExpr) + Opt(NL)) + + Opt(UNDENT) + ) + + # add a parse action to remove backup_stack from list of backups + smExpr.add_parse_action( + lambda: backup_stacks.pop(-1) and None if backup_stacks else None + ) + smExpr.set_fail_action(lambda a, b, c, d: reset_stack()) + blockStatementExpr.ignore(_bslash + LineEnd()) + return smExpr.set_name("indented block") + + +# it's easy to get these comment structures wrong - they're very common, +# so may as well make them available +c_style_comment = Regex(r"/\*(?:[^*]|\*(?!/))*\*\/").set_name("C style comment") +"Comment of the form ``/* ... */``" + +html_comment = Regex(r"").set_name("HTML comment") +"Comment of the form ````" + +rest_of_line = Regex(r".*").leave_whitespace().set_name("rest of line") +dbl_slash_comment = Regex(r"//(?:\\\n|[^\n])*").set_name("// comment") +"Comment of the form ``// ... (to end of line)``" + +cpp_style_comment = Regex( + r"(?:/\*(?:[^*]|\*(?!/))*\*\/)|(?://(?:\\\n|[^\n])*)" +).set_name("C++ style comment") +"Comment of either form :class:`c_style_comment` or :class:`dbl_slash_comment`" + +java_style_comment = cpp_style_comment +"Same as :class:`cpp_style_comment`" + +python_style_comment = Regex(r"#.*").set_name("Python style comment") +"Comment of the form ``# ... (to end of line)``" + + +# build list of built-in expressions, for future reference if a global default value +# gets updated +_builtin_exprs: list[ParserElement] = [ + v for v in vars().values() if isinstance(v, ParserElement) +] + + +# compatibility function, superseded by DelimitedList class +def delimited_list( + expr: Union[str, ParserElement], + delim: Union[str, ParserElement] = ",", + combine: bool = False, + min: typing.Optional[int] = None, + max: typing.Optional[int] = None, + *, + allow_trailing_delim: bool = False, +) -> ParserElement: + """ + .. deprecated:: 3.1.0 + Use the :class:`DelimitedList` class instead. + """ + return DelimitedList( + expr, delim, combine, min, max, allow_trailing_delim=allow_trailing_delim + ) + + +# Compatibility synonyms +# fmt: off +opAssoc = OpAssoc +anyOpenTag = any_open_tag +anyCloseTag = any_close_tag +commonHTMLEntity = common_html_entity +cStyleComment = c_style_comment +htmlComment = html_comment +restOfLine = rest_of_line +dblSlashComment = dbl_slash_comment +cppStyleComment = cpp_style_comment +javaStyleComment = java_style_comment +pythonStyleComment = python_style_comment +delimitedList = replaced_by_pep8("delimitedList", DelimitedList) +delimited_list = replaced_by_pep8("delimited_list", DelimitedList) +countedArray = replaced_by_pep8("countedArray", counted_array) +matchPreviousLiteral = replaced_by_pep8("matchPreviousLiteral", match_previous_literal) +matchPreviousExpr = replaced_by_pep8("matchPreviousExpr", match_previous_expr) +oneOf = replaced_by_pep8("oneOf", one_of) +dictOf = replaced_by_pep8("dictOf", dict_of) +originalTextFor = replaced_by_pep8("originalTextFor", original_text_for) +nestedExpr = replaced_by_pep8("nestedExpr", nested_expr) +makeHTMLTags = replaced_by_pep8("makeHTMLTags", make_html_tags) +makeXMLTags = replaced_by_pep8("makeXMLTags", make_xml_tags) +replaceHTMLEntity = replaced_by_pep8("replaceHTMLEntity", replace_html_entity) +infixNotation = replaced_by_pep8("infixNotation", infix_notation) +# fmt: on diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pyparsing/py.typed b/TTS/Kokoro/.venv/Lib/site-packages/pyparsing/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pyparsing/results.py b/TTS/Kokoro/.venv/Lib/site-packages/pyparsing/results.py new file mode 100644 index 0000000000000000000000000000000000000000..f7d674f180b6721187da8945cfad64a2a8ac67a5 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/pyparsing/results.py @@ -0,0 +1,928 @@ +# results.py + +from __future__ import annotations + +import collections +from collections.abc import ( + MutableMapping, + Mapping, + MutableSequence, + Iterator, + Iterable, +) +import pprint +from typing import Any + +from .util import deprecate_argument, _is_iterable, _flatten + + +str_type: tuple[type, ...] = (str, bytes) +_generator_type = type((_ for _ in ())) +NULL_SLICE: slice = slice(None) + + +class _ParseResultsWithOffset: + tup: tuple[ParseResults, int] + __slots__ = ["tup"] + + def __init__(self, p1: ParseResults, p2: int) -> None: + self.tup: tuple[ParseResults, int] = (p1, p2) + + def __getitem__(self, i): + return self.tup[i] + + def __getstate__(self): + return self.tup + + def __setstate__(self, *args): + self.tup = args[0] + + +class ParseResults: + """Structured parse results, to provide multiple means of access to + the parsed data: + + - as a list (``len(results)``) + - by list index (``results[0], results[1]``, etc.) + - by attribute (``results.`` - see :class:`ParserElement.set_results_name`) + + Example: + + .. testcode:: + + integer = Word(nums) + date_str = (integer.set_results_name("year") + '/' + + integer.set_results_name("month") + '/' + + integer.set_results_name("day")) + # equivalent form: + # date_str = (integer("year") + '/' + # + integer("month") + '/' + # + integer("day")) + + # parse_string returns a ParseResults object + result = date_str.parse_string("1999/12/31") + + def test(s, fn=repr): + print(f"{s} -> {fn(eval(s))}") + + test("list(result)") + test("result[0]") + test("result['month']") + test("result.day") + test("'month' in result") + test("'minutes' in result") + test("result.dump()", str) + + prints: + + .. testoutput:: + + list(result) -> ['1999', '/', '12', '/', '31'] + result[0] -> '1999' + result['month'] -> '12' + result.day -> '31' + 'month' in result -> True + 'minutes' in result -> False + result.dump() -> ['1999', '/', '12', '/', '31'] + - day: '31' + - month: '12' + - year: '1999' + + """ + + _null_values: tuple[Any, ...] = (None, [], ()) + + _name: str + _parent: ParseResults + _all_names: set[str] + _modal: bool + _toklist: list[Any] + _tokdict: dict[str, Any] + + __slots__ = ( + "_name", + "_parent", + "_all_names", + "_modal", + "_toklist", + "_tokdict", + ) + + class List(list): + """ + Simple wrapper class to distinguish parsed list results that should be preserved + as actual Python lists, instead of being converted to :class:`ParseResults`: + + .. testcode:: + + import pyparsing as pp + ppc = pp.common + + LBRACK, RBRACK, LPAR, RPAR = pp.Suppress.using_each("[]()") + element = pp.Forward() + item = ppc.integer + item_list = pp.DelimitedList(element) + element_list = LBRACK + item_list + RBRACK | LPAR + item_list + RPAR + element <<= item | element_list + + # add parse action to convert from ParseResults + # to actual Python collection types + @element_list.add_parse_action + def as_python_list(t): + return pp.ParseResults.List(t.as_list()) + + element.run_tests(''' + 100 + [2,3,4] + [[2, 1],3,4] + [(2, 1),3,4] + (2,3,4) + ([2, 3], 4) + ''', post_parse=lambda s, r: (r[0], type(r[0])) + ) + + prints: + + .. testoutput:: + :options: +NORMALIZE_WHITESPACE + + + 100 + (100, ) + + [2,3,4] + ([2, 3, 4], ) + + [[2, 1],3,4] + ([[2, 1], 3, 4], ) + + [(2, 1),3,4] + ([[2, 1], 3, 4], ) + + (2,3,4) + ([2, 3, 4], ) + + ([2, 3], 4) + ([[2, 3], 4], ) + + (Used internally by :class:`Group` when `aslist=True`.) + """ + + def __new__(cls, contained=None): + if contained is None: + contained = [] + + if not isinstance(contained, list): + raise TypeError( + f"{cls.__name__} may only be constructed with a list, not {type(contained).__name__}" + ) + + return list.__new__(cls) + + def __new__(cls, toklist=None, name=None, **kwargs): + if isinstance(toklist, ParseResults): + return toklist + self = object.__new__(cls) + self._name = None + self._parent = None + self._all_names = set() + + if toklist is None: + self._toklist = [] + elif isinstance(toklist, (list, _generator_type)): + self._toklist = ( + [toklist[:]] + if isinstance(toklist, ParseResults.List) + else list(toklist) + ) + else: + self._toklist = [toklist] + self._tokdict = dict() + return self + + # Performance tuning: we construct a *lot* of these, so keep this + # constructor as small and fast as possible + def __init__( + self, + toklist=None, + name=None, + aslist=True, + modal=True, + isinstance=isinstance, + **kwargs, + ) -> None: + asList = deprecate_argument(kwargs, "asList", True, new_name="aslist") + + asList = asList and aslist + self._tokdict: dict[str, _ParseResultsWithOffset] + self._modal = modal + + if name is None or name == "": + return + + if isinstance(name, int): + name = str(name) + + if not modal: + self._all_names = {name} + + self._name = name + + if toklist in self._null_values: + return + + if isinstance(toklist, (str_type, type)): + toklist = [toklist] + + if asList: + if isinstance(toklist, ParseResults): + self[name] = _ParseResultsWithOffset(ParseResults(toklist._toklist), 0) + else: + self[name] = _ParseResultsWithOffset(ParseResults(toklist[0]), 0) + self[name]._name = name + return + + try: + self[name] = toklist[0] + except (KeyError, TypeError, IndexError): + if toklist is not self: + self[name] = toklist + else: + self._name = name + + def __getitem__(self, i): + if isinstance(i, (int, slice)): + return self._toklist[i] + + if i not in self._all_names: + return self._tokdict[i][-1][0] + + return ParseResults([v[0] for v in self._tokdict[i]]) + + def __setitem__(self, k, v, isinstance=isinstance): + if isinstance(v, _ParseResultsWithOffset): + self._tokdict[k] = self._tokdict.get(k, list()) + [v] + sub = v[0] + elif isinstance(k, (int, slice)): + self._toklist[k] = v + sub = v + else: + self._tokdict[k] = self._tokdict.get(k, []) + [ + _ParseResultsWithOffset(v, 0) + ] + sub = v + if isinstance(sub, ParseResults): + sub._parent = self + + def __delitem__(self, i): + if not isinstance(i, (int, slice)): + del self._tokdict[i] + return + + # slight optimization if del results[:] + if i == NULL_SLICE: + self._toklist.clear() + return + + mylen = len(self._toklist) + del self._toklist[i] + + # convert int to slice + if isinstance(i, int): + if i < 0: + i += mylen + i = slice(i, i + 1) + # get removed indices + removed = list(range(*i.indices(mylen))) + removed.reverse() + # fixup indices in token dictionary + for occurrences in self._tokdict.values(): + for j in removed: + for k, (value, position) in enumerate(occurrences): + occurrences[k] = _ParseResultsWithOffset( + value, position - (position > j) + ) + + def __contains__(self, k) -> bool: + return k in self._tokdict + + def __len__(self) -> int: + return len(self._toklist) + + def __bool__(self) -> bool: + return not not (self._toklist or self._tokdict) + + def __iter__(self) -> Iterator: + return iter(self._toklist) + + def __reversed__(self) -> Iterator: + return iter(self._toklist[::-1]) + + def keys(self): + return iter(self._tokdict) + + def values(self): + return (self[k] for k in self.keys()) + + def items(self): + return ((k, self[k]) for k in self.keys()) + + def haskeys(self) -> bool: + """ + Since ``keys()`` returns an iterator, this method is helpful in bypassing + code that looks for the existence of any defined results names.""" + return not not self._tokdict + + def pop(self, *args, **kwargs): + """ + Removes and returns item at specified index (default= ``last``). + Supports both ``list`` and ``dict`` semantics for ``pop()``. If + passed no argument or an integer argument, it will use ``list`` + semantics and pop tokens from the list of parsed tokens. If passed + a non-integer argument (most likely a string), it will use ``dict`` + semantics and pop the corresponding value from any defined results + names. A second default return value argument is supported, just as in + ``dict.pop()``. + + Example: + + .. doctest:: + + >>> numlist = Word(nums)[...] + >>> print(numlist.parse_string("0 123 321")) + ['0', '123', '321'] + + >>> def remove_first(tokens): + ... tokens.pop(0) + ... + >>> numlist.add_parse_action(remove_first) + [W:(0-9)]... + >>> print(numlist.parse_string("0 123 321")) + ['123', '321'] + + >>> label = Word(alphas) + >>> patt = label("LABEL") + Word(nums)[1, ...] + >>> print(patt.parse_string("AAB 123 321").dump()) + ['AAB', '123', '321'] + - LABEL: 'AAB' + + >>> # Use pop() in a parse action to remove named result + >>> # (note that corresponding value is not + >>> # removed from list form of results) + >>> def remove_LABEL(tokens): + ... tokens.pop("LABEL") + ... return tokens + ... + >>> patt.add_parse_action(remove_LABEL) + {W:(A-Za-z) {W:(0-9)}...} + >>> print(patt.parse_string("AAB 123 321").dump()) + ['AAB', '123', '321'] + + """ + if not args: + args = [-1] + for k, v in kwargs.items(): + if k == "default": + args = (args[0], v) + else: + raise TypeError(f"pop() got an unexpected keyword argument {k!r}") + if isinstance(args[0], int) or len(args) == 1 or args[0] in self: + index = args[0] + ret = self[index] + del self[index] + return ret + else: + defaultvalue = args[1] + return defaultvalue + + def get(self, key, default_value=None): + """ + Returns named result matching the given key, or if there is no + such name, then returns the given ``default_value`` or ``None`` if no + ``default_value`` is specified. + + Similar to ``dict.get()``. + + Example: + + .. doctest:: + + >>> integer = Word(nums) + >>> date_str = integer("year") + '/' + integer("month") + '/' + integer("day") + + >>> result = date_str.parse_string("1999/12/31") + >>> result.get("year") + '1999' + >>> result.get("hour", "not specified") + 'not specified' + >>> result.get("hour") + + """ + if key in self: + return self[key] + else: + return default_value + + def insert(self, index, ins_string): + """ + Inserts new element at location index in the list of parsed tokens. + + Similar to ``list.insert()``. + + Example: + + .. doctest:: + + >>> numlist = Word(nums)[...] + >>> print(numlist.parse_string("0 123 321")) + ['0', '123', '321'] + + >>> # use a parse action to insert the parse location + >>> # in the front of the parsed results + >>> def insert_locn(locn, tokens): + ... tokens.insert(0, locn) + ... + >>> numlist.add_parse_action(insert_locn) + [W:(0-9)]... + >>> print(numlist.parse_string("0 123 321")) + [0, '0', '123', '321'] + + """ + self._toklist.insert(index, ins_string) + # fixup indices in token dictionary + for occurrences in self._tokdict.values(): + for k, (value, position) in enumerate(occurrences): + occurrences[k] = _ParseResultsWithOffset( + value, position + (position > index) + ) + + def append(self, item): + """ + Add single element to end of ``ParseResults`` list of elements. + + Example: + + .. doctest:: + + >>> numlist = Word(nums)[...] + >>> print(numlist.parse_string("0 123 321")) + ['0', '123', '321'] + + >>> # use a parse action to compute the sum of the parsed integers, + >>> # and add it to the end + >>> def append_sum(tokens): + ... tokens.append(sum(map(int, tokens))) + ... + >>> numlist.add_parse_action(append_sum) + [W:(0-9)]... + >>> print(numlist.parse_string("0 123 321")) + ['0', '123', '321', 444] + """ + self._toklist.append(item) + + def extend(self, itemseq): + """ + Add sequence of elements to end of :class:`ParseResults` list of elements. + + Example: + + .. testcode:: + + patt = Word(alphas)[1, ...] + + # use a parse action to append the reverse of the matched strings, + # to make a palindrome + def make_palindrome(tokens): + tokens.extend(reversed([t[::-1] for t in tokens])) + return ''.join(tokens) + + patt.add_parse_action(make_palindrome) + print(patt.parse_string("lskdj sdlkjf lksd")) + + prints: + + .. testoutput:: + + ['lskdjsdlkjflksddsklfjkldsjdksl'] + """ + if isinstance(itemseq, ParseResults): + self.__iadd__(itemseq) + else: + self._toklist.extend(itemseq) + + def clear(self): + """ + Clear all elements and results names. + """ + del self._toklist[:] + self._tokdict.clear() + + def __getattr__(self, name): + try: + return self[name] + except KeyError: + if name.startswith("__"): + raise AttributeError(name) + return "" + + def __add__(self, other: ParseResults) -> ParseResults: + ret = self.copy() + ret += other + return ret + + def __iadd__(self, other: ParseResults) -> ParseResults: + if not other: + return self + + if other._tokdict: + offset = len(self._toklist) + addoffset = lambda a: offset if a < 0 else a + offset + otheritems = other._tokdict.items() + otherdictitems = [ + (k, _ParseResultsWithOffset(v[0], addoffset(v[1]))) + for k, vlist in otheritems + for v in vlist + ] + for k, v in otherdictitems: + self[k] = v + if isinstance(v[0], ParseResults): + v[0]._parent = self + + self._toklist += other._toklist + self._all_names |= other._all_names + return self + + def __radd__(self, other) -> ParseResults: + if isinstance(other, int) and other == 0: + # useful for merging many ParseResults using sum() builtin + return self.copy() + else: + # this may raise a TypeError - so be it + return other + self + + def __repr__(self) -> str: + return f"{type(self).__name__}({self._toklist!r}, {self.as_dict()})" + + def __str__(self) -> str: + return ( + "[" + + ", ".join( + [ + str(i) if isinstance(i, ParseResults) else repr(i) + for i in self._toklist + ] + ) + + "]" + ) + + def _asStringList(self, sep=""): + out = [] + for item in self._toklist: + if out and sep: + out.append(sep) + if isinstance(item, ParseResults): + out += item._asStringList() + else: + out.append(str(item)) + return out + + def as_list(self, *, flatten: bool = False) -> list: + """ + Returns the parse results as a nested list of matching tokens, all converted to strings. + If ``flatten`` is True, all the nesting levels in the returned list are collapsed. + + Example: + + .. doctest:: + + >>> patt = Word(alphas)[1, ...] + >>> result = patt.parse_string("sldkj lsdkj sldkj") + >>> # even though the result prints in string-like form, + >>> # it is actually a pyparsing ParseResults + >>> type(result) + + >>> print(result) + ['sldkj', 'lsdkj', 'sldkj'] + + .. doctest:: + + >>> # Use as_list() to create an actual list + >>> result_list = result.as_list() + >>> type(result_list) + + >>> print(result_list) + ['sldkj', 'lsdkj', 'sldkj'] + + .. versionchanged:: 3.2.0 + New ``flatten`` argument. + """ + + if flatten: + return [*_flatten(self)] + else: + return [ + res.as_list() if isinstance(res, ParseResults) else res + for res in self._toklist + ] + + def as_dict(self) -> dict: + """ + Returns the named parse results as a nested dictionary. + + Example: + + .. doctest:: + + >>> integer = pp.Word(pp.nums) + >>> date_str = integer("year") + '/' + integer("month") + '/' + integer("day") + + >>> result = date_str.parse_string('1999/12/31') + >>> type(result) + + >>> result + ParseResults(['1999', '/', '12', '/', '31'], {'year': '1999', 'month': '12', 'day': '31'}) + + >>> result_dict = result.as_dict() + >>> type(result_dict) + + >>> result_dict + {'year': '1999', 'month': '12', 'day': '31'} + + >>> # even though a ParseResults supports dict-like access, + >>> # sometime you just need to have a dict + >>> import json + >>> print(json.dumps(result)) + Traceback (most recent call last): + TypeError: Object of type ParseResults is not JSON serializable + >>> print(json.dumps(result.as_dict())) + {"year": "1999", "month": "12", "day": "31"} + """ + + def to_item(obj): + if isinstance(obj, ParseResults): + return obj.as_dict() if obj.haskeys() else [to_item(v) for v in obj] + else: + return obj + + return dict((k, to_item(v)) for k, v in self.items()) + + def copy(self) -> ParseResults: + """ + Returns a new shallow copy of a :class:`ParseResults` object. + :class:`ParseResults` items contained within the source are + shared with the copy. Use :meth:`ParseResults.deepcopy` to + create a copy with its own separate content values. + """ + ret = ParseResults(self._toklist) + ret._tokdict = self._tokdict.copy() + ret._parent = self._parent + ret._all_names |= self._all_names + ret._name = self._name + return ret + + def deepcopy(self) -> ParseResults: + """ + Returns a new deep copy of a :class:`ParseResults` object. + + .. versionadded:: 3.1.0 + """ + ret = self.copy() + # replace values with copies if they are of known mutable types + for i, obj in enumerate(self._toklist): + if isinstance(obj, ParseResults): + ret._toklist[i] = obj.deepcopy() + elif isinstance(obj, (str, bytes)): + pass + elif isinstance(obj, MutableMapping): + ret._toklist[i] = dest = type(obj)() + for k, v in obj.items(): + dest[k] = v.deepcopy() if isinstance(v, ParseResults) else v + elif isinstance(obj, Iterable): + ret._toklist[i] = type(obj)( + v.deepcopy() if isinstance(v, ParseResults) else v for v in obj # type: ignore[call-arg] + ) + return ret + + def get_name(self) -> str | None: + r""" + Returns the results name for this token expression. + + Useful when several different expressions might match + at a particular location. + + Example: + + .. testcode:: + + integer = Word(nums) + ssn_expr = Regex(r"\d\d\d-\d\d-\d\d\d\d") + house_number_expr = Suppress('#') + Word(nums, alphanums) + user_data = (Group(house_number_expr)("house_number") + | Group(ssn_expr)("ssn") + | Group(integer)("age")) + user_info = user_data[1, ...] + + result = user_info.parse_string("22 111-22-3333 #221B") + for item in result: + print(item.get_name(), ':', item[0]) + + prints: + + .. testoutput:: + + age : 22 + ssn : 111-22-3333 + house_number : 221B + + """ + if self._name: + return self._name + elif self._parent: + par: ParseResults = self._parent + parent_tokdict_items = par._tokdict.items() + return next( + ( + k + for k, vlist in parent_tokdict_items + for v, loc in vlist + if v is self + ), + None, + ) + elif ( + len(self) == 1 + and len(self._tokdict) == 1 + and next(iter(self._tokdict.values()))[0][1] in (0, -1) + ): + return next(iter(self._tokdict.keys())) + else: + return None + + def dump(self, indent="", full=True, include_list=True, _depth=0) -> str: + """ + Diagnostic method for listing out the contents of + a :class:`ParseResults`. Accepts an optional ``indent`` argument so + that this string can be embedded in a nested display of other data. + + Example: + + .. testcode:: + + integer = Word(nums) + date_str = integer("year") + '/' + integer("month") + '/' + integer("day") + + result = date_str.parse_string('1999/12/31') + print(result.dump()) + + prints: + + .. testoutput:: + + ['1999', '/', '12', '/', '31'] + - day: '31' + - month: '12' + - year: '1999' + """ + out = [] + NL = "\n" + out.append(indent + str(self.as_list()) if include_list else "") + + if not full: + return "".join(out) + + if self.haskeys(): + items = sorted((str(k), v) for k, v in self.items()) + for k, v in items: + if out: + out.append(NL) + out.append(f"{indent}{(' ' * _depth)}- {k}: ") + if not isinstance(v, ParseResults): + out.append(repr(v)) + continue + + if not v: + out.append(str(v)) + continue + + out.append( + v.dump( + indent=indent, + full=full, + include_list=include_list, + _depth=_depth + 1, + ) + ) + if not any(isinstance(vv, ParseResults) for vv in self): + return "".join(out) + + v = self + incr = " " + nl = "\n" + for i, vv in enumerate(v): + if isinstance(vv, ParseResults): + vv_dump = vv.dump( + indent=indent, + full=full, + include_list=include_list, + _depth=_depth + 1, + ) + out.append( + f"{nl}{indent}{incr * _depth}[{i}]:{nl}{indent}{incr * (_depth + 1)}{vv_dump}" + ) + else: + out.append( + f"{nl}{indent}{incr * _depth}[{i}]:{nl}{indent}{incr * (_depth + 1)}{vv}" + ) + + return "".join(out) + + def pprint(self, *args, **kwargs): + """ + Pretty-printer for parsed results as a list, using the + `pprint `_ module. + Accepts additional positional or keyword args as defined for + `pprint.pprint `_ . + + Example: + + .. testcode:: + + ident = Word(alphas, alphanums) + num = Word(nums) + func = Forward() + term = ident | num | Group('(' + func + ')') + func <<= ident + Group(Optional(DelimitedList(term))) + result = func.parse_string("fna a,b,(fnb c,d,200),100") + result.pprint(width=40) + + prints: + + .. testoutput:: + + ['fna', + ['a', + 'b', + ['(', 'fnb', ['c', 'd', '200'], ')'], + '100']] + """ + pprint.pprint(self.as_list(), *args, **kwargs) + + # add support for pickle protocol + def __getstate__(self): + return ( + self._toklist, + ( + self._tokdict.copy(), + None, + self._all_names, + self._name, + ), + ) + + def __setstate__(self, state): + self._toklist, (self._tokdict, par, inAccumNames, self._name) = state + self._all_names = set(inAccumNames) + self._parent = None + + def __getnewargs__(self): + return self._toklist, self._name + + def __dir__(self): + return dir(type(self)) + list(self.keys()) + + @classmethod + def from_dict(cls, other, name=None) -> ParseResults: + """ + Helper classmethod to construct a :class:`ParseResults` from a ``dict``, preserving the + name-value relations as results names. If an optional ``name`` argument is + given, a nested :class:`ParseResults` will be returned. + """ + ret = cls([]) + for k, v in other.items(): + if isinstance(v, Mapping): + ret += cls.from_dict(v, name=k) + else: + ret += cls([v], name=k, aslist=_is_iterable(v)) + if name is not None: + ret = cls([ret], name=name) + return ret + + asList = as_list + """ + .. deprecated:: 3.0.0 + use :meth:`as_list` + """ + asDict = as_dict + """ + .. deprecated:: 3.0.0 + use :meth:`as_dict` + """ + getName = get_name + """ + .. deprecated:: 3.0.0 + use :meth:`get_name` + """ + + +MutableMapping.register(ParseResults) +MutableSequence.register(ParseResults) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pyparsing/testing.py b/TTS/Kokoro/.venv/Lib/site-packages/pyparsing/testing.py new file mode 100644 index 0000000000000000000000000000000000000000..d7b60b852bfae552aead2f254ba5b8d0e67f5216 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/pyparsing/testing.py @@ -0,0 +1,398 @@ +# testing.py + +from contextlib import contextmanager +import re +import typing +import unittest + + +from .core import ( + ParserElement, + ParseException, + Keyword, + __diag__, + __compat__, +) +from . import core_builtin_exprs + + +class pyparsing_test: + """ + namespace class for classes useful in writing unit tests + """ + + class reset_pyparsing_context: + """ + Context manager to be used when writing unit tests that modify pyparsing config values: + - packrat parsing + - bounded recursion parsing + - default whitespace characters + - default keyword characters + - literal string auto-conversion class + - ``__diag__`` settings + + Example: + + .. testcode:: + + ppt = pyparsing.pyparsing_test + + class MyTestClass(ppt.TestParseResultsAsserts): + def test_literal(self): + with ppt.reset_pyparsing_context(): + # test that literals used to construct + # a grammar are automatically suppressed + ParserElement.inline_literals_using(Suppress) + + term = Word(alphas) | Word(nums) + group = Group('(' + term[...] + ')') + + # assert that the '()' characters + # are not included in the parsed tokens + self.assertParseAndCheckList( + group, + "(abc 123 def)", + ['abc', '123', 'def'] + ) + + # after exiting context manager, literals + # are converted to Literal expressions again + """ + + def __init__(self): + self._save_context = {} + + def save(self): + self._save_context["default_whitespace"] = ParserElement.DEFAULT_WHITE_CHARS + self._save_context["default_keyword_chars"] = Keyword.DEFAULT_KEYWORD_CHARS + + self._save_context["literal_string_class"] = ( + ParserElement._literalStringClass + ) + + self._save_context["verbose_stacktrace"] = ParserElement.verbose_stacktrace + + self._save_context["packrat_enabled"] = ParserElement._packratEnabled + if ParserElement._packratEnabled: + self._save_context["packrat_cache_size"] = ( + ParserElement.packrat_cache.size + ) + else: + self._save_context["packrat_cache_size"] = None + self._save_context["packrat_parse"] = ParserElement._parse + self._save_context["recursion_enabled"] = ( + ParserElement._left_recursion_enabled + ) + + self._save_context["__diag__"] = { + name: getattr(__diag__, name) for name in __diag__._all_names + } + + self._save_context["__compat__"] = { + "collect_all_And_tokens": __compat__.collect_all_And_tokens + } + + return self + + def restore(self): + # reset pyparsing global state + if ( + ParserElement.DEFAULT_WHITE_CHARS + != self._save_context["default_whitespace"] + ): + ParserElement.set_default_whitespace_chars( + self._save_context["default_whitespace"] + ) + + ParserElement.verbose_stacktrace = self._save_context["verbose_stacktrace"] + + Keyword.DEFAULT_KEYWORD_CHARS = self._save_context["default_keyword_chars"] + ParserElement.inline_literals_using( + self._save_context["literal_string_class"] + ) + + for name, value in self._save_context["__diag__"].items(): + (__diag__.enable if value else __diag__.disable)(name) + + ParserElement._packratEnabled = False + if self._save_context["packrat_enabled"]: + ParserElement.enable_packrat(self._save_context["packrat_cache_size"]) + else: + ParserElement._parse = self._save_context["packrat_parse"] + ParserElement._left_recursion_enabled = self._save_context[ + "recursion_enabled" + ] + + # clear debug flags on all builtins + for expr in core_builtin_exprs: + expr.set_debug(False) + + __compat__.collect_all_And_tokens = self._save_context["__compat__"] + + return self + + def copy(self): + ret = type(self)() + ret._save_context.update(self._save_context) + return ret + + def __enter__(self): + return self.save() + + def __exit__(self, *args): + self.restore() + + class TestParseResultsAsserts(unittest.TestCase): + """ + A mixin class to add parse results assertion methods to normal unittest.TestCase classes. + """ + + def assertParseResultsEquals( + self, result, expected_list=None, expected_dict=None, msg=None + ): + """ + Unit test assertion to compare a :class:`ParseResults` object with an optional ``expected_list``, + and compare any defined results names with an optional ``expected_dict``. + """ + if expected_list is not None: + self.assertEqual(expected_list, result.as_list(), msg=msg) + if expected_dict is not None: + self.assertEqual(expected_dict, result.as_dict(), msg=msg) + + def assertParseAndCheckList( + self, expr, test_string, expected_list, msg=None, verbose=True + ): + """ + Convenience wrapper assert to test a parser element and input string, and assert that + the resulting :meth:`ParseResults.as_list` is equal to the ``expected_list``. + """ + result = expr.parse_string(test_string, parse_all=True) + if verbose: + print(result.dump()) + else: + print(result.as_list()) + self.assertParseResultsEquals(result, expected_list=expected_list, msg=msg) + + def assertParseAndCheckDict( + self, expr, test_string, expected_dict, msg=None, verbose=True + ): + """ + Convenience wrapper assert to test a parser element and input string, and assert that + the resulting :meth:`ParseResults.as_dict` is equal to the ``expected_dict``. + """ + result = expr.parse_string(test_string, parse_all=True) + if verbose: + print(result.dump()) + else: + print(result.as_list()) + self.assertParseResultsEquals(result, expected_dict=expected_dict, msg=msg) + + def assertRunTestResults( + self, run_tests_report, expected_parse_results=None, msg=None + ): + """ + Unit test assertion to evaluate output of + :meth:`~ParserElement.run_tests`. + + If a list of list-dict tuples is given as the + ``expected_parse_results`` argument, then these are zipped + with the report tuples returned by ``run_tests()`` + and evaluated using :meth:`assertParseResultsEquals`. + Finally, asserts that the overall + `:meth:~ParserElement.run_tests` success value is ``True``. + + :param run_tests_report: the return value from :meth:`ParserElement.run_tests` + :type run_tests_report: tuple[bool, list[tuple[str, ParseResults | Exception]]] + :param expected_parse_results: (optional) + :type expected_parse_results: list[tuple[str | list | dict | Exception, ...]] + """ + run_test_success, run_test_results = run_tests_report + + if expected_parse_results is None: + self.assertTrue( + run_test_success, msg=msg if msg is not None else "failed runTests" + ) + return + + merged = [ + (*rpt, expected) + for rpt, expected in zip(run_test_results, expected_parse_results) + ] + for test_string, result, expected in merged: + # expected should be a tuple containing a list and/or a dict or an exception, + # and optional failure message string + # an empty tuple will skip any result validation + fail_msg = next((exp for exp in expected if isinstance(exp, str)), None) + expected_exception = next( + ( + exp + for exp in expected + if isinstance(exp, type) and issubclass(exp, Exception) + ), + None, + ) + if expected_exception is not None: + with self.assertRaises( + expected_exception=expected_exception, msg=fail_msg or msg + ): + if isinstance(result, Exception): + raise result + else: + expected_list = next( + (exp for exp in expected if isinstance(exp, list)), None + ) + expected_dict = next( + (exp for exp in expected if isinstance(exp, dict)), None + ) + if (expected_list, expected_dict) != (None, None): + self.assertParseResultsEquals( + result, + expected_list=expected_list, + expected_dict=expected_dict, + msg=fail_msg or msg, + ) + else: + # warning here maybe? + print(f"no validation for {test_string!r}") + + # do this last, in case some specific test results can be reported instead + self.assertTrue( + run_test_success, msg=msg if msg is not None else "failed runTests" + ) + + @contextmanager + def assertRaisesParseException( + self, exc_type=ParseException, expected_msg=None, msg=None + ): + if expected_msg is not None: + if isinstance(expected_msg, str): + expected_msg = re.escape(expected_msg) + with self.assertRaisesRegex(exc_type, expected_msg, msg=msg) as ctx: + yield ctx + + else: + with self.assertRaises(exc_type, msg=msg) as ctx: + yield ctx + + @staticmethod + def with_line_numbers( + s: str, + start_line: typing.Optional[int] = None, + end_line: typing.Optional[int] = None, + expand_tabs: bool = True, + eol_mark: str = "|", + mark_spaces: typing.Optional[str] = None, + mark_control: typing.Optional[str] = None, + *, + indent: typing.Union[str, int] = "", + base_1: bool = True, + ) -> str: + """ + Helpful method for debugging a parser - prints a string with line and column numbers. + (Line and column numbers are 1-based by default - if debugging a parse action, + pass base_1=False, to correspond to the loc value passed to the parse action.) + + :param s: string to be printed with line and column numbers + :param start_line: starting line number in s to print (default=1) + :param end_line: ending line number in s to print (default=len(s)) + :param expand_tabs: expand tabs to spaces, to match the pyparsing default + :param eol_mark: string to mark the end of lines, helps visualize trailing spaces + :param mark_spaces: special character to display in place of spaces + :param mark_control: convert non-printing control characters to a placeholding + character; valid values: + + - ``"unicode"`` - replaces control chars with Unicode symbols, such as "␍" and "␊" + - any single character string - replace control characters with given string + - ``None`` (default) - string is displayed as-is + + + :param indent: string to indent with line and column numbers; if an int + is passed, converted to ``" " * indent`` + :param base_1: whether to label string using base 1; if False, string will be + labeled based at 0 + + :returns: input string with leading line numbers and column number headers + + .. versionchanged:: 3.2.0 + New ``indent`` and ``base_1`` arguments. + """ + if expand_tabs: + s = s.expandtabs() + if isinstance(indent, int): + indent = " " * indent + indent = indent.expandtabs() + if mark_control is not None: + mark_control = typing.cast(str, mark_control) + if mark_control == "unicode": + transtable_map = { + c: u for c, u in zip(range(0, 33), range(0x2400, 0x2433)) + } + transtable_map[127] = 0x2421 + tbl = str.maketrans(transtable_map) + eol_mark = "" + else: + ord_mark_control = ord(mark_control) + tbl = str.maketrans( + {c: ord_mark_control for c in list(range(0, 32)) + [127]} + ) + s = s.translate(tbl) + if mark_spaces is not None and mark_spaces != " ": + if mark_spaces == "unicode": + tbl = str.maketrans({9: 0x2409, 32: 0x2423}) + s = s.translate(tbl) + else: + s = s.replace(" ", mark_spaces) + if start_line is None: + start_line = 0 + if end_line is None: + end_line = len(s.splitlines()) + end_line = min(end_line, len(s.splitlines())) + start_line = min(max(0, start_line), end_line) + + if mark_control != "unicode": + s_lines = s.splitlines()[max(start_line - base_1, 0) : end_line] + else: + s_lines = [ + line + "␊" + for line in s.split("␊")[max(start_line - base_1, 0) : end_line] + ] + if not s_lines: + return "" + + lineno_width = len(str(end_line)) + max_line_len = max(len(line) for line in s_lines) + lead = f"{indent}{' ' * (lineno_width + 1)}" + + if max_line_len >= 99: + header0 = ( + lead + + ("" if base_1 else " ") + + "".join( + f"{' ' * 99}{(i + 1) % 100}" + for i in range(max(max_line_len // 100, 1)) + ) + + "\n" + ) + else: + header0 = "" + + header1 = ( + ("" if base_1 else " ") + + lead + + "".join(f" {(i + 1) % 10}" for i in range(-(-max_line_len // 10))) + + "\n" + ) + digits = "1234567890" + header2 = ( + lead + ("" if base_1 else "0") + digits * (-(-max_line_len // 10)) + "\n" + ) + return ( + header0 + + header1 + + header2 + + "\n".join( + f"{indent}{i:{lineno_width}d}:{line}{eol_mark}" + for i, line in enumerate(s_lines, start=start_line + base_1) + ) + + "\n" + ) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pyparsing/unicode.py b/TTS/Kokoro/.venv/Lib/site-packages/pyparsing/unicode.py new file mode 100644 index 0000000000000000000000000000000000000000..32bb94e4397a2dd4b66e2a725c1e119e3518de71 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/pyparsing/unicode.py @@ -0,0 +1,356 @@ +# unicode.py + +import sys +from itertools import filterfalse +from typing import Union + + +class _lazyclassproperty: + def __init__(self, fn): + self.fn = fn + self.__doc__ = fn.__doc__ + self.__name__ = fn.__name__ + + def __get__(self, obj, cls): + if cls is None: + cls = type(obj) + if not hasattr(cls, "_intern") or any( + cls._intern is getattr(superclass, "_intern", []) + for superclass in cls.__mro__[1:] + ): + cls._intern = {} + attrname = self.fn.__name__ + if attrname not in cls._intern: + cls._intern[attrname] = self.fn(cls) + return cls._intern[attrname] + + +UnicodeRangeList = list[Union[tuple[int, int], tuple[int]]] + + +class unicode_set: + """ + A set of Unicode characters, for language-specific strings for + ``alphas``, ``nums``, ``alphanums``, and ``printables``. + A unicode_set is defined by a list of ranges in the Unicode character + set, in a class attribute ``_ranges``. Ranges can be specified using + 2-tuples or a 1-tuple, such as:: + + _ranges = [ + (0x0020, 0x007e), + (0x00a0, 0x00ff), + (0x0100,), + ] + + Ranges are left- and right-inclusive. A 1-tuple of (x,) is treated as (x, x). + + A unicode set can also be defined using multiple inheritance of other unicode sets:: + + class CJK(Chinese, Japanese, Korean): + pass + """ + + _ranges: UnicodeRangeList = [] + + @_lazyclassproperty + def _chars_for_ranges(cls) -> list[str]: + ret: list[int] = [] + for cc in cls.__mro__: # type: ignore[attr-defined] + if cc is unicode_set: + break + for rr in getattr(cc, "_ranges", ()): + ret.extend(range(rr[0], rr[-1] + 1)) + return sorted(chr(c) for c in set(ret)) + + @_lazyclassproperty + def printables(cls) -> str: + """all non-whitespace characters in this range""" + return "".join(filterfalse(str.isspace, cls._chars_for_ranges)) + + @_lazyclassproperty + def alphas(cls) -> str: + """all alphabetic characters in this range""" + return "".join(filter(str.isalpha, cls._chars_for_ranges)) + + @_lazyclassproperty + def nums(cls) -> str: + """all numeric digit characters in this range""" + return "".join(filter(str.isdigit, cls._chars_for_ranges)) + + @_lazyclassproperty + def alphanums(cls) -> str: + """all alphanumeric characters in this range""" + return cls.alphas + cls.nums + + @_lazyclassproperty + def identchars(cls) -> str: + """all characters in this range that are valid identifier characters, plus underscore '_'""" + return "".join( + sorted( + set(filter(str.isidentifier, cls._chars_for_ranges)) + | set( + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzªµº" + "ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ" + "_" + ) + ) + ) + + @_lazyclassproperty + def identbodychars(cls) -> str: + """ + all characters in this range that are valid identifier body characters, + plus the digits 0-9, and · (Unicode MIDDLE DOT) + """ + identifier_chars = set( + c for c in cls._chars_for_ranges if f"_{c}".isidentifier() + ) + return "".join( + sorted(identifier_chars | set(cls.identchars) | set("0123456789·")) + ) + + @_lazyclassproperty + def identifier(cls): + """ + a pyparsing Word expression for an identifier using this range's definitions for + identchars and identbodychars + """ + from pyparsing import Word + + return Word(cls.identchars, cls.identbodychars) + + +class pyparsing_unicode(unicode_set): + """ + A namespace class for defining common language unicode_sets. + """ + + # fmt: off + + # define ranges in language character sets + _ranges: UnicodeRangeList = [ + (0x0020, sys.maxunicode), + ] + + class BasicMultilingualPlane(unicode_set): + """Unicode set for the Basic Multilingual Plane""" + _ranges: UnicodeRangeList = [ + (0x0020, 0xFFFF), + ] + + class Latin1(unicode_set): + """Unicode set for Latin-1 Unicode Character Range""" + _ranges: UnicodeRangeList = [ + (0x0020, 0x007E), + (0x00A0, 0x00FF), + ] + + class LatinA(unicode_set): + """Unicode set for Latin-A Unicode Character Range""" + _ranges: UnicodeRangeList = [ + (0x0100, 0x017F), + ] + + class LatinB(unicode_set): + """Unicode set for Latin-B Unicode Character Range""" + _ranges: UnicodeRangeList = [ + (0x0180, 0x024F), + ] + + class Greek(unicode_set): + """Unicode set for Greek Unicode Character Ranges""" + _ranges: UnicodeRangeList = [ + (0x0342, 0x0345), + (0x0370, 0x0377), + (0x037A, 0x037F), + (0x0384, 0x038A), + (0x038C,), + (0x038E, 0x03A1), + (0x03A3, 0x03E1), + (0x03F0, 0x03FF), + (0x1D26, 0x1D2A), + (0x1D5E,), + (0x1D60,), + (0x1D66, 0x1D6A), + (0x1F00, 0x1F15), + (0x1F18, 0x1F1D), + (0x1F20, 0x1F45), + (0x1F48, 0x1F4D), + (0x1F50, 0x1F57), + (0x1F59,), + (0x1F5B,), + (0x1F5D,), + (0x1F5F, 0x1F7D), + (0x1F80, 0x1FB4), + (0x1FB6, 0x1FC4), + (0x1FC6, 0x1FD3), + (0x1FD6, 0x1FDB), + (0x1FDD, 0x1FEF), + (0x1FF2, 0x1FF4), + (0x1FF6, 0x1FFE), + (0x2129,), + (0x2719, 0x271A), + (0xAB65,), + (0x10140, 0x1018D), + (0x101A0,), + (0x1D200, 0x1D245), + (0x1F7A1, 0x1F7A7), + ] + + class Cyrillic(unicode_set): + """Unicode set for Cyrillic Unicode Character Range""" + _ranges: UnicodeRangeList = [ + (0x0400, 0x052F), + (0x1C80, 0x1C88), + (0x1D2B,), + (0x1D78,), + (0x2DE0, 0x2DFF), + (0xA640, 0xA672), + (0xA674, 0xA69F), + (0xFE2E, 0xFE2F), + ] + + class Chinese(unicode_set): + """Unicode set for Chinese Unicode Character Range""" + _ranges: UnicodeRangeList = [ + (0x2E80, 0x2E99), + (0x2E9B, 0x2EF3), + (0x31C0, 0x31E3), + (0x3400, 0x4DB5), + (0x4E00, 0x9FEF), + (0xA700, 0xA707), + (0xF900, 0xFA6D), + (0xFA70, 0xFAD9), + (0x16FE2, 0x16FE3), + (0x1F210, 0x1F212), + (0x1F214, 0x1F23B), + (0x1F240, 0x1F248), + (0x20000, 0x2A6D6), + (0x2A700, 0x2B734), + (0x2B740, 0x2B81D), + (0x2B820, 0x2CEA1), + (0x2CEB0, 0x2EBE0), + (0x2F800, 0x2FA1D), + ] + + class Japanese(unicode_set): + """Unicode set for Japanese Unicode Character Range, combining Kanji, Hiragana, and Katakana ranges""" + + class Kanji(unicode_set): + "Unicode set for Kanji Unicode Character Range" + _ranges: UnicodeRangeList = [ + (0x4E00, 0x9FBF), + (0x3000, 0x303F), + ] + + class Hiragana(unicode_set): + """Unicode set for Hiragana Unicode Character Range""" + _ranges: UnicodeRangeList = [ + (0x3041, 0x3096), + (0x3099, 0x30A0), + (0x30FC,), + (0xFF70,), + (0x1B001,), + (0x1B150, 0x1B152), + (0x1F200,), + ] + + class Katakana(unicode_set): + """Unicode set for Katakana Unicode Character Range""" + _ranges: UnicodeRangeList = [ + (0x3099, 0x309C), + (0x30A0, 0x30FF), + (0x31F0, 0x31FF), + (0x32D0, 0x32FE), + (0xFF65, 0xFF9F), + (0x1B000,), + (0x1B164, 0x1B167), + (0x1F201, 0x1F202), + (0x1F213,), + ] + + 漢字 = Kanji + カタカナ = Katakana + ひらがな = Hiragana + + _ranges = ( + Kanji._ranges + + Hiragana._ranges + + Katakana._ranges + ) + + class Hangul(unicode_set): + """Unicode set for Hangul (Korean) Unicode Character Range""" + _ranges: UnicodeRangeList = [ + (0x1100, 0x11FF), + (0x302E, 0x302F), + (0x3131, 0x318E), + (0x3200, 0x321C), + (0x3260, 0x327B), + (0x327E,), + (0xA960, 0xA97C), + (0xAC00, 0xD7A3), + (0xD7B0, 0xD7C6), + (0xD7CB, 0xD7FB), + (0xFFA0, 0xFFBE), + (0xFFC2, 0xFFC7), + (0xFFCA, 0xFFCF), + (0xFFD2, 0xFFD7), + (0xFFDA, 0xFFDC), + ] + + Korean = Hangul + + class CJK(Chinese, Japanese, Hangul): + """Unicode set for combined Chinese, Japanese, and Korean (CJK) Unicode Character Range""" + + class Thai(unicode_set): + """Unicode set for Thai Unicode Character Range""" + _ranges: UnicodeRangeList = [ + (0x0E01, 0x0E3A), + (0x0E3F, 0x0E5B) + ] + + class Arabic(unicode_set): + """Unicode set for Arabic Unicode Character Range""" + _ranges: UnicodeRangeList = [ + (0x0600, 0x061B), + (0x061E, 0x06FF), + (0x0700, 0x077F), + ] + + class Hebrew(unicode_set): + """Unicode set for Hebrew Unicode Character Range""" + _ranges: UnicodeRangeList = [ + (0x0591, 0x05C7), + (0x05D0, 0x05EA), + (0x05EF, 0x05F4), + (0xFB1D, 0xFB36), + (0xFB38, 0xFB3C), + (0xFB3E,), + (0xFB40, 0xFB41), + (0xFB43, 0xFB44), + (0xFB46, 0xFB4F), + ] + + class Devanagari(unicode_set): + """Unicode set for Devanagari Unicode Character Range""" + _ranges: UnicodeRangeList = [ + (0x0900, 0x097F), + (0xA8E0, 0xA8FF) + ] + + BMP = BasicMultilingualPlane + + # add language identifiers using language Unicode + العربية = Arabic + 中文 = Chinese + кириллица = Cyrillic + Ελληνικά = Greek + עִברִית = Hebrew + 日本語 = Japanese + 한국어 = Korean + ไทย = Thai + देवनागरी = Devanagari + + # fmt: on diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pyparsing/util.py b/TTS/Kokoro/.venv/Lib/site-packages/pyparsing/util.py new file mode 100644 index 0000000000000000000000000000000000000000..62295915fa37da1831ce6839d5ec2d7f9add4779 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/pyparsing/util.py @@ -0,0 +1,514 @@ +# util.py +import contextlib +import re +from functools import lru_cache, wraps +import inspect +import itertools +import types +from typing import Callable, Union, Iterable, TypeVar, cast, Any +import warnings + +from .warnings import PyparsingDeprecationWarning, PyparsingDiagnosticWarning + +_bslash = chr(92) +C = TypeVar("C", bound=Callable) + + +class __config_flags: + """Internal class for defining compatibility and debugging flags""" + + _all_names: list[str] = [] + _fixed_names: list[str] = [] + _type_desc = "configuration" + + @classmethod + def _set(cls, dname, value): + if dname in cls._fixed_names: + warnings.warn( + f"{cls.__name__}.{dname} {cls._type_desc} is {str(getattr(cls, dname)).upper()}" + f" and cannot be overridden", + PyparsingDiagnosticWarning, + stacklevel=3, + ) + return + if dname in cls._all_names: + setattr(cls, dname, value) + else: + raise ValueError(f"no such {cls._type_desc} {dname!r}") + + enable = classmethod(lambda cls, name: cls._set(name, True)) + disable = classmethod(lambda cls, name: cls._set(name, False)) + + +@lru_cache(maxsize=128) +def col(loc: int, strg: str) -> int: + """ + Returns current column within a string, counting newlines as line separators. + The first column is number 1. + + Note: the default parsing behavior is to expand tabs in the input string + before starting the parsing process. See + :meth:`ParserElement.parse_string` for more + information on parsing strings containing ```` s, and suggested + methods to maintain a consistent view of the parsed string, the parse + location, and line and column positions within the parsed string. + """ + s = strg + return 1 if 0 < loc < len(s) and s[loc - 1] == "\n" else loc - s.rfind("\n", 0, loc) + + +@lru_cache(maxsize=128) +def lineno(loc: int, strg: str) -> int: + """Returns current line number within a string, counting newlines as line separators. + The first line is number 1. + + Note - the default parsing behavior is to expand tabs in the input string + before starting the parsing process. See :meth:`ParserElement.parse_string` + for more information on parsing strings containing ```` s, and + suggested methods to maintain a consistent view of the parsed string, the + parse location, and line and column positions within the parsed string. + """ + return strg.count("\n", 0, loc) + 1 + + +@lru_cache(maxsize=128) +def line(loc: int, strg: str) -> str: + """ + Returns the line of text containing loc within a string, counting newlines as line separators. + """ + last_cr = strg.rfind("\n", 0, loc) + next_cr = strg.find("\n", loc) + return strg[last_cr + 1 : next_cr] if next_cr >= 0 else strg[last_cr + 1 :] + + +class _UnboundedCache: + def __init__(self): + cache = {} + cache_get = cache.get + self.not_in_cache = not_in_cache = object() + + def get(_, key): + return cache_get(key, not_in_cache) + + def set_(_, key, value): + cache[key] = value + + def clear(_): + cache.clear() + + self.size = None + self.get = types.MethodType(get, self) + self.set = types.MethodType(set_, self) + self.clear = types.MethodType(clear, self) + + +class _FifoCache: + def __init__(self, size): + cache = {} + self.size = size + self.not_in_cache = not_in_cache = object() + cache_get = cache.get + cache_pop = cache.pop + + def get(_, key): + return cache_get(key, not_in_cache) + + def set_(_, key, value): + cache[key] = value + while len(cache) > size: + # pop oldest element in cache by getting the first key + cache_pop(next(iter(cache))) + + def clear(_): + cache.clear() + + self.get = types.MethodType(get, self) + self.set = types.MethodType(set_, self) + self.clear = types.MethodType(clear, self) + + +class LRUMemo: + """ + A memoizing mapping that retains `capacity` deleted items + + The memo tracks retained items by their access order; once `capacity` items + are retained, the least recently used item is discarded. + """ + + def __init__(self, capacity): + self._capacity = capacity + self._active = {} + self._memory = {} + + def __getitem__(self, key): + try: + return self._active[key] + except KeyError: + self._memory[key] = self._memory.pop(key) + return self._memory[key] + + def __setitem__(self, key, value): + self._memory.pop(key, None) + self._active[key] = value + + def __delitem__(self, key): + try: + value = self._active.pop(key) + except KeyError: + pass + else: + oldest_keys = list(self._memory)[: -(self._capacity + 1)] + for key_to_delete in oldest_keys: + self._memory.pop(key_to_delete) + self._memory[key] = value + + def clear(self): + self._active.clear() + self._memory.clear() + + +class UnboundedMemo(dict): + """ + A memoizing mapping that retains all deleted items + """ + + def __delitem__(self, key): + pass + + +def _escape_regex_range_chars(s: str) -> str: + # escape these chars: ^-[] + for c in r"\^-[]": + s = s.replace(c, _bslash + c) + s = s.replace("\n", r"\n") + s = s.replace("\t", r"\t") + return str(s) + + +class _GroupConsecutive: + """ + Used as a callable `key` for itertools.groupby to group + characters that are consecutive: + + .. testcode:: + + from itertools import groupby + from pyparsing.util import _GroupConsecutive + + grouped = groupby("abcdejkmpqrs", key=_GroupConsecutive()) + for index, group in grouped: + print(tuple([index, list(group)])) + + prints: + + .. testoutput:: + + (0, ['a', 'b', 'c', 'd', 'e']) + (1, ['j', 'k']) + (2, ['m']) + (3, ['p', 'q', 'r', 's']) + """ + + def __init__(self) -> None: + self.prev = 0 + self.counter = itertools.count() + self.value = -1 + + def __call__(self, char: str) -> int: + c_int = ord(char) + self.prev, prev = c_int, self.prev + if c_int - prev > 1: + self.value = next(self.counter) + return self.value + + +def _is_iterable(obj, _str_type=(str, bytes), _iter_exception=Exception): + # str's are iterable, but in pyparsing, we don't want to iterate over them + if isinstance(obj, _str_type): + return False + + try: + iter(obj) + except _iter_exception: # noqa + return False + else: + return True + + +def _escape_re_range_char(c: str) -> str: + return fr"\{c}" if c in r"\^-][" else c + + +def _collapse_string_to_ranges( + s: Union[str, Iterable[str]], re_escape: bool = True +) -> str: + r""" + Take a string or list of single-character strings, and return + a string of the consecutive characters in that string collapsed + into groups, as might be used in a regular expression '[a-z]' + character set:: + + 'a' -> 'a' -> '[a]' + 'bc' -> 'bc' -> '[bc]' + 'defgh' -> 'd-h' -> '[d-h]' + 'fdgeh' -> 'd-h' -> '[d-h]' + 'jklnpqrtu' -> 'j-lnp-rtu' -> '[j-lnp-rtu]' + + Duplicates get collapsed out:: + + 'aaa' -> 'a' -> '[a]' + 'bcbccb' -> 'bc' -> '[bc]' + 'defghhgf' -> 'd-h' -> '[d-h]' + 'jklnpqrjjjtu' -> 'j-lnp-rtu' -> '[j-lnp-rtu]' + + Spaces are preserved:: + + 'ab c' -> ' a-c' -> '[ a-c]' + + Characters that are significant when defining regex ranges + get escaped:: + + 'acde[]-' -> r'\-\[\]ac-e' -> r'[\-\[\]ac-e]' + """ + + # Developer notes: + # - Do not optimize this code assuming that the given input string + # or internal lists will be short (such as in loading generators into + # lists to make it easier to find the last element); this method is also + # used to generate regex ranges for character sets in the pyparsing.unicode + # classes, and these can be _very_ long lists of strings + + escape_re_range_char: Callable[[str], str] + if re_escape: + escape_re_range_char = _escape_re_range_char + else: + escape_re_range_char = lambda ss: ss + + ret = [] + + # reduce input string to remove duplicates, and put in sorted order + s_chars: list[str] = sorted(set(s)) + + if len(s_chars) > 2: + # find groups of characters that are consecutive (can be collapsed + # down to "-") + for _, chars in itertools.groupby(s_chars, key=_GroupConsecutive()): + # _ is unimportant, is just used to identify groups + # chars is an iterator of one or more consecutive characters + # that comprise the current group + first = last = next(chars) + with contextlib.suppress(ValueError): + *_, last = chars + + if first == last: + # there was only a single char in this group + ret.append(escape_re_range_char(first)) + + elif last == chr(ord(first) + 1): + # there were only 2 characters in this group + # 'a','b' -> 'ab' + ret.append(f"{escape_re_range_char(first)}{escape_re_range_char(last)}") + + else: + # there were > 2 characters in this group, make into a range + # 'c','d','e' -> 'c-e' + ret.append( + f"{escape_re_range_char(first)}-{escape_re_range_char(last)}" + ) + else: + # only 1 or 2 chars were given to form into groups + # 'a' -> ['a'] + # 'bc' -> ['b', 'c'] + # 'dg' -> ['d', 'g'] + # no need to list them with "-", just return as a list + # (after escaping) + ret = [escape_re_range_char(c) for c in s_chars] + + return "".join(ret) + + +def _flatten(ll: Iterable) -> list: + ret = [] + for i in ll: + # Developer notes: + # - do not collapse this section of code, isinstance checks are done + # in optimal order + if isinstance(i, str): + ret.append(i) + elif isinstance(i, Iterable): + ret.extend(_flatten(i)) + else: + ret.append(i) + return ret + + +def _convert_escaped_numerics_to_char(s: str) -> str: + if s == "0": + return "\0" + if s.isdigit() and len(s) == 3: + return chr(int(s, 8)) + elif s.startswith(("u", "x")): + return chr(int(s[1:], 16)) + return s + + +def make_compressed_re( + word_list: Iterable[str], + max_level: int = 2, + *, + non_capturing_groups: bool = True, + _level: int = 1, +) -> str: + """ + Create a regular expression string from a list of words, collapsing by common + prefixes and optional suffixes. + + Calls itself recursively to build nested sublists for each group of suffixes + that have a shared prefix. + """ + + def get_suffixes_from_common_prefixes(namelist: list[str]): + if len(namelist) > 1: + for prefix, suffixes in itertools.groupby(namelist, key=lambda s: s[:1]): + yield prefix, sorted([s[1:] for s in suffixes], key=len, reverse=True) + else: + yield namelist[0][0], [namelist[0][1:]] + + if _level == 1: + if not word_list: + raise ValueError("no words given to make_compressed_re()") + + if "" in word_list: + raise ValueError("word list cannot contain empty string") + else: + # internal recursive call, just return empty string if no words + if not word_list: + return "" + + # dedupe the word list + word_list = list({}.fromkeys(word_list)) + + if max_level == 0: + if any(len(wd) > 1 for wd in word_list): + return "|".join( + sorted([re.escape(wd) for wd in word_list], key=len, reverse=True) + ) + else: + return f"[{''.join(_escape_regex_range_chars(wd) for wd in word_list)}]" + + ret = [] + sep = "" + ncgroup = "?:" if non_capturing_groups else "" + + for initial, suffixes in get_suffixes_from_common_prefixes(sorted(word_list)): + ret.append(sep) + sep = "|" + + initial = re.escape(initial) + + trailing = "" + if "" in suffixes: + trailing = "?" + suffixes.remove("") + + if len(suffixes) > 1: + if all(len(s) == 1 for s in suffixes): + ret.append( + f"{initial}[{''.join(_escape_regex_range_chars(s) for s in suffixes)}]{trailing}" + ) + else: + if _level < max_level: + suffix_re = make_compressed_re( + sorted(suffixes), + max_level, + non_capturing_groups=non_capturing_groups, + _level=_level + 1, + ) + ret.append(f"{initial}({ncgroup}{suffix_re}){trailing}") + else: + if all(len(s) == 1 for s in suffixes): + ret.append( + f"{initial}[{''.join(_escape_regex_range_chars(s) for s in suffixes)}]{trailing}" + ) + else: + suffixes.sort(key=len, reverse=True) + ret.append( + f"{initial}({ncgroup}{'|'.join(re.escape(s) for s in suffixes)}){trailing}" + ) + else: + if suffixes: + suffix = re.escape(suffixes[0]) + if len(suffix) > 1 and trailing: + ret.append(f"{initial}({ncgroup}{suffix}){trailing}") + else: + ret.append(f"{initial}{suffix}{trailing}") + else: + ret.append(initial) + return "".join(ret) + + +def replaced_by_pep8(compat_name: str, fn: C) -> C: + + # Unwrap staticmethod/classmethod + fn = getattr(fn, "__func__", fn) + + # (Presence of 'self' arg in signature is used by explain_exception() methods, so we take + # some extra steps to add it if present in decorated function.) + if ["self"] == list(inspect.signature(fn).parameters)[:1]: + + @wraps(fn) + def _inner(self, *args, **kwargs): + warnings.warn( + f"{compat_name!r} deprecated - use {fn.__name__!r}", + PyparsingDeprecationWarning, + stacklevel=2, + ) + return fn(self, *args, **kwargs) + + else: + + @wraps(fn) + def _inner(*args, **kwargs): + warnings.warn( + f"{compat_name!r} deprecated - use {fn.__name__!r}", + PyparsingDeprecationWarning, + stacklevel=2, + ) + return fn(*args, **kwargs) + + _inner.__doc__ = f""" + .. deprecated:: 3.0.0 + Use :class:`{fn.__name__}` instead + """ + _inner.__name__ = compat_name + _inner.__annotations__ = fn.__annotations__ + if isinstance(fn, types.FunctionType): + _inner.__kwdefaults__ = fn.__kwdefaults__ # type: ignore [attr-defined] + elif isinstance(fn, type) and hasattr(fn, "__init__"): + _inner.__kwdefaults__ = fn.__init__.__kwdefaults__ # type: ignore [misc,attr-defined] + else: + _inner.__kwdefaults__ = None # type: ignore [attr-defined] + _inner.__qualname__ = fn.__qualname__ + return cast(C, _inner) + + +def _to_pep8_name(s: str, _re_sub_pattern=re.compile(r"([a-z])([A-Z])")) -> str: + s = _re_sub_pattern.sub(r"\1_\2", s) + return s.lower() + + +def deprecate_argument( + kwargs: dict[str, Any], arg_name: str, default_value=None, *, new_name: str = "" +) -> Any: + + if arg_name in kwargs: + new_name = new_name or _to_pep8_name(arg_name) + warnings.warn( + f"{arg_name!r} argument is deprecated, use {new_name!r}", + category=PyparsingDeprecationWarning, + stacklevel=3, + ) + else: + kwargs[arg_name] = default_value + + return kwargs[arg_name] diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pyparsing/warnings.py b/TTS/Kokoro/.venv/Lib/site-packages/pyparsing/warnings.py new file mode 100644 index 0000000000000000000000000000000000000000..1e4e9425e62a62d1b70fe26d5b6fae12d3b9d5da --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/pyparsing/warnings.py @@ -0,0 +1,10 @@ +class PyparsingWarning(UserWarning): + """Base warning class for all pyparsing warnings""" + + +class PyparsingDeprecationWarning(PyparsingWarning, DeprecationWarning): + """Base warning class for all pyparsing deprecation warnings""" + + +class PyparsingDiagnosticWarning(PyparsingWarning): + """Base warning class for all pyparsing diagnostic warnings""" diff --git a/TTS/Kokoro/.venv/Lib/site-packages/python_dateutil-2.9.0.post0.dist-info/INSTALLER b/TTS/Kokoro/.venv/Lib/site-packages/python_dateutil-2.9.0.post0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/python_dateutil-2.9.0.post0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/TTS/Kokoro/.venv/Lib/site-packages/python_dateutil-2.9.0.post0.dist-info/LICENSE b/TTS/Kokoro/.venv/Lib/site-packages/python_dateutil-2.9.0.post0.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1e65815cf0b3132689485874a93034ede7206bf4 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/python_dateutil-2.9.0.post0.dist-info/LICENSE @@ -0,0 +1,54 @@ +Copyright 2017- Paul Ganssle +Copyright 2017- dateutil contributors (see AUTHORS file) + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + 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. + +The above license applies to all contributions after 2017-12-01, as well as +all contributions that have been re-licensed (see AUTHORS file for the list of +contributors who have re-licensed their code). +-------------------------------------------------------------------------------- +dateutil - Extensions to the standard Python datetime module. + +Copyright (c) 2003-2011 - Gustavo Niemeyer +Copyright (c) 2012-2014 - Tomi Pieviläinen +Copyright (c) 2014-2016 - Yaron de Leeuw +Copyright (c) 2015- - Paul Ganssle +Copyright (c) 2015- - dateutil contributors (see AUTHORS file) + +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 the copyright holder 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. + +The above BSD License Applies to all code, even that also covered by Apache 2.0. \ No newline at end of file diff --git a/TTS/Kokoro/.venv/Lib/site-packages/python_dateutil-2.9.0.post0.dist-info/METADATA b/TTS/Kokoro/.venv/Lib/site-packages/python_dateutil-2.9.0.post0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..577f2bf2b7749e1b123b8225d610b1b257e430cc --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/python_dateutil-2.9.0.post0.dist-info/METADATA @@ -0,0 +1,204 @@ +Metadata-Version: 2.1 +Name: python-dateutil +Version: 2.9.0.post0 +Summary: Extensions to the standard Python datetime module +Home-page: https://github.com/dateutil/dateutil +Author: Gustavo Niemeyer +Author-email: gustavo@niemeyer.net +Maintainer: Paul Ganssle +Maintainer-email: dateutil@python.org +License: Dual License +Project-URL: Documentation, https://dateutil.readthedocs.io/en/stable/ +Project-URL: Source, https://github.com/dateutil/dateutil +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: BSD License +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 2 +Classifier: Programming Language :: Python :: 2.7 +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.3 +Classifier: Programming Language :: Python :: 3.4 +Classifier: Programming Language :: Python :: 3.5 +Classifier: Programming Language :: Python :: 3.6 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Topic :: Software Development :: Libraries +Requires-Python: !=3.0.*,!=3.1.*,!=3.2.*,>=2.7 +Description-Content-Type: text/x-rst +License-File: LICENSE +Requires-Dist: six >=1.5 + +dateutil - powerful extensions to datetime +========================================== + +|pypi| |support| |licence| + +|gitter| |readthedocs| + +|travis| |appveyor| |pipelines| |coverage| + +.. |pypi| image:: https://img.shields.io/pypi/v/python-dateutil.svg?style=flat-square + :target: https://pypi.org/project/python-dateutil/ + :alt: pypi version + +.. |support| image:: https://img.shields.io/pypi/pyversions/python-dateutil.svg?style=flat-square + :target: https://pypi.org/project/python-dateutil/ + :alt: supported Python version + +.. |travis| image:: https://img.shields.io/travis/dateutil/dateutil/master.svg?style=flat-square&label=Travis%20Build + :target: https://travis-ci.org/dateutil/dateutil + :alt: travis build status + +.. |appveyor| image:: https://img.shields.io/appveyor/ci/dateutil/dateutil/master.svg?style=flat-square&logo=appveyor + :target: https://ci.appveyor.com/project/dateutil/dateutil + :alt: appveyor build status + +.. |pipelines| image:: https://dev.azure.com/pythondateutilazure/dateutil/_apis/build/status/dateutil.dateutil?branchName=master + :target: https://dev.azure.com/pythondateutilazure/dateutil/_build/latest?definitionId=1&branchName=master + :alt: azure pipelines build status + +.. |coverage| image:: https://codecov.io/gh/dateutil/dateutil/branch/master/graphs/badge.svg?branch=master + :target: https://codecov.io/gh/dateutil/dateutil?branch=master + :alt: Code coverage + +.. |gitter| image:: https://badges.gitter.im/dateutil/dateutil.svg + :alt: Join the chat at https://gitter.im/dateutil/dateutil + :target: https://gitter.im/dateutil/dateutil + +.. |licence| image:: https://img.shields.io/pypi/l/python-dateutil.svg?style=flat-square + :target: https://pypi.org/project/python-dateutil/ + :alt: licence + +.. |readthedocs| image:: https://img.shields.io/readthedocs/dateutil/latest.svg?style=flat-square&label=Read%20the%20Docs + :alt: Read the documentation at https://dateutil.readthedocs.io/en/latest/ + :target: https://dateutil.readthedocs.io/en/latest/ + +The `dateutil` module provides powerful extensions to +the standard `datetime` module, available in Python. + +Installation +============ +`dateutil` can be installed from PyPI using `pip` (note that the package name is +different from the importable name):: + + pip install python-dateutil + +Download +======== +dateutil is available on PyPI +https://pypi.org/project/python-dateutil/ + +The documentation is hosted at: +https://dateutil.readthedocs.io/en/stable/ + +Code +==== +The code and issue tracker are hosted on GitHub: +https://github.com/dateutil/dateutil/ + +Features +======== + +* Computing of relative deltas (next month, next year, + next Monday, last week of month, etc); +* Computing of relative deltas between two given + date and/or datetime objects; +* Computing of dates based on very flexible recurrence rules, + using a superset of the `iCalendar `_ + specification. Parsing of RFC strings is supported as well. +* Generic parsing of dates in almost any string format; +* Timezone (tzinfo) implementations for tzfile(5) format + files (/etc/localtime, /usr/share/zoneinfo, etc), TZ + environment string (in all known formats), iCalendar + format files, given ranges (with help from relative deltas), + local machine timezone, fixed offset timezone, UTC timezone, + and Windows registry-based time zones. +* Internal up-to-date world timezone information based on + Olson's database. +* Computing of Easter Sunday dates for any given year, + using Western, Orthodox or Julian algorithms; +* A comprehensive test suite. + +Quick example +============= +Here's a snapshot, just to give an idea about the power of the +package. For more examples, look at the documentation. + +Suppose you want to know how much time is left, in +years/months/days/etc, before the next easter happening on a +year with a Friday 13th in August, and you want to get today's +date out of the "date" unix system command. Here is the code: + +.. code-block:: python3 + + >>> from dateutil.relativedelta import * + >>> from dateutil.easter import * + >>> from dateutil.rrule import * + >>> from dateutil.parser import * + >>> from datetime import * + >>> now = parse("Sat Oct 11 17:13:46 UTC 2003") + >>> today = now.date() + >>> year = rrule(YEARLY,dtstart=now,bymonth=8,bymonthday=13,byweekday=FR)[0].year + >>> rdelta = relativedelta(easter(year), today) + >>> print("Today is: %s" % today) + Today is: 2003-10-11 + >>> print("Year with next Aug 13th on a Friday is: %s" % year) + Year with next Aug 13th on a Friday is: 2004 + >>> print("How far is the Easter of that year: %s" % rdelta) + How far is the Easter of that year: relativedelta(months=+6) + >>> print("And the Easter of that year is: %s" % (today+rdelta)) + And the Easter of that year is: 2004-04-11 + +Being exactly 6 months ahead was **really** a coincidence :) + +Contributing +============ + +We welcome many types of contributions - bug reports, pull requests (code, infrastructure or documentation fixes). For more information about how to contribute to the project, see the ``CONTRIBUTING.md`` file in the repository. + + +Author +====== +The dateutil module was written by Gustavo Niemeyer +in 2003. + +It is maintained by: + +* Gustavo Niemeyer 2003-2011 +* Tomi Pieviläinen 2012-2014 +* Yaron de Leeuw 2014-2016 +* Paul Ganssle 2015- + +Starting with version 2.4.1 and running until 2.8.2, all source and binary +distributions will be signed by a PGP key that has, at the very least, been +signed by the key which made the previous release. A table of release signing +keys can be found below: + +=========== ============================ +Releases Signing key fingerprint +=========== ============================ +2.4.1-2.8.2 `6B49 ACBA DCF6 BD1C A206 67AB CD54 FCE3 D964 BEFB`_ +=========== ============================ + +New releases *may* have signed tags, but binary and source distributions +uploaded to PyPI will no longer have GPG signatures attached. + +Contact +======= +Our mailing list is available at `dateutil@python.org `_. As it is hosted by the PSF, it is subject to the `PSF code of +conduct `_. + +License +======= + +All contributions after December 1, 2017 released under dual license - either `Apache 2.0 License `_ or the `BSD 3-Clause License `_. Contributions before December 1, 2017 - except those those explicitly relicensed - are released only under the BSD 3-Clause License. + + +.. _6B49 ACBA DCF6 BD1C A206 67AB CD54 FCE3 D964 BEFB: + https://pgp.mit.edu/pks/lookup?op=vindex&search=0xCD54FCE3D964BEFB diff --git a/TTS/Kokoro/.venv/Lib/site-packages/python_dateutil-2.9.0.post0.dist-info/RECORD b/TTS/Kokoro/.venv/Lib/site-packages/python_dateutil-2.9.0.post0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..8abf769beb56ed307111268106e19c87137b23df --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/python_dateutil-2.9.0.post0.dist-info/RECORD @@ -0,0 +1,44 @@ +dateutil/__init__.py,sha256=Mqam67WO9IkTmUFyI66vS6IoSXTp9G388DadH2LCMLY,620 +dateutil/__pycache__/__init__.cpython-312.pyc,, +dateutil/__pycache__/_common.cpython-312.pyc,, +dateutil/__pycache__/_version.cpython-312.pyc,, +dateutil/__pycache__/easter.cpython-312.pyc,, +dateutil/__pycache__/relativedelta.cpython-312.pyc,, +dateutil/__pycache__/rrule.cpython-312.pyc,, +dateutil/__pycache__/tzwin.cpython-312.pyc,, +dateutil/__pycache__/utils.cpython-312.pyc,, +dateutil/_common.py,sha256=77w0yytkrxlYbSn--lDVPUMabUXRR9I3lBv_vQRUqUY,932 +dateutil/_version.py,sha256=BV031OxDDAmy58neUg5yyqLkLaqIw7ibK9As3jiMib0,166 +dateutil/easter.py,sha256=dyBi-lKvimH1u_k6p7Z0JJK72QhqVtVBsqByvpEPKvc,2678 +dateutil/parser/__init__.py,sha256=wWk6GFuxTpjoggCGtgkceJoti4pVjl4_fHQXpNOaSYg,1766 +dateutil/parser/__pycache__/__init__.cpython-312.pyc,, +dateutil/parser/__pycache__/_parser.cpython-312.pyc,, +dateutil/parser/__pycache__/isoparser.cpython-312.pyc,, +dateutil/parser/_parser.py,sha256=7klDdyicksQB_Xgl-3UAmBwzCYor1AIZqklIcT6dH_8,58796 +dateutil/parser/isoparser.py,sha256=8Fy999bnCd1frSdOYuOraWfJTtd5W7qQ51NwNuH_hXM,13233 +dateutil/relativedelta.py,sha256=IY_mglMjoZbYfrvloTY2ce02aiVjPIkiZfqgNTZRfuA,24903 +dateutil/rrule.py,sha256=KJzKlaCd1jEbu4A38ZltslaoAUh9nSbdbOFdjp70Kew,66557 +dateutil/tz/__init__.py,sha256=F-Mz13v6jYseklQf9Te9J6nzcLDmq47gORa61K35_FA,444 +dateutil/tz/__pycache__/__init__.cpython-312.pyc,, +dateutil/tz/__pycache__/_common.cpython-312.pyc,, +dateutil/tz/__pycache__/_factories.cpython-312.pyc,, +dateutil/tz/__pycache__/tz.cpython-312.pyc,, +dateutil/tz/__pycache__/win.cpython-312.pyc,, +dateutil/tz/_common.py,sha256=cgzDTANsOXvEc86cYF77EsliuSab8Puwpsl5-bX3_S4,12977 +dateutil/tz/_factories.py,sha256=unb6XQNXrPMveksTCU-Ag8jmVZs4SojoPUcAHpWnrvU,2569 +dateutil/tz/tz.py,sha256=EUnEdMfeThXiY6l4sh9yBabZ63_POzy01zSsh9thn1o,62855 +dateutil/tz/win.py,sha256=xJszWgSwE1xPx_HJj4ZkepyukC_hNy016WMcXhbRaB8,12935 +dateutil/tzwin.py,sha256=7Ar4vdQCnnM0mKR3MUjbIKsZrBVfHgdwsJZc_mGYRew,59 +dateutil/utils.py,sha256=dKCchEw8eObi0loGTx91unBxm_7UGlU3v_FjFMdqwYM,1965 +dateutil/zoneinfo/__init__.py,sha256=KYg0pthCMjcp5MXSEiBJn3nMjZeNZav7rlJw5-tz1S4,5889 +dateutil/zoneinfo/__pycache__/__init__.cpython-312.pyc,, +dateutil/zoneinfo/__pycache__/rebuild.cpython-312.pyc,, +dateutil/zoneinfo/dateutil-zoneinfo.tar.gz,sha256=0-pS57bpaN4NiE3xKIGTWW-pW4A9tPkqGCeac5gARHU,156400 +dateutil/zoneinfo/rebuild.py,sha256=MiqYzCIHvNbMH-LdRYLv-4T0EIA7hDKt5GLR0IRTLdI,2392 +python_dateutil-2.9.0.post0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +python_dateutil-2.9.0.post0.dist-info/LICENSE,sha256=ugD1Gg2SgjtaHN4n2LW50jIeZ-2NqbwWPv-W1eF-V34,2889 +python_dateutil-2.9.0.post0.dist-info/METADATA,sha256=qdQ22jIr6AgzL5jYgyWZjofLaTpniplp_rTPrXKabpM,8354 +python_dateutil-2.9.0.post0.dist-info/RECORD,, +python_dateutil-2.9.0.post0.dist-info/WHEEL,sha256=-G_t0oGuE7UD0DrSpVZnq1hHMBV9DD2XkS5v7XpmTnk,110 +python_dateutil-2.9.0.post0.dist-info/top_level.txt,sha256=4tjdWkhRZvF7LA_BYe_L9gB2w_p2a-z5y6ArjaRkot8,9 +python_dateutil-2.9.0.post0.dist-info/zip-safe,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1 diff --git a/TTS/Kokoro/.venv/Lib/site-packages/python_dateutil-2.9.0.post0.dist-info/WHEEL b/TTS/Kokoro/.venv/Lib/site-packages/python_dateutil-2.9.0.post0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..4724c45738f6ac125bb3a21787855562e6870440 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/python_dateutil-2.9.0.post0.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.42.0) +Root-Is-Purelib: true +Tag: py2-none-any +Tag: py3-none-any + diff --git a/TTS/Kokoro/.venv/Lib/site-packages/python_dateutil-2.9.0.post0.dist-info/top_level.txt b/TTS/Kokoro/.venv/Lib/site-packages/python_dateutil-2.9.0.post0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..66501480ba5b63f98ee9a59c1f99e5e6917da6d9 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/python_dateutil-2.9.0.post0.dist-info/top_level.txt @@ -0,0 +1 @@ +dateutil diff --git a/TTS/Kokoro/.venv/Lib/site-packages/python_dateutil-2.9.0.post0.dist-info/zip-safe b/TTS/Kokoro/.venv/Lib/site-packages/python_dateutil-2.9.0.post0.dist-info/zip-safe new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/python_dateutil-2.9.0.post0.dist-info/zip-safe @@ -0,0 +1 @@ + diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pyyaml-6.0.3.dist-info/INSTALLER b/TTS/Kokoro/.venv/Lib/site-packages/pyyaml-6.0.3.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/pyyaml-6.0.3.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pyyaml-6.0.3.dist-info/METADATA b/TTS/Kokoro/.venv/Lib/site-packages/pyyaml-6.0.3.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..ea62a9bf4d748acfc9f936f09234369b43f46630 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/pyyaml-6.0.3.dist-info/METADATA @@ -0,0 +1,59 @@ +Metadata-Version: 2.4 +Name: PyYAML +Version: 6.0.3 +Summary: YAML parser and emitter for Python +Home-page: https://pyyaml.org/ +Download-URL: https://pypi.org/project/PyYAML/ +Author: Kirill Simonov +Author-email: xi@resolvent.net +License: MIT +Project-URL: Bug Tracker, https://github.com/yaml/pyyaml/issues +Project-URL: CI, https://github.com/yaml/pyyaml/actions +Project-URL: Documentation, https://pyyaml.org/wiki/PyYAMLDocumentation +Project-URL: Mailing lists, http://lists.sourceforge.net/lists/listinfo/yaml-core +Project-URL: Source Code, https://github.com/yaml/pyyaml +Platform: Any +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Cython +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Topic :: Text Processing :: Markup +Requires-Python: >=3.8 +License-File: LICENSE +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: download-url +Dynamic: home-page +Dynamic: license +Dynamic: license-file +Dynamic: platform +Dynamic: project-url +Dynamic: requires-python +Dynamic: summary + +YAML is a data serialization format designed for human readability +and interaction with scripting languages. PyYAML is a YAML parser +and emitter for Python. + +PyYAML features a complete YAML 1.1 parser, Unicode support, pickle +support, capable extension API, and sensible error messages. PyYAML +supports standard YAML tags and provides Python-specific tags that +allow to represent an arbitrary Python object. + +PyYAML is applicable for a broad range of tasks from complex +configuration files to object serialization and persistence. diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pyyaml-6.0.3.dist-info/RECORD b/TTS/Kokoro/.venv/Lib/site-packages/pyyaml-6.0.3.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..81e481c1a0c0f678eeec16a3b0586c0bba56dbfe --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/pyyaml-6.0.3.dist-info/RECORD @@ -0,0 +1,43 @@ +_yaml/__init__.py,sha256=04Ae_5osxahpJHa3XBZUAf4wi6XX32gR8D6X6p64GEA,1402 +_yaml/__pycache__/__init__.cpython-312.pyc,, +pyyaml-6.0.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +pyyaml-6.0.3.dist-info/METADATA,sha256=hHpwECAzQ4aFK24HutEFPLDOPanuGEbn6dArJOi7P40,2410 +pyyaml-6.0.3.dist-info/RECORD,, +pyyaml-6.0.3.dist-info/WHEEL,sha256=8UP9x9puWI0P1V_d7K2oMTBqfeLNm21CTzZ_Ptr0NXU,101 +pyyaml-6.0.3.dist-info/licenses/LICENSE,sha256=jTko-dxEkP1jVwfLiOsmvXZBAqcoKVQwfT5RZ6V36KQ,1101 +pyyaml-6.0.3.dist-info/top_level.txt,sha256=rpj0IVMTisAjh_1vG3Ccf9v5jpCQwAz6cD1IVU5ZdhQ,11 +yaml/__init__.py,sha256=sZ38wzPWp139cwc5ARZFByUvJxtB07X32FUQAzoFR6c,12311 +yaml/__pycache__/__init__.cpython-312.pyc,, +yaml/__pycache__/composer.cpython-312.pyc,, +yaml/__pycache__/constructor.cpython-312.pyc,, +yaml/__pycache__/cyaml.cpython-312.pyc,, +yaml/__pycache__/dumper.cpython-312.pyc,, +yaml/__pycache__/emitter.cpython-312.pyc,, +yaml/__pycache__/error.cpython-312.pyc,, +yaml/__pycache__/events.cpython-312.pyc,, +yaml/__pycache__/loader.cpython-312.pyc,, +yaml/__pycache__/nodes.cpython-312.pyc,, +yaml/__pycache__/parser.cpython-312.pyc,, +yaml/__pycache__/reader.cpython-312.pyc,, +yaml/__pycache__/representer.cpython-312.pyc,, +yaml/__pycache__/resolver.cpython-312.pyc,, +yaml/__pycache__/scanner.cpython-312.pyc,, +yaml/__pycache__/serializer.cpython-312.pyc,, +yaml/__pycache__/tokens.cpython-312.pyc,, +yaml/_yaml.cp312-win_amd64.pyd,sha256=T9DoT1AmHtCIbP_N2ACLBVrzNSVG5knD10G1Dq4fm18,253952 +yaml/composer.py,sha256=_Ko30Wr6eDWUeUpauUGT3Lcg9QPBnOPVlTnIMRGJ9FM,4883 +yaml/constructor.py,sha256=kNgkfaeLUkwQYY_Q6Ff1Tz2XVw_pG1xVE9Ak7z-viLA,28639 +yaml/cyaml.py,sha256=6ZrAG9fAYvdVe2FK_w0hmXoG7ZYsoYUwapG8CiC72H0,3851 +yaml/dumper.py,sha256=PLctZlYwZLp7XmeUdwRuv4nYOZ2UBnDIUy8-lKfLF-o,2837 +yaml/emitter.py,sha256=jghtaU7eFwg31bG0B7RZea_29Adi9CKmXq_QjgQpCkQ,43006 +yaml/error.py,sha256=Ah9z-toHJUbE9j-M8YpxgSRM5CgLCcwVzJgLLRF2Fxo,2533 +yaml/events.py,sha256=50_TksgQiE4up-lKo_V-nBy-tAIxkIPQxY5qDhKCeHw,2445 +yaml/loader.py,sha256=UVa-zIqmkFSCIYq_PgSGm4NSJttHY2Rf_zQ4_b1fHN0,2061 +yaml/nodes.py,sha256=gPKNj8pKCdh2d4gr3gIYINnPOaOxGhJAUiYhGRnPE84,1440 +yaml/parser.py,sha256=ilWp5vvgoHFGzvOZDItFoGjD6D42nhlZrZyjAwa0oJo,25495 +yaml/reader.py,sha256=0dmzirOiDG4Xo41RnuQS7K9rkY3xjHiVasfDMNTqCNw,6794 +yaml/representer.py,sha256=IuWP-cAW9sHKEnS0gCqSa894k1Bg4cgTxaDwIcbRQ-Y,14190 +yaml/resolver.py,sha256=9L-VYfm4mWHxUD1Vg4X7rjDRK_7VZd6b92wzq7Y2IKY,9004 +yaml/scanner.py,sha256=YEM3iLZSaQwXcQRg2l2R4MdT0zGP2F9eHkKGKnHyWQY,51279 +yaml/serializer.py,sha256=ChuFgmhU01hj4xgI8GaKv6vfM2Bujwa9i7d2FAHj7cA,4165 +yaml/tokens.py,sha256=lTQIzSVw8Mg9wv459-TjiOQe6wVziqaRlqX2_89rp54,2573 diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pyyaml-6.0.3.dist-info/WHEEL b/TTS/Kokoro/.venv/Lib/site-packages/pyyaml-6.0.3.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..10ac2c23843796b65786bc9aba179a906c8bcc88 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/pyyaml-6.0.3.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: false +Tag: cp312-cp312-win_amd64 + diff --git a/TTS/Kokoro/.venv/Lib/site-packages/pyyaml-6.0.3.dist-info/top_level.txt b/TTS/Kokoro/.venv/Lib/site-packages/pyyaml-6.0.3.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..e6475e911f628412049bc4090d86f23ac403adde --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/pyyaml-6.0.3.dist-info/top_level.txt @@ -0,0 +1,2 @@ +_yaml +yaml diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rdflib-7.6.0.dist-info/INSTALLER b/TTS/Kokoro/.venv/Lib/site-packages/rdflib-7.6.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rdflib-7.6.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rdflib-7.6.0.dist-info/LICENSE b/TTS/Kokoro/.venv/Lib/site-packages/rdflib-7.6.0.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..4972574c7b888f820f3f3e3ee50f06e05f7d4849 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rdflib-7.6.0.dist-info/LICENSE @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2002-2026, RDFLib Team +All rights reserved. + +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. + +3. Neither the name of the copyright holder 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 HOLDER 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. diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rdflib-7.6.0.dist-info/METADATA b/TTS/Kokoro/.venv/Lib/site-packages/rdflib-7.6.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..b9cd6637cbfef483ca7ac804fc18ed6e7447de86 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rdflib-7.6.0.dist-info/METADATA @@ -0,0 +1,293 @@ +Metadata-Version: 2.1 +Name: rdflib +Version: 7.6.0 +Summary: RDFLib is a Python library for working with RDF, a simple yet powerful language for representing information. +Home-page: https://github.com/RDFLib/rdflib +License: BSD-3-Clause +Author: Daniel 'eikeon' Krech +Author-email: eikeon@eikeon.com +Maintainer: RDFLib Team +Maintainer-email: rdflib-dev@googlegroups.com +Requires-Python: >=3.8.1 +Classifier: License :: OSI Approved :: BSD License +Classifier: Natural Language :: English +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Provides-Extra: berkeleydb +Provides-Extra: graphdb +Provides-Extra: html +Provides-Extra: lxml +Provides-Extra: networkx +Provides-Extra: orjson +Provides-Extra: rdf4j +Requires-Dist: berkeleydb (>=18.1.0,<19.0.0) ; extra == "berkeleydb" +Requires-Dist: html5rdf (>=1.2,<2) ; extra == "html" +Requires-Dist: httpx (>=0.28.1,<0.29.0) ; extra == "rdf4j" or extra == "graphdb" +Requires-Dist: isodate (>=0.7.2,<1.0.0) ; python_version < "3.11" +Requires-Dist: lxml (>=4.3,<6.0) ; extra == "lxml" +Requires-Dist: networkx (>=2,<4) ; extra == "networkx" +Requires-Dist: orjson (>=3.9.14,<4) ; extra == "orjson" +Requires-Dist: pyparsing (>=2.1.0,<4) +Project-URL: Documentation, https://rdflib.readthedocs.org/ +Project-URL: Repository, https://github.com/RDFLib/rdflib +Description-Content-Type: text/markdown + +![](docs/_static/RDFlib.png) + +# RDFLib + +[![Build Status](https://github.com/RDFLib/rdflib/actions/workflows/validate.yaml/badge.svg?branch=main)](https://github.com/RDFLib/rdflib/actions?query=branch%3Amain) +[![Documentation Status](https://readthedocs.org/projects/rdflib/badge/?version=latest)](https://rdflib.readthedocs.io/en/latest/?badge=latest) +[![Coveralls branch](https://img.shields.io/coveralls/RDFLib/rdflib/main.svg)](https://coveralls.io/r/RDFLib/rdflib?branch=main) + +[![GitHub stars](https://img.shields.io/github/stars/RDFLib/rdflib.svg)](https://github.com/RDFLib/rdflib/stargazers) +[![Downloads](https://pepy.tech/badge/rdflib/week)](https://pepy.tech/project/rdflib) +[![PyPI](https://img.shields.io/pypi/v/rdflib.svg)](https://pypi.python.org/pypi/rdflib) +[![PyPI](https://img.shields.io/pypi/pyversions/rdflib.svg)](https://pypi.python.org/pypi/rdflib) +[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.6845245.svg)](https://doi.org/10.5281/zenodo.6845245) + +[![Contribute with Gitpod](https://img.shields.io/badge/Contribute%20with-Gitpod-908a85?logo=gitpod)](https://gitpod.io/#https://github.com/RDFLib/rdflib) +[![Gitter](https://badges.gitter.im/RDFLib/rdflib.svg)](https://gitter.im/RDFLib/rdflib?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) +[![Matrix](https://img.shields.io/matrix/rdflib:matrix.org?label=matrix.org%20chat)](https://matrix.to/#/#RDFLib_rdflib:gitter.im) + +RDFLib is a pure Python package for working with [RDF](http://www.w3.org/RDF/). RDFLib contains most things you need to work with RDF, including: + +* parsers and serializers for RDF/XML, N3, NTriples, N-Quads, Turtle, TriX, Trig, JSON-LD and even HexTuples +* a Graph interface which can be backed by any one of a number of Store implementations +* Store implementations for in-memory, persistent on disk (Berkeley DB) and remote SPARQL endpoints + * additional Stores can be supplied via plugins +* a SPARQL 1.1 implementation - supporting SPARQL 1.1 Queries and Update statements +* SPARQL function extension mechanisms + +## RDFlib Family of packages +The RDFlib community maintains many RDF-related Python code repositories with different purposes. For example: + +* [rdflib](https://github.com/RDFLib/rdflib) - the RDFLib core +* [sparqlwrapper](https://github.com/RDFLib/sparqlwrapper) - a simple Python wrapper around a SPARQL service to remotely execute your queries +* [pyLODE](https://github.com/RDFLib/pyLODE) - An OWL ontology documentation tool using Python and templating, based on LODE. +* [pyrdfa3](https://github.com/RDFLib/pyrdfa3) - RDFa 1.1 distiller/parser library: can extract RDFa 1.1/1.0 from (X)HTML, SVG, or XML in general. +* [pymicrodata](https://github.com/RDFLib/pymicrodata) - A module to extract RDF from an HTML5 page annotated with microdata. +* [pySHACL](https://github.com/RDFLib/pySHACL) - A pure Python module which allows for the validation of RDF graphs against SHACL graphs. +* [OWL-RL](https://github.com/RDFLib/OWL-RL) - A simple implementation of the OWL2 RL Profile which expands the graph with all possible triples that OWL RL defines. + +Please see the list for all packages/repositories here: + +* + +Help with maintenance of all of the RDFLib family of packages is always welcome and appreciated. + +## Versions & Releases + +* `main` branch in this repository is the current unstable release - version 8 alpha +* `7.6.0` GraphDB Client, and many improvements and fixes. See changelog for details +* `7.5.0` RDF4J Store integration, RDF4J Client, and other improvements. See changelog for details +* `7.4.0` a few small fixes, add test matrix for active python versions, and move v7 documentation to MkDocs +* `7.3.0` many fixes and usability improvements, particularly for the Dataset class. See changelog for details +* `7.2.1` tiny clean up release, relaxes Python version requirement +* `7.2.0` general fixes and usability improvements, see changelog for details +* `7.1.4` tidy-up release, possibly last 7.x release +* `7.1.3` current stable release, small improvements to 7.1.1 +* `7.1.2` previously deleted release +* `7.1.1` previous stable release + * see +* `7.0.0` previous stable release, supports Python 3.8.1+ only. + * see [Releases](https://github.com/RDFLib/rdflib/releases) +* `6.x.y` supports Python 3.7+ only. Many improvements over 5.0.0 + * see [Releases](https://github.com/RDFLib/rdflib/releases) +* `5.x.y` supports Python 2.7 and 3.4+ and is [mostly backwards compatible with 4.2.2](https://rdflib.readthedocs.io/en/stable/upgrade4to5.html). + +See for the release details. + +## Documentation +See for our documentation built from the code. Note that there are `latest`, `stable` and versioned builds, such as `5.0.0`, matching releases. + +## Installation +The stable release of RDFLib may be installed with Python's package management tool *pip*: + + $ pip install rdflib + +Some features of RDFLib require optional dependencies which may be installed using *pip* extras: + + $ pip install rdflib[berkeleydb,networkx,html,lxml,orjson] + +Alternatively manually download the package from the Python Package +Index (PyPI) at https://pypi.python.org/pypi/rdflib + +### Installation of the current main branch (for developers) + +With *pip* you can also install rdflib from the git repository with one of the following options: + + $ pip install git+https://github.com/rdflib/rdflib@main + +or + + $ pip install -e git+https://github.com/rdflib/rdflib@main#egg=rdflib + +or from your locally cloned repository you can install it with one of the following options: + + $ poetry install # installs into a poetry-managed venv + +or + + $ pip install -e . + +## Getting Started +RDFLib aims to be a pythonic RDF API. RDFLib's main data object is a `Graph` which is a Python collection +of RDF *Subject, Predicate, Object* Triples: + +To create graph and load it with RDF data from DBPedia then print the results: + +```python +from rdflib import Graph +g = Graph() +g.parse('http://dbpedia.org/resource/Semantic_Web') + +for s, p, o in g: + print(s, p, o) +``` +The components of the triples are URIs (resources) or Literals +(values). + +URIs are grouped together by *namespace*, common namespaces are included in RDFLib: + +```python +from rdflib.namespace import DC, DCTERMS, DOAP, FOAF, SKOS, OWL, RDF, RDFS, VOID, XMLNS, XSD +``` + +You can use them like this: + +```python +from rdflib import Graph, URIRef, Literal +from rdflib.namespace import RDFS, XSD + +g = Graph() +semweb = URIRef('http://dbpedia.org/resource/Semantic_Web') +type = g.value(semweb, RDFS.label) +``` +Where `RDFS` is the RDFS namespace, `XSD` the XML Schema Datatypes namespace and `g.value` returns an object of the triple-pattern given (or an arbitrary one if multiple exist). + +Or like this, adding a triple to a graph `g`: + +```python +g.add(( + URIRef("http://example.com/person/nick"), + FOAF.givenName, + Literal("Nick", datatype=XSD.string) +)) +``` + +The triple (in n-triples notation) ` "Nick"^^ .` +is created where the property `FOAF.givenName` is the URI `` and `XSD.string` is the +URI ``. + +You can bind namespaces to prefixes to shorten the URIs for RDF/XML, Turtle, N3, TriG, TriX & JSON-LD serializations: + +```python +g.bind("foaf", FOAF) +g.bind("xsd", XSD) +``` + +This will allow the n-triples triple above to be serialised like this: + +```python +print(g.serialize(format="turtle")) +``` + +With these results: +```turtle +PREFIX foaf: +PREFIX xsd: + + foaf:givenName "Nick"^^xsd:string . +``` + +New Namespaces can also be defined: + +```python +dbpedia = Namespace('http://dbpedia.org/ontology/') + +abstracts = list(x for x in g.objects(semweb, dbpedia['abstract']) if x.language=='en') +``` + +See also [./examples](./examples) + + +## Features +The library contains parsers and serializers for RDF/XML, N3, +NTriples, N-Quads, Turtle, TriX, JSON-LD, RDFa and Microdata. + +The library presents a Graph interface which can be backed by +any one of a number of Store implementations. + +This core RDFLib package includes store implementations for +in-memory storage and persistent storage on top of the Berkeley DB. + +A SPARQL 1.1 implementation is included - supporting SPARQL 1.1 Queries and Update statements. + +RDFLib is open source and is maintained on [GitHub](https://github.com/RDFLib/rdflib/). RDFLib releases, current and previous +are listed on [PyPI](https://pypi.python.org/pypi/rdflib/) + +Multiple other projects are contained within the RDFlib "family", see . + +## Running tests + +### Running the tests on the host + +Run the test suite with `pytest`. +```shell +poetry install +poetry run pytest +``` + +### Running test coverage on the host with coverage report + +Run the test suite and generate a HTML coverage report with `pytest` and `pytest-cov`. +```shell +poetry run pytest --cov +``` + +### Viewing test coverage + +Once tests have produced HTML output of the coverage report, view it by running: +```shell +poetry run pytest --cov --cov-report term --cov-report html +python -m http.server --directory=htmlcov +``` + +## Contributing + +RDFLib survives and grows via user contributions! +Please read our [contributing guide](https://rdflib.readthedocs.io/en/latest/CONTRIBUTING.html) and [developers guide](https://rdflib.readthedocs.io/en/latest/developers.html) to get started. +Please consider lodging Pull Requests here: + +* + +To get a development environment consider using Gitpod or Google Cloud Shell. + +[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/RDFLib/rdflib) +[![Open in Cloud Shell](https://gstatic.com/cloudssh/images/open-btn.svg)](https://shell.cloud.google.com/cloudshell/editor?cloudshell_git_repo=https%3A%2F%2Fgithub.com%2FRDFLib%2Frdflib&cloudshell_git_branch=main&cloudshell_open_in_editor=README.md) + +You can also raise issues here: + +* + +## Support & Contacts +For general "how do I..." queries, please use https://stackoverflow.com and tag your question with `rdflib`. +Existing questions: + +* + +If you want to contact the rdflib maintainers, please do so via: + +* the rdflib-dev mailing list: +* the chat, which is available at [gitter](https://gitter.im/RDFLib/rdflib) or via matrix [#RDFLib_rdflib:gitter.im](https://matrix.to/#/#RDFLib_rdflib:gitter.im) + diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rdflib-7.6.0.dist-info/RECORD b/TTS/Kokoro/.venv/Lib/site-packages/rdflib-7.6.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..3f9502786b74593cd8f43172e69023e10772d216 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rdflib-7.6.0.dist-info/RECORD @@ -0,0 +1,285 @@ +../../Scripts/csv2rdf.exe,sha256=GsYBj6kccaSqpW3TlqCDuQMnNffZ5_Ur5HTGs9T9QP8,108383 +../../Scripts/rdf2dot.exe,sha256=kQOxSd5MD38neA-CSqF11npwROw8MchzO10fLA2d4oQ,108383 +../../Scripts/rdfgraphisomorphism.exe,sha256=F6bgNthjswECHikwDCJU3NaKCfMtpWMklwPiDtvhlAo,108392 +../../Scripts/rdfpipe.exe,sha256=zCc7d0EbI8LsGSqCMPwzWJui7DYSH8vZzVlEbt41hQw,108383 +../../Scripts/rdfs2dot.exe,sha256=MIqxqKC84S--NLWmV3Gkh0zyJv9LMEHRdFJ6GUmUJps,108384 +../../Scripts/sparqlquery.exe,sha256=KrvLG6jdp5WZ1DbfI1ZIa0P2Y73uEAm9AHsx1MTLoQk,108387 +rdflib-7.6.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +rdflib-7.6.0.dist-info/LICENSE,sha256=U6cF5Rv9GZ6Ml9BEI3bLS71P_PE7pPLEwnlCEUAOQBI,1524 +rdflib-7.6.0.dist-info/METADATA,sha256=KcVpRDc4pFv9hd03hloDjX4Z5csoLdO9X4DxSdjR9VI,12584 +rdflib-7.6.0.dist-info/RECORD,, +rdflib-7.6.0.dist-info/WHEEL,sha256=Nq82e9rUAnEjt98J6MlVmMCZb-t9cYE2Ir1kpBmnWfs,88 +rdflib-7.6.0.dist-info/entry_points.txt,sha256=tI4kjBWTSLLo2RCWq4yYdawLSoMg4ZxXEf6mA-goQpE,254 +rdflib/__init__.py,sha256=WxHTXawsb2CLhnYFahPXhuUm7GYKpJTAgeAXlxZXkvw,4762 +rdflib/__pycache__/__init__.cpython-312.pyc,, +rdflib/__pycache__/_networking.cpython-312.pyc,, +rdflib/__pycache__/_type_checking.cpython-312.pyc,, +rdflib/__pycache__/collection.cpython-312.pyc,, +rdflib/__pycache__/compare.cpython-312.pyc,, +rdflib/__pycache__/compat.cpython-312.pyc,, +rdflib/__pycache__/container.cpython-312.pyc,, +rdflib/__pycache__/events.cpython-312.pyc,, +rdflib/__pycache__/exceptions.cpython-312.pyc,, +rdflib/__pycache__/graph.cpython-312.pyc,, +rdflib/__pycache__/parser.cpython-312.pyc,, +rdflib/__pycache__/paths.cpython-312.pyc,, +rdflib/__pycache__/plugin.cpython-312.pyc,, +rdflib/__pycache__/query.cpython-312.pyc,, +rdflib/__pycache__/resource.cpython-312.pyc,, +rdflib/__pycache__/serializer.cpython-312.pyc,, +rdflib/__pycache__/store.cpython-312.pyc,, +rdflib/__pycache__/term.cpython-312.pyc,, +rdflib/__pycache__/util.cpython-312.pyc,, +rdflib/__pycache__/void.cpython-312.pyc,, +rdflib/__pycache__/xsd_datetime.cpython-312.pyc,, +rdflib/_networking.py,sha256=HKONCCUrQfpWwDgDN-NAEYRMZc0hCCd2IIcvw-zavLg,4623 +rdflib/_type_checking.py,sha256=Uxbms7Se7DxeD2y7VvxMdSY9KWpHTeMHJq3s-HkA3nM,916 +rdflib/collection.py,sha256=di9_m-CZB3JLUgBFzITWkutfT7Vzy9gi9t9egP1eZqk,10085 +rdflib/compare.py,sha256=wnoe3YxKERFIioeHnfbqjztiHIXjob9sbQoCaGB1Gx4,22033 +rdflib/compat.py,sha256=lmdF6eDnroUYERcZsYrr9xEvXfaiD8-hdAEKoeqvk9w,2406 +rdflib/container.py,sha256=TIBb8eZQIBRZezF25G1cOnHTlOLEsMkXXRPs4eurVHM,8138 +rdflib/contrib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +rdflib/contrib/__pycache__/__init__.cpython-312.pyc,, +rdflib/contrib/graphdb/__init__.py,sha256=lABzO6a45KxM7hHvuTxSpHywic2mF81GPLd6gCMvqL4,129 +rdflib/contrib/graphdb/__pycache__/__init__.cpython-312.pyc,, +rdflib/contrib/graphdb/__pycache__/client.cpython-312.pyc,, +rdflib/contrib/graphdb/__pycache__/exceptions.cpython-312.pyc,, +rdflib/contrib/graphdb/__pycache__/models.cpython-312.pyc,, +rdflib/contrib/graphdb/__pycache__/util.cpython-312.pyc,, +rdflib/contrib/graphdb/client.py,sha256=aN-pkoRxkRRaDmAC3XYYn26ZIG5UgocAmG_tDhIwH5w,123860 +rdflib/contrib/graphdb/exceptions.py,sha256=GH8LGJZFbFy7YBjxXU0K4-_ZtzXNZDyPKEBtRPQA5AA,1318 +rdflib/contrib/graphdb/models.py,sha256=w10tlzik7ewM6MQWbWU5qG7Ix7MGr-sU5wUjhCvdHk0,61466 +rdflib/contrib/graphdb/util.py,sha256=xtftKtU9RYF7d6ZXJ_8euSDNj2NLZxwWVqjhZcnlDak,2135 +rdflib/contrib/rdf4j/__init__.py,sha256=qEz2f3-e5Z9zIo7JJ2kHktKo4qYIgu0WpUJfa-jkvg8,210 +rdflib/contrib/rdf4j/__pycache__/__init__.cpython-312.pyc,, +rdflib/contrib/rdf4j/__pycache__/client.cpython-312.pyc,, +rdflib/contrib/rdf4j/__pycache__/exceptions.cpython-312.pyc,, +rdflib/contrib/rdf4j/__pycache__/util.cpython-312.pyc,, +rdflib/contrib/rdf4j/client.py,sha256=BN6V2ZHk5OwPLniqM_kiqTybtx2EJ4jRIzN2vrzM0gw,44292 +rdflib/contrib/rdf4j/exceptions.py,sha256=_0agbUgxDpxXa_eRxyhFVonYE8B6KCvaATF_CiaWG9k,1477 +rdflib/contrib/rdf4j/util.py,sha256=hMnQtbg0WCuMzq31k5c_nH8TcyzP523_sNa7B0uwLcI,5931 +rdflib/events.py,sha256=T8PqvbuDTFYgI12xSzfhrZgpXY7XQWO69FE_TesBpWA,2978 +rdflib/exceptions.py,sha256=5LYvnkGqs0snG8nRe9OF9jndaJnd54ayKS2slH7ahZc,850 +rdflib/extras/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +rdflib/extras/__pycache__/__init__.cpython-312.pyc,, +rdflib/extras/__pycache__/cmdlineutils.cpython-312.pyc,, +rdflib/extras/__pycache__/describer.cpython-312.pyc,, +rdflib/extras/__pycache__/external_graph_libs.cpython-312.pyc,, +rdflib/extras/__pycache__/infixowl.cpython-312.pyc,, +rdflib/extras/__pycache__/shacl.cpython-312.pyc,, +rdflib/extras/cmdlineutils.py,sha256=5AH_JNF--DRZWSXh5PoHi4lm9nivXnioz1w1pMrkCxE,1948 +rdflib/extras/describer.py,sha256=rkMGcoF9ARJw_uaf-gQppo0JeoiTWHLNjjB1BDhtdCA,9071 +rdflib/extras/external_graph_libs.py,sha256=1Wxr1po_340jZTNEHdT7YSp2yp2pv2YYiFeE8ZNCSX8,12400 +rdflib/extras/infixowl.py,sha256=IBQvCaRzUSZhzQ7hDY5jdRxuW2LqpqcCPn_tL_lP2Fo,81391 +rdflib/extras/shacl.py,sha256=_GJ8C2LuDW1-YnR7fHGXb4UEK_J-4vTTjsZ3XpOiwC0,8434 +rdflib/graph.py,sha256=DKMywGvMvBaDP8-R91VXrJyW5aM60tei4ao_LTws_EI,127386 +rdflib/namespace/_BRICK.py,sha256=XsMA9-_01jbMR1T9l-3600q4K1v4TZU8nAn7pjbiIKA,126990 +rdflib/namespace/_CSVW.py,sha256=veMbUAm24GONxs1Kdk1VMat65niKWEPySlqcT8YxLQg,12976 +rdflib/namespace/_DC.py,sha256=mjA91wYdEvT-Hx79RHZgcpMB_SVw_yjwj98F6_iD4vg,1673 +rdflib/namespace/_DCAM.py,sha256=JxvGJe95380fDIvZsgUhIGYGI9aIF7aF_4hf6RjY63Y,887 +rdflib/namespace/_DCAT.py,sha256=pHlF5yFsUAu6RqfbyvULir6tiQpDTCiNzPGwIbGEiYs,5474 +rdflib/namespace/_DCMITYPE.py,sha256=MC2f0ChRgWho8hS9Rv1dGO3LY_g1WP1WPkwcYfh6d6c,1337 +rdflib/namespace/_DCTERMS.py,sha256=4HDU5fid7Z0v6MOUuZpvvHnNQ3MzMeboizsfgJg4qxA,10012 +rdflib/namespace/_DOAP.py,sha256=wk_uK25tvoAjwJSieIpiUeg1iJoCq6yd33D2fPWokSQ,14664 +rdflib/namespace/_FOAF.py,sha256=io2arNzBsiYtHXJVxz9UdhljSPNFEkC4L_YmWqTomqI,6247 +rdflib/namespace/_GEO.py,sha256=Ld5Ff6ZFnJt2zFjppXvLKJnmBo_b4-J2-qul6pckjwA,9083 +rdflib/namespace/_ODRL2.py,sha256=yeDIBtPymmv0cwsxoW22OogQibcBkMl1OC4IZH2ECYs,22158 +rdflib/namespace/_ORG.py,sha256=zhobrfzEmjam_W0JeZKKJxIcvID3SE1TcWKjrD8CIuo,13207 +rdflib/namespace/_OWL.py,sha256=Q_A272osHglNHzvJVaaR0-h31TuJBeLKS2TS7NM5R7w,10480 +rdflib/namespace/_PROF.py,sha256=QKYhG7ulMe_6wKS5Ye6FZ_oghKeVmo7Qdcupk7vMlyQ,2807 +rdflib/namespace/_PROV.py,sha256=DNq0vTDBa9Vh4rXMVnz5VJ8vIRSPltHn8nhljdyStes,24148 +rdflib/namespace/_QB.py,sha256=bPegKsZ_iZh47HPoeRqIN2k1FXNYG6kITECKaqN75vw,5413 +rdflib/namespace/_RDF.py,sha256=icPqdMkOC1ukMJDyGFR6nWdC7KsMp1cuHX2_587SXnc,2249 +rdflib/namespace/_RDFS.py,sha256=Gw0zTb0B0VTn2pvwI3bQYEqjH91JguG_XSy3den7DDA,1488 +rdflib/namespace/_SDO.py,sha256=iCWwLFWqoupbQK7d2k_7zqD84SZ90LAHijexqTU47kU,424141 +rdflib/namespace/_SH.py,sha256=dMK9rpvD9JqrVssb3jYUniuOQjF4Ug4C-3nK86ahPPQ,23321 +rdflib/namespace/_SKOS.py,sha256=qnTVyb31WxMoFf2vRcEnAYXJXaEwsVpCNKeUMl73_d8,4715 +rdflib/namespace/_SOSA.py,sha256=BzuIlQSzNgaN5jYMQaR0HA4COX68wsROl2gOI2in8v8,7117 +rdflib/namespace/_SSN.py,sha256=T9JKgBQdipzcKc3o6xwz4wM9WLI-avhywRXROqCbHkM,3213 +rdflib/namespace/_TIME.py,sha256=JiSNziV0A4r8KMstVppHgeY8ZHzDzQhzwU7lHybpblI,12936 +rdflib/namespace/_VANN.py,sha256=pKantDMzEu_wfOFT7zXYIhFlsgTJu_ylgv5PCpRGLJE,1232 +rdflib/namespace/_VOID.py,sha256=Nyv3GnciRwLLu6aNL-feMbrRuYv4fU66deCwDVCFSjA,4689 +rdflib/namespace/_WGS.py,sha256=HPXnL6MqFJ8b6uVl_QdgG456dZLKfwH89UpAC7G58Pc,633 +rdflib/namespace/_XSD.py,sha256=vPN0Cg5PcZzqIj4NdwhFiYOJuiHYbCUb5v-tBsWAQGs,6276 +rdflib/namespace/__init__.py,sha256=ulmMLBkug_gE8kVF_HPypwoFVQUa2L_aTPedPkQTUcw,34375 +rdflib/namespace/__pycache__/_BRICK.cpython-312.pyc,, +rdflib/namespace/__pycache__/_CSVW.cpython-312.pyc,, +rdflib/namespace/__pycache__/_DC.cpython-312.pyc,, +rdflib/namespace/__pycache__/_DCAM.cpython-312.pyc,, +rdflib/namespace/__pycache__/_DCAT.cpython-312.pyc,, +rdflib/namespace/__pycache__/_DCMITYPE.cpython-312.pyc,, +rdflib/namespace/__pycache__/_DCTERMS.cpython-312.pyc,, +rdflib/namespace/__pycache__/_DOAP.cpython-312.pyc,, +rdflib/namespace/__pycache__/_FOAF.cpython-312.pyc,, +rdflib/namespace/__pycache__/_GEO.cpython-312.pyc,, +rdflib/namespace/__pycache__/_ODRL2.cpython-312.pyc,, +rdflib/namespace/__pycache__/_ORG.cpython-312.pyc,, +rdflib/namespace/__pycache__/_OWL.cpython-312.pyc,, +rdflib/namespace/__pycache__/_PROF.cpython-312.pyc,, +rdflib/namespace/__pycache__/_PROV.cpython-312.pyc,, +rdflib/namespace/__pycache__/_QB.cpython-312.pyc,, +rdflib/namespace/__pycache__/_RDF.cpython-312.pyc,, +rdflib/namespace/__pycache__/_RDFS.cpython-312.pyc,, +rdflib/namespace/__pycache__/_SDO.cpython-312.pyc,, +rdflib/namespace/__pycache__/_SH.cpython-312.pyc,, +rdflib/namespace/__pycache__/_SKOS.cpython-312.pyc,, +rdflib/namespace/__pycache__/_SOSA.cpython-312.pyc,, +rdflib/namespace/__pycache__/_SSN.cpython-312.pyc,, +rdflib/namespace/__pycache__/_TIME.cpython-312.pyc,, +rdflib/namespace/__pycache__/_VANN.cpython-312.pyc,, +rdflib/namespace/__pycache__/_VOID.cpython-312.pyc,, +rdflib/namespace/__pycache__/_WGS.cpython-312.pyc,, +rdflib/namespace/__pycache__/_XSD.cpython-312.pyc,, +rdflib/namespace/__pycache__/__init__.cpython-312.pyc,, +rdflib/parser.py,sha256=55iXoQl_nZeAA6ZuWn0zlMF324quRziVJlgAABMrQEQ,27817 +rdflib/paths.py,sha256=spHsA7zjrEV8Be-l0f51uTYkU1Ne8C273jMZbPKft9E,20416 +rdflib/plugin.py,sha256=rEIDmLsBNH-L3O39oD_wfPqCstcvuBM06puIItu5IEQ,13082 +rdflib/plugins/__init__.py,sha256=39nGkLLAy54hfMDO9jCpUoaAcVeDdmKCKB3xRQ7KnkA,111 +rdflib/plugins/__pycache__/__init__.cpython-312.pyc,, +rdflib/plugins/parsers/RDFVOC.py,sha256=WTqXCoT8Lu3o58z6IqECgu30aKumUGDRQX4iApKgZSE,481 +rdflib/plugins/parsers/__init__.py,sha256=ZDM6PY6oTeexN42BfYxOW10i7SyAdg65d7zGHivdPl0,268 +rdflib/plugins/parsers/__pycache__/RDFVOC.cpython-312.pyc,, +rdflib/plugins/parsers/__pycache__/__init__.cpython-312.pyc,, +rdflib/plugins/parsers/__pycache__/hext.cpython-312.pyc,, +rdflib/plugins/parsers/__pycache__/jsonld.cpython-312.pyc,, +rdflib/plugins/parsers/__pycache__/notation3.cpython-312.pyc,, +rdflib/plugins/parsers/__pycache__/nquads.cpython-312.pyc,, +rdflib/plugins/parsers/__pycache__/ntriples.cpython-312.pyc,, +rdflib/plugins/parsers/__pycache__/patch.cpython-312.pyc,, +rdflib/plugins/parsers/__pycache__/rdfxml.cpython-312.pyc,, +rdflib/plugins/parsers/__pycache__/trig.cpython-312.pyc,, +rdflib/plugins/parsers/__pycache__/trix.cpython-312.pyc,, +rdflib/plugins/parsers/hext.py,sha256=1J4ZexQ2lrqgwip-7c5JOqBWAR0961XMmFmtEJuT1xE,6459 +rdflib/plugins/parsers/jsonld.py,sha256=D_9Ml1I-9HcMe-qN50jKNu4weC6zDNz2z-p_5GMXS-w,24409 +rdflib/plugins/parsers/notation3.py,sha256=o-NhYyVntTJqBjGOk-CB8x-Tx0l9G1LLuR8u9GCp08o,67404 +rdflib/plugins/parsers/nquads.py,sha256=6r4uYH4HUEn8rvNiHQjwlLjX-q73VQomN3TnfOUZJTo,5333 +rdflib/plugins/parsers/ntriples.py,sha256=EagrUzaZhu8d49uK9LBKJbRDaK-MDthyCZ0LVtBBtX8,12632 +rdflib/plugins/parsers/patch.py,sha256=KWOkZFoDgSu7rVqzG2OsM8cqd5Qe_o5BUxvkYeUGkt4,6555 +rdflib/plugins/parsers/rdfxml.py,sha256=A_XaUmfimwcL_TKz3XeNQuF-GXhWQ1T5JygYWy-Cb0M,26145 +rdflib/plugins/parsers/trig.py,sha256=_KKmS5XYnGMv8pqoVBNTo9LyLjNTcr1GKkOyb0jscMU,5428 +rdflib/plugins/parsers/trix.py,sha256=gh_msqDxG8xuiNUUree42KbDJUHRjmqp9ZbjwY3kBQk,10078 +rdflib/plugins/serializers/__init__.py,sha256=c4Qll5RuxnrZoqhOnoPFxTVf444szzVENam14jzGCug,293 +rdflib/plugins/serializers/__pycache__/__init__.cpython-312.pyc,, +rdflib/plugins/serializers/__pycache__/hext.cpython-312.pyc,, +rdflib/plugins/serializers/__pycache__/jsonld.cpython-312.pyc,, +rdflib/plugins/serializers/__pycache__/longturtle.cpython-312.pyc,, +rdflib/plugins/serializers/__pycache__/n3.cpython-312.pyc,, +rdflib/plugins/serializers/__pycache__/nquads.cpython-312.pyc,, +rdflib/plugins/serializers/__pycache__/nt.cpython-312.pyc,, +rdflib/plugins/serializers/__pycache__/patch.cpython-312.pyc,, +rdflib/plugins/serializers/__pycache__/rdfxml.cpython-312.pyc,, +rdflib/plugins/serializers/__pycache__/trig.cpython-312.pyc,, +rdflib/plugins/serializers/__pycache__/trix.cpython-312.pyc,, +rdflib/plugins/serializers/__pycache__/turtle.cpython-312.pyc,, +rdflib/plugins/serializers/__pycache__/xmlwriter.cpython-312.pyc,, +rdflib/plugins/serializers/hext.py,sha256=xc__dMPlKO5beQqQLWFD2wPyldht72t6B2r805TG1Bo,7549 +rdflib/plugins/serializers/jsonld.py,sha256=4spGcdzXbTDWDLMJ2HOFsqmSnFuGn_kCz6z8ucPLBzA,15400 +rdflib/plugins/serializers/longturtle.py,sha256=2_vLRYzrgq1AmgF05-Qmp3bGa64OFKnLY5zcPbxMrW4,12375 +rdflib/plugins/serializers/n3.py,sha256=_XhWpxmn65Goh48Iv_JkJlEnWXRWBsp3kKinmAvW0Bc,3447 +rdflib/plugins/serializers/nquads.py,sha256=ntShF8iHCoI2St8dLqGVnyp8pcm8GFLnhwA6tAzEu_E,1988 +rdflib/plugins/serializers/nt.py,sha256=RvrkE-_VPBwd_beMQKvNMWwx2xKixGQBdcQ55hggSjI,3106 +rdflib/plugins/serializers/patch.py,sha256=3MNghnZgBf_4DjjEsEXTlUkSatQ9UYRiTlstdfh--8s,4085 +rdflib/plugins/serializers/rdfxml.py,sha256=Mw-ORiqV0lhDZcUtT1hl1yH4o8YeIEBNKdn2G5urP7g,15774 +rdflib/plugins/serializers/trig.py,sha256=Kd3P-F3Il0tgeCj9wVE8x4VCsl8i9pdT2j_HY9TPFPM,4020 +rdflib/plugins/serializers/trix.py,sha256=khaCdnyKa3RsU7PCp9MRdordYA_8NI4Q7Ivf0Wvy7aw,3467 +rdflib/plugins/serializers/turtle.py,sha256=bcUVHyxb26bLQRVdSiduqQiAPR6b_460aGL_126TFiw,17928 +rdflib/plugins/serializers/xmlwriter.py,sha256=LNgcMCiBrbGWtG60xBCeQ-ON3er90PCrp-lUcAtAv7U,4340 +rdflib/plugins/shared/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +rdflib/plugins/shared/__pycache__/__init__.cpython-312.pyc,, +rdflib/plugins/shared/jsonld/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +rdflib/plugins/shared/jsonld/__pycache__/__init__.cpython-312.pyc,, +rdflib/plugins/shared/jsonld/__pycache__/context.cpython-312.pyc,, +rdflib/plugins/shared/jsonld/__pycache__/errors.cpython-312.pyc,, +rdflib/plugins/shared/jsonld/__pycache__/keys.cpython-312.pyc,, +rdflib/plugins/shared/jsonld/__pycache__/util.cpython-312.pyc,, +rdflib/plugins/shared/jsonld/context.py,sha256=8axbnIItzsEYFJu6GQ_lqj5Nu4Uz2h9UpT8dAQHzewo,23112 +rdflib/plugins/shared/jsonld/errors.py,sha256=QGRCaFanGyYmXrw2LNTTYBYklvz_bUG5VyysZFyYxY4,435 +rdflib/plugins/shared/jsonld/keys.py,sha256=SHKyniVqNBoV6MtUKmk_ltE2JXoFUbwpi7vtW8tLGrY,534 +rdflib/plugins/shared/jsonld/util.py,sha256=JkYhNAhUTtSkkwkZ49s6y-vemGFHO1Di7-HnK0SSgYo,12852 +rdflib/plugins/sparql/__init__.py,sha256=r8JLSHs8JnDZD4UvJOOTO-UFsrDRKg9WIzj40HNfvFM,1389 +rdflib/plugins/sparql/__pycache__/__init__.cpython-312.pyc,, +rdflib/plugins/sparql/__pycache__/aggregates.cpython-312.pyc,, +rdflib/plugins/sparql/__pycache__/algebra.cpython-312.pyc,, +rdflib/plugins/sparql/__pycache__/datatypes.cpython-312.pyc,, +rdflib/plugins/sparql/__pycache__/evaluate.cpython-312.pyc,, +rdflib/plugins/sparql/__pycache__/evalutils.cpython-312.pyc,, +rdflib/plugins/sparql/__pycache__/operators.cpython-312.pyc,, +rdflib/plugins/sparql/__pycache__/parser.cpython-312.pyc,, +rdflib/plugins/sparql/__pycache__/parserutils.cpython-312.pyc,, +rdflib/plugins/sparql/__pycache__/processor.cpython-312.pyc,, +rdflib/plugins/sparql/__pycache__/pyparsing_compat.cpython-312.pyc,, +rdflib/plugins/sparql/__pycache__/sparql.cpython-312.pyc,, +rdflib/plugins/sparql/__pycache__/update.cpython-312.pyc,, +rdflib/plugins/sparql/aggregates.py,sha256=rmSkZPnikO7dBMkjkWs4g2S_eFjGBdbhkdpIpFWEqyk,10681 +rdflib/plugins/sparql/algebra.py,sha256=IkQcSOYrIsQOwXof-vU2C3sIz7lxz-itWaWZ6HZtgbM,60938 +rdflib/plugins/sparql/datatypes.py,sha256=E8Oo4eIkl1d6rg6wjzjok0ZDeQECygU3bTxEsIz8vHI,2547 +rdflib/plugins/sparql/evaluate.py,sha256=mRlE91Y5h3PE3fDaC_WjwihfKmcUDJl2qKgGul2EAr4,21870 +rdflib/plugins/sparql/evalutils.py,sha256=HUFnd5GJ6_OCV-zI4gidCnHfZHCxD3zN6MtRdr01nQk,4908 +rdflib/plugins/sparql/operators.py,sha256=NJ02hZ7D3KO1bjPUN4bQNKM_PBoboe73GhO_laCAlDc,36752 +rdflib/plugins/sparql/parser.py,sha256=m_8FAUZfyQ-y2nRhs15viK1yQnKoj9uJtDlF65WMn98,51890 +rdflib/plugins/sparql/parserutils.py,sha256=HWuRm9n3bTDfJ5tdxd2T6zMFW46oAazmWs8YK3iHs9k,9233 +rdflib/plugins/sparql/processor.py,sha256=9vV4Z4LI1cBRjhwlZLqbREaQGJxTnChqIcSNQ3_vZ-g,4963 +rdflib/plugins/sparql/pyparsing_compat.py,sha256=ycGo4UyC1IjFud0WVlv_LkGSEY9iKj6RJvJvA05fuNY,3135 +rdflib/plugins/sparql/results/__init__.py,sha256=vS-p5U2ciXs22N4AqZAdSMCDCqIZGK6gKp_QmdIGVbI,670 +rdflib/plugins/sparql/results/__pycache__/__init__.cpython-312.pyc,, +rdflib/plugins/sparql/results/__pycache__/csvresults.cpython-312.pyc,, +rdflib/plugins/sparql/results/__pycache__/graph.cpython-312.pyc,, +rdflib/plugins/sparql/results/__pycache__/jsonresults.cpython-312.pyc,, +rdflib/plugins/sparql/results/__pycache__/rdfresults.cpython-312.pyc,, +rdflib/plugins/sparql/results/__pycache__/tsvresults.cpython-312.pyc,, +rdflib/plugins/sparql/results/__pycache__/txtresults.cpython-312.pyc,, +rdflib/plugins/sparql/results/__pycache__/xmlresults.cpython-312.pyc,, +rdflib/plugins/sparql/results/csvresults.py,sha256=ocSdkclkeDpP6bdO-5i4jWSXpEU0ZEbvSda8Gu9LRpU,3819 +rdflib/plugins/sparql/results/graph.py,sha256=6slf96keAyM3w0stGN9jdJQl2xnPnYSrOv5AcqTX9QQ,530 +rdflib/plugins/sparql/results/jsonresults.py,sha256=lYQLej_K1CWy3SjYqbh3Pq2rw_c2m2HFdggz1--Hp5E,5670 +rdflib/plugins/sparql/results/rdfresults.py,sha256=0nGwPcdkyhLXTQGdNdFSO7CWEQJi8nWjrxfVmBO3SFQ,2780 +rdflib/plugins/sparql/results/tsvresults.py,sha256=3PGyMKdYEG_it6-pwr4-qKiWu5pQpuP7K6XDKV8BfWM,3513 +rdflib/plugins/sparql/results/txtresults.py,sha256=wU3nVevDaRpVnXF7n2U5nvaqnRvk1bOQ46ZufcVOvZ0,3136 +rdflib/plugins/sparql/results/xmlresults.py,sha256=GkeefD1WuX6QCO7IuGBVF9Els2UFUVQKZavmEngJUW4,12337 +rdflib/plugins/sparql/sparql.py,sha256=k4sTpFPPhfQrVZu_MDwG2XEIAfvDnfy4f_efuHsVpV8,15855 +rdflib/plugins/sparql/update.py,sha256=fun4HiQcVRSL1KerRSeRz3V0nIgnMZV90cTciru8X8E,11776 +rdflib/plugins/stores/__init__.py,sha256=hsUmdKrMt9-eRJ6R_1SXW9My7KX3Q7GtDtwNbsiuFiM,259 +rdflib/plugins/stores/__pycache__/__init__.cpython-312.pyc,, +rdflib/plugins/stores/__pycache__/auditable.cpython-312.pyc,, +rdflib/plugins/stores/__pycache__/berkeleydb.cpython-312.pyc,, +rdflib/plugins/stores/__pycache__/concurrent.cpython-312.pyc,, +rdflib/plugins/stores/__pycache__/memory.cpython-312.pyc,, +rdflib/plugins/stores/__pycache__/rdf4j.cpython-312.pyc,, +rdflib/plugins/stores/__pycache__/regexmatching.cpython-312.pyc,, +rdflib/plugins/stores/__pycache__/sparqlconnector.cpython-312.pyc,, +rdflib/plugins/stores/__pycache__/sparqlstore.cpython-312.pyc,, +rdflib/plugins/stores/auditable.py,sha256=HhTlPMSZzbkV9whMhGDGxx90FX2uB7ldSdYTAM1NqBE,8000 +rdflib/plugins/stores/berkeleydb.py,sha256=B-a3VuZCje3CK04DNwPQSZApBK2hFYdq23hh6BR0b_A,30131 +rdflib/plugins/stores/concurrent.py,sha256=SiKvbLb_3SHQkiZcubhgEP2TNhgIMIWvCe9nNZsyhSE,2779 +rdflib/plugins/stores/memory.py,sha256=pfCAhEfzzRkyp6gBHf6n6Mj-qzXjIrVQQdrVmPUUJsI,30062 +rdflib/plugins/stores/rdf4j.py,sha256=FyQ-_9mWWoTX0iX2fsWMTqAZBmZ63wp9M84QylQsLL0,7479 +rdflib/plugins/stores/regexmatching.py,sha256=4nMbcJN7ayFdll6VhSUmCAWIwMBHBOgU_Yt8LTvQ2Ao,6490 +rdflib/plugins/stores/sparqlconnector.py,sha256=aGVCnCKL7FmDGJGIczrFT85eOAF7kPDkdkoU7W4YLmw,7194 +rdflib/plugins/stores/sparqlstore.py,sha256=ugRgsSlyA-Pi8f-0egWALBnbgAnPQK5b9CbldBHrss4,38904 +rdflib/py.typed,sha256=KT9WNyn4878ZisihNjjF3Bm2qu8R9s2F5irJrg8vxhQ,66 +rdflib/query.py,sha256=RCPRHhCkPffuj8sH08CRjv1UzVNW5_GAjI88W5j6nV8,15526 +rdflib/resource.py,sha256=GQF78yhhZrMVBVjutPnWHfWxUJiOEJ3BSy_b1yaThQI,13666 +rdflib/serializer.py,sha256=EMOYN86Szf9v56-XRW2FdrDWYbIGQiCvxC3cjSUBk50,1924 +rdflib/store.py,sha256=JVfZ4HI_h_r_oOJsdIviau9zqyRNRoFaW0pFAC8as0Y,16089 +rdflib/term.py,sha256=VkKA6XxOZLW3BL0f_5brw3Tr0tzC3xNM2mJFKj-Dwds,91610 +rdflib/tools/__init__.py,sha256=YzY7Eyz4zw8Ib5fl5bv4bQXzbAbsVxa2LrybTtJDYw0,58 +rdflib/tools/__pycache__/__init__.cpython-312.pyc,, +rdflib/tools/__pycache__/chunk_serializer.cpython-312.pyc,, +rdflib/tools/__pycache__/csv2rdf.cpython-312.pyc,, +rdflib/tools/__pycache__/defined_namespace_creator.cpython-312.pyc,, +rdflib/tools/__pycache__/graphisomorphism.cpython-312.pyc,, +rdflib/tools/__pycache__/rdf2dot.cpython-312.pyc,, +rdflib/tools/__pycache__/rdfpipe.cpython-312.pyc,, +rdflib/tools/__pycache__/rdfs2dot.cpython-312.pyc,, +rdflib/tools/__pycache__/sparqlquery.cpython-312.pyc,, +rdflib/tools/chunk_serializer.py,sha256=mVt_7yFeiHZRUTc2SQpFH2nitCi3dVNc2TrJrTO2Zog,4776 +rdflib/tools/csv2rdf.py,sha256=e30MHo7yy_Owg28iQ_0T6PjPbGpIc7q1QJPq_gg2z8k,16693 +rdflib/tools/defined_namespace_creator.py,sha256=0Dns50_gRl7tO7rL6jN2USYAADvjLWFkQlTI8MZfSkw,6719 +rdflib/tools/graphisomorphism.py,sha256=8gZxbH5vKhpZ6vIVY8ohJ8SoBRJOMZhQVDkhKMr2ZuA,3411 +rdflib/tools/rdf2dot.py,sha256=qOwEJ3ZbS__LirNHHGbqdPc6JfRTcs9CjGhTB4dXpRU,4982 +rdflib/tools/rdfpipe.py,sha256=14YoqF3kEKpOUb-xADKFGKr3r_YS_K0m2d_ICfwpjq4,5521 +rdflib/tools/rdfs2dot.py,sha256=NXEomJ7qNAJwUZV_rZ_sPQYJDTSR0fRVxM8JPRH-48A,3771 +rdflib/tools/sparqlquery.py,sha256=2IFveCAqWTdZC-Z-vCMC8rOrPpF0lDjA9uiAlcaQfh0,11401 +rdflib/util.py,sha256=-8Q5Q_CeXr4zhk32hL5w5vPrsXlbBWDHNF6mefxwlRA,18246 +rdflib/void.py,sha256=65gVWFXGhX3KMkAZ-njCelGB7kWGkTz2Dnbvv1vhslc,4635 +rdflib/xsd_datetime.py,sha256=iPX-FkZnIfcmGOmBABoz0xCOV0rDMBYG2jO8r4-oBVU,23387 diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rdflib-7.6.0.dist-info/WHEEL b/TTS/Kokoro/.venv/Lib/site-packages/rdflib-7.6.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..8b9b3a1bf3a91ed02f801f5487f2988a9aa4c454 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rdflib-7.6.0.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: poetry-core 1.9.1 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rdflib-7.6.0.dist-info/entry_points.txt b/TTS/Kokoro/.venv/Lib/site-packages/rdflib-7.6.0.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..e7810f179320de5890c961b1c5ec24225c8b2e68 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rdflib-7.6.0.dist-info/entry_points.txt @@ -0,0 +1,8 @@ +[console_scripts] +csv2rdf=rdflib.tools.csv2rdf:main +rdf2dot=rdflib.tools.rdf2dot:main +rdfgraphisomorphism=rdflib.tools.graphisomorphism:main +rdfpipe=rdflib.tools.rdfpipe:main +rdfs2dot=rdflib.tools.rdfs2dot:main +sparqlquery=rdflib.tools.sparqlquery:main + diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rdflib/__init__.py b/TTS/Kokoro/.venv/Lib/site-packages/rdflib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..041f2434616a3bc0061cd5a9ca20eef70ce7daec --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rdflib/__init__.py @@ -0,0 +1,206 @@ +"""A pure Python package providing the core RDF constructs. + +The packages is intended to provide the core RDF types and interfaces +for working with RDF. The package defines a plugin interface for +parsers, stores, and serializers that other packages can use to +implement parsers, stores, and serializers that will plug into the +rdflib package. + +The primary interface `rdflib` exposes to work with RDF is +[`rdflib.graph.Graph`][rdflib.graph.Graph]. + +A tiny example: + +```python +>>> from rdflib import Graph, URIRef, Literal + +>>> g = Graph() +>>> result = g.parse("http://www.w3.org/2000/10/swap/test/meet/blue.rdf") + +>>> print("graph has %s statements." % len(g)) +graph has 4 statements. +>>> +>>> for s, p, o in g: +... if (s, p, o) not in g: +... raise Exception("It better be!") + +>>> s = g.serialize(format='nt') +>>> +>>> sorted(g) == [ +... (URIRef("http://meetings.example.com/cal#m1"), +... URIRef("http://www.example.org/meeting_organization#homePage"), +... URIRef("http://meetings.example.com/m1/hp")), +... (URIRef("http://www.example.org/people#fred"), +... URIRef("http://www.example.org/meeting_organization#attending"), +... URIRef("http://meetings.example.com/cal#m1")), +... (URIRef("http://www.example.org/people#fred"), +... URIRef("http://www.example.org/personal_details#GivenName"), +... Literal("Fred")), +... (URIRef("http://www.example.org/people#fred"), +... URIRef("http://www.example.org/personal_details#hasEmail"), +... URIRef("mailto:fred@example.com")) +... ] +True + +``` +""" + +import logging +import sys +from importlib import metadata + +_DISTRIBUTION_METADATA = metadata.metadata("rdflib") + +__docformat__ = "restructuredtext en" + +__version__: str = _DISTRIBUTION_METADATA["Version"] +__date__ = "2026-02-13" + +__all__ = [ + "URIRef", + "BNode", + "IdentifiedNode", + "Literal", + "Node", + "Variable", + "Namespace", + "Dataset", + "Graph", + "ConjunctiveGraph", + "BRICK", + "CSVW", + "DC", + "DCAT", + "DCMITYPE", + "DCTERMS", + "DOAP", + "FOAF", + "ODRL2", + "ORG", + "OWL", + "PROF", + "PROV", + "QB", + "RDF", + "RDFS", + "SDO", + "SH", + "SKOS", + "SOSA", + "SSN", + "TIME", + "VANN", + "VOID", + "XMLNS", + "XSD", + "util", + "plugin", + "query", + "NORMALIZE_LITERALS", +] + +logger = logging.getLogger(__name__) + +try: + import __main__ + + if ( + not hasattr(__main__, "__file__") + and sys.stdout is not None + and hasattr(sys.stderr, "isatty") + and sys.stderr.isatty() + ): + # show log messages in interactive mode + logger.setLevel(logging.INFO) + logger.addHandler(logging.StreamHandler()) + del __main__ +except ImportError: + # Main already imported from elsewhere + import warnings + + warnings.warn("__main__ already imported", ImportWarning) + del warnings + +del sys + + +NORMALIZE_LITERALS = True +""" +If True - Literals lexical forms are normalized when created. +I.e. the lexical forms is parsed according to data-type, then the +stored lexical form is the re-serialized value that was parsed. + +Illegal values for a datatype are simply kept. The normalized keyword +for Literal.__new__ can override this. + +For example: + +```python +>>> from rdflib import Literal,XSD +>>> Literal("01", datatype=XSD.int) +rdflib.term.Literal("1", datatype=rdflib.term.URIRef("http://www.w3.org/2001/XMLSchema#integer")) + +``` + +This flag may be changed at any time, but will only affect literals +created after that time, previously created literals will remain +(un)normalized. + +""" + + +DAWG_LITERAL_COLLATION = False +"""DAWG_LITERAL_COLLATION determines how literals are ordered or compared +to each other. + +In SPARQL, applying the >,<,>=,<= operators to literals of +incompatible data-types is an error, i.e: + +`Literal(2)>Literal('cake')` is neither true nor false, but an error. + +This is a problem in PY3, where lists of Literals of incompatible +types can no longer be sorted. + +Setting this flag to True gives you strict DAWG/SPARQL compliance, +setting it to False will order Literals with incompatible datatypes by +datatype URI + +In particular, this determines how the rich comparison operators for +Literal work, eq, `__neq__`, `__lt__`, etc. +""" + + +from rdflib.graph import ConjunctiveGraph, Dataset, Graph +from rdflib.namespace import ( + BRICK, + CSVW, + DC, + DCAT, + DCMITYPE, + DCTERMS, + DOAP, + FOAF, + ODRL2, + ORG, + OWL, + PROF, + PROV, + QB, + RDF, + RDFS, + SDO, + SH, + SKOS, + SOSA, + SSN, + TIME, + VANN, + VOID, + XMLNS, + XSD, + Namespace, +) +from rdflib.term import BNode, IdentifiedNode, Literal, Node, URIRef, Variable + +from rdflib import plugin, query, util # isort:skip +from rdflib.container import * # isort:skip # noqa: F403 diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rdflib/_networking.py b/TTS/Kokoro/.venv/Lib/site-packages/rdflib/_networking.py new file mode 100644 index 0000000000000000000000000000000000000000..2788fe0aeb3f5d44b2038a8c7dd289c823c440b3 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rdflib/_networking.py @@ -0,0 +1,123 @@ +from __future__ import annotations + +import string +import sys +from typing import Dict +from urllib.error import HTTPError +from urllib.parse import quote as urlquote +from urllib.parse import urljoin, urlsplit +from urllib.request import HTTPRedirectHandler, Request, urlopen +from urllib.response import addinfourl + + +def _make_redirect_request(request: Request, http_error: HTTPError) -> Request: + """Create a new request object for a redirected request. + + The logic is based on [HTTPRedirectHandler](https://github.com/python/cpython/blob/b58bc8c2a9a316891a5ea1a0487aebfc86c2793a/Lib/urllib/request.py#L641-L751) from urllib.request. + + Args: + request: The original request that resulted in the redirect. + http_error: The response to the original request that indicates a + redirect should occur and contains the new location. + + Returns: + A new request object to the location indicated by the response. + + Raises: + HTTPError: the supplied `http_error` if the redirect request + cannot be created. + ValueError: If the response code is None. + ValueError: If the response does not contain a `Location` header + or the `Location` header is not a string. + HTTPError: If the scheme of the new location is not `http`, + `https`, or `ftp`. + HTTPError: If there are too many redirects or a redirect loop. + """ + new_url = http_error.headers.get("Location") + if new_url is None: + raise http_error + if not isinstance(new_url, str): + raise ValueError(f"Location header {new_url!r} is not a string") + + new_url_parts = urlsplit(new_url) + + # For security reasons don't allow redirection to anything other than http, + # https or ftp. + if new_url_parts.scheme not in ("http", "https", "ftp", ""): + raise HTTPError( + new_url, + http_error.code, + f"{http_error.reason} - Redirection to url {new_url!r} is not allowed", + http_error.headers, + http_error.fp, + ) + + # http.client.parse_headers() decodes as ISO-8859-1. Recover the original + # bytes and percent-encode non-ASCII bytes, and any special characters such + # as the space. + new_url = urlquote(new_url, encoding="iso-8859-1", safe=string.punctuation) + new_url = urljoin(request.full_url, new_url) + + # XXX Probably want to forget about the state of the current + # request, although that might interact poorly with other + # handlers that also use handler-specific request attributes + content_headers = ("content-length", "content-type") + newheaders = { + k: v for k, v in request.headers.items() if k.lower() not in content_headers + } + new_request = Request( + new_url, + headers=newheaders, + origin_req_host=request.origin_req_host, + unverifiable=True, + ) + + visited: Dict[str, int] + if hasattr(request, "redirect_dict"): + visited = request.redirect_dict + if ( + visited.get(new_url, 0) >= HTTPRedirectHandler.max_repeats + or len(visited) >= HTTPRedirectHandler.max_redirections + ): + raise HTTPError( + request.full_url, + http_error.code, + HTTPRedirectHandler.inf_msg + http_error.reason, + http_error.headers, + http_error.fp, + ) + else: + visited = {} + setattr(request, "redirect_dict", visited) + + setattr(new_request, "redirect_dict", visited) + visited[new_url] = visited.get(new_url, 0) + 1 + return new_request + + +def _urlopen(request: Request) -> addinfourl: + """This is a shim for `urlopen` that handles HTTP redirects with status code + 308 (Permanent Redirect). + + This function should be removed once all supported versions of Python + handles the 308 HTTP status code. + + Args: + request: The request to open. + + Returns: + The response to the request. + """ + try: + return urlopen(request) + except HTTPError as error: + if error.code == 308 and sys.version_info < (3, 11): + # HTTP response code 308 (Permanent Redirect) is not supported by python + # versions older than 3.11. See and + # for more details. + # This custom error handling should be removed once all supported + # versions of Python handles 308. + new_request = _make_redirect_request(request, error) + return _urlopen(new_request) + else: + raise diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rdflib/_type_checking.py b/TTS/Kokoro/.venv/Lib/site-packages/rdflib/_type_checking.py new file mode 100644 index 0000000000000000000000000000000000000000..2ead0eabd775bdda062413d167a56ef77e5015d8 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rdflib/_type_checking.py @@ -0,0 +1,26 @@ +""" +This module contains type aliases that should only be used when type checking +as it would otherwise introduce a runtime dependency on `typing_extensions` for +older python versions which is not desirable. + +This was made mainly to accommodate `sphinx-autodoc-typehints` which cannot +recognize type aliases from imported files if the type aliases are defined +inside `if TYPE_CHECKING:`. So instead of placing the type aliases in normal +modules inside `TYPE_CHECKING` guards they are in this file which should only +be imported inside `TYPE_CHECKING` guards. + +!!! info "Internal use only" + Things inside this module are not for use outside of RDFLib + and this module is not part the the RDFLib public API. +""" + +__all__ = [ + "_NamespaceSetString", + "_MulPathMod", +] + + +from typing import Literal as PyLiteral + +_NamespaceSetString = PyLiteral["core", "rdflib", "none"] +_MulPathMod = PyLiteral["*", "+", "?"] diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rdflib/collection.py b/TTS/Kokoro/.venv/Lib/site-packages/rdflib/collection.py new file mode 100644 index 0000000000000000000000000000000000000000..dd63c4ed21f3cf90555cce5e8049995a4c783e05 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rdflib/collection.py @@ -0,0 +1,282 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Iterable, Iterator, List, Optional + +from rdflib.namespace import RDF +from rdflib.term import BNode, Node + +if TYPE_CHECKING: + from rdflib.graph import Graph + +__all__ = ["Collection"] + + +class Collection: + """See "Emulating container types": + + ```python + >>> from rdflib.term import Literal + >>> from rdflib.graph import Graph + >>> from pprint import pprint + >>> listname = BNode() + >>> g = Graph('Memory') + >>> listItem1 = BNode() + >>> listItem2 = BNode() + >>> g.add((listname, RDF.first, Literal(1))) # doctest: +ELLIPSIS + )> + >>> g.add((listname, RDF.rest, listItem1)) # doctest: +ELLIPSIS + )> + >>> g.add((listItem1, RDF.first, Literal(2))) # doctest: +ELLIPSIS + )> + >>> g.add((listItem1, RDF.rest, listItem2)) # doctest: +ELLIPSIS + )> + >>> g.add((listItem2, RDF.rest, RDF.nil)) # doctest: +ELLIPSIS + )> + >>> g.add((listItem2, RDF.first, Literal(3))) # doctest: +ELLIPSIS + )> + >>> c = Collection(g,listname) + >>> pprint([term.n3() for term in c]) + ['"1"^^', + '"2"^^', + '"3"^^'] + >>> Literal(1) in c + True + >>> len(c) + 3 + >>> c._get_container(1) == listItem1 + True + >>> c.index(Literal(2)) == 1 + True + + ``` + + The collection is immutable if `uri` is the empty list (`http://www.w3.org/1999/02/22-rdf-syntax-ns#nil`). + """ + + def __init__(self, graph: Graph, uri: Node, seq: List[Node] = []): + self.graph = graph + self.uri = uri or BNode() + if seq: + self += seq + + def n3(self) -> str: + """ + ```python + >>> from rdflib.term import Literal + >>> from rdflib.graph import Graph + >>> listname = BNode() + >>> g = Graph('Memory') + >>> listItem1 = BNode() + >>> listItem2 = BNode() + >>> g.add((listname, RDF.first, Literal(1))) # doctest: +ELLIPSIS + )> + >>> g.add((listname, RDF.rest, listItem1)) # doctest: +ELLIPSIS + )> + >>> g.add((listItem1, RDF.first, Literal(2))) # doctest: +ELLIPSIS + )> + >>> g.add((listItem1, RDF.rest, listItem2)) # doctest: +ELLIPSIS + )> + >>> g.add((listItem2, RDF.rest, RDF.nil)) # doctest: +ELLIPSIS + )> + >>> g.add((listItem2, RDF.first, Literal(3))) # doctest: +ELLIPSIS + )> + >>> c = Collection(g, listname) + >>> print(c.n3()) #doctest: +NORMALIZE_WHITESPACE + ( "1"^^ + "2"^^ + "3"^^ ) + + ``` + """ + return "( %s )" % (" ".join([i.n3() for i in self])) + + def _get_container(self, index: int) -> Optional[Node]: + """Gets the first, rest holding node at index.""" + assert isinstance(index, int) + graph = self.graph + container: Optional[Node] = self.uri + i = 0 + while i < index: + i += 1 + container = graph.value(container, RDF.rest) + if container is None: + break + return container + + def __len__(self) -> int: + """length of items in collection.""" + return len(list(self.graph.items(self.uri))) + + def index(self, item: Node) -> int: + """ + Returns the 0-based numerical index of the item in the list + """ + listname = self.uri + index = 0 + while True: + if (listname, RDF.first, item) in self.graph: + return index + else: + newlink = list(self.graph.objects(listname, RDF.rest)) + index += 1 + if newlink == [RDF.nil]: + raise ValueError("%s is not in %s" % (item, self.uri)) + elif not newlink: + raise Exception("Malformed RDF Collection: %s" % self.uri) + else: + assert len(newlink) == 1, "Malformed RDF Collection: %s" % self.uri + listname = newlink[0] + + def __getitem__(self, key: int) -> Node: + """TODO""" + c = self._get_container(key) + if c: + v = self.graph.value(c, RDF.first) + if v: + return v + else: + raise KeyError(key) + else: + raise IndexError(key) + + def __setitem__(self, key: int, value: Node) -> None: + """TODO""" + c = self._get_container(key) + if c: + self.graph.set((c, RDF.first, value)) + else: + raise IndexError(key) + + def __delitem__(self, key: int) -> None: + """ + ```python + >>> from rdflib.namespace import RDF, RDFS + >>> from rdflib import Graph + >>> from pprint import pformat + >>> g = Graph() + >>> a = BNode('foo') + >>> b = BNode('bar') + >>> c = BNode('baz') + >>> g.add((a, RDF.first, RDF.type)) # doctest: +ELLIPSIS + )> + >>> g.add((a, RDF.rest, b)) # doctest: +ELLIPSIS + )> + >>> g.add((b, RDF.first, RDFS.label)) # doctest: +ELLIPSIS + )> + >>> g.add((b, RDF.rest, c)) # doctest: +ELLIPSIS + )> + >>> g.add((c, RDF.first, RDFS.comment)) # doctest: +ELLIPSIS + )> + >>> g.add((c, RDF.rest, RDF.nil)) # doctest: +ELLIPSIS + )> + >>> len(g) + 6 + >>> def listAncestry(node, graph): + ... for i in graph.subjects(RDF.rest, node): + ... yield i + >>> [str(node.n3()) + ... for node in g.transitiveClosure(listAncestry, RDF.nil)] + ['_:baz', '_:bar', '_:foo'] + >>> lst = Collection(g, a) + >>> len(lst) + 3 + >>> b == lst._get_container(1) + True + >>> c == lst._get_container(2) + True + >>> del lst[1] + >>> len(lst) + 2 + >>> len(g) + 4 + + ``` + """ + self[key] # to raise any potential key exceptions + graph = self.graph + current = self._get_container(key) + assert current + if len(self) == 1 and key > 0: + pass + elif key == len(self) - 1: + # the tail + priorlink = self._get_container(key - 1) + # type error: Argument 1 to "set" of "Graph" has incompatible type "Tuple[Optional[Node], URIRef, URIRef]"; expected "Tuple[Node, Node, Any]" + self.graph.set((priorlink, RDF.rest, RDF.nil)) # type: ignore[arg-type] + graph.remove((current, None, None)) + else: + next = self._get_container(key + 1) + prior = self._get_container(key - 1) + assert next and prior + graph.remove((current, None, None)) + graph.set((prior, RDF.rest, next)) + + def __iter__(self) -> Iterator[Node]: + """Iterator over items in Collections""" + return self.graph.items(self.uri) + + def _end(self) -> Node: + # find end of list + container = self.uri + while True: + rest = self.graph.value(container, RDF.rest) + if rest is None or rest == RDF.nil: + return container + else: + container = rest + + def append(self, item: Node) -> Collection: + """ + ```python + >>> from rdflib.term import Literal + >>> from rdflib.graph import Graph + >>> listname = BNode() + >>> g = Graph() + >>> c = Collection(g,listname,[Literal(1),Literal(2)]) + >>> links = [ + ... list(g.subjects(object=i, predicate=RDF.first))[0] for i in c] + >>> len([i for i in links if (i, RDF.rest, RDF.nil) in g]) + 1 + + ``` + """ + end = self._end() + if end == RDF.nil: + raise ValueError("Cannot append to empty list") + + if (end, RDF.first, None) in self.graph: + # append new node to the end of the linked list + node = BNode() + self.graph.set((end, RDF.rest, node)) + end = node + + self.graph.add((end, RDF.first, item)) + self.graph.add((end, RDF.rest, RDF.nil)) + return self + + def __iadd__(self, other: Iterable[Node]): + end = self._end() + if end == RDF.nil: + raise ValueError("Cannot append to empty list") + self.graph.remove((end, RDF.rest, None)) + + for item in other: + if (end, RDF.first, None) in self.graph: + nxt = BNode() + self.graph.add((end, RDF.rest, nxt)) + end = nxt + + self.graph.add((end, RDF.first, item)) + + self.graph.add((end, RDF.rest, RDF.nil)) + return self + + def clear(self): + container: Optional[Node] = self.uri + graph = self.graph + while container: + rest = graph.value(container, RDF.rest) + graph.remove((container, RDF.first, None)) + graph.remove((container, RDF.rest, None)) + container = rest + return self diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rdflib/compare.py b/TTS/Kokoro/.venv/Lib/site-packages/rdflib/compare.py new file mode 100644 index 0000000000000000000000000000000000000000..77d99d533bbadc0db7c29a2b2f3929d3e2ed6454 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rdflib/compare.py @@ -0,0 +1,647 @@ +""" +A collection of utilities for canonicalizing and inspecting graphs. + +Among other things, they solve of the problem of deterministic bnode +comparisons. + +Warning: the time to canonicalize bnodes may increase exponentially on +degenerate larger graphs. Use with care! + +Example of comparing two graphs: + +```python +>>> g1 = Graph().parse(format='n3', data=''' +... @prefix : . +... :rel +... , +... [ :label "Same" ], +... , +... [ :label "A" ] . +... ''') +>>> g2 = Graph().parse(format='n3', data=''' +... @prefix : . +... :rel +... , +... [ :label "Same" ], +... , +... [ :label "B" ] . +... ''') +>>> +>>> iso1 = to_isomorphic(g1) +>>> iso2 = to_isomorphic(g2) + +``` + +These are not isomorphic + +```python +>>> iso1 == iso2 +False + +``` + +Diff the two graphs: + +```python +>>> in_both, in_first, in_second = graph_diff(iso1, iso2) + +``` + +Present in both: + +```python +>>> def dump_nt_sorted(g): +... for l in sorted(g.serialize(format='nt').splitlines()): +... if l: print(l.decode('ascii')) +>>> dump_nt_sorted(in_both) #doctest: +SKIP + + . + + _:cbcaabaaba17fecbc304a64f8edee4335e . +_:cbcaabaaba17fecbc304a64f8edee4335e + "Same" . +``` + +Only in first: + +```python +>>> dump_nt_sorted(in_first) #doctest: +SKIP + + . + + _:cb124e4c6da0579f810c0ffe4eff485bd9 . +_:cb124e4c6da0579f810c0ffe4eff485bd9 + "A" . +``` + +Only in second: + +```python +>>> dump_nt_sorted(in_second) #doctest: +SKIP + + . + + _:cb558f30e21ddfc05ca53108348338ade8 . +_:cb558f30e21ddfc05ca53108348338ade8 + "B" . +``` +""" + +from __future__ import annotations + +# TODO: +# - Doesn't handle quads. +# - Add warning and/or safety mechanism before working on large graphs? +# - use this in existing Graph.isomorphic? + +__all__ = [ + "IsomorphicGraph", + "to_isomorphic", + "isomorphic", + "to_canonical_graph", + "graph_diff", + "similar", +] + +from collections import defaultdict +from datetime import datetime +from hashlib import sha256 +from typing import ( + TYPE_CHECKING, + Callable, + Dict, + Iterator, + List, + Optional, + Set, + Tuple, + Union, +) + +from rdflib.graph import ConjunctiveGraph, Graph, ReadOnlyGraphAggregate, _TripleType +from rdflib.term import BNode, IdentifiedNode, Node, URIRef + +if TYPE_CHECKING: + from _hashlib import HASH + + +def _total_seconds(td): + result = td.days * 24 * 60 * 60 + result += td.seconds + result += td.microseconds / 1000000.0 + return result + + +class _runtime: # noqa: N801 + def __init__(self, label): + self.label = label + + def __call__(self, f): + if self.label is None: + self.label = f.__name__ + "_runtime" + + def wrapped_f(*args, **kwargs): + start = datetime.now() + result = f(*args, **kwargs) + if "stats" in kwargs and kwargs["stats"] is not None: + stats = kwargs["stats"] + stats[self.label] = _total_seconds(datetime.now() - start) + return result + + return wrapped_f + + +class _call_count: # noqa: N801 + def __init__(self, label): + self.label = label + + def __call__(self, f): + if self.label is None: + self.label = f.__name__ + "_runtime" + + def wrapped_f(*args, **kwargs): + if "stats" in kwargs and kwargs["stats"] is not None: + stats = kwargs["stats"] + if self.label not in stats: + stats[self.label] = 0 + stats[self.label] += 1 + return f(*args, **kwargs) + + return wrapped_f + + +class IsomorphicGraph(ConjunctiveGraph): + """An implementation of the RGDA1 graph digest algorithm. + + An implementation of RGDA1 (publication below), + a combination of Sayers & Karp's graph digest algorithm using + sum and SHA-256 + and traces , an average case + polynomial time algorithm for graph canonicalization. + + McCusker, J. P. (2015). WebSig: A Digital Signature Framework for the Web. + Rensselaer Polytechnic Institute, Troy, NY. + http://gradworks.umi.com/3727015.pdf + """ + + def __init__(self, **kwargs): + super(IsomorphicGraph, self).__init__(**kwargs) + + def __eq__(self, other): + """Graph isomorphism testing.""" + if not isinstance(other, IsomorphicGraph): + return False + elif len(self) != len(other): + return False + return self.internal_hash() == other.internal_hash() + + def __ne__(self, other): + """Negative graph isomorphism testing.""" + return not self.__eq__(other) + + def __hash__(self): + return super(IsomorphicGraph, self).__hash__() + + def graph_digest(self, stats=None): + """Synonym for IsomorphicGraph.internal_hash.""" + return self.internal_hash(stats=stats) + + def internal_hash(self, stats=None): + """ + This is defined instead of `__hash__` to avoid a circular recursion + scenario with the Memory store for rdflib which requires a hash lookup + in order to return a generator of triples. + """ + return _TripleCanonicalizer(self).to_hash(stats=stats) + + +HashFunc = Callable[[str], int] +ColorItem = Tuple[Union[int, str], URIRef, Union[int, str]] +ColorItemTuple = Tuple[ColorItem, ...] +HashCache = Optional[Dict[ColorItemTuple, str]] +Stats = Dict[str, Union[int, str]] + + +class Color: + def __init__( + self, + nodes: List[IdentifiedNode], + hashfunc: HashFunc, + color: ColorItemTuple = (), + hash_cache: HashCache = None, + ): + if hash_cache is None: + hash_cache = {} + self._hash_cache = hash_cache + self.color = color + self.nodes = nodes + self.hashfunc = hashfunc + self._hash_color = None + + def __str__(self): + nodes, color = self.key() + return "Color %s (%s nodes)" % (color, nodes) + + def key(self): + return (len(self.nodes), self.hash_color()) + + def hash_color(self, color: Optional[Tuple[ColorItem, ...]] = None) -> str: + if color is None: + color = self.color + if color in self._hash_cache: + return self._hash_cache[color] + + def stringify(x): + if isinstance(x, Node): + return x.n3() + else: + return str(x) + + if isinstance(color, Node): + return stringify(color) + value = 0 + for triple in color: + value += self.hashfunc(" ".join([stringify(x) for x in triple])) + val: str = "%x" % value + self._hash_cache[color] = val + return val + + def distinguish(self, W: Color, graph: Graph): # noqa: N803 + colors: Dict[str, Color] = {} + for n in self.nodes: + new_color: Tuple[ColorItem, ...] = list(self.color) # type: ignore[assignment] + for node in W.nodes: + new_color += [ # type: ignore[operator] + (1, p, W.hash_color()) for s, p, o in graph.triples((n, None, node)) + ] + new_color += [ # type: ignore[operator] + (W.hash_color(), p, 3) for s, p, o in graph.triples((node, None, n)) + ] + new_color = tuple(new_color) + new_hash_color = self.hash_color(new_color) + + if new_hash_color not in colors: + c = Color([], self.hashfunc, new_color, hash_cache=self._hash_cache) + colors[new_hash_color] = c + colors[new_hash_color].nodes.append(n) + return colors.values() + + def discrete(self): + return len(self.nodes) == 1 + + def copy(self): + return Color( + self.nodes[:], self.hashfunc, self.color, hash_cache=self._hash_cache + ) + + +_HashT = Callable[[], "HASH"] + + +class _TripleCanonicalizer: + def __init__(self, graph: Graph, hashfunc: _HashT = sha256): + self.graph = graph + + def _hashfunc(s: str): + h = hashfunc() + h.update(str(s).encode("utf8")) + return int(h.hexdigest(), 16) + + self._hash_cache: HashCache = {} + self.hashfunc = _hashfunc + + def _discrete(self, coloring: List[Color]) -> bool: + return len([c for c in coloring if not c.discrete()]) == 0 + + def _initial_color(self) -> List[Color]: + """Finds an initial color for the graph. + + Finds an initial color of the graph by finding all blank nodes and + non-blank nodes that are adjacent. Nodes that are not adjacent to blank + nodes are not included, as they are a) already colored (by URI or literal) + and b) do not factor into the color of any blank node. + """ + bnodes: Set[BNode] = set() + others = set() + self._neighbors = defaultdict(set) + for s, p, o in self.graph: + nodes = set([s, p, o]) + b = set([x for x in nodes if isinstance(x, BNode)]) + if len(b) > 0: + others |= nodes - b + bnodes |= b + if isinstance(s, BNode): + self._neighbors[s].add(o) + if isinstance(o, BNode): + self._neighbors[o].add(s) + if isinstance(p, BNode): + self._neighbors[p].add(s) + self._neighbors[p].add(p) + if len(bnodes) > 0: + return [Color(list(bnodes), self.hashfunc, hash_cache=self._hash_cache)] + [ + # type error: List item 0 has incompatible type "Union[IdentifiedNode, Literal]"; expected "IdentifiedNode" + # type error: Argument 3 to "Color" has incompatible type "Union[IdentifiedNode, Literal]"; expected "Tuple[Tuple[Union[int, str], URIRef, Union[int, str]], ...]" + Color([x], self.hashfunc, x, hash_cache=self._hash_cache) # type: ignore[list-item, arg-type] + for x in others + ] + else: + return [] + + def _individuate(self, color, individual): + new_color = list(color.color) + new_color.append((len(color.nodes),)) + + color.nodes.remove(individual) + c = Color( + [individual], self.hashfunc, tuple(new_color), hash_cache=self._hash_cache + ) + return c + + def _get_candidates(self, coloring: List[Color]) -> Iterator[Tuple[Node, Color]]: + for c in [c for c in coloring if not c.discrete()]: + for node in c.nodes: + yield node, c + + def _refine(self, coloring: List[Color], sequence: List[Color]) -> List[Color]: + sequence = sorted(sequence, key=lambda x: x.key(), reverse=True) + coloring = coloring[:] + while len(sequence) > 0 and not self._discrete(coloring): + W = sequence.pop() # noqa: N806 + for c in coloring[:]: + if len(c.nodes) > 1 or isinstance(c.nodes[0], BNode): + colors = sorted( + c.distinguish(W, self.graph), + key=lambda x: x.key(), + reverse=True, + ) + coloring.remove(c) + coloring.extend(colors) + try: + si = sequence.index(c) + sequence = sequence[:si] + colors + sequence[si + 1 :] + except ValueError: + sequence = colors[1:] + sequence + combined_colors: List[Color] = [] + combined_color_map: Dict[str, Color] = dict() + for color in coloring: + color_hash = color.hash_color() + # This is a hash collision, and be combined into a single color for individuation. + if color_hash in combined_color_map: + combined_color_map[color_hash].nodes.extend(color.nodes) + else: + combined_colors.append(color) + combined_color_map[color_hash] = color + return combined_colors + + @_runtime("to_hash_runtime") + def to_hash(self, stats: Optional[Stats] = None): + result = 0 + for triple in self.canonical_triples(stats=stats): + result += self.hashfunc(" ".join([x.n3() for x in triple])) + if stats is not None: + stats["graph_digest"] = "%x" % result + return result + + def _experimental_path(self, coloring: List[Color]) -> List[Color]: + coloring = [c.copy() for c in coloring] + while not self._discrete(coloring): + color = [x for x in coloring if not x.discrete()][0] + node = color.nodes[0] + new_color = self._individuate(color, node) + coloring.append(new_color) + coloring = self._refine(coloring, [new_color]) + return coloring + + def _create_generator( + self, + colorings: List[List[Color]], + groupings: Optional[Dict[Node, Set[Node]]] = None, + ) -> Dict[Node, Set[Node]]: + if not groupings: + groupings = defaultdict(set) + for group in zip(*colorings): + g = set([c.nodes[0] for c in group]) + for n in group: + g |= groupings[n] + for n in g: + groupings[n] = g + return groupings + + @_call_count("individuations") + def _traces( + self, + coloring: List[Color], + stats: Optional[Stats] = None, + depth: List[int] = [0], + ) -> List[Color]: + if stats is not None and "prunings" not in stats: + stats["prunings"] = 0 + depth[0] += 1 + candidates = self._get_candidates(coloring) + best: List[List[Color]] = [] + best_score = None + best_experimental_score = None + last_coloring = None + generator: Dict[Node, Set[Node]] = defaultdict(set) + visited: Set[Node] = set() + for candidate, color in candidates: + if candidate in generator: + v = generator[candidate] & visited + if len(v) > 0: + visited.add(candidate) + continue + visited.add(candidate) + coloring_copy: List[Color] = [] + color_copy = None + for c in coloring: + c_copy = c.copy() + coloring_copy.append(c_copy) + if c == color: + color_copy = c_copy + new_color = self._individuate(color_copy, candidate) + coloring_copy.append(new_color) + refined_coloring = self._refine(coloring_copy, [new_color]) + color_score = tuple([c.key() for c in refined_coloring]) + experimental = self._experimental_path(coloring_copy) + experimental_score = set([c.key() for c in experimental]) + if last_coloring: + # type error: Statement is unreachable + generator = self._create_generator( # type: ignore[unreachable] + [last_coloring, experimental], generator + ) + last_coloring = experimental + if best_score is None or best_score < color_score: # type: ignore[unreachable] + best = [refined_coloring] + best_score = color_score + best_experimental_score = experimental_score + elif best_score > color_score: # type: ignore[unreachable] + # prune this branch. + if stats is not None and isinstance(stats["prunings"], int): + stats["prunings"] += 1 + elif experimental_score != best_experimental_score: + best.append(refined_coloring) + else: + # prune this branch. + if stats is not None and isinstance(stats["prunings"], int): + stats["prunings"] += 1 + discrete: List[List[Color]] = [x for x in best if self._discrete(x)] + if len(discrete) == 0: + best_score = None + best_depth = None + for coloring in best: + d = [depth[0]] + new_color = self._traces(coloring, stats=stats, depth=d) + color_score = tuple([c.key() for c in refined_coloring]) + if best_score is None or color_score > best_score: # type: ignore[unreachable] + discrete = [new_color] + best_score = color_score + best_depth = d[0] + depth[0] = best_depth # type: ignore[assignment] + return discrete[0] + + def canonical_triples(self, stats: Optional[Stats] = None): + if stats is not None: + start_coloring = datetime.now() + coloring = self._initial_color() + if stats is not None: + stats["triple_count"] = len(self.graph) + stats["adjacent_nodes"] = max(0, len(coloring) - 1) + coloring = self._refine(coloring, coloring[:]) + if stats is not None: + stats["initial_coloring_runtime"] = _total_seconds( + datetime.now() - start_coloring + ) + stats["initial_color_count"] = len(coloring) + + if not self._discrete(coloring): + depth = [0] + coloring = self._traces(coloring, stats=stats, depth=depth) + if stats is not None: + stats["tree_depth"] = depth[0] + elif stats is not None: + stats["individuations"] = 0 + stats["tree_depth"] = 0 + if stats is not None: + stats["color_count"] = len(coloring) + + bnode_labels: Dict[Node, str] = dict( + [(c.nodes[0], c.hash_color()) for c in coloring] + ) + if stats is not None: + stats["canonicalize_triples_runtime"] = _total_seconds( + datetime.now() - start_coloring + ) + for triple in self.graph: + result = tuple(self._canonicalize_bnodes(triple, bnode_labels)) + yield result + + def _canonicalize_bnodes( + self, + triple: _TripleType, + labels: Dict[Node, str], + ): + for term in triple: + if isinstance(term, BNode): + yield BNode(value="cb%s" % labels[term]) + else: + yield term + + +def to_isomorphic(graph: Graph) -> IsomorphicGraph: + if isinstance(graph, IsomorphicGraph): + return graph + result = IsomorphicGraph() + if hasattr(graph, "identifier"): + result = IsomorphicGraph(identifier=graph.identifier) + result += graph + return result + + +def isomorphic(graph1: Graph, graph2: Graph) -> bool: + """Compare graph for equality. + + Uses an algorithm to compute unique hashes which takes bnodes into account. + + Example: + ```python + >>> g1 = Graph().parse(format='n3', data=''' + ... @prefix : . + ... :rel . + ... :rel . + ... :rel [ :label "A bnode." ] . + ... ''') + >>> g2 = Graph().parse(format='n3', data=''' + ... @prefix ns: . + ... ns:rel [ ns:label "A bnode." ] . + ... ns:rel , + ... . + ... ''') + >>> isomorphic(g1, g2) + True + >>> g3 = Graph().parse(format='n3', data=''' + ... @prefix : . + ... :rel . + ... :rel . + ... :rel . + ... ''') + >>> isomorphic(g1, g3) + False + + ``` + """ + gd1 = _TripleCanonicalizer(graph1).to_hash() + gd2 = _TripleCanonicalizer(graph2).to_hash() + return gd1 == gd2 + + +def to_canonical_graph( + g1: Graph, stats: Optional[Stats] = None +) -> ReadOnlyGraphAggregate: + """Creates a canonical, read-only graph. + + Creates a canonical, read-only graph where all bnode id:s are based on + deterministical SHA-256 checksums, correlated with the graph contents. + """ + graph = Graph() + graph += _TripleCanonicalizer(g1).canonical_triples(stats=stats) + return ReadOnlyGraphAggregate([graph]) + + +def graph_diff(g1: Graph, g2: Graph) -> Tuple[Graph, Graph, Graph]: + """Returns three sets of triples: "in both", "in first" and "in second".""" + # bnodes have deterministic values in canonical graphs: + cg1 = to_canonical_graph(g1) + cg2 = to_canonical_graph(g2) + in_both = cg1 * cg2 + in_first = cg1 - cg2 + in_second = cg2 - cg1 + return (in_both, in_first, in_second) + + +_MOCK_BNODE = BNode() + + +def similar(g1: Graph, g2: Graph): + """Checks if the two graphs are "similar". + + Checks if the two graphs are "similar", by comparing sorted triples where + all bnodes have been replaced by a singular mock bnode (the + `_MOCK_BNODE`). + + This is a much cheaper, but less reliable, alternative to the comparison + algorithm in `isomorphic`. + """ + return all(t1 == t2 for (t1, t2) in _squashed_graphs_triples(g1, g2)) + + +def _squashed_graphs_triples(g1: Graph, g2: Graph): + for t1, t2 in zip(sorted(_squash_graph(g1)), sorted(_squash_graph(g2))): + yield t1, t2 + + +def _squash_graph(graph: Graph): + return (_squash_bnodes(triple) for triple in graph) + + +def _squash_bnodes(triple): + return tuple((isinstance(t, BNode) and _MOCK_BNODE) or t for t in triple) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rdflib/compat.py b/TTS/Kokoro/.venv/Lib/site-packages/rdflib/compat.py new file mode 100644 index 0000000000000000000000000000000000000000..ddb55eb0b9263bdb354f7e9f3dfa7e453aada843 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rdflib/compat.py @@ -0,0 +1,102 @@ +""" +Utility functions and objects to ease Python 2/3 compatibility, +and different versions of support libraries. +""" + +from __future__ import annotations + +import codecs +import re +import warnings +from typing import Match + + +def cast_bytes(s, enc="utf-8"): + if isinstance(s, str): + return s.encode(enc) + return s + + +def ascii(stream): + return codecs.getreader("ascii")(stream) + + +def bopen(*args, **kwargs): + # type error: No overload variant of "open" matches argument types "Tuple[Any, ...]", "str", "Dict[str, Any]" + return open(*args, mode="rb", **kwargs) # type: ignore[call-overload] + + +long_type = int + + +def sign(n): + if n < 0: + return -1 + if n > 0: + return 1 + return 0 + + +r_unicodeEscape = re.compile(r"(\\u[0-9A-Fa-f]{4}|\\U[0-9A-Fa-f]{8})") # noqa: N816 + + +def _unicodeExpand(s): # noqa: N802 + return r_unicodeEscape.sub(lambda m: chr(int(m.group(0)[2:], 16)), s) + + +def decodeStringEscape(s): # noqa: N802 + warnings.warn( + DeprecationWarning( + "rdflib.compat.decodeStringEscape() is deprecated, " + "it will be removed in rdflib 7.0.0. " + "This function is not used anywhere in rdflib anymore " + "and the utility that it does provide is not implemented correctly." + ) + ) + r""" + s is byte-string - replace \ escapes in string + """ + + s = s.replace("\\t", "\t") + s = s.replace("\\n", "\n") + s = s.replace("\\r", "\r") + s = s.replace("\\b", "\b") + s = s.replace("\\f", "\f") + s = s.replace('\\"', '"') + s = s.replace("\\'", "'") + s = s.replace("\\\\", "\\") + + return s + # return _unicodeExpand(s) # hmm - string escape doesn't do unicode escaping + + +_string_escape_map = { + "t": "\t", + "b": "\b", + "n": "\n", + "r": "\r", + "f": "\f", + '"': '"', + "'": "'", + "\\": "\\", +} + + +def _turtle_escape_subber(match: Match[str]) -> str: + smatch, umatch = match.groups() + if smatch is not None: + return _string_escape_map[smatch] + else: + return chr(int(umatch[1:], 16)) + + +_turtle_escape_pattern = re.compile( + r"""\\(?:([tbnrf"'\\])|(u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8}))""", +) + + +def decodeUnicodeEscape(escaped: str) -> str: # noqa: N802 + if "\\" not in escaped: + # Most of times, there are no backslashes in strings. + return escaped + return _turtle_escape_pattern.sub(_turtle_escape_subber, escaped) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rdflib/container.py b/TTS/Kokoro/.venv/Lib/site-packages/rdflib/container.py new file mode 100644 index 0000000000000000000000000000000000000000..cbfd2cac5bcd9a5eea296494fabae32f9eb98342 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rdflib/container.py @@ -0,0 +1,281 @@ +import warnings +from random import randint + +from rdflib.namespace import RDF +from rdflib.term import BNode, URIRef + +__all__ = ["Container", "Bag", "Seq", "Alt", "NoElementException"] + + +class Container: + """A class for constructing RDF containers, as per + + Basic usage, creating a `Bag` and adding to it: + + ```python + >>> from rdflib import Graph, BNode, Literal, Bag + >>> g = Graph() + >>> b = Bag(g, BNode(), [Literal("One"), Literal("Two"), Literal("Three")]) + >>> print(g.serialize(format="turtle")) + @prefix rdf: . + + [] a rdf:Bag ; + rdf:_1 "One" ; + rdf:_2 "Two" ; + rdf:_3 "Three" . + + + + >>> # print out an item using an index reference + >>> print(b[2]) + Two + + >>> # add a new item + >>> b.append(Literal("Hello")) # doctest: +ELLIPSIS + + >>> print(g.serialize(format="turtle")) + @prefix rdf: . + + [] a rdf:Bag ; + rdf:_1 "One" ; + rdf:_2 "Two" ; + rdf:_3 "Three" ; + rdf:_4 "Hello" . + + + + ``` + """ + + def __init__(self, graph, uri, seq=[], rtype="Bag"): + """Creates a Container + + Args: + graph: a Graph instance + uri: URI or Blank Node of the Container + seq: the elements of the Container + rtype: the type of Container, one of "Bag", "Seq" or "Alt" + """ + + self.graph = graph + self.uri = uri or BNode() + self._len = 0 + self._rtype = rtype # rdf:Bag or rdf:Seq or rdf:Alt + + self.append_multiple(seq) + + # adding triple corresponding to container type + self.graph.add((self.uri, RDF.type, RDF[self._rtype])) + + def n3(self): + items = [] + for i in range(len(self)): + v = self[i + 1] + items.append(v) + + return "( %s )" % " ".join([a.n3() for a in items]) + + def _get_container(self): + """Returns the URI of the container""" + + return self.uri + + def __len__(self): + """Number of items in container""" + + return self._len + + def type_of_conatiner(self): + warnings.warn( + "rdflib.container.Container.type_of_conatiner is deprecated. " + "Use type_of_container method instead.", + DeprecationWarning, + stacklevel=2, + ) + return self._rtype + + def type_of_container(self): + return self._rtype + + def index(self, item): + """Returns the 1-based numerical index of the item in the container""" + + pred = self.graph.predicates(self.uri, item) + if not pred: + raise ValueError("%s is not in %s" % (item, "container")) + li_index = URIRef(str(RDF) + "_") + + i = None + for p in pred: + i = int(p.replace(li_index, "")) + return i + + def __getitem__(self, key): + """Returns item of the container at index key""" + + c = self._get_container() + + assert isinstance(key, int) + elem_uri = str(RDF) + "_" + str(key) + if key <= 0 or key > len(self): + raise KeyError(key) + v = self.graph.value(c, URIRef(elem_uri)) + if v: + return v + else: + raise KeyError(key) + + def __setitem__(self, key, value): + """Sets the item at index key or predicate rdf:_key of the container to value""" + + assert isinstance(key, int) + + c = self._get_container() + elem_uri = str(RDF) + "_" + str(key) + if key <= 0 or key > len(self): + raise KeyError(key) + + self.graph.set((c, URIRef(elem_uri), value)) + + def __delitem__(self, key): + """Removing the item with index key or predicate rdf:_key""" + + assert isinstance(key, int) + if key <= 0 or key > len(self): + raise KeyError(key) + + graph = self.graph + container = self.uri + elem_uri = str(RDF) + "_" + str(key) + graph.remove((container, URIRef(elem_uri), None)) + for j in range(key + 1, len(self) + 1): + elem_uri = str(RDF) + "_" + str(j) + v = graph.value(container, URIRef(elem_uri)) + graph.remove((container, URIRef(elem_uri), v)) + elem_uri = str(RDF) + "_" + str(j - 1) + graph.add((container, URIRef(elem_uri), v)) + + self._len -= 1 + + def items(self): + """Returns a list of all items in the container""" + + l_ = [] + container = self.uri + i = 1 + while True: + elem_uri = str(RDF) + "_" + str(i) + + if (container, URIRef(elem_uri), None) in self.graph: + i += 1 + l_.append(self.graph.value(container, URIRef(elem_uri))) + else: + break + return l_ + + def end(self): # + # find end index (1-based) of container + + container = self.uri + i = 1 + while True: + elem_uri = str(RDF) + "_" + str(i) + + if (container, URIRef(elem_uri), None) in self.graph: + i += 1 + else: + return i - 1 + + def append(self, item): + """Adding item to the end of the container""" + + end = self.end() + elem_uri = str(RDF) + "_" + str(end + 1) + container = self.uri + self.graph.add((container, URIRef(elem_uri), item)) + self._len += 1 + + return self + + def append_multiple(self, other): + """Adding multiple elements to the container to the end which are in python list other""" + + end = self.end() # it should return the last index + + container = self.uri + for item in other: + end += 1 + self._len += 1 + elem_uri = str(RDF) + "_" + str(end) + self.graph.add((container, URIRef(elem_uri), item)) + + return self + + def clear(self): + """Removing all elements from the container""" + + container = self.uri + graph = self.graph + i = 1 + while True: + elem_uri = str(RDF) + "_" + str(i) + if (container, URIRef(elem_uri), None) in self.graph: + graph.remove((container, URIRef(elem_uri), None)) + i += 1 + else: + break + self._len = 0 + return self + + +class Bag(Container): + """Unordered container (no preference order of elements)""" + + def __init__(self, graph, uri, seq=[]): + Container.__init__(self, graph, uri, seq, "Bag") + + +class Alt(Container): + def __init__(self, graph, uri, seq=[]): + Container.__init__(self, graph, uri, seq, "Alt") + + def anyone(self): + if len(self) == 0: + raise NoElementException() + else: + p = randint(1, len(self)) + item = self.__getitem__(p) + return item + + +class Seq(Container): + def __init__(self, graph, uri, seq=[]): + Container.__init__(self, graph, uri, seq, "Seq") + + def add_at_position(self, pos, item): + assert isinstance(pos, int) + if pos <= 0 or pos > len(self) + 1: + raise ValueError("Invalid Position for inserting element in rdf:Seq") + + if pos == len(self) + 1: + self.append(item) + else: + for j in range(len(self), pos - 1, -1): + container = self._get_container() + elem_uri = str(RDF) + "_" + str(j) + v = self.graph.value(container, URIRef(elem_uri)) + self.graph.remove((container, URIRef(elem_uri), v)) + elem_uri = str(RDF) + "_" + str(j + 1) + self.graph.add((container, URIRef(elem_uri), v)) + elem_uri_pos = str(RDF) + "_" + str(pos) + self.graph.add((container, URIRef(elem_uri_pos), item)) + self._len += 1 + return self + + +class NoElementException(Exception): # noqa: N818 + def __init__(self, message="rdf:Alt Container is empty"): + self.message = message + + def __str__(self): + return self.message diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rdflib/events.py b/TTS/Kokoro/.venv/Lib/site-packages/rdflib/events.py new file mode 100644 index 0000000000000000000000000000000000000000..b22d7bc3ab9f3ab4477017b513e06955bcf4267f --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rdflib/events.py @@ -0,0 +1,102 @@ +""" +Dirt Simple Events + +A Dispatcher (or a subclass of Dispatcher) stores event handlers that +are 'fired' simple event objects when interesting things happen. + +Create a dispatcher: + +```python +>>> d = Dispatcher() + +``` + +Now create a handler for the event and subscribe it to the dispatcher +to handle Event events. A handler is a simple function or method that +accepts the event as an argument: + +```python +>>> def handler1(event): print(repr(event)) +>>> d.subscribe(Event, handler1) # doctest: +ELLIPSIS + + +``` + +Now dispatch a new event into the dispatcher, and see handler1 get +fired: + +```python +>>> d.dispatch(Event(foo='bar', data='yours', used_by='the event handlers')) + + +``` +""" + +from __future__ import annotations + +from typing import Any, Dict, Optional + +__all__ = ["Event", "Dispatcher"] + + +class Event: + """ + An event is a container for attributes. The source of an event + creates this object, or a subclass, gives it any kind of data that + the events handlers need to handle the event, and then calls + notify(event). + + The target of an event registers a function to handle the event it + is interested with subscribe(). When a sources calls + notify(event), each subscriber to that event will be called in no + particular order. + """ + + def __init__(self, **kw): + self.__dict__.update(kw) + + def __repr__(self): + attrs = sorted(self.__dict__.keys()) + return "" % ([a for a in attrs],) + + +class Dispatcher: + """ + An object that can dispatch events to a privately managed group of + subscribers. + """ + + _dispatch_map: Optional[Dict[Any, Any]] = None + + def set_map(self, amap: Dict[Any, Any]): + self._dispatch_map = amap + return self + + def get_map(self): + return self._dispatch_map + + def subscribe(self, event_type, handler): + """Subscribe the given handler to an event_type. Handlers + are called in the order they are subscribed. + """ + if self._dispatch_map is None: + self.set_map({}) + # type error: error: Item "None" of "Optional[Dict[Any, Any]]" has no attribute "get" + lst = self._dispatch_map.get(event_type, None) # type: ignore[union-attr] + if lst is None: + lst = [handler] + else: + lst.append(handler) + # type error: Unsupported target for indexed assignment ("Optional[Dict[Any, Any]]") + self._dispatch_map[event_type] = lst # type: ignore[index] + return self + + def dispatch(self, event): + """Dispatch the given event to the subscribed handlers for + the event's type""" + if self._dispatch_map is not None: + lst = self._dispatch_map.get(type(event), None) + if lst is None: + raise ValueError("unknown event type: %s" % type(event)) + for l_ in lst: + l_(event) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rdflib/exceptions.py b/TTS/Kokoro/.venv/Lib/site-packages/rdflib/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..cbe68fb98750895149b7f874dd4efbbad5f1f116 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rdflib/exceptions.py @@ -0,0 +1,45 @@ +""" +TODO: +""" + +from __future__ import annotations + +__all__ = [ + "Error", + "ParserError", + "UniquenessError", +] + + +from typing import Any, Optional + + +class Error(Exception): + """Base class for rdflib exceptions.""" + + def __init__(self, msg: Optional[str] = None): + Exception.__init__(self, msg) + self.msg = msg + + +class ParserError(Error): + """RDF Parser error.""" + + def __init__(self, msg: str): + Error.__init__(self, msg) + self.msg: str = msg + + def __str__(self) -> str: + return self.msg + + +class UniquenessError(Error): + """A uniqueness assumption was made in the context, and that is not true""" + + def __init__(self, values: Any): + Error.__init__( + self, + "\ +Uniqueness assumption is not fulfilled. Multiple values are: %s" + % values, + ) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rdflib/graph.py b/TTS/Kokoro/.venv/Lib/site-packages/rdflib/graph.py new file mode 100644 index 0000000000000000000000000000000000000000..bd4a9fb0c0ddc12c8f651304381156a280e2e5d5 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rdflib/graph.py @@ -0,0 +1,3401 @@ +""" +RDFLib defines the following kinds of Graphs: + +* [`Graph`][rdflib.graph.Graph] +* [`QuotedGraph`][rdflib.graph.QuotedGraph] +* [`ConjunctiveGraph`][rdflib.graph.ConjunctiveGraph] +* [`Dataset`][rdflib.graph.Dataset] + +## Graph + +An RDF graph is a set of RDF triples. Graphs support the python `in` +operator, as well as iteration and some operations like union, +difference and intersection. + +See [`Graph`][rdflib.graph.Graph] + +## Conjunctive Graph + +!!! warning "Deprecation notice" + `ConjunctiveGraph` is deprecated, use [`Dataset`][rdflib.graph.Dataset] instead. + +A Conjunctive Graph is the most relevant collection of graphs that are +considered to be the boundary for closed world assumptions. This +boundary is equivalent to that of the store instance (which is itself +uniquely identified and distinct from other instances of +[`Store`][rdflib.store.Store] that signify other Conjunctive Graphs). It is +equivalent to all the named graphs within it and associated with a +`_default_` graph which is automatically assigned a +[`BNode`][rdflib.term.BNode] for an identifier - if one isn't given. + +See [`ConjunctiveGraph`][rdflib.graph.ConjunctiveGraph] + +## Quoted graph + +The notion of an RDF graph [14] is extended to include the concept of +a formula node. A formula node may occur wherever any other kind of +node can appear. Associated with a formula node is an RDF graph that +is completely disjoint from all other graphs; i.e. has no nodes in +common with any other graph. (It may contain the same labels as other +RDF graphs; because this is, by definition, a separate graph, +considerations of tidiness do not apply between the graph at a formula +node and any other graph.) + +This is intended to map the idea of "{ N3-expression }" that is used +by N3 into an RDF graph upon which RDF semantics is defined. + +See [`QuotedGraph`][rdflib.graph.QuotedGraph] + +## Dataset + +The RDF 1.1 Dataset, a small extension to the Conjunctive Graph. The +primary term is "graphs in the datasets" and not "contexts with quads" +so there is a separate method to set/retrieve a graph in a dataset and +to operate with dataset graphs. As a consequence of this approach, +dataset graphs cannot be identified with blank nodes, a name is always +required (RDFLib will automatically add a name if one is not provided +at creation time). This implementation includes a convenience method +to directly add a single quad to a dataset graph. + +See [`Dataset`][rdflib.graph.Dataset] + +## Working with graphs + +Instantiating Graphs with default store (Memory) and default identifier +(a BNode): + +```python +>>> g = Graph() +>>> g.store.__class__ + +>>> g.identifier.__class__ + + +``` + +Instantiating Graphs with a Memory store and an identifier - +: + +```python +>>> g = Graph('Memory', URIRef("https://rdflib.github.io")) +>>> g.identifier +rdflib.term.URIRef('https://rdflib.github.io') +>>> str(g) # doctest: +NORMALIZE_WHITESPACE +" a rdfg:Graph;rdflib:storage + [a rdflib:Store;rdfs:label 'Memory']." + +``` + +Creating a ConjunctiveGraph - The top level container for all named Graphs +in a "database": + +```python +>>> g = ConjunctiveGraph() +>>> str(g.default_context) +"[a rdfg:Graph;rdflib:storage [a rdflib:Store;rdfs:label 'Memory']]." + +``` + +Adding / removing reified triples to Graph and iterating over it directly or +via triple pattern: + +```python +>>> g = Graph() +>>> statementId = BNode() +>>> print(len(g)) +0 +>>> g.add((statementId, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS +)> +>>> g.add((statementId, RDF.subject, +... URIRef("https://rdflib.github.io/store/ConjunctiveGraph"))) # doctest: +ELLIPSIS +)> +>>> g.add((statementId, RDF.predicate, namespace.RDFS.label)) # doctest: +ELLIPSIS +)> +>>> g.add((statementId, RDF.object, Literal("Conjunctive Graph"))) # doctest: +ELLIPSIS +)> +>>> print(len(g)) +4 +>>> for s, p, o in g: +... print(type(s)) +... + + + + + +>>> for s, p, o in g.triples((None, RDF.object, None)): +... print(o) +... +Conjunctive Graph +>>> g.remove((statementId, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS +)> +>>> print(len(g)) +3 + +``` + +`None` terms in calls to [`triples()`][rdflib.graph.Graph.triples] can be +thought of as "open variables". + +Graph support set-theoretic operators, you can add/subtract graphs, as +well as intersection (with multiplication operator g1*g2) and xor (g1 +^ g2). + +Note that BNode IDs are kept when doing set-theoretic operations, this +may or may not be what you want. Two named graphs within the same +application probably want share BNode IDs, two graphs with data from +different sources probably not. If your BNode IDs are all generated +by RDFLib they are UUIDs and unique. + +```python +>>> g1 = Graph() +>>> g2 = Graph() +>>> u = URIRef("http://example.com/foo") +>>> g1.add([u, namespace.RDFS.label, Literal("foo")]) # doctest: +ELLIPSIS +)> +>>> g1.add([u, namespace.RDFS.label, Literal("bar")]) # doctest: +ELLIPSIS +)> +>>> g2.add([u, namespace.RDFS.label, Literal("foo")]) # doctest: +ELLIPSIS +)> +>>> g2.add([u, namespace.RDFS.label, Literal("bing")]) # doctest: +ELLIPSIS +)> +>>> len(g1 + g2) # adds bing as label +3 +>>> len(g1 - g2) # removes foo +1 +>>> len(g1 * g2) # only foo +1 +>>> g1 += g2 # now g1 contains everything + +``` + +Graph Aggregation - ConjunctiveGraphs and ReadOnlyGraphAggregate within +the same store: + +```python +>>> store = plugin.get("Memory", Store)() +>>> g1 = Graph(store) +>>> g2 = Graph(store) +>>> g3 = Graph(store) +>>> stmt1 = BNode() +>>> stmt2 = BNode() +>>> stmt3 = BNode() +>>> g1.add((stmt1, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS +)> +>>> g1.add((stmt1, RDF.subject, +... URIRef('https://rdflib.github.io/store/ConjunctiveGraph'))) # doctest: +ELLIPSIS +)> +>>> g1.add((stmt1, RDF.predicate, namespace.RDFS.label)) # doctest: +ELLIPSIS +)> +>>> g1.add((stmt1, RDF.object, Literal('Conjunctive Graph'))) # doctest: +ELLIPSIS +)> +>>> g2.add((stmt2, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS +)> +>>> g2.add((stmt2, RDF.subject, +... URIRef('https://rdflib.github.io/store/ConjunctiveGraph'))) # doctest: +ELLIPSIS +)> +>>> g2.add((stmt2, RDF.predicate, RDF.type)) # doctest: +ELLIPSIS +)> +>>> g2.add((stmt2, RDF.object, namespace.RDFS.Class)) # doctest: +ELLIPSIS +)> +>>> g3.add((stmt3, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS +)> +>>> g3.add((stmt3, RDF.subject, +... URIRef('https://rdflib.github.io/store/ConjunctiveGraph'))) # doctest: +ELLIPSIS +)> +>>> g3.add((stmt3, RDF.predicate, namespace.RDFS.comment)) # doctest: +ELLIPSIS +)> +>>> g3.add((stmt3, RDF.object, Literal( +... 'The top-level aggregate graph - The sum ' + +... 'of all named graphs within a Store'))) # doctest: +ELLIPSIS +)> +>>> len(list(ConjunctiveGraph(store).subjects(RDF.type, RDF.Statement))) +3 +>>> len(list(ReadOnlyGraphAggregate([g1,g2]).subjects( +... RDF.type, RDF.Statement))) +2 + +``` + +ConjunctiveGraphs have a [`quads()`][rdflib.graph.ConjunctiveGraph.quads] method +which returns quads instead of triples, where the fourth item is the Graph +(or subclass thereof) instance in which the triple was asserted: + +```python +>>> uniqueGraphNames = set( +... [graph.identifier for s, p, o, graph in ConjunctiveGraph(store +... ).quads((None, RDF.predicate, None))]) +>>> len(uniqueGraphNames) +3 +>>> unionGraph = ReadOnlyGraphAggregate([g1, g2]) +>>> uniqueGraphNames = set( +... [graph.identifier for s, p, o, graph in unionGraph.quads( +... (None, RDF.predicate, None))]) +>>> len(uniqueGraphNames) +2 + +``` + +Parsing N3 from a string: + +```python +>>> g2 = Graph() +>>> src = ''' +... @prefix rdf: . +... @prefix rdfs: . +... [ a rdf:Statement ; +... rdf:subject ; +... rdf:predicate rdfs:label; +... rdf:object "Conjunctive Graph" ] . +... ''' +>>> g2 = g2.parse(data=src, format="n3") +>>> print(len(g2)) +4 + +``` + +Using Namespace class: + +```python +>>> RDFLib = Namespace("https://rdflib.github.io/") +>>> RDFLib.ConjunctiveGraph +rdflib.term.URIRef('https://rdflib.github.io/ConjunctiveGraph') +>>> RDFLib["Graph"] +rdflib.term.URIRef('https://rdflib.github.io/Graph') + +``` +""" + +from __future__ import annotations + +import logging +import pathlib +import random +import warnings +from io import BytesIO +from typing import ( + IO, + TYPE_CHECKING, + Any, + BinaryIO, + Callable, + Dict, + Generator, + Iterable, + List, + Mapping, + NoReturn, + Optional, + Set, + TextIO, + Tuple, + Type, + TypeVar, + Union, + cast, + overload, +) +from urllib.parse import urlparse +from urllib.request import url2pathname + +import rdflib.exceptions as exceptions +import rdflib.namespace as namespace # noqa: F401 # This is here because it is used in a docstring. +import rdflib.plugin as plugin +import rdflib.query as query +import rdflib.util # avoid circular dependency +from rdflib.collection import Collection +from rdflib.exceptions import ParserError +from rdflib.namespace import RDF, Namespace, NamespaceManager +from rdflib.parser import InputSource, Parser, create_input_source +from rdflib.paths import Path +from rdflib.resource import Resource +from rdflib.serializer import Serializer +from rdflib.store import Store +from rdflib.term import ( + BNode, + Genid, + IdentifiedNode, + Identifier, + Literal, + Node, + RDFLibGenid, + URIRef, +) + +if TYPE_CHECKING: + import typing_extensions as te + + import rdflib.query + from rdflib.plugins.sparql.sparql import Query, Update + +_SubjectType = Node +_PredicateType = Node +_ObjectType = Node +_ContextIdentifierType = IdentifiedNode + +_TripleType = Tuple["_SubjectType", "_PredicateType", "_ObjectType"] +_QuadType = Tuple["_SubjectType", "_PredicateType", "_ObjectType", "_ContextType"] +_OptionalQuadType = Tuple[ + "_SubjectType", "_PredicateType", "_ObjectType", Optional["_ContextType"] +] +_TripleOrOptionalQuadType = Union["_TripleType", "_OptionalQuadType"] +_OptionalIdentifiedQuadType = Tuple[ + "_SubjectType", "_PredicateType", "_ObjectType", Optional["_ContextIdentifierType"] +] +_TriplePatternType = Tuple[ + Optional["_SubjectType"], Optional["_PredicateType"], Optional["_ObjectType"] +] +_TriplePathPatternType = Tuple[Optional["_SubjectType"], Path, Optional["_ObjectType"]] +_QuadPatternType = Tuple[ + Optional["_SubjectType"], + Optional["_PredicateType"], + Optional["_ObjectType"], + Optional["_ContextType"], +] +_QuadPathPatternType = Tuple[ + Optional["_SubjectType"], + Path, + Optional["_ObjectType"], + Optional["_ContextType"], +] +_TripleOrQuadPatternType = Union["_TriplePatternType", "_QuadPatternType"] +_TripleOrQuadPathPatternType = Union["_TriplePathPatternType", "_QuadPathPatternType"] +_TripleSelectorType = Tuple[ + Optional["_SubjectType"], + Optional[Union["Path", "_PredicateType"]], + Optional["_ObjectType"], +] +_QuadSelectorType = Tuple[ + Optional["_SubjectType"], + Optional[Union["Path", "_PredicateType"]], + Optional["_ObjectType"], + Optional["_ContextType"], +] +_TripleOrQuadSelectorType = Union["_TripleSelectorType", "_QuadSelectorType"] +_TriplePathType = Tuple["_SubjectType", Path, "_ObjectType"] +_TripleOrTriplePathType = Union["_TripleType", "_TriplePathType"] +_TripleChoiceType = Union[ + Tuple[List[_SubjectType], Optional[_PredicateType], Optional[_ObjectType]], + Tuple[Optional[_SubjectType], List[_PredicateType], Optional[_ObjectType]], + Tuple[Optional[_SubjectType], Optional[_PredicateType], List[_ObjectType]], +] + +_GraphT = TypeVar("_GraphT", bound="Graph") +_ConjunctiveGraphT = TypeVar("_ConjunctiveGraphT", bound="ConjunctiveGraph") +_DatasetT = TypeVar("_DatasetT", bound="Dataset") + +# type error: Function "Type[Literal]" could always be true in boolean contex +assert Literal # type: ignore[truthy-function] # avoid warning +# type error: Function "Type[Namespace]" could always be true in boolean context +assert Namespace # type: ignore[truthy-function] # avoid warning + +if TYPE_CHECKING: + from rdflib._type_checking import _NamespaceSetString + +logger = logging.getLogger(__name__) + + +__all__ = [ + "Graph", + "ConjunctiveGraph", + "QuotedGraph", + "Seq", + "ModificationException", + "Dataset", + "UnSupportedAggregateOperation", + "ReadOnlyGraphAggregate", + "BatchAddGraph", + "_ConjunctiveGraphT", + "_ContextIdentifierType", + "_DatasetT", + "_GraphT", + "_ObjectType", + "_OptionalIdentifiedQuadType", + "_OptionalQuadType", + "_PredicateType", + "_QuadPathPatternType", + "_QuadPatternType", + "_QuadSelectorType", + "_QuadType", + "_SubjectType", + "_TripleOrOptionalQuadType", + "_TripleOrTriplePathType", + "_TripleOrQuadPathPatternType", + "_TripleOrQuadPatternType", + "_TripleOrQuadSelectorType", + "_TriplePathPatternType", + "_TriplePathType", + "_TriplePatternType", + "_TripleSelectorType", + "_TripleType", +] + +# : Transitive closure arg type. +_TCArgT = TypeVar("_TCArgT") + + +# Graph is a node because technically a formula-aware graph +# take a Graph as subject or object, but we usually use QuotedGraph for that. +class Graph(Node): + """An RDF Graph: a Python object containing nodes and relations between them as + RDF 'triples'. + + This is the central RDFLib object class and Graph objects are almost always present + in all uses of RDFLib. + + Example: + The basic use is to create a Graph and iterate through or query its content: + + ```python + >>> from rdflib import Graph, URIRef + >>> g = Graph() + >>> g.add(( + ... URIRef("http://example.com/s1"), # subject + ... URIRef("http://example.com/p1"), # predicate + ... URIRef("http://example.com/o1"), # object + ... )) # doctest: +ELLIPSIS + )> + + >>> g.add(( + ... URIRef("http://example.com/s2"), # subject + ... URIRef("http://example.com/p2"), # predicate + ... URIRef("http://example.com/o2"), # object + ... )) # doctest: +ELLIPSIS + )> + + >>> for triple in sorted(g): # simple looping + ... print(triple) + (rdflib.term.URIRef('http://example.com/s1'), rdflib.term.URIRef('http://example.com/p1'), rdflib.term.URIRef('http://example.com/o1')) + (rdflib.term.URIRef('http://example.com/s2'), rdflib.term.URIRef('http://example.com/p2'), rdflib.term.URIRef('http://example.com/o2')) + + >>> # get the object of the triple with subject s1 and predicate p1 + >>> o = g.value( + ... subject=URIRef("http://example.com/s1"), + ... predicate=URIRef("http://example.com/p1") + ... ) + + ``` + + + Args: + store: The constructor accepts one argument, the "store" that will be used to store the + graph data with the default being the [`Memory`][rdflib.plugins.stores.memory.Memory] + (in memory) Store. Other Stores that persist content to disk using various file + databases or Stores that use remote servers (SPARQL systems) are supported. + All [builtin storetypes][rdflib.plugins.stores] can be accessed via + their registered names. + Other Stores not shipped with RDFLib can be added as plugins, such as + [HDT](https://github.com/rdflib/rdflib-hdt/). + Registration of external plugins + is described in [`rdflib.plugin`][rdflib.plugin]. + + Stores can be context-aware or unaware. Unaware stores take up + (some) less space but cannot support features that require + context, such as true merging/demerging of sub-graphs and + provenance. + + Even if used with a context-aware store, Graph will only expose the quads which + belong to the default graph. To access the rest of the data the + `Dataset` class can be used instead. + + The Graph constructor can take an identifier which identifies the Graph + by name. If none is given, the graph is assigned a BNode for its + identifier. + + For more on Named Graphs, see the RDFLib `Dataset` class and the TriG Specification, + . + identifier: identifier of the graph itself + namespace_manager: Used namespace manager. + Create with bind_namespaces if `None`. + base: Base used for [URIs][rdflib.term.URIRef] + bind_namespaces: Used bind_namespaces for namespace_manager + Is only used, when no namespace_manager is provided. + """ + + context_aware: bool + formula_aware: bool + default_union: bool + base: Optional[str] + + def __init__( + self, + store: Union[Store, str] = "default", + identifier: Optional[Union[_ContextIdentifierType, str]] = None, + namespace_manager: Optional[NamespaceManager] = None, + base: Optional[str] = None, + bind_namespaces: _NamespaceSetString = "rdflib", + ): + super(Graph, self).__init__() + self.base = base + self.__identifier: _ContextIdentifierType + self.__identifier = identifier or BNode() # type: ignore[assignment] + if not isinstance(self.__identifier, IdentifiedNode): + self.__identifier = URIRef(self.__identifier) # type: ignore[unreachable] + self.__store: Store + if not isinstance(store, Store): + # TODO: error handling + self.__store = store = plugin.get(store, Store)() + else: + self.__store = store + self.__namespace_manager = namespace_manager + self._bind_namespaces = bind_namespaces + self.context_aware = False + self.formula_aware = False + self.default_union = False + + @property + def store(self) -> Store: + return self.__store + + @property + def identifier(self) -> _ContextIdentifierType: + return self.__identifier + + @property + def namespace_manager(self) -> NamespaceManager: + """ + this graph's namespace-manager + """ + if self.__namespace_manager is None: + self.__namespace_manager = NamespaceManager(self, self._bind_namespaces) + return self.__namespace_manager + + @namespace_manager.setter + def namespace_manager(self, nm: NamespaceManager) -> None: + self.__namespace_manager = nm + + def __repr__(self) -> str: + return "" % (self.identifier, type(self)) + + def __str__(self) -> str: + if isinstance(self.identifier, URIRef): + return ( + "%s a rdfg:Graph;rdflib:storage " + "[a rdflib:Store;rdfs:label '%s']." + ) % (self.identifier.n3(), self.store.__class__.__name__) + else: + return ( + "[a rdfg:Graph;rdflib:storage " + "[a rdflib:Store;rdfs:label '%s']]." + ) % self.store.__class__.__name__ + + def toPython(self: _GraphT) -> _GraphT: # noqa: N802 + return self + + def destroy(self: _GraphT, configuration: str) -> _GraphT: + """Destroy the store identified by `configuration` if supported""" + self.__store.destroy(configuration) + return self + + # Transactional interfaces (optional) + def commit(self: _GraphT) -> _GraphT: + """Commits active transactions""" + self.__store.commit() + return self + + def rollback(self: _GraphT) -> _GraphT: + """Rollback active transactions""" + self.__store.rollback() + return self + + def open( + self, configuration: Union[str, tuple[str, str]], create: bool = False + ) -> Optional[int]: + """Open the graph store + + Might be necessary for stores that require opening a connection to a + database or acquiring some resource. + """ + return self.__store.open(configuration, create) + + def close(self, commit_pending_transaction: bool = False) -> None: + """Close the graph store + + Might be necessary for stores that require closing a connection to a + database or releasing some resource. + """ + return self.__store.close(commit_pending_transaction=commit_pending_transaction) + + def add(self: _GraphT, triple: _TripleType) -> _GraphT: + """Add a triple with self as context. + + Args: + triple: The triple to add to the graph. + + Returns: + The graph instance. + """ + s, p, o = triple + assert isinstance(s, Node), "Subject %s must be an rdflib term" % (s,) + assert isinstance(p, Node), "Predicate %s must be an rdflib term" % (p,) + assert isinstance(o, Node), "Object %s must be an rdflib term" % (o,) + self.__store.add((s, p, o), self, quoted=False) + return self + + def addN(self: _GraphT, quads: Iterable[_QuadType]) -> _GraphT: # noqa: N802 + """Add a sequence of triple with context""" + + self.__store.addN( + (s, p, o, c) + for s, p, o, c in quads + if isinstance(c, Graph) + and c.identifier is self.identifier + and _assertnode(s, p, o) + ) + return self + + def remove(self: _GraphT, triple: _TriplePatternType) -> _GraphT: + """Remove a triple from the graph + + If the triple does not provide a context attribute, removes the triple + from all contexts. + """ + self.__store.remove(triple, context=self) + return self + + @overload + def triples( + self, + triple: _TriplePatternType, + ) -> Generator[_TripleType, None, None]: ... + + @overload + def triples( + self, + triple: _TriplePathPatternType, + ) -> Generator[_TriplePathType, None, None]: ... + + @overload + def triples( + self, + triple: _TripleSelectorType, + ) -> Generator[_TripleOrTriplePathType, None, None]: ... + + def triples( + self, + triple: _TripleSelectorType, + ) -> Generator[_TripleOrTriplePathType, None, None]: + """Generator over the triple store. + + Returns triples that match the given triple pattern. If the triple pattern + does not provide a context, all contexts will be searched. + + Args: + triple: A triple pattern where each component can be a specific value or None + as a wildcard. The predicate can also be a path expression. + + Yields: + Triples matching the given pattern. + """ + s, p, o = triple + if isinstance(p, Path): + for _s, _o in p.eval(self, s, o): + yield _s, p, _o + else: + for (_s, _p, _o), cg in self.__store.triples((s, p, o), context=self): + yield _s, _p, _o + + def __getitem__(self, item): + """ + A graph can be "sliced" as a shortcut for the triples method + The python slice syntax is (ab)used for specifying triples. + A generator over matches is returned, + the returned tuples include only the parts not given + + ```python + >>> import rdflib + >>> g = rdflib.Graph() + >>> g.add((rdflib.URIRef("urn:bob"), namespace.RDFS.label, rdflib.Literal("Bob"))) # doctest: +ELLIPSIS + )> + + >>> list(g[rdflib.URIRef("urn:bob")]) # all triples about bob + [(rdflib.term.URIRef('http://www.w3.org/2000/01/rdf-schema#label'), rdflib.term.Literal('Bob'))] + + >>> list(g[:namespace.RDFS.label]) # all label triples + [(rdflib.term.URIRef('urn:bob'), rdflib.term.Literal('Bob'))] + + >>> list(g[::rdflib.Literal("Bob")]) # all triples with bob as object + [(rdflib.term.URIRef('urn:bob'), rdflib.term.URIRef('http://www.w3.org/2000/01/rdf-schema#label'))] + + ``` + + Combined with SPARQL paths, more complex queries can be + written concisely: + + - Name of all Bobs friends: `g[bob : FOAF.knows/FOAF.name ]` + - Some label for Bob: `g[bob : DC.title|FOAF.name|RDFS.label]` + - All friends and friends of friends of Bob: `g[bob : FOAF.knows * "+"]` + - etc. + + !!! example "New in version 4.0" + """ + + if isinstance(item, slice): + s, p, o = item.start, item.stop, item.step + if s is None and p is None and o is None: + return self.triples((s, p, o)) + elif s is None and p is None: + # type error: Argument 1 to "subject_predicates" of "Graph" has incompatible type "Union[int, Any]"; expected "Optional[Node]" + return self.subject_predicates(o) # type: ignore[arg-type] + elif s is None and o is None: + # type error: Argument 1 to "subject_objects" of "Graph" has incompatible type "Union[int, Any]"; expected "Union[Path, Node, None]" + return self.subject_objects(p) # type: ignore[arg-type] + elif p is None and o is None: + # type error: Argument 1 to "predicate_objects" of "Graph" has incompatible type "Union[int, Any]"; expected "Optional[Node]" + return self.predicate_objects(s) # type: ignore[arg-type] + elif s is None: + # type error: Argument 1 to "subjects" of "Graph" has incompatible type "Union[int, Any]"; expected "Union[Path, Node, None]" + # Argument 2 to "subjects" of "Graph" has incompatible type "Union[int, Any]"; expected "Union[Node, List[Node], None]" + return self.subjects(p, o) # type: ignore[arg-type] + elif p is None: + # type error: Argument 1 to "predicates" of "Graph" has incompatible type "Union[int, Any]"; expected "Optional[Node]" + # Argument 2 to "predicates" of "Graph" has incompatible type "Union[int, Any]"; expected "Optional[Node]" + return self.predicates(s, o) # type: ignore[arg-type] + elif o is None: + # type error: Argument 1 to "objects" of "Graph" has incompatible type "Union[int, Any]"; expected "Union[Node, List[Node], None]" + # Argument 2 to "objects" of "Graph" has incompatible type "Union[int, Any]"; expected "Union[Path, Node, None]" + return self.objects(s, p) # type: ignore[arg-type] + else: + # type error: Unsupported operand types for in ("Tuple[Union[int, Any], Union[int, Any], Union[int, Any]]" and "Graph") + # all given + return (s, p, o) in self # type: ignore[operator] + + elif isinstance(item, (Path, Node)): + # type error: Argument 1 to "predicate_objects" of "Graph" has incompatible type "Union[Path, Node]"; expected "Optional[Node]" + return self.predicate_objects(item) # type: ignore[arg-type] + + else: + raise TypeError( + "You can only index a graph by a single rdflib term or path, or a slice of rdflib terms." + ) + + def __len__(self) -> int: + """Returns the number of triples in the graph. + + If context is specified then the number of triples in the context is + returned instead. + + Returns: + The number of triples in the graph. + """ + # type error: Unexpected keyword argument "context" for "__len__" of "Store" + return self.__store.__len__(context=self) # type: ignore[call-arg] + + def __iter__(self) -> Generator[_TripleType, None, None]: + """Iterates over all triples in the store. + + Returns: + A generator yielding all triples in the store. + """ + return self.triples((None, None, None)) + + def __contains__(self, triple: _TripleSelectorType) -> bool: + """Support for 'triple in graph' syntax. + + Args: + triple: The triple pattern to check for. + + Returns: + True if the triple pattern exists in the graph, False otherwise. + """ + for triple in self.triples(triple): + return True + return False + + def __hash__(self) -> int: + return hash(self.identifier) + + def __cmp__(self, other) -> int: + if other is None: + return -1 + elif isinstance(other, Graph): + return (self.identifier > other.identifier) - ( + self.identifier < other.identifier + ) + else: + # Note if None is considered equivalent to owl:Nothing + # Then perhaps a graph with length 0 should be considered + # equivalent to None (if compared to it)? + return 1 + + def __eq__(self, other) -> bool: + return isinstance(other, Graph) and self.identifier == other.identifier + + def __lt__(self, other) -> bool: + return (other is None) or ( + isinstance(other, Graph) and self.identifier < other.identifier + ) + + def __le__(self, other: Graph) -> bool: + return self < other or self == other + + def __gt__(self, other) -> bool: + return (isinstance(other, Graph) and self.identifier > other.identifier) or ( + other is not None + ) + + def __ge__(self, other: Graph) -> bool: + return self > other or self == other + + def __iadd__(self: _GraphT, other: Iterable[_TripleType]) -> _GraphT: + """Add all triples in Graph other to Graph. + BNode IDs are not changed.""" + self.addN((s, p, o, self) for s, p, o in other) + return self + + def __isub__(self: _GraphT, other: Iterable[_TripleType]) -> _GraphT: + """Subtract all triples in Graph other from Graph. + BNode IDs are not changed.""" + for triple in other: + self.remove(triple) + return self + + def __add__(self, other: Graph) -> Graph: + """Set-theoretic union + BNode IDs are not changed.""" + try: + retval = type(self)() + except TypeError: + retval = Graph() + for prefix, uri in set(list(self.namespaces()) + list(other.namespaces())): + retval.bind(prefix, uri) + for x in self: + retval.add(x) + for y in other: + retval.add(y) + return retval + + def __mul__(self, other: Graph) -> Graph: + """Set-theoretic intersection. + BNode IDs are not changed.""" + try: + retval = type(self)() + except TypeError: + retval = Graph() + for x in other: + if x in self: + retval.add(x) + return retval + + def __sub__(self, other: Graph) -> Graph: + """Set-theoretic difference. + BNode IDs are not changed.""" + try: + retval = type(self)() + except TypeError: + retval = Graph() + for x in self: + if x not in other: + retval.add(x) + return retval + + def __xor__(self, other: Graph) -> Graph: + """Set-theoretic XOR. + BNode IDs are not changed.""" + return (self - other) + (other - self) + + __or__ = __add__ + __and__ = __mul__ + + # Conv. methods + + def set( + self: _GraphT, triple: Tuple[_SubjectType, _PredicateType, _ObjectType] + ) -> _GraphT: + """Convenience method to update the value of object + + Remove any existing triples for subject and predicate before adding + (subject, predicate, object). + """ + (subject, predicate, object_) = triple + assert ( + subject is not None + ), "s can't be None in .set([s,p,o]), as it would remove (*, p, *)" + assert ( + predicate is not None + ), "p can't be None in .set([s,p,o]), as it would remove (s, *, *)" + self.remove((subject, predicate, None)) + self.add((subject, predicate, object_)) + return self + + def subjects( + self, + predicate: Union[None, Path, _PredicateType] = None, + object: Optional[Union[_ObjectType, List[_ObjectType]]] = None, + unique: bool = False, + ) -> Generator[_SubjectType, None, None]: + """A generator of (optionally unique) subjects with the given + predicate and object(s) + + Args: + predicate: A specific predicate to match or None to match any predicate. + object: A specific object or list of objects to match or None to match any object. + unique: If True, only yield unique subjects. + """ + # if the object is a list of Nodes, yield results from subject() call for each + if isinstance(object, list): + for obj in object: + for s in self.subjects(predicate, obj, unique): + yield s + else: + if not unique: + for s, p, o in self.triples((None, predicate, object)): + yield s + else: + subs = set() + for s, p, o in self.triples((None, predicate, object)): + if s not in subs: + yield s + try: + subs.add(s) + except MemoryError as e: + logger.error( + f"{e}. Consider not setting parameter 'unique' to True" + ) + raise + + def predicates( + self, + subject: Optional[_SubjectType] = None, + object: Optional[_ObjectType] = None, + unique: bool = False, + ) -> Generator[_PredicateType, None, None]: + """Generate predicates with the given subject and object. + + Args: + subject: A specific subject to match or None to match any subject. + object: A specific object to match or None to match any object. + unique: If True, only yield unique predicates. + + Yields: + Predicates matching the given subject and object. + """ + if not unique: + for s, p, o in self.triples((subject, None, object)): + yield p + else: + preds = set() + for s, p, o in self.triples((subject, None, object)): + if p not in preds: + yield p + try: + preds.add(p) + except MemoryError as e: + logger.error( + f"{e}. Consider not setting parameter 'unique' to True" + ) + raise + + def objects( + self, + subject: Optional[Union[_SubjectType, List[_SubjectType]]] = None, + predicate: Union[None, Path, _PredicateType] = None, + unique: bool = False, + ) -> Generator[_ObjectType, None, None]: + """A generator of (optionally unique) objects with the given + subject(s) and predicate + + Args: + subject: A specific subject or a list of subjects to match or None to match any subject. + predicate: A specific predicate to match or None to match any predicate. + unique: If True, only yield unique objects. + + Yields: + Objects matching the given subject and predicate. + """ + if isinstance(subject, list): + for subj in subject: + for o in self.objects(subj, predicate, unique): + yield o + else: + if not unique: + for s, p, o in self.triples((subject, predicate, None)): + yield o + else: + objs = set() + for s, p, o in self.triples((subject, predicate, None)): + if o not in objs: + yield o + try: + objs.add(o) + except MemoryError as e: + logger.error( + f"{e}. Consider not setting parameter 'unique' to True" + ) + raise + + def subject_predicates( + self, object: Optional[_ObjectType] = None, unique: bool = False + ) -> Generator[Tuple[_SubjectType, _PredicateType], None, None]: + """A generator of (optionally unique) (subject, predicate) tuples + for the given object""" + if not unique: + for s, p, o in self.triples((None, None, object)): + yield s, p + else: + subj_preds = set() + for s, p, o in self.triples((None, None, object)): + if (s, p) not in subj_preds: + yield s, p + try: + subj_preds.add((s, p)) + except MemoryError as e: + logger.error( + f"{e}. Consider not setting parameter 'unique' to True" + ) + raise + + def subject_objects( + self, + predicate: Union[None, Path, _PredicateType] = None, + unique: bool = False, + ) -> Generator[Tuple[_SubjectType, _ObjectType], None, None]: + """A generator of (optionally unique) (subject, object) tuples + for the given predicate""" + if not unique: + for s, p, o in self.triples((None, predicate, None)): + yield s, o + else: + subj_objs = set() + for s, p, o in self.triples((None, predicate, None)): + if (s, o) not in subj_objs: + yield s, o + try: + subj_objs.add((s, o)) + except MemoryError as e: + logger.error( + f"{e}. Consider not setting parameter 'unique' to True" + ) + raise + + def predicate_objects( + self, subject: Optional[_SubjectType] = None, unique: bool = False + ) -> Generator[Tuple[_PredicateType, _ObjectType], None, None]: + """A generator of (optionally unique) (predicate, object) tuples + for the given subject""" + if not unique: + for s, p, o in self.triples((subject, None, None)): + yield p, o + else: + pred_objs = set() + for s, p, o in self.triples((subject, None, None)): + if (p, o) not in pred_objs: + yield p, o + try: + pred_objs.add((p, o)) + except MemoryError as e: + logger.error( + f"{e}. Consider not setting parameter 'unique' to True" + ) + raise + + def triples_choices( + self, + triple: _TripleChoiceType, + context: Optional[_ContextType] = None, + ) -> Generator[_TripleType, None, None]: + subject, predicate, object_ = triple + # type error: Argument 1 to "triples_choices" of "Store" has incompatible type "Tuple[Union[List[Node], Node], Union[Node, List[Node]], Union[Node, List[Node]]]"; expected "Union[Tuple[List[Node], Node, Node], Tuple[Node, List[Node], Node], Tuple[Node, Node, List[Node]]]" + # type error note: unpacking discards type info + for (s, p, o), cg in self.store.triples_choices( + (subject, predicate, object_), context=self # type: ignore[arg-type] + ): + yield s, p, o + + @overload + def value( + self, + subject: None = ..., + predicate: None = ..., + object: Optional[_ObjectType] = ..., + default: Optional[Node] = ..., + any: bool = ..., + ) -> None: ... + + @overload + def value( + self, + subject: Optional[_SubjectType] = ..., + predicate: None = ..., + object: None = ..., + default: Optional[Node] = ..., + any: bool = ..., + ) -> None: ... + + @overload + def value( + self, + subject: None = ..., + predicate: Optional[_PredicateType] = ..., + object: None = ..., + default: Optional[Node] = ..., + any: bool = ..., + ) -> None: ... + + @overload + def value( + self, + subject: Optional[_SubjectType] = ..., + predicate: Optional[_PredicateType] = ..., + object: Optional[_ObjectType] = ..., + default: Optional[Node] = ..., + any: bool = ..., + ) -> Optional[Node]: ... + + def value( + self, + subject: Optional[_SubjectType] = None, + predicate: Optional[_PredicateType] = RDF.value, + object: Optional[_ObjectType] = None, + default: Optional[Node] = None, + any: bool = True, + ) -> Optional[Node]: + """Get a value for a pair of two criteria + + Exactly one of subject, predicate, object must be None. Useful if one + knows that there may only be one value. + + It is one of those situations that occur a lot, hence this + 'macro' like utility + + Args: + subject: Subject of the triple pattern, exactly one of subject, predicate, object must be None + predicate: Predicate of the triple pattern, exactly one of subject, predicate, object must be None + object: Object of the triple pattern, exactly one of subject, predicate, object must be None + default: Value to be returned if no values found + any: If True, return any value in the case there is more than one, else, raise UniquenessError + """ + retval = default + + if ( + (subject is None and predicate is None) + or (subject is None and object is None) + or (predicate is None and object is None) + ): + return None + + if object is None: + values = self.objects(subject, predicate) + if subject is None: + values = self.subjects(predicate, object) + if predicate is None: + values = self.predicates(subject, object) + + try: + retval = next(values) + except StopIteration: + retval = default + else: + if any is False: + try: + next(values) + msg = ( + "While trying to find a value for (%s, %s, %s) the" + " following multiple values where found:\n" + % (subject, predicate, object) + ) + triples = self.store.triples((subject, predicate, object), None) + for (s, p, o), contexts in triples: + msg += "(%s, %s, %s)\n (contexts: %s)\n" % ( + s, + p, + o, + list(contexts), + ) + raise exceptions.UniquenessError(msg) + except StopIteration: + pass + return retval + + def items(self, list: Node) -> Generator[Node, None, None]: + """Generator over all items in the resource specified by list + + Args: + list: An RDF collection. + """ + chain = set([list]) + while list: + item = self.value(list, RDF.first) + if item is not None: + yield item + # type error: Incompatible types in assignment (expression has type "Optional[Node]", variable has type "Node") + list = self.value(list, RDF.rest) # type: ignore[assignment] + if list in chain: + raise ValueError("List contains a recursive rdf:rest reference") + chain.add(list) + + def transitiveClosure( # noqa: N802 + self, + func: Callable[[_TCArgT, Graph], Iterable[_TCArgT]], + arg: _TCArgT, + seen: Optional[Dict[_TCArgT, int]] = None, + ): + """Generates transitive closure of a user-defined function against the graph + + ```python + from rdflib.collection import Collection + g = Graph() + a = BNode("foo") + b = BNode("bar") + c = BNode("baz") + g.add((a,RDF.first,RDF.type)) + g.add((a,RDF.rest,b)) + g.add((b,RDF.first,namespace.RDFS.label)) + g.add((b,RDF.rest,c)) + g.add((c,RDF.first,namespace.RDFS.comment)) + g.add((c,RDF.rest,RDF.nil)) + def topList(node,g): + for s in g.subjects(RDF.rest, node): + yield s + def reverseList(node,g): + for f in g.objects(node, RDF.first): + print(f) + for s in g.subjects(RDF.rest, node): + yield s + + [rt for rt in g.transitiveClosure( + topList,RDF.nil)] + # [rdflib.term.BNode('baz'), + # rdflib.term.BNode('bar'), + # rdflib.term.BNode('foo')] + + [rt for rt in g.transitiveClosure( + reverseList,RDF.nil)] + # http://www.w3.org/2000/01/rdf-schema#comment + # http://www.w3.org/2000/01/rdf-schema#label + # http://www.w3.org/1999/02/22-rdf-syntax-ns#type + # [rdflib.term.BNode('baz'), + # rdflib.term.BNode('bar'), + # rdflib.term.BNode('foo')] + ``` + + Args: + func: A function that generates a sequence of nodes + arg: The starting node + seen: A dict of visited nodes + """ + if seen is None: + seen = {} + elif arg in seen: + return + seen[arg] = 1 + for rt in func(arg, self): + yield rt + for rt_2 in self.transitiveClosure(func, rt, seen): + yield rt_2 + + def transitive_objects( + self, + subject: Optional[_SubjectType], + predicate: Optional[_PredicateType], + remember: Optional[Dict[Optional[_SubjectType], int]] = None, + ) -> Generator[Optional[_SubjectType], None, None]: + """Transitively generate objects for the ``predicate`` relationship + + Generated objects belong to the depth first transitive closure of the + `predicate` relationship starting at `subject`. + + Args: + subject: The subject to start the transitive closure from + predicate: The predicate to follow + remember: A dict of visited nodes + """ + if remember is None: + remember = {} + if subject in remember: + return + remember[subject] = 1 + yield subject + for object in self.objects(subject, predicate): + for o in self.transitive_objects(object, predicate, remember): + yield o + + def transitive_subjects( + self, + predicate: Optional[_PredicateType], + object: Optional[_ObjectType], + remember: Optional[Dict[Optional[_ObjectType], int]] = None, + ) -> Generator[Optional[_ObjectType], None, None]: + """Transitively generate subjects for the ``predicate`` relationship + + Generated subjects belong to the depth first transitive closure of the + `predicate` relationship starting at `object`. + + Args: + predicate: The predicate to follow + object: The object to start the transitive closure from + remember: A dict of visited nodes + """ + if remember is None: + remember = {} + if object in remember: + return + remember[object] = 1 + yield object + for subject in self.subjects(predicate, object): + for s in self.transitive_subjects(predicate, subject, remember): + yield s + + def qname(self, uri: str) -> str: + return self.namespace_manager.qname(uri) + + def compute_qname(self, uri: str, generate: bool = True) -> Tuple[str, URIRef, str]: + return self.namespace_manager.compute_qname(uri, generate) + + def bind( + self, + prefix: Optional[str], + namespace: Any, # noqa: F811 + override: bool = True, + replace: bool = False, + ) -> None: + """Bind prefix to namespace + + If override is True will bind namespace to given prefix even + if namespace was already bound to a different prefix. + + if replace, replace any existing prefix with the new namespace + + Args: + prefix: The prefix to bind + namespace: The namespace to bind the prefix to + override: If True, override any existing prefix binding + replace: If True, replace any existing namespace binding + + Example: + ```python + graph.bind("foaf", "http://xmlns.com/foaf/0.1/") + ``` + """ + # TODO FIXME: This method's behaviour should be simplified and made + # more robust. If the method cannot do what it is asked it should raise + # an exception, it is also unclear why this method has all the + # different modes. It seems to just make it more complex to use, maybe + # it should be clarified when someone will need to use override=False + # and replace=False. And also why silent failure here is preferred over + # raising an exception. + return self.namespace_manager.bind( + prefix, namespace, override=override, replace=replace + ) + + def namespaces(self) -> Generator[Tuple[str, URIRef], None, None]: + """Generator over all the prefix, namespace tuples + + Returns: + Generator yielding prefix, namespace tuples + """ + for prefix, namespace in self.namespace_manager.namespaces(): # noqa: F402 + yield prefix, namespace + + def absolutize(self, uri: str, defrag: int = 1) -> URIRef: + """Turn uri into an absolute URI if it's not one already""" + return self.namespace_manager.absolutize(uri, defrag) + + # no destination and non-None positional encoding + @overload + def serialize( + self, + destination: None, + format: str, + base: Optional[str], + encoding: str, + **args: Any, + ) -> bytes: ... + + # no destination and non-None keyword encoding + @overload + def serialize( + self, + destination: None = ..., + format: str = ..., + base: Optional[str] = ..., + *, + encoding: str, + **args: Any, + ) -> bytes: ... + + # no destination and None encoding + @overload + def serialize( + self, + destination: None = ..., + format: str = ..., + base: Optional[str] = ..., + encoding: None = ..., + **args: Any, + ) -> str: ... + + # non-None destination + @overload + def serialize( + self, + destination: Union[str, pathlib.PurePath, IO[bytes]], + format: str = ..., + base: Optional[str] = ..., + encoding: Optional[str] = ..., + **args: Any, + ) -> Graph: ... + + # fallback + @overload + def serialize( + self, + destination: Optional[Union[str, pathlib.PurePath, IO[bytes]]] = ..., + format: str = ..., + base: Optional[str] = ..., + encoding: Optional[str] = ..., + **args: Any, + ) -> Union[bytes, str, Graph]: ... + + def serialize( + self: _GraphT, + destination: Optional[Union[str, pathlib.PurePath, IO[bytes]]] = None, + format: str = "turtle", + base: Optional[str] = None, + encoding: Optional[str] = None, + **args: Any, + ) -> Union[bytes, str, _GraphT]: + """Serialize the graph. + + Args: + destination: The destination to serialize the graph to. This can be a path as a + string or pathlib.PurePath object, or it can be an IO[bytes] like object. + If this parameter is not supplied the serialized graph will be returned. + format: The format that the output should be written in. This value + references a Serializer plugin. + Format support is managed with [plugins][rdflib.plugin]. + Defaults to "turtle" and some other formats are builtin, + like "xml" and "trix". + See also [serialize module][rdflib.plugins.parsers]. + base: The base IRI for formats that support it. For the turtle format this + will be used as the @base directive. + encoding: Encoding of output. + args: Additional arguments to pass to the Serializer that will be used. + + Returns: + The serialized graph if `destination` is None. The serialized graph is returned + as str if no encoding is specified, and as bytes if an encoding is specified. + + self (i.e. the Graph instance) if `destination` is not None. + """ + + # if base is not given as attribute use the base set for the graph + if base is None: + base = self.base + + serializer = plugin.get(format, Serializer)(self) + stream: IO[bytes] + if destination is None: + stream = BytesIO() + if encoding is None: + serializer.serialize(stream, base=base, encoding="utf-8", **args) + return stream.getvalue().decode("utf-8") + else: + serializer.serialize(stream, base=base, encoding=encoding, **args) + return stream.getvalue() + if hasattr(destination, "write"): + stream = cast(IO[bytes], destination) + serializer.serialize(stream, base=base, encoding=encoding, **args) + else: + if isinstance(destination, pathlib.PurePath): + os_path = str(destination) + else: + location = cast(str, destination) + scheme, netloc, path, params, _query, fragment = urlparse(location) + if scheme == "file": + if netloc != "": + raise ValueError( + f"the file URI {location!r} has an authority component which is not supported" + ) + os_path = url2pathname(path) + else: + os_path = location + with open(os_path, "wb") as stream: + serializer.serialize(stream, base=base, encoding=encoding, **args) + return self + + def print( + self, + format: str = "turtle", + encoding: str = "utf-8", + out: Optional[TextIO] = None, + ) -> None: + print( + self.serialize(None, format=format, encoding=encoding).decode(encoding), + file=out, + flush=True, + ) + + def parse( + self, + source: Optional[ + Union[IO[bytes], TextIO, InputSource, str, bytes, pathlib.PurePath] + ] = None, + publicID: Optional[str] = None, # noqa: N803 + format: Optional[str] = None, + location: Optional[str] = None, + file: Optional[Union[BinaryIO, TextIO]] = None, + data: Optional[Union[str, bytes]] = None, + **args: Any, + ) -> Graph: + """Parse an RDF source adding the resulting triples to the Graph. + + The source is specified using one of source, location, file or data. + + Args: + source: An `xml.sax.xmlreader.InputSource`, file-like object, + `pathlib.Path` like object, or string. In the case of a string the string + is the location of the source. + publicID: The logical URI to use as the document base. If None + specified the document location is used (at least in the case where + there is a document location). This is used as the base URI when + resolving relative URIs in the source document, as defined in `IETF + RFC 3986 `_, + given the source document does not define a base URI. + format: Used if format can not be determined from source, e.g. + file extension or Media Type. Format support is managed + with [plugins][rdflib.plugin]. + Available formats are e.g. "turle", "xml", "n3", "nt" and "trix" + or see [parser module][rdflib.plugins.parsers]. + location: A string indicating the relative or absolute URL of the + source. `Graph`'s absolutize method is used if a relative location + is specified. + file: A file-like object. + data: A string containing the data to be parsed. + args: Additional arguments to pass to the parser. + + Returns: + self, i.e. the Graph instance. + + Example: + ```python + >>> my_data = ''' + ... + ... + ... Example + ... This is really just an example. + ... + ... + ... ''' + >>> import os, tempfile + >>> fd, file_name = tempfile.mkstemp() + >>> f = os.fdopen(fd, "w") + >>> dummy = f.write(my_data) # Returns num bytes written + >>> f.close() + + >>> g = Graph() + >>> result = g.parse(data=my_data, format="application/rdf+xml") + >>> len(g) + 2 + + >>> g = Graph() + >>> result = g.parse(location=file_name, format="application/rdf+xml") + >>> len(g) + 2 + + >>> g = Graph() + >>> with open(file_name, "r") as f: + ... result = g.parse(f, format="application/rdf+xml") + >>> len(g) + 2 + + >>> os.remove(file_name) + + >>> # default turtle parsing + >>> result = g.parse(data=" .") + >>> len(g) + 3 + + ``` + + !!! warning "Caution" + This method can access directly or indirectly requested network or + file resources, for example, when parsing JSON-LD documents with + `@context` directives that point to a network location. + + When processing untrusted or potentially malicious documents, + measures should be taken to restrict network and file access. + + For information on available security measures, see the RDFLib + [Security Considerations](../security_considerations.md) + documentation. + """ + + source = create_input_source( + source=source, + publicID=publicID, + location=location, + file=file, + data=data, + format=format, + ) + if format is None: + format = source.content_type + could_not_guess_format = False + if format is None: + if ( + hasattr(source, "file") + and getattr(source.file, "name", None) + and isinstance(source.file.name, str) + ): + format = rdflib.util.guess_format(source.file.name) + if format is None: + format = "turtle" + could_not_guess_format = True + try: + parser = plugin.get(format, Parser)() + except plugin.PluginException: + # Handle the case when a URLInputSource returns RDF but with the headers + # as a format that does not exist in the plugin system. + # Use guess_format to guess the format based on the input's file suffix. + format = rdflib.util.guess_format( + source if not isinstance(source, InputSource) else str(source) + ) + if format is None: + raise + parser = plugin.get(format, Parser)() + try: + # TODO FIXME: Parser.parse should have **kwargs argument. + parser.parse(source, self, **args) + except SyntaxError as se: + if could_not_guess_format: + raise ParserError( + "Could not guess RDF format for %r from file extension so tried Turtle but failed." + "You can explicitly specify format using the format argument." + % source + ) + else: + raise se + finally: + if source.auto_close: + source.close() + return self + + def query( + self, + query_object: Union[str, Query], + processor: Union[str, query.Processor] = "sparql", + result: Union[str, Type[query.Result]] = "sparql", + initNs: Optional[Mapping[str, Any]] = None, # noqa: N803 + initBindings: Optional[Mapping[str, Identifier]] = None, # noqa: N803 + use_store_provided: bool = True, + **kwargs: Any, + ) -> query.Result: + """ + Query this graph. + + Args: + query_object: The query string or object to execute. + processor: The query processor to use. Default is "sparql". + result: The result format to use. Default is "sparql". + initNs: Initial namespaces to use for resolving prefixes in the query. + If none are given, the namespaces from the graph's namespace manager are used. + initBindings: Initial variable bindings to use. A type of 'prepared queries' + can be realized by providing these bindings. + use_store_provided: Whether to use the store's query method if available. + kwargs: Additional arguments to pass to the query processor. + + Returns: + A [`rdflib.query.Result`][`rdflib.query.Result`] instance. + + !!! warning "Caution" + This method can access indirectly requested network endpoints, for + example, query processing will attempt to access network endpoints + specified in `SERVICE` directives. + + When processing untrusted or potentially malicious queries, measures + should be taken to restrict network and file access. + + For information on available security measures, see the RDFLib + [Security Considerations](../security_considerations.md) + documentation. + """ + + initBindings = initBindings or {} # noqa: N806 + initNs = initNs or dict(self.namespaces()) # noqa: N806 + + if self.default_union: + query_graph = "__UNION__" + elif isinstance(self, ConjunctiveGraph): + query_graph = self.default_context.identifier + else: + query_graph = self.identifier + if hasattr(self.store, "query") and use_store_provided: + try: + return self.store.query( + query_object, + initNs, + initBindings, + query_graph, + **kwargs, + ) + except NotImplementedError: + pass # store has no own implementation + + if not isinstance(result, query.Result): + result = plugin.get(cast(str, result), query.Result) + if not isinstance(processor, query.Processor): + processor = plugin.get(processor, query.Processor)(self) + + # type error: Argument 1 to "Result" has incompatible type "Mapping[str, Any]"; expected "str" + return result(processor.query(query_object, initBindings, initNs, **kwargs)) # type: ignore[arg-type] + + def update( + self, + update_object: Union[Update, str], + processor: Union[str, rdflib.query.UpdateProcessor] = "sparql", + initNs: Optional[Mapping[str, Any]] = None, # noqa: N803 + initBindings: Optional[Mapping[str, Identifier]] = None, # noqa: N803 + use_store_provided: bool = True, + **kwargs: Any, + ) -> None: + """Update this graph with the given update query. + + Args: + update_object: The update query string or object to execute. + processor: The update processor to use. Default is "sparql". + initNs: Initial namespaces to use for resolving prefixes in the query. + If none are given, the namespaces from the graph's namespace manager are used. + initBindings: Initial variable bindings to use. + use_store_provided: Whether to use the store's update method if available. + kwargs: Additional arguments to pass to the update processor. + + !!! warning "Caution" + This method can access indirectly requested network endpoints, for + example, query processing will attempt to access network endpoints + specified in `SERVICE` directives. + + When processing untrusted or potentially malicious queries, measures + should be taken to restrict network and file access. + + For information on available security measures, see the RDFLib + Security Considerations documentation. + """ + initBindings = initBindings or {} # noqa: N806 + initNs = initNs or dict(self.namespaces()) # noqa: N806 + + if self.default_union: + query_graph = "__UNION__" + elif isinstance(self, ConjunctiveGraph): + query_graph = self.default_context.identifier + else: + query_graph = self.identifier + + if hasattr(self.store, "update") and use_store_provided: + try: + return self.store.update( + update_object, + initNs, + initBindings, + query_graph, + **kwargs, + ) + except NotImplementedError: + pass # store has no own implementation + + if not isinstance(processor, query.UpdateProcessor): + processor = plugin.get(processor, query.UpdateProcessor)(self) + + return processor.update(update_object, initBindings, initNs, **kwargs) + + def n3(self, namespace_manager: Optional[NamespaceManager] = None) -> str: + """Return an n3 identifier for the Graph""" + return "[%s]" % self.identifier.n3(namespace_manager=namespace_manager) + + def __reduce__(self) -> Tuple[Type[Graph], Tuple[Store, _ContextIdentifierType]]: + return ( + Graph, + ( + self.store, + self.identifier, + ), + ) + + def isomorphic(self, other: Graph) -> bool: + """Check if this graph is isomorphic to another graph. + + Performs a basic check if these graphs are the same. + If no BNodes are involved, this is accurate. + + Args: + other: The graph to compare with. + + Returns: + True if the graphs are isomorphic, False otherwise. + + Note: + This is only an approximation. See rdflib.compare for a correct + implementation of isomorphism checks. + """ + # TODO: this is only an approximation. + if len(self) != len(other): + return False + for s, p, o in self: + if not isinstance(s, BNode) and not isinstance(o, BNode): + if not (s, p, o) in other: # noqa: E713 + return False + for s, p, o in other: + if not isinstance(s, BNode) and not isinstance(o, BNode): + if not (s, p, o) in self: # noqa: E713 + return False + # TODO: very well could be a false positive at this point yet. + return True + + def connected(self) -> bool: + """Check if the Graph is connected. + + The Graph is considered undirectional. + + Returns: + True if all nodes have been visited and there are no unvisited nodes left, + False otherwise. + + Note: + Performs a search on the Graph, starting from a random node. Then + iteratively goes depth-first through the triplets where the node is + subject and object. + """ + all_nodes = list(self.all_nodes()) + discovered = [] + + # take a random one, could also always take the first one, doesn't + # really matter. + if not all_nodes: + return False + + visiting = [all_nodes[random.randrange(len(all_nodes))]] + while visiting: + x = visiting.pop() + if x not in discovered: + discovered.append(x) + for new_x in self.objects(subject=x): + if new_x not in discovered and new_x not in visiting: + visiting.append(new_x) + for new_x in self.subjects(object=x): + if new_x not in discovered and new_x not in visiting: + visiting.append(new_x) + + # optimisation by only considering length, since no new objects can + # be introduced anywhere. + if len(all_nodes) == len(discovered): + return True + else: + return False + + def all_nodes(self) -> Set[Node]: + res = set(self.objects()) + res.update(self.subjects()) + return res + + def collection(self, identifier: _SubjectType) -> Collection: + """Create a new `Collection` instance. + + Args: + identifier: A URIRef or BNode instance. + + Returns: + A new Collection instance. + + Example: + ```python + >>> graph = Graph() + >>> uri = URIRef("http://example.org/resource") + >>> collection = graph.collection(uri) + >>> assert isinstance(collection, Collection) + >>> assert collection.uri is uri + >>> assert collection.graph is graph + >>> collection += [ Literal(1), Literal(2) ] + + ``` + """ + + return Collection(self, identifier) + + def resource(self, identifier: Union[Node, str]) -> Resource: + """Create a new ``Resource`` instance. + + Args: + identifier: A URIRef or BNode instance. + + Returns: + A new Resource instance. + + Example: + ```python + >>> graph = Graph() + >>> uri = URIRef("http://example.org/resource") + >>> resource = graph.resource(uri) + >>> assert isinstance(resource, Resource) + >>> assert resource.identifier is uri + >>> assert resource.graph is graph + + ``` + """ + if not isinstance(identifier, Node): + identifier = URIRef(identifier) + return Resource(self, identifier) + + def _process_skolem_tuples( + self, target: Graph, func: Callable[[_TripleType], _TripleType] + ) -> None: + for t in self.triples((None, None, None)): + target.add(func(t)) + + def skolemize( + self, + new_graph: Optional[Graph] = None, + bnode: Optional[BNode] = None, + authority: Optional[str] = None, + basepath: Optional[str] = None, + ) -> Graph: + def do_skolemize(bnode: BNode, t: _TripleType) -> _TripleType: + (s, p, o) = t + if s == bnode: + if TYPE_CHECKING: + assert isinstance(s, BNode) + s = s.skolemize(authority=authority, basepath=basepath) + if o == bnode: + if TYPE_CHECKING: + assert isinstance(o, BNode) + o = o.skolemize(authority=authority, basepath=basepath) + return s, p, o + + def do_skolemize2(t: _TripleType) -> _TripleType: + (s, p, o) = t + if isinstance(s, BNode): + s = s.skolemize(authority=authority, basepath=basepath) + if isinstance(o, BNode): + o = o.skolemize(authority=authority, basepath=basepath) + return s, p, o + + retval = Graph() if new_graph is None else new_graph + + if bnode is None: + self._process_skolem_tuples(retval, do_skolemize2) + elif isinstance(bnode, BNode): + # type error: Argument 1 to "do_skolemize" has incompatible type "Optional[BNode]"; expected "BNode" + self._process_skolem_tuples(retval, lambda t: do_skolemize(bnode, t)) # type: ignore[arg-type, unused-ignore] + + return retval + + def de_skolemize( + self, new_graph: Optional[Graph] = None, uriref: Optional[URIRef] = None + ) -> Graph: + def do_de_skolemize(uriref: URIRef, t: _TripleType) -> _TripleType: + (s, p, o) = t + if s == uriref: + if TYPE_CHECKING: + assert isinstance(s, URIRef) + s = s.de_skolemize() + if o == uriref: + if TYPE_CHECKING: + assert isinstance(o, URIRef) + o = o.de_skolemize() + return s, p, o + + def do_de_skolemize2(t: _TripleType) -> _TripleType: + (s, p, o) = t + + if RDFLibGenid._is_rdflib_skolem(s): + # type error: Argument 1 to "RDFLibGenid" has incompatible type "Node"; expected "str" + s = RDFLibGenid(s).de_skolemize() # type: ignore[arg-type] + elif Genid._is_external_skolem(s): + # type error: Argument 1 to "Genid" has incompatible type "Node"; expected "str" + s = Genid(s).de_skolemize() # type: ignore[arg-type] + + if isinstance(o, URIRef): + if RDFLibGenid._is_rdflib_skolem(o): + o = RDFLibGenid(o).de_skolemize() + elif Genid._is_external_skolem(o): + o = Genid(o).de_skolemize() + + return s, p, o + + retval = Graph() if new_graph is None else new_graph + + if uriref is None: + self._process_skolem_tuples(retval, do_de_skolemize2) + elif isinstance(uriref, Genid): + # type error: Argument 1 to "do_de_skolemize" has incompatible type "Optional[URIRef]"; expected "URIRef" + self._process_skolem_tuples(retval, lambda t: do_de_skolemize(uriref, t)) # type: ignore[arg-type, unused-ignore] + + return retval + + def cbd( + self, + resource: _SubjectType, + *, + target_graph: Graph | None = None, + include_reifications: bool = True, + ) -> Graph: + """Retrieves the Concise Bounded Description of a Resource from a Graph. + + Args: + resource: A URIRef object, the Resource to query for. + target_graph: Optionally, a graph to add the CBD to; otherwise, + a new graph is created for the CBD. + include_reifications: If False, skip Rule 3 to exclude reified statements (default: True) + + Returns: + A Graph, subgraph of self if no graph was provided otherwise the provided graph. + + Note: + Concise Bounded Description (CBD) is defined as: + + Given a particular node (the starting node) in a particular RDF graph (the source graph), + a subgraph of that particular graph, taken to comprise a concise bounded description of + the resource denoted by the starting node, can be identified as follows: + + 1. Include in the subgraph all statements in the source graph where the subject of the + statement is the starting node; + + 2. Recursively, for all statements identified in the subgraph thus far having a blank + node object, include in the subgraph all statements in the source graph where the + subject of the statement is the blank node in question and which are not already + included in the subgraph. + + 3. Recursively, for all statements included in the subgraph thus far, for all + reifications of each statement in the source graph, include the concise bounded + description beginning from the rdf:Statement node of each reification. + + This results in a subgraph where the object nodes are either URI references, literals, + or blank nodes not serving as the subject of any statement in the graph. + + If include_reifications is set to False, Rule 3 above will be skipped, meaning reified statements + will not be included in the CBD. This can improve performance when reified statements are not present + or can be used to deliberately exclude them from the result. + """ + # If no target graph is provided, create a new Graph to hold the CBD. + if target_graph is None: + subgraph = Graph() + else: + subgraph = target_graph + + def add_to_cbd(uri: _SubjectType) -> None: + # Rule 3 Preparation: + # If reifications are to be included, build an index mapping triples with + # this subject to the set of reification nodes (rdf:Statement nodes) that reify them. + if include_reifications: + reif_index: dict[_TripleType, set[_SubjectType]] = {} + for stmt in self.subjects(RDF.subject, uri): + p: _PredicateType = self.value(stmt, RDF.predicate) # type: ignore[assignment] + o = self.value(stmt, RDF.object) + if p is not None and o is not None: + triple = (uri, p, o) + if triple not in reif_index: + reif_index[triple] = {stmt} + else: + reif_index[triple].add(stmt) + + # For all triples where the subject is the current subject (Rule 1) + for s, p, o in self.triples((uri, None, None)): + # Add the triple to the CBD subgraph + subgraph.add((s, p, o)) + # If the object is a blank node, recursively add its CBD (Rule 2) + if type(o) is BNode and (o, None, None) not in subgraph: + add_to_cbd(o) + + # If including reifications (Rule 3): + if include_reifications: + # For each reification node of this triple, recursively add its CBD + stmts = reif_index.get((s, p, o), set()) + for stmt in stmts: + if (stmt, None, None) not in subgraph: + add_to_cbd(stmt) + + # Start the CBD construction from the given resource + add_to_cbd(resource) + + return subgraph + + +_ContextType = Graph + + +class ConjunctiveGraph(Graph): + """A ConjunctiveGraph is an (unnamed) aggregation of all the named + graphs in a store. + + !!! warning "Deprecation notice" + ConjunctiveGraph is deprecated, use [`rdflib.graph.Dataset`][rdflib.graph.Dataset] instead. + + It has a `default` graph, whose name is associated with the + graph throughout its life. Constructor can take an identifier + to use as the name of this default graph or it will assign a + BNode. + + All methods that add triples work against this default graph. + + All queries are carried out against the union of all graphs. + """ + + _default_context: _ContextType + + def __init__( + self, + store: Union[Store, str] = "default", + identifier: Optional[Union[IdentifiedNode, str]] = None, + default_graph_base: Optional[str] = None, + ): + super(ConjunctiveGraph, self).__init__(store, identifier=identifier) + + if type(self) is ConjunctiveGraph: + warnings.warn( + "ConjunctiveGraph is deprecated, use Dataset instead.", + DeprecationWarning, + stacklevel=2, + ) + + assert self.store.context_aware, ( + "ConjunctiveGraph must be backed by" " a context aware store." + ) + self.context_aware = True + self.default_union = True # Conjunctive! + self._default_context: _ContextType = Graph( + store=self.store, identifier=identifier or BNode(), base=default_graph_base + ) + + @property + def default_context(self): + return self._default_context + + @default_context.setter + def default_context(self, value): + self._default_context = value + + def __str__(self) -> str: + pattern = ( + "[a rdflib:ConjunctiveGraph;rdflib:storage " + "[a rdflib:Store;rdfs:label '%s']]" + ) + return pattern % self.store.__class__.__name__ + + @overload + def _spoc( + self, + triple_or_quad: _QuadType, + default: bool = False, + ) -> _QuadType: ... + + @overload + def _spoc( + self, + triple_or_quad: Union[_TripleType, _OptionalQuadType], + default: bool = False, + ) -> _OptionalQuadType: ... + + @overload + def _spoc( + self, + triple_or_quad: None, + default: bool = False, + ) -> Tuple[None, None, None, Optional[Graph]]: ... + + @overload + def _spoc( + self, + triple_or_quad: Optional[_TripleOrQuadPatternType], + default: bool = False, + ) -> _QuadPatternType: ... + + @overload + def _spoc( + self, + triple_or_quad: _TripleOrQuadSelectorType, + default: bool = False, + ) -> _QuadSelectorType: ... + + @overload + def _spoc( + self, + triple_or_quad: Optional[_TripleOrQuadSelectorType], + default: bool = False, + ) -> _QuadSelectorType: ... + + def _spoc( + self, + triple_or_quad: Optional[_TripleOrQuadSelectorType], + default: bool = False, + ) -> _QuadSelectorType: + """ + helper method for having methods that support + either triples or quads + """ + if triple_or_quad is None: + return (None, None, None, self.default_context if default else None) + if len(triple_or_quad) == 3: + c = self.default_context if default else None + # type error: Too many values to unpack (3 expected, 4 provided) + (s, p, o) = triple_or_quad # type: ignore[misc, unused-ignore] + elif len(triple_or_quad) == 4: + # type error: Need more than 3 values to unpack (4 expected) + (s, p, o, c) = triple_or_quad # type: ignore[misc, unused-ignore] + c = self._graph(c) + return s, p, o, c + + def __contains__(self, triple_or_quad: _TripleOrQuadSelectorType) -> bool: + """Support for 'triple/quad in graph' syntax""" + s, p, o, c = self._spoc(triple_or_quad) + for t in self.triples((s, p, o), context=c): + return True + return False + + def add( + self: _ConjunctiveGraphT, + triple_or_quad: _TripleOrOptionalQuadType, + ) -> _ConjunctiveGraphT: + """Add a triple or quad to the store. + + if a triple is given it is added to the default context + """ + + s, p, o, c = self._spoc(triple_or_quad, default=True) + + _assertnode(s, p, o) + + # type error: Argument "context" to "add" of "Store" has incompatible type "Optional[Graph]"; expected "Graph" + self.store.add((s, p, o), context=c, quoted=False) # type: ignore[arg-type] + return self + + @overload + def _graph(self, c: Union[Graph, _ContextIdentifierType, str]) -> Graph: ... + + @overload + def _graph(self, c: None) -> None: ... + + def _graph( + self, + c: Optional[Union[Graph, _ContextIdentifierType, str]], + ) -> Optional[Graph]: + if c is None: + return None + if isinstance(c, (Dataset, ConjunctiveGraph)): + # Preserve the old behaviour for datasets. + return c + if isinstance(c, Graph): + # Resolve to a graph backed by this dataset store. + return self.get_context(c.identifier) + return self.get_context(c) + + def addN( # noqa: N802 + self: _ConjunctiveGraphT, quads: Iterable[_QuadType] + ) -> _ConjunctiveGraphT: + """Add a sequence of triples with context""" + + self.store.addN( + (s, p, o, self._graph(c)) for s, p, o, c in quads if _assertnode(s, p, o) + ) + return self + + # type error: Argument 1 of "remove" is incompatible with supertype "Graph"; supertype defines the argument type as "Tuple[Optional[Node], Optional[Node], Optional[Node]]" + def remove(self: _ConjunctiveGraphT, triple_or_quad: _TripleOrOptionalQuadType) -> _ConjunctiveGraphT: # type: ignore[override] + """Removes a triple or quads + + if a triple is given it is removed from all contexts + a quad is removed from the given context only + """ + s, p, o, c = self._spoc(triple_or_quad) + + self.store.remove((s, p, o), context=c) + return self + + @overload + def triples( + self, + triple_or_quad: _TripleOrQuadPatternType, + context: Optional[_ContextType] = ..., + ) -> Generator[_TripleType, None, None]: ... + + @overload + def triples( + self, + triple_or_quad: _TripleOrQuadPathPatternType, + context: Optional[_ContextType] = ..., + ) -> Generator[_TriplePathType, None, None]: ... + + @overload + def triples( + self, + triple_or_quad: _TripleOrQuadSelectorType, + context: Optional[_ContextType] = ..., + ) -> Generator[_TripleOrTriplePathType, None, None]: ... + + def triples( + self, + triple_or_quad: _TripleOrQuadSelectorType, + context: Optional[_ContextType] = None, + ) -> Generator[_TripleOrTriplePathType, None, None]: + """Iterate over all the triples in the entire conjunctive graph + + For legacy reasons, this can take the context to query either + as a fourth element of the quad, or as the explicit context + keyword parameter. The kw param takes precedence. + """ + + s, p, o, c = self._spoc(triple_or_quad) + context = self._graph(context or c) + + if self.default_union: + if context == self.default_context: + context = None + else: + if context is None: + context = self.default_context + + if isinstance(p, Path): + if context is None: + context = self + + for s, o in p.eval(context, s, o): + yield s, p, o + else: + for (s, p, o), cg in self.store.triples((s, p, o), context=context): + yield s, p, o + + def quads( + self, triple_or_quad: Optional[_TripleOrQuadPatternType] = None + ) -> Generator[_OptionalQuadType, None, None]: + """Iterate over all the quads in the entire conjunctive graph""" + + s, p, o, c = self._spoc(triple_or_quad) + + for (s, p, o), cg in self.store.triples((s, p, o), context=c): + for ctx in cg: + yield s, p, o, ctx + + def triples_choices( + self, + triple: _TripleChoiceType, + context: Optional[_ContextType] = None, + ) -> Generator[_TripleType, None, None]: + """Iterate over all the triples in the entire conjunctive graph""" + s, p, o = triple + if context is None: + if not self.default_union: + context = self.default_context + else: + context = self._graph(context) + # type error: Argument 1 to "triples_choices" of "Store" has incompatible type "Tuple[Union[List[Node], Node], Union[Node, List[Node]], Union[Node, List[Node]]]"; expected "Union[Tuple[List[Node], Node, Node], Tuple[Node, List[Node], Node], Tuple[Node, Node, List[Node]]]" + # type error note: unpacking discards type info + for (s1, p1, o1), cg in self.store.triples_choices((s, p, o), context=context): # type: ignore[arg-type] + yield s1, p1, o1 + + def __len__(self) -> int: + """Number of triples in the entire conjunctive graph""" + return self.store.__len__() + + def contexts( + self, triple: Optional[_TripleType] = None + ) -> Generator[_ContextType, None, None]: + """Iterate over all contexts in the graph + + If triple is specified, iterate over all contexts the triple is in. + """ + for context in self.store.contexts(triple): + if isinstance(context, Graph): + # TODO: One of these should never happen and probably + # should raise an exception rather than smoothing over + # the weirdness - see #225 + yield context + else: + # type error: Statement is unreachable + yield self.get_context(context) # type: ignore[unreachable] + + def get_graph(self, identifier: _ContextIdentifierType) -> Union[Graph, None]: + """Returns the graph identified by given identifier""" + return [x for x in self.contexts() if x.identifier == identifier][0] + + def get_context( + self, + identifier: Optional[Union[_ContextIdentifierType, str]], + quoted: bool = False, + base: Optional[str] = None, + ) -> Graph: + """Return a context graph for the given identifier + + identifier must be a URIRef or BNode. + """ + return Graph( + store=self.store, + identifier=identifier, + namespace_manager=self.namespace_manager, + base=base, + ) + + def remove_context(self, context: _ContextType) -> None: + """Removes the given context from the graph""" + self.store.remove((None, None, None), context) + + def context_id(self, uri: str, context_id: Optional[str] = None) -> URIRef: + """URI#context""" + uri = uri.split("#", 1)[0] + if context_id is None: + context_id = "#context" + return URIRef(context_id, base=uri) + + def parse( + self, + source: Optional[ + Union[IO[bytes], TextIO, InputSource, str, bytes, pathlib.PurePath] + ] = None, + publicID: Optional[str] = None, # noqa: N803 + format: Optional[str] = None, + location: Optional[str] = None, + file: Optional[Union[BinaryIO, TextIO]] = None, + data: Optional[Union[str, bytes]] = None, + **args: Any, + ) -> Graph: + """Parse source adding the resulting triples to its own context (sub graph + of this graph). + + See [`rdflib.graph.Graph.parse`][rdflib.graph.Graph.parse] for documentation on arguments. + + Args: + source: The source to parse + publicID: The public ID of the source + format: The format of the source + location: The location of the source + file: The file object to parse + data: The data to parse + **args: Additional arguments + + Returns: + The graph into which the source was parsed. In the case of n3 it returns + the root context. + + Note: + If the source is in a format that does not support named graphs its triples + will be added to the default graph (i.e. ConjunctiveGraph.default_context). + + !!! warning "Caution" + This method can access directly or indirectly requested network or + file resources, for example, when parsing JSON-LD documents with + `@context` directives that point to a network location. + + When processing untrusted or potentially malicious documents, + measures should be taken to restrict network and file access. + + For information on available security measures, see the RDFLib + Security Considerations documentation. + + !!! example "Changed in 7.0" + The `publicID` argument is no longer used as the identifier (i.e. name) + of the default graph as was the case before version 7.0. In the case of + sources that do not support named graphs, the `publicID` parameter will + also not be used as the name for the graph that the data is loaded into, + and instead the triples from sources that do not support named graphs will + be loaded into the default graph (i.e. ConjunctiveGraph.default_context). + """ + + source = create_input_source( + source=source, + publicID=publicID, + location=location, + file=file, + data=data, + format=format, + ) + + # NOTE on type hint: `xml.sax.xmlreader.InputSource.getPublicId` has no + # type annotations but given that systemId should be a string, and + # given that there is no specific mention of type for publicId, it + # seems reasonable to assume it should also be a string. Furthermore, + # create_input_source will ensure that publicId is not None, though it + # would be good if this guarantee was made more explicit i.e. by type + # hint on InputSource (TODO/FIXME). + + context = self.default_context + context.parse(source, publicID=publicID, format=format, **args) + return self + + def __reduce__(self) -> Tuple[Type[Graph], Tuple[Store, _ContextIdentifierType]]: + return ConjunctiveGraph, (self.store, self.identifier) + + +DATASET_DEFAULT_GRAPH_ID = URIRef("urn:x-rdflib:default") + + +class Dataset(ConjunctiveGraph): + """ + An RDFLib Dataset is an object that stores multiple Named Graphs - instances of + RDFLib Graph identified by IRI - within it and allows whole-of-dataset or single + Graph use. + + RDFLib's Dataset class is based on the [RDF 1.2. 'Dataset' definition](https://www.w3.org/TR/rdf12-datasets/): + + An RDF dataset is a collection of RDF graphs, and comprises: + + - Exactly one default graph, being an RDF graph. The default graph does not + have a name and MAY be empty. + - Zero or more named graphs. Each named graph is a pair consisting of an IRI or + a blank node (the graph name), and an RDF graph. Graph names are unique + within an RDF dataset. + + Accordingly, a Dataset allows for `Graph` objects to be added to it with + [`URIRef`][rdflib.term.URIRef] or [`BNode`][rdflib.term.BNode] identifiers and always + creats a default graph with the [`URIRef`][rdflib.term.URIRef] identifier + `urn:x-rdflib:default`. + + Dataset extends Graph's Subject, Predicate, Object (s, p, o) 'triple' + structure to include a graph identifier - archaically called Context - producing + 'quads' of s, p, o, g. + + Triples, or quads, can be added to a Dataset. Triples, or quads with the graph + identifer :code:`urn:x-rdflib:default` go into the default graph. + + !!! warning "Deprecation notice" + Dataset builds on the `ConjunctiveGraph` class but that class's direct + use is now deprecated (since RDFLib 7.x) and it should not be used. + `ConjunctiveGraph` will be removed from future RDFLib versions. + + Examples of usage and see also the `examples/datast.py` file: + + ```python + >>> # Create a new Dataset + >>> ds = Dataset() + >>> # simple triples goes to default graph + >>> ds.add(( + ... URIRef("http://example.org/a"), + ... URIRef("http://www.example.org/b"), + ... Literal("foo") + ... )) # doctest: +ELLIPSIS + )> + + >>> # Create a graph in the dataset, if the graph name has already been + >>> # used, the corresponding graph will be returned + >>> # (ie, the Dataset keeps track of the constituent graphs) + >>> g = ds.graph(URIRef("http://www.example.com/gr")) + + >>> # add triples to the new graph as usual + >>> g.add(( + ... URIRef("http://example.org/x"), + ... URIRef("http://example.org/y"), + ... Literal("bar") + ... )) # doctest: +ELLIPSIS + )> + >>> # alternatively: add a quad to the dataset -> goes to the graph + >>> ds.add(( + ... URIRef("http://example.org/x"), + ... URIRef("http://example.org/z"), + ... Literal("foo-bar"), + ... g + ... )) # doctest: +ELLIPSIS + )> + + >>> # querying triples return them all regardless of the graph + >>> for t in ds.triples((None,None,None)): # doctest: +SKIP + ... print(t) # doctest: +NORMALIZE_WHITESPACE + (rdflib.term.URIRef("http://example.org/a"), + rdflib.term.URIRef("http://www.example.org/b"), + rdflib.term.Literal("foo")) + (rdflib.term.URIRef("http://example.org/x"), + rdflib.term.URIRef("http://example.org/z"), + rdflib.term.Literal("foo-bar")) + (rdflib.term.URIRef("http://example.org/x"), + rdflib.term.URIRef("http://example.org/y"), + rdflib.term.Literal("bar")) + + >>> # querying quads() return quads; the fourth argument can be unrestricted + >>> # (None) or restricted to a graph + >>> for q in ds.quads((None, None, None, None)): # doctest: +SKIP + ... print(q) # doctest: +NORMALIZE_WHITESPACE + (rdflib.term.URIRef("http://example.org/a"), + rdflib.term.URIRef("http://www.example.org/b"), + rdflib.term.Literal("foo"), + None) + (rdflib.term.URIRef("http://example.org/x"), + rdflib.term.URIRef("http://example.org/y"), + rdflib.term.Literal("bar"), + rdflib.term.URIRef("http://www.example.com/gr")) + (rdflib.term.URIRef("http://example.org/x"), + rdflib.term.URIRef("http://example.org/z"), + rdflib.term.Literal("foo-bar"), + rdflib.term.URIRef("http://www.example.com/gr")) + + >>> # unrestricted looping is equivalent to iterating over the entire Dataset + >>> for q in ds: # doctest: +SKIP + ... print(q) # doctest: +NORMALIZE_WHITESPACE + (rdflib.term.URIRef("http://example.org/a"), + rdflib.term.URIRef("http://www.example.org/b"), + rdflib.term.Literal("foo"), + None) + (rdflib.term.URIRef("http://example.org/x"), + rdflib.term.URIRef("http://example.org/y"), + rdflib.term.Literal("bar"), + rdflib.term.URIRef("http://www.example.com/gr")) + (rdflib.term.URIRef("http://example.org/x"), + rdflib.term.URIRef("http://example.org/z"), + rdflib.term.Literal("foo-bar"), + rdflib.term.URIRef("http://www.example.com/gr")) + + >>> # resticting iteration to a graph: + >>> for q in ds.quads((None, None, None, g)): # doctest: +SKIP + ... print(q) # doctest: +NORMALIZE_WHITESPACE + (rdflib.term.URIRef("http://example.org/x"), + rdflib.term.URIRef("http://example.org/y"), + rdflib.term.Literal("bar"), + rdflib.term.URIRef("http://www.example.com/gr")) + (rdflib.term.URIRef("http://example.org/x"), + rdflib.term.URIRef("http://example.org/z"), + rdflib.term.Literal("foo-bar"), + rdflib.term.URIRef("http://www.example.com/gr")) + >>> # Note that in the call above - + >>> # ds.quads((None,None,None,"http://www.example.com/gr")) + >>> # would have been accepted, too + + >>> # graph names in the dataset can be queried: + >>> for c in ds.graphs(): # doctest: +SKIP + ... print(c.identifier) # doctest: + urn:x-rdflib:default + http://www.example.com/gr + >>> # A graph can be created without specifying a name; a skolemized genid + >>> # is created on the fly + >>> h = ds.graph() + >>> for c in ds.graphs(): # doctest: +SKIP + ... print(c) # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS + DEFAULT + https://rdflib.github.io/.well-known/genid/rdflib/N... + http://www.example.com/gr + >>> # Note that the Dataset.graphs() call returns names of empty graphs, + >>> # too. This can be restricted: + >>> for c in ds.graphs(empty=False): # doctest: +SKIP + ... print(c) # doctest: +NORMALIZE_WHITESPACE + DEFAULT + http://www.example.com/gr + + >>> # a graph can also be removed from a dataset via ds.remove_graph(g) + ``` + + !!! example "New in version 4.0" + """ + + def __init__( + self, + store: Union[Store, str] = "default", + default_union: bool = False, + default_graph_base: Optional[str] = None, + ): + super(Dataset, self).__init__(store=store, identifier=None) + + if not self.store.graph_aware: + raise Exception("Dataset must be backed by a graph-aware store!") + self._default_context = Graph( + store=self.store, + identifier=DATASET_DEFAULT_GRAPH_ID, + base=default_graph_base, + ) + + self.default_union = default_union + + @property + def default_context(self): + warnings.warn( + "Dataset.default_context is deprecated, use Dataset.default_graph instead.", + DeprecationWarning, + stacklevel=2, + ) + return self._default_context + + @default_context.setter + def default_context(self, value): + warnings.warn( + "Dataset.default_context is deprecated, use Dataset.default_graph instead.", + DeprecationWarning, + stacklevel=2, + ) + self._default_context = value + + @property + def default_graph(self): + return self._default_context + + @default_graph.setter + def default_graph(self, value): + self._default_context = value + + @property + def identifier(self): + warnings.warn( + "Dataset.identifier is deprecated and will be removed in future versions.", + DeprecationWarning, + stacklevel=2, + ) + return super(Dataset, self).identifier + + def __str__(self) -> str: + pattern = ( + "[a rdflib:Dataset;rdflib:storage " "[a rdflib:Store;rdfs:label '%s']]" + ) + return pattern % self.store.__class__.__name__ + + # type error: Return type "Tuple[Type[Dataset], Tuple[Store, bool]]" of "__reduce__" incompatible with return type "Tuple[Type[Graph], Tuple[Store, IdentifiedNode]]" in supertype "ConjunctiveGraph" + # type error: Return type "Tuple[Type[Dataset], Tuple[Store, bool]]" of "__reduce__" incompatible with return type "Tuple[Type[Graph], Tuple[Store, IdentifiedNode]]" in supertype "Graph" + def __reduce__(self) -> Tuple[Type[Dataset], Tuple[Store, bool]]: # type: ignore[override] + return (type(self), (self.store, self.default_union)) + + def __getstate__(self) -> Tuple[Store, _ContextIdentifierType, _ContextType, bool]: + return self.store, self.identifier, self.default_graph, self.default_union + + def __setstate__( + self, state: Tuple[Store, _ContextIdentifierType, _ContextType, bool] + ) -> None: + # type error: Property "store" defined in "Graph" is read-only + # type error: Property "identifier" defined in "Graph" is read-only + self.store, self.identifier, self.default_graph, self.default_union = state # type: ignore[misc] + + def __iadd__(self: _DatasetT, other: Iterable[_QuadType]) -> _DatasetT: # type: ignore[override, misc] + """Add all quads in Dataset other to Dataset. + BNode IDs are not changed.""" + self.addN((s, p, o, g) for s, p, o, g in other) + return self + + def graph( + self, + identifier: Optional[Union[_ContextIdentifierType, _ContextType, str]] = None, + base: Optional[str] = None, + ) -> Graph: + if identifier is None: + from rdflib.term import _SKOLEM_DEFAULT_AUTHORITY, rdflib_skolem_genid + + self.bind( + "genid", + _SKOLEM_DEFAULT_AUTHORITY + rdflib_skolem_genid, + override=False, + ) + identifier = BNode().skolemize() + + graph_to_copy: Optional[Graph] = None + if isinstance(identifier, Graph) and not isinstance( + identifier, (Dataset, ConjunctiveGraph) + ): + # Preserve #3259 semantics: importing an external graph through + # Dataset.graph()/add_graph() should copy its statements. + graph_to_copy = identifier + + g = self._graph(identifier) + if graph_to_copy is not None: + g.__iadd__(graph_to_copy) + g.base = base + + self.store.add_graph(g) + return g + + def parse( + self, + source: Optional[ + Union[IO[bytes], TextIO, InputSource, str, bytes, pathlib.PurePath] + ] = None, + publicID: Optional[str] = None, # noqa: N803 + format: Optional[str] = None, + location: Optional[str] = None, + file: Optional[Union[BinaryIO, TextIO]] = None, + data: Optional[Union[str, bytes]] = None, + **args: Any, + ) -> Dataset: + """Parse an RDF source adding the resulting triples to the Graph. + + Args: + source: The source to parse. See rdflib.graph.Graph.parse for details. + publicID: The public ID of the source. + format: The format of the source. + location: The location of the source. + file: The file object to parse. + data: The data to parse. + **args: Additional arguments. + + Returns: + The graph that the source was parsed into. + + Note: + The source is specified using one of source, location, file or data. + + If the source is in a format that does not support named graphs its triples + will be added to the default graph + (i.e. :attr:`.Dataset.default_graph`). + If the source is in a format that does not support named graphs its triples + will be added to the default graph (i.e. Dataset.default_graph). + + !!! warning "Caution" + This method can access directly or indirectly requested network or + file resources, for example, when parsing JSON-LD documents with + `@context` directives that point to a network location. + + When processing untrusted or potentially malicious documents, + measures should be taken to restrict network and file access. + + For information on available security measures, see the RDFLib + Security Considerations documentation. + + !!! example "Changed in 7.0" + The `publicID` argument is no longer used as the identifier (i.e. name) + of the default graph as was the case before version 7.0. In the case of + sources that do not support named graphs, the `publicID` parameter will + also not be used as the name for the graph that the data is loaded into, + and instead the triples from sources that do not support named graphs will + be loaded into the default graph (i.e. Dataset.default_graph). + """ + + ConjunctiveGraph.parse( + self, source, publicID, format, location, file, data, **args + ) + return self + + def add_graph( + self, g: Optional[Union[_ContextIdentifierType, _ContextType, str]] + ) -> Graph: + """alias of graph for consistency""" + return self.graph(g) + + def remove_graph( + self: _DatasetT, g: Optional[Union[_ContextIdentifierType, _ContextType, str]] + ) -> _DatasetT: + if not isinstance(g, Graph): + g = self.get_context(g) + + self.store.remove_graph(g) + if g is None or g == self.default_graph: + # default graph cannot be removed + # only triples deleted, so add it back in + self.store.add_graph(self.default_graph) + return self + + def contexts( + self, triple: Optional[_TripleType] = None + ) -> Generator[_ContextType, None, None]: + warnings.warn( + "Dataset.contexts is deprecated, use Dataset.graphs instead.", + DeprecationWarning, + stacklevel=2, + ) + default = False + for c in super(Dataset, self).contexts(triple): + default |= c.identifier == DATASET_DEFAULT_GRAPH_ID + yield c + if not default: + yield self.graph(DATASET_DEFAULT_GRAPH_ID) + + def graphs( + self, triple: Optional[_TripleType] = None + ) -> Generator[_ContextType, None, None]: + default = False + for c in super(Dataset, self).contexts(triple): + default |= c.identifier == DATASET_DEFAULT_GRAPH_ID + yield c + if not default: + yield self.graph(DATASET_DEFAULT_GRAPH_ID) + + # type error: Return type "Generator[Tuple[Node, Node, Node, Optional[Node]], None, None]" of "quads" incompatible with return type "Generator[Tuple[Node, Node, Node, Optional[Graph]], None, None]" in supertype "ConjunctiveGraph" + def quads( # type: ignore[override] + self, quad: Optional[_TripleOrQuadPatternType] = None + ) -> Generator[_OptionalIdentifiedQuadType, None, None]: + for s, p, o, c in super(Dataset, self).quads(quad): + # type error: Item "None" of "Optional[Graph]" has no attribute "identifier" + if c.identifier == self.default_graph: # type: ignore[union-attr] + yield s, p, o, None + else: + # type error: Item "None" of "Optional[Graph]" has no attribute "identifier" [union-attr] + yield s, p, o, c.identifier # type: ignore[union-attr] + + # type error: Return type "Generator[Tuple[Node, URIRef, Node, Optional[IdentifiedNode]], None, None]" of "__iter__" incompatible with return type "Generator[Tuple[IdentifiedNode, IdentifiedNode, Union[IdentifiedNode, Literal]], None, None]" in supertype "Graph" + def __iter__( # type: ignore[override] + self, + ) -> Generator[_OptionalIdentifiedQuadType, None, None]: + """Iterates over all quads in the store""" + return self.quads((None, None, None, None)) + + @overload + def serialize( + self, + destination: None, + format: str, + base: Optional[str], + encoding: str, + **args: Any, + ) -> bytes: ... + + # no destination and non-None keyword encoding + @overload + def serialize( + self, + destination: None = ..., + format: str = ..., + base: Optional[str] = ..., + *, + encoding: str, + **args: Any, + ) -> bytes: ... + + # no destination and None encoding + @overload + def serialize( + self, + destination: None = ..., + format: str = ..., + base: Optional[str] = ..., + encoding: None = ..., + **args: Any, + ) -> str: ... + + # non-None destination + @overload + def serialize( + self, + destination: Union[str, pathlib.PurePath, IO[bytes]], + format: str = ..., + base: Optional[str] = ..., + encoding: Optional[str] = ..., + **args: Any, + ) -> Graph: ... + + # fallback + @overload + def serialize( + self, + destination: Optional[Union[str, pathlib.PurePath, IO[bytes]]] = ..., + format: str = ..., + base: Optional[str] = ..., + encoding: Optional[str] = ..., + **args: Any, + ) -> Union[bytes, str, Graph]: ... + + def serialize( + self, + destination: Optional[Union[str, pathlib.PurePath, IO[bytes]]] = None, + format: str = "trig", + base: Optional[str] = None, + encoding: Optional[str] = None, + **args: Any, + ) -> Union[bytes, str, Graph]: + return super(Dataset, self).serialize( + destination=destination, format=format, base=base, encoding=encoding, **args + ) + + +class QuotedGraph(Graph): + """ + Quoted Graphs are intended to implement Notation 3 formulae. They are + associated with a required identifier that the N3 parser *must* provide + in order to maintain consistent formulae identification for scenarios + such as implication and other such processing. + """ + + def __init__( + self, + store: Union[Store, str], + identifier: Optional[Union[_ContextIdentifierType, str]], + ): + super(QuotedGraph, self).__init__(store, identifier) + + def add(self: _GraphT, triple: _TripleType) -> _GraphT: + """Add a triple with self as context""" + s, p, o = triple + assert isinstance(s, Node), "Subject %s must be an rdflib term" % (s,) + assert isinstance(p, Node), "Predicate %s must be an rdflib term" % (p,) + assert isinstance(o, Node), "Object %s must be an rdflib term" % (o,) + + self.store.add((s, p, o), self, quoted=True) + return self + + def addN(self: _GraphT, quads: Iterable[_QuadType]) -> _GraphT: # noqa: N802 + """Add a sequence of triple with context""" + + self.store.addN( + (s, p, o, c) + for s, p, o, c in quads + if isinstance(c, QuotedGraph) + and c.identifier is self.identifier + and _assertnode(s, p, o) + ) + return self + + def n3(self, namespace_manager: Optional[NamespaceManager] = None) -> str: + """Return an n3 identifier for the Graph""" + return "{%s}" % self.identifier.n3(namespace_manager=namespace_manager) + + def __str__(self) -> str: + identifier = self.identifier.n3() + label = self.store.__class__.__name__ + pattern = ( + "{this rdflib.identifier %s;rdflib:storage " + "[a rdflib:Store;rdfs:label '%s']}" + ) + return pattern % (identifier, label) + + def __reduce__(self) -> Tuple[Type[Graph], Tuple[Store, _ContextIdentifierType]]: + return QuotedGraph, (self.store, self.identifier) + + +# Make sure QuotedGraph is ordered correctly +# wrt to other Terms. +# this must be done here, as the QuotedGraph cannot be +# circularily imported in term.py +rdflib.term._ORDERING[QuotedGraph] = 11 + + +class Seq: + """Wrapper around an RDF Seq resource + + It implements a container type in Python with the order of the items + returned corresponding to the Seq content. It is based on the natural + ordering of the predicate names _1, _2, _3, etc, which is the + 'implementation' of a sequence in RDF terms. + + Args: + graph: the graph containing the Seq + subject:the subject of a Seq. Note that the init does not + check whether this is a Seq, this is done in whoever + creates this instance! + """ + + def __init__(self, graph: Graph, subject: _SubjectType): + self._list: List[Tuple[int, _ObjectType]] + _list = self._list = list() + LI_INDEX = URIRef(str(RDF) + "_") # noqa: N806 + for p, o in graph.predicate_objects(subject): + # type error: "Node" has no attribute "startswith" + if p.startswith(LI_INDEX): # type: ignore[attr-defined] # != RDF.Seq: + # type error: "Node" has no attribute "replace" + i = int(p.replace(LI_INDEX, "")) # type: ignore[attr-defined] + _list.append((i, o)) + + # here is the trick: the predicates are _1, _2, _3, etc. Ie, + # by sorting the keys (by integer) we have what we want! + _list.sort() + + def toPython(self) -> Seq: # noqa: N802 + return self + + def __iter__(self) -> Generator[_ObjectType, None, None]: + """Generator over the items in the Seq""" + for _, item in self._list: + yield item + + def __len__(self) -> int: + """Length of the Seq""" + return len(self._list) + + def __getitem__(self, index) -> _ObjectType: + """Item given by index from the Seq""" + index, item = self._list.__getitem__(index) + return item + + +class ModificationException(Exception): # noqa: N818 + def __init__(self) -> None: + pass + + def __str__(self) -> str: + return ( + "Modifications and transactional operations not allowed on " + "ReadOnlyGraphAggregate instances" + ) + + +class UnSupportedAggregateOperation(Exception): # noqa: N818 + def __init__(self) -> None: + pass + + def __str__(self) -> str: + return "This operation is not supported by ReadOnlyGraphAggregate " "instances" + + +class ReadOnlyGraphAggregate(ConjunctiveGraph): + """Utility class for treating a set of graphs as a single graph + + Only read operations are supported (hence the name). Essentially a + ConjunctiveGraph over an explicit subset of the entire store. + """ + + def __init__(self, graphs: List[Graph], store: Union[str, Store] = "default"): + if store is not None: + super(ReadOnlyGraphAggregate, self).__init__(store) + Graph.__init__(self, store) + self.__namespace_manager = None + + assert ( + isinstance(graphs, list) + and graphs + and [g for g in graphs if isinstance(g, Graph)] + ), "graphs argument must be a list of Graphs!!" + self.graphs = graphs + + def __repr__(self) -> str: + return "" % len(self.graphs) + + def destroy(self, configuration: str) -> NoReturn: + raise ModificationException() + + # Transactional interfaces (optional) + def commit(self) -> NoReturn: + raise ModificationException() + + def rollback(self) -> NoReturn: + raise ModificationException() + + def open(self, configuration: str | tuple[str, str], create: bool = False) -> None: + # TODO: is there a use case for this method? + for graph in self.graphs: + # type error: Too many arguments for "open" of "Graph" + # type error: Argument 1 to "open" of "Graph" has incompatible type "ReadOnlyGraphAggregate"; expected "str" [arg-type] + # type error: Argument 2 to "open" of "Graph" has incompatible type "str"; expected "bool" [arg-type] + graph.open(self, configuration, create) # type: ignore[call-arg, arg-type] + + # type error: Signature of "close" incompatible with supertype "Graph" + def close(self) -> None: # type: ignore[override] + for graph in self.graphs: + graph.close() + + def add(self, triple: _TripleOrOptionalQuadType) -> NoReturn: + raise ModificationException() + + def addN(self, quads: Iterable[_QuadType]) -> NoReturn: # noqa: N802 + raise ModificationException() + + # type error: Argument 1 of "remove" is incompatible with supertype "Graph"; supertype defines the argument type as "Tuple[Optional[Node], Optional[Node], Optional[Node]]" + def remove(self, triple: _TripleOrOptionalQuadType) -> NoReturn: # type: ignore[override] + raise ModificationException() + + # type error: Signature of "triples" incompatible with supertype "ConjunctiveGraph" + @overload # type: ignore[override] + def triples( + self, + triple: _TriplePatternType, + ) -> Generator[_TripleType, None, None]: ... + + @overload + def triples( + self, + triple: _TriplePathPatternType, + ) -> Generator[_TriplePathType, None, None]: ... + + @overload + def triples( + self, + triple: _TripleSelectorType, + ) -> Generator[_TripleOrTriplePathType, None, None]: ... + + def triples( + self, + triple: _TripleSelectorType, + ) -> Generator[_TripleOrTriplePathType, None, None]: + s, p, o = triple + for graph in self.graphs: + if isinstance(p, Path): + for s, o in p.eval(self, s, o): + yield s, p, o + else: + for s1, p1, o1 in graph.triples((s, p, o)): + yield s1, p1, o1 + + def __contains__(self, triple_or_quad: _TripleOrQuadSelectorType) -> bool: + context = None + if len(triple_or_quad) == 4: + # type error: Tuple index out of range + context = triple_or_quad[3] # type: ignore [misc, unused-ignore] + for graph in self.graphs: + if context is None or graph.identifier == context.identifier: + if triple_or_quad[:3] in graph: + return True + return False + + # type error: Signature of "quads" incompatible with supertype "ConjunctiveGraph" + def quads( # type: ignore[override] + self, triple_or_quad: _TripleOrQuadSelectorType + ) -> Generator[ + Tuple[_SubjectType, Union[Path, _PredicateType], _ObjectType, _ContextType], + None, + None, + ]: + """Iterate over all the quads in the entire aggregate graph""" + c = None + if len(triple_or_quad) == 4: + # type error: Need more than 3 values to unpack (4 expected) + s, p, o, c = triple_or_quad # type: ignore[misc, unused-ignore] + else: + # type error: Too many values to unpack (3 expected, 4 provided) + s, p, o = triple_or_quad # type: ignore[misc, unused-ignore] + + if c is not None: + for graph in [g for g in self.graphs if g == c]: + for s1, p1, o1 in graph.triples((s, p, o)): + yield s1, p1, o1, graph + else: + for graph in self.graphs: + for s1, p1, o1 in graph.triples((s, p, o)): + yield s1, p1, o1, graph + + def __len__(self) -> int: + return sum(len(g) for g in self.graphs) + + def __hash__(self) -> NoReturn: + raise UnSupportedAggregateOperation() + + def __cmp__(self, other) -> int: + if other is None: + return -1 + elif isinstance(other, Graph): + return -1 + elif isinstance(other, ReadOnlyGraphAggregate): + return (self.graphs > other.graphs) - (self.graphs < other.graphs) + else: + return -1 + + def __iadd__(self: _GraphT, other: Iterable[_TripleType]) -> NoReturn: + raise ModificationException() + + def __isub__(self: _GraphT, other: Iterable[_TripleType]) -> NoReturn: + raise ModificationException() + + # Conv. methods + + def triples_choices( + self, + triple: _TripleChoiceType, + context: Optional[_ContextType] = None, + ) -> Generator[_TripleType, None, None]: + subject, predicate, object_ = triple + for graph in self.graphs: + # type error: Argument 1 to "triples_choices" of "Graph" has incompatible type "Tuple[Union[List[Node], Node], Union[Node, List[Node]], Union[Node, List[Node]]]"; expected "Union[Tuple[List[Node], Node, Node], Tuple[Node, List[Node], Node], Tuple[Node, Node, List[Node]]]" + # type error note: unpacking discards type info + choices = graph.triples_choices((subject, predicate, object_)) # type: ignore[arg-type] + for s, p, o in choices: + yield s, p, o + + def qname(self, uri: str) -> str: + if hasattr(self, "namespace_manager") and self.namespace_manager: + return self.namespace_manager.qname(uri) + raise UnSupportedAggregateOperation() + + def compute_qname(self, uri: str, generate: bool = True) -> Tuple[str, URIRef, str]: + if hasattr(self, "namespace_manager") and self.namespace_manager: + return self.namespace_manager.compute_qname(uri, generate) + raise UnSupportedAggregateOperation() + + # type error: Signature of "bind" incompatible with supertype "Graph" + def bind( # type: ignore[override] + self, prefix: Optional[str], namespace: Any, override: bool = True # noqa: F811 + ) -> NoReturn: + raise UnSupportedAggregateOperation() + + def namespaces(self) -> Generator[Tuple[str, URIRef], None, None]: + if hasattr(self, "namespace_manager"): + for prefix, namespace in self.namespace_manager.namespaces(): + yield prefix, namespace + else: + for graph in self.graphs: + for prefix, namespace in graph.namespaces(): + yield prefix, namespace + + def absolutize(self, uri: str, defrag: int = 1) -> NoReturn: + raise UnSupportedAggregateOperation() + + # type error: Signature of "parse" incompatible with supertype "ConjunctiveGraph" + def parse( # type: ignore[override] + self, + source: Optional[ + Union[IO[bytes], TextIO, InputSource, str, bytes, pathlib.PurePath] + ], + publicID: Optional[str] = None, # noqa: N803 + format: Optional[str] = None, + **args: Any, + ) -> NoReturn: + raise ModificationException() + + def n3(self, namespace_manager: Optional[NamespaceManager] = None) -> NoReturn: + raise UnSupportedAggregateOperation() + + def __reduce__(self) -> NoReturn: + raise UnSupportedAggregateOperation() + + +@overload +def _assertnode(*terms: Node) -> te.Literal[True]: ... + + +@overload +def _assertnode(*terms: Any) -> bool: ... + + +def _assertnode(*terms: Any) -> bool: + for t in terms: + assert isinstance(t, Node), "Term %s must be an rdflib term" % (t,) + return True + + +class BatchAddGraph: + """Wrapper around graph that turns batches of calls to Graph's add + (and optionally, addN) into calls to batched calls to addN`. + + Args: + graph: The graph to wrap + batch_size: The maximum number of triples to buffer before passing to + Graph's addN + batch_addn: If True, then even calls to `addN` will be batched according to + batch_size + + Attributes: + graph: The wrapped graph + count: The number of triples buffered since initialization or the last call to reset + batch: The current buffer of triples + """ + + def __init__(self, graph: Graph, batch_size: int = 1000, batch_addn: bool = False): + if not batch_size or batch_size < 2: + raise ValueError("batch_size must be a positive number") + self.graph = graph + self.__graph_tuple = (graph,) + self.__batch_size = batch_size + self.__batch_addn = batch_addn + self.reset() + + def reset(self) -> BatchAddGraph: + """ + Manually clear the buffered triples and reset the count to zero + """ + self.batch: List[_QuadType] = [] + self.count = 0 + return self + + def add( + self, + triple_or_quad: Union[ + _TripleType, + _QuadType, + ], + ) -> BatchAddGraph: + """Add a triple to the buffer. + + Args: + triple_or_quad: The triple or quad to add + + Returns: + The BatchAddGraph instance + """ + if len(self.batch) >= self.__batch_size: + self.graph.addN(self.batch) + self.batch = [] + self.count += 1 + if len(triple_or_quad) == 3: + # type error: Argument 1 to "append" of "list" has incompatible type "Tuple[Node, ...]"; expected "Tuple[Node, Node, Node, Graph]" + self.batch.append(triple_or_quad + self.__graph_tuple) # type: ignore[arg-type, unused-ignore] + else: + # type error: Argument 1 to "append" of "list" has incompatible type "Union[Tuple[Node, Node, Node], Tuple[Node, Node, Node, Graph]]"; expected "Tuple[Node, Node, Node, Graph]" + self.batch.append(triple_or_quad) # type: ignore[arg-type, unused-ignore] + return self + + def addN(self, quads: Iterable[_QuadType]) -> BatchAddGraph: # noqa: N802 + if self.__batch_addn: + for q in quads: + self.add(q) + else: + self.graph.addN(quads) + return self + + def __enter__(self) -> BatchAddGraph: + self.reset() + return self + + def __exit__(self, *exc) -> None: + if exc[0] is None: + self.graph.addN(self.batch) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rdflib/parser.py b/TTS/Kokoro/.venv/Lib/site-packages/rdflib/parser.py new file mode 100644 index 0000000000000000000000000000000000000000..79bcc6b96473ed93279906a5e6a53d90b1661e87 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rdflib/parser.py @@ -0,0 +1,800 @@ +"""Parser plugin interface. + +This module defines the parser plugin interface and contains other +related parser support code. + +The module is mainly useful for those wanting to write a parser that +can plugin to rdflib. If you are wanting to invoke a parser you likely +want to do so through the Graph class parse method. +""" + +from __future__ import annotations + +import codecs +import os +import pathlib +import sys +from io import BufferedIOBase, BytesIO, RawIOBase, StringIO, TextIOBase, TextIOWrapper +from typing import ( + IO, + TYPE_CHECKING, + Any, + BinaryIO, + List, + Optional, + TextIO, + Tuple, + Union, + cast, +) +from urllib.parse import urljoin +from urllib.request import Request, url2pathname +from xml.sax import xmlreader + +import rdflib.util +from rdflib import __version__ +from rdflib._networking import _urlopen +from rdflib.namespace import Namespace +from rdflib.term import URIRef + +if TYPE_CHECKING: + from email.message import Message + from io import BufferedReader + from urllib.response import addinfourl + + from typing_extensions import Buffer + + from rdflib.graph import Graph + + +__all__ = [ + "Parser", + "InputSource", + "StringInputSource", + "URLInputSource", + "FileInputSource", + "PythonInputSource", +] + + +class Parser: + __slots__ = () + + def __init__(self): + pass + + def parse(self, source: InputSource, sink: Graph) -> None: + pass + + +class BytesIOWrapper(BufferedIOBase): + __slots__ = ( + "wrapped", + "enc_str", + "text_str", + "encoding", + "encoder", + "has_read1", + "has_seek", + "_name", + "_fileno", + "_isatty", + "_leftover", + "_bytes_per_char", + "_text_bytes_offset", + ) + + def __init__(self, wrapped: Union[str, StringIO, TextIOBase], encoding="utf-8"): + super(BytesIOWrapper, self).__init__() + self.wrapped = wrapped + self.encoding = encoding + self.encoder = codecs.getencoder(self.encoding) + self.enc_str: Optional[Union[BytesIO, BufferedIOBase]] = None + self.text_str: Optional[Union[StringIO, TextIOBase]] = None + self.has_read1: Optional[bool] = None + self.has_seek: Optional[bool] = None + self._name: Optional[str] = None + self._fileno: Optional[Union[int, BaseException]] = None + self._isatty: Optional[Union[bool, BaseException]] = None + self._leftover: bytes = b"" + self._text_bytes_offset: int = 0 + norm_encoding = encoding.lower().replace("_", "-") + if norm_encoding in ("utf-8", "utf8", "u8", "cp65001"): + # utf-8 has a variable number of bytes per character, 1-4 + self._bytes_per_char: int = 1 # assume average of 1 byte per character + elif norm_encoding in ( + "latin1", + "latin-1", + "iso-8859-1", + "iso8859-1", + "ascii", + "us-ascii", + ): + # these are all 1-byte-per-character encodings + self._bytes_per_char = 1 + elif norm_encoding.startswith("utf-16") or norm_encoding.startswith("utf16"): + # utf-16 has a variable number of bytes per character, 2-3 + self._bytes_per_char = 2 # assume average of 2 bytes per character + elif norm_encoding.startswith("utf-32") or norm_encoding.startswith("utf32"): + # utf-32 is fixed length with 4 bytes per character + self._bytes_per_char = 4 + else: + # not sure, just assume it is 2 bytes per character + self._bytes_per_char = 2 + + def _init(self): + name: Optional[str] = None + if isinstance(self.wrapped, str): + b, blen = self.encoder(self.wrapped) + self.enc_str = BytesIO(b) + name = "string" + elif isinstance(self.wrapped, TextIOWrapper): + inner = self.wrapped.buffer + if isinstance(inner, BytesIOWrapper): + raise Exception( + "BytesIOWrapper cannot be wrapped in TextIOWrapper, " + "then wrapped in another BytesIOWrapper" + ) + else: + self.enc_str = cast(BufferedIOBase, inner) + elif isinstance(self.wrapped, (TextIOBase, StringIO)): + self.text_str = self.wrapped + use_stream: Union[BytesIO, StringIO, BufferedIOBase, TextIOBase] + if self.enc_str is not None: + use_stream = self.enc_str + elif self.text_str is not None: + use_stream = self.text_str + else: + raise Exception("No stream to read from") + if name is None: + try: + name = use_stream.name # type: ignore[union-attr] + except AttributeError: + name = "stream" + self.has_read1 = hasattr(use_stream, "read1") + try: + self.has_seek = use_stream.seekable() + except AttributeError: + self.has_seek = hasattr(use_stream, "seek") + + self._name = name + + def _check_fileno(self): + use_stream: Union[BytesIO, StringIO, BufferedIOBase, TextIOBase] + if self.enc_str is None and self.text_str is None: + self._init() + if self.enc_str is not None: + use_stream = self.enc_str + elif self.text_str is not None: + use_stream = self.text_str + try: + self._fileno = use_stream.fileno() + except OSError as e: + self._fileno = e + except AttributeError: + self._fileno = -1 + + def _check_isatty(self): + use_stream: Union[BytesIO, StringIO, BufferedIOBase, TextIOBase] + if self.enc_str is None and self.text_str is None: + self._init() + if self.enc_str is not None: + use_stream = self.enc_str + elif self.text_str is not None: + use_stream = self.text_str + try: + self._isatty = use_stream.isatty() + except OSError as e: + self._isatty = e + except AttributeError: + self._isatty = False + + @property + def name(self) -> Any: + if self._name is None: + self._init() + return self._name + + @property + def closed(self) -> bool: + if self.enc_str is None and self.text_str is None: + return False + closed: Optional[bool] = None + if self.enc_str is not None: + try: + closed = self.enc_str.closed + except AttributeError: + closed = None + elif self.text_str is not None: + try: + closed = self.text_str.closed + except AttributeError: + closed = None + return False if closed is None else closed + + def readable(self) -> bool: + return True + + def writable(self) -> bool: + return False + + def truncate(self, size: Optional[int] = None) -> int: + raise NotImplementedError("Cannot truncate on BytesIOWrapper") + + def isatty(self) -> bool: + if self._isatty is None: + self._check_isatty() + if isinstance(self._isatty, BaseException): + raise self._isatty + else: + return bool(self._isatty) + + def fileno(self) -> int: + if self._fileno is None: + self._check_fileno() + if isinstance(self._fileno, BaseException): + raise self._fileno + else: + return -1 if self._fileno is None else self._fileno + + def close(self): + if self.enc_str is None and self.text_str is None: + return + if self.enc_str is not None: + try: + self.enc_str.close() + except AttributeError: + pass + elif self.text_str is not None: + try: + self.text_str.close() + except AttributeError: + pass + + def flush(self): + return # Does nothing on read-only streams + + def _read_bytes_from_text_stream(self, size: Optional[int] = -1, /) -> bytes: + if TYPE_CHECKING: + assert self.text_str is not None + if size is None or size < 0: + try: + ret_str: str = self.text_str.read() + except EOFError: + ret_str = "" + ret_encoded, enc_len = self.encoder(ret_str) + if self._leftover: + ret_bytes = self._leftover + ret_encoded + self._leftover = b"" + else: + ret_bytes = ret_encoded + elif size == len(self._leftover): + ret_bytes = self._leftover + self._leftover = b"" + elif size < len(self._leftover): + ret_bytes = self._leftover[:size] + self._leftover = self._leftover[size:] + else: + d, m = divmod(size, self._bytes_per_char) + get_per_loop = int(d) + (1 if m > 0 else 0) + got_bytes: bytes = self._leftover + while len(got_bytes) < size: + try: + got_str: str = self.text_str.read(get_per_loop) + except EOFError: + got_str = "" + if len(got_str) < 1: + break + ret_encoded, enc_len = self.encoder(got_str) + got_bytes += ret_encoded + if len(got_bytes) == size: + self._leftover = b"" + ret_bytes = got_bytes + else: + ret_bytes = got_bytes[:size] + self._leftover = got_bytes[size:] + del got_bytes + self._text_bytes_offset += len(ret_bytes) + return ret_bytes + + def read(self, size: Optional[int] = -1, /) -> bytes: + """ + Read at most size bytes, returned as a bytes object. + + If the size argument is negative or omitted read until EOF is reached. + Return an empty bytes object if already at EOF. + """ + if size is not None and size == 0: + return b"" + if self.enc_str is None and self.text_str is None: + self._init() + if self.enc_str is not None: + ret_bytes = self.enc_str.read(size) + else: + ret_bytes = self._read_bytes_from_text_stream(size) + return ret_bytes + + def read1(self, size: Optional[int] = -1, /) -> bytes: + """ + Read at most size bytes, with at most one call to the underlying raw stream’s + read() or readinto() method. Returned as a bytes object. + + If the size argument is negative or omitted, read until EOF is reached. + Return an empty bytes object at EOF. + """ + if (self.enc_str is None and self.text_str is None) or self.has_read1 is None: + self._init() + if not self.has_read1: + raise NotImplementedError() + if self.enc_str is not None: + if size is None or size < 0: + return self.enc_str.read1() + return self.enc_str.read1(size) + raise NotImplementedError("read1() not supported for TextIO in BytesIOWrapper") + + def readinto(self, b: Buffer, /) -> int: + """ + Read len(b) bytes into buffer b. + + Returns number of bytes read (0 for EOF), or error if the object + is set not to block and has no data to read. + """ + if TYPE_CHECKING: + assert isinstance(b, (memoryview, bytearray)) + if len(b) == 0: + return 0 + if self.enc_str is None and self.text_str is None: + self._init() + if self.enc_str is not None: + return self.enc_str.readinto(b) + else: + size = len(b) + read_data: bytes = self._read_bytes_from_text_stream(size) + read_len = len(read_data) + if read_len == 0: + return 0 + b[:read_len] = read_data + return read_len + + def readinto1(self, b: Buffer, /) -> int: + """ + Read len(b) bytes into buffer b, with at most one call to the underlying raw + stream's read() or readinto() method. + + Returns number of bytes read (0 for EOF), or error if the object + is set not to block and has no data to read. + """ + if TYPE_CHECKING: + assert isinstance(b, (memoryview, bytearray)) + if (self.enc_str is None and self.text_str is None) or self.has_read1 is None: + self._init() + if not self.has_read1: + raise NotImplementedError() + if self.enc_str is not None: + return self.enc_str.readinto1(b) + raise NotImplementedError( + "readinto1() not supported for TextIO in BytesIOWrapper" + ) + + def seek(self, offset: int, whence: int = 0, /) -> int: + if self.has_seek is not None and not self.has_seek: + raise NotImplementedError() + if (self.enc_str is None and self.text_str is None) or self.has_seek is None: + self._init() + + if not whence == 0: + raise NotImplementedError("Only SEEK_SET is supported on BytesIOWrapper") + if offset != 0: + raise NotImplementedError( + "Only seeking to zero is supported on BytesIOWrapper" + ) + if self.enc_str is not None: + self.enc_str.seek(offset, whence) + elif self.text_str is not None: + self.text_str.seek(offset, whence) + self._text_bytes_offset = 0 + self._leftover = b"" + return 0 + + def seekable(self): + if (self.enc_str is None and self.text_str is None) or self.has_seek is None: + self._init() + return self.has_seek + + def tell(self) -> int: + if self.has_seek is not None and not self.has_seek: + raise NotImplementedError("Cannot tell() pos because file is not seekable.") + if self.enc_str is not None: + try: + self._text_bytes_offset = self.enc_str.tell() + except AttributeError: + pass + return self._text_bytes_offset + + def write(self, b, /): + raise NotImplementedError("Cannot write to a BytesIOWrapper") + + +class InputSource(xmlreader.InputSource): + """ + TODO: + """ + + def __init__(self, system_id: Optional[str] = None): + xmlreader.InputSource.__init__(self, system_id=system_id) + self.content_type: Optional[str] = None + self.auto_close = False # see Graph.parse(), true if opened by us + + def close(self) -> None: + c = self.getCharacterStream() + if c and hasattr(c, "close"): + try: + c.close() + except Exception: + pass + f = self.getByteStream() + if f and hasattr(f, "close"): + try: + f.close() + except Exception: + pass + + +class PythonInputSource(InputSource): + """ + Constructs an RDFLib Parser InputSource from a Python data structure, + for example, loaded from JSON with json.load or json.loads: + + >>> import json + >>> as_string = \"\"\"{ + ... "@context" : {"ex" : "http://example.com/ns#"}, + ... "@graph": [{"@type": "ex:item", "@id": "#example"}] + ... }\"\"\" + >>> as_python = json.loads(as_string) + >>> source = create_input_source(data=as_python) + >>> isinstance(source, PythonInputSource) + True + """ + + def __init__(self, data: Any, system_id: Optional[str] = None): + self.content_type = None + self.auto_close = False # see Graph.parse(), true if opened by us + self.public_id: Optional[str] = None + self.system_id: Optional[str] = system_id + self.data = data + + def getPublicId(self) -> Optional[str]: # noqa: N802 + return self.public_id + + def setPublicId(self, public_id: Optional[str]) -> None: # noqa: N802 + self.public_id = public_id + + def getSystemId(self) -> Optional[str]: # noqa: N802 + return self.system_id + + def setSystemId(self, system_id: Optional[str]) -> None: # noqa: N802 + self.system_id = system_id + + def close(self) -> None: + self.data = None + + +class StringInputSource(InputSource): + """ + Constructs an RDFLib Parser InputSource from a Python String or Bytes + """ + + def __init__( + self, + value: Union[str, bytes], + encoding: str = "utf-8", + system_id: Optional[str] = None, + ): + super(StringInputSource, self).__init__(system_id) + stream: Union[BinaryIO, TextIO] + if isinstance(value, str): + stream = StringIO(value) + self.setCharacterStream(stream) + self.setEncoding(encoding) + b_stream = BytesIOWrapper(value, encoding) + self.setByteStream(b_stream) + else: + stream = BytesIO(value) + self.setByteStream(stream) + c_stream = TextIOWrapper(stream, encoding) + self.setCharacterStream(c_stream) + self.setEncoding(c_stream.encoding) + + +headers = { + "User-agent": "rdflib-%s (https://rdflib.github.io/; eikeon@eikeon.com)" + % __version__ +} + + +class URLInputSource(InputSource): + """ + Constructs an RDFLib Parser InputSource from a URL to read it from the Web. + """ + + links: List[str] + + @classmethod + def getallmatchingheaders(cls, message: Message, name) -> List[str]: + # This is reimplemented here, because the method + # getallmatchingheaders from HTTPMessage is broken since Python 3.0 + name = name.lower() + return [val for key, val in message.items() if key.lower() == name] + + @classmethod + def get_links(cls, response: addinfourl) -> List[str]: + linkslines = cls.getallmatchingheaders(response.headers, "Link") + retarray: List[str] = [] + for linksline in linkslines: + links = [linkstr.strip() for linkstr in linksline.split(",")] + for link in links: + retarray.append(link) + return retarray + + def get_alternates(self, type_: Optional[str] = None) -> List[str]: + typestr: Optional[str] = f'type="{type_}"' if type_ else None + relstr = 'rel="alternate"' + alts = [] + for link in self.links: + parts = [p.strip() for p in link.split(";")] + if relstr not in parts: + continue + if typestr: + if typestr in parts: + alts.append(parts[0].strip("<>")) + else: + alts.append(parts[0].strip("<>")) + return alts + + def __init__(self, system_id: Optional[str] = None, format: Optional[str] = None): + super(URLInputSource, self).__init__(system_id) + self.url = system_id + + # copy headers to change + myheaders = dict(headers) + if format == "xml": + myheaders["Accept"] = "application/rdf+xml, */*;q=0.1" + elif format == "n3": + myheaders["Accept"] = "text/n3, */*;q=0.1" + elif format in ["turtle", "ttl"]: + myheaders["Accept"] = "text/turtle, application/x-turtle, */*;q=0.1" + elif format == "nt": + myheaders["Accept"] = "text/plain, */*;q=0.1" + elif format == "trig": + myheaders["Accept"] = "application/trig, */*;q=0.1" + elif format == "trix": + myheaders["Accept"] = "application/trix, */*;q=0.1" + elif format == "json-ld": + myheaders["Accept"] = ( + "application/ld+json, application/json;q=0.9, */*;q=0.1" + ) + else: + # if format not given, create an Accept header from all registered + # parser Media Types + from rdflib.parser import Parser + from rdflib.plugin import plugins + + acc = [] + for p in plugins(kind=Parser): # only get parsers + if "/" in p.name: # all Media Types known have a / in them + acc.append(p.name) + + myheaders["Accept"] = ", ".join(acc) + + req = Request(system_id, None, myheaders) # type: ignore[arg-type] + + response: addinfourl = _urlopen(req) + self.url = response.geturl() # in case redirections took place + self.links = self.get_links(response) + if format in ("json-ld", "application/ld+json"): + alts = self.get_alternates(type_="application/ld+json") + for link in alts: + full_link = urljoin(self.url, link) + if full_link != self.url and full_link != system_id: + response = _urlopen(Request(full_link)) + self.url = response.geturl() # in case redirections took place + break + + self.setPublicId(self.url) + content_types = self.getallmatchingheaders(response.headers, "content-type") + self.content_type = content_types[0] if content_types else None + if self.content_type is not None: + self.content_type = self.content_type.split(";", 1)[0] + self.setByteStream(response) + # TODO: self.setEncoding(encoding) + self.response_info = response.info() # a mimetools.Message instance + + def __repr__(self) -> str: + # type error: Incompatible return value type (got "Optional[str]", expected "str") + return self.url # type: ignore[return-value] + + +class FileInputSource(InputSource): + def __init__( + self, + file: Union[BinaryIO, TextIO, TextIOBase, RawIOBase, BufferedIOBase], + /, + encoding: Optional[str] = None, + ): + base = pathlib.Path.cwd().as_uri() + system_id = URIRef(pathlib.Path(file.name).absolute().as_uri(), base=base) # type: ignore[union-attr] + super(FileInputSource, self).__init__(system_id) + self.file = file + if isinstance(file, TextIOBase): # Python3 unicode fp + self.setCharacterStream(file) + self.setEncoding(file.encoding) + try: + b = file.buffer # type: ignore[attr-defined] + self.setByteStream(b) + except (AttributeError, LookupError): + self.setByteStream(BytesIOWrapper(file, encoding=file.encoding)) + else: + if TYPE_CHECKING: + assert isinstance(file, BufferedReader) + self.setByteStream(file) + if encoding is not None: + self.setEncoding(encoding) + self.setCharacterStream(TextIOWrapper(file, encoding=encoding)) + else: + # We cannot set characterStream here because + # we do not know the Raw Bytes File encoding. + pass + + def __repr__(self) -> str: + return repr(self.file) + + +def create_input_source( + source: Optional[ + Union[IO[bytes], TextIO, InputSource, str, bytes, pathlib.PurePath] + ] = None, + publicID: Optional[str] = None, # noqa: N803 + location: Optional[str] = None, + file: Optional[Union[BinaryIO, TextIO]] = None, + data: Optional[Union[str, bytes, dict]] = None, + format: Optional[str] = None, +) -> InputSource: + """ + Return an appropriate InputSource instance for the given + parameters. + """ + + # test that exactly one of source, location, file, and data is not None. + non_empty_arguments = list( + filter( + lambda v: v is not None, + [source, location, file, data], + ) + ) + + if len(non_empty_arguments) != 1: + raise ValueError( + "exactly one of source, location, file or data must be given", + ) + + input_source = None + + if source is not None: + if TYPE_CHECKING: + assert file is None + assert data is None + assert location is None + if isinstance(source, InputSource): + input_source = source + else: + if isinstance(source, str): + location = source + elif isinstance(source, pathlib.PurePath): + location = str(source) + elif isinstance(source, bytes): + data = source + elif hasattr(source, "read") and not isinstance(source, Namespace): + f = source + input_source = InputSource() + if hasattr(source, "encoding"): + input_source.setCharacterStream(source) + input_source.setEncoding(source.encoding) + try: + b = source.buffer # type: ignore[union-attr] + input_source.setByteStream(b) + except (AttributeError, LookupError): + input_source.setByteStream(source) + else: + input_source.setByteStream(f) + if f is sys.stdin: + input_source.setSystemId("file:///dev/stdin") + elif hasattr(f, "name"): + input_source.setSystemId(f.name) + else: + raise Exception( + "Unexpected type '%s' for source '%s'" % (type(source), source) + ) + + absolute_location = None # Further to fix for issue 130 + + auto_close = False # make sure we close all file handles we open + + if location is not None: + if TYPE_CHECKING: + assert file is None + assert data is None + assert source is None + ( + absolute_location, + auto_close, + file, + input_source, + ) = _create_input_source_from_location( + file=file, + format=format, + input_source=input_source, + location=location, + ) + + if file is not None: + if TYPE_CHECKING: + assert location is None + assert data is None + assert source is None + input_source = FileInputSource(file) + + if data is not None: + if TYPE_CHECKING: + assert location is None + assert file is None + assert source is None + if isinstance(data, dict): + input_source = PythonInputSource(data) + auto_close = True + elif isinstance(data, (str, bytes, bytearray)): + input_source = StringInputSource(data) + auto_close = True + else: + raise RuntimeError(f"parse data can only str, or bytes. not: {type(data)}") + + if input_source is None: + raise Exception("could not create InputSource") + else: + input_source.auto_close |= auto_close + if publicID is not None: # Further to fix for issue 130 + input_source.setPublicId(publicID) + # Further to fix for issue 130 + elif input_source.getPublicId() is None: + input_source.setPublicId(absolute_location or "") + return input_source + + +def _create_input_source_from_location( + file: Optional[Union[BinaryIO, TextIO]], + format: Optional[str], + input_source: Optional[InputSource], + location: str, +) -> Tuple[URIRef, bool, Optional[Union[BinaryIO, TextIO]], Optional[InputSource]]: + # Fix for Windows problem https://github.com/RDFLib/rdflib/issues/145 and + # https://github.com/RDFLib/rdflib/issues/1430 + # NOTE: using pathlib.Path.exists on a URL fails on windows as it is not a + # valid path. However os.path.exists() returns false for a URL on windows + # which is why it is being used instead. + if os.path.exists(location): + location = pathlib.Path(location).absolute().as_uri() + + base = pathlib.Path.cwd().as_uri() + + absolute_location = URIRef(rdflib.util._iri2uri(location), base=base) + + if absolute_location.startswith("file:///"): + filename = url2pathname(absolute_location.replace("file:///", "/")) + file = open(filename, "rb") + else: + input_source = URLInputSource(absolute_location, format) + + auto_close = True + # publicID = publicID or absolute_location # Further to fix + # for issue 130 + + return absolute_location, auto_close, file, input_source diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rdflib/paths.py b/TTS/Kokoro/.venv/Lib/site-packages/rdflib/paths.py new file mode 100644 index 0000000000000000000000000000000000000000..d8f6d12521368affbfd517d7f4603d7af3608abb --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rdflib/paths.py @@ -0,0 +1,606 @@ +r""" +This module implements the SPARQL 1.1 Property path operators, as +defined in: +[http://www.w3.org/TR/sparql11-query/#propertypaths](http://www.w3.org/TR/sparql11-query/#propertypaths) + +In SPARQL the syntax is as follows: + +| Syntax | Matches | +|---------------------|-------------------------------------------------------------------------| +| `iri` | An IRI. A path of length one. | +| `^elt` | Inverse path (object to subject). | +| `elt1 / elt2` | A sequence path of `elt1` followed by `elt2`. | +| `elt1 \| elt2` | An alternative path of `elt1` or `elt2` (all possibilities are tried). | +| `elt*` | A path that connects subject and object by zero or more matches of `elt`.| +| `elt+` | A path that connects subject and object by one or more matches of `elt`.| +| `elt?` | A path that connects subject and object by zero or one matches of `elt`.| +| `!iri` or
`!(iri1 \| ... \| irin)` | Negated property set. An IRI not among `iri1` to `irin`.
`!iri` is short for `!(iri)`. | +| `!^iri` or
`!(^iri1 \| ... \| ^irin)` | Negated reverse property set. Excludes `^iri1` to `^irin` as reverse paths.
`!^iri` is short for `!(^iri)`. | +| `!(iri1 \| ... \| irij \| ^irij+1 \| ... \| ^irin)` | A combination of forward and reverse properties in a negated property set. | +| `(elt)` | A grouped path `elt`, where parentheses control precedence. | + +This module is used internally by the SPARQL engine, but the property paths +can also be used to query RDFLib Graphs directly. + +Where possible the SPARQL syntax is mapped to Python operators, and property +path objects can be constructed from existing URIRefs. + +```python +>>> from rdflib import Graph, Namespace +>>> from rdflib.namespace import FOAF + +>>> ~FOAF.knows +Path(~http://xmlns.com/foaf/0.1/knows) + +>>> FOAF.knows/FOAF.name +Path(http://xmlns.com/foaf/0.1/knows / http://xmlns.com/foaf/0.1/name) + +>>> FOAF.name|FOAF.givenName +Path(http://xmlns.com/foaf/0.1/name | http://xmlns.com/foaf/0.1/givenName) + +``` + +Modifiers (?, \*, +) are done using \* (the multiplication operator) and +the strings '\*', '?', '+', also defined as constants in this file. + +```python +>>> FOAF.knows*OneOrMore +Path(http://xmlns.com/foaf/0.1/knows+) + +``` + +The path objects can also be used with the normal graph methods. + +First some example data: + +```python +>>> g=Graph() + +>>> g=g.parse(data=''' +... @prefix : . +... +... :a :p1 :c ; :p2 :f . +... :c :p2 :e ; :p3 :g . +... :g :p3 :h ; :p2 :j . +... :h :p3 :a ; :p2 :g . +... +... :q :px :q . +... +... ''', format='n3') # doctest: +ELLIPSIS + +>>> e = Namespace('ex:') + +``` + +Graph contains: + +```python +>>> (e.a, e.p1/e.p2, e.e) in g +True + +``` + +Graph generator functions, triples, subjects, objects, etc. : + +```python +>>> list(g.objects(e.c, (e.p3*OneOrMore)/e.p2)) # doctest: +NORMALIZE_WHITESPACE +[rdflib.term.URIRef('ex:j'), rdflib.term.URIRef('ex:g'), + rdflib.term.URIRef('ex:f')] + +``` + +A more complete set of tests: + +```python +>>> list(eval_path(g, (None, e.p1/e.p2, None)))==[(e.a, e.e)] +True +>>> list(eval_path(g, (e.a, e.p1|e.p2, None)))==[(e.a,e.c), (e.a,e.f)] +True +>>> list(eval_path(g, (e.c, ~e.p1, None))) == [ (e.c, e.a) ] +True +>>> list(eval_path(g, (e.a, e.p1*ZeroOrOne, None))) == [(e.a, e.a), (e.a, e.c)] +True +>>> list(eval_path(g, (e.c, e.p3*OneOrMore, None))) == [ +... (e.c, e.g), (e.c, e.h), (e.c, e.a)] +True +>>> list(eval_path(g, (e.c, e.p3*ZeroOrMore, None))) == [(e.c, e.c), +... (e.c, e.g), (e.c, e.h), (e.c, e.a)] +True +>>> list(eval_path(g, (e.a, -e.p1, None))) == [(e.a, e.f)] +True +>>> list(eval_path(g, (e.a, -(e.p1|e.p2), None))) == [] +True +>>> list(eval_path(g, (e.g, -~e.p2, None))) == [(e.g, e.j)] +True +>>> list(eval_path(g, (e.e, ~(e.p1/e.p2), None))) == [(e.e, e.a)] +True +>>> list(eval_path(g, (e.a, e.p1/e.p3/e.p3, None))) == [(e.a, e.h)] +True + +>>> list(eval_path(g, (e.q, e.px*OneOrMore, None))) +[(rdflib.term.URIRef('ex:q'), rdflib.term.URIRef('ex:q'))] + +>>> list(eval_path(g, (None, e.p1|e.p2, e.c))) +[(rdflib.term.URIRef('ex:a'), rdflib.term.URIRef('ex:c'))] + +>>> list(eval_path(g, (None, ~e.p1, e.a))) == [ (e.c, e.a) ] +True +>>> list(eval_path(g, (None, e.p1*ZeroOrOne, e.c))) # doctest: +NORMALIZE_WHITESPACE +[(rdflib.term.URIRef('ex:c'), rdflib.term.URIRef('ex:c')), + (rdflib.term.URIRef('ex:a'), rdflib.term.URIRef('ex:c'))] + +>>> list(eval_path(g, (None, e.p3*OneOrMore, e.a))) # doctest: +NORMALIZE_WHITESPACE +[(rdflib.term.URIRef('ex:h'), rdflib.term.URIRef('ex:a')), + (rdflib.term.URIRef('ex:g'), rdflib.term.URIRef('ex:a')), + (rdflib.term.URIRef('ex:c'), rdflib.term.URIRef('ex:a'))] + +>>> list(eval_path(g, (None, e.p3*ZeroOrMore, e.a))) # doctest: +NORMALIZE_WHITESPACE +[(rdflib.term.URIRef('ex:a'), rdflib.term.URIRef('ex:a')), + (rdflib.term.URIRef('ex:h'), rdflib.term.URIRef('ex:a')), + (rdflib.term.URIRef('ex:g'), rdflib.term.URIRef('ex:a')), + (rdflib.term.URIRef('ex:c'), rdflib.term.URIRef('ex:a'))] + +>>> list(eval_path(g, (None, -e.p1, e.f))) == [(e.a, e.f)] +True +>>> list(eval_path(g, (None, -(e.p1|e.p2), e.c))) == [] +True +>>> list(eval_path(g, (None, -~e.p2, e.j))) == [(e.g, e.j)] +True +>>> list(eval_path(g, (None, ~(e.p1/e.p2), e.a))) == [(e.e, e.a)] +True +>>> list(eval_path(g, (None, e.p1/e.p3/e.p3, e.h))) == [(e.a, e.h)] +True + +>>> list(eval_path(g, (e.q, e.px*OneOrMore, None))) +[(rdflib.term.URIRef('ex:q'), rdflib.term.URIRef('ex:q'))] + +>>> list(eval_path(g, (e.c, (e.p2|e.p3)*ZeroOrMore, e.j))) +[(rdflib.term.URIRef('ex:c'), rdflib.term.URIRef('ex:j'))] + +``` + +No vars specified: + +```python +>>> sorted(list(eval_path(g, (None, e.p3*OneOrMore, None)))) #doctest: +NORMALIZE_WHITESPACE +[(rdflib.term.URIRef('ex:c'), rdflib.term.URIRef('ex:a')), + (rdflib.term.URIRef('ex:c'), rdflib.term.URIRef('ex:g')), + (rdflib.term.URIRef('ex:c'), rdflib.term.URIRef('ex:h')), + (rdflib.term.URIRef('ex:g'), rdflib.term.URIRef('ex:a')), + (rdflib.term.URIRef('ex:g'), rdflib.term.URIRef('ex:h')), + (rdflib.term.URIRef('ex:h'), rdflib.term.URIRef('ex:a'))] + +``` +""" + +from __future__ import annotations + +import warnings +from abc import ABC, abstractmethod +from functools import total_ordering +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Generator, + Iterator, + List, + Optional, + Set, + Tuple, + Union, +) + +from rdflib.term import Node, URIRef + +if TYPE_CHECKING: + from rdflib._type_checking import _MulPathMod + from rdflib.graph import Graph, _ObjectType, _PredicateType, _SubjectType + from rdflib.namespace import NamespaceManager + + +# property paths + +ZeroOrMore = "*" +OneOrMore = "+" +ZeroOrOne = "?" + + +def _n3( + arg: Union[URIRef, Path], namespace_manager: Optional[NamespaceManager] = None +) -> str: + if isinstance(arg, (SequencePath, AlternativePath)) and len(arg.args) > 1: + return "(%s)" % arg.n3(namespace_manager) + return arg.n3(namespace_manager) + + +@total_ordering +class Path(ABC): + """Base class for all property paths.""" + + __or__: Callable[[Path, Union[URIRef, Path]], AlternativePath] + __invert__: Callable[[Path], InvPath] + __neg__: Callable[[Path], NegatedPath] + __truediv__: Callable[[Path, Union[URIRef, Path]], SequencePath] + __mul__: Callable[[Path, str], MulPath] + + @abstractmethod + def eval( + self, + graph: Graph, + subj: Optional[_SubjectType] = None, + obj: Optional[_ObjectType] = None, + ) -> Iterator[Tuple[_SubjectType, _ObjectType]]: ... + + @abstractmethod + def n3(self, namespace_manager: Optional[NamespaceManager] = None) -> str: ... + + def __hash__(self): + return hash(repr(self)) + + def __eq__(self, other): + return repr(self) == repr(other) + + def __lt__(self, other: Any) -> bool: + if not isinstance(other, (Path, Node)): + raise TypeError( + "unorderable types: %s() < %s()" % (repr(self), repr(other)) + ) + return repr(self) < repr(other) + + +class InvPath(Path): + def __init__(self, arg: Union[Path, URIRef]): + self.arg = arg + + def eval( + self, + graph: Graph, + subj: Optional[_SubjectType] = None, + obj: Optional[_ObjectType] = None, + ) -> Generator[Tuple[_ObjectType, _SubjectType], None, None]: + for s, o in eval_path(graph, (obj, self.arg, subj)): + yield o, s + + def __repr__(self) -> str: + return "Path(~%s)" % (self.arg,) + + def n3(self, namespace_manager: Optional[NamespaceManager] = None) -> str: + return "^%s" % _n3(self.arg, namespace_manager) + + +class SequencePath(Path): + def __init__(self, *args: Union[Path, URIRef]): + self.args: List[Union[Path, URIRef]] = [] + for a in args: + if isinstance(a, SequencePath): + self.args += a.args + else: + self.args.append(a) + + def eval( + self, + graph: Graph, + subj: Optional[_SubjectType] = None, + obj: Optional[_ObjectType] = None, + ) -> Generator[Tuple[_SubjectType, _ObjectType], None, None]: + def _eval_seq( + paths: List[Union[Path, URIRef]], + subj: Optional[_SubjectType], + obj: Optional[_ObjectType], + ) -> Generator[Tuple[_SubjectType, _ObjectType], None, None]: + if paths[1:]: + for s, o in eval_path(graph, (subj, paths[0], None)): + for r in _eval_seq(paths[1:], o, obj): + yield s, r[1] + + else: + for s, o in eval_path(graph, (subj, paths[0], obj)): + yield s, o + + def _eval_seq_bw( + paths: List[Union[Path, URIRef]], + subj: Optional[_SubjectType], + obj: _ObjectType, + ) -> Generator[Tuple[_SubjectType, _ObjectType], None, None]: + if paths[:-1]: + for s, o in eval_path(graph, (None, paths[-1], obj)): + for r in _eval_seq(paths[:-1], subj, s): + yield r[0], o + + else: + for s, o in eval_path(graph, (subj, paths[0], obj)): + yield s, o + + if subj: + return _eval_seq(self.args, subj, obj) + elif obj: + return _eval_seq_bw(self.args, subj, obj) + else: # no vars bound, we can start anywhere + return _eval_seq(self.args, subj, obj) + + def __repr__(self) -> str: + return "Path(%s)" % " / ".join(str(x) for x in self.args) + + def n3(self, namespace_manager: Optional[NamespaceManager] = None) -> str: + return "/".join(_n3(a, namespace_manager) for a in self.args) + + +class AlternativePath(Path): + def __init__(self, *args: Union[Path, URIRef]): + self.args: List[Union[Path, URIRef]] = [] + for a in args: + if isinstance(a, AlternativePath): + self.args += a.args + else: + self.args.append(a) + + def eval( + self, + graph: Graph, + subj: Optional[_SubjectType] = None, + obj: Optional[_ObjectType] = None, + ) -> Generator[Tuple[_SubjectType, _ObjectType], None, None]: + for x in self.args: + for y in eval_path(graph, (subj, x, obj)): + yield y + + def __repr__(self) -> str: + return "Path(%s)" % " | ".join(str(x) for x in self.args) + + def n3(self, namespace_manager: Optional[NamespaceManager] = None) -> str: + return "|".join(_n3(a, namespace_manager) for a in self.args) + + +class MulPath(Path): + def __init__(self, path: Union[Path, URIRef], mod: _MulPathMod): + self.path = path + self.mod = mod + + if mod == ZeroOrOne: + self.zero = True + self.more = False + elif mod == ZeroOrMore: + self.zero = True + self.more = True + elif mod == OneOrMore: + self.zero = False + self.more = True + else: + raise Exception("Unknown modifier %s" % mod) + + def eval( + self, + graph: Graph, + subj: Optional[_SubjectType] = None, + obj: Optional[_ObjectType] = None, + first: bool = True, + ) -> Generator[Tuple[_SubjectType, _ObjectType], None, None]: + if self.zero and first: + if subj and obj: + if subj == obj: + yield subj, obj + elif subj: + yield subj, subj + elif obj: + yield obj, obj + + def _fwd( + subj: Optional[_SubjectType] = None, + obj: Optional[_ObjectType] = None, + seen: Optional[Set[_SubjectType]] = None, + ) -> Generator[Tuple[_SubjectType, _ObjectType], None, None]: + # type error: Item "None" of "Optional[Set[Node]]" has no attribute "add" + # type error: Argument 1 to "add" of "set" has incompatible type "Optional[Node]"; expected "Node" + seen.add(subj) # type: ignore[union-attr, arg-type] + + for s, o in eval_path(graph, (subj, self.path, None)): + if not obj or o == obj: + yield s, o + if self.more: + # type error: Unsupported right operand type for in ("Optional[Set[Node]]") + if o in seen: # type: ignore[operator] + continue + for s2, o2 in _fwd(o, obj, seen): + yield s, o2 + + def _bwd( + subj: Optional[_SubjectType] = None, + obj: Optional[_ObjectType] = None, + seen: Optional[Set[_ObjectType]] = None, + ) -> Generator[Tuple[_SubjectType, _ObjectType], None, None]: + # type error: Item "None" of "Optional[Set[Node]]" has no attribute "add" + # type error: Argument 1 to "add" of "set" has incompatible type "Optional[Node]"; expected "Node" + seen.add(obj) # type: ignore[union-attr, arg-type] + + for s, o in eval_path(graph, (None, self.path, obj)): + if not subj or subj == s: + yield s, o + if self.more: + # type error: Unsupported right operand type for in ("Optional[Set[Node]]") + if s in seen: # type: ignore[operator] + continue + + for s2, o2 in _bwd(None, s, seen): + yield s2, o + + def _all_fwd_paths() -> Generator[Tuple[_SubjectType, _ObjectType], None, None]: + if self.zero: + seen1 = set() + # According to the spec, ALL nodes are possible solutions + # (even literals) + # we cannot do this without going through ALL triples + # unless we keep an index of all terms somehow + # but let's just hope this query doesn't happen very often... + for s, o in graph.subject_objects(None): + if s not in seen1: + seen1.add(s) + yield s, s + if o not in seen1: + seen1.add(o) + yield o, o + + seen = set() + for s, o in eval_path(graph, (None, self.path, None)): + if not self.more: + yield s, o + else: + if s not in seen: + seen.add(s) + f = list(_fwd(s, None, set())) + for s1, o1 in f: + assert s1 == s + yield s1, o1 + + done = set() # the spec does, by defn, not allow duplicates + if subj: + for x in _fwd(subj, obj, set()): + if x not in done: + done.add(x) + yield x + elif obj: + for x in _bwd(subj, obj, set()): + if x not in done: + done.add(x) + yield x + else: + for x in _all_fwd_paths(): + if x not in done: + done.add(x) + yield x + + def __repr__(self) -> str: + return "Path(%s%s)" % (self.path, self.mod) + + def n3(self, namespace_manager: Optional[NamespaceManager] = None) -> str: + return "%s%s" % (_n3(self.path, namespace_manager), self.mod) + + +class NegatedPath(Path): + def __init__(self, arg: Union[AlternativePath, InvPath, URIRef]): + self.args: List[Union[URIRef, Path]] + if isinstance(arg, (URIRef, InvPath)): + self.args = [arg] + elif isinstance(arg, AlternativePath): + self.args = arg.args + else: + raise Exception( + "Can only negate URIRefs, InvPaths or " + + "AlternativePaths, not: %s" % (arg,) + ) + + def eval(self, graph, subj=None, obj=None): + for s, p, o in graph.triples((subj, None, obj)): + for a in self.args: + if isinstance(a, URIRef): + if p == a: + break + elif isinstance(a, InvPath): + if (o, a.arg, s) in graph: + break + else: + raise Exception("Invalid path in NegatedPath: %s" % a) + else: + yield s, o + + def __repr__(self) -> str: + return "Path(! %s)" % ",".join(str(x) for x in self.args) + + def n3(self, namespace_manager: Optional[NamespaceManager] = None) -> str: + return "!(%s)" % ("|".join(_n3(arg, namespace_manager) for arg in self.args)) + + +class PathList(list): + pass + + +def path_alternative(self: Union[URIRef, Path], other: Union[URIRef, Path]): + """ + alternative path + """ + if not isinstance(other, (URIRef, Path)): + raise Exception("Only URIRefs or Paths can be in paths!") + return AlternativePath(self, other) + + +def path_sequence(self: Union[URIRef, Path], other: Union[URIRef, Path]): + """ + sequence path + """ + if not isinstance(other, (URIRef, Path)): + raise Exception("Only URIRefs or Paths can be in paths!") + return SequencePath(self, other) + + +def evalPath( # noqa: N802 + graph: Graph, + t: Tuple[ + Optional[_SubjectType], + Union[None, Path, _PredicateType], + Optional[_ObjectType], + ], +) -> Iterator[Tuple[_SubjectType, _ObjectType]]: + warnings.warn( + DeprecationWarning( + "rdflib.path.evalPath() is deprecated, use the (snake-cased) eval_path(). " + "The mixed-case evalPath() function name is incompatible with PEP8 " + "recommendations and will be replaced by eval_path() in rdflib 7.0.0." + ) + ) + return eval_path(graph, t) + + +def eval_path( + graph: Graph, + t: Tuple[ + Optional[_SubjectType], + Union[None, Path, _PredicateType], + Optional[_ObjectType], + ], +) -> Iterator[Tuple[_SubjectType, _ObjectType]]: + return ((s, o) for s, p, o in graph.triples(t)) + + +def mul_path(p: Union[URIRef, Path], mul: _MulPathMod) -> MulPath: + """ + cardinality path + """ + return MulPath(p, mul) + + +def inv_path(p: Union[URIRef, Path]) -> InvPath: + """ + inverse path + """ + return InvPath(p) + + +def neg_path(p: Union[URIRef, AlternativePath, InvPath]) -> NegatedPath: + """ + negated path + """ + return NegatedPath(p) + + +if __name__ == "__main__": + pass +else: + # monkey patch + # (these cannot be directly in terms.py + # as it would introduce circular imports) + + URIRef.__or__ = path_alternative + # ignore typing here as URIRef inherits from str, + # which has an incompatible definition of __mul__. + URIRef.__mul__ = mul_path # type: ignore + URIRef.__invert__ = inv_path + URIRef.__neg__ = neg_path + URIRef.__truediv__ = path_sequence + + Path.__invert__ = inv_path + # type error: Incompatible types in assignment (expression has type "Callable[[Union[URIRef, AlternativePath, InvPath]], NegatedPath]", variable has type "Callable[[Path], NegatedPath]") + Path.__neg__ = neg_path # type: ignore[assignment] + # type error: Incompatible types in assignment (expression has type "Callable[[Union[URIRef, Path], Literal['*', '+', '?']], MulPath]", variable has type "Callable[[Path, str], MulPath]") + Path.__mul__ = mul_path # type: ignore[assignment] + Path.__or__ = path_alternative + Path.__truediv__ = path_sequence diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rdflib/plugin.py b/TTS/Kokoro/.venv/Lib/site-packages/rdflib/plugin.py new file mode 100644 index 0000000000000000000000000000000000000000..d0ad7247d7fd29aa4f99a615f7c4177cd4a3c530 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rdflib/plugin.py @@ -0,0 +1,626 @@ +"""Plugin support for rdf. + +There are a number of plugin points for rdf: parser, serializer, +store, query processor, and query result. Plugins can be registered +either through setuptools entry_points or by calling +rdf.plugin.register directly. + +If you have a package that uses a setuptools based `setup.py` you can add the +following to your setup: + +```python +entry_points = { + 'rdf.plugins.parser': [ + 'nt = rdf.plugins.parsers.ntriples:NTParser', + ], + 'rdf.plugins.serializer': [ + 'nt = rdf.plugins.serializers.NTSerializer:NTSerializer', + ], + } +``` + +See the [setuptools dynamic discovery of services and plugins](http://peak.telecommunity.com/DevCenter/setuptools#dynamic-discovery-of-services-and-plugins) +for moreinformation. +""" + +from __future__ import annotations + +from importlib.metadata import EntryPoint, entry_points +from typing import ( + TYPE_CHECKING, + Any, + Dict, + Generic, + Iterator, + Optional, + Tuple, + Type, + TypeVar, + overload, +) + +import rdflib.plugins.stores.berkeleydb +from rdflib.exceptions import Error +from rdflib.parser import Parser +from rdflib.query import ( + Processor, + Result, + ResultParser, + ResultSerializer, + UpdateProcessor, +) +from rdflib.serializer import Serializer +from rdflib.store import Store + +__all__ = [ + "register", + "get", + "plugins", + "PluginException", + "Plugin", + "PluginT", + "PKGPlugin", +] + +rdflib_entry_points = { + "rdf.plugins.store": Store, + "rdf.plugins.serializer": Serializer, + "rdf.plugins.parser": Parser, + "rdf.plugins.resultparser": ResultParser, + "rdf.plugins.resultserializer": ResultSerializer, + "rdf.plugins.queryprocessor": Processor, + "rdf.plugins.queryresult": Result, + "rdf.plugins.updateprocessor": UpdateProcessor, +} + +_plugins: Dict[Tuple[str, Type[Any]], Plugin] = {} + + +class PluginException(Error): # noqa: N818 + pass + + +#: A generic type variable for plugins +PluginT = TypeVar("PluginT") + + +class Plugin(Generic[PluginT]): + def __init__( + self, name: str, kind: Type[PluginT], module_path: str, class_name: str + ): + self.name = name + self.kind = kind + self.module_path = module_path + self.class_name = class_name + self._class: Optional[Type[PluginT]] = None + + def getClass(self) -> Type[PluginT]: # noqa: N802 + if self._class is None: + module = __import__(self.module_path, globals(), locals(), [""]) + self._class = getattr(module, self.class_name) + return self._class + + +class PKGPlugin(Plugin[PluginT]): + def __init__(self, name: str, kind: Type[PluginT], ep: EntryPoint): + self.name = name + self.kind = kind + self.ep = ep + self._class: Optional[Type[PluginT]] = None + + def getClass(self) -> Type[PluginT]: # noqa: N802 + if self._class is None: + self._class = self.ep.load() + return self._class + + +def register(name: str, kind: Type[Any], module_path, class_name): + """ + Register the plugin for (name, kind). The module_path and + class_name should be the path to a plugin class. + """ + p = Plugin(name, kind, module_path, class_name) + _plugins[(name, kind)] = p + + +def get(name: str, kind: Type[PluginT]) -> Type[PluginT]: + """ + Return the class for the specified (name, kind). Raises a + PluginException if unable to do so. + """ + try: + p: Plugin[PluginT] = _plugins[(name, kind)] + except KeyError: + raise PluginException("No plugin registered for (%s, %s)" % (name, kind)) + return p.getClass() + + +all_entry_points = entry_points() +if hasattr(all_entry_points, "select"): + for entry_point, kind in rdflib_entry_points.items(): + for ep in all_entry_points.select(group=entry_point): + _plugins[(ep.name, kind)] = PKGPlugin(ep.name, kind, ep) +else: + # Prior to Python 3.10, this returns a dict instead of the selection interface, which is slightly slower + if TYPE_CHECKING: + assert isinstance(all_entry_points, dict) + for entry_point, kind in rdflib_entry_points.items(): + for ep in all_entry_points.get(entry_point, []): + _plugins[(ep.name, kind)] = PKGPlugin(ep.name, kind, ep) + + +@overload +def plugins( + name: Optional[str] = ..., kind: Type[PluginT] = ... +) -> Iterator[Plugin[PluginT]]: ... + + +@overload +def plugins(name: Optional[str] = ..., kind: None = ...) -> Iterator[Plugin]: ... + + +def plugins( + name: Optional[str] = None, kind: Optional[Type[PluginT]] = None +) -> Iterator[Plugin[PluginT]]: + """ + A generator of the plugins. + + Pass in name and kind to filter... else leave None to match all. + """ + for p in _plugins.values(): + if (name is None or name == p.name) and (kind is None or kind == p.kind): + yield p + + +# Register Stores + +if rdflib.plugins.stores.berkeleydb.has_bsddb: + # Checks for BerkeleyDB before registering it + register( + "BerkeleyDB", + Store, + "rdflib.plugins.stores.berkeleydb", + "BerkeleyDB", + ) +register( + "default", + Store, + "rdflib.plugins.stores.memory", + "Memory", +) +register( + "Memory", + Store, + "rdflib.plugins.stores.memory", + "Memory", +) +register( + "SimpleMemory", + Store, + "rdflib.plugins.stores.memory", + "SimpleMemory", +) +register( + "Auditable", + Store, + "rdflib.plugins.stores.auditable", + "AuditableStore", +) +register( + "Concurrent", + Store, + "rdflib.plugins.stores.concurrent", + "ConcurrentStore", +) + +register( + "SPARQLStore", + Store, + "rdflib.plugins.stores.sparqlstore", + "SPARQLStore", +) +register( + "SPARQLUpdateStore", + Store, + "rdflib.plugins.stores.sparqlstore", + "SPARQLUpdateStore", +) + +# Register Triple Serializers +register( + "application/rdf+xml", + Serializer, + "rdflib.plugins.serializers.rdfxml", + "XMLSerializer", +) +register( + "xml", + Serializer, + "rdflib.plugins.serializers.rdfxml", + "XMLSerializer", +) +register( + "pretty-xml", + Serializer, + "rdflib.plugins.serializers.rdfxml", + "PrettyXMLSerializer", +) +register( + "text/n3", + Serializer, + "rdflib.plugins.serializers.n3", + "N3Serializer", +) +register( + "n3", + Serializer, + "rdflib.plugins.serializers.n3", + "N3Serializer", +) +register( + "text/turtle", + Serializer, + "rdflib.plugins.serializers.turtle", + "TurtleSerializer", +) +register( + "turtle", + Serializer, + "rdflib.plugins.serializers.turtle", + "TurtleSerializer", +) +register( + "ttl", + Serializer, + "rdflib.plugins.serializers.turtle", + "TurtleSerializer", +) +register( + "longturtle", + Serializer, + "rdflib.plugins.serializers.longturtle", + "LongTurtleSerializer", +) +register( + "application/n-triples", + Serializer, + "rdflib.plugins.serializers.nt", + "NTSerializer", +) +register( + "ntriples", + Serializer, + "rdflib.plugins.serializers.nt", + "NTSerializer", +) +register( + "nt", + Serializer, + "rdflib.plugins.serializers.nt", + "NTSerializer", +) +register( + "nt11", + Serializer, + "rdflib.plugins.serializers.nt", + "NT11Serializer", +) +register( + "json-ld", + Serializer, + "rdflib.plugins.serializers.jsonld", + "JsonLDSerializer", +) +register( + "application/ld+json", + Serializer, + "rdflib.plugins.serializers.jsonld", + "JsonLDSerializer", +) + +# Register Quad Serializers +register( + "application/n-quads", + Serializer, + "rdflib.plugins.serializers.nquads", + "NQuadsSerializer", +) +register( + "nquads", + Serializer, + "rdflib.plugins.serializers.nquads", + "NQuadsSerializer", +) +register( + "application/trix", + Serializer, + "rdflib.plugins.serializers.trix", + "TriXSerializer", +) +register( + "trix", + Serializer, + "rdflib.plugins.serializers.trix", + "TriXSerializer", +) +register( + "application/trig", + Serializer, + "rdflib.plugins.serializers.trig", + "TrigSerializer", +) +register( + "trig", + Serializer, + "rdflib.plugins.serializers.trig", + "TrigSerializer", +) +register( + "hext", + Serializer, + "rdflib.plugins.serializers.hext", + "HextuplesSerializer", +) +register( + "patch", + Serializer, + "rdflib.plugins.serializers.patch", + "PatchSerializer", +) + +# Register Triple Parsers +register( + "application/rdf+xml", + Parser, + "rdflib.plugins.parsers.rdfxml", + "RDFXMLParser", +) +register( + "xml", + Parser, + "rdflib.plugins.parsers.rdfxml", + "RDFXMLParser", +) +register( + "text/n3", + Parser, + "rdflib.plugins.parsers.notation3", + "N3Parser", +) +register( + "n3", + Parser, + "rdflib.plugins.parsers.notation3", + "N3Parser", +) +register( + "text/turtle", + Parser, + "rdflib.plugins.parsers.notation3", + "TurtleParser", +) +register( + "turtle", + Parser, + "rdflib.plugins.parsers.notation3", + "TurtleParser", +) +register( + "ttl", + Parser, + "rdflib.plugins.parsers.notation3", + "TurtleParser", +) +register( + "application/n-triples", + Parser, + "rdflib.plugins.parsers.ntriples", + "NTParser", +) +register( + "ntriples", + Parser, + "rdflib.plugins.parsers.ntriples", + "NTParser", +) +register( + "nt", + Parser, + "rdflib.plugins.parsers.ntriples", + "NTParser", +) +register( + "nt11", + Parser, + "rdflib.plugins.parsers.ntriples", + "NTParser", +) +register( + "application/ld+json", + Parser, + "rdflib.plugins.parsers.jsonld", + "JsonLDParser", +) +register( + "json-ld", + Parser, + "rdflib.plugins.parsers.jsonld", + "JsonLDParser", +) + +# Register Quad Parsers +register( + "application/n-quads", + Parser, + "rdflib.plugins.parsers.nquads", + "NQuadsParser", +) +register( + "nquads", + Parser, + "rdflib.plugins.parsers.nquads", + "NQuadsParser", +) +register( + "application/trix", + Parser, + "rdflib.plugins.parsers.trix", + "TriXParser", +) +register( + "trix", + Parser, + "rdflib.plugins.parsers.trix", + "TriXParser", +) +register( + "application/trig", + Parser, + "rdflib.plugins.parsers.trig", + "TrigParser", +) +register( + "trig", + Parser, + "rdflib.plugins.parsers.trig", + "TrigParser", +) +register( + "hext", + Parser, + "rdflib.plugins.parsers.hext", + "HextuplesParser", +) + +# Register RDF Patch Parsers +register( + "patch", + Parser, + "rdflib.plugins.parsers.patch", + "RDFPatchParser", +) + +# Register SPARQL Processors +register( + "sparql", + Result, + "rdflib.plugins.sparql.processor", + "SPARQLResult", +) +register( + "sparql", + Processor, + "rdflib.plugins.sparql.processor", + "SPARQLProcessor", +) +register( + "sparql", + UpdateProcessor, + "rdflib.plugins.sparql.processor", + "SPARQLUpdateProcessor", +) + +# Register SPARQL Result Serializers +register( + "xml", + ResultSerializer, + "rdflib.plugins.sparql.results.xmlresults", + "XMLResultSerializer", +) +register( + "application/sparql-results+xml", + ResultSerializer, + "rdflib.plugins.sparql.results.xmlresults", + "XMLResultSerializer", +) +register( + "txt", + ResultSerializer, + "rdflib.plugins.sparql.results.txtresults", + "TXTResultSerializer", +) +register( + "json", + ResultSerializer, + "rdflib.plugins.sparql.results.jsonresults", + "JSONResultSerializer", +) +register( + "application/sparql-results+json", + ResultSerializer, + "rdflib.plugins.sparql.results.jsonresults", + "JSONResultSerializer", +) +register( + "csv", + ResultSerializer, + "rdflib.plugins.sparql.results.csvresults", + "CSVResultSerializer", +) +register( + "text/csv", + ResultSerializer, + "rdflib.plugins.sparql.results.csvresults", + "CSVResultSerializer", +) + +# Register SPARQL Result Parsers +register( + "xml", + ResultParser, + "rdflib.plugins.sparql.results.xmlresults", + "XMLResultParser", +) +register( + "application/sparql-results+xml", + ResultParser, + "rdflib.plugins.sparql.results.xmlresults", + "XMLResultParser", +) +register( + "json", + ResultParser, + "rdflib.plugins.sparql.results.jsonresults", + "JSONResultParser", +) +register( + "application/sparql-results+json", + ResultParser, + "rdflib.plugins.sparql.results.jsonresults", + "JSONResultParser", +) +register( + "csv", + ResultParser, + "rdflib.plugins.sparql.results.csvresults", + "CSVResultParser", +) +register( + "text/csv", + ResultParser, + "rdflib.plugins.sparql.results.csvresults", + "CSVResultParser", +) +register( + "tsv", + ResultParser, + "rdflib.plugins.sparql.results.tsvresults", + "TSVResultParser", +) +register( + "text/tab-separated-values", + ResultParser, + "rdflib.plugins.sparql.results.tsvresults", + "TSVResultParser", +) + +graph_parsers = {parser.name for parser in plugins(kind=Parser)} +result_parsers = {parser.name for parser in plugins(kind=ResultParser)} +graph_result_parsers = graph_parsers - result_parsers +for parser_name in graph_result_parsers: + register( + parser_name, + ResultParser, + "rdflib.plugins.sparql.results.graph", + "GraphResultParser", + ) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rdflib/py.typed b/TTS/Kokoro/.venv/Lib/site-packages/rdflib/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..cff72238ec020808168f3923f8ccf227a9e5e50a --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rdflib/py.typed @@ -0,0 +1,2 @@ +# PEP 561 marker file +# https://www.python.org/dev/peps/pep-0561/ diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rdflib/query.py b/TTS/Kokoro/.venv/Lib/site-packages/rdflib/query.py new file mode 100644 index 0000000000000000000000000000000000000000..87fdf016bfc6d4be5b1e1ca6eebc5fa67129366b --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rdflib/query.py @@ -0,0 +1,431 @@ +from __future__ import annotations + +import itertools +import types +import warnings +from io import BytesIO +from typing import ( + IO, + TYPE_CHECKING, + Any, + BinaryIO, + Dict, + Iterator, + List, + Mapping, + MutableSequence, + Optional, + Tuple, + Union, + cast, + overload, +) +from urllib.parse import urlparse +from urllib.request import url2pathname + +__all__ = [ + "Processor", + "UpdateProcessor", + "Result", + "ResultRow", + "ResultParser", + "ResultSerializer", + "ResultException", + "EncodeOnlyUnicode", +] + +import rdflib.term + +if TYPE_CHECKING: + from rdflib.graph import Graph, _TripleType + from rdflib.plugins.sparql.sparql import Query, Update + from rdflib.term import Identifier, Variable + + +class Processor: + """ + Query plugin interface. + + This module is useful for those wanting to write a query processor + that can plugin to rdf. If you are wanting to execute a query you + likely want to do so through the Graph class query method. + """ + + def __init__(self, graph: Graph): + pass + + # type error: Missing return statement + def query( # type: ignore[empty-body] + self, + strOrQuery: Union[str, Query], # noqa: N803 + initBindings: Mapping[str, Identifier] = {}, # noqa: N803 + initNs: Mapping[str, Any] = {}, # noqa: N803 + DEBUG: bool = False, # noqa: N803 + ) -> Mapping[str, Any]: + pass + + +class UpdateProcessor: + """Update plugin interface. + + This module is useful for those wanting to write an update + processor that can plugin to rdflib. If you are wanting to execute + an update statement you likely want to do so through the Graph + class update method. + + !!! example "New in version 4.0" + """ + + def __init__(self, graph: Graph): + pass + + def update( + self, + strOrQuery: Union[str, Update], # noqa: N803 + initBindings: Mapping[str, Identifier] = {}, # noqa: N803 + initNs: Mapping[str, Any] = {}, # noqa: N803 + ) -> None: + pass + + +class ResultException(Exception): # noqa: N818 + pass + + +class EncodeOnlyUnicode: + """This is a crappy work-around for http://bugs.python.org/issue11649""" + + def __init__(self, stream: BinaryIO): + self.__stream = stream + + def write(self, arg): + if isinstance(arg, str): + self.__stream.write(arg.encode("utf-8")) + else: + self.__stream.write(arg) + + def __getattr__(self, name: str) -> Any: + return getattr(self.__stream, name) + + +class ResultRow(Tuple[rdflib.term.Identifier, ...]): + """A single result row allows accessing bindings as attributes or with [] + + ```python + >>> from rdflib import URIRef, Variable + >>> rr=ResultRow({ Variable('a'): URIRef('urn:cake') }, [Variable('a')]) + + >>> rr[0] + rdflib.term.URIRef('urn:cake') + >>> rr[1] + Traceback (most recent call last): + ... + IndexError: tuple index out of range + + >>> rr.a + rdflib.term.URIRef('urn:cake') + >>> rr.b + Traceback (most recent call last): + ... + AttributeError: b + + >>> rr['a'] + rdflib.term.URIRef('urn:cake') + >>> rr['b'] + Traceback (most recent call last): + ... + KeyError: 'b' + + >>> rr[Variable('a')] + rdflib.term.URIRef('urn:cake') + + ``` + + !!! example "New in version 4.0" + """ + + labels: Mapping[str, int] + + def __new__(cls, values: Mapping[Variable, Identifier], labels: List[Variable]): + # type error: Value of type variable "Self" of "__new__" of "tuple" cannot be "ResultRow" [type-var] + # type error: Generator has incompatible item type "Optional[Identifier]"; expected "_T_co" [misc] + instance = super(ResultRow, cls).__new__(cls, (values.get(v) for v in labels)) # type: ignore[type-var, misc, unused-ignore] + instance.labels = dict((str(x[1]), x[0]) for x in enumerate(labels)) + return instance + + def __getattr__(self, name: str) -> Identifier: + if name not in self.labels: + raise AttributeError(name) + return tuple.__getitem__(self, self.labels[name]) + + # type error: Signature of "__getitem__" incompatible with supertype "tuple" + # type error: Signature of "__getitem__" incompatible with supertype "Sequence" + def __getitem__(self, name: Union[str, int, Any]) -> Identifier: # type: ignore[override] + try: + # type error: Invalid index type "Union[str, int, Any]" for "tuple"; expected type "int" + return tuple.__getitem__(self, name) # type: ignore[index] + except TypeError: + if name in self.labels: + # type error: Invalid index type "Union[str, int, slice, Any]" for "Mapping[str, int]"; expected type "str" + return tuple.__getitem__(self, self.labels[name]) # type: ignore[index] + if str(name) in self.labels: # passing in variable object + return tuple.__getitem__(self, self.labels[str(name)]) + raise KeyError(name) + + @overload + def get(self, name: str, default: Identifier) -> Identifier: ... + + @overload + def get( + self, name: str, default: Optional[Identifier] = ... + ) -> Optional[Identifier]: ... + + def get( + self, name: str, default: Optional[Identifier] = None + ) -> Optional[Identifier]: + try: + return self[name] + except KeyError: + return default + + def asdict(self) -> Dict[str, Identifier]: + return dict((v, self[v]) for v in self.labels if self[v] is not None) + + +class Result: + """ + A common class for representing query result. + + There is a bit of magic here that makes this appear like different + Python objects, depending on the type of result. + + If the type is "SELECT", iterating will yield lists of ResultRow objects + + If the type is "ASK", iterating will yield a single bool (or + bool(result) will return the same bool) + + If the type is "CONSTRUCT" or "DESCRIBE" iterating will yield the + triples. + + `len(result)` also works. + """ + + def __init__(self, type_: str): + if type_ not in ("CONSTRUCT", "DESCRIBE", "SELECT", "ASK"): + raise ResultException("Unknown Result type: %s" % type_) + + self.type = type_ + #: variables contained in the result. + self.vars: Optional[List[Variable]] = None + """a list of variables contained in the result""" + self._bindings: MutableSequence[Mapping[Variable, Identifier]] = None # type: ignore[assignment] + self._genbindings: Optional[Iterator[Mapping[Variable, Identifier]]] = None + self.askAnswer: Optional[bool] = None + self.graph: Optional[Graph] = None + + @property + def bindings(self) -> MutableSequence[Mapping[Variable, Identifier]]: + """ + a list of variable bindings as dicts + """ + if self._genbindings: + self._bindings += list(self._genbindings) + self._genbindings = None + + return self._bindings + + @bindings.setter + def bindings( + self, + b: Union[ + MutableSequence[Mapping[Variable, Identifier]], + Iterator[Mapping[Variable, Identifier]], + ], + ) -> None: + if isinstance(b, (types.GeneratorType, itertools.islice)): + self._genbindings = b + self._bindings = [] + else: + # type error: Incompatible types in assignment (expression has type "Union[MutableSequence[Mapping[Variable, Identifier]], Iterator[Mapping[Variable, Identifier]]]", variable has type "MutableSequence[Mapping[Variable, Identifier]]") + self._bindings = b # type: ignore[assignment] + + @staticmethod + def parse( + source: Optional[IO] = None, + format: Optional[str] = None, + content_type: Optional[str] = None, + **kwargs: Any, + ) -> Result: + """Parse a query result from a source.""" + from rdflib import plugin + + if format: + plugin_key = format + elif content_type: + plugin_key = content_type.split(";", 1)[0] + else: + plugin_key = "xml" + + parser = plugin.get(plugin_key, ResultParser)() + + # type error: Argument 1 to "parse" of "ResultParser" has incompatible type "Optional[IO[Any]]"; expected "IO[Any]" + return parser.parse( + source, content_type=content_type, **kwargs # type:ignore[arg-type] + ) + + def serialize( + self, + destination: Optional[Union[str, IO]] = None, + encoding: str = "utf-8", + format: str = "xml", + **args: Any, + ) -> Optional[bytes]: + """ + Serialize the query result. + + + Args: + destination: Path of file output or BufferedIOBase object + to write the output to. If `None` this function + will return the output as `bytes` + encoding: Encoding of output. + format: The format used for serialization. + See [sparql.results module][rdflib.plugins.sparql.results] + for all builtin SPARQL result serialization. + Further serializer can be loaded [as plugin][rdflib.plugin]. + Some example formats are + [csv][rdflib.plugins.sparql.results.csvresults.CSVResultSerializer], + [json][rdflib.plugins.sparql.results.jsonresults.JSONResultSerializer], + [txt][rdflib.plugins.sparql.results.txtresults.TXTResultSerializer] + or + [xml][rdflib.plugins.sparql.results.xmlresults.XMLResultSerializer] + + Returns: + Serialized result, when destination is not given. + """ + if self.type in ("CONSTRUCT", "DESCRIBE"): + # type error: Item "None" of "Optional[Graph]" has no attribute "serialize" + # type error: Incompatible return value type (got "Union[bytes, str, Graph, Any]", expected "Optional[bytes]") + return self.graph.serialize( # type: ignore[union-attr,return-value] + destination, encoding=encoding, format=format, **args + ) + + """stolen wholesale from graph.serialize""" + from rdflib import plugin + + serializer = plugin.get(format, ResultSerializer)(self) + if destination is None: + streamb: BytesIO = BytesIO() + stream2 = EncodeOnlyUnicode(streamb) # TODO: Remove the need for this + # TODO: All QueryResult serializers should write to a Bytes Stream. + # type error: Argument 1 to "serialize" of "ResultSerializer" has incompatible type "EncodeOnlyUnicode"; expected "IO[Any]" + serializer.serialize(stream2, encoding=encoding, **args) # type: ignore[arg-type] + return streamb.getvalue() + if hasattr(destination, "write"): + stream = cast(IO[bytes], destination) + serializer.serialize(stream, encoding=encoding, **args) + else: + location = cast(str, destination) + scheme, netloc, path, params, query, fragment = urlparse(location) + if scheme == "file": + if netloc != "": + raise ValueError( + f"the file URI {location!r} has an authority component which is not supported" + ) + os_path = url2pathname(path) + else: + os_path = location + with open(os_path, "wb") as stream: + serializer.serialize(stream, encoding=encoding, **args) + return None + + def __len__(self) -> int: + if self.type == "ASK": + return 1 + elif self.type == "SELECT": + return len(self.bindings) + else: + # type error: Argument 1 to "len" has incompatible type "Optional[Graph]"; expected "Sized" + return len(self.graph) # type: ignore[arg-type] + + def __bool__(self) -> bool: + if self.type == "ASK": + # type error: Incompatible return value type (got "Optional[bool]", expected "bool") + return self.askAnswer # type: ignore[return-value] + else: + return len(self) > 0 + + def __iter__( + self, + ) -> Iterator[Union[_TripleType, bool, ResultRow]]: + if self.type in ("CONSTRUCT", "DESCRIBE"): + # type error: Item "None" of "Optional[Graph]" has no attribute "__iter__" (not iterable) + for t in self.graph: # type: ignore[union-attr] + yield t + elif self.type == "ASK": + # type error: Incompatible types in "yield" (actual type "Optional[bool]", expected type "Union[Tuple[Identifier, Identifier, Identifier], bool, ResultRow]") [misc] + yield self.askAnswer # type: ignore[misc] + elif self.type == "SELECT": + # this iterates over ResultRows of variable bindings + + if self._genbindings: + for b in self._genbindings: + if b: # don't add a result row in case of empty binding {} + self._bindings.append(b) + # type error: Argument 2 to "ResultRow" has incompatible type "Optional[List[Variable]]"; expected "List[Variable]" + yield ResultRow(b, self.vars) # type: ignore[arg-type] + self._genbindings = None + else: + for b in self._bindings: + if b: # don't add a result row in case of empty binding {} + # type error: Argument 2 to "ResultRow" has incompatible type "Optional[List[Variable]]"; expected "List[Variable]" + yield ResultRow(b, self.vars) # type: ignore[arg-type] + + def __getattr__(self, name: str) -> Any: + if self.type in ("CONSTRUCT", "DESCRIBE") and self.graph is not None: + # type error: "Graph" has no attribute "__getattr__" + return self.graph.__getattr__(self, name) # type: ignore[attr-defined] + elif self.type == "SELECT" and name == "result": + warnings.warn( + "accessing the 'result' attribute is deprecated." + " Iterate over the object instead.", + DeprecationWarning, + stacklevel=2, + ) + # copied from __iter__, above + # type error: Item "None" of "Optional[List[Variable]]" has no attribute "__iter__" (not iterable) + return [(tuple(b[v] for v in self.vars)) for b in self.bindings] # type: ignore[union-attr] + else: + raise AttributeError("'%s' object has no attribute '%s'" % (self, name)) + + def __eq__(self, other: Any) -> bool: + try: + if self.type != other.type: + return False + if self.type == "ASK": + return self.askAnswer == other.askAnswer + elif self.type == "SELECT": + return self.vars == other.vars and self.bindings == other.bindings + else: + return self.graph == other.graph + except Exception: + return False + + +class ResultParser: + def __init__(self): + pass + + # type error: Missing return statement + def parse(self, source: IO, **kwargs: Any) -> Result: # type: ignore[empty-body] + """return a Result object""" + pass # abstract + + +class ResultSerializer: + def __init__(self, result: Result): + self.result = result + + def serialize(self, stream: IO, encoding: str = "utf-8", **kwargs: Any) -> None: + """return a string properly serialized""" + pass # abstract diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rdflib/resource.py b/TTS/Kokoro/.venv/Lib/site-packages/rdflib/resource.py new file mode 100644 index 0000000000000000000000000000000000000000..b69af6015fee2dc32a91e6cc6be2e0c9f6f7e31e --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rdflib/resource.py @@ -0,0 +1,527 @@ +""" +The [`Resource`][rdflib.resource.Resource] class wraps a +[`Graph`][rdflib.graph.Graph] +and a resource reference (i.e. a [`URIRef`][rdflib.term.URIRef] or +[`BNode`][rdflib.term.BNode]) to support a resource-oriented way of +working with a graph. + +It contains methods directly corresponding to those methods of the Graph +interface that relate to reading and writing data. The difference is that a +Resource also binds a resource identifier, making it possible to work without +tracking both the graph and a current subject. This makes for a "resource +oriented" style, as compared to the triple orientation of the Graph API. + +Resulting generators are also wrapped so that any resource reference values +([`URIRef`][rdflib.term.URIRef] and [`BNode`][rdflib.term.BNode]) are in turn +wrapped as Resources. (Note that this behaviour differs from the corresponding +methods in [`Graph`][rdflib.graph.Graph], where no such conversion takes place.) + + +## Basic Usage Scenario + +Start by importing things we need and define some namespaces: + +```python +>>> from rdflib import * +>>> FOAF = Namespace("http://xmlns.com/foaf/0.1/") +>>> CV = Namespace("http://purl.org/captsolo/resume-rdf/0.2/cv#") + +``` + +Load some RDF data: + +```python +>>> graph = Graph().parse(format='n3', data=''' +... @prefix rdfs: . +... @prefix xsd: . +... @prefix foaf: . +... @prefix cv: . +... +... @base . +... +... a foaf:Person; +... rdfs:comment "Just a Python & RDF hacker."@en; +... foaf:depiction ; +... foaf:homepage ; +... foaf:name "Some Body" . +... +... a foaf:Image; +... rdfs:label "some 1"@en; +... rdfs:comment "Just an image"@en; +... foaf:thumbnail . +... +... a foaf:Image . +... +... [] a cv:CV; +... cv:aboutPerson ; +... cv:hasWorkHistory [ cv:employedIn ; +... cv:startDate "2009-09-04"^^xsd:date ] . +... ''') + +``` + +Create a Resource: + +```python +>>> person = Resource( +... graph, URIRef("http://example.org/person/some1#self")) + +``` + +Retrieve some basic facts: + +```python +>>> person.identifier +rdflib.term.URIRef('http://example.org/person/some1#self') + +>>> person.value(FOAF.name) +rdflib.term.Literal('Some Body') + +>>> person.value(RDFS.comment) +rdflib.term.Literal('Just a Python & RDF hacker.', lang='en') + +``` + +Resources can be sliced (like graphs, but the subject is fixed): + +```python +>>> for name in person[FOAF.name]: +... print(name) +Some Body +>>> person[FOAF.name : Literal("Some Body")] +True + +``` + +Resources as unicode are represented by their identifiers as unicode: + +```python +>>> %(unicode)s(person) #doctest: +SKIP +'Resource(http://example.org/person/some1#self' + +``` + +Resource references are also Resources, so you can easily get e.g. a qname +for the type of a resource, like: + +```python +>>> person.value(RDF.type).qname() +'foaf:Person' + +``` + +Or for the predicates of a resource: + +```python +>>> sorted( +... p.qname() for p in person.predicates() +... ) #doctest: +NORMALIZE_WHITESPACE +SKIP +['foaf:depiction', 'foaf:homepage', + 'foaf:name', 'rdf:type', 'rdfs:comment'] + +``` + +Follow relations and get more data from their Resources as well: + +```python +>>> for pic in person.objects(FOAF.depiction): +... print(pic.identifier) +... print(pic.value(RDF.type).qname()) +... print(pic.value(FOAF.thumbnail).identifier) +http://example.org/images/person/some1.jpg +foaf:Image +http://example.org/images/person/some1-thumb.jpg + +``` + +```python +>>> for cv in person.subjects(CV.aboutPerson): +... work = list(cv.objects(CV.hasWorkHistory))[0] +... print(work.value(CV.employedIn).identifier) +... print(work.value(CV.startDate)) +http://example.org/#company +2009-09-04 + +``` + +It's just as easy to work with the predicates of a resource: + +```python +>>> for s, p in person.subject_predicates(): +... print(s.value(RDF.type).qname()) +... print(p.qname()) +... for s, o in p.subject_objects(): +... print(s.value(RDF.type).qname()) +... print(o.value(RDF.type).qname()) +cv:CV +cv:aboutPerson +cv:CV +foaf:Person + +``` + +This is useful for e.g. inspection: + +```python +>>> thumb_ref = URIRef("http://example.org/images/person/some1-thumb.jpg") +>>> thumb = Resource(graph, thumb_ref) +>>> for p, o in thumb.predicate_objects(): +... print(p.qname()) +... print(o.qname()) +rdf:type +foaf:Image + +``` + +## Schema Example + +With this artificial schema data: + +```python +>>> graph = Graph().parse(format='n3', data=''' +... @prefix rdf: . +... @prefix rdfs: . +... @prefix owl: . +... @prefix v: . +... +... v:Artifact a owl:Class . +... +... v:Document a owl:Class; +... rdfs:subClassOf v:Artifact . +... +... v:Paper a owl:Class; +... rdfs:subClassOf v:Document . +... +... v:Choice owl:oneOf (v:One v:Other) . +... +... v:Stuff a rdf:Seq; rdf:_1 v:One; rdf:_2 v:Other . +... +... ''') + +``` + +From this class: + +```python +>>> artifact = Resource(graph, URIRef("http://example.org/def/v#Artifact")) + +``` + +we can get at subclasses: + +```python +>>> subclasses = list(artifact.transitive_subjects(RDFS.subClassOf)) +>>> [c.qname() for c in subclasses] +['v:Artifact', 'v:Document', 'v:Paper'] + +``` + +and superclasses from the last subclass: + +```python +>>> [c.qname() for c in subclasses[-1].transitive_objects(RDFS.subClassOf)] +['v:Paper', 'v:Document', 'v:Artifact'] + +``` + +Get items from the Choice: + +```python +>>> choice = Resource(graph, URIRef("http://example.org/def/v#Choice")) +>>> [it.qname() for it in choice.value(OWL.oneOf).items()] +['v:One', 'v:Other'] + +``` + +On add, other resources are auto-unboxed: + +```python +>>> paper = Resource(graph, URIRef("http://example.org/def/v#Paper")) +>>> paper.add(RDFS.subClassOf, artifact) +>>> artifact in paper.objects(RDFS.subClassOf) # checks Resource instance +True +>>> (paper._identifier, RDFS.subClassOf, artifact._identifier) in graph +True + +``` + +## Technical Details + +Comparison is based on graph and identifier: + +```python +>>> g1 = Graph() +>>> t1 = Resource(g1, URIRef("http://example.org/thing")) +>>> t2 = Resource(g1, URIRef("http://example.org/thing")) +>>> t3 = Resource(g1, URIRef("http://example.org/other")) +>>> t4 = Resource(Graph(), URIRef("http://example.org/other")) + +>>> t1 is t2 +False + +>>> t1 == t2 +True +>>> t1 != t2 +False + +>>> t1 == t3 +False +>>> t1 != t3 +True + +>>> t3 != t4 +True + +>>> t3 < t1 and t1 > t3 +True +>>> t1 >= t1 and t1 >= t3 +True +>>> t1 <= t1 and t3 <= t1 +True + +>>> t1 < t1 or t1 < t3 or t3 > t1 or t3 > t3 +False + +``` + +Hash is computed from graph and identifier: + +```python +>>> g1 = Graph() +>>> t1 = Resource(g1, URIRef("http://example.org/thing")) + +>>> hash(t1) == hash(Resource(g1, URIRef("http://example.org/thing"))) +True + +>>> hash(t1) == hash(Resource(Graph(), t1.identifier)) +False +>>> hash(t1) == hash(Resource(Graph(), URIRef("http://example.org/thing"))) +False + +``` + +The Resource class is suitable as a base class for mapper toolkits. For +example, consider this utility for accessing RDF properties via qname-like +attributes: + +```python +>>> class Item(Resource): +... +... def __getattr__(self, p): +... return list(self.objects(self._to_ref(*p.split('_', 1)))) +... +... def _to_ref(self, pfx, name): +... return URIRef(self._graph.store.namespace(pfx) + name) + +``` + +It works as follows: + +```python +>>> graph = Graph().parse(format='n3', data=''' +... @prefix rdfs: . +... @prefix foaf: . +... +... @base . +... +... foaf:name "Some Body"; +... foaf:depiction . +... rdfs:comment "Just an image"@en . +... ''') + +>>> person = Item(graph, URIRef("http://example.org/person/some1#self")) + +>>> print(person.foaf_name[0]) +Some Body + +``` + +The mechanism for wrapping references as resources cooperates with subclasses. +Therefore, accessing referenced resources automatically creates new `Item` +objects: + +```python +>>> isinstance(person.foaf_depiction[0], Item) +True + +>>> print(person.foaf_depiction[0].rdfs_comment[0]) +Just an image + +``` +""" + +from rdflib.namespace import RDF +from rdflib.paths import Path +from rdflib.term import BNode, Node, URIRef + +__all__ = ["Resource"] + + +class Resource: + """A Resource is a wrapper for a graph and a resource identifier.""" + + def __init__(self, graph, subject): + self._graph = graph + self._identifier = subject + + @property + def graph(self): + return self._graph + + @property + def identifier(self): + return self._identifier + + def __hash__(self): + return hash(Resource) ^ hash(self._graph) ^ hash(self._identifier) + + def __eq__(self, other): + return ( + isinstance(other, Resource) + and self._graph == other._graph + and self._identifier == other._identifier + ) + + def __ne__(self, other): + return not self == other + + def __lt__(self, other): + if isinstance(other, Resource): + return self._identifier < other._identifier + else: + return False + + def __gt__(self, other): + return not (self < other or self == other) + + def __le__(self, other): + return self < other or self == other + + def __ge__(self, other): + return not self < other + + def __unicode__(self): + return str(self._identifier) + + def add(self, p, o): + if isinstance(o, Resource): + o = o._identifier + + self._graph.add((self._identifier, p, o)) + + def remove(self, p, o=None): + if isinstance(o, Resource): + o = o._identifier + + self._graph.remove((self._identifier, p, o)) + + def set(self, p, o): + if isinstance(o, Resource): + o = o._identifier + + self._graph.set((self._identifier, p, o)) + + def subjects(self, predicate=None): # rev + return self._resources(self._graph.subjects(predicate, self._identifier)) + + def predicates(self, o=None): + if isinstance(o, Resource): + o = o._identifier + + return self._resources(self._graph.predicates(self._identifier, o)) + + def objects(self, predicate=None): + return self._resources(self._graph.objects(self._identifier, predicate)) + + def subject_predicates(self): + return self._resource_pairs(self._graph.subject_predicates(self._identifier)) + + def subject_objects(self): + return self._resource_pairs(self._graph.subject_objects(self._identifier)) + + def predicate_objects(self): + return self._resource_pairs(self._graph.predicate_objects(self._identifier)) + + def value(self, p=RDF.value, o=None, default=None, any=True): + if isinstance(o, Resource): + o = o._identifier + + return self._cast(self._graph.value(self._identifier, p, o, default, any)) + + def items(self): + return self._resources(self._graph.items(self._identifier)) + + def transitive_objects(self, predicate, remember=None): + return self._resources( + self._graph.transitive_objects(self._identifier, predicate, remember) + ) + + def transitive_subjects(self, predicate, remember=None): + return self._resources( + self._graph.transitive_subjects(predicate, self._identifier, remember) + ) + + def qname(self): + return self._graph.qname(self._identifier) + + def _resource_pairs(self, pairs): + for s1, s2 in pairs: + yield self._cast(s1), self._cast(s2) + + def _resource_triples(self, triples): + for s, p, o in triples: + yield self._cast(s), self._cast(p), self._cast(o) + + def _resources(self, nodes): + for node in nodes: + yield self._cast(node) + + def _cast(self, node): + if isinstance(node, (BNode, URIRef)): + return self._new(node) + else: + return node + + def __iter__(self): + return self._resource_triples( + self._graph.triples((self.identifier, None, None)) + ) + + def __getitem__(self, item): + if isinstance(item, slice): + if item.step: + raise TypeError( + "Resources fix the subject for slicing, and can only be sliced by predicate/object. " + ) + p, o = item.start, item.stop + if isinstance(p, Resource): + p = p._identifier + if isinstance(o, Resource): + o = o._identifier + if p is None and o is None: + return self.predicate_objects() + elif p is None: + return self.predicates(o) + elif o is None: + return self.objects(p) + else: + return (self.identifier, p, o) in self._graph + elif isinstance(item, (Node, Path)): + return self.objects(item) + else: + raise TypeError( + "You can only index a resource by a single rdflib term, a slice of rdflib terms, not %s (%s)" + % (item, type(item)) + ) + + def __setitem__(self, item, value): + self.set(item, value) + + def _new(self, subject): + return type(self)(self._graph, subject) + + def __str__(self): + return "Resource(%s)" % self._identifier + + def __repr__(self): + return "Resource(%s,%s)" % (self._graph, self._identifier) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rdflib/serializer.py b/TTS/Kokoro/.venv/Lib/site-packages/rdflib/serializer.py new file mode 100644 index 0000000000000000000000000000000000000000..549a37b58c3fd656fc4b0dc1d8e412749081d3b7 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rdflib/serializer.py @@ -0,0 +1,65 @@ +"""Serializer plugin interface. + +The RDF serialization plugins used during +[RDFlib's common serialization of a graph][rdflib.graph.Graph.serialize] +is described in this module. + +TODO: info for how to write a serializer that can plugin to rdflib. +See also [`rdflib.plugin`][rdflib.plugin] + +All builtin RDF Serializer are listed +under [`rdflib.plugins.serializers`][rdflib.plugins.serializers]. +""" + +from __future__ import annotations + +from typing import IO, TYPE_CHECKING, Any, Optional, TypeVar, Union + +from rdflib.term import URIRef + +if TYPE_CHECKING: + from rdflib.graph import Graph + + +__all__ = ["Serializer"] + +_StrT = TypeVar("_StrT", bound=str) + + +class Serializer: + """Base class for RDF Serializer. + + New Serializer can be registered as plugin as described + in [`rdflib.plugin`][rdflib.plugin]. + """ + + def __init__(self, store: Graph): + self.store: Graph = store + self.encoding: str = "utf-8" + self.base: Optional[str] = None + + def serialize( + self, + stream: IO[bytes], + base: Optional[str] = None, + encoding: Optional[str] = None, + **args: Any, + ) -> None: + """Abstract method. Print [Graph][rdflib.graph.Graph]. + Used in [Graph.serialize][rdflib.graph.Graph.serialize] + + Serialize Graph + + Args: + stream: The destination to serialize the graph to. + base: The base IRI for formats that support it. + encoding: Encoding of output. + args: Additional arguments to pass to the Serializer that will be used. + """ + + def relativize(self, uri: _StrT) -> Union[_StrT, URIRef]: + base = self.base + if base is not None and uri.startswith(base): + # type error: Incompatible types in assignment (expression has type "str", variable has type "Node") + uri = URIRef(uri.replace(base, "", 1)) # type: ignore[assignment] + return uri diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rdflib/store.py b/TTS/Kokoro/.venv/Lib/site-packages/rdflib/store.py new file mode 100644 index 0000000000000000000000000000000000000000..397577e5c9cbbd433da66ba324f19e4661d6d1f4 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rdflib/store.py @@ -0,0 +1,486 @@ +"""## Types of store + +`Context-aware`: An RDF store capable of storing statements within contexts +is considered context-aware. Essentially, such a store is able to partition +the RDF model it represents into individual, named, and addressable +sub-graphs. + +Relevant Notation3 reference regarding formulae, quoted statements, and such: +http://www.w3.org/DesignIssues/Notation3.html + +`Formula-aware`: An RDF store capable of distinguishing between statements +that are asserted and statements that are quoted is considered formula-aware. + +`Transaction-capable`: capable of providing transactional integrity to the +RDF operations performed on it. + +`Graph-aware`: capable of keeping track of empty graphs. +""" + +from __future__ import annotations + +import pickle +from io import BytesIO +from typing import ( + TYPE_CHECKING, + Any, + Dict, + Generator, + Iterable, + Iterator, + Mapping, + Optional, + Tuple, + Union, +) + +from rdflib.events import Dispatcher, Event + +if TYPE_CHECKING: + from rdflib.graph import ( + Graph, + _ContextType, + _QuadType, + _TripleChoiceType, + _TriplePatternType, + _TripleType, + ) + from rdflib.plugins.sparql.sparql import Query, Update + from rdflib.query import Result + from rdflib.term import Identifier, Node, URIRef + + +# Constants representing the state of a Store (returned by the open method) +VALID_STORE = 1 +CORRUPTED_STORE = 0 +NO_STORE = -1 +UNKNOWN: None = None + + +Pickler = pickle.Pickler +Unpickler = pickle.Unpickler +UnpicklingError = pickle.UnpicklingError + +__all__ = [ + "StoreCreatedEvent", + "TripleAddedEvent", + "TripleRemovedEvent", + "NodePickler", + "Store", +] + + +class StoreCreatedEvent(Event): + """This event is fired when the Store is created. + + Attributes: + configuration: String used to create the store + """ + + +class TripleAddedEvent(Event): + """This event is fired when a triple is added. + + Attributes: + triple: The triple added to the graph. + context: The context of the triple, if any. + graph: The graph to which the triple was added. + """ + + +class TripleRemovedEvent(Event): + """This event is fired when a triple is removed. + + Attributes: + triple: The triple removed from the graph. + context: The context of the triple, if any. + graph: The graph from which the triple was removed. + """ + + +class NodePickler: + def __init__(self) -> None: + self._objects: Dict[str, Any] = {} + self._ids: Dict[Any, str] = {} + self._get_object = self._objects.__getitem__ + + def _get_ids(self, key: Any) -> Optional[str]: + try: + return self._ids.get(key) + except TypeError: + return None + + def register(self, object: Any, id: str) -> None: + self._objects[id] = object + self._ids[object] = id + + def loads(self, s: bytes) -> Node: + up = Unpickler(BytesIO(s)) + # NOTE on type error: https://github.com/python/mypy/issues/2427 + # type error: Cannot assign to a method + up.persistent_load = self._get_object # type: ignore[assignment] + try: + return up.load() + except KeyError as e: + raise UnpicklingError("Could not find Node class for %s" % e) + + def dumps( + self, obj: Node, protocol: Optional[Any] = None, bin: Optional[Any] = None + ): + src = BytesIO() + p = Pickler(src) + # NOTE on type error: https://github.com/python/mypy/issues/2427 + # type error: Cannot assign to a method + p.persistent_id = self._get_ids # type: ignore[assignment] + p.dump(obj) + return src.getvalue() + + def __getstate__(self) -> Mapping[str, Any]: + state = self.__dict__.copy() + del state["_get_object"] + state.update( + {"_ids": tuple(self._ids.items()), "_objects": tuple(self._objects.items())} + ) + return state + + def __setstate__(self, state: Mapping[str, Any]) -> None: + self.__dict__.update(state) + self._ids = dict(self._ids) + self._objects = dict(self._objects) + self._get_object = self._objects.__getitem__ + + +class Store: + # Properties + context_aware: bool = False + formula_aware: bool = False + transaction_aware: bool = False + graph_aware: bool = False + + def __init__( + self, + configuration: Optional[str] = None, + identifier: Optional[Identifier] = None, + ): + """Initialize the Store. + + Args: + identifier: URIRef of the Store. Defaults to CWD + configuration: String containing information open can use to + connect to datastore. + """ + self.__node_pickler: Optional[NodePickler] = None + self.dispatcher = Dispatcher() + if configuration: + self.open(configuration) + + @property + def node_pickler(self) -> NodePickler: + if self.__node_pickler is None: + from rdflib.graph import Graph, QuotedGraph + from rdflib.term import BNode, Literal, URIRef, Variable + + self.__node_pickler = np = NodePickler() + np.register(self, "S") + np.register(URIRef, "U") + np.register(BNode, "B") + np.register(Literal, "L") + np.register(Graph, "G") + np.register(QuotedGraph, "Q") + np.register(Variable, "V") + return self.__node_pickler + + # Database management methods + # NOTE: Can't find any stores using this, we should consider deprecating it. + def create(self, configuration: str) -> None: + self.dispatcher.dispatch(StoreCreatedEvent(configuration=configuration)) + + def open( + self, configuration: Union[str, tuple[str, str]], create: bool = False + ) -> Optional[int]: + """Opens the store specified by the configuration string. + + Args: + configuration: Store configuration string + create: If True, a store will be created if it doesn't exist. + If False and the store doesn't exist, an exception is raised. + + Returns: + One of: VALID_STORE, CORRUPTED_STORE, or NO_STORE + + Raises: + Exception: If there are insufficient permissions to open the store. + """ + return UNKNOWN + + def close(self, commit_pending_transaction: bool = False) -> None: + """Closes the database connection. + + Args: + commit_pending_transaction: Whether to commit all pending + transactions before closing (if the store is transactional). + """ + + def destroy(self, configuration: str) -> None: + """Destroys the instance of the store. + + Args: + configuration: The configuration string identifying the store instance. + """ + + def gc(self) -> None: + """Allows the store to perform any needed garbage collection.""" + pass + + # RDF APIs + def add( + self, + triple: _TripleType, + context: _ContextType, + quoted: bool = False, + ) -> None: + """Adds the given statement to a specific context or to the model. + + Args: + triple: The triple to add + context: The context to add the triple to + quoted: If True, indicates this statement is quoted/hypothetical + (for formula-aware stores) + + Note: + It should be an error to not specify a context and have the quoted + argument be True. It should also be an error for the quoted argument + to be True when the store is not formula-aware. + """ + self.dispatcher.dispatch(TripleAddedEvent(triple=triple, context=context)) + + def addN(self, quads: Iterable[_QuadType]) -> None: # noqa: N802 + """Adds each item in the list of statements to a specific context. + + The quoted argument is interpreted by formula-aware stores to indicate this + statement is quoted/hypothetical. + + Note: + The default implementation is a redirect to add. + + Args: + quads: An iterable of quads to add + """ + for s, p, o, c in quads: + assert c is not None, "Context associated with %s %s %s is None!" % ( + s, + p, + o, + ) + self.add((s, p, o), c) + + def remove( + self, + triple: _TriplePatternType, + context: Optional[_ContextType] = None, + ) -> None: + """Remove the set of triples matching the pattern from the store""" + self.dispatcher.dispatch(TripleRemovedEvent(triple=triple, context=context)) + + def triples_choices( + self, + triple: _TripleChoiceType, + context: Optional[_ContextType] = None, + ) -> Generator[ + Tuple[ + _TripleType, + Iterator[Optional[_ContextType]], + ], + None, + None, + ]: + """ + A variant of triples that can take a list of terms instead of a single + term in any slot. Stores can implement this to optimize the response + time from the default 'fallback' implementation, which will iterate + over each term in the list and dispatch to triples + """ + subject, predicate, object_ = triple + if isinstance(object_, list): + assert not isinstance(subject, list), "object_ / subject are both lists" + assert not isinstance(predicate, list), "object_ / predicate are both lists" + if object_: + for obj in object_: + for (s1, p1, o1), cg in self.triples( + (subject, predicate, obj), context + ): + yield (s1, p1, o1), cg + else: + for (s1, p1, o1), cg in self.triples( + (subject, predicate, None), context + ): + yield (s1, p1, o1), cg + + elif isinstance(subject, list): + assert not isinstance(predicate, list), "subject / predicate are both lists" + if subject: + for subj in subject: + for (s1, p1, o1), cg in self.triples( + (subj, predicate, object_), context + ): + yield (s1, p1, o1), cg + else: + for (s1, p1, o1), cg in self.triples( + (None, predicate, object_), context + ): + yield (s1, p1, o1), cg + + elif isinstance(predicate, list): + assert not isinstance(subject, list), "predicate / subject are both lists" + if predicate: + for pred in predicate: + for (s1, p1, o1), cg in self.triples( + (subject, pred, object_), context + ): + yield (s1, p1, o1), cg + else: + for (s1, p1, o1), cg in self.triples((subject, None, object_), context): + yield (s1, p1, o1), cg + + # type error: Missing return statement + def triples( # type: ignore[return] + self, + triple_pattern: _TriplePatternType, + context: Optional[_ContextType] = None, + ) -> Iterator[Tuple[_TripleType, Iterator[Optional[_ContextType]]]]: + """ + A generator over all the triples matching the pattern. Pattern can + include any objects for used for comparing against nodes in the store, + for example, REGEXTerm, URIRef, Literal, BNode, Variable, Graph, + QuotedGraph, Date? DateRange? + + Args: + context: A conjunctive query can be indicated by either + providing a value of None, or a specific context can be + queries by passing a Graph instance (if store is context aware). + """ + subject, predicate, object = triple_pattern + + # variants of triples will be done if / when optimization is needed + + # type error: Missing return statement + def __len__(self, context: Optional[_ContextType] = None) -> int: # type: ignore[empty-body] + """ + Number of statements in the store. This should only account for non- + quoted (asserted) statements if the context is not specified, + otherwise it should return the number of statements in the formula or + context given. + + Args: + context: a graph instance to query or None + """ + + # type error: Missing return statement + def contexts( # type: ignore[empty-body] + self, triple: Optional[_TripleType] = None + ) -> Generator[_ContextType, None, None]: + """ + Generator over all contexts in the graph. If triple is specified, + a generator over all contexts the triple is in. + + if store is graph_aware, may also return empty contexts + + :returns: a generator over Nodes + """ + + # TODO FIXME: the result of query is inconsistent. + def query( + self, + query: Union[Query, str], + initNs: Mapping[str, Any], # noqa: N803 + initBindings: Mapping[str, Identifier], # noqa: N803 + queryGraph: str, # noqa: N803 + **kwargs: Any, + ) -> Result: + """If stores provide their own SPARQL implementation, override this. + + queryGraph is None, a URIRef or `__UNION__` + If None the graph is specified in the query-string/object + If URIRef it specifies the graph to query, + If `__UNION__` the union of all named graphs should be queried + (This is used by ConjunctiveGraphs + Values other than None obviously only makes sense for + context-aware stores.) + """ + + raise NotImplementedError + + def update( + self, + update: Union[Update, str], + initNs: Mapping[str, Any], # noqa: N803 + initBindings: Mapping[str, Identifier], # noqa: N803 + queryGraph: str, # noqa: N803 + **kwargs: Any, + ) -> None: + """If stores provide their own (SPARQL) Update implementation, override this. + + queryGraph is None, a URIRef or `__UNION__` + If None the graph is specified in the query-string/object + If URIRef it specifies the graph to query, + If `__UNION__` the union of all named graphs should be queried + (This is used by ConjunctiveGraphs + Values other than None obviously only makes sense for + context-aware stores.) + """ + + raise NotImplementedError + + # Optional Namespace methods + + def bind(self, prefix: str, namespace: URIRef, override: bool = True) -> None: + """Bind a namespace to a prefix. + + Args: + prefix: The prefix to bind the namespace to. + namespace: The URIRef of the namespace to bind. + override: If True, rebind even if the given namespace is already bound + to another prefix + """ + + def prefix(self, namespace: URIRef) -> Optional[str]: + """""" + + def namespace(self, prefix: str) -> Optional[URIRef]: + """ """ + + def namespaces(self) -> Iterator[Tuple[str, URIRef]]: + """ """ + # This is here so that the function becomes an empty generator. + # See https://stackoverflow.com/q/13243766 and + # https://www.python.org/dev/peps/pep-0255/#why-a-new-keyword-for-yield-why-not-a-builtin-function-instead + if False: + yield None # type: ignore[unreachable] + + # Optional Transactional methods + + def commit(self) -> None: + """ """ + + def rollback(self) -> None: + """ """ + + # Optional graph methods + + def add_graph(self, graph: Graph) -> None: + """Add a graph to the store, no effect if the graph already + exists. + + Args: + graph: a Graph instance + """ + raise Exception("Graph method called on non-graph_aware store") + + def remove_graph(self, graph: Graph) -> None: + """Remove a graph from the store, this should also remove all + triples in the graph + + Args: + graphid: a Graph instance + """ + raise Exception("Graph method called on non-graph_aware store") diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rdflib/term.py b/TTS/Kokoro/.venv/Lib/site-packages/rdflib/term.py new file mode 100644 index 0000000000000000000000000000000000000000..d9f0646175236d949d9aacdd648d789d47d12c17 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rdflib/term.py @@ -0,0 +1,2517 @@ +""" +This module defines the different types of terms. Terms are the kinds of +objects that can appear in a quoted/asserted triple. This includes those +that are core to RDF: + +* [Blank Nodes][rdflib.term.BNode] - Blank Nodes +* [URI References][rdflib.term.URIRef] - URI References +* [Literals][rdflib.term.Literal] - Literals (which consist of a literal value, datatype and language tag) + +Those that extend the RDF model into N3: + +* [`QuotedGraph`][rdflib.graph.QuotedGraph] - Formulae +* [`Variable`][rdflib.term.Variable] - Universal Quantifications (Variables) + +And those that are primarily for matching against 'Nodes' in the +underlying Graph: + +* REGEX Expressions +* Date Ranges +* Numerical Ranges +""" + +from __future__ import annotations + +import abc +import re +from fractions import Fraction + +__all__ = [ + "bind", + "_is_valid_uri", + "Node", + "IdentifiedNode", + "Identifier", + "URIRef", + "BNode", + "Literal", + "Variable", +] +import logging +import math +import warnings +import xml.dom.minidom +from base64 import b64decode, b64encode +from binascii import hexlify, unhexlify +from collections import defaultdict +from datetime import date, datetime, time, timedelta +from decimal import Decimal +from re import compile, sub +from types import GeneratorType +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + Generator, + List, + Optional, + Tuple, + Type, + TypeVar, + Union, +) +from urllib.parse import urldefrag, urljoin, urlparse +from uuid import uuid4 + +import rdflib +import rdflib.util +from rdflib.compat import long_type + +from .xsd_datetime import ( # type: ignore[attr-defined] + Duration, + duration_isoformat, + parse_datetime, + parse_time, + parse_xsd_date, + parse_xsd_duration, +) + +if TYPE_CHECKING: + from .namespace import NamespaceManager + from .paths import AlternativePath, InvPath, NegatedPath, Path, SequencePath + +_HAS_HTML5RDF = False + +try: + import html5rdf + + _HAS_HTML5RDF = True +except ImportError: + html5rdf = None + +_SKOLEM_DEFAULT_AUTHORITY = "https://rdflib.github.io" + +logger = logging.getLogger(__name__) +skolem_genid = "/.well-known/genid/" +rdflib_skolem_genid = "/.well-known/genid/rdflib/" +skolems: Dict[str, BNode] = {} + + +_invalid_uri_chars = '<>" {}|\\^`' + + +def _is_valid_uri(uri: str) -> bool: + for c in _invalid_uri_chars: + if c in uri: + return False + return True + + +_lang_tag_regex = compile("^[a-zA-Z]+(?:-[a-zA-Z0-9]+)*$") + + +def _is_valid_langtag(tag: str) -> bool: + return bool(_lang_tag_regex.match(tag)) + + +def _is_valid_unicode(value: Union[str, bytes]) -> bool: + """ + Verify that the provided value can be converted into a Python + unicode object. + """ + if isinstance(value, bytes): + coding_func, param = getattr(value, "decode"), "utf-8" + else: + coding_func, param = str, value + + # try to convert value into unicode + try: + coding_func(param) + except UnicodeError: + return False + return True + + +class Node(abc.ABC): + """A Node in the Graph.""" + + __slots__ = () + + @abc.abstractmethod + def n3(self, namespace_manager: Optional[NamespaceManager] = None) -> str: ... + + +class Identifier(Node, str): # allow Identifiers to be Nodes in the Graph + """See http://www.w3.org/2002/07/rdf-identifer-terminology/ + regarding choice of terminology.""" + + __slots__ = () + + def __new__(cls, value: str): + return str.__new__(cls, value) + + def eq(self, other: Any) -> bool: + """A "semantic"/interpreted equality function, + by default, same as __eq__""" + return self.__eq__(other) + + def neq(self, other: Any) -> bool: + """A "semantic"/interpreted not equal function, + by default, same as __ne__""" + return self.__ne__(other) + + def __ne__(self, other: Any) -> bool: + return not self.__eq__(other) + + def __eq__(self, other: Any) -> bool: + """Equality for Nodes. + + ```python + >>> BNode("foo")==None + False + >>> BNode("foo")==URIRef("foo") + False + >>> URIRef("foo")==BNode("foo") + False + >>> BNode("foo")!=URIRef("foo") + True + >>> URIRef("foo")!=BNode("foo") + True + >>> Variable('a')!=URIRef('a') + True + >>> Variable('a')!=Variable('a') + False + + ``` + """ + + if type(self) is type(other): + return str(self) == str(other) + else: + return False + + def __gt__(self, other: Any) -> bool: + """This implements ordering for Nodes. + + This tries to implement this: + http://www.w3.org/TR/sparql11-query/#modOrderBy + + Variables are not included in the SPARQL list, but + they are greater than BNodes and smaller than everything else + """ + if other is None: + return True # everything bigger than None + elif type(self) is type(other): + return str(self) > str(other) + elif isinstance(other, Node): + return _ORDERING[type(self)] > _ORDERING[type(other)] + + return NotImplemented + + def __lt__(self, other: Any) -> bool: + if other is None: + return False # Nothing is less than None + elif type(self) is type(other): + return str(self) < str(other) + elif isinstance(other, Node): + return _ORDERING[type(self)] < _ORDERING[type(other)] + + return NotImplemented + + def __le__(self, other: Any) -> bool: + r = self.__lt__(other) + if r: + return True + return self == other + + def __ge__(self, other: Any) -> bool: + r = self.__gt__(other) + if r: + return True + return self == other + + # type error: Argument 1 of "startswith" is incompatible with supertype "str"; supertype defines the argument type as "Union[str, Tuple[str, ...]]" + # FIXME: this does not accommodate prefix of type Tuple[str, ...] which is a + # valid for str.startswith + def startswith(self, prefix: str, start=..., end=...) -> bool: # type: ignore[override] # FIXME + return str(self).startswith(str(prefix)) + + # use parent's hash for efficiency reasons + # clashes of 'foo', URIRef('foo') and Literal('foo') are typically so rare + # that they don't justify additional overhead. Notice that even in case of + # clash __eq__ is still the fallback and very quick in those cases. + __hash__ = str.__hash__ + + +class IdentifiedNode(Identifier): + """ + An abstract class, primarily defined to identify Nodes that are not Literals. + + The name "Identified Node" is not explicitly defined in the RDF specification, but can be drawn from this section: https://www.w3.org/TR/rdf-concepts/#section-URI-Vocabulary + """ + + __slots__ = () + + def __getnewargs__(self) -> Tuple[str]: + return (str(self),) + + def n3(self, namespace_manager: Optional[NamespaceManager] = None) -> str: + raise NotImplementedError() + + def toPython(self) -> str: # noqa: N802 + return str(self) + + +class URIRef(IdentifiedNode): + """[RDF 1.1's IRI Section](https://www.w3.org/TR/rdf11-concepts/#section-IRIs) + + !!! info "Terminology" + Documentation on RDF outside of RDFLib uses the term IRI or URI whereas this class is called URIRef. This is because it was made when the first version of the RDF specification was current, and it used the term *URIRef*, see [RDF 1.0 URIRef](http://www.w3.org/TR/rdf-concepts/#section-Graph-URIref) + + An IRI (Internationalized Resource Identifier) within an RDF graph is a Unicode string that conforms to the syntax defined in RFC 3987. + + IRIs in the RDF abstract syntax MUST be absolute, and MAY contain a fragment identifier. + + IRIs are a generalization of URIs [RFC3986] that permits a wider range of Unicode characters. + """ + + __slots__ = () + + __or__: Callable[[URIRef, Union[URIRef, Path]], AlternativePath] + __invert__: Callable[[URIRef], InvPath] + __neg__: Callable[[URIRef], NegatedPath] + __truediv__: Callable[[URIRef, Union[URIRef, Path]], SequencePath] + + def __new__(cls, value: str, base: Optional[str] = None): + if base is not None: + ends_in_hash = value.endswith("#") + # type error: Argument "allow_fragments" to "urljoin" has incompatible type "int"; expected "bool" + value = urljoin(base, value, allow_fragments=1) # type: ignore[arg-type] + if ends_in_hash: + if not value.endswith("#"): + value += "#" + + if not _is_valid_uri(value): + logger.warning( + f"{value} does not look like a valid URI, trying to serialize this will break." + ) + + try: + rt = str.__new__(cls, value) + except UnicodeDecodeError: + # type error: No overload variant of "__new__" of "str" matches argument types "Type[URIRef]", "str", "str" + rt = str.__new__(cls, value, "utf-8") # type: ignore[call-overload] + return rt + + def n3(self, namespace_manager: Optional[NamespaceManager] = None) -> str: + """This will do a limited check for valid URIs, + essentially just making sure that the string includes no illegal + characters (`<, >, ", {, }, |, \\, `, ^`) + + Args: + namespace_manager: if not None, will be used to make up a prefixed name + """ + + if not _is_valid_uri(self): + raise Exception( + f'"{self}" does not look like a valid URI, I cannot serialize this as N3/Turtle. Perhaps you wanted to urlencode it?' + ) + + if namespace_manager: + return namespace_manager.normalizeUri(self) + else: + return f"<{self}>" + + def defrag(self) -> URIRef: + if "#" in self: + url, frag = urldefrag(self) + return URIRef(url) + else: + return self + + @property + def fragment(self) -> str: + """Return the URL Fragment + + ```python + >>> URIRef("http://example.com/some/path/#some-fragment").fragment + 'some-fragment' + >>> URIRef("http://example.com/some/path/").fragment + '' + + ``` + """ + return urlparse(self).fragment + + def __reduce__(self) -> Tuple[Type[URIRef], Tuple[str]]: + return (URIRef, (str(self),)) + + def __repr__(self) -> str: + if self.__class__ is URIRef: + clsName = "rdflib.term.URIRef" # noqa: N806 + else: + clsName = self.__class__.__name__ # noqa: N806 + + return f"{clsName}({str.__repr__(self)})" + + def __add__(self, other) -> URIRef: + return self.__class__(str(self) + other) + + def __radd__(self, other) -> URIRef: + return self.__class__(other + str(self)) + + def __mod__(self, other) -> URIRef: + return self.__class__(str(self) % other) + + def de_skolemize(self) -> BNode: + """Create a Blank Node from a skolem URI, in accordance + with http://www.w3.org/TR/rdf11-concepts/#section-skolemization. + This function accepts only rdflib type skolemization, to provide + a round-tripping within the system. + + Added in version 4.0 + """ + if isinstance(self, RDFLibGenid): + parsed_uri = urlparse(f"{self}") + return BNode(value=parsed_uri.path[len(rdflib_skolem_genid) :]) + elif isinstance(self, Genid): + bnode_id = f"{self}" + if bnode_id in skolems: + return skolems[bnode_id] + else: + retval = BNode() + skolems[bnode_id] = retval + return retval + else: + raise Exception(f"<{self}> is not a skolem URI") + + +class Genid(URIRef): + __slots__ = () + + @staticmethod + def _is_external_skolem(uri: Any) -> bool: + if not isinstance(uri, str): + uri = str(uri) + parsed_uri = urlparse(uri) + gen_id = parsed_uri.path.rfind(skolem_genid) + if gen_id != 0: + return False + return True + + +class RDFLibGenid(Genid): + __slots__ = () + + @staticmethod + def _is_rdflib_skolem(uri: Any) -> bool: + if not isinstance(uri, str): + uri = str(uri) + parsed_uri = urlparse(uri) + if ( + parsed_uri.params != "" + or parsed_uri.query != "" + or parsed_uri.fragment != "" + ): + return False + gen_id = parsed_uri.path.rfind(rdflib_skolem_genid) + if gen_id != 0: + return False + return True + + +def _unique_id() -> str: + # Used to read: """Create a (hopefully) unique prefix""" + # now retained merely to leave internal API unchanged. + # From BNode.__new__() below ... + # + # acceptable bnode value range for RDF/XML needs to be + # something that can be serialzed as a nodeID for N3 + # + # BNode identifiers must be valid NCNames" _:[A-Za-z][A-Za-z0-9]* + # http://www.w3.org/TR/2004/REC-rdf-testcases-20040210/#nodeID + return "N" # ensure that id starts with a letter + + +class BNode(IdentifiedNode): + """ + RDF 1.1's Blank Nodes Section: https://www.w3.org/TR/rdf11-concepts/#section-blank-nodes + + Blank Nodes are local identifiers for unnamed nodes in RDF graphs that are used in + some concrete RDF syntaxes or RDF store implementations. They are always locally + scoped to the file or RDF store, and are not persistent or portable identifiers for + blank nodes. The identifiers for Blank Nodes are not part of the RDF abstract + syntax, but are entirely dependent on particular concrete syntax or implementation + (such as Turtle, JSON-LD). + + --- + + RDFLib's `BNode` class makes unique IDs for all the Blank Nodes in a Graph but you + should *never* expect, or reply on, BNodes' IDs to match across graphs, or even for + multiple copies of the same graph, if they are regenerated from some non-RDFLib + source, such as loading from RDF data. + """ + + __slots__ = () + + def __new__( + cls, + value: Optional[str] = None, + _sn_gen: Optional[Union[Callable[[], str], Generator]] = None, + _prefix: str = _unique_id(), + ): + """ + # only store implementations should pass in a value + """ + if value is None: + # so that BNode values do not collide with ones created with + # a different instance of this module at some other time. + if _sn_gen is not None: + if callable(_sn_gen): + sn_result: Union[str, Generator] = _sn_gen() + else: + sn_result = _sn_gen + if isinstance(sn_result, GeneratorType): + node_id = next(sn_result) + else: + node_id = sn_result + else: + node_id = uuid4().hex + # note, for two (and only two) string variables, + # concat with + is faster than f"{x}{y}" + value = _prefix + f"{node_id}" + else: + # TODO: check that value falls within acceptable bnode value range + # for RDF/XML needs to be something that can be serialized + # as a nodeID for N3 ?? Unless we require these + # constraints be enforced elsewhere? + pass # assert is_ncname(str(value)), "BNode identifiers + # must be valid NCNames" _:[A-Za-z][A-Za-z0-9]* + # http://www.w3.org/TR/2004/REC-rdf-testcases-20040210/#nodeID + # type error: Incompatible return value type (got "Identifier", expected "BNode") + return Identifier.__new__(cls, value) + + def n3(self, namespace_manager: Optional[NamespaceManager] = None) -> str: + # note - for two strings, concat with + is faster than f"{x}{y}" + return "_:" + self + + def __reduce__(self) -> Tuple[Type[BNode], Tuple[str]]: + return (BNode, (str(self),)) + + def __repr__(self) -> str: + if self.__class__ is BNode: + clsName = "rdflib.term.BNode" # noqa: N806 + else: + clsName = self.__class__.__name__ # noqa: N806 + return f"{clsName}({str.__repr__(self)})" + + def skolemize( + self, authority: Optional[str] = None, basepath: Optional[str] = None + ) -> URIRef: + """Create a URIRef "skolem" representation of the BNode, in accordance + with http://www.w3.org/TR/rdf11-concepts/#section-skolemization + + Added in version 4.0 + """ + if authority is None: + authority = _SKOLEM_DEFAULT_AUTHORITY + if basepath is None: + basepath = rdflib_skolem_genid + skolem = basepath + str(self) + return URIRef(urljoin(authority, skolem)) + + +class Literal(Identifier): + """ + + RDF 1.1's Literals Section: http://www.w3.org/TR/rdf-concepts/#section-Graph-Literal + + Literals are used for values such as strings, numbers, and dates. + + A literal in an RDF graph consists of two or three elements: + + * a lexical form, being a Unicode string, which SHOULD be in Normal Form C + * a datatype IRI, being an IRI identifying a datatype that determines how the lexical form maps to a literal value, and + * if and only if the datatype IRI is `http://www.w3.org/1999/02/22-rdf-syntax-ns#langString`, a non-empty language tag. The language tag MUST be well-formed according to section 2.2.9 of `Tags for identifying languages `_. + + A literal is a language-tagged string if the third element is present. Lexical representations of language tags MAY be converted to lower case. The value space of language tags is always in lower case. + + --- + + For valid XSD datatypes, the lexical form is optionally normalized + at construction time. Default behaviour is set by `rdflib.NORMALIZE_LITERALS` + and can be overridden by the normalize parameter to `__new__` + + Equality and hashing of Literals are done based on the lexical form, i.e.: + + ```python + >>> from rdflib.namespace import XSD + >>> Literal('01') != Literal('1') # clear - strings differ + True + + ``` + + but with data-type they get normalized: + + ```python + >>> Literal('01', datatype=XSD.integer) != Literal('1', datatype=XSD.integer) + False + + ``` + + unless disabled: + + ```python + >>> Literal('01', datatype=XSD.integer, normalize=False) != Literal('1', datatype=XSD.integer) + True + + ``` + + Value based comparison is possible: + + ```python + >>> Literal('01', datatype=XSD.integer).eq(Literal('1', datatype=XSD.float)) + True + + ``` + + The eq method also provides limited support for basic python types: + + ```python + >>> Literal(1).eq(1) # fine - int compatible with xsd:integer + True + >>> Literal('a').eq('b') # fine - str compatible with plain-lit + False + >>> Literal('a', datatype=XSD.string).eq('a') # fine - str compatible with xsd:string + True + >>> Literal('a').eq(1) # not fine, int incompatible with plain-lit + NotImplemented + + ``` + + Greater-than/less-than ordering comparisons are also done in value + space, when compatible datatypes are used. Incompatible datatypes + are ordered by DT, or by lang-tag. For other nodes the ordering + is None < BNode < URIRef < Literal + + Any comparison with non-rdflib Node are "NotImplemented" + In PY3 this is an error. + + ```python + >>> from rdflib import Literal, XSD + >>> lit2006 = Literal('2006-01-01',datatype=XSD.date) + >>> lit2006.toPython() + datetime.date(2006, 1, 1) + >>> lit2006 < Literal('2007-01-01',datatype=XSD.date) + True + >>> Literal(datetime.utcnow()).datatype + rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#dateTime') + >>> Literal(1) > Literal(2) # by value + False + >>> Literal(1) > Literal(2.0) # by value + False + >>> Literal('1') > Literal(1) # by DT + True + >>> Literal('1') < Literal('1') # by lexical form + False + >>> Literal('a', lang='en') > Literal('a', lang='fr') # by lang-tag + False + >>> Literal(1) > URIRef('foo') # by node-type + True + + ``` + + The > < operators will eat this NotImplemented and throw a TypeError (py3k): + + ```python + >>> Literal(1).__gt__(2.0) + NotImplemented + + ``` + """ + + _value: Any + _language: Optional[str] + # NOTE: _datatype should maybe be of type URIRef, and not optional. + _datatype: Optional[URIRef] + _ill_typed: Optional[bool] + __slots__ = ("_language", "_datatype", "_value", "_ill_typed") + + def __new__( + cls, + lexical_or_value: Any, + lang: Optional[str] = None, + datatype: Optional[str] = None, + normalize: Optional[bool] = None, + ): + """Create a new Literal instance.""" + if lang == "": + lang = None # no empty lang-tags in RDF + + normalize = normalize if normalize is not None else rdflib.NORMALIZE_LITERALS + + if lang is not None and datatype is not None: + raise TypeError( + "A Literal can only have one of lang or datatype, " + "per http://www.w3.org/TR/rdf-concepts/#section-Graph-Literal" + ) + + if lang is not None and not _is_valid_langtag(lang): + raise ValueError(f"'{str(lang)}' is not a valid language tag!") + + if datatype is not None: + datatype = URIRef(datatype) + + value = None + ill_typed: Optional[bool] = None + if isinstance(lexical_or_value, Literal): + # create from another Literal instance + + lang = lang or lexical_or_value.language + if datatype is not None: + # override datatype + value = _castLexicalToPython(lexical_or_value, datatype) + else: + datatype = lexical_or_value.datatype + value = lexical_or_value.value + + elif isinstance(lexical_or_value, str) or isinstance(lexical_or_value, bytes): + # passed a string + # try parsing lexical form of datatyped literal + value = _castLexicalToPython(lexical_or_value, datatype) + if datatype is not None and datatype in _toPythonMapping: + # datatype is a recognized datatype IRI: + # https://www.w3.org/TR/rdf11-concepts/#dfn-recognized-datatype-iris + dt_uri: URIRef = URIRef(datatype) + checker = _check_well_formed_types.get(dt_uri, _well_formed_by_value) + well_formed = checker(lexical_or_value, value) + ill_typed = ill_typed or (not well_formed) + if value is not None and normalize: + _value, _datatype = _castPythonToLiteral(value, datatype) + if _value is not None and _is_valid_unicode(_value): + lexical_or_value = _value + + else: + # passed some python object + value = lexical_or_value + _value, _datatype = _castPythonToLiteral(lexical_or_value, datatype) + + _datatype = None if _datatype is None else URIRef(_datatype) + + datatype = rdflib.util._coalesce(datatype, _datatype) + if _value is not None: + lexical_or_value = _value + if datatype is not None: + lang = None + + if isinstance(lexical_or_value, bytes): + lexical_or_value = lexical_or_value.decode("utf-8") + + if datatype in (_XSD_NORMALISED_STRING, _XSD_TOKEN): + lexical_or_value = _normalise_XSD_STRING(lexical_or_value) + + if datatype in (_XSD_TOKEN,): + lexical_or_value = _strip_and_collapse_whitespace(lexical_or_value) + + try: + inst = str.__new__(cls, lexical_or_value) + except UnicodeDecodeError: + inst = str.__new__(cls, lexical_or_value, "utf-8") + + inst._language = lang + inst._datatype = datatype + inst._value = value + inst._ill_typed = ill_typed + + return inst + + def normalize(self) -> Literal: + """ + Returns a new literal with a normalised lexical representation + of this literal + + ```python + >>> from rdflib import XSD + >>> Literal("01", datatype=XSD.integer, normalize=False).normalize() + rdflib.term.Literal('1', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#integer')) + + ``` + + Illegal lexical forms for the datatype given are simply passed on + + ```python + >>> Literal("a", datatype=XSD.integer, normalize=False) + rdflib.term.Literal('a', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#integer')) + + ``` + """ + + if self.value is not None: + return Literal(self.value, datatype=self.datatype, lang=self.language) + else: + return self + + @property + def ill_typed(self) -> Optional[bool]: + """ + For `recognized datatype IRIs + `_, + this value will be `True` if the literal is ill formed, otherwise it + will be `False`. `Literal.value` (i.e. the `literal value `_) should always be defined if this property is `False`, but should not be considered reliable if this property is `True`. + + If the literal's datatype is `None` or not in the set of `recognized datatype IRIs + `_ this value will be `None`. + """ + return self._ill_typed + + @property + def value(self) -> Any: + return self._value + + @property + def language(self) -> Optional[str]: + return self._language + + @property + def datatype(self) -> Optional[URIRef]: + return self._datatype + + def __reduce__( + self, + ) -> Tuple[Type[Literal], Tuple[str, Union[str, None], Union[str, None]]]: + return ( + Literal, + (str(self), self.language, self.datatype), + ) + + def __getstate__(self) -> Tuple[None, Dict[str, Union[str, None]]]: + return (None, dict(language=self.language, datatype=self.datatype)) + + def __setstate__(self, arg: Tuple[Any, Dict[str, Any]]) -> None: + _, d = arg + self._language = d["language"] + self._datatype = d["datatype"] + + def __add__(self, val: Any) -> Literal: + """ + ```python + >>> from rdflib.namespace import XSD + >>> Literal(1) + 1 + rdflib.term.Literal('2', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#integer')) + >>> Literal("1") + "1" + rdflib.term.Literal('11') + + # Handling dateTime/date/time based operations in Literals + >>> a = Literal('2006-01-01T20:50:00', datatype=XSD.dateTime) + >>> b = Literal('P31D', datatype=XSD.duration) + >>> (a + b) + rdflib.term.Literal('2006-02-01T20:50:00', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#dateTime')) + >>> from rdflib.namespace import XSD + >>> a = Literal('2006-07-01T20:52:00', datatype=XSD.dateTime) + >>> b = Literal('P122DT15H58M', datatype=XSD.duration) + >>> (a + b) + rdflib.term.Literal('2006-11-01T12:50:00', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#dateTime')) + + ``` + """ + + # if no val is supplied, return this Literal + if val is None: + return self + + # convert the val to a Literal, if it isn't already one + if not isinstance(val, Literal): + val = Literal(val) + + # if self is datetime based and value is duration + if ( + self.datatype in (_XSD_DATETIME, _XSD_DATE) + and val.datatype in _TIME_DELTA_TYPES + ): + date1: Union[datetime, date] = self.toPython() + duration: Union[Duration, timedelta] = val.toPython() + difference = date1 + duration + return Literal(difference, datatype=self.datatype) + + # if self is time based and value is duration + elif self.datatype == _XSD_TIME and val.datatype in _TIME_DELTA_TYPES: + selfv: time = self.toPython() + valv: Union[Duration, timedelta] = val.toPython() + sdt = datetime.combine(date(2000, 1, 1), selfv) + valv + return Literal(sdt.time(), datatype=self.datatype) + + # if self is datetime based and value is not or vice versa + elif ( + ( + self.datatype in _ALL_DATE_AND_TIME_TYPES + and val.datatype not in _ALL_DATE_AND_TIME_TYPES + ) + or ( + self.datatype not in _ALL_DATE_AND_TIME_TYPES + and val.datatype in _ALL_DATE_AND_TIME_TYPES + ) + or ( + self.datatype in _TIME_DELTA_TYPES + and ( + (val.datatype not in _TIME_DELTA_TYPES) + or (self.datatype != val.datatype) + ) + ) + ): + raise TypeError( + f"Cannot add a Literal of datatype {str(val.datatype)} to a Literal of datatype {str(self.datatype)}" + ) + + # if the datatypes are the same, just add the Python values and convert back + if self.datatype == val.datatype: + return Literal( + self.toPython() + val.toPython(), self.language, datatype=self.datatype + ) + # if the datatypes are not the same but are both numeric, add the Python values and strip off decimal junk + # (i.e. tiny numbers (more than 17 decimal places) and trailing zeros) and return as a decimal + elif ( + self.datatype in _NUMERIC_LITERAL_TYPES + and val.datatype in _NUMERIC_LITERAL_TYPES + ): + return Literal( + Decimal( + f"{round(Decimal(self.toPython()) + Decimal(val.toPython()), 15):f}".rstrip( + "0" + ).rstrip( + "." + ) + ), + datatype=_XSD_DECIMAL, + ) + # in all other cases, perform string concatenation + else: + try: + s = str.__add__(self, val) + except TypeError: + s = str(self.value) + str(val) + + # if the original datatype is string-like, use that + if self.datatype in _STRING_LITERAL_TYPES: + new_datatype = self.datatype + # if not, use string + else: + new_datatype = _XSD_STRING + + return Literal(s, self.language, datatype=new_datatype) + + def __sub__(self, val: Any) -> Literal: + """Implements subtraction between Literals or between a Literal and a Python object. + + Example: + ```python + from rdflib.namespace import XSD + + # Basic numeric subtraction + Literal(2) - 1 + # rdflib.term.Literal('1', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#integer')) + + Literal(1.1) - 1.0 + # rdflib.term.Literal('0.10000000000000009', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#double')) + + Literal(1.1) - 1 + # rdflib.term.Literal('0.1', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#decimal')) + + Literal(1.1, datatype=XSD.float) - Literal(1.0, datatype=XSD.float) + # rdflib.term.Literal('0.10000000000000009', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#float')) + + # This will raise a TypeError + Literal("1.1") - 1.0 + # TypeError: Not a number; rdflib.term.Literal('1.1') + + Literal(1.1, datatype=XSD.integer) - Literal(1.0, datatype=XSD.integer) + # rdflib.term.Literal('0.10000000000000009', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#integer')) + + # Handling dateTime/date/time based operations in Literals + a = Literal('2006-01-01T20:50:00', datatype=XSD.dateTime) + b = Literal('2006-02-01T20:50:00', datatype=XSD.dateTime) + (b - a) + # rdflib.term.Literal('P31D', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#duration')) + + a = Literal('2006-07-01T20:52:00', datatype=XSD.dateTime) + b = Literal('2006-11-01T12:50:00', datatype=XSD.dateTime) + (a - b) + # rdflib.term.Literal('-P122DT15H58M', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#duration')) + (b - a) + # rdflib.term.Literal('P122DT15H58M', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#duration')) + ``` + """ + # if no val is supplied, return this Literal + if val is None: + return self + + # convert the val to a Literal, if it isn't already one + if not isinstance(val, Literal): + val = Literal(val) + + if not getattr(self, "datatype"): + raise TypeError( + "Minuend Literal must have Numeric, Date, Datetime or Time datatype." + ) + elif not getattr(val, "datatype"): + raise TypeError( + "Subtrahend Literal must have Numeric, Date, Datetime or Time datatype." + ) + + if ( + self.datatype in (_XSD_DATETIME, _XSD_DATE) + and val.datatype in _TIME_DELTA_TYPES + ): + date1: Union[datetime, date] = self.toPython() + duration: Union[Duration, timedelta] = val.toPython() + difference = date1 - duration + return Literal(difference, datatype=self.datatype) + + # if self is time based and value is duration + elif self.datatype == _XSD_TIME and val.datatype in _TIME_DELTA_TYPES: + selfv: time = self.toPython() + valv: Union[Duration, timedelta] = val.toPython() + sdt = datetime.combine(date(2000, 1, 1), selfv) - valv + return Literal(sdt.time(), datatype=self.datatype) + + # if the datatypes are the same, just subtract the Python values and convert back + if self.datatype == val.datatype: + if self.datatype == _XSD_TIME: + sdt = datetime.combine(date.today(), self.toPython()) + vdt = datetime.combine(date.today(), val.toPython()) + return Literal(sdt - vdt, datatype=_XSD_DURATION) + else: + return Literal( + self.toPython() - val.toPython(), + self.language, + datatype=( + _XSD_DURATION + if self.datatype in (_XSD_DATETIME, _XSD_DATE, _XSD_TIME) + else self.datatype + ), + ) + + # if the datatypes are not the same but are both numeric, subtract the Python values and strip off decimal junk + # (i.e. tiny numbers (more than 17 decimal places) and trailing zeros) and return as a decimal + elif ( + self.datatype in _NUMERIC_LITERAL_TYPES + and val.datatype in _NUMERIC_LITERAL_TYPES + ): + return Literal( + Decimal( + f"{round(Decimal(self.toPython()) - Decimal(val.toPython()), 15):f}".rstrip( + "0" + ).rstrip( + "." + ) + ), + datatype=_XSD_DECIMAL, + ) + # in all other cases, perform string concatenation + else: + raise TypeError( + f"Cannot subtract a Literal of datatype {str(val.datatype)} from a Literal of datatype {str(self.datatype)}" + ) + + def __bool__(self) -> bool: + """Determines the truth value of the Literal. + + Used for if statements, bool(literal), etc. + """ + if self.value is not None: + return bool(self.value) + return len(self) != 0 + + def __neg__(self) -> Literal: + """Implements unary negation for Literals with numeric values. + + Example: + ```python + # Negating an integer Literal + -Literal(1) + # rdflib.term.Literal('-1', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#integer')) + + # Negating a float Literal + -Literal(10.5) + # rdflib.term.Literal('-10.5', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#double')) + + # Using a string with a datatype + from rdflib.namespace import XSD + -Literal("1", datatype=XSD.integer) + # rdflib.term.Literal('-1', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#integer')) + + # This will raise a TypeError + -Literal("1") + # TypeError: Not a number; rdflib.term.Literal('1') + ``` + """ + + if isinstance(self.value, (int, long_type, float)): + return Literal(self.value.__neg__()) + else: + raise TypeError(f"Not a number; {self!r}") + + def __pos__(self) -> Literal: + """Implements unary plus operation for Literals with numeric values. + + Example: + ```python + # Applying unary plus to an integer Literal + +Literal(1) + # rdflib.term.Literal('1', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#integer')) + + # Applying unary plus to a negative integer Literal + +Literal(-1) + # rdflib.term.Literal('-1', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#integer')) + + # Using a string with a datatype + from rdflib.namespace import XSD + +Literal("-1", datatype=XSD.integer) + # rdflib.term.Literal('-1', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#integer')) + + # This will raise a TypeError + +Literal("1") + # TypeError: Not a number; rdflib.term.Literal('1') + ``` + """ + if isinstance(self.value, (int, long_type, float)): + return Literal(self.value.__pos__()) + else: + raise TypeError(f"Not a number; {self!r}") + + def __abs__(self) -> Literal: + """Implements absolute value operation for Literals with numeric values. + + Example: + ```python + # Absolute value of a negative integer Literal + abs(Literal(-1)) + # rdflib.term.Literal('1', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#integer')) + + # Using a string with a datatype + from rdflib.namespace import XSD + abs(Literal("-1", datatype=XSD.integer)) + # rdflib.term.Literal('1', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#integer')) + + # This will raise a TypeError + abs(Literal("1")) + # TypeError: Not a number; rdflib.term.Literal('1') + ``` + """ + if isinstance(self.value, (int, long_type, float)): + return Literal(self.value.__abs__()) + else: + raise TypeError(f"Not a number; {self!r}") + + def __invert__(self) -> Literal: + """Implements bitwise NOT operation for Literals with numeric values. + + Example: + ```python + # Bitwise NOT of a negative integer Literal + ~(Literal(-1)) + # rdflib.term.Literal('0', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#integer')) + + # Using a string with a datatype + from rdflib.namespace import XSD + ~(Literal("-1", datatype=XSD.integer)) + # rdflib.term.Literal('0', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#integer')) + + # This will raise a TypeError + ~(Literal("1")) + # TypeError: Not a number; rdflib.term.Literal('1') + ``` + """ + if isinstance(self.value, (int, long_type, float)): + # type error: Unsupported operand type for ~ ("float") + return Literal(self.value.__invert__()) # type: ignore[operator] # FIXME + else: + raise TypeError(f"Not a number; {self!r}") + + def __gt__(self, other: Any) -> bool: + """Implements the greater-than comparison for Literals. + + This is the base method for ordering comparisons - other comparison methods delegate here. + + Implements the ordering rules described in http://www.w3.org/TR/sparql11-query/#modOrderBy + + In summary: + 1. Literals with compatible data-types are ordered in value space + 2. Incompatible datatypes are ordered by their datatype URIs + 3. Literals with language tags are ordered by their language tags + 4. Plain literals come before xsd:string literals + 5. In the node order: None < BNode < URIRef < Literal + + Example: + ```python + from rdflib import XSD + from decimal import Decimal + + # Comparing numeric literals in value space + Literal(1) > Literal(2) # int/int + # False + + Literal(2.0) > Literal(1) # double/int + # True + + Literal(Decimal("3.3")) > Literal(2.0) # decimal/double + # True + + Literal(Decimal("3.3")) < Literal(4.0) # decimal/double + # True + + # Comparing string literals + Literal('b') > Literal('a') # plain lit/plain lit + # True + + Literal('b') > Literal('a', datatype=XSD.string) # plain lit/xsd:str + # True + + # Incompatible datatypes ordered by DT + Literal(1) > Literal("2") # int>string + # False + + # Langtagged literals ordered by lang tag + Literal("a", lang="en") > Literal("a", lang="fr") + # False + ``` + """ + if other is None: + return True # Everything is greater than None + if isinstance(other, Literal): + # Fast path for comparing numeric literals + # that are not ill-typed and don't have a None value + if ( + ( + self.datatype in _NUMERIC_LITERAL_TYPES + and other.datatype in _NUMERIC_LITERAL_TYPES + ) + and ((not self.ill_typed) and (not other.ill_typed)) + and (self.value is not None and other.value is not None) + ): + return self.value > other.value + + # plain-literals and xsd:string literals + # are "the same" + dtself = rdflib.util._coalesce(self.datatype, default=_XSD_STRING) + dtother = rdflib.util._coalesce(other.datatype, default=_XSD_STRING) + + if dtself != dtother: + if rdflib.DAWG_LITERAL_COLLATION: + return NotImplemented + else: + return dtself > dtother + + if self.language != other.language: + if not self.language: + return False + elif not other.language: + return True + else: + return self.language > other.language + + if self.value is not None and other.value is not None: + if type(self.value) in _TOTAL_ORDER_CASTERS: + caster = _TOTAL_ORDER_CASTERS[type(self.value)] + return caster(self.value) > caster(other.value) + + try: + return self.value > other.value + except TypeError: + pass + + if str(self) != str(other): + return str(self) > str(other) + + # same language, same lexical form, check real dt + # plain-literals come before xsd:string! + if self.datatype != other.datatype: + if self.datatype is None: + return False + elif other.datatype is None: + return True + else: + return self.datatype > other.datatype + + return False # they are the same + + elif isinstance(other, Node): + return True # Literal are the greatest! + else: + return NotImplemented # we can only compare to nodes + + def __lt__(self, other: Any) -> bool: + if other is None: + return False # Nothing is less than None + if isinstance(other, Literal): + try: + return not self.__gt__(other) and not self.eq(other) + except TypeError: + return NotImplemented + if isinstance(other, Node): + return False # all nodes are less-than Literals + + return NotImplemented + + def __le__(self, other: Any) -> bool: + """Less than or equal operator for Literals. + + Example: + ```python + from rdflib.namespace import XSD + Literal('2007-01-01T10:00:00', datatype=XSD.dateTime) <= Literal('2007-01-01T10:00:00', datatype=XSD.dateTime) + # True + ``` + """ + r = self.__lt__(other) + if r: + return True + try: + return self.eq(other) + except TypeError: + return NotImplemented + + def __ge__(self, other: Any) -> bool: + r = self.__gt__(other) + if r: + return True + try: + return self.eq(other) + except TypeError: + return NotImplemented + + def _comparable_to(self, other: Any) -> bool: + """Helper method to decide which things are meaningful to rich-compare with this literal.""" + if isinstance(other, Literal): + if self.datatype is not None and other.datatype is not None: + # two datatyped literals + if ( + self.datatype not in XSDToPython + or other.datatype not in XSDToPython + ): + # non XSD DTs must match + if self.datatype != other.datatype: + return False + + else: + # xsd:string may be compared with plain literals + if not (self.datatype == _XSD_STRING and not other.datatype) or ( + other.datatype == _XSD_STRING and not self.datatype + ): + return False + + # if given lang-tag has to be case insensitive equal + if (self.language or "").lower() != (other.language or "").lower(): + return False + + return True + + # type error: Signature of "__hash__" incompatible with supertype "Identifier" + # Superclass: def __hash__(self: str) -> int + # Subclass: def __hash__(self) -> int + # NOTE for type ignore: This can possibly be fixed by changing how __hash__ is implemented in Identifier + def __hash__(self) -> int: # type: ignore[override] + """Hash function for Literals to enable their use as dictionary keys. + + Example: + ```python + from rdflib.namespace import XSD + a = {Literal('1', datatype=XSD.integer):'one'} + Literal('1', datatype=XSD.double) in a + # False + ``` + + Notes: + "Called for the key object for dictionary operations, + and by the built-in function hash(). Should return + a 32-bit integer usable as a hash value for + dictionary operations. The only required property + is that objects which compare equal have the same + hash value; it is advised to somehow mix together + (e.g., using exclusive or) the hash values for the + components of the object that also play a part in + comparison of objects." -- 3.4.1 Basic customization (Python) + + "Two literals are equal if and only if all of the following hold: + * The strings of the two lexical forms compare equal, character by character. + * Either both or neither have language tags. + * The language tags, if any, compare equal. + * Either both or neither have datatype URIs. + * The two datatype URIs, if any, compare equal, character by character." + -- 6.5.1 Literal Equality (RDF: Concepts and Abstract Syntax) + """ + # don't use super()... for efficiency reasons, see Identifier.__hash__ + res = str.__hash__(self) + # Directly accessing the member is faster than the property. + if self._language: + res ^= hash(self._language.lower()) + if self._datatype is not None: + res ^= hash(self._datatype) + return res + + def __eq__(self, other: Any) -> bool: + """Equality operator for Literals. + + Literals are only equal to other literals. + + Notes: + "Two literals are equal if and only if all of the following hold: + * The strings of the two lexical forms compare equal, character by character. + * Either both or neither have language tags. + * The language tags, if any, compare equal. + * Either both or neither have datatype URIs. + * The two datatype URIs, if any, compare equal, character by character." + -- 6.5.1 Literal Equality (RDF: Concepts and Abstract Syntax) + + Example: + ```python + Literal("1", datatype=URIRef("foo")) == Literal("1", datatype=URIRef("foo")) + # True + Literal("1", datatype=URIRef("foo")) == Literal("1", datatype=URIRef("foo2")) + # False + + Literal("1", datatype=URIRef("foo")) == Literal("2", datatype=URIRef("foo")) + # False + Literal("1", datatype=URIRef("foo")) == "asdf" + # False + + from rdflib import XSD + Literal('2007-01-01', datatype=XSD.date) == Literal('2007-01-01', datatype=XSD.date) + # True + Literal('2007-01-01', datatype=XSD.date) == date(2007, 1, 1) + # False + + Literal("one", lang="en") == Literal("one", lang="en") + # True + Literal("hast", lang='en') == Literal("hast", lang='de') + # False + + Literal("1", datatype=XSD.integer) == Literal(1) + # True + Literal("1", datatype=XSD.integer) == Literal("01", datatype=XSD.integer) + # True + ``` + """ + if self is other: + return True + if other is None: + return False + # Directly accessing the member is faster than the property. + if isinstance(other, Literal): + return ( + self._datatype == other._datatype + and (self._language.lower() if self._language else None) + == (other._language.lower() if other._language else None) + and str.__eq__(self, other) + ) + + return False + + def eq(self, other: Any) -> bool: + """Compare the value of this literal with something else. + + This comparison can be done in two ways: + + 1. With the value of another literal - comparisons are then done in literal "value space" + according to the rules of XSD subtype-substitution/type-promotion + + 2. With a Python object: + * string objects can be compared with plain-literals or those with datatype xsd:string + * bool objects with xsd:boolean + * int, long or float with numeric xsd types + * date, time, datetime objects with xsd:date, xsd:time, xsd:datetime + + Any other operations returns NotImplemented. + """ + if isinstance(other, Literal): + # Fast path for comparing numeric literals + # that are not ill-typed and don't have a None value + if ( + ( + self.datatype in _NUMERIC_LITERAL_TYPES + and other.datatype in _NUMERIC_LITERAL_TYPES + ) + and ((not self.ill_typed) and (not other.ill_typed)) + and (self.value is not None and other.value is not None) + ): + if self.value is not None and other.value is not None: + return self.value == other.value + else: + if str.__eq__(self, other): + return True + raise TypeError( + # TODO: Should this use repr strings in the error message? + "I cannot know that these two lexical forms do not map to the " + f"same value: {self} and {other}" + ) + if (self.language or "").lower() != (other.language or "").lower(): + return False + + dtself = rdflib.util._coalesce(self.datatype, default=_XSD_STRING) + dtother = rdflib.util._coalesce(other.datatype, default=_XSD_STRING) + + if dtself == _XSD_STRING and dtother == _XSD_STRING: + # string/plain literals, compare on lexical form + return str.__eq__(self, other) + + # XML can be compared to HTML, only if html5rdf is enabled + if ( + (dtself in _XML_COMPARABLE and dtother in _XML_COMPARABLE) + and + # Ill-typed can be None if unknown, but we don't want it to be True. + ((self.ill_typed is not True) and (other.ill_typed is not True)) + and (self.value is not None and other.value is not None) + ): + return _isEqualXMLNode(self.value, other.value) + + if dtself != dtother: + if rdflib.DAWG_LITERAL_COLLATION: + raise TypeError( + f"I don't know how to compare literals with datatypes {self.datatype} and {other.datatype}" + ) + else: + return False + + # matching non-string DTs now - do we compare values or + # lexical form first? comparing two ints is far quicker - + # maybe there are counter examples + + if self.value is not None and other.value is not None: + return self.value == other.value + else: + if str.__eq__(self, other): + return True + + if self.datatype == _XSD_STRING: + return False # string value space=lexical space + + # matching DTs, but not matching, we cannot compare! + raise TypeError( + # TODO: Should this use repr strings in the error message? + "I cannot know that these two lexical forms do not map to the same " + f"value: {self} and {other}" + ) + + elif isinstance(other, Node): + return False # no non-Literal nodes are equal to a literal + + elif isinstance(other, str): + # only plain-literals can be directly compared to strings + + # TODO: Is "blah"@en eq "blah" ? + if self.language is not None: + return False + + if self.datatype == _XSD_STRING or self.datatype is None: + return str(self) == other + + elif isinstance(other, (int, long_type, float)): + if self.datatype in _NUMERIC_LITERAL_TYPES: + return self.value == other + elif isinstance(other, (date, datetime, time)): + if self.datatype in (_XSD_DATETIME, _XSD_DATE, _XSD_TIME): + return self.value == other + elif isinstance(other, (timedelta, Duration)): + if self.datatype in ( + _XSD_DURATION, + _XSD_DAYTIMEDURATION, + _XSD_YEARMONTHDURATION, + ): + return self.value == other + # NOTE for type ignore: bool is a subclass of int so this won't ever run. + elif isinstance(other, bool): # type: ignore[unreachable, unused-ignore] + if self.datatype == _XSD_BOOLEAN: + return self.value == other + + return NotImplemented + + def neq(self, other: Any) -> bool: + return not self.eq(other) + + def n3(self, namespace_manager: Optional[NamespaceManager] = None) -> str: + r'''Returns a representation in the N3 format. + + ```python + >>> Literal("foo").n3() + '"foo"' + + ``` + + Strings with newlines or triple-quotes: + + ```python + >>> Literal("foo\nbar").n3() + '"""foo\nbar"""' + >>> Literal("''\'").n3() + '"\'\'\'"' + >>> Literal('"""').n3() + '"\\"\\"\\""' + + ``` + + Language: + + ```python + >>> Literal("hello", lang="en").n3() + '"hello"@en' + + ``` + + Datatypes: + + ```python + >>> Literal(1).n3() + '"1"^^' + >>> Literal(1.0).n3() + '"1.0"^^' + >>> Literal(True).n3() + '"true"^^' + + ``` + + Datatype and language isn't allowed (datatype takes precedence): + + ```python + >>> Literal(1, lang="en").n3() + '"1"^^' + + ``` + + Custom datatype: + + ```python + >>> footype = URIRef("http://example.org/ns#foo") + >>> Literal("1", datatype=footype).n3() + '"1"^^' + + ``` + + Passing a namespace-manager will use it to abbreviate datatype URIs: + + ```python + >>> from rdflib import Graph + >>> Literal(1).n3(Graph().namespace_manager) + '"1"^^xsd:integer' + + ``` + ''' + if namespace_manager: + return self._literal_n3(qname_callback=namespace_manager.normalizeUri) + else: + return self._literal_n3() + + def _literal_n3( + self, + use_plain: bool = False, + qname_callback: Optional[Callable[[URIRef], Optional[str]]] = None, + ) -> str: + """Internal method for N3 serialization with more options. + + Args: + use_plain: Whether to use plain literal (shorthand) output + qname_callback: Function to convert URIs to prefixed names + + Example: + Using plain literal (shorthand) output: + + ```python + >>> from rdflib.namespace import XSD + + >>> Literal(1)._literal_n3(use_plain=True) + '1' + + >>> Literal(1.0)._literal_n3(use_plain=True) + '1e+00' + + >>> Literal(1.0, datatype=XSD.decimal)._literal_n3(use_plain=True) + '1.0' + + >>> Literal(1.0, datatype=XSD.float)._literal_n3(use_plain=True) + '"1.0"^^' + + >>> Literal("foo", datatype=XSD.string)._literal_n3(use_plain=True) + '"foo"^^' + + >>> Literal(True)._literal_n3(use_plain=True) + 'true' + + >>> Literal(False)._literal_n3(use_plain=True) + 'false' + + >>> Literal(1.91)._literal_n3(use_plain=True) + '1.91e+00' + + ``` + + Only limited precision available for floats: + + ```python + >>> Literal(0.123456789)._literal_n3(use_plain=True) + '1.234568e-01' + + >>> Literal('0.123456789', datatype=XSD.decimal)._literal_n3(use_plain=True) + '0.123456789' + + ``` + + Using callback for datatype QNames: + + ```python + >>> Literal(1)._literal_n3(qname_callback=lambda uri: "xsd:integer") + '"1"^^xsd:integer' + + ``` + """ + if use_plain and self.datatype in _PLAIN_LITERAL_TYPES: + if self.value is not None: + # If self is inf or NaN, we need a datatype + # (there is no plain representation) + if self.datatype in _NUMERIC_INF_NAN_LITERAL_TYPES: + try: + v = float(self) + if math.isinf(v) or math.isnan(v): + return self._literal_n3(False, qname_callback) + except ValueError: + return self._literal_n3(False, qname_callback) + + # this is a bit of a mess - + # we try to produce "pretty" output + # that is compatible with n3 (turtle) notation + if self.datatype == _XSD_DOUBLE: + return sub("\\.?0*e", "e", f"{float(self):e}") + elif self.datatype == _XSD_DECIMAL: + s = f"{self}" # f"{self}" is faster than "%s" % self and str(self) + if "." not in s and "e" not in s and "E" not in s: + s += ".0" + return s + elif self.datatype == _XSD_BOOLEAN: + return f"{self}".lower() + else: + return f"{self}" + + encoded: str = self._quote_encode() + + datatype = self.datatype + quoted_dt = None + if datatype is not None: + if qname_callback: + quoted_dt = qname_callback(datatype) + if not quoted_dt: + quoted_dt = f"<{datatype}>" + if datatype in _NUMERIC_INF_NAN_LITERAL_TYPES: + try: + v = float(self) + if math.isinf(v): + # py string reps: float: 'inf', Decimal: 'Infinity" + # both need to become "INF" in xsd datatypes + encoded = encoded.replace("inf", "INF").replace( + "Infinity", "INF" + ) + if math.isnan(v): + encoded = encoded.replace("nan", "NaN") + except ValueError: + # if we can't cast to float something is wrong, but we can + # still serialize. Warn user about it + warnings.warn(f"Serializing weird numerical {self!r}") + + language = self.language + if language: + return f"{encoded}@{language}" + elif datatype: + return f"{encoded}^^{quoted_dt}" + else: + return encoded + + def _quote_encode(self) -> str: + # This simpler encoding doesn't work; a newline gets encoded as "\\n", + # which is ok in sourcecode, but we want "\n". + # encoded = self.encode('unicode-escape').replace( + # '\\', '\\\\').replace('"','\\"') + # encoded = self.replace.replace('\\', '\\\\').replace('"','\\"') + + # NOTE: Could in theory chose quotes based on quotes appearing in the + # string, i.e. '"' and "'", but N3/turtle doesn't allow "'"(?). + + if "\n" in self: + # Triple quote this string. + encoded = self.replace("\\", "\\\\") + if '"""' in self: + # is this ok? + encoded = encoded.replace('"""', '\\"\\"\\"') + if encoded[-1] == '"' and encoded[-2] != "\\": + encoded = encoded[:-1] + "\\" + '"' + # TODO: Replace usage of %s here with fstrings + # when we have ability to escape \r and \n inside + # f-string inline function calls + return '"""%s"""' % encoded.replace("\r", "\\r") + else: + return '"%s"' % self.replace("\n", "\\n").replace("\\", "\\\\").replace( + '"', '\\"' + ).replace("\r", "\\r") + + def __repr__(self) -> str: + args = [str.__repr__(self)] + if self.language is not None: + args.append("lang=" + repr(self.language)) + if self.datatype is not None: + args.append("datatype=" + repr(self.datatype)) + if self.__class__ == Literal: + clsName = "rdflib.term.Literal" # noqa: N806 + else: + clsName = self.__class__.__name__ # noqa: N806 + return f"{clsName}({', '.join(args)})" + + def toPython(self) -> Any: # noqa: N802 + """ + Returns an appropriate python datatype derived from this RDF Literal + """ + + if self.value is not None: + return self.value + return self + + +def _parseXML(xmlstring: str) -> xml.dom.minidom.Document: # noqa: N802 + retval = xml.dom.minidom.parseString( + f"{xmlstring}" + ) + retval.normalize() + return retval + + +def _parse_html(lexical_form: str) -> xml.dom.minidom.DocumentFragment: + """ + Parse the lexical form of an HTML literal into a document fragment + using the `dom` from html5rdf tree builder. + + Args: + lexical_form: The lexical form of the HTML literal. + + Returns: + A document fragment representing the HTML literal. + + Raises: + html5rdf.html5parser.ParseError: If the lexical form is not valid HTML. + """ + parser = html5rdf.HTMLParser( + tree=html5rdf.treebuilders.getTreeBuilder("dom"), strict=True + ) + try: + result: xml.dom.minidom.DocumentFragment = parser.parseFragment(lexical_form) + except html5rdf.html5parser.ParseError as e: + logger.info(f"Failed to parse HTML: {e}") + raise e + result.normalize() + return result + + +def _write_html(value: xml.dom.minidom.DocumentFragment) -> bytes: + """ + Serialize a document fragment representing an HTML literal into + its lexical form. + + Args: + value: A document fragment representing an HTML literal. + + Returns: + The lexical form of the HTML literal. + """ + result = html5rdf.serialize(value, tree="dom") + return result + + +def _writeXML( # noqa: N802 + xmlnode: Union[xml.dom.minidom.Document, xml.dom.minidom.DocumentFragment] +) -> bytes: + if isinstance(xmlnode, xml.dom.minidom.DocumentFragment): + d = xml.dom.minidom.Document() + d.childNodes += xmlnode.childNodes + xmlnode = d + s = xmlnode.toxml("utf-8") + # for clean round-tripping, remove headers -- I have great and + # specific worries that this will blow up later, but this margin + # is too narrow to contain them + if s.startswith(b''): + s = s[38:] + if s.startswith(b""): + s = s[23:-24] + if s == b"": + s = b"" + return s + + +def _unhexlify(value: Union[str, bytes, Literal]) -> bytes: + # In Python 3.2, unhexlify does not support str (only bytes) + if isinstance(value, str): + value = value.encode() + return unhexlify(value) + + +def _parseBoolean(value: Union[str, bytes]) -> bool: # noqa: N802 + """ + Boolean is a datatype with value space {true,false}, + lexical space {"true", "false","1","0"} and + lexical-to-value mapping {"true"→true, "false"→false, "1"→true, "0"→false}. + """ + true_accepted_values = ["1", "true", b"1", b"true"] + false_accepted_values = ["0", "false", b"0", b"false"] + new_value = value.lower() + if new_value in true_accepted_values: + return True + if new_value not in false_accepted_values: + warnings.warn( + f"Parsing weird boolean, {value!r} does not map to True or False", + category=UserWarning, + ) + return False + + +def _well_formed_by_value(lexical: Union[str, bytes], value: Any) -> bool: + """ + This function is used as the fallback for detecting ill-typed/ill-formed + literals and operates on the asumption that if a value (i.e. + `Literal.value`) could be determined for a Literal then it is not + ill-typed/ill-formed. + + This function will be called with `Literal.lexical` and `Literal.value` as arguments. + """ + return value is not None + + +def _well_formed_unsignedlong(lexical: Union[str, bytes], value: Any) -> bool: + """ + xsd:unsignedInteger and xsd:unsignedLong must not be negative + """ + return len(lexical) > 0 and isinstance(value, long_type) and value >= 0 + + +def _well_formed_boolean(lexical: Union[str, bytes], value: Any) -> bool: + """ + Boolean is a datatype with value space {true,false}, + lexical space {"true", "false","1","0"} and + lexical-to-value mapping {"true"→true, "false"→false, "1"→true, "0"→false}. + """ + return lexical in ("true", b"true", "false", b"false", "1", b"1", "0", b"0") + + +def _well_formed_int(lexical: Union[str, bytes], value: Any) -> bool: + """ + The value space of xs:int is the set of common single size integers (32 bits), + i.e., the integers between -2147483648 and 2147483647, + its lexical space allows any number of insignificant leading zeros. + """ + return ( + len(lexical) > 0 + and isinstance(value, int) + and (-2147483648 <= value <= 2147483647) + ) + + +def _well_formed_unsignedint(lexical: Union[str, bytes], value: Any) -> bool: + """ + xsd:unsignedInt has a 32bit value of between 0 and 4294967295 + """ + return len(lexical) > 0 and isinstance(value, int) and (0 <= value <= 4294967295) + + +def _well_formed_short(lexical: Union[str, bytes], value: Any) -> bool: + """ + The value space of xs:short is the set of common short integers (16 bits), + i.e., the integers between -32768 and 32767, + its lexical space allows any number of insignificant leading zeros. + """ + return len(lexical) > 0 and isinstance(value, int) and (-32768 <= value <= 32767) + + +def _well_formed_unsignedshort(lexical: Union[str, bytes], value: Any) -> bool: + """ + xsd:unsignedShort has a 16bit value of between 0 and 65535 + """ + return len(lexical) > 0 and isinstance(value, int) and (0 <= value <= 65535) + + +def _well_formed_byte(lexical: Union[str, bytes], value: Any) -> bool: + """ + The value space of xs:byte is the set of common single byte integers (8 bits), + i.e., the integers between -128 and 127, + its lexical space allows any number of insignificant leading zeros. + """ + return len(lexical) > 0 and isinstance(value, int) and (-128 <= value <= 127) + + +def _well_formed_unsignedbyte(lexical: Union[str, bytes], value: Any) -> bool: + """ + xsd:unsignedByte has a 8bit value of between 0 and 255 + """ + return len(lexical) > 0 and isinstance(value, int) and (0 <= value <= 255) + + +def _well_formed_non_negative_integer(lexical: Union[str, bytes], value: Any) -> bool: + return isinstance(value, int) and value >= 0 + + +def _well_formed_positive_integer(lexical: Union[str, bytes], value: Any) -> bool: + return isinstance(value, int) and value > 0 + + +def _well_formed_non_positive_integer(lexical: Union[str, bytes], value: Any) -> bool: + return isinstance(value, int) and value <= 0 + + +def _well_formed_negative_integer(lexical: Union[str, bytes], value: Any) -> bool: + return isinstance(value, int) and value < 0 + + +# Cannot import Namespace/XSD because of circular dependencies +_XSD_PFX = "http://www.w3.org/2001/XMLSchema#" +_RDF_PFX = "http://www.w3.org/1999/02/22-rdf-syntax-ns#" + +_RDF_XMLLITERAL = URIRef(_RDF_PFX + "XMLLiteral") +_RDF_HTMLLITERAL = URIRef(_RDF_PFX + "HTML") + +_XSD_STRING = URIRef(_XSD_PFX + "string") +_XSD_NORMALISED_STRING = URIRef(_XSD_PFX + "normalizedString") +_XSD_TOKEN = URIRef(_XSD_PFX + "token") + +_XSD_FLOAT = URIRef(_XSD_PFX + "float") +_XSD_DOUBLE = URIRef(_XSD_PFX + "double") +_XSD_DECIMAL = URIRef(_XSD_PFX + "decimal") +_XSD_INTEGER = URIRef(_XSD_PFX + "integer") +_XSD_BOOLEAN = URIRef(_XSD_PFX + "boolean") + +_XSD_DATETIME = URIRef(_XSD_PFX + "dateTime") +_XSD_DATE = URIRef(_XSD_PFX + "date") +_XSD_TIME = URIRef(_XSD_PFX + "time") +_XSD_DURATION = URIRef(_XSD_PFX + "duration") +_XSD_DAYTIMEDURATION = URIRef(_XSD_PFX + "dayTimeDuration") +_XSD_YEARMONTHDURATION = URIRef(_XSD_PFX + "yearMonthDuration") + +_OWL_RATIONAL = URIRef("http://www.w3.org/2002/07/owl#rational") +_XSD_B64BINARY = URIRef(_XSD_PFX + "base64Binary") +_XSD_HEXBINARY = URIRef(_XSD_PFX + "hexBinary") +_XSD_GYEAR = URIRef(_XSD_PFX + "gYear") +_XSD_GYEARMONTH = URIRef(_XSD_PFX + "gYearMonth") +# TODO: gMonthDay, gDay, gMonth + +_NUMERIC_LITERAL_TYPES: Tuple[URIRef, ...] = ( + _XSD_INTEGER, + _XSD_DECIMAL, + _XSD_DOUBLE, + URIRef(_XSD_PFX + "float"), + URIRef(_XSD_PFX + "byte"), + URIRef(_XSD_PFX + "int"), + URIRef(_XSD_PFX + "long"), + URIRef(_XSD_PFX + "negativeInteger"), + URIRef(_XSD_PFX + "nonNegativeInteger"), + URIRef(_XSD_PFX + "nonPositiveInteger"), + URIRef(_XSD_PFX + "positiveInteger"), + URIRef(_XSD_PFX + "short"), + URIRef(_XSD_PFX + "unsignedByte"), + URIRef(_XSD_PFX + "unsignedInt"), + URIRef(_XSD_PFX + "unsignedLong"), + URIRef(_XSD_PFX + "unsignedShort"), +) + +# these have "native" syntax in N3/SPARQL +_PLAIN_LITERAL_TYPES: Tuple[URIRef, ...] = ( + _XSD_INTEGER, + _XSD_BOOLEAN, + _XSD_DOUBLE, + _XSD_DECIMAL, + _OWL_RATIONAL, +) + +# these have special INF and NaN XSD representations +_NUMERIC_INF_NAN_LITERAL_TYPES: Tuple[URIRef, ...] = ( + URIRef(_XSD_PFX + "float"), + _XSD_DOUBLE, + _XSD_DECIMAL, +) + +# these need dedicated operators +_DATE_AND_TIME_TYPES: Tuple[URIRef, ...] = ( + _XSD_DATETIME, + _XSD_DATE, + _XSD_TIME, +) + +# These are recognized datatype IRIs +# (https://www.w3.org/TR/rdf11-concepts/#dfn-recognized-datatype-iris) that +# represents durations. +_TIME_DELTA_TYPES: Tuple[URIRef, ...] = ( + _XSD_DURATION, + _XSD_DAYTIMEDURATION, +) + +_ALL_DATE_AND_TIME_TYPES: Tuple[URIRef, ...] = _DATE_AND_TIME_TYPES + _TIME_DELTA_TYPES + +# the following types need special treatment for reasonable sorting because +# certain instances can't be compared to each other. We treat this by +# partitioning and then sorting within those partitions. +_TOTAL_ORDER_CASTERS: Dict[Type[Any], Callable[[Any], Any]] = { + datetime: lambda value: ( + # naive vs. aware + value.tzinfo is not None and value.tzinfo.utcoffset(value) is not None, + value, + ), + time: lambda value: ( + # naive vs. aware + value.tzinfo is not None and value.tzinfo.utcoffset(None) is not None, + value, + ), + xml.dom.minidom.Document: lambda value: value.toxml(), +} + + +_STRING_LITERAL_TYPES: Tuple[URIRef, ...] = ( + _XSD_STRING, + _RDF_XMLLITERAL, + _RDF_HTMLLITERAL, + URIRef(_XSD_PFX + "normalizedString"), + URIRef(_XSD_PFX + "token"), +) + +_StrT = TypeVar("_StrT", bound=str) + + +def _py2literal( + obj: Any, + pType: Any, # noqa: N803 + castFunc: Optional[Callable[[Any], Any]], # noqa: N803 + dType: Optional[_StrT], # noqa: N803 +) -> Tuple[Any, Optional[_StrT]]: + if castFunc is not None: + return castFunc(obj), dType + elif dType is not None: + return obj, dType + else: + return obj, None + + +def _castPythonToLiteral( # noqa: N802 + obj: Any, datatype: Optional[str] +) -> Tuple[Any, Optional[str]]: + """ + Casts a tuple of a python type and a special datatype URI to a tuple of the lexical value and a + datatype URI (or None) + """ + castFunc: Optional[Callable[[Any], Union[str, bytes]]] # noqa: N806 + dType: Optional[str] # noqa: N806 + for (pType, dType), castFunc in _SpecificPythonToXSDRules: # noqa: N806 + if isinstance(obj, pType) and dType == datatype: + return _py2literal(obj, pType, castFunc, dType) + + for pType, (castFunc, dType) in _GenericPythonToXSDRules: # noqa: N806 + if isinstance(obj, pType): + return _py2literal(obj, pType, castFunc, dType) + return obj, None # TODO: is this right for the fall through case? + + +# Mappings from Python types to XSD datatypes and back (borrowed from sparta) +# datetime instances are also instances of date... so we need to order these. + +# SPARQL/Turtle/N3 has shortcuts for integer, double, decimal +# python has only float - to be in tune with sparql/n3/turtle +# we default to XSD.double for float literals + +# python ints are promoted to longs when overflowing +# python longs have no limit +# both map to the abstract integer type, +# rather than some concrete bit-limited datatype +_GenericPythonToXSDRules: List[ + Tuple[Type[Any], Tuple[Optional[Callable[[Any], Union[str, bytes]]], Optional[str]]] +] = [ + (str, (None, None)), + (float, (None, _XSD_DOUBLE)), + (bool, (lambda i: str(i).lower(), _XSD_BOOLEAN)), + (int, (None, _XSD_INTEGER)), + (long_type, (None, _XSD_INTEGER)), + (Decimal, (lambda i: f"{i:f}", _XSD_DECIMAL)), + (datetime, (lambda i: i.isoformat(), _XSD_DATETIME)), + (date, (lambda i: i.isoformat(), _XSD_DATE)), + (time, (lambda i: i.isoformat(), _XSD_TIME)), + (Duration, (lambda i: duration_isoformat(i), _XSD_DURATION)), + (timedelta, (lambda i: duration_isoformat(i), _XSD_DAYTIMEDURATION)), + (xml.dom.minidom.Document, (_writeXML, _RDF_XMLLITERAL)), + (Fraction, (None, _OWL_RATIONAL)), +] + +if html5rdf is not None: + # This is a bit dirty, by accident the html5rdf parser produces + # DocumentFragments, and the xml parser Documents, letting this + # decide what datatype to use makes roundtripping easier, but its a + # bit random. + + # This must happen before _GenericPythonToXSDRules is assigned to + # _OriginalGenericPythonToXSDRules. + _GenericPythonToXSDRules.append( + (xml.dom.minidom.DocumentFragment, (_write_html, _RDF_HTMLLITERAL)) + ) + +_OriginalGenericPythonToXSDRules = list(_GenericPythonToXSDRules) + +_SpecificPythonToXSDRules: List[ + Tuple[Tuple[Type[Any], str], Optional[Callable[[Any], Union[str, bytes]]]] +] = [ + ((date, _XSD_GYEAR), lambda val: val.strftime("%Y").zfill(4)), + ((date, _XSD_GYEARMONTH), lambda val: val.strftime("%Y-%m").zfill(7)), + ((str, _XSD_HEXBINARY), hexlify), + ((bytes, _XSD_HEXBINARY), hexlify), + ((str, _XSD_B64BINARY), b64encode), + ((bytes, _XSD_B64BINARY), b64encode), +] + +_OriginalSpecificPythonToXSDRules = list(_SpecificPythonToXSDRules) + +XSDToPython: Dict[Optional[str], Optional[Callable[[str], Any]]] = { + None: None, # plain literals map directly to value space + URIRef(_XSD_PFX + "time"): parse_time, + URIRef(_XSD_PFX + "date"): parse_xsd_date, + URIRef(_XSD_PFX + "dateTime"): parse_datetime, + URIRef(_XSD_PFX + "duration"): parse_xsd_duration, + URIRef(_XSD_PFX + "dayTimeDuration"): parse_xsd_duration, + URIRef(_XSD_PFX + "yearMonthDuration"): parse_xsd_duration, + URIRef(_XSD_PFX + "hexBinary"): _unhexlify, + URIRef(_XSD_PFX + "string"): None, + URIRef(_XSD_PFX + "normalizedString"): None, + URIRef(_XSD_PFX + "token"): None, + URIRef(_XSD_PFX + "language"): None, + URIRef(_XSD_PFX + "boolean"): _parseBoolean, + URIRef(_XSD_PFX + "decimal"): Decimal, + URIRef(_XSD_PFX + "integer"): long_type, + URIRef(_XSD_PFX + "nonPositiveInteger"): long_type, + URIRef(_XSD_PFX + "long"): long_type, + URIRef(_XSD_PFX + "nonNegativeInteger"): long_type, + URIRef(_XSD_PFX + "negativeInteger"): long_type, + URIRef(_XSD_PFX + "int"): int, + URIRef(_XSD_PFX + "unsignedLong"): long_type, + URIRef(_XSD_PFX + "positiveInteger"): long_type, + URIRef(_XSD_PFX + "short"): int, + URIRef(_XSD_PFX + "unsignedInt"): int, + URIRef(_XSD_PFX + "byte"): int, + URIRef(_XSD_PFX + "unsignedShort"): int, + URIRef(_XSD_PFX + "unsignedByte"): int, + URIRef(_XSD_PFX + "float"): float, + URIRef(_XSD_PFX + "double"): float, + URIRef(_XSD_PFX + "base64Binary"): b64decode, + URIRef(_XSD_PFX + "anyURI"): None, + _RDF_XMLLITERAL: _parseXML, +} + +if html5rdf is not None: + # It is probably best to keep this close to the definition of + # _GenericPythonToXSDRules so nobody misses it. + XSDToPython[_RDF_HTMLLITERAL] = _parse_html + _XML_COMPARABLE: Tuple[URIRef, ...] = (_RDF_XMLLITERAL, _RDF_HTMLLITERAL) +else: + _XML_COMPARABLE = (_RDF_XMLLITERAL,) + +_check_well_formed_types: Dict[URIRef, Callable[[Union[str, bytes], Any], bool]] = { + URIRef(_XSD_PFX + "boolean"): _well_formed_boolean, + URIRef(_XSD_PFX + "nonPositiveInteger"): _well_formed_non_positive_integer, + URIRef(_XSD_PFX + "nonNegativeInteger"): _well_formed_non_negative_integer, + URIRef(_XSD_PFX + "negativeInteger"): _well_formed_negative_integer, + URIRef(_XSD_PFX + "positiveInteger"): _well_formed_positive_integer, + URIRef(_XSD_PFX + "int"): _well_formed_int, + URIRef(_XSD_PFX + "short"): _well_formed_short, + URIRef(_XSD_PFX + "byte"): _well_formed_byte, + URIRef(_XSD_PFX + "unsignedInt"): _well_formed_unsignedint, + URIRef(_XSD_PFX + "unsignedLong"): _well_formed_unsignedlong, + URIRef(_XSD_PFX + "unsignedShort"): _well_formed_unsignedshort, + URIRef(_XSD_PFX + "unsignedByte"): _well_formed_unsignedbyte, +} + +_toPythonMapping: Dict[Optional[str], Optional[Callable[[str], Any]]] = {} # noqa: N816 + +_toPythonMapping.update(XSDToPython) + + +def _reset_bindings() -> None: + """Reset lexical<->value space binding for `Literal`.""" + _toPythonMapping.clear() + _toPythonMapping.update(XSDToPython) + + _GenericPythonToXSDRules.clear() + _GenericPythonToXSDRules.extend(_OriginalGenericPythonToXSDRules) + + _SpecificPythonToXSDRules.clear() + _SpecificPythonToXSDRules.extend(_OriginalSpecificPythonToXSDRules) + + +def _castLexicalToPython( # noqa: N802 + lexical: Union[str, bytes], datatype: Optional[URIRef] +) -> Any: + """Map a lexical form to the value-space for the given datatype. + + Returns: + A python object for the value or `None` + """ + try: + conv_func = _toPythonMapping[datatype] + except KeyError: + # no conv_func -> unknown data-type + return None + + if conv_func is not None: + try: + # type error: Argument 1 has incompatible type "Union[str, bytes]"; expected "str" + # NOTE for type ignore: various functions in _toPythonMapping will + # only work for str, so there is some inconsistency here, the right + # approach may be to change lexical to be of str type but this will + # require runtime changes. + return conv_func(lexical) # type: ignore[arg-type] + except Exception: + logger.warning( + f"Failed to convert Literal lexical form to value. Datatype={datatype}, Converter={conv_func}", + exc_info=True, + ) + # not a valid lexical representation for this dt + return None + else: + # no conv func means 1-1 lexical<->value-space mapping + try: + return str(lexical) + except UnicodeDecodeError: + # type error: Argument 1 to "str" has incompatible type "Union[str, bytes]"; expected "bytes" + # NOTE for type ignore: code assumes that lexical is of type bytes + # at this point. + return str(lexical, "utf-8") # type: ignore[arg-type] + + +_AnyT = TypeVar("_AnyT", bound=Any) + + +def _normalise_XSD_STRING(lexical_or_value: _AnyT) -> _AnyT: # noqa: N802 + """Replaces \\t, \\n, \\r (#x9 (tab), #xA (linefeed), and #xD (carriage return)) with space without any whitespace collapsing.""" + if isinstance(lexical_or_value, str): + # type error: Incompatible return value type (got "str", expected "_AnyT") [return-value] + # NOTE for type ignore: this is an issue with mypy: https://github.com/python/mypy/issues/10003 + return lexical_or_value.replace("\t", " ").replace("\n", " ").replace("\r", " ") # type: ignore[return-value] + return lexical_or_value + + +def _strip_and_collapse_whitespace(lexical_or_value: _AnyT) -> _AnyT: + if isinstance(lexical_or_value, str): + # Use regex to substitute contiguous whitespace into a single whitespace. Strip trailing whitespace. + # type error: Incompatible return value type (got "str", expected "_AnyT") [return-value] + # NOTE for type ignore: this is an issue with mypy: https://github.com/python/mypy/issues/10003 + return re.sub(" +", " ", lexical_or_value.strip()) # type: ignore[return-value] + return lexical_or_value + + +def bind( + datatype: str, + pythontype: Type[Any], + constructor: Optional[Callable[[str], Any]] = None, + lexicalizer: Optional[Callable[[Any], Union[str, bytes]]] = None, + datatype_specific: bool = False, +) -> None: + """ + register a new datatype<->pythontype binding + + Args: + constructor: An optional function for converting lexical forms + into a Python instances, if not given the pythontype + is used directly + lexicalizer: An optional function for converting python objects to + lexical form, if not given object.__str__ is used + datatype_specific: Makes the lexicalizer function be accessible + from the pair (pythontype, datatype) if set to True + or from the pythontype otherwise. False by default + """ + if datatype_specific and datatype is None: + raise Exception("No datatype given for a datatype-specific binding") + + if datatype in _toPythonMapping: + logger.warning(f"datatype '{datatype}' was already bound. Rebinding.") + + if constructor is None: + constructor = pythontype + _toPythonMapping[datatype] = constructor + if datatype_specific: + _SpecificPythonToXSDRules.append(((pythontype, datatype), lexicalizer)) + else: + _GenericPythonToXSDRules.append((pythontype, (lexicalizer, datatype))) + + +class Variable(Identifier): + """ + A Variable - this is used for querying, or in Formula aware + graphs, where Variables can be stored + """ + + __slots__ = () + + def __new__(cls, value: str): + if len(value) == 0: + raise Exception("Attempted to create variable with empty string as name!") + if value[0] == "?": + value = value[1:] + return str.__new__(cls, value) + + def __repr__(self) -> str: + if self.__class__ is Variable: + clsName = "rdflib.term.Variable" # noqa: N806 + else: + clsName = self.__class__.__name__ # noqa: N806 + + return f"{clsName}({str.__repr__(self)})" + + def toPython(self) -> str: # noqa: N802 + return "?" + self + + def n3(self, namespace_manager: Optional[NamespaceManager] = None) -> str: + return "?" + self + + def __reduce__(self) -> Tuple[Type[Variable], Tuple[str]]: + return (Variable, (str(self),)) + + +# Nodes are ordered like this +# See http://www.w3.org/TR/sparql11-query/#modOrderBy +# we leave "space" for more subclasses of Node elsewhere +# default-dict to grazefully fail for new subclasses +_ORDERING: Dict[Type[Node], int] = defaultdict(int) +_ORDERING.update({BNode: 10, Variable: 20, URIRef: 30, Literal: 40}) + + +def _isEqualXMLNode( # noqa: N802 + node: Union[ + None, + xml.dom.minidom.Attr, + xml.dom.minidom.Comment, + xml.dom.minidom.Document, + xml.dom.minidom.DocumentFragment, + xml.dom.minidom.DocumentType, + xml.dom.minidom.Element, + xml.dom.minidom.Entity, + xml.dom.minidom.Notation, + xml.dom.minidom.ProcessingInstruction, + xml.dom.minidom.Text, + ], + other: Union[ + None, + xml.dom.minidom.Attr, + xml.dom.minidom.Comment, + xml.dom.minidom.Document, + xml.dom.minidom.DocumentFragment, + xml.dom.minidom.DocumentType, + xml.dom.minidom.Element, + xml.dom.minidom.Entity, + xml.dom.minidom.Notation, + xml.dom.minidom.ProcessingInstruction, + xml.dom.minidom.Text, + ], +) -> bool: + # importing xml.dom.minidom.Node as XMLNode to avoid confusion with + # rdflib.term.Node + from xml.dom.minidom import Node as XMLNode + + def recurse(): + # Recursion through the children + # In Python2, the semantics of 'map' is such that the check on + # length would be unnecessary. In Python 3, + # the semantics of map has changed (why, oh why???) and the check + # for the length becomes necessary... + # type error: Item "None" of "Union[None, Attr, Comment, Document, DocumentFragment, DocumentType, Element, Entity, Notation, ProcessingInstruction, Text]" has no attribute "childNodes" + if len(node.childNodes) != len(other.childNodes): # type: ignore[union-attr] + return False + # type error: Item "None" of "Union[None, Attr, Comment, Document, DocumentFragment, DocumentType, Element, Entity, Notation, ProcessingInstruction, Text]" has no attribute "childNodes" + for nc, oc in map(lambda x, y: (x, y), node.childNodes, other.childNodes): # type: ignore[union-attr] + if not _isEqualXMLNode(nc, oc): + return False + # if we got here then everything is fine: + return True + + if node is None or other is None: + return False + + if node.nodeType != other.nodeType: + return False + + if node.nodeType in [XMLNode.DOCUMENT_NODE, XMLNode.DOCUMENT_FRAGMENT_NODE]: + return recurse() + + elif node.nodeType == XMLNode.ELEMENT_NODE: + if TYPE_CHECKING: + assert isinstance(node, xml.dom.minidom.Element) + assert isinstance(other, xml.dom.minidom.Element) + # Get the basics right + if not ( + node.tagName == other.tagName and node.namespaceURI == other.namespaceURI + ): + return False + + # Handle the (namespaced) attributes; the namespace setting key + # should be ignored, though + # Note that the minidom orders the keys already, so we do not have + # to worry about that, which is a bonus... + n_keys = [ + k + for k in node.attributes.keysNS() + if k[0] != "http://www.w3.org/2000/xmlns/" + ] + o_keys = [ + k + for k in other.attributes.keysNS() + if k[0] != "http://www.w3.org/2000/xmlns/" + ] + if len(n_keys) != len(o_keys): + return False + for k in n_keys: + if not ( + k in o_keys + and node.getAttributeNS(k[0], k[1]) == other.getAttributeNS(k[0], k[1]) + ): + return False + + # if we got here, the attributes are all right, we can go down + # the tree recursively + return recurse() + + elif node.nodeType in [ + XMLNode.TEXT_NODE, + XMLNode.COMMENT_NODE, + XMLNode.CDATA_SECTION_NODE, + XMLNode.NOTATION_NODE, + ]: + if TYPE_CHECKING: + assert isinstance( + node, + ( + xml.dom.minidom.Text, + xml.dom.minidom.Comment, + xml.dom.minidom.CDATASection, + xml.dom.minidom.Notation, + ), + ) + assert isinstance( + other, + ( + xml.dom.minidom.Text, + xml.dom.minidom.Comment, + xml.dom.minidom.CDATASection, + xml.dom.minidom.Notation, + ), + ) + # type error: Item "Notation" of "Union[Comment, Document, Notation, Text]" has no attribute "data" + return node.data == other.data # type: ignore[union-attr] # FIXME + + elif node.nodeType == XMLNode.PROCESSING_INSTRUCTION_NODE: + if TYPE_CHECKING: + assert isinstance(node, xml.dom.minidom.ProcessingInstruction) + assert isinstance(other, xml.dom.minidom.ProcessingInstruction) + return node.data == other.data and node.target == other.target + + elif node.nodeType == XMLNode.ENTITY_NODE: + return node.nodeValue == other.nodeValue + + elif node.nodeType == XMLNode.DOCUMENT_TYPE_NODE: + if TYPE_CHECKING: + assert isinstance(node, xml.dom.minidom.DocumentType) + assert isinstance(other, xml.dom.minidom.DocumentType) + return node.publicId == other.publicId and node.systemId == other.systemId + + else: + # should not happen, in fact + raise Exception(f"I dont know how to compare XML Node type: {node.nodeType}") diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rdflib/util.py b/TTS/Kokoro/.venv/Lib/site-packages/rdflib/util.py new file mode 100644 index 0000000000000000000000000000000000000000..39459d8e92d9f5c9213cbce50d3b99b91a8a74f3 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rdflib/util.py @@ -0,0 +1,659 @@ +""" +Some utility functions. + +Miscellaneous utilities + +* list2set +* first +* uniq +* more_than + +Term characterisation and generation + +* to_term +* from_n3 + +Date/time utilities + +* date_time +* parse_date_time + +""" + +from __future__ import annotations + +from calendar import timegm +from os.path import splitext + +# from time import daylight +from time import altzone, gmtime, localtime, time, timezone +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + Hashable, + Iterable, + Iterator, + List, + Optional, + Set, + Tuple, + TypeVar, + Union, + overload, +) +from urllib.parse import quote, urlsplit, urlunsplit + +import rdflib.graph # avoid circular dependency +import rdflib.namespace +import rdflib.term +from rdflib.compat import sign + +if TYPE_CHECKING: + from rdflib.graph import Graph + + +__all__ = [ + "list2set", + "first", + "uniq", + "more_than", + "to_term", + "from_n3", + "date_time", + "parse_date_time", + "guess_format", + "find_roots", + "get_tree", + "_coalesce", + "_iri2uri", +] + +_HashableT = TypeVar("_HashableT", bound=Hashable) +_AnyT = TypeVar("_AnyT") + + +SUFFIX_FORMAT_MAP = { + "xml": "xml", + "rdf": "xml", + "owl": "xml", + "n3": "n3", + "ttl": "turtle", + "nt": "nt", + "trix": "trix", + "xhtml": "rdfa", + "html": "rdfa", + "svg": "rdfa", + "nq": "nquads", + "nquads": "nquads", + "trig": "trig", + "json": "json-ld", + "jsonld": "json-ld", + "json-ld": "json-ld", +} + + +FORMAT_MIMETYPE_MAP = { + "xml": ["application/rdf+xml"], + "n3": ["text/n3"], + "turtle": ["text/turtle"], + "nt": ["application/n-triples"], + "trix": ["application/trix"], + "rdfa": ["text/html", "application/xhtml+xml"], + "nquads": ["application/n-quads"], + "trig": ["application/trig"], + "json-ld": ["application/ld+json"], +} + + +RESPONSE_TABLE_FORMAT_MIMETYPE_MAP = { + "xml": ["application/sparql-results+xml"], + "json": ["application/sparql-results+json"], + "csv": ["text/csv"], + "tsv": ["text/tab-separated-values"], +} + + +def list2set(seq: Iterable[_HashableT]) -> List[_HashableT]: + """ + Return a new list without duplicates. + Preserves the order, unlike set(seq) + """ + seen = set() + # type error: "add" of "set" does not return a value + return [x for x in seq if x not in seen and not seen.add(x)] # type: ignore[func-returns-value] + + +def first(seq: Iterable[_AnyT]) -> Optional[_AnyT]: + """ + return the first element in a python sequence + for graphs, use graph.value instead + """ + for result in seq: + return result + return None + + +def uniq(sequence: Iterable[str], strip: int = 0) -> Set[str]: + """removes duplicate strings from the sequence.""" + if strip: + return set(s.strip() for s in sequence) + else: + return set(sequence) + + +def more_than(sequence: Iterable[Any], number: int) -> int: + "Returns 1 if sequence has more items than number and 0 if not." + i = 0 + for item in sequence: + i += 1 + if i > number: + return 1 + return 0 + + +def to_term( + s: Optional[str], default: Optional[rdflib.term.Identifier] = None +) -> Optional[rdflib.term.Identifier]: + """ + Creates and returns an Identifier of type corresponding + to the pattern of the given positional argument string `s`: + + '' returns the `default` keyword argument value or `None` + + '' returns `URIRef(s)` (i.e. without angle brackets) + + '"s"' returns `Literal(s)` (i.e. without doublequotes) + + '_s' returns `BNode(s)` (i.e. without leading underscore) + + """ + if not s: + return default + elif s.startswith("<") and s.endswith(">"): + return rdflib.term.URIRef(s[1:-1]) + elif s.startswith('"') and s.endswith('"'): + return rdflib.term.Literal(s[1:-1]) + elif s.startswith("_"): + return rdflib.term.BNode(s) + else: + msg = "Unrecognised term syntax: '%s'" % s + raise Exception(msg) + + +def from_n3( + s: str, + default: Optional[str] = None, + backend: Optional[str] = None, + nsm: Optional[rdflib.namespace.NamespaceManager] = None, +) -> Optional[Union[rdflib.term.Node, str]]: + r'''Creates the Identifier corresponding to the given n3 string. + + ```python + >>> from rdflib.term import URIRef, Literal + >>> from rdflib.namespace import NamespaceManager + >>> from_n3('') == URIRef('http://ex.com/foo') + True + >>> from_n3('"foo"@de') == Literal('foo', lang='de') + True + >>> from_n3('"""multi\nline\nstring"""@en') == Literal( + ... 'multi\nline\nstring', lang='en') + True + >>> from_n3('42') == Literal(42) + True + >>> from_n3(Literal(42).n3()) == Literal(42) + True + >>> from_n3('"42"^^xsd:integer') == Literal(42) + True + >>> from rdflib import RDFS + >>> from_n3('rdfs:label') == RDFS['label'] + True + >>> nsm = NamespaceManager(rdflib.graph.Graph()) + >>> nsm.bind('dbpedia', 'http://dbpedia.org/resource/') + >>> berlin = URIRef('http://dbpedia.org/resource/Berlin') + >>> from_n3('dbpedia:Berlin', nsm=nsm) == berlin + True + + ``` + ''' + if not s: + return default + if s.startswith("<"): + # Hack: this should correctly handle strings with either native unicode + # characters, or \u1234 unicode escapes. + return rdflib.term.URIRef( + s[1:-1].encode("raw-unicode-escape").decode("unicode-escape") + ) + elif s.startswith('"'): + if s.startswith('"""'): + quotes = '"""' + else: + quotes = '"' + value, rest = s.rsplit(quotes, 1) + value = value[len(quotes) :] # strip leading quotes + datatype = None + language = None + + # as a given datatype overrules lang-tag check for it first + dtoffset = rest.rfind("^^") + if dtoffset >= 0: + # found a datatype + # datatype has to come after lang-tag so ignore everything before + # see: http://www.w3.org/TR/2011/WD-turtle-20110809/ + # #prod-turtle2-RDFLiteral + datatype = from_n3(rest[dtoffset + 2 :], default, backend, nsm) + else: + if rest.startswith("@"): + language = rest[1:] # strip leading at sign + + value = value.replace(r"\"", '"') + # unicode-escape interprets \xhh as an escape sequence, + # but n3 does not define it as such. + value = value.replace(r"\x", r"\\x") + # Hack: this should correctly handle strings with either native unicode + # characters, or \u1234 unicode escapes. + value = value.encode("raw-unicode-escape").decode("unicode-escape") + # type error: Argument 3 to "Literal" has incompatible type "Union[Node, str, None]"; expected "Optional[str]" + return rdflib.term.Literal(value, language, datatype) # type: ignore[arg-type] + elif s == "true" or s == "false": + return rdflib.term.Literal(s == "true") + elif ( + s.lower() + .replace(".", "", 1) + .replace("-", "", 1) + .replace("e", "", 1) + .isnumeric() + ): + if "e" in s.lower(): + return rdflib.term.Literal(s, datatype=rdflib.namespace.XSD.double) + if "." in s: + return rdflib.term.Literal(float(s), datatype=rdflib.namespace.XSD.decimal) + return rdflib.term.Literal(int(s), datatype=rdflib.namespace.XSD.integer) + + elif s.startswith("{"): + identifier = from_n3(s[1:-1]) + # type error: Argument 1 to "QuotedGraph" has incompatible type "Optional[str]"; expected "Union[Store, str]" + # type error: Argument 2 to "QuotedGraph" has incompatible type "Union[Node, str, None]"; expected "Union[IdentifiedNode, str, None]" + return rdflib.graph.QuotedGraph(backend, identifier) # type: ignore[arg-type] + elif s.startswith("["): + identifier = from_n3(s[1:-1]) + # type error: Argument 1 to "Graph" has incompatible type "Optional[str]"; expected "Union[Store, str]" + # type error: Argument 2 to "Graph" has incompatible type "Union[Node, str, None]"; expected "Union[IdentifiedNode, str, None]" + return rdflib.graph.Graph(backend, identifier) # type: ignore[arg-type] + elif s.startswith("_:"): + return rdflib.term.BNode(s[2:]) + elif ":" in s: + if nsm is None: + # instantiate default NamespaceManager and rely on its defaults + nsm = rdflib.namespace.NamespaceManager(rdflib.graph.Graph()) + prefix, last_part = s.split(":", 1) + ns = dict(nsm.namespaces())[prefix] + return rdflib.namespace.Namespace(ns)[last_part] + else: + return rdflib.term.BNode(s) + + +def date_time(t=None, local_time_zone=False): + """http://www.w3.org/TR/NOTE-datetime ex: 1997-07-16T19:20:30Z + + ```python + >>> date_time(1126482850) + '2005-09-11T23:54:10Z' + + @@ this will change depending on where it is run + #>>> date_time(1126482850, local_time_zone=True) + #'2005-09-11T19:54:10-04:00' + + >>> date_time(1) + '1970-01-01T00:00:01Z' + + >>> date_time(0) + '1970-01-01T00:00:00Z' + + ``` + """ + if t is None: + t = time() + + if local_time_zone: + time_tuple = localtime(t) + if time_tuple[8]: + tz_mins = altzone // 60 + else: + tz_mins = timezone // 60 + tzd = "-%02d:%02d" % (tz_mins // 60, tz_mins % 60) + else: + time_tuple = gmtime(t) + tzd = "Z" + + year, month, day, hh, mm, ss, wd, y, z = time_tuple + s = "%0004d-%02d-%02dT%02d:%02d:%02d%s" % (year, month, day, hh, mm, ss, tzd) + return s + + +def parse_date_time(val: str) -> int: + """always returns seconds in UTC + + ```python + # tests are written like this to make any errors easier to understand + >>> parse_date_time('2005-09-11T23:54:10Z') - 1126482850.0 + 0.0 + + >>> parse_date_time('2005-09-11T16:54:10-07:00') - 1126482850.0 + 0.0 + + >>> parse_date_time('1970-01-01T00:00:01Z') - 1.0 + 0.0 + + >>> parse_date_time('1970-01-01T00:00:00Z') - 0.0 + 0.0 + >>> parse_date_time("2005-09-05T10:42:00") - 1125916920.0 + 0.0 + + ``` + """ + + if "T" not in val: + val += "T00:00:00Z" + + ymd, time = val.split("T") + hms, tz_str = time[0:8], time[8:] + + if not tz_str or tz_str == "Z": + time = time[:-1] + tz_offset = 0 + else: + signed_hrs = int(tz_str[:3]) + mins = int(tz_str[4:6]) + secs = (sign(signed_hrs) * mins + signed_hrs * 60) * 60 + tz_offset = -secs + + year, month, day = ymd.split("-") + hour, minute, second = hms.split(":") + + t = timegm( + (int(year), int(month), int(day), int(hour), int(minute), int(second), 0, 0, 0) + ) + t = t + tz_offset + return t + + +def guess_format(fpath: str, fmap: Optional[Dict[str, str]] = None) -> Optional[str]: + """ + Guess RDF serialization based on file suffix. Uses + `SUFFIX_FORMAT_MAP` unless `fmap` is provided. + + Example: + ```python + >>> guess_format('path/to/file.rdf') + 'xml' + >>> guess_format('path/to/file.owl') + 'xml' + >>> guess_format('path/to/file.ttl') + 'turtle' + >>> guess_format('path/to/file.json') + 'json-ld' + >>> guess_format('path/to/file.xhtml') + 'rdfa' + >>> guess_format('path/to/file.svg') + 'rdfa' + >>> guess_format('path/to/file.xhtml', {'xhtml': 'grddl'}) + 'grddl' + + ``` + + This also works with just the suffixes, with or without leading dot, and + regardless of letter case: + + ```python + >>> guess_format('.rdf') + 'xml' + >>> guess_format('rdf') + 'xml' + >>> guess_format('RDF') + 'xml' + + ``` + """ + fmap = fmap or SUFFIX_FORMAT_MAP + return fmap.get(_get_ext(fpath)) or fmap.get(fpath.lower()) + + +def _get_ext(fpath: str, lower: bool = True) -> str: + """ + Gets the file extension from a file(path); stripped of leading '.' and in + lower case. + + Example: + ```python + >>> _get_ext("path/to/file.txt") + 'txt' + >>> _get_ext("OTHER.PDF") + 'pdf' + >>> _get_ext("noext") + '' + >>> _get_ext(".rdf") + 'rdf' + + ``` + """ + ext = splitext(fpath)[-1] + if ext == "" and fpath.startswith("."): + ext = fpath + if lower: + ext = ext.lower() + if ext.startswith("."): + ext = ext[1:] + return ext + + +def find_roots( + graph: Graph, + prop: rdflib.term.URIRef, + roots: Optional[Set[rdflib.term.Node]] = None, +) -> Set[rdflib.term.Node]: + """Find the roots in some sort of transitive hierarchy. + + find_roots(graph, rdflib.RDFS.subClassOf) + will return a set of all roots of the sub-class hierarchy + + Assumes triple of the form (child, prop, parent), i.e. the direction of + `RDFS.subClassOf` or `SKOS.broader` + """ + + non_roots: Set[rdflib.term.Node] = set() + if roots is None: + roots = set() + for x, y in graph.subject_objects(prop): + non_roots.add(x) + if x in roots: + roots.remove(x) + if y not in non_roots: + roots.add(y) + return roots + + +def get_tree( + graph: Graph, + root: rdflib.term.Node, + prop: rdflib.term.URIRef, + mapper: Callable[[rdflib.term.Node], rdflib.term.Node] = lambda x: x, + sortkey: Optional[Callable[[Any], Any]] = None, + done: Optional[Set[rdflib.term.Node]] = None, + dir: str = "down", +) -> Optional[Tuple[rdflib.term.Node, List[Any]]]: + """ + Return a nested list/tuple structure representing the tree + built by the transitive property given, starting from the root given + + i.e. + + ```python + get_tree( + graph, + rdflib.URIRef("http://xmlns.com/foaf/0.1/Person"), + rdflib.RDFS.subClassOf, + ) + ``` + + will return the structure for the subClassTree below person. + + dir='down' assumes triple of the form (child, prop, parent), + i.e. the direction of RDFS.subClassOf or SKOS.broader + Any other dir traverses in the other direction + """ + + if done is None: + done = set() + if root in done: + # type error: Return value expected + return # type: ignore[return-value] + done.add(root) + tree = [] + + branches: Iterator[rdflib.term.Node] + if dir == "down": + branches = graph.subjects(prop, root) + else: + branches = graph.objects(root, prop) + + for branch in branches: + t = get_tree(graph, branch, prop, mapper, sortkey, done, dir) + if t: + tree.append(t) + + return (mapper(root), sorted(tree, key=sortkey)) + + +@overload +def _coalesce(*args: Optional[_AnyT], default: _AnyT) -> _AnyT: ... + + +@overload +def _coalesce( + *args: Optional[_AnyT], default: Optional[_AnyT] = ... +) -> Optional[_AnyT]: ... + + +def _coalesce( + *args: Optional[_AnyT], default: Optional[_AnyT] = None +) -> Optional[_AnyT]: + """ + This is a null coalescing function, it will return the first non-`None` + argument passed to it, otherwise it will return `default` which is `None` + by default. + + For more info regarding the rationale of this function see deferred + [PEP 505](https://peps.python.org/pep-0505/). + + Args: + *args: Values to consider as candidates to return, the first arg that + is not `None` will be returned. If no argument is passed this function + will return None. + default: The default value to return if none of the args are not `None`. + + Returns: + The first `args` that is not `None`, otherwise the value of + `default` if there are no `args` or if all `args` are `None`. + """ + for arg in args: + if arg is not None: + return arg + return default + + +_RFC3986_SUBDELIMS = "!$&'()*+,;=" +""" +`sub-delims` production from +[RFC 3986, section 2.2](https://www.rfc-editor.org/rfc/rfc3986.html#section-2.2). +""" + +_RFC3986_PCHAR_NU = "%" + _RFC3986_SUBDELIMS + ":@" +""" +The non-unreserved characters in the `pchar` production from RFC 3986. +""" + +_QUERY_SAFE_CHARS = _RFC3986_PCHAR_NU + "/?" +""" +The non-unreserved characters that are safe to use in in the query and fragment +components. + +``` +pchar = unreserved / pct-encoded / sub-delims / ":" / "@" query += *( pchar / "/" / "?" ) fragment = *( pchar / "/" / "?" ) +``` +""" + +_USERNAME_SAFE_CHARS = _RFC3986_SUBDELIMS + "%" +""" +The non-unreserved characters that are safe to use in the username and password +components. + +``` +userinfo = *( unreserved / pct-encoded / sub-delims / ":" ) +``` + +":" is excluded as this is only used for the username and password components, +and they are treated separately. +""" + +_PATH_SAFE_CHARS = _RFC3986_PCHAR_NU + "/" +""" +The non-unreserved characters that are safe to use in the path component. + +This is based on various path-related productions from RFC 3986. +""" + + +def _iri2uri(iri: str) -> str: + """ + Prior art: + + - [iri_to_uri from Werkzeug](https://github.com/pallets/werkzeug/blob/92c6380248c7272ee668e1f8bbd80447027ccce2/src/werkzeug/urls.py#L926-L931) + + ```python + >>> _iri2uri("https://dbpedia.org/resource/Almería") + 'https://dbpedia.org/resource/Almer%C3%ADa' + + ``` + """ + # https://datatracker.ietf.org/doc/html/rfc3986 + # https://datatracker.ietf.org/doc/html/rfc3305 + + parts = urlsplit(iri) + (scheme, netloc, path, query, fragment) = parts + + # Just support http/https, otherwise return the iri unaltered + if scheme not in ["http", "https"]: + return iri + + path = quote(path, safe=_PATH_SAFE_CHARS) + query = quote(query, safe=_QUERY_SAFE_CHARS) + fragment = quote(fragment, safe=_QUERY_SAFE_CHARS) + + if parts.hostname: + netloc = parts.hostname.encode("idna").decode("ascii") + else: + netloc = "" + + if ":" in netloc: + # Quote IPv6 addresses + netloc = f"[{netloc}]" + + if parts.port: + netloc = f"{netloc}:{parts.port}" + + if parts.username: + auth = quote(parts.username, safe=_USERNAME_SAFE_CHARS) + if parts.password: + pass_quoted = quote(parts.password, safe=_USERNAME_SAFE_CHARS) + auth = f"{auth}:{pass_quoted}" + netloc = f"{auth}@{netloc}" + + uri = urlunsplit((scheme, netloc, path, query, fragment)) + + if iri.endswith("#") and not uri.endswith("#"): + uri += "#" + + return uri diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rdflib/void.py b/TTS/Kokoro/.venv/Lib/site-packages/rdflib/void.py new file mode 100644 index 0000000000000000000000000000000000000000..97b705d8a1385d77dd85ac2fa0640424361829be --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rdflib/void.py @@ -0,0 +1,136 @@ +from __future__ import annotations + +import collections +from typing import DefaultDict, Dict, Optional, Set + +from rdflib.graph import Graph, _ObjectType, _PredicateType, _SubjectType +from rdflib.namespace import RDF, VOID +from rdflib.term import IdentifiedNode, Literal, URIRef + + +def generateVoID( # noqa: N802 + g: Graph, + dataset: Optional[IdentifiedNode] = None, + res: Optional[Graph] = None, + distinctForPartitions: bool = True, # noqa: N803 +): + """Returns a new graph with a VoID description of the passed dataset + + For more info on Vocabulary of Interlinked Datasets (VoID), see: + http://vocab.deri.ie/void + + This only makes two passes through the triples (once to detect the types + of things) + + The tradeoff is that lots of temporary structures are built up in memory + meaning lots of memory may be consumed :) + I imagine at least a few copies of your original graph. + + the distinctForPartitions parameter controls whether + distinctSubjects/objects are tracked for each class/propertyPartition + this requires more memory again + """ + + typeMap: Dict[_SubjectType, Set[_SubjectType]] = ( # noqa: N806 + collections.defaultdict(set) + ) + classes: Dict[_ObjectType, Set[_SubjectType]] = collections.defaultdict(set) + for e, c in g.subject_objects(RDF.type): + classes[c].add(e) + typeMap[e].add(c) + + triples = 0 + subjects: Set[_SubjectType] = set() + objects: Set[_ObjectType] = set() + properties: Set[_PredicateType] = set() + classCount: DefaultDict[_SubjectType, int] = collections.defaultdict( # noqa: N806 + int + ) + propCount: DefaultDict[_PredicateType, int] = collections.defaultdict( # noqa: N806 + int + ) + + classProps = collections.defaultdict(set) # noqa: N806 + classObjects = collections.defaultdict(set) # noqa: N806 + propSubjects = collections.defaultdict(set) # noqa: N806 + propObjects = collections.defaultdict(set) # noqa: N806 + + for s, p, o in g: + triples += 1 + subjects.add(s) + properties.add(p) + objects.add(o) + + # class partitions + if s in typeMap: + for c in typeMap[s]: + classCount[c] += 1 + if distinctForPartitions: + classObjects[c].add(o) + classProps[c].add(p) + + # property partitions + propCount[p] += 1 + if distinctForPartitions: + propObjects[p].add(o) + propSubjects[p].add(s) + + if not dataset: + dataset = URIRef("http://example.org/Dataset") + + if not res: + res = Graph() + + res.add((dataset, RDF.type, VOID.Dataset)) + + # basic stats + res.add((dataset, VOID.triples, Literal(triples))) + res.add((dataset, VOID.classes, Literal(len(classes)))) + + res.add((dataset, VOID.distinctObjects, Literal(len(objects)))) + res.add((dataset, VOID.distinctSubjects, Literal(len(subjects)))) + res.add((dataset, VOID.properties, Literal(len(properties)))) + + for i, c in enumerate(classes): + part = URIRef(dataset + "_class%d" % i) + res.add((dataset, VOID.classPartition, part)) + res.add((part, RDF.type, VOID.Dataset)) + + res.add((part, VOID.triples, Literal(classCount[c]))) + res.add((part, VOID.classes, Literal(1))) + + res.add((part, VOID["class"], c)) + + res.add((part, VOID.entities, Literal(len(classes[c])))) + res.add((part, VOID.distinctSubjects, Literal(len(classes[c])))) + + if distinctForPartitions: + res.add((part, VOID.properties, Literal(len(classProps[c])))) + res.add((part, VOID.distinctObjects, Literal(len(classObjects[c])))) + + for i, p in enumerate(properties): + part = URIRef(dataset + "_property%d" % i) + res.add((dataset, VOID.propertyPartition, part)) + res.add((part, RDF.type, VOID.Dataset)) + + res.add((part, VOID.triples, Literal(propCount[p]))) + res.add((part, VOID.properties, Literal(1))) + + res.add((part, VOID.property, p)) + + if distinctForPartitions: + entities = 0 + propClasses = set() # noqa: N806 + for s in propSubjects[p]: + if s in typeMap: + entities += 1 + for c in typeMap[s]: + propClasses.add(c) + + res.add((part, VOID.entities, Literal(entities))) + res.add((part, VOID.classes, Literal(len(propClasses)))) + + res.add((part, VOID.distinctSubjects, Literal(len(propSubjects[p])))) + res.add((part, VOID.distinctObjects, Literal(len(propObjects[p])))) + + return res, dataset diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rdflib/xsd_datetime.py b/TTS/Kokoro/.venv/Lib/site-packages/rdflib/xsd_datetime.py new file mode 100644 index 0000000000000000000000000000000000000000..e7abfd1d0fa721114fa2602418d87f720de110be --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rdflib/xsd_datetime.py @@ -0,0 +1,598 @@ +""" +Large parts of this module are taken from the `isodate` package. +https://pypi.org/project/isodate/ +Modifications are made to isodate features to allow compatibility with +XSD dates and durations that are not necessarily valid ISO8601 strings. + +Copyright (c) 2024, Ashley Sommer, and RDFLib contributors +Copyright (c) 2021, Hugo van Kemenade and contributors +Copyright (c) 2009-2018, Gerhard Weis and contributors +Copyright (c) 2009, Gerhard Weis +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 the 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 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. +""" + +from __future__ import annotations + +import re +import sys +from datetime import date, datetime, time, timedelta +from decimal import ROUND_FLOOR, Decimal +from typing import List, Tuple, Union, cast + +if sys.version_info[:3] < (3, 11, 0): + from isodate import parse_date, parse_datetime, parse_time +else: + # On python 3.11, use the built-in parsers + parse_date = date.fromisoformat + parse_datetime = datetime.fromisoformat + parse_time = time.fromisoformat + + +def fquotmod( + val: Decimal, low: Union[Decimal, int], high: Union[Decimal, int] +) -> Tuple[int, Decimal]: + """A divmod function with boundaries.""" + # assumes that all the maths is done with Decimals. + # divmod for Decimal uses truncate instead of floor as builtin + # divmod, so we have to do it manually here. + a: Decimal = val - low + b: Union[Decimal, int] = high - low + div: Decimal = (a / b).to_integral(ROUND_FLOOR) + mod: Decimal = a - div * b + # if we were not using Decimal, it would look like this. + # div, mod = divmod(val - low, high - low) + mod += low + return int(div), mod + + +def max_days_in_month(year: int, month: int) -> int: + """ + Determines the number of days of a specific month in a specific year. + """ + if month in (1, 3, 5, 7, 8, 10, 12): + return 31 + if month in (4, 6, 9, 11): + return 30 + if month < 1 or month > 12: + raise ValueError("Month must be in 1..12") + # Month is February + if ((year % 400) == 0) or ((year % 100) != 0) and ((year % 4) == 0): + return 29 + return 28 + + +class Duration: + """A class which represents a duration. + + The difference to datetime.timedelta is, that this class handles also + differences given in years and months. + A Duration treats differences given in year, months separately from all + other components. + + A Duration can be used almost like any timedelta object, however there + are some restrictions: + - It is not really possible to compare Durations, because it is unclear, + whether a duration of 1 year is bigger than 365 days or not. + - Equality is only tested between the two (year, month vs. timedelta) + basic components. + + A Duration can also be converted into a datetime object, but this requires + a start date or an end date. + + The algorithm to add a duration to a date is defined at + http://www.w3.org/TR/xmlschema-2/#adding-durations-to-dateTimes + """ + + def __init__( + self, + days: float = 0, + seconds: float = 0, + microseconds: float = 0, + milliseconds: float = 0, + minutes: float = 0, + hours: float = 0, + weeks: float = 0, + months: Union[Decimal, float, int, str] = 0, + years: Union[Decimal, float, int, str] = 0, + ): + """ + Initialise this Duration instance with the given parameters. + """ + if not isinstance(months, Decimal): + months = Decimal(str(months)) + if not isinstance(years, Decimal): + years = Decimal(str(years)) + new_years, months = fquotmod(months, 0, 12) + self.months = months + self.years = Decimal(years + new_years) + self.tdelta = timedelta( + days, seconds, microseconds, milliseconds, minutes, hours, weeks + ) + if self.years < 0 and self.tdelta.days < 0: + raise ValueError("Duration cannot have negative years and negative days") + + def __getstate__(self): + return self.__dict__ + + def __setstate__(self, state): + self.__dict__.update(state) + + def __getattr__(self, name): + """ + Provide direct access to attributes of included timedelta instance. + """ + return getattr(self.tdelta, name) + + def __str__(self): + """ + Return a string representation of this duration similar to timedelta. + """ + params = [] + if self.years: + params.append("%d years" % self.years) + if self.months: + fmt = "%d months" + if self.months <= 1: + fmt = "%d month" + params.append(fmt % self.months) + params.append(str(self.tdelta)) + return ", ".join(params) + + def __repr__(self): + """ + Return a string suitable for repr(x) calls. + """ + return "%s.%s(%d, %d, %d, years=%s, months=%s)" % ( + self.__class__.__module__, + self.__class__.__name__, + self.tdelta.days, + self.tdelta.seconds, + self.tdelta.microseconds, + str(self.years), + str(self.months), + ) + + def __hash__(self): + """ + Return a hash of this instance so that it can be used in, for + example, dicts and sets. + """ + return hash((self.tdelta, self.months, self.years)) + + def __neg__(self): + """A simple unary minus. + + Returns a new Duration instance with all it's negated. + """ + negduration = Duration(years=-self.years, months=-self.months) + negduration.tdelta = -self.tdelta + return negduration + + def __add__(self, other: Union[Duration, timedelta, date, datetime]): + """ + Durations can be added with Duration, timedelta, date and datetime + objects. + """ + if isinstance(other, Duration): + newduration = Duration( + years=self.years + other.years, months=self.months + other.months + ) + newduration.tdelta = self.tdelta + other.tdelta + return newduration + elif isinstance(other, timedelta): + newduration = Duration(years=self.years, months=self.months) + newduration.tdelta = self.tdelta + other + return newduration + try: + # try anything that looks like a date or datetime + # 'other' has attributes year, month, day + # and relies on 'timedelta + other' being implemented + if not (float(self.years).is_integer() and float(self.months).is_integer()): + raise ValueError( + "fractional years or months not supported for date calculations" + ) + newmonth: Decimal = Decimal(other.month) + self.months + carry, newmonth = fquotmod(newmonth, 1, 13) + newyear: int = other.year + int(self.years) + carry + maxdays: int = max_days_in_month(newyear, int(newmonth)) + newday: Union[int, float] + if other.day > maxdays: + newday = maxdays + else: + newday = other.day + newdt = other.replace(year=newyear, month=int(newmonth), day=newday) + # does a timedelta + date/datetime + return self.tdelta + newdt + except AttributeError: + # other probably was not a date/datetime compatible object + pass + # we have tried everything .... return a NotImplemented + return NotImplemented + + __radd__ = __add__ + + def __mul__(self, other): + if isinstance(other, int): + newduration = Duration(years=self.years * other, months=self.months * other) + newduration.tdelta = self.tdelta * other + return newduration + return NotImplemented + + __rmul__ = __mul__ + + def __sub__(self, other: Union[Duration, timedelta]): + """ + It is possible to subtract Duration and timedelta objects from Duration + objects. + """ + if isinstance(other, Duration): + newduration = Duration( + years=self.years - other.years, months=self.months - other.months + ) + newduration.tdelta = self.tdelta - other.tdelta + return newduration + try: + # do maths with our timedelta object .... + newduration = Duration(years=self.years, months=self.months) + newduration.tdelta = self.tdelta - other + return newduration + except TypeError: + # looks like timedelta - other is not implemented + pass + return NotImplemented + + def __rsub__(self, other: Union[timedelta, date, datetime]): + """ + It is possible to subtract Duration objects from date, datetime and + timedelta objects. + """ + # TODO: there is some weird behaviour in date - timedelta ... + # if timedelta has seconds or microseconds set, then + # date - timedelta != date + (-timedelta) + # for now we follow this behaviour to avoid surprises when mixing + # timedeltas with Durations, but in case this ever changes in + # the stdlib we can just do: + # return -self + other + # instead of all the current code + + if isinstance(other, timedelta): + tmpdur = Duration() + tmpdur.tdelta = other + return tmpdur - self + try: + # check if other behaves like a date/datetime object + # does it have year, month, day and replace? + if not (float(self.years).is_integer() and float(self.months).is_integer()): + raise ValueError( + "fractional years or months not supported for date calculations" + ) + newmonth: Decimal = Decimal(other.month) - self.months + carry, newmonth = fquotmod(newmonth, 1, 13) + newyear: int = other.year - int(self.years) + carry + maxdays: int = max_days_in_month(newyear, int(newmonth)) + newday: Union[int, float] + if other.day > maxdays: + newday = maxdays + else: + newday = other.day + newdt = other.replace(year=newyear, month=int(newmonth), day=newday) + return newdt - self.tdelta + except AttributeError: + # other probably was not compatible with data/datetime + pass + return NotImplemented + + def __eq__(self, other): + """ + If the years, month part and the timedelta part are both equal, then + the two Durations are considered equal. + """ + if isinstance(other, Duration): + if (self.years * 12 + self.months) == ( + other.years * 12 + other.months + ) and self.tdelta == other.tdelta: + return True + return False + # check if other con be compared against timedelta object + # will raise an AssertionError when optimisation is off + if self.years == 0 and self.months == 0: + return self.tdelta == other + return False + + def __ne__(self, other): + """ + If the years, month part or the timedelta part is not equal, then + the two Durations are considered not equal. + """ + if isinstance(other, Duration): + if (self.years * 12 + self.months) != ( + other.years * 12 + other.months + ) or self.tdelta != other.tdelta: + return True + return False + # check if other can be compared against timedelta object + # will raise an AssertionError when optimisation is off + if self.years == 0 and self.months == 0: + return self.tdelta != other + return True + + def totimedelta(self, start=None, end=None): + """Convert this duration into a timedelta object. + + This method requires a start datetime or end datetime, but raises + an exception if both are given. + """ + if start is None and end is None: + raise ValueError("start or end required") + if start is not None and end is not None: + raise ValueError("only start or end allowed") + if start is not None: + return (start + self) - start + return end - (end - self) + + +ISO8601_PERIOD_REGEX = re.compile( + r"^(?P[+-])?" + r"P(?!\b)" + r"(?P[0-9]+([,.][0-9]+)?Y)?" + r"(?P[0-9]+([,.][0-9]+)?M)?" + r"(?P[0-9]+([,.][0-9]+)?W)?" + r"(?P[0-9]+([,.][0-9]+)?D)?" + r"((?PT)(?P[0-9]+([,.][0-9]+)?H)?" + r"(?P[0-9]+([,.][0-9]+)?M)?" + r"(?P[0-9]+([,.][0-9]+)?S)?)?$" +) +# regular expression to parse ISO duration strings. + + +def parse_xsd_duration( + dur_string: str, as_timedelta_if_possible: bool = True +) -> Union[Duration, timedelta]: + """Parses an ISO 8601 durations into datetime.timedelta or Duration objects. + + If the ISO date string does not contain years or months, a timedelta + instance is returned, else a Duration instance is returned. + + The following duration formats are supported: + + -`PnnW` duration in weeks + -`PnnYnnMnnDTnnHnnMnnS` complete duration specification + -`PYYYYMMDDThhmmss` basic alternative complete date format + -`PYYYY-MM-DDThh:mm:ss` extended alternative complete date format + -`PYYYYDDDThhmmss` basic alternative ordinal date format + -`PYYYY-DDDThh:mm:ss` extended alternative ordinal date format + + The '-' is optional. + + Limitations: ISO standard defines some restrictions about where to use + fractional numbers and which component and format combinations are + allowed. This parser implementation ignores all those restrictions and + returns something when it is able to find all necessary components. + In detail: + - it does not check, whether only the last component has fractions. + - it allows weeks specified with all other combinations + The alternative format does not support durations with years, months or + days set to 0. + """ + if not isinstance(dur_string, str): + raise TypeError(f"Expecting a string: {dur_string!r}") + match = ISO8601_PERIOD_REGEX.match(dur_string) + if not match: + # try alternative format: + if dur_string.startswith("P"): + durdt = parse_datetime(dur_string[1:]) + if as_timedelta_if_possible and durdt.year == 0 and durdt.month == 0: + # FIXME: currently not possible in alternative format + # create timedelta + return timedelta( + days=durdt.day, + seconds=durdt.second, + microseconds=durdt.microsecond, + minutes=durdt.minute, + hours=durdt.hour, + ) + else: + # create Duration + return Duration( + days=durdt.day, + seconds=durdt.second, + microseconds=durdt.microsecond, + minutes=durdt.minute, + hours=durdt.hour, + months=durdt.month, + years=durdt.year, + ) + raise ValueError("Unable to parse duration string " + dur_string) + groups = match.groupdict() + for key, val in groups.items(): + if key not in ("separator", "sign"): + if val is None: + groups[key] = "0n" + # print groups[key] + if key in ("years", "months"): + groups[key] = Decimal(groups[key][:-1].replace(",", ".")) + else: + # these values are passed into a timedelta object, + # which works with floats. + groups[key] = float(groups[key][:-1].replace(",", ".")) + ret: Union[Duration, timedelta] + if as_timedelta_if_possible and groups["years"] == 0 and groups["months"] == 0: + ret = timedelta( + days=groups["days"], # type: ignore[arg-type] + hours=groups["hours"], # type: ignore[arg-type] + minutes=groups["minutes"], # type: ignore[arg-type] + seconds=groups["seconds"], # type: ignore[arg-type] + weeks=groups["weeks"], # type: ignore[arg-type] + ) + if groups["sign"] == "-": + ret = timedelta(0) - ret + else: + ret = Duration( + years=cast(Decimal, groups["years"]), + months=cast(Decimal, groups["months"]), + days=groups["days"], # type: ignore[arg-type] + hours=groups["hours"], # type: ignore[arg-type] + minutes=groups["minutes"], # type: ignore[arg-type] + seconds=groups["seconds"], # type: ignore[arg-type] + weeks=groups["weeks"], # type: ignore[arg-type] + ) + if groups["sign"] == "-": + ret = Duration(0) - ret + + return ret + + +def duration_isoformat(tdt: Union[Duration, timedelta], in_weeks: bool = False) -> str: + if not in_weeks: + ret: List[str] = [] + minus = False + has_year_or_month = False + if isinstance(tdt, Duration): + if tdt.years == 0 and tdt.months == 0: + pass # don't do anything, we have no year or month + else: + has_year_or_month = True + months = tdt.years * 12 + tdt.months + if months < 0: + minus = True + months = abs(months) + # We can use divmod instead of fquotmod here because its month_count + # not month_index, and we don't have any negative months at this point. + new_years, new_months = divmod(months, 12) + if new_years: + ret.append(str(new_years) + "Y") + if tdt.months: + ret.append(str(new_months) + "M") + tdt = tdt.tdelta + usecs: int = ((tdt.days * 86400) + tdt.seconds) * 1000000 + tdt.microseconds + if usecs < 0: + if minus: + raise ValueError( + "Duration cannot have negative years and negative days" + ) + elif has_year_or_month: + raise ValueError( + "Duration cannot have positive years and months but negative days" + ) + minus = True + usecs = abs(usecs) + if usecs == 0: + # No delta parts other than years and months + pass + else: + seconds, usecs = divmod(usecs, 1000000) + minutes, seconds = divmod(seconds, 60) + hours, minutes = divmod(minutes, 60) + days, hours = divmod(hours, 24) + if days: + ret.append(str(days) + "D") + if hours or minutes or seconds or usecs: + ret.append("T") + if hours: + ret.append(str(hours) + "H") + if minutes: + ret.append(str(minutes) + "M") + if seconds or usecs: + if usecs: + ret.append(("%d.%06d" % (seconds, usecs)).rstrip("0")) + else: + ret.append("%d" % seconds) + ret.append("S") + if ret: + return ("-P" if minus else "P") + "".join(ret) + else: + # at least one component has to be there. + return "-P0D" if minus else "P0D" + else: + if tdt.days < 0: + return f"-P{abs(tdt.days // 7)}W" + return f"P{tdt.days // 7}W" + + +def xsd_datetime_isoformat(dt: datetime): + if dt.microsecond == 0: + no_tz_str = dt.strftime("%Y-%m-%dT%H:%M:%S") + else: + no_tz_str = dt.strftime("%Y-%m-%dT%H:%M:%S.%f") + if dt.tzinfo is None: + return no_tz_str + else: + offset_string = dt.strftime("%z") + if offset_string == "+0000": + return no_tz_str + "Z" + first_char = offset_string[0] + if first_char == "+" or first_char == "-": + offset_string = offset_string[1:] + sign = first_char + else: + sign = "+" + tz_part = sign + offset_string[:2] + ":" + offset_string[2:] + return no_tz_str + tz_part + + +def parse_xsd_date(date_string: str): + """ + XSD Dates have more features than ISO8601 dates, specifically + XSD allows timezones on dates, that must be stripped off. + Also, XSD requires dashed separators, while ISO8601 is optional. + RDFLib test suite has some date strings with times, the times are expected + to be dropped during parsing. + """ + if date_string.endswith("Z") or date_string.endswith("z"): + date_string = date_string[:-1] + if date_string.startswith("-"): + date_string = date_string[1:] + minus = True + else: + minus = False + if "T" in date_string: + # RDFLib test suite has some strange date strings, with times. + # this has the side effect of also dropping the + # TZ part, that is not wanted anyway for a date. + date_string = date_string.split("T")[0] + else: + has_plus = date_string.rfind("+") + if has_plus > 0: + # Drop the +07:00 timezone part + date_string = date_string[:has_plus] + else: + split_parts = date_string.rsplit("-", 1) + if len(split_parts) > 1 and ":" in split_parts[-1]: + # Drop the -09:00 timezone part + date_string = split_parts[0] + if "-" not in date_string: + raise ValueError("XSD Date string must contain at least two dashes") + return parse_date(date_string if not minus else ("-" + date_string)) + + +# Parse XSD Datetime is the same as ISO8601 Datetime +# It uses datetime.fromisoformat for python 3.11 and above +# or isodate.parse_datetime for older versions +# parse_xsd_datetime = parse_datetime + +# Parse XSD Time is the same as ISO8601 Time +# It uses time.fromisoformat for python 3.11 and above +# or isodate.parse_time for older versions +# parse_xsd_time = parse_time diff --git a/TTS/Kokoro/.venv/Lib/site-packages/referencing-0.37.0.dist-info/INSTALLER b/TTS/Kokoro/.venv/Lib/site-packages/referencing-0.37.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/referencing-0.37.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/TTS/Kokoro/.venv/Lib/site-packages/referencing-0.37.0.dist-info/METADATA b/TTS/Kokoro/.venv/Lib/site-packages/referencing-0.37.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..9a6abbc83beb35659b354df6e9951043c6b10b42 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/referencing-0.37.0.dist-info/METADATA @@ -0,0 +1,64 @@ +Metadata-Version: 2.4 +Name: referencing +Version: 0.37.0 +Summary: JSON Referencing + Python +Project-URL: Documentation, https://referencing.readthedocs.io/ +Project-URL: Homepage, https://github.com/python-jsonschema/referencing +Project-URL: Issues, https://github.com/python-jsonschema/referencing/issues/ +Project-URL: Funding, https://github.com/sponsors/Julian +Project-URL: Tidelift, https://tidelift.com/subscription/pkg/pypi-referencing?utm_source=pypi-referencing&utm_medium=referral&utm_campaign=pypi-link +Project-URL: Changelog, https://referencing.readthedocs.io/en/stable/changes/ +Project-URL: Source, https://github.com/python-jsonschema/referencing +Author-email: Julian Berman +License-Expression: MIT +License-File: COPYING +Keywords: asyncapi,json,jsonschema,openapi,referencing +Classifier: Development Status :: 3 - Alpha +Classifier: Intended Audience :: Developers +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: File Formats :: JSON +Classifier: Topic :: File Formats :: JSON :: JSON Schema +Requires-Python: >=3.10 +Requires-Dist: attrs>=22.2.0 +Requires-Dist: rpds-py>=0.7.0 +Requires-Dist: typing-extensions>=4.4.0; python_version < '3.13' +Description-Content-Type: text/x-rst + +=============== +``referencing`` +=============== + +|PyPI| |Pythons| |CI| |ReadTheDocs| |pre-commit| + +.. |PyPI| image:: https://img.shields.io/pypi/v/referencing.svg + :alt: PyPI version + :target: https://pypi.org/project/referencing/ + +.. |Pythons| image:: https://img.shields.io/pypi/pyversions/referencing.svg + :alt: Supported Python versions + :target: https://pypi.org/project/referencing/ + +.. |CI| image:: https://github.com/python-jsonschema/referencing/workflows/CI/badge.svg + :alt: Build status + :target: https://github.com/python-jsonschema/referencing/actions?query=workflow%3ACI + +.. |ReadTheDocs| image:: https://readthedocs.org/projects/referencing/badge/?version=stable&style=flat + :alt: ReadTheDocs status + :target: https://referencing.readthedocs.io/en/stable/ + +.. |pre-commit| image:: https://results.pre-commit.ci/badge/github/python-jsonschema/referencing/main.svg + :alt: pre-commit.ci status + :target: https://results.pre-commit.ci/latest/github/python-jsonschema/referencing/main + + +An implementation-agnostic implementation of JSON reference resolution. + +See `the documentation `_ for more details. diff --git a/TTS/Kokoro/.venv/Lib/site-packages/referencing-0.37.0.dist-info/RECORD b/TTS/Kokoro/.venv/Lib/site-packages/referencing-0.37.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..9dc99ade049bf567de8f74434df712dba2140970 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/referencing-0.37.0.dist-info/RECORD @@ -0,0 +1,33 @@ +referencing-0.37.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +referencing-0.37.0.dist-info/METADATA,sha256=yTsA5qsVJP1ghIN2YEwYmhFDdHdkdcJaMdV75Hsp3mo,2845 +referencing-0.37.0.dist-info/RECORD,, +referencing-0.37.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87 +referencing-0.37.0.dist-info/licenses/COPYING,sha256=QtzWNJX4e063x3V6-jebtVpT-Ur9el9lfZrfVyNuUVw,1057 +referencing/__init__.py,sha256=5IZKXaAH_FWyCJRkaTn1XcptLfg9cveLb9u5nYUxJKs,207 +referencing/__pycache__/__init__.cpython-312.pyc,, +referencing/__pycache__/_attrs.cpython-312.pyc,, +referencing/__pycache__/_core.cpython-312.pyc,, +referencing/__pycache__/exceptions.cpython-312.pyc,, +referencing/__pycache__/jsonschema.cpython-312.pyc,, +referencing/__pycache__/retrieval.cpython-312.pyc,, +referencing/__pycache__/typing.cpython-312.pyc,, +referencing/_attrs.py,sha256=bgT-KMhDVLeGtWxM_SGKYeLaZBFzT2kUVFdAkOcXi8g,791 +referencing/_attrs.pyi,sha256=g2wX-aLEqQAvWU-s0qIN2OMGAqjOA0R72R_uSffO8_M,573 +referencing/_core.py,sha256=2SPGfaTvzA3sRqbj_4R2wC--fiXolCUVpLFLJJ6zdZ8,24732 +referencing/exceptions.py,sha256=zFgaEg6WiKeT58MQuKNsgGDnHszp26c4oReC6sF9gHM,4176 +referencing/jsonschema.py,sha256=jXZ6t6x9oTvTHMIC0tRyaFjW5r2qeHObYuu7UhSfK3Q,18615 +referencing/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +referencing/retrieval.py,sha256=cn9EeAdaaTbnMDdC4JRIhiEpXDjflRdHCOLFrw1ZhLA,2729 +referencing/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +referencing/tests/__pycache__/__init__.cpython-312.pyc,, +referencing/tests/__pycache__/test_core.cpython-312.pyc,, +referencing/tests/__pycache__/test_exceptions.cpython-312.pyc,, +referencing/tests/__pycache__/test_jsonschema.cpython-312.pyc,, +referencing/tests/__pycache__/test_referencing_suite.cpython-312.pyc,, +referencing/tests/__pycache__/test_retrieval.cpython-312.pyc,, +referencing/tests/test_core.py,sha256=eap0CAaI23vjMIbVyEj92qLddp3iHH3AxC55CKUN4LU,37854 +referencing/tests/test_exceptions.py,sha256=7eOdHyobXMt7-h5AnnH7u8iw2uHPaH7U4Bs9JhLgjWo,934 +referencing/tests/test_jsonschema.py,sha256=4QnjUWOAMAn5yeA8ZtldJkhI54vwKWJWB0LDzNdx5xc,11687 +referencing/tests/test_referencing_suite.py,sha256=wD6veMfLsUu0s4MLjm7pS8cg4cIfL7FMBENngk73zCI,2335 +referencing/tests/test_retrieval.py,sha256=vcbnfA4TqVeqUzW073wO-nLeqVIv0rQZWNWv0z9km48,3719 +referencing/typing.py,sha256=WjUbnZ6jPAd31cnCFAaeWIVENzyHtHdJyOlelv1GY70,1445 diff --git a/TTS/Kokoro/.venv/Lib/site-packages/referencing-0.37.0.dist-info/WHEEL b/TTS/Kokoro/.venv/Lib/site-packages/referencing-0.37.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..12228d414b6cfed7c39d3781c85c63256a1d7fb5 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/referencing-0.37.0.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.27.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/TTS/Kokoro/.venv/Lib/site-packages/referencing/__init__.py b/TTS/Kokoro/.venv/Lib/site-packages/referencing/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e09207d7e4b90aba221181d87886fd4f54038abf --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/referencing/__init__.py @@ -0,0 +1,7 @@ +""" +Cross-specification, implementation-agnostic JSON referencing. +""" + +from referencing._core import Anchor, Registry, Resource, Specification + +__all__ = ["Anchor", "Registry", "Resource", "Specification"] diff --git a/TTS/Kokoro/.venv/Lib/site-packages/referencing/_attrs.py b/TTS/Kokoro/.venv/Lib/site-packages/referencing/_attrs.py new file mode 100644 index 0000000000000000000000000000000000000000..ae85b865fed622afe83e8d6b7b17a1f0d174aba3 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/referencing/_attrs.py @@ -0,0 +1,31 @@ +from __future__ import annotations + +from typing import NoReturn, TypeVar + +from attrs import define as _define, frozen as _frozen + +_T = TypeVar("_T") + + +def define(cls: type[_T]) -> type[_T]: # pragma: no cover + cls.__init_subclass__ = _do_not_subclass + return _define(cls) + + +def frozen(cls: type[_T]) -> type[_T]: + cls.__init_subclass__ = _do_not_subclass + return _frozen(cls) + + +class UnsupportedSubclassing(Exception): + def __str__(self): + return ( + "Subclassing is not part of referencing's public API. " + "If no other suitable API exists for what you're trying to do, " + "feel free to file an issue asking for one." + ) + + +@staticmethod +def _do_not_subclass() -> NoReturn: # pragma: no cover + raise UnsupportedSubclassing() diff --git a/TTS/Kokoro/.venv/Lib/site-packages/referencing/_attrs.pyi b/TTS/Kokoro/.venv/Lib/site-packages/referencing/_attrs.pyi new file mode 100644 index 0000000000000000000000000000000000000000..eca6db2bc88efb8c0183f260e8a34af6701ffbd2 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/referencing/_attrs.pyi @@ -0,0 +1,21 @@ +from collections.abc import Callable +from typing import Any, TypeVar + +from attr import attrib, field + +class UnsupportedSubclassing(Exception): ... + +_T = TypeVar("_T") + +def __dataclass_transform__( + *, + frozen_default: bool = False, + field_descriptors: tuple[type | Callable[..., Any], ...] = ..., +) -> Callable[[_T], _T]: ... +@__dataclass_transform__(field_descriptors=(attrib, field)) +def define(cls: type[_T]) -> type[_T]: ... +@__dataclass_transform__( + frozen_default=True, + field_descriptors=(attrib, field), +) +def frozen(cls: type[_T]) -> type[_T]: ... diff --git a/TTS/Kokoro/.venv/Lib/site-packages/referencing/_core.py b/TTS/Kokoro/.venv/Lib/site-packages/referencing/_core.py new file mode 100644 index 0000000000000000000000000000000000000000..42068451afb4b52ab885d9098b7ec66765282d3e --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/referencing/_core.py @@ -0,0 +1,739 @@ +from __future__ import annotations + +from collections.abc import Callable, Iterable, Iterator, Sequence +from enum import Enum +from typing import Any, ClassVar, Generic, Protocol +from urllib.parse import unquote, urldefrag, urljoin + +from attrs import evolve, field +from rpds import HashTrieMap, HashTrieSet, List + +try: + from typing_extensions import TypeVar +except ImportError: # pragma: no cover + from typing import TypeVar + +from referencing import exceptions +from referencing._attrs import frozen +from referencing.typing import URI, Anchor as AnchorType, D, Mapping, Retrieve + +EMPTY_UNCRAWLED: HashTrieSet[URI] = HashTrieSet() +EMPTY_PREVIOUS_RESOLVERS: List[URI] = List() + + +class _Unset(Enum): + """ + What sillyness... + """ + + SENTINEL = 1 + + +_UNSET = _Unset.SENTINEL + + +class _MaybeInSubresource(Protocol[D]): + def __call__( + self, + segments: Sequence[int | str], + resolver: Resolver[D], + subresource: Resource[D], + ) -> Resolver[D]: ... + + +def _detect_or_error(contents: D) -> Specification[D]: + if not isinstance(contents, Mapping): + raise exceptions.CannotDetermineSpecification(contents) + + jsonschema_dialect_id = contents.get("$schema") # type: ignore[reportUnknownMemberType] + if not isinstance(jsonschema_dialect_id, str): + raise exceptions.CannotDetermineSpecification(contents) + + from referencing.jsonschema import specification_with + + return specification_with(jsonschema_dialect_id) + + +def _detect_or_default( + default: Specification[D], +) -> Callable[[D], Specification[D]]: + def _detect(contents: D) -> Specification[D]: + if not isinstance(contents, Mapping): + return default + + jsonschema_dialect_id = contents.get("$schema") # type: ignore[reportUnknownMemberType] + if jsonschema_dialect_id is None: + return default + + from referencing.jsonschema import specification_with + + return specification_with( + jsonschema_dialect_id, # type: ignore[reportUnknownArgumentType] + default=default, + ) + + return _detect + + +class _SpecificationDetector: + def __get__( + self, + instance: Specification[D] | None, + cls: type[Specification[D]], + ) -> Callable[[D], Specification[D]]: + if instance is None: + return _detect_or_error + else: + return _detect_or_default(instance) + + +@frozen +class Specification(Generic[D]): + """ + A specification which defines referencing behavior. + + The various methods of a `Specification` allow for varying referencing + behavior across JSON Schema specification versions, etc. + """ + + #: A short human-readable name for the specification, used for debugging. + name: str + + #: Find the ID of a given document. + id_of: Callable[[D], URI | None] + + #: Retrieve the subresources of the given document (without traversing into + #: the subresources themselves). + subresources_of: Callable[[D], Iterable[D]] + + #: While resolving a JSON pointer, conditionally enter a subresource + #: (if e.g. we have just entered a keyword whose value is a subresource) + maybe_in_subresource: _MaybeInSubresource[D] + + #: Retrieve the anchors contained in the given document. + _anchors_in: Callable[ + [Specification[D], D], + Iterable[AnchorType[D]], + ] = field(alias="anchors_in") + + #: An opaque specification where resources have no subresources + #: nor internal identifiers. + OPAQUE: ClassVar[Specification[Any]] + + #: Attempt to discern which specification applies to the given contents. + #: + #: May be called either as an instance method or as a class method, with + #: slightly different behavior in the following case: + #: + #: Recall that not all contents contains enough internal information about + #: which specification it is written for -- the JSON Schema ``{}``, + #: for instance, is valid under many different dialects and may be + #: interpreted as any one of them. + #: + #: When this method is used as an instance method (i.e. called on a + #: specific specification), that specification is used as the default + #: if the given contents are unidentifiable. + #: + #: On the other hand when called as a class method, an error is raised. + #: + #: To reiterate, ``DRAFT202012.detect({})`` will return ``DRAFT202012`` + #: whereas the class method ``Specification.detect({})`` will raise an + #: error. + #: + #: (Note that of course ``DRAFT202012.detect(...)`` may return some other + #: specification when given a schema which *does* identify as being for + #: another version). + #: + #: Raises: + #: + #: `CannotDetermineSpecification` + #: + #: if the given contents don't have any discernible + #: information which could be used to guess which + #: specification they identify as + detect = _SpecificationDetector() + + def __repr__(self) -> str: + return f"" + + def anchors_in(self, contents: D): + """ + Retrieve the anchors contained in the given document. + """ + return self._anchors_in(self, contents) + + def create_resource(self, contents: D) -> Resource[D]: + """ + Create a resource which is interpreted using this specification. + """ + return Resource(contents=contents, specification=self) + + +Specification.OPAQUE = Specification( + name="opaque", + id_of=lambda contents: None, + subresources_of=lambda contents: [], + anchors_in=lambda specification, contents: [], + maybe_in_subresource=lambda segments, resolver, subresource: resolver, +) + + +@frozen +class Resource(Generic[D]): + r""" + A document (deserialized JSON) with a concrete interpretation under a spec. + + In other words, a Python object, along with an instance of `Specification` + which describes how the document interacts with referencing -- both + internally (how it refers to other `Resource`\ s) and externally (how it + should be identified such that it is referenceable by other documents). + """ + + contents: D + _specification: Specification[D] = field(alias="specification") + + @classmethod + def from_contents( + cls, + contents: D, + default_specification: ( + type[Specification[D]] | Specification[D] + ) = Specification, + ) -> Resource[D]: + """ + Create a resource guessing which specification applies to the contents. + + Raises: + + `CannotDetermineSpecification` + + if the given contents don't have any discernible + information which could be used to guess which + specification they identify as + + """ + specification = default_specification.detect(contents) + return specification.create_resource(contents=contents) + + @classmethod + def opaque(cls, contents: D) -> Resource[D]: + """ + Create an opaque `Resource` -- i.e. one with opaque specification. + + See `Specification.OPAQUE` for details. + """ + return Specification.OPAQUE.create_resource(contents=contents) + + def id(self) -> URI | None: + """ + Retrieve this resource's (specification-specific) identifier. + """ + id = self._specification.id_of(self.contents) + if id is None: + return + return id.rstrip("#") + + def subresources(self) -> Iterable[Resource[D]]: + """ + Retrieve this resource's subresources. + """ + return ( + Resource.from_contents( + each, + default_specification=self._specification, + ) + for each in self._specification.subresources_of(self.contents) + ) + + def anchors(self) -> Iterable[AnchorType[D]]: + """ + Retrieve this resource's (specification-specific) identifier. + """ + return self._specification.anchors_in(self.contents) + + def pointer(self, pointer: str, resolver: Resolver[D]) -> Resolved[D]: + """ + Resolve the given JSON pointer. + + Raises: + + `exceptions.PointerToNowhere` + + if the pointer points to a location not present in the document + + """ + if not pointer: + return Resolved(contents=self.contents, resolver=resolver) + + contents = self.contents + segments: list[int | str] = [] + for segment in unquote(pointer[1:]).split("/"): + if isinstance(contents, Sequence): + segment = int(segment) + else: + segment = segment.replace("~1", "/").replace("~0", "~") + try: + contents = contents[segment] # type: ignore[reportUnknownArgumentType] + except LookupError as lookup_error: + error = exceptions.PointerToNowhere(ref=pointer, resource=self) + raise error from lookup_error + + segments.append(segment) + last = resolver + resolver = self._specification.maybe_in_subresource( + segments=segments, + resolver=resolver, + subresource=self._specification.create_resource(contents), + ) + if resolver is not last: + segments = [] + return Resolved(contents=contents, resolver=resolver) # type: ignore[reportUnknownArgumentType] + + +def _fail_to_retrieve(uri: URI): + raise exceptions.NoSuchResource(ref=uri) + + +@frozen +class Registry(Mapping[URI, Resource[D]]): + r""" + A registry of `Resource`\ s, each identified by their canonical URIs. + + Registries store a collection of in-memory resources, and optionally + enable additional resources which may be stored elsewhere (e.g. in a + database, a separate set of files, over the network, etc.). + + They also lazily walk their known resources, looking for subresources + within them. In other words, subresources contained within any added + resources will be retrievable via their own IDs (though this discovery of + subresources will be delayed until necessary). + + Registries are immutable, and their methods return new instances of the + registry with the additional resources added to them. + + The ``retrieve`` argument can be used to configure retrieval of resources + dynamically, either over the network, from a database, or the like. + Pass it a callable which will be called if any URI not present in the + registry is accessed. It must either return a `Resource` or else raise a + `NoSuchResource` exception indicating that the resource does not exist + even according to the retrieval logic. + """ + + _resources: HashTrieMap[URI, Resource[D]] = field( + default=HashTrieMap(), + converter=HashTrieMap.convert, # type: ignore[reportGeneralTypeIssues] + alias="resources", + ) + _anchors: HashTrieMap[tuple[URI, str], AnchorType[D]] = HashTrieMap() + _uncrawled: HashTrieSet[URI] = EMPTY_UNCRAWLED + _retrieve: Retrieve[D] = field(default=_fail_to_retrieve, alias="retrieve") + + def __getitem__(self, uri: URI) -> Resource[D]: + """ + Return the (already crawled) `Resource` identified by the given URI. + """ + try: + return self._resources[uri.rstrip("#")] + except KeyError: + raise exceptions.NoSuchResource(ref=uri) from None + + def __iter__(self) -> Iterator[URI]: + """ + Iterate over all crawled URIs in the registry. + """ + return iter(self._resources) + + def __len__(self) -> int: + """ + Count the total number of fully crawled resources in this registry. + """ + return len(self._resources) + + def __rmatmul__( + self, + new: Resource[D] | Iterable[Resource[D]], + ) -> Registry[D]: + """ + Create a new registry with resource(s) added using their internal IDs. + + Resources must have a internal IDs (e.g. the :kw:`$id` keyword in + modern JSON Schema versions), otherwise an error will be raised. + + Both a single resource as well as an iterable of resources works, i.e.: + + * ``resource @ registry`` or + + * ``[iterable, of, multiple, resources] @ registry`` + + which -- again, assuming the resources have internal IDs -- is + equivalent to calling `Registry.with_resources` as such: + + .. code:: python + + registry.with_resources( + (resource.id(), resource) for resource in new_resources + ) + + Raises: + + `NoInternalID` + + if the resource(s) in fact do not have IDs + + """ + if isinstance(new, Resource): + new = (new,) + + resources = self._resources + uncrawled = self._uncrawled + for resource in new: + id = resource.id() + if id is None: + raise exceptions.NoInternalID(resource=resource) + uncrawled = uncrawled.insert(id) + resources = resources.insert(id, resource) + return evolve(self, resources=resources, uncrawled=uncrawled) + + def __repr__(self) -> str: + size = len(self) + pluralized = "resource" if size == 1 else "resources" + if self._uncrawled: + uncrawled = len(self._uncrawled) + if uncrawled == size: + summary = f"uncrawled {pluralized}" + else: + summary = f"{pluralized}, {uncrawled} uncrawled" + else: + summary = f"{pluralized}" + return f"" + + def get_or_retrieve(self, uri: URI) -> Retrieved[D, Resource[D]]: + """ + Get a resource from the registry, crawling or retrieving if necessary. + + May involve crawling to find the given URI if it is not already known, + so the returned object is a `Retrieved` object which contains both the + resource value as well as the registry which ultimately contained it. + """ + resource = self._resources.get(uri) + if resource is not None: + return Retrieved(registry=self, value=resource) + + registry = self.crawl() + resource = registry._resources.get(uri) + if resource is not None: + return Retrieved(registry=registry, value=resource) + + try: + resource = registry._retrieve(uri) + except ( + exceptions.CannotDetermineSpecification, + exceptions.NoSuchResource, + ): + raise + except Exception as error: + raise exceptions.Unretrievable(ref=uri) from error + else: + registry = registry.with_resource(uri, resource) + return Retrieved(registry=registry, value=resource) + + def remove(self, uri: URI): + """ + Return a registry with the resource identified by a given URI removed. + """ + if uri not in self._resources: + raise exceptions.NoSuchResource(ref=uri) + + return evolve( + self, + resources=self._resources.remove(uri), + uncrawled=self._uncrawled.discard(uri), + anchors=HashTrieMap( + (k, v) for k, v in self._anchors.items() if k[0] != uri + ), + ) + + def anchor(self, uri: URI, name: str): + """ + Retrieve a given anchor from a resource which must already be crawled. + """ + value = self._anchors.get((uri, name)) + if value is not None: + return Retrieved(value=value, registry=self) + + registry = self.crawl() + value = registry._anchors.get((uri, name)) + if value is not None: + return Retrieved(value=value, registry=registry) + + resource = self[uri] + canonical_uri = resource.id() + if canonical_uri is not None: + value = registry._anchors.get((canonical_uri, name)) + if value is not None: + return Retrieved(value=value, registry=registry) + + if "/" in name: + raise exceptions.InvalidAnchor( + ref=uri, + resource=resource, + anchor=name, + ) + raise exceptions.NoSuchAnchor(ref=uri, resource=resource, anchor=name) + + def contents(self, uri: URI) -> D: + """ + Retrieve the (already crawled) contents identified by the given URI. + """ + return self[uri].contents + + def crawl(self) -> Registry[D]: + """ + Crawl all added resources, discovering subresources. + """ + resources = self._resources + anchors = self._anchors + uncrawled = [(uri, resources[uri]) for uri in self._uncrawled] + while uncrawled: + uri, resource = uncrawled.pop() + + id = resource.id() + if id is not None: + uri = urljoin(uri, id) + resources = resources.insert(uri, resource) + for each in resource.anchors(): + anchors = anchors.insert((uri, each.name), each) + uncrawled.extend((uri, each) for each in resource.subresources()) + return evolve( + self, + resources=resources, + anchors=anchors, + uncrawled=EMPTY_UNCRAWLED, + ) + + def with_resource(self, uri: URI, resource: Resource[D]): + """ + Add the given `Resource` to the registry, without crawling it. + """ + return self.with_resources([(uri, resource)]) + + def with_resources( + self, + pairs: Iterable[tuple[URI, Resource[D]]], + ) -> Registry[D]: + r""" + Add the given `Resource`\ s to the registry, without crawling them. + """ + resources = self._resources + uncrawled = self._uncrawled + for uri, resource in pairs: + # Empty fragment URIs are equivalent to URIs without the fragment. + # TODO: Is this true for non JSON Schema resources? Probably not. + uri = uri.rstrip("#") + uncrawled = uncrawled.insert(uri) + resources = resources.insert(uri, resource) + return evolve(self, resources=resources, uncrawled=uncrawled) + + def with_contents( + self, + pairs: Iterable[tuple[URI, D]], + **kwargs: Any, + ) -> Registry[D]: + r""" + Add the given contents to the registry, autodetecting when necessary. + """ + return self.with_resources( + (uri, Resource.from_contents(each, **kwargs)) + for uri, each in pairs + ) + + def combine(self, *registries: Registry[D]) -> Registry[D]: + """ + Combine together one or more other registries, producing a unified one. + """ + if registries == (self,): + return self + resources = self._resources + anchors = self._anchors + uncrawled = self._uncrawled + retrieve = self._retrieve + for registry in registries: + resources = resources.update(registry._resources) + anchors = anchors.update(registry._anchors) + uncrawled = uncrawled.update(registry._uncrawled) + + if registry._retrieve is not _fail_to_retrieve: + if registry._retrieve is not retrieve is not _fail_to_retrieve: + raise ValueError( # noqa: TRY003 + "Cannot combine registries with conflicting retrieval " + "functions.", + ) + retrieve = registry._retrieve + return evolve( + self, + anchors=anchors, + resources=resources, + uncrawled=uncrawled, + retrieve=retrieve, + ) + + def resolver(self, base_uri: URI = "") -> Resolver[D]: + """ + Return a `Resolver` which resolves references against this registry. + """ + return Resolver(base_uri=base_uri, registry=self) + + def resolver_with_root(self, resource: Resource[D]) -> Resolver[D]: + """ + Return a `Resolver` with a specific root resource. + """ + uri = resource.id() or "" + return Resolver( + base_uri=uri, + registry=self.with_resource(uri, resource), + ) + + +#: An anchor or resource. +AnchorOrResource = TypeVar( + "AnchorOrResource", + AnchorType[Any], + Resource[Any], + default=Resource[Any], +) + + +@frozen +class Retrieved(Generic[D, AnchorOrResource]): + """ + A value retrieved from a `Registry`. + """ + + value: AnchorOrResource + registry: Registry[D] + + +@frozen +class Resolved(Generic[D]): + """ + A reference resolved to its contents by a `Resolver`. + """ + + contents: D + resolver: Resolver[D] + + +@frozen +class Resolver(Generic[D]): + """ + A reference resolver. + + Resolvers help resolve references (including relative ones) by + pairing a fixed base URI with a `Registry`. + + This object, under normal circumstances, is expected to be used by + *implementers of libraries* built on top of `referencing` (e.g. JSON Schema + implementations or other libraries resolving JSON references), + not directly by end-users populating registries or while writing + schemas or other resources. + + References are resolved against the base URI, and the combined URI + is then looked up within the registry. + + The process of resolving a reference may itself involve calculating + a *new* base URI for future reference resolution (e.g. if an + intermediate resource sets a new base URI), or may involve encountering + additional subresources and adding them to a new registry. + """ + + _base_uri: URI = field(alias="base_uri") + _registry: Registry[D] = field(alias="registry") + _previous: List[URI] = field(default=List(), repr=False, alias="previous") + + def lookup(self, ref: URI) -> Resolved[D]: + """ + Resolve the given reference to the resource it points to. + + Raises: + + `exceptions.Unresolvable` + + or a subclass thereof (see below) if the reference isn't + resolvable + + `exceptions.NoSuchAnchor` + + if the reference is to a URI where a resource exists but + contains a plain name fragment which does not exist within + the resource + + `exceptions.PointerToNowhere` + + if the reference is to a URI where a resource exists but + contains a JSON pointer to a location within the resource + that does not exist + + """ + if ref.startswith("#"): + uri, fragment = self._base_uri, ref[1:] + else: + uri, fragment = urldefrag(urljoin(self._base_uri, ref)) + try: + retrieved = self._registry.get_or_retrieve(uri) + except exceptions.NoSuchResource: + raise exceptions.Unresolvable(ref=ref) from None + except exceptions.Unretrievable as error: + raise exceptions.Unresolvable(ref=ref) from error + + if fragment.startswith("/"): + resolver = self._evolve(registry=retrieved.registry, base_uri=uri) + return retrieved.value.pointer(pointer=fragment, resolver=resolver) + + if fragment: + retrieved = retrieved.registry.anchor(uri, fragment) + resolver = self._evolve(registry=retrieved.registry, base_uri=uri) + return retrieved.value.resolve(resolver=resolver) + + resolver = self._evolve(registry=retrieved.registry, base_uri=uri) + return Resolved(contents=retrieved.value.contents, resolver=resolver) + + def in_subresource(self, subresource: Resource[D]) -> Resolver[D]: + """ + Create a resolver for a subresource (which may have a new base URI). + """ + id = subresource.id() + if id is None: + return self + return evolve(self, base_uri=urljoin(self._base_uri, id)) + + def dynamic_scope(self) -> Iterable[tuple[URI, Registry[D]]]: + """ + In specs with such a notion, return the URIs in the dynamic scope. + """ + for uri in self._previous: + yield uri, self._registry + + def _evolve(self, base_uri: URI, **kwargs: Any): + """ + Evolve, appending to the dynamic scope. + """ + previous = self._previous + if self._base_uri and (not previous or base_uri != self._base_uri): + previous = previous.push_front(self._base_uri) + return evolve(self, base_uri=base_uri, previous=previous, **kwargs) + + +@frozen +class Anchor(Generic[D]): + """ + A simple anchor in a `Resource`. + """ + + name: str + resource: Resource[D] + + def resolve(self, resolver: Resolver[D]): + """ + Return the resource for this anchor. + """ + return Resolved(contents=self.resource.contents, resolver=resolver) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/referencing/exceptions.py b/TTS/Kokoro/.venv/Lib/site-packages/referencing/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..3267fc70732e73c0a888d9f60551ad9373ed6d16 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/referencing/exceptions.py @@ -0,0 +1,165 @@ +""" +Errors, oh no! +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +import attrs + +from referencing._attrs import frozen + +if TYPE_CHECKING: + from referencing import Resource + from referencing.typing import URI + + +@frozen +class NoSuchResource(KeyError): + """ + The given URI is not present in a registry. + + Unlike most exceptions, this class *is* intended to be publicly + instantiable and *is* part of the public API of the package. + """ + + ref: URI + + def __eq__(self, other: object) -> bool: + if self.__class__ is not other.__class__: + return NotImplemented + return attrs.astuple(self) == attrs.astuple(other) + + def __hash__(self) -> int: + return hash(attrs.astuple(self)) + + +@frozen +class NoInternalID(Exception): + """ + A resource has no internal ID, but one is needed. + + E.g. in modern JSON Schema drafts, this is the :kw:`$id` keyword. + + One might be needed if a resource was to-be added to a registry but no + other URI is available, and the resource doesn't declare its canonical URI. + """ + + resource: Resource[Any] + + def __eq__(self, other: object) -> bool: + if self.__class__ is not other.__class__: + return NotImplemented + return attrs.astuple(self) == attrs.astuple(other) + + def __hash__(self) -> int: + return hash(attrs.astuple(self)) + + +@frozen +class Unretrievable(KeyError): + """ + The given URI is not present in a registry, and retrieving it failed. + """ + + ref: URI + + def __eq__(self, other: object) -> bool: + if self.__class__ is not other.__class__: + return NotImplemented + return attrs.astuple(self) == attrs.astuple(other) + + def __hash__(self) -> int: + return hash(attrs.astuple(self)) + + +@frozen +class CannotDetermineSpecification(Exception): + """ + Attempting to detect the appropriate `Specification` failed. + + This happens if no discernible information is found in the contents of the + new resource which would help identify it. + """ + + contents: Any + + def __eq__(self, other: object) -> bool: + if self.__class__ is not other.__class__: + return NotImplemented + return attrs.astuple(self) == attrs.astuple(other) + + def __hash__(self) -> int: + return hash(attrs.astuple(self)) + + +@attrs.frozen # Because here we allow subclassing below. +class Unresolvable(Exception): + """ + A reference was unresolvable. + """ + + ref: URI + + def __eq__(self, other: object) -> bool: + if self.__class__ is not other.__class__: + return NotImplemented + return attrs.astuple(self) == attrs.astuple(other) + + def __hash__(self) -> int: + return hash(attrs.astuple(self)) + + +@frozen +class PointerToNowhere(Unresolvable): + """ + A JSON Pointer leads to a part of a document that does not exist. + """ + + resource: Resource[Any] + + def __str__(self) -> str: + msg = f"{self.ref!r} does not exist within {self.resource.contents!r}" + if self.ref == "/": + msg += ( + ". The pointer '/' is a valid JSON Pointer but it points to " + "an empty string property ''. If you intended to point " + "to the entire resource, you should use '#'." + ) + return msg + + +@frozen +class NoSuchAnchor(Unresolvable): + """ + An anchor does not exist within a particular resource. + """ + + resource: Resource[Any] + anchor: str + + def __str__(self) -> str: + return ( + f"{self.anchor!r} does not exist within {self.resource.contents!r}" + ) + + +@frozen +class InvalidAnchor(Unresolvable): + """ + An anchor which could never exist in a resource was dereferenced. + + It is somehow syntactically invalid. + """ + + resource: Resource[Any] + anchor: str + + def __str__(self) -> str: + return ( + f"'#{self.anchor}' is not a valid anchor, neither as a " + "plain name anchor nor as a JSON Pointer. You may have intended " + f"to use '#/{self.anchor}', as the slash is required *before each " + "segment* of a JSON pointer." + ) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/referencing/jsonschema.py b/TTS/Kokoro/.venv/Lib/site-packages/referencing/jsonschema.py new file mode 100644 index 0000000000000000000000000000000000000000..93e77a78717183c3290427a448993e0bb997cfe4 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/referencing/jsonschema.py @@ -0,0 +1,642 @@ +""" +Referencing implementations for JSON Schema specs (historic & current). +""" + +from __future__ import annotations + +from collections.abc import Iterable, Sequence, Set +from typing import Any + +from referencing import Anchor, Registry, Resource, Specification, exceptions +from referencing._attrs import frozen +from referencing._core import ( + _UNSET, # type: ignore[reportPrivateUsage] + Resolved as _Resolved, + Resolver as _Resolver, + _Unset, # type: ignore[reportPrivateUsage] +) +from referencing.typing import URI, Anchor as AnchorType, Mapping + +#: A JSON Schema which is a JSON object +ObjectSchema = Mapping[str, Any] + +#: A JSON Schema of any kind +Schema = bool | ObjectSchema + +#: A Resource whose contents are JSON Schemas +SchemaResource = Resource[Schema] + +#: A JSON Schema Registry +SchemaRegistry = Registry[Schema] + +#: The empty JSON Schema Registry +EMPTY_REGISTRY: SchemaRegistry = Registry() + + +@frozen +class UnknownDialect(Exception): + """ + A dialect identifier was found for a dialect unknown by this library. + + If it's a custom ("unofficial") dialect, be sure you've registered it. + """ + + uri: URI + + +def _dollar_id(contents: Schema) -> URI | None: + if isinstance(contents, bool): + return + return contents.get("$id") + + +def _legacy_dollar_id(contents: Schema) -> URI | None: + if isinstance(contents, bool) or "$ref" in contents: + return + id = contents.get("$id") + if id is not None and not id.startswith("#"): + return id + + +def _legacy_id(contents: ObjectSchema) -> URI | None: + if "$ref" in contents: + return + id = contents.get("id") + if id is not None and not id.startswith("#"): + return id + + +def _anchor( + specification: Specification[Schema], + contents: Schema, +) -> Iterable[AnchorType[Schema]]: + if isinstance(contents, bool): + return + anchor = contents.get("$anchor") + if anchor is not None: + yield Anchor( + name=anchor, + resource=specification.create_resource(contents), + ) + + dynamic_anchor = contents.get("$dynamicAnchor") + if dynamic_anchor is not None: + yield DynamicAnchor( + name=dynamic_anchor, + resource=specification.create_resource(contents), + ) + + +def _anchor_2019( + specification: Specification[Schema], + contents: Schema, +) -> Iterable[Anchor[Schema]]: + if isinstance(contents, bool): + return [] + anchor = contents.get("$anchor") + if anchor is None: + return [] + return [ + Anchor( + name=anchor, + resource=specification.create_resource(contents), + ), + ] + + +def _legacy_anchor_in_dollar_id( + specification: Specification[Schema], + contents: Schema, +) -> Iterable[Anchor[Schema]]: + if isinstance(contents, bool): + return [] + id = contents.get("$id", "") + if not id.startswith("#"): + return [] + return [ + Anchor( + name=id[1:], + resource=specification.create_resource(contents), + ), + ] + + +def _legacy_anchor_in_id( + specification: Specification[ObjectSchema], + contents: ObjectSchema, +) -> Iterable[Anchor[ObjectSchema]]: + id = contents.get("id", "") + if not id.startswith("#"): + return [] + return [ + Anchor( + name=id[1:], + resource=specification.create_resource(contents), + ), + ] + + +def _subresources_of( + in_value: Set[str] = frozenset(), + in_subvalues: Set[str] = frozenset(), + in_subarray: Set[str] = frozenset(), +): + """ + Create a callable returning JSON Schema specification-style subschemas. + + Relies on specifying the set of keywords containing subschemas in their + values, in a subobject's values, or in a subarray. + """ + + def subresources_of(contents: Schema) -> Iterable[ObjectSchema]: + if isinstance(contents, bool): + return + for each in in_value: + if each in contents: + yield contents[each] + for each in in_subarray: + if each in contents: + yield from contents[each] + for each in in_subvalues: + if each in contents: + yield from contents[each].values() + + return subresources_of + + +def _subresources_of_with_crazy_items( + in_value: Set[str] = frozenset(), + in_subvalues: Set[str] = frozenset(), + in_subarray: Set[str] = frozenset(), +): + """ + Specifically handle older drafts where there are some funky keywords. + """ + + def subresources_of(contents: Schema) -> Iterable[ObjectSchema]: + if isinstance(contents, bool): + return + for each in in_value: + if each in contents: + yield contents[each] + for each in in_subarray: + if each in contents: + yield from contents[each] + for each in in_subvalues: + if each in contents: + yield from contents[each].values() + + items = contents.get("items") + if items is not None: + if isinstance(items, Sequence): + yield from items + else: + yield items + + return subresources_of + + +def _subresources_of_with_crazy_items_dependencies( + in_value: Set[str] = frozenset(), + in_subvalues: Set[str] = frozenset(), + in_subarray: Set[str] = frozenset(), +): + """ + Specifically handle older drafts where there are some funky keywords. + """ + + def subresources_of(contents: Schema) -> Iterable[ObjectSchema]: + if isinstance(contents, bool): + return + for each in in_value: + if each in contents: + yield contents[each] + for each in in_subarray: + if each in contents: + yield from contents[each] + for each in in_subvalues: + if each in contents: + yield from contents[each].values() + + items = contents.get("items") + if items is not None: + if isinstance(items, Sequence): + yield from items + else: + yield items + dependencies = contents.get("dependencies") + if dependencies is not None: + values = iter(dependencies.values()) + value = next(values, None) + if isinstance(value, Mapping): + yield value + yield from values + + return subresources_of + + +def _subresources_of_with_crazy_aP_items_dependencies( + in_value: Set[str] = frozenset(), + in_subvalues: Set[str] = frozenset(), + in_subarray: Set[str] = frozenset(), +): + """ + Specifically handle even older drafts where there are some funky keywords. + """ + + def subresources_of(contents: ObjectSchema) -> Iterable[ObjectSchema]: + for each in in_value: + if each in contents: + yield contents[each] + for each in in_subarray: + if each in contents: + yield from contents[each] + for each in in_subvalues: + if each in contents: + yield from contents[each].values() + + items = contents.get("items") + if items is not None: + if isinstance(items, Sequence): + yield from items + else: + yield items + dependencies = contents.get("dependencies") + if dependencies is not None: + values = iter(dependencies.values()) + value = next(values, None) + if isinstance(value, Mapping): + yield value + yield from values + + for each in "additionalItems", "additionalProperties": + value = contents.get(each) + if isinstance(value, Mapping): + yield value + + return subresources_of + + +def _maybe_in_subresource( + in_value: Set[str] = frozenset(), + in_subvalues: Set[str] = frozenset(), + in_subarray: Set[str] = frozenset(), +): + in_child = in_subvalues | in_subarray + + def maybe_in_subresource( + segments: Sequence[int | str], + resolver: _Resolver[Any], + subresource: Resource[Any], + ) -> _Resolver[Any]: + _segments = iter(segments) + for segment in _segments: + if segment not in in_value and ( + segment not in in_child or next(_segments, None) is None + ): + return resolver + return resolver.in_subresource(subresource) + + return maybe_in_subresource + + +def _maybe_in_subresource_crazy_items( + in_value: Set[str] = frozenset(), + in_subvalues: Set[str] = frozenset(), + in_subarray: Set[str] = frozenset(), +): + in_child = in_subvalues | in_subarray + + def maybe_in_subresource( + segments: Sequence[int | str], + resolver: _Resolver[Any], + subresource: Resource[Any], + ) -> _Resolver[Any]: + _segments = iter(segments) + for segment in _segments: + if segment == "items" and isinstance( + subresource.contents, + Mapping, + ): + return resolver.in_subresource(subresource) + if segment not in in_value and ( + segment not in in_child or next(_segments, None) is None + ): + return resolver + return resolver.in_subresource(subresource) + + return maybe_in_subresource + + +def _maybe_in_subresource_crazy_items_dependencies( + in_value: Set[str] = frozenset(), + in_subvalues: Set[str] = frozenset(), + in_subarray: Set[str] = frozenset(), +): + in_child = in_subvalues | in_subarray + + def maybe_in_subresource( + segments: Sequence[int | str], + resolver: _Resolver[Any], + subresource: Resource[Any], + ) -> _Resolver[Any]: + _segments = iter(segments) + for segment in _segments: + if segment in {"items", "dependencies"} and isinstance( + subresource.contents, + Mapping, + ): + return resolver.in_subresource(subresource) + if segment not in in_value and ( + segment not in in_child or next(_segments, None) is None + ): + return resolver + return resolver.in_subresource(subresource) + + return maybe_in_subresource + + +#: JSON Schema draft 2020-12 +DRAFT202012 = Specification( + name="draft2020-12", + id_of=_dollar_id, + subresources_of=_subresources_of( + in_value={ + "additionalProperties", + "contains", + "contentSchema", + "else", + "if", + "items", + "not", + "propertyNames", + "then", + "unevaluatedItems", + "unevaluatedProperties", + }, + in_subarray={"allOf", "anyOf", "oneOf", "prefixItems"}, + in_subvalues={ + "$defs", + "definitions", + "dependentSchemas", + "patternProperties", + "properties", + }, + ), + anchors_in=_anchor, + maybe_in_subresource=_maybe_in_subresource( + in_value={ + "additionalProperties", + "contains", + "contentSchema", + "else", + "if", + "items", + "not", + "propertyNames", + "then", + "unevaluatedItems", + "unevaluatedProperties", + }, + in_subarray={"allOf", "anyOf", "oneOf", "prefixItems"}, + in_subvalues={ + "$defs", + "definitions", + "dependentSchemas", + "patternProperties", + "properties", + }, + ), +) +#: JSON Schema draft 2019-09 +DRAFT201909 = Specification( + name="draft2019-09", + id_of=_dollar_id, + subresources_of=_subresources_of_with_crazy_items( + in_value={ + "additionalItems", + "additionalProperties", + "contains", + "contentSchema", + "else", + "if", + "not", + "propertyNames", + "then", + "unevaluatedItems", + "unevaluatedProperties", + }, + in_subarray={"allOf", "anyOf", "oneOf"}, + in_subvalues={ + "$defs", + "definitions", + "dependentSchemas", + "patternProperties", + "properties", + }, + ), + anchors_in=_anchor_2019, + maybe_in_subresource=_maybe_in_subresource_crazy_items( + in_value={ + "additionalItems", + "additionalProperties", + "contains", + "contentSchema", + "else", + "if", + "not", + "propertyNames", + "then", + "unevaluatedItems", + "unevaluatedProperties", + }, + in_subarray={"allOf", "anyOf", "oneOf"}, + in_subvalues={ + "$defs", + "definitions", + "dependentSchemas", + "patternProperties", + "properties", + }, + ), +) +#: JSON Schema draft 7 +DRAFT7 = Specification( + name="draft-07", + id_of=_legacy_dollar_id, + subresources_of=_subresources_of_with_crazy_items_dependencies( + in_value={ + "additionalItems", + "additionalProperties", + "contains", + "else", + "if", + "not", + "propertyNames", + "then", + }, + in_subarray={"allOf", "anyOf", "oneOf"}, + in_subvalues={"definitions", "patternProperties", "properties"}, + ), + anchors_in=_legacy_anchor_in_dollar_id, + maybe_in_subresource=_maybe_in_subresource_crazy_items_dependencies( + in_value={ + "additionalItems", + "additionalProperties", + "contains", + "else", + "if", + "not", + "propertyNames", + "then", + }, + in_subarray={"allOf", "anyOf", "oneOf"}, + in_subvalues={"definitions", "patternProperties", "properties"}, + ), +) +#: JSON Schema draft 6 +DRAFT6 = Specification( + name="draft-06", + id_of=_legacy_dollar_id, + subresources_of=_subresources_of_with_crazy_items_dependencies( + in_value={ + "additionalItems", + "additionalProperties", + "contains", + "not", + "propertyNames", + }, + in_subarray={"allOf", "anyOf", "oneOf"}, + in_subvalues={"definitions", "patternProperties", "properties"}, + ), + anchors_in=_legacy_anchor_in_dollar_id, + maybe_in_subresource=_maybe_in_subresource_crazy_items_dependencies( + in_value={ + "additionalItems", + "additionalProperties", + "contains", + "not", + "propertyNames", + }, + in_subarray={"allOf", "anyOf", "oneOf"}, + in_subvalues={"definitions", "patternProperties", "properties"}, + ), +) +#: JSON Schema draft 4 +DRAFT4 = Specification( + name="draft-04", + id_of=_legacy_id, + subresources_of=_subresources_of_with_crazy_aP_items_dependencies( + in_value={"not"}, + in_subarray={"allOf", "anyOf", "oneOf"}, + in_subvalues={"definitions", "patternProperties", "properties"}, + ), + anchors_in=_legacy_anchor_in_id, + maybe_in_subresource=_maybe_in_subresource_crazy_items_dependencies( + in_value={"additionalItems", "additionalProperties", "not"}, + in_subarray={"allOf", "anyOf", "oneOf"}, + in_subvalues={"definitions", "patternProperties", "properties"}, + ), +) +#: JSON Schema draft 3 +DRAFT3 = Specification( + name="draft-03", + id_of=_legacy_id, + subresources_of=_subresources_of_with_crazy_aP_items_dependencies( + in_subarray={"extends"}, + in_subvalues={"definitions", "patternProperties", "properties"}, + ), + anchors_in=_legacy_anchor_in_id, + maybe_in_subresource=_maybe_in_subresource_crazy_items_dependencies( + in_value={"additionalItems", "additionalProperties"}, + in_subarray={"extends"}, + in_subvalues={"definitions", "patternProperties", "properties"}, + ), +) + + +_SPECIFICATIONS: Registry[Specification[Schema]] = Registry( + { + dialect_id: Resource.opaque(specification) + for dialect_id, specification in [ + ("https://json-schema.org/draft/2020-12/schema", DRAFT202012), + ("https://json-schema.org/draft/2019-09/schema", DRAFT201909), + ("http://json-schema.org/draft-07/schema", DRAFT7), + ("http://json-schema.org/draft-06/schema", DRAFT6), + ("http://json-schema.org/draft-04/schema", DRAFT4), + ("http://json-schema.org/draft-03/schema", DRAFT3), + ] + }, +) + + +def specification_with( + dialect_id: URI, + default: Specification[Any] | _Unset = _UNSET, +) -> Specification[Any]: + """ + Retrieve the `Specification` with the given dialect identifier. + + Raises: + + `UnknownDialect` + + if the given ``dialect_id`` isn't known + + """ + resource = _SPECIFICATIONS.get(dialect_id.rstrip("#")) + if resource is not None: + return resource.contents + if default is _UNSET: + raise UnknownDialect(dialect_id) + return default + + +@frozen +class DynamicAnchor: + """ + Dynamic anchors, introduced in draft 2020. + """ + + name: str + resource: SchemaResource + + def resolve(self, resolver: _Resolver[Schema]) -> _Resolved[Schema]: + """ + Resolve this anchor dynamically. + """ + last = self.resource + for uri, registry in resolver.dynamic_scope(): + try: + anchor = registry.anchor(uri, self.name).value + except exceptions.NoSuchAnchor: + continue + if isinstance(anchor, DynamicAnchor): + last = anchor.resource + return _Resolved( + contents=last.contents, + resolver=resolver.in_subresource(last), + ) + + +def lookup_recursive_ref(resolver: _Resolver[Schema]) -> _Resolved[Schema]: + """ + Recursive references (via recursive anchors), present only in draft 2019. + + As per the 2019 specification (§ 8.2.4.2.1), only the ``#`` recursive + reference is supported (and is therefore assumed to be the relevant + reference). + """ + resolved = resolver.lookup("#") + if isinstance(resolved.contents, Mapping) and resolved.contents.get( + "$recursiveAnchor", + ): + for uri, _ in resolver.dynamic_scope(): + next_resolved = resolver.lookup(uri) + if not isinstance( + next_resolved.contents, + Mapping, + ) or not next_resolved.contents.get("$recursiveAnchor"): + break + resolved = next_resolved + return resolved diff --git a/TTS/Kokoro/.venv/Lib/site-packages/referencing/py.typed b/TTS/Kokoro/.venv/Lib/site-packages/referencing/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/TTS/Kokoro/.venv/Lib/site-packages/referencing/retrieval.py b/TTS/Kokoro/.venv/Lib/site-packages/referencing/retrieval.py new file mode 100644 index 0000000000000000000000000000000000000000..ac5a65bd604abb7548778f1f3331d3514d57b363 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/referencing/retrieval.py @@ -0,0 +1,94 @@ +""" +Helpers related to (dynamic) resource retrieval. +""" + +from __future__ import annotations + +from functools import lru_cache +from typing import TYPE_CHECKING +import json + +try: + from typing_extensions import TypeVar +except ImportError: # pragma: no cover + from typing import TypeVar + +from referencing import Resource + +if TYPE_CHECKING: + from collections.abc import Callable + + from referencing.typing import URI, D, Retrieve + +#: A serialized document (e.g. a JSON string) +_T = TypeVar("_T", default=str) + + +def to_cached_resource( + cache: Callable[[Retrieve[D]], Retrieve[D]] | None = None, + loads: Callable[[_T], D] = json.loads, + from_contents: Callable[[D], Resource[D]] = Resource.from_contents, +) -> Callable[[Callable[[URI], _T]], Retrieve[D]]: + """ + Create a retriever which caches its return values from a simpler callable. + + Takes a function which returns things like serialized JSON (strings) and + returns something suitable for passing to `Registry` as a retrieve + function. + + This decorator both reduces a small bit of boilerplate for a common case + (deserializing JSON from strings and creating `Resource` objects from the + result) as well as makes the probable need for caching a bit easier. + Retrievers which otherwise do expensive operations (like hitting the + network) might otherwise be called repeatedly. + + Examples + -------- + + .. testcode:: + + from referencing import Registry + from referencing.typing import URI + import referencing.retrieval + + + @referencing.retrieval.to_cached_resource() + def retrieve(uri: URI): + print(f"Retrieved {uri}") + + # Normally, go get some expensive JSON from the network, a file ... + return ''' + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "foo": "bar" + } + ''' + + one = Registry(retrieve=retrieve).get_or_retrieve("urn:example:foo") + print(one.value.contents["foo"]) + + # Retrieving the same URI again reuses the same value (and thus doesn't + # print another retrieval message here) + two = Registry(retrieve=retrieve).get_or_retrieve("urn:example:foo") + print(two.value.contents["foo"]) + + .. testoutput:: + + Retrieved urn:example:foo + bar + bar + + """ + if cache is None: + cache = lru_cache(maxsize=None) + + def decorator(retrieve: Callable[[URI], _T]): + @cache + def cached_retrieve(uri: URI): + response = retrieve(uri) + contents = loads(response) + return from_contents(contents) + + return cached_retrieve + + return decorator diff --git a/TTS/Kokoro/.venv/Lib/site-packages/referencing/typing.py b/TTS/Kokoro/.venv/Lib/site-packages/referencing/typing.py new file mode 100644 index 0000000000000000000000000000000000000000..a61446417e68e8e397346b14e8525cc9062f1c59 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/referencing/typing.py @@ -0,0 +1,61 @@ +""" +Type-annotation related support for the referencing library. +""" + +from __future__ import annotations + +from collections.abc import Mapping as Mapping +from typing import TYPE_CHECKING, Any, Protocol + +try: + from typing_extensions import TypeVar +except ImportError: # pragma: no cover + from typing import TypeVar + +if TYPE_CHECKING: + from referencing._core import Resolved, Resolver, Resource + +#: A URI which identifies a `Resource`. +URI = str + +#: The type of documents within a registry. +D = TypeVar("D", default=Any) + + +class Retrieve(Protocol[D]): + """ + A retrieval callable, usable within a `Registry` for resource retrieval. + + Does not make assumptions about where the resource might be coming from. + """ + + def __call__(self, uri: URI) -> Resource[D]: + """ + Retrieve the resource with the given URI. + + Raise `referencing.exceptions.NoSuchResource` if you wish to indicate + the retriever cannot lookup the given URI. + """ + ... + + +class Anchor(Protocol[D]): + """ + An anchor within a `Resource`. + + Beyond "simple" anchors, some specifications like JSON Schema's 2020 + version have dynamic anchors. + """ + + @property + def name(self) -> str: + """ + Return the name of this anchor. + """ + ... + + def resolve(self, resolver: Resolver[D]) -> Resolved[D]: + """ + Return the resource for this anchor. + """ + ... diff --git a/TTS/Kokoro/.venv/Lib/site-packages/regex-2026.2.19.dist-info/INSTALLER b/TTS/Kokoro/.venv/Lib/site-packages/regex-2026.2.19.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/regex-2026.2.19.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/TTS/Kokoro/.venv/Lib/site-packages/regex-2026.2.19.dist-info/METADATA b/TTS/Kokoro/.venv/Lib/site-packages/regex-2026.2.19.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..0c0d37ad58549e1db6185658315f6a613e5b1282 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/regex-2026.2.19.dist-info/METADATA @@ -0,0 +1,1058 @@ +Metadata-Version: 2.4 +Name: regex +Version: 2026.2.19 +Summary: Alternative regular expression module, to replace re. +Author-email: Matthew Barnett +License-Expression: Apache-2.0 AND CNRI-Python +Project-URL: Homepage, https://github.com/mrabarnett/mrab-regex +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Topic :: Scientific/Engineering :: Information Analysis +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Topic :: Text Processing +Classifier: Topic :: Text Processing :: General +Requires-Python: >=3.10 +Description-Content-Type: text/x-rst +License-File: LICENSE.txt +Dynamic: license-file + +Introduction +------------ + +This regex implementation is backwards-compatible with the standard 're' module, but offers additional functionality. + +Python 2 +-------- + +Python 2 is no longer supported. The last release that supported Python 2 was 2021.11.10. + +PyPy +---- + +This module is targeted at CPython. It expects that all codepoints are the same width, so it won't behave properly with PyPy outside U+0000..U+007F because PyPy stores strings as UTF-8. + +Multithreading +-------------- + +The regex module releases the GIL during matching on instances of the built-in (immutable) string classes, enabling other Python threads to run concurrently. It is also possible to force the regex module to release the GIL during matching by calling the matching methods with the keyword argument ``concurrent=True``. The behaviour is undefined if the string changes during matching, so use it *only* when it is guaranteed that that won't happen. + +Unicode +------- + +This module supports Unicode 17.0.0. Full Unicode case-folding is supported. + +Flags +----- + +There are 2 kinds of flag: scoped and global. Scoped flags can apply to only part of a pattern and can be turned on or off; global flags apply to the entire pattern and can only be turned on. + +The scoped flags are: ``ASCII (?a)``, ``FULLCASE (?f)``, ``IGNORECASE (?i)``, ``LOCALE (?L)``, ``MULTILINE (?m)``, ``DOTALL (?s)``, ``UNICODE (?u)``, ``VERBOSE (?x)``, ``WORD (?w)``. + +The global flags are: ``BESTMATCH (?b)``, ``ENHANCEMATCH (?e)``, ``POSIX (?p)``, ``REVERSE (?r)``, ``VERSION0 (?V0)``, ``VERSION1 (?V1)``. + +If neither the ``ASCII``, ``LOCALE`` nor ``UNICODE`` flag is specified, it will default to ``UNICODE`` if the regex pattern is a Unicode string and ``ASCII`` if it's a bytestring. + +The ``ENHANCEMATCH`` flag makes fuzzy matching attempt to improve the fit of the next match that it finds. + +The ``BESTMATCH`` flag makes fuzzy matching search for the best match instead of the next match. + +Old vs new behaviour +-------------------- + +In order to be compatible with the re module, this module has 2 behaviours: + +* **Version 0** behaviour (old behaviour, compatible with the re module): + + Please note that the re module's behaviour may change over time, and I'll endeavour to match that behaviour in version 0. + + * Indicated by the ``VERSION0`` flag. + + * Zero-width matches are not handled correctly in the re module before Python 3.7. The behaviour in those earlier versions is: + + * ``.split`` won't split a string at a zero-width match. + + * ``.sub`` will advance by one character after a zero-width match. + + * Inline flags apply to the entire pattern, and they can't be turned off. + + * Only simple sets are supported. + + * Case-insensitive matches in Unicode use simple case-folding by default. + +* **Version 1** behaviour (new behaviour, possibly different from the re module): + + * Indicated by the ``VERSION1`` flag. + + * Zero-width matches are handled correctly. + + * Inline flags apply to the end of the group or pattern, and they can be turned off. + + * Nested sets and set operations are supported. + + * Case-insensitive matches in Unicode use full case-folding by default. + +If no version is specified, the regex module will default to ``regex.DEFAULT_VERSION``. + +Case-insensitive matches in Unicode +----------------------------------- + +The regex module supports both simple and full case-folding for case-insensitive matches in Unicode. Use of full case-folding can be turned on using the ``FULLCASE`` flag. Please note that this flag affects how the ``IGNORECASE`` flag works; the ``FULLCASE`` flag itself does not turn on case-insensitive matching. + +Version 0 behaviour: the flag is off by default. + +Version 1 behaviour: the flag is on by default. + +Nested sets and set operations +------------------------------ + +It's not possible to support both simple sets, as used in the re module, and nested sets at the same time because of a difference in the meaning of an unescaped ``"["`` in a set. + +For example, the pattern ``[[a-z]--[aeiou]]`` is treated in the version 0 behaviour (simple sets, compatible with the re module) as: + +* Set containing "[" and the letters "a" to "z" + +* Literal "--" + +* Set containing letters "a", "e", "i", "o", "u" + +* Literal "]" + +but in the version 1 behaviour (nested sets, enhanced behaviour) as: + +* Set which is: + + * Set containing the letters "a" to "z" + +* but excluding: + + * Set containing the letters "a", "e", "i", "o", "u" + +Version 0 behaviour: only simple sets are supported. + +Version 1 behaviour: nested sets and set operations are supported. + +Notes on named groups +--------------------- + +All groups have a group number, starting from 1. + +Groups with the same group name will have the same group number, and groups with a different group name will have a different group number. + +The same name can be used by more than one group, with later captures 'overwriting' earlier captures. All the captures of the group will be available from the ``captures`` method of the match object. + +Group numbers will be reused across different branches of a branch reset, eg. ``(?|(first)|(second))`` has only group 1. If groups have different group names then they will, of course, have different group numbers, eg. ``(?|(?Pfirst)|(?Psecond))`` has group 1 ("foo") and group 2 ("bar"). + +In the regex ``(\s+)(?|(?P[A-Z]+)|(\w+) (?P[0-9]+)`` there are 2 groups: + +* ``(\s+)`` is group 1. + +* ``(?P[A-Z]+)`` is group 2, also called "foo". + +* ``(\w+)`` is group 2 because of the branch reset. + +* ``(?P[0-9]+)`` is group 2 because it's called "foo". + +If you want to prevent ``(\w+)`` from being group 2, you need to name it (different name, different group number). + +Additional features +------------------- + +The issue numbers relate to the Python bug tracker, except where listed otherwise. + +Added ``\p{Horiz_Space}`` and ``\p{Vert_Space}`` (`GitHub issue 477 `_) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +``\p{Horiz_Space}`` or ``\p{H}`` matches horizontal whitespace and ``\p{Vert_Space}`` or ``\p{V}`` matches vertical whitespace. + +Added support for lookaround in conditional pattern (`Hg issue 163 `_) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The test of a conditional pattern can be a lookaround. + +.. sourcecode:: python + + >>> regex.match(r'(?(?=\d)\d+|\w+)', '123abc') + + >>> regex.match(r'(?(?=\d)\d+|\w+)', 'abc123') + + +This is not quite the same as putting a lookaround in the first branch of a pair of alternatives. + +.. sourcecode:: python + + >>> print(regex.match(r'(?:(?=\d)\d+\b|\w+)', '123abc')) + + >>> print(regex.match(r'(?(?=\d)\d+\b|\w+)', '123abc')) + None + +In the first example, the lookaround matched, but the remainder of the first branch failed to match, and so the second branch was attempted, whereas in the second example, the lookaround matched, and the first branch failed to match, but the second branch was **not** attempted. + +Added POSIX matching (leftmost longest) (`Hg issue 150 `_) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The POSIX standard for regex is to return the leftmost longest match. This can be turned on using the ``POSIX`` flag. + +.. sourcecode:: python + + >>> # Normal matching. + >>> regex.search(r'Mr|Mrs', 'Mrs') + + >>> regex.search(r'one(self)?(selfsufficient)?', 'oneselfsufficient') + + >>> # POSIX matching. + >>> regex.search(r'(?p)Mr|Mrs', 'Mrs') + + >>> regex.search(r'(?p)one(self)?(selfsufficient)?', 'oneselfsufficient') + + +Note that it will take longer to find matches because when it finds a match at a certain position, it won't return that immediately, but will keep looking to see if there's another longer match there. + +Added ``(?(DEFINE)...)`` (`Hg issue 152 `_) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +If there's no group called "DEFINE", then ... will be ignored except that any groups defined within it can be called and that the normal rules for numbering groups still apply. + +.. sourcecode:: python + + >>> regex.search(r'(?(DEFINE)(?P\d+)(?P\w+))(?&quant) (?&item)', '5 elephants') + + +Added ``(*PRUNE)``, ``(*SKIP)`` and ``(*FAIL)`` (`Hg issue 153 `_) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +``(*PRUNE)`` discards the backtracking info up to that point. When used in an atomic group or a lookaround, it won't affect the enclosing pattern. + +``(*SKIP)`` is similar to ``(*PRUNE)``, except that it also sets where in the text the next attempt to match will start. When used in an atomic group or a lookaround, it won't affect the enclosing pattern. + +``(*FAIL)`` causes immediate backtracking. ``(*F)`` is a permitted abbreviation. + +Added ``\K`` (`Hg issue 151 `_) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Keeps the part of the entire match after the position where ``\K`` occurred; the part before it is discarded. + +It does not affect what groups return. + +.. sourcecode:: python + + >>> m = regex.search(r'(\w\w\K\w\w\w)', 'abcdef') + >>> m[0] + 'cde' + >>> m[1] + 'abcde' + >>> + >>> m = regex.search(r'(?r)(\w\w\K\w\w\w)', 'abcdef') + >>> m[0] + 'bc' + >>> m[1] + 'bcdef' + +Added capture subscripting for ``expandf`` and ``subf``/``subfn`` (`Hg issue 133 `_) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +You can use subscripting to get the captures of a repeated group. + +.. sourcecode:: python + + >>> m = regex.match(r"(\w)+", "abc") + >>> m.expandf("{1}") + 'c' + >>> m.expandf("{1[0]} {1[1]} {1[2]}") + 'a b c' + >>> m.expandf("{1[-1]} {1[-2]} {1[-3]}") + 'c b a' + >>> + >>> m = regex.match(r"(?P\w)+", "abc") + >>> m.expandf("{letter}") + 'c' + >>> m.expandf("{letter[0]} {letter[1]} {letter[2]}") + 'a b c' + >>> m.expandf("{letter[-1]} {letter[-2]} {letter[-3]}") + 'c b a' + +Added support for referring to a group by number using ``(?P=...)`` +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +This is in addition to the existing ``\g<...>``. + +Fixed the handling of locale-sensitive regexes +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The ``LOCALE`` flag is intended for legacy code and has limited support. You're still recommended to use Unicode instead. + +Added partial matches (`Hg issue 102 `_) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +A partial match is one that matches up to the end of string, but that string has been truncated and you want to know whether a complete match could be possible if the string had not been truncated. + +Partial matches are supported by ``match``, ``search``, ``fullmatch`` and ``finditer`` with the ``partial`` keyword argument. + +Match objects have a ``partial`` attribute, which is ``True`` if it's a partial match. + +For example, if you wanted a user to enter a 4-digit number and check it character by character as it was being entered: + +.. sourcecode:: python + + >>> pattern = regex.compile(r'\d{4}') + + >>> # Initially, nothing has been entered: + >>> print(pattern.fullmatch('', partial=True)) + + + >>> # An empty string is OK, but it's only a partial match. + >>> # The user enters a letter: + >>> print(pattern.fullmatch('a', partial=True)) + None + >>> # It'll never match. + + >>> # The user deletes that and enters a digit: + >>> print(pattern.fullmatch('1', partial=True)) + + >>> # It matches this far, but it's only a partial match. + + >>> # The user enters 2 more digits: + >>> print(pattern.fullmatch('123', partial=True)) + + >>> # It matches this far, but it's only a partial match. + + >>> # The user enters another digit: + >>> print(pattern.fullmatch('1234', partial=True)) + + >>> # It's a complete match. + + >>> # If the user enters another digit: + >>> print(pattern.fullmatch('12345', partial=True)) + None + >>> # It's no longer a match. + + >>> # This is a partial match: + >>> pattern.match('123', partial=True).partial + True + + >>> # This is a complete match: + >>> pattern.match('1233', partial=True).partial + False + +``*`` operator not working correctly with sub() (`Hg issue 106 `_) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Sometimes it's not clear how zero-width matches should be handled. For example, should ``.*`` match 0 characters directly after matching >0 characters? + +.. sourcecode:: python + + >>> regex.sub('.*', 'x', 'test') + 'xx' + >>> regex.sub('.*?', '|', 'test') + '|||||||||' + +Added ``capturesdict`` (`Hg issue 86 `_) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +``capturesdict`` is a combination of ``groupdict`` and ``captures``: + +``groupdict`` returns a dict of the named groups and the last capture of those groups. + +``captures`` returns a list of all the captures of a group + +``capturesdict`` returns a dict of the named groups and lists of all the captures of those groups. + +.. sourcecode:: python + + >>> m = regex.match(r"(?:(?P\w+) (?P\d+)\n)+", "one 1\ntwo 2\nthree 3\n") + >>> m.groupdict() + {'word': 'three', 'digits': '3'} + >>> m.captures("word") + ['one', 'two', 'three'] + >>> m.captures("digits") + ['1', '2', '3'] + >>> m.capturesdict() + {'word': ['one', 'two', 'three'], 'digits': ['1', '2', '3']} + +Added ``allcaptures`` and ``allspans`` (`Git issue 474 `_) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +``allcaptures`` returns a list of all the captures of all the groups. + +``allspans`` returns a list of all the spans of the all captures of all the groups. + +.. sourcecode:: python + + >>> m = regex.match(r"(?:(?P\w+) (?P\d+)\n)+", "one 1\ntwo 2\nthree 3\n") + >>> m.allcaptures() + (['one 1\ntwo 2\nthree 3\n'], ['one', 'two', 'three'], ['1', '2', '3']) + >>> m.allspans() + ([(0, 20)], [(0, 3), (6, 9), (12, 17)], [(4, 5), (10, 11), (18, 19)]) + +Allow duplicate names of groups (`Hg issue 87 `_) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Group names can be duplicated. + +.. sourcecode:: python + + >>> # With optional groups: + >>> + >>> # Both groups capture, the second capture 'overwriting' the first. + >>> m = regex.match(r"(?P\w+)? or (?P\w+)?", "first or second") + >>> m.group("item") + 'second' + >>> m.captures("item") + ['first', 'second'] + >>> # Only the second group captures. + >>> m = regex.match(r"(?P\w+)? or (?P\w+)?", " or second") + >>> m.group("item") + 'second' + >>> m.captures("item") + ['second'] + >>> # Only the first group captures. + >>> m = regex.match(r"(?P\w+)? or (?P\w+)?", "first or ") + >>> m.group("item") + 'first' + >>> m.captures("item") + ['first'] + >>> + >>> # With mandatory groups: + >>> + >>> # Both groups capture, the second capture 'overwriting' the first. + >>> m = regex.match(r"(?P\w*) or (?P\w*)?", "first or second") + >>> m.group("item") + 'second' + >>> m.captures("item") + ['first', 'second'] + >>> # Again, both groups capture, the second capture 'overwriting' the first. + >>> m = regex.match(r"(?P\w*) or (?P\w*)", " or second") + >>> m.group("item") + 'second' + >>> m.captures("item") + ['', 'second'] + >>> # And yet again, both groups capture, the second capture 'overwriting' the first. + >>> m = regex.match(r"(?P\w*) or (?P\w*)", "first or ") + >>> m.group("item") + '' + >>> m.captures("item") + ['first', ''] + +Added ``fullmatch`` (`issue #16203 `_) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +``fullmatch`` behaves like ``match``, except that it must match all of the string. + +.. sourcecode:: python + + >>> print(regex.fullmatch(r"abc", "abc").span()) + (0, 3) + >>> print(regex.fullmatch(r"abc", "abcx")) + None + >>> print(regex.fullmatch(r"abc", "abcx", endpos=3).span()) + (0, 3) + >>> print(regex.fullmatch(r"abc", "xabcy", pos=1, endpos=4).span()) + (1, 4) + >>> + >>> regex.match(r"a.*?", "abcd").group(0) + 'a' + >>> regex.fullmatch(r"a.*?", "abcd").group(0) + 'abcd' + +Added ``subf`` and ``subfn`` +^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +``subf`` and ``subfn`` are alternatives to ``sub`` and ``subn`` respectively. When passed a replacement string, they treat it as a format string. + +.. sourcecode:: python + + >>> regex.subf(r"(\w+) (\w+)", "{0} => {2} {1}", "foo bar") + 'foo bar => bar foo' + >>> regex.subf(r"(?P\w+) (?P\w+)", "{word2} {word1}", "foo bar") + 'bar foo' + +Added ``expandf`` to match object +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +``expandf`` is an alternative to ``expand``. When passed a replacement string, it treats it as a format string. + +.. sourcecode:: python + + >>> m = regex.match(r"(\w+) (\w+)", "foo bar") + >>> m.expandf("{0} => {2} {1}") + 'foo bar => bar foo' + >>> + >>> m = regex.match(r"(?P\w+) (?P\w+)", "foo bar") + >>> m.expandf("{word2} {word1}") + 'bar foo' + +Detach searched string +^^^^^^^^^^^^^^^^^^^^^^ + +A match object contains a reference to the string that was searched, via its ``string`` attribute. The ``detach_string`` method will 'detach' that string, making it available for garbage collection, which might save valuable memory if that string is very large. + +.. sourcecode:: python + + >>> m = regex.search(r"\w+", "Hello world") + >>> print(m.group()) + Hello + >>> print(m.string) + Hello world + >>> m.detach_string() + >>> print(m.group()) + Hello + >>> print(m.string) + None + +Recursive patterns (`Hg issue 27 `_) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Recursive and repeated patterns are supported. + +``(?R)`` or ``(?0)`` tries to match the entire regex recursively. ``(?1)``, ``(?2)``, etc, try to match the relevant group. + +``(?&name)`` tries to match the named group. + +.. sourcecode:: python + + >>> regex.match(r"(Tarzan|Jane) loves (?1)", "Tarzan loves Jane").groups() + ('Tarzan',) + >>> regex.match(r"(Tarzan|Jane) loves (?1)", "Jane loves Tarzan").groups() + ('Jane',) + + >>> m = regex.search(r"(\w)(?:(?R)|(\w?))\1", "kayak") + >>> m.group(0, 1, 2) + ('kayak', 'k', None) + +The first two examples show how the subpattern within the group is reused, but is _not_ itself a group. In other words, ``"(Tarzan|Jane) loves (?1)"`` is equivalent to ``"(Tarzan|Jane) loves (?:Tarzan|Jane)"``. + +It's possible to backtrack into a recursed or repeated group. + +You can't call a group if there is more than one group with that group name or group number (``"ambiguous group reference"``). + +The alternative forms ``(?P>name)`` and ``(?P&name)`` are also supported. + +Full Unicode case-folding is supported +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +In version 1 behaviour, the regex module uses full case-folding when performing case-insensitive matches in Unicode. + +.. sourcecode:: python + + >>> regex.match(r"(?iV1)strasse", "stra\N{LATIN SMALL LETTER SHARP S}e").span() + (0, 6) + >>> regex.match(r"(?iV1)stra\N{LATIN SMALL LETTER SHARP S}e", "STRASSE").span() + (0, 7) + +In version 0 behaviour, it uses simple case-folding for backward compatibility with the re module. + +Approximate "fuzzy" matching (`Hg issue 12 `_, `Hg issue 41 `_, `Hg issue 109 `_) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Regex usually attempts an exact match, but sometimes an approximate, or "fuzzy", match is needed, for those cases where the text being searched may contain errors in the form of inserted, deleted or substituted characters. + +A fuzzy regex specifies which types of errors are permitted, and, optionally, either the minimum and maximum or only the maximum permitted number of each type. (You cannot specify only a minimum.) + +The 3 types of error are: + +* Insertion, indicated by "i" + +* Deletion, indicated by "d" + +* Substitution, indicated by "s" + +In addition, "e" indicates any type of error. + +The fuzziness of a regex item is specified between "{" and "}" after the item. + +Examples: + +* ``foo`` match "foo" exactly + +* ``(?:foo){i}`` match "foo", permitting insertions + +* ``(?:foo){d}`` match "foo", permitting deletions + +* ``(?:foo){s}`` match "foo", permitting substitutions + +* ``(?:foo){i,s}`` match "foo", permitting insertions and substitutions + +* ``(?:foo){e}`` match "foo", permitting errors + +If a certain type of error is specified, then any type not specified will **not** be permitted. + +In the following examples I'll omit the item and write only the fuzziness: + +* ``{d<=3}`` permit at most 3 deletions, but no other types + +* ``{i<=1,s<=2}`` permit at most 1 insertion and at most 2 substitutions, but no deletions + +* ``{1<=e<=3}`` permit at least 1 and at most 3 errors + +* ``{i<=2,d<=2,e<=3}`` permit at most 2 insertions, at most 2 deletions, at most 3 errors in total, but no substitutions + +It's also possible to state the costs of each type of error and the maximum permitted total cost. + +Examples: + +* ``{2i+2d+1s<=4}`` each insertion costs 2, each deletion costs 2, each substitution costs 1, the total cost must not exceed 4 + +* ``{i<=1,d<=1,s<=1,2i+2d+1s<=4}`` at most 1 insertion, at most 1 deletion, at most 1 substitution; each insertion costs 2, each deletion costs 2, each substitution costs 1, the total cost must not exceed 4 + +You can also use "<" instead of "<=" if you want an exclusive minimum or maximum. + +You can add a test to perform on a character that's substituted or inserted. + +Examples: + +* ``{s<=2:[a-z]}`` at most 2 substitutions, which must be in the character set ``[a-z]``. + +* ``{s<=2,i<=3:\d}`` at most 2 substitutions, at most 3 insertions, which must be digits. + +By default, fuzzy matching searches for the first match that meets the given constraints. The ``ENHANCEMATCH`` flag will cause it to attempt to improve the fit (i.e. reduce the number of errors) of the match that it has found. + +The ``BESTMATCH`` flag will make it search for the best match instead. + +Further examples to note: + +* ``regex.search("(dog){e}", "cat and dog")[1]`` returns ``"cat"`` because that matches ``"dog"`` with 3 errors (an unlimited number of errors is permitted). + +* ``regex.search("(dog){e<=1}", "cat and dog")[1]`` returns ``" dog"`` (with a leading space) because that matches ``"dog"`` with 1 error, which is within the limit. + +* ``regex.search("(?e)(dog){e<=1}", "cat and dog")[1]`` returns ``"dog"`` (without a leading space) because the fuzzy search matches ``" dog"`` with 1 error, which is within the limit, and the ``(?e)`` then it attempts a better fit. + +In the first two examples there are perfect matches later in the string, but in neither case is it the first possible match. + +The match object has an attribute ``fuzzy_counts`` which gives the total number of substitutions, insertions and deletions. + +.. sourcecode:: python + + >>> # A 'raw' fuzzy match: + >>> regex.fullmatch(r"(?:cats|cat){e<=1}", "cat").fuzzy_counts + (0, 0, 1) + >>> # 0 substitutions, 0 insertions, 1 deletion. + + >>> # A better match might be possible if the ENHANCEMATCH flag used: + >>> regex.fullmatch(r"(?e)(?:cats|cat){e<=1}", "cat").fuzzy_counts + (0, 0, 0) + >>> # 0 substitutions, 0 insertions, 0 deletions. + +The match object also has an attribute ``fuzzy_changes`` which gives a tuple of the positions of the substitutions, insertions and deletions. + +.. sourcecode:: python + + >>> m = regex.search('(fuu){i<=2,d<=2,e<=5}', 'anaconda foo bar') + >>> m + + >>> m.fuzzy_changes + ([], [7, 8], [10, 11]) + +What this means is that if the matched part of the string had been: + +.. sourcecode:: python + + 'anacondfuuoo bar' + +it would've been an exact match. + +However, there were insertions at positions 7 and 8: + +.. sourcecode:: python + + 'anaconda fuuoo bar' + ^^ + +and deletions at positions 10 and 11: + +.. sourcecode:: python + + 'anaconda f~~oo bar' + ^^ + +So the actual string was: + +.. sourcecode:: python + + 'anaconda foo bar' + +Named lists ``\L`` (`Hg issue 11 `_) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +There are occasions where you may want to include a list (actually, a set) of options in a regex. + +One way is to build the pattern like this: + +.. sourcecode:: python + + >>> p = regex.compile(r"first|second|third|fourth|fifth") + +but if the list is large, parsing the resulting regex can take considerable time, and care must also be taken that the strings are properly escaped and properly ordered, for example, "cats" before "cat". + +The new alternative is to use a named list: + +.. sourcecode:: python + + >>> option_set = ["first", "second", "third", "fourth", "fifth"] + >>> p = regex.compile(r"\L", options=option_set) + +The order of the items is irrelevant, they are treated as a set. The named lists are available as the ``.named_lists`` attribute of the pattern object : + +.. sourcecode:: python + + >>> print(p.named_lists) + {'options': frozenset({'third', 'first', 'fifth', 'fourth', 'second'})} + +If there are any unused keyword arguments, ``ValueError`` will be raised unless you tell it otherwise: + +.. sourcecode:: python + + >>> option_set = ["first", "second", "third", "fourth", "fifth"] + >>> p = regex.compile(r"\L", options=option_set, other_options=[]) + Traceback (most recent call last): + File "", line 1, in + File "C:\Python310\lib\site-packages\regex\regex.py", line 353, in compile + return _compile(pattern, flags, ignore_unused, kwargs, cache_pattern) + File "C:\Python310\lib\site-packages\regex\regex.py", line 500, in _compile + complain_unused_args() + File "C:\Python310\lib\site-packages\regex\regex.py", line 483, in complain_unused_args + raise ValueError('unused keyword argument {!a}'.format(any_one)) + ValueError: unused keyword argument 'other_options' + >>> p = regex.compile(r"\L", options=option_set, other_options=[], ignore_unused=True) + >>> p = regex.compile(r"\L", options=option_set, other_options=[], ignore_unused=False) + Traceback (most recent call last): + File "", line 1, in + File "C:\Python310\lib\site-packages\regex\regex.py", line 353, in compile + return _compile(pattern, flags, ignore_unused, kwargs, cache_pattern) + File "C:\Python310\lib\site-packages\regex\regex.py", line 500, in _compile + complain_unused_args() + File "C:\Python310\lib\site-packages\regex\regex.py", line 483, in complain_unused_args + raise ValueError('unused keyword argument {!a}'.format(any_one)) + ValueError: unused keyword argument 'other_options' + >>> + +Start and end of word +^^^^^^^^^^^^^^^^^^^^^ + +``\m`` matches at the start of a word. + +``\M`` matches at the end of a word. + +Compare with ``\b``, which matches at the start or end of a word. + +Unicode line separators +^^^^^^^^^^^^^^^^^^^^^^^ + +Normally the only line separator is ``\n`` (``\x0A``), but if the ``WORD`` flag is turned on then the line separators are ``\x0D\x0A``, ``\x0A``, ``\x0B``, ``\x0C`` and ``\x0D``, plus ``\x85``, ``\u2028`` and ``\u2029`` when working with Unicode. + +This affects the regex dot ``"."``, which, with the ``DOTALL`` flag turned off, matches any character except a line separator. It also affects the line anchors ``^`` and ``$`` (in multiline mode). + +Set operators +^^^^^^^^^^^^^ + +**Version 1 behaviour only** + +Set operators have been added, and a set ``[...]`` can include nested sets. + +The operators, in order of increasing precedence, are: + +* ``||`` for union ("x||y" means "x or y") + +* ``~~`` (double tilde) for symmetric difference ("x~~y" means "x or y, but not both") + +* ``&&`` for intersection ("x&&y" means "x and y") + +* ``--`` (double dash) for difference ("x--y" means "x but not y") + +Implicit union, ie, simple juxtaposition like in ``[ab]``, has the highest precedence. Thus, ``[ab&&cd]`` is the same as ``[[a||b]&&[c||d]]``. + +Examples: + +* ``[ab]`` # Set containing 'a' and 'b' + +* ``[a-z]`` # Set containing 'a' .. 'z' + +* ``[[a-z]--[qw]]`` # Set containing 'a' .. 'z', but not 'q' or 'w' + +* ``[a-z--qw]`` # Same as above + +* ``[\p{L}--QW]`` # Set containing all letters except 'Q' and 'W' + +* ``[\p{N}--[0-9]]`` # Set containing all numbers except '0' .. '9' + +* ``[\p{ASCII}&&\p{Letter}]`` # Set containing all characters which are ASCII and letter + +regex.escape (`issue #2650 `_) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +regex.escape has an additional keyword parameter ``special_only``. When True, only 'special' regex characters, such as '?', are escaped. + +.. sourcecode:: python + + >>> regex.escape("foo!?", special_only=False) + 'foo\\!\\?' + >>> regex.escape("foo!?", special_only=True) + 'foo!\\?' + +regex.escape (`Hg issue 249 `_) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +regex.escape has an additional keyword parameter ``literal_spaces``. When True, spaces are not escaped. + +.. sourcecode:: python + + >>> regex.escape("foo bar!?", literal_spaces=False) + 'foo\\ bar!\\?' + >>> regex.escape("foo bar!?", literal_spaces=True) + 'foo bar!\\?' + +Repeated captures (`issue #7132 `_) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +A match object has additional methods which return information on all the successful matches of a repeated group. These methods are: + +* ``matchobject.captures([group1, ...])`` + + * Returns a list of the strings matched in a group or groups. Compare with ``matchobject.group([group1, ...])``. + +* ``matchobject.starts([group])`` + + * Returns a list of the start positions. Compare with ``matchobject.start([group])``. + +* ``matchobject.ends([group])`` + + * Returns a list of the end positions. Compare with ``matchobject.end([group])``. + +* ``matchobject.spans([group])`` + + * Returns a list of the spans. Compare with ``matchobject.span([group])``. + +.. sourcecode:: python + + >>> m = regex.search(r"(\w{3})+", "123456789") + >>> m.group(1) + '789' + >>> m.captures(1) + ['123', '456', '789'] + >>> m.start(1) + 6 + >>> m.starts(1) + [0, 3, 6] + >>> m.end(1) + 9 + >>> m.ends(1) + [3, 6, 9] + >>> m.span(1) + (6, 9) + >>> m.spans(1) + [(0, 3), (3, 6), (6, 9)] + +Atomic grouping ``(?>...)`` (`issue #433030 `_) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +If the following pattern subsequently fails, then the subpattern as a whole will fail. + +Possessive quantifiers +^^^^^^^^^^^^^^^^^^^^^^ + +``(?:...)?+`` ; ``(?:...)*+`` ; ``(?:...)++`` ; ``(?:...){min,max}+`` + +The subpattern is matched up to 'max' times. If the following pattern subsequently fails, then all the repeated subpatterns will fail as a whole. For example, ``(?:...)++`` is equivalent to ``(?>(?:...)+)``. + +Scoped flags (`issue #433028 `_) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +``(?flags-flags:...)`` + +The flags will apply only to the subpattern. Flags can be turned on or off. + +Definition of 'word' character (`issue #1693050 `_) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The definition of a 'word' character has been expanded for Unicode. It conforms to the Unicode specification at ``http://www.unicode.org/reports/tr29/``. + +Variable-length lookbehind +^^^^^^^^^^^^^^^^^^^^^^^^^^ + +A lookbehind can match a variable-length string. + +Flags argument for regex.split, regex.sub and regex.subn (`issue #3482 `_) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +``regex.split``, ``regex.sub`` and ``regex.subn`` support a 'flags' argument. + +Pos and endpos arguments for regex.sub and regex.subn +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +``regex.sub`` and ``regex.subn`` support 'pos' and 'endpos' arguments. + +'Overlapped' argument for regex.findall and regex.finditer +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +``regex.findall`` and ``regex.finditer`` support an 'overlapped' flag which permits overlapped matches. + +Splititer +^^^^^^^^^ + +``regex.splititer`` has been added. It's a generator equivalent of ``regex.split``. + +Subscripting match objects for groups +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +A match object accepts access to the groups via subscripting and slicing: + +.. sourcecode:: python + + >>> m = regex.search(r"(?P.*?)(?P\d+)(?P.*)", "pqr123stu") + >>> print(m["before"]) + pqr + >>> print(len(m)) + 4 + >>> print(m[:]) + ('pqr123stu', 'pqr', '123', 'stu') + +Named groups +^^^^^^^^^^^^ + +Groups can be named with ``(?...)`` as well as the existing ``(?P...)``. + +Group references +^^^^^^^^^^^^^^^^ + +Groups can be referenced within a pattern with ``\g``. This also allows there to be more than 99 groups. + +Named characters ``\N{name}`` +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Named characters are supported. Note that only those known by Python's Unicode database will be recognised. + +Unicode codepoint properties, including scripts and blocks +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +``\p{property=value}``; ``\P{property=value}``; ``\p{value}`` ; ``\P{value}`` + +Many Unicode properties are supported, including blocks and scripts. ``\p{property=value}`` or ``\p{property:value}`` matches a character whose property ``property`` has value ``value``. The inverse of ``\p{property=value}`` is ``\P{property=value}`` or ``\p{^property=value}``. + +If the short form ``\p{value}`` is used, the properties are checked in the order: ``General_Category``, ``Script``, ``Block``, binary property: + +* ``Latin``, the 'Latin' script (``Script=Latin``). + +* ``BasicLatin``, the 'BasicLatin' block (``Block=BasicLatin``). + +* ``Alphabetic``, the 'Alphabetic' binary property (``Alphabetic=Yes``). + +A short form starting with ``Is`` indicates a script or binary property: + +* ``IsLatin``, the 'Latin' script (``Script=Latin``). + +* ``IsAlphabetic``, the 'Alphabetic' binary property (``Alphabetic=Yes``). + +A short form starting with ``In`` indicates a block property: + +* ``InBasicLatin``, the 'BasicLatin' block (``Block=BasicLatin``). + +POSIX character classes +^^^^^^^^^^^^^^^^^^^^^^^ + +``[[:alpha:]]``; ``[[:^alpha:]]`` + +POSIX character classes are supported. These are normally treated as an alternative form of ``\p{...}``. + +The exceptions are ``alnum``, ``digit``, ``punct`` and ``xdigit``, whose definitions are different from those of Unicode. + +``[[:alnum:]]`` is equivalent to ``\p{posix_alnum}``. + +``[[:digit:]]`` is equivalent to ``\p{posix_digit}``. + +``[[:punct:]]`` is equivalent to ``\p{posix_punct}``. + +``[[:xdigit:]]`` is equivalent to ``\p{posix_xdigit}``. + +Search anchor ``\G`` +^^^^^^^^^^^^^^^^^^^^ + +A search anchor has been added. It matches at the position where each search started/continued and can be used for contiguous matches or in negative variable-length lookbehinds to limit how far back the lookbehind goes: + +.. sourcecode:: python + + >>> regex.findall(r"\w{2}", "abcd ef") + ['ab', 'cd', 'ef'] + >>> regex.findall(r"\G\w{2}", "abcd ef") + ['ab', 'cd'] + +* The search starts at position 0 and matches 'ab'. + +* The search continues at position 2 and matches 'cd'. + +* The search continues at position 4 and fails to match any letters. + +* The anchor stops the search start position from being advanced, so there are no more results. + +Reverse searching +^^^^^^^^^^^^^^^^^ + +Searches can also work backwards: + +.. sourcecode:: python + + >>> regex.findall(r".", "abc") + ['a', 'b', 'c'] + >>> regex.findall(r"(?r).", "abc") + ['c', 'b', 'a'] + +Note that the result of a reverse search is not necessarily the reverse of a forward search: + +.. sourcecode:: python + + >>> regex.findall(r"..", "abcde") + ['ab', 'cd'] + >>> regex.findall(r"(?r)..", "abcde") + ['de', 'bc'] + +Matching a single grapheme ``\X`` +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The grapheme matcher is supported. It conforms to the Unicode specification at ``http://www.unicode.org/reports/tr29/``. + +Branch reset ``(?|...|...)`` +^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Group numbers will be reused across the alternatives, but groups with different names will have different group numbers. + +.. sourcecode:: python + + >>> regex.match(r"(?|(first)|(second))", "first").groups() + ('first',) + >>> regex.match(r"(?|(first)|(second))", "second").groups() + ('second',) + +Note that there is only one group. + +Default Unicode word boundary +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The ``WORD`` flag changes the definition of a 'word boundary' to that of a default Unicode word boundary. This applies to ``\b`` and ``\B``. + +Timeout +^^^^^^^ + +The matching methods and functions support timeouts. The timeout (in seconds) applies to the entire operation: + +.. sourcecode:: python + + >>> from time import sleep + >>> + >>> def fast_replace(m): + ... return 'X' + ... + >>> def slow_replace(m): + ... sleep(0.5) + ... return 'X' + ... + >>> regex.sub(r'[a-z]', fast_replace, 'abcde', timeout=2) + 'XXXXX' + >>> regex.sub(r'[a-z]', slow_replace, 'abcde', timeout=2) + Traceback (most recent call last): + File "", line 1, in + File "C:\Python310\lib\site-packages\regex\regex.py", line 278, in sub + return pat.sub(repl, string, count, pos, endpos, concurrent, timeout) + TimeoutError: regex timed out diff --git a/TTS/Kokoro/.venv/Lib/site-packages/regex-2026.2.19.dist-info/RECORD b/TTS/Kokoro/.venv/Lib/site-packages/regex-2026.2.19.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..6ee8cede461910ca7da51d7a310d4917683b11b7 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/regex-2026.2.19.dist-info/RECORD @@ -0,0 +1,15 @@ +regex-2026.2.19.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +regex-2026.2.19.dist-info/METADATA,sha256=IsUhlAb8szeTtEKrE5SaRjNDsjFF-Z1YyrXMBgUEn_8,41476 +regex-2026.2.19.dist-info/RECORD,, +regex-2026.2.19.dist-info/WHEEL,sha256=-GHpayM8oxmVQ6lwBZOCUBihymZgdGGr6p98RT74444,101 +regex-2026.2.19.dist-info/licenses/LICENSE.txt,sha256=PSIMBllLgmu6vxEDEvYPOF-Z5X5Sn6S55Tb3kJH4tMc,11792 +regex-2026.2.19.dist-info/top_level.txt,sha256=aQmiDMhNTF26cCK4_7D-qaVvhbxClG0wyCTnEhkzYBs,6 +regex/__init__.py,sha256=K0DzoWlqFh5039Pujrkm1NZ_rc2xhRenbfBthB06W48,78 +regex/__pycache__/__init__.cpython-312.pyc,, +regex/__pycache__/_main.cpython-312.pyc,, +regex/__pycache__/_regex_core.cpython-312.pyc,, +regex/_main.py,sha256=g9UcmCWh_Emj9zLpsc0RkSdw2wLuoPzD1RXnF6NG5LE,34100 +regex/_regex.cp312-win_amd64.pyd,sha256=DAgplDYv2VnsNqcfSkNPWHZeJVUCjLYab7kE6Gd6tEI,725504 +regex/_regex_core.py,sha256=JqytYkXE_iuuDc_nmNHlvOqyZU-Lr-u4FSki2zPzM8s,152050 +regex/tests/__pycache__/test_regex.cpython-312.pyc,, +regex/tests/test_regex.py,sha256=6eTTXBYB12CNVIklDLs4PpYhgzlV_7HysBgCBwqsato,230349 diff --git a/TTS/Kokoro/.venv/Lib/site-packages/regex-2026.2.19.dist-info/WHEEL b/TTS/Kokoro/.venv/Lib/site-packages/regex-2026.2.19.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..2b2c55260c2206183c46b40a94fc421bb6f84594 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/regex-2026.2.19.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (82.0.0) +Root-Is-Purelib: false +Tag: cp312-cp312-win_amd64 + diff --git a/TTS/Kokoro/.venv/Lib/site-packages/regex-2026.2.19.dist-info/top_level.txt b/TTS/Kokoro/.venv/Lib/site-packages/regex-2026.2.19.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..4f9256d62325c75de027d1cd48f1ff520117413e --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/regex-2026.2.19.dist-info/top_level.txt @@ -0,0 +1 @@ +regex diff --git a/TTS/Kokoro/.venv/Lib/site-packages/regex/__init__.py b/TTS/Kokoro/.venv/Lib/site-packages/regex/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a09c5be0ca624842db12ba39ce4f0d8d890b3a0f --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/regex/__init__.py @@ -0,0 +1,3 @@ +import regex._main +from regex._main import * +__all__ = regex._main.__all__ diff --git a/TTS/Kokoro/.venv/Lib/site-packages/regex/_main.py b/TTS/Kokoro/.venv/Lib/site-packages/regex/_main.py new file mode 100644 index 0000000000000000000000000000000000000000..878ca25a0f2673a5499e699c0f14137bba2a65ea --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/regex/_main.py @@ -0,0 +1,756 @@ +# +# Secret Labs' Regular Expression Engine +# +# Copyright (c) 1998-2001 by Secret Labs AB. All rights reserved. +# +# This version of the SRE library can be redistributed under CNRI's +# Python 1.6 license. For any other use, please contact Secret Labs +# AB (info@pythonware.com). +# +# Portions of this engine have been developed in cooperation with +# CNRI. Hewlett-Packard provided funding for 1.6 integration and +# other compatibility work. +# +# 2010-01-16 mrab Python front-end re-written and extended + +r"""Support for regular expressions (RE). + +This module provides regular expression matching operations similar to those +found in Perl. It supports both 8-bit and Unicode strings; both the pattern and +the strings being processed can contain null bytes and characters outside the +US ASCII range. + +Regular expressions can contain both special and ordinary characters. Most +ordinary characters, like "A", "a", or "0", are the simplest regular +expressions; they simply match themselves. You can concatenate ordinary +characters, so last matches the string 'last'. + +There are a few differences between the old (legacy) behaviour and the new +(enhanced) behaviour, which are indicated by VERSION0 or VERSION1. + +The special characters are: + "." Matches any character except a newline. + "^" Matches the start of the string. + "$" Matches the end of the string or just before the + newline at the end of the string. + "*" Matches 0 or more (greedy) repetitions of the preceding + RE. Greedy means that it will match as many repetitions + as possible. + "+" Matches 1 or more (greedy) repetitions of the preceding + RE. + "?" Matches 0 or 1 (greedy) of the preceding RE. + *?,+?,?? Non-greedy versions of the previous three special + characters. + *+,++,?+ Possessive versions of the previous three special + characters. + {m,n} Matches from m to n repetitions of the preceding RE. + {m,n}? Non-greedy version of the above. + {m,n}+ Possessive version of the above. + {...} Fuzzy matching constraints. + "\\" Either escapes special characters or signals a special + sequence. + [...] Indicates a set of characters. A "^" as the first + character indicates a complementing set. + "|" A|B, creates an RE that will match either A or B. + (...) Matches the RE inside the parentheses. The contents are + captured and can be retrieved or matched later in the + string. + (?flags-flags) VERSION1: Sets/clears the flags for the remainder of + the group or pattern; VERSION0: Sets the flags for the + entire pattern. + (?:...) Non-capturing version of regular parentheses. + (?>...) Atomic non-capturing version of regular parentheses. + (?flags-flags:...) Non-capturing version of regular parentheses with local + flags. + (?P...) The substring matched by the group is accessible by + name. + (?...) The substring matched by the group is accessible by + name. + (?P=name) Matches the text matched earlier by the group named + name. + (?#...) A comment; ignored. + (?=...) Matches if ... matches next, but doesn't consume the + string. + (?!...) Matches if ... doesn't match next. + (?<=...) Matches if preceded by .... + (? Matches the text matched by the group named name. + \G Matches the empty string, but only at the position where + the search started. + \h Matches horizontal whitespace. + \K Keeps only what follows for the entire match. + \L Named list. The list is provided as a keyword argument. + \m Matches the empty string, but only at the start of a word. + \M Matches the empty string, but only at the end of a word. + \n Matches the newline character. + \N{name} Matches the named character. + \p{name=value} Matches the character if its property has the specified + value. + \P{name=value} Matches the character if its property hasn't the specified + value. + \r Matches the carriage-return character. + \s Matches any whitespace character; equivalent to + [ \t\n\r\f\v]. + \S Matches any non-whitespace character; equivalent to [^\s]. + \t Matches the tab character. + \uXXXX Matches the Unicode codepoint with 4-digit hex code XXXX. + \UXXXXXXXX Matches the Unicode codepoint with 8-digit hex code + XXXXXXXX. + \v Matches the vertical tab character. + \w Matches any alphanumeric character; equivalent to + [a-zA-Z0-9_] when matching a bytestring or a Unicode string + with the ASCII flag, or the whole range of Unicode + alphanumeric characters (letters plus digits plus + underscore) when matching a Unicode string. With LOCALE, it + will match the set [0-9_] plus characters defined as + letters for the current locale. + \W Matches the complement of \w; equivalent to [^\w]. + \xXX Matches the character with 2-digit hex code XX. + \X Matches a grapheme. + \Z Matches only at the end of the string. + \z Matches only at the end of the string. Alias of \Z. + \\ Matches a literal backslash. + +This module exports the following functions: + match Match a regular expression pattern at the beginning of a string. + prefixmatch Match a regular expression pattern at the beginning of a string. + Alias of match. + fullmatch Match a regular expression pattern against all of a string. + search Search a string for the presence of a pattern. + sub Substitute occurrences of a pattern found in a string using a + template string. + subf Substitute occurrences of a pattern found in a string using a + format string. + subn Same as sub, but also return the number of substitutions made. + subfn Same as subf, but also return the number of substitutions made. + split Split a string by the occurrences of a pattern. VERSION1: will + split at zero-width match; VERSION0: won't split at zero-width + match. + splititer Return an iterator yielding the parts of a split string. + findall Find all occurrences of a pattern in a string. + finditer Return an iterator yielding a match object for each match. + compile Compile a pattern into a Pattern object. + purge Clear the regular expression cache. + escape Backslash all non-alphanumerics or special characters in a + string. + +Most of the functions support a concurrent parameter: if True, the GIL will be +released during matching, allowing other Python threads to run concurrently. If +the string changes during matching, the behaviour is undefined. This parameter +is not needed when working on the builtin (immutable) string classes. + +Some of the functions in this module take flags as optional parameters. Most of +these flags can also be set within an RE: + A a ASCII Make \w, \W, \b, \B, \d, and \D match the + corresponding ASCII character categories. Default + when matching a bytestring. + B b BESTMATCH Find the best fuzzy match (default is first). + D DEBUG Print the parsed pattern. + E e ENHANCEMATCH Attempt to improve the fit after finding the first + fuzzy match. + F f FULLCASE Use full case-folding when performing + case-insensitive matching in Unicode. + I i IGNORECASE Perform case-insensitive matching. + L L LOCALE Make \w, \W, \b, \B, \d, and \D dependent on the + current locale. (One byte per character only.) + M m MULTILINE "^" matches the beginning of lines (after a newline) + as well as the string. "$" matches the end of lines + (before a newline) as well as the end of the string. + P p POSIX Perform POSIX-standard matching (leftmost longest). + R r REVERSE Searches backwards. + S s DOTALL "." matches any character at all, including the + newline. + U u UNICODE Make \w, \W, \b, \B, \d, and \D dependent on the + Unicode locale. Default when matching a Unicode + string. + V0 V0 VERSION0 Turn on the old legacy behaviour. + V1 V1 VERSION1 Turn on the new enhanced behaviour. This flag + includes the FULLCASE flag. + W w WORD Make \b and \B work with default Unicode word breaks + and make ".", "^" and "$" work with Unicode line + breaks. + X x VERBOSE Ignore whitespace and comments for nicer looking REs. + +This module also defines an exception 'error'. + +""" + +# Public symbols. +__all__ = ["cache_all", "compile", "DEFAULT_VERSION", "escape", "findall", + "finditer", "fullmatch", "match", "prefixmatch", "purge", "search", "split", "splititer", + "sub", "subf", "subfn", "subn", "template", "Scanner", "A", "ASCII", "B", + "BESTMATCH", "D", "DEBUG", "E", "ENHANCEMATCH", "S", "DOTALL", "F", + "FULLCASE", "I", "IGNORECASE", "L", "LOCALE", "M", "MULTILINE", "P", "POSIX", + "R", "REVERSE", "T", "TEMPLATE", "U", "UNICODE", "V0", "VERSION0", "V1", + "VERSION1", "X", "VERBOSE", "W", "WORD", "error", "Regex", "__version__", + "__doc__", "RegexFlag"] + +__version__ = "2026.2.19" + +# -------------------------------------------------------------------- +# Public interface. + +def match(pattern, string, flags=0, pos=None, endpos=None, partial=False, + concurrent=None, timeout=None, ignore_unused=False, **kwargs): + """Try to apply the pattern at the start of the string, returning a match + object, or None if no match was found.""" + pat = _compile(pattern, flags, ignore_unused, kwargs, True) + return pat.match(string, pos, endpos, concurrent, partial, timeout) + +def prefixmatch(pattern, string, flags=0, pos=None, endpos=None, partial=False, + concurrent=None, timeout=None, ignore_unused=False, **kwargs): + """Try to apply the pattern at the start of the string, returning a match + object, or None if no match was found. Alias of match().""" + pat = _compile(pattern, flags, ignore_unused, kwargs, True) + return pat.match(string, pos, endpos, concurrent, partial, timeout) + +def fullmatch(pattern, string, flags=0, pos=None, endpos=None, partial=False, + concurrent=None, timeout=None, ignore_unused=False, **kwargs): + """Try to apply the pattern against all of the string, returning a match + object, or None if no match was found.""" + pat = _compile(pattern, flags, ignore_unused, kwargs, True) + return pat.fullmatch(string, pos, endpos, concurrent, partial, timeout) + +def search(pattern, string, flags=0, pos=None, endpos=None, partial=False, + concurrent=None, timeout=None, ignore_unused=False, **kwargs): + """Search through string looking for a match to the pattern, returning a + match object, or None if no match was found.""" + pat = _compile(pattern, flags, ignore_unused, kwargs, True) + return pat.search(string, pos, endpos, concurrent, partial, timeout) + +def sub(pattern, repl, string, count=0, flags=0, pos=None, endpos=None, + concurrent=None, timeout=None, ignore_unused=False, **kwargs): + """Return the string obtained by replacing the leftmost (or rightmost with a + reverse pattern) non-overlapping occurrences of the pattern in string by the + replacement repl. repl can be either a string or a callable; if a string, + backslash escapes in it are processed; if a callable, it's passed the match + object and must return a replacement string to be used.""" + pat = _compile(pattern, flags, ignore_unused, kwargs, True) + return pat.sub(repl, string, count, pos, endpos, concurrent, timeout) + +def subf(pattern, format, string, count=0, flags=0, pos=None, endpos=None, + concurrent=None, timeout=None, ignore_unused=False, **kwargs): + """Return the string obtained by replacing the leftmost (or rightmost with a + reverse pattern) non-overlapping occurrences of the pattern in string by the + replacement format. format can be either a string or a callable; if a string, + it's treated as a format string; if a callable, it's passed the match object + and must return a replacement string to be used.""" + pat = _compile(pattern, flags, ignore_unused, kwargs, True) + return pat.subf(format, string, count, pos, endpos, concurrent, timeout) + +def subn(pattern, repl, string, count=0, flags=0, pos=None, endpos=None, + concurrent=None, timeout=None, ignore_unused=False, **kwargs): + """Return a 2-tuple containing (new_string, number). new_string is the string + obtained by replacing the leftmost (or rightmost with a reverse pattern) + non-overlapping occurrences of the pattern in the source string by the + replacement repl. number is the number of substitutions that were made. repl + can be either a string or a callable; if a string, backslash escapes in it + are processed; if a callable, it's passed the match object and must return a + replacement string to be used.""" + pat = _compile(pattern, flags, ignore_unused, kwargs, True) + return pat.subn(repl, string, count, pos, endpos, concurrent, timeout) + +def subfn(pattern, format, string, count=0, flags=0, pos=None, endpos=None, + concurrent=None, timeout=None, ignore_unused=False, **kwargs): + """Return a 2-tuple containing (new_string, number). new_string is the string + obtained by replacing the leftmost (or rightmost with a reverse pattern) + non-overlapping occurrences of the pattern in the source string by the + replacement format. number is the number of substitutions that were made. format + can be either a string or a callable; if a string, it's treated as a format + string; if a callable, it's passed the match object and must return a + replacement string to be used.""" + pat = _compile(pattern, flags, ignore_unused, kwargs, True) + return pat.subfn(format, string, count, pos, endpos, concurrent, timeout) + +def split(pattern, string, maxsplit=0, flags=0, concurrent=None, timeout=None, + ignore_unused=False, **kwargs): + """Split the source string by the occurrences of the pattern, returning a + list containing the resulting substrings. If capturing parentheses are used + in pattern, then the text of all groups in the pattern are also returned as + part of the resulting list. If maxsplit is nonzero, at most maxsplit splits + occur, and the remainder of the string is returned as the final element of + the list.""" + pat = _compile(pattern, flags, ignore_unused, kwargs, True) + return pat.split(string, maxsplit, concurrent, timeout) + +def splititer(pattern, string, maxsplit=0, flags=0, concurrent=None, + timeout=None, ignore_unused=False, **kwargs): + "Return an iterator yielding the parts of a split string." + pat = _compile(pattern, flags, ignore_unused, kwargs, True) + return pat.splititer(string, maxsplit, concurrent, timeout) + +def findall(pattern, string, flags=0, pos=None, endpos=None, overlapped=False, + concurrent=None, timeout=None, ignore_unused=False, **kwargs): + """Return a list of all matches in the string. The matches may be overlapped + if overlapped is True. If one or more groups are present in the pattern, + return a list of groups; this will be a list of tuples if the pattern has + more than one group. Empty matches are included in the result.""" + pat = _compile(pattern, flags, ignore_unused, kwargs, True) + return pat.findall(string, pos, endpos, overlapped, concurrent, timeout) + +def finditer(pattern, string, flags=0, pos=None, endpos=None, overlapped=False, + partial=False, concurrent=None, timeout=None, ignore_unused=False, **kwargs): + """Return an iterator over all matches in the string. The matches may be + overlapped if overlapped is True. For each match, the iterator returns a + match object. Empty matches are included in the result.""" + pat = _compile(pattern, flags, ignore_unused, kwargs, True) + return pat.finditer(string, pos, endpos, overlapped, concurrent, partial, + timeout) + +def compile(pattern, flags=0, ignore_unused=False, cache_pattern=None, **kwargs): + "Compile a regular expression pattern, returning a pattern object." + if cache_pattern is None: + cache_pattern = _cache_all + return _compile(pattern, flags, ignore_unused, kwargs, cache_pattern) + +def purge(): + "Clear the regular expression cache" + _cache.clear() + _locale_sensitive.clear() + +# Whether to cache all patterns. +_cache_all = True + +def cache_all(value=True): + """Sets whether to cache all patterns, even those are compiled explicitly. + Passing None has no effect, but returns the current setting.""" + global _cache_all + + if value is None: + return _cache_all + + _cache_all = value + +def template(pattern, flags=0): + "Compile a template pattern, returning a pattern object." + return _compile(pattern, flags | TEMPLATE, False, {}, False) + +def escape(pattern, special_only=True, literal_spaces=False): + """Escape a string for use as a literal in a pattern. If special_only is + True, escape only special characters, else escape all non-alphanumeric + characters. If literal_spaces is True, don't escape spaces.""" + # Convert it to Unicode. + if isinstance(pattern, bytes): + p = pattern.decode("latin-1") + else: + p = pattern + + s = [] + if special_only: + for c in p: + if c == " " and literal_spaces: + s.append(c) + elif c in _METACHARS or c.isspace(): + s.append("\\") + s.append(c) + else: + s.append(c) + else: + for c in p: + if c == " " and literal_spaces: + s.append(c) + elif c in _ALNUM: + s.append(c) + else: + s.append("\\") + s.append(c) + + r = "".join(s) + # Convert it back to bytes if necessary. + if isinstance(pattern, bytes): + r = r.encode("latin-1") + + return r + +# -------------------------------------------------------------------- +# Internals. + +from regex import _regex_core +from regex import _regex +from threading import RLock as _RLock +from locale import getpreferredencoding as _getpreferredencoding +from regex._regex_core import * +from regex._regex_core import (_ALL_VERSIONS, _ALL_ENCODINGS, _FirstSetError, + _UnscopedFlagSet, _check_group_features, _compile_firstset, + _compile_replacement, _flatten_code, _fold_case, _get_required_string, + _parse_pattern, _shrink_cache) +from regex._regex_core import (ALNUM as _ALNUM, Info as _Info, OP as _OP, Source + as _Source, Fuzzy as _Fuzzy) + +# Version 0 is the old behaviour, compatible with the original 're' module. +# Version 1 is the new behaviour, which differs slightly. + +DEFAULT_VERSION = RegexFlag.VERSION0 + +_METACHARS = frozenset("()[]{}?*+|^$\\.-#&~") + +_regex_core.DEFAULT_VERSION = DEFAULT_VERSION + +# Caches for the patterns and replacements. +_cache = {} +_cache_lock = _RLock() +_named_args = {} +_replacement_cache = {} +_locale_sensitive = {} + +# Maximum size of the cache. +_MAXCACHE = 500 +_MAXREPCACHE = 500 + +def _compile(pattern, flags, ignore_unused, kwargs, cache_it): + "Compiles a regular expression to a PatternObject." + + global DEFAULT_VERSION + try: + from regex import DEFAULT_VERSION + except ImportError: + pass + + # We won't bother to cache the pattern if we're debugging. + if (flags & DEBUG) != 0: + cache_it = False + + # What locale is this pattern using? + locale_key = (type(pattern), pattern) + if _locale_sensitive.get(locale_key, True) or (flags & LOCALE) != 0: + # This pattern is, or might be, locale-sensitive. + pattern_locale = _getpreferredencoding() + else: + # This pattern is definitely not locale-sensitive. + pattern_locale = None + + def complain_unused_args(): + if ignore_unused: + return + + # Complain about any unused keyword arguments, possibly resulting from a typo. + unused_kwargs = set(kwargs) - {k for k, v in args_needed} + if unused_kwargs: + any_one = next(iter(unused_kwargs)) + raise ValueError('unused keyword argument {!a}'.format(any_one)) + + if cache_it: + try: + # Do we know what keyword arguments are needed? + args_key = pattern, type(pattern), flags + args_needed = _named_args[args_key] + + # Are we being provided with its required keyword arguments? + args_supplied = set() + if args_needed: + for k, v in args_needed: + try: + args_supplied.add((k, frozenset(kwargs[k]))) + except KeyError: + raise error("missing named list: {!r}".format(k)) + + complain_unused_args() + + args_supplied = frozenset(args_supplied) + + # Have we already seen this regular expression and named list? + pattern_key = (pattern, type(pattern), flags, args_supplied, + DEFAULT_VERSION, pattern_locale) + return _cache[pattern_key] + except KeyError: + # It's a new pattern, or new named list for a known pattern. + pass + + # Guess the encoding from the class of the pattern string. + if isinstance(pattern, str): + guess_encoding = UNICODE + elif isinstance(pattern, bytes): + guess_encoding = ASCII + elif isinstance(pattern, Pattern): + if flags: + raise ValueError("cannot process flags argument with a compiled pattern") + + return pattern + else: + raise TypeError("first argument must be a string or compiled pattern") + + # Set the default version in the core code in case it has been changed. + _regex_core.DEFAULT_VERSION = DEFAULT_VERSION + + global_flags = flags + + while True: + caught_exception = None + try: + source = _Source(pattern) + info = _Info(global_flags, source.char_type, kwargs) + info.guess_encoding = guess_encoding + source.ignore_space = bool(info.flags & VERBOSE) + parsed = _parse_pattern(source, info) + break + except _UnscopedFlagSet: + # Remember the global flags for the next attempt. + global_flags = info.global_flags + except error as e: + caught_exception = e + + if caught_exception: + raise error(caught_exception.msg, caught_exception.pattern, + caught_exception.pos) + + if not source.at_end(): + raise error("unbalanced parenthesis", pattern, source.pos) + + # Check the global flags for conflicts. + version = (info.flags & _ALL_VERSIONS) or DEFAULT_VERSION + if version not in (0, VERSION0, VERSION1): + raise ValueError("VERSION0 and VERSION1 flags are mutually incompatible") + + if (info.flags & _ALL_ENCODINGS) not in (0, ASCII, LOCALE, UNICODE): + raise ValueError("ASCII, LOCALE and UNICODE flags are mutually incompatible") + + if isinstance(pattern, bytes) and (info.flags & UNICODE): + raise ValueError("cannot use UNICODE flag with a bytes pattern") + + if not (info.flags & _ALL_ENCODINGS): + if isinstance(pattern, str): + info.flags |= UNICODE + else: + info.flags |= ASCII + + reverse = bool(info.flags & REVERSE) + fuzzy = isinstance(parsed, _Fuzzy) + + # Remember whether this pattern as an inline locale flag. + _locale_sensitive[locale_key] = info.inline_locale + + # Fix the group references. + caught_exception = None + try: + parsed.fix_groups(pattern, reverse, False) + except error as e: + caught_exception = e + + if caught_exception: + raise error(caught_exception.msg, caught_exception.pattern, + caught_exception.pos) + + # Should we print the parsed pattern? + if flags & DEBUG: + parsed.dump(indent=0, reverse=reverse) + + # Optimise the parsed pattern. + parsed = parsed.optimise(info, reverse) + parsed = parsed.pack_characters(info) + + # Get the required string. + req_offset, req_chars, req_flags = _get_required_string(parsed, info.flags) + + # Build the named lists. + named_lists = {} + named_list_indexes = [None] * len(info.named_lists_used) + args_needed = set() + for key, index in info.named_lists_used.items(): + name, case_flags = key + values = frozenset(kwargs[name]) + if case_flags: + items = frozenset(_fold_case(info, v) for v in values) + else: + items = values + named_lists[name] = values + named_list_indexes[index] = items + args_needed.add((name, values)) + + complain_unused_args() + + # Check the features of the groups. + _check_group_features(info, parsed) + + # Compile the parsed pattern. The result is a list of tuples. + code = parsed.compile(reverse) + + # Is there a group call to the pattern as a whole? + key = (0, reverse, fuzzy) + ref = info.call_refs.get(key) + if ref is not None: + code = [(_OP.CALL_REF, ref)] + code + [(_OP.END, )] + + # Add the final 'success' opcode. + code += [(_OP.SUCCESS, )] + + # Compile the additional copies of the groups that we need. + for group, rev, fuz in info.additional_groups: + code += group.compile(rev, fuz) + + # Flatten the code into a list of ints. + code = _flatten_code(code) + + if not parsed.has_simple_start(): + # Get the first set, if possible. + try: + fs_code = _compile_firstset(info, parsed.get_firstset(reverse)) + fs_code = _flatten_code(fs_code) + code = fs_code + code + except _FirstSetError: + pass + + # The named capture groups. + index_group = dict((v, n) for n, v in info.group_index.items()) + + # Create the PatternObject. + # + # Local flags like IGNORECASE affect the code generation, but aren't needed + # by the PatternObject itself. Conversely, global flags like LOCALE _don't_ + # affect the code generation but _are_ needed by the PatternObject. + compiled_pattern = _regex.compile(pattern, info.flags | version, code, + info.group_index, index_group, named_lists, named_list_indexes, + req_offset, req_chars, req_flags, info.group_count) + + # Do we need to reduce the size of the cache? + if len(_cache) >= _MAXCACHE: + with _cache_lock: + _shrink_cache(_cache, _named_args, _locale_sensitive, _MAXCACHE) + + if cache_it: + if (info.flags & LOCALE) == 0: + pattern_locale = None + + args_needed = frozenset(args_needed) + + # Store this regular expression and named list. + pattern_key = (pattern, type(pattern), flags, args_needed, + DEFAULT_VERSION, pattern_locale) + _cache[pattern_key] = compiled_pattern + + # Store what keyword arguments are needed. + _named_args[args_key] = args_needed + + return compiled_pattern + +def _compile_replacement_helper(pattern, template): + "Compiles a replacement template." + # This function is called by the _regex module. + + # Have we seen this before? + key = pattern.pattern, pattern.flags, template + compiled = _replacement_cache.get(key) + if compiled is not None: + return compiled + + if len(_replacement_cache) >= _MAXREPCACHE: + _replacement_cache.clear() + + is_unicode = isinstance(template, str) + source = _Source(template) + if is_unicode: + def make_string(char_codes): + return "".join(chr(c) for c in char_codes) + else: + def make_string(char_codes): + return bytes(char_codes) + + compiled = [] + literal = [] + while True: + ch = source.get() + if not ch: + break + if ch == "\\": + # '_compile_replacement' will return either an int group reference + # or a string literal. It returns items (plural) in order to handle + # a 2-character literal (an invalid escape sequence). + is_group, items = _compile_replacement(source, pattern, is_unicode) + if is_group: + # It's a group, so first flush the literal. + if literal: + compiled.append(make_string(literal)) + literal = [] + compiled.extend(items) + else: + literal.extend(items) + else: + literal.append(ord(ch)) + + # Flush the literal. + if literal: + compiled.append(make_string(literal)) + + _replacement_cache[key] = compiled + + return compiled + +# We define Pattern here after all the support objects have been defined. +_pat = _compile('', 0, False, {}, False) +Pattern = type(_pat) +Match = type(_pat.match('')) +del _pat + +# Make Pattern public for typing annotations. +__all__.append("Pattern") +__all__.append("Match") + +# We'll define an alias for the 'compile' function so that the repr of a +# pattern object is eval-able. +Regex = compile + +# Register myself for pickling. +import copyreg as _copy_reg + +def _pickle(pattern): + return _regex.compile, pattern._pickled_data + +_copy_reg.pickle(Pattern, _pickle) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/regex/_regex_core.py b/TTS/Kokoro/.venv/Lib/site-packages/regex/_regex_core.py new file mode 100644 index 0000000000000000000000000000000000000000..4f7bf12acddd4c5b7a4b4e7ca412548c459b8bf8 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/regex/_regex_core.py @@ -0,0 +1,4676 @@ +# +# Secret Labs' Regular Expression Engine core module +# +# Copyright (c) 1998-2001 by Secret Labs AB. All rights reserved. +# +# This version of the SRE library can be redistributed under CNRI's +# Python 1.6 license. For any other use, please contact Secret Labs +# AB (info@pythonware.com). +# +# Portions of this engine have been developed in cooperation with +# CNRI. Hewlett-Packard provided funding for 1.6 integration and +# other compatibility work. +# +# 2010-01-16 mrab Python front-end re-written and extended + +import enum +import string +import unicodedata +from collections import defaultdict + +from regex import _regex + +__all__ = ["A", "ASCII", "B", "BESTMATCH", "D", "DEBUG", "E", "ENHANCEMATCH", + "F", "FULLCASE", "I", "IGNORECASE", "L", "LOCALE", "M", "MULTILINE", "P", + "POSIX", "R", "REVERSE", "S", "DOTALL", "T", "TEMPLATE", "U", "UNICODE", + "V0", "VERSION0", "V1", "VERSION1", "W", "WORD", "X", "VERBOSE", "error", + "Scanner", "RegexFlag"] + +# The regex exception. +class error(Exception): + """Exception raised for invalid regular expressions. + + Attributes: + + msg: The unformatted error message + pattern: The regular expression pattern + pos: The position in the pattern where compilation failed, or None + lineno: The line number where compilation failed, unless pos is None + colno: The column number where compilation failed, unless pos is None + """ + + def __init__(self, message, pattern=None, pos=None): + newline = '\n' if isinstance(pattern, str) else b'\n' + self.msg = message + self.pattern = pattern + self.pos = pos + if pattern is not None and pos is not None: + self.lineno = pattern.count(newline, 0, pos) + 1 + self.colno = pos - pattern.rfind(newline, 0, pos) + + message = "{} at position {}".format(message, pos) + + if newline in pattern: + message += " (line {}, column {})".format(self.lineno, + self.colno) + + Exception.__init__(self, message) + +# The exception for when a positional flag has been turned on in the old +# behaviour. +class _UnscopedFlagSet(Exception): + pass + +# The exception for when parsing fails and we want to try something else. +class ParseError(Exception): + pass + +# The exception for when there isn't a valid first set. +class _FirstSetError(Exception): + pass + +# Flags. +class RegexFlag(enum.IntFlag): + A = ASCII = 0x80 # Assume ASCII locale. + B = BESTMATCH = 0x1000 # Best fuzzy match. + D = DEBUG = 0x200 # Print parsed pattern. + E = ENHANCEMATCH = 0x8000 # Attempt to improve the fit after finding the first + # fuzzy match. + F = FULLCASE = 0x4000 # Unicode full case-folding. + I = IGNORECASE = 0x2 # Ignore case. + L = LOCALE = 0x4 # Assume current 8-bit locale. + M = MULTILINE = 0x8 # Make anchors look for newline. + P = POSIX = 0x10000 # POSIX-style matching (leftmost longest). + R = REVERSE = 0x400 # Search backwards. + S = DOTALL = 0x10 # Make dot match newline. + U = UNICODE = 0x20 # Assume Unicode locale. + V0 = VERSION0 = 0x2000 # Old legacy behaviour. + V1 = VERSION1 = 0x100 # New enhanced behaviour. + W = WORD = 0x800 # Default Unicode word breaks. + X = VERBOSE = 0x40 # Ignore whitespace and comments. + T = TEMPLATE = 0x1 # Template (present because re module has it). + + def __repr__(self): + if self._name_ is not None: + return 'regex.%s' % self._name_ + + value = self._value_ + members = [] + negative = value < 0 + + if negative: + value = ~value + + for m in self.__class__: + if value & m._value_: + value &= ~m._value_ + members.append('regex.%s' % m._name_) + + if value: + members.append(hex(value)) + + res = '|'.join(members) + + if negative: + if len(members) > 1: + res = '~(%s)' % res + else: + res = '~%s' % res + + return res + + __str__ = object.__str__ + +# Put the flags into the module namespace. Being explicit here helps tools like +# linters and IDEs understand the code better. +ASCII = RegexFlag.ASCII +BESTMATCH = RegexFlag.BESTMATCH +DEBUG = RegexFlag.DEBUG +DOTALL = RegexFlag.DOTALL +ENHANCEMATCH = RegexFlag.ENHANCEMATCH +FULLCASE = RegexFlag.FULLCASE +IGNORECASE = RegexFlag.IGNORECASE +LOCALE = RegexFlag.LOCALE +MULTILINE = RegexFlag.MULTILINE +POSIX = RegexFlag.POSIX +REVERSE = RegexFlag.REVERSE +TEMPLATE = RegexFlag.TEMPLATE +UNICODE = RegexFlag.UNICODE +VERBOSE = RegexFlag.VERBOSE +VERSION0 = RegexFlag.VERSION0 +VERSION1 = RegexFlag.VERSION1 +WORD = RegexFlag.WORD +A = RegexFlag.A +B = RegexFlag.B +D = RegexFlag.D +E = RegexFlag.E +F = RegexFlag.F +I = RegexFlag.I +L = RegexFlag.L +M = RegexFlag.M +P = RegexFlag.P +R = RegexFlag.R +S = RegexFlag.S +U = RegexFlag.U +V0 = RegexFlag.V0 +V1 = RegexFlag.V1 +W = RegexFlag.W +X = RegexFlag.X +T = RegexFlag.T + +DEFAULT_VERSION = VERSION1 + +_ALL_VERSIONS = VERSION0 | VERSION1 +_ALL_ENCODINGS = ASCII | LOCALE | UNICODE + +# The default flags for the various versions. +DEFAULT_FLAGS = {VERSION0: 0, VERSION1: FULLCASE} + +# The mask for the flags. +GLOBAL_FLAGS = (_ALL_VERSIONS | BESTMATCH | DEBUG | ENHANCEMATCH | POSIX | + REVERSE) +SCOPED_FLAGS = (FULLCASE | IGNORECASE | MULTILINE | DOTALL | WORD | VERBOSE | + _ALL_ENCODINGS) + +ALPHA = frozenset(string.ascii_letters) +DIGITS = frozenset(string.digits) +ALNUM = ALPHA | DIGITS +OCT_DIGITS = frozenset(string.octdigits) +HEX_DIGITS = frozenset(string.hexdigits) +SPECIAL_CHARS = frozenset("()|?*+{^$.[\\#") | frozenset([""]) +NAMED_CHAR_PART = ALNUM | frozenset(" -") +PROPERTY_NAME_PART = ALNUM | frozenset(" &_-.") +SET_OPS = ("||", "~~", "&&", "--") + +# The width of the code words inside the regex engine. +BYTES_PER_CODE = _regex.get_code_size() +BITS_PER_CODE = BYTES_PER_CODE * 8 + +# The repeat count which represents infinity. +UNLIMITED = (1 << BITS_PER_CODE) - 1 + +# The regular expression flags. +REGEX_FLAGS = {"a": ASCII, "b": BESTMATCH, "e": ENHANCEMATCH, "f": FULLCASE, + "i": IGNORECASE, "L": LOCALE, "m": MULTILINE, "p": POSIX, "r": REVERSE, + "s": DOTALL, "u": UNICODE, "V0": VERSION0, "V1": VERSION1, "w": WORD, "x": + VERBOSE} + +# The case flags. +CASE_FLAGS = FULLCASE | IGNORECASE +NOCASE = 0 +FULLIGNORECASE = FULLCASE | IGNORECASE + +FULL_CASE_FOLDING = UNICODE | FULLIGNORECASE + +CASE_FLAGS_COMBINATIONS = {0: 0, FULLCASE: 0, IGNORECASE: IGNORECASE, + FULLIGNORECASE: FULLIGNORECASE} + +# The number of digits in hexadecimal escapes. +HEX_ESCAPES = {"x": 2, "u": 4, "U": 8} + +# The names of the opcodes. +OPCODES = """ +FAILURE +SUCCESS +ANY +ANY_ALL +ANY_ALL_REV +ANY_REV +ANY_U +ANY_U_REV +ATOMIC +BOUNDARY +BRANCH +CALL_REF +CHARACTER +CHARACTER_IGN +CHARACTER_IGN_REV +CHARACTER_REV +CONDITIONAL +DEFAULT_BOUNDARY +DEFAULT_END_OF_WORD +DEFAULT_START_OF_WORD +END +END_OF_LINE +END_OF_LINE_U +END_OF_STRING +END_OF_STRING_LINE +END_OF_STRING_LINE_U +END_OF_WORD +FUZZY +GRAPHEME_BOUNDARY +GREEDY_REPEAT +GROUP +GROUP_CALL +GROUP_EXISTS +KEEP +LAZY_REPEAT +LOOKAROUND +NEXT +PROPERTY +PROPERTY_IGN +PROPERTY_IGN_REV +PROPERTY_REV +PRUNE +RANGE +RANGE_IGN +RANGE_IGN_REV +RANGE_REV +REF_GROUP +REF_GROUP_FLD +REF_GROUP_FLD_REV +REF_GROUP_IGN +REF_GROUP_IGN_REV +REF_GROUP_REV +SEARCH_ANCHOR +SET_DIFF +SET_DIFF_IGN +SET_DIFF_IGN_REV +SET_DIFF_REV +SET_INTER +SET_INTER_IGN +SET_INTER_IGN_REV +SET_INTER_REV +SET_SYM_DIFF +SET_SYM_DIFF_IGN +SET_SYM_DIFF_IGN_REV +SET_SYM_DIFF_REV +SET_UNION +SET_UNION_IGN +SET_UNION_IGN_REV +SET_UNION_REV +SKIP +START_OF_LINE +START_OF_LINE_U +START_OF_STRING +START_OF_WORD +STRING +STRING_FLD +STRING_FLD_REV +STRING_IGN +STRING_IGN_REV +STRING_REV +FUZZY_EXT +""" + +# Define the opcodes in a namespace. +class Namespace: + pass + +OP = Namespace() +for i, op in enumerate(OPCODES.split()): + setattr(OP, op, i) + +def _shrink_cache(cache_dict, args_dict, locale_sensitive, max_length, divisor=5): + """Make room in the given cache. + + Args: + cache_dict: The cache dictionary to modify. + args_dict: The dictionary of named list args used by patterns. + max_length: Maximum # of entries in cache_dict before it is shrunk. + divisor: Cache will shrink to max_length - 1/divisor*max_length items. + """ + # Toss out a fraction of the entries at random to make room for new ones. + # A random algorithm was chosen as opposed to simply cache_dict.popitem() + # as popitem could penalize the same regular expression repeatedly based + # on its internal hash value. Being random should spread the cache miss + # love around. + cache_keys = tuple(cache_dict.keys()) + overage = len(cache_keys) - max_length + if overage < 0: + # Cache is already within limits. Normally this should not happen + # but it could due to multithreading. + return + + number_to_toss = max_length // divisor + overage + + # The import is done here to avoid a circular dependency. + import random + if not hasattr(random, 'sample'): + # Do nothing while resolving the circular dependency: + # re->random->warnings->tokenize->string->re + return + + for doomed_key in random.sample(cache_keys, number_to_toss): + try: + del cache_dict[doomed_key] + except KeyError: + # Ignore problems if the cache changed from another thread. + pass + + # Rebuild the arguments and locale-sensitivity dictionaries. + args_dict.clear() + sensitivity_dict = {} + for pattern, pattern_type, flags, args, default_version, locale in tuple(cache_dict): + args_dict[pattern, pattern_type, flags, default_version, locale] = args + try: + sensitivity_dict[pattern_type, pattern] = locale_sensitive[pattern_type, pattern] + except KeyError: + pass + + locale_sensitive.clear() + locale_sensitive.update(sensitivity_dict) + +def _fold_case(info, string): + "Folds the case of a string." + flags = info.flags + if (flags & _ALL_ENCODINGS) == 0: + flags |= info.guess_encoding + + return _regex.fold_case(flags, string) + +def is_cased_i(info, char): + "Checks whether a character is cased." + return len(_regex.get_all_cases(info.flags, char)) > 1 + +def is_cased_f(flags, char): + "Checks whether a character is cased." + return len(_regex.get_all_cases(flags, char)) > 1 + +def _compile_firstset(info, fs): + "Compiles the firstset for the pattern." + reverse = bool(info.flags & REVERSE) + fs = _check_firstset(info, reverse, fs) + if not fs or isinstance(fs, AnyAll): + return [] + + # Compile the firstset. + return fs.compile(reverse) + +def _check_firstset(info, reverse, fs): + "Checks the firstset for the pattern." + if not fs or None in fs: + return None + + # If we ignore the case, for simplicity we won't build a firstset. + members = set() + case_flags = NOCASE + for i in fs: + if isinstance(i, Character) and not i.positive: + return None + +# if i.case_flags: +# if isinstance(i, Character): +# if is_cased_i(info, i.value): +# return [] +# elif isinstance(i, SetBase): +# return [] + case_flags |= i.case_flags + members.add(i.with_flags(case_flags=NOCASE)) + + if case_flags == (FULLCASE | IGNORECASE): + return None + + # Build the firstset. + fs = SetUnion(info, list(members), case_flags=case_flags & ~FULLCASE, + zerowidth=True) + fs = fs.optimise(info, reverse, in_set=True) + + return fs + +def _flatten_code(code): + "Flattens the code from a list of tuples." + flat_code = [] + for c in code: + flat_code.extend(c) + + return flat_code + +def make_case_flags(info): + "Makes the case flags." + flags = info.flags & CASE_FLAGS + + # Turn off FULLCASE if ASCII is turned on. + if info.flags & ASCII: + flags &= ~FULLCASE + + return flags + +def make_character(info, value, in_set=False): + "Makes a character literal." + if in_set: + # A character set is built case-sensitively. + return Character(value) + + return Character(value, case_flags=make_case_flags(info)) + +def make_ref_group(info, name, position): + "Makes a group reference." + return RefGroup(info, name, position, case_flags=make_case_flags(info)) + +def make_string_set(info, name): + "Makes a string set." + return StringSet(info, name, case_flags=make_case_flags(info)) + +def make_property(info, prop, in_set): + "Makes a property." + if in_set: + return prop + + return prop.with_flags(case_flags=make_case_flags(info)) + +def _parse_pattern(source, info): + "Parses a pattern, eg. 'a|b|c'." + branches = [parse_sequence(source, info)] + while source.match("|"): + branches.append(parse_sequence(source, info)) + + if len(branches) == 1: + return branches[0] + return Branch(branches) + +def parse_sequence(source, info): + "Parses a sequence, eg. 'abc'." + sequence = [None] + case_flags = make_case_flags(info) + while True: + saved_pos = source.pos + ch = source.get() + if ch in SPECIAL_CHARS: + if ch in ")|": + # The end of a sequence. At the end of the pattern ch is "". + source.pos = saved_pos + break + elif ch == "\\": + # An escape sequence outside a set. + sequence.append(parse_escape(source, info, False)) + elif ch == "(": + # A parenthesised subpattern or a flag. + element = parse_paren(source, info) + if element is None: + case_flags = make_case_flags(info) + else: + sequence.append(element) + elif ch == ".": + # Any character. + if info.flags & DOTALL: + sequence.append(AnyAll()) + elif info.flags & WORD: + sequence.append(AnyU()) + else: + sequence.append(Any()) + elif ch == "[": + # A character set. + sequence.append(parse_set(source, info)) + elif ch == "^": + # The start of a line or the string. + if info.flags & MULTILINE: + if info.flags & WORD: + sequence.append(StartOfLineU()) + else: + sequence.append(StartOfLine()) + else: + sequence.append(StartOfString()) + elif ch == "$": + # The end of a line or the string. + if info.flags & MULTILINE: + if info.flags & WORD: + sequence.append(EndOfLineU()) + else: + sequence.append(EndOfLine()) + else: + if info.flags & WORD: + sequence.append(EndOfStringLineU()) + else: + sequence.append(EndOfStringLine()) + elif ch in "?*+{": + # Looks like a quantifier. + counts = parse_quantifier(source, info, ch) + if counts: + # It _is_ a quantifier. + apply_quantifier(source, info, counts, case_flags, ch, + saved_pos, sequence) + sequence.append(None) + else: + # It's not a quantifier. Maybe it's a fuzzy constraint. + constraints = parse_fuzzy(source, info, ch, case_flags) + + if constraints: + # It _is_ a fuzzy constraint. + if is_actually_fuzzy(constraints): + apply_constraint(source, info, constraints, case_flags, + saved_pos, sequence) + sequence.append(None) + else: + # The element was just a literal. + sequence.append(Character(ord(ch), + case_flags=case_flags)) + else: + # A literal. + sequence.append(Character(ord(ch), case_flags=case_flags)) + else: + # A literal. + sequence.append(Character(ord(ch), case_flags=case_flags)) + + sequence = [item for item in sequence if item is not None] + return Sequence(sequence) + +def is_actually_fuzzy(constraints): + "Checks whether a fuzzy constraint is actually fuzzy." + if constraints.get("e") == (0, 0): + return False + + if (constraints.get("s"), constraints.get("i"), constraints.get("d")) == ((0, 0), (0, 0), (0, 0)): + return False + + return True + +def apply_quantifier(source, info, counts, case_flags, ch, saved_pos, + sequence): + element = sequence.pop() + if element is None: + if sequence: + raise error("multiple repeat", source.string, saved_pos) + raise error("nothing to repeat", source.string, saved_pos) + + if isinstance(element, (GreedyRepeat, LazyRepeat, PossessiveRepeat)): + raise error("multiple repeat", source.string, saved_pos) + + min_count, max_count = counts + saved_pos = source.pos + ch = source.get() + if ch == "?": + # The "?" suffix that means it's a lazy repeat. + repeated = LazyRepeat + elif ch == "+": + # The "+" suffix that means it's a possessive repeat. + repeated = PossessiveRepeat + else: + # No suffix means that it's a greedy repeat. + source.pos = saved_pos + repeated = GreedyRepeat + + # Ignore the quantifier if it applies to a zero-width item or the number of + # repeats is fixed at 1. + if not element.is_empty() and (min_count != 1 or max_count != 1): + element = repeated(element, min_count, max_count) + + sequence.append(element) + +def apply_constraint(source, info, constraints, case_flags, saved_pos, + sequence): + element = sequence.pop() + if element is None: + raise error("nothing for fuzzy constraint", source.string, saved_pos) + + # If a group is marked as fuzzy then put all of the fuzzy part in the + # group. + if isinstance(element, Group): + element.subpattern = Fuzzy(element.subpattern, constraints) + sequence.append(element) + else: + sequence.append(Fuzzy(element, constraints)) + +_QUANTIFIERS = {"?": (0, 1), "*": (0, None), "+": (1, None)} + +def parse_quantifier(source, info, ch): + "Parses a quantifier." + q = _QUANTIFIERS.get(ch) + if q: + # It's a quantifier. + return q + + if ch == "{": + # Looks like a limited repeated element, eg. 'a{2,3}'. + counts = parse_limited_quantifier(source) + if counts: + return counts + + return None + +def is_above_limit(count): + "Checks whether a count is above the maximum." + return count is not None and count >= UNLIMITED + +def parse_limited_quantifier(source): + "Parses a limited quantifier." + saved_pos = source.pos + min_count = parse_count(source) + if source.match(","): + max_count = parse_count(source) + + # No minimum means 0 and no maximum means unlimited. + min_count = int(min_count or 0) + max_count = int(max_count) if max_count else None + else: + if not min_count: + source.pos = saved_pos + return None + + min_count = max_count = int(min_count) + + if not source.match ("}"): + source.pos = saved_pos + return None + + if is_above_limit(min_count) or is_above_limit(max_count): + raise error("repeat count too big", source.string, saved_pos) + + if max_count is not None and min_count > max_count: + raise error("min repeat greater than max repeat", source.string, + saved_pos) + + return min_count, max_count + +def parse_fuzzy(source, info, ch, case_flags): + "Parses a fuzzy setting, if present." + saved_pos = source.pos + + if ch != "{": + return None + + constraints = {} + try: + parse_fuzzy_item(source, constraints) + while source.match(","): + parse_fuzzy_item(source, constraints) + except ParseError: + source.pos = saved_pos + return None + + if source.match(":"): + constraints["test"] = parse_fuzzy_test(source, info, case_flags) + + if not source.match("}"): + raise error("expected }", source.string, source.pos) + + return constraints + +def parse_fuzzy_item(source, constraints): + "Parses a fuzzy setting item." + saved_pos = source.pos + try: + parse_cost_constraint(source, constraints) + except ParseError: + source.pos = saved_pos + + parse_cost_equation(source, constraints) + +def parse_cost_constraint(source, constraints): + "Parses a cost constraint." + saved_pos = source.pos + ch = source.get() + if ch in ALPHA: + # Syntax: constraint [("<=" | "<") cost] + constraint = parse_constraint(source, constraints, ch) + + max_inc = parse_fuzzy_compare(source) + + if max_inc is None: + # No maximum cost. + constraints[constraint] = 0, None + else: + # There's a maximum cost. + cost_pos = source.pos + max_cost = parse_cost_limit(source) + + # Inclusive or exclusive limit? + if not max_inc: + max_cost -= 1 + + if max_cost < 0: + raise error("bad fuzzy cost limit", source.string, cost_pos) + + constraints[constraint] = 0, max_cost + elif ch in DIGITS: + # Syntax: cost ("<=" | "<") constraint ("<=" | "<") cost + source.pos = saved_pos + + # Minimum cost. + cost_pos = source.pos + min_cost = parse_cost_limit(source) + + min_inc = parse_fuzzy_compare(source) + if min_inc is None: + raise ParseError() + + constraint = parse_constraint(source, constraints, source.get()) + + max_inc = parse_fuzzy_compare(source) + if max_inc is None: + raise ParseError() + + # Maximum cost. + cost_pos = source.pos + max_cost = parse_cost_limit(source) + + # Inclusive or exclusive limits? + if not min_inc: + min_cost += 1 + if not max_inc: + max_cost -= 1 + + if not 0 <= min_cost <= max_cost: + raise error("bad fuzzy cost limit", source.string, cost_pos) + + constraints[constraint] = min_cost, max_cost + else: + raise ParseError() + +def parse_cost_limit(source): + "Parses a cost limit." + cost_pos = source.pos + digits = parse_count(source) + + try: + return int(digits) + except ValueError: + pass + + raise error("bad fuzzy cost limit", source.string, cost_pos) + +def parse_constraint(source, constraints, ch): + "Parses a constraint." + if ch not in "deis": + raise ParseError() + + if ch in constraints: + raise ParseError() + + return ch + +def parse_fuzzy_compare(source): + "Parses a cost comparator." + if source.match("<="): + return True + elif source.match("<"): + return False + else: + return None + +def parse_cost_equation(source, constraints): + "Parses a cost equation." + if "cost" in constraints: + raise error("more than one cost equation", source.string, source.pos) + + cost = {} + + parse_cost_term(source, cost) + while source.match("+"): + parse_cost_term(source, cost) + + max_inc = parse_fuzzy_compare(source) + if max_inc is None: + raise ParseError() + + max_cost = int(parse_count(source)) + + if not max_inc: + max_cost -= 1 + + if max_cost < 0: + raise error("bad fuzzy cost limit", source.string, source.pos) + + cost["max"] = max_cost + + constraints["cost"] = cost + +def parse_cost_term(source, cost): + "Parses a cost equation term." + coeff = parse_count(source) + ch = source.get() + if ch not in "dis": + raise ParseError() + + if ch in cost: + raise error("repeated fuzzy cost", source.string, source.pos) + + cost[ch] = int(coeff or 1) + +def parse_fuzzy_test(source, info, case_flags): + saved_pos = source.pos + ch = source.get() + if ch in SPECIAL_CHARS: + if ch == "\\": + # An escape sequence outside a set. + return parse_escape(source, info, False) + elif ch == ".": + # Any character. + if info.flags & DOTALL: + return AnyAll() + elif info.flags & WORD: + return AnyU() + else: + return Any() + elif ch == "[": + # A character set. + return parse_set(source, info) + else: + raise error("expected character set", source.string, saved_pos) + elif ch: + # A literal. + return Character(ord(ch), case_flags=case_flags) + else: + raise error("expected character set", source.string, saved_pos) + +def parse_count(source): + "Parses a quantifier's count, which can be empty." + return source.get_while(DIGITS) + +def parse_paren(source, info): + """Parses a parenthesised subpattern or a flag. Returns FLAGS if it's an + inline flag. + """ + saved_pos = source.pos + ch = source.get(True) + if ch == "?": + # (?... + saved_pos_2 = source.pos + ch = source.get(True) + if ch == "<": + # (?<... + saved_pos_3 = source.pos + ch = source.get() + if ch in ("=", "!"): + # (?<=... or (?") + saved_flags = info.flags + try: + subpattern = _parse_pattern(source, info) + source.expect(")") + finally: + info.flags = saved_flags + source.ignore_space = bool(info.flags & VERBOSE) + + info.close_group() + return Group(info, group, subpattern) + if ch in ("=", "!"): + # (?=... or (?!...: lookahead. + return parse_lookaround(source, info, False, ch == "=") + if ch == "P": + # (?P...: a Python extension. + return parse_extension(source, info) + if ch == "#": + # (?#...: a comment. + return parse_comment(source) + if ch == "(": + # (?(...: a conditional subpattern. + return parse_conditional(source, info) + if ch == ">": + # (?>...: an atomic subpattern. + return parse_atomic(source, info) + if ch == "|": + # (?|...: a common/reset groups branch. + return parse_common(source, info) + if ch == "R" or "0" <= ch <= "9": + # (?R...: probably a call to a group. + return parse_call_group(source, info, ch, saved_pos_2) + if ch == "&": + # (?&...: a call to a named group. + return parse_call_named_group(source, info, saved_pos_2) + if (ch == "+" or ch == "-") and source.peek() in DIGITS: + return parse_rel_call_group(source, info, ch, saved_pos_2) + + # (?...: probably a flags subpattern. + source.pos = saved_pos_2 + return parse_flags_subpattern(source, info) + + if ch == "*": + # (*... + saved_pos_2 = source.pos + word = source.get_while(set(")>"), include=False) + if word[ : 1].isalpha(): + verb = VERBS.get(word) + if not verb: + raise error("unknown verb", source.string, saved_pos_2) + + source.expect(")") + + return verb + + # (...: an unnamed capture group. + source.pos = saved_pos + group = info.open_group() + saved_flags = info.flags + try: + subpattern = _parse_pattern(source, info) + source.expect(")") + finally: + info.flags = saved_flags + source.ignore_space = bool(info.flags & VERBOSE) + + info.close_group() + + return Group(info, group, subpattern) + +def parse_extension(source, info): + "Parses a Python extension." + saved_pos = source.pos + ch = source.get() + if ch == "<": + # (?P<...: a named capture group. + name = parse_name(source) + group = info.open_group(name) + source.expect(">") + saved_flags = info.flags + try: + subpattern = _parse_pattern(source, info) + source.expect(")") + finally: + info.flags = saved_flags + source.ignore_space = bool(info.flags & VERBOSE) + + info.close_group() + + return Group(info, group, subpattern) + if ch == "=": + # (?P=...: a named group reference. + name = parse_name(source, allow_numeric=True) + source.expect(")") + if info.is_open_group(name): + raise error("cannot refer to an open group", source.string, + saved_pos) + + return make_ref_group(info, name, saved_pos) + if ch == ">" or ch == "&": + # (?P>...: a call to a group. + return parse_call_named_group(source, info, saved_pos) + + source.pos = saved_pos + raise error("unknown extension", source.string, saved_pos) + +def parse_comment(source): + "Parses a comment." + while True: + saved_pos = source.pos + c = source.get(True) + + if not c or c == ")": + break + + if c == "\\": + c = source.get(True) + + source.pos = saved_pos + source.expect(")") + + return None + +def parse_lookaround(source, info, behind, positive): + "Parses a lookaround." + saved_flags = info.flags + try: + subpattern = _parse_pattern(source, info) + source.expect(")") + finally: + info.flags = saved_flags + source.ignore_space = bool(info.flags & VERBOSE) + + return LookAround(behind, positive, subpattern) + +def parse_conditional(source, info): + "Parses a conditional subpattern." + saved_flags = info.flags + saved_pos = source.pos + ch = source.get() + if ch == "?": + # (?(?... + ch = source.get() + if ch in ("=", "!"): + # (?(?=... or (?(?!...: lookahead conditional. + return parse_lookaround_conditional(source, info, False, ch == "=") + if ch == "<": + # (?(?<... + ch = source.get() + if ch in ("=", "!"): + # (?(?<=... or (?(?"), include=False) + + if not name: + raise error("missing group name", source.string, source.pos) + + if name.isdigit(): + min_group = 0 if allow_group_0 else 1 + if not allow_numeric or int(name) < min_group: + raise error("bad character in group name", source.string, + source.pos) + else: + if not name.isidentifier(): + raise error("bad character in group name", source.string, + source.pos) + + return name + +def is_octal(string): + "Checks whether a string is octal." + return all(ch in OCT_DIGITS for ch in string) + +def is_decimal(string): + "Checks whether a string is decimal." + return all(ch in DIGITS for ch in string) + +def is_hexadecimal(string): + "Checks whether a string is hexadecimal." + return all(ch in HEX_DIGITS for ch in string) + +def parse_escape(source, info, in_set): + "Parses an escape sequence." + saved_ignore = source.ignore_space + source.ignore_space = False + ch = source.get() + source.ignore_space = saved_ignore + if not ch: + # A backslash at the end of the pattern. + raise error("bad escape (end of pattern)", source.string, source.pos) + if ch in HEX_ESCAPES: + # A hexadecimal escape sequence. + return parse_hex_escape(source, info, ch, HEX_ESCAPES[ch], in_set, ch) + elif ch == "g" and not in_set: + # A group reference. + saved_pos = source.pos + try: + return parse_group_ref(source, info) + except error: + # Invalid as a group reference, so assume it's a literal. + source.pos = saved_pos + + return make_character(info, ord(ch), in_set) + elif ch == "G" and not in_set: + # A search anchor. + return SearchAnchor() + elif ch == "L" and not in_set: + # A string set. + return parse_string_set(source, info) + elif ch == "N": + # A named codepoint. + return parse_named_char(source, info, in_set) + elif ch in "pP": + # A Unicode property, positive or negative. + return parse_property(source, info, ch == "p", in_set) + elif ch == "R" and not in_set: + # A line ending. + charset = [0x0A, 0x0B, 0x0C, 0x0D] + if info.guess_encoding == UNICODE: + charset.extend([0x85, 0x2028, 0x2029]) + + return Atomic(Branch([String([0x0D, 0x0A]), SetUnion(info, [Character(c) + for c in charset])])) + elif ch == "X" and not in_set: + # A grapheme cluster. + return Grapheme() + elif ch in ALPHA: + # An alphabetic escape sequence. + # Positional escapes aren't allowed inside a character set. + if not in_set: + if info.flags & WORD: + value = WORD_POSITION_ESCAPES.get(ch) + elif info.flags & ASCII: + value = ASCII_POSITION_ESCAPES.get(ch) + elif info.flags & UNICODE: + value = UNICODE_POSITION_ESCAPES.get(ch) + else: + value = POSITION_ESCAPES.get(ch) + + if value: + return value + + if info.flags & ASCII: + value = ASCII_CHARSET_ESCAPES.get(ch) + elif info.flags & UNICODE: + value = UNICODE_CHARSET_ESCAPES.get(ch) + else: + value = CHARSET_ESCAPES.get(ch) + + if value: + return value + + value = CHARACTER_ESCAPES.get(ch) + if value: + return Character(ord(value)) + + raise error("bad escape \\%s" % ch, source.string, source.pos) + elif ch in DIGITS: + # A numeric escape sequence. + return parse_numeric_escape(source, info, ch, in_set) + else: + # A literal. + return make_character(info, ord(ch), in_set) + +def parse_numeric_escape(source, info, ch, in_set): + "Parses a numeric escape sequence." + if in_set or ch == "0": + # Octal escape sequence, max 3 digits. + return parse_octal_escape(source, info, [ch], in_set) + + # At least 1 digit, so either octal escape or group. + digits = ch + saved_pos = source.pos + ch = source.get() + if ch in DIGITS: + # At least 2 digits, so either octal escape or group. + digits += ch + saved_pos = source.pos + ch = source.get() + if is_octal(digits) and ch in OCT_DIGITS: + # 3 octal digits, so octal escape sequence. + encoding = info.flags & _ALL_ENCODINGS + if encoding == ASCII or encoding == LOCALE: + octal_mask = 0xFF + else: + octal_mask = 0x1FF + + value = int(digits + ch, 8) & octal_mask + return make_character(info, value) + + # Group reference. + source.pos = saved_pos + if info.is_open_group(digits): + raise error("cannot refer to an open group", source.string, source.pos) + + return make_ref_group(info, digits, source.pos) + +def parse_octal_escape(source, info, digits, in_set): + "Parses an octal escape sequence." + saved_pos = source.pos + ch = source.get() + while len(digits) < 3 and ch in OCT_DIGITS: + digits.append(ch) + saved_pos = source.pos + ch = source.get() + + source.pos = saved_pos + try: + value = int("".join(digits), 8) + return make_character(info, value, in_set) + except ValueError: + if digits[0] in OCT_DIGITS: + raise error("incomplete escape \\%s" % ''.join(digits), + source.string, source.pos) + else: + raise error("bad escape \\%s" % digits[0], source.string, + source.pos) + +def parse_hex_escape(source, info, esc, expected_len, in_set, type): + "Parses a hex escape sequence." + saved_pos = source.pos + digits = [] + for i in range(expected_len): + ch = source.get() + if ch not in HEX_DIGITS: + raise error("incomplete escape \\%s%s" % (type, ''.join(digits)), + source.string, saved_pos) + digits.append(ch) + + try: + value = int("".join(digits), 16) + except ValueError: + pass + else: + if value < 0x110000: + return make_character(info, value, in_set) + + # Bad hex escape. + raise error("bad hex escape \\%s%s" % (esc, ''.join(digits)), + source.string, saved_pos) + +def parse_group_ref(source, info): + "Parses a group reference." + source.expect("<") + saved_pos = source.pos + name = parse_name(source, True) + source.expect(">") + if info.is_open_group(name): + raise error("cannot refer to an open group", source.string, source.pos) + + return make_ref_group(info, name, saved_pos) + +def parse_string_set(source, info): + "Parses a string set reference." + source.expect("<") + name = parse_name(source, True) + source.expect(">") + if name is None or name not in info.kwargs: + raise error("undefined named list", source.string, source.pos) + + return make_string_set(info, name) + +def parse_named_char(source, info, in_set): + "Parses a named character." + saved_pos = source.pos + if source.match("{"): + name = source.get_while(NAMED_CHAR_PART, keep_spaces=True) + if source.match("}"): + try: + value = unicodedata.lookup(name) + return make_character(info, ord(value), in_set) + except KeyError: + raise error("undefined character name", source.string, + source.pos) + + source.pos = saved_pos + return make_character(info, ord("N"), in_set) + +def parse_property(source, info, positive, in_set): + "Parses a Unicode property." + saved_pos = source.pos + ch = source.get() + if ch == "{": + negate = source.match("^") + prop_name, name = parse_property_name(source) + if source.match("}"): + # It's correctly delimited. + if info.flags & ASCII: + encoding = ASCII_ENCODING + elif info.flags & UNICODE: + encoding = UNICODE_ENCODING + else: + encoding = 0 + + prop = lookup_property(prop_name, name, positive != negate, source, + encoding=encoding) + return make_property(info, prop, in_set) + elif ch and ch in "CLMNPSZ": + # An abbreviated property, eg \pL. + if info.flags & ASCII: + encoding = ASCII_ENCODING + elif info.flags & UNICODE: + encoding = UNICODE_ENCODING + else: + encoding = 0 + + prop = lookup_property(None, ch, positive, source, encoding=encoding) + return make_property(info, prop, in_set) + + # Not a property, so treat as a literal "p" or "P". + source.pos = saved_pos + ch = "p" if positive else "P" + return make_character(info, ord(ch), in_set) + +def parse_property_name(source): + "Parses a property name, which may be qualified." + name = source.get_while(PROPERTY_NAME_PART) + saved_pos = source.pos + + ch = source.get() + if ch and ch in ":=": + prop_name = name + name = source.get_while(ALNUM | set(" &_-./")).strip() + + if name: + # Name after the ":" or "=", so it's a qualified name. + saved_pos = source.pos + else: + # No name after the ":" or "=", so assume it's an unqualified name. + prop_name, name = None, prop_name + else: + prop_name = None + + source.pos = saved_pos + return prop_name, name + +def parse_set(source, info): + "Parses a character set." + version = (info.flags & _ALL_VERSIONS) or DEFAULT_VERSION + + saved_ignore = source.ignore_space + source.ignore_space = False + # Negative set? + negate = source.match("^") + try: + if version == VERSION0: + item = parse_set_imp_union(source, info) + else: + item = parse_set_union(source, info) + + if not source.match("]"): + raise error("missing ]", source.string, source.pos) + finally: + source.ignore_space = saved_ignore + + if negate: + item = item.with_flags(positive=not item.positive) + + item = item.with_flags(case_flags=make_case_flags(info)) + + return item + +def parse_set_union(source, info): + "Parses a set union ([x||y])." + items = [parse_set_symm_diff(source, info)] + while source.match("||"): + items.append(parse_set_symm_diff(source, info)) + + if len(items) == 1: + return items[0] + return SetUnion(info, items) + +def parse_set_symm_diff(source, info): + "Parses a set symmetric difference ([x~~y])." + items = [parse_set_inter(source, info)] + while source.match("~~"): + items.append(parse_set_inter(source, info)) + + if len(items) == 1: + return items[0] + return SetSymDiff(info, items) + +def parse_set_inter(source, info): + "Parses a set intersection ([x&&y])." + items = [parse_set_diff(source, info)] + while source.match("&&"): + items.append(parse_set_diff(source, info)) + + if len(items) == 1: + return items[0] + return SetInter(info, items) + +def parse_set_diff(source, info): + "Parses a set difference ([x--y])." + items = [parse_set_imp_union(source, info)] + while source.match("--"): + items.append(parse_set_imp_union(source, info)) + + if len(items) == 1: + return items[0] + return SetDiff(info, items) + +def parse_set_imp_union(source, info): + "Parses a set implicit union ([xy])." + version = (info.flags & _ALL_VERSIONS) or DEFAULT_VERSION + + items = [parse_set_member(source, info)] + while True: + saved_pos = source.pos + if source.match("]"): + # End of the set. + source.pos = saved_pos + break + + if version == VERSION1 and any(source.match(op) for op in SET_OPS): + # The new behaviour has set operators. + source.pos = saved_pos + break + + items.append(parse_set_member(source, info)) + + if len(items) == 1: + return items[0] + return SetUnion(info, items) + +def parse_set_member(source, info): + "Parses a member in a character set." + # Parse a set item. + start = parse_set_item(source, info) + saved_pos1 = source.pos + if (not isinstance(start, Character) or not start.positive or not + source.match("-")): + # It's not the start of a range. + return start + + version = (info.flags & _ALL_VERSIONS) or DEFAULT_VERSION + + # It looks like the start of a range of characters. + saved_pos2 = source.pos + if version == VERSION1 and source.match("-"): + # It's actually the set difference operator '--', so return the + # character. + source.pos = saved_pos1 + return start + + if source.match("]"): + # We've reached the end of the set, so return both the character and + # hyphen. + source.pos = saved_pos2 + return SetUnion(info, [start, Character(ord("-"))]) + + # Parse a set item. + end = parse_set_item(source, info) + if not isinstance(end, Character) or not end.positive: + # It's not a range, so return the character, hyphen and property. + return SetUnion(info, [start, Character(ord("-")), end]) + + # It _is_ a range. + if start.value > end.value: + raise error("bad character range", source.string, source.pos) + + if start.value == end.value: + return start + + return Range(start.value, end.value) + +def parse_set_item(source, info): + "Parses an item in a character set." + version = (info.flags & _ALL_VERSIONS) or DEFAULT_VERSION + + if source.match("\\"): + # An escape sequence in a set. + return parse_escape(source, info, True) + + saved_pos = source.pos + if source.match("[:"): + # Looks like a POSIX character class. + try: + return parse_posix_class(source, info) + except ParseError: + # Not a POSIX character class. + source.pos = saved_pos + + if version == VERSION1 and source.match("["): + # It's the start of a nested set. + + # Negative set? + negate = source.match("^") + item = parse_set_union(source, info) + + if not source.match("]"): + raise error("missing ]", source.string, source.pos) + + if negate: + item = item.with_flags(positive=not item.positive) + + return item + + ch = source.get() + if not ch: + raise error("unterminated character set", source.string, source.pos) + + return Character(ord(ch)) + +def parse_posix_class(source, info): + "Parses a POSIX character class." + negate = source.match("^") + prop_name, name = parse_property_name(source) + if not source.match(":]"): + raise ParseError() + + return lookup_property(prop_name, name, not negate, source, posix=True) + +def float_to_rational(flt): + "Converts a float to a rational pair." + int_part = int(flt) + error = flt - int_part + if abs(error) < 0.0001: + return int_part, 1 + + den, num = float_to_rational(1.0 / error) + + return int_part * den + num, den + +def numeric_to_rational(numeric): + "Converts a numeric string to a rational string, if possible." + if numeric[ : 1] == "-": + sign, numeric = numeric[0], numeric[1 : ] + else: + sign = "" + + parts = numeric.split("/") + if len(parts) == 2: + num, den = float_to_rational(float(parts[0]) / float(parts[1])) + elif len(parts) == 1: + num, den = float_to_rational(float(parts[0])) + else: + raise ValueError() + + result = "{}{}/{}".format(sign, num, den) + if result.endswith("/1"): + return result[ : -2] + + return result + +def standardise_name(name): + "Standardises a property or value name." + try: + return numeric_to_rational("".join(name)) + except (ValueError, ZeroDivisionError): + return "".join(ch for ch in name if ch not in "_- ").upper() + +_POSIX_CLASSES = set('ALNUM DIGIT PUNCT XDIGIT'.split()) + +_BINARY_VALUES = set('YES Y NO N TRUE T FALSE F'.split()) + +def lookup_property(property, value, positive, source=None, posix=False, encoding=0): + "Looks up a property." + # Normalise the names (which may still be lists). + property = standardise_name(property) if property else None + value = standardise_name(value) + + if (property, value) == ("GENERALCATEGORY", "ASSIGNED"): + property, value, positive = "GENERALCATEGORY", "UNASSIGNED", not positive + + if posix and not property and value.upper() in _POSIX_CLASSES: + value = 'POSIX' + value + + if property: + # Both the property and the value are provided. + prop = PROPERTIES.get(property) + if not prop: + if not source: + raise error("unknown property") + + raise error("unknown property", source.string, source.pos) + + prop_id, value_dict = prop + val_id = value_dict.get(value) + if val_id is None: + if not source: + raise error("unknown property value") + + raise error("unknown property value", source.string, source.pos) + + return Property((prop_id << 16) | val_id, positive, encoding=encoding) + + # Only the value is provided. + # It might be the name of a GC, script or block value. + for property in ("GC", "SCRIPT", "BLOCK"): + prop_id, value_dict = PROPERTIES.get(property) + val_id = value_dict.get(value) + if val_id is not None: + return Property((prop_id << 16) | val_id, positive, encoding=encoding) + + # It might be the name of a binary property. + prop = PROPERTIES.get(value) + if prop: + prop_id, value_dict = prop + if set(value_dict) == _BINARY_VALUES: + return Property((prop_id << 16) | 1, positive, encoding=encoding) + + return Property(prop_id << 16, not positive, encoding=encoding) + + # It might be the name of a binary property starting with a prefix. + if value.startswith("IS"): + prop = PROPERTIES.get(value[2 : ]) + if prop: + prop_id, value_dict = prop + if "YES" in value_dict: + return Property((prop_id << 16) | 1, positive, encoding=encoding) + + # It might be the name of a script or block starting with a prefix. + for prefix, property in (("IS", "SCRIPT"), ("IN", "BLOCK")): + if value.startswith(prefix): + prop_id, value_dict = PROPERTIES.get(property) + val_id = value_dict.get(value[2 : ]) + if val_id is not None: + return Property((prop_id << 16) | val_id, positive, encoding=encoding) + + # Unknown property. + if not source: + raise error("unknown property") + + raise error("unknown property", source.string, source.pos) + +def _compile_replacement(source, pattern, is_unicode): + "Compiles a replacement template escape sequence." + ch = source.get() + if ch in ALPHA: + # An alphabetic escape sequence. + value = CHARACTER_ESCAPES.get(ch) + if value: + return False, [ord(value)] + + if ch in HEX_ESCAPES and (ch == "x" or is_unicode): + # A hexadecimal escape sequence. + return False, [parse_repl_hex_escape(source, HEX_ESCAPES[ch], ch)] + + if ch == "g": + # A group preference. + return True, [compile_repl_group(source, pattern)] + + if ch == "N" and is_unicode: + # A named character. + value = parse_repl_named_char(source) + if value is not None: + return False, [value] + + raise error("bad escape \\%s" % ch, source.string, source.pos) + + if isinstance(source.sep, bytes): + octal_mask = 0xFF + else: + octal_mask = 0x1FF + + if ch == "0": + # An octal escape sequence. + digits = ch + while len(digits) < 3: + saved_pos = source.pos + ch = source.get() + if ch not in OCT_DIGITS: + source.pos = saved_pos + break + digits += ch + + return False, [int(digits, 8) & octal_mask] + + if ch in DIGITS: + # Either an octal escape sequence (3 digits) or a group reference (max + # 2 digits). + digits = ch + saved_pos = source.pos + ch = source.get() + if ch in DIGITS: + digits += ch + saved_pos = source.pos + ch = source.get() + if ch and is_octal(digits + ch): + # An octal escape sequence. + return False, [int(digits + ch, 8) & octal_mask] + + # A group reference. + source.pos = saved_pos + return True, [int(digits)] + + if ch == "\\": + # An escaped backslash is a backslash. + return False, [ord("\\")] + + if not ch: + # A trailing backslash. + raise error("bad escape (end of pattern)", source.string, source.pos) + + # An escaped non-backslash is a backslash followed by the literal. + return False, [ord("\\"), ord(ch)] + +def parse_repl_hex_escape(source, expected_len, type): + "Parses a hex escape sequence in a replacement string." + digits = [] + for i in range(expected_len): + ch = source.get() + if ch not in HEX_DIGITS: + raise error("incomplete escape \\%s%s" % (type, ''.join(digits)), + source.string, source.pos) + digits.append(ch) + + return int("".join(digits), 16) + +def parse_repl_named_char(source): + "Parses a named character in a replacement string." + saved_pos = source.pos + if source.match("{"): + name = source.get_while(ALPHA | set(" ")) + + if source.match("}"): + try: + value = unicodedata.lookup(name) + return ord(value) + except KeyError: + raise error("undefined character name", source.string, + source.pos) + + source.pos = saved_pos + return None + +def compile_repl_group(source, pattern): + "Compiles a replacement template group reference." + source.expect("<") + name = parse_name(source, True, True) + + source.expect(">") + if name.isdigit(): + index = int(name) + if not 0 <= index <= pattern.groups: + raise error("invalid group reference", source.string, source.pos) + + return index + + try: + return pattern.groupindex[name] + except KeyError: + raise IndexError("unknown group") + +# The regular expression is parsed into a syntax tree. The different types of +# node are defined below. + +INDENT = " " +POSITIVE_OP = 0x1 +ZEROWIDTH_OP = 0x2 +FUZZY_OP = 0x4 +REVERSE_OP = 0x8 +REQUIRED_OP = 0x10 +ENCODING_OP_SHIFT = 5 + +POS_TEXT = {False: "NON-MATCH", True: "MATCH"} +CASE_TEXT = {NOCASE: "", IGNORECASE: " SIMPLE_IGNORE_CASE", FULLCASE: "", + FULLIGNORECASE: " FULL_IGNORE_CASE"} + +def make_sequence(items): + if len(items) == 1: + return items[0] + return Sequence(items) + +# Common base class for all nodes. +class RegexBase: + def __init__(self): + self._key = self.__class__ + + def with_flags(self, positive=None, case_flags=None, zerowidth=None): + if positive is None: + positive = self.positive + else: + positive = bool(positive) + if case_flags is None: + case_flags = self.case_flags + else: + case_flags = CASE_FLAGS_COMBINATIONS[case_flags & CASE_FLAGS] + if zerowidth is None: + zerowidth = self.zerowidth + else: + zerowidth = bool(zerowidth) + + if (positive == self.positive and case_flags == self.case_flags and + zerowidth == self.zerowidth): + return self + + return self.rebuild(positive, case_flags, zerowidth) + + def fix_groups(self, pattern, reverse, fuzzy): + pass + + def optimise(self, info, reverse): + return self + + def pack_characters(self, info): + return self + + def remove_captures(self): + return self + + def is_atomic(self): + return True + + def can_be_affix(self): + return True + + def contains_group(self): + return False + + def get_firstset(self, reverse): + raise _FirstSetError() + + def has_simple_start(self): + return False + + def compile(self, reverse=False, fuzzy=False): + return self._compile(reverse, fuzzy) + + def is_empty(self): + return False + + def __hash__(self): + return hash(self._key) + + def __eq__(self, other): + return type(self) is type(other) and self._key == other._key + + def __ne__(self, other): + return not self.__eq__(other) + + def get_required_string(self, reverse): + return self.max_width(), None + +# Base class for zero-width nodes. +class ZeroWidthBase(RegexBase): + def __init__(self, positive=True, encoding=0): + RegexBase.__init__(self) + self.positive = bool(positive) + self.encoding = encoding + + self._key = self.__class__, self.positive + + def get_firstset(self, reverse): + return set([None]) + + def _compile(self, reverse, fuzzy): + flags = 0 + if self.positive: + flags |= POSITIVE_OP + if fuzzy: + flags |= FUZZY_OP + if reverse: + flags |= REVERSE_OP + flags |= self.encoding << ENCODING_OP_SHIFT + return [(self._opcode, flags)] + + def dump(self, indent, reverse): + print("{}{} {}{}".format(INDENT * indent, self._op_name, + POS_TEXT[self.positive], ["", " ASCII"][self.encoding])) + + def max_width(self): + return 0 + +class Any(RegexBase): + _opcode = {False: OP.ANY, True: OP.ANY_REV} + _op_name = "ANY" + + def has_simple_start(self): + return True + + def _compile(self, reverse, fuzzy): + flags = 0 + if fuzzy: + flags |= FUZZY_OP + return [(self._opcode[reverse], flags)] + + def dump(self, indent, reverse): + print("{}{}".format(INDENT * indent, self._op_name)) + + def max_width(self): + return 1 + +class AnyAll(Any): + _opcode = {False: OP.ANY_ALL, True: OP.ANY_ALL_REV} + _op_name = "ANY_ALL" + + def __init__(self): + self.positive = True + self.zerowidth = False + self.case_flags = 0 + + self._key = self.__class__, self.positive + +class AnyU(Any): + _opcode = {False: OP.ANY_U, True: OP.ANY_U_REV} + _op_name = "ANY_U" + +class Atomic(RegexBase): + def __init__(self, subpattern): + RegexBase.__init__(self) + self.subpattern = subpattern + + def fix_groups(self, pattern, reverse, fuzzy): + self.subpattern.fix_groups(pattern, reverse, fuzzy) + + def optimise(self, info, reverse): + self.subpattern = self.subpattern.optimise(info, reverse) + + if self.subpattern.is_empty(): + return self.subpattern + return self + + def pack_characters(self, info): + self.subpattern = self.subpattern.pack_characters(info) + return self + + def remove_captures(self): + self.subpattern = self.subpattern.remove_captures() + return self + + def can_be_affix(self): + return self.subpattern.can_be_affix() + + def contains_group(self): + return self.subpattern.contains_group() + + def get_firstset(self, reverse): + return self.subpattern.get_firstset(reverse) + + def has_simple_start(self): + return self.subpattern.has_simple_start() + + def _compile(self, reverse, fuzzy): + return ([(OP.ATOMIC, )] + self.subpattern.compile(reverse, fuzzy) + + [(OP.END, )]) + + def dump(self, indent, reverse): + print("{}ATOMIC".format(INDENT * indent)) + self.subpattern.dump(indent + 1, reverse) + + def is_empty(self): + return self.subpattern.is_empty() + + def __eq__(self, other): + return (type(self) is type(other) and self.subpattern == + other.subpattern) + + def max_width(self): + return self.subpattern.max_width() + + def get_required_string(self, reverse): + return self.subpattern.get_required_string(reverse) + +class Boundary(ZeroWidthBase): + _opcode = OP.BOUNDARY + _op_name = "BOUNDARY" + +class Branch(RegexBase): + def __init__(self, branches): + RegexBase.__init__(self) + self.branches = branches + + def fix_groups(self, pattern, reverse, fuzzy): + for b in self.branches: + b.fix_groups(pattern, reverse, fuzzy) + + def optimise(self, info, reverse): + if not self.branches: + return Sequence([]) + + # Flatten branches within branches. + branches = Branch._flatten_branches(info, reverse, self.branches) + + # Move any common prefix or suffix out of the branches. + if reverse: + suffix, branches = Branch._split_common_suffix(info, branches) + prefix = [] + else: + prefix, branches = Branch._split_common_prefix(info, branches) + suffix = [] + + # Try to reduce adjacent single-character branches to sets. + branches = Branch._reduce_to_set(info, reverse, branches) + + if len(branches) > 1: + sequence = [Branch(branches)] + + if not prefix or not suffix: + # We might be able to add a quick precheck before the branches. + firstset = self._add_precheck(info, reverse, branches) + + if firstset: + if reverse: + sequence.append(firstset) + else: + sequence.insert(0, firstset) + else: + sequence = branches + + return make_sequence(prefix + sequence + suffix) + + def _add_precheck(self, info, reverse, branches): + charset = set() + pos = -1 if reverse else 0 + + for branch in branches: + if type(branch) is Literal and branch.case_flags == NOCASE: + charset.add(branch.characters[pos]) + else: + return + + if not charset: + return None + + return _check_firstset(info, reverse, [Character(c) for c in charset]) + + def pack_characters(self, info): + self.branches = [b.pack_characters(info) for b in self.branches] + return self + + def remove_captures(self): + self.branches = [b.remove_captures() for b in self.branches] + return self + + def is_atomic(self): + return all(b.is_atomic() for b in self.branches) + + def can_be_affix(self): + return all(b.can_be_affix() for b in self.branches) + + def contains_group(self): + return any(b.contains_group() for b in self.branches) + + def get_firstset(self, reverse): + fs = set() + for b in self.branches: + fs |= b.get_firstset(reverse) + + return fs or set([None]) + + def _compile(self, reverse, fuzzy): + if not self.branches: + return [] + + code = [(OP.BRANCH, )] + for b in self.branches: + code.extend(b.compile(reverse, fuzzy)) + code.append((OP.NEXT, )) + + code[-1] = (OP.END, ) + + return code + + def dump(self, indent, reverse): + print("{}BRANCH".format(INDENT * indent)) + self.branches[0].dump(indent + 1, reverse) + for b in self.branches[1 : ]: + print("{}OR".format(INDENT * indent)) + b.dump(indent + 1, reverse) + + @staticmethod + def _flatten_branches(info, reverse, branches): + # Flatten the branches so that there aren't branches of branches. + new_branches = [] + for b in branches: + b = b.optimise(info, reverse) + if isinstance(b, Branch): + new_branches.extend(b.branches) + else: + new_branches.append(b) + + return new_branches + + @staticmethod + def _split_common_prefix(info, branches): + # Common leading items can be moved out of the branches. + # Get the items in the branches. + alternatives = [] + for b in branches: + if isinstance(b, Sequence): + alternatives.append(b.items) + else: + alternatives.append([b]) + + # What is the maximum possible length of the prefix? + max_count = min(len(a) for a in alternatives) + + # What is the longest common prefix? + prefix = alternatives[0] + pos = 0 + end_pos = max_count + while pos < end_pos and prefix[pos].can_be_affix() and all(a[pos] == + prefix[pos] for a in alternatives): + pos += 1 + count = pos + + if info.flags & UNICODE: + # We need to check that we're not splitting a sequence of + # characters which could form part of full case-folding. + count = pos + while count > 0 and not all(Branch._can_split(a, count) for a in + alternatives): + count -= 1 + + # No common prefix is possible. + if count == 0: + return [], branches + + # Rebuild the branches. + new_branches = [] + for a in alternatives: + new_branches.append(make_sequence(a[count : ])) + + return prefix[ : count], new_branches + + @staticmethod + def _split_common_suffix(info, branches): + # Common trailing items can be moved out of the branches. + # Get the items in the branches. + alternatives = [] + for b in branches: + if isinstance(b, Sequence): + alternatives.append(b.items) + else: + alternatives.append([b]) + + # What is the maximum possible length of the suffix? + max_count = min(len(a) for a in alternatives) + + # What is the longest common suffix? + suffix = alternatives[0] + pos = -1 + end_pos = -1 - max_count + while pos > end_pos and suffix[pos].can_be_affix() and all(a[pos] == + suffix[pos] for a in alternatives): + pos -= 1 + count = -1 - pos + + if info.flags & UNICODE: + # We need to check that we're not splitting a sequence of + # characters which could form part of full case-folding. + while count > 0 and not all(Branch._can_split_rev(a, count) for a + in alternatives): + count -= 1 + + # No common suffix is possible. + if count == 0: + return [], branches + + # Rebuild the branches. + new_branches = [] + for a in alternatives: + new_branches.append(make_sequence(a[ : -count])) + + return suffix[-count : ], new_branches + + @staticmethod + def _can_split(items, count): + # Check the characters either side of the proposed split. + if not Branch._is_full_case(items, count - 1): + return True + + if not Branch._is_full_case(items, count): + return True + + # Check whether a 1-1 split would be OK. + if Branch._is_folded(items[count - 1 : count + 1]): + return False + + # Check whether a 1-2 split would be OK. + if (Branch._is_full_case(items, count + 2) and + Branch._is_folded(items[count - 1 : count + 2])): + return False + + # Check whether a 2-1 split would be OK. + if (Branch._is_full_case(items, count - 2) and + Branch._is_folded(items[count - 2 : count + 1])): + return False + + return True + + @staticmethod + def _can_split_rev(items, count): + end = len(items) + + # Check the characters either side of the proposed split. + if not Branch._is_full_case(items, end - count): + return True + + if not Branch._is_full_case(items, end - count - 1): + return True + + # Check whether a 1-1 split would be OK. + if Branch._is_folded(items[end - count - 1 : end - count + 1]): + return False + + # Check whether a 1-2 split would be OK. + if (Branch._is_full_case(items, end - count + 2) and + Branch._is_folded(items[end - count - 1 : end - count + 2])): + return False + + # Check whether a 2-1 split would be OK. + if (Branch._is_full_case(items, end - count - 2) and + Branch._is_folded(items[end - count - 2 : end - count + 1])): + return False + + return True + + @staticmethod + def _merge_common_prefixes(info, reverse, branches): + # Branches with the same case-sensitive character prefix can be grouped + # together if they are separated only by other branches with a + # character prefix. + prefixed = defaultdict(list) + order = {} + new_branches = [] + for b in branches: + if Branch._is_simple_character(b): + # Branch starts with a simple character. + prefixed[b.value].append([b]) + order.setdefault(b.value, len(order)) + elif (isinstance(b, Sequence) and b.items and + Branch._is_simple_character(b.items[0])): + # Branch starts with a simple character. + prefixed[b.items[0].value].append(b.items) + order.setdefault(b.items[0].value, len(order)) + else: + Branch._flush_char_prefix(info, reverse, prefixed, order, + new_branches) + + new_branches.append(b) + + Branch._flush_char_prefix(info, prefixed, order, new_branches) + + return new_branches + + @staticmethod + def _is_simple_character(c): + return isinstance(c, Character) and c.positive and not c.case_flags + + @staticmethod + def _reduce_to_set(info, reverse, branches): + # Can the branches be reduced to a set? + new_branches = [] + items = set() + case_flags = NOCASE + for b in branches: + if isinstance(b, (Character, Property, SetBase)): + # Branch starts with a single character. + if b.case_flags != case_flags: + # Different case sensitivity, so flush. + Branch._flush_set_members(info, reverse, items, case_flags, + new_branches) + + case_flags = b.case_flags + + items.add(b.with_flags(case_flags=NOCASE)) + else: + Branch._flush_set_members(info, reverse, items, case_flags, + new_branches) + + new_branches.append(b) + + Branch._flush_set_members(info, reverse, items, case_flags, + new_branches) + + return new_branches + + @staticmethod + def _flush_char_prefix(info, reverse, prefixed, order, new_branches): + # Flush the prefixed branches. + if not prefixed: + return + + for value, branches in sorted(prefixed.items(), key=lambda pair: + order[pair[0]]): + if len(branches) == 1: + new_branches.append(make_sequence(branches[0])) + else: + subbranches = [] + optional = False + for b in branches: + if len(b) > 1: + subbranches.append(make_sequence(b[1 : ])) + elif not optional: + subbranches.append(Sequence()) + optional = True + + sequence = Sequence([Character(value), Branch(subbranches)]) + new_branches.append(sequence.optimise(info, reverse)) + + prefixed.clear() + order.clear() + + @staticmethod + def _flush_set_members(info, reverse, items, case_flags, new_branches): + # Flush the set members. + if not items: + return + + if len(items) == 1: + item = list(items)[0] + else: + item = SetUnion(info, list(items)).optimise(info, reverse) + + new_branches.append(item.with_flags(case_flags=case_flags)) + + items.clear() + + @staticmethod + def _is_full_case(items, i): + if not 0 <= i < len(items): + return False + + item = items[i] + return (isinstance(item, Character) and item.positive and + (item.case_flags & FULLIGNORECASE) == FULLIGNORECASE) + + @staticmethod + def _is_folded(items): + if len(items) < 2: + return False + + for i in items: + if (not isinstance(i, Character) or not i.positive or not + i.case_flags): + return False + + folded = "".join(chr(i.value) for i in items) + folded = _regex.fold_case(FULL_CASE_FOLDING, folded) + + # Get the characters which expand to multiple codepoints on folding. + expanding_chars = _regex.get_expand_on_folding() + + for c in expanding_chars: + if folded == _regex.fold_case(FULL_CASE_FOLDING, c): + return True + + return False + + def is_empty(self): + return all(b.is_empty() for b in self.branches) + + def __eq__(self, other): + return type(self) is type(other) and self.branches == other.branches + + def max_width(self): + return max(b.max_width() for b in self.branches) + +class CallGroup(RegexBase): + def __init__(self, info, group, position): + RegexBase.__init__(self) + self.info = info + self.group = group + self.position = position + + self._key = self.__class__, self.group + + def fix_groups(self, pattern, reverse, fuzzy): + try: + self.group = int(self.group) + except ValueError: + try: + self.group = self.info.group_index[self.group] + except KeyError: + raise error("invalid group reference", pattern, self.position) + + if not 0 <= self.group <= self.info.group_count: + raise error("unknown group", pattern, self.position) + + if self.group > 0 and self.info.open_group_count[self.group] > 1: + raise error("ambiguous group reference", pattern, self.position) + + self.info.group_calls.append((self, reverse, fuzzy)) + + self._key = self.__class__, self.group + + def remove_captures(self): + raise error("group reference not allowed", self.pattern, self.position) + + def _compile(self, reverse, fuzzy): + return [(OP.GROUP_CALL, self.call_ref)] + + def dump(self, indent, reverse): + print("{}GROUP_CALL {}".format(INDENT * indent, self.group)) + + def __eq__(self, other): + return type(self) is type(other) and self.group == other.group + + def max_width(self): + return UNLIMITED + + def __del__(self): + self.info = None + +class CallRef(RegexBase): + def __init__(self, ref, parsed): + self.ref = ref + self.parsed = parsed + + def _compile(self, reverse, fuzzy): + return ([(OP.CALL_REF, self.ref)] + self.parsed._compile(reverse, + fuzzy) + [(OP.END, )]) + +class Character(RegexBase): + _opcode = {(NOCASE, False): OP.CHARACTER, (IGNORECASE, False): + OP.CHARACTER_IGN, (FULLCASE, False): OP.CHARACTER, (FULLIGNORECASE, + False): OP.CHARACTER_IGN, (NOCASE, True): OP.CHARACTER_REV, (IGNORECASE, + True): OP.CHARACTER_IGN_REV, (FULLCASE, True): OP.CHARACTER_REV, + (FULLIGNORECASE, True): OP.CHARACTER_IGN_REV} + + def __init__(self, value, positive=True, case_flags=NOCASE, + zerowidth=False): + RegexBase.__init__(self) + self.value = value + self.positive = bool(positive) + self.case_flags = CASE_FLAGS_COMBINATIONS[case_flags] + self.zerowidth = bool(zerowidth) + + if (self.positive and (self.case_flags & FULLIGNORECASE) == + FULLIGNORECASE): + self.folded = _regex.fold_case(FULL_CASE_FOLDING, chr(self.value)) + else: + self.folded = chr(self.value) + + self._key = (self.__class__, self.value, self.positive, + self.case_flags, self.zerowidth) + + def rebuild(self, positive, case_flags, zerowidth): + return Character(self.value, positive, case_flags, zerowidth) + + def optimise(self, info, reverse, in_set=False): + return self + + def get_firstset(self, reverse): + return set([self]) + + def has_simple_start(self): + return True + + def _compile(self, reverse, fuzzy): + flags = 0 + if self.positive: + flags |= POSITIVE_OP + if self.zerowidth: + flags |= ZEROWIDTH_OP + if fuzzy: + flags |= FUZZY_OP + + code = PrecompiledCode([self._opcode[self.case_flags, reverse], flags, + self.value]) + + if len(self.folded) > 1: + # The character expands on full case-folding. + code = Branch([code, String([ord(c) for c in self.folded], + case_flags=self.case_flags)]) + + return code.compile(reverse, fuzzy) + + def dump(self, indent, reverse): + display = ascii(chr(self.value)).lstrip("bu") + print("{}CHARACTER {} {}{}".format(INDENT * indent, + POS_TEXT[self.positive], display, CASE_TEXT[self.case_flags])) + + def matches(self, ch): + return (ch == self.value) == self.positive + + def max_width(self): + return len(self.folded) + + def get_required_string(self, reverse): + if not self.positive: + return 1, None + + self.folded_characters = tuple(ord(c) for c in self.folded) + + return 0, self + +class Conditional(RegexBase): + def __init__(self, info, group, yes_item, no_item, position): + RegexBase.__init__(self) + self.info = info + self.group = group + self.yes_item = yes_item + self.no_item = no_item + self.position = position + + def fix_groups(self, pattern, reverse, fuzzy): + try: + self.group = int(self.group) + except ValueError: + try: + self.group = self.info.group_index[self.group] + except KeyError: + if self.group == 'DEFINE': + # 'DEFINE' is a special name unless there's a group with + # that name. + self.group = 0 + else: + raise error("unknown group", pattern, self.position) + + if not 0 <= self.group <= self.info.group_count: + raise error("invalid group reference", pattern, self.position) + + self.yes_item.fix_groups(pattern, reverse, fuzzy) + self.no_item.fix_groups(pattern, reverse, fuzzy) + + def optimise(self, info, reverse): + yes_item = self.yes_item.optimise(info, reverse) + no_item = self.no_item.optimise(info, reverse) + + return Conditional(info, self.group, yes_item, no_item, self.position) + + def pack_characters(self, info): + self.yes_item = self.yes_item.pack_characters(info) + self.no_item = self.no_item.pack_characters(info) + return self + + def remove_captures(self): + self.yes_item = self.yes_item.remove_captures() + self.no_item = self.no_item.remove_captures() + + def is_atomic(self): + return self.yes_item.is_atomic() and self.no_item.is_atomic() + + def can_be_affix(self): + return self.yes_item.can_be_affix() and self.no_item.can_be_affix() + + def contains_group(self): + return self.yes_item.contains_group() or self.no_item.contains_group() + + def get_firstset(self, reverse): + return (self.yes_item.get_firstset(reverse) | + self.no_item.get_firstset(reverse)) + + def _compile(self, reverse, fuzzy): + code = [(OP.GROUP_EXISTS, self.group)] + code.extend(self.yes_item.compile(reverse, fuzzy)) + add_code = self.no_item.compile(reverse, fuzzy) + if add_code: + code.append((OP.NEXT, )) + code.extend(add_code) + + code.append((OP.END, )) + + return code + + def dump(self, indent, reverse): + print("{}GROUP_EXISTS {}".format(INDENT * indent, self.group)) + self.yes_item.dump(indent + 1, reverse) + if not self.no_item.is_empty(): + print("{}OR".format(INDENT * indent)) + self.no_item.dump(indent + 1, reverse) + + def is_empty(self): + return self.yes_item.is_empty() and self.no_item.is_empty() + + def __eq__(self, other): + return type(self) is type(other) and (self.group, self.yes_item, + self.no_item) == (other.group, other.yes_item, other.no_item) + + def max_width(self): + return max(self.yes_item.max_width(), self.no_item.max_width()) + + def __del__(self): + self.info = None + +class DefaultBoundary(ZeroWidthBase): + _opcode = OP.DEFAULT_BOUNDARY + _op_name = "DEFAULT_BOUNDARY" + +class DefaultEndOfWord(ZeroWidthBase): + _opcode = OP.DEFAULT_END_OF_WORD + _op_name = "DEFAULT_END_OF_WORD" + +class DefaultStartOfWord(ZeroWidthBase): + _opcode = OP.DEFAULT_START_OF_WORD + _op_name = "DEFAULT_START_OF_WORD" + +class EndOfLine(ZeroWidthBase): + _opcode = OP.END_OF_LINE + _op_name = "END_OF_LINE" + +class EndOfLineU(EndOfLine): + _opcode = OP.END_OF_LINE_U + _op_name = "END_OF_LINE_U" + +class EndOfString(ZeroWidthBase): + _opcode = OP.END_OF_STRING + _op_name = "END_OF_STRING" + +class EndOfStringLine(ZeroWidthBase): + _opcode = OP.END_OF_STRING_LINE + _op_name = "END_OF_STRING_LINE" + +class EndOfStringLineU(EndOfStringLine): + _opcode = OP.END_OF_STRING_LINE_U + _op_name = "END_OF_STRING_LINE_U" + +class EndOfWord(ZeroWidthBase): + _opcode = OP.END_OF_WORD + _op_name = "END_OF_WORD" + +class Failure(ZeroWidthBase): + _op_name = "FAILURE" + + def _compile(self, reverse, fuzzy): + return [(OP.FAILURE, )] + +class Fuzzy(RegexBase): + def __init__(self, subpattern, constraints=None): + RegexBase.__init__(self) + if constraints is None: + constraints = {} + self.subpattern = subpattern + self.constraints = constraints + + # If an error type is mentioned in the cost equation, then its maximum + # defaults to unlimited. + if "cost" in constraints: + for e in "dis": + if e in constraints["cost"]: + constraints.setdefault(e, (0, None)) + + # If any error type is mentioned, then all the error maxima default to + # 0, otherwise they default to unlimited. + if set(constraints) & set("dis"): + for e in "dis": + constraints.setdefault(e, (0, 0)) + else: + for e in "dis": + constraints.setdefault(e, (0, None)) + + # The maximum of the generic error type defaults to unlimited. + constraints.setdefault("e", (0, None)) + + # The cost equation defaults to equal costs. Also, the cost of any + # error type not mentioned in the cost equation defaults to 0. + if "cost" in constraints: + for e in "dis": + constraints["cost"].setdefault(e, 0) + else: + constraints["cost"] = {"d": 1, "i": 1, "s": 1, "max": + constraints["e"][1]} + + def fix_groups(self, pattern, reverse, fuzzy): + self.subpattern.fix_groups(pattern, reverse, True) + + def pack_characters(self, info): + self.subpattern = self.subpattern.pack_characters(info) + return self + + def remove_captures(self): + self.subpattern = self.subpattern.remove_captures() + return self + + def is_atomic(self): + return self.subpattern.is_atomic() + + def contains_group(self): + return self.subpattern.contains_group() + + def _compile(self, reverse, fuzzy): + # The individual limits. + arguments = [] + for e in "dise": + v = self.constraints[e] + arguments.append(v[0]) + arguments.append(UNLIMITED if v[1] is None else v[1]) + + # The coeffs of the cost equation. + for e in "dis": + arguments.append(self.constraints["cost"][e]) + + # The maximum of the cost equation. + v = self.constraints["cost"]["max"] + arguments.append(UNLIMITED if v is None else v) + + flags = 0 + if reverse: + flags |= REVERSE_OP + + test = self.constraints.get("test") + + if test: + return ([(OP.FUZZY_EXT, flags) + tuple(arguments)] + + test.compile(reverse, True) + [(OP.NEXT,)] + + self.subpattern.compile(reverse, True) + [(OP.END,)]) + + return ([(OP.FUZZY, flags) + tuple(arguments)] + + self.subpattern.compile(reverse, True) + [(OP.END,)]) + + def dump(self, indent, reverse): + constraints = self._constraints_to_string() + if constraints: + constraints = " " + constraints + print("{}FUZZY{}".format(INDENT * indent, constraints)) + self.subpattern.dump(indent + 1, reverse) + + def is_empty(self): + return self.subpattern.is_empty() + + def __eq__(self, other): + return (type(self) is type(other) and self.subpattern == + other.subpattern and self.constraints == other.constraints) + + def max_width(self): + return UNLIMITED + + def _constraints_to_string(self): + constraints = [] + + for name in "ids": + min, max = self.constraints[name] + if max == 0: + continue + + con = "" + + if min > 0: + con = "{}<=".format(min) + + con += name + + if max is not None: + con += "<={}".format(max) + + constraints.append(con) + + cost = [] + for name in "ids": + coeff = self.constraints["cost"][name] + if coeff > 0: + cost.append("{}{}".format(coeff, name)) + + limit = self.constraints["cost"]["max"] + if limit is not None and limit > 0: + cost = "{}<={}".format("+".join(cost), limit) + constraints.append(cost) + + return ",".join(constraints) + +class Grapheme(RegexBase): + def _compile(self, reverse, fuzzy): + # Match at least 1 character until a grapheme boundary is reached. Note + # that this is the same whether matching forwards or backwards. + grapheme_matcher = Atomic(Sequence([LazyRepeat(AnyAll(), 1, None), + GraphemeBoundary()])) + + return grapheme_matcher.compile(reverse, fuzzy) + + def dump(self, indent, reverse): + print("{}GRAPHEME".format(INDENT * indent)) + + def max_width(self): + return UNLIMITED + +class GraphemeBoundary: + def compile(self, reverse, fuzzy): + return [(OP.GRAPHEME_BOUNDARY, 1)] + +class GreedyRepeat(RegexBase): + _opcode = OP.GREEDY_REPEAT + _op_name = "GREEDY_REPEAT" + + def __init__(self, subpattern, min_count, max_count): + RegexBase.__init__(self) + self.subpattern = subpattern + self.min_count = min_count + self.max_count = max_count + + def fix_groups(self, pattern, reverse, fuzzy): + self.subpattern.fix_groups(pattern, reverse, fuzzy) + + def optimise(self, info, reverse): + subpattern = self.subpattern.optimise(info, reverse) + + return type(self)(subpattern, self.min_count, self.max_count) + + def pack_characters(self, info): + self.subpattern = self.subpattern.pack_characters(info) + return self + + def remove_captures(self): + self.subpattern = self.subpattern.remove_captures() + return self + + def is_atomic(self): + return self.min_count == self.max_count and self.subpattern.is_atomic() + + def can_be_affix(self): + return False + + def contains_group(self): + return self.subpattern.contains_group() + + def get_firstset(self, reverse): + fs = self.subpattern.get_firstset(reverse) + if self.min_count == 0: + fs.add(None) + + return fs + + def _compile(self, reverse, fuzzy): + repeat = [self._opcode, self.min_count] + if self.max_count is None: + repeat.append(UNLIMITED) + else: + repeat.append(self.max_count) + + subpattern = self.subpattern.compile(reverse, fuzzy) + if not subpattern: + return [] + + return ([tuple(repeat)] + subpattern + [(OP.END, )]) + + def dump(self, indent, reverse): + if self.max_count is None: + limit = "INF" + else: + limit = self.max_count + print("{}{} {} {}".format(INDENT * indent, self._op_name, + self.min_count, limit)) + + self.subpattern.dump(indent + 1, reverse) + + def is_empty(self): + return self.subpattern.is_empty() + + def __eq__(self, other): + return type(self) is type(other) and (self.subpattern, self.min_count, + self.max_count) == (other.subpattern, other.min_count, + other.max_count) + + def max_width(self): + if self.max_count is None: + return UNLIMITED + + return self.subpattern.max_width() * self.max_count + + def get_required_string(self, reverse): + max_count = UNLIMITED if self.max_count is None else self.max_count + if self.min_count == 0: + w = self.subpattern.max_width() * max_count + return min(w, UNLIMITED), None + + ofs, req = self.subpattern.get_required_string(reverse) + if req: + return ofs, req + + w = self.subpattern.max_width() * max_count + return min(w, UNLIMITED), None + +class PossessiveRepeat(GreedyRepeat): + def is_atomic(self): + return True + + def _compile(self, reverse, fuzzy): + subpattern = self.subpattern.compile(reverse, fuzzy) + if not subpattern: + return [] + + repeat = [self._opcode, self.min_count] + if self.max_count is None: + repeat.append(UNLIMITED) + else: + repeat.append(self.max_count) + + return ([(OP.ATOMIC, ), tuple(repeat)] + subpattern + [(OP.END, ), + (OP.END, )]) + + def dump(self, indent, reverse): + print("{}ATOMIC".format(INDENT * indent)) + + if self.max_count is None: + limit = "INF" + else: + limit = self.max_count + print("{}{} {} {}".format(INDENT * (indent + 1), self._op_name, + self.min_count, limit)) + + self.subpattern.dump(indent + 2, reverse) + +class Group(RegexBase): + def __init__(self, info, group, subpattern): + RegexBase.__init__(self) + self.info = info + self.group = group + self.subpattern = subpattern + + self.call_ref = None + + def fix_groups(self, pattern, reverse, fuzzy): + self.info.defined_groups[self.group] = (self, reverse, fuzzy) + self.subpattern.fix_groups(pattern, reverse, fuzzy) + + def optimise(self, info, reverse): + subpattern = self.subpattern.optimise(info, reverse) + + return Group(self.info, self.group, subpattern) + + def pack_characters(self, info): + self.subpattern = self.subpattern.pack_characters(info) + return self + + def remove_captures(self): + return self.subpattern.remove_captures() + + def is_atomic(self): + return self.subpattern.is_atomic() + + def can_be_affix(self): + return False + + def contains_group(self): + return True + + def get_firstset(self, reverse): + return self.subpattern.get_firstset(reverse) + + def has_simple_start(self): + return self.subpattern.has_simple_start() + + def _compile(self, reverse, fuzzy): + code = [] + + public_group = private_group = self.group + if private_group < 0: + public_group = self.info.private_groups[private_group] + private_group = self.info.group_count - private_group + + key = self.group, reverse, fuzzy + ref = self.info.call_refs.get(key) + if ref is not None: + code += [(OP.CALL_REF, ref)] + + code += [(OP.GROUP, int(not reverse), private_group, public_group)] + code += self.subpattern.compile(reverse, fuzzy) + code += [(OP.END, )] + + if ref is not None: + code += [(OP.END, )] + + return code + + def dump(self, indent, reverse): + group = self.group + if group < 0: + group = self.info.private_groups[group] + print("{}GROUP {}".format(INDENT * indent, group)) + self.subpattern.dump(indent + 1, reverse) + + def __eq__(self, other): + return (type(self) is type(other) and (self.group, self.subpattern) == + (other.group, other.subpattern)) + + def max_width(self): + return self.subpattern.max_width() + + def get_required_string(self, reverse): + return self.subpattern.get_required_string(reverse) + + def __del__(self): + self.info = None + +class Keep(ZeroWidthBase): + _opcode = OP.KEEP + _op_name = "KEEP" + +class LazyRepeat(GreedyRepeat): + _opcode = OP.LAZY_REPEAT + _op_name = "LAZY_REPEAT" + +class LookAround(RegexBase): + _dir_text = {False: "AHEAD", True: "BEHIND"} + + def __init__(self, behind, positive, subpattern): + RegexBase.__init__(self) + self.behind = bool(behind) + self.positive = bool(positive) + self.subpattern = subpattern + + def fix_groups(self, pattern, reverse, fuzzy): + self.subpattern.fix_groups(pattern, self.behind, fuzzy) + + def optimise(self, info, reverse): + subpattern = self.subpattern.optimise(info, self.behind) + if self.positive and subpattern.is_empty(): + return subpattern + + return LookAround(self.behind, self.positive, subpattern) + + def pack_characters(self, info): + self.subpattern = self.subpattern.pack_characters(info) + return self + + def remove_captures(self): + return self.subpattern.remove_captures() + + def is_atomic(self): + return self.subpattern.is_atomic() + + def can_be_affix(self): + return self.subpattern.can_be_affix() + + def contains_group(self): + return self.subpattern.contains_group() + + def get_firstset(self, reverse): + if self.positive and self.behind == reverse: + return self.subpattern.get_firstset(reverse) + + return set([None]) + + def _compile(self, reverse, fuzzy): + flags = 0 + if self.positive: + flags |= POSITIVE_OP + if fuzzy: + flags |= FUZZY_OP + if reverse: + flags |= REVERSE_OP + + return ([(OP.LOOKAROUND, flags, int(not self.behind))] + + self.subpattern.compile(self.behind) + [(OP.END, )]) + + def dump(self, indent, reverse): + print("{}LOOK{} {}".format(INDENT * indent, + self._dir_text[self.behind], POS_TEXT[self.positive])) + self.subpattern.dump(indent + 1, self.behind) + + def is_empty(self): + return self.positive and self.subpattern.is_empty() + + def __eq__(self, other): + return type(self) is type(other) and (self.behind, self.positive, + self.subpattern) == (other.behind, other.positive, other.subpattern) + + def max_width(self): + return 0 + +class LookAroundConditional(RegexBase): + _dir_text = {False: "AHEAD", True: "BEHIND"} + + def __init__(self, behind, positive, subpattern, yes_item, no_item): + RegexBase.__init__(self) + self.behind = bool(behind) + self.positive = bool(positive) + self.subpattern = subpattern + self.yes_item = yes_item + self.no_item = no_item + + def fix_groups(self, pattern, reverse, fuzzy): + self.subpattern.fix_groups(pattern, reverse, fuzzy) + self.yes_item.fix_groups(pattern, reverse, fuzzy) + self.no_item.fix_groups(pattern, reverse, fuzzy) + + def optimise(self, info, reverse): + subpattern = self.subpattern.optimise(info, self.behind) + yes_item = self.yes_item.optimise(info, self.behind) + no_item = self.no_item.optimise(info, self.behind) + + return LookAroundConditional(self.behind, self.positive, subpattern, + yes_item, no_item) + + def pack_characters(self, info): + self.subpattern = self.subpattern.pack_characters(info) + self.yes_item = self.yes_item.pack_characters(info) + self.no_item = self.no_item.pack_characters(info) + return self + + def remove_captures(self): + self.subpattern = self.subpattern.remove_captures() + self.yes_item = self.yes_item.remove_captures() + self.no_item = self.no_item.remove_captures() + + def is_atomic(self): + return (self.subpattern.is_atomic() and self.yes_item.is_atomic() and + self.no_item.is_atomic()) + + def can_be_affix(self): + return (self.subpattern.can_be_affix() and self.yes_item.can_be_affix() + and self.no_item.can_be_affix()) + + def contains_group(self): + return (self.subpattern.contains_group() or + self.yes_item.contains_group() or self.no_item.contains_group()) + + def _compile(self, reverse, fuzzy): + code = [(OP.CONDITIONAL, int(self.positive), int(not self.behind))] + code.extend(self.subpattern.compile(self.behind, fuzzy)) + code.append((OP.NEXT, )) + code.extend(self.yes_item.compile(reverse, fuzzy)) + add_code = self.no_item.compile(reverse, fuzzy) + if add_code: + code.append((OP.NEXT, )) + code.extend(add_code) + + code.append((OP.END, )) + + return code + + def dump(self, indent, reverse): + print("{}CONDITIONAL {} {}".format(INDENT * indent, + self._dir_text[self.behind], POS_TEXT[self.positive])) + self.subpattern.dump(indent + 1, self.behind) + print("{}EITHER".format(INDENT * indent)) + self.yes_item.dump(indent + 1, reverse) + if not self.no_item.is_empty(): + print("{}OR".format(INDENT * indent)) + self.no_item.dump(indent + 1, reverse) + + def is_empty(self): + return (self.subpattern.is_empty() and self.yes_item.is_empty() or + self.no_item.is_empty()) + + def __eq__(self, other): + return type(self) is type(other) and (self.subpattern, self.yes_item, + self.no_item) == (other.subpattern, other.yes_item, other.no_item) + + def max_width(self): + return max(self.yes_item.max_width(), self.no_item.max_width()) + + def get_required_string(self, reverse): + return self.max_width(), None + +class PrecompiledCode(RegexBase): + def __init__(self, code): + self.code = code + + def _compile(self, reverse, fuzzy): + return [tuple(self.code)] + +class Property(RegexBase): + _opcode = {(NOCASE, False): OP.PROPERTY, (IGNORECASE, False): + OP.PROPERTY_IGN, (FULLCASE, False): OP.PROPERTY, (FULLIGNORECASE, False): + OP.PROPERTY_IGN, (NOCASE, True): OP.PROPERTY_REV, (IGNORECASE, True): + OP.PROPERTY_IGN_REV, (FULLCASE, True): OP.PROPERTY_REV, (FULLIGNORECASE, + True): OP.PROPERTY_IGN_REV} + + def __init__(self, value, positive=True, case_flags=NOCASE, + zerowidth=False, encoding=0): + RegexBase.__init__(self) + self.value = value + self.positive = bool(positive) + self.case_flags = CASE_FLAGS_COMBINATIONS[case_flags] + self.zerowidth = bool(zerowidth) + self.encoding = encoding + + self._key = (self.__class__, self.value, self.positive, + self.case_flags, self.zerowidth) + + def rebuild(self, positive, case_flags, zerowidth): + return Property(self.value, positive, case_flags, zerowidth, + self.encoding) + + def optimise(self, info, reverse, in_set=False): + return self + + def get_firstset(self, reverse): + return set([self]) + + def has_simple_start(self): + return True + + def _compile(self, reverse, fuzzy): + flags = 0 + if self.positive: + flags |= POSITIVE_OP + if self.zerowidth: + flags |= ZEROWIDTH_OP + if fuzzy: + flags |= FUZZY_OP + flags |= self.encoding << ENCODING_OP_SHIFT + return [(self._opcode[self.case_flags, reverse], flags, self.value)] + + def dump(self, indent, reverse): + prop = PROPERTY_NAMES[self.value >> 16] + name, value = prop[0], prop[1][self.value & 0xFFFF] + print("{}PROPERTY {} {}:{}{}{}".format(INDENT * indent, + POS_TEXT[self.positive], name, value, CASE_TEXT[self.case_flags], + ["", " ASCII"][self.encoding])) + + def matches(self, ch): + return _regex.has_property_value(self.value, ch) == self.positive + + def max_width(self): + return 1 + +class Prune(ZeroWidthBase): + _op_name = "PRUNE" + + def _compile(self, reverse, fuzzy): + return [(OP.PRUNE, )] + +class Range(RegexBase): + _opcode = {(NOCASE, False): OP.RANGE, (IGNORECASE, False): OP.RANGE_IGN, + (FULLCASE, False): OP.RANGE, (FULLIGNORECASE, False): OP.RANGE_IGN, + (NOCASE, True): OP.RANGE_REV, (IGNORECASE, True): OP.RANGE_IGN_REV, + (FULLCASE, True): OP.RANGE_REV, (FULLIGNORECASE, True): OP.RANGE_IGN_REV} + _op_name = "RANGE" + + def __init__(self, lower, upper, positive=True, case_flags=NOCASE, + zerowidth=False): + RegexBase.__init__(self) + self.lower = lower + self.upper = upper + self.positive = bool(positive) + self.case_flags = CASE_FLAGS_COMBINATIONS[case_flags] + self.zerowidth = bool(zerowidth) + + self._key = (self.__class__, self.lower, self.upper, self.positive, + self.case_flags, self.zerowidth) + + def rebuild(self, positive, case_flags, zerowidth): + return Range(self.lower, self.upper, positive, case_flags, zerowidth) + + def optimise(self, info, reverse, in_set=False): + # Is the range case-sensitive? + if not self.positive or not (self.case_flags & IGNORECASE) or in_set: + return self + + # Is full case-folding possible? + if (not (info.flags & UNICODE) or (self.case_flags & FULLIGNORECASE) != + FULLIGNORECASE): + return self + + # Get the characters which expand to multiple codepoints on folding. + expanding_chars = _regex.get_expand_on_folding() + + # Get the folded characters in the range. + items = [] + for ch in expanding_chars: + if self.lower <= ord(ch) <= self.upper: + folded = _regex.fold_case(FULL_CASE_FOLDING, ch) + items.append(String([ord(c) for c in folded], + case_flags=self.case_flags)) + + if not items: + # We can fall back to simple case-folding. + return self + + if len(items) < self.upper - self.lower + 1: + # Not all the characters are covered by the full case-folding. + items.insert(0, self) + + return Branch(items) + + def _compile(self, reverse, fuzzy): + flags = 0 + if self.positive: + flags |= POSITIVE_OP + if self.zerowidth: + flags |= ZEROWIDTH_OP + if fuzzy: + flags |= FUZZY_OP + return [(self._opcode[self.case_flags, reverse], flags, self.lower, + self.upper)] + + def dump(self, indent, reverse): + display_lower = ascii(chr(self.lower)).lstrip("bu") + display_upper = ascii(chr(self.upper)).lstrip("bu") + print("{}RANGE {} {} {}{}".format(INDENT * indent, + POS_TEXT[self.positive], display_lower, display_upper, + CASE_TEXT[self.case_flags])) + + def matches(self, ch): + return (self.lower <= ch <= self.upper) == self.positive + + def max_width(self): + return 1 + +class RefGroup(RegexBase): + _opcode = {(NOCASE, False): OP.REF_GROUP, (IGNORECASE, False): + OP.REF_GROUP_IGN, (FULLCASE, False): OP.REF_GROUP, (FULLIGNORECASE, + False): OP.REF_GROUP_FLD, (NOCASE, True): OP.REF_GROUP_REV, (IGNORECASE, + True): OP.REF_GROUP_IGN_REV, (FULLCASE, True): OP.REF_GROUP_REV, + (FULLIGNORECASE, True): OP.REF_GROUP_FLD_REV} + + def __init__(self, info, group, position, case_flags=NOCASE): + RegexBase.__init__(self) + self.info = info + self.group = group + self.position = position + self.case_flags = CASE_FLAGS_COMBINATIONS[case_flags] + + self._key = self.__class__, self.group, self.case_flags + + def fix_groups(self, pattern, reverse, fuzzy): + try: + self.group = int(self.group) + except ValueError: + try: + self.group = self.info.group_index[self.group] + except KeyError: + raise error("unknown group", pattern, self.position) + + if not 1 <= self.group <= self.info.group_count: + raise error("invalid group reference", pattern, self.position) + + self._key = self.__class__, self.group, self.case_flags + + def remove_captures(self): + raise error("group reference not allowed", self.pattern, self.position) + + def _compile(self, reverse, fuzzy): + flags = 0 + if fuzzy: + flags |= FUZZY_OP + return [(self._opcode[self.case_flags, reverse], flags, self.group)] + + def dump(self, indent, reverse): + print("{}REF_GROUP {}{}".format(INDENT * indent, self.group, + CASE_TEXT[self.case_flags])) + + def max_width(self): + return UNLIMITED + + def __del__(self): + self.info = None + +class SearchAnchor(ZeroWidthBase): + _opcode = OP.SEARCH_ANCHOR + _op_name = "SEARCH_ANCHOR" + +class Sequence(RegexBase): + def __init__(self, items=None): + RegexBase.__init__(self) + if items is None: + items = [] + + self.items = items + + def fix_groups(self, pattern, reverse, fuzzy): + for s in self.items: + s.fix_groups(pattern, reverse, fuzzy) + + def optimise(self, info, reverse): + # Flatten the sequences. + items = [] + for s in self.items: + s = s.optimise(info, reverse) + if isinstance(s, Sequence): + items.extend(s.items) + else: + items.append(s) + + return make_sequence(items) + + def pack_characters(self, info): + "Packs sequences of characters into strings." + items = [] + characters = [] + case_flags = NOCASE + for s in self.items: + if type(s) is Character and s.positive and not s.zerowidth: + if s.case_flags != case_flags: + # Different case sensitivity, so flush, unless neither the + # previous nor the new character are cased. + if s.case_flags or is_cased_i(info, s.value): + Sequence._flush_characters(info, characters, + case_flags, items) + + case_flags = s.case_flags + + characters.append(s.value) + elif type(s) is String or type(s) is Literal: + if s.case_flags != case_flags: + # Different case sensitivity, so flush, unless the neither + # the previous nor the new string are cased. + if s.case_flags or any(is_cased_i(info, c) for c in + characters): + Sequence._flush_characters(info, characters, + case_flags, items) + + case_flags = s.case_flags + + characters.extend(s.characters) + else: + Sequence._flush_characters(info, characters, case_flags, items) + + items.append(s.pack_characters(info)) + + Sequence._flush_characters(info, characters, case_flags, items) + + return make_sequence(items) + + def remove_captures(self): + self.items = [s.remove_captures() for s in self.items] + return self + + def is_atomic(self): + return all(s.is_atomic() for s in self.items) + + def can_be_affix(self): + return False + + def contains_group(self): + return any(s.contains_group() for s in self.items) + + def get_firstset(self, reverse): + fs = set() + items = self.items + if reverse: + items.reverse() + for s in items: + fs |= s.get_firstset(reverse) + if None not in fs: + return fs + fs.discard(None) + + return fs | set([None]) + + def has_simple_start(self): + return bool(self.items) and self.items[0].has_simple_start() + + def _compile(self, reverse, fuzzy): + seq = self.items + if reverse: + seq = seq[::-1] + + code = [] + for s in seq: + code.extend(s.compile(reverse, fuzzy)) + + return code + + def dump(self, indent, reverse): + for s in self.items: + s.dump(indent, reverse) + + @staticmethod + def _flush_characters(info, characters, case_flags, items): + if not characters: + return + + # Disregard case_flags if all of the characters are case-less. + if case_flags & IGNORECASE: + if not any(is_cased_i(info, c) for c in characters): + case_flags = NOCASE + + if (case_flags & FULLIGNORECASE) == FULLIGNORECASE: + literals = Sequence._fix_full_casefold(characters) + + for item in literals: + chars = item.characters + + if len(chars) == 1: + items.append(Character(chars[0], case_flags=item.case_flags)) + else: + items.append(String(chars, case_flags=item.case_flags)) + else: + if len(characters) == 1: + items.append(Character(characters[0], case_flags=case_flags)) + else: + items.append(String(characters, case_flags=case_flags)) + + characters[:] = [] + + @staticmethod + def _fix_full_casefold(characters): + # Split a literal needing full case-folding into chunks that need it + # and chunks that can use simple case-folding, which is faster. + expanded = [_regex.fold_case(FULL_CASE_FOLDING, c) for c in + _regex.get_expand_on_folding()] + string = _regex.fold_case(FULL_CASE_FOLDING, ''.join(chr(c) + for c in characters)).lower() + chunks = [] + + for e in expanded: + found = string.find(e) + + while found >= 0: + chunks.append((found, found + len(e))) + found = string.find(e, found + 1) + + pos = 0 + literals = [] + + for start, end in Sequence._merge_chunks(chunks): + if pos < start: + literals.append(Literal(characters[pos : start], + case_flags=IGNORECASE)) + + literals.append(Literal(characters[start : end], + case_flags=FULLIGNORECASE)) + pos = end + + if pos < len(characters): + literals.append(Literal(characters[pos : ], case_flags=IGNORECASE)) + + return literals + + @staticmethod + def _merge_chunks(chunks): + if len(chunks) < 2: + return chunks + + chunks.sort() + + start, end = chunks[0] + new_chunks = [] + + for s, e in chunks[1 : ]: + if s <= end: + end = max(end, e) + else: + new_chunks.append((start, end)) + start, end = s, e + + new_chunks.append((start, end)) + + return new_chunks + + def is_empty(self): + return all(i.is_empty() for i in self.items) + + def __eq__(self, other): + return type(self) is type(other) and self.items == other.items + + def max_width(self): + return sum(s.max_width() for s in self.items) + + def get_required_string(self, reverse): + seq = self.items + if reverse: + seq = seq[::-1] + + offset = 0 + + for s in seq: + ofs, req = s.get_required_string(reverse) + offset += ofs + if req: + return offset, req + + return offset, None + +class SetBase(RegexBase): + def __init__(self, info, items, positive=True, case_flags=NOCASE, + zerowidth=False): + RegexBase.__init__(self) + self.info = info + self.items = tuple(items) + self.positive = bool(positive) + self.case_flags = CASE_FLAGS_COMBINATIONS[case_flags] + self.zerowidth = bool(zerowidth) + + self.char_width = 1 + + self._key = (self.__class__, self.items, self.positive, + self.case_flags, self.zerowidth) + + def rebuild(self, positive, case_flags, zerowidth): + return type(self)(self.info, self.items, positive, case_flags, + zerowidth).optimise(self.info, False) + + def get_firstset(self, reverse): + return set([self]) + + def has_simple_start(self): + return True + + def _compile(self, reverse, fuzzy): + flags = 0 + if self.positive: + flags |= POSITIVE_OP + if self.zerowidth: + flags |= ZEROWIDTH_OP + if fuzzy: + flags |= FUZZY_OP + code = [(self._opcode[self.case_flags, reverse], flags)] + for m in self.items: + code.extend(m.compile()) + + code.append((OP.END, )) + + return code + + def dump(self, indent, reverse): + print("{}{} {}{}".format(INDENT * indent, self._op_name, + POS_TEXT[self.positive], CASE_TEXT[self.case_flags])) + for i in self.items: + i.dump(indent + 1, reverse) + + def _handle_case_folding(self, info, in_set): + # Is the set case-sensitive? + if not self.positive or not (self.case_flags & IGNORECASE) or in_set: + return self + + # Is full case-folding possible? + if (not (self.info.flags & UNICODE) or (self.case_flags & + FULLIGNORECASE) != FULLIGNORECASE): + return self + + # Get the characters which expand to multiple codepoints on folding. + expanding_chars = _regex.get_expand_on_folding() + + # Get the folded characters in the set. + items = [] + seen = set() + for ch in expanding_chars: + if self.matches(ord(ch)): + folded = _regex.fold_case(FULL_CASE_FOLDING, ch) + if folded not in seen: + items.append(String([ord(c) for c in folded], + case_flags=self.case_flags)) + seen.add(folded) + + if not items: + # We can fall back to simple case-folding. + return self + + return Branch([self] + items) + + def max_width(self): + # Is the set case-sensitive? + if not self.positive or not (self.case_flags & IGNORECASE): + return 1 + + # Is full case-folding possible? + if (not (self.info.flags & UNICODE) or (self.case_flags & + FULLIGNORECASE) != FULLIGNORECASE): + return 1 + + # Get the characters which expand to multiple codepoints on folding. + expanding_chars = _regex.get_expand_on_folding() + + # Get the folded characters in the set. + seen = set() + for ch in expanding_chars: + if self.matches(ord(ch)): + folded = _regex.fold_case(FULL_CASE_FOLDING, ch) + seen.add(folded) + + if not seen: + return 1 + + return max(len(folded) for folded in seen) + + def __del__(self): + self.info = None + +class SetDiff(SetBase): + _opcode = {(NOCASE, False): OP.SET_DIFF, (IGNORECASE, False): + OP.SET_DIFF_IGN, (FULLCASE, False): OP.SET_DIFF, (FULLIGNORECASE, False): + OP.SET_DIFF_IGN, (NOCASE, True): OP.SET_DIFF_REV, (IGNORECASE, True): + OP.SET_DIFF_IGN_REV, (FULLCASE, True): OP.SET_DIFF_REV, (FULLIGNORECASE, + True): OP.SET_DIFF_IGN_REV} + _op_name = "SET_DIFF" + + def optimise(self, info, reverse, in_set=False): + items = self.items + if len(items) > 2: + items = [items[0], SetUnion(info, items[1 : ])] + + if len(items) == 1: + return items[0].with_flags(case_flags=self.case_flags, + zerowidth=self.zerowidth).optimise(info, reverse, in_set) + + self.items = tuple(m.optimise(info, reverse, in_set=True) for m in + items) + + return self._handle_case_folding(info, in_set) + + def matches(self, ch): + m = self.items[0].matches(ch) and not self.items[1].matches(ch) + return m == self.positive + +class SetInter(SetBase): + _opcode = {(NOCASE, False): OP.SET_INTER, (IGNORECASE, False): + OP.SET_INTER_IGN, (FULLCASE, False): OP.SET_INTER, (FULLIGNORECASE, + False): OP.SET_INTER_IGN, (NOCASE, True): OP.SET_INTER_REV, (IGNORECASE, + True): OP.SET_INTER_IGN_REV, (FULLCASE, True): OP.SET_INTER_REV, + (FULLIGNORECASE, True): OP.SET_INTER_IGN_REV} + _op_name = "SET_INTER" + + def optimise(self, info, reverse, in_set=False): + items = [] + for m in self.items: + m = m.optimise(info, reverse, in_set=True) + if isinstance(m, SetInter) and m.positive: + # Intersection in intersection. + items.extend(m.items) + else: + items.append(m) + + if len(items) == 1: + return items[0].with_flags(case_flags=self.case_flags, + zerowidth=self.zerowidth).optimise(info, reverse, in_set) + + self.items = tuple(items) + + return self._handle_case_folding(info, in_set) + + def matches(self, ch): + m = all(i.matches(ch) for i in self.items) + return m == self.positive + +class SetSymDiff(SetBase): + _opcode = {(NOCASE, False): OP.SET_SYM_DIFF, (IGNORECASE, False): + OP.SET_SYM_DIFF_IGN, (FULLCASE, False): OP.SET_SYM_DIFF, (FULLIGNORECASE, + False): OP.SET_SYM_DIFF_IGN, (NOCASE, True): OP.SET_SYM_DIFF_REV, + (IGNORECASE, True): OP.SET_SYM_DIFF_IGN_REV, (FULLCASE, True): + OP.SET_SYM_DIFF_REV, (FULLIGNORECASE, True): OP.SET_SYM_DIFF_IGN_REV} + _op_name = "SET_SYM_DIFF" + + def optimise(self, info, reverse, in_set=False): + items = [] + for m in self.items: + m = m.optimise(info, reverse, in_set=True) + if isinstance(m, SetSymDiff) and m.positive: + # Symmetric difference in symmetric difference. + items.extend(m.items) + else: + items.append(m) + + if len(items) == 1: + return items[0].with_flags(case_flags=self.case_flags, + zerowidth=self.zerowidth).optimise(info, reverse, in_set) + + self.items = tuple(items) + + return self._handle_case_folding(info, in_set) + + def matches(self, ch): + m = False + for i in self.items: + m = m != i.matches(ch) + + return m == self.positive + +class SetUnion(SetBase): + _opcode = {(NOCASE, False): OP.SET_UNION, (IGNORECASE, False): + OP.SET_UNION_IGN, (FULLCASE, False): OP.SET_UNION, (FULLIGNORECASE, + False): OP.SET_UNION_IGN, (NOCASE, True): OP.SET_UNION_REV, (IGNORECASE, + True): OP.SET_UNION_IGN_REV, (FULLCASE, True): OP.SET_UNION_REV, + (FULLIGNORECASE, True): OP.SET_UNION_IGN_REV} + _op_name = "SET_UNION" + + def optimise(self, info, reverse, in_set=False): + items = [] + for m in self.items: + m = m.optimise(info, reverse, in_set=True) + if isinstance(m, SetUnion) and m.positive: + # Union in union. + items.extend(m.items) + elif isinstance(m, AnyAll): + return AnyAll() + else: + items.append(m) + + # Are there complementary properties? + properties = (set(), set()) + + for m in items: + if isinstance(m, Property): + properties[m.positive].add((m.value, m.case_flags, m.zerowidth)) + + if properties[0] & properties[1]: + return AnyAll() + + if len(items) == 1: + i = items[0] + return i.with_flags(positive=i.positive == self.positive, + case_flags=self.case_flags, + zerowidth=self.zerowidth).optimise(info, reverse, in_set) + + self.items = tuple(items) + + return self._handle_case_folding(info, in_set) + + def _compile(self, reverse, fuzzy): + flags = 0 + if self.positive: + flags |= POSITIVE_OP + if self.zerowidth: + flags |= ZEROWIDTH_OP + if fuzzy: + flags |= FUZZY_OP + + characters, others = defaultdict(list), [] + for m in self.items: + if isinstance(m, Character): + characters[m.positive].append(m.value) + else: + others.append(m) + + code = [(self._opcode[self.case_flags, reverse], flags)] + + for positive, values in characters.items(): + flags = 0 + if positive: + flags |= POSITIVE_OP + if len(values) == 1: + code.append((OP.CHARACTER, flags, values[0])) + else: + code.append((OP.STRING, flags, len(values)) + tuple(values)) + + for m in others: + code.extend(m.compile()) + + code.append((OP.END, )) + + return code + + def matches(self, ch): + m = any(i.matches(ch) for i in self.items) + return m == self.positive + +class Skip(ZeroWidthBase): + _op_name = "SKIP" + _opcode = OP.SKIP + +class StartOfLine(ZeroWidthBase): + _opcode = OP.START_OF_LINE + _op_name = "START_OF_LINE" + +class StartOfLineU(StartOfLine): + _opcode = OP.START_OF_LINE_U + _op_name = "START_OF_LINE_U" + +class StartOfString(ZeroWidthBase): + _opcode = OP.START_OF_STRING + _op_name = "START_OF_STRING" + +class StartOfWord(ZeroWidthBase): + _opcode = OP.START_OF_WORD + _op_name = "START_OF_WORD" + +class String(RegexBase): + _opcode = {(NOCASE, False): OP.STRING, (IGNORECASE, False): OP.STRING_IGN, + (FULLCASE, False): OP.STRING, (FULLIGNORECASE, False): OP.STRING_FLD, + (NOCASE, True): OP.STRING_REV, (IGNORECASE, True): OP.STRING_IGN_REV, + (FULLCASE, True): OP.STRING_REV, (FULLIGNORECASE, True): + OP.STRING_FLD_REV} + + def __init__(self, characters, case_flags=NOCASE): + self.characters = tuple(characters) + self.case_flags = CASE_FLAGS_COMBINATIONS[case_flags] + + if (self.case_flags & FULLIGNORECASE) == FULLIGNORECASE: + folded_characters = [] + for char in self.characters: + folded = _regex.fold_case(FULL_CASE_FOLDING, chr(char)) + folded_characters.extend(ord(c) for c in folded) + else: + folded_characters = self.characters + + self.folded_characters = tuple(folded_characters) + self.required = False + + self._key = self.__class__, self.characters, self.case_flags + + def get_firstset(self, reverse): + if reverse: + pos = -1 + else: + pos = 0 + return set([Character(self.characters[pos], + case_flags=self.case_flags)]) + + def has_simple_start(self): + return True + + def _compile(self, reverse, fuzzy): + flags = 0 + if fuzzy: + flags |= FUZZY_OP + if self.required: + flags |= REQUIRED_OP + return [(self._opcode[self.case_flags, reverse], flags, + len(self.folded_characters)) + self.folded_characters] + + def dump(self, indent, reverse): + display = ascii("".join(chr(c) for c in self.characters)).lstrip("bu") + print("{}STRING {}{}".format(INDENT * indent, display, + CASE_TEXT[self.case_flags])) + + def max_width(self): + return len(self.folded_characters) + + def get_required_string(self, reverse): + return 0, self + +class Literal(String): + def dump(self, indent, reverse): + literal = ''.join(chr(c) for c in self.characters) + display = ascii(literal).lstrip("bu") + print("{}LITERAL MATCH {}{}".format(INDENT * indent, display, + CASE_TEXT[self.case_flags])) + +class StringSet(Branch): + def __init__(self, info, name, case_flags=NOCASE): + self.info = info + self.name = name + self.case_flags = CASE_FLAGS_COMBINATIONS[case_flags] + + self._key = self.__class__, self.name, self.case_flags + + self.set_key = (name, self.case_flags) + if self.set_key not in info.named_lists_used: + info.named_lists_used[self.set_key] = len(info.named_lists_used) + + index = self.info.named_lists_used[self.set_key] + items = self.info.kwargs[self.name] + + case_flags = self.case_flags + + encoding = self.info.flags & _ALL_ENCODINGS + fold_flags = encoding | case_flags + + choices = [] + + for string in items: + if isinstance(string, str): + string = [ord(c) for c in string] + + choices.append([Character(c, case_flags=case_flags) for c in + string]) + + # Sort from longest to shortest. + choices.sort(key=len, reverse=True) + + self.branches = [Sequence(choice) for choice in choices] + + def dump(self, indent, reverse): + print("{}STRING_SET {}{}".format(INDENT * indent, self.name, + CASE_TEXT[self.case_flags])) + + def __del__(self): + self.info = None + +class Source: + "Scanner for the regular expression source string." + def __init__(self, string): + if isinstance(string, str): + self.string = string + self.char_type = chr + else: + self.string = string.decode("latin-1") + self.char_type = lambda c: bytes([c]) + + self.pos = 0 + self.ignore_space = False + self.sep = string[ : 0] + + def peek(self, override_ignore=False): + string = self.string + pos = self.pos + + try: + if self.ignore_space and not override_ignore: + while True: + if string[pos].isspace(): + # Skip over the whitespace. + pos += 1 + elif string[pos] == "#": + # Skip over the comment to the end of the line. + pos = string.index("\n", pos) + else: + break + + return string[pos] + except IndexError: + # We've reached the end of the string. + return string[ : 0] + except ValueError: + # The comment extended to the end of the string. + return string[ : 0] + + def get(self, override_ignore=False): + string = self.string + pos = self.pos + + try: + if self.ignore_space and not override_ignore: + while True: + if string[pos].isspace(): + # Skip over the whitespace. + pos += 1 + elif string[pos] == "#": + # Skip over the comment to the end of the line. + pos = string.index("\n", pos) + else: + break + + ch = string[pos] + self.pos = pos + 1 + return ch + except IndexError: + # We've reached the end of the string. + self.pos = pos + return string[ : 0] + except ValueError: + # The comment extended to the end of the string. + self.pos = len(string) + return string[ : 0] + + def get_many(self, count=1): + string = self.string + pos = self.pos + + try: + if self.ignore_space: + substring = [] + + while len(substring) < count: + while True: + if string[pos].isspace(): + # Skip over the whitespace. + pos += 1 + elif string[pos] == "#": + # Skip over the comment to the end of the line. + pos = string.index("\n", pos) + else: + break + + substring.append(string[pos]) + pos += 1 + + substring = "".join(substring) + else: + substring = string[pos : pos + count] + pos += len(substring) + + self.pos = pos + return substring + except IndexError: + # We've reached the end of the string. + self.pos = len(string) + return "".join(substring) + except ValueError: + # The comment extended to the end of the string. + self.pos = len(string) + return "".join(substring) + + def get_while(self, test_set, include=True, keep_spaces=False): + string = self.string + pos = self.pos + + if self.ignore_space and not keep_spaces: + try: + substring = [] + + while True: + if string[pos].isspace(): + # Skip over the whitespace. + pos += 1 + elif string[pos] == "#": + # Skip over the comment to the end of the line. + pos = string.index("\n", pos) + elif (string[pos] in test_set) == include: + substring.append(string[pos]) + pos += 1 + else: + break + + self.pos = pos + except IndexError: + # We've reached the end of the string. + self.pos = len(string) + except ValueError: + # The comment extended to the end of the string. + self.pos = len(string) + + return "".join(substring) + else: + try: + while (string[pos] in test_set) == include: + pos += 1 + + substring = string[self.pos : pos] + + self.pos = pos + + return substring + except IndexError: + # We've reached the end of the string. + substring = string[self.pos : pos] + + self.pos = pos + + return substring + + def skip_while(self, test_set, include=True): + string = self.string + pos = self.pos + + try: + if self.ignore_space: + while True: + if string[pos].isspace(): + # Skip over the whitespace. + pos += 1 + elif string[pos] == "#": + # Skip over the comment to the end of the line. + pos = string.index("\n", pos) + elif (string[pos] in test_set) == include: + pos += 1 + else: + break + else: + while (string[pos] in test_set) == include: + pos += 1 + + self.pos = pos + except IndexError: + # We've reached the end of the string. + self.pos = len(string) + except ValueError: + # The comment extended to the end of the string. + self.pos = len(string) + + def match(self, substring): + string = self.string + pos = self.pos + + if self.ignore_space: + try: + for c in substring: + while True: + if string[pos].isspace(): + # Skip over the whitespace. + pos += 1 + elif string[pos] == "#": + # Skip over the comment to the end of the line. + pos = string.index("\n", pos) + else: + break + + if string[pos] != c: + return False + + pos += 1 + + self.pos = pos + + return True + except IndexError: + # We've reached the end of the string. + return False + except ValueError: + # The comment extended to the end of the string. + return False + else: + if not string.startswith(substring, pos): + return False + + self.pos = pos + len(substring) + + return True + + def expect(self, substring): + if not self.match(substring): + raise error("missing {}".format(substring), self.string, self.pos) + + def at_end(self): + string = self.string + pos = self.pos + + try: + if self.ignore_space: + while True: + if string[pos].isspace(): + pos += 1 + elif string[pos] == "#": + pos = string.index("\n", pos) + else: + break + + return pos >= len(string) + except IndexError: + # We've reached the end of the string. + return True + except ValueError: + # The comment extended to the end of the string. + return True + +class Info: + "Info about the regular expression." + + def __init__(self, flags=0, char_type=None, kwargs={}): + flags |= DEFAULT_FLAGS[(flags & _ALL_VERSIONS) or DEFAULT_VERSION] + self.flags = flags + self.global_flags = flags + self.inline_locale = False + + self.kwargs = kwargs + + self.group_count = 0 + self.group_index = {} + self.group_name = {} + self.char_type = char_type + self.named_lists_used = {} + self.open_groups = [] + self.open_group_count = {} + self.defined_groups = {} + self.group_calls = [] + self.private_groups = {} + + def open_group(self, name=None): + group = self.group_index.get(name) + if group is None: + while True: + self.group_count += 1 + if name is None or self.group_count not in self.group_name: + break + + group = self.group_count + if name: + self.group_index[name] = group + self.group_name[group] = name + + if group in self.open_groups: + # We have a nested named group. We'll assign it a private group + # number, initially negative until we can assign a proper + # (positive) number. + group_alias = -(len(self.private_groups) + 1) + self.private_groups[group_alias] = group + group = group_alias + + self.open_groups.append(group) + self.open_group_count[group] = self.open_group_count.get(group, 0) + 1 + + return group + + def close_group(self): + self.open_groups.pop() + + def is_open_group(self, name): + # In version 1, a group reference can refer to an open group. We'll + # just pretend the group isn't open. + version = (self.flags & _ALL_VERSIONS) or DEFAULT_VERSION + if version == VERSION1: + return False + + if name.isdigit(): + group = int(name) + else: + group = self.group_index.get(name) + + return group in self.open_groups + +def _check_group_features(info, parsed): + """Checks whether the reverse and fuzzy features of the group calls match + the groups which they call. + """ + call_refs = {} + additional_groups = [] + for call, reverse, fuzzy in info.group_calls: + # Look up the reference of this group call. + key = (call.group, reverse, fuzzy) + ref = call_refs.get(key) + if ref is None: + # This group doesn't have a reference yet, so look up its features. + if call.group == 0: + # Calling the pattern as a whole. + rev = bool(info.flags & REVERSE) + fuz = isinstance(parsed, Fuzzy) + if (rev, fuz) != (reverse, fuzzy): + # The pattern as a whole doesn't have the features we want, + # so we'll need to make a copy of it with the desired + # features. + additional_groups.append((CallRef(len(call_refs), parsed), + reverse, fuzzy)) + else: + # Calling a capture group. + def_info = info.defined_groups[call.group] + group = def_info[0] + if def_info[1 : ] != (reverse, fuzzy): + # The group doesn't have the features we want, so we'll + # need to make a copy of it with the desired features. + additional_groups.append((group, reverse, fuzzy)) + + ref = len(call_refs) + call_refs[key] = ref + + call.call_ref = ref + + info.call_refs = call_refs + info.additional_groups = additional_groups + +def _get_required_string(parsed, flags): + "Gets the required string and related info of a parsed pattern." + + req_offset, required = parsed.get_required_string(bool(flags & REVERSE)) + if required: + required.required = True + if req_offset >= UNLIMITED: + req_offset = -1 + + req_flags = required.case_flags + if not (flags & UNICODE): + req_flags &= ~UNICODE + + req_chars = required.folded_characters + else: + req_offset = 0 + req_chars = () + req_flags = 0 + + return req_offset, req_chars, req_flags + +class Scanner: + def __init__(self, lexicon, flags=0): + self.lexicon = lexicon + + # Combine phrases into a compound pattern. + patterns = [] + for phrase, action in lexicon: + # Parse the regular expression. + source = Source(phrase) + info = Info(flags, source.char_type) + source.ignore_space = bool(info.flags & VERBOSE) + parsed = _parse_pattern(source, info) + if not source.at_end(): + raise error("unbalanced parenthesis", source.string, + source.pos) + + # We want to forbid capture groups within each phrase. + patterns.append(parsed.remove_captures()) + + # Combine all the subpatterns into one pattern. + info = Info(flags) + patterns = [Group(info, g + 1, p) for g, p in enumerate(patterns)] + parsed = Branch(patterns) + + # Optimise the compound pattern. + reverse = bool(info.flags & REVERSE) + parsed = parsed.optimise(info, reverse) + parsed = parsed.pack_characters(info) + + # Get the required string. + req_offset, req_chars, req_flags = _get_required_string(parsed, + info.flags) + + # Check the features of the groups. + _check_group_features(info, parsed) + + # Complain if there are any group calls. They are not supported by the + # Scanner class. + if info.call_refs: + raise error("recursive regex not supported by Scanner", + source.string, source.pos) + + reverse = bool(info.flags & REVERSE) + + # Compile the compound pattern. The result is a list of tuples. + code = parsed.compile(reverse) + [(OP.SUCCESS, )] + + # Flatten the code into a list of ints. + code = _flatten_code(code) + + if not parsed.has_simple_start(): + # Get the first set, if possible. + try: + fs_code = _compile_firstset(info, parsed.get_firstset(reverse)) + fs_code = _flatten_code(fs_code) + code = fs_code + code + except _FirstSetError: + pass + + # Check the global flags for conflicts. + version = (info.flags & _ALL_VERSIONS) or DEFAULT_VERSION + if version not in (0, VERSION0, VERSION1): + raise ValueError("VERSION0 and VERSION1 flags are mutually incompatible") + + # Create the PatternObject. + # + # Local flags like IGNORECASE affect the code generation, but aren't + # needed by the PatternObject itself. Conversely, global flags like + # LOCALE _don't_ affect the code generation but _are_ needed by the + # PatternObject. + self.scanner = _regex.compile(None, (flags & GLOBAL_FLAGS) | version, + code, {}, {}, {}, [], req_offset, req_chars, req_flags, + len(patterns)) + + def scan(self, string): + result = [] + append = result.append + match = self.scanner.scanner(string).match + i = 0 + while True: + m = match() + if not m: + break + j = m.end() + if i == j: + break + action = self.lexicon[m.lastindex - 1][1] + if hasattr(action, '__call__'): + self.match = m + action = action(self, m.group()) + if action is not None: + append(action) + i = j + + return result, string[i : ] + +# Get the known properties dict. +PROPERTIES = _regex.get_properties() + +# Build the inverse of the properties dict. +PROPERTY_NAMES = {} +for prop_name, (prop_id, values) in PROPERTIES.items(): + name, prop_values = PROPERTY_NAMES.get(prop_id, ("", {})) + name = max(name, prop_name, key=len) + PROPERTY_NAMES[prop_id] = name, prop_values + + for val_name, val_id in values.items(): + prop_values[val_id] = max(prop_values.get(val_id, ""), val_name, + key=len) + +# Character escape sequences. +CHARACTER_ESCAPES = { + "a": "\a", + "b": "\b", + "f": "\f", + "n": "\n", + "r": "\r", + "t": "\t", + "v": "\v", +} + +ASCII_ENCODING = 1 +UNICODE_ENCODING = 2 + +# Predefined character set escape sequences. +CHARSET_ESCAPES = { + "d": lookup_property(None, "Digit", True), + "D": lookup_property(None, "Digit", False), + "h": lookup_property(None, "Blank", True), + "s": lookup_property(None, "Space", True), + "S": lookup_property(None, "Space", False), + "w": lookup_property(None, "Word", True), + "W": lookup_property(None, "Word", False), +} + +ASCII_CHARSET_ESCAPES = dict(CHARSET_ESCAPES) +ASCII_CHARSET_ESCAPES.update({ + "d": lookup_property(None, "Digit", True, encoding=ASCII_ENCODING), + "D": lookup_property(None, "Digit", False, encoding=ASCII_ENCODING), + "s": lookup_property(None, "Space", True, encoding=ASCII_ENCODING), + "S": lookup_property(None, "Space", False, encoding=ASCII_ENCODING), + "w": lookup_property(None, "Word", True, encoding=ASCII_ENCODING), + "W": lookup_property(None, "Word", False, encoding=ASCII_ENCODING), +}) +UNICODE_CHARSET_ESCAPES = dict(CHARSET_ESCAPES) +UNICODE_CHARSET_ESCAPES.update({ + "d": lookup_property(None, "Digit", True, encoding=UNICODE_ENCODING), + "D": lookup_property(None, "Digit", False, encoding=UNICODE_ENCODING), + "s": lookup_property(None, "Space", True, encoding=UNICODE_ENCODING), + "S": lookup_property(None, "Space", False, encoding=UNICODE_ENCODING), + "w": lookup_property(None, "Word", True, encoding=UNICODE_ENCODING), + "W": lookup_property(None, "Word", False, encoding=UNICODE_ENCODING), +}) + +# Positional escape sequences. +POSITION_ESCAPES = { + "A": StartOfString(), + "b": Boundary(), + "B": Boundary(False), + "K": Keep(), + "m": StartOfWord(), + "M": EndOfWord(), + "Z": EndOfString(), + "z": EndOfString(), +} +ASCII_POSITION_ESCAPES = dict(POSITION_ESCAPES) +ASCII_POSITION_ESCAPES.update({ + "b": Boundary(encoding=ASCII_ENCODING), + "B": Boundary(False, encoding=ASCII_ENCODING), + "m": StartOfWord(encoding=ASCII_ENCODING), + "M": EndOfWord(encoding=ASCII_ENCODING), +}) +UNICODE_POSITION_ESCAPES = dict(POSITION_ESCAPES) +UNICODE_POSITION_ESCAPES.update({ + "b": Boundary(encoding=UNICODE_ENCODING), + "B": Boundary(False, encoding=UNICODE_ENCODING), + "m": StartOfWord(encoding=UNICODE_ENCODING), + "M": EndOfWord(encoding=UNICODE_ENCODING), +}) + +# Positional escape sequences when WORD flag set. +WORD_POSITION_ESCAPES = dict(POSITION_ESCAPES) +WORD_POSITION_ESCAPES.update({ + "b": DefaultBoundary(), + "B": DefaultBoundary(False), + "m": DefaultStartOfWord(), + "M": DefaultEndOfWord(), +}) + +# Regex control verbs. +VERBS = { + "FAIL": Failure(), + "F": Failure(), + "PRUNE": Prune(), + "SKIP": Skip(), +} diff --git a/TTS/Kokoro/.venv/Lib/site-packages/requests-2.32.5.dist-info/INSTALLER b/TTS/Kokoro/.venv/Lib/site-packages/requests-2.32.5.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/requests-2.32.5.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/TTS/Kokoro/.venv/Lib/site-packages/requests-2.32.5.dist-info/METADATA b/TTS/Kokoro/.venv/Lib/site-packages/requests-2.32.5.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..b31773e3ea2d0e0e16e77d33fefd8b8f8ff3fc85 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/requests-2.32.5.dist-info/METADATA @@ -0,0 +1,133 @@ +Metadata-Version: 2.4 +Name: requests +Version: 2.32.5 +Summary: Python HTTP for Humans. +Home-page: https://requests.readthedocs.io +Author: Kenneth Reitz +Author-email: me@kennethreitz.org +License: Apache-2.0 +Project-URL: Documentation, https://requests.readthedocs.io +Project-URL: Source, https://github.com/psf/requests +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Web Environment +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Natural Language :: English +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Internet :: WWW/HTTP +Classifier: Topic :: Software Development :: Libraries +Requires-Python: >=3.9 +Description-Content-Type: text/markdown +License-File: LICENSE +Requires-Dist: charset_normalizer<4,>=2 +Requires-Dist: idna<4,>=2.5 +Requires-Dist: urllib3<3,>=1.21.1 +Requires-Dist: certifi>=2017.4.17 +Provides-Extra: security +Provides-Extra: socks +Requires-Dist: PySocks!=1.5.7,>=1.5.6; extra == "socks" +Provides-Extra: use-chardet-on-py3 +Requires-Dist: chardet<6,>=3.0.2; extra == "use-chardet-on-py3" +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: description-content-type +Dynamic: home-page +Dynamic: license +Dynamic: license-file +Dynamic: project-url +Dynamic: provides-extra +Dynamic: requires-dist +Dynamic: requires-python +Dynamic: summary + +# Requests + +**Requests** is a simple, yet elegant, HTTP library. + +```python +>>> import requests +>>> r = requests.get('https://httpbin.org/basic-auth/user/pass', auth=('user', 'pass')) +>>> r.status_code +200 +>>> r.headers['content-type'] +'application/json; charset=utf8' +>>> r.encoding +'utf-8' +>>> r.text +'{"authenticated": true, ...' +>>> r.json() +{'authenticated': True, ...} +``` + +Requests allows you to send HTTP/1.1 requests extremely easily. There’s no need to manually add query strings to your URLs, or to form-encode your `PUT` & `POST` data — but nowadays, just use the `json` method! + +Requests is one of the most downloaded Python packages today, pulling in around `30M downloads / week`— according to GitHub, Requests is currently [depended upon](https://github.com/psf/requests/network/dependents?package_id=UGFja2FnZS01NzA4OTExNg%3D%3D) by `1,000,000+` repositories. You may certainly put your trust in this code. + +[![Downloads](https://static.pepy.tech/badge/requests/month)](https://pepy.tech/project/requests) +[![Supported Versions](https://img.shields.io/pypi/pyversions/requests.svg)](https://pypi.org/project/requests) +[![Contributors](https://img.shields.io/github/contributors/psf/requests.svg)](https://github.com/psf/requests/graphs/contributors) + +## Installing Requests and Supported Versions + +Requests is available on PyPI: + +```console +$ python -m pip install requests +``` + +Requests officially supports Python 3.9+. + +## Supported Features & Best–Practices + +Requests is ready for the demands of building robust and reliable HTTP–speaking applications, for the needs of today. + +- Keep-Alive & Connection Pooling +- International Domains and URLs +- Sessions with Cookie Persistence +- Browser-style TLS/SSL Verification +- Basic & Digest Authentication +- Familiar `dict`–like Cookies +- Automatic Content Decompression and Decoding +- Multi-part File Uploads +- SOCKS Proxy Support +- Connection Timeouts +- Streaming Downloads +- Automatic honoring of `.netrc` +- Chunked HTTP Requests + +## API Reference and User Guide available on [Read the Docs](https://requests.readthedocs.io) + +[![Read the Docs](https://raw.githubusercontent.com/psf/requests/main/ext/ss.png)](https://requests.readthedocs.io) + +## Cloning the repository + +When cloning the Requests repository, you may need to add the `-c +fetch.fsck.badTimezone=ignore` flag to avoid an error about a bad commit timestamp (see +[this issue](https://github.com/psf/requests/issues/2690) for more background): + +```shell +git clone -c fetch.fsck.badTimezone=ignore https://github.com/psf/requests.git +``` + +You can also apply this setting to your global Git config: + +```shell +git config --global fetch.fsck.badTimezone ignore +``` + +--- + +[![Kenneth Reitz](https://raw.githubusercontent.com/psf/requests/main/ext/kr.png)](https://kennethreitz.org) [![Python Software Foundation](https://raw.githubusercontent.com/psf/requests/main/ext/psf.png)](https://www.python.org/psf) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/requests-2.32.5.dist-info/RECORD b/TTS/Kokoro/.venv/Lib/site-packages/requests-2.32.5.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..590229191d822443d8fa06ec8e1e9f105b357a20 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/requests-2.32.5.dist-info/RECORD @@ -0,0 +1,42 @@ +requests-2.32.5.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +requests-2.32.5.dist-info/METADATA,sha256=ZbWgjagfSRVRPnYJZf8Ut1GPZbe7Pv4NqzZLvMTUDLA,4945 +requests-2.32.5.dist-info/RECORD,, +requests-2.32.5.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91 +requests-2.32.5.dist-info/licenses/LICENSE,sha256=CeipvOyAZxBGUsFoaFqwkx54aPnIKEtm9a5u2uXxEws,10142 +requests-2.32.5.dist-info/top_level.txt,sha256=fMSVmHfb5rbGOo6xv-O_tUX6j-WyixssE-SnwcDRxNQ,9 +requests/__init__.py,sha256=4xaAERmPDIBPsa2PsjpU9r06yooK-2mZKHTZAhWRWts,5072 +requests/__pycache__/__init__.cpython-312.pyc,, +requests/__pycache__/__version__.cpython-312.pyc,, +requests/__pycache__/_internal_utils.cpython-312.pyc,, +requests/__pycache__/adapters.cpython-312.pyc,, +requests/__pycache__/api.cpython-312.pyc,, +requests/__pycache__/auth.cpython-312.pyc,, +requests/__pycache__/certs.cpython-312.pyc,, +requests/__pycache__/compat.cpython-312.pyc,, +requests/__pycache__/cookies.cpython-312.pyc,, +requests/__pycache__/exceptions.cpython-312.pyc,, +requests/__pycache__/help.cpython-312.pyc,, +requests/__pycache__/hooks.cpython-312.pyc,, +requests/__pycache__/models.cpython-312.pyc,, +requests/__pycache__/packages.cpython-312.pyc,, +requests/__pycache__/sessions.cpython-312.pyc,, +requests/__pycache__/status_codes.cpython-312.pyc,, +requests/__pycache__/structures.cpython-312.pyc,, +requests/__pycache__/utils.cpython-312.pyc,, +requests/__version__.py,sha256=QKDceK8K_ujqwDDc3oYrR0odOBYgKVOQQ5vFap_G_cg,435 +requests/_internal_utils.py,sha256=nMQymr4hs32TqVo5AbCrmcJEhvPUh7xXlluyqwslLiQ,1495 +requests/adapters.py,sha256=8nX113gbb123aUtx2ETkAN_6IsYX-M2fRoLGluTEcRk,26285 +requests/api.py,sha256=_Zb9Oa7tzVIizTKwFrPjDEY9ejtm_OnSRERnADxGsQs,6449 +requests/auth.py,sha256=kF75tqnLctZ9Mf_hm9TZIj4cQWnN5uxRz8oWsx5wmR0,10186 +requests/certs.py,sha256=Z9Sb410Anv6jUFTyss0jFFhU6xst8ctELqfy8Ev23gw,429 +requests/compat.py,sha256=J7sIjR6XoDGp5JTVzOxkK5fSoUVUa_Pjc7iRZhAWGmI,2142 +requests/cookies.py,sha256=bNi-iqEj4NPZ00-ob-rHvzkvObzN3lEpgw3g6paS3Xw,18590 +requests/exceptions.py,sha256=jJPS1UWATs86ShVUaLorTiJb1SaGuoNEWgICJep-VkY,4260 +requests/help.py,sha256=gPX5d_H7Xd88aDABejhqGgl9B1VFRTt5BmiYvL3PzIQ,3875 +requests/hooks.py,sha256=CiuysiHA39V5UfcCBXFIx83IrDpuwfN9RcTUgv28ftQ,733 +requests/models.py,sha256=MjZdZ4k7tnw-1nz5PKShjmPmqyk0L6DciwnFngb_Vk4,35510 +requests/packages.py,sha256=_g0gZ681UyAlKHRjH6kanbaoxx2eAb6qzcXiODyTIoc,904 +requests/sessions.py,sha256=Cl1dpEnOfwrzzPbku-emepNeN4Rt_0_58Iy2x-JGTm8,30503 +requests/status_codes.py,sha256=iJUAeA25baTdw-6PfD0eF4qhpINDJRJI-yaMqxs4LEI,4322 +requests/structures.py,sha256=-IbmhVz06S-5aPSZuUthZ6-6D9XOjRuTXHOabY041XM,2912 +requests/utils.py,sha256=WqU86rZ3wvhC-tQjWcjtH_HEKZwWB3iWCZV6SW5DEdQ,33213 diff --git a/TTS/Kokoro/.venv/Lib/site-packages/requests-2.32.5.dist-info/WHEEL b/TTS/Kokoro/.venv/Lib/site-packages/requests-2.32.5.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..e7fa31b6f3f78deb1022c1f7927f07d4d16da822 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/requests-2.32.5.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/TTS/Kokoro/.venv/Lib/site-packages/requests-2.32.5.dist-info/top_level.txt b/TTS/Kokoro/.venv/Lib/site-packages/requests-2.32.5.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..f2293605cf1b01dca72aad0a15c45b72ed5429a2 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/requests-2.32.5.dist-info/top_level.txt @@ -0,0 +1 @@ +requests diff --git a/TTS/Kokoro/.venv/Lib/site-packages/requests/__init__.py b/TTS/Kokoro/.venv/Lib/site-packages/requests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..051cda1340effaa0706b46dd68ac002ceda3d45c --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/requests/__init__.py @@ -0,0 +1,184 @@ +# __ +# /__) _ _ _ _ _/ _ +# / ( (- (/ (/ (- _) / _) +# / + +""" +Requests HTTP Library +~~~~~~~~~~~~~~~~~~~~~ + +Requests is an HTTP library, written in Python, for human beings. +Basic GET usage: + + >>> import requests + >>> r = requests.get('https://www.python.org') + >>> r.status_code + 200 + >>> b'Python is a programming language' in r.content + True + +... or POST: + + >>> payload = dict(key1='value1', key2='value2') + >>> r = requests.post('https://httpbin.org/post', data=payload) + >>> print(r.text) + { + ... + "form": { + "key1": "value1", + "key2": "value2" + }, + ... + } + +The other HTTP methods are supported - see `requests.api`. Full documentation +is at . + +:copyright: (c) 2017 by Kenneth Reitz. +:license: Apache 2.0, see LICENSE for more details. +""" + +import warnings + +import urllib3 + +from .exceptions import RequestsDependencyWarning + +try: + from charset_normalizer import __version__ as charset_normalizer_version +except ImportError: + charset_normalizer_version = None + +try: + from chardet import __version__ as chardet_version +except ImportError: + chardet_version = None + + +def check_compatibility(urllib3_version, chardet_version, charset_normalizer_version): + urllib3_version = urllib3_version.split(".") + assert urllib3_version != ["dev"] # Verify urllib3 isn't installed from git. + + # Sometimes, urllib3 only reports its version as 16.1. + if len(urllib3_version) == 2: + urllib3_version.append("0") + + # Check urllib3 for compatibility. + major, minor, patch = urllib3_version # noqa: F811 + major, minor, patch = int(major), int(minor), int(patch) + # urllib3 >= 1.21.1 + assert major >= 1 + if major == 1: + assert minor >= 21 + + # Check charset_normalizer for compatibility. + if chardet_version: + major, minor, patch = chardet_version.split(".")[:3] + major, minor, patch = int(major), int(minor), int(patch) + # chardet_version >= 3.0.2, < 6.0.0 + assert (3, 0, 2) <= (major, minor, patch) < (6, 0, 0) + elif charset_normalizer_version: + major, minor, patch = charset_normalizer_version.split(".")[:3] + major, minor, patch = int(major), int(minor), int(patch) + # charset_normalizer >= 2.0.0 < 4.0.0 + assert (2, 0, 0) <= (major, minor, patch) < (4, 0, 0) + else: + warnings.warn( + "Unable to find acceptable character detection dependency " + "(chardet or charset_normalizer).", + RequestsDependencyWarning, + ) + + +def _check_cryptography(cryptography_version): + # cryptography < 1.3.4 + try: + cryptography_version = list(map(int, cryptography_version.split("."))) + except ValueError: + return + + if cryptography_version < [1, 3, 4]: + warning = "Old version of cryptography ({}) may cause slowdown.".format( + cryptography_version + ) + warnings.warn(warning, RequestsDependencyWarning) + + +# Check imported dependencies for compatibility. +try: + check_compatibility( + urllib3.__version__, chardet_version, charset_normalizer_version + ) +except (AssertionError, ValueError): + warnings.warn( + "urllib3 ({}) or chardet ({})/charset_normalizer ({}) doesn't match a supported " + "version!".format( + urllib3.__version__, chardet_version, charset_normalizer_version + ), + RequestsDependencyWarning, + ) + +# Attempt to enable urllib3's fallback for SNI support +# if the standard library doesn't support SNI or the +# 'ssl' library isn't available. +try: + try: + import ssl + except ImportError: + ssl = None + + if not getattr(ssl, "HAS_SNI", False): + from urllib3.contrib import pyopenssl + + pyopenssl.inject_into_urllib3() + + # Check cryptography version + from cryptography import __version__ as cryptography_version + + _check_cryptography(cryptography_version) +except ImportError: + pass + +# urllib3's DependencyWarnings should be silenced. +from urllib3.exceptions import DependencyWarning + +warnings.simplefilter("ignore", DependencyWarning) + +# Set default logging handler to avoid "No handler found" warnings. +import logging +from logging import NullHandler + +from . import packages, utils +from .__version__ import ( + __author__, + __author_email__, + __build__, + __cake__, + __copyright__, + __description__, + __license__, + __title__, + __url__, + __version__, +) +from .api import delete, get, head, options, patch, post, put, request +from .exceptions import ( + ConnectionError, + ConnectTimeout, + FileModeWarning, + HTTPError, + JSONDecodeError, + ReadTimeout, + RequestException, + Timeout, + TooManyRedirects, + URLRequired, +) +from .models import PreparedRequest, Request, Response +from .sessions import Session, session +from .status_codes import codes + +logging.getLogger(__name__).addHandler(NullHandler()) + +# FileModeWarnings go off per the default. +warnings.simplefilter("default", FileModeWarning, append=True) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/requests/__version__.py b/TTS/Kokoro/.venv/Lib/site-packages/requests/__version__.py new file mode 100644 index 0000000000000000000000000000000000000000..effdd98cf159371a36cb3ffaa8ad3e31ee3885f2 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/requests/__version__.py @@ -0,0 +1,14 @@ +# .-. .-. .-. . . .-. .-. .-. .-. +# |( |- |.| | | |- `-. | `-. +# ' ' `-' `-`.`-' `-' `-' ' `-' + +__title__ = "requests" +__description__ = "Python HTTP for Humans." +__url__ = "https://requests.readthedocs.io" +__version__ = "2.32.5" +__build__ = 0x023205 +__author__ = "Kenneth Reitz" +__author_email__ = "me@kennethreitz.org" +__license__ = "Apache-2.0" +__copyright__ = "Copyright Kenneth Reitz" +__cake__ = "\u2728 \U0001f370 \u2728" diff --git a/TTS/Kokoro/.venv/Lib/site-packages/requests/_internal_utils.py b/TTS/Kokoro/.venv/Lib/site-packages/requests/_internal_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f2cf635e2937ee9b123a1498c5c5f723a6e20084 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/requests/_internal_utils.py @@ -0,0 +1,50 @@ +""" +requests._internal_utils +~~~~~~~~~~~~~~ + +Provides utility functions that are consumed internally by Requests +which depend on extremely few external helpers (such as compat) +""" +import re + +from .compat import builtin_str + +_VALID_HEADER_NAME_RE_BYTE = re.compile(rb"^[^:\s][^:\r\n]*$") +_VALID_HEADER_NAME_RE_STR = re.compile(r"^[^:\s][^:\r\n]*$") +_VALID_HEADER_VALUE_RE_BYTE = re.compile(rb"^\S[^\r\n]*$|^$") +_VALID_HEADER_VALUE_RE_STR = re.compile(r"^\S[^\r\n]*$|^$") + +_HEADER_VALIDATORS_STR = (_VALID_HEADER_NAME_RE_STR, _VALID_HEADER_VALUE_RE_STR) +_HEADER_VALIDATORS_BYTE = (_VALID_HEADER_NAME_RE_BYTE, _VALID_HEADER_VALUE_RE_BYTE) +HEADER_VALIDATORS = { + bytes: _HEADER_VALIDATORS_BYTE, + str: _HEADER_VALIDATORS_STR, +} + + +def to_native_string(string, encoding="ascii"): + """Given a string object, regardless of type, returns a representation of + that string in the native string type, encoding and decoding where + necessary. This assumes ASCII unless told otherwise. + """ + if isinstance(string, builtin_str): + out = string + else: + out = string.decode(encoding) + + return out + + +def unicode_is_ascii(u_string): + """Determine if unicode string only contains ASCII characters. + + :param str u_string: unicode string to check. Must be unicode + and not Python 2 `str`. + :rtype: bool + """ + assert isinstance(u_string, str) + try: + u_string.encode("ascii") + return True + except UnicodeEncodeError: + return False diff --git a/TTS/Kokoro/.venv/Lib/site-packages/requests/adapters.py b/TTS/Kokoro/.venv/Lib/site-packages/requests/adapters.py new file mode 100644 index 0000000000000000000000000000000000000000..670c92767c5420a21538688132ce1f4f45e45873 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/requests/adapters.py @@ -0,0 +1,696 @@ +""" +requests.adapters +~~~~~~~~~~~~~~~~~ + +This module contains the transport adapters that Requests uses to define +and maintain connections. +""" + +import os.path +import socket # noqa: F401 +import typing +import warnings + +from urllib3.exceptions import ClosedPoolError, ConnectTimeoutError +from urllib3.exceptions import HTTPError as _HTTPError +from urllib3.exceptions import InvalidHeader as _InvalidHeader +from urllib3.exceptions import ( + LocationValueError, + MaxRetryError, + NewConnectionError, + ProtocolError, +) +from urllib3.exceptions import ProxyError as _ProxyError +from urllib3.exceptions import ReadTimeoutError, ResponseError +from urllib3.exceptions import SSLError as _SSLError +from urllib3.poolmanager import PoolManager, proxy_from_url +from urllib3.util import Timeout as TimeoutSauce +from urllib3.util import parse_url +from urllib3.util.retry import Retry + +from .auth import _basic_auth_str +from .compat import basestring, urlparse +from .cookies import extract_cookies_to_jar +from .exceptions import ( + ConnectionError, + ConnectTimeout, + InvalidHeader, + InvalidProxyURL, + InvalidSchema, + InvalidURL, + ProxyError, + ReadTimeout, + RetryError, + SSLError, +) +from .models import Response +from .structures import CaseInsensitiveDict +from .utils import ( + DEFAULT_CA_BUNDLE_PATH, + extract_zipped_paths, + get_auth_from_url, + get_encoding_from_headers, + prepend_scheme_if_needed, + select_proxy, + urldefragauth, +) + +try: + from urllib3.contrib.socks import SOCKSProxyManager +except ImportError: + + def SOCKSProxyManager(*args, **kwargs): + raise InvalidSchema("Missing dependencies for SOCKS support.") + + +if typing.TYPE_CHECKING: + from .models import PreparedRequest + + +DEFAULT_POOLBLOCK = False +DEFAULT_POOLSIZE = 10 +DEFAULT_RETRIES = 0 +DEFAULT_POOL_TIMEOUT = None + + +def _urllib3_request_context( + request: "PreparedRequest", + verify: "bool | str | None", + client_cert: "typing.Tuple[str, str] | str | None", + poolmanager: "PoolManager", +) -> "(typing.Dict[str, typing.Any], typing.Dict[str, typing.Any])": + host_params = {} + pool_kwargs = {} + parsed_request_url = urlparse(request.url) + scheme = parsed_request_url.scheme.lower() + port = parsed_request_url.port + + cert_reqs = "CERT_REQUIRED" + if verify is False: + cert_reqs = "CERT_NONE" + elif isinstance(verify, str): + if not os.path.isdir(verify): + pool_kwargs["ca_certs"] = verify + else: + pool_kwargs["ca_cert_dir"] = verify + pool_kwargs["cert_reqs"] = cert_reqs + if client_cert is not None: + if isinstance(client_cert, tuple) and len(client_cert) == 2: + pool_kwargs["cert_file"] = client_cert[0] + pool_kwargs["key_file"] = client_cert[1] + else: + # According to our docs, we allow users to specify just the client + # cert path + pool_kwargs["cert_file"] = client_cert + host_params = { + "scheme": scheme, + "host": parsed_request_url.hostname, + "port": port, + } + return host_params, pool_kwargs + + +class BaseAdapter: + """The Base Transport Adapter""" + + def __init__(self): + super().__init__() + + def send( + self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None + ): + """Sends PreparedRequest object. Returns Response object. + + :param request: The :class:`PreparedRequest ` being sent. + :param stream: (optional) Whether to stream the request content. + :param timeout: (optional) How long to wait for the server to send + data before giving up, as a float, or a :ref:`(connect timeout, + read timeout) ` tuple. + :type timeout: float or tuple + :param verify: (optional) Either a boolean, in which case it controls whether we verify + the server's TLS certificate, or a string, in which case it must be a path + to a CA bundle to use + :param cert: (optional) Any user-provided SSL certificate to be trusted. + :param proxies: (optional) The proxies dictionary to apply to the request. + """ + raise NotImplementedError + + def close(self): + """Cleans up adapter specific items.""" + raise NotImplementedError + + +class HTTPAdapter(BaseAdapter): + """The built-in HTTP Adapter for urllib3. + + Provides a general-case interface for Requests sessions to contact HTTP and + HTTPS urls by implementing the Transport Adapter interface. This class will + usually be created by the :class:`Session ` class under the + covers. + + :param pool_connections: The number of urllib3 connection pools to cache. + :param pool_maxsize: The maximum number of connections to save in the pool. + :param max_retries: The maximum number of retries each connection + should attempt. Note, this applies only to failed DNS lookups, socket + connections and connection timeouts, never to requests where data has + made it to the server. By default, Requests does not retry failed + connections. If you need granular control over the conditions under + which we retry a request, import urllib3's ``Retry`` class and pass + that instead. + :param pool_block: Whether the connection pool should block for connections. + + Usage:: + + >>> import requests + >>> s = requests.Session() + >>> a = requests.adapters.HTTPAdapter(max_retries=3) + >>> s.mount('http://', a) + """ + + __attrs__ = [ + "max_retries", + "config", + "_pool_connections", + "_pool_maxsize", + "_pool_block", + ] + + def __init__( + self, + pool_connections=DEFAULT_POOLSIZE, + pool_maxsize=DEFAULT_POOLSIZE, + max_retries=DEFAULT_RETRIES, + pool_block=DEFAULT_POOLBLOCK, + ): + if max_retries == DEFAULT_RETRIES: + self.max_retries = Retry(0, read=False) + else: + self.max_retries = Retry.from_int(max_retries) + self.config = {} + self.proxy_manager = {} + + super().__init__() + + self._pool_connections = pool_connections + self._pool_maxsize = pool_maxsize + self._pool_block = pool_block + + self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block) + + def __getstate__(self): + return {attr: getattr(self, attr, None) for attr in self.__attrs__} + + def __setstate__(self, state): + # Can't handle by adding 'proxy_manager' to self.__attrs__ because + # self.poolmanager uses a lambda function, which isn't pickleable. + self.proxy_manager = {} + self.config = {} + + for attr, value in state.items(): + setattr(self, attr, value) + + self.init_poolmanager( + self._pool_connections, self._pool_maxsize, block=self._pool_block + ) + + def init_poolmanager( + self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs + ): + """Initializes a urllib3 PoolManager. + + This method should not be called from user code, and is only + exposed for use when subclassing the + :class:`HTTPAdapter `. + + :param connections: The number of urllib3 connection pools to cache. + :param maxsize: The maximum number of connections to save in the pool. + :param block: Block when no free connections are available. + :param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager. + """ + # save these values for pickling + self._pool_connections = connections + self._pool_maxsize = maxsize + self._pool_block = block + + self.poolmanager = PoolManager( + num_pools=connections, + maxsize=maxsize, + block=block, + **pool_kwargs, + ) + + def proxy_manager_for(self, proxy, **proxy_kwargs): + """Return urllib3 ProxyManager for the given proxy. + + This method should not be called from user code, and is only + exposed for use when subclassing the + :class:`HTTPAdapter `. + + :param proxy: The proxy to return a urllib3 ProxyManager for. + :param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager. + :returns: ProxyManager + :rtype: urllib3.ProxyManager + """ + if proxy in self.proxy_manager: + manager = self.proxy_manager[proxy] + elif proxy.lower().startswith("socks"): + username, password = get_auth_from_url(proxy) + manager = self.proxy_manager[proxy] = SOCKSProxyManager( + proxy, + username=username, + password=password, + num_pools=self._pool_connections, + maxsize=self._pool_maxsize, + block=self._pool_block, + **proxy_kwargs, + ) + else: + proxy_headers = self.proxy_headers(proxy) + manager = self.proxy_manager[proxy] = proxy_from_url( + proxy, + proxy_headers=proxy_headers, + num_pools=self._pool_connections, + maxsize=self._pool_maxsize, + block=self._pool_block, + **proxy_kwargs, + ) + + return manager + + def cert_verify(self, conn, url, verify, cert): + """Verify a SSL certificate. This method should not be called from user + code, and is only exposed for use when subclassing the + :class:`HTTPAdapter `. + + :param conn: The urllib3 connection object associated with the cert. + :param url: The requested URL. + :param verify: Either a boolean, in which case it controls whether we verify + the server's TLS certificate, or a string, in which case it must be a path + to a CA bundle to use + :param cert: The SSL certificate to verify. + """ + if url.lower().startswith("https") and verify: + cert_loc = None + + # Allow self-specified cert location. + if verify is not True: + cert_loc = verify + + if not cert_loc: + cert_loc = extract_zipped_paths(DEFAULT_CA_BUNDLE_PATH) + + if not cert_loc or not os.path.exists(cert_loc): + raise OSError( + f"Could not find a suitable TLS CA certificate bundle, " + f"invalid path: {cert_loc}" + ) + + conn.cert_reqs = "CERT_REQUIRED" + + if not os.path.isdir(cert_loc): + conn.ca_certs = cert_loc + else: + conn.ca_cert_dir = cert_loc + else: + conn.cert_reqs = "CERT_NONE" + conn.ca_certs = None + conn.ca_cert_dir = None + + if cert: + if not isinstance(cert, basestring): + conn.cert_file = cert[0] + conn.key_file = cert[1] + else: + conn.cert_file = cert + conn.key_file = None + if conn.cert_file and not os.path.exists(conn.cert_file): + raise OSError( + f"Could not find the TLS certificate file, " + f"invalid path: {conn.cert_file}" + ) + if conn.key_file and not os.path.exists(conn.key_file): + raise OSError( + f"Could not find the TLS key file, invalid path: {conn.key_file}" + ) + + def build_response(self, req, resp): + """Builds a :class:`Response ` object from a urllib3 + response. This should not be called from user code, and is only exposed + for use when subclassing the + :class:`HTTPAdapter ` + + :param req: The :class:`PreparedRequest ` used to generate the response. + :param resp: The urllib3 response object. + :rtype: requests.Response + """ + response = Response() + + # Fallback to None if there's no status_code, for whatever reason. + response.status_code = getattr(resp, "status", None) + + # Make headers case-insensitive. + response.headers = CaseInsensitiveDict(getattr(resp, "headers", {})) + + # Set encoding. + response.encoding = get_encoding_from_headers(response.headers) + response.raw = resp + response.reason = response.raw.reason + + if isinstance(req.url, bytes): + response.url = req.url.decode("utf-8") + else: + response.url = req.url + + # Add new cookies from the server. + extract_cookies_to_jar(response.cookies, req, resp) + + # Give the Response some context. + response.request = req + response.connection = self + + return response + + def build_connection_pool_key_attributes(self, request, verify, cert=None): + """Build the PoolKey attributes used by urllib3 to return a connection. + + This looks at the PreparedRequest, the user-specified verify value, + and the value of the cert parameter to determine what PoolKey values + to use to select a connection from a given urllib3 Connection Pool. + + The SSL related pool key arguments are not consistently set. As of + this writing, use the following to determine what keys may be in that + dictionary: + + * If ``verify`` is ``True``, ``"ssl_context"`` will be set and will be the + default Requests SSL Context + * If ``verify`` is ``False``, ``"ssl_context"`` will not be set but + ``"cert_reqs"`` will be set + * If ``verify`` is a string, (i.e., it is a user-specified trust bundle) + ``"ca_certs"`` will be set if the string is not a directory recognized + by :py:func:`os.path.isdir`, otherwise ``"ca_cert_dir"`` will be + set. + * If ``"cert"`` is specified, ``"cert_file"`` will always be set. If + ``"cert"`` is a tuple with a second item, ``"key_file"`` will also + be present + + To override these settings, one may subclass this class, call this + method and use the above logic to change parameters as desired. For + example, if one wishes to use a custom :py:class:`ssl.SSLContext` one + must both set ``"ssl_context"`` and based on what else they require, + alter the other keys to ensure the desired behaviour. + + :param request: + The PreparedReqest being sent over the connection. + :type request: + :class:`~requests.models.PreparedRequest` + :param verify: + Either a boolean, in which case it controls whether + we verify the server's TLS certificate, or a string, in which case it + must be a path to a CA bundle to use. + :param cert: + (optional) Any user-provided SSL certificate for client + authentication (a.k.a., mTLS). This may be a string (i.e., just + the path to a file which holds both certificate and key) or a + tuple of length 2 with the certificate file path and key file + path. + :returns: + A tuple of two dictionaries. The first is the "host parameters" + portion of the Pool Key including scheme, hostname, and port. The + second is a dictionary of SSLContext related parameters. + """ + return _urllib3_request_context(request, verify, cert, self.poolmanager) + + def get_connection_with_tls_context(self, request, verify, proxies=None, cert=None): + """Returns a urllib3 connection for the given request and TLS settings. + This should not be called from user code, and is only exposed for use + when subclassing the :class:`HTTPAdapter `. + + :param request: + The :class:`PreparedRequest ` object to be sent + over the connection. + :param verify: + Either a boolean, in which case it controls whether we verify the + server's TLS certificate, or a string, in which case it must be a + path to a CA bundle to use. + :param proxies: + (optional) The proxies dictionary to apply to the request. + :param cert: + (optional) Any user-provided SSL certificate to be used for client + authentication (a.k.a., mTLS). + :rtype: + urllib3.ConnectionPool + """ + proxy = select_proxy(request.url, proxies) + try: + host_params, pool_kwargs = self.build_connection_pool_key_attributes( + request, + verify, + cert, + ) + except ValueError as e: + raise InvalidURL(e, request=request) + if proxy: + proxy = prepend_scheme_if_needed(proxy, "http") + proxy_url = parse_url(proxy) + if not proxy_url.host: + raise InvalidProxyURL( + "Please check proxy URL. It is malformed " + "and could be missing the host." + ) + proxy_manager = self.proxy_manager_for(proxy) + conn = proxy_manager.connection_from_host( + **host_params, pool_kwargs=pool_kwargs + ) + else: + # Only scheme should be lower case + conn = self.poolmanager.connection_from_host( + **host_params, pool_kwargs=pool_kwargs + ) + + return conn + + def get_connection(self, url, proxies=None): + """DEPRECATED: Users should move to `get_connection_with_tls_context` + for all subclasses of HTTPAdapter using Requests>=2.32.2. + + Returns a urllib3 connection for the given URL. This should not be + called from user code, and is only exposed for use when subclassing the + :class:`HTTPAdapter `. + + :param url: The URL to connect to. + :param proxies: (optional) A Requests-style dictionary of proxies used on this request. + :rtype: urllib3.ConnectionPool + """ + warnings.warn( + ( + "`get_connection` has been deprecated in favor of " + "`get_connection_with_tls_context`. Custom HTTPAdapter subclasses " + "will need to migrate for Requests>=2.32.2. Please see " + "https://github.com/psf/requests/pull/6710 for more details." + ), + DeprecationWarning, + ) + proxy = select_proxy(url, proxies) + + if proxy: + proxy = prepend_scheme_if_needed(proxy, "http") + proxy_url = parse_url(proxy) + if not proxy_url.host: + raise InvalidProxyURL( + "Please check proxy URL. It is malformed " + "and could be missing the host." + ) + proxy_manager = self.proxy_manager_for(proxy) + conn = proxy_manager.connection_from_url(url) + else: + # Only scheme should be lower case + parsed = urlparse(url) + url = parsed.geturl() + conn = self.poolmanager.connection_from_url(url) + + return conn + + def close(self): + """Disposes of any internal state. + + Currently, this closes the PoolManager and any active ProxyManager, + which closes any pooled connections. + """ + self.poolmanager.clear() + for proxy in self.proxy_manager.values(): + proxy.clear() + + def request_url(self, request, proxies): + """Obtain the url to use when making the final request. + + If the message is being sent through a HTTP proxy, the full URL has to + be used. Otherwise, we should only use the path portion of the URL. + + This should not be called from user code, and is only exposed for use + when subclassing the + :class:`HTTPAdapter `. + + :param request: The :class:`PreparedRequest ` being sent. + :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs. + :rtype: str + """ + proxy = select_proxy(request.url, proxies) + scheme = urlparse(request.url).scheme + + is_proxied_http_request = proxy and scheme != "https" + using_socks_proxy = False + if proxy: + proxy_scheme = urlparse(proxy).scheme.lower() + using_socks_proxy = proxy_scheme.startswith("socks") + + url = request.path_url + if url.startswith("//"): # Don't confuse urllib3 + url = f"/{url.lstrip('/')}" + + if is_proxied_http_request and not using_socks_proxy: + url = urldefragauth(request.url) + + return url + + def add_headers(self, request, **kwargs): + """Add any headers needed by the connection. As of v2.0 this does + nothing by default, but is left for overriding by users that subclass + the :class:`HTTPAdapter `. + + This should not be called from user code, and is only exposed for use + when subclassing the + :class:`HTTPAdapter `. + + :param request: The :class:`PreparedRequest ` to add headers to. + :param kwargs: The keyword arguments from the call to send(). + """ + pass + + def proxy_headers(self, proxy): + """Returns a dictionary of the headers to add to any request sent + through a proxy. This works with urllib3 magic to ensure that they are + correctly sent to the proxy, rather than in a tunnelled request if + CONNECT is being used. + + This should not be called from user code, and is only exposed for use + when subclassing the + :class:`HTTPAdapter `. + + :param proxy: The url of the proxy being used for this request. + :rtype: dict + """ + headers = {} + username, password = get_auth_from_url(proxy) + + if username: + headers["Proxy-Authorization"] = _basic_auth_str(username, password) + + return headers + + def send( + self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None + ): + """Sends PreparedRequest object. Returns Response object. + + :param request: The :class:`PreparedRequest ` being sent. + :param stream: (optional) Whether to stream the request content. + :param timeout: (optional) How long to wait for the server to send + data before giving up, as a float, or a :ref:`(connect timeout, + read timeout) ` tuple. + :type timeout: float or tuple or urllib3 Timeout object + :param verify: (optional) Either a boolean, in which case it controls whether + we verify the server's TLS certificate, or a string, in which case it + must be a path to a CA bundle to use + :param cert: (optional) Any user-provided SSL certificate to be trusted. + :param proxies: (optional) The proxies dictionary to apply to the request. + :rtype: requests.Response + """ + + try: + conn = self.get_connection_with_tls_context( + request, verify, proxies=proxies, cert=cert + ) + except LocationValueError as e: + raise InvalidURL(e, request=request) + + self.cert_verify(conn, request.url, verify, cert) + url = self.request_url(request, proxies) + self.add_headers( + request, + stream=stream, + timeout=timeout, + verify=verify, + cert=cert, + proxies=proxies, + ) + + chunked = not (request.body is None or "Content-Length" in request.headers) + + if isinstance(timeout, tuple): + try: + connect, read = timeout + timeout = TimeoutSauce(connect=connect, read=read) + except ValueError: + raise ValueError( + f"Invalid timeout {timeout}. Pass a (connect, read) timeout tuple, " + f"or a single float to set both timeouts to the same value." + ) + elif isinstance(timeout, TimeoutSauce): + pass + else: + timeout = TimeoutSauce(connect=timeout, read=timeout) + + try: + resp = conn.urlopen( + method=request.method, + url=url, + body=request.body, + headers=request.headers, + redirect=False, + assert_same_host=False, + preload_content=False, + decode_content=False, + retries=self.max_retries, + timeout=timeout, + chunked=chunked, + ) + + except (ProtocolError, OSError) as err: + raise ConnectionError(err, request=request) + + except MaxRetryError as e: + if isinstance(e.reason, ConnectTimeoutError): + # TODO: Remove this in 3.0.0: see #2811 + if not isinstance(e.reason, NewConnectionError): + raise ConnectTimeout(e, request=request) + + if isinstance(e.reason, ResponseError): + raise RetryError(e, request=request) + + if isinstance(e.reason, _ProxyError): + raise ProxyError(e, request=request) + + if isinstance(e.reason, _SSLError): + # This branch is for urllib3 v1.22 and later. + raise SSLError(e, request=request) + + raise ConnectionError(e, request=request) + + except ClosedPoolError as e: + raise ConnectionError(e, request=request) + + except _ProxyError as e: + raise ProxyError(e) + + except (_SSLError, _HTTPError) as e: + if isinstance(e, _SSLError): + # This branch is for urllib3 versions earlier than v1.22 + raise SSLError(e, request=request) + elif isinstance(e, ReadTimeoutError): + raise ReadTimeout(e, request=request) + elif isinstance(e, _InvalidHeader): + raise InvalidHeader(e, request=request) + else: + raise + + return self.build_response(request, resp) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/requests/api.py b/TTS/Kokoro/.venv/Lib/site-packages/requests/api.py new file mode 100644 index 0000000000000000000000000000000000000000..5960744552e7f8eea815429e7bdad38b0cc2741d --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/requests/api.py @@ -0,0 +1,157 @@ +""" +requests.api +~~~~~~~~~~~~ + +This module implements the Requests API. + +:copyright: (c) 2012 by Kenneth Reitz. +:license: Apache2, see LICENSE for more details. +""" + +from . import sessions + + +def request(method, url, **kwargs): + """Constructs and sends a :class:`Request `. + + :param method: method for the new :class:`Request` object: ``GET``, ``OPTIONS``, ``HEAD``, ``POST``, ``PUT``, ``PATCH``, or ``DELETE``. + :param url: URL for the new :class:`Request` object. + :param params: (optional) Dictionary, list of tuples or bytes to send + in the query string for the :class:`Request`. + :param data: (optional) Dictionary, list of tuples, bytes, or file-like + object to send in the body of the :class:`Request`. + :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`. + :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`. + :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`. + :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload. + ``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')`` + or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content_type'`` is a string + defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers + to add for the file. + :param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth. + :param timeout: (optional) How many seconds to wait for the server to send data + before giving up, as a float, or a :ref:`(connect timeout, read + timeout) ` tuple. + :type timeout: float or tuple + :param allow_redirects: (optional) Boolean. Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to ``True``. + :type allow_redirects: bool + :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy. + :param verify: (optional) Either a boolean, in which case it controls whether we verify + the server's TLS certificate, or a string, in which case it must be a path + to a CA bundle to use. Defaults to ``True``. + :param stream: (optional) if ``False``, the response content will be immediately downloaded. + :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair. + :return: :class:`Response ` object + :rtype: requests.Response + + Usage:: + + >>> import requests + >>> req = requests.request('GET', 'https://httpbin.org/get') + >>> req + + """ + + # By using the 'with' statement we are sure the session is closed, thus we + # avoid leaving sockets open which can trigger a ResourceWarning in some + # cases, and look like a memory leak in others. + with sessions.Session() as session: + return session.request(method=method, url=url, **kwargs) + + +def get(url, params=None, **kwargs): + r"""Sends a GET request. + + :param url: URL for the new :class:`Request` object. + :param params: (optional) Dictionary, list of tuples or bytes to send + in the query string for the :class:`Request`. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :return: :class:`Response ` object + :rtype: requests.Response + """ + + return request("get", url, params=params, **kwargs) + + +def options(url, **kwargs): + r"""Sends an OPTIONS request. + + :param url: URL for the new :class:`Request` object. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :return: :class:`Response ` object + :rtype: requests.Response + """ + + return request("options", url, **kwargs) + + +def head(url, **kwargs): + r"""Sends a HEAD request. + + :param url: URL for the new :class:`Request` object. + :param \*\*kwargs: Optional arguments that ``request`` takes. If + `allow_redirects` is not provided, it will be set to `False` (as + opposed to the default :meth:`request` behavior). + :return: :class:`Response ` object + :rtype: requests.Response + """ + + kwargs.setdefault("allow_redirects", False) + return request("head", url, **kwargs) + + +def post(url, data=None, json=None, **kwargs): + r"""Sends a POST request. + + :param url: URL for the new :class:`Request` object. + :param data: (optional) Dictionary, list of tuples, bytes, or file-like + object to send in the body of the :class:`Request`. + :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :return: :class:`Response ` object + :rtype: requests.Response + """ + + return request("post", url, data=data, json=json, **kwargs) + + +def put(url, data=None, **kwargs): + r"""Sends a PUT request. + + :param url: URL for the new :class:`Request` object. + :param data: (optional) Dictionary, list of tuples, bytes, or file-like + object to send in the body of the :class:`Request`. + :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :return: :class:`Response ` object + :rtype: requests.Response + """ + + return request("put", url, data=data, **kwargs) + + +def patch(url, data=None, **kwargs): + r"""Sends a PATCH request. + + :param url: URL for the new :class:`Request` object. + :param data: (optional) Dictionary, list of tuples, bytes, or file-like + object to send in the body of the :class:`Request`. + :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :return: :class:`Response ` object + :rtype: requests.Response + """ + + return request("patch", url, data=data, **kwargs) + + +def delete(url, **kwargs): + r"""Sends a DELETE request. + + :param url: URL for the new :class:`Request` object. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :return: :class:`Response ` object + :rtype: requests.Response + """ + + return request("delete", url, **kwargs) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/requests/auth.py b/TTS/Kokoro/.venv/Lib/site-packages/requests/auth.py new file mode 100644 index 0000000000000000000000000000000000000000..4a7ce6dc1460e0de8aa0c38ea9123faa69bd5110 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/requests/auth.py @@ -0,0 +1,314 @@ +""" +requests.auth +~~~~~~~~~~~~~ + +This module contains the authentication handlers for Requests. +""" + +import hashlib +import os +import re +import threading +import time +import warnings +from base64 import b64encode + +from ._internal_utils import to_native_string +from .compat import basestring, str, urlparse +from .cookies import extract_cookies_to_jar +from .utils import parse_dict_header + +CONTENT_TYPE_FORM_URLENCODED = "application/x-www-form-urlencoded" +CONTENT_TYPE_MULTI_PART = "multipart/form-data" + + +def _basic_auth_str(username, password): + """Returns a Basic Auth string.""" + + # "I want us to put a big-ol' comment on top of it that + # says that this behaviour is dumb but we need to preserve + # it because people are relying on it." + # - Lukasa + # + # These are here solely to maintain backwards compatibility + # for things like ints. This will be removed in 3.0.0. + if not isinstance(username, basestring): + warnings.warn( + "Non-string usernames will no longer be supported in Requests " + "3.0.0. Please convert the object you've passed in ({!r}) to " + "a string or bytes object in the near future to avoid " + "problems.".format(username), + category=DeprecationWarning, + ) + username = str(username) + + if not isinstance(password, basestring): + warnings.warn( + "Non-string passwords will no longer be supported in Requests " + "3.0.0. Please convert the object you've passed in ({!r}) to " + "a string or bytes object in the near future to avoid " + "problems.".format(type(password)), + category=DeprecationWarning, + ) + password = str(password) + # -- End Removal -- + + if isinstance(username, str): + username = username.encode("latin1") + + if isinstance(password, str): + password = password.encode("latin1") + + authstr = "Basic " + to_native_string( + b64encode(b":".join((username, password))).strip() + ) + + return authstr + + +class AuthBase: + """Base class that all auth implementations derive from""" + + def __call__(self, r): + raise NotImplementedError("Auth hooks must be callable.") + + +class HTTPBasicAuth(AuthBase): + """Attaches HTTP Basic Authentication to the given Request object.""" + + def __init__(self, username, password): + self.username = username + self.password = password + + def __eq__(self, other): + return all( + [ + self.username == getattr(other, "username", None), + self.password == getattr(other, "password", None), + ] + ) + + def __ne__(self, other): + return not self == other + + def __call__(self, r): + r.headers["Authorization"] = _basic_auth_str(self.username, self.password) + return r + + +class HTTPProxyAuth(HTTPBasicAuth): + """Attaches HTTP Proxy Authentication to a given Request object.""" + + def __call__(self, r): + r.headers["Proxy-Authorization"] = _basic_auth_str(self.username, self.password) + return r + + +class HTTPDigestAuth(AuthBase): + """Attaches HTTP Digest Authentication to the given Request object.""" + + def __init__(self, username, password): + self.username = username + self.password = password + # Keep state in per-thread local storage + self._thread_local = threading.local() + + def init_per_thread_state(self): + # Ensure state is initialized just once per-thread + if not hasattr(self._thread_local, "init"): + self._thread_local.init = True + self._thread_local.last_nonce = "" + self._thread_local.nonce_count = 0 + self._thread_local.chal = {} + self._thread_local.pos = None + self._thread_local.num_401_calls = None + + def build_digest_header(self, method, url): + """ + :rtype: str + """ + + realm = self._thread_local.chal["realm"] + nonce = self._thread_local.chal["nonce"] + qop = self._thread_local.chal.get("qop") + algorithm = self._thread_local.chal.get("algorithm") + opaque = self._thread_local.chal.get("opaque") + hash_utf8 = None + + if algorithm is None: + _algorithm = "MD5" + else: + _algorithm = algorithm.upper() + # lambdas assume digest modules are imported at the top level + if _algorithm == "MD5" or _algorithm == "MD5-SESS": + + def md5_utf8(x): + if isinstance(x, str): + x = x.encode("utf-8") + return hashlib.md5(x).hexdigest() + + hash_utf8 = md5_utf8 + elif _algorithm == "SHA": + + def sha_utf8(x): + if isinstance(x, str): + x = x.encode("utf-8") + return hashlib.sha1(x).hexdigest() + + hash_utf8 = sha_utf8 + elif _algorithm == "SHA-256": + + def sha256_utf8(x): + if isinstance(x, str): + x = x.encode("utf-8") + return hashlib.sha256(x).hexdigest() + + hash_utf8 = sha256_utf8 + elif _algorithm == "SHA-512": + + def sha512_utf8(x): + if isinstance(x, str): + x = x.encode("utf-8") + return hashlib.sha512(x).hexdigest() + + hash_utf8 = sha512_utf8 + + KD = lambda s, d: hash_utf8(f"{s}:{d}") # noqa:E731 + + if hash_utf8 is None: + return None + + # XXX not implemented yet + entdig = None + p_parsed = urlparse(url) + #: path is request-uri defined in RFC 2616 which should not be empty + path = p_parsed.path or "/" + if p_parsed.query: + path += f"?{p_parsed.query}" + + A1 = f"{self.username}:{realm}:{self.password}" + A2 = f"{method}:{path}" + + HA1 = hash_utf8(A1) + HA2 = hash_utf8(A2) + + if nonce == self._thread_local.last_nonce: + self._thread_local.nonce_count += 1 + else: + self._thread_local.nonce_count = 1 + ncvalue = f"{self._thread_local.nonce_count:08x}" + s = str(self._thread_local.nonce_count).encode("utf-8") + s += nonce.encode("utf-8") + s += time.ctime().encode("utf-8") + s += os.urandom(8) + + cnonce = hashlib.sha1(s).hexdigest()[:16] + if _algorithm == "MD5-SESS": + HA1 = hash_utf8(f"{HA1}:{nonce}:{cnonce}") + + if not qop: + respdig = KD(HA1, f"{nonce}:{HA2}") + elif qop == "auth" or "auth" in qop.split(","): + noncebit = f"{nonce}:{ncvalue}:{cnonce}:auth:{HA2}" + respdig = KD(HA1, noncebit) + else: + # XXX handle auth-int. + return None + + self._thread_local.last_nonce = nonce + + # XXX should the partial digests be encoded too? + base = ( + f'username="{self.username}", realm="{realm}", nonce="{nonce}", ' + f'uri="{path}", response="{respdig}"' + ) + if opaque: + base += f', opaque="{opaque}"' + if algorithm: + base += f', algorithm="{algorithm}"' + if entdig: + base += f', digest="{entdig}"' + if qop: + base += f', qop="auth", nc={ncvalue}, cnonce="{cnonce}"' + + return f"Digest {base}" + + def handle_redirect(self, r, **kwargs): + """Reset num_401_calls counter on redirects.""" + if r.is_redirect: + self._thread_local.num_401_calls = 1 + + def handle_401(self, r, **kwargs): + """ + Takes the given response and tries digest-auth, if needed. + + :rtype: requests.Response + """ + + # If response is not 4xx, do not auth + # See https://github.com/psf/requests/issues/3772 + if not 400 <= r.status_code < 500: + self._thread_local.num_401_calls = 1 + return r + + if self._thread_local.pos is not None: + # Rewind the file position indicator of the body to where + # it was to resend the request. + r.request.body.seek(self._thread_local.pos) + s_auth = r.headers.get("www-authenticate", "") + + if "digest" in s_auth.lower() and self._thread_local.num_401_calls < 2: + self._thread_local.num_401_calls += 1 + pat = re.compile(r"digest ", flags=re.IGNORECASE) + self._thread_local.chal = parse_dict_header(pat.sub("", s_auth, count=1)) + + # Consume content and release the original connection + # to allow our new request to reuse the same one. + r.content + r.close() + prep = r.request.copy() + extract_cookies_to_jar(prep._cookies, r.request, r.raw) + prep.prepare_cookies(prep._cookies) + + prep.headers["Authorization"] = self.build_digest_header( + prep.method, prep.url + ) + _r = r.connection.send(prep, **kwargs) + _r.history.append(r) + _r.request = prep + + return _r + + self._thread_local.num_401_calls = 1 + return r + + def __call__(self, r): + # Initialize per-thread state, if needed + self.init_per_thread_state() + # If we have a saved nonce, skip the 401 + if self._thread_local.last_nonce: + r.headers["Authorization"] = self.build_digest_header(r.method, r.url) + try: + self._thread_local.pos = r.body.tell() + except AttributeError: + # In the case of HTTPDigestAuth being reused and the body of + # the previous request was a file-like object, pos has the + # file position of the previous body. Ensure it's set to + # None. + self._thread_local.pos = None + r.register_hook("response", self.handle_401) + r.register_hook("response", self.handle_redirect) + self._thread_local.num_401_calls = 1 + + return r + + def __eq__(self, other): + return all( + [ + self.username == getattr(other, "username", None), + self.password == getattr(other, "password", None), + ] + ) + + def __ne__(self, other): + return not self == other diff --git a/TTS/Kokoro/.venv/Lib/site-packages/requests/certs.py b/TTS/Kokoro/.venv/Lib/site-packages/requests/certs.py new file mode 100644 index 0000000000000000000000000000000000000000..be422c3e91e43bacf60ff3302688df0b28742333 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/requests/certs.py @@ -0,0 +1,17 @@ +#!/usr/bin/env python + +""" +requests.certs +~~~~~~~~~~~~~~ + +This module returns the preferred default CA certificate bundle. There is +only one — the one from the certifi package. + +If you are packaging Requests, e.g., for a Linux distribution or a managed +environment, you can change the definition of where() to return a separately +packaged CA bundle. +""" +from certifi import where + +if __name__ == "__main__": + print(where()) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/requests/compat.py b/TTS/Kokoro/.venv/Lib/site-packages/requests/compat.py new file mode 100644 index 0000000000000000000000000000000000000000..7f9d754350c9fe28db41e328ea880b9e4b20cc8b --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/requests/compat.py @@ -0,0 +1,106 @@ +""" +requests.compat +~~~~~~~~~~~~~~~ + +This module previously handled import compatibility issues +between Python 2 and Python 3. It remains for backwards +compatibility until the next major version. +""" + +import importlib +import sys + +# ------- +# urllib3 +# ------- +from urllib3 import __version__ as urllib3_version + +# Detect which major version of urllib3 is being used. +try: + is_urllib3_1 = int(urllib3_version.split(".")[0]) == 1 +except (TypeError, AttributeError): + # If we can't discern a version, prefer old functionality. + is_urllib3_1 = True + +# ------------------- +# Character Detection +# ------------------- + + +def _resolve_char_detection(): + """Find supported character detection libraries.""" + chardet = None + for lib in ("chardet", "charset_normalizer"): + if chardet is None: + try: + chardet = importlib.import_module(lib) + except ImportError: + pass + return chardet + + +chardet = _resolve_char_detection() + +# ------- +# Pythons +# ------- + +# Syntax sugar. +_ver = sys.version_info + +#: Python 2.x? +is_py2 = _ver[0] == 2 + +#: Python 3.x? +is_py3 = _ver[0] == 3 + +# json/simplejson module import resolution +has_simplejson = False +try: + import simplejson as json + + has_simplejson = True +except ImportError: + import json + +if has_simplejson: + from simplejson import JSONDecodeError +else: + from json import JSONDecodeError + +# Keep OrderedDict for backwards compatibility. +from collections import OrderedDict +from collections.abc import Callable, Mapping, MutableMapping +from http import cookiejar as cookielib +from http.cookies import Morsel +from io import StringIO + +# -------------- +# Legacy Imports +# -------------- +from urllib.parse import ( + quote, + quote_plus, + unquote, + unquote_plus, + urldefrag, + urlencode, + urljoin, + urlparse, + urlsplit, + urlunparse, +) +from urllib.request import ( + getproxies, + getproxies_environment, + parse_http_list, + proxy_bypass, + proxy_bypass_environment, +) + +builtin_str = str +str = str +bytes = bytes +basestring = (str, bytes) +numeric_types = (int, float) +integer_types = (int,) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/requests/cookies.py b/TTS/Kokoro/.venv/Lib/site-packages/requests/cookies.py new file mode 100644 index 0000000000000000000000000000000000000000..f69d0cda9e1c893401015a09f2db2de5a5960fd2 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/requests/cookies.py @@ -0,0 +1,561 @@ +""" +requests.cookies +~~~~~~~~~~~~~~~~ + +Compatibility code to be able to use `http.cookiejar.CookieJar` with requests. + +requests.utils imports from here, so be careful with imports. +""" + +import calendar +import copy +import time + +from ._internal_utils import to_native_string +from .compat import Morsel, MutableMapping, cookielib, urlparse, urlunparse + +try: + import threading +except ImportError: + import dummy_threading as threading + + +class MockRequest: + """Wraps a `requests.Request` to mimic a `urllib2.Request`. + + The code in `http.cookiejar.CookieJar` expects this interface in order to correctly + manage cookie policies, i.e., determine whether a cookie can be set, given the + domains of the request and the cookie. + + The original request object is read-only. The client is responsible for collecting + the new headers via `get_new_headers()` and interpreting them appropriately. You + probably want `get_cookie_header`, defined below. + """ + + def __init__(self, request): + self._r = request + self._new_headers = {} + self.type = urlparse(self._r.url).scheme + + def get_type(self): + return self.type + + def get_host(self): + return urlparse(self._r.url).netloc + + def get_origin_req_host(self): + return self.get_host() + + def get_full_url(self): + # Only return the response's URL if the user hadn't set the Host + # header + if not self._r.headers.get("Host"): + return self._r.url + # If they did set it, retrieve it and reconstruct the expected domain + host = to_native_string(self._r.headers["Host"], encoding="utf-8") + parsed = urlparse(self._r.url) + # Reconstruct the URL as we expect it + return urlunparse( + [ + parsed.scheme, + host, + parsed.path, + parsed.params, + parsed.query, + parsed.fragment, + ] + ) + + def is_unverifiable(self): + return True + + def has_header(self, name): + return name in self._r.headers or name in self._new_headers + + def get_header(self, name, default=None): + return self._r.headers.get(name, self._new_headers.get(name, default)) + + def add_header(self, key, val): + """cookiejar has no legitimate use for this method; add it back if you find one.""" + raise NotImplementedError( + "Cookie headers should be added with add_unredirected_header()" + ) + + def add_unredirected_header(self, name, value): + self._new_headers[name] = value + + def get_new_headers(self): + return self._new_headers + + @property + def unverifiable(self): + return self.is_unverifiable() + + @property + def origin_req_host(self): + return self.get_origin_req_host() + + @property + def host(self): + return self.get_host() + + +class MockResponse: + """Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`. + + ...what? Basically, expose the parsed HTTP headers from the server response + the way `http.cookiejar` expects to see them. + """ + + def __init__(self, headers): + """Make a MockResponse for `cookiejar` to read. + + :param headers: a httplib.HTTPMessage or analogous carrying the headers + """ + self._headers = headers + + def info(self): + return self._headers + + def getheaders(self, name): + self._headers.getheaders(name) + + +def extract_cookies_to_jar(jar, request, response): + """Extract the cookies from the response into a CookieJar. + + :param jar: http.cookiejar.CookieJar (not necessarily a RequestsCookieJar) + :param request: our own requests.Request object + :param response: urllib3.HTTPResponse object + """ + if not (hasattr(response, "_original_response") and response._original_response): + return + # the _original_response field is the wrapped httplib.HTTPResponse object, + req = MockRequest(request) + # pull out the HTTPMessage with the headers and put it in the mock: + res = MockResponse(response._original_response.msg) + jar.extract_cookies(res, req) + + +def get_cookie_header(jar, request): + """ + Produce an appropriate Cookie header string to be sent with `request`, or None. + + :rtype: str + """ + r = MockRequest(request) + jar.add_cookie_header(r) + return r.get_new_headers().get("Cookie") + + +def remove_cookie_by_name(cookiejar, name, domain=None, path=None): + """Unsets a cookie by name, by default over all domains and paths. + + Wraps CookieJar.clear(), is O(n). + """ + clearables = [] + for cookie in cookiejar: + if cookie.name != name: + continue + if domain is not None and domain != cookie.domain: + continue + if path is not None and path != cookie.path: + continue + clearables.append((cookie.domain, cookie.path, cookie.name)) + + for domain, path, name in clearables: + cookiejar.clear(domain, path, name) + + +class CookieConflictError(RuntimeError): + """There are two cookies that meet the criteria specified in the cookie jar. + Use .get and .set and include domain and path args in order to be more specific. + """ + + +class RequestsCookieJar(cookielib.CookieJar, MutableMapping): + """Compatibility class; is a http.cookiejar.CookieJar, but exposes a dict + interface. + + This is the CookieJar we create by default for requests and sessions that + don't specify one, since some clients may expect response.cookies and + session.cookies to support dict operations. + + Requests does not use the dict interface internally; it's just for + compatibility with external client code. All requests code should work + out of the box with externally provided instances of ``CookieJar``, e.g. + ``LWPCookieJar`` and ``FileCookieJar``. + + Unlike a regular CookieJar, this class is pickleable. + + .. warning:: dictionary operations that are normally O(1) may be O(n). + """ + + def get(self, name, default=None, domain=None, path=None): + """Dict-like get() that also supports optional domain and path args in + order to resolve naming collisions from using one cookie jar over + multiple domains. + + .. warning:: operation is O(n), not O(1). + """ + try: + return self._find_no_duplicates(name, domain, path) + except KeyError: + return default + + def set(self, name, value, **kwargs): + """Dict-like set() that also supports optional domain and path args in + order to resolve naming collisions from using one cookie jar over + multiple domains. + """ + # support client code that unsets cookies by assignment of a None value: + if value is None: + remove_cookie_by_name( + self, name, domain=kwargs.get("domain"), path=kwargs.get("path") + ) + return + + if isinstance(value, Morsel): + c = morsel_to_cookie(value) + else: + c = create_cookie(name, value, **kwargs) + self.set_cookie(c) + return c + + def iterkeys(self): + """Dict-like iterkeys() that returns an iterator of names of cookies + from the jar. + + .. seealso:: itervalues() and iteritems(). + """ + for cookie in iter(self): + yield cookie.name + + def keys(self): + """Dict-like keys() that returns a list of names of cookies from the + jar. + + .. seealso:: values() and items(). + """ + return list(self.iterkeys()) + + def itervalues(self): + """Dict-like itervalues() that returns an iterator of values of cookies + from the jar. + + .. seealso:: iterkeys() and iteritems(). + """ + for cookie in iter(self): + yield cookie.value + + def values(self): + """Dict-like values() that returns a list of values of cookies from the + jar. + + .. seealso:: keys() and items(). + """ + return list(self.itervalues()) + + def iteritems(self): + """Dict-like iteritems() that returns an iterator of name-value tuples + from the jar. + + .. seealso:: iterkeys() and itervalues(). + """ + for cookie in iter(self): + yield cookie.name, cookie.value + + def items(self): + """Dict-like items() that returns a list of name-value tuples from the + jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a + vanilla python dict of key value pairs. + + .. seealso:: keys() and values(). + """ + return list(self.iteritems()) + + def list_domains(self): + """Utility method to list all the domains in the jar.""" + domains = [] + for cookie in iter(self): + if cookie.domain not in domains: + domains.append(cookie.domain) + return domains + + def list_paths(self): + """Utility method to list all the paths in the jar.""" + paths = [] + for cookie in iter(self): + if cookie.path not in paths: + paths.append(cookie.path) + return paths + + def multiple_domains(self): + """Returns True if there are multiple domains in the jar. + Returns False otherwise. + + :rtype: bool + """ + domains = [] + for cookie in iter(self): + if cookie.domain is not None and cookie.domain in domains: + return True + domains.append(cookie.domain) + return False # there is only one domain in jar + + def get_dict(self, domain=None, path=None): + """Takes as an argument an optional domain and path and returns a plain + old Python dict of name-value pairs of cookies that meet the + requirements. + + :rtype: dict + """ + dictionary = {} + for cookie in iter(self): + if (domain is None or cookie.domain == domain) and ( + path is None or cookie.path == path + ): + dictionary[cookie.name] = cookie.value + return dictionary + + def __contains__(self, name): + try: + return super().__contains__(name) + except CookieConflictError: + return True + + def __getitem__(self, name): + """Dict-like __getitem__() for compatibility with client code. Throws + exception if there are more than one cookie with name. In that case, + use the more explicit get() method instead. + + .. warning:: operation is O(n), not O(1). + """ + return self._find_no_duplicates(name) + + def __setitem__(self, name, value): + """Dict-like __setitem__ for compatibility with client code. Throws + exception if there is already a cookie of that name in the jar. In that + case, use the more explicit set() method instead. + """ + self.set(name, value) + + def __delitem__(self, name): + """Deletes a cookie given a name. Wraps ``http.cookiejar.CookieJar``'s + ``remove_cookie_by_name()``. + """ + remove_cookie_by_name(self, name) + + def set_cookie(self, cookie, *args, **kwargs): + if ( + hasattr(cookie.value, "startswith") + and cookie.value.startswith('"') + and cookie.value.endswith('"') + ): + cookie.value = cookie.value.replace('\\"', "") + return super().set_cookie(cookie, *args, **kwargs) + + def update(self, other): + """Updates this jar with cookies from another CookieJar or dict-like""" + if isinstance(other, cookielib.CookieJar): + for cookie in other: + self.set_cookie(copy.copy(cookie)) + else: + super().update(other) + + def _find(self, name, domain=None, path=None): + """Requests uses this method internally to get cookie values. + + If there are conflicting cookies, _find arbitrarily chooses one. + See _find_no_duplicates if you want an exception thrown if there are + conflicting cookies. + + :param name: a string containing name of cookie + :param domain: (optional) string containing domain of cookie + :param path: (optional) string containing path of cookie + :return: cookie.value + """ + for cookie in iter(self): + if cookie.name == name: + if domain is None or cookie.domain == domain: + if path is None or cookie.path == path: + return cookie.value + + raise KeyError(f"name={name!r}, domain={domain!r}, path={path!r}") + + def _find_no_duplicates(self, name, domain=None, path=None): + """Both ``__get_item__`` and ``get`` call this function: it's never + used elsewhere in Requests. + + :param name: a string containing name of cookie + :param domain: (optional) string containing domain of cookie + :param path: (optional) string containing path of cookie + :raises KeyError: if cookie is not found + :raises CookieConflictError: if there are multiple cookies + that match name and optionally domain and path + :return: cookie.value + """ + toReturn = None + for cookie in iter(self): + if cookie.name == name: + if domain is None or cookie.domain == domain: + if path is None or cookie.path == path: + if toReturn is not None: + # if there are multiple cookies that meet passed in criteria + raise CookieConflictError( + f"There are multiple cookies with name, {name!r}" + ) + # we will eventually return this as long as no cookie conflict + toReturn = cookie.value + + if toReturn: + return toReturn + raise KeyError(f"name={name!r}, domain={domain!r}, path={path!r}") + + def __getstate__(self): + """Unlike a normal CookieJar, this class is pickleable.""" + state = self.__dict__.copy() + # remove the unpickleable RLock object + state.pop("_cookies_lock") + return state + + def __setstate__(self, state): + """Unlike a normal CookieJar, this class is pickleable.""" + self.__dict__.update(state) + if "_cookies_lock" not in self.__dict__: + self._cookies_lock = threading.RLock() + + def copy(self): + """Return a copy of this RequestsCookieJar.""" + new_cj = RequestsCookieJar() + new_cj.set_policy(self.get_policy()) + new_cj.update(self) + return new_cj + + def get_policy(self): + """Return the CookiePolicy instance used.""" + return self._policy + + +def _copy_cookie_jar(jar): + if jar is None: + return None + + if hasattr(jar, "copy"): + # We're dealing with an instance of RequestsCookieJar + return jar.copy() + # We're dealing with a generic CookieJar instance + new_jar = copy.copy(jar) + new_jar.clear() + for cookie in jar: + new_jar.set_cookie(copy.copy(cookie)) + return new_jar + + +def create_cookie(name, value, **kwargs): + """Make a cookie from underspecified parameters. + + By default, the pair of `name` and `value` will be set for the domain '' + and sent on every request (this is sometimes called a "supercookie"). + """ + result = { + "version": 0, + "name": name, + "value": value, + "port": None, + "domain": "", + "path": "/", + "secure": False, + "expires": None, + "discard": True, + "comment": None, + "comment_url": None, + "rest": {"HttpOnly": None}, + "rfc2109": False, + } + + badargs = set(kwargs) - set(result) + if badargs: + raise TypeError( + f"create_cookie() got unexpected keyword arguments: {list(badargs)}" + ) + + result.update(kwargs) + result["port_specified"] = bool(result["port"]) + result["domain_specified"] = bool(result["domain"]) + result["domain_initial_dot"] = result["domain"].startswith(".") + result["path_specified"] = bool(result["path"]) + + return cookielib.Cookie(**result) + + +def morsel_to_cookie(morsel): + """Convert a Morsel object into a Cookie containing the one k/v pair.""" + + expires = None + if morsel["max-age"]: + try: + expires = int(time.time() + int(morsel["max-age"])) + except ValueError: + raise TypeError(f"max-age: {morsel['max-age']} must be integer") + elif morsel["expires"]: + time_template = "%a, %d-%b-%Y %H:%M:%S GMT" + expires = calendar.timegm(time.strptime(morsel["expires"], time_template)) + return create_cookie( + comment=morsel["comment"], + comment_url=bool(morsel["comment"]), + discard=False, + domain=morsel["domain"], + expires=expires, + name=morsel.key, + path=morsel["path"], + port=None, + rest={"HttpOnly": morsel["httponly"]}, + rfc2109=False, + secure=bool(morsel["secure"]), + value=morsel.value, + version=morsel["version"] or 0, + ) + + +def cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True): + """Returns a CookieJar from a key/value dictionary. + + :param cookie_dict: Dict of key/values to insert into CookieJar. + :param cookiejar: (optional) A cookiejar to add the cookies to. + :param overwrite: (optional) If False, will not replace cookies + already in the jar with new ones. + :rtype: CookieJar + """ + if cookiejar is None: + cookiejar = RequestsCookieJar() + + if cookie_dict is not None: + names_from_jar = [cookie.name for cookie in cookiejar] + for name in cookie_dict: + if overwrite or (name not in names_from_jar): + cookiejar.set_cookie(create_cookie(name, cookie_dict[name])) + + return cookiejar + + +def merge_cookies(cookiejar, cookies): + """Add cookies to cookiejar and returns a merged CookieJar. + + :param cookiejar: CookieJar object to add the cookies to. + :param cookies: Dictionary or CookieJar object to be added. + :rtype: CookieJar + """ + if not isinstance(cookiejar, cookielib.CookieJar): + raise ValueError("You can only merge into CookieJar") + + if isinstance(cookies, dict): + cookiejar = cookiejar_from_dict(cookies, cookiejar=cookiejar, overwrite=False) + elif isinstance(cookies, cookielib.CookieJar): + try: + cookiejar.update(cookies) + except AttributeError: + for cookie_in_jar in cookies: + cookiejar.set_cookie(cookie_in_jar) + + return cookiejar diff --git a/TTS/Kokoro/.venv/Lib/site-packages/requests/exceptions.py b/TTS/Kokoro/.venv/Lib/site-packages/requests/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..83986b489849131efeb7f286b328961205256fd8 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/requests/exceptions.py @@ -0,0 +1,151 @@ +""" +requests.exceptions +~~~~~~~~~~~~~~~~~~~ + +This module contains the set of Requests' exceptions. +""" +from urllib3.exceptions import HTTPError as BaseHTTPError + +from .compat import JSONDecodeError as CompatJSONDecodeError + + +class RequestException(IOError): + """There was an ambiguous exception that occurred while handling your + request. + """ + + def __init__(self, *args, **kwargs): + """Initialize RequestException with `request` and `response` objects.""" + response = kwargs.pop("response", None) + self.response = response + self.request = kwargs.pop("request", None) + if response is not None and not self.request and hasattr(response, "request"): + self.request = self.response.request + super().__init__(*args, **kwargs) + + +class InvalidJSONError(RequestException): + """A JSON error occurred.""" + + +class JSONDecodeError(InvalidJSONError, CompatJSONDecodeError): + """Couldn't decode the text into json""" + + def __init__(self, *args, **kwargs): + """ + Construct the JSONDecodeError instance first with all + args. Then use it's args to construct the IOError so that + the json specific args aren't used as IOError specific args + and the error message from JSONDecodeError is preserved. + """ + CompatJSONDecodeError.__init__(self, *args) + InvalidJSONError.__init__(self, *self.args, **kwargs) + + def __reduce__(self): + """ + The __reduce__ method called when pickling the object must + be the one from the JSONDecodeError (be it json/simplejson) + as it expects all the arguments for instantiation, not just + one like the IOError, and the MRO would by default call the + __reduce__ method from the IOError due to the inheritance order. + """ + return CompatJSONDecodeError.__reduce__(self) + + +class HTTPError(RequestException): + """An HTTP error occurred.""" + + +class ConnectionError(RequestException): + """A Connection error occurred.""" + + +class ProxyError(ConnectionError): + """A proxy error occurred.""" + + +class SSLError(ConnectionError): + """An SSL error occurred.""" + + +class Timeout(RequestException): + """The request timed out. + + Catching this error will catch both + :exc:`~requests.exceptions.ConnectTimeout` and + :exc:`~requests.exceptions.ReadTimeout` errors. + """ + + +class ConnectTimeout(ConnectionError, Timeout): + """The request timed out while trying to connect to the remote server. + + Requests that produced this error are safe to retry. + """ + + +class ReadTimeout(Timeout): + """The server did not send any data in the allotted amount of time.""" + + +class URLRequired(RequestException): + """A valid URL is required to make a request.""" + + +class TooManyRedirects(RequestException): + """Too many redirects.""" + + +class MissingSchema(RequestException, ValueError): + """The URL scheme (e.g. http or https) is missing.""" + + +class InvalidSchema(RequestException, ValueError): + """The URL scheme provided is either invalid or unsupported.""" + + +class InvalidURL(RequestException, ValueError): + """The URL provided was somehow invalid.""" + + +class InvalidHeader(RequestException, ValueError): + """The header value provided was somehow invalid.""" + + +class InvalidProxyURL(InvalidURL): + """The proxy URL provided is invalid.""" + + +class ChunkedEncodingError(RequestException): + """The server declared chunked encoding but sent an invalid chunk.""" + + +class ContentDecodingError(RequestException, BaseHTTPError): + """Failed to decode response content.""" + + +class StreamConsumedError(RequestException, TypeError): + """The content for this response was already consumed.""" + + +class RetryError(RequestException): + """Custom retries logic failed""" + + +class UnrewindableBodyError(RequestException): + """Requests encountered an error when trying to rewind a body.""" + + +# Warnings + + +class RequestsWarning(Warning): + """Base warning for Requests.""" + + +class FileModeWarning(RequestsWarning, DeprecationWarning): + """A file was opened in text mode, but Requests determined its binary length.""" + + +class RequestsDependencyWarning(RequestsWarning): + """An imported dependency doesn't match the expected version range.""" diff --git a/TTS/Kokoro/.venv/Lib/site-packages/requests/help.py b/TTS/Kokoro/.venv/Lib/site-packages/requests/help.py new file mode 100644 index 0000000000000000000000000000000000000000..8fbcd6560a8fe2c8a07e3bd1441a81e0db9cb689 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/requests/help.py @@ -0,0 +1,134 @@ +"""Module containing bug report helper(s).""" + +import json +import platform +import ssl +import sys + +import idna +import urllib3 + +from . import __version__ as requests_version + +try: + import charset_normalizer +except ImportError: + charset_normalizer = None + +try: + import chardet +except ImportError: + chardet = None + +try: + from urllib3.contrib import pyopenssl +except ImportError: + pyopenssl = None + OpenSSL = None + cryptography = None +else: + import cryptography + import OpenSSL + + +def _implementation(): + """Return a dict with the Python implementation and version. + + Provide both the name and the version of the Python implementation + currently running. For example, on CPython 3.10.3 it will return + {'name': 'CPython', 'version': '3.10.3'}. + + This function works best on CPython and PyPy: in particular, it probably + doesn't work for Jython or IronPython. Future investigation should be done + to work out the correct shape of the code for those platforms. + """ + implementation = platform.python_implementation() + + if implementation == "CPython": + implementation_version = platform.python_version() + elif implementation == "PyPy": + implementation_version = "{}.{}.{}".format( + sys.pypy_version_info.major, + sys.pypy_version_info.minor, + sys.pypy_version_info.micro, + ) + if sys.pypy_version_info.releaselevel != "final": + implementation_version = "".join( + [implementation_version, sys.pypy_version_info.releaselevel] + ) + elif implementation == "Jython": + implementation_version = platform.python_version() # Complete Guess + elif implementation == "IronPython": + implementation_version = platform.python_version() # Complete Guess + else: + implementation_version = "Unknown" + + return {"name": implementation, "version": implementation_version} + + +def info(): + """Generate information for a bug report.""" + try: + platform_info = { + "system": platform.system(), + "release": platform.release(), + } + except OSError: + platform_info = { + "system": "Unknown", + "release": "Unknown", + } + + implementation_info = _implementation() + urllib3_info = {"version": urllib3.__version__} + charset_normalizer_info = {"version": None} + chardet_info = {"version": None} + if charset_normalizer: + charset_normalizer_info = {"version": charset_normalizer.__version__} + if chardet: + chardet_info = {"version": chardet.__version__} + + pyopenssl_info = { + "version": None, + "openssl_version": "", + } + if OpenSSL: + pyopenssl_info = { + "version": OpenSSL.__version__, + "openssl_version": f"{OpenSSL.SSL.OPENSSL_VERSION_NUMBER:x}", + } + cryptography_info = { + "version": getattr(cryptography, "__version__", ""), + } + idna_info = { + "version": getattr(idna, "__version__", ""), + } + + system_ssl = ssl.OPENSSL_VERSION_NUMBER + system_ssl_info = {"version": f"{system_ssl:x}" if system_ssl is not None else ""} + + return { + "platform": platform_info, + "implementation": implementation_info, + "system_ssl": system_ssl_info, + "using_pyopenssl": pyopenssl is not None, + "using_charset_normalizer": chardet is None, + "pyOpenSSL": pyopenssl_info, + "urllib3": urllib3_info, + "chardet": chardet_info, + "charset_normalizer": charset_normalizer_info, + "cryptography": cryptography_info, + "idna": idna_info, + "requests": { + "version": requests_version, + }, + } + + +def main(): + """Pretty-print the bug information as JSON.""" + print(json.dumps(info(), sort_keys=True, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/TTS/Kokoro/.venv/Lib/site-packages/requests/hooks.py b/TTS/Kokoro/.venv/Lib/site-packages/requests/hooks.py new file mode 100644 index 0000000000000000000000000000000000000000..d181ba2ec2e55d274897315887b78fbdca757da8 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/requests/hooks.py @@ -0,0 +1,33 @@ +""" +requests.hooks +~~~~~~~~~~~~~~ + +This module provides the capabilities for the Requests hooks system. + +Available hooks: + +``response``: + The response generated from a Request. +""" +HOOKS = ["response"] + + +def default_hooks(): + return {event: [] for event in HOOKS} + + +# TODO: response is the only one + + +def dispatch_hook(key, hooks, hook_data, **kwargs): + """Dispatches a hook dictionary on a given piece of data.""" + hooks = hooks or {} + hooks = hooks.get(key) + if hooks: + if hasattr(hooks, "__call__"): + hooks = [hooks] + for hook in hooks: + _hook_data = hook(hook_data, **kwargs) + if _hook_data is not None: + hook_data = _hook_data + return hook_data diff --git a/TTS/Kokoro/.venv/Lib/site-packages/requests/models.py b/TTS/Kokoro/.venv/Lib/site-packages/requests/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c4b25fa0790da44683dab185c89ac08b69fb7419 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/requests/models.py @@ -0,0 +1,1039 @@ +""" +requests.models +~~~~~~~~~~~~~~~ + +This module contains the primary objects that power Requests. +""" + +import datetime + +# Import encoding now, to avoid implicit import later. +# Implicit import within threads may cause LookupError when standard library is in a ZIP, +# such as in Embedded Python. See https://github.com/psf/requests/issues/3578. +import encodings.idna # noqa: F401 +from io import UnsupportedOperation + +from urllib3.exceptions import ( + DecodeError, + LocationParseError, + ProtocolError, + ReadTimeoutError, + SSLError, +) +from urllib3.fields import RequestField +from urllib3.filepost import encode_multipart_formdata +from urllib3.util import parse_url + +from ._internal_utils import to_native_string, unicode_is_ascii +from .auth import HTTPBasicAuth +from .compat import ( + Callable, + JSONDecodeError, + Mapping, + basestring, + builtin_str, + chardet, + cookielib, +) +from .compat import json as complexjson +from .compat import urlencode, urlsplit, urlunparse +from .cookies import _copy_cookie_jar, cookiejar_from_dict, get_cookie_header +from .exceptions import ( + ChunkedEncodingError, + ConnectionError, + ContentDecodingError, + HTTPError, + InvalidJSONError, + InvalidURL, +) +from .exceptions import JSONDecodeError as RequestsJSONDecodeError +from .exceptions import MissingSchema +from .exceptions import SSLError as RequestsSSLError +from .exceptions import StreamConsumedError +from .hooks import default_hooks +from .status_codes import codes +from .structures import CaseInsensitiveDict +from .utils import ( + check_header_validity, + get_auth_from_url, + guess_filename, + guess_json_utf, + iter_slices, + parse_header_links, + requote_uri, + stream_decode_response_unicode, + super_len, + to_key_val_list, +) + +#: The set of HTTP status codes that indicate an automatically +#: processable redirect. +REDIRECT_STATI = ( + codes.moved, # 301 + codes.found, # 302 + codes.other, # 303 + codes.temporary_redirect, # 307 + codes.permanent_redirect, # 308 +) + +DEFAULT_REDIRECT_LIMIT = 30 +CONTENT_CHUNK_SIZE = 10 * 1024 +ITER_CHUNK_SIZE = 512 + + +class RequestEncodingMixin: + @property + def path_url(self): + """Build the path URL to use.""" + + url = [] + + p = urlsplit(self.url) + + path = p.path + if not path: + path = "/" + + url.append(path) + + query = p.query + if query: + url.append("?") + url.append(query) + + return "".join(url) + + @staticmethod + def _encode_params(data): + """Encode parameters in a piece of data. + + Will successfully encode parameters when passed as a dict or a list of + 2-tuples. Order is retained if data is a list of 2-tuples but arbitrary + if parameters are supplied as a dict. + """ + + if isinstance(data, (str, bytes)): + return data + elif hasattr(data, "read"): + return data + elif hasattr(data, "__iter__"): + result = [] + for k, vs in to_key_val_list(data): + if isinstance(vs, basestring) or not hasattr(vs, "__iter__"): + vs = [vs] + for v in vs: + if v is not None: + result.append( + ( + k.encode("utf-8") if isinstance(k, str) else k, + v.encode("utf-8") if isinstance(v, str) else v, + ) + ) + return urlencode(result, doseq=True) + else: + return data + + @staticmethod + def _encode_files(files, data): + """Build the body for a multipart/form-data request. + + Will successfully encode files when passed as a dict or a list of + tuples. Order is retained if data is a list of tuples but arbitrary + if parameters are supplied as a dict. + The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype) + or 4-tuples (filename, fileobj, contentype, custom_headers). + """ + if not files: + raise ValueError("Files must be provided.") + elif isinstance(data, basestring): + raise ValueError("Data must not be a string.") + + new_fields = [] + fields = to_key_val_list(data or {}) + files = to_key_val_list(files or {}) + + for field, val in fields: + if isinstance(val, basestring) or not hasattr(val, "__iter__"): + val = [val] + for v in val: + if v is not None: + # Don't call str() on bytestrings: in Py3 it all goes wrong. + if not isinstance(v, bytes): + v = str(v) + + new_fields.append( + ( + field.decode("utf-8") + if isinstance(field, bytes) + else field, + v.encode("utf-8") if isinstance(v, str) else v, + ) + ) + + for k, v in files: + # support for explicit filename + ft = None + fh = None + if isinstance(v, (tuple, list)): + if len(v) == 2: + fn, fp = v + elif len(v) == 3: + fn, fp, ft = v + else: + fn, fp, ft, fh = v + else: + fn = guess_filename(v) or k + fp = v + + if isinstance(fp, (str, bytes, bytearray)): + fdata = fp + elif hasattr(fp, "read"): + fdata = fp.read() + elif fp is None: + continue + else: + fdata = fp + + rf = RequestField(name=k, data=fdata, filename=fn, headers=fh) + rf.make_multipart(content_type=ft) + new_fields.append(rf) + + body, content_type = encode_multipart_formdata(new_fields) + + return body, content_type + + +class RequestHooksMixin: + def register_hook(self, event, hook): + """Properly register a hook.""" + + if event not in self.hooks: + raise ValueError(f'Unsupported event specified, with event name "{event}"') + + if isinstance(hook, Callable): + self.hooks[event].append(hook) + elif hasattr(hook, "__iter__"): + self.hooks[event].extend(h for h in hook if isinstance(h, Callable)) + + def deregister_hook(self, event, hook): + """Deregister a previously registered hook. + Returns True if the hook existed, False if not. + """ + + try: + self.hooks[event].remove(hook) + return True + except ValueError: + return False + + +class Request(RequestHooksMixin): + """A user-created :class:`Request ` object. + + Used to prepare a :class:`PreparedRequest `, which is sent to the server. + + :param method: HTTP method to use. + :param url: URL to send. + :param headers: dictionary of headers to send. + :param files: dictionary of {filename: fileobject} files to multipart upload. + :param data: the body to attach to the request. If a dictionary or + list of tuples ``[(key, value)]`` is provided, form-encoding will + take place. + :param json: json for the body to attach to the request (if files or data is not specified). + :param params: URL parameters to append to the URL. If a dictionary or + list of tuples ``[(key, value)]`` is provided, form-encoding will + take place. + :param auth: Auth handler or (user, pass) tuple. + :param cookies: dictionary or CookieJar of cookies to attach to this request. + :param hooks: dictionary of callback hooks, for internal usage. + + Usage:: + + >>> import requests + >>> req = requests.Request('GET', 'https://httpbin.org/get') + >>> req.prepare() + + """ + + def __init__( + self, + method=None, + url=None, + headers=None, + files=None, + data=None, + params=None, + auth=None, + cookies=None, + hooks=None, + json=None, + ): + # Default empty dicts for dict params. + data = [] if data is None else data + files = [] if files is None else files + headers = {} if headers is None else headers + params = {} if params is None else params + hooks = {} if hooks is None else hooks + + self.hooks = default_hooks() + for k, v in list(hooks.items()): + self.register_hook(event=k, hook=v) + + self.method = method + self.url = url + self.headers = headers + self.files = files + self.data = data + self.json = json + self.params = params + self.auth = auth + self.cookies = cookies + + def __repr__(self): + return f"" + + def prepare(self): + """Constructs a :class:`PreparedRequest ` for transmission and returns it.""" + p = PreparedRequest() + p.prepare( + method=self.method, + url=self.url, + headers=self.headers, + files=self.files, + data=self.data, + json=self.json, + params=self.params, + auth=self.auth, + cookies=self.cookies, + hooks=self.hooks, + ) + return p + + +class PreparedRequest(RequestEncodingMixin, RequestHooksMixin): + """The fully mutable :class:`PreparedRequest ` object, + containing the exact bytes that will be sent to the server. + + Instances are generated from a :class:`Request ` object, and + should not be instantiated manually; doing so may produce undesirable + effects. + + Usage:: + + >>> import requests + >>> req = requests.Request('GET', 'https://httpbin.org/get') + >>> r = req.prepare() + >>> r + + + >>> s = requests.Session() + >>> s.send(r) + + """ + + def __init__(self): + #: HTTP verb to send to the server. + self.method = None + #: HTTP URL to send the request to. + self.url = None + #: dictionary of HTTP headers. + self.headers = None + # The `CookieJar` used to create the Cookie header will be stored here + # after prepare_cookies is called + self._cookies = None + #: request body to send to the server. + self.body = None + #: dictionary of callback hooks, for internal usage. + self.hooks = default_hooks() + #: integer denoting starting position of a readable file-like body. + self._body_position = None + + def prepare( + self, + method=None, + url=None, + headers=None, + files=None, + data=None, + params=None, + auth=None, + cookies=None, + hooks=None, + json=None, + ): + """Prepares the entire request with the given parameters.""" + + self.prepare_method(method) + self.prepare_url(url, params) + self.prepare_headers(headers) + self.prepare_cookies(cookies) + self.prepare_body(data, files, json) + self.prepare_auth(auth, url) + + # Note that prepare_auth must be last to enable authentication schemes + # such as OAuth to work on a fully prepared request. + + # This MUST go after prepare_auth. Authenticators could add a hook + self.prepare_hooks(hooks) + + def __repr__(self): + return f"" + + def copy(self): + p = PreparedRequest() + p.method = self.method + p.url = self.url + p.headers = self.headers.copy() if self.headers is not None else None + p._cookies = _copy_cookie_jar(self._cookies) + p.body = self.body + p.hooks = self.hooks + p._body_position = self._body_position + return p + + def prepare_method(self, method): + """Prepares the given HTTP method.""" + self.method = method + if self.method is not None: + self.method = to_native_string(self.method.upper()) + + @staticmethod + def _get_idna_encoded_host(host): + import idna + + try: + host = idna.encode(host, uts46=True).decode("utf-8") + except idna.IDNAError: + raise UnicodeError + return host + + def prepare_url(self, url, params): + """Prepares the given HTTP URL.""" + #: Accept objects that have string representations. + #: We're unable to blindly call unicode/str functions + #: as this will include the bytestring indicator (b'') + #: on python 3.x. + #: https://github.com/psf/requests/pull/2238 + if isinstance(url, bytes): + url = url.decode("utf8") + else: + url = str(url) + + # Remove leading whitespaces from url + url = url.lstrip() + + # Don't do any URL preparation for non-HTTP schemes like `mailto`, + # `data` etc to work around exceptions from `url_parse`, which + # handles RFC 3986 only. + if ":" in url and not url.lower().startswith("http"): + self.url = url + return + + # Support for unicode domain names and paths. + try: + scheme, auth, host, port, path, query, fragment = parse_url(url) + except LocationParseError as e: + raise InvalidURL(*e.args) + + if not scheme: + raise MissingSchema( + f"Invalid URL {url!r}: No scheme supplied. " + f"Perhaps you meant https://{url}?" + ) + + if not host: + raise InvalidURL(f"Invalid URL {url!r}: No host supplied") + + # In general, we want to try IDNA encoding the hostname if the string contains + # non-ASCII characters. This allows users to automatically get the correct IDNA + # behaviour. For strings containing only ASCII characters, we need to also verify + # it doesn't start with a wildcard (*), before allowing the unencoded hostname. + if not unicode_is_ascii(host): + try: + host = self._get_idna_encoded_host(host) + except UnicodeError: + raise InvalidURL("URL has an invalid label.") + elif host.startswith(("*", ".")): + raise InvalidURL("URL has an invalid label.") + + # Carefully reconstruct the network location + netloc = auth or "" + if netloc: + netloc += "@" + netloc += host + if port: + netloc += f":{port}" + + # Bare domains aren't valid URLs. + if not path: + path = "/" + + if isinstance(params, (str, bytes)): + params = to_native_string(params) + + enc_params = self._encode_params(params) + if enc_params: + if query: + query = f"{query}&{enc_params}" + else: + query = enc_params + + url = requote_uri(urlunparse([scheme, netloc, path, None, query, fragment])) + self.url = url + + def prepare_headers(self, headers): + """Prepares the given HTTP headers.""" + + self.headers = CaseInsensitiveDict() + if headers: + for header in headers.items(): + # Raise exception on invalid header value. + check_header_validity(header) + name, value = header + self.headers[to_native_string(name)] = value + + def prepare_body(self, data, files, json=None): + """Prepares the given HTTP body data.""" + + # Check if file, fo, generator, iterator. + # If not, run through normal process. + + # Nottin' on you. + body = None + content_type = None + + if not data and json is not None: + # urllib3 requires a bytes-like body. Python 2's json.dumps + # provides this natively, but Python 3 gives a Unicode string. + content_type = "application/json" + + try: + body = complexjson.dumps(json, allow_nan=False) + except ValueError as ve: + raise InvalidJSONError(ve, request=self) + + if not isinstance(body, bytes): + body = body.encode("utf-8") + + is_stream = all( + [ + hasattr(data, "__iter__"), + not isinstance(data, (basestring, list, tuple, Mapping)), + ] + ) + + if is_stream: + try: + length = super_len(data) + except (TypeError, AttributeError, UnsupportedOperation): + length = None + + body = data + + if getattr(body, "tell", None) is not None: + # Record the current file position before reading. + # This will allow us to rewind a file in the event + # of a redirect. + try: + self._body_position = body.tell() + except OSError: + # This differentiates from None, allowing us to catch + # a failed `tell()` later when trying to rewind the body + self._body_position = object() + + if files: + raise NotImplementedError( + "Streamed bodies and files are mutually exclusive." + ) + + if length: + self.headers["Content-Length"] = builtin_str(length) + else: + self.headers["Transfer-Encoding"] = "chunked" + else: + # Multi-part file uploads. + if files: + (body, content_type) = self._encode_files(files, data) + else: + if data: + body = self._encode_params(data) + if isinstance(data, basestring) or hasattr(data, "read"): + content_type = None + else: + content_type = "application/x-www-form-urlencoded" + + self.prepare_content_length(body) + + # Add content-type if it wasn't explicitly provided. + if content_type and ("content-type" not in self.headers): + self.headers["Content-Type"] = content_type + + self.body = body + + def prepare_content_length(self, body): + """Prepare Content-Length header based on request method and body""" + if body is not None: + length = super_len(body) + if length: + # If length exists, set it. Otherwise, we fallback + # to Transfer-Encoding: chunked. + self.headers["Content-Length"] = builtin_str(length) + elif ( + self.method not in ("GET", "HEAD") + and self.headers.get("Content-Length") is None + ): + # Set Content-Length to 0 for methods that can have a body + # but don't provide one. (i.e. not GET or HEAD) + self.headers["Content-Length"] = "0" + + def prepare_auth(self, auth, url=""): + """Prepares the given HTTP auth data.""" + + # If no Auth is explicitly provided, extract it from the URL first. + if auth is None: + url_auth = get_auth_from_url(self.url) + auth = url_auth if any(url_auth) else None + + if auth: + if isinstance(auth, tuple) and len(auth) == 2: + # special-case basic HTTP auth + auth = HTTPBasicAuth(*auth) + + # Allow auth to make its changes. + r = auth(self) + + # Update self to reflect the auth changes. + self.__dict__.update(r.__dict__) + + # Recompute Content-Length + self.prepare_content_length(self.body) + + def prepare_cookies(self, cookies): + """Prepares the given HTTP cookie data. + + This function eventually generates a ``Cookie`` header from the + given cookies using cookielib. Due to cookielib's design, the header + will not be regenerated if it already exists, meaning this function + can only be called once for the life of the + :class:`PreparedRequest ` object. Any subsequent calls + to ``prepare_cookies`` will have no actual effect, unless the "Cookie" + header is removed beforehand. + """ + if isinstance(cookies, cookielib.CookieJar): + self._cookies = cookies + else: + self._cookies = cookiejar_from_dict(cookies) + + cookie_header = get_cookie_header(self._cookies, self) + if cookie_header is not None: + self.headers["Cookie"] = cookie_header + + def prepare_hooks(self, hooks): + """Prepares the given hooks.""" + # hooks can be passed as None to the prepare method and to this + # method. To prevent iterating over None, simply use an empty list + # if hooks is False-y + hooks = hooks or [] + for event in hooks: + self.register_hook(event, hooks[event]) + + +class Response: + """The :class:`Response ` object, which contains a + server's response to an HTTP request. + """ + + __attrs__ = [ + "_content", + "status_code", + "headers", + "url", + "history", + "encoding", + "reason", + "cookies", + "elapsed", + "request", + ] + + def __init__(self): + self._content = False + self._content_consumed = False + self._next = None + + #: Integer Code of responded HTTP Status, e.g. 404 or 200. + self.status_code = None + + #: Case-insensitive Dictionary of Response Headers. + #: For example, ``headers['content-encoding']`` will return the + #: value of a ``'Content-Encoding'`` response header. + self.headers = CaseInsensitiveDict() + + #: File-like object representation of response (for advanced usage). + #: Use of ``raw`` requires that ``stream=True`` be set on the request. + #: This requirement does not apply for use internally to Requests. + self.raw = None + + #: Final URL location of Response. + self.url = None + + #: Encoding to decode with when accessing r.text. + self.encoding = None + + #: A list of :class:`Response ` objects from + #: the history of the Request. Any redirect responses will end + #: up here. The list is sorted from the oldest to the most recent request. + self.history = [] + + #: Textual reason of responded HTTP Status, e.g. "Not Found" or "OK". + self.reason = None + + #: A CookieJar of Cookies the server sent back. + self.cookies = cookiejar_from_dict({}) + + #: The amount of time elapsed between sending the request + #: and the arrival of the response (as a timedelta). + #: This property specifically measures the time taken between sending + #: the first byte of the request and finishing parsing the headers. It + #: is therefore unaffected by consuming the response content or the + #: value of the ``stream`` keyword argument. + self.elapsed = datetime.timedelta(0) + + #: The :class:`PreparedRequest ` object to which this + #: is a response. + self.request = None + + def __enter__(self): + return self + + def __exit__(self, *args): + self.close() + + def __getstate__(self): + # Consume everything; accessing the content attribute makes + # sure the content has been fully read. + if not self._content_consumed: + self.content + + return {attr: getattr(self, attr, None) for attr in self.__attrs__} + + def __setstate__(self, state): + for name, value in state.items(): + setattr(self, name, value) + + # pickled objects do not have .raw + setattr(self, "_content_consumed", True) + setattr(self, "raw", None) + + def __repr__(self): + return f"" + + def __bool__(self): + """Returns True if :attr:`status_code` is less than 400. + + This attribute checks if the status code of the response is between + 400 and 600 to see if there was a client error or a server error. If + the status code, is between 200 and 400, this will return True. This + is **not** a check to see if the response code is ``200 OK``. + """ + return self.ok + + def __nonzero__(self): + """Returns True if :attr:`status_code` is less than 400. + + This attribute checks if the status code of the response is between + 400 and 600 to see if there was a client error or a server error. If + the status code, is between 200 and 400, this will return True. This + is **not** a check to see if the response code is ``200 OK``. + """ + return self.ok + + def __iter__(self): + """Allows you to use a response as an iterator.""" + return self.iter_content(128) + + @property + def ok(self): + """Returns True if :attr:`status_code` is less than 400, False if not. + + This attribute checks if the status code of the response is between + 400 and 600 to see if there was a client error or a server error. If + the status code is between 200 and 400, this will return True. This + is **not** a check to see if the response code is ``200 OK``. + """ + try: + self.raise_for_status() + except HTTPError: + return False + return True + + @property + def is_redirect(self): + """True if this Response is a well-formed HTTP redirect that could have + been processed automatically (by :meth:`Session.resolve_redirects`). + """ + return "location" in self.headers and self.status_code in REDIRECT_STATI + + @property + def is_permanent_redirect(self): + """True if this Response one of the permanent versions of redirect.""" + return "location" in self.headers and self.status_code in ( + codes.moved_permanently, + codes.permanent_redirect, + ) + + @property + def next(self): + """Returns a PreparedRequest for the next request in a redirect chain, if there is one.""" + return self._next + + @property + def apparent_encoding(self): + """The apparent encoding, provided by the charset_normalizer or chardet libraries.""" + if chardet is not None: + return chardet.detect(self.content)["encoding"] + else: + # If no character detection library is available, we'll fall back + # to a standard Python utf-8 str. + return "utf-8" + + def iter_content(self, chunk_size=1, decode_unicode=False): + """Iterates over the response data. When stream=True is set on the + request, this avoids reading the content at once into memory for + large responses. The chunk size is the number of bytes it should + read into memory. This is not necessarily the length of each item + returned as decoding can take place. + + chunk_size must be of type int or None. A value of None will + function differently depending on the value of `stream`. + stream=True will read data as it arrives in whatever size the + chunks are received. If stream=False, data is returned as + a single chunk. + + If decode_unicode is True, content will be decoded using the best + available encoding based on the response. + """ + + def generate(): + # Special case for urllib3. + if hasattr(self.raw, "stream"): + try: + yield from self.raw.stream(chunk_size, decode_content=True) + except ProtocolError as e: + raise ChunkedEncodingError(e) + except DecodeError as e: + raise ContentDecodingError(e) + except ReadTimeoutError as e: + raise ConnectionError(e) + except SSLError as e: + raise RequestsSSLError(e) + else: + # Standard file-like object. + while True: + chunk = self.raw.read(chunk_size) + if not chunk: + break + yield chunk + + self._content_consumed = True + + if self._content_consumed and isinstance(self._content, bool): + raise StreamConsumedError() + elif chunk_size is not None and not isinstance(chunk_size, int): + raise TypeError( + f"chunk_size must be an int, it is instead a {type(chunk_size)}." + ) + # simulate reading small chunks of the content + reused_chunks = iter_slices(self._content, chunk_size) + + stream_chunks = generate() + + chunks = reused_chunks if self._content_consumed else stream_chunks + + if decode_unicode: + chunks = stream_decode_response_unicode(chunks, self) + + return chunks + + def iter_lines( + self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=False, delimiter=None + ): + """Iterates over the response data, one line at a time. When + stream=True is set on the request, this avoids reading the + content at once into memory for large responses. + + .. note:: This method is not reentrant safe. + """ + + pending = None + + for chunk in self.iter_content( + chunk_size=chunk_size, decode_unicode=decode_unicode + ): + if pending is not None: + chunk = pending + chunk + + if delimiter: + lines = chunk.split(delimiter) + else: + lines = chunk.splitlines() + + if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]: + pending = lines.pop() + else: + pending = None + + yield from lines + + if pending is not None: + yield pending + + @property + def content(self): + """Content of the response, in bytes.""" + + if self._content is False: + # Read the contents. + if self._content_consumed: + raise RuntimeError("The content for this response was already consumed") + + if self.status_code == 0 or self.raw is None: + self._content = None + else: + self._content = b"".join(self.iter_content(CONTENT_CHUNK_SIZE)) or b"" + + self._content_consumed = True + # don't need to release the connection; that's been handled by urllib3 + # since we exhausted the data. + return self._content + + @property + def text(self): + """Content of the response, in unicode. + + If Response.encoding is None, encoding will be guessed using + ``charset_normalizer`` or ``chardet``. + + The encoding of the response content is determined based solely on HTTP + headers, following RFC 2616 to the letter. If you can take advantage of + non-HTTP knowledge to make a better guess at the encoding, you should + set ``r.encoding`` appropriately before accessing this property. + """ + + # Try charset from content-type + content = None + encoding = self.encoding + + if not self.content: + return "" + + # Fallback to auto-detected encoding. + if self.encoding is None: + encoding = self.apparent_encoding + + # Decode unicode from given encoding. + try: + content = str(self.content, encoding, errors="replace") + except (LookupError, TypeError): + # A LookupError is raised if the encoding was not found which could + # indicate a misspelling or similar mistake. + # + # A TypeError can be raised if encoding is None + # + # So we try blindly encoding. + content = str(self.content, errors="replace") + + return content + + def json(self, **kwargs): + r"""Decodes the JSON response body (if any) as a Python object. + + This may return a dictionary, list, etc. depending on what is in the response. + + :param \*\*kwargs: Optional arguments that ``json.loads`` takes. + :raises requests.exceptions.JSONDecodeError: If the response body does not + contain valid json. + """ + + if not self.encoding and self.content and len(self.content) > 3: + # No encoding set. JSON RFC 4627 section 3 states we should expect + # UTF-8, -16 or -32. Detect which one to use; If the detection or + # decoding fails, fall back to `self.text` (using charset_normalizer to make + # a best guess). + encoding = guess_json_utf(self.content) + if encoding is not None: + try: + return complexjson.loads(self.content.decode(encoding), **kwargs) + except UnicodeDecodeError: + # Wrong UTF codec detected; usually because it's not UTF-8 + # but some other 8-bit codec. This is an RFC violation, + # and the server didn't bother to tell us what codec *was* + # used. + pass + except JSONDecodeError as e: + raise RequestsJSONDecodeError(e.msg, e.doc, e.pos) + + try: + return complexjson.loads(self.text, **kwargs) + except JSONDecodeError as e: + # Catch JSON-related errors and raise as requests.JSONDecodeError + # This aliases json.JSONDecodeError and simplejson.JSONDecodeError + raise RequestsJSONDecodeError(e.msg, e.doc, e.pos) + + @property + def links(self): + """Returns the parsed header links of the response, if any.""" + + header = self.headers.get("link") + + resolved_links = {} + + if header: + links = parse_header_links(header) + + for link in links: + key = link.get("rel") or link.get("url") + resolved_links[key] = link + + return resolved_links + + def raise_for_status(self): + """Raises :class:`HTTPError`, if one occurred.""" + + http_error_msg = "" + if isinstance(self.reason, bytes): + # We attempt to decode utf-8 first because some servers + # choose to localize their reason strings. If the string + # isn't utf-8, we fall back to iso-8859-1 for all other + # encodings. (See PR #3538) + try: + reason = self.reason.decode("utf-8") + except UnicodeDecodeError: + reason = self.reason.decode("iso-8859-1") + else: + reason = self.reason + + if 400 <= self.status_code < 500: + http_error_msg = ( + f"{self.status_code} Client Error: {reason} for url: {self.url}" + ) + + elif 500 <= self.status_code < 600: + http_error_msg = ( + f"{self.status_code} Server Error: {reason} for url: {self.url}" + ) + + if http_error_msg: + raise HTTPError(http_error_msg, response=self) + + def close(self): + """Releases the connection back to the pool. Once this method has been + called the underlying ``raw`` object must not be accessed again. + + *Note: Should not normally need to be called explicitly.* + """ + if not self._content_consumed: + self.raw.close() + + release_conn = getattr(self.raw, "release_conn", None) + if release_conn is not None: + release_conn() diff --git a/TTS/Kokoro/.venv/Lib/site-packages/requests/packages.py b/TTS/Kokoro/.venv/Lib/site-packages/requests/packages.py new file mode 100644 index 0000000000000000000000000000000000000000..5ab3d8e250de8475cb22553f564e5444e02c7460 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/requests/packages.py @@ -0,0 +1,23 @@ +import sys + +from .compat import chardet + +# This code exists for backwards compatibility reasons. +# I don't like it either. Just look the other way. :) + +for package in ("urllib3", "idna"): + locals()[package] = __import__(package) + # This traversal is apparently necessary such that the identities are + # preserved (requests.packages.urllib3.* is urllib3.*) + for mod in list(sys.modules): + if mod == package or mod.startswith(f"{package}."): + sys.modules[f"requests.packages.{mod}"] = sys.modules[mod] + +if chardet is not None: + target = chardet.__name__ + for mod in list(sys.modules): + if mod == target or mod.startswith(f"{target}."): + imported_mod = sys.modules[mod] + sys.modules[f"requests.packages.{mod}"] = imported_mod + mod = mod.replace(target, "chardet") + sys.modules[f"requests.packages.{mod}"] = imported_mod diff --git a/TTS/Kokoro/.venv/Lib/site-packages/requests/sessions.py b/TTS/Kokoro/.venv/Lib/site-packages/requests/sessions.py new file mode 100644 index 0000000000000000000000000000000000000000..731550de88aceb59747460faf519c2277e300e87 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/requests/sessions.py @@ -0,0 +1,831 @@ +""" +requests.sessions +~~~~~~~~~~~~~~~~~ + +This module provides a Session object to manage and persist settings across +requests (cookies, auth, proxies). +""" +import os +import sys +import time +from collections import OrderedDict +from datetime import timedelta + +from ._internal_utils import to_native_string +from .adapters import HTTPAdapter +from .auth import _basic_auth_str +from .compat import Mapping, cookielib, urljoin, urlparse +from .cookies import ( + RequestsCookieJar, + cookiejar_from_dict, + extract_cookies_to_jar, + merge_cookies, +) +from .exceptions import ( + ChunkedEncodingError, + ContentDecodingError, + InvalidSchema, + TooManyRedirects, +) +from .hooks import default_hooks, dispatch_hook + +# formerly defined here, reexposed here for backward compatibility +from .models import ( # noqa: F401 + DEFAULT_REDIRECT_LIMIT, + REDIRECT_STATI, + PreparedRequest, + Request, +) +from .status_codes import codes +from .structures import CaseInsensitiveDict +from .utils import ( # noqa: F401 + DEFAULT_PORTS, + default_headers, + get_auth_from_url, + get_environ_proxies, + get_netrc_auth, + requote_uri, + resolve_proxies, + rewind_body, + should_bypass_proxies, + to_key_val_list, +) + +# Preferred clock, based on which one is more accurate on a given system. +if sys.platform == "win32": + preferred_clock = time.perf_counter +else: + preferred_clock = time.time + + +def merge_setting(request_setting, session_setting, dict_class=OrderedDict): + """Determines appropriate setting for a given request, taking into account + the explicit setting on that request, and the setting in the session. If a + setting is a dictionary, they will be merged together using `dict_class` + """ + + if session_setting is None: + return request_setting + + if request_setting is None: + return session_setting + + # Bypass if not a dictionary (e.g. verify) + if not ( + isinstance(session_setting, Mapping) and isinstance(request_setting, Mapping) + ): + return request_setting + + merged_setting = dict_class(to_key_val_list(session_setting)) + merged_setting.update(to_key_val_list(request_setting)) + + # Remove keys that are set to None. Extract keys first to avoid altering + # the dictionary during iteration. + none_keys = [k for (k, v) in merged_setting.items() if v is None] + for key in none_keys: + del merged_setting[key] + + return merged_setting + + +def merge_hooks(request_hooks, session_hooks, dict_class=OrderedDict): + """Properly merges both requests and session hooks. + + This is necessary because when request_hooks == {'response': []}, the + merge breaks Session hooks entirely. + """ + if session_hooks is None or session_hooks.get("response") == []: + return request_hooks + + if request_hooks is None or request_hooks.get("response") == []: + return session_hooks + + return merge_setting(request_hooks, session_hooks, dict_class) + + +class SessionRedirectMixin: + def get_redirect_target(self, resp): + """Receives a Response. Returns a redirect URI or ``None``""" + # Due to the nature of how requests processes redirects this method will + # be called at least once upon the original response and at least twice + # on each subsequent redirect response (if any). + # If a custom mixin is used to handle this logic, it may be advantageous + # to cache the redirect location onto the response object as a private + # attribute. + if resp.is_redirect: + location = resp.headers["location"] + # Currently the underlying http module on py3 decode headers + # in latin1, but empirical evidence suggests that latin1 is very + # rarely used with non-ASCII characters in HTTP headers. + # It is more likely to get UTF8 header rather than latin1. + # This causes incorrect handling of UTF8 encoded location headers. + # To solve this, we re-encode the location in latin1. + location = location.encode("latin1") + return to_native_string(location, "utf8") + return None + + def should_strip_auth(self, old_url, new_url): + """Decide whether Authorization header should be removed when redirecting""" + old_parsed = urlparse(old_url) + new_parsed = urlparse(new_url) + if old_parsed.hostname != new_parsed.hostname: + return True + # Special case: allow http -> https redirect when using the standard + # ports. This isn't specified by RFC 7235, but is kept to avoid + # breaking backwards compatibility with older versions of requests + # that allowed any redirects on the same host. + if ( + old_parsed.scheme == "http" + and old_parsed.port in (80, None) + and new_parsed.scheme == "https" + and new_parsed.port in (443, None) + ): + return False + + # Handle default port usage corresponding to scheme. + changed_port = old_parsed.port != new_parsed.port + changed_scheme = old_parsed.scheme != new_parsed.scheme + default_port = (DEFAULT_PORTS.get(old_parsed.scheme, None), None) + if ( + not changed_scheme + and old_parsed.port in default_port + and new_parsed.port in default_port + ): + return False + + # Standard case: root URI must match + return changed_port or changed_scheme + + def resolve_redirects( + self, + resp, + req, + stream=False, + timeout=None, + verify=True, + cert=None, + proxies=None, + yield_requests=False, + **adapter_kwargs, + ): + """Receives a Response. Returns a generator of Responses or Requests.""" + + hist = [] # keep track of history + + url = self.get_redirect_target(resp) + previous_fragment = urlparse(req.url).fragment + while url: + prepared_request = req.copy() + + # Update history and keep track of redirects. + # resp.history must ignore the original request in this loop + hist.append(resp) + resp.history = hist[1:] + + try: + resp.content # Consume socket so it can be released + except (ChunkedEncodingError, ContentDecodingError, RuntimeError): + resp.raw.read(decode_content=False) + + if len(resp.history) >= self.max_redirects: + raise TooManyRedirects( + f"Exceeded {self.max_redirects} redirects.", response=resp + ) + + # Release the connection back into the pool. + resp.close() + + # Handle redirection without scheme (see: RFC 1808 Section 4) + if url.startswith("//"): + parsed_rurl = urlparse(resp.url) + url = ":".join([to_native_string(parsed_rurl.scheme), url]) + + # Normalize url case and attach previous fragment if needed (RFC 7231 7.1.2) + parsed = urlparse(url) + if parsed.fragment == "" and previous_fragment: + parsed = parsed._replace(fragment=previous_fragment) + elif parsed.fragment: + previous_fragment = parsed.fragment + url = parsed.geturl() + + # Facilitate relative 'location' headers, as allowed by RFC 7231. + # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource') + # Compliant with RFC3986, we percent encode the url. + if not parsed.netloc: + url = urljoin(resp.url, requote_uri(url)) + else: + url = requote_uri(url) + + prepared_request.url = to_native_string(url) + + self.rebuild_method(prepared_request, resp) + + # https://github.com/psf/requests/issues/1084 + if resp.status_code not in ( + codes.temporary_redirect, + codes.permanent_redirect, + ): + # https://github.com/psf/requests/issues/3490 + purged_headers = ("Content-Length", "Content-Type", "Transfer-Encoding") + for header in purged_headers: + prepared_request.headers.pop(header, None) + prepared_request.body = None + + headers = prepared_request.headers + headers.pop("Cookie", None) + + # Extract any cookies sent on the response to the cookiejar + # in the new request. Because we've mutated our copied prepared + # request, use the old one that we haven't yet touched. + extract_cookies_to_jar(prepared_request._cookies, req, resp.raw) + merge_cookies(prepared_request._cookies, self.cookies) + prepared_request.prepare_cookies(prepared_request._cookies) + + # Rebuild auth and proxy information. + proxies = self.rebuild_proxies(prepared_request, proxies) + self.rebuild_auth(prepared_request, resp) + + # A failed tell() sets `_body_position` to `object()`. This non-None + # value ensures `rewindable` will be True, allowing us to raise an + # UnrewindableBodyError, instead of hanging the connection. + rewindable = prepared_request._body_position is not None and ( + "Content-Length" in headers or "Transfer-Encoding" in headers + ) + + # Attempt to rewind consumed file-like object. + if rewindable: + rewind_body(prepared_request) + + # Override the original request. + req = prepared_request + + if yield_requests: + yield req + else: + resp = self.send( + req, + stream=stream, + timeout=timeout, + verify=verify, + cert=cert, + proxies=proxies, + allow_redirects=False, + **adapter_kwargs, + ) + + extract_cookies_to_jar(self.cookies, prepared_request, resp.raw) + + # extract redirect url, if any, for the next loop + url = self.get_redirect_target(resp) + yield resp + + def rebuild_auth(self, prepared_request, response): + """When being redirected we may want to strip authentication from the + request to avoid leaking credentials. This method intelligently removes + and reapplies authentication where possible to avoid credential loss. + """ + headers = prepared_request.headers + url = prepared_request.url + + if "Authorization" in headers and self.should_strip_auth( + response.request.url, url + ): + # If we get redirected to a new host, we should strip out any + # authentication headers. + del headers["Authorization"] + + # .netrc might have more auth for us on our new host. + new_auth = get_netrc_auth(url) if self.trust_env else None + if new_auth is not None: + prepared_request.prepare_auth(new_auth) + + def rebuild_proxies(self, prepared_request, proxies): + """This method re-evaluates the proxy configuration by considering the + environment variables. If we are redirected to a URL covered by + NO_PROXY, we strip the proxy configuration. Otherwise, we set missing + proxy keys for this URL (in case they were stripped by a previous + redirect). + + This method also replaces the Proxy-Authorization header where + necessary. + + :rtype: dict + """ + headers = prepared_request.headers + scheme = urlparse(prepared_request.url).scheme + new_proxies = resolve_proxies(prepared_request, proxies, self.trust_env) + + if "Proxy-Authorization" in headers: + del headers["Proxy-Authorization"] + + try: + username, password = get_auth_from_url(new_proxies[scheme]) + except KeyError: + username, password = None, None + + # urllib3 handles proxy authorization for us in the standard adapter. + # Avoid appending this to TLS tunneled requests where it may be leaked. + if not scheme.startswith("https") and username and password: + headers["Proxy-Authorization"] = _basic_auth_str(username, password) + + return new_proxies + + def rebuild_method(self, prepared_request, response): + """When being redirected we may want to change the method of the request + based on certain specs or browser behavior. + """ + method = prepared_request.method + + # https://tools.ietf.org/html/rfc7231#section-6.4.4 + if response.status_code == codes.see_other and method != "HEAD": + method = "GET" + + # Do what the browsers do, despite standards... + # First, turn 302s into GETs. + if response.status_code == codes.found and method != "HEAD": + method = "GET" + + # Second, if a POST is responded to with a 301, turn it into a GET. + # This bizarre behaviour is explained in Issue 1704. + if response.status_code == codes.moved and method == "POST": + method = "GET" + + prepared_request.method = method + + +class Session(SessionRedirectMixin): + """A Requests session. + + Provides cookie persistence, connection-pooling, and configuration. + + Basic Usage:: + + >>> import requests + >>> s = requests.Session() + >>> s.get('https://httpbin.org/get') + + + Or as a context manager:: + + >>> with requests.Session() as s: + ... s.get('https://httpbin.org/get') + + """ + + __attrs__ = [ + "headers", + "cookies", + "auth", + "proxies", + "hooks", + "params", + "verify", + "cert", + "adapters", + "stream", + "trust_env", + "max_redirects", + ] + + def __init__(self): + #: A case-insensitive dictionary of headers to be sent on each + #: :class:`Request ` sent from this + #: :class:`Session `. + self.headers = default_headers() + + #: Default Authentication tuple or object to attach to + #: :class:`Request `. + self.auth = None + + #: Dictionary mapping protocol or protocol and host to the URL of the proxy + #: (e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}) to + #: be used on each :class:`Request `. + self.proxies = {} + + #: Event-handling hooks. + self.hooks = default_hooks() + + #: Dictionary of querystring data to attach to each + #: :class:`Request `. The dictionary values may be lists for + #: representing multivalued query parameters. + self.params = {} + + #: Stream response content default. + self.stream = False + + #: SSL Verification default. + #: Defaults to `True`, requiring requests to verify the TLS certificate at the + #: remote end. + #: If verify is set to `False`, requests will accept any TLS certificate + #: presented by the server, and will ignore hostname mismatches and/or + #: expired certificates, which will make your application vulnerable to + #: man-in-the-middle (MitM) attacks. + #: Only set this to `False` for testing. + self.verify = True + + #: SSL client certificate default, if String, path to ssl client + #: cert file (.pem). If Tuple, ('cert', 'key') pair. + self.cert = None + + #: Maximum number of redirects allowed. If the request exceeds this + #: limit, a :class:`TooManyRedirects` exception is raised. + #: This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is + #: 30. + self.max_redirects = DEFAULT_REDIRECT_LIMIT + + #: Trust environment settings for proxy configuration, default + #: authentication and similar. + self.trust_env = True + + #: A CookieJar containing all currently outstanding cookies set on this + #: session. By default it is a + #: :class:`RequestsCookieJar `, but + #: may be any other ``cookielib.CookieJar`` compatible object. + self.cookies = cookiejar_from_dict({}) + + # Default connection adapters. + self.adapters = OrderedDict() + self.mount("https://", HTTPAdapter()) + self.mount("http://", HTTPAdapter()) + + def __enter__(self): + return self + + def __exit__(self, *args): + self.close() + + def prepare_request(self, request): + """Constructs a :class:`PreparedRequest ` for + transmission and returns it. The :class:`PreparedRequest` has settings + merged from the :class:`Request ` instance and those of the + :class:`Session`. + + :param request: :class:`Request` instance to prepare with this + session's settings. + :rtype: requests.PreparedRequest + """ + cookies = request.cookies or {} + + # Bootstrap CookieJar. + if not isinstance(cookies, cookielib.CookieJar): + cookies = cookiejar_from_dict(cookies) + + # Merge with session cookies + merged_cookies = merge_cookies( + merge_cookies(RequestsCookieJar(), self.cookies), cookies + ) + + # Set environment's basic authentication if not explicitly set. + auth = request.auth + if self.trust_env and not auth and not self.auth: + auth = get_netrc_auth(request.url) + + p = PreparedRequest() + p.prepare( + method=request.method.upper(), + url=request.url, + files=request.files, + data=request.data, + json=request.json, + headers=merge_setting( + request.headers, self.headers, dict_class=CaseInsensitiveDict + ), + params=merge_setting(request.params, self.params), + auth=merge_setting(auth, self.auth), + cookies=merged_cookies, + hooks=merge_hooks(request.hooks, self.hooks), + ) + return p + + def request( + self, + method, + url, + params=None, + data=None, + headers=None, + cookies=None, + files=None, + auth=None, + timeout=None, + allow_redirects=True, + proxies=None, + hooks=None, + stream=None, + verify=None, + cert=None, + json=None, + ): + """Constructs a :class:`Request `, prepares it and sends it. + Returns :class:`Response ` object. + + :param method: method for the new :class:`Request` object. + :param url: URL for the new :class:`Request` object. + :param params: (optional) Dictionary or bytes to be sent in the query + string for the :class:`Request`. + :param data: (optional) Dictionary, list of tuples, bytes, or file-like + object to send in the body of the :class:`Request`. + :param json: (optional) json to send in the body of the + :class:`Request`. + :param headers: (optional) Dictionary of HTTP Headers to send with the + :class:`Request`. + :param cookies: (optional) Dict or CookieJar object to send with the + :class:`Request`. + :param files: (optional) Dictionary of ``'filename': file-like-objects`` + for multipart encoding upload. + :param auth: (optional) Auth tuple or callable to enable + Basic/Digest/Custom HTTP Auth. + :param timeout: (optional) How many seconds to wait for the server to send + data before giving up, as a float, or a :ref:`(connect timeout, + read timeout) ` tuple. + :type timeout: float or tuple + :param allow_redirects: (optional) Set to True by default. + :type allow_redirects: bool + :param proxies: (optional) Dictionary mapping protocol or protocol and + hostname to the URL of the proxy. + :param hooks: (optional) Dictionary mapping hook name to one event or + list of events, event must be callable. + :param stream: (optional) whether to immediately download the response + content. Defaults to ``False``. + :param verify: (optional) Either a boolean, in which case it controls whether we verify + the server's TLS certificate, or a string, in which case it must be a path + to a CA bundle to use. Defaults to ``True``. When set to + ``False``, requests will accept any TLS certificate presented by + the server, and will ignore hostname mismatches and/or expired + certificates, which will make your application vulnerable to + man-in-the-middle (MitM) attacks. Setting verify to ``False`` + may be useful during local development or testing. + :param cert: (optional) if String, path to ssl client cert file (.pem). + If Tuple, ('cert', 'key') pair. + :rtype: requests.Response + """ + # Create the Request. + req = Request( + method=method.upper(), + url=url, + headers=headers, + files=files, + data=data or {}, + json=json, + params=params or {}, + auth=auth, + cookies=cookies, + hooks=hooks, + ) + prep = self.prepare_request(req) + + proxies = proxies or {} + + settings = self.merge_environment_settings( + prep.url, proxies, stream, verify, cert + ) + + # Send the request. + send_kwargs = { + "timeout": timeout, + "allow_redirects": allow_redirects, + } + send_kwargs.update(settings) + resp = self.send(prep, **send_kwargs) + + return resp + + def get(self, url, **kwargs): + r"""Sends a GET request. Returns :class:`Response` object. + + :param url: URL for the new :class:`Request` object. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :rtype: requests.Response + """ + + kwargs.setdefault("allow_redirects", True) + return self.request("GET", url, **kwargs) + + def options(self, url, **kwargs): + r"""Sends a OPTIONS request. Returns :class:`Response` object. + + :param url: URL for the new :class:`Request` object. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :rtype: requests.Response + """ + + kwargs.setdefault("allow_redirects", True) + return self.request("OPTIONS", url, **kwargs) + + def head(self, url, **kwargs): + r"""Sends a HEAD request. Returns :class:`Response` object. + + :param url: URL for the new :class:`Request` object. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :rtype: requests.Response + """ + + kwargs.setdefault("allow_redirects", False) + return self.request("HEAD", url, **kwargs) + + def post(self, url, data=None, json=None, **kwargs): + r"""Sends a POST request. Returns :class:`Response` object. + + :param url: URL for the new :class:`Request` object. + :param data: (optional) Dictionary, list of tuples, bytes, or file-like + object to send in the body of the :class:`Request`. + :param json: (optional) json to send in the body of the :class:`Request`. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :rtype: requests.Response + """ + + return self.request("POST", url, data=data, json=json, **kwargs) + + def put(self, url, data=None, **kwargs): + r"""Sends a PUT request. Returns :class:`Response` object. + + :param url: URL for the new :class:`Request` object. + :param data: (optional) Dictionary, list of tuples, bytes, or file-like + object to send in the body of the :class:`Request`. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :rtype: requests.Response + """ + + return self.request("PUT", url, data=data, **kwargs) + + def patch(self, url, data=None, **kwargs): + r"""Sends a PATCH request. Returns :class:`Response` object. + + :param url: URL for the new :class:`Request` object. + :param data: (optional) Dictionary, list of tuples, bytes, or file-like + object to send in the body of the :class:`Request`. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :rtype: requests.Response + """ + + return self.request("PATCH", url, data=data, **kwargs) + + def delete(self, url, **kwargs): + r"""Sends a DELETE request. Returns :class:`Response` object. + + :param url: URL for the new :class:`Request` object. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :rtype: requests.Response + """ + + return self.request("DELETE", url, **kwargs) + + def send(self, request, **kwargs): + """Send a given PreparedRequest. + + :rtype: requests.Response + """ + # Set defaults that the hooks can utilize to ensure they always have + # the correct parameters to reproduce the previous request. + kwargs.setdefault("stream", self.stream) + kwargs.setdefault("verify", self.verify) + kwargs.setdefault("cert", self.cert) + if "proxies" not in kwargs: + kwargs["proxies"] = resolve_proxies(request, self.proxies, self.trust_env) + + # It's possible that users might accidentally send a Request object. + # Guard against that specific failure case. + if isinstance(request, Request): + raise ValueError("You can only send PreparedRequests.") + + # Set up variables needed for resolve_redirects and dispatching of hooks + allow_redirects = kwargs.pop("allow_redirects", True) + stream = kwargs.get("stream") + hooks = request.hooks + + # Get the appropriate adapter to use + adapter = self.get_adapter(url=request.url) + + # Start time (approximately) of the request + start = preferred_clock() + + # Send the request + r = adapter.send(request, **kwargs) + + # Total elapsed time of the request (approximately) + elapsed = preferred_clock() - start + r.elapsed = timedelta(seconds=elapsed) + + # Response manipulation hooks + r = dispatch_hook("response", hooks, r, **kwargs) + + # Persist cookies + if r.history: + # If the hooks create history then we want those cookies too + for resp in r.history: + extract_cookies_to_jar(self.cookies, resp.request, resp.raw) + + extract_cookies_to_jar(self.cookies, request, r.raw) + + # Resolve redirects if allowed. + if allow_redirects: + # Redirect resolving generator. + gen = self.resolve_redirects(r, request, **kwargs) + history = [resp for resp in gen] + else: + history = [] + + # Shuffle things around if there's history. + if history: + # Insert the first (original) request at the start + history.insert(0, r) + # Get the last request made + r = history.pop() + r.history = history + + # If redirects aren't being followed, store the response on the Request for Response.next(). + if not allow_redirects: + try: + r._next = next( + self.resolve_redirects(r, request, yield_requests=True, **kwargs) + ) + except StopIteration: + pass + + if not stream: + r.content + + return r + + def merge_environment_settings(self, url, proxies, stream, verify, cert): + """ + Check the environment and merge it with some settings. + + :rtype: dict + """ + # Gather clues from the surrounding environment. + if self.trust_env: + # Set environment's proxies. + no_proxy = proxies.get("no_proxy") if proxies is not None else None + env_proxies = get_environ_proxies(url, no_proxy=no_proxy) + for k, v in env_proxies.items(): + proxies.setdefault(k, v) + + # Look for requests environment configuration + # and be compatible with cURL. + if verify is True or verify is None: + verify = ( + os.environ.get("REQUESTS_CA_BUNDLE") + or os.environ.get("CURL_CA_BUNDLE") + or verify + ) + + # Merge all the kwargs. + proxies = merge_setting(proxies, self.proxies) + stream = merge_setting(stream, self.stream) + verify = merge_setting(verify, self.verify) + cert = merge_setting(cert, self.cert) + + return {"proxies": proxies, "stream": stream, "verify": verify, "cert": cert} + + def get_adapter(self, url): + """ + Returns the appropriate connection adapter for the given URL. + + :rtype: requests.adapters.BaseAdapter + """ + for prefix, adapter in self.adapters.items(): + if url.lower().startswith(prefix.lower()): + return adapter + + # Nothing matches :-/ + raise InvalidSchema(f"No connection adapters were found for {url!r}") + + def close(self): + """Closes all adapters and as such the session""" + for v in self.adapters.values(): + v.close() + + def mount(self, prefix, adapter): + """Registers a connection adapter to a prefix. + + Adapters are sorted in descending order by prefix length. + """ + self.adapters[prefix] = adapter + keys_to_move = [k for k in self.adapters if len(k) < len(prefix)] + + for key in keys_to_move: + self.adapters[key] = self.adapters.pop(key) + + def __getstate__(self): + state = {attr: getattr(self, attr, None) for attr in self.__attrs__} + return state + + def __setstate__(self, state): + for attr, value in state.items(): + setattr(self, attr, value) + + +def session(): + """ + Returns a :class:`Session` for context-management. + + .. deprecated:: 1.0.0 + + This method has been deprecated since version 1.0.0 and is only kept for + backwards compatibility. New code should use :class:`~requests.sessions.Session` + to create a session. This may be removed at a future date. + + :rtype: Session + """ + return Session() diff --git a/TTS/Kokoro/.venv/Lib/site-packages/requests/status_codes.py b/TTS/Kokoro/.venv/Lib/site-packages/requests/status_codes.py new file mode 100644 index 0000000000000000000000000000000000000000..c7945a2f06897ed980cc575df2f48d9e6c1a9f7e --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/requests/status_codes.py @@ -0,0 +1,128 @@ +r""" +The ``codes`` object defines a mapping from common names for HTTP statuses +to their numerical codes, accessible either as attributes or as dictionary +items. + +Example:: + + >>> import requests + >>> requests.codes['temporary_redirect'] + 307 + >>> requests.codes.teapot + 418 + >>> requests.codes['\o/'] + 200 + +Some codes have multiple names, and both upper- and lower-case versions of +the names are allowed. For example, ``codes.ok``, ``codes.OK``, and +``codes.okay`` all correspond to the HTTP status code 200. +""" + +from .structures import LookupDict + +_codes = { + # Informational. + 100: ("continue",), + 101: ("switching_protocols",), + 102: ("processing", "early-hints"), + 103: ("checkpoint",), + 122: ("uri_too_long", "request_uri_too_long"), + 200: ("ok", "okay", "all_ok", "all_okay", "all_good", "\\o/", "✓"), + 201: ("created",), + 202: ("accepted",), + 203: ("non_authoritative_info", "non_authoritative_information"), + 204: ("no_content",), + 205: ("reset_content", "reset"), + 206: ("partial_content", "partial"), + 207: ("multi_status", "multiple_status", "multi_stati", "multiple_stati"), + 208: ("already_reported",), + 226: ("im_used",), + # Redirection. + 300: ("multiple_choices",), + 301: ("moved_permanently", "moved", "\\o-"), + 302: ("found",), + 303: ("see_other", "other"), + 304: ("not_modified",), + 305: ("use_proxy",), + 306: ("switch_proxy",), + 307: ("temporary_redirect", "temporary_moved", "temporary"), + 308: ( + "permanent_redirect", + "resume_incomplete", + "resume", + ), # "resume" and "resume_incomplete" to be removed in 3.0 + # Client Error. + 400: ("bad_request", "bad"), + 401: ("unauthorized",), + 402: ("payment_required", "payment"), + 403: ("forbidden",), + 404: ("not_found", "-o-"), + 405: ("method_not_allowed", "not_allowed"), + 406: ("not_acceptable",), + 407: ("proxy_authentication_required", "proxy_auth", "proxy_authentication"), + 408: ("request_timeout", "timeout"), + 409: ("conflict",), + 410: ("gone",), + 411: ("length_required",), + 412: ("precondition_failed", "precondition"), + 413: ("request_entity_too_large", "content_too_large"), + 414: ("request_uri_too_large", "uri_too_long"), + 415: ("unsupported_media_type", "unsupported_media", "media_type"), + 416: ( + "requested_range_not_satisfiable", + "requested_range", + "range_not_satisfiable", + ), + 417: ("expectation_failed",), + 418: ("im_a_teapot", "teapot", "i_am_a_teapot"), + 421: ("misdirected_request",), + 422: ("unprocessable_entity", "unprocessable", "unprocessable_content"), + 423: ("locked",), + 424: ("failed_dependency", "dependency"), + 425: ("unordered_collection", "unordered", "too_early"), + 426: ("upgrade_required", "upgrade"), + 428: ("precondition_required", "precondition"), + 429: ("too_many_requests", "too_many"), + 431: ("header_fields_too_large", "fields_too_large"), + 444: ("no_response", "none"), + 449: ("retry_with", "retry"), + 450: ("blocked_by_windows_parental_controls", "parental_controls"), + 451: ("unavailable_for_legal_reasons", "legal_reasons"), + 499: ("client_closed_request",), + # Server Error. + 500: ("internal_server_error", "server_error", "/o\\", "✗"), + 501: ("not_implemented",), + 502: ("bad_gateway",), + 503: ("service_unavailable", "unavailable"), + 504: ("gateway_timeout",), + 505: ("http_version_not_supported", "http_version"), + 506: ("variant_also_negotiates",), + 507: ("insufficient_storage",), + 509: ("bandwidth_limit_exceeded", "bandwidth"), + 510: ("not_extended",), + 511: ("network_authentication_required", "network_auth", "network_authentication"), +} + +codes = LookupDict(name="status_codes") + + +def _init(): + for code, titles in _codes.items(): + for title in titles: + setattr(codes, title, code) + if not title.startswith(("\\", "/")): + setattr(codes, title.upper(), code) + + def doc(code): + names = ", ".join(f"``{n}``" for n in _codes[code]) + return "* %d: %s" % (code, names) + + global __doc__ + __doc__ = ( + __doc__ + "\n" + "\n".join(doc(code) for code in sorted(_codes)) + if __doc__ is not None + else None + ) + + +_init() diff --git a/TTS/Kokoro/.venv/Lib/site-packages/requests/structures.py b/TTS/Kokoro/.venv/Lib/site-packages/requests/structures.py new file mode 100644 index 0000000000000000000000000000000000000000..188e13e4829591facb23ae0e2eda84b9807cb818 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/requests/structures.py @@ -0,0 +1,99 @@ +""" +requests.structures +~~~~~~~~~~~~~~~~~~~ + +Data structures that power Requests. +""" + +from collections import OrderedDict + +from .compat import Mapping, MutableMapping + + +class CaseInsensitiveDict(MutableMapping): + """A case-insensitive ``dict``-like object. + + Implements all methods and operations of + ``MutableMapping`` as well as dict's ``copy``. Also + provides ``lower_items``. + + All keys are expected to be strings. The structure remembers the + case of the last key to be set, and ``iter(instance)``, + ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()`` + will contain case-sensitive keys. However, querying and contains + testing is case insensitive:: + + cid = CaseInsensitiveDict() + cid['Accept'] = 'application/json' + cid['aCCEPT'] == 'application/json' # True + list(cid) == ['Accept'] # True + + For example, ``headers['content-encoding']`` will return the + value of a ``'Content-Encoding'`` response header, regardless + of how the header name was originally stored. + + If the constructor, ``.update``, or equality comparison + operations are given keys that have equal ``.lower()``s, the + behavior is undefined. + """ + + def __init__(self, data=None, **kwargs): + self._store = OrderedDict() + if data is None: + data = {} + self.update(data, **kwargs) + + def __setitem__(self, key, value): + # Use the lowercased key for lookups, but store the actual + # key alongside the value. + self._store[key.lower()] = (key, value) + + def __getitem__(self, key): + return self._store[key.lower()][1] + + def __delitem__(self, key): + del self._store[key.lower()] + + def __iter__(self): + return (casedkey for casedkey, mappedvalue in self._store.values()) + + def __len__(self): + return len(self._store) + + def lower_items(self): + """Like iteritems(), but with all lowercase keys.""" + return ((lowerkey, keyval[1]) for (lowerkey, keyval) in self._store.items()) + + def __eq__(self, other): + if isinstance(other, Mapping): + other = CaseInsensitiveDict(other) + else: + return NotImplemented + # Compare insensitively + return dict(self.lower_items()) == dict(other.lower_items()) + + # Copy is required + def copy(self): + return CaseInsensitiveDict(self._store.values()) + + def __repr__(self): + return str(dict(self.items())) + + +class LookupDict(dict): + """Dictionary lookup object.""" + + def __init__(self, name=None): + self.name = name + super().__init__() + + def __repr__(self): + return f"" + + def __getitem__(self, key): + # We allow fall-through here, so values default to None + + return self.__dict__.get(key, None) + + def get(self, key, default=None): + return self.__dict__.get(key, default) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/requests/utils.py b/TTS/Kokoro/.venv/Lib/site-packages/requests/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..8ab55852cc2188c53f08462ec4319c97fa49f04b --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/requests/utils.py @@ -0,0 +1,1086 @@ +""" +requests.utils +~~~~~~~~~~~~~~ + +This module provides utility functions that are used within Requests +that are also useful for external consumption. +""" + +import codecs +import contextlib +import io +import os +import re +import socket +import struct +import sys +import tempfile +import warnings +import zipfile +from collections import OrderedDict + +from urllib3.util import make_headers, parse_url + +from . import certs +from .__version__ import __version__ + +# to_native_string is unused here, but imported here for backwards compatibility +from ._internal_utils import ( # noqa: F401 + _HEADER_VALIDATORS_BYTE, + _HEADER_VALIDATORS_STR, + HEADER_VALIDATORS, + to_native_string, +) +from .compat import ( + Mapping, + basestring, + bytes, + getproxies, + getproxies_environment, + integer_types, + is_urllib3_1, +) +from .compat import parse_http_list as _parse_list_header +from .compat import ( + proxy_bypass, + proxy_bypass_environment, + quote, + str, + unquote, + urlparse, + urlunparse, +) +from .cookies import cookiejar_from_dict +from .exceptions import ( + FileModeWarning, + InvalidHeader, + InvalidURL, + UnrewindableBodyError, +) +from .structures import CaseInsensitiveDict + +NETRC_FILES = (".netrc", "_netrc") + +DEFAULT_CA_BUNDLE_PATH = certs.where() + +DEFAULT_PORTS = {"http": 80, "https": 443} + +# Ensure that ', ' is used to preserve previous delimiter behavior. +DEFAULT_ACCEPT_ENCODING = ", ".join( + re.split(r",\s*", make_headers(accept_encoding=True)["accept-encoding"]) +) + + +if sys.platform == "win32": + # provide a proxy_bypass version on Windows without DNS lookups + + def proxy_bypass_registry(host): + try: + import winreg + except ImportError: + return False + + try: + internetSettings = winreg.OpenKey( + winreg.HKEY_CURRENT_USER, + r"Software\Microsoft\Windows\CurrentVersion\Internet Settings", + ) + # ProxyEnable could be REG_SZ or REG_DWORD, normalizing it + proxyEnable = int(winreg.QueryValueEx(internetSettings, "ProxyEnable")[0]) + # ProxyOverride is almost always a string + proxyOverride = winreg.QueryValueEx(internetSettings, "ProxyOverride")[0] + except (OSError, ValueError): + return False + if not proxyEnable or not proxyOverride: + return False + + # make a check value list from the registry entry: replace the + # '' string by the localhost entry and the corresponding + # canonical entry. + proxyOverride = proxyOverride.split(";") + # filter out empty strings to avoid re.match return true in the following code. + proxyOverride = filter(None, proxyOverride) + # now check if we match one of the registry values. + for test in proxyOverride: + if test == "": + if "." not in host: + return True + test = test.replace(".", r"\.") # mask dots + test = test.replace("*", r".*") # change glob sequence + test = test.replace("?", r".") # change glob char + if re.match(test, host, re.I): + return True + return False + + def proxy_bypass(host): # noqa + """Return True, if the host should be bypassed. + + Checks proxy settings gathered from the environment, if specified, + or the registry. + """ + if getproxies_environment(): + return proxy_bypass_environment(host) + else: + return proxy_bypass_registry(host) + + +def dict_to_sequence(d): + """Returns an internal sequence dictionary update.""" + + if hasattr(d, "items"): + d = d.items() + + return d + + +def super_len(o): + total_length = None + current_position = 0 + + if not is_urllib3_1 and isinstance(o, str): + # urllib3 2.x+ treats all strings as utf-8 instead + # of latin-1 (iso-8859-1) like http.client. + o = o.encode("utf-8") + + if hasattr(o, "__len__"): + total_length = len(o) + + elif hasattr(o, "len"): + total_length = o.len + + elif hasattr(o, "fileno"): + try: + fileno = o.fileno() + except (io.UnsupportedOperation, AttributeError): + # AttributeError is a surprising exception, seeing as how we've just checked + # that `hasattr(o, 'fileno')`. It happens for objects obtained via + # `Tarfile.extractfile()`, per issue 5229. + pass + else: + total_length = os.fstat(fileno).st_size + + # Having used fstat to determine the file length, we need to + # confirm that this file was opened up in binary mode. + if "b" not in o.mode: + warnings.warn( + ( + "Requests has determined the content-length for this " + "request using the binary size of the file: however, the " + "file has been opened in text mode (i.e. without the 'b' " + "flag in the mode). This may lead to an incorrect " + "content-length. In Requests 3.0, support will be removed " + "for files in text mode." + ), + FileModeWarning, + ) + + if hasattr(o, "tell"): + try: + current_position = o.tell() + except OSError: + # This can happen in some weird situations, such as when the file + # is actually a special file descriptor like stdin. In this + # instance, we don't know what the length is, so set it to zero and + # let requests chunk it instead. + if total_length is not None: + current_position = total_length + else: + if hasattr(o, "seek") and total_length is None: + # StringIO and BytesIO have seek but no usable fileno + try: + # seek to end of file + o.seek(0, 2) + total_length = o.tell() + + # seek back to current position to support + # partially read file-like objects + o.seek(current_position or 0) + except OSError: + total_length = 0 + + if total_length is None: + total_length = 0 + + return max(0, total_length - current_position) + + +def get_netrc_auth(url, raise_errors=False): + """Returns the Requests tuple auth for a given url from netrc.""" + + netrc_file = os.environ.get("NETRC") + if netrc_file is not None: + netrc_locations = (netrc_file,) + else: + netrc_locations = (f"~/{f}" for f in NETRC_FILES) + + try: + from netrc import NetrcParseError, netrc + + netrc_path = None + + for f in netrc_locations: + loc = os.path.expanduser(f) + if os.path.exists(loc): + netrc_path = loc + break + + # Abort early if there isn't one. + if netrc_path is None: + return + + ri = urlparse(url) + host = ri.hostname + + try: + _netrc = netrc(netrc_path).authenticators(host) + if _netrc: + # Return with login / password + login_i = 0 if _netrc[0] else 1 + return (_netrc[login_i], _netrc[2]) + except (NetrcParseError, OSError): + # If there was a parsing error or a permissions issue reading the file, + # we'll just skip netrc auth unless explicitly asked to raise errors. + if raise_errors: + raise + + # App Engine hackiness. + except (ImportError, AttributeError): + pass + + +def guess_filename(obj): + """Tries to guess the filename of the given object.""" + name = getattr(obj, "name", None) + if name and isinstance(name, basestring) and name[0] != "<" and name[-1] != ">": + return os.path.basename(name) + + +def extract_zipped_paths(path): + """Replace nonexistent paths that look like they refer to a member of a zip + archive with the location of an extracted copy of the target, or else + just return the provided path unchanged. + """ + if os.path.exists(path): + # this is already a valid path, no need to do anything further + return path + + # find the first valid part of the provided path and treat that as a zip archive + # assume the rest of the path is the name of a member in the archive + archive, member = os.path.split(path) + while archive and not os.path.exists(archive): + archive, prefix = os.path.split(archive) + if not prefix: + # If we don't check for an empty prefix after the split (in other words, archive remains unchanged after the split), + # we _can_ end up in an infinite loop on a rare corner case affecting a small number of users + break + member = "/".join([prefix, member]) + + if not zipfile.is_zipfile(archive): + return path + + zip_file = zipfile.ZipFile(archive) + if member not in zip_file.namelist(): + return path + + # we have a valid zip archive and a valid member of that archive + tmp = tempfile.gettempdir() + extracted_path = os.path.join(tmp, member.split("/")[-1]) + if not os.path.exists(extracted_path): + # use read + write to avoid the creating nested folders, we only want the file, avoids mkdir racing condition + with atomic_open(extracted_path) as file_handler: + file_handler.write(zip_file.read(member)) + return extracted_path + + +@contextlib.contextmanager +def atomic_open(filename): + """Write a file to the disk in an atomic fashion""" + tmp_descriptor, tmp_name = tempfile.mkstemp(dir=os.path.dirname(filename)) + try: + with os.fdopen(tmp_descriptor, "wb") as tmp_handler: + yield tmp_handler + os.replace(tmp_name, filename) + except BaseException: + os.remove(tmp_name) + raise + + +def from_key_val_list(value): + """Take an object and test to see if it can be represented as a + dictionary. Unless it can not be represented as such, return an + OrderedDict, e.g., + + :: + + >>> from_key_val_list([('key', 'val')]) + OrderedDict([('key', 'val')]) + >>> from_key_val_list('string') + Traceback (most recent call last): + ... + ValueError: cannot encode objects that are not 2-tuples + >>> from_key_val_list({'key': 'val'}) + OrderedDict([('key', 'val')]) + + :rtype: OrderedDict + """ + if value is None: + return None + + if isinstance(value, (str, bytes, bool, int)): + raise ValueError("cannot encode objects that are not 2-tuples") + + return OrderedDict(value) + + +def to_key_val_list(value): + """Take an object and test to see if it can be represented as a + dictionary. If it can be, return a list of tuples, e.g., + + :: + + >>> to_key_val_list([('key', 'val')]) + [('key', 'val')] + >>> to_key_val_list({'key': 'val'}) + [('key', 'val')] + >>> to_key_val_list('string') + Traceback (most recent call last): + ... + ValueError: cannot encode objects that are not 2-tuples + + :rtype: list + """ + if value is None: + return None + + if isinstance(value, (str, bytes, bool, int)): + raise ValueError("cannot encode objects that are not 2-tuples") + + if isinstance(value, Mapping): + value = value.items() + + return list(value) + + +# From mitsuhiko/werkzeug (used with permission). +def parse_list_header(value): + """Parse lists as described by RFC 2068 Section 2. + + In particular, parse comma-separated lists where the elements of + the list may include quoted-strings. A quoted-string could + contain a comma. A non-quoted string could have quotes in the + middle. Quotes are removed automatically after parsing. + + It basically works like :func:`parse_set_header` just that items + may appear multiple times and case sensitivity is preserved. + + The return value is a standard :class:`list`: + + >>> parse_list_header('token, "quoted value"') + ['token', 'quoted value'] + + To create a header from the :class:`list` again, use the + :func:`dump_header` function. + + :param value: a string with a list header. + :return: :class:`list` + :rtype: list + """ + result = [] + for item in _parse_list_header(value): + if item[:1] == item[-1:] == '"': + item = unquote_header_value(item[1:-1]) + result.append(item) + return result + + +# From mitsuhiko/werkzeug (used with permission). +def parse_dict_header(value): + """Parse lists of key, value pairs as described by RFC 2068 Section 2 and + convert them into a python dict: + + >>> d = parse_dict_header('foo="is a fish", bar="as well"') + >>> type(d) is dict + True + >>> sorted(d.items()) + [('bar', 'as well'), ('foo', 'is a fish')] + + If there is no value for a key it will be `None`: + + >>> parse_dict_header('key_without_value') + {'key_without_value': None} + + To create a header from the :class:`dict` again, use the + :func:`dump_header` function. + + :param value: a string with a dict header. + :return: :class:`dict` + :rtype: dict + """ + result = {} + for item in _parse_list_header(value): + if "=" not in item: + result[item] = None + continue + name, value = item.split("=", 1) + if value[:1] == value[-1:] == '"': + value = unquote_header_value(value[1:-1]) + result[name] = value + return result + + +# From mitsuhiko/werkzeug (used with permission). +def unquote_header_value(value, is_filename=False): + r"""Unquotes a header value. (Reversal of :func:`quote_header_value`). + This does not use the real unquoting but what browsers are actually + using for quoting. + + :param value: the header value to unquote. + :rtype: str + """ + if value and value[0] == value[-1] == '"': + # this is not the real unquoting, but fixing this so that the + # RFC is met will result in bugs with internet explorer and + # probably some other browsers as well. IE for example is + # uploading files with "C:\foo\bar.txt" as filename + value = value[1:-1] + + # if this is a filename and the starting characters look like + # a UNC path, then just return the value without quotes. Using the + # replace sequence below on a UNC path has the effect of turning + # the leading double slash into a single slash and then + # _fix_ie_filename() doesn't work correctly. See #458. + if not is_filename or value[:2] != "\\\\": + return value.replace("\\\\", "\\").replace('\\"', '"') + return value + + +def dict_from_cookiejar(cj): + """Returns a key/value dictionary from a CookieJar. + + :param cj: CookieJar object to extract cookies from. + :rtype: dict + """ + + cookie_dict = {cookie.name: cookie.value for cookie in cj} + return cookie_dict + + +def add_dict_to_cookiejar(cj, cookie_dict): + """Returns a CookieJar from a key/value dictionary. + + :param cj: CookieJar to insert cookies into. + :param cookie_dict: Dict of key/values to insert into CookieJar. + :rtype: CookieJar + """ + + return cookiejar_from_dict(cookie_dict, cj) + + +def get_encodings_from_content(content): + """Returns encodings from given content string. + + :param content: bytestring to extract encodings from. + """ + warnings.warn( + ( + "In requests 3.0, get_encodings_from_content will be removed. For " + "more information, please see the discussion on issue #2266. (This" + " warning should only appear once.)" + ), + DeprecationWarning, + ) + + charset_re = re.compile(r']', flags=re.I) + pragma_re = re.compile(r']', flags=re.I) + xml_re = re.compile(r'^<\?xml.*?encoding=["\']*(.+?)["\'>]') + + return ( + charset_re.findall(content) + + pragma_re.findall(content) + + xml_re.findall(content) + ) + + +def _parse_content_type_header(header): + """Returns content type and parameters from given header + + :param header: string + :return: tuple containing content type and dictionary of + parameters + """ + + tokens = header.split(";") + content_type, params = tokens[0].strip(), tokens[1:] + params_dict = {} + items_to_strip = "\"' " + + for param in params: + param = param.strip() + if param: + key, value = param, True + index_of_equals = param.find("=") + if index_of_equals != -1: + key = param[:index_of_equals].strip(items_to_strip) + value = param[index_of_equals + 1 :].strip(items_to_strip) + params_dict[key.lower()] = value + return content_type, params_dict + + +def get_encoding_from_headers(headers): + """Returns encodings from given HTTP Header Dict. + + :param headers: dictionary to extract encoding from. + :rtype: str + """ + + content_type = headers.get("content-type") + + if not content_type: + return None + + content_type, params = _parse_content_type_header(content_type) + + if "charset" in params: + return params["charset"].strip("'\"") + + if "text" in content_type: + return "ISO-8859-1" + + if "application/json" in content_type: + # Assume UTF-8 based on RFC 4627: https://www.ietf.org/rfc/rfc4627.txt since the charset was unset + return "utf-8" + + +def stream_decode_response_unicode(iterator, r): + """Stream decodes an iterator.""" + + if r.encoding is None: + yield from iterator + return + + decoder = codecs.getincrementaldecoder(r.encoding)(errors="replace") + for chunk in iterator: + rv = decoder.decode(chunk) + if rv: + yield rv + rv = decoder.decode(b"", final=True) + if rv: + yield rv + + +def iter_slices(string, slice_length): + """Iterate over slices of a string.""" + pos = 0 + if slice_length is None or slice_length <= 0: + slice_length = len(string) + while pos < len(string): + yield string[pos : pos + slice_length] + pos += slice_length + + +def get_unicode_from_response(r): + """Returns the requested content back in unicode. + + :param r: Response object to get unicode content from. + + Tried: + + 1. charset from content-type + 2. fall back and replace all unicode characters + + :rtype: str + """ + warnings.warn( + ( + "In requests 3.0, get_unicode_from_response will be removed. For " + "more information, please see the discussion on issue #2266. (This" + " warning should only appear once.)" + ), + DeprecationWarning, + ) + + tried_encodings = [] + + # Try charset from content-type + encoding = get_encoding_from_headers(r.headers) + + if encoding: + try: + return str(r.content, encoding) + except UnicodeError: + tried_encodings.append(encoding) + + # Fall back: + try: + return str(r.content, encoding, errors="replace") + except TypeError: + return r.content + + +# The unreserved URI characters (RFC 3986) +UNRESERVED_SET = frozenset( + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "0123456789-._~" +) + + +def unquote_unreserved(uri): + """Un-escape any percent-escape sequences in a URI that are unreserved + characters. This leaves all reserved, illegal and non-ASCII bytes encoded. + + :rtype: str + """ + parts = uri.split("%") + for i in range(1, len(parts)): + h = parts[i][0:2] + if len(h) == 2 and h.isalnum(): + try: + c = chr(int(h, 16)) + except ValueError: + raise InvalidURL(f"Invalid percent-escape sequence: '{h}'") + + if c in UNRESERVED_SET: + parts[i] = c + parts[i][2:] + else: + parts[i] = f"%{parts[i]}" + else: + parts[i] = f"%{parts[i]}" + return "".join(parts) + + +def requote_uri(uri): + """Re-quote the given URI. + + This function passes the given URI through an unquote/quote cycle to + ensure that it is fully and consistently quoted. + + :rtype: str + """ + safe_with_percent = "!#$%&'()*+,/:;=?@[]~" + safe_without_percent = "!#$&'()*+,/:;=?@[]~" + try: + # Unquote only the unreserved characters + # Then quote only illegal characters (do not quote reserved, + # unreserved, or '%') + return quote(unquote_unreserved(uri), safe=safe_with_percent) + except InvalidURL: + # We couldn't unquote the given URI, so let's try quoting it, but + # there may be unquoted '%'s in the URI. We need to make sure they're + # properly quoted so they do not cause issues elsewhere. + return quote(uri, safe=safe_without_percent) + + +def address_in_network(ip, net): + """This function allows you to check if an IP belongs to a network subnet + + Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24 + returns False if ip = 192.168.1.1 and net = 192.168.100.0/24 + + :rtype: bool + """ + ipaddr = struct.unpack("=L", socket.inet_aton(ip))[0] + netaddr, bits = net.split("/") + netmask = struct.unpack("=L", socket.inet_aton(dotted_netmask(int(bits))))[0] + network = struct.unpack("=L", socket.inet_aton(netaddr))[0] & netmask + return (ipaddr & netmask) == (network & netmask) + + +def dotted_netmask(mask): + """Converts mask from /xx format to xxx.xxx.xxx.xxx + + Example: if mask is 24 function returns 255.255.255.0 + + :rtype: str + """ + bits = 0xFFFFFFFF ^ (1 << 32 - mask) - 1 + return socket.inet_ntoa(struct.pack(">I", bits)) + + +def is_ipv4_address(string_ip): + """ + :rtype: bool + """ + try: + socket.inet_aton(string_ip) + except OSError: + return False + return True + + +def is_valid_cidr(string_network): + """ + Very simple check of the cidr format in no_proxy variable. + + :rtype: bool + """ + if string_network.count("/") == 1: + try: + mask = int(string_network.split("/")[1]) + except ValueError: + return False + + if mask < 1 or mask > 32: + return False + + try: + socket.inet_aton(string_network.split("/")[0]) + except OSError: + return False + else: + return False + return True + + +@contextlib.contextmanager +def set_environ(env_name, value): + """Set the environment variable 'env_name' to 'value' + + Save previous value, yield, and then restore the previous value stored in + the environment variable 'env_name'. + + If 'value' is None, do nothing""" + value_changed = value is not None + if value_changed: + old_value = os.environ.get(env_name) + os.environ[env_name] = value + try: + yield + finally: + if value_changed: + if old_value is None: + del os.environ[env_name] + else: + os.environ[env_name] = old_value + + +def should_bypass_proxies(url, no_proxy): + """ + Returns whether we should bypass proxies or not. + + :rtype: bool + """ + + # Prioritize lowercase environment variables over uppercase + # to keep a consistent behaviour with other http projects (curl, wget). + def get_proxy(key): + return os.environ.get(key) or os.environ.get(key.upper()) + + # First check whether no_proxy is defined. If it is, check that the URL + # we're getting isn't in the no_proxy list. + no_proxy_arg = no_proxy + if no_proxy is None: + no_proxy = get_proxy("no_proxy") + parsed = urlparse(url) + + if parsed.hostname is None: + # URLs don't always have hostnames, e.g. file:/// urls. + return True + + if no_proxy: + # We need to check whether we match here. We need to see if we match + # the end of the hostname, both with and without the port. + no_proxy = (host for host in no_proxy.replace(" ", "").split(",") if host) + + if is_ipv4_address(parsed.hostname): + for proxy_ip in no_proxy: + if is_valid_cidr(proxy_ip): + if address_in_network(parsed.hostname, proxy_ip): + return True + elif parsed.hostname == proxy_ip: + # If no_proxy ip was defined in plain IP notation instead of cidr notation & + # matches the IP of the index + return True + else: + host_with_port = parsed.hostname + if parsed.port: + host_with_port += f":{parsed.port}" + + for host in no_proxy: + if parsed.hostname.endswith(host) or host_with_port.endswith(host): + # The URL does match something in no_proxy, so we don't want + # to apply the proxies on this URL. + return True + + with set_environ("no_proxy", no_proxy_arg): + # parsed.hostname can be `None` in cases such as a file URI. + try: + bypass = proxy_bypass(parsed.hostname) + except (TypeError, socket.gaierror): + bypass = False + + if bypass: + return True + + return False + + +def get_environ_proxies(url, no_proxy=None): + """ + Return a dict of environment proxies. + + :rtype: dict + """ + if should_bypass_proxies(url, no_proxy=no_proxy): + return {} + else: + return getproxies() + + +def select_proxy(url, proxies): + """Select a proxy for the url, if applicable. + + :param url: The url being for the request + :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs + """ + proxies = proxies or {} + urlparts = urlparse(url) + if urlparts.hostname is None: + return proxies.get(urlparts.scheme, proxies.get("all")) + + proxy_keys = [ + urlparts.scheme + "://" + urlparts.hostname, + urlparts.scheme, + "all://" + urlparts.hostname, + "all", + ] + proxy = None + for proxy_key in proxy_keys: + if proxy_key in proxies: + proxy = proxies[proxy_key] + break + + return proxy + + +def resolve_proxies(request, proxies, trust_env=True): + """This method takes proxy information from a request and configuration + input to resolve a mapping of target proxies. This will consider settings + such as NO_PROXY to strip proxy configurations. + + :param request: Request or PreparedRequest + :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs + :param trust_env: Boolean declaring whether to trust environment configs + + :rtype: dict + """ + proxies = proxies if proxies is not None else {} + url = request.url + scheme = urlparse(url).scheme + no_proxy = proxies.get("no_proxy") + new_proxies = proxies.copy() + + if trust_env and not should_bypass_proxies(url, no_proxy=no_proxy): + environ_proxies = get_environ_proxies(url, no_proxy=no_proxy) + + proxy = environ_proxies.get(scheme, environ_proxies.get("all")) + + if proxy: + new_proxies.setdefault(scheme, proxy) + return new_proxies + + +def default_user_agent(name="python-requests"): + """ + Return a string representing the default user agent. + + :rtype: str + """ + return f"{name}/{__version__}" + + +def default_headers(): + """ + :rtype: requests.structures.CaseInsensitiveDict + """ + return CaseInsensitiveDict( + { + "User-Agent": default_user_agent(), + "Accept-Encoding": DEFAULT_ACCEPT_ENCODING, + "Accept": "*/*", + "Connection": "keep-alive", + } + ) + + +def parse_header_links(value): + """Return a list of parsed link headers proxies. + + i.e. Link: ; rel=front; type="image/jpeg",; rel=back;type="image/jpeg" + + :rtype: list + """ + + links = [] + + replace_chars = " '\"" + + value = value.strip(replace_chars) + if not value: + return links + + for val in re.split(", *<", value): + try: + url, params = val.split(";", 1) + except ValueError: + url, params = val, "" + + link = {"url": url.strip("<> '\"")} + + for param in params.split(";"): + try: + key, value = param.split("=") + except ValueError: + break + + link[key.strip(replace_chars)] = value.strip(replace_chars) + + links.append(link) + + return links + + +# Null bytes; no need to recreate these on each call to guess_json_utf +_null = "\x00".encode("ascii") # encoding to ASCII for Python 3 +_null2 = _null * 2 +_null3 = _null * 3 + + +def guess_json_utf(data): + """ + :rtype: str + """ + # JSON always starts with two ASCII characters, so detection is as + # easy as counting the nulls and from their location and count + # determine the encoding. Also detect a BOM, if present. + sample = data[:4] + if sample in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE): + return "utf-32" # BOM included + if sample[:3] == codecs.BOM_UTF8: + return "utf-8-sig" # BOM included, MS style (discouraged) + if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE): + return "utf-16" # BOM included + nullcount = sample.count(_null) + if nullcount == 0: + return "utf-8" + if nullcount == 2: + if sample[::2] == _null2: # 1st and 3rd are null + return "utf-16-be" + if sample[1::2] == _null2: # 2nd and 4th are null + return "utf-16-le" + # Did not detect 2 valid UTF-16 ascii-range characters + if nullcount == 3: + if sample[:3] == _null3: + return "utf-32-be" + if sample[1:] == _null3: + return "utf-32-le" + # Did not detect a valid UTF-32 ascii-range character + return None + + +def prepend_scheme_if_needed(url, new_scheme): + """Given a URL that may or may not have a scheme, prepend the given scheme. + Does not replace a present scheme with the one provided as an argument. + + :rtype: str + """ + parsed = parse_url(url) + scheme, auth, host, port, path, query, fragment = parsed + + # A defect in urlparse determines that there isn't a netloc present in some + # urls. We previously assumed parsing was overly cautious, and swapped the + # netloc and path. Due to a lack of tests on the original defect, this is + # maintained with parse_url for backwards compatibility. + netloc = parsed.netloc + if not netloc: + netloc, path = path, netloc + + if auth: + # parse_url doesn't provide the netloc with auth + # so we'll add it ourselves. + netloc = "@".join([auth, netloc]) + if scheme is None: + scheme = new_scheme + if path is None: + path = "" + + return urlunparse((scheme, netloc, path, "", query, fragment)) + + +def get_auth_from_url(url): + """Given a url with authentication components, extract them into a tuple of + username,password. + + :rtype: (str,str) + """ + parsed = urlparse(url) + + try: + auth = (unquote(parsed.username), unquote(parsed.password)) + except (AttributeError, TypeError): + auth = ("", "") + + return auth + + +def check_header_validity(header): + """Verifies that header parts don't contain leading whitespace + reserved characters, or return characters. + + :param header: tuple, in the format (name, value). + """ + name, value = header + _validate_header_part(header, name, 0) + _validate_header_part(header, value, 1) + + +def _validate_header_part(header, header_part, header_validator_index): + if isinstance(header_part, str): + validator = _HEADER_VALIDATORS_STR[header_validator_index] + elif isinstance(header_part, bytes): + validator = _HEADER_VALIDATORS_BYTE[header_validator_index] + else: + raise InvalidHeader( + f"Header part ({header_part!r}) from {header} " + f"must be of type str or bytes, not {type(header_part)}" + ) + + if not validator.match(header_part): + header_kind = "name" if header_validator_index == 0 else "value" + raise InvalidHeader( + f"Invalid leading whitespace, reserved character(s), or return " + f"character(s) in header {header_kind}: {header_part!r}" + ) + + +def urldefragauth(url): + """ + Given a url remove the fragment and the authentication part. + + :rtype: str + """ + scheme, netloc, path, params, query, fragment = urlparse(url) + + # see func:`prepend_scheme_if_needed` + if not netloc: + netloc, path = path, netloc + + netloc = netloc.rsplit("@", 1)[-1] + + return urlunparse((scheme, netloc, path, params, query, "")) + + +def rewind_body(prepared_request): + """Move file pointer back to its recorded starting position + so it can be read again on redirect. + """ + body_seek = getattr(prepared_request.body, "seek", None) + if body_seek is not None and isinstance( + prepared_request._body_position, integer_types + ): + try: + body_seek(prepared_request._body_position) + except OSError: + raise UnrewindableBodyError( + "An error occurred when rewinding request body for redirect." + ) + else: + raise UnrewindableBodyError("Unable to rewind request body for redirect.") diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rfc3986-1.5.0.dist-info/AUTHORS.rst b/TTS/Kokoro/.venv/Lib/site-packages/rfc3986-1.5.0.dist-info/AUTHORS.rst new file mode 100644 index 0000000000000000000000000000000000000000..54cb3c9e11e829d8cfa796cba4487a4991cc9380 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rfc3986-1.5.0.dist-info/AUTHORS.rst @@ -0,0 +1,14 @@ +Development Lead +---------------- + +- Ian Stapleton Cordasco + +Contributors +------------ + +- Thomas Weißschuh +- Kostya Esmukov +- Derek Higgins +- Victor Stinner +- Viktor Haag +- Seth Michael Larson diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rfc3986-1.5.0.dist-info/INSTALLER b/TTS/Kokoro/.venv/Lib/site-packages/rfc3986-1.5.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rfc3986-1.5.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rfc3986-1.5.0.dist-info/LICENSE b/TTS/Kokoro/.venv/Lib/site-packages/rfc3986-1.5.0.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..72ce24cf02822ef81cd50905c094b5c7ac958df8 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rfc3986-1.5.0.dist-info/LICENSE @@ -0,0 +1,13 @@ +Copyright 2014 Ian Cordasco, Rackspace + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +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. diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rfc3986-1.5.0.dist-info/METADATA b/TTS/Kokoro/.venv/Lib/site-packages/rfc3986-1.5.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..2ddcde04052b61db582136248e4cd57be39fae84 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rfc3986-1.5.0.dist-info/METADATA @@ -0,0 +1,230 @@ +Metadata-Version: 2.1 +Name: rfc3986 +Version: 1.5.0 +Summary: Validating URI References per RFC 3986 +Home-page: http://rfc3986.readthedocs.io +Author: Ian Stapleton Cordasco +Author-email: graffatcolmingov@gmail.com +License: Apache 2.0 +Platform: UNKNOWN +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Natural Language :: English +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 2.7 +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.4 +Classifier: Programming Language :: Python :: 3.5 +Classifier: Programming Language :: Python :: 3.6 +Classifier: Programming Language :: Python :: 3.7 +Provides-Extra: idna2008 +Requires-Dist: idna ; extra == 'idna2008' + +rfc3986 +======= + +A Python implementation of `RFC 3986`_ including validation and authority +parsing. + +Installation +------------ + +Use pip to install ``rfc3986`` like so:: + + pip install rfc3986 + +License +------- + +`Apache License Version 2.0`_ + +Example Usage +------------- + +The following are the two most common use cases envisioned for ``rfc3986``. + +Replacing ``urlparse`` +`````````````````````` + +To parse a URI and receive something very similar to the standard library's +``urllib.parse.urlparse`` + +.. code-block:: python + + from rfc3986 import urlparse + + ssh = urlparse('ssh://user@git.openstack.org:29418/openstack/glance.git') + print(ssh.scheme) # => ssh + print(ssh.userinfo) # => user + print(ssh.params) # => None + print(ssh.port) # => 29418 + +To create a copy of it with new pieces you can use ``copy_with``: + +.. code-block:: python + + new_ssh = ssh.copy_with( + scheme='https' + userinfo='', + port=443, + path='/openstack/glance' + ) + print(new_ssh.scheme) # => https + print(new_ssh.userinfo) # => None + # etc. + +Strictly Parsing a URI and Applying Validation +`````````````````````````````````````````````` + +To parse a URI into a convenient named tuple, you can simply: + +.. code-block:: python + + from rfc3986 import uri_reference + + example = uri_reference('http://example.com') + email = uri_reference('mailto:user@domain.com') + ssh = uri_reference('ssh://user@git.openstack.org:29418/openstack/keystone.git') + +With a parsed URI you can access data about the components: + +.. code-block:: python + + print(example.scheme) # => http + print(email.path) # => user@domain.com + print(ssh.userinfo) # => user + print(ssh.host) # => git.openstack.org + print(ssh.port) # => 29418 + +It can also parse URIs with unicode present: + +.. code-block:: python + + uni = uri_reference(b'http://httpbin.org/get?utf8=\xe2\x98\x83') # ☃ + print(uni.query) # utf8=%E2%98%83 + +With a parsed URI you can also validate it: + +.. code-block:: python + + if ssh.is_valid(): + subprocess.call(['git', 'clone', ssh.unsplit()]) + +You can also take a parsed URI and normalize it: + +.. code-block:: python + + mangled = uri_reference('hTTp://exAMPLe.COM') + print(mangled.scheme) # => hTTp + print(mangled.authority) # => exAMPLe.COM + + normal = mangled.normalize() + print(normal.scheme) # => http + print(mangled.authority) # => example.com + +But these two URIs are (functionally) equivalent: + +.. code-block:: python + + if normal == mangled: + webbrowser.open(normal.unsplit()) + +Your paths, queries, and fragments are safe with us though: + +.. code-block:: python + + mangled = uri_reference('hTTp://exAMPLe.COM/Some/reallY/biZZare/pAth') + normal = mangled.normalize() + assert normal == 'hTTp://exAMPLe.COM/Some/reallY/biZZare/pAth' + assert normal == 'http://example.com/Some/reallY/biZZare/pAth' + assert normal != 'http://example.com/some/really/bizzare/path' + +If you do not actually need a real reference object and just want to normalize +your URI: + +.. code-block:: python + + from rfc3986 import normalize_uri + + assert (normalize_uri('hTTp://exAMPLe.COM/Some/reallY/biZZare/pAth') == + 'http://example.com/Some/reallY/biZZare/pAth') + +You can also very simply validate a URI: + +.. code-block:: python + + from rfc3986 import is_valid_uri + + assert is_valid_uri('hTTp://exAMPLe.COM/Some/reallY/biZZare/pAth') + +Requiring Components +~~~~~~~~~~~~~~~~~~~~ + +You can validate that a particular string is a valid URI and require +independent components: + +.. code-block:: python + + from rfc3986 import is_valid_uri + + assert is_valid_uri('http://localhost:8774/v2/resource', + require_scheme=True, + require_authority=True, + require_path=True) + + # Assert that a mailto URI is invalid if you require an authority + # component + assert is_valid_uri('mailto:user@example.com', require_authority=True) is False + +If you have an instance of a ``URIReference``, you can pass the same arguments +to ``URIReference#is_valid``, e.g., + +.. code-block:: python + + from rfc3986 import uri_reference + + http = uri_reference('http://localhost:8774/v2/resource') + assert uri.is_valid(require_scheme=True, + require_authority=True, + require_path=True) + + # Assert that a mailto URI is invalid if you require an authority + # component + mailto = uri_reference('mailto:user@example.com') + assert uri.is_valid(require_authority=True) is False + +Alternatives +------------ + +- `rfc3987 `_ + + This is a direct competitor to this library, with extra features, + licensed under the GPL. + +- `uritools `_ + + This can parse URIs in the manner of RFC 3986 but provides no validation and + only recently added Python 3 support. + +- Standard library's `urlparse`/`urllib.parse` + + The functions in these libraries can only split a URI (valid or not) and + provide no validation. + +Contributing +------------ + +This project follows and enforces the Python Software Foundation's `Code of +Conduct `_. + +If you would like to contribute but do not have a bug or feature in mind, feel +free to email Ian and find out how you can help. + +The git repository for this project is maintained at +https://github.com/python-hyper/rfc3986 + +.. _RFC 3986: http://tools.ietf.org/html/rfc3986 +.. _Apache License Version 2.0: https://www.apache.org/licenses/LICENSE-2.0 + + diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rfc3986-1.5.0.dist-info/RECORD b/TTS/Kokoro/.venv/Lib/site-packages/rfc3986-1.5.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..b7ed4d0dc745fcafc93a75337410497f6a36a240 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rfc3986-1.5.0.dist-info/RECORD @@ -0,0 +1,33 @@ +rfc3986-1.5.0.dist-info/AUTHORS.rst,sha256=QjlDdMHiNeQv1lPqHeGQ4OtiEPCwFafJLu7t23AXDHo,223 +rfc3986-1.5.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +rfc3986-1.5.0.dist-info/LICENSE,sha256=wN3OM7-sSApmveQMWQ7eJkekyKcp3LDSzkbAFEc9Xdg,564 +rfc3986-1.5.0.dist-info/METADATA,sha256=qkuCB_ifgypthNS6-M-IOKli-F3YPR8xzOOXPHEu2Wo,6458 +rfc3986-1.5.0.dist-info/RECORD,, +rfc3986-1.5.0.dist-info/WHEEL,sha256=Z-nyYpwrcSqxfdux5Mbn_DQ525iP7J2DG3JgGvOYyTQ,110 +rfc3986-1.5.0.dist-info/top_level.txt,sha256=Z10Qesb0UV9AbxlTIV9AnOAwk-343WnE85K8xfN4OmA,8 +rfc3986/__init__.py,sha256=Yc1nYWLNwBn1XUCt3lPMC6cPD3S82FKPPc4IpTaFjCE,1591 +rfc3986/__pycache__/__init__.cpython-312.pyc,, +rfc3986/__pycache__/_mixin.cpython-312.pyc,, +rfc3986/__pycache__/abnf_regexp.cpython-312.pyc,, +rfc3986/__pycache__/api.cpython-312.pyc,, +rfc3986/__pycache__/builder.cpython-312.pyc,, +rfc3986/__pycache__/compat.cpython-312.pyc,, +rfc3986/__pycache__/exceptions.cpython-312.pyc,, +rfc3986/__pycache__/iri.cpython-312.pyc,, +rfc3986/__pycache__/misc.cpython-312.pyc,, +rfc3986/__pycache__/normalizers.cpython-312.pyc,, +rfc3986/__pycache__/parseresult.cpython-312.pyc,, +rfc3986/__pycache__/uri.cpython-312.pyc,, +rfc3986/__pycache__/validators.cpython-312.pyc,, +rfc3986/_mixin.py,sha256=iFnLyRbd-QMQv9LlYwglAt-vNA4CxpBhnZMu-XyKP4w,13280 +rfc3986/abnf_regexp.py,sha256=hTIxwQQcngkTmmDn0T0m0_6dZZIiMovYEsITUrZIL3Q,9121 +rfc3986/api.py,sha256=UzjPnQ4_G0ludMVXEeq6CVYmFQ55rDpKvHakGZMxVe8,3887 +rfc3986/builder.py,sha256=vuI6u7B3UQbVrh47xDF7X5sducTxzkLQeuvW7vPavok,12757 +rfc3986/compat.py,sha256=51xDR7kfVhaM7GqTLmw-lQY4jv2mw2MbCNuBnG4PnbA,1644 +rfc3986/exceptions.py,sha256=dFYnm-TabVYpWUEPXqtGp8xfSg1wWYk09TaUjCetWYI,3847 +rfc3986/iri.py,sha256=BX1nFD0JyZnUfAHxDFqyz0hN8J-YfKxIhYJLyBZGAZo,5520 +rfc3986/misc.py,sha256=bye9xhySD_GshuL_MD0VTledl6jBw_ErG8kXtTNXzXQ,4163 +rfc3986/normalizers.py,sha256=f6oLvNUadxZDJDtx3JvqF_exGGD7PvLaibYQBUfh2NE,5294 +rfc3986/parseresult.py,sha256=NvbPpPzuuputHpJc4J2cjcNy6B7c6rscFqzSnksDWmc,14742 +rfc3986/uri.py,sha256=LYNAlr2ujVfCa6jcV8o1I1hOuviuuXsSRHpST2DyvAw,5225 +rfc3986/validators.py,sha256=qcvNnrpk2el-otJN-ZRGZ0PE4xaSEP97lKREXG_YtpM,13839 diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rfc3986-1.5.0.dist-info/WHEEL b/TTS/Kokoro/.venv/Lib/site-packages/rfc3986-1.5.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..01b8fc7d4a10cb8b4f1d21f11d3398d07d6b3478 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rfc3986-1.5.0.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.36.2) +Root-Is-Purelib: true +Tag: py2-none-any +Tag: py3-none-any + diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rfc3986-1.5.0.dist-info/top_level.txt b/TTS/Kokoro/.venv/Lib/site-packages/rfc3986-1.5.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..af30258c1e2827d6873e713213e651a00175aac7 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rfc3986-1.5.0.dist-info/top_level.txt @@ -0,0 +1 @@ +rfc3986 diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rfc3986/__init__.py b/TTS/Kokoro/.venv/Lib/site-packages/rfc3986/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a052299c71b53aaa6f00112dbb23d05234d686b6 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rfc3986/__init__.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2014 Rackspace +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# 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. + +""" +An implementation of semantics and validations described in RFC 3986. + +See http://rfc3986.readthedocs.io/ for detailed documentation. + +:copyright: (c) 2014 Rackspace +:license: Apache v2.0, see LICENSE for details +""" + +from .api import iri_reference +from .api import IRIReference +from .api import is_valid_uri +from .api import normalize_uri +from .api import uri_reference +from .api import URIReference +from .api import urlparse +from .parseresult import ParseResult + +__title__ = "rfc3986" +__author__ = "Ian Stapleton Cordasco" +__author_email__ = "graffatcolmingov@gmail.com" +__license__ = "Apache v2.0" +__copyright__ = "Copyright 2014 Rackspace; 2016 Ian Stapleton Cordasco" +__version__ = "1.5.0" + +__all__ = ( + "ParseResult", + "URIReference", + "IRIReference", + "is_valid_uri", + "normalize_uri", + "uri_reference", + "iri_reference", + "urlparse", + "__title__", + "__author__", + "__author_email__", + "__license__", + "__copyright__", + "__version__", +) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rfc3986/_mixin.py b/TTS/Kokoro/.venv/Lib/site-packages/rfc3986/_mixin.py new file mode 100644 index 0000000000000000000000000000000000000000..46e200e2f9a11f800405c59b209a2213e74b97b7 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rfc3986/_mixin.py @@ -0,0 +1,373 @@ +"""Module containing the implementation of the URIMixin class.""" +import warnings + +from . import exceptions as exc +from . import misc +from . import normalizers +from . import validators + + +class URIMixin(object): + """Mixin with all shared methods for URIs and IRIs.""" + + __hash__ = tuple.__hash__ + + def authority_info(self): + """Return a dictionary with the ``userinfo``, ``host``, and ``port``. + + If the authority is not valid, it will raise a + :class:`~rfc3986.exceptions.InvalidAuthority` Exception. + + :returns: + ``{'userinfo': 'username:password', 'host': 'www.example.com', + 'port': '80'}`` + :rtype: dict + :raises rfc3986.exceptions.InvalidAuthority: + If the authority is not ``None`` and can not be parsed. + """ + if not self.authority: + return {"userinfo": None, "host": None, "port": None} + + match = self._match_subauthority() + + if match is None: + # In this case, we have an authority that was parsed from the URI + # Reference, but it cannot be further parsed by our + # misc.SUBAUTHORITY_MATCHER. In this case it must not be a valid + # authority. + raise exc.InvalidAuthority(self.authority.encode(self.encoding)) + + # We had a match, now let's ensure that it is actually a valid host + # address if it is IPv4 + matches = match.groupdict() + host = matches.get("host") + + if ( + host + and misc.IPv4_MATCHER.match(host) + and not validators.valid_ipv4_host_address(host) + ): + # If we have a host, it appears to be IPv4 and it does not have + # valid bytes, it is an InvalidAuthority. + raise exc.InvalidAuthority(self.authority.encode(self.encoding)) + + return matches + + def _match_subauthority(self): + return misc.SUBAUTHORITY_MATCHER.match(self.authority) + + @property + def host(self): + """If present, a string representing the host.""" + try: + authority = self.authority_info() + except exc.InvalidAuthority: + return None + return authority["host"] + + @property + def port(self): + """If present, the port extracted from the authority.""" + try: + authority = self.authority_info() + except exc.InvalidAuthority: + return None + return authority["port"] + + @property + def userinfo(self): + """If present, the userinfo extracted from the authority.""" + try: + authority = self.authority_info() + except exc.InvalidAuthority: + return None + return authority["userinfo"] + + def is_absolute(self): + """Determine if this URI Reference is an absolute URI. + + See http://tools.ietf.org/html/rfc3986#section-4.3 for explanation. + + :returns: ``True`` if it is an absolute URI, ``False`` otherwise. + :rtype: bool + """ + return bool(misc.ABSOLUTE_URI_MATCHER.match(self.unsplit())) + + def is_valid(self, **kwargs): + """Determine if the URI is valid. + + .. deprecated:: 1.1.0 + + Use the :class:`~rfc3986.validators.Validator` object instead. + + :param bool require_scheme: Set to ``True`` if you wish to require the + presence of the scheme component. + :param bool require_authority: Set to ``True`` if you wish to require + the presence of the authority component. + :param bool require_path: Set to ``True`` if you wish to require the + presence of the path component. + :param bool require_query: Set to ``True`` if you wish to require the + presence of the query component. + :param bool require_fragment: Set to ``True`` if you wish to require + the presence of the fragment component. + :returns: ``True`` if the URI is valid. ``False`` otherwise. + :rtype: bool + """ + warnings.warn( + "Please use rfc3986.validators.Validator instead. " + "This method will be eventually removed.", + DeprecationWarning, + ) + validators = [ + (self.scheme_is_valid, kwargs.get("require_scheme", False)), + (self.authority_is_valid, kwargs.get("require_authority", False)), + (self.path_is_valid, kwargs.get("require_path", False)), + (self.query_is_valid, kwargs.get("require_query", False)), + (self.fragment_is_valid, kwargs.get("require_fragment", False)), + ] + return all(v(r) for v, r in validators) + + def authority_is_valid(self, require=False): + """Determine if the authority component is valid. + + .. deprecated:: 1.1.0 + + Use the :class:`~rfc3986.validators.Validator` object instead. + + :param bool require: + Set to ``True`` to require the presence of this component. + :returns: + ``True`` if the authority is valid. ``False`` otherwise. + :rtype: + bool + """ + warnings.warn( + "Please use rfc3986.validators.Validator instead. " + "This method will be eventually removed.", + DeprecationWarning, + ) + try: + self.authority_info() + except exc.InvalidAuthority: + return False + + return validators.authority_is_valid( + self.authority, + host=self.host, + require=require, + ) + + def scheme_is_valid(self, require=False): + """Determine if the scheme component is valid. + + .. deprecated:: 1.1.0 + + Use the :class:`~rfc3986.validators.Validator` object instead. + + :param str require: Set to ``True`` to require the presence of this + component. + :returns: ``True`` if the scheme is valid. ``False`` otherwise. + :rtype: bool + """ + warnings.warn( + "Please use rfc3986.validators.Validator instead. " + "This method will be eventually removed.", + DeprecationWarning, + ) + return validators.scheme_is_valid(self.scheme, require) + + def path_is_valid(self, require=False): + """Determine if the path component is valid. + + .. deprecated:: 1.1.0 + + Use the :class:`~rfc3986.validators.Validator` object instead. + + :param str require: Set to ``True`` to require the presence of this + component. + :returns: ``True`` if the path is valid. ``False`` otherwise. + :rtype: bool + """ + warnings.warn( + "Please use rfc3986.validators.Validator instead. " + "This method will be eventually removed.", + DeprecationWarning, + ) + return validators.path_is_valid(self.path, require) + + def query_is_valid(self, require=False): + """Determine if the query component is valid. + + .. deprecated:: 1.1.0 + + Use the :class:`~rfc3986.validators.Validator` object instead. + + :param str require: Set to ``True`` to require the presence of this + component. + :returns: ``True`` if the query is valid. ``False`` otherwise. + :rtype: bool + """ + warnings.warn( + "Please use rfc3986.validators.Validator instead. " + "This method will be eventually removed.", + DeprecationWarning, + ) + return validators.query_is_valid(self.query, require) + + def fragment_is_valid(self, require=False): + """Determine if the fragment component is valid. + + .. deprecated:: 1.1.0 + + Use the Validator object instead. + + :param str require: Set to ``True`` to require the presence of this + component. + :returns: ``True`` if the fragment is valid. ``False`` otherwise. + :rtype: bool + """ + warnings.warn( + "Please use rfc3986.validators.Validator instead. " + "This method will be eventually removed.", + DeprecationWarning, + ) + return validators.fragment_is_valid(self.fragment, require) + + def normalized_equality(self, other_ref): + """Compare this URIReference to another URIReference. + + :param URIReference other_ref: (required), The reference with which + we're comparing. + :returns: ``True`` if the references are equal, ``False`` otherwise. + :rtype: bool + """ + return tuple(self.normalize()) == tuple(other_ref.normalize()) + + def resolve_with(self, base_uri, strict=False): + """Use an absolute URI Reference to resolve this relative reference. + + Assuming this is a relative reference that you would like to resolve, + use the provided base URI to resolve it. + + See http://tools.ietf.org/html/rfc3986#section-5 for more information. + + :param base_uri: Either a string or URIReference. It must be an + absolute URI or it will raise an exception. + :returns: A new URIReference which is the result of resolving this + reference using ``base_uri``. + :rtype: :class:`URIReference` + :raises rfc3986.exceptions.ResolutionError: + If the ``base_uri`` is not an absolute URI. + """ + if not isinstance(base_uri, URIMixin): + base_uri = type(self).from_string(base_uri) + + if not base_uri.is_absolute(): + raise exc.ResolutionError(base_uri) + + # This is optional per + # http://tools.ietf.org/html/rfc3986#section-5.2.1 + base_uri = base_uri.normalize() + + # The reference we're resolving + resolving = self + + if not strict and resolving.scheme == base_uri.scheme: + resolving = resolving.copy_with(scheme=None) + + # http://tools.ietf.org/html/rfc3986#page-32 + if resolving.scheme is not None: + target = resolving.copy_with( + path=normalizers.normalize_path(resolving.path) + ) + else: + if resolving.authority is not None: + target = resolving.copy_with( + scheme=base_uri.scheme, + path=normalizers.normalize_path(resolving.path), + ) + else: + if resolving.path is None: + if resolving.query is not None: + query = resolving.query + else: + query = base_uri.query + target = resolving.copy_with( + scheme=base_uri.scheme, + authority=base_uri.authority, + path=base_uri.path, + query=query, + ) + else: + if resolving.path.startswith("/"): + path = normalizers.normalize_path(resolving.path) + else: + path = normalizers.normalize_path( + misc.merge_paths(base_uri, resolving.path) + ) + target = resolving.copy_with( + scheme=base_uri.scheme, + authority=base_uri.authority, + path=path, + query=resolving.query, + ) + return target + + def unsplit(self): + """Create a URI string from the components. + + :returns: The URI Reference reconstituted as a string. + :rtype: str + """ + # See http://tools.ietf.org/html/rfc3986#section-5.3 + result_list = [] + if self.scheme: + result_list.extend([self.scheme, ":"]) + if self.authority: + result_list.extend(["//", self.authority]) + if self.path: + result_list.append(self.path) + if self.query is not None: + result_list.extend(["?", self.query]) + if self.fragment is not None: + result_list.extend(["#", self.fragment]) + return "".join(result_list) + + def copy_with( + self, + scheme=misc.UseExisting, + authority=misc.UseExisting, + path=misc.UseExisting, + query=misc.UseExisting, + fragment=misc.UseExisting, + ): + """Create a copy of this reference with the new components. + + :param str scheme: + (optional) The scheme to use for the new reference. + :param str authority: + (optional) The authority to use for the new reference. + :param str path: + (optional) The path to use for the new reference. + :param str query: + (optional) The query to use for the new reference. + :param str fragment: + (optional) The fragment to use for the new reference. + :returns: + New URIReference with provided components. + :rtype: + URIReference + """ + attributes = { + "scheme": scheme, + "authority": authority, + "path": path, + "query": query, + "fragment": fragment, + } + for key, value in list(attributes.items()): + if value is misc.UseExisting: + del attributes[key] + uri = self._replace(**attributes) + uri.encoding = self.encoding + return uri diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rfc3986/abnf_regexp.py b/TTS/Kokoro/.venv/Lib/site-packages/rfc3986/abnf_regexp.py new file mode 100644 index 0000000000000000000000000000000000000000..a2e7ee7ab076c5240a77ec363f13d0ea681a8b39 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rfc3986/abnf_regexp.py @@ -0,0 +1,282 @@ +# -*- coding: utf-8 -*- +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# 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. +"""Module for the regular expressions crafted from ABNF.""" + +import sys + +# https://tools.ietf.org/html/rfc3986#page-13 +GEN_DELIMS = GENERIC_DELIMITERS = ":/?#[]@" +GENERIC_DELIMITERS_SET = set(GENERIC_DELIMITERS) +# https://tools.ietf.org/html/rfc3986#page-13 +SUB_DELIMS = SUB_DELIMITERS = "!$&'()*+,;=" +SUB_DELIMITERS_SET = set(SUB_DELIMITERS) +# Escape the '*' for use in regular expressions +SUB_DELIMITERS_RE = r"!$&'()\*+,;=" +RESERVED_CHARS_SET = GENERIC_DELIMITERS_SET.union(SUB_DELIMITERS_SET) +ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" +DIGIT = "0123456789" +# https://tools.ietf.org/html/rfc3986#section-2.3 +UNRESERVED = UNRESERVED_CHARS = ALPHA + DIGIT + r"._!-~" +UNRESERVED_CHARS_SET = set(UNRESERVED_CHARS) +NON_PCT_ENCODED_SET = RESERVED_CHARS_SET.union(UNRESERVED_CHARS_SET) +# We need to escape the '-' in this case: +UNRESERVED_RE = r"A-Za-z0-9._~\-" + +# Percent encoded character values +PERCENT_ENCODED = PCT_ENCODED = "%[A-Fa-f0-9]{2}" +PCHAR = "([" + UNRESERVED_RE + SUB_DELIMITERS_RE + ":@]|%s)" % PCT_ENCODED + +# NOTE(sigmavirus24): We're going to use more strict regular expressions +# than appear in Appendix B for scheme. This will prevent over-eager +# consuming of items that aren't schemes. +SCHEME_RE = "[a-zA-Z][a-zA-Z0-9+.-]*" +_AUTHORITY_RE = "[^\\\\/?#]*" +_PATH_RE = "[^?#]*" +_QUERY_RE = "[^#]*" +_FRAGMENT_RE = ".*" + +# Extracted from http://tools.ietf.org/html/rfc3986#appendix-B +COMPONENT_PATTERN_DICT = { + "scheme": SCHEME_RE, + "authority": _AUTHORITY_RE, + "path": _PATH_RE, + "query": _QUERY_RE, + "fragment": _FRAGMENT_RE, +} + +# See http://tools.ietf.org/html/rfc3986#appendix-B +# In this case, we name each of the important matches so we can use +# SRE_Match#groupdict to parse the values out if we so choose. This is also +# modified to ignore other matches that are not important to the parsing of +# the reference so we can also simply use SRE_Match#groups. +URL_PARSING_RE = ( + r"(?:(?P{scheme}):)?(?://(?P{authority}))?" + r"(?P{path})(?:\?(?P{query}))?" + r"(?:#(?P{fragment}))?" +).format(**COMPONENT_PATTERN_DICT) + + +# ######################### +# Authority Matcher Section +# ######################### + +# Host patterns, see: http://tools.ietf.org/html/rfc3986#section-3.2.2 +# The pattern for a regular name, e.g., www.google.com, api.github.com +REGULAR_NAME_RE = REG_NAME = "((?:{0}|[{1}])*)".format( + "%[0-9A-Fa-f]{2}", SUB_DELIMITERS_RE + UNRESERVED_RE +) +# The pattern for an IPv4 address, e.g., 192.168.255.255, 127.0.0.1, +IPv4_RE = r"([0-9]{1,3}\.){3}[0-9]{1,3}" +# Hexadecimal characters used in each piece of an IPv6 address +HEXDIG_RE = "[0-9A-Fa-f]{1,4}" +# Least-significant 32 bits of an IPv6 address +LS32_RE = "({hex}:{hex}|{ipv4})".format(hex=HEXDIG_RE, ipv4=IPv4_RE) +# Substitutions into the following patterns for IPv6 patterns defined +# http://tools.ietf.org/html/rfc3986#page-20 +_subs = {"hex": HEXDIG_RE, "ls32": LS32_RE} + +# Below: h16 = hexdig, see: https://tools.ietf.org/html/rfc5234 for details +# about ABNF (Augmented Backus-Naur Form) use in the comments +variations = [ + # 6( h16 ":" ) ls32 + "(%(hex)s:){6}%(ls32)s" % _subs, + # "::" 5( h16 ":" ) ls32 + "::(%(hex)s:){5}%(ls32)s" % _subs, + # [ h16 ] "::" 4( h16 ":" ) ls32 + "(%(hex)s)?::(%(hex)s:){4}%(ls32)s" % _subs, + # [ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32 + "((%(hex)s:)?%(hex)s)?::(%(hex)s:){3}%(ls32)s" % _subs, + # [ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32 + "((%(hex)s:){0,2}%(hex)s)?::(%(hex)s:){2}%(ls32)s" % _subs, + # [ *3( h16 ":" ) h16 ] "::" h16 ":" ls32 + "((%(hex)s:){0,3}%(hex)s)?::%(hex)s:%(ls32)s" % _subs, + # [ *4( h16 ":" ) h16 ] "::" ls32 + "((%(hex)s:){0,4}%(hex)s)?::%(ls32)s" % _subs, + # [ *5( h16 ":" ) h16 ] "::" h16 + "((%(hex)s:){0,5}%(hex)s)?::%(hex)s" % _subs, + # [ *6( h16 ":" ) h16 ] "::" + "((%(hex)s:){0,6}%(hex)s)?::" % _subs, +] + +IPv6_RE = "(({0})|({1})|({2})|({3})|({4})|({5})|({6})|({7})|({8}))".format( + *variations +) + +IPv_FUTURE_RE = r"v[0-9A-Fa-f]+\.[%s]+" % ( + UNRESERVED_RE + SUB_DELIMITERS_RE + ":" +) + +# RFC 6874 Zone ID ABNF +ZONE_ID = "(?:[" + UNRESERVED_RE + "]|" + PCT_ENCODED + ")+" + +IPv6_ADDRZ_RFC4007_RE = IPv6_RE + "(?:(?:%25|%)" + ZONE_ID + ")?" +IPv6_ADDRZ_RE = IPv6_RE + "(?:%25" + ZONE_ID + ")?" + +IP_LITERAL_RE = r"\[({0}|{1})\]".format( + IPv6_ADDRZ_RFC4007_RE, + IPv_FUTURE_RE, +) + +# Pattern for matching the host piece of the authority +HOST_RE = HOST_PATTERN = "({0}|{1}|{2})".format( + REG_NAME, + IPv4_RE, + IP_LITERAL_RE, +) +USERINFO_RE = ( + "^([" + UNRESERVED_RE + SUB_DELIMITERS_RE + ":]|%s)+" % (PCT_ENCODED) +) +PORT_RE = "[0-9]{1,5}" + +# #################### +# Path Matcher Section +# #################### + +# See http://tools.ietf.org/html/rfc3986#section-3.3 for more information +# about the path patterns defined below. +segments = { + "segment": PCHAR + "*", + # Non-zero length segment + "segment-nz": PCHAR + "+", + # Non-zero length segment without ":" + "segment-nz-nc": PCHAR.replace(":", "") + "+", +} + +# Path types taken from Section 3.3 (linked above) +PATH_EMPTY = "^$" +PATH_ROOTLESS = "%(segment-nz)s(/%(segment)s)*" % segments +PATH_NOSCHEME = "%(segment-nz-nc)s(/%(segment)s)*" % segments +PATH_ABSOLUTE = "/(%s)?" % PATH_ROOTLESS +PATH_ABEMPTY = "(/%(segment)s)*" % segments +PATH_RE = "^(%s|%s|%s|%s|%s)$" % ( + PATH_ABEMPTY, + PATH_ABSOLUTE, + PATH_NOSCHEME, + PATH_ROOTLESS, + PATH_EMPTY, +) + +FRAGMENT_RE = QUERY_RE = ( + "^([/?:@" + UNRESERVED_RE + SUB_DELIMITERS_RE + "]|%s)*$" % PCT_ENCODED +) + +# ########################## +# Relative reference matcher +# ########################## + +# See http://tools.ietf.org/html/rfc3986#section-4.2 for details +RELATIVE_PART_RE = "(//%s%s|%s|%s|%s)" % ( + COMPONENT_PATTERN_DICT["authority"], + PATH_ABEMPTY, + PATH_ABSOLUTE, + PATH_NOSCHEME, + PATH_EMPTY, +) + +# See http://tools.ietf.org/html/rfc3986#section-3 for definition +HIER_PART_RE = "(//%s%s|%s|%s|%s)" % ( + COMPONENT_PATTERN_DICT["authority"], + PATH_ABEMPTY, + PATH_ABSOLUTE, + PATH_ROOTLESS, + PATH_EMPTY, +) + +# ############### +# IRIs / RFC 3987 +# ############### + +# Only wide-unicode gets the high-ranges of UCSCHAR +if sys.maxunicode > 0xFFFF: # pragma: no cover + IPRIVATE = u"\uE000-\uF8FF\U000F0000-\U000FFFFD\U00100000-\U0010FFFD" + UCSCHAR_RE = ( + u"\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF" + u"\U00010000-\U0001FFFD\U00020000-\U0002FFFD" + u"\U00030000-\U0003FFFD\U00040000-\U0004FFFD" + u"\U00050000-\U0005FFFD\U00060000-\U0006FFFD" + u"\U00070000-\U0007FFFD\U00080000-\U0008FFFD" + u"\U00090000-\U0009FFFD\U000A0000-\U000AFFFD" + u"\U000B0000-\U000BFFFD\U000C0000-\U000CFFFD" + u"\U000D0000-\U000DFFFD\U000E1000-\U000EFFFD" + ) +else: # pragma: no cover + IPRIVATE = u"\uE000-\uF8FF" + UCSCHAR_RE = u"\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF" + +IUNRESERVED_RE = u"A-Za-z0-9\\._~\\-" + UCSCHAR_RE +IPCHAR = u"([" + IUNRESERVED_RE + SUB_DELIMITERS_RE + u":@]|%s)" % PCT_ENCODED + +isegments = { + "isegment": IPCHAR + u"*", + # Non-zero length segment + "isegment-nz": IPCHAR + u"+", + # Non-zero length segment without ":" + "isegment-nz-nc": IPCHAR.replace(":", "") + u"+", +} + +IPATH_ROOTLESS = u"%(isegment-nz)s(/%(isegment)s)*" % isegments +IPATH_NOSCHEME = u"%(isegment-nz-nc)s(/%(isegment)s)*" % isegments +IPATH_ABSOLUTE = u"/(?:%s)?" % IPATH_ROOTLESS +IPATH_ABEMPTY = u"(?:/%(isegment)s)*" % isegments +IPATH_RE = u"^(?:%s|%s|%s|%s|%s)$" % ( + IPATH_ABEMPTY, + IPATH_ABSOLUTE, + IPATH_NOSCHEME, + IPATH_ROOTLESS, + PATH_EMPTY, +) + +IREGULAR_NAME_RE = IREG_NAME = u"(?:{0}|[{1}])*".format( + u"%[0-9A-Fa-f]{2}", SUB_DELIMITERS_RE + IUNRESERVED_RE +) + +IHOST_RE = IHOST_PATTERN = u"({0}|{1}|{2})".format( + IREG_NAME, + IPv4_RE, + IP_LITERAL_RE, +) + +IUSERINFO_RE = ( + u"^(?:[" + IUNRESERVED_RE + SUB_DELIMITERS_RE + u":]|%s)+" % (PCT_ENCODED) +) + +IFRAGMENT_RE = ( + u"^(?:[/?:@" + + IUNRESERVED_RE + + SUB_DELIMITERS_RE + + u"]|%s)*$" % PCT_ENCODED +) +IQUERY_RE = ( + u"^(?:[/?:@" + + IUNRESERVED_RE + + SUB_DELIMITERS_RE + + IPRIVATE + + u"]|%s)*$" % PCT_ENCODED +) + +IRELATIVE_PART_RE = u"(//%s%s|%s|%s|%s)" % ( + COMPONENT_PATTERN_DICT["authority"], + IPATH_ABEMPTY, + IPATH_ABSOLUTE, + IPATH_NOSCHEME, + PATH_EMPTY, +) + +IHIER_PART_RE = u"(//%s%s|%s|%s|%s)" % ( + COMPONENT_PATTERN_DICT["authority"], + IPATH_ABEMPTY, + IPATH_ABSOLUTE, + IPATH_ROOTLESS, + PATH_EMPTY, +) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rfc3986/api.py b/TTS/Kokoro/.venv/Lib/site-packages/rfc3986/api.py new file mode 100644 index 0000000000000000000000000000000000000000..1e098b34fffbaf12cac3d6edb6edc8885f622fd6 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rfc3986/api.py @@ -0,0 +1,106 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2014 Rackspace +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# 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. +""" +Module containing the simple and functional API for rfc3986. + +This module defines functions and provides access to the public attributes +and classes of rfc3986. +""" + +from .iri import IRIReference +from .parseresult import ParseResult +from .uri import URIReference + + +def uri_reference(uri, encoding="utf-8"): + """Parse a URI string into a URIReference. + + This is a convenience function. You could achieve the same end by using + ``URIReference.from_string(uri)``. + + :param str uri: The URI which needs to be parsed into a reference. + :param str encoding: The encoding of the string provided + :returns: A parsed URI + :rtype: :class:`URIReference` + """ + return URIReference.from_string(uri, encoding) + + +def iri_reference(iri, encoding="utf-8"): + """Parse a IRI string into an IRIReference. + + This is a convenience function. You could achieve the same end by using + ``IRIReference.from_string(iri)``. + + :param str iri: The IRI which needs to be parsed into a reference. + :param str encoding: The encoding of the string provided + :returns: A parsed IRI + :rtype: :class:`IRIReference` + """ + return IRIReference.from_string(iri, encoding) + + +def is_valid_uri(uri, encoding="utf-8", **kwargs): + """Determine if the URI given is valid. + + This is a convenience function. You could use either + ``uri_reference(uri).is_valid()`` or + ``URIReference.from_string(uri).is_valid()`` to achieve the same result. + + :param str uri: The URI to be validated. + :param str encoding: The encoding of the string provided + :param bool require_scheme: Set to ``True`` if you wish to require the + presence of the scheme component. + :param bool require_authority: Set to ``True`` if you wish to require the + presence of the authority component. + :param bool require_path: Set to ``True`` if you wish to require the + presence of the path component. + :param bool require_query: Set to ``True`` if you wish to require the + presence of the query component. + :param bool require_fragment: Set to ``True`` if you wish to require the + presence of the fragment component. + :returns: ``True`` if the URI is valid, ``False`` otherwise. + :rtype: bool + """ + return URIReference.from_string(uri, encoding).is_valid(**kwargs) + + +def normalize_uri(uri, encoding="utf-8"): + """Normalize the given URI. + + This is a convenience function. You could use either + ``uri_reference(uri).normalize().unsplit()`` or + ``URIReference.from_string(uri).normalize().unsplit()`` instead. + + :param str uri: The URI to be normalized. + :param str encoding: The encoding of the string provided + :returns: The normalized URI. + :rtype: str + """ + normalized_reference = URIReference.from_string(uri, encoding).normalize() + return normalized_reference.unsplit() + + +def urlparse(uri, encoding="utf-8"): + """Parse a given URI and return a ParseResult. + + This is a partial replacement of the standard library's urlparse function. + + :param str uri: The URI to be parsed. + :param str encoding: The encoding of the string provided. + :returns: A parsed URI + :rtype: :class:`~rfc3986.parseresult.ParseResult` + """ + return ParseResult.from_string(uri, encoding, strict=False) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rfc3986/builder.py b/TTS/Kokoro/.venv/Lib/site-packages/rfc3986/builder.py new file mode 100644 index 0000000000000000000000000000000000000000..8fc178c6cc390475ba9834a762c40381045f1c41 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rfc3986/builder.py @@ -0,0 +1,389 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2017 Ian Stapleton Cordasco +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# 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. +"""Module containing the logic for the URIBuilder object.""" +from . import compat +from . import normalizers +from . import uri +from . import uri_reference + + +class URIBuilder(object): + """Object to aid in building up a URI Reference from parts. + + .. note:: + + This object should be instantiated by the user, but it's recommended + that it is not provided with arguments. Instead, use the available + method to populate the fields. + + """ + + def __init__( + self, + scheme=None, + userinfo=None, + host=None, + port=None, + path=None, + query=None, + fragment=None, + ): + """Initialize our URI builder. + + :param str scheme: + (optional) + :param str userinfo: + (optional) + :param str host: + (optional) + :param int port: + (optional) + :param str path: + (optional) + :param str query: + (optional) + :param str fragment: + (optional) + """ + self.scheme = scheme + self.userinfo = userinfo + self.host = host + self.port = port + self.path = path + self.query = query + self.fragment = fragment + + def __repr__(self): + """Provide a convenient view of our builder object.""" + formatstr = ( + "URIBuilder(scheme={b.scheme}, userinfo={b.userinfo}, " + "host={b.host}, port={b.port}, path={b.path}, " + "query={b.query}, fragment={b.fragment})" + ) + return formatstr.format(b=self) + + @classmethod + def from_uri(cls, reference): + """Initialize the URI builder from another URI. + + Takes the given URI reference and creates a new URI builder instance + populated with the values from the reference. If given a string it will + try to convert it to a reference before constructing the builder. + """ + if not isinstance(reference, uri.URIReference): + reference = uri_reference(reference) + return cls( + scheme=reference.scheme, + userinfo=reference.userinfo, + host=reference.host, + port=reference.port, + path=reference.path, + query=reference.query, + fragment=reference.fragment, + ) + + def add_scheme(self, scheme): + """Add a scheme to our builder object. + + After normalizing, this will generate a new URIBuilder instance with + the specified scheme and all other attributes the same. + + .. code-block:: python + + >>> URIBuilder().add_scheme('HTTPS') + URIBuilder(scheme='https', userinfo=None, host=None, port=None, + path=None, query=None, fragment=None) + + """ + scheme = normalizers.normalize_scheme(scheme) + return URIBuilder( + scheme=scheme, + userinfo=self.userinfo, + host=self.host, + port=self.port, + path=self.path, + query=self.query, + fragment=self.fragment, + ) + + def add_credentials(self, username, password): + """Add credentials as the userinfo portion of the URI. + + .. code-block:: python + + >>> URIBuilder().add_credentials('root', 's3crete') + URIBuilder(scheme=None, userinfo='root:s3crete', host=None, + port=None, path=None, query=None, fragment=None) + + >>> URIBuilder().add_credentials('root', None) + URIBuilder(scheme=None, userinfo='root', host=None, + port=None, path=None, query=None, fragment=None) + """ + if username is None: + raise ValueError("Username cannot be None") + userinfo = normalizers.normalize_username(username) + + if password is not None: + userinfo = "{}:{}".format( + userinfo, + normalizers.normalize_password(password), + ) + + return URIBuilder( + scheme=self.scheme, + userinfo=userinfo, + host=self.host, + port=self.port, + path=self.path, + query=self.query, + fragment=self.fragment, + ) + + def add_host(self, host): + """Add hostname to the URI. + + .. code-block:: python + + >>> URIBuilder().add_host('google.com') + URIBuilder(scheme=None, userinfo=None, host='google.com', + port=None, path=None, query=None, fragment=None) + + """ + return URIBuilder( + scheme=self.scheme, + userinfo=self.userinfo, + host=normalizers.normalize_host(host), + port=self.port, + path=self.path, + query=self.query, + fragment=self.fragment, + ) + + def add_port(self, port): + """Add port to the URI. + + .. code-block:: python + + >>> URIBuilder().add_port(80) + URIBuilder(scheme=None, userinfo=None, host=None, port='80', + path=None, query=None, fragment=None) + + >>> URIBuilder().add_port(443) + URIBuilder(scheme=None, userinfo=None, host=None, port='443', + path=None, query=None, fragment=None) + + """ + port_int = int(port) + if port_int < 0: + raise ValueError( + "ports are not allowed to be negative. You provided {}".format( + port_int, + ) + ) + if port_int > 65535: + raise ValueError( + "ports are not allowed to be larger than 65535. " + "You provided {}".format( + port_int, + ) + ) + + return URIBuilder( + scheme=self.scheme, + userinfo=self.userinfo, + host=self.host, + port="{}".format(port_int), + path=self.path, + query=self.query, + fragment=self.fragment, + ) + + def add_path(self, path): + """Add a path to the URI. + + .. code-block:: python + + >>> URIBuilder().add_path('sigmavirus24/rfc3985') + URIBuilder(scheme=None, userinfo=None, host=None, port=None, + path='/sigmavirus24/rfc3986', query=None, fragment=None) + + >>> URIBuilder().add_path('/checkout.php') + URIBuilder(scheme=None, userinfo=None, host=None, port=None, + path='/checkout.php', query=None, fragment=None) + + """ + if not path.startswith("/"): + path = "/{}".format(path) + + return URIBuilder( + scheme=self.scheme, + userinfo=self.userinfo, + host=self.host, + port=self.port, + path=normalizers.normalize_path(path), + query=self.query, + fragment=self.fragment, + ) + + def extend_path(self, path): + """Extend the existing path value with the provided value. + + .. versionadded:: 1.5.0 + + .. code-block:: python + + >>> URIBuilder(path="/users").extend_path("/sigmavirus24") + URIBuilder(scheme=None, userinfo=None, host=None, port=None, + path='/users/sigmavirus24', query=None, fragment=None) + + >>> URIBuilder(path="/users/").extend_path("/sigmavirus24") + URIBuilder(scheme=None, userinfo=None, host=None, port=None, + path='/users/sigmavirus24', query=None, fragment=None) + + >>> URIBuilder(path="/users/").extend_path("sigmavirus24") + URIBuilder(scheme=None, userinfo=None, host=None, port=None, + path='/users/sigmavirus24', query=None, fragment=None) + + >>> URIBuilder(path="/users").extend_path("sigmavirus24") + URIBuilder(scheme=None, userinfo=None, host=None, port=None, + path='/users/sigmavirus24', query=None, fragment=None) + + """ + existing_path = self.path or "" + path = "{}/{}".format(existing_path.rstrip("/"), path.lstrip("/")) + + return self.add_path(path) + + def add_query_from(self, query_items): + """Generate and add a query a dictionary or list of tuples. + + .. code-block:: python + + >>> URIBuilder().add_query_from({'a': 'b c'}) + URIBuilder(scheme=None, userinfo=None, host=None, port=None, + path=None, query='a=b+c', fragment=None) + + >>> URIBuilder().add_query_from([('a', 'b c')]) + URIBuilder(scheme=None, userinfo=None, host=None, port=None, + path=None, query='a=b+c', fragment=None) + + """ + query = normalizers.normalize_query(compat.urlencode(query_items)) + + return URIBuilder( + scheme=self.scheme, + userinfo=self.userinfo, + host=self.host, + port=self.port, + path=self.path, + query=query, + fragment=self.fragment, + ) + + def extend_query_with(self, query_items): + """Extend the existing query string with the new query items. + + .. versionadded:: 1.5.0 + + .. code-block:: python + + >>> URIBuilder(query='a=b+c').extend_query_with({'a': 'b c'}) + URIBuilder(scheme=None, userinfo=None, host=None, port=None, + path=None, query='a=b+c&a=b+c', fragment=None) + + >>> URIBuilder(query='a=b+c').extend_query_with([('a', 'b c')]) + URIBuilder(scheme=None, userinfo=None, host=None, port=None, + path=None, query='a=b+c&a=b+c', fragment=None) + """ + original_query_items = compat.parse_qsl(self.query or "") + if not isinstance(query_items, list): + query_items = list(query_items.items()) + + return self.add_query_from(original_query_items + query_items) + + def add_query(self, query): + """Add a pre-formated query string to the URI. + + .. code-block:: python + + >>> URIBuilder().add_query('a=b&c=d') + URIBuilder(scheme=None, userinfo=None, host=None, port=None, + path=None, query='a=b&c=d', fragment=None) + + """ + return URIBuilder( + scheme=self.scheme, + userinfo=self.userinfo, + host=self.host, + port=self.port, + path=self.path, + query=normalizers.normalize_query(query), + fragment=self.fragment, + ) + + def add_fragment(self, fragment): + """Add a fragment to the URI. + + .. code-block:: python + + >>> URIBuilder().add_fragment('section-2.6.1') + URIBuilder(scheme=None, userinfo=None, host=None, port=None, + path=None, query=None, fragment='section-2.6.1') + + """ + return URIBuilder( + scheme=self.scheme, + userinfo=self.userinfo, + host=self.host, + port=self.port, + path=self.path, + query=self.query, + fragment=normalizers.normalize_fragment(fragment), + ) + + def finalize(self): + """Create a URIReference from our builder. + + .. code-block:: python + + >>> URIBuilder().add_scheme('https').add_host('github.com' + ... ).add_path('sigmavirus24/rfc3986').finalize().unsplit() + 'https://github.com/sigmavirus24/rfc3986' + + >>> URIBuilder().add_scheme('https').add_host('github.com' + ... ).add_path('sigmavirus24/rfc3986').add_credentials( + ... 'sigmavirus24', 'not-re@l').finalize().unsplit() + 'https://sigmavirus24:not-re%40l@github.com/sigmavirus24/rfc3986' + + """ + return uri.URIReference( + self.scheme, + normalizers.normalize_authority( + (self.userinfo, self.host, self.port) + ), + self.path, + self.query, + self.fragment, + ) + + def geturl(self): + """Generate the URL from this builder. + + .. versionadded:: 1.5.0 + + This is an alternative to calling :meth:`finalize` and keeping the + :class:`rfc3986.uri.URIReference` around. + """ + return self.finalize().unsplit() diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rfc3986/compat.py b/TTS/Kokoro/.venv/Lib/site-packages/rfc3986/compat.py new file mode 100644 index 0000000000000000000000000000000000000000..83e5c784b5cbc6e65def6a3b0347ad12f455e639 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rfc3986/compat.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2014 Rackspace +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# 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. +"""Compatibility module for Python 2 and 3 support.""" +import sys + +try: + from urllib.parse import quote as urlquote +except ImportError: # Python 2.x + from urllib import quote as urlquote + +try: + from urllib.parse import parse_qsl +except ImportError: # Python 2.x + from urlparse import parse_qsl + +try: + from urllib.parse import urlencode +except ImportError: # Python 2.x + from urllib import urlencode + +__all__ = ( + "to_bytes", + "to_str", + "urlquote", + "urlencode", + "parse_qsl", +) + +PY3 = (3, 0) <= sys.version_info < (4, 0) +PY2 = (2, 6) <= sys.version_info < (2, 8) + + +if PY3: + unicode = str # Python 3.x + + +def to_str(b, encoding="utf-8"): + """Ensure that b is text in the specified encoding.""" + if hasattr(b, "decode") and not isinstance(b, unicode): + b = b.decode(encoding) + return b + + +def to_bytes(s, encoding="utf-8"): + """Ensure that s is converted to bytes from the encoding.""" + if hasattr(s, "encode") and not isinstance(s, bytes): + s = s.encode(encoding) + return s diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rfc3986/exceptions.py b/TTS/Kokoro/.venv/Lib/site-packages/rfc3986/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..b117bc9ca21a04878370170b57ed7adad27a59c8 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rfc3986/exceptions.py @@ -0,0 +1,124 @@ +# -*- coding: utf-8 -*- +"""Exceptions module for rfc3986.""" + +from . import compat + + +class RFC3986Exception(Exception): + """Base class for all rfc3986 exception classes.""" + + pass + + +class InvalidAuthority(RFC3986Exception): + """Exception when the authority string is invalid.""" + + def __init__(self, authority): + """Initialize the exception with the invalid authority.""" + super(InvalidAuthority, self).__init__( + u"The authority ({0}) is not valid.".format( + compat.to_str(authority) + ) + ) + + +class InvalidPort(RFC3986Exception): + """Exception when the port is invalid.""" + + def __init__(self, port): + """Initialize the exception with the invalid port.""" + super(InvalidPort, self).__init__( + 'The port ("{0}") is not valid.'.format(port) + ) + + +class ResolutionError(RFC3986Exception): + """Exception to indicate a failure to resolve a URI.""" + + def __init__(self, uri): + """Initialize the error with the failed URI.""" + super(ResolutionError, self).__init__( + "{0} is not an absolute URI.".format(uri.unsplit()) + ) + + +class ValidationError(RFC3986Exception): + """Exception raised during Validation of a URI.""" + + pass + + +class MissingComponentError(ValidationError): + """Exception raised when a required component is missing.""" + + def __init__(self, uri, *component_names): + """Initialize the error with the missing component name.""" + verb = "was" + if len(component_names) > 1: + verb = "were" + + self.uri = uri + self.components = sorted(component_names) + components = ", ".join(self.components) + super(MissingComponentError, self).__init__( + "{} {} required but missing".format(components, verb), + uri, + self.components, + ) + + +class UnpermittedComponentError(ValidationError): + """Exception raised when a component has an unpermitted value.""" + + def __init__(self, component_name, component_value, allowed_values): + """Initialize the error with the unpermitted component.""" + super(UnpermittedComponentError, self).__init__( + "{} was required to be one of {!r} but was {!r}".format( + component_name, + list(sorted(allowed_values)), + component_value, + ), + component_name, + component_value, + allowed_values, + ) + self.component_name = component_name + self.component_value = component_value + self.allowed_values = allowed_values + + +class PasswordForbidden(ValidationError): + """Exception raised when a URL has a password in the userinfo section.""" + + def __init__(self, uri): + """Initialize the error with the URI that failed validation.""" + unsplit = getattr(uri, "unsplit", lambda: uri) + super(PasswordForbidden, self).__init__( + '"{}" contained a password when validation forbade it'.format( + unsplit() + ) + ) + self.uri = uri + + +class InvalidComponentsError(ValidationError): + """Exception raised when one or more components are invalid.""" + + def __init__(self, uri, *component_names): + """Initialize the error with the invalid component name(s).""" + verb = "was" + if len(component_names) > 1: + verb = "were" + + self.uri = uri + self.components = sorted(component_names) + components = ", ".join(self.components) + super(InvalidComponentsError, self).__init__( + "{} {} found to be invalid".format(components, verb), + uri, + self.components, + ) + + +class MissingDependencyError(RFC3986Exception): + """Exception raised when an IRI is encoded without the 'idna' module.""" diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rfc3986/iri.py b/TTS/Kokoro/.venv/Lib/site-packages/rfc3986/iri.py new file mode 100644 index 0000000000000000000000000000000000000000..540aa7bc24e404f0211b889b6c64774aa9b79193 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rfc3986/iri.py @@ -0,0 +1,162 @@ +"""Module containing the implementation of the IRIReference class.""" +# -*- coding: utf-8 -*- +# Copyright (c) 2014 Rackspace +# Copyright (c) 2015 Ian Stapleton Cordasco +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# 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. +from collections import namedtuple + +from . import compat +from . import exceptions +from . import misc +from . import normalizers +from . import uri + + +try: + import idna +except ImportError: # pragma: no cover + idna = None + + +class IRIReference( + namedtuple("IRIReference", misc.URI_COMPONENTS), uri.URIMixin +): + """Immutable object representing a parsed IRI Reference. + + Can be encoded into an URIReference object via the procedure + specified in RFC 3987 Section 3.1 + + .. note:: + The IRI submodule is a new interface and may possibly change in + the future. Check for changes to the interface when upgrading. + """ + + slots = () + + def __new__( + cls, scheme, authority, path, query, fragment, encoding="utf-8" + ): + """Create a new IRIReference.""" + ref = super(IRIReference, cls).__new__( + cls, + scheme or None, + authority or None, + path or None, + query, + fragment, + ) + ref.encoding = encoding + return ref + + def __eq__(self, other): + """Compare this reference to another.""" + other_ref = other + if isinstance(other, tuple): + other_ref = self.__class__(*other) + elif not isinstance(other, IRIReference): + try: + other_ref = self.__class__.from_string(other) + except TypeError: + raise TypeError( + "Unable to compare {0}() to {1}()".format( + type(self).__name__, type(other).__name__ + ) + ) + + # See http://tools.ietf.org/html/rfc3986#section-6.2 + return tuple(self) == tuple(other_ref) + + def _match_subauthority(self): + return misc.ISUBAUTHORITY_MATCHER.match(self.authority) + + @classmethod + def from_string(cls, iri_string, encoding="utf-8"): + """Parse a IRI reference from the given unicode IRI string. + + :param str iri_string: Unicode IRI to be parsed into a reference. + :param str encoding: The encoding of the string provided + :returns: :class:`IRIReference` or subclass thereof + """ + iri_string = compat.to_str(iri_string, encoding) + + split_iri = misc.IRI_MATCHER.match(iri_string).groupdict() + return cls( + split_iri["scheme"], + split_iri["authority"], + normalizers.encode_component(split_iri["path"], encoding), + normalizers.encode_component(split_iri["query"], encoding), + normalizers.encode_component(split_iri["fragment"], encoding), + encoding, + ) + + def encode(self, idna_encoder=None): # noqa: C901 + """Encode an IRIReference into a URIReference instance. + + If the ``idna`` module is installed or the ``rfc3986[idna]`` + extra is used then unicode characters in the IRI host + component will be encoded with IDNA2008. + + :param idna_encoder: + Function that encodes each part of the host component + If not given will raise an exception if the IRI + contains a host component. + :rtype: uri.URIReference + :returns: A URI reference + """ + authority = self.authority + if authority: + if idna_encoder is None: + if idna is None: # pragma: no cover + raise exceptions.MissingDependencyError( + "Could not import the 'idna' module " + "and the IRI hostname requires encoding" + ) + + def idna_encoder(name): + if any(ord(c) > 128 for c in name): + try: + return idna.encode( + name.lower(), strict=True, std3_rules=True + ) + except idna.IDNAError: + raise exceptions.InvalidAuthority(self.authority) + return name + + authority = "" + if self.host: + authority = ".".join( + [ + compat.to_str(idna_encoder(part)) + for part in self.host.split(".") + ] + ) + + if self.userinfo is not None: + authority = ( + normalizers.encode_component(self.userinfo, self.encoding) + + "@" + + authority + ) + + if self.port is not None: + authority += ":" + str(self.port) + + return uri.URIReference( + self.scheme, + authority, + path=self.path, + query=self.query, + fragment=self.fragment, + encoding=self.encoding, + ) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rfc3986/misc.py b/TTS/Kokoro/.venv/Lib/site-packages/rfc3986/misc.py new file mode 100644 index 0000000000000000000000000000000000000000..338b18794c8cc4e094a5ebed19b63c46ac250620 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rfc3986/misc.py @@ -0,0 +1,135 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2014 Rackspace +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# 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. +""" +Module containing compiled regular expressions and constants. + +This module contains important constants, patterns, and compiled regular +expressions for parsing and validating URIs and their components. +""" + +import re + +from . import abnf_regexp + +# These are enumerated for the named tuple used as a superclass of +# URIReference +URI_COMPONENTS = ["scheme", "authority", "path", "query", "fragment"] + +important_characters = { + "generic_delimiters": abnf_regexp.GENERIC_DELIMITERS, + "sub_delimiters": abnf_regexp.SUB_DELIMITERS, + # We need to escape the '*' in this case + "re_sub_delimiters": abnf_regexp.SUB_DELIMITERS_RE, + "unreserved_chars": abnf_regexp.UNRESERVED_CHARS, + # We need to escape the '-' in this case: + "re_unreserved": abnf_regexp.UNRESERVED_RE, +} + +# For details about delimiters and reserved characters, see: +# http://tools.ietf.org/html/rfc3986#section-2.2 +GENERIC_DELIMITERS = abnf_regexp.GENERIC_DELIMITERS_SET +SUB_DELIMITERS = abnf_regexp.SUB_DELIMITERS_SET +RESERVED_CHARS = abnf_regexp.RESERVED_CHARS_SET +# For details about unreserved characters, see: +# http://tools.ietf.org/html/rfc3986#section-2.3 +UNRESERVED_CHARS = abnf_regexp.UNRESERVED_CHARS_SET +NON_PCT_ENCODED = abnf_regexp.NON_PCT_ENCODED_SET + +URI_MATCHER = re.compile(abnf_regexp.URL_PARSING_RE) + +SUBAUTHORITY_MATCHER = re.compile( + ( + "^(?:(?P{0})@)?" # userinfo + "(?P{1})" # host + ":?(?P{2})?$" # port + ).format( + abnf_regexp.USERINFO_RE, abnf_regexp.HOST_PATTERN, abnf_regexp.PORT_RE + ) +) + + +HOST_MATCHER = re.compile("^" + abnf_regexp.HOST_RE + "$") +IPv4_MATCHER = re.compile("^" + abnf_regexp.IPv4_RE + "$") +IPv6_MATCHER = re.compile(r"^\[" + abnf_regexp.IPv6_ADDRZ_RFC4007_RE + r"\]$") + +# Used by host validator +IPv6_NO_RFC4007_MATCHER = re.compile( + r"^\[%s\]$" % (abnf_regexp.IPv6_ADDRZ_RE) +) + +# Matcher used to validate path components +PATH_MATCHER = re.compile(abnf_regexp.PATH_RE) + + +# ################################## +# Query and Fragment Matcher Section +# ################################## + +QUERY_MATCHER = re.compile(abnf_regexp.QUERY_RE) + +FRAGMENT_MATCHER = QUERY_MATCHER + +# Scheme validation, see: http://tools.ietf.org/html/rfc3986#section-3.1 +SCHEME_MATCHER = re.compile("^{0}$".format(abnf_regexp.SCHEME_RE)) + +RELATIVE_REF_MATCHER = re.compile( + r"^%s(\?%s)?(#%s)?$" + % ( + abnf_regexp.RELATIVE_PART_RE, + abnf_regexp.QUERY_RE, + abnf_regexp.FRAGMENT_RE, + ) +) + +# See http://tools.ietf.org/html/rfc3986#section-4.3 +ABSOLUTE_URI_MATCHER = re.compile( + r"^%s:%s(\?%s)?$" + % ( + abnf_regexp.COMPONENT_PATTERN_DICT["scheme"], + abnf_regexp.HIER_PART_RE, + abnf_regexp.QUERY_RE[1:-1], + ) +) + +# ############### +# IRIs / RFC 3987 +# ############### + +IRI_MATCHER = re.compile(abnf_regexp.URL_PARSING_RE, re.UNICODE) + +ISUBAUTHORITY_MATCHER = re.compile( + ( + u"^(?:(?P{0})@)?" # iuserinfo + u"(?P{1})" # ihost + u":?(?P{2})?$" # port + ).format( + abnf_regexp.IUSERINFO_RE, abnf_regexp.IHOST_RE, abnf_regexp.PORT_RE + ), + re.UNICODE, +) + + +# Path merger as defined in http://tools.ietf.org/html/rfc3986#section-5.2.3 +def merge_paths(base_uri, relative_path): + """Merge a base URI's path with a relative URI's path.""" + if base_uri.path is None and base_uri.authority is not None: + return "/" + relative_path + else: + path = base_uri.path or "" + index = path.rfind("/") + return path[:index] + "/" + relative_path + + +UseExisting = object() diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rfc3986/normalizers.py b/TTS/Kokoro/.venv/Lib/site-packages/rfc3986/normalizers.py new file mode 100644 index 0000000000000000000000000000000000000000..0d702b6d4c9e978195b0f6e19393d448315e9ba5 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rfc3986/normalizers.py @@ -0,0 +1,172 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2014 Rackspace +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# 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. +"""Module with functions to normalize components.""" +import re + +from . import compat +from . import misc + + +def normalize_scheme(scheme): + """Normalize the scheme component.""" + return scheme.lower() + + +def normalize_authority(authority): + """Normalize an authority tuple to a string.""" + userinfo, host, port = authority + result = "" + if userinfo: + result += normalize_percent_characters(userinfo) + "@" + if host: + result += normalize_host(host) + if port: + result += ":" + port + return result + + +def normalize_username(username): + """Normalize a username to make it safe to include in userinfo.""" + return compat.urlquote(username) + + +def normalize_password(password): + """Normalize a password to make safe for userinfo.""" + return compat.urlquote(password) + + +def normalize_host(host): + """Normalize a host string.""" + if misc.IPv6_MATCHER.match(host): + percent = host.find("%") + if percent != -1: + percent_25 = host.find("%25") + + # Replace RFC 4007 IPv6 Zone ID delimiter '%' with '%25' + # from RFC 6874. If the host is '[%25]' then we + # assume RFC 4007 and normalize to '[%2525]' + if ( + percent_25 == -1 + or percent < percent_25 + or (percent == percent_25 and percent_25 == len(host) - 4) + ): + host = host.replace("%", "%25", 1) + + # Don't normalize the casing of the Zone ID + return host[:percent].lower() + host[percent:] + + return host.lower() + + +def normalize_path(path): + """Normalize the path string.""" + if not path: + return path + + path = normalize_percent_characters(path) + return remove_dot_segments(path) + + +def normalize_query(query): + """Normalize the query string.""" + if not query: + return query + return normalize_percent_characters(query) + + +def normalize_fragment(fragment): + """Normalize the fragment string.""" + if not fragment: + return fragment + return normalize_percent_characters(fragment) + + +PERCENT_MATCHER = re.compile("%[A-Fa-f0-9]{2}") + + +def normalize_percent_characters(s): + """All percent characters should be upper-cased. + + For example, ``"%3afoo%DF%ab"`` should be turned into ``"%3Afoo%DF%AB"``. + """ + matches = set(PERCENT_MATCHER.findall(s)) + for m in matches: + if not m.isupper(): + s = s.replace(m, m.upper()) + return s + + +def remove_dot_segments(s): + """Remove dot segments from the string. + + See also Section 5.2.4 of :rfc:`3986`. + """ + # See http://tools.ietf.org/html/rfc3986#section-5.2.4 for pseudo-code + segments = s.split("/") # Turn the path into a list of segments + output = [] # Initialize the variable to use to store output + + for segment in segments: + # '.' is the current directory, so ignore it, it is superfluous + if segment == ".": + continue + # Anything other than '..', should be appended to the output + elif segment != "..": + output.append(segment) + # In this case segment == '..', if we can, we should pop the last + # element + elif output: + output.pop() + + # If the path starts with '/' and the output is empty or the first string + # is non-empty + if s.startswith("/") and (not output or output[0]): + output.insert(0, "") + + # If the path starts with '/.' or '/..' ensure we add one more empty + # string to add a trailing '/' + if s.endswith(("/.", "/..")): + output.append("") + + return "/".join(output) + + +def encode_component(uri_component, encoding): + """Encode the specific component in the provided encoding.""" + if uri_component is None: + return uri_component + + # Try to see if the component we're encoding is already percent-encoded + # so we can skip all '%' characters but still encode all others. + percent_encodings = len( + PERCENT_MATCHER.findall(compat.to_str(uri_component, encoding)) + ) + + uri_bytes = compat.to_bytes(uri_component, encoding) + is_percent_encoded = percent_encodings == uri_bytes.count(b"%") + + encoded_uri = bytearray() + + for i in range(0, len(uri_bytes)): + # Will return a single character bytestring on both Python 2 & 3 + byte = uri_bytes[i : i + 1] + byte_ord = ord(byte) + if (is_percent_encoded and byte == b"%") or ( + byte_ord < 128 and byte.decode() in misc.NON_PCT_ENCODED + ): + encoded_uri.extend(byte) + continue + encoded_uri.extend("%{0:02x}".format(byte_ord).encode().upper()) + + return encoded_uri.decode(encoding) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rfc3986/parseresult.py b/TTS/Kokoro/.venv/Lib/site-packages/rfc3986/parseresult.py new file mode 100644 index 0000000000000000000000000000000000000000..8887e8f1179d907c9ae05d930e2b236b333a6252 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rfc3986/parseresult.py @@ -0,0 +1,479 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2015 Ian Stapleton Cordasco +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# 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. +"""Module containing the urlparse compatibility logic.""" +from collections import namedtuple + +from . import compat +from . import exceptions +from . import misc +from . import normalizers +from . import uri + +__all__ = ("ParseResult", "ParseResultBytes") + +PARSED_COMPONENTS = ( + "scheme", + "userinfo", + "host", + "port", + "path", + "query", + "fragment", +) + + +class ParseResultMixin(object): + def _generate_authority(self, attributes): + # I swear I did not align the comparisons below. That's just how they + # happened to align based on pep8 and attribute lengths. + userinfo, host, port = ( + attributes[p] for p in ("userinfo", "host", "port") + ) + if ( + self.userinfo != userinfo + or self.host != host + or self.port != port + ): + if port: + port = "{0}".format(port) + return normalizers.normalize_authority( + ( + compat.to_str(userinfo, self.encoding), + compat.to_str(host, self.encoding), + port, + ) + ) + if isinstance(self.authority, bytes): + return self.authority.decode("utf-8") + return self.authority + + def geturl(self): + """Shim to match the standard library method.""" + return self.unsplit() + + @property + def hostname(self): + """Shim to match the standard library.""" + return self.host + + @property + def netloc(self): + """Shim to match the standard library.""" + return self.authority + + @property + def params(self): + """Shim to match the standard library.""" + return self.query + + +class ParseResult( + namedtuple("ParseResult", PARSED_COMPONENTS), ParseResultMixin +): + """Implementation of urlparse compatibility class. + + This uses the URIReference logic to handle compatibility with the + urlparse.ParseResult class. + """ + + slots = () + + def __new__( + cls, + scheme, + userinfo, + host, + port, + path, + query, + fragment, + uri_ref, + encoding="utf-8", + ): + """Create a new ParseResult.""" + parse_result = super(ParseResult, cls).__new__( + cls, + scheme or None, + userinfo or None, + host, + port or None, + path or None, + query, + fragment, + ) + parse_result.encoding = encoding + parse_result.reference = uri_ref + return parse_result + + @classmethod + def from_parts( + cls, + scheme=None, + userinfo=None, + host=None, + port=None, + path=None, + query=None, + fragment=None, + encoding="utf-8", + ): + """Create a ParseResult instance from its parts.""" + authority = "" + if userinfo is not None: + authority += userinfo + "@" + if host is not None: + authority += host + if port is not None: + authority += ":{0}".format(port) + uri_ref = uri.URIReference( + scheme=scheme, + authority=authority, + path=path, + query=query, + fragment=fragment, + encoding=encoding, + ).normalize() + userinfo, host, port = authority_from(uri_ref, strict=True) + return cls( + scheme=uri_ref.scheme, + userinfo=userinfo, + host=host, + port=port, + path=uri_ref.path, + query=uri_ref.query, + fragment=uri_ref.fragment, + uri_ref=uri_ref, + encoding=encoding, + ) + + @classmethod + def from_string( + cls, uri_string, encoding="utf-8", strict=True, lazy_normalize=True + ): + """Parse a URI from the given unicode URI string. + + :param str uri_string: Unicode URI to be parsed into a reference. + :param str encoding: The encoding of the string provided + :param bool strict: Parse strictly according to :rfc:`3986` if True. + If False, parse similarly to the standard library's urlparse + function. + :returns: :class:`ParseResult` or subclass thereof + """ + reference = uri.URIReference.from_string(uri_string, encoding) + if not lazy_normalize: + reference = reference.normalize() + userinfo, host, port = authority_from(reference, strict) + + return cls( + scheme=reference.scheme, + userinfo=userinfo, + host=host, + port=port, + path=reference.path, + query=reference.query, + fragment=reference.fragment, + uri_ref=reference, + encoding=encoding, + ) + + @property + def authority(self): + """Return the normalized authority.""" + return self.reference.authority + + def copy_with( + self, + scheme=misc.UseExisting, + userinfo=misc.UseExisting, + host=misc.UseExisting, + port=misc.UseExisting, + path=misc.UseExisting, + query=misc.UseExisting, + fragment=misc.UseExisting, + ): + """Create a copy of this instance replacing with specified parts.""" + attributes = zip( + PARSED_COMPONENTS, + (scheme, userinfo, host, port, path, query, fragment), + ) + attrs_dict = {} + for name, value in attributes: + if value is misc.UseExisting: + value = getattr(self, name) + attrs_dict[name] = value + authority = self._generate_authority(attrs_dict) + ref = self.reference.copy_with( + scheme=attrs_dict["scheme"], + authority=authority, + path=attrs_dict["path"], + query=attrs_dict["query"], + fragment=attrs_dict["fragment"], + ) + return ParseResult(uri_ref=ref, encoding=self.encoding, **attrs_dict) + + def encode(self, encoding=None): + """Convert to an instance of ParseResultBytes.""" + encoding = encoding or self.encoding + attrs = dict( + zip( + PARSED_COMPONENTS, + ( + attr.encode(encoding) if hasattr(attr, "encode") else attr + for attr in self + ), + ) + ) + return ParseResultBytes( + uri_ref=self.reference, encoding=encoding, **attrs + ) + + def unsplit(self, use_idna=False): + """Create a URI string from the components. + + :returns: The parsed URI reconstituted as a string. + :rtype: str + """ + parse_result = self + if use_idna and self.host: + hostbytes = self.host.encode("idna") + host = hostbytes.decode(self.encoding) + parse_result = self.copy_with(host=host) + return parse_result.reference.unsplit() + + +class ParseResultBytes( + namedtuple("ParseResultBytes", PARSED_COMPONENTS), ParseResultMixin +): + """Compatibility shim for the urlparse.ParseResultBytes object.""" + + def __new__( + cls, + scheme, + userinfo, + host, + port, + path, + query, + fragment, + uri_ref, + encoding="utf-8", + lazy_normalize=True, + ): + """Create a new ParseResultBytes instance.""" + parse_result = super(ParseResultBytes, cls).__new__( + cls, + scheme or None, + userinfo or None, + host, + port or None, + path or None, + query or None, + fragment or None, + ) + parse_result.encoding = encoding + parse_result.reference = uri_ref + parse_result.lazy_normalize = lazy_normalize + return parse_result + + @classmethod + def from_parts( + cls, + scheme=None, + userinfo=None, + host=None, + port=None, + path=None, + query=None, + fragment=None, + encoding="utf-8", + lazy_normalize=True, + ): + """Create a ParseResult instance from its parts.""" + authority = "" + if userinfo is not None: + authority += userinfo + "@" + if host is not None: + authority += host + if port is not None: + authority += ":{0}".format(int(port)) + uri_ref = uri.URIReference( + scheme=scheme, + authority=authority, + path=path, + query=query, + fragment=fragment, + encoding=encoding, + ) + if not lazy_normalize: + uri_ref = uri_ref.normalize() + to_bytes = compat.to_bytes + userinfo, host, port = authority_from(uri_ref, strict=True) + return cls( + scheme=to_bytes(scheme, encoding), + userinfo=to_bytes(userinfo, encoding), + host=to_bytes(host, encoding), + port=port, + path=to_bytes(path, encoding), + query=to_bytes(query, encoding), + fragment=to_bytes(fragment, encoding), + uri_ref=uri_ref, + encoding=encoding, + lazy_normalize=lazy_normalize, + ) + + @classmethod + def from_string( + cls, uri_string, encoding="utf-8", strict=True, lazy_normalize=True + ): + """Parse a URI from the given unicode URI string. + + :param str uri_string: Unicode URI to be parsed into a reference. + :param str encoding: The encoding of the string provided + :param bool strict: Parse strictly according to :rfc:`3986` if True. + If False, parse similarly to the standard library's urlparse + function. + :returns: :class:`ParseResultBytes` or subclass thereof + """ + reference = uri.URIReference.from_string(uri_string, encoding) + if not lazy_normalize: + reference = reference.normalize() + userinfo, host, port = authority_from(reference, strict) + + to_bytes = compat.to_bytes + return cls( + scheme=to_bytes(reference.scheme, encoding), + userinfo=to_bytes(userinfo, encoding), + host=to_bytes(host, encoding), + port=port, + path=to_bytes(reference.path, encoding), + query=to_bytes(reference.query, encoding), + fragment=to_bytes(reference.fragment, encoding), + uri_ref=reference, + encoding=encoding, + lazy_normalize=lazy_normalize, + ) + + @property + def authority(self): + """Return the normalized authority.""" + return self.reference.authority.encode(self.encoding) + + def copy_with( + self, + scheme=misc.UseExisting, + userinfo=misc.UseExisting, + host=misc.UseExisting, + port=misc.UseExisting, + path=misc.UseExisting, + query=misc.UseExisting, + fragment=misc.UseExisting, + lazy_normalize=True, + ): + """Create a copy of this instance replacing with specified parts.""" + attributes = zip( + PARSED_COMPONENTS, + (scheme, userinfo, host, port, path, query, fragment), + ) + attrs_dict = {} + for name, value in attributes: + if value is misc.UseExisting: + value = getattr(self, name) + if not isinstance(value, bytes) and hasattr(value, "encode"): + value = value.encode(self.encoding) + attrs_dict[name] = value + authority = self._generate_authority(attrs_dict) + to_str = compat.to_str + ref = self.reference.copy_with( + scheme=to_str(attrs_dict["scheme"], self.encoding), + authority=to_str(authority, self.encoding), + path=to_str(attrs_dict["path"], self.encoding), + query=to_str(attrs_dict["query"], self.encoding), + fragment=to_str(attrs_dict["fragment"], self.encoding), + ) + if not lazy_normalize: + ref = ref.normalize() + return ParseResultBytes( + uri_ref=ref, + encoding=self.encoding, + lazy_normalize=lazy_normalize, + **attrs_dict + ) + + def unsplit(self, use_idna=False): + """Create a URI bytes object from the components. + + :returns: The parsed URI reconstituted as a string. + :rtype: bytes + """ + parse_result = self + if use_idna and self.host: + # self.host is bytes, to encode to idna, we need to decode it + # first + host = self.host.decode(self.encoding) + hostbytes = host.encode("idna") + parse_result = self.copy_with(host=hostbytes) + if self.lazy_normalize: + parse_result = parse_result.copy_with(lazy_normalize=False) + uri = parse_result.reference.unsplit() + return uri.encode(self.encoding) + + +def split_authority(authority): + # Initialize our expected return values + userinfo = host = port = None + # Initialize an extra var we may need to use + extra_host = None + # Set-up rest in case there is no userinfo portion + rest = authority + + if "@" in authority: + userinfo, rest = authority.rsplit("@", 1) + + # Handle IPv6 host addresses + if rest.startswith("["): + host, rest = rest.split("]", 1) + host += "]" + + if ":" in rest: + extra_host, port = rest.split(":", 1) + elif not host and rest: + host = rest + + if extra_host and not host: + host = extra_host + + return userinfo, host, port + + +def authority_from(reference, strict): + try: + subauthority = reference.authority_info() + except exceptions.InvalidAuthority: + if strict: + raise + userinfo, host, port = split_authority(reference.authority) + else: + # Thanks to Richard Barrell for this idea: + # https://twitter.com/0x2ba22e11/status/617338811975139328 + userinfo, host, port = ( + subauthority.get(p) for p in ("userinfo", "host", "port") + ) + + if port: + try: + port = int(port) + except ValueError: + raise exceptions.InvalidPort(port) + return userinfo, host, port diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rfc3986/uri.py b/TTS/Kokoro/.venv/Lib/site-packages/rfc3986/uri.py new file mode 100644 index 0000000000000000000000000000000000000000..75c617d2a55a09d84a6fa75360360536481d61e4 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rfc3986/uri.py @@ -0,0 +1,161 @@ +"""Module containing the implementation of the URIReference class.""" +# -*- coding: utf-8 -*- +# Copyright (c) 2014 Rackspace +# Copyright (c) 2015 Ian Stapleton Cordasco +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# 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. +from collections import namedtuple + +from . import compat +from . import misc +from . import normalizers +from ._mixin import URIMixin + + +class URIReference(namedtuple("URIReference", misc.URI_COMPONENTS), URIMixin): + """Immutable object representing a parsed URI Reference. + + .. note:: + + This class is not intended to be directly instantiated by the user. + + This object exposes attributes for the following components of a + URI: + + - scheme + - authority + - path + - query + - fragment + + .. attribute:: scheme + + The scheme that was parsed for the URI Reference. For example, + ``http``, ``https``, ``smtp``, ``imap``, etc. + + .. attribute:: authority + + Component of the URI that contains the user information, host, + and port sub-components. For example, + ``google.com``, ``127.0.0.1:5000``, ``username@[::1]``, + ``username:password@example.com:443``, etc. + + .. attribute:: path + + The path that was parsed for the given URI Reference. For example, + ``/``, ``/index.php``, etc. + + .. attribute:: query + + The query component for a given URI Reference. For example, ``a=b``, + ``a=b%20c``, ``a=b+c``, ``a=b,c=d,e=%20f``, etc. + + .. attribute:: fragment + + The fragment component of a URI. For example, ``section-3.1``. + + This class also provides extra attributes for easier access to information + like the subcomponents of the authority component. + + .. attribute:: userinfo + + The user information parsed from the authority. + + .. attribute:: host + + The hostname, IPv4, or IPv6 address parsed from the authority. + + .. attribute:: port + + The port parsed from the authority. + """ + + slots = () + + def __new__( + cls, scheme, authority, path, query, fragment, encoding="utf-8" + ): + """Create a new URIReference.""" + ref = super(URIReference, cls).__new__( + cls, + scheme or None, + authority or None, + path or None, + query, + fragment, + ) + ref.encoding = encoding + return ref + + __hash__ = tuple.__hash__ + + def __eq__(self, other): + """Compare this reference to another.""" + other_ref = other + if isinstance(other, tuple): + other_ref = URIReference(*other) + elif not isinstance(other, URIReference): + try: + other_ref = URIReference.from_string(other) + except TypeError: + raise TypeError( + "Unable to compare URIReference() to {0}()".format( + type(other).__name__ + ) + ) + + # See http://tools.ietf.org/html/rfc3986#section-6.2 + naive_equality = tuple(self) == tuple(other_ref) + return naive_equality or self.normalized_equality(other_ref) + + def normalize(self): + """Normalize this reference as described in Section 6.2.2. + + This is not an in-place normalization. Instead this creates a new + URIReference. + + :returns: A new reference object with normalized components. + :rtype: URIReference + """ + # See http://tools.ietf.org/html/rfc3986#section-6.2.2 for logic in + # this method. + return URIReference( + normalizers.normalize_scheme(self.scheme or ""), + normalizers.normalize_authority( + (self.userinfo, self.host, self.port) + ), + normalizers.normalize_path(self.path or ""), + normalizers.normalize_query(self.query), + normalizers.normalize_fragment(self.fragment), + self.encoding, + ) + + @classmethod + def from_string(cls, uri_string, encoding="utf-8"): + """Parse a URI reference from the given unicode URI string. + + :param str uri_string: Unicode URI to be parsed into a reference. + :param str encoding: The encoding of the string provided + :returns: :class:`URIReference` or subclass thereof + """ + uri_string = compat.to_str(uri_string, encoding) + + split_uri = misc.URI_MATCHER.match(uri_string).groupdict() + return cls( + split_uri["scheme"], + split_uri["authority"], + normalizers.encode_component(split_uri["path"], encoding), + normalizers.encode_component(split_uri["query"], encoding), + normalizers.encode_component(split_uri["fragment"], encoding), + encoding, + ) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rfc3986/validators.py b/TTS/Kokoro/.venv/Lib/site-packages/rfc3986/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..f375248828d7aaf5366277db1d7fddfda8478ece --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rfc3986/validators.py @@ -0,0 +1,447 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2017 Ian Stapleton Cordasco +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# 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. +"""Module containing the validation logic for rfc3986.""" +from . import exceptions +from . import misc +from . import normalizers + + +class Validator(object): + """Object used to configure validation of all objects in rfc3986. + + .. versionadded:: 1.0 + + Example usage:: + + >>> from rfc3986 import api, validators + >>> uri = api.uri_reference('https://github.com/') + >>> validator = validators.Validator().require_presence_of( + ... 'scheme', 'host', 'path', + ... ).allow_schemes( + ... 'http', 'https', + ... ).allow_hosts( + ... '127.0.0.1', 'github.com', + ... ) + >>> validator.validate(uri) + >>> invalid_uri = rfc3986.uri_reference('imap://mail.google.com') + >>> validator.validate(invalid_uri) + Traceback (most recent call last): + ... + rfc3986.exceptions.MissingComponentError: ('path was required but + missing', URIReference(scheme=u'imap', authority=u'mail.google.com', + path=None, query=None, fragment=None), ['path']) + + """ + + COMPONENT_NAMES = frozenset( + ["scheme", "userinfo", "host", "port", "path", "query", "fragment"] + ) + + def __init__(self): + """Initialize our default validations.""" + self.allowed_schemes = set() + self.allowed_hosts = set() + self.allowed_ports = set() + self.allow_password = True + self.required_components = { + "scheme": False, + "userinfo": False, + "host": False, + "port": False, + "path": False, + "query": False, + "fragment": False, + } + self.validated_components = self.required_components.copy() + + def allow_schemes(self, *schemes): + """Require the scheme to be one of the provided schemes. + + .. versionadded:: 1.0 + + :param schemes: + Schemes, without ``://`` that are allowed. + :returns: + The validator instance. + :rtype: + Validator + """ + for scheme in schemes: + self.allowed_schemes.add(normalizers.normalize_scheme(scheme)) + return self + + def allow_hosts(self, *hosts): + """Require the host to be one of the provided hosts. + + .. versionadded:: 1.0 + + :param hosts: + Hosts that are allowed. + :returns: + The validator instance. + :rtype: + Validator + """ + for host in hosts: + self.allowed_hosts.add(normalizers.normalize_host(host)) + return self + + def allow_ports(self, *ports): + """Require the port to be one of the provided ports. + + .. versionadded:: 1.0 + + :param ports: + Ports that are allowed. + :returns: + The validator instance. + :rtype: + Validator + """ + for port in ports: + port_int = int(port, base=10) + if 0 <= port_int <= 65535: + self.allowed_ports.add(port) + return self + + def allow_use_of_password(self): + """Allow passwords to be present in the URI. + + .. versionadded:: 1.0 + + :returns: + The validator instance. + :rtype: + Validator + """ + self.allow_password = True + return self + + def forbid_use_of_password(self): + """Prevent passwords from being included in the URI. + + .. versionadded:: 1.0 + + :returns: + The validator instance. + :rtype: + Validator + """ + self.allow_password = False + return self + + def check_validity_of(self, *components): + """Check the validity of the components provided. + + This can be specified repeatedly. + + .. versionadded:: 1.1 + + :param components: + Names of components from :attr:`Validator.COMPONENT_NAMES`. + :returns: + The validator instance. + :rtype: + Validator + """ + components = [c.lower() for c in components] + for component in components: + if component not in self.COMPONENT_NAMES: + raise ValueError( + '"{}" is not a valid component'.format(component) + ) + self.validated_components.update( + {component: True for component in components} + ) + return self + + def require_presence_of(self, *components): + """Require the components provided. + + This can be specified repeatedly. + + .. versionadded:: 1.0 + + :param components: + Names of components from :attr:`Validator.COMPONENT_NAMES`. + :returns: + The validator instance. + :rtype: + Validator + """ + components = [c.lower() for c in components] + for component in components: + if component not in self.COMPONENT_NAMES: + raise ValueError( + '"{}" is not a valid component'.format(component) + ) + self.required_components.update( + {component: True for component in components} + ) + return self + + def validate(self, uri): + """Check a URI for conditions specified on this validator. + + .. versionadded:: 1.0 + + :param uri: + Parsed URI to validate. + :type uri: + rfc3986.uri.URIReference + :raises MissingComponentError: + When a required component is missing. + :raises UnpermittedComponentError: + When a component is not one of those allowed. + :raises PasswordForbidden: + When a password is present in the userinfo component but is + not permitted by configuration. + :raises InvalidComponentsError: + When a component was found to be invalid. + """ + if not self.allow_password: + check_password(uri) + + required_components = [ + component + for component, required in self.required_components.items() + if required + ] + validated_components = [ + component + for component, required in self.validated_components.items() + if required + ] + if required_components: + ensure_required_components_exist(uri, required_components) + if validated_components: + ensure_components_are_valid(uri, validated_components) + + ensure_one_of(self.allowed_schemes, uri, "scheme") + ensure_one_of(self.allowed_hosts, uri, "host") + ensure_one_of(self.allowed_ports, uri, "port") + + +def check_password(uri): + """Assert that there is no password present in the uri.""" + userinfo = uri.userinfo + if not userinfo: + return + credentials = userinfo.split(":", 1) + if len(credentials) <= 1: + return + raise exceptions.PasswordForbidden(uri) + + +def ensure_one_of(allowed_values, uri, attribute): + """Assert that the uri's attribute is one of the allowed values.""" + value = getattr(uri, attribute) + if value is not None and allowed_values and value not in allowed_values: + raise exceptions.UnpermittedComponentError( + attribute, + value, + allowed_values, + ) + + +def ensure_required_components_exist(uri, required_components): + """Assert that all required components are present in the URI.""" + missing_components = sorted( + [ + component + for component in required_components + if getattr(uri, component) is None + ] + ) + if missing_components: + raise exceptions.MissingComponentError(uri, *missing_components) + + +def is_valid(value, matcher, require): + """Determine if a value is valid based on the provided matcher. + + :param str value: + Value to validate. + :param matcher: + Compiled regular expression to use to validate the value. + :param require: + Whether or not the value is required. + """ + if require: + return value is not None and matcher.match(value) + + # require is False and value is not None + return value is None or matcher.match(value) + + +def authority_is_valid(authority, host=None, require=False): + """Determine if the authority string is valid. + + :param str authority: + The authority to validate. + :param str host: + (optional) The host portion of the authority to validate. + :param bool require: + (optional) Specify if authority must not be None. + :returns: + ``True`` if valid, ``False`` otherwise + :rtype: + bool + """ + validated = is_valid(authority, misc.SUBAUTHORITY_MATCHER, require) + if validated and host is not None: + return host_is_valid(host, require) + return validated + + +def host_is_valid(host, require=False): + """Determine if the host string is valid. + + :param str host: + The host to validate. + :param bool require: + (optional) Specify if host must not be None. + :returns: + ``True`` if valid, ``False`` otherwise + :rtype: + bool + """ + validated = is_valid(host, misc.HOST_MATCHER, require) + if validated and host is not None and misc.IPv4_MATCHER.match(host): + return valid_ipv4_host_address(host) + elif validated and host is not None and misc.IPv6_MATCHER.match(host): + return misc.IPv6_NO_RFC4007_MATCHER.match(host) is not None + return validated + + +def scheme_is_valid(scheme, require=False): + """Determine if the scheme is valid. + + :param str scheme: + The scheme string to validate. + :param bool require: + (optional) Set to ``True`` to require the presence of a scheme. + :returns: + ``True`` if the scheme is valid. ``False`` otherwise. + :rtype: + bool + """ + return is_valid(scheme, misc.SCHEME_MATCHER, require) + + +def path_is_valid(path, require=False): + """Determine if the path component is valid. + + :param str path: + The path string to validate. + :param bool require: + (optional) Set to ``True`` to require the presence of a path. + :returns: + ``True`` if the path is valid. ``False`` otherwise. + :rtype: + bool + """ + return is_valid(path, misc.PATH_MATCHER, require) + + +def query_is_valid(query, require=False): + """Determine if the query component is valid. + + :param str query: + The query string to validate. + :param bool require: + (optional) Set to ``True`` to require the presence of a query. + :returns: + ``True`` if the query is valid. ``False`` otherwise. + :rtype: + bool + """ + return is_valid(query, misc.QUERY_MATCHER, require) + + +def fragment_is_valid(fragment, require=False): + """Determine if the fragment component is valid. + + :param str fragment: + The fragment string to validate. + :param bool require: + (optional) Set to ``True`` to require the presence of a fragment. + :returns: + ``True`` if the fragment is valid. ``False`` otherwise. + :rtype: + bool + """ + return is_valid(fragment, misc.FRAGMENT_MATCHER, require) + + +def valid_ipv4_host_address(host): + """Determine if the given host is a valid IPv4 address.""" + # If the host exists, and it might be IPv4, check each byte in the + # address. + return all([0 <= int(byte, base=10) <= 255 for byte in host.split(".")]) + + +_COMPONENT_VALIDATORS = { + "scheme": scheme_is_valid, + "path": path_is_valid, + "query": query_is_valid, + "fragment": fragment_is_valid, +} + +_SUBAUTHORITY_VALIDATORS = set(["userinfo", "host", "port"]) + + +def subauthority_component_is_valid(uri, component): + """Determine if the userinfo, host, and port are valid.""" + try: + subauthority_dict = uri.authority_info() + except exceptions.InvalidAuthority: + return False + + # If we can parse the authority into sub-components and we're not + # validating the port, we can assume it's valid. + if component == "host": + return host_is_valid(subauthority_dict["host"]) + elif component != "port": + return True + + try: + port = int(subauthority_dict["port"]) + except TypeError: + # If the port wasn't provided it'll be None and int(None) raises a + # TypeError + return True + + return 0 <= port <= 65535 + + +def ensure_components_are_valid(uri, validated_components): + """Assert that all components are valid in the URI.""" + invalid_components = set([]) + for component in validated_components: + if component in _SUBAUTHORITY_VALIDATORS: + if not subauthority_component_is_valid(uri, component): + invalid_components.add(component) + # Python's peephole optimizer means that while this continue *is* + # actually executed, coverage.py cannot detect that. See also, + # https://bitbucket.org/ned/coveragepy/issues/198/continue-marked-as-not-covered + continue # nocov: Python 2.7, 3.3, 3.4 + + validator = _COMPONENT_VALIDATORS[component] + if not validator(getattr(uri, component)): + invalid_components.add(component) + + if invalid_components: + raise exceptions.InvalidComponentsError(uri, *invalid_components) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rich/_emoji_codes.py b/TTS/Kokoro/.venv/Lib/site-packages/rich/_emoji_codes.py new file mode 100644 index 0000000000000000000000000000000000000000..1f2877bb2bd520253502b1c05bb811bb0d7ef64c --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rich/_emoji_codes.py @@ -0,0 +1,3610 @@ +EMOJI = { + "1st_place_medal": "🥇", + "2nd_place_medal": "🥈", + "3rd_place_medal": "🥉", + "ab_button_(blood_type)": "🆎", + "atm_sign": "🏧", + "a_button_(blood_type)": "🅰", + "afghanistan": "🇦🇫", + "albania": "🇦🇱", + "algeria": "🇩🇿", + "american_samoa": "🇦🇸", + "andorra": "🇦🇩", + "angola": "🇦🇴", + "anguilla": "🇦🇮", + "antarctica": "🇦🇶", + "antigua_&_barbuda": "🇦🇬", + "aquarius": "♒", + "argentina": "🇦🇷", + "aries": "♈", + "armenia": "🇦🇲", + "aruba": "🇦🇼", + "ascension_island": "🇦🇨", + "australia": "🇦🇺", + "austria": "🇦🇹", + "azerbaijan": "🇦🇿", + "back_arrow": "🔙", + "b_button_(blood_type)": "🅱", + "bahamas": "🇧🇸", + "bahrain": "🇧🇭", + "bangladesh": "🇧🇩", + "barbados": "🇧🇧", + "belarus": "🇧🇾", + "belgium": "🇧🇪", + "belize": "🇧🇿", + "benin": "🇧🇯", + "bermuda": "🇧🇲", + "bhutan": "🇧🇹", + "bolivia": "🇧🇴", + "bosnia_&_herzegovina": "🇧🇦", + "botswana": "🇧🇼", + "bouvet_island": "🇧🇻", + "brazil": "🇧🇷", + "british_indian_ocean_territory": "🇮🇴", + "british_virgin_islands": "🇻🇬", + "brunei": "🇧🇳", + "bulgaria": "🇧🇬", + "burkina_faso": "🇧🇫", + "burundi": "🇧🇮", + "cl_button": "🆑", + "cool_button": "🆒", + "cambodia": "🇰🇭", + "cameroon": "🇨🇲", + "canada": "🇨🇦", + "canary_islands": "🇮🇨", + "cancer": "♋", + "cape_verde": "🇨🇻", + "capricorn": "♑", + "caribbean_netherlands": "🇧🇶", + "cayman_islands": "🇰🇾", + "central_african_republic": "🇨🇫", + "ceuta_&_melilla": "🇪🇦", + "chad": "🇹🇩", + "chile": "🇨🇱", + "china": "🇨🇳", + "christmas_island": "🇨🇽", + "christmas_tree": "🎄", + "clipperton_island": "🇨🇵", + "cocos_(keeling)_islands": "🇨🇨", + "colombia": "🇨🇴", + "comoros": "🇰🇲", + "congo_-_brazzaville": "🇨🇬", + "congo_-_kinshasa": "🇨🇩", + "cook_islands": "🇨🇰", + "costa_rica": "🇨🇷", + "croatia": "🇭🇷", + "cuba": "🇨🇺", + "curaçao": "🇨🇼", + "cyprus": "🇨🇾", + "czechia": "🇨🇿", + "côte_d’ivoire": "🇨🇮", + "denmark": "🇩🇰", + "diego_garcia": "🇩🇬", + "djibouti": "🇩🇯", + "dominica": "🇩🇲", + "dominican_republic": "🇩🇴", + "end_arrow": "🔚", + "ecuador": "🇪🇨", + "egypt": "🇪🇬", + "el_salvador": "🇸🇻", + "england": "🏴\U000e0067\U000e0062\U000e0065\U000e006e\U000e0067\U000e007f", + "equatorial_guinea": "🇬🇶", + "eritrea": "🇪🇷", + "estonia": "🇪🇪", + "ethiopia": "🇪🇹", + "european_union": "🇪🇺", + "free_button": "🆓", + "falkland_islands": "🇫🇰", + "faroe_islands": "🇫🇴", + "fiji": "🇫🇯", + "finland": "🇫🇮", + "france": "🇫🇷", + "french_guiana": "🇬🇫", + "french_polynesia": "🇵🇫", + "french_southern_territories": "🇹🇫", + "gabon": "🇬🇦", + "gambia": "🇬🇲", + "gemini": "♊", + "georgia": "🇬🇪", + "germany": "🇩🇪", + "ghana": "🇬🇭", + "gibraltar": "🇬🇮", + "greece": "🇬🇷", + "greenland": "🇬🇱", + "grenada": "🇬🇩", + "guadeloupe": "🇬🇵", + "guam": "🇬🇺", + "guatemala": "🇬🇹", + "guernsey": "🇬🇬", + "guinea": "🇬🇳", + "guinea-bissau": "🇬🇼", + "guyana": "🇬🇾", + "haiti": "🇭🇹", + "heard_&_mcdonald_islands": "🇭🇲", + "honduras": "🇭🇳", + "hong_kong_sar_china": "🇭🇰", + "hungary": "🇭🇺", + "id_button": "🆔", + "iceland": "🇮🇸", + "india": "🇮🇳", + "indonesia": "🇮🇩", + "iran": "🇮🇷", + "iraq": "🇮🇶", + "ireland": "🇮🇪", + "isle_of_man": "🇮🇲", + "israel": "🇮🇱", + "italy": "🇮🇹", + "jamaica": "🇯🇲", + "japan": "🗾", + "japanese_acceptable_button": "🉑", + "japanese_application_button": "🈸", + "japanese_bargain_button": "🉐", + "japanese_castle": "🏯", + "japanese_congratulations_button": "㊗", + "japanese_discount_button": "🈹", + "japanese_dolls": "🎎", + "japanese_free_of_charge_button": "🈚", + "japanese_here_button": "🈁", + "japanese_monthly_amount_button": "🈷", + "japanese_no_vacancy_button": "🈵", + "japanese_not_free_of_charge_button": "🈶", + "japanese_open_for_business_button": "🈺", + "japanese_passing_grade_button": "🈴", + "japanese_post_office": "🏣", + "japanese_prohibited_button": "🈲", + "japanese_reserved_button": "🈯", + "japanese_secret_button": "㊙", + "japanese_service_charge_button": "🈂", + "japanese_symbol_for_beginner": "🔰", + "japanese_vacancy_button": "🈳", + "jersey": "🇯🇪", + "jordan": "🇯🇴", + "kazakhstan": "🇰🇿", + "kenya": "🇰🇪", + "kiribati": "🇰🇮", + "kosovo": "🇽🇰", + "kuwait": "🇰🇼", + "kyrgyzstan": "🇰🇬", + "laos": "🇱🇦", + "latvia": "🇱🇻", + "lebanon": "🇱🇧", + "leo": "♌", + "lesotho": "🇱🇸", + "liberia": "🇱🇷", + "libra": "♎", + "libya": "🇱🇾", + "liechtenstein": "🇱🇮", + "lithuania": "🇱🇹", + "luxembourg": "🇱🇺", + "macau_sar_china": "🇲🇴", + "macedonia": "🇲🇰", + "madagascar": "🇲🇬", + "malawi": "🇲🇼", + "malaysia": "🇲🇾", + "maldives": "🇲🇻", + "mali": "🇲🇱", + "malta": "🇲🇹", + "marshall_islands": "🇲🇭", + "martinique": "🇲🇶", + "mauritania": "🇲🇷", + "mauritius": "🇲🇺", + "mayotte": "🇾🇹", + "mexico": "🇲🇽", + "micronesia": "🇫🇲", + "moldova": "🇲🇩", + "monaco": "🇲🇨", + "mongolia": "🇲🇳", + "montenegro": "🇲🇪", + "montserrat": "🇲🇸", + "morocco": "🇲🇦", + "mozambique": "🇲🇿", + "mrs._claus": "🤶", + "mrs._claus_dark_skin_tone": "🤶🏿", + "mrs._claus_light_skin_tone": "🤶🏻", + "mrs._claus_medium-dark_skin_tone": "🤶🏾", + "mrs._claus_medium-light_skin_tone": "🤶🏼", + "mrs._claus_medium_skin_tone": "🤶🏽", + "myanmar_(burma)": "🇲🇲", + "new_button": "🆕", + "ng_button": "🆖", + "namibia": "🇳🇦", + "nauru": "🇳🇷", + "nepal": "🇳🇵", + "netherlands": "🇳🇱", + "new_caledonia": "🇳🇨", + "new_zealand": "🇳🇿", + "nicaragua": "🇳🇮", + "niger": "🇳🇪", + "nigeria": "🇳🇬", + "niue": "🇳🇺", + "norfolk_island": "🇳🇫", + "north_korea": "🇰🇵", + "northern_mariana_islands": "🇲🇵", + "norway": "🇳🇴", + "ok_button": "🆗", + "ok_hand": "👌", + "ok_hand_dark_skin_tone": "👌🏿", + "ok_hand_light_skin_tone": "👌🏻", + "ok_hand_medium-dark_skin_tone": "👌🏾", + "ok_hand_medium-light_skin_tone": "👌🏼", + "ok_hand_medium_skin_tone": "👌🏽", + "on!_arrow": "🔛", + "o_button_(blood_type)": "🅾", + "oman": "🇴🇲", + "ophiuchus": "⛎", + "p_button": "🅿", + "pakistan": "🇵🇰", + "palau": "🇵🇼", + "palestinian_territories": "🇵🇸", + "panama": "🇵🇦", + "papua_new_guinea": "🇵🇬", + "paraguay": "🇵🇾", + "peru": "🇵🇪", + "philippines": "🇵🇭", + "pisces": "♓", + "pitcairn_islands": "🇵🇳", + "poland": "🇵🇱", + "portugal": "🇵🇹", + "puerto_rico": "🇵🇷", + "qatar": "🇶🇦", + "romania": "🇷🇴", + "russia": "🇷🇺", + "rwanda": "🇷🇼", + "réunion": "🇷🇪", + "soon_arrow": "🔜", + "sos_button": "🆘", + "sagittarius": "♐", + "samoa": "🇼🇸", + "san_marino": "🇸🇲", + "santa_claus": "🎅", + "santa_claus_dark_skin_tone": "🎅🏿", + "santa_claus_light_skin_tone": "🎅🏻", + "santa_claus_medium-dark_skin_tone": "🎅🏾", + "santa_claus_medium-light_skin_tone": "🎅🏼", + "santa_claus_medium_skin_tone": "🎅🏽", + "saudi_arabia": "🇸🇦", + "scorpio": "♏", + "scotland": "🏴\U000e0067\U000e0062\U000e0073\U000e0063\U000e0074\U000e007f", + "senegal": "🇸🇳", + "serbia": "🇷🇸", + "seychelles": "🇸🇨", + "sierra_leone": "🇸🇱", + "singapore": "🇸🇬", + "sint_maarten": "🇸🇽", + "slovakia": "🇸🇰", + "slovenia": "🇸🇮", + "solomon_islands": "🇸🇧", + "somalia": "🇸🇴", + "south_africa": "🇿🇦", + "south_georgia_&_south_sandwich_islands": "🇬🇸", + "south_korea": "🇰🇷", + "south_sudan": "🇸🇸", + "spain": "🇪🇸", + "sri_lanka": "🇱🇰", + "st._barthélemy": "🇧🇱", + "st._helena": "🇸🇭", + "st._kitts_&_nevis": "🇰🇳", + "st._lucia": "🇱🇨", + "st._martin": "🇲🇫", + "st._pierre_&_miquelon": "🇵🇲", + "st._vincent_&_grenadines": "🇻🇨", + "statue_of_liberty": "🗽", + "sudan": "🇸🇩", + "suriname": "🇸🇷", + "svalbard_&_jan_mayen": "🇸🇯", + "swaziland": "🇸🇿", + "sweden": "🇸🇪", + "switzerland": "🇨🇭", + "syria": "🇸🇾", + "são_tomé_&_príncipe": "🇸🇹", + "t-rex": "🦖", + "top_arrow": "🔝", + "taiwan": "🇹🇼", + "tajikistan": "🇹🇯", + "tanzania": "🇹🇿", + "taurus": "♉", + "thailand": "🇹🇭", + "timor-leste": "🇹🇱", + "togo": "🇹🇬", + "tokelau": "🇹🇰", + "tokyo_tower": "🗼", + "tonga": "🇹🇴", + "trinidad_&_tobago": "🇹🇹", + "tristan_da_cunha": "🇹🇦", + "tunisia": "🇹🇳", + "turkey": "🦃", + "turkmenistan": "🇹🇲", + "turks_&_caicos_islands": "🇹🇨", + "tuvalu": "🇹🇻", + "u.s._outlying_islands": "🇺🇲", + "u.s._virgin_islands": "🇻🇮", + "up!_button": "🆙", + "uganda": "🇺🇬", + "ukraine": "🇺🇦", + "united_arab_emirates": "🇦🇪", + "united_kingdom": "🇬🇧", + "united_nations": "🇺🇳", + "united_states": "🇺🇸", + "uruguay": "🇺🇾", + "uzbekistan": "🇺🇿", + "vs_button": "🆚", + "vanuatu": "🇻🇺", + "vatican_city": "🇻🇦", + "venezuela": "🇻🇪", + "vietnam": "🇻🇳", + "virgo": "♍", + "wales": "🏴\U000e0067\U000e0062\U000e0077\U000e006c\U000e0073\U000e007f", + "wallis_&_futuna": "🇼🇫", + "western_sahara": "🇪🇭", + "yemen": "🇾🇪", + "zambia": "🇿🇲", + "zimbabwe": "🇿🇼", + "abacus": "🧮", + "adhesive_bandage": "🩹", + "admission_tickets": "🎟", + "adult": "🧑", + "adult_dark_skin_tone": "🧑🏿", + "adult_light_skin_tone": "🧑🏻", + "adult_medium-dark_skin_tone": "🧑🏾", + "adult_medium-light_skin_tone": "🧑🏼", + "adult_medium_skin_tone": "🧑🏽", + "aerial_tramway": "🚡", + "airplane": "✈", + "airplane_arrival": "🛬", + "airplane_departure": "🛫", + "alarm_clock": "⏰", + "alembic": "⚗", + "alien": "👽", + "alien_monster": "👾", + "ambulance": "🚑", + "american_football": "🏈", + "amphora": "🏺", + "anchor": "⚓", + "anger_symbol": "💢", + "angry_face": "😠", + "angry_face_with_horns": "👿", + "anguished_face": "😧", + "ant": "🐜", + "antenna_bars": "📶", + "anxious_face_with_sweat": "😰", + "articulated_lorry": "🚛", + "artist_palette": "🎨", + "astonished_face": "😲", + "atom_symbol": "⚛", + "auto_rickshaw": "🛺", + "automobile": "🚗", + "avocado": "🥑", + "axe": "🪓", + "baby": "👶", + "baby_angel": "👼", + "baby_angel_dark_skin_tone": "👼🏿", + "baby_angel_light_skin_tone": "👼🏻", + "baby_angel_medium-dark_skin_tone": "👼🏾", + "baby_angel_medium-light_skin_tone": "👼🏼", + "baby_angel_medium_skin_tone": "👼🏽", + "baby_bottle": "🍼", + "baby_chick": "🐤", + "baby_dark_skin_tone": "👶🏿", + "baby_light_skin_tone": "👶🏻", + "baby_medium-dark_skin_tone": "👶🏾", + "baby_medium-light_skin_tone": "👶🏼", + "baby_medium_skin_tone": "👶🏽", + "baby_symbol": "🚼", + "backhand_index_pointing_down": "👇", + "backhand_index_pointing_down_dark_skin_tone": "👇🏿", + "backhand_index_pointing_down_light_skin_tone": "👇🏻", + "backhand_index_pointing_down_medium-dark_skin_tone": "👇🏾", + "backhand_index_pointing_down_medium-light_skin_tone": "👇🏼", + "backhand_index_pointing_down_medium_skin_tone": "👇🏽", + "backhand_index_pointing_left": "👈", + "backhand_index_pointing_left_dark_skin_tone": "👈🏿", + "backhand_index_pointing_left_light_skin_tone": "👈🏻", + "backhand_index_pointing_left_medium-dark_skin_tone": "👈🏾", + "backhand_index_pointing_left_medium-light_skin_tone": "👈🏼", + "backhand_index_pointing_left_medium_skin_tone": "👈🏽", + "backhand_index_pointing_right": "👉", + "backhand_index_pointing_right_dark_skin_tone": "👉🏿", + "backhand_index_pointing_right_light_skin_tone": "👉🏻", + "backhand_index_pointing_right_medium-dark_skin_tone": "👉🏾", + "backhand_index_pointing_right_medium-light_skin_tone": "👉🏼", + "backhand_index_pointing_right_medium_skin_tone": "👉🏽", + "backhand_index_pointing_up": "👆", + "backhand_index_pointing_up_dark_skin_tone": "👆🏿", + "backhand_index_pointing_up_light_skin_tone": "👆🏻", + "backhand_index_pointing_up_medium-dark_skin_tone": "👆🏾", + "backhand_index_pointing_up_medium-light_skin_tone": "👆🏼", + "backhand_index_pointing_up_medium_skin_tone": "👆🏽", + "bacon": "🥓", + "badger": "🦡", + "badminton": "🏸", + "bagel": "🥯", + "baggage_claim": "🛄", + "baguette_bread": "🥖", + "balance_scale": "⚖", + "bald": "🦲", + "bald_man": "👨\u200d🦲", + "bald_woman": "👩\u200d🦲", + "ballet_shoes": "🩰", + "balloon": "🎈", + "ballot_box_with_ballot": "🗳", + "ballot_box_with_check": "☑", + "banana": "🍌", + "banjo": "🪕", + "bank": "🏦", + "bar_chart": "📊", + "barber_pole": "💈", + "baseball": "⚾", + "basket": "🧺", + "basketball": "🏀", + "bat": "🦇", + "bathtub": "🛁", + "battery": "🔋", + "beach_with_umbrella": "🏖", + "beaming_face_with_smiling_eyes": "😁", + "bear_face": "🐻", + "bearded_person": "🧔", + "bearded_person_dark_skin_tone": "🧔🏿", + "bearded_person_light_skin_tone": "🧔🏻", + "bearded_person_medium-dark_skin_tone": "🧔🏾", + "bearded_person_medium-light_skin_tone": "🧔🏼", + "bearded_person_medium_skin_tone": "🧔🏽", + "beating_heart": "💓", + "bed": "🛏", + "beer_mug": "🍺", + "bell": "🔔", + "bell_with_slash": "🔕", + "bellhop_bell": "🛎", + "bento_box": "🍱", + "beverage_box": "🧃", + "bicycle": "🚲", + "bikini": "👙", + "billed_cap": "🧢", + "biohazard": "☣", + "bird": "🐦", + "birthday_cake": "🎂", + "black_circle": "⚫", + "black_flag": "🏴", + "black_heart": "🖤", + "black_large_square": "⬛", + "black_medium-small_square": "◾", + "black_medium_square": "◼", + "black_nib": "✒", + "black_small_square": "▪", + "black_square_button": "🔲", + "blond-haired_man": "👱\u200d♂️", + "blond-haired_man_dark_skin_tone": "👱🏿\u200d♂️", + "blond-haired_man_light_skin_tone": "👱🏻\u200d♂️", + "blond-haired_man_medium-dark_skin_tone": "👱🏾\u200d♂️", + "blond-haired_man_medium-light_skin_tone": "👱🏼\u200d♂️", + "blond-haired_man_medium_skin_tone": "👱🏽\u200d♂️", + "blond-haired_person": "👱", + "blond-haired_person_dark_skin_tone": "👱🏿", + "blond-haired_person_light_skin_tone": "👱🏻", + "blond-haired_person_medium-dark_skin_tone": "👱🏾", + "blond-haired_person_medium-light_skin_tone": "👱🏼", + "blond-haired_person_medium_skin_tone": "👱🏽", + "blond-haired_woman": "👱\u200d♀️", + "blond-haired_woman_dark_skin_tone": "👱🏿\u200d♀️", + "blond-haired_woman_light_skin_tone": "👱🏻\u200d♀️", + "blond-haired_woman_medium-dark_skin_tone": "👱🏾\u200d♀️", + "blond-haired_woman_medium-light_skin_tone": "👱🏼\u200d♀️", + "blond-haired_woman_medium_skin_tone": "👱🏽\u200d♀️", + "blossom": "🌼", + "blowfish": "🐡", + "blue_book": "📘", + "blue_circle": "🔵", + "blue_heart": "💙", + "blue_square": "🟦", + "boar": "🐗", + "bomb": "💣", + "bone": "🦴", + "bookmark": "🔖", + "bookmark_tabs": "📑", + "books": "📚", + "bottle_with_popping_cork": "🍾", + "bouquet": "💐", + "bow_and_arrow": "🏹", + "bowl_with_spoon": "🥣", + "bowling": "🎳", + "boxing_glove": "🥊", + "boy": "👦", + "boy_dark_skin_tone": "👦🏿", + "boy_light_skin_tone": "👦🏻", + "boy_medium-dark_skin_tone": "👦🏾", + "boy_medium-light_skin_tone": "👦🏼", + "boy_medium_skin_tone": "👦🏽", + "brain": "🧠", + "bread": "🍞", + "breast-feeding": "🤱", + "breast-feeding_dark_skin_tone": "🤱🏿", + "breast-feeding_light_skin_tone": "🤱🏻", + "breast-feeding_medium-dark_skin_tone": "🤱🏾", + "breast-feeding_medium-light_skin_tone": "🤱🏼", + "breast-feeding_medium_skin_tone": "🤱🏽", + "brick": "🧱", + "bride_with_veil": "👰", + "bride_with_veil_dark_skin_tone": "👰🏿", + "bride_with_veil_light_skin_tone": "👰🏻", + "bride_with_veil_medium-dark_skin_tone": "👰🏾", + "bride_with_veil_medium-light_skin_tone": "👰🏼", + "bride_with_veil_medium_skin_tone": "👰🏽", + "bridge_at_night": "🌉", + "briefcase": "💼", + "briefs": "🩲", + "bright_button": "🔆", + "broccoli": "🥦", + "broken_heart": "💔", + "broom": "🧹", + "brown_circle": "🟤", + "brown_heart": "🤎", + "brown_square": "🟫", + "bug": "🐛", + "building_construction": "🏗", + "bullet_train": "🚅", + "burrito": "🌯", + "bus": "🚌", + "bus_stop": "🚏", + "bust_in_silhouette": "👤", + "busts_in_silhouette": "👥", + "butter": "🧈", + "butterfly": "🦋", + "cactus": "🌵", + "calendar": "📆", + "call_me_hand": "🤙", + "call_me_hand_dark_skin_tone": "🤙🏿", + "call_me_hand_light_skin_tone": "🤙🏻", + "call_me_hand_medium-dark_skin_tone": "🤙🏾", + "call_me_hand_medium-light_skin_tone": "🤙🏼", + "call_me_hand_medium_skin_tone": "🤙🏽", + "camel": "🐫", + "camera": "📷", + "camera_with_flash": "📸", + "camping": "🏕", + "candle": "🕯", + "candy": "🍬", + "canned_food": "🥫", + "canoe": "🛶", + "card_file_box": "🗃", + "card_index": "📇", + "card_index_dividers": "🗂", + "carousel_horse": "🎠", + "carp_streamer": "🎏", + "carrot": "🥕", + "castle": "🏰", + "cat": "🐱", + "cat_face": "🐱", + "cat_face_with_tears_of_joy": "😹", + "cat_face_with_wry_smile": "😼", + "chains": "⛓", + "chair": "🪑", + "chart_decreasing": "📉", + "chart_increasing": "📈", + "chart_increasing_with_yen": "💹", + "cheese_wedge": "🧀", + "chequered_flag": "🏁", + "cherries": "🍒", + "cherry_blossom": "🌸", + "chess_pawn": "♟", + "chestnut": "🌰", + "chicken": "🐔", + "child": "🧒", + "child_dark_skin_tone": "🧒🏿", + "child_light_skin_tone": "🧒🏻", + "child_medium-dark_skin_tone": "🧒🏾", + "child_medium-light_skin_tone": "🧒🏼", + "child_medium_skin_tone": "🧒🏽", + "children_crossing": "🚸", + "chipmunk": "🐿", + "chocolate_bar": "🍫", + "chopsticks": "🥢", + "church": "⛪", + "cigarette": "🚬", + "cinema": "🎦", + "circled_m": "Ⓜ", + "circus_tent": "🎪", + "cityscape": "🏙", + "cityscape_at_dusk": "🌆", + "clamp": "🗜", + "clapper_board": "🎬", + "clapping_hands": "👏", + "clapping_hands_dark_skin_tone": "👏🏿", + "clapping_hands_light_skin_tone": "👏🏻", + "clapping_hands_medium-dark_skin_tone": "👏🏾", + "clapping_hands_medium-light_skin_tone": "👏🏼", + "clapping_hands_medium_skin_tone": "👏🏽", + "classical_building": "🏛", + "clinking_beer_mugs": "🍻", + "clinking_glasses": "🥂", + "clipboard": "📋", + "clockwise_vertical_arrows": "🔃", + "closed_book": "📕", + "closed_mailbox_with_lowered_flag": "📪", + "closed_mailbox_with_raised_flag": "📫", + "closed_umbrella": "🌂", + "cloud": "☁", + "cloud_with_lightning": "🌩", + "cloud_with_lightning_and_rain": "⛈", + "cloud_with_rain": "🌧", + "cloud_with_snow": "🌨", + "clown_face": "🤡", + "club_suit": "♣", + "clutch_bag": "👝", + "coat": "🧥", + "cocktail_glass": "🍸", + "coconut": "🥥", + "coffin": "⚰", + "cold_face": "🥶", + "collision": "💥", + "comet": "☄", + "compass": "🧭", + "computer_disk": "💽", + "computer_mouse": "🖱", + "confetti_ball": "🎊", + "confounded_face": "😖", + "confused_face": "😕", + "construction": "🚧", + "construction_worker": "👷", + "construction_worker_dark_skin_tone": "👷🏿", + "construction_worker_light_skin_tone": "👷🏻", + "construction_worker_medium-dark_skin_tone": "👷🏾", + "construction_worker_medium-light_skin_tone": "👷🏼", + "construction_worker_medium_skin_tone": "👷🏽", + "control_knobs": "🎛", + "convenience_store": "🏪", + "cooked_rice": "🍚", + "cookie": "🍪", + "cooking": "🍳", + "copyright": "©", + "couch_and_lamp": "🛋", + "counterclockwise_arrows_button": "🔄", + "couple_with_heart": "💑", + "couple_with_heart_man_man": "👨\u200d❤️\u200d👨", + "couple_with_heart_woman_man": "👩\u200d❤️\u200d👨", + "couple_with_heart_woman_woman": "👩\u200d❤️\u200d👩", + "cow": "🐮", + "cow_face": "🐮", + "cowboy_hat_face": "🤠", + "crab": "🦀", + "crayon": "🖍", + "credit_card": "💳", + "crescent_moon": "🌙", + "cricket": "🦗", + "cricket_game": "🏏", + "crocodile": "🐊", + "croissant": "🥐", + "cross_mark": "❌", + "cross_mark_button": "❎", + "crossed_fingers": "🤞", + "crossed_fingers_dark_skin_tone": "🤞🏿", + "crossed_fingers_light_skin_tone": "🤞🏻", + "crossed_fingers_medium-dark_skin_tone": "🤞🏾", + "crossed_fingers_medium-light_skin_tone": "🤞🏼", + "crossed_fingers_medium_skin_tone": "🤞🏽", + "crossed_flags": "🎌", + "crossed_swords": "⚔", + "crown": "👑", + "crying_cat_face": "😿", + "crying_face": "😢", + "crystal_ball": "🔮", + "cucumber": "🥒", + "cupcake": "🧁", + "cup_with_straw": "🥤", + "curling_stone": "🥌", + "curly_hair": "🦱", + "curly-haired_man": "👨\u200d🦱", + "curly-haired_woman": "👩\u200d🦱", + "curly_loop": "➰", + "currency_exchange": "💱", + "curry_rice": "🍛", + "custard": "🍮", + "customs": "🛃", + "cut_of_meat": "🥩", + "cyclone": "🌀", + "dagger": "🗡", + "dango": "🍡", + "dashing_away": "💨", + "deaf_person": "🧏", + "deciduous_tree": "🌳", + "deer": "🦌", + "delivery_truck": "🚚", + "department_store": "🏬", + "derelict_house": "🏚", + "desert": "🏜", + "desert_island": "🏝", + "desktop_computer": "🖥", + "detective": "🕵", + "detective_dark_skin_tone": "🕵🏿", + "detective_light_skin_tone": "🕵🏻", + "detective_medium-dark_skin_tone": "🕵🏾", + "detective_medium-light_skin_tone": "🕵🏼", + "detective_medium_skin_tone": "🕵🏽", + "diamond_suit": "♦", + "diamond_with_a_dot": "💠", + "dim_button": "🔅", + "direct_hit": "🎯", + "disappointed_face": "😞", + "diving_mask": "🤿", + "diya_lamp": "🪔", + "dizzy": "💫", + "dizzy_face": "😵", + "dna": "🧬", + "dog": "🐶", + "dog_face": "🐶", + "dollar_banknote": "💵", + "dolphin": "🐬", + "door": "🚪", + "dotted_six-pointed_star": "🔯", + "double_curly_loop": "➿", + "double_exclamation_mark": "‼", + "doughnut": "🍩", + "dove": "🕊", + "down-left_arrow": "↙", + "down-right_arrow": "↘", + "down_arrow": "⬇", + "downcast_face_with_sweat": "😓", + "downwards_button": "🔽", + "dragon": "🐉", + "dragon_face": "🐲", + "dress": "👗", + "drooling_face": "🤤", + "drop_of_blood": "🩸", + "droplet": "💧", + "drum": "🥁", + "duck": "🦆", + "dumpling": "🥟", + "dvd": "📀", + "e-mail": "📧", + "eagle": "🦅", + "ear": "👂", + "ear_dark_skin_tone": "👂🏿", + "ear_light_skin_tone": "👂🏻", + "ear_medium-dark_skin_tone": "👂🏾", + "ear_medium-light_skin_tone": "👂🏼", + "ear_medium_skin_tone": "👂🏽", + "ear_of_corn": "🌽", + "ear_with_hearing_aid": "🦻", + "egg": "🍳", + "eggplant": "🍆", + "eight-pointed_star": "✴", + "eight-spoked_asterisk": "✳", + "eight-thirty": "🕣", + "eight_o’clock": "🕗", + "eject_button": "⏏", + "electric_plug": "🔌", + "elephant": "🐘", + "eleven-thirty": "🕦", + "eleven_o’clock": "🕚", + "elf": "🧝", + "elf_dark_skin_tone": "🧝🏿", + "elf_light_skin_tone": "🧝🏻", + "elf_medium-dark_skin_tone": "🧝🏾", + "elf_medium-light_skin_tone": "🧝🏼", + "elf_medium_skin_tone": "🧝🏽", + "envelope": "✉", + "envelope_with_arrow": "📩", + "euro_banknote": "💶", + "evergreen_tree": "🌲", + "ewe": "🐑", + "exclamation_mark": "❗", + "exclamation_question_mark": "⁉", + "exploding_head": "🤯", + "expressionless_face": "😑", + "eye": "👁", + "eye_in_speech_bubble": "👁️\u200d🗨️", + "eyes": "👀", + "face_blowing_a_kiss": "😘", + "face_savoring_food": "😋", + "face_screaming_in_fear": "😱", + "face_vomiting": "🤮", + "face_with_hand_over_mouth": "🤭", + "face_with_head-bandage": "🤕", + "face_with_medical_mask": "😷", + "face_with_monocle": "🧐", + "face_with_open_mouth": "😮", + "face_with_raised_eyebrow": "🤨", + "face_with_rolling_eyes": "🙄", + "face_with_steam_from_nose": "😤", + "face_with_symbols_on_mouth": "🤬", + "face_with_tears_of_joy": "😂", + "face_with_thermometer": "🤒", + "face_with_tongue": "😛", + "face_without_mouth": "😶", + "factory": "🏭", + "fairy": "🧚", + "fairy_dark_skin_tone": "🧚🏿", + "fairy_light_skin_tone": "🧚🏻", + "fairy_medium-dark_skin_tone": "🧚🏾", + "fairy_medium-light_skin_tone": "🧚🏼", + "fairy_medium_skin_tone": "🧚🏽", + "falafel": "🧆", + "fallen_leaf": "🍂", + "family": "👪", + "family_man_boy": "👨\u200d👦", + "family_man_boy_boy": "👨\u200d👦\u200d👦", + "family_man_girl": "👨\u200d👧", + "family_man_girl_boy": "👨\u200d👧\u200d👦", + "family_man_girl_girl": "👨\u200d👧\u200d👧", + "family_man_man_boy": "👨\u200d👨\u200d👦", + "family_man_man_boy_boy": "👨\u200d👨\u200d👦\u200d👦", + "family_man_man_girl": "👨\u200d👨\u200d👧", + "family_man_man_girl_boy": "👨\u200d👨\u200d👧\u200d👦", + "family_man_man_girl_girl": "👨\u200d👨\u200d👧\u200d👧", + "family_man_woman_boy": "👨\u200d👩\u200d👦", + "family_man_woman_boy_boy": "👨\u200d👩\u200d👦\u200d👦", + "family_man_woman_girl": "👨\u200d👩\u200d👧", + "family_man_woman_girl_boy": "👨\u200d👩\u200d👧\u200d👦", + "family_man_woman_girl_girl": "👨\u200d👩\u200d👧\u200d👧", + "family_woman_boy": "👩\u200d👦", + "family_woman_boy_boy": "👩\u200d👦\u200d👦", + "family_woman_girl": "👩\u200d👧", + "family_woman_girl_boy": "👩\u200d👧\u200d👦", + "family_woman_girl_girl": "👩\u200d👧\u200d👧", + "family_woman_woman_boy": "👩\u200d👩\u200d👦", + "family_woman_woman_boy_boy": "👩\u200d👩\u200d👦\u200d👦", + "family_woman_woman_girl": "👩\u200d👩\u200d👧", + "family_woman_woman_girl_boy": "👩\u200d👩\u200d👧\u200d👦", + "family_woman_woman_girl_girl": "👩\u200d👩\u200d👧\u200d👧", + "fast-forward_button": "⏩", + "fast_down_button": "⏬", + "fast_reverse_button": "⏪", + "fast_up_button": "⏫", + "fax_machine": "📠", + "fearful_face": "😨", + "female_sign": "♀", + "ferris_wheel": "🎡", + "ferry": "⛴", + "field_hockey": "🏑", + "file_cabinet": "🗄", + "file_folder": "📁", + "film_frames": "🎞", + "film_projector": "📽", + "fire": "🔥", + "fire_extinguisher": "🧯", + "firecracker": "🧨", + "fire_engine": "🚒", + "fireworks": "🎆", + "first_quarter_moon": "🌓", + "first_quarter_moon_face": "🌛", + "fish": "🐟", + "fish_cake_with_swirl": "🍥", + "fishing_pole": "🎣", + "five-thirty": "🕠", + "five_o’clock": "🕔", + "flag_in_hole": "⛳", + "flamingo": "🦩", + "flashlight": "🔦", + "flat_shoe": "🥿", + "fleur-de-lis": "⚜", + "flexed_biceps": "💪", + "flexed_biceps_dark_skin_tone": "💪🏿", + "flexed_biceps_light_skin_tone": "💪🏻", + "flexed_biceps_medium-dark_skin_tone": "💪🏾", + "flexed_biceps_medium-light_skin_tone": "💪🏼", + "flexed_biceps_medium_skin_tone": "💪🏽", + "floppy_disk": "💾", + "flower_playing_cards": "🎴", + "flushed_face": "😳", + "flying_disc": "🥏", + "flying_saucer": "🛸", + "fog": "🌫", + "foggy": "🌁", + "folded_hands": "🙏", + "folded_hands_dark_skin_tone": "🙏🏿", + "folded_hands_light_skin_tone": "🙏🏻", + "folded_hands_medium-dark_skin_tone": "🙏🏾", + "folded_hands_medium-light_skin_tone": "🙏🏼", + "folded_hands_medium_skin_tone": "🙏🏽", + "foot": "🦶", + "footprints": "👣", + "fork_and_knife": "🍴", + "fork_and_knife_with_plate": "🍽", + "fortune_cookie": "🥠", + "fountain": "⛲", + "fountain_pen": "🖋", + "four-thirty": "🕟", + "four_leaf_clover": "🍀", + "four_o’clock": "🕓", + "fox_face": "🦊", + "framed_picture": "🖼", + "french_fries": "🍟", + "fried_shrimp": "🍤", + "frog_face": "🐸", + "front-facing_baby_chick": "🐥", + "frowning_face": "☹", + "frowning_face_with_open_mouth": "😦", + "fuel_pump": "⛽", + "full_moon": "🌕", + "full_moon_face": "🌝", + "funeral_urn": "⚱", + "game_die": "🎲", + "garlic": "🧄", + "gear": "⚙", + "gem_stone": "💎", + "genie": "🧞", + "ghost": "👻", + "giraffe": "🦒", + "girl": "👧", + "girl_dark_skin_tone": "👧🏿", + "girl_light_skin_tone": "👧🏻", + "girl_medium-dark_skin_tone": "👧🏾", + "girl_medium-light_skin_tone": "👧🏼", + "girl_medium_skin_tone": "👧🏽", + "glass_of_milk": "🥛", + "glasses": "👓", + "globe_showing_americas": "🌎", + "globe_showing_asia-australia": "🌏", + "globe_showing_europe-africa": "🌍", + "globe_with_meridians": "🌐", + "gloves": "🧤", + "glowing_star": "🌟", + "goal_net": "🥅", + "goat": "🐐", + "goblin": "👺", + "goggles": "🥽", + "gorilla": "🦍", + "graduation_cap": "🎓", + "grapes": "🍇", + "green_apple": "🍏", + "green_book": "📗", + "green_circle": "🟢", + "green_heart": "💚", + "green_salad": "🥗", + "green_square": "🟩", + "grimacing_face": "😬", + "grinning_cat_face": "😺", + "grinning_cat_face_with_smiling_eyes": "😸", + "grinning_face": "😀", + "grinning_face_with_big_eyes": "😃", + "grinning_face_with_smiling_eyes": "😄", + "grinning_face_with_sweat": "😅", + "grinning_squinting_face": "😆", + "growing_heart": "💗", + "guard": "💂", + "guard_dark_skin_tone": "💂🏿", + "guard_light_skin_tone": "💂🏻", + "guard_medium-dark_skin_tone": "💂🏾", + "guard_medium-light_skin_tone": "💂🏼", + "guard_medium_skin_tone": "💂🏽", + "guide_dog": "🦮", + "guitar": "🎸", + "hamburger": "🍔", + "hammer": "🔨", + "hammer_and_pick": "⚒", + "hammer_and_wrench": "🛠", + "hamster_face": "🐹", + "hand_with_fingers_splayed": "🖐", + "hand_with_fingers_splayed_dark_skin_tone": "🖐🏿", + "hand_with_fingers_splayed_light_skin_tone": "🖐🏻", + "hand_with_fingers_splayed_medium-dark_skin_tone": "🖐🏾", + "hand_with_fingers_splayed_medium-light_skin_tone": "🖐🏼", + "hand_with_fingers_splayed_medium_skin_tone": "🖐🏽", + "handbag": "👜", + "handshake": "🤝", + "hatching_chick": "🐣", + "headphone": "🎧", + "hear-no-evil_monkey": "🙉", + "heart_decoration": "💟", + "heart_suit": "♥", + "heart_with_arrow": "💘", + "heart_with_ribbon": "💝", + "heavy_check_mark": "✔", + "heavy_division_sign": "➗", + "heavy_dollar_sign": "💲", + "heavy_heart_exclamation": "❣", + "heavy_large_circle": "⭕", + "heavy_minus_sign": "➖", + "heavy_multiplication_x": "✖", + "heavy_plus_sign": "➕", + "hedgehog": "🦔", + "helicopter": "🚁", + "herb": "🌿", + "hibiscus": "🌺", + "high-heeled_shoe": "👠", + "high-speed_train": "🚄", + "high_voltage": "⚡", + "hiking_boot": "🥾", + "hindu_temple": "🛕", + "hippopotamus": "🦛", + "hole": "🕳", + "honey_pot": "🍯", + "honeybee": "🐝", + "horizontal_traffic_light": "🚥", + "horse": "🐴", + "horse_face": "🐴", + "horse_racing": "🏇", + "horse_racing_dark_skin_tone": "🏇🏿", + "horse_racing_light_skin_tone": "🏇🏻", + "horse_racing_medium-dark_skin_tone": "🏇🏾", + "horse_racing_medium-light_skin_tone": "🏇🏼", + "horse_racing_medium_skin_tone": "🏇🏽", + "hospital": "🏥", + "hot_beverage": "☕", + "hot_dog": "🌭", + "hot_face": "🥵", + "hot_pepper": "🌶", + "hot_springs": "♨", + "hotel": "🏨", + "hourglass_done": "⌛", + "hourglass_not_done": "⏳", + "house": "🏠", + "house_with_garden": "🏡", + "houses": "🏘", + "hugging_face": "🤗", + "hundred_points": "💯", + "hushed_face": "😯", + "ice": "🧊", + "ice_cream": "🍨", + "ice_hockey": "🏒", + "ice_skate": "⛸", + "inbox_tray": "📥", + "incoming_envelope": "📨", + "index_pointing_up": "☝", + "index_pointing_up_dark_skin_tone": "☝🏿", + "index_pointing_up_light_skin_tone": "☝🏻", + "index_pointing_up_medium-dark_skin_tone": "☝🏾", + "index_pointing_up_medium-light_skin_tone": "☝🏼", + "index_pointing_up_medium_skin_tone": "☝🏽", + "infinity": "♾", + "information": "ℹ", + "input_latin_letters": "🔤", + "input_latin_lowercase": "🔡", + "input_latin_uppercase": "🔠", + "input_numbers": "🔢", + "input_symbols": "🔣", + "jack-o-lantern": "🎃", + "jeans": "👖", + "jigsaw": "🧩", + "joker": "🃏", + "joystick": "🕹", + "kaaba": "🕋", + "kangaroo": "🦘", + "key": "🔑", + "keyboard": "⌨", + "keycap_#": "#️⃣", + "keycap_*": "*️⃣", + "keycap_0": "0️⃣", + "keycap_1": "1️⃣", + "keycap_10": "🔟", + "keycap_2": "2️⃣", + "keycap_3": "3️⃣", + "keycap_4": "4️⃣", + "keycap_5": "5️⃣", + "keycap_6": "6️⃣", + "keycap_7": "7️⃣", + "keycap_8": "8️⃣", + "keycap_9": "9️⃣", + "kick_scooter": "🛴", + "kimono": "👘", + "kiss": "💋", + "kiss_man_man": "👨\u200d❤️\u200d💋\u200d👨", + "kiss_mark": "💋", + "kiss_woman_man": "👩\u200d❤️\u200d💋\u200d👨", + "kiss_woman_woman": "👩\u200d❤️\u200d💋\u200d👩", + "kissing_cat_face": "😽", + "kissing_face": "😗", + "kissing_face_with_closed_eyes": "😚", + "kissing_face_with_smiling_eyes": "😙", + "kitchen_knife": "🔪", + "kite": "🪁", + "kiwi_fruit": "🥝", + "koala": "🐨", + "lab_coat": "🥼", + "label": "🏷", + "lacrosse": "🥍", + "lady_beetle": "🐞", + "laptop_computer": "💻", + "large_blue_diamond": "🔷", + "large_orange_diamond": "🔶", + "last_quarter_moon": "🌗", + "last_quarter_moon_face": "🌜", + "last_track_button": "⏮", + "latin_cross": "✝", + "leaf_fluttering_in_wind": "🍃", + "leafy_green": "🥬", + "ledger": "📒", + "left-facing_fist": "🤛", + "left-facing_fist_dark_skin_tone": "🤛🏿", + "left-facing_fist_light_skin_tone": "🤛🏻", + "left-facing_fist_medium-dark_skin_tone": "🤛🏾", + "left-facing_fist_medium-light_skin_tone": "🤛🏼", + "left-facing_fist_medium_skin_tone": "🤛🏽", + "left-right_arrow": "↔", + "left_arrow": "⬅", + "left_arrow_curving_right": "↪", + "left_luggage": "🛅", + "left_speech_bubble": "🗨", + "leg": "🦵", + "lemon": "🍋", + "leopard": "🐆", + "level_slider": "🎚", + "light_bulb": "💡", + "light_rail": "🚈", + "link": "🔗", + "linked_paperclips": "🖇", + "lion_face": "🦁", + "lipstick": "💄", + "litter_in_bin_sign": "🚮", + "lizard": "🦎", + "llama": "🦙", + "lobster": "🦞", + "locked": "🔒", + "locked_with_key": "🔐", + "locked_with_pen": "🔏", + "locomotive": "🚂", + "lollipop": "🍭", + "lotion_bottle": "🧴", + "loudly_crying_face": "😭", + "loudspeaker": "📢", + "love-you_gesture": "🤟", + "love-you_gesture_dark_skin_tone": "🤟🏿", + "love-you_gesture_light_skin_tone": "🤟🏻", + "love-you_gesture_medium-dark_skin_tone": "🤟🏾", + "love-you_gesture_medium-light_skin_tone": "🤟🏼", + "love-you_gesture_medium_skin_tone": "🤟🏽", + "love_hotel": "🏩", + "love_letter": "💌", + "luggage": "🧳", + "lying_face": "🤥", + "mage": "🧙", + "mage_dark_skin_tone": "🧙🏿", + "mage_light_skin_tone": "🧙🏻", + "mage_medium-dark_skin_tone": "🧙🏾", + "mage_medium-light_skin_tone": "🧙🏼", + "mage_medium_skin_tone": "🧙🏽", + "magnet": "🧲", + "magnifying_glass_tilted_left": "🔍", + "magnifying_glass_tilted_right": "🔎", + "mahjong_red_dragon": "🀄", + "male_sign": "♂", + "man": "👨", + "man_and_woman_holding_hands": "👫", + "man_artist": "👨\u200d🎨", + "man_artist_dark_skin_tone": "👨🏿\u200d🎨", + "man_artist_light_skin_tone": "👨🏻\u200d🎨", + "man_artist_medium-dark_skin_tone": "👨🏾\u200d🎨", + "man_artist_medium-light_skin_tone": "👨🏼\u200d🎨", + "man_artist_medium_skin_tone": "👨🏽\u200d🎨", + "man_astronaut": "👨\u200d🚀", + "man_astronaut_dark_skin_tone": "👨🏿\u200d🚀", + "man_astronaut_light_skin_tone": "👨🏻\u200d🚀", + "man_astronaut_medium-dark_skin_tone": "👨🏾\u200d🚀", + "man_astronaut_medium-light_skin_tone": "👨🏼\u200d🚀", + "man_astronaut_medium_skin_tone": "👨🏽\u200d🚀", + "man_biking": "🚴\u200d♂️", + "man_biking_dark_skin_tone": "🚴🏿\u200d♂️", + "man_biking_light_skin_tone": "🚴🏻\u200d♂️", + "man_biking_medium-dark_skin_tone": "🚴🏾\u200d♂️", + "man_biking_medium-light_skin_tone": "🚴🏼\u200d♂️", + "man_biking_medium_skin_tone": "🚴🏽\u200d♂️", + "man_bouncing_ball": "⛹️\u200d♂️", + "man_bouncing_ball_dark_skin_tone": "⛹🏿\u200d♂️", + "man_bouncing_ball_light_skin_tone": "⛹🏻\u200d♂️", + "man_bouncing_ball_medium-dark_skin_tone": "⛹🏾\u200d♂️", + "man_bouncing_ball_medium-light_skin_tone": "⛹🏼\u200d♂️", + "man_bouncing_ball_medium_skin_tone": "⛹🏽\u200d♂️", + "man_bowing": "🙇\u200d♂️", + "man_bowing_dark_skin_tone": "🙇🏿\u200d♂️", + "man_bowing_light_skin_tone": "🙇🏻\u200d♂️", + "man_bowing_medium-dark_skin_tone": "🙇🏾\u200d♂️", + "man_bowing_medium-light_skin_tone": "🙇🏼\u200d♂️", + "man_bowing_medium_skin_tone": "🙇🏽\u200d♂️", + "man_cartwheeling": "🤸\u200d♂️", + "man_cartwheeling_dark_skin_tone": "🤸🏿\u200d♂️", + "man_cartwheeling_light_skin_tone": "🤸🏻\u200d♂️", + "man_cartwheeling_medium-dark_skin_tone": "🤸🏾\u200d♂️", + "man_cartwheeling_medium-light_skin_tone": "🤸🏼\u200d♂️", + "man_cartwheeling_medium_skin_tone": "🤸🏽\u200d♂️", + "man_climbing": "🧗\u200d♂️", + "man_climbing_dark_skin_tone": "🧗🏿\u200d♂️", + "man_climbing_light_skin_tone": "🧗🏻\u200d♂️", + "man_climbing_medium-dark_skin_tone": "🧗🏾\u200d♂️", + "man_climbing_medium-light_skin_tone": "🧗🏼\u200d♂️", + "man_climbing_medium_skin_tone": "🧗🏽\u200d♂️", + "man_construction_worker": "👷\u200d♂️", + "man_construction_worker_dark_skin_tone": "👷🏿\u200d♂️", + "man_construction_worker_light_skin_tone": "👷🏻\u200d♂️", + "man_construction_worker_medium-dark_skin_tone": "👷🏾\u200d♂️", + "man_construction_worker_medium-light_skin_tone": "👷🏼\u200d♂️", + "man_construction_worker_medium_skin_tone": "👷🏽\u200d♂️", + "man_cook": "👨\u200d🍳", + "man_cook_dark_skin_tone": "👨🏿\u200d🍳", + "man_cook_light_skin_tone": "👨🏻\u200d🍳", + "man_cook_medium-dark_skin_tone": "👨🏾\u200d🍳", + "man_cook_medium-light_skin_tone": "👨🏼\u200d🍳", + "man_cook_medium_skin_tone": "👨🏽\u200d🍳", + "man_dancing": "🕺", + "man_dancing_dark_skin_tone": "🕺🏿", + "man_dancing_light_skin_tone": "🕺🏻", + "man_dancing_medium-dark_skin_tone": "🕺🏾", + "man_dancing_medium-light_skin_tone": "🕺🏼", + "man_dancing_medium_skin_tone": "🕺🏽", + "man_dark_skin_tone": "👨🏿", + "man_detective": "🕵️\u200d♂️", + "man_detective_dark_skin_tone": "🕵🏿\u200d♂️", + "man_detective_light_skin_tone": "🕵🏻\u200d♂️", + "man_detective_medium-dark_skin_tone": "🕵🏾\u200d♂️", + "man_detective_medium-light_skin_tone": "🕵🏼\u200d♂️", + "man_detective_medium_skin_tone": "🕵🏽\u200d♂️", + "man_elf": "🧝\u200d♂️", + "man_elf_dark_skin_tone": "🧝🏿\u200d♂️", + "man_elf_light_skin_tone": "🧝🏻\u200d♂️", + "man_elf_medium-dark_skin_tone": "🧝🏾\u200d♂️", + "man_elf_medium-light_skin_tone": "🧝🏼\u200d♂️", + "man_elf_medium_skin_tone": "🧝🏽\u200d♂️", + "man_facepalming": "🤦\u200d♂️", + "man_facepalming_dark_skin_tone": "🤦🏿\u200d♂️", + "man_facepalming_light_skin_tone": "🤦🏻\u200d♂️", + "man_facepalming_medium-dark_skin_tone": "🤦🏾\u200d♂️", + "man_facepalming_medium-light_skin_tone": "🤦🏼\u200d♂️", + "man_facepalming_medium_skin_tone": "🤦🏽\u200d♂️", + "man_factory_worker": "👨\u200d🏭", + "man_factory_worker_dark_skin_tone": "👨🏿\u200d🏭", + "man_factory_worker_light_skin_tone": "👨🏻\u200d🏭", + "man_factory_worker_medium-dark_skin_tone": "👨🏾\u200d🏭", + "man_factory_worker_medium-light_skin_tone": "👨🏼\u200d🏭", + "man_factory_worker_medium_skin_tone": "👨🏽\u200d🏭", + "man_fairy": "🧚\u200d♂️", + "man_fairy_dark_skin_tone": "🧚🏿\u200d♂️", + "man_fairy_light_skin_tone": "🧚🏻\u200d♂️", + "man_fairy_medium-dark_skin_tone": "🧚🏾\u200d♂️", + "man_fairy_medium-light_skin_tone": "🧚🏼\u200d♂️", + "man_fairy_medium_skin_tone": "🧚🏽\u200d♂️", + "man_farmer": "👨\u200d🌾", + "man_farmer_dark_skin_tone": "👨🏿\u200d🌾", + "man_farmer_light_skin_tone": "👨🏻\u200d🌾", + "man_farmer_medium-dark_skin_tone": "👨🏾\u200d🌾", + "man_farmer_medium-light_skin_tone": "👨🏼\u200d🌾", + "man_farmer_medium_skin_tone": "👨🏽\u200d🌾", + "man_firefighter": "👨\u200d🚒", + "man_firefighter_dark_skin_tone": "👨🏿\u200d🚒", + "man_firefighter_light_skin_tone": "👨🏻\u200d🚒", + "man_firefighter_medium-dark_skin_tone": "👨🏾\u200d🚒", + "man_firefighter_medium-light_skin_tone": "👨🏼\u200d🚒", + "man_firefighter_medium_skin_tone": "👨🏽\u200d🚒", + "man_frowning": "🙍\u200d♂️", + "man_frowning_dark_skin_tone": "🙍🏿\u200d♂️", + "man_frowning_light_skin_tone": "🙍🏻\u200d♂️", + "man_frowning_medium-dark_skin_tone": "🙍🏾\u200d♂️", + "man_frowning_medium-light_skin_tone": "🙍🏼\u200d♂️", + "man_frowning_medium_skin_tone": "🙍🏽\u200d♂️", + "man_genie": "🧞\u200d♂️", + "man_gesturing_no": "🙅\u200d♂️", + "man_gesturing_no_dark_skin_tone": "🙅🏿\u200d♂️", + "man_gesturing_no_light_skin_tone": "🙅🏻\u200d♂️", + "man_gesturing_no_medium-dark_skin_tone": "🙅🏾\u200d♂️", + "man_gesturing_no_medium-light_skin_tone": "🙅🏼\u200d♂️", + "man_gesturing_no_medium_skin_tone": "🙅🏽\u200d♂️", + "man_gesturing_ok": "🙆\u200d♂️", + "man_gesturing_ok_dark_skin_tone": "🙆🏿\u200d♂️", + "man_gesturing_ok_light_skin_tone": "🙆🏻\u200d♂️", + "man_gesturing_ok_medium-dark_skin_tone": "🙆🏾\u200d♂️", + "man_gesturing_ok_medium-light_skin_tone": "🙆🏼\u200d♂️", + "man_gesturing_ok_medium_skin_tone": "🙆🏽\u200d♂️", + "man_getting_haircut": "💇\u200d♂️", + "man_getting_haircut_dark_skin_tone": "💇🏿\u200d♂️", + "man_getting_haircut_light_skin_tone": "💇🏻\u200d♂️", + "man_getting_haircut_medium-dark_skin_tone": "💇🏾\u200d♂️", + "man_getting_haircut_medium-light_skin_tone": "💇🏼\u200d♂️", + "man_getting_haircut_medium_skin_tone": "💇🏽\u200d♂️", + "man_getting_massage": "💆\u200d♂️", + "man_getting_massage_dark_skin_tone": "💆🏿\u200d♂️", + "man_getting_massage_light_skin_tone": "💆🏻\u200d♂️", + "man_getting_massage_medium-dark_skin_tone": "💆🏾\u200d♂️", + "man_getting_massage_medium-light_skin_tone": "💆🏼\u200d♂️", + "man_getting_massage_medium_skin_tone": "💆🏽\u200d♂️", + "man_golfing": "🏌️\u200d♂️", + "man_golfing_dark_skin_tone": "🏌🏿\u200d♂️", + "man_golfing_light_skin_tone": "🏌🏻\u200d♂️", + "man_golfing_medium-dark_skin_tone": "🏌🏾\u200d♂️", + "man_golfing_medium-light_skin_tone": "🏌🏼\u200d♂️", + "man_golfing_medium_skin_tone": "🏌🏽\u200d♂️", + "man_guard": "💂\u200d♂️", + "man_guard_dark_skin_tone": "💂🏿\u200d♂️", + "man_guard_light_skin_tone": "💂🏻\u200d♂️", + "man_guard_medium-dark_skin_tone": "💂🏾\u200d♂️", + "man_guard_medium-light_skin_tone": "💂🏼\u200d♂️", + "man_guard_medium_skin_tone": "💂🏽\u200d♂️", + "man_health_worker": "👨\u200d⚕️", + "man_health_worker_dark_skin_tone": "👨🏿\u200d⚕️", + "man_health_worker_light_skin_tone": "👨🏻\u200d⚕️", + "man_health_worker_medium-dark_skin_tone": "👨🏾\u200d⚕️", + "man_health_worker_medium-light_skin_tone": "👨🏼\u200d⚕️", + "man_health_worker_medium_skin_tone": "👨🏽\u200d⚕️", + "man_in_lotus_position": "🧘\u200d♂️", + "man_in_lotus_position_dark_skin_tone": "🧘🏿\u200d♂️", + "man_in_lotus_position_light_skin_tone": "🧘🏻\u200d♂️", + "man_in_lotus_position_medium-dark_skin_tone": "🧘🏾\u200d♂️", + "man_in_lotus_position_medium-light_skin_tone": "🧘🏼\u200d♂️", + "man_in_lotus_position_medium_skin_tone": "🧘🏽\u200d♂️", + "man_in_manual_wheelchair": "👨\u200d🦽", + "man_in_motorized_wheelchair": "👨\u200d🦼", + "man_in_steamy_room": "🧖\u200d♂️", + "man_in_steamy_room_dark_skin_tone": "🧖🏿\u200d♂️", + "man_in_steamy_room_light_skin_tone": "🧖🏻\u200d♂️", + "man_in_steamy_room_medium-dark_skin_tone": "🧖🏾\u200d♂️", + "man_in_steamy_room_medium-light_skin_tone": "🧖🏼\u200d♂️", + "man_in_steamy_room_medium_skin_tone": "🧖🏽\u200d♂️", + "man_in_suit_levitating": "🕴", + "man_in_suit_levitating_dark_skin_tone": "🕴🏿", + "man_in_suit_levitating_light_skin_tone": "🕴🏻", + "man_in_suit_levitating_medium-dark_skin_tone": "🕴🏾", + "man_in_suit_levitating_medium-light_skin_tone": "🕴🏼", + "man_in_suit_levitating_medium_skin_tone": "🕴🏽", + "man_in_tuxedo": "🤵", + "man_in_tuxedo_dark_skin_tone": "🤵🏿", + "man_in_tuxedo_light_skin_tone": "🤵🏻", + "man_in_tuxedo_medium-dark_skin_tone": "🤵🏾", + "man_in_tuxedo_medium-light_skin_tone": "🤵🏼", + "man_in_tuxedo_medium_skin_tone": "🤵🏽", + "man_judge": "👨\u200d⚖️", + "man_judge_dark_skin_tone": "👨🏿\u200d⚖️", + "man_judge_light_skin_tone": "👨🏻\u200d⚖️", + "man_judge_medium-dark_skin_tone": "👨🏾\u200d⚖️", + "man_judge_medium-light_skin_tone": "👨🏼\u200d⚖️", + "man_judge_medium_skin_tone": "👨🏽\u200d⚖️", + "man_juggling": "🤹\u200d♂️", + "man_juggling_dark_skin_tone": "🤹🏿\u200d♂️", + "man_juggling_light_skin_tone": "🤹🏻\u200d♂️", + "man_juggling_medium-dark_skin_tone": "🤹🏾\u200d♂️", + "man_juggling_medium-light_skin_tone": "🤹🏼\u200d♂️", + "man_juggling_medium_skin_tone": "🤹🏽\u200d♂️", + "man_lifting_weights": "🏋️\u200d♂️", + "man_lifting_weights_dark_skin_tone": "🏋🏿\u200d♂️", + "man_lifting_weights_light_skin_tone": "🏋🏻\u200d♂️", + "man_lifting_weights_medium-dark_skin_tone": "🏋🏾\u200d♂️", + "man_lifting_weights_medium-light_skin_tone": "🏋🏼\u200d♂️", + "man_lifting_weights_medium_skin_tone": "🏋🏽\u200d♂️", + "man_light_skin_tone": "👨🏻", + "man_mage": "🧙\u200d♂️", + "man_mage_dark_skin_tone": "🧙🏿\u200d♂️", + "man_mage_light_skin_tone": "🧙🏻\u200d♂️", + "man_mage_medium-dark_skin_tone": "🧙🏾\u200d♂️", + "man_mage_medium-light_skin_tone": "🧙🏼\u200d♂️", + "man_mage_medium_skin_tone": "🧙🏽\u200d♂️", + "man_mechanic": "👨\u200d🔧", + "man_mechanic_dark_skin_tone": "👨🏿\u200d🔧", + "man_mechanic_light_skin_tone": "👨🏻\u200d🔧", + "man_mechanic_medium-dark_skin_tone": "👨🏾\u200d🔧", + "man_mechanic_medium-light_skin_tone": "👨🏼\u200d🔧", + "man_mechanic_medium_skin_tone": "👨🏽\u200d🔧", + "man_medium-dark_skin_tone": "👨🏾", + "man_medium-light_skin_tone": "👨🏼", + "man_medium_skin_tone": "👨🏽", + "man_mountain_biking": "🚵\u200d♂️", + "man_mountain_biking_dark_skin_tone": "🚵🏿\u200d♂️", + "man_mountain_biking_light_skin_tone": "🚵🏻\u200d♂️", + "man_mountain_biking_medium-dark_skin_tone": "🚵🏾\u200d♂️", + "man_mountain_biking_medium-light_skin_tone": "🚵🏼\u200d♂️", + "man_mountain_biking_medium_skin_tone": "🚵🏽\u200d♂️", + "man_office_worker": "👨\u200d💼", + "man_office_worker_dark_skin_tone": "👨🏿\u200d💼", + "man_office_worker_light_skin_tone": "👨🏻\u200d💼", + "man_office_worker_medium-dark_skin_tone": "👨🏾\u200d💼", + "man_office_worker_medium-light_skin_tone": "👨🏼\u200d💼", + "man_office_worker_medium_skin_tone": "👨🏽\u200d💼", + "man_pilot": "👨\u200d✈️", + "man_pilot_dark_skin_tone": "👨🏿\u200d✈️", + "man_pilot_light_skin_tone": "👨🏻\u200d✈️", + "man_pilot_medium-dark_skin_tone": "👨🏾\u200d✈️", + "man_pilot_medium-light_skin_tone": "👨🏼\u200d✈️", + "man_pilot_medium_skin_tone": "👨🏽\u200d✈️", + "man_playing_handball": "🤾\u200d♂️", + "man_playing_handball_dark_skin_tone": "🤾🏿\u200d♂️", + "man_playing_handball_light_skin_tone": "🤾🏻\u200d♂️", + "man_playing_handball_medium-dark_skin_tone": "🤾🏾\u200d♂️", + "man_playing_handball_medium-light_skin_tone": "🤾🏼\u200d♂️", + "man_playing_handball_medium_skin_tone": "🤾🏽\u200d♂️", + "man_playing_water_polo": "🤽\u200d♂️", + "man_playing_water_polo_dark_skin_tone": "🤽🏿\u200d♂️", + "man_playing_water_polo_light_skin_tone": "🤽🏻\u200d♂️", + "man_playing_water_polo_medium-dark_skin_tone": "🤽🏾\u200d♂️", + "man_playing_water_polo_medium-light_skin_tone": "🤽🏼\u200d♂️", + "man_playing_water_polo_medium_skin_tone": "🤽🏽\u200d♂️", + "man_police_officer": "👮\u200d♂️", + "man_police_officer_dark_skin_tone": "👮🏿\u200d♂️", + "man_police_officer_light_skin_tone": "👮🏻\u200d♂️", + "man_police_officer_medium-dark_skin_tone": "👮🏾\u200d♂️", + "man_police_officer_medium-light_skin_tone": "👮🏼\u200d♂️", + "man_police_officer_medium_skin_tone": "👮🏽\u200d♂️", + "man_pouting": "🙎\u200d♂️", + "man_pouting_dark_skin_tone": "🙎🏿\u200d♂️", + "man_pouting_light_skin_tone": "🙎🏻\u200d♂️", + "man_pouting_medium-dark_skin_tone": "🙎🏾\u200d♂️", + "man_pouting_medium-light_skin_tone": "🙎🏼\u200d♂️", + "man_pouting_medium_skin_tone": "🙎🏽\u200d♂️", + "man_raising_hand": "🙋\u200d♂️", + "man_raising_hand_dark_skin_tone": "🙋🏿\u200d♂️", + "man_raising_hand_light_skin_tone": "🙋🏻\u200d♂️", + "man_raising_hand_medium-dark_skin_tone": "🙋🏾\u200d♂️", + "man_raising_hand_medium-light_skin_tone": "🙋🏼\u200d♂️", + "man_raising_hand_medium_skin_tone": "🙋🏽\u200d♂️", + "man_rowing_boat": "🚣\u200d♂️", + "man_rowing_boat_dark_skin_tone": "🚣🏿\u200d♂️", + "man_rowing_boat_light_skin_tone": "🚣🏻\u200d♂️", + "man_rowing_boat_medium-dark_skin_tone": "🚣🏾\u200d♂️", + "man_rowing_boat_medium-light_skin_tone": "🚣🏼\u200d♂️", + "man_rowing_boat_medium_skin_tone": "🚣🏽\u200d♂️", + "man_running": "🏃\u200d♂️", + "man_running_dark_skin_tone": "🏃🏿\u200d♂️", + "man_running_light_skin_tone": "🏃🏻\u200d♂️", + "man_running_medium-dark_skin_tone": "🏃🏾\u200d♂️", + "man_running_medium-light_skin_tone": "🏃🏼\u200d♂️", + "man_running_medium_skin_tone": "🏃🏽\u200d♂️", + "man_scientist": "👨\u200d🔬", + "man_scientist_dark_skin_tone": "👨🏿\u200d🔬", + "man_scientist_light_skin_tone": "👨🏻\u200d🔬", + "man_scientist_medium-dark_skin_tone": "👨🏾\u200d🔬", + "man_scientist_medium-light_skin_tone": "👨🏼\u200d🔬", + "man_scientist_medium_skin_tone": "👨🏽\u200d🔬", + "man_shrugging": "🤷\u200d♂️", + "man_shrugging_dark_skin_tone": "🤷🏿\u200d♂️", + "man_shrugging_light_skin_tone": "🤷🏻\u200d♂️", + "man_shrugging_medium-dark_skin_tone": "🤷🏾\u200d♂️", + "man_shrugging_medium-light_skin_tone": "🤷🏼\u200d♂️", + "man_shrugging_medium_skin_tone": "🤷🏽\u200d♂️", + "man_singer": "👨\u200d🎤", + "man_singer_dark_skin_tone": "👨🏿\u200d🎤", + "man_singer_light_skin_tone": "👨🏻\u200d🎤", + "man_singer_medium-dark_skin_tone": "👨🏾\u200d🎤", + "man_singer_medium-light_skin_tone": "👨🏼\u200d🎤", + "man_singer_medium_skin_tone": "👨🏽\u200d🎤", + "man_student": "👨\u200d🎓", + "man_student_dark_skin_tone": "👨🏿\u200d🎓", + "man_student_light_skin_tone": "👨🏻\u200d🎓", + "man_student_medium-dark_skin_tone": "👨🏾\u200d🎓", + "man_student_medium-light_skin_tone": "👨🏼\u200d🎓", + "man_student_medium_skin_tone": "👨🏽\u200d🎓", + "man_surfing": "🏄\u200d♂️", + "man_surfing_dark_skin_tone": "🏄🏿\u200d♂️", + "man_surfing_light_skin_tone": "🏄🏻\u200d♂️", + "man_surfing_medium-dark_skin_tone": "🏄🏾\u200d♂️", + "man_surfing_medium-light_skin_tone": "🏄🏼\u200d♂️", + "man_surfing_medium_skin_tone": "🏄🏽\u200d♂️", + "man_swimming": "🏊\u200d♂️", + "man_swimming_dark_skin_tone": "🏊🏿\u200d♂️", + "man_swimming_light_skin_tone": "🏊🏻\u200d♂️", + "man_swimming_medium-dark_skin_tone": "🏊🏾\u200d♂️", + "man_swimming_medium-light_skin_tone": "🏊🏼\u200d♂️", + "man_swimming_medium_skin_tone": "🏊🏽\u200d♂️", + "man_teacher": "👨\u200d🏫", + "man_teacher_dark_skin_tone": "👨🏿\u200d🏫", + "man_teacher_light_skin_tone": "👨🏻\u200d🏫", + "man_teacher_medium-dark_skin_tone": "👨🏾\u200d🏫", + "man_teacher_medium-light_skin_tone": "👨🏼\u200d🏫", + "man_teacher_medium_skin_tone": "👨🏽\u200d🏫", + "man_technologist": "👨\u200d💻", + "man_technologist_dark_skin_tone": "👨🏿\u200d💻", + "man_technologist_light_skin_tone": "👨🏻\u200d💻", + "man_technologist_medium-dark_skin_tone": "👨🏾\u200d💻", + "man_technologist_medium-light_skin_tone": "👨🏼\u200d💻", + "man_technologist_medium_skin_tone": "👨🏽\u200d💻", + "man_tipping_hand": "💁\u200d♂️", + "man_tipping_hand_dark_skin_tone": "💁🏿\u200d♂️", + "man_tipping_hand_light_skin_tone": "💁🏻\u200d♂️", + "man_tipping_hand_medium-dark_skin_tone": "💁🏾\u200d♂️", + "man_tipping_hand_medium-light_skin_tone": "💁🏼\u200d♂️", + "man_tipping_hand_medium_skin_tone": "💁🏽\u200d♂️", + "man_vampire": "🧛\u200d♂️", + "man_vampire_dark_skin_tone": "🧛🏿\u200d♂️", + "man_vampire_light_skin_tone": "🧛🏻\u200d♂️", + "man_vampire_medium-dark_skin_tone": "🧛🏾\u200d♂️", + "man_vampire_medium-light_skin_tone": "🧛🏼\u200d♂️", + "man_vampire_medium_skin_tone": "🧛🏽\u200d♂️", + "man_walking": "🚶\u200d♂️", + "man_walking_dark_skin_tone": "🚶🏿\u200d♂️", + "man_walking_light_skin_tone": "🚶🏻\u200d♂️", + "man_walking_medium-dark_skin_tone": "🚶🏾\u200d♂️", + "man_walking_medium-light_skin_tone": "🚶🏼\u200d♂️", + "man_walking_medium_skin_tone": "🚶🏽\u200d♂️", + "man_wearing_turban": "👳\u200d♂️", + "man_wearing_turban_dark_skin_tone": "👳🏿\u200d♂️", + "man_wearing_turban_light_skin_tone": "👳🏻\u200d♂️", + "man_wearing_turban_medium-dark_skin_tone": "👳🏾\u200d♂️", + "man_wearing_turban_medium-light_skin_tone": "👳🏼\u200d♂️", + "man_wearing_turban_medium_skin_tone": "👳🏽\u200d♂️", + "man_with_probing_cane": "👨\u200d🦯", + "man_with_chinese_cap": "👲", + "man_with_chinese_cap_dark_skin_tone": "👲🏿", + "man_with_chinese_cap_light_skin_tone": "👲🏻", + "man_with_chinese_cap_medium-dark_skin_tone": "👲🏾", + "man_with_chinese_cap_medium-light_skin_tone": "👲🏼", + "man_with_chinese_cap_medium_skin_tone": "👲🏽", + "man_zombie": "🧟\u200d♂️", + "mango": "🥭", + "mantelpiece_clock": "🕰", + "manual_wheelchair": "🦽", + "man’s_shoe": "👞", + "map_of_japan": "🗾", + "maple_leaf": "🍁", + "martial_arts_uniform": "🥋", + "mate": "🧉", + "meat_on_bone": "🍖", + "mechanical_arm": "🦾", + "mechanical_leg": "🦿", + "medical_symbol": "⚕", + "megaphone": "📣", + "melon": "🍈", + "memo": "📝", + "men_with_bunny_ears": "👯\u200d♂️", + "men_wrestling": "🤼\u200d♂️", + "menorah": "🕎", + "men’s_room": "🚹", + "mermaid": "🧜\u200d♀️", + "mermaid_dark_skin_tone": "🧜🏿\u200d♀️", + "mermaid_light_skin_tone": "🧜🏻\u200d♀️", + "mermaid_medium-dark_skin_tone": "🧜🏾\u200d♀️", + "mermaid_medium-light_skin_tone": "🧜🏼\u200d♀️", + "mermaid_medium_skin_tone": "🧜🏽\u200d♀️", + "merman": "🧜\u200d♂️", + "merman_dark_skin_tone": "🧜🏿\u200d♂️", + "merman_light_skin_tone": "🧜🏻\u200d♂️", + "merman_medium-dark_skin_tone": "🧜🏾\u200d♂️", + "merman_medium-light_skin_tone": "🧜🏼\u200d♂️", + "merman_medium_skin_tone": "🧜🏽\u200d♂️", + "merperson": "🧜", + "merperson_dark_skin_tone": "🧜🏿", + "merperson_light_skin_tone": "🧜🏻", + "merperson_medium-dark_skin_tone": "🧜🏾", + "merperson_medium-light_skin_tone": "🧜🏼", + "merperson_medium_skin_tone": "🧜🏽", + "metro": "🚇", + "microbe": "🦠", + "microphone": "🎤", + "microscope": "🔬", + "middle_finger": "🖕", + "middle_finger_dark_skin_tone": "🖕🏿", + "middle_finger_light_skin_tone": "🖕🏻", + "middle_finger_medium-dark_skin_tone": "🖕🏾", + "middle_finger_medium-light_skin_tone": "🖕🏼", + "middle_finger_medium_skin_tone": "🖕🏽", + "military_medal": "🎖", + "milky_way": "🌌", + "minibus": "🚐", + "moai": "🗿", + "mobile_phone": "📱", + "mobile_phone_off": "📴", + "mobile_phone_with_arrow": "📲", + "money-mouth_face": "🤑", + "money_bag": "💰", + "money_with_wings": "💸", + "monkey": "🐒", + "monkey_face": "🐵", + "monorail": "🚝", + "moon_cake": "🥮", + "moon_viewing_ceremony": "🎑", + "mosque": "🕌", + "mosquito": "🦟", + "motor_boat": "🛥", + "motor_scooter": "🛵", + "motorcycle": "🏍", + "motorized_wheelchair": "🦼", + "motorway": "🛣", + "mount_fuji": "🗻", + "mountain": "⛰", + "mountain_cableway": "🚠", + "mountain_railway": "🚞", + "mouse": "🐭", + "mouse_face": "🐭", + "mouth": "👄", + "movie_camera": "🎥", + "mushroom": "🍄", + "musical_keyboard": "🎹", + "musical_note": "🎵", + "musical_notes": "🎶", + "musical_score": "🎼", + "muted_speaker": "🔇", + "nail_polish": "💅", + "nail_polish_dark_skin_tone": "💅🏿", + "nail_polish_light_skin_tone": "💅🏻", + "nail_polish_medium-dark_skin_tone": "💅🏾", + "nail_polish_medium-light_skin_tone": "💅🏼", + "nail_polish_medium_skin_tone": "💅🏽", + "name_badge": "📛", + "national_park": "🏞", + "nauseated_face": "🤢", + "nazar_amulet": "🧿", + "necktie": "👔", + "nerd_face": "🤓", + "neutral_face": "😐", + "new_moon": "🌑", + "new_moon_face": "🌚", + "newspaper": "📰", + "next_track_button": "⏭", + "night_with_stars": "🌃", + "nine-thirty": "🕤", + "nine_o’clock": "🕘", + "no_bicycles": "🚳", + "no_entry": "⛔", + "no_littering": "🚯", + "no_mobile_phones": "📵", + "no_one_under_eighteen": "🔞", + "no_pedestrians": "🚷", + "no_smoking": "🚭", + "non-potable_water": "🚱", + "nose": "👃", + "nose_dark_skin_tone": "👃🏿", + "nose_light_skin_tone": "👃🏻", + "nose_medium-dark_skin_tone": "👃🏾", + "nose_medium-light_skin_tone": "👃🏼", + "nose_medium_skin_tone": "👃🏽", + "notebook": "📓", + "notebook_with_decorative_cover": "📔", + "nut_and_bolt": "🔩", + "octopus": "🐙", + "oden": "🍢", + "office_building": "🏢", + "ogre": "👹", + "oil_drum": "🛢", + "old_key": "🗝", + "old_man": "👴", + "old_man_dark_skin_tone": "👴🏿", + "old_man_light_skin_tone": "👴🏻", + "old_man_medium-dark_skin_tone": "👴🏾", + "old_man_medium-light_skin_tone": "👴🏼", + "old_man_medium_skin_tone": "👴🏽", + "old_woman": "👵", + "old_woman_dark_skin_tone": "👵🏿", + "old_woman_light_skin_tone": "👵🏻", + "old_woman_medium-dark_skin_tone": "👵🏾", + "old_woman_medium-light_skin_tone": "👵🏼", + "old_woman_medium_skin_tone": "👵🏽", + "older_adult": "🧓", + "older_adult_dark_skin_tone": "🧓🏿", + "older_adult_light_skin_tone": "🧓🏻", + "older_adult_medium-dark_skin_tone": "🧓🏾", + "older_adult_medium-light_skin_tone": "🧓🏼", + "older_adult_medium_skin_tone": "🧓🏽", + "om": "🕉", + "oncoming_automobile": "🚘", + "oncoming_bus": "🚍", + "oncoming_fist": "👊", + "oncoming_fist_dark_skin_tone": "👊🏿", + "oncoming_fist_light_skin_tone": "👊🏻", + "oncoming_fist_medium-dark_skin_tone": "👊🏾", + "oncoming_fist_medium-light_skin_tone": "👊🏼", + "oncoming_fist_medium_skin_tone": "👊🏽", + "oncoming_police_car": "🚔", + "oncoming_taxi": "🚖", + "one-piece_swimsuit": "🩱", + "one-thirty": "🕜", + "one_o’clock": "🕐", + "onion": "🧅", + "open_book": "📖", + "open_file_folder": "📂", + "open_hands": "👐", + "open_hands_dark_skin_tone": "👐🏿", + "open_hands_light_skin_tone": "👐🏻", + "open_hands_medium-dark_skin_tone": "👐🏾", + "open_hands_medium-light_skin_tone": "👐🏼", + "open_hands_medium_skin_tone": "👐🏽", + "open_mailbox_with_lowered_flag": "📭", + "open_mailbox_with_raised_flag": "📬", + "optical_disk": "💿", + "orange_book": "📙", + "orange_circle": "🟠", + "orange_heart": "🧡", + "orange_square": "🟧", + "orangutan": "🦧", + "orthodox_cross": "☦", + "otter": "🦦", + "outbox_tray": "📤", + "owl": "🦉", + "ox": "🐂", + "oyster": "🦪", + "package": "📦", + "page_facing_up": "📄", + "page_with_curl": "📃", + "pager": "📟", + "paintbrush": "🖌", + "palm_tree": "🌴", + "palms_up_together": "🤲", + "palms_up_together_dark_skin_tone": "🤲🏿", + "palms_up_together_light_skin_tone": "🤲🏻", + "palms_up_together_medium-dark_skin_tone": "🤲🏾", + "palms_up_together_medium-light_skin_tone": "🤲🏼", + "palms_up_together_medium_skin_tone": "🤲🏽", + "pancakes": "🥞", + "panda_face": "🐼", + "paperclip": "📎", + "parrot": "🦜", + "part_alternation_mark": "〽", + "party_popper": "🎉", + "partying_face": "🥳", + "passenger_ship": "🛳", + "passport_control": "🛂", + "pause_button": "⏸", + "paw_prints": "🐾", + "peace_symbol": "☮", + "peach": "🍑", + "peacock": "🦚", + "peanuts": "🥜", + "pear": "🍐", + "pen": "🖊", + "pencil": "📝", + "penguin": "🐧", + "pensive_face": "😔", + "people_holding_hands": "🧑\u200d🤝\u200d🧑", + "people_with_bunny_ears": "👯", + "people_wrestling": "🤼", + "performing_arts": "🎭", + "persevering_face": "😣", + "person_biking": "🚴", + "person_biking_dark_skin_tone": "🚴🏿", + "person_biking_light_skin_tone": "🚴🏻", + "person_biking_medium-dark_skin_tone": "🚴🏾", + "person_biking_medium-light_skin_tone": "🚴🏼", + "person_biking_medium_skin_tone": "🚴🏽", + "person_bouncing_ball": "⛹", + "person_bouncing_ball_dark_skin_tone": "⛹🏿", + "person_bouncing_ball_light_skin_tone": "⛹🏻", + "person_bouncing_ball_medium-dark_skin_tone": "⛹🏾", + "person_bouncing_ball_medium-light_skin_tone": "⛹🏼", + "person_bouncing_ball_medium_skin_tone": "⛹🏽", + "person_bowing": "🙇", + "person_bowing_dark_skin_tone": "🙇🏿", + "person_bowing_light_skin_tone": "🙇🏻", + "person_bowing_medium-dark_skin_tone": "🙇🏾", + "person_bowing_medium-light_skin_tone": "🙇🏼", + "person_bowing_medium_skin_tone": "🙇🏽", + "person_cartwheeling": "🤸", + "person_cartwheeling_dark_skin_tone": "🤸🏿", + "person_cartwheeling_light_skin_tone": "🤸🏻", + "person_cartwheeling_medium-dark_skin_tone": "🤸🏾", + "person_cartwheeling_medium-light_skin_tone": "🤸🏼", + "person_cartwheeling_medium_skin_tone": "🤸🏽", + "person_climbing": "🧗", + "person_climbing_dark_skin_tone": "🧗🏿", + "person_climbing_light_skin_tone": "🧗🏻", + "person_climbing_medium-dark_skin_tone": "🧗🏾", + "person_climbing_medium-light_skin_tone": "🧗🏼", + "person_climbing_medium_skin_tone": "🧗🏽", + "person_facepalming": "🤦", + "person_facepalming_dark_skin_tone": "🤦🏿", + "person_facepalming_light_skin_tone": "🤦🏻", + "person_facepalming_medium-dark_skin_tone": "🤦🏾", + "person_facepalming_medium-light_skin_tone": "🤦🏼", + "person_facepalming_medium_skin_tone": "🤦🏽", + "person_fencing": "🤺", + "person_frowning": "🙍", + "person_frowning_dark_skin_tone": "🙍🏿", + "person_frowning_light_skin_tone": "🙍🏻", + "person_frowning_medium-dark_skin_tone": "🙍🏾", + "person_frowning_medium-light_skin_tone": "🙍🏼", + "person_frowning_medium_skin_tone": "🙍🏽", + "person_gesturing_no": "🙅", + "person_gesturing_no_dark_skin_tone": "🙅🏿", + "person_gesturing_no_light_skin_tone": "🙅🏻", + "person_gesturing_no_medium-dark_skin_tone": "🙅🏾", + "person_gesturing_no_medium-light_skin_tone": "🙅🏼", + "person_gesturing_no_medium_skin_tone": "🙅🏽", + "person_gesturing_ok": "🙆", + "person_gesturing_ok_dark_skin_tone": "🙆🏿", + "person_gesturing_ok_light_skin_tone": "🙆🏻", + "person_gesturing_ok_medium-dark_skin_tone": "🙆🏾", + "person_gesturing_ok_medium-light_skin_tone": "🙆🏼", + "person_gesturing_ok_medium_skin_tone": "🙆🏽", + "person_getting_haircut": "💇", + "person_getting_haircut_dark_skin_tone": "💇🏿", + "person_getting_haircut_light_skin_tone": "💇🏻", + "person_getting_haircut_medium-dark_skin_tone": "💇🏾", + "person_getting_haircut_medium-light_skin_tone": "💇🏼", + "person_getting_haircut_medium_skin_tone": "💇🏽", + "person_getting_massage": "💆", + "person_getting_massage_dark_skin_tone": "💆🏿", + "person_getting_massage_light_skin_tone": "💆🏻", + "person_getting_massage_medium-dark_skin_tone": "💆🏾", + "person_getting_massage_medium-light_skin_tone": "💆🏼", + "person_getting_massage_medium_skin_tone": "💆🏽", + "person_golfing": "🏌", + "person_golfing_dark_skin_tone": "🏌🏿", + "person_golfing_light_skin_tone": "🏌🏻", + "person_golfing_medium-dark_skin_tone": "🏌🏾", + "person_golfing_medium-light_skin_tone": "🏌🏼", + "person_golfing_medium_skin_tone": "🏌🏽", + "person_in_bed": "🛌", + "person_in_bed_dark_skin_tone": "🛌🏿", + "person_in_bed_light_skin_tone": "🛌🏻", + "person_in_bed_medium-dark_skin_tone": "🛌🏾", + "person_in_bed_medium-light_skin_tone": "🛌🏼", + "person_in_bed_medium_skin_tone": "🛌🏽", + "person_in_lotus_position": "🧘", + "person_in_lotus_position_dark_skin_tone": "🧘🏿", + "person_in_lotus_position_light_skin_tone": "🧘🏻", + "person_in_lotus_position_medium-dark_skin_tone": "🧘🏾", + "person_in_lotus_position_medium-light_skin_tone": "🧘🏼", + "person_in_lotus_position_medium_skin_tone": "🧘🏽", + "person_in_steamy_room": "🧖", + "person_in_steamy_room_dark_skin_tone": "🧖🏿", + "person_in_steamy_room_light_skin_tone": "🧖🏻", + "person_in_steamy_room_medium-dark_skin_tone": "🧖🏾", + "person_in_steamy_room_medium-light_skin_tone": "🧖🏼", + "person_in_steamy_room_medium_skin_tone": "🧖🏽", + "person_juggling": "🤹", + "person_juggling_dark_skin_tone": "🤹🏿", + "person_juggling_light_skin_tone": "🤹🏻", + "person_juggling_medium-dark_skin_tone": "🤹🏾", + "person_juggling_medium-light_skin_tone": "🤹🏼", + "person_juggling_medium_skin_tone": "🤹🏽", + "person_kneeling": "🧎", + "person_lifting_weights": "🏋", + "person_lifting_weights_dark_skin_tone": "🏋🏿", + "person_lifting_weights_light_skin_tone": "🏋🏻", + "person_lifting_weights_medium-dark_skin_tone": "🏋🏾", + "person_lifting_weights_medium-light_skin_tone": "🏋🏼", + "person_lifting_weights_medium_skin_tone": "🏋🏽", + "person_mountain_biking": "🚵", + "person_mountain_biking_dark_skin_tone": "🚵🏿", + "person_mountain_biking_light_skin_tone": "🚵🏻", + "person_mountain_biking_medium-dark_skin_tone": "🚵🏾", + "person_mountain_biking_medium-light_skin_tone": "🚵🏼", + "person_mountain_biking_medium_skin_tone": "🚵🏽", + "person_playing_handball": "🤾", + "person_playing_handball_dark_skin_tone": "🤾🏿", + "person_playing_handball_light_skin_tone": "🤾🏻", + "person_playing_handball_medium-dark_skin_tone": "🤾🏾", + "person_playing_handball_medium-light_skin_tone": "🤾🏼", + "person_playing_handball_medium_skin_tone": "🤾🏽", + "person_playing_water_polo": "🤽", + "person_playing_water_polo_dark_skin_tone": "🤽🏿", + "person_playing_water_polo_light_skin_tone": "🤽🏻", + "person_playing_water_polo_medium-dark_skin_tone": "🤽🏾", + "person_playing_water_polo_medium-light_skin_tone": "🤽🏼", + "person_playing_water_polo_medium_skin_tone": "🤽🏽", + "person_pouting": "🙎", + "person_pouting_dark_skin_tone": "🙎🏿", + "person_pouting_light_skin_tone": "🙎🏻", + "person_pouting_medium-dark_skin_tone": "🙎🏾", + "person_pouting_medium-light_skin_tone": "🙎🏼", + "person_pouting_medium_skin_tone": "🙎🏽", + "person_raising_hand": "🙋", + "person_raising_hand_dark_skin_tone": "🙋🏿", + "person_raising_hand_light_skin_tone": "🙋🏻", + "person_raising_hand_medium-dark_skin_tone": "🙋🏾", + "person_raising_hand_medium-light_skin_tone": "🙋🏼", + "person_raising_hand_medium_skin_tone": "🙋🏽", + "person_rowing_boat": "🚣", + "person_rowing_boat_dark_skin_tone": "🚣🏿", + "person_rowing_boat_light_skin_tone": "🚣🏻", + "person_rowing_boat_medium-dark_skin_tone": "🚣🏾", + "person_rowing_boat_medium-light_skin_tone": "🚣🏼", + "person_rowing_boat_medium_skin_tone": "🚣🏽", + "person_running": "🏃", + "person_running_dark_skin_tone": "🏃🏿", + "person_running_light_skin_tone": "🏃🏻", + "person_running_medium-dark_skin_tone": "🏃🏾", + "person_running_medium-light_skin_tone": "🏃🏼", + "person_running_medium_skin_tone": "🏃🏽", + "person_shrugging": "🤷", + "person_shrugging_dark_skin_tone": "🤷🏿", + "person_shrugging_light_skin_tone": "🤷🏻", + "person_shrugging_medium-dark_skin_tone": "🤷🏾", + "person_shrugging_medium-light_skin_tone": "🤷🏼", + "person_shrugging_medium_skin_tone": "🤷🏽", + "person_standing": "🧍", + "person_surfing": "🏄", + "person_surfing_dark_skin_tone": "🏄🏿", + "person_surfing_light_skin_tone": "🏄🏻", + "person_surfing_medium-dark_skin_tone": "🏄🏾", + "person_surfing_medium-light_skin_tone": "🏄🏼", + "person_surfing_medium_skin_tone": "🏄🏽", + "person_swimming": "🏊", + "person_swimming_dark_skin_tone": "🏊🏿", + "person_swimming_light_skin_tone": "🏊🏻", + "person_swimming_medium-dark_skin_tone": "🏊🏾", + "person_swimming_medium-light_skin_tone": "🏊🏼", + "person_swimming_medium_skin_tone": "🏊🏽", + "person_taking_bath": "🛀", + "person_taking_bath_dark_skin_tone": "🛀🏿", + "person_taking_bath_light_skin_tone": "🛀🏻", + "person_taking_bath_medium-dark_skin_tone": "🛀🏾", + "person_taking_bath_medium-light_skin_tone": "🛀🏼", + "person_taking_bath_medium_skin_tone": "🛀🏽", + "person_tipping_hand": "💁", + "person_tipping_hand_dark_skin_tone": "💁🏿", + "person_tipping_hand_light_skin_tone": "💁🏻", + "person_tipping_hand_medium-dark_skin_tone": "💁🏾", + "person_tipping_hand_medium-light_skin_tone": "💁🏼", + "person_tipping_hand_medium_skin_tone": "💁🏽", + "person_walking": "🚶", + "person_walking_dark_skin_tone": "🚶🏿", + "person_walking_light_skin_tone": "🚶🏻", + "person_walking_medium-dark_skin_tone": "🚶🏾", + "person_walking_medium-light_skin_tone": "🚶🏼", + "person_walking_medium_skin_tone": "🚶🏽", + "person_wearing_turban": "👳", + "person_wearing_turban_dark_skin_tone": "👳🏿", + "person_wearing_turban_light_skin_tone": "👳🏻", + "person_wearing_turban_medium-dark_skin_tone": "👳🏾", + "person_wearing_turban_medium-light_skin_tone": "👳🏼", + "person_wearing_turban_medium_skin_tone": "👳🏽", + "petri_dish": "🧫", + "pick": "⛏", + "pie": "🥧", + "pig": "🐷", + "pig_face": "🐷", + "pig_nose": "🐽", + "pile_of_poo": "💩", + "pill": "💊", + "pinching_hand": "🤏", + "pine_decoration": "🎍", + "pineapple": "🍍", + "ping_pong": "🏓", + "pirate_flag": "🏴\u200d☠️", + "pistol": "🔫", + "pizza": "🍕", + "place_of_worship": "🛐", + "play_button": "▶", + "play_or_pause_button": "⏯", + "pleading_face": "🥺", + "police_car": "🚓", + "police_car_light": "🚨", + "police_officer": "👮", + "police_officer_dark_skin_tone": "👮🏿", + "police_officer_light_skin_tone": "👮🏻", + "police_officer_medium-dark_skin_tone": "👮🏾", + "police_officer_medium-light_skin_tone": "👮🏼", + "police_officer_medium_skin_tone": "👮🏽", + "poodle": "🐩", + "pool_8_ball": "🎱", + "popcorn": "🍿", + "post_office": "🏣", + "postal_horn": "📯", + "postbox": "📮", + "pot_of_food": "🍲", + "potable_water": "🚰", + "potato": "🥔", + "poultry_leg": "🍗", + "pound_banknote": "💷", + "pouting_cat_face": "😾", + "pouting_face": "😡", + "prayer_beads": "📿", + "pregnant_woman": "🤰", + "pregnant_woman_dark_skin_tone": "🤰🏿", + "pregnant_woman_light_skin_tone": "🤰🏻", + "pregnant_woman_medium-dark_skin_tone": "🤰🏾", + "pregnant_woman_medium-light_skin_tone": "🤰🏼", + "pregnant_woman_medium_skin_tone": "🤰🏽", + "pretzel": "🥨", + "probing_cane": "🦯", + "prince": "🤴", + "prince_dark_skin_tone": "🤴🏿", + "prince_light_skin_tone": "🤴🏻", + "prince_medium-dark_skin_tone": "🤴🏾", + "prince_medium-light_skin_tone": "🤴🏼", + "prince_medium_skin_tone": "🤴🏽", + "princess": "👸", + "princess_dark_skin_tone": "👸🏿", + "princess_light_skin_tone": "👸🏻", + "princess_medium-dark_skin_tone": "👸🏾", + "princess_medium-light_skin_tone": "👸🏼", + "princess_medium_skin_tone": "👸🏽", + "printer": "🖨", + "prohibited": "🚫", + "purple_circle": "🟣", + "purple_heart": "💜", + "purple_square": "🟪", + "purse": "👛", + "pushpin": "📌", + "question_mark": "❓", + "rabbit": "🐰", + "rabbit_face": "🐰", + "raccoon": "🦝", + "racing_car": "🏎", + "radio": "📻", + "radio_button": "🔘", + "radioactive": "☢", + "railway_car": "🚃", + "railway_track": "🛤", + "rainbow": "🌈", + "rainbow_flag": "🏳️\u200d🌈", + "raised_back_of_hand": "🤚", + "raised_back_of_hand_dark_skin_tone": "🤚🏿", + "raised_back_of_hand_light_skin_tone": "🤚🏻", + "raised_back_of_hand_medium-dark_skin_tone": "🤚🏾", + "raised_back_of_hand_medium-light_skin_tone": "🤚🏼", + "raised_back_of_hand_medium_skin_tone": "🤚🏽", + "raised_fist": "✊", + "raised_fist_dark_skin_tone": "✊🏿", + "raised_fist_light_skin_tone": "✊🏻", + "raised_fist_medium-dark_skin_tone": "✊🏾", + "raised_fist_medium-light_skin_tone": "✊🏼", + "raised_fist_medium_skin_tone": "✊🏽", + "raised_hand": "✋", + "raised_hand_dark_skin_tone": "✋🏿", + "raised_hand_light_skin_tone": "✋🏻", + "raised_hand_medium-dark_skin_tone": "✋🏾", + "raised_hand_medium-light_skin_tone": "✋🏼", + "raised_hand_medium_skin_tone": "✋🏽", + "raising_hands": "🙌", + "raising_hands_dark_skin_tone": "🙌🏿", + "raising_hands_light_skin_tone": "🙌🏻", + "raising_hands_medium-dark_skin_tone": "🙌🏾", + "raising_hands_medium-light_skin_tone": "🙌🏼", + "raising_hands_medium_skin_tone": "🙌🏽", + "ram": "🐏", + "rat": "🐀", + "razor": "🪒", + "ringed_planet": "🪐", + "receipt": "🧾", + "record_button": "⏺", + "recycling_symbol": "♻", + "red_apple": "🍎", + "red_circle": "🔴", + "red_envelope": "🧧", + "red_hair": "🦰", + "red-haired_man": "👨\u200d🦰", + "red-haired_woman": "👩\u200d🦰", + "red_heart": "❤", + "red_paper_lantern": "🏮", + "red_square": "🟥", + "red_triangle_pointed_down": "🔻", + "red_triangle_pointed_up": "🔺", + "registered": "®", + "relieved_face": "😌", + "reminder_ribbon": "🎗", + "repeat_button": "🔁", + "repeat_single_button": "🔂", + "rescue_worker’s_helmet": "⛑", + "restroom": "🚻", + "reverse_button": "◀", + "revolving_hearts": "💞", + "rhinoceros": "🦏", + "ribbon": "🎀", + "rice_ball": "🍙", + "rice_cracker": "🍘", + "right-facing_fist": "🤜", + "right-facing_fist_dark_skin_tone": "🤜🏿", + "right-facing_fist_light_skin_tone": "🤜🏻", + "right-facing_fist_medium-dark_skin_tone": "🤜🏾", + "right-facing_fist_medium-light_skin_tone": "🤜🏼", + "right-facing_fist_medium_skin_tone": "🤜🏽", + "right_anger_bubble": "🗯", + "right_arrow": "➡", + "right_arrow_curving_down": "⤵", + "right_arrow_curving_left": "↩", + "right_arrow_curving_up": "⤴", + "ring": "💍", + "roasted_sweet_potato": "🍠", + "robot_face": "🤖", + "rocket": "🚀", + "roll_of_paper": "🧻", + "rolled-up_newspaper": "🗞", + "roller_coaster": "🎢", + "rolling_on_the_floor_laughing": "🤣", + "rooster": "🐓", + "rose": "🌹", + "rosette": "🏵", + "round_pushpin": "📍", + "rugby_football": "🏉", + "running_shirt": "🎽", + "running_shoe": "👟", + "sad_but_relieved_face": "😥", + "safety_pin": "🧷", + "safety_vest": "🦺", + "salt": "🧂", + "sailboat": "⛵", + "sake": "🍶", + "sandwich": "🥪", + "sari": "🥻", + "satellite": "📡", + "satellite_antenna": "📡", + "sauropod": "🦕", + "saxophone": "🎷", + "scarf": "🧣", + "school": "🏫", + "school_backpack": "🎒", + "scissors": "✂", + "scorpion": "🦂", + "scroll": "📜", + "seat": "💺", + "see-no-evil_monkey": "🙈", + "seedling": "🌱", + "selfie": "🤳", + "selfie_dark_skin_tone": "🤳🏿", + "selfie_light_skin_tone": "🤳🏻", + "selfie_medium-dark_skin_tone": "🤳🏾", + "selfie_medium-light_skin_tone": "🤳🏼", + "selfie_medium_skin_tone": "🤳🏽", + "service_dog": "🐕\u200d🦺", + "seven-thirty": "🕢", + "seven_o’clock": "🕖", + "shallow_pan_of_food": "🥘", + "shamrock": "☘", + "shark": "🦈", + "shaved_ice": "🍧", + "sheaf_of_rice": "🌾", + "shield": "🛡", + "shinto_shrine": "⛩", + "ship": "🚢", + "shooting_star": "🌠", + "shopping_bags": "🛍", + "shopping_cart": "🛒", + "shortcake": "🍰", + "shorts": "🩳", + "shower": "🚿", + "shrimp": "🦐", + "shuffle_tracks_button": "🔀", + "shushing_face": "🤫", + "sign_of_the_horns": "🤘", + "sign_of_the_horns_dark_skin_tone": "🤘🏿", + "sign_of_the_horns_light_skin_tone": "🤘🏻", + "sign_of_the_horns_medium-dark_skin_tone": "🤘🏾", + "sign_of_the_horns_medium-light_skin_tone": "🤘🏼", + "sign_of_the_horns_medium_skin_tone": "🤘🏽", + "six-thirty": "🕡", + "six_o’clock": "🕕", + "skateboard": "🛹", + "skier": "⛷", + "skis": "🎿", + "skull": "💀", + "skull_and_crossbones": "☠", + "skunk": "🦨", + "sled": "🛷", + "sleeping_face": "😴", + "sleepy_face": "😪", + "slightly_frowning_face": "🙁", + "slightly_smiling_face": "🙂", + "slot_machine": "🎰", + "sloth": "🦥", + "small_airplane": "🛩", + "small_blue_diamond": "🔹", + "small_orange_diamond": "🔸", + "smiling_cat_face_with_heart-eyes": "😻", + "smiling_face": "☺", + "smiling_face_with_halo": "😇", + "smiling_face_with_3_hearts": "🥰", + "smiling_face_with_heart-eyes": "😍", + "smiling_face_with_horns": "😈", + "smiling_face_with_smiling_eyes": "😊", + "smiling_face_with_sunglasses": "😎", + "smirking_face": "😏", + "snail": "🐌", + "snake": "🐍", + "sneezing_face": "🤧", + "snow-capped_mountain": "🏔", + "snowboarder": "🏂", + "snowboarder_dark_skin_tone": "🏂🏿", + "snowboarder_light_skin_tone": "🏂🏻", + "snowboarder_medium-dark_skin_tone": "🏂🏾", + "snowboarder_medium-light_skin_tone": "🏂🏼", + "snowboarder_medium_skin_tone": "🏂🏽", + "snowflake": "❄", + "snowman": "☃", + "snowman_without_snow": "⛄", + "soap": "🧼", + "soccer_ball": "⚽", + "socks": "🧦", + "softball": "🥎", + "soft_ice_cream": "🍦", + "spade_suit": "♠", + "spaghetti": "🍝", + "sparkle": "❇", + "sparkler": "🎇", + "sparkles": "✨", + "sparkling_heart": "💖", + "speak-no-evil_monkey": "🙊", + "speaker_high_volume": "🔊", + "speaker_low_volume": "🔈", + "speaker_medium_volume": "🔉", + "speaking_head": "🗣", + "speech_balloon": "💬", + "speedboat": "🚤", + "spider": "🕷", + "spider_web": "🕸", + "spiral_calendar": "🗓", + "spiral_notepad": "🗒", + "spiral_shell": "🐚", + "spoon": "🥄", + "sponge": "🧽", + "sport_utility_vehicle": "🚙", + "sports_medal": "🏅", + "spouting_whale": "🐳", + "squid": "🦑", + "squinting_face_with_tongue": "😝", + "stadium": "🏟", + "star-struck": "🤩", + "star_and_crescent": "☪", + "star_of_david": "✡", + "station": "🚉", + "steaming_bowl": "🍜", + "stethoscope": "🩺", + "stop_button": "⏹", + "stop_sign": "🛑", + "stopwatch": "⏱", + "straight_ruler": "📏", + "strawberry": "🍓", + "studio_microphone": "🎙", + "stuffed_flatbread": "🥙", + "sun": "☀", + "sun_behind_cloud": "⛅", + "sun_behind_large_cloud": "🌥", + "sun_behind_rain_cloud": "🌦", + "sun_behind_small_cloud": "🌤", + "sun_with_face": "🌞", + "sunflower": "🌻", + "sunglasses": "😎", + "sunrise": "🌅", + "sunrise_over_mountains": "🌄", + "sunset": "🌇", + "superhero": "🦸", + "supervillain": "🦹", + "sushi": "🍣", + "suspension_railway": "🚟", + "swan": "🦢", + "sweat_droplets": "💦", + "synagogue": "🕍", + "syringe": "💉", + "t-shirt": "👕", + "taco": "🌮", + "takeout_box": "🥡", + "tanabata_tree": "🎋", + "tangerine": "🍊", + "taxi": "🚕", + "teacup_without_handle": "🍵", + "tear-off_calendar": "📆", + "teddy_bear": "🧸", + "telephone": "☎", + "telephone_receiver": "📞", + "telescope": "🔭", + "television": "📺", + "ten-thirty": "🕥", + "ten_o’clock": "🕙", + "tennis": "🎾", + "tent": "⛺", + "test_tube": "🧪", + "thermometer": "🌡", + "thinking_face": "🤔", + "thought_balloon": "💭", + "thread": "🧵", + "three-thirty": "🕞", + "three_o’clock": "🕒", + "thumbs_down": "👎", + "thumbs_down_dark_skin_tone": "👎🏿", + "thumbs_down_light_skin_tone": "👎🏻", + "thumbs_down_medium-dark_skin_tone": "👎🏾", + "thumbs_down_medium-light_skin_tone": "👎🏼", + "thumbs_down_medium_skin_tone": "👎🏽", + "thumbs_up": "👍", + "thumbs_up_dark_skin_tone": "👍🏿", + "thumbs_up_light_skin_tone": "👍🏻", + "thumbs_up_medium-dark_skin_tone": "👍🏾", + "thumbs_up_medium-light_skin_tone": "👍🏼", + "thumbs_up_medium_skin_tone": "👍🏽", + "ticket": "🎫", + "tiger": "🐯", + "tiger_face": "🐯", + "timer_clock": "⏲", + "tired_face": "😫", + "toolbox": "🧰", + "toilet": "🚽", + "tomato": "🍅", + "tongue": "👅", + "tooth": "🦷", + "top_hat": "🎩", + "tornado": "🌪", + "trackball": "🖲", + "tractor": "🚜", + "trade_mark": "™", + "train": "🚋", + "tram": "🚊", + "tram_car": "🚋", + "triangular_flag": "🚩", + "triangular_ruler": "📐", + "trident_emblem": "🔱", + "trolleybus": "🚎", + "trophy": "🏆", + "tropical_drink": "🍹", + "tropical_fish": "🐠", + "trumpet": "🎺", + "tulip": "🌷", + "tumbler_glass": "🥃", + "turtle": "🐢", + "twelve-thirty": "🕧", + "twelve_o’clock": "🕛", + "two-hump_camel": "🐫", + "two-thirty": "🕝", + "two_hearts": "💕", + "two_men_holding_hands": "👬", + "two_o’clock": "🕑", + "two_women_holding_hands": "👭", + "umbrella": "☂", + "umbrella_on_ground": "⛱", + "umbrella_with_rain_drops": "☔", + "unamused_face": "😒", + "unicorn_face": "🦄", + "unlocked": "🔓", + "up-down_arrow": "↕", + "up-left_arrow": "↖", + "up-right_arrow": "↗", + "up_arrow": "⬆", + "upside-down_face": "🙃", + "upwards_button": "🔼", + "vampire": "🧛", + "vampire_dark_skin_tone": "🧛🏿", + "vampire_light_skin_tone": "🧛🏻", + "vampire_medium-dark_skin_tone": "🧛🏾", + "vampire_medium-light_skin_tone": "🧛🏼", + "vampire_medium_skin_tone": "🧛🏽", + "vertical_traffic_light": "🚦", + "vibration_mode": "📳", + "victory_hand": "✌", + "victory_hand_dark_skin_tone": "✌🏿", + "victory_hand_light_skin_tone": "✌🏻", + "victory_hand_medium-dark_skin_tone": "✌🏾", + "victory_hand_medium-light_skin_tone": "✌🏼", + "victory_hand_medium_skin_tone": "✌🏽", + "video_camera": "📹", + "video_game": "🎮", + "videocassette": "📼", + "violin": "🎻", + "volcano": "🌋", + "volleyball": "🏐", + "vulcan_salute": "🖖", + "vulcan_salute_dark_skin_tone": "🖖🏿", + "vulcan_salute_light_skin_tone": "🖖🏻", + "vulcan_salute_medium-dark_skin_tone": "🖖🏾", + "vulcan_salute_medium-light_skin_tone": "🖖🏼", + "vulcan_salute_medium_skin_tone": "🖖🏽", + "waffle": "🧇", + "waning_crescent_moon": "🌘", + "waning_gibbous_moon": "🌖", + "warning": "⚠", + "wastebasket": "🗑", + "watch": "⌚", + "water_buffalo": "🐃", + "water_closet": "🚾", + "water_wave": "🌊", + "watermelon": "🍉", + "waving_hand": "👋", + "waving_hand_dark_skin_tone": "👋🏿", + "waving_hand_light_skin_tone": "👋🏻", + "waving_hand_medium-dark_skin_tone": "👋🏾", + "waving_hand_medium-light_skin_tone": "👋🏼", + "waving_hand_medium_skin_tone": "👋🏽", + "wavy_dash": "〰", + "waxing_crescent_moon": "🌒", + "waxing_gibbous_moon": "🌔", + "weary_cat_face": "🙀", + "weary_face": "😩", + "wedding": "💒", + "whale": "🐳", + "wheel_of_dharma": "☸", + "wheelchair_symbol": "♿", + "white_circle": "⚪", + "white_exclamation_mark": "❕", + "white_flag": "🏳", + "white_flower": "💮", + "white_hair": "🦳", + "white-haired_man": "👨\u200d🦳", + "white-haired_woman": "👩\u200d🦳", + "white_heart": "🤍", + "white_heavy_check_mark": "✅", + "white_large_square": "⬜", + "white_medium-small_square": "◽", + "white_medium_square": "◻", + "white_medium_star": "⭐", + "white_question_mark": "❔", + "white_small_square": "▫", + "white_square_button": "🔳", + "wilted_flower": "🥀", + "wind_chime": "🎐", + "wind_face": "🌬", + "wine_glass": "🍷", + "winking_face": "😉", + "winking_face_with_tongue": "😜", + "wolf_face": "🐺", + "woman": "👩", + "woman_artist": "👩\u200d🎨", + "woman_artist_dark_skin_tone": "👩🏿\u200d🎨", + "woman_artist_light_skin_tone": "👩🏻\u200d🎨", + "woman_artist_medium-dark_skin_tone": "👩🏾\u200d🎨", + "woman_artist_medium-light_skin_tone": "👩🏼\u200d🎨", + "woman_artist_medium_skin_tone": "👩🏽\u200d🎨", + "woman_astronaut": "👩\u200d🚀", + "woman_astronaut_dark_skin_tone": "👩🏿\u200d🚀", + "woman_astronaut_light_skin_tone": "👩🏻\u200d🚀", + "woman_astronaut_medium-dark_skin_tone": "👩🏾\u200d🚀", + "woman_astronaut_medium-light_skin_tone": "👩🏼\u200d🚀", + "woman_astronaut_medium_skin_tone": "👩🏽\u200d🚀", + "woman_biking": "🚴\u200d♀️", + "woman_biking_dark_skin_tone": "🚴🏿\u200d♀️", + "woman_biking_light_skin_tone": "🚴🏻\u200d♀️", + "woman_biking_medium-dark_skin_tone": "🚴🏾\u200d♀️", + "woman_biking_medium-light_skin_tone": "🚴🏼\u200d♀️", + "woman_biking_medium_skin_tone": "🚴🏽\u200d♀️", + "woman_bouncing_ball": "⛹️\u200d♀️", + "woman_bouncing_ball_dark_skin_tone": "⛹🏿\u200d♀️", + "woman_bouncing_ball_light_skin_tone": "⛹🏻\u200d♀️", + "woman_bouncing_ball_medium-dark_skin_tone": "⛹🏾\u200d♀️", + "woman_bouncing_ball_medium-light_skin_tone": "⛹🏼\u200d♀️", + "woman_bouncing_ball_medium_skin_tone": "⛹🏽\u200d♀️", + "woman_bowing": "🙇\u200d♀️", + "woman_bowing_dark_skin_tone": "🙇🏿\u200d♀️", + "woman_bowing_light_skin_tone": "🙇🏻\u200d♀️", + "woman_bowing_medium-dark_skin_tone": "🙇🏾\u200d♀️", + "woman_bowing_medium-light_skin_tone": "🙇🏼\u200d♀️", + "woman_bowing_medium_skin_tone": "🙇🏽\u200d♀️", + "woman_cartwheeling": "🤸\u200d♀️", + "woman_cartwheeling_dark_skin_tone": "🤸🏿\u200d♀️", + "woman_cartwheeling_light_skin_tone": "🤸🏻\u200d♀️", + "woman_cartwheeling_medium-dark_skin_tone": "🤸🏾\u200d♀️", + "woman_cartwheeling_medium-light_skin_tone": "🤸🏼\u200d♀️", + "woman_cartwheeling_medium_skin_tone": "🤸🏽\u200d♀️", + "woman_climbing": "🧗\u200d♀️", + "woman_climbing_dark_skin_tone": "🧗🏿\u200d♀️", + "woman_climbing_light_skin_tone": "🧗🏻\u200d♀️", + "woman_climbing_medium-dark_skin_tone": "🧗🏾\u200d♀️", + "woman_climbing_medium-light_skin_tone": "🧗🏼\u200d♀️", + "woman_climbing_medium_skin_tone": "🧗🏽\u200d♀️", + "woman_construction_worker": "👷\u200d♀️", + "woman_construction_worker_dark_skin_tone": "👷🏿\u200d♀️", + "woman_construction_worker_light_skin_tone": "👷🏻\u200d♀️", + "woman_construction_worker_medium-dark_skin_tone": "👷🏾\u200d♀️", + "woman_construction_worker_medium-light_skin_tone": "👷🏼\u200d♀️", + "woman_construction_worker_medium_skin_tone": "👷🏽\u200d♀️", + "woman_cook": "👩\u200d🍳", + "woman_cook_dark_skin_tone": "👩🏿\u200d🍳", + "woman_cook_light_skin_tone": "👩🏻\u200d🍳", + "woman_cook_medium-dark_skin_tone": "👩🏾\u200d🍳", + "woman_cook_medium-light_skin_tone": "👩🏼\u200d🍳", + "woman_cook_medium_skin_tone": "👩🏽\u200d🍳", + "woman_dancing": "💃", + "woman_dancing_dark_skin_tone": "💃🏿", + "woman_dancing_light_skin_tone": "💃🏻", + "woman_dancing_medium-dark_skin_tone": "💃🏾", + "woman_dancing_medium-light_skin_tone": "💃🏼", + "woman_dancing_medium_skin_tone": "💃🏽", + "woman_dark_skin_tone": "👩🏿", + "woman_detective": "🕵️\u200d♀️", + "woman_detective_dark_skin_tone": "🕵🏿\u200d♀️", + "woman_detective_light_skin_tone": "🕵🏻\u200d♀️", + "woman_detective_medium-dark_skin_tone": "🕵🏾\u200d♀️", + "woman_detective_medium-light_skin_tone": "🕵🏼\u200d♀️", + "woman_detective_medium_skin_tone": "🕵🏽\u200d♀️", + "woman_elf": "🧝\u200d♀️", + "woman_elf_dark_skin_tone": "🧝🏿\u200d♀️", + "woman_elf_light_skin_tone": "🧝🏻\u200d♀️", + "woman_elf_medium-dark_skin_tone": "🧝🏾\u200d♀️", + "woman_elf_medium-light_skin_tone": "🧝🏼\u200d♀️", + "woman_elf_medium_skin_tone": "🧝🏽\u200d♀️", + "woman_facepalming": "🤦\u200d♀️", + "woman_facepalming_dark_skin_tone": "🤦🏿\u200d♀️", + "woman_facepalming_light_skin_tone": "🤦🏻\u200d♀️", + "woman_facepalming_medium-dark_skin_tone": "🤦🏾\u200d♀️", + "woman_facepalming_medium-light_skin_tone": "🤦🏼\u200d♀️", + "woman_facepalming_medium_skin_tone": "🤦🏽\u200d♀️", + "woman_factory_worker": "👩\u200d🏭", + "woman_factory_worker_dark_skin_tone": "👩🏿\u200d🏭", + "woman_factory_worker_light_skin_tone": "👩🏻\u200d🏭", + "woman_factory_worker_medium-dark_skin_tone": "👩🏾\u200d🏭", + "woman_factory_worker_medium-light_skin_tone": "👩🏼\u200d🏭", + "woman_factory_worker_medium_skin_tone": "👩🏽\u200d🏭", + "woman_fairy": "🧚\u200d♀️", + "woman_fairy_dark_skin_tone": "🧚🏿\u200d♀️", + "woman_fairy_light_skin_tone": "🧚🏻\u200d♀️", + "woman_fairy_medium-dark_skin_tone": "🧚🏾\u200d♀️", + "woman_fairy_medium-light_skin_tone": "🧚🏼\u200d♀️", + "woman_fairy_medium_skin_tone": "🧚🏽\u200d♀️", + "woman_farmer": "👩\u200d🌾", + "woman_farmer_dark_skin_tone": "👩🏿\u200d🌾", + "woman_farmer_light_skin_tone": "👩🏻\u200d🌾", + "woman_farmer_medium-dark_skin_tone": "👩🏾\u200d🌾", + "woman_farmer_medium-light_skin_tone": "👩🏼\u200d🌾", + "woman_farmer_medium_skin_tone": "👩🏽\u200d🌾", + "woman_firefighter": "👩\u200d🚒", + "woman_firefighter_dark_skin_tone": "👩🏿\u200d🚒", + "woman_firefighter_light_skin_tone": "👩🏻\u200d🚒", + "woman_firefighter_medium-dark_skin_tone": "👩🏾\u200d🚒", + "woman_firefighter_medium-light_skin_tone": "👩🏼\u200d🚒", + "woman_firefighter_medium_skin_tone": "👩🏽\u200d🚒", + "woman_frowning": "🙍\u200d♀️", + "woman_frowning_dark_skin_tone": "🙍🏿\u200d♀️", + "woman_frowning_light_skin_tone": "🙍🏻\u200d♀️", + "woman_frowning_medium-dark_skin_tone": "🙍🏾\u200d♀️", + "woman_frowning_medium-light_skin_tone": "🙍🏼\u200d♀️", + "woman_frowning_medium_skin_tone": "🙍🏽\u200d♀️", + "woman_genie": "🧞\u200d♀️", + "woman_gesturing_no": "🙅\u200d♀️", + "woman_gesturing_no_dark_skin_tone": "🙅🏿\u200d♀️", + "woman_gesturing_no_light_skin_tone": "🙅🏻\u200d♀️", + "woman_gesturing_no_medium-dark_skin_tone": "🙅🏾\u200d♀️", + "woman_gesturing_no_medium-light_skin_tone": "🙅🏼\u200d♀️", + "woman_gesturing_no_medium_skin_tone": "🙅🏽\u200d♀️", + "woman_gesturing_ok": "🙆\u200d♀️", + "woman_gesturing_ok_dark_skin_tone": "🙆🏿\u200d♀️", + "woman_gesturing_ok_light_skin_tone": "🙆🏻\u200d♀️", + "woman_gesturing_ok_medium-dark_skin_tone": "🙆🏾\u200d♀️", + "woman_gesturing_ok_medium-light_skin_tone": "🙆🏼\u200d♀️", + "woman_gesturing_ok_medium_skin_tone": "🙆🏽\u200d♀️", + "woman_getting_haircut": "💇\u200d♀️", + "woman_getting_haircut_dark_skin_tone": "💇🏿\u200d♀️", + "woman_getting_haircut_light_skin_tone": "💇🏻\u200d♀️", + "woman_getting_haircut_medium-dark_skin_tone": "💇🏾\u200d♀️", + "woman_getting_haircut_medium-light_skin_tone": "💇🏼\u200d♀️", + "woman_getting_haircut_medium_skin_tone": "💇🏽\u200d♀️", + "woman_getting_massage": "💆\u200d♀️", + "woman_getting_massage_dark_skin_tone": "💆🏿\u200d♀️", + "woman_getting_massage_light_skin_tone": "💆🏻\u200d♀️", + "woman_getting_massage_medium-dark_skin_tone": "💆🏾\u200d♀️", + "woman_getting_massage_medium-light_skin_tone": "💆🏼\u200d♀️", + "woman_getting_massage_medium_skin_tone": "💆🏽\u200d♀️", + "woman_golfing": "🏌️\u200d♀️", + "woman_golfing_dark_skin_tone": "🏌🏿\u200d♀️", + "woman_golfing_light_skin_tone": "🏌🏻\u200d♀️", + "woman_golfing_medium-dark_skin_tone": "🏌🏾\u200d♀️", + "woman_golfing_medium-light_skin_tone": "🏌🏼\u200d♀️", + "woman_golfing_medium_skin_tone": "🏌🏽\u200d♀️", + "woman_guard": "💂\u200d♀️", + "woman_guard_dark_skin_tone": "💂🏿\u200d♀️", + "woman_guard_light_skin_tone": "💂🏻\u200d♀️", + "woman_guard_medium-dark_skin_tone": "💂🏾\u200d♀️", + "woman_guard_medium-light_skin_tone": "💂🏼\u200d♀️", + "woman_guard_medium_skin_tone": "💂🏽\u200d♀️", + "woman_health_worker": "👩\u200d⚕️", + "woman_health_worker_dark_skin_tone": "👩🏿\u200d⚕️", + "woman_health_worker_light_skin_tone": "👩🏻\u200d⚕️", + "woman_health_worker_medium-dark_skin_tone": "👩🏾\u200d⚕️", + "woman_health_worker_medium-light_skin_tone": "👩🏼\u200d⚕️", + "woman_health_worker_medium_skin_tone": "👩🏽\u200d⚕️", + "woman_in_lotus_position": "🧘\u200d♀️", + "woman_in_lotus_position_dark_skin_tone": "🧘🏿\u200d♀️", + "woman_in_lotus_position_light_skin_tone": "🧘🏻\u200d♀️", + "woman_in_lotus_position_medium-dark_skin_tone": "🧘🏾\u200d♀️", + "woman_in_lotus_position_medium-light_skin_tone": "🧘🏼\u200d♀️", + "woman_in_lotus_position_medium_skin_tone": "🧘🏽\u200d♀️", + "woman_in_manual_wheelchair": "👩\u200d🦽", + "woman_in_motorized_wheelchair": "👩\u200d🦼", + "woman_in_steamy_room": "🧖\u200d♀️", + "woman_in_steamy_room_dark_skin_tone": "🧖🏿\u200d♀️", + "woman_in_steamy_room_light_skin_tone": "🧖🏻\u200d♀️", + "woman_in_steamy_room_medium-dark_skin_tone": "🧖🏾\u200d♀️", + "woman_in_steamy_room_medium-light_skin_tone": "🧖🏼\u200d♀️", + "woman_in_steamy_room_medium_skin_tone": "🧖🏽\u200d♀️", + "woman_judge": "👩\u200d⚖️", + "woman_judge_dark_skin_tone": "👩🏿\u200d⚖️", + "woman_judge_light_skin_tone": "👩🏻\u200d⚖️", + "woman_judge_medium-dark_skin_tone": "👩🏾\u200d⚖️", + "woman_judge_medium-light_skin_tone": "👩🏼\u200d⚖️", + "woman_judge_medium_skin_tone": "👩🏽\u200d⚖️", + "woman_juggling": "🤹\u200d♀️", + "woman_juggling_dark_skin_tone": "🤹🏿\u200d♀️", + "woman_juggling_light_skin_tone": "🤹🏻\u200d♀️", + "woman_juggling_medium-dark_skin_tone": "🤹🏾\u200d♀️", + "woman_juggling_medium-light_skin_tone": "🤹🏼\u200d♀️", + "woman_juggling_medium_skin_tone": "🤹🏽\u200d♀️", + "woman_lifting_weights": "🏋️\u200d♀️", + "woman_lifting_weights_dark_skin_tone": "🏋🏿\u200d♀️", + "woman_lifting_weights_light_skin_tone": "🏋🏻\u200d♀️", + "woman_lifting_weights_medium-dark_skin_tone": "🏋🏾\u200d♀️", + "woman_lifting_weights_medium-light_skin_tone": "🏋🏼\u200d♀️", + "woman_lifting_weights_medium_skin_tone": "🏋🏽\u200d♀️", + "woman_light_skin_tone": "👩🏻", + "woman_mage": "🧙\u200d♀️", + "woman_mage_dark_skin_tone": "🧙🏿\u200d♀️", + "woman_mage_light_skin_tone": "🧙🏻\u200d♀️", + "woman_mage_medium-dark_skin_tone": "🧙🏾\u200d♀️", + "woman_mage_medium-light_skin_tone": "🧙🏼\u200d♀️", + "woman_mage_medium_skin_tone": "🧙🏽\u200d♀️", + "woman_mechanic": "👩\u200d🔧", + "woman_mechanic_dark_skin_tone": "👩🏿\u200d🔧", + "woman_mechanic_light_skin_tone": "👩🏻\u200d🔧", + "woman_mechanic_medium-dark_skin_tone": "👩🏾\u200d🔧", + "woman_mechanic_medium-light_skin_tone": "👩🏼\u200d🔧", + "woman_mechanic_medium_skin_tone": "👩🏽\u200d🔧", + "woman_medium-dark_skin_tone": "👩🏾", + "woman_medium-light_skin_tone": "👩🏼", + "woman_medium_skin_tone": "👩🏽", + "woman_mountain_biking": "🚵\u200d♀️", + "woman_mountain_biking_dark_skin_tone": "🚵🏿\u200d♀️", + "woman_mountain_biking_light_skin_tone": "🚵🏻\u200d♀️", + "woman_mountain_biking_medium-dark_skin_tone": "🚵🏾\u200d♀️", + "woman_mountain_biking_medium-light_skin_tone": "🚵🏼\u200d♀️", + "woman_mountain_biking_medium_skin_tone": "🚵🏽\u200d♀️", + "woman_office_worker": "👩\u200d💼", + "woman_office_worker_dark_skin_tone": "👩🏿\u200d💼", + "woman_office_worker_light_skin_tone": "👩🏻\u200d💼", + "woman_office_worker_medium-dark_skin_tone": "👩🏾\u200d💼", + "woman_office_worker_medium-light_skin_tone": "👩🏼\u200d💼", + "woman_office_worker_medium_skin_tone": "👩🏽\u200d💼", + "woman_pilot": "👩\u200d✈️", + "woman_pilot_dark_skin_tone": "👩🏿\u200d✈️", + "woman_pilot_light_skin_tone": "👩🏻\u200d✈️", + "woman_pilot_medium-dark_skin_tone": "👩🏾\u200d✈️", + "woman_pilot_medium-light_skin_tone": "👩🏼\u200d✈️", + "woman_pilot_medium_skin_tone": "👩🏽\u200d✈️", + "woman_playing_handball": "🤾\u200d♀️", + "woman_playing_handball_dark_skin_tone": "🤾🏿\u200d♀️", + "woman_playing_handball_light_skin_tone": "🤾🏻\u200d♀️", + "woman_playing_handball_medium-dark_skin_tone": "🤾🏾\u200d♀️", + "woman_playing_handball_medium-light_skin_tone": "🤾🏼\u200d♀️", + "woman_playing_handball_medium_skin_tone": "🤾🏽\u200d♀️", + "woman_playing_water_polo": "🤽\u200d♀️", + "woman_playing_water_polo_dark_skin_tone": "🤽🏿\u200d♀️", + "woman_playing_water_polo_light_skin_tone": "🤽🏻\u200d♀️", + "woman_playing_water_polo_medium-dark_skin_tone": "🤽🏾\u200d♀️", + "woman_playing_water_polo_medium-light_skin_tone": "🤽🏼\u200d♀️", + "woman_playing_water_polo_medium_skin_tone": "🤽🏽\u200d♀️", + "woman_police_officer": "👮\u200d♀️", + "woman_police_officer_dark_skin_tone": "👮🏿\u200d♀️", + "woman_police_officer_light_skin_tone": "👮🏻\u200d♀️", + "woman_police_officer_medium-dark_skin_tone": "👮🏾\u200d♀️", + "woman_police_officer_medium-light_skin_tone": "👮🏼\u200d♀️", + "woman_police_officer_medium_skin_tone": "👮🏽\u200d♀️", + "woman_pouting": "🙎\u200d♀️", + "woman_pouting_dark_skin_tone": "🙎🏿\u200d♀️", + "woman_pouting_light_skin_tone": "🙎🏻\u200d♀️", + "woman_pouting_medium-dark_skin_tone": "🙎🏾\u200d♀️", + "woman_pouting_medium-light_skin_tone": "🙎🏼\u200d♀️", + "woman_pouting_medium_skin_tone": "🙎🏽\u200d♀️", + "woman_raising_hand": "🙋\u200d♀️", + "woman_raising_hand_dark_skin_tone": "🙋🏿\u200d♀️", + "woman_raising_hand_light_skin_tone": "🙋🏻\u200d♀️", + "woman_raising_hand_medium-dark_skin_tone": "🙋🏾\u200d♀️", + "woman_raising_hand_medium-light_skin_tone": "🙋🏼\u200d♀️", + "woman_raising_hand_medium_skin_tone": "🙋🏽\u200d♀️", + "woman_rowing_boat": "🚣\u200d♀️", + "woman_rowing_boat_dark_skin_tone": "🚣🏿\u200d♀️", + "woman_rowing_boat_light_skin_tone": "🚣🏻\u200d♀️", + "woman_rowing_boat_medium-dark_skin_tone": "🚣🏾\u200d♀️", + "woman_rowing_boat_medium-light_skin_tone": "🚣🏼\u200d♀️", + "woman_rowing_boat_medium_skin_tone": "🚣🏽\u200d♀️", + "woman_running": "🏃\u200d♀️", + "woman_running_dark_skin_tone": "🏃🏿\u200d♀️", + "woman_running_light_skin_tone": "🏃🏻\u200d♀️", + "woman_running_medium-dark_skin_tone": "🏃🏾\u200d♀️", + "woman_running_medium-light_skin_tone": "🏃🏼\u200d♀️", + "woman_running_medium_skin_tone": "🏃🏽\u200d♀️", + "woman_scientist": "👩\u200d🔬", + "woman_scientist_dark_skin_tone": "👩🏿\u200d🔬", + "woman_scientist_light_skin_tone": "👩🏻\u200d🔬", + "woman_scientist_medium-dark_skin_tone": "👩🏾\u200d🔬", + "woman_scientist_medium-light_skin_tone": "👩🏼\u200d🔬", + "woman_scientist_medium_skin_tone": "👩🏽\u200d🔬", + "woman_shrugging": "🤷\u200d♀️", + "woman_shrugging_dark_skin_tone": "🤷🏿\u200d♀️", + "woman_shrugging_light_skin_tone": "🤷🏻\u200d♀️", + "woman_shrugging_medium-dark_skin_tone": "🤷🏾\u200d♀️", + "woman_shrugging_medium-light_skin_tone": "🤷🏼\u200d♀️", + "woman_shrugging_medium_skin_tone": "🤷🏽\u200d♀️", + "woman_singer": "👩\u200d🎤", + "woman_singer_dark_skin_tone": "👩🏿\u200d🎤", + "woman_singer_light_skin_tone": "👩🏻\u200d🎤", + "woman_singer_medium-dark_skin_tone": "👩🏾\u200d🎤", + "woman_singer_medium-light_skin_tone": "👩🏼\u200d🎤", + "woman_singer_medium_skin_tone": "👩🏽\u200d🎤", + "woman_student": "👩\u200d🎓", + "woman_student_dark_skin_tone": "👩🏿\u200d🎓", + "woman_student_light_skin_tone": "👩🏻\u200d🎓", + "woman_student_medium-dark_skin_tone": "👩🏾\u200d🎓", + "woman_student_medium-light_skin_tone": "👩🏼\u200d🎓", + "woman_student_medium_skin_tone": "👩🏽\u200d🎓", + "woman_surfing": "🏄\u200d♀️", + "woman_surfing_dark_skin_tone": "🏄🏿\u200d♀️", + "woman_surfing_light_skin_tone": "🏄🏻\u200d♀️", + "woman_surfing_medium-dark_skin_tone": "🏄🏾\u200d♀️", + "woman_surfing_medium-light_skin_tone": "🏄🏼\u200d♀️", + "woman_surfing_medium_skin_tone": "🏄🏽\u200d♀️", + "woman_swimming": "🏊\u200d♀️", + "woman_swimming_dark_skin_tone": "🏊🏿\u200d♀️", + "woman_swimming_light_skin_tone": "🏊🏻\u200d♀️", + "woman_swimming_medium-dark_skin_tone": "🏊🏾\u200d♀️", + "woman_swimming_medium-light_skin_tone": "🏊🏼\u200d♀️", + "woman_swimming_medium_skin_tone": "🏊🏽\u200d♀️", + "woman_teacher": "👩\u200d🏫", + "woman_teacher_dark_skin_tone": "👩🏿\u200d🏫", + "woman_teacher_light_skin_tone": "👩🏻\u200d🏫", + "woman_teacher_medium-dark_skin_tone": "👩🏾\u200d🏫", + "woman_teacher_medium-light_skin_tone": "👩🏼\u200d🏫", + "woman_teacher_medium_skin_tone": "👩🏽\u200d🏫", + "woman_technologist": "👩\u200d💻", + "woman_technologist_dark_skin_tone": "👩🏿\u200d💻", + "woman_technologist_light_skin_tone": "👩🏻\u200d💻", + "woman_technologist_medium-dark_skin_tone": "👩🏾\u200d💻", + "woman_technologist_medium-light_skin_tone": "👩🏼\u200d💻", + "woman_technologist_medium_skin_tone": "👩🏽\u200d💻", + "woman_tipping_hand": "💁\u200d♀️", + "woman_tipping_hand_dark_skin_tone": "💁🏿\u200d♀️", + "woman_tipping_hand_light_skin_tone": "💁🏻\u200d♀️", + "woman_tipping_hand_medium-dark_skin_tone": "💁🏾\u200d♀️", + "woman_tipping_hand_medium-light_skin_tone": "💁🏼\u200d♀️", + "woman_tipping_hand_medium_skin_tone": "💁🏽\u200d♀️", + "woman_vampire": "🧛\u200d♀️", + "woman_vampire_dark_skin_tone": "🧛🏿\u200d♀️", + "woman_vampire_light_skin_tone": "🧛🏻\u200d♀️", + "woman_vampire_medium-dark_skin_tone": "🧛🏾\u200d♀️", + "woman_vampire_medium-light_skin_tone": "🧛🏼\u200d♀️", + "woman_vampire_medium_skin_tone": "🧛🏽\u200d♀️", + "woman_walking": "🚶\u200d♀️", + "woman_walking_dark_skin_tone": "🚶🏿\u200d♀️", + "woman_walking_light_skin_tone": "🚶🏻\u200d♀️", + "woman_walking_medium-dark_skin_tone": "🚶🏾\u200d♀️", + "woman_walking_medium-light_skin_tone": "🚶🏼\u200d♀️", + "woman_walking_medium_skin_tone": "🚶🏽\u200d♀️", + "woman_wearing_turban": "👳\u200d♀️", + "woman_wearing_turban_dark_skin_tone": "👳🏿\u200d♀️", + "woman_wearing_turban_light_skin_tone": "👳🏻\u200d♀️", + "woman_wearing_turban_medium-dark_skin_tone": "👳🏾\u200d♀️", + "woman_wearing_turban_medium-light_skin_tone": "👳🏼\u200d♀️", + "woman_wearing_turban_medium_skin_tone": "👳🏽\u200d♀️", + "woman_with_headscarf": "🧕", + "woman_with_headscarf_dark_skin_tone": "🧕🏿", + "woman_with_headscarf_light_skin_tone": "🧕🏻", + "woman_with_headscarf_medium-dark_skin_tone": "🧕🏾", + "woman_with_headscarf_medium-light_skin_tone": "🧕🏼", + "woman_with_headscarf_medium_skin_tone": "🧕🏽", + "woman_with_probing_cane": "👩\u200d🦯", + "woman_zombie": "🧟\u200d♀️", + "woman’s_boot": "👢", + "woman’s_clothes": "👚", + "woman’s_hat": "👒", + "woman’s_sandal": "👡", + "women_with_bunny_ears": "👯\u200d♀️", + "women_wrestling": "🤼\u200d♀️", + "women’s_room": "🚺", + "woozy_face": "🥴", + "world_map": "🗺", + "worried_face": "😟", + "wrapped_gift": "🎁", + "wrench": "🔧", + "writing_hand": "✍", + "writing_hand_dark_skin_tone": "✍🏿", + "writing_hand_light_skin_tone": "✍🏻", + "writing_hand_medium-dark_skin_tone": "✍🏾", + "writing_hand_medium-light_skin_tone": "✍🏼", + "writing_hand_medium_skin_tone": "✍🏽", + "yarn": "🧶", + "yawning_face": "🥱", + "yellow_circle": "🟡", + "yellow_heart": "💛", + "yellow_square": "🟨", + "yen_banknote": "💴", + "yo-yo": "🪀", + "yin_yang": "☯", + "zany_face": "🤪", + "zebra": "🦓", + "zipper-mouth_face": "🤐", + "zombie": "🧟", + "zzz": "💤", + "åland_islands": "🇦🇽", + "keycap_asterisk": "*⃣", + "keycap_digit_eight": "8⃣", + "keycap_digit_five": "5⃣", + "keycap_digit_four": "4⃣", + "keycap_digit_nine": "9⃣", + "keycap_digit_one": "1⃣", + "keycap_digit_seven": "7⃣", + "keycap_digit_six": "6⃣", + "keycap_digit_three": "3⃣", + "keycap_digit_two": "2⃣", + "keycap_digit_zero": "0⃣", + "keycap_number_sign": "#⃣", + "light_skin_tone": "🏻", + "medium_light_skin_tone": "🏼", + "medium_skin_tone": "🏽", + "medium_dark_skin_tone": "🏾", + "dark_skin_tone": "🏿", + "regional_indicator_symbol_letter_a": "🇦", + "regional_indicator_symbol_letter_b": "🇧", + "regional_indicator_symbol_letter_c": "🇨", + "regional_indicator_symbol_letter_d": "🇩", + "regional_indicator_symbol_letter_e": "🇪", + "regional_indicator_symbol_letter_f": "🇫", + "regional_indicator_symbol_letter_g": "🇬", + "regional_indicator_symbol_letter_h": "🇭", + "regional_indicator_symbol_letter_i": "🇮", + "regional_indicator_symbol_letter_j": "🇯", + "regional_indicator_symbol_letter_k": "🇰", + "regional_indicator_symbol_letter_l": "🇱", + "regional_indicator_symbol_letter_m": "🇲", + "regional_indicator_symbol_letter_n": "🇳", + "regional_indicator_symbol_letter_o": "🇴", + "regional_indicator_symbol_letter_p": "🇵", + "regional_indicator_symbol_letter_q": "🇶", + "regional_indicator_symbol_letter_r": "🇷", + "regional_indicator_symbol_letter_s": "🇸", + "regional_indicator_symbol_letter_t": "🇹", + "regional_indicator_symbol_letter_u": "🇺", + "regional_indicator_symbol_letter_v": "🇻", + "regional_indicator_symbol_letter_w": "🇼", + "regional_indicator_symbol_letter_x": "🇽", + "regional_indicator_symbol_letter_y": "🇾", + "regional_indicator_symbol_letter_z": "🇿", + "airplane_arriving": "🛬", + "space_invader": "👾", + "football": "🏈", + "anger": "💢", + "angry": "😠", + "anguished": "😧", + "signal_strength": "📶", + "arrows_counterclockwise": "🔄", + "arrow_heading_down": "⤵", + "arrow_heading_up": "⤴", + "art": "🎨", + "astonished": "😲", + "athletic_shoe": "👟", + "atm": "🏧", + "car": "🚗", + "red_car": "🚗", + "angel": "👼", + "back": "🔙", + "badminton_racquet_and_shuttlecock": "🏸", + "dollar": "💵", + "euro": "💶", + "pound": "💷", + "yen": "💴", + "barber": "💈", + "bath": "🛀", + "bear": "🐻", + "heartbeat": "💓", + "beer": "🍺", + "no_bell": "🔕", + "bento": "🍱", + "bike": "🚲", + "bicyclist": "🚴", + "8ball": "🎱", + "biohazard_sign": "☣", + "birthday": "🎂", + "black_circle_for_record": "⏺", + "clubs": "♣", + "diamonds": "♦", + "arrow_double_down": "⏬", + "hearts": "♥", + "rewind": "⏪", + "black_left__pointing_double_triangle_with_vertical_bar": "⏮", + "arrow_backward": "◀", + "black_medium_small_square": "◾", + "question": "❓", + "fast_forward": "⏩", + "black_right__pointing_double_triangle_with_vertical_bar": "⏭", + "arrow_forward": "▶", + "black_right__pointing_triangle_with_double_vertical_bar": "⏯", + "arrow_right": "➡", + "spades": "♠", + "black_square_for_stop": "⏹", + "sunny": "☀", + "phone": "☎", + "recycle": "♻", + "arrow_double_up": "⏫", + "busstop": "🚏", + "date": "📅", + "flags": "🎏", + "cat2": "🐈", + "joy_cat": "😹", + "smirk_cat": "😼", + "chart_with_downwards_trend": "📉", + "chart_with_upwards_trend": "📈", + "chart": "💹", + "mega": "📣", + "checkered_flag": "🏁", + "accept": "🉑", + "ideograph_advantage": "🉐", + "congratulations": "㊗", + "secret": "㊙", + "m": "Ⓜ", + "city_sunset": "🌆", + "clapper": "🎬", + "clap": "👏", + "beers": "🍻", + "clock830": "🕣", + "clock8": "🕗", + "clock1130": "🕦", + "clock11": "🕚", + "clock530": "🕠", + "clock5": "🕔", + "clock430": "🕟", + "clock4": "🕓", + "clock930": "🕤", + "clock9": "🕘", + "clock130": "🕜", + "clock1": "🕐", + "clock730": "🕢", + "clock7": "🕖", + "clock630": "🕡", + "clock6": "🕕", + "clock1030": "🕥", + "clock10": "🕙", + "clock330": "🕞", + "clock3": "🕒", + "clock1230": "🕧", + "clock12": "🕛", + "clock230": "🕝", + "clock2": "🕑", + "arrows_clockwise": "🔃", + "repeat": "🔁", + "repeat_one": "🔂", + "closed_lock_with_key": "🔐", + "mailbox_closed": "📪", + "mailbox": "📫", + "cloud_with_tornado": "🌪", + "cocktail": "🍸", + "boom": "💥", + "compression": "🗜", + "confounded": "😖", + "confused": "😕", + "rice": "🍚", + "cow2": "🐄", + "cricket_bat_and_ball": "🏏", + "x": "❌", + "cry": "😢", + "curry": "🍛", + "dagger_knife": "🗡", + "dancer": "💃", + "dark_sunglasses": "🕶", + "dash": "💨", + "truck": "🚚", + "derelict_house_building": "🏚", + "diamond_shape_with_a_dot_inside": "💠", + "dart": "🎯", + "disappointed_relieved": "😥", + "disappointed": "😞", + "do_not_litter": "🚯", + "dog2": "🐕", + "flipper": "🐬", + "loop": "➿", + "bangbang": "‼", + "double_vertical_bar": "⏸", + "dove_of_peace": "🕊", + "small_red_triangle_down": "🔻", + "arrow_down_small": "🔽", + "arrow_down": "⬇", + "dromedary_camel": "🐪", + "e__mail": "📧", + "corn": "🌽", + "ear_of_rice": "🌾", + "earth_americas": "🌎", + "earth_asia": "🌏", + "earth_africa": "🌍", + "eight_pointed_black_star": "✴", + "eight_spoked_asterisk": "✳", + "eject_symbol": "⏏", + "bulb": "💡", + "emoji_modifier_fitzpatrick_type__1__2": "🏻", + "emoji_modifier_fitzpatrick_type__3": "🏼", + "emoji_modifier_fitzpatrick_type__4": "🏽", + "emoji_modifier_fitzpatrick_type__5": "🏾", + "emoji_modifier_fitzpatrick_type__6": "🏿", + "end": "🔚", + "email": "✉", + "european_castle": "🏰", + "european_post_office": "🏤", + "interrobang": "⁉", + "expressionless": "😑", + "eyeglasses": "👓", + "massage": "💆", + "yum": "😋", + "scream": "😱", + "kissing_heart": "😘", + "sweat": "😓", + "face_with_head__bandage": "🤕", + "triumph": "😤", + "mask": "😷", + "no_good": "🙅", + "ok_woman": "🙆", + "open_mouth": "😮", + "cold_sweat": "😰", + "stuck_out_tongue": "😛", + "stuck_out_tongue_closed_eyes": "😝", + "stuck_out_tongue_winking_eye": "😜", + "joy": "😂", + "no_mouth": "😶", + "santa": "🎅", + "fax": "📠", + "fearful": "😨", + "field_hockey_stick_and_ball": "🏑", + "first_quarter_moon_with_face": "🌛", + "fish_cake": "🍥", + "fishing_pole_and_fish": "🎣", + "facepunch": "👊", + "punch": "👊", + "flag_for_afghanistan": "🇦🇫", + "flag_for_albania": "🇦🇱", + "flag_for_algeria": "🇩🇿", + "flag_for_american_samoa": "🇦🇸", + "flag_for_andorra": "🇦🇩", + "flag_for_angola": "🇦🇴", + "flag_for_anguilla": "🇦🇮", + "flag_for_antarctica": "🇦🇶", + "flag_for_antigua_&_barbuda": "🇦🇬", + "flag_for_argentina": "🇦🇷", + "flag_for_armenia": "🇦🇲", + "flag_for_aruba": "🇦🇼", + "flag_for_ascension_island": "🇦🇨", + "flag_for_australia": "🇦🇺", + "flag_for_austria": "🇦🇹", + "flag_for_azerbaijan": "🇦🇿", + "flag_for_bahamas": "🇧🇸", + "flag_for_bahrain": "🇧🇭", + "flag_for_bangladesh": "🇧🇩", + "flag_for_barbados": "🇧🇧", + "flag_for_belarus": "🇧🇾", + "flag_for_belgium": "🇧🇪", + "flag_for_belize": "🇧🇿", + "flag_for_benin": "🇧🇯", + "flag_for_bermuda": "🇧🇲", + "flag_for_bhutan": "🇧🇹", + "flag_for_bolivia": "🇧🇴", + "flag_for_bosnia_&_herzegovina": "🇧🇦", + "flag_for_botswana": "🇧🇼", + "flag_for_bouvet_island": "🇧🇻", + "flag_for_brazil": "🇧🇷", + "flag_for_british_indian_ocean_territory": "🇮🇴", + "flag_for_british_virgin_islands": "🇻🇬", + "flag_for_brunei": "🇧🇳", + "flag_for_bulgaria": "🇧🇬", + "flag_for_burkina_faso": "🇧🇫", + "flag_for_burundi": "🇧🇮", + "flag_for_cambodia": "🇰🇭", + "flag_for_cameroon": "🇨🇲", + "flag_for_canada": "🇨🇦", + "flag_for_canary_islands": "🇮🇨", + "flag_for_cape_verde": "🇨🇻", + "flag_for_caribbean_netherlands": "🇧🇶", + "flag_for_cayman_islands": "🇰🇾", + "flag_for_central_african_republic": "🇨🇫", + "flag_for_ceuta_&_melilla": "🇪🇦", + "flag_for_chad": "🇹🇩", + "flag_for_chile": "🇨🇱", + "flag_for_china": "🇨🇳", + "flag_for_christmas_island": "🇨🇽", + "flag_for_clipperton_island": "🇨🇵", + "flag_for_cocos__islands": "🇨🇨", + "flag_for_colombia": "🇨🇴", + "flag_for_comoros": "🇰🇲", + "flag_for_congo____brazzaville": "🇨🇬", + "flag_for_congo____kinshasa": "🇨🇩", + "flag_for_cook_islands": "🇨🇰", + "flag_for_costa_rica": "🇨🇷", + "flag_for_croatia": "🇭🇷", + "flag_for_cuba": "🇨🇺", + "flag_for_curaçao": "🇨🇼", + "flag_for_cyprus": "🇨🇾", + "flag_for_czech_republic": "🇨🇿", + "flag_for_côte_d’ivoire": "🇨🇮", + "flag_for_denmark": "🇩🇰", + "flag_for_diego_garcia": "🇩🇬", + "flag_for_djibouti": "🇩🇯", + "flag_for_dominica": "🇩🇲", + "flag_for_dominican_republic": "🇩🇴", + "flag_for_ecuador": "🇪🇨", + "flag_for_egypt": "🇪🇬", + "flag_for_el_salvador": "🇸🇻", + "flag_for_equatorial_guinea": "🇬🇶", + "flag_for_eritrea": "🇪🇷", + "flag_for_estonia": "🇪🇪", + "flag_for_ethiopia": "🇪🇹", + "flag_for_european_union": "🇪🇺", + "flag_for_falkland_islands": "🇫🇰", + "flag_for_faroe_islands": "🇫🇴", + "flag_for_fiji": "🇫🇯", + "flag_for_finland": "🇫🇮", + "flag_for_france": "🇫🇷", + "flag_for_french_guiana": "🇬🇫", + "flag_for_french_polynesia": "🇵🇫", + "flag_for_french_southern_territories": "🇹🇫", + "flag_for_gabon": "🇬🇦", + "flag_for_gambia": "🇬🇲", + "flag_for_georgia": "🇬🇪", + "flag_for_germany": "🇩🇪", + "flag_for_ghana": "🇬🇭", + "flag_for_gibraltar": "🇬🇮", + "flag_for_greece": "🇬🇷", + "flag_for_greenland": "🇬🇱", + "flag_for_grenada": "🇬🇩", + "flag_for_guadeloupe": "🇬🇵", + "flag_for_guam": "🇬🇺", + "flag_for_guatemala": "🇬🇹", + "flag_for_guernsey": "🇬🇬", + "flag_for_guinea": "🇬🇳", + "flag_for_guinea__bissau": "🇬🇼", + "flag_for_guyana": "🇬🇾", + "flag_for_haiti": "🇭🇹", + "flag_for_heard_&_mcdonald_islands": "🇭🇲", + "flag_for_honduras": "🇭🇳", + "flag_for_hong_kong": "🇭🇰", + "flag_for_hungary": "🇭🇺", + "flag_for_iceland": "🇮🇸", + "flag_for_india": "🇮🇳", + "flag_for_indonesia": "🇮🇩", + "flag_for_iran": "🇮🇷", + "flag_for_iraq": "🇮🇶", + "flag_for_ireland": "🇮🇪", + "flag_for_isle_of_man": "🇮🇲", + "flag_for_israel": "🇮🇱", + "flag_for_italy": "🇮🇹", + "flag_for_jamaica": "🇯🇲", + "flag_for_japan": "🇯🇵", + "flag_for_jersey": "🇯🇪", + "flag_for_jordan": "🇯🇴", + "flag_for_kazakhstan": "🇰🇿", + "flag_for_kenya": "🇰🇪", + "flag_for_kiribati": "🇰🇮", + "flag_for_kosovo": "🇽🇰", + "flag_for_kuwait": "🇰🇼", + "flag_for_kyrgyzstan": "🇰🇬", + "flag_for_laos": "🇱🇦", + "flag_for_latvia": "🇱🇻", + "flag_for_lebanon": "🇱🇧", + "flag_for_lesotho": "🇱🇸", + "flag_for_liberia": "🇱🇷", + "flag_for_libya": "🇱🇾", + "flag_for_liechtenstein": "🇱🇮", + "flag_for_lithuania": "🇱🇹", + "flag_for_luxembourg": "🇱🇺", + "flag_for_macau": "🇲🇴", + "flag_for_macedonia": "🇲🇰", + "flag_for_madagascar": "🇲🇬", + "flag_for_malawi": "🇲🇼", + "flag_for_malaysia": "🇲🇾", + "flag_for_maldives": "🇲🇻", + "flag_for_mali": "🇲🇱", + "flag_for_malta": "🇲🇹", + "flag_for_marshall_islands": "🇲🇭", + "flag_for_martinique": "🇲🇶", + "flag_for_mauritania": "🇲🇷", + "flag_for_mauritius": "🇲🇺", + "flag_for_mayotte": "🇾🇹", + "flag_for_mexico": "🇲🇽", + "flag_for_micronesia": "🇫🇲", + "flag_for_moldova": "🇲🇩", + "flag_for_monaco": "🇲🇨", + "flag_for_mongolia": "🇲🇳", + "flag_for_montenegro": "🇲🇪", + "flag_for_montserrat": "🇲🇸", + "flag_for_morocco": "🇲🇦", + "flag_for_mozambique": "🇲🇿", + "flag_for_myanmar": "🇲🇲", + "flag_for_namibia": "🇳🇦", + "flag_for_nauru": "🇳🇷", + "flag_for_nepal": "🇳🇵", + "flag_for_netherlands": "🇳🇱", + "flag_for_new_caledonia": "🇳🇨", + "flag_for_new_zealand": "🇳🇿", + "flag_for_nicaragua": "🇳🇮", + "flag_for_niger": "🇳🇪", + "flag_for_nigeria": "🇳🇬", + "flag_for_niue": "🇳🇺", + "flag_for_norfolk_island": "🇳🇫", + "flag_for_north_korea": "🇰🇵", + "flag_for_northern_mariana_islands": "🇲🇵", + "flag_for_norway": "🇳🇴", + "flag_for_oman": "🇴🇲", + "flag_for_pakistan": "🇵🇰", + "flag_for_palau": "🇵🇼", + "flag_for_palestinian_territories": "🇵🇸", + "flag_for_panama": "🇵🇦", + "flag_for_papua_new_guinea": "🇵🇬", + "flag_for_paraguay": "🇵🇾", + "flag_for_peru": "🇵🇪", + "flag_for_philippines": "🇵🇭", + "flag_for_pitcairn_islands": "🇵🇳", + "flag_for_poland": "🇵🇱", + "flag_for_portugal": "🇵🇹", + "flag_for_puerto_rico": "🇵🇷", + "flag_for_qatar": "🇶🇦", + "flag_for_romania": "🇷🇴", + "flag_for_russia": "🇷🇺", + "flag_for_rwanda": "🇷🇼", + "flag_for_réunion": "🇷🇪", + "flag_for_samoa": "🇼🇸", + "flag_for_san_marino": "🇸🇲", + "flag_for_saudi_arabia": "🇸🇦", + "flag_for_senegal": "🇸🇳", + "flag_for_serbia": "🇷🇸", + "flag_for_seychelles": "🇸🇨", + "flag_for_sierra_leone": "🇸🇱", + "flag_for_singapore": "🇸🇬", + "flag_for_sint_maarten": "🇸🇽", + "flag_for_slovakia": "🇸🇰", + "flag_for_slovenia": "🇸🇮", + "flag_for_solomon_islands": "🇸🇧", + "flag_for_somalia": "🇸🇴", + "flag_for_south_africa": "🇿🇦", + "flag_for_south_georgia_&_south_sandwich_islands": "🇬🇸", + "flag_for_south_korea": "🇰🇷", + "flag_for_south_sudan": "🇸🇸", + "flag_for_spain": "🇪🇸", + "flag_for_sri_lanka": "🇱🇰", + "flag_for_st._barthélemy": "🇧🇱", + "flag_for_st._helena": "🇸🇭", + "flag_for_st._kitts_&_nevis": "🇰🇳", + "flag_for_st._lucia": "🇱🇨", + "flag_for_st._martin": "🇲🇫", + "flag_for_st._pierre_&_miquelon": "🇵🇲", + "flag_for_st._vincent_&_grenadines": "🇻🇨", + "flag_for_sudan": "🇸🇩", + "flag_for_suriname": "🇸🇷", + "flag_for_svalbard_&_jan_mayen": "🇸🇯", + "flag_for_swaziland": "🇸🇿", + "flag_for_sweden": "🇸🇪", + "flag_for_switzerland": "🇨🇭", + "flag_for_syria": "🇸🇾", + "flag_for_são_tomé_&_príncipe": "🇸🇹", + "flag_for_taiwan": "🇹🇼", + "flag_for_tajikistan": "🇹🇯", + "flag_for_tanzania": "🇹🇿", + "flag_for_thailand": "🇹🇭", + "flag_for_timor__leste": "🇹🇱", + "flag_for_togo": "🇹🇬", + "flag_for_tokelau": "🇹🇰", + "flag_for_tonga": "🇹🇴", + "flag_for_trinidad_&_tobago": "🇹🇹", + "flag_for_tristan_da_cunha": "🇹🇦", + "flag_for_tunisia": "🇹🇳", + "flag_for_turkey": "🇹🇷", + "flag_for_turkmenistan": "🇹🇲", + "flag_for_turks_&_caicos_islands": "🇹🇨", + "flag_for_tuvalu": "🇹🇻", + "flag_for_u.s._outlying_islands": "🇺🇲", + "flag_for_u.s._virgin_islands": "🇻🇮", + "flag_for_uganda": "🇺🇬", + "flag_for_ukraine": "🇺🇦", + "flag_for_united_arab_emirates": "🇦🇪", + "flag_for_united_kingdom": "🇬🇧", + "flag_for_united_states": "🇺🇸", + "flag_for_uruguay": "🇺🇾", + "flag_for_uzbekistan": "🇺🇿", + "flag_for_vanuatu": "🇻🇺", + "flag_for_vatican_city": "🇻🇦", + "flag_for_venezuela": "🇻🇪", + "flag_for_vietnam": "🇻🇳", + "flag_for_wallis_&_futuna": "🇼🇫", + "flag_for_western_sahara": "🇪🇭", + "flag_for_yemen": "🇾🇪", + "flag_for_zambia": "🇿🇲", + "flag_for_zimbabwe": "🇿🇼", + "flag_for_åland_islands": "🇦🇽", + "golf": "⛳", + "fleur__de__lis": "⚜", + "muscle": "💪", + "flushed": "😳", + "frame_with_picture": "🖼", + "fries": "🍟", + "frog": "🐸", + "hatched_chick": "🐥", + "frowning": "😦", + "fuelpump": "⛽", + "full_moon_with_face": "🌝", + "gem": "💎", + "star2": "🌟", + "golfer": "🏌", + "mortar_board": "🎓", + "grimacing": "😬", + "smile_cat": "😸", + "grinning": "😀", + "grin": "😁", + "heartpulse": "💗", + "guardsman": "💂", + "haircut": "💇", + "hamster": "🐹", + "raising_hand": "🙋", + "headphones": "🎧", + "hear_no_evil": "🙉", + "cupid": "💘", + "gift_heart": "💝", + "heart": "❤", + "exclamation": "❗", + "heavy_exclamation_mark": "❗", + "heavy_heart_exclamation_mark_ornament": "❣", + "o": "⭕", + "helm_symbol": "⎈", + "helmet_with_white_cross": "⛑", + "high_heel": "👠", + "bullettrain_side": "🚄", + "bullettrain_front": "🚅", + "high_brightness": "🔆", + "zap": "⚡", + "hocho": "🔪", + "knife": "🔪", + "bee": "🐝", + "traffic_light": "🚥", + "racehorse": "🐎", + "coffee": "☕", + "hotsprings": "♨", + "hourglass": "⌛", + "hourglass_flowing_sand": "⏳", + "house_buildings": "🏘", + "100": "💯", + "hushed": "😯", + "ice_hockey_stick_and_puck": "🏒", + "imp": "👿", + "information_desk_person": "💁", + "information_source": "ℹ", + "capital_abcd": "🔠", + "abc": "🔤", + "abcd": "🔡", + "1234": "🔢", + "symbols": "🔣", + "izakaya_lantern": "🏮", + "lantern": "🏮", + "jack_o_lantern": "🎃", + "dolls": "🎎", + "japanese_goblin": "👺", + "japanese_ogre": "👹", + "beginner": "🔰", + "zero": "0️⃣", + "one": "1️⃣", + "ten": "🔟", + "two": "2️⃣", + "three": "3️⃣", + "four": "4️⃣", + "five": "5️⃣", + "six": "6️⃣", + "seven": "7️⃣", + "eight": "8️⃣", + "nine": "9️⃣", + "couplekiss": "💏", + "kissing_cat": "😽", + "kissing": "😗", + "kissing_closed_eyes": "😚", + "kissing_smiling_eyes": "😙", + "beetle": "🐞", + "large_blue_circle": "🔵", + "last_quarter_moon_with_face": "🌜", + "leaves": "🍃", + "mag": "🔍", + "left_right_arrow": "↔", + "leftwards_arrow_with_hook": "↩", + "arrow_left": "⬅", + "lock": "🔒", + "lock_with_ink_pen": "🔏", + "sob": "😭", + "low_brightness": "🔅", + "lower_left_ballpoint_pen": "🖊", + "lower_left_crayon": "🖍", + "lower_left_fountain_pen": "🖋", + "lower_left_paintbrush": "🖌", + "mahjong": "🀄", + "couple": "👫", + "man_in_business_suit_levitating": "🕴", + "man_with_gua_pi_mao": "👲", + "man_with_turban": "👳", + "mans_shoe": "👞", + "shoe": "👞", + "menorah_with_nine_branches": "🕎", + "mens": "🚹", + "minidisc": "💽", + "iphone": "📱", + "calling": "📲", + "money__mouth_face": "🤑", + "moneybag": "💰", + "rice_scene": "🎑", + "mountain_bicyclist": "🚵", + "mouse2": "🐁", + "lips": "👄", + "moyai": "🗿", + "notes": "🎶", + "nail_care": "💅", + "ab": "🆎", + "negative_squared_cross_mark": "❎", + "a": "🅰", + "b": "🅱", + "o2": "🅾", + "parking": "🅿", + "new_moon_with_face": "🌚", + "no_entry_sign": "🚫", + "underage": "🔞", + "non__potable_water": "🚱", + "arrow_upper_right": "↗", + "arrow_upper_left": "↖", + "office": "🏢", + "older_man": "👴", + "older_woman": "👵", + "om_symbol": "🕉", + "on": "🔛", + "book": "📖", + "unlock": "🔓", + "mailbox_with_no_mail": "📭", + "mailbox_with_mail": "📬", + "cd": "💿", + "tada": "🎉", + "feet": "🐾", + "walking": "🚶", + "pencil2": "✏", + "pensive": "😔", + "persevere": "😣", + "bow": "🙇", + "raised_hands": "🙌", + "person_with_ball": "⛹", + "person_with_blond_hair": "👱", + "pray": "🙏", + "person_with_pouting_face": "🙎", + "computer": "💻", + "pig2": "🐖", + "hankey": "💩", + "poop": "💩", + "shit": "💩", + "bamboo": "🎍", + "gun": "🔫", + "black_joker": "🃏", + "rotating_light": "🚨", + "cop": "👮", + "stew": "🍲", + "pouch": "👝", + "pouting_cat": "😾", + "rage": "😡", + "put_litter_in_its_place": "🚮", + "rabbit2": "🐇", + "racing_motorcycle": "🏍", + "radioactive_sign": "☢", + "fist": "✊", + "hand": "✋", + "raised_hand_with_fingers_splayed": "🖐", + "raised_hand_with_part_between_middle_and_ring_fingers": "🖖", + "blue_car": "🚙", + "apple": "🍎", + "relieved": "😌", + "reversed_hand_with_middle_finger_extended": "🖕", + "mag_right": "🔎", + "arrow_right_hook": "↪", + "sweet_potato": "🍠", + "robot": "🤖", + "rolled__up_newspaper": "🗞", + "rowboat": "🚣", + "runner": "🏃", + "running": "🏃", + "running_shirt_with_sash": "🎽", + "boat": "⛵", + "scales": "⚖", + "school_satchel": "🎒", + "scorpius": "♏", + "see_no_evil": "🙈", + "sheep": "🐑", + "stars": "🌠", + "cake": "🍰", + "six_pointed_star": "🔯", + "ski": "🎿", + "sleeping_accommodation": "🛌", + "sleeping": "😴", + "sleepy": "😪", + "sleuth_or_spy": "🕵", + "heart_eyes_cat": "😻", + "smiley_cat": "😺", + "innocent": "😇", + "heart_eyes": "😍", + "smiling_imp": "😈", + "smiley": "😃", + "sweat_smile": "😅", + "smile": "😄", + "laughing": "😆", + "satisfied": "😆", + "blush": "😊", + "smirk": "😏", + "smoking": "🚬", + "snow_capped_mountain": "🏔", + "soccer": "⚽", + "icecream": "🍦", + "soon": "🔜", + "arrow_lower_right": "↘", + "arrow_lower_left": "↙", + "speak_no_evil": "🙊", + "speaker": "🔈", + "mute": "🔇", + "sound": "🔉", + "loud_sound": "🔊", + "speaking_head_in_silhouette": "🗣", + "spiral_calendar_pad": "🗓", + "spiral_note_pad": "🗒", + "shell": "🐚", + "sweat_drops": "💦", + "u5272": "🈹", + "u5408": "🈴", + "u55b6": "🈺", + "u6307": "🈯", + "u6708": "🈷", + "u6709": "🈶", + "u6e80": "🈵", + "u7121": "🈚", + "u7533": "🈸", + "u7981": "🈲", + "u7a7a": "🈳", + "cl": "🆑", + "cool": "🆒", + "free": "🆓", + "id": "🆔", + "koko": "🈁", + "sa": "🈂", + "new": "🆕", + "ng": "🆖", + "ok": "🆗", + "sos": "🆘", + "up": "🆙", + "vs": "🆚", + "steam_locomotive": "🚂", + "ramen": "🍜", + "partly_sunny": "⛅", + "city_sunrise": "🌇", + "surfer": "🏄", + "swimmer": "🏊", + "shirt": "👕", + "tshirt": "👕", + "table_tennis_paddle_and_ball": "🏓", + "tea": "🍵", + "tv": "📺", + "three_button_mouse": "🖱", + "+1": "👍", + "thumbsup": "👍", + "__1": "👎", + "-1": "👎", + "thumbsdown": "👎", + "thunder_cloud_and_rain": "⛈", + "tiger2": "🐅", + "tophat": "🎩", + "top": "🔝", + "tm": "™", + "train2": "🚆", + "triangular_flag_on_post": "🚩", + "trident": "🔱", + "twisted_rightwards_arrows": "🔀", + "unamused": "😒", + "small_red_triangle": "🔺", + "arrow_up_small": "🔼", + "arrow_up_down": "↕", + "upside__down_face": "🙃", + "arrow_up": "⬆", + "v": "✌", + "vhs": "📼", + "wc": "🚾", + "ocean": "🌊", + "waving_black_flag": "🏴", + "wave": "👋", + "waving_white_flag": "🏳", + "moon": "🌔", + "scream_cat": "🙀", + "weary": "😩", + "weight_lifter": "🏋", + "whale2": "🐋", + "wheelchair": "♿", + "point_down": "👇", + "grey_exclamation": "❕", + "white_frowning_face": "☹", + "white_check_mark": "✅", + "point_left": "👈", + "white_medium_small_square": "◽", + "star": "⭐", + "grey_question": "❔", + "point_right": "👉", + "relaxed": "☺", + "white_sun_behind_cloud": "🌥", + "white_sun_behind_cloud_with_rain": "🌦", + "white_sun_with_small_cloud": "🌤", + "point_up_2": "👆", + "point_up": "☝", + "wind_blowing_face": "🌬", + "wink": "😉", + "wolf": "🐺", + "dancers": "👯", + "boot": "👢", + "womans_clothes": "👚", + "womans_hat": "👒", + "sandal": "👡", + "womens": "🚺", + "worried": "😟", + "gift": "🎁", + "zipper__mouth_face": "🤐", + "regional_indicator_a": "🇦", + "regional_indicator_b": "🇧", + "regional_indicator_c": "🇨", + "regional_indicator_d": "🇩", + "regional_indicator_e": "🇪", + "regional_indicator_f": "🇫", + "regional_indicator_g": "🇬", + "regional_indicator_h": "🇭", + "regional_indicator_i": "🇮", + "regional_indicator_j": "🇯", + "regional_indicator_k": "🇰", + "regional_indicator_l": "🇱", + "regional_indicator_m": "🇲", + "regional_indicator_n": "🇳", + "regional_indicator_o": "🇴", + "regional_indicator_p": "🇵", + "regional_indicator_q": "🇶", + "regional_indicator_r": "🇷", + "regional_indicator_s": "🇸", + "regional_indicator_t": "🇹", + "regional_indicator_u": "🇺", + "regional_indicator_v": "🇻", + "regional_indicator_w": "🇼", + "regional_indicator_x": "🇽", + "regional_indicator_y": "🇾", + "regional_indicator_z": "🇿", +} diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rich/_emoji_replace.py b/TTS/Kokoro/.venv/Lib/site-packages/rich/_emoji_replace.py new file mode 100644 index 0000000000000000000000000000000000000000..bb2cafa18011e7115773055338291c366f173d6f --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rich/_emoji_replace.py @@ -0,0 +1,32 @@ +from typing import Callable, Match, Optional +import re + +from ._emoji_codes import EMOJI + + +_ReStringMatch = Match[str] # regex match object +_ReSubCallable = Callable[[_ReStringMatch], str] # Callable invoked by re.sub +_EmojiSubMethod = Callable[[_ReSubCallable, str], str] # Sub method of a compiled re + + +def _emoji_replace( + text: str, + default_variant: Optional[str] = None, + _emoji_sub: _EmojiSubMethod = re.compile(r"(:(\S*?)(?:(?:\-)(emoji|text))?:)").sub, +) -> str: + """Replace emoji code in text.""" + get_emoji = EMOJI.__getitem__ + variants = {"text": "\uFE0E", "emoji": "\uFE0F"} + get_variant = variants.get + default_variant_code = variants.get(default_variant, "") if default_variant else "" + + def do_replace(match: Match[str]) -> str: + emoji_code, emoji_name, variant = match.groups() + try: + return get_emoji(emoji_name.lower()) + get_variant( + variant, default_variant_code + ) + except KeyError: + return emoji_code + + return _emoji_sub(do_replace, text) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rich/_export_format.py b/TTS/Kokoro/.venv/Lib/site-packages/rich/_export_format.py new file mode 100644 index 0000000000000000000000000000000000000000..e7527e52f6613328630fc6305f957d9ea58027d8 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rich/_export_format.py @@ -0,0 +1,76 @@ +CONSOLE_HTML_FORMAT = """\ + + + + + + + +
{code}
+ + +""" + +CONSOLE_SVG_FORMAT = """\ + + + + + + + + + {lines} + + + {chrome} + + {backgrounds} + + {matrix} + + + +""" + +_SVG_FONT_FAMILY = "Rich Fira Code" +_SVG_CLASSES_PREFIX = "rich-svg" diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rich/_extension.py b/TTS/Kokoro/.venv/Lib/site-packages/rich/_extension.py new file mode 100644 index 0000000000000000000000000000000000000000..38658864eb1e9b9839e953e070af11c8bc0d1836 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rich/_extension.py @@ -0,0 +1,10 @@ +from typing import Any + + +def load_ipython_extension(ip: Any) -> None: # pragma: no cover + # prevent circular import + from rich.pretty import install + from rich.traceback import install as tr_install + + install() + tr_install() diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rich/_fileno.py b/TTS/Kokoro/.venv/Lib/site-packages/rich/_fileno.py new file mode 100644 index 0000000000000000000000000000000000000000..b17ee6511742d7a8d5950bf0ee57ced4d5fd45c2 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rich/_fileno.py @@ -0,0 +1,24 @@ +from __future__ import annotations + +from typing import IO, Callable + + +def get_fileno(file_like: IO[str]) -> int | None: + """Get fileno() from a file, accounting for poorly implemented file-like objects. + + Args: + file_like (IO): A file-like object. + + Returns: + int | None: The result of fileno if available, or None if operation failed. + """ + fileno: Callable[[], int] | None = getattr(file_like, "fileno", None) + if fileno is not None: + try: + return fileno() + except Exception: + # `fileno` is documented as potentially raising a OSError + # Alas, from the issues, there are so many poorly implemented file-like objects, + # that `fileno()` can raise just about anything. + return None + return None diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rich/_log_render.py b/TTS/Kokoro/.venv/Lib/site-packages/rich/_log_render.py new file mode 100644 index 0000000000000000000000000000000000000000..e8810100b323450c63507e16629a09bb2e9dc97f --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rich/_log_render.py @@ -0,0 +1,94 @@ +from datetime import datetime +from typing import Iterable, List, Optional, TYPE_CHECKING, Union, Callable + + +from .text import Text, TextType + +if TYPE_CHECKING: + from .console import Console, ConsoleRenderable, RenderableType + from .table import Table + +FormatTimeCallable = Callable[[datetime], Text] + + +class LogRender: + def __init__( + self, + show_time: bool = True, + show_level: bool = False, + show_path: bool = True, + time_format: Union[str, FormatTimeCallable] = "[%x %X]", + omit_repeated_times: bool = True, + level_width: Optional[int] = 8, + ) -> None: + self.show_time = show_time + self.show_level = show_level + self.show_path = show_path + self.time_format = time_format + self.omit_repeated_times = omit_repeated_times + self.level_width = level_width + self._last_time: Optional[Text] = None + + def __call__( + self, + console: "Console", + renderables: Iterable["ConsoleRenderable"], + log_time: Optional[datetime] = None, + time_format: Optional[Union[str, FormatTimeCallable]] = None, + level: TextType = "", + path: Optional[str] = None, + line_no: Optional[int] = None, + link_path: Optional[str] = None, + ) -> "Table": + from .containers import Renderables + from .table import Table + + output = Table.grid(padding=(0, 1)) + output.expand = True + if self.show_time: + output.add_column(style="log.time") + if self.show_level: + output.add_column(style="log.level", width=self.level_width) + output.add_column(ratio=1, style="log.message", overflow="fold") + if self.show_path and path: + output.add_column(style="log.path") + row: List["RenderableType"] = [] + if self.show_time: + log_time = log_time or console.get_datetime() + time_format = time_format or self.time_format + if callable(time_format): + log_time_display = time_format(log_time) + else: + log_time_display = Text(log_time.strftime(time_format)) + if log_time_display == self._last_time and self.omit_repeated_times: + row.append(Text(" " * len(log_time_display))) + else: + row.append(log_time_display) + self._last_time = log_time_display + if self.show_level: + row.append(level) + + row.append(Renderables(renderables)) + if self.show_path and path: + path_text = Text() + path_text.append( + path, style=f"link file://{link_path}" if link_path else "" + ) + if line_no: + path_text.append(":") + path_text.append( + f"{line_no}", + style=f"link file://{link_path}#{line_no}" if link_path else "", + ) + row.append(path_text) + + output.add_row(*row) + return output + + +if __name__ == "__main__": # pragma: no cover + from rich.console import Console + + c = Console() + c.print("[on blue]Hello", justify="right") + c.log("[on blue]hello", justify="right") diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rich/_null_file.py b/TTS/Kokoro/.venv/Lib/site-packages/rich/_null_file.py new file mode 100644 index 0000000000000000000000000000000000000000..6ae05d3e2a901af754b1626d911ebc3c45e22a40 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rich/_null_file.py @@ -0,0 +1,69 @@ +from types import TracebackType +from typing import IO, Iterable, Iterator, List, Optional, Type + + +class NullFile(IO[str]): + def close(self) -> None: + pass + + def isatty(self) -> bool: + return False + + def read(self, __n: int = 1) -> str: + return "" + + def readable(self) -> bool: + return False + + def readline(self, __limit: int = 1) -> str: + return "" + + def readlines(self, __hint: int = 1) -> List[str]: + return [] + + def seek(self, __offset: int, __whence: int = 1) -> int: + return 0 + + def seekable(self) -> bool: + return False + + def tell(self) -> int: + return 0 + + def truncate(self, __size: Optional[int] = 1) -> int: + return 0 + + def writable(self) -> bool: + return False + + def writelines(self, __lines: Iterable[str]) -> None: + pass + + def __next__(self) -> str: + return "" + + def __iter__(self) -> Iterator[str]: + return iter([""]) + + def __enter__(self) -> IO[str]: + return self + + def __exit__( + self, + __t: Optional[Type[BaseException]], + __value: Optional[BaseException], + __traceback: Optional[TracebackType], + ) -> None: + pass + + def write(self, text: str) -> int: + return 0 + + def flush(self) -> None: + pass + + def fileno(self) -> int: + return -1 + + +NULL_FILE = NullFile() diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rich/abc.py b/TTS/Kokoro/.venv/Lib/site-packages/rich/abc.py new file mode 100644 index 0000000000000000000000000000000000000000..42db7c00202962561f5dfdb295b2cab54d4868c7 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rich/abc.py @@ -0,0 +1,33 @@ +from abc import ABC + + +class RichRenderable(ABC): + """An abstract base class for Rich renderables. + + Note that there is no need to extend this class, the intended use is to check if an + object supports the Rich renderable protocol. For example:: + + if isinstance(my_object, RichRenderable): + console.print(my_object) + + """ + + @classmethod + def __subclasshook__(cls, other: type) -> bool: + """Check if this class supports the rich render protocol.""" + return hasattr(other, "__rich_console__") or hasattr(other, "__rich__") + + +if __name__ == "__main__": # pragma: no cover + from rich.text import Text + + t = Text() + print(isinstance(Text, RichRenderable)) + print(isinstance(t, RichRenderable)) + + class Foo: + pass + + f = Foo() + print(isinstance(f, RichRenderable)) + print(isinstance("", RichRenderable)) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rich/align.py b/TTS/Kokoro/.venv/Lib/site-packages/rich/align.py new file mode 100644 index 0000000000000000000000000000000000000000..2fa66b1ad3ceb923892aed0d43dcb141b3e3e7e7 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rich/align.py @@ -0,0 +1,320 @@ +from itertools import chain +from typing import TYPE_CHECKING, Iterable, Optional, Literal + +from .constrain import Constrain +from .jupyter import JupyterMixin +from .measure import Measurement +from .segment import Segment +from .style import StyleType + +if TYPE_CHECKING: + from .console import Console, ConsoleOptions, RenderableType, RenderResult + +AlignMethod = Literal["left", "center", "right"] +VerticalAlignMethod = Literal["top", "middle", "bottom"] + + +class Align(JupyterMixin): + """Align a renderable by adding spaces if necessary. + + Args: + renderable (RenderableType): A console renderable. + align (AlignMethod): One of "left", "center", or "right"" + style (StyleType, optional): An optional style to apply to the background. + vertical (Optional[VerticalAlignMethod], optional): Optional vertical align, one of "top", "middle", or "bottom". Defaults to None. + pad (bool, optional): Pad the right with spaces. Defaults to True. + width (int, optional): Restrict contents to given width, or None to use default width. Defaults to None. + height (int, optional): Set height of align renderable, or None to fit to contents. Defaults to None. + + Raises: + ValueError: if ``align`` is not one of the expected values. + + Example: + .. code-block:: python + + from rich.console import Console + from rich.align import Align + from rich.panel import Panel + + console = Console() + # Create a panel 20 characters wide + p = Panel("Hello, [b]World[/b]!", style="on green", width=20) + + # Renders the panel centered in the terminal + console.print(Align(p, align="center")) + """ + + def __init__( + self, + renderable: "RenderableType", + align: AlignMethod = "left", + style: Optional[StyleType] = None, + *, + vertical: Optional[VerticalAlignMethod] = None, + pad: bool = True, + width: Optional[int] = None, + height: Optional[int] = None, + ) -> None: + if align not in ("left", "center", "right"): + raise ValueError( + f'invalid value for align, expected "left", "center", or "right" (not {align!r})' + ) + if vertical is not None and vertical not in ("top", "middle", "bottom"): + raise ValueError( + f'invalid value for vertical, expected "top", "middle", or "bottom" (not {vertical!r})' + ) + self.renderable = renderable + self.align = align + self.style = style + self.vertical = vertical + self.pad = pad + self.width = width + self.height = height + + def __repr__(self) -> str: + return f"Align({self.renderable!r}, {self.align!r})" + + @classmethod + def left( + cls, + renderable: "RenderableType", + style: Optional[StyleType] = None, + *, + vertical: Optional[VerticalAlignMethod] = None, + pad: bool = True, + width: Optional[int] = None, + height: Optional[int] = None, + ) -> "Align": + """Align a renderable to the left.""" + return cls( + renderable, + "left", + style=style, + vertical=vertical, + pad=pad, + width=width, + height=height, + ) + + @classmethod + def center( + cls, + renderable: "RenderableType", + style: Optional[StyleType] = None, + *, + vertical: Optional[VerticalAlignMethod] = None, + pad: bool = True, + width: Optional[int] = None, + height: Optional[int] = None, + ) -> "Align": + """Align a renderable to the center.""" + return cls( + renderable, + "center", + style=style, + vertical=vertical, + pad=pad, + width=width, + height=height, + ) + + @classmethod + def right( + cls, + renderable: "RenderableType", + style: Optional[StyleType] = None, + *, + vertical: Optional[VerticalAlignMethod] = None, + pad: bool = True, + width: Optional[int] = None, + height: Optional[int] = None, + ) -> "Align": + """Align a renderable to the right.""" + return cls( + renderable, + "right", + style=style, + vertical=vertical, + pad=pad, + width=width, + height=height, + ) + + def __rich_console__( + self, console: "Console", options: "ConsoleOptions" + ) -> "RenderResult": + align = self.align + width = console.measure(self.renderable, options=options).maximum + rendered = console.render( + Constrain( + self.renderable, width if self.width is None else min(width, self.width) + ), + options.update(height=None), + ) + lines = list(Segment.split_lines(rendered)) + width, height = Segment.get_shape(lines) + lines = Segment.set_shape(lines, width, height) + new_line = Segment.line() + excess_space = options.max_width - width + style = console.get_style(self.style) if self.style is not None else None + + def generate_segments() -> Iterable[Segment]: + if excess_space <= 0: + # Exact fit + for line in lines: + yield from line + yield new_line + + elif align == "left": + # Pad on the right + pad = Segment(" " * excess_space, style) if self.pad else None + for line in lines: + yield from line + if pad: + yield pad + yield new_line + + elif align == "center": + # Pad left and right + left = excess_space // 2 + pad = Segment(" " * left, style) + pad_right = ( + Segment(" " * (excess_space - left), style) if self.pad else None + ) + for line in lines: + if left: + yield pad + yield from line + if pad_right: + yield pad_right + yield new_line + + elif align == "right": + # Padding on left + pad = Segment(" " * excess_space, style) + for line in lines: + yield pad + yield from line + yield new_line + + blank_line = ( + Segment(f"{' ' * (self.width or options.max_width)}\n", style) + if self.pad + else Segment("\n") + ) + + def blank_lines(count: int) -> Iterable[Segment]: + if count > 0: + for _ in range(count): + yield blank_line + + vertical_height = self.height or options.height + iter_segments: Iterable[Segment] + if self.vertical and vertical_height is not None: + if self.vertical == "top": + bottom_space = vertical_height - height + iter_segments = chain(generate_segments(), blank_lines(bottom_space)) + elif self.vertical == "middle": + top_space = (vertical_height - height) // 2 + bottom_space = vertical_height - top_space - height + iter_segments = chain( + blank_lines(top_space), + generate_segments(), + blank_lines(bottom_space), + ) + else: # self.vertical == "bottom": + top_space = vertical_height - height + iter_segments = chain(blank_lines(top_space), generate_segments()) + else: + iter_segments = generate_segments() + if self.style: + style = console.get_style(self.style) + iter_segments = Segment.apply_style(iter_segments, style) + yield from iter_segments + + def __rich_measure__( + self, console: "Console", options: "ConsoleOptions" + ) -> Measurement: + measurement = Measurement.get(console, options, self.renderable) + return measurement + + +class VerticalCenter(JupyterMixin): + """Vertically aligns a renderable. + + Warn: + This class is deprecated and may be removed in a future version. Use Align class with + `vertical="middle"`. + + Args: + renderable (RenderableType): A renderable object. + style (StyleType, optional): An optional style to apply to the background. Defaults to None. + """ + + def __init__( + self, + renderable: "RenderableType", + style: Optional[StyleType] = None, + ) -> None: + self.renderable = renderable + self.style = style + + def __repr__(self) -> str: + return f"VerticalCenter({self.renderable!r})" + + def __rich_console__( + self, console: "Console", options: "ConsoleOptions" + ) -> "RenderResult": + style = console.get_style(self.style) if self.style is not None else None + lines = console.render_lines( + self.renderable, options.update(height=None), pad=False + ) + width, _height = Segment.get_shape(lines) + new_line = Segment.line() + height = options.height or options.size.height + top_space = (height - len(lines)) // 2 + bottom_space = height - top_space - len(lines) + blank_line = Segment(f"{' ' * width}", style) + + def blank_lines(count: int) -> Iterable[Segment]: + for _ in range(count): + yield blank_line + yield new_line + + if top_space > 0: + yield from blank_lines(top_space) + for line in lines: + yield from line + yield new_line + if bottom_space > 0: + yield from blank_lines(bottom_space) + + def __rich_measure__( + self, console: "Console", options: "ConsoleOptions" + ) -> Measurement: + measurement = Measurement.get(console, options, self.renderable) + return measurement + + +if __name__ == "__main__": # pragma: no cover + from rich.console import Console, Group + from rich.highlighter import ReprHighlighter + from rich.panel import Panel + + highlighter = ReprHighlighter() + console = Console() + + panel = Panel( + Group( + Align.left(highlighter("align='left'")), + Align.center(highlighter("align='center'")), + Align.right(highlighter("align='right'")), + ), + width=60, + style="on dark_blue", + title="Align", + ) + + console.print( + Align.center(panel, vertical="middle", style="on red", height=console.height) + ) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rich/ansi.py b/TTS/Kokoro/.venv/Lib/site-packages/rich/ansi.py new file mode 100644 index 0000000000000000000000000000000000000000..7de86ce5043feeee4b6c28302cc1e72c2ad4cfe1 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rich/ansi.py @@ -0,0 +1,241 @@ +import re +import sys +from contextlib import suppress +from typing import Iterable, NamedTuple, Optional + +from .color import Color +from .style import Style +from .text import Text + +re_ansi = re.compile( + r""" +(?:\x1b[0-?])| +(?:\x1b\](.*?)\x1b\\)| +(?:\x1b([(@-Z\\-_]|\[[0-?]*[ -/]*[@-~])) +""", + re.VERBOSE, +) + + +class _AnsiToken(NamedTuple): + """Result of ansi tokenized string.""" + + plain: str = "" + sgr: Optional[str] = "" + osc: Optional[str] = "" + + +def _ansi_tokenize(ansi_text: str) -> Iterable[_AnsiToken]: + """Tokenize a string in to plain text and ANSI codes. + + Args: + ansi_text (str): A String containing ANSI codes. + + Yields: + AnsiToken: A named tuple of (plain, sgr, osc) + """ + + position = 0 + sgr: Optional[str] + osc: Optional[str] + for match in re_ansi.finditer(ansi_text): + start, end = match.span(0) + osc, sgr = match.groups() + if start > position: + yield _AnsiToken(ansi_text[position:start]) + if sgr: + if sgr == "(": + position = end + 1 + continue + if sgr.endswith("m"): + yield _AnsiToken("", sgr[1:-1], osc) + else: + yield _AnsiToken("", sgr, osc) + position = end + if position < len(ansi_text): + yield _AnsiToken(ansi_text[position:]) + + +SGR_STYLE_MAP = { + 1: "bold", + 2: "dim", + 3: "italic", + 4: "underline", + 5: "blink", + 6: "blink2", + 7: "reverse", + 8: "conceal", + 9: "strike", + 21: "underline2", + 22: "not dim not bold", + 23: "not italic", + 24: "not underline", + 25: "not blink", + 26: "not blink2", + 27: "not reverse", + 28: "not conceal", + 29: "not strike", + 30: "color(0)", + 31: "color(1)", + 32: "color(2)", + 33: "color(3)", + 34: "color(4)", + 35: "color(5)", + 36: "color(6)", + 37: "color(7)", + 39: "default", + 40: "on color(0)", + 41: "on color(1)", + 42: "on color(2)", + 43: "on color(3)", + 44: "on color(4)", + 45: "on color(5)", + 46: "on color(6)", + 47: "on color(7)", + 49: "on default", + 51: "frame", + 52: "encircle", + 53: "overline", + 54: "not frame not encircle", + 55: "not overline", + 90: "color(8)", + 91: "color(9)", + 92: "color(10)", + 93: "color(11)", + 94: "color(12)", + 95: "color(13)", + 96: "color(14)", + 97: "color(15)", + 100: "on color(8)", + 101: "on color(9)", + 102: "on color(10)", + 103: "on color(11)", + 104: "on color(12)", + 105: "on color(13)", + 106: "on color(14)", + 107: "on color(15)", +} + + +class AnsiDecoder: + """Translate ANSI code in to styled Text.""" + + def __init__(self) -> None: + self.style = Style.null() + + def decode(self, terminal_text: str) -> Iterable[Text]: + """Decode ANSI codes in an iterable of lines. + + Args: + lines (Iterable[str]): An iterable of lines of terminal output. + + Yields: + Text: Marked up Text. + """ + for line in terminal_text.splitlines(): + yield self.decode_line(line) + + def decode_line(self, line: str) -> Text: + """Decode a line containing ansi codes. + + Args: + line (str): A line of terminal output. + + Returns: + Text: A Text instance marked up according to ansi codes. + """ + from_ansi = Color.from_ansi + from_rgb = Color.from_rgb + _Style = Style + text = Text() + append = text.append + line = line.rsplit("\r", 1)[-1] + for plain_text, sgr, osc in _ansi_tokenize(line): + if plain_text: + append(plain_text, self.style or None) + elif osc is not None: + if osc.startswith("8;"): + _params, semicolon, link = osc[2:].partition(";") + if semicolon: + self.style = self.style.update_link(link or None) + elif sgr is not None: + # Translate in to semi-colon separated codes + # Ignore invalid codes, because we want to be lenient + codes = [ + min(255, int(_code) if _code else 0) + for _code in sgr.split(";") + if _code.isdigit() or _code == "" + ] + iter_codes = iter(codes) + for code in iter_codes: + if code == 0: + # reset + self.style = _Style.null() + elif code in SGR_STYLE_MAP: + # styles + self.style += _Style.parse(SGR_STYLE_MAP[code]) + elif code == 38: + #  Foreground + with suppress(StopIteration): + color_type = next(iter_codes) + if color_type == 5: + self.style += _Style.from_color( + from_ansi(next(iter_codes)) + ) + elif color_type == 2: + self.style += _Style.from_color( + from_rgb( + next(iter_codes), + next(iter_codes), + next(iter_codes), + ) + ) + elif code == 48: + # Background + with suppress(StopIteration): + color_type = next(iter_codes) + if color_type == 5: + self.style += _Style.from_color( + None, from_ansi(next(iter_codes)) + ) + elif color_type == 2: + self.style += _Style.from_color( + None, + from_rgb( + next(iter_codes), + next(iter_codes), + next(iter_codes), + ), + ) + + return text + + +if sys.platform != "win32" and __name__ == "__main__": # pragma: no cover + import io + import os + import pty + import sys + + decoder = AnsiDecoder() + + stdout = io.BytesIO() + + def read(fd: int) -> bytes: + data = os.read(fd, 1024) + stdout.write(data) + return data + + pty.spawn(sys.argv[1:], read) + + from .console import Console + + console = Console(record=True) + + stdout_result = stdout.getvalue().decode("utf-8") + print(stdout_result) + + for line in decoder.decode(stdout_result): + console.print(line) + + console.save_html("stdout.html") diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rich/bar.py b/TTS/Kokoro/.venv/Lib/site-packages/rich/bar.py new file mode 100644 index 0000000000000000000000000000000000000000..022284b57881d8b133aced5b5a843e6447bb4e0b --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rich/bar.py @@ -0,0 +1,93 @@ +from typing import Optional, Union + +from .color import Color +from .console import Console, ConsoleOptions, RenderResult +from .jupyter import JupyterMixin +from .measure import Measurement +from .segment import Segment +from .style import Style + +# There are left-aligned characters for 1/8 to 7/8, but +# the right-aligned characters exist only for 1/8 and 4/8. +BEGIN_BLOCK_ELEMENTS = ["█", "█", "█", "▐", "▐", "▐", "▕", "▕"] +END_BLOCK_ELEMENTS = [" ", "▏", "▎", "▍", "▌", "▋", "▊", "▉"] +FULL_BLOCK = "█" + + +class Bar(JupyterMixin): + """Renders a solid block bar. + + Args: + size (float): Value for the end of the bar. + begin (float): Begin point (between 0 and size, inclusive). + end (float): End point (between 0 and size, inclusive). + width (int, optional): Width of the bar, or ``None`` for maximum width. Defaults to None. + color (Union[Color, str], optional): Color of the bar. Defaults to "default". + bgcolor (Union[Color, str], optional): Color of bar background. Defaults to "default". + """ + + def __init__( + self, + size: float, + begin: float, + end: float, + *, + width: Optional[int] = None, + color: Union[Color, str] = "default", + bgcolor: Union[Color, str] = "default", + ): + self.size = size + self.begin = max(begin, 0) + self.end = min(end, size) + self.width = width + self.style = Style(color=color, bgcolor=bgcolor) + + def __repr__(self) -> str: + return f"Bar({self.size}, {self.begin}, {self.end})" + + def __rich_console__( + self, console: Console, options: ConsoleOptions + ) -> RenderResult: + width = min( + self.width if self.width is not None else options.max_width, + options.max_width, + ) + + if self.begin >= self.end: + yield Segment(" " * width, self.style) + yield Segment.line() + return + + prefix_complete_eights = int(width * 8 * self.begin / self.size) + prefix_bar_count = prefix_complete_eights // 8 + prefix_eights_count = prefix_complete_eights % 8 + + body_complete_eights = int(width * 8 * self.end / self.size) + body_bar_count = body_complete_eights // 8 + body_eights_count = body_complete_eights % 8 + + # When start and end fall into the same cell, we ideally should render + # a symbol that's "center-aligned", but there is no good symbol in Unicode. + # In this case, we fall back to right-aligned block symbol for simplicity. + + prefix = " " * prefix_bar_count + if prefix_eights_count: + prefix += BEGIN_BLOCK_ELEMENTS[prefix_eights_count] + + body = FULL_BLOCK * body_bar_count + if body_eights_count: + body += END_BLOCK_ELEMENTS[body_eights_count] + + suffix = " " * (width - len(body)) + + yield Segment(prefix + body[len(prefix) :] + suffix, self.style) + yield Segment.line() + + def __rich_measure__( + self, console: Console, options: ConsoleOptions + ) -> Measurement: + return ( + Measurement(self.width, self.width) + if self.width is not None + else Measurement(4, options.max_width) + ) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rich/box.py b/TTS/Kokoro/.venv/Lib/site-packages/rich/box.py new file mode 100644 index 0000000000000000000000000000000000000000..82555b61cd29efab220cf47b9fb3c26b80e8adde --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rich/box.py @@ -0,0 +1,474 @@ +from typing import TYPE_CHECKING, Iterable, List, Literal + + +from ._loop import loop_last + +if TYPE_CHECKING: + from rich.console import ConsoleOptions + + +class Box: + """Defines characters to render boxes. + + ┌─┬┐ top + │ ││ head + ├─┼┤ head_row + │ ││ mid + ├─┼┤ row + ├─┼┤ foot_row + │ ││ foot + └─┴┘ bottom + + Args: + box (str): Characters making up box. + ascii (bool, optional): True if this box uses ascii characters only. Default is False. + """ + + def __init__(self, box: str, *, ascii: bool = False) -> None: + self._box = box + self.ascii = ascii + line1, line2, line3, line4, line5, line6, line7, line8 = box.splitlines() + # top + self.top_left, self.top, self.top_divider, self.top_right = iter(line1) + # head + self.head_left, _, self.head_vertical, self.head_right = iter(line2) + # head_row + ( + self.head_row_left, + self.head_row_horizontal, + self.head_row_cross, + self.head_row_right, + ) = iter(line3) + + # mid + self.mid_left, _, self.mid_vertical, self.mid_right = iter(line4) + # row + self.row_left, self.row_horizontal, self.row_cross, self.row_right = iter(line5) + # foot_row + ( + self.foot_row_left, + self.foot_row_horizontal, + self.foot_row_cross, + self.foot_row_right, + ) = iter(line6) + # foot + self.foot_left, _, self.foot_vertical, self.foot_right = iter(line7) + # bottom + self.bottom_left, self.bottom, self.bottom_divider, self.bottom_right = iter( + line8 + ) + + def __repr__(self) -> str: + return "Box(...)" + + def __str__(self) -> str: + return self._box + + def substitute(self, options: "ConsoleOptions", safe: bool = True) -> "Box": + """Substitute this box for another if it won't render due to platform issues. + + Args: + options (ConsoleOptions): Console options used in rendering. + safe (bool, optional): Substitute this for another Box if there are known problems + displaying on the platform (currently only relevant on Windows). Default is True. + + Returns: + Box: A different Box or the same Box. + """ + box = self + if options.legacy_windows and safe: + box = LEGACY_WINDOWS_SUBSTITUTIONS.get(box, box) + if options.ascii_only and not box.ascii: + box = ASCII + return box + + def get_plain_headed_box(self) -> "Box": + """If this box uses special characters for the borders of the header, then + return the equivalent box that does not. + + Returns: + Box: The most similar Box that doesn't use header-specific box characters. + If the current Box already satisfies this criterion, then it's returned. + """ + return PLAIN_HEADED_SUBSTITUTIONS.get(self, self) + + def get_top(self, widths: Iterable[int]) -> str: + """Get the top of a simple box. + + Args: + widths (List[int]): Widths of columns. + + Returns: + str: A string of box characters. + """ + + parts: List[str] = [] + append = parts.append + append(self.top_left) + for last, width in loop_last(widths): + append(self.top * width) + if not last: + append(self.top_divider) + append(self.top_right) + return "".join(parts) + + def get_row( + self, + widths: Iterable[int], + level: Literal["head", "row", "foot", "mid"] = "row", + edge: bool = True, + ) -> str: + """Get the top of a simple box. + + Args: + width (List[int]): Widths of columns. + + Returns: + str: A string of box characters. + """ + if level == "head": + left = self.head_row_left + horizontal = self.head_row_horizontal + cross = self.head_row_cross + right = self.head_row_right + elif level == "row": + left = self.row_left + horizontal = self.row_horizontal + cross = self.row_cross + right = self.row_right + elif level == "mid": + left = self.mid_left + horizontal = " " + cross = self.mid_vertical + right = self.mid_right + elif level == "foot": + left = self.foot_row_left + horizontal = self.foot_row_horizontal + cross = self.foot_row_cross + right = self.foot_row_right + else: + raise ValueError("level must be 'head', 'row' or 'foot'") + + parts: List[str] = [] + append = parts.append + if edge: + append(left) + for last, width in loop_last(widths): + append(horizontal * width) + if not last: + append(cross) + if edge: + append(right) + return "".join(parts) + + def get_bottom(self, widths: Iterable[int]) -> str: + """Get the bottom of a simple box. + + Args: + widths (List[int]): Widths of columns. + + Returns: + str: A string of box characters. + """ + + parts: List[str] = [] + append = parts.append + append(self.bottom_left) + for last, width in loop_last(widths): + append(self.bottom * width) + if not last: + append(self.bottom_divider) + append(self.bottom_right) + return "".join(parts) + + +# fmt: off +ASCII: Box = Box( + "+--+\n" + "| ||\n" + "|-+|\n" + "| ||\n" + "|-+|\n" + "|-+|\n" + "| ||\n" + "+--+\n", + ascii=True, +) + +ASCII2: Box = Box( + "+-++\n" + "| ||\n" + "+-++\n" + "| ||\n" + "+-++\n" + "+-++\n" + "| ||\n" + "+-++\n", + ascii=True, +) + +ASCII_DOUBLE_HEAD: Box = Box( + "+-++\n" + "| ||\n" + "+=++\n" + "| ||\n" + "+-++\n" + "+-++\n" + "| ||\n" + "+-++\n", + ascii=True, +) + +SQUARE: Box = Box( + "┌─┬┐\n" + "│ ││\n" + "├─┼┤\n" + "│ ││\n" + "├─┼┤\n" + "├─┼┤\n" + "│ ││\n" + "└─┴┘\n" +) + +SQUARE_DOUBLE_HEAD: Box = Box( + "┌─┬┐\n" + "│ ││\n" + "╞═╪╡\n" + "│ ││\n" + "├─┼┤\n" + "├─┼┤\n" + "│ ││\n" + "└─┴┘\n" +) + +MINIMAL: Box = Box( + " ╷ \n" + " │ \n" + "╶─┼╴\n" + " │ \n" + "╶─┼╴\n" + "╶─┼╴\n" + " │ \n" + " ╵ \n" +) + + +MINIMAL_HEAVY_HEAD: Box = Box( + " ╷ \n" + " │ \n" + "╺━┿╸\n" + " │ \n" + "╶─┼╴\n" + "╶─┼╴\n" + " │ \n" + " ╵ \n" +) + +MINIMAL_DOUBLE_HEAD: Box = Box( + " ╷ \n" + " │ \n" + " ═╪ \n" + " │ \n" + " ─┼ \n" + " ─┼ \n" + " │ \n" + " ╵ \n" +) + + +SIMPLE: Box = Box( + " \n" + " \n" + " ── \n" + " \n" + " \n" + " ── \n" + " \n" + " \n" +) + +SIMPLE_HEAD: Box = Box( + " \n" + " \n" + " ── \n" + " \n" + " \n" + " \n" + " \n" + " \n" +) + + +SIMPLE_HEAVY: Box = Box( + " \n" + " \n" + " ━━ \n" + " \n" + " \n" + " ━━ \n" + " \n" + " \n" +) + + +HORIZONTALS: Box = Box( + " ── \n" + " \n" + " ── \n" + " \n" + " ── \n" + " ── \n" + " \n" + " ── \n" +) + +ROUNDED: Box = Box( + "╭─┬╮\n" + "│ ││\n" + "├─┼┤\n" + "│ ││\n" + "├─┼┤\n" + "├─┼┤\n" + "│ ││\n" + "╰─┴╯\n" +) + +HEAVY: Box = Box( + "┏━┳┓\n" + "┃ ┃┃\n" + "┣━╋┫\n" + "┃ ┃┃\n" + "┣━╋┫\n" + "┣━╋┫\n" + "┃ ┃┃\n" + "┗━┻┛\n" +) + +HEAVY_EDGE: Box = Box( + "┏━┯┓\n" + "┃ │┃\n" + "┠─┼┨\n" + "┃ │┃\n" + "┠─┼┨\n" + "┠─┼┨\n" + "┃ │┃\n" + "┗━┷┛\n" +) + +HEAVY_HEAD: Box = Box( + "┏━┳┓\n" + "┃ ┃┃\n" + "┡━╇┩\n" + "│ ││\n" + "├─┼┤\n" + "├─┼┤\n" + "│ ││\n" + "└─┴┘\n" +) + +DOUBLE: Box = Box( + "╔═╦╗\n" + "║ ║║\n" + "╠═╬╣\n" + "║ ║║\n" + "╠═╬╣\n" + "╠═╬╣\n" + "║ ║║\n" + "╚═╩╝\n" +) + +DOUBLE_EDGE: Box = Box( + "╔═╤╗\n" + "║ │║\n" + "╟─┼╢\n" + "║ │║\n" + "╟─┼╢\n" + "╟─┼╢\n" + "║ │║\n" + "╚═╧╝\n" +) + +MARKDOWN: Box = Box( + " \n" + "| ||\n" + "|-||\n" + "| ||\n" + "|-||\n" + "|-||\n" + "| ||\n" + " \n", + ascii=True, +) +# fmt: on + +# Map Boxes that don't render with raster fonts on to equivalent that do +LEGACY_WINDOWS_SUBSTITUTIONS = { + ROUNDED: SQUARE, + MINIMAL_HEAVY_HEAD: MINIMAL, + SIMPLE_HEAVY: SIMPLE, + HEAVY: SQUARE, + HEAVY_EDGE: SQUARE, + HEAVY_HEAD: SQUARE, +} + +# Map headed boxes to their headerless equivalents +PLAIN_HEADED_SUBSTITUTIONS = { + HEAVY_HEAD: SQUARE, + SQUARE_DOUBLE_HEAD: SQUARE, + MINIMAL_DOUBLE_HEAD: MINIMAL, + MINIMAL_HEAVY_HEAD: MINIMAL, + ASCII_DOUBLE_HEAD: ASCII2, +} + + +if __name__ == "__main__": # pragma: no cover + from rich.columns import Columns + from rich.panel import Panel + + from . import box as box + from .console import Console + from .table import Table + from .text import Text + + console = Console(record=True) + + BOXES = [ + "ASCII", + "ASCII2", + "ASCII_DOUBLE_HEAD", + "SQUARE", + "SQUARE_DOUBLE_HEAD", + "MINIMAL", + "MINIMAL_HEAVY_HEAD", + "MINIMAL_DOUBLE_HEAD", + "SIMPLE", + "SIMPLE_HEAD", + "SIMPLE_HEAVY", + "HORIZONTALS", + "ROUNDED", + "HEAVY", + "HEAVY_EDGE", + "HEAVY_HEAD", + "DOUBLE", + "DOUBLE_EDGE", + "MARKDOWN", + ] + + console.print(Panel("[bold green]Box Constants", style="green"), justify="center") + console.print() + + columns = Columns(expand=True, padding=2) + for box_name in sorted(BOXES): + table = Table( + show_footer=True, style="dim", border_style="not dim", expand=True + ) + table.add_column("Header 1", "Footer 1") + table.add_column("Header 2", "Footer 2") + table.add_row("Cell", "Cell") + table.add_row("Cell", "Cell") + table.box = getattr(box, box_name) + table.title = Text(f"box.{box_name}", style="magenta") + columns.add_renderable(table) + console.print(columns) + + # console.save_svg("box.svg") diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rich/cells.py b/TTS/Kokoro/.venv/Lib/site-packages/rich/cells.py new file mode 100644 index 0000000000000000000000000000000000000000..9d590b04e89b81a592f82ddd64aa5ccd50e36e9c --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rich/cells.py @@ -0,0 +1,352 @@ +from __future__ import annotations + +from functools import lru_cache +from operator import itemgetter +from typing import Callable, NamedTuple, Sequence, Tuple + +from rich._unicode_data import load as load_cell_table + +CellSpan = Tuple[int, int, int] + +_span_get_cell_len = itemgetter(2) + +# Ranges of unicode ordinals that produce a 1-cell wide character +# This is non-exhaustive, but covers most common Western characters +_SINGLE_CELL_UNICODE_RANGES: list[tuple[int, int]] = [ + (0x20, 0x7E), # Latin (excluding non-printable) + (0xA0, 0xAC), + (0xAE, 0x002FF), + (0x00370, 0x00482), # Greek / Cyrillic + (0x02500, 0x025FC), # Box drawing, box elements, geometric shapes + (0x02800, 0x028FF), # Braille +] + +# A frozen set of characters that are a single cell wide +_SINGLE_CELLS = frozenset( + [ + character + for _start, _end in _SINGLE_CELL_UNICODE_RANGES + for character in map(chr, range(_start, _end + 1)) + ] +) + +# When called with a string this will return True if all +# characters are single-cell, otherwise False +_is_single_cell_widths: Callable[[str], bool] = _SINGLE_CELLS.issuperset + + +class CellTable(NamedTuple): + """Contains unicode data required to measure the cell widths of glyphs.""" + + unicode_version: str + widths: Sequence[tuple[int, int, int]] + narrow_to_wide: frozenset[str] + + +@lru_cache(maxsize=4096) +def get_character_cell_size(character: str, unicode_version: str = "auto") -> int: + """Get the cell size of a character. + + Args: + character (str): A single character. + unicode_version: Unicode version, `"auto"` to auto detect, `"latest"` for the latest unicode version. + + Returns: + int: Number of cells (0, 1 or 2) occupied by that character. + """ + codepoint = ord(character) + if codepoint and codepoint < 32 or 0x07F <= codepoint < 0x0A0: + return 0 + table = load_cell_table(unicode_version).widths + + last_entry = table[-1] + if codepoint > last_entry[1]: + return 1 + + lower_bound = 0 + upper_bound = len(table) - 1 + + while lower_bound <= upper_bound: + index = (lower_bound + upper_bound) >> 1 + start, end, width = table[index] + if codepoint < start: + upper_bound = index - 1 + elif codepoint > end: + lower_bound = index + 1 + else: + return width + return 1 + + +@lru_cache(4096) +def cached_cell_len(text: str, unicode_version: str = "auto") -> int: + """Get the number of cells required to display text. + + This method always caches, which may use up a lot of memory. It is recommended to use + `cell_len` over this method. + + Args: + text (str): Text to display. + unicode_version: Unicode version, `"auto"` to auto detect, `"latest"` for the latest unicode version. + + Returns: + int: Get the number of cells required to display text. + """ + return _cell_len(text, unicode_version) + + +def cell_len(text: str, unicode_version: str = "auto") -> int: + """Get the cell length of a string (length as it appears in the terminal). + + Args: + text: String to measure. + unicode_version: Unicode version, `"auto"` to auto detect, `"latest"` for the latest unicode version. + + Returns: + Length of string in terminal cells. + """ + if len(text) < 512: + return cached_cell_len(text, unicode_version) + return _cell_len(text, unicode_version) + + +def _cell_len(text: str, unicode_version: str) -> int: + """Get the cell length of a string (length as it appears in the terminal). + + Args: + text: String to measure. + unicode_version: Unicode version, `"auto"` to auto detect, `"latest"` for the latest unicode version. + + Returns: + Length of string in terminal cells. + """ + + if _is_single_cell_widths(text): + return len(text) + + # "\u200d" is zero width joiner + # "\ufe0f" is variation selector 16 + if "\u200d" not in text and "\ufe0f" not in text: + # Simplest case with no unicode stuff that changes the size + return sum( + get_character_cell_size(character, unicode_version) for character in text + ) + + cell_table = load_cell_table(unicode_version) + total_width = 0 + last_measured_character: str | None = None + + SPECIAL = {"\u200d", "\ufe0f"} + + index = 0 + character_count = len(text) + + while index < character_count: + character = text[index] + if character in SPECIAL: + if character == "\u200d": + index += 1 + elif last_measured_character: + total_width += last_measured_character in cell_table.narrow_to_wide + last_measured_character = None + else: + if character_width := get_character_cell_size(character, unicode_version): + last_measured_character = character + total_width += character_width + index += 1 + + return total_width + + +def split_graphemes( + text: str, unicode_version: str = "auto" +) -> "tuple[list[CellSpan], int]": + """Divide text into spans that define a single grapheme, and additionally return the cell length of the whole string. + + The returned spans will cover every index in the string, with no gaps. It is possible for some graphemes to have a cell length of zero. + This can occur for nonsense strings like two zero width joiners, or for control codes that don't contribute to the grapheme size. + + Args: + text: String to split. + unicode_version: Unicode version, `"auto"` to auto detect, `"latest"` for the latest unicode version. + + Returns: + A tuple of a list of *spans* and the cell length of the entire string. A span is a list of tuples + of three values consisting of (, , ), where START and END are string indices, + and CELL LENGTH is the cell length of the single grapheme. + """ + + cell_table = load_cell_table(unicode_version) + codepoint_count = len(text) + index = 0 + last_measured_character: str | None = None + + total_width = 0 + spans: list[tuple[int, int, int]] = [] + SPECIAL = {"\u200d", "\ufe0f"} + while index < codepoint_count: + if (character := text[index]) in SPECIAL: + if not spans: + # ZWJ or variation selector at the beginning of the string doesn't really make sense. + # But handle it, we must. + spans.append((index, index := index + 1, 0)) + continue + if character == "\u200d": + # zero width joiner + # The condition handles the case where a ZWJ is at the end of the string, and has nothing to join + index += 2 if index < (codepoint_count - 1) else 1 + start, _end, cell_length = spans[-1] + spans[-1] = (start, index, cell_length) + else: + # variation selector 16 + index += 1 + if last_measured_character: + start, _end, cell_length = spans[-1] + if last_measured_character in cell_table.narrow_to_wide: + last_measured_character = None + cell_length += 1 + total_width += 1 + spans[-1] = (start, index, cell_length) + else: + # No previous character to change the size of. + # Shouldn't occur in practice. + # But handle it, we must. + start, _end, cell_length = spans[-1] + spans[-1] = (start, index, cell_length) + continue + + if character_width := get_character_cell_size(character, unicode_version): + last_measured_character = character + spans.append((index, index := index + 1, character_width)) + total_width += character_width + else: + # Character has zero width + if spans: + # zero width characters are associated with the previous character + start, _end, cell_length = spans[-1] + spans[-1] = (start, index := index + 1, cell_length) + else: + # A zero width character with no prior spans + spans.append((index, index := index + 1, 0)) + + return (spans, total_width) + + +def _split_text( + text: str, cell_position: int, unicode_version: str = "auto" +) -> tuple[str, str]: + """Split text by cell position. + + If the cell position falls within a double width character, it is converted to two spaces. + + Args: + text: Text to split. + cell_position Offset in cells. + unicode_version: Unicode version, `"auto"` to auto detect, `"latest"` for the latest unicode version. + + Returns: + Tuple to two split strings. + """ + if cell_position <= 0: + return "", text + + spans, cell_length = split_graphemes(text, unicode_version) + + # Guess initial offset + offset = int((cell_position / cell_length) * len(spans)) + left_size = sum(map(_span_get_cell_len, spans[:offset])) + + while True: + if left_size == cell_position: + if offset >= len(spans): + return text, "" + split_index = spans[offset][0] + return text[:split_index], text[split_index:] + if left_size < cell_position: + start, end, cell_size = spans[offset] + if left_size + cell_size > cell_position: + return text[:start] + " ", " " + text[end:] + offset += 1 + left_size += cell_size + else: # left_size > cell_position + start, end, cell_size = spans[offset - 1] + if left_size - cell_size < cell_position: + return text[:start] + " ", " " + text[end:] + offset -= 1 + left_size -= cell_size + + +def split_text( + text: str, cell_position: int, unicode_version: str = "auto" +) -> tuple[str, str]: + """Split text by cell position. + + If the cell position falls within a double width character, it is converted to two spaces. + + Args: + text: Text to split. + cell_position Offset in cells. + unicode_version: Unicode version, `"auto"` to auto detect, `"latest"` for the latest unicode version. + + Returns: + Tuple to two split strings. + """ + if _is_single_cell_widths(text): + return text[:cell_position], text[cell_position:] + return _split_text(text, cell_position, unicode_version) + + +def set_cell_size(text: str, total: int, unicode_version: str = "auto") -> str: + """Adjust a string by cropping or padding with spaces such that it fits within the given number of cells. + + Args: + text: String to adjust. + total: Desired size in cells. + unicode_version: Unicode version. + + Returns: + A string with cell size equal to total. + """ + if _is_single_cell_widths(text): + size = len(text) + if size < total: + return text + " " * (total - size) + return text[:total] + if total <= 0: + return "" + cell_size = cell_len(text) + if cell_size == total: + return text + if cell_size < total: + return text + " " * (total - cell_size) + text, _ = _split_text(text, total, unicode_version) + return text + + +def chop_cells(text: str, width: int, unicode_version: str = "auto") -> list[str]: + """Split text into lines such that each line fits within the available (cell) width. + + Args: + text: The text to fold such that it fits in the given width. + width: The width available (number of cells). + + Returns: + A list of strings such that each string in the list has cell width + less than or equal to the available width. + """ + if _is_single_cell_widths(text): + return [text[index : index + width] for index in range(0, len(text), width)] + spans, _ = split_graphemes(text, unicode_version) + line_size = 0 # Size of line in cells + lines: list[str] = [] + line_offset = 0 # Offset (in codepoints) of start of line + for start, end, cell_size in spans: + if line_size + cell_size > width: + lines.append(text[line_offset:start]) + line_offset = start + line_size = 0 + line_size += cell_size + if line_size: + lines.append(text[line_offset:]) + + return lines diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rich/color.py b/TTS/Kokoro/.venv/Lib/site-packages/rich/color.py new file mode 100644 index 0000000000000000000000000000000000000000..e2c23a6a91b833fd9bb20bd5238421a5c0f08df3 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rich/color.py @@ -0,0 +1,621 @@ +import re +import sys +from colorsys import rgb_to_hls +from enum import IntEnum +from functools import lru_cache +from typing import TYPE_CHECKING, NamedTuple, Optional, Tuple + +from ._palettes import EIGHT_BIT_PALETTE, STANDARD_PALETTE, WINDOWS_PALETTE +from .color_triplet import ColorTriplet +from .repr import Result, rich_repr +from .terminal_theme import DEFAULT_TERMINAL_THEME + +if TYPE_CHECKING: # pragma: no cover + from .terminal_theme import TerminalTheme + from .text import Text + + +WINDOWS = sys.platform == "win32" + + +class ColorSystem(IntEnum): + """One of the 3 color system supported by terminals.""" + + STANDARD = 1 + EIGHT_BIT = 2 + TRUECOLOR = 3 + WINDOWS = 4 + + def __repr__(self) -> str: + return f"ColorSystem.{self.name}" + + def __str__(self) -> str: + return repr(self) + + +class ColorType(IntEnum): + """Type of color stored in Color class.""" + + DEFAULT = 0 + STANDARD = 1 + EIGHT_BIT = 2 + TRUECOLOR = 3 + WINDOWS = 4 + + def __repr__(self) -> str: + return f"ColorType.{self.name}" + + +ANSI_COLOR_NAMES = { + "black": 0, + "red": 1, + "green": 2, + "yellow": 3, + "blue": 4, + "magenta": 5, + "cyan": 6, + "white": 7, + "bright_black": 8, + "bright_red": 9, + "bright_green": 10, + "bright_yellow": 11, + "bright_blue": 12, + "bright_magenta": 13, + "bright_cyan": 14, + "bright_white": 15, + "grey0": 16, + "gray0": 16, + "navy_blue": 17, + "dark_blue": 18, + "blue3": 20, + "blue1": 21, + "dark_green": 22, + "deep_sky_blue4": 25, + "dodger_blue3": 26, + "dodger_blue2": 27, + "green4": 28, + "spring_green4": 29, + "turquoise4": 30, + "deep_sky_blue3": 32, + "dodger_blue1": 33, + "green3": 40, + "spring_green3": 41, + "dark_cyan": 36, + "light_sea_green": 37, + "deep_sky_blue2": 38, + "deep_sky_blue1": 39, + "spring_green2": 47, + "cyan3": 43, + "dark_turquoise": 44, + "turquoise2": 45, + "green1": 46, + "spring_green1": 48, + "medium_spring_green": 49, + "cyan2": 50, + "cyan1": 51, + "dark_red": 88, + "deep_pink4": 125, + "purple4": 55, + "purple3": 56, + "blue_violet": 57, + "orange4": 94, + "grey37": 59, + "gray37": 59, + "medium_purple4": 60, + "slate_blue3": 62, + "royal_blue1": 63, + "chartreuse4": 64, + "dark_sea_green4": 71, + "pale_turquoise4": 66, + "steel_blue": 67, + "steel_blue3": 68, + "cornflower_blue": 69, + "chartreuse3": 76, + "cadet_blue": 73, + "sky_blue3": 74, + "steel_blue1": 81, + "pale_green3": 114, + "sea_green3": 78, + "aquamarine3": 79, + "medium_turquoise": 80, + "chartreuse2": 112, + "sea_green2": 83, + "sea_green1": 85, + "aquamarine1": 122, + "dark_slate_gray2": 87, + "dark_magenta": 91, + "dark_violet": 128, + "purple": 129, + "light_pink4": 95, + "plum4": 96, + "medium_purple3": 98, + "slate_blue1": 99, + "yellow4": 106, + "wheat4": 101, + "grey53": 102, + "gray53": 102, + "light_slate_grey": 103, + "light_slate_gray": 103, + "medium_purple": 104, + "light_slate_blue": 105, + "dark_olive_green3": 149, + "dark_sea_green": 108, + "light_sky_blue3": 110, + "sky_blue2": 111, + "dark_sea_green3": 150, + "dark_slate_gray3": 116, + "sky_blue1": 117, + "chartreuse1": 118, + "light_green": 120, + "pale_green1": 156, + "dark_slate_gray1": 123, + "red3": 160, + "medium_violet_red": 126, + "magenta3": 164, + "dark_orange3": 166, + "indian_red": 167, + "hot_pink3": 168, + "medium_orchid3": 133, + "medium_orchid": 134, + "medium_purple2": 140, + "dark_goldenrod": 136, + "light_salmon3": 173, + "rosy_brown": 138, + "grey63": 139, + "gray63": 139, + "medium_purple1": 141, + "gold3": 178, + "dark_khaki": 143, + "navajo_white3": 144, + "grey69": 145, + "gray69": 145, + "light_steel_blue3": 146, + "light_steel_blue": 147, + "yellow3": 184, + "dark_sea_green2": 157, + "light_cyan3": 152, + "light_sky_blue1": 153, + "green_yellow": 154, + "dark_olive_green2": 155, + "dark_sea_green1": 193, + "pale_turquoise1": 159, + "deep_pink3": 162, + "magenta2": 200, + "hot_pink2": 169, + "orchid": 170, + "medium_orchid1": 207, + "orange3": 172, + "light_pink3": 174, + "pink3": 175, + "plum3": 176, + "violet": 177, + "light_goldenrod3": 179, + "tan": 180, + "misty_rose3": 181, + "thistle3": 182, + "plum2": 183, + "khaki3": 185, + "light_goldenrod2": 222, + "light_yellow3": 187, + "grey84": 188, + "gray84": 188, + "light_steel_blue1": 189, + "yellow2": 190, + "dark_olive_green1": 192, + "honeydew2": 194, + "light_cyan1": 195, + "red1": 196, + "deep_pink2": 197, + "deep_pink1": 199, + "magenta1": 201, + "orange_red1": 202, + "indian_red1": 204, + "hot_pink": 206, + "dark_orange": 208, + "salmon1": 209, + "light_coral": 210, + "pale_violet_red1": 211, + "orchid2": 212, + "orchid1": 213, + "orange1": 214, + "sandy_brown": 215, + "light_salmon1": 216, + "light_pink1": 217, + "pink1": 218, + "plum1": 219, + "gold1": 220, + "navajo_white1": 223, + "misty_rose1": 224, + "thistle1": 225, + "yellow1": 226, + "light_goldenrod1": 227, + "khaki1": 228, + "wheat1": 229, + "cornsilk1": 230, + "grey100": 231, + "gray100": 231, + "grey3": 232, + "gray3": 232, + "grey7": 233, + "gray7": 233, + "grey11": 234, + "gray11": 234, + "grey15": 235, + "gray15": 235, + "grey19": 236, + "gray19": 236, + "grey23": 237, + "gray23": 237, + "grey27": 238, + "gray27": 238, + "grey30": 239, + "gray30": 239, + "grey35": 240, + "gray35": 240, + "grey39": 241, + "gray39": 241, + "grey42": 242, + "gray42": 242, + "grey46": 243, + "gray46": 243, + "grey50": 244, + "gray50": 244, + "grey54": 245, + "gray54": 245, + "grey58": 246, + "gray58": 246, + "grey62": 247, + "gray62": 247, + "grey66": 248, + "gray66": 248, + "grey70": 249, + "gray70": 249, + "grey74": 250, + "gray74": 250, + "grey78": 251, + "gray78": 251, + "grey82": 252, + "gray82": 252, + "grey85": 253, + "gray85": 253, + "grey89": 254, + "gray89": 254, + "grey93": 255, + "gray93": 255, +} + + +class ColorParseError(Exception): + """The color could not be parsed.""" + + +RE_COLOR = re.compile( + r"""^ +\#([0-9a-f]{6})$| +color\(([0-9]{1,3})\)$| +rgb\(([\d\s,]+)\)$ +""", + re.VERBOSE, +) + + +@rich_repr +class Color(NamedTuple): + """Terminal color definition.""" + + name: str + """The name of the color (typically the input to Color.parse).""" + type: ColorType + """The type of the color.""" + number: Optional[int] = None + """The color number, if a standard color, or None.""" + triplet: Optional[ColorTriplet] = None + """A triplet of color components, if an RGB color.""" + + def __rich__(self) -> "Text": + """Displays the actual color if Rich printed.""" + from .style import Style + from .text import Text + + return Text.assemble( + f"", + ) + + def __rich_repr__(self) -> Result: + yield self.name + yield self.type + yield "number", self.number, None + yield "triplet", self.triplet, None + + @property + def system(self) -> ColorSystem: + """Get the native color system for this color.""" + if self.type == ColorType.DEFAULT: + return ColorSystem.STANDARD + return ColorSystem(int(self.type)) + + @property + def is_system_defined(self) -> bool: + """Check if the color is ultimately defined by the system.""" + return self.system not in (ColorSystem.EIGHT_BIT, ColorSystem.TRUECOLOR) + + @property + def is_default(self) -> bool: + """Check if the color is a default color.""" + return self.type == ColorType.DEFAULT + + def get_truecolor( + self, theme: Optional["TerminalTheme"] = None, foreground: bool = True + ) -> ColorTriplet: + """Get an equivalent color triplet for this color. + + Args: + theme (TerminalTheme, optional): Optional terminal theme, or None to use default. Defaults to None. + foreground (bool, optional): True for a foreground color, or False for background. Defaults to True. + + Returns: + ColorTriplet: A color triplet containing RGB components. + """ + + if theme is None: + theme = DEFAULT_TERMINAL_THEME + if self.type == ColorType.TRUECOLOR: + assert self.triplet is not None + return self.triplet + elif self.type == ColorType.EIGHT_BIT: + assert self.number is not None + return EIGHT_BIT_PALETTE[self.number] + elif self.type == ColorType.STANDARD: + assert self.number is not None + return theme.ansi_colors[self.number] + elif self.type == ColorType.WINDOWS: + assert self.number is not None + return WINDOWS_PALETTE[self.number] + else: # self.type == ColorType.DEFAULT: + assert self.number is None + return theme.foreground_color if foreground else theme.background_color + + @classmethod + def from_ansi(cls, number: int) -> "Color": + """Create a Color number from it's 8-bit ansi number. + + Args: + number (int): A number between 0-255 inclusive. + + Returns: + Color: A new Color instance. + """ + return cls( + name=f"color({number})", + type=(ColorType.STANDARD if number < 16 else ColorType.EIGHT_BIT), + number=number, + ) + + @classmethod + def from_triplet(cls, triplet: "ColorTriplet") -> "Color": + """Create a truecolor RGB color from a triplet of values. + + Args: + triplet (ColorTriplet): A color triplet containing red, green and blue components. + + Returns: + Color: A new color object. + """ + return cls(name=triplet.hex, type=ColorType.TRUECOLOR, triplet=triplet) + + @classmethod + def from_rgb(cls, red: float, green: float, blue: float) -> "Color": + """Create a truecolor from three color components in the range(0->255). + + Args: + red (float): Red component in range 0-255. + green (float): Green component in range 0-255. + blue (float): Blue component in range 0-255. + + Returns: + Color: A new color object. + """ + return cls.from_triplet(ColorTriplet(int(red), int(green), int(blue))) + + @classmethod + def default(cls) -> "Color": + """Get a Color instance representing the default color. + + Returns: + Color: Default color. + """ + return cls(name="default", type=ColorType.DEFAULT) + + @classmethod + @lru_cache(maxsize=1024) + def parse(cls, color: str) -> "Color": + """Parse a color definition.""" + original_color = color + color = color.lower().strip() + + if color == "default": + return cls(color, type=ColorType.DEFAULT) + + color_number = ANSI_COLOR_NAMES.get(color) + if color_number is not None: + return cls( + color, + type=(ColorType.STANDARD if color_number < 16 else ColorType.EIGHT_BIT), + number=color_number, + ) + + color_match = RE_COLOR.match(color) + if color_match is None: + raise ColorParseError(f"{original_color!r} is not a valid color") + + color_24, color_8, color_rgb = color_match.groups() + if color_24: + triplet = ColorTriplet( + int(color_24[0:2], 16), int(color_24[2:4], 16), int(color_24[4:6], 16) + ) + return cls(color, ColorType.TRUECOLOR, triplet=triplet) + + elif color_8: + number = int(color_8) + if number > 255: + raise ColorParseError(f"color number must be <= 255 in {color!r}") + return cls( + color, + type=(ColorType.STANDARD if number < 16 else ColorType.EIGHT_BIT), + number=number, + ) + + else: # color_rgb: + components = color_rgb.split(",") + if len(components) != 3: + raise ColorParseError( + f"expected three components in {original_color!r}" + ) + red, green, blue = components + triplet = ColorTriplet(int(red), int(green), int(blue)) + if not all(component <= 255 for component in triplet): + raise ColorParseError( + f"color components must be <= 255 in {original_color!r}" + ) + return cls(color, ColorType.TRUECOLOR, triplet=triplet) + + @lru_cache(maxsize=1024) + def get_ansi_codes(self, foreground: bool = True) -> Tuple[str, ...]: + """Get the ANSI escape codes for this color.""" + _type = self.type + if _type == ColorType.DEFAULT: + return ("39" if foreground else "49",) + + elif _type == ColorType.WINDOWS: + number = self.number + assert number is not None + fore, back = (30, 40) if number < 8 else (82, 92) + return (str(fore + number if foreground else back + number),) + + elif _type == ColorType.STANDARD: + number = self.number + assert number is not None + fore, back = (30, 40) if number < 8 else (82, 92) + return (str(fore + number if foreground else back + number),) + + elif _type == ColorType.EIGHT_BIT: + assert self.number is not None + return ("38" if foreground else "48", "5", str(self.number)) + + else: # self.standard == ColorStandard.TRUECOLOR: + assert self.triplet is not None + red, green, blue = self.triplet + return ("38" if foreground else "48", "2", str(red), str(green), str(blue)) + + @lru_cache(maxsize=1024) + def downgrade(self, system: ColorSystem) -> "Color": + """Downgrade a color system to a system with fewer colors.""" + + if self.type in (ColorType.DEFAULT, system): + return self + # Convert to 8-bit color from truecolor color + if system == ColorSystem.EIGHT_BIT and self.system == ColorSystem.TRUECOLOR: + assert self.triplet is not None + _h, l, s = rgb_to_hls(*self.triplet.normalized) + # If saturation is under 15% assume it is grayscale + if s < 0.15: + gray = round(l * 25.0) + if gray == 0: + color_number = 16 + elif gray == 25: + color_number = 231 + else: + color_number = 231 + gray + return Color(self.name, ColorType.EIGHT_BIT, number=color_number) + + red, green, blue = self.triplet + six_red = red / 95 if red < 95 else 1 + (red - 95) / 40 + six_green = green / 95 if green < 95 else 1 + (green - 95) / 40 + six_blue = blue / 95 if blue < 95 else 1 + (blue - 95) / 40 + + color_number = ( + 16 + 36 * round(six_red) + 6 * round(six_green) + round(six_blue) + ) + return Color(self.name, ColorType.EIGHT_BIT, number=color_number) + + # Convert to standard from truecolor or 8-bit + elif system == ColorSystem.STANDARD: + if self.system == ColorSystem.TRUECOLOR: + assert self.triplet is not None + triplet = self.triplet + else: # self.system == ColorSystem.EIGHT_BIT + assert self.number is not None + triplet = ColorTriplet(*EIGHT_BIT_PALETTE[self.number]) + + color_number = STANDARD_PALETTE.match(triplet) + return Color(self.name, ColorType.STANDARD, number=color_number) + + elif system == ColorSystem.WINDOWS: + if self.system == ColorSystem.TRUECOLOR: + assert self.triplet is not None + triplet = self.triplet + else: # self.system == ColorSystem.EIGHT_BIT + assert self.number is not None + if self.number < 16: + return Color(self.name, ColorType.WINDOWS, number=self.number) + triplet = ColorTriplet(*EIGHT_BIT_PALETTE[self.number]) + + color_number = WINDOWS_PALETTE.match(triplet) + return Color(self.name, ColorType.WINDOWS, number=color_number) + + return self + + +def parse_rgb_hex(hex_color: str) -> ColorTriplet: + """Parse six hex characters in to RGB triplet.""" + assert len(hex_color) == 6, "must be 6 characters" + color = ColorTriplet( + int(hex_color[0:2], 16), int(hex_color[2:4], 16), int(hex_color[4:6], 16) + ) + return color + + +def blend_rgb( + color1: ColorTriplet, color2: ColorTriplet, cross_fade: float = 0.5 +) -> ColorTriplet: + """Blend one RGB color in to another.""" + r1, g1, b1 = color1 + r2, g2, b2 = color2 + new_color = ColorTriplet( + int(r1 + (r2 - r1) * cross_fade), + int(g1 + (g2 - g1) * cross_fade), + int(b1 + (b2 - b1) * cross_fade), + ) + return new_color + + +if __name__ == "__main__": # pragma: no cover + from .console import Console + from .table import Table + from .text import Text + + console = Console() + + table = Table(show_footer=False, show_edge=True) + table.add_column("Color", width=10, overflow="ellipsis") + table.add_column("Number", justify="right", style="yellow") + table.add_column("Name", style="green") + table.add_column("Hex", style="blue") + table.add_column("RGB", style="magenta") + + colors = sorted((v, k) for k, v in ANSI_COLOR_NAMES.items()) + for color_number, name in colors: + if "grey" in name: + continue + color_cell = Text(" " * 10, style=f"on {name}") + if color_number < 16: + table.add_row(color_cell, f"{color_number}", Text(f'"{name}"')) + else: + color = EIGHT_BIT_PALETTE[color_number] # type: ignore[has-type] + table.add_row( + color_cell, str(color_number), Text(f'"{name}"'), color.hex, color.rgb + ) + + console.print(table) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rich/color_triplet.py b/TTS/Kokoro/.venv/Lib/site-packages/rich/color_triplet.py new file mode 100644 index 0000000000000000000000000000000000000000..02cab328251af9bfa809981aaa44933c407e2cd7 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rich/color_triplet.py @@ -0,0 +1,38 @@ +from typing import NamedTuple, Tuple + + +class ColorTriplet(NamedTuple): + """The red, green, and blue components of a color.""" + + red: int + """Red component in 0 to 255 range.""" + green: int + """Green component in 0 to 255 range.""" + blue: int + """Blue component in 0 to 255 range.""" + + @property + def hex(self) -> str: + """get the color triplet in CSS style.""" + red, green, blue = self + return f"#{red:02x}{green:02x}{blue:02x}" + + @property + def rgb(self) -> str: + """The color in RGB format. + + Returns: + str: An rgb color, e.g. ``"rgb(100,23,255)"``. + """ + red, green, blue = self + return f"rgb({red},{green},{blue})" + + @property + def normalized(self) -> Tuple[float, float, float]: + """Convert components into floats between 0 and 1. + + Returns: + Tuple[float, float, float]: A tuple of three normalized colour components. + """ + red, green, blue = self + return red / 255.0, green / 255.0, blue / 255.0 diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rich/columns.py b/TTS/Kokoro/.venv/Lib/site-packages/rich/columns.py new file mode 100644 index 0000000000000000000000000000000000000000..669a3a7074f9a9e1af29cb4bc78b05851df67959 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rich/columns.py @@ -0,0 +1,187 @@ +from collections import defaultdict +from itertools import chain +from operator import itemgetter +from typing import Dict, Iterable, List, Optional, Tuple + +from .align import Align, AlignMethod +from .console import Console, ConsoleOptions, RenderableType, RenderResult +from .constrain import Constrain +from .measure import Measurement +from .padding import Padding, PaddingDimensions +from .table import Table +from .text import TextType +from .jupyter import JupyterMixin + + +class Columns(JupyterMixin): + """Display renderables in neat columns. + + Args: + renderables (Iterable[RenderableType]): Any number of Rich renderables (including str). + width (int, optional): The desired width of the columns, or None to auto detect. Defaults to None. + padding (PaddingDimensions, optional): Optional padding around cells. Defaults to (0, 1). + expand (bool, optional): Expand columns to full width. Defaults to False. + equal (bool, optional): Arrange in to equal sized columns. Defaults to False. + column_first (bool, optional): Align items from top to bottom (rather than left to right). Defaults to False. + right_to_left (bool, optional): Start column from right hand side. Defaults to False. + align (str, optional): Align value ("left", "right", or "center") or None for default. Defaults to None. + title (TextType, optional): Optional title for Columns. + """ + + def __init__( + self, + renderables: Optional[Iterable[RenderableType]] = None, + padding: PaddingDimensions = (0, 1), + *, + width: Optional[int] = None, + expand: bool = False, + equal: bool = False, + column_first: bool = False, + right_to_left: bool = False, + align: Optional[AlignMethod] = None, + title: Optional[TextType] = None, + ) -> None: + self.renderables = list(renderables or []) + self.width = width + self.padding = padding + self.expand = expand + self.equal = equal + self.column_first = column_first + self.right_to_left = right_to_left + self.align: Optional[AlignMethod] = align + self.title = title + + def add_renderable(self, renderable: RenderableType) -> None: + """Add a renderable to the columns. + + Args: + renderable (RenderableType): Any renderable object. + """ + self.renderables.append(renderable) + + def __rich_console__( + self, console: Console, options: ConsoleOptions + ) -> RenderResult: + render_str = console.render_str + renderables = [ + render_str(renderable) if isinstance(renderable, str) else renderable + for renderable in self.renderables + ] + if not renderables: + return + _top, right, _bottom, left = Padding.unpack(self.padding) + width_padding = max(left, right) + max_width = options.max_width + widths: Dict[int, int] = defaultdict(int) + column_count = len(renderables) + + get_measurement = Measurement.get + renderable_widths = [ + get_measurement(console, options, renderable).maximum + for renderable in renderables + ] + if self.equal: + renderable_widths = [max(renderable_widths)] * len(renderable_widths) + + def iter_renderables( + column_count: int, + ) -> Iterable[Tuple[int, Optional[RenderableType]]]: + item_count = len(renderables) + if self.column_first: + width_renderables = list(zip(renderable_widths, renderables)) + + column_lengths: List[int] = [item_count // column_count] * column_count + for col_no in range(item_count % column_count): + column_lengths[col_no] += 1 + + row_count = (item_count + column_count - 1) // column_count + cells = [[-1] * column_count for _ in range(row_count)] + row = col = 0 + for index in range(item_count): + cells[row][col] = index + column_lengths[col] -= 1 + if column_lengths[col]: + row += 1 + else: + col += 1 + row = 0 + for index in chain.from_iterable(cells): + if index == -1: + break + yield width_renderables[index] + else: + yield from zip(renderable_widths, renderables) + # Pad odd elements with spaces + if item_count % column_count: + for _ in range(column_count - (item_count % column_count)): + yield 0, None + + table = Table.grid(padding=self.padding, collapse_padding=True, pad_edge=False) + table.expand = self.expand + table.title = self.title + + if self.width is not None: + column_count = (max_width) // (self.width + width_padding) + for _ in range(column_count): + table.add_column(width=self.width) + else: + while column_count > 1: + widths.clear() + column_no = 0 + for renderable_width, _ in iter_renderables(column_count): + widths[column_no] = max(widths[column_no], renderable_width) + total_width = sum(widths.values()) + width_padding * ( + len(widths) - 1 + ) + if total_width > max_width: + column_count = len(widths) - 1 + break + else: + column_no = (column_no + 1) % column_count + else: + break + + get_renderable = itemgetter(1) + _renderables = [ + get_renderable(_renderable) + for _renderable in iter_renderables(column_count) + ] + if self.equal: + _renderables = [ + None + if renderable is None + else Constrain(renderable, renderable_widths[0]) + for renderable in _renderables + ] + if self.align: + align = self.align + _Align = Align + _renderables = [ + None if renderable is None else _Align(renderable, align) + for renderable in _renderables + ] + + right_to_left = self.right_to_left + add_row = table.add_row + for start in range(0, len(_renderables), column_count): + row = _renderables[start : start + column_count] + if right_to_left: + row = row[::-1] + add_row(*row) + yield table + + +if __name__ == "__main__": # pragma: no cover + import os + + console = Console() + + files = [f"{i} {s}" for i, s in enumerate(sorted(os.listdir()))] + columns = Columns(files, padding=(0, 1), expand=False, equal=False) + console.print(columns) + console.rule() + columns.column_first = True + console.print(columns) + columns.right_to_left = True + console.rule() + console.print(columns) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rich/console.py b/TTS/Kokoro/.venv/Lib/site-packages/rich/console.py new file mode 100644 index 0000000000000000000000000000000000000000..ad92d529c0f8bdd09214ae393d598bb4d90067bc --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rich/console.py @@ -0,0 +1,2684 @@ +import inspect +import os +import sys +import threading +import zlib +from abc import ABC, abstractmethod +from dataclasses import dataclass, field +from datetime import datetime +from functools import wraps +from getpass import getpass +from html import escape +from inspect import isclass +from itertools import islice +from math import ceil +from time import monotonic +from types import FrameType, ModuleType, TracebackType +from typing import ( + IO, + TYPE_CHECKING, + Any, + Callable, + Dict, + Iterable, + List, + Literal, + Mapping, + NamedTuple, + Optional, + Protocol, + TextIO, + Tuple, + Type, + Union, + cast, + runtime_checkable, +) + +from rich._null_file import NULL_FILE + +from . import errors, themes +from ._emoji_replace import _emoji_replace +from ._export_format import CONSOLE_HTML_FORMAT, CONSOLE_SVG_FORMAT +from ._fileno import get_fileno +from ._log_render import FormatTimeCallable, LogRender +from .align import Align, AlignMethod +from .color import ColorSystem, blend_rgb +from .control import Control +from .emoji import EmojiVariant +from .highlighter import NullHighlighter, ReprHighlighter +from .markup import render as render_markup +from .measure import Measurement, measure_renderables +from .pager import Pager, SystemPager +from .pretty import Pretty, is_expandable +from .protocol import rich_cast +from .region import Region +from .scope import render_scope +from .screen import Screen +from .segment import Segment +from .style import Style, StyleType +from .styled import Styled +from .terminal_theme import DEFAULT_TERMINAL_THEME, SVG_EXPORT_THEME, TerminalTheme +from .text import Text, TextType +from .theme import Theme, ThemeStack + +if TYPE_CHECKING: + from ._windows import WindowsConsoleFeatures + from .live import Live + from .status import Status + +JUPYTER_DEFAULT_COLUMNS = 115 +JUPYTER_DEFAULT_LINES = 100 +WINDOWS = sys.platform == "win32" + +HighlighterType = Callable[[Union[str, "Text"]], "Text"] +JustifyMethod = Literal["default", "left", "center", "right", "full"] +OverflowMethod = Literal["fold", "crop", "ellipsis", "ignore"] + + +class NoChange: + pass + + +NO_CHANGE = NoChange() + +try: + _STDIN_FILENO = sys.__stdin__.fileno() # type: ignore[union-attr] +except Exception: + _STDIN_FILENO = 0 +try: + _STDOUT_FILENO = sys.__stdout__.fileno() # type: ignore[union-attr] +except Exception: + _STDOUT_FILENO = 1 +try: + _STDERR_FILENO = sys.__stderr__.fileno() # type: ignore[union-attr] +except Exception: + _STDERR_FILENO = 2 + +_STD_STREAMS = (_STDIN_FILENO, _STDOUT_FILENO, _STDERR_FILENO) +_STD_STREAMS_OUTPUT = (_STDOUT_FILENO, _STDERR_FILENO) + + +_TERM_COLORS = { + "kitty": ColorSystem.EIGHT_BIT, + "256color": ColorSystem.EIGHT_BIT, + "16color": ColorSystem.STANDARD, +} + + +class ConsoleDimensions(NamedTuple): + """Size of the terminal.""" + + width: int + """The width of the console in 'cells'.""" + height: int + """The height of the console in lines.""" + + +@dataclass +class ConsoleOptions: + """Options for __rich_console__ method.""" + + size: ConsoleDimensions + """Size of console.""" + legacy_windows: bool + """legacy_windows: flag for legacy windows.""" + min_width: int + """Minimum width of renderable.""" + max_width: int + """Maximum width of renderable.""" + is_terminal: bool + """True if the target is a terminal, otherwise False.""" + encoding: str + """Encoding of terminal.""" + max_height: int + """Height of container (starts as terminal)""" + justify: Optional[JustifyMethod] = None + """Justify value override for renderable.""" + overflow: Optional[OverflowMethod] = None + """Overflow value override for renderable.""" + no_wrap: Optional[bool] = False + """Disable wrapping for text.""" + highlight: Optional[bool] = None + """Highlight override for render_str.""" + markup: Optional[bool] = None + """Enable markup when rendering strings.""" + height: Optional[int] = None + + @property + def ascii_only(self) -> bool: + """Check if renderables should use ascii only.""" + return not self.encoding.startswith("utf") + + def copy(self) -> "ConsoleOptions": + """Return a copy of the options. + + Returns: + ConsoleOptions: a copy of self. + """ + options: ConsoleOptions = ConsoleOptions.__new__(ConsoleOptions) + options.__dict__ = self.__dict__.copy() + return options + + def update( + self, + *, + width: Union[int, NoChange] = NO_CHANGE, + min_width: Union[int, NoChange] = NO_CHANGE, + max_width: Union[int, NoChange] = NO_CHANGE, + justify: Union[Optional[JustifyMethod], NoChange] = NO_CHANGE, + overflow: Union[Optional[OverflowMethod], NoChange] = NO_CHANGE, + no_wrap: Union[Optional[bool], NoChange] = NO_CHANGE, + highlight: Union[Optional[bool], NoChange] = NO_CHANGE, + markup: Union[Optional[bool], NoChange] = NO_CHANGE, + height: Union[Optional[int], NoChange] = NO_CHANGE, + ) -> "ConsoleOptions": + """Update values, return a copy.""" + options = self.copy() + if not isinstance(width, NoChange): + options.min_width = options.max_width = max(0, width) + if not isinstance(min_width, NoChange): + options.min_width = min_width + if not isinstance(max_width, NoChange): + options.max_width = max_width + if not isinstance(justify, NoChange): + options.justify = justify + if not isinstance(overflow, NoChange): + options.overflow = overflow + if not isinstance(no_wrap, NoChange): + options.no_wrap = no_wrap + if not isinstance(highlight, NoChange): + options.highlight = highlight + if not isinstance(markup, NoChange): + options.markup = markup + if not isinstance(height, NoChange): + if height is not None: + options.max_height = height + options.height = None if height is None else max(0, height) + return options + + def update_width(self, width: int) -> "ConsoleOptions": + """Update just the width, return a copy. + + Args: + width (int): New width (sets both min_width and max_width) + + Returns: + ~ConsoleOptions: New console options instance. + """ + options = self.copy() + options.min_width = options.max_width = max(0, width) + return options + + def update_height(self, height: int) -> "ConsoleOptions": + """Update the height, and return a copy. + + Args: + height (int): New height + + Returns: + ~ConsoleOptions: New Console options instance. + """ + options = self.copy() + options.max_height = options.height = height + return options + + def reset_height(self) -> "ConsoleOptions": + """Return a copy of the options with height set to ``None``. + + Returns: + ~ConsoleOptions: New console options instance. + """ + options = self.copy() + options.height = None + return options + + def update_dimensions(self, width: int, height: int) -> "ConsoleOptions": + """Update the width and height, and return a copy. + + Args: + width (int): New width (sets both min_width and max_width). + height (int): New height. + + Returns: + ~ConsoleOptions: New console options instance. + """ + options = self.copy() + options.min_width = options.max_width = max(0, width) + options.height = options.max_height = height + return options + + +@runtime_checkable +class RichCast(Protocol): + """An object that may be 'cast' to a console renderable.""" + + def __rich__( + self, + ) -> Union["ConsoleRenderable", "RichCast", str]: # pragma: no cover + ... + + +@runtime_checkable +class ConsoleRenderable(Protocol): + """An object that supports the console protocol.""" + + def __rich_console__( + self, console: "Console", options: "ConsoleOptions" + ) -> "RenderResult": # pragma: no cover + ... + + +# A type that may be rendered by Console. +RenderableType = Union[ConsoleRenderable, RichCast, str] +"""A string or any object that may be rendered by Rich.""" + +# The result of calling a __rich_console__ method. +RenderResult = Iterable[Union[RenderableType, Segment]] + +_null_highlighter = NullHighlighter() + + +class CaptureError(Exception): + """An error in the Capture context manager.""" + + +class NewLine: + """A renderable to generate new line(s)""" + + def __init__(self, count: int = 1) -> None: + self.count = count + + def __rich_console__( + self, console: "Console", options: "ConsoleOptions" + ) -> Iterable[Segment]: + yield Segment("\n" * self.count) + + +class ScreenUpdate: + """Render a list of lines at a given offset.""" + + def __init__(self, lines: List[List[Segment]], x: int, y: int) -> None: + self._lines = lines + self.x = x + self.y = y + + def __rich_console__( + self, console: "Console", options: ConsoleOptions + ) -> RenderResult: + x = self.x + move_to = Control.move_to + for offset, line in enumerate(self._lines, self.y): + yield move_to(x, offset) + yield from line + + +class Capture: + """Context manager to capture the result of printing to the console. + See :meth:`~rich.console.Console.capture` for how to use. + + Args: + console (Console): A console instance to capture output. + """ + + def __init__(self, console: "Console") -> None: + self._console = console + self._result: Optional[str] = None + + def __enter__(self) -> "Capture": + self._console.begin_capture() + return self + + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> None: + self._result = self._console.end_capture() + + def get(self) -> str: + """Get the result of the capture.""" + if self._result is None: + raise CaptureError( + "Capture result is not available until context manager exits." + ) + return self._result + + +class ThemeContext: + """A context manager to use a temporary theme. See :meth:`~rich.console.Console.use_theme` for usage.""" + + def __init__(self, console: "Console", theme: Theme, inherit: bool = True) -> None: + self.console = console + self.theme = theme + self.inherit = inherit + + def __enter__(self) -> "ThemeContext": + self.console.push_theme(self.theme) + return self + + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> None: + self.console.pop_theme() + + +class PagerContext: + """A context manager that 'pages' content. See :meth:`~rich.console.Console.pager` for usage.""" + + def __init__( + self, + console: "Console", + pager: Optional[Pager] = None, + styles: bool = False, + links: bool = False, + ) -> None: + self._console = console + self.pager = SystemPager() if pager is None else pager + self.styles = styles + self.links = links + + def __enter__(self) -> "PagerContext": + self._console._enter_buffer() + return self + + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> None: + if exc_type is None: + with self._console._lock: + buffer: List[Segment] = self._console._buffer[:] + del self._console._buffer[:] + segments: Iterable[Segment] = buffer + if not self.styles: + segments = Segment.strip_styles(segments) + elif not self.links: + segments = Segment.strip_links(segments) + content = self._console._render_buffer(segments) + self.pager.show(content) + self._console._exit_buffer() + + +class ScreenContext: + """A context manager that enables an alternative screen. See :meth:`~rich.console.Console.screen` for usage.""" + + def __init__( + self, console: "Console", hide_cursor: bool, style: StyleType = "" + ) -> None: + self.console = console + self.hide_cursor = hide_cursor + self.screen = Screen(style=style) + self._changed = False + + def update( + self, *renderables: RenderableType, style: Optional[StyleType] = None + ) -> None: + """Update the screen. + + Args: + renderable (RenderableType, optional): Optional renderable to replace current renderable, + or None for no change. Defaults to None. + style: (Style, optional): Replacement style, or None for no change. Defaults to None. + """ + if renderables: + self.screen.renderable = ( + Group(*renderables) if len(renderables) > 1 else renderables[0] + ) + if style is not None: + self.screen.style = style + self.console.print(self.screen, end="") + + def __enter__(self) -> "ScreenContext": + self._changed = self.console.set_alt_screen(True) + if self._changed and self.hide_cursor: + self.console.show_cursor(False) + return self + + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> None: + if self._changed: + self.console.set_alt_screen(False) + if self.hide_cursor: + self.console.show_cursor(True) + + +class Group: + """Takes a group of renderables and returns a renderable object that renders the group. + + Args: + renderables (Iterable[RenderableType]): An iterable of renderable objects. + fit (bool, optional): Fit dimension of group to contents, or fill available space. Defaults to True. + """ + + def __init__(self, *renderables: "RenderableType", fit: bool = True) -> None: + self._renderables = renderables + self.fit = fit + self._render: Optional[List[RenderableType]] = None + + @property + def renderables(self) -> List["RenderableType"]: + if self._render is None: + self._render = list(self._renderables) + return self._render + + def __rich_measure__( + self, console: "Console", options: "ConsoleOptions" + ) -> "Measurement": + if self.fit: + return measure_renderables(console, options, self.renderables) + else: + return Measurement(options.max_width, options.max_width) + + def __rich_console__( + self, console: "Console", options: "ConsoleOptions" + ) -> RenderResult: + yield from self.renderables + + +def group(fit: bool = True) -> Callable[..., Callable[..., Group]]: + """A decorator that turns an iterable of renderables in to a group. + + Args: + fit (bool, optional): Fit dimension of group to contents, or fill available space. Defaults to True. + """ + + def decorator( + method: Callable[..., Iterable[RenderableType]], + ) -> Callable[..., Group]: + """Convert a method that returns an iterable of renderables in to a Group.""" + + @wraps(method) + def _replace(*args: Any, **kwargs: Any) -> Group: + renderables = method(*args, **kwargs) + return Group(*renderables, fit=fit) + + return _replace + + return decorator + + +def _is_jupyter() -> bool: # pragma: no cover + """Check if we're running in a Jupyter notebook.""" + try: + get_ipython # type: ignore[name-defined] + except NameError: + return False + ipython = get_ipython() # type: ignore[name-defined] + shell = ipython.__class__.__name__ + if ( + "google.colab" in str(ipython.__class__) + or os.getenv("DATABRICKS_RUNTIME_VERSION") + or shell == "ZMQInteractiveShell" + ): + return True # Jupyter notebook or qtconsole + elif shell == "TerminalInteractiveShell": + return False # Terminal running IPython + else: + return False # Other type (?) + + +COLOR_SYSTEMS = { + "standard": ColorSystem.STANDARD, + "256": ColorSystem.EIGHT_BIT, + "truecolor": ColorSystem.TRUECOLOR, + "windows": ColorSystem.WINDOWS, +} + +_COLOR_SYSTEMS_NAMES = {system: name for name, system in COLOR_SYSTEMS.items()} + + +@dataclass +class ConsoleThreadLocals(threading.local): + """Thread local values for Console context.""" + + theme_stack: ThemeStack + buffer: List[Segment] = field(default_factory=list) + buffer_index: int = 0 + + +class RenderHook(ABC): + """Provides hooks in to the render process.""" + + @abstractmethod + def process_renderables( + self, renderables: List[ConsoleRenderable] + ) -> List[ConsoleRenderable]: + """Called with a list of objects to render. + + This method can return a new list of renderables, or modify and return the same list. + + Args: + renderables (List[ConsoleRenderable]): A number of renderable objects. + + Returns: + List[ConsoleRenderable]: A replacement list of renderables. + """ + + +_windows_console_features: Optional["WindowsConsoleFeatures"] = None + + +def get_windows_console_features() -> "WindowsConsoleFeatures": # pragma: no cover + global _windows_console_features + if _windows_console_features is not None: + return _windows_console_features + from ._windows import get_windows_console_features + + _windows_console_features = get_windows_console_features() + return _windows_console_features + + +def detect_legacy_windows() -> bool: + """Detect legacy Windows.""" + return WINDOWS and not get_windows_console_features().vt + + +class Console: + """A high level console interface. + + Args: + color_system (str, optional): The color system supported by your terminal, + either ``"standard"``, ``"256"`` or ``"truecolor"``. Leave as ``"auto"`` to autodetect. + force_terminal (Optional[bool], optional): Enable/disable terminal control codes, or None to auto-detect terminal. Defaults to None. + force_jupyter (Optional[bool], optional): Enable/disable Jupyter rendering, or None to auto-detect Jupyter. Defaults to None. + force_interactive (Optional[bool], optional): Enable/disable interactive mode, or None to auto detect. Defaults to None. + soft_wrap (Optional[bool], optional): Set soft wrap default on print method. Defaults to False. + theme (Theme, optional): An optional style theme object, or ``None`` for default theme. + stderr (bool, optional): Use stderr rather than stdout if ``file`` is not specified. Defaults to False. + file (IO, optional): A file object where the console should write to. Defaults to stdout. + quiet (bool, Optional): Boolean to suppress all output. Defaults to False. + width (int, optional): The width of the terminal. Leave as default to auto-detect width. + height (int, optional): The height of the terminal. Leave as default to auto-detect height. + style (StyleType, optional): Style to apply to all output, or None for no style. Defaults to None. + no_color (Optional[bool], optional): Enabled no color mode, or None to auto detect. Defaults to None. + tab_size (int, optional): Number of spaces used to replace a tab character. Defaults to 8. + record (bool, optional): Boolean to enable recording of terminal output, + required to call :meth:`export_html`, :meth:`export_svg`, and :meth:`export_text`. Defaults to False. + markup (bool, optional): Boolean to enable :ref:`console_markup`. Defaults to True. + emoji (bool, optional): Enable emoji code. Defaults to True. + emoji_variant (str, optional): Optional emoji variant, either "text" or "emoji". Defaults to None. + highlight (bool, optional): Enable automatic highlighting. Defaults to True. + log_time (bool, optional): Boolean to enable logging of time by :meth:`log` methods. Defaults to True. + log_path (bool, optional): Boolean to enable the logging of the caller by :meth:`log`. Defaults to True. + log_time_format (Union[str, TimeFormatterCallable], optional): If ``log_time`` is enabled, either string for strftime or callable that formats the time. Defaults to "[%X] ". + highlighter (HighlighterType, optional): Default highlighter. + legacy_windows (bool, optional): Enable legacy Windows mode, or ``None`` to auto detect. Defaults to ``None``. + safe_box (bool, optional): Restrict box options that don't render on legacy Windows. + get_datetime (Callable[[], datetime], optional): Callable that gets the current time as a datetime.datetime object (used by Console.log), + or None for datetime.now. + get_time (Callable[[], time], optional): Callable that gets the current time in seconds, default uses time.monotonic. + """ + + _environ: Mapping[str, str] = os.environ + + def __init__( + self, + *, + color_system: Optional[ + Literal["auto", "standard", "256", "truecolor", "windows"] + ] = "auto", + force_terminal: Optional[bool] = None, + force_jupyter: Optional[bool] = None, + force_interactive: Optional[bool] = None, + soft_wrap: bool = False, + theme: Optional[Theme] = None, + stderr: bool = False, + file: Optional[IO[str]] = None, + quiet: bool = False, + width: Optional[int] = None, + height: Optional[int] = None, + style: Optional[StyleType] = None, + no_color: Optional[bool] = None, + tab_size: int = 8, + record: bool = False, + markup: bool = True, + emoji: bool = True, + emoji_variant: Optional[EmojiVariant] = None, + highlight: bool = True, + log_time: bool = True, + log_path: bool = True, + log_time_format: Union[str, FormatTimeCallable] = "[%X]", + highlighter: Optional["HighlighterType"] = ReprHighlighter(), + legacy_windows: Optional[bool] = None, + safe_box: bool = True, + get_datetime: Optional[Callable[[], datetime]] = None, + get_time: Optional[Callable[[], float]] = None, + _environ: Optional[Mapping[str, str]] = None, + ): + # Copy of os.environ allows us to replace it for testing + if _environ is not None: + self._environ = _environ + + self.is_jupyter = _is_jupyter() if force_jupyter is None else force_jupyter + if self.is_jupyter: + if width is None: + jupyter_columns = self._environ.get("JUPYTER_COLUMNS") + if jupyter_columns is not None and jupyter_columns.isdigit(): + width = int(jupyter_columns) + else: + width = JUPYTER_DEFAULT_COLUMNS + if height is None: + jupyter_lines = self._environ.get("JUPYTER_LINES") + if jupyter_lines is not None and jupyter_lines.isdigit(): + height = int(jupyter_lines) + else: + height = JUPYTER_DEFAULT_LINES + + self.tab_size = tab_size + self.record = record + self._markup = markup + self._emoji = emoji + self._emoji_variant: Optional[EmojiVariant] = emoji_variant + self._highlight = highlight + self.legacy_windows: bool = ( + (detect_legacy_windows() and not self.is_jupyter) + if legacy_windows is None + else legacy_windows + ) + + if width is None: + columns = self._environ.get("COLUMNS") + if columns is not None and columns.isdigit(): + width = int(columns) - self.legacy_windows + if height is None: + lines = self._environ.get("LINES") + if lines is not None and lines.isdigit(): + height = int(lines) + + self.soft_wrap = soft_wrap + self._width = width + self._height = height + + self._color_system: Optional[ColorSystem] + + self._force_terminal = None + if force_terminal is not None: + self._force_terminal = force_terminal + + self._file = file + self.quiet = quiet + self.stderr = stderr + + if color_system is None: + self._color_system = None + elif color_system == "auto": + self._color_system = self._detect_color_system() + else: + self._color_system = COLOR_SYSTEMS[color_system] + + self._lock = threading.RLock() + self._log_render = LogRender( + show_time=log_time, + show_path=log_path, + time_format=log_time_format, + ) + self.highlighter: HighlighterType = highlighter or _null_highlighter + self.safe_box = safe_box + self.get_datetime = get_datetime or datetime.now + self.get_time = get_time or monotonic + self.style = style + self.no_color = ( + no_color + if no_color is not None + else self._environ.get("NO_COLOR", "") != "" + ) + if force_interactive is None: + tty_interactive = self._environ.get("TTY_INTERACTIVE", None) + if tty_interactive is not None: + if tty_interactive == "0": + force_interactive = False + elif tty_interactive == "1": + force_interactive = True + + self.is_interactive = ( + (self.is_terminal and not self.is_dumb_terminal) + if force_interactive is None + else force_interactive + ) + + self._record_buffer_lock = threading.RLock() + self._thread_locals = ConsoleThreadLocals( + theme_stack=ThemeStack(themes.DEFAULT if theme is None else theme) + ) + self._record_buffer: List[Segment] = [] + self._render_hooks: List[RenderHook] = [] + self._live_stack: List[Live] = [] + self._is_alt_screen = False + + def __repr__(self) -> str: + return f"" + + @property + def file(self) -> IO[str]: + """Get the file object to write to.""" + file = self._file or (sys.stderr if self.stderr else sys.stdout) + file = getattr(file, "rich_proxied_file", file) + if file is None: + file = NULL_FILE + return file + + @file.setter + def file(self, new_file: IO[str]) -> None: + """Set a new file object.""" + self._file = new_file + + @property + def _buffer(self) -> List[Segment]: + """Get a thread local buffer.""" + return self._thread_locals.buffer + + @property + def _buffer_index(self) -> int: + """Get a thread local buffer.""" + return self._thread_locals.buffer_index + + @_buffer_index.setter + def _buffer_index(self, value: int) -> None: + self._thread_locals.buffer_index = value + + @property + def _theme_stack(self) -> ThemeStack: + """Get the thread local theme stack.""" + return self._thread_locals.theme_stack + + def _detect_color_system(self) -> Optional[ColorSystem]: + """Detect color system from env vars.""" + if self.is_jupyter: + return ColorSystem.TRUECOLOR + if not self.is_terminal or self.is_dumb_terminal: + return None + if WINDOWS: # pragma: no cover + if self.legacy_windows: # pragma: no cover + return ColorSystem.WINDOWS + windows_console_features = get_windows_console_features() + return ( + ColorSystem.TRUECOLOR + if windows_console_features.truecolor + else ColorSystem.EIGHT_BIT + ) + else: + color_term = self._environ.get("COLORTERM", "").strip().lower() + if color_term in ("truecolor", "24bit"): + return ColorSystem.TRUECOLOR + term = self._environ.get("TERM", "").strip().lower() + _term_name, _hyphen, colors = term.rpartition("-") + color_system = _TERM_COLORS.get(colors, ColorSystem.STANDARD) + return color_system + + def _enter_buffer(self) -> None: + """Enter in to a buffer context, and buffer all output.""" + self._buffer_index += 1 + + def _exit_buffer(self) -> None: + """Leave buffer context, and render content if required.""" + self._buffer_index -= 1 + self._check_buffer() + + def set_live(self, live: "Live") -> bool: + """Set Live instance. Used by Live context manager (no need to call directly). + + Args: + live (Live): Live instance using this Console. + + Returns: + Boolean that indicates if the live is the topmost of the stack. + + Raises: + errors.LiveError: If this Console has a Live context currently active. + """ + with self._lock: + self._live_stack.append(live) + return len(self._live_stack) == 1 + + def clear_live(self) -> None: + """Clear the Live instance. Used by the Live context manager (no need to call directly).""" + with self._lock: + self._live_stack.pop() + + def push_render_hook(self, hook: RenderHook) -> None: + """Add a new render hook to the stack. + + Args: + hook (RenderHook): Render hook instance. + """ + with self._lock: + self._render_hooks.append(hook) + + def pop_render_hook(self) -> None: + """Pop the last renderhook from the stack.""" + with self._lock: + self._render_hooks.pop() + + def __enter__(self) -> "Console": + """Own context manager to enter buffer context.""" + self._enter_buffer() + return self + + def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None: + """Exit buffer context.""" + self._exit_buffer() + + def begin_capture(self) -> None: + """Begin capturing console output. Call :meth:`end_capture` to exit capture mode and return output.""" + self._enter_buffer() + + def end_capture(self) -> str: + """End capture mode and return captured string. + + Returns: + str: Console output. + """ + render_result = self._render_buffer(self._buffer) + del self._buffer[:] + self._exit_buffer() + return render_result + + def push_theme(self, theme: Theme, *, inherit: bool = True) -> None: + """Push a new theme on to the top of the stack, replacing the styles from the previous theme. + Generally speaking, you should call :meth:`~rich.console.Console.use_theme` to get a context manager, rather + than calling this method directly. + + Args: + theme (Theme): A theme instance. + inherit (bool, optional): Inherit existing styles. Defaults to True. + """ + self._theme_stack.push_theme(theme, inherit=inherit) + + def pop_theme(self) -> None: + """Remove theme from top of stack, restoring previous theme.""" + self._theme_stack.pop_theme() + + def use_theme(self, theme: Theme, *, inherit: bool = True) -> ThemeContext: + """Use a different theme for the duration of the context manager. + + Args: + theme (Theme): Theme instance to user. + inherit (bool, optional): Inherit existing console styles. Defaults to True. + + Returns: + ThemeContext: [description] + """ + return ThemeContext(self, theme, inherit) + + @property + def color_system(self) -> Optional[str]: + """Get color system string. + + Returns: + Optional[str]: "standard", "256" or "truecolor". + """ + + if self._color_system is not None: + return _COLOR_SYSTEMS_NAMES[self._color_system] + else: + return None + + @property + def encoding(self) -> str: + """Get the encoding of the console file, e.g. ``"utf-8"``. + + Returns: + str: A standard encoding string. + """ + return (getattr(self.file, "encoding", "utf-8") or "utf-8").lower() + + @property + def is_terminal(self) -> bool: + """Check if the console is writing to a terminal. + + Returns: + bool: True if the console writing to a device capable of + understanding escape sequences, otherwise False. + """ + # If dev has explicitly set this value, return it + if self._force_terminal is not None: + return self._force_terminal + + # Fudge for Idle + if hasattr(sys.stdin, "__module__") and sys.stdin.__module__.startswith( + "idlelib" + ): + # Return False for Idle which claims to be a tty but can't handle ansi codes + return False + + if self.is_jupyter: + # return False for Jupyter, which may have FORCE_COLOR set + return False + + environ = self._environ + + tty_compatible = environ.get("TTY_COMPATIBLE", "") + # 0 indicates device is not tty compatible + if tty_compatible == "0": + return False + # 1 indicates device is tty compatible + if tty_compatible == "1": + return True + + # https://force-color.org/ + force_color = environ.get("FORCE_COLOR") + if force_color is not None: + return force_color != "" + + # Any other value defaults to auto detect + isatty: Optional[Callable[[], bool]] = getattr(self.file, "isatty", None) + try: + return False if isatty is None else isatty() + except ValueError: + # in some situation (at the end of a pytest run for example) isatty() can raise + # ValueError: I/O operation on closed file + # return False because we aren't in a terminal anymore + return False + + @property + def is_dumb_terminal(self) -> bool: + """Detect dumb terminal. + + Returns: + bool: True if writing to a dumb terminal, otherwise False. + + """ + _term = self._environ.get("TERM", "") + is_dumb = _term.lower() in ("dumb", "unknown") + return self.is_terminal and is_dumb + + @property + def options(self) -> ConsoleOptions: + """Get default console options.""" + size = self.size + return ConsoleOptions( + max_height=size.height, + size=size, + legacy_windows=self.legacy_windows, + min_width=1, + max_width=size.width, + encoding=self.encoding, + is_terminal=self.is_terminal, + ) + + @property + def size(self) -> ConsoleDimensions: + """Get the size of the console. + + Returns: + ConsoleDimensions: A named tuple containing the dimensions. + """ + + if self._width is not None and self._height is not None: + return ConsoleDimensions(self._width - self.legacy_windows, self._height) + + if self.is_dumb_terminal: + return ConsoleDimensions(80, 25) + + width: Optional[int] = None + height: Optional[int] = None + + streams = _STD_STREAMS_OUTPUT if WINDOWS else _STD_STREAMS + for file_descriptor in streams: + try: + width, height = os.get_terminal_size(file_descriptor) + except (AttributeError, ValueError, OSError): # Probably not a terminal + pass + else: + break + + columns = self._environ.get("COLUMNS") + if columns is not None and columns.isdigit(): + width = int(columns) + lines = self._environ.get("LINES") + if lines is not None and lines.isdigit(): + height = int(lines) + + # get_terminal_size can report 0, 0 if run from pseudo-terminal + width = width or 80 + height = height or 25 + return ConsoleDimensions( + width - self.legacy_windows if self._width is None else self._width, + height if self._height is None else self._height, + ) + + @size.setter + def size(self, new_size: Tuple[int, int]) -> None: + """Set a new size for the terminal. + + Args: + new_size (Tuple[int, int]): New width and height. + """ + width, height = new_size + self._width = width + self._height = height + + @property + def width(self) -> int: + """Get the width of the console. + + Returns: + int: The width (in characters) of the console. + """ + return self.size.width + + @width.setter + def width(self, width: int) -> None: + """Set width. + + Args: + width (int): New width. + """ + self._width = width + + @property + def height(self) -> int: + """Get the height of the console. + + Returns: + int: The height (in lines) of the console. + """ + return self.size.height + + @height.setter + def height(self, height: int) -> None: + """Set height. + + Args: + height (int): new height. + """ + self._height = height + + def bell(self) -> None: + """Play a 'bell' sound (if supported by the terminal).""" + self.control(Control.bell()) + + def capture(self) -> Capture: + """A context manager to *capture* the result of print() or log() in a string, + rather than writing it to the console. + + Example: + >>> from rich.console import Console + >>> console = Console() + >>> with console.capture() as capture: + ... console.print("[bold magenta]Hello World[/]") + >>> print(capture.get()) + + Returns: + Capture: Context manager with disables writing to the terminal. + """ + capture = Capture(self) + return capture + + def pager( + self, pager: Optional[Pager] = None, styles: bool = False, links: bool = False + ) -> PagerContext: + """A context manager to display anything printed within a "pager". The pager application + is defined by the system and will typically support at least pressing a key to scroll. + + Args: + pager (Pager, optional): A pager object, or None to use :class:`~rich.pager.SystemPager`. Defaults to None. + styles (bool, optional): Show styles in pager. Defaults to False. + links (bool, optional): Show links in pager. Defaults to False. + + Example: + >>> from rich.console import Console + >>> from rich.__main__ import make_test_card + >>> console = Console() + >>> with console.pager(): + console.print(make_test_card()) + + Returns: + PagerContext: A context manager. + """ + return PagerContext(self, pager=pager, styles=styles, links=links) + + def line(self, count: int = 1) -> None: + """Write new line(s). + + Args: + count (int, optional): Number of new lines. Defaults to 1. + """ + + assert count >= 0, "count must be >= 0" + self.print(NewLine(count)) + + def clear(self, home: bool = True) -> None: + """Clear the screen. + + Args: + home (bool, optional): Also move the cursor to 'home' position. Defaults to True. + """ + if home: + self.control(Control.clear(), Control.home()) + else: + self.control(Control.clear()) + + def status( + self, + status: RenderableType, + *, + spinner: str = "dots", + spinner_style: StyleType = "status.spinner", + speed: float = 1.0, + refresh_per_second: float = 12.5, + ) -> "Status": + """Display a status and spinner. + + Args: + status (RenderableType): A status renderable (str or Text typically). + spinner (str, optional): Name of spinner animation (see python -m rich.spinner). Defaults to "dots". + spinner_style (StyleType, optional): Style of spinner. Defaults to "status.spinner". + speed (float, optional): Speed factor for spinner animation. Defaults to 1.0. + refresh_per_second (float, optional): Number of refreshes per second. Defaults to 12.5. + + Returns: + Status: A Status object that may be used as a context manager. + """ + from .status import Status + + status_renderable = Status( + status, + console=self, + spinner=spinner, + spinner_style=spinner_style, + speed=speed, + refresh_per_second=refresh_per_second, + ) + return status_renderable + + def show_cursor(self, show: bool = True) -> bool: + """Show or hide the cursor. + + Args: + show (bool, optional): Set visibility of the cursor. + """ + if self.is_terminal: + self.control(Control.show_cursor(show)) + return True + return False + + def set_alt_screen(self, enable: bool = True) -> bool: + """Enables alternative screen mode. + + Note, if you enable this mode, you should ensure that is disabled before + the application exits. See :meth:`~rich.Console.screen` for a context manager + that handles this for you. + + Args: + enable (bool, optional): Enable (True) or disable (False) alternate screen. Defaults to True. + + Returns: + bool: True if the control codes were written. + + """ + changed = False + if self.is_terminal and not self.legacy_windows: + self.control(Control.alt_screen(enable)) + changed = True + self._is_alt_screen = enable + return changed + + @property + def is_alt_screen(self) -> bool: + """Check if the alt screen was enabled. + + Returns: + bool: True if the alt screen was enabled, otherwise False. + """ + return self._is_alt_screen + + def set_window_title(self, title: str) -> bool: + """Set the title of the console terminal window. + + Warning: There is no means within Rich of "resetting" the window title to its + previous value, meaning the title you set will persist even after your application + exits. + + ``fish`` shell resets the window title before and after each command by default, + negating this issue. Windows Terminal and command prompt will also reset the title for you. + Most other shells and terminals, however, do not do this. + + Some terminals may require configuration changes before you can set the title. + Some terminals may not support setting the title at all. + + Other software (including the terminal itself, the shell, custom prompts, plugins, etc.) + may also set the terminal window title. This could result in whatever value you write + using this method being overwritten. + + Args: + title (str): The new title of the terminal window. + + Returns: + bool: True if the control code to change the terminal title was + written, otherwise False. Note that a return value of True + does not guarantee that the window title has actually changed, + since the feature may be unsupported/disabled in some terminals. + """ + if self.is_terminal: + self.control(Control.title(title)) + return True + return False + + def screen( + self, hide_cursor: bool = True, style: Optional[StyleType] = None + ) -> "ScreenContext": + """Context manager to enable and disable 'alternative screen' mode. + + Args: + hide_cursor (bool, optional): Also hide the cursor. Defaults to False. + style (Style, optional): Optional style for screen. Defaults to None. + + Returns: + ~ScreenContext: Context which enables alternate screen on enter, and disables it on exit. + """ + return ScreenContext(self, hide_cursor=hide_cursor, style=style or "") + + def measure( + self, renderable: RenderableType, *, options: Optional[ConsoleOptions] = None + ) -> Measurement: + """Measure a renderable. Returns a :class:`~rich.measure.Measurement` object which contains + information regarding the number of characters required to print the renderable. + + Args: + renderable (RenderableType): Any renderable or string. + options (Optional[ConsoleOptions], optional): Options to use when measuring, or None + to use default options. Defaults to None. + + Returns: + Measurement: A measurement of the renderable. + """ + measurement = Measurement.get(self, options or self.options, renderable) + return measurement + + def render( + self, renderable: RenderableType, options: Optional[ConsoleOptions] = None + ) -> Iterable[Segment]: + """Render an object in to an iterable of `Segment` instances. + + This method contains the logic for rendering objects with the console protocol. + You are unlikely to need to use it directly, unless you are extending the library. + + Args: + renderable (RenderableType): An object supporting the console protocol, or + an object that may be converted to a string. + options (ConsoleOptions, optional): An options object, or None to use self.options. Defaults to None. + + Returns: + Iterable[Segment]: An iterable of segments that may be rendered. + """ + + _options = options or self.options + if _options.max_width < 1: + # No space to render anything. This prevents potential recursion errors. + return + render_iterable: RenderResult + + renderable = rich_cast(renderable) + if hasattr(renderable, "__rich_console__") and not isclass(renderable): + render_iterable = renderable.__rich_console__(self, _options) + elif isinstance(renderable, str): + text_renderable = self.render_str( + renderable, highlight=_options.highlight, markup=_options.markup + ) + render_iterable = text_renderable.__rich_console__(self, _options) + else: + raise errors.NotRenderableError( + f"Unable to render {renderable!r}; " + "A str, Segment or object with __rich_console__ method is required" + ) + + try: + iter_render = iter(render_iterable) + except TypeError: + raise errors.NotRenderableError( + f"object {render_iterable!r} is not renderable" + ) + _Segment = Segment + _options = _options.reset_height() + for render_output in iter_render: + if isinstance(render_output, _Segment): + yield render_output + else: + yield from self.render(render_output, _options) + + def render_lines( + self, + renderable: RenderableType, + options: Optional[ConsoleOptions] = None, + *, + style: Optional[Style] = None, + pad: bool = True, + new_lines: bool = False, + ) -> List[List[Segment]]: + """Render objects in to a list of lines. + + The output of render_lines is useful when further formatting of rendered console text + is required, such as the Panel class which draws a border around any renderable object. + + Args: + renderable (RenderableType): Any object renderable in the console. + options (Optional[ConsoleOptions], optional): Console options, or None to use self.options. Default to ``None``. + style (Style, optional): Optional style to apply to renderables. Defaults to ``None``. + pad (bool, optional): Pad lines shorter than render width. Defaults to ``True``. + new_lines (bool, optional): Include "\n" characters at end of lines. + + Returns: + List[List[Segment]]: A list of lines, where a line is a list of Segment objects. + """ + with self._lock: + render_options = options or self.options + _rendered = self.render(renderable, render_options) + if style: + _rendered = Segment.apply_style(_rendered, style) + + render_height = render_options.height + if render_height is not None: + render_height = max(0, render_height) + + lines = list( + islice( + Segment.split_and_crop_lines( + _rendered, + render_options.max_width, + include_new_lines=new_lines, + pad=pad, + style=style, + ), + None, + render_height, + ) + ) + if render_options.height is not None: + extra_lines = render_options.height - len(lines) + if extra_lines > 0: + pad_line = [ + ( + [ + Segment(" " * render_options.max_width, style), + Segment("\n"), + ] + if new_lines + else [Segment(" " * render_options.max_width, style)] + ) + ] + lines.extend(pad_line * extra_lines) + + return lines + + def render_str( + self, + text: str, + *, + style: Union[str, Style] = "", + justify: Optional[JustifyMethod] = None, + overflow: Optional[OverflowMethod] = None, + emoji: Optional[bool] = None, + markup: Optional[bool] = None, + highlight: Optional[bool] = None, + highlighter: Optional[HighlighterType] = None, + ) -> "Text": + """Convert a string to a Text instance. This is called automatically if + you print or log a string. + + Args: + text (str): Text to render. + style (Union[str, Style], optional): Style to apply to rendered text. + justify (str, optional): Justify method: "default", "left", "center", "full", or "right". Defaults to ``None``. + overflow (str, optional): Overflow method: "crop", "fold", or "ellipsis". Defaults to ``None``. + emoji (Optional[bool], optional): Enable emoji, or ``None`` to use Console default. + markup (Optional[bool], optional): Enable markup, or ``None`` to use Console default. + highlight (Optional[bool], optional): Enable highlighting, or ``None`` to use Console default. + highlighter (HighlighterType, optional): Optional highlighter to apply. + Returns: + ConsoleRenderable: Renderable object. + + """ + emoji_enabled = emoji or (emoji is None and self._emoji) + markup_enabled = markup or (markup is None and self._markup) + highlight_enabled = highlight or (highlight is None and self._highlight) + + if markup_enabled: + rich_text = render_markup( + text, + style=style, + emoji=emoji_enabled, + emoji_variant=self._emoji_variant, + ) + rich_text.justify = justify + rich_text.overflow = overflow + else: + rich_text = Text( + ( + _emoji_replace(text, default_variant=self._emoji_variant) + if emoji_enabled + else text + ), + justify=justify, + overflow=overflow, + style=style, + ) + + _highlighter = (highlighter or self.highlighter) if highlight_enabled else None + if _highlighter is not None: + highlight_text = _highlighter(str(rich_text)) + highlight_text.copy_styles(rich_text) + return highlight_text + + return rich_text + + def get_style( + self, name: Union[str, Style], *, default: Optional[Union[Style, str]] = None + ) -> Style: + """Get a Style instance by its theme name or parse a definition. + + Args: + name (str): The name of a style or a style definition. + + Returns: + Style: A Style object. + + Raises: + MissingStyle: If no style could be parsed from name. + + """ + if isinstance(name, Style): + return name + + try: + style = self._theme_stack.get(name) + if style is None: + style = Style.parse(name) + return style.copy() if style.link else style + except errors.StyleSyntaxError as error: + if default is not None: + return self.get_style(default) + raise errors.MissingStyle( + f"Failed to get style {name!r}; {error}" + ) from None + + def _collect_renderables( + self, + objects: Iterable[Any], + sep: str, + end: str, + *, + justify: Optional[JustifyMethod] = None, + emoji: Optional[bool] = None, + markup: Optional[bool] = None, + highlight: Optional[bool] = None, + ) -> List[ConsoleRenderable]: + """Combine a number of renderables and text into one renderable. + + Args: + objects (Iterable[Any]): Anything that Rich can render. + sep (str): String to write between print data. + end (str): String to write at end of print data. + justify (str, optional): One of "left", "right", "center", or "full". Defaults to ``None``. + emoji (Optional[bool], optional): Enable emoji code, or ``None`` to use console default. + markup (Optional[bool], optional): Enable markup, or ``None`` to use console default. + highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use console default. + + Returns: + List[ConsoleRenderable]: A list of things to render. + """ + renderables: List[ConsoleRenderable] = [] + _append = renderables.append + text: List[Text] = [] + append_text = text.append + + append = _append + if justify in ("left", "center", "right"): + + def align_append(renderable: RenderableType) -> None: + _append(Align(renderable, cast(AlignMethod, justify))) + + append = align_append + + _highlighter: HighlighterType = _null_highlighter + if highlight or (highlight is None and self._highlight): + _highlighter = self.highlighter + + def check_text() -> None: + if text: + sep_text = Text(sep, justify=justify, end=end) + append(sep_text.join(text)) + text.clear() + + for renderable in objects: + renderable = rich_cast(renderable) + if isinstance(renderable, str): + append_text( + self.render_str( + renderable, + emoji=emoji, + markup=markup, + highlight=highlight, + highlighter=_highlighter, + ) + ) + elif isinstance(renderable, Text): + append_text(renderable) + elif isinstance(renderable, ConsoleRenderable): + check_text() + append(renderable) + elif is_expandable(renderable): + check_text() + append(Pretty(renderable, highlighter=_highlighter)) + else: + append_text(_highlighter(str(renderable))) + + check_text() + + if self.style is not None: + style = self.get_style(self.style) + renderables = [Styled(renderable, style) for renderable in renderables] + + return renderables + + def rule( + self, + title: TextType = "", + *, + characters: str = "─", + style: Union[str, Style] = "rule.line", + align: AlignMethod = "center", + ) -> None: + """Draw a line with optional centered title. + + Args: + title (str, optional): Text to render over the rule. Defaults to "". + characters (str, optional): Character(s) to form the line. Defaults to "─". + style (str, optional): Style of line. Defaults to "rule.line". + align (str, optional): How to align the title, one of "left", "center", or "right". Defaults to "center". + """ + from .rule import Rule + + rule = Rule(title=title, characters=characters, style=style, align=align) + self.print(rule) + + def control(self, *control: Control) -> None: + """Insert non-printing control codes. + + Args: + control_codes (str): Control codes, such as those that may move the cursor. + """ + if not self.is_dumb_terminal: + with self: + self._buffer.extend(_control.segment for _control in control) + + def out( + self, + *objects: Any, + sep: str = " ", + end: str = "\n", + style: Optional[Union[str, Style]] = None, + highlight: Optional[bool] = None, + ) -> None: + """Output to the terminal. This is a low-level way of writing to the terminal which unlike + :meth:`~rich.console.Console.print` won't pretty print, wrap text, or apply markup, but will + optionally apply highlighting and a basic style. + + Args: + sep (str, optional): String to write between print data. Defaults to " ". + end (str, optional): String to write at end of print data. Defaults to "\\\\n". + style (Union[str, Style], optional): A style to apply to output. Defaults to None. + highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use + console default. Defaults to ``None``. + """ + raw_output: str = sep.join(str(_object) for _object in objects) + self.print( + raw_output, + style=style, + highlight=highlight, + emoji=False, + markup=False, + no_wrap=True, + overflow="ignore", + crop=False, + end=end, + ) + + def print( + self, + *objects: Any, + sep: str = " ", + end: str = "\n", + style: Optional[Union[str, Style]] = None, + justify: Optional[JustifyMethod] = None, + overflow: Optional[OverflowMethod] = None, + no_wrap: Optional[bool] = None, + emoji: Optional[bool] = None, + markup: Optional[bool] = None, + highlight: Optional[bool] = None, + width: Optional[int] = None, + height: Optional[int] = None, + crop: bool = True, + soft_wrap: Optional[bool] = None, + new_line_start: bool = False, + ) -> None: + """Print to the console. + + Args: + objects (positional args): Objects to log to the terminal. + sep (str, optional): String to write between print data. Defaults to " ". + end (str, optional): String to write at end of print data. Defaults to "\\\\n". + style (Union[str, Style], optional): A style to apply to output. Defaults to None. + justify (str, optional): Justify method: "default", "left", "right", "center", or "full". Defaults to ``None``. + overflow (str, optional): Overflow method: "ignore", "crop", "fold", or "ellipsis". Defaults to None. + no_wrap (Optional[bool], optional): Disable word wrapping. Defaults to None. + emoji (Optional[bool], optional): Enable emoji code, or ``None`` to use console default. Defaults to ``None``. + markup (Optional[bool], optional): Enable markup, or ``None`` to use console default. Defaults to ``None``. + highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use console default. Defaults to ``None``. + width (Optional[int], optional): Width of output, or ``None`` to auto-detect. Defaults to ``None``. + crop (Optional[bool], optional): Crop output to width of terminal. Defaults to True. + soft_wrap (bool, optional): Enable soft wrap mode which disables word wrapping and cropping of text or ``None`` for + Console default. Defaults to ``None``. + new_line_start (bool, False): Insert a new line at the start if the output contains more than one line. Defaults to ``False``. + """ + if not objects: + objects = (NewLine(),) + + if soft_wrap is None: + soft_wrap = self.soft_wrap + if soft_wrap: + if no_wrap is None: + no_wrap = True + if overflow is None: + overflow = "ignore" + crop = False + render_hooks = self._render_hooks[:] + with self: + renderables = self._collect_renderables( + objects, + sep, + end, + justify=justify, + emoji=emoji, + markup=markup, + highlight=highlight, + ) + for hook in render_hooks: + renderables = hook.process_renderables(renderables) + render_options = self.options.update( + justify=justify, + overflow=overflow, + width=min(width, self.width) if width is not None else NO_CHANGE, + height=height, + no_wrap=no_wrap, + markup=markup, + highlight=highlight, + ) + + new_segments: List[Segment] = [] + extend = new_segments.extend + render = self.render + if style is None: + for renderable in renderables: + extend(render(renderable, render_options)) + else: + render_style = self.get_style(style) + new_line = Segment.line() + for renderable in renderables: + for line, add_new_line in Segment.split_lines_terminator( + render(renderable, render_options) + ): + extend(Segment.apply_style(line, render_style)) + if add_new_line: + new_segments.append(new_line) + + if new_line_start: + if ( + len("".join(segment.text for segment in new_segments).splitlines()) + > 1 + ): + new_segments.insert(0, Segment.line()) + if crop: + buffer_extend = self._buffer.extend + for line in Segment.split_and_crop_lines( + new_segments, self.width, pad=False + ): + buffer_extend(line) + else: + self._buffer.extend(new_segments) + + def print_json( + self, + json: Optional[str] = None, + *, + data: Any = None, + indent: Union[None, int, str] = 2, + highlight: bool = True, + skip_keys: bool = False, + ensure_ascii: bool = False, + check_circular: bool = True, + allow_nan: bool = True, + default: Optional[Callable[[Any], Any]] = None, + sort_keys: bool = False, + ) -> None: + """Pretty prints JSON. Output will be valid JSON. + + Args: + json (Optional[str]): A string containing JSON. + data (Any): If json is not supplied, then encode this data. + indent (Union[None, int, str], optional): Number of spaces to indent. Defaults to 2. + highlight (bool, optional): Enable highlighting of output: Defaults to True. + skip_keys (bool, optional): Skip keys not of a basic type. Defaults to False. + ensure_ascii (bool, optional): Escape all non-ascii characters. Defaults to False. + check_circular (bool, optional): Check for circular references. Defaults to True. + allow_nan (bool, optional): Allow NaN and Infinity values. Defaults to True. + default (Callable, optional): A callable that converts values that can not be encoded + in to something that can be JSON encoded. Defaults to None. + sort_keys (bool, optional): Sort dictionary keys. Defaults to False. + """ + from rich.json import JSON + + if json is None: + json_renderable = JSON.from_data( + data, + indent=indent, + highlight=highlight, + skip_keys=skip_keys, + ensure_ascii=ensure_ascii, + check_circular=check_circular, + allow_nan=allow_nan, + default=default, + sort_keys=sort_keys, + ) + else: + if not isinstance(json, str): + raise TypeError( + f"json must be str. Did you mean print_json(data={json!r}) ?" + ) + json_renderable = JSON( + json, + indent=indent, + highlight=highlight, + skip_keys=skip_keys, + ensure_ascii=ensure_ascii, + check_circular=check_circular, + allow_nan=allow_nan, + default=default, + sort_keys=sort_keys, + ) + self.print(json_renderable, soft_wrap=True) + + def update_screen( + self, + renderable: RenderableType, + *, + region: Optional[Region] = None, + options: Optional[ConsoleOptions] = None, + ) -> None: + """Update the screen at a given offset. + + Args: + renderable (RenderableType): A Rich renderable. + region (Region, optional): Region of screen to update, or None for entire screen. Defaults to None. + x (int, optional): x offset. Defaults to 0. + y (int, optional): y offset. Defaults to 0. + + Raises: + errors.NoAltScreen: If the Console isn't in alt screen mode. + + """ + if not self.is_alt_screen: + raise errors.NoAltScreen("Alt screen must be enabled to call update_screen") + render_options = options or self.options + if region is None: + x = y = 0 + render_options = render_options.update_dimensions( + render_options.max_width, render_options.height or self.height + ) + else: + x, y, width, height = region + render_options = render_options.update_dimensions(width, height) + + lines = self.render_lines(renderable, options=render_options) + self.update_screen_lines(lines, x, y) + + def update_screen_lines( + self, lines: List[List[Segment]], x: int = 0, y: int = 0 + ) -> None: + """Update lines of the screen at a given offset. + + Args: + lines (List[List[Segment]]): Rendered lines (as produced by :meth:`~rich.Console.render_lines`). + x (int, optional): x offset (column no). Defaults to 0. + y (int, optional): y offset (column no). Defaults to 0. + + Raises: + errors.NoAltScreen: If the Console isn't in alt screen mode. + """ + if not self.is_alt_screen: + raise errors.NoAltScreen("Alt screen must be enabled to call update_screen") + screen_update = ScreenUpdate(lines, x, y) + segments = self.render(screen_update) + self._buffer.extend(segments) + self._check_buffer() + + def print_exception( + self, + *, + width: Optional[int] = 100, + extra_lines: int = 3, + theme: Optional[str] = None, + word_wrap: bool = False, + show_locals: bool = False, + suppress: Iterable[Union[str, ModuleType]] = (), + max_frames: int = 100, + ) -> None: + """Prints a rich render of the last exception and traceback. + + Args: + width (Optional[int], optional): Number of characters used to render code. Defaults to 100. + extra_lines (int, optional): Additional lines of code to render. Defaults to 3. + theme (str, optional): Override pygments theme used in traceback + word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False. + show_locals (bool, optional): Enable display of local variables. Defaults to False. + suppress (Iterable[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback. + max_frames (int): Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100. + """ + from .traceback import Traceback + + traceback = Traceback( + width=width, + extra_lines=extra_lines, + theme=theme, + word_wrap=word_wrap, + show_locals=show_locals, + suppress=suppress, + max_frames=max_frames, + ) + self.print(traceback) + + @staticmethod + def _caller_frame_info( + offset: int, + currentframe: Callable[[], Optional[FrameType]] = inspect.currentframe, + ) -> Tuple[str, int, Dict[str, Any]]: + """Get caller frame information. + + Args: + offset (int): the caller offset within the current frame stack. + currentframe (Callable[[], Optional[FrameType]], optional): the callable to use to + retrieve the current frame. Defaults to ``inspect.currentframe``. + + Returns: + Tuple[str, int, Dict[str, Any]]: A tuple containing the filename, the line number and + the dictionary of local variables associated with the caller frame. + + Raises: + RuntimeError: If the stack offset is invalid. + """ + # Ignore the frame of this local helper + offset += 1 + + frame = currentframe() + if frame is not None: + # Use the faster currentframe where implemented + while offset and frame is not None: + frame = frame.f_back + offset -= 1 + assert frame is not None + return frame.f_code.co_filename, frame.f_lineno, frame.f_locals + else: + # Fallback to the slower stack + frame_info = inspect.stack()[offset] + return frame_info.filename, frame_info.lineno, frame_info.frame.f_locals + + def log( + self, + *objects: Any, + sep: str = " ", + end: str = "\n", + style: Optional[Union[str, Style]] = None, + justify: Optional[JustifyMethod] = None, + emoji: Optional[bool] = None, + markup: Optional[bool] = None, + highlight: Optional[bool] = None, + log_locals: bool = False, + _stack_offset: int = 1, + ) -> None: + """Log rich content to the terminal. + + Args: + objects (positional args): Objects to log to the terminal. + sep (str, optional): String to write between print data. Defaults to " ". + end (str, optional): String to write at end of print data. Defaults to "\\\\n". + style (Union[str, Style], optional): A style to apply to output. Defaults to None. + justify (str, optional): One of "left", "right", "center", or "full". Defaults to ``None``. + emoji (Optional[bool], optional): Enable emoji code, or ``None`` to use console default. Defaults to None. + markup (Optional[bool], optional): Enable markup, or ``None`` to use console default. Defaults to None. + highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use console default. Defaults to None. + log_locals (bool, optional): Boolean to enable logging of locals where ``log()`` + was called. Defaults to False. + _stack_offset (int, optional): Offset of caller from end of call stack. Defaults to 1. + """ + if not objects: + objects = (NewLine(),) + + render_hooks = self._render_hooks[:] + + with self: + renderables = self._collect_renderables( + objects, + sep, + end, + justify=justify, + emoji=emoji, + markup=markup, + highlight=highlight, + ) + if style is not None: + renderables = [Styled(renderable, style) for renderable in renderables] + + filename, line_no, locals = self._caller_frame_info(_stack_offset) + link_path = None if filename.startswith("<") else os.path.abspath(filename) + path = filename.rpartition(os.sep)[-1] + if log_locals: + locals_map = { + key: value + for key, value in locals.items() + if not key.startswith("__") + } + renderables.append(render_scope(locals_map, title="[i]locals")) + + renderables = [ + self._log_render( + self, + renderables, + log_time=self.get_datetime(), + path=path, + line_no=line_no, + link_path=link_path, + ) + ] + for hook in render_hooks: + renderables = hook.process_renderables(renderables) + new_segments: List[Segment] = [] + extend = new_segments.extend + render = self.render + render_options = self.options + for renderable in renderables: + extend(render(renderable, render_options)) + buffer_extend = self._buffer.extend + for line in Segment.split_and_crop_lines( + new_segments, self.width, pad=False + ): + buffer_extend(line) + + def on_broken_pipe(self) -> None: + """This function is called when a `BrokenPipeError` is raised. + + This can occur when piping Textual output in Linux and macOS. + The default implementation is to exit the app, but you could implement + this method in a subclass to change the behavior. + + See https://docs.python.org/3/library/signal.html#note-on-sigpipe for details. + """ + self.quiet = True + devnull = os.open(os.devnull, os.O_WRONLY) + os.dup2(devnull, sys.stdout.fileno()) + raise SystemExit(1) + + def _check_buffer(self) -> None: + """Check if the buffer may be rendered. Render it if it can (e.g. Console.quiet is False) + Rendering is supported on Windows, Unix and Jupyter environments. For + legacy Windows consoles, the win32 API is called directly. + This method will also record what it renders if recording is enabled via Console.record. + """ + if self.quiet: + del self._buffer[:] + return + + try: + self._write_buffer() + except BrokenPipeError: + self.on_broken_pipe() + + def _write_buffer(self) -> None: + """Write the buffer to the output file.""" + + with self._lock: + if self.record and not self._buffer_index: + with self._record_buffer_lock: + self._record_buffer.extend(self._buffer[:]) + + if self._buffer_index == 0: + if self.is_jupyter: # pragma: no cover + from .jupyter import display + + display(self._buffer, self._render_buffer(self._buffer[:])) + del self._buffer[:] + else: + if WINDOWS: + use_legacy_windows_render = False + if self.legacy_windows: + fileno = get_fileno(self.file) + if fileno is not None: + use_legacy_windows_render = ( + fileno in _STD_STREAMS_OUTPUT + ) + + if use_legacy_windows_render: + from rich._win32_console import LegacyWindowsTerm + from rich._windows_renderer import legacy_windows_render + + buffer = self._buffer[:] + if self.no_color and self._color_system: + buffer = list(Segment.remove_color(buffer)) + + legacy_windows_render(buffer, LegacyWindowsTerm(self.file)) + else: + # Either a non-std stream on legacy Windows, or modern Windows. + text = self._render_buffer(self._buffer[:]) + # https://bugs.python.org/issue37871 + # https://github.com/python/cpython/issues/82052 + # We need to avoid writing more than 32Kb in a single write, due to the above bug + write = self.file.write + # Worse case scenario, every character is 4 bytes of utf-8 + MAX_WRITE = 32 * 1024 // 4 + try: + if len(text) <= MAX_WRITE: + write(text) + else: + batch: List[str] = [] + batch_append = batch.append + size = 0 + for line in text.splitlines(True): + if size + len(line) > MAX_WRITE and batch: + write("".join(batch)) + batch.clear() + size = 0 + batch_append(line) + size += len(line) + if batch: + write("".join(batch)) + batch.clear() + except UnicodeEncodeError as error: + error.reason = f"{error.reason}\n*** You may need to add PYTHONIOENCODING=utf-8 to your environment ***" + raise + else: + text = self._render_buffer(self._buffer[:]) + try: + self.file.write(text) + except UnicodeEncodeError as error: + error.reason = f"{error.reason}\n*** You may need to add PYTHONIOENCODING=utf-8 to your environment ***" + raise + + self.file.flush() + del self._buffer[:] + + def _render_buffer(self, buffer: Iterable[Segment]) -> str: + """Render buffered output, and clear buffer.""" + output: List[str] = [] + append = output.append + color_system = self._color_system + legacy_windows = self.legacy_windows + not_terminal = not self.is_terminal + if self.no_color and color_system: + buffer = Segment.remove_color(buffer) + for text, style, control in buffer: + if style: + append( + style.render( + text, + color_system=color_system, + legacy_windows=legacy_windows, + ) + ) + elif not (not_terminal and control): + append(text) + + rendered = "".join(output) + return rendered + + def input( + self, + prompt: TextType = "", + *, + markup: bool = True, + emoji: bool = True, + password: bool = False, + stream: Optional[TextIO] = None, + ) -> str: + """Displays a prompt and waits for input from the user. The prompt may contain color / style. + + It works in the same way as Python's builtin :func:`input` function and provides elaborate line editing and history features if Python's builtin :mod:`readline` module is previously loaded. + + Args: + prompt (Union[str, Text]): Text to render in the prompt. + markup (bool, optional): Enable console markup (requires a str prompt). Defaults to True. + emoji (bool, optional): Enable emoji (requires a str prompt). Defaults to True. + password: (bool, optional): Hide typed text. Defaults to False. + stream: (TextIO, optional): Optional file to read input from (rather than stdin). Defaults to None. + + Returns: + str: Text read from stdin. + """ + if prompt: + self.print(prompt, markup=markup, emoji=emoji, end="") + if password: + result = getpass("", stream=stream) + else: + if stream: + result = stream.readline() + else: + result = input() + return result + + def export_text(self, *, clear: bool = True, styles: bool = False) -> str: + """Generate text from console contents (requires record=True argument in constructor). + + Args: + clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``. + styles (bool, optional): If ``True``, ansi escape codes will be included. ``False`` for plain text. + Defaults to ``False``. + + Returns: + str: String containing console contents. + + """ + assert ( + self.record + ), "To export console contents set record=True in the constructor or instance" + + with self._record_buffer_lock: + if styles: + text = "".join( + (style.render(text) if style else text) + for text, style, _ in self._record_buffer + ) + else: + text = "".join( + segment.text + for segment in self._record_buffer + if not segment.control + ) + if clear: + del self._record_buffer[:] + return text + + def save_text(self, path: str, *, clear: bool = True, styles: bool = False) -> None: + """Generate text from console and save to a given location (requires record=True argument in constructor). + + Args: + path (str): Path to write text files. + clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``. + styles (bool, optional): If ``True``, ansi style codes will be included. ``False`` for plain text. + Defaults to ``False``. + + """ + text = self.export_text(clear=clear, styles=styles) + with open(path, "w", encoding="utf-8") as write_file: + write_file.write(text) + + def export_html( + self, + *, + theme: Optional[TerminalTheme] = None, + clear: bool = True, + code_format: Optional[str] = None, + inline_styles: bool = False, + ) -> str: + """Generate HTML from console contents (requires record=True argument in constructor). + + Args: + theme (TerminalTheme, optional): TerminalTheme object containing console colors. + clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``. + code_format (str, optional): Format string to render HTML. In addition to '{foreground}', + '{background}', and '{code}', should contain '{stylesheet}' if inline_styles is ``False``. + inline_styles (bool, optional): If ``True`` styles will be inlined in to spans, which makes files + larger but easier to cut and paste markup. If ``False``, styles will be embedded in a style tag. + Defaults to False. + + Returns: + str: String containing console contents as HTML. + """ + assert ( + self.record + ), "To export console contents set record=True in the constructor or instance" + fragments: List[str] = [] + append = fragments.append + _theme = theme or DEFAULT_TERMINAL_THEME + stylesheet = "" + + render_code_format = CONSOLE_HTML_FORMAT if code_format is None else code_format + + with self._record_buffer_lock: + if inline_styles: + for text, style, _ in Segment.filter_control( + Segment.simplify(self._record_buffer) + ): + text = escape(text) + if style: + rule = style.get_html_style(_theme) + if style.link: + text = f'
{text}' + text = f'{text}' if rule else text + append(text) + else: + styles: Dict[str, int] = {} + for text, style, _ in Segment.filter_control( + Segment.simplify(self._record_buffer) + ): + text = escape(text) + if style: + rule = style.get_html_style(_theme) + style_number = styles.setdefault(rule, len(styles) + 1) + if style.link: + text = f'{text}' + else: + text = f'{text}' + append(text) + stylesheet_rules: List[str] = [] + stylesheet_append = stylesheet_rules.append + for style_rule, style_number in styles.items(): + if style_rule: + stylesheet_append(f".r{style_number} {{{style_rule}}}") + stylesheet = "\n".join(stylesheet_rules) + + rendered_code = render_code_format.format( + code="".join(fragments), + stylesheet=stylesheet, + foreground=_theme.foreground_color.hex, + background=_theme.background_color.hex, + ) + if clear: + del self._record_buffer[:] + return rendered_code + + def save_html( + self, + path: str, + *, + theme: Optional[TerminalTheme] = None, + clear: bool = True, + code_format: str = CONSOLE_HTML_FORMAT, + inline_styles: bool = False, + ) -> None: + """Generate HTML from console contents and write to a file (requires record=True argument in constructor). + + Args: + path (str): Path to write html file. + theme (TerminalTheme, optional): TerminalTheme object containing console colors. + clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``. + code_format (str, optional): Format string to render HTML. In addition to '{foreground}', + '{background}', and '{code}', should contain '{stylesheet}' if inline_styles is ``False``. + inline_styles (bool, optional): If ``True`` styles will be inlined in to spans, which makes files + larger but easier to cut and paste markup. If ``False``, styles will be embedded in a style tag. + Defaults to False. + + """ + html = self.export_html( + theme=theme, + clear=clear, + code_format=code_format, + inline_styles=inline_styles, + ) + with open(path, "w", encoding="utf-8") as write_file: + write_file.write(html) + + def export_svg( + self, + *, + title: str = "Rich", + theme: Optional[TerminalTheme] = None, + clear: bool = True, + code_format: str = CONSOLE_SVG_FORMAT, + font_aspect_ratio: float = 0.61, + unique_id: Optional[str] = None, + ) -> str: + """ + Generate an SVG from the console contents (requires record=True in Console constructor). + + Args: + title (str, optional): The title of the tab in the output image + theme (TerminalTheme, optional): The ``TerminalTheme`` object to use to style the terminal + clear (bool, optional): Clear record buffer after exporting. Defaults to ``True`` + code_format (str, optional): Format string used to generate the SVG. Rich will inject a number of variables + into the string in order to form the final SVG output. The default template used and the variables + injected by Rich can be found by inspecting the ``console.CONSOLE_SVG_FORMAT`` variable. + font_aspect_ratio (float, optional): The width to height ratio of the font used in the ``code_format`` + string. Defaults to 0.61, which is the width to height ratio of Fira Code (the default font). + If you aren't specifying a different font inside ``code_format``, you probably don't need this. + unique_id (str, optional): unique id that is used as the prefix for various elements (CSS styles, node + ids). If not set, this defaults to a computed value based on the recorded content. + """ + + from rich.cells import cell_len + + style_cache: Dict[Style, str] = {} + + def get_svg_style(style: Style) -> str: + """Convert a Style to CSS rules for SVG.""" + if style in style_cache: + return style_cache[style] + css_rules = [] + color = ( + _theme.foreground_color + if (style.color is None or style.color.is_default) + else style.color.get_truecolor(_theme) + ) + bgcolor = ( + _theme.background_color + if (style.bgcolor is None or style.bgcolor.is_default) + else style.bgcolor.get_truecolor(_theme) + ) + if style.reverse: + color, bgcolor = bgcolor, color + if style.dim: + color = blend_rgb(color, bgcolor, 0.4) + css_rules.append(f"fill: {color.hex}") + if style.bold: + css_rules.append("font-weight: bold") + if style.italic: + css_rules.append("font-style: italic;") + if style.underline: + css_rules.append("text-decoration: underline;") + if style.strike: + css_rules.append("text-decoration: line-through;") + + css = ";".join(css_rules) + style_cache[style] = css + return css + + _theme = theme or SVG_EXPORT_THEME + + width = self.width + char_height = 20 + char_width = char_height * font_aspect_ratio + line_height = char_height * 1.22 + + margin_top = 1 + margin_right = 1 + margin_bottom = 1 + margin_left = 1 + + padding_top = 40 + padding_right = 8 + padding_bottom = 8 + padding_left = 8 + + padding_width = padding_left + padding_right + padding_height = padding_top + padding_bottom + margin_width = margin_left + margin_right + margin_height = margin_top + margin_bottom + + text_backgrounds: List[str] = [] + text_group: List[str] = [] + classes: Dict[str, int] = {} + style_no = 1 + + def escape_text(text: str) -> str: + """HTML escape text and replace spaces with nbsp.""" + return escape(text).replace(" ", " ") + + def make_tag( + name: str, content: Optional[str] = None, **attribs: object + ) -> str: + """Make a tag from name, content, and attributes.""" + + def stringify(value: object) -> str: + if isinstance(value, (float)): + return format(value, "g") + return str(value) + + tag_attribs = " ".join( + f'{k.lstrip("_").replace("_", "-")}="{stringify(v)}"' + for k, v in attribs.items() + ) + return ( + f"<{name} {tag_attribs}>{content}" + if content + else f"<{name} {tag_attribs}/>" + ) + + with self._record_buffer_lock: + segments = list(Segment.filter_control(self._record_buffer)) + if clear: + self._record_buffer.clear() + + if unique_id is None: + unique_id = "terminal-" + str( + zlib.adler32( + ("".join(repr(segment) for segment in segments)).encode( + "utf-8", + "ignore", + ) + + title.encode("utf-8", "ignore") + ) + ) + y = 0 + for y, line in enumerate(Segment.split_and_crop_lines(segments, length=width)): + x = 0 + for text, style, _control in line: + style = style or Style() + rules = get_svg_style(style) + if rules not in classes: + classes[rules] = style_no + style_no += 1 + class_name = f"r{classes[rules]}" + + if style.reverse: + has_background = True + background = ( + _theme.foreground_color.hex + if style.color is None + else style.color.get_truecolor(_theme).hex + ) + else: + bgcolor = style.bgcolor + has_background = bgcolor is not None and not bgcolor.is_default + background = ( + _theme.background_color.hex + if style.bgcolor is None + else style.bgcolor.get_truecolor(_theme).hex + ) + + text_length = cell_len(text) + if has_background: + text_backgrounds.append( + make_tag( + "rect", + fill=background, + x=x * char_width, + y=y * line_height + 1.5, + width=char_width * text_length, + height=line_height + 0.25, + shape_rendering="crispEdges", + ) + ) + + if text != " " * len(text): + text_group.append( + make_tag( + "text", + escape_text(text), + _class=f"{unique_id}-{class_name}", + x=x * char_width, + y=y * line_height + char_height, + textLength=char_width * len(text), + clip_path=f"url(#{unique_id}-line-{y})", + ) + ) + x += cell_len(text) + + line_offsets = [line_no * line_height + 1.5 for line_no in range(y)] + lines = "\n".join( + f""" + {make_tag("rect", x=0, y=offset, width=char_width * width, height=line_height + 0.25)} + """ + for line_no, offset in enumerate(line_offsets) + ) + + styles = "\n".join( + f".{unique_id}-r{rule_no} {{ {css} }}" for css, rule_no in classes.items() + ) + backgrounds = "".join(text_backgrounds) + matrix = "".join(text_group) + + terminal_width = ceil(width * char_width + padding_width) + terminal_height = (y + 1) * line_height + padding_height + chrome = make_tag( + "rect", + fill=_theme.background_color.hex, + stroke="rgba(255,255,255,0.35)", + stroke_width="1", + x=margin_left, + y=margin_top, + width=terminal_width, + height=terminal_height, + rx=8, + ) + + title_color = _theme.foreground_color.hex + if title: + chrome += make_tag( + "text", + escape_text(title), + _class=f"{unique_id}-title", + fill=title_color, + text_anchor="middle", + x=terminal_width // 2, + y=margin_top + char_height + 6, + ) + chrome += f""" + + + + + + """ + + svg = code_format.format( + unique_id=unique_id, + char_width=char_width, + char_height=char_height, + line_height=line_height, + terminal_width=char_width * width - 1, + terminal_height=(y + 1) * line_height - 1, + width=terminal_width + margin_width, + height=terminal_height + margin_height, + terminal_x=margin_left + padding_left, + terminal_y=margin_top + padding_top, + styles=styles, + chrome=chrome, + backgrounds=backgrounds, + matrix=matrix, + lines=lines, + ) + return svg + + def save_svg( + self, + path: str, + *, + title: str = "Rich", + theme: Optional[TerminalTheme] = None, + clear: bool = True, + code_format: str = CONSOLE_SVG_FORMAT, + font_aspect_ratio: float = 0.61, + unique_id: Optional[str] = None, + ) -> None: + """Generate an SVG file from the console contents (requires record=True in Console constructor). + + Args: + path (str): The path to write the SVG to. + title (str, optional): The title of the tab in the output image + theme (TerminalTheme, optional): The ``TerminalTheme`` object to use to style the terminal + clear (bool, optional): Clear record buffer after exporting. Defaults to ``True`` + code_format (str, optional): Format string used to generate the SVG. Rich will inject a number of variables + into the string in order to form the final SVG output. The default template used and the variables + injected by Rich can be found by inspecting the ``console.CONSOLE_SVG_FORMAT`` variable. + font_aspect_ratio (float, optional): The width to height ratio of the font used in the ``code_format`` + string. Defaults to 0.61, which is the width to height ratio of Fira Code (the default font). + If you aren't specifying a different font inside ``code_format``, you probably don't need this. + unique_id (str, optional): unique id that is used as the prefix for various elements (CSS styles, node + ids). If not set, this defaults to a computed value based on the recorded content. + """ + svg = self.export_svg( + title=title, + theme=theme, + clear=clear, + code_format=code_format, + font_aspect_ratio=font_aspect_ratio, + unique_id=unique_id, + ) + with open(path, "w", encoding="utf-8") as write_file: + write_file.write(svg) + + +def _svg_hash(svg_main_code: str) -> str: + """Returns a unique hash for the given SVG main code. + + Args: + svg_main_code (str): The content we're going to inject in the SVG envelope. + + Returns: + str: a hash of the given content + """ + return str(zlib.adler32(svg_main_code.encode())) + + +if __name__ == "__main__": # pragma: no cover + console = Console(record=True) + + console.log( + "JSONRPC [i]request[/i]", + 5, + 1.3, + True, + False, + None, + { + "jsonrpc": "2.0", + "method": "subtract", + "params": {"minuend": 42, "subtrahend": 23}, + "id": 3, + }, + ) + + console.log("Hello, World!", "{'a': 1}", repr(console)) + + console.print( + { + "name": None, + "empty": [], + "quiz": { + "sport": { + "answered": True, + "q1": { + "question": "Which one is correct team name in NBA?", + "options": [ + "New York Bulls", + "Los Angeles Kings", + "Golden State Warriors", + "Huston Rocket", + ], + "answer": "Huston Rocket", + }, + }, + "maths": { + "answered": False, + "q1": { + "question": "5 + 7 = ?", + "options": [10, 11, 12, 13], + "answer": 12, + }, + "q2": { + "question": "12 - 8 = ?", + "options": [1, 2, 3, 4], + "answer": 4, + }, + }, + }, + } + ) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rich/constrain.py b/TTS/Kokoro/.venv/Lib/site-packages/rich/constrain.py new file mode 100644 index 0000000000000000000000000000000000000000..65fdf56342e8b5b8e181914881025231684e1871 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rich/constrain.py @@ -0,0 +1,37 @@ +from typing import Optional, TYPE_CHECKING + +from .jupyter import JupyterMixin +from .measure import Measurement + +if TYPE_CHECKING: + from .console import Console, ConsoleOptions, RenderableType, RenderResult + + +class Constrain(JupyterMixin): + """Constrain the width of a renderable to a given number of characters. + + Args: + renderable (RenderableType): A renderable object. + width (int, optional): The maximum width (in characters) to render. Defaults to 80. + """ + + def __init__(self, renderable: "RenderableType", width: Optional[int] = 80) -> None: + self.renderable = renderable + self.width = width + + def __rich_console__( + self, console: "Console", options: "ConsoleOptions" + ) -> "RenderResult": + if self.width is None: + yield self.renderable + else: + child_options = options.update_width(min(self.width, options.max_width)) + yield from console.render(self.renderable, child_options) + + def __rich_measure__( + self, console: "Console", options: "ConsoleOptions" + ) -> "Measurement": + if self.width is not None: + options = options.update_width(self.width) + measurement = Measurement.get(console, options, self.renderable) + return measurement diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rich/containers.py b/TTS/Kokoro/.venv/Lib/site-packages/rich/containers.py new file mode 100644 index 0000000000000000000000000000000000000000..901ff8ba6ea0836481a015ed5c627889cc416c03 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rich/containers.py @@ -0,0 +1,167 @@ +from itertools import zip_longest +from typing import ( + TYPE_CHECKING, + Iterable, + Iterator, + List, + Optional, + TypeVar, + Union, + overload, +) + +if TYPE_CHECKING: + from .console import ( + Console, + ConsoleOptions, + JustifyMethod, + OverflowMethod, + RenderResult, + RenderableType, + ) + from .text import Text + +from .cells import cell_len +from .measure import Measurement + +T = TypeVar("T") + + +class Renderables: + """A list subclass which renders its contents to the console.""" + + def __init__( + self, renderables: Optional[Iterable["RenderableType"]] = None + ) -> None: + self._renderables: List["RenderableType"] = ( + list(renderables) if renderables is not None else [] + ) + + def __rich_console__( + self, console: "Console", options: "ConsoleOptions" + ) -> "RenderResult": + """Console render method to insert line-breaks.""" + yield from self._renderables + + def __rich_measure__( + self, console: "Console", options: "ConsoleOptions" + ) -> "Measurement": + dimensions = [ + Measurement.get(console, options, renderable) + for renderable in self._renderables + ] + if not dimensions: + return Measurement(1, 1) + _min = max(dimension.minimum for dimension in dimensions) + _max = max(dimension.maximum for dimension in dimensions) + return Measurement(_min, _max) + + def append(self, renderable: "RenderableType") -> None: + self._renderables.append(renderable) + + def __iter__(self) -> Iterable["RenderableType"]: + return iter(self._renderables) + + +class Lines: + """A list subclass which can render to the console.""" + + def __init__(self, lines: Iterable["Text"] = ()) -> None: + self._lines: List["Text"] = list(lines) + + def __repr__(self) -> str: + return f"Lines({self._lines!r})" + + def __iter__(self) -> Iterator["Text"]: + return iter(self._lines) + + @overload + def __getitem__(self, index: int) -> "Text": + ... + + @overload + def __getitem__(self, index: slice) -> List["Text"]: + ... + + def __getitem__(self, index: Union[slice, int]) -> Union["Text", List["Text"]]: + return self._lines[index] + + def __setitem__(self, index: int, value: "Text") -> "Lines": + self._lines[index] = value + return self + + def __len__(self) -> int: + return self._lines.__len__() + + def __rich_console__( + self, console: "Console", options: "ConsoleOptions" + ) -> "RenderResult": + """Console render method to insert line-breaks.""" + yield from self._lines + + def append(self, line: "Text") -> None: + self._lines.append(line) + + def extend(self, lines: Iterable["Text"]) -> None: + self._lines.extend(lines) + + def pop(self, index: int = -1) -> "Text": + return self._lines.pop(index) + + def justify( + self, + console: "Console", + width: int, + justify: "JustifyMethod" = "left", + overflow: "OverflowMethod" = "fold", + ) -> None: + """Justify and overflow text to a given width. + + Args: + console (Console): Console instance. + width (int): Number of cells available per line. + justify (str, optional): Default justify method for text: "left", "center", "full" or "right". Defaults to "left". + overflow (str, optional): Default overflow for text: "crop", "fold", or "ellipsis". Defaults to "fold". + + """ + from .text import Text + + if justify == "left": + for line in self._lines: + line.truncate(width, overflow=overflow, pad=True) + elif justify == "center": + for line in self._lines: + line.rstrip() + line.truncate(width, overflow=overflow) + line.pad_left((width - cell_len(line.plain)) // 2) + line.pad_right(width - cell_len(line.plain)) + elif justify == "right": + for line in self._lines: + line.rstrip() + line.truncate(width, overflow=overflow) + line.pad_left(width - cell_len(line.plain)) + elif justify == "full": + for line_index, line in enumerate(self._lines): + if line_index == len(self._lines) - 1: + break + words = line.split(" ") + words_size = sum(cell_len(word.plain) for word in words) + num_spaces = len(words) - 1 + spaces = [1 for _ in range(num_spaces)] + index = 0 + if spaces: + while words_size + num_spaces < width: + spaces[len(spaces) - index - 1] += 1 + num_spaces += 1 + index = (index + 1) % len(spaces) + tokens: List[Text] = [] + for index, (word, next_word) in enumerate( + zip_longest(words, words[1:]) + ): + tokens.append(word) + if index < len(spaces): + style = word.get_style_at_offset(console, -1) + next_style = next_word.get_style_at_offset(console, 0) + space_style = style if style == next_style else line.style + tokens.append(Text(" " * spaces[index], style=space_style)) + self[line_index] = Text("").join(tokens) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rich/control.py b/TTS/Kokoro/.venv/Lib/site-packages/rich/control.py new file mode 100644 index 0000000000000000000000000000000000000000..248b0f595a5f101eb43c62ccc090729271be3c43 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rich/control.py @@ -0,0 +1,219 @@ +import time +from typing import TYPE_CHECKING, Callable, Dict, Iterable, List, Union, Final + +from .segment import ControlCode, ControlType, Segment + +if TYPE_CHECKING: + from .console import Console, ConsoleOptions, RenderResult + +STRIP_CONTROL_CODES: Final = [ + 7, # Bell + 8, # Backspace + 11, # Vertical tab + 12, # Form feed + 13, # Carriage return +] +_CONTROL_STRIP_TRANSLATE: Final = { + _codepoint: None for _codepoint in STRIP_CONTROL_CODES +} + +CONTROL_ESCAPE: Final = { + 7: "\\a", + 8: "\\b", + 11: "\\v", + 12: "\\f", + 13: "\\r", +} + +CONTROL_CODES_FORMAT: Dict[int, Callable[..., str]] = { + ControlType.BELL: lambda: "\x07", + ControlType.CARRIAGE_RETURN: lambda: "\r", + ControlType.HOME: lambda: "\x1b[H", + ControlType.CLEAR: lambda: "\x1b[2J", + ControlType.ENABLE_ALT_SCREEN: lambda: "\x1b[?1049h", + ControlType.DISABLE_ALT_SCREEN: lambda: "\x1b[?1049l", + ControlType.SHOW_CURSOR: lambda: "\x1b[?25h", + ControlType.HIDE_CURSOR: lambda: "\x1b[?25l", + ControlType.CURSOR_UP: lambda param: f"\x1b[{param}A", + ControlType.CURSOR_DOWN: lambda param: f"\x1b[{param}B", + ControlType.CURSOR_FORWARD: lambda param: f"\x1b[{param}C", + ControlType.CURSOR_BACKWARD: lambda param: f"\x1b[{param}D", + ControlType.CURSOR_MOVE_TO_COLUMN: lambda param: f"\x1b[{param+1}G", + ControlType.ERASE_IN_LINE: lambda param: f"\x1b[{param}K", + ControlType.CURSOR_MOVE_TO: lambda x, y: f"\x1b[{y+1};{x+1}H", + ControlType.SET_WINDOW_TITLE: lambda title: f"\x1b]0;{title}\x07", +} + + +class Control: + """A renderable that inserts a control code (non printable but may move cursor). + + Args: + *codes (str): Positional arguments are either a :class:`~rich.segment.ControlType` enum or a + tuple of ControlType and an integer parameter + """ + + __slots__ = ["segment"] + + def __init__(self, *codes: Union[ControlType, ControlCode]) -> None: + control_codes: List[ControlCode] = [ + (code,) if isinstance(code, ControlType) else code for code in codes + ] + _format_map = CONTROL_CODES_FORMAT + rendered_codes = "".join( + _format_map[code](*parameters) for code, *parameters in control_codes + ) + self.segment = Segment(rendered_codes, None, control_codes) + + @classmethod + def bell(cls) -> "Control": + """Ring the 'bell'.""" + return cls(ControlType.BELL) + + @classmethod + def home(cls) -> "Control": + """Move cursor to 'home' position.""" + return cls(ControlType.HOME) + + @classmethod + def move(cls, x: int = 0, y: int = 0) -> "Control": + """Move cursor relative to current position. + + Args: + x (int): X offset. + y (int): Y offset. + + Returns: + ~Control: Control object. + + """ + + def get_codes() -> Iterable[ControlCode]: + control = ControlType + if x: + yield ( + control.CURSOR_FORWARD if x > 0 else control.CURSOR_BACKWARD, + abs(x), + ) + if y: + yield ( + control.CURSOR_DOWN if y > 0 else control.CURSOR_UP, + abs(y), + ) + + control = cls(*get_codes()) + return control + + @classmethod + def move_to_column(cls, x: int, y: int = 0) -> "Control": + """Move to the given column, optionally add offset to row. + + Returns: + x (int): absolute x (column) + y (int): optional y offset (row) + + Returns: + ~Control: Control object. + """ + + return ( + cls( + (ControlType.CURSOR_MOVE_TO_COLUMN, x), + ( + ControlType.CURSOR_DOWN if y > 0 else ControlType.CURSOR_UP, + abs(y), + ), + ) + if y + else cls((ControlType.CURSOR_MOVE_TO_COLUMN, x)) + ) + + @classmethod + def move_to(cls, x: int, y: int) -> "Control": + """Move cursor to absolute position. + + Args: + x (int): x offset (column) + y (int): y offset (row) + + Returns: + ~Control: Control object. + """ + return cls((ControlType.CURSOR_MOVE_TO, x, y)) + + @classmethod + def clear(cls) -> "Control": + """Clear the screen.""" + return cls(ControlType.CLEAR) + + @classmethod + def show_cursor(cls, show: bool) -> "Control": + """Show or hide the cursor.""" + return cls(ControlType.SHOW_CURSOR if show else ControlType.HIDE_CURSOR) + + @classmethod + def alt_screen(cls, enable: bool) -> "Control": + """Enable or disable alt screen.""" + if enable: + return cls(ControlType.ENABLE_ALT_SCREEN, ControlType.HOME) + else: + return cls(ControlType.DISABLE_ALT_SCREEN) + + @classmethod + def title(cls, title: str) -> "Control": + """Set the terminal window title + + Args: + title (str): The new terminal window title + """ + return cls((ControlType.SET_WINDOW_TITLE, title)) + + def __str__(self) -> str: + return self.segment.text + + def __rich_console__( + self, console: "Console", options: "ConsoleOptions" + ) -> "RenderResult": + if self.segment.text: + yield self.segment + + +def strip_control_codes( + text: str, _translate_table: Dict[int, None] = _CONTROL_STRIP_TRANSLATE +) -> str: + """Remove control codes from text. + + Args: + text (str): A string possibly contain control codes. + + Returns: + str: String with control codes removed. + """ + return text.translate(_translate_table) + + +def escape_control_codes( + text: str, + _translate_table: Dict[int, str] = CONTROL_ESCAPE, +) -> str: + """Replace control codes with their "escaped" equivalent in the given text. + (e.g. "\b" becomes "\\b") + + Args: + text (str): A string possibly containing control codes. + + Returns: + str: String with control codes replaced with their escaped version. + """ + return text.translate(_translate_table) + + +if __name__ == "__main__": # pragma: no cover + from rich.console import Console + + console = Console() + console.print("Look at the title of your terminal window ^") + # console.print(Control((ControlType.SET_WINDOW_TITLE, "Hello, world!"))) + for i in range(10): + console.set_window_title("🚀 Loading" + "." * i) + time.sleep(0.5) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rich/default_styles.py b/TTS/Kokoro/.venv/Lib/site-packages/rich/default_styles.py new file mode 100644 index 0000000000000000000000000000000000000000..c18b6095e48ae76a92b8c67b04a179c2e68a7371 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rich/default_styles.py @@ -0,0 +1,195 @@ +from typing import Dict + +from .style import Style + +DEFAULT_STYLES: Dict[str, Style] = { + "none": Style.null(), + "reset": Style( + color="default", + bgcolor="default", + dim=False, + bold=False, + italic=False, + underline=False, + blink=False, + blink2=False, + reverse=False, + conceal=False, + strike=False, + ), + "dim": Style(dim=True), + "bright": Style(dim=False), + "bold": Style(bold=True), + "strong": Style(bold=True), + "code": Style(reverse=True, bold=True), + "italic": Style(italic=True), + "emphasize": Style(italic=True), + "underline": Style(underline=True), + "blink": Style(blink=True), + "blink2": Style(blink2=True), + "reverse": Style(reverse=True), + "strike": Style(strike=True), + "black": Style(color="black"), + "red": Style(color="red"), + "green": Style(color="green"), + "yellow": Style(color="yellow"), + "magenta": Style(color="magenta"), + "cyan": Style(color="cyan"), + "white": Style(color="white"), + "inspect.attr": Style(color="yellow", italic=True), + "inspect.attr.dunder": Style(color="yellow", italic=True, dim=True), + "inspect.callable": Style(bold=True, color="red"), + "inspect.async_def": Style(italic=True, color="bright_cyan"), + "inspect.def": Style(italic=True, color="bright_cyan"), + "inspect.class": Style(italic=True, color="bright_cyan"), + "inspect.error": Style(bold=True, color="red"), + "inspect.equals": Style(), + "inspect.help": Style(color="cyan"), + "inspect.doc": Style(dim=True), + "inspect.value.border": Style(color="green"), + "live.ellipsis": Style(bold=True, color="red"), + "layout.tree.row": Style(dim=False, color="red"), + "layout.tree.column": Style(dim=False, color="blue"), + "logging.keyword": Style(bold=True, color="yellow"), + "logging.level.notset": Style(dim=True), + "logging.level.debug": Style(color="green"), + "logging.level.info": Style(color="blue"), + "logging.level.warning": Style(color="yellow"), + "logging.level.error": Style(color="red", bold=True), + "logging.level.critical": Style(color="red", bold=True, reverse=True), + "log.level": Style.null(), + "log.time": Style(color="cyan", dim=True), + "log.message": Style.null(), + "log.path": Style(dim=True), + "repr.ellipsis": Style(color="yellow"), + "repr.indent": Style(color="green", dim=True), + "repr.error": Style(color="red", bold=True), + "repr.str": Style(color="green", italic=False, bold=False), + "repr.brace": Style(bold=True), + "repr.comma": Style(bold=True), + "repr.ipv4": Style(bold=True, color="bright_green"), + "repr.ipv6": Style(bold=True, color="bright_green"), + "repr.eui48": Style(bold=True, color="bright_green"), + "repr.eui64": Style(bold=True, color="bright_green"), + "repr.tag_start": Style(bold=True), + "repr.tag_name": Style(color="bright_magenta", bold=True), + "repr.tag_contents": Style(color="default"), + "repr.tag_end": Style(bold=True), + "repr.attrib_name": Style(color="yellow", italic=False), + "repr.attrib_equal": Style(bold=True), + "repr.attrib_value": Style(color="magenta", italic=False), + "repr.number": Style(color="cyan", bold=True, italic=False), + "repr.number_complex": Style(color="cyan", bold=True, italic=False), # same + "repr.bool_true": Style(color="bright_green", italic=True), + "repr.bool_false": Style(color="bright_red", italic=True), + "repr.none": Style(color="magenta", italic=True), + "repr.url": Style(underline=True, color="bright_blue", italic=False, bold=False), + "repr.uuid": Style(color="bright_yellow", bold=False), + "repr.call": Style(color="magenta", bold=True), + "repr.path": Style(color="magenta"), + "repr.filename": Style(color="bright_magenta"), + "rule.line": Style(color="bright_green"), + "rule.text": Style.null(), + "json.brace": Style(bold=True), + "json.bool_true": Style(color="bright_green", italic=True), + "json.bool_false": Style(color="bright_red", italic=True), + "json.null": Style(color="magenta", italic=True), + "json.number": Style(color="cyan", bold=True, italic=False), + "json.str": Style(color="green", italic=False, bold=False), + "json.key": Style(color="blue", bold=True), + "prompt": Style.null(), + "prompt.choices": Style(color="magenta", bold=True), + "prompt.default": Style(color="cyan", bold=True), + "prompt.invalid": Style(color="red"), + "prompt.invalid.choice": Style(color="red"), + "pretty": Style.null(), + "scope.border": Style(color="blue"), + "scope.key": Style(color="yellow", italic=True), + "scope.key.special": Style(color="yellow", italic=True, dim=True), + "scope.equals": Style(color="red"), + "table.header": Style(bold=True), + "table.footer": Style(bold=True), + "table.cell": Style.null(), + "table.title": Style(italic=True), + "table.caption": Style(italic=True, dim=True), + "traceback.error": Style(color="red", italic=True), + "traceback.border.syntax_error": Style(color="bright_red"), + "traceback.border": Style(color="red"), + "traceback.text": Style.null(), + "traceback.title": Style(color="red", bold=True), + "traceback.exc_type": Style(color="bright_red", bold=True), + "traceback.exc_value": Style.null(), + "traceback.offset": Style(color="bright_red", bold=True), + "traceback.error_range": Style(underline=True, bold=True), + "traceback.note": Style(color="green", bold=True), + "traceback.group.border": Style(color="magenta"), + "bar.back": Style(color="grey23"), + "bar.complete": Style(color="rgb(249,38,114)"), + "bar.finished": Style(color="rgb(114,156,31)"), + "bar.pulse": Style(color="rgb(249,38,114)"), + "progress.description": Style.null(), + "progress.filesize": Style(color="green"), + "progress.filesize.total": Style(color="green"), + "progress.download": Style(color="green"), + "progress.elapsed": Style(color="yellow"), + "progress.percentage": Style(color="magenta"), + "progress.remaining": Style(color="cyan"), + "progress.data.speed": Style(color="red"), + "progress.spinner": Style(color="green"), + "status.spinner": Style(color="green"), + "tree": Style(), + "tree.line": Style(), + "markdown.paragraph": Style(), + "markdown.text": Style(), + "markdown.em": Style(italic=True), + "markdown.emph": Style(italic=True), # For commonmark backwards compatibility + "markdown.strong": Style(bold=True), + "markdown.code": Style(bold=True, color="cyan", bgcolor="black"), + "markdown.code_block": Style(color="cyan", bgcolor="black"), + "markdown.block_quote": Style(color="magenta"), + "markdown.list": Style(color="cyan"), + "markdown.item": Style(), + "markdown.item.bullet": Style(bold=True), + "markdown.item.number": Style(color="cyan"), + "markdown.hr": Style(dim=True), + "markdown.h1.border": Style(), + "markdown.h1": Style(bold=True, underline=True), + "markdown.h2": Style(color="magenta", underline=True), + "markdown.h3": Style(color="magenta", bold=True), + "markdown.h4": Style(color="magenta", italic=True), + "markdown.h5": Style(italic=True), + "markdown.h6": Style(dim=True), + "markdown.h7": Style(italic=True, dim=True), + "markdown.link": Style(color="bright_blue"), + "markdown.link_url": Style(color="blue", underline=True), + "markdown.s": Style(strike=True), + "markdown.table.border": Style(color="cyan"), + "markdown.table.header": Style(color="cyan", bold=False), + "iso8601.date": Style(color="blue"), + "iso8601.time": Style(color="magenta"), + "iso8601.timezone": Style(color="yellow"), +} + + +if __name__ == "__main__": # pragma: no cover + import argparse + import io + + from rich.console import Console + from rich.table import Table + from rich.text import Text + + parser = argparse.ArgumentParser() + parser.add_argument("--html", action="store_true", help="Export as HTML table") + args = parser.parse_args() + html: bool = args.html + console = Console(record=True, width=70, file=io.StringIO()) if html else Console() + + table = Table("Name", "Styling") + + for style_name, style in DEFAULT_STYLES.items(): + table.add_row(Text(style_name, style=style), str(style)) + + console.print(table) + if html: + print(console.export_html(inline_styles=True)) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rich/diagnose.py b/TTS/Kokoro/.venv/Lib/site-packages/rich/diagnose.py new file mode 100644 index 0000000000000000000000000000000000000000..9d5ff3ec3299994c61171859854c16242468ed8b --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rich/diagnose.py @@ -0,0 +1,39 @@ +import os +import platform + +from rich import inspect +from rich.console import Console, get_windows_console_features +from rich.panel import Panel +from rich.pretty import Pretty + + +def report() -> None: # pragma: no cover + """Print a report to the terminal with debugging information""" + console = Console() + inspect(console) + features = get_windows_console_features() + inspect(features) + + env_names = ( + "CLICOLOR", + "COLORTERM", + "COLUMNS", + "JPY_PARENT_PID", + "JUPYTER_COLUMNS", + "JUPYTER_LINES", + "LINES", + "NO_COLOR", + "TERM_PROGRAM", + "TERM", + "TTY_COMPATIBLE", + "TTY_INTERACTIVE", + "VSCODE_VERBOSE_LOGGING", + ) + env = {name: os.getenv(name) for name in env_names} + console.print(Panel.fit((Pretty(env)), title="[b]Environment Variables")) + + console.print(f'platform="{platform.system()}"') + + +if __name__ == "__main__": # pragma: no cover + report() diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rich/emoji.py b/TTS/Kokoro/.venv/Lib/site-packages/rich/emoji.py new file mode 100644 index 0000000000000000000000000000000000000000..9433e6fb3ffb1f2e3f1f868131f82525d0e455db --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rich/emoji.py @@ -0,0 +1,91 @@ +import sys +from typing import TYPE_CHECKING, Optional, Union, Literal + +from .jupyter import JupyterMixin +from .segment import Segment +from .style import Style +from ._emoji_codes import EMOJI +from ._emoji_replace import _emoji_replace + + +if TYPE_CHECKING: + from .console import Console, ConsoleOptions, RenderResult + + +EmojiVariant = Literal["emoji", "text"] + + +class NoEmoji(Exception): + """No emoji by that name.""" + + +class Emoji(JupyterMixin): + __slots__ = ["name", "style", "_char", "variant"] + + VARIANTS = {"text": "\uFE0E", "emoji": "\uFE0F"} + + def __init__( + self, + name: str, + style: Union[str, Style] = "none", + variant: Optional[EmojiVariant] = None, + ) -> None: + """A single emoji character. + + Args: + name (str): Name of emoji. + style (Union[str, Style], optional): Optional style. Defaults to None. + + Raises: + NoEmoji: If the emoji doesn't exist. + """ + self.name = name + self.style = style + self.variant = variant + try: + self._char = EMOJI[name] + except KeyError: + raise NoEmoji(f"No emoji called {name!r}") + if variant is not None: + self._char += self.VARIANTS.get(variant, "") + + @classmethod + def replace(cls, text: str) -> str: + """Replace emoji markup with corresponding unicode characters. + + Args: + text (str): A string with emojis codes, e.g. "Hello :smiley:!" + + Returns: + str: A string with emoji codes replaces with actual emoji. + """ + return _emoji_replace(text) + + def __repr__(self) -> str: + return f"" + + def __str__(self) -> str: + return self._char + + def __rich_console__( + self, console: "Console", options: "ConsoleOptions" + ) -> "RenderResult": + yield Segment(self._char, console.get_style(self.style)) + + +if __name__ == "__main__": # pragma: no cover + import sys + + from rich.columns import Columns + from rich.console import Console + + console = Console(record=True) + + columns = Columns( + (f":{name}: {name}" for name in sorted(EMOJI.keys()) if "\u200D" not in name), + column_first=True, + ) + + console.print(columns) + if len(sys.argv) > 1: + console.save_html(sys.argv[1]) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rich/errors.py b/TTS/Kokoro/.venv/Lib/site-packages/rich/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..0bcbe53ef59373c608e62ea285536f8b22b47ecb --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rich/errors.py @@ -0,0 +1,34 @@ +class ConsoleError(Exception): + """An error in console operation.""" + + +class StyleError(Exception): + """An error in styles.""" + + +class StyleSyntaxError(ConsoleError): + """Style was badly formatted.""" + + +class MissingStyle(StyleError): + """No such style.""" + + +class StyleStackError(ConsoleError): + """Style stack is invalid.""" + + +class NotRenderableError(ConsoleError): + """Object is not renderable.""" + + +class MarkupError(ConsoleError): + """Markup was badly formatted.""" + + +class LiveError(ConsoleError): + """Error related to Live display.""" + + +class NoAltScreen(ConsoleError): + """Alt screen mode was required.""" diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rich/file_proxy.py b/TTS/Kokoro/.venv/Lib/site-packages/rich/file_proxy.py new file mode 100644 index 0000000000000000000000000000000000000000..4b0b0da6c2a62b2b1468c35ddd69f1bbb9b91aa8 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rich/file_proxy.py @@ -0,0 +1,57 @@ +import io +from typing import IO, TYPE_CHECKING, Any, List + +from .ansi import AnsiDecoder +from .text import Text + +if TYPE_CHECKING: + from .console import Console + + +class FileProxy(io.TextIOBase): + """Wraps a file (e.g. sys.stdout) and redirects writes to a console.""" + + def __init__(self, console: "Console", file: IO[str]) -> None: + self.__console = console + self.__file = file + self.__buffer: List[str] = [] + self.__ansi_decoder = AnsiDecoder() + + @property + def rich_proxied_file(self) -> IO[str]: + """Get proxied file.""" + return self.__file + + def __getattr__(self, name: str) -> Any: + return getattr(self.__file, name) + + def write(self, text: str) -> int: + if not isinstance(text, str): + raise TypeError(f"write() argument must be str, not {type(text).__name__}") + buffer = self.__buffer + lines: List[str] = [] + while text: + line, new_line, text = text.partition("\n") + if new_line: + lines.append("".join(buffer) + line) + buffer.clear() + else: + buffer.append(line) + break + if lines: + console = self.__console + with console: + output = Text("\n").join( + self.__ansi_decoder.decode_line(line) for line in lines + ) + console.print(output) + return len(text) + + def flush(self) -> None: + output = "".join(self.__buffer) + if output: + self.__console.print(output) + del self.__buffer[:] + + def fileno(self) -> int: + return self.__file.fileno() diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rich/filesize.py b/TTS/Kokoro/.venv/Lib/site-packages/rich/filesize.py new file mode 100644 index 0000000000000000000000000000000000000000..83bc9118d2bdb8983f863063687c2ea394a9abb1 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rich/filesize.py @@ -0,0 +1,88 @@ +"""Functions for reporting filesizes. Borrowed from https://github.com/PyFilesystem/pyfilesystem2 + +The functions declared in this module should cover the different +use cases needed to generate a string representation of a file size +using several different units. Since there are many standards regarding +file size units, three different functions have been implemented. + +See Also: + * `Wikipedia: Binary prefix `_ + +""" + +__all__ = ["decimal"] + +from typing import Iterable, List, Optional, Tuple + + +def _to_str( + size: int, + suffixes: Iterable[str], + base: int, + *, + precision: Optional[int] = 1, + separator: Optional[str] = " ", +) -> str: + if size == 1: + return "1 byte" + elif size < base: + return f"{size:,} bytes" + + for i, suffix in enumerate(suffixes, 2): # noqa: B007 + unit = base**i + if size < unit: + break + return "{:,.{precision}f}{separator}{}".format( + (base * size / unit), + suffix, + precision=precision, + separator=separator, + ) + + +def pick_unit_and_suffix(size: int, suffixes: List[str], base: int) -> Tuple[int, str]: + """Pick a suffix and base for the given size.""" + for i, suffix in enumerate(suffixes): + unit = base**i + if size < unit * base: + break + return unit, suffix + + +def decimal( + size: int, + *, + precision: Optional[int] = 1, + separator: Optional[str] = " ", +) -> str: + """Convert a filesize in to a string (powers of 1000, SI prefixes). + + In this convention, ``1000 B = 1 kB``. + + This is typically the format used to advertise the storage + capacity of USB flash drives and the like (*256 MB* meaning + actually a storage capacity of more than *256 000 000 B*), + or used by **Mac OS X** since v10.6 to report file sizes. + + Arguments: + int (size): A file size. + int (precision): The number of decimal places to include (default = 1). + str (separator): The string to separate the value from the units (default = " "). + + Returns: + `str`: A string containing a abbreviated file size and units. + + Example: + >>> filesize.decimal(30000) + '30.0 kB' + >>> filesize.decimal(30000, precision=2, separator="") + '30.00kB' + + """ + return _to_str( + size, + ("kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"), + 1000, + precision=precision, + separator=separator, + ) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/rich/highlighter.py b/TTS/Kokoro/.venv/Lib/site-packages/rich/highlighter.py new file mode 100644 index 0000000000000000000000000000000000000000..df28048f8842bdab06631189ca474f869ab3d544 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/rich/highlighter.py @@ -0,0 +1,232 @@ +import re +from abc import ABC, abstractmethod +from typing import ClassVar, Sequence, Union + +from .text import Span, Text + + +def _combine_regex(*regexes: str) -> str: + """Combine a number of regexes in to a single regex. + + Returns: + str: New regex with all regexes ORed together. + """ + return "|".join(regexes) + + +class Highlighter(ABC): + """Abstract base class for highlighters.""" + + def __call__(self, text: Union[str, Text]) -> Text: + """Highlight a str or Text instance. + + Args: + text (Union[str, ~Text]): Text to highlight. + + Raises: + TypeError: If not called with text or str. + + Returns: + Text: A test instance with highlighting applied. + """ + if isinstance(text, str): + highlight_text = Text(text) + elif isinstance(text, Text): + highlight_text = text.copy() + else: + raise TypeError(f"str or Text instance required, not {text!r}") + self.highlight(highlight_text) + return highlight_text + + @abstractmethod + def highlight(self, text: Text) -> None: + """Apply highlighting in place to text. + + Args: + text (~Text): A text object highlight. + """ + + +class NullHighlighter(Highlighter): + """A highlighter object that doesn't highlight. + + May be used to disable highlighting entirely. + + """ + + def highlight(self, text: Text) -> None: + """Nothing to do""" + + +class RegexHighlighter(Highlighter): + """Applies highlighting from a list of regular expressions.""" + + highlights: ClassVar[Sequence[str]] = [] + base_style: ClassVar[str] = "" + + def highlight(self, text: Text) -> None: + """Highlight :class:`rich.text.Text` using regular expressions. + + Args: + text (~Text): Text to highlighted. + + """ + + highlight_regex = text.highlight_regex + for re_highlight in self.highlights: + highlight_regex(re_highlight, style_prefix=self.base_style) + + +class ReprHighlighter(RegexHighlighter): + """Highlights the text typically produced from ``__repr__`` methods.""" + + base_style = "repr." + highlights: ClassVar[Sequence[str]] = [ + r"(?P<)(?P[-\w.:|]*)(?P[\w\W]*)(?P>)", + r'(?P[\w_]{1,50})=(?P"?[\w_]+"?)?', + r"(?P[][{}()])", + _combine_regex( + r"(?P[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})", + r"(?P([A-Fa-f0-9]{1,4}::?){1,7}[A-Fa-f0-9]{1,4})", + r"(?P(?:[0-9A-Fa-f]{1,2}-){7}[0-9A-Fa-f]{1,2}|(?:[0-9A-Fa-f]{1,2}:){7}[0-9A-Fa-f]{1,2}|(?:[0-9A-Fa-f]{4}\.){3}[0-9A-Fa-f]{4})", + r"(?P(?:[0-9A-Fa-f]{1,2}-){5}[0-9A-Fa-f]{1,2}|(?:[0-9A-Fa-f]{1,2}:){5}[0-9A-Fa-f]{1,2}|(?:[0-9A-Fa-f]{4}\.){2}[0-9A-Fa-f]{4})", + r"(?P[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})", + r"(?P[\w.]*?)\(", + r"\b(?PTrue)\b|\b(?PFalse)\b|\b(?PNone)\b", + r"(?P\.\.\.)", + r"(?P(?(?\B(/[-\w._+]+)*\/)(?P[-\w._+]*)?", + r"(?b?'''.*?(?(file|https|http|ws|wss)://[-0-9a-zA-Z$_+!`(),.?/;:&=%#~@]*)", + ), + ] + + +class JSONHighlighter(RegexHighlighter): + """Highlights JSON""" + + # Captures the start and end of JSON strings, handling escaped quotes + JSON_STR = r"(?b?\".*?(?[\{\[\(\)\]\}])", + r"\b(?Ptrue)\b|\b(?Pfalse)\b|\b(?Pnull)\b", + r"(?P(? None: + super().highlight(text) + + # Additional work to handle highlighting JSON keys + plain = text.plain + append = text.spans.append + whitespace = self.JSON_WHITESPACE + for match in re.finditer(self.JSON_STR, plain): + start, end = match.span() + cursor = end + while cursor < len(plain): + char = plain[cursor] + cursor += 1 + if char == ":": + append(Span(start, end, "json.key")) + elif char in whitespace: + continue + break + + +class ISO8601Highlighter(RegexHighlighter): + """Highlights the ISO8601 date time strings. + Regex reference: https://www.oreilly.com/library/view/regular-expressions-cookbook/9781449327453/ch04s07.html + """ + + base_style: ClassVar[str] = "iso8601." + highlights: ClassVar[Sequence[str]] = [ + # + # Dates + # + # Calendar month (e.g. 2008-08). The hyphen is required + r"^(?P[0-9]{4})-(?P1[0-2]|0[1-9])$", + # Calendar date w/o hyphens (e.g. 20080830) + r"^(?P(?P[0-9]{4})(?P1[0-2]|0[1-9])(?P3[01]|0[1-9]|[12][0-9]))$", + # Ordinal date (e.g. 2008-243). The hyphen is optional + r"^(?P(?P[0-9]{4})-?(?P36[0-6]|3[0-5][0-9]|[12][0-9]{2}|0[1-9][0-9]|00[1-9]))$", + # + # Weeks + # + # Week of the year (e.g., 2008-W35). The hyphen is optional + r"^(?P(?P[0-9]{4})-?W(?P5[0-3]|[1-4][0-9]|0[1-9]))$", + # Week date (e.g., 2008-W35-6). The hyphens are optional + r"^(?P(?P[0-9]{4})-?W(?P5[0-3]|[1-4][0-9]|0[1-9])-?(?P[1-7]))$", + # + # Times + # + # Hours and minutes (e.g., 17:21). The colon is optional + r"^(?P