giancap61 commited on
Commit
1983329
·
verified ·
1 Parent(s): e0e418d

Add files using upload-large-folder tool

Browse files
Files changed (50) hide show
  1. LLM/llama.cpp-cpu/convert_hf_to_gguf.py +0 -0
  2. LLM/llama.cpp-cpu/ggml.dll +0 -0
  3. LLM/llama.cpp-cpu/llama-gemma3-cli.exe +0 -0
  4. LLM/llama.cpp-cpu/llama-gguf-split.exe +0 -0
  5. LLM/llama.cpp-cpu/llama-llava-cli.exe +0 -0
  6. LLM/llama.cpp-cpu/llama-minicpmv-cli.exe +0 -0
  7. LLM/llama.cpp-cpu/llama-qwen2vl-cli.exe +0 -0
  8. LLM/llama.cpp-cuda12/convert_hf_to_gguf.py.txt +0 -0
  9. LLM/llama.cpp-cuda12/ggml.dll +0 -0
  10. LLM/llama.cpp-cuda12/llama-gemma3-cli.exe +0 -0
  11. LLM/llama.cpp-cuda12/llama-gguf-split.exe +0 -0
  12. LLM/llama.cpp-cuda12/llama-llava-cli.exe +0 -0
  13. LLM/llama.cpp-cuda12/llama-minicpmv-cli.exe +0 -0
  14. LLM/llama.cpp-cuda12/llama-qwen2vl-cli.exe +0 -0
  15. TTS/Kokoro/.venv/Lib/site-packages/_soundfile.py +11 -0
  16. TTS/Kokoro/.venv/Lib/site-packages/addict-2.4.0.dist-info/INSTALLER +1 -0
  17. TTS/Kokoro/.venv/Lib/site-packages/addict-2.4.0.dist-info/LICENSE +22 -0
  18. TTS/Kokoro/.venv/Lib/site-packages/addict-2.4.0.dist-info/METADATA +23 -0
  19. TTS/Kokoro/.venv/Lib/site-packages/addict-2.4.0.dist-info/RECORD +10 -0
  20. TTS/Kokoro/.venv/Lib/site-packages/addict-2.4.0.dist-info/WHEEL +5 -0
  21. TTS/Kokoro/.venv/Lib/site-packages/addict-2.4.0.dist-info/top_level.txt +1 -0
  22. TTS/Kokoro/.venv/Lib/site-packages/addict/__init__.py +10 -0
  23. TTS/Kokoro/.venv/Lib/site-packages/addict/addict.py +159 -0
  24. TTS/Kokoro/.venv/Lib/site-packages/annotated_doc-0.0.4.dist-info/INSTALLER +1 -0
  25. TTS/Kokoro/.venv/Lib/site-packages/annotated_doc-0.0.4.dist-info/METADATA +145 -0
  26. TTS/Kokoro/.venv/Lib/site-packages/annotated_doc-0.0.4.dist-info/RECORD +11 -0
  27. TTS/Kokoro/.venv/Lib/site-packages/annotated_doc-0.0.4.dist-info/WHEEL +4 -0
  28. TTS/Kokoro/.venv/Lib/site-packages/annotated_doc-0.0.4.dist-info/entry_points.txt +4 -0
  29. TTS/Kokoro/.venv/Lib/site-packages/annotated_doc/__init__.py +3 -0
  30. TTS/Kokoro/.venv/Lib/site-packages/annotated_doc/main.py +36 -0
  31. TTS/Kokoro/.venv/Lib/site-packages/annotated_doc/py.typed +0 -0
  32. TTS/Kokoro/.venv/Lib/site-packages/annotated_types-0.7.0.dist-info/INSTALLER +1 -0
  33. TTS/Kokoro/.venv/Lib/site-packages/annotated_types-0.7.0.dist-info/RECORD +10 -0
  34. TTS/Kokoro/.venv/Lib/site-packages/annotated_types/__init__.py +432 -0
  35. TTS/Kokoro/.venv/Lib/site-packages/annotated_types/py.typed +0 -0
  36. TTS/Kokoro/.venv/Lib/site-packages/annotated_types/test_cases.py +151 -0
  37. TTS/Kokoro/.venv/Lib/site-packages/docopt.py +579 -0
  38. TTS/Kokoro/.venv/Lib/site-packages/isympy.py +342 -0
  39. TTS/Kokoro/.venv/Lib/site-packages/six.py +1003 -0
  40. TTS/Kokoro/.venv/Lib/site-packages/soundfile.py +1674 -0
  41. TTS/Kokoro/.venv/Lib/site-packages/typing_extensions.py +0 -0
  42. TTS/Kokoro/.venv/Scripts/Activate.ps1 +528 -0
  43. TTS/Kokoro/.venv/Scripts/activate +71 -0
  44. TTS/Kokoro/.venv/Scripts/activate.bat +34 -0
  45. TTS/Kokoro/.venv/Scripts/deactivate.bat +22 -0
  46. TTS/Kokoro/.venv/Scripts/num2words +95 -0
  47. TTS/Kokoro/.venv/pyvenv.cfg +5 -0
  48. TTS/Kokoro/kokoro_server.py +81 -0
  49. TTS/Kokoro/kokoro_tts.py +29 -0
  50. TTS/Piper/onnxruntime_providers_shared.dll +0 -0
LLM/llama.cpp-cpu/convert_hf_to_gguf.py ADDED
The diff for this file is too large to render. See raw diff
 
LLM/llama.cpp-cpu/ggml.dll ADDED
Binary file (96.8 kB). View file
 
LLM/llama.cpp-cpu/llama-gemma3-cli.exe ADDED
Binary file (27.6 kB). View file
 
LLM/llama.cpp-cpu/llama-gguf-split.exe ADDED
Binary file (63.5 kB). View file
 
LLM/llama.cpp-cpu/llama-llava-cli.exe ADDED
Binary file (27.6 kB). View file
 
LLM/llama.cpp-cpu/llama-minicpmv-cli.exe ADDED
Binary file (27.6 kB). View file
 
LLM/llama.cpp-cpu/llama-qwen2vl-cli.exe ADDED
Binary file (27.6 kB). View file
 
LLM/llama.cpp-cuda12/convert_hf_to_gguf.py.txt ADDED
The diff for this file is too large to render. See raw diff
 
LLM/llama.cpp-cuda12/ggml.dll ADDED
Binary file (96.8 kB). View file
 
LLM/llama.cpp-cuda12/llama-gemma3-cli.exe ADDED
Binary file (27.6 kB). View file
 
LLM/llama.cpp-cuda12/llama-gguf-split.exe ADDED
Binary file (63.5 kB). View file
 
LLM/llama.cpp-cuda12/llama-llava-cli.exe ADDED
Binary file (27.6 kB). View file
 
LLM/llama.cpp-cuda12/llama-minicpmv-cli.exe ADDED
Binary file (27.6 kB). View file
 
LLM/llama.cpp-cuda12/llama-qwen2vl-cli.exe ADDED
Binary file (27.6 kB). View file
 
TTS/Kokoro/.venv/Lib/site-packages/_soundfile.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # auto-generated file
2
+ import _cffi_backend
3
+
4
+ ffi = _cffi_backend.FFI('_soundfile',
5
+ _version = 0x2601,
6
+ _types = b'\x00\x00\x17\x0D\x00\x00\x6D\x03\x00\x00\x07\x01\x00\x00\x6C\x03\x00\x00\x7A\x03\x00\x00\x00\x0F\x00\x00\x17\x0D\x00\x00\x6F\x03\x00\x00\x07\x01\x00\x00\x03\x11\x00\x00\x00\x0F\x00\x00\x17\x0D\x00\x00\x07\x01\x00\x00\x07\x01\x00\x00\x03\x11\x00\x00\x07\x01\x00\x00\x00\x0F\x00\x00\x17\x0D\x00\x00\x7B\x03\x00\x00\x07\x01\x00\x00\x03\x11\x00\x00\x00\x0F\x00\x00\x07\x0D\x00\x00\x6E\x03\x00\x00\x00\x0F\x00\x00\x07\x0D\x00\x00\x17\x11\x00\x00\x07\x01\x00\x00\x00\x0F\x00\x00\x07\x0D\x00\x00\x07\x01\x00\x00\x00\x0F\x00\x00\x07\x0D\x00\x00\x00\x0F\x00\x00\x02\x0D\x00\x00\x6C\x03\x00\x00\x00\x0F\x00\x00\x02\x0D\x00\x00\x17\x11\x00\x00\x00\x0F\x00\x00\x02\x0D\x00\x00\x17\x11\x00\x00\x6F\x03\x00\x00\x1C\x01\x00\x00\x00\x0F\x00\x00\x02\x0D\x00\x00\x17\x11\x00\x00\x07\x01\x00\x00\x07\x11\x00\x00\x00\x0F\x00\x00\x02\x0D\x00\x00\x17\x11\x00\x00\x07\x01\x00\x00\x04\x11\x00\x00\x07\x01\x00\x00\x00\x0F\x00\x00\x3B\x0D\x00\x00\x17\x11\x00\x00\x70\x03\x00\x00\x17\x01\x00\x00\x00\x0F\x00\x00\x3B\x0D\x00\x00\x17\x11\x00\x00\x74\x03\x00\x00\x17\x01\x00\x00\x00\x0F\x00\x00\x3B\x0D\x00\x00\x17\x11\x00\x00\x02\x03\x00\x00\x17\x01\x00\x00\x00\x0F\x00\x00\x3B\x0D\x00\x00\x17\x11\x00\x00\x17\x01\x00\x00\x07\x01\x00\x00\x00\x0F\x00\x00\x3B\x0D\x00\x00\x17\x11\x00\x00\x79\x03\x00\x00\x17\x01\x00\x00\x00\x0F\x00\x00\x3B\x0D\x00\x00\x17\x11\x00\x00\x04\x11\x00\x00\x17\x01\x00\x00\x00\x0F\x00\x00\x3B\x0D\x00\x00\x17\x01\x00\x00\x07\x01\x00\x00\x04\x11\x00\x00\x00\x0F\x00\x00\x3B\x0D\x00\x00\x04\x11\x00\x00\x00\x0F\x00\x00\x3B\x0D\x00\x00\x04\x11\x00\x00\x17\x01\x00\x00\x04\x11\x00\x00\x00\x0F\x00\x00\x3B\x0D\x00\x00\x7A\x03\x00\x00\x17\x01\x00\x00\x04\x11\x00\x00\x00\x0F\x00\x00\x7A\x0D\x00\x00\x17\x11\x00\x00\x00\x0F\x00\x00\x00\x09\x00\x00\x01\x09\x00\x00\x02\x09\x00\x00\x03\x09\x00\x00\x02\x01\x00\x00\x0E\x01\x00\x00\x00\x0B\x00\x00\x01\x0B\x00\x00\x02\x0B\x00\x00\x0D\x01\x00\x00\x56\x03\x00\x00\x5B\x03\x00\x00\x5E\x03\x00\x00\x63\x03\x00\x00\x05\x01\x00\x00\x00\x01\x00\x00\x10\x01',
7
+ _globals = (b'\xFF\xFF\xFF\x0BSFC_FILE_TRUNCATE',4224,b'\xFF\xFF\xFF\x0BSFC_GET_FORMAT_INFO',4136,b'\xFF\xFF\xFF\x0BSFC_GET_FORMAT_MAJOR',4145,b'\xFF\xFF\xFF\x0BSFC_GET_FORMAT_MAJOR_COUNT',4144,b'\xFF\xFF\xFF\x0BSFC_GET_FORMAT_SUBTYPE',4147,b'\xFF\xFF\xFF\x0BSFC_GET_FORMAT_SUBTYPE_COUNT',4146,b'\xFF\xFF\xFF\x0BSFC_GET_LIB_VERSION',4096,b'\xFF\xFF\xFF\x0BSFC_GET_LOG_INFO',4097,b'\xFF\xFF\xFF\x0BSFC_SET_BITRATE_MODE',4869,b'\xFF\xFF\xFF\x0BSFC_SET_CLIPPING',4288,b'\xFF\xFF\xFF\x0BSFC_SET_COMPRESSION_LEVEL',4865,b'\xFF\xFF\xFF\x0BSFC_SET_SCALE_FLOAT_INT_READ',4116,b'\xFF\xFF\xFF\x0BSFC_SET_SCALE_INT_FLOAT_WRITE',4117,b'\xFF\xFF\xFF\x0BSFM_RDWR',48,b'\xFF\xFF\xFF\x0BSFM_READ',16,b'\xFF\xFF\xFF\x0BSFM_WRITE',32,b'\xFF\xFF\xFF\x0BSF_BITRATE_MODE_AVERAGE',1,b'\xFF\xFF\xFF\x0BSF_BITRATE_MODE_CONSTANT',0,b'\xFF\xFF\xFF\x0BSF_BITRATE_MODE_VARIABLE',2,b'\xFF\xFF\xFF\x0BSF_FALSE',0,b'\xFF\xFF\xFF\x0BSF_FORMAT_ENDMASK',805306368,b'\xFF\xFF\xFF\x0BSF_FORMAT_SUBMASK',65535,b'\xFF\xFF\xFF\x0BSF_FORMAT_TYPEMASK',268369920,b'\xFF\xFF\xFF\x0BSF_TRUE',1,b'\x00\x00\x25\x23sf_close',0,b'\x00\x00\x32\x23sf_command',0,b'\x00\x00\x25\x23sf_error',0,b'\x00\x00\x1D\x23sf_error_number',0,b'\x00\x00\x28\x23sf_error_str',0,b'\x00\x00\x22\x23sf_format_check',0,b'\x00\x00\x19\x23sf_get_string',0,b'\x00\x00\x06\x23sf_open',0,b'\x00\x00\x0B\x23sf_open_fd',0,b'\x00\x00\x00\x23sf_open_virtual',0,b'\x00\x00\x25\x23sf_perror',0,b'\x00\x00\x38\x23sf_read_double',0,b'\x00\x00\x3D\x23sf_read_float',0,b'\x00\x00\x42\x23sf_read_int',0,b'\x00\x00\x51\x23sf_read_raw',0,b'\x00\x00\x4C\x23sf_read_short',0,b'\x00\x00\x51\x23sf_readf_double',0,b'\x00\x00\x51\x23sf_readf_float',0,b'\x00\x00\x51\x23sf_readf_int',0,b'\x00\x00\x51\x23sf_readf_short',0,b'\x00\x00\x47\x23sf_seek',0,b'\x00\x00\x2D\x23sf_set_string',0,b'\x00\x00\x16\x23sf_strerror',0,b'\x00\x00\x20\x23sf_version_string',0,b'\x00\x00\x11\x23sf_wchar_open',0,b'\x00\x00\x38\x23sf_write_double',0,b'\x00\x00\x3D\x23sf_write_float',0,b'\x00\x00\x42\x23sf_write_int',0,b'\x00\x00\x51\x23sf_write_raw',0,b'\x00\x00\x4C\x23sf_write_short',0,b'\x00\x00\x68\x23sf_write_sync',0,b'\x00\x00\x51\x23sf_writef_double',0,b'\x00\x00\x51\x23sf_writef_float',0,b'\x00\x00\x51\x23sf_writef_int',0,b'\x00\x00\x51\x23sf_writef_short',0),
8
+ _struct_unions = ((b'\x00\x00\x00\x6B\x00\x00\x00\x02SF_FORMAT_INFO',b'\x00\x00\x02\x11format',b'\x00\x00\x07\x11name',b'\x00\x00\x07\x11extension'),(b'\x00\x00\x00\x6C\x00\x00\x00\x02SF_INFO',b'\x00\x00\x3B\x11frames',b'\x00\x00\x02\x11samplerate',b'\x00\x00\x02\x11channels',b'\x00\x00\x02\x11format',b'\x00\x00\x02\x11sections',b'\x00\x00\x02\x11seekable'),(b'\x00\x00\x00\x6D\x00\x00\x00\x02SF_VIRTUAL_IO',b'\x00\x00\x76\x11get_filelen',b'\x00\x00\x75\x11seek',b'\x00\x00\x77\x11read',b'\x00\x00\x78\x11write',b'\x00\x00\x76\x11tell'),(b'\x00\x00\x00\x6E\x00\x00\x00\x10SNDFILE_tag',)),
9
+ _enums = (b'\x00\x00\x00\x71\x00\x00\x00\x16$1\x00SF_FORMAT_SUBMASK,SF_FORMAT_TYPEMASK,SF_FORMAT_ENDMASK',b'\x00\x00\x00\x72\x00\x00\x00\x16$2\x00SFC_GET_LIB_VERSION,SFC_GET_LOG_INFO,SFC_GET_FORMAT_INFO,SFC_GET_FORMAT_MAJOR_COUNT,SFC_GET_FORMAT_MAJOR,SFC_GET_FORMAT_SUBTYPE_COUNT,SFC_GET_FORMAT_SUBTYPE,SFC_FILE_TRUNCATE,SFC_SET_CLIPPING,SFC_SET_SCALE_FLOAT_INT_READ,SFC_SET_SCALE_INT_FLOAT_WRITE,SFC_SET_COMPRESSION_LEVEL,SFC_SET_BITRATE_MODE',b'\x00\x00\x00\x73\x00\x00\x00\x16$3\x00SF_FALSE,SF_TRUE,SFM_READ,SFM_WRITE,SFM_RDWR,SF_BITRATE_MODE_CONSTANT,SF_BITRATE_MODE_AVERAGE,SF_BITRATE_MODE_VARIABLE'),
10
+ _typenames = (b'\x00\x00\x00\x6BSF_FORMAT_INFO',b'\x00\x00\x00\x6CSF_INFO',b'\x00\x00\x00\x6DSF_VIRTUAL_IO',b'\x00\x00\x00\x6ESNDFILE',b'\x00\x00\x00\x3Bsf_count_t',b'\x00\x00\x00\x76sf_vio_get_filelen',b'\x00\x00\x00\x77sf_vio_read',b'\x00\x00\x00\x75sf_vio_seek',b'\x00\x00\x00\x76sf_vio_tell',b'\x00\x00\x00\x78sf_vio_write'),
11
+ )
TTS/Kokoro/.venv/Lib/site-packages/addict-2.4.0.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
TTS/Kokoro/.venv/Lib/site-packages/addict-2.4.0.dist-info/LICENSE ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2014 Mats Julian Olsen
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
TTS/Kokoro/.venv/Lib/site-packages/addict-2.4.0.dist-info/METADATA ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: addict
3
+ Version: 2.4.0
4
+ Summary: Addict is a dictionary whose items can be set using both attribute and item syntax.
5
+ Home-page: https://github.com/mewwts/addict
6
+ Author: Mats Julian Olsen
7
+ Author-email: mats@plysjbyen.net
8
+ License: UNKNOWN
9
+ Platform: UNKNOWN
10
+ Classifier: Programming Language :: Python
11
+ Classifier: Programming Language :: Python :: 2.7
12
+ Classifier: Programming Language :: Python :: 3.6
13
+ Classifier: Programming Language :: Python :: 3.7
14
+ Classifier: Programming Language :: Python :: 3.8
15
+ Classifier: Programming Language :: Python :: 3.9
16
+ Classifier: License :: OSI Approved :: MIT License
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Intended Audience :: Developers
19
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
20
+
21
+ Addict is a module that exposes a dictionary subclass that allows items to be set like attributes. Values are gettable and settable using both attribute and item syntax. For more info check out the README at 'github.com/mewwts/addict'.
22
+
23
+
TTS/Kokoro/.venv/Lib/site-packages/addict-2.4.0.dist-info/RECORD ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ addict-2.4.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ addict-2.4.0.dist-info/LICENSE,sha256=ykiNM8US0LImFCCQr5DomuJmqQGik_if1kLf7JMeIsE,1085
3
+ addict-2.4.0.dist-info/METADATA,sha256=ZjIJZ5lvhfohHxIWp79fkh0TtBsN5duX84na3bxU6vQ,1028
4
+ addict-2.4.0.dist-info/RECORD,,
5
+ addict-2.4.0.dist-info/WHEEL,sha256=EVRjI69F5qVjm_YgqcTXPnTAv3BfSUr0WVAHuSP3Xoo,92
6
+ addict-2.4.0.dist-info/top_level.txt,sha256=GGfQKsz1N-bSRYzNpyp8GY8uAEqh3SWaXRbAnBUKjHA,7
7
+ addict/__init__.py,sha256=xmlNiYYVoAD3_FfmgfOM2cc3wI17GSgsMBODbFRs_mY,233
8
+ addict/__pycache__/__init__.cpython-312.pyc,,
9
+ addict/__pycache__/addict.cpython-312.pyc,,
10
+ addict/addict.py,sha256=ScOfclaAM7ugyZoXOW2HHL9gCXt_XPe-i5bTLiY8ufU,4901
TTS/Kokoro/.venv/Lib/site-packages/addict-2.4.0.dist-info/WHEEL ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.35.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
TTS/Kokoro/.venv/Lib/site-packages/addict-2.4.0.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ addict
TTS/Kokoro/.venv/Lib/site-packages/addict/__init__.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ from .addict import Dict
2
+ from .addict import Dict as Addict
3
+
4
+
5
+ __title__ = 'addict'
6
+ __version__ = '2.4.0'
7
+ __author__ = 'Mats Julian Olsen'
8
+ __license__ = 'MIT'
9
+ __copyright__ = 'Copyright 2014-2020 Mats Julian Olsen'
10
+ __all__ = ['Dict']
TTS/Kokoro/.venv/Lib/site-packages/addict/addict.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+
3
+
4
+ class Dict(dict):
5
+
6
+ def __init__(__self, *args, **kwargs):
7
+ object.__setattr__(__self, '__parent', kwargs.pop('__parent', None))
8
+ object.__setattr__(__self, '__key', kwargs.pop('__key', None))
9
+ object.__setattr__(__self, '__frozen', False)
10
+ for arg in args:
11
+ if not arg:
12
+ continue
13
+ elif isinstance(arg, dict):
14
+ for key, val in arg.items():
15
+ __self[key] = __self._hook(val)
16
+ elif isinstance(arg, tuple) and (not isinstance(arg[0], tuple)):
17
+ __self[arg[0]] = __self._hook(arg[1])
18
+ else:
19
+ for key, val in iter(arg):
20
+ __self[key] = __self._hook(val)
21
+
22
+ for key, val in kwargs.items():
23
+ __self[key] = __self._hook(val)
24
+
25
+ def __setattr__(self, name, value):
26
+ if hasattr(self.__class__, name):
27
+ raise AttributeError("'Dict' object attribute "
28
+ "'{0}' is read-only".format(name))
29
+ else:
30
+ self[name] = value
31
+
32
+ def __setitem__(self, name, value):
33
+ isFrozen = (hasattr(self, '__frozen') and
34
+ object.__getattribute__(self, '__frozen'))
35
+ if isFrozen and name not in super(Dict, self).keys():
36
+ raise KeyError(name)
37
+ super(Dict, self).__setitem__(name, value)
38
+ try:
39
+ p = object.__getattribute__(self, '__parent')
40
+ key = object.__getattribute__(self, '__key')
41
+ except AttributeError:
42
+ p = None
43
+ key = None
44
+ if p is not None:
45
+ p[key] = self
46
+ object.__delattr__(self, '__parent')
47
+ object.__delattr__(self, '__key')
48
+
49
+ def __add__(self, other):
50
+ if not self.keys():
51
+ return other
52
+ else:
53
+ self_type = type(self).__name__
54
+ other_type = type(other).__name__
55
+ msg = "unsupported operand type(s) for +: '{}' and '{}'"
56
+ raise TypeError(msg.format(self_type, other_type))
57
+
58
+ @classmethod
59
+ def _hook(cls, item):
60
+ if isinstance(item, dict):
61
+ return cls(item)
62
+ elif isinstance(item, (list, tuple)):
63
+ return type(item)(cls._hook(elem) for elem in item)
64
+ return item
65
+
66
+ def __getattr__(self, item):
67
+ return self.__getitem__(item)
68
+
69
+ def __missing__(self, name):
70
+ if object.__getattribute__(self, '__frozen'):
71
+ raise KeyError(name)
72
+ return self.__class__(__parent=self, __key=name)
73
+
74
+ def __delattr__(self, name):
75
+ del self[name]
76
+
77
+ def to_dict(self):
78
+ base = {}
79
+ for key, value in self.items():
80
+ if isinstance(value, type(self)):
81
+ base[key] = value.to_dict()
82
+ elif isinstance(value, (list, tuple)):
83
+ base[key] = type(value)(
84
+ item.to_dict() if isinstance(item, type(self)) else
85
+ item for item in value)
86
+ else:
87
+ base[key] = value
88
+ return base
89
+
90
+ def copy(self):
91
+ return copy.copy(self)
92
+
93
+ def deepcopy(self):
94
+ return copy.deepcopy(self)
95
+
96
+ def __deepcopy__(self, memo):
97
+ other = self.__class__()
98
+ memo[id(self)] = other
99
+ for key, value in self.items():
100
+ other[copy.deepcopy(key, memo)] = copy.deepcopy(value, memo)
101
+ return other
102
+
103
+ def update(self, *args, **kwargs):
104
+ other = {}
105
+ if args:
106
+ if len(args) > 1:
107
+ raise TypeError()
108
+ other.update(args[0])
109
+ other.update(kwargs)
110
+ for k, v in other.items():
111
+ if ((k not in self) or
112
+ (not isinstance(self[k], dict)) or
113
+ (not isinstance(v, dict))):
114
+ self[k] = v
115
+ else:
116
+ self[k].update(v)
117
+
118
+ def __getnewargs__(self):
119
+ return tuple(self.items())
120
+
121
+ def __getstate__(self):
122
+ return self
123
+
124
+ def __setstate__(self, state):
125
+ self.update(state)
126
+
127
+ def __or__(self, other):
128
+ if not isinstance(other, (Dict, dict)):
129
+ return NotImplemented
130
+ new = Dict(self)
131
+ new.update(other)
132
+ return new
133
+
134
+ def __ror__(self, other):
135
+ if not isinstance(other, (Dict, dict)):
136
+ return NotImplemented
137
+ new = Dict(other)
138
+ new.update(self)
139
+ return new
140
+
141
+ def __ior__(self, other):
142
+ self.update(other)
143
+ return self
144
+
145
+ def setdefault(self, key, default=None):
146
+ if key in self:
147
+ return self[key]
148
+ else:
149
+ self[key] = default
150
+ return default
151
+
152
+ def freeze(self, shouldFreeze=True):
153
+ object.__setattr__(self, '__frozen', shouldFreeze)
154
+ for key, val in self.items():
155
+ if isinstance(val, Dict):
156
+ val.freeze(shouldFreeze)
157
+
158
+ def unfreeze(self):
159
+ self.freeze(False)
TTS/Kokoro/.venv/Lib/site-packages/annotated_doc-0.0.4.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
TTS/Kokoro/.venv/Lib/site-packages/annotated_doc-0.0.4.dist-info/METADATA ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: annotated-doc
3
+ Version: 0.0.4
4
+ Summary: Document parameters, class attributes, return types, and variables inline, with Annotated.
5
+ Author-Email: =?utf-8?q?Sebasti=C3=A1n_Ram=C3=ADrez?= <tiangolo@gmail.com>
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Classifier: Intended Audience :: Information Technology
9
+ Classifier: Intended Audience :: System Administrators
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python
13
+ Classifier: Topic :: Internet
14
+ Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
15
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
16
+ Classifier: Topic :: Software Development :: Libraries
17
+ Classifier: Topic :: Software Development
18
+ Classifier: Typing :: Typed
19
+ Classifier: Development Status :: 4 - Beta
20
+ Classifier: Intended Audience :: Developers
21
+ Classifier: Programming Language :: Python :: 3 :: Only
22
+ Classifier: Programming Language :: Python :: 3.8
23
+ Classifier: Programming Language :: Python :: 3.9
24
+ Classifier: Programming Language :: Python :: 3.10
25
+ Classifier: Programming Language :: Python :: 3.11
26
+ Classifier: Programming Language :: Python :: 3.12
27
+ Classifier: Programming Language :: Python :: 3.13
28
+ Classifier: Programming Language :: Python :: 3.14
29
+ Project-URL: Homepage, https://github.com/fastapi/annotated-doc
30
+ Project-URL: Documentation, https://github.com/fastapi/annotated-doc
31
+ Project-URL: Repository, https://github.com/fastapi/annotated-doc
32
+ Project-URL: Issues, https://github.com/fastapi/annotated-doc/issues
33
+ Project-URL: Changelog, https://github.com/fastapi/annotated-doc/release-notes.md
34
+ Requires-Python: >=3.8
35
+ Description-Content-Type: text/markdown
36
+
37
+ # Annotated Doc
38
+
39
+ Document parameters, class attributes, return types, and variables inline, with `Annotated`.
40
+
41
+ <a href="https://github.com/fastapi/annotated-doc/actions?query=workflow%3ATest+event%3Apush+branch%3Amain" target="_blank">
42
+ <img src="https://github.com/fastapi/annotated-doc/actions/workflows/test.yml/badge.svg?event=push&branch=main" alt="Test">
43
+ </a>
44
+ <a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/fastapi/annotated-doc" target="_blank">
45
+ <img src="https://coverage-badge.samuelcolvin.workers.dev/fastapi/annotated-doc.svg" alt="Coverage">
46
+ </a>
47
+ <a href="https://pypi.org/project/annotated-doc" target="_blank">
48
+ <img src="https://img.shields.io/pypi/v/annotated-doc?color=%2334D058&label=pypi%20package" alt="Package version">
49
+ </a>
50
+ <a href="https://pypi.org/project/annotated-doc" target="_blank">
51
+ <img src="https://img.shields.io/pypi/pyversions/annotated-doc.svg?color=%2334D058" alt="Supported Python versions">
52
+ </a>
53
+
54
+ ## Installation
55
+
56
+ ```bash
57
+ pip install annotated-doc
58
+ ```
59
+
60
+ Or with `uv`:
61
+
62
+ ```Python
63
+ uv add annotated-doc
64
+ ```
65
+
66
+ ## Usage
67
+
68
+ Import `Doc` and pass a single literal string with the documentation for the specific parameter, class attribute, return type, or variable.
69
+
70
+ For example, to document a parameter `name` in a function `hi` you could do:
71
+
72
+ ```Python
73
+ from typing import Annotated
74
+
75
+ from annotated_doc import Doc
76
+
77
+ def hi(name: Annotated[str, Doc("Who to say hi to")]) -> None:
78
+ print(f"Hi, {name}!")
79
+ ```
80
+
81
+ You can also use it to document class attributes:
82
+
83
+ ```Python
84
+ from typing import Annotated
85
+
86
+ from annotated_doc import Doc
87
+
88
+ class User:
89
+ name: Annotated[str, Doc("The user's name")]
90
+ age: Annotated[int, Doc("The user's age")]
91
+ ```
92
+
93
+ The same way, you could document return types and variables, or anything that could have a type annotation with `Annotated`.
94
+
95
+ ## Who Uses This
96
+
97
+ `annotated-doc` was made for:
98
+
99
+ * [FastAPI](https://fastapi.tiangolo.com/)
100
+ * [Typer](https://typer.tiangolo.com/)
101
+ * [SQLModel](https://sqlmodel.tiangolo.com/)
102
+ * [Asyncer](https://asyncer.tiangolo.com/)
103
+
104
+ `annotated-doc` is supported by [griffe-typingdoc](https://github.com/mkdocstrings/griffe-typingdoc), which powers reference documentation like the one in the [FastAPI Reference](https://fastapi.tiangolo.com/reference/).
105
+
106
+ ## Reasons not to use `annotated-doc`
107
+
108
+ You are already comfortable with one of the existing docstring formats, like:
109
+
110
+ * Sphinx
111
+ * numpydoc
112
+ * Google
113
+ * Keras
114
+
115
+ Your team is already comfortable using them.
116
+
117
+ You prefer having the documentation about parameters all together in a docstring, separated from the code defining them.
118
+
119
+ You care about a specific set of users, using one specific editor, and that editor already has support for the specific docstring format you use.
120
+
121
+ ## Reasons to use `annotated-doc`
122
+
123
+ * No micro-syntax to learn for newcomers, it’s **just Python** syntax.
124
+ * **Editing** would be already fully supported by default by any editor (current or future) supporting Python syntax, including syntax errors, syntax highlighting, etc.
125
+ * **Rendering** would be relatively straightforward to implement by static tools (tools that don't need runtime execution), as the information can be extracted from the AST they normally already create.
126
+ * **Deduplication of information**: the name of a parameter would be defined in a single place, not duplicated inside of a docstring.
127
+ * **Elimination** of the possibility of having **inconsistencies** when removing a parameter or class variable and **forgetting to remove** its documentation.
128
+ * **Minimization** of the probability of adding a new parameter or class variable and **forgetting to add its documentation**.
129
+ * **Elimination** of the possibility of having **inconsistencies** between the **name** of a parameter in the **signature** and the name in the docstring when it is renamed.
130
+ * **Access** to the documentation string for each symbol at **runtime**, including existing (older) Python versions.
131
+ * A more formalized way to document other symbols, like type aliases, that could use Annotated.
132
+ * **Support** for apps using FastAPI, Typer and others.
133
+ * **AI Accessibility**: AI tools will have an easier way understanding each parameter as the distance from documentation to parameter is much closer.
134
+
135
+ ## History
136
+
137
+ I ([@tiangolo](https://github.com/tiangolo)) originally wanted for this to be part of the Python standard library (in [PEP 727](https://peps.python.org/pep-0727/)), but the proposal was withdrawn as there was a fair amount of negative feedback and opposition.
138
+
139
+ The conclusion was that this was better done as an external effort, in a third-party library.
140
+
141
+ So, here it is, with a simpler approach, as a third-party library, in a way that can be used by others, starting with FastAPI and friends.
142
+
143
+ ## License
144
+
145
+ This project is licensed under the terms of the MIT license.
TTS/Kokoro/.venv/Lib/site-packages/annotated_doc-0.0.4.dist-info/RECORD ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ annotated_doc-0.0.4.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ annotated_doc-0.0.4.dist-info/METADATA,sha256=Irm5KJua33dY2qKKAjJ-OhKaVBVIfwFGej_dSe3Z1TU,6566
3
+ annotated_doc-0.0.4.dist-info/RECORD,,
4
+ annotated_doc-0.0.4.dist-info/WHEEL,sha256=9P2ygRxDrTJz3gsagc0Z96ukrxjr-LFBGOgv3AuKlCA,90
5
+ annotated_doc-0.0.4.dist-info/entry_points.txt,sha256=6OYgBcLyFCUgeqLgnvMyOJxPCWzgy7se4rLPKtNonMs,34
6
+ annotated_doc-0.0.4.dist-info/licenses/LICENSE,sha256=__Fwd5pqy_ZavbQFwIfxzuF4ZpHkqWpANFF-SlBKDN8,1086
7
+ annotated_doc/__init__.py,sha256=VuyxxUe80kfEyWnOrCx_Bk8hybo3aKo6RYBlkBBYW8k,52
8
+ annotated_doc/__pycache__/__init__.cpython-312.pyc,,
9
+ annotated_doc/__pycache__/main.cpython-312.pyc,,
10
+ annotated_doc/main.py,sha256=5Zfvxv80SwwLqpRW73AZyZyiM4bWma9QWRbp_cgD20s,1075
11
+ annotated_doc/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
TTS/Kokoro/.venv/Lib/site-packages/annotated_doc-0.0.4.dist-info/WHEEL ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: pdm-backend (2.4.5)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
TTS/Kokoro/.venv/Lib/site-packages/annotated_doc-0.0.4.dist-info/entry_points.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ [console_scripts]
2
+
3
+ [gui_scripts]
4
+
TTS/Kokoro/.venv/Lib/site-packages/annotated_doc/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .main import Doc as Doc
2
+
3
+ __version__ = "0.0.4"
TTS/Kokoro/.venv/Lib/site-packages/annotated_doc/main.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class Doc:
2
+ """Define the documentation of a type annotation using `Annotated`, to be
3
+ used in class attributes, function and method parameters, return values,
4
+ and variables.
5
+
6
+ The value should be a positional-only string literal to allow static tools
7
+ like editors and documentation generators to use it.
8
+
9
+ This complements docstrings.
10
+
11
+ The string value passed is available in the attribute `documentation`.
12
+
13
+ Example:
14
+
15
+ ```Python
16
+ from typing import Annotated
17
+ from annotated_doc import Doc
18
+
19
+ def hi(name: Annotated[str, Doc("Who to say hi to")]) -> None:
20
+ print(f"Hi, {name}!")
21
+ ```
22
+ """
23
+
24
+ def __init__(self, documentation: str, /) -> None:
25
+ self.documentation = documentation
26
+
27
+ def __repr__(self) -> str:
28
+ return f"Doc({self.documentation!r})"
29
+
30
+ def __hash__(self) -> int:
31
+ return hash(self.documentation)
32
+
33
+ def __eq__(self, other: object) -> bool:
34
+ if not isinstance(other, Doc):
35
+ return NotImplemented
36
+ return self.documentation == other.documentation
TTS/Kokoro/.venv/Lib/site-packages/annotated_doc/py.typed ADDED
File without changes
TTS/Kokoro/.venv/Lib/site-packages/annotated_types-0.7.0.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
TTS/Kokoro/.venv/Lib/site-packages/annotated_types-0.7.0.dist-info/RECORD ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ annotated_types-0.7.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ annotated_types-0.7.0.dist-info/METADATA,sha256=7ltqxksJJ0wCYFGBNIQCWTlWQGeAH0hRFdnK3CB895E,15046
3
+ annotated_types-0.7.0.dist-info/RECORD,,
4
+ annotated_types-0.7.0.dist-info/WHEEL,sha256=zEMcRr9Kr03x1ozGwg5v9NQBKn3kndp6LSoSlVg-jhU,87
5
+ annotated_types-0.7.0.dist-info/licenses/LICENSE,sha256=_hBJiEsaDZNCkB6I4H8ykl0ksxIdmXK2poBfuYJLCV0,1083
6
+ annotated_types/__init__.py,sha256=RynLsRKUEGI0KimXydlD1fZEfEzWwDo0Uon3zOKhG1Q,13819
7
+ annotated_types/__pycache__/__init__.cpython-312.pyc,,
8
+ annotated_types/__pycache__/test_cases.cpython-312.pyc,,
9
+ ann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
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import sys
3
+ import types
4
+ from dataclasses import dataclass
5
+ from datetime import tzinfo
6
+ from typing import TYPE_CHECKING, Any, Callable, Iterator, Optional, SupportsFloat, SupportsIndex, TypeVar, Union
7
+
8
+ if sys.version_info < (3, 8):
9
+ from typing_extensions import Protocol, runtime_checkable
10
+ else:
11
+ from typing import Protocol, runtime_checkable
12
+
13
+ if sys.version_info < (3, 9):
14
+ from typing_extensions import Annotated, Literal
15
+ else:
16
+ from typing import Annotated, Literal
17
+
18
+ if sys.version_info < (3, 10):
19
+ EllipsisType = type(Ellipsis)
20
+ KW_ONLY = {}
21
+ SLOTS = {}
22
+ else:
23
+ from types import EllipsisType
24
+
25
+ KW_ONLY = {"kw_only": True}
26
+ SLOTS = {"slots": True}
27
+
28
+
29
+ __all__ = (
30
+ 'BaseMetadata',
31
+ 'GroupedMetadata',
32
+ 'Gt',
33
+ 'Ge',
34
+ 'Lt',
35
+ 'Le',
36
+ 'Interval',
37
+ 'MultipleOf',
38
+ 'MinLen',
39
+ 'MaxLen',
40
+ 'Len',
41
+ 'Timezone',
42
+ 'Predicate',
43
+ 'LowerCase',
44
+ 'UpperCase',
45
+ 'IsDigits',
46
+ 'IsFinite',
47
+ 'IsNotFinite',
48
+ 'IsNan',
49
+ 'IsNotNan',
50
+ 'IsInfinite',
51
+ 'IsNotInfinite',
52
+ 'doc',
53
+ 'DocInfo',
54
+ '__version__',
55
+ )
56
+
57
+ __version__ = '0.7.0'
58
+
59
+
60
+ T = TypeVar('T')
61
+
62
+
63
+ # arguments that start with __ are considered
64
+ # positional only
65
+ # see https://peps.python.org/pep-0484/#positional-only-arguments
66
+
67
+
68
+ class SupportsGt(Protocol):
69
+ def __gt__(self: T, __other: T) -> bool:
70
+ ...
71
+
72
+
73
+ class SupportsGe(Protocol):
74
+ def __ge__(self: T, __other: T) -> bool:
75
+ ...
76
+
77
+
78
+ class SupportsLt(Protocol):
79
+ def __lt__(self: T, __other: T) -> bool:
80
+ ...
81
+
82
+
83
+ class SupportsLe(Protocol):
84
+ def __le__(self: T, __other: T) -> bool:
85
+ ...
86
+
87
+
88
+ class SupportsMod(Protocol):
89
+ def __mod__(self: T, __other: T) -> T:
90
+ ...
91
+
92
+
93
+ class SupportsDiv(Protocol):
94
+ def __div__(self: T, __other: T) -> T:
95
+ ...
96
+
97
+
98
+ class BaseMetadata:
99
+ """Base class for all metadata.
100
+
101
+ This exists mainly so that implementers
102
+ can do `isinstance(..., BaseMetadata)` while traversing field annotations.
103
+ """
104
+
105
+ __slots__ = ()
106
+
107
+
108
+ @dataclass(frozen=True, **SLOTS)
109
+ class Gt(BaseMetadata):
110
+ """Gt(gt=x) implies that the value must be greater than x.
111
+
112
+ It can be used with any type that supports the ``>`` operator,
113
+ including numbers, dates and times, strings, sets, and so on.
114
+ """
115
+
116
+ gt: SupportsGt
117
+
118
+
119
+ @dataclass(frozen=True, **SLOTS)
120
+ class Ge(BaseMetadata):
121
+ """Ge(ge=x) implies that the value must be greater than or equal to x.
122
+
123
+ It can be used with any type that supports the ``>=`` operator,
124
+ including numbers, dates and times, strings, sets, and so on.
125
+ """
126
+
127
+ ge: SupportsGe
128
+
129
+
130
+ @dataclass(frozen=True, **SLOTS)
131
+ class Lt(BaseMetadata):
132
+ """Lt(lt=x) implies that the value must be less than x.
133
+
134
+ It can be used with any type that supports the ``<`` operator,
135
+ including numbers, dates and times, strings, sets, and so on.
136
+ """
137
+
138
+ lt: SupportsLt
139
+
140
+
141
+ @dataclass(frozen=True, **SLOTS)
142
+ class Le(BaseMetadata):
143
+ """Le(le=x) implies that the value must be less than or equal to x.
144
+
145
+ It can be used with any type that supports the ``<=`` operator,
146
+ including numbers, dates and times, strings, sets, and so on.
147
+ """
148
+
149
+ le: SupportsLe
150
+
151
+
152
+ @runtime_checkable
153
+ class GroupedMetadata(Protocol):
154
+ """A grouping of multiple objects, like typing.Unpack.
155
+
156
+ `GroupedMetadata` on its own is not metadata and has no meaning.
157
+ All of the constraints and metadata should be fully expressable
158
+ in terms of the `BaseMetadata`'s returned by `GroupedMetadata.__iter__()`.
159
+
160
+ Concrete implementations should override `GroupedMetadata.__iter__()`
161
+ to add their own metadata.
162
+ For example:
163
+
164
+ >>> @dataclass
165
+ >>> class Field(GroupedMetadata):
166
+ >>> gt: float | None = None
167
+ >>> description: str | None = None
168
+ ...
169
+ >>> def __iter__(self) -> Iterable[object]:
170
+ >>> if self.gt is not None:
171
+ >>> yield Gt(self.gt)
172
+ >>> if self.description is not None:
173
+ >>> yield Description(self.gt)
174
+
175
+ Also see the implementation of `Interval` below for an example.
176
+
177
+ Parsers should recognize this and unpack it so that it can be used
178
+ both with and without unpacking:
179
+
180
+ - `Annotated[int, Field(...)]` (parser must unpack Field)
181
+ - `Annotated[int, *Field(...)]` (PEP-646)
182
+ """ # noqa: trailing-whitespace
183
+
184
+ @property
185
+ def __is_annotated_types_grouped_metadata__(self) -> Literal[True]:
186
+ return True
187
+
188
+ def __iter__(self) -> Iterator[object]:
189
+ ...
190
+
191
+ if not TYPE_CHECKING:
192
+ __slots__ = () # allow subclasses to use slots
193
+
194
+ def __init_subclass__(cls, *args: Any, **kwargs: Any) -> None:
195
+ # Basic ABC like functionality without the complexity of an ABC
196
+ super().__init_subclass__(*args, **kwargs)
197
+ if cls.__iter__ is GroupedMetadata.__iter__:
198
+ raise TypeError("Can't subclass GroupedMetadata without implementing __iter__")
199
+
200
+ def __iter__(self) -> Iterator[object]: # noqa: F811
201
+ raise NotImplementedError # more helpful than "None has no attribute..." type errors
202
+
203
+
204
+ @dataclass(frozen=True, **KW_ONLY, **SLOTS)
205
+ class Interval(GroupedMetadata):
206
+ """Interval can express inclusive or exclusive bounds with a single object.
207
+
208
+ It accepts keyword arguments ``gt``, ``ge``, ``lt``, and/or ``le``, which
209
+ are interpreted the same way as the single-bound constraints.
210
+ """
211
+
212
+ gt: Union[SupportsGt, None] = None
213
+ ge: Union[SupportsGe, None] = None
214
+ lt: Union[SupportsLt, None] = None
215
+ le: Union[SupportsLe, None] = None
216
+
217
+ def __iter__(self) -> Iterator[BaseMetadata]:
218
+ """Unpack an Interval into zero or more single-bounds."""
219
+ if self.gt is not None:
220
+ yield Gt(self.gt)
221
+ if self.ge is not None:
222
+ yield Ge(self.ge)
223
+ if self.lt is not None:
224
+ yield Lt(self.lt)
225
+ if self.le is not None:
226
+ yield Le(self.le)
227
+
228
+
229
+ @dataclass(frozen=True, **SLOTS)
230
+ class MultipleOf(BaseMetadata):
231
+ """MultipleOf(multiple_of=x) might be interpreted in two ways:
232
+
233
+ 1. Python semantics, implying ``value % multiple_of == 0``, or
234
+ 2. JSONschema semantics, where ``int(value / multiple_of) == value / multiple_of``
235
+
236
+ We encourage users to be aware of these two common interpretations,
237
+ and libraries to carefully document which they implement.
238
+ """
239
+
240
+ multiple_of: Union[SupportsDiv, SupportsMod]
241
+
242
+
243
+ @dataclass(frozen=True, **SLOTS)
244
+ class MinLen(BaseMetadata):
245
+ """
246
+ MinLen() implies minimum inclusive length,
247
+ e.g. ``len(value) >= min_length``.
248
+ """
249
+
250
+ min_length: Annotated[int, Ge(0)]
251
+
252
+
253
+ @dataclass(frozen=True, **SLOTS)
254
+ class MaxLen(BaseMetadata):
255
+ """
256
+ MaxLen() implies maximum inclusive length,
257
+ e.g. ``len(value) <= max_length``.
258
+ """
259
+
260
+ max_length: Annotated[int, Ge(0)]
261
+
262
+
263
+ @dataclass(frozen=True, **SLOTS)
264
+ class Len(GroupedMetadata):
265
+ """
266
+ Len() implies that ``min_length <= len(value) <= max_length``.
267
+
268
+ Upper bound may be omitted or ``None`` to indicate no upper length bound.
269
+ """
270
+
271
+ min_length: Annotated[int, Ge(0)] = 0
272
+ max_length: Optional[Annotated[int, Ge(0)]] = None
273
+
274
+ def __iter__(self) -> Iterator[BaseMetadata]:
275
+ """Unpack a Len into zone or more single-bounds."""
276
+ if self.min_length > 0:
277
+ yield MinLen(self.min_length)
278
+ if self.max_length is not None:
279
+ yield MaxLen(self.max_length)
280
+
281
+
282
+ @dataclass(frozen=True, **SLOTS)
283
+ class Timezone(BaseMetadata):
284
+ """Timezone(tz=...) requires a datetime to be aware (or ``tz=None``, naive).
285
+
286
+ ``Annotated[datetime, Timezone(None)]`` must be a naive datetime.
287
+ ``Timezone[...]`` (the ellipsis literal) expresses that the datetime must be
288
+ tz-aware but any timezone is allowed.
289
+
290
+ You may also pass a specific timezone string or tzinfo object such as
291
+ ``Timezone(timezone.utc)`` or ``Timezone("Africa/Abidjan")`` to express that
292
+ you only allow a specific timezone, though we note that this is often
293
+ a symptom of poor design.
294
+ """
295
+
296
+ tz: Union[str, tzinfo, EllipsisType, None]
297
+
298
+
299
+ @dataclass(frozen=True, **SLOTS)
300
+ class Unit(BaseMetadata):
301
+ """Indicates that the value is a physical quantity with the specified unit.
302
+
303
+ It is intended for usage with numeric types, where the value represents the
304
+ magnitude of the quantity. For example, ``distance: Annotated[float, Unit('m')]``
305
+ or ``speed: Annotated[float, Unit('m/s')]``.
306
+
307
+ Interpretation of the unit string is left to the discretion of the consumer.
308
+ It is suggested to follow conventions established by python libraries that work
309
+ with physical quantities, such as
310
+
311
+ - ``pint`` : <https://pint.readthedocs.io/en/stable/>
312
+ - ``astropy.units``: <https://docs.astropy.org/en/stable/units/>
313
+
314
+ For indicating a quantity with a certain dimensionality but without a specific unit
315
+ it is recommended to use square brackets, e.g. `Annotated[float, Unit('[time]')]`.
316
+ Note, however, ``annotated_types`` itself makes no use of the unit string.
317
+ """
318
+
319
+ unit: str
320
+
321
+
322
+ @dataclass(frozen=True, **SLOTS)
323
+ class Predicate(BaseMetadata):
324
+ """``Predicate(func: Callable)`` implies `func(value)` is truthy for valid values.
325
+
326
+ Users should prefer statically inspectable metadata, but if you need the full
327
+ power and flexibility of arbitrary runtime predicates... here it is.
328
+
329
+ We provide a few predefined predicates for common string constraints:
330
+ ``IsLower = Predicate(str.islower)``, ``IsUpper = Predicate(str.isupper)``, and
331
+ ``IsDigits = Predicate(str.isdigit)``. Users are encouraged to use methods which
332
+ can be given special handling, and avoid indirection like ``lambda s: s.lower()``.
333
+
334
+ Some libraries might have special logic to handle certain predicates, e.g. by
335
+ checking for `str.isdigit` and using its presence to both call custom logic to
336
+ enforce digit-only strings, and customise some generated external schema.
337
+
338
+ We do not specify what behaviour should be expected for predicates that raise
339
+ an exception. For example `Annotated[int, Predicate(str.isdigit)]` might silently
340
+ skip invalid constraints, or statically raise an error; or it might try calling it
341
+ and then propagate or discard the resulting exception.
342
+ """
343
+
344
+ func: Callable[[Any], bool]
345
+
346
+ def __repr__(self) -> str:
347
+ if getattr(self.func, "__name__", "<lambda>") == "<lambda>":
348
+ return f"{self.__class__.__name__}({self.func!r})"
349
+ if isinstance(self.func, (types.MethodType, types.BuiltinMethodType)) and (
350
+ namespace := getattr(self.func.__self__, "__name__", None)
351
+ ):
352
+ return f"{self.__class__.__name__}({namespace}.{self.func.__name__})"
353
+ if isinstance(self.func, type(str.isascii)): # method descriptor
354
+ return f"{self.__class__.__name__}({self.func.__qualname__})"
355
+ return f"{self.__class__.__name__}({self.func.__name__})"
356
+
357
+
358
+ @dataclass
359
+ class Not:
360
+ func: Callable[[Any], bool]
361
+
362
+ def __call__(self, __v: Any) -> bool:
363
+ return not self.func(__v)
364
+
365
+
366
+ _StrType = TypeVar("_StrType", bound=str)
367
+
368
+ LowerCase = Annotated[_StrType, Predicate(str.islower)]
369
+ """
370
+ Return True if the string is a lowercase string, False otherwise.
371
+
372
+ A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.
373
+ """ # noqa: E501
374
+ UpperCase = Annotated[_StrType, Predicate(str.isupper)]
375
+ """
376
+ Return True if the string is an uppercase string, False otherwise.
377
+
378
+ A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.
379
+ """ # noqa: E501
380
+ IsDigit = Annotated[_StrType, Predicate(str.isdigit)]
381
+ IsDigits = IsDigit # type: ignore # plural for backwards compatibility, see #63
382
+ """
383
+ Return True if the string is a digit string, False otherwise.
384
+
385
+ A string is a digit string if all characters in the string are digits and there is at least one character in the string.
386
+ """ # noqa: E501
387
+ IsAscii = Annotated[_StrType, Predicate(str.isascii)]
388
+ """
389
+ Return True if all characters in the string are ASCII, False otherwise.
390
+
391
+ ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.
392
+ """
393
+
394
+ _NumericType = TypeVar('_NumericType', bound=Union[SupportsFloat, SupportsIndex])
395
+ IsFinite = Annotated[_NumericType, Predicate(math.isfinite)]
396
+ """Return True if x is neither an infinity nor a NaN, and False otherwise."""
397
+ IsNotFinite = Annotated[_NumericType, Predicate(Not(math.isfinite))]
398
+ """Return True if x is one of infinity or NaN, and False otherwise"""
399
+ IsNan = Annotated[_NumericType, Predicate(math.isnan)]
400
+ """Return True if x is a NaN (not a number), and False otherwise."""
401
+ IsNotNan = Annotated[_NumericType, Predicate(Not(math.isnan))]
402
+ """Return True if x is anything but NaN (not a number), and False otherwise."""
403
+ IsInfinite = Annotated[_NumericType, Predicate(math.isinf)]
404
+ """Return True if x is a positive or negative infinity, and False otherwise."""
405
+ IsNotInfinite = Annotated[_NumericType, Predicate(Not(math.isinf))]
406
+ """Return True if x is neither a positive or negative infinity, and False otherwise."""
407
+
408
+ try:
409
+ from typing_extensions import DocInfo, doc # type: ignore [attr-defined]
410
+ except ImportError:
411
+
412
+ @dataclass(frozen=True, **SLOTS)
413
+ class DocInfo: # type: ignore [no-redef]
414
+ """ "
415
+ The return value of doc(), mainly to be used by tools that want to extract the
416
+ Annotated documentation at runtime.
417
+ """
418
+
419
+ documentation: str
420
+ """The documentation string passed to doc()."""
421
+
422
+ def doc(
423
+ documentation: str,
424
+ ) -> DocInfo:
425
+ """
426
+ Add documentation to a type annotation inside of Annotated.
427
+
428
+ For example:
429
+
430
+ >>> def hi(name: Annotated[int, doc("The name of the user")]) -> None: ...
431
+ """
432
+ return DocInfo(documentation)
TTS/Kokoro/.venv/Lib/site-packages/annotated_types/py.typed ADDED
File without changes
TTS/Kokoro/.venv/Lib/site-packages/annotated_types/test_cases.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import sys
3
+ from datetime import date, datetime, timedelta, timezone
4
+ from decimal import Decimal
5
+ from typing import Any, Dict, Iterable, Iterator, List, NamedTuple, Set, Tuple
6
+
7
+ if sys.version_info < (3, 9):
8
+ from typing_extensions import Annotated
9
+ else:
10
+ from typing import Annotated
11
+
12
+ import annotated_types as at
13
+
14
+
15
+ class Case(NamedTuple):
16
+ """
17
+ A test case for `annotated_types`.
18
+ """
19
+
20
+ annotation: Any
21
+ valid_cases: Iterable[Any]
22
+ invalid_cases: Iterable[Any]
23
+
24
+
25
+ def cases() -> Iterable[Case]:
26
+ # Gt, Ge, Lt, Le
27
+ yield Case(Annotated[int, at.Gt(4)], (5, 6, 1000), (4, 0, -1))
28
+ yield Case(Annotated[float, at.Gt(0.5)], (0.6, 0.7, 0.8, 0.9), (0.5, 0.0, -0.1))
29
+ yield Case(
30
+ Annotated[datetime, at.Gt(datetime(2000, 1, 1))],
31
+ [datetime(2000, 1, 2), datetime(2000, 1, 3)],
32
+ [datetime(2000, 1, 1), datetime(1999, 12, 31)],
33
+ )
34
+ yield Case(
35
+ Annotated[datetime, at.Gt(date(2000, 1, 1))],
36
+ [date(2000, 1, 2), date(2000, 1, 3)],
37
+ [date(2000, 1, 1), date(1999, 12, 31)],
38
+ )
39
+ yield Case(
40
+ Annotated[datetime, at.Gt(Decimal('1.123'))],
41
+ [Decimal('1.1231'), Decimal('123')],
42
+ [Decimal('1.123'), Decimal('0')],
43
+ )
44
+
45
+ yield Case(Annotated[int, at.Ge(4)], (4, 5, 6, 1000, 4), (0, -1))
46
+ yield Case(Annotated[float, at.Ge(0.5)], (0.5, 0.6, 0.7, 0.8, 0.9), (0.4, 0.0, -0.1))
47
+ yield Case(
48
+ Annotated[datetime, at.Ge(datetime(2000, 1, 1))],
49
+ [datetime(2000, 1, 2), datetime(2000, 1, 3)],
50
+ [datetime(1998, 1, 1), datetime(1999, 12, 31)],
51
+ )
52
+
53
+ yield Case(Annotated[int, at.Lt(4)], (0, -1), (4, 5, 6, 1000, 4))
54
+ yield Case(Annotated[float, at.Lt(0.5)], (0.4, 0.0, -0.1), (0.5, 0.6, 0.7, 0.8, 0.9))
55
+ yield Case(
56
+ Annotated[datetime, at.Lt(datetime(2000, 1, 1))],
57
+ [datetime(1999, 12, 31), datetime(1999, 12, 31)],
58
+ [datetime(2000, 1, 2), datetime(2000, 1, 3)],
59
+ )
60
+
61
+ yield Case(Annotated[int, at.Le(4)], (4, 0, -1), (5, 6, 1000))
62
+ yield Case(Annotated[float, at.Le(0.5)], (0.5, 0.0, -0.1), (0.6, 0.7, 0.8, 0.9))
63
+ yield Case(
64
+ Annotated[datetime, at.Le(datetime(2000, 1, 1))],
65
+ [datetime(2000, 1, 1), datetime(1999, 12, 31)],
66
+ [datetime(2000, 1, 2), datetime(2000, 1, 3)],
67
+ )
68
+
69
+ # Interval
70
+ yield Case(Annotated[int, at.Interval(gt=4)], (5, 6, 1000), (4, 0, -1))
71
+ yield Case(Annotated[int, at.Interval(gt=4, lt=10)], (5, 6), (4, 10, 1000, 0, -1))
72
+ yield Case(Annotated[float, at.Interval(ge=0.5, le=1)], (0.5, 0.9, 1), (0.49, 1.1))
73
+ yield Case(
74
+ Annotated[datetime, at.Interval(gt=datetime(2000, 1, 1), le=datetime(2000, 1, 3))],
75
+ [datetime(2000, 1, 2), datetime(2000, 1, 3)],
76
+ [datetime(2000, 1, 1), datetime(2000, 1, 4)],
77
+ )
78
+
79
+ yield Case(Annotated[int, at.MultipleOf(multiple_of=3)], (0, 3, 9), (1, 2, 4))
80
+ yield Case(Annotated[float, at.MultipleOf(multiple_of=0.5)], (0, 0.5, 1, 1.5), (0.4, 1.1))
81
+
82
+ # lengths
83
+
84
+ yield Case(Annotated[str, at.MinLen(3)], ('123', '1234', 'x' * 10), ('', '1', '12'))
85
+ yield Case(Annotated[str, at.Len(3)], ('123', '1234', 'x' * 10), ('', '1', '12'))
86
+ yield Case(Annotated[List[int], at.MinLen(3)], ([1, 2, 3], [1, 2, 3, 4], [1] * 10), ([], [1], [1, 2]))
87
+ yield Case(Annotated[List[int], at.Len(3)], ([1, 2, 3], [1, 2, 3, 4], [1] * 10), ([], [1], [1, 2]))
88
+
89
+ yield Case(Annotated[str, at.MaxLen(4)], ('', '1234'), ('12345', 'x' * 10))
90
+ yield Case(Annotated[str, at.Len(0, 4)], ('', '1234'), ('12345', 'x' * 10))
91
+ yield Case(Annotated[List[str], at.MaxLen(4)], ([], ['a', 'bcdef'], ['a', 'b', 'c']), (['a'] * 5, ['b'] * 10))
92
+ yield Case(Annotated[List[str], at.Len(0, 4)], ([], ['a', 'bcdef'], ['a', 'b', 'c']), (['a'] * 5, ['b'] * 10))
93
+
94
+ yield Case(Annotated[str, at.Len(3, 5)], ('123', '12345'), ('', '1', '12', '123456', 'x' * 10))
95
+ yield Case(Annotated[str, at.Len(3, 3)], ('123',), ('12', '1234'))
96
+
97
+ yield Case(Annotated[Dict[int, int], at.Len(2, 3)], [{1: 1, 2: 2}], [{}, {1: 1}, {1: 1, 2: 2, 3: 3, 4: 4}])
98
+ yield Case(Annotated[Set[int], at.Len(2, 3)], ({1, 2}, {1, 2, 3}), (set(), {1}, {1, 2, 3, 4}))
99
+ yield Case(Annotated[Tuple[int, ...], at.Len(2, 3)], ((1, 2), (1, 2, 3)), ((), (1,), (1, 2, 3, 4)))
100
+
101
+ # Timezone
102
+
103
+ yield Case(
104
+ Annotated[datetime, at.Timezone(None)], [datetime(2000, 1, 1)], [datetime(2000, 1, 1, tzinfo=timezone.utc)]
105
+ )
106
+ yield Case(
107
+ Annotated[datetime, at.Timezone(...)], [datetime(2000, 1, 1, tzinfo=timezone.utc)], [datetime(2000, 1, 1)]
108
+ )
109
+ yield Case(
110
+ Annotated[datetime, at.Timezone(timezone.utc)],
111
+ [datetime(2000, 1, 1, tzinfo=timezone.utc)],
112
+ [datetime(2000, 1, 1), datetime(2000, 1, 1, tzinfo=timezone(timedelta(hours=6)))],
113
+ )
114
+ yield Case(
115
+ Annotated[datetime, at.Timezone('Europe/London')],
116
+ [datetime(2000, 1, 1, tzinfo=timezone(timedelta(0), name='Europe/London'))],
117
+ [datetime(2000, 1, 1), datetime(2000, 1, 1, tzinfo=timezone(timedelta(hours=6)))],
118
+ )
119
+
120
+ # Quantity
121
+
122
+ yield Case(Annotated[float, at.Unit(unit='m')], (5, 4.2), ('5m', '4.2m'))
123
+
124
+ # predicate types
125
+
126
+ yield Case(at.LowerCase[str], ['abc', 'foobar'], ['', 'A', 'Boom'])
127
+ yield Case(at.UpperCase[str], ['ABC', 'DEFO'], ['', 'a', 'abc', 'AbC'])
128
+ yield Case(at.IsDigit[str], ['123'], ['', 'ab', 'a1b2'])
129
+ yield Case(at.IsAscii[str], ['123', 'foo bar'], ['£100', '😊', 'whatever 👀'])
130
+
131
+ yield Case(Annotated[int, at.Predicate(lambda x: x % 2 == 0)], [0, 2, 4], [1, 3, 5])
132
+
133
+ yield Case(at.IsFinite[float], [1.23], [math.nan, math.inf, -math.inf])
134
+ yield Case(at.IsNotFinite[float], [math.nan, math.inf], [1.23])
135
+ yield Case(at.IsNan[float], [math.nan], [1.23, math.inf])
136
+ yield Case(at.IsNotNan[float], [1.23, math.inf], [math.nan])
137
+ yield Case(at.IsInfinite[float], [math.inf], [math.nan, 1.23])
138
+ yield Case(at.IsNotInfinite[float], [math.nan, 1.23], [math.inf])
139
+
140
+ # check stacked predicates
141
+ yield Case(at.IsInfinite[Annotated[float, at.Predicate(lambda x: x > 0)]], [math.inf], [-math.inf, 1.23, math.nan])
142
+
143
+ # doc
144
+ yield Case(Annotated[int, at.doc("A number")], [1, 2], [])
145
+
146
+ # custom GroupedMetadata
147
+ class MyCustomGroupedMetadata(at.GroupedMetadata):
148
+ def __iter__(self) -> Iterator[at.Predicate]:
149
+ yield at.Predicate(lambda x: float(x).is_integer())
150
+
151
+ yield Case(Annotated[float, MyCustomGroupedMetadata()], [0, 2.0], [0.01, 1.5])
TTS/Kokoro/.venv/Lib/site-packages/docopt.py ADDED
@@ -0,0 +1,579 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pythonic command-line interface parser that will make you smile.
2
+
3
+ * http://docopt.org
4
+ * Repository and issue-tracker: https://github.com/docopt/docopt
5
+ * Licensed under terms of MIT license (see LICENSE-MIT)
6
+ * Copyright (c) 2013 Vladimir Keleshev, vladimir@keleshev.com
7
+
8
+ """
9
+ import sys
10
+ import re
11
+
12
+
13
+ __all__ = ['docopt']
14
+ __version__ = '0.6.2'
15
+
16
+
17
+ class DocoptLanguageError(Exception):
18
+
19
+ """Error in construction of usage-message by developer."""
20
+
21
+
22
+ class DocoptExit(SystemExit):
23
+
24
+ """Exit in case user invoked program with incorrect arguments."""
25
+
26
+ usage = ''
27
+
28
+ def __init__(self, message=''):
29
+ SystemExit.__init__(self, (message + '\n' + self.usage).strip())
30
+
31
+
32
+ class Pattern(object):
33
+
34
+ def __eq__(self, other):
35
+ return repr(self) == repr(other)
36
+
37
+ def __hash__(self):
38
+ return hash(repr(self))
39
+
40
+ def fix(self):
41
+ self.fix_identities()
42
+ self.fix_repeating_arguments()
43
+ return self
44
+
45
+ def fix_identities(self, uniq=None):
46
+ """Make pattern-tree tips point to same object if they are equal."""
47
+ if not hasattr(self, 'children'):
48
+ return self
49
+ uniq = list(set(self.flat())) if uniq is None else uniq
50
+ for i, c in enumerate(self.children):
51
+ if not hasattr(c, 'children'):
52
+ assert c in uniq
53
+ self.children[i] = uniq[uniq.index(c)]
54
+ else:
55
+ c.fix_identities(uniq)
56
+
57
+ def fix_repeating_arguments(self):
58
+ """Fix elements that should accumulate/increment values."""
59
+ either = [list(c.children) for c in self.either.children]
60
+ for case in either:
61
+ for e in [c for c in case if case.count(c) > 1]:
62
+ if type(e) is Argument or type(e) is Option and e.argcount:
63
+ if e.value is None:
64
+ e.value = []
65
+ elif type(e.value) is not list:
66
+ e.value = e.value.split()
67
+ if type(e) is Command or type(e) is Option and e.argcount == 0:
68
+ e.value = 0
69
+ return self
70
+
71
+ @property
72
+ def either(self):
73
+ """Transform pattern into an equivalent, with only top-level Either."""
74
+ # Currently the pattern will not be equivalent, but more "narrow",
75
+ # although good enough to reason about list arguments.
76
+ ret = []
77
+ groups = [[self]]
78
+ while groups:
79
+ children = groups.pop(0)
80
+ types = [type(c) for c in children]
81
+ if Either in types:
82
+ either = [c for c in children if type(c) is Either][0]
83
+ children.pop(children.index(either))
84
+ for c in either.children:
85
+ groups.append([c] + children)
86
+ elif Required in types:
87
+ required = [c for c in children if type(c) is Required][0]
88
+ children.pop(children.index(required))
89
+ groups.append(list(required.children) + children)
90
+ elif Optional in types:
91
+ optional = [c for c in children if type(c) is Optional][0]
92
+ children.pop(children.index(optional))
93
+ groups.append(list(optional.children) + children)
94
+ elif AnyOptions in types:
95
+ optional = [c for c in children if type(c) is AnyOptions][0]
96
+ children.pop(children.index(optional))
97
+ groups.append(list(optional.children) + children)
98
+ elif OneOrMore in types:
99
+ oneormore = [c for c in children if type(c) is OneOrMore][0]
100
+ children.pop(children.index(oneormore))
101
+ groups.append(list(oneormore.children) * 2 + children)
102
+ else:
103
+ ret.append(children)
104
+ return Either(*[Required(*e) for e in ret])
105
+
106
+
107
+ class ChildPattern(Pattern):
108
+
109
+ def __init__(self, name, value=None):
110
+ self.name = name
111
+ self.value = value
112
+
113
+ def __repr__(self):
114
+ return '%s(%r, %r)' % (self.__class__.__name__, self.name, self.value)
115
+
116
+ def flat(self, *types):
117
+ return [self] if not types or type(self) in types else []
118
+
119
+ def match(self, left, collected=None):
120
+ collected = [] if collected is None else collected
121
+ pos, match = self.single_match(left)
122
+ if match is None:
123
+ return False, left, collected
124
+ left_ = left[:pos] + left[pos + 1:]
125
+ same_name = [a for a in collected if a.name == self.name]
126
+ if type(self.value) in (int, list):
127
+ if type(self.value) is int:
128
+ increment = 1
129
+ else:
130
+ increment = ([match.value] if type(match.value) is str
131
+ else match.value)
132
+ if not same_name:
133
+ match.value = increment
134
+ return True, left_, collected + [match]
135
+ same_name[0].value += increment
136
+ return True, left_, collected
137
+ return True, left_, collected + [match]
138
+
139
+
140
+ class ParentPattern(Pattern):
141
+
142
+ def __init__(self, *children):
143
+ self.children = list(children)
144
+
145
+ def __repr__(self):
146
+ return '%s(%s)' % (self.__class__.__name__,
147
+ ', '.join(repr(a) for a in self.children))
148
+
149
+ def flat(self, *types):
150
+ if type(self) in types:
151
+ return [self]
152
+ return sum([c.flat(*types) for c in self.children], [])
153
+
154
+
155
+ class Argument(ChildPattern):
156
+
157
+ def single_match(self, left):
158
+ for n, p in enumerate(left):
159
+ if type(p) is Argument:
160
+ return n, Argument(self.name, p.value)
161
+ return None, None
162
+
163
+ @classmethod
164
+ def parse(class_, source):
165
+ name = re.findall('(<\S*?>)', source)[0]
166
+ value = re.findall('\[default: (.*)\]', source, flags=re.I)
167
+ return class_(name, value[0] if value else None)
168
+
169
+
170
+ class Command(Argument):
171
+
172
+ def __init__(self, name, value=False):
173
+ self.name = name
174
+ self.value = value
175
+
176
+ def single_match(self, left):
177
+ for n, p in enumerate(left):
178
+ if type(p) is Argument:
179
+ if p.value == self.name:
180
+ return n, Command(self.name, True)
181
+ else:
182
+ break
183
+ return None, None
184
+
185
+
186
+ class Option(ChildPattern):
187
+
188
+ def __init__(self, short=None, long=None, argcount=0, value=False):
189
+ assert argcount in (0, 1)
190
+ self.short, self.long = short, long
191
+ self.argcount, self.value = argcount, value
192
+ self.value = None if value is False and argcount else value
193
+
194
+ @classmethod
195
+ def parse(class_, option_description):
196
+ short, long, argcount, value = None, None, 0, False
197
+ options, _, description = option_description.strip().partition(' ')
198
+ options = options.replace(',', ' ').replace('=', ' ')
199
+ for s in options.split():
200
+ if s.startswith('--'):
201
+ long = s
202
+ elif s.startswith('-'):
203
+ short = s
204
+ else:
205
+ argcount = 1
206
+ if argcount:
207
+ matched = re.findall('\[default: (.*)\]', description, flags=re.I)
208
+ value = matched[0] if matched else None
209
+ return class_(short, long, argcount, value)
210
+
211
+ def single_match(self, left):
212
+ for n, p in enumerate(left):
213
+ if self.name == p.name:
214
+ return n, p
215
+ return None, None
216
+
217
+ @property
218
+ def name(self):
219
+ return self.long or self.short
220
+
221
+ def __repr__(self):
222
+ return 'Option(%r, %r, %r, %r)' % (self.short, self.long,
223
+ self.argcount, self.value)
224
+
225
+
226
+ class Required(ParentPattern):
227
+
228
+ def match(self, left, collected=None):
229
+ collected = [] if collected is None else collected
230
+ l = left
231
+ c = collected
232
+ for p in self.children:
233
+ matched, l, c = p.match(l, c)
234
+ if not matched:
235
+ return False, left, collected
236
+ return True, l, c
237
+
238
+
239
+ class Optional(ParentPattern):
240
+
241
+ def match(self, left, collected=None):
242
+ collected = [] if collected is None else collected
243
+ for p in self.children:
244
+ m, left, collected = p.match(left, collected)
245
+ return True, left, collected
246
+
247
+
248
+ class AnyOptions(Optional):
249
+
250
+ """Marker/placeholder for [options] shortcut."""
251
+
252
+
253
+ class OneOrMore(ParentPattern):
254
+
255
+ def match(self, left, collected=None):
256
+ assert len(self.children) == 1
257
+ collected = [] if collected is None else collected
258
+ l = left
259
+ c = collected
260
+ l_ = None
261
+ matched = True
262
+ times = 0
263
+ while matched:
264
+ # could it be that something didn't match but changed l or c?
265
+ matched, l, c = self.children[0].match(l, c)
266
+ times += 1 if matched else 0
267
+ if l_ == l:
268
+ break
269
+ l_ = l
270
+ if times >= 1:
271
+ return True, l, c
272
+ return False, left, collected
273
+
274
+
275
+ class Either(ParentPattern):
276
+
277
+ def match(self, left, collected=None):
278
+ collected = [] if collected is None else collected
279
+ outcomes = []
280
+ for p in self.children:
281
+ matched, _, _ = outcome = p.match(left, collected)
282
+ if matched:
283
+ outcomes.append(outcome)
284
+ if outcomes:
285
+ return min(outcomes, key=lambda outcome: len(outcome[1]))
286
+ return False, left, collected
287
+
288
+
289
+ class TokenStream(list):
290
+
291
+ def __init__(self, source, error):
292
+ self += source.split() if hasattr(source, 'split') else source
293
+ self.error = error
294
+
295
+ def move(self):
296
+ return self.pop(0) if len(self) else None
297
+
298
+ def current(self):
299
+ return self[0] if len(self) else None
300
+
301
+
302
+ def parse_long(tokens, options):
303
+ """long ::= '--' chars [ ( ' ' | '=' ) chars ] ;"""
304
+ long, eq, value = tokens.move().partition('=')
305
+ assert long.startswith('--')
306
+ value = None if eq == value == '' else value
307
+ similar = [o for o in options if o.long == long]
308
+ if tokens.error is DocoptExit and similar == []: # if no exact match
309
+ similar = [o for o in options if o.long and o.long.startswith(long)]
310
+ if len(similar) > 1: # might be simply specified ambiguously 2+ times?
311
+ raise tokens.error('%s is not a unique prefix: %s?' %
312
+ (long, ', '.join(o.long for o in similar)))
313
+ elif len(similar) < 1:
314
+ argcount = 1 if eq == '=' else 0
315
+ o = Option(None, long, argcount)
316
+ options.append(o)
317
+ if tokens.error is DocoptExit:
318
+ o = Option(None, long, argcount, value if argcount else True)
319
+ else:
320
+ o = Option(similar[0].short, similar[0].long,
321
+ similar[0].argcount, similar[0].value)
322
+ if o.argcount == 0:
323
+ if value is not None:
324
+ raise tokens.error('%s must not have an argument' % o.long)
325
+ else:
326
+ if value is None:
327
+ if tokens.current() is None:
328
+ raise tokens.error('%s requires argument' % o.long)
329
+ value = tokens.move()
330
+ if tokens.error is DocoptExit:
331
+ o.value = value if value is not None else True
332
+ return [o]
333
+
334
+
335
+ def parse_shorts(tokens, options):
336
+ """shorts ::= '-' ( chars )* [ [ ' ' ] chars ] ;"""
337
+ token = tokens.move()
338
+ assert token.startswith('-') and not token.startswith('--')
339
+ left = token.lstrip('-')
340
+ parsed = []
341
+ while left != '':
342
+ short, left = '-' + left[0], left[1:]
343
+ similar = [o for o in options if o.short == short]
344
+ if len(similar) > 1:
345
+ raise tokens.error('%s is specified ambiguously %d times' %
346
+ (short, len(similar)))
347
+ elif len(similar) < 1:
348
+ o = Option(short, None, 0)
349
+ options.append(o)
350
+ if tokens.error is DocoptExit:
351
+ o = Option(short, None, 0, True)
352
+ else: # why copying is necessary here?
353
+ o = Option(short, similar[0].long,
354
+ similar[0].argcount, similar[0].value)
355
+ value = None
356
+ if o.argcount != 0:
357
+ if left == '':
358
+ if tokens.current() is None:
359
+ raise tokens.error('%s requires argument' % short)
360
+ value = tokens.move()
361
+ else:
362
+ value = left
363
+ left = ''
364
+ if tokens.error is DocoptExit:
365
+ o.value = value if value is not None else True
366
+ parsed.append(o)
367
+ return parsed
368
+
369
+
370
+ def parse_pattern(source, options):
371
+ tokens = TokenStream(re.sub(r'([\[\]\(\)\|]|\.\.\.)', r' \1 ', source),
372
+ DocoptLanguageError)
373
+ result = parse_expr(tokens, options)
374
+ if tokens.current() is not None:
375
+ raise tokens.error('unexpected ending: %r' % ' '.join(tokens))
376
+ return Required(*result)
377
+
378
+
379
+ def parse_expr(tokens, options):
380
+ """expr ::= seq ( '|' seq )* ;"""
381
+ seq = parse_seq(tokens, options)
382
+ if tokens.current() != '|':
383
+ return seq
384
+ result = [Required(*seq)] if len(seq) > 1 else seq
385
+ while tokens.current() == '|':
386
+ tokens.move()
387
+ seq = parse_seq(tokens, options)
388
+ result += [Required(*seq)] if len(seq) > 1 else seq
389
+ return [Either(*result)] if len(result) > 1 else result
390
+
391
+
392
+ def parse_seq(tokens, options):
393
+ """seq ::= ( atom [ '...' ] )* ;"""
394
+ result = []
395
+ while tokens.current() not in [None, ']', ')', '|']:
396
+ atom = parse_atom(tokens, options)
397
+ if tokens.current() == '...':
398
+ atom = [OneOrMore(*atom)]
399
+ tokens.move()
400
+ result += atom
401
+ return result
402
+
403
+
404
+ def parse_atom(tokens, options):
405
+ """atom ::= '(' expr ')' | '[' expr ']' | 'options'
406
+ | long | shorts | argument | command ;
407
+ """
408
+ token = tokens.current()
409
+ result = []
410
+ if token in '([':
411
+ tokens.move()
412
+ matching, pattern = {'(': [')', Required], '[': [']', Optional]}[token]
413
+ result = pattern(*parse_expr(tokens, options))
414
+ if tokens.move() != matching:
415
+ raise tokens.error("unmatched '%s'" % token)
416
+ return [result]
417
+ elif token == 'options':
418
+ tokens.move()
419
+ return [AnyOptions()]
420
+ elif token.startswith('--') and token != '--':
421
+ return parse_long(tokens, options)
422
+ elif token.startswith('-') and token not in ('-', '--'):
423
+ return parse_shorts(tokens, options)
424
+ elif token.startswith('<') and token.endswith('>') or token.isupper():
425
+ return [Argument(tokens.move())]
426
+ else:
427
+ return [Command(tokens.move())]
428
+
429
+
430
+ def parse_argv(tokens, options, options_first=False):
431
+ """Parse command-line argument vector.
432
+
433
+ If options_first:
434
+ argv ::= [ long | shorts ]* [ argument ]* [ '--' [ argument ]* ] ;
435
+ else:
436
+ argv ::= [ long | shorts | argument ]* [ '--' [ argument ]* ] ;
437
+
438
+ """
439
+ parsed = []
440
+ while tokens.current() is not None:
441
+ if tokens.current() == '--':
442
+ return parsed + [Argument(None, v) for v in tokens]
443
+ elif tokens.current().startswith('--'):
444
+ parsed += parse_long(tokens, options)
445
+ elif tokens.current().startswith('-') and tokens.current() != '-':
446
+ parsed += parse_shorts(tokens, options)
447
+ elif options_first:
448
+ return parsed + [Argument(None, v) for v in tokens]
449
+ else:
450
+ parsed.append(Argument(None, tokens.move()))
451
+ return parsed
452
+
453
+
454
+ def parse_defaults(doc):
455
+ # in python < 2.7 you can't pass flags=re.MULTILINE
456
+ split = re.split('\n *(<\S+?>|-\S+?)', doc)[1:]
457
+ split = [s1 + s2 for s1, s2 in zip(split[::2], split[1::2])]
458
+ options = [Option.parse(s) for s in split if s.startswith('-')]
459
+ #arguments = [Argument.parse(s) for s in split if s.startswith('<')]
460
+ #return options, arguments
461
+ return options
462
+
463
+
464
+ def printable_usage(doc):
465
+ # in python < 2.7 you can't pass flags=re.IGNORECASE
466
+ usage_split = re.split(r'([Uu][Ss][Aa][Gg][Ee]:)', doc)
467
+ if len(usage_split) < 3:
468
+ raise DocoptLanguageError('"usage:" (case-insensitive) not found.')
469
+ if len(usage_split) > 3:
470
+ raise DocoptLanguageError('More than one "usage:" (case-insensitive).')
471
+ return re.split(r'\n\s*\n', ''.join(usage_split[1:]))[0].strip()
472
+
473
+
474
+ def formal_usage(printable_usage):
475
+ pu = printable_usage.split()[1:] # split and drop "usage:"
476
+ return '( ' + ' '.join(') | (' if s == pu[0] else s for s in pu[1:]) + ' )'
477
+
478
+
479
+ def extras(help, version, options, doc):
480
+ if help and any((o.name in ('-h', '--help')) and o.value for o in options):
481
+ print(doc.strip("\n"))
482
+ sys.exit()
483
+ if version and any(o.name == '--version' and o.value for o in options):
484
+ print(version)
485
+ sys.exit()
486
+
487
+
488
+ class Dict(dict):
489
+ def __repr__(self):
490
+ return '{%s}' % ',\n '.join('%r: %r' % i for i in sorted(self.items()))
491
+
492
+
493
+ def docopt(doc, argv=None, help=True, version=None, options_first=False):
494
+ """Parse `argv` based on command-line interface described in `doc`.
495
+
496
+ `docopt` creates your command-line interface based on its
497
+ description that you pass as `doc`. Such description can contain
498
+ --options, <positional-argument>, commands, which could be
499
+ [optional], (required), (mutually | exclusive) or repeated...
500
+
501
+ Parameters
502
+ ----------
503
+ doc : str
504
+ Description of your command-line interface.
505
+ argv : list of str, optional
506
+ Argument vector to be parsed. sys.argv[1:] is used if not
507
+ provided.
508
+ help : bool (default: True)
509
+ Set to False to disable automatic help on -h or --help
510
+ options.
511
+ version : any object
512
+ If passed, the object will be printed if --version is in
513
+ `argv`.
514
+ options_first : bool (default: False)
515
+ Set to True to require options preceed positional arguments,
516
+ i.e. to forbid options and positional arguments intermix.
517
+
518
+ Returns
519
+ -------
520
+ args : dict
521
+ A dictionary, where keys are names of command-line elements
522
+ such as e.g. "--verbose" and "<path>", and values are the
523
+ parsed values of those elements.
524
+
525
+ Example
526
+ -------
527
+ >>> from docopt import docopt
528
+ >>> doc = '''
529
+ Usage:
530
+ my_program tcp <host> <port> [--timeout=<seconds>]
531
+ my_program serial <port> [--baud=<n>] [--timeout=<seconds>]
532
+ my_program (-h | --help | --version)
533
+
534
+ Options:
535
+ -h, --help Show this screen and exit.
536
+ --baud=<n> Baudrate [default: 9600]
537
+ '''
538
+ >>> argv = ['tcp', '127.0.0.1', '80', '--timeout', '30']
539
+ >>> docopt(doc, argv)
540
+ {'--baud': '9600',
541
+ '--help': False,
542
+ '--timeout': '30',
543
+ '--version': False,
544
+ '<host>': '127.0.0.1',
545
+ '<port>': '80',
546
+ 'serial': False,
547
+ 'tcp': True}
548
+
549
+ See also
550
+ --------
551
+ * For video introduction see http://docopt.org
552
+ * Full documentation is available in README.rst as well as online
553
+ at https://github.com/docopt/docopt#readme
554
+
555
+ """
556
+ if argv is None:
557
+ argv = sys.argv[1:]
558
+ DocoptExit.usage = printable_usage(doc)
559
+ options = parse_defaults(doc)
560
+ pattern = parse_pattern(formal_usage(DocoptExit.usage), options)
561
+ # [default] syntax for argument is disabled
562
+ #for a in pattern.flat(Argument):
563
+ # same_name = [d for d in arguments if d.name == a.name]
564
+ # if same_name:
565
+ # a.value = same_name[0].value
566
+ argv = parse_argv(TokenStream(argv, DocoptExit), list(options),
567
+ options_first)
568
+ pattern_options = set(pattern.flat(Option))
569
+ for ao in pattern.flat(AnyOptions):
570
+ doc_options = parse_defaults(doc)
571
+ ao.children = list(set(doc_options) - pattern_options)
572
+ #if any_options:
573
+ # ao.children += [Option(o.short, o.long, o.argcount)
574
+ # for o in argv if type(o) is Option]
575
+ extras(help, version, argv, doc)
576
+ matched, left, collected = pattern.fix().match(argv)
577
+ if matched and left == []: # better error message if left?
578
+ return Dict((a.name, a.value) for a in (pattern.flat() + collected))
579
+ raise DocoptExit()
TTS/Kokoro/.venv/Lib/site-packages/isympy.py ADDED
@@ -0,0 +1,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Python shell for SymPy.
3
+
4
+ This is just a normal Python shell (IPython shell if you have the
5
+ IPython package installed), that executes the following commands for
6
+ the user:
7
+
8
+ >>> from __future__ import division
9
+ >>> from sympy import *
10
+ >>> x, y, z, t = symbols('x y z t')
11
+ >>> k, m, n = symbols('k m n', integer=True)
12
+ >>> f, g, h = symbols('f g h', cls=Function)
13
+ >>> init_printing()
14
+
15
+ So starting 'isympy' is equivalent to starting Python (or IPython) and
16
+ executing the above commands by hand. It is intended for easy and quick
17
+ experimentation with SymPy. isympy is a good way to use SymPy as an
18
+ interactive calculator. If you have IPython and Matplotlib installed, then
19
+ interactive plotting is enabled by default.
20
+
21
+ COMMAND LINE OPTIONS
22
+ --------------------
23
+
24
+ -c CONSOLE, --console=CONSOLE
25
+
26
+ Use the specified shell (Python or IPython) shell as the console
27
+ backend instead of the default one (IPython if present, Python
28
+ otherwise), e.g.:
29
+
30
+ $isympy -c python
31
+
32
+ CONSOLE must be one of 'ipython' or 'python'
33
+
34
+ -p PRETTY, --pretty PRETTY
35
+
36
+ Setup pretty-printing in SymPy. When pretty-printing is enabled,
37
+ expressions can be printed with Unicode or ASCII. The default is
38
+ to use pretty-printing (with Unicode if the terminal supports it).
39
+ When this option is 'no', expressions will not be pretty-printed
40
+ and ASCII will be used:
41
+
42
+ $isympy -p no
43
+
44
+ PRETTY must be one of 'unicode', 'ascii', or 'no'
45
+
46
+ -t TYPES, --types=TYPES
47
+
48
+ Setup the ground types for the polys. By default, gmpy ground types
49
+ are used if gmpy2 or gmpy is installed, otherwise it falls back to python
50
+ ground types, which are a little bit slower. You can manually
51
+ choose python ground types even if gmpy is installed (e.g., for
52
+ testing purposes):
53
+
54
+ $isympy -t python
55
+
56
+ TYPES must be one of 'gmpy', 'gmpy1' or 'python'
57
+
58
+ Note that the ground type gmpy1 is primarily intended for testing; it
59
+ forces the use of gmpy version 1 even if gmpy2 is available.
60
+
61
+ This is the same as setting the environment variable
62
+ SYMPY_GROUND_TYPES to the given ground type (e.g.,
63
+ SYMPY_GROUND_TYPES='gmpy')
64
+
65
+ The ground types can be determined interactively from the variable
66
+ sympy.polys.domains.GROUND_TYPES.
67
+
68
+ -o ORDER, --order ORDER
69
+
70
+ Setup the ordering of terms for printing. The default is lex, which
71
+ orders terms lexicographically (e.g., x**2 + x + 1). You can choose
72
+ other orderings, such as rev-lex, which will use reverse
73
+ lexicographic ordering (e.g., 1 + x + x**2):
74
+
75
+ $isympy -o rev-lex
76
+
77
+ ORDER must be one of 'lex', 'rev-lex', 'grlex', 'rev-grlex',
78
+ 'grevlex', 'rev-grevlex', 'old', or 'none'.
79
+
80
+ Note that for very large expressions, ORDER='none' may speed up
81
+ printing considerably but the terms will have no canonical order.
82
+
83
+ -q, --quiet
84
+
85
+ Print only Python's and SymPy's versions to stdout at startup.
86
+
87
+ -d, --doctest
88
+
89
+ Use the same format that should be used for doctests. This is
90
+ equivalent to -c python -p no.
91
+
92
+ -C, --no-cache
93
+
94
+ Disable the caching mechanism. Disabling the cache may slow certain
95
+ operations down considerably. This is useful for testing the cache,
96
+ or for benchmarking, as the cache can result in deceptive timings.
97
+
98
+ This is equivalent to setting the environment variable
99
+ SYMPY_USE_CACHE to 'no'.
100
+
101
+ -a, --auto-symbols (requires at least IPython 0.11)
102
+
103
+ Automatically create missing symbols. Normally, typing a name of a
104
+ Symbol that has not been instantiated first would raise NameError,
105
+ but with this option enabled, any undefined name will be
106
+ automatically created as a Symbol.
107
+
108
+ Note that this is intended only for interactive, calculator style
109
+ usage. In a script that uses SymPy, Symbols should be instantiated
110
+ at the top, so that it's clear what they are.
111
+
112
+ This will not override any names that are already defined, which
113
+ includes the single character letters represented by the mnemonic
114
+ QCOSINE (see the "Gotchas and Pitfalls" document in the
115
+ documentation). You can delete existing names by executing "del
116
+ name". If a name is defined, typing "'name' in dir()" will return True.
117
+
118
+ The Symbols that are created using this have default assumptions.
119
+ If you want to place assumptions on symbols, you should create them
120
+ using symbols() or var().
121
+
122
+ Finally, this only works in the top level namespace. So, for
123
+ example, if you define a function in isympy with an undefined
124
+ Symbol, it will not work.
125
+
126
+ See also the -i and -I options.
127
+
128
+ -i, --int-to-Integer (requires at least IPython 0.11)
129
+
130
+ Automatically wrap int literals with Integer. This makes it so that
131
+ things like 1/2 will come out as Rational(1, 2), rather than 0.5. This
132
+ works by preprocessing the source and wrapping all int literals with
133
+ Integer. Note that this will not change the behavior of int literals
134
+ assigned to variables, and it also won't change the behavior of functions
135
+ that return int literals.
136
+
137
+ If you want an int, you can wrap the literal in int(), e.g. int(3)/int(2)
138
+ gives 1.5 (with division imported from __future__).
139
+
140
+ -I, --interactive (requires at least IPython 0.11)
141
+
142
+ This is equivalent to --auto-symbols --int-to-Integer. Future options
143
+ designed for ease of interactive use may be added to this.
144
+
145
+ -D, --debug
146
+
147
+ Enable debugging output. This is the same as setting the
148
+ environment variable SYMPY_DEBUG to 'True'. The debug status is set
149
+ in the variable SYMPY_DEBUG within isympy.
150
+
151
+ -- IPython options
152
+
153
+ Additionally you can pass command line options directly to the IPython
154
+ interpreter (the standard Python shell is not supported). However you
155
+ need to add the '--' separator between two types of options, e.g the
156
+ startup banner option and the colors option. You need to enter the
157
+ options as required by the version of IPython that you are using, too:
158
+
159
+ in IPython 0.11,
160
+
161
+ $isympy -q -- --colors=NoColor
162
+
163
+ or older versions of IPython,
164
+
165
+ $isympy -q -- -colors NoColor
166
+
167
+ See also isympy --help.
168
+ """
169
+
170
+ import os
171
+ import sys
172
+
173
+ # DO NOT IMPORT SYMPY HERE! Or the setting of the sympy environment variables
174
+ # by the command line will break.
175
+
176
+ def main() -> None:
177
+ from argparse import ArgumentParser, RawDescriptionHelpFormatter
178
+
179
+ VERSION = None
180
+ if '--version' in sys.argv:
181
+ # We cannot import sympy before this is run, because flags like -C and
182
+ # -t set environment variables that must be set before SymPy is
183
+ # imported. The only thing we need to import it for is to get the
184
+ # version, which only matters with the --version flag.
185
+ import sympy
186
+ VERSION = sympy.__version__
187
+
188
+ usage = 'isympy [options] -- [ipython options]'
189
+ parser = ArgumentParser(
190
+ usage=usage,
191
+ description=__doc__,
192
+ formatter_class=RawDescriptionHelpFormatter,
193
+ )
194
+
195
+ parser.add_argument('--version', action='version', version=VERSION)
196
+
197
+ parser.add_argument(
198
+ '-c', '--console',
199
+ dest='console',
200
+ action='store',
201
+ default=None,
202
+ choices=['ipython', 'python'],
203
+ metavar='CONSOLE',
204
+ help='select type of interactive session: ipython | python; defaults '
205
+ 'to ipython if IPython is installed, otherwise python')
206
+
207
+ parser.add_argument(
208
+ '-p', '--pretty',
209
+ dest='pretty',
210
+ action='store',
211
+ default=None,
212
+ metavar='PRETTY',
213
+ choices=['unicode', 'ascii', 'no'],
214
+ help='setup pretty printing: unicode | ascii | no; defaults to '
215
+ 'unicode printing if the terminal supports it, otherwise ascii')
216
+
217
+ parser.add_argument(
218
+ '-t', '--types',
219
+ dest='types',
220
+ action='store',
221
+ default=None,
222
+ metavar='TYPES',
223
+ choices=['gmpy', 'gmpy1', 'python'],
224
+ help='setup ground types: gmpy | gmpy1 | python; defaults to gmpy if gmpy2 '
225
+ 'or gmpy is installed, otherwise python')
226
+
227
+ parser.add_argument(
228
+ '-o', '--order',
229
+ dest='order',
230
+ action='store',
231
+ default=None,
232
+ metavar='ORDER',
233
+ choices=['lex', 'grlex', 'grevlex', 'rev-lex', 'rev-grlex', 'rev-grevlex', 'old', 'none'],
234
+ help='setup ordering of terms: [rev-]lex | [rev-]grlex | [rev-]grevlex | old | none; defaults to lex')
235
+
236
+ parser.add_argument(
237
+ '-q', '--quiet',
238
+ dest='quiet',
239
+ action='store_true',
240
+ default=False,
241
+ help='print only version information at startup')
242
+
243
+ parser.add_argument(
244
+ '-d', '--doctest',
245
+ dest='doctest',
246
+ action='store_true',
247
+ default=False,
248
+ help='use the doctest format for output (you can just copy and paste it)')
249
+
250
+ parser.add_argument(
251
+ '-C', '--no-cache',
252
+ dest='cache',
253
+ action='store_false',
254
+ default=True,
255
+ help='disable caching mechanism')
256
+
257
+ parser.add_argument(
258
+ '-a', '--auto-symbols',
259
+ dest='auto_symbols',
260
+ action='store_true',
261
+ default=False,
262
+ help='automatically construct missing symbols')
263
+
264
+ parser.add_argument(
265
+ '-i', '--int-to-Integer',
266
+ dest='auto_int_to_Integer',
267
+ action='store_true',
268
+ default=False,
269
+ help="automatically wrap int literals with Integer")
270
+
271
+ parser.add_argument(
272
+ '-I', '--interactive',
273
+ dest='interactive',
274
+ action='store_true',
275
+ default=False,
276
+ help="equivalent to -a -i")
277
+
278
+ parser.add_argument(
279
+ '-D', '--debug',
280
+ dest='debug',
281
+ action='store_true',
282
+ default=False,
283
+ help='enable debugging output')
284
+
285
+ (options, ipy_args) = parser.parse_known_args()
286
+ if '--' in ipy_args:
287
+ ipy_args.remove('--')
288
+
289
+ if not options.cache:
290
+ os.environ['SYMPY_USE_CACHE'] = 'no'
291
+
292
+ if options.types:
293
+ os.environ['SYMPY_GROUND_TYPES'] = options.types
294
+
295
+ if options.debug:
296
+ os.environ['SYMPY_DEBUG'] = str(options.debug)
297
+
298
+ if options.doctest:
299
+ options.pretty = 'no'
300
+ options.console = 'python'
301
+
302
+ session = options.console
303
+
304
+ if session is not None:
305
+ ipython = session == 'ipython'
306
+ else:
307
+ try:
308
+ import IPython # noqa: F401
309
+ ipython = True
310
+ except ImportError:
311
+ if not options.quiet:
312
+ from sympy.interactive.session import no_ipython
313
+ print(no_ipython)
314
+ ipython = False
315
+
316
+ args = {
317
+ 'pretty_print': True,
318
+ 'use_unicode': None,
319
+ 'use_latex': None,
320
+ 'order': None,
321
+ 'argv': ipy_args,
322
+ }
323
+
324
+ if options.pretty == 'unicode':
325
+ args['use_unicode'] = True
326
+ elif options.pretty == 'ascii':
327
+ args['use_unicode'] = False
328
+ elif options.pretty == 'no':
329
+ args['pretty_print'] = False
330
+
331
+ if options.order is not None:
332
+ args['order'] = options.order
333
+
334
+ args['quiet'] = options.quiet
335
+ args['auto_symbols'] = options.auto_symbols or options.interactive
336
+ args['auto_int_to_Integer'] = options.auto_int_to_Integer or options.interactive
337
+
338
+ from sympy.interactive import init_session
339
+ init_session(ipython, **args)
340
+
341
+ if __name__ == "__main__":
342
+ main()
TTS/Kokoro/.venv/Lib/site-packages/six.py ADDED
@@ -0,0 +1,1003 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2010-2024 Benjamin Peterson
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ # of this software and associated documentation files (the "Software"), to deal
5
+ # in the Software without restriction, including without limitation the rights
6
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ # copies of the Software, and to permit persons to whom the Software is
8
+ # furnished to do so, subject to the following conditions:
9
+ #
10
+ # The above copyright notice and this permission notice shall be included in all
11
+ # copies or substantial portions of the Software.
12
+ #
13
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ # SOFTWARE.
20
+
21
+ """Utilities for writing code that runs on Python 2 and 3"""
22
+
23
+ from __future__ import absolute_import
24
+
25
+ import functools
26
+ import itertools
27
+ import operator
28
+ import sys
29
+ import types
30
+
31
+ __author__ = "Benjamin Peterson <benjamin@python.org>"
32
+ __version__ = "1.17.0"
33
+
34
+
35
+ # Useful for very coarse version differentiation.
36
+ PY2 = sys.version_info[0] == 2
37
+ PY3 = sys.version_info[0] == 3
38
+ PY34 = sys.version_info[0:2] >= (3, 4)
39
+
40
+ if PY3:
41
+ string_types = str,
42
+ integer_types = int,
43
+ class_types = type,
44
+ text_type = str
45
+ binary_type = bytes
46
+
47
+ MAXSIZE = sys.maxsize
48
+ else:
49
+ string_types = basestring,
50
+ integer_types = (int, long)
51
+ class_types = (type, types.ClassType)
52
+ text_type = unicode
53
+ binary_type = str
54
+
55
+ if sys.platform.startswith("java"):
56
+ # Jython always uses 32 bits.
57
+ MAXSIZE = int((1 << 31) - 1)
58
+ else:
59
+ # It's possible to have sizeof(long) != sizeof(Py_ssize_t).
60
+ class X(object):
61
+
62
+ def __len__(self):
63
+ return 1 << 31
64
+ try:
65
+ len(X())
66
+ except OverflowError:
67
+ # 32-bit
68
+ MAXSIZE = int((1 << 31) - 1)
69
+ else:
70
+ # 64-bit
71
+ MAXSIZE = int((1 << 63) - 1)
72
+ del X
73
+
74
+ if PY34:
75
+ from importlib.util import spec_from_loader
76
+ else:
77
+ spec_from_loader = None
78
+
79
+
80
+ def _add_doc(func, doc):
81
+ """Add documentation to a function."""
82
+ func.__doc__ = doc
83
+
84
+
85
+ def _import_module(name):
86
+ """Import module, returning the module after the last dot."""
87
+ __import__(name)
88
+ return sys.modules[name]
89
+
90
+
91
+ class _LazyDescr(object):
92
+
93
+ def __init__(self, name):
94
+ self.name = name
95
+
96
+ def __get__(self, obj, tp):
97
+ result = self._resolve()
98
+ setattr(obj, self.name, result) # Invokes __set__.
99
+ try:
100
+ # This is a bit ugly, but it avoids running this again by
101
+ # removing this descriptor.
102
+ delattr(obj.__class__, self.name)
103
+ except AttributeError:
104
+ pass
105
+ return result
106
+
107
+
108
+ class MovedModule(_LazyDescr):
109
+
110
+ def __init__(self, name, old, new=None):
111
+ super(MovedModule, self).__init__(name)
112
+ if PY3:
113
+ if new is None:
114
+ new = name
115
+ self.mod = new
116
+ else:
117
+ self.mod = old
118
+
119
+ def _resolve(self):
120
+ return _import_module(self.mod)
121
+
122
+ def __getattr__(self, attr):
123
+ _module = self._resolve()
124
+ value = getattr(_module, attr)
125
+ setattr(self, attr, value)
126
+ return value
127
+
128
+
129
+ class _LazyModule(types.ModuleType):
130
+
131
+ def __init__(self, name):
132
+ super(_LazyModule, self).__init__(name)
133
+ self.__doc__ = self.__class__.__doc__
134
+
135
+ def __dir__(self):
136
+ attrs = ["__doc__", "__name__"]
137
+ attrs += [attr.name for attr in self._moved_attributes]
138
+ return attrs
139
+
140
+ # Subclasses should override this
141
+ _moved_attributes = []
142
+
143
+
144
+ class MovedAttribute(_LazyDescr):
145
+
146
+ def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None):
147
+ super(MovedAttribute, self).__init__(name)
148
+ if PY3:
149
+ if new_mod is None:
150
+ new_mod = name
151
+ self.mod = new_mod
152
+ if new_attr is None:
153
+ if old_attr is None:
154
+ new_attr = name
155
+ else:
156
+ new_attr = old_attr
157
+ self.attr = new_attr
158
+ else:
159
+ self.mod = old_mod
160
+ if old_attr is None:
161
+ old_attr = name
162
+ self.attr = old_attr
163
+
164
+ def _resolve(self):
165
+ module = _import_module(self.mod)
166
+ return getattr(module, self.attr)
167
+
168
+
169
+ class _SixMetaPathImporter(object):
170
+
171
+ """
172
+ A meta path importer to import six.moves and its submodules.
173
+
174
+ This class implements a PEP302 finder and loader. It should be compatible
175
+ with Python 2.5 and all existing versions of Python3
176
+ """
177
+
178
+ def __init__(self, six_module_name):
179
+ self.name = six_module_name
180
+ self.known_modules = {}
181
+
182
+ def _add_module(self, mod, *fullnames):
183
+ for fullname in fullnames:
184
+ self.known_modules[self.name + "." + fullname] = mod
185
+
186
+ def _get_module(self, fullname):
187
+ return self.known_modules[self.name + "." + fullname]
188
+
189
+ def find_module(self, fullname, path=None):
190
+ if fullname in self.known_modules:
191
+ return self
192
+ return None
193
+
194
+ def find_spec(self, fullname, path, target=None):
195
+ if fullname in self.known_modules:
196
+ return spec_from_loader(fullname, self)
197
+ return None
198
+
199
+ def __get_module(self, fullname):
200
+ try:
201
+ return self.known_modules[fullname]
202
+ except KeyError:
203
+ raise ImportError("This loader does not know module " + fullname)
204
+
205
+ def load_module(self, fullname):
206
+ try:
207
+ # in case of a reload
208
+ return sys.modules[fullname]
209
+ except KeyError:
210
+ pass
211
+ mod = self.__get_module(fullname)
212
+ if isinstance(mod, MovedModule):
213
+ mod = mod._resolve()
214
+ else:
215
+ mod.__loader__ = self
216
+ sys.modules[fullname] = mod
217
+ return mod
218
+
219
+ def is_package(self, fullname):
220
+ """
221
+ Return true, if the named module is a package.
222
+
223
+ We need this method to get correct spec objects with
224
+ Python 3.4 (see PEP451)
225
+ """
226
+ return hasattr(self.__get_module(fullname), "__path__")
227
+
228
+ def get_code(self, fullname):
229
+ """Return None
230
+
231
+ Required, if is_package is implemented"""
232
+ self.__get_module(fullname) # eventually raises ImportError
233
+ return None
234
+ get_source = get_code # same as get_code
235
+
236
+ def create_module(self, spec):
237
+ return self.load_module(spec.name)
238
+
239
+ def exec_module(self, module):
240
+ pass
241
+
242
+ _importer = _SixMetaPathImporter(__name__)
243
+
244
+
245
+ class _MovedItems(_LazyModule):
246
+
247
+ """Lazy loading of moved objects"""
248
+ __path__ = [] # mark as package
249
+
250
+
251
+ _moved_attributes = [
252
+ MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"),
253
+ MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"),
254
+ MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"),
255
+ MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"),
256
+ MovedAttribute("intern", "__builtin__", "sys"),
257
+ MovedAttribute("map", "itertools", "builtins", "imap", "map"),
258
+ MovedAttribute("getcwd", "os", "os", "getcwdu", "getcwd"),
259
+ MovedAttribute("getcwdb", "os", "os", "getcwd", "getcwdb"),
260
+ MovedAttribute("getoutput", "commands", "subprocess"),
261
+ MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"),
262
+ MovedAttribute("reload_module", "__builtin__", "importlib" if PY34 else "imp", "reload"),
263
+ MovedAttribute("reduce", "__builtin__", "functools"),
264
+ MovedAttribute("shlex_quote", "pipes", "shlex", "quote"),
265
+ MovedAttribute("StringIO", "StringIO", "io"),
266
+ MovedAttribute("UserDict", "UserDict", "collections", "IterableUserDict", "UserDict"),
267
+ MovedAttribute("UserList", "UserList", "collections"),
268
+ MovedAttribute("UserString", "UserString", "collections"),
269
+ MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"),
270
+ MovedAttribute("zip", "itertools", "builtins", "izip", "zip"),
271
+ MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"),
272
+ MovedModule("builtins", "__builtin__"),
273
+ MovedModule("configparser", "ConfigParser"),
274
+ MovedModule("collections_abc", "collections", "collections.abc" if sys.version_info >= (3, 3) else "collections"),
275
+ MovedModule("copyreg", "copy_reg"),
276
+ MovedModule("dbm_gnu", "gdbm", "dbm.gnu"),
277
+ MovedModule("dbm_ndbm", "dbm", "dbm.ndbm"),
278
+ MovedModule("_dummy_thread", "dummy_thread", "_dummy_thread" if sys.version_info < (3, 9) else "_thread"),
279
+ MovedModule("http_cookiejar", "cookielib", "http.cookiejar"),
280
+ MovedModule("http_cookies", "Cookie", "http.cookies"),
281
+ MovedModule("html_entities", "htmlentitydefs", "html.entities"),
282
+ MovedModule("html_parser", "HTMLParser", "html.parser"),
283
+ MovedModule("http_client", "httplib", "http.client"),
284
+ MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"),
285
+ MovedModule("email_mime_image", "email.MIMEImage", "email.mime.image"),
286
+ MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"),
287
+ MovedModule("email_mime_nonmultipart", "email.MIMENonMultipart", "email.mime.nonmultipart"),
288
+ MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"),
289
+ MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"),
290
+ MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"),
291
+ MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"),
292
+ MovedModule("cPickle", "cPickle", "pickle"),
293
+ MovedModule("queue", "Queue"),
294
+ MovedModule("reprlib", "repr"),
295
+ MovedModule("socketserver", "SocketServer"),
296
+ MovedModule("_thread", "thread", "_thread"),
297
+ MovedModule("tkinter", "Tkinter"),
298
+ MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"),
299
+ MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"),
300
+ MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"),
301
+ MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"),
302
+ MovedModule("tkinter_tix", "Tix", "tkinter.tix"),
303
+ MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"),
304
+ MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"),
305
+ MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"),
306
+ MovedModule("tkinter_colorchooser", "tkColorChooser",
307
+ "tkinter.colorchooser"),
308
+ MovedModule("tkinter_commondialog", "tkCommonDialog",
309
+ "tkinter.commondialog"),
310
+ MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"),
311
+ MovedModule("tkinter_font", "tkFont", "tkinter.font"),
312
+ MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"),
313
+ MovedModule("tkinter_tksimpledialog", "tkSimpleDialog",
314
+ "tkinter.simpledialog"),
315
+ MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"),
316
+ MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"),
317
+ MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"),
318
+ MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"),
319
+ MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"),
320
+ MovedModule("xmlrpc_server", "SimpleXMLRPCServer", "xmlrpc.server"),
321
+ ]
322
+ # Add windows specific modules.
323
+ if sys.platform == "win32":
324
+ _moved_attributes += [
325
+ MovedModule("winreg", "_winreg"),
326
+ ]
327
+
328
+ for attr in _moved_attributes:
329
+ setattr(_MovedItems, attr.name, attr)
330
+ if isinstance(attr, MovedModule):
331
+ _importer._add_module(attr, "moves." + attr.name)
332
+ del attr
333
+
334
+ _MovedItems._moved_attributes = _moved_attributes
335
+
336
+ moves = _MovedItems(__name__ + ".moves")
337
+ _importer._add_module(moves, "moves")
338
+
339
+
340
+ class Module_six_moves_urllib_parse(_LazyModule):
341
+
342
+ """Lazy loading of moved objects in six.moves.urllib_parse"""
343
+
344
+
345
+ _urllib_parse_moved_attributes = [
346
+ MovedAttribute("ParseResult", "urlparse", "urllib.parse"),
347
+ MovedAttribute("SplitResult", "urlparse", "urllib.parse"),
348
+ MovedAttribute("parse_qs", "urlparse", "urllib.parse"),
349
+ MovedAttribute("parse_qsl", "urlparse", "urllib.parse"),
350
+ MovedAttribute("urldefrag", "urlparse", "urllib.parse"),
351
+ MovedAttribute("urljoin", "urlparse", "urllib.parse"),
352
+ MovedAttribute("urlparse", "urlparse", "urllib.parse"),
353
+ MovedAttribute("urlsplit", "urlparse", "urllib.parse"),
354
+ MovedAttribute("urlunparse", "urlparse", "urllib.parse"),
355
+ MovedAttribute("urlunsplit", "urlparse", "urllib.parse"),
356
+ MovedAttribute("quote", "urllib", "urllib.parse"),
357
+ MovedAttribute("quote_plus", "urllib", "urllib.parse"),
358
+ MovedAttribute("unquote", "urllib", "urllib.parse"),
359
+ MovedAttribute("unquote_plus", "urllib", "urllib.parse"),
360
+ MovedAttribute("unquote_to_bytes", "urllib", "urllib.parse", "unquote", "unquote_to_bytes"),
361
+ MovedAttribute("urlencode", "urllib", "urllib.parse"),
362
+ MovedAttribute("splitquery", "urllib", "urllib.parse"),
363
+ MovedAttribute("splittag", "urllib", "urllib.parse"),
364
+ MovedAttribute("splituser", "urllib", "urllib.parse"),
365
+ MovedAttribute("splitvalue", "urllib", "urllib.parse"),
366
+ MovedAttribute("uses_fragment", "urlparse", "urllib.parse"),
367
+ MovedAttribute("uses_netloc", "urlparse", "urllib.parse"),
368
+ MovedAttribute("uses_params", "urlparse", "urllib.parse"),
369
+ MovedAttribute("uses_query", "urlparse", "urllib.parse"),
370
+ MovedAttribute("uses_relative", "urlparse", "urllib.parse"),
371
+ ]
372
+ for attr in _urllib_parse_moved_attributes:
373
+ setattr(Module_six_moves_urllib_parse, attr.name, attr)
374
+ del attr
375
+
376
+ Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes
377
+
378
+ _importer._add_module(Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse"),
379
+ "moves.urllib_parse", "moves.urllib.parse")
380
+
381
+
382
+ class Module_six_moves_urllib_error(_LazyModule):
383
+
384
+ """Lazy loading of moved objects in six.moves.urllib_error"""
385
+
386
+
387
+ _urllib_error_moved_attributes = [
388
+ MovedAttribute("URLError", "urllib2", "urllib.error"),
389
+ MovedAttribute("HTTPError", "urllib2", "urllib.error"),
390
+ MovedAttribute("ContentTooShortError", "urllib", "urllib.error"),
391
+ ]
392
+ for attr in _urllib_error_moved_attributes:
393
+ setattr(Module_six_moves_urllib_error, attr.name, attr)
394
+ del attr
395
+
396
+ Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes
397
+
398
+ _importer._add_module(Module_six_moves_urllib_error(__name__ + ".moves.urllib.error"),
399
+ "moves.urllib_error", "moves.urllib.error")
400
+
401
+
402
+ class Module_six_moves_urllib_request(_LazyModule):
403
+
404
+ """Lazy loading of moved objects in six.moves.urllib_request"""
405
+
406
+
407
+ _urllib_request_moved_attributes = [
408
+ MovedAttribute("urlopen", "urllib2", "urllib.request"),
409
+ MovedAttribute("install_opener", "urllib2", "urllib.request"),
410
+ MovedAttribute("build_opener", "urllib2", "urllib.request"),
411
+ MovedAttribute("pathname2url", "urllib", "urllib.request"),
412
+ MovedAttribute("url2pathname", "urllib", "urllib.request"),
413
+ MovedAttribute("getproxies", "urllib", "urllib.request"),
414
+ MovedAttribute("Request", "urllib2", "urllib.request"),
415
+ MovedAttribute("OpenerDirector", "urllib2", "urllib.request"),
416
+ MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"),
417
+ MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"),
418
+ MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"),
419
+ MovedAttribute("ProxyHandler", "urllib2", "urllib.request"),
420
+ MovedAttribute("BaseHandler", "urllib2", "urllib.request"),
421
+ MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"),
422
+ MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"),
423
+ MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"),
424
+ MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"),
425
+ MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"),
426
+ MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"),
427
+ MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"),
428
+ MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"),
429
+ MovedAttribute("HTTPHandler", "urllib2", "urllib.request"),
430
+ MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"),
431
+ MovedAttribute("FileHandler", "urllib2", "urllib.request"),
432
+ MovedAttribute("FTPHandler", "urllib2", "urllib.request"),
433
+ MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"),
434
+ MovedAttribute("UnknownHandler", "urllib2", "urllib.request"),
435
+ MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"),
436
+ MovedAttribute("urlretrieve", "urllib", "urllib.request"),
437
+ MovedAttribute("urlcleanup", "urllib", "urllib.request"),
438
+ MovedAttribute("proxy_bypass", "urllib", "urllib.request"),
439
+ MovedAttribute("parse_http_list", "urllib2", "urllib.request"),
440
+ MovedAttribute("parse_keqv_list", "urllib2", "urllib.request"),
441
+ ]
442
+ if sys.version_info[:2] < (3, 14):
443
+ _urllib_request_moved_attributes.extend(
444
+ [
445
+ MovedAttribute("URLopener", "urllib", "urllib.request"),
446
+ MovedAttribute("FancyURLopener", "urllib", "urllib.request"),
447
+ ]
448
+ )
449
+ for attr in _urllib_request_moved_attributes:
450
+ setattr(Module_six_moves_urllib_request, attr.name, attr)
451
+ del attr
452
+
453
+ Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes
454
+
455
+ _importer._add_module(Module_six_moves_urllib_request(__name__ + ".moves.urllib.request"),
456
+ "moves.urllib_request", "moves.urllib.request")
457
+
458
+
459
+ class Module_six_moves_urllib_response(_LazyModule):
460
+
461
+ """Lazy loading of moved objects in six.moves.urllib_response"""
462
+
463
+
464
+ _urllib_response_moved_attributes = [
465
+ MovedAttribute("addbase", "urllib", "urllib.response"),
466
+ MovedAttribute("addclosehook", "urllib", "urllib.response"),
467
+ MovedAttribute("addinfo", "urllib", "urllib.response"),
468
+ MovedAttribute("addinfourl", "urllib", "urllib.response"),
469
+ ]
470
+ for attr in _urllib_response_moved_attributes:
471
+ setattr(Module_six_moves_urllib_response, attr.name, attr)
472
+ del attr
473
+
474
+ Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes
475
+
476
+ _importer._add_module(Module_six_moves_urllib_response(__name__ + ".moves.urllib.response"),
477
+ "moves.urllib_response", "moves.urllib.response")
478
+
479
+
480
+ class Module_six_moves_urllib_robotparser(_LazyModule):
481
+
482
+ """Lazy loading of moved objects in six.moves.urllib_robotparser"""
483
+
484
+
485
+ _urllib_robotparser_moved_attributes = [
486
+ MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"),
487
+ ]
488
+ for attr in _urllib_robotparser_moved_attributes:
489
+ setattr(Module_six_moves_urllib_robotparser, attr.name, attr)
490
+ del attr
491
+
492
+ Module_six_moves_urllib_robotparser._moved_attributes = _urllib_robotparser_moved_attributes
493
+
494
+ _importer._add_module(Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser"),
495
+ "moves.urllib_robotparser", "moves.urllib.robotparser")
496
+
497
+
498
+ class Module_six_moves_urllib(types.ModuleType):
499
+
500
+ """Create a six.moves.urllib namespace that resembles the Python 3 namespace"""
501
+ __path__ = [] # mark as package
502
+ parse = _importer._get_module("moves.urllib_parse")
503
+ error = _importer._get_module("moves.urllib_error")
504
+ request = _importer._get_module("moves.urllib_request")
505
+ response = _importer._get_module("moves.urllib_response")
506
+ robotparser = _importer._get_module("moves.urllib_robotparser")
507
+
508
+ def __dir__(self):
509
+ return ['parse', 'error', 'request', 'response', 'robotparser']
510
+
511
+ _importer._add_module(Module_six_moves_urllib(__name__ + ".moves.urllib"),
512
+ "moves.urllib")
513
+
514
+
515
+ def add_move(move):
516
+ """Add an item to six.moves."""
517
+ setattr(_MovedItems, move.name, move)
518
+
519
+
520
+ def remove_move(name):
521
+ """Remove item from six.moves."""
522
+ try:
523
+ delattr(_MovedItems, name)
524
+ except AttributeError:
525
+ try:
526
+ del moves.__dict__[name]
527
+ except KeyError:
528
+ raise AttributeError("no such move, %r" % (name,))
529
+
530
+
531
+ if PY3:
532
+ _meth_func = "__func__"
533
+ _meth_self = "__self__"
534
+
535
+ _func_closure = "__closure__"
536
+ _func_code = "__code__"
537
+ _func_defaults = "__defaults__"
538
+ _func_globals = "__globals__"
539
+ else:
540
+ _meth_func = "im_func"
541
+ _meth_self = "im_self"
542
+
543
+ _func_closure = "func_closure"
544
+ _func_code = "func_code"
545
+ _func_defaults = "func_defaults"
546
+ _func_globals = "func_globals"
547
+
548
+
549
+ try:
550
+ advance_iterator = next
551
+ except NameError:
552
+ def advance_iterator(it):
553
+ return it.next()
554
+ next = advance_iterator
555
+
556
+
557
+ try:
558
+ callable = callable
559
+ except NameError:
560
+ def callable(obj):
561
+ return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)
562
+
563
+
564
+ if PY3:
565
+ def get_unbound_function(unbound):
566
+ return unbound
567
+
568
+ create_bound_method = types.MethodType
569
+
570
+ def create_unbound_method(func, cls):
571
+ return func
572
+
573
+ Iterator = object
574
+ else:
575
+ def get_unbound_function(unbound):
576
+ return unbound.im_func
577
+
578
+ def create_bound_method(func, obj):
579
+ return types.MethodType(func, obj, obj.__class__)
580
+
581
+ def create_unbound_method(func, cls):
582
+ return types.MethodType(func, None, cls)
583
+
584
+ class Iterator(object):
585
+
586
+ def next(self):
587
+ return type(self).__next__(self)
588
+
589
+ callable = callable
590
+ _add_doc(get_unbound_function,
591
+ """Get the function out of a possibly unbound function""")
592
+
593
+
594
+ get_method_function = operator.attrgetter(_meth_func)
595
+ get_method_self = operator.attrgetter(_meth_self)
596
+ get_function_closure = operator.attrgetter(_func_closure)
597
+ get_function_code = operator.attrgetter(_func_code)
598
+ get_function_defaults = operator.attrgetter(_func_defaults)
599
+ get_function_globals = operator.attrgetter(_func_globals)
600
+
601
+
602
+ if PY3:
603
+ def iterkeys(d, **kw):
604
+ return iter(d.keys(**kw))
605
+
606
+ def itervalues(d, **kw):
607
+ return iter(d.values(**kw))
608
+
609
+ def iteritems(d, **kw):
610
+ return iter(d.items(**kw))
611
+
612
+ def iterlists(d, **kw):
613
+ return iter(d.lists(**kw))
614
+
615
+ viewkeys = operator.methodcaller("keys")
616
+
617
+ viewvalues = operator.methodcaller("values")
618
+
619
+ viewitems = operator.methodcaller("items")
620
+ else:
621
+ def iterkeys(d, **kw):
622
+ return d.iterkeys(**kw)
623
+
624
+ def itervalues(d, **kw):
625
+ return d.itervalues(**kw)
626
+
627
+ def iteritems(d, **kw):
628
+ return d.iteritems(**kw)
629
+
630
+ def iterlists(d, **kw):
631
+ return d.iterlists(**kw)
632
+
633
+ viewkeys = operator.methodcaller("viewkeys")
634
+
635
+ viewvalues = operator.methodcaller("viewvalues")
636
+
637
+ viewitems = operator.methodcaller("viewitems")
638
+
639
+ _add_doc(iterkeys, "Return an iterator over the keys of a dictionary.")
640
+ _add_doc(itervalues, "Return an iterator over the values of a dictionary.")
641
+ _add_doc(iteritems,
642
+ "Return an iterator over the (key, value) pairs of a dictionary.")
643
+ _add_doc(iterlists,
644
+ "Return an iterator over the (key, [values]) pairs of a dictionary.")
645
+
646
+
647
+ if PY3:
648
+ def b(s):
649
+ return s.encode("latin-1")
650
+
651
+ def u(s):
652
+ return s
653
+ unichr = chr
654
+ import struct
655
+ int2byte = struct.Struct(">B").pack
656
+ del struct
657
+ byte2int = operator.itemgetter(0)
658
+ indexbytes = operator.getitem
659
+ iterbytes = iter
660
+ import io
661
+ StringIO = io.StringIO
662
+ BytesIO = io.BytesIO
663
+ del io
664
+ _assertCountEqual = "assertCountEqual"
665
+ if sys.version_info[1] <= 1:
666
+ _assertRaisesRegex = "assertRaisesRegexp"
667
+ _assertRegex = "assertRegexpMatches"
668
+ _assertNotRegex = "assertNotRegexpMatches"
669
+ else:
670
+ _assertRaisesRegex = "assertRaisesRegex"
671
+ _assertRegex = "assertRegex"
672
+ _assertNotRegex = "assertNotRegex"
673
+ else:
674
+ def b(s):
675
+ return s
676
+ # Workaround for standalone backslash
677
+
678
+ def u(s):
679
+ return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape")
680
+ unichr = unichr
681
+ int2byte = chr
682
+
683
+ def byte2int(bs):
684
+ return ord(bs[0])
685
+
686
+ def indexbytes(buf, i):
687
+ return ord(buf[i])
688
+ iterbytes = functools.partial(itertools.imap, ord)
689
+ import StringIO
690
+ StringIO = BytesIO = StringIO.StringIO
691
+ _assertCountEqual = "assertItemsEqual"
692
+ _assertRaisesRegex = "assertRaisesRegexp"
693
+ _assertRegex = "assertRegexpMatches"
694
+ _assertNotRegex = "assertNotRegexpMatches"
695
+ _add_doc(b, """Byte literal""")
696
+ _add_doc(u, """Text literal""")
697
+
698
+
699
+ def assertCountEqual(self, *args, **kwargs):
700
+ return getattr(self, _assertCountEqual)(*args, **kwargs)
701
+
702
+
703
+ def assertRaisesRegex(self, *args, **kwargs):
704
+ return getattr(self, _assertRaisesRegex)(*args, **kwargs)
705
+
706
+
707
+ def assertRegex(self, *args, **kwargs):
708
+ return getattr(self, _assertRegex)(*args, **kwargs)
709
+
710
+
711
+ def assertNotRegex(self, *args, **kwargs):
712
+ return getattr(self, _assertNotRegex)(*args, **kwargs)
713
+
714
+
715
+ if PY3:
716
+ exec_ = getattr(moves.builtins, "exec")
717
+
718
+ def reraise(tp, value, tb=None):
719
+ try:
720
+ if value is None:
721
+ value = tp()
722
+ if value.__traceback__ is not tb:
723
+ raise value.with_traceback(tb)
724
+ raise value
725
+ finally:
726
+ value = None
727
+ tb = None
728
+
729
+ else:
730
+ def exec_(_code_, _globs_=None, _locs_=None):
731
+ """Execute code in a namespace."""
732
+ if _globs_ is None:
733
+ frame = sys._getframe(1)
734
+ _globs_ = frame.f_globals
735
+ if _locs_ is None:
736
+ _locs_ = frame.f_locals
737
+ del frame
738
+ elif _locs_ is None:
739
+ _locs_ = _globs_
740
+ exec("""exec _code_ in _globs_, _locs_""")
741
+
742
+ exec_("""def reraise(tp, value, tb=None):
743
+ try:
744
+ raise tp, value, tb
745
+ finally:
746
+ tb = None
747
+ """)
748
+
749
+
750
+ if sys.version_info[:2] > (3,):
751
+ exec_("""def raise_from(value, from_value):
752
+ try:
753
+ raise value from from_value
754
+ finally:
755
+ value = None
756
+ """)
757
+ else:
758
+ def raise_from(value, from_value):
759
+ raise value
760
+
761
+
762
+ print_ = getattr(moves.builtins, "print", None)
763
+ if print_ is None:
764
+ def print_(*args, **kwargs):
765
+ """The new-style print function for Python 2.4 and 2.5."""
766
+ fp = kwargs.pop("file", sys.stdout)
767
+ if fp is None:
768
+ return
769
+
770
+ def write(data):
771
+ if not isinstance(data, basestring):
772
+ data = str(data)
773
+ # If the file has an encoding, encode unicode with it.
774
+ if (isinstance(fp, file) and
775
+ isinstance(data, unicode) and
776
+ fp.encoding is not None):
777
+ errors = getattr(fp, "errors", None)
778
+ if errors is None:
779
+ errors = "strict"
780
+ data = data.encode(fp.encoding, errors)
781
+ fp.write(data)
782
+ want_unicode = False
783
+ sep = kwargs.pop("sep", None)
784
+ if sep is not None:
785
+ if isinstance(sep, unicode):
786
+ want_unicode = True
787
+ elif not isinstance(sep, str):
788
+ raise TypeError("sep must be None or a string")
789
+ end = kwargs.pop("end", None)
790
+ if end is not None:
791
+ if isinstance(end, unicode):
792
+ want_unicode = True
793
+ elif not isinstance(end, str):
794
+ raise TypeError("end must be None or a string")
795
+ if kwargs:
796
+ raise TypeError("invalid keyword arguments to print()")
797
+ if not want_unicode:
798
+ for arg in args:
799
+ if isinstance(arg, unicode):
800
+ want_unicode = True
801
+ break
802
+ if want_unicode:
803
+ newline = unicode("\n")
804
+ space = unicode(" ")
805
+ else:
806
+ newline = "\n"
807
+ space = " "
808
+ if sep is None:
809
+ sep = space
810
+ if end is None:
811
+ end = newline
812
+ for i, arg in enumerate(args):
813
+ if i:
814
+ write(sep)
815
+ write(arg)
816
+ write(end)
817
+ if sys.version_info[:2] < (3, 3):
818
+ _print = print_
819
+
820
+ def print_(*args, **kwargs):
821
+ fp = kwargs.get("file", sys.stdout)
822
+ flush = kwargs.pop("flush", False)
823
+ _print(*args, **kwargs)
824
+ if flush and fp is not None:
825
+ fp.flush()
826
+
827
+ _add_doc(reraise, """Reraise an exception.""")
828
+
829
+ if sys.version_info[0:2] < (3, 4):
830
+ # This does exactly the same what the :func:`py3:functools.update_wrapper`
831
+ # function does on Python versions after 3.2. It sets the ``__wrapped__``
832
+ # attribute on ``wrapper`` object and it doesn't raise an error if any of
833
+ # the attributes mentioned in ``assigned`` and ``updated`` are missing on
834
+ # ``wrapped`` object.
835
+ def _update_wrapper(wrapper, wrapped,
836
+ assigned=functools.WRAPPER_ASSIGNMENTS,
837
+ updated=functools.WRAPPER_UPDATES):
838
+ for attr in assigned:
839
+ try:
840
+ value = getattr(wrapped, attr)
841
+ except AttributeError:
842
+ continue
843
+ else:
844
+ setattr(wrapper, attr, value)
845
+ for attr in updated:
846
+ getattr(wrapper, attr).update(getattr(wrapped, attr, {}))
847
+ wrapper.__wrapped__ = wrapped
848
+ return wrapper
849
+ _update_wrapper.__doc__ = functools.update_wrapper.__doc__
850
+
851
+ def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS,
852
+ updated=functools.WRAPPER_UPDATES):
853
+ return functools.partial(_update_wrapper, wrapped=wrapped,
854
+ assigned=assigned, updated=updated)
855
+ wraps.__doc__ = functools.wraps.__doc__
856
+
857
+ else:
858
+ wraps = functools.wraps
859
+
860
+
861
+ def with_metaclass(meta, *bases):
862
+ """Create a base class with a metaclass."""
863
+ # This requires a bit of explanation: the basic idea is to make a dummy
864
+ # metaclass for one level of class instantiation that replaces itself with
865
+ # the actual metaclass.
866
+ class metaclass(type):
867
+
868
+ def __new__(cls, name, this_bases, d):
869
+ if sys.version_info[:2] >= (3, 7):
870
+ # This version introduced PEP 560 that requires a bit
871
+ # of extra care (we mimic what is done by __build_class__).
872
+ resolved_bases = types.resolve_bases(bases)
873
+ if resolved_bases is not bases:
874
+ d['__orig_bases__'] = bases
875
+ else:
876
+ resolved_bases = bases
877
+ return meta(name, resolved_bases, d)
878
+
879
+ @classmethod
880
+ def __prepare__(cls, name, this_bases):
881
+ return meta.__prepare__(name, bases)
882
+ return type.__new__(metaclass, 'temporary_class', (), {})
883
+
884
+
885
+ def add_metaclass(metaclass):
886
+ """Class decorator for creating a class with a metaclass."""
887
+ def wrapper(cls):
888
+ orig_vars = cls.__dict__.copy()
889
+ slots = orig_vars.get('__slots__')
890
+ if slots is not None:
891
+ if isinstance(slots, str):
892
+ slots = [slots]
893
+ for slots_var in slots:
894
+ orig_vars.pop(slots_var)
895
+ orig_vars.pop('__dict__', None)
896
+ orig_vars.pop('__weakref__', None)
897
+ if hasattr(cls, '__qualname__'):
898
+ orig_vars['__qualname__'] = cls.__qualname__
899
+ return metaclass(cls.__name__, cls.__bases__, orig_vars)
900
+ return wrapper
901
+
902
+
903
+ def ensure_binary(s, encoding='utf-8', errors='strict'):
904
+ """Coerce **s** to six.binary_type.
905
+
906
+ For Python 2:
907
+ - `unicode` -> encoded to `str`
908
+ - `str` -> `str`
909
+
910
+ For Python 3:
911
+ - `str` -> encoded to `bytes`
912
+ - `bytes` -> `bytes`
913
+ """
914
+ if isinstance(s, binary_type):
915
+ return s
916
+ if isinstance(s, text_type):
917
+ return s.encode(encoding, errors)
918
+ raise TypeError("not expecting type '%s'" % type(s))
919
+
920
+
921
+ def ensure_str(s, encoding='utf-8', errors='strict'):
922
+ """Coerce *s* to `str`.
923
+
924
+ For Python 2:
925
+ - `unicode` -> encoded to `str`
926
+ - `str` -> `str`
927
+
928
+ For Python 3:
929
+ - `str` -> `str`
930
+ - `bytes` -> decoded to `str`
931
+ """
932
+ # Optimization: Fast return for the common case.
933
+ if type(s) is str:
934
+ return s
935
+ if PY2 and isinstance(s, text_type):
936
+ return s.encode(encoding, errors)
937
+ elif PY3 and isinstance(s, binary_type):
938
+ return s.decode(encoding, errors)
939
+ elif not isinstance(s, (text_type, binary_type)):
940
+ raise TypeError("not expecting type '%s'" % type(s))
941
+ return s
942
+
943
+
944
+ def ensure_text(s, encoding='utf-8', errors='strict'):
945
+ """Coerce *s* to six.text_type.
946
+
947
+ For Python 2:
948
+ - `unicode` -> `unicode`
949
+ - `str` -> `unicode`
950
+
951
+ For Python 3:
952
+ - `str` -> `str`
953
+ - `bytes` -> decoded to `str`
954
+ """
955
+ if isinstance(s, binary_type):
956
+ return s.decode(encoding, errors)
957
+ elif isinstance(s, text_type):
958
+ return s
959
+ else:
960
+ raise TypeError("not expecting type '%s'" % type(s))
961
+
962
+
963
+ def python_2_unicode_compatible(klass):
964
+ """
965
+ A class decorator that defines __unicode__ and __str__ methods under Python 2.
966
+ Under Python 3 it does nothing.
967
+
968
+ To support Python 2 and 3 with a single code base, define a __str__ method
969
+ returning text and apply this decorator to the class.
970
+ """
971
+ if PY2:
972
+ if '__str__' not in klass.__dict__:
973
+ raise ValueError("@python_2_unicode_compatible cannot be applied "
974
+ "to %s because it doesn't define __str__()." %
975
+ klass.__name__)
976
+ klass.__unicode__ = klass.__str__
977
+ klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
978
+ return klass
979
+
980
+
981
+ # Complete the moves implementation.
982
+ # This code is at the end of this module to speed up module loading.
983
+ # Turn this module into a package.
984
+ __path__ = [] # required for PEP 302 and PEP 451
985
+ __package__ = __name__ # see PEP 366 @ReservedAssignment
986
+ if globals().get("__spec__") is not None:
987
+ __spec__.submodule_search_locations = [] # PEP 451 @UndefinedVariable
988
+ # Remove other six meta path importers, since they cause problems. This can
989
+ # happen if six is removed from sys.modules and then reloaded. (Setuptools does
990
+ # this for some reason.)
991
+ if sys.meta_path:
992
+ for i, importer in enumerate(sys.meta_path):
993
+ # Here's some real nastiness: Another "instance" of the six module might
994
+ # be floating around. Therefore, we can't use isinstance() to check for
995
+ # the six meta path importer, since the other six instance will have
996
+ # inserted an importer with different class.
997
+ if (type(importer).__name__ == "_SixMetaPathImporter" and
998
+ importer.name == __name__):
999
+ del sys.meta_path[i]
1000
+ break
1001
+ del i, importer
1002
+ # Finally, add the importer to the meta path import hook.
1003
+ sys.meta_path.append(_importer)
TTS/Kokoro/.venv/Lib/site-packages/soundfile.py ADDED
@@ -0,0 +1,1674 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """python-soundfile is an audio library based on libsndfile, CFFI and NumPy.
2
+
3
+ Sound files can be read or written directly using the functions
4
+ `read()` and `write()`.
5
+ To read a sound file in a block-wise fashion, use `blocks()`.
6
+ Alternatively, sound files can be opened as `SoundFile` objects.
7
+
8
+ For further information, see https://python-soundfile.readthedocs.io/.
9
+
10
+ """
11
+ __version__ = "0.13.1"
12
+
13
+ import os as _os
14
+ import sys as _sys
15
+ from os import SEEK_SET, SEEK_CUR, SEEK_END
16
+ from ctypes.util import find_library as _find_library
17
+ from _soundfile import ffi as _ffi
18
+
19
+ try:
20
+ _unicode = unicode # doesn't exist in Python 3.x
21
+ except NameError:
22
+ _unicode = str
23
+
24
+
25
+ _str_types = {
26
+ 'title': 0x01,
27
+ 'copyright': 0x02,
28
+ 'software': 0x03,
29
+ 'artist': 0x04,
30
+ 'comment': 0x05,
31
+ 'date': 0x06,
32
+ 'album': 0x07,
33
+ 'license': 0x08,
34
+ 'tracknumber': 0x09,
35
+ 'genre': 0x10,
36
+ }
37
+
38
+ _formats = {
39
+ 'WAV': 0x010000, # Microsoft WAV format (little endian default).
40
+ 'AIFF': 0x020000, # Apple/SGI AIFF format (big endian).
41
+ 'AU': 0x030000, # Sun/NeXT AU format (big endian).
42
+ 'RAW': 0x040000, # RAW PCM data.
43
+ 'PAF': 0x050000, # Ensoniq PARIS file format.
44
+ 'SVX': 0x060000, # Amiga IFF / SVX8 / SV16 format.
45
+ 'NIST': 0x070000, # Sphere NIST format.
46
+ 'VOC': 0x080000, # VOC files.
47
+ 'IRCAM': 0x0A0000, # Berkeley/IRCAM/CARL
48
+ 'W64': 0x0B0000, # Sonic Foundry's 64 bit RIFF/WAV
49
+ 'MAT4': 0x0C0000, # Matlab (tm) V4.2 / GNU Octave 2.0
50
+ 'MAT5': 0x0D0000, # Matlab (tm) V5.0 / GNU Octave 2.1
51
+ 'PVF': 0x0E0000, # Portable Voice Format
52
+ 'XI': 0x0F0000, # Fasttracker 2 Extended Instrument
53
+ 'HTK': 0x100000, # HMM Tool Kit format
54
+ 'SDS': 0x110000, # Midi Sample Dump Standard
55
+ 'AVR': 0x120000, # Audio Visual Research
56
+ 'WAVEX': 0x130000, # MS WAVE with WAVEFORMATEX
57
+ 'SD2': 0x160000, # Sound Designer 2
58
+ 'FLAC': 0x170000, # FLAC lossless file format
59
+ 'CAF': 0x180000, # Core Audio File format
60
+ 'WVE': 0x190000, # Psion WVE format
61
+ 'OGG': 0x200000, # Xiph OGG container
62
+ 'MPC2K': 0x210000, # Akai MPC 2000 sampler
63
+ 'RF64': 0x220000, # RF64 WAV file
64
+ 'MP3': 0x230000, # MPEG-1/2 audio stream
65
+ }
66
+
67
+ _subtypes = {
68
+ 'PCM_S8': 0x0001, # Signed 8 bit data
69
+ 'PCM_16': 0x0002, # Signed 16 bit data
70
+ 'PCM_24': 0x0003, # Signed 24 bit data
71
+ 'PCM_32': 0x0004, # Signed 32 bit data
72
+ 'PCM_U8': 0x0005, # Unsigned 8 bit data (WAV and RAW only)
73
+ 'FLOAT': 0x0006, # 32 bit float data
74
+ 'DOUBLE': 0x0007, # 64 bit float data
75
+ 'ULAW': 0x0010, # U-Law encoded.
76
+ 'ALAW': 0x0011, # A-Law encoded.
77
+ 'IMA_ADPCM': 0x0012, # IMA ADPCM.
78
+ 'MS_ADPCM': 0x0013, # Microsoft ADPCM.
79
+ 'GSM610': 0x0020, # GSM 6.10 encoding.
80
+ 'VOX_ADPCM': 0x0021, # OKI / Dialogix ADPCM
81
+ 'NMS_ADPCM_16': 0x0022, # 16kbs NMS G721-variant encoding.
82
+ 'NMS_ADPCM_24': 0x0023, # 24kbs NMS G721-variant encoding.
83
+ 'NMS_ADPCM_32': 0x0024, # 32kbs NMS G721-variant encoding.
84
+ 'G721_32': 0x0030, # 32kbs G721 ADPCM encoding.
85
+ 'G723_24': 0x0031, # 24kbs G723 ADPCM encoding.
86
+ 'G723_40': 0x0032, # 40kbs G723 ADPCM encoding.
87
+ 'DWVW_12': 0x0040, # 12 bit Delta Width Variable Word encoding.
88
+ 'DWVW_16': 0x0041, # 16 bit Delta Width Variable Word encoding.
89
+ 'DWVW_24': 0x0042, # 24 bit Delta Width Variable Word encoding.
90
+ 'DWVW_N': 0x0043, # N bit Delta Width Variable Word encoding.
91
+ 'DPCM_8': 0x0050, # 8 bit differential PCM (XI only)
92
+ 'DPCM_16': 0x0051, # 16 bit differential PCM (XI only)
93
+ 'VORBIS': 0x0060, # Xiph Vorbis encoding.
94
+ 'OPUS': 0x0064, # Xiph/Skype Opus encoding.
95
+ 'ALAC_16': 0x0070, # Apple Lossless Audio Codec (16 bit).
96
+ 'ALAC_20': 0x0071, # Apple Lossless Audio Codec (20 bit).
97
+ 'ALAC_24': 0x0072, # Apple Lossless Audio Codec (24 bit).
98
+ 'ALAC_32': 0x0073, # Apple Lossless Audio Codec (32 bit).
99
+ 'MPEG_LAYER_I': 0x0080, # MPEG-1 Audio Layer I.
100
+ 'MPEG_LAYER_II': 0x0081, # MPEG-1 Audio Layer II.
101
+ 'MPEG_LAYER_III': 0x0082, # MPEG-2 Audio Layer III.
102
+ }
103
+
104
+ _endians = {
105
+ 'FILE': 0x00000000, # Default file endian-ness.
106
+ 'LITTLE': 0x10000000, # Force little endian-ness.
107
+ 'BIG': 0x20000000, # Force big endian-ness.
108
+ 'CPU': 0x30000000, # Force CPU endian-ness.
109
+ }
110
+
111
+ # libsndfile doesn't specify default subtypes, these are somehow arbitrary:
112
+ _default_subtypes = {
113
+ 'WAV': 'PCM_16',
114
+ 'AIFF': 'PCM_16',
115
+ 'AU': 'PCM_16',
116
+ # 'RAW': # subtype must be explicit!
117
+ 'PAF': 'PCM_16',
118
+ 'SVX': 'PCM_16',
119
+ 'NIST': 'PCM_16',
120
+ 'VOC': 'PCM_16',
121
+ 'IRCAM': 'PCM_16',
122
+ 'W64': 'PCM_16',
123
+ 'MAT4': 'DOUBLE',
124
+ 'MAT5': 'DOUBLE',
125
+ 'PVF': 'PCM_16',
126
+ 'XI': 'DPCM_16',
127
+ 'HTK': 'PCM_16',
128
+ 'SDS': 'PCM_16',
129
+ 'AVR': 'PCM_16',
130
+ 'WAVEX': 'PCM_16',
131
+ 'SD2': 'PCM_16',
132
+ 'FLAC': 'PCM_16',
133
+ 'CAF': 'PCM_16',
134
+ 'WVE': 'ALAW',
135
+ 'OGG': 'VORBIS',
136
+ 'MPC2K': 'PCM_16',
137
+ 'RF64': 'PCM_16',
138
+ 'MP3': 'MPEG_LAYER_III',
139
+ }
140
+
141
+ _ffi_types = {
142
+ 'float64': 'double',
143
+ 'float32': 'float',
144
+ 'int32': 'int',
145
+ 'int16': 'short'
146
+ }
147
+
148
+ _bitrate_modes = {
149
+ 'CONSTANT': 0,
150
+ 'AVERAGE': 1,
151
+ 'VARIABLE': 2,
152
+ }
153
+
154
+ try: # packaged lib (in _soundfile_data which should be on python path)
155
+ if _sys.platform == 'darwin':
156
+ from platform import machine as _machine
157
+ _packaged_libname = 'libsndfile_' + _machine() + '.dylib'
158
+ elif _sys.platform == 'win32':
159
+ from platform import architecture as _architecture
160
+ from platform import machine as _machine
161
+ # this check can not be completed correctly: for x64 binaries running on
162
+ # arm64 Windows report the same values as arm64 binaries. For now, neither
163
+ # numpy nor cffi are available for arm64, so we can safely assume we're
164
+ # in x86 land:
165
+ if _architecture()[0] == '64bit':
166
+ _packaged_libname = 'libsndfile_x64.dll'
167
+ elif _architecture()[0] == '32bit':
168
+ _packaged_libname = 'libsndfile_x86.dll'
169
+ else:
170
+ raise OSError('no packaged library for Windows {} {}'
171
+ .format(_architecture(), _machine()))
172
+ elif _sys.platform == 'linux':
173
+ from platform import machine as _machine
174
+ if _machine() in ["aarch64", "aarch64_be", "armv8b", "armv8l"]:
175
+ _packaged_libname = 'libsndfile_arm64.so'
176
+ else:
177
+ _packaged_libname = 'libsndfile_' + _machine() + '.so'
178
+ else:
179
+ raise OSError('no packaged library for this platform')
180
+
181
+ import _soundfile_data # ImportError if this doesn't exist
182
+ _path = _os.path.dirname(_soundfile_data.__file__) # TypeError if __file__ is None
183
+ _full_path = _os.path.join(_path, _packaged_libname)
184
+ _snd = _ffi.dlopen(_full_path) # OSError if file doesn't exist or can't be loaded
185
+
186
+ except (OSError, ImportError, TypeError):
187
+ try: # system-wide libsndfile:
188
+ _libname = _find_library('sndfile')
189
+ if _libname is None:
190
+ raise OSError('sndfile library not found using ctypes.util.find_library')
191
+ _snd = _ffi.dlopen(_libname)
192
+
193
+ except OSError:
194
+ # Try explicit file name, if the general does not work (e.g. on nixos)
195
+ if _sys.platform == 'darwin':
196
+ _explicit_libname = 'libsndfile.dylib'
197
+ elif _sys.platform == 'win32':
198
+ _explicit_libname = 'libsndfile.dll'
199
+ elif _sys.platform == 'linux':
200
+ _explicit_libname = 'libsndfile.so'
201
+ else:
202
+ raise
203
+
204
+ # Homebrew on Apple M1 uses a `/opt/homebrew/lib` instead of
205
+ # `/usr/local/lib`. We are making sure we pick that up.
206
+ from platform import machine as _machine
207
+ if _sys.platform == 'darwin' and _machine() == 'arm64':
208
+ _hbrew_path = '/opt/homebrew/lib/' if _os.path.isdir('/opt/homebrew/lib/') \
209
+ else '/usr/local/lib/'
210
+ _snd = _ffi.dlopen(_os.path.join(_hbrew_path, _explicit_libname))
211
+ else:
212
+ _snd = _ffi.dlopen(_explicit_libname)
213
+
214
+ __libsndfile_version__ = _ffi.string(_snd.sf_version_string()).decode('utf-8', 'replace')
215
+ if __libsndfile_version__.startswith('libsndfile-'):
216
+ __libsndfile_version__ = __libsndfile_version__[len('libsndfile-'):]
217
+
218
+
219
+ def read(file, frames=-1, start=0, stop=None, dtype='float64', always_2d=False,
220
+ fill_value=None, out=None, samplerate=None, channels=None,
221
+ format=None, subtype=None, endian=None, closefd=True):
222
+ """Provide audio data from a sound file as NumPy array.
223
+
224
+ By default, the whole file is read from the beginning, but the
225
+ position to start reading can be specified with *start* and the
226
+ number of frames to read can be specified with *frames*.
227
+ Alternatively, a range can be specified with *start* and *stop*.
228
+
229
+ If there is less data left in the file than requested, the rest of
230
+ the frames are filled with *fill_value*.
231
+ If no *fill_value* is specified, a smaller array is returned.
232
+
233
+ Parameters
234
+ ----------
235
+ file : str or int or file-like object
236
+ The file to read from. See `SoundFile` for details.
237
+ frames : int, optional
238
+ The number of frames to read. If *frames* is negative, the whole
239
+ rest of the file is read. Not allowed if *stop* is given.
240
+ start : int, optional
241
+ Where to start reading. A negative value counts from the end.
242
+ stop : int, optional
243
+ The index after the last frame to be read. A negative value
244
+ counts from the end. Not allowed if *frames* is given.
245
+ dtype : {'float64', 'float32', 'int32', 'int16'}, optional
246
+ Data type of the returned array, by default ``'float64'``.
247
+ Floating point audio data is typically in the range from
248
+ ``-1.0`` to ``1.0``. Integer data is in the range from
249
+ ``-2**15`` to ``2**15-1`` for ``'int16'`` and from ``-2**31`` to
250
+ ``2**31-1`` for ``'int32'``.
251
+
252
+ .. note:: Reading int values from a float file will *not*
253
+ scale the data to [-1.0, 1.0). If the file contains
254
+ ``np.array([42.6], dtype='float32')``, you will read
255
+ ``np.array([43], dtype='int32')`` for ``dtype='int32'``.
256
+
257
+ Returns
258
+ -------
259
+ audiodata : `numpy.ndarray` or type(out)
260
+ A two-dimensional (frames x channels) NumPy array is returned.
261
+ If the sound file has only one channel, a one-dimensional array
262
+ is returned. Use ``always_2d=True`` to return a two-dimensional
263
+ array anyway.
264
+
265
+ If *out* was specified, it is returned. If *out* has more
266
+ frames than available in the file (or if *frames* is smaller
267
+ than the length of *out*) and no *fill_value* is given, then
268
+ only a part of *out* is overwritten and a view containing all
269
+ valid frames is returned.
270
+ samplerate : int
271
+ The sample rate of the audio file.
272
+
273
+ Other Parameters
274
+ ----------------
275
+ always_2d : bool, optional
276
+ By default, reading a mono sound file will return a
277
+ one-dimensional array. With ``always_2d=True``, audio data is
278
+ always returned as a two-dimensional array, even if the audio
279
+ file has only one channel.
280
+ fill_value : float, optional
281
+ If more frames are requested than available in the file, the
282
+ rest of the output is be filled with *fill_value*. If
283
+ *fill_value* is not specified, a smaller array is returned.
284
+ out : `numpy.ndarray` or subclass, optional
285
+ If *out* is specified, the data is written into the given array
286
+ instead of creating a new array. In this case, the arguments
287
+ *dtype* and *always_2d* are silently ignored! If *frames* is
288
+ not given, it is obtained from the length of *out*.
289
+ samplerate, channels, format, subtype, endian, closefd
290
+ See `SoundFile`.
291
+
292
+ Examples
293
+ --------
294
+ >>> import soundfile as sf
295
+ >>> data, samplerate = sf.read('stereo_file.wav')
296
+ >>> data
297
+ array([[ 0.71329652, 0.06294799],
298
+ [-0.26450912, -0.38874483],
299
+ ...
300
+ [ 0.67398441, -0.11516333]])
301
+ >>> samplerate
302
+ 44100
303
+
304
+ """
305
+ with SoundFile(file, 'r', samplerate, channels,
306
+ subtype, endian, format, closefd) as f:
307
+ frames = f._prepare_read(start, stop, frames)
308
+ data = f.read(frames, dtype, always_2d, fill_value, out)
309
+ return data, f.samplerate
310
+
311
+
312
+ def write(file, data, samplerate, subtype=None, endian=None, format=None,
313
+ closefd=True, compression_level=None, bitrate_mode=None):
314
+ """Write data to a sound file.
315
+
316
+ .. note:: If *file* exists, it will be truncated and overwritten!
317
+
318
+ Parameters
319
+ ----------
320
+ file : str or int or file-like object
321
+ The file to write to. See `SoundFile` for details.
322
+ data : array_like
323
+ The data to write. Usually two-dimensional (frames x channels),
324
+ but one-dimensional *data* can be used for mono files.
325
+ Only the data types ``'float64'``, ``'float32'``, ``'int32'``
326
+ and ``'int16'`` are supported.
327
+
328
+ .. note:: The data type of *data* does **not** select the data
329
+ type of the written file. Audio data will be
330
+ converted to the given *subtype*. Writing int values
331
+ to a float file will *not* scale the values to
332
+ [-1.0, 1.0). If you write the value ``np.array([42],
333
+ dtype='int32')``, to a ``subtype='FLOAT'`` file, the
334
+ file will then contain ``np.array([42.],
335
+ dtype='float32')``.
336
+
337
+ samplerate : int
338
+ The sample rate of the audio data.
339
+ subtype : str, optional
340
+ See `default_subtype()` for the default value and
341
+ `available_subtypes()` for all possible values.
342
+
343
+ Other Parameters
344
+ ----------------
345
+ format, endian, closefd, compression_level, bitrate_mode
346
+ See `SoundFile`.
347
+
348
+ Examples
349
+ --------
350
+ Write 10 frames of random data to a new file:
351
+
352
+ >>> import numpy as np
353
+ >>> import soundfile as sf
354
+ >>> sf.write('stereo_file.wav', np.random.randn(10, 2), 44100, 'PCM_24')
355
+
356
+ """
357
+ import numpy as np
358
+ data = np.asarray(data)
359
+ if data.ndim == 1:
360
+ channels = 1
361
+ else:
362
+ channels = data.shape[1]
363
+ with SoundFile(file, 'w', samplerate, channels,
364
+ subtype, endian, format, closefd,
365
+ compression_level, bitrate_mode) as f:
366
+ f.write(data)
367
+
368
+
369
+ def blocks(file, blocksize=None, overlap=0, frames=-1, start=0, stop=None,
370
+ dtype='float64', always_2d=False, fill_value=None, out=None,
371
+ samplerate=None, channels=None,
372
+ format=None, subtype=None, endian=None, closefd=True):
373
+ """Return a generator for block-wise reading.
374
+
375
+ By default, iteration starts at the beginning and stops at the end
376
+ of the file. Use *start* to start at a later position and *frames*
377
+ or *stop* to stop earlier.
378
+
379
+ If you stop iterating over the generator before it's exhausted,
380
+ the sound file is not closed. This is normally not a problem
381
+ because the file is opened in read-only mode. To close the file
382
+ properly, the generator's ``close()`` method can be called.
383
+
384
+ Parameters
385
+ ----------
386
+ file : str or int or file-like object
387
+ The file to read from. See `SoundFile` for details.
388
+ blocksize : int
389
+ The number of frames to read per block.
390
+ Either this or *out* must be given.
391
+ overlap : int, optional
392
+ The number of frames to rewind between each block.
393
+
394
+ Yields
395
+ ------
396
+ `numpy.ndarray` or type(out)
397
+ Blocks of audio data.
398
+ If *out* was given, and the requested frames are not an integer
399
+ multiple of the length of *out*, and no *fill_value* was given,
400
+ the last block will be a smaller view into *out*.
401
+
402
+ Other Parameters
403
+ ----------------
404
+ frames, start, stop
405
+ See `read()`.
406
+ dtype : {'float64', 'float32', 'int32', 'int16'}, optional
407
+ See `read()`.
408
+ always_2d, fill_value, out
409
+ See `read()`.
410
+ samplerate, channels, format, subtype, endian, closefd
411
+ See `SoundFile`.
412
+
413
+ Examples
414
+ --------
415
+ >>> import soundfile as sf
416
+ >>> for block in sf.blocks('stereo_file.wav', blocksize=1024):
417
+ >>> pass # do something with 'block'
418
+
419
+ """
420
+ with SoundFile(file, 'r', samplerate, channels,
421
+ subtype, endian, format, closefd) as f:
422
+ frames = f._prepare_read(start, stop, frames)
423
+ for block in f.blocks(blocksize, overlap, frames,
424
+ dtype, always_2d, fill_value, out):
425
+ yield block
426
+
427
+
428
+ class _SoundFileInfo(object):
429
+ """Information about a SoundFile"""
430
+
431
+ def __init__(self, file, verbose):
432
+ self.verbose = verbose
433
+ with SoundFile(file) as f:
434
+ self.name = f.name
435
+ self.samplerate = f.samplerate
436
+ self.channels = f.channels
437
+ self.frames = f.frames
438
+ self.duration = float(self.frames)/f.samplerate
439
+ self.format = f.format
440
+ self.subtype = f.subtype
441
+ self.endian = f.endian
442
+ self.format_info = f.format_info
443
+ self.subtype_info = f.subtype_info
444
+ self.sections = f.sections
445
+ self.extra_info = f.extra_info
446
+
447
+ @property
448
+ def _duration_str(self):
449
+ hours, rest = divmod(self.duration, 3600)
450
+ minutes, seconds = divmod(rest, 60)
451
+ if hours >= 1:
452
+ duration = "{0:.0g}:{1:02.0g}:{2:05.3f} h".format(hours, minutes, seconds)
453
+ elif minutes >= 1:
454
+ duration = "{0:02.0g}:{1:05.3f} min".format(minutes, seconds)
455
+ elif seconds <= 1:
456
+ duration = "{0:d} samples".format(self.frames)
457
+ else:
458
+ duration = "{0:.3f} s".format(seconds)
459
+ return duration
460
+
461
+ def __repr__(self):
462
+ info = "\n".join(
463
+ ["{0.name}",
464
+ "samplerate: {0.samplerate} Hz",
465
+ "channels: {0.channels}",
466
+ "duration: {0._duration_str}",
467
+ "format: {0.format_info} [{0.format}]",
468
+ "subtype: {0.subtype_info} [{0.subtype}]"])
469
+ if self.verbose:
470
+ info += "\n".join(
471
+ ["\nendian: {0.endian}",
472
+ "sections: {0.sections}",
473
+ "frames: {0.frames}",
474
+ 'extra_info: """',
475
+ ' {1}"""'])
476
+ indented_extra_info = ("\n"+" "*4).join(self.extra_info.split("\n"))
477
+ return info.format(self, indented_extra_info)
478
+
479
+
480
+ def info(file, verbose=False):
481
+ """Returns an object with information about a `SoundFile`.
482
+
483
+ Parameters
484
+ ----------
485
+ verbose : bool
486
+ Whether to print additional information.
487
+ """
488
+ return _SoundFileInfo(file, verbose)
489
+
490
+
491
+ def available_formats():
492
+ """Return a dictionary of available major formats.
493
+
494
+ Examples
495
+ --------
496
+ >>> import soundfile as sf
497
+ >>> sf.available_formats()
498
+ {'FLAC': 'FLAC (FLAC Lossless Audio Codec)',
499
+ 'OGG': 'OGG (OGG Container format)',
500
+ 'WAV': 'WAV (Microsoft)',
501
+ 'AIFF': 'AIFF (Apple/SGI)',
502
+ ...
503
+ 'WAVEX': 'WAVEX (Microsoft)',
504
+ 'RAW': 'RAW (header-less)',
505
+ 'MAT5': 'MAT5 (GNU Octave 2.1 / Matlab 5.0)'}
506
+
507
+ """
508
+ return dict(_available_formats_helper(_snd.SFC_GET_FORMAT_MAJOR_COUNT,
509
+ _snd.SFC_GET_FORMAT_MAJOR))
510
+
511
+
512
+ def available_subtypes(format=None):
513
+ """Return a dictionary of available subtypes.
514
+
515
+ Parameters
516
+ ----------
517
+ format : str
518
+ If given, only compatible subtypes are returned.
519
+
520
+ Examples
521
+ --------
522
+ >>> import soundfile as sf
523
+ >>> sf.available_subtypes('FLAC')
524
+ {'PCM_24': 'Signed 24 bit PCM',
525
+ 'PCM_16': 'Signed 16 bit PCM',
526
+ 'PCM_S8': 'Signed 8 bit PCM'}
527
+
528
+ """
529
+ subtypes = _available_formats_helper(_snd.SFC_GET_FORMAT_SUBTYPE_COUNT,
530
+ _snd.SFC_GET_FORMAT_SUBTYPE)
531
+ return dict((subtype, name) for subtype, name in subtypes
532
+ if format is None or check_format(format, subtype))
533
+
534
+
535
+ def check_format(format, subtype=None, endian=None):
536
+ """Check if the combination of format/subtype/endian is valid.
537
+
538
+ Examples
539
+ --------
540
+ >>> import soundfile as sf
541
+ >>> sf.check_format('WAV', 'PCM_24')
542
+ True
543
+ >>> sf.check_format('FLAC', 'VORBIS')
544
+ False
545
+
546
+ """
547
+ try:
548
+ return bool(_format_int(format, subtype, endian))
549
+ except (ValueError, TypeError):
550
+ return False
551
+
552
+
553
+ def default_subtype(format):
554
+ """Return the default subtype for a given format.
555
+
556
+ Examples
557
+ --------
558
+ >>> import soundfile as sf
559
+ >>> sf.default_subtype('WAV')
560
+ 'PCM_16'
561
+ >>> sf.default_subtype('MAT5')
562
+ 'DOUBLE'
563
+
564
+ """
565
+ _check_format(format)
566
+ return _default_subtypes.get(format.upper())
567
+
568
+
569
+ class SoundFile(object):
570
+ """A sound file.
571
+
572
+ For more documentation see the __init__() docstring (which is also
573
+ used for the online documentation (https://python-soundfile.readthedocs.io/).
574
+
575
+ """
576
+
577
+ def __init__(self, file, mode='r', samplerate=None, channels=None,
578
+ subtype=None, endian=None, format=None, closefd=True,
579
+ compression_level=None, bitrate_mode=None):
580
+ """Open a sound file.
581
+
582
+ If a file is opened with `mode` ``'r'`` (the default) or
583
+ ``'r+'``, no sample rate, channels or file format need to be
584
+ given because the information is obtained from the file. An
585
+ exception is the ``'RAW'`` data format, which always requires
586
+ these data points.
587
+
588
+ File formats consist of three case-insensitive strings:
589
+
590
+ * a *major format* which is by default obtained from the
591
+ extension of the file name (if known) and which can be
592
+ forced with the format argument (e.g. ``format='WAVEX'``).
593
+ * a *subtype*, e.g. ``'PCM_24'``. Most major formats have a
594
+ default subtype which is used if no subtype is specified.
595
+ * an *endian-ness*, which doesn't have to be specified at all in
596
+ most cases.
597
+
598
+ A `SoundFile` object is a *context manager*, which means
599
+ if used in a "with" statement, `close()` is automatically
600
+ called when reaching the end of the code block inside the "with"
601
+ statement.
602
+
603
+ Parameters
604
+ ----------
605
+ file : str or int or file-like object
606
+ The file to open. This can be a file name, a file
607
+ descriptor or a Python file object (or a similar object with
608
+ the methods ``read()``/``readinto()``, ``write()``,
609
+ ``seek()`` and ``tell()``).
610
+ mode : {'r', 'r+', 'w', 'w+', 'x', 'x+'}, optional
611
+ Open mode. Has to begin with one of these three characters:
612
+ ``'r'`` for reading, ``'w'`` for writing (truncates *file*)
613
+ or ``'x'`` for writing (raises an error if *file* already
614
+ exists). Additionally, it may contain ``'+'`` to open
615
+ *file* for both reading and writing.
616
+ The character ``'b'`` for *binary mode* is implied because
617
+ all sound files have to be opened in this mode.
618
+ If *file* is a file descriptor or a file-like object,
619
+ ``'w'`` doesn't truncate and ``'x'`` doesn't raise an error.
620
+ samplerate : int
621
+ The sample rate of the file. If `mode` contains ``'r'``,
622
+ this is obtained from the file (except for ``'RAW'`` files).
623
+ channels : int
624
+ The number of channels of the file.
625
+ If `mode` contains ``'r'``, this is obtained from the file
626
+ (except for ``'RAW'`` files).
627
+ subtype : str, sometimes optional
628
+ The subtype of the sound file. If `mode` contains ``'r'``,
629
+ this is obtained from the file (except for ``'RAW'``
630
+ files), if not, the default value depends on the selected
631
+ `format` (see `default_subtype()`).
632
+ See `available_subtypes()` for all possible subtypes for
633
+ a given `format`.
634
+ endian : {'FILE', 'LITTLE', 'BIG', 'CPU'}, sometimes optional
635
+ The endian-ness of the sound file. If `mode` contains
636
+ ``'r'``, this is obtained from the file (except for
637
+ ``'RAW'`` files), if not, the default value is ``'FILE'``,
638
+ which is correct in most cases.
639
+ format : str, sometimes optional
640
+ The major format of the sound file. If `mode` contains
641
+ ``'r'``, this is obtained from the file (except for
642
+ ``'RAW'`` files), if not, the default value is determined
643
+ from the file extension. See `available_formats()` for
644
+ all possible values.
645
+ closefd : bool, optional
646
+ Whether to close the file descriptor on `close()`. Only
647
+ applicable if the *file* argument is a file descriptor.
648
+ compression_level : float, optional
649
+ The compression level on 'write()'. The compression level
650
+ should be between 0.0 (minimum compression level) and 1.0
651
+ (highest compression level).
652
+ See `libsndfile document <https://github.com/libsndfile/libsndfile/blob/c81375f070f3c6764969a738eacded64f53a076e/docs/command.md>`__.
653
+ bitrate_mode : {'CONSTANT', 'AVERAGE', 'VARIABLE'}, optional
654
+ The bitrate mode on 'write()'.
655
+ See `libsndfile document <https://github.com/libsndfile/libsndfile/blob/c81375f070f3c6764969a738eacded64f53a076e/docs/command.md>`__.
656
+
657
+ Examples
658
+ --------
659
+ >>> from soundfile import SoundFile
660
+
661
+ Open an existing file for reading:
662
+
663
+ >>> myfile = SoundFile('existing_file.wav')
664
+ >>> # do something with myfile
665
+ >>> myfile.close()
666
+
667
+ Create a new sound file for reading and writing using a with
668
+ statement:
669
+
670
+ >>> with SoundFile('new_file.wav', 'x+', 44100, 2) as myfile:
671
+ >>> # do something with myfile
672
+ >>> # ...
673
+ >>> assert not myfile.closed
674
+ >>> # myfile.close() is called automatically at the end
675
+ >>> assert myfile.closed
676
+
677
+ """
678
+ # resolve PathLike objects (see PEP519 for details):
679
+ # can be replaced with _os.fspath(file) for Python >= 3.6
680
+ file = file.__fspath__() if hasattr(file, '__fspath__') else file
681
+ self._name = file
682
+ if mode is None:
683
+ mode = getattr(file, 'mode', None)
684
+ mode_int = _check_mode(mode)
685
+ self._mode = mode
686
+ self._compression_level = compression_level
687
+ self._bitrate_mode = bitrate_mode
688
+ self._info = _create_info_struct(file, mode, samplerate, channels,
689
+ format, subtype, endian)
690
+ self._file = self._open(file, mode_int, closefd)
691
+ if set(mode).issuperset('r+') and self.seekable():
692
+ # Move write position to 0 (like in Python file objects)
693
+ self.seek(0)
694
+ _snd.sf_command(self._file, _snd.SFC_SET_CLIPPING, _ffi.NULL,
695
+ _snd.SF_TRUE)
696
+
697
+ # set compression setting
698
+ if self._compression_level is not None:
699
+ # needs to be called before set_bitrate_mode
700
+ self._set_compression_level(self._compression_level)
701
+ if self._bitrate_mode is not None:
702
+ self._set_bitrate_mode(self._bitrate_mode)
703
+
704
+ name = property(lambda self: self._name)
705
+ """The file name of the sound file."""
706
+ mode = property(lambda self: self._mode)
707
+ """The open mode the sound file was opened with."""
708
+ samplerate = property(lambda self: self._info.samplerate)
709
+ """The sample rate of the sound file."""
710
+ frames = property(lambda self: self._info.frames)
711
+ """The number of frames in the sound file."""
712
+ channels = property(lambda self: self._info.channels)
713
+ """The number of channels in the sound file."""
714
+ format = property(
715
+ lambda self: _format_str(self._info.format & _snd.SF_FORMAT_TYPEMASK))
716
+ """The major format of the sound file."""
717
+ subtype = property(
718
+ lambda self: _format_str(self._info.format & _snd.SF_FORMAT_SUBMASK))
719
+ """The subtype of data in the the sound file."""
720
+ endian = property(
721
+ lambda self: _format_str(self._info.format & _snd.SF_FORMAT_ENDMASK))
722
+ """The endian-ness of the data in the sound file."""
723
+ format_info = property(
724
+ lambda self: _format_info(self._info.format &
725
+ _snd.SF_FORMAT_TYPEMASK)[1])
726
+ """A description of the major format of the sound file."""
727
+ subtype_info = property(
728
+ lambda self: _format_info(self._info.format &
729
+ _snd.SF_FORMAT_SUBMASK)[1])
730
+ """A description of the subtype of the sound file."""
731
+ sections = property(lambda self: self._info.sections)
732
+ """The number of sections of the sound file."""
733
+ closed = property(lambda self: self._file is None)
734
+ """Whether the sound file is closed or not."""
735
+ _errorcode = property(lambda self: _snd.sf_error(self._file))
736
+ """A pending sndfile error code."""
737
+ compression_level = property(lambda self: self._compression_level)
738
+ """The compression level on 'write()'"""
739
+ bitrate_mode = property(lambda self: self._bitrate_mode)
740
+ """The bitrate mode on 'write()'"""
741
+
742
+ @property
743
+ def extra_info(self):
744
+ """Retrieve the log string generated when opening the file."""
745
+ info = _ffi.new("char[]", 2**14)
746
+ _snd.sf_command(self._file, _snd.SFC_GET_LOG_INFO,
747
+ info, _ffi.sizeof(info))
748
+ return _ffi.string(info).decode('utf-8', 'replace')
749
+
750
+ # avoid confusion if something goes wrong before assigning self._file:
751
+ _file = None
752
+
753
+ def __repr__(self):
754
+ compression_setting = (", compression_level={0}".format(self.compression_level)
755
+ if self.compression_level is not None else "")
756
+ compression_setting += (", bitrate_mode='{0}'".format(self.bitrate_mode)
757
+ if self.bitrate_mode is not None else "")
758
+ return ("SoundFile({0.name!r}, mode={0.mode!r}, "
759
+ "samplerate={0.samplerate}, channels={0.channels}, "
760
+ "format={0.format!r}, subtype={0.subtype!r}, "
761
+ "endian={0.endian!r}{1})".format(self, compression_setting))
762
+
763
+ def __del__(self):
764
+ self.close()
765
+
766
+ def __enter__(self):
767
+ return self
768
+
769
+ def __exit__(self, *args):
770
+ self.close()
771
+
772
+ def __setattr__(self, name, value):
773
+ """Write text meta-data in the sound file through properties."""
774
+ if name in _str_types:
775
+ self._check_if_closed()
776
+ err = _snd.sf_set_string(self._file, _str_types[name],
777
+ value.encode())
778
+ _error_check(err)
779
+ else:
780
+ object.__setattr__(self, name, value)
781
+
782
+ def __getattr__(self, name):
783
+ """Read text meta-data in the sound file through properties."""
784
+ if name in _str_types:
785
+ self._check_if_closed()
786
+ data = _snd.sf_get_string(self._file, _str_types[name])
787
+ return _ffi.string(data).decode('utf-8', 'replace') if data else ""
788
+ else:
789
+ raise AttributeError(
790
+ "'SoundFile' object has no attribute {0!r}".format(name))
791
+
792
+ def __len__(self):
793
+ # Note: This is deprecated and will be removed at some point,
794
+ # see https://github.com/bastibe/python-soundfile/issues/199
795
+ return self._info.frames
796
+
797
+ def __bool__(self):
798
+ # Note: This is temporary until __len__ is removed, afterwards it
799
+ # can (and should) be removed without change of behavior
800
+ return True
801
+
802
+ def __nonzero__(self):
803
+ # Note: This is only for compatibility with Python 2 and it shall be
804
+ # removed at the same time as __bool__().
805
+ return self.__bool__()
806
+
807
+ def seekable(self):
808
+ """Return True if the file supports seeking."""
809
+ return self._info.seekable == _snd.SF_TRUE
810
+
811
+ def seek(self, frames, whence=SEEK_SET):
812
+ """Set the read/write position.
813
+
814
+ Parameters
815
+ ----------
816
+ frames : int
817
+ The frame index or offset to seek.
818
+ whence : {SEEK_SET, SEEK_CUR, SEEK_END}, optional
819
+ By default (``whence=SEEK_SET``), *frames* are counted from
820
+ the beginning of the file.
821
+ ``whence=SEEK_CUR`` seeks from the current position
822
+ (positive and negative values are allowed for *frames*).
823
+ ``whence=SEEK_END`` seeks from the end (use negative value
824
+ for *frames*).
825
+
826
+ Returns
827
+ -------
828
+ int
829
+ The new absolute read/write position in frames.
830
+
831
+ Examples
832
+ --------
833
+ >>> from soundfile import SoundFile, SEEK_END
834
+ >>> myfile = SoundFile('stereo_file.wav')
835
+
836
+ Seek to the beginning of the file:
837
+
838
+ >>> myfile.seek(0)
839
+ 0
840
+
841
+ Seek to the end of the file:
842
+
843
+ >>> myfile.seek(0, SEEK_END)
844
+ 44100 # this is the file length
845
+
846
+ """
847
+ self._check_if_closed()
848
+ position = _snd.sf_seek(self._file, frames, whence)
849
+ _error_check(self._errorcode)
850
+ return position
851
+
852
+ def tell(self):
853
+ """Return the current read/write position."""
854
+ return self.seek(0, SEEK_CUR)
855
+
856
+ def read(self, frames=-1, dtype='float64', always_2d=False,
857
+ fill_value=None, out=None):
858
+ """Read from the file and return data as NumPy array.
859
+
860
+ Reads the given number of frames in the given data format
861
+ starting at the current read/write position. This advances the
862
+ read/write position by the same number of frames.
863
+ By default, all frames from the current read/write position to
864
+ the end of the file are returned.
865
+ Use `seek()` to move the current read/write position.
866
+
867
+ Parameters
868
+ ----------
869
+ frames : int, optional
870
+ The number of frames to read. If ``frames < 0``, the whole
871
+ rest of the file is read.
872
+ dtype : {'float64', 'float32', 'int32', 'int16'}, optional
873
+ Data type of the returned array, by default ``'float64'``.
874
+ Floating point audio data is typically in the range from
875
+ ``-1.0`` to ``1.0``. Integer data is in the range from
876
+ ``-2**15`` to ``2**15-1`` for ``'int16'`` and from
877
+ ``-2**31`` to ``2**31-1`` for ``'int32'``.
878
+
879
+ .. note:: Reading int values from a float file will *not*
880
+ scale the data to [-1.0, 1.0). If the file contains
881
+ ``np.array([42.6], dtype='float32')``, you will read
882
+ ``np.array([43], dtype='int32')`` for
883
+ ``dtype='int32'``.
884
+
885
+ Returns
886
+ -------
887
+ audiodata : `numpy.ndarray` or type(out)
888
+ A two-dimensional NumPy (frames x channels) array is
889
+ returned. If the sound file has only one channel, a
890
+ one-dimensional array is returned. Use ``always_2d=True``
891
+ to return a two-dimensional array anyway.
892
+
893
+ If *out* was specified, it is returned. If *out* has more
894
+ frames than available in the file (or if *frames* is
895
+ smaller than the length of *out*) and no *fill_value* is
896
+ given, then only a part of *out* is overwritten and a view
897
+ containing all valid frames is returned.
898
+
899
+ Other Parameters
900
+ ----------------
901
+ always_2d : bool, optional
902
+ By default, reading a mono sound file will return a
903
+ one-dimensional array. With ``always_2d=True``, audio data
904
+ is always returned as a two-dimensional array, even if the
905
+ audio file has only one channel.
906
+ fill_value : float, optional
907
+ If more frames are requested than available in the file,
908
+ the rest of the output is be filled with *fill_value*. If
909
+ *fill_value* is not specified, a smaller array is
910
+ returned.
911
+ out : `numpy.ndarray` or subclass, optional
912
+ If *out* is specified, the data is written into the given
913
+ array instead of creating a new array. In this case, the
914
+ arguments *dtype* and *always_2d* are silently ignored! If
915
+ *frames* is not given, it is obtained from the length of
916
+ *out*.
917
+
918
+ Examples
919
+ --------
920
+ >>> from soundfile import SoundFile
921
+ >>> myfile = SoundFile('stereo_file.wav')
922
+
923
+ Reading 3 frames from a stereo file:
924
+
925
+ >>> myfile.read(3)
926
+ array([[ 0.71329652, 0.06294799],
927
+ [-0.26450912, -0.38874483],
928
+ [ 0.67398441, -0.11516333]])
929
+ >>> myfile.close()
930
+
931
+ See Also
932
+ --------
933
+ buffer_read, .write
934
+
935
+ """
936
+ if out is None:
937
+ frames = self._check_frames(frames, fill_value)
938
+ out = self._create_empty_array(frames, always_2d, dtype)
939
+ else:
940
+ if frames < 0 or frames > len(out):
941
+ frames = len(out)
942
+ frames = self._array_io('read', out, frames)
943
+ if len(out) > frames:
944
+ if fill_value is None:
945
+ out = out[:frames]
946
+ else:
947
+ out[frames:] = fill_value
948
+ return out
949
+
950
+ def buffer_read(self, frames=-1, dtype=None):
951
+ """Read from the file and return data as buffer object.
952
+
953
+ Reads the given number of *frames* in the given data format
954
+ starting at the current read/write position. This advances the
955
+ read/write position by the same number of frames.
956
+ By default, all frames from the current read/write position to
957
+ the end of the file are returned.
958
+ Use `seek()` to move the current read/write position.
959
+
960
+ Parameters
961
+ ----------
962
+ frames : int, optional
963
+ The number of frames to read. If ``frames < 0``, the whole
964
+ rest of the file is read.
965
+ dtype : {'float64', 'float32', 'int32', 'int16'}
966
+ Audio data will be converted to the given data type.
967
+
968
+ Returns
969
+ -------
970
+ buffer
971
+ A buffer containing the read data.
972
+
973
+ See Also
974
+ --------
975
+ buffer_read_into, .read, buffer_write
976
+
977
+ """
978
+ frames = self._check_frames(frames, fill_value=None)
979
+ ctype = self._check_dtype(dtype)
980
+ cdata = _ffi.new(ctype + '[]', frames * self.channels)
981
+ read_frames = self._cdata_io('read', cdata, ctype, frames)
982
+ assert read_frames == frames
983
+ return _ffi.buffer(cdata)
984
+
985
+ def buffer_read_into(self, buffer, dtype):
986
+ """Read from the file into a given buffer object.
987
+
988
+ Fills the given *buffer* with frames in the given data format
989
+ starting at the current read/write position (which can be
990
+ changed with `seek()`) until the buffer is full or the end
991
+ of the file is reached. This advances the read/write position
992
+ by the number of frames that were read.
993
+
994
+ Parameters
995
+ ----------
996
+ buffer : writable buffer
997
+ Audio frames from the file are written to this buffer.
998
+ dtype : {'float64', 'float32', 'int32', 'int16'}
999
+ The data type of *buffer*.
1000
+
1001
+ Returns
1002
+ -------
1003
+ int
1004
+ The number of frames that were read from the file.
1005
+ This can be less than the size of *buffer*.
1006
+ The rest of the buffer is not filled with meaningful data.
1007
+
1008
+ See Also
1009
+ --------
1010
+ buffer_read, .read
1011
+
1012
+ """
1013
+ ctype = self._check_dtype(dtype)
1014
+ cdata, frames = self._check_buffer(buffer, ctype)
1015
+ frames = self._cdata_io('read', cdata, ctype, frames)
1016
+ return frames
1017
+
1018
+ def write(self, data):
1019
+ """Write audio data from a NumPy array to the file.
1020
+
1021
+ Writes a number of frames at the read/write position to the
1022
+ file. This also advances the read/write position by the same
1023
+ number of frames and enlarges the file if necessary.
1024
+
1025
+ Note that writing int values to a float file will *not* scale
1026
+ the values to [-1.0, 1.0). If you write the value
1027
+ ``np.array([42], dtype='int32')``, to a ``subtype='FLOAT'``
1028
+ file, the file will then contain ``np.array([42.],
1029
+ dtype='float32')``.
1030
+
1031
+ Parameters
1032
+ ----------
1033
+ data : array_like
1034
+ The data to write. Usually two-dimensional (frames x
1035
+ channels), but one-dimensional *data* can be used for mono
1036
+ files. Only the data types ``'float64'``, ``'float32'``,
1037
+ ``'int32'`` and ``'int16'`` are supported.
1038
+
1039
+ .. note:: The data type of *data* does **not** select the
1040
+ data type of the written file. Audio data will be
1041
+ converted to the given *subtype*. Writing int values
1042
+ to a float file will *not* scale the values to
1043
+ [-1.0, 1.0). If you write the value ``np.array([42],
1044
+ dtype='int32')``, to a ``subtype='FLOAT'`` file, the
1045
+ file will then contain ``np.array([42.],
1046
+ dtype='float32')``.
1047
+
1048
+ Examples
1049
+ --------
1050
+ >>> import numpy as np
1051
+ >>> from soundfile import SoundFile
1052
+ >>> myfile = SoundFile('stereo_file.wav')
1053
+
1054
+ Write 10 frames of random data to a new file:
1055
+
1056
+ >>> with SoundFile('stereo_file.wav', 'w', 44100, 2, 'PCM_24') as f:
1057
+ >>> f.write(np.random.randn(10, 2))
1058
+
1059
+ See Also
1060
+ --------
1061
+ buffer_write, .read
1062
+
1063
+ """
1064
+ import numpy as np
1065
+
1066
+ # no copy is made if data has already the correct memory layout:
1067
+ data = np.ascontiguousarray(data)
1068
+ written = self._array_io('write', data, len(data))
1069
+ assert written == len(data)
1070
+ self._update_frames(written)
1071
+
1072
+ def buffer_write(self, data, dtype):
1073
+ """Write audio data from a buffer/bytes object to the file.
1074
+
1075
+ Writes the contents of *data* to the file at the current
1076
+ read/write position.
1077
+ This also advances the read/write position by the number of
1078
+ frames that were written and enlarges the file if necessary.
1079
+
1080
+ Parameters
1081
+ ----------
1082
+ data : buffer or bytes
1083
+ A buffer or bytes object containing the audio data to be
1084
+ written.
1085
+ dtype : {'float64', 'float32', 'int32', 'int16'}
1086
+ The data type of the audio data stored in *data*.
1087
+
1088
+ See Also
1089
+ --------
1090
+ .write, buffer_read
1091
+
1092
+ """
1093
+ ctype = self._check_dtype(dtype)
1094
+ cdata, frames = self._check_buffer(data, ctype)
1095
+ written = self._cdata_io('write', cdata, ctype, frames)
1096
+ assert written == frames
1097
+ self._update_frames(written)
1098
+
1099
+ def blocks(self, blocksize=None, overlap=0, frames=-1, dtype='float64',
1100
+ always_2d=False, fill_value=None, out=None):
1101
+ """Return a generator for block-wise reading.
1102
+
1103
+ By default, the generator yields blocks of the given
1104
+ *blocksize* (using a given *overlap*) until the end of the file
1105
+ is reached; *frames* can be used to stop earlier.
1106
+
1107
+ Parameters
1108
+ ----------
1109
+ blocksize : int
1110
+ The number of frames to read per block. Either this or *out*
1111
+ must be given.
1112
+ overlap : int, optional
1113
+ The number of frames to rewind between each block.
1114
+ frames : int, optional
1115
+ The number of frames to read.
1116
+ If ``frames < 0``, the file is read until the end.
1117
+ dtype : {'float64', 'float32', 'int32', 'int16'}, optional
1118
+ See `read()`.
1119
+
1120
+ Yields
1121
+ ------
1122
+ `numpy.ndarray` or type(out)
1123
+ Blocks of audio data.
1124
+ If *out* was given, and the requested frames are not an
1125
+ integer multiple of the length of *out*, and no
1126
+ *fill_value* was given, the last block will be a smaller
1127
+ view into *out*.
1128
+
1129
+
1130
+ Other Parameters
1131
+ ----------------
1132
+ always_2d, fill_value, out
1133
+ See `read()`.
1134
+ fill_value : float, optional
1135
+ See `read()`.
1136
+ out : `numpy.ndarray` or subclass, optional
1137
+ If *out* is specified, the data is written into the given
1138
+ array instead of creating a new array. In this case, the
1139
+ arguments *dtype* and *always_2d* are silently ignored!
1140
+
1141
+ Examples
1142
+ --------
1143
+ >>> from soundfile import SoundFile
1144
+ >>> with SoundFile('stereo_file.wav') as f:
1145
+ >>> for block in f.blocks(blocksize=1024):
1146
+ >>> pass # do something with 'block'
1147
+
1148
+ """
1149
+ import numpy as np
1150
+
1151
+ if 'r' not in self.mode and '+' not in self.mode:
1152
+ raise SoundFileRuntimeError("blocks() is not allowed in write-only mode")
1153
+
1154
+ frames = self._check_frames(frames, fill_value)
1155
+ if out is None:
1156
+ if blocksize is None:
1157
+ raise TypeError("One of {blocksize, out} must be specified")
1158
+ out_size = blocksize if fill_value is not None else min(blocksize, frames)
1159
+ out = self._create_empty_array(out_size, always_2d, dtype)
1160
+ copy_out = True
1161
+ else:
1162
+ if blocksize is not None:
1163
+ raise TypeError(
1164
+ "Only one of {blocksize, out} may be specified")
1165
+ blocksize = len(out)
1166
+ copy_out = False
1167
+
1168
+ overlap_memory = None
1169
+ while frames > 0:
1170
+ if overlap_memory is None:
1171
+ output_offset = 0
1172
+ else:
1173
+ output_offset = len(overlap_memory)
1174
+ out[:output_offset] = overlap_memory
1175
+
1176
+ toread = min(blocksize - output_offset, frames)
1177
+ self.read(toread, dtype, always_2d, fill_value, out[output_offset:])
1178
+
1179
+ if overlap:
1180
+ if overlap_memory is None:
1181
+ overlap_memory = np.copy(out[-overlap:])
1182
+ else:
1183
+ overlap_memory[:] = out[-overlap:]
1184
+
1185
+ if blocksize > frames + overlap and fill_value is None:
1186
+ block = out[:frames + overlap]
1187
+ else:
1188
+ block = out
1189
+ yield np.copy(block) if copy_out else block
1190
+ frames -= toread
1191
+
1192
+ def truncate(self, frames=None):
1193
+ """Truncate the file to a given number of frames.
1194
+
1195
+ After this command, the read/write position will be at the new
1196
+ end of the file.
1197
+
1198
+ Parameters
1199
+ ----------
1200
+ frames : int, optional
1201
+ Only the data before *frames* is kept, the rest is deleted.
1202
+ If not specified, the current read/write position is used.
1203
+
1204
+ """
1205
+ if frames is None:
1206
+ frames = self.tell()
1207
+ err = _snd.sf_command(self._file, _snd.SFC_FILE_TRUNCATE,
1208
+ _ffi.new("sf_count_t*", frames),
1209
+ _ffi.sizeof("sf_count_t"))
1210
+ if err:
1211
+ # get the actual error code
1212
+ err = _snd.sf_error(self._file)
1213
+ raise LibsndfileError(err, "Error truncating the file")
1214
+ self._info.frames = frames
1215
+
1216
+ def flush(self):
1217
+ """Write unwritten data to the file system.
1218
+
1219
+ Data written with `write()` is not immediately written to
1220
+ the file system but buffered in memory to be written at a later
1221
+ time. Calling `flush()` makes sure that all changes are
1222
+ actually written to the file system.
1223
+
1224
+ This has no effect on files opened in read-only mode.
1225
+
1226
+ """
1227
+ self._check_if_closed()
1228
+ _snd.sf_write_sync(self._file)
1229
+
1230
+ def close(self):
1231
+ """Close the file. Can be called multiple times."""
1232
+ if not self.closed:
1233
+ # be sure to flush data to disk before closing the file
1234
+ self.flush()
1235
+ err = _snd.sf_close(self._file)
1236
+ self._file = None
1237
+ _error_check(err)
1238
+
1239
+ def _open(self, file, mode_int, closefd):
1240
+ """Call the appropriate sf_open*() function from libsndfile."""
1241
+ if isinstance(file, (_unicode, bytes)):
1242
+ if _os.path.isfile(file):
1243
+ if 'x' in self.mode:
1244
+ raise OSError("File exists: {0!r}".format(self.name))
1245
+ elif set(self.mode).issuperset('w+'):
1246
+ # truncate the file, because SFM_RDWR doesn't:
1247
+ _os.close(_os.open(file, _os.O_WRONLY | _os.O_TRUNC))
1248
+ openfunction = _snd.sf_open
1249
+ if isinstance(file, _unicode):
1250
+ if _sys.platform == 'win32':
1251
+ openfunction = _snd.sf_wchar_open
1252
+ else:
1253
+ file = file.encode(_sys.getfilesystemencoding())
1254
+ file_ptr = openfunction(file, mode_int, self._info)
1255
+ elif isinstance(file, int):
1256
+ file_ptr = _snd.sf_open_fd(file, mode_int, self._info, closefd)
1257
+ elif _has_virtual_io_attrs(file, mode_int):
1258
+ file_ptr = _snd.sf_open_virtual(self._init_virtual_io(file),
1259
+ mode_int, self._info, _ffi.NULL)
1260
+ else:
1261
+ raise TypeError("Invalid file: {0!r}".format(self.name))
1262
+ if file_ptr == _ffi.NULL:
1263
+ # get the actual error code
1264
+ err = _snd.sf_error(file_ptr)
1265
+ raise LibsndfileError(err, prefix="Error opening {0!r}: ".format(self.name))
1266
+ if mode_int == _snd.SFM_WRITE:
1267
+ # Due to a bug in libsndfile version <= 1.0.25, frames != 0
1268
+ # when opening a named pipe in SFM_WRITE mode.
1269
+ # See http://github.com/erikd/libsndfile/issues/77.
1270
+ self._info.frames = 0
1271
+ # This is not necessary for "normal" files (because
1272
+ # frames == 0 in this case), but it doesn't hurt, either.
1273
+ return file_ptr
1274
+
1275
+ def _init_virtual_io(self, file):
1276
+ """Initialize callback functions for sf_open_virtual()."""
1277
+ @_ffi.callback("sf_vio_get_filelen")
1278
+ def vio_get_filelen(user_data):
1279
+ curr = file.tell()
1280
+ file.seek(0, SEEK_END)
1281
+ size = file.tell()
1282
+ file.seek(curr, SEEK_SET)
1283
+ return size
1284
+
1285
+ @_ffi.callback("sf_vio_seek")
1286
+ def vio_seek(offset, whence, user_data):
1287
+ file.seek(offset, whence)
1288
+ return file.tell()
1289
+
1290
+ @_ffi.callback("sf_vio_read")
1291
+ def vio_read(ptr, count, user_data):
1292
+ # first try readinto(), if not available fall back to read()
1293
+ try:
1294
+ buf = _ffi.buffer(ptr, count)
1295
+ data_read = file.readinto(buf)
1296
+ except AttributeError:
1297
+ data = file.read(count)
1298
+ data_read = len(data)
1299
+ buf = _ffi.buffer(ptr, data_read)
1300
+ buf[0:data_read] = data
1301
+ return data_read
1302
+
1303
+ @_ffi.callback("sf_vio_write")
1304
+ def vio_write(ptr, count, user_data):
1305
+ buf = _ffi.buffer(ptr, count)
1306
+ data = buf[:]
1307
+ written = file.write(data)
1308
+ # write() returns None for file objects in Python <= 2.7:
1309
+ if written is None:
1310
+ written = count
1311
+ return written
1312
+
1313
+ @_ffi.callback("sf_vio_tell")
1314
+ def vio_tell(user_data):
1315
+ return file.tell()
1316
+
1317
+ # Note: the callback functions must be kept alive!
1318
+ self._virtual_io = {'get_filelen': vio_get_filelen,
1319
+ 'seek': vio_seek,
1320
+ 'read': vio_read,
1321
+ 'write': vio_write,
1322
+ 'tell': vio_tell}
1323
+
1324
+ return _ffi.new("SF_VIRTUAL_IO*", self._virtual_io)
1325
+
1326
+ def _getAttributeNames(self):
1327
+ """Return all attributes used in __setattr__ and __getattr__.
1328
+
1329
+ This is useful for auto-completion (e.g. IPython).
1330
+
1331
+ """
1332
+ return _str_types
1333
+
1334
+ def _check_if_closed(self):
1335
+ """Check if the file is closed and raise an error if it is.
1336
+
1337
+ This should be used in every method that uses self._file.
1338
+
1339
+ """
1340
+ if self.closed:
1341
+ raise SoundFileRuntimeError("I/O operation on closed file")
1342
+
1343
+ def _check_frames(self, frames, fill_value):
1344
+ """Reduce frames to no more than are available in the file."""
1345
+ if self.seekable():
1346
+ remaining_frames = self.frames - self.tell()
1347
+ if frames < 0 or (frames > remaining_frames and
1348
+ fill_value is None):
1349
+ frames = remaining_frames
1350
+ elif frames < 0:
1351
+ raise ValueError("frames must be specified for non-seekable files")
1352
+ return frames
1353
+
1354
+ def _check_buffer(self, data, ctype):
1355
+ """Convert buffer to cdata and check for valid size."""
1356
+ assert ctype in _ffi_types.values()
1357
+ if not isinstance(data, bytes):
1358
+ data = _ffi.from_buffer(data)
1359
+ frames, remainder = divmod(len(data),
1360
+ self.channels * _ffi.sizeof(ctype))
1361
+ if remainder:
1362
+ raise ValueError("Data size must be a multiple of frame size")
1363
+ return data, frames
1364
+
1365
+ def _create_empty_array(self, frames, always_2d, dtype):
1366
+ """Create an empty array with appropriate shape."""
1367
+ import numpy as np
1368
+ if always_2d or self.channels > 1:
1369
+ shape = frames, self.channels
1370
+ else:
1371
+ shape = frames,
1372
+ return np.empty(shape, dtype, order='C')
1373
+
1374
+ def _check_dtype(self, dtype):
1375
+ """Check if dtype string is valid and return ctype string."""
1376
+ try:
1377
+ return _ffi_types[dtype]
1378
+ except KeyError:
1379
+ raise ValueError("dtype must be one of {0!r} and not {1!r}".format(
1380
+ sorted(_ffi_types.keys()), dtype))
1381
+
1382
+ def _array_io(self, action, array, frames):
1383
+ """Check array and call low-level IO function."""
1384
+ if array.ndim not in (1,2):
1385
+ raise ValueError("Invalid shape: {0!r} ({1})".format(array.shape, "0 dimensions not supported" if array.ndim < 1 else "too many dimensions"))
1386
+ array_channels = 1 if array.ndim == 1 else array.shape[1]
1387
+ if array_channels != self.channels:
1388
+ raise ValueError("Invalid shape: {0!r} (Expected {1} channels, got {2})".format(array.shape, self.channels, array_channels))
1389
+ if not array.flags.c_contiguous:
1390
+ raise ValueError("Data must be C-contiguous")
1391
+ ctype = self._check_dtype(array.dtype.name)
1392
+ assert array.dtype.itemsize == _ffi.sizeof(ctype)
1393
+ cdata = _ffi.cast(ctype + '*', array.__array_interface__['data'][0])
1394
+ return self._cdata_io(action, cdata, ctype, frames)
1395
+
1396
+ def _cdata_io(self, action, data, ctype, frames):
1397
+ """Call one of libsndfile's read/write functions."""
1398
+ assert ctype in _ffi_types.values()
1399
+ self._check_if_closed()
1400
+ if self.seekable():
1401
+ curr = self.tell()
1402
+ func = getattr(_snd, 'sf_' + action + 'f_' + ctype)
1403
+ frames = func(self._file, data, frames)
1404
+ _error_check(self._errorcode)
1405
+ if self.seekable():
1406
+ self.seek(curr + frames, SEEK_SET) # Update read & write position
1407
+ return frames
1408
+
1409
+ def _update_frames(self, written):
1410
+ """Update self.frames after writing."""
1411
+ if self.seekable():
1412
+ curr = self.tell()
1413
+ self._info.frames = self.seek(0, SEEK_END)
1414
+ self.seek(curr, SEEK_SET)
1415
+ else:
1416
+ self._info.frames += written
1417
+
1418
+ def _prepare_read(self, start, stop, frames):
1419
+ """Seek to start frame and calculate length."""
1420
+ if start != 0 and not self.seekable():
1421
+ raise ValueError("start is only allowed for seekable files")
1422
+ if frames >= 0 and stop is not None:
1423
+ raise TypeError("Only one of {frames, stop} may be used")
1424
+
1425
+ start, stop, _ = slice(start, stop).indices(self.frames)
1426
+ if stop < start:
1427
+ stop = start
1428
+ if frames < 0:
1429
+ frames = stop - start
1430
+ if self.seekable():
1431
+ self.seek(start, SEEK_SET)
1432
+ return frames
1433
+
1434
+ def copy_metadata(self):
1435
+ """Get all metadata present in this SoundFile
1436
+
1437
+ Returns
1438
+ -------
1439
+
1440
+ metadata: dict[str, str]
1441
+ A dict with all metadata. Possible keys are: 'title', 'copyright',
1442
+ 'software', 'artist', 'comment', 'date', 'album', 'license',
1443
+ 'tracknumber' and 'genre'.
1444
+ """
1445
+ strs = {}
1446
+ for strtype, strid in _str_types.items():
1447
+ data = _snd.sf_get_string(self._file, strid)
1448
+ if data:
1449
+ strs[strtype] = _ffi.string(data).decode('utf-8', 'replace')
1450
+ return strs
1451
+
1452
+ def _set_bitrate_mode(self, bitrate_mode):
1453
+ """Call libsndfile's set bitrate mode function."""
1454
+ assert bitrate_mode in _bitrate_modes
1455
+
1456
+ pointer_bitrate_mode = _ffi.new("int[1]")
1457
+ pointer_bitrate_mode[0] = _bitrate_modes[bitrate_mode]
1458
+ err = _snd.sf_command(self._file, _snd.SFC_SET_BITRATE_MODE, pointer_bitrate_mode, _ffi.sizeof(pointer_bitrate_mode))
1459
+ if err != _snd.SF_TRUE:
1460
+ err = _snd.sf_error(self._file)
1461
+ raise LibsndfileError(err, f"Error set bitrate mode {bitrate_mode}")
1462
+
1463
+
1464
+ def _set_compression_level(self, compression_level):
1465
+ """Call libsndfile's set compression level function."""
1466
+ if not (0 <= compression_level <= 1):
1467
+ raise ValueError("Compression level must be in range [0..1]")
1468
+
1469
+ pointer_compression_level = _ffi.new("double[1]")
1470
+ pointer_compression_level[0] = compression_level
1471
+ err = _snd.sf_command(self._file, _snd.SFC_SET_COMPRESSION_LEVEL, pointer_compression_level, _ffi.sizeof(pointer_compression_level))
1472
+ if err != _snd.SF_TRUE:
1473
+ err = _snd.sf_error(self._file)
1474
+ raise LibsndfileError(err, f"Error set compression level {compression_level}")
1475
+
1476
+
1477
+ def _error_check(err, prefix=""):
1478
+ """Raise LibsndfileError if there is an error."""
1479
+ if err != 0:
1480
+ raise LibsndfileError(err, prefix=prefix)
1481
+
1482
+
1483
+ def _format_int(format, subtype, endian):
1484
+ """Return numeric ID for given format|subtype|endian combo."""
1485
+ result = _check_format(format)
1486
+ if subtype is None:
1487
+ subtype = default_subtype(format)
1488
+ if subtype is None:
1489
+ raise TypeError(
1490
+ "No default subtype for major format {0!r}".format(format))
1491
+ elif not isinstance(subtype, (_unicode, str)):
1492
+ raise TypeError("Invalid subtype: {0!r}".format(subtype))
1493
+ try:
1494
+ result |= _subtypes[subtype.upper()]
1495
+ except KeyError:
1496
+ raise ValueError("Unknown subtype: {0!r}".format(subtype))
1497
+ if endian is None:
1498
+ endian = 'FILE'
1499
+ elif not isinstance(endian, (_unicode, str)):
1500
+ raise TypeError("Invalid endian-ness: {0!r}".format(endian))
1501
+ try:
1502
+ result |= _endians[endian.upper()]
1503
+ except KeyError:
1504
+ raise ValueError("Unknown endian-ness: {0!r}".format(endian))
1505
+
1506
+ info = _ffi.new("SF_INFO*")
1507
+ info.format = result
1508
+ info.channels = 1
1509
+ if _snd.sf_format_check(info) == _snd.SF_FALSE:
1510
+ raise ValueError(
1511
+ "Invalid combination of format, subtype and endian")
1512
+ return result
1513
+
1514
+
1515
+ def _check_mode(mode):
1516
+ """Check if mode is valid and return its integer representation."""
1517
+ if not isinstance(mode, (_unicode, str)):
1518
+ raise TypeError("Invalid mode: {0!r}".format(mode))
1519
+ mode_set = set(mode)
1520
+ if mode_set.difference('xrwb+') or len(mode) > len(mode_set):
1521
+ raise ValueError("Invalid mode: {0!r}".format(mode))
1522
+ if len(mode_set.intersection('xrw')) != 1:
1523
+ raise ValueError("mode must contain exactly one of 'xrw'")
1524
+
1525
+ if '+' in mode_set:
1526
+ mode_int = _snd.SFM_RDWR
1527
+ elif 'r' in mode_set:
1528
+ mode_int = _snd.SFM_READ
1529
+ else:
1530
+ mode_int = _snd.SFM_WRITE
1531
+ return mode_int
1532
+
1533
+
1534
+ def _create_info_struct(file, mode, samplerate, channels,
1535
+ format, subtype, endian):
1536
+ """Check arguments and create SF_INFO struct."""
1537
+ original_format = format
1538
+ if format is None:
1539
+ format = _get_format_from_filename(file, mode)
1540
+ assert isinstance(format, (_unicode, str))
1541
+ else:
1542
+ _check_format(format)
1543
+
1544
+ info = _ffi.new("SF_INFO*")
1545
+ if 'r' not in mode or format.upper() == 'RAW':
1546
+ if samplerate is None:
1547
+ raise TypeError("samplerate must be specified")
1548
+ info.samplerate = samplerate
1549
+ if channels is None:
1550
+ raise TypeError("channels must be specified")
1551
+ info.channels = channels
1552
+ info.format = _format_int(format, subtype, endian)
1553
+ else:
1554
+ if any(arg is not None for arg in (
1555
+ samplerate, channels, original_format, subtype, endian)):
1556
+ raise TypeError("Not allowed for existing files (except 'RAW'): "
1557
+ "samplerate, channels, format, subtype, endian")
1558
+ return info
1559
+
1560
+
1561
+ def _get_format_from_filename(file, mode):
1562
+ """Return a format string obtained from file (or file.name).
1563
+
1564
+ If file already exists (= read mode), an empty string is returned on
1565
+ error. If not, an exception is raised.
1566
+ The return type will always be str or unicode (even if
1567
+ file/file.name is a bytes object).
1568
+
1569
+ """
1570
+ format = ''
1571
+ file = getattr(file, 'name', file)
1572
+ try:
1573
+ # This raises an exception if file is not a (Unicode/byte) string:
1574
+ format = _os.path.splitext(file)[-1][1:]
1575
+ # Convert bytes to unicode (raises AttributeError on Python 3 str):
1576
+ format = format.decode('utf-8', 'replace')
1577
+ except Exception:
1578
+ pass
1579
+ if format.upper() not in _formats and 'r' not in mode:
1580
+ raise TypeError("No format specified and unable to get format from "
1581
+ "file extension: {0!r}".format(file))
1582
+ return format
1583
+
1584
+
1585
+ def _format_str(format_int):
1586
+ """Return the string representation of a given numeric format."""
1587
+ for dictionary in _formats, _subtypes, _endians:
1588
+ for k, v in dictionary.items():
1589
+ if v == format_int:
1590
+ return k
1591
+ else:
1592
+ return 'n/a'
1593
+
1594
+
1595
+ def _format_info(format_int, format_flag=_snd.SFC_GET_FORMAT_INFO):
1596
+ """Return the ID and short description of a given format."""
1597
+ format_info = _ffi.new("SF_FORMAT_INFO*")
1598
+ format_info.format = format_int
1599
+ _snd.sf_command(_ffi.NULL, format_flag, format_info,
1600
+ _ffi.sizeof("SF_FORMAT_INFO"))
1601
+ name = format_info.name
1602
+ return (_format_str(format_info.format),
1603
+ _ffi.string(name).decode('utf-8', 'replace') if name else "")
1604
+
1605
+
1606
+ def _available_formats_helper(count_flag, format_flag):
1607
+ """Helper for available_formats() and available_subtypes()."""
1608
+ count = _ffi.new("int*")
1609
+ _snd.sf_command(_ffi.NULL, count_flag, count, _ffi.sizeof("int"))
1610
+ for format_int in range(count[0]):
1611
+ yield _format_info(format_int, format_flag)
1612
+
1613
+
1614
+ def _check_format(format_str):
1615
+ """Check if `format_str` is valid and return format ID."""
1616
+ if not isinstance(format_str, (_unicode, str)):
1617
+ raise TypeError("Invalid format: {0!r}".format(format_str))
1618
+ try:
1619
+ format_int = _formats[format_str.upper()]
1620
+ except KeyError:
1621
+ raise ValueError("Unknown format: {0!r}".format(format_str))
1622
+ return format_int
1623
+
1624
+
1625
+ def _has_virtual_io_attrs(file, mode_int):
1626
+ """Check if file has all the necessary attributes for virtual IO."""
1627
+ readonly = mode_int == _snd.SFM_READ
1628
+ writeonly = mode_int == _snd.SFM_WRITE
1629
+ return all([
1630
+ hasattr(file, 'seek'),
1631
+ hasattr(file, 'tell'),
1632
+ hasattr(file, 'write') or readonly,
1633
+ hasattr(file, 'read') or hasattr(file, 'readinto') or writeonly,
1634
+ ])
1635
+
1636
+
1637
+ class SoundFileError(Exception):
1638
+ """Base class for all soundfile-specific errors."""
1639
+ pass
1640
+
1641
+ class SoundFileRuntimeError(SoundFileError, RuntimeError):
1642
+ """soundfile module runtime error.
1643
+
1644
+ Errors that used to be `RuntimeError`."""
1645
+ pass
1646
+
1647
+ class LibsndfileError(SoundFileRuntimeError):
1648
+ """libsndfile errors.
1649
+
1650
+
1651
+ Attributes
1652
+ ----------
1653
+ code
1654
+ libsndfile internal error number.
1655
+ """
1656
+ def __init__(self, code, prefix=""):
1657
+ SoundFileRuntimeError.__init__(self, code, prefix)
1658
+ self.code = code
1659
+ self.prefix = prefix
1660
+
1661
+ @property
1662
+ def error_string(self):
1663
+ """Raw libsndfile error message."""
1664
+ if self.code:
1665
+ err_str = _snd.sf_error_number(self.code)
1666
+ return _ffi.string(err_str).decode('utf-8', 'replace')
1667
+ else:
1668
+ # Due to race conditions, if used concurrently, sf_error() may
1669
+ # return 0 (= no error) even if an error has happened.
1670
+ # See https://github.com/erikd/libsndfile/issues/610 for details.
1671
+ return "(Garbled error message from libsndfile)"
1672
+
1673
+ def __str__(self):
1674
+ return self.prefix + self.error_string
TTS/Kokoro/.venv/Lib/site-packages/typing_extensions.py ADDED
The diff for this file is too large to render. See raw diff
 
TTS/Kokoro/.venv/Scripts/Activate.ps1 ADDED
@@ -0,0 +1,528 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <#
2
+ .Synopsis
3
+ Activate a Python virtual environment for the current PowerShell session.
4
+
5
+ .Description
6
+ Pushes the python executable for a virtual environment to the front of the
7
+ $Env:PATH environment variable and sets the prompt to signify that you are
8
+ in a Python virtual environment. Makes use of the command line switches as
9
+ well as the `pyvenv.cfg` file values present in the virtual environment.
10
+
11
+ .Parameter VenvDir
12
+ Path to the directory that contains the virtual environment to activate. The
13
+ default value for this is the parent of the directory that the Activate.ps1
14
+ script is located within.
15
+
16
+ .Parameter Prompt
17
+ The prompt prefix to display when this virtual environment is activated. By
18
+ default, this prompt is the name of the virtual environment folder (VenvDir)
19
+ surrounded by parentheses and followed by a single space (ie. '(.venv) ').
20
+
21
+ .Example
22
+ Activate.ps1
23
+ Activates the Python virtual environment that contains the Activate.ps1 script.
24
+
25
+ .Example
26
+ Activate.ps1 -Verbose
27
+ Activates the Python virtual environment that contains the Activate.ps1 script,
28
+ and shows extra information about the activation as it executes.
29
+
30
+ .Example
31
+ Activate.ps1 -VenvDir C:\Users\MyUser\Common\.venv
32
+ Activates the Python virtual environment located in the specified location.
33
+
34
+ .Example
35
+ Activate.ps1 -Prompt "MyPython"
36
+ Activates the Python virtual environment that contains the Activate.ps1 script,
37
+ and prefixes the current prompt with the specified string (surrounded in
38
+ parentheses) while the virtual environment is active.
39
+
40
+ .Notes
41
+ On Windows, it may be required to enable this Activate.ps1 script by setting the
42
+ execution policy for the user. You can do this by issuing the following PowerShell
43
+ command:
44
+
45
+ PS C:\> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
46
+
47
+ For more information on Execution Policies:
48
+ https://go.microsoft.com/fwlink/?LinkID=135170
49
+
50
+ #>
51
+ Param(
52
+ [Parameter(Mandatory = $false)]
53
+ [String]
54
+ $VenvDir,
55
+ [Parameter(Mandatory = $false)]
56
+ [String]
57
+ $Prompt
58
+ )
59
+
60
+ <# Function declarations --------------------------------------------------- #>
61
+
62
+ <#
63
+ .Synopsis
64
+ Remove all shell session elements added by the Activate script, including the
65
+ addition of the virtual environment's Python executable from the beginning of
66
+ the PATH variable.
67
+
68
+ .Parameter NonDestructive
69
+ If present, do not remove this function from the global namespace for the
70
+ session.
71
+
72
+ #>
73
+ function global:deactivate ([switch]$NonDestructive) {
74
+ # Revert to original values
75
+
76
+ # The prior prompt:
77
+ if (Test-Path -Path Function:_OLD_VIRTUAL_PROMPT) {
78
+ Copy-Item -Path Function:_OLD_VIRTUAL_PROMPT -Destination Function:prompt
79
+ Remove-Item -Path Function:_OLD_VIRTUAL_PROMPT
80
+ }
81
+
82
+ # The prior PYTHONHOME:
83
+ if (Test-Path -Path Env:_OLD_VIRTUAL_PYTHONHOME) {
84
+ Copy-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME -Destination Env:PYTHONHOME
85
+ Remove-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME
86
+ }
87
+
88
+ # The prior PATH:
89
+ if (Test-Path -Path Env:_OLD_VIRTUAL_PATH) {
90
+ Copy-Item -Path Env:_OLD_VIRTUAL_PATH -Destination Env:PATH
91
+ Remove-Item -Path Env:_OLD_VIRTUAL_PATH
92
+ }
93
+
94
+ # Just remove the VIRTUAL_ENV altogether:
95
+ if (Test-Path -Path Env:VIRTUAL_ENV) {
96
+ Remove-Item -Path env:VIRTUAL_ENV
97
+ }
98
+
99
+ # Just remove VIRTUAL_ENV_PROMPT altogether.
100
+ if (Test-Path -Path Env:VIRTUAL_ENV_PROMPT) {
101
+ Remove-Item -Path env:VIRTUAL_ENV_PROMPT
102
+ }
103
+
104
+ # Just remove the _PYTHON_VENV_PROMPT_PREFIX altogether:
105
+ if (Get-Variable -Name "_PYTHON_VENV_PROMPT_PREFIX" -ErrorAction SilentlyContinue) {
106
+ Remove-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Scope Global -Force
107
+ }
108
+
109
+ # Leave deactivate function in the global namespace if requested:
110
+ if (-not $NonDestructive) {
111
+ Remove-Item -Path function:deactivate
112
+ }
113
+ }
114
+
115
+ <#
116
+ .Description
117
+ Get-PyVenvConfig parses the values from the pyvenv.cfg file located in the
118
+ given folder, and returns them in a map.
119
+
120
+ For each line in the pyvenv.cfg file, if that line can be parsed into exactly
121
+ two strings separated by `=` (with any amount of whitespace surrounding the =)
122
+ then it is considered a `key = value` line. The left hand string is the key,
123
+ the right hand is the value.
124
+
125
+ If the value starts with a `'` or a `"` then the first and last character is
126
+ stripped from the value before being captured.
127
+
128
+ .Parameter ConfigDir
129
+ Path to the directory that contains the `pyvenv.cfg` file.
130
+ #>
131
+ function Get-PyVenvConfig(
132
+ [String]
133
+ $ConfigDir
134
+ ) {
135
+ Write-Verbose "Given ConfigDir=$ConfigDir, obtain values in pyvenv.cfg"
136
+
137
+ # Ensure the file exists, and issue a warning if it doesn't (but still allow the function to continue).
138
+ $pyvenvConfigPath = Join-Path -Resolve -Path $ConfigDir -ChildPath 'pyvenv.cfg' -ErrorAction Continue
139
+
140
+ # An empty map will be returned if no config file is found.
141
+ $pyvenvConfig = @{ }
142
+
143
+ if ($pyvenvConfigPath) {
144
+
145
+ Write-Verbose "File exists, parse `key = value` lines"
146
+ $pyvenvConfigContent = Get-Content -Path $pyvenvConfigPath
147
+
148
+ $pyvenvConfigContent | ForEach-Object {
149
+ $keyval = $PSItem -split "\s*=\s*", 2
150
+ if ($keyval[0] -and $keyval[1]) {
151
+ $val = $keyval[1]
152
+
153
+ # Remove extraneous quotations around a string value.
154
+ if ("'""".Contains($val.Substring(0, 1))) {
155
+ $val = $val.Substring(1, $val.Length - 2)
156
+ }
157
+
158
+ $pyvenvConfig[$keyval[0]] = $val
159
+ Write-Verbose "Adding Key: '$($keyval[0])'='$val'"
160
+ }
161
+ }
162
+ }
163
+ return $pyvenvConfig
164
+ }
165
+
166
+
167
+ <# Begin Activate script --------------------------------------------------- #>
168
+
169
+ # Determine the containing directory of this script
170
+ $VenvExecPath = Split-Path -Parent $MyInvocation.MyCommand.Definition
171
+ $VenvExecDir = Get-Item -Path $VenvExecPath
172
+
173
+ Write-Verbose "Activation script is located in path: '$VenvExecPath'"
174
+ Write-Verbose "VenvExecDir Fullname: '$($VenvExecDir.FullName)"
175
+ Write-Verbose "VenvExecDir Name: '$($VenvExecDir.Name)"
176
+
177
+ # Set values required in priority: CmdLine, ConfigFile, Default
178
+ # First, get the location of the virtual environment, it might not be
179
+ # VenvExecDir if specified on the command line.
180
+ if ($VenvDir) {
181
+ Write-Verbose "VenvDir given as parameter, using '$VenvDir' to determine values"
182
+ }
183
+ else {
184
+ Write-Verbose "VenvDir not given as a parameter, using parent directory name as VenvDir."
185
+ $VenvDir = $VenvExecDir.Parent.FullName.TrimEnd("\\/")
186
+ Write-Verbose "VenvDir=$VenvDir"
187
+ }
188
+
189
+ # Next, read the `pyvenv.cfg` file to determine any required value such
190
+ # as `prompt`.
191
+ $pyvenvCfg = Get-PyVenvConfig -ConfigDir $VenvDir
192
+
193
+ # Next, set the prompt from the command line, or the config file, or
194
+ # just use the name of the virtual environment folder.
195
+ if ($Prompt) {
196
+ Write-Verbose "Prompt specified as argument, using '$Prompt'"
197
+ }
198
+ else {
199
+ Write-Verbose "Prompt not specified as argument to script, checking pyvenv.cfg value"
200
+ if ($pyvenvCfg -and $pyvenvCfg['prompt']) {
201
+ Write-Verbose " Setting based on value in pyvenv.cfg='$($pyvenvCfg['prompt'])'"
202
+ $Prompt = $pyvenvCfg['prompt'];
203
+ }
204
+ else {
205
+ Write-Verbose " Setting prompt based on parent's directory's name. (Is the directory name passed to venv module when creating the virtual environment)"
206
+ Write-Verbose " Got leaf-name of $VenvDir='$(Split-Path -Path $venvDir -Leaf)'"
207
+ $Prompt = Split-Path -Path $venvDir -Leaf
208
+ }
209
+ }
210
+
211
+ Write-Verbose "Prompt = '$Prompt'"
212
+ Write-Verbose "VenvDir='$VenvDir'"
213
+
214
+ # Deactivate any currently active virtual environment, but leave the
215
+ # deactivate function in place.
216
+ deactivate -nondestructive
217
+
218
+ # Now set the environment variable VIRTUAL_ENV, used by many tools to determine
219
+ # that there is an activated venv.
220
+ $env:VIRTUAL_ENV = $VenvDir
221
+
222
+ if (-not $Env:VIRTUAL_ENV_DISABLE_PROMPT) {
223
+
224
+ Write-Verbose "Setting prompt to '$Prompt'"
225
+
226
+ # Set the prompt to include the env name
227
+ # Make sure _OLD_VIRTUAL_PROMPT is global
228
+ function global:_OLD_VIRTUAL_PROMPT { "" }
229
+ Copy-Item -Path function:prompt -Destination function:_OLD_VIRTUAL_PROMPT
230
+ New-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Description "Python virtual environment prompt prefix" -Scope Global -Option ReadOnly -Visibility Public -Value $Prompt
231
+
232
+ function global:prompt {
233
+ Write-Host -NoNewline -ForegroundColor Green "($_PYTHON_VENV_PROMPT_PREFIX) "
234
+ _OLD_VIRTUAL_PROMPT
235
+ }
236
+ $env:VIRTUAL_ENV_PROMPT = $Prompt
237
+ }
238
+
239
+ # Clear PYTHONHOME
240
+ if (Test-Path -Path Env:PYTHONHOME) {
241
+ Copy-Item -Path Env:PYTHONHOME -Destination Env:_OLD_VIRTUAL_PYTHONHOME
242
+ Remove-Item -Path Env:PYTHONHOME
243
+ }
244
+
245
+ # Add the venv to the PATH
246
+ Copy-Item -Path Env:PATH -Destination Env:_OLD_VIRTUAL_PATH
247
+ $Env:PATH = "$VenvExecDir$([System.IO.Path]::PathSeparator)$Env:PATH"
248
+
249
+ # SIG # Begin signature block
250
+ # MII0BQYJKoZIhvcNAQcCoIIz9jCCM/ICAQExDzANBglghkgBZQMEAgEFADB5Bgor
251
+ # BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG
252
+ # KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCBnL745ElCYk8vk
253
+ # dBtMuQhLeWJ3ZGfzKW4DHCYzAn+QB6CCG9IwggXMMIIDtKADAgECAhBUmNLR1FsZ
254
+ # lUgTecgRwIeZMA0GCSqGSIb3DQEBDAUAMHcxCzAJBgNVBAYTAlVTMR4wHAYDVQQK
255
+ # ExVNaWNyb3NvZnQgQ29ycG9yYXRpb24xSDBGBgNVBAMTP01pY3Jvc29mdCBJZGVu
256
+ # dGl0eSBWZXJpZmljYXRpb24gUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkgMjAy
257
+ # MDAeFw0yMDA0MTYxODM2MTZaFw00NTA0MTYxODQ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qhkiG9w0BAQsFAASCAgCdP6W/pipO
517
+ # iiPBIEiwauOezR9CLHH8fUwrELK2E4Ej+JxrWhNY2aoYzKDvgs78zTCuqcEL7JVR
518
+ # D16ohPKCJPy6+lIO769TboPoYO7qkAlG3S6czokR264Qw//ocQQhKbgJh8pAbr9m
519
+ # aQwRw+pQORNlsgHsUPYFDY5dgoKWja/52CqzzDnuOEvzSrXcXbWEAb3lRS1KIUN+
520
+ # 8y9VH/6WBg4gf/B07Te84Ktqg/6XafVoGzeZP1YW6AQ2eqyg/9ieVCkeFUkCj9NI
521
+ # Ud3h1FDzeeDRSV8mw7yu48lt8pjJbWY1iJAnl7p8BwrOQVJBOH17AZwFqU7XG+hJ
522
+ # TGqb0fUEgSX8dfybEvZo6ts1VGdJmQdZoYjVDvPaccOdORakejwCm9VHFql0nhUN
523
+ # llq53/ftAVHgSG403TjNfD43ZQhoDbPLZiUB58ujhC+vrWDrbnKgdL8Bh5Khru2T
524
+ # sJlAEw48RWBGn92YR1Q4oFuXOfBSLKJ2FEVhp3tL2ncyp8ynlyM2KjaSsaCVFGCS
525
+ # awia+fswKwvH0VyU+gtr1dB10SAVMZvqR2xmc3skKSxqFclvk2W2kApKB1OqZgOo
526
+ # JRFWTz/zxVl77yc228ZzFrL8BJwLCXiLHn7DtD6kiwYrHAW04Ix3n8WGBaI5ULaa
527
+ # noz5eyimOTWgxuLUCMQ1GGwFJdVbGJrQ+Q==
528
+ # SIG # End signature block
TTS/Kokoro/.venv/Scripts/activate ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file must be used with "source bin/activate" *from bash*
2
+ # You cannot run it directly
3
+
4
+ deactivate () {
5
+ # reset old environment variables
6
+ if [ -n "${_OLD_VIRTUAL_PATH:-}" ] ; then
7
+ PATH="${_OLD_VIRTUAL_PATH:-}"
8
+ export PATH
9
+ unset _OLD_VIRTUAL_PATH
10
+ fi
11
+ if [ -n "${_OLD_VIRTUAL_PYTHONHOME:-}" ] ; then
12
+ PYTHONHOME="${_OLD_VIRTUAL_PYTHONHOME:-}"
13
+ export PYTHONHOME
14
+ unset _OLD_VIRTUAL_PYTHONHOME
15
+ fi
16
+
17
+ # Call hash to forget past locations. Without forgetting
18
+ # past locations the $PATH changes we made may not be respected.
19
+ # See "man bash" for more details. hash is usually a builtin of your shell
20
+ hash -r 2> /dev/null
21
+
22
+ if [ -n "${_OLD_VIRTUAL_PS1:-}" ] ; then
23
+ PS1="${_OLD_VIRTUAL_PS1:-}"
24
+ export PS1
25
+ unset _OLD_VIRTUAL_PS1
26
+ fi
27
+
28
+ unset VIRTUAL_ENV
29
+ unset VIRTUAL_ENV_PROMPT
30
+ if [ ! "${1:-}" = "nondestructive" ] ; then
31
+ # Self destruct!
32
+ unset -f deactivate
33
+ fi
34
+ }
35
+
36
+ # unset irrelevant variables
37
+ deactivate nondestructive
38
+
39
+ # on Windows, a path can contain colons and backslashes and has to be converted:
40
+ if [ "${OSTYPE:-}" = "cygwin" ] || [ "${OSTYPE:-}" = "msys" ] ; then
41
+ # transform D:\path\to\venv to /d/path/to/venv on MSYS
42
+ # and to /cygdrive/d/path/to/venv on Cygwin
43
+ export VIRTUAL_ENV=$(cygpath 'D:\SimRacingEngineer\SimRacingEngineer.HUD\Tools\Kokoro\.venv')
44
+ else
45
+ # use the path as-is
46
+ export VIRTUAL_ENV='D:\SimRacingEngineer\SimRacingEngineer.HUD\Tools\Kokoro\.venv'
47
+ fi
48
+
49
+ _OLD_VIRTUAL_PATH="$PATH"
50
+ PATH="$VIRTUAL_ENV/"Scripts":$PATH"
51
+ export PATH
52
+
53
+ # unset PYTHONHOME if set
54
+ # this will fail if PYTHONHOME is set to the empty string (which is bad anyway)
55
+ # could use `if (set -u; : $PYTHONHOME) ;` in bash
56
+ if [ -n "${PYTHONHOME:-}" ] ; then
57
+ _OLD_VIRTUAL_PYTHONHOME="${PYTHONHOME:-}"
58
+ unset PYTHONHOME
59
+ fi
60
+
61
+ if [ -z "${VIRTUAL_ENV_DISABLE_PROMPT:-}" ] ; then
62
+ _OLD_VIRTUAL_PS1="${PS1:-}"
63
+ PS1='(.venv) '"${PS1:-}"
64
+ export PS1
65
+ VIRTUAL_ENV_PROMPT='(.venv) '
66
+ export VIRTUAL_ENV_PROMPT
67
+ fi
68
+
69
+ # Call hash to forget past commands. Without forgetting
70
+ # past commands the $PATH changes we made may not be respected
71
+ hash -r 2> /dev/null
TTS/Kokoro/.venv/Scripts/activate.bat ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @echo off
2
+
3
+ rem This file is UTF-8 encoded, so we need to update the current code page while executing it
4
+ for /f "tokens=2 delims=:." %%a in ('"%SystemRoot%\System32\chcp.com"') do (
5
+ set _OLD_CODEPAGE=%%a
6
+ )
7
+ if defined _OLD_CODEPAGE (
8
+ "%SystemRoot%\System32\chcp.com" 65001 > nul
9
+ )
10
+
11
+ set "VIRTUAL_ENV=D:\SimRacingEngineer\SimRacingEngineer.HUD\Tools\Kokoro\.venv"
12
+
13
+ if not defined PROMPT set PROMPT=$P$G
14
+
15
+ if defined _OLD_VIRTUAL_PROMPT set PROMPT=%_OLD_VIRTUAL_PROMPT%
16
+ if defined _OLD_VIRTUAL_PYTHONHOME set PYTHONHOME=%_OLD_VIRTUAL_PYTHONHOME%
17
+
18
+ set _OLD_VIRTUAL_PROMPT=%PROMPT%
19
+ set PROMPT=(.venv) %PROMPT%
20
+
21
+ if defined PYTHONHOME set _OLD_VIRTUAL_PYTHONHOME=%PYTHONHOME%
22
+ set PYTHONHOME=
23
+
24
+ if defined _OLD_VIRTUAL_PATH set PATH=%_OLD_VIRTUAL_PATH%
25
+ if not defined _OLD_VIRTUAL_PATH set _OLD_VIRTUAL_PATH=%PATH%
26
+
27
+ set "PATH=%VIRTUAL_ENV%\Scripts;%PATH%"
28
+ set "VIRTUAL_ENV_PROMPT=(.venv) "
29
+
30
+ :END
31
+ if defined _OLD_CODEPAGE (
32
+ "%SystemRoot%\System32\chcp.com" %_OLD_CODEPAGE% > nul
33
+ set _OLD_CODEPAGE=
34
+ )
TTS/Kokoro/.venv/Scripts/deactivate.bat ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @echo off
2
+
3
+ if defined _OLD_VIRTUAL_PROMPT (
4
+ set "PROMPT=%_OLD_VIRTUAL_PROMPT%"
5
+ )
6
+ set _OLD_VIRTUAL_PROMPT=
7
+
8
+ if defined _OLD_VIRTUAL_PYTHONHOME (
9
+ set "PYTHONHOME=%_OLD_VIRTUAL_PYTHONHOME%"
10
+ set _OLD_VIRTUAL_PYTHONHOME=
11
+ )
12
+
13
+ if defined _OLD_VIRTUAL_PATH (
14
+ set "PATH=%_OLD_VIRTUAL_PATH%"
15
+ )
16
+
17
+ set _OLD_VIRTUAL_PATH=
18
+
19
+ set VIRTUAL_ENV=
20
+ set VIRTUAL_ENV_PROMPT=
21
+
22
+ :END
TTS/Kokoro/.venv/Scripts/num2words ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!D:\SimRacingEngineer\SimRacingEngineer.HUD\Tools\Kokoro\.venv\Scripts\python.exe
2
+ # -*- coding: utf-8 -*-
3
+ # Copyright (c) 2003, Taro Ogawa. All Rights Reserved.
4
+ # Copyright (c) 2013, Savoir-faire Linux inc. All Rights Reserved.
5
+
6
+ # This library is free software; you can redistribute it and/or
7
+ # modify it under the terms of the GNU Lesser General Public
8
+ # License as published by the Free Software Foundation; either
9
+ # version 2.1 of the License, or (at your option) any later version.
10
+ # This library is distributed in the hope that it will be useful,
11
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13
+ # Lesser General Public License for more details.
14
+ # You should have received a copy of the GNU Lesser General Public
15
+ # License along with this library; if not, write to the Free Software
16
+ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
17
+ # MA 02110-1301 USA
18
+
19
+ """num2words: convert numbers into words.
20
+
21
+ Usage:
22
+ num2words [options] <number>
23
+ num2words --list-languages
24
+ num2words --list-converters
25
+ num2words --help
26
+
27
+ Arguments:
28
+ <number> Number you want to convert into words
29
+
30
+ Options:
31
+ -L --list-languages Show all languages.
32
+ -C --list-converters Show all converters.
33
+ -l --lang=<lang> Output language [default: en].
34
+ -t --to=<to> Output converter [default: cardinal].
35
+ -h --help Show this message.
36
+ -v --version Show version.
37
+
38
+ Examples:
39
+ $ num2words 10001
40
+ ten thousand and one
41
+
42
+ $ num2words 24,120.10
43
+ twenty-four thousand, one hundred and twenty point one
44
+
45
+ $ num2words 24,120.10 -l es
46
+ veinticuatro mil ciento veinte punto uno
47
+
48
+ $num2words 2.14 -l es --to currency
49
+ dos euros con catorce céntimos
50
+ """
51
+
52
+ from __future__ import print_function, unicode_literals
53
+ import os
54
+ import sys
55
+ from docopt import docopt
56
+ import num2words
57
+
58
+ __version__ = "0.5.14"
59
+ __license__ = "LGPL"
60
+
61
+
62
+ def get_languages():
63
+ return sorted(list(num2words.CONVERTER_CLASSES.keys()))
64
+
65
+
66
+ def get_converters():
67
+ return sorted(list(num2words.CONVERTES_TYPES))
68
+
69
+
70
+ def main():
71
+ version = "{}=={}".format(os.path.basename(__file__), __version__)
72
+ args = docopt(__doc__, argv=None, help=True, version=version, options_first=False)
73
+ if args["--list-languages"]:
74
+ for lang in get_languages():
75
+ sys.stdout.write(lang)
76
+ sys.stdout.write(os.linesep)
77
+ sys.exit(0)
78
+ if args["--list-converters"]:
79
+ for cvt in get_converters():
80
+ sys.stdout.write(cvt)
81
+ sys.stdout.write(os.linesep)
82
+ sys.exit(0)
83
+ try:
84
+ words = num2words.num2words(args['<number>'], lang=args['--lang'], to=args['--to'])
85
+ sys.stdout.write(words + os.linesep)
86
+ sys.exit(0)
87
+ except Exception as err:
88
+ sys.stderr.write(str(args['<number>']))
89
+ sys.stderr.write(str(err) + os.linesep)
90
+ sys.stderr.write(__doc__)
91
+ sys.exit(1)
92
+
93
+
94
+ if __name__ == '__main__':
95
+ main()
TTS/Kokoro/.venv/pyvenv.cfg ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ home = C:\Program Files\Python312
2
+ include-system-site-packages = false
3
+ version = 3.12.9
4
+ executable = C:\Program Files\Python312\python.exe
5
+ command = C:\Program Files\Python312\python.exe -m venv D:\SimRacingEngineer\SimRacingEngineer.HUD\Tools\Kokoro\.venv
TTS/Kokoro/kokoro_server.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ # Força o PyTorch a NÃO usar GPU (evita disputar com o jogo)
4
+ os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
5
+
6
+ # Limita threads pra reduzir picos (ajuste se quiser 1, 2 ou 4)
7
+ os.environ["OMP_NUM_THREADS"] = "2"
8
+ os.environ["MKL_NUM_THREADS"] = "2"
9
+
10
+ import io
11
+ import argparse
12
+ import numpy as np
13
+ import soundfile as sf
14
+ from fastapi import FastAPI
15
+ from fastapi.responses import Response
16
+ from pydantic import BaseModel
17
+ import uvicorn
18
+
19
+ from kokoro import KPipeline
20
+
21
+ import torch
22
+ torch.set_num_threads(2)
23
+ torch.set_num_interop_threads(1)
24
+
25
+ app = FastAPI()
26
+
27
+ class TtsReq(BaseModel):
28
+ text: str
29
+ voice: str = "pm_alex"
30
+ speed: float = 1.0
31
+
32
+ # carrega uma vez e fica residente
33
+ PIPE = None
34
+
35
+ @app.on_event("startup")
36
+ def startup():
37
+ global PIPE
38
+ if PIPE is None:
39
+ PIPE = KPipeline(lang_code='p', repo_id='hexgrad/Kokoro-82M')
40
+
41
+ @app.get("/health")
42
+ def health():
43
+ return {"ok": True}
44
+
45
+ @app.post("/tts_wav")
46
+ def tts_wav(req: TtsReq):
47
+ global PIPE
48
+ try:
49
+ # Garantia extra (caso startup não tenha rodado)
50
+ if PIPE is None:
51
+ PIPE = KPipeline(lang_code='p', repo_id='hexgrad/Kokoro-82M')
52
+
53
+ chunks = []
54
+ for _, _, audio in PIPE(req.text, voice=req.voice, speed=req.speed, split_pattern=r'\n+'):
55
+ chunks.append(audio)
56
+
57
+ if not chunks:
58
+ return Response(content=b"", media_type="audio/wav")
59
+
60
+ audio = np.concatenate(chunks, axis=0)
61
+
62
+ buf = io.BytesIO()
63
+ sf.write(buf, audio, 24000, format="WAV")
64
+ wav_bytes = buf.getvalue()
65
+
66
+ return Response(content=wav_bytes, media_type="audio/wav")
67
+
68
+ except Exception as e:
69
+ print("[KOKORO_SERVER] ERROR:", repr(e))
70
+ raise
71
+
72
+ def main():
73
+ ap = argparse.ArgumentParser()
74
+ ap.add_argument("--host", default="127.0.0.1")
75
+ ap.add_argument("--port", type=int, default=7033)
76
+ args = ap.parse_args()
77
+
78
+ uvicorn.run(app, host=args.host, port=args.port, log_level="warning")
79
+
80
+ if __name__ == "__main__":
81
+ main()
TTS/Kokoro/kokoro_tts.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import numpy as np
3
+ import soundfile as sf
4
+ from kokoro import KPipeline
5
+
6
+ def main():
7
+ ap = argparse.ArgumentParser()
8
+ ap.add_argument("--text", required=True)
9
+ ap.add_argument("--out", required=True)
10
+ ap.add_argument("--voice", default="af_heart")
11
+ ap.add_argument("--speed", type=float, default=1.0)
12
+ args = ap.parse_args()
13
+
14
+ # 'p' = Portuguese (pt-br)
15
+ # Força repo_id explicitamente (evita confusão de assets) e usa PT-BR
16
+ pipeline = KPipeline(lang_code='p', repo_id='hexgrad/Kokoro-82M')
17
+
18
+ chunks = []
19
+ for _, _, audio in pipeline(args.text, voice=args.voice, speed=args.speed, split_pattern=r'\n+'):
20
+ chunks.append(audio)
21
+
22
+ if not chunks:
23
+ raise RuntimeError("Kokoro não gerou áudio.")
24
+
25
+ audio = np.concatenate(chunks, axis=0)
26
+ sf.write(args.out, audio, 24000)
27
+
28
+ if __name__ == "__main__":
29
+ main()
TTS/Piper/onnxruntime_providers_shared.dll ADDED
Binary file (22.4 kB). View file