diff --git a/TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib-0.23.0.dist-info/INSTALLER b/TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib-0.23.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib-0.23.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib-0.23.0.dist-info/METADATA b/TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib-0.23.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..a7d4ada1b879d5385cb0c11333dd4d1683f6f9e3 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib-0.23.0.dist-info/METADATA @@ -0,0 +1,259 @@ +Metadata-Version: 2.4 +Name: cloudpathlib +Version: 0.23.0 +Summary: pathlib-style classes for cloud storage services. +Keywords: pathlib,cloud storage,s3,azure blob storage,google cloud storage +Author-email: DrivenData +Requires-Python: >=3.9 +Description-Content-Type: text/markdown +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +License-File: LICENSE +Requires-Dist: typing-extensions>4 ; python_version < '3.11' +Requires-Dist: cloudpathlib[azure] ; extra == "all" +Requires-Dist: cloudpathlib[gs] ; extra == "all" +Requires-Dist: cloudpathlib[s3] ; extra == "all" +Requires-Dist: azure-storage-blob>=12 ; extra == "azure" +Requires-Dist: azure-storage-file-datalake>=12 ; extra == "azure" +Requires-Dist: google-cloud-storage ; extra == "gs" +Requires-Dist: boto3>=1.34.0 ; extra == "s3" +Project-URL: Bug Tracker, https://github.com/drivendataorg/cloudpathlib/issues +Project-URL: Changelog, https://cloudpathlib.drivendata.org/stable/changelog/ +Project-URL: Documentation, https://cloudpathlib.drivendata.org/ +Project-URL: Repository, https://github.com/drivendataorg/cloudpathlib +Provides-Extra: all +Provides-Extra: azure +Provides-Extra: gs +Provides-Extra: s3 + +![](https://raw.githubusercontent.com/drivendataorg/cloudpathlib/master/docs/docs/logo.svg) + +

+ +[![Docs Status](https://img.shields.io/badge/docs-stable-informational)](https://cloudpathlib.drivendata.org/) +[![PyPI](https://img.shields.io/pypi/v/cloudpathlib.svg)](https://pypi.org/project/cloudpathlib/) +[![conda-forge](https://img.shields.io/conda/vn/conda-forge/cloudpathlib.svg)](https://anaconda.org/conda-forge/cloudpathlib) +[![conda-forge feedstock](https://img.shields.io/badge/conda--forge-feedstock-yellowgreen)](https://github.com/conda-forge/cloudpathlib-feedstock) +[![tests](https://github.com/drivendataorg/cloudpathlib/actions/workflows/tests.yml/badge.svg?branch=master)](https://github.com/drivendataorg/cloudpathlib/actions/workflows/tests.yml?query=branch%3Amaster) +[![codecov](https://codecov.io/gh/drivendataorg/cloudpathlib/branch/master/graph/badge.svg)](https://codecov.io/gh/drivendataorg/cloudpathlib) + +> Our goal is to be the meringue of file management libraries: the subtle sweetness of `pathlib` working in harmony with the ethereal lightness of the cloud. + +A Python library with classes that mimic `pathlib.Path`'s interface for URIs from different cloud storage services. + +```python +with CloudPath("s3://bucket/filename.txt").open("w+") as f: + f.write("Send my changes to the cloud!") +``` + +## Why use cloudpathlib? + + - **Familiar**: If you know how to interact with `Path`, you know how to interact with `CloudPath`. All of the cloud-relevant `Path` methods are implemented. + - **Supported clouds**: AWS S3, Google Cloud Storage, and Azure Blob Storage are implemented. FTP is on the way. + - **Extensible**: The base classes do most of the work generically, so implementing two small classes `MyPath` and `MyClient` is all you need to add support for a new cloud storage service. + - **Read/write support**: Reading just works. Using the `write_text`, `write_bytes` or `.open('w')` methods will all upload your changes to cloud storage without any additional file management as a developer. + - **Seamless caching**: Files are downloaded locally only when necessary. You can also easily pass a persistent cache folder so that across processes and sessions you only re-download what is necessary. + - **Tested**: Comprehensive test suite and code coverage. + - **Testability**: Local filesystem implementations that can be used to easily mock cloud storage in your unit tests. + + +## Installation + +`cloudpathlib` depends on the cloud services' SDKs (e.g., `boto3`, `google-cloud-storage`, `azure-storage-blob`) to communicate with their respective storage service. If you try to use cloud paths for a cloud service for which you don't have dependencies installed, `cloudpathlib` will error and let you know what you need to install. + +To install a cloud service's SDK dependency when installing `cloudpathlib`, you need to specify it using pip's ["extras"](https://packaging.python.org/tutorials/installing-packages/#installing-setuptools-extras) specification. For example: + +```bash +pip install cloudpathlib[s3,gs,azure] +``` + +With some shells, you may need to use quotes: + +```bash +pip install "cloudpathlib[s3,gs,azure]" +``` + +Currently supported cloud storage services are: `azure`, `gs`, `s3`. You can also use `all` to install all available services' dependencies. + +If you do not specify any extras or separately install any cloud SDKs, you will only be able to develop with the base classes for rolling your own cloud path class. + +### conda + +`cloudpathlib` is also available using `conda` from conda-forge. Note that to install the necessary cloud service SDK dependency, you should include the appropriate suffix in the package name. For example: + +```bash +conda install cloudpathlib-s3 -c conda-forge +``` + +If no suffix is used, only the base classes will be usable. See the [conda-forge/cloudpathlib-feedstock](https://github.com/conda-forge/cloudpathlib-feedstock) for all installation options. + +### Development version + +You can get latest development version from GitHub: + +```bash +pip install https://github.com/drivendataorg/cloudpathlib.git#egg=cloudpathlib[all] +``` + +Note that you similarly need to specify cloud service dependencies, such as `all` in the above example command. + +## Quick usage + +Here's an example to get the gist of using the package. By default, `cloudpathlib` authenticates with the environment variables supported by each respective cloud service SDK. For more details and advanced authentication options, see the ["Authentication"](https://cloudpathlib.drivendata.org/stable/authentication/) documentation. + +```python +from cloudpathlib import CloudPath + +# dispatches to S3Path based on prefix +root_dir = CloudPath("s3://drivendata-public-assets/") +root_dir +#> S3Path('s3://drivendata-public-assets/') + +# there's only one file, but globbing works in nested folder +for f in root_dir.glob('**/*.txt'): + text_data = f.read_text() + print(f) + print(text_data) +#> s3://drivendata-public-assets/odsc-west-2019/DATA_DICTIONARY.txt +#> Eviction Lab Data Dictionary +#> +#> Additional information in our FAQ evictionlab.org/help-faq/ +#> Full methodology evictionlab.org/methods/ +#> +#> ... (additional text output truncated) + +# use / to join paths (and, in this case, create a new file) +new_file_copy = root_dir / "nested_dir/copy_file.txt" +new_file_copy +#> S3Path('s3://drivendata-public-assets/nested_dir/copy_file.txt') + +# show things work and the file does not exist yet +new_file_copy.exists() +#> False + +# writing text data to the new file in the cloud +new_file_copy.write_text(text_data) +#> 6933 + +# file now listed +list(root_dir.glob('**/*.txt')) +#> [S3Path('s3://drivendata-public-assets/nested_dir/copy_file.txt'), +#> S3Path('s3://drivendata-public-assets/odsc-west-2019/DATA_DICTIONARY.txt')] + +# but, we can remove it +new_file_copy.unlink() + +# no longer there +list(root_dir.glob('**/*.txt')) +#> [S3Path('s3://drivendata-public-assets/odsc-west-2019/DATA_DICTIONARY.txt')] +``` + +## Supported methods and properties + +Most methods and properties from `pathlib.Path` are supported except for the ones that don't make sense in a cloud context. There are a few additional methods or properties that relate to specific cloud services or specifically for cloud paths. + +| Methods + properties | `AzureBlobPath` | `GSPath` | `HttpsPath` | `S3Path` | +|:-----------------------|:------------------|:-----------|:--------------|:-----------| +| `absolute` | ✅ | ✅ | ✅ | ✅ | +| `anchor` | ✅ | ✅ | ✅ | ✅ | +| `as_uri` | ✅ | ✅ | ✅ | ✅ | +| `drive` | ✅ | ✅ | ✅ | ✅ | +| `exists` | ✅ | ✅ | ✅ | ✅ | +| `glob` | ✅ | ✅ | ✅ | ✅ | +| `is_absolute` | ✅ | ✅ | ✅ | ✅ | +| `is_dir` | ✅ | ✅ | ✅ | ✅ | +| `is_file` | ✅ | ✅ | ✅ | ✅ | +| `is_junction` | ✅ | ✅ | ✅ | ✅ | +| `is_relative_to` | ✅ | ✅ | ✅ | ✅ | +| `iterdir` | ✅ | ✅ | ✅ | ✅ | +| `joinpath` | ✅ | ✅ | ✅ | ✅ | +| `match` | ✅ | ✅ | ✅ | ✅ | +| `mkdir` | ✅ | ✅ | ✅ | ✅ | +| `name` | ✅ | ✅ | ✅ | ✅ | +| `open` | ✅ | ✅ | ✅ | ✅ | +| `parent` | ✅ | ✅ | ✅ | ✅ | +| `parents` | ✅ | ✅ | ✅ | ✅ | +| `parts` | ✅ | ✅ | ✅ | ✅ | +| `read_bytes` | ✅ | ✅ | ✅ | ✅ | +| `read_text` | ✅ | ✅ | ✅ | ✅ | +| `relative_to` | ✅ | ✅ | ✅ | ✅ | +| `rename` | ✅ | ✅ | ✅ | ✅ | +| `replace` | ✅ | ✅ | ✅ | ✅ | +| `resolve` | ✅ | ✅ | ✅ | ✅ | +| `rglob` | ✅ | ✅ | ✅ | ✅ | +| `rmdir` | ✅ | ✅ | ✅ | ✅ | +| `samefile` | ✅ | ✅ | ✅ | ✅ | +| `stat` | ✅ | ✅ | ✅ | ✅ | +| `stem` | ✅ | ✅ | ✅ | ✅ | +| `suffix` | ✅ | ✅ | ✅ | ✅ | +| `suffixes` | ✅ | ✅ | ✅ | ✅ | +| `touch` | ✅ | ✅ | ✅ | ✅ | +| `unlink` | ✅ | ✅ | ✅ | ✅ | +| `walk` | ✅ | ✅ | ✅ | ✅ | +| `with_name` | ✅ | ✅ | ✅ | ✅ | +| `with_segments` | ✅ | ✅ | ✅ | ✅ | +| `with_stem` | ✅ | ✅ | ✅ | ✅ | +| `with_suffix` | ✅ | ✅ | ✅ | ✅ | +| `write_bytes` | ✅ | ✅ | ✅ | ✅ | +| `write_text` | ✅ | ✅ | ✅ | ✅ | +| `as_posix` | ❌ | ❌ | ❌ | ❌ | +| `chmod` | ❌ | ❌ | ❌ | ❌ | +| `cwd` | ❌ | ❌ | ❌ | ❌ | +| `expanduser` | ❌ | ❌ | ❌ | ❌ | +| `group` | ❌ | ❌ | ❌ | ❌ | +| `hardlink_to` | ❌ | ❌ | ❌ | ❌ | +| `home` | ❌ | ❌ | ❌ | ❌ | +| `is_block_device` | ❌ | ❌ | ❌ | ❌ | +| `is_char_device` | ❌ | ❌ | ❌ | ❌ | +| `is_fifo` | ❌ | ❌ | ❌ | ❌ | +| `is_mount` | ❌ | ❌ | ❌ | ❌ | +| `is_reserved` | ❌ | ❌ | ❌ | ❌ | +| `is_socket` | ❌ | ❌ | ❌ | ❌ | +| `is_symlink` | ❌ | ❌ | ❌ | ❌ | +| `lchmod` | ❌ | ❌ | ❌ | ❌ | +| `lstat` | ❌ | ❌ | ❌ | ❌ | +| `owner` | ❌ | ❌ | ❌ | ❌ | +| `readlink` | ❌ | ❌ | ❌ | ❌ | +| `root` | ❌ | ❌ | ❌ | ❌ | +| `symlink_to` | ❌ | ❌ | ❌ | ❌ | +| `as_url` | ✅ | ✅ | ✅ | ✅ | +| `clear_cache` | ✅ | ✅ | ✅ | ✅ | +| `client` | ✅ | ✅ | ✅ | ✅ | +| `cloud_prefix` | ✅ | ✅ | ✅ | ✅ | +| `copy` | ✅ | ✅ | ✅ | ✅ | +| `copytree` | ✅ | ✅ | ✅ | ✅ | +| `download_to` | ✅ | ✅ | ✅ | ✅ | +| `from_uri` | ✅ | ✅ | ✅ | ✅ | +| `fspath` | ✅ | ✅ | ✅ | ✅ | +| `full_match` | ✅ | ✅ | ✅ | ✅ | +| `is_valid_cloudpath` | ✅ | ✅ | ✅ | ✅ | +| `parser` | ✅ | ✅ | ✅ | ✅ | +| `rmtree` | ✅ | ✅ | ✅ | ✅ | +| `upload_from` | ✅ | ✅ | ✅ | ✅ | +| `validate` | ✅ | ✅ | ✅ | ✅ | +| `etag` | ✅ | ✅ | ❌ | ✅ | +| `blob` | ✅ | ✅ | ❌ | ❌ | +| `bucket` | ❌ | ✅ | ❌ | ✅ | +| `md5` | ✅ | ✅ | ❌ | ❌ | +| `container` | ✅ | ❌ | ❌ | ❌ | +| `delete` | ❌ | ❌ | ✅ | ❌ | +| `get` | ❌ | ❌ | ✅ | ❌ | +| `head` | ❌ | ❌ | ✅ | ❌ | +| `key` | ❌ | ❌ | ❌ | ✅ | +| `parsed_url` | ❌ | ❌ | ✅ | ❌ | +| `post` | ❌ | ❌ | ✅ | ❌ | +| `put` | ❌ | ❌ | ✅ | ❌ | + +---- + +Icon made by srip from www.flaticon.com. +
Sample code block generated using the [reprexpy package](https://github.com/crew102/reprexpy). + diff --git a/TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib-0.23.0.dist-info/RECORD b/TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib-0.23.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..01840a944d036a0ca62922c0e17236015e767afe --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib-0.23.0.dist-info/RECORD @@ -0,0 +1,64 @@ +cloudpathlib-0.23.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +cloudpathlib-0.23.0.dist-info/METADATA,sha256=eVWbDCUsZPr6k_xykJQPmQ7BY6FX1Rv1loVecL7HKRk,16601 +cloudpathlib-0.23.0.dist-info/RECORD,, +cloudpathlib-0.23.0.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82 +cloudpathlib-0.23.0.dist-info/licenses/LICENSE,sha256=erAfpsP7WZARylUBfp8J-eZ7ho-0IXNqZlmS23cSwTU,1072 +cloudpathlib/__init__.py,sha256=H9UblguOpsq5xvIbJhVjKd0H-KguDrYJLJ5jEMUBRfs,1359 +cloudpathlib/__pycache__/__init__.cpython-312.pyc,, +cloudpathlib/__pycache__/anypath.cpython-312.pyc,, +cloudpathlib/__pycache__/client.cpython-312.pyc,, +cloudpathlib/__pycache__/cloudpath.cpython-312.pyc,, +cloudpathlib/__pycache__/cloudpath_info.cpython-312.pyc,, +cloudpathlib/__pycache__/enums.cpython-312.pyc,, +cloudpathlib/__pycache__/exceptions.cpython-312.pyc,, +cloudpathlib/__pycache__/patches.cpython-312.pyc,, +cloudpathlib/__pycache__/url_utils.cpython-312.pyc,, +cloudpathlib/anypath.py,sha256=0QmVGO4t6L7Uj7YuVeLikAU4BNcRtJnhjgMLa980Xyg,3510 +cloudpathlib/azure/__init__.py,sha256=eykD2Bqbxyd1NSesyu7_KYslm_5X0OqJpUjZtRX9AYc,139 +cloudpathlib/azure/__pycache__/__init__.cpython-312.pyc,, +cloudpathlib/azure/__pycache__/azblobclient.cpython-312.pyc,, +cloudpathlib/azure/__pycache__/azblobpath.cpython-312.pyc,, +cloudpathlib/azure/azblobclient.py,sha256=k1tvM84N_GK9k5LFsu1fT9FmP_2OkEDWIvChUyxt-vE,22543 +cloudpathlib/azure/azblobpath.py,sha256=hyS3bCXpaZu20RW5hiMgobwWJPEjto_h8RO1i3bL20Y,3703 +cloudpathlib/client.py,sha256=HkPiqBsDkmPR7JlYngtUs-rZSqZPoELCtIfRfV3mfqI,6415 +cloudpathlib/cloudpath.py,sha256=2en2kXLThnywc-H4_ZtAgFIHwQS7YXwJtnf6MMR9uyo,60715 +cloudpathlib/cloudpath_info.py,sha256=aDBcd69tn-qSfiN_pUhIWsxony6Ul5heNyx9MhF5bqA,861 +cloudpathlib/enums.py,sha256=87MNSRcBpXOUD56UIOIZgUerSug2PpH0WBipTkfRUAM,1900 +cloudpathlib/exceptions.py,sha256=OkmReEp1jPRPbkBZNlxo7vKmRSEa3lhTbsewJY47Vd4,1872 +cloudpathlib/gs/__init__.py,sha256=H8poYrpJdGM4Hp16jRJT0iXOW_Zh_6klt0KGoTo8a-o,103 +cloudpathlib/gs/__pycache__/__init__.cpython-312.pyc,, +cloudpathlib/gs/__pycache__/gsclient.cpython-312.pyc,, +cloudpathlib/gs/__pycache__/gspath.cpython-312.pyc,, +cloudpathlib/gs/gsclient.py,sha256=uzG57yjDpBxwgthLfUBfLVYhB91UTYb-tvKNyBWjbrQ,14172 +cloudpathlib/gs/gspath.py,sha256=6eEh6fapPO53SqrFVnSOlHC7MbMtyJ8RNdnCrlSm_gI,3249 +cloudpathlib/http/__init__.py,sha256=HTUt82vdwozNfizoYAcM8RRsJMhKbuvJoYPQshyGBlY,175 +cloudpathlib/http/__pycache__/__init__.cpython-312.pyc,, +cloudpathlib/http/__pycache__/httpclient.cpython-312.pyc,, +cloudpathlib/http/__pycache__/httppath.cpython-312.pyc,, +cloudpathlib/http/httpclient.py,sha256=7vJf10V_w_kg_zk729bmKMe9Emuh0fA9kwV4KoKKGzc,9495 +cloudpathlib/http/httppath.py,sha256=Esld5MwPuuzm8QEaOCm1N5wUOxDD5gAb8mEV3rF_CsM,5635 +cloudpathlib/legacy/__pycache__/glob.cpython-312.pyc,, +cloudpathlib/legacy/glob.py,sha256=Y2K1WjE6nGTa5td5IDYNxhow9OvzQn9e6v6MHhYYIXo,7465 +cloudpathlib/local/__init__.py,sha256=RK8a8rHM-6IajTPSKpf0EaHKCPYdkmuCR56WlkSAOqQ,1004 +cloudpathlib/local/__pycache__/__init__.cpython-312.pyc,, +cloudpathlib/local/__pycache__/localclient.cpython-312.pyc,, +cloudpathlib/local/__pycache__/localpath.cpython-312.pyc,, +cloudpathlib/local/implementations/__init__.py,sha256=SkIsKSSos4oqz8o_BKsHJ5mgBXVo2SEE_WYIqmSvjws,479 +cloudpathlib/local/implementations/__pycache__/__init__.cpython-312.pyc,, +cloudpathlib/local/implementations/__pycache__/azure.cpython-312.pyc,, +cloudpathlib/local/implementations/__pycache__/gs.cpython-312.pyc,, +cloudpathlib/local/implementations/__pycache__/s3.cpython-312.pyc,, +cloudpathlib/local/implementations/azure.py,sha256=GR_2VLWLub_IGjbwQqwaxEzs_EH09Ih4Jo_O_RoTeDA,2451 +cloudpathlib/local/implementations/gs.py,sha256=jB6--dGZ6aentk9fY2fqX8XEdnTLAj_D-_TCgGIk2qo,1694 +cloudpathlib/local/implementations/s3.py,sha256=DaKsXbNU651GHANdVCXvh8Ceb4eN7o1ZTtZCXyYC3Fc,1614 +cloudpathlib/local/localclient.py,sha256=ku8c7jlY8StTrGJ-2xFxfCort5Smwt7pVYynTTXjVKE,8832 +cloudpathlib/local/localpath.py,sha256=6PgLWw4w5hgC3OfTi4V2nal1aWAniijcjzTU-IsvnZ0,1043 +cloudpathlib/patches.py,sha256=mbk_7_aC6FTWGdcsJoEAHQ0oQ5WSMOP7Nv9e6zJhbhw,11457 +cloudpathlib/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +cloudpathlib/s3/__init__.py,sha256=o4aATyl9nVQ46JSKpIBLBPnbyiZ5NcmD2txYPAuIR2E,103 +cloudpathlib/s3/__pycache__/__init__.cpython-312.pyc,, +cloudpathlib/s3/__pycache__/s3client.cpython-312.pyc,, +cloudpathlib/s3/__pycache__/s3path.cpython-312.pyc,, +cloudpathlib/s3/s3client.py,sha256=e2CIx_NZnuRCtYMNub6Td6j32rZ9NQgHroMkJRjz-LQ,17311 +cloudpathlib/s3/s3path.py,sha256=YKDI6yn0joSrldfr1hQSiuqqlaDUBQlHHo5kjc5J8NY,2996 +cloudpathlib/url_utils.py,sha256=fAO9RFq9NBMV8qBvkmcE3DBMAPAtW5Pl7XuXB9i49b8,1211 diff --git a/TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib-0.23.0.dist-info/WHEEL b/TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib-0.23.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..d8b9936dad9ab2513fa6979f411560d3b6b57e37 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib-0.23.0.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: flit 3.12.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib/__init__.py b/TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8caf2613abaf7d6df8d18dba3f92879baaaf0e90 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib/__init__.py @@ -0,0 +1,57 @@ +import os +import sys + +from .anypath import AnyPath +from .azure.azblobclient import AzureBlobClient +from .azure.azblobpath import AzureBlobPath +from .cloudpath import CloudPath, implementation_registry +from .patches import patch_open, patch_os_functions, patch_glob, patch_all_builtins +from .gs.gsclient import GSClient +from .gs.gspath import GSPath +from .http.httpclient import HttpClient, HttpsClient +from .http.httppath import HttpPath, HttpsPath +from .s3.s3client import S3Client +from .s3.s3path import S3Path + + +if sys.version_info[:2] >= (3, 8): + import importlib.metadata as importlib_metadata +else: + import importlib_metadata + + +__version__ = importlib_metadata.version(__name__.split(".", 1)[0]) + + +__all__ = [ + "AnyPath", + "AzureBlobClient", + "AzureBlobPath", + "CloudPath", + "implementation_registry", + "GSClient", + "GSPath", + "HttpClient", + "HttpsClient", + "HttpPath", + "HttpsPath", + "patch_open", + "patch_glob", + "patch_os_functions", + "patch_all_builtins", + "S3Client", + "S3Path", +] + + +if bool(os.environ.get("CLOUDPATHLIB_PATCH_OPEN", "")): + patch_open() + +if bool(os.environ.get("CLOUDPATHLIB_PATCH_OS", "")): + patch_os_functions() + +if bool(os.environ.get("CLOUDPATHLIB_PATCH_GLOB", "")): + patch_glob() + +if bool(os.environ.get("CLOUDPATHLIB_PATCH_ALL", "")): + patch_all_builtins() diff --git a/TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib/cloudpath.py b/TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib/cloudpath.py new file mode 100644 index 0000000000000000000000000000000000000000..fa925b5bbf8661c1ee564162fe0d480b29d61a20 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib/cloudpath.py @@ -0,0 +1,1721 @@ +import abc +from collections import defaultdict +import collections.abc +from contextlib import contextmanager +from io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOWrapper +import os +from pathlib import ( # type: ignore + Path, + PosixPath, + PurePosixPath, + WindowsPath, +) + +import shutil +import sys +from types import MethodType +from typing import ( + BinaryIO, + Literal, + overload, + Any, + Callable, + Container, + Iterable, + IO, + Dict, + Generator, + List, + Optional, + Tuple, + Type, + TYPE_CHECKING, + TypeVar, + Union, + cast, +) +from urllib.parse import urlparse +from warnings import warn + +if TYPE_CHECKING: + from _typeshed import ( + OpenBinaryMode, + OpenBinaryModeReading, + OpenBinaryModeUpdating, + OpenBinaryModeWriting, + OpenTextMode, + ) + +if sys.version_info >= (3, 10): + from typing import TypeGuard +else: + from typing_extensions import TypeGuard + +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self + + +if sys.version_info < (3, 12): + from pathlib import _posix_flavour # type: ignore[attr-defined] # noqa: F811 + from pathlib import _make_selector as _make_selector_pathlib # type: ignore[attr-defined] # noqa: F811 + from pathlib import _PathParents # type: ignore[attr-defined] + + def _make_selector(pattern_parts, _flavour, case_sensitive=True): # noqa: F811 + return _make_selector_pathlib(tuple(pattern_parts), _flavour) + +elif sys.version_info[:2] == (3, 12): + from pathlib import _PathParents # type: ignore[attr-defined] + from pathlib import posixpath as _posix_flavour # type: ignore[attr-defined] + from pathlib import _make_selector # type: ignore[attr-defined] +elif sys.version_info[:2] == (3, 13): + from pathlib._local import _PathParents + import posixpath as _posix_flavour # type: ignore[attr-defined] # noqa: F811 + + from .legacy.glob import _make_selector # noqa: F811 +elif sys.version_info >= (3, 14): + from pathlib import _PathParents # type: ignore[attr-defined] + import posixpath as _posix_flavour # type: ignore[attr-defined] + from .legacy.glob import _make_selector # noqa: F811 + + +from cloudpathlib.enums import FileCacheMode + +from . import anypath +from .exceptions import ( + ClientMismatchError, + CloudPathFileExistsError, + CloudPathFileNotFoundError, + CloudPathIsADirectoryError, + CloudPathNotADirectoryError, + CloudPathNotExistsError, + CloudPathNotImplementedError, + DirectoryNotEmptyError, + IncompleteImplementationError, + InvalidPrefixError, + MissingDependenciesError, + NoStatError, + OverwriteDirtyFileError, + OverwriteNewerCloudError, + OverwriteNewerLocalError, +) + + +if TYPE_CHECKING: + from .client import Client + +from .cloudpath_info import CloudPathInfo + + +class CloudImplementation: + name: str + dependencies_loaded: bool = True + _client_class: Type["Client"] + _path_class: Type["CloudPath"] + + def validate_completeness(self) -> None: + expected = ["client_class", "path_class"] + missing = [cls for cls in expected if getattr(self, f"_{cls}") is None] + if missing: + raise IncompleteImplementationError( + f"Implementation is missing registered components: {missing}" + ) + if not self.dependencies_loaded: + raise MissingDependenciesError( + f"Missing dependencies for {self._client_class.__name__}. You can install them " + f"with 'pip install cloudpathlib[{self.name}]'." + ) + + @property + def client_class(self) -> Type["Client"]: + self.validate_completeness() + return self._client_class + + @property + def path_class(self) -> Type["CloudPath"]: + self.validate_completeness() + return self._path_class + + +implementation_registry: Dict[str, CloudImplementation] = defaultdict(CloudImplementation) + + +T = TypeVar("T") +CloudPathT = TypeVar("CloudPathT", bound="CloudPath") + + +def register_path_class(key: str) -> Callable[[Type[CloudPathT]], Type[CloudPathT]]: + def decorator(cls: Type[CloudPathT]) -> Type[CloudPathT]: + if not issubclass(cls, CloudPath): + raise TypeError("Only subclasses of CloudPath can be registered.") + implementation_registry[key]._path_class = cls + cls._cloud_meta = implementation_registry[key] + return cls + + return decorator + + +class CloudPathMeta(abc.ABCMeta): + @overload + def __call__( + cls: Type[T], cloud_path: CloudPathT, *args: Any, **kwargs: Any + ) -> CloudPathT: ... + + @overload + def __call__( + cls: Type[T], cloud_path: Union[str, "CloudPath"], *args: Any, **kwargs: Any + ) -> T: ... + + def __call__( + cls: Type[T], cloud_path: Union[str, CloudPathT], *args: Any, **kwargs: Any + ) -> Union[T, "CloudPath", CloudPathT]: + # cls is a class that is the instance of this metaclass, e.g., CloudPath + if not issubclass(cls, CloudPath): + raise TypeError( + f"Only subclasses of {CloudPath.__name__} can be instantiated from its meta class." + ) + + # Dispatch to subclass if base CloudPath + if cls is CloudPath: + for implementation in implementation_registry.values(): + path_class = implementation._path_class + if path_class is not None and path_class.is_valid_cloudpath( + cloud_path, raise_on_error=False + ): + # Instantiate path_class instance + new_obj = object.__new__(path_class) + path_class.__init__(new_obj, cloud_path, *args, **kwargs) # type: ignore[type-var] + return new_obj + valid_prefixes = [ + impl._path_class.cloud_prefix + for impl in implementation_registry.values() + if impl._path_class is not None + ] + raise InvalidPrefixError( + f"Path {cloud_path} does not begin with a known prefix {valid_prefixes}." + ) + + new_obj = object.__new__(cls) + cls.__init__(new_obj, cloud_path, *args, **kwargs) # type: ignore[type-var] + return new_obj + + def __init__(cls, name: str, bases: Tuple[type, ...], dic: Dict[str, Any]) -> None: + # Copy docstring from pathlib.Path + for attr in dir(cls): + if ( + not attr.startswith("_") + and hasattr(Path, attr) + and getattr(getattr(Path, attr), "__doc__", None) + ): + docstring = getattr(Path, attr).__doc__ + " _(Docstring copied from pathlib.Path)_" + + if isinstance(getattr(cls, attr), (MethodType)): + getattr(cls, attr).__func__.__doc__ = docstring + else: + getattr(cls, attr).__doc__ = docstring + + if isinstance(getattr(cls, attr), property): + # Properties have __doc__ duplicated under fget, and at least some parsers + # read it from there. + getattr(cls, attr).fget.__doc__ = docstring + + +# Abstract base class +class CloudPath(metaclass=CloudPathMeta): + """Base class for cloud storage file URIs, in the style of the Python standard library's + [`pathlib` module](https://docs.python.org/3/library/pathlib.html). Instances represent a path + in cloud storage with filesystem path semantics, and convenient methods allow for basic + operations like joining, reading, writing, iterating over contents, etc. `CloudPath` almost + entirely mimics the [`pathlib.Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path) + interface, so most familiar properties and methods should be available and behave in the + expected way. + + Analogous to the way `pathlib.Path` works, instantiating `CloudPath` will instead create an + instance of an appropriate subclass that implements a particular cloud storage service, such as + [`S3Path`](../s3path). This dispatching behavior is based on the URI scheme part of a cloud + storage URI (e.g., `"s3://"`). + """ + + _cloud_meta: CloudImplementation + cloud_prefix: str + + def __init__( + self, + cloud_path: Union[str, Self, "CloudPath"], + *parts: str, + client: Optional["Client"] = None, + ) -> None: + # handle if local file gets opened. must be set at the top of the method in case any code + # below raises an exception, this prevents __del__ from raising an AttributeError + self._handle: Optional[IO] = None + self._client: Optional["Client"] = None + + if parts: + # ensure first part ends in "/"; (sometimes it is just prefix, sometimes a longer path) + if not str(cloud_path).endswith("/"): + cloud_path = str(cloud_path) + "/" + + cloud_path = str(cloud_path) + "/".join(p.strip("/") for p in parts) + + self.is_valid_cloudpath(cloud_path, raise_on_error=True) + self._cloud_meta.validate_completeness() + + # versions of the raw string that provide useful methods + self._str = str(cloud_path) + self._url = urlparse(self._str) + self._path = PurePosixPath(f"/{self._no_prefix}") + + # setup client + if client is None: + if isinstance(cloud_path, CloudPath): + self._client = cloud_path.client + else: + self._client = client + + if client is not None and not isinstance(client, self._cloud_meta.client_class): + raise ClientMismatchError( + f"Client of type [{client.__class__}] is not valid for cloud path of type " + f"[{self.__class__}]; must be instance of [{self._cloud_meta.client_class}], or " + f"None to use default client for this cloud path class." + ) + + # track if local has been written to, if so it may need to be uploaded + self._dirty = False + + @property + def client(self): + if getattr(self, "_client", None) is None: + self._client = self._cloud_meta.client_class.get_default_client() + + return self._client + + def __del__(self) -> None: + # make sure that file handle to local path is closed + if self._handle is not None and self._local.exists(): + self._handle.close() + + # ensure file removed from cache when cloudpath object deleted + client = getattr(self, "_client", None) + if getattr(client, "file_cache_mode", None) == FileCacheMode.cloudpath_object: + self.clear_cache() + + def __getstate__(self) -> Dict[str, Any]: + state = self.__dict__.copy() + + # don't pickle client + if "_client" in state: + del state["_client"] + + return state + + def __setstate__(self, state: Dict[str, Any]) -> None: + self.__dict__.update(state) + + @property + def _no_prefix(self) -> str: + return self._str[len(self.anchor) :] + + @property + def _no_prefix_no_drive(self) -> str: + return self._str[len(self.anchor) + len(self.drive) :] + + @overload + @classmethod + def is_valid_cloudpath( + cls, path: "CloudPath", raise_on_error: bool = ... + ) -> TypeGuard[Self]: ... + + @overload + @classmethod + def is_valid_cloudpath(cls, path: str, raise_on_error: bool = ...) -> bool: ... + + @classmethod + def is_valid_cloudpath( + cls, path: Union[str, "CloudPath"], raise_on_error: bool = False + ) -> Union[bool, TypeGuard[Self]]: + valid = str(path).lower().startswith(cls.cloud_prefix.lower()) + + if raise_on_error and not valid: + raise InvalidPrefixError( + f"'{path}' is not a valid path since it does not start with '{cls.cloud_prefix}'" + ) + + return valid + + def __repr__(self) -> str: + return f"{self.__class__.__name__}('{self}')" + + def __str__(self) -> str: + return self._str + + def __hash__(self) -> int: + return hash((type(self).__name__, str(self))) + + def __eq__(self, other: Any) -> bool: + return isinstance(other, type(self)) and str(self) == str(other) + + def __fspath__(self) -> str: + if self.is_file(): + self._refresh_cache() + return str(self._local) + + def __lt__(self, other: Any) -> bool: + if not isinstance(other, type(self)): + return NotImplemented + return self.parts < other.parts + + def __le__(self, other: Any) -> bool: + if not isinstance(other, type(self)): + return NotImplemented + return self.parts <= other.parts + + def __gt__(self, other: Any) -> bool: + if not isinstance(other, type(self)): + return NotImplemented + return self.parts > other.parts + + def __ge__(self, other: Any) -> bool: + if not isinstance(other, type(self)): + return NotImplemented + return self.parts >= other.parts + + # ====================== NOT IMPLEMENTED ====================== + # as_posix - no cloud equivalent; not needed since we assume url separator + # chmod - permission changing should be explicitly done per client with methods + # that make sense for the client permission options + # cwd - no cloud equivalent + # expanduser - no cloud equivalent + # group - should be implemented with client-specific permissions + # home - no cloud equivalent + # is_block_device - no cloud equivalent + # is_char_device - no cloud equivalent + # is_fifo - no cloud equivalent + # is_mount - no cloud equivalent + # is_reserved - no cloud equivalent + # is_socket - no cloud equivalent + # is_symlink - no cloud equivalent + # lchmod - no cloud equivalent + # lstat - no cloud equivalent + # owner - no cloud equivalent + # readlink - no cloud equivalent + # root - drive already has the bucket and anchor/prefix has the scheme, so nothing to store here + # symlink_to - no cloud equivalent + # link_to - no cloud equivalent + # hardlink_to - no cloud equivalent + + # ====================== REQUIRED, NOT GENERIC ====================== + # Methods that must be implemented, but have no generic application + @property + @abc.abstractmethod + def drive(self) -> str: + """For example "bucket" on S3 or "container" on Azure; needs to be defined for each class""" + pass + + @abc.abstractmethod + def mkdir( + self, parents: bool = False, exist_ok: bool = False, mode: Optional[Any] = None + ) -> None: + """Should be implemented using the client API without requiring a dir is downloaded""" + pass + + @abc.abstractmethod + def touch(self, exist_ok: bool = True, mode: Optional[Any] = None) -> None: + """Should be implemented using the client API to create and update modified time""" + pass + + def as_url(self, presign: bool = False, expire_seconds: int = 60 * 60) -> str: + if presign: + url = self.client._generate_presigned_url(self, expire_seconds=expire_seconds) + else: + url = self.client._get_public_url(self) + return url + + # ====================== IMPLEMENTED FROM SCRATCH ====================== + # Methods with their own implementations that work generically + def __rtruediv__(self, other: Any) -> None: + raise ValueError( + "Cannot change a cloud path's root since all paths are absolute; create a new path instead." + ) + + @property + def anchor(self) -> str: + return self.cloud_prefix + + def as_uri(self) -> str: + return str(self) + + def exists(self, follow_symlinks=True) -> bool: + return self.client._exists(self) + + def is_dir(self, follow_symlinks=True) -> bool: + return self.client._is_file_or_dir(self) == "dir" + + def is_file(self, follow_symlinks=True) -> bool: + return self.client._is_file_or_dir(self) == "file" + + @property + def fspath(self) -> str: + return self.__fspath__() + + @classmethod + def from_uri(cls, uri: str) -> Self: + return cls(uri) + + def _glob_checks(self, pattern: Union[str, os.PathLike]) -> str: + if isinstance(pattern, os.PathLike): + if isinstance(pattern, CloudPath): + str_pattern = str(pattern.relative_to(self)) + else: + str_pattern = os.fspath(pattern) + else: + str_pattern = str(pattern) + + if ".." in str_pattern: + raise CloudPathNotImplementedError( + "Relative paths with '..' not supported in glob patterns." + ) + + if str_pattern.startswith(self.cloud_prefix) or str_pattern.startswith("/"): + raise CloudPathNotImplementedError("Non-relative patterns are unsupported") + + if self.drive == "": + raise CloudPathNotImplementedError( + ".glob is only supported within a bucket or container; you can use `.iterdir` to list buckets; for example, CloudPath('s3://').iterdir()" + ) + + return str_pattern + + def _build_subtree(self, recursive): + # build a tree structure for all files out of default dicts + Tree: Callable = lambda: defaultdict(Tree) + + def _build_tree(trunk, branch, nodes, is_dir): + """Utility to build a tree from nested defaultdicts with a generator + of nodes (parts) of a path.""" + next_branch = next(nodes, None) + + if next_branch is None: + trunk[branch] = Tree() if is_dir else None # leaf node + + else: + _build_tree(trunk[branch], next_branch, nodes, is_dir) + + file_tree = Tree() + + for f, is_dir in self.client._list_dir(self, recursive=recursive): + parts = str(f.relative_to(self)).split("/") + + # skip self + if len(parts) == 1 and parts[0] == ".": + continue + + nodes = (p for p in parts) + _build_tree(file_tree, next(nodes, None), nodes, is_dir) + + return dict(file_tree) # freeze as normal dict before passing in + + def _glob(self, selector, recursive: bool) -> Generator[Self, None, None]: + file_tree = self._build_subtree(recursive) + + root = _CloudPathSelectable( + self.name, + [], # nothing above self will be returned, so initial parents is empty + file_tree, + ) + + for p in selector.select_from(root): + # select_from returns self.name/... so strip before joining + yield (self / str(p)[len(self.name) + 1 :]) + + def glob( + self, + pattern: Union[str, os.PathLike], + case_sensitive: Optional[bool] = None, + recurse_symlinks: bool = True, + ) -> Generator[Self, None, None]: + pattern = self._glob_checks(pattern) + + pattern_parts = PurePosixPath(pattern).parts + selector = _make_selector( + tuple(pattern_parts), _posix_flavour, case_sensitive=case_sensitive + ) + + yield from self._glob( + selector, + "/" in pattern + or "**" + in pattern, # recursive listing needed if explicit ** or any sub folder in pattern + ) + + def rglob( + self, + pattern: Union[str, os.PathLike], + case_sensitive: Optional[bool] = None, + recurse_symlinks: bool = True, + ) -> Generator[Self, None, None]: + pattern = self._glob_checks(pattern) + + pattern_parts = PurePosixPath(pattern).parts + selector = _make_selector( + ("**",) + tuple(pattern_parts), _posix_flavour, case_sensitive=case_sensitive + ) + + yield from self._glob(selector, True) + + def iterdir(self) -> Generator[Self, None, None]: + for f, _ in self.client._list_dir(self, recursive=False): + if f != self: # iterdir does not include itself in pathlib + yield f + + @staticmethod + def _walk_results_from_tree(root, tree, top_down=True): + """Utility to yield tuples in the form expected by `.walk` from the file + tree constructed by `_build_substree`. + """ + dirs = [] + files = [] + for item, branch in tree.items(): + files.append(item) if branch is None else dirs.append(item) + + if top_down: + yield root, dirs, files + + for dir in dirs: + yield from CloudPath._walk_results_from_tree(root / dir, tree[dir], top_down=top_down) + + if not top_down: + yield root, dirs, files + + def walk( + self, + top_down: bool = True, + on_error: Optional[Callable] = None, + follow_symlinks: bool = False, + ) -> Generator[Tuple[Self, List[str], List[str]], None, None]: + try: + file_tree = self._build_subtree(recursive=True) # walking is always recursive + yield from self._walk_results_from_tree(self, file_tree, top_down=top_down) + + except Exception as e: + if on_error is not None: + on_error(e) + else: + raise + + @overload + def open( + self, + mode: "OpenTextMode" = "r", + buffering: int = -1, + encoding: Optional[str] = None, + errors: Optional[str] = None, + newline: Optional[str] = None, + force_overwrite_from_cloud: Optional[bool] = None, + force_overwrite_to_cloud: Optional[bool] = None, + ) -> "TextIOWrapper": ... + + @overload + def open( + self, + mode: "OpenBinaryMode", + buffering: Literal[0], + encoding: None = None, + errors: None = None, + newline: None = None, + force_overwrite_from_cloud: Optional[bool] = None, + force_overwrite_to_cloud: Optional[bool] = None, + ) -> "FileIO": ... + + @overload + def open( + self, + mode: "OpenBinaryModeUpdating", + buffering: Literal[-1, 1] = -1, + encoding: None = None, + errors: None = None, + newline: None = None, + force_overwrite_from_cloud: Optional[bool] = None, + force_overwrite_to_cloud: Optional[bool] = None, + ) -> "BufferedRandom": ... + + @overload + def open( + self, + mode: "OpenBinaryModeWriting", + buffering: Literal[-1, 1] = -1, + encoding: None = None, + errors: None = None, + newline: None = None, + force_overwrite_from_cloud: Optional[bool] = None, + force_overwrite_to_cloud: Optional[bool] = None, + ) -> "BufferedWriter": ... + + @overload + def open( + self, + mode: "OpenBinaryModeReading", + buffering: Literal[-1, 1] = -1, + encoding: None = None, + errors: None = None, + newline: None = None, + force_overwrite_from_cloud: Optional[bool] = None, + force_overwrite_to_cloud: Optional[bool] = None, + ) -> "BufferedReader": ... + + @overload + def open( + self, + mode: "OpenBinaryMode", + buffering: int = -1, + encoding: None = None, + errors: None = None, + newline: None = None, + force_overwrite_from_cloud: Optional[bool] = None, + force_overwrite_to_cloud: Optional[bool] = None, + ) -> "BinaryIO": ... + + @overload + def open( + self, + mode: str, + buffering: int = -1, + encoding: Optional[str] = None, + errors: Optional[str] = None, + newline: Optional[str] = None, + force_overwrite_from_cloud: Optional[bool] = None, + force_overwrite_to_cloud: Optional[bool] = None, + ) -> "IO[Any]": ... + + def open( + self, + mode: str = "r", + buffering: int = -1, + encoding: Optional[str] = None, + errors: Optional[str] = None, + newline: Optional[str] = None, + force_overwrite_from_cloud: Optional[bool] = None, # extra kwarg not in pathlib + force_overwrite_to_cloud: Optional[bool] = None, # extra kwarg not in pathlib + ) -> "IO[Any]": + # if trying to call open on a directory that exists + exists_on_cloud = self.exists() + + if exists_on_cloud and not self.is_file(): + raise CloudPathIsADirectoryError( + f"Cannot open directory, only files. Tried to open ({self})" + ) + + if not exists_on_cloud and any(m in mode for m in ("r", "a")): + raise CloudPathFileNotFoundError( + f"File opened for read or append, but it does not exist on cloud: {self}" + ) + + if mode == "x" and self.exists(): + raise CloudPathFileExistsError(f"Cannot open existing file ({self}) for creation.") + + # TODO: consider streaming from client rather than DLing entire file to cache + self._refresh_cache(force_overwrite_from_cloud=force_overwrite_from_cloud) + + # create any directories that may be needed if the file is new + if not self._local.exists(): + self._local.parent.mkdir(parents=True, exist_ok=True) + original_mtime = 0.0 + else: + original_mtime = self._local.stat().st_mtime + + buffer = self._local.open( + mode=mode, + buffering=buffering, + encoding=encoding, + errors=errors, + newline=newline, + ) + + # write modes need special on closing the buffer + if any(m in mode for m in ("w", "+", "x", "a")): + # dirty, handle, patch close + wrapped_close = buffer.close + + # since we are pretending this is a cloud file, upload it to the cloud + # when the buffer is closed + def _patched_close_upload(*args, **kwargs) -> None: + wrapped_close(*args, **kwargs) + + # we should be idempotent and not upload again if + # we already ran our close method patch + if not self._dirty: + return + + # original mtime should match what was in the cloud; because of system clocks or rounding + # by the cloud provider, the new version in our cache is "older" than the original version; + # explicitly set the new modified time to be after the original modified time. + if self._local.stat().st_mtime < original_mtime: + new_mtime = original_mtime + 1 + os.utime(self._local, times=(new_mtime, new_mtime)) + + self._upload_local_to_cloud(force_overwrite_to_cloud=force_overwrite_to_cloud) + self._dirty = False + + buffer.close = _patched_close_upload # type: ignore + + # keep reference in case we need to close when __del__ is called on this object + self._handle = buffer + + # opened for write, so mark dirty + self._dirty = True + + # if we don't want any cache around, remove the cache + # as soon as the file is closed + if self.client.file_cache_mode == FileCacheMode.close_file: + # this may be _patched_close_upload, in which case we need to + # make sure to call that first so the file gets uploaded + wrapped_close_for_cache = buffer.close + + def _patched_close_empty_cache(*args, **kwargs): + wrapped_close_for_cache(*args, **kwargs) + + # remove local file as last step on closing + self.clear_cache() + + buffer.close = _patched_close_empty_cache # type: ignore + + return buffer + + def replace(self, target: Self) -> Self: + if type(self) is not type(target): + raise TypeError( + f"The target based to rename must be an instantiated class of type: {type(self)}" + ) + + if self.is_dir(): + raise CloudPathIsADirectoryError( + f"Path {self} is a directory; rename/replace the files recursively." + ) + + if target == self: + # Request is to replace/rename this with the same path - nothing to do + return self + + if target.exists(): + target.unlink() + + self.client._move_file(self, target) + return target + + def rename(self, target: Self) -> Self: + # for cloud services replace == rename since we don't just rename, + # we actually move files + return self.replace(target) + + def rmdir(self) -> None: + if self.is_file(): + raise CloudPathNotADirectoryError( + f"Path {self} is a file; call unlink instead of rmdir." + ) + try: + next(self.iterdir()) + raise DirectoryNotEmptyError( + f"Directory not empty: '{self}'. Use rmtree to delete recursively." + ) + except StopIteration: + pass + self.client._remove(self) + + def samefile(self, other_path: Union[str, os.PathLike]) -> bool: + # all cloud paths are absolute and the paths are used for hash + return self == other_path + + def unlink(self, missing_ok: bool = True) -> None: + # Note: missing_ok defaults to False in pathlib, but changing the default now would be a breaking change. + if self.is_dir(): + raise CloudPathIsADirectoryError( + f"Path {self} is a directory; call rmdir instead of unlink." + ) + self.client._remove(self, missing_ok) + + def write_bytes(self, data: bytes) -> int: + """Open the file in bytes mode, write to it, and close the file. + + NOTE: vendored from pathlib since we override open + https://github.com/python/cpython/blob/3.8/Lib/pathlib.py#L1235-L1242 + """ + # type-check for the buffer interface before truncating the file + view = memoryview(data) + with self.open(mode="wb") as f: + return f.write(view) + + def write_text( + self, + data: str, + encoding: Optional[str] = None, + errors: Optional[str] = None, + newline: Optional[str] = None, + ) -> int: + """Open the file in text mode, write to it, and close the file. + + NOTE: vendored from pathlib since we override open + https://github.com/python/cpython/blob/3.10/Lib/pathlib.py#L1146-L1155 + """ + if not isinstance(data, str): + raise TypeError("data must be str, not %s" % data.__class__.__name__) + + with self.open(mode="w", encoding=encoding, errors=errors, newline=newline) as f: + return f.write(data) + + def read_bytes(self) -> bytes: + with self.open(mode="rb") as f: + return f.read() + + def read_text( + self, + encoding: Optional[str] = None, + errors: Optional[str] = None, + newline: Optional[str] = None, + ) -> str: + with self.open(mode="r", encoding=encoding, errors=errors, newline=newline) as f: + return f.read() + + def is_junction(self): + return False # only windows paths can be junctions, not cloudpaths + + # ====================== DISPATCHED TO POSIXPATH FOR PURE PATHS ====================== + # Methods that are dispatched to exactly how pathlib.PurePosixPath would calculate it on + # self._path for pure paths (does not matter if file exists); + # see the next session for ones that require a real file to exist + def _dispatch_to_path(self, func: str, *args, **kwargs) -> Any: + """Some functions we can just dispatch to the pathlib version + We want to do this explicitly so we don't have to support all + of pathlib and subclasses can override individually if necessary. + """ + path_version = self._path.__getattribute__(func) + + # Path functions should be called so the results are calculated + if callable(path_version): + path_version = path_version(*args, **kwargs) + + # Paths should always be resolved and then converted to the same client + class as this one + if isinstance(path_version, PurePosixPath): + # always resolve since cloud paths must be absolute + path_version = _resolve(path_version) + return self._new_cloudpath(path_version) + + # When sequence of PurePosixPath, we want to convert to sequence of CloudPaths + if ( + isinstance(path_version, collections.abc.Sequence) + and len(path_version) > 0 + and isinstance(path_version[0], PurePosixPath) + ): + sequence_class = ( + type(path_version) if not isinstance(path_version, _PathParents) else tuple + ) + return sequence_class( # type: ignore + self._new_cloudpath(_resolve(p)) for p in path_version if _resolve(p) != p.root + ) + + # when pathlib returns something else, we probably just want that thing + # cases this should include: str, empty sequence, sequence of str, ... + else: + return path_version + + def __truediv__(self, other: Union[str, PurePosixPath]) -> Self: + if not isinstance(other, (str, PurePosixPath)): + return NotImplemented + + return self._dispatch_to_path("__truediv__", other) + + def joinpath(self, *pathsegments: Union[str, os.PathLike]) -> Self: + return self._dispatch_to_path("joinpath", *pathsegments) + + def absolute(self) -> Self: + return self + + def is_absolute(self) -> bool: + return True + + def resolve(self, strict: bool = False) -> Self: + return self + + def relative_to(self, other: Self, walk_up: bool = False) -> PurePosixPath: + # We don't dispatch regularly since this never returns a cloud path (since it is relative, and cloud paths are + # absolute) + if not isinstance(other, CloudPath): + raise ValueError(f"{self} is a cloud path, but {other} is not") + if self.anchor != other.anchor: + raise ValueError( + f"{self} is a {self.anchor} path, but {other} is a {other.anchor} path" + ) + + kwargs = dict(walk_up=walk_up) + + if sys.version_info < (3, 12): + kwargs.pop("walk_up") + + return self._path.relative_to(other._path, **kwargs) # type: ignore[call-arg] + + def is_relative_to(self, other: Self) -> bool: + try: + self.relative_to(other) + return True + except ValueError: + return False + + @property + def name(self) -> str: + return self._dispatch_to_path("name") + + def full_match(self, pattern: str, case_sensitive: Optional[bool] = None) -> bool: + if sys.version_info < (3, 13): + raise NotImplementedError("full_match requires Python 3.13 or higher") + + # strip scheme from start of pattern before testing + if pattern.startswith(self.anchor + self.drive): + pattern = pattern[len(self.anchor + self.drive) :] + elif pattern.startswith(self.anchor): + # for http paths, keep leading slash + pattern = pattern[len(self.anchor) - 1 :] + + # remove drive, which is kept on normal dispatch to pathlib + return PurePosixPath(self._no_prefix_no_drive).full_match( # type: ignore[attr-defined] + pattern, case_sensitive=case_sensitive + ) + + def match(self, path_pattern: str, case_sensitive: Optional[bool] = None) -> bool: + # strip scheme from start of pattern before testing + if path_pattern.startswith(self.anchor + self.drive + "/"): + path_pattern = path_pattern[len(self.anchor + self.drive + "/") :] + + kwargs = dict(case_sensitive=case_sensitive) + + if sys.version_info < (3, 12): + kwargs.pop("case_sensitive") + + return self._dispatch_to_path("match", path_pattern, **kwargs) + + @property + def parser(self) -> Self: + if sys.version_info < (3, 13): + raise NotImplementedError("parser requires Python 3.13 or higher") + + return self._dispatch_to_path("parser") + + @property + def parent(self) -> Self: + return self._dispatch_to_path("parent") + + @property + def parents(self) -> Tuple[Self, ...]: + return self._dispatch_to_path("parents") + + @property + def parts(self) -> Tuple[str, ...]: + parts = self._dispatch_to_path("parts") + if parts[0] == "/": + parts = parts[1:] + + return (self.anchor, *parts) + + @property + def stem(self) -> str: + return self._dispatch_to_path("stem") + + @property + def suffix(self) -> str: + return self._dispatch_to_path("suffix") + + @property + def suffixes(self) -> List[str]: + return self._dispatch_to_path("suffixes") + + def with_stem(self, stem: str) -> Self: + try: + return self._dispatch_to_path("with_stem", stem) + except AttributeError: + # with_stem was only added in python 3.9, so we fallback for compatibility + return self.with_name(stem + self.suffix) + + def with_name(self, name: str) -> Self: + return self._dispatch_to_path("with_name", name) + + def with_segments(self, *pathsegments) -> Self: + """Create a new CloudPath with the same client out of the given segments. + The first segment will be interpreted as the bucket/container name. + """ + return self._new_cloudpath("/".join(pathsegments)) + + def with_suffix(self, suffix: str) -> Self: + return self._dispatch_to_path("with_suffix", suffix) + + # ====================== DISPATCHED TO LOCAL CACHE FOR CONCRETE PATHS ====================== + # Items that can be executed on the cached file on the local filesystem + def _dispatch_to_local_cache_path(self, func: str, *args, **kwargs) -> Any: + self._refresh_cache() + + path_version = self._local.__getattribute__(func) + + # Path functions should be called so the results are calculated + if callable(path_version): + path_version = path_version(*args, **kwargs) + + # Paths should always be resolved and then converted to the same client + class as this one + if isinstance(path_version, (PosixPath, WindowsPath)): + # always resolve since cloud paths must be absolute + path_version = path_version.resolve() + return self._new_cloudpath(path_version) + + # when pathlib returns a string, etc. we probably just want that thing + else: + return path_version + + def stat(self, follow_symlinks: bool = True) -> os.stat_result: + """Note: for many clients, we may want to override so we don't incur + network costs since many of these properties are available as + API calls. + """ + warn( + f"stat not implemented as API call for {self.__class__} so file must be downloaded to " + f"calculate stats; this may take a long time depending on filesize" + ) + return self._dispatch_to_local_cache_path("stat", follow_symlinks=follow_symlinks) + + def info(self) -> "CloudPathInfo": + """Return a CloudPathInfo object for this path.""" + return CloudPathInfo(self) + + # =========== public cloud methods, not in pathlib =============== + def download_to(self, destination: Union[str, os.PathLike]) -> Path: + destination = Path(destination) + + if not self.exists(): + raise CloudPathNotExistsError(f"Cannot download because path does not exist: {self}") + + if self.is_file(): + if destination.is_dir(): + destination = destination / self.name + return self.client._download_file(self, destination) + else: + destination.mkdir(exist_ok=True) + for f in self.iterdir(): + rel = str(self) + if not rel.endswith("/"): + rel = rel + "/" + + rel_dest = str(f)[len(rel) :] + f.download_to(destination / rel_dest) + + return destination + + def rmtree(self) -> None: + """Delete an entire directory tree.""" + if self.is_file(): + raise CloudPathNotADirectoryError( + f"Path {self} is a file; call unlink instead of rmtree." + ) + self.client._remove(self) + + def upload_from( + self, + source: Union[str, os.PathLike], + force_overwrite_to_cloud: Optional[bool] = None, + ) -> Self: + """Upload a file or directory to the cloud path.""" + source = Path(source) + + if source.is_dir(): + for p in source.iterdir(): + (self / p.name).upload_from(p, force_overwrite_to_cloud=force_overwrite_to_cloud) + + return self + + else: + if self.exists() and self.is_dir(): + dst = self / source.name + else: + dst = self + + dst._upload_file_to_cloud(source, force_overwrite_to_cloud=force_overwrite_to_cloud) + + return dst + + def _copy( + self, + target: Union[str, os.PathLike, "CloudPath"], + follow_symlinks: bool = True, + preserve_metadata: bool = False, + force_overwrite_to_cloud: Optional[bool] = None, + remove_src: bool = False, + ) -> Union[Path, Self]: + if not self.exists(): + raise ValueError(f"Path {self} must exist to copy.") + + destination = anypath.to_anypath(target) + + if self.is_dir(): + result = self.copytree( + destination, # type: ignore[arg-type] + force_overwrite_to_cloud=force_overwrite_to_cloud, + ) + return cast(Union[Path, Self], result) + + if not isinstance(destination, CloudPath): + return self.download_to(destination) + + # if same client, use cloud-native _move_file on client to avoid downloading + if self.client is destination.client: + if destination.exists() and destination.is_dir(): + destination = destination / self.name + + if force_overwrite_to_cloud is None: + force_overwrite_to_cloud = os.environ.get( + "CLOUDPATHLIB_FORCE_OVERWRITE_TO_CLOUD", "False" + ).lower() in ["1", "true"] + + if ( + not force_overwrite_to_cloud + and destination.exists() + and destination.stat().st_mtime >= self.stat().st_mtime + ): + raise OverwriteNewerCloudError( + f"File ({destination}) is newer than ({self}). " + f"To overwrite " + f"pass `force_overwrite_to_cloud=True`." + ) + + return cast(Self, self.client._move_file(self, destination, remove_src=remove_src)) + + else: + if not destination.exists() or destination.is_file(): + return cast( + Union[Path, Self], + destination.upload_from( + self.fspath, force_overwrite_to_cloud=force_overwrite_to_cloud + ), + ) + else: + return cast( + Union[Path, Self], + (destination / self.name).upload_from( + self.fspath, force_overwrite_to_cloud=force_overwrite_to_cloud + ), + ) + + @overload + def copy( + self, + target: Self, + follow_symlinks=True, + preserve_metadata=False, + force_overwrite_to_cloud: Optional[bool] = None, + ) -> Self: ... + + @overload + def copy( + self, + target: Path, + follow_symlinks=True, + preserve_metadata=False, + force_overwrite_to_cloud: Optional[bool] = None, + ) -> Path: ... + + @overload + def copy( + self, + target: str, + follow_symlinks=True, + preserve_metadata=False, + force_overwrite_to_cloud: Optional[bool] = None, + ) -> Union[Path, "CloudPath"]: ... + + def copy( + self, + target: Union[str, os.PathLike, Self], + follow_symlinks: bool = True, + preserve_metadata: bool = False, + force_overwrite_to_cloud: Optional[bool] = None, + ) -> Union[Path, Self]: + """Copy self to target folder or file, if self is a file.""" + return self._copy( + target, + follow_symlinks=follow_symlinks, + preserve_metadata=preserve_metadata, + force_overwrite_to_cloud=force_overwrite_to_cloud, + remove_src=False, + ) + + @overload + def copy_into( + self, + target_dir: Self, + follow_symlinks: bool = True, + preserve_metadata: bool = False, + force_overwrite_to_cloud: Optional[bool] = None, + ) -> Self: ... + + @overload + def copy_into( + self, + target_dir: Path, + follow_symlinks: bool = True, + preserve_metadata: bool = False, + force_overwrite_to_cloud: Optional[bool] = None, + ) -> Path: ... + + @overload + def copy_into( + self, + target_dir: str, + follow_symlinks: bool = True, + preserve_metadata: bool = False, + force_overwrite_to_cloud: Optional[bool] = None, + ) -> Union[Path, "CloudPath"]: ... + + def copy_into( + self, + target_dir: Union[str, os.PathLike, Self], + follow_symlinks: bool = True, + preserve_metadata: bool = False, + force_overwrite_to_cloud: Optional[bool] = None, + ) -> Union[Path, Self]: + """Copy self into target directory, preserving the filename.""" + target_path = anypath.to_anypath(target_dir) / self.name + + result = self._copy( + target_path, + follow_symlinks=follow_symlinks, + preserve_metadata=preserve_metadata, + force_overwrite_to_cloud=force_overwrite_to_cloud, + remove_src=False, + ) + return cast(Union[Path, Self], result) + + @overload + def copytree( + self, + destination: Self, + force_overwrite_to_cloud: Optional[bool] = None, + ignore: Optional[Callable[[str, Iterable[str]], Container[str]]] = None, + ) -> Self: ... + + @overload + def copytree( + self, + destination: Path, + force_overwrite_to_cloud: Optional[bool] = None, + ignore: Optional[Callable[[str, Iterable[str]], Container[str]]] = None, + ) -> Path: ... + + @overload + def copytree( + self, + destination: Union[str, os.PathLike, Self], + force_overwrite_to_cloud: Optional[bool] = None, + ignore: Optional[Callable[[str, Iterable[str]], Container[str]]] = None, + ) -> Union[Path, "CloudPath"]: ... + + def copytree(self, destination, force_overwrite_to_cloud=None, ignore=None): + """Copy self to a directory, if self is a directory.""" + if not self.is_dir(): + raise CloudPathNotADirectoryError( + f"Origin path {self} must be a directory. To copy a single file use the method copy." + ) + + destination = anypath.to_anypath(destination) + + if destination.exists() and destination.is_file(): + raise CloudPathFileExistsError( + f"Destination path {destination} of copytree must be a directory." + ) + + contents = list(self.iterdir()) + + if ignore is not None: + ignored_names = ignore(self._no_prefix_no_drive, [x.name for x in contents]) + else: + ignored_names = set() + + destination.mkdir(parents=True, exist_ok=True) + + for subpath in contents: + if subpath.name in ignored_names: + continue + if subpath.is_file(): + subpath.copy( + destination / subpath.name, force_overwrite_to_cloud=force_overwrite_to_cloud + ) + elif subpath.is_dir(): + subpath.copytree( + destination / (subpath.name + ("" if subpath.name.endswith("/") else "/")), + force_overwrite_to_cloud=force_overwrite_to_cloud, + ignore=ignore, + ) + + return destination + + @overload + def move( + self, + target: Self, + follow_symlinks: bool = True, + preserve_metadata: bool = False, + force_overwrite_to_cloud: Optional[bool] = None, + ) -> Self: ... + + @overload + def move( + self, + target: Path, + follow_symlinks: bool = True, + preserve_metadata: bool = False, + force_overwrite_to_cloud: Optional[bool] = None, + ) -> Path: ... + + @overload + def move( + self, + target: str, + follow_symlinks: bool = True, + preserve_metadata: bool = False, + force_overwrite_to_cloud: Optional[bool] = None, + ) -> Union[Path, "CloudPath"]: ... + + def move( + self, + target: Union[str, os.PathLike, Self], + follow_symlinks: bool = True, + preserve_metadata: bool = False, + force_overwrite_to_cloud: Optional[bool] = None, + ) -> Union[Path, Self]: + """Move self to target location, removing the source.""" + return self._copy( + target, + follow_symlinks=follow_symlinks, + preserve_metadata=preserve_metadata, + force_overwrite_to_cloud=force_overwrite_to_cloud, + remove_src=True, + ) + + @overload + def move_into( + self, + target_dir: Self, + follow_symlinks: bool = True, + preserve_metadata: bool = False, + force_overwrite_to_cloud: Optional[bool] = None, + ) -> Self: ... + + @overload + def move_into( + self, + target_dir: Path, + follow_symlinks: bool = True, + preserve_metadata: bool = False, + force_overwrite_to_cloud: Optional[bool] = None, + ) -> Path: ... + + @overload + def move_into( + self, + target_dir: str, + follow_symlinks: bool = True, + preserve_metadata: bool = False, + force_overwrite_to_cloud: Optional[bool] = None, + ) -> Union[Path, "CloudPath"]: ... + + def move_into( + self, + target_dir: Union[str, os.PathLike, Self], + follow_symlinks: bool = True, + preserve_metadata: bool = False, + force_overwrite_to_cloud: Optional[bool] = None, + ) -> Union[Path, Self]: + """Move self into target directory, preserving the filename and removing the source.""" + target_path = anypath.to_anypath(target_dir) / self.name + + result = self._copy( + target_path, + follow_symlinks=follow_symlinks, + preserve_metadata=preserve_metadata, + force_overwrite_to_cloud=force_overwrite_to_cloud, + remove_src=True, + ) + return cast(Union[Path, Self], result) + + def clear_cache(self): + """Removes cache if it exists""" + if self._local.exists(): + if self._local.is_file(): + self._local.unlink() + else: + shutil.rmtree(self._local) + + # =========== private cloud methods =============== + @property + def _local(self) -> Path: + """Cached local version of the file.""" + return self.client._local_cache_dir / self._no_prefix + + def _new_cloudpath(self, path: Union[str, os.PathLike], *parts: str) -> Self: + """Use the scheme, client, cache dir of this cloudpath to instantiate + a new cloudpath of the same type with the path passed. + + Used to make results of iterdir and joins have a unified client + cache. + """ + path = str(path) + + # strip initial "/" if path has one + if path.startswith("/"): + path = path[1:] + + # add prefix/anchor if it is not already + if not path.startswith(self.anchor): + path = f"{self.anchor}{path}" + + return self.client.CloudPath(path, *parts) + + def _refresh_cache(self, force_overwrite_from_cloud: Optional[bool] = None) -> None: + try: + stats = self.stat() + except NoStatError: + # nothing to cache if the file does not exist; happens when creating + # new files that will be uploaded + return + + if force_overwrite_from_cloud is None: + force_overwrite_from_cloud = os.environ.get( + "CLOUDPATHLIB_FORCE_OVERWRITE_FROM_CLOUD", "False" + ).lower() in ["1", "true"] + + # if not exist or cloud newer + if ( + force_overwrite_from_cloud + or not self._local.exists() + or (self._local.stat().st_mtime < stats.st_mtime) + ): + # ensure there is a home for the file + self._local.parent.mkdir(parents=True, exist_ok=True) + self.download_to(self._local) + + # force cache time to match cloud times + os.utime(self._local, times=(stats.st_mtime, stats.st_mtime)) + + if self._dirty: + raise OverwriteDirtyFileError( + f"Local file ({self._local}) for cloud path ({self}) has been changed by your code, but " + f"is being requested for download from cloud. Either (1) push your changes to the cloud, " + f"(2) remove the local file, or (3) pass `force_overwrite_from_cloud=True` to " + f"overwrite; or set env var CLOUDPATHLIB_FORCE_OVERWRITE_FROM_CLOUD=1." + ) + + # if local newer but not dirty, it was updated + # by a separate process; do not overwrite unless forced to + if self._local.stat().st_mtime > stats.st_mtime: + raise OverwriteNewerLocalError( + f"Local file ({self._local}) for cloud path ({self}) is newer on disk, but " + f"is being requested for download from cloud. Either (1) push your changes to the cloud, " + f"(2) remove the local file, or (3) pass `force_overwrite_from_cloud=True` to " + f"overwrite; or set env var CLOUDPATHLIB_FORCE_OVERWRITE_FROM_CLOUD=1." + ) + + def _upload_local_to_cloud( + self, + force_overwrite_to_cloud: Optional[bool] = None, + ) -> Self: + """Uploads cache file at self._local to the cloud""" + # We should never try to be syncing entire directories; we should only + # cache and upload individual files. + if self._local.is_dir(): + raise ValueError("Only individual files can be uploaded to the cloud") + + uploaded = self._upload_file_to_cloud( + self._local, force_overwrite_to_cloud=force_overwrite_to_cloud + ) + + # force cache time to match cloud times + stats = self.stat() + os.utime(self._local, times=(stats.st_mtime, stats.st_mtime)) + + # reset dirty and handle now that this is uploaded + self._dirty = False + self._handle = None + + return uploaded + + def _upload_file_to_cloud( + self, + local_path: Path, + force_overwrite_to_cloud: Optional[bool] = None, + ) -> Self: + """Uploads file at `local_path` to the cloud if there is not a newer file + already there. + """ + if force_overwrite_to_cloud is None: + force_overwrite_to_cloud = os.environ.get( + "CLOUDPATHLIB_FORCE_OVERWRITE_TO_CLOUD", "False" + ).lower() in ["1", "true"] + + if force_overwrite_to_cloud: + # If we are overwriting no need to perform any checks, so we can save time + self.client._upload_file( + local_path, + self, + ) + return self + + try: + stats = self.stat() + except NoStatError: + stats = None + + # if cloud does not exist or local is newer, do the upload + if not stats or (local_path.stat().st_mtime > stats.st_mtime): + self.client._upload_file( + local_path, + self, + ) + + return self + + # cloud is newer and we are not overwriting + raise OverwriteNewerCloudError( + f"Local file ({self._local}) for cloud path ({self}) is newer in the cloud disk, but " + f"is being requested to be uploaded to the cloud. Either (1) redownload changes from the cloud or " + f"(2) pass `force_overwrite_to_cloud=True` to " + f"overwrite; or set env var CLOUDPATHLIB_FORCE_OVERWRITE_TO_CLOUD=1." + ) + + # =========== pydantic integration special methods =============== + @classmethod + def __get_pydantic_core_schema__(cls, _source_type: Any, _handler): + """Pydantic special method. See + https://docs.pydantic.dev/2.0/usage/types/custom/""" + try: + from pydantic_core import core_schema + + return core_schema.no_info_after_validator_function( + cls.validate, + core_schema.any_schema(), + ) + except ImportError: + return None + + @classmethod + def validate(cls, v: str) -> Self: + """Used as a Pydantic validator. See + https://docs.pydantic.dev/2.0/usage/types/custom/""" + return cls(v) + + @classmethod + def __get_validators__(cls) -> Generator[Callable[[Any], Self], None, None]: + """Pydantic special method. See + https://pydantic-docs.helpmanual.io/usage/types/#custom-data-types""" + yield cls._validate + + @classmethod + def _validate(cls, value: Any) -> Self: + """Used as a Pydantic validator. See + https://pydantic-docs.helpmanual.io/usage/types/#custom-data-types""" + return cls(value) + + +# The function resolve is not available on Pure paths because it removes relative +# paths and symlinks. We _just_ want the relative path resolution for +# cloud paths, so the other logic is removed. Also, we can assume that +# cloud paths are absolute. +# +# Based on resolve from pathlib: +# https://github.com/python/cpython/blob/3.8/Lib/pathlib.py#L316-L359 +def _resolve(path: PurePosixPath) -> str: + sep = "/" + + # rebuild path from parts + newpath = "" + for name in str(path).split(sep): + if not name or name == ".": + # current dir, nothing to add + continue + if name == "..": + # parent dir, drop right-most part + newpath, _, _ = newpath.rpartition(sep) + continue + newpath = newpath + sep + name + + return newpath or sep + + +# These objects are used to wrap CloudPaths in a context where we can use +# the python pathlib implementations for `glob` and `rglob`, which depend +# on the Selector created by the `_make_selector` method being passed +# an object like the below when `select_from` is called. We implement these methods +# in a simple wrapper to use the same glob recursion and pattern logic without +# rolling our own. +# +# Designed to be compatible when used by these selector implementations from pathlib: +# https://github.com/python/cpython/blob/3.10/Lib/pathlib.py#L385-L500 +class _CloudPathSelectableAccessor: + def __init__(self, scandir_func: Callable) -> None: + self.scandir = scandir_func + + +class _CloudPathSelectable: + def __init__( + self, + name: str, + parents: List[str], + children: Any, # Nested dictionaries as tree + exists: bool = True, + ) -> None: + self._name = name + self._all_children = children + self._parents = parents + self._exists = exists + + self._accessor = _CloudPathSelectableAccessor(self.scandir) + + def __repr__(self) -> str: + return "/".join(self._parents + [self.name]) + + def is_dir(self, follow_symlinks: bool = False) -> bool: + return self._all_children is not None + + def exists(self) -> bool: + return self._exists + + def is_symlink(self) -> bool: + return False + + @property + def name(self) -> str: + return self._name + + def _make_child_relpath(self, part): + # pathlib internals shortcut; makes a relative path, even if it doesn't actually exist + return _CloudPathSelectable( + part, + self._parents + [self.name], + self._all_children.get(part, None), + exists=part in self._all_children, + ) + + @staticmethod + @contextmanager + def scandir( + root: "_CloudPathSelectable", + ) -> Generator[Generator["_CloudPathSelectable", None, None], None, None]: + yield ( + _CloudPathSelectable(child, root._parents + [root._name], grand_children) + for child, grand_children in root._all_children.items() + ) + + _scandir = scandir # Py 3.11 compatibility + + def walk(self): + # split into dirs and files + dirs_files = defaultdict(list) + with self.scandir(self) as items: + for child in items: + dirs_files[child.is_dir()].append(child) + + # top-down, so yield self before recursive call + yield self, [f.name for f in dirs_files[True]], [f.name for f in dirs_files[False]] + + for child_dir in dirs_files[True]: + yield from child_dir.walk() diff --git a/TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib/enums.py b/TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib/enums.py new file mode 100644 index 0000000000000000000000000000000000000000..55260c176b2bd630901e625f716f50ae7139ff3c --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib/enums.py @@ -0,0 +1,44 @@ +from enum import Enum +import os +from typing import Optional + + +class FileCacheMode(str, Enum): + """Enumeration of the modes available for for the cloudpathlib file cache. + + Attributes: + persistent (str): Cache is not removed by `cloudpathlib`. + tmp_dir (str): Cache is stored in a + [`TemporaryDirectory`](https://docs.python.org/3/library/tempfile.html#tempfile.TemporaryDirectory) + which is removed when the Client object is garbage collected (or by the OS at some point if not). + cloudpath_object (str): Cache for a `CloudPath` object is removed when `__del__` for that object is + called by Python garbage collection. + close_file (str): Cache for a `CloudPath` file is removed as soon as the file is closed. Note: you must + use `CloudPath.open` whenever opening the file for this method to function. + + Modes can be set by passing them to the Client or by setting the `CLOUDPATHLIB_FILE_CACHE_MODE` + environment variable. + + For more detail, see the [caching documentation page](../../caching). + """ + + persistent = "persistent" # cache stays as long as dir on OS does + tmp_dir = "tmp_dir" # DEFAULT: handled by deleting client, Python, or OS (usually on machine restart) + cloudpath_object = "cloudpath_object" # __del__ called on the CloudPath object + close_file = "close_file" # cache is cleared when file is closed + + @classmethod + def from_environment(cls) -> Optional["FileCacheMode"]: + """Parses the environment variable `CLOUDPATHLIB_FILE_CACHE_MODE` into + an instance of this Enum. + + Returns: + FileCacheMode enum value if the env var is defined, else None. + """ + + env_string = os.environ.get("CLOUDPATHLIB_FILE_CACHE_MODE", "").lower() + + if not env_string: + return None + else: + return cls(env_string) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib/exceptions.py b/TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..a9f2ffb439a80b00c9f508e441a6437753135726 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib/exceptions.py @@ -0,0 +1,87 @@ +"""This module contains all custom exceptions in the `cloudpathlib` library. All exceptions +subclass the [`CloudPathException` base exception][cloudpathlib.exceptions.CloudPathException] to +facilitate catching any exception from this library. +""" + + +class CloudPathException(Exception): + """Base exception for all cloudpathlib custom exceptions.""" + + +class AnyPathTypeError(CloudPathException, TypeError): + pass + + +class ClientMismatchError(CloudPathException, ValueError): + pass + + +class CloudPathFileExistsError(CloudPathException, FileExistsError): + pass + + +class CloudPathNotExistsError(CloudPathException): + pass + + +class CloudPathFileNotFoundError(CloudPathException, FileNotFoundError): + pass + + +class CloudPathIsADirectoryError(CloudPathException, IsADirectoryError): + pass + + +class CloudPathNotADirectoryError(CloudPathException, NotADirectoryError): + pass + + +class CloudPathNotImplementedError(CloudPathException, NotImplementedError): + pass + + +class DirectoryNotEmptyError(CloudPathException): + pass + + +class IncompleteImplementationError(CloudPathException, NotImplementedError): + pass + + +class InvalidPrefixError(CloudPathException, ValueError): + pass + + +class InvalidConfigurationException(CloudPathException, ValueError): + pass + + +class MissingCredentialsError(CloudPathException): + pass + + +class MissingDependenciesError(CloudPathException, ModuleNotFoundError): + pass + + +class NoStatError(CloudPathException): + """Used if stats cannot be retrieved; e.g., file does not exist + or for some backends path is a directory (which doesn't have + stats available). + """ + + +class OverwriteDirtyFileError(CloudPathException): + pass + + +class OverwriteNewerCloudError(CloudPathException): + pass + + +class OverwriteNewerLocalError(CloudPathException): + pass + + +class InvalidGlobArgumentsError(CloudPathException): + pass diff --git a/TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib/patches.py b/TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib/patches.py new file mode 100644 index 0000000000000000000000000000000000000000..dafce8696771c89de063b714589930862648ad83 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib/patches.py @@ -0,0 +1,388 @@ +import builtins +import glob +import os +import os.path + +from cloudpathlib.exceptions import InvalidGlobArgumentsError + +from .cloudpath import CloudPath + + +def _check_first_arg(*args, **kwargs): + return isinstance(args[0], CloudPath) + + +def _check_first_arg_first_index(*args, **kwargs): + return isinstance(args[0][0], CloudPath) + + +def _check_first_arg_or_root_dir(*args, **kwargs): + return isinstance(args[0], CloudPath) or isinstance(kwargs.get("root_dir", None), CloudPath) + + +def _patch_factory(original_version, cpl_version, cpl_check=_check_first_arg): + _original = original_version + + def _patched_version(*args, **kwargs): + if cpl_check(*args, **kwargs): + return cpl_version(*args, **kwargs) + else: + return _original(*args, **kwargs) + + original_version = _patched_version + return _patched_version + + +class _OpenPatch: + def __init__(self, original_open=None): + if original_open is None: + original_open = builtins.open + + self._orig_open = original_open + self._orig_fspath = CloudPath.__fspath__ + self.patched = _patch_factory( + original_open, + CloudPath.open, + ) + + # patch immediately so a plain call works + builtins.open = self.patched + CloudPath.__fspath__ = lambda x: x + + def __enter__(self): + return builtins.open + + def __exit__(self, exc_type, exc_value, traceback): + builtins.open = self._orig_open + CloudPath.__fspath__ = self._orig_fspath + + +def patch_open(original_open=None): + return _OpenPatch(original_open) + + +def _cloudpath_fspath(path): + return path # no op, since methods should all handle cloudpaths when patched + + +def _cloudpath_os_listdir(path="."): + return list(path.iterdir()) + + +def _cloudpath_lstat(path, *, dir_fd=None): + return path.stat() + + +def _cloudpath_mkdir(path, *, dir_fd=None): + return path.mkdir() + + +def _cloudpath_os_makedirs(name, mode=0o777, exist_ok=False): + return CloudPath.mkdir(name, parents=True, exist_ok=exist_ok) + + +def _cloudpath_os_remove(path, *, dir_fd=None): + return path.unlink(missing_ok=False) # os.remove raises if missing + + +def _cloudpath_os_removedirs(name): + for d in name.parents: + d.rmdir() + + +def _cloudpath_os_rename(src, dst, *, src_dir_fd=None, dst_dir_fd=None): + return src.rename(dst) + + +def _cloudpath_os_renames(old, new): + old.rename(new) # move file + _cloudpath_os_removedirs(old) # remove previous directories if empty + + +def _cloudpath_os_replace(src, dst, *, src_dir_fd=None, dst_dir_fd=None): + return src.rename(dst) + + +def _cloudpath_os_rmdir(path, *, dir_fd=None): + return path.rmdir() + + +def _cloudpath_os_scandir(path="."): + return path.iterdir() + + +def _cloudpath_os_stat(path, *, dir_fd=None, follow_symlinks=True): + return path.stat() + + +def _cloudpath_os_unlink(path, *, dir_fd=None): + return path.unlink() + + +def _cloudpath_os_walk(top, topdown=True, onerror=None, followlinks=False): + # pathlib.Path.walk returns dirs and files as string, not Path objects + # we follow the same convention, but since these could get used downstream, + # this method may need to be changed to return absolute CloudPath objects + # if it becomes a compatibility problem with major downstream libraries + yield from top.walk(top_down=topdown, on_error=onerror, follow_symlinks=followlinks) + + +def _cloudpath_os_path_basename(path): + return path.name + + +def __common(parts): + i = 0 + + try: + while all(item[i] == parts[0][i] for item in parts[1:]): + i += 1 + except IndexError: + pass + + return parts[0][:i] + + +def _cloudpath_os_path_commonpath(paths): + common = __common([p.parts for p in paths]) + return paths[0].client.CloudPath(*common) + + +def _cloudpath_os_path_commonprefix(list): + common = __common([str(p) for p in list]) + return common + + +def _cloudpath_os_path_dirname(path): + return path.parent + + +def _cloudpath_os_path_getatime(path): + return (path.stat().st_atime,) + + +def _cloudpath_os_path_getmtime(path): + return (path.stat().st_mtime,) + + +def _cloudpath_os_path_getctime(path): + return (path.stat().st_ctime,) + + +def _cloudpath_os_path_getsize(path): + return (path.stat().st_size,) + + +def _cloudpath_os_path_join(path, *paths): + for p in paths: + path /= p + return path + + +def _cloudpath_os_path_split(path): + return path.parent, path.name + + +def _cloudpath_os_path_splitext(path): + return str(path)[: -len(path.suffix)], path.suffix + + +class _OSPatch: + def __init__(self): + os_level = [ + ("fspath", os.fspath, _cloudpath_fspath), + ("listdir", os.listdir, _cloudpath_os_listdir), + ("lstat", os.lstat, _cloudpath_lstat), + ("mkdir", os.mkdir, _cloudpath_mkdir), + ("makedirs", os.makedirs, _cloudpath_os_makedirs), + ("remove", os.remove, _cloudpath_os_remove), + ("removedirs", os.removedirs, _cloudpath_os_removedirs), + ("rename", os.rename, _cloudpath_os_rename), + ("renames", os.renames, _cloudpath_os_renames), + ("replace", os.replace, _cloudpath_os_replace), + ("rmdir", os.rmdir, _cloudpath_os_rmdir), + ("scandir", os.scandir, _cloudpath_os_scandir), + ("stat", os.stat, _cloudpath_os_stat), + ("unlink", os.unlink, _cloudpath_os_unlink), + ("walk", os.walk, _cloudpath_os_walk), + ] + + self.os_originals = {} + + for name, original, cloud in os_level: + self.os_originals[name] = original + patched = _patch_factory(original, cloud) + setattr(os, name, patched) + + os_path_level = [ + ("basename", os.path.basename, _cloudpath_os_path_basename, _check_first_arg), + ( + "commonpath", + os.path.commonpath, + _cloudpath_os_path_commonpath, + _check_first_arg_first_index, + ), + ( + "commonprefix", + os.path.commonprefix, + _cloudpath_os_path_commonprefix, + _check_first_arg_first_index, + ), + ("dirname", os.path.dirname, _cloudpath_os_path_dirname, _check_first_arg), + ("exists", os.path.exists, CloudPath.exists, _check_first_arg), + ("getatime", os.path.getatime, _cloudpath_os_path_getatime, _check_first_arg), + ("getmtime", os.path.getmtime, _cloudpath_os_path_getmtime, _check_first_arg), + ("getctime", os.path.getctime, _cloudpath_os_path_getctime, _check_first_arg), + ("getsize", os.path.getsize, _cloudpath_os_path_getsize, _check_first_arg), + ("isfile", os.path.isfile, CloudPath.is_file, _check_first_arg), + ("isdir", os.path.isdir, CloudPath.is_dir, _check_first_arg), + ("join", os.path.join, _cloudpath_os_path_join, _check_first_arg), + ("split", os.path.split, _cloudpath_os_path_split, _check_first_arg), + ("splitext", os.path.splitext, _cloudpath_os_path_splitext, _check_first_arg), + ] + + self.os_path_originals = {} + + for name, original, cloud, check in os_path_level: + self.os_path_originals[name] = original + patched = _patch_factory(original, cloud, cpl_check=check) + setattr(os.path, name, patched) + + def __enter__(self): + return + + def __exit__(self, exc_type, exc_value, traceback): + for name, original in self.os_originals.items(): + setattr(os, name, original) + + for name, original in self.os_path_originals.items(): + setattr(os.path, name, original) + + +def patch_os_functions(): + return _OSPatch() + + +def _get_root_dir_pattern_from_pathname(pathname): + # get first wildcard + for i, part in enumerate(pathname.parts): + if "*" in part or "?" in part or "[" in part: + root_parts = pathname.parts[:i] + pattern_parts = pathname.parts[i:] + break + else: + # No wildcards found, treat the entire path as root_dir with empty pattern + root_parts = pathname.parts + pattern_parts = [] + + root_dir = pathname._new_cloudpath(*root_parts) + + # Handle empty pattern case - use "*" to match all files in directory + if not pattern_parts: + pattern = "*" + else: + pattern = "/".join(pattern_parts) + + return root_dir, pattern + + +def _cloudpath_glob_iglob( + pathname, *, root_dir=None, dir_fd=None, recursive=False, include_hidden=False +): + # if both are cloudpath, root_dir and pathname must share a parent, otherwise we don't know + # where to start the pattern + if isinstance(pathname, CloudPath) and isinstance(root_dir, CloudPath): + if not pathname.is_relative_to(root_dir): + raise InvalidGlobArgumentsError( + f"If both are CloudPaths, root_dir ({root_dir}) must be a parent of pathname ({pathname})." + ) + + else: + pattern = pathname.relative_to(root_dir) + + elif isinstance(pathname, CloudPath): + if root_dir is not None: + raise InvalidGlobArgumentsError( + "If pathname is a CloudPath, root_dir must also be a CloudPath or None." + ) + + root_dir, pattern = _get_root_dir_pattern_from_pathname(pathname) + + elif isinstance(root_dir, CloudPath): + pattern = pathname + + else: + raise InvalidGlobArgumentsError( + "At least one of pathname or root_dir must be a CloudPath." + ) + + # CloudPath automatically detects recursive patterns from ** or / in the pattern + # No need to pass recursive parameter + return root_dir.glob(pattern) + + +def _cloudpath_glob_glob( + pathname, *, root_dir=None, dir_fd=None, recursive=False, include_hidden=False +): + return list( + _cloudpath_glob_iglob( + pathname, + root_dir=root_dir, + dir_fd=dir_fd, + recursive=recursive, + include_hidden=include_hidden, + ) + ) + + +class _GlobPatch: + def __init__(self): + self.original_glob = glob.glob + self.original_iglob = glob.iglob + + self.patched_glob = _patch_factory( + self.original_glob, + _cloudpath_glob_glob, + cpl_check=_check_first_arg_or_root_dir, + ) + + self.patched_iglob = _patch_factory( + self.original_iglob, + _cloudpath_glob_iglob, + cpl_check=_check_first_arg_or_root_dir, + ) + + def __enter__(self): + glob.glob = self.patched_glob + glob.iglob = self.patched_iglob + return + + def __exit__(self, exc_type, exc_value, traceback): + glob.glob = self.original_glob + glob.iglob = self.original_iglob + + +def patch_glob(): + return _GlobPatch() + + +class _PatchAllBuiltins: + def __init__(self): + self.patch_open = patch_open() + self.patch_os_functions = patch_os_functions() + self.patch_glob = patch_glob() + + def __enter__(self): + self.patch_open.__enter__() + self.patch_os_functions.__enter__() + self.patch_glob.__enter__() + return + + def __exit__(self, exc_type, exc_value, traceback): + self.patch_open.__exit__(exc_type, exc_value, traceback) + self.patch_os_functions.__exit__(exc_type, exc_value, traceback) + self.patch_glob.__exit__(exc_type, exc_value, traceback) + + +def patch_all_builtins(): + return _PatchAllBuiltins() diff --git a/TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib/py.typed b/TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib/url_utils.py b/TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib/url_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..1b3f1959eeb5fd40244f077b6436a4505d2d3b31 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib/url_utils.py @@ -0,0 +1,31 @@ +from pathlib import PureWindowsPath, Path +from urllib.request import url2pathname +from urllib.parse import urlparse, unquote + + +def path_from_fileurl(urlstr, **kwargs): + """ + Take a file:// url and return a Path. + + Adapted from: + https://github.com/AcademySoftwareFoundation/OpenTimelineIO/blob/4c17494dee2e515aedc8623741556fae3e4afe72/src/py-opentimelineio/opentimelineio/url_utils.py#L43-L72 + """ + # explicitly unquote first in case drive colon is url encoded + unquoted = unquote(urlstr) + + # Parse provided URL + parsed_result = urlparse(unquoted) + + # Convert the parsed URL to a path + filepath = Path(url2pathname(parsed_result.path), **kwargs) + + # If the network location is a window drive, reassemble the path + if PureWindowsPath(parsed_result.netloc).drive: + filepath = Path(parsed_result.netloc + parsed_result.path, **kwargs) + + # Otherwise check if the specified index is a windows drive, then offset the path + elif len(filepath.parts) > 1 and PureWindowsPath(filepath.parts[1]).drive: + # Remove leading "/" if/when `request.url2pathname` yields "/S:/path/file.ext" + filepath = Path(*filepath.parts[1:], **kwargs) + + return filepath diff --git a/TTS/Kokoro/.venv/Lib/site-packages/colorama-0.4.6.dist-info/INSTALLER b/TTS/Kokoro/.venv/Lib/site-packages/colorama-0.4.6.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/colorama-0.4.6.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/TTS/Kokoro/.venv/Lib/site-packages/colorama-0.4.6.dist-info/METADATA b/TTS/Kokoro/.venv/Lib/site-packages/colorama-0.4.6.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..a1b5c57543005b310ac2efb02243a6b6ab6d8932 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/colorama-0.4.6.dist-info/METADATA @@ -0,0 +1,441 @@ +Metadata-Version: 2.1 +Name: colorama +Version: 0.4.6 +Summary: Cross-platform colored terminal text. +Project-URL: Homepage, https://github.com/tartley/colorama +Author-email: Jonathan Hartley +License-File: LICENSE.txt +Keywords: ansi,color,colour,crossplatform,terminal,text,windows,xplatform +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Console +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: BSD License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 2 +Classifier: Programming Language :: Python :: 2.7 +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Terminals +Requires-Python: !=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,>=2.7 +Description-Content-Type: text/x-rst + +.. image:: https://img.shields.io/pypi/v/colorama.svg + :target: https://pypi.org/project/colorama/ + :alt: Latest Version + +.. image:: https://img.shields.io/pypi/pyversions/colorama.svg + :target: https://pypi.org/project/colorama/ + :alt: Supported Python versions + +.. image:: https://github.com/tartley/colorama/actions/workflows/test.yml/badge.svg + :target: https://github.com/tartley/colorama/actions/workflows/test.yml + :alt: Build Status + +Colorama +======== + +Makes ANSI escape character sequences (for producing colored terminal text and +cursor positioning) work under MS Windows. + +.. |donate| image:: https://www.paypalobjects.com/en_US/i/btn/btn_donate_SM.gif + :target: https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=2MZ9D2GMLYCUJ&item_name=Colorama¤cy_code=USD + :alt: Donate with Paypal + +`PyPI for releases `_ | +`Github for source `_ | +`Colorama for enterprise on Tidelift `_ + +If you find Colorama useful, please |donate| to the authors. Thank you! + +Installation +------------ + +Tested on CPython 2.7, 3.7, 3.8, 3.9 and 3.10 and Pypy 2.7 and 3.8. + +No requirements other than the standard library. + +.. code-block:: bash + + pip install colorama + # or + conda install -c anaconda colorama + +Description +----------- + +ANSI escape character sequences have long been used to produce colored terminal +text and cursor positioning on Unix and Macs. Colorama makes this work on +Windows, too, by wrapping ``stdout``, stripping ANSI sequences it finds (which +would appear as gobbledygook in the output), and converting them into the +appropriate win32 calls to modify the state of the terminal. On other platforms, +Colorama does nothing. + +This has the upshot of providing a simple cross-platform API for printing +colored terminal text from Python, and has the happy side-effect that existing +applications or libraries which use ANSI sequences to produce colored output on +Linux or Macs can now also work on Windows, simply by calling +``colorama.just_fix_windows_console()`` (since v0.4.6) or ``colorama.init()`` +(all versions, but may have other side-effects – see below). + +An alternative approach is to install ``ansi.sys`` on Windows machines, which +provides the same behaviour for all applications running in terminals. Colorama +is intended for situations where that isn't easy (e.g., maybe your app doesn't +have an installer.) + +Demo scripts in the source code repository print some colored text using +ANSI sequences. Compare their output under Gnome-terminal's built in ANSI +handling, versus on Windows Command-Prompt using Colorama: + +.. image:: https://github.com/tartley/colorama/raw/master/screenshots/ubuntu-demo.png + :width: 661 + :height: 357 + :alt: ANSI sequences on Ubuntu under gnome-terminal. + +.. image:: https://github.com/tartley/colorama/raw/master/screenshots/windows-demo.png + :width: 668 + :height: 325 + :alt: Same ANSI sequences on Windows, using Colorama. + +These screenshots show that, on Windows, Colorama does not support ANSI 'dim +text'; it looks the same as 'normal text'. + +Usage +----- + +Initialisation +.............. + +If the only thing you want from Colorama is to get ANSI escapes to work on +Windows, then run: + +.. code-block:: python + + from colorama import just_fix_windows_console + just_fix_windows_console() + +If you're on a recent version of Windows 10 or better, and your stdout/stderr +are pointing to a Windows console, then this will flip the magic configuration +switch to enable Windows' built-in ANSI support. + +If you're on an older version of Windows, and your stdout/stderr are pointing to +a Windows console, then this will wrap ``sys.stdout`` and/or ``sys.stderr`` in a +magic file object that intercepts ANSI escape sequences and issues the +appropriate Win32 calls to emulate them. + +In all other circumstances, it does nothing whatsoever. Basically the idea is +that this makes Windows act like Unix with respect to ANSI escape handling. + +It's safe to call this function multiple times. It's safe to call this function +on non-Windows platforms, but it won't do anything. It's safe to call this +function when one or both of your stdout/stderr are redirected to a file – it +won't do anything to those streams. + +Alternatively, you can use the older interface with more features (but also more +potential footguns): + +.. code-block:: python + + from colorama import init + init() + +This does the same thing as ``just_fix_windows_console``, except for the +following differences: + +- It's not safe to call ``init`` multiple times; you can end up with multiple + layers of wrapping and broken ANSI support. + +- Colorama will apply a heuristic to guess whether stdout/stderr support ANSI, + and if it thinks they don't, then it will wrap ``sys.stdout`` and + ``sys.stderr`` in a magic file object that strips out ANSI escape sequences + before printing them. This happens on all platforms, and can be convenient if + you want to write your code to emit ANSI escape sequences unconditionally, and + let Colorama decide whether they should actually be output. But note that + Colorama's heuristic is not particularly clever. + +- ``init`` also accepts explicit keyword args to enable/disable various + functionality – see below. + +To stop using Colorama before your program exits, simply call ``deinit()``. +This will restore ``stdout`` and ``stderr`` to their original values, so that +Colorama is disabled. To resume using Colorama again, call ``reinit()``; it is +cheaper than calling ``init()`` again (but does the same thing). + +Most users should depend on ``colorama >= 0.4.6``, and use +``just_fix_windows_console``. The old ``init`` interface will be supported +indefinitely for backwards compatibility, but we don't plan to fix any issues +with it, also for backwards compatibility. + +Colored Output +.............. + +Cross-platform printing of colored text can then be done using Colorama's +constant shorthand for ANSI escape sequences. These are deliberately +rudimentary, see below. + +.. code-block:: python + + from colorama import Fore, Back, Style + print(Fore.RED + 'some red text') + print(Back.GREEN + 'and with a green background') + print(Style.DIM + 'and in dim text') + print(Style.RESET_ALL) + print('back to normal now') + +...or simply by manually printing ANSI sequences from your own code: + +.. code-block:: python + + print('\033[31m' + 'some red text') + print('\033[39m') # and reset to default color + +...or, Colorama can be used in conjunction with existing ANSI libraries +such as the venerable `Termcolor `_ +the fabulous `Blessings `_, +or the incredible `_Rich `_. + +If you wish Colorama's Fore, Back and Style constants were more capable, +then consider using one of the above highly capable libraries to generate +colors, etc, and use Colorama just for its primary purpose: to convert +those ANSI sequences to also work on Windows: + +SIMILARLY, do not send PRs adding the generation of new ANSI types to Colorama. +We are only interested in converting ANSI codes to win32 API calls, not +shortcuts like the above to generate ANSI characters. + +.. code-block:: python + + from colorama import just_fix_windows_console + from termcolor import colored + + # use Colorama to make Termcolor work on Windows too + just_fix_windows_console() + + # then use Termcolor for all colored text output + print(colored('Hello, World!', 'green', 'on_red')) + +Available formatting constants are:: + + Fore: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET. + Back: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET. + Style: DIM, NORMAL, BRIGHT, RESET_ALL + +``Style.RESET_ALL`` resets foreground, background, and brightness. Colorama will +perform this reset automatically on program exit. + +These are fairly well supported, but not part of the standard:: + + Fore: LIGHTBLACK_EX, LIGHTRED_EX, LIGHTGREEN_EX, LIGHTYELLOW_EX, LIGHTBLUE_EX, LIGHTMAGENTA_EX, LIGHTCYAN_EX, LIGHTWHITE_EX + Back: LIGHTBLACK_EX, LIGHTRED_EX, LIGHTGREEN_EX, LIGHTYELLOW_EX, LIGHTBLUE_EX, LIGHTMAGENTA_EX, LIGHTCYAN_EX, LIGHTWHITE_EX + +Cursor Positioning +.................. + +ANSI codes to reposition the cursor are supported. See ``demos/demo06.py`` for +an example of how to generate them. + +Init Keyword Args +................. + +``init()`` accepts some ``**kwargs`` to override default behaviour. + +init(autoreset=False): + If you find yourself repeatedly sending reset sequences to turn off color + changes at the end of every print, then ``init(autoreset=True)`` will + automate that: + + .. code-block:: python + + from colorama import init + init(autoreset=True) + print(Fore.RED + 'some red text') + print('automatically back to default color again') + +init(strip=None): + Pass ``True`` or ``False`` to override whether ANSI codes should be + stripped from the output. The default behaviour is to strip if on Windows + or if output is redirected (not a tty). + +init(convert=None): + Pass ``True`` or ``False`` to override whether to convert ANSI codes in the + output into win32 calls. The default behaviour is to convert if on Windows + and output is to a tty (terminal). + +init(wrap=True): + On Windows, Colorama works by replacing ``sys.stdout`` and ``sys.stderr`` + with proxy objects, which override the ``.write()`` method to do their work. + If this wrapping causes you problems, then this can be disabled by passing + ``init(wrap=False)``. The default behaviour is to wrap if ``autoreset`` or + ``strip`` or ``convert`` are True. + + When wrapping is disabled, colored printing on non-Windows platforms will + continue to work as normal. To do cross-platform colored output, you can + use Colorama's ``AnsiToWin32`` proxy directly: + + .. code-block:: python + + import sys + from colorama import init, AnsiToWin32 + init(wrap=False) + stream = AnsiToWin32(sys.stderr).stream + + # Python 2 + print >>stream, Fore.BLUE + 'blue text on stderr' + + # Python 3 + print(Fore.BLUE + 'blue text on stderr', file=stream) + +Recognised ANSI Sequences +......................... + +ANSI sequences generally take the form:: + + ESC [ ; ... + +Where ```` is an integer, and ```` is a single letter. Zero or +more params are passed to a ````. If no params are passed, it is +generally synonymous with passing a single zero. No spaces exist in the +sequence; they have been inserted here simply to read more easily. + +The only ANSI sequences that Colorama converts into win32 calls are:: + + ESC [ 0 m # reset all (colors and brightness) + ESC [ 1 m # bright + ESC [ 2 m # dim (looks same as normal brightness) + ESC [ 22 m # normal brightness + + # FOREGROUND: + ESC [ 30 m # black + ESC [ 31 m # red + ESC [ 32 m # green + ESC [ 33 m # yellow + ESC [ 34 m # blue + ESC [ 35 m # magenta + ESC [ 36 m # cyan + ESC [ 37 m # white + ESC [ 39 m # reset + + # BACKGROUND + ESC [ 40 m # black + ESC [ 41 m # red + ESC [ 42 m # green + ESC [ 43 m # yellow + ESC [ 44 m # blue + ESC [ 45 m # magenta + ESC [ 46 m # cyan + ESC [ 47 m # white + ESC [ 49 m # reset + + # cursor positioning + ESC [ y;x H # position cursor at x across, y down + ESC [ y;x f # position cursor at x across, y down + ESC [ n A # move cursor n lines up + ESC [ n B # move cursor n lines down + ESC [ n C # move cursor n characters forward + ESC [ n D # move cursor n characters backward + + # clear the screen + ESC [ mode J # clear the screen + + # clear the line + ESC [ mode K # clear the line + +Multiple numeric params to the ``'m'`` command can be combined into a single +sequence:: + + ESC [ 36 ; 45 ; 1 m # bright cyan text on magenta background + +All other ANSI sequences of the form ``ESC [ ; ... `` +are silently stripped from the output on Windows. + +Any other form of ANSI sequence, such as single-character codes or alternative +initial characters, are not recognised or stripped. It would be cool to add +them though. Let me know if it would be useful for you, via the Issues on +GitHub. + +Status & Known Problems +----------------------- + +I've personally only tested it on Windows XP (CMD, Console2), Ubuntu +(gnome-terminal, xterm), and OS X. + +Some valid ANSI sequences aren't recognised. + +If you're hacking on the code, see `README-hacking.md`_. ESPECIALLY, see the +explanation there of why we do not want PRs that allow Colorama to generate new +types of ANSI codes. + +See outstanding issues and wish-list: +https://github.com/tartley/colorama/issues + +If anything doesn't work for you, or doesn't do what you expected or hoped for, +I'd love to hear about it on that issues list, would be delighted by patches, +and would be happy to grant commit access to anyone who submits a working patch +or two. + +.. _README-hacking.md: README-hacking.md + +License +------- + +Copyright Jonathan Hartley & Arnon Yaari, 2013-2020. BSD 3-Clause license; see +LICENSE file. + +Professional support +-------------------- + +.. |tideliftlogo| image:: https://cdn2.hubspot.net/hubfs/4008838/website/logos/logos_for_download/Tidelift_primary-shorthand-logo.png + :alt: Tidelift + :target: https://tidelift.com/subscription/pkg/pypi-colorama?utm_source=pypi-colorama&utm_medium=referral&utm_campaign=readme + +.. list-table:: + :widths: 10 100 + + * - |tideliftlogo| + - Professional support for colorama is available as part of the + `Tidelift Subscription`_. + Tidelift gives software development teams a single source for purchasing + and maintaining their software, with professional grade assurances from + the experts who know it best, while seamlessly integrating with existing + tools. + +.. _Tidelift Subscription: https://tidelift.com/subscription/pkg/pypi-colorama?utm_source=pypi-colorama&utm_medium=referral&utm_campaign=readme + +Thanks +------ + +See the CHANGELOG for more thanks! + +* Marc Schlaich (schlamar) for a ``setup.py`` fix for Python2.5. +* Marc Abramowitz, reported & fixed a crash on exit with closed ``stdout``, + providing a solution to issue #7's setuptools/distutils debate, + and other fixes. +* User 'eryksun', for guidance on correctly instantiating ``ctypes.windll``. +* Matthew McCormick for politely pointing out a longstanding crash on non-Win. +* Ben Hoyt, for a magnificent fix under 64-bit Windows. +* Jesse at Empty Square for submitting a fix for examples in the README. +* User 'jamessp', an observant documentation fix for cursor positioning. +* User 'vaal1239', Dave Mckee & Lackner Kristof for a tiny but much-needed Win7 + fix. +* Julien Stuyck, for wisely suggesting Python3 compatible updates to README. +* Daniel Griffith for multiple fabulous patches. +* Oscar Lesta for a valuable fix to stop ANSI chars being sent to non-tty + output. +* Roger Binns, for many suggestions, valuable feedback, & bug reports. +* Tim Golden for thought and much appreciated feedback on the initial idea. +* User 'Zearin' for updates to the README file. +* John Szakmeister for adding support for light colors +* Charles Merriam for adding documentation to demos +* Jurko for a fix on 64-bit Windows CPython2.5 w/o ctypes +* Florian Bruhin for a fix when stdout or stderr are None +* Thomas Weininger for fixing ValueError on Windows +* Remi Rampin for better Github integration and fixes to the README file +* Simeon Visser for closing a file handle using 'with' and updating classifiers + to include Python 3.3 and 3.4 +* Andy Neff for fixing RESET of LIGHT_EX colors. +* Jonathan Hartley for the initial idea and implementation. diff --git a/TTS/Kokoro/.venv/Lib/site-packages/colorama-0.4.6.dist-info/RECORD b/TTS/Kokoro/.venv/Lib/site-packages/colorama-0.4.6.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..496de2727d15000bdd9199c585cb2a8df9562ad5 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/colorama-0.4.6.dist-info/RECORD @@ -0,0 +1,31 @@ +colorama-0.4.6.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +colorama-0.4.6.dist-info/METADATA,sha256=e67SnrUMOym9sz_4TjF3vxvAV4T3aF7NyqRHHH3YEMw,17158 +colorama-0.4.6.dist-info/RECORD,, +colorama-0.4.6.dist-info/WHEEL,sha256=cdcF4Fbd0FPtw2EMIOwH-3rSOTUdTCeOSXRMD1iLUb8,105 +colorama-0.4.6.dist-info/licenses/LICENSE.txt,sha256=ysNcAmhuXQSlpxQL-zs25zrtSWZW6JEQLkKIhteTAxg,1491 +colorama/__init__.py,sha256=wePQA4U20tKgYARySLEC047ucNX-g8pRLpYBuiHlLb8,266 +colorama/__pycache__/__init__.cpython-312.pyc,, +colorama/__pycache__/ansi.cpython-312.pyc,, +colorama/__pycache__/ansitowin32.cpython-312.pyc,, +colorama/__pycache__/initialise.cpython-312.pyc,, +colorama/__pycache__/win32.cpython-312.pyc,, +colorama/__pycache__/winterm.cpython-312.pyc,, +colorama/ansi.py,sha256=Top4EeEuaQdBWdteKMEcGOTeKeF19Q-Wo_6_Cj5kOzQ,2522 +colorama/ansitowin32.py,sha256=vPNYa3OZbxjbuFyaVo0Tmhmy1FZ1lKMWCnT7odXpItk,11128 +colorama/initialise.py,sha256=-hIny86ClXo39ixh5iSCfUIa2f_h_bgKRDW7gqs-KLU,3325 +colorama/tests/__init__.py,sha256=MkgPAEzGQd-Rq0w0PZXSX2LadRWhUECcisJY8lSrm4Q,75 +colorama/tests/__pycache__/__init__.cpython-312.pyc,, +colorama/tests/__pycache__/ansi_test.cpython-312.pyc,, +colorama/tests/__pycache__/ansitowin32_test.cpython-312.pyc,, +colorama/tests/__pycache__/initialise_test.cpython-312.pyc,, +colorama/tests/__pycache__/isatty_test.cpython-312.pyc,, +colorama/tests/__pycache__/utils.cpython-312.pyc,, +colorama/tests/__pycache__/winterm_test.cpython-312.pyc,, +colorama/tests/ansi_test.py,sha256=FeViDrUINIZcr505PAxvU4AjXz1asEiALs9GXMhwRaE,2839 +colorama/tests/ansitowin32_test.py,sha256=RN7AIhMJ5EqDsYaCjVo-o4u8JzDD4ukJbmevWKS70rY,10678 +colorama/tests/initialise_test.py,sha256=BbPy-XfyHwJ6zKozuQOvNvQZzsx9vdb_0bYXn7hsBTc,6741 +colorama/tests/isatty_test.py,sha256=Pg26LRpv0yQDB5Ac-sxgVXG7hsA1NYvapFgApZfYzZg,1866 +colorama/tests/utils.py,sha256=1IIRylG39z5-dzq09R_ngufxyPZxgldNbrxKxUGwGKE,1079 +colorama/tests/winterm_test.py,sha256=qoWFPEjym5gm2RuMwpf3pOis3a5r_PJZFCzK254JL8A,3709 +colorama/win32.py,sha256=YQOKwMTwtGBbsY4dL5HYTvwTeP9wIQra5MvPNddpxZs,6181 +colorama/winterm.py,sha256=XCQFDHjPi6AHYNdZwy0tA02H-Jh48Jp-HvCjeLeLp3U,7134 diff --git a/TTS/Kokoro/.venv/Lib/site-packages/colorama-0.4.6.dist-info/WHEEL b/TTS/Kokoro/.venv/Lib/site-packages/colorama-0.4.6.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..d79189fda3251187de18c3998f23ae6fec11b20f --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/colorama-0.4.6.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.11.1 +Root-Is-Purelib: true +Tag: py2-none-any +Tag: py3-none-any diff --git a/TTS/Kokoro/.venv/Lib/site-packages/colorama/__init__.py b/TTS/Kokoro/.venv/Lib/site-packages/colorama/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..383101cdb38706c305449674044e9288b92b7d75 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/colorama/__init__.py @@ -0,0 +1,7 @@ +# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. +from .initialise import init, deinit, reinit, colorama_text, just_fix_windows_console +from .ansi import Fore, Back, Style, Cursor +from .ansitowin32 import AnsiToWin32 + +__version__ = '0.4.6' + diff --git a/TTS/Kokoro/.venv/Lib/site-packages/colorama/ansi.py b/TTS/Kokoro/.venv/Lib/site-packages/colorama/ansi.py new file mode 100644 index 0000000000000000000000000000000000000000..11ec695ff79627463a0282d25079527562de9e42 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/colorama/ansi.py @@ -0,0 +1,102 @@ +# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. +''' +This module generates ANSI character codes to printing colors to terminals. +See: http://en.wikipedia.org/wiki/ANSI_escape_code +''' + +CSI = '\033[' +OSC = '\033]' +BEL = '\a' + + +def code_to_chars(code): + return CSI + str(code) + 'm' + +def set_title(title): + return OSC + '2;' + title + BEL + +def clear_screen(mode=2): + return CSI + str(mode) + 'J' + +def clear_line(mode=2): + return CSI + str(mode) + 'K' + + +class AnsiCodes(object): + def __init__(self): + # the subclasses declare class attributes which are numbers. + # Upon instantiation we define instance attributes, which are the same + # as the class attributes but wrapped with the ANSI escape sequence + for name in dir(self): + if not name.startswith('_'): + value = getattr(self, name) + setattr(self, name, code_to_chars(value)) + + +class AnsiCursor(object): + def UP(self, n=1): + return CSI + str(n) + 'A' + def DOWN(self, n=1): + return CSI + str(n) + 'B' + def FORWARD(self, n=1): + return CSI + str(n) + 'C' + def BACK(self, n=1): + return CSI + str(n) + 'D' + def POS(self, x=1, y=1): + return CSI + str(y) + ';' + str(x) + 'H' + + +class AnsiFore(AnsiCodes): + BLACK = 30 + RED = 31 + GREEN = 32 + YELLOW = 33 + BLUE = 34 + MAGENTA = 35 + CYAN = 36 + WHITE = 37 + RESET = 39 + + # These are fairly well supported, but not part of the standard. + LIGHTBLACK_EX = 90 + LIGHTRED_EX = 91 + LIGHTGREEN_EX = 92 + LIGHTYELLOW_EX = 93 + LIGHTBLUE_EX = 94 + LIGHTMAGENTA_EX = 95 + LIGHTCYAN_EX = 96 + LIGHTWHITE_EX = 97 + + +class AnsiBack(AnsiCodes): + BLACK = 40 + RED = 41 + GREEN = 42 + YELLOW = 43 + BLUE = 44 + MAGENTA = 45 + CYAN = 46 + WHITE = 47 + RESET = 49 + + # These are fairly well supported, but not part of the standard. + LIGHTBLACK_EX = 100 + LIGHTRED_EX = 101 + LIGHTGREEN_EX = 102 + LIGHTYELLOW_EX = 103 + LIGHTBLUE_EX = 104 + LIGHTMAGENTA_EX = 105 + LIGHTCYAN_EX = 106 + LIGHTWHITE_EX = 107 + + +class AnsiStyle(AnsiCodes): + BRIGHT = 1 + DIM = 2 + NORMAL = 22 + RESET_ALL = 0 + +Fore = AnsiFore() +Back = AnsiBack() +Style = AnsiStyle() +Cursor = AnsiCursor() diff --git a/TTS/Kokoro/.venv/Lib/site-packages/colorama/ansitowin32.py b/TTS/Kokoro/.venv/Lib/site-packages/colorama/ansitowin32.py new file mode 100644 index 0000000000000000000000000000000000000000..abf209e60c7c4a9b1ae57452e36b383969848c2e --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/colorama/ansitowin32.py @@ -0,0 +1,277 @@ +# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. +import re +import sys +import os + +from .ansi import AnsiFore, AnsiBack, AnsiStyle, Style, BEL +from .winterm import enable_vt_processing, WinTerm, WinColor, WinStyle +from .win32 import windll, winapi_test + + +winterm = None +if windll is not None: + winterm = WinTerm() + + +class StreamWrapper(object): + ''' + Wraps a stream (such as stdout), acting as a transparent proxy for all + attribute access apart from method 'write()', which is delegated to our + Converter instance. + ''' + def __init__(self, wrapped, converter): + # double-underscore everything to prevent clashes with names of + # attributes on the wrapped stream object. + self.__wrapped = wrapped + self.__convertor = converter + + def __getattr__(self, name): + return getattr(self.__wrapped, name) + + def __enter__(self, *args, **kwargs): + # special method lookup bypasses __getattr__/__getattribute__, see + # https://stackoverflow.com/questions/12632894/why-doesnt-getattr-work-with-exit + # thus, contextlib magic methods are not proxied via __getattr__ + return self.__wrapped.__enter__(*args, **kwargs) + + def __exit__(self, *args, **kwargs): + return self.__wrapped.__exit__(*args, **kwargs) + + def __setstate__(self, state): + self.__dict__ = state + + def __getstate__(self): + return self.__dict__ + + def write(self, text): + self.__convertor.write(text) + + def isatty(self): + stream = self.__wrapped + if 'PYCHARM_HOSTED' in os.environ: + if stream is not None and (stream is sys.__stdout__ or stream is sys.__stderr__): + return True + try: + stream_isatty = stream.isatty + except AttributeError: + return False + else: + return stream_isatty() + + @property + def closed(self): + stream = self.__wrapped + try: + return stream.closed + # AttributeError in the case that the stream doesn't support being closed + # ValueError for the case that the stream has already been detached when atexit runs + except (AttributeError, ValueError): + return True + + +class AnsiToWin32(object): + ''' + Implements a 'write()' method which, on Windows, will strip ANSI character + sequences from the text, and if outputting to a tty, will convert them into + win32 function calls. + ''' + ANSI_CSI_RE = re.compile('\001?\033\\[((?:\\d|;)*)([a-zA-Z])\002?') # Control Sequence Introducer + ANSI_OSC_RE = re.compile('\001?\033\\]([^\a]*)(\a)\002?') # Operating System Command + + def __init__(self, wrapped, convert=None, strip=None, autoreset=False): + # The wrapped stream (normally sys.stdout or sys.stderr) + self.wrapped = wrapped + + # should we reset colors to defaults after every .write() + self.autoreset = autoreset + + # create the proxy wrapping our output stream + self.stream = StreamWrapper(wrapped, self) + + on_windows = os.name == 'nt' + # We test if the WinAPI works, because even if we are on Windows + # we may be using a terminal that doesn't support the WinAPI + # (e.g. Cygwin Terminal). In this case it's up to the terminal + # to support the ANSI codes. + conversion_supported = on_windows and winapi_test() + try: + fd = wrapped.fileno() + except Exception: + fd = -1 + system_has_native_ansi = not on_windows or enable_vt_processing(fd) + have_tty = not self.stream.closed and self.stream.isatty() + need_conversion = conversion_supported and not system_has_native_ansi + + # should we strip ANSI sequences from our output? + if strip is None: + strip = need_conversion or not have_tty + self.strip = strip + + # should we should convert ANSI sequences into win32 calls? + if convert is None: + convert = need_conversion and have_tty + self.convert = convert + + # dict of ansi codes to win32 functions and parameters + self.win32_calls = self.get_win32_calls() + + # are we wrapping stderr? + self.on_stderr = self.wrapped is sys.stderr + + def should_wrap(self): + ''' + True if this class is actually needed. If false, then the output + stream will not be affected, nor will win32 calls be issued, so + wrapping stdout is not actually required. This will generally be + False on non-Windows platforms, unless optional functionality like + autoreset has been requested using kwargs to init() + ''' + return self.convert or self.strip or self.autoreset + + def get_win32_calls(self): + if self.convert and winterm: + return { + AnsiStyle.RESET_ALL: (winterm.reset_all, ), + AnsiStyle.BRIGHT: (winterm.style, WinStyle.BRIGHT), + AnsiStyle.DIM: (winterm.style, WinStyle.NORMAL), + AnsiStyle.NORMAL: (winterm.style, WinStyle.NORMAL), + AnsiFore.BLACK: (winterm.fore, WinColor.BLACK), + AnsiFore.RED: (winterm.fore, WinColor.RED), + AnsiFore.GREEN: (winterm.fore, WinColor.GREEN), + AnsiFore.YELLOW: (winterm.fore, WinColor.YELLOW), + AnsiFore.BLUE: (winterm.fore, WinColor.BLUE), + AnsiFore.MAGENTA: (winterm.fore, WinColor.MAGENTA), + AnsiFore.CYAN: (winterm.fore, WinColor.CYAN), + AnsiFore.WHITE: (winterm.fore, WinColor.GREY), + AnsiFore.RESET: (winterm.fore, ), + AnsiFore.LIGHTBLACK_EX: (winterm.fore, WinColor.BLACK, True), + AnsiFore.LIGHTRED_EX: (winterm.fore, WinColor.RED, True), + AnsiFore.LIGHTGREEN_EX: (winterm.fore, WinColor.GREEN, True), + AnsiFore.LIGHTYELLOW_EX: (winterm.fore, WinColor.YELLOW, True), + AnsiFore.LIGHTBLUE_EX: (winterm.fore, WinColor.BLUE, True), + AnsiFore.LIGHTMAGENTA_EX: (winterm.fore, WinColor.MAGENTA, True), + AnsiFore.LIGHTCYAN_EX: (winterm.fore, WinColor.CYAN, True), + AnsiFore.LIGHTWHITE_EX: (winterm.fore, WinColor.GREY, True), + AnsiBack.BLACK: (winterm.back, WinColor.BLACK), + AnsiBack.RED: (winterm.back, WinColor.RED), + AnsiBack.GREEN: (winterm.back, WinColor.GREEN), + AnsiBack.YELLOW: (winterm.back, WinColor.YELLOW), + AnsiBack.BLUE: (winterm.back, WinColor.BLUE), + AnsiBack.MAGENTA: (winterm.back, WinColor.MAGENTA), + AnsiBack.CYAN: (winterm.back, WinColor.CYAN), + AnsiBack.WHITE: (winterm.back, WinColor.GREY), + AnsiBack.RESET: (winterm.back, ), + AnsiBack.LIGHTBLACK_EX: (winterm.back, WinColor.BLACK, True), + AnsiBack.LIGHTRED_EX: (winterm.back, WinColor.RED, True), + AnsiBack.LIGHTGREEN_EX: (winterm.back, WinColor.GREEN, True), + AnsiBack.LIGHTYELLOW_EX: (winterm.back, WinColor.YELLOW, True), + AnsiBack.LIGHTBLUE_EX: (winterm.back, WinColor.BLUE, True), + AnsiBack.LIGHTMAGENTA_EX: (winterm.back, WinColor.MAGENTA, True), + AnsiBack.LIGHTCYAN_EX: (winterm.back, WinColor.CYAN, True), + AnsiBack.LIGHTWHITE_EX: (winterm.back, WinColor.GREY, True), + } + return dict() + + def write(self, text): + if self.strip or self.convert: + self.write_and_convert(text) + else: + self.wrapped.write(text) + self.wrapped.flush() + if self.autoreset: + self.reset_all() + + + def reset_all(self): + if self.convert: + self.call_win32('m', (0,)) + elif not self.strip and not self.stream.closed: + self.wrapped.write(Style.RESET_ALL) + + + def write_and_convert(self, text): + ''' + Write the given text to our wrapped stream, stripping any ANSI + sequences from the text, and optionally converting them into win32 + calls. + ''' + cursor = 0 + text = self.convert_osc(text) + for match in self.ANSI_CSI_RE.finditer(text): + start, end = match.span() + self.write_plain_text(text, cursor, start) + self.convert_ansi(*match.groups()) + cursor = end + self.write_plain_text(text, cursor, len(text)) + + + def write_plain_text(self, text, start, end): + if start < end: + self.wrapped.write(text[start:end]) + self.wrapped.flush() + + + def convert_ansi(self, paramstring, command): + if self.convert: + params = self.extract_params(command, paramstring) + self.call_win32(command, params) + + + def extract_params(self, command, paramstring): + if command in 'Hf': + params = tuple(int(p) if len(p) != 0 else 1 for p in paramstring.split(';')) + while len(params) < 2: + # defaults: + params = params + (1,) + else: + params = tuple(int(p) for p in paramstring.split(';') if len(p) != 0) + if len(params) == 0: + # defaults: + if command in 'JKm': + params = (0,) + elif command in 'ABCD': + params = (1,) + + return params + + + def call_win32(self, command, params): + if command == 'm': + for param in params: + if param in self.win32_calls: + func_args = self.win32_calls[param] + func = func_args[0] + args = func_args[1:] + kwargs = dict(on_stderr=self.on_stderr) + func(*args, **kwargs) + elif command in 'J': + winterm.erase_screen(params[0], on_stderr=self.on_stderr) + elif command in 'K': + winterm.erase_line(params[0], on_stderr=self.on_stderr) + elif command in 'Hf': # cursor position - absolute + winterm.set_cursor_position(params, on_stderr=self.on_stderr) + elif command in 'ABCD': # cursor position - relative + n = params[0] + # A - up, B - down, C - forward, D - back + x, y = {'A': (0, -n), 'B': (0, n), 'C': (n, 0), 'D': (-n, 0)}[command] + winterm.cursor_adjust(x, y, on_stderr=self.on_stderr) + + + def convert_osc(self, text): + for match in self.ANSI_OSC_RE.finditer(text): + start, end = match.span() + text = text[:start] + text[end:] + paramstring, command = match.groups() + if command == BEL: + if paramstring.count(";") == 1: + params = paramstring.split(";") + # 0 - change title and icon (we will only change title) + # 1 - change icon (we don't support this) + # 2 - change title + if params[0] in '02': + winterm.set_title(params[1]) + return text + + + def flush(self): + self.wrapped.flush() diff --git a/TTS/Kokoro/.venv/Lib/site-packages/colorama/initialise.py b/TTS/Kokoro/.venv/Lib/site-packages/colorama/initialise.py new file mode 100644 index 0000000000000000000000000000000000000000..d5fd4b71fed1bb4871717f978f0c470280f099c1 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/colorama/initialise.py @@ -0,0 +1,121 @@ +# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. +import atexit +import contextlib +import sys + +from .ansitowin32 import AnsiToWin32 + + +def _wipe_internal_state_for_tests(): + global orig_stdout, orig_stderr + orig_stdout = None + orig_stderr = None + + global wrapped_stdout, wrapped_stderr + wrapped_stdout = None + wrapped_stderr = None + + global atexit_done + atexit_done = False + + global fixed_windows_console + fixed_windows_console = False + + try: + # no-op if it wasn't registered + atexit.unregister(reset_all) + except AttributeError: + # python 2: no atexit.unregister. Oh well, we did our best. + pass + + +def reset_all(): + if AnsiToWin32 is not None: # Issue #74: objects might become None at exit + AnsiToWin32(orig_stdout).reset_all() + + +def init(autoreset=False, convert=None, strip=None, wrap=True): + + if not wrap and any([autoreset, convert, strip]): + raise ValueError('wrap=False conflicts with any other arg=True') + + global wrapped_stdout, wrapped_stderr + global orig_stdout, orig_stderr + + orig_stdout = sys.stdout + orig_stderr = sys.stderr + + if sys.stdout is None: + wrapped_stdout = None + else: + sys.stdout = wrapped_stdout = \ + wrap_stream(orig_stdout, convert, strip, autoreset, wrap) + if sys.stderr is None: + wrapped_stderr = None + else: + sys.stderr = wrapped_stderr = \ + wrap_stream(orig_stderr, convert, strip, autoreset, wrap) + + global atexit_done + if not atexit_done: + atexit.register(reset_all) + atexit_done = True + + +def deinit(): + if orig_stdout is not None: + sys.stdout = orig_stdout + if orig_stderr is not None: + sys.stderr = orig_stderr + + +def just_fix_windows_console(): + global fixed_windows_console + + if sys.platform != "win32": + return + if fixed_windows_console: + return + if wrapped_stdout is not None or wrapped_stderr is not None: + # Someone already ran init() and it did stuff, so we won't second-guess them + return + + # On newer versions of Windows, AnsiToWin32.__init__ will implicitly enable the + # native ANSI support in the console as a side-effect. We only need to actually + # replace sys.stdout/stderr if we're in the old-style conversion mode. + new_stdout = AnsiToWin32(sys.stdout, convert=None, strip=None, autoreset=False) + if new_stdout.convert: + sys.stdout = new_stdout + new_stderr = AnsiToWin32(sys.stderr, convert=None, strip=None, autoreset=False) + if new_stderr.convert: + sys.stderr = new_stderr + + fixed_windows_console = True + +@contextlib.contextmanager +def colorama_text(*args, **kwargs): + init(*args, **kwargs) + try: + yield + finally: + deinit() + + +def reinit(): + if wrapped_stdout is not None: + sys.stdout = wrapped_stdout + if wrapped_stderr is not None: + sys.stderr = wrapped_stderr + + +def wrap_stream(stream, convert, strip, autoreset, wrap): + if wrap: + wrapper = AnsiToWin32(stream, + convert=convert, strip=strip, autoreset=autoreset) + if wrapper.should_wrap(): + stream = wrapper.stream + return stream + + +# Use this for initial setup as well, to reduce code duplication +_wipe_internal_state_for_tests() diff --git a/TTS/Kokoro/.venv/Lib/site-packages/colorama/win32.py b/TTS/Kokoro/.venv/Lib/site-packages/colorama/win32.py new file mode 100644 index 0000000000000000000000000000000000000000..841b0e270a381cdfaca544a9be976d7276d83b1e --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/colorama/win32.py @@ -0,0 +1,180 @@ +# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. + +# from winbase.h +STDOUT = -11 +STDERR = -12 + +ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004 + +try: + import ctypes + from ctypes import LibraryLoader + windll = LibraryLoader(ctypes.WinDLL) + from ctypes import wintypes +except (AttributeError, ImportError): + windll = None + SetConsoleTextAttribute = lambda *_: None + winapi_test = lambda *_: None +else: + from ctypes import byref, Structure, c_char, POINTER + + COORD = wintypes._COORD + + class CONSOLE_SCREEN_BUFFER_INFO(Structure): + """struct in wincon.h.""" + _fields_ = [ + ("dwSize", COORD), + ("dwCursorPosition", COORD), + ("wAttributes", wintypes.WORD), + ("srWindow", wintypes.SMALL_RECT), + ("dwMaximumWindowSize", COORD), + ] + def __str__(self): + return '(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)' % ( + self.dwSize.Y, self.dwSize.X + , self.dwCursorPosition.Y, self.dwCursorPosition.X + , self.wAttributes + , self.srWindow.Top, self.srWindow.Left, self.srWindow.Bottom, self.srWindow.Right + , self.dwMaximumWindowSize.Y, self.dwMaximumWindowSize.X + ) + + _GetStdHandle = windll.kernel32.GetStdHandle + _GetStdHandle.argtypes = [ + wintypes.DWORD, + ] + _GetStdHandle.restype = wintypes.HANDLE + + _GetConsoleScreenBufferInfo = windll.kernel32.GetConsoleScreenBufferInfo + _GetConsoleScreenBufferInfo.argtypes = [ + wintypes.HANDLE, + POINTER(CONSOLE_SCREEN_BUFFER_INFO), + ] + _GetConsoleScreenBufferInfo.restype = wintypes.BOOL + + _SetConsoleTextAttribute = windll.kernel32.SetConsoleTextAttribute + _SetConsoleTextAttribute.argtypes = [ + wintypes.HANDLE, + wintypes.WORD, + ] + _SetConsoleTextAttribute.restype = wintypes.BOOL + + _SetConsoleCursorPosition = windll.kernel32.SetConsoleCursorPosition + _SetConsoleCursorPosition.argtypes = [ + wintypes.HANDLE, + COORD, + ] + _SetConsoleCursorPosition.restype = wintypes.BOOL + + _FillConsoleOutputCharacterA = windll.kernel32.FillConsoleOutputCharacterA + _FillConsoleOutputCharacterA.argtypes = [ + wintypes.HANDLE, + c_char, + wintypes.DWORD, + COORD, + POINTER(wintypes.DWORD), + ] + _FillConsoleOutputCharacterA.restype = wintypes.BOOL + + _FillConsoleOutputAttribute = windll.kernel32.FillConsoleOutputAttribute + _FillConsoleOutputAttribute.argtypes = [ + wintypes.HANDLE, + wintypes.WORD, + wintypes.DWORD, + COORD, + POINTER(wintypes.DWORD), + ] + _FillConsoleOutputAttribute.restype = wintypes.BOOL + + _SetConsoleTitleW = windll.kernel32.SetConsoleTitleW + _SetConsoleTitleW.argtypes = [ + wintypes.LPCWSTR + ] + _SetConsoleTitleW.restype = wintypes.BOOL + + _GetConsoleMode = windll.kernel32.GetConsoleMode + _GetConsoleMode.argtypes = [ + wintypes.HANDLE, + POINTER(wintypes.DWORD) + ] + _GetConsoleMode.restype = wintypes.BOOL + + _SetConsoleMode = windll.kernel32.SetConsoleMode + _SetConsoleMode.argtypes = [ + wintypes.HANDLE, + wintypes.DWORD + ] + _SetConsoleMode.restype = wintypes.BOOL + + def _winapi_test(handle): + csbi = CONSOLE_SCREEN_BUFFER_INFO() + success = _GetConsoleScreenBufferInfo( + handle, byref(csbi)) + return bool(success) + + def winapi_test(): + return any(_winapi_test(h) for h in + (_GetStdHandle(STDOUT), _GetStdHandle(STDERR))) + + def GetConsoleScreenBufferInfo(stream_id=STDOUT): + handle = _GetStdHandle(stream_id) + csbi = CONSOLE_SCREEN_BUFFER_INFO() + success = _GetConsoleScreenBufferInfo( + handle, byref(csbi)) + return csbi + + def SetConsoleTextAttribute(stream_id, attrs): + handle = _GetStdHandle(stream_id) + return _SetConsoleTextAttribute(handle, attrs) + + def SetConsoleCursorPosition(stream_id, position, adjust=True): + position = COORD(*position) + # If the position is out of range, do nothing. + if position.Y <= 0 or position.X <= 0: + return + # Adjust for Windows' SetConsoleCursorPosition: + # 1. being 0-based, while ANSI is 1-based. + # 2. expecting (x,y), while ANSI uses (y,x). + adjusted_position = COORD(position.Y - 1, position.X - 1) + if adjust: + # Adjust for viewport's scroll position + sr = GetConsoleScreenBufferInfo(STDOUT).srWindow + adjusted_position.Y += sr.Top + adjusted_position.X += sr.Left + # Resume normal processing + handle = _GetStdHandle(stream_id) + return _SetConsoleCursorPosition(handle, adjusted_position) + + def FillConsoleOutputCharacter(stream_id, char, length, start): + handle = _GetStdHandle(stream_id) + char = c_char(char.encode()) + length = wintypes.DWORD(length) + num_written = wintypes.DWORD(0) + # Note that this is hard-coded for ANSI (vs wide) bytes. + success = _FillConsoleOutputCharacterA( + handle, char, length, start, byref(num_written)) + return num_written.value + + def FillConsoleOutputAttribute(stream_id, attr, length, start): + ''' FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten )''' + handle = _GetStdHandle(stream_id) + attribute = wintypes.WORD(attr) + length = wintypes.DWORD(length) + num_written = wintypes.DWORD(0) + # Note that this is hard-coded for ANSI (vs wide) bytes. + return _FillConsoleOutputAttribute( + handle, attribute, length, start, byref(num_written)) + + def SetConsoleTitle(title): + return _SetConsoleTitleW(title) + + def GetConsoleMode(handle): + mode = wintypes.DWORD() + success = _GetConsoleMode(handle, byref(mode)) + if not success: + raise ctypes.WinError() + return mode.value + + def SetConsoleMode(handle, mode): + success = _SetConsoleMode(handle, mode) + if not success: + raise ctypes.WinError() diff --git a/TTS/Kokoro/.venv/Lib/site-packages/colorama/winterm.py b/TTS/Kokoro/.venv/Lib/site-packages/colorama/winterm.py new file mode 100644 index 0000000000000000000000000000000000000000..aad867e8c80b826bf6a060116f17fa08a8eb0765 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/colorama/winterm.py @@ -0,0 +1,195 @@ +# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. +try: + from msvcrt import get_osfhandle +except ImportError: + def get_osfhandle(_): + raise OSError("This isn't windows!") + + +from . import win32 + +# from wincon.h +class WinColor(object): + BLACK = 0 + BLUE = 1 + GREEN = 2 + CYAN = 3 + RED = 4 + MAGENTA = 5 + YELLOW = 6 + GREY = 7 + +# from wincon.h +class WinStyle(object): + NORMAL = 0x00 # dim text, dim background + BRIGHT = 0x08 # bright text, dim background + BRIGHT_BACKGROUND = 0x80 # dim text, bright background + +class WinTerm(object): + + def __init__(self): + self._default = win32.GetConsoleScreenBufferInfo(win32.STDOUT).wAttributes + self.set_attrs(self._default) + self._default_fore = self._fore + self._default_back = self._back + self._default_style = self._style + # In order to emulate LIGHT_EX in windows, we borrow the BRIGHT style. + # So that LIGHT_EX colors and BRIGHT style do not clobber each other, + # we track them separately, since LIGHT_EX is overwritten by Fore/Back + # and BRIGHT is overwritten by Style codes. + self._light = 0 + + def get_attrs(self): + return self._fore + self._back * 16 + (self._style | self._light) + + def set_attrs(self, value): + self._fore = value & 7 + self._back = (value >> 4) & 7 + self._style = value & (WinStyle.BRIGHT | WinStyle.BRIGHT_BACKGROUND) + + def reset_all(self, on_stderr=None): + self.set_attrs(self._default) + self.set_console(attrs=self._default) + self._light = 0 + + def fore(self, fore=None, light=False, on_stderr=False): + if fore is None: + fore = self._default_fore + self._fore = fore + # Emulate LIGHT_EX with BRIGHT Style + if light: + self._light |= WinStyle.BRIGHT + else: + self._light &= ~WinStyle.BRIGHT + self.set_console(on_stderr=on_stderr) + + def back(self, back=None, light=False, on_stderr=False): + if back is None: + back = self._default_back + self._back = back + # Emulate LIGHT_EX with BRIGHT_BACKGROUND Style + if light: + self._light |= WinStyle.BRIGHT_BACKGROUND + else: + self._light &= ~WinStyle.BRIGHT_BACKGROUND + self.set_console(on_stderr=on_stderr) + + def style(self, style=None, on_stderr=False): + if style is None: + style = self._default_style + self._style = style + self.set_console(on_stderr=on_stderr) + + def set_console(self, attrs=None, on_stderr=False): + if attrs is None: + attrs = self.get_attrs() + handle = win32.STDOUT + if on_stderr: + handle = win32.STDERR + win32.SetConsoleTextAttribute(handle, attrs) + + def get_position(self, handle): + position = win32.GetConsoleScreenBufferInfo(handle).dwCursorPosition + # Because Windows coordinates are 0-based, + # and win32.SetConsoleCursorPosition expects 1-based. + position.X += 1 + position.Y += 1 + return position + + def set_cursor_position(self, position=None, on_stderr=False): + if position is None: + # I'm not currently tracking the position, so there is no default. + # position = self.get_position() + return + handle = win32.STDOUT + if on_stderr: + handle = win32.STDERR + win32.SetConsoleCursorPosition(handle, position) + + def cursor_adjust(self, x, y, on_stderr=False): + handle = win32.STDOUT + if on_stderr: + handle = win32.STDERR + position = self.get_position(handle) + adjusted_position = (position.Y + y, position.X + x) + win32.SetConsoleCursorPosition(handle, adjusted_position, adjust=False) + + def erase_screen(self, mode=0, on_stderr=False): + # 0 should clear from the cursor to the end of the screen. + # 1 should clear from the cursor to the beginning of the screen. + # 2 should clear the entire screen, and move cursor to (1,1) + handle = win32.STDOUT + if on_stderr: + handle = win32.STDERR + csbi = win32.GetConsoleScreenBufferInfo(handle) + # get the number of character cells in the current buffer + cells_in_screen = csbi.dwSize.X * csbi.dwSize.Y + # get number of character cells before current cursor position + cells_before_cursor = csbi.dwSize.X * csbi.dwCursorPosition.Y + csbi.dwCursorPosition.X + if mode == 0: + from_coord = csbi.dwCursorPosition + cells_to_erase = cells_in_screen - cells_before_cursor + elif mode == 1: + from_coord = win32.COORD(0, 0) + cells_to_erase = cells_before_cursor + elif mode == 2: + from_coord = win32.COORD(0, 0) + cells_to_erase = cells_in_screen + else: + # invalid mode + return + # fill the entire screen with blanks + win32.FillConsoleOutputCharacter(handle, ' ', cells_to_erase, from_coord) + # now set the buffer's attributes accordingly + win32.FillConsoleOutputAttribute(handle, self.get_attrs(), cells_to_erase, from_coord) + if mode == 2: + # put the cursor where needed + win32.SetConsoleCursorPosition(handle, (1, 1)) + + def erase_line(self, mode=0, on_stderr=False): + # 0 should clear from the cursor to the end of the line. + # 1 should clear from the cursor to the beginning of the line. + # 2 should clear the entire line. + handle = win32.STDOUT + if on_stderr: + handle = win32.STDERR + csbi = win32.GetConsoleScreenBufferInfo(handle) + if mode == 0: + from_coord = csbi.dwCursorPosition + cells_to_erase = csbi.dwSize.X - csbi.dwCursorPosition.X + elif mode == 1: + from_coord = win32.COORD(0, csbi.dwCursorPosition.Y) + cells_to_erase = csbi.dwCursorPosition.X + elif mode == 2: + from_coord = win32.COORD(0, csbi.dwCursorPosition.Y) + cells_to_erase = csbi.dwSize.X + else: + # invalid mode + return + # fill the entire screen with blanks + win32.FillConsoleOutputCharacter(handle, ' ', cells_to_erase, from_coord) + # now set the buffer's attributes accordingly + win32.FillConsoleOutputAttribute(handle, self.get_attrs(), cells_to_erase, from_coord) + + def set_title(self, title): + win32.SetConsoleTitle(title) + + +def enable_vt_processing(fd): + if win32.windll is None or not win32.winapi_test(): + return False + + try: + handle = get_osfhandle(fd) + mode = win32.GetConsoleMode(handle) + win32.SetConsoleMode( + handle, + mode | win32.ENABLE_VIRTUAL_TERMINAL_PROCESSING, + ) + + mode = win32.GetConsoleMode(handle) + if mode & win32.ENABLE_VIRTUAL_TERMINAL_PROCESSING: + return True + # Can get TypeError in testsuite where 'fd' is a Mock() + except (OSError, TypeError): + return False diff --git a/TTS/Kokoro/.venv/Lib/site-packages/confection-0.1.5.dist-info/INSTALLER b/TTS/Kokoro/.venv/Lib/site-packages/confection-0.1.5.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/confection-0.1.5.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/TTS/Kokoro/.venv/Lib/site-packages/confection-0.1.5.dist-info/LICENSE b/TTS/Kokoro/.venv/Lib/site-packages/confection-0.1.5.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..37f77c60f9236be556499225f09cb67c00eb4795 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/confection-0.1.5.dist-info/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 ExplosionAI GmbH + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/TTS/Kokoro/.venv/Lib/site-packages/confection-0.1.5.dist-info/METADATA b/TTS/Kokoro/.venv/Lib/site-packages/confection-0.1.5.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..38116f4c78f1f780208d8717025ba8f8dbf64435 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/confection-0.1.5.dist-info/METADATA @@ -0,0 +1,416 @@ +Metadata-Version: 2.1 +Name: confection +Version: 0.1.5 +Summary: The sweetest config system for Python +Home-page: https://github.com/explosion/confection +Author: Explosion +Author-email: contact@explosion.ai +License: MIT +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Console +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Science/Research +Classifier: License :: OSI Approved :: MIT License +Classifier: Operating System :: POSIX :: Linux +Classifier: Operating System :: MacOS :: MacOS X +Classifier: Operating System :: Microsoft :: Windows +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.6 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Topic :: Scientific/Engineering +Requires-Python: >=3.6 +Description-Content-Type: text/markdown +License-File: LICENSE +Requires-Dist: pydantic !=1.8,!=1.8.1,<3.0.0,>=1.7.4 +Requires-Dist: srsly <3.0.0,>=2.4.0 +Requires-Dist: typing-extensions <5.0.0,>=3.7.4.1 ; python_version < "3.8" + + + +# Confection: The sweetest config system for Python + +`confection` :candy: is a lightweight library that offers a **configuration +system** letting you conveniently describe arbitrary trees of objects. + +Configuration is a huge challenge for machine-learning code because you may want +to expose almost any detail of any function as a hyperparameter. The setting you +want to expose might be arbitrarily far down in your call stack, so it might +need to pass all the way through the CLI or REST API, through any number of +intermediate functions, affecting the interface of everything along the way. And +then once those settings are added, they become hard to remove later. Default +values also become hard to change without breaking backwards compatibility. + +To solve this problem, `confection` offers a config system that lets you easily +describe arbitrary trees of objects. The objects can be created via function +calls you register using a simple decorator syntax. You can even version the +functions you create, allowing you to make improvements without breaking +backwards compatibility. The most similar config system we’re aware of is +[Gin](https://github.com/google/gin-config), which uses a similar syntax, and +also allows you to link the configuration system to functions in your code using +a decorator. `confection`'s config system is simpler and emphasizes a different +workflow via a subset of Gin’s functionality. + +[![tests](https://github.com/explosion/confection/actions/workflows/tests.yml/badge.svg)](https://github.com/explosion/confection/actions/workflows/tests.yml) +[![Current Release Version](https://img.shields.io/github/v/release/explosion/confection.svg?style=flat-square&include_prereleases&logo=github)](https://github.com/explosion/confection/releases) +[![pypi Version](https://img.shields.io/pypi/v/confection.svg?style=flat-square&logo=pypi&logoColor=white)](https://pypi.org/project/confection/) +[![conda Version](https://img.shields.io/conda/vn/conda-forge/confection.svg?style=flat-square&logo=conda-forge&logoColor=white)](https://anaconda.org/conda-forge/confection) +[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg?style=flat-square)](https://github.com/ambv/black) + +## ⏳ Installation + +```bash +pip install confection +``` + +```bash +conda install -c conda-forge confection +``` + +## 👩‍💻 Usage + +The configuration system parses a `.cfg` file like + +```ini +[training] +patience = 10 +dropout = 0.2 +use_vectors = false + +[training.logging] +level = "INFO" + +[nlp] +# This uses the value of training.use_vectors +use_vectors = ${training.use_vectors} +lang = "en" +``` + +and resolves it to a `Dict`: + +```json +{ + "training": { + "patience": 10, + "dropout": 0.2, + "use_vectors": false, + "logging": { + "level": "INFO" + } + }, + "nlp": { + "use_vectors": false, + "lang": "en" + } +} +``` + +The config is divided into sections, with the section name in square brackets – +for example, `[training]`. Within the sections, config values can be assigned to +keys using `=`. Values can also be referenced from other sections using the dot +notation and placeholders indicated by the dollar sign and curly braces. For +example, `${training.use_vectors}` will receive the value of use_vectors in the +training block. This is useful for settings that are shared across components. + +The config format has three main differences from Python’s built-in +`configparser`: + +1. JSON-formatted values. `confection` passes all values through `json.loads` to + interpret them. You can use atomic values like strings, floats, integers or + booleans, or you can use complex objects such as lists or maps. +2. Structured sections. `confection` uses a dot notation to build nested + sections. If you have a section named `[section.subsection]`, `confection` + will parse that into a nested structure, placing subsection within section. +3. References to registry functions. If a key starts with `@`, `confection` will + interpret its value as the name of a function registry, load the function + registered for that name and pass in the rest of the block as arguments. If + type hints are available on the function, the argument values (and return + value of the function) will be validated against them. This lets you express + complex configurations, like a training pipeline where `batch_size` is + populated by a function that yields floats. + +There’s no pre-defined scheme you have to follow; how you set up the top-level +sections is up to you. At the end of it, you’ll receive a dictionary with the +values that you can use in your script – whether it’s complete initialized +functions, or just basic settings. + +For instance, let’s say you want to define a new optimizer. You'd define its +arguments in `config.cfg` like so: + +```ini +[optimizer] +@optimizers = "my_cool_optimizer.v1" +learn_rate = 0.001 +gamma = 1e-8 +``` + +To load and parse this configuration using a `catalogue` registry (install +[`catalogue`](https://github.com/explosion/catalogue) separately): + +```python +import dataclasses +from typing import Union, Iterable +import catalogue +from confection import registry, Config + +# Create a new registry. +registry.optimizers = catalogue.create("confection", "optimizers", entry_points=False) + + +# Define a dummy optimizer class. +@dataclasses.dataclass +class MyCoolOptimizer: + learn_rate: float + gamma: float + + +@registry.optimizers.register("my_cool_optimizer.v1") +def make_my_optimizer(learn_rate: Union[float, Iterable[float]], gamma: float): + return MyCoolOptimizer(learn_rate, gamma) + + +# Load the config file from disk, resolve it and fetch the instantiated optimizer object. +config = Config().from_disk("./config.cfg") +resolved = registry.resolve(config) +optimizer = resolved["optimizer"] # MyCoolOptimizer(learn_rate=0.001, gamma=1e-08) +``` + +> ⚠️ Caution: Type-checkers such as `mypy` will mark adding new attributes to `registry` this way - i. e. +> `registry.new_attr = ...` - as errors. This is because a new attribute is added to the class after initialization. If +> you are using typecheckers, you can either ignore this (e. g. with `# type: ignore` for `mypy`) or use a typesafe +> alternative: instead of `registry.new_attr = ...`, use `setattr(registry, "new_attr", ...)`. + +Under the hood, `confection` will look up the `"my_cool_optimizer.v1"` function +in the "optimizers" registry and then call it with the arguments `learn_rate` +and `gamma`. If the function has type annotations, it will also validate the +input. For instance, if `learn_rate` is annotated as a float and the config +defines a string, `confection` will raise an error. + +The Thinc documentation offers further information on the configuration system: + +- [recursive blocks](https://thinc.ai/docs/usage-config#registry-recursive) +- [defining variable positional arguments](https://thinc.ai/docs/usage-config#registries-args) +- [using interpolation](https://thinc.ai/docs/usage-config#config-interpolation) +- [using custom registries](https://thinc.ai/docs/usage-config#registries-custom) +- [advanced type annotations with Pydantic](https://thinc.ai/docs/usage-config#advanced-types) +- [using base schemas](https://thinc.ai/docs/usage-config#advanced-types-base-schema) +- [filling a configuration with defaults](https://thinc.ai/docs/usage-config#advanced-types-fill-defaults) + +## 🎛 API + +### class `Config` + +This class holds the model and training +[configuration](https://thinc.ai/docs/usage-config) and can load and save the +INI-style configuration format from/to a string, file or bytes. The `Config` +class is a subclass of `dict` and uses Python’s `ConfigParser` under the hood. + +#### method `Config.__init__` + +Initialize a new `Config` object with optional data. + +```python +from confection import Config +config = Config({"training": {"patience": 10, "dropout": 0.2}}) +``` + +| Argument | Type | Description | +| ----------------- | ----------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `data` | `Optional[Union[Dict[str, Any], Config]]` | Optional data to initialize the config with. | +| `section_order` | `Optional[List[str]]` | Top-level section names, in order, used to sort the saved and loaded config. All other sections will be sorted alphabetically. | +| `is_interpolated` | `Optional[bool]` | Whether the config is interpolated or whether it contains variables. Read from the `data` if it’s an instance of `Config` and otherwise defaults to `True`. | + +#### method `Config.from_str` + +Load the config from a string. + +```python +from confection import Config + +config_str = """ +[training] +patience = 10 +dropout = 0.2 +""" +config = Config().from_str(config_str) +print(config["training"]) # {'patience': 10, 'dropout': 0.2}} +``` + +| Argument | Type | Description | +| ------------- | ---------------- | -------------------------------------------------------------------------------------------------------------------- | +| `text` | `str` | The string config to load. | +| `interpolate` | `bool` | Whether to interpolate variables like `${section.key}`. Defaults to `True`. | +| `overrides` | `Dict[str, Any]` | Overrides for values and sections. Keys are provided in dot notation, e.g. `"training.dropout"` mapped to the value. | +| **RETURNS** | `Config` | The loaded config. | + +#### method `Config.to_str` + +Load the config from a string. + +```python +from confection import Config + +config = Config({"training": {"patience": 10, "dropout": 0.2}}) +print(config.to_str()) # '[training]\npatience = 10\n\ndropout = 0.2' +``` + +| Argument | Type | Description | +| ------------- | ------ | --------------------------------------------------------------------------- | +| `interpolate` | `bool` | Whether to interpolate variables like `${section.key}`. Defaults to `True`. | +| **RETURNS** | `str` | The string config. | + +#### method `Config.to_bytes` + +Serialize the config to a byte string. + +```python +from confection import Config + +config = Config({"training": {"patience": 10, "dropout": 0.2}}) +config_bytes = config.to_bytes() +print(config_bytes) # b'[training]\npatience = 10\n\ndropout = 0.2' +``` + +| Argument | Type | Description | +| ------------- | ---------------- | -------------------------------------------------------------------------------------------------------------------- | +| `interpolate` | `bool` | Whether to interpolate variables like `${section.key}`. Defaults to `True`. | +| `overrides` | `Dict[str, Any]` | Overrides for values and sections. Keys are provided in dot notation, e.g. `"training.dropout"` mapped to the value. | +| **RETURNS** | `str` | The serialized config. | + +#### method `Config.from_bytes` + +Load the config from a byte string. + +```python +from confection import Config + +config = Config({"training": {"patience": 10, "dropout": 0.2}}) +config_bytes = config.to_bytes() +new_config = Config().from_bytes(config_bytes) +``` + +| Argument | Type | Description | +| ------------- | -------- | --------------------------------------------------------------------------- | +| `bytes_data` | `bool` | The data to load. | +| `interpolate` | `bool` | Whether to interpolate variables like `${section.key}`. Defaults to `True`. | +| **RETURNS** | `Config` | The loaded config. | + +#### method `Config.to_disk` + +Serialize the config to a file. + +```python +from confection import Config + +config = Config({"training": {"patience": 10, "dropout": 0.2}}) +config.to_disk("./config.cfg") +``` + +| Argument | Type | Description | +| ------------- | ------------------ | --------------------------------------------------------------------------- | +| `path` | `Union[Path, str]` | The file path. | +| `interpolate` | `bool` | Whether to interpolate variables like `${section.key}`. Defaults to `True`. | + +#### method `Config.from_disk` + +Load the config from a file. + +```python +from confection import Config + +config = Config({"training": {"patience": 10, "dropout": 0.2}}) +config.to_disk("./config.cfg") +new_config = Config().from_disk("./config.cfg") +``` + +| Argument | Type | Description | +| ------------- | ------------------ | -------------------------------------------------------------------------------------------------------------------- | +| `path` | `Union[Path, str]` | The file path. | +| `interpolate` | `bool` | Whether to interpolate variables like `${section.key}`. Defaults to `True`. | +| `overrides` | `Dict[str, Any]` | Overrides for values and sections. Keys are provided in dot notation, e.g. `"training.dropout"` mapped to the value. | +| **RETURNS** | `Config` | The loaded config. | + +#### method `Config.copy` + +Deep-copy the config. + +| Argument | Type | Description | +| ----------- | -------- | ------------------ | +| **RETURNS** | `Config` | The copied config. | + +#### method `Config.interpolate` + +Interpolate variables like `${section.value}` or `${section.subsection}` and +return a copy of the config with interpolated values. Can be used if a config is +loaded with `interpolate=False`, e.g. via `Config.from_str`. + +```python +from confection import Config + +config_str = """ +[hyper_params] +dropout = 0.2 + +[training] +dropout = ${hyper_params.dropout} +""" +config = Config().from_str(config_str, interpolate=False) +print(config["training"]) # {'dropout': '${hyper_params.dropout}'}} +config = config.interpolate() +print(config["training"]) # {'dropout': 0.2}} +``` + +| Argument | Type | Description | +| ----------- | -------- | ---------------------------------------------- | +| **RETURNS** | `Config` | A copy of the config with interpolated values. | + +##### method `Config.merge` + +Deep-merge two config objects, using the current config as the default. Only +merges sections and dictionaries and not other values like lists. Values that +are provided in the updates are overwritten in the base config, and any new +values or sections are added. If a config value is a variable like +`${section.key}` (e.g. if the config was loaded with `interpolate=False)`, **the +variable is preferred**, even if the updates provide a different value. This +ensures that variable references aren’t destroyed by a merge. + +> :warning: Note that blocks that refer to registered functions using the `@` +> syntax are only merged if they are referring to the same functions. Otherwise, +> merging could easily produce invalid configs, since different functions can +> take different arguments. If a block refers to a different function, it’s +> overwritten. + +```python +from confection import Config + +base_config_str = """ +[training] +patience = 10 +dropout = 0.2 +""" +update_config_str = """ +[training] +dropout = 0.1 +max_epochs = 2000 +""" + +base_config = Config().from_str(base_config_str) +update_config = Config().from_str(update_config_str) +merged = Config(base_config).merge(update_config) +print(merged["training"]) # {'patience': 10, 'dropout': 0.1, 'max_epochs': 2000} +``` + +| Argument | Type | Description | +| ----------- | ------------------------------- | --------------------------------------------------- | +| `overrides` | `Union[Dict[str, Any], Config]` | The updates to merge into the config. | +| **RETURNS** | `Config` | A new config instance containing the merged config. | + +### Config Attributes + +| Argument | Type | Description | +| ----------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `is_interpolated` | `bool` | Whether the config values have been interpolated. Defaults to `True` and is set to `False` if a config is loaded with `interpolate=False`, e.g. using `Config.from_str`. | diff --git a/TTS/Kokoro/.venv/Lib/site-packages/confection-0.1.5.dist-info/RECORD b/TTS/Kokoro/.venv/Lib/site-packages/confection-0.1.5.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..e207c4939c3b7c3071778f3eb5d766d0bfc1c78e --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/confection-0.1.5.dist-info/RECORD @@ -0,0 +1,22 @@ +confection-0.1.5.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +confection-0.1.5.dist-info/LICENSE,sha256=9_dOqC-aENfOK6Bd1-RgyMK7QqbMfZrnGrNWYbX3HJs,1073 +confection-0.1.5.dist-info/METADATA,sha256=E4IAhPzCjN22pZCJlF2sfzw02BfE3kchnaZhv-H_ulM,19597 +confection-0.1.5.dist-info/RECORD,, +confection-0.1.5.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92 +confection-0.1.5.dist-info/top_level.txt,sha256=IW0MglPluqVnP26bD2x7YDauBNEgafciyjlKd7s2dzM,11 +confection-0.1.5.dist-info/zip-safe,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1 +confection/__init__.py,sha256=wuhtsxT6aFk0XEou9P-MmxInKUS5a7eEghCIyvbXYHs,47656 +confection/__pycache__/__init__.cpython-312.pyc,, +confection/__pycache__/util.cpython-312.pyc,, +confection/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +confection/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +confection/tests/__pycache__/__init__.cpython-312.pyc,, +confection/tests/__pycache__/conftest.cpython-312.pyc,, +confection/tests/__pycache__/test_config.cpython-312.pyc,, +confection/tests/__pycache__/test_frozen_structures.cpython-312.pyc,, +confection/tests/__pycache__/util.cpython-312.pyc,, +confection/tests/conftest.py,sha256=06QImBbGxE7pAv3x8JMehJN9xvGD8Y9n71MhYQIMN2Y,489 +confection/tests/test_config.py,sha256=pknGSLihotM7iLi0KYeCfOTx1uHWxaXcKWCyjxzLY_I,54505 +confection/tests/test_frozen_structures.py,sha256=OJyqk-xY4hu8yDrAbX8cSpvA9FlLpl49GISh1cmQ2cY,1713 +confection/tests/util.py,sha256=CSUh9wOm5OMAdjbDP4vDT0GOdHGT8RgYCq8CUhx1SLk,3686 +confection/util.py,sha256=0iohHQdDgFd8ec57mhj41zA7wihKvTPcXKLv7JoKLbo,4300 diff --git a/TTS/Kokoro/.venv/Lib/site-packages/confection-0.1.5.dist-info/WHEEL b/TTS/Kokoro/.venv/Lib/site-packages/confection-0.1.5.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..bab98d675883cc7567a79df485cd7b4f015e376f --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/confection-0.1.5.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.43.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/TTS/Kokoro/.venv/Lib/site-packages/confection-0.1.5.dist-info/top_level.txt b/TTS/Kokoro/.venv/Lib/site-packages/confection-0.1.5.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..9e9963fb975950c3255b142c589f060a158902ca --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/confection-0.1.5.dist-info/top_level.txt @@ -0,0 +1 @@ +confection diff --git a/TTS/Kokoro/.venv/Lib/site-packages/confection-0.1.5.dist-info/zip-safe b/TTS/Kokoro/.venv/Lib/site-packages/confection-0.1.5.dist-info/zip-safe new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/confection-0.1.5.dist-info/zip-safe @@ -0,0 +1 @@ + diff --git a/TTS/Kokoro/.venv/Lib/site-packages/confection/__init__.py b/TTS/Kokoro/.venv/Lib/site-packages/confection/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..039549833571499a863b873855318ac116bc68c9 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/confection/__init__.py @@ -0,0 +1,1095 @@ +import copy +import inspect +import io +import re +import warnings +from configparser import ( + MAX_INTERPOLATION_DEPTH, + ConfigParser, + ExtendedInterpolation, + InterpolationDepthError, + InterpolationMissingOptionError, + InterpolationSyntaxError, + NoOptionError, + NoSectionError, + ParsingError, +) +from dataclasses import dataclass +from pathlib import Path +from types import GeneratorType +from typing import ( + Any, + Callable, + Dict, + Iterable, + List, + Mapping, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import srsly + +try: + from pydantic.v1 import BaseModel, Extra, ValidationError, create_model + from pydantic.v1.fields import ModelField + from pydantic.v1.main import ModelMetaclass +except ImportError: + from pydantic import BaseModel, create_model, ValidationError, Extra # type: ignore + from pydantic.main import ModelMetaclass # type: ignore + from pydantic.fields import ModelField # type: ignore + +from .util import SimpleFrozenDict, SimpleFrozenList # noqa: F401 + +# Field used for positional arguments, e.g. [section.*.xyz]. The alias is +# required for the schema (shouldn't clash with user-defined arg names) +ARGS_FIELD = "*" +ARGS_FIELD_ALIAS = "VARIABLE_POSITIONAL_ARGS" +# Aliases for fields that would otherwise shadow pydantic attributes. Can be any +# string, so we're using name + space so it looks the same in error messages etc. +RESERVED_FIELDS = {"validate": "validate\u0020"} +# Internal prefix used to mark section references for custom interpolation +SECTION_PREFIX = "__SECTION__:" +# Values that shouldn't be loaded during interpolation because it'd cause +# even explicit string values to be incorrectly parsed as bools/None etc. +JSON_EXCEPTIONS = ("true", "false", "null") +# Regex to detect whether a value contains a variable +VARIABLE_RE = re.compile(r"\$\{[\w\.:]+\}") + + +class CustomInterpolation(ExtendedInterpolation): + def before_read(self, parser, section, option, value): + # If we're dealing with a quoted string as the interpolation value, + # make sure we load and unquote it so we don't end up with '"value"' + try: + json_value = srsly.json_loads(value) + if isinstance(json_value, str) and json_value not in JSON_EXCEPTIONS: + value = json_value + except ValueError: + if value and value[0] == value[-1] == "'": + warnings.warn( + f"The value [{value}] seems to be single-quoted, but values " + "use JSON formatting, which requires double quotes." + ) + except Exception: + pass + return super().before_read(parser, section, option, value) + + def before_get(self, parser, section, option, value, defaults): + # Mostly copy-pasted from the built-in configparser implementation. + L = [] + self.interpolate(parser, option, L, value, section, defaults, 1) + return "".join(L) + + def interpolate(self, parser, option, accum, rest, section, map, depth): + # Mostly copy-pasted from the built-in configparser implementation. + # We need to overwrite this method so we can add special handling for + # block references :( All values produced here should be strings – + # we need to wait until the whole config is interpreted anyways so + # filling in incomplete values here is pointless. All we need is the + # section reference so we can fetch it later. + rawval = parser.get(section, option, raw=True, fallback=rest) + if depth > MAX_INTERPOLATION_DEPTH: + raise InterpolationDepthError(option, section, rawval) + while rest: + p = rest.find("$") + if p < 0: + accum.append(rest) + return + if p > 0: + accum.append(rest[:p]) + rest = rest[p:] + # p is no longer used + c = rest[1:2] + if c == "$": + accum.append("$") + rest = rest[2:] + elif c == "{": + # We want to treat both ${a:b} and ${a.b} the same + m = self._KEYCRE.match(rest) + if m is None: + err = f"bad interpolation variable reference {rest}" + raise InterpolationSyntaxError(option, section, err) + orig_var = m.group(1) + path = orig_var.replace(":", ".").rsplit(".", 1) + rest = rest[m.end() :] + sect = section + opt = option + try: + if len(path) == 1: + opt = parser.optionxform(path[0]) + if opt in map: + v = map[opt] + else: + # We have block reference, store it as a special key + section_name = parser[parser.optionxform(path[0])]._name + v = self._get_section_name(section_name) + elif len(path) == 2: + sect = path[0] + opt = parser.optionxform(path[1]) + fallback = "__FALLBACK__" + v = parser.get(sect, opt, raw=True, fallback=fallback) + # If a variable doesn't exist, try again and treat the + # reference as a section + if v == fallback: + v = self._get_section_name(parser[f"{sect}.{opt}"]._name) + else: + err = f"More than one ':' found: {rest}" + raise InterpolationSyntaxError(option, section, err) + except (KeyError, NoSectionError, NoOptionError): + raise InterpolationMissingOptionError( + option, section, rawval, orig_var + ) from None + if "$" in v: + new_map = dict(parser.items(sect, raw=True)) + self.interpolate(parser, opt, accum, v, sect, new_map, depth + 1) + else: + accum.append(v) + else: + err = "'$' must be followed by '$' or '{', found: %r" % (rest,) + raise InterpolationSyntaxError(option, section, err) + + def _get_section_name(self, name: str) -> str: + """Generate the name of a section. Note that we use a quoted string here + so we can use section references within lists and load the list as + JSON. Since section references can't be used within strings, we don't + need the quoted vs. unquoted distinction like we do for variables. + + Examples (assuming section = {"foo": 1}): + - value: ${section.foo} -> value: 1 + - value: "hello ${section.foo}" -> value: "hello 1" + - value: ${section} -> value: {"foo": 1} + - value: "${section}" -> value: {"foo": 1} + - value: "hello ${section}" -> invalid + """ + return f'"{SECTION_PREFIX}{name}"' + + +def get_configparser(interpolate: bool = True): + config = ConfigParser(interpolation=CustomInterpolation() if interpolate else None) + # Preserve case of keys: https://stackoverflow.com/a/1611877/6400719 + config.optionxform = str # type: ignore + return config + + +class Config(dict): + """This class holds the model and training configuration and can load and + save the TOML-style configuration format from/to a string, file or bytes. + The Config class is a subclass of dict and uses Python's ConfigParser + under the hood. + """ + + is_interpolated: bool + + def __init__( + self, + data: Optional[Union[Dict[str, Any], "ConfigParser", "Config"]] = None, + *, + is_interpolated: Optional[bool] = None, + section_order: Optional[List[str]] = None, + ) -> None: + """Initialize a new Config object with optional data.""" + dict.__init__(self) + if data is None: + data = {} + if not isinstance(data, (dict, Config, ConfigParser)): + raise ValueError( + f"Can't initialize Config with data. Expected dict, Config or " + f"ConfigParser but got: {type(data)}" + ) + # Whether the config has been interpolated. We can use this to check + # whether we need to interpolate again when it's resolved. We assume + # that a config is interpolated by default. + if is_interpolated is not None: + self.is_interpolated = is_interpolated + elif isinstance(data, Config): + self.is_interpolated = data.is_interpolated + else: + self.is_interpolated = True + if section_order is not None: + self.section_order = section_order + elif isinstance(data, Config): + self.section_order = data.section_order + else: + self.section_order = [] + # Update with data + self.update(self._sort(data)) + + def interpolate(self) -> "Config": + """Interpolate a config. Returns a copy of the object.""" + # This is currently the most effective way because we need our custom + # to_str logic to run in order to re-serialize the values so we can + # interpolate them again. ConfigParser.read_dict will just call str() + # on all values, which isn't enough. + return Config().from_str(self.to_str()) + + def interpret_config(self, config: "ConfigParser") -> None: + """Interpret a config, parse nested sections and parse the values + as JSON. Mostly used internally and modifies the config in place. + """ + self._validate_sections(config) + # Sort sections by depth, so that we can iterate breadth-first. This + # allows us to check that we're not expanding an undefined block. + get_depth = lambda item: len(item[0].split(".")) + for section, values in sorted(config.items(), key=get_depth): + if section == "DEFAULT": + # Skip [DEFAULT] section so it doesn't cause validation error + continue + parts = section.split(".") + node = self + for part in parts[:-1]: + if part == "*": + node = node.setdefault(part, {}) + elif part not in node: + err_title = ( + "Error parsing config section. Perhaps a section name is wrong?" + ) + err = [{"loc": parts, "msg": f"Section '{part}' is not defined"}] + raise ConfigValidationError( + config=self, errors=err, title=err_title + ) + else: + node = node[part] + if not isinstance(node, dict): + # Happens if both value *and* subsection were defined for a key + err = [{"loc": parts, "msg": "found conflicting values"}] + err_cfg = f"{self}\n{({part: dict(values)})}" + raise ConfigValidationError(config=err_cfg, errors=err) + # Set the default section + node = node.setdefault(parts[-1], {}) + if not isinstance(node, dict): + # Happens if both value *and* subsection were defined for a key + err = [{"loc": parts, "msg": "found conflicting values"}] + err_cfg = f"{self}\n{({part: dict(values)})}" + raise ConfigValidationError(config=err_cfg, errors=err) + try: + keys_values = list(values.items()) + except InterpolationMissingOptionError as e: + raise ConfigValidationError(desc=f"{e}") from None + for key, value in keys_values: + config_v = config.get(section, key) + node[key] = self._interpret_value(config_v) + self.replace_section_refs(self) + + def replace_section_refs( + self, config: Union[Dict[str, Any], "Config"], parent: str = "" + ) -> None: + """Replace references to section blocks in the final config.""" + for key, value in config.items(): + key_parent = f"{parent}.{key}".strip(".") + if isinstance(value, dict): + self.replace_section_refs(value, parent=key_parent) + elif isinstance(value, list): + config[key] = [ + self._get_section_ref(v, parent=[parent, key]) for v in value + ] + else: + config[key] = self._get_section_ref(value, parent=[parent, key]) + + def _interpret_value(self, value: Any) -> Any: + """Interpret a single config value.""" + result = try_load_json(value) + # If value is a string and it contains a variable, use original value + # (not interpreted string, which could lead to double quotes: + # ${x.y} -> "${x.y}" -> "'${x.y}'"). Make sure to check it's a string, + # so we're not keeping lists as strings. + # NOTE: This currently can't handle uninterpolated values like [${x.y}]! + if isinstance(result, str) and VARIABLE_RE.search(value): + result = value + return result + + def _get_section_ref(self, value: Any, *, parent: List[str] = []) -> Any: + """Get a single section reference.""" + if isinstance(value, str) and value.startswith(f'"{SECTION_PREFIX}'): + value = try_load_json(value) + if isinstance(value, str) and value.startswith(SECTION_PREFIX): + parts = value.replace(SECTION_PREFIX, "").split(".") + result = self + for item in parts: + try: + result = result[item] + except (KeyError, TypeError): # This should never happen + err_title = "Error parsing reference to config section" + err_msg = f"Section '{'.'.join(parts)}' is not defined" + err = [{"loc": parts, "msg": err_msg}] + raise ConfigValidationError( + config=self, errors=err, title=err_title + ) from None + return result + elif isinstance(value, str) and SECTION_PREFIX in value: + # String value references a section (either a dict or return + # value of promise). We can't allow this, since variables are + # always interpolated *before* configs are resolved. + err_desc = ( + "Can't reference whole sections or return values of function " + "blocks inside a string or list\n\nYou can change your variable to " + "reference a value instead. Keep in mind that it's not " + "possible to interpolate the return value of a registered " + "function, since variables are interpolated when the config " + "is loaded, and registered functions are resolved afterwards." + ) + err = [{"loc": parent, "msg": "uses section variable in string or list"}] + raise ConfigValidationError(errors=err, desc=err_desc) + return value + + def copy(self) -> "Config": + """Deepcopy the config.""" + try: + config = copy.deepcopy(self) + except Exception as e: + raise ValueError(f"Couldn't deep-copy config: {e}") from e + return Config( + config, + is_interpolated=self.is_interpolated, + section_order=self.section_order, + ) + + def merge( + self, updates: Union[Dict[str, Any], "Config"], remove_extra: bool = False + ) -> "Config": + """Deep merge the config with updates, using current as defaults.""" + defaults = self.copy() + updates = Config(updates).copy() + merged = deep_merge_configs(updates, defaults, remove_extra=remove_extra) + return Config( + merged, + is_interpolated=defaults.is_interpolated and updates.is_interpolated, + section_order=defaults.section_order, + ) + + def _sort( + self, data: Union["Config", "ConfigParser", Dict[str, Any]] + ) -> Dict[str, Any]: + """Sort sections using the currently defined sort order. Sort + sections by index on section order, if available, then alphabetic, and + account for subsections, which should always follow their parent. + """ + sort_map = {section: i for i, section in enumerate(self.section_order)} + sort_key = lambda x: ( + sort_map.get(x[0].split(".")[0], len(sort_map)), + _mask_positional_args(x[0]), + ) + return dict(sorted(data.items(), key=sort_key)) + + def _set_overrides(self, config: "ConfigParser", overrides: Dict[str, Any]) -> None: + """Set overrides in the ConfigParser before config is interpreted.""" + err_title = "Error parsing config overrides" + for key, value in overrides.items(): + err_msg = "not a section value that can be overridden" + err = [{"loc": key.split("."), "msg": err_msg}] + if "." not in key: + raise ConfigValidationError(errors=err, title=err_title) + section, option = key.rsplit(".", 1) + # Check for section and accept if option not in config[section] + if section not in config: + raise ConfigValidationError(errors=err, title=err_title) + config.set(section, option, try_dump_json(value, overrides)) + + def _validate_sections(self, config: "ConfigParser") -> None: + # If the config defines top-level properties that are not sections (e.g. + # if config was constructed from dict), those values would be added as + # [DEFAULTS] and included in *every other section*. This is usually not + # what we want and it can lead to very confusing results. + default_section = config.defaults() + if default_section: + err_title = "Found config values without a top-level section" + err_msg = "not part of a section" + err = [{"loc": [k], "msg": err_msg} for k in default_section] + raise ConfigValidationError(errors=err, title=err_title) + + def from_str( + self, text: str, *, interpolate: bool = True, overrides: Dict[str, Any] = {} + ) -> "Config": + """Load the config from a string.""" + config = get_configparser(interpolate=interpolate) + if overrides: + config = get_configparser(interpolate=False) + try: + config.read_string(text) + except ParsingError as e: + desc = f"Make sure the sections and values are formatted correctly.\n\n{e}" + raise ConfigValidationError(desc=desc) from None + config._sections = self._sort(config._sections) + self._set_overrides(config, overrides) + self.clear() + self.interpret_config(config) + if overrides and interpolate: + # do the interpolation. Avoids recursion because the new call from_str call will have overrides as empty + self = self.interpolate() + self.is_interpolated = interpolate + return self + + def to_str(self, *, interpolate: bool = True) -> str: + """Write the config to a string.""" + flattened = get_configparser(interpolate=interpolate) + queue: List[Tuple[tuple, "Config"]] = [(tuple(), self)] + for path, node in queue: + section_name = ".".join(path) + is_kwarg = path and path[-1] != "*" + if is_kwarg and not flattened.has_section(section_name): + # Always create sections for non-'*' sections, not only if + # they have leaf entries, as we don't want to expand + # blocks that are undefined + flattened.add_section(section_name) + for key, value in node.items(): + if hasattr(value, "items"): + # Reference to a function with no arguments, serialize + # inline as a dict and don't create new section + if registry.is_promise(value) and len(value) == 1 and is_kwarg: + flattened.set(section_name, key, try_dump_json(value, node)) + else: + queue.append((path + (key,), value)) + else: + flattened.set(section_name, key, try_dump_json(value, node)) + # Order so subsection follow parent (not all sections, then all subs etc.) + flattened._sections = self._sort(flattened._sections) + self._validate_sections(flattened) + string_io = io.StringIO() + flattened.write(string_io) + return string_io.getvalue().strip() + + def to_bytes(self, *, interpolate: bool = True) -> bytes: + """Serialize the config to a byte string.""" + return self.to_str(interpolate=interpolate).encode("utf8") + + def from_bytes( + self, + bytes_data: bytes, + *, + interpolate: bool = True, + overrides: Dict[str, Any] = {}, + ) -> "Config": + """Load the config from a byte string.""" + return self.from_str( + bytes_data.decode("utf8"), interpolate=interpolate, overrides=overrides + ) + + def to_disk(self, path: Union[str, Path], *, interpolate: bool = True): + """Serialize the config to a file.""" + path = Path(path) if isinstance(path, str) else path + with path.open("w", encoding="utf8") as file_: + file_.write(self.to_str(interpolate=interpolate)) + + def from_disk( + self, + path: Union[str, Path], + *, + interpolate: bool = True, + overrides: Dict[str, Any] = {}, + ) -> "Config": + """Load config from a file.""" + path = Path(path) if isinstance(path, str) else path + with path.open("r", encoding="utf8") as file_: + text = file_.read() + return self.from_str(text, interpolate=interpolate, overrides=overrides) + + +def _mask_positional_args(name: str) -> List[Optional[str]]: + """Create a section name representation that masks names + of positional arguments to retain their order in sorts.""" + + stable_name = cast(List[Optional[str]], name.split(".")) + + # Remove names of sections that are a positional argument. + for i in range(1, len(stable_name)): + if stable_name[i - 1] == "*": + stable_name[i] = None + + return stable_name + + +def try_load_json(value: str) -> Any: + """Load a JSON string if possible, otherwise default to original value.""" + try: + return srsly.json_loads(value) + except Exception: + return value + + +def try_dump_json(value: Any, data: Union[Dict[str, dict], Config, str] = "") -> str: + """Dump a config value as JSON and output user-friendly error if it fails.""" + # Special case if we have a variable: it's already a string so don't dump + # to preserve ${x:y} vs. "${x:y}" + if isinstance(value, str) and VARIABLE_RE.search(value): + return value + if isinstance(value, str) and value.replace(".", "", 1).isdigit(): + # Work around values that are strings but numbers + value = f'"{value}"' + try: + value = srsly.json_dumps(value) + value = re.sub(r"\$([^{])", "$$\1", value) + value = re.sub(r"\$$", "$$", value) + return value + except Exception as e: + err_msg = ( + f"Couldn't serialize config value of type {type(value)}: {e}. Make " + f"sure all values in your config are JSON-serializable. If you want " + f"to include Python objects, use a registered function that returns " + f"the object instead." + ) + raise ConfigValidationError(config=data, desc=err_msg) from e + + +def deep_merge_configs( + config: Union[Dict[str, Any], Config], + defaults: Union[Dict[str, Any], Config], + *, + remove_extra: bool = False, +) -> Union[Dict[str, Any], Config]: + """Deep merge two configs.""" + if remove_extra: + # Filter out values in the original config that are not in defaults + keys = list(config.keys()) + for key in keys: + if key not in defaults: + del config[key] + for key, value in defaults.items(): + if isinstance(value, dict): + node = config.setdefault(key, {}) + if not isinstance(node, dict): + continue + value_promises = [k for k in value if k.startswith("@")] + value_promise = value_promises[0] if value_promises else None + node_promises = [k for k in node if k.startswith("@")] if node else [] + node_promise = node_promises[0] if node_promises else None + # We only update the block from defaults if it refers to the same + # registered function + if ( + value_promise + and node_promise + and ( + value_promise in node + and node[value_promise] != value[value_promise] + ) + ): + continue + if node_promise and ( + node_promise not in value or node[node_promise] != value[node_promise] + ): + continue + defaults = deep_merge_configs(node, value, remove_extra=remove_extra) + elif key not in config: + config[key] = value + return config + + +class ConfigValidationError(ValueError): + def __init__( + self, + *, + config: Optional[Union[Config, Dict[str, Dict[str, Any]], str]] = None, + errors: Union[Sequence[Mapping[str, Any]], Iterable[Dict[str, Any]]] = tuple(), + title: Optional[str] = "Config validation error", + desc: Optional[str] = None, + parent: Optional[str] = None, + show_config: bool = True, + ) -> None: + """Custom error for validating configs. + + config (Union[Config, Dict[str, Dict[str, Any]], str]): The + config the validation error refers to. + errors (Union[Sequence[Mapping[str, Any]], Iterable[Dict[str, Any]]]): + A list of errors as dicts with keys "loc" (list of strings + describing the path of the value), "msg" (validation message + to show) and optional "type" (mostly internals). + Same format as produced by pydantic's validation error (e.errors()). + title (str): The error title. + desc (str): Optional error description, displayed below the title. + parent (str): Optional parent to use as prefix for all error locations. + For example, parent "element" will result in "element -> a -> b". + show_config (bool): Whether to print the whole config with the error. + + ATTRIBUTES: + config (Union[Config, Dict[str, Dict[str, Any]], str]): The config. + errors (Iterable[Dict[str, Any]]): The errors. + error_types (Set[str]): All "type" values defined in the errors, if + available. This is most relevant for the pydantic errors that define + types like "type_error.integer". This attribute makes it easy to + check if a config validation error includes errors of a certain + type, e.g. to log additional information or custom help messages. + title (str): The title. + desc (str): The description. + parent (str): The parent. + show_config (bool): Whether to show the config. + text (str): The formatted error text. + """ + self.config = config + self.errors = errors + self.title = title + self.desc = desc + self.parent = parent + self.show_config = show_config + self.error_types = set() + for error in self.errors: + err_type = error.get("type") + if err_type: + self.error_types.add(err_type) + self.text = self._format() + ValueError.__init__(self, self.text) + + @classmethod + def from_error( + cls, + err: "ConfigValidationError", + title: Optional[str] = None, + desc: Optional[str] = None, + parent: Optional[str] = None, + show_config: Optional[bool] = None, + ) -> "ConfigValidationError": + """Create a new ConfigValidationError based on an existing error, e.g. + to re-raise it with different settings. If no overrides are provided, + the values from the original error are used. + + err (ConfigValidationError): The original error. + title (str): Overwrite error title. + desc (str): Overwrite error description. + parent (str): Overwrite error parent. + show_config (bool): Overwrite whether to show config. + RETURNS (ConfigValidationError): The new error. + """ + return cls( + config=err.config, + errors=err.errors, + title=title if title is not None else err.title, + desc=desc if desc is not None else err.desc, + parent=parent if parent is not None else err.parent, + show_config=show_config if show_config is not None else err.show_config, + ) + + def _format(self) -> str: + """Format the error message.""" + loc_divider = "->" + data = [] + for error in self.errors: + err_loc = f" {loc_divider} ".join([str(p) for p in error.get("loc", [])]) + if self.parent: + err_loc = f"{self.parent} {loc_divider} {err_loc}" + data.append((err_loc, error.get("msg"))) + result = [] + if self.title: + result.append(self.title) + if self.desc: + result.append(self.desc) + if data: + result.append("\n".join([f"{entry[0]}\t{entry[1]}" for entry in data])) + if self.config and self.show_config: + result.append(f"{self.config}") + return "\n\n" + "\n".join(result) + + +def alias_generator(name: str) -> str: + """Generate field aliases in promise schema.""" + # Underscore fields are not allowed in model, so use alias + if name == ARGS_FIELD_ALIAS: + return ARGS_FIELD + # Auto-alias fields that shadow base model attributes + if name in RESERVED_FIELDS: + return RESERVED_FIELDS[name] + return name + + +def copy_model_field(field: ModelField, type_: Any) -> ModelField: + """Copy a model field and assign a new type, e.g. to accept an Any type + even though the original value is typed differently. + """ + return ModelField( + name=field.name, + type_=type_, + class_validators=field.class_validators, + model_config=field.model_config, + default=field.default, + default_factory=field.default_factory, + required=field.required, + alias=field.alias, + ) + + +class EmptySchema(BaseModel): + class Config: + extra = "allow" + arbitrary_types_allowed = True + + +class _PromiseSchemaConfig: + extra = "forbid" + arbitrary_types_allowed = True + alias_generator = alias_generator + + +@dataclass +class Promise: + registry: str + name: str + args: List[str] + kwargs: Dict[str, Any] + + +class registry: + @classmethod + def has(cls, registry_name: str, func_name: str) -> bool: + """Check whether a function is available in a registry.""" + if not hasattr(cls, registry_name): + return False + reg = getattr(cls, registry_name) + return func_name in reg + + @classmethod + def get(cls, registry_name: str, func_name: str) -> Callable: + """Get a registered function from a given registry.""" + if not hasattr(cls, registry_name): + raise ValueError(f"Unknown registry: '{registry_name}'") + reg = getattr(cls, registry_name) + func = reg.get(func_name) + if func is None: + raise ValueError(f"Could not find '{func_name}' in '{registry_name}'") + return func + + @classmethod + def resolve( + cls, + config: Union[Config, Dict[str, Dict[str, Any]]], + *, + schema: Type[BaseModel] = EmptySchema, + overrides: Dict[str, Any] = {}, + validate: bool = True, + ) -> Dict[str, Any]: + resolved, _ = cls._make( + config, schema=schema, overrides=overrides, validate=validate, resolve=True + ) + return resolved + + @classmethod + def fill( + cls, + config: Union[Config, Dict[str, Dict[str, Any]]], + *, + schema: Type[BaseModel] = EmptySchema, + overrides: Dict[str, Any] = {}, + validate: bool = True, + ): + _, filled = cls._make( + config, schema=schema, overrides=overrides, validate=validate, resolve=False + ) + return filled + + @classmethod + def _make( + cls, + config: Union[Config, Dict[str, Dict[str, Any]]], + *, + schema: Type[BaseModel] = EmptySchema, + overrides: Dict[str, Any] = {}, + resolve: bool = True, + validate: bool = True, + ) -> Tuple[Dict[str, Any], Config]: + """Unpack a config dictionary and create two versions of the config: + a resolved version with objects from the registry created recursively, + and a filled version with all references to registry functions left + intact, but filled with all values and defaults based on the type + annotations. If validate=True, the config will be validated against the + type annotations of the registered functions referenced in the config + (if available) and/or the schema (if available). + """ + # Valid: {"optimizer": {"@optimizers": "my_cool_optimizer", "rate": 1.0}} + # Invalid: {"@optimizers": "my_cool_optimizer", "rate": 1.0} + if cls.is_promise(config): + err_msg = "The top-level config object can't be a reference to a registered function." + raise ConfigValidationError(config=config, errors=[{"msg": err_msg}]) + # If a Config was loaded with interpolate=False, we assume it needs to + # be interpolated first, otherwise we take it at face value + is_interpolated = not isinstance(config, Config) or config.is_interpolated + section_order = config.section_order if isinstance(config, Config) else None + orig_config = config + if not is_interpolated: + config = Config(orig_config).interpolate() + filled, _, resolved = cls._fill( + config, schema, validate=validate, overrides=overrides, resolve=resolve + ) + filled = Config(filled, section_order=section_order) + # Check that overrides didn't include invalid properties not in config + if validate: + cls._validate_overrides(filled, overrides) + # Merge the original config back to preserve variables if we started + # with a config that wasn't interpolated. Here, we prefer variables to + # allow auto-filling a non-interpolated config without destroying + # variable references. + if not is_interpolated: + filled = filled.merge( + Config(orig_config, is_interpolated=False), remove_extra=True + ) + return dict(resolved), filled + + @classmethod + def _fill( + cls, + config: Union[Config, Dict[str, Dict[str, Any]]], + schema: Type[BaseModel] = EmptySchema, + *, + validate: bool = True, + resolve: bool = True, + parent: str = "", + overrides: Dict[str, Dict[str, Any]] = {}, + ) -> Tuple[ + Union[Dict[str, Any], Config], Union[Dict[str, Any], Config], Dict[str, Any] + ]: + """Build three representations of the config: + 1. All promises are preserved (just like config user would provide). + 2. Promises are replaced by their return values. This is the validation + copy and will be parsed by pydantic. It lets us include hacks to + work around problems (e.g. handling of generators). + 3. Final copy with promises replaced by their return values. + """ + filled: Dict[str, Any] = {} + validation: Dict[str, Any] = {} + final: Dict[str, Any] = {} + for key, value in config.items(): + # If the field name is reserved, we use its alias for validation + v_key = RESERVED_FIELDS.get(key, key) + key_parent = f"{parent}.{key}".strip(".") + if key_parent in overrides: + value = overrides[key_parent] + config[key] = value + if cls.is_promise(value): + if key in schema.__fields__ and not resolve: + # If we're not resolving the config, make sure that the field + # expecting the promise is typed Any so it doesn't fail + # validation if it doesn't receive the function return value + field = schema.__fields__[key] + schema.__fields__[key] = copy_model_field(field, Any) + promise_schema = cls.make_promise_schema(value, resolve=resolve) + filled[key], validation[v_key], final[key] = cls._fill( + value, + promise_schema, + validate=validate, + resolve=resolve, + parent=key_parent, + overrides=overrides, + ) + reg_name, func_name = cls.get_constructor(final[key]) + args, kwargs = cls.parse_args(final[key]) + if resolve: + # Call the function and populate the field value. We can't + # just create an instance of the type here, since this + # wouldn't work for generics / more complex custom types + getter = cls.get(reg_name, func_name) + # We don't want to try/except this and raise our own error + # here, because we want the traceback if the function fails. + getter_result = getter(*args, **kwargs) + else: + # We're not resolving and calling the function, so replace + # the getter_result with a Promise class + getter_result = Promise( + registry=reg_name, name=func_name, args=args, kwargs=kwargs + ) + validation[v_key] = getter_result + final[key] = getter_result + if isinstance(validation[v_key], GeneratorType): + # If value is a generator we can't validate type without + # consuming it (which doesn't work if it's infinite – see + # schedule for examples). So we skip it. + validation[v_key] = [] + elif hasattr(value, "items"): + field_type = EmptySchema + if key in schema.__fields__: + field = schema.__fields__[key] + field_type = field.type_ + if not isinstance(field.type_, ModelMetaclass): + # If we don't have a pydantic schema and just a type + field_type = EmptySchema + filled[key], validation[v_key], final[key] = cls._fill( + value, + field_type, + validate=validate, + resolve=resolve, + parent=key_parent, + overrides=overrides, + ) + if key == ARGS_FIELD and isinstance(validation[v_key], dict): + # If the value of variable positional args is a dict (e.g. + # created via config blocks), only use its values + validation[v_key] = list(validation[v_key].values()) + final[key] = list(final[key].values()) + + if ARGS_FIELD_ALIAS in schema.__fields__ and not resolve: + # If we're not resolving the config, make sure that the field + # expecting the promise is typed Any so it doesn't fail + # validation if it doesn't receive the function return value + field = schema.__fields__[ARGS_FIELD_ALIAS] + schema.__fields__[ARGS_FIELD_ALIAS] = copy_model_field( + field, Any + ) + else: + filled[key] = value + # Prevent pydantic from consuming generator if part of a union + validation[v_key] = ( + value if not isinstance(value, GeneratorType) else [] + ) + final[key] = value + # Now that we've filled in all of the promises, update with defaults + # from schema, and validate if validation is enabled + exclude = [] + if validate: + try: + result = schema.parse_obj(validation) + except ValidationError as e: + raise ConfigValidationError( + config=config, errors=e.errors(), parent=parent + ) from None + else: + # Same as parse_obj, but without validation + result = schema.construct(**validation) + # If our schema doesn't allow extra values, we need to filter them + # manually because .construct doesn't parse anything + if schema.Config.extra in (Extra.forbid, Extra.ignore): + fields = schema.__fields__.keys() + # If we have a reserved field, we need to use its alias + field_set = [ + k if k != ARGS_FIELD else ARGS_FIELD_ALIAS + for k in result.__fields_set__ + ] + exclude = [k for k in field_set if k not in fields] + exclude_validation = set([ARGS_FIELD_ALIAS, *RESERVED_FIELDS.keys()]) + validation.update(result.dict(exclude=exclude_validation)) + filled, final = cls._update_from_parsed(validation, filled, final) + if exclude: + filled = {k: v for k, v in filled.items() if k not in exclude} + validation = {k: v for k, v in validation.items() if k not in exclude} + final = {k: v for k, v in final.items() if k not in exclude} + return filled, validation, final + + @classmethod + def _update_from_parsed( + cls, validation: Dict[str, Any], filled: Dict[str, Any], final: Dict[str, Any] + ): + """Update the final result with the parsed config like converted + values recursively. + """ + for key, value in validation.items(): + if key in RESERVED_FIELDS.values(): + continue # skip aliases for reserved fields + if key not in filled: + filled[key] = value + if key not in final: + final[key] = value + if isinstance(value, dict): + filled[key], final[key] = cls._update_from_parsed( + value, filled[key], final[key] + ) + # Update final config with parsed value if they're not equal (in + # value and in type) but not if it's a generator because we had to + # replace that to validate it correctly + elif key == ARGS_FIELD: + continue # don't substitute if list of positional args + # Check numpy first, just in case. Use stringified type so that numpy dependency can be ditched. + elif str(type(value)) == "": + final[key] = value + elif ( + value != final[key] or not isinstance(type(value), type(final[key])) + ) and not isinstance(final[key], GeneratorType): + final[key] = value + return filled, final + + @classmethod + def _validate_overrides(cls, filled: Config, overrides: Dict[str, Any]): + """Validate overrides against a filled config to make sure there are + no references to properties that don't exist and weren't used.""" + error_msg = "Invalid override: config value doesn't exist" + errors = [] + for override_key in overrides.keys(): + if not cls._is_in_config(override_key, filled): + errors.append({"msg": error_msg, "loc": [override_key]}) + if errors: + raise ConfigValidationError(config=filled, errors=errors) + + @classmethod + def _is_in_config(cls, prop: str, config: Union[Dict[str, Any], Config]): + """Check whether a nested config property like "section.subsection.key" + is in a given config.""" + tree = prop.split(".") + obj = dict(config) + while tree: + key = tree.pop(0) + if isinstance(obj, dict) and key in obj: + obj = obj[key] + else: + return False + return True + + @classmethod + def is_promise(cls, obj: Any) -> bool: + """Check whether an object is a "promise", i.e. contains a reference + to a registered function (via a key starting with `"@"`. + """ + if not hasattr(obj, "keys"): + return False + id_keys = [k for k in obj.keys() if k.startswith("@")] + if len(id_keys): + return True + return False + + @classmethod + def get_constructor(cls, obj: Dict[str, Any]) -> Tuple[str, str]: + id_keys = [k for k in obj.keys() if k.startswith("@")] + if len(id_keys) != 1: + err_msg = f"A block can only contain one function registry reference. Got: {id_keys}" + raise ConfigValidationError(config=obj, errors=[{"msg": err_msg}]) + else: + key = id_keys[0] + value = obj[key] + return (key[1:], value) + + @classmethod + def parse_args(cls, obj: Dict[str, Any]) -> Tuple[List[Any], Dict[str, Any]]: + args = [] + kwargs = {} + for key, value in obj.items(): + if not key.startswith("@"): + if key == ARGS_FIELD: + args = value + elif key in RESERVED_FIELDS.values(): + continue + else: + kwargs[key] = value + return args, kwargs + + @classmethod + def make_promise_schema( + cls, obj: Dict[str, Any], *, resolve: bool = True + ) -> Type[BaseModel]: + """Create a schema for a promise dict (referencing a registry function) + by inspecting the function signature. + """ + reg_name, func_name = cls.get_constructor(obj) + if not resolve and not cls.has(reg_name, func_name): + return EmptySchema + func = cls.get(reg_name, func_name) + # Read the argument annotations and defaults from the function signature + id_keys = [k for k in obj.keys() if k.startswith("@")] + sig_args: Dict[str, Any] = {id_keys[0]: (str, ...)} + for param in inspect.signature(func).parameters.values(): + # If no annotation is specified assume it's anything + annotation = param.annotation if param.annotation != param.empty else Any + # If no default value is specified assume that it's required + default = param.default if param.default != param.empty else ... + # Handle spread arguments and use their annotation as Sequence[whatever] + if param.kind == param.VAR_POSITIONAL: + spread_annot = Sequence[annotation] # type: ignore + sig_args[ARGS_FIELD_ALIAS] = (spread_annot, default) + else: + name = RESERVED_FIELDS.get(param.name, param.name) + sig_args[name] = (annotation, default) + sig_args["__config__"] = _PromiseSchemaConfig + return create_model("ArgModel", **sig_args) + + +__all__ = [ + "Config", + "registry", + "ConfigValidationError", + "SimpleFrozenDict", + "SimpleFrozenList", +] diff --git a/TTS/Kokoro/.venv/Lib/site-packages/confection/py.typed b/TTS/Kokoro/.venv/Lib/site-packages/confection/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/TTS/Kokoro/.venv/Lib/site-packages/confection/util.py b/TTS/Kokoro/.venv/Lib/site-packages/confection/util.py new file mode 100644 index 0000000000000000000000000000000000000000..d48bc7884a2e4e73279a578c2df833a10da1814f --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/confection/util.py @@ -0,0 +1,143 @@ +import functools +import sys +from copy import deepcopy +from typing import Any, Callable, Iterator, TypeVar + +if sys.version_info < (3, 8): + # Ignoring type for mypy to avoid "Incompatible import" error (https://github.com/python/mypy/issues/4427). + from typing_extensions import Protocol # type: ignore +else: + from typing import Protocol + +_DIn = TypeVar("_DIn") + + +class Decorator(Protocol): + """Protocol to mark a function as returning its child with identical signature.""" + + def __call__(self, name: str) -> Callable[[_DIn], _DIn]: + ... + + +# This is how functools.partials seems to do it, too, to retain the return type +PartialT = TypeVar("PartialT") + + +def partial( + func: Callable[..., PartialT], *args: Any, **kwargs: Any +) -> Callable[..., PartialT]: + """Wrapper around functools.partial that retains docstrings and can include + other workarounds if needed. + """ + partial_func = functools.partial(func, *args, **kwargs) + partial_func.__doc__ = func.__doc__ + return partial_func + + +class Generator(Iterator): + """Custom generator type. Used to annotate function arguments that accept + generators so they can be validated by pydantic (which doesn't support + iterators/iterables otherwise). + """ + + @classmethod + def __get_validators__(cls): + yield cls.validate + + @classmethod + def validate(cls, v): + if not hasattr(v, "__iter__") and not hasattr(v, "__next__"): + raise TypeError("not a valid iterator") + return v + + +DEFAULT_FROZEN_DICT_ERROR = ( + "Can't write to frozen dictionary. This is likely an internal " + "error. Are you writing to a default function argument?" +) + +DEFAULT_FROZEN_LIST_ERROR = ( + "Can't write to frozen list. Maybe you're trying to modify a computed " + "property or default function argument?" +) + + +class SimpleFrozenDict(dict): + """Simplified implementation of a frozen dict, mainly used as default + function or method argument (for arguments that should default to empty + dictionary). Will raise an error if the user attempts to add to dict. + """ + + def __init__( + self, + *args, + error: str = DEFAULT_FROZEN_DICT_ERROR, + **kwargs, + ) -> None: + """Initialize the frozen dict. Can be initialized with pre-defined + values. + + error (str): The error message when user tries to assign to dict. + """ + super().__init__(*args, **kwargs) + self.error = error + + def __setitem__(self, key, value): + raise NotImplementedError(self.error) + + def pop(self, key, default=None): + raise NotImplementedError(self.error) + + def update(self, other): + raise NotImplementedError(self.error) + + def __deepcopy__(self, memo): + return self.__class__(deepcopy({k: v for k, v in self.items()})) + + +class SimpleFrozenList(list): + """Wrapper class around a list that lets us raise custom errors if certain + attributes/methods are accessed. Mostly used for properties that return an + immutable list (and that we don't want to convert to a tuple to not break + too much backwards compatibility). If a user accidentally calls + frozen_list.append(), we can raise a more helpful error. + """ + + def __init__( + self, + *args, + error: str = DEFAULT_FROZEN_LIST_ERROR, + ) -> None: + """Initialize the frozen list. + + error (str): The error message when user tries to mutate the list. + """ + self.error = error + super().__init__(*args) + + def append(self, *args, **kwargs): + raise NotImplementedError(self.error) + + def clear(self, *args, **kwargs): + raise NotImplementedError(self.error) + + def extend(self, *args, **kwargs): + raise NotImplementedError(self.error) + + def insert(self, *args, **kwargs): + raise NotImplementedError(self.error) + + def pop(self, *args, **kwargs): + raise NotImplementedError(self.error) + + def remove(self, *args, **kwargs): + raise NotImplementedError(self.error) + + def reverse(self, *args, **kwargs): + raise NotImplementedError(self.error) + + def sort(self, *args, **kwargs): + raise NotImplementedError(self.error) + + def __deepcopy__(self, memo): + return self.__class__(deepcopy(v) for v in self) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/csvw-3.7.0.dist-info/INSTALLER b/TTS/Kokoro/.venv/Lib/site-packages/csvw-3.7.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/csvw-3.7.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/TTS/Kokoro/.venv/Lib/site-packages/csvw-3.7.0.dist-info/LICENSE b/TTS/Kokoro/.venv/Lib/site-packages/csvw-3.7.0.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/csvw-3.7.0.dist-info/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/TTS/Kokoro/.venv/Lib/site-packages/csvw-3.7.0.dist-info/METADATA b/TTS/Kokoro/.venv/Lib/site-packages/csvw-3.7.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..a76a402a5f50d35f49e6220297c5e345350ecac3 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/csvw-3.7.0.dist-info/METADATA @@ -0,0 +1,301 @@ +Metadata-Version: 2.1 +Name: csvw +Version: 3.7.0 +Summary: Python library to work with CSVW described tabular data +Home-page: https://github.com/cldf/csvw +Author: Robert Forkel +Author-email: robert_forkel@eva.mpg.de +License: Apache 2.0 +Project-URL: Bug Tracker, https://github.com/cldf/csvw/issues +Keywords: csv,w3c,tabular-data +Platform: any +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Science/Research +Classifier: Natural Language :: English +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: License :: OSI Approved :: Apache Software License +Requires-Python: >=3.8 +Description-Content-Type: text/markdown +License-File: LICENSE +Requires-Dist: attrs>=18.1 +Requires-Dist: isodate +Requires-Dist: python-dateutil +Requires-Dist: rfc3986<2 +Requires-Dist: uritemplate>=3.0.0 +Requires-Dist: babel +Requires-Dist: requests +Requires-Dist: language-tags +Requires-Dist: rdflib +Requires-Dist: termcolor +Requires-Dist: jsonschema +Provides-Extra: dev +Requires-Dist: flake8; extra == "dev" +Requires-Dist: wheel; extra == "dev" +Requires-Dist: twine; extra == "dev" +Requires-Dist: build; extra == "dev" +Provides-Extra: docs +Requires-Dist: sphinx<7; extra == "docs" +Requires-Dist: sphinx-autodoc-typehints; extra == "docs" +Requires-Dist: sphinx-rtd-theme; extra == "docs" +Provides-Extra: test +Requires-Dist: frictionless; extra == "test" +Requires-Dist: pytest>=5; extra == "test" +Requires-Dist: pytest-mock; extra == "test" +Requires-Dist: requests-mock; extra == "test" +Requires-Dist: pytest-cov; extra == "test" + +# csvw + +[![Build Status](https://github.com/cldf/csvw/workflows/tests/badge.svg)](https://github.com/cldf/csvw/actions?query=workflow%3Atests) +[![PyPI](https://img.shields.io/pypi/v/csvw.svg)](https://pypi.org/project/csvw) +[![Documentation Status](https://readthedocs.org/projects/csvw/badge/?version=latest)](https://csvw.readthedocs.io/en/latest/?badge=latest) + + +This package provides +- a Python API to read and write relational, tabular data according to the [CSV on the Web](https://csvw.org/) specification and +- commandline tools for reading and validating CSVW data. + + +## Links + +- GitHub: https://github.com/cldf/csvw +- PyPI: https://pypi.org/project/csvw +- Issue Tracker: https://github.com/cldf/csvw/issues + + +## Installation + +This package runs under Python >=3.8, use pip to install: + +```bash +$ pip install csvw +``` + + +## CLI + +### `csvw2json` + +Converting CSVW data [to JSON](https://www.w3.org/TR/csv2json/) + +```shell +$ csvw2json tests/fixtures/zipped-metadata.json +{ + "tables": [ + { + "url": "tests/fixtures/zipped.csv", + "row": [ + { + "url": "tests/fixtures/zipped.csv#row=2", + "rownum": 1, + "describes": [ + { + "ID": "abc", + "Value": "the value" + } + ] + }, + { + "url": "tests/fixtures/zipped.csv#row=3", + "rownum": 2, + "describes": [ + { + "ID": "cde", + "Value": "another one" + } + ] + } + ] + } + ] +} +``` + +### `csvwvalidate` + +Validating CSVW data + +```shell +$ csvwvalidate tests/fixtures/zipped-metadata.json +OK +``` + +### `csvwdescribe` + +Describing tabular-data files with CSVW metadata + +```shell +$ csvwdescribe --delimiter "|" tests/fixtures/frictionless-data.csv +{ + "@context": "http://www.w3.org/ns/csvw", + "dc:conformsTo": "data-package", + "tables": [ + { + "dialect": { + "delimiter": "|" + }, + "tableSchema": { + "columns": [ + { + "datatype": "string", + "name": "FK" + }, + { + "datatype": "integer", + "name": "Year" + }, + { + "datatype": "string", + "name": "Location name" + }, + { + "datatype": "string", + "name": "Value" + }, + { + "datatype": "string", + "name": "binary" + }, + { + "datatype": "string", + "name": "anyURI" + }, + { + "datatype": "string", + "name": "email" + }, + { + "datatype": "string", + "name": "boolean" + }, + { + "datatype": { + "dc:format": "application/json", + "base": "json" + }, + "name": "array" + }, + { + "datatype": { + "dc:format": "application/json", + "base": "json" + }, + "name": "geojson" + } + ] + }, + "url": "tests/fixtures/frictionless-data.csv" + } + ] +} +``` + + +## Python API + +Find the Python API documentation at [csvw.readthedocs.io](https://csvw.readthedocs.io/en/latest/). + +A quick example for using `csvw` from Python code: + +```python +import json +from csvw import CSVW +data = CSVW('https://raw.githubusercontent.com/cldf/csvw/master/tests/fixtures/test.tsv') +print(json.dumps(data.to_json(minimal=True), indent=4)) +[ + { + "province": "Hello", + "territory": "world", + "precinct": "1" + } +] +``` + + +## Known limitations + +- We read **all** data which is specified as UTF-8 encoded using the + [`utf-8-sig` codecs](https://docs.python.org/3/library/codecs.html#module-encodings.utf_8_sig). + Thus, if such data starts with `U+FEFF` this will be interpreted as [BOM](https://en.wikipedia.org/wiki/Byte_order_mark) + and skipped. +- Low level CSV parsing is delegated to the `csv` module in Python's standard library. Thus, if a `commentPrefix` + is specified in a `Dialect` instance, this will lead to skipping rows where the first value starts + with `commentPrefix`, **even if the value was quoted**. +- Also, cell content containing `escapechar` may not be round-tripped as expected (when specifying + `escapechar` or a `csvw.Dialect` with `quoteChar` but `doubleQuote==False`), + when minimal quoting is specified. This is due to inconsistent `csv` behaviour + across Python versions (see https://bugs.python.org/issue44861). + + +## CSVW conformance + +While we use the CSVW specification as guideline, this package does not (and +probably never will) implement the full extent of this spec. + +- When CSV files with a header are read, columns are not matched in order with + column descriptions in the `tableSchema`, but instead are matched based on the + CSV column header and the column descriptions' `name` and `titles` atributes. + This allows for more flexibility, because columns in the CSV file may be + re-ordered without invalidating the metadata. A stricter matching can be forced + by specifying `"header": false` and `"skipRows": 1` in the table's dialect + description. + +However, `csvw.CSVW` works correctly for +- 269 out of 270 [JSON tests](https://w3c.github.io/csvw/tests/#manifest-json), +- 280 out of 282 [validation tests](https://w3c.github.io/csvw/tests/#manifest-validation), +- 10 out of 18 [non-normative tests](https://w3c.github.io/csvw/tests/#manifest-nonnorm) + +from the [CSVW Test suites](https://w3c.github.io/csvw/tests/). + + +## Compatibility with [Frictionless Data Specs](https://specs.frictionlessdata.io/) + +A CSVW-described dataset is basically equivalent to a Frictionless DataPackage where all +[Data Resources](https://specs.frictionlessdata.io/data-resource/) are [Tabular Data](https://specs.frictionlessdata.io/tabular-data-resource/). +Thus, the `csvw` package provides some conversion functionality. To +"read CSVW data from a Data Package", there's the `csvw.TableGroup.from_frictionless_datapackage` method: +```python +from csvw import TableGroup +tg = TableGroup.from_frictionless_datapackage('PATH/TO/datapackage.json') +``` +To convert the metadata, the `TableGroup` can then be serialzed: +```python +tg.to_file('csvw-metadata.json') +``` + +Note that the CSVW metadata file must be written to the Data Package's directory +to make sure relative paths to data resources work. + +This functionality - together with the schema inference capabilities +of [`frictionless describe`](https://framework.frictionlessdata.io/docs/guides/describing-data/) - provides +a convenient way to bootstrap CSVW metadata for a set of "raw" CSV +files, implemented in the [`csvwdescribe` command described above](#csvwdescribe). + + +## See also + +- https://www.w3.org/2013/csvw/wiki/Main_Page +- https://csvw.org +- https://github.com/CLARIAH/COW +- https://github.com/CLARIAH/ruminator +- https://github.com/bloomberg/pycsvw +- https://specs.frictionlessdata.io/table-schema/ +- https://github.com/theodi/csvlint.rb +- https://github.com/ruby-rdf/rdf-tabular +- https://github.com/rdf-ext/rdf-parser-csvw +- https://github.com/Robsteranium/csvwr + + +## License + +This package is distributed under the [Apache 2.0 license](https://opensource.org/licenses/Apache-2.0). diff --git a/TTS/Kokoro/.venv/Lib/site-packages/csvw-3.7.0.dist-info/RECORD b/TTS/Kokoro/.venv/Lib/site-packages/csvw-3.7.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..6e23bfc8cf553bfa49d7d158f5eb453e92ce32a9 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/csvw-3.7.0.dist-info/RECORD @@ -0,0 +1,33 @@ +../../Scripts/csvw2datasette.exe,sha256=dqEjTZxR5Dcu1mKKRIZw3bPEtofwEPS4NIcpyyYJ5Uk,108396 +../../Scripts/csvw2json.exe,sha256=-sQdGj1yfarDuHeXBZHCR-Z5glgEeR6exPX0Qi3tFlI,108386 +../../Scripts/csvw2markdown.exe,sha256=CW1sVb9mZC3F5kj5YKQFIa8-XawSSMpg5CcE0fLqpjQ,108394 +../../Scripts/csvw2sqlite.exe,sha256=aKviCAO96DS7KKXahS2BJSFoER6HnCSarn0xxov4AT0,108390 +../../Scripts/csvwdescribe.exe,sha256=cAugtD9btqFSJ3CBEDSw6u1qC-D21ILGus8pEo6DbGY,108392 +../../Scripts/csvwvalidate.exe,sha256=KA4jH8fu8R2Q5CZnoz-Sl5li8BMkguPaW1wwqbog364,108392 +csvw-3.7.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +csvw-3.7.0.dist-info/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357 +csvw-3.7.0.dist-info/METADATA,sha256=VNInfVEiobvxNhBkU0khBflyNe9HclL-V2RoTi6DLJs,10159 +csvw-3.7.0.dist-info/RECORD,, +csvw-3.7.0.dist-info/WHEEL,sha256=TJ49d73sNs10F0aze1W_bTW2P_X7-F4YXOlBqoqA-jY,109 +csvw-3.7.0.dist-info/entry_points.txt,sha256=fk9IQtAGIpAeWAXe3I3xGNozh4ww_7b80c_vD2GFuEI,268 +csvw-3.7.0.dist-info/top_level.txt,sha256=mkl3l5vQaigdnccNcB3IT5J_Puu2Rp5PVYHqoUOh0Vo,5 +csvw/__init__.py,sha256=tuw2tzIid2s-ErfZD6uyB9FRDeJG45GwOk3oenFOpwI,781 +csvw/__main__.py,sha256=h0R5f7kWgvjg8VwBPJRpiTROGY91ZgplGfZZkbGKn5U,5618 +csvw/__pycache__/__init__.cpython-312.pyc,, +csvw/__pycache__/__main__.cpython-312.pyc,, +csvw/__pycache__/datatypes.cpython-312.pyc,, +csvw/__pycache__/db.cpython-312.pyc,, +csvw/__pycache__/dsv.cpython-312.pyc,, +csvw/__pycache__/dsv_dialects.cpython-312.pyc,, +csvw/__pycache__/frictionless.cpython-312.pyc,, +csvw/__pycache__/jsonld.cpython-312.pyc,, +csvw/__pycache__/metadata.cpython-312.pyc,, +csvw/__pycache__/utils.cpython-312.pyc,, +csvw/datatypes.py,sha256=gKWd-WmoDgyoprmUioU3W7nsMu4N52cP1o45HyeJ3QQ,38609 +csvw/db.py,sha256=2iyFhMmioPJwww447wN1S6o1TcpW0Vz5cnR4zAfxwSU,25011 +csvw/dsv.py,sha256=WfbotNzcT9Q4k9Mqofqu3F8ARTYrVPetPNceJLQRDRM,16870 +csvw/dsv_dialects.py,sha256=TUVi-gtYXC-OhHQbZZykpvnOfHgghsFKk0wE7jokAaQ,5177 +csvw/frictionless.py,sha256=YuC36bL7Bs3elZ-MIpLBpcNIkKCt49jA0-VqGyNW4-0,8284 +csvw/jsonld.py,sha256=U6qp_gBXAMeBnwdgMsPHeUB6-NCZYWbv_BrH3EJGX2Q,6501 +csvw/metadata.py,sha256=UMtUxjycvGCgY23U93wzlHzU8QX1oIpg1F3de-jcK4w,73653 +csvw/utils.py,sha256=46wWXpjmpd7esW96MeCPydqCMQoXYxmblalwKmbnzrc,8280 diff --git a/TTS/Kokoro/.venv/Lib/site-packages/csvw-3.7.0.dist-info/WHEEL b/TTS/Kokoro/.venv/Lib/site-packages/csvw-3.7.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..17c0299e4939ec0b7f7cf5b02ed977ee81d70312 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/csvw-3.7.0.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: setuptools (75.2.0) +Root-Is-Purelib: true +Tag: py2-none-any +Tag: py3-none-any + diff --git a/TTS/Kokoro/.venv/Lib/site-packages/csvw-3.7.0.dist-info/entry_points.txt b/TTS/Kokoro/.venv/Lib/site-packages/csvw-3.7.0.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..e9402216205f69a9c13381fbe33da244c01dfae8 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/csvw-3.7.0.dist-info/entry_points.txt @@ -0,0 +1,7 @@ +[console_scripts] +csvw2datasette = csvw.__main__:csvw2datasette +csvw2json = csvw.__main__:csvw2json +csvw2markdown = csvw.__main__:csvw2markdown +csvw2sqlite = csvw.__main__:csvw2sqlite +csvwdescribe = csvw.__main__:csvwdescribe +csvwvalidate = csvw.__main__:csvwvalidate diff --git a/TTS/Kokoro/.venv/Lib/site-packages/csvw-3.7.0.dist-info/top_level.txt b/TTS/Kokoro/.venv/Lib/site-packages/csvw-3.7.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..1c9a63e96d032d440164fc41a82657b92a2bdf92 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/csvw-3.7.0.dist-info/top_level.txt @@ -0,0 +1 @@ +csvw diff --git a/TTS/Kokoro/.venv/Lib/site-packages/csvw/__init__.py b/TTS/Kokoro/.venv/Lib/site-packages/csvw/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7db4aecbec648bfc9f1c32de169ae1c5d1b11fb5 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/csvw/__init__.py @@ -0,0 +1,27 @@ +# csvw - https://w3c.github.io/csvw/primer/ + +from .metadata import ( + TableGroup, Table, Column, ForeignKey, Link, NaturalLanguage, Datatype, URITemplate, CSVW, + Dialect) + +from .dsv import (UnicodeWriter, + UnicodeReader, UnicodeReaderWithLineNumber, UnicodeDictReader, NamedTupleReader, + iterrows, rewrite) + +__all__ = [ + 'TableGroup', + 'Table', 'Column', 'ForeignKey', + 'Link', 'NaturalLanguage', + 'Datatype', + 'URITemplate', + 'Dialect', 'UnicodeWriter', + 'UnicodeReader', 'UnicodeReaderWithLineNumber', 'UnicodeDictReader', 'NamedTupleReader', + 'iterrows', 'rewrite', + 'CSVW', +] + +__title__ = 'csvw' +__version__ = '3.7.0' +__author__ = 'Robert Forkel' +__license__ = 'Apache 2.0, see LICENSE' +__copyright__ = 'Copyright (c) 2025 Robert Forkel' diff --git a/TTS/Kokoro/.venv/Lib/site-packages/csvw/__main__.py b/TTS/Kokoro/.venv/Lib/site-packages/csvw/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..3f599f80275df880281e79277016f81101145159 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/csvw/__main__.py @@ -0,0 +1,163 @@ +import sys +import json +import shutil +import pathlib +import argparse +import subprocess + +from termcolor import colored + +from csvw import CSVW, TableGroup +from csvw.db import Database +from csvw.utils import metadata2markdown + + +def parsed_args(desc, args, *argspecs): + if args is None: # pragma: no cover + parser = argparse.ArgumentParser(description=desc) + for kw, kwargs in argspecs: + parser.add_argument(*kw, **kwargs) + return parser.parse_args() + return args + + +def exit(ret, test=False): + if test: + return ret + sys.exit(ret) # pragma: no cover + + +def csvwdescribe(args=None, test=False): + frictionless = shutil.which('frictionless') + if not frictionless: # pragma: no cover + raise ValueError('The frictionless command must be installed for this functionality!\n' + 'Run `pip install frictionless` and try again.') + + args = parsed_args( + "Describe a (set of) CSV file(s) with basic CSVW metadata.", + args, + (['--delimiter'], dict(default=None)), + (['csv'], dict(nargs='+', help="CSV files to describe as CSVW TableGroup")), + ) + fargs = ['describe', '--json'] + if args.delimiter: + fargs.extend(['--dialect', '{"delimiter": "%s"}' % args.delimiter]) + onefile = False + if len(args.csv) == 1 and '*' not in args.csv[0]: + onefile = True + # Make sure we infer a tabular-data schema even if the file suffix does not suggest a CSV + # file. + fargs.extend(['--format', 'csv']) + else: + fargs.extend(['--type', 'package']) + + dp = json.loads(subprocess.check_output([frictionless] + fargs + args.csv)) + if onefile: + dp = dict(resources=[dp], profile='data-package') + + tg = TableGroup.from_frictionless_datapackage(dp) + print(json.dumps(tg.asdict(), indent=4)) + return exit(0, test=test) + + +def csvwvalidate(args=None, test=False): + args = parsed_args( + "Validate a (set of) CSV file(s) described by CSVW metadata.", + args, + (['url'], dict(help='URL or local path to CSV or JSON metadata file.')), + (['-v', '--verbose'], dict(action='store_true', default=False)), + ) + ret = 0 + try: + csvw = CSVW(args.url, validate=True) + if csvw.is_valid: + print(colored('OK', 'green', attrs=['bold'])) + else: + ret = 1 + print(colored('FAIL', 'red', attrs=['bold'])) + if args.verbose: + for w in csvw.warnings: + print(colored(str(w.message), 'blue')) + except ValueError as e: + ret = 2 + print(colored('FAIL', 'red', attrs=['bold'])) + if args.verbose: + print(colored(str(e), 'blue')) + return exit(ret, test=test) + + +def csvw2datasette(args=None, test=False): + args = parsed_args( + "Convert CSVW to data for datasette (https://datasette.io/).", + args, + (['url'], dict(help='URL or local path to CSV or JSON metadata file.')), + (['-o', '--outdir'], dict(type=pathlib.Path, default=pathlib.Path('.'))), + ) + dbname, mdname = 'datasette.db', 'datasette-metadata.json' + csvw = CSVW(args.url) + db = Database(csvw.tablegroup, fname=args.outdir / dbname) + db.write_from_tg() + md = {} + for k in ['title', 'description', 'license']: + if 'dc:{}'.format(k) in csvw.common_props: + md[k] = csvw.common_props['dc:{}'.format(k)] + # FIXME: flesh out, see https://docs.datasette.io/en/stable/metadata.html + args.outdir.joinpath(mdname).write_text(json.dumps(md, indent=4)) + print("""Run + datasette {} --metadata {} +and open your browser at + http://localhost:8001/ +to browse the data. +""".format(args.outdir / dbname, args.outdir / mdname)) + return exit(0, test=test) + + +def csvw2json(args=None, test=False): + args = parsed_args( + "Convert CSVW to JSON, see https://w3c.github.io/csvw/csv2json/", + args, + (['url'], dict(help='URL or local path to CSV or JSON metadata file.')), + ) + csvw = CSVW(args.url) + print(json.dumps(csvw.to_json(), indent=4)) + return exit(0, test=test) + + +def csvw2sqlite(args=None, test=False): # pragma: no cover + args = parsed_args( + "Convert CSVW to JSON, see https://w3c.github.io/csvw/csv2json/", + args, + ( + ['url'], + dict(help='URL or local path to CSVW metadata file describing a TableGroup.\n\n' + 'Note that not all valid CSVW datasets can be converted to SQLite. One ' + 'limitation is that all tables which are referenced by foreign keys must ' + 'have a primary key.')), + ( + ['output'], + dict(help='Path for the generated SQLite database file.')), + ) + tg = TableGroup.from_file(args.url) + db = Database(tg, args.output) + db.write_from_tg(_force=True) + return exit(0, test=test) + + +def csvw2markdown(args=None, test=False): + args = parsed_args( + "Convert CSVW to JSON, see https://w3c.github.io/csvw/csv2json/", + args, + ( + ['url'], + dict(help='URL or local path to CSVW metadata file describing a TableGroup.\n\n' + 'Note that not all valid CSVW datasets can be converted to SQLite. One ' + 'limitation is that all tables which are referenced by foreign keys must ' + 'have a primary key.')), + ) + tg = TableGroup.from_file(args.url) + print(metadata2markdown(tg, link_files=True)) + return exit(0, test=test) + + +if __name__ == '__main__': # pragma: no cover + csvw2json() diff --git a/TTS/Kokoro/.venv/Lib/site-packages/csvw/datatypes.py b/TTS/Kokoro/.venv/Lib/site-packages/csvw/datatypes.py new file mode 100644 index 0000000000000000000000000000000000000000..ad17973ae1018c9d483956c042a90a3cdae22b51 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/csvw/datatypes.py @@ -0,0 +1,1280 @@ +""" +We model the hierarchy of basic datatypes using a class hierarchy. + +`Derived datatypes `_ are implemented +via :class:`csvw.Datatype` which is +`composed of `_ +a basic datatype and additional behaviour. + +.. seealso:: http://w3c.github.io/csvw/metadata/#datatypes +""" +import re +import json as _json +import math +import base64 +import typing +import decimal as _decimal +import binascii +import datetime +import warnings +import itertools +import collections + +import isodate +import rfc3986 +import dateutil.parser +import babel.numbers +import babel.dates +import jsonschema + +if typing.TYPE_CHECKING: # pragma: no cover + import csvw + +__all__ = ['DATATYPES'] + +DATATYPES = {} + + +def register(cls): + DATATYPES[cls.name] = cls + return cls + + +def to_binary(s, encoding='utf-8'): + if not isinstance(s, bytes): + return bytes(s, encoding=encoding) + return s # pragma: no cover + + +@register +class anyAtomicType: + """ + A basic datatype consists of + + - a bag of attributes, most importantly a `name` which matches the name or alias of one of the \ + `CSVW built-in datatypes `_ + - three staticmethods controlling marshalling and unmarshalling of Python objects to strings. + + Theses methods are orchestrated from :class:`csvw.Datatype` in its `read` and `formatted` + methods. + """ + name = 'any' + minmax = False + example = 'x' + + @classmethod + def value_error(cls, v): + raise ValueError('invalid lexical value for {}: {}'.format(cls.name, v)) + + def __str__(self) -> str: + return self.name + + @staticmethod + def derived_description(datatype: "csvw.Datatype") -> dict: + return {} + + @staticmethod + def to_python(v: str, **kw) -> object: + return v # pragma: no cover + + @staticmethod + def to_string(v: object, **kw) -> str: + return '{}'.format(v) + + +@register +class string(anyAtomicType): + """ + Maps to `str`. + + The lexical and value spaces of xs:string are the set of all possible strings composed of + any character allowed in a XML 1.0 document without any treatment done on whitespaces. + """ + name = 'string' + + @staticmethod + def derived_description(datatype: "csvw.Datatype") -> dict: + if datatype.format: + # We wrap a regex specified as `format` property into a group and add `$` to + # make sure the whole string is matched when validating. + try: + return {'regex': re.compile(r'({})$'.format(datatype.format))} + except re.error: + warnings.warn('Invalid regex pattern as datatype format') + return {} + + @staticmethod + def to_python(v, regex=None): + if regex and not regex.match(v): + string.value_error(v) + return v + + +@register +class anyURI(string): + """ + Maps to `rfc3986.URIReference`. + + This datatype corresponds normatively to the XLink href attribute. Its value space includes + the URIs defined by the RFCs `2396 `_ and + `2732 `_, but its lexical space doesn’t + require the character escapes needed to include non-ASCII characters in URIs. + + .. note:: + + We normalize URLs according to the rules in + `RFC 3986 `_ when serializing + to `str`. Thus roundtripping isn't guaranteed. + """ + name = 'anyURI' + + @staticmethod + def to_python(v, regex=None): + res = string.to_python(v, regex=regex) + return rfc3986.URIReference.from_string(res.encode('utf-8')) + + @staticmethod + def to_string(v, **kw): + if hasattr(v, 'geturl'): + # Presumably a `urllib.parse.ParseResult`. + return v.geturl() + if hasattr(v, 'unsplit'): + # Presumable a `rfc3986.URIReference` + return v.unsplit() + assert isinstance(v, str) + return rfc3986.normalize_uri(v) + + +@register +class NMTOKEN(string): + """ + Maps to `str` + + The lexical and value spaces of xs:NMTOKEN are the set of XML 1.0 “name tokens,” i.e., + tokens composed of characters, digits, “.”, “:”, “-”, and the characters defined by Unicode, + such as “combining” or “extender”. + + This type is usually called a “token.” + + Valid values include "Snoopy", "CMS", "1950-10-04", or "0836217462". + + Invalid values include "brought classical music to the Peanuts strip" (spaces are forbidden) + or "bold,brash" (commas are forbidden). + """ + name = "NMTOKEN" + + @staticmethod + def to_python(v, regex=None): + v = string.to_python(v, regex=regex) + if not re.fullmatch(r'[\w.:-]*', v): + NMTOKEN.value_error(v) + return v + + +@register +class base64Binary(anyAtomicType): + """ + Maps to `bytes` + """ + name = 'base64Binary' + example = 'YWJj' + + @staticmethod + def to_python(v, **kw): + try: + res = to_binary(v, encoding='ascii') + except UnicodeEncodeError: + base64Binary.value_error(v[:10]) + try: + res = base64.decodebytes(res) + except Exception: + raise ValueError('invalid base64 encoding') + return res + + @staticmethod + def to_string(v, **kw): + return base64.encodebytes(v).decode().strip() + + +@register +class _binary(base64Binary): + """ + Maps to `bytes`. Alias for :class:`base64Binary` + """ + name = 'binary' + + +@register +class hexBinary(anyAtomicType): + """ + Maps to `bytes`. + + .. note:: + + We normalize to uppercase hex digits when seriializing to `str`. Thus, roundtripping is + limited. + """ + name = 'hexBinary' + example = 'ab' + + @staticmethod + def to_python(v, **kw): + try: + res = to_binary(v, encoding='ascii') + except UnicodeEncodeError: + hexBinary.value_error(v[:10]) + try: + res = binascii.unhexlify(res) + except (binascii.Error, TypeError): + raise ValueError('invalid hexBinary encoding') + return res + + @staticmethod + def to_string(v, **kw): + return binascii.hexlify(v).decode().upper() + + +@register +class boolean(anyAtomicType): + """ + Maps to `bool`. + + .. code-block:: python + + >>> from csvw import Datatype + >>> dt = Datatype.fromvalue({"base": "boolean", "format": "Yea|Nay"}) + >>> dt.read('Nay') + False + >>> dt.formatted(True) + 'Yea' + + .. seealso:: ``_ + """ + + name = 'boolean' + example = 'false' + + @staticmethod + def derived_description(datatype: "csvw.Datatype") -> dict: + if datatype.format and isinstance(datatype.format, str) and datatype.format.count('|') == 1: + true, false = [[v] for v in datatype.format.split('|')] + else: + if datatype.format and ( + (not isinstance(datatype.format, str)) or (datatype.format.count('|') != 1)): + warnings.warn('Invalid format spec for boolean') + true, false = ['true', '1'], ['false', '0'] + return {'true': true, 'false': false} + + @staticmethod + def to_python(s, true=('true', '1'), false=('false', '0')): + if isinstance(s, bool) or s is None: + return s + if s in true: + return True + if s in false: + return False + raise boolean.value_error(s) + + @staticmethod + def to_string(v, true=('true', '1'), false=('false', '0')): + return (true if v else false)[0] + + +def with_tz(v, func, args, kw): + tz_pattern = re.compile('(Z|[+-][0-2][0-9]:[0-5][0-9])$') + tz = tz_pattern.search(v) + if tz: + v = v[:tz.start()] + tz = tz.groups()[0] + res = func(v, *args, **kw) + if tz: + dt = dateutil.parser.parse('{}{}'.format(datetime.datetime.now(), tz)) + res = datetime.datetime( + res.year, res.month, res.day, res.hour, res.minute, res.second, res.microsecond, + dt.tzinfo) + return res + + +@register +class dateTime(anyAtomicType): + """ + Maps to `datetime.datetime`. + """ + name = 'datetime' + minmax = True + example = '2018-12-10T20:20:20' + + @staticmethod + def derived_description(datatype: "csvw.Datatype") -> dict: + return dt_format_and_regex(datatype.format) + + @staticmethod + def _parse(v, cls, regex, tz_marker=None): + v = v.strip() + try: + comps = regex.match(v).groupdict() + except AttributeError: # pragma: no cover + dateTime.value_error(v) + if comps.get('extramicroseconds'): + raise ValueError('Extra microseconds') + if comps.get('microsecond'): + # We have to convert decimal fractions of seconds to microseconds. + # This is done by first chopping off anything under 6 decimal places, + # then (in case we got less precision) right-padding with 0 to get a + # 6-digit number. + comps['microsecond'] = comps['microsecond'][:6].ljust(6, '0') + if cls == datetime.datetime and 'year' not in comps: + d = datetime.date.today() + for a in ['year', 'month', 'day']: + comps[a] = getattr(d, a) + res = cls(**{k: int(v) for k, v in comps.items() if v is not None}) + if tz_marker: + # Let dateutils take care of parsing the timezone info: + res = res.replace(tzinfo=dateutil.parser.parse(v).tzinfo) + return res + + @staticmethod + def to_python(v, regex=None, fmt=None, tz_marker=None, pattern=None): + if pattern and regex: + match = regex.match(v) + if not match: + raise ValueError('{} -- {} -- {}'.format(pattern, v, regex)) # pragma: + try: + return dateutil.parser.isoparse(v) + except ValueError: + return dateTime._parse(v, datetime.datetime, regex, tz_marker=tz_marker) + + @staticmethod + def to_string(v, regex=None, fmt=None, tz_marker=None, pattern=None): + if pattern: + return babel.dates.format_datetime(v, tzinfo=v.tzinfo, format=pattern) + return v.isoformat() + + +@register +class _dateTime(dateTime): + """ + Maps to `datetime.datetime`. Alias for :class:`dateTime` + """ + name = 'dateTime' + + +@register +class date(dateTime): + """ + Maps to `datetime.datetime` (in order to be able to preserve timezone information). + """ + name = 'date' + example = '2018-12-10' + + @staticmethod + def derived_description(datatype: "csvw.Datatype") -> dict: + try: + return dt_format_and_regex(datatype.format or 'yyyy-MM-dd') + except ValueError: + warnings.warn('Invalid date format') + return dt_format_and_regex('yyyy-MM-dd') + + @staticmethod + def to_python(v, regex=None, fmt=None, tz_marker=None, pattern=None): + return with_tz( + v.strip(), dateTime.to_python, [], dict(regex=regex, fmt=fmt, pattern=pattern)) + + @staticmethod + def to_string(v, regex=None, fmt=None, tz_marker=None, pattern=None): + from babel.dates import format_date + if pattern: + return format_date(v, format=pattern, locale='en') + return dateTime.to_string(v, regex=regex, fmt=fmt, tz_marker=tz_marker, pattern=pattern) + + +@register +class dateTimeStamp(dateTime): + """ + Maps to `datetime.datetime`. + """ + name = 'dateTimeStamp' + example = '2018-12-10T20:20:20' + + @staticmethod + def derived_description(datatype: "csvw.Datatype") -> dict: + res = dt_format_and_regex(datatype.format or 'yyyy-MM-ddTHH:mm:ss.SSSSSSXXX') + if not res['tz_marker']: + raise ValueError('dateTimeStamp must have timezone marker') + return res + + +@register +class _time(dateTime): + """ + Maps to `datetime.datetime` (in order to be able to preserve timezone information). + """ + name = 'time' + example = '20:20:20' + + @staticmethod + def derived_description(datatype: "csvw.Datatype") -> dict: + return dt_format_and_regex(datatype.format or 'HH:mm:ss', no_date=True) + + @staticmethod + def to_python(v, regex=None, fmt=None, tz_marker=None, pattern=None): + if pattern and 'x' in pattern.lower(): + return dateutil.parser.parse('{}T{}'.format(datetime.date.today().isoformat(), v)) + assert regex is not None + return with_tz(v, dateTime._parse, [datetime.datetime, regex], dict(tz_marker=tz_marker)) + + @staticmethod + def to_string(v, regex=None, fmt=None, tz_marker=None, pattern=None): + return babel.dates.format_time(v, tzinfo=v.tzinfo, format=pattern) + + +@register +class duration(anyAtomicType): + """ + Maps to `datetime.timedelta`. + + .. code-block: python + + >>> from csvw import Datatype + >>> dt = Datatype.fromvalue("datetime") + >>> duration = Datatype.fromvalue("duration") + >>> dt.formatted(dt.read("2022-06-24T12:00:00") + duration.read("P1MT2H")) + '2022-07-24T14:00:00' + + """ + name = 'duration' + example = 'P3Y6M4DT12H30M5S' + + @staticmethod + def derived_description(datatype: "csvw.Datatype") -> dict: + return {'format': datatype.format} + + @staticmethod + def to_python(v, format=None, **kw): + if format and not re.match(format, v): + raise ValueError + return isodate.parse_duration(v) + + @staticmethod + def to_string(v, format=None, **kw): + return isodate.duration_isoformat(v) + + +@register +class dayTimeDuration(duration): + """ + Maps to `datetime.timedelta`. + """ + name = 'dayTimeDuration' + + +@register +class yearMonthDuration(duration): + """ + Maps to `datetime.timedelta`. + """ + name = 'yearMonthDuration' + + +@register +class decimal(anyAtomicType): + """ + Maps to `decimal.Decimal`. + + xs:decimal is the datatype that represents the set of all the decimal numbers with + arbitrary lengths. Its lexical space allows any number of insignificant leading and + trailing zeros (after the decimal point). + + There is no support for scientific notations. + + Valid values include: "123.456", "+1234.456", "-1234.456", "-.456", or "-456". + + The following values would be invalid: [...] "1234.456E+2" (scientific notation ("E+2") + is forbidden). + + XML-Schema restricts the lexical space by disallowing "thousand separator" and forcing the + decimal separator to be ".". But these limitations can be overcome within CSVW using a + `derived datatype `_: + + .. code-block:: python + + >>> from csvw import Datatype + >>> dt = Datatype.fromvalue( + ... {"base": "decimal", "format": {"groupChar": ".", "decimalChar": ","}}) + >>> dt.read("1.234,5") + Decimal('1234.5') + + .. note:: + + While mapping to `decimal.Decimal` rather than `float` makes handling of the Python object + somewhat cumbersome, it makes sure we can roundtrip values correctly. + """ + name = 'decimal' + minmax = True + example = '5' + + _special = { + 'INF': 'Infinity', + '-INF': '-Infinity', + 'NaN': 'NaN', + } + _reverse_special = {v: k for k, v in _special.items()} + + @staticmethod + def derived_description(datatype: "csvw.Datatype") -> dict: + if datatype.format: + return datatype.format if isinstance(datatype.format, dict) \ + else {'pattern': datatype.format} + return {} + + @staticmethod + def to_python(v, pattern=None, decimalChar=None, groupChar=None): + if isinstance(v, str) and 'e' in v.lower(): + raise ValueError('Invalid value for decimal') + + if isinstance(v, str) and re.search('{0}{0}+'.format(re.escape(groupChar or ',')), v): + raise ValueError('Invalid value for decimal') + + if groupChar is None and pattern and ',' in pattern: + groupChar = ',' + if decimalChar is None and pattern and '.' in pattern: + decimalChar = '.' + if pattern and not NumberPattern(pattern).is_valid( + v.replace(groupChar or ',', ',').replace(decimalChar or '.', '.')): + raise ValueError( + 'Invalid value "{}" for decimal with pattern "{}"'.format(v, pattern)) + + factor = 1 + if isinstance(v, str): + if v in decimal._special: + warnings.warn('Invalid special value for decimal') + return _decimal.Decimal(decimal._special[v]) + if groupChar: + v = v.replace(groupChar, '') + if decimalChar and decimalChar != '.': + v = v.replace(decimalChar, '.') + for c, factor in [('%', _decimal.Decimal('0.01')), ('‰', _decimal.Decimal('0.001'))]: + if c in v: + v = v.replace(c, '') + break + else: + factor = 1 + try: + return _decimal.Decimal(v) * factor + except (TypeError, _decimal.InvalidOperation): + decimal.value_error(v) + + @staticmethod + def to_string(v, pattern=None, decimalChar=None, groupChar=None): + if '{}'.format(v) in decimal._reverse_special: + return decimal._reverse_special['{}'.format(v)] + + if pattern: + v = babel.numbers.format_decimal(v, pattern, 'en') + if decimalChar: + v = v.replace('.', decimalChar) + if groupChar: + v = v.replace(',', groupChar) + return v + + fmt = '{}' if groupChar is None else '{:,}' + try: + neg = v < 0 + except TypeError: + neg = None + v = fmt.format(v) + if 'e' in v.lower(): # detect scientific notation + digits, exp = v.lower().split('e') + digits = digits.replace('.', '').replace('-', '') + exp = int(exp) + zero_padding = '0' * (abs(int(exp)) - 1) + sign = '-' if neg else '' + return '{}{}{}.0'.format(sign, digits, zero_padding) if exp > 0 else ( + '{}0.{}{}'.format(sign, zero_padding, digits)) + + if groupChar or decimalChar: + def repl(m): + if m.group('c') == ',': + return groupChar + if m.group('c') == '.': + return decimalChar + r = '(?P[{}])'.format(re.escape((decimalChar or '') + (groupChar or ''))) + v = re.sub(r, repl, v) + return v + + +@register +class integer(decimal): + """ + Maps to `int`. + """ + name = 'integer' + range = None + + @classmethod + def to_python(cls, v, **kw): + res = decimal.to_python(v, **kw) + numerator, denominator = res.as_integer_ratio() + if denominator == 1: + if cls.range and not (cls.range[0] <= numerator <= cls.range[1]): + raise ValueError("{} must be an integer between {} and {}, but got ".format( + cls.name, cls.range[0], cls.range[1]), v) + return numerator + raise ValueError('Invalid value for integer') + + +@register +class _int(integer): + """ + Maps to `int`. Alias for :class:`integer`. + """ + name = 'int' + + +@register +class unsignedInt(integer): + """ + Maps to `int`. + + The value space of xs:unsignedInt is the integers between 0 and 4294967295, i.e., the + unsigned values that can fit in a word of 32 bits. Its lexical space allows an optional “+” + sign and leading zeros before the significant digits. + + The decimal point (even when followed only by insignificant zeros) is forbidden. + + Valid values include "4294967295", "0", "+0000000000000000000005", or "1". + + Invalid values include "-1" and "1.". + """ + name = 'unsignedInt' + range = (0, 4294967295) + + +@register +class unsignedShort(integer): + """ + Maps to `int`. + + The value space of xs:unsignedShort is the integers between 0 and 65535, i.e., the unsigned + values that can fit in a word of 16 bits. Its lexical space allows an optional “+” sign and + leading zeros before the significant digits. + + The decimal point (even when followed only by insignificant zeros) is forbidden. + + Valid values include "65535", "0", "+0000000000000000000005", or "1". + + Invalid values include "-1" and "1." . + """ + name = 'unsignedShort' + range = (0, 65535) + + +@register +class unsignedLong(integer): + """ + Maps to `int`. + + The value space of xs:unsignedLong is the integers between 0 and 18446744073709551615, i.e., + the unsigned values that can fit in a word of 64 bits. Its lexical space allows an optional + “+” sign and leading zeros before the significant digits. + + The decimal point (even when followed only by insignificant zeros) is forbidden. + + Valid values include "18446744073709551615", "0", "+0000000000000000000005", or "1". + + Invalid values include "-1" and "1.". + """ + name = 'unsignedLong' + range = (0, 18446744073709551615) + + +@register +class unsignedByte(integer): + """ + Maps to `int`. + + The value space of xs:unsignedByte is the integers between 0 and 255, i.e., the unsigned + values that can fit in a word of 8 bits. Its lexical space allows an optional “+” sign and + leading zeros before the significant digits. + + The lexical space does not allow values expressed in other numeration bases (such as + hexadecimal, octal, or binary). + + The decimal point (even when followed only by insignificant zeros) is forbidden. + + Valid values include "255", "0", "+0000000000000000000005", or "1". + + Invalid values include "-1" and "1.". + """ + name = 'unsignedByte' + range = (0, 255) + + +@register +class short(integer): + """ + Maps to `int`. + + The value space of xs:short is the set of common short integers (16 bits), i.e., the + integers between -32768 and 32767; its lexical space allows any number of insignificant + leading zeros. + + The decimal point (even when followed only by insignificant zeros) is forbidden. + + Valid values include "-32768", "0", "-0000000000000000000005", or "32767". + + Invalid values include "32768" and "1.". + """ + name = 'short' + range = (-32768, 32767) + + +@register +class long(integer): + """ + Maps to `int`. + + The value space of xs:long is the set of common double-size integers (64 bits), i.e., the + integers between -9223372036854775808 and 9223372036854775807; its lexical space allows any + number of insignificant leading zeros. + + The decimal point (even when followed only by insignificant zeros) is forbidden. + + Valid values for xs:long include "-9223372036854775808", "0", "-0000000000000000000005", or + "9223372036854775807". + + Invalid values include "9223372036854775808" and "1.". + """ + name = 'long' + range = (-9223372036854775808, 9223372036854775807) + + +@register +class byte(integer): + """ + Maps to `int`. + + The value space of xs:byte is the integers between -128 and 127, i.e., the signed values + that can fit in a word of 8 bits. Its lexical space allows an optional sign and leading + zeros before the significant digits. + + The lexical space does not allow values expressed in other numeration bases (such as + hexadecimal, octal, or binary). + + Valid values for byte include 27, -34, +105, and 0. + + Invalid values include 0A, 1524, and INF. + """ + name = 'byte' + range = (-128, 127) + + +@register +class nonNegativeInteger(integer): + """ + Maps to `int`. + """ + name = 'nonNegativeInteger' + range = (0, math.inf) + + +@register +class positiveInteger(integer): + """ + Maps to `int`. + """ + name = 'positiveInteger' + range = (1, math.inf) + + +@register +class nonPositiveInteger(integer): + """ + Maps to `int`. + """ + name = 'nonPositiveInteger' + example = '-5' + range = (-math.inf, 0) + + +@register +class negativeInteger(integer): + """ + Maps to `int`. + """ + name = 'negativeInteger' + example = '-5' + range = (-math.inf, -1) + + +@register +class _float(anyAtomicType): + """ + Maps to `float`. + + .. note:: + + Due to the well known issues with representing floating point numbers, roundtripping may + not work correctly. + + .. seealso:: ``_ + """ + name = 'float' + minmax = True + example = '5.3' + + @staticmethod + def derived_description(datatype: "csvw.Datatype") -> dict: + if datatype.format: + return datatype.format if isinstance(datatype.format, dict) \ + else {'pattern': datatype.format} + return {} + + @staticmethod + def to_python(v, pattern=None, **kw): + if pattern and not NumberPattern(pattern).is_valid(v): + raise ValueError( + 'Invalid value "{}" for number with pattern "{}"'.format(v, pattern)) + + try: + return float(v) + except (TypeError, ValueError): + _float.value_error(v) + + @staticmethod + def to_string(v, **kw): + return '{}'.format(v) + + +@register +class number(_float): + """ + Maps to `float`. + """ + name = 'number' + + +@register +class double(_float): + """ + Maps to `float`. + """ + name = 'double' + + +@register +class normalizedString(string): + """ + Maps to `str`. + + The lexical space of xs:normalizedString is unconstrained (any valid XML character may be + used), and its value space is the set of strings after whitespace replacement (i.e., after + any occurrence of #x9 (tab), #xA (linefeed), and #xD (carriage return) have been replaced + by an occurrence of #x20 (space) without any whitespace collapsing). + + .. note:: + + The CSVW test suite (specifically in `test036 `_ + and `test037 `_) requires that `normalizedString` + is also trimmed, i.e. stripped from leading and trailing whitespace. So that's we do. + """ + name = 'normalizedString' + + @staticmethod + def to_python(v, regex=None): + if v: + for c in '\r\n\t': + v = v.replace(c, ' ') + v = v.strip() + return string.to_python(v, '') + + +@register +class QName(string): + """ + Maps to `str`. + """ + name = 'QName' + + +@register +class gDay(string): + """ + Maps to `str`. + """ + name = 'gDay' + + +@register +class gMonth(string): + """ + Maps to `str`. + """ + name = 'gMonth' + + +@register +class gMonthDay(string): + """ + Maps to `str`. + """ + name = 'gMonthDay' + + +@register +class gYear(string): + """ + Maps to `str`. + """ + name = 'gYear' + + +@register +class gYearMonth(string): + """ + Maps to `str`. + """ + name = 'gYearMonth' + + +@register +class xml(string): + """ + Maps to `str`. + """ + name = 'xml' + + +@register +class html(string): + """ + Maps to `str`. + """ + name = 'html' + + +@register +class json(string): + """ + Maps to `str`, `list` or `dict`, i.e. to the result of `json.loads`. + + .. code-block:: python + + >>> from csvw import Datatype + >>> dt = Datatype.fromvalue("json") + >>> d = dt.read("{}") + >>> d["a"] = '123' + >>> dt.formatted(d) + '{"a": "123"}' + + Additional constraints on JSON data can be imposed by specifying + `JSON Schema `_ documents as `format` annotation: + + .. code-block:: python + + >>> from csvw import Datatype + >>> dt = Datatype.fromvalue({"base": "json", "format": '{"type": "object"}'}) + >>> dt.read('{}') + OrderedDict() + >>> dt.read('4') + ... + jsonschema.exceptions.ValidationError: 4 is not of type 'object' + ... + ValueError: invalid lexical value for json: 4 + + .. note:: + + To ensure proper roundtripping, we load the JSON strings using the + `object_pairs_hook=collections.OrderedDict` keyword. + """ + name = 'json' + example = '{"a": [1,2]}' + + @staticmethod + def derived_description(datatype: "csvw.Datatype") -> dict: + if datatype.format: + try: + schema = _json.loads(datatype.format) + try: + jsonschema.validate({}, schema=schema) + return {'schema': schema} + except jsonschema.ValidationError: + return {'schema': schema} + except jsonschema.SchemaError: + warnings.warn('Invalid JSON schema as datatype format') + except _json.JSONDecodeError: + pass + return {} + + # FIXME: ignored **kw? + # why not just to_python = staticmethod(_json.loads)? + @staticmethod + def to_python(v, schema=None, **kw): + res = _json.loads(v, object_pairs_hook=collections.OrderedDict) + if schema: + try: + jsonschema.validate(res, schema=schema) + except jsonschema.ValidationError: + json.value_error(v) + return res + + @staticmethod + def to_string(v, **kw): + return _json.dumps(v) + + +def dt_format_and_regex(fmt, no_date=False): + """ + + .. seealso:: http://w3c.github.io/csvw/syntax/#formats-for-dates-and-times + """ + if fmt is None: + return {'fmt': None, 'tz_marker': None, 'regex': None, 'pattern': None} + + if isinstance(fmt, dict) and list(fmt.keys()) == ['pattern']: + fmt = fmt['pattern'] + + pattern = fmt + + # First, we strip off an optional timezone marker: + tz_marker = None + match = re.search('(?P ?[xX]{1,3})$', fmt) + if match: + tz_marker = match.group('marker') + if len(set(tz_marker.strip())) != 1: # mixing x and X is not allowed! + raise ValueError(fmt) + fmt = fmt[:match.start()] + + date_patterns = { + "yyyy-MM-dd", # e.g., 2015-03-22 + "yyyyMMdd", # e.g., 20150322 + "dd-MM-yyyy", # e.g., 22-03-2015 + "d-M-yyyy", # e.g., 22-3-2015 + "MM-dd-yyyy", # e.g., 03-22-2015 + "M-d-yyyy", # e.g., 3-22-2015 + "dd/MM/yyyy", # e.g., 22/03/2015 + "d/M/yyyy", # e.g., 22/3/2015 + "MM/dd/yyyy", # e.g., 03/22/2015 + "M/d/yyyy", # e.g., 3/22/2015 + "dd.MM.yyyy", # e.g., 22.03.2015 + "d.M.yyyy", # e.g., 22.3.2015 + "MM.dd.yyyy", # e.g., 03.22.2015 + "M.d.yyyy", # e.g., 3.22.2015 + } + + time_patterns = {"HH:mm:ss", "HHmmss", "HH:mm", "HHmm"} + + # We map dateTime component markers to corresponding fromat specs and regular + # expressions used for formatting and parsing. + translate = { + 'yyyy': ('{dt.year:04d}', '(?P[0-9]{4})'), + 'MM': ('{dt.month:02d}', '(?P[0-9]{2})'), + 'dd': ('{dt.day:02d}', '(?P[0-9]{2})'), + 'M': ('{dt.month}', '(?P[0-9]{1,2})'), + 'd': ('{dt.day}', '(?P[0-9]{1,2})'), + 'HH': ('{dt.hour:02d}', '(?P[0-9]{2})'), + 'mm': ('{dt.minute:02d}', '(?P[0-9]{2})'), + 'ss': ('{dt.second:02d}', '(?P[0-9]{2})'), + } + + for dt_sep in ' T': # Only a single space or "T" may separate date and time format. + # Since space or "T" isn't allowed anywhere else in the format, checking whether + # we are dealing with a date or dateTime format is simple: + if dt_sep in fmt: + break + else: + dt_sep = None + + if dt_sep: + dfmt, tfmt = fmt.split(dt_sep) + elif no_date: + dfmt, tfmt = None, fmt + else: + dfmt, tfmt = fmt, None + + msecs = None # The maximal number of decimal places for fractions of seconds. + if tfmt and '.' in tfmt: # There is a microseconds marker. + tfmt, msecs = tfmt.split('.') # Strip it off ... + if set(msecs) != {'S'}: # ... make sure it's valid ... + raise ValueError(fmt) + msecs = len(msecs) # ... and store it's length. + + # Now we can check whether the bare date and time formats are valid: + if (dfmt and dfmt not in date_patterns) or (tfmt and tfmt not in time_patterns): + raise ValueError(fmt) + + regex, format = '', '' # Initialize the output. + + if dfmt: + for d_sep in '.-/': # Determine the separator used for date components. + if d_sep in dfmt: + break + else: + d_sep = None + + if d_sep: + # Iterate over date components, converting them to string format specs and regular + # expressions. + for i, part in enumerate(dfmt.split(d_sep)): + if i > 0: + format += d_sep + regex += re.escape(d_sep) + f, r = translate[part] + format += f + regex += r + else: + for _, chars in itertools.groupby(dfmt, lambda k: k): + f, r = translate[''.join(chars)] + format += f + regex += r + + if dt_sep: + format += dt_sep + regex += re.escape(dt_sep) + + if tfmt: + # For time components the only valid separator is ":". + if ':' in tfmt: + for i, part in enumerate(tfmt.split(':')): + if i > 0: + format += ':' + regex += re.escape(':') + f, r = translate[part] + format += f + regex += r + else: + for _, chars in itertools.groupby(tfmt, lambda k: k): + f, r = translate[''.join(chars)] + format += f + regex += r + + # Fractions of seconds are a bit of a problem, because datetime objects only offer + # microseconds. + if msecs: + format += '.{microsecond:.%s}' % msecs + regex += r'(\.(?P[0-9]{1,%s})(?![0-9]))?' % msecs + regex += r'(\.(?P[0-9]{%s,})(?![0-9]))?' % (msecs + 1,) + + return {'regex': re.compile(regex), 'fmt': format, 'tz_marker': tz_marker, 'pattern': pattern} + + +class NumberPattern: + """ + Implementations MUST recognise number format patterns containing the symbols 0, #, the specified + decimalChar (or "." if unspecified), the specified groupChar (or "," if unspecified), E, +, % + and ‰. + + The number of # placeholder characters before the decimal do not matter, since no limit is + placed on the maximum number of digits. There should, however, be at least one zero someplace + in the pattern. + """ + + def __init__(self, pattern): + assert pattern.count(';') <= 1 + self.positive, _, self.negative = pattern.partition(';') + if not self.negative: + self.negative = '-' + self.positive.replace('+', '') + + @property + def primary_grouping_size(self): + comps = self.positive.split('.')[0].split(',') + if len(comps) > 1: + return comps[-1].count('#') + comps[-1].count('0') + + @property + def secondary_grouping_size(self): + comps = self.positive.split('.')[0].split(',') + if len(comps) > 2: + return comps[1].count('#') + comps[1].count('0') + return self.primary_grouping_size + + @property + def min_digits_before_decimal_point(self): + integral_part = self.positive.split('.')[0] + match = re.search('([0]+)$', integral_part) + if match: + return len(match.groups()[0]) + + @property + def exponent_digits(self): + _, _, exponent = self.positive.lower().partition('e') + i = 0 + for c in exponent: + if c in '0#': + i += 1 + elif c in ',': + continue + else: + break + return i + + @property + def decimal_digits(self): + i = 0 + _, _, decimal_part = self.positive.partition('.') + for c in decimal_part: + if c in '#0': + i += 1 + if c == 'E': + break + return i + + @property + def significant_decimal_digits(self): + i = 0 + _, _, decimal_part = self.positive.partition('.') + for c in decimal_part: + if c == '0': + i += 1 + if c in ['E', '#']: + break + return i + + def is_valid(self, s): + def digits(ss): + return [c for c in ss if c not in '.,E+-%‰'] + + integral_part, _, decimal_part = s.partition('.') + decimal_part, _, exponent = decimal_part.lower().partition('e') + groups = integral_part.split(',') + significant, leadingzero, skip = [], False, True + for c in ''.join(groups): + if c in ['+', '-', '%', # fixme: permil + ]: + continue + if c == '0' and skip: + leadingzero = True + continue + if c != '0': + skip = False + significant.append(c) + if not significant and leadingzero: + significant = ['0'] + if self.min_digits_before_decimal_point and \ + len(significant) < self.min_digits_before_decimal_point: + return False + if self.primary_grouping_size and groups: + if len(digits(groups[-1])) > self.primary_grouping_size: + return False + if len(groups) > 1 and len(digits(groups[-1])) < self.primary_grouping_size: + return False + if self.secondary_grouping_size and len(groups) > 1: + for i, group in enumerate(groups[:-1]): + if i == 0: + if len(digits(group)) > self.secondary_grouping_size: + return False + else: + if len(digits(group)) != self.secondary_grouping_size: + return False + if decimal_part: + if len(digits(decimal_part)) > self.decimal_digits: + return False + if self.significant_decimal_digits: + if (not decimal_part) or (len(digits(decimal_part)) < self.significant_decimal_digits): + return False + + if self.exponent_digits and 'e' in s.lower(): + if len(digits(s.lower().split('e')[-1])) > self.exponent_digits: + return False + + return True diff --git a/TTS/Kokoro/.venv/Lib/site-packages/csvw/db.py b/TTS/Kokoro/.venv/Lib/site-packages/csvw/db.py new file mode 100644 index 0000000000000000000000000000000000000000..8a03c62a7dcfc781a204d0a671bc562f52393c7f --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/csvw/db.py @@ -0,0 +1,581 @@ +""" +SQLite as alternative storage backend for a TableGroup's data. + +For the most part, translation of a TableGroup's tableSchema to SQL works as expected: + +- each table is converted to a `CREATE TABLE` statement +- each column specifies a column in the corresponding `CREATE TABLE` statement +- `foreignKey` constraints are added according to the corresponding `tableSchema` property. + +List-valued foreignKeys are supported as follows: For each pair of tables related through a +list-valued foreign key, an association table is created. To make it possible to distinguish +multiple list-valued foreign keys between the same two tables, the association table has +a column `context`, which stores the name of the foreign key column from which a row in the +assocation table was created. + +Other list-valued columns work in two different ways: If the atomic datatype is `string`, the +specified separator is used to create a concatenated string representation in the database field. +Otherwise, the list of values is serialized as JSON. + +SQL table and column names can be customized by passing a translator callable when instantiating +a :class:`Database`. + +SQLite support has the following limitations: + +- regex constraints on strings (as specified via a :class:`csvw.Datatype`'s format attribute) are + not enforced by the database. +""" +import json +import typing +import decimal +import pathlib +import sqlite3 +import functools +import contextlib +import collections + +import attr + +import csvw +from csvw.datatypes import DATATYPES +from csvw.metadata import TableGroup + + +def identity(s): + return s + + +TYPE_MAP = { + 'string': ( + 'TEXT', + identity, + identity), + 'integer': ( + 'INTEGER', + identity, + identity), + 'boolean': ( + 'INTEGER', + lambda s: s if s is None else int(s), + lambda s: s if s is None else bool(s)), + 'decimal': ( + 'REAL', + lambda s: s if s is None else float(s), + lambda s: s if s is None else decimal.Decimal(s)), + 'hexBinary': ( + 'BLOB', + identity, + identity), +} + + +class SchemaTranslator(typing.Protocol): + def __call__(self, table: str, column: typing.Optional[str] = None) -> str: + ... # pragma: no cover + + +class ColumnTranslator(typing.Protocol): + def __call__(self, column: str) -> str: + ... # pragma: no cover + + +def quoted(*names): + return ','.join('`{0}`'.format(name) for name in names) + + +def insert(db: sqlite3.Connection, + translate: SchemaTranslator, + table: str, + keys: typing.Sequence[str], + *rows: list, + single: typing.Optional[bool] = False): + """ + Insert a sequence of rows into a table. + + :param db: Database connection. + :param translate: Callable translating table and column names to proper schema object names. + :param table: Untranslated table name. + :param keys: Untranslated column names. + :param rows: Sequence of rows to insert. + :param single: Flag signaling whether to insert all rows at once using `executemany` or one at \ + a time, allowing for more focused debugging output in case of errors. + """ + if rows: + sql = "INSERT INTO {0} ({1}) VALUES ({2})".format( + quoted(translate(table)), + quoted(*[translate(table, k) for k in keys]), + ','.join(['?' for _ in keys])) + try: + db.executemany(sql, rows) + except: # noqa: E722 - this is purely for debugging. + if not single: + for row in rows: + insert(db, translate, table, keys, row, single=True) + else: + print(sql) + print(rows) + raise + + +def select(db: sqlite3.Connection, table: str) -> typing.Tuple[typing.List[str], typing.Sequence]: + cu = db.execute("SELECT * FROM {0}".format(quoted(table))) + cols = [d[0] for d in cu.description] + return cols, list(cu.fetchall()) + + +@attr.s +class ColSpec: + """ + A `ColSpec` captures sufficient information about a :class:`csvw.Column` for the DB schema. + """ + name = attr.ib() + csvw_type = attr.ib(default='string', converter=lambda s: s if s else 'string') + separator = attr.ib(default=None) + db_type = attr.ib(default=None) + convert = attr.ib(default=None) + read = attr.ib(default=None) + required = attr.ib(default=False) + csvw = attr.ib(default=None) + + def __attrs_post_init__(self): + if self.csvw_type in TYPE_MAP: + self.db_type, self.convert, self.read = TYPE_MAP[self.csvw_type] + else: + self.db_type = 'TEXT' + self.convert = DATATYPES[self.csvw_type].to_string + self.read = DATATYPES[self.csvw_type].to_python + if self.separator and self.db_type != 'TEXT': + self.db_type = 'TEXT' + + def check(self, translate: ColumnTranslator) -> typing.Optional[str]: + """ + We try to convert as many data constraints as possible into SQLite CHECK constraints. + + :param translate: Callable to translate column names between CSVW metadata and DB schema. + :return: A string suitable as argument of an SQL CHECK constraint. + """ + if not self.csvw: + return + c, cname = self.csvw, translate(self.name) + constraints = [] + if (c.minimum is not None) or (c.maximum is not None): + func = { + 'date': 'date', + 'datetime': 'datetime', + }.get(self.csvw_type) + if c.minimum is not None: + if func: + constraints.append("{2}(`{0}`) >= {2}('{1}')".format(cname, c.minimum, func)) + else: + constraints.append('`{0}` >= {1}'.format(cname, c.minimum)) + if c.maximum is not None: + if func: + constraints.append("{2}(`{0}`) <= {2}('{1}')".format(cname, c.maximum, func)) + else: + constraints.append('`{0}` <= {1}'.format(cname, c.maximum)) + elif any(cc is not None for cc in [c.length, c.minLength, c.maxLength]): + if c.length: + constraints.append('length(`{0}`) = {1}'.format(cname, c.length)) + if c.minLength: + constraints.append('length(`{0}`) >= {1}'.format(cname, c.minLength)) + if c.maxLength: + constraints.append('length(`{0}`) <= {1}'.format(cname, c.maxLength)) + return ' AND '.join(constraints) + + def sql(self, translate: ColumnTranslator) -> str: + _check = self.check(translate) + return '`{0}` {1}{2}{3}'.format( + translate(self.name), + self.db_type, + ' NOT NULL' if self.required else '', + ' CHECK ({0})'.format(_check) if _check else '') + + +@attr.s +class TableSpec(object): + """ + A `TableSpec` captures sufficient information about a :class:`csvw.Table` for the DB schema. + + .. note:: + + We support "light-weight" many-to-many relationships by allowing list-valued foreign key + columns in CSVW. In the database these columns are turned into an associative table, adding + the name of the column as value a `context` column. Thus, multiple columns in a table my be + specified as targets of many-to-many relations with the same table. + + .. seealso:: ``_ + """ + name = attr.ib() + columns = attr.ib(default=attr.Factory(list)) + foreign_keys = attr.ib(default=attr.Factory(list)) + many_to_many = attr.ib(default=attr.Factory(collections.OrderedDict)) + primary_key = attr.ib(default=None) + + @classmethod + def from_table_metadata(cls, + table: csvw.Table, + drop_self_referential_fks: typing.Optional[bool] = True) -> 'TableSpec': + """ + Create a `TableSpec` from the schema description of a `csvw.metadata.Table`. + + :param table: `csvw.metadata.Table` instance. + :param drop_self_referential_fks: Flag signaling whether to drop self-referential foreign \ + keys. This may be necessary, if the order of rows in a CSVW table does not guarantee \ + referential integrity when inserted in order (e.g. an eralier row refering to a later one). + :return: `TableSpec` instance. + """ + spec = cls(name=table.local_name, primary_key=table.tableSchema.primaryKey) + list_valued = {c.header for c in table.tableSchema.columns if c.separator} + for fk in table.tableSchema.foreignKeys: + # We only support Foreign Key references between tables! + if not fk.reference.schemaReference: + if len(fk.columnReference) == 1 and fk.columnReference[0] in list_valued: + # List-valued foreign keys are turned into a many-to-many relation! + assert len(fk.reference.columnReference) == 1, \ + 'Composite key {0} in table {1} referenced'.format( + fk.reference.columnReference, + fk.reference.resource) + assert spec.primary_key and len(spec.primary_key) == 1, \ + 'Table {0} referenced by list-valued foreign key must have non-composite ' \ + 'primary key'.format(spec.name) + spec.many_to_many[fk.columnReference[0]] = TableSpec.association_table( + spec.name, + spec.primary_key[0], + fk.reference.resource.string, + fk.reference.columnReference[0], + ) + elif not (drop_self_referential_fks and fk.reference.resource.string == spec.name): + spec.foreign_keys.append(( + sorted(fk.columnReference), + fk.reference.resource.string, + sorted(fk.reference.columnReference), + )) + for c in table.tableSchema.columns: + if c.header not in spec.many_to_many: + datatype = c.inherit('datatype') + spec.columns.append(ColSpec( + name=c.header, + csvw_type=datatype.base if datatype else datatype, + separator=c.inherit('separator'), + required=c.inherit('required'), + csvw=c.inherit('datatype'), + )) + return spec + + @classmethod + def association_table(cls, atable, apk, btable, bpk) -> 'TableSpec': + """ + List-valued foreignKeys are supported as follows: For each pair of tables related through a + list-valued foreign key, an association table is created. To make it possible to distinguish + multiple list-valued foreign keys between the same two tables, the association table has + a column `context`, which stores the name of the foreign key column from which a row in the + assocation table was created. + """ + afk = ColSpec('{0}_{1}'.format(atable, apk)) + bfk = ColSpec('{0}_{1}'.format(btable, bpk)) + if afk.name == bfk.name: + afk.name += '_1' + bfk.name += '_2' + return cls( + name='{0}_{1}'.format(atable, btable), + columns=[afk, bfk, ColSpec('context')], + foreign_keys=[ + ([afk.name], atable, [apk]), + ([bfk.name], btable, [bpk]), + ] + ) + + def sql(self, translate: SchemaTranslator) -> str: + """ + :param translate: + :return: The SQL statement to create the table. + """ + col_translate = functools.partial(translate, self.name) + clauses = [col.sql(col_translate) for col in self.columns] + if self.primary_key: + clauses.append('PRIMARY KEY({0})'.format(quoted( + *[col_translate(c) for c in self.primary_key]))) + for fk, ref, refcols in self.foreign_keys: + clauses.append('FOREIGN KEY({0}) REFERENCES {1}({2}) ON DELETE CASCADE'.format( + quoted(*[col_translate(c) for c in fk]), + quoted(translate(ref)), + quoted(*[translate(ref, c) for c in refcols]))) + return "CREATE TABLE IF NOT EXISTS `{0}` (\n {1}\n)".format( + translate(self.name), ',\n '.join(clauses)) + + +def schema(tg: csvw.TableGroup, + drop_self_referential_fks: typing.Optional[bool] = True) -> typing.List[TableSpec]: + """ + Convert the table and column descriptions of a `TableGroup` into specifications for the + DB schema. + + :param tg: CSVW TableGroup. + :param drop_self_referential_fks: Flag signaling whether to drop self-referential foreign \ + keys. This may be necessary, if the order of rows in a CSVW table does not guarantee \ + referential integrity when inserted in order (e.g. an eralier row refering to a later one). + :return: A pair (tables, reference_tables). + """ + tables = {} + for tname, table in tg.tabledict.items(): + t = TableSpec.from_table_metadata( + table, drop_self_referential_fks=drop_self_referential_fks) + tables[t.name] = t + for at in t.many_to_many.values(): + tables[at.name] = at + + # We must determine the order in which tables must be created! + ordered = collections.OrderedDict() + i = 0 + + # We loop through the tables repeatedly, and whenever we find one, which has all + # referenced tables already in ordered, we move it from tables to ordered. + while tables and i < 100: + i += 1 + for table in list(tables.keys()): + if all((ref[1] in ordered) or ref[1] == table for ref in tables[table].foreign_keys): + # All referenced tables are already created (or self-referential). + ordered[table] = tables.pop(table) + break + if tables: # pragma: no cover + raise ValueError('there seem to be cyclic dependencies between the tables') + + return list(ordered.values()) + + +class Database(object): + """ + Represents a SQLite database associated with a :class:`csvw.TableGroup` instance. + + :param tg: `TableGroup` instance defining the schema of the database. + :param fname: Path to which to write the database file. + :param translate: Schema object name translator. + :param drop_self_referential_fks: Flag signaling whether to drop or enforce self-referential \ + foreign-key constraints. + + .. warning:: + + We write rows of a table to the database sequentially. Since CSVW does not require ordering + rows in tables such that self-referential foreign-key constraints are satisfied at each row, + we don't enforce self-referential foreign-keys by default in order to not trigger "false" + integrity errors. If data in a CSVW Table is known to be ordered appropriately, `False` + should be passed as `drop_self_referential_fks` keyword parameter to enforce + self-referential foreign-keys. + """ + def __init__( + self, + tg: TableGroup, + fname: typing.Optional[typing.Union[pathlib.Path, str]] = None, + translate: typing.Optional[SchemaTranslator] = None, + drop_self_referential_fks: typing.Optional[bool] = True, + ): + self.translate = translate or Database.name_translator + self.fname = pathlib.Path(fname) if fname else None + self.init_schema(tg, drop_self_referential_fks=drop_self_referential_fks) + self._connection = None # For in-memory dbs we need to keep the connection! + + def init_schema(self, tg, drop_self_referential_fks=True): + self.tg = tg + self.tables = schema( + self.tg, drop_self_referential_fks=drop_self_referential_fks) if self.tg else [] + + @property + def tdict(self) -> typing.Dict[str, TableSpec]: + return {t.name: t for t in self.tables} + + @staticmethod + def name_translator(table: str, column: typing.Optional[str] = None) -> str: + """ + A callable with this signature can be passed into DB creation to control the names + of the schema objects. + + :param table: CSVW name of the table before translation + :param column: CSVW name of a column of `table` before translation + :return: Translated table name if `column is None` else translated column name + """ + # By default, no translation is done: + return column or table + + def connection(self) -> typing.Union[sqlite3.Connection, contextlib.closing]: + if self.fname: + return contextlib.closing(sqlite3.connect(str(self.fname))) + if not self._connection: + self._connection = sqlite3.connect(':memory:') + return self._connection + + def select_many_to_many(self, db, table, context) -> dict: + if context is not None: + context_sql = "WHERE context = '{0}'".format(context) + else: + context_sql = '' + sql = """\ +SELECT {0}, group_concat({1}, ' '), group_concat(COALESCE(context, ''), '||') +FROM {2} {3} GROUP BY {0}""".format( + quoted(self.translate(table.name, table.columns[0].name)), + quoted(self.translate(table.name, table.columns[1].name)), + quoted(self.translate(table.name)), + context_sql) + cu = db.execute(sql) + return { + r[0]: [(k, v) if context is None else k + for k, v in zip(r[1].split(), r[2].split('||'))] for r in cu.fetchall()} + + def separator(self, tname: str, cname: str) -> typing.Optional[str]: + """ + :return: separator for the column specified by db schema names `tname` and `cname`. + """ + for name in self.tdict: + if self.translate(name) == tname: + for col in self.tdict[name].columns: + if self.translate(name, col.name) == cname: + return col.separator + + def split_value(self, tname, cname, value) -> typing.Union[typing.List[str], str, None]: + sep = self.separator(tname, cname) + return (value or '').split(sep) if sep else value + + def read(self) -> typing.Dict[str, typing.List[typing.OrderedDict]]: + """ + :return: A `dict` where keys are SQL table names corresponding to CSVW tables and values \ + are lists of rows, represented as dicts where keys are the SQL column names. + """ + res = collections.defaultdict(list) + with self.connection() as conn: + for tname in self.tg.tabledict: + # + # FIXME: how much do we want to use DB types? Probably as much as possible! + # Thus we need to convert on write **and** read! + # + convert, seps, refs = {}, {}, collections.defaultdict(dict) + table = self.tdict[tname] # The TableSpec object. + + # Assemble the conversion dictionary: + for col in table.columns: + convert[self.translate(tname, col.name)] = [col.name, identity] + if col.csvw_type in TYPE_MAP: + convert[self.translate(tname, col.name)][1] = TYPE_MAP[col.csvw_type][2] + else: + convert[self.translate(tname, col.name)][1] = \ + DATATYPES[col.csvw_type].to_python + if col.separator: + if col.csvw_type == 'string': + seps[self.translate(tname, col.name)] = col.separator + else: + seps[self.translate(tname, col.name)] = 'json' + + # Retrieve the many-to-many relations: + for col, at in table.many_to_many.items(): + for pk, v in self.select_many_to_many(conn, at, col).items(): + refs[pk][self.translate(tname, col)] = v + + cols, rows = select(conn, self.translate(tname)) + for row in rows: + d = collections.OrderedDict() + for k, v in zip(cols, row): + if k in seps: + if v is None: + d[k] = None + elif not v: + d[k] = [] + elif seps[k] == 'json': + d[k] = json.loads(v) + else: + d[k] = [convert[k][1](v_) for v_ in (v or '').split(seps[k])] + else: + d[k] = convert[k][1](v) if v is not None else None + pk = d[self.translate(tname, table.primary_key[0])] \ + if table.primary_key and len(table.primary_key) == 1 else None + d.update({k: [] for k in table.many_to_many}) + d.update(refs.get(pk, {})) + res[self.translate(tname)].append(d) + return res + + def association_table_context(self, table, column, fkey): + """ + Context for association tables is created calling this method. + + Note: If a custom value for the `context` column is created by overwriting this method, + `select_many_to_many` must be adapted accordingly, to make sure the custom + context is retrieved when reading the data from the db. + + :param table: + :param column: + :param fkey: + :return: a pair (foreign key, context) + """ + # The default implementation takes the column name as context: + return fkey, column + + def write_from_tg(self, _force=False, _exists_ok=False, _skip_extra=False): + return self.write( + force=_force, + _exists_ok=_exists_ok, + _skip_extra=_skip_extra, + **self.tg.read()) + + def write(self, *, force=False, _exists_ok=False, _skip_extra=False, **items): + """ + Creates a db file with the core schema. + + :param force: If `True` an existing db file will be overwritten. + """ + if self.fname and self.fname.exists(): + if not force: + raise ValueError('db file already exists, use force=True to overwrite') + else: + self.fname.unlink() + + with self.connection() as db: + for table in self.tables: + db.execute(table.sql(translate=self.translate)) + + db.execute('PRAGMA foreign_keys = ON;') + db.commit() + + refs = collections.defaultdict(list) # collects rows in association tables. + for t in self.tables: + if t.name not in items: + continue + rows, keys = [], [] + cols = {c.name: c for c in t.columns} + for i, row in enumerate(items[t.name]): + pk = row[t.primary_key[0]] \ + if t.primary_key and len(t.primary_key) == 1 else None + values = [] + for k, v in row.items(): + if k in t.many_to_many: + assert pk + at = t.many_to_many[k] + atkey = tuple([at.name] + [c.name for c in at.columns]) + # We distinguish None - meaning NULL - and [] - meaning no items - as + # values of list-valued columns. + for vv in (v or []): + fkey, context = self.association_table_context(t, k, vv) + refs[atkey].append((pk, fkey, context)) + else: + if k not in cols: + if _skip_extra: + continue + else: + raise ValueError( + 'unspecified column {0} found in data'.format(k)) + col = cols[k] + if isinstance(v, list): + # Note: This assumes list-valued columns are of datatype string! + if col.csvw_type == 'string': + v = (col.separator or ';').join( + col.convert(vv) or '' for vv in v) + else: + v = json.dumps(v) + else: + v = col.convert(v) if v is not None else None + if i == 0: + keys.append(col.name) + values.append(v) + rows.append(tuple(values)) + insert(db, self.translate, t.name, keys, *rows) + + for atkey, rows in refs.items(): + insert(db, self.translate, atkey[0], atkey[1:], *rows) + + db.commit() diff --git a/TTS/Kokoro/.venv/Lib/site-packages/csvw/dsv.py b/TTS/Kokoro/.venv/Lib/site-packages/csvw/dsv.py new file mode 100644 index 0000000000000000000000000000000000000000..0d050d2623c4fbb1ac3239177c4a273ead323c11 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/csvw/dsv.py @@ -0,0 +1,458 @@ +"""Support for reading delimiter-separated value files. + +This module contains unicode aware replacements for :func:`csv.reader` +and :func:`csv.writer`. It was stolen/extracted from the ``csvkit`` +project to allow re-use when the whole ``csvkit`` package isn't +required. + +The original implementations were largely copied from +`examples in the csv module documentation `_. + +.. seealso:: http://en.wikipedia.org/wiki/Delimiter-separated_values +""" +import io +import csv +import codecs +import shutil +import typing +import pathlib +import tempfile +import warnings +import functools +import collections + +from . import utils +from .dsv_dialects import Dialect + +__all__ = [ + 'UnicodeWriter', + 'UnicodeReader', 'UnicodeReaderWithLineNumber', 'UnicodeDictReader', 'NamedTupleReader', + 'iterrows', + 'rewrite', 'add_rows', 'filter_rows_as_dict', +] + +LINES_OR_PATH = typing.Union[str, pathlib.Path, typing.IO, typing.Iterable[str]] + + +def normalize_encoding(encoding: str) -> str: + return codecs.lookup(encoding).name + + +class UnicodeWriter: + """ + Write Unicode data to a csv file. + + :param f: The target to which to write the data; a local path specified as `str` or \ + `pathlib.Path` or `None`, in which case the data, formatted as DSV can be retrieved \ + via :meth:`~UnicodeWriter.read` + :param dialect: Either a dialect name as recognized by `csv.writer` or a \ + :class:`~Dialect` instance for dialect customization beyond what can be done with \ + `csv.writer`. + :param kw: Keyword arguments passed through to `csv.writer`. + + .. code-block:: python + + >>> from csvw import UnicodeWriter + >>> with UnicodeWriter('data.tsv', delimiter='\t') as writer: + ... writer.writerow(['ä', 'ö', 'ü']) + """ + + def __init__( + self, + f: typing.Optional[typing.Union[str, pathlib.Path]] = None, + dialect: typing.Optional[typing.Union[Dialect, str]] = None, + **kw): + self.f = f + self.encoding = kw.pop('encoding', 'utf-8') + if isinstance(dialect, Dialect): + self.encoding = dialect.python_encoding + self.kw = dialect.as_python_formatting_parameters() + self.kw.update(kw) + else: + self.kw = kw + if dialect: + self.kw['dialect'] = dialect + self.encoding = normalize_encoding(self.encoding) + self.escapechar = self.kw.get('escapechar') + if self.escapechar and self.kw.get('quoting') != csv.QUOTE_NONE: + # work around https://bugs.python.org/issue12178 + # (csv.writer doesn't escape escapechar while csv.reader expects it) + def _escapedoubled(row, + _type=str, + _old=self.escapechar, + _new=2 * self.escapechar): + return [s.replace(_old, _new) if isinstance(s, _type) else s for s in row] + else: + def _escapedoubled(row): + return row + self._escapedoubled = _escapedoubled + self._close = False + self._rows_written = 0 + + def __enter__(self): + if isinstance(self.f, (str, pathlib.Path)): + if isinstance(self.f, pathlib.Path): + self.f = str(self.f) + + self.f = io.open(self.f, 'wt', encoding=self.encoding, newline='') + self._close = True + elif self.f is None: + self.f = io.StringIO(newline='') + + self.writer = csv.writer(self.f, **self.kw) + return self + + def read(self) -> typing.Optional[bytes]: + """ + If the writer has been initialized passing `None` as target, the CSV data as `bytes` can be + retrieved calling this method. + """ + if hasattr(self.f, 'seek'): + self.f.seek(0) + if hasattr(self.f, 'read'): + return self.f.read().encode('utf-8') + + def __exit__(self, type, value, traceback): + if self._close: + self.f.close() + + def writerow(self, row: typing.Iterable[typing.Union[str, None]]): + self.writer.writerow(self._escapedoubled(row)) + self._rows_written += 1 + + def writerows(self, rows: typing.Iterable[typing.Union[tuple, list, dict]]): + """ + Writes each row in `rows` formatted as CSV row. This behaves as + [`csvwriter.writerows`](https://docs.python.org/3/library/csv.html#csv.csvwriter.writerows) + except when an iterable of `dict` objects is passed. In that case, it is assumed that all + items in `rows` are `dict`s and all have the same keys in the same order (as what would + be read by `UnicodeDictReader`). Then, the keys of the first item are written as header row + and the values of each row are written as subsequent rows. + + :param rows: The data to be written. + """ + for i, row in enumerate(rows): + if isinstance(row, dict): + if i == 0 and not self._rows_written: + # We write a header row. + self.writerow(row.keys()) + row = row.values() + self.writerow(row) + + +class UnicodeReader: + """ + Read Unicode data from a csv file. + + :param f: The source from which to read the data; a local path specified as `str` or \ + `pathlib.Path`, a file-like object or a `list` of lines. + :param dialect: Either a dialect name as recognized by `csv.reader` or a \ + :class:`~Dialect` instance for dialect customization beyond what can be done with \ + `csv.writer`. + :param kw: Keyword arguments passed through to `csv.reader`. + + .. code-block:: python + + >>> with UnicodeReader('tests/fixtures/frictionless-data.csv', delimiter='|') as reader: + ... for row in reader: + ... print(row) + ... break + ... + ['FK', 'Year', 'Location name', 'Value', 'binary', 'anyURI', 'email', 'boolean', 'array', + 'geojson'] + """ + def __init__( + self, + f: LINES_OR_PATH, + dialect: typing.Optional[typing.Union[Dialect, str]] = None, + **kw): + self.f = f + self.encoding = normalize_encoding(kw.pop('encoding', 'utf-8-sig')) + self.newline = kw.pop('lineterminator', None) + self.dialect = dialect if isinstance(dialect, Dialect) else None + if self.dialect: + self.encoding = self.dialect.python_encoding + self.kw = dialect.as_python_formatting_parameters() + self.kw.update(kw) + else: + self.kw = kw + if dialect: + self.kw['dialect'] = dialect + self._close = False + self.comments = [] + + # We potentially screw people with valid CSV files where the content - presumably the + # header - starts with 0xfeff. But the chance of irritating people trying to read Excel + # exported CSV with the defaults seems way bigger - and anyone with CSV column names + # starting with 0xfeff will run into more trouble down the line anyway ... + if self.encoding == 'utf-8': + self.encoding = 'utf-8-sig' + + # encoding of self.reader rows: differs from source encoding + # where we need to recode from non-8bit clean source encoding + # to utf-8 first to feed into the (byte-based) PY2 csv.reader + self._reader_encoding = self.encoding + + def __enter__(self): + if isinstance(self.f, (str, pathlib.Path)): + if isinstance(self.f, pathlib.Path): + self.f = str(self.f) + + self.f = io.open(self.f, mode='rt', encoding=self.encoding, newline=self.newline or '') + self._close = True + elif not hasattr(self.f, 'read'): + lines = [] + for line in self.f: + lines.append(line.decode(self.encoding) if isinstance(line, bytes) else line) + self.f = lines + self.reader = csv.reader(self.f, **self.kw) + self.lineno = -1 + return self + + def _next_row(self): + self.lineno += 1 + row = [ + s if isinstance(s, str) else s.decode(self._reader_encoding) + for s in next(self.reader)] + self.lineno += sum([list(s).count('\n') for s in row]) + return row + + def __next__(self): + row = self._next_row() + if self.dialect: + while (row and self.dialect.commentPrefix and # noqa: W504 + row[0].startswith(self.dialect.commentPrefix)) or \ + ((not row or set(row) == {''}) and self.dialect.skipBlankRows) or \ + (self.lineno < self.dialect.skipRows): + if (row and self.dialect.commentPrefix and # noqa: W504 + row[0].startswith(self.dialect.commentPrefix)) or \ + (row and self.lineno < self.dialect.skipRows): + self.comments.append(( + self.lineno, + self.dialect.delimiter.join(row).lstrip(self.dialect.commentPrefix).strip(), + )) + row = self._next_row() + row = [self.dialect.trimmer(s) for s in row][self.dialect.skipColumns:] + return row + + def __exit__(self, exc_type, exc_val, exc_tb): + if self._close: + self.f.close() + + def __iter__(self): + return self + + +class UnicodeReaderWithLineNumber(UnicodeReader): + """ + A `UnicodeReader` yielding (lineno, row) pairs, where "lineno" is the 1-based number of the + the **text line** where the (possibly multi-line) row data starts in the DSV file. + """ + def __next__(self): + """ + :return: a pair (1-based line number in the input, row) + """ + # Retrieve the row, thereby incrementing the line number: + row = super(UnicodeReaderWithLineNumber, self).__next__() + return self.lineno + 1, row + + +class UnicodeDictReader(UnicodeReader): + """ + A `UnicodeReader` yielding one `dict` per row. + + :param f: As for :class:`UnicodeReader` + :param fieldnames: + + .. code-block:: python + + >>> with UnicodeDictReader( + ... 'tests/fixtures/frictionless-data.csv', + ... dialect=Dialect(delimiter='|', header=False), + ... fieldnames=[str(i) for i in range(1, 11)]) as reader: + ... for row in reader: + ... print(row) + ... break + ... + OrderedDict([('1', 'FK'), ('2', 'Year'), ('3', 'Location name'), ('4', 'Value'), + ('5', 'binary'), ('6', 'anyURI'), ('7', 'email'), ('8', 'boolean'), ('9', 'array'), + ('10', 'geojson')]) + + """ + + def __init__(self, f, fieldnames=None, restkey=None, restval=None, **kw): + self._fieldnames = fieldnames # list of keys for the dict + self.restkey = restkey # key to catch long rows + self.restval = restval # default value for short rows + self.line_num = 0 + super(UnicodeDictReader, self).__init__(f, **kw) + + @property + def fieldnames(self): + if self._fieldnames is None: + try: + self._fieldnames = super(UnicodeDictReader, self).__next__() + except StopIteration: + pass + self.line_num = self.reader.line_num + if self._fieldnames: + if len(set(self._fieldnames)) != len(self._fieldnames): + warnings.warn('Duplicate column names!') + return self._fieldnames + + def __next__(self) -> collections.OrderedDict: + if self.line_num == 0: + # Used only for its side effect. + self.fieldnames + row = super(UnicodeDictReader, self).__next__() + self.line_num = self.reader.line_num + + # unlike the basic reader, we prefer not to return blanks, + # because we will typically wind up with a dict full of None + # values + while row == []: + row = super(UnicodeDictReader, self).__next__() + return self.item(row) + + def item(self, row) -> collections.OrderedDict: + d = collections.OrderedDict((k, v) for k, v in zip(self.fieldnames, row)) + lf = len(self.fieldnames) + lr = len(row) + if lf < lr: + d[self.restkey] = row[lf:] + elif lf > lr: + for key in self.fieldnames[lr:]: + d[key] = self.restval + return d + + +class NamedTupleReader(UnicodeDictReader): + """ + A `UnicodeReader` yielding one `namedtuple` per row. + + .. note:: + + This reader has some limitations, notably that fieldnames must be normalized to be + admissible Python names, but also bad performance (compared with `UnicodeDictReader`). + """ + + _normalize_fieldname = staticmethod(utils.normalize_name) + + @functools.cached_property + def cls(self): + fieldnames = list(map(self._normalize_fieldname, self.fieldnames)) + return collections.namedtuple('Row', fieldnames) + + def item(self, row): + d = UnicodeDictReader.item(self, row) + for name in self.fieldnames: + d.setdefault(name, None) + return self.cls( + **{self._normalize_fieldname(k): v for k, v in d.items() if k in self.fieldnames}) + + +def iterrows(lines_or_file: LINES_OR_PATH, + namedtuples: typing.Optional[bool] = False, + dicts: typing.Optional[bool] = False, + encoding: typing.Optional[str] = 'utf-8', + **kw) -> typing.Generator: + """Convenience factory function for csv reader. + + :param lines_or_file: Content to be read. Either a file handle, a file path or a list\ + of strings. + :param namedtuples: Yield namedtuples. + :param dicts: Yield dicts. + :param encoding: Encoding of the content. + :param kw: Keyword parameters are passed through to csv.reader. + :return: A generator over the rows. + """ + if namedtuples and dicts: + raise ValueError('either namedtuples or dicts can be chosen as output format') + elif namedtuples: + _reader = NamedTupleReader + elif dicts: + _reader = UnicodeDictReader + else: + _reader = UnicodeReader + + with _reader(lines_or_file, encoding=encoding, **kw) as r: + for item in r: + yield item + + +reader = iterrows + + +def rewrite(fname: typing.Union[str, pathlib.Path], + visitor: typing.Callable[[int, typing.List[str]], typing.Union[None, typing.List[str]]], + **kw): + """Utility function to rewrite rows in dsv files. + + :param fname: Path of the dsv file to operate on. + :param visitor: A callable that takes a line-number and a row as input and returns a \ + (modified) row or None to filter out the row. + :param kw: Keyword parameters are passed through to csv.reader/csv.writer. + """ + fname = utils.ensure_path(fname) + assert fname.is_file() + with tempfile.NamedTemporaryFile(delete=False) as fp: + tmp = pathlib.Path(fp.name) + + with UnicodeReader(fname, **kw) as reader_: + with UnicodeWriter(tmp, **kw) as writer: + for i, row in enumerate(reader_): + row = visitor(i, row) + if row is not None: + writer.writerow(row) + shutil.move(str(tmp), str(fname)) # Path.replace is Python 3.3+ + + +def add_rows(fname: typing.Union[str, pathlib.Path], *rows: typing.List[str]): + with tempfile.NamedTemporaryFile(delete=False) as fp: + tmp = pathlib.Path(fp.name) + + fname = utils.ensure_path(fname) + with UnicodeWriter(tmp) as writer: + if fname.exists(): + with UnicodeReader(fname) as reader_: + for row in reader_: + writer.writerow(row) + writer.writerows(rows) + shutil.move(str(tmp), str(fname)) # Path.replace is Python 3.3+ + + +def filter_rows_as_dict(fname: typing.Union[str, pathlib.Path], + filter_: typing.Callable[[dict], bool], + **kw) -> int: + """Rewrite a dsv file, filtering the rows. + + :param fname: Path to dsv file + :param filter_: callable which accepts a `dict` with a row's data as single argument\ + returning a `Boolean` indicating whether to keep the row (`True`) or to discard it \ + `False`. + :param kw: Keyword arguments to be passed `UnicodeReader` and `UnicodeWriter`. + :return: The number of rows that have been removed. + """ + filter_ = DictFilter(filter_) + rewrite(fname, filter_, **kw) + return filter_.removed + + +class DictFilter(object): + + def __init__(self, filter_): + self.header = None + self.filter = filter_ + self.removed = 0 + + def __call__(self, i, row): + if i == 0: + self.header = row + return row + if row: + item = dict(zip(self.header, row)) + if self.filter(item): + return row + else: + self.removed += 1 diff --git a/TTS/Kokoro/.venv/Lib/site-packages/csvw/dsv_dialects.py b/TTS/Kokoro/.venv/Lib/site-packages/csvw/dsv_dialects.py new file mode 100644 index 0000000000000000000000000000000000000000..e35f39118aff6f85c1a323c13a8bf7a35e0cf4b0 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/csvw/dsv_dialects.py @@ -0,0 +1,160 @@ +""" +DSV data can be surprisingly diverse. While Python's `csv` module offers out-of-the-box support +for the basic formatting parameters, CSVW recognizes a couple more, like `skipColumns` or +`skipRows`. + +.. seealso:: + + - ``_ + - ``_ + - ``_ +""" +import attr +import warnings +import functools + +from . import utils + +__all__ = ['Dialect'] + +ENCODING_MAP = { + 'UTF-8-BOM': 'utf-8-sig', # Recognize the name of this encoding in R. +} + + +# FIXME: replace with attrs.validators.ge(0) from attrs 21.3.0 +def _non_negative(instance, attribute, value): + if value < 0: # pragma: no cover + raise ValueError('{0} is not a valid {1}'.format(value, attribute.name)) + + +non_negative_int = [attr.validators.instance_of(int), _non_negative] + + +def convert_encoding(s): + s = utils.converter(str, 'utf-8', s) + try: + _ = 'x'.encode(ENCODING_MAP.get(s, s)) + return s + except LookupError: + warnings.warn('Invalid value for property: {}'.format(s)) + return 'utf-8' + + +@attr.s +class Dialect(object): + """ + A CSV dialect specification. + + .. seealso:: ``_ + """ + + encoding = attr.ib( + default='utf-8', + converter=convert_encoding, + validator=attr.validators.instance_of(str)) + + lineTerminators = attr.ib( + converter=functools.partial(utils.converter, list, ['\r\n', '\n']), + default=attr.Factory(lambda: ['\r\n', '\n'])) + + quoteChar = attr.ib( + converter=functools.partial(utils.converter, str, '"', allow_none=True), + default='"', + ) + + doubleQuote = attr.ib( + default=True, + converter=functools.partial(utils.converter, bool, True), + validator=attr.validators.instance_of(bool)) + + skipRows = attr.ib( + default=0, + converter=functools.partial(utils.converter, int, 0, cond=lambda s: s >= 0), + validator=non_negative_int) + + commentPrefix = attr.ib( + default='#', + converter=functools.partial(utils.converter, str, '#', allow_none=True), + validator=attr.validators.optional(attr.validators.instance_of(str))) + + header = attr.ib( + default=True, + converter=functools.partial(utils.converter, bool, True), + validator=attr.validators.instance_of(bool)) + + headerRowCount = attr.ib( + default=1, + converter=functools.partial(utils.converter, int, 1, cond=lambda s: s >= 0), + validator=non_negative_int) + + delimiter = attr.ib( + default=',', + converter=functools.partial(utils.converter, str, ','), + validator=attr.validators.instance_of(str)) + + skipColumns = attr.ib( + default=0, + converter=functools.partial(utils.converter, int, 0, cond=lambda s: s >= 0), + validator=non_negative_int) + + skipBlankRows = attr.ib( + default=False, + converter=functools.partial(utils.converter, bool, False), + validator=attr.validators.instance_of(bool)) + + skipInitialSpace = attr.ib( + default=False, + converter=functools.partial(utils.converter, bool, False), + validator=attr.validators.instance_of(bool)) + + trim = attr.ib( + default='false', + validator=attr.validators.in_(['true', 'false', 'start', 'end']), + converter=lambda v: functools.partial( + utils.converter, + (str, bool), 'false')('{0}'.format(v).lower() if isinstance(v, bool) else v)) + + def updated(self, **kw): + res = self.__class__(**attr.asdict(self)) + for k, v in kw.items(): + setattr(res, k, v) + return res + + @functools.cached_property + def escape_character(self): + return None if self.quoteChar is None else ('"' if self.doubleQuote else '\\') + + @functools.cached_property + def line_terminators(self): + return [self.lineTerminators] \ + if isinstance(self.lineTerminators, str) else self.lineTerminators + + @functools.cached_property + def trimmer(self): + return { + 'true': lambda s: s.strip(), + 'false': lambda s: s, + 'start': lambda s: s.lstrip(), + 'end': lambda s: s.rstrip() + }[self.trim] + + def asdict(self, omit_defaults=True): + return utils.attr_asdict(self, omit_defaults=omit_defaults) + + @property + def python_encoding(self): + return ENCODING_MAP.get(self.encoding, self.encoding) + + def as_python_formatting_parameters(self): + return { + 'delimiter': self.delimiter, + 'doublequote': self.doubleQuote, + # We have to hack around incompatible ways escape char is interpreted in csvw + # and python's csv lib: + 'escapechar': self.escape_character if not self.doubleQuote else None, + 'lineterminator': self.line_terminators[0], + 'quotechar': self.quoteChar, + 'skipinitialspace': self.skipInitialSpace, + 'strict': True, + } diff --git a/TTS/Kokoro/.venv/Lib/site-packages/csvw/frictionless.py b/TTS/Kokoro/.venv/Lib/site-packages/csvw/frictionless.py new file mode 100644 index 0000000000000000000000000000000000000000..3bd020025dd3b39bca95aba22a076abe69734ee9 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/csvw/frictionless.py @@ -0,0 +1,224 @@ +""" +Functionality to convert tabular data in Frictionless Data Packages to CSVW. + +We translate [table schemas](https://specs.frictionlessdata.io/table-schema/) defined +for [data resources](https://specs.frictionlessdata.io/data-resource/) in a +[data package](https://specs.frictionlessdata.io/data-package/) to a CVSW TableGroup. + +This functionality can be used together with the `frictionless describe` command to add +CSVW metadata to "raw" CSV tables. +""" +import json +import pathlib + + +def convert_column_spec(spec): + """ + https://specs.frictionlessdata.io/table-schema/#field-descriptors + + :param spec: + :return: + """ + typemap = { + 'year': 'gYear', + 'yearmonth': 'gYearMonth', + } + + titles = [t for t in [spec.get('title')] if t] + + res = {'name': spec['name'], 'datatype': {'base': 'string'}} + if 'type' in spec: + if spec['type'] == 'string' and spec.get('format') == 'binary': + res['datatype']['base'] = 'binary' + elif spec['type'] == 'string' and spec.get('format') == 'uri': + res['datatype']['base'] = 'anyURI' + elif spec['type'] in typemap: + res['datatype']['base'] = typemap[spec['type']] + elif spec['type'] in [ + 'string', 'number', 'integer', 'boolean', 'date', 'time', 'datetime', 'duration', + ]: + res['datatype']['base'] = spec['type'] + if spec['type'] == 'string' and spec.get('format'): + res['datatype']['dc:format'] = spec['format'] + if spec['type'] == 'boolean' and spec.get('trueValues') and spec.get('falseValues'): + res['datatype']['format'] = '{}|{}'.format( + spec['trueValues'][0], spec['falseValues'][0]) + if spec['type'] in ['number', 'integer']: + if spec.get('bareNumber') is True: # pragma: no cover + raise NotImplementedError( + 'bareNumber is not supported in CSVW. It may be possible to translate to ' + 'a number pattern, though. See ' + 'https://www.w3.org/TR/2015/REC-tabular-data-model-20151217/' + '#formats-for-numeric-types') + if any(prop in spec for prop in ['decimalChar', 'groupChar']): + res['datatype']['format'] = {} + for p in ['decimalChar', 'groupChar']: + if spec.get(p): + res['datatype']['format'][p] = spec[p] + elif spec['type'] in ['object', 'array']: + res['datatype']['base'] = 'json' + res['datatype']['dc:format'] = 'application/json' + elif spec['type'] == 'geojson': + res['datatype']['base'] = 'json' + res['datatype']['dc:format'] = 'application/geo+json' + + if titles: + res['titles'] = titles + if 'description' in spec: + res['dc:description'] = [spec['description']] + if 'rdfType' in spec: + res['propertyUrl'] = spec['rdfType'] + + constraints = spec.get('constraints', {}) + for prop in ['required', 'minLength', 'maxLength', 'minimum', 'maximum']: + if prop in constraints: + res['datatype'][prop] = constraints[prop] + if ('pattern' in constraints) and ('format' not in res['datatype']): + res['datatype']['format'] = constraints['pattern'] + # FIXME: we could transform the "enum" constraint for string into + # a regular expression in the "format" property. + return res + + +def convert_foreignKey(rsc_name, fk, resource_map): + """ + https://specs.frictionlessdata.io/table-schema/#foreign-keys + """ + # Rename "fields" to "columnReference" and map resource name to url (resolving self-referential + # foreign keys). + return dict( + columnReference=fk['fields'], + reference=dict( + columnReference=fk['reference']['fields'], + resource=resource_map[fk['reference']['resource'] or rsc_name], + ) + ) + + +def convert_table_schema(rsc_name, schema, resource_map): + """ + :param rsc_name: `name` property of the resource the schema belongs to. Needed to resolve \ + self-referential foreign keys. + :param schema: `dict` parsed from JSON representing a frictionless Table Schema object. + :param resource_map: `dict` mapping resource names to resource paths, needed to convert foreign\ + key constraints. + :return: `dict` suitable for instantiating a `csvw.metadata.Schema` object. + """ + res = dict( + columns=[convert_column_spec(f) for f in schema['fields']], + ) + for prop in [ + ('missingValues', 'null'), + 'primaryKey', + 'foreignKeys', + ]: + if isinstance(prop, tuple): + prop, toprop = prop + else: + toprop = prop + if prop in schema: + res[toprop] = schema[prop] + if prop == 'foreignKeys': + res[toprop] = [convert_foreignKey(rsc_name, fk, resource_map) for fk in res[toprop]] + return res + + +def convert_dialect(rsc): + """ + Limitations: lineTerminator is not supported. + + https://specs.frictionlessdata.io/csv-dialect/ + """ + d = rsc.get('dialect', {}) + # Work around https://github.com/frictionlessdata/frictionless-py/issues/1506 + if 'csv' in d: + d = d['csv'] + res = {} + if d.get('delimiter'): + res['delimiter'] = d['delimiter'] + if rsc.get('encoding'): + res['encoding'] = rsc['encoding'] + for prop in [ + 'delimiter', + 'quoteChar', + 'doubleQuote', + 'skipInitialSpace', + 'header', + ]: + if prop in d: + res[prop] = d[prop] + if 'commentChar' in d: + res['commentPrefix'] = d['commentChar'] + return res + + +class DataPackage: + def __init__(self, spec, directory=None): + if isinstance(spec, DataPackage): + self.json = spec.json + self.dir = spec.dir + return + if isinstance(spec, dict): + # already a parsed JSON object + self.dir = pathlib.Path(directory or '.') + elif isinstance(spec, pathlib.Path): + self.dir = directory or spec.parent + spec = json.loads(spec.read_text(encoding='utf8')) + else: # assume a JSON formatted string + spec = json.loads(spec) + self.dir = pathlib.Path(directory or '.') + + self.json = spec + + def to_tablegroup(self, cls=None): + from csvw import TableGroup + + md = {'@context': "http://www.w3.org/ns/csvw"} + # Package metadata: + md['dc:replaces'] = json.dumps(self.json) + + # version, + # image, + + for flprop, csvwprop in [ + ('id', 'dc:identifier'), + ('licenses', 'dc:license'), + ('title', 'dc:title'), + ('homepage', 'dcat:accessURL'), + ('description', 'dc:description'), + ('sources', 'dc:source'), + ('contributors', 'dc:contributor'), + ('profile', 'dc:conformsTo'), + ('keywords', 'dc:subject'), + ('created', 'dc:created'), + ]: + if flprop in self.json: + md[csvwprop] = self.json[flprop] + + if 'name' in self.json: + if 'id' not in self.json: + md['dc:identifier'] = self.json['name'] + elif 'title' not in self.json: + md['dc:title'] = self.json['name'] + + # Data Resource metadata: + resources = [rsc for rsc in self.json.get('resources', []) if 'path' in rsc] + resource_map = {rsc['name']: rsc['path'] for rsc in resources if 'name' in rsc} + for rsc in resources: + schema = rsc.get('schema') + if schema and \ + rsc.get('scheme') == 'file' and \ + rsc.get('format') == 'csv': + # Table Schema: + md.setdefault('tables', []) + table = dict( + url=rsc['path'], + tableSchema=convert_table_schema(rsc.get('name'), schema, resource_map), + dialect=convert_dialect(rsc), + ) + md['tables'].append(table) + + cls = cls or TableGroup + res = cls.fromvalue(md) + res._fname = self.dir / 'csvw-metadata.json' + return res diff --git a/TTS/Kokoro/.venv/Lib/site-packages/csvw/jsonld.py b/TTS/Kokoro/.venv/Lib/site-packages/csvw/jsonld.py new file mode 100644 index 0000000000000000000000000000000000000000..92daa4609780d42adb124846b79216692ee54001 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/csvw/jsonld.py @@ -0,0 +1,189 @@ +import re +import json +import math +import typing +import decimal +import pathlib +import datetime +import collections + +import attr +from rdflib import Graph, URIRef, Literal +from rfc3986 import URIReference +from isodate.duration import Duration + +from .utils import is_url + +__all__ = ['group_triples', 'to_json', 'Triple', 'format_value'] + + +def format_value(value, col): + """ + Format values as JSON-LD literals. + """ + if isinstance(value, (datetime.date, datetime.datetime, datetime.time)): + res = value.isoformat() + if col and col.datatype.base == 'time': + res = res.split('T')[-1] + if col and col.datatype.base == 'date': + res = re.sub('T[0-9.:]+', '', res) + if isinstance(value, (datetime.datetime, datetime.time)): + stamp, _, milliseconds = res.partition('.') + return '{}.{}'.format(stamp, milliseconds.rstrip('0')) if milliseconds \ + else stamp.replace('+00:00', 'Z') + return res # pragma: no cover + if isinstance(value, datetime.timedelta): + return col.datatype.formatted(value) + if isinstance(value, Duration): + return col.datatype.formatted(value) + if isinstance(value, decimal.Decimal): + value = float(value) + if isinstance(value, URIReference): + return value.unsplit() + if isinstance(value, bytes): + return col.datatype.formatted(value) + if isinstance(value, pathlib.Path): + return str(value) + if isinstance(value, float): + return 'NaN' if math.isnan(value) else ( + '{}INF'.format('-' if value < 0 else '') if math.isinf(value) else value) + return value + + +@attr.s +class Triple: + """ + A table cell's data as RDF triple. + """ + about = attr.ib() + property = attr.ib() + value = attr.ib() + + def as_rdflib_triple(self): + return ( + URIRef(self.about), + URIRef(self.property), + URIRef(self.value) if is_url(self.value) else Literal(self.value)) + + @classmethod + def from_col(cls, table, col, row, prop, val, rownum): + """ + + """ + _name = col.header if col else None + + propertyUrl = col.propertyUrl if col else table.inherit('propertyUrl') + if propertyUrl: + prop = table.expand(propertyUrl, row, _row=rownum, _name=_name, qname=True) + + is_type = prop == 'rdf:type' + valueUrl = col.valueUrl if col else table.inherit('valueUrl') + if valueUrl: + val = table.expand(valueUrl, row, _row=rownum, _name=_name, qname=is_type) + val = format_value(val, col) + s = None + aboutUrl = col.aboutUrl if col else None + if aboutUrl: + s = table.expand(aboutUrl, row, _row=rownum, _name=_name) or s + return cls(about=s, property=prop, value=val) + + +def frame(data: list) -> list: + """ + Inline referenced items to force a deterministic graph layout. + + .. see:: https://w3c.github.io/json-ld-framing/#introduction + """ + items, refs = collections.OrderedDict(), {} + for item in data: + itemid = item.get('@id') + if itemid: + items[itemid] = item + for vs in item.values(): + for v in [vs] if not isinstance(vs, list) else vs: + if isinstance(v, dict): + refid = v.get('@id') + if refid: + refs.setdefault(refid, (v, []))[1].append(item) + for ref, subjects in refs.values(): + if len(subjects) == 1 and ref['@id'] in items: + ref.update(items.pop(ref['@id'])) + return list(items.values()) + + +def to_json(obj, flatten_list=False): + """ + Simplify JSON-LD data by refactoring trivial objects. + """ + if isinstance(obj, dict): + if '@value' in obj: + obj = obj['@value'] + if len(obj) == 1 and '@id' in obj: + obj = obj['@id'] + if isinstance(obj, dict): + return { + '@type' if k == 'rdf:type' else k: to_json(v, flatten_list=flatten_list) + for k, v in obj.items()} + if isinstance(obj, list): + if len(obj) == 1 and flatten_list: + return to_json(obj[0], flatten_list=flatten_list) + return [to_json(v, flatten_list=flatten_list) for v in obj] + return obj + + +def group_triples(triples: typing.Iterable[Triple]) -> typing.List[dict]: + """ + Group and frame triples into a `list` of JSON objects. + """ + merged = [] + for triple in triples: + if isinstance(triple.value, list): + for t in merged: + if t.property == triple.property and isinstance(t.value, list): + t.value.extend(triple.value) + break + else: + merged.append(triple) + else: + merged.append(triple) + + grouped = collections.OrderedDict() + triples = [] + # First pass: get top-level properties. + for triple in merged: + if triple.about is None and triple.property == '@id': + grouped[triple.property] = triple.value + else: + if not triple.about: + # For test48 + if triple.property in grouped: + if not isinstance(grouped[triple.property], list): + grouped[triple.property] = [grouped[triple.property]] + grouped[triple.property].append(triple.value) + else: + grouped[triple.property] = triple.value + else: + triples.append(triple) + if not triples: + return [grouped] + + g = Graph() + for triple in triples: + g.add(triple.as_rdflib_triple()) + if '@id' in grouped: + for prop, val in grouped.items(): + if prop != '@id': + g.add(Triple(about=grouped['@id'], property=prop, value=val).as_rdflib_triple()) + res = g.serialize(format='json-ld') + # Frame and simplify the resulting objects, augment with list index: + res = [(i, to_json(v, flatten_list=True)) for i, v in enumerate(frame(json.loads(res)))] + # Sort the objects making sure the one with the row's aboutUrl as @id comes first: + res = [k[1] for k in sorted( + res, key=lambda o: -1 if o[1].get('@id') == grouped.get('@id') else o[0])] + # If there's no aboutUrl for the row and we have only one object from triples, we just merge + # the properties into a single object. + if grouped and ('@id' not in grouped) and len(res) == 1: + grouped.update(res[0]) + return [grouped] + + return res diff --git a/TTS/Kokoro/.venv/Lib/site-packages/csvw/metadata.py b/TTS/Kokoro/.venv/Lib/site-packages/csvw/metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..4d485e2bf20e8496057f8bf2799f7327313960e2 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/csvw/metadata.py @@ -0,0 +1,1873 @@ +# metadata.py + +"""Functionality to read and write metadata for CSV files. + +This module implements (partially) the W3C recommendation +"Metadata Vocabulary for Tabular Data". + +.. seealso:: https://www.w3.org/TR/tabular-metadata/ +""" +import io +import re +import json +import shutil +import decimal +import pathlib +import typing +import zipfile +import operator +import warnings +import functools +import itertools +import contextlib +import collections +from urllib.parse import urljoin, urlparse, urlunparse + +from language_tags import tags +import attr +import requests +import uritemplate + +from . import utils +from .datatypes import DATATYPES +from .dsv import Dialect as BaseDialect, UnicodeReaderWithLineNumber, UnicodeWriter +from .frictionless import DataPackage +from . import jsonld + +DEFAULT = object() + +__all__ = [ + 'TableGroup', + 'Table', 'Column', 'ForeignKey', + 'Link', 'NaturalLanguage', + 'Datatype', + 'is_url', + 'CSVW', +] + +NAMESPACES = { + 'csvw': 'http://www.w3.org/ns/csvw#', + 'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#', + 'rdfs': 'http://www.w3.org/2000/01/rdf-schema#', + 'xsd': 'http://www.w3.org/2001/XMLSchema#', + 'dc': 'http://purl.org/dc/terms/', + 'dcat': 'http://www.w3.org/ns/dcat#', + 'prov': 'http://www.w3.org/ns/prov#', + 'schema': 'http://schema.org/', + "as": "https://www.w3.org/ns/activitystreams#", + "cc": "http://creativecommons.org/ns#", + "ctag": "http://commontag.org/ns#", + "dc11": "http://purl.org/dc/elements/1.1/", + "dctypes": "http://purl.org/dc/dcmitype/", + "dqv": "http://www.w3.org/ns/dqv#", + "duv": "https://www.w3.org/ns/duv#", + "foaf": "http://xmlns.com/foaf/0.1/", + "gr": "http://purl.org/goodrelations/v1#", + "grddl": "http://www.w3.org/2003/g/data-view#", + "ical": "http://www.w3.org/2002/12/cal/icaltzd#", + "jsonld": "http://www.w3.org/ns/json-ld#", + "ldp": "http://www.w3.org/ns/ldp#", + "ma": "http://www.w3.org/ns/ma-ont#", + "oa": "http://www.w3.org/ns/oa#", + "odrl": "http://www.w3.org/ns/odrl/2/", + "og": "http://ogp.me/ns#", + "org": "http://www.w3.org/ns/org#", + "owl": "http://www.w3.org/2002/07/owl#", + "qb": "http://purl.org/linked-data/cube#", + "rdfa": "http://www.w3.org/ns/rdfa#", + "rev": "http://purl.org/stuff/rev#", + "rif": "http://www.w3.org/2007/rif#", + "rr": "http://www.w3.org/ns/r2rml#", + "sd": "http://www.w3.org/ns/sparql-service-description#", + "sioc": "http://rdfs.org/sioc/ns#", + "skos": "http://www.w3.org/2004/02/skos/core#", + "skosxl": "http://www.w3.org/2008/05/skos-xl#", + "sosa": "http://www.w3.org/ns/sosa/", + "ssn": "http://www.w3.org/ns/ssn/", + "time": "http://www.w3.org/2006/time#", + "v": "http://rdf.data-vocabulary.org/#", + "vcard": "http://www.w3.org/2006/vcard/ns#", + "void": "http://rdfs.org/ns/void#", + "wdr": "http://www.w3.org/2007/05/powder#", + "wrds": "http://www.w3.org/2007/05/powder-s#", + "xhv": "http://www.w3.org/1999/xhtml/vocab#", + "xml": "http://www.w3.org/XML/1998/namespace", +} +CSVW_TERMS = """Cell +Column +Datatype +Dialect +Direction +ForeignKey +JSON +NumericFormat +Row +Schema +Table +TableGroup +TableReference +Transformation +aboutUrl +base +columnReference +columns +commentPrefix +datatype +decimalChar +default +delimiter +describes +dialect +doubleQuote +encoding +foreignKeys +format +groupChar +header +headerRowCount +json +lang +length +lineTerminators +maxExclusive +maxInclusive +maxLength +maximum +minExclusive +minInclusive +minLength +minimum +name +notes +null +ordered +pattern +primaryKey +propertyUrl +quoteChar +reference +referencedRows +required +resource +row +rowTitles +rownum +schemaReference +scriptFormat +separator +skipBlankRows +skipColumns +skipInitialSpace +skipRows +source +suppressOutput +tableDirection +tableSchema +tables +targetFormat +textDirection +titles +transformations +trim +uriTemplate +url +valueUrl +virtual""".split() +is_url = utils.is_url + + +class Invalid: + pass + + +INVALID = Invalid() + + +@attr.s +class Dialect(BaseDialect): + """ + The spec is ambiguous regarding a default for the commentPrefix property: + + > commentPrefix + > An atomic property that sets the comment prefix flag to the single provided value, which + > MUST be a string. The default is "#". + + vs. + + > comment prefix + > A string that, when it appears at the beginning of a row, indicates that the row is a + > comment that should be associated as a rdfs:comment annotation to the table. This is set + > by the commentPrefix property of a dialect description. The default is null, which means + > no rows are treated as comments. A value other than null may mean that the source numbers + > of rows are different from their numbers. + + So, in order to pass the number formatting tests, with column names like `##.#`, we chose + the second reading - i.e. by default no rows are treated as comments. + """ + commentPrefix = attr.ib( + default=None, + converter=functools.partial(utils.converter, str, None, allow_none=True), + validator=attr.validators.optional(attr.validators.instance_of(str))) + + +def json_open(filename, mode='r', encoding='utf-8'): + assert encoding == 'utf-8' + return io.open(filename, mode, encoding=encoding) + + +def get_json(fname) -> typing.Union[list, dict]: + fname = str(fname) + if is_url(fname): + return requests.get(fname).json(object_pairs_hook=collections.OrderedDict) + with json_open(fname) as f: + return json.load(f, object_pairs_hook=collections.OrderedDict) + + +def log_or_raise(msg, log=None, level='warning', exception_cls=ValueError): + if log: + getattr(log, level)(msg) + else: + raise exception_cls(msg) + + +def nolog(level='warning'): + from types import MethodType + + class Log(object): + pass + + log = Log() + setattr(log, level, MethodType(lambda *args, **kw: None, log)) + return log + + +class URITemplate(uritemplate.URITemplate): + + def __eq__(self, other): + if isinstance(other, str): + return self.uri == other + if not hasattr(other, 'uri'): + return False + return super(URITemplate, self).__eq__(other) + + def asdict(self, **kw): + return '{}'.format(self) + + +def uri_template_property(): + """ + + Note: We do not currently provide support for supplying the "_" variables like "_row" + when expanding a URI template. + + .. seealso:: http://w3c.github.io/csvw/metadata/#uri-template-properties + """ + def converter_uriTemplate(v): + if v is None: + return None + if not isinstance(v, str): + warnings.warn('Invalid value for aboutUrl property') + return INVALID + return URITemplate(v) + + return attr.ib( + default=None, + validator=attr.validators.optional(attr.validators.instance_of((URITemplate, Invalid))), + converter=converter_uriTemplate) + + +class Link: + """ + + .. seealso:: http://w3c.github.io/csvw/metadata/#link-properties + """ + + def __init__(self, string: typing.Union[str, pathlib.Path]): + if not isinstance(string, (str, pathlib.Path)): + raise ValueError('Invalid value for link property') + self.string = string + + def __str__(self): + return self.string + + def asdict(self, omit_defaults=True): + return self.string + + def __eq__(self, other): + # FIXME: Only naive, un-resolved comparison is supported at the moment. + return self.string == other.string if isinstance(other, Link) else False + + def resolve(self, base): + """ + Resolve a `Link` relative to `base`. + + :param base: + :return: Either a string, representing a URL, or a `pathlib.Path` object, representing \ + a local file. + """ + if hasattr(base, 'joinpath'): + if is_url(self.string): + return self.string + return (base if base.is_dir() else base.parent) / self.string + return urljoin(base, self.string) + + +def link_property(required=False): + return attr.ib( + default=None, + validator=attr.validators.optional(attr.validators.instance_of(Link)), + converter=lambda v: v if v is None else Link(v)) + + +class NaturalLanguage(collections.OrderedDict): + """ + + .. seealso:: http://w3c.github.io/csvw/metadata/#natural-language-properties + """ + + def __init__(self, value): + super(NaturalLanguage, self).__init__() + self.value = value + if isinstance(self.value, str): + self[None] = [self.value] + elif isinstance(self.value, (list, tuple)): + if not all(isinstance(v, str) for v in self.value): + warnings.warn('titles with array values containing non-string values are ignored') + else: + self[None] = list(self.value) + elif isinstance(self.value, dict): + for k, v in self.value.items(): + if not tags.check(k): + raise ValueError('Invalid language tag for NaturalLanguage') + if not isinstance(v, (list, tuple)): + v = [v] + titles = [] + for vv in v: + if isinstance(vv, str): + titles.append(vv) + else: + warnings.warn('Title with value which is not a string is ignored') + self[k] = titles + else: + raise ValueError('invalid value type for NaturalLanguage') + + def asdict(self, omit_defaults=True): + if list(self) == [None]: + if len(self[None]) == 1: + return self.getfirst() + return self[None] + return collections.OrderedDict( + ('und' if k is None else k, v[0] if len(v) == 1 else v) + for k, v in self.items()) + + def add(self, string, lang=None): + if lang not in self: + self[lang] = [] + self[lang].append(string) + + def __str__(self): + return self.getfirst() or next(iter(self.values()))[0] + + def getfirst(self, lang=None): + return self.get(lang, [None])[0] + + +def valid_id_property(v): + if not isinstance(v, str): + warnings.warn('Inconsistent link property') + return None + if v.startswith('_'): + raise ValueError('Invalid @id property: {}'.format(v)) + return v + + +def valid_common_property(v): + if isinstance(v, dict): + if not {k[1:] for k in v if k.startswith('@')}.issubset( + {'id', 'language', 'type', 'value'}): + raise ValueError( + "Aside from @value, @type, @language, and @id, the properties used on an object " + "MUST NOT start with @.") + if '@value' in v: + if len(v) > 1: + if len(v) > 2 \ + or set(v.keys()) not in [{'@value', '@language'}, {'@value', '@type'}] \ + or not isinstance(v['@value'], (str, bool, int, decimal.Decimal)): + raise ValueError( + "If a @value property is used on an object, that object MUST NOT have " + "any other properties aside from either @type or @language, and MUST " + "NOT have both @type and @language as properties. The value of the " + "@value property MUST be a string, number, or boolean value.") + if '@language' in v and '@value' not in v: + raise ValueError( + "A @language property MUST NOT be used on an object unless it also has a " + "@value property.") + if '@id' in v: + v['@id'] = valid_id_property(v['@id']) + if '@language' in v: + if not (isinstance(v['@language'], str) and tags.check(v['@language'])): + warnings.warn('Invalid language tag') + del v['@language'] + if '@type' in v: + vv = v['@type'] + if isinstance(vv, str): + if vv.startswith('_:'): + raise ValueError( + 'The value of any @id or @type contained within a metadata document ' + 'MUST NOT be a blank node.') + if not is_url(vv) and \ + not any(vv == ns or vv.startswith(ns + ':') for ns in NAMESPACES) and \ + vv not in CSVW_TERMS: + raise ValueError( + 'The value of any member of @type MUST be either a term defined in ' + '[csvw-context], a prefixed name where the prefix is a term defined in ' + '[csvw-context], or an absolute URL.') + elif not isinstance(vv, (list, dict)): + raise ValueError('Invalid datatype for @type') + return {k: valid_common_property(vv) for k, vv in v.items()} + if isinstance(v, list): + return [valid_common_property(vv) for vv in v] + return v + + +@attr.s +class DescriptionBase: + """Container for + - common properties (see http://w3c.github.io/csvw/metadata/#common-properties) + - @-properties. + """ + + common_props = attr.ib(default=attr.Factory(dict)) + at_props = attr.ib(default=attr.Factory(dict)) + + @classmethod + def partition_properties(cls, + d: typing.Union[dict, typing.Any], + type_name: typing.Optional[str] = None, + strict=True) -> typing.Union[dict, None]: + if d and not isinstance(d, dict): + return + fields = attr.fields_dict(cls) + type_name = type_name or cls.__name__ + c, a, dd = {}, {}, {} + for k, v in (d or {}).items(): + if k.startswith('@'): + if k == '@id': + v = valid_id_property(v) + if k == '@type' and v != type_name: + raise ValueError('Invalid @type property {} for {}'.format(v, type_name)) + a[k[1:]] = v + elif ':' in k: + c[k] = valid_common_property(v) + else: + if strict and (k not in fields): + warnings.warn('Invalid property {} for {}'.format(k, type_name)) + else: + dd[k] = v + return dict(common_props=c, at_props=a, **dd) + + @classmethod + def fromvalue(cls, d: dict): + return cls(**cls.partition_properties(d)) + + def _iter_dict_items(self, omit_defaults): + def _asdict_single(v): + return v.asdict(omit_defaults=omit_defaults) if hasattr(v, 'asdict') else v + + def _asdict_multiple(v): + if isinstance(v, (list, tuple)): + return [_asdict_single(vv) for vv in v] + return _asdict_single(v) + + for k, v in sorted(self.at_props.items()): + yield '@' + k, _asdict_multiple(v) + + for k, v in sorted(self.common_props.items()): + yield k, _asdict_multiple(v) + + for k, v in utils.attr_asdict(self, omit_defaults=omit_defaults).items(): + if k not in ('common_props', 'at_props'): + yield k, _asdict_multiple(v) + + def asdict(self, omit_defaults=True) -> dict: + # Note: The `null` property is the only inherited, list-valued property where the default + # is not the empty list. Thus, to allow setting it to empty, we must treat `null` as + # special case here. + # See also https://www.w3.org/TR/tabular-metadata/#dfn-inherited-property + return collections.OrderedDict( + (k, v) for k, v in self._iter_dict_items(omit_defaults) + if (k == 'null' or (v not in ([], {})))) + + +def optional_int(): + return attr.ib( + default=None, + validator=attr.validators.optional(attr.validators.instance_of(int)), + converter=lambda v: v if v is None else int(v)) + + +@attr.s +class Datatype(DescriptionBase): + """ + A datatype description + + Cells within tables may be annotated with a datatype which indicates the type of the values + obtained by parsing the string value of the cell. + + .. seealso:: ``_ + """ + + base = attr.ib( + default=None, + converter=functools.partial( + utils.converter, + str, 'string', allow_none=True, cond=lambda ss: ss is None or ss in DATATYPES), + validator=attr.validators.optional(attr.validators.in_(DATATYPES))) + format = attr.ib(default=None) + length = optional_int() + minLength = optional_int() + maxLength = optional_int() + minimum = attr.ib(default=None) + maximum = attr.ib(default=None) + minInclusive = attr.ib(default=None) + maxInclusive = attr.ib(default=None) + minExclusive = attr.ib(default=None) + maxExclusive = attr.ib(default=None) + + @classmethod + def fromvalue(cls, v: typing.Union[str, dict, 'Datatype']) -> 'Datatype': + """ + :param v: Initialization data for `cls`; either a single string that is the main datatype \ + of the values of the cell or a datatype description object, i.e. a `dict` or a `cls` \ + instance. + :return: An instance of `cls` + """ + if isinstance(v, str): + return cls(base=v) + + if isinstance(v, dict): + v.setdefault('base', 'string') + return cls(**cls.partition_properties(v)) + + if isinstance(v, cls): + return v + + raise ValueError(v) + + def __attrs_post_init__(self): + for attr_ in [ + 'minimum', 'maximum', 'minInclusive', 'maxInclusive', 'minExclusive', 'maxExclusive' + ]: + if getattr(self, attr_) is not None: + setattr(self, attr_, self.parse(getattr(self, attr_))) + + if self.length is not None: + if self.minLength is not None and self.length < self.minLength: + raise ValueError('minLength > length') + + if self.maxLength is not None: + if self.length > self.maxLength: + raise ValueError('maxLength < length') + + if self.minLength is not None and self.maxLength is not None \ + and self.minLength > self.maxLength: + raise ValueError('minLength > maxLength') + + if not isinstance(self.derived_description, dict): + raise ValueError() # pragma: no cover + + if not isinstance( + self.basetype(), + tuple((DATATYPES[name] for name in ['decimal', 'float', 'datetime', 'duration']))): + if any([getattr(self, at) for at in + 'minimum maximum minExclusive maxExclusive minInclusive maxInclusive'.split()]): + raise ValueError( + 'Applications MUST raise an error if minimum, minInclusive, maximum, ' + 'maxInclusive, minExclusive, or maxExclusive are specified and the base ' + 'datatype is not a numeric, date/time, or duration type.') + + if not isinstance( + self.basetype(), + (DATATYPES['string'], DATATYPES['base64Binary'], DATATYPES['hexBinary'])): + if self.length or self.minLength or self.maxLength: + raise ValueError( + 'Applications MUST raise an error if length, maxLength, or minLength are ' + 'specified and the base datatype is not string or one of its subtypes, or a ' + 'binary type.') + + if (self.minInclusive and self.minExclusive) or (self.maxInclusive and self.maxExclusive): + raise ValueError( + 'Applications MUST raise an error if both minInclusive and minExclusive are ' + 'specified, or if both maxInclusive and maxExclusive are specified.') + + if (self.minInclusive and self.maxExclusive and self.maxExclusive <= self.minInclusive) or \ + (self.minInclusive and self.maxInclusive and self.maxInclusive < self.minInclusive): + raise ValueError('') + + if (self.minExclusive and self.maxExclusive and self.maxExclusive <= self.minExclusive) or ( + self.minExclusive and self.maxInclusive and self.maxInclusive <= self.minExclusive): + raise ValueError('') + + if 'id' in self.at_props and any( + self.at_props['id'] == NAMESPACES['xsd'] + dt for dt in DATATYPES): + raise ValueError('datatype @id MUST NOT be the URL of a built-in datatype.') + + if isinstance(self.basetype(), DATATYPES['decimal']) and \ + 'pattern' in self.derived_description: + if not set(self.derived_description['pattern']).issubset(set('#0.,;%‰E-+')): + self.format = None + warnings.warn('Invalid number pattern') + + def asdict(self, omit_defaults=True): + res = DescriptionBase.asdict(self, omit_defaults=omit_defaults) + for attr_ in [ + 'minimum', 'maximum', 'minInclusive', 'maxInclusive', 'minExclusive', 'maxExclusive' + ]: + if attr_ in res: + res[attr_] = self.formatted(res[attr_]) + if len(res) == 1 and 'base' in res: + return res['base'] + return res + + @property + def basetype(self): + return DATATYPES[self.base] + + @property + def derived_description(self): + return self.basetype.derived_description(self) + + def formatted(self, v): + return self.basetype.to_string(v, **self.derived_description) + + def parse(self, v): + if v is None: + return v + return self.basetype.to_python(v, **self.derived_description) + + def validate(self, v): + if v is None: + return v + try: + l_ = len(v or '') + if self.length is not None and l_ != self.length: + raise ValueError('value must have length {}'.format(self.length)) + if self.minLength is not None and l_ < self.minLength: + raise ValueError('value must have at least length {}'.format(self.minLength)) + if self.maxLength is not None and l_ > self.maxLength: + raise ValueError('value must have at most length {}'.format(self.maxLength)) + except TypeError: + pass + if self.basetype.minmax: + if self.minimum is not None and v < self.minimum: + raise ValueError('value must be >= {}'.format(self.minimum)) + if self.minInclusive is not None and v < self.minInclusive: + raise ValueError('value must be >= {}'.format(self.minInclusive)) + if self.minExclusive is not None and v <= self.minExclusive: + raise ValueError('value must be > {}'.format(self.minExclusive)) + if self.maximum is not None and v > self.maximum: + raise ValueError('value must be <= {}'.format(self.maximum)) + if self.maxInclusive is not None and v > self.maxInclusive: + raise ValueError('value must be <= {}'.format(self.maxInclusive)) + if self.maxExclusive is not None and v >= self.maxExclusive: + raise ValueError('value must be < {}'.format(self.maxExclusive)) + return v + + def read(self, v): + return self.validate(self.parse(v)) + + +def converter_null(v): + res = [] if v is None else (v if isinstance(v, list) else [v]) + if not all(isinstance(vv, str) for vv in res): + warnings.warn('Invalid null property') + return [""] + return res + + +def converter_lang(v): + if not tags.check(v): + warnings.warn('Invalid language tag') + return 'und' + return v + + +@attr.s +class Description(DescriptionBase): + """Adds support for inherited properties. + + .. seealso:: http://w3c.github.io/csvw/metadata/#inherited-properties + """ + + # To be able to resolve inheritance chains, we also provide a place to store a + # reference to the containing object. Note that this attribute is ignored when judging + # equality between objects. Thus, identically specified columns of different tables will be + # considered equal. + _parent = attr.ib(default=None, repr=False, eq=False) + + aboutUrl = uri_template_property() + datatype = attr.ib( + default=None, + converter=lambda v: v if not v else Datatype.fromvalue(v)) + default = attr.ib( + default="", + converter=functools.partial(utils.converter, str, "", allow_list=False), + ) + lang = attr.ib(default="und", converter=converter_lang) + null = attr.ib(default=attr.Factory(lambda: [""]), converter=converter_null) + ordered = attr.ib( + default=None, + converter=functools.partial(utils.converter, bool, False, allow_none=True), + ) + propertyUrl = uri_template_property() + required = attr.ib(default=None) + separator = attr.ib( + converter=functools.partial(utils.converter, str, None, allow_none=True), + default=None, + ) + textDirection = attr.ib( + default=None, + converter=functools.partial( + utils.converter, + str, None, allow_none=True, cond=lambda v: v in [None, "ltr", "rtl", "auto", "inherit"]) + ) + valueUrl = uri_template_property() + + def inherit(self, attr): + v = getattr(self, attr) + if v is None and self._parent: + return self._parent.inherit(attr) if hasattr(self._parent, 'inherit') \ + else getattr(self._parent, attr) + return v + + def inherit_null(self): + if self.null == [""]: + if self._parent and hasattr(self._parent, 'inherit_null'): + return self._parent.inherit_null() + return self.null + + +def converter_titles(v): + try: + return v if v is None else NaturalLanguage(v) + except ValueError: + warnings.warn('Invalid titles property') + return None + + +@attr.s +class Column(Description): + """ + A column description is an object that describes a single column. + + The description provides additional human-readable documentation for a column, as well as + additional information that may be used to validate the cells within the column, create a + user interface for data entry, or inform conversion into other formats. + + .. seealso:: ``_ + """ + name = attr.ib( + default=None, + converter=functools.partial(utils.converter, str, None, allow_none=True) + ) + suppressOutput = attr.ib( + default=False, + converter=functools.partial(utils.converter, bool, False)) + titles = attr.ib( + default=None, + validator=attr.validators.optional(attr.validators.instance_of(NaturalLanguage)), + converter=converter_titles) + virtual = attr.ib(default=False, converter=functools.partial(utils.converter, bool, False)) + _number = attr.ib(default=None, repr=False) + + def __str__(self): + return self.name or \ + (self.titles and self.titles.getfirst()) or \ + '_col.{}'.format(self._number) + + def has_title(self, v): + if self.name and self.name == v: + return True + for tag, titles in (self.titles or {}).items(): + if v in titles: + return tag or 'und' + return False + + @property + def header(self): + return '{}'.format(self) + + def read(self, v, strict=True): + required = self.inherit('required') + null = self.inherit_null() + default = self.inherit('default') + separator = self.inherit('separator') + datatype = self.inherit('datatype') + + if not v: + v = default + + if required and v in null: + if not strict: + warnings.warn('required column value is missing') + raise ValueError('required column value is missing') + + if separator: + if not v: + v = [] + elif v in null: + v = None + else: + v = (vv or default for vv in v.split(separator)) + v = [None if vv in null else vv for vv in v] + elif v in null: + v = None + + if datatype: + if isinstance(v, list): + try: + return [datatype.read(vv) for vv in v] + except ValueError: + if not strict: + warnings.warn('Invalid value for list element.') + return v + raise + return datatype.read(v) + return v + + def write(self, v): + sep = self.inherit('separator') + null = self.inherit_null() + datatype = self.inherit('datatype') + + def fmt(v): + if v is None: + return null[0] + if datatype: + return datatype.formatted(v) + return v + + if sep: + return sep.join(fmt(vv) for vv in v or []) + return fmt(v) + + +def column_reference(): + return attr.ib( + default=None, + validator=attr.validators.optional(attr.validators.instance_of(list)), + converter=lambda v: v if isinstance(v, list) or v is None else [v]) + + +@attr.s +class Reference: + + resource = link_property() + schemaReference = link_property() + columnReference = column_reference() + + def __attrs_post_init__(self): + if self.resource is not None and self.schemaReference is not None: + raise ValueError(self) + + +@attr.s +class ForeignKey: + + columnReference = column_reference() + reference = attr.ib(default=None) + + @classmethod + def fromdict(cls, d): + if isinstance(d, dict): + try: + _ = Reference(**d['reference']) + except TypeError: + raise ValueError('Invalid reference property') + if not set(d.keys()).issubset({'columnReference', 'reference'}): + raise ValueError('Invalid foreignKey spec') + kw = dict(d, reference=Reference(**d['reference'])) + return cls(**kw) + + def asdict(self, **kw): + res = utils.attr_asdict(self, **kw) + res['reference'] = utils.attr_asdict(res['reference'], **kw) + return res + + +def converter_foreignKeys(v): + res = [] + for d in functools.partial(utils.converter, dict, None)(v): + try: + res.append(ForeignKey.fromdict(d)) + except TypeError: + warnings.warn('Invalid foreignKeys spec') + return res + + +@attr.s +class Schema(Description): + """ + A schema description is an object that encodes the information about a schema, which describes + the structure of a table. + + :ivar columns: `list` of :class:`Column` descriptions. + :ivar foreignKeys: `list` of :class:`ForeignKey` descriptions. + + .. seealso:: ``_ + """ + columns = attr.ib( + default=attr.Factory(list), + converter=lambda v: [ + Column.fromvalue(c) for c in functools.partial(utils.converter, dict, None)( + functools.partial(utils.converter, list, [])(v))]) + foreignKeys = attr.ib( + default=attr.Factory(list), + converter=lambda v: [] if v is None else converter_foreignKeys(v)) + primaryKey = column_reference() + rowTitles = attr.ib( + default=attr.Factory(list), + converter=lambda v: v if isinstance(v, list) else [v], + ) + + def __attrs_post_init__(self): + virtual, seen, names = False, set(), set() + for i, col in enumerate(self.columns): + if col.name and (col.name.startswith('_') or re.search(r'\s', col.name)): + warnings.warn('Invalid column name') + if col.virtual: # first virtual column sets the flag + virtual = True + elif virtual: # non-virtual column after virtual column! + raise ValueError('no non-virtual column allowed after virtual columns') + if not virtual: + if col.header in seen: + warnings.warn('Duplicate column name!') + if col.name: + if col.name in names: + raise ValueError('Duplicate column name {}'.format(col.name)) + names.add(col.name) + seen.add(col.header) + col._parent = self + col._number = i + 1 + for colref in self.primaryKey or []: + col = self.columndict.get(colref) + if col and not col.name: + warnings.warn('A primaryKey referenced column MUST have a `name` property') + self.primaryKey = None + + @classmethod + def fromvalue(cls, v): + if isinstance(v, str): + try: + # The schema is referenced with a URL + v = requests.get(v).json() + except: # pragma: no cover # noqa: E722 + return v + if not isinstance(v, dict): + if isinstance(v, int): + warnings.warn('Invalid value for tableSchema property') + v = {} + return cls(**cls.partition_properties(v)) + + @property + def columndict(self): + return {c.header: c for c in self.columns} + + def get_column(self, name, strict=False): + col = self.columndict.get(name) + assert (not strict) or (col and col.name) + if not col: + for c in self.columns: + if c.titles and c.titles.getfirst() == name: + return c + if c.propertyUrl and c.propertyUrl.uri == name: + return c + return col + + +def dialect_props(d): + if not isinstance(d, dict): + warnings.warn('Invalid dialect spec') + return {} + partitioned = Description.partition_properties(d, type_name='Dialect', strict=False) + del partitioned['at_props'] + del partitioned['common_props'] + if partitioned.get('headerRowCount'): + partitioned['header'] = True + return partitioned + + +def valid_transformations(instance, attribute, value): + if not isinstance(value, list): + warnings.warn('Invalid transformations property') + for tr in value: + Description.partition_properties(tr, type_name='Template') + + +@attr.s +class TableLike(Description): + """ + A CSVW description object as encountered "in the wild", i.e. identified by URL on the web or + as file on disk. + + Since `TableLike` objects may be instantiated from "externally referenced" objects + (via file paths or URLs), they have the necessary means to resolve + `link properties `_ + + .. code-block:: python + + >>> from csvw import Table, TableGroup, Link + >>> t = Table.from_file('tests/fixtures/csv.txt-table-metadata.json') + >>> Link('abc.txt').resolve(t.base) + PosixPath('tests/fixtures/abc.txt') + >>> tg = TableGroup.from_url( + ... 'https://raw.githubusercontent.com/cldf/csvw/master/tests/fixtures/' + ... 'csv.txt-metadata.json') + >>> str(tg.tables[0].url) + 'csv.txt' + >>> tg.tables[0].url.resolve(tg.base) + 'https://raw.githubusercontent.com/cldf/csvw/master/tests/fixtures/csv.txt' + + and `URI template properties `_ + (see :meth:`~TableLike.expand`). + """ + dialect = attr.ib( + default=None, + converter=lambda v: v if (v is None or isinstance(v, str)) + else Dialect(**dialect_props(v))) + notes = attr.ib(default=attr.Factory(list)) + tableDirection = attr.ib( + default='auto', + converter=functools.partial( + utils.converter, str, 'auto', cond=lambda s: s in ['rtl', 'ltr', 'auto']), + validator=attr.validators.in_(['rtl', 'ltr', 'auto'])) + tableSchema = attr.ib( + default=None, + converter=lambda v: Schema.fromvalue(v)) + transformations = attr.ib( + validator=valid_transformations, + default=attr.Factory(list), + ) + url = link_property() + _fname = attr.ib(default=None) # The path of the metadata file. + + def __attrs_post_init__(self): + if isinstance(self.dialect, str): + self.dialect = Dialect(**dialect_props(get_json(Link(self.dialect).resolve(self.base)))) + if self.tableSchema and not (isinstance(self.tableSchema, str)): + self.tableSchema._parent = self + if 'id' in self.at_props and self.at_props['id'] is None: + self.at_props['id'] = self.base + ctx = self.at_props.get('context') + if isinstance(ctx, list): + for obj in ctx: + if (isinstance(obj, dict) and not set(obj.keys()).issubset({'@base', '@language'}))\ + or (isinstance(obj, str) and obj != 'http://www.w3.org/ns/csvw'): + raise ValueError( + 'The @context MUST have one of the following values: An array composed ' + 'of a string followed by an object, where the string is ' + 'http://www.w3.org/ns/csvw and the object represents a local context ' + 'definition, which is restricted to contain either or both of' + '@base and @language.') + if isinstance(obj, dict) and '@language' in obj: + if not tags.check(obj['@language']): + warnings.warn('Invalid value for @language property') + del obj['@language'] + + def get_column(self, spec): + return self.tableSchema.get_column(spec) if self.tableSchema else None + + @classmethod + def from_file(cls, fname: typing.Union[str, pathlib.Path], data=None) -> 'TableLike': + """ + Instantiate a CSVW Table or TableGroup description from a metadata file. + """ + if is_url(str(fname)): + return cls.from_url(str(fname), data=data) + res = cls.fromvalue(data or get_json(fname)) + res._fname = pathlib.Path(fname) + return res + + @classmethod + def from_url(cls, url: str, data=None) -> 'TableLike': + """ + Instantiate a CSVW Table or TableGroup description from a metadata file specified by URL. + """ + data = data or get_json(url) + url = urlparse(url) + data.setdefault('@base', urlunparse((url.scheme, url.netloc, url.path, '', '', ''))) + for table in data.get('tables', [data]): + if isinstance(table, dict) and isinstance(table.get('tableSchema'), str): + table['tableSchema'] = Link(table['tableSchema']).resolve(data['@base']) + res = cls.fromvalue(data) + return res + + def to_file(self, fname: typing.Union[str, pathlib.Path], omit_defaults=True) -> pathlib.Path: + """ + Write a CSVW Table or TableGroup description as JSON object to a local file. + + :param omit_defaults: The CSVW spec specifies defaults for most properties of most \ + description objects. If `omit_defaults==True`, these properties will be pruned from \ + the JSON object. + """ + fname = utils.ensure_path(fname) + data = self.asdict(omit_defaults=omit_defaults) + with json_open(str(fname), 'w') as f: + json.dump(data, f, indent=4, separators=(',', ': ')) + return fname + + @property + def base(self) -> typing.Union[str, pathlib.Path]: + """ + The "base" to resolve relative links against. + """ + at_props = self._parent.at_props if self._parent else self.at_props + ctxbase = None + for obj in self.at_props.get('context', []): + if isinstance(obj, dict) and '@base' in obj: + ctxbase = obj['@base'] + if 'base' in at_props: + if ctxbase: + # If present, its value MUST be a string that is interpreted as a URL which is + # resolved against the location of the metadata document to provide the + # **base URL** for other URLs in the metadata document. + return Link(ctxbase).resolve(at_props['base']) + return at_props['base'] + return self._parent._fname.parent if (self._parent and self._parent._fname) else \ + (self._fname.parent if self._fname else None) + + def expand(self, tmpl: URITemplate, row: dict, _row, _name=None, qname=False) -> str: + """ + Expand a `URITemplate` using `row`, `_row` and `_name` as context and resolving the result + against `TableLike.url`. + + .. code-block:: python + + >>> from csvw import URITemplate, TableGroup + >>> tg = TableGroup.from_url( + ... 'https://raw.githubusercontent.com/cldf/csvw/master/tests/fixtures/' + ... 'csv.txt-metadata.json') + >>> tg.expand(URITemplate('/path?{a}{#b}'), dict(a='1', b='2'), None) + 'https://raw.githubusercontent.com/path?1#2' + + """ + if tmpl is INVALID: + return self.url.resolve(self.base) + + for prefix, url in NAMESPACES.items(): + if tmpl.uri.startswith(prefix + ':'): + # If the URI Template is a QName, we expand it to a URL to prevent `Link.resolve` + # from turning it into a local path. + res = '{}{}'.format(url, tmpl.uri.split(':')[1]) + break + else: + res = Link( + tmpl.expand( + _row=_row, + _name=_name, + **{_k: _v for _k, _v in row.items() if isinstance(_k, str)} + )).resolve(self.url.resolve(self.base) if self.url else self.base) + if not isinstance(res, pathlib.Path): + if qname: + for prefix, url in NAMESPACES.items(): + if res.startswith(url): + res = res.replace(url, prefix + ':') + break + return res + + +@attr.s +class Table(TableLike): + """ + A table description is an object that describes a table within a CSV file. + + `Table` objects provide access to schema manipulation either by manipulating the `tableSchema` + property directly or via higher-level methods like :meth:`~Table.add_foreign_key` + + `Table` objects also mediate read/write access to the actual data through + + - :meth:`~Table.write` + - :meth:`~Table.iterdicts` + + .. seealso:: ``_ + """ + suppressOutput = attr.ib(default=False) + _comments = [] + + def add_foreign_key(self, colref, ref_resource, ref_colref): + """ + Add a foreign key constraint to `tableSchema.foreignKeys`. + + :param colref: Column reference for the foreign key. + :param ref_resource: Referenced table. + :param ref_colref: Column reference of the key in the referenced table. + """ + colref = [colref] if not isinstance(colref, (tuple, list)) else colref + if not all(col in [c.name for c in self.tableSchema.columns] for col in colref): + raise ValueError('unknown column in foreignKey {0}'.format(colref)) + + self.tableSchema.foreignKeys.append(ForeignKey.fromdict({ + 'columnReference': colref, + 'reference': {'resource': ref_resource, 'columnReference': ref_colref} + })) + + def __attrs_post_init__(self): + TableLike.__attrs_post_init__(self) + if not self.url: + raise ValueError('url property is required for Tables') + + @property + def local_name(self) -> typing.Union[str, None]: + return self.url.string if self.url else None + + def _get_dialect(self) -> Dialect: + return self.dialect or (self._parent and self._parent.dialect) or Dialect() + + def write(self, + items: typing.Iterable[typing.Union[dict, list, tuple]], + fname: typing.Optional[typing.Union[str, pathlib.Path]] = DEFAULT, + base: typing.Optional[typing.Union[str, pathlib.Path]] = None, + strict: typing.Optional[bool] = False, + _zipped: typing.Optional[bool] = False) -> typing.Union[str, int]: + """ + Write row items to a CSV file according to the table schema. + + :param items: Iterator of `dict` storing the data per row. + :param fname: Name of the file to which to write the data. + :param base: Base directory relative to which to interpret table urls. + :param strict: Flag signaling to use strict mode when writing. This will raise `ValueError`\ + if any row (dict) passed in `items` contains unspecified fieldnames. + :param _zipped: Flag signaling whether the resulting data file should be zipped. + :return: The CSV content if `fname==None` else the number of rows written. + """ + dialect = self._get_dialect() + non_virtual_cols = [c for c in self.tableSchema.columns if not c.virtual] + if fname is DEFAULT: + fname = self.url.resolve(pathlib.Path(base) if base else self.base) + + rowcount = 0 + with UnicodeWriter(fname, dialect=dialect) as writer: + if dialect.header: + writer.writerow([c.header for c in non_virtual_cols]) + for item in items: + if isinstance(item, (list, tuple)): + row = [col.write(item[i]) for i, col in enumerate(non_virtual_cols)] + else: + if strict: + add = set(item.keys()) - {'{}'.format(col) for col in non_virtual_cols} + if add: + raise ValueError("dict contains fields not in fieldnames: {}".format( + ', '.join("'{}'".format(field) for field in add))) + row = [ + col.write(item.get( + col.header, item.get('{}'.format(col)))) + for col in non_virtual_cols] + rowcount += 1 + writer.writerow(row) + if fname is None: + return writer.read() + if fname and _zipped: + fpath = pathlib.Path(fname) + with zipfile.ZipFile( + str(fpath.parent.joinpath(fpath.name + '.zip')), + 'w', + compression=zipfile.ZIP_DEFLATED + ) as zipf: + zipf.write(str(fpath), arcname=fpath.name) + fpath.unlink() + return rowcount + + def check_primary_key(self, log=None, items=None) -> bool: + success = True + if items is not None: + warnings.warn('the items argument of check_primary_key ' + 'is deprecated (its content will be ignored)') # pragma: no cover + if self.tableSchema.primaryKey: + get_pk = operator.itemgetter(*self.tableSchema.primaryKey) + seen = set() + # Read all rows in the table, ignoring errors: + for fname, lineno, row in self.iterdicts(log=nolog(), with_metadata=True): + pk = get_pk(row) + if pk in seen: + log_or_raise( + '{0}:{1} duplicate primary key: {2}'.format(fname, lineno, pk), + log=log) + success = False + else: + seen.add(pk) + return success + + def __iter__(self): + return self.iterdicts() + + def iterdicts( + self, + log=None, + with_metadata=False, + fname=None, + _Row=collections.OrderedDict, + strict=True, + ) -> typing.Generator[dict, None, None]: + """Iterate over the rows of the table + + Create an iterator that maps the information in each row to a `dict` whose keys are + the column names of the table and whose values are the values in the corresponding + table cells, or for virtual columns (which have no values) the valueUrl for that + column. This includes columns not specified in the table specification. + + Note: If the resolved data filename does not exist - but there is a zip file of the form + `fname+'.zip'`, we try to read the data from this file after unzipping. + + :param log: Logger object (default None) The object that reports parsing errors.\ + If none is given, parsing errors raise ValueError instead. + :param bool with_metadata: (default False) Also yield fname and lineno + :param fname: file-like, pathlib.Path, or str (default None)\ + The file to be read. Defaults to inheriting from a parent object, if one exists. + :param strict: Flag signaling whether data is read strictly - i.e. raising `ValueError` \ + when invalid data is encountered - or not - i.e. only issueing a warning and returning \ + invalid data as `str` as provided by the undelying DSV reader. + :return: A generator of dicts or triples (fname, lineno, dict) if with_metadata + """ + dialect = self._get_dialect() + fname = fname or self.url.resolve(self.base) + colnames, virtualcols, requiredcols = [], [], set() + for col in self.tableSchema.columns: + if col.virtual: + if col.valueUrl: + virtualcols.append((col.header, col.valueUrl)) + else: + colnames.append(col.header) + if col.required: + requiredcols.add(col.header) + + with contextlib.ExitStack() as stack: + if is_url(fname): + handle = io.TextIOWrapper( + io.BytesIO(requests.get(str(fname)).content), encoding=dialect.encoding) + else: + handle = fname + fpath = pathlib.Path(fname) + if not fpath.exists(): + zipfname = fpath.parent.joinpath(fpath.name + '.zip') + if zipfname.exists(): + zipf = stack.enter_context(zipfile.ZipFile(str(zipfname))) + handle = io.TextIOWrapper( + zipf.open([n for n in zipf.namelist() if n.endswith(fpath.name)][0]), + encoding=dialect.encoding) + + reader = stack.enter_context(UnicodeReaderWithLineNumber(handle, dialect=dialect)) + reader = iter(reader) + + # If the data file has a header row, this row overrides the header as + # specified in the metadata. + if dialect.header: + try: + _, header = next(reader) + if not strict: + if self.tableSchema.columns and len(self.tableSchema.columns) < len(header): + warnings.warn('Column number mismatch') + for name, col in zip(header, self.tableSchema.columns): + res = col.has_title(name) + if (not col.name) and not res: + warnings.warn('Incompatible table models') + if isinstance(res, str) and res.split('-')[0] not in [ + 'und', (self.lang or 'und').split('-')[0]]: + warnings.warn('Incompatible column titles') + except StopIteration: # pragma: no cover + return + else: + header = colnames + + # If columns in the data are ordered as in the spec, we can match values to + # columns by index, rather than looking up columns by name. + if (header == colnames) or \ + (len(self.tableSchema.columns) >= len(header) and not strict): + # Note that virtual columns are only allowed to come **after** regular ones, + # so we can simply zip the whole columns list, and silently ignore surplus + # virtual columns. + header_cols = list(zip(header, self.tableSchema.columns)) + elif not strict and self.tableSchema.columns and \ + (len(self.tableSchema.columns) < len(header)): + header_cols = [] + for i, cname in enumerate(header): + try: + header_cols.append((cname, self.tableSchema.columns[i])) + except IndexError: + header_cols.append(( + '_col.{}'.format(i + 1), + Column.fromvalue({'name': '_col.{}'.format(i + 1)}))) + else: + header_cols = [(h, self.tableSchema.get_column(h)) for h in header] + header_cols = [(j, h, c) for j, (h, c) in enumerate(header_cols)] + missing = requiredcols - set(c.header for j, h, c in header_cols if c) + if missing: + raise ValueError('{0} is missing required columns {1}'.format(fname, missing)) + + for lineno, row in reader: + required = {h: j for j, h, c in header_cols if c and c.required} + res = _Row() + error = False + if (not header_cols) and row: + header_cols = [ + (i, + '_col.{}'.format(i + 1), + Column.fromvalue({'name': '_col.{}'.format(i + 1)})) + for i, _ in enumerate(row)] + for (j, k, col), v in zip(header_cols, row): + # see http://w3c.github.io/csvw/syntax/#parsing-cells + if col: + try: + res[col.header] = col.read(v, strict=strict) + except ValueError as e: + if not strict: + warnings.warn( + 'Invalid column value: {} {}; {}'.format(v, col.datatype, e)) + res[col.header] = v + else: + log_or_raise( + '{0}:{1}:{2} {3}: {4}'.format(fname, lineno, j + 1, k, e), + log=log) + error = True + if k in required: + del required[k] + else: + if strict: + warnings.warn( + 'Unspecified column "{0}" in table {1}'.format(k, self.local_name)) + res[k] = v + + for k, j in required.items(): + if k not in res: + log_or_raise( + '{0}:{1}:{2} {3}: {4}'.format( + fname, lineno, j + 1, k, 'required column value is missing'), + log=log) + error = True + + # Augment result with regular columns not provided in the data: + for key in colnames: + res.setdefault(key, None) + + # Augment result with virtual columns: + for key, valueUrl in virtualcols: + res[key] = valueUrl.expand(**res) + + if not error: + if with_metadata: + yield fname, lineno, res + else: + yield res + self._comments = reader.comments + + +def converter_tables(v): + res = [] + for vv in v: + if not isinstance(vv, (dict, Table)): + warnings.warn('Invalid value for Table spec') + else: + res.append(Table.fromvalue(vv) if isinstance(vv, dict) else vv) + return res + + +@attr.s +class TableGroup(TableLike): + """ + A table group description is an object that describes a group of tables. + + A `TableGroup` delegates most of its responsibilities to the `Table` objects listed in its + `tables` property. For convenience, `TableGroup` provides methods to + - read data from all tables: :meth:`TableGroup.read` + - write data for all tables: :meth:`TableGroup.write` + + It also provides a method to check the referential integrity of data in related tables via + :meth:`TableGroup.check_referential_integrity` + + .. seealso:: ``_ + """ + tables = attr.ib(repr=False, default=attr.Factory(list), converter=converter_tables) + + def __attrs_post_init__(self): + TableLike.__attrs_post_init__(self) + for table in self.tables: + table._parent = self + + @classmethod + def from_frictionless_datapackage(cls, dp): + return DataPackage(dp).to_tablegroup(cls) + + def read(self): + """ + Read all data of a TableGroup + """ + return {tname: list(t.iterdicts()) for tname, t in self.tabledict.items()} + + def write(self, + fname: typing.Union[str, pathlib.Path], + strict: typing.Optional[bool] = False, + _zipped: typing.Optional[bool] = False, + **items: typing.Iterable[typing.Union[list, tuple, dict]]): + """ + Write a TableGroup's data and metadata to files. + + :param fname: Filename for the metadata file. + :param items: Keyword arguments are used to pass iterables of rows per table, where the \ + table URL is specified as keyword. + """ + fname = pathlib.Path(fname) + for tname, rows in items.items(): + self.tabledict[tname].write(rows, base=fname.parent, strict=strict, _zipped=_zipped) + self.to_file(fname) + + def copy(self, dest: typing.Union[pathlib.Path, str]): + """ + Write a TableGroup's data and metadata to files relative to `dest`, adapting the `base` + attribute. + + :param dest: + :return: + """ + dest = pathlib.Path(dest) + for table in self.tables: + shutil.copy(str(table.url.resolve(self.base)), str(table.url.resolve(dest))) + self._fname = dest / self._fname.name + self.to_file(self._fname) + + @property + def tabledict(self) -> typing.Dict[str, Table]: + return {t.local_name: t for t in self.tables} + + def foreign_keys(self) -> typing.List[typing.Tuple[Table, list, Table, list]]: + return [ + ( + self.tabledict[fk.reference.resource.string], + fk.reference.columnReference, + t, + fk.columnReference) + for t in self.tables for fk in t.tableSchema.foreignKeys + if not fk.reference.schemaReference] + + def validate_schema(self, strict=False): + try: + for st, sc, tt, tc in self.foreign_keys(): + if len(sc) != len(tc): + raise ValueError( + 'Foreign key error: non-matching number of columns in source and target') + for scol, tcol in zip(sc, tc): + scolumn = st.tableSchema.get_column(scol, strict=strict) + tcolumn = tt.tableSchema.get_column(tcol, strict=strict) + if not (scolumn and tcolumn): + raise ValueError( + 'Foregin key error: missing column "{}" or "{}"'.format(scol, tcol)) + if scolumn.datatype and tcolumn.datatype and \ + scolumn.datatype.base != tcolumn.datatype.base: + raise ValueError( + 'Foregin key error: non-matching datatype "{}:{}" or "{}:{}"'.format( + scol, scolumn.datatype.base, tcol, tcolumn.datatype.base)) + except (KeyError, AssertionError) as e: + raise ValueError('Foreign key error: missing table "{}" referenced'.format(e)) + + def check_referential_integrity(self, data=None, log=None, strict=False): + """ + Strict validation does not allow for nullable foreign key columns. + """ + if data is not None: + warnings.warn('the data argument of check_referential_integrity ' + 'is deprecated (its content will be ignored)') # pragma: no cover + if strict: + for t in self.tables: + for fk in t.tableSchema.foreignKeys: + for row in t: + if any(row.get(col) is None for col in fk.columnReference): + raise ValueError('Foreign key column is null: {} {}'.format( + [row.get(col) for col in fk.columnReference], fk.columnReference)) + try: + self.validate_schema() + success = True + except ValueError as e: + success = False + log_or_raise(str(e), log=log, level='error') + fkeys = self.foreign_keys() + # FIXME: We only support Foreign Key references between tables! + fkeys = sorted(fkeys, key=lambda x: (x[0].local_name, x[1], x[2].local_name)) + # Grouping by local_name of tables - even though we'd like to have the table objects + # around, too. This it to prevent going down the rabbit hole of comparing table objects + # for equality, when comparison of the string names is enough. + for _, grp in itertools.groupby(fkeys, lambda x: x[0].local_name): + grp = list(grp) + table = grp[0][0] + t_fkeys = [(key, [(child, ref) for _, _, child, ref in kgrp]) + for key, kgrp in itertools.groupby(grp, lambda x: x[1])] + get_seen = [(operator.itemgetter(*key), set()) for key, _ in t_fkeys] + for row in table.iterdicts(log=log): + for get, seen in get_seen: + if get(row) in seen: + # column references for a foreign key are not unique! + if strict: + success = False + seen.add(get(row)) + for (key, children), (_, seen) in zip(t_fkeys, get_seen): + single_column = (len(key) == 1) + for child, ref in children: + get_ref = operator.itemgetter(*ref) + for fname, lineno, item in child.iterdicts(log=log, with_metadata=True): + colref = get_ref(item) + if colref is None: + continue + elif single_column and isinstance(colref, list): + # We allow list-valued columns as foreign key columns in case + # it's not a composite key. If a foreign key is list-valued, we + # check for a matching row for each of the values in the list. + colrefs = colref + else: + colrefs = [colref] + for colref in colrefs: + if not single_column and None in colref: # pragma: no cover + # TODO: raise if any(c is not None for c in colref)? + continue + elif colref not in seen: + log_or_raise( + '{0}:{1} Key `{2}` not found in table {3}'.format( + fname, + lineno, + colref, + table.url.string), + log=log) + success = False + return success + + +class CSVW: + """ + Python API to read CSVW described data and convert it to JSON. + """ + def __init__(self, url: str, md_url: typing.Optional[str] = None, validate: bool = False): + self.warnings = [] + w = None + with contextlib.ExitStack() as stack: + if validate: + w = stack.enter_context(warnings.catch_warnings(record=True)) + + no_header = False + try: + md = get_json(md_url or url) + # The URL could be read as JSON document, thus, the user supplied us with overriding + # metadata as per https://w3c.github.io/csvw/syntax/#overriding-metadata + except json.decoder.JSONDecodeError: + # So we got a CSV file, no JSON. Let's locate metadata using the other methods. + md, no_header = self.locate_metadata(url) + + self.no_metadata = set(md.keys()) == {'@context', 'url'} + if "http://www.w3.org/ns/csvw" not in md.get('@context', ''): + raise ValueError('Invalid or no @context') + if 'tables' in md: + if not md['tables'] or not isinstance(md['tables'], list): + raise ValueError('Invalid TableGroup with empty tables property') + if is_url(url): + self.t = TableGroup.from_url(url, data=md) + self.t.validate_schema(strict=True) + else: + self.t = TableGroup.from_file(url, data=md) + else: + if is_url(url): + self.t = Table.from_url(url, data=md) + if no_header: + if self.t.dialect: + self.t.dialect.header = False # pragma: no cover + else: + self.t.dialect = Dialect(header=False) + else: + self.t = Table.from_file(url, data=md) + self.tables = self.t.tables if isinstance(self.t, TableGroup) else [self.t] + for table in self.tables: + for col in table.tableSchema.columns: + if col.name and (re.search(r'\s', col.name) or col.name.startswith('_')): + col.name = None + self.common_props = self.t.common_props + if w: + self.warnings.extend(w) + + @property + def is_valid(self) -> bool: + """ + Performs CSVW validation. + + .. note:: + + For this to also catch problems during metadata location, the + `CSVW` instance must be initialized with `validate=True`. + """ + if self.warnings: + return False + with warnings.catch_warnings(record=True) as w: + for table in self.tables: + for _ in table.iterdicts(strict=False): + pass + if not table.check_primary_key(): # pragma: no cover + warnings.warn('Duplicate primary key') + if not self.tablegroup.check_referential_integrity(strict=True): + warnings.warn('Referential integrity check failed') + if w: + self.warnings.extend(w) + return not bool(self.warnings) + + @property + def tablegroup(self): + return self.t if isinstance(self.t, TableGroup) else \ + TableGroup(at_props={'base': self.t.base}, tables=self.tables) + + @staticmethod + def locate_metadata(url=None) -> typing.Tuple[dict, bool]: + """ + Implements metadata discovery as specified in + `§5. Locating Metadata `_ + """ + def describes(md, url): + for table in md.get('tables', [md]): + # FIXME: We check whether the metadata describes a CSV file just superficially, + # by comparing the last path components of the respective URLs. + if url.split('/')[-1] == table['url'].split('/')[-1]: + return True + return False + + no_header = False + if url and is_url(url): + # §5.2 Link Header + # https://w3c.github.io/csvw/syntax/#link-header + res = requests.head(url) + no_header = bool(re.search(r'header\s*=\s*absent', res.headers.get('content-type', ''))) + desc = res.links.get('describedby') + if desc and desc['type'] in [ + "application/csvm+json", "application/ld+json", "application/json"]: + md = get_json(Link(desc['url']).resolve(url)) + if describes(md, url): + return md, no_header + else: + warnings.warn('Ignoring linked metadata because it does not reference the data') + + # §5.3 Default Locations and Site-wide Location Configuration + # https://w3c.github.io/csvw/syntax/ + # #default-locations-and-site-wide-location-configuration + res = requests.get(Link('/.well-known/csvm').resolve(url)) + locs = res.text if res.status_code == 200 else '{+url}-metadata.json\ncsv-metadata.json' + for line in locs.split('\n'): + res = requests.get(Link(URITemplate(line).expand(url=url)).resolve(url)) + if res.status_code == 200: + try: + md = res.json() + if describes(md, url): + return md, no_header + warnings.warn('Ignoring metadata because it does not reference the data') + except json.JSONDecodeError: + pass + + # §5.4 Embedded Metadata + # https://w3c.github.io/csvw/syntax/#embedded-metadata + # We only recognize column names read from the first row of a CSV file. + elif url: + # Default Locations for local files: + if pathlib.Path(str(url) + '-metadata.json').exists(): + return get_json(pathlib.Path(str(url) + '-metadata.json')), no_header + res = { + '@context': "http://www.w3.org/ns/csvw", + 'url': url, + } + if not is_url(url or ''): + # No metadata detected for a local CSV file. To make table reading work, we set the + # directory as @base and the filename as url property of the description. + p = pathlib.Path(url) + res['@base'] = str(p) + res['url'] = p.name + return res, no_header + + def to_json(self, minimal=False): + """ + Implements algorithm described in ``_ + """ + res = collections.OrderedDict() + # Insert any notes and non-core annotations specified for the group of tables into object + # G according to the rules provided in § 5. JSON-LD to JSON. + if self.t.common_props and not isinstance(self.t, Table): + res.update(jsonld.to_json(self.t.common_props, flatten_list=True)) + res['tables'] = [ + self._table_to_json(table) for table in self.tables if not table.suppressOutput] + if minimal: + return list( + itertools.chain(*[[r['describes'][0] for r in t['row']] for t in res['tables']])) + + return res + + def _table_to_json(self, table): + res = collections.OrderedDict() + # FIXME: id + res['url'] = str(table.url.resolve(table.base)) + if 'id' in table.at_props: + res['@id'] = table.at_props['id'] + if table.notes: + res['notes'] = jsonld.to_json(table.notes) + # Insert any notes and non-core annotations specified for the group of tables into object + # G according to the rules provided in § 5. JSON-LD to JSON. + res.update(jsonld.to_json(table.common_props)) + + cols = collections.OrderedDict([(col.header, col) for col in table.tableSchema.columns]) + for col in cols.values(): + col.propertyUrl = col.inherit('propertyUrl') + col.valueUrl = col.inherit('valueUrl') + + row = [ + self._row_to_json(table, cols, row, rownum, rowsourcenum) + for rownum, (_, rowsourcenum, row) in enumerate( + table.iterdicts(with_metadata=True, strict=False), start=1) + ] + if table._comments: + res['rdfs:comment'] = [c[1] for c in table._comments] + res['row'] = row + return res + + def _row_to_json(self, table, cols, row, rownum, rowsourcenum): + res = collections.OrderedDict() + res['url'] = '{}#row={}'.format(table.url.resolve(table.base), rowsourcenum) + res['rownum'] = rownum + if table.tableSchema.rowTitles: + res['titles'] = [ + t for t in [row.get(name) for name in table.tableSchema.rowTitles] if t] + if len(res['titles']) == 1: + res['titles'] = res['titles'][0] + # Insert any notes and non-core annotations specified for the group of tables into object + # G according to the rules provided in § 5. JSON-LD to JSON. + + res['describes'] = self._describes(table, cols, row, rownum) + return res + + def _describes(self, table, cols, row, rownum): + triples = [] + + aboutUrl = table.tableSchema.inherit('aboutUrl') + if aboutUrl: + triples.append(jsonld.Triple( + about=None, property='@id', value=table.expand(aboutUrl, row, _row=rownum))) + + for i, (k, v) in enumerate(row.items(), start=1): + col = cols.get(k) + if col and (col.suppressOutput or col.virtual): + continue + + # Skip null values: + null = col.inherit_null() if col else table.inherit_null() + if (null and v in null) or v == "" or (v is None) or \ + (col and col.separator and v == []): + continue + + triples.append(jsonld.Triple.from_col( + table, + col, + row, + '_col.{}'.format(i) + if (not table.tableSchema.columns and not self.no_metadata) else k, + v, + rownum)) + + for col in table.tableSchema.columns: + if col.virtual: + triples.append(jsonld.Triple.from_col(table, col, row, col.header, None, rownum)) + return jsonld.group_triples(triples) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/csvw/utils.py b/TTS/Kokoro/.venv/Lib/site-packages/csvw/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..affbfdfd294137ab6e5fdc075ff04c84f180a658 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/csvw/utils.py @@ -0,0 +1,230 @@ +import re +import copy +import html +import json +import string +import keyword +import pathlib +import warnings +import collections +import unicodedata + +import attr + + +def is_url(s): + return re.match(r'https?://', str(s)) + + +def converter(type_, default, s, allow_none=False, cond=None, allow_list=True): + if allow_list and type_ != list and isinstance(s, list): + return [v for v in [converter(type_, None, ss, cond=cond) for ss in s] if v is not None] + + if allow_none and s is None: + return s + if not isinstance(s, type_) or (type_ == int and isinstance(s, bool)) or (cond and not cond(s)): + warnings.warn('Invalid value for property: {}'.format(s)) + return default + return s + + +def ensure_path(fname): + if not isinstance(fname, pathlib.Path): + assert isinstance(fname, str) + return pathlib.Path(fname) + return fname + + +def attr_defaults(cls): + res = collections.OrderedDict() + for field in attr.fields(cls): + default = field.default + if isinstance(default, attr.Factory): + default = default.factory() + res[field.name] = default + return res + + +def attr_asdict(obj, omit_defaults=True, omit_private=True): + defs = attr_defaults(obj.__class__) + res = collections.OrderedDict() + for field in attr.fields(obj.__class__): + if not (omit_private and field.name.startswith('_')): + value = getattr(obj, field.name) + if not (omit_defaults and value == defs[field.name]): + if hasattr(value, 'asdict'): + value = value.asdict(omit_defaults=True) + res[field.name] = value + return res + + +def normalize_name(s): + """Convert a string into a valid python attribute name. + This function is called to convert ASCII strings to something that can pass as + python attribute name, to be used with namedtuples. + + >>> str(normalize_name('class')) + 'class_' + >>> str(normalize_name('a-name')) + 'a_name' + >>> str(normalize_name('a n\u00e4me')) + 'a_name' + >>> str(normalize_name('Name')) + 'Name' + >>> str(normalize_name('')) + '_' + >>> str(normalize_name('1')) + '_1' + """ + s = s.replace('-', '_').replace('.', '_').replace(' ', '_') + if s in keyword.kwlist: + return s + '_' + s = '_'.join(slug(ss, lowercase=False) for ss in s.split('_')) + if not s: + s = '_' + if s[0] not in string.ascii_letters + '_': + s = '_' + s + return s + + +def slug(s, remove_whitespace=True, lowercase=True): + """Condensed version of s, containing only lowercase alphanumeric characters. + + >>> str(slug('A B. \u00e4C')) + 'abac' + """ + res = ''.join(c for c in unicodedata.normalize('NFD', s) + if unicodedata.category(c) != 'Mn') + if lowercase: + res = res.lower() + for c in string.punctuation: + res = res.replace(c, '') + res = re.sub(r'\s+', '' if remove_whitespace else ' ', res) + res = res.encode('ascii', 'ignore').decode('ascii') + assert re.match('[ A-Za-z0-9]*$', res) + return res + + +def qname2url(qname): + for prefix, uri in { + 'csvw': 'http://www.w3.org/ns/csvw#', + 'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#', + 'rdfs': 'http://www.w3.org/2000/01/rdf-schema#', + 'xsd': 'http://www.w3.org/2001/XMLSchema#', + 'dc': 'http://purl.org/dc/terms/', + 'dcat': 'http://www.w3.org/ns/dcat#', + 'prov': 'http://www.w3.org/ns/prov#', + }.items(): + if qname.startswith(prefix + ':'): + return qname.replace(prefix + ':', uri) + + +def metadata2markdown(tg, link_files=False) -> str: + """ + Render the metadata of a dataset as markdown. + + :param link_files: If True, links to data files will be added, assuming the markdown is stored \ + in the same directory as the metadata file. + :return: `str` with markdown formatted text + """ + def qname2link(qname, html=False): + url = qname2url(qname) + if url: + if html: + return '{}'.format(url, qname) + return '[{}]({})'.format(qname, url) + return qname + + def htmlify(obj, key=None): + """ + For inclusion in tables we must use HTML for lists. + """ + if isinstance(obj, list): + return '
    {}
'.format( + ''.join('
  • {}
  • '.format(htmlify(item, key=key)) for item in obj)) + if isinstance(obj, dict): + items = [] + for k, v in obj.items(): + items.append('
    {}
    {}
    '.format( + qname2link(k, html=True), html.escape(str(v)))) + return '
    {}
    '.format(''.join(items)) + return str(obj) + + def properties(props): + props = {k: v for k, v in copy.deepcopy(props).items() if v} + res = [] + desc = props.pop('dc:description', None) + if desc: + res.append(desc + '\n') + img = props.pop('https://schema.org/image', None) + if img: + if isinstance(img, str): # pragma: no cover + img = {'contentUrl': img} + res.append('![{}]({})\n'.format( + img.get('https://schema.org/caption') or '', + img.get('https://schema.org/contentUrl'))) + if props: + res.append('property | value\n --- | ---') + for k, v in props.items(): + res.append('{} | {}'.format(qname2link(k), htmlify(v, key=k))) + return '\n'.join(res) + '\n' + + def colrow(col, fks, pk): + dt = '`{}`'.format(col.datatype.base if col.datatype else 'string') + if col.datatype: + if col.datatype.format: + if re.fullmatch(r'[\w\s]+(\|[\w\s]+)*', col.datatype.format): + dt += '
    Valid choices:
    ' + dt += ''.join(' `{}`'.format(w) for w in col.datatype.format.split('|')) + elif col.datatype.base == 'string': + dt += '
    Regex: `{}`'.format(col.datatype.format) + if col.datatype.minimum: + dt += '
    ≥ {}'.format(col.datatype.minimum) + if col.datatype.maximum: + dt += '
    ≤ {}'.format(col.datatype.maximum) + if col.separator: + dt = 'list of {} (separated by `{}`)'.format(dt, col.separator) + desc = col.common_props.get('dc:description', '').replace('\n', ' ') + + if pk and col.name in pk: + desc = (desc + '
    ') if desc else desc + desc += 'Primary key' + + if col.name in fks: + desc = (desc + '
    ') if desc else desc + desc += 'References [{}::{}](#table-{})'.format( + fks[col.name][1], fks[col.name][0], slug(fks[col.name][1])) + + return ' | '.join([ + '[{}]({})'.format(col.name, col.propertyUrl) + if col.propertyUrl else '`{}`'.format(col.name), + dt, + desc, + ]) + + res = ['# {}\n'.format(tg.common_props.get('dc:title', 'Dataset'))] + if tg._fname and link_files: + res.append('> [!NOTE]\n> Described by [{0}]({0}).\n'.format(tg._fname.name)) + + res.append(properties({k: v for k, v in tg.common_props.items() if k != 'dc:title'})) + + for table in tg.tables: + fks = { + fk.columnReference[0]: (fk.reference.columnReference[0], fk.reference.resource.string) + for fk in table.tableSchema.foreignKeys if len(fk.columnReference) == 1} + header = '## Table '.format(slug(table.url.string)) + if link_files and tg._fname and tg._fname.parent.joinpath(table.url.string).exists(): + header += '[{0}]({0})\n'.format(table.url.string) + else: # pragma: no cover + header += table.url.string + res.append('\n' + header + '\n') + res.append(properties(table.common_props)) + dialect = table.inherit('dialect') + if dialect.asdict(): + res.append('\n**CSV dialect**: `{}`\n'.format(json.dumps(dialect.asdict()))) + res.append('\n### Columns\n') + res.append('Name/Property | Datatype | Description') + res.append(' --- | --- | --- ') + for col in table.tableSchema.columns: + res.append(colrow(col, fks, table.tableSchema.primaryKey)) + return '\n'.join(res) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers-0.0.9.dist-info/INSTALLER b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers-0.0.9.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers-0.0.9.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers-0.0.9.dist-info/LICENSE b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers-0.0.9.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..bd6ce863f14844f9f288ab4c60e9277afce69cdc --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers-0.0.9.dist-info/LICENSE @@ -0,0 +1,52 @@ +The MIT License (MIT) + +Copyright (C) 2022 ExplosionAI GmbH + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +--- + +The BPE byte mapping and split pattern in ByteBPEProcessor were taken directly +from GPT-2 to ensure identical splittings. The following nice notice applies +to this code: + +Software Copyright (c) 2019 OpenAI + +We don’t claim ownership of the content you create with GPT-2, so it is yours to +do with as you please. We only ask that you use GPT-2 responsibly and clearly +indicate your content was created using GPT-2. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. The above copyright notice and +this permission notice need not be included with content created by the +Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers-0.0.9.dist-info/METADATA b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers-0.0.9.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..f0644210a301fd19d67a5bedb6fedfe2124861eb --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers-0.0.9.dist-info/METADATA @@ -0,0 +1,57 @@ +Metadata-Version: 2.1 +Name: curated-tokenizers +Version: 0.0.9 +Summary: Lightweight piece tokenization library +Home-page: https://github.com/explosion/curated-tokenizers +Author: Explosion +Author-email: contact@explosion.ai +License: MIT +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Console +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Science/Research +Classifier: License :: OSI Approved :: MIT License +Classifier: Operating System :: MacOS :: MacOS X +Classifier: Programming Language :: Cython +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.6 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Topic :: Scientific/Engineering +Requires-Python: >=3.6 +Description-Content-Type: text/markdown +License-File: LICENSE +Requires-Dist: regex >=2022 + +# 🥢 Curated Tokenizers + +This Python library provides word-/sentencepiece tokenizers. The following +types of tokenizers are currenty supported: + +| Tokenizer | Binding | Example model | +| --------- | ------------- | ------------- | +| BPE | sentencepiece | | +| Byte BPE | Native | RoBERTa/GPT-2 | +| Unigram | sentencepiece | XLM-RoBERTa | +| Wordpiece | Native | BERT | + +## ⚠️ Warning: experimental package + +This package is experimental and it is likely that the APIs will change in +incompatible ways. + +## ⏳ Install + +Curated tokenizers is availble through PyPI: + +```bash +pip install curated_tokenizers +``` + +## 🚀 Quickstart + +The best way to get started with curated tokenizers is through the +[`curated-transformers`](https://github.com/explosion/curated-transformers) +library. `curated-transformers` also provides functionality to load tokenization +models from Huggingface Hub. diff --git a/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers-0.0.9.dist-info/RECORD b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers-0.0.9.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..55b24ce99f034905f28a70a614ca5733faff68c9 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers-0.0.9.dist-info/RECORD @@ -0,0 +1,41 @@ +curated_tokenizers-0.0.9.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +curated_tokenizers-0.0.9.dist-info/LICENSE,sha256=tTKVA-2oaLtu5MKsNMDQUjVhbPAa0z5X6VB_W06KS7s,2693 +curated_tokenizers-0.0.9.dist-info/METADATA,sha256=hgruKy6g2NaPgqQVal-HHisZBh5LYSTimhQslREAFEA,1965 +curated_tokenizers-0.0.9.dist-info/RECORD,, +curated_tokenizers-0.0.9.dist-info/WHEEL,sha256=j9Aissza3750LQHFAQyYerNjmkEON1-8w_RaZNFtKSs,102 +curated_tokenizers-0.0.9.dist-info/top_level.txt,sha256=EKBDsRk94HtBI7QQVDtt8uMqpwI--el9tTFO5T99Yjw,19 +curated_tokenizers-0.0.9.dist-info/zip-safe,sha256=frcCV1k9oG9oKj3dpUqdJg1PxRT2RSN_XKdLCPjaYaY,2 +curated_tokenizers/__init__.py,sha256=I5Ylm5wnIZo2FyIk8nSTokNOctBmx37gM1Tw-bdciZ8,123 +curated_tokenizers/__pycache__/__init__.cpython-312.pyc,, +curated_tokenizers/_bbpe.cp312-win_amd64.pyd,sha256=8neoWaLuCxypRyM44eN5E4nCxImxpbzkfGEbSNq0aCs,139264 +curated_tokenizers/_bbpe.cpp,sha256=uMHRxWOhSczZ_gzWzO062Va6rbfdDzThoaO3K6hMCPo,697845 +curated_tokenizers/_bbpe.pxd,sha256=UnpX3I-0VpIlmSlPJvBsCfKTVlt303xAc7xrr2Oxay0,341 +curated_tokenizers/_bbpe.pyx,sha256=tkjsvc0-_cA9WZghKNFXGgBb9xtYbHnGlBMF9xh0fUc,6635 +curated_tokenizers/_spp.cp312-win_amd64.pyd,sha256=AfASDhqYul_phGkCEL-YykvnjHKJ-PK_ufrKAsifM6E,440832 +curated_tokenizers/_spp.cpp,sha256=Zf-CexbSgHXTPb9N80EXMZFHMNhK4NpThZVikmzH5tY,565133 +curated_tokenizers/_spp.pxd,sha256=pQkyxqdzu5ttvUW1s3ogVTp0AFux8DaH0XzuIQ_rcnw,2208 +curated_tokenizers/_spp.pyx,sha256=43WyCKajuWxmHtJPUmKNqkvlJqmlDEPSfBMoSvGzm7M,8023 +curated_tokenizers/_wordpiece.cp312-win_amd64.pyd,sha256=GrHzhAnYmqx7VUBqb_aNgE7Lcjky4LBYi1wOc6rqrSw,94720 +curated_tokenizers/_wordpiece.cpp,sha256=OnHvomYjtWjlTjX5D-42Hs9vyJYs2yCz-ocEtf6Np6s,523452 +curated_tokenizers/_wordpiece.pxd,sha256=yOEFdQzCYGDP4GEFGEVx5lovdF5h5BuHges0yfLdUF4,676 +curated_tokenizers/_wordpiece.pyx,sha256=Fcv8D5fW2KczX_Geq-dfxg7Pts_WKJAJdpz51rFczIA,4976 +curated_tokenizers/config.h,sha256=oqYLY79H-0BDs6gb4lvIlkHpNErL0G-O-v8ogUnO7WQ,165 +curated_tokenizers/merges.cc,sha256=BCQYv3XTcb59fQxZ6k0YDV6aviuvjBg3ZDSorBSXZdA,2200 +curated_tokenizers/merges.hh,sha256=wQ5kmTyCREWmvfgNHDetnD_37EOeaLU2well9pAHkS4,1233 +curated_tokenizers/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +curated_tokenizers/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +curated_tokenizers/tests/__pycache__/__init__.cpython-312.pyc,, +curated_tokenizers/tests/__pycache__/test_bbpe_processor.cpython-312.pyc,, +curated_tokenizers/tests/__pycache__/test_sp.cpython-312.pyc,, +curated_tokenizers/tests/__pycache__/test_word_piece_processor.cpython-312.pyc,, +curated_tokenizers/tests/incorrect-merges.txt,sha256=fnsVuf9z1j0xufXD-pk7Co_84FllzO7nFOnVCJrwcYY,20 +curated_tokenizers/tests/robbert-merges-1000.txt,sha256=2rMsEPdaED-CmBtoGTO0cnqt-vJeZyesKFg86aWu6t8,7292 +curated_tokenizers/tests/robbert-vocab-1000.json,sha256=sTR5uy1sMPqy8H-Uz1UuLcR4eBDMx-uz-BiOD4dHthM,17902 +curated_tokenizers/tests/test_bbpe_processor.py,sha256=jlm2TBQgLUp-gwz_L_DAScggVPzkEz0lD93e6QsKxGA,2253 +curated_tokenizers/tests/test_sp.py,sha256=MRR_VYZbRCjd9IWeeIG5feq0jOYVYqIs3xsl3Hr69II,4851 +curated_tokenizers/tests/test_word_piece_processor.py,sha256=SCGA5RhBH7tg0X6CbSag92FyiR2dnJUr8PuB0bbN3Y4,2355 +curated_tokenizers/tests/toy-word-pieces.txt,sha256=sj8CZR_4F20yURvo1IfUmJDz-hAk4g2yeLjXefzcKQg,35 +curated_tokenizers/tests/toy.model,sha256=aOgs9MnD7wvh8lp8riyDb8r6fTyDgh-5hkEeVnea0eI,253270 +curated_tokenizers/util.hh,sha256=NvGqvq5yxhOSoI6sDIbeNDWF3mrIRbOEg56ESg3gxlk,346 +curated_tokenizers/wordpiece.cc,sha256=Cun1biGOuh9YaSm-wAJOjs57ibvetlZS2Ml_55vMFcM,1120 +curated_tokenizers/wordpiece.hh,sha256=fpjoC1eYHf9l1U_owkOJguCau_EWRJhIRqDaauQCIqg,1051 diff --git a/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers-0.0.9.dist-info/WHEEL b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers-0.0.9.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..1c1a93de9b166abfb749f83ce73ce2cc2eff289b --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers-0.0.9.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.42.0) +Root-Is-Purelib: false +Tag: cp312-cp312-win_amd64 + diff --git a/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers-0.0.9.dist-info/top_level.txt b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers-0.0.9.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..43ba3bde7dce284bbac77dffcf447be62caaf99b --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers-0.0.9.dist-info/top_level.txt @@ -0,0 +1 @@ +curated_tokenizers diff --git a/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers-0.0.9.dist-info/zip-safe b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers-0.0.9.dist-info/zip-safe new file mode 100644 index 0000000000000000000000000000000000000000..d3f5a12faa99758192ecc4ed3fc22c9249232e86 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers-0.0.9.dist-info/zip-safe @@ -0,0 +1 @@ + diff --git a/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/__init__.py b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a1ec6072803e3b969b5b05a98ae259c7a64e29b4 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/__init__.py @@ -0,0 +1,3 @@ +from ._bbpe import ByteBPEProcessor +from ._spp import SentencePieceProcessor +from ._wordpiece import WordPieceProcessor diff --git a/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/_bbpe.cpp b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/_bbpe.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e4db6715643aaf356b241eb9b22791bac83c62f0 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/_bbpe.cpp @@ -0,0 +1,17007 @@ +/* Generated by Cython 3.0.8 */ + +/* BEGIN: Cython Metadata +{ + "distutils": { + "depends": [ + "curated_tokenizers\\merges.hh" + ], + "include_dirs": [ + "curated_tokenizers" + ], + "language": "c++", + "name": "curated_tokenizers._bbpe", + "sources": [ + "curated_tokenizers/_bbpe.pyx", + "curated_tokenizers/merges.cc" + ] + }, + "module_name": "curated_tokenizers._bbpe" +} +END: Cython Metadata */ + +#ifndef PY_SSIZE_T_CLEAN +#define PY_SSIZE_T_CLEAN +#endif /* PY_SSIZE_T_CLEAN */ +#if defined(CYTHON_LIMITED_API) && 0 + #ifndef Py_LIMITED_API + #if CYTHON_LIMITED_API+0 > 0x03030000 + #define Py_LIMITED_API CYTHON_LIMITED_API + #else + #define Py_LIMITED_API 0x03030000 + #endif + #endif +#endif + +#include "Python.h" +#ifndef Py_PYTHON_H + #error Python headers needed to compile C extensions, please install development version of Python. +#elif PY_VERSION_HEX < 0x02070000 || (0x03000000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x03030000) + #error Cython requires Python 2.7+ or Python 3.3+. +#else +#if defined(CYTHON_LIMITED_API) && CYTHON_LIMITED_API +#define __PYX_EXTRA_ABI_MODULE_NAME "limited" +#else +#define __PYX_EXTRA_ABI_MODULE_NAME "" +#endif +#define CYTHON_ABI "3_0_8" __PYX_EXTRA_ABI_MODULE_NAME +#define __PYX_ABI_MODULE_NAME "_cython_" CYTHON_ABI +#define __PYX_TYPE_MODULE_PREFIX __PYX_ABI_MODULE_NAME "." +#define CYTHON_HEX_VERSION 0x030008F0 +#define CYTHON_FUTURE_DIVISION 0 +#include +#ifndef offsetof + #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) +#endif +#if !defined(_WIN32) && !defined(WIN32) && !defined(MS_WINDOWS) + #ifndef __stdcall + #define __stdcall + #endif + #ifndef __cdecl + #define __cdecl + #endif + #ifndef __fastcall + #define __fastcall + #endif +#endif +#ifndef DL_IMPORT + #define DL_IMPORT(t) t +#endif +#ifndef DL_EXPORT + #define DL_EXPORT(t) t +#endif +#define __PYX_COMMA , +#ifndef HAVE_LONG_LONG + #define HAVE_LONG_LONG +#endif +#ifndef PY_LONG_LONG + #define PY_LONG_LONG LONG_LONG +#endif +#ifndef Py_HUGE_VAL + #define Py_HUGE_VAL HUGE_VAL +#endif +#define __PYX_LIMITED_VERSION_HEX PY_VERSION_HEX +#if defined(GRAALVM_PYTHON) + /* For very preliminary testing purposes. Most variables are set the same as PyPy. + The existence of this section does not imply that anything works or is even tested */ + #define CYTHON_COMPILING_IN_PYPY 0 + #define CYTHON_COMPILING_IN_CPYTHON 0 + #define CYTHON_COMPILING_IN_LIMITED_API 0 + #define CYTHON_COMPILING_IN_GRAAL 1 + #define CYTHON_COMPILING_IN_NOGIL 0 + #undef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 0 + #undef CYTHON_USE_TYPE_SPECS + #define CYTHON_USE_TYPE_SPECS 0 + #undef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 0 + #if PY_VERSION_HEX < 0x03050000 + #undef CYTHON_USE_ASYNC_SLOTS + #define CYTHON_USE_ASYNC_SLOTS 0 + #elif !defined(CYTHON_USE_ASYNC_SLOTS) + #define CYTHON_USE_ASYNC_SLOTS 1 + #endif + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #undef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 0 + #undef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #undef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 0 + #undef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 1 + #undef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 0 + #undef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 0 + #undef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 0 + #undef CYTHON_FAST_GIL + #define CYTHON_FAST_GIL 0 + #undef CYTHON_METH_FASTCALL + #define CYTHON_METH_FASTCALL 0 + #undef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 0 + #ifndef CYTHON_PEP487_INIT_SUBCLASS + #define CYTHON_PEP487_INIT_SUBCLASS (PY_MAJOR_VERSION >= 3) + #endif + #undef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #undef CYTHON_USE_MODULE_STATE + #define CYTHON_USE_MODULE_STATE 0 + #undef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE 0 + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #undef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 0 + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC 0 + #endif +#elif defined(PYPY_VERSION) + #define CYTHON_COMPILING_IN_PYPY 1 + #define CYTHON_COMPILING_IN_CPYTHON 0 + #define CYTHON_COMPILING_IN_LIMITED_API 0 + #define CYTHON_COMPILING_IN_GRAAL 0 + #define CYTHON_COMPILING_IN_NOGIL 0 + #undef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 0 + #ifndef CYTHON_USE_TYPE_SPECS + #define CYTHON_USE_TYPE_SPECS 0 + #endif + #undef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 0 + #if PY_VERSION_HEX < 0x03050000 + #undef CYTHON_USE_ASYNC_SLOTS + #define CYTHON_USE_ASYNC_SLOTS 0 + #elif !defined(CYTHON_USE_ASYNC_SLOTS) + #define CYTHON_USE_ASYNC_SLOTS 1 + #endif + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #undef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 0 + #undef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #undef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 0 + #undef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 1 + #undef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 0 + #undef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 0 + #undef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 0 + #undef CYTHON_FAST_GIL + #define CYTHON_FAST_GIL 0 + #undef CYTHON_METH_FASTCALL + #define CYTHON_METH_FASTCALL 0 + #undef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 0 + #ifndef CYTHON_PEP487_INIT_SUBCLASS + #define CYTHON_PEP487_INIT_SUBCLASS (PY_MAJOR_VERSION >= 3) + #endif + #if PY_VERSION_HEX < 0x03090000 + #undef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 0 + #elif !defined(CYTHON_PEP489_MULTI_PHASE_INIT) + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #endif + #undef CYTHON_USE_MODULE_STATE + #define CYTHON_USE_MODULE_STATE 0 + #undef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE (PY_VERSION_HEX >= 0x030400a1 && PYPY_VERSION_NUM >= 0x07030C00) + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #undef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 0 + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC 0 + #endif +#elif defined(CYTHON_LIMITED_API) + #ifdef Py_LIMITED_API + #undef __PYX_LIMITED_VERSION_HEX + #define __PYX_LIMITED_VERSION_HEX Py_LIMITED_API + #endif + #define CYTHON_COMPILING_IN_PYPY 0 + #define CYTHON_COMPILING_IN_CPYTHON 0 + #define CYTHON_COMPILING_IN_LIMITED_API 1 + #define CYTHON_COMPILING_IN_GRAAL 0 + #define CYTHON_COMPILING_IN_NOGIL 0 + #undef CYTHON_CLINE_IN_TRACEBACK + #define CYTHON_CLINE_IN_TRACEBACK 0 + #undef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 0 + #undef CYTHON_USE_TYPE_SPECS + #define CYTHON_USE_TYPE_SPECS 1 + #undef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 0 + #undef CYTHON_USE_ASYNC_SLOTS + #define CYTHON_USE_ASYNC_SLOTS 0 + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #undef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 0 + #ifndef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #endif + #undef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 0 + #ifndef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 0 + #endif + #undef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 0 + #undef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 0 + #undef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 0 + #undef CYTHON_FAST_GIL + #define CYTHON_FAST_GIL 0 + #undef CYTHON_METH_FASTCALL + #define CYTHON_METH_FASTCALL 0 + #undef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 0 + #ifndef CYTHON_PEP487_INIT_SUBCLASS + #define CYTHON_PEP487_INIT_SUBCLASS 1 + #endif + #undef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 0 + #undef CYTHON_USE_MODULE_STATE + #define CYTHON_USE_MODULE_STATE 1 + #ifndef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE 0 + #endif + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #undef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 0 + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC 0 + #endif +#elif defined(Py_GIL_DISABLED) || defined(Py_NOGIL) + #define CYTHON_COMPILING_IN_PYPY 0 + #define CYTHON_COMPILING_IN_CPYTHON 0 + #define CYTHON_COMPILING_IN_LIMITED_API 0 + #define CYTHON_COMPILING_IN_GRAAL 0 + #define CYTHON_COMPILING_IN_NOGIL 1 + #ifndef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 1 + #endif + #undef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 0 + #ifndef CYTHON_USE_ASYNC_SLOTS + #define CYTHON_USE_ASYNC_SLOTS 1 + #endif + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #ifndef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 1 + #endif + #undef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #undef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 0 + #ifndef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 0 + #endif + #ifndef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 1 + #endif + #ifndef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 1 + #endif + #undef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 0 + #undef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 0 + #ifndef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #endif + #ifndef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE 1 + #endif + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #undef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 0 +#else + #define CYTHON_COMPILING_IN_PYPY 0 + #define CYTHON_COMPILING_IN_CPYTHON 1 + #define CYTHON_COMPILING_IN_LIMITED_API 0 + #define CYTHON_COMPILING_IN_GRAAL 0 + #define CYTHON_COMPILING_IN_NOGIL 0 + #ifndef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 1 + #endif + #ifndef CYTHON_USE_TYPE_SPECS + #define CYTHON_USE_TYPE_SPECS 0 + #endif + #ifndef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 1 + #endif + #if PY_MAJOR_VERSION < 3 + #undef CYTHON_USE_ASYNC_SLOTS + #define CYTHON_USE_ASYNC_SLOTS 0 + #elif !defined(CYTHON_USE_ASYNC_SLOTS) + #define CYTHON_USE_ASYNC_SLOTS 1 + #endif + #ifndef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 1 + #endif + #ifndef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 1 + #endif + #ifndef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 1 + #endif + #if PY_VERSION_HEX < 0x030300F0 || PY_VERSION_HEX >= 0x030B00A2 + #undef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #elif !defined(CYTHON_USE_UNICODE_WRITER) + #define CYTHON_USE_UNICODE_WRITER 1 + #endif + #ifndef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 0 + #endif + #ifndef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 1 + #endif + #ifndef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 1 + #endif + #ifndef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 1 + #endif + #ifndef CYTHON_FAST_GIL + #define CYTHON_FAST_GIL (PY_MAJOR_VERSION < 3 || PY_VERSION_HEX >= 0x03060000 && PY_VERSION_HEX < 0x030C00A6) + #endif + #ifndef CYTHON_METH_FASTCALL + #define CYTHON_METH_FASTCALL (PY_VERSION_HEX >= 0x030700A1) + #endif + #ifndef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 1 + #endif + #ifndef CYTHON_PEP487_INIT_SUBCLASS + #define CYTHON_PEP487_INIT_SUBCLASS 1 + #endif + #if PY_VERSION_HEX < 0x03050000 + #undef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 0 + #elif !defined(CYTHON_PEP489_MULTI_PHASE_INIT) + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #endif + #ifndef CYTHON_USE_MODULE_STATE + #define CYTHON_USE_MODULE_STATE 0 + #endif + #if PY_VERSION_HEX < 0x030400a1 + #undef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE 0 + #elif !defined(CYTHON_USE_TP_FINALIZE) + #define CYTHON_USE_TP_FINALIZE 1 + #endif + #if PY_VERSION_HEX < 0x030600B1 + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #elif !defined(CYTHON_USE_DICT_VERSIONS) + #define CYTHON_USE_DICT_VERSIONS (PY_VERSION_HEX < 0x030C00A5) + #endif + #if PY_VERSION_HEX < 0x030700A3 + #undef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 0 + #elif !defined(CYTHON_USE_EXC_INFO_STACK) + #define CYTHON_USE_EXC_INFO_STACK 1 + #endif + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC 1 + #endif +#endif +#if !defined(CYTHON_FAST_PYCCALL) +#define CYTHON_FAST_PYCCALL (CYTHON_FAST_PYCALL && PY_VERSION_HEX >= 0x030600B1) +#endif +#if !defined(CYTHON_VECTORCALL) +#define CYTHON_VECTORCALL (CYTHON_FAST_PYCCALL && PY_VERSION_HEX >= 0x030800B1) +#endif +#define CYTHON_BACKPORT_VECTORCALL (CYTHON_METH_FASTCALL && PY_VERSION_HEX < 0x030800B1) +#if CYTHON_USE_PYLONG_INTERNALS + #if PY_MAJOR_VERSION < 3 + #include "longintrepr.h" + #endif + #undef SHIFT + #undef BASE + #undef MASK + #ifdef SIZEOF_VOID_P + enum { __pyx_check_sizeof_voidp = 1 / (int)(SIZEOF_VOID_P == sizeof(void*)) }; + #endif +#endif +#ifndef __has_attribute + #define __has_attribute(x) 0 +#endif +#ifndef __has_cpp_attribute + #define __has_cpp_attribute(x) 0 +#endif +#ifndef CYTHON_RESTRICT + #if defined(__GNUC__) + #define CYTHON_RESTRICT __restrict__ + #elif defined(_MSC_VER) && _MSC_VER >= 1400 + #define CYTHON_RESTRICT __restrict + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_RESTRICT restrict + #else + #define CYTHON_RESTRICT + #endif +#endif +#ifndef CYTHON_UNUSED + #if defined(__cplusplus) + /* for clang __has_cpp_attribute(maybe_unused) is true even before C++17 + * but leads to warnings with -pedantic, since it is a C++17 feature */ + #if ((defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) || __cplusplus >= 201703L) + #if __has_cpp_attribute(maybe_unused) + #define CYTHON_UNUSED [[maybe_unused]] + #endif + #endif + #endif +#endif +#ifndef CYTHON_UNUSED +# if defined(__GNUC__) +# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +#endif +#ifndef CYTHON_UNUSED_VAR +# if defined(__cplusplus) + template void CYTHON_UNUSED_VAR( const T& ) { } +# else +# define CYTHON_UNUSED_VAR(x) (void)(x) +# endif +#endif +#ifndef CYTHON_MAYBE_UNUSED_VAR + #define CYTHON_MAYBE_UNUSED_VAR(x) CYTHON_UNUSED_VAR(x) +#endif +#ifndef CYTHON_NCP_UNUSED +# if CYTHON_COMPILING_IN_CPYTHON +# define CYTHON_NCP_UNUSED +# else +# define CYTHON_NCP_UNUSED CYTHON_UNUSED +# endif +#endif +#ifndef CYTHON_USE_CPP_STD_MOVE + #if defined(__cplusplus) && (\ + __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1600)) + #define CYTHON_USE_CPP_STD_MOVE 1 + #else + #define CYTHON_USE_CPP_STD_MOVE 0 + #endif +#endif +#define __Pyx_void_to_None(void_result) ((void)(void_result), Py_INCREF(Py_None), Py_None) +#ifdef _MSC_VER + #ifndef _MSC_STDINT_H_ + #if _MSC_VER < 1300 + typedef unsigned char uint8_t; + typedef unsigned short uint16_t; + typedef unsigned int uint32_t; + #else + typedef unsigned __int8 uint8_t; + typedef unsigned __int16 uint16_t; + typedef unsigned __int32 uint32_t; + #endif + #endif + #if _MSC_VER < 1300 + #ifdef _WIN64 + typedef unsigned long long __pyx_uintptr_t; + #else + typedef unsigned int __pyx_uintptr_t; + #endif + #else + #ifdef _WIN64 + typedef unsigned __int64 __pyx_uintptr_t; + #else + typedef unsigned __int32 __pyx_uintptr_t; + #endif + #endif +#else + #include + typedef uintptr_t __pyx_uintptr_t; +#endif +#ifndef CYTHON_FALLTHROUGH + #if defined(__cplusplus) + /* for clang __has_cpp_attribute(fallthrough) is true even before C++17 + * but leads to warnings with -pedantic, since it is a C++17 feature */ + #if ((defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) || __cplusplus >= 201703L) + #if __has_cpp_attribute(fallthrough) + #define CYTHON_FALLTHROUGH [[fallthrough]] + #endif + #endif + #ifndef CYTHON_FALLTHROUGH + #if __has_cpp_attribute(clang::fallthrough) + #define CYTHON_FALLTHROUGH [[clang::fallthrough]] + #elif __has_cpp_attribute(gnu::fallthrough) + #define CYTHON_FALLTHROUGH [[gnu::fallthrough]] + #endif + #endif + #endif + #ifndef CYTHON_FALLTHROUGH + #if __has_attribute(fallthrough) + #define CYTHON_FALLTHROUGH __attribute__((fallthrough)) + #else + #define CYTHON_FALLTHROUGH + #endif + #endif + #if defined(__clang__) && defined(__apple_build_version__) + #if __apple_build_version__ < 7000000 + #undef CYTHON_FALLTHROUGH + #define CYTHON_FALLTHROUGH + #endif + #endif +#endif +#ifdef __cplusplus + template + struct __PYX_IS_UNSIGNED_IMPL {static const bool value = T(0) < T(-1);}; + #define __PYX_IS_UNSIGNED(type) (__PYX_IS_UNSIGNED_IMPL::value) +#else + #define __PYX_IS_UNSIGNED(type) (((type)-1) > 0) +#endif +#if CYTHON_COMPILING_IN_PYPY == 1 + #define __PYX_NEED_TP_PRINT_SLOT (PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x030A0000) +#else + #define __PYX_NEED_TP_PRINT_SLOT (PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000) +#endif +#define __PYX_REINTERPRET_FUNCION(func_pointer, other_pointer) ((func_pointer)(void(*)(void))(other_pointer)) + +#ifndef __cplusplus + #error "Cython files generated with the C++ option must be compiled with a C++ compiler." +#endif +#ifndef CYTHON_INLINE + #if defined(__clang__) + #define CYTHON_INLINE __inline__ __attribute__ ((__unused__)) + #else + #define CYTHON_INLINE inline + #endif +#endif +template +void __Pyx_call_destructor(T& x) { + x.~T(); +} +template +class __Pyx_FakeReference { + public: + __Pyx_FakeReference() : ptr(NULL) { } + __Pyx_FakeReference(const T& ref) : ptr(const_cast(&ref)) { } + T *operator->() { return ptr; } + T *operator&() { return ptr; } + operator T&() { return *ptr; } + template bool operator ==(const U& other) const { return *ptr == other; } + template bool operator !=(const U& other) const { return *ptr != other; } + template bool operator==(const __Pyx_FakeReference& other) const { return *ptr == *other.ptr; } + template bool operator!=(const __Pyx_FakeReference& other) const { return *ptr != *other.ptr; } + private: + T *ptr; +}; + +#define __PYX_BUILD_PY_SSIZE_T "n" +#define CYTHON_FORMAT_SSIZE_T "z" +#if PY_MAJOR_VERSION < 3 + #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" + #define __Pyx_DefaultClassType PyClass_Type + #define __Pyx_PyCode_New(a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ + PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#else + #define __Pyx_BUILTIN_MODULE_NAME "builtins" + #define __Pyx_DefaultClassType PyType_Type +#if CYTHON_COMPILING_IN_LIMITED_API + static CYTHON_INLINE PyObject* __Pyx_PyCode_New(int a, int p, int k, int l, int s, int f, + PyObject *code, PyObject *c, PyObject* n, PyObject *v, + PyObject *fv, PyObject *cell, PyObject* fn, + PyObject *name, int fline, PyObject *lnos) { + PyObject *exception_table = NULL; + PyObject *types_module=NULL, *code_type=NULL, *result=NULL; + #if __PYX_LIMITED_VERSION_HEX < 0x030B0000 + PyObject *version_info; + PyObject *py_minor_version = NULL; + #endif + long minor_version = 0; + PyObject *type, *value, *traceback; + PyErr_Fetch(&type, &value, &traceback); + #if __PYX_LIMITED_VERSION_HEX >= 0x030B0000 + minor_version = 11; + #else + if (!(version_info = PySys_GetObject("version_info"))) goto end; + if (!(py_minor_version = PySequence_GetItem(version_info, 1))) goto end; + minor_version = PyLong_AsLong(py_minor_version); + Py_DECREF(py_minor_version); + if (minor_version == -1 && PyErr_Occurred()) goto end; + #endif + if (!(types_module = PyImport_ImportModule("types"))) goto end; + if (!(code_type = PyObject_GetAttrString(types_module, "CodeType"))) goto end; + if (minor_version <= 7) { + (void)p; + result = PyObject_CallFunction(code_type, "iiiiiOOOOOOiOO", a, k, l, s, f, code, + c, n, v, fn, name, fline, lnos, fv, cell); + } else if (minor_version <= 10) { + result = PyObject_CallFunction(code_type, "iiiiiiOOOOOOiOO", a,p, k, l, s, f, code, + c, n, v, fn, name, fline, lnos, fv, cell); + } else { + if (!(exception_table = PyBytes_FromStringAndSize(NULL, 0))) goto end; + result = PyObject_CallFunction(code_type, "iiiiiiOOOOOOOiOO", a,p, k, l, s, f, code, + c, n, v, fn, name, name, fline, lnos, exception_table, fv, cell); + } + end: + Py_XDECREF(code_type); + Py_XDECREF(exception_table); + Py_XDECREF(types_module); + if (type) { + PyErr_Restore(type, value, traceback); + } + return result; + } + #ifndef CO_OPTIMIZED + #define CO_OPTIMIZED 0x0001 + #endif + #ifndef CO_NEWLOCALS + #define CO_NEWLOCALS 0x0002 + #endif + #ifndef CO_VARARGS + #define CO_VARARGS 0x0004 + #endif + #ifndef CO_VARKEYWORDS + #define CO_VARKEYWORDS 0x0008 + #endif + #ifndef CO_ASYNC_GENERATOR + #define CO_ASYNC_GENERATOR 0x0200 + #endif + #ifndef CO_GENERATOR + #define CO_GENERATOR 0x0020 + #endif + #ifndef CO_COROUTINE + #define CO_COROUTINE 0x0080 + #endif +#elif PY_VERSION_HEX >= 0x030B0000 + static CYTHON_INLINE PyCodeObject* __Pyx_PyCode_New(int a, int p, int k, int l, int s, int f, + PyObject *code, PyObject *c, PyObject* n, PyObject *v, + PyObject *fv, PyObject *cell, PyObject* fn, + PyObject *name, int fline, PyObject *lnos) { + PyCodeObject *result; + PyObject *empty_bytes = PyBytes_FromStringAndSize("", 0); + if (!empty_bytes) return NULL; + result = + #if PY_VERSION_HEX >= 0x030C0000 + PyUnstable_Code_NewWithPosOnlyArgs + #else + PyCode_NewWithPosOnlyArgs + #endif + (a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, name, fline, lnos, empty_bytes); + Py_DECREF(empty_bytes); + return result; + } +#elif PY_VERSION_HEX >= 0x030800B2 && !CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyCode_New(a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ + PyCode_NewWithPosOnlyArgs(a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#else + #define __Pyx_PyCode_New(a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ + PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#endif +#endif +#if PY_VERSION_HEX >= 0x030900A4 || defined(Py_IS_TYPE) + #define __Pyx_IS_TYPE(ob, type) Py_IS_TYPE(ob, type) +#else + #define __Pyx_IS_TYPE(ob, type) (((const PyObject*)ob)->ob_type == (type)) +#endif +#if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_Is) + #define __Pyx_Py_Is(x, y) Py_Is(x, y) +#else + #define __Pyx_Py_Is(x, y) ((x) == (y)) +#endif +#if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_IsNone) + #define __Pyx_Py_IsNone(ob) Py_IsNone(ob) +#else + #define __Pyx_Py_IsNone(ob) __Pyx_Py_Is((ob), Py_None) +#endif +#if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_IsTrue) + #define __Pyx_Py_IsTrue(ob) Py_IsTrue(ob) +#else + #define __Pyx_Py_IsTrue(ob) __Pyx_Py_Is((ob), Py_True) +#endif +#if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_IsFalse) + #define __Pyx_Py_IsFalse(ob) Py_IsFalse(ob) +#else + #define __Pyx_Py_IsFalse(ob) __Pyx_Py_Is((ob), Py_False) +#endif +#define __Pyx_NoneAsNull(obj) (__Pyx_Py_IsNone(obj) ? NULL : (obj)) +#if PY_VERSION_HEX >= 0x030900F0 && !CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyObject_GC_IsFinalized(o) PyObject_GC_IsFinalized(o) +#else + #define __Pyx_PyObject_GC_IsFinalized(o) _PyGC_FINALIZED(o) +#endif +#ifndef CO_COROUTINE + #define CO_COROUTINE 0x80 +#endif +#ifndef CO_ASYNC_GENERATOR + #define CO_ASYNC_GENERATOR 0x200 +#endif +#ifndef Py_TPFLAGS_CHECKTYPES + #define Py_TPFLAGS_CHECKTYPES 0 +#endif +#ifndef Py_TPFLAGS_HAVE_INDEX + #define Py_TPFLAGS_HAVE_INDEX 0 +#endif +#ifndef Py_TPFLAGS_HAVE_NEWBUFFER + #define Py_TPFLAGS_HAVE_NEWBUFFER 0 +#endif +#ifndef Py_TPFLAGS_HAVE_FINALIZE + #define Py_TPFLAGS_HAVE_FINALIZE 0 +#endif +#ifndef Py_TPFLAGS_SEQUENCE + #define Py_TPFLAGS_SEQUENCE 0 +#endif +#ifndef Py_TPFLAGS_MAPPING + #define Py_TPFLAGS_MAPPING 0 +#endif +#ifndef METH_STACKLESS + #define METH_STACKLESS 0 +#endif +#if PY_VERSION_HEX <= 0x030700A3 || !defined(METH_FASTCALL) + #ifndef METH_FASTCALL + #define METH_FASTCALL 0x80 + #endif + typedef PyObject *(*__Pyx_PyCFunctionFast) (PyObject *self, PyObject *const *args, Py_ssize_t nargs); + typedef PyObject *(*__Pyx_PyCFunctionFastWithKeywords) (PyObject *self, PyObject *const *args, + Py_ssize_t nargs, PyObject *kwnames); +#else + #define __Pyx_PyCFunctionFast _PyCFunctionFast + #define __Pyx_PyCFunctionFastWithKeywords _PyCFunctionFastWithKeywords +#endif +#if CYTHON_METH_FASTCALL + #define __Pyx_METH_FASTCALL METH_FASTCALL + #define __Pyx_PyCFunction_FastCall __Pyx_PyCFunctionFast + #define __Pyx_PyCFunction_FastCallWithKeywords __Pyx_PyCFunctionFastWithKeywords +#else + #define __Pyx_METH_FASTCALL METH_VARARGS + #define __Pyx_PyCFunction_FastCall PyCFunction + #define __Pyx_PyCFunction_FastCallWithKeywords PyCFunctionWithKeywords +#endif +#if CYTHON_VECTORCALL + #define __pyx_vectorcallfunc vectorcallfunc + #define __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET PY_VECTORCALL_ARGUMENTS_OFFSET + #define __Pyx_PyVectorcall_NARGS(n) PyVectorcall_NARGS((size_t)(n)) +#elif CYTHON_BACKPORT_VECTORCALL + typedef PyObject *(*__pyx_vectorcallfunc)(PyObject *callable, PyObject *const *args, + size_t nargsf, PyObject *kwnames); + #define __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET ((size_t)1 << (8 * sizeof(size_t) - 1)) + #define __Pyx_PyVectorcall_NARGS(n) ((Py_ssize_t)(((size_t)(n)) & ~__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)) +#else + #define __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET 0 + #define __Pyx_PyVectorcall_NARGS(n) ((Py_ssize_t)(n)) +#endif +#if PY_MAJOR_VERSION >= 0x030900B1 +#define __Pyx_PyCFunction_CheckExact(func) PyCFunction_CheckExact(func) +#else +#define __Pyx_PyCFunction_CheckExact(func) PyCFunction_Check(func) +#endif +#define __Pyx_CyOrPyCFunction_Check(func) PyCFunction_Check(func) +#if CYTHON_COMPILING_IN_CPYTHON +#define __Pyx_CyOrPyCFunction_GET_FUNCTION(func) (((PyCFunctionObject*)(func))->m_ml->ml_meth) +#elif !CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_CyOrPyCFunction_GET_FUNCTION(func) PyCFunction_GET_FUNCTION(func) +#endif +#if CYTHON_COMPILING_IN_CPYTHON +#define __Pyx_CyOrPyCFunction_GET_FLAGS(func) (((PyCFunctionObject*)(func))->m_ml->ml_flags) +static CYTHON_INLINE PyObject* __Pyx_CyOrPyCFunction_GET_SELF(PyObject *func) { + return (__Pyx_CyOrPyCFunction_GET_FLAGS(func) & METH_STATIC) ? NULL : ((PyCFunctionObject*)func)->m_self; +} +#endif +static CYTHON_INLINE int __Pyx__IsSameCFunction(PyObject *func, void *cfunc) { +#if CYTHON_COMPILING_IN_LIMITED_API + return PyCFunction_Check(func) && PyCFunction_GetFunction(func) == (PyCFunction) cfunc; +#else + return PyCFunction_Check(func) && PyCFunction_GET_FUNCTION(func) == (PyCFunction) cfunc; +#endif +} +#define __Pyx_IsSameCFunction(func, cfunc) __Pyx__IsSameCFunction(func, cfunc) +#if __PYX_LIMITED_VERSION_HEX < 0x030900B1 + #define __Pyx_PyType_FromModuleAndSpec(m, s, b) ((void)m, PyType_FromSpecWithBases(s, b)) + typedef PyObject *(*__Pyx_PyCMethod)(PyObject *, PyTypeObject *, PyObject *const *, size_t, PyObject *); +#else + #define __Pyx_PyType_FromModuleAndSpec(m, s, b) PyType_FromModuleAndSpec(m, s, b) + #define __Pyx_PyCMethod PyCMethod +#endif +#ifndef METH_METHOD + #define METH_METHOD 0x200 +#endif +#if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Malloc) + #define PyObject_Malloc(s) PyMem_Malloc(s) + #define PyObject_Free(p) PyMem_Free(p) + #define PyObject_Realloc(p) PyMem_Realloc(p) +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) + #define __Pyx_PyFrame_SetLineNumber(frame, lineno) +#else + #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) + #define __Pyx_PyFrame_SetLineNumber(frame, lineno) (frame)->f_lineno = (lineno) +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_PyThreadState_Current PyThreadState_Get() +#elif !CYTHON_FAST_THREAD_STATE + #define __Pyx_PyThreadState_Current PyThreadState_GET() +#elif PY_VERSION_HEX >= 0x030d00A1 + #define __Pyx_PyThreadState_Current PyThreadState_GetUnchecked() +#elif PY_VERSION_HEX >= 0x03060000 + #define __Pyx_PyThreadState_Current _PyThreadState_UncheckedGet() +#elif PY_VERSION_HEX >= 0x03000000 + #define __Pyx_PyThreadState_Current PyThreadState_GET() +#else + #define __Pyx_PyThreadState_Current _PyThreadState_Current +#endif +#if CYTHON_COMPILING_IN_LIMITED_API +static CYTHON_INLINE void *__Pyx_PyModule_GetState(PyObject *op) +{ + void *result; + result = PyModule_GetState(op); + if (!result) + Py_FatalError("Couldn't find the module state"); + return result; +} +#endif +#define __Pyx_PyObject_GetSlot(obj, name, func_ctype) __Pyx_PyType_GetSlot(Py_TYPE(obj), name, func_ctype) +#if CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_PyType_GetSlot(type, name, func_ctype) ((func_ctype) PyType_GetSlot((type), Py_##name)) +#else + #define __Pyx_PyType_GetSlot(type, name, func_ctype) ((type)->name) +#endif +#if PY_VERSION_HEX < 0x030700A2 && !defined(PyThread_tss_create) && !defined(Py_tss_NEEDS_INIT) +#include "pythread.h" +#define Py_tss_NEEDS_INIT 0 +typedef int Py_tss_t; +static CYTHON_INLINE int PyThread_tss_create(Py_tss_t *key) { + *key = PyThread_create_key(); + return 0; +} +static CYTHON_INLINE Py_tss_t * PyThread_tss_alloc(void) { + Py_tss_t *key = (Py_tss_t *)PyObject_Malloc(sizeof(Py_tss_t)); + *key = Py_tss_NEEDS_INIT; + return key; +} +static CYTHON_INLINE void PyThread_tss_free(Py_tss_t *key) { + PyObject_Free(key); +} +static CYTHON_INLINE int PyThread_tss_is_created(Py_tss_t *key) { + return *key != Py_tss_NEEDS_INIT; +} +static CYTHON_INLINE void PyThread_tss_delete(Py_tss_t *key) { + PyThread_delete_key(*key); + *key = Py_tss_NEEDS_INIT; +} +static CYTHON_INLINE int PyThread_tss_set(Py_tss_t *key, void *value) { + return PyThread_set_key_value(*key, value); +} +static CYTHON_INLINE void * PyThread_tss_get(Py_tss_t *key) { + return PyThread_get_key_value(*key); +} +#endif +#if PY_MAJOR_VERSION < 3 + #if CYTHON_COMPILING_IN_PYPY + #if PYPY_VERSION_NUM < 0x07030600 + #if defined(__cplusplus) && __cplusplus >= 201402L + [[deprecated("`with nogil:` inside a nogil function will not release the GIL in PyPy2 < 7.3.6")]] + #elif defined(__GNUC__) || defined(__clang__) + __attribute__ ((__deprecated__("`with nogil:` inside a nogil function will not release the GIL in PyPy2 < 7.3.6"))) + #elif defined(_MSC_VER) + __declspec(deprecated("`with nogil:` inside a nogil function will not release the GIL in PyPy2 < 7.3.6")) + #endif + static CYTHON_INLINE int PyGILState_Check(void) { + return 0; + } + #else // PYPY_VERSION_NUM < 0x07030600 + #endif // PYPY_VERSION_NUM < 0x07030600 + #else + static CYTHON_INLINE int PyGILState_Check(void) { + PyThreadState * tstate = _PyThreadState_Current; + return tstate && (tstate == PyGILState_GetThisThreadState()); + } + #endif +#endif +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030d0000 || defined(_PyDict_NewPresized) +#define __Pyx_PyDict_NewPresized(n) ((n <= 8) ? PyDict_New() : _PyDict_NewPresized(n)) +#else +#define __Pyx_PyDict_NewPresized(n) PyDict_New() +#endif +#if PY_MAJOR_VERSION >= 3 || CYTHON_FUTURE_DIVISION + #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) +#else + #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) +#endif +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX > 0x030600B4 && PY_VERSION_HEX < 0x030d0000 && CYTHON_USE_UNICODE_INTERNALS +#define __Pyx_PyDict_GetItemStrWithError(dict, name) _PyDict_GetItem_KnownHash(dict, name, ((PyASCIIObject *) name)->hash) +static CYTHON_INLINE PyObject * __Pyx_PyDict_GetItemStr(PyObject *dict, PyObject *name) { + PyObject *res = __Pyx_PyDict_GetItemStrWithError(dict, name); + if (res == NULL) PyErr_Clear(); + return res; +} +#elif PY_MAJOR_VERSION >= 3 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07020000) +#define __Pyx_PyDict_GetItemStrWithError PyDict_GetItemWithError +#define __Pyx_PyDict_GetItemStr PyDict_GetItem +#else +static CYTHON_INLINE PyObject * __Pyx_PyDict_GetItemStrWithError(PyObject *dict, PyObject *name) { +#if CYTHON_COMPILING_IN_PYPY + return PyDict_GetItem(dict, name); +#else + PyDictEntry *ep; + PyDictObject *mp = (PyDictObject*) dict; + long hash = ((PyStringObject *) name)->ob_shash; + assert(hash != -1); + ep = (mp->ma_lookup)(mp, name, hash); + if (ep == NULL) { + return NULL; + } + return ep->me_value; +#endif +} +#define __Pyx_PyDict_GetItemStr PyDict_GetItem +#endif +#if CYTHON_USE_TYPE_SLOTS + #define __Pyx_PyType_GetFlags(tp) (((PyTypeObject *)tp)->tp_flags) + #define __Pyx_PyType_HasFeature(type, feature) ((__Pyx_PyType_GetFlags(type) & (feature)) != 0) + #define __Pyx_PyObject_GetIterNextFunc(obj) (Py_TYPE(obj)->tp_iternext) +#else + #define __Pyx_PyType_GetFlags(tp) (PyType_GetFlags((PyTypeObject *)tp)) + #define __Pyx_PyType_HasFeature(type, feature) PyType_HasFeature(type, feature) + #define __Pyx_PyObject_GetIterNextFunc(obj) PyIter_Next +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_SetItemOnTypeDict(tp, k, v) PyObject_GenericSetAttr((PyObject*)tp, k, v) +#else + #define __Pyx_SetItemOnTypeDict(tp, k, v) PyDict_SetItem(tp->tp_dict, k, v) +#endif +#if CYTHON_USE_TYPE_SPECS && PY_VERSION_HEX >= 0x03080000 +#define __Pyx_PyHeapTypeObject_GC_Del(obj) {\ + PyTypeObject *type = Py_TYPE((PyObject*)obj);\ + assert(__Pyx_PyType_HasFeature(type, Py_TPFLAGS_HEAPTYPE));\ + PyObject_GC_Del(obj);\ + Py_DECREF(type);\ +} +#else +#define __Pyx_PyHeapTypeObject_GC_Del(obj) PyObject_GC_Del(obj) +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + #define CYTHON_PEP393_ENABLED 1 + #define __Pyx_PyUnicode_READY(op) (0) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GetLength(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_ReadChar(u, i) + #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) ((void)u, 1114111U) + #define __Pyx_PyUnicode_KIND(u) ((void)u, (0)) + #define __Pyx_PyUnicode_DATA(u) ((void*)u) + #define __Pyx_PyUnicode_READ(k, d, i) ((void)k, PyUnicode_ReadChar((PyObject*)(d), i)) + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GetLength(u)) +#elif PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) + #define CYTHON_PEP393_ENABLED 1 + #if PY_VERSION_HEX >= 0x030C0000 + #define __Pyx_PyUnicode_READY(op) (0) + #else + #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ?\ + 0 : _PyUnicode_Ready((PyObject *)(op))) + #endif + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) + #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) PyUnicode_MAX_CHAR_VALUE(u) + #define __Pyx_PyUnicode_KIND(u) ((int)PyUnicode_KIND(u)) + #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) + #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) + #define __Pyx_PyUnicode_WRITE(k, d, i, ch) PyUnicode_WRITE(k, d, i, (Py_UCS4) ch) + #if PY_VERSION_HEX >= 0x030C0000 + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_LENGTH(u)) + #else + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x03090000 + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : ((PyCompactUnicodeObject *)(u))->wstr_length)) + #else + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : PyUnicode_GET_SIZE(u))) + #endif + #endif +#else + #define CYTHON_PEP393_ENABLED 0 + #define PyUnicode_1BYTE_KIND 1 + #define PyUnicode_2BYTE_KIND 2 + #define PyUnicode_4BYTE_KIND 4 + #define __Pyx_PyUnicode_READY(op) (0) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) + #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) ((sizeof(Py_UNICODE) == 2) ? 65535U : 1114111U) + #define __Pyx_PyUnicode_KIND(u) ((int)sizeof(Py_UNICODE)) + #define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u)) + #define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i])) + #define __Pyx_PyUnicode_WRITE(k, d, i, ch) (((void)(k)), ((Py_UNICODE*)d)[i] = (Py_UNICODE) ch) + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_SIZE(u)) +#endif +#if CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) +#else + #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ?\ + PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) +#endif +#if CYTHON_COMPILING_IN_PYPY + #if !defined(PyUnicode_DecodeUnicodeEscape) + #define PyUnicode_DecodeUnicodeEscape(s, size, errors) PyUnicode_Decode(s, size, "unicode_escape", errors) + #endif + #if !defined(PyUnicode_Contains) || (PY_MAJOR_VERSION == 2 && PYPY_VERSION_NUM < 0x07030500) + #undef PyUnicode_Contains + #define PyUnicode_Contains(u, s) PySequence_Contains(u, s) + #endif + #if !defined(PyByteArray_Check) + #define PyByteArray_Check(obj) PyObject_TypeCheck(obj, &PyByteArray_Type) + #endif + #if !defined(PyObject_Format) + #define PyObject_Format(obj, fmt) PyObject_CallMethod(obj, "__format__", "O", fmt) + #endif +#endif +#define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyString_Check(b) && !PyString_CheckExact(b)))) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) +#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyUnicode_Check(b) && !PyUnicode_CheckExact(b)))) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b) +#else + #define __Pyx_PyString_Format(a, b) PyString_Format(a, b) +#endif +#if PY_MAJOR_VERSION < 3 && !defined(PyObject_ASCII) + #define PyObject_ASCII(o) PyObject_Repr(o) +#endif +#if PY_MAJOR_VERSION >= 3 + #define PyBaseString_Type PyUnicode_Type + #define PyStringObject PyUnicodeObject + #define PyString_Type PyUnicode_Type + #define PyString_Check PyUnicode_Check + #define PyString_CheckExact PyUnicode_CheckExact +#ifndef PyObject_Unicode + #define PyObject_Unicode PyObject_Str +#endif +#endif +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) + #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) +#else + #define __Pyx_PyBaseString_Check(obj) (PyString_Check(obj) || PyUnicode_Check(obj)) + #define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj)) +#endif +#if CYTHON_COMPILING_IN_CPYTHON + #define __Pyx_PySequence_ListKeepNew(obj)\ + (likely(PyList_CheckExact(obj) && Py_REFCNT(obj) == 1) ? __Pyx_NewRef(obj) : PySequence_List(obj)) +#else + #define __Pyx_PySequence_ListKeepNew(obj) PySequence_List(obj) +#endif +#ifndef PySet_CheckExact + #define PySet_CheckExact(obj) __Pyx_IS_TYPE(obj, &PySet_Type) +#endif +#if PY_VERSION_HEX >= 0x030900A4 + #define __Pyx_SET_REFCNT(obj, refcnt) Py_SET_REFCNT(obj, refcnt) + #define __Pyx_SET_SIZE(obj, size) Py_SET_SIZE(obj, size) +#else + #define __Pyx_SET_REFCNT(obj, refcnt) Py_REFCNT(obj) = (refcnt) + #define __Pyx_SET_SIZE(obj, size) Py_SIZE(obj) = (size) +#endif +#if CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_PySequence_ITEM(o, i) PySequence_ITEM(o, i) + #define __Pyx_PySequence_SIZE(seq) Py_SIZE(seq) + #define __Pyx_PyTuple_SET_ITEM(o, i, v) (PyTuple_SET_ITEM(o, i, v), (0)) + #define __Pyx_PyList_SET_ITEM(o, i, v) (PyList_SET_ITEM(o, i, v), (0)) + #define __Pyx_PyTuple_GET_SIZE(o) PyTuple_GET_SIZE(o) + #define __Pyx_PyList_GET_SIZE(o) PyList_GET_SIZE(o) + #define __Pyx_PySet_GET_SIZE(o) PySet_GET_SIZE(o) + #define __Pyx_PyBytes_GET_SIZE(o) PyBytes_GET_SIZE(o) + #define __Pyx_PyByteArray_GET_SIZE(o) PyByteArray_GET_SIZE(o) +#else + #define __Pyx_PySequence_ITEM(o, i) PySequence_GetItem(o, i) + #define __Pyx_PySequence_SIZE(seq) PySequence_Size(seq) + #define __Pyx_PyTuple_SET_ITEM(o, i, v) PyTuple_SetItem(o, i, v) + #define __Pyx_PyList_SET_ITEM(o, i, v) PyList_SetItem(o, i, v) + #define __Pyx_PyTuple_GET_SIZE(o) PyTuple_Size(o) + #define __Pyx_PyList_GET_SIZE(o) PyList_Size(o) + #define __Pyx_PySet_GET_SIZE(o) PySet_Size(o) + #define __Pyx_PyBytes_GET_SIZE(o) PyBytes_Size(o) + #define __Pyx_PyByteArray_GET_SIZE(o) PyByteArray_Size(o) +#endif +#if PY_VERSION_HEX >= 0x030d00A1 + #define __Pyx_PyImport_AddModuleRef(name) PyImport_AddModuleRef(name) +#else + static CYTHON_INLINE PyObject *__Pyx_PyImport_AddModuleRef(const char *name) { + PyObject *module = PyImport_AddModule(name); + Py_XINCREF(module); + return module; + } +#endif +#if PY_MAJOR_VERSION >= 3 + #define PyIntObject PyLongObject + #define PyInt_Type PyLong_Type + #define PyInt_Check(op) PyLong_Check(op) + #define PyInt_CheckExact(op) PyLong_CheckExact(op) + #define __Pyx_Py3Int_Check(op) PyLong_Check(op) + #define __Pyx_Py3Int_CheckExact(op) PyLong_CheckExact(op) + #define PyInt_FromString PyLong_FromString + #define PyInt_FromUnicode PyLong_FromUnicode + #define PyInt_FromLong PyLong_FromLong + #define PyInt_FromSize_t PyLong_FromSize_t + #define PyInt_FromSsize_t PyLong_FromSsize_t + #define PyInt_AsLong PyLong_AsLong + #define PyInt_AS_LONG PyLong_AS_LONG + #define PyInt_AsSsize_t PyLong_AsSsize_t + #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask + #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask + #define PyNumber_Int PyNumber_Long +#else + #define __Pyx_Py3Int_Check(op) (PyLong_Check(op) || PyInt_Check(op)) + #define __Pyx_Py3Int_CheckExact(op) (PyLong_CheckExact(op) || PyInt_CheckExact(op)) +#endif +#if PY_MAJOR_VERSION >= 3 + #define PyBoolObject PyLongObject +#endif +#if PY_MAJOR_VERSION >= 3 && CYTHON_COMPILING_IN_PYPY + #ifndef PyUnicode_InternFromString + #define PyUnicode_InternFromString(s) PyUnicode_FromString(s) + #endif +#endif +#if PY_VERSION_HEX < 0x030200A4 + typedef long Py_hash_t; + #define __Pyx_PyInt_FromHash_t PyInt_FromLong + #define __Pyx_PyInt_AsHash_t __Pyx_PyIndex_AsHash_t +#else + #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t + #define __Pyx_PyInt_AsHash_t __Pyx_PyIndex_AsSsize_t +#endif +#if CYTHON_USE_ASYNC_SLOTS + #if PY_VERSION_HEX >= 0x030500B1 + #define __Pyx_PyAsyncMethodsStruct PyAsyncMethods + #define __Pyx_PyType_AsAsync(obj) (Py_TYPE(obj)->tp_as_async) + #else + #define __Pyx_PyType_AsAsync(obj) ((__Pyx_PyAsyncMethodsStruct*) (Py_TYPE(obj)->tp_reserved)) + #endif +#else + #define __Pyx_PyType_AsAsync(obj) NULL +#endif +#ifndef __Pyx_PyAsyncMethodsStruct + typedef struct { + unaryfunc am_await; + unaryfunc am_aiter; + unaryfunc am_anext; + } __Pyx_PyAsyncMethodsStruct; +#endif + +#if defined(_WIN32) || defined(WIN32) || defined(MS_WINDOWS) + #if !defined(_USE_MATH_DEFINES) + #define _USE_MATH_DEFINES + #endif +#endif +#include +#ifdef NAN +#define __PYX_NAN() ((float) NAN) +#else +static CYTHON_INLINE float __PYX_NAN() { + float value; + memset(&value, 0xFF, sizeof(value)); + return value; +} +#endif +#if defined(__CYGWIN__) && defined(_LDBL_EQ_DBL) +#define __Pyx_truncl trunc +#else +#define __Pyx_truncl truncl +#endif + +#define __PYX_MARK_ERR_POS(f_index, lineno) \ + { __pyx_filename = __pyx_f[f_index]; (void)__pyx_filename; __pyx_lineno = lineno; (void)__pyx_lineno; __pyx_clineno = __LINE__; (void)__pyx_clineno; } +#define __PYX_ERR(f_index, lineno, Ln_error) \ + { __PYX_MARK_ERR_POS(f_index, lineno) goto Ln_error; } + +#ifdef CYTHON_EXTERN_C + #undef __PYX_EXTERN_C + #define __PYX_EXTERN_C CYTHON_EXTERN_C +#elif defined(__PYX_EXTERN_C) + #ifdef _MSC_VER + #pragma message ("Please do not define the '__PYX_EXTERN_C' macro externally. Use 'CYTHON_EXTERN_C' instead.") + #else + #warning Please do not define the '__PYX_EXTERN_C' macro externally. Use 'CYTHON_EXTERN_C' instead. + #endif +#else + #define __PYX_EXTERN_C extern "C++" +#endif + +#define __PYX_HAVE__curated_tokenizers___bbpe +#define __PYX_HAVE_API__curated_tokenizers___bbpe +/* Early includes */ +#include +#include +#include "ios" +#include "new" +#include "stdexcept" +#include "typeinfo" +#include +#include + + #if __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1600) + // move should be defined for these versions of MSVC, but __cplusplus isn't set usefully + #include + + namespace cython_std { + template typename std::remove_reference::type&& move(T& t) noexcept { return std::move(t); } + template typename std::remove_reference::type&& move(T&& t) noexcept { return std::move(t); } + } + + #endif + +#include "merges.hh" +#include +#ifdef _OPENMP +#include +#endif /* _OPENMP */ + +#if defined(PYREX_WITHOUT_ASSERTIONS) && !defined(CYTHON_WITHOUT_ASSERTIONS) +#define CYTHON_WITHOUT_ASSERTIONS +#endif + +typedef struct {PyObject **p; const char *s; const Py_ssize_t n; const char* encoding; + const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; + +#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 +#define __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 0 +#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT (PY_MAJOR_VERSION >= 3 && __PYX_DEFAULT_STRING_ENCODING_IS_UTF8) +#define __PYX_DEFAULT_STRING_ENCODING "" +#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString +#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#define __Pyx_uchar_cast(c) ((unsigned char)c) +#define __Pyx_long_cast(x) ((long)x) +#define __Pyx_fits_Py_ssize_t(v, type, is_signed) (\ + (sizeof(type) < sizeof(Py_ssize_t)) ||\ + (sizeof(type) > sizeof(Py_ssize_t) &&\ + likely(v < (type)PY_SSIZE_T_MAX ||\ + v == (type)PY_SSIZE_T_MAX) &&\ + (!is_signed || likely(v > (type)PY_SSIZE_T_MIN ||\ + v == (type)PY_SSIZE_T_MIN))) ||\ + (sizeof(type) == sizeof(Py_ssize_t) &&\ + (is_signed || likely(v < (type)PY_SSIZE_T_MAX ||\ + v == (type)PY_SSIZE_T_MAX))) ) +static CYTHON_INLINE int __Pyx_is_valid_index(Py_ssize_t i, Py_ssize_t limit) { + return (size_t) i < (size_t) limit; +} +#if defined (__cplusplus) && __cplusplus >= 201103L + #include + #define __Pyx_sst_abs(value) std::abs(value) +#elif SIZEOF_INT >= SIZEOF_SIZE_T + #define __Pyx_sst_abs(value) abs(value) +#elif SIZEOF_LONG >= SIZEOF_SIZE_T + #define __Pyx_sst_abs(value) labs(value) +#elif defined (_MSC_VER) + #define __Pyx_sst_abs(value) ((Py_ssize_t)_abs64(value)) +#elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define __Pyx_sst_abs(value) llabs(value) +#elif defined (__GNUC__) + #define __Pyx_sst_abs(value) __builtin_llabs(value) +#else + #define __Pyx_sst_abs(value) ((value<0) ? -value : value) +#endif +static CYTHON_INLINE Py_ssize_t __Pyx_ssize_strlen(const char *s); +static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject*); +static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); +static CYTHON_INLINE PyObject* __Pyx_PyByteArray_FromString(const char*); +#define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) +#define __Pyx_PyBytes_FromString PyBytes_FromString +#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#else + #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize +#endif +#define __Pyx_PyBytes_AsWritableString(s) ((char*) PyBytes_AS_STRING(s)) +#define __Pyx_PyBytes_AsWritableSString(s) ((signed char*) PyBytes_AS_STRING(s)) +#define __Pyx_PyBytes_AsWritableUString(s) ((unsigned char*) PyBytes_AS_STRING(s)) +#define __Pyx_PyBytes_AsString(s) ((const char*) PyBytes_AS_STRING(s)) +#define __Pyx_PyBytes_AsSString(s) ((const signed char*) PyBytes_AS_STRING(s)) +#define __Pyx_PyBytes_AsUString(s) ((const unsigned char*) PyBytes_AS_STRING(s)) +#define __Pyx_PyObject_AsWritableString(s) ((char*)(__pyx_uintptr_t) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsWritableSString(s) ((signed char*)(__pyx_uintptr_t) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsWritableUString(s) ((unsigned char*)(__pyx_uintptr_t) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsSString(s) ((const signed char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsUString(s) ((const unsigned char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_FromCString(s) __Pyx_PyObject_FromString((const char*)s) +#define __Pyx_PyBytes_FromCString(s) __Pyx_PyBytes_FromString((const char*)s) +#define __Pyx_PyByteArray_FromCString(s) __Pyx_PyByteArray_FromString((const char*)s) +#define __Pyx_PyStr_FromCString(s) __Pyx_PyStr_FromString((const char*)s) +#define __Pyx_PyUnicode_FromCString(s) __Pyx_PyUnicode_FromString((const char*)s) +#if CYTHON_COMPILING_IN_LIMITED_API +static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const wchar_t *u) +{ + const wchar_t *u_end = u; + while (*u_end++) ; + return (size_t)(u_end - u - 1); +} +#else +static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) +{ + const Py_UNICODE *u_end = u; + while (*u_end++) ; + return (size_t)(u_end - u - 1); +} +#endif +#define __Pyx_PyUnicode_FromOrdinal(o) PyUnicode_FromOrdinal((int)o) +#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) +#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode +#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode +#define __Pyx_NewRef(obj) (Py_INCREF(obj), obj) +#define __Pyx_Owned_Py_None(b) __Pyx_NewRef(Py_None) +static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b); +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); +static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject*); +static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x); +#define __Pyx_PySequence_Tuple(obj)\ + (likely(PyTuple_CheckExact(obj)) ? __Pyx_NewRef(obj) : PySequence_Tuple(obj)) +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); +static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); +static CYTHON_INLINE Py_hash_t __Pyx_PyIndex_AsHash_t(PyObject*); +#if CYTHON_ASSUME_SAFE_MACROS +#define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) +#else +#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) +#endif +#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) +#if PY_MAJOR_VERSION >= 3 +#define __Pyx_PyNumber_Int(x) (PyLong_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Long(x)) +#else +#define __Pyx_PyNumber_Int(x) (PyInt_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Int(x)) +#endif +#if CYTHON_USE_PYLONG_INTERNALS + #if PY_VERSION_HEX >= 0x030C00A7 + #ifndef _PyLong_SIGN_MASK + #define _PyLong_SIGN_MASK 3 + #endif + #ifndef _PyLong_NON_SIZE_BITS + #define _PyLong_NON_SIZE_BITS 3 + #endif + #define __Pyx_PyLong_Sign(x) (((PyLongObject*)x)->long_value.lv_tag & _PyLong_SIGN_MASK) + #define __Pyx_PyLong_IsNeg(x) ((__Pyx_PyLong_Sign(x) & 2) != 0) + #define __Pyx_PyLong_IsNonNeg(x) (!__Pyx_PyLong_IsNeg(x)) + #define __Pyx_PyLong_IsZero(x) (__Pyx_PyLong_Sign(x) & 1) + #define __Pyx_PyLong_IsPos(x) (__Pyx_PyLong_Sign(x) == 0) + #define __Pyx_PyLong_CompactValueUnsigned(x) (__Pyx_PyLong_Digits(x)[0]) + #define __Pyx_PyLong_DigitCount(x) ((Py_ssize_t) (((PyLongObject*)x)->long_value.lv_tag >> _PyLong_NON_SIZE_BITS)) + #define __Pyx_PyLong_SignedDigitCount(x)\ + ((1 - (Py_ssize_t) __Pyx_PyLong_Sign(x)) * __Pyx_PyLong_DigitCount(x)) + #if defined(PyUnstable_Long_IsCompact) && defined(PyUnstable_Long_CompactValue) + #define __Pyx_PyLong_IsCompact(x) PyUnstable_Long_IsCompact((PyLongObject*) x) + #define __Pyx_PyLong_CompactValue(x) PyUnstable_Long_CompactValue((PyLongObject*) x) + #else + #define __Pyx_PyLong_IsCompact(x) (((PyLongObject*)x)->long_value.lv_tag < (2 << _PyLong_NON_SIZE_BITS)) + #define __Pyx_PyLong_CompactValue(x) ((1 - (Py_ssize_t) __Pyx_PyLong_Sign(x)) * (Py_ssize_t) __Pyx_PyLong_Digits(x)[0]) + #endif + typedef Py_ssize_t __Pyx_compact_pylong; + typedef size_t __Pyx_compact_upylong; + #else + #define __Pyx_PyLong_IsNeg(x) (Py_SIZE(x) < 0) + #define __Pyx_PyLong_IsNonNeg(x) (Py_SIZE(x) >= 0) + #define __Pyx_PyLong_IsZero(x) (Py_SIZE(x) == 0) + #define __Pyx_PyLong_IsPos(x) (Py_SIZE(x) > 0) + #define __Pyx_PyLong_CompactValueUnsigned(x) ((Py_SIZE(x) == 0) ? 0 : __Pyx_PyLong_Digits(x)[0]) + #define __Pyx_PyLong_DigitCount(x) __Pyx_sst_abs(Py_SIZE(x)) + #define __Pyx_PyLong_SignedDigitCount(x) Py_SIZE(x) + #define __Pyx_PyLong_IsCompact(x) (Py_SIZE(x) == 0 || Py_SIZE(x) == 1 || Py_SIZE(x) == -1) + #define __Pyx_PyLong_CompactValue(x)\ + ((Py_SIZE(x) == 0) ? (sdigit) 0 : ((Py_SIZE(x) < 0) ? -(sdigit)__Pyx_PyLong_Digits(x)[0] : (sdigit)__Pyx_PyLong_Digits(x)[0])) + typedef sdigit __Pyx_compact_pylong; + typedef digit __Pyx_compact_upylong; + #endif + #if PY_VERSION_HEX >= 0x030C00A5 + #define __Pyx_PyLong_Digits(x) (((PyLongObject*)x)->long_value.ob_digit) + #else + #define __Pyx_PyLong_Digits(x) (((PyLongObject*)x)->ob_digit) + #endif +#endif +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII +#include +static int __Pyx_sys_getdefaultencoding_not_ascii; +static int __Pyx_init_sys_getdefaultencoding_params(void) { + PyObject* sys; + PyObject* default_encoding = NULL; + PyObject* ascii_chars_u = NULL; + PyObject* ascii_chars_b = NULL; + const char* default_encoding_c; + sys = PyImport_ImportModule("sys"); + if (!sys) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) "getdefaultencoding", NULL); + Py_DECREF(sys); + if (!default_encoding) goto bad; + default_encoding_c = PyBytes_AsString(default_encoding); + if (!default_encoding_c) goto bad; + if (strcmp(default_encoding_c, "ascii") == 0) { + __Pyx_sys_getdefaultencoding_not_ascii = 0; + } else { + char ascii_chars[128]; + int c; + for (c = 0; c < 128; c++) { + ascii_chars[c] = (char) c; + } + __Pyx_sys_getdefaultencoding_not_ascii = 1; + ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); + if (!ascii_chars_u) goto bad; + ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); + if (!ascii_chars_b || !PyBytes_Check(ascii_chars_b) || memcmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { + PyErr_Format( + PyExc_ValueError, + "This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.", + default_encoding_c); + goto bad; + } + Py_DECREF(ascii_chars_u); + Py_DECREF(ascii_chars_b); + } + Py_DECREF(default_encoding); + return 0; +bad: + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return -1; +} +#endif +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) +#else +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT +#include +static char* __PYX_DEFAULT_STRING_ENCODING; +static int __Pyx_init_sys_getdefaultencoding_params(void) { + PyObject* sys; + PyObject* default_encoding = NULL; + char* default_encoding_c; + sys = PyImport_ImportModule("sys"); + if (!sys) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + Py_DECREF(sys); + if (!default_encoding) goto bad; + default_encoding_c = PyBytes_AsString(default_encoding); + if (!default_encoding_c) goto bad; + __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c) + 1); + if (!__PYX_DEFAULT_STRING_ENCODING) goto bad; + strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); + Py_DECREF(default_encoding); + return 0; +bad: + Py_XDECREF(default_encoding); + return -1; +} +#endif +#endif + + +/* Test for GCC > 2.95 */ +#if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))) + #define likely(x) __builtin_expect(!!(x), 1) + #define unlikely(x) __builtin_expect(!!(x), 0) +#else /* !__GNUC__ or GCC < 2.95 */ + #define likely(x) (x) + #define unlikely(x) (x) +#endif /* __GNUC__ */ +static CYTHON_INLINE void __Pyx_pretend_to_initialize(void* ptr) { (void)ptr; } + +#if !CYTHON_USE_MODULE_STATE +static PyObject *__pyx_m = NULL; +#endif +static int __pyx_lineno; +static int __pyx_clineno = 0; +static const char * __pyx_cfilenm = __FILE__; +static const char *__pyx_filename; + +/* #### Code section: filename_table ### */ + +static const char *__pyx_f[] = { + "curated_tokenizers\\\\_bbpe.pyx", + "", +}; +/* #### Code section: utility_code_proto_before_types ### */ +/* ForceInitThreads.proto */ +#ifndef __PYX_FORCE_INIT_THREADS + #define __PYX_FORCE_INIT_THREADS 0 +#endif + +/* #### Code section: numeric_typedefs ### */ +/* #### Code section: complex_type_declarations ### */ +/* #### Code section: type_declarations ### */ + +/*--- Type declarations ---*/ +struct __pyx_obj_18curated_tokenizers_5_bbpe_ByteBPEProcessor; +struct __pyx_obj_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr; + +/* "curated_tokenizers/_bbpe.pyx":50 + * return dict(zip(bs, cs)) + * + * cdef class ByteBPEProcessor: # <<<<<<<<<<<<<< + * cdef shared_ptr[Merges] _merges + * cdef dict _byte_decoder + */ +struct __pyx_obj_18curated_tokenizers_5_bbpe_ByteBPEProcessor { + PyObject_HEAD + std::shared_ptr _merges; + PyObject *_byte_decoder; + PyObject *_byte_encoder; + PyObject *_split_pattern; + PyObject *_piece_to_id; + PyObject *_id_to_piece; +}; + + +/* "curated_tokenizers/_bbpe.pyx":141 + * token_bytes = [self._byte_encoder[b] for b in token.encode("utf-8")] + * merged = deref(self._merges).apply_merges(token_bytes) + * pieces.extend(merge.decode("utf-8") for merge in merged) # <<<<<<<<<<<<<< + * return pieces + * + */ +struct __pyx_obj_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr { + PyObject_HEAD + std::vector __pyx_genexpr_arg_0; + std::string __pyx_v_merge; + std::vector ::iterator __pyx_t_0; +}; + +/* #### Code section: utility_code_proto ### */ + +/* --- Runtime support code (head) --- */ +/* Refnanny.proto */ +#ifndef CYTHON_REFNANNY + #define CYTHON_REFNANNY 0 +#endif +#if CYTHON_REFNANNY + typedef struct { + void (*INCREF)(void*, PyObject*, Py_ssize_t); + void (*DECREF)(void*, PyObject*, Py_ssize_t); + void (*GOTREF)(void*, PyObject*, Py_ssize_t); + void (*GIVEREF)(void*, PyObject*, Py_ssize_t); + void* (*SetupContext)(const char*, Py_ssize_t, const char*); + void (*FinishContext)(void**); + } __Pyx_RefNannyAPIStruct; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); + #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; +#ifdef WITH_THREAD + #define __Pyx_RefNannySetupContext(name, acquire_gil)\ + if (acquire_gil) {\ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), (__LINE__), (__FILE__));\ + PyGILState_Release(__pyx_gilstate_save);\ + } else {\ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), (__LINE__), (__FILE__));\ + } + #define __Pyx_RefNannyFinishContextNogil() {\ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ + __Pyx_RefNannyFinishContext();\ + PyGILState_Release(__pyx_gilstate_save);\ + } +#else + #define __Pyx_RefNannySetupContext(name, acquire_gil)\ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), (__LINE__), (__FILE__)) + #define __Pyx_RefNannyFinishContextNogil() __Pyx_RefNannyFinishContext() +#endif + #define __Pyx_RefNannyFinishContextNogil() {\ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ + __Pyx_RefNannyFinishContext();\ + PyGILState_Release(__pyx_gilstate_save);\ + } + #define __Pyx_RefNannyFinishContext()\ + __Pyx_RefNanny->FinishContext(&__pyx_refnanny) + #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) + #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) + #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) + #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) + #define __Pyx_XINCREF(r) do { if((r) == NULL); else {__Pyx_INCREF(r); }} while(0) + #define __Pyx_XDECREF(r) do { if((r) == NULL); else {__Pyx_DECREF(r); }} while(0) + #define __Pyx_XGOTREF(r) do { if((r) == NULL); else {__Pyx_GOTREF(r); }} while(0) + #define __Pyx_XGIVEREF(r) do { if((r) == NULL); else {__Pyx_GIVEREF(r);}} while(0) +#else + #define __Pyx_RefNannyDeclarations + #define __Pyx_RefNannySetupContext(name, acquire_gil) + #define __Pyx_RefNannyFinishContextNogil() + #define __Pyx_RefNannyFinishContext() + #define __Pyx_INCREF(r) Py_INCREF(r) + #define __Pyx_DECREF(r) Py_DECREF(r) + #define __Pyx_GOTREF(r) + #define __Pyx_GIVEREF(r) + #define __Pyx_XINCREF(r) Py_XINCREF(r) + #define __Pyx_XDECREF(r) Py_XDECREF(r) + #define __Pyx_XGOTREF(r) + #define __Pyx_XGIVEREF(r) +#endif +#define __Pyx_Py_XDECREF_SET(r, v) do {\ + PyObject *tmp = (PyObject *) r;\ + r = v; Py_XDECREF(tmp);\ + } while (0) +#define __Pyx_XDECREF_SET(r, v) do {\ + PyObject *tmp = (PyObject *) r;\ + r = v; __Pyx_XDECREF(tmp);\ + } while (0) +#define __Pyx_DECREF_SET(r, v) do {\ + PyObject *tmp = (PyObject *) r;\ + r = v; __Pyx_DECREF(tmp);\ + } while (0) +#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) +#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) + +/* PyErrExceptionMatches.proto */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_PyErr_ExceptionMatches(err) __Pyx_PyErr_ExceptionMatchesInState(__pyx_tstate, err) +static CYTHON_INLINE int __Pyx_PyErr_ExceptionMatchesInState(PyThreadState* tstate, PyObject* err); +#else +#define __Pyx_PyErr_ExceptionMatches(err) PyErr_ExceptionMatches(err) +#endif + +/* PyThreadStateGet.proto */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_PyThreadState_declare PyThreadState *__pyx_tstate; +#define __Pyx_PyThreadState_assign __pyx_tstate = __Pyx_PyThreadState_Current; +#if PY_VERSION_HEX >= 0x030C00A6 +#define __Pyx_PyErr_Occurred() (__pyx_tstate->current_exception != NULL) +#define __Pyx_PyErr_CurrentExceptionType() (__pyx_tstate->current_exception ? (PyObject*) Py_TYPE(__pyx_tstate->current_exception) : (PyObject*) NULL) +#else +#define __Pyx_PyErr_Occurred() (__pyx_tstate->curexc_type != NULL) +#define __Pyx_PyErr_CurrentExceptionType() (__pyx_tstate->curexc_type) +#endif +#else +#define __Pyx_PyThreadState_declare +#define __Pyx_PyThreadState_assign +#define __Pyx_PyErr_Occurred() (PyErr_Occurred() != NULL) +#define __Pyx_PyErr_CurrentExceptionType() PyErr_Occurred() +#endif + +/* PyErrFetchRestore.proto */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_PyErr_Clear() __Pyx_ErrRestore(NULL, NULL, NULL) +#define __Pyx_ErrRestoreWithState(type, value, tb) __Pyx_ErrRestoreInState(PyThreadState_GET(), type, value, tb) +#define __Pyx_ErrFetchWithState(type, value, tb) __Pyx_ErrFetchInState(PyThreadState_GET(), type, value, tb) +#define __Pyx_ErrRestore(type, value, tb) __Pyx_ErrRestoreInState(__pyx_tstate, type, value, tb) +#define __Pyx_ErrFetch(type, value, tb) __Pyx_ErrFetchInState(__pyx_tstate, type, value, tb) +static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); +static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A6 +#define __Pyx_PyErr_SetNone(exc) (Py_INCREF(exc), __Pyx_ErrRestore((exc), NULL, NULL)) +#else +#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) +#endif +#else +#define __Pyx_PyErr_Clear() PyErr_Clear() +#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) +#define __Pyx_ErrRestoreWithState(type, value, tb) PyErr_Restore(type, value, tb) +#define __Pyx_ErrFetchWithState(type, value, tb) PyErr_Fetch(type, value, tb) +#define __Pyx_ErrRestoreInState(tstate, type, value, tb) PyErr_Restore(type, value, tb) +#define __Pyx_ErrFetchInState(tstate, type, value, tb) PyErr_Fetch(type, value, tb) +#define __Pyx_ErrRestore(type, value, tb) PyErr_Restore(type, value, tb) +#define __Pyx_ErrFetch(type, value, tb) PyErr_Fetch(type, value, tb) +#endif + +/* PyObjectGetAttrStr.proto */ +#if CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name); +#else +#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) +#endif + +/* PyObjectGetAttrStrNoError.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStrNoError(PyObject* obj, PyObject* attr_name); + +/* GetBuiltinName.proto */ +static PyObject *__Pyx_GetBuiltinName(PyObject *name); + +/* TupleAndListFromArray.proto */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyList_FromArray(PyObject *const *src, Py_ssize_t n); +static CYTHON_INLINE PyObject* __Pyx_PyTuple_FromArray(PyObject *const *src, Py_ssize_t n); +#endif + +/* IncludeStringH.proto */ +#include + +/* BytesEquals.proto */ +static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals); + +/* UnicodeEquals.proto */ +static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); + +/* fastcall.proto */ +#if CYTHON_AVOID_BORROWED_REFS + #define __Pyx_Arg_VARARGS(args, i) PySequence_GetItem(args, i) +#elif CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_Arg_VARARGS(args, i) PyTuple_GET_ITEM(args, i) +#else + #define __Pyx_Arg_VARARGS(args, i) PyTuple_GetItem(args, i) +#endif +#if CYTHON_AVOID_BORROWED_REFS + #define __Pyx_Arg_NewRef_VARARGS(arg) __Pyx_NewRef(arg) + #define __Pyx_Arg_XDECREF_VARARGS(arg) Py_XDECREF(arg) +#else + #define __Pyx_Arg_NewRef_VARARGS(arg) arg + #define __Pyx_Arg_XDECREF_VARARGS(arg) +#endif +#define __Pyx_NumKwargs_VARARGS(kwds) PyDict_Size(kwds) +#define __Pyx_KwValues_VARARGS(args, nargs) NULL +#define __Pyx_GetKwValue_VARARGS(kw, kwvalues, s) __Pyx_PyDict_GetItemStrWithError(kw, s) +#define __Pyx_KwargsAsDict_VARARGS(kw, kwvalues) PyDict_Copy(kw) +#if CYTHON_METH_FASTCALL + #define __Pyx_Arg_FASTCALL(args, i) args[i] + #define __Pyx_NumKwargs_FASTCALL(kwds) PyTuple_GET_SIZE(kwds) + #define __Pyx_KwValues_FASTCALL(args, nargs) ((args) + (nargs)) + static CYTHON_INLINE PyObject * __Pyx_GetKwValue_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues, PyObject *s); +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030d0000 + CYTHON_UNUSED static PyObject *__Pyx_KwargsAsDict_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues); + #else + #define __Pyx_KwargsAsDict_FASTCALL(kw, kwvalues) _PyStack_AsDict(kwvalues, kw) + #endif + #define __Pyx_Arg_NewRef_FASTCALL(arg) arg /* no-op, __Pyx_Arg_FASTCALL is direct and this needs + to have the same reference counting */ + #define __Pyx_Arg_XDECREF_FASTCALL(arg) +#else + #define __Pyx_Arg_FASTCALL __Pyx_Arg_VARARGS + #define __Pyx_NumKwargs_FASTCALL __Pyx_NumKwargs_VARARGS + #define __Pyx_KwValues_FASTCALL __Pyx_KwValues_VARARGS + #define __Pyx_GetKwValue_FASTCALL __Pyx_GetKwValue_VARARGS + #define __Pyx_KwargsAsDict_FASTCALL __Pyx_KwargsAsDict_VARARGS + #define __Pyx_Arg_NewRef_FASTCALL(arg) __Pyx_Arg_NewRef_VARARGS(arg) + #define __Pyx_Arg_XDECREF_FASTCALL(arg) __Pyx_Arg_XDECREF_VARARGS(arg) +#endif +#if CYTHON_COMPILING_IN_CPYTHON && CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS +#define __Pyx_ArgsSlice_VARARGS(args, start, stop) __Pyx_PyTuple_FromArray(&__Pyx_Arg_VARARGS(args, start), stop - start) +#define __Pyx_ArgsSlice_FASTCALL(args, start, stop) __Pyx_PyTuple_FromArray(&__Pyx_Arg_FASTCALL(args, start), stop - start) +#else +#define __Pyx_ArgsSlice_VARARGS(args, start, stop) PyTuple_GetSlice(args, start, stop) +#define __Pyx_ArgsSlice_FASTCALL(args, start, stop) PyTuple_GetSlice(args, start, stop) +#endif + +/* PyObjectCall.proto */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); +#else +#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) +#endif + +/* SliceTupleAndList.proto */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyList_GetSlice(PyObject* src, Py_ssize_t start, Py_ssize_t stop); +static CYTHON_INLINE PyObject* __Pyx_PyTuple_GetSlice(PyObject* src, Py_ssize_t start, Py_ssize_t stop); +#else +#define __Pyx_PyList_GetSlice(seq, start, stop) PySequence_GetSlice(seq, start, stop) +#define __Pyx_PyTuple_GetSlice(seq, start, stop) PySequence_GetSlice(seq, start, stop) +#endif + +/* PySequenceContains.proto */ +static CYTHON_INLINE int __Pyx_PySequence_ContainsTF(PyObject* item, PyObject* seq, int eq) { + int result = PySequence_Contains(seq, item); + return unlikely(result < 0) ? result : (result == (eq == Py_EQ)); +} + +/* ListAppend.proto */ +#if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS +static CYTHON_INLINE int __Pyx_PyList_Append(PyObject* list, PyObject* x) { + PyListObject* L = (PyListObject*) list; + Py_ssize_t len = Py_SIZE(list); + if (likely(L->allocated > len) & likely(len > (L->allocated >> 1))) { + Py_INCREF(x); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030d0000 + L->ob_item[len] = x; + #else + PyList_SET_ITEM(list, len, x); + #endif + __Pyx_SET_SIZE(list, len + 1); + return 0; + } + return PyList_Append(list, x); +} +#else +#define __Pyx_PyList_Append(L,x) PyList_Append(L,x) +#endif + +/* PyIntBinop.proto */ +#if !CYTHON_COMPILING_IN_PYPY +static PyObject* __Pyx_PyInt_AddCObj(PyObject *op1, PyObject *op2, long intval, int inplace, int zerodivision_check); +#else +#define __Pyx_PyInt_AddCObj(op1, op2, intval, inplace, zerodivision_check)\ + (inplace ? PyNumber_InPlaceAdd(op1, op2) : PyNumber_Add(op1, op2)) +#endif + +/* PyIntBinop.proto */ +#if !CYTHON_COMPILING_IN_PYPY +static PyObject* __Pyx_PyInt_AddObjC(PyObject *op1, PyObject *op2, long intval, int inplace, int zerodivision_check); +#else +#define __Pyx_PyInt_AddObjC(op1, op2, intval, inplace, zerodivision_check)\ + (inplace ? PyNumber_InPlaceAdd(op1, op2) : PyNumber_Add(op1, op2)) +#endif + +/* ListCompAppend.proto */ +#if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS +static CYTHON_INLINE int __Pyx_ListComp_Append(PyObject* list, PyObject* x) { + PyListObject* L = (PyListObject*) list; + Py_ssize_t len = Py_SIZE(list); + if (likely(L->allocated > len)) { + Py_INCREF(x); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030d0000 + L->ob_item[len] = x; + #else + PyList_SET_ITEM(list, len, x); + #endif + __Pyx_SET_SIZE(list, len + 1); + return 0; + } + return PyList_Append(list, x); +} +#else +#define __Pyx_ListComp_Append(L,x) PyList_Append(L,x) +#endif + +/* PyFunctionFastCall.proto */ +#if CYTHON_FAST_PYCALL +#if !CYTHON_VECTORCALL +#define __Pyx_PyFunction_FastCall(func, args, nargs)\ + __Pyx_PyFunction_FastCallDict((func), (args), (nargs), NULL) +static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, Py_ssize_t nargs, PyObject *kwargs); +#endif +#define __Pyx_BUILD_ASSERT_EXPR(cond)\ + (sizeof(char [1 - 2*!(cond)]) - 1) +#ifndef Py_MEMBER_SIZE +#define Py_MEMBER_SIZE(type, member) sizeof(((type *)0)->member) +#endif +#if !CYTHON_VECTORCALL +#if PY_VERSION_HEX >= 0x03080000 + #include "frameobject.h" +#if PY_VERSION_HEX >= 0x030b00a6 && !CYTHON_COMPILING_IN_LIMITED_API + #ifndef Py_BUILD_CORE + #define Py_BUILD_CORE 1 + #endif + #include "internal/pycore_frame.h" +#endif + #define __Pxy_PyFrame_Initialize_Offsets() + #define __Pyx_PyFrame_GetLocalsplus(frame) ((frame)->f_localsplus) +#else + static size_t __pyx_pyframe_localsplus_offset = 0; + #include "frameobject.h" + #define __Pxy_PyFrame_Initialize_Offsets()\ + ((void)__Pyx_BUILD_ASSERT_EXPR(sizeof(PyFrameObject) == offsetof(PyFrameObject, f_localsplus) + Py_MEMBER_SIZE(PyFrameObject, f_localsplus)),\ + (void)(__pyx_pyframe_localsplus_offset = ((size_t)PyFrame_Type.tp_basicsize) - Py_MEMBER_SIZE(PyFrameObject, f_localsplus))) + #define __Pyx_PyFrame_GetLocalsplus(frame)\ + (assert(__pyx_pyframe_localsplus_offset), (PyObject **)(((char *)(frame)) + __pyx_pyframe_localsplus_offset)) +#endif +#endif +#endif + +/* PyObjectCallMethO.proto */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg); +#endif + +/* PyObjectFastCall.proto */ +#define __Pyx_PyObject_FastCall(func, args, nargs) __Pyx_PyObject_FastCallDict(func, args, (size_t)(nargs), NULL) +static CYTHON_INLINE PyObject* __Pyx_PyObject_FastCallDict(PyObject *func, PyObject **args, size_t nargs, PyObject *kwargs); + +/* PyObjectCallOneArg.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg); + +/* RaiseArgTupleInvalid.proto */ +static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, + Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); + +/* RaiseDoubleKeywords.proto */ +static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); + +/* ParseKeywords.proto */ +static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject *const *kwvalues, + PyObject **argnames[], + PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, + const char* function_name); + +/* PyDictVersioning.proto */ +#if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS +#define __PYX_DICT_VERSION_INIT ((PY_UINT64_T) -1) +#define __PYX_GET_DICT_VERSION(dict) (((PyDictObject*)(dict))->ma_version_tag) +#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var)\ + (version_var) = __PYX_GET_DICT_VERSION(dict);\ + (cache_var) = (value); +#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) {\ + static PY_UINT64_T __pyx_dict_version = 0;\ + static PyObject *__pyx_dict_cached_value = NULL;\ + if (likely(__PYX_GET_DICT_VERSION(DICT) == __pyx_dict_version)) {\ + (VAR) = __pyx_dict_cached_value;\ + } else {\ + (VAR) = __pyx_dict_cached_value = (LOOKUP);\ + __pyx_dict_version = __PYX_GET_DICT_VERSION(DICT);\ + }\ +} +static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj); +static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj); +static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version); +#else +#define __PYX_GET_DICT_VERSION(dict) (0) +#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var) +#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) (VAR) = (LOOKUP); +#endif + +/* GetModuleGlobalName.proto */ +#if CYTHON_USE_DICT_VERSIONS +#define __Pyx_GetModuleGlobalName(var, name) do {\ + static PY_UINT64_T __pyx_dict_version = 0;\ + static PyObject *__pyx_dict_cached_value = NULL;\ + (var) = (likely(__pyx_dict_version == __PYX_GET_DICT_VERSION(__pyx_d))) ?\ + (likely(__pyx_dict_cached_value) ? __Pyx_NewRef(__pyx_dict_cached_value) : __Pyx_GetBuiltinName(name)) :\ + __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ +} while(0) +#define __Pyx_GetModuleGlobalNameUncached(var, name) do {\ + PY_UINT64_T __pyx_dict_version;\ + PyObject *__pyx_dict_cached_value;\ + (var) = __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ +} while(0) +static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value); +#else +#define __Pyx_GetModuleGlobalName(var, name) (var) = __Pyx__GetModuleGlobalName(name) +#define __Pyx_GetModuleGlobalNameUncached(var, name) (var) = __Pyx__GetModuleGlobalName(name) +static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name); +#endif + +/* RaiseUnexpectedTypeError.proto */ +static int __Pyx_RaiseUnexpectedTypeError(const char *expected, PyObject *obj); + +/* py_dict_items.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyDict_Items(PyObject* d); + +/* UnpackUnboundCMethod.proto */ +typedef struct { + PyObject *type; + PyObject **method_name; + PyCFunction func; + PyObject *method; + int flag; +} __Pyx_CachedCFunction; + +/* CallUnboundCMethod0.proto */ +static PyObject* __Pyx__CallUnboundCMethod0(__Pyx_CachedCFunction* cfunc, PyObject* self); +#if CYTHON_COMPILING_IN_CPYTHON +#define __Pyx_CallUnboundCMethod0(cfunc, self)\ + (likely((cfunc)->func) ?\ + (likely((cfunc)->flag == METH_NOARGS) ? (*((cfunc)->func))(self, NULL) :\ + (PY_VERSION_HEX >= 0x030600B1 && likely((cfunc)->flag == METH_FASTCALL) ?\ + (PY_VERSION_HEX >= 0x030700A0 ?\ + (*(__Pyx_PyCFunctionFast)(void*)(PyCFunction)(cfunc)->func)(self, &__pyx_empty_tuple, 0) :\ + (*(__Pyx_PyCFunctionFastWithKeywords)(void*)(PyCFunction)(cfunc)->func)(self, &__pyx_empty_tuple, 0, NULL)) :\ + (PY_VERSION_HEX >= 0x030700A0 && (cfunc)->flag == (METH_FASTCALL | METH_KEYWORDS) ?\ + (*(__Pyx_PyCFunctionFastWithKeywords)(void*)(PyCFunction)(cfunc)->func)(self, &__pyx_empty_tuple, 0, NULL) :\ + (likely((cfunc)->flag == (METH_VARARGS | METH_KEYWORDS)) ? ((*(PyCFunctionWithKeywords)(void*)(PyCFunction)(cfunc)->func)(self, __pyx_empty_tuple, NULL)) :\ + ((cfunc)->flag == METH_VARARGS ? (*((cfunc)->func))(self, __pyx_empty_tuple) :\ + __Pyx__CallUnboundCMethod0(cfunc, self)))))) :\ + __Pyx__CallUnboundCMethod0(cfunc, self)) +#else +#define __Pyx_CallUnboundCMethod0(cfunc, self) __Pyx__CallUnboundCMethod0(cfunc, self) +#endif + +/* RaiseTooManyValuesToUnpack.proto */ +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); + +/* RaiseNeedMoreValuesToUnpack.proto */ +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); + +/* IterFinish.proto */ +static CYTHON_INLINE int __Pyx_IterFinish(void); + +/* UnpackItemEndCheck.proto */ +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected); + +/* MoveIfSupported.proto */ +#if CYTHON_USE_CPP_STD_MOVE + #include + #define __PYX_STD_MOVE_IF_SUPPORTED(x) std::move(x) +#else + #define __PYX_STD_MOVE_IF_SUPPORTED(x) x +#endif + +/* KeywordStringCheck.proto */ +static int __Pyx_CheckKeywordStrings(PyObject *kw, const char* function_name, int kw_allowed); + +/* RaiseKeywordRequired.proto */ +static void __Pyx_RaiseKeywordRequired(const char* func_name, PyObject* kw_name); + +/* PyObjectLookupSpecial.proto */ +#if CYTHON_USE_PYTYPE_LOOKUP && CYTHON_USE_TYPE_SLOTS +#define __Pyx_PyObject_LookupSpecialNoError(obj, attr_name) __Pyx__PyObject_LookupSpecial(obj, attr_name, 0) +#define __Pyx_PyObject_LookupSpecial(obj, attr_name) __Pyx__PyObject_LookupSpecial(obj, attr_name, 1) +static CYTHON_INLINE PyObject* __Pyx__PyObject_LookupSpecial(PyObject* obj, PyObject* attr_name, int with_error); +#else +#define __Pyx_PyObject_LookupSpecialNoError(o,n) __Pyx_PyObject_GetAttrStrNoError(o,n) +#define __Pyx_PyObject_LookupSpecial(o,n) __Pyx_PyObject_GetAttrStr(o,n) +#endif + +/* GetTopmostException.proto */ +#if CYTHON_USE_EXC_INFO_STACK && CYTHON_FAST_THREAD_STATE +static _PyErr_StackItem * __Pyx_PyErr_GetTopmostException(PyThreadState *tstate); +#endif + +/* SaveResetException.proto */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_ExceptionSave(type, value, tb) __Pyx__ExceptionSave(__pyx_tstate, type, value, tb) +static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); +#define __Pyx_ExceptionReset(type, value, tb) __Pyx__ExceptionReset(__pyx_tstate, type, value, tb) +static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); +#else +#define __Pyx_ExceptionSave(type, value, tb) PyErr_GetExcInfo(type, value, tb) +#define __Pyx_ExceptionReset(type, value, tb) PyErr_SetExcInfo(type, value, tb) +#endif + +/* GetException.proto */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_GetException(type, value, tb) __Pyx__GetException(__pyx_tstate, type, value, tb) +static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); +#else +static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); +#endif + +/* PyObjectFormatSimple.proto */ +#if CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyObject_FormatSimple(s, f) (\ + likely(PyUnicode_CheckExact(s)) ? (Py_INCREF(s), s) :\ + PyObject_Format(s, f)) +#elif PY_MAJOR_VERSION < 3 + #define __Pyx_PyObject_FormatSimple(s, f) (\ + likely(PyUnicode_CheckExact(s)) ? (Py_INCREF(s), s) :\ + likely(PyString_CheckExact(s)) ? PyUnicode_FromEncodedObject(s, NULL, "strict") :\ + PyObject_Format(s, f)) +#elif CYTHON_USE_TYPE_SLOTS + #define __Pyx_PyObject_FormatSimple(s, f) (\ + likely(PyUnicode_CheckExact(s)) ? (Py_INCREF(s), s) :\ + likely(PyLong_CheckExact(s)) ? PyLong_Type.tp_repr(s) :\ + likely(PyFloat_CheckExact(s)) ? PyFloat_Type.tp_repr(s) :\ + PyObject_Format(s, f)) +#else + #define __Pyx_PyObject_FormatSimple(s, f) (\ + likely(PyUnicode_CheckExact(s)) ? (Py_INCREF(s), s) :\ + PyObject_Format(s, f)) +#endif + +/* RaiseException.proto */ +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); + +/* GCCDiagnostics.proto */ +#if !defined(__INTEL_COMPILER) && defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) +#define __Pyx_HAS_GCC_DIAGNOSTIC +#endif + +/* BuildPyUnicode.proto */ +static PyObject* __Pyx_PyUnicode_BuildFromAscii(Py_ssize_t ulength, char* chars, int clength, + int prepend_sign, char padding_char); + +/* CIntToPyUnicode.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_From_Py_ssize_t(Py_ssize_t value, Py_ssize_t width, char padding_char, char format_char); + +/* JoinPyUnicode.proto */ +static PyObject* __Pyx_PyUnicode_Join(PyObject* value_tuple, Py_ssize_t value_count, Py_ssize_t result_ulength, + Py_UCS4 max_char); + +/* PyObjectCall2Args.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2); + +/* PyObjectGetMethod.proto */ +static int __Pyx_PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method); + +/* PyObjectCallMethod1.proto */ +static PyObject* __Pyx_PyObject_CallMethod1(PyObject* obj, PyObject* method_name, PyObject* arg); + +/* append.proto */ +static CYTHON_INLINE int __Pyx_PyObject_Append(PyObject* L, PyObject* x); + +/* dict_getitem_default.proto */ +static PyObject* __Pyx_PyDict_GetItemDefault(PyObject* d, PyObject* key, PyObject* default_value); + +/* CallUnboundCMethod1.proto */ +static PyObject* __Pyx__CallUnboundCMethod1(__Pyx_CachedCFunction* cfunc, PyObject* self, PyObject* arg); +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_CallUnboundCMethod1(__Pyx_CachedCFunction* cfunc, PyObject* self, PyObject* arg); +#else +#define __Pyx_CallUnboundCMethod1(cfunc, self, arg) __Pyx__CallUnboundCMethod1(cfunc, self, arg) +#endif + +/* CallUnboundCMethod2.proto */ +static PyObject* __Pyx__CallUnboundCMethod2(__Pyx_CachedCFunction* cfunc, PyObject* self, PyObject* arg1, PyObject* arg2); +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030600B1 +static CYTHON_INLINE PyObject *__Pyx_CallUnboundCMethod2(__Pyx_CachedCFunction *cfunc, PyObject *self, PyObject *arg1, PyObject *arg2); +#else +#define __Pyx_CallUnboundCMethod2(cfunc, self, arg1, arg2) __Pyx__CallUnboundCMethod2(cfunc, self, arg1, arg2) +#endif + +/* DictGetItem.proto */ +#if PY_MAJOR_VERSION >= 3 && !CYTHON_COMPILING_IN_PYPY +static PyObject *__Pyx_PyDict_GetItem(PyObject *d, PyObject* key); +#define __Pyx_PyObject_Dict_GetItem(obj, name)\ + (likely(PyDict_CheckExact(obj)) ?\ + __Pyx_PyDict_GetItem(obj, name) : PyObject_GetItem(obj, name)) +#else +#define __Pyx_PyDict_GetItem(d, key) PyObject_GetItem(d, key) +#define __Pyx_PyObject_Dict_GetItem(obj, name) PyObject_GetItem(obj, name) +#endif + +/* IncludeCppStringH.proto */ +#include + +/* decode_c_string_utf16.proto */ +static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16(const char *s, Py_ssize_t size, const char *errors) { + int byteorder = 0; + return PyUnicode_DecodeUTF16(s, size, errors, &byteorder); +} +static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16LE(const char *s, Py_ssize_t size, const char *errors) { + int byteorder = -1; + return PyUnicode_DecodeUTF16(s, size, errors, &byteorder); +} +static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16BE(const char *s, Py_ssize_t size, const char *errors) { + int byteorder = 1; + return PyUnicode_DecodeUTF16(s, size, errors, &byteorder); +} + +/* decode_c_bytes.proto */ +static CYTHON_INLINE PyObject* __Pyx_decode_c_bytes( + const char* cstring, Py_ssize_t length, Py_ssize_t start, Py_ssize_t stop, + const char* encoding, const char* errors, + PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)); + +/* decode_cpp_string.proto */ +static CYTHON_INLINE PyObject* __Pyx_decode_cpp_string( + std::string cppstring, Py_ssize_t start, Py_ssize_t stop, + const char* encoding, const char* errors, + PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) { + return __Pyx_decode_c_bytes( + cppstring.data(), cppstring.size(), start, stop, encoding, errors, decode_func); +} + +/* ListExtend.proto */ +static CYTHON_INLINE int __Pyx_PyList_Extend(PyObject* L, PyObject* v) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030d0000 + PyObject* none = _PyList_Extend((PyListObject*)L, v); + if (unlikely(!none)) + return -1; + Py_DECREF(none); + return 0; +#else + return PyList_SetSlice(L, PY_SSIZE_T_MAX, PY_SSIZE_T_MAX, v); +#endif +} + +/* IncludeStructmemberH.proto */ +#include + +/* FixUpExtensionType.proto */ +#if CYTHON_USE_TYPE_SPECS +static int __Pyx_fix_up_extension_type_from_spec(PyType_Spec *spec, PyTypeObject *type); +#endif + +/* PyObjectCallNoArg.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func); + +/* PyObjectCallMethod0.proto */ +static PyObject* __Pyx_PyObject_CallMethod0(PyObject* obj, PyObject* method_name); + +/* ValidateBasesTuple.proto */ +#if CYTHON_COMPILING_IN_CPYTHON || CYTHON_COMPILING_IN_LIMITED_API || CYTHON_USE_TYPE_SPECS +static int __Pyx_validate_bases_tuple(const char *type_name, Py_ssize_t dictoffset, PyObject *bases); +#endif + +/* PyType_Ready.proto */ +CYTHON_UNUSED static int __Pyx_PyType_Ready(PyTypeObject *t); + +/* PyObject_GenericGetAttrNoDict.proto */ +#if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 +static CYTHON_INLINE PyObject* __Pyx_PyObject_GenericGetAttrNoDict(PyObject* obj, PyObject* attr_name); +#else +#define __Pyx_PyObject_GenericGetAttrNoDict PyObject_GenericGetAttr +#endif + +/* PyObject_GenericGetAttr.proto */ +#if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 +static PyObject* __Pyx_PyObject_GenericGetAttr(PyObject* obj, PyObject* attr_name); +#else +#define __Pyx_PyObject_GenericGetAttr PyObject_GenericGetAttr +#endif + +/* Import.proto */ +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); + +/* ImportFrom.proto */ +static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name); + +/* ImportDottedModule.proto */ +static PyObject *__Pyx_ImportDottedModule(PyObject *name, PyObject *parts_tuple); +#if PY_MAJOR_VERSION >= 3 +static PyObject *__Pyx_ImportDottedModule_WalkParts(PyObject *module, PyObject *name, PyObject *parts_tuple); +#endif + +/* ImportDottedModuleRelFirst.proto */ +static PyObject *__Pyx_ImportDottedModuleRelFirst(PyObject *name, PyObject *parts_tuple); + +/* FetchSharedCythonModule.proto */ +static PyObject *__Pyx_FetchSharedCythonABIModule(void); + +/* FetchCommonType.proto */ +#if !CYTHON_USE_TYPE_SPECS +static PyTypeObject* __Pyx_FetchCommonType(PyTypeObject* type); +#else +static PyTypeObject* __Pyx_FetchCommonTypeFromSpec(PyObject *module, PyType_Spec *spec, PyObject *bases); +#endif + +/* PyMethodNew.proto */ +#if CYTHON_COMPILING_IN_LIMITED_API +static PyObject *__Pyx_PyMethod_New(PyObject *func, PyObject *self, PyObject *typ) { + PyObject *typesModule=NULL, *methodType=NULL, *result=NULL; + CYTHON_UNUSED_VAR(typ); + if (!self) + return __Pyx_NewRef(func); + typesModule = PyImport_ImportModule("types"); + if (!typesModule) return NULL; + methodType = PyObject_GetAttrString(typesModule, "MethodType"); + Py_DECREF(typesModule); + if (!methodType) return NULL; + result = PyObject_CallFunctionObjArgs(methodType, func, self, NULL); + Py_DECREF(methodType); + return result; +} +#elif PY_MAJOR_VERSION >= 3 +static PyObject *__Pyx_PyMethod_New(PyObject *func, PyObject *self, PyObject *typ) { + CYTHON_UNUSED_VAR(typ); + if (!self) + return __Pyx_NewRef(func); + return PyMethod_New(func, self); +} +#else + #define __Pyx_PyMethod_New PyMethod_New +#endif + +/* PyVectorcallFastCallDict.proto */ +#if CYTHON_METH_FASTCALL +static CYTHON_INLINE PyObject *__Pyx_PyVectorcall_FastCallDict(PyObject *func, __pyx_vectorcallfunc vc, PyObject *const *args, size_t nargs, PyObject *kw); +#endif + +/* CythonFunctionShared.proto */ +#define __Pyx_CyFunction_USED +#define __Pyx_CYFUNCTION_STATICMETHOD 0x01 +#define __Pyx_CYFUNCTION_CLASSMETHOD 0x02 +#define __Pyx_CYFUNCTION_CCLASS 0x04 +#define __Pyx_CYFUNCTION_COROUTINE 0x08 +#define __Pyx_CyFunction_GetClosure(f)\ + (((__pyx_CyFunctionObject *) (f))->func_closure) +#if PY_VERSION_HEX < 0x030900B1 || CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_CyFunction_GetClassObj(f)\ + (((__pyx_CyFunctionObject *) (f))->func_classobj) +#else + #define __Pyx_CyFunction_GetClassObj(f)\ + ((PyObject*) ((PyCMethodObject *) (f))->mm_class) +#endif +#define __Pyx_CyFunction_SetClassObj(f, classobj)\ + __Pyx__CyFunction_SetClassObj((__pyx_CyFunctionObject *) (f), (classobj)) +#define __Pyx_CyFunction_Defaults(type, f)\ + ((type *)(((__pyx_CyFunctionObject *) (f))->defaults)) +#define __Pyx_CyFunction_SetDefaultsGetter(f, g)\ + ((__pyx_CyFunctionObject *) (f))->defaults_getter = (g) +typedef struct { +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject_HEAD + PyObject *func; +#elif PY_VERSION_HEX < 0x030900B1 + PyCFunctionObject func; +#else + PyCMethodObject func; +#endif +#if CYTHON_BACKPORT_VECTORCALL + __pyx_vectorcallfunc func_vectorcall; +#endif +#if PY_VERSION_HEX < 0x030500A0 || CYTHON_COMPILING_IN_LIMITED_API + PyObject *func_weakreflist; +#endif + PyObject *func_dict; + PyObject *func_name; + PyObject *func_qualname; + PyObject *func_doc; + PyObject *func_globals; + PyObject *func_code; + PyObject *func_closure; +#if PY_VERSION_HEX < 0x030900B1 || CYTHON_COMPILING_IN_LIMITED_API + PyObject *func_classobj; +#endif + void *defaults; + int defaults_pyobjects; + size_t defaults_size; + int flags; + PyObject *defaults_tuple; + PyObject *defaults_kwdict; + PyObject *(*defaults_getter)(PyObject *); + PyObject *func_annotations; + PyObject *func_is_coroutine; +} __pyx_CyFunctionObject; +#undef __Pyx_CyOrPyCFunction_Check +#define __Pyx_CyFunction_Check(obj) __Pyx_TypeCheck(obj, __pyx_CyFunctionType) +#define __Pyx_CyOrPyCFunction_Check(obj) __Pyx_TypeCheck2(obj, __pyx_CyFunctionType, &PyCFunction_Type) +#define __Pyx_CyFunction_CheckExact(obj) __Pyx_IS_TYPE(obj, __pyx_CyFunctionType) +static CYTHON_INLINE int __Pyx__IsSameCyOrCFunction(PyObject *func, void *cfunc); +#undef __Pyx_IsSameCFunction +#define __Pyx_IsSameCFunction(func, cfunc) __Pyx__IsSameCyOrCFunction(func, cfunc) +static PyObject *__Pyx_CyFunction_Init(__pyx_CyFunctionObject* op, PyMethodDef *ml, + int flags, PyObject* qualname, + PyObject *closure, + PyObject *module, PyObject *globals, + PyObject* code); +static CYTHON_INLINE void __Pyx__CyFunction_SetClassObj(__pyx_CyFunctionObject* f, PyObject* classobj); +static CYTHON_INLINE void *__Pyx_CyFunction_InitDefaults(PyObject *m, + size_t size, + int pyobjects); +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsTuple(PyObject *m, + PyObject *tuple); +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsKwDict(PyObject *m, + PyObject *dict); +static CYTHON_INLINE void __Pyx_CyFunction_SetAnnotationsDict(PyObject *m, + PyObject *dict); +static int __pyx_CyFunction_init(PyObject *module); +#if CYTHON_METH_FASTCALL +static PyObject * __Pyx_CyFunction_Vectorcall_NOARGS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); +static PyObject * __Pyx_CyFunction_Vectorcall_O(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); +static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); +static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS_METHOD(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); +#if CYTHON_BACKPORT_VECTORCALL +#define __Pyx_CyFunction_func_vectorcall(f) (((__pyx_CyFunctionObject*)f)->func_vectorcall) +#else +#define __Pyx_CyFunction_func_vectorcall(f) (((PyCFunctionObject*)f)->vectorcall) +#endif +#endif + +/* CythonFunction.proto */ +static PyObject *__Pyx_CyFunction_New(PyMethodDef *ml, + int flags, PyObject* qualname, + PyObject *closure, + PyObject *module, PyObject *globals, + PyObject* code); + +/* GetNameInClass.proto */ +#define __Pyx_GetNameInClass(var, nmspace, name) (var) = __Pyx__GetNameInClass(nmspace, name) +static PyObject *__Pyx__GetNameInClass(PyObject *nmspace, PyObject *name); + +/* CLineInTraceback.proto */ +#ifdef CYTHON_CLINE_IN_TRACEBACK +#define __Pyx_CLineForTraceback(tstate, c_line) (((CYTHON_CLINE_IN_TRACEBACK)) ? c_line : 0) +#else +static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line); +#endif + +/* CodeObjectCache.proto */ +#if !CYTHON_COMPILING_IN_LIMITED_API +typedef struct { + PyCodeObject* code_object; + int code_line; +} __Pyx_CodeObjectCacheEntry; +struct __Pyx_CodeObjectCache { + int count; + int max_count; + __Pyx_CodeObjectCacheEntry* entries; +}; +static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); +static PyCodeObject *__pyx_find_code_object(int code_line); +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); +#endif + +/* AddTraceback.proto */ +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename); + +/* None.proto */ +#include + +/* CppExceptionConversion.proto */ +#ifndef __Pyx_CppExn2PyErr +#include +#include +#include +#include +static void __Pyx_CppExn2PyErr() { + try { + if (PyErr_Occurred()) + ; // let the latest Python exn pass through and ignore the current one + else + throw; + } catch (const std::bad_alloc& exn) { + PyErr_SetString(PyExc_MemoryError, exn.what()); + } catch (const std::bad_cast& exn) { + PyErr_SetString(PyExc_TypeError, exn.what()); + } catch (const std::bad_typeid& exn) { + PyErr_SetString(PyExc_TypeError, exn.what()); + } catch (const std::domain_error& exn) { + PyErr_SetString(PyExc_ValueError, exn.what()); + } catch (const std::invalid_argument& exn) { + PyErr_SetString(PyExc_ValueError, exn.what()); + } catch (const std::ios_base::failure& exn) { + PyErr_SetString(PyExc_IOError, exn.what()); + } catch (const std::out_of_range& exn) { + PyErr_SetString(PyExc_IndexError, exn.what()); + } catch (const std::overflow_error& exn) { + PyErr_SetString(PyExc_OverflowError, exn.what()); + } catch (const std::range_error& exn) { + PyErr_SetString(PyExc_ArithmeticError, exn.what()); + } catch (const std::underflow_error& exn) { + PyErr_SetString(PyExc_ArithmeticError, exn.what()); + } catch (const std::exception& exn) { + PyErr_SetString(PyExc_RuntimeError, exn.what()); + } + catch (...) + { + PyErr_SetString(PyExc_RuntimeError, "Unknown exception"); + } +} +#endif + +/* CIntToPy.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); + +/* CIntFromPy.proto */ +static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); + +/* FormatTypeName.proto */ +#if CYTHON_COMPILING_IN_LIMITED_API +typedef PyObject *__Pyx_TypeName; +#define __Pyx_FMT_TYPENAME "%U" +static __Pyx_TypeName __Pyx_PyType_GetName(PyTypeObject* tp); +#define __Pyx_DECREF_TypeName(obj) Py_XDECREF(obj) +#else +typedef const char *__Pyx_TypeName; +#define __Pyx_FMT_TYPENAME "%.200s" +#define __Pyx_PyType_GetName(tp) ((tp)->tp_name) +#define __Pyx_DECREF_TypeName(obj) +#endif + +/* CIntFromPy.proto */ +static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); + +/* FastTypeChecks.proto */ +#if CYTHON_COMPILING_IN_CPYTHON +#define __Pyx_TypeCheck(obj, type) __Pyx_IsSubtype(Py_TYPE(obj), (PyTypeObject *)type) +#define __Pyx_TypeCheck2(obj, type1, type2) __Pyx_IsAnySubtype2(Py_TYPE(obj), (PyTypeObject *)type1, (PyTypeObject *)type2) +static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b); +static CYTHON_INLINE int __Pyx_IsAnySubtype2(PyTypeObject *cls, PyTypeObject *a, PyTypeObject *b); +static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches(PyObject *err, PyObject *type); +static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *type1, PyObject *type2); +#else +#define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) +#define __Pyx_TypeCheck2(obj, type1, type2) (PyObject_TypeCheck(obj, (PyTypeObject *)type1) || PyObject_TypeCheck(obj, (PyTypeObject *)type2)) +#define __Pyx_PyErr_GivenExceptionMatches(err, type) PyErr_GivenExceptionMatches(err, type) +#define __Pyx_PyErr_GivenExceptionMatches2(err, type1, type2) (PyErr_GivenExceptionMatches(err, type1) || PyErr_GivenExceptionMatches(err, type2)) +#endif +#define __Pyx_PyErr_ExceptionMatches2(err1, err2) __Pyx_PyErr_GivenExceptionMatches2(__Pyx_PyErr_CurrentExceptionType(), err1, err2) +#define __Pyx_PyException_Check(obj) __Pyx_TypeCheck(obj, PyExc_Exception) + +/* SwapException.proto */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_ExceptionSwap(type, value, tb) __Pyx__ExceptionSwap(__pyx_tstate, type, value, tb) +static CYTHON_INLINE void __Pyx__ExceptionSwap(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); +#else +static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb); +#endif + +/* CoroutineBase.proto */ +struct __pyx_CoroutineObject; +typedef PyObject *(*__pyx_coroutine_body_t)(struct __pyx_CoroutineObject *, PyThreadState *, PyObject *); +#if CYTHON_USE_EXC_INFO_STACK +#define __Pyx_ExcInfoStruct _PyErr_StackItem +#else +typedef struct { + PyObject *exc_type; + PyObject *exc_value; + PyObject *exc_traceback; +} __Pyx_ExcInfoStruct; +#endif +typedef struct __pyx_CoroutineObject { + PyObject_HEAD + __pyx_coroutine_body_t body; + PyObject *closure; + __Pyx_ExcInfoStruct gi_exc_state; + PyObject *gi_weakreflist; + PyObject *classobj; + PyObject *yieldfrom; + PyObject *gi_name; + PyObject *gi_qualname; + PyObject *gi_modulename; + PyObject *gi_code; + PyObject *gi_frame; + int resume_label; + char is_running; +} __pyx_CoroutineObject; +static __pyx_CoroutineObject *__Pyx__Coroutine_New( + PyTypeObject *type, __pyx_coroutine_body_t body, PyObject *code, PyObject *closure, + PyObject *name, PyObject *qualname, PyObject *module_name); +static __pyx_CoroutineObject *__Pyx__Coroutine_NewInit( + __pyx_CoroutineObject *gen, __pyx_coroutine_body_t body, PyObject *code, PyObject *closure, + PyObject *name, PyObject *qualname, PyObject *module_name); +static CYTHON_INLINE void __Pyx_Coroutine_ExceptionClear(__Pyx_ExcInfoStruct *self); +static int __Pyx_Coroutine_clear(PyObject *self); +static PyObject *__Pyx_Coroutine_Send(PyObject *self, PyObject *value); +static PyObject *__Pyx_Coroutine_Close(PyObject *self); +static PyObject *__Pyx_Coroutine_Throw(PyObject *gen, PyObject *args); +#if CYTHON_USE_EXC_INFO_STACK +#define __Pyx_Coroutine_SwapException(self) +#define __Pyx_Coroutine_ResetAndClearException(self) __Pyx_Coroutine_ExceptionClear(&(self)->gi_exc_state) +#else +#define __Pyx_Coroutine_SwapException(self) {\ + __Pyx_ExceptionSwap(&(self)->gi_exc_state.exc_type, &(self)->gi_exc_state.exc_value, &(self)->gi_exc_state.exc_traceback);\ + __Pyx_Coroutine_ResetFrameBackpointer(&(self)->gi_exc_state);\ + } +#define __Pyx_Coroutine_ResetAndClearException(self) {\ + __Pyx_ExceptionReset((self)->gi_exc_state.exc_type, (self)->gi_exc_state.exc_value, (self)->gi_exc_state.exc_traceback);\ + (self)->gi_exc_state.exc_type = (self)->gi_exc_state.exc_value = (self)->gi_exc_state.exc_traceback = NULL;\ + } +#endif +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_PyGen_FetchStopIterationValue(pvalue)\ + __Pyx_PyGen__FetchStopIterationValue(__pyx_tstate, pvalue) +#else +#define __Pyx_PyGen_FetchStopIterationValue(pvalue)\ + __Pyx_PyGen__FetchStopIterationValue(__Pyx_PyThreadState_Current, pvalue) +#endif +static int __Pyx_PyGen__FetchStopIterationValue(PyThreadState *tstate, PyObject **pvalue); +static CYTHON_INLINE void __Pyx_Coroutine_ResetFrameBackpointer(__Pyx_ExcInfoStruct *exc_state); + +/* PatchModuleWithCoroutine.proto */ +static PyObject* __Pyx_Coroutine_patch_module(PyObject* module, const char* py_code); + +/* PatchGeneratorABC.proto */ +static int __Pyx_patch_abc(void); + +/* Generator.proto */ +#define __Pyx_Generator_USED +#define __Pyx_Generator_CheckExact(obj) __Pyx_IS_TYPE(obj, __pyx_GeneratorType) +#define __Pyx_Generator_New(body, code, closure, name, qualname, module_name)\ + __Pyx__Coroutine_New(__pyx_GeneratorType, body, code, closure, name, qualname, module_name) +static PyObject *__Pyx_Generator_Next(PyObject *self); +static int __pyx_Generator_init(PyObject *module); + +/* CheckBinaryVersion.proto */ +static unsigned long __Pyx_get_runtime_version(void); +static int __Pyx_check_binary_version(unsigned long ct_version, unsigned long rt_version, int allow_newer); + +/* InitStrings.proto */ +static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); + +/* #### Code section: module_declarations ### */ + +/* Module declarations from "libc.string" */ + +/* Module declarations from "libcpp.string" */ + +/* Module declarations from "libcpp.vector" */ + +/* Module declarations from "libcpp.utility" */ + +/* Module declarations from "libcpp" */ + +/* Module declarations from "libcpp.memory" */ + +/* Module declarations from "curated_tokenizers._bbpe" */ +static std::string __pyx_convert_string_from_py_std__in_string(PyObject *); /*proto*/ +static std::vector __pyx_convert_vector_from_py_std_3a__3a_string(PyObject *); /*proto*/ +static CYTHON_INLINE PyObject *__pyx_convert_PyObject_string_to_py_std__in_string(std::string const &); /*proto*/ +static CYTHON_INLINE PyObject *__pyx_convert_PyUnicode_string_to_py_std__in_string(std::string const &); /*proto*/ +static CYTHON_INLINE PyObject *__pyx_convert_PyStr_string_to_py_std__in_string(std::string const &); /*proto*/ +static CYTHON_INLINE PyObject *__pyx_convert_PyBytes_string_to_py_std__in_string(std::string const &); /*proto*/ +static CYTHON_INLINE PyObject *__pyx_convert_PyByteArray_string_to_py_std__in_string(std::string const &); /*proto*/ +static PyObject *__pyx_convert_pair_to_py_std_3a__3a_string____std_3a__3a_string(std::pair const &); /*proto*/ +/* #### Code section: typeinfo ### */ +/* #### Code section: before_global_var ### */ +#define __Pyx_MODULE_NAME "curated_tokenizers._bbpe" +extern int __pyx_module_is_main_curated_tokenizers___bbpe; +int __pyx_module_is_main_curated_tokenizers___bbpe = 0; + +/* Implementation of "curated_tokenizers._bbpe" */ +/* #### Code section: global_var ### */ +static PyObject *__pyx_builtin_staticmethod; +static PyObject *__pyx_builtin_range; +static PyObject *__pyx_builtin_chr; +static PyObject *__pyx_builtin_zip; +static PyObject *__pyx_builtin_open; +static PyObject *__pyx_builtin_ValueError; +/* #### Code section: string_decls ### */ +static const char __pyx_k_b[] = "b"; +static const char __pyx_k_f[] = "f"; +static const char __pyx_k_n[] = "n"; +static const char __pyx_k__2[] = " "; +static const char __pyx_k__3[] = ": "; +static const char __pyx_k__4[] = "."; +static const char __pyx_k__5[] = "*"; +static const char __pyx_k_bs[] = "bs"; +static const char __pyx_k_cp[] = "cp"; +static const char __pyx_k_cs[] = "cs"; +static const char __pyx_k_gc[] = "gc"; +static const char __pyx_k_io[] = "io"; +static const char __pyx_k__28[] = "?"; +static const char __pyx_k_chr[] = "chr"; +static const char __pyx_k_get[] = "get"; +static const char __pyx_k_ids[] = "ids"; +static const char __pyx_k_str[] = "str"; +static const char __pyx_k_zip[] = "zip"; +static const char __pyx_k_Dict[] = "Dict"; +static const char __pyx_k_List[] = "List"; +static const char __pyx_k_Path[] = "Path"; +static const char __pyx_k_args[] = "args"; +static const char __pyx_k_copy[] = "__copy__"; +static const char __pyx_k_dict[] = "__dict__"; +static const char __pyx_k_exit[] = "__exit__"; +static const char __pyx_k_json[] = "json"; +static const char __pyx_k_line[] = "line"; +static const char __pyx_k_load[] = "load"; +static const char __pyx_k_main[] = "__main__"; +static const char __pyx_k_memo[] = "memo"; +static const char __pyx_k_name[] = "__name__"; +static const char __pyx_k_open[] = "open"; +static const char __pyx_k_self[] = "self"; +static const char __pyx_k_send[] = "send"; +static const char __pyx_k_spec[] = "__spec__"; +static const char __pyx_k_test[] = "__test__"; +static const char __pyx_k_text[] = "text"; +static const char __pyx_k_Tuple[] = "Tuple"; +static const char __pyx_k_close[] = "close"; +static const char __pyx_k_enter[] = "__enter__"; +static const char __pyx_k_items[] = "items"; +static const char __pyx_k_merge[] = "merge"; +static const char __pyx_k_piece[] = "piece"; +static const char __pyx_k_range[] = "range"; +static const char __pyx_k_regex[] = "regex"; +static const char __pyx_k_split[] = "split"; +static const char __pyx_k_strip[] = "strip"; +static const char __pyx_k_throw[] = "throw"; +static const char __pyx_k_token[] = "token"; +static const char __pyx_k_utf_8[] = "utf-8"; +static const char __pyx_k_vocab[] = "vocab"; +static const char __pyx_k_write[] = "write"; +static const char __pyx_k_append[] = "append"; +static const char __pyx_k_decode[] = "decode"; +static const char __pyx_k_enable[] = "enable"; +static const char __pyx_k_encode[] = "encode"; +static const char __pyx_k_import[] = "__import__"; +static const char __pyx_k_merged[] = "merged"; +static const char __pyx_k_merges[] = "merges"; +static const char __pyx_k_pieces[] = "pieces"; +static const char __pyx_k_reduce[] = "__reduce__"; +static const char __pyx_k_return[] = "return"; +static const char __pyx_k_typing[] = "typing"; +static const char __pyx_k_BytesIO[] = "BytesIO"; +static const char __pyx_k_compile[] = "compile"; +static const char __pyx_k_decoded[] = "decoded"; +static const char __pyx_k_disable[] = "disable"; +static const char __pyx_k_findall[] = "findall"; +static const char __pyx_k_genexpr[] = "genexpr"; +static const char __pyx_k_pathlib[] = "pathlib"; +static const char __pyx_k_version[] = "version"; +static const char __pyx_k_Iterable[] = "Iterable"; +static const char __pyx_k_List_int[] = "List[int]"; +static const char __pyx_k_List_str[] = "List[str]"; +static const char __pyx_k_Optional[] = "Optional"; +static const char __pyx_k_deepcopy[] = "__deepcopy__"; +static const char __pyx_k_encoding[] = "encoding"; +static const char __pyx_k_getvalue[] = "getvalue"; +static const char __pyx_k_piece_id[] = "piece_id"; +static const char __pyx_k_readline[] = "readline"; +static const char __pyx_k_functools[] = "functools"; +static const char __pyx_k_isenabled[] = "isenabled"; +static const char __pyx_k_lru_cache[] = "lru_cache"; +static const char __pyx_k_piece_ids[] = "piece_ids"; +static const char __pyx_k_ValueError[] = "ValueError"; +static const char __pyx_k_startswith[] = "startswith"; +static const char __pyx_k_token_bytes[] = "token_bytes"; +static const char __pyx_k_version_0_2[] = "#version: 0.2"; +static const char __pyx_k_Dict_str_int[] = "Dict[str, int]"; +static const char __pyx_k_Iterable_int[] = "Iterable[int]"; +static const char __pyx_k_Optional_int[] = "Optional[int]"; +static const char __pyx_k_initializing[] = "_initializing"; +static const char __pyx_k_is_coroutine[] = "_is_coroutine"; +static const char __pyx_k_staticmethod[] = "staticmethod"; +static const char __pyx_k_SPLIT_PATTERN[] = "SPLIT_PATTERN"; +static const char __pyx_k_encode_as_ids[] = "encode_as_ids"; +static const char __pyx_k_pieces_to_ids[] = "_pieces_to_ids"; +static const char __pyx_k_Dict_int_bytes[] = "Dict[int, bytes]"; +static const char __pyx_k_decode_from_ids[] = "decode_from_ids"; +static const char __pyx_k_load_from_files[] = "load_from_files"; +static const char __pyx_k_ByteBPEProcessor[] = "ByteBPEProcessor"; +static const char __pyx_k_bytes_to_unicode[] = "bytes_to_unicode"; +static const char __pyx_k_encode_as_pieces[] = "encode_as_pieces"; +static const char __pyx_k_List_Tuple_str_str[] = "List[Tuple[str, str]]"; +static const char __pyx_k_asyncio_coroutines[] = "asyncio.coroutines"; +static const char __pyx_k_cline_in_traceback[] = "cline_in_traceback"; +static const char __pyx_k_ByteBPEProcessor___copy[] = "ByteBPEProcessor.__copy__"; +static const char __pyx_k_ByteBPEProcessor_encode[] = "ByteBPEProcessor.encode"; +static const char __pyx_k_Tuple_List_int_List_str[] = "Tuple[List[int], List[str]]"; +static const char __pyx_k_Unknown_piece_identifier[] = "Unknown piece identifier: "; +static const char __pyx_k_curated_tokenizers__bbpe[] = "curated_tokenizers._bbpe"; +static const char __pyx_k_ByteBPEProcessor___reduce[] = "ByteBPEProcessor.__reduce__"; +static const char __pyx_k_ByteBPEProcessor_piece_id[] = "ByteBPEProcessor.piece_id"; +static const char __pyx_k_Piece_is_not_in_vocabulary[] = "Piece is not in vocabulary: "; +static const char __pyx_k_ByteBPEProcessor___deepcopy[] = "ByteBPEProcessor.__deepcopy__"; +static const char __pyx_k_unpickle_byte_bpe_processor[] = "unpickle_byte_bpe_processor"; +static const char __pyx_k_curated_tokenizers__bbpe_pyx[] = "curated_tokenizers\\_bbpe.pyx"; +static const char __pyx_k_ByteBPEProcessor_encode_as_ids[] = "ByteBPEProcessor.encode_as_ids"; +static const char __pyx_k_s_t_re_ve_m_ll_d_p_L_p_N_s_p_L[] = "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+"; +static const char __pyx_k_ByteBPEProcessor__pieces_to_ids[] = "ByteBPEProcessor._pieces_to_ids"; +static const char __pyx_k_encode_as_pieces_locals_genexpr[] = "encode_as_pieces..genexpr"; +static const char __pyx_k_ByteBPEProcessor_decode_from_ids[] = "ByteBPEProcessor.decode_from_ids"; +static const char __pyx_k_ByteBPEProcessor_encode_as_piece[] = "ByteBPEProcessor.encode_as_pieces"; +static const char __pyx_k_ByteBPEProcessor_load_from_files[] = "ByteBPEProcessor.load_from_files"; +static const char __pyx_k_Merge_must_consist_of_2_items_wa[] = "Merge must consist of 2 items, was "; +static const char __pyx_k_Only_version_0_2_of_the_merges_f[] = "Only version 0.2 of the merges format is supported, was: "; +/* #### Code section: decls ### */ +static PyObject *__pyx_pf_18curated_tokenizers_5_bbpe_bytes_to_unicode(CYTHON_UNUSED PyObject *__pyx_self); /* proto */ +static int __pyx_pf_18curated_tokenizers_5_bbpe_16ByteBPEProcessor___init__(struct __pyx_obj_18curated_tokenizers_5_bbpe_ByteBPEProcessor *__pyx_v_self, PyObject *__pyx_v_vocab, PyObject *__pyx_v_merges); /* proto */ +static PyObject *__pyx_pf_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_2__copy__(struct __pyx_obj_18curated_tokenizers_5_bbpe_ByteBPEProcessor *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_4__deepcopy__(struct __pyx_obj_18curated_tokenizers_5_bbpe_ByteBPEProcessor *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v_memo); /* proto */ +static PyObject *__pyx_pf_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_6load_from_files(PyObject *__pyx_v_vocab, PyObject *__pyx_v_merges); /* proto */ +static PyObject *__pyx_pf_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_8decode_from_ids(struct __pyx_obj_18curated_tokenizers_5_bbpe_ByteBPEProcessor *__pyx_v_self, PyObject *__pyx_v_ids); /* proto */ +static PyObject *__pyx_pf_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_10encode(struct __pyx_obj_18curated_tokenizers_5_bbpe_ByteBPEProcessor *__pyx_v_self, PyObject *__pyx_v_text); /* proto */ +static PyObject *__pyx_pf_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_12encode_as_ids(struct __pyx_obj_18curated_tokenizers_5_bbpe_ByteBPEProcessor *__pyx_v_self, PyObject *__pyx_v_text); /* proto */ +static PyObject *__pyx_pf_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_16encode_as_pieces_genexpr(CYTHON_UNUSED PyObject *__pyx_self, std::vector __pyx_genexpr_arg_0); /* proto */ +static PyObject *__pyx_pf_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_14encode_as_pieces(struct __pyx_obj_18curated_tokenizers_5_bbpe_ByteBPEProcessor *__pyx_v_self, PyObject *__pyx_v_text); /* proto */ +static PyObject *__pyx_pf_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_6merges___get__(struct __pyx_obj_18curated_tokenizers_5_bbpe_ByteBPEProcessor *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_16piece_id(struct __pyx_obj_18curated_tokenizers_5_bbpe_ByteBPEProcessor *__pyx_v_self, PyObject *__pyx_v_piece); /* proto */ +static PyObject *__pyx_pf_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_5vocab___get__(struct __pyx_obj_18curated_tokenizers_5_bbpe_ByteBPEProcessor *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_18_pieces_to_ids(struct __pyx_obj_18curated_tokenizers_5_bbpe_ByteBPEProcessor *__pyx_v_self, PyObject *__pyx_v_pieces); /* proto */ +static PyObject *__pyx_pf_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_20__reduce__(struct __pyx_obj_18curated_tokenizers_5_bbpe_ByteBPEProcessor *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_18curated_tokenizers_5_bbpe_2unpickle_byte_bpe_processor(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_vocab, PyObject *__pyx_v_merges); /* proto */ +static PyObject *__pyx_tp_new_18curated_tokenizers_5_bbpe_ByteBPEProcessor(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static __Pyx_CachedCFunction __pyx_umethod_PyDict_Type_get = {0, 0, 0, 0, 0}; +static __Pyx_CachedCFunction __pyx_umethod_PyDict_Type_items = {0, 0, 0, 0, 0}; +/* #### Code section: late_includes ### */ +/* #### Code section: module_state ### */ +typedef struct { + PyObject *__pyx_d; + PyObject *__pyx_b; + PyObject *__pyx_cython_runtime; + PyObject *__pyx_empty_tuple; + PyObject *__pyx_empty_bytes; + PyObject *__pyx_empty_unicode; + #ifdef __Pyx_CyFunction_USED + PyTypeObject *__pyx_CyFunctionType; + #endif + #ifdef __Pyx_FusedFunction_USED + PyTypeObject *__pyx_FusedFunctionType; + #endif + #ifdef __Pyx_Generator_USED + PyTypeObject *__pyx_GeneratorType; + #endif + #ifdef __Pyx_IterableCoroutine_USED + PyTypeObject *__pyx_IterableCoroutineType; + #endif + #ifdef __Pyx_Coroutine_USED + PyTypeObject *__pyx_CoroutineAwaitType; + #endif + #ifdef __Pyx_Coroutine_USED + PyTypeObject *__pyx_CoroutineType; + #endif + #if CYTHON_USE_MODULE_STATE + #endif + #if CYTHON_USE_MODULE_STATE + #endif + #if CYTHON_USE_MODULE_STATE + #endif + #if CYTHON_USE_MODULE_STATE + #endif + #if CYTHON_USE_MODULE_STATE + #endif + #if CYTHON_USE_MODULE_STATE + #endif + #if CYTHON_USE_MODULE_STATE + PyObject *__pyx_type_18curated_tokenizers_5_bbpe_ByteBPEProcessor; + PyObject *__pyx_type_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr; + #endif + PyTypeObject *__pyx_ptype_18curated_tokenizers_5_bbpe_ByteBPEProcessor; + PyTypeObject *__pyx_ptype_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr; + PyObject *__pyx_n_s_ByteBPEProcessor; + PyObject *__pyx_n_s_ByteBPEProcessor___copy; + PyObject *__pyx_n_s_ByteBPEProcessor___deepcopy; + PyObject *__pyx_n_s_ByteBPEProcessor___reduce; + PyObject *__pyx_n_s_ByteBPEProcessor__pieces_to_ids; + PyObject *__pyx_n_s_ByteBPEProcessor_decode_from_ids; + PyObject *__pyx_n_s_ByteBPEProcessor_encode; + PyObject *__pyx_n_s_ByteBPEProcessor_encode_as_ids; + PyObject *__pyx_n_s_ByteBPEProcessor_encode_as_piece; + PyObject *__pyx_n_s_ByteBPEProcessor_load_from_files; + PyObject *__pyx_n_s_ByteBPEProcessor_piece_id; + PyObject *__pyx_n_s_BytesIO; + PyObject *__pyx_n_s_Dict; + PyObject *__pyx_kp_s_Dict_int_bytes; + PyObject *__pyx_kp_s_Dict_str_int; + PyObject *__pyx_n_s_Iterable; + PyObject *__pyx_kp_s_Iterable_int; + PyObject *__pyx_n_s_List; + PyObject *__pyx_kp_s_List_Tuple_str_str; + PyObject *__pyx_kp_s_List_int; + PyObject *__pyx_kp_s_List_str; + PyObject *__pyx_kp_u_Merge_must_consist_of_2_items_wa; + PyObject *__pyx_kp_u_Only_version_0_2_of_the_merges_f; + PyObject *__pyx_n_s_Optional; + PyObject *__pyx_kp_s_Optional_int; + PyObject *__pyx_n_s_Path; + PyObject *__pyx_kp_u_Piece_is_not_in_vocabulary; + PyObject *__pyx_n_s_SPLIT_PATTERN; + PyObject *__pyx_n_s_Tuple; + PyObject *__pyx_kp_s_Tuple_List_int_List_str; + PyObject *__pyx_kp_u_Unknown_piece_identifier; + PyObject *__pyx_n_s_ValueError; + PyObject *__pyx_kp_s__2; + PyObject *__pyx_n_s__28; + PyObject *__pyx_kp_u__3; + PyObject *__pyx_kp_u__4; + PyObject *__pyx_n_s__5; + PyObject *__pyx_n_s_append; + PyObject *__pyx_n_s_args; + PyObject *__pyx_n_s_asyncio_coroutines; + PyObject *__pyx_n_s_b; + PyObject *__pyx_n_s_bs; + PyObject *__pyx_n_s_bytes_to_unicode; + PyObject *__pyx_n_s_chr; + PyObject *__pyx_n_s_cline_in_traceback; + PyObject *__pyx_n_s_close; + PyObject *__pyx_n_s_compile; + PyObject *__pyx_n_s_copy; + PyObject *__pyx_n_s_cp; + PyObject *__pyx_n_s_cs; + PyObject *__pyx_n_s_curated_tokenizers__bbpe; + PyObject *__pyx_kp_s_curated_tokenizers__bbpe_pyx; + PyObject *__pyx_n_s_decode; + PyObject *__pyx_n_s_decode_from_ids; + PyObject *__pyx_n_s_decoded; + PyObject *__pyx_n_s_deepcopy; + PyObject *__pyx_n_s_dict; + PyObject *__pyx_kp_u_disable; + PyObject *__pyx_kp_u_enable; + PyObject *__pyx_n_s_encode; + PyObject *__pyx_n_s_encode_as_ids; + PyObject *__pyx_n_s_encode_as_pieces; + PyObject *__pyx_n_s_encode_as_pieces_locals_genexpr; + PyObject *__pyx_n_s_encoding; + PyObject *__pyx_n_s_enter; + PyObject *__pyx_n_s_exit; + PyObject *__pyx_n_s_f; + PyObject *__pyx_n_s_findall; + PyObject *__pyx_n_s_functools; + PyObject *__pyx_kp_u_gc; + PyObject *__pyx_n_s_genexpr; + PyObject *__pyx_n_s_get; + PyObject *__pyx_n_s_getvalue; + PyObject *__pyx_n_s_ids; + PyObject *__pyx_n_s_import; + PyObject *__pyx_n_s_initializing; + PyObject *__pyx_n_s_io; + PyObject *__pyx_n_s_is_coroutine; + PyObject *__pyx_kp_u_isenabled; + PyObject *__pyx_n_s_items; + PyObject *__pyx_n_s_json; + PyObject *__pyx_n_s_line; + PyObject *__pyx_n_s_load; + PyObject *__pyx_n_s_load_from_files; + PyObject *__pyx_n_s_lru_cache; + PyObject *__pyx_n_s_main; + PyObject *__pyx_n_s_memo; + PyObject *__pyx_n_s_merge; + PyObject *__pyx_n_s_merged; + PyObject *__pyx_n_s_merges; + PyObject *__pyx_n_s_n; + PyObject *__pyx_n_s_name; + PyObject *__pyx_n_s_open; + PyObject *__pyx_n_s_pathlib; + PyObject *__pyx_n_s_piece; + PyObject *__pyx_n_s_piece_id; + PyObject *__pyx_n_s_piece_ids; + PyObject *__pyx_n_s_pieces; + PyObject *__pyx_n_s_pieces_to_ids; + PyObject *__pyx_n_s_range; + PyObject *__pyx_n_s_readline; + PyObject *__pyx_n_s_reduce; + PyObject *__pyx_n_s_regex; + PyObject *__pyx_n_s_return; + PyObject *__pyx_kp_s_s_t_re_ve_m_ll_d_p_L_p_N_s_p_L; + PyObject *__pyx_n_s_self; + PyObject *__pyx_n_s_send; + PyObject *__pyx_n_s_spec; + PyObject *__pyx_n_s_split; + PyObject *__pyx_n_s_startswith; + PyObject *__pyx_n_s_staticmethod; + PyObject *__pyx_n_s_str; + PyObject *__pyx_n_s_strip; + PyObject *__pyx_n_s_test; + PyObject *__pyx_n_s_text; + PyObject *__pyx_n_s_throw; + PyObject *__pyx_n_s_token; + PyObject *__pyx_n_s_token_bytes; + PyObject *__pyx_n_s_typing; + PyObject *__pyx_n_s_unpickle_byte_bpe_processor; + PyObject *__pyx_kp_s_utf_8; + PyObject *__pyx_n_s_version; + PyObject *__pyx_kp_s_version_0_2; + PyObject *__pyx_n_s_vocab; + PyObject *__pyx_n_s_write; + PyObject *__pyx_n_s_zip; + PyObject *__pyx_int_0; + PyObject *__pyx_int_1; + PyObject *__pyx_int_33; + PyObject *__pyx_int_161; + PyObject *__pyx_int_174; + PyObject *__pyx_int_256; + PyObject *__pyx_tuple_; + PyObject *__pyx_tuple__6; + PyObject *__pyx_tuple__8; + PyObject *__pyx_tuple__10; + PyObject *__pyx_tuple__12; + PyObject *__pyx_tuple__14; + PyObject *__pyx_tuple__16; + PyObject *__pyx_tuple__19; + PyObject *__pyx_tuple__21; + PyObject *__pyx_tuple__23; + PyObject *__pyx_tuple__26; + PyObject *__pyx_codeobj__7; + PyObject *__pyx_codeobj__9; + PyObject *__pyx_codeobj__11; + PyObject *__pyx_codeobj__13; + PyObject *__pyx_codeobj__15; + PyObject *__pyx_codeobj__17; + PyObject *__pyx_codeobj__18; + PyObject *__pyx_codeobj__20; + PyObject *__pyx_codeobj__22; + PyObject *__pyx_codeobj__24; + PyObject *__pyx_codeobj__25; + PyObject *__pyx_codeobj__27; +} __pyx_mstate; + +#if CYTHON_USE_MODULE_STATE +#ifdef __cplusplus +namespace { + extern struct PyModuleDef __pyx_moduledef; +} /* anonymous namespace */ +#else +static struct PyModuleDef __pyx_moduledef; +#endif + +#define __pyx_mstate(o) ((__pyx_mstate *)__Pyx_PyModule_GetState(o)) + +#define __pyx_mstate_global (__pyx_mstate(PyState_FindModule(&__pyx_moduledef))) + +#define __pyx_m (PyState_FindModule(&__pyx_moduledef)) +#else +static __pyx_mstate __pyx_mstate_global_static = +#ifdef __cplusplus + {}; +#else + {0}; +#endif +static __pyx_mstate *__pyx_mstate_global = &__pyx_mstate_global_static; +#endif +/* #### Code section: module_state_clear ### */ +#if CYTHON_USE_MODULE_STATE +static int __pyx_m_clear(PyObject *m) { + __pyx_mstate *clear_module_state = __pyx_mstate(m); + if (!clear_module_state) return 0; + Py_CLEAR(clear_module_state->__pyx_d); + Py_CLEAR(clear_module_state->__pyx_b); + Py_CLEAR(clear_module_state->__pyx_cython_runtime); + Py_CLEAR(clear_module_state->__pyx_empty_tuple); + Py_CLEAR(clear_module_state->__pyx_empty_bytes); + Py_CLEAR(clear_module_state->__pyx_empty_unicode); + #ifdef __Pyx_CyFunction_USED + Py_CLEAR(clear_module_state->__pyx_CyFunctionType); + #endif + #ifdef __Pyx_FusedFunction_USED + Py_CLEAR(clear_module_state->__pyx_FusedFunctionType); + #endif + Py_CLEAR(clear_module_state->__pyx_ptype_18curated_tokenizers_5_bbpe_ByteBPEProcessor); + Py_CLEAR(clear_module_state->__pyx_type_18curated_tokenizers_5_bbpe_ByteBPEProcessor); + Py_CLEAR(clear_module_state->__pyx_ptype_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr); + Py_CLEAR(clear_module_state->__pyx_type_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr); + Py_CLEAR(clear_module_state->__pyx_n_s_ByteBPEProcessor); + Py_CLEAR(clear_module_state->__pyx_n_s_ByteBPEProcessor___copy); + Py_CLEAR(clear_module_state->__pyx_n_s_ByteBPEProcessor___deepcopy); + Py_CLEAR(clear_module_state->__pyx_n_s_ByteBPEProcessor___reduce); + Py_CLEAR(clear_module_state->__pyx_n_s_ByteBPEProcessor__pieces_to_ids); + Py_CLEAR(clear_module_state->__pyx_n_s_ByteBPEProcessor_decode_from_ids); + Py_CLEAR(clear_module_state->__pyx_n_s_ByteBPEProcessor_encode); + Py_CLEAR(clear_module_state->__pyx_n_s_ByteBPEProcessor_encode_as_ids); + Py_CLEAR(clear_module_state->__pyx_n_s_ByteBPEProcessor_encode_as_piece); + Py_CLEAR(clear_module_state->__pyx_n_s_ByteBPEProcessor_load_from_files); + Py_CLEAR(clear_module_state->__pyx_n_s_ByteBPEProcessor_piece_id); + Py_CLEAR(clear_module_state->__pyx_n_s_BytesIO); + Py_CLEAR(clear_module_state->__pyx_n_s_Dict); + Py_CLEAR(clear_module_state->__pyx_kp_s_Dict_int_bytes); + Py_CLEAR(clear_module_state->__pyx_kp_s_Dict_str_int); + Py_CLEAR(clear_module_state->__pyx_n_s_Iterable); + Py_CLEAR(clear_module_state->__pyx_kp_s_Iterable_int); + Py_CLEAR(clear_module_state->__pyx_n_s_List); + Py_CLEAR(clear_module_state->__pyx_kp_s_List_Tuple_str_str); + Py_CLEAR(clear_module_state->__pyx_kp_s_List_int); + Py_CLEAR(clear_module_state->__pyx_kp_s_List_str); + Py_CLEAR(clear_module_state->__pyx_kp_u_Merge_must_consist_of_2_items_wa); + Py_CLEAR(clear_module_state->__pyx_kp_u_Only_version_0_2_of_the_merges_f); + Py_CLEAR(clear_module_state->__pyx_n_s_Optional); + Py_CLEAR(clear_module_state->__pyx_kp_s_Optional_int); + Py_CLEAR(clear_module_state->__pyx_n_s_Path); + Py_CLEAR(clear_module_state->__pyx_kp_u_Piece_is_not_in_vocabulary); + Py_CLEAR(clear_module_state->__pyx_n_s_SPLIT_PATTERN); + Py_CLEAR(clear_module_state->__pyx_n_s_Tuple); + Py_CLEAR(clear_module_state->__pyx_kp_s_Tuple_List_int_List_str); + Py_CLEAR(clear_module_state->__pyx_kp_u_Unknown_piece_identifier); + Py_CLEAR(clear_module_state->__pyx_n_s_ValueError); + Py_CLEAR(clear_module_state->__pyx_kp_s__2); + Py_CLEAR(clear_module_state->__pyx_n_s__28); + Py_CLEAR(clear_module_state->__pyx_kp_u__3); + Py_CLEAR(clear_module_state->__pyx_kp_u__4); + Py_CLEAR(clear_module_state->__pyx_n_s__5); + Py_CLEAR(clear_module_state->__pyx_n_s_append); + Py_CLEAR(clear_module_state->__pyx_n_s_args); + Py_CLEAR(clear_module_state->__pyx_n_s_asyncio_coroutines); + Py_CLEAR(clear_module_state->__pyx_n_s_b); + Py_CLEAR(clear_module_state->__pyx_n_s_bs); + Py_CLEAR(clear_module_state->__pyx_n_s_bytes_to_unicode); + Py_CLEAR(clear_module_state->__pyx_n_s_chr); + Py_CLEAR(clear_module_state->__pyx_n_s_cline_in_traceback); + Py_CLEAR(clear_module_state->__pyx_n_s_close); + Py_CLEAR(clear_module_state->__pyx_n_s_compile); + Py_CLEAR(clear_module_state->__pyx_n_s_copy); + Py_CLEAR(clear_module_state->__pyx_n_s_cp); + Py_CLEAR(clear_module_state->__pyx_n_s_cs); + Py_CLEAR(clear_module_state->__pyx_n_s_curated_tokenizers__bbpe); + Py_CLEAR(clear_module_state->__pyx_kp_s_curated_tokenizers__bbpe_pyx); + Py_CLEAR(clear_module_state->__pyx_n_s_decode); + Py_CLEAR(clear_module_state->__pyx_n_s_decode_from_ids); + Py_CLEAR(clear_module_state->__pyx_n_s_decoded); + Py_CLEAR(clear_module_state->__pyx_n_s_deepcopy); + Py_CLEAR(clear_module_state->__pyx_n_s_dict); + Py_CLEAR(clear_module_state->__pyx_kp_u_disable); + Py_CLEAR(clear_module_state->__pyx_kp_u_enable); + Py_CLEAR(clear_module_state->__pyx_n_s_encode); + Py_CLEAR(clear_module_state->__pyx_n_s_encode_as_ids); + Py_CLEAR(clear_module_state->__pyx_n_s_encode_as_pieces); + Py_CLEAR(clear_module_state->__pyx_n_s_encode_as_pieces_locals_genexpr); + Py_CLEAR(clear_module_state->__pyx_n_s_encoding); + Py_CLEAR(clear_module_state->__pyx_n_s_enter); + Py_CLEAR(clear_module_state->__pyx_n_s_exit); + Py_CLEAR(clear_module_state->__pyx_n_s_f); + Py_CLEAR(clear_module_state->__pyx_n_s_findall); + Py_CLEAR(clear_module_state->__pyx_n_s_functools); + Py_CLEAR(clear_module_state->__pyx_kp_u_gc); + Py_CLEAR(clear_module_state->__pyx_n_s_genexpr); + Py_CLEAR(clear_module_state->__pyx_n_s_get); + Py_CLEAR(clear_module_state->__pyx_n_s_getvalue); + Py_CLEAR(clear_module_state->__pyx_n_s_ids); + Py_CLEAR(clear_module_state->__pyx_n_s_import); + Py_CLEAR(clear_module_state->__pyx_n_s_initializing); + Py_CLEAR(clear_module_state->__pyx_n_s_io); + Py_CLEAR(clear_module_state->__pyx_n_s_is_coroutine); + Py_CLEAR(clear_module_state->__pyx_kp_u_isenabled); + Py_CLEAR(clear_module_state->__pyx_n_s_items); + Py_CLEAR(clear_module_state->__pyx_n_s_json); + Py_CLEAR(clear_module_state->__pyx_n_s_line); + Py_CLEAR(clear_module_state->__pyx_n_s_load); + Py_CLEAR(clear_module_state->__pyx_n_s_load_from_files); + Py_CLEAR(clear_module_state->__pyx_n_s_lru_cache); + Py_CLEAR(clear_module_state->__pyx_n_s_main); + Py_CLEAR(clear_module_state->__pyx_n_s_memo); + Py_CLEAR(clear_module_state->__pyx_n_s_merge); + Py_CLEAR(clear_module_state->__pyx_n_s_merged); + Py_CLEAR(clear_module_state->__pyx_n_s_merges); + Py_CLEAR(clear_module_state->__pyx_n_s_n); + Py_CLEAR(clear_module_state->__pyx_n_s_name); + Py_CLEAR(clear_module_state->__pyx_n_s_open); + Py_CLEAR(clear_module_state->__pyx_n_s_pathlib); + Py_CLEAR(clear_module_state->__pyx_n_s_piece); + Py_CLEAR(clear_module_state->__pyx_n_s_piece_id); + Py_CLEAR(clear_module_state->__pyx_n_s_piece_ids); + Py_CLEAR(clear_module_state->__pyx_n_s_pieces); + Py_CLEAR(clear_module_state->__pyx_n_s_pieces_to_ids); + Py_CLEAR(clear_module_state->__pyx_n_s_range); + Py_CLEAR(clear_module_state->__pyx_n_s_readline); + Py_CLEAR(clear_module_state->__pyx_n_s_reduce); + Py_CLEAR(clear_module_state->__pyx_n_s_regex); + Py_CLEAR(clear_module_state->__pyx_n_s_return); + Py_CLEAR(clear_module_state->__pyx_kp_s_s_t_re_ve_m_ll_d_p_L_p_N_s_p_L); + Py_CLEAR(clear_module_state->__pyx_n_s_self); + Py_CLEAR(clear_module_state->__pyx_n_s_send); + Py_CLEAR(clear_module_state->__pyx_n_s_spec); + Py_CLEAR(clear_module_state->__pyx_n_s_split); + Py_CLEAR(clear_module_state->__pyx_n_s_startswith); + Py_CLEAR(clear_module_state->__pyx_n_s_staticmethod); + Py_CLEAR(clear_module_state->__pyx_n_s_str); + Py_CLEAR(clear_module_state->__pyx_n_s_strip); + Py_CLEAR(clear_module_state->__pyx_n_s_test); + Py_CLEAR(clear_module_state->__pyx_n_s_text); + Py_CLEAR(clear_module_state->__pyx_n_s_throw); + Py_CLEAR(clear_module_state->__pyx_n_s_token); + Py_CLEAR(clear_module_state->__pyx_n_s_token_bytes); + Py_CLEAR(clear_module_state->__pyx_n_s_typing); + Py_CLEAR(clear_module_state->__pyx_n_s_unpickle_byte_bpe_processor); + Py_CLEAR(clear_module_state->__pyx_kp_s_utf_8); + Py_CLEAR(clear_module_state->__pyx_n_s_version); + Py_CLEAR(clear_module_state->__pyx_kp_s_version_0_2); + Py_CLEAR(clear_module_state->__pyx_n_s_vocab); + Py_CLEAR(clear_module_state->__pyx_n_s_write); + Py_CLEAR(clear_module_state->__pyx_n_s_zip); + Py_CLEAR(clear_module_state->__pyx_int_0); + Py_CLEAR(clear_module_state->__pyx_int_1); + Py_CLEAR(clear_module_state->__pyx_int_33); + Py_CLEAR(clear_module_state->__pyx_int_161); + Py_CLEAR(clear_module_state->__pyx_int_174); + Py_CLEAR(clear_module_state->__pyx_int_256); + Py_CLEAR(clear_module_state->__pyx_tuple_); + Py_CLEAR(clear_module_state->__pyx_tuple__6); + Py_CLEAR(clear_module_state->__pyx_tuple__8); + Py_CLEAR(clear_module_state->__pyx_tuple__10); + Py_CLEAR(clear_module_state->__pyx_tuple__12); + Py_CLEAR(clear_module_state->__pyx_tuple__14); + Py_CLEAR(clear_module_state->__pyx_tuple__16); + Py_CLEAR(clear_module_state->__pyx_tuple__19); + Py_CLEAR(clear_module_state->__pyx_tuple__21); + Py_CLEAR(clear_module_state->__pyx_tuple__23); + Py_CLEAR(clear_module_state->__pyx_tuple__26); + Py_CLEAR(clear_module_state->__pyx_codeobj__7); + Py_CLEAR(clear_module_state->__pyx_codeobj__9); + Py_CLEAR(clear_module_state->__pyx_codeobj__11); + Py_CLEAR(clear_module_state->__pyx_codeobj__13); + Py_CLEAR(clear_module_state->__pyx_codeobj__15); + Py_CLEAR(clear_module_state->__pyx_codeobj__17); + Py_CLEAR(clear_module_state->__pyx_codeobj__18); + Py_CLEAR(clear_module_state->__pyx_codeobj__20); + Py_CLEAR(clear_module_state->__pyx_codeobj__22); + Py_CLEAR(clear_module_state->__pyx_codeobj__24); + Py_CLEAR(clear_module_state->__pyx_codeobj__25); + Py_CLEAR(clear_module_state->__pyx_codeobj__27); + return 0; +} +#endif +/* #### Code section: module_state_traverse ### */ +#if CYTHON_USE_MODULE_STATE +static int __pyx_m_traverse(PyObject *m, visitproc visit, void *arg) { + __pyx_mstate *traverse_module_state = __pyx_mstate(m); + if (!traverse_module_state) return 0; + Py_VISIT(traverse_module_state->__pyx_d); + Py_VISIT(traverse_module_state->__pyx_b); + Py_VISIT(traverse_module_state->__pyx_cython_runtime); + Py_VISIT(traverse_module_state->__pyx_empty_tuple); + Py_VISIT(traverse_module_state->__pyx_empty_bytes); + Py_VISIT(traverse_module_state->__pyx_empty_unicode); + #ifdef __Pyx_CyFunction_USED + Py_VISIT(traverse_module_state->__pyx_CyFunctionType); + #endif + #ifdef __Pyx_FusedFunction_USED + Py_VISIT(traverse_module_state->__pyx_FusedFunctionType); + #endif + Py_VISIT(traverse_module_state->__pyx_ptype_18curated_tokenizers_5_bbpe_ByteBPEProcessor); + Py_VISIT(traverse_module_state->__pyx_type_18curated_tokenizers_5_bbpe_ByteBPEProcessor); + Py_VISIT(traverse_module_state->__pyx_ptype_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr); + Py_VISIT(traverse_module_state->__pyx_type_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr); + Py_VISIT(traverse_module_state->__pyx_n_s_ByteBPEProcessor); + Py_VISIT(traverse_module_state->__pyx_n_s_ByteBPEProcessor___copy); + Py_VISIT(traverse_module_state->__pyx_n_s_ByteBPEProcessor___deepcopy); + Py_VISIT(traverse_module_state->__pyx_n_s_ByteBPEProcessor___reduce); + Py_VISIT(traverse_module_state->__pyx_n_s_ByteBPEProcessor__pieces_to_ids); + Py_VISIT(traverse_module_state->__pyx_n_s_ByteBPEProcessor_decode_from_ids); + Py_VISIT(traverse_module_state->__pyx_n_s_ByteBPEProcessor_encode); + Py_VISIT(traverse_module_state->__pyx_n_s_ByteBPEProcessor_encode_as_ids); + Py_VISIT(traverse_module_state->__pyx_n_s_ByteBPEProcessor_encode_as_piece); + Py_VISIT(traverse_module_state->__pyx_n_s_ByteBPEProcessor_load_from_files); + Py_VISIT(traverse_module_state->__pyx_n_s_ByteBPEProcessor_piece_id); + Py_VISIT(traverse_module_state->__pyx_n_s_BytesIO); + Py_VISIT(traverse_module_state->__pyx_n_s_Dict); + Py_VISIT(traverse_module_state->__pyx_kp_s_Dict_int_bytes); + Py_VISIT(traverse_module_state->__pyx_kp_s_Dict_str_int); + Py_VISIT(traverse_module_state->__pyx_n_s_Iterable); + Py_VISIT(traverse_module_state->__pyx_kp_s_Iterable_int); + Py_VISIT(traverse_module_state->__pyx_n_s_List); + Py_VISIT(traverse_module_state->__pyx_kp_s_List_Tuple_str_str); + Py_VISIT(traverse_module_state->__pyx_kp_s_List_int); + Py_VISIT(traverse_module_state->__pyx_kp_s_List_str); + Py_VISIT(traverse_module_state->__pyx_kp_u_Merge_must_consist_of_2_items_wa); + Py_VISIT(traverse_module_state->__pyx_kp_u_Only_version_0_2_of_the_merges_f); + Py_VISIT(traverse_module_state->__pyx_n_s_Optional); + Py_VISIT(traverse_module_state->__pyx_kp_s_Optional_int); + Py_VISIT(traverse_module_state->__pyx_n_s_Path); + Py_VISIT(traverse_module_state->__pyx_kp_u_Piece_is_not_in_vocabulary); + Py_VISIT(traverse_module_state->__pyx_n_s_SPLIT_PATTERN); + Py_VISIT(traverse_module_state->__pyx_n_s_Tuple); + Py_VISIT(traverse_module_state->__pyx_kp_s_Tuple_List_int_List_str); + Py_VISIT(traverse_module_state->__pyx_kp_u_Unknown_piece_identifier); + Py_VISIT(traverse_module_state->__pyx_n_s_ValueError); + Py_VISIT(traverse_module_state->__pyx_kp_s__2); + Py_VISIT(traverse_module_state->__pyx_n_s__28); + Py_VISIT(traverse_module_state->__pyx_kp_u__3); + Py_VISIT(traverse_module_state->__pyx_kp_u__4); + Py_VISIT(traverse_module_state->__pyx_n_s__5); + Py_VISIT(traverse_module_state->__pyx_n_s_append); + Py_VISIT(traverse_module_state->__pyx_n_s_args); + Py_VISIT(traverse_module_state->__pyx_n_s_asyncio_coroutines); + Py_VISIT(traverse_module_state->__pyx_n_s_b); + Py_VISIT(traverse_module_state->__pyx_n_s_bs); + Py_VISIT(traverse_module_state->__pyx_n_s_bytes_to_unicode); + Py_VISIT(traverse_module_state->__pyx_n_s_chr); + Py_VISIT(traverse_module_state->__pyx_n_s_cline_in_traceback); + Py_VISIT(traverse_module_state->__pyx_n_s_close); + Py_VISIT(traverse_module_state->__pyx_n_s_compile); + Py_VISIT(traverse_module_state->__pyx_n_s_copy); + Py_VISIT(traverse_module_state->__pyx_n_s_cp); + Py_VISIT(traverse_module_state->__pyx_n_s_cs); + Py_VISIT(traverse_module_state->__pyx_n_s_curated_tokenizers__bbpe); + Py_VISIT(traverse_module_state->__pyx_kp_s_curated_tokenizers__bbpe_pyx); + Py_VISIT(traverse_module_state->__pyx_n_s_decode); + Py_VISIT(traverse_module_state->__pyx_n_s_decode_from_ids); + Py_VISIT(traverse_module_state->__pyx_n_s_decoded); + Py_VISIT(traverse_module_state->__pyx_n_s_deepcopy); + Py_VISIT(traverse_module_state->__pyx_n_s_dict); + Py_VISIT(traverse_module_state->__pyx_kp_u_disable); + Py_VISIT(traverse_module_state->__pyx_kp_u_enable); + Py_VISIT(traverse_module_state->__pyx_n_s_encode); + Py_VISIT(traverse_module_state->__pyx_n_s_encode_as_ids); + Py_VISIT(traverse_module_state->__pyx_n_s_encode_as_pieces); + Py_VISIT(traverse_module_state->__pyx_n_s_encode_as_pieces_locals_genexpr); + Py_VISIT(traverse_module_state->__pyx_n_s_encoding); + Py_VISIT(traverse_module_state->__pyx_n_s_enter); + Py_VISIT(traverse_module_state->__pyx_n_s_exit); + Py_VISIT(traverse_module_state->__pyx_n_s_f); + Py_VISIT(traverse_module_state->__pyx_n_s_findall); + Py_VISIT(traverse_module_state->__pyx_n_s_functools); + Py_VISIT(traverse_module_state->__pyx_kp_u_gc); + Py_VISIT(traverse_module_state->__pyx_n_s_genexpr); + Py_VISIT(traverse_module_state->__pyx_n_s_get); + Py_VISIT(traverse_module_state->__pyx_n_s_getvalue); + Py_VISIT(traverse_module_state->__pyx_n_s_ids); + Py_VISIT(traverse_module_state->__pyx_n_s_import); + Py_VISIT(traverse_module_state->__pyx_n_s_initializing); + Py_VISIT(traverse_module_state->__pyx_n_s_io); + Py_VISIT(traverse_module_state->__pyx_n_s_is_coroutine); + Py_VISIT(traverse_module_state->__pyx_kp_u_isenabled); + Py_VISIT(traverse_module_state->__pyx_n_s_items); + Py_VISIT(traverse_module_state->__pyx_n_s_json); + Py_VISIT(traverse_module_state->__pyx_n_s_line); + Py_VISIT(traverse_module_state->__pyx_n_s_load); + Py_VISIT(traverse_module_state->__pyx_n_s_load_from_files); + Py_VISIT(traverse_module_state->__pyx_n_s_lru_cache); + Py_VISIT(traverse_module_state->__pyx_n_s_main); + Py_VISIT(traverse_module_state->__pyx_n_s_memo); + Py_VISIT(traverse_module_state->__pyx_n_s_merge); + Py_VISIT(traverse_module_state->__pyx_n_s_merged); + Py_VISIT(traverse_module_state->__pyx_n_s_merges); + Py_VISIT(traverse_module_state->__pyx_n_s_n); + Py_VISIT(traverse_module_state->__pyx_n_s_name); + Py_VISIT(traverse_module_state->__pyx_n_s_open); + Py_VISIT(traverse_module_state->__pyx_n_s_pathlib); + Py_VISIT(traverse_module_state->__pyx_n_s_piece); + Py_VISIT(traverse_module_state->__pyx_n_s_piece_id); + Py_VISIT(traverse_module_state->__pyx_n_s_piece_ids); + Py_VISIT(traverse_module_state->__pyx_n_s_pieces); + Py_VISIT(traverse_module_state->__pyx_n_s_pieces_to_ids); + Py_VISIT(traverse_module_state->__pyx_n_s_range); + Py_VISIT(traverse_module_state->__pyx_n_s_readline); + Py_VISIT(traverse_module_state->__pyx_n_s_reduce); + Py_VISIT(traverse_module_state->__pyx_n_s_regex); + Py_VISIT(traverse_module_state->__pyx_n_s_return); + Py_VISIT(traverse_module_state->__pyx_kp_s_s_t_re_ve_m_ll_d_p_L_p_N_s_p_L); + Py_VISIT(traverse_module_state->__pyx_n_s_self); + Py_VISIT(traverse_module_state->__pyx_n_s_send); + Py_VISIT(traverse_module_state->__pyx_n_s_spec); + Py_VISIT(traverse_module_state->__pyx_n_s_split); + Py_VISIT(traverse_module_state->__pyx_n_s_startswith); + Py_VISIT(traverse_module_state->__pyx_n_s_staticmethod); + Py_VISIT(traverse_module_state->__pyx_n_s_str); + Py_VISIT(traverse_module_state->__pyx_n_s_strip); + Py_VISIT(traverse_module_state->__pyx_n_s_test); + Py_VISIT(traverse_module_state->__pyx_n_s_text); + Py_VISIT(traverse_module_state->__pyx_n_s_throw); + Py_VISIT(traverse_module_state->__pyx_n_s_token); + Py_VISIT(traverse_module_state->__pyx_n_s_token_bytes); + Py_VISIT(traverse_module_state->__pyx_n_s_typing); + Py_VISIT(traverse_module_state->__pyx_n_s_unpickle_byte_bpe_processor); + Py_VISIT(traverse_module_state->__pyx_kp_s_utf_8); + Py_VISIT(traverse_module_state->__pyx_n_s_version); + Py_VISIT(traverse_module_state->__pyx_kp_s_version_0_2); + Py_VISIT(traverse_module_state->__pyx_n_s_vocab); + Py_VISIT(traverse_module_state->__pyx_n_s_write); + Py_VISIT(traverse_module_state->__pyx_n_s_zip); + Py_VISIT(traverse_module_state->__pyx_int_0); + Py_VISIT(traverse_module_state->__pyx_int_1); + Py_VISIT(traverse_module_state->__pyx_int_33); + Py_VISIT(traverse_module_state->__pyx_int_161); + Py_VISIT(traverse_module_state->__pyx_int_174); + Py_VISIT(traverse_module_state->__pyx_int_256); + Py_VISIT(traverse_module_state->__pyx_tuple_); + Py_VISIT(traverse_module_state->__pyx_tuple__6); + Py_VISIT(traverse_module_state->__pyx_tuple__8); + Py_VISIT(traverse_module_state->__pyx_tuple__10); + Py_VISIT(traverse_module_state->__pyx_tuple__12); + Py_VISIT(traverse_module_state->__pyx_tuple__14); + Py_VISIT(traverse_module_state->__pyx_tuple__16); + Py_VISIT(traverse_module_state->__pyx_tuple__19); + Py_VISIT(traverse_module_state->__pyx_tuple__21); + Py_VISIT(traverse_module_state->__pyx_tuple__23); + Py_VISIT(traverse_module_state->__pyx_tuple__26); + Py_VISIT(traverse_module_state->__pyx_codeobj__7); + Py_VISIT(traverse_module_state->__pyx_codeobj__9); + Py_VISIT(traverse_module_state->__pyx_codeobj__11); + Py_VISIT(traverse_module_state->__pyx_codeobj__13); + Py_VISIT(traverse_module_state->__pyx_codeobj__15); + Py_VISIT(traverse_module_state->__pyx_codeobj__17); + Py_VISIT(traverse_module_state->__pyx_codeobj__18); + Py_VISIT(traverse_module_state->__pyx_codeobj__20); + Py_VISIT(traverse_module_state->__pyx_codeobj__22); + Py_VISIT(traverse_module_state->__pyx_codeobj__24); + Py_VISIT(traverse_module_state->__pyx_codeobj__25); + Py_VISIT(traverse_module_state->__pyx_codeobj__27); + return 0; +} +#endif +/* #### Code section: module_state_defines ### */ +#define __pyx_d __pyx_mstate_global->__pyx_d +#define __pyx_b __pyx_mstate_global->__pyx_b +#define __pyx_cython_runtime __pyx_mstate_global->__pyx_cython_runtime +#define __pyx_empty_tuple __pyx_mstate_global->__pyx_empty_tuple +#define __pyx_empty_bytes __pyx_mstate_global->__pyx_empty_bytes +#define __pyx_empty_unicode __pyx_mstate_global->__pyx_empty_unicode +#ifdef __Pyx_CyFunction_USED +#define __pyx_CyFunctionType __pyx_mstate_global->__pyx_CyFunctionType +#endif +#ifdef __Pyx_FusedFunction_USED +#define __pyx_FusedFunctionType __pyx_mstate_global->__pyx_FusedFunctionType +#endif +#ifdef __Pyx_Generator_USED +#define __pyx_GeneratorType __pyx_mstate_global->__pyx_GeneratorType +#endif +#ifdef __Pyx_IterableCoroutine_USED +#define __pyx_IterableCoroutineType __pyx_mstate_global->__pyx_IterableCoroutineType +#endif +#ifdef __Pyx_Coroutine_USED +#define __pyx_CoroutineAwaitType __pyx_mstate_global->__pyx_CoroutineAwaitType +#endif +#ifdef __Pyx_Coroutine_USED +#define __pyx_CoroutineType __pyx_mstate_global->__pyx_CoroutineType +#endif +#if CYTHON_USE_MODULE_STATE +#endif +#if CYTHON_USE_MODULE_STATE +#endif +#if CYTHON_USE_MODULE_STATE +#endif +#if CYTHON_USE_MODULE_STATE +#endif +#if CYTHON_USE_MODULE_STATE +#endif +#if CYTHON_USE_MODULE_STATE +#endif +#if CYTHON_USE_MODULE_STATE +#define __pyx_type_18curated_tokenizers_5_bbpe_ByteBPEProcessor __pyx_mstate_global->__pyx_type_18curated_tokenizers_5_bbpe_ByteBPEProcessor +#define __pyx_type_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr __pyx_mstate_global->__pyx_type_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr +#endif +#define __pyx_ptype_18curated_tokenizers_5_bbpe_ByteBPEProcessor __pyx_mstate_global->__pyx_ptype_18curated_tokenizers_5_bbpe_ByteBPEProcessor +#define __pyx_ptype_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr __pyx_mstate_global->__pyx_ptype_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr +#define __pyx_n_s_ByteBPEProcessor __pyx_mstate_global->__pyx_n_s_ByteBPEProcessor +#define __pyx_n_s_ByteBPEProcessor___copy __pyx_mstate_global->__pyx_n_s_ByteBPEProcessor___copy +#define __pyx_n_s_ByteBPEProcessor___deepcopy __pyx_mstate_global->__pyx_n_s_ByteBPEProcessor___deepcopy +#define __pyx_n_s_ByteBPEProcessor___reduce __pyx_mstate_global->__pyx_n_s_ByteBPEProcessor___reduce +#define __pyx_n_s_ByteBPEProcessor__pieces_to_ids __pyx_mstate_global->__pyx_n_s_ByteBPEProcessor__pieces_to_ids +#define __pyx_n_s_ByteBPEProcessor_decode_from_ids __pyx_mstate_global->__pyx_n_s_ByteBPEProcessor_decode_from_ids +#define __pyx_n_s_ByteBPEProcessor_encode __pyx_mstate_global->__pyx_n_s_ByteBPEProcessor_encode +#define __pyx_n_s_ByteBPEProcessor_encode_as_ids __pyx_mstate_global->__pyx_n_s_ByteBPEProcessor_encode_as_ids +#define __pyx_n_s_ByteBPEProcessor_encode_as_piece __pyx_mstate_global->__pyx_n_s_ByteBPEProcessor_encode_as_piece +#define __pyx_n_s_ByteBPEProcessor_load_from_files __pyx_mstate_global->__pyx_n_s_ByteBPEProcessor_load_from_files +#define __pyx_n_s_ByteBPEProcessor_piece_id __pyx_mstate_global->__pyx_n_s_ByteBPEProcessor_piece_id +#define __pyx_n_s_BytesIO __pyx_mstate_global->__pyx_n_s_BytesIO +#define __pyx_n_s_Dict __pyx_mstate_global->__pyx_n_s_Dict +#define __pyx_kp_s_Dict_int_bytes __pyx_mstate_global->__pyx_kp_s_Dict_int_bytes +#define __pyx_kp_s_Dict_str_int __pyx_mstate_global->__pyx_kp_s_Dict_str_int +#define __pyx_n_s_Iterable __pyx_mstate_global->__pyx_n_s_Iterable +#define __pyx_kp_s_Iterable_int __pyx_mstate_global->__pyx_kp_s_Iterable_int +#define __pyx_n_s_List __pyx_mstate_global->__pyx_n_s_List +#define __pyx_kp_s_List_Tuple_str_str __pyx_mstate_global->__pyx_kp_s_List_Tuple_str_str +#define __pyx_kp_s_List_int __pyx_mstate_global->__pyx_kp_s_List_int +#define __pyx_kp_s_List_str __pyx_mstate_global->__pyx_kp_s_List_str +#define __pyx_kp_u_Merge_must_consist_of_2_items_wa __pyx_mstate_global->__pyx_kp_u_Merge_must_consist_of_2_items_wa +#define __pyx_kp_u_Only_version_0_2_of_the_merges_f __pyx_mstate_global->__pyx_kp_u_Only_version_0_2_of_the_merges_f +#define __pyx_n_s_Optional __pyx_mstate_global->__pyx_n_s_Optional +#define __pyx_kp_s_Optional_int __pyx_mstate_global->__pyx_kp_s_Optional_int +#define __pyx_n_s_Path __pyx_mstate_global->__pyx_n_s_Path +#define __pyx_kp_u_Piece_is_not_in_vocabulary __pyx_mstate_global->__pyx_kp_u_Piece_is_not_in_vocabulary +#define __pyx_n_s_SPLIT_PATTERN __pyx_mstate_global->__pyx_n_s_SPLIT_PATTERN +#define __pyx_n_s_Tuple __pyx_mstate_global->__pyx_n_s_Tuple +#define __pyx_kp_s_Tuple_List_int_List_str __pyx_mstate_global->__pyx_kp_s_Tuple_List_int_List_str +#define __pyx_kp_u_Unknown_piece_identifier __pyx_mstate_global->__pyx_kp_u_Unknown_piece_identifier +#define __pyx_n_s_ValueError __pyx_mstate_global->__pyx_n_s_ValueError +#define __pyx_kp_s__2 __pyx_mstate_global->__pyx_kp_s__2 +#define __pyx_n_s__28 __pyx_mstate_global->__pyx_n_s__28 +#define __pyx_kp_u__3 __pyx_mstate_global->__pyx_kp_u__3 +#define __pyx_kp_u__4 __pyx_mstate_global->__pyx_kp_u__4 +#define __pyx_n_s__5 __pyx_mstate_global->__pyx_n_s__5 +#define __pyx_n_s_append __pyx_mstate_global->__pyx_n_s_append +#define __pyx_n_s_args __pyx_mstate_global->__pyx_n_s_args +#define __pyx_n_s_asyncio_coroutines __pyx_mstate_global->__pyx_n_s_asyncio_coroutines +#define __pyx_n_s_b __pyx_mstate_global->__pyx_n_s_b +#define __pyx_n_s_bs __pyx_mstate_global->__pyx_n_s_bs +#define __pyx_n_s_bytes_to_unicode __pyx_mstate_global->__pyx_n_s_bytes_to_unicode +#define __pyx_n_s_chr __pyx_mstate_global->__pyx_n_s_chr +#define __pyx_n_s_cline_in_traceback __pyx_mstate_global->__pyx_n_s_cline_in_traceback +#define __pyx_n_s_close __pyx_mstate_global->__pyx_n_s_close +#define __pyx_n_s_compile __pyx_mstate_global->__pyx_n_s_compile +#define __pyx_n_s_copy __pyx_mstate_global->__pyx_n_s_copy +#define __pyx_n_s_cp __pyx_mstate_global->__pyx_n_s_cp +#define __pyx_n_s_cs __pyx_mstate_global->__pyx_n_s_cs +#define __pyx_n_s_curated_tokenizers__bbpe __pyx_mstate_global->__pyx_n_s_curated_tokenizers__bbpe +#define __pyx_kp_s_curated_tokenizers__bbpe_pyx __pyx_mstate_global->__pyx_kp_s_curated_tokenizers__bbpe_pyx +#define __pyx_n_s_decode __pyx_mstate_global->__pyx_n_s_decode +#define __pyx_n_s_decode_from_ids __pyx_mstate_global->__pyx_n_s_decode_from_ids +#define __pyx_n_s_decoded __pyx_mstate_global->__pyx_n_s_decoded +#define __pyx_n_s_deepcopy __pyx_mstate_global->__pyx_n_s_deepcopy +#define __pyx_n_s_dict __pyx_mstate_global->__pyx_n_s_dict +#define __pyx_kp_u_disable __pyx_mstate_global->__pyx_kp_u_disable +#define __pyx_kp_u_enable __pyx_mstate_global->__pyx_kp_u_enable +#define __pyx_n_s_encode __pyx_mstate_global->__pyx_n_s_encode +#define __pyx_n_s_encode_as_ids __pyx_mstate_global->__pyx_n_s_encode_as_ids +#define __pyx_n_s_encode_as_pieces __pyx_mstate_global->__pyx_n_s_encode_as_pieces +#define __pyx_n_s_encode_as_pieces_locals_genexpr __pyx_mstate_global->__pyx_n_s_encode_as_pieces_locals_genexpr +#define __pyx_n_s_encoding __pyx_mstate_global->__pyx_n_s_encoding +#define __pyx_n_s_enter __pyx_mstate_global->__pyx_n_s_enter +#define __pyx_n_s_exit __pyx_mstate_global->__pyx_n_s_exit +#define __pyx_n_s_f __pyx_mstate_global->__pyx_n_s_f +#define __pyx_n_s_findall __pyx_mstate_global->__pyx_n_s_findall +#define __pyx_n_s_functools __pyx_mstate_global->__pyx_n_s_functools +#define __pyx_kp_u_gc __pyx_mstate_global->__pyx_kp_u_gc +#define __pyx_n_s_genexpr __pyx_mstate_global->__pyx_n_s_genexpr +#define __pyx_n_s_get __pyx_mstate_global->__pyx_n_s_get +#define __pyx_n_s_getvalue __pyx_mstate_global->__pyx_n_s_getvalue +#define __pyx_n_s_ids __pyx_mstate_global->__pyx_n_s_ids +#define __pyx_n_s_import __pyx_mstate_global->__pyx_n_s_import +#define __pyx_n_s_initializing __pyx_mstate_global->__pyx_n_s_initializing +#define __pyx_n_s_io __pyx_mstate_global->__pyx_n_s_io +#define __pyx_n_s_is_coroutine __pyx_mstate_global->__pyx_n_s_is_coroutine +#define __pyx_kp_u_isenabled __pyx_mstate_global->__pyx_kp_u_isenabled +#define __pyx_n_s_items __pyx_mstate_global->__pyx_n_s_items +#define __pyx_n_s_json __pyx_mstate_global->__pyx_n_s_json +#define __pyx_n_s_line __pyx_mstate_global->__pyx_n_s_line +#define __pyx_n_s_load __pyx_mstate_global->__pyx_n_s_load +#define __pyx_n_s_load_from_files __pyx_mstate_global->__pyx_n_s_load_from_files +#define __pyx_n_s_lru_cache __pyx_mstate_global->__pyx_n_s_lru_cache +#define __pyx_n_s_main __pyx_mstate_global->__pyx_n_s_main +#define __pyx_n_s_memo __pyx_mstate_global->__pyx_n_s_memo +#define __pyx_n_s_merge __pyx_mstate_global->__pyx_n_s_merge +#define __pyx_n_s_merged __pyx_mstate_global->__pyx_n_s_merged +#define __pyx_n_s_merges __pyx_mstate_global->__pyx_n_s_merges +#define __pyx_n_s_n __pyx_mstate_global->__pyx_n_s_n +#define __pyx_n_s_name __pyx_mstate_global->__pyx_n_s_name +#define __pyx_n_s_open __pyx_mstate_global->__pyx_n_s_open +#define __pyx_n_s_pathlib __pyx_mstate_global->__pyx_n_s_pathlib +#define __pyx_n_s_piece __pyx_mstate_global->__pyx_n_s_piece +#define __pyx_n_s_piece_id __pyx_mstate_global->__pyx_n_s_piece_id +#define __pyx_n_s_piece_ids __pyx_mstate_global->__pyx_n_s_piece_ids +#define __pyx_n_s_pieces __pyx_mstate_global->__pyx_n_s_pieces +#define __pyx_n_s_pieces_to_ids __pyx_mstate_global->__pyx_n_s_pieces_to_ids +#define __pyx_n_s_range __pyx_mstate_global->__pyx_n_s_range +#define __pyx_n_s_readline __pyx_mstate_global->__pyx_n_s_readline +#define __pyx_n_s_reduce __pyx_mstate_global->__pyx_n_s_reduce +#define __pyx_n_s_regex __pyx_mstate_global->__pyx_n_s_regex +#define __pyx_n_s_return __pyx_mstate_global->__pyx_n_s_return +#define __pyx_kp_s_s_t_re_ve_m_ll_d_p_L_p_N_s_p_L __pyx_mstate_global->__pyx_kp_s_s_t_re_ve_m_ll_d_p_L_p_N_s_p_L +#define __pyx_n_s_self __pyx_mstate_global->__pyx_n_s_self +#define __pyx_n_s_send __pyx_mstate_global->__pyx_n_s_send +#define __pyx_n_s_spec __pyx_mstate_global->__pyx_n_s_spec +#define __pyx_n_s_split __pyx_mstate_global->__pyx_n_s_split +#define __pyx_n_s_startswith __pyx_mstate_global->__pyx_n_s_startswith +#define __pyx_n_s_staticmethod __pyx_mstate_global->__pyx_n_s_staticmethod +#define __pyx_n_s_str __pyx_mstate_global->__pyx_n_s_str +#define __pyx_n_s_strip __pyx_mstate_global->__pyx_n_s_strip +#define __pyx_n_s_test __pyx_mstate_global->__pyx_n_s_test +#define __pyx_n_s_text __pyx_mstate_global->__pyx_n_s_text +#define __pyx_n_s_throw __pyx_mstate_global->__pyx_n_s_throw +#define __pyx_n_s_token __pyx_mstate_global->__pyx_n_s_token +#define __pyx_n_s_token_bytes __pyx_mstate_global->__pyx_n_s_token_bytes +#define __pyx_n_s_typing __pyx_mstate_global->__pyx_n_s_typing +#define __pyx_n_s_unpickle_byte_bpe_processor __pyx_mstate_global->__pyx_n_s_unpickle_byte_bpe_processor +#define __pyx_kp_s_utf_8 __pyx_mstate_global->__pyx_kp_s_utf_8 +#define __pyx_n_s_version __pyx_mstate_global->__pyx_n_s_version +#define __pyx_kp_s_version_0_2 __pyx_mstate_global->__pyx_kp_s_version_0_2 +#define __pyx_n_s_vocab __pyx_mstate_global->__pyx_n_s_vocab +#define __pyx_n_s_write __pyx_mstate_global->__pyx_n_s_write +#define __pyx_n_s_zip __pyx_mstate_global->__pyx_n_s_zip +#define __pyx_int_0 __pyx_mstate_global->__pyx_int_0 +#define __pyx_int_1 __pyx_mstate_global->__pyx_int_1 +#define __pyx_int_33 __pyx_mstate_global->__pyx_int_33 +#define __pyx_int_161 __pyx_mstate_global->__pyx_int_161 +#define __pyx_int_174 __pyx_mstate_global->__pyx_int_174 +#define __pyx_int_256 __pyx_mstate_global->__pyx_int_256 +#define __pyx_tuple_ __pyx_mstate_global->__pyx_tuple_ +#define __pyx_tuple__6 __pyx_mstate_global->__pyx_tuple__6 +#define __pyx_tuple__8 __pyx_mstate_global->__pyx_tuple__8 +#define __pyx_tuple__10 __pyx_mstate_global->__pyx_tuple__10 +#define __pyx_tuple__12 __pyx_mstate_global->__pyx_tuple__12 +#define __pyx_tuple__14 __pyx_mstate_global->__pyx_tuple__14 +#define __pyx_tuple__16 __pyx_mstate_global->__pyx_tuple__16 +#define __pyx_tuple__19 __pyx_mstate_global->__pyx_tuple__19 +#define __pyx_tuple__21 __pyx_mstate_global->__pyx_tuple__21 +#define __pyx_tuple__23 __pyx_mstate_global->__pyx_tuple__23 +#define __pyx_tuple__26 __pyx_mstate_global->__pyx_tuple__26 +#define __pyx_codeobj__7 __pyx_mstate_global->__pyx_codeobj__7 +#define __pyx_codeobj__9 __pyx_mstate_global->__pyx_codeobj__9 +#define __pyx_codeobj__11 __pyx_mstate_global->__pyx_codeobj__11 +#define __pyx_codeobj__13 __pyx_mstate_global->__pyx_codeobj__13 +#define __pyx_codeobj__15 __pyx_mstate_global->__pyx_codeobj__15 +#define __pyx_codeobj__17 __pyx_mstate_global->__pyx_codeobj__17 +#define __pyx_codeobj__18 __pyx_mstate_global->__pyx_codeobj__18 +#define __pyx_codeobj__20 __pyx_mstate_global->__pyx_codeobj__20 +#define __pyx_codeobj__22 __pyx_mstate_global->__pyx_codeobj__22 +#define __pyx_codeobj__24 __pyx_mstate_global->__pyx_codeobj__24 +#define __pyx_codeobj__25 __pyx_mstate_global->__pyx_codeobj__25 +#define __pyx_codeobj__27 __pyx_mstate_global->__pyx_codeobj__27 +/* #### Code section: module_code ### */ + +/* "string.from_py":13 + * + * @cname("__pyx_convert_string_from_py_std__in_string") + * cdef string __pyx_convert_string_from_py_std__in_string(object o) except *: # <<<<<<<<<<<<<< + * cdef Py_ssize_t length = 0 + * cdef const char* data = __Pyx_PyObject_AsStringAndSize(o, &length) + */ + +static std::string __pyx_convert_string_from_py_std__in_string(PyObject *__pyx_v_o) { + Py_ssize_t __pyx_v_length; + char const *__pyx_v_data; + std::string __pyx_r; + char const *__pyx_t_1; + std::string __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "string.from_py":14 + * @cname("__pyx_convert_string_from_py_std__in_string") + * cdef string __pyx_convert_string_from_py_std__in_string(object o) except *: + * cdef Py_ssize_t length = 0 # <<<<<<<<<<<<<< + * cdef const char* data = __Pyx_PyObject_AsStringAndSize(o, &length) + * return string(data, length) + */ + __pyx_v_length = 0; + + /* "string.from_py":15 + * cdef string __pyx_convert_string_from_py_std__in_string(object o) except *: + * cdef Py_ssize_t length = 0 + * cdef const char* data = __Pyx_PyObject_AsStringAndSize(o, &length) # <<<<<<<<<<<<<< + * return string(data, length) + * + */ + __pyx_t_1 = __Pyx_PyObject_AsStringAndSize(__pyx_v_o, (&__pyx_v_length)); if (unlikely(__pyx_t_1 == ((char const *)NULL))) __PYX_ERR(1, 15, __pyx_L1_error) + __pyx_v_data = __pyx_t_1; + + /* "string.from_py":16 + * cdef Py_ssize_t length = 0 + * cdef const char* data = __Pyx_PyObject_AsStringAndSize(o, &length) + * return string(data, length) # <<<<<<<<<<<<<< + * + * + */ + try { + __pyx_t_2 = std::string(__pyx_v_data, __pyx_v_length); + } catch(...) { + __Pyx_CppExn2PyErr(); + __PYX_ERR(1, 16, __pyx_L1_error) + } + __pyx_r = __pyx_t_2; + goto __pyx_L0; + + /* "string.from_py":13 + * + * @cname("__pyx_convert_string_from_py_std__in_string") + * cdef string __pyx_convert_string_from_py_std__in_string(object o) except *: # <<<<<<<<<<<<<< + * cdef Py_ssize_t length = 0 + * cdef const char* data = __Pyx_PyObject_AsStringAndSize(o, &length) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("string.from_py.__pyx_convert_string_from_py_std__in_string", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_pretend_to_initialize(&__pyx_r); + __pyx_L0:; + return __pyx_r; +} + +/* "vector.from_py":45 + * + * @cname("__pyx_convert_vector_from_py_std_3a__3a_string") + * cdef vector[X] __pyx_convert_vector_from_py_std_3a__3a_string(object o) except *: # <<<<<<<<<<<<<< + * cdef vector[X] v + * for item in o: + */ + +static std::vector __pyx_convert_vector_from_py_std_3a__3a_string(PyObject *__pyx_v_o) { + std::vector __pyx_v_v; + PyObject *__pyx_v_item = NULL; + std::vector __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + Py_ssize_t __pyx_t_2; + PyObject *(*__pyx_t_3)(PyObject *); + PyObject *__pyx_t_4 = NULL; + std::string __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__pyx_convert_vector_from_py_std_3a__3a_string", 1); + + /* "vector.from_py":47 + * cdef vector[X] __pyx_convert_vector_from_py_std_3a__3a_string(object o) except *: + * cdef vector[X] v + * for item in o: # <<<<<<<<<<<<<< + * v.push_back(item) + * return v + */ + if (likely(PyList_CheckExact(__pyx_v_o)) || PyTuple_CheckExact(__pyx_v_o)) { + __pyx_t_1 = __pyx_v_o; __Pyx_INCREF(__pyx_t_1); + __pyx_t_2 = 0; + __pyx_t_3 = NULL; + } else { + __pyx_t_2 = -1; __pyx_t_1 = PyObject_GetIter(__pyx_v_o); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 47, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PyObject_GetIterNextFunc(__pyx_t_1); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 47, __pyx_L1_error) + } + for (;;) { + if (likely(!__pyx_t_3)) { + if (likely(PyList_CheckExact(__pyx_t_1))) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_1); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((__pyx_temp < 0))) __PYX_ERR(1, 47, __pyx_L1_error) + #endif + if (__pyx_t_2 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_4 = PyList_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_4); __pyx_t_2++; if (unlikely((0 < 0))) __PYX_ERR(1, 47, __pyx_L1_error) + #else + __pyx_t_4 = __Pyx_PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 47, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + #endif + } else { + { + Py_ssize_t __pyx_temp = __Pyx_PyTuple_GET_SIZE(__pyx_t_1); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((__pyx_temp < 0))) __PYX_ERR(1, 47, __pyx_L1_error) + #endif + if (__pyx_t_2 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_4 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_4); __pyx_t_2++; if (unlikely((0 < 0))) __PYX_ERR(1, 47, __pyx_L1_error) + #else + __pyx_t_4 = __Pyx_PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 47, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + #endif + } + } else { + __pyx_t_4 = __pyx_t_3(__pyx_t_1); + if (unlikely(!__pyx_t_4)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else __PYX_ERR(1, 47, __pyx_L1_error) + } + break; + } + __Pyx_GOTREF(__pyx_t_4); + } + __Pyx_XDECREF_SET(__pyx_v_item, __pyx_t_4); + __pyx_t_4 = 0; + + /* "vector.from_py":48 + * cdef vector[X] v + * for item in o: + * v.push_back(item) # <<<<<<<<<<<<<< + * return v + * + */ + __pyx_t_5 = __pyx_convert_string_from_py_std__in_string(__pyx_v_item); if (unlikely(PyErr_Occurred())) __PYX_ERR(1, 48, __pyx_L1_error) + try { + __pyx_v_v.push_back(((std::string)__pyx_t_5)); + } catch(...) { + __Pyx_CppExn2PyErr(); + __PYX_ERR(1, 48, __pyx_L1_error) + } + + /* "vector.from_py":47 + * cdef vector[X] __pyx_convert_vector_from_py_std_3a__3a_string(object o) except *: + * cdef vector[X] v + * for item in o: # <<<<<<<<<<<<<< + * v.push_back(item) + * return v + */ + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "vector.from_py":49 + * for item in o: + * v.push_back(item) + * return v # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = __pyx_v_v; + goto __pyx_L0; + + /* "vector.from_py":45 + * + * @cname("__pyx_convert_vector_from_py_std_3a__3a_string") + * cdef vector[X] __pyx_convert_vector_from_py_std_3a__3a_string(object o) except *: # <<<<<<<<<<<<<< + * cdef vector[X] v + * for item in o: + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("vector.from_py.__pyx_convert_vector_from_py_std_3a__3a_string", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_pretend_to_initialize(&__pyx_r); + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_item); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "string.to_py":31 + * + * @cname("__pyx_convert_PyObject_string_to_py_std__in_string") + * cdef inline object __pyx_convert_PyObject_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< + * return __Pyx_PyObject_FromStringAndSize(s.data(), s.size()) + * cdef extern from *: + */ + +static CYTHON_INLINE PyObject *__pyx_convert_PyObject_string_to_py_std__in_string(std::string const &__pyx_v_s) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__pyx_convert_PyObject_string_to_py_std__in_string", 1); + + /* "string.to_py":32 + * @cname("__pyx_convert_PyObject_string_to_py_std__in_string") + * cdef inline object __pyx_convert_PyObject_string_to_py_std__in_string(const string& s): + * return __Pyx_PyObject_FromStringAndSize(s.data(), s.size()) # <<<<<<<<<<<<<< + * cdef extern from *: + * cdef object __Pyx_PyUnicode_FromStringAndSize(const char*, size_t) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_FromStringAndSize(__pyx_v_s.data(), __pyx_v_s.size()); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 32, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "string.to_py":31 + * + * @cname("__pyx_convert_PyObject_string_to_py_std__in_string") + * cdef inline object __pyx_convert_PyObject_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< + * return __Pyx_PyObject_FromStringAndSize(s.data(), s.size()) + * cdef extern from *: + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("string.to_py.__pyx_convert_PyObject_string_to_py_std__in_string", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "string.to_py":37 + * + * @cname("__pyx_convert_PyUnicode_string_to_py_std__in_string") + * cdef inline object __pyx_convert_PyUnicode_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< + * return __Pyx_PyUnicode_FromStringAndSize(s.data(), s.size()) + * cdef extern from *: + */ + +static CYTHON_INLINE PyObject *__pyx_convert_PyUnicode_string_to_py_std__in_string(std::string const &__pyx_v_s) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__pyx_convert_PyUnicode_string_to_py_std__in_string", 1); + + /* "string.to_py":38 + * @cname("__pyx_convert_PyUnicode_string_to_py_std__in_string") + * cdef inline object __pyx_convert_PyUnicode_string_to_py_std__in_string(const string& s): + * return __Pyx_PyUnicode_FromStringAndSize(s.data(), s.size()) # <<<<<<<<<<<<<< + * cdef extern from *: + * cdef object __Pyx_PyStr_FromStringAndSize(const char*, size_t) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyUnicode_FromStringAndSize(__pyx_v_s.data(), __pyx_v_s.size()); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 38, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "string.to_py":37 + * + * @cname("__pyx_convert_PyUnicode_string_to_py_std__in_string") + * cdef inline object __pyx_convert_PyUnicode_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< + * return __Pyx_PyUnicode_FromStringAndSize(s.data(), s.size()) + * cdef extern from *: + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("string.to_py.__pyx_convert_PyUnicode_string_to_py_std__in_string", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "string.to_py":43 + * + * @cname("__pyx_convert_PyStr_string_to_py_std__in_string") + * cdef inline object __pyx_convert_PyStr_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< + * return __Pyx_PyStr_FromStringAndSize(s.data(), s.size()) + * cdef extern from *: + */ + +static CYTHON_INLINE PyObject *__pyx_convert_PyStr_string_to_py_std__in_string(std::string const &__pyx_v_s) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__pyx_convert_PyStr_string_to_py_std__in_string", 1); + + /* "string.to_py":44 + * @cname("__pyx_convert_PyStr_string_to_py_std__in_string") + * cdef inline object __pyx_convert_PyStr_string_to_py_std__in_string(const string& s): + * return __Pyx_PyStr_FromStringAndSize(s.data(), s.size()) # <<<<<<<<<<<<<< + * cdef extern from *: + * cdef object __Pyx_PyBytes_FromStringAndSize(const char*, size_t) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyStr_FromStringAndSize(__pyx_v_s.data(), __pyx_v_s.size()); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 44, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "string.to_py":43 + * + * @cname("__pyx_convert_PyStr_string_to_py_std__in_string") + * cdef inline object __pyx_convert_PyStr_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< + * return __Pyx_PyStr_FromStringAndSize(s.data(), s.size()) + * cdef extern from *: + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("string.to_py.__pyx_convert_PyStr_string_to_py_std__in_string", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "string.to_py":49 + * + * @cname("__pyx_convert_PyBytes_string_to_py_std__in_string") + * cdef inline object __pyx_convert_PyBytes_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< + * return __Pyx_PyBytes_FromStringAndSize(s.data(), s.size()) + * cdef extern from *: + */ + +static CYTHON_INLINE PyObject *__pyx_convert_PyBytes_string_to_py_std__in_string(std::string const &__pyx_v_s) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__pyx_convert_PyBytes_string_to_py_std__in_string", 1); + + /* "string.to_py":50 + * @cname("__pyx_convert_PyBytes_string_to_py_std__in_string") + * cdef inline object __pyx_convert_PyBytes_string_to_py_std__in_string(const string& s): + * return __Pyx_PyBytes_FromStringAndSize(s.data(), s.size()) # <<<<<<<<<<<<<< + * cdef extern from *: + * cdef object __Pyx_PyByteArray_FromStringAndSize(const char*, size_t) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyBytes_FromStringAndSize(__pyx_v_s.data(), __pyx_v_s.size()); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 50, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "string.to_py":49 + * + * @cname("__pyx_convert_PyBytes_string_to_py_std__in_string") + * cdef inline object __pyx_convert_PyBytes_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< + * return __Pyx_PyBytes_FromStringAndSize(s.data(), s.size()) + * cdef extern from *: + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("string.to_py.__pyx_convert_PyBytes_string_to_py_std__in_string", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "string.to_py":55 + * + * @cname("__pyx_convert_PyByteArray_string_to_py_std__in_string") + * cdef inline object __pyx_convert_PyByteArray_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< + * return __Pyx_PyByteArray_FromStringAndSize(s.data(), s.size()) + * + */ + +static CYTHON_INLINE PyObject *__pyx_convert_PyByteArray_string_to_py_std__in_string(std::string const &__pyx_v_s) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__pyx_convert_PyByteArray_string_to_py_std__in_string", 1); + + /* "string.to_py":56 + * @cname("__pyx_convert_PyByteArray_string_to_py_std__in_string") + * cdef inline object __pyx_convert_PyByteArray_string_to_py_std__in_string(const string& s): + * return __Pyx_PyByteArray_FromStringAndSize(s.data(), s.size()) # <<<<<<<<<<<<<< + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyByteArray_FromStringAndSize(__pyx_v_s.data(), __pyx_v_s.size()); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 56, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "string.to_py":55 + * + * @cname("__pyx_convert_PyByteArray_string_to_py_std__in_string") + * cdef inline object __pyx_convert_PyByteArray_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< + * return __Pyx_PyByteArray_FromStringAndSize(s.data(), s.size()) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("string.to_py.__pyx_convert_PyByteArray_string_to_py_std__in_string", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pair.to_py":190 + * + * @cname("__pyx_convert_pair_to_py_std_3a__3a_string____std_3a__3a_string") + * cdef object __pyx_convert_pair_to_py_std_3a__3a_string____std_3a__3a_string(const pair[X,Y]& p): # <<<<<<<<<<<<<< + * return p.first, p.second + * + */ + +static PyObject *__pyx_convert_pair_to_py_std_3a__3a_string____std_3a__3a_string(std::pair const &__pyx_v_p) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__pyx_convert_pair_to_py_std_3a__3a_string____std_3a__3a_string", 1); + + /* "pair.to_py":191 + * @cname("__pyx_convert_pair_to_py_std_3a__3a_string____std_3a__3a_string") + * cdef object __pyx_convert_pair_to_py_std_3a__3a_string____std_3a__3a_string(const pair[X,Y]& p): + * return p.first, p.second # <<<<<<<<<<<<<< + * + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __pyx_convert_PyBytes_string_to_py_std__in_string(__pyx_v_p.first); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 191, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __pyx_convert_PyBytes_string_to_py_std__in_string(__pyx_v_p.second); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 191, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 191, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_GIVEREF(__pyx_t_1); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1)) __PYX_ERR(1, 191, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_2); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_2)) __PYX_ERR(1, 191, __pyx_L1_error); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + + /* "pair.to_py":190 + * + * @cname("__pyx_convert_pair_to_py_std_3a__3a_string____std_3a__3a_string") + * cdef object __pyx_convert_pair_to_py_std_3a__3a_string____std_3a__3a_string(const pair[X,Y]& p): # <<<<<<<<<<<<<< + * return p.first, p.second + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("pair.to_py.__pyx_convert_pair_to_py_std_3a__3a_string____std_3a__3a_string", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_bbpe.pyx":24 + * + * + * @lru_cache() # <<<<<<<<<<<<<< + * def bytes_to_unicode() -> Dict[int, bytes]: + * """ + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_18curated_tokenizers_5_bbpe_1bytes_to_unicode(PyObject *__pyx_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +PyDoc_STRVAR(__pyx_doc_18curated_tokenizers_5_bbpe_bytes_to_unicode, "bytes_to_unicode() -> Dict[int, bytes]\n\n Returns list of utf-8 byte and a corresponding list of unicode strings.\n The reversible bpe codes work on unicode strings.\n This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.\n When you're at something like a 10B token dataset you end up needing around 5K for decent coverage.\n This is a signficant percentage of your normal, say, 32K bpe vocab.\n To avoid that, we want lookup tables between utf-8 bytes and unicode strings.\n And avoids mapping to whitespace/control characters the bpe code barfs on.\n "); +static PyMethodDef __pyx_mdef_18curated_tokenizers_5_bbpe_1bytes_to_unicode = {"bytes_to_unicode", (PyCFunction)__pyx_pw_18curated_tokenizers_5_bbpe_1bytes_to_unicode, METH_NOARGS, __pyx_doc_18curated_tokenizers_5_bbpe_bytes_to_unicode}; +static PyObject *__pyx_pw_18curated_tokenizers_5_bbpe_1bytes_to_unicode(PyObject *__pyx_self, CYTHON_UNUSED PyObject *unused) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("bytes_to_unicode (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_18curated_tokenizers_5_bbpe_bytes_to_unicode(__pyx_self); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_18curated_tokenizers_5_bbpe_bytes_to_unicode(CYTHON_UNUSED PyObject *__pyx_self) { + PyObject *__pyx_v_bs = NULL; + PyObject *__pyx_v_cs = NULL; + PyObject *__pyx_v_n = NULL; + long __pyx_v_b; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + long __pyx_t_4; + int __pyx_t_5; + int __pyx_t_6; + Py_ssize_t __pyx_t_7; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + int __pyx_t_10; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("bytes_to_unicode", 1); + + /* "curated_tokenizers/_bbpe.pyx":36 + * """ + * bs = ( + * list(range(ord("!"), ord("~") + 1)) # <<<<<<<<<<<<<< + * + list(range(ord(""), ord("") + 1)) + * + list(range(ord(""), ord("") + 1)) + */ + __pyx_t_1 = __Pyx_PyInt_From_long((0x7E + 1)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 36, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 36, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_int_33); + __Pyx_GIVEREF(__pyx_int_33); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_int_33)) __PYX_ERR(0, 36, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_1); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_1)) __PYX_ERR(0, 36, __pyx_L1_error); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_range, __pyx_t_2, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 36, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PySequence_ListKeepNew(__pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 36, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "curated_tokenizers/_bbpe.pyx":37 + * bs = ( + * list(range(ord("!"), ord("~") + 1)) + * + list(range(ord(""), ord("") + 1)) # <<<<<<<<<<<<<< + * + list(range(ord(""), ord("") + 1)) + * ) + */ + __pyx_t_1 = __Pyx_PyInt_From_long((0xAC + 1)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 37, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 37, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_int_161); + __Pyx_GIVEREF(__pyx_int_161); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_int_161)) __PYX_ERR(0, 37, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_1); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1)) __PYX_ERR(0, 37, __pyx_L1_error); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_range, __pyx_t_3, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 37, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PySequence_ListKeepNew(__pyx_t_1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 37, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyNumber_Add(__pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 37, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "curated_tokenizers/_bbpe.pyx":38 + * list(range(ord("!"), ord("~") + 1)) + * + list(range(ord(""), ord("") + 1)) + * + list(range(ord(""), ord("") + 1)) # <<<<<<<<<<<<<< + * ) + * cs = bs[:] + */ + __pyx_t_3 = __Pyx_PyInt_From_long((0xFF + 1)); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 38, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 38, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_int_174); + __Pyx_GIVEREF(__pyx_int_174); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_int_174)) __PYX_ERR(0, 38, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_3); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_3)) __PYX_ERR(0, 38, __pyx_L1_error); + __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_range, __pyx_t_2, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 38, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PySequence_ListKeepNew(__pyx_t_3); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 38, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyNumber_Add(__pyx_t_1, __pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 38, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v_bs = ((PyObject*)__pyx_t_3); + __pyx_t_3 = 0; + + /* "curated_tokenizers/_bbpe.pyx":40 + * + list(range(ord(""), ord("") + 1)) + * ) + * cs = bs[:] # <<<<<<<<<<<<<< + * n = 0 + * for b in range(2**8): + */ + __pyx_t_3 = __Pyx_PyList_GetSlice(__pyx_v_bs, 0, PY_SSIZE_T_MAX); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 40, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_v_cs = ((PyObject*)__pyx_t_3); + __pyx_t_3 = 0; + + /* "curated_tokenizers/_bbpe.pyx":41 + * ) + * cs = bs[:] + * n = 0 # <<<<<<<<<<<<<< + * for b in range(2**8): + * if b not in bs: + */ + __Pyx_INCREF(__pyx_int_0); + __pyx_v_n = __pyx_int_0; + + /* "curated_tokenizers/_bbpe.pyx":42 + * cs = bs[:] + * n = 0 + * for b in range(2**8): # <<<<<<<<<<<<<< + * if b not in bs: + * bs.append(b) + */ + for (__pyx_t_4 = 0; __pyx_t_4 < 0x100; __pyx_t_4+=1) { + __pyx_v_b = __pyx_t_4; + + /* "curated_tokenizers/_bbpe.pyx":43 + * n = 0 + * for b in range(2**8): + * if b not in bs: # <<<<<<<<<<<<<< + * bs.append(b) + * cs.append(2**8 + n) + */ + __pyx_t_3 = __Pyx_PyInt_From_long(__pyx_v_b); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 43, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = (__Pyx_PySequence_ContainsTF(__pyx_t_3, __pyx_v_bs, Py_NE)); if (unlikely((__pyx_t_5 < 0))) __PYX_ERR(0, 43, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_5) { + + /* "curated_tokenizers/_bbpe.pyx":44 + * for b in range(2**8): + * if b not in bs: + * bs.append(b) # <<<<<<<<<<<<<< + * cs.append(2**8 + n) + * n += 1 + */ + __pyx_t_3 = __Pyx_PyInt_From_long(__pyx_v_b); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 44, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_6 = __Pyx_PyList_Append(__pyx_v_bs, __pyx_t_3); if (unlikely(__pyx_t_6 == ((int)-1))) __PYX_ERR(0, 44, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "curated_tokenizers/_bbpe.pyx":45 + * if b not in bs: + * bs.append(b) + * cs.append(2**8 + n) # <<<<<<<<<<<<<< + * n += 1 + * cs = [chr(n).encode("utf-8") for n in cs] + */ + __pyx_t_3 = __Pyx_PyInt_AddCObj(__pyx_int_256, __pyx_v_n, 0x100, 0, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 45, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_6 = __Pyx_PyList_Append(__pyx_v_cs, __pyx_t_3); if (unlikely(__pyx_t_6 == ((int)-1))) __PYX_ERR(0, 45, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "curated_tokenizers/_bbpe.pyx":46 + * bs.append(b) + * cs.append(2**8 + n) + * n += 1 # <<<<<<<<<<<<<< + * cs = [chr(n).encode("utf-8") for n in cs] + * return dict(zip(bs, cs)) + */ + __pyx_t_3 = __Pyx_PyInt_AddObjC(__pyx_v_n, __pyx_int_1, 1, 1, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 46, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF_SET(__pyx_v_n, __pyx_t_3); + __pyx_t_3 = 0; + + /* "curated_tokenizers/_bbpe.pyx":43 + * n = 0 + * for b in range(2**8): + * if b not in bs: # <<<<<<<<<<<<<< + * bs.append(b) + * cs.append(2**8 + n) + */ + } + } + + /* "curated_tokenizers/_bbpe.pyx":47 + * cs.append(2**8 + n) + * n += 1 + * cs = [chr(n).encode("utf-8") for n in cs] # <<<<<<<<<<<<<< + * return dict(zip(bs, cs)) + * + */ + __pyx_t_3 = PyList_New(0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 47, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __pyx_v_cs; __Pyx_INCREF(__pyx_t_2); + __pyx_t_7 = 0; + for (;;) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_2); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 47, __pyx_L1_error) + #endif + if (__pyx_t_7 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_1 = PyList_GET_ITEM(__pyx_t_2, __pyx_t_7); __Pyx_INCREF(__pyx_t_1); __pyx_t_7++; if (unlikely((0 < 0))) __PYX_ERR(0, 47, __pyx_L1_error) + #else + __pyx_t_1 = __Pyx_PySequence_ITEM(__pyx_t_2, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 47, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + #endif + __Pyx_DECREF_SET(__pyx_v_n, __pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_8 = __Pyx_PyObject_CallOneArg(__pyx_builtin_chr, __pyx_v_n); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 47, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_t_8, __pyx_n_s_encode); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 47, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_8 = NULL; + __pyx_t_10 = 0; + #if CYTHON_UNPACK_METHODS + if (likely(PyMethod_Check(__pyx_t_9))) { + __pyx_t_8 = PyMethod_GET_SELF(__pyx_t_9); + if (likely(__pyx_t_8)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_9); + __Pyx_INCREF(__pyx_t_8); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_9, function); + __pyx_t_10 = 1; + } + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_8, __pyx_kp_s_utf_8}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_9, __pyx_callargs+1-__pyx_t_10, 1+__pyx_t_10); + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 47, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + } + if (unlikely(__Pyx_ListComp_Append(__pyx_t_3, (PyObject*)__pyx_t_1))) __PYX_ERR(0, 47, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF_SET(__pyx_v_cs, ((PyObject*)__pyx_t_3)); + __pyx_t_3 = 0; + + /* "curated_tokenizers/_bbpe.pyx":48 + * n += 1 + * cs = [chr(n).encode("utf-8") for n in cs] + * return dict(zip(bs, cs)) # <<<<<<<<<<<<<< + * + * cdef class ByteBPEProcessor: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 48, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_bs); + __Pyx_GIVEREF(__pyx_v_bs); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_bs)) __PYX_ERR(0, 48, __pyx_L1_error); + __Pyx_INCREF(__pyx_v_cs); + __Pyx_GIVEREF(__pyx_v_cs); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_v_cs)) __PYX_ERR(0, 48, __pyx_L1_error); + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_builtin_zip, __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 48, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_CallOneArg(((PyObject *)(&PyDict_Type)), __pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 48, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + + /* "curated_tokenizers/_bbpe.pyx":24 + * + * + * @lru_cache() # <<<<<<<<<<<<<< + * def bytes_to_unicode() -> Dict[int, bytes]: + * """ + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_AddTraceback("curated_tokenizers._bbpe.bytes_to_unicode", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_bs); + __Pyx_XDECREF(__pyx_v_cs); + __Pyx_XDECREF(__pyx_v_n); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_bbpe.pyx":58 + * cdef dict _id_to_piece + * + * def __init__(self, vocab: Dict[str, int], merges: List[Tuple[str, str]]): # <<<<<<<<<<<<<< + * self._byte_encoder = bytes_to_unicode() + * self._byte_decoder = {v.decode("utf-8"): k for k, v in self._byte_encoder.items()} + */ + +/* Python wrapper */ +static int __pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_vocab = 0; + PyObject *__pyx_v_merges = 0; + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[2] = {0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); + #if CYTHON_ASSUME_SAFE_MACROS + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return -1; + #endif + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + { + PyObject **__pyx_pyargnames[] = {&__pyx_n_s_vocab,&__pyx_n_s_merges,0}; + if (__pyx_kwds) { + Py_ssize_t kw_args; + switch (__pyx_nargs) { + case 2: values[1] = __Pyx_Arg_VARARGS(__pyx_args, 1); + CYTHON_FALLTHROUGH; + case 1: values[0] = __Pyx_Arg_VARARGS(__pyx_args, 0); + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = __Pyx_NumKwargs_VARARGS(__pyx_kwds); + switch (__pyx_nargs) { + case 0: + if (likely((values[0] = __Pyx_GetKwValue_VARARGS(__pyx_kwds, __pyx_kwvalues, __pyx_n_s_vocab)) != 0)) { + (void)__Pyx_Arg_NewRef_VARARGS(values[0]); + kw_args--; + } + else if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 58, __pyx_L3_error) + else goto __pyx_L5_argtuple_error; + CYTHON_FALLTHROUGH; + case 1: + if (likely((values[1] = __Pyx_GetKwValue_VARARGS(__pyx_kwds, __pyx_kwvalues, __pyx_n_s_merges)) != 0)) { + (void)__Pyx_Arg_NewRef_VARARGS(values[1]); + kw_args--; + } + else if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 58, __pyx_L3_error) + else { + __Pyx_RaiseArgtupleInvalid("__init__", 1, 2, 2, 1); __PYX_ERR(0, 58, __pyx_L3_error) + } + } + if (unlikely(kw_args > 0)) { + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values + 0, kwd_pos_args, "__init__") < 0)) __PYX_ERR(0, 58, __pyx_L3_error) + } + } else if (unlikely(__pyx_nargs != 2)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_Arg_VARARGS(__pyx_args, 0); + values[1] = __Pyx_Arg_VARARGS(__pyx_args, 1); + } + __pyx_v_vocab = values[0]; + __pyx_v_merges = values[1]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__init__", 1, 2, 2, __pyx_nargs); __PYX_ERR(0, 58, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_VARARGS(values[__pyx_temp]); + } + } + __Pyx_AddTraceback("curated_tokenizers._bbpe.ByteBPEProcessor.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_18curated_tokenizers_5_bbpe_16ByteBPEProcessor___init__(((struct __pyx_obj_18curated_tokenizers_5_bbpe_ByteBPEProcessor *)__pyx_v_self), __pyx_v_vocab, __pyx_v_merges); + + /* function exit code */ + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_VARARGS(values[__pyx_temp]); + } + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_18curated_tokenizers_5_bbpe_16ByteBPEProcessor___init__(struct __pyx_obj_18curated_tokenizers_5_bbpe_ByteBPEProcessor *__pyx_v_self, PyObject *__pyx_v_vocab, PyObject *__pyx_v_merges) { + std::vector > __pyx_v_c_merges; + PyObject *__pyx_v_p1 = NULL; + PyObject *__pyx_v_p2 = NULL; + PyObject *__pyx_7genexpr__pyx_v_k = NULL; + PyObject *__pyx_7genexpr__pyx_v_v = NULL; + PyObject *__pyx_8genexpr1__pyx_v_k = NULL; + PyObject *__pyx_8genexpr1__pyx_v_v = NULL; + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_t_4; + Py_ssize_t __pyx_t_5; + PyObject *(*__pyx_t_6)(PyObject *); + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + PyObject *(*__pyx_t_10)(PyObject *); + std::string __pyx_t_11; + std::string __pyx_t_12; + std::pair __pyx_t_13; + std::shared_ptr __pyx_t_14; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__init__", 1); + + /* "curated_tokenizers/_bbpe.pyx":59 + * + * def __init__(self, vocab: Dict[str, int], merges: List[Tuple[str, str]]): + * self._byte_encoder = bytes_to_unicode() # <<<<<<<<<<<<<< + * self._byte_decoder = {v.decode("utf-8"): k for k, v in self._byte_encoder.items()} + * self._split_pattern = regex.compile(SPLIT_PATTERN) + */ + __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_bytes_to_unicode); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 59, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = NULL; + __pyx_t_4 = 0; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2); + if (likely(__pyx_t_3)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_2, function); + __pyx_t_4 = 1; + } + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, NULL}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_2, __pyx_callargs+1-__pyx_t_4, 0+__pyx_t_4); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 59, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } + if (!(likely(PyDict_CheckExact(__pyx_t_1))||((__pyx_t_1) == Py_None) || __Pyx_RaiseUnexpectedTypeError("dict", __pyx_t_1))) __PYX_ERR(0, 59, __pyx_L1_error) + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF(__pyx_v_self->_byte_encoder); + __Pyx_DECREF(__pyx_v_self->_byte_encoder); + __pyx_v_self->_byte_encoder = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + + /* "curated_tokenizers/_bbpe.pyx":60 + * def __init__(self, vocab: Dict[str, int], merges: List[Tuple[str, str]]): + * self._byte_encoder = bytes_to_unicode() + * self._byte_decoder = {v.decode("utf-8"): k for k, v in self._byte_encoder.items()} # <<<<<<<<<<<<<< + * self._split_pattern = regex.compile(SPLIT_PATTERN) + * self._piece_to_id = vocab + */ + { /* enter inner scope */ + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 60, __pyx_L5_error) + __Pyx_GOTREF(__pyx_t_1); + if (unlikely(__pyx_v_self->_byte_encoder == Py_None)) { + PyErr_Format(PyExc_AttributeError, "'NoneType' object has no attribute '%.30s'", "items"); + __PYX_ERR(0, 60, __pyx_L5_error) + } + __pyx_t_2 = __Pyx_PyDict_Items(__pyx_v_self->_byte_encoder); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 60, __pyx_L5_error) + __Pyx_GOTREF(__pyx_t_2); + if (likely(PyList_CheckExact(__pyx_t_2)) || PyTuple_CheckExact(__pyx_t_2)) { + __pyx_t_3 = __pyx_t_2; __Pyx_INCREF(__pyx_t_3); + __pyx_t_5 = 0; + __pyx_t_6 = NULL; + } else { + __pyx_t_5 = -1; __pyx_t_3 = PyObject_GetIter(__pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 60, __pyx_L5_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_6 = __Pyx_PyObject_GetIterNextFunc(__pyx_t_3); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 60, __pyx_L5_error) + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + for (;;) { + if (likely(!__pyx_t_6)) { + if (likely(PyList_CheckExact(__pyx_t_3))) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_3); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 60, __pyx_L5_error) + #endif + if (__pyx_t_5 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_2 = PyList_GET_ITEM(__pyx_t_3, __pyx_t_5); __Pyx_INCREF(__pyx_t_2); __pyx_t_5++; if (unlikely((0 < 0))) __PYX_ERR(0, 60, __pyx_L5_error) + #else + __pyx_t_2 = __Pyx_PySequence_ITEM(__pyx_t_3, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 60, __pyx_L5_error) + __Pyx_GOTREF(__pyx_t_2); + #endif + } else { + { + Py_ssize_t __pyx_temp = __Pyx_PyTuple_GET_SIZE(__pyx_t_3); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 60, __pyx_L5_error) + #endif + if (__pyx_t_5 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_2 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_5); __Pyx_INCREF(__pyx_t_2); __pyx_t_5++; if (unlikely((0 < 0))) __PYX_ERR(0, 60, __pyx_L5_error) + #else + __pyx_t_2 = __Pyx_PySequence_ITEM(__pyx_t_3, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 60, __pyx_L5_error) + __Pyx_GOTREF(__pyx_t_2); + #endif + } + } else { + __pyx_t_2 = __pyx_t_6(__pyx_t_3); + if (unlikely(!__pyx_t_2)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else __PYX_ERR(0, 60, __pyx_L5_error) + } + break; + } + __Pyx_GOTREF(__pyx_t_2); + } + if ((likely(PyTuple_CheckExact(__pyx_t_2))) || (PyList_CheckExact(__pyx_t_2))) { + PyObject* sequence = __pyx_t_2; + Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + __PYX_ERR(0, 60, __pyx_L5_error) + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_7 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_8 = PyTuple_GET_ITEM(sequence, 1); + } else { + __pyx_t_7 = PyList_GET_ITEM(sequence, 0); + __pyx_t_8 = PyList_GET_ITEM(sequence, 1); + } + __Pyx_INCREF(__pyx_t_7); + __Pyx_INCREF(__pyx_t_8); + #else + __pyx_t_7 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 60, __pyx_L5_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_8 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 60, __pyx_L5_error) + __Pyx_GOTREF(__pyx_t_8); + #endif + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } else { + Py_ssize_t index = -1; + __pyx_t_9 = PyObject_GetIter(__pyx_t_2); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 60, __pyx_L5_error) + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_10 = __Pyx_PyObject_GetIterNextFunc(__pyx_t_9); + index = 0; __pyx_t_7 = __pyx_t_10(__pyx_t_9); if (unlikely(!__pyx_t_7)) goto __pyx_L8_unpacking_failed; + __Pyx_GOTREF(__pyx_t_7); + index = 1; __pyx_t_8 = __pyx_t_10(__pyx_t_9); if (unlikely(!__pyx_t_8)) goto __pyx_L8_unpacking_failed; + __Pyx_GOTREF(__pyx_t_8); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_10(__pyx_t_9), 2) < 0) __PYX_ERR(0, 60, __pyx_L5_error) + __pyx_t_10 = NULL; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + goto __pyx_L9_unpacking_done; + __pyx_L8_unpacking_failed:; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_10 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + __PYX_ERR(0, 60, __pyx_L5_error) + __pyx_L9_unpacking_done:; + } + __Pyx_XDECREF_SET(__pyx_7genexpr__pyx_v_k, __pyx_t_7); + __pyx_t_7 = 0; + __Pyx_XDECREF_SET(__pyx_7genexpr__pyx_v_v, __pyx_t_8); + __pyx_t_8 = 0; + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_7genexpr__pyx_v_v, __pyx_n_s_decode); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 60, __pyx_L5_error) + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_7 = NULL; + __pyx_t_4 = 0; + #if CYTHON_UNPACK_METHODS + if (likely(PyMethod_Check(__pyx_t_8))) { + __pyx_t_7 = PyMethod_GET_SELF(__pyx_t_8); + if (likely(__pyx_t_7)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_8); + __Pyx_INCREF(__pyx_t_7); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_8, function); + __pyx_t_4 = 1; + } + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_7, __pyx_kp_s_utf_8}; + __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_8, __pyx_callargs+1-__pyx_t_4, 1+__pyx_t_4); + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 60, __pyx_L5_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + } + if (unlikely(PyDict_SetItem(__pyx_t_1, (PyObject*)__pyx_t_2, (PyObject*)__pyx_7genexpr__pyx_v_k))) __PYX_ERR(0, 60, __pyx_L5_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_XDECREF(__pyx_7genexpr__pyx_v_k); __pyx_7genexpr__pyx_v_k = 0; + __Pyx_XDECREF(__pyx_7genexpr__pyx_v_v); __pyx_7genexpr__pyx_v_v = 0; + goto __pyx_L11_exit_scope; + __pyx_L5_error:; + __Pyx_XDECREF(__pyx_7genexpr__pyx_v_k); __pyx_7genexpr__pyx_v_k = 0; + __Pyx_XDECREF(__pyx_7genexpr__pyx_v_v); __pyx_7genexpr__pyx_v_v = 0; + goto __pyx_L1_error; + __pyx_L11_exit_scope:; + } /* exit inner scope */ + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF(__pyx_v_self->_byte_decoder); + __Pyx_DECREF(__pyx_v_self->_byte_decoder); + __pyx_v_self->_byte_decoder = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + + /* "curated_tokenizers/_bbpe.pyx":61 + * self._byte_encoder = bytes_to_unicode() + * self._byte_decoder = {v.decode("utf-8"): k for k, v in self._byte_encoder.items()} + * self._split_pattern = regex.compile(SPLIT_PATTERN) # <<<<<<<<<<<<<< + * self._piece_to_id = vocab + * self._id_to_piece = {v: k for k, v in vocab.items()} + */ + __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_regex); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 61, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_compile); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 61, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_SPLIT_PATTERN); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 61, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_8 = NULL; + __pyx_t_4 = 0; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_8 = PyMethod_GET_SELF(__pyx_t_2); + if (likely(__pyx_t_8)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_8); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_2, function); + __pyx_t_4 = 1; + } + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_8, __pyx_t_3}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_2, __pyx_callargs+1-__pyx_t_4, 1+__pyx_t_4); + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 61, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF(__pyx_v_self->_split_pattern); + __Pyx_DECREF(__pyx_v_self->_split_pattern); + __pyx_v_self->_split_pattern = __pyx_t_1; + __pyx_t_1 = 0; + + /* "curated_tokenizers/_bbpe.pyx":62 + * self._byte_decoder = {v.decode("utf-8"): k for k, v in self._byte_encoder.items()} + * self._split_pattern = regex.compile(SPLIT_PATTERN) + * self._piece_to_id = vocab # <<<<<<<<<<<<<< + * self._id_to_piece = {v: k for k, v in vocab.items()} + * cdef vector[pair[string, string]] c_merges + */ + if (!(likely(PyDict_CheckExact(__pyx_v_vocab))||((__pyx_v_vocab) == Py_None) || __Pyx_RaiseUnexpectedTypeError("dict", __pyx_v_vocab))) __PYX_ERR(0, 62, __pyx_L1_error) + __pyx_t_1 = __pyx_v_vocab; + __Pyx_INCREF(__pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF(__pyx_v_self->_piece_to_id); + __Pyx_DECREF(__pyx_v_self->_piece_to_id); + __pyx_v_self->_piece_to_id = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + + /* "curated_tokenizers/_bbpe.pyx":63 + * self._split_pattern = regex.compile(SPLIT_PATTERN) + * self._piece_to_id = vocab + * self._id_to_piece = {v: k for k, v in vocab.items()} # <<<<<<<<<<<<<< + * cdef vector[pair[string, string]] c_merges + * for p1, p2 in merges: + */ + { /* enter inner scope */ + __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 63, __pyx_L14_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_vocab, __pyx_n_s_items); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 63, __pyx_L14_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_8 = NULL; + __pyx_t_4 = 0; + #if CYTHON_UNPACK_METHODS + if (likely(PyMethod_Check(__pyx_t_3))) { + __pyx_t_8 = PyMethod_GET_SELF(__pyx_t_3); + if (likely(__pyx_t_8)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); + __Pyx_INCREF(__pyx_t_8); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_3, function); + __pyx_t_4 = 1; + } + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_8, NULL}; + __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_3, __pyx_callargs+1-__pyx_t_4, 0+__pyx_t_4); + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 63, __pyx_L14_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + } + if (likely(PyList_CheckExact(__pyx_t_2)) || PyTuple_CheckExact(__pyx_t_2)) { + __pyx_t_3 = __pyx_t_2; __Pyx_INCREF(__pyx_t_3); + __pyx_t_5 = 0; + __pyx_t_6 = NULL; + } else { + __pyx_t_5 = -1; __pyx_t_3 = PyObject_GetIter(__pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 63, __pyx_L14_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_6 = __Pyx_PyObject_GetIterNextFunc(__pyx_t_3); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 63, __pyx_L14_error) + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + for (;;) { + if (likely(!__pyx_t_6)) { + if (likely(PyList_CheckExact(__pyx_t_3))) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_3); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 63, __pyx_L14_error) + #endif + if (__pyx_t_5 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_2 = PyList_GET_ITEM(__pyx_t_3, __pyx_t_5); __Pyx_INCREF(__pyx_t_2); __pyx_t_5++; if (unlikely((0 < 0))) __PYX_ERR(0, 63, __pyx_L14_error) + #else + __pyx_t_2 = __Pyx_PySequence_ITEM(__pyx_t_3, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 63, __pyx_L14_error) + __Pyx_GOTREF(__pyx_t_2); + #endif + } else { + { + Py_ssize_t __pyx_temp = __Pyx_PyTuple_GET_SIZE(__pyx_t_3); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 63, __pyx_L14_error) + #endif + if (__pyx_t_5 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_2 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_5); __Pyx_INCREF(__pyx_t_2); __pyx_t_5++; if (unlikely((0 < 0))) __PYX_ERR(0, 63, __pyx_L14_error) + #else + __pyx_t_2 = __Pyx_PySequence_ITEM(__pyx_t_3, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 63, __pyx_L14_error) + __Pyx_GOTREF(__pyx_t_2); + #endif + } + } else { + __pyx_t_2 = __pyx_t_6(__pyx_t_3); + if (unlikely(!__pyx_t_2)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else __PYX_ERR(0, 63, __pyx_L14_error) + } + break; + } + __Pyx_GOTREF(__pyx_t_2); + } + if ((likely(PyTuple_CheckExact(__pyx_t_2))) || (PyList_CheckExact(__pyx_t_2))) { + PyObject* sequence = __pyx_t_2; + Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + __PYX_ERR(0, 63, __pyx_L14_error) + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_8 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_7 = PyTuple_GET_ITEM(sequence, 1); + } else { + __pyx_t_8 = PyList_GET_ITEM(sequence, 0); + __pyx_t_7 = PyList_GET_ITEM(sequence, 1); + } + __Pyx_INCREF(__pyx_t_8); + __Pyx_INCREF(__pyx_t_7); + #else + __pyx_t_8 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 63, __pyx_L14_error) + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_7 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 63, __pyx_L14_error) + __Pyx_GOTREF(__pyx_t_7); + #endif + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } else { + Py_ssize_t index = -1; + __pyx_t_9 = PyObject_GetIter(__pyx_t_2); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 63, __pyx_L14_error) + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_10 = __Pyx_PyObject_GetIterNextFunc(__pyx_t_9); + index = 0; __pyx_t_8 = __pyx_t_10(__pyx_t_9); if (unlikely(!__pyx_t_8)) goto __pyx_L17_unpacking_failed; + __Pyx_GOTREF(__pyx_t_8); + index = 1; __pyx_t_7 = __pyx_t_10(__pyx_t_9); if (unlikely(!__pyx_t_7)) goto __pyx_L17_unpacking_failed; + __Pyx_GOTREF(__pyx_t_7); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_10(__pyx_t_9), 2) < 0) __PYX_ERR(0, 63, __pyx_L14_error) + __pyx_t_10 = NULL; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + goto __pyx_L18_unpacking_done; + __pyx_L17_unpacking_failed:; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_10 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + __PYX_ERR(0, 63, __pyx_L14_error) + __pyx_L18_unpacking_done:; + } + __Pyx_XDECREF_SET(__pyx_8genexpr1__pyx_v_k, __pyx_t_8); + __pyx_t_8 = 0; + __Pyx_XDECREF_SET(__pyx_8genexpr1__pyx_v_v, __pyx_t_7); + __pyx_t_7 = 0; + if (unlikely(PyDict_SetItem(__pyx_t_1, (PyObject*)__pyx_8genexpr1__pyx_v_v, (PyObject*)__pyx_8genexpr1__pyx_v_k))) __PYX_ERR(0, 63, __pyx_L14_error) + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_XDECREF(__pyx_8genexpr1__pyx_v_k); __pyx_8genexpr1__pyx_v_k = 0; + __Pyx_XDECREF(__pyx_8genexpr1__pyx_v_v); __pyx_8genexpr1__pyx_v_v = 0; + goto __pyx_L20_exit_scope; + __pyx_L14_error:; + __Pyx_XDECREF(__pyx_8genexpr1__pyx_v_k); __pyx_8genexpr1__pyx_v_k = 0; + __Pyx_XDECREF(__pyx_8genexpr1__pyx_v_v); __pyx_8genexpr1__pyx_v_v = 0; + goto __pyx_L1_error; + __pyx_L20_exit_scope:; + } /* exit inner scope */ + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF(__pyx_v_self->_id_to_piece); + __Pyx_DECREF(__pyx_v_self->_id_to_piece); + __pyx_v_self->_id_to_piece = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + + /* "curated_tokenizers/_bbpe.pyx":65 + * self._id_to_piece = {v: k for k, v in vocab.items()} + * cdef vector[pair[string, string]] c_merges + * for p1, p2 in merges: # <<<<<<<<<<<<<< + * c_merges.push_back(pair[string, string](p1.encode('utf-8'), p2.encode('utf-8'))) + * self._merges = make_shared[Merges](c_merges) + */ + if (likely(PyList_CheckExact(__pyx_v_merges)) || PyTuple_CheckExact(__pyx_v_merges)) { + __pyx_t_1 = __pyx_v_merges; __Pyx_INCREF(__pyx_t_1); + __pyx_t_5 = 0; + __pyx_t_6 = NULL; + } else { + __pyx_t_5 = -1; __pyx_t_1 = PyObject_GetIter(__pyx_v_merges); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 65, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_6 = __Pyx_PyObject_GetIterNextFunc(__pyx_t_1); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 65, __pyx_L1_error) + } + for (;;) { + if (likely(!__pyx_t_6)) { + if (likely(PyList_CheckExact(__pyx_t_1))) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_1); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 65, __pyx_L1_error) + #endif + if (__pyx_t_5 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_3 = PyList_GET_ITEM(__pyx_t_1, __pyx_t_5); __Pyx_INCREF(__pyx_t_3); __pyx_t_5++; if (unlikely((0 < 0))) __PYX_ERR(0, 65, __pyx_L1_error) + #else + __pyx_t_3 = __Pyx_PySequence_ITEM(__pyx_t_1, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 65, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + #endif + } else { + { + Py_ssize_t __pyx_temp = __Pyx_PyTuple_GET_SIZE(__pyx_t_1); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 65, __pyx_L1_error) + #endif + if (__pyx_t_5 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_5); __Pyx_INCREF(__pyx_t_3); __pyx_t_5++; if (unlikely((0 < 0))) __PYX_ERR(0, 65, __pyx_L1_error) + #else + __pyx_t_3 = __Pyx_PySequence_ITEM(__pyx_t_1, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 65, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + #endif + } + } else { + __pyx_t_3 = __pyx_t_6(__pyx_t_1); + if (unlikely(!__pyx_t_3)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else __PYX_ERR(0, 65, __pyx_L1_error) + } + break; + } + __Pyx_GOTREF(__pyx_t_3); + } + if ((likely(PyTuple_CheckExact(__pyx_t_3))) || (PyList_CheckExact(__pyx_t_3))) { + PyObject* sequence = __pyx_t_3; + Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + __PYX_ERR(0, 65, __pyx_L1_error) + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_2 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_7 = PyTuple_GET_ITEM(sequence, 1); + } else { + __pyx_t_2 = PyList_GET_ITEM(sequence, 0); + __pyx_t_7 = PyList_GET_ITEM(sequence, 1); + } + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(__pyx_t_7); + #else + __pyx_t_2 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 65, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_7 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 65, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + #endif + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + } else { + Py_ssize_t index = -1; + __pyx_t_8 = PyObject_GetIter(__pyx_t_3); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 65, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_10 = __Pyx_PyObject_GetIterNextFunc(__pyx_t_8); + index = 0; __pyx_t_2 = __pyx_t_10(__pyx_t_8); if (unlikely(!__pyx_t_2)) goto __pyx_L23_unpacking_failed; + __Pyx_GOTREF(__pyx_t_2); + index = 1; __pyx_t_7 = __pyx_t_10(__pyx_t_8); if (unlikely(!__pyx_t_7)) goto __pyx_L23_unpacking_failed; + __Pyx_GOTREF(__pyx_t_7); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_10(__pyx_t_8), 2) < 0) __PYX_ERR(0, 65, __pyx_L1_error) + __pyx_t_10 = NULL; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + goto __pyx_L24_unpacking_done; + __pyx_L23_unpacking_failed:; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_10 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + __PYX_ERR(0, 65, __pyx_L1_error) + __pyx_L24_unpacking_done:; + } + __Pyx_XDECREF_SET(__pyx_v_p1, __pyx_t_2); + __pyx_t_2 = 0; + __Pyx_XDECREF_SET(__pyx_v_p2, __pyx_t_7); + __pyx_t_7 = 0; + + /* "curated_tokenizers/_bbpe.pyx":66 + * cdef vector[pair[string, string]] c_merges + * for p1, p2 in merges: + * c_merges.push_back(pair[string, string](p1.encode('utf-8'), p2.encode('utf-8'))) # <<<<<<<<<<<<<< + * self._merges = make_shared[Merges](c_merges) + * + */ + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_v_p1, __pyx_n_s_encode); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 66, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_2 = NULL; + __pyx_t_4 = 0; + #if CYTHON_UNPACK_METHODS + if (likely(PyMethod_Check(__pyx_t_7))) { + __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_7); + if (likely(__pyx_t_2)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_7); + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_7, function); + __pyx_t_4 = 1; + } + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, __pyx_kp_s_utf_8}; + __pyx_t_3 = __Pyx_PyObject_FastCall(__pyx_t_7, __pyx_callargs+1-__pyx_t_4, 1+__pyx_t_4); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 66, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + } + __pyx_t_11 = __pyx_convert_string_from_py_std__in_string(__pyx_t_3); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 66, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_v_p2, __pyx_n_s_encode); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 66, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_2 = NULL; + __pyx_t_4 = 0; + #if CYTHON_UNPACK_METHODS + if (likely(PyMethod_Check(__pyx_t_7))) { + __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_7); + if (likely(__pyx_t_2)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_7); + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_7, function); + __pyx_t_4 = 1; + } + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, __pyx_kp_s_utf_8}; + __pyx_t_3 = __Pyx_PyObject_FastCall(__pyx_t_7, __pyx_callargs+1-__pyx_t_4, 1+__pyx_t_4); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 66, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + } + __pyx_t_12 = __pyx_convert_string_from_py_std__in_string(__pyx_t_3); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 66, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + try { + __pyx_t_13 = std::pair (__pyx_t_11, __pyx_t_12); + } catch(...) { + __Pyx_CppExn2PyErr(); + __PYX_ERR(0, 66, __pyx_L1_error) + } + try { + __pyx_v_c_merges.push_back(__pyx_t_13); + } catch(...) { + __Pyx_CppExn2PyErr(); + __PYX_ERR(0, 66, __pyx_L1_error) + } + + /* "curated_tokenizers/_bbpe.pyx":65 + * self._id_to_piece = {v: k for k, v in vocab.items()} + * cdef vector[pair[string, string]] c_merges + * for p1, p2 in merges: # <<<<<<<<<<<<<< + * c_merges.push_back(pair[string, string](p1.encode('utf-8'), p2.encode('utf-8'))) + * self._merges = make_shared[Merges](c_merges) + */ + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "curated_tokenizers/_bbpe.pyx":67 + * for p1, p2 in merges: + * c_merges.push_back(pair[string, string](p1.encode('utf-8'), p2.encode('utf-8'))) + * self._merges = make_shared[Merges](c_merges) # <<<<<<<<<<<<<< + * + * def __copy__(self): + */ + try { + __pyx_t_14 = std::make_shared(__pyx_v_c_merges); + } catch(...) { + __Pyx_CppExn2PyErr(); + __PYX_ERR(0, 67, __pyx_L1_error) + } + __pyx_v_self->_merges = __PYX_STD_MOVE_IF_SUPPORTED(__pyx_t_14); + + /* "curated_tokenizers/_bbpe.pyx":58 + * cdef dict _id_to_piece + * + * def __init__(self, vocab: Dict[str, int], merges: List[Tuple[str, str]]): # <<<<<<<<<<<<<< + * self._byte_encoder = bytes_to_unicode() + * self._byte_decoder = {v.decode("utf-8"): k for k, v in self._byte_encoder.items()} + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_AddTraceback("curated_tokenizers._bbpe.ByteBPEProcessor.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_p1); + __Pyx_XDECREF(__pyx_v_p2); + __Pyx_XDECREF(__pyx_7genexpr__pyx_v_k); + __Pyx_XDECREF(__pyx_7genexpr__pyx_v_v); + __Pyx_XDECREF(__pyx_8genexpr1__pyx_v_k); + __Pyx_XDECREF(__pyx_8genexpr1__pyx_v_v); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_bbpe.pyx":69 + * self._merges = make_shared[Merges](c_merges) + * + * def __copy__(self): # <<<<<<<<<<<<<< + * return ByteBPEProcessor(vocab=self.vocab, merges=self.merges) + * + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_3__copy__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_2__copy__, "ByteBPEProcessor.__copy__(self)"); +static PyMethodDef __pyx_mdef_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_3__copy__ = {"__copy__", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_3__copy__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_2__copy__}; +static PyObject *__pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_3__copy__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__copy__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_MACROS + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { + __Pyx_RaiseArgtupleInvalid("__copy__", 1, 0, 0, __pyx_nargs); return NULL;} + if (unlikely(__pyx_kwds) && __Pyx_NumKwargs_FASTCALL(__pyx_kwds) && unlikely(!__Pyx_CheckKeywordStrings(__pyx_kwds, "__copy__", 0))) return NULL; + __pyx_r = __pyx_pf_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_2__copy__(((struct __pyx_obj_18curated_tokenizers_5_bbpe_ByteBPEProcessor *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_2__copy__(struct __pyx_obj_18curated_tokenizers_5_bbpe_ByteBPEProcessor *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__copy__", 1); + + /* "curated_tokenizers/_bbpe.pyx":70 + * + * def __copy__(self): + * return ByteBPEProcessor(vocab=self.vocab, merges=self.merges) # <<<<<<<<<<<<<< + * + * def __deepcopy__(self, memo): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyDict_NewPresized(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 70, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_vocab); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 70, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_vocab, __pyx_t_2) < 0) __PYX_ERR(0, 70, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_merges); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 70, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_merges, __pyx_t_2) < 0) __PYX_ERR(0, 70, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)__pyx_ptype_18curated_tokenizers_5_bbpe_ByteBPEProcessor), __pyx_empty_tuple, __pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 70, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "curated_tokenizers/_bbpe.pyx":69 + * self._merges = make_shared[Merges](c_merges) + * + * def __copy__(self): # <<<<<<<<<<<<<< + * return ByteBPEProcessor(vocab=self.vocab, merges=self.merges) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("curated_tokenizers._bbpe.ByteBPEProcessor.__copy__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_bbpe.pyx":72 + * return ByteBPEProcessor(vocab=self.vocab, merges=self.merges) + * + * def __deepcopy__(self, memo): # <<<<<<<<<<<<<< + * # We don't need a deepcopy of the vocab and merges dicts as their + * # contents will be copied into a backing store in the c'tor. + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_5__deepcopy__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_4__deepcopy__, "ByteBPEProcessor.__deepcopy__(self, memo)"); +static PyMethodDef __pyx_mdef_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_5__deepcopy__ = {"__deepcopy__", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_5__deepcopy__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_4__deepcopy__}; +static PyObject *__pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_5__deepcopy__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + CYTHON_UNUSED PyObject *__pyx_v_memo = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__deepcopy__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_MACROS + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject **__pyx_pyargnames[] = {&__pyx_n_s_memo,0}; + if (__pyx_kwds) { + Py_ssize_t kw_args; + switch (__pyx_nargs) { + case 1: values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = __Pyx_NumKwargs_FASTCALL(__pyx_kwds); + switch (__pyx_nargs) { + case 0: + if (likely((values[0] = __Pyx_GetKwValue_FASTCALL(__pyx_kwds, __pyx_kwvalues, __pyx_n_s_memo)) != 0)) { + (void)__Pyx_Arg_NewRef_FASTCALL(values[0]); + kw_args--; + } + else if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 72, __pyx_L3_error) + else goto __pyx_L5_argtuple_error; + } + if (unlikely(kw_args > 0)) { + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values + 0, kwd_pos_args, "__deepcopy__") < 0)) __PYX_ERR(0, 72, __pyx_L3_error) + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + } + __pyx_v_memo = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__deepcopy__", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 72, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_AddTraceback("curated_tokenizers._bbpe.ByteBPEProcessor.__deepcopy__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_4__deepcopy__(((struct __pyx_obj_18curated_tokenizers_5_bbpe_ByteBPEProcessor *)__pyx_v_self), __pyx_v_memo); + + /* function exit code */ + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_4__deepcopy__(struct __pyx_obj_18curated_tokenizers_5_bbpe_ByteBPEProcessor *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v_memo) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__deepcopy__", 1); + + /* "curated_tokenizers/_bbpe.pyx":75 + * # We don't need a deepcopy of the vocab and merges dicts as their + * # contents will be copied into a backing store in the c'tor. + * return ByteBPEProcessor(vocab=self.vocab, merges=self.merges) # <<<<<<<<<<<<<< + * + * @staticmethod + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyDict_NewPresized(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 75, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_vocab); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 75, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_vocab, __pyx_t_2) < 0) __PYX_ERR(0, 75, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_merges); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 75, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_merges, __pyx_t_2) < 0) __PYX_ERR(0, 75, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)__pyx_ptype_18curated_tokenizers_5_bbpe_ByteBPEProcessor), __pyx_empty_tuple, __pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 75, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "curated_tokenizers/_bbpe.pyx":72 + * return ByteBPEProcessor(vocab=self.vocab, merges=self.merges) + * + * def __deepcopy__(self, memo): # <<<<<<<<<<<<<< + * # We don't need a deepcopy of the vocab and merges dicts as their + * # contents will be copied into a backing store in the c'tor. + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("curated_tokenizers._bbpe.ByteBPEProcessor.__deepcopy__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_bbpe.pyx":77 + * return ByteBPEProcessor(vocab=self.vocab, merges=self.merges) + * + * @staticmethod # <<<<<<<<<<<<<< + * def load_from_files(*, vocab: Path, merges: Path) -> ByteBPEProcessor: + * """Construct a processor from the given vocabulary and merges files.""" + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_7load_from_files(CYTHON_UNUSED PyObject *__pyx_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_6load_from_files, "ByteBPEProcessor.load_from_files(*, vocab: Path, merges: Path) -> ByteBPEProcessor\nConstruct a processor from the given vocabulary and merges files."); +static PyMethodDef __pyx_mdef_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_7load_from_files = {"load_from_files", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_7load_from_files, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_6load_from_files}; +static PyObject *__pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_7load_from_files(CYTHON_UNUSED PyObject *__pyx_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_vocab = 0; + PyObject *__pyx_v_merges = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[2] = {0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("load_from_files (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_MACROS + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject **__pyx_pyargnames[] = {&__pyx_n_s_vocab,&__pyx_n_s_merges,0}; + if (likely(__pyx_kwds)) { + Py_ssize_t kw_args; + switch (__pyx_nargs) { + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = __Pyx_NumKwargs_FASTCALL(__pyx_kwds); + if (likely((values[0] = __Pyx_GetKwValue_FASTCALL(__pyx_kwds, __pyx_kwvalues, __pyx_n_s_vocab)) != 0)) { + (void)__Pyx_Arg_NewRef_FASTCALL(values[0]); + kw_args--; + } + else if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 77, __pyx_L3_error) + else { + __Pyx_RaiseKeywordRequired("load_from_files", __pyx_n_s_vocab); __PYX_ERR(0, 77, __pyx_L3_error) + } + if (likely((values[1] = __Pyx_GetKwValue_FASTCALL(__pyx_kwds, __pyx_kwvalues, __pyx_n_s_merges)) != 0)) { + (void)__Pyx_Arg_NewRef_FASTCALL(values[1]); + kw_args--; + } + else if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 77, __pyx_L3_error) + else { + __Pyx_RaiseKeywordRequired("load_from_files", __pyx_n_s_merges); __PYX_ERR(0, 77, __pyx_L3_error) + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values + 0, 0, "load_from_files") < 0)) __PYX_ERR(0, 77, __pyx_L3_error) + } + } else if (unlikely(__pyx_nargs != 0)) { + goto __pyx_L5_argtuple_error; + } else { + __Pyx_RaiseKeywordRequired("load_from_files", __pyx_n_s_vocab); __PYX_ERR(0, 77, __pyx_L3_error) + } + __pyx_v_vocab = values[0]; + __pyx_v_merges = values[1]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("load_from_files", 1, 0, 0, __pyx_nargs); __PYX_ERR(0, 77, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_AddTraceback("curated_tokenizers._bbpe.ByteBPEProcessor.load_from_files", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_6load_from_files(__pyx_v_vocab, __pyx_v_merges); + + /* function exit code */ + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_6load_from_files(PyObject *__pyx_v_vocab, PyObject *__pyx_v_merges) { + PyObject *__pyx_v_f = NULL; + PyObject *__pyx_v_version = NULL; + PyObject *__pyx_v_line = NULL; + PyObject *__pyx_v_merge = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + int __pyx_t_6; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + PyObject *__pyx_t_10 = NULL; + int __pyx_t_11; + int __pyx_t_12; + Py_ssize_t __pyx_t_13; + PyObject *(*__pyx_t_14)(PyObject *); + PyObject *__pyx_t_15 = NULL; + Py_ssize_t __pyx_t_16; + Py_UCS4 __pyx_t_17; + Py_ssize_t __pyx_t_18; + int __pyx_t_19; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("load_from_files", 0); + __Pyx_INCREF(__pyx_v_vocab); + __Pyx_INCREF(__pyx_v_merges); + + /* "curated_tokenizers/_bbpe.pyx":80 + * def load_from_files(*, vocab: Path, merges: Path) -> ByteBPEProcessor: + * """Construct a processor from the given vocabulary and merges files.""" + * with open(vocab, encoding="utf-8") as f: # <<<<<<<<<<<<<< + * vocab = json.load(f) + * with open(merges, encoding="utf-8") as f: + */ + /*with:*/ { + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 80, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_vocab); + __Pyx_GIVEREF(__pyx_v_vocab); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_vocab)) __PYX_ERR(0, 80, __pyx_L1_error); + __pyx_t_2 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 80, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_encoding, __pyx_kp_s_utf_8) < 0) __PYX_ERR(0, 80, __pyx_L1_error) + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_open, __pyx_t_1, __pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 80, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_4 = __Pyx_PyObject_LookupSpecial(__pyx_t_3, __pyx_n_s_exit); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 80, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_1 = __Pyx_PyObject_LookupSpecial(__pyx_t_3, __pyx_n_s_enter); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 80, __pyx_L3_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_5 = NULL; + __pyx_t_6 = 0; + #if CYTHON_UNPACK_METHODS + if (likely(PyMethod_Check(__pyx_t_1))) { + __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_1); + if (likely(__pyx_t_5)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_1); + __Pyx_INCREF(__pyx_t_5); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_1, function); + __pyx_t_6 = 1; + } + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_5, NULL}; + __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_1, __pyx_callargs+1-__pyx_t_6, 0+__pyx_t_6); + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 80, __pyx_L3_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } + __pyx_t_1 = __pyx_t_2; + __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + /*try:*/ { + { + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + __Pyx_ExceptionSave(&__pyx_t_7, &__pyx_t_8, &__pyx_t_9); + __Pyx_XGOTREF(__pyx_t_7); + __Pyx_XGOTREF(__pyx_t_8); + __Pyx_XGOTREF(__pyx_t_9); + /*try:*/ { + __pyx_v_f = __pyx_t_1; + __pyx_t_1 = 0; + + /* "curated_tokenizers/_bbpe.pyx":81 + * """Construct a processor from the given vocabulary and merges files.""" + * with open(vocab, encoding="utf-8") as f: + * vocab = json.load(f) # <<<<<<<<<<<<<< + * with open(merges, encoding="utf-8") as f: + * version = f.readline() + */ + __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_json); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 81, __pyx_L7_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_load); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 81, __pyx_L7_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = NULL; + __pyx_t_6 = 0; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2); + if (likely(__pyx_t_3)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_2, function); + __pyx_t_6 = 1; + } + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_v_f}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_2, __pyx_callargs+1-__pyx_t_6, 1+__pyx_t_6); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 81, __pyx_L7_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } + __Pyx_DECREF_SET(__pyx_v_vocab, __pyx_t_1); + __pyx_t_1 = 0; + + /* "curated_tokenizers/_bbpe.pyx":80 + * def load_from_files(*, vocab: Path, merges: Path) -> ByteBPEProcessor: + * """Construct a processor from the given vocabulary and merges files.""" + * with open(vocab, encoding="utf-8") as f: # <<<<<<<<<<<<<< + * vocab = json.load(f) + * with open(merges, encoding="utf-8") as f: + */ + } + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; + goto __pyx_L12_try_end; + __pyx_L7_error:; + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + /*except:*/ { + __Pyx_AddTraceback("curated_tokenizers._bbpe.ByteBPEProcessor.load_from_files", __pyx_clineno, __pyx_lineno, __pyx_filename); + if (__Pyx_GetException(&__pyx_t_1, &__pyx_t_2, &__pyx_t_3) < 0) __PYX_ERR(0, 80, __pyx_L9_except_error) + __Pyx_XGOTREF(__pyx_t_1); + __Pyx_XGOTREF(__pyx_t_2); + __Pyx_XGOTREF(__pyx_t_3); + __pyx_t_5 = PyTuple_Pack(3, __pyx_t_1, __pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 80, __pyx_L9_except_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_10 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_5, NULL); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 80, __pyx_L9_except_error) + __Pyx_GOTREF(__pyx_t_10); + __pyx_t_11 = __Pyx_PyObject_IsTrue(__pyx_t_10); + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + if (__pyx_t_11 < 0) __PYX_ERR(0, 80, __pyx_L9_except_error) + __pyx_t_12 = (!__pyx_t_11); + if (unlikely(__pyx_t_12)) { + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GIVEREF(__pyx_t_2); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_ErrRestoreWithState(__pyx_t_1, __pyx_t_2, __pyx_t_3); + __pyx_t_1 = 0; __pyx_t_2 = 0; __pyx_t_3 = 0; + __PYX_ERR(0, 80, __pyx_L9_except_error) + } + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + goto __pyx_L8_exception_handled; + } + __pyx_L9_except_error:; + __Pyx_XGIVEREF(__pyx_t_7); + __Pyx_XGIVEREF(__pyx_t_8); + __Pyx_XGIVEREF(__pyx_t_9); + __Pyx_ExceptionReset(__pyx_t_7, __pyx_t_8, __pyx_t_9); + goto __pyx_L1_error; + __pyx_L8_exception_handled:; + __Pyx_XGIVEREF(__pyx_t_7); + __Pyx_XGIVEREF(__pyx_t_8); + __Pyx_XGIVEREF(__pyx_t_9); + __Pyx_ExceptionReset(__pyx_t_7, __pyx_t_8, __pyx_t_9); + __pyx_L12_try_end:; + } + } + /*finally:*/ { + /*normal exit:*/{ + if (__pyx_t_4) { + __pyx_t_9 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_tuple_, NULL); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 80, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + } + goto __pyx_L6; + } + __pyx_L6:; + } + goto __pyx_L16; + __pyx_L3_error:; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + goto __pyx_L1_error; + __pyx_L16:; + } + + /* "curated_tokenizers/_bbpe.pyx":82 + * with open(vocab, encoding="utf-8") as f: + * vocab = json.load(f) + * with open(merges, encoding="utf-8") as f: # <<<<<<<<<<<<<< + * version = f.readline() + * if not version.startswith("#version: 0.2"): + */ + /*with:*/ { + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 82, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_v_merges); + __Pyx_GIVEREF(__pyx_v_merges); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_merges)) __PYX_ERR(0, 82, __pyx_L1_error); + __pyx_t_2 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 82, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_encoding, __pyx_kp_s_utf_8) < 0) __PYX_ERR(0, 82, __pyx_L1_error) + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_open, __pyx_t_3, __pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 82, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_4 = __Pyx_PyObject_LookupSpecial(__pyx_t_1, __pyx_n_s_exit); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 82, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = __Pyx_PyObject_LookupSpecial(__pyx_t_1, __pyx_n_s_enter); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 82, __pyx_L17_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = NULL; + __pyx_t_6 = 0; + #if CYTHON_UNPACK_METHODS + if (likely(PyMethod_Check(__pyx_t_3))) { + __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_3); + if (likely(__pyx_t_5)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); + __Pyx_INCREF(__pyx_t_5); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_3, function); + __pyx_t_6 = 1; + } + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_5, NULL}; + __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_3, __pyx_callargs+1-__pyx_t_6, 0+__pyx_t_6); + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 82, __pyx_L17_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + } + __pyx_t_3 = __pyx_t_2; + __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + /*try:*/ { + { + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + __Pyx_ExceptionSave(&__pyx_t_9, &__pyx_t_8, &__pyx_t_7); + __Pyx_XGOTREF(__pyx_t_9); + __Pyx_XGOTREF(__pyx_t_8); + __Pyx_XGOTREF(__pyx_t_7); + /*try:*/ { + __Pyx_XDECREF_SET(__pyx_v_f, __pyx_t_3); + __pyx_t_3 = 0; + + /* "curated_tokenizers/_bbpe.pyx":83 + * vocab = json.load(f) + * with open(merges, encoding="utf-8") as f: + * version = f.readline() # <<<<<<<<<<<<<< + * if not version.startswith("#version: 0.2"): + * raise ValueError(f"Only version 0.2 of the merges format is supported, was: {version.strip()}") + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_f, __pyx_n_s_readline); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 83, __pyx_L21_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = NULL; + __pyx_t_6 = 0; + #if CYTHON_UNPACK_METHODS + if (likely(PyMethod_Check(__pyx_t_1))) { + __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_1); + if (likely(__pyx_t_2)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_1); + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_1, function); + __pyx_t_6 = 1; + } + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, NULL}; + __pyx_t_3 = __Pyx_PyObject_FastCall(__pyx_t_1, __pyx_callargs+1-__pyx_t_6, 0+__pyx_t_6); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 83, __pyx_L21_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } + __pyx_v_version = __pyx_t_3; + __pyx_t_3 = 0; + + /* "curated_tokenizers/_bbpe.pyx":84 + * with open(merges, encoding="utf-8") as f: + * version = f.readline() + * if not version.startswith("#version: 0.2"): # <<<<<<<<<<<<<< + * raise ValueError(f"Only version 0.2 of the merges format is supported, was: {version.strip()}") + * merges = [] + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_version, __pyx_n_s_startswith); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 84, __pyx_L21_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = NULL; + __pyx_t_6 = 0; + #if CYTHON_UNPACK_METHODS + if (likely(PyMethod_Check(__pyx_t_1))) { + __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_1); + if (likely(__pyx_t_2)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_1); + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_1, function); + __pyx_t_6 = 1; + } + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, __pyx_kp_s_version_0_2}; + __pyx_t_3 = __Pyx_PyObject_FastCall(__pyx_t_1, __pyx_callargs+1-__pyx_t_6, 1+__pyx_t_6); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 84, __pyx_L21_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } + __pyx_t_12 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely((__pyx_t_12 < 0))) __PYX_ERR(0, 84, __pyx_L21_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_11 = (!__pyx_t_12); + if (unlikely(__pyx_t_11)) { + + /* "curated_tokenizers/_bbpe.pyx":85 + * version = f.readline() + * if not version.startswith("#version: 0.2"): + * raise ValueError(f"Only version 0.2 of the merges format is supported, was: {version.strip()}") # <<<<<<<<<<<<<< + * merges = [] + * for line in f: + */ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_version, __pyx_n_s_strip); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 85, __pyx_L21_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = NULL; + __pyx_t_6 = 0; + #if CYTHON_UNPACK_METHODS + if (likely(PyMethod_Check(__pyx_t_1))) { + __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_1); + if (likely(__pyx_t_2)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_1); + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_1, function); + __pyx_t_6 = 1; + } + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, NULL}; + __pyx_t_3 = __Pyx_PyObject_FastCall(__pyx_t_1, __pyx_callargs+1-__pyx_t_6, 0+__pyx_t_6); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 85, __pyx_L21_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } + __pyx_t_1 = __Pyx_PyObject_FormatSimple(__pyx_t_3, __pyx_empty_unicode); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 85, __pyx_L21_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyUnicode_Concat(__pyx_kp_u_Only_version_0_2_of_the_merges_f, __pyx_t_1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 85, __pyx_L21_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_builtin_ValueError, __pyx_t_3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 85, __pyx_L21_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(0, 85, __pyx_L21_error) + + /* "curated_tokenizers/_bbpe.pyx":84 + * with open(merges, encoding="utf-8") as f: + * version = f.readline() + * if not version.startswith("#version: 0.2"): # <<<<<<<<<<<<<< + * raise ValueError(f"Only version 0.2 of the merges format is supported, was: {version.strip()}") + * merges = [] + */ + } + + /* "curated_tokenizers/_bbpe.pyx":86 + * if not version.startswith("#version: 0.2"): + * raise ValueError(f"Only version 0.2 of the merges format is supported, was: {version.strip()}") + * merges = [] # <<<<<<<<<<<<<< + * for line in f: + * merge = line.strip().split(" ") + */ + __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 86, __pyx_L21_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF_SET(__pyx_v_merges, __pyx_t_1); + __pyx_t_1 = 0; + + /* "curated_tokenizers/_bbpe.pyx":87 + * raise ValueError(f"Only version 0.2 of the merges format is supported, was: {version.strip()}") + * merges = [] + * for line in f: # <<<<<<<<<<<<<< + * merge = line.strip().split(" ") + * if len(merge) != 2: + */ + if (likely(PyList_CheckExact(__pyx_v_f)) || PyTuple_CheckExact(__pyx_v_f)) { + __pyx_t_1 = __pyx_v_f; __Pyx_INCREF(__pyx_t_1); + __pyx_t_13 = 0; + __pyx_t_14 = NULL; + } else { + __pyx_t_13 = -1; __pyx_t_1 = PyObject_GetIter(__pyx_v_f); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 87, __pyx_L21_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_14 = __Pyx_PyObject_GetIterNextFunc(__pyx_t_1); if (unlikely(!__pyx_t_14)) __PYX_ERR(0, 87, __pyx_L21_error) + } + for (;;) { + if (likely(!__pyx_t_14)) { + if (likely(PyList_CheckExact(__pyx_t_1))) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_1); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 87, __pyx_L21_error) + #endif + if (__pyx_t_13 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_3 = PyList_GET_ITEM(__pyx_t_1, __pyx_t_13); __Pyx_INCREF(__pyx_t_3); __pyx_t_13++; if (unlikely((0 < 0))) __PYX_ERR(0, 87, __pyx_L21_error) + #else + __pyx_t_3 = __Pyx_PySequence_ITEM(__pyx_t_1, __pyx_t_13); __pyx_t_13++; if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 87, __pyx_L21_error) + __Pyx_GOTREF(__pyx_t_3); + #endif + } else { + { + Py_ssize_t __pyx_temp = __Pyx_PyTuple_GET_SIZE(__pyx_t_1); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 87, __pyx_L21_error) + #endif + if (__pyx_t_13 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_13); __Pyx_INCREF(__pyx_t_3); __pyx_t_13++; if (unlikely((0 < 0))) __PYX_ERR(0, 87, __pyx_L21_error) + #else + __pyx_t_3 = __Pyx_PySequence_ITEM(__pyx_t_1, __pyx_t_13); __pyx_t_13++; if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 87, __pyx_L21_error) + __Pyx_GOTREF(__pyx_t_3); + #endif + } + } else { + __pyx_t_3 = __pyx_t_14(__pyx_t_1); + if (unlikely(!__pyx_t_3)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else __PYX_ERR(0, 87, __pyx_L21_error) + } + break; + } + __Pyx_GOTREF(__pyx_t_3); + } + __Pyx_XDECREF_SET(__pyx_v_line, __pyx_t_3); + __pyx_t_3 = 0; + + /* "curated_tokenizers/_bbpe.pyx":88 + * merges = [] + * for line in f: + * merge = line.strip().split(" ") # <<<<<<<<<<<<<< + * if len(merge) != 2: + * raise ValueError(f"Merge must consist of 2 items, was {len(merge)}: {line.strip()}") + */ + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_line, __pyx_n_s_strip); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 88, __pyx_L21_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_15 = NULL; + __pyx_t_6 = 0; + #if CYTHON_UNPACK_METHODS + if (likely(PyMethod_Check(__pyx_t_5))) { + __pyx_t_15 = PyMethod_GET_SELF(__pyx_t_5); + if (likely(__pyx_t_15)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_5); + __Pyx_INCREF(__pyx_t_15); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_5, function); + __pyx_t_6 = 1; + } + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_15, NULL}; + __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_5, __pyx_callargs+1-__pyx_t_6, 0+__pyx_t_6); + __Pyx_XDECREF(__pyx_t_15); __pyx_t_15 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 88, __pyx_L21_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + } + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_split); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 88, __pyx_L21_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = NULL; + __pyx_t_6 = 0; + #if CYTHON_UNPACK_METHODS + if (likely(PyMethod_Check(__pyx_t_5))) { + __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_5); + if (likely(__pyx_t_2)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_5); + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_5, function); + __pyx_t_6 = 1; + } + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, __pyx_kp_s__2}; + __pyx_t_3 = __Pyx_PyObject_FastCall(__pyx_t_5, __pyx_callargs+1-__pyx_t_6, 1+__pyx_t_6); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 88, __pyx_L21_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + } + __Pyx_XDECREF_SET(__pyx_v_merge, __pyx_t_3); + __pyx_t_3 = 0; + + /* "curated_tokenizers/_bbpe.pyx":89 + * for line in f: + * merge = line.strip().split(" ") + * if len(merge) != 2: # <<<<<<<<<<<<<< + * raise ValueError(f"Merge must consist of 2 items, was {len(merge)}: {line.strip()}") + * merges.append(merge) + */ + __pyx_t_16 = PyObject_Length(__pyx_v_merge); if (unlikely(__pyx_t_16 == ((Py_ssize_t)-1))) __PYX_ERR(0, 89, __pyx_L21_error) + __pyx_t_11 = (__pyx_t_16 != 2); + if (unlikely(__pyx_t_11)) { + + /* "curated_tokenizers/_bbpe.pyx":90 + * merge = line.strip().split(" ") + * if len(merge) != 2: + * raise ValueError(f"Merge must consist of 2 items, was {len(merge)}: {line.strip()}") # <<<<<<<<<<<<<< + * merges.append(merge) + * return ByteBPEProcessor(vocab, merges) + */ + __pyx_t_3 = PyTuple_New(4); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 90, __pyx_L21_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_16 = 0; + __pyx_t_17 = 127; + __Pyx_INCREF(__pyx_kp_u_Merge_must_consist_of_2_items_wa); + __pyx_t_16 += 35; + __Pyx_GIVEREF(__pyx_kp_u_Merge_must_consist_of_2_items_wa); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_kp_u_Merge_must_consist_of_2_items_wa); + __pyx_t_18 = PyObject_Length(__pyx_v_merge); if (unlikely(__pyx_t_18 == ((Py_ssize_t)-1))) __PYX_ERR(0, 90, __pyx_L21_error) + __pyx_t_5 = __Pyx_PyUnicode_From_Py_ssize_t(__pyx_t_18, 0, ' ', 'd'); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 90, __pyx_L21_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_16 += __Pyx_PyUnicode_GET_LENGTH(__pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_5); + __pyx_t_5 = 0; + __Pyx_INCREF(__pyx_kp_u__3); + __pyx_t_16 += 2; + __Pyx_GIVEREF(__pyx_kp_u__3); + PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_kp_u__3); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_line, __pyx_n_s_strip); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 90, __pyx_L21_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_15 = NULL; + __pyx_t_6 = 0; + #if CYTHON_UNPACK_METHODS + if (likely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_15 = PyMethod_GET_SELF(__pyx_t_2); + if (likely(__pyx_t_15)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_15); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_2, function); + __pyx_t_6 = 1; + } + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_15, NULL}; + __pyx_t_5 = __Pyx_PyObject_FastCall(__pyx_t_2, __pyx_callargs+1-__pyx_t_6, 0+__pyx_t_6); + __Pyx_XDECREF(__pyx_t_15); __pyx_t_15 = 0; + if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 90, __pyx_L21_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } + __pyx_t_2 = __Pyx_PyObject_FormatSimple(__pyx_t_5, __pyx_empty_unicode); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 90, __pyx_L21_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_17 = (__Pyx_PyUnicode_MAX_CHAR_VALUE(__pyx_t_2) > __pyx_t_17) ? __Pyx_PyUnicode_MAX_CHAR_VALUE(__pyx_t_2) : __pyx_t_17; + __pyx_t_16 += __Pyx_PyUnicode_GET_LENGTH(__pyx_t_2); + __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_3, 3, __pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyUnicode_Join(__pyx_t_3, 4, __pyx_t_16, __pyx_t_17); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 90, __pyx_L21_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_builtin_ValueError, __pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 90, __pyx_L21_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __PYX_ERR(0, 90, __pyx_L21_error) + + /* "curated_tokenizers/_bbpe.pyx":89 + * for line in f: + * merge = line.strip().split(" ") + * if len(merge) != 2: # <<<<<<<<<<<<<< + * raise ValueError(f"Merge must consist of 2 items, was {len(merge)}: {line.strip()}") + * merges.append(merge) + */ + } + + /* "curated_tokenizers/_bbpe.pyx":91 + * if len(merge) != 2: + * raise ValueError(f"Merge must consist of 2 items, was {len(merge)}: {line.strip()}") + * merges.append(merge) # <<<<<<<<<<<<<< + * return ByteBPEProcessor(vocab, merges) + * + */ + __pyx_t_19 = __Pyx_PyObject_Append(__pyx_v_merges, __pyx_v_merge); if (unlikely(__pyx_t_19 == ((int)-1))) __PYX_ERR(0, 91, __pyx_L21_error) + + /* "curated_tokenizers/_bbpe.pyx":87 + * raise ValueError(f"Only version 0.2 of the merges format is supported, was: {version.strip()}") + * merges = [] + * for line in f: # <<<<<<<<<<<<<< + * merge = line.strip().split(" ") + * if len(merge) != 2: + */ + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "curated_tokenizers/_bbpe.pyx":82 + * with open(vocab, encoding="utf-8") as f: + * vocab = json.load(f) + * with open(merges, encoding="utf-8") as f: # <<<<<<<<<<<<<< + * version = f.readline() + * if not version.startswith("#version: 0.2"): + */ + } + __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + goto __pyx_L26_try_end; + __pyx_L21_error:; + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_XDECREF(__pyx_t_15); __pyx_t_15 = 0; + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + /*except:*/ { + __Pyx_AddTraceback("curated_tokenizers._bbpe.ByteBPEProcessor.load_from_files", __pyx_clineno, __pyx_lineno, __pyx_filename); + if (__Pyx_GetException(&__pyx_t_1, &__pyx_t_3, &__pyx_t_2) < 0) __PYX_ERR(0, 82, __pyx_L23_except_error) + __Pyx_XGOTREF(__pyx_t_1); + __Pyx_XGOTREF(__pyx_t_3); + __Pyx_XGOTREF(__pyx_t_2); + __pyx_t_5 = PyTuple_Pack(3, __pyx_t_1, __pyx_t_3, __pyx_t_2); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 82, __pyx_L23_except_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_10 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_5, NULL); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 82, __pyx_L23_except_error) + __Pyx_GOTREF(__pyx_t_10); + __pyx_t_11 = __Pyx_PyObject_IsTrue(__pyx_t_10); + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + if (__pyx_t_11 < 0) __PYX_ERR(0, 82, __pyx_L23_except_error) + __pyx_t_12 = (!__pyx_t_11); + if (unlikely(__pyx_t_12)) { + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_2); + __Pyx_ErrRestoreWithState(__pyx_t_1, __pyx_t_3, __pyx_t_2); + __pyx_t_1 = 0; __pyx_t_3 = 0; __pyx_t_2 = 0; + __PYX_ERR(0, 82, __pyx_L23_except_error) + } + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + goto __pyx_L22_exception_handled; + } + __pyx_L23_except_error:; + __Pyx_XGIVEREF(__pyx_t_9); + __Pyx_XGIVEREF(__pyx_t_8); + __Pyx_XGIVEREF(__pyx_t_7); + __Pyx_ExceptionReset(__pyx_t_9, __pyx_t_8, __pyx_t_7); + goto __pyx_L1_error; + __pyx_L22_exception_handled:; + __Pyx_XGIVEREF(__pyx_t_9); + __Pyx_XGIVEREF(__pyx_t_8); + __Pyx_XGIVEREF(__pyx_t_7); + __Pyx_ExceptionReset(__pyx_t_9, __pyx_t_8, __pyx_t_7); + __pyx_L26_try_end:; + } + } + /*finally:*/ { + /*normal exit:*/{ + if (__pyx_t_4) { + __pyx_t_7 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_tuple_, NULL); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 82, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + } + goto __pyx_L20; + } + __pyx_L20:; + } + goto __pyx_L35; + __pyx_L17_error:; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + goto __pyx_L1_error; + __pyx_L35:; + } + + /* "curated_tokenizers/_bbpe.pyx":92 + * raise ValueError(f"Merge must consist of 2 items, was {len(merge)}: {line.strip()}") + * merges.append(merge) + * return ByteBPEProcessor(vocab, merges) # <<<<<<<<<<<<<< + * + * def decode_from_ids(self, ids: Iterable[int]) -> str: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 92, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_v_vocab); + __Pyx_GIVEREF(__pyx_v_vocab); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_vocab)) __PYX_ERR(0, 92, __pyx_L1_error); + __Pyx_INCREF(__pyx_v_merges); + __Pyx_GIVEREF(__pyx_v_merges); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_v_merges)) __PYX_ERR(0, 92, __pyx_L1_error); + __pyx_t_3 = __Pyx_PyObject_Call(((PyObject *)__pyx_ptype_18curated_tokenizers_5_bbpe_ByteBPEProcessor), __pyx_t_2, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 92, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + + /* "curated_tokenizers/_bbpe.pyx":77 + * return ByteBPEProcessor(vocab=self.vocab, merges=self.merges) + * + * @staticmethod # <<<<<<<<<<<<<< + * def load_from_files(*, vocab: Path, merges: Path) -> ByteBPEProcessor: + * """Construct a processor from the given vocabulary and merges files.""" + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_15); + __Pyx_AddTraceback("curated_tokenizers._bbpe.ByteBPEProcessor.load_from_files", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_f); + __Pyx_XDECREF(__pyx_v_version); + __Pyx_XDECREF(__pyx_v_line); + __Pyx_XDECREF(__pyx_v_merge); + __Pyx_XDECREF(__pyx_v_vocab); + __Pyx_XDECREF(__pyx_v_merges); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_bbpe.pyx":94 + * return ByteBPEProcessor(vocab, merges) + * + * def decode_from_ids(self, ids: Iterable[int]) -> str: # <<<<<<<<<<<<<< + * """ + * Decode piece identifiers into string. + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_9decode_from_ids(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_8decode_from_ids, "ByteBPEProcessor.decode_from_ids(self, ids: Iterable[int]) -> str\n\n Decode piece identifiers into string.\n\n ids (Iterable[int]): piece identifiers.\n RETURNS (str): decoded string.\n "); +static PyMethodDef __pyx_mdef_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_9decode_from_ids = {"decode_from_ids", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_9decode_from_ids, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_8decode_from_ids}; +static PyObject *__pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_9decode_from_ids(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_ids = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("decode_from_ids (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_MACROS + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject **__pyx_pyargnames[] = {&__pyx_n_s_ids,0}; + if (__pyx_kwds) { + Py_ssize_t kw_args; + switch (__pyx_nargs) { + case 1: values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = __Pyx_NumKwargs_FASTCALL(__pyx_kwds); + switch (__pyx_nargs) { + case 0: + if (likely((values[0] = __Pyx_GetKwValue_FASTCALL(__pyx_kwds, __pyx_kwvalues, __pyx_n_s_ids)) != 0)) { + (void)__Pyx_Arg_NewRef_FASTCALL(values[0]); + kw_args--; + } + else if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 94, __pyx_L3_error) + else goto __pyx_L5_argtuple_error; + } + if (unlikely(kw_args > 0)) { + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values + 0, kwd_pos_args, "decode_from_ids") < 0)) __PYX_ERR(0, 94, __pyx_L3_error) + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + } + __pyx_v_ids = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("decode_from_ids", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 94, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_AddTraceback("curated_tokenizers._bbpe.ByteBPEProcessor.decode_from_ids", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_8decode_from_ids(((struct __pyx_obj_18curated_tokenizers_5_bbpe_ByteBPEProcessor *)__pyx_v_self), __pyx_v_ids); + + /* function exit code */ + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_8decode_from_ids(struct __pyx_obj_18curated_tokenizers_5_bbpe_ByteBPEProcessor *__pyx_v_self, PyObject *__pyx_v_ids) { + PyObject *__pyx_v_decoded = NULL; + PyObject *__pyx_v_piece_id = NULL; + PyObject *__pyx_v_piece = NULL; + PyObject *__pyx_v_cp = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_t_4; + Py_ssize_t __pyx_t_5; + PyObject *(*__pyx_t_6)(PyObject *); + int __pyx_t_7; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + PyObject *__pyx_t_10 = NULL; + Py_ssize_t __pyx_t_11; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("decode_from_ids", 1); + + /* "curated_tokenizers/_bbpe.pyx":101 + * RETURNS (str): decoded string. + * """ + * decoded = BytesIO() # <<<<<<<<<<<<<< + * for piece_id in ids: + * piece = self._id_to_piece.get(piece_id, None) + */ + __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_BytesIO); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 101, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = NULL; + __pyx_t_4 = 0; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2); + if (likely(__pyx_t_3)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_2, function); + __pyx_t_4 = 1; + } + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, NULL}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_2, __pyx_callargs+1-__pyx_t_4, 0+__pyx_t_4); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 101, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } + __pyx_v_decoded = __pyx_t_1; + __pyx_t_1 = 0; + + /* "curated_tokenizers/_bbpe.pyx":102 + * """ + * decoded = BytesIO() + * for piece_id in ids: # <<<<<<<<<<<<<< + * piece = self._id_to_piece.get(piece_id, None) + * if piece is None: + */ + if (likely(PyList_CheckExact(__pyx_v_ids)) || PyTuple_CheckExact(__pyx_v_ids)) { + __pyx_t_1 = __pyx_v_ids; __Pyx_INCREF(__pyx_t_1); + __pyx_t_5 = 0; + __pyx_t_6 = NULL; + } else { + __pyx_t_5 = -1; __pyx_t_1 = PyObject_GetIter(__pyx_v_ids); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 102, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_6 = __Pyx_PyObject_GetIterNextFunc(__pyx_t_1); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 102, __pyx_L1_error) + } + for (;;) { + if (likely(!__pyx_t_6)) { + if (likely(PyList_CheckExact(__pyx_t_1))) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_1); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 102, __pyx_L1_error) + #endif + if (__pyx_t_5 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_2 = PyList_GET_ITEM(__pyx_t_1, __pyx_t_5); __Pyx_INCREF(__pyx_t_2); __pyx_t_5++; if (unlikely((0 < 0))) __PYX_ERR(0, 102, __pyx_L1_error) + #else + __pyx_t_2 = __Pyx_PySequence_ITEM(__pyx_t_1, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 102, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #endif + } else { + { + Py_ssize_t __pyx_temp = __Pyx_PyTuple_GET_SIZE(__pyx_t_1); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 102, __pyx_L1_error) + #endif + if (__pyx_t_5 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_2 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_5); __Pyx_INCREF(__pyx_t_2); __pyx_t_5++; if (unlikely((0 < 0))) __PYX_ERR(0, 102, __pyx_L1_error) + #else + __pyx_t_2 = __Pyx_PySequence_ITEM(__pyx_t_1, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 102, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #endif + } + } else { + __pyx_t_2 = __pyx_t_6(__pyx_t_1); + if (unlikely(!__pyx_t_2)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else __PYX_ERR(0, 102, __pyx_L1_error) + } + break; + } + __Pyx_GOTREF(__pyx_t_2); + } + __Pyx_XDECREF_SET(__pyx_v_piece_id, __pyx_t_2); + __pyx_t_2 = 0; + + /* "curated_tokenizers/_bbpe.pyx":103 + * decoded = BytesIO() + * for piece_id in ids: + * piece = self._id_to_piece.get(piece_id, None) # <<<<<<<<<<<<<< + * if piece is None: + * raise ValueError(f"Unknown piece identifier: {piece_id}") + */ + if (unlikely(__pyx_v_self->_id_to_piece == Py_None)) { + PyErr_Format(PyExc_AttributeError, "'NoneType' object has no attribute '%.30s'", "get"); + __PYX_ERR(0, 103, __pyx_L1_error) + } + __pyx_t_2 = __Pyx_PyDict_GetItemDefault(__pyx_v_self->_id_to_piece, __pyx_v_piece_id, Py_None); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 103, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_XDECREF_SET(__pyx_v_piece, __pyx_t_2); + __pyx_t_2 = 0; + + /* "curated_tokenizers/_bbpe.pyx":104 + * for piece_id in ids: + * piece = self._id_to_piece.get(piece_id, None) + * if piece is None: # <<<<<<<<<<<<<< + * raise ValueError(f"Unknown piece identifier: {piece_id}") + * decoded.write(bytes([self._byte_decoder[cp] for cp in list(piece)])) + */ + __pyx_t_7 = (__pyx_v_piece == Py_None); + if (unlikely(__pyx_t_7)) { + + /* "curated_tokenizers/_bbpe.pyx":105 + * piece = self._id_to_piece.get(piece_id, None) + * if piece is None: + * raise ValueError(f"Unknown piece identifier: {piece_id}") # <<<<<<<<<<<<<< + * decoded.write(bytes([self._byte_decoder[cp] for cp in list(piece)])) + * + */ + __pyx_t_2 = __Pyx_PyObject_FormatSimple(__pyx_v_piece_id, __pyx_empty_unicode); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 105, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyUnicode_Concat(__pyx_kp_u_Unknown_piece_identifier, __pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 105, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_builtin_ValueError, __pyx_t_3); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 105, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __PYX_ERR(0, 105, __pyx_L1_error) + + /* "curated_tokenizers/_bbpe.pyx":104 + * for piece_id in ids: + * piece = self._id_to_piece.get(piece_id, None) + * if piece is None: # <<<<<<<<<<<<<< + * raise ValueError(f"Unknown piece identifier: {piece_id}") + * decoded.write(bytes([self._byte_decoder[cp] for cp in list(piece)])) + */ + } + + /* "curated_tokenizers/_bbpe.pyx":106 + * if piece is None: + * raise ValueError(f"Unknown piece identifier: {piece_id}") + * decoded.write(bytes([self._byte_decoder[cp] for cp in list(piece)])) # <<<<<<<<<<<<<< + * + * return decoded.getvalue().decode("utf-8") + */ + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_decoded, __pyx_n_s_write); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 106, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_8 = PyList_New(0); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 106, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_9 = PySequence_List(__pyx_v_piece); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 106, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_10 = __pyx_t_9; __Pyx_INCREF(__pyx_t_10); + __pyx_t_11 = 0; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + for (;;) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_10); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 106, __pyx_L1_error) + #endif + if (__pyx_t_11 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_9 = PyList_GET_ITEM(__pyx_t_10, __pyx_t_11); __Pyx_INCREF(__pyx_t_9); __pyx_t_11++; if (unlikely((0 < 0))) __PYX_ERR(0, 106, __pyx_L1_error) + #else + __pyx_t_9 = __Pyx_PySequence_ITEM(__pyx_t_10, __pyx_t_11); __pyx_t_11++; if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 106, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + #endif + __Pyx_XDECREF_SET(__pyx_v_cp, __pyx_t_9); + __pyx_t_9 = 0; + if (unlikely(__pyx_v_self->_byte_decoder == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); + __PYX_ERR(0, 106, __pyx_L1_error) + } + __pyx_t_9 = __Pyx_PyDict_GetItem(__pyx_v_self->_byte_decoder, __pyx_v_cp); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 106, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + if (unlikely(__Pyx_ListComp_Append(__pyx_t_8, (PyObject*)__pyx_t_9))) __PYX_ERR(0, 106, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + } + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __pyx_t_10 = __Pyx_PyObject_CallOneArg(((PyObject *)(&PyBytes_Type)), __pyx_t_8); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 106, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_8 = NULL; + __pyx_t_4 = 0; + #if CYTHON_UNPACK_METHODS + if (likely(PyMethod_Check(__pyx_t_3))) { + __pyx_t_8 = PyMethod_GET_SELF(__pyx_t_3); + if (likely(__pyx_t_8)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); + __Pyx_INCREF(__pyx_t_8); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_3, function); + __pyx_t_4 = 1; + } + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_8, __pyx_t_10}; + __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_3, __pyx_callargs+1-__pyx_t_4, 1+__pyx_t_4); + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 106, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "curated_tokenizers/_bbpe.pyx":102 + * """ + * decoded = BytesIO() + * for piece_id in ids: # <<<<<<<<<<<<<< + * piece = self._id_to_piece.get(piece_id, None) + * if piece is None: + */ + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "curated_tokenizers/_bbpe.pyx":108 + * decoded.write(bytes([self._byte_decoder[cp] for cp in list(piece)])) + * + * return decoded.getvalue().decode("utf-8") # <<<<<<<<<<<<<< + * + * def encode(self, text: str) -> Tuple[List[int], List[str]]: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_decoded, __pyx_n_s_getvalue); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 108, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_10 = NULL; + __pyx_t_4 = 0; + #if CYTHON_UNPACK_METHODS + if (likely(PyMethod_Check(__pyx_t_3))) { + __pyx_t_10 = PyMethod_GET_SELF(__pyx_t_3); + if (likely(__pyx_t_10)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); + __Pyx_INCREF(__pyx_t_10); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_3, function); + __pyx_t_4 = 1; + } + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_10, NULL}; + __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_3, __pyx_callargs+1-__pyx_t_4, 0+__pyx_t_4); + __Pyx_XDECREF(__pyx_t_10); __pyx_t_10 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 108, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + } + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_decode); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 108, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = NULL; + __pyx_t_4 = 0; + #if CYTHON_UNPACK_METHODS + if (likely(PyMethod_Check(__pyx_t_3))) { + __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_3); + if (likely(__pyx_t_2)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_3, function); + __pyx_t_4 = 1; + } + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, __pyx_kp_s_utf_8}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_3, __pyx_callargs+1-__pyx_t_4, 1+__pyx_t_4); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 108, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + } + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "curated_tokenizers/_bbpe.pyx":94 + * return ByteBPEProcessor(vocab, merges) + * + * def decode_from_ids(self, ids: Iterable[int]) -> str: # <<<<<<<<<<<<<< + * """ + * Decode piece identifiers into string. + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_XDECREF(__pyx_t_10); + __Pyx_AddTraceback("curated_tokenizers._bbpe.ByteBPEProcessor.decode_from_ids", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_decoded); + __Pyx_XDECREF(__pyx_v_piece_id); + __Pyx_XDECREF(__pyx_v_piece); + __Pyx_XDECREF(__pyx_v_cp); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_bbpe.pyx":110 + * return decoded.getvalue().decode("utf-8") + * + * def encode(self, text: str) -> Tuple[List[int], List[str]]: # <<<<<<<<<<<<<< + * """ + * Split a text into pieces. + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_11encode(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_10encode, "ByteBPEProcessor.encode(self, text: str) -> Tuple[List[int], List[str]]\n\n Split a text into pieces.\n\n text: The text to split.\n RETURNS: A pair of pieces and piece identifiers.\n "); +static PyMethodDef __pyx_mdef_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_11encode = {"encode", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_11encode, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_10encode}; +static PyObject *__pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_11encode(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_text = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("encode (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_MACROS + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject **__pyx_pyargnames[] = {&__pyx_n_s_text,0}; + if (__pyx_kwds) { + Py_ssize_t kw_args; + switch (__pyx_nargs) { + case 1: values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = __Pyx_NumKwargs_FASTCALL(__pyx_kwds); + switch (__pyx_nargs) { + case 0: + if (likely((values[0] = __Pyx_GetKwValue_FASTCALL(__pyx_kwds, __pyx_kwvalues, __pyx_n_s_text)) != 0)) { + (void)__Pyx_Arg_NewRef_FASTCALL(values[0]); + kw_args--; + } + else if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 110, __pyx_L3_error) + else goto __pyx_L5_argtuple_error; + } + if (unlikely(kw_args > 0)) { + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values + 0, kwd_pos_args, "encode") < 0)) __PYX_ERR(0, 110, __pyx_L3_error) + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + } + __pyx_v_text = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("encode", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 110, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_AddTraceback("curated_tokenizers._bbpe.ByteBPEProcessor.encode", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_10encode(((struct __pyx_obj_18curated_tokenizers_5_bbpe_ByteBPEProcessor *)__pyx_v_self), __pyx_v_text); + + /* function exit code */ + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_10encode(struct __pyx_obj_18curated_tokenizers_5_bbpe_ByteBPEProcessor *__pyx_v_self, PyObject *__pyx_v_text) { + PyObject *__pyx_v_pieces = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_t_4; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("encode", 1); + + /* "curated_tokenizers/_bbpe.pyx":117 + * RETURNS: A pair of pieces and piece identifiers. + * """ + * pieces = self.encode_as_pieces(text) # <<<<<<<<<<<<<< + * return self._pieces_to_ids(pieces), pieces + * + */ + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_encode_as_pieces); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 117, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = NULL; + __pyx_t_4 = 0; + #if CYTHON_UNPACK_METHODS + if (likely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2); + if (likely(__pyx_t_3)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_2, function); + __pyx_t_4 = 1; + } + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_v_text}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_2, __pyx_callargs+1-__pyx_t_4, 1+__pyx_t_4); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 117, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } + __pyx_v_pieces = __pyx_t_1; + __pyx_t_1 = 0; + + /* "curated_tokenizers/_bbpe.pyx":118 + * """ + * pieces = self.encode_as_pieces(text) + * return self._pieces_to_ids(pieces), pieces # <<<<<<<<<<<<<< + * + * def encode_as_ids(self, text: str) -> List[int]: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_pieces_to_ids); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 118, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = NULL; + __pyx_t_4 = 0; + #if CYTHON_UNPACK_METHODS + if (likely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2); + if (likely(__pyx_t_3)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_2, function); + __pyx_t_4 = 1; + } + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_v_pieces}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_2, __pyx_callargs+1-__pyx_t_4, 1+__pyx_t_4); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 118, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } + __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 118, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_GIVEREF(__pyx_t_1); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1)) __PYX_ERR(0, 118, __pyx_L1_error); + __Pyx_INCREF(__pyx_v_pieces); + __Pyx_GIVEREF(__pyx_v_pieces); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_v_pieces)) __PYX_ERR(0, 118, __pyx_L1_error); + __pyx_t_1 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "curated_tokenizers/_bbpe.pyx":110 + * return decoded.getvalue().decode("utf-8") + * + * def encode(self, text: str) -> Tuple[List[int], List[str]]: # <<<<<<<<<<<<<< + * """ + * Split a text into pieces. + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("curated_tokenizers._bbpe.ByteBPEProcessor.encode", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_pieces); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_bbpe.pyx":120 + * return self._pieces_to_ids(pieces), pieces + * + * def encode_as_ids(self, text: str) -> List[int]: # <<<<<<<<<<<<<< + * """ + * Split a text into pieces, returning piece identifiers. + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_13encode_as_ids(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_12encode_as_ids, "ByteBPEProcessor.encode_as_ids(self, text: str) -> List[int]\n\n Split a text into pieces, returning piece identifiers.\n\n text: The text to split.\n RETURNS: Piece identifiers.\n "); +static PyMethodDef __pyx_mdef_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_13encode_as_ids = {"encode_as_ids", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_13encode_as_ids, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_12encode_as_ids}; +static PyObject *__pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_13encode_as_ids(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_text = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("encode_as_ids (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_MACROS + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject **__pyx_pyargnames[] = {&__pyx_n_s_text,0}; + if (__pyx_kwds) { + Py_ssize_t kw_args; + switch (__pyx_nargs) { + case 1: values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = __Pyx_NumKwargs_FASTCALL(__pyx_kwds); + switch (__pyx_nargs) { + case 0: + if (likely((values[0] = __Pyx_GetKwValue_FASTCALL(__pyx_kwds, __pyx_kwvalues, __pyx_n_s_text)) != 0)) { + (void)__Pyx_Arg_NewRef_FASTCALL(values[0]); + kw_args--; + } + else if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 120, __pyx_L3_error) + else goto __pyx_L5_argtuple_error; + } + if (unlikely(kw_args > 0)) { + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values + 0, kwd_pos_args, "encode_as_ids") < 0)) __PYX_ERR(0, 120, __pyx_L3_error) + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + } + __pyx_v_text = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("encode_as_ids", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 120, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_AddTraceback("curated_tokenizers._bbpe.ByteBPEProcessor.encode_as_ids", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_12encode_as_ids(((struct __pyx_obj_18curated_tokenizers_5_bbpe_ByteBPEProcessor *)__pyx_v_self), __pyx_v_text); + + /* function exit code */ + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_12encode_as_ids(struct __pyx_obj_18curated_tokenizers_5_bbpe_ByteBPEProcessor *__pyx_v_self, PyObject *__pyx_v_text) { + PyObject *__pyx_v_pieces = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_t_4; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("encode_as_ids", 1); + + /* "curated_tokenizers/_bbpe.pyx":127 + * RETURNS: Piece identifiers. + * """ + * pieces = self.encode_as_pieces(text) # <<<<<<<<<<<<<< + * return self._pieces_to_ids(pieces) + * + */ + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_encode_as_pieces); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 127, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = NULL; + __pyx_t_4 = 0; + #if CYTHON_UNPACK_METHODS + if (likely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2); + if (likely(__pyx_t_3)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_2, function); + __pyx_t_4 = 1; + } + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_v_text}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_2, __pyx_callargs+1-__pyx_t_4, 1+__pyx_t_4); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 127, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } + __pyx_v_pieces = __pyx_t_1; + __pyx_t_1 = 0; + + /* "curated_tokenizers/_bbpe.pyx":128 + * """ + * pieces = self.encode_as_pieces(text) + * return self._pieces_to_ids(pieces) # <<<<<<<<<<<<<< + * + * def encode_as_pieces(self, text: str) -> List[str]: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_pieces_to_ids); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 128, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = NULL; + __pyx_t_4 = 0; + #if CYTHON_UNPACK_METHODS + if (likely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2); + if (likely(__pyx_t_3)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_2, function); + __pyx_t_4 = 1; + } + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_v_pieces}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_2, __pyx_callargs+1-__pyx_t_4, 1+__pyx_t_4); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 128, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "curated_tokenizers/_bbpe.pyx":120 + * return self._pieces_to_ids(pieces), pieces + * + * def encode_as_ids(self, text: str) -> List[int]: # <<<<<<<<<<<<<< + * """ + * Split a text into pieces, returning piece identifiers. + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("curated_tokenizers._bbpe.ByteBPEProcessor.encode_as_ids", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_pieces); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_bbpe.pyx":130 + * return self._pieces_to_ids(pieces) + * + * def encode_as_pieces(self, text: str) -> List[str]: # <<<<<<<<<<<<<< + * """ + * Split a text into pieces, returning piece pieces. + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_15encode_as_pieces(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_14encode_as_pieces, "ByteBPEProcessor.encode_as_pieces(self, text: str) -> List[str]\n\n Split a text into pieces, returning piece pieces.\n\n text: The text to split.\n RETURNS: Piece pieces.\n "); +static PyMethodDef __pyx_mdef_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_15encode_as_pieces = {"encode_as_pieces", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_15encode_as_pieces, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_14encode_as_pieces}; +static PyObject *__pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_15encode_as_pieces(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_text = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("encode_as_pieces (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_MACROS + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject **__pyx_pyargnames[] = {&__pyx_n_s_text,0}; + if (__pyx_kwds) { + Py_ssize_t kw_args; + switch (__pyx_nargs) { + case 1: values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = __Pyx_NumKwargs_FASTCALL(__pyx_kwds); + switch (__pyx_nargs) { + case 0: + if (likely((values[0] = __Pyx_GetKwValue_FASTCALL(__pyx_kwds, __pyx_kwvalues, __pyx_n_s_text)) != 0)) { + (void)__Pyx_Arg_NewRef_FASTCALL(values[0]); + kw_args--; + } + else if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 130, __pyx_L3_error) + else goto __pyx_L5_argtuple_error; + } + if (unlikely(kw_args > 0)) { + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values + 0, kwd_pos_args, "encode_as_pieces") < 0)) __PYX_ERR(0, 130, __pyx_L3_error) + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + } + __pyx_v_text = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("encode_as_pieces", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 130, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_AddTraceback("curated_tokenizers._bbpe.ByteBPEProcessor.encode_as_pieces", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_14encode_as_pieces(((struct __pyx_obj_18curated_tokenizers_5_bbpe_ByteBPEProcessor *)__pyx_v_self), __pyx_v_text); + + /* function exit code */ + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} +static PyObject *__pyx_gb_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_16encode_as_pieces_2generator(__pyx_CoroutineObject *__pyx_generator, CYTHON_UNUSED PyThreadState *__pyx_tstate, PyObject *__pyx_sent_value); /* proto */ + +/* "curated_tokenizers/_bbpe.pyx":141 + * token_bytes = [self._byte_encoder[b] for b in token.encode("utf-8")] + * merged = deref(self._merges).apply_merges(token_bytes) + * pieces.extend(merge.decode("utf-8") for merge in merged) # <<<<<<<<<<<<<< + * return pieces + * + */ + +static PyObject *__pyx_pf_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_16encode_as_pieces_genexpr(CYTHON_UNUSED PyObject *__pyx_self, std::vector __pyx_genexpr_arg_0) { + struct __pyx_obj_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr *__pyx_cur_scope; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("genexpr", 0); + __pyx_cur_scope = (struct __pyx_obj_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr *)__pyx_tp_new_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr(__pyx_ptype_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr, __pyx_empty_tuple, NULL); + if (unlikely(!__pyx_cur_scope)) { + __pyx_cur_scope = ((struct __pyx_obj_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr *)Py_None); + __Pyx_INCREF(Py_None); + __PYX_ERR(0, 141, __pyx_L1_error) + } else { + __Pyx_GOTREF((PyObject *)__pyx_cur_scope); + } + __pyx_cur_scope->__pyx_genexpr_arg_0 = __pyx_genexpr_arg_0; + { + __pyx_CoroutineObject *gen = __Pyx_Generator_New((__pyx_coroutine_body_t) __pyx_gb_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_16encode_as_pieces_2generator, NULL, (PyObject *) __pyx_cur_scope, __pyx_n_s_genexpr, __pyx_n_s_encode_as_pieces_locals_genexpr, __pyx_n_s_curated_tokenizers__bbpe); if (unlikely(!gen)) __PYX_ERR(0, 141, __pyx_L1_error) + __Pyx_DECREF(__pyx_cur_scope); + __Pyx_RefNannyFinishContext(); + return (PyObject *) gen; + } + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("curated_tokenizers._bbpe.ByteBPEProcessor.encode_as_pieces.genexpr", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __Pyx_DECREF((PyObject *)__pyx_cur_scope); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_gb_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_16encode_as_pieces_2generator(__pyx_CoroutineObject *__pyx_generator, CYTHON_UNUSED PyThreadState *__pyx_tstate, PyObject *__pyx_sent_value) /* generator body */ +{ + struct __pyx_obj_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr *__pyx_cur_scope = ((struct __pyx_obj_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr *)__pyx_generator->closure); + PyObject *__pyx_r = NULL; + std::vector ::iterator __pyx_t_1; + std::string __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("genexpr", 0); + switch (__pyx_generator->resume_label) { + case 0: goto __pyx_L3_first_run; + case 1: goto __pyx_L6_resume_from_yield; + default: /* CPython raises the right error here */ + __Pyx_RefNannyFinishContext(); + return NULL; + } + __pyx_L3_first_run:; + if (unlikely(!__pyx_sent_value)) __PYX_ERR(0, 141, __pyx_L1_error) + __pyx_t_1 = __pyx_cur_scope->__pyx_genexpr_arg_0.begin(); + for (;;) { + if (!(__pyx_t_1 != __pyx_cur_scope->__pyx_genexpr_arg_0.end())) break; + __pyx_t_2 = *__pyx_t_1; + ++__pyx_t_1; + __pyx_cur_scope->__pyx_v_merge = __PYX_STD_MOVE_IF_SUPPORTED(__pyx_t_2); + __pyx_t_3 = __Pyx_decode_cpp_string(__pyx_cur_scope->__pyx_v_merge, 0, PY_SSIZE_T_MAX, NULL, NULL, PyUnicode_DecodeUTF8); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 141, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + __pyx_cur_scope->__pyx_t_0 = __PYX_STD_MOVE_IF_SUPPORTED(__pyx_t_1); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + __Pyx_Coroutine_ResetAndClearException(__pyx_generator); + /* return from generator, yielding value */ + __pyx_generator->resume_label = 1; + return __pyx_r; + __pyx_L6_resume_from_yield:; + __pyx_t_1 = __PYX_STD_MOVE_IF_SUPPORTED(__pyx_cur_scope->__pyx_t_0); + if (unlikely(!__pyx_sent_value)) __PYX_ERR(0, 141, __pyx_L1_error) + } + CYTHON_MAYBE_UNUSED_VAR(__pyx_cur_scope); + + /* function exit code */ + PyErr_SetNone(PyExc_StopIteration); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("genexpr", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_L0:; + __Pyx_XDECREF(__pyx_r); __pyx_r = 0; + #if !CYTHON_USE_EXC_INFO_STACK + __Pyx_Coroutine_ResetAndClearException(__pyx_generator); + #endif + __pyx_generator->resume_label = -1; + __Pyx_Coroutine_clear((PyObject*)__pyx_generator); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_bbpe.pyx":130 + * return self._pieces_to_ids(pieces) + * + * def encode_as_pieces(self, text: str) -> List[str]: # <<<<<<<<<<<<<< + * """ + * Split a text into pieces, returning piece pieces. + */ + +static PyObject *__pyx_pf_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_14encode_as_pieces(struct __pyx_obj_18curated_tokenizers_5_bbpe_ByteBPEProcessor *__pyx_v_self, PyObject *__pyx_v_text) { + PyObject *__pyx_v_pieces = NULL; + PyObject *__pyx_v_token = NULL; + PyObject *__pyx_v_token_bytes = NULL; + std::vector __pyx_v_merged; + PyObject *__pyx_v_b = NULL; + PyObject *__pyx_gb_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_16encode_as_pieces_2generator = 0; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_t_4; + Py_ssize_t __pyx_t_5; + PyObject *(*__pyx_t_6)(PyObject *); + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + Py_ssize_t __pyx_t_9; + PyObject *(*__pyx_t_10)(PyObject *); + std::vector __pyx_t_11; + int __pyx_t_12; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("encode_as_pieces", 1); + + /* "curated_tokenizers/_bbpe.pyx":137 + * RETURNS: Piece pieces. + * """ + * pieces = [] # <<<<<<<<<<<<<< + * for token in regex.findall(self._split_pattern, text): + * token_bytes = [self._byte_encoder[b] for b in token.encode("utf-8")] + */ + __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 137, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_pieces = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + + /* "curated_tokenizers/_bbpe.pyx":138 + * """ + * pieces = [] + * for token in regex.findall(self._split_pattern, text): # <<<<<<<<<<<<<< + * token_bytes = [self._byte_encoder[b] for b in token.encode("utf-8")] + * merged = deref(self._merges).apply_merges(token_bytes) + */ + __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_regex); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 138, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_findall); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 138, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = NULL; + __pyx_t_4 = 0; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_3))) { + __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_3); + if (likely(__pyx_t_2)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_3, function); + __pyx_t_4 = 1; + } + } + #endif + { + PyObject *__pyx_callargs[3] = {__pyx_t_2, __pyx_v_self->_split_pattern, __pyx_v_text}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_3, __pyx_callargs+1-__pyx_t_4, 2+__pyx_t_4); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 138, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + } + if (likely(PyList_CheckExact(__pyx_t_1)) || PyTuple_CheckExact(__pyx_t_1)) { + __pyx_t_3 = __pyx_t_1; __Pyx_INCREF(__pyx_t_3); + __pyx_t_5 = 0; + __pyx_t_6 = NULL; + } else { + __pyx_t_5 = -1; __pyx_t_3 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 138, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_6 = __Pyx_PyObject_GetIterNextFunc(__pyx_t_3); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 138, __pyx_L1_error) + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + for (;;) { + if (likely(!__pyx_t_6)) { + if (likely(PyList_CheckExact(__pyx_t_3))) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_3); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 138, __pyx_L1_error) + #endif + if (__pyx_t_5 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_1 = PyList_GET_ITEM(__pyx_t_3, __pyx_t_5); __Pyx_INCREF(__pyx_t_1); __pyx_t_5++; if (unlikely((0 < 0))) __PYX_ERR(0, 138, __pyx_L1_error) + #else + __pyx_t_1 = __Pyx_PySequence_ITEM(__pyx_t_3, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 138, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + #endif + } else { + { + Py_ssize_t __pyx_temp = __Pyx_PyTuple_GET_SIZE(__pyx_t_3); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 138, __pyx_L1_error) + #endif + if (__pyx_t_5 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_1 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_5); __Pyx_INCREF(__pyx_t_1); __pyx_t_5++; if (unlikely((0 < 0))) __PYX_ERR(0, 138, __pyx_L1_error) + #else + __pyx_t_1 = __Pyx_PySequence_ITEM(__pyx_t_3, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 138, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + #endif + } + } else { + __pyx_t_1 = __pyx_t_6(__pyx_t_3); + if (unlikely(!__pyx_t_1)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else __PYX_ERR(0, 138, __pyx_L1_error) + } + break; + } + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_XDECREF_SET(__pyx_v_token, __pyx_t_1); + __pyx_t_1 = 0; + + /* "curated_tokenizers/_bbpe.pyx":139 + * pieces = [] + * for token in regex.findall(self._split_pattern, text): + * token_bytes = [self._byte_encoder[b] for b in token.encode("utf-8")] # <<<<<<<<<<<<<< + * merged = deref(self._merges).apply_merges(token_bytes) + * pieces.extend(merge.decode("utf-8") for merge in merged) + */ + __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 139, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_v_token, __pyx_n_s_encode); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 139, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_8 = NULL; + __pyx_t_4 = 0; + #if CYTHON_UNPACK_METHODS + if (likely(PyMethod_Check(__pyx_t_7))) { + __pyx_t_8 = PyMethod_GET_SELF(__pyx_t_7); + if (likely(__pyx_t_8)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_7); + __Pyx_INCREF(__pyx_t_8); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_7, function); + __pyx_t_4 = 1; + } + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_8, __pyx_kp_s_utf_8}; + __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_7, __pyx_callargs+1-__pyx_t_4, 1+__pyx_t_4); + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 139, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + } + if (likely(PyList_CheckExact(__pyx_t_2)) || PyTuple_CheckExact(__pyx_t_2)) { + __pyx_t_7 = __pyx_t_2; __Pyx_INCREF(__pyx_t_7); + __pyx_t_9 = 0; + __pyx_t_10 = NULL; + } else { + __pyx_t_9 = -1; __pyx_t_7 = PyObject_GetIter(__pyx_t_2); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 139, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_10 = __Pyx_PyObject_GetIterNextFunc(__pyx_t_7); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 139, __pyx_L1_error) + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + for (;;) { + if (likely(!__pyx_t_10)) { + if (likely(PyList_CheckExact(__pyx_t_7))) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_7); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 139, __pyx_L1_error) + #endif + if (__pyx_t_9 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_2 = PyList_GET_ITEM(__pyx_t_7, __pyx_t_9); __Pyx_INCREF(__pyx_t_2); __pyx_t_9++; if (unlikely((0 < 0))) __PYX_ERR(0, 139, __pyx_L1_error) + #else + __pyx_t_2 = __Pyx_PySequence_ITEM(__pyx_t_7, __pyx_t_9); __pyx_t_9++; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 139, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #endif + } else { + { + Py_ssize_t __pyx_temp = __Pyx_PyTuple_GET_SIZE(__pyx_t_7); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 139, __pyx_L1_error) + #endif + if (__pyx_t_9 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_2 = PyTuple_GET_ITEM(__pyx_t_7, __pyx_t_9); __Pyx_INCREF(__pyx_t_2); __pyx_t_9++; if (unlikely((0 < 0))) __PYX_ERR(0, 139, __pyx_L1_error) + #else + __pyx_t_2 = __Pyx_PySequence_ITEM(__pyx_t_7, __pyx_t_9); __pyx_t_9++; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 139, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #endif + } + } else { + __pyx_t_2 = __pyx_t_10(__pyx_t_7); + if (unlikely(!__pyx_t_2)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else __PYX_ERR(0, 139, __pyx_L1_error) + } + break; + } + __Pyx_GOTREF(__pyx_t_2); + } + __Pyx_XDECREF_SET(__pyx_v_b, __pyx_t_2); + __pyx_t_2 = 0; + if (unlikely(__pyx_v_self->_byte_encoder == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); + __PYX_ERR(0, 139, __pyx_L1_error) + } + __pyx_t_2 = __Pyx_PyDict_GetItem(__pyx_v_self->_byte_encoder, __pyx_v_b); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 139, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (unlikely(__Pyx_ListComp_Append(__pyx_t_1, (PyObject*)__pyx_t_2))) __PYX_ERR(0, 139, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_XDECREF_SET(__pyx_v_token_bytes, ((PyObject*)__pyx_t_1)); + __pyx_t_1 = 0; + + /* "curated_tokenizers/_bbpe.pyx":140 + * for token in regex.findall(self._split_pattern, text): + * token_bytes = [self._byte_encoder[b] for b in token.encode("utf-8")] + * merged = deref(self._merges).apply_merges(token_bytes) # <<<<<<<<<<<<<< + * pieces.extend(merge.decode("utf-8") for merge in merged) + * return pieces + */ + __pyx_t_11 = __pyx_convert_vector_from_py_std_3a__3a_string(__pyx_v_token_bytes); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 140, __pyx_L1_error) + __pyx_v_merged = (*__pyx_v_self->_merges).apply_merges(__PYX_STD_MOVE_IF_SUPPORTED(__pyx_t_11)); + + /* "curated_tokenizers/_bbpe.pyx":141 + * token_bytes = [self._byte_encoder[b] for b in token.encode("utf-8")] + * merged = deref(self._merges).apply_merges(token_bytes) + * pieces.extend(merge.decode("utf-8") for merge in merged) # <<<<<<<<<<<<<< + * return pieces + * + */ + __pyx_t_1 = __pyx_pf_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_16encode_as_pieces_genexpr(NULL, __pyx_v_merged); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 141, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_12 = __Pyx_PyList_Extend(__pyx_v_pieces, __pyx_t_1); if (unlikely(__pyx_t_12 == ((int)-1))) __PYX_ERR(0, 141, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "curated_tokenizers/_bbpe.pyx":138 + * """ + * pieces = [] + * for token in regex.findall(self._split_pattern, text): # <<<<<<<<<<<<<< + * token_bytes = [self._byte_encoder[b] for b in token.encode("utf-8")] + * merged = deref(self._merges).apply_merges(token_bytes) + */ + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "curated_tokenizers/_bbpe.pyx":142 + * merged = deref(self._merges).apply_merges(token_bytes) + * pieces.extend(merge.decode("utf-8") for merge in merged) + * return pieces # <<<<<<<<<<<<<< + * + * @property + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_pieces); + __pyx_r = __pyx_v_pieces; + goto __pyx_L0; + + /* "curated_tokenizers/_bbpe.pyx":130 + * return self._pieces_to_ids(pieces) + * + * def encode_as_pieces(self, text: str) -> List[str]: # <<<<<<<<<<<<<< + * """ + * Split a text into pieces, returning piece pieces. + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_AddTraceback("curated_tokenizers._bbpe.ByteBPEProcessor.encode_as_pieces", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_pieces); + __Pyx_XDECREF(__pyx_v_token); + __Pyx_XDECREF(__pyx_v_token_bytes); + __Pyx_XDECREF(__pyx_v_b); + __Pyx_XDECREF(__pyx_gb_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_16encode_as_pieces_2generator); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_bbpe.pyx":144 + * return pieces + * + * @property # <<<<<<<<<<<<<< + * def merges(self) -> List[Tuple[str, str]]: + * """Get all merges.""" + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_6merges_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_6merges_1__get__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_6merges___get__(((struct __pyx_obj_18curated_tokenizers_5_bbpe_ByteBPEProcessor *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_6merges___get__(struct __pyx_obj_18curated_tokenizers_5_bbpe_ByteBPEProcessor *__pyx_v_self) { + std::vector > __pyx_v_merges_bytes; + PyObject *__pyx_v_m1 = NULL; + PyObject *__pyx_v_m2 = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + std::vector > ::iterator __pyx_t_2; + std::pair __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *(*__pyx_t_8)(PyObject *); + int __pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 1); + + /* "curated_tokenizers/_bbpe.pyx":147 + * def merges(self) -> List[Tuple[str, str]]: + * """Get all merges.""" + * merges_bytes = deref(self._merges).merges() # <<<<<<<<<<<<<< + * return [(m1.decode('utf-8'), m2.decode('utf-8')) for m1, m2 in merges_bytes] + * + */ + __pyx_v_merges_bytes = (*__pyx_v_self->_merges).merges(); + + /* "curated_tokenizers/_bbpe.pyx":148 + * """Get all merges.""" + * merges_bytes = deref(self._merges).merges() + * return [(m1.decode('utf-8'), m2.decode('utf-8')) for m1, m2 in merges_bytes] # <<<<<<<<<<<<<< + * + * def piece_id(self, piece: str) -> Optional[int]: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 148, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __pyx_v_merges_bytes.begin(); + for (;;) { + if (!(__pyx_t_2 != __pyx_v_merges_bytes.end())) break; + __pyx_t_3 = *__pyx_t_2; + ++__pyx_t_2; + __pyx_t_4 = __pyx_convert_pair_to_py_std_3a__3a_string____std_3a__3a_string(__pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 148, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + if ((likely(PyTuple_CheckExact(__pyx_t_4))) || (PyList_CheckExact(__pyx_t_4))) { + PyObject* sequence = __pyx_t_4; + Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + __PYX_ERR(0, 148, __pyx_L1_error) + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_5 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_6 = PyTuple_GET_ITEM(sequence, 1); + } else { + __pyx_t_5 = PyList_GET_ITEM(sequence, 0); + __pyx_t_6 = PyList_GET_ITEM(sequence, 1); + } + __Pyx_INCREF(__pyx_t_5); + __Pyx_INCREF(__pyx_t_6); + #else + __pyx_t_5 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 148, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 148, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + #endif + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + } else { + Py_ssize_t index = -1; + __pyx_t_7 = PyObject_GetIter(__pyx_t_4); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 148, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_8 = __Pyx_PyObject_GetIterNextFunc(__pyx_t_7); + index = 0; __pyx_t_5 = __pyx_t_8(__pyx_t_7); if (unlikely(!__pyx_t_5)) goto __pyx_L5_unpacking_failed; + __Pyx_GOTREF(__pyx_t_5); + index = 1; __pyx_t_6 = __pyx_t_8(__pyx_t_7); if (unlikely(!__pyx_t_6)) goto __pyx_L5_unpacking_failed; + __Pyx_GOTREF(__pyx_t_6); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_8(__pyx_t_7), 2) < 0) __PYX_ERR(0, 148, __pyx_L1_error) + __pyx_t_8 = NULL; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + goto __pyx_L6_unpacking_done; + __pyx_L5_unpacking_failed:; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_8 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + __PYX_ERR(0, 148, __pyx_L1_error) + __pyx_L6_unpacking_done:; + } + __Pyx_XDECREF_SET(__pyx_v_m1, __pyx_t_5); + __pyx_t_5 = 0; + __Pyx_XDECREF_SET(__pyx_v_m2, __pyx_t_6); + __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_m1, __pyx_n_s_decode); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 148, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_5 = NULL; + __pyx_t_9 = 0; + #if CYTHON_UNPACK_METHODS + if (likely(PyMethod_Check(__pyx_t_6))) { + __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_6); + if (likely(__pyx_t_5)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_6); + __Pyx_INCREF(__pyx_t_5); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_6, function); + __pyx_t_9 = 1; + } + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_5, __pyx_kp_s_utf_8}; + __pyx_t_4 = __Pyx_PyObject_FastCall(__pyx_t_6, __pyx_callargs+1-__pyx_t_9, 1+__pyx_t_9); + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 148, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + } + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_m2, __pyx_n_s_decode); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 148, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_7 = NULL; + __pyx_t_9 = 0; + #if CYTHON_UNPACK_METHODS + if (likely(PyMethod_Check(__pyx_t_5))) { + __pyx_t_7 = PyMethod_GET_SELF(__pyx_t_5); + if (likely(__pyx_t_7)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_5); + __Pyx_INCREF(__pyx_t_7); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_5, function); + __pyx_t_9 = 1; + } + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_7, __pyx_kp_s_utf_8}; + __pyx_t_6 = __Pyx_PyObject_FastCall(__pyx_t_5, __pyx_callargs+1-__pyx_t_9, 1+__pyx_t_9); + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 148, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + } + __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 148, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_GIVEREF(__pyx_t_4); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4)) __PYX_ERR(0, 148, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_6); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_6)) __PYX_ERR(0, 148, __pyx_L1_error); + __pyx_t_4 = 0; + __pyx_t_6 = 0; + if (unlikely(__Pyx_ListComp_Append(__pyx_t_1, (PyObject*)__pyx_t_5))) __PYX_ERR(0, 148, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + } + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "curated_tokenizers/_bbpe.pyx":144 + * return pieces + * + * @property # <<<<<<<<<<<<<< + * def merges(self) -> List[Tuple[str, str]]: + * """Get all merges.""" + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_AddTraceback("curated_tokenizers._bbpe.ByteBPEProcessor.merges.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_m1); + __Pyx_XDECREF(__pyx_v_m2); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_bbpe.pyx":150 + * return [(m1.decode('utf-8'), m2.decode('utf-8')) for m1, m2 in merges_bytes] + * + * def piece_id(self, piece: str) -> Optional[int]: # <<<<<<<<<<<<<< + * """Get the identifier for a piece.""" + * return self._piece_to_id.get(piece) + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_17piece_id(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_16piece_id, "ByteBPEProcessor.piece_id(self, piece: str) -> Optional[int]\nGet the identifier for a piece."); +static PyMethodDef __pyx_mdef_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_17piece_id = {"piece_id", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_17piece_id, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_16piece_id}; +static PyObject *__pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_17piece_id(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_piece = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("piece_id (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_MACROS + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject **__pyx_pyargnames[] = {&__pyx_n_s_piece,0}; + if (__pyx_kwds) { + Py_ssize_t kw_args; + switch (__pyx_nargs) { + case 1: values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = __Pyx_NumKwargs_FASTCALL(__pyx_kwds); + switch (__pyx_nargs) { + case 0: + if (likely((values[0] = __Pyx_GetKwValue_FASTCALL(__pyx_kwds, __pyx_kwvalues, __pyx_n_s_piece)) != 0)) { + (void)__Pyx_Arg_NewRef_FASTCALL(values[0]); + kw_args--; + } + else if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 150, __pyx_L3_error) + else goto __pyx_L5_argtuple_error; + } + if (unlikely(kw_args > 0)) { + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values + 0, kwd_pos_args, "piece_id") < 0)) __PYX_ERR(0, 150, __pyx_L3_error) + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + } + __pyx_v_piece = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("piece_id", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 150, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_AddTraceback("curated_tokenizers._bbpe.ByteBPEProcessor.piece_id", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_16piece_id(((struct __pyx_obj_18curated_tokenizers_5_bbpe_ByteBPEProcessor *)__pyx_v_self), __pyx_v_piece); + + /* function exit code */ + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_16piece_id(struct __pyx_obj_18curated_tokenizers_5_bbpe_ByteBPEProcessor *__pyx_v_self, PyObject *__pyx_v_piece) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("piece_id", 1); + + /* "curated_tokenizers/_bbpe.pyx":152 + * def piece_id(self, piece: str) -> Optional[int]: + * """Get the identifier for a piece.""" + * return self._piece_to_id.get(piece) # <<<<<<<<<<<<<< + * + * @property + */ + __Pyx_XDECREF(__pyx_r); + if (unlikely(__pyx_v_self->_piece_to_id == Py_None)) { + PyErr_Format(PyExc_AttributeError, "'NoneType' object has no attribute '%.30s'", "get"); + __PYX_ERR(0, 152, __pyx_L1_error) + } + __pyx_t_1 = __Pyx_PyDict_GetItemDefault(__pyx_v_self->_piece_to_id, __pyx_v_piece, Py_None); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 152, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "curated_tokenizers/_bbpe.pyx":150 + * return [(m1.decode('utf-8'), m2.decode('utf-8')) for m1, m2 in merges_bytes] + * + * def piece_id(self, piece: str) -> Optional[int]: # <<<<<<<<<<<<<< + * """Get the identifier for a piece.""" + * return self._piece_to_id.get(piece) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("curated_tokenizers._bbpe.ByteBPEProcessor.piece_id", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_bbpe.pyx":154 + * return self._piece_to_id.get(piece) + * + * @property # <<<<<<<<<<<<<< + * def vocab(self) -> Dict[str, int]: + * """Get a copy of the vocabulary.""" + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_5vocab_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_5vocab_1__get__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_5vocab___get__(((struct __pyx_obj_18curated_tokenizers_5_bbpe_ByteBPEProcessor *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_5vocab___get__(struct __pyx_obj_18curated_tokenizers_5_bbpe_ByteBPEProcessor *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__get__", 1); + + /* "curated_tokenizers/_bbpe.pyx":157 + * def vocab(self) -> Dict[str, int]: + * """Get a copy of the vocabulary.""" + * return dict(self._piece_to_id) # <<<<<<<<<<<<<< + * + * def _pieces_to_ids(self, pieces): + */ + __Pyx_XDECREF(__pyx_r); + if (unlikely(__pyx_v_self->_piece_to_id == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' is not iterable"); + __PYX_ERR(0, 157, __pyx_L1_error) + } + __pyx_t_1 = PyDict_Copy(__pyx_v_self->_piece_to_id); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 157, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "curated_tokenizers/_bbpe.pyx":154 + * return self._piece_to_id.get(piece) + * + * @property # <<<<<<<<<<<<<< + * def vocab(self) -> Dict[str, int]: + * """Get a copy of the vocabulary.""" + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("curated_tokenizers._bbpe.ByteBPEProcessor.vocab.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_bbpe.pyx":159 + * return dict(self._piece_to_id) + * + * def _pieces_to_ids(self, pieces): # <<<<<<<<<<<<<< + * piece_ids = [] + * for piece in pieces: + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_19_pieces_to_ids(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_18_pieces_to_ids, "ByteBPEProcessor._pieces_to_ids(self, pieces)"); +static PyMethodDef __pyx_mdef_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_19_pieces_to_ids = {"_pieces_to_ids", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_19_pieces_to_ids, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_18_pieces_to_ids}; +static PyObject *__pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_19_pieces_to_ids(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_pieces = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_pieces_to_ids (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_MACROS + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject **__pyx_pyargnames[] = {&__pyx_n_s_pieces,0}; + if (__pyx_kwds) { + Py_ssize_t kw_args; + switch (__pyx_nargs) { + case 1: values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = __Pyx_NumKwargs_FASTCALL(__pyx_kwds); + switch (__pyx_nargs) { + case 0: + if (likely((values[0] = __Pyx_GetKwValue_FASTCALL(__pyx_kwds, __pyx_kwvalues, __pyx_n_s_pieces)) != 0)) { + (void)__Pyx_Arg_NewRef_FASTCALL(values[0]); + kw_args--; + } + else if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 159, __pyx_L3_error) + else goto __pyx_L5_argtuple_error; + } + if (unlikely(kw_args > 0)) { + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values + 0, kwd_pos_args, "_pieces_to_ids") < 0)) __PYX_ERR(0, 159, __pyx_L3_error) + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + } + __pyx_v_pieces = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("_pieces_to_ids", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 159, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_AddTraceback("curated_tokenizers._bbpe.ByteBPEProcessor._pieces_to_ids", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_18_pieces_to_ids(((struct __pyx_obj_18curated_tokenizers_5_bbpe_ByteBPEProcessor *)__pyx_v_self), __pyx_v_pieces); + + /* function exit code */ + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_18_pieces_to_ids(struct __pyx_obj_18curated_tokenizers_5_bbpe_ByteBPEProcessor *__pyx_v_self, PyObject *__pyx_v_pieces) { + PyObject *__pyx_v_piece_ids = NULL; + PyObject *__pyx_v_piece = NULL; + PyObject *__pyx_v_piece_id = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + Py_ssize_t __pyx_t_2; + PyObject *(*__pyx_t_3)(PyObject *); + PyObject *__pyx_t_4 = NULL; + int __pyx_t_5; + PyObject *__pyx_t_6 = NULL; + int __pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_pieces_to_ids", 1); + + /* "curated_tokenizers/_bbpe.pyx":160 + * + * def _pieces_to_ids(self, pieces): + * piece_ids = [] # <<<<<<<<<<<<<< + * for piece in pieces: + * piece_id = self._piece_to_id.get(piece) + */ + __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 160, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_piece_ids = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + + /* "curated_tokenizers/_bbpe.pyx":161 + * def _pieces_to_ids(self, pieces): + * piece_ids = [] + * for piece in pieces: # <<<<<<<<<<<<<< + * piece_id = self._piece_to_id.get(piece) + * if piece_id is None: + */ + if (likely(PyList_CheckExact(__pyx_v_pieces)) || PyTuple_CheckExact(__pyx_v_pieces)) { + __pyx_t_1 = __pyx_v_pieces; __Pyx_INCREF(__pyx_t_1); + __pyx_t_2 = 0; + __pyx_t_3 = NULL; + } else { + __pyx_t_2 = -1; __pyx_t_1 = PyObject_GetIter(__pyx_v_pieces); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 161, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PyObject_GetIterNextFunc(__pyx_t_1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 161, __pyx_L1_error) + } + for (;;) { + if (likely(!__pyx_t_3)) { + if (likely(PyList_CheckExact(__pyx_t_1))) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_1); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 161, __pyx_L1_error) + #endif + if (__pyx_t_2 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_4 = PyList_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_4); __pyx_t_2++; if (unlikely((0 < 0))) __PYX_ERR(0, 161, __pyx_L1_error) + #else + __pyx_t_4 = __Pyx_PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 161, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + #endif + } else { + { + Py_ssize_t __pyx_temp = __Pyx_PyTuple_GET_SIZE(__pyx_t_1); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 161, __pyx_L1_error) + #endif + if (__pyx_t_2 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_4 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_4); __pyx_t_2++; if (unlikely((0 < 0))) __PYX_ERR(0, 161, __pyx_L1_error) + #else + __pyx_t_4 = __Pyx_PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 161, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + #endif + } + } else { + __pyx_t_4 = __pyx_t_3(__pyx_t_1); + if (unlikely(!__pyx_t_4)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else __PYX_ERR(0, 161, __pyx_L1_error) + } + break; + } + __Pyx_GOTREF(__pyx_t_4); + } + __Pyx_XDECREF_SET(__pyx_v_piece, __pyx_t_4); + __pyx_t_4 = 0; + + /* "curated_tokenizers/_bbpe.pyx":162 + * piece_ids = [] + * for piece in pieces: + * piece_id = self._piece_to_id.get(piece) # <<<<<<<<<<<<<< + * if piece_id is None: + * raise ValueError(f"Piece is not in vocabulary: {piece}") + */ + if (unlikely(__pyx_v_self->_piece_to_id == Py_None)) { + PyErr_Format(PyExc_AttributeError, "'NoneType' object has no attribute '%.30s'", "get"); + __PYX_ERR(0, 162, __pyx_L1_error) + } + __pyx_t_4 = __Pyx_PyDict_GetItemDefault(__pyx_v_self->_piece_to_id, __pyx_v_piece, Py_None); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 162, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_XDECREF_SET(__pyx_v_piece_id, __pyx_t_4); + __pyx_t_4 = 0; + + /* "curated_tokenizers/_bbpe.pyx":163 + * for piece in pieces: + * piece_id = self._piece_to_id.get(piece) + * if piece_id is None: # <<<<<<<<<<<<<< + * raise ValueError(f"Piece is not in vocabulary: {piece}") + * piece_ids.append(piece_id) + */ + __pyx_t_5 = (__pyx_v_piece_id == Py_None); + if (unlikely(__pyx_t_5)) { + + /* "curated_tokenizers/_bbpe.pyx":164 + * piece_id = self._piece_to_id.get(piece) + * if piece_id is None: + * raise ValueError(f"Piece is not in vocabulary: {piece}") # <<<<<<<<<<<<<< + * piece_ids.append(piece_id) + * + */ + __pyx_t_4 = __Pyx_PyObject_FormatSimple(__pyx_v_piece, __pyx_empty_unicode); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 164, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_6 = __Pyx_PyUnicode_Concat(__pyx_kp_u_Piece_is_not_in_vocabulary, __pyx_t_4); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 164, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = __Pyx_PyObject_CallOneArg(__pyx_builtin_ValueError, __pyx_t_6); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 164, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __PYX_ERR(0, 164, __pyx_L1_error) + + /* "curated_tokenizers/_bbpe.pyx":163 + * for piece in pieces: + * piece_id = self._piece_to_id.get(piece) + * if piece_id is None: # <<<<<<<<<<<<<< + * raise ValueError(f"Piece is not in vocabulary: {piece}") + * piece_ids.append(piece_id) + */ + } + + /* "curated_tokenizers/_bbpe.pyx":165 + * if piece_id is None: + * raise ValueError(f"Piece is not in vocabulary: {piece}") + * piece_ids.append(piece_id) # <<<<<<<<<<<<<< + * + * return piece_ids + */ + __pyx_t_7 = __Pyx_PyList_Append(__pyx_v_piece_ids, __pyx_v_piece_id); if (unlikely(__pyx_t_7 == ((int)-1))) __PYX_ERR(0, 165, __pyx_L1_error) + + /* "curated_tokenizers/_bbpe.pyx":161 + * def _pieces_to_ids(self, pieces): + * piece_ids = [] + * for piece in pieces: # <<<<<<<<<<<<<< + * piece_id = self._piece_to_id.get(piece) + * if piece_id is None: + */ + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "curated_tokenizers/_bbpe.pyx":167 + * piece_ids.append(piece_id) + * + * return piece_ids # <<<<<<<<<<<<<< + * + * def __reduce__(self): + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_piece_ids); + __pyx_r = __pyx_v_piece_ids; + goto __pyx_L0; + + /* "curated_tokenizers/_bbpe.pyx":159 + * return dict(self._piece_to_id) + * + * def _pieces_to_ids(self, pieces): # <<<<<<<<<<<<<< + * piece_ids = [] + * for piece in pieces: + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_AddTraceback("curated_tokenizers._bbpe.ByteBPEProcessor._pieces_to_ids", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_piece_ids); + __Pyx_XDECREF(__pyx_v_piece); + __Pyx_XDECREF(__pyx_v_piece_id); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_bbpe.pyx":169 + * return piece_ids + * + * def __reduce__(self): # <<<<<<<<<<<<<< + * return (unpickle_byte_bpe_processor, (self.vocab, self.merges,)) + * + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_21__reduce__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_20__reduce__, "ByteBPEProcessor.__reduce__(self)"); +static PyMethodDef __pyx_mdef_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_21__reduce__ = {"__reduce__", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_21__reduce__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_20__reduce__}; +static PyObject *__pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_21__reduce__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__reduce__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_MACROS + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { + __Pyx_RaiseArgtupleInvalid("__reduce__", 1, 0, 0, __pyx_nargs); return NULL;} + if (unlikely(__pyx_kwds) && __Pyx_NumKwargs_FASTCALL(__pyx_kwds) && unlikely(!__Pyx_CheckKeywordStrings(__pyx_kwds, "__reduce__", 0))) return NULL; + __pyx_r = __pyx_pf_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_20__reduce__(((struct __pyx_obj_18curated_tokenizers_5_bbpe_ByteBPEProcessor *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_20__reduce__(struct __pyx_obj_18curated_tokenizers_5_bbpe_ByteBPEProcessor *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__reduce__", 1); + + /* "curated_tokenizers/_bbpe.pyx":170 + * + * def __reduce__(self): + * return (unpickle_byte_bpe_processor, (self.vocab, self.merges,)) # <<<<<<<<<<<<<< + * + * def unpickle_byte_bpe_processor(vocab: Dict[str, int], + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_unpickle_byte_bpe_processor); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 170, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_vocab); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 170, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_merges); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 170, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 170, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_GIVEREF(__pyx_t_2); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_2)) __PYX_ERR(0, 170, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_3); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_3)) __PYX_ERR(0, 170, __pyx_L1_error); + __pyx_t_2 = 0; + __pyx_t_3 = 0; + __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 170, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_GIVEREF(__pyx_t_1); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1)) __PYX_ERR(0, 170, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_4); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_4)) __PYX_ERR(0, 170, __pyx_L1_error); + __pyx_t_1 = 0; + __pyx_t_4 = 0; + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; + + /* "curated_tokenizers/_bbpe.pyx":169 + * return piece_ids + * + * def __reduce__(self): # <<<<<<<<<<<<<< + * return (unpickle_byte_bpe_processor, (self.vocab, self.merges,)) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("curated_tokenizers._bbpe.ByteBPEProcessor.__reduce__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_bbpe.pyx":172 + * return (unpickle_byte_bpe_processor, (self.vocab, self.merges,)) + * + * def unpickle_byte_bpe_processor(vocab: Dict[str, int], # <<<<<<<<<<<<<< + * merges: List[Tuple[str, str]]) -> ByteBPEProcessor: + * return ByteBPEProcessor(vocab, merges) + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_18curated_tokenizers_5_bbpe_3unpickle_byte_bpe_processor(PyObject *__pyx_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_18curated_tokenizers_5_bbpe_2unpickle_byte_bpe_processor, "unpickle_byte_bpe_processor(vocab: Dict[str, int], merges: List[Tuple[str, str]]) -> ByteBPEProcessor"); +static PyMethodDef __pyx_mdef_18curated_tokenizers_5_bbpe_3unpickle_byte_bpe_processor = {"unpickle_byte_bpe_processor", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_5_bbpe_3unpickle_byte_bpe_processor, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_5_bbpe_2unpickle_byte_bpe_processor}; +static PyObject *__pyx_pw_18curated_tokenizers_5_bbpe_3unpickle_byte_bpe_processor(PyObject *__pyx_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_vocab = 0; + PyObject *__pyx_v_merges = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[2] = {0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("unpickle_byte_bpe_processor (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_MACROS + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject **__pyx_pyargnames[] = {&__pyx_n_s_vocab,&__pyx_n_s_merges,0}; + if (__pyx_kwds) { + Py_ssize_t kw_args; + switch (__pyx_nargs) { + case 2: values[1] = __Pyx_Arg_FASTCALL(__pyx_args, 1); + CYTHON_FALLTHROUGH; + case 1: values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = __Pyx_NumKwargs_FASTCALL(__pyx_kwds); + switch (__pyx_nargs) { + case 0: + if (likely((values[0] = __Pyx_GetKwValue_FASTCALL(__pyx_kwds, __pyx_kwvalues, __pyx_n_s_vocab)) != 0)) { + (void)__Pyx_Arg_NewRef_FASTCALL(values[0]); + kw_args--; + } + else if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 172, __pyx_L3_error) + else goto __pyx_L5_argtuple_error; + CYTHON_FALLTHROUGH; + case 1: + if (likely((values[1] = __Pyx_GetKwValue_FASTCALL(__pyx_kwds, __pyx_kwvalues, __pyx_n_s_merges)) != 0)) { + (void)__Pyx_Arg_NewRef_FASTCALL(values[1]); + kw_args--; + } + else if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 172, __pyx_L3_error) + else { + __Pyx_RaiseArgtupleInvalid("unpickle_byte_bpe_processor", 1, 2, 2, 1); __PYX_ERR(0, 172, __pyx_L3_error) + } + } + if (unlikely(kw_args > 0)) { + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values + 0, kwd_pos_args, "unpickle_byte_bpe_processor") < 0)) __PYX_ERR(0, 172, __pyx_L3_error) + } + } else if (unlikely(__pyx_nargs != 2)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + values[1] = __Pyx_Arg_FASTCALL(__pyx_args, 1); + } + __pyx_v_vocab = values[0]; + __pyx_v_merges = values[1]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("unpickle_byte_bpe_processor", 1, 2, 2, __pyx_nargs); __PYX_ERR(0, 172, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_AddTraceback("curated_tokenizers._bbpe.unpickle_byte_bpe_processor", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_18curated_tokenizers_5_bbpe_2unpickle_byte_bpe_processor(__pyx_self, __pyx_v_vocab, __pyx_v_merges); + + /* function exit code */ + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_18curated_tokenizers_5_bbpe_2unpickle_byte_bpe_processor(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_vocab, PyObject *__pyx_v_merges) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("unpickle_byte_bpe_processor", 1); + + /* "curated_tokenizers/_bbpe.pyx":174 + * def unpickle_byte_bpe_processor(vocab: Dict[str, int], + * merges: List[Tuple[str, str]]) -> ByteBPEProcessor: + * return ByteBPEProcessor(vocab, merges) # <<<<<<<<<<<<<< + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 174, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_vocab); + __Pyx_GIVEREF(__pyx_v_vocab); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_vocab)) __PYX_ERR(0, 174, __pyx_L1_error); + __Pyx_INCREF(__pyx_v_merges); + __Pyx_GIVEREF(__pyx_v_merges); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_merges)) __PYX_ERR(0, 174, __pyx_L1_error); + __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)__pyx_ptype_18curated_tokenizers_5_bbpe_ByteBPEProcessor), __pyx_t_1, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 174, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "curated_tokenizers/_bbpe.pyx":172 + * return (unpickle_byte_bpe_processor, (self.vocab, self.merges,)) + * + * def unpickle_byte_bpe_processor(vocab: Dict[str, int], # <<<<<<<<<<<<<< + * merges: List[Tuple[str, str]]) -> ByteBPEProcessor: + * return ByteBPEProcessor(vocab, merges) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("curated_tokenizers._bbpe.unpickle_byte_bpe_processor", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_tp_new_18curated_tokenizers_5_bbpe_ByteBPEProcessor(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { + struct __pyx_obj_18curated_tokenizers_5_bbpe_ByteBPEProcessor *p; + PyObject *o; + #if CYTHON_COMPILING_IN_LIMITED_API + allocfunc alloc_func = (allocfunc)PyType_GetSlot(t, Py_tp_alloc); + o = alloc_func(t, 0); + #else + if (likely(!__Pyx_PyType_HasFeature(t, Py_TPFLAGS_IS_ABSTRACT))) { + o = (*t->tp_alloc)(t, 0); + } else { + o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); + } + if (unlikely(!o)) return 0; + #endif + p = ((struct __pyx_obj_18curated_tokenizers_5_bbpe_ByteBPEProcessor *)o); + new((void*)&(p->_merges)) std::shared_ptr (); + p->_byte_decoder = ((PyObject*)Py_None); Py_INCREF(Py_None); + p->_byte_encoder = ((PyObject*)Py_None); Py_INCREF(Py_None); + p->_split_pattern = Py_None; Py_INCREF(Py_None); + p->_piece_to_id = ((PyObject*)Py_None); Py_INCREF(Py_None); + p->_id_to_piece = ((PyObject*)Py_None); Py_INCREF(Py_None); + return o; +} + +static void __pyx_tp_dealloc_18curated_tokenizers_5_bbpe_ByteBPEProcessor(PyObject *o) { + struct __pyx_obj_18curated_tokenizers_5_bbpe_ByteBPEProcessor *p = (struct __pyx_obj_18curated_tokenizers_5_bbpe_ByteBPEProcessor *)o; + #if CYTHON_USE_TP_FINALIZE + if (unlikely((PY_VERSION_HEX >= 0x03080000 || __Pyx_PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE)) && __Pyx_PyObject_GetSlot(o, tp_finalize, destructor)) && !__Pyx_PyObject_GC_IsFinalized(o)) { + if (__Pyx_PyObject_GetSlot(o, tp_dealloc, destructor) == __pyx_tp_dealloc_18curated_tokenizers_5_bbpe_ByteBPEProcessor) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + } + #endif + PyObject_GC_UnTrack(o); + __Pyx_call_destructor(p->_merges); + Py_CLEAR(p->_byte_decoder); + Py_CLEAR(p->_byte_encoder); + Py_CLEAR(p->_split_pattern); + Py_CLEAR(p->_piece_to_id); + Py_CLEAR(p->_id_to_piece); + #if CYTHON_USE_TYPE_SLOTS || CYTHON_COMPILING_IN_PYPY + (*Py_TYPE(o)->tp_free)(o); + #else + { + freefunc tp_free = (freefunc)PyType_GetSlot(Py_TYPE(o), Py_tp_free); + if (tp_free) tp_free(o); + } + #endif +} + +static int __pyx_tp_traverse_18curated_tokenizers_5_bbpe_ByteBPEProcessor(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_obj_18curated_tokenizers_5_bbpe_ByteBPEProcessor *p = (struct __pyx_obj_18curated_tokenizers_5_bbpe_ByteBPEProcessor *)o; + if (p->_byte_decoder) { + e = (*v)(p->_byte_decoder, a); if (e) return e; + } + if (p->_byte_encoder) { + e = (*v)(p->_byte_encoder, a); if (e) return e; + } + if (p->_split_pattern) { + e = (*v)(p->_split_pattern, a); if (e) return e; + } + if (p->_piece_to_id) { + e = (*v)(p->_piece_to_id, a); if (e) return e; + } + if (p->_id_to_piece) { + e = (*v)(p->_id_to_piece, a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_18curated_tokenizers_5_bbpe_ByteBPEProcessor(PyObject *o) { + PyObject* tmp; + struct __pyx_obj_18curated_tokenizers_5_bbpe_ByteBPEProcessor *p = (struct __pyx_obj_18curated_tokenizers_5_bbpe_ByteBPEProcessor *)o; + tmp = ((PyObject*)p->_byte_decoder); + p->_byte_decoder = ((PyObject*)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->_byte_encoder); + p->_byte_encoder = ((PyObject*)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->_split_pattern); + p->_split_pattern = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->_piece_to_id); + p->_piece_to_id = ((PyObject*)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->_id_to_piece); + p->_id_to_piece = ((PyObject*)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + return 0; +} + +static PyObject *__pyx_getprop_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_merges(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_6merges_1__get__(o); +} + +static PyObject *__pyx_getprop_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_vocab(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_5vocab_1__get__(o); +} + +static PyMethodDef __pyx_methods_18curated_tokenizers_5_bbpe_ByteBPEProcessor[] = { + {"__copy__", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_3__copy__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_2__copy__}, + {"__deepcopy__", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_5__deepcopy__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_4__deepcopy__}, + {"load_from_files", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_7load_from_files, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_6load_from_files}, + {"decode_from_ids", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_9decode_from_ids, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_8decode_from_ids}, + {"encode", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_11encode, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_10encode}, + {"encode_as_ids", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_13encode_as_ids, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_12encode_as_ids}, + {"encode_as_pieces", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_15encode_as_pieces, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_14encode_as_pieces}, + {"piece_id", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_17piece_id, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_16piece_id}, + {"_pieces_to_ids", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_19_pieces_to_ids, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_18_pieces_to_ids}, + {"__reduce__", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_21__reduce__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_20__reduce__}, + {0, 0, 0, 0} +}; + +static struct PyGetSetDef __pyx_getsets_18curated_tokenizers_5_bbpe_ByteBPEProcessor[] = { + {(char *)"merges", __pyx_getprop_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_merges, 0, (char *)PyDoc_STR("ByteBPEProcessor.merges: List[Tuple[str, str]]\nGet all merges."), 0}, + {(char *)"vocab", __pyx_getprop_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_vocab, 0, (char *)PyDoc_STR("ByteBPEProcessor.vocab: Dict[str, int]\nGet a copy of the vocabulary."), 0}, + {0, 0, 0, 0, 0} +}; +#if CYTHON_USE_TYPE_SPECS +static PyType_Slot __pyx_type_18curated_tokenizers_5_bbpe_ByteBPEProcessor_slots[] = { + {Py_tp_dealloc, (void *)__pyx_tp_dealloc_18curated_tokenizers_5_bbpe_ByteBPEProcessor}, + {Py_tp_doc, (void *)PyDoc_STR("ByteBPEProcessor(vocab: Dict[str, int], merges: List[Tuple[str, str]])")}, + {Py_tp_traverse, (void *)__pyx_tp_traverse_18curated_tokenizers_5_bbpe_ByteBPEProcessor}, + {Py_tp_clear, (void *)__pyx_tp_clear_18curated_tokenizers_5_bbpe_ByteBPEProcessor}, + {Py_tp_methods, (void *)__pyx_methods_18curated_tokenizers_5_bbpe_ByteBPEProcessor}, + {Py_tp_getset, (void *)__pyx_getsets_18curated_tokenizers_5_bbpe_ByteBPEProcessor}, + {Py_tp_init, (void *)__pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_1__init__}, + {Py_tp_new, (void *)__pyx_tp_new_18curated_tokenizers_5_bbpe_ByteBPEProcessor}, + {0, 0}, +}; +static PyType_Spec __pyx_type_18curated_tokenizers_5_bbpe_ByteBPEProcessor_spec = { + "curated_tokenizers._bbpe.ByteBPEProcessor", + sizeof(struct __pyx_obj_18curated_tokenizers_5_bbpe_ByteBPEProcessor), + 0, + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, + __pyx_type_18curated_tokenizers_5_bbpe_ByteBPEProcessor_slots, +}; +#else + +static PyTypeObject __pyx_type_18curated_tokenizers_5_bbpe_ByteBPEProcessor = { + PyVarObject_HEAD_INIT(0, 0) + "curated_tokenizers._bbpe.""ByteBPEProcessor", /*tp_name*/ + sizeof(struct __pyx_obj_18curated_tokenizers_5_bbpe_ByteBPEProcessor), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_18curated_tokenizers_5_bbpe_ByteBPEProcessor, /*tp_dealloc*/ + #if PY_VERSION_HEX < 0x030800b4 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030800b4 + 0, /*tp_vectorcall_offset*/ + #endif + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #endif + #if PY_MAJOR_VERSION >= 3 + 0, /*tp_as_async*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + PyDoc_STR("ByteBPEProcessor(vocab: Dict[str, int], merges: List[Tuple[str, str]])"), /*tp_doc*/ + __pyx_tp_traverse_18curated_tokenizers_5_bbpe_ByteBPEProcessor, /*tp_traverse*/ + __pyx_tp_clear_18curated_tokenizers_5_bbpe_ByteBPEProcessor, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_18curated_tokenizers_5_bbpe_ByteBPEProcessor, /*tp_methods*/ + 0, /*tp_members*/ + __pyx_getsets_18curated_tokenizers_5_bbpe_ByteBPEProcessor, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + #if !CYTHON_USE_TYPE_SPECS + 0, /*tp_dictoffset*/ + #endif + __pyx_pw_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_1__init__, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_18curated_tokenizers_5_bbpe_ByteBPEProcessor, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if PY_VERSION_HEX >= 0x030400a1 + #if CYTHON_USE_TP_FINALIZE + 0, /*tp_finalize*/ + #else + NULL, /*tp_finalize*/ + #endif + #endif + #if PY_VERSION_HEX >= 0x030800b1 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) + 0, /*tp_vectorcall*/ + #endif + #if __PYX_NEED_TP_PRINT_SLOT == 1 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030C0000 + 0, /*tp_watched*/ + #endif + #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 + 0, /*tp_pypy_flags*/ + #endif +}; +#endif + +static struct __pyx_obj_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr *__pyx_freelist_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr[8]; +static int __pyx_freecount_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr = 0; + +static PyObject *__pyx_tp_new_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { + struct __pyx_obj_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr *p; + PyObject *o; + #if CYTHON_COMPILING_IN_LIMITED_API + allocfunc alloc_func = (allocfunc)PyType_GetSlot(t, Py_tp_alloc); + o = alloc_func(t, 0); + #else + #if CYTHON_COMPILING_IN_CPYTHON + if (likely((int)(__pyx_freecount_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr > 0) & (int)(t->tp_basicsize == sizeof(struct __pyx_obj_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr)))) { + o = (PyObject*)__pyx_freelist_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr[--__pyx_freecount_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr]; + memset(o, 0, sizeof(struct __pyx_obj_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr)); + (void) PyObject_INIT(o, t); + } else + #endif + { + o = (*t->tp_alloc)(t, 0); + if (unlikely(!o)) return 0; + } + #endif + p = ((struct __pyx_obj_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr *)o); + new((void*)&(p->__pyx_genexpr_arg_0)) std::vector (); + new((void*)&(p->__pyx_v_merge)) std::string(); + new((void*)&(p->__pyx_t_0)) std::vector ::iterator(); + return o; +} + +static void __pyx_tp_dealloc_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr(PyObject *o) { + struct __pyx_obj_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr *p = (struct __pyx_obj_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr *)o; + #if CYTHON_USE_TP_FINALIZE + if (unlikely((PY_VERSION_HEX >= 0x03080000 || __Pyx_PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE)) && __Pyx_PyObject_GetSlot(o, tp_finalize, destructor)) && (!PyType_IS_GC(Py_TYPE(o)) || !__Pyx_PyObject_GC_IsFinalized(o))) { + if (__Pyx_PyObject_GetSlot(o, tp_dealloc, destructor) == __pyx_tp_dealloc_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + } + #endif + __Pyx_call_destructor(p->__pyx_genexpr_arg_0); + __Pyx_call_destructor(p->__pyx_v_merge); + __Pyx_call_destructor(p->__pyx_t_0); + #if CYTHON_COMPILING_IN_CPYTHON + if (((int)(__pyx_freecount_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr < 8) & (int)(Py_TYPE(o)->tp_basicsize == sizeof(struct __pyx_obj_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr)))) { + __pyx_freelist_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr[__pyx_freecount_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr++] = ((struct __pyx_obj_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr *)o); + } else + #endif + { + #if CYTHON_USE_TYPE_SLOTS || CYTHON_COMPILING_IN_PYPY + (*Py_TYPE(o)->tp_free)(o); + #else + { + freefunc tp_free = (freefunc)PyType_GetSlot(Py_TYPE(o), Py_tp_free); + if (tp_free) tp_free(o); + } + #endif + } +} +#if CYTHON_USE_TYPE_SPECS +static PyType_Slot __pyx_type_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr_slots[] = { + {Py_tp_dealloc, (void *)__pyx_tp_dealloc_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr}, + {Py_tp_new, (void *)__pyx_tp_new_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr}, + {0, 0}, +}; +static PyType_Spec __pyx_type_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr_spec = { + "curated_tokenizers._bbpe.__pyx_scope_struct__genexpr", + sizeof(struct __pyx_obj_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr), + 0, + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_HAVE_FINALIZE, + __pyx_type_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr_slots, +}; +#else + +static PyTypeObject __pyx_type_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr = { + PyVarObject_HEAD_INIT(0, 0) + "curated_tokenizers._bbpe.""__pyx_scope_struct__genexpr", /*tp_name*/ + sizeof(struct __pyx_obj_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr, /*tp_dealloc*/ + #if PY_VERSION_HEX < 0x030800b4 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030800b4 + 0, /*tp_vectorcall_offset*/ + #endif + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #endif + #if PY_MAJOR_VERSION >= 3 + 0, /*tp_as_async*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_HAVE_FINALIZE, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + 0, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + #if !CYTHON_USE_TYPE_SPECS + 0, /*tp_dictoffset*/ + #endif + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if PY_VERSION_HEX >= 0x030400a1 + #if CYTHON_USE_TP_FINALIZE + 0, /*tp_finalize*/ + #else + NULL, /*tp_finalize*/ + #endif + #endif + #if PY_VERSION_HEX >= 0x030800b1 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) + 0, /*tp_vectorcall*/ + #endif + #if __PYX_NEED_TP_PRINT_SLOT == 1 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030C0000 + 0, /*tp_watched*/ + #endif + #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 + 0, /*tp_pypy_flags*/ + #endif +}; +#endif + +static PyMethodDef __pyx_methods[] = { + {0, 0, 0, 0} +}; +#ifndef CYTHON_SMALL_CODE +#if defined(__clang__) + #define CYTHON_SMALL_CODE +#elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) + #define CYTHON_SMALL_CODE __attribute__((cold)) +#else + #define CYTHON_SMALL_CODE +#endif +#endif +/* #### Code section: pystring_table ### */ + +static int __Pyx_CreateStringTabAndInitStrings(void) { + __Pyx_StringTabEntry __pyx_string_tab[] = { + {&__pyx_n_s_ByteBPEProcessor, __pyx_k_ByteBPEProcessor, sizeof(__pyx_k_ByteBPEProcessor), 0, 0, 1, 1}, + {&__pyx_n_s_ByteBPEProcessor___copy, __pyx_k_ByteBPEProcessor___copy, sizeof(__pyx_k_ByteBPEProcessor___copy), 0, 0, 1, 1}, + {&__pyx_n_s_ByteBPEProcessor___deepcopy, __pyx_k_ByteBPEProcessor___deepcopy, sizeof(__pyx_k_ByteBPEProcessor___deepcopy), 0, 0, 1, 1}, + {&__pyx_n_s_ByteBPEProcessor___reduce, __pyx_k_ByteBPEProcessor___reduce, sizeof(__pyx_k_ByteBPEProcessor___reduce), 0, 0, 1, 1}, + {&__pyx_n_s_ByteBPEProcessor__pieces_to_ids, __pyx_k_ByteBPEProcessor__pieces_to_ids, sizeof(__pyx_k_ByteBPEProcessor__pieces_to_ids), 0, 0, 1, 1}, + {&__pyx_n_s_ByteBPEProcessor_decode_from_ids, __pyx_k_ByteBPEProcessor_decode_from_ids, sizeof(__pyx_k_ByteBPEProcessor_decode_from_ids), 0, 0, 1, 1}, + {&__pyx_n_s_ByteBPEProcessor_encode, __pyx_k_ByteBPEProcessor_encode, sizeof(__pyx_k_ByteBPEProcessor_encode), 0, 0, 1, 1}, + {&__pyx_n_s_ByteBPEProcessor_encode_as_ids, __pyx_k_ByteBPEProcessor_encode_as_ids, sizeof(__pyx_k_ByteBPEProcessor_encode_as_ids), 0, 0, 1, 1}, + {&__pyx_n_s_ByteBPEProcessor_encode_as_piece, __pyx_k_ByteBPEProcessor_encode_as_piece, sizeof(__pyx_k_ByteBPEProcessor_encode_as_piece), 0, 0, 1, 1}, + {&__pyx_n_s_ByteBPEProcessor_load_from_files, __pyx_k_ByteBPEProcessor_load_from_files, sizeof(__pyx_k_ByteBPEProcessor_load_from_files), 0, 0, 1, 1}, + {&__pyx_n_s_ByteBPEProcessor_piece_id, __pyx_k_ByteBPEProcessor_piece_id, sizeof(__pyx_k_ByteBPEProcessor_piece_id), 0, 0, 1, 1}, + {&__pyx_n_s_BytesIO, __pyx_k_BytesIO, sizeof(__pyx_k_BytesIO), 0, 0, 1, 1}, + {&__pyx_n_s_Dict, __pyx_k_Dict, sizeof(__pyx_k_Dict), 0, 0, 1, 1}, + {&__pyx_kp_s_Dict_int_bytes, __pyx_k_Dict_int_bytes, sizeof(__pyx_k_Dict_int_bytes), 0, 0, 1, 0}, + {&__pyx_kp_s_Dict_str_int, __pyx_k_Dict_str_int, sizeof(__pyx_k_Dict_str_int), 0, 0, 1, 0}, + {&__pyx_n_s_Iterable, __pyx_k_Iterable, sizeof(__pyx_k_Iterable), 0, 0, 1, 1}, + {&__pyx_kp_s_Iterable_int, __pyx_k_Iterable_int, sizeof(__pyx_k_Iterable_int), 0, 0, 1, 0}, + {&__pyx_n_s_List, __pyx_k_List, sizeof(__pyx_k_List), 0, 0, 1, 1}, + {&__pyx_kp_s_List_Tuple_str_str, __pyx_k_List_Tuple_str_str, sizeof(__pyx_k_List_Tuple_str_str), 0, 0, 1, 0}, + {&__pyx_kp_s_List_int, __pyx_k_List_int, sizeof(__pyx_k_List_int), 0, 0, 1, 0}, + {&__pyx_kp_s_List_str, __pyx_k_List_str, sizeof(__pyx_k_List_str), 0, 0, 1, 0}, + {&__pyx_kp_u_Merge_must_consist_of_2_items_wa, __pyx_k_Merge_must_consist_of_2_items_wa, sizeof(__pyx_k_Merge_must_consist_of_2_items_wa), 0, 1, 0, 0}, + {&__pyx_kp_u_Only_version_0_2_of_the_merges_f, __pyx_k_Only_version_0_2_of_the_merges_f, sizeof(__pyx_k_Only_version_0_2_of_the_merges_f), 0, 1, 0, 0}, + {&__pyx_n_s_Optional, __pyx_k_Optional, sizeof(__pyx_k_Optional), 0, 0, 1, 1}, + {&__pyx_kp_s_Optional_int, __pyx_k_Optional_int, sizeof(__pyx_k_Optional_int), 0, 0, 1, 0}, + {&__pyx_n_s_Path, __pyx_k_Path, sizeof(__pyx_k_Path), 0, 0, 1, 1}, + {&__pyx_kp_u_Piece_is_not_in_vocabulary, __pyx_k_Piece_is_not_in_vocabulary, sizeof(__pyx_k_Piece_is_not_in_vocabulary), 0, 1, 0, 0}, + {&__pyx_n_s_SPLIT_PATTERN, __pyx_k_SPLIT_PATTERN, sizeof(__pyx_k_SPLIT_PATTERN), 0, 0, 1, 1}, + {&__pyx_n_s_Tuple, __pyx_k_Tuple, sizeof(__pyx_k_Tuple), 0, 0, 1, 1}, + {&__pyx_kp_s_Tuple_List_int_List_str, __pyx_k_Tuple_List_int_List_str, sizeof(__pyx_k_Tuple_List_int_List_str), 0, 0, 1, 0}, + {&__pyx_kp_u_Unknown_piece_identifier, __pyx_k_Unknown_piece_identifier, sizeof(__pyx_k_Unknown_piece_identifier), 0, 1, 0, 0}, + {&__pyx_n_s_ValueError, __pyx_k_ValueError, sizeof(__pyx_k_ValueError), 0, 0, 1, 1}, + {&__pyx_kp_s__2, __pyx_k__2, sizeof(__pyx_k__2), 0, 0, 1, 0}, + {&__pyx_n_s__28, __pyx_k__28, sizeof(__pyx_k__28), 0, 0, 1, 1}, + {&__pyx_kp_u__3, __pyx_k__3, sizeof(__pyx_k__3), 0, 1, 0, 0}, + {&__pyx_kp_u__4, __pyx_k__4, sizeof(__pyx_k__4), 0, 1, 0, 0}, + {&__pyx_n_s__5, __pyx_k__5, sizeof(__pyx_k__5), 0, 0, 1, 1}, + {&__pyx_n_s_append, __pyx_k_append, sizeof(__pyx_k_append), 0, 0, 1, 1}, + {&__pyx_n_s_args, __pyx_k_args, sizeof(__pyx_k_args), 0, 0, 1, 1}, + {&__pyx_n_s_asyncio_coroutines, __pyx_k_asyncio_coroutines, sizeof(__pyx_k_asyncio_coroutines), 0, 0, 1, 1}, + {&__pyx_n_s_b, __pyx_k_b, sizeof(__pyx_k_b), 0, 0, 1, 1}, + {&__pyx_n_s_bs, __pyx_k_bs, sizeof(__pyx_k_bs), 0, 0, 1, 1}, + {&__pyx_n_s_bytes_to_unicode, __pyx_k_bytes_to_unicode, sizeof(__pyx_k_bytes_to_unicode), 0, 0, 1, 1}, + {&__pyx_n_s_chr, __pyx_k_chr, sizeof(__pyx_k_chr), 0, 0, 1, 1}, + {&__pyx_n_s_cline_in_traceback, __pyx_k_cline_in_traceback, sizeof(__pyx_k_cline_in_traceback), 0, 0, 1, 1}, + {&__pyx_n_s_close, __pyx_k_close, sizeof(__pyx_k_close), 0, 0, 1, 1}, + {&__pyx_n_s_compile, __pyx_k_compile, sizeof(__pyx_k_compile), 0, 0, 1, 1}, + {&__pyx_n_s_copy, __pyx_k_copy, sizeof(__pyx_k_copy), 0, 0, 1, 1}, + {&__pyx_n_s_cp, __pyx_k_cp, sizeof(__pyx_k_cp), 0, 0, 1, 1}, + {&__pyx_n_s_cs, __pyx_k_cs, sizeof(__pyx_k_cs), 0, 0, 1, 1}, + {&__pyx_n_s_curated_tokenizers__bbpe, __pyx_k_curated_tokenizers__bbpe, sizeof(__pyx_k_curated_tokenizers__bbpe), 0, 0, 1, 1}, + {&__pyx_kp_s_curated_tokenizers__bbpe_pyx, __pyx_k_curated_tokenizers__bbpe_pyx, sizeof(__pyx_k_curated_tokenizers__bbpe_pyx), 0, 0, 1, 0}, + {&__pyx_n_s_decode, __pyx_k_decode, sizeof(__pyx_k_decode), 0, 0, 1, 1}, + {&__pyx_n_s_decode_from_ids, __pyx_k_decode_from_ids, sizeof(__pyx_k_decode_from_ids), 0, 0, 1, 1}, + {&__pyx_n_s_decoded, __pyx_k_decoded, sizeof(__pyx_k_decoded), 0, 0, 1, 1}, + {&__pyx_n_s_deepcopy, __pyx_k_deepcopy, sizeof(__pyx_k_deepcopy), 0, 0, 1, 1}, + {&__pyx_n_s_dict, __pyx_k_dict, sizeof(__pyx_k_dict), 0, 0, 1, 1}, + {&__pyx_kp_u_disable, __pyx_k_disable, sizeof(__pyx_k_disable), 0, 1, 0, 0}, + {&__pyx_kp_u_enable, __pyx_k_enable, sizeof(__pyx_k_enable), 0, 1, 0, 0}, + {&__pyx_n_s_encode, __pyx_k_encode, sizeof(__pyx_k_encode), 0, 0, 1, 1}, + {&__pyx_n_s_encode_as_ids, __pyx_k_encode_as_ids, sizeof(__pyx_k_encode_as_ids), 0, 0, 1, 1}, + {&__pyx_n_s_encode_as_pieces, __pyx_k_encode_as_pieces, sizeof(__pyx_k_encode_as_pieces), 0, 0, 1, 1}, + {&__pyx_n_s_encode_as_pieces_locals_genexpr, __pyx_k_encode_as_pieces_locals_genexpr, sizeof(__pyx_k_encode_as_pieces_locals_genexpr), 0, 0, 1, 1}, + {&__pyx_n_s_encoding, __pyx_k_encoding, sizeof(__pyx_k_encoding), 0, 0, 1, 1}, + {&__pyx_n_s_enter, __pyx_k_enter, sizeof(__pyx_k_enter), 0, 0, 1, 1}, + {&__pyx_n_s_exit, __pyx_k_exit, sizeof(__pyx_k_exit), 0, 0, 1, 1}, + {&__pyx_n_s_f, __pyx_k_f, sizeof(__pyx_k_f), 0, 0, 1, 1}, + {&__pyx_n_s_findall, __pyx_k_findall, sizeof(__pyx_k_findall), 0, 0, 1, 1}, + {&__pyx_n_s_functools, __pyx_k_functools, sizeof(__pyx_k_functools), 0, 0, 1, 1}, + {&__pyx_kp_u_gc, __pyx_k_gc, sizeof(__pyx_k_gc), 0, 1, 0, 0}, + {&__pyx_n_s_genexpr, __pyx_k_genexpr, sizeof(__pyx_k_genexpr), 0, 0, 1, 1}, + {&__pyx_n_s_get, __pyx_k_get, sizeof(__pyx_k_get), 0, 0, 1, 1}, + {&__pyx_n_s_getvalue, __pyx_k_getvalue, sizeof(__pyx_k_getvalue), 0, 0, 1, 1}, + {&__pyx_n_s_ids, __pyx_k_ids, sizeof(__pyx_k_ids), 0, 0, 1, 1}, + {&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1}, + {&__pyx_n_s_initializing, __pyx_k_initializing, sizeof(__pyx_k_initializing), 0, 0, 1, 1}, + {&__pyx_n_s_io, __pyx_k_io, sizeof(__pyx_k_io), 0, 0, 1, 1}, + {&__pyx_n_s_is_coroutine, __pyx_k_is_coroutine, sizeof(__pyx_k_is_coroutine), 0, 0, 1, 1}, + {&__pyx_kp_u_isenabled, __pyx_k_isenabled, sizeof(__pyx_k_isenabled), 0, 1, 0, 0}, + {&__pyx_n_s_items, __pyx_k_items, sizeof(__pyx_k_items), 0, 0, 1, 1}, + {&__pyx_n_s_json, __pyx_k_json, sizeof(__pyx_k_json), 0, 0, 1, 1}, + {&__pyx_n_s_line, __pyx_k_line, sizeof(__pyx_k_line), 0, 0, 1, 1}, + {&__pyx_n_s_load, __pyx_k_load, sizeof(__pyx_k_load), 0, 0, 1, 1}, + {&__pyx_n_s_load_from_files, __pyx_k_load_from_files, sizeof(__pyx_k_load_from_files), 0, 0, 1, 1}, + {&__pyx_n_s_lru_cache, __pyx_k_lru_cache, sizeof(__pyx_k_lru_cache), 0, 0, 1, 1}, + {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, + {&__pyx_n_s_memo, __pyx_k_memo, sizeof(__pyx_k_memo), 0, 0, 1, 1}, + {&__pyx_n_s_merge, __pyx_k_merge, sizeof(__pyx_k_merge), 0, 0, 1, 1}, + {&__pyx_n_s_merged, __pyx_k_merged, sizeof(__pyx_k_merged), 0, 0, 1, 1}, + {&__pyx_n_s_merges, __pyx_k_merges, sizeof(__pyx_k_merges), 0, 0, 1, 1}, + {&__pyx_n_s_n, __pyx_k_n, sizeof(__pyx_k_n), 0, 0, 1, 1}, + {&__pyx_n_s_name, __pyx_k_name, sizeof(__pyx_k_name), 0, 0, 1, 1}, + {&__pyx_n_s_open, __pyx_k_open, sizeof(__pyx_k_open), 0, 0, 1, 1}, + {&__pyx_n_s_pathlib, __pyx_k_pathlib, sizeof(__pyx_k_pathlib), 0, 0, 1, 1}, + {&__pyx_n_s_piece, __pyx_k_piece, sizeof(__pyx_k_piece), 0, 0, 1, 1}, + {&__pyx_n_s_piece_id, __pyx_k_piece_id, sizeof(__pyx_k_piece_id), 0, 0, 1, 1}, + {&__pyx_n_s_piece_ids, __pyx_k_piece_ids, sizeof(__pyx_k_piece_ids), 0, 0, 1, 1}, + {&__pyx_n_s_pieces, __pyx_k_pieces, sizeof(__pyx_k_pieces), 0, 0, 1, 1}, + {&__pyx_n_s_pieces_to_ids, __pyx_k_pieces_to_ids, sizeof(__pyx_k_pieces_to_ids), 0, 0, 1, 1}, + {&__pyx_n_s_range, __pyx_k_range, sizeof(__pyx_k_range), 0, 0, 1, 1}, + {&__pyx_n_s_readline, __pyx_k_readline, sizeof(__pyx_k_readline), 0, 0, 1, 1}, + {&__pyx_n_s_reduce, __pyx_k_reduce, sizeof(__pyx_k_reduce), 0, 0, 1, 1}, + {&__pyx_n_s_regex, __pyx_k_regex, sizeof(__pyx_k_regex), 0, 0, 1, 1}, + {&__pyx_n_s_return, __pyx_k_return, sizeof(__pyx_k_return), 0, 0, 1, 1}, + {&__pyx_kp_s_s_t_re_ve_m_ll_d_p_L_p_N_s_p_L, __pyx_k_s_t_re_ve_m_ll_d_p_L_p_N_s_p_L, sizeof(__pyx_k_s_t_re_ve_m_ll_d_p_L_p_N_s_p_L), 0, 0, 1, 0}, + {&__pyx_n_s_self, __pyx_k_self, sizeof(__pyx_k_self), 0, 0, 1, 1}, + {&__pyx_n_s_send, __pyx_k_send, sizeof(__pyx_k_send), 0, 0, 1, 1}, + {&__pyx_n_s_spec, __pyx_k_spec, sizeof(__pyx_k_spec), 0, 0, 1, 1}, + {&__pyx_n_s_split, __pyx_k_split, sizeof(__pyx_k_split), 0, 0, 1, 1}, + {&__pyx_n_s_startswith, __pyx_k_startswith, sizeof(__pyx_k_startswith), 0, 0, 1, 1}, + {&__pyx_n_s_staticmethod, __pyx_k_staticmethod, sizeof(__pyx_k_staticmethod), 0, 0, 1, 1}, + {&__pyx_n_s_str, __pyx_k_str, sizeof(__pyx_k_str), 0, 0, 1, 1}, + {&__pyx_n_s_strip, __pyx_k_strip, sizeof(__pyx_k_strip), 0, 0, 1, 1}, + {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, + {&__pyx_n_s_text, __pyx_k_text, sizeof(__pyx_k_text), 0, 0, 1, 1}, + {&__pyx_n_s_throw, __pyx_k_throw, sizeof(__pyx_k_throw), 0, 0, 1, 1}, + {&__pyx_n_s_token, __pyx_k_token, sizeof(__pyx_k_token), 0, 0, 1, 1}, + {&__pyx_n_s_token_bytes, __pyx_k_token_bytes, sizeof(__pyx_k_token_bytes), 0, 0, 1, 1}, + {&__pyx_n_s_typing, __pyx_k_typing, sizeof(__pyx_k_typing), 0, 0, 1, 1}, + {&__pyx_n_s_unpickle_byte_bpe_processor, __pyx_k_unpickle_byte_bpe_processor, sizeof(__pyx_k_unpickle_byte_bpe_processor), 0, 0, 1, 1}, + {&__pyx_kp_s_utf_8, __pyx_k_utf_8, sizeof(__pyx_k_utf_8), 0, 0, 1, 0}, + {&__pyx_n_s_version, __pyx_k_version, sizeof(__pyx_k_version), 0, 0, 1, 1}, + {&__pyx_kp_s_version_0_2, __pyx_k_version_0_2, sizeof(__pyx_k_version_0_2), 0, 0, 1, 0}, + {&__pyx_n_s_vocab, __pyx_k_vocab, sizeof(__pyx_k_vocab), 0, 0, 1, 1}, + {&__pyx_n_s_write, __pyx_k_write, sizeof(__pyx_k_write), 0, 0, 1, 1}, + {&__pyx_n_s_zip, __pyx_k_zip, sizeof(__pyx_k_zip), 0, 0, 1, 1}, + {0, 0, 0, 0, 0, 0, 0} + }; + return __Pyx_InitStrings(__pyx_string_tab); +} +/* #### Code section: cached_builtins ### */ +static CYTHON_SMALL_CODE int __Pyx_InitCachedBuiltins(void) { + __pyx_builtin_staticmethod = __Pyx_GetBuiltinName(__pyx_n_s_staticmethod); if (!__pyx_builtin_staticmethod) __PYX_ERR(0, 77, __pyx_L1_error) + __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) __PYX_ERR(0, 36, __pyx_L1_error) + __pyx_builtin_chr = __Pyx_GetBuiltinName(__pyx_n_s_chr); if (!__pyx_builtin_chr) __PYX_ERR(0, 47, __pyx_L1_error) + __pyx_builtin_zip = __Pyx_GetBuiltinName(__pyx_n_s_zip); if (!__pyx_builtin_zip) __PYX_ERR(0, 48, __pyx_L1_error) + __pyx_builtin_open = __Pyx_GetBuiltinName(__pyx_n_s_open); if (!__pyx_builtin_open) __PYX_ERR(0, 80, __pyx_L1_error) + __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s_ValueError); if (!__pyx_builtin_ValueError) __PYX_ERR(0, 85, __pyx_L1_error) + return 0; + __pyx_L1_error:; + return -1; +} +/* #### Code section: cached_constants ### */ + +static CYTHON_SMALL_CODE int __Pyx_InitCachedConstants(void) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); + + /* "curated_tokenizers/_bbpe.pyx":80 + * def load_from_files(*, vocab: Path, merges: Path) -> ByteBPEProcessor: + * """Construct a processor from the given vocabulary and merges files.""" + * with open(vocab, encoding="utf-8") as f: # <<<<<<<<<<<<<< + * vocab = json.load(f) + * with open(merges, encoding="utf-8") as f: + */ + __pyx_tuple_ = PyTuple_Pack(3, Py_None, Py_None, Py_None); if (unlikely(!__pyx_tuple_)) __PYX_ERR(0, 80, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple_); + __Pyx_GIVEREF(__pyx_tuple_); + + /* "curated_tokenizers/_bbpe.pyx":24 + * + * + * @lru_cache() # <<<<<<<<<<<<<< + * def bytes_to_unicode() -> Dict[int, bytes]: + * """ + */ + __pyx_tuple__6 = PyTuple_Pack(4, __pyx_n_s_bs, __pyx_n_s_cs, __pyx_n_s_n, __pyx_n_s_b); if (unlikely(!__pyx_tuple__6)) __PYX_ERR(0, 24, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__6); + __Pyx_GIVEREF(__pyx_tuple__6); + __pyx_codeobj__7 = (PyObject*)__Pyx_PyCode_New(0, 0, 0, 4, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__6, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_curated_tokenizers__bbpe_pyx, __pyx_n_s_bytes_to_unicode, 24, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__7)) __PYX_ERR(0, 24, __pyx_L1_error) + + /* "curated_tokenizers/_bbpe.pyx":69 + * self._merges = make_shared[Merges](c_merges) + * + * def __copy__(self): # <<<<<<<<<<<<<< + * return ByteBPEProcessor(vocab=self.vocab, merges=self.merges) + * + */ + __pyx_tuple__8 = PyTuple_Pack(1, __pyx_n_s_self); if (unlikely(!__pyx_tuple__8)) __PYX_ERR(0, 69, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__8); + __Pyx_GIVEREF(__pyx_tuple__8); + __pyx_codeobj__9 = (PyObject*)__Pyx_PyCode_New(1, 0, 0, 1, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__8, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_curated_tokenizers__bbpe_pyx, __pyx_n_s_copy, 69, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__9)) __PYX_ERR(0, 69, __pyx_L1_error) + + /* "curated_tokenizers/_bbpe.pyx":72 + * return ByteBPEProcessor(vocab=self.vocab, merges=self.merges) + * + * def __deepcopy__(self, memo): # <<<<<<<<<<<<<< + * # We don't need a deepcopy of the vocab and merges dicts as their + * # contents will be copied into a backing store in the c'tor. + */ + __pyx_tuple__10 = PyTuple_Pack(2, __pyx_n_s_self, __pyx_n_s_memo); if (unlikely(!__pyx_tuple__10)) __PYX_ERR(0, 72, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__10); + __Pyx_GIVEREF(__pyx_tuple__10); + __pyx_codeobj__11 = (PyObject*)__Pyx_PyCode_New(2, 0, 0, 2, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__10, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_curated_tokenizers__bbpe_pyx, __pyx_n_s_deepcopy, 72, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__11)) __PYX_ERR(0, 72, __pyx_L1_error) + + /* "curated_tokenizers/_bbpe.pyx":77 + * return ByteBPEProcessor(vocab=self.vocab, merges=self.merges) + * + * @staticmethod # <<<<<<<<<<<<<< + * def load_from_files(*, vocab: Path, merges: Path) -> ByteBPEProcessor: + * """Construct a processor from the given vocabulary and merges files.""" + */ + __pyx_tuple__12 = PyTuple_Pack(6, __pyx_n_s_vocab, __pyx_n_s_merges, __pyx_n_s_f, __pyx_n_s_version, __pyx_n_s_line, __pyx_n_s_merge); if (unlikely(!__pyx_tuple__12)) __PYX_ERR(0, 77, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__12); + __Pyx_GIVEREF(__pyx_tuple__12); + __pyx_codeobj__13 = (PyObject*)__Pyx_PyCode_New(0, 0, 2, 6, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__12, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_curated_tokenizers__bbpe_pyx, __pyx_n_s_load_from_files, 77, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__13)) __PYX_ERR(0, 77, __pyx_L1_error) + + /* "curated_tokenizers/_bbpe.pyx":94 + * return ByteBPEProcessor(vocab, merges) + * + * def decode_from_ids(self, ids: Iterable[int]) -> str: # <<<<<<<<<<<<<< + * """ + * Decode piece identifiers into string. + */ + __pyx_tuple__14 = PyTuple_Pack(6, __pyx_n_s_self, __pyx_n_s_ids, __pyx_n_s_decoded, __pyx_n_s_piece_id, __pyx_n_s_piece, __pyx_n_s_cp); if (unlikely(!__pyx_tuple__14)) __PYX_ERR(0, 94, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__14); + __Pyx_GIVEREF(__pyx_tuple__14); + __pyx_codeobj__15 = (PyObject*)__Pyx_PyCode_New(2, 0, 0, 6, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__14, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_curated_tokenizers__bbpe_pyx, __pyx_n_s_decode_from_ids, 94, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__15)) __PYX_ERR(0, 94, __pyx_L1_error) + + /* "curated_tokenizers/_bbpe.pyx":110 + * return decoded.getvalue().decode("utf-8") + * + * def encode(self, text: str) -> Tuple[List[int], List[str]]: # <<<<<<<<<<<<<< + * """ + * Split a text into pieces. + */ + __pyx_tuple__16 = PyTuple_Pack(3, __pyx_n_s_self, __pyx_n_s_text, __pyx_n_s_pieces); if (unlikely(!__pyx_tuple__16)) __PYX_ERR(0, 110, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__16); + __Pyx_GIVEREF(__pyx_tuple__16); + __pyx_codeobj__17 = (PyObject*)__Pyx_PyCode_New(2, 0, 0, 3, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__16, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_curated_tokenizers__bbpe_pyx, __pyx_n_s_encode, 110, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__17)) __PYX_ERR(0, 110, __pyx_L1_error) + + /* "curated_tokenizers/_bbpe.pyx":120 + * return self._pieces_to_ids(pieces), pieces + * + * def encode_as_ids(self, text: str) -> List[int]: # <<<<<<<<<<<<<< + * """ + * Split a text into pieces, returning piece identifiers. + */ + __pyx_codeobj__18 = (PyObject*)__Pyx_PyCode_New(2, 0, 0, 3, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__16, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_curated_tokenizers__bbpe_pyx, __pyx_n_s_encode_as_ids, 120, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__18)) __PYX_ERR(0, 120, __pyx_L1_error) + + /* "curated_tokenizers/_bbpe.pyx":130 + * return self._pieces_to_ids(pieces) + * + * def encode_as_pieces(self, text: str) -> List[str]: # <<<<<<<<<<<<<< + * """ + * Split a text into pieces, returning piece pieces. + */ + __pyx_tuple__19 = PyTuple_Pack(9, __pyx_n_s_self, __pyx_n_s_text, __pyx_n_s_pieces, __pyx_n_s_token, __pyx_n_s_token_bytes, __pyx_n_s_merged, __pyx_n_s_b, __pyx_n_s_genexpr, __pyx_n_s_genexpr); if (unlikely(!__pyx_tuple__19)) __PYX_ERR(0, 130, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__19); + __Pyx_GIVEREF(__pyx_tuple__19); + __pyx_codeobj__20 = (PyObject*)__Pyx_PyCode_New(2, 0, 0, 9, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__19, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_curated_tokenizers__bbpe_pyx, __pyx_n_s_encode_as_pieces, 130, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__20)) __PYX_ERR(0, 130, __pyx_L1_error) + + /* "curated_tokenizers/_bbpe.pyx":150 + * return [(m1.decode('utf-8'), m2.decode('utf-8')) for m1, m2 in merges_bytes] + * + * def piece_id(self, piece: str) -> Optional[int]: # <<<<<<<<<<<<<< + * """Get the identifier for a piece.""" + * return self._piece_to_id.get(piece) + */ + __pyx_tuple__21 = PyTuple_Pack(2, __pyx_n_s_self, __pyx_n_s_piece); if (unlikely(!__pyx_tuple__21)) __PYX_ERR(0, 150, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__21); + __Pyx_GIVEREF(__pyx_tuple__21); + __pyx_codeobj__22 = (PyObject*)__Pyx_PyCode_New(2, 0, 0, 2, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__21, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_curated_tokenizers__bbpe_pyx, __pyx_n_s_piece_id, 150, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__22)) __PYX_ERR(0, 150, __pyx_L1_error) + + /* "curated_tokenizers/_bbpe.pyx":159 + * return dict(self._piece_to_id) + * + * def _pieces_to_ids(self, pieces): # <<<<<<<<<<<<<< + * piece_ids = [] + * for piece in pieces: + */ + __pyx_tuple__23 = PyTuple_Pack(5, __pyx_n_s_self, __pyx_n_s_pieces, __pyx_n_s_piece_ids, __pyx_n_s_piece, __pyx_n_s_piece_id); if (unlikely(!__pyx_tuple__23)) __PYX_ERR(0, 159, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__23); + __Pyx_GIVEREF(__pyx_tuple__23); + __pyx_codeobj__24 = (PyObject*)__Pyx_PyCode_New(2, 0, 0, 5, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__23, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_curated_tokenizers__bbpe_pyx, __pyx_n_s_pieces_to_ids, 159, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__24)) __PYX_ERR(0, 159, __pyx_L1_error) + + /* "curated_tokenizers/_bbpe.pyx":169 + * return piece_ids + * + * def __reduce__(self): # <<<<<<<<<<<<<< + * return (unpickle_byte_bpe_processor, (self.vocab, self.merges,)) + * + */ + __pyx_codeobj__25 = (PyObject*)__Pyx_PyCode_New(1, 0, 0, 1, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__8, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_curated_tokenizers__bbpe_pyx, __pyx_n_s_reduce, 169, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__25)) __PYX_ERR(0, 169, __pyx_L1_error) + + /* "curated_tokenizers/_bbpe.pyx":172 + * return (unpickle_byte_bpe_processor, (self.vocab, self.merges,)) + * + * def unpickle_byte_bpe_processor(vocab: Dict[str, int], # <<<<<<<<<<<<<< + * merges: List[Tuple[str, str]]) -> ByteBPEProcessor: + * return ByteBPEProcessor(vocab, merges) + */ + __pyx_tuple__26 = PyTuple_Pack(2, __pyx_n_s_vocab, __pyx_n_s_merges); if (unlikely(!__pyx_tuple__26)) __PYX_ERR(0, 172, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__26); + __Pyx_GIVEREF(__pyx_tuple__26); + __pyx_codeobj__27 = (PyObject*)__Pyx_PyCode_New(2, 0, 0, 2, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__26, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_curated_tokenizers__bbpe_pyx, __pyx_n_s_unpickle_byte_bpe_processor, 172, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__27)) __PYX_ERR(0, 172, __pyx_L1_error) + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_RefNannyFinishContext(); + return -1; +} +/* #### Code section: init_constants ### */ + +static CYTHON_SMALL_CODE int __Pyx_InitConstants(void) { + __pyx_umethod_PyDict_Type_get.type = (PyObject*)&PyDict_Type; + __pyx_umethod_PyDict_Type_get.method_name = &__pyx_n_s_get; + __pyx_umethod_PyDict_Type_items.type = (PyObject*)&PyDict_Type; + __pyx_umethod_PyDict_Type_items.method_name = &__pyx_n_s_items; + if (__Pyx_CreateStringTabAndInitStrings() < 0) __PYX_ERR(0, 1, __pyx_L1_error); + __pyx_int_0 = PyInt_FromLong(0); if (unlikely(!__pyx_int_0)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_int_1 = PyInt_FromLong(1); if (unlikely(!__pyx_int_1)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_int_33 = PyInt_FromLong(33); if (unlikely(!__pyx_int_33)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_int_161 = PyInt_FromLong(161); if (unlikely(!__pyx_int_161)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_int_174 = PyInt_FromLong(174); if (unlikely(!__pyx_int_174)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_int_256 = PyInt_FromLong(256); if (unlikely(!__pyx_int_256)) __PYX_ERR(0, 1, __pyx_L1_error) + return 0; + __pyx_L1_error:; + return -1; +} +/* #### Code section: init_globals ### */ + +static CYTHON_SMALL_CODE int __Pyx_InitGlobals(void) { + return 0; +} +/* #### Code section: init_module ### */ + +static CYTHON_SMALL_CODE int __Pyx_modinit_global_init_code(void); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_variable_export_code(void); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_function_export_code(void); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_type_init_code(void); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_type_import_code(void); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_variable_import_code(void); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_function_import_code(void); /*proto*/ + +static int __Pyx_modinit_global_init_code(void) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__Pyx_modinit_global_init_code", 0); + /*--- Global init code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_variable_export_code(void) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__Pyx_modinit_variable_export_code", 0); + /*--- Variable export code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_function_export_code(void) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__Pyx_modinit_function_export_code", 0); + /*--- Function export code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_type_init_code(void) { + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__Pyx_modinit_type_init_code", 0); + /*--- Type init code ---*/ + #if CYTHON_USE_TYPE_SPECS + __pyx_ptype_18curated_tokenizers_5_bbpe_ByteBPEProcessor = (PyTypeObject *) __Pyx_PyType_FromModuleAndSpec(__pyx_m, &__pyx_type_18curated_tokenizers_5_bbpe_ByteBPEProcessor_spec, NULL); if (unlikely(!__pyx_ptype_18curated_tokenizers_5_bbpe_ByteBPEProcessor)) __PYX_ERR(0, 50, __pyx_L1_error) + if (__Pyx_fix_up_extension_type_from_spec(&__pyx_type_18curated_tokenizers_5_bbpe_ByteBPEProcessor_spec, __pyx_ptype_18curated_tokenizers_5_bbpe_ByteBPEProcessor) < 0) __PYX_ERR(0, 50, __pyx_L1_error) + #else + __pyx_ptype_18curated_tokenizers_5_bbpe_ByteBPEProcessor = &__pyx_type_18curated_tokenizers_5_bbpe_ByteBPEProcessor; + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + #endif + #if !CYTHON_USE_TYPE_SPECS + if (__Pyx_PyType_Ready(__pyx_ptype_18curated_tokenizers_5_bbpe_ByteBPEProcessor) < 0) __PYX_ERR(0, 50, __pyx_L1_error) + #endif + #if PY_MAJOR_VERSION < 3 + __pyx_ptype_18curated_tokenizers_5_bbpe_ByteBPEProcessor->tp_print = 0; + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_ptype_18curated_tokenizers_5_bbpe_ByteBPEProcessor->tp_dictoffset && __pyx_ptype_18curated_tokenizers_5_bbpe_ByteBPEProcessor->tp_getattro == PyObject_GenericGetAttr)) { + __pyx_ptype_18curated_tokenizers_5_bbpe_ByteBPEProcessor->tp_getattro = __Pyx_PyObject_GenericGetAttr; + } + #endif + if (PyObject_SetAttr(__pyx_m, __pyx_n_s_ByteBPEProcessor, (PyObject *) __pyx_ptype_18curated_tokenizers_5_bbpe_ByteBPEProcessor) < 0) __PYX_ERR(0, 50, __pyx_L1_error) + #if CYTHON_USE_TYPE_SPECS + __pyx_ptype_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr = (PyTypeObject *) __Pyx_PyType_FromModuleAndSpec(__pyx_m, &__pyx_type_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr_spec, NULL); if (unlikely(!__pyx_ptype_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr)) __PYX_ERR(0, 141, __pyx_L1_error) + if (__Pyx_fix_up_extension_type_from_spec(&__pyx_type_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr_spec, __pyx_ptype_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr) < 0) __PYX_ERR(0, 141, __pyx_L1_error) + #else + __pyx_ptype_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr = &__pyx_type_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr; + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + #endif + #if !CYTHON_USE_TYPE_SPECS + if (__Pyx_PyType_Ready(__pyx_ptype_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr) < 0) __PYX_ERR(0, 141, __pyx_L1_error) + #endif + #if PY_MAJOR_VERSION < 3 + __pyx_ptype_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr->tp_print = 0; + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_ptype_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr->tp_dictoffset && __pyx_ptype_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr->tp_getattro == PyObject_GenericGetAttr)) { + __pyx_ptype_18curated_tokenizers_5_bbpe___pyx_scope_struct__genexpr->tp_getattro = __Pyx_PyObject_GenericGetAttrNoDict; + } + #endif + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_RefNannyFinishContext(); + return -1; +} + +static int __Pyx_modinit_type_import_code(void) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__Pyx_modinit_type_import_code", 0); + /*--- Type import code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_variable_import_code(void) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__Pyx_modinit_variable_import_code", 0); + /*--- Variable import code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_function_import_code(void) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__Pyx_modinit_function_import_code", 0); + /*--- Function import code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + + +#if PY_MAJOR_VERSION >= 3 +#if CYTHON_PEP489_MULTI_PHASE_INIT +static PyObject* __pyx_pymod_create(PyObject *spec, PyModuleDef *def); /*proto*/ +static int __pyx_pymod_exec__bbpe(PyObject* module); /*proto*/ +static PyModuleDef_Slot __pyx_moduledef_slots[] = { + {Py_mod_create, (void*)__pyx_pymod_create}, + {Py_mod_exec, (void*)__pyx_pymod_exec__bbpe}, + {0, NULL} +}; +#endif + +#ifdef __cplusplus +namespace { + struct PyModuleDef __pyx_moduledef = + #else + static struct PyModuleDef __pyx_moduledef = + #endif + { + PyModuleDef_HEAD_INIT, + "_bbpe", + 0, /* m_doc */ + #if CYTHON_PEP489_MULTI_PHASE_INIT + 0, /* m_size */ + #elif CYTHON_USE_MODULE_STATE + sizeof(__pyx_mstate), /* m_size */ + #else + -1, /* m_size */ + #endif + __pyx_methods /* m_methods */, + #if CYTHON_PEP489_MULTI_PHASE_INIT + __pyx_moduledef_slots, /* m_slots */ + #else + NULL, /* m_reload */ + #endif + #if CYTHON_USE_MODULE_STATE + __pyx_m_traverse, /* m_traverse */ + __pyx_m_clear, /* m_clear */ + NULL /* m_free */ + #else + NULL, /* m_traverse */ + NULL, /* m_clear */ + NULL /* m_free */ + #endif + }; + #ifdef __cplusplus +} /* anonymous namespace */ +#endif +#endif + +#ifndef CYTHON_NO_PYINIT_EXPORT +#define __Pyx_PyMODINIT_FUNC PyMODINIT_FUNC +#elif PY_MAJOR_VERSION < 3 +#ifdef __cplusplus +#define __Pyx_PyMODINIT_FUNC extern "C" void +#else +#define __Pyx_PyMODINIT_FUNC void +#endif +#else +#ifdef __cplusplus +#define __Pyx_PyMODINIT_FUNC extern "C" PyObject * +#else +#define __Pyx_PyMODINIT_FUNC PyObject * +#endif +#endif + + +#if PY_MAJOR_VERSION < 3 +__Pyx_PyMODINIT_FUNC init_bbpe(void) CYTHON_SMALL_CODE; /*proto*/ +__Pyx_PyMODINIT_FUNC init_bbpe(void) +#else +__Pyx_PyMODINIT_FUNC PyInit__bbpe(void) CYTHON_SMALL_CODE; /*proto*/ +__Pyx_PyMODINIT_FUNC PyInit__bbpe(void) +#if CYTHON_PEP489_MULTI_PHASE_INIT +{ + return PyModuleDef_Init(&__pyx_moduledef); +} +static CYTHON_SMALL_CODE int __Pyx_check_single_interpreter(void) { + #if PY_VERSION_HEX >= 0x030700A1 + static PY_INT64_T main_interpreter_id = -1; + PY_INT64_T current_id = PyInterpreterState_GetID(PyThreadState_Get()->interp); + if (main_interpreter_id == -1) { + main_interpreter_id = current_id; + return (unlikely(current_id == -1)) ? -1 : 0; + } else if (unlikely(main_interpreter_id != current_id)) + #else + static PyInterpreterState *main_interpreter = NULL; + PyInterpreterState *current_interpreter = PyThreadState_Get()->interp; + if (!main_interpreter) { + main_interpreter = current_interpreter; + } else if (unlikely(main_interpreter != current_interpreter)) + #endif + { + PyErr_SetString( + PyExc_ImportError, + "Interpreter change detected - this module can only be loaded into one interpreter per process."); + return -1; + } + return 0; +} +#if CYTHON_COMPILING_IN_LIMITED_API +static CYTHON_SMALL_CODE int __Pyx_copy_spec_to_module(PyObject *spec, PyObject *module, const char* from_name, const char* to_name, int allow_none) +#else +static CYTHON_SMALL_CODE int __Pyx_copy_spec_to_module(PyObject *spec, PyObject *moddict, const char* from_name, const char* to_name, int allow_none) +#endif +{ + PyObject *value = PyObject_GetAttrString(spec, from_name); + int result = 0; + if (likely(value)) { + if (allow_none || value != Py_None) { +#if CYTHON_COMPILING_IN_LIMITED_API + result = PyModule_AddObject(module, to_name, value); +#else + result = PyDict_SetItemString(moddict, to_name, value); +#endif + } + Py_DECREF(value); + } else if (PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Clear(); + } else { + result = -1; + } + return result; +} +static CYTHON_SMALL_CODE PyObject* __pyx_pymod_create(PyObject *spec, PyModuleDef *def) { + PyObject *module = NULL, *moddict, *modname; + CYTHON_UNUSED_VAR(def); + if (__Pyx_check_single_interpreter()) + return NULL; + if (__pyx_m) + return __Pyx_NewRef(__pyx_m); + modname = PyObject_GetAttrString(spec, "name"); + if (unlikely(!modname)) goto bad; + module = PyModule_NewObject(modname); + Py_DECREF(modname); + if (unlikely(!module)) goto bad; +#if CYTHON_COMPILING_IN_LIMITED_API + moddict = module; +#else + moddict = PyModule_GetDict(module); + if (unlikely(!moddict)) goto bad; +#endif + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "loader", "__loader__", 1) < 0)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "origin", "__file__", 1) < 0)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "parent", "__package__", 1) < 0)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "submodule_search_locations", "__path__", 0) < 0)) goto bad; + return module; +bad: + Py_XDECREF(module); + return NULL; +} + + +static CYTHON_SMALL_CODE int __pyx_pymod_exec__bbpe(PyObject *__pyx_pyinit_module) +#endif +#endif +{ + int stringtab_initialized = 0; + #if CYTHON_USE_MODULE_STATE + int pystate_addmodule_run = 0; + #endif + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannyDeclarations + #if CYTHON_PEP489_MULTI_PHASE_INIT + if (__pyx_m) { + if (__pyx_m == __pyx_pyinit_module) return 0; + PyErr_SetString(PyExc_RuntimeError, "Module '_bbpe' has already been imported. Re-initialisation is not supported."); + return -1; + } + #elif PY_MAJOR_VERSION >= 3 + if (__pyx_m) return __Pyx_NewRef(__pyx_m); + #endif + /*--- Module creation code ---*/ + #if CYTHON_PEP489_MULTI_PHASE_INIT + __pyx_m = __pyx_pyinit_module; + Py_INCREF(__pyx_m); + #else + #if PY_MAJOR_VERSION < 3 + __pyx_m = Py_InitModule4("_bbpe", __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); + if (unlikely(!__pyx_m)) __PYX_ERR(0, 1, __pyx_L1_error) + #elif CYTHON_USE_MODULE_STATE + __pyx_t_1 = PyModule_Create(&__pyx_moduledef); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1, __pyx_L1_error) + { + int add_module_result = PyState_AddModule(__pyx_t_1, &__pyx_moduledef); + __pyx_t_1 = 0; /* transfer ownership from __pyx_t_1 to "_bbpe" pseudovariable */ + if (unlikely((add_module_result < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + pystate_addmodule_run = 1; + } + #else + __pyx_m = PyModule_Create(&__pyx_moduledef); + if (unlikely(!__pyx_m)) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + #endif + CYTHON_UNUSED_VAR(__pyx_t_1); + __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) __PYX_ERR(0, 1, __pyx_L1_error) + Py_INCREF(__pyx_d); + __pyx_b = __Pyx_PyImport_AddModuleRef(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_b)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_cython_runtime = __Pyx_PyImport_AddModuleRef((const char *) "cython_runtime"); if (unlikely(!__pyx_cython_runtime)) __PYX_ERR(0, 1, __pyx_L1_error) + if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #if CYTHON_REFNANNY +__Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); +if (!__Pyx_RefNanny) { + PyErr_Clear(); + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); + if (!__Pyx_RefNanny) + Py_FatalError("failed to import 'refnanny' module"); +} +#endif + __Pyx_RefNannySetupContext("__Pyx_PyMODINIT_FUNC PyInit__bbpe(void)", 0); + if (__Pyx_check_binary_version(__PYX_LIMITED_VERSION_HEX, __Pyx_get_runtime_version(), CYTHON_COMPILING_IN_LIMITED_API) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #ifdef __Pxy_PyFrame_Initialize_Offsets + __Pxy_PyFrame_Initialize_Offsets(); + #endif + __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_empty_unicode = PyUnicode_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_unicode)) __PYX_ERR(0, 1, __pyx_L1_error) + #ifdef __Pyx_CyFunction_USED + if (__pyx_CyFunction_init(__pyx_m) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + #ifdef __Pyx_FusedFunction_USED + if (__pyx_FusedFunction_init(__pyx_m) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + #ifdef __Pyx_Coroutine_USED + if (__pyx_Coroutine_init(__pyx_m) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + #ifdef __Pyx_Generator_USED + if (__pyx_Generator_init(__pyx_m) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + #ifdef __Pyx_AsyncGen_USED + if (__pyx_AsyncGen_init(__pyx_m) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + #ifdef __Pyx_StopAsyncIteration_USED + if (__pyx_StopAsyncIteration_init(__pyx_m) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + /*--- Library function declarations ---*/ + /*--- Threads initialization code ---*/ + #if defined(WITH_THREAD) && PY_VERSION_HEX < 0x030700F0 && defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS + PyEval_InitThreads(); + #endif + /*--- Initialize various global constants etc. ---*/ + if (__Pyx_InitConstants() < 0) __PYX_ERR(0, 1, __pyx_L1_error) + stringtab_initialized = 1; + if (__Pyx_InitGlobals() < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) + if (__Pyx_init_sys_getdefaultencoding_params() < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + if (__pyx_module_is_main_curated_tokenizers___bbpe) { + if (PyObject_SetAttr(__pyx_m, __pyx_n_s_name, __pyx_n_s_main) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + } + #if PY_MAJOR_VERSION >= 3 + { + PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) __PYX_ERR(0, 1, __pyx_L1_error) + if (!PyDict_GetItemString(modules, "curated_tokenizers._bbpe")) { + if (unlikely((PyDict_SetItemString(modules, "curated_tokenizers._bbpe", __pyx_m) < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + } + } + #endif + /*--- Builtin init code ---*/ + if (__Pyx_InitCachedBuiltins() < 0) __PYX_ERR(0, 1, __pyx_L1_error) + /*--- Constants init code ---*/ + if (__Pyx_InitCachedConstants() < 0) __PYX_ERR(0, 1, __pyx_L1_error) + /*--- Global type/function init code ---*/ + (void)__Pyx_modinit_global_init_code(); + (void)__Pyx_modinit_variable_export_code(); + (void)__Pyx_modinit_function_export_code(); + if (unlikely((__Pyx_modinit_type_init_code() < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + (void)__Pyx_modinit_type_import_code(); + (void)__Pyx_modinit_variable_import_code(); + (void)__Pyx_modinit_function_import_code(); + /*--- Execution code ---*/ + #if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED) + if (__Pyx_patch_abc() < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + + /* "curated_tokenizers/_bbpe.pyx":3 + * # cython: infer_types + * + * from typing import Dict, Iterable, List, Optional, Tuple # <<<<<<<<<<<<<< + * from cython.operator cimport dereference as deref + * from functools import lru_cache + */ + __pyx_t_2 = PyList_New(5); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 3, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_n_s_Dict); + __Pyx_GIVEREF(__pyx_n_s_Dict); + if (__Pyx_PyList_SET_ITEM(__pyx_t_2, 0, __pyx_n_s_Dict)) __PYX_ERR(0, 3, __pyx_L1_error); + __Pyx_INCREF(__pyx_n_s_Iterable); + __Pyx_GIVEREF(__pyx_n_s_Iterable); + if (__Pyx_PyList_SET_ITEM(__pyx_t_2, 1, __pyx_n_s_Iterable)) __PYX_ERR(0, 3, __pyx_L1_error); + __Pyx_INCREF(__pyx_n_s_List); + __Pyx_GIVEREF(__pyx_n_s_List); + if (__Pyx_PyList_SET_ITEM(__pyx_t_2, 2, __pyx_n_s_List)) __PYX_ERR(0, 3, __pyx_L1_error); + __Pyx_INCREF(__pyx_n_s_Optional); + __Pyx_GIVEREF(__pyx_n_s_Optional); + if (__Pyx_PyList_SET_ITEM(__pyx_t_2, 3, __pyx_n_s_Optional)) __PYX_ERR(0, 3, __pyx_L1_error); + __Pyx_INCREF(__pyx_n_s_Tuple); + __Pyx_GIVEREF(__pyx_n_s_Tuple); + if (__Pyx_PyList_SET_ITEM(__pyx_t_2, 4, __pyx_n_s_Tuple)) __PYX_ERR(0, 3, __pyx_L1_error); + __pyx_t_3 = __Pyx_Import(__pyx_n_s_typing, __pyx_t_2, -1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 3, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_3, __pyx_n_s_Dict); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 3, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_Dict, __pyx_t_2) < 0) __PYX_ERR(0, 3, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_3, __pyx_n_s_Iterable); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 3, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_Iterable, __pyx_t_2) < 0) __PYX_ERR(0, 3, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_3, __pyx_n_s_List); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 3, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_List, __pyx_t_2) < 0) __PYX_ERR(0, 3, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_3, __pyx_n_s_Optional); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 3, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_Optional, __pyx_t_2) < 0) __PYX_ERR(0, 3, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_3, __pyx_n_s_Tuple); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 3, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_Tuple, __pyx_t_2) < 0) __PYX_ERR(0, 3, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "curated_tokenizers/_bbpe.pyx":5 + * from typing import Dict, Iterable, List, Optional, Tuple + * from cython.operator cimport dereference as deref + * from functools import lru_cache # <<<<<<<<<<<<<< + * from io import BytesIO + * import json + */ + __pyx_t_3 = PyList_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 5, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_n_s_lru_cache); + __Pyx_GIVEREF(__pyx_n_s_lru_cache); + if (__Pyx_PyList_SET_ITEM(__pyx_t_3, 0, __pyx_n_s_lru_cache)) __PYX_ERR(0, 5, __pyx_L1_error); + __pyx_t_2 = __Pyx_Import(__pyx_n_s_functools, __pyx_t_3, -1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 5, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_lru_cache); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 5, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_lru_cache, __pyx_t_3) < 0) __PYX_ERR(0, 5, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "curated_tokenizers/_bbpe.pyx":6 + * from cython.operator cimport dereference as deref + * from functools import lru_cache + * from io import BytesIO # <<<<<<<<<<<<<< + * import json + * from libcpp.memory cimport make_shared, shared_ptr + */ + __pyx_t_2 = PyList_New(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 6, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_n_s_BytesIO); + __Pyx_GIVEREF(__pyx_n_s_BytesIO); + if (__Pyx_PyList_SET_ITEM(__pyx_t_2, 0, __pyx_n_s_BytesIO)) __PYX_ERR(0, 6, __pyx_L1_error); + __pyx_t_3 = __Pyx_Import(__pyx_n_s_io, __pyx_t_2, -1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 6, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_3, __pyx_n_s_BytesIO); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 6, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_BytesIO, __pyx_t_2) < 0) __PYX_ERR(0, 6, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "curated_tokenizers/_bbpe.pyx":7 + * from functools import lru_cache + * from io import BytesIO + * import json # <<<<<<<<<<<<<< + * from libcpp.memory cimport make_shared, shared_ptr + * from pathlib import Path + */ + __pyx_t_3 = __Pyx_ImportDottedModuleRelFirst(__pyx_n_s_json, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 7, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_json, __pyx_t_3) < 0) __PYX_ERR(0, 7, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "curated_tokenizers/_bbpe.pyx":9 + * import json + * from libcpp.memory cimport make_shared, shared_ptr + * from pathlib import Path # <<<<<<<<<<<<<< + * import regex + * + */ + __pyx_t_3 = PyList_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 9, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_INCREF(__pyx_n_s_Path); + __Pyx_GIVEREF(__pyx_n_s_Path); + if (__Pyx_PyList_SET_ITEM(__pyx_t_3, 0, __pyx_n_s_Path)) __PYX_ERR(0, 9, __pyx_L1_error); + __pyx_t_2 = __Pyx_Import(__pyx_n_s_pathlib, __pyx_t_3, -1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 9, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_Path); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 9, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_Path, __pyx_t_3) < 0) __PYX_ERR(0, 9, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "curated_tokenizers/_bbpe.pyx":10 + * from libcpp.memory cimport make_shared, shared_ptr + * from pathlib import Path + * import regex # <<<<<<<<<<<<<< + * + * + */ + __pyx_t_2 = __Pyx_ImportDottedModuleRelFirst(__pyx_n_s_regex, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 10, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_regex, __pyx_t_2) < 0) __PYX_ERR(0, 10, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "curated_tokenizers/_bbpe.pyx":21 + * + * + * SPLIT_PATTERN = r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""" # <<<<<<<<<<<<<< + * + * + */ + if (PyDict_SetItem(__pyx_d, __pyx_n_s_SPLIT_PATTERN, __pyx_kp_s_s_t_re_ve_m_ll_d_p_L_p_N_s_p_L) < 0) __PYX_ERR(0, 21, __pyx_L1_error) + + /* "curated_tokenizers/_bbpe.pyx":24 + * + * + * @lru_cache() # <<<<<<<<<<<<<< + * def bytes_to_unicode() -> Dict[int, bytes]: + * """ + */ + __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_lru_cache); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 24, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyObject_CallNoArg(__pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 24, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 24, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_return, __pyx_kp_s_Dict_int_bytes) < 0) __PYX_ERR(0, 24, __pyx_L1_error) + __pyx_t_4 = __Pyx_CyFunction_New(&__pyx_mdef_18curated_tokenizers_5_bbpe_1bytes_to_unicode, 0, __pyx_n_s_bytes_to_unicode, NULL, __pyx_n_s_curated_tokenizers__bbpe, __pyx_d, ((PyObject *)__pyx_codeobj__7)); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 24, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_CyFunction_SetAnnotationsDict(__pyx_t_4, __pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_4); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 24, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (PyDict_SetItem(__pyx_d, __pyx_n_s_bytes_to_unicode, __pyx_t_2) < 0) __PYX_ERR(0, 24, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "curated_tokenizers/_bbpe.pyx":69 + * self._merges = make_shared[Merges](c_merges) + * + * def __copy__(self): # <<<<<<<<<<<<<< + * return ByteBPEProcessor(vocab=self.vocab, merges=self.merges) + * + */ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_3__copy__, __Pyx_CYFUNCTION_CCLASS, __pyx_n_s_ByteBPEProcessor___copy, NULL, __pyx_n_s_curated_tokenizers__bbpe, __pyx_d, ((PyObject *)__pyx_codeobj__9)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 69, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_SetItemOnTypeDict((PyObject *)__pyx_ptype_18curated_tokenizers_5_bbpe_ByteBPEProcessor, __pyx_n_s_copy, __pyx_t_2) < 0) __PYX_ERR(0, 69, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + PyType_Modified(__pyx_ptype_18curated_tokenizers_5_bbpe_ByteBPEProcessor); + + /* "curated_tokenizers/_bbpe.pyx":72 + * return ByteBPEProcessor(vocab=self.vocab, merges=self.merges) + * + * def __deepcopy__(self, memo): # <<<<<<<<<<<<<< + * # We don't need a deepcopy of the vocab and merges dicts as their + * # contents will be copied into a backing store in the c'tor. + */ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_5__deepcopy__, __Pyx_CYFUNCTION_CCLASS, __pyx_n_s_ByteBPEProcessor___deepcopy, NULL, __pyx_n_s_curated_tokenizers__bbpe, __pyx_d, ((PyObject *)__pyx_codeobj__11)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 72, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_SetItemOnTypeDict((PyObject *)__pyx_ptype_18curated_tokenizers_5_bbpe_ByteBPEProcessor, __pyx_n_s_deepcopy, __pyx_t_2) < 0) __PYX_ERR(0, 72, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + PyType_Modified(__pyx_ptype_18curated_tokenizers_5_bbpe_ByteBPEProcessor); + + /* "curated_tokenizers/_bbpe.pyx":77 + * return ByteBPEProcessor(vocab=self.vocab, merges=self.merges) + * + * @staticmethod # <<<<<<<<<<<<<< + * def load_from_files(*, vocab: Path, merges: Path) -> ByteBPEProcessor: + * """Construct a processor from the given vocabulary and merges files.""" + */ + __pyx_t_2 = __Pyx_PyDict_NewPresized(3); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 77, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_vocab, __pyx_n_s_Path) < 0) __PYX_ERR(0, 77, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_merges, __pyx_n_s_Path) < 0) __PYX_ERR(0, 77, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_return, __pyx_n_s_ByteBPEProcessor) < 0) __PYX_ERR(0, 77, __pyx_L1_error) + __pyx_t_4 = __Pyx_CyFunction_New(&__pyx_mdef_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_7load_from_files, __Pyx_CYFUNCTION_STATICMETHOD | __Pyx_CYFUNCTION_CCLASS, __pyx_n_s_ByteBPEProcessor_load_from_files, NULL, __pyx_n_s_curated_tokenizers__bbpe, __pyx_d, ((PyObject *)__pyx_codeobj__13)); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 77, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_CyFunction_SetAnnotationsDict(__pyx_t_4, __pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (__Pyx_SetItemOnTypeDict((PyObject *)__pyx_ptype_18curated_tokenizers_5_bbpe_ByteBPEProcessor, __pyx_n_s_load_from_files, __pyx_t_4) < 0) __PYX_ERR(0, 77, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + PyType_Modified(__pyx_ptype_18curated_tokenizers_5_bbpe_ByteBPEProcessor); + __Pyx_GetNameInClass(__pyx_t_4, (PyObject *)__pyx_ptype_18curated_tokenizers_5_bbpe_ByteBPEProcessor, __pyx_n_s_load_from_files); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 77, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_builtin_staticmethod, __pyx_t_4); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 77, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__Pyx_SetItemOnTypeDict((PyObject *)__pyx_ptype_18curated_tokenizers_5_bbpe_ByteBPEProcessor, __pyx_n_s_load_from_files, __pyx_t_2) < 0) __PYX_ERR(0, 77, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + PyType_Modified(__pyx_ptype_18curated_tokenizers_5_bbpe_ByteBPEProcessor); + + /* "curated_tokenizers/_bbpe.pyx":94 + * return ByteBPEProcessor(vocab, merges) + * + * def decode_from_ids(self, ids: Iterable[int]) -> str: # <<<<<<<<<<<<<< + * """ + * Decode piece identifiers into string. + */ + __pyx_t_2 = __Pyx_PyDict_NewPresized(2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 94, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_ids, __pyx_kp_s_Iterable_int) < 0) __PYX_ERR(0, 94, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_return, __pyx_n_s_str) < 0) __PYX_ERR(0, 94, __pyx_L1_error) + __pyx_t_4 = __Pyx_CyFunction_New(&__pyx_mdef_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_9decode_from_ids, __Pyx_CYFUNCTION_CCLASS, __pyx_n_s_ByteBPEProcessor_decode_from_ids, NULL, __pyx_n_s_curated_tokenizers__bbpe, __pyx_d, ((PyObject *)__pyx_codeobj__15)); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 94, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_CyFunction_SetAnnotationsDict(__pyx_t_4, __pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (__Pyx_SetItemOnTypeDict((PyObject *)__pyx_ptype_18curated_tokenizers_5_bbpe_ByteBPEProcessor, __pyx_n_s_decode_from_ids, __pyx_t_4) < 0) __PYX_ERR(0, 94, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + PyType_Modified(__pyx_ptype_18curated_tokenizers_5_bbpe_ByteBPEProcessor); + + /* "curated_tokenizers/_bbpe.pyx":110 + * return decoded.getvalue().decode("utf-8") + * + * def encode(self, text: str) -> Tuple[List[int], List[str]]: # <<<<<<<<<<<<<< + * """ + * Split a text into pieces. + */ + __pyx_t_4 = __Pyx_PyDict_NewPresized(2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 110, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_text, __pyx_n_s_str) < 0) __PYX_ERR(0, 110, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_return, __pyx_kp_s_Tuple_List_int_List_str) < 0) __PYX_ERR(0, 110, __pyx_L1_error) + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_11encode, __Pyx_CYFUNCTION_CCLASS, __pyx_n_s_ByteBPEProcessor_encode, NULL, __pyx_n_s_curated_tokenizers__bbpe, __pyx_d, ((PyObject *)__pyx_codeobj__17)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 110, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_CyFunction_SetAnnotationsDict(__pyx_t_2, __pyx_t_4); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__Pyx_SetItemOnTypeDict((PyObject *)__pyx_ptype_18curated_tokenizers_5_bbpe_ByteBPEProcessor, __pyx_n_s_encode, __pyx_t_2) < 0) __PYX_ERR(0, 110, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + PyType_Modified(__pyx_ptype_18curated_tokenizers_5_bbpe_ByteBPEProcessor); + + /* "curated_tokenizers/_bbpe.pyx":120 + * return self._pieces_to_ids(pieces), pieces + * + * def encode_as_ids(self, text: str) -> List[int]: # <<<<<<<<<<<<<< + * """ + * Split a text into pieces, returning piece identifiers. + */ + __pyx_t_2 = __Pyx_PyDict_NewPresized(2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 120, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_text, __pyx_n_s_str) < 0) __PYX_ERR(0, 120, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_return, __pyx_kp_s_List_int) < 0) __PYX_ERR(0, 120, __pyx_L1_error) + __pyx_t_4 = __Pyx_CyFunction_New(&__pyx_mdef_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_13encode_as_ids, __Pyx_CYFUNCTION_CCLASS, __pyx_n_s_ByteBPEProcessor_encode_as_ids, NULL, __pyx_n_s_curated_tokenizers__bbpe, __pyx_d, ((PyObject *)__pyx_codeobj__18)); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 120, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_CyFunction_SetAnnotationsDict(__pyx_t_4, __pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (__Pyx_SetItemOnTypeDict((PyObject *)__pyx_ptype_18curated_tokenizers_5_bbpe_ByteBPEProcessor, __pyx_n_s_encode_as_ids, __pyx_t_4) < 0) __PYX_ERR(0, 120, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + PyType_Modified(__pyx_ptype_18curated_tokenizers_5_bbpe_ByteBPEProcessor); + + /* "curated_tokenizers/_bbpe.pyx":130 + * return self._pieces_to_ids(pieces) + * + * def encode_as_pieces(self, text: str) -> List[str]: # <<<<<<<<<<<<<< + * """ + * Split a text into pieces, returning piece pieces. + */ + __pyx_t_4 = __Pyx_PyDict_NewPresized(2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 130, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_text, __pyx_n_s_str) < 0) __PYX_ERR(0, 130, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_return, __pyx_kp_s_List_str) < 0) __PYX_ERR(0, 130, __pyx_L1_error) + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_15encode_as_pieces, __Pyx_CYFUNCTION_CCLASS, __pyx_n_s_ByteBPEProcessor_encode_as_piece, NULL, __pyx_n_s_curated_tokenizers__bbpe, __pyx_d, ((PyObject *)__pyx_codeobj__20)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 130, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_CyFunction_SetAnnotationsDict(__pyx_t_2, __pyx_t_4); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__Pyx_SetItemOnTypeDict((PyObject *)__pyx_ptype_18curated_tokenizers_5_bbpe_ByteBPEProcessor, __pyx_n_s_encode_as_pieces, __pyx_t_2) < 0) __PYX_ERR(0, 130, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + PyType_Modified(__pyx_ptype_18curated_tokenizers_5_bbpe_ByteBPEProcessor); + + /* "curated_tokenizers/_bbpe.pyx":150 + * return [(m1.decode('utf-8'), m2.decode('utf-8')) for m1, m2 in merges_bytes] + * + * def piece_id(self, piece: str) -> Optional[int]: # <<<<<<<<<<<<<< + * """Get the identifier for a piece.""" + * return self._piece_to_id.get(piece) + */ + __pyx_t_2 = __Pyx_PyDict_NewPresized(2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 150, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_piece, __pyx_n_s_str) < 0) __PYX_ERR(0, 150, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_return, __pyx_kp_s_Optional_int) < 0) __PYX_ERR(0, 150, __pyx_L1_error) + __pyx_t_4 = __Pyx_CyFunction_New(&__pyx_mdef_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_17piece_id, __Pyx_CYFUNCTION_CCLASS, __pyx_n_s_ByteBPEProcessor_piece_id, NULL, __pyx_n_s_curated_tokenizers__bbpe, __pyx_d, ((PyObject *)__pyx_codeobj__22)); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 150, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_CyFunction_SetAnnotationsDict(__pyx_t_4, __pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (__Pyx_SetItemOnTypeDict((PyObject *)__pyx_ptype_18curated_tokenizers_5_bbpe_ByteBPEProcessor, __pyx_n_s_piece_id, __pyx_t_4) < 0) __PYX_ERR(0, 150, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + PyType_Modified(__pyx_ptype_18curated_tokenizers_5_bbpe_ByteBPEProcessor); + + /* "curated_tokenizers/_bbpe.pyx":159 + * return dict(self._piece_to_id) + * + * def _pieces_to_ids(self, pieces): # <<<<<<<<<<<<<< + * piece_ids = [] + * for piece in pieces: + */ + __pyx_t_4 = __Pyx_CyFunction_New(&__pyx_mdef_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_19_pieces_to_ids, __Pyx_CYFUNCTION_CCLASS, __pyx_n_s_ByteBPEProcessor__pieces_to_ids, NULL, __pyx_n_s_curated_tokenizers__bbpe, __pyx_d, ((PyObject *)__pyx_codeobj__24)); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 159, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + if (__Pyx_SetItemOnTypeDict((PyObject *)__pyx_ptype_18curated_tokenizers_5_bbpe_ByteBPEProcessor, __pyx_n_s_pieces_to_ids, __pyx_t_4) < 0) __PYX_ERR(0, 159, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + PyType_Modified(__pyx_ptype_18curated_tokenizers_5_bbpe_ByteBPEProcessor); + + /* "curated_tokenizers/_bbpe.pyx":169 + * return piece_ids + * + * def __reduce__(self): # <<<<<<<<<<<<<< + * return (unpickle_byte_bpe_processor, (self.vocab, self.merges,)) + * + */ + __pyx_t_4 = __Pyx_CyFunction_New(&__pyx_mdef_18curated_tokenizers_5_bbpe_16ByteBPEProcessor_21__reduce__, __Pyx_CYFUNCTION_CCLASS, __pyx_n_s_ByteBPEProcessor___reduce, NULL, __pyx_n_s_curated_tokenizers__bbpe, __pyx_d, ((PyObject *)__pyx_codeobj__25)); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 169, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + if (__Pyx_SetItemOnTypeDict((PyObject *)__pyx_ptype_18curated_tokenizers_5_bbpe_ByteBPEProcessor, __pyx_n_s_reduce, __pyx_t_4) < 0) __PYX_ERR(0, 169, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + PyType_Modified(__pyx_ptype_18curated_tokenizers_5_bbpe_ByteBPEProcessor); + + /* "curated_tokenizers/_bbpe.pyx":172 + * return (unpickle_byte_bpe_processor, (self.vocab, self.merges,)) + * + * def unpickle_byte_bpe_processor(vocab: Dict[str, int], # <<<<<<<<<<<<<< + * merges: List[Tuple[str, str]]) -> ByteBPEProcessor: + * return ByteBPEProcessor(vocab, merges) + */ + __pyx_t_4 = __Pyx_PyDict_NewPresized(3); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 172, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_vocab, __pyx_kp_s_Dict_str_int) < 0) __PYX_ERR(0, 172, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_merges, __pyx_kp_s_List_Tuple_str_str) < 0) __PYX_ERR(0, 172, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_return, __pyx_n_s_ByteBPEProcessor) < 0) __PYX_ERR(0, 172, __pyx_L1_error) + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_18curated_tokenizers_5_bbpe_3unpickle_byte_bpe_processor, 0, __pyx_n_s_unpickle_byte_bpe_processor, NULL, __pyx_n_s_curated_tokenizers__bbpe, __pyx_d, ((PyObject *)__pyx_codeobj__27)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 172, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_CyFunction_SetAnnotationsDict(__pyx_t_2, __pyx_t_4); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (PyDict_SetItem(__pyx_d, __pyx_n_s_unpickle_byte_bpe_processor, __pyx_t_2) < 0) __PYX_ERR(0, 172, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "curated_tokenizers/_bbpe.pyx":1 + * # cython: infer_types # <<<<<<<<<<<<<< + * + * from typing import Dict, Iterable, List, Optional, Tuple + */ + __pyx_t_2 = __Pyx_PyDict_NewPresized(0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_2) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /*--- Wrapped vars code ---*/ + + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + if (__pyx_m) { + if (__pyx_d && stringtab_initialized) { + __Pyx_AddTraceback("init curated_tokenizers._bbpe", __pyx_clineno, __pyx_lineno, __pyx_filename); + } + #if !CYTHON_USE_MODULE_STATE + Py_CLEAR(__pyx_m); + #else + Py_DECREF(__pyx_m); + if (pystate_addmodule_run) { + PyObject *tp, *value, *tb; + PyErr_Fetch(&tp, &value, &tb); + PyState_RemoveModule(&__pyx_moduledef); + PyErr_Restore(tp, value, tb); + } + #endif + } else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_ImportError, "init curated_tokenizers._bbpe"); + } + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + #if CYTHON_PEP489_MULTI_PHASE_INIT + return (__pyx_m != NULL) ? 0 : -1; + #elif PY_MAJOR_VERSION >= 3 + return __pyx_m; + #else + return; + #endif +} +/* #### Code section: cleanup_globals ### */ +/* #### Code section: cleanup_module ### */ +/* #### Code section: main_method ### */ +/* #### Code section: utility_code_pragmas ### */ +#ifdef _MSC_VER +#pragma warning( push ) +/* Warning 4127: conditional expression is constant + * Cython uses constant conditional expressions to allow in inline functions to be optimized at + * compile-time, so this warning is not useful + */ +#pragma warning( disable : 4127 ) +#endif + + + +/* #### Code section: utility_code_def ### */ + +/* --- Runtime support code --- */ +/* Refnanny */ +#if CYTHON_REFNANNY +static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { + PyObject *m = NULL, *p = NULL; + void *r = NULL; + m = PyImport_ImportModule(modname); + if (!m) goto end; + p = PyObject_GetAttrString(m, "RefNannyAPI"); + if (!p) goto end; + r = PyLong_AsVoidPtr(p); +end: + Py_XDECREF(p); + Py_XDECREF(m); + return (__Pyx_RefNannyAPIStruct *)r; +} +#endif + +/* PyErrExceptionMatches */ +#if CYTHON_FAST_THREAD_STATE +static int __Pyx_PyErr_ExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { + Py_ssize_t i, n; + n = PyTuple_GET_SIZE(tuple); +#if PY_MAJOR_VERSION >= 3 + for (i=0; i= 0x030C00A6 + PyObject *current_exception = tstate->current_exception; + if (unlikely(!current_exception)) return 0; + exc_type = (PyObject*) Py_TYPE(current_exception); + if (exc_type == err) return 1; +#else + exc_type = tstate->curexc_type; + if (exc_type == err) return 1; + if (unlikely(!exc_type)) return 0; +#endif + #if CYTHON_AVOID_BORROWED_REFS + Py_INCREF(exc_type); + #endif + if (unlikely(PyTuple_Check(err))) { + result = __Pyx_PyErr_ExceptionMatchesTuple(exc_type, err); + } else { + result = __Pyx_PyErr_GivenExceptionMatches(exc_type, err); + } + #if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(exc_type); + #endif + return result; +} +#endif + +/* PyErrFetchRestore */ +#if CYTHON_FAST_THREAD_STATE +static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { +#if PY_VERSION_HEX >= 0x030C00A6 + PyObject *tmp_value; + assert(type == NULL || (value != NULL && type == (PyObject*) Py_TYPE(value))); + if (value) { + #if CYTHON_COMPILING_IN_CPYTHON + if (unlikely(((PyBaseExceptionObject*) value)->traceback != tb)) + #endif + PyException_SetTraceback(value, tb); + } + tmp_value = tstate->current_exception; + tstate->current_exception = value; + Py_XDECREF(tmp_value); + Py_XDECREF(type); + Py_XDECREF(tb); +#else + PyObject *tmp_type, *tmp_value, *tmp_tb; + tmp_type = tstate->curexc_type; + tmp_value = tstate->curexc_value; + tmp_tb = tstate->curexc_traceback; + tstate->curexc_type = type; + tstate->curexc_value = value; + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#endif +} +static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { +#if PY_VERSION_HEX >= 0x030C00A6 + PyObject* exc_value; + exc_value = tstate->current_exception; + tstate->current_exception = 0; + *value = exc_value; + *type = NULL; + *tb = NULL; + if (exc_value) { + *type = (PyObject*) Py_TYPE(exc_value); + Py_INCREF(*type); + #if CYTHON_COMPILING_IN_CPYTHON + *tb = ((PyBaseExceptionObject*) exc_value)->traceback; + Py_XINCREF(*tb); + #else + *tb = PyException_GetTraceback(exc_value); + #endif + } +#else + *type = tstate->curexc_type; + *value = tstate->curexc_value; + *tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; +#endif +} +#endif + +/* PyObjectGetAttrStr */ +#if CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro)) + return tp->tp_getattro(obj, attr_name); +#if PY_MAJOR_VERSION < 3 + if (likely(tp->tp_getattr)) + return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); +#endif + return PyObject_GetAttr(obj, attr_name); +} +#endif + +/* PyObjectGetAttrStrNoError */ +#if __PYX_LIMITED_VERSION_HEX < 0x030d00A1 +static void __Pyx_PyObject_GetAttrStr_ClearAttributeError(void) { + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + if (likely(__Pyx_PyErr_ExceptionMatches(PyExc_AttributeError))) + __Pyx_PyErr_Clear(); +} +#endif +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStrNoError(PyObject* obj, PyObject* attr_name) { + PyObject *result; +#if __PYX_LIMITED_VERSION_HEX >= 0x030d00A1 + (void) PyObject_GetOptionalAttr(obj, attr_name, &result); + return result; +#else +#if CYTHON_COMPILING_IN_CPYTHON && CYTHON_USE_TYPE_SLOTS && PY_VERSION_HEX >= 0x030700B1 + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro == PyObject_GenericGetAttr)) { + return _PyObject_GenericGetAttrWithDict(obj, attr_name, NULL, 1); + } +#endif + result = __Pyx_PyObject_GetAttrStr(obj, attr_name); + if (unlikely(!result)) { + __Pyx_PyObject_GetAttrStr_ClearAttributeError(); + } + return result; +#endif +} + +/* GetBuiltinName */ +static PyObject *__Pyx_GetBuiltinName(PyObject *name) { + PyObject* result = __Pyx_PyObject_GetAttrStrNoError(__pyx_b, name); + if (unlikely(!result) && !PyErr_Occurred()) { + PyErr_Format(PyExc_NameError, +#if PY_MAJOR_VERSION >= 3 + "name '%U' is not defined", name); +#else + "name '%.200s' is not defined", PyString_AS_STRING(name)); +#endif + } + return result; +} + +/* TupleAndListFromArray */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE void __Pyx_copy_object_array(PyObject *const *CYTHON_RESTRICT src, PyObject** CYTHON_RESTRICT dest, Py_ssize_t length) { + PyObject *v; + Py_ssize_t i; + for (i = 0; i < length; i++) { + v = dest[i] = src[i]; + Py_INCREF(v); + } +} +static CYTHON_INLINE PyObject * +__Pyx_PyTuple_FromArray(PyObject *const *src, Py_ssize_t n) +{ + PyObject *res; + if (n <= 0) { + Py_INCREF(__pyx_empty_tuple); + return __pyx_empty_tuple; + } + res = PyTuple_New(n); + if (unlikely(res == NULL)) return NULL; + __Pyx_copy_object_array(src, ((PyTupleObject*)res)->ob_item, n); + return res; +} +static CYTHON_INLINE PyObject * +__Pyx_PyList_FromArray(PyObject *const *src, Py_ssize_t n) +{ + PyObject *res; + if (n <= 0) { + return PyList_New(0); + } + res = PyList_New(n); + if (unlikely(res == NULL)) return NULL; + __Pyx_copy_object_array(src, ((PyListObject*)res)->ob_item, n); + return res; +} +#endif + +/* BytesEquals */ +static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals) { +#if CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API + return PyObject_RichCompareBool(s1, s2, equals); +#else + if (s1 == s2) { + return (equals == Py_EQ); + } else if (PyBytes_CheckExact(s1) & PyBytes_CheckExact(s2)) { + const char *ps1, *ps2; + Py_ssize_t length = PyBytes_GET_SIZE(s1); + if (length != PyBytes_GET_SIZE(s2)) + return (equals == Py_NE); + ps1 = PyBytes_AS_STRING(s1); + ps2 = PyBytes_AS_STRING(s2); + if (ps1[0] != ps2[0]) { + return (equals == Py_NE); + } else if (length == 1) { + return (equals == Py_EQ); + } else { + int result; +#if CYTHON_USE_UNICODE_INTERNALS && (PY_VERSION_HEX < 0x030B0000) + Py_hash_t hash1, hash2; + hash1 = ((PyBytesObject*)s1)->ob_shash; + hash2 = ((PyBytesObject*)s2)->ob_shash; + if (hash1 != hash2 && hash1 != -1 && hash2 != -1) { + return (equals == Py_NE); + } +#endif + result = memcmp(ps1, ps2, (size_t)length); + return (equals == Py_EQ) ? (result == 0) : (result != 0); + } + } else if ((s1 == Py_None) & PyBytes_CheckExact(s2)) { + return (equals == Py_NE); + } else if ((s2 == Py_None) & PyBytes_CheckExact(s1)) { + return (equals == Py_NE); + } else { + int result; + PyObject* py_result = PyObject_RichCompare(s1, s2, equals); + if (!py_result) + return -1; + result = __Pyx_PyObject_IsTrue(py_result); + Py_DECREF(py_result); + return result; + } +#endif +} + +/* UnicodeEquals */ +static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals) { +#if CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API + return PyObject_RichCompareBool(s1, s2, equals); +#else +#if PY_MAJOR_VERSION < 3 + PyObject* owned_ref = NULL; +#endif + int s1_is_unicode, s2_is_unicode; + if (s1 == s2) { + goto return_eq; + } + s1_is_unicode = PyUnicode_CheckExact(s1); + s2_is_unicode = PyUnicode_CheckExact(s2); +#if PY_MAJOR_VERSION < 3 + if ((s1_is_unicode & (!s2_is_unicode)) && PyString_CheckExact(s2)) { + owned_ref = PyUnicode_FromObject(s2); + if (unlikely(!owned_ref)) + return -1; + s2 = owned_ref; + s2_is_unicode = 1; + } else if ((s2_is_unicode & (!s1_is_unicode)) && PyString_CheckExact(s1)) { + owned_ref = PyUnicode_FromObject(s1); + if (unlikely(!owned_ref)) + return -1; + s1 = owned_ref; + s1_is_unicode = 1; + } else if (((!s2_is_unicode) & (!s1_is_unicode))) { + return __Pyx_PyBytes_Equals(s1, s2, equals); + } +#endif + if (s1_is_unicode & s2_is_unicode) { + Py_ssize_t length; + int kind; + void *data1, *data2; + if (unlikely(__Pyx_PyUnicode_READY(s1) < 0) || unlikely(__Pyx_PyUnicode_READY(s2) < 0)) + return -1; + length = __Pyx_PyUnicode_GET_LENGTH(s1); + if (length != __Pyx_PyUnicode_GET_LENGTH(s2)) { + goto return_ne; + } +#if CYTHON_USE_UNICODE_INTERNALS + { + Py_hash_t hash1, hash2; + #if CYTHON_PEP393_ENABLED + hash1 = ((PyASCIIObject*)s1)->hash; + hash2 = ((PyASCIIObject*)s2)->hash; + #else + hash1 = ((PyUnicodeObject*)s1)->hash; + hash2 = ((PyUnicodeObject*)s2)->hash; + #endif + if (hash1 != hash2 && hash1 != -1 && hash2 != -1) { + goto return_ne; + } + } +#endif + kind = __Pyx_PyUnicode_KIND(s1); + if (kind != __Pyx_PyUnicode_KIND(s2)) { + goto return_ne; + } + data1 = __Pyx_PyUnicode_DATA(s1); + data2 = __Pyx_PyUnicode_DATA(s2); + if (__Pyx_PyUnicode_READ(kind, data1, 0) != __Pyx_PyUnicode_READ(kind, data2, 0)) { + goto return_ne; + } else if (length == 1) { + goto return_eq; + } else { + int result = memcmp(data1, data2, (size_t)(length * kind)); + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(owned_ref); + #endif + return (equals == Py_EQ) ? (result == 0) : (result != 0); + } + } else if ((s1 == Py_None) & s2_is_unicode) { + goto return_ne; + } else if ((s2 == Py_None) & s1_is_unicode) { + goto return_ne; + } else { + int result; + PyObject* py_result = PyObject_RichCompare(s1, s2, equals); + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(owned_ref); + #endif + if (!py_result) + return -1; + result = __Pyx_PyObject_IsTrue(py_result); + Py_DECREF(py_result); + return result; + } +return_eq: + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(owned_ref); + #endif + return (equals == Py_EQ); +return_ne: + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(owned_ref); + #endif + return (equals == Py_NE); +#endif +} + +/* fastcall */ +#if CYTHON_METH_FASTCALL +static CYTHON_INLINE PyObject * __Pyx_GetKwValue_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues, PyObject *s) +{ + Py_ssize_t i, n = PyTuple_GET_SIZE(kwnames); + for (i = 0; i < n; i++) + { + if (s == PyTuple_GET_ITEM(kwnames, i)) return kwvalues[i]; + } + for (i = 0; i < n; i++) + { + int eq = __Pyx_PyUnicode_Equals(s, PyTuple_GET_ITEM(kwnames, i), Py_EQ); + if (unlikely(eq != 0)) { + if (unlikely(eq < 0)) return NULL; + return kwvalues[i]; + } + } + return NULL; +} +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030d0000 +CYTHON_UNUSED static PyObject *__Pyx_KwargsAsDict_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues) { + Py_ssize_t i, nkwargs = PyTuple_GET_SIZE(kwnames); + PyObject *dict; + dict = PyDict_New(); + if (unlikely(!dict)) + return NULL; + for (i=0; itp_call; + if (unlikely(!call)) + return PyObject_Call(func, arg, kw); + #if PY_MAJOR_VERSION < 3 + if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) + return NULL; + #else + if (unlikely(Py_EnterRecursiveCall(" while calling a Python object"))) + return NULL; + #endif + result = (*call)(func, arg, kw); + Py_LeaveRecursiveCall(); + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + } + return result; +} +#endif + +/* SliceTupleAndList */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE void __Pyx_crop_slice(Py_ssize_t* _start, Py_ssize_t* _stop, Py_ssize_t* _length) { + Py_ssize_t start = *_start, stop = *_stop, length = *_length; + if (start < 0) { + start += length; + if (start < 0) + start = 0; + } + if (stop < 0) + stop += length; + else if (stop > length) + stop = length; + *_length = stop - start; + *_start = start; + *_stop = stop; +} +static CYTHON_INLINE PyObject* __Pyx_PyList_GetSlice( + PyObject* src, Py_ssize_t start, Py_ssize_t stop) { + Py_ssize_t length = PyList_GET_SIZE(src); + __Pyx_crop_slice(&start, &stop, &length); + if (length <= 0) { + return PyList_New(0); + } + return __Pyx_PyList_FromArray(((PyListObject*)src)->ob_item + start, length); +} +static CYTHON_INLINE PyObject* __Pyx_PyTuple_GetSlice( + PyObject* src, Py_ssize_t start, Py_ssize_t stop) { + Py_ssize_t length = PyTuple_GET_SIZE(src); + __Pyx_crop_slice(&start, &stop, &length); + return __Pyx_PyTuple_FromArray(((PyTupleObject*)src)->ob_item + start, length); +} +#endif + +/* PyIntBinop */ +#if !CYTHON_COMPILING_IN_PYPY +static PyObject* __Pyx_PyInt_AddCObj(PyObject *op1, PyObject *op2, long intval, int inplace, int zerodivision_check) { + CYTHON_MAYBE_UNUSED_VAR(intval); + CYTHON_MAYBE_UNUSED_VAR(inplace); + CYTHON_UNUSED_VAR(zerodivision_check); + #if PY_MAJOR_VERSION < 3 + if (likely(PyInt_CheckExact(op2))) { + const long a = intval; + long x; + long b = PyInt_AS_LONG(op2); + + x = (long)((unsigned long)a + (unsigned long)b); + if (likely((x^a) >= 0 || (x^b) >= 0)) + return PyInt_FromLong(x); + return PyLong_Type.tp_as_number->nb_add(op1, op2); + } + #endif + #if CYTHON_USE_PYLONG_INTERNALS + if (likely(PyLong_CheckExact(op2))) { + const long a = intval; + long b, x; +#ifdef HAVE_LONG_LONG + const PY_LONG_LONG lla = intval; + PY_LONG_LONG llb, llx; +#endif + if (unlikely(__Pyx_PyLong_IsZero(op2))) { + return __Pyx_NewRef(op1); + } + if (likely(__Pyx_PyLong_IsCompact(op2))) { + b = __Pyx_PyLong_CompactValue(op2); + } else { + const digit* digits = __Pyx_PyLong_Digits(op2); + const Py_ssize_t size = __Pyx_PyLong_SignedDigitCount(op2); + switch (size) { + case -2: + if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { + b = -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + break; + #ifdef HAVE_LONG_LONG + } else if (8 * sizeof(PY_LONG_LONG) - 1 > 2 * PyLong_SHIFT) { + llb = -(PY_LONG_LONG) (((((unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + goto long_long; + #endif + } + CYTHON_FALLTHROUGH; + case 2: + if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { + b = (long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + break; + #ifdef HAVE_LONG_LONG + } else if (8 * sizeof(PY_LONG_LONG) - 1 > 2 * PyLong_SHIFT) { + llb = (PY_LONG_LONG) (((((unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + goto long_long; + #endif + } + CYTHON_FALLTHROUGH; + case -3: + if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { + b = -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + break; + #ifdef HAVE_LONG_LONG + } else if (8 * sizeof(PY_LONG_LONG) - 1 > 3 * PyLong_SHIFT) { + llb = -(PY_LONG_LONG) (((((((unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + goto long_long; + #endif + } + CYTHON_FALLTHROUGH; + case 3: + if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { + b = (long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + break; + #ifdef HAVE_LONG_LONG + } else if (8 * sizeof(PY_LONG_LONG) - 1 > 3 * PyLong_SHIFT) { + llb = (PY_LONG_LONG) (((((((unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + goto long_long; + #endif + } + CYTHON_FALLTHROUGH; + case -4: + if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { + b = -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + break; + #ifdef HAVE_LONG_LONG + } else if (8 * sizeof(PY_LONG_LONG) - 1 > 4 * PyLong_SHIFT) { + llb = -(PY_LONG_LONG) (((((((((unsigned PY_LONG_LONG)digits[3]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + goto long_long; + #endif + } + CYTHON_FALLTHROUGH; + case 4: + if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { + b = (long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + break; + #ifdef HAVE_LONG_LONG + } else if (8 * sizeof(PY_LONG_LONG) - 1 > 4 * PyLong_SHIFT) { + llb = (PY_LONG_LONG) (((((((((unsigned PY_LONG_LONG)digits[3]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + goto long_long; + #endif + } + CYTHON_FALLTHROUGH; + default: return PyLong_Type.tp_as_number->nb_add(op1, op2); + } + } + x = a + b; + return PyLong_FromLong(x); +#ifdef HAVE_LONG_LONG + long_long: + llx = lla + llb; + return PyLong_FromLongLong(llx); +#endif + + + } + #endif + if (PyFloat_CheckExact(op2)) { + const long a = intval; +#if CYTHON_COMPILING_IN_LIMITED_API + double b = __pyx_PyFloat_AsDouble(op2); +#else + double b = PyFloat_AS_DOUBLE(op2); +#endif + double result; + + PyFPE_START_PROTECT("add", return NULL) + result = ((double)a) + (double)b; + PyFPE_END_PROTECT(result) + return PyFloat_FromDouble(result); + } + return (inplace ? PyNumber_InPlaceAdd : PyNumber_Add)(op1, op2); +} +#endif + +/* PyIntBinop */ +#if !CYTHON_COMPILING_IN_PYPY +static PyObject* __Pyx_PyInt_AddObjC(PyObject *op1, PyObject *op2, long intval, int inplace, int zerodivision_check) { + CYTHON_MAYBE_UNUSED_VAR(intval); + CYTHON_MAYBE_UNUSED_VAR(inplace); + CYTHON_UNUSED_VAR(zerodivision_check); + #if PY_MAJOR_VERSION < 3 + if (likely(PyInt_CheckExact(op1))) { + const long b = intval; + long x; + long a = PyInt_AS_LONG(op1); + + x = (long)((unsigned long)a + (unsigned long)b); + if (likely((x^a) >= 0 || (x^b) >= 0)) + return PyInt_FromLong(x); + return PyLong_Type.tp_as_number->nb_add(op1, op2); + } + #endif + #if CYTHON_USE_PYLONG_INTERNALS + if (likely(PyLong_CheckExact(op1))) { + const long b = intval; + long a, x; +#ifdef HAVE_LONG_LONG + const PY_LONG_LONG llb = intval; + PY_LONG_LONG lla, llx; +#endif + if (unlikely(__Pyx_PyLong_IsZero(op1))) { + return __Pyx_NewRef(op2); + } + if (likely(__Pyx_PyLong_IsCompact(op1))) { + a = __Pyx_PyLong_CompactValue(op1); + } else { + const digit* digits = __Pyx_PyLong_Digits(op1); + const Py_ssize_t size = __Pyx_PyLong_SignedDigitCount(op1); + switch (size) { + case -2: + if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { + a = -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + break; + #ifdef HAVE_LONG_LONG + } else if (8 * sizeof(PY_LONG_LONG) - 1 > 2 * PyLong_SHIFT) { + lla = -(PY_LONG_LONG) (((((unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + goto long_long; + #endif + } + CYTHON_FALLTHROUGH; + case 2: + if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { + a = (long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + break; + #ifdef HAVE_LONG_LONG + } else if (8 * sizeof(PY_LONG_LONG) - 1 > 2 * PyLong_SHIFT) { + lla = (PY_LONG_LONG) (((((unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + goto long_long; + #endif + } + CYTHON_FALLTHROUGH; + case -3: + if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { + a = -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + break; + #ifdef HAVE_LONG_LONG + } else if (8 * sizeof(PY_LONG_LONG) - 1 > 3 * PyLong_SHIFT) { + lla = -(PY_LONG_LONG) (((((((unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + goto long_long; + #endif + } + CYTHON_FALLTHROUGH; + case 3: + if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { + a = (long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + break; + #ifdef HAVE_LONG_LONG + } else if (8 * sizeof(PY_LONG_LONG) - 1 > 3 * PyLong_SHIFT) { + lla = (PY_LONG_LONG) (((((((unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + goto long_long; + #endif + } + CYTHON_FALLTHROUGH; + case -4: + if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { + a = -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + break; + #ifdef HAVE_LONG_LONG + } else if (8 * sizeof(PY_LONG_LONG) - 1 > 4 * PyLong_SHIFT) { + lla = -(PY_LONG_LONG) (((((((((unsigned PY_LONG_LONG)digits[3]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + goto long_long; + #endif + } + CYTHON_FALLTHROUGH; + case 4: + if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { + a = (long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + break; + #ifdef HAVE_LONG_LONG + } else if (8 * sizeof(PY_LONG_LONG) - 1 > 4 * PyLong_SHIFT) { + lla = (PY_LONG_LONG) (((((((((unsigned PY_LONG_LONG)digits[3]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + goto long_long; + #endif + } + CYTHON_FALLTHROUGH; + default: return PyLong_Type.tp_as_number->nb_add(op1, op2); + } + } + x = a + b; + return PyLong_FromLong(x); +#ifdef HAVE_LONG_LONG + long_long: + llx = lla + llb; + return PyLong_FromLongLong(llx); +#endif + + + } + #endif + if (PyFloat_CheckExact(op1)) { + const long b = intval; +#if CYTHON_COMPILING_IN_LIMITED_API + double a = __pyx_PyFloat_AsDouble(op1); +#else + double a = PyFloat_AS_DOUBLE(op1); +#endif + double result; + + PyFPE_START_PROTECT("add", return NULL) + result = ((double)a) + (double)b; + PyFPE_END_PROTECT(result) + return PyFloat_FromDouble(result); + } + return (inplace ? PyNumber_InPlaceAdd : PyNumber_Add)(op1, op2); +} +#endif + +/* PyFunctionFastCall */ +#if CYTHON_FAST_PYCALL && !CYTHON_VECTORCALL +static PyObject* __Pyx_PyFunction_FastCallNoKw(PyCodeObject *co, PyObject **args, Py_ssize_t na, + PyObject *globals) { + PyFrameObject *f; + PyThreadState *tstate = __Pyx_PyThreadState_Current; + PyObject **fastlocals; + Py_ssize_t i; + PyObject *result; + assert(globals != NULL); + /* XXX Perhaps we should create a specialized + PyFrame_New() that doesn't take locals, but does + take builtins without sanity checking them. + */ + assert(tstate != NULL); + f = PyFrame_New(tstate, co, globals, NULL); + if (f == NULL) { + return NULL; + } + fastlocals = __Pyx_PyFrame_GetLocalsplus(f); + for (i = 0; i < na; i++) { + Py_INCREF(*args); + fastlocals[i] = *args++; + } + result = PyEval_EvalFrameEx(f,0); + ++tstate->recursion_depth; + Py_DECREF(f); + --tstate->recursion_depth; + return result; +} +static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, Py_ssize_t nargs, PyObject *kwargs) { + PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func); + PyObject *globals = PyFunction_GET_GLOBALS(func); + PyObject *argdefs = PyFunction_GET_DEFAULTS(func); + PyObject *closure; +#if PY_MAJOR_VERSION >= 3 + PyObject *kwdefs; +#endif + PyObject *kwtuple, **k; + PyObject **d; + Py_ssize_t nd; + Py_ssize_t nk; + PyObject *result; + assert(kwargs == NULL || PyDict_Check(kwargs)); + nk = kwargs ? PyDict_Size(kwargs) : 0; + #if PY_MAJOR_VERSION < 3 + if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) { + return NULL; + } + #else + if (unlikely(Py_EnterRecursiveCall(" while calling a Python object"))) { + return NULL; + } + #endif + if ( +#if PY_MAJOR_VERSION >= 3 + co->co_kwonlyargcount == 0 && +#endif + likely(kwargs == NULL || nk == 0) && + co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) { + if (argdefs == NULL && co->co_argcount == nargs) { + result = __Pyx_PyFunction_FastCallNoKw(co, args, nargs, globals); + goto done; + } + else if (nargs == 0 && argdefs != NULL + && co->co_argcount == Py_SIZE(argdefs)) { + /* function called with no arguments, but all parameters have + a default value: use default values as arguments .*/ + args = &PyTuple_GET_ITEM(argdefs, 0); + result =__Pyx_PyFunction_FastCallNoKw(co, args, Py_SIZE(argdefs), globals); + goto done; + } + } + if (kwargs != NULL) { + Py_ssize_t pos, i; + kwtuple = PyTuple_New(2 * nk); + if (kwtuple == NULL) { + result = NULL; + goto done; + } + k = &PyTuple_GET_ITEM(kwtuple, 0); + pos = i = 0; + while (PyDict_Next(kwargs, &pos, &k[i], &k[i+1])) { + Py_INCREF(k[i]); + Py_INCREF(k[i+1]); + i += 2; + } + nk = i / 2; + } + else { + kwtuple = NULL; + k = NULL; + } + closure = PyFunction_GET_CLOSURE(func); +#if PY_MAJOR_VERSION >= 3 + kwdefs = PyFunction_GET_KW_DEFAULTS(func); +#endif + if (argdefs != NULL) { + d = &PyTuple_GET_ITEM(argdefs, 0); + nd = Py_SIZE(argdefs); + } + else { + d = NULL; + nd = 0; + } +#if PY_MAJOR_VERSION >= 3 + result = PyEval_EvalCodeEx((PyObject*)co, globals, (PyObject *)NULL, + args, (int)nargs, + k, (int)nk, + d, (int)nd, kwdefs, closure); +#else + result = PyEval_EvalCodeEx(co, globals, (PyObject *)NULL, + args, (int)nargs, + k, (int)nk, + d, (int)nd, closure); +#endif + Py_XDECREF(kwtuple); +done: + Py_LeaveRecursiveCall(); + return result; +} +#endif + +/* PyObjectCallMethO */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg) { + PyObject *self, *result; + PyCFunction cfunc; + cfunc = __Pyx_CyOrPyCFunction_GET_FUNCTION(func); + self = __Pyx_CyOrPyCFunction_GET_SELF(func); + #if PY_MAJOR_VERSION < 3 + if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) + return NULL; + #else + if (unlikely(Py_EnterRecursiveCall(" while calling a Python object"))) + return NULL; + #endif + result = cfunc(self, arg); + Py_LeaveRecursiveCall(); + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + } + return result; +} +#endif + +/* PyObjectFastCall */ +#if PY_VERSION_HEX < 0x03090000 || CYTHON_COMPILING_IN_LIMITED_API +static PyObject* __Pyx_PyObject_FastCall_fallback(PyObject *func, PyObject **args, size_t nargs, PyObject *kwargs) { + PyObject *argstuple; + PyObject *result = 0; + size_t i; + argstuple = PyTuple_New((Py_ssize_t)nargs); + if (unlikely(!argstuple)) return NULL; + for (i = 0; i < nargs; i++) { + Py_INCREF(args[i]); + if (__Pyx_PyTuple_SET_ITEM(argstuple, (Py_ssize_t)i, args[i]) < 0) goto bad; + } + result = __Pyx_PyObject_Call(func, argstuple, kwargs); + bad: + Py_DECREF(argstuple); + return result; +} +#endif +static CYTHON_INLINE PyObject* __Pyx_PyObject_FastCallDict(PyObject *func, PyObject **args, size_t _nargs, PyObject *kwargs) { + Py_ssize_t nargs = __Pyx_PyVectorcall_NARGS(_nargs); +#if CYTHON_COMPILING_IN_CPYTHON + if (nargs == 0 && kwargs == NULL) { + if (__Pyx_CyOrPyCFunction_Check(func) && likely( __Pyx_CyOrPyCFunction_GET_FLAGS(func) & METH_NOARGS)) + return __Pyx_PyObject_CallMethO(func, NULL); + } + else if (nargs == 1 && kwargs == NULL) { + if (__Pyx_CyOrPyCFunction_Check(func) && likely( __Pyx_CyOrPyCFunction_GET_FLAGS(func) & METH_O)) + return __Pyx_PyObject_CallMethO(func, args[0]); + } +#endif + #if PY_VERSION_HEX < 0x030800B1 + #if CYTHON_FAST_PYCCALL + if (PyCFunction_Check(func)) { + if (kwargs) { + return _PyCFunction_FastCallDict(func, args, nargs, kwargs); + } else { + return _PyCFunction_FastCallKeywords(func, args, nargs, NULL); + } + } + #if PY_VERSION_HEX >= 0x030700A1 + if (!kwargs && __Pyx_IS_TYPE(func, &PyMethodDescr_Type)) { + return _PyMethodDescr_FastCallKeywords(func, args, nargs, NULL); + } + #endif + #endif + #if CYTHON_FAST_PYCALL + if (PyFunction_Check(func)) { + return __Pyx_PyFunction_FastCallDict(func, args, nargs, kwargs); + } + #endif + #endif + if (kwargs == NULL) { + #if CYTHON_VECTORCALL + #if PY_VERSION_HEX < 0x03090000 + vectorcallfunc f = _PyVectorcall_Function(func); + #else + vectorcallfunc f = PyVectorcall_Function(func); + #endif + if (f) { + return f(func, args, (size_t)nargs, NULL); + } + #elif defined(__Pyx_CyFunction_USED) && CYTHON_BACKPORT_VECTORCALL + if (__Pyx_CyFunction_CheckExact(func)) { + __pyx_vectorcallfunc f = __Pyx_CyFunction_func_vectorcall(func); + if (f) return f(func, args, (size_t)nargs, NULL); + } + #endif + } + if (nargs == 0) { + return __Pyx_PyObject_Call(func, __pyx_empty_tuple, kwargs); + } + #if PY_VERSION_HEX >= 0x03090000 && !CYTHON_COMPILING_IN_LIMITED_API + return PyObject_VectorcallDict(func, args, (size_t)nargs, kwargs); + #else + return __Pyx_PyObject_FastCall_fallback(func, args, (size_t)nargs, kwargs); + #endif +} + +/* PyObjectCallOneArg */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { + PyObject *args[2] = {NULL, arg}; + return __Pyx_PyObject_FastCall(func, args+1, 1 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET); +} + +/* RaiseArgTupleInvalid */ +static void __Pyx_RaiseArgtupleInvalid( + const char* func_name, + int exact, + Py_ssize_t num_min, + Py_ssize_t num_max, + Py_ssize_t num_found) +{ + Py_ssize_t num_expected; + const char *more_or_less; + if (num_found < num_min) { + num_expected = num_min; + more_or_less = "at least"; + } else { + num_expected = num_max; + more_or_less = "at most"; + } + if (exact) { + more_or_less = "exactly"; + } + PyErr_Format(PyExc_TypeError, + "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", + func_name, more_or_less, num_expected, + (num_expected == 1) ? "" : "s", num_found); +} + +/* RaiseDoubleKeywords */ +static void __Pyx_RaiseDoubleKeywordsError( + const char* func_name, + PyObject* kw_name) +{ + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION >= 3 + "%s() got multiple values for keyword argument '%U'", func_name, kw_name); + #else + "%s() got multiple values for keyword argument '%s'", func_name, + PyString_AsString(kw_name)); + #endif +} + +/* ParseKeywords */ +static int __Pyx_ParseOptionalKeywords( + PyObject *kwds, + PyObject *const *kwvalues, + PyObject **argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + const char* function_name) +{ + PyObject *key = 0, *value = 0; + Py_ssize_t pos = 0; + PyObject*** name; + PyObject*** first_kw_arg = argnames + num_pos_args; + int kwds_is_tuple = CYTHON_METH_FASTCALL && likely(PyTuple_Check(kwds)); + while (1) { + Py_XDECREF(key); key = NULL; + Py_XDECREF(value); value = NULL; + if (kwds_is_tuple) { + Py_ssize_t size; +#if CYTHON_ASSUME_SAFE_MACROS + size = PyTuple_GET_SIZE(kwds); +#else + size = PyTuple_Size(kwds); + if (size < 0) goto bad; +#endif + if (pos >= size) break; +#if CYTHON_AVOID_BORROWED_REFS + key = __Pyx_PySequence_ITEM(kwds, pos); + if (!key) goto bad; +#elif CYTHON_ASSUME_SAFE_MACROS + key = PyTuple_GET_ITEM(kwds, pos); +#else + key = PyTuple_GetItem(kwds, pos); + if (!key) goto bad; +#endif + value = kwvalues[pos]; + pos++; + } + else + { + if (!PyDict_Next(kwds, &pos, &key, &value)) break; +#if CYTHON_AVOID_BORROWED_REFS + Py_INCREF(key); +#endif + } + name = first_kw_arg; + while (*name && (**name != key)) name++; + if (*name) { + values[name-argnames] = value; +#if CYTHON_AVOID_BORROWED_REFS + Py_INCREF(value); + Py_DECREF(key); +#endif + key = NULL; + value = NULL; + continue; + } +#if !CYTHON_AVOID_BORROWED_REFS + Py_INCREF(key); +#endif + Py_INCREF(value); + name = first_kw_arg; + #if PY_MAJOR_VERSION < 3 + if (likely(PyString_Check(key))) { + while (*name) { + if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) + && _PyString_Eq(**name, key)) { + values[name-argnames] = value; +#if CYTHON_AVOID_BORROWED_REFS + value = NULL; +#endif + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + if ((**argname == key) || ( + (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) + && _PyString_Eq(**argname, key))) { + goto arg_passed_twice; + } + argname++; + } + } + } else + #endif + if (likely(PyUnicode_Check(key))) { + while (*name) { + int cmp = ( + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (__Pyx_PyUnicode_GET_LENGTH(**name) != __Pyx_PyUnicode_GET_LENGTH(key)) ? 1 : + #endif + PyUnicode_Compare(**name, key) + ); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) { + values[name-argnames] = value; +#if CYTHON_AVOID_BORROWED_REFS + value = NULL; +#endif + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + int cmp = (**argname == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (__Pyx_PyUnicode_GET_LENGTH(**argname) != __Pyx_PyUnicode_GET_LENGTH(key)) ? 1 : + #endif + PyUnicode_Compare(**argname, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) goto arg_passed_twice; + argname++; + } + } + } else + goto invalid_keyword_type; + if (kwds2) { + if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; + } else { + goto invalid_keyword; + } + } + Py_XDECREF(key); + Py_XDECREF(value); + return 0; +arg_passed_twice: + __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; +invalid_keyword_type: + PyErr_Format(PyExc_TypeError, + "%.200s() keywords must be strings", function_name); + goto bad; +invalid_keyword: + #if PY_MAJOR_VERSION < 3 + PyErr_Format(PyExc_TypeError, + "%.200s() got an unexpected keyword argument '%.200s'", + function_name, PyString_AsString(key)); + #else + PyErr_Format(PyExc_TypeError, + "%s() got an unexpected keyword argument '%U'", + function_name, key); + #endif +bad: + Py_XDECREF(key); + Py_XDECREF(value); + return -1; +} + +/* PyDictVersioning */ +#if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj) { + PyObject *dict = Py_TYPE(obj)->tp_dict; + return likely(dict) ? __PYX_GET_DICT_VERSION(dict) : 0; +} +static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj) { + PyObject **dictptr = NULL; + Py_ssize_t offset = Py_TYPE(obj)->tp_dictoffset; + if (offset) { +#if CYTHON_COMPILING_IN_CPYTHON + dictptr = (likely(offset > 0)) ? (PyObject **) ((char *)obj + offset) : _PyObject_GetDictPtr(obj); +#else + dictptr = _PyObject_GetDictPtr(obj); +#endif + } + return (dictptr && *dictptr) ? __PYX_GET_DICT_VERSION(*dictptr) : 0; +} +static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version) { + PyObject *dict = Py_TYPE(obj)->tp_dict; + if (unlikely(!dict) || unlikely(tp_dict_version != __PYX_GET_DICT_VERSION(dict))) + return 0; + return obj_dict_version == __Pyx_get_object_dict_version(obj); +} +#endif + +/* GetModuleGlobalName */ +#if CYTHON_USE_DICT_VERSIONS +static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value) +#else +static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name) +#endif +{ + PyObject *result; +#if !CYTHON_AVOID_BORROWED_REFS +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030500A1 && PY_VERSION_HEX < 0x030d0000 + result = _PyDict_GetItem_KnownHash(__pyx_d, name, ((PyASCIIObject *) name)->hash); + __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) + if (likely(result)) { + return __Pyx_NewRef(result); + } else if (unlikely(PyErr_Occurred())) { + return NULL; + } +#elif CYTHON_COMPILING_IN_LIMITED_API + if (unlikely(!__pyx_m)) { + return NULL; + } + result = PyObject_GetAttr(__pyx_m, name); + if (likely(result)) { + return result; + } +#else + result = PyDict_GetItem(__pyx_d, name); + __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) + if (likely(result)) { + return __Pyx_NewRef(result); + } +#endif +#else + result = PyObject_GetItem(__pyx_d, name); + __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) + if (likely(result)) { + return __Pyx_NewRef(result); + } + PyErr_Clear(); +#endif + return __Pyx_GetBuiltinName(name); +} + +/* RaiseUnexpectedTypeError */ +static int +__Pyx_RaiseUnexpectedTypeError(const char *expected, PyObject *obj) +{ + __Pyx_TypeName obj_type_name = __Pyx_PyType_GetName(Py_TYPE(obj)); + PyErr_Format(PyExc_TypeError, "Expected %s, got " __Pyx_FMT_TYPENAME, + expected, obj_type_name); + __Pyx_DECREF_TypeName(obj_type_name); + return 0; +} + +/* UnpackUnboundCMethod */ +static PyObject *__Pyx_SelflessCall(PyObject *method, PyObject *args, PyObject *kwargs) { + PyObject *result; + PyObject *selfless_args = PyTuple_GetSlice(args, 1, PyTuple_Size(args)); + if (unlikely(!selfless_args)) return NULL; + result = PyObject_Call(method, selfless_args, kwargs); + Py_DECREF(selfless_args); + return result; +} +static PyMethodDef __Pyx_UnboundCMethod_Def = { + "CythonUnboundCMethod", + __PYX_REINTERPRET_FUNCION(PyCFunction, __Pyx_SelflessCall), + METH_VARARGS | METH_KEYWORDS, + NULL +}; +static int __Pyx_TryUnpackUnboundCMethod(__Pyx_CachedCFunction* target) { + PyObject *method; + method = __Pyx_PyObject_GetAttrStr(target->type, *target->method_name); + if (unlikely(!method)) + return -1; + target->method = method; +#if CYTHON_COMPILING_IN_CPYTHON + #if PY_MAJOR_VERSION >= 3 + if (likely(__Pyx_TypeCheck(method, &PyMethodDescr_Type))) + #else + if (likely(!__Pyx_CyOrPyCFunction_Check(method))) + #endif + { + PyMethodDescrObject *descr = (PyMethodDescrObject*) method; + target->func = descr->d_method->ml_meth; + target->flag = descr->d_method->ml_flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_STACKLESS); + } else +#endif +#if CYTHON_COMPILING_IN_PYPY +#else + if (PyCFunction_Check(method)) +#endif + { + PyObject *self; + int self_found; +#if CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_PYPY + self = PyObject_GetAttrString(method, "__self__"); + if (!self) { + PyErr_Clear(); + } +#else + self = PyCFunction_GET_SELF(method); +#endif + self_found = (self && self != Py_None); +#if CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_PYPY + Py_XDECREF(self); +#endif + if (self_found) { + PyObject *unbound_method = PyCFunction_New(&__Pyx_UnboundCMethod_Def, method); + if (unlikely(!unbound_method)) return -1; + Py_DECREF(method); + target->method = unbound_method; + } + } + return 0; +} + +/* CallUnboundCMethod0 */ +static PyObject* __Pyx__CallUnboundCMethod0(__Pyx_CachedCFunction* cfunc, PyObject* self) { + PyObject *args, *result = NULL; + if (unlikely(!cfunc->method) && unlikely(__Pyx_TryUnpackUnboundCMethod(cfunc) < 0)) return NULL; +#if CYTHON_ASSUME_SAFE_MACROS + args = PyTuple_New(1); + if (unlikely(!args)) goto bad; + Py_INCREF(self); + PyTuple_SET_ITEM(args, 0, self); +#else + args = PyTuple_Pack(1, self); + if (unlikely(!args)) goto bad; +#endif + result = __Pyx_PyObject_Call(cfunc->method, args, NULL); + Py_DECREF(args); +bad: + return result; +} + +/* py_dict_items */ +static CYTHON_INLINE PyObject* __Pyx_PyDict_Items(PyObject* d) { + if (PY_MAJOR_VERSION >= 3) + return __Pyx_CallUnboundCMethod0(&__pyx_umethod_PyDict_Type_items, d); + else + return PyDict_Items(d); +} + +/* RaiseTooManyValuesToUnpack */ +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { + PyErr_Format(PyExc_ValueError, + "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); +} + +/* RaiseNeedMoreValuesToUnpack */ +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { + PyErr_Format(PyExc_ValueError, + "need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack", + index, (index == 1) ? "" : "s"); +} + +/* IterFinish */ +static CYTHON_INLINE int __Pyx_IterFinish(void) { + PyObject* exc_type; + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + exc_type = __Pyx_PyErr_CurrentExceptionType(); + if (unlikely(exc_type)) { + if (unlikely(!__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) + return -1; + __Pyx_PyErr_Clear(); + return 0; + } + return 0; +} + +/* UnpackItemEndCheck */ +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected) { + if (unlikely(retval)) { + Py_DECREF(retval); + __Pyx_RaiseTooManyValuesError(expected); + return -1; + } + return __Pyx_IterFinish(); +} + +/* KeywordStringCheck */ +static int __Pyx_CheckKeywordStrings( + PyObject *kw, + const char* function_name, + int kw_allowed) +{ + PyObject* key = 0; + Py_ssize_t pos = 0; +#if CYTHON_COMPILING_IN_PYPY + if (!kw_allowed && PyDict_Next(kw, &pos, &key, 0)) + goto invalid_keyword; + return 1; +#else + if (CYTHON_METH_FASTCALL && likely(PyTuple_Check(kw))) { + Py_ssize_t kwsize; +#if CYTHON_ASSUME_SAFE_MACROS + kwsize = PyTuple_GET_SIZE(kw); +#else + kwsize = PyTuple_Size(kw); + if (kwsize < 0) return 0; +#endif + if (unlikely(kwsize == 0)) + return 1; + if (!kw_allowed) { +#if CYTHON_ASSUME_SAFE_MACROS + key = PyTuple_GET_ITEM(kw, 0); +#else + key = PyTuple_GetItem(kw, pos); + if (!key) return 0; +#endif + goto invalid_keyword; + } +#if PY_VERSION_HEX < 0x03090000 + for (pos = 0; pos < kwsize; pos++) { +#if CYTHON_ASSUME_SAFE_MACROS + key = PyTuple_GET_ITEM(kw, pos); +#else + key = PyTuple_GetItem(kw, pos); + if (!key) return 0; +#endif + if (unlikely(!PyUnicode_Check(key))) + goto invalid_keyword_type; + } +#endif + return 1; + } + while (PyDict_Next(kw, &pos, &key, 0)) { + #if PY_MAJOR_VERSION < 3 + if (unlikely(!PyString_Check(key))) + #endif + if (unlikely(!PyUnicode_Check(key))) + goto invalid_keyword_type; + } + if (!kw_allowed && unlikely(key)) + goto invalid_keyword; + return 1; +invalid_keyword_type: + PyErr_Format(PyExc_TypeError, + "%.200s() keywords must be strings", function_name); + return 0; +#endif +invalid_keyword: + #if PY_MAJOR_VERSION < 3 + PyErr_Format(PyExc_TypeError, + "%.200s() got an unexpected keyword argument '%.200s'", + function_name, PyString_AsString(key)); + #else + PyErr_Format(PyExc_TypeError, + "%s() got an unexpected keyword argument '%U'", + function_name, key); + #endif + return 0; +} + +/* RaiseKeywordRequired */ +static void __Pyx_RaiseKeywordRequired(const char* func_name, PyObject* kw_name) { + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION >= 3 + "%s() needs keyword-only argument %U", func_name, kw_name); + #else + "%s() needs keyword-only argument %s", func_name, + PyString_AS_STRING(kw_name)); + #endif +} + +/* PyObjectLookupSpecial */ +#if CYTHON_USE_PYTYPE_LOOKUP && CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE PyObject* __Pyx__PyObject_LookupSpecial(PyObject* obj, PyObject* attr_name, int with_error) { + PyObject *res; + PyTypeObject *tp = Py_TYPE(obj); +#if PY_MAJOR_VERSION < 3 + if (unlikely(PyInstance_Check(obj))) + return with_error ? __Pyx_PyObject_GetAttrStr(obj, attr_name) : __Pyx_PyObject_GetAttrStrNoError(obj, attr_name); +#endif + res = _PyType_Lookup(tp, attr_name); + if (likely(res)) { + descrgetfunc f = Py_TYPE(res)->tp_descr_get; + if (!f) { + Py_INCREF(res); + } else { + res = f(res, obj, (PyObject *)tp); + } + } else if (with_error) { + PyErr_SetObject(PyExc_AttributeError, attr_name); + } + return res; +} +#endif + +/* GetTopmostException */ +#if CYTHON_USE_EXC_INFO_STACK && CYTHON_FAST_THREAD_STATE +static _PyErr_StackItem * +__Pyx_PyErr_GetTopmostException(PyThreadState *tstate) +{ + _PyErr_StackItem *exc_info = tstate->exc_info; + while ((exc_info->exc_value == NULL || exc_info->exc_value == Py_None) && + exc_info->previous_item != NULL) + { + exc_info = exc_info->previous_item; + } + return exc_info; +} +#endif + +/* SaveResetException */ +#if CYTHON_FAST_THREAD_STATE +static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { + #if CYTHON_USE_EXC_INFO_STACK && PY_VERSION_HEX >= 0x030B00a4 + _PyErr_StackItem *exc_info = __Pyx_PyErr_GetTopmostException(tstate); + PyObject *exc_value = exc_info->exc_value; + if (exc_value == NULL || exc_value == Py_None) { + *value = NULL; + *type = NULL; + *tb = NULL; + } else { + *value = exc_value; + Py_INCREF(*value); + *type = (PyObject*) Py_TYPE(exc_value); + Py_INCREF(*type); + *tb = PyException_GetTraceback(exc_value); + } + #elif CYTHON_USE_EXC_INFO_STACK + _PyErr_StackItem *exc_info = __Pyx_PyErr_GetTopmostException(tstate); + *type = exc_info->exc_type; + *value = exc_info->exc_value; + *tb = exc_info->exc_traceback; + Py_XINCREF(*type); + Py_XINCREF(*value); + Py_XINCREF(*tb); + #else + *type = tstate->exc_type; + *value = tstate->exc_value; + *tb = tstate->exc_traceback; + Py_XINCREF(*type); + Py_XINCREF(*value); + Py_XINCREF(*tb); + #endif +} +static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { + #if CYTHON_USE_EXC_INFO_STACK && PY_VERSION_HEX >= 0x030B00a4 + _PyErr_StackItem *exc_info = tstate->exc_info; + PyObject *tmp_value = exc_info->exc_value; + exc_info->exc_value = value; + Py_XDECREF(tmp_value); + Py_XDECREF(type); + Py_XDECREF(tb); + #else + PyObject *tmp_type, *tmp_value, *tmp_tb; + #if CYTHON_USE_EXC_INFO_STACK + _PyErr_StackItem *exc_info = tstate->exc_info; + tmp_type = exc_info->exc_type; + tmp_value = exc_info->exc_value; + tmp_tb = exc_info->exc_traceback; + exc_info->exc_type = type; + exc_info->exc_value = value; + exc_info->exc_traceback = tb; + #else + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = type; + tstate->exc_value = value; + tstate->exc_traceback = tb; + #endif + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); + #endif +} +#endif + +/* GetException */ +#if CYTHON_FAST_THREAD_STATE +static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) +#else +static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) +#endif +{ + PyObject *local_type = NULL, *local_value, *local_tb = NULL; +#if CYTHON_FAST_THREAD_STATE + PyObject *tmp_type, *tmp_value, *tmp_tb; + #if PY_VERSION_HEX >= 0x030C00A6 + local_value = tstate->current_exception; + tstate->current_exception = 0; + if (likely(local_value)) { + local_type = (PyObject*) Py_TYPE(local_value); + Py_INCREF(local_type); + local_tb = PyException_GetTraceback(local_value); + } + #else + local_type = tstate->curexc_type; + local_value = tstate->curexc_value; + local_tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; + #endif +#else + PyErr_Fetch(&local_type, &local_value, &local_tb); +#endif + PyErr_NormalizeException(&local_type, &local_value, &local_tb); +#if CYTHON_FAST_THREAD_STATE && PY_VERSION_HEX >= 0x030C00A6 + if (unlikely(tstate->current_exception)) +#elif CYTHON_FAST_THREAD_STATE + if (unlikely(tstate->curexc_type)) +#else + if (unlikely(PyErr_Occurred())) +#endif + goto bad; + #if PY_MAJOR_VERSION >= 3 + if (local_tb) { + if (unlikely(PyException_SetTraceback(local_value, local_tb) < 0)) + goto bad; + } + #endif + Py_XINCREF(local_tb); + Py_XINCREF(local_type); + Py_XINCREF(local_value); + *type = local_type; + *value = local_value; + *tb = local_tb; +#if CYTHON_FAST_THREAD_STATE + #if CYTHON_USE_EXC_INFO_STACK + { + _PyErr_StackItem *exc_info = tstate->exc_info; + #if PY_VERSION_HEX >= 0x030B00a4 + tmp_value = exc_info->exc_value; + exc_info->exc_value = local_value; + tmp_type = NULL; + tmp_tb = NULL; + Py_XDECREF(local_type); + Py_XDECREF(local_tb); + #else + tmp_type = exc_info->exc_type; + tmp_value = exc_info->exc_value; + tmp_tb = exc_info->exc_traceback; + exc_info->exc_type = local_type; + exc_info->exc_value = local_value; + exc_info->exc_traceback = local_tb; + #endif + } + #else + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = local_type; + tstate->exc_value = local_value; + tstate->exc_traceback = local_tb; + #endif + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#else + PyErr_SetExcInfo(local_type, local_value, local_tb); +#endif + return 0; +bad: + *type = 0; + *value = 0; + *tb = 0; + Py_XDECREF(local_type); + Py_XDECREF(local_value); + Py_XDECREF(local_tb); + return -1; +} + +/* RaiseException */ +#if PY_MAJOR_VERSION < 3 +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { + __Pyx_PyThreadState_declare + CYTHON_UNUSED_VAR(cause); + Py_XINCREF(type); + if (!value || value == Py_None) + value = NULL; + else + Py_INCREF(value); + if (!tb || tb == Py_None) + tb = NULL; + else { + Py_INCREF(tb); + if (!PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto raise_error; + } + } + if (PyType_Check(type)) { +#if CYTHON_COMPILING_IN_PYPY + if (!value) { + Py_INCREF(Py_None); + value = Py_None; + } +#endif + PyErr_NormalizeException(&type, &value, &tb); + } else { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto raise_error; + } + value = type; + type = (PyObject*) Py_TYPE(type); + Py_INCREF(type); + if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto raise_error; + } + } + __Pyx_PyThreadState_assign + __Pyx_ErrRestore(type, value, tb); + return; +raise_error: + Py_XDECREF(value); + Py_XDECREF(type); + Py_XDECREF(tb); + return; +} +#else +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { + PyObject* owned_instance = NULL; + if (tb == Py_None) { + tb = 0; + } else if (tb && !PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto bad; + } + if (value == Py_None) + value = 0; + if (PyExceptionInstance_Check(type)) { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto bad; + } + value = type; + type = (PyObject*) Py_TYPE(value); + } else if (PyExceptionClass_Check(type)) { + PyObject *instance_class = NULL; + if (value && PyExceptionInstance_Check(value)) { + instance_class = (PyObject*) Py_TYPE(value); + if (instance_class != type) { + int is_subclass = PyObject_IsSubclass(instance_class, type); + if (!is_subclass) { + instance_class = NULL; + } else if (unlikely(is_subclass == -1)) { + goto bad; + } else { + type = instance_class; + } + } + } + if (!instance_class) { + PyObject *args; + if (!value) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } else + args = PyTuple_Pack(1, value); + if (!args) + goto bad; + owned_instance = PyObject_Call(type, args, NULL); + Py_DECREF(args); + if (!owned_instance) + goto bad; + value = owned_instance; + if (!PyExceptionInstance_Check(value)) { + PyErr_Format(PyExc_TypeError, + "calling %R should have returned an instance of " + "BaseException, not %R", + type, Py_TYPE(value)); + goto bad; + } + } + } else { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto bad; + } + if (cause) { + PyObject *fixed_cause; + if (cause == Py_None) { + fixed_cause = NULL; + } else if (PyExceptionClass_Check(cause)) { + fixed_cause = PyObject_CallObject(cause, NULL); + if (fixed_cause == NULL) + goto bad; + } else if (PyExceptionInstance_Check(cause)) { + fixed_cause = cause; + Py_INCREF(fixed_cause); + } else { + PyErr_SetString(PyExc_TypeError, + "exception causes must derive from " + "BaseException"); + goto bad; + } + PyException_SetCause(value, fixed_cause); + } + PyErr_SetObject(type, value); + if (tb) { + #if PY_VERSION_HEX >= 0x030C00A6 + PyException_SetTraceback(value, tb); + #elif CYTHON_FAST_THREAD_STATE + PyThreadState *tstate = __Pyx_PyThreadState_Current; + PyObject* tmp_tb = tstate->curexc_traceback; + if (tb != tmp_tb) { + Py_INCREF(tb); + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_tb); + } +#else + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyErr_Fetch(&tmp_type, &tmp_value, &tmp_tb); + Py_INCREF(tb); + PyErr_Restore(tmp_type, tmp_value, tb); + Py_XDECREF(tmp_tb); +#endif + } +bad: + Py_XDECREF(owned_instance); + return; +} +#endif + +/* CIntToDigits */ +static const char DIGIT_PAIRS_10[2*10*10+1] = { + "00010203040506070809" + "10111213141516171819" + "20212223242526272829" + "30313233343536373839" + "40414243444546474849" + "50515253545556575859" + "60616263646566676869" + "70717273747576777879" + "80818283848586878889" + "90919293949596979899" +}; +static const char DIGIT_PAIRS_8[2*8*8+1] = { + "0001020304050607" + "1011121314151617" + "2021222324252627" + "3031323334353637" + "4041424344454647" + "5051525354555657" + "6061626364656667" + "7071727374757677" +}; +static const char DIGITS_HEX[2*16+1] = { + "0123456789abcdef" + "0123456789ABCDEF" +}; + +/* BuildPyUnicode */ +static PyObject* __Pyx_PyUnicode_BuildFromAscii(Py_ssize_t ulength, char* chars, int clength, + int prepend_sign, char padding_char) { + PyObject *uval; + Py_ssize_t uoffset = ulength - clength; +#if CYTHON_USE_UNICODE_INTERNALS + Py_ssize_t i; +#if CYTHON_PEP393_ENABLED + void *udata; + uval = PyUnicode_New(ulength, 127); + if (unlikely(!uval)) return NULL; + udata = PyUnicode_DATA(uval); +#else + Py_UNICODE *udata; + uval = PyUnicode_FromUnicode(NULL, ulength); + if (unlikely(!uval)) return NULL; + udata = PyUnicode_AS_UNICODE(uval); +#endif + if (uoffset > 0) { + i = 0; + if (prepend_sign) { + __Pyx_PyUnicode_WRITE(PyUnicode_1BYTE_KIND, udata, 0, '-'); + i++; + } + for (; i < uoffset; i++) { + __Pyx_PyUnicode_WRITE(PyUnicode_1BYTE_KIND, udata, i, padding_char); + } + } + for (i=0; i < clength; i++) { + __Pyx_PyUnicode_WRITE(PyUnicode_1BYTE_KIND, udata, uoffset+i, chars[i]); + } +#else + { + PyObject *sign = NULL, *padding = NULL; + uval = NULL; + if (uoffset > 0) { + prepend_sign = !!prepend_sign; + if (uoffset > prepend_sign) { + padding = PyUnicode_FromOrdinal(padding_char); + if (likely(padding) && uoffset > prepend_sign + 1) { + PyObject *tmp; + PyObject *repeat = PyInt_FromSsize_t(uoffset - prepend_sign); + if (unlikely(!repeat)) goto done_or_error; + tmp = PyNumber_Multiply(padding, repeat); + Py_DECREF(repeat); + Py_DECREF(padding); + padding = tmp; + } + if (unlikely(!padding)) goto done_or_error; + } + if (prepend_sign) { + sign = PyUnicode_FromOrdinal('-'); + if (unlikely(!sign)) goto done_or_error; + } + } + uval = PyUnicode_DecodeASCII(chars, clength, NULL); + if (likely(uval) && padding) { + PyObject *tmp = PyNumber_Add(padding, uval); + Py_DECREF(uval); + uval = tmp; + } + if (likely(uval) && sign) { + PyObject *tmp = PyNumber_Add(sign, uval); + Py_DECREF(uval); + uval = tmp; + } +done_or_error: + Py_XDECREF(padding); + Py_XDECREF(sign); + } +#endif + return uval; +} + +/* CIntToPyUnicode */ +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_From_Py_ssize_t(Py_ssize_t value, Py_ssize_t width, char padding_char, char format_char) { + char digits[sizeof(Py_ssize_t)*3+2]; + char *dpos, *end = digits + sizeof(Py_ssize_t)*3+2; + const char *hex_digits = DIGITS_HEX; + Py_ssize_t length, ulength; + int prepend_sign, last_one_off; + Py_ssize_t remaining; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const Py_ssize_t neg_one = (Py_ssize_t) -1, const_zero = (Py_ssize_t) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (format_char == 'X') { + hex_digits += 16; + format_char = 'x'; + } + remaining = value; + last_one_off = 0; + dpos = end; + do { + int digit_pos; + switch (format_char) { + case 'o': + digit_pos = abs((int)(remaining % (8*8))); + remaining = (Py_ssize_t) (remaining / (8*8)); + dpos -= 2; + memcpy(dpos, DIGIT_PAIRS_8 + digit_pos * 2, 2); + last_one_off = (digit_pos < 8); + break; + case 'd': + digit_pos = abs((int)(remaining % (10*10))); + remaining = (Py_ssize_t) (remaining / (10*10)); + dpos -= 2; + memcpy(dpos, DIGIT_PAIRS_10 + digit_pos * 2, 2); + last_one_off = (digit_pos < 10); + break; + case 'x': + *(--dpos) = hex_digits[abs((int)(remaining % 16))]; + remaining = (Py_ssize_t) (remaining / 16); + break; + default: + assert(0); + break; + } + } while (unlikely(remaining != 0)); + assert(!last_one_off || *dpos == '0'); + dpos += last_one_off; + length = end - dpos; + ulength = length; + prepend_sign = 0; + if (!is_unsigned && value <= neg_one) { + if (padding_char == ' ' || width <= length + 1) { + *(--dpos) = '-'; + ++length; + } else { + prepend_sign = 1; + } + ++ulength; + } + if (width > ulength) { + ulength = width; + } + if (ulength == 1) { + return PyUnicode_FromOrdinal(*dpos); + } + return __Pyx_PyUnicode_BuildFromAscii(ulength, dpos, (int) length, prepend_sign, padding_char); +} + +/* JoinPyUnicode */ +static PyObject* __Pyx_PyUnicode_Join(PyObject* value_tuple, Py_ssize_t value_count, Py_ssize_t result_ulength, + Py_UCS4 max_char) { +#if CYTHON_USE_UNICODE_INTERNALS && CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + PyObject *result_uval; + int result_ukind, kind_shift; + Py_ssize_t i, char_pos; + void *result_udata; + CYTHON_MAYBE_UNUSED_VAR(max_char); +#if CYTHON_PEP393_ENABLED + result_uval = PyUnicode_New(result_ulength, max_char); + if (unlikely(!result_uval)) return NULL; + result_ukind = (max_char <= 255) ? PyUnicode_1BYTE_KIND : (max_char <= 65535) ? PyUnicode_2BYTE_KIND : PyUnicode_4BYTE_KIND; + kind_shift = (result_ukind == PyUnicode_4BYTE_KIND) ? 2 : result_ukind - 1; + result_udata = PyUnicode_DATA(result_uval); +#else + result_uval = PyUnicode_FromUnicode(NULL, result_ulength); + if (unlikely(!result_uval)) return NULL; + result_ukind = sizeof(Py_UNICODE); + kind_shift = (result_ukind == 4) ? 2 : result_ukind - 1; + result_udata = PyUnicode_AS_UNICODE(result_uval); +#endif + assert(kind_shift == 2 || kind_shift == 1 || kind_shift == 0); + char_pos = 0; + for (i=0; i < value_count; i++) { + int ukind; + Py_ssize_t ulength; + void *udata; + PyObject *uval = PyTuple_GET_ITEM(value_tuple, i); + if (unlikely(__Pyx_PyUnicode_READY(uval))) + goto bad; + ulength = __Pyx_PyUnicode_GET_LENGTH(uval); + if (unlikely(!ulength)) + continue; + if (unlikely((PY_SSIZE_T_MAX >> kind_shift) - ulength < char_pos)) + goto overflow; + ukind = __Pyx_PyUnicode_KIND(uval); + udata = __Pyx_PyUnicode_DATA(uval); + if (!CYTHON_PEP393_ENABLED || ukind == result_ukind) { + memcpy((char *)result_udata + (char_pos << kind_shift), udata, (size_t) (ulength << kind_shift)); + } else { + #if PY_VERSION_HEX >= 0x030d0000 + if (unlikely(PyUnicode_CopyCharacters(result_uval, char_pos, uval, 0, ulength) < 0)) goto bad; + #elif CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030300F0 || defined(_PyUnicode_FastCopyCharacters) + _PyUnicode_FastCopyCharacters(result_uval, char_pos, uval, 0, ulength); + #else + Py_ssize_t j; + for (j=0; j < ulength; j++) { + Py_UCS4 uchar = __Pyx_PyUnicode_READ(ukind, udata, j); + __Pyx_PyUnicode_WRITE(result_ukind, result_udata, char_pos+j, uchar); + } + #endif + } + char_pos += ulength; + } + return result_uval; +overflow: + PyErr_SetString(PyExc_OverflowError, "join() result is too long for a Python string"); +bad: + Py_DECREF(result_uval); + return NULL; +#else + CYTHON_UNUSED_VAR(max_char); + CYTHON_UNUSED_VAR(result_ulength); + CYTHON_UNUSED_VAR(value_count); + return PyUnicode_Join(__pyx_empty_unicode, value_tuple); +#endif +} + +/* PyObjectCall2Args */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2) { + PyObject *args[3] = {NULL, arg1, arg2}; + return __Pyx_PyObject_FastCall(function, args+1, 2 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET); +} + +/* PyObjectGetMethod */ +static int __Pyx_PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method) { + PyObject *attr; +#if CYTHON_UNPACK_METHODS && CYTHON_COMPILING_IN_CPYTHON && CYTHON_USE_PYTYPE_LOOKUP + __Pyx_TypeName type_name; + PyTypeObject *tp = Py_TYPE(obj); + PyObject *descr; + descrgetfunc f = NULL; + PyObject **dictptr, *dict; + int meth_found = 0; + assert (*method == NULL); + if (unlikely(tp->tp_getattro != PyObject_GenericGetAttr)) { + attr = __Pyx_PyObject_GetAttrStr(obj, name); + goto try_unpack; + } + if (unlikely(tp->tp_dict == NULL) && unlikely(PyType_Ready(tp) < 0)) { + return 0; + } + descr = _PyType_Lookup(tp, name); + if (likely(descr != NULL)) { + Py_INCREF(descr); +#if defined(Py_TPFLAGS_METHOD_DESCRIPTOR) && Py_TPFLAGS_METHOD_DESCRIPTOR + if (__Pyx_PyType_HasFeature(Py_TYPE(descr), Py_TPFLAGS_METHOD_DESCRIPTOR)) +#elif PY_MAJOR_VERSION >= 3 + #ifdef __Pyx_CyFunction_USED + if (likely(PyFunction_Check(descr) || __Pyx_IS_TYPE(descr, &PyMethodDescr_Type) || __Pyx_CyFunction_Check(descr))) + #else + if (likely(PyFunction_Check(descr) || __Pyx_IS_TYPE(descr, &PyMethodDescr_Type))) + #endif +#else + #ifdef __Pyx_CyFunction_USED + if (likely(PyFunction_Check(descr) || __Pyx_CyFunction_Check(descr))) + #else + if (likely(PyFunction_Check(descr))) + #endif +#endif + { + meth_found = 1; + } else { + f = Py_TYPE(descr)->tp_descr_get; + if (f != NULL && PyDescr_IsData(descr)) { + attr = f(descr, obj, (PyObject *)Py_TYPE(obj)); + Py_DECREF(descr); + goto try_unpack; + } + } + } + dictptr = _PyObject_GetDictPtr(obj); + if (dictptr != NULL && (dict = *dictptr) != NULL) { + Py_INCREF(dict); + attr = __Pyx_PyDict_GetItemStr(dict, name); + if (attr != NULL) { + Py_INCREF(attr); + Py_DECREF(dict); + Py_XDECREF(descr); + goto try_unpack; + } + Py_DECREF(dict); + } + if (meth_found) { + *method = descr; + return 1; + } + if (f != NULL) { + attr = f(descr, obj, (PyObject *)Py_TYPE(obj)); + Py_DECREF(descr); + goto try_unpack; + } + if (likely(descr != NULL)) { + *method = descr; + return 0; + } + type_name = __Pyx_PyType_GetName(tp); + PyErr_Format(PyExc_AttributeError, +#if PY_MAJOR_VERSION >= 3 + "'" __Pyx_FMT_TYPENAME "' object has no attribute '%U'", + type_name, name); +#else + "'" __Pyx_FMT_TYPENAME "' object has no attribute '%.400s'", + type_name, PyString_AS_STRING(name)); +#endif + __Pyx_DECREF_TypeName(type_name); + return 0; +#else + attr = __Pyx_PyObject_GetAttrStr(obj, name); + goto try_unpack; +#endif +try_unpack: +#if CYTHON_UNPACK_METHODS + if (likely(attr) && PyMethod_Check(attr) && likely(PyMethod_GET_SELF(attr) == obj)) { + PyObject *function = PyMethod_GET_FUNCTION(attr); + Py_INCREF(function); + Py_DECREF(attr); + *method = function; + return 1; + } +#endif + *method = attr; + return 0; +} + +/* PyObjectCallMethod1 */ +#if !(CYTHON_VECTORCALL && __PYX_LIMITED_VERSION_HEX >= 0x030C00A2) +static PyObject* __Pyx__PyObject_CallMethod1(PyObject* method, PyObject* arg) { + PyObject *result = __Pyx_PyObject_CallOneArg(method, arg); + Py_DECREF(method); + return result; +} +#endif +static PyObject* __Pyx_PyObject_CallMethod1(PyObject* obj, PyObject* method_name, PyObject* arg) { +#if CYTHON_VECTORCALL && __PYX_LIMITED_VERSION_HEX >= 0x030C00A2 + PyObject *args[2] = {obj, arg}; + (void) __Pyx_PyObject_GetMethod; + (void) __Pyx_PyObject_CallOneArg; + (void) __Pyx_PyObject_Call2Args; + return PyObject_VectorcallMethod(method_name, args, 2 | PY_VECTORCALL_ARGUMENTS_OFFSET, NULL); +#else + PyObject *method = NULL, *result; + int is_method = __Pyx_PyObject_GetMethod(obj, method_name, &method); + if (likely(is_method)) { + result = __Pyx_PyObject_Call2Args(method, obj, arg); + Py_DECREF(method); + return result; + } + if (unlikely(!method)) return NULL; + return __Pyx__PyObject_CallMethod1(method, arg); +#endif +} + +/* append */ +static CYTHON_INLINE int __Pyx_PyObject_Append(PyObject* L, PyObject* x) { + if (likely(PyList_CheckExact(L))) { + if (unlikely(__Pyx_PyList_Append(L, x) < 0)) return -1; + } else { + PyObject* retval = __Pyx_PyObject_CallMethod1(L, __pyx_n_s_append, x); + if (unlikely(!retval)) + return -1; + Py_DECREF(retval); + } + return 0; +} + +/* CallUnboundCMethod1 */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_CallUnboundCMethod1(__Pyx_CachedCFunction* cfunc, PyObject* self, PyObject* arg) { + if (likely(cfunc->func)) { + int flag = cfunc->flag; + if (flag == METH_O) { + return (*(cfunc->func))(self, arg); + } else if ((PY_VERSION_HEX >= 0x030600B1) && flag == METH_FASTCALL) { + #if PY_VERSION_HEX >= 0x030700A0 + return (*(__Pyx_PyCFunctionFast)(void*)(PyCFunction)cfunc->func)(self, &arg, 1); + #else + return (*(__Pyx_PyCFunctionFastWithKeywords)(void*)(PyCFunction)cfunc->func)(self, &arg, 1, NULL); + #endif + } else if ((PY_VERSION_HEX >= 0x030700A0) && flag == (METH_FASTCALL | METH_KEYWORDS)) { + return (*(__Pyx_PyCFunctionFastWithKeywords)(void*)(PyCFunction)cfunc->func)(self, &arg, 1, NULL); + } + } + return __Pyx__CallUnboundCMethod1(cfunc, self, arg); +} +#endif +static PyObject* __Pyx__CallUnboundCMethod1(__Pyx_CachedCFunction* cfunc, PyObject* self, PyObject* arg){ + PyObject *args, *result = NULL; + if (unlikely(!cfunc->func && !cfunc->method) && unlikely(__Pyx_TryUnpackUnboundCMethod(cfunc) < 0)) return NULL; +#if CYTHON_COMPILING_IN_CPYTHON + if (cfunc->func && (cfunc->flag & METH_VARARGS)) { + args = PyTuple_New(1); + if (unlikely(!args)) goto bad; + Py_INCREF(arg); + PyTuple_SET_ITEM(args, 0, arg); + if (cfunc->flag & METH_KEYWORDS) + result = (*(PyCFunctionWithKeywords)(void*)(PyCFunction)cfunc->func)(self, args, NULL); + else + result = (*cfunc->func)(self, args); + } else { + args = PyTuple_New(2); + if (unlikely(!args)) goto bad; + Py_INCREF(self); + PyTuple_SET_ITEM(args, 0, self); + Py_INCREF(arg); + PyTuple_SET_ITEM(args, 1, arg); + result = __Pyx_PyObject_Call(cfunc->method, args, NULL); + } +#else + args = PyTuple_Pack(2, self, arg); + if (unlikely(!args)) goto bad; + result = __Pyx_PyObject_Call(cfunc->method, args, NULL); +#endif +bad: + Py_XDECREF(args); + return result; +} + +/* CallUnboundCMethod2 */ +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030600B1 +static CYTHON_INLINE PyObject *__Pyx_CallUnboundCMethod2(__Pyx_CachedCFunction *cfunc, PyObject *self, PyObject *arg1, PyObject *arg2) { + if (likely(cfunc->func)) { + PyObject *args[2] = {arg1, arg2}; + if (cfunc->flag == METH_FASTCALL) { + #if PY_VERSION_HEX >= 0x030700A0 + return (*(__Pyx_PyCFunctionFast)(void*)(PyCFunction)cfunc->func)(self, args, 2); + #else + return (*(__Pyx_PyCFunctionFastWithKeywords)(void*)(PyCFunction)cfunc->func)(self, args, 2, NULL); + #endif + } + #if PY_VERSION_HEX >= 0x030700A0 + if (cfunc->flag == (METH_FASTCALL | METH_KEYWORDS)) + return (*(__Pyx_PyCFunctionFastWithKeywords)(void*)(PyCFunction)cfunc->func)(self, args, 2, NULL); + #endif + } + return __Pyx__CallUnboundCMethod2(cfunc, self, arg1, arg2); +} +#endif +static PyObject* __Pyx__CallUnboundCMethod2(__Pyx_CachedCFunction* cfunc, PyObject* self, PyObject* arg1, PyObject* arg2){ + PyObject *args, *result = NULL; + if (unlikely(!cfunc->func && !cfunc->method) && unlikely(__Pyx_TryUnpackUnboundCMethod(cfunc) < 0)) return NULL; +#if CYTHON_COMPILING_IN_CPYTHON + if (cfunc->func && (cfunc->flag & METH_VARARGS)) { + args = PyTuple_New(2); + if (unlikely(!args)) goto bad; + Py_INCREF(arg1); + PyTuple_SET_ITEM(args, 0, arg1); + Py_INCREF(arg2); + PyTuple_SET_ITEM(args, 1, arg2); + if (cfunc->flag & METH_KEYWORDS) + result = (*(PyCFunctionWithKeywords)(void*)(PyCFunction)cfunc->func)(self, args, NULL); + else + result = (*cfunc->func)(self, args); + } else { + args = PyTuple_New(3); + if (unlikely(!args)) goto bad; + Py_INCREF(self); + PyTuple_SET_ITEM(args, 0, self); + Py_INCREF(arg1); + PyTuple_SET_ITEM(args, 1, arg1); + Py_INCREF(arg2); + PyTuple_SET_ITEM(args, 2, arg2); + result = __Pyx_PyObject_Call(cfunc->method, args, NULL); + } +#else + args = PyTuple_Pack(3, self, arg1, arg2); + if (unlikely(!args)) goto bad; + result = __Pyx_PyObject_Call(cfunc->method, args, NULL); +#endif +bad: + Py_XDECREF(args); + return result; +} + +/* dict_getitem_default */ +static PyObject* __Pyx_PyDict_GetItemDefault(PyObject* d, PyObject* key, PyObject* default_value) { + PyObject* value; +#if PY_MAJOR_VERSION >= 3 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07020000) + value = PyDict_GetItemWithError(d, key); + if (unlikely(!value)) { + if (unlikely(PyErr_Occurred())) + return NULL; + value = default_value; + } + Py_INCREF(value); + if ((1)); +#else + if (PyString_CheckExact(key) || PyUnicode_CheckExact(key) || PyInt_CheckExact(key)) { + value = PyDict_GetItem(d, key); + if (unlikely(!value)) { + value = default_value; + } + Py_INCREF(value); + } +#endif + else { + if (default_value == Py_None) + value = __Pyx_CallUnboundCMethod1(&__pyx_umethod_PyDict_Type_get, d, key); + else + value = __Pyx_CallUnboundCMethod2(&__pyx_umethod_PyDict_Type_get, d, key, default_value); + } + return value; +} + +/* DictGetItem */ +#if PY_MAJOR_VERSION >= 3 && !CYTHON_COMPILING_IN_PYPY +static PyObject *__Pyx_PyDict_GetItem(PyObject *d, PyObject* key) { + PyObject *value; + value = PyDict_GetItemWithError(d, key); + if (unlikely(!value)) { + if (!PyErr_Occurred()) { + if (unlikely(PyTuple_Check(key))) { + PyObject* args = PyTuple_Pack(1, key); + if (likely(args)) { + PyErr_SetObject(PyExc_KeyError, args); + Py_DECREF(args); + } + } else { + PyErr_SetObject(PyExc_KeyError, key); + } + } + return NULL; + } + Py_INCREF(value); + return value; +} +#endif + +/* decode_c_bytes */ +static CYTHON_INLINE PyObject* __Pyx_decode_c_bytes( + const char* cstring, Py_ssize_t length, Py_ssize_t start, Py_ssize_t stop, + const char* encoding, const char* errors, + PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) { + if (unlikely((start < 0) | (stop < 0))) { + if (start < 0) { + start += length; + if (start < 0) + start = 0; + } + if (stop < 0) + stop += length; + } + if (stop > length) + stop = length; + if (unlikely(stop <= start)) + return __Pyx_NewRef(__pyx_empty_unicode); + length = stop - start; + cstring += start; + if (decode_func) { + return decode_func(cstring, length, errors); + } else { + return PyUnicode_Decode(cstring, length, encoding, errors); + } +} + +/* FixUpExtensionType */ +#if CYTHON_USE_TYPE_SPECS +static int __Pyx_fix_up_extension_type_from_spec(PyType_Spec *spec, PyTypeObject *type) { +#if PY_VERSION_HEX > 0x030900B1 || CYTHON_COMPILING_IN_LIMITED_API + CYTHON_UNUSED_VAR(spec); + CYTHON_UNUSED_VAR(type); +#else + const PyType_Slot *slot = spec->slots; + while (slot && slot->slot && slot->slot != Py_tp_members) + slot++; + if (slot && slot->slot == Py_tp_members) { + int changed = 0; +#if !(PY_VERSION_HEX <= 0x030900b1 && CYTHON_COMPILING_IN_CPYTHON) + const +#endif + PyMemberDef *memb = (PyMemberDef*) slot->pfunc; + while (memb && memb->name) { + if (memb->name[0] == '_' && memb->name[1] == '_') { +#if PY_VERSION_HEX < 0x030900b1 + if (strcmp(memb->name, "__weaklistoffset__") == 0) { + assert(memb->type == T_PYSSIZET); + assert(memb->flags == READONLY); + type->tp_weaklistoffset = memb->offset; + changed = 1; + } + else if (strcmp(memb->name, "__dictoffset__") == 0) { + assert(memb->type == T_PYSSIZET); + assert(memb->flags == READONLY); + type->tp_dictoffset = memb->offset; + changed = 1; + } +#if CYTHON_METH_FASTCALL + else if (strcmp(memb->name, "__vectorcalloffset__") == 0) { + assert(memb->type == T_PYSSIZET); + assert(memb->flags == READONLY); +#if PY_VERSION_HEX >= 0x030800b4 + type->tp_vectorcall_offset = memb->offset; +#else + type->tp_print = (printfunc) memb->offset; +#endif + changed = 1; + } +#endif +#else + if ((0)); +#endif +#if PY_VERSION_HEX <= 0x030900b1 && CYTHON_COMPILING_IN_CPYTHON + else if (strcmp(memb->name, "__module__") == 0) { + PyObject *descr; + assert(memb->type == T_OBJECT); + assert(memb->flags == 0 || memb->flags == READONLY); + descr = PyDescr_NewMember(type, memb); + if (unlikely(!descr)) + return -1; + if (unlikely(PyDict_SetItem(type->tp_dict, PyDescr_NAME(descr), descr) < 0)) { + Py_DECREF(descr); + return -1; + } + Py_DECREF(descr); + changed = 1; + } +#endif + } + memb++; + } + if (changed) + PyType_Modified(type); + } +#endif + return 0; +} +#endif + +/* PyObjectCallNoArg */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func) { + PyObject *arg[2] = {NULL, NULL}; + return __Pyx_PyObject_FastCall(func, arg + 1, 0 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET); +} + +/* PyObjectCallMethod0 */ +static PyObject* __Pyx_PyObject_CallMethod0(PyObject* obj, PyObject* method_name) { + PyObject *method = NULL, *result = NULL; + int is_method = __Pyx_PyObject_GetMethod(obj, method_name, &method); + if (likely(is_method)) { + result = __Pyx_PyObject_CallOneArg(method, obj); + Py_DECREF(method); + return result; + } + if (unlikely(!method)) goto bad; + result = __Pyx_PyObject_CallNoArg(method); + Py_DECREF(method); +bad: + return result; +} + +/* ValidateBasesTuple */ +#if CYTHON_COMPILING_IN_CPYTHON || CYTHON_COMPILING_IN_LIMITED_API || CYTHON_USE_TYPE_SPECS +static int __Pyx_validate_bases_tuple(const char *type_name, Py_ssize_t dictoffset, PyObject *bases) { + Py_ssize_t i, n; +#if CYTHON_ASSUME_SAFE_MACROS + n = PyTuple_GET_SIZE(bases); +#else + n = PyTuple_Size(bases); + if (n < 0) return -1; +#endif + for (i = 1; i < n; i++) + { +#if CYTHON_AVOID_BORROWED_REFS + PyObject *b0 = PySequence_GetItem(bases, i); + if (!b0) return -1; +#elif CYTHON_ASSUME_SAFE_MACROS + PyObject *b0 = PyTuple_GET_ITEM(bases, i); +#else + PyObject *b0 = PyTuple_GetItem(bases, i); + if (!b0) return -1; +#endif + PyTypeObject *b; +#if PY_MAJOR_VERSION < 3 + if (PyClass_Check(b0)) + { + PyErr_Format(PyExc_TypeError, "base class '%.200s' is an old-style class", + PyString_AS_STRING(((PyClassObject*)b0)->cl_name)); +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(b0); +#endif + return -1; + } +#endif + b = (PyTypeObject*) b0; + if (!__Pyx_PyType_HasFeature(b, Py_TPFLAGS_HEAPTYPE)) + { + __Pyx_TypeName b_name = __Pyx_PyType_GetName(b); + PyErr_Format(PyExc_TypeError, + "base class '" __Pyx_FMT_TYPENAME "' is not a heap type", b_name); + __Pyx_DECREF_TypeName(b_name); +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(b0); +#endif + return -1; + } + if (dictoffset == 0) + { + Py_ssize_t b_dictoffset = 0; +#if CYTHON_USE_TYPE_SLOTS || CYTHON_COMPILING_IN_PYPY + b_dictoffset = b->tp_dictoffset; +#else + PyObject *py_b_dictoffset = PyObject_GetAttrString((PyObject*)b, "__dictoffset__"); + if (!py_b_dictoffset) goto dictoffset_return; + b_dictoffset = PyLong_AsSsize_t(py_b_dictoffset); + Py_DECREF(py_b_dictoffset); + if (b_dictoffset == -1 && PyErr_Occurred()) goto dictoffset_return; +#endif + if (b_dictoffset) { + { + __Pyx_TypeName b_name = __Pyx_PyType_GetName(b); + PyErr_Format(PyExc_TypeError, + "extension type '%.200s' has no __dict__ slot, " + "but base type '" __Pyx_FMT_TYPENAME "' has: " + "either add 'cdef dict __dict__' to the extension type " + "or add '__slots__ = [...]' to the base type", + type_name, b_name); + __Pyx_DECREF_TypeName(b_name); + } +#if !(CYTHON_USE_TYPE_SLOTS || CYTHON_COMPILING_IN_PYPY) + dictoffset_return: +#endif +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(b0); +#endif + return -1; + } + } +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(b0); +#endif + } + return 0; +} +#endif + +/* PyType_Ready */ +static int __Pyx_PyType_Ready(PyTypeObject *t) { +#if CYTHON_USE_TYPE_SPECS || !(CYTHON_COMPILING_IN_CPYTHON || CYTHON_COMPILING_IN_LIMITED_API) || defined(PYSTON_MAJOR_VERSION) + (void)__Pyx_PyObject_CallMethod0; +#if CYTHON_USE_TYPE_SPECS + (void)__Pyx_validate_bases_tuple; +#endif + return PyType_Ready(t); +#else + int r; + PyObject *bases = __Pyx_PyType_GetSlot(t, tp_bases, PyObject*); + if (bases && unlikely(__Pyx_validate_bases_tuple(t->tp_name, t->tp_dictoffset, bases) == -1)) + return -1; +#if PY_VERSION_HEX >= 0x03050000 && !defined(PYSTON_MAJOR_VERSION) + { + int gc_was_enabled; + #if PY_VERSION_HEX >= 0x030A00b1 + gc_was_enabled = PyGC_Disable(); + (void)__Pyx_PyObject_CallMethod0; + #else + PyObject *ret, *py_status; + PyObject *gc = NULL; + #if PY_VERSION_HEX >= 0x030700a1 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM+0 >= 0x07030400) + gc = PyImport_GetModule(__pyx_kp_u_gc); + #endif + if (unlikely(!gc)) gc = PyImport_Import(__pyx_kp_u_gc); + if (unlikely(!gc)) return -1; + py_status = __Pyx_PyObject_CallMethod0(gc, __pyx_kp_u_isenabled); + if (unlikely(!py_status)) { + Py_DECREF(gc); + return -1; + } + gc_was_enabled = __Pyx_PyObject_IsTrue(py_status); + Py_DECREF(py_status); + if (gc_was_enabled > 0) { + ret = __Pyx_PyObject_CallMethod0(gc, __pyx_kp_u_disable); + if (unlikely(!ret)) { + Py_DECREF(gc); + return -1; + } + Py_DECREF(ret); + } else if (unlikely(gc_was_enabled == -1)) { + Py_DECREF(gc); + return -1; + } + #endif + t->tp_flags |= Py_TPFLAGS_HEAPTYPE; +#if PY_VERSION_HEX >= 0x030A0000 + t->tp_flags |= Py_TPFLAGS_IMMUTABLETYPE; +#endif +#else + (void)__Pyx_PyObject_CallMethod0; +#endif + r = PyType_Ready(t); +#if PY_VERSION_HEX >= 0x03050000 && !defined(PYSTON_MAJOR_VERSION) + t->tp_flags &= ~Py_TPFLAGS_HEAPTYPE; + #if PY_VERSION_HEX >= 0x030A00b1 + if (gc_was_enabled) + PyGC_Enable(); + #else + if (gc_was_enabled) { + PyObject *tp, *v, *tb; + PyErr_Fetch(&tp, &v, &tb); + ret = __Pyx_PyObject_CallMethod0(gc, __pyx_kp_u_enable); + if (likely(ret || r == -1)) { + Py_XDECREF(ret); + PyErr_Restore(tp, v, tb); + } else { + Py_XDECREF(tp); + Py_XDECREF(v); + Py_XDECREF(tb); + r = -1; + } + } + Py_DECREF(gc); + #endif + } +#endif + return r; +#endif +} + +/* PyObject_GenericGetAttrNoDict */ +#if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 +static PyObject *__Pyx_RaiseGenericGetAttributeError(PyTypeObject *tp, PyObject *attr_name) { + __Pyx_TypeName type_name = __Pyx_PyType_GetName(tp); + PyErr_Format(PyExc_AttributeError, +#if PY_MAJOR_VERSION >= 3 + "'" __Pyx_FMT_TYPENAME "' object has no attribute '%U'", + type_name, attr_name); +#else + "'" __Pyx_FMT_TYPENAME "' object has no attribute '%.400s'", + type_name, PyString_AS_STRING(attr_name)); +#endif + __Pyx_DECREF_TypeName(type_name); + return NULL; +} +static CYTHON_INLINE PyObject* __Pyx_PyObject_GenericGetAttrNoDict(PyObject* obj, PyObject* attr_name) { + PyObject *descr; + PyTypeObject *tp = Py_TYPE(obj); + if (unlikely(!PyString_Check(attr_name))) { + return PyObject_GenericGetAttr(obj, attr_name); + } + assert(!tp->tp_dictoffset); + descr = _PyType_Lookup(tp, attr_name); + if (unlikely(!descr)) { + return __Pyx_RaiseGenericGetAttributeError(tp, attr_name); + } + Py_INCREF(descr); + #if PY_MAJOR_VERSION < 3 + if (likely(PyType_HasFeature(Py_TYPE(descr), Py_TPFLAGS_HAVE_CLASS))) + #endif + { + descrgetfunc f = Py_TYPE(descr)->tp_descr_get; + if (unlikely(f)) { + PyObject *res = f(descr, obj, (PyObject *)tp); + Py_DECREF(descr); + return res; + } + } + return descr; +} +#endif + +/* PyObject_GenericGetAttr */ +#if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 +static PyObject* __Pyx_PyObject_GenericGetAttr(PyObject* obj, PyObject* attr_name) { + if (unlikely(Py_TYPE(obj)->tp_dictoffset)) { + return PyObject_GenericGetAttr(obj, attr_name); + } + return __Pyx_PyObject_GenericGetAttrNoDict(obj, attr_name); +} +#endif + +/* Import */ +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { + PyObject *module = 0; + PyObject *empty_dict = 0; + PyObject *empty_list = 0; + #if PY_MAJOR_VERSION < 3 + PyObject *py_import; + py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s_import); + if (unlikely(!py_import)) + goto bad; + if (!from_list) { + empty_list = PyList_New(0); + if (unlikely(!empty_list)) + goto bad; + from_list = empty_list; + } + #endif + empty_dict = PyDict_New(); + if (unlikely(!empty_dict)) + goto bad; + { + #if PY_MAJOR_VERSION >= 3 + if (level == -1) { + if (strchr(__Pyx_MODULE_NAME, '.') != NULL) { + module = PyImport_ImportModuleLevelObject( + name, __pyx_d, empty_dict, from_list, 1); + if (unlikely(!module)) { + if (unlikely(!PyErr_ExceptionMatches(PyExc_ImportError))) + goto bad; + PyErr_Clear(); + } + } + level = 0; + } + #endif + if (!module) { + #if PY_MAJOR_VERSION < 3 + PyObject *py_level = PyInt_FromLong(level); + if (unlikely(!py_level)) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, __pyx_d, empty_dict, from_list, py_level, (PyObject *)NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, __pyx_d, empty_dict, from_list, level); + #endif + } + } +bad: + Py_XDECREF(empty_dict); + Py_XDECREF(empty_list); + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(py_import); + #endif + return module; +} + +/* ImportFrom */ +static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name) { + PyObject* value = __Pyx_PyObject_GetAttrStr(module, name); + if (unlikely(!value) && PyErr_ExceptionMatches(PyExc_AttributeError)) { + const char* module_name_str = 0; + PyObject* module_name = 0; + PyObject* module_dot = 0; + PyObject* full_name = 0; + PyErr_Clear(); + module_name_str = PyModule_GetName(module); + if (unlikely(!module_name_str)) { goto modbad; } + module_name = PyUnicode_FromString(module_name_str); + if (unlikely(!module_name)) { goto modbad; } + module_dot = PyUnicode_Concat(module_name, __pyx_kp_u__4); + if (unlikely(!module_dot)) { goto modbad; } + full_name = PyUnicode_Concat(module_dot, name); + if (unlikely(!full_name)) { goto modbad; } + #if PY_VERSION_HEX < 0x030700A1 || (CYTHON_COMPILING_IN_PYPY && PYPY_VERSION_NUM < 0x07030400) + { + PyObject *modules = PyImport_GetModuleDict(); + if (unlikely(!modules)) + goto modbad; + value = PyObject_GetItem(modules, full_name); + } + #else + value = PyImport_GetModule(full_name); + #endif + modbad: + Py_XDECREF(full_name); + Py_XDECREF(module_dot); + Py_XDECREF(module_name); + } + if (unlikely(!value)) { + PyErr_Format(PyExc_ImportError, + #if PY_MAJOR_VERSION < 3 + "cannot import name %.230s", PyString_AS_STRING(name)); + #else + "cannot import name %S", name); + #endif + } + return value; +} + +/* ImportDottedModule */ +#if PY_MAJOR_VERSION >= 3 +static PyObject *__Pyx__ImportDottedModule_Error(PyObject *name, PyObject *parts_tuple, Py_ssize_t count) { + PyObject *partial_name = NULL, *slice = NULL, *sep = NULL; + if (unlikely(PyErr_Occurred())) { + PyErr_Clear(); + } + if (likely(PyTuple_GET_SIZE(parts_tuple) == count)) { + partial_name = name; + } else { + slice = PySequence_GetSlice(parts_tuple, 0, count); + if (unlikely(!slice)) + goto bad; + sep = PyUnicode_FromStringAndSize(".", 1); + if (unlikely(!sep)) + goto bad; + partial_name = PyUnicode_Join(sep, slice); + } + PyErr_Format( +#if PY_MAJOR_VERSION < 3 + PyExc_ImportError, + "No module named '%s'", PyString_AS_STRING(partial_name)); +#else +#if PY_VERSION_HEX >= 0x030600B1 + PyExc_ModuleNotFoundError, +#else + PyExc_ImportError, +#endif + "No module named '%U'", partial_name); +#endif +bad: + Py_XDECREF(sep); + Py_XDECREF(slice); + Py_XDECREF(partial_name); + return NULL; +} +#endif +#if PY_MAJOR_VERSION >= 3 +static PyObject *__Pyx__ImportDottedModule_Lookup(PyObject *name) { + PyObject *imported_module; +#if PY_VERSION_HEX < 0x030700A1 || (CYTHON_COMPILING_IN_PYPY && PYPY_VERSION_NUM < 0x07030400) + PyObject *modules = PyImport_GetModuleDict(); + if (unlikely(!modules)) + return NULL; + imported_module = __Pyx_PyDict_GetItemStr(modules, name); + Py_XINCREF(imported_module); +#else + imported_module = PyImport_GetModule(name); +#endif + return imported_module; +} +#endif +#if PY_MAJOR_VERSION >= 3 +static PyObject *__Pyx_ImportDottedModule_WalkParts(PyObject *module, PyObject *name, PyObject *parts_tuple) { + Py_ssize_t i, nparts; + nparts = PyTuple_GET_SIZE(parts_tuple); + for (i=1; i < nparts && module; i++) { + PyObject *part, *submodule; +#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + part = PyTuple_GET_ITEM(parts_tuple, i); +#else + part = PySequence_ITEM(parts_tuple, i); +#endif + submodule = __Pyx_PyObject_GetAttrStrNoError(module, part); +#if !(CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS) + Py_DECREF(part); +#endif + Py_DECREF(module); + module = submodule; + } + if (unlikely(!module)) { + return __Pyx__ImportDottedModule_Error(name, parts_tuple, i); + } + return module; +} +#endif +static PyObject *__Pyx__ImportDottedModule(PyObject *name, PyObject *parts_tuple) { +#if PY_MAJOR_VERSION < 3 + PyObject *module, *from_list, *star = __pyx_n_s__5; + CYTHON_UNUSED_VAR(parts_tuple); + from_list = PyList_New(1); + if (unlikely(!from_list)) + return NULL; + Py_INCREF(star); + PyList_SET_ITEM(from_list, 0, star); + module = __Pyx_Import(name, from_list, 0); + Py_DECREF(from_list); + return module; +#else + PyObject *imported_module; + PyObject *module = __Pyx_Import(name, NULL, 0); + if (!parts_tuple || unlikely(!module)) + return module; + imported_module = __Pyx__ImportDottedModule_Lookup(name); + if (likely(imported_module)) { + Py_DECREF(module); + return imported_module; + } + PyErr_Clear(); + return __Pyx_ImportDottedModule_WalkParts(module, name, parts_tuple); +#endif +} +static PyObject *__Pyx_ImportDottedModule(PyObject *name, PyObject *parts_tuple) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030400B1 + PyObject *module = __Pyx__ImportDottedModule_Lookup(name); + if (likely(module)) { + PyObject *spec = __Pyx_PyObject_GetAttrStrNoError(module, __pyx_n_s_spec); + if (likely(spec)) { + PyObject *unsafe = __Pyx_PyObject_GetAttrStrNoError(spec, __pyx_n_s_initializing); + if (likely(!unsafe || !__Pyx_PyObject_IsTrue(unsafe))) { + Py_DECREF(spec); + spec = NULL; + } + Py_XDECREF(unsafe); + } + if (likely(!spec)) { + PyErr_Clear(); + return module; + } + Py_DECREF(spec); + Py_DECREF(module); + } else if (PyErr_Occurred()) { + PyErr_Clear(); + } +#endif + return __Pyx__ImportDottedModule(name, parts_tuple); +} + +/* ImportDottedModuleRelFirst */ +static PyObject *__Pyx_ImportDottedModuleRelFirst(PyObject *name, PyObject *parts_tuple) { + PyObject *module; + PyObject *from_list = NULL; +#if PY_MAJOR_VERSION < 3 + PyObject *star = __pyx_n_s__5; + from_list = PyList_New(1); + if (unlikely(!from_list)) + return NULL; + Py_INCREF(star); + PyList_SET_ITEM(from_list, 0, star); +#endif + module = __Pyx_Import(name, from_list, -1); + Py_XDECREF(from_list); + if (module) { + #if PY_MAJOR_VERSION >= 3 + if (parts_tuple) { + module = __Pyx_ImportDottedModule_WalkParts(module, name, parts_tuple); + } + #endif + return module; + } + if (unlikely(!PyErr_ExceptionMatches(PyExc_ImportError))) + return NULL; + PyErr_Clear(); + return __Pyx_ImportDottedModule(name, parts_tuple); +} + +/* FetchSharedCythonModule */ +static PyObject *__Pyx_FetchSharedCythonABIModule(void) { + return __Pyx_PyImport_AddModuleRef((char*) __PYX_ABI_MODULE_NAME); +} + +/* FetchCommonType */ +static int __Pyx_VerifyCachedType(PyObject *cached_type, + const char *name, + Py_ssize_t basicsize, + Py_ssize_t expected_basicsize) { + if (!PyType_Check(cached_type)) { + PyErr_Format(PyExc_TypeError, + "Shared Cython type %.200s is not a type object", name); + return -1; + } + if (basicsize != expected_basicsize) { + PyErr_Format(PyExc_TypeError, + "Shared Cython type %.200s has the wrong size, try recompiling", + name); + return -1; + } + return 0; +} +#if !CYTHON_USE_TYPE_SPECS +static PyTypeObject* __Pyx_FetchCommonType(PyTypeObject* type) { + PyObject* abi_module; + const char* object_name; + PyTypeObject *cached_type = NULL; + abi_module = __Pyx_FetchSharedCythonABIModule(); + if (!abi_module) return NULL; + object_name = strrchr(type->tp_name, '.'); + object_name = object_name ? object_name+1 : type->tp_name; + cached_type = (PyTypeObject*) PyObject_GetAttrString(abi_module, object_name); + if (cached_type) { + if (__Pyx_VerifyCachedType( + (PyObject *)cached_type, + object_name, + cached_type->tp_basicsize, + type->tp_basicsize) < 0) { + goto bad; + } + goto done; + } + if (!PyErr_ExceptionMatches(PyExc_AttributeError)) goto bad; + PyErr_Clear(); + if (PyType_Ready(type) < 0) goto bad; + if (PyObject_SetAttrString(abi_module, object_name, (PyObject *)type) < 0) + goto bad; + Py_INCREF(type); + cached_type = type; +done: + Py_DECREF(abi_module); + return cached_type; +bad: + Py_XDECREF(cached_type); + cached_type = NULL; + goto done; +} +#else +static PyTypeObject *__Pyx_FetchCommonTypeFromSpec(PyObject *module, PyType_Spec *spec, PyObject *bases) { + PyObject *abi_module, *cached_type = NULL; + const char* object_name = strrchr(spec->name, '.'); + object_name = object_name ? object_name+1 : spec->name; + abi_module = __Pyx_FetchSharedCythonABIModule(); + if (!abi_module) return NULL; + cached_type = PyObject_GetAttrString(abi_module, object_name); + if (cached_type) { + Py_ssize_t basicsize; +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *py_basicsize; + py_basicsize = PyObject_GetAttrString(cached_type, "__basicsize__"); + if (unlikely(!py_basicsize)) goto bad; + basicsize = PyLong_AsSsize_t(py_basicsize); + Py_DECREF(py_basicsize); + py_basicsize = 0; + if (unlikely(basicsize == (Py_ssize_t)-1) && PyErr_Occurred()) goto bad; +#else + basicsize = likely(PyType_Check(cached_type)) ? ((PyTypeObject*) cached_type)->tp_basicsize : -1; +#endif + if (__Pyx_VerifyCachedType( + cached_type, + object_name, + basicsize, + spec->basicsize) < 0) { + goto bad; + } + goto done; + } + if (!PyErr_ExceptionMatches(PyExc_AttributeError)) goto bad; + PyErr_Clear(); + CYTHON_UNUSED_VAR(module); + cached_type = __Pyx_PyType_FromModuleAndSpec(abi_module, spec, bases); + if (unlikely(!cached_type)) goto bad; + if (unlikely(__Pyx_fix_up_extension_type_from_spec(spec, (PyTypeObject *) cached_type) < 0)) goto bad; + if (PyObject_SetAttrString(abi_module, object_name, cached_type) < 0) goto bad; +done: + Py_DECREF(abi_module); + assert(cached_type == NULL || PyType_Check(cached_type)); + return (PyTypeObject *) cached_type; +bad: + Py_XDECREF(cached_type); + cached_type = NULL; + goto done; +} +#endif + +/* PyVectorcallFastCallDict */ +#if CYTHON_METH_FASTCALL +static PyObject *__Pyx_PyVectorcall_FastCallDict_kw(PyObject *func, __pyx_vectorcallfunc vc, PyObject *const *args, size_t nargs, PyObject *kw) +{ + PyObject *res = NULL; + PyObject *kwnames; + PyObject **newargs; + PyObject **kwvalues; + Py_ssize_t i, pos; + size_t j; + PyObject *key, *value; + unsigned long keys_are_strings; + Py_ssize_t nkw = PyDict_GET_SIZE(kw); + newargs = (PyObject **)PyMem_Malloc((nargs + (size_t)nkw) * sizeof(args[0])); + if (unlikely(newargs == NULL)) { + PyErr_NoMemory(); + return NULL; + } + for (j = 0; j < nargs; j++) newargs[j] = args[j]; + kwnames = PyTuple_New(nkw); + if (unlikely(kwnames == NULL)) { + PyMem_Free(newargs); + return NULL; + } + kwvalues = newargs + nargs; + pos = i = 0; + keys_are_strings = Py_TPFLAGS_UNICODE_SUBCLASS; + while (PyDict_Next(kw, &pos, &key, &value)) { + keys_are_strings &= Py_TYPE(key)->tp_flags; + Py_INCREF(key); + Py_INCREF(value); + PyTuple_SET_ITEM(kwnames, i, key); + kwvalues[i] = value; + i++; + } + if (unlikely(!keys_are_strings)) { + PyErr_SetString(PyExc_TypeError, "keywords must be strings"); + goto cleanup; + } + res = vc(func, newargs, nargs, kwnames); +cleanup: + Py_DECREF(kwnames); + for (i = 0; i < nkw; i++) + Py_DECREF(kwvalues[i]); + PyMem_Free(newargs); + return res; +} +static CYTHON_INLINE PyObject *__Pyx_PyVectorcall_FastCallDict(PyObject *func, __pyx_vectorcallfunc vc, PyObject *const *args, size_t nargs, PyObject *kw) +{ + if (likely(kw == NULL) || PyDict_GET_SIZE(kw) == 0) { + return vc(func, args, nargs, NULL); + } + return __Pyx_PyVectorcall_FastCallDict_kw(func, vc, args, nargs, kw); +} +#endif + +/* CythonFunctionShared */ +#if CYTHON_COMPILING_IN_LIMITED_API +static CYTHON_INLINE int __Pyx__IsSameCyOrCFunction(PyObject *func, void *cfunc) { + if (__Pyx_CyFunction_Check(func)) { + return PyCFunction_GetFunction(((__pyx_CyFunctionObject*)func)->func) == (PyCFunction) cfunc; + } else if (PyCFunction_Check(func)) { + return PyCFunction_GetFunction(func) == (PyCFunction) cfunc; + } + return 0; +} +#else +static CYTHON_INLINE int __Pyx__IsSameCyOrCFunction(PyObject *func, void *cfunc) { + return __Pyx_CyOrPyCFunction_Check(func) && __Pyx_CyOrPyCFunction_GET_FUNCTION(func) == (PyCFunction) cfunc; +} +#endif +static CYTHON_INLINE void __Pyx__CyFunction_SetClassObj(__pyx_CyFunctionObject* f, PyObject* classobj) { +#if PY_VERSION_HEX < 0x030900B1 || CYTHON_COMPILING_IN_LIMITED_API + __Pyx_Py_XDECREF_SET( + __Pyx_CyFunction_GetClassObj(f), + ((classobj) ? __Pyx_NewRef(classobj) : NULL)); +#else + __Pyx_Py_XDECREF_SET( + ((PyCMethodObject *) (f))->mm_class, + (PyTypeObject*)((classobj) ? __Pyx_NewRef(classobj) : NULL)); +#endif +} +static PyObject * +__Pyx_CyFunction_get_doc(__pyx_CyFunctionObject *op, void *closure) +{ + CYTHON_UNUSED_VAR(closure); + if (unlikely(op->func_doc == NULL)) { +#if CYTHON_COMPILING_IN_LIMITED_API + op->func_doc = PyObject_GetAttrString(op->func, "__doc__"); + if (unlikely(!op->func_doc)) return NULL; +#else + if (((PyCFunctionObject*)op)->m_ml->ml_doc) { +#if PY_MAJOR_VERSION >= 3 + op->func_doc = PyUnicode_FromString(((PyCFunctionObject*)op)->m_ml->ml_doc); +#else + op->func_doc = PyString_FromString(((PyCFunctionObject*)op)->m_ml->ml_doc); +#endif + if (unlikely(op->func_doc == NULL)) + return NULL; + } else { + Py_INCREF(Py_None); + return Py_None; + } +#endif + } + Py_INCREF(op->func_doc); + return op->func_doc; +} +static int +__Pyx_CyFunction_set_doc(__pyx_CyFunctionObject *op, PyObject *value, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (value == NULL) { + value = Py_None; + } + Py_INCREF(value); + __Pyx_Py_XDECREF_SET(op->func_doc, value); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_name(__pyx_CyFunctionObject *op, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (unlikely(op->func_name == NULL)) { +#if CYTHON_COMPILING_IN_LIMITED_API + op->func_name = PyObject_GetAttrString(op->func, "__name__"); +#elif PY_MAJOR_VERSION >= 3 + op->func_name = PyUnicode_InternFromString(((PyCFunctionObject*)op)->m_ml->ml_name); +#else + op->func_name = PyString_InternFromString(((PyCFunctionObject*)op)->m_ml->ml_name); +#endif + if (unlikely(op->func_name == NULL)) + return NULL; + } + Py_INCREF(op->func_name); + return op->func_name; +} +static int +__Pyx_CyFunction_set_name(__pyx_CyFunctionObject *op, PyObject *value, void *context) +{ + CYTHON_UNUSED_VAR(context); +#if PY_MAJOR_VERSION >= 3 + if (unlikely(value == NULL || !PyUnicode_Check(value))) +#else + if (unlikely(value == NULL || !PyString_Check(value))) +#endif + { + PyErr_SetString(PyExc_TypeError, + "__name__ must be set to a string object"); + return -1; + } + Py_INCREF(value); + __Pyx_Py_XDECREF_SET(op->func_name, value); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_qualname(__pyx_CyFunctionObject *op, void *context) +{ + CYTHON_UNUSED_VAR(context); + Py_INCREF(op->func_qualname); + return op->func_qualname; +} +static int +__Pyx_CyFunction_set_qualname(__pyx_CyFunctionObject *op, PyObject *value, void *context) +{ + CYTHON_UNUSED_VAR(context); +#if PY_MAJOR_VERSION >= 3 + if (unlikely(value == NULL || !PyUnicode_Check(value))) +#else + if (unlikely(value == NULL || !PyString_Check(value))) +#endif + { + PyErr_SetString(PyExc_TypeError, + "__qualname__ must be set to a string object"); + return -1; + } + Py_INCREF(value); + __Pyx_Py_XDECREF_SET(op->func_qualname, value); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_dict(__pyx_CyFunctionObject *op, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (unlikely(op->func_dict == NULL)) { + op->func_dict = PyDict_New(); + if (unlikely(op->func_dict == NULL)) + return NULL; + } + Py_INCREF(op->func_dict); + return op->func_dict; +} +static int +__Pyx_CyFunction_set_dict(__pyx_CyFunctionObject *op, PyObject *value, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (unlikely(value == NULL)) { + PyErr_SetString(PyExc_TypeError, + "function's dictionary may not be deleted"); + return -1; + } + if (unlikely(!PyDict_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "setting function's dictionary to a non-dict"); + return -1; + } + Py_INCREF(value); + __Pyx_Py_XDECREF_SET(op->func_dict, value); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_globals(__pyx_CyFunctionObject *op, void *context) +{ + CYTHON_UNUSED_VAR(context); + Py_INCREF(op->func_globals); + return op->func_globals; +} +static PyObject * +__Pyx_CyFunction_get_closure(__pyx_CyFunctionObject *op, void *context) +{ + CYTHON_UNUSED_VAR(op); + CYTHON_UNUSED_VAR(context); + Py_INCREF(Py_None); + return Py_None; +} +static PyObject * +__Pyx_CyFunction_get_code(__pyx_CyFunctionObject *op, void *context) +{ + PyObject* result = (op->func_code) ? op->func_code : Py_None; + CYTHON_UNUSED_VAR(context); + Py_INCREF(result); + return result; +} +static int +__Pyx_CyFunction_init_defaults(__pyx_CyFunctionObject *op) { + int result = 0; + PyObject *res = op->defaults_getter((PyObject *) op); + if (unlikely(!res)) + return -1; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + op->defaults_tuple = PyTuple_GET_ITEM(res, 0); + Py_INCREF(op->defaults_tuple); + op->defaults_kwdict = PyTuple_GET_ITEM(res, 1); + Py_INCREF(op->defaults_kwdict); + #else + op->defaults_tuple = __Pyx_PySequence_ITEM(res, 0); + if (unlikely(!op->defaults_tuple)) result = -1; + else { + op->defaults_kwdict = __Pyx_PySequence_ITEM(res, 1); + if (unlikely(!op->defaults_kwdict)) result = -1; + } + #endif + Py_DECREF(res); + return result; +} +static int +__Pyx_CyFunction_set_defaults(__pyx_CyFunctionObject *op, PyObject* value, void *context) { + CYTHON_UNUSED_VAR(context); + if (!value) { + value = Py_None; + } else if (unlikely(value != Py_None && !PyTuple_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__defaults__ must be set to a tuple object"); + return -1; + } + PyErr_WarnEx(PyExc_RuntimeWarning, "changes to cyfunction.__defaults__ will not " + "currently affect the values used in function calls", 1); + Py_INCREF(value); + __Pyx_Py_XDECREF_SET(op->defaults_tuple, value); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_defaults(__pyx_CyFunctionObject *op, void *context) { + PyObject* result = op->defaults_tuple; + CYTHON_UNUSED_VAR(context); + if (unlikely(!result)) { + if (op->defaults_getter) { + if (unlikely(__Pyx_CyFunction_init_defaults(op) < 0)) return NULL; + result = op->defaults_tuple; + } else { + result = Py_None; + } + } + Py_INCREF(result); + return result; +} +static int +__Pyx_CyFunction_set_kwdefaults(__pyx_CyFunctionObject *op, PyObject* value, void *context) { + CYTHON_UNUSED_VAR(context); + if (!value) { + value = Py_None; + } else if (unlikely(value != Py_None && !PyDict_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__kwdefaults__ must be set to a dict object"); + return -1; + } + PyErr_WarnEx(PyExc_RuntimeWarning, "changes to cyfunction.__kwdefaults__ will not " + "currently affect the values used in function calls", 1); + Py_INCREF(value); + __Pyx_Py_XDECREF_SET(op->defaults_kwdict, value); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_kwdefaults(__pyx_CyFunctionObject *op, void *context) { + PyObject* result = op->defaults_kwdict; + CYTHON_UNUSED_VAR(context); + if (unlikely(!result)) { + if (op->defaults_getter) { + if (unlikely(__Pyx_CyFunction_init_defaults(op) < 0)) return NULL; + result = op->defaults_kwdict; + } else { + result = Py_None; + } + } + Py_INCREF(result); + return result; +} +static int +__Pyx_CyFunction_set_annotations(__pyx_CyFunctionObject *op, PyObject* value, void *context) { + CYTHON_UNUSED_VAR(context); + if (!value || value == Py_None) { + value = NULL; + } else if (unlikely(!PyDict_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__annotations__ must be set to a dict object"); + return -1; + } + Py_XINCREF(value); + __Pyx_Py_XDECREF_SET(op->func_annotations, value); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_annotations(__pyx_CyFunctionObject *op, void *context) { + PyObject* result = op->func_annotations; + CYTHON_UNUSED_VAR(context); + if (unlikely(!result)) { + result = PyDict_New(); + if (unlikely(!result)) return NULL; + op->func_annotations = result; + } + Py_INCREF(result); + return result; +} +static PyObject * +__Pyx_CyFunction_get_is_coroutine(__pyx_CyFunctionObject *op, void *context) { + int is_coroutine; + CYTHON_UNUSED_VAR(context); + if (op->func_is_coroutine) { + return __Pyx_NewRef(op->func_is_coroutine); + } + is_coroutine = op->flags & __Pyx_CYFUNCTION_COROUTINE; +#if PY_VERSION_HEX >= 0x03050000 + if (is_coroutine) { + PyObject *module, *fromlist, *marker = __pyx_n_s_is_coroutine; + fromlist = PyList_New(1); + if (unlikely(!fromlist)) return NULL; + Py_INCREF(marker); +#if CYTHON_ASSUME_SAFE_MACROS + PyList_SET_ITEM(fromlist, 0, marker); +#else + if (unlikely(PyList_SetItem(fromlist, 0, marker) < 0)) { + Py_DECREF(marker); + Py_DECREF(fromlist); + return NULL; + } +#endif + module = PyImport_ImportModuleLevelObject(__pyx_n_s_asyncio_coroutines, NULL, NULL, fromlist, 0); + Py_DECREF(fromlist); + if (unlikely(!module)) goto ignore; + op->func_is_coroutine = __Pyx_PyObject_GetAttrStr(module, marker); + Py_DECREF(module); + if (likely(op->func_is_coroutine)) { + return __Pyx_NewRef(op->func_is_coroutine); + } +ignore: + PyErr_Clear(); + } +#endif + op->func_is_coroutine = __Pyx_PyBool_FromLong(is_coroutine); + return __Pyx_NewRef(op->func_is_coroutine); +} +#if CYTHON_COMPILING_IN_LIMITED_API +static PyObject * +__Pyx_CyFunction_get_module(__pyx_CyFunctionObject *op, void *context) { + CYTHON_UNUSED_VAR(context); + return PyObject_GetAttrString(op->func, "__module__"); +} +static int +__Pyx_CyFunction_set_module(__pyx_CyFunctionObject *op, PyObject* value, void *context) { + CYTHON_UNUSED_VAR(context); + return PyObject_SetAttrString(op->func, "__module__", value); +} +#endif +static PyGetSetDef __pyx_CyFunction_getsets[] = { + {(char *) "func_doc", (getter)__Pyx_CyFunction_get_doc, (setter)__Pyx_CyFunction_set_doc, 0, 0}, + {(char *) "__doc__", (getter)__Pyx_CyFunction_get_doc, (setter)__Pyx_CyFunction_set_doc, 0, 0}, + {(char *) "func_name", (getter)__Pyx_CyFunction_get_name, (setter)__Pyx_CyFunction_set_name, 0, 0}, + {(char *) "__name__", (getter)__Pyx_CyFunction_get_name, (setter)__Pyx_CyFunction_set_name, 0, 0}, + {(char *) "__qualname__", (getter)__Pyx_CyFunction_get_qualname, (setter)__Pyx_CyFunction_set_qualname, 0, 0}, + {(char *) "func_dict", (getter)__Pyx_CyFunction_get_dict, (setter)__Pyx_CyFunction_set_dict, 0, 0}, + {(char *) "__dict__", (getter)__Pyx_CyFunction_get_dict, (setter)__Pyx_CyFunction_set_dict, 0, 0}, + {(char *) "func_globals", (getter)__Pyx_CyFunction_get_globals, 0, 0, 0}, + {(char *) "__globals__", (getter)__Pyx_CyFunction_get_globals, 0, 0, 0}, + {(char *) "func_closure", (getter)__Pyx_CyFunction_get_closure, 0, 0, 0}, + {(char *) "__closure__", (getter)__Pyx_CyFunction_get_closure, 0, 0, 0}, + {(char *) "func_code", (getter)__Pyx_CyFunction_get_code, 0, 0, 0}, + {(char *) "__code__", (getter)__Pyx_CyFunction_get_code, 0, 0, 0}, + {(char *) "func_defaults", (getter)__Pyx_CyFunction_get_defaults, (setter)__Pyx_CyFunction_set_defaults, 0, 0}, + {(char *) "__defaults__", (getter)__Pyx_CyFunction_get_defaults, (setter)__Pyx_CyFunction_set_defaults, 0, 0}, + {(char *) "__kwdefaults__", (getter)__Pyx_CyFunction_get_kwdefaults, (setter)__Pyx_CyFunction_set_kwdefaults, 0, 0}, + {(char *) "__annotations__", (getter)__Pyx_CyFunction_get_annotations, (setter)__Pyx_CyFunction_set_annotations, 0, 0}, + {(char *) "_is_coroutine", (getter)__Pyx_CyFunction_get_is_coroutine, 0, 0, 0}, +#if CYTHON_COMPILING_IN_LIMITED_API + {"__module__", (getter)__Pyx_CyFunction_get_module, (setter)__Pyx_CyFunction_set_module, 0, 0}, +#endif + {0, 0, 0, 0, 0} +}; +static PyMemberDef __pyx_CyFunction_members[] = { +#if !CYTHON_COMPILING_IN_LIMITED_API + {(char *) "__module__", T_OBJECT, offsetof(PyCFunctionObject, m_module), 0, 0}, +#endif +#if CYTHON_USE_TYPE_SPECS + {(char *) "__dictoffset__", T_PYSSIZET, offsetof(__pyx_CyFunctionObject, func_dict), READONLY, 0}, +#if CYTHON_METH_FASTCALL +#if CYTHON_BACKPORT_VECTORCALL + {(char *) "__vectorcalloffset__", T_PYSSIZET, offsetof(__pyx_CyFunctionObject, func_vectorcall), READONLY, 0}, +#else +#if !CYTHON_COMPILING_IN_LIMITED_API + {(char *) "__vectorcalloffset__", T_PYSSIZET, offsetof(PyCFunctionObject, vectorcall), READONLY, 0}, +#endif +#endif +#endif +#if PY_VERSION_HEX < 0x030500A0 || CYTHON_COMPILING_IN_LIMITED_API + {(char *) "__weaklistoffset__", T_PYSSIZET, offsetof(__pyx_CyFunctionObject, func_weakreflist), READONLY, 0}, +#else + {(char *) "__weaklistoffset__", T_PYSSIZET, offsetof(PyCFunctionObject, m_weakreflist), READONLY, 0}, +#endif +#endif + {0, 0, 0, 0, 0} +}; +static PyObject * +__Pyx_CyFunction_reduce(__pyx_CyFunctionObject *m, PyObject *args) +{ + CYTHON_UNUSED_VAR(args); +#if PY_MAJOR_VERSION >= 3 + Py_INCREF(m->func_qualname); + return m->func_qualname; +#else + return PyString_FromString(((PyCFunctionObject*)m)->m_ml->ml_name); +#endif +} +static PyMethodDef __pyx_CyFunction_methods[] = { + {"__reduce__", (PyCFunction)__Pyx_CyFunction_reduce, METH_VARARGS, 0}, + {0, 0, 0, 0} +}; +#if PY_VERSION_HEX < 0x030500A0 || CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_CyFunction_weakreflist(cyfunc) ((cyfunc)->func_weakreflist) +#else +#define __Pyx_CyFunction_weakreflist(cyfunc) (((PyCFunctionObject*)cyfunc)->m_weakreflist) +#endif +static PyObject *__Pyx_CyFunction_Init(__pyx_CyFunctionObject *op, PyMethodDef *ml, int flags, PyObject* qualname, + PyObject *closure, PyObject *module, PyObject* globals, PyObject* code) { +#if !CYTHON_COMPILING_IN_LIMITED_API + PyCFunctionObject *cf = (PyCFunctionObject*) op; +#endif + if (unlikely(op == NULL)) + return NULL; +#if CYTHON_COMPILING_IN_LIMITED_API + op->func = PyCFunction_NewEx(ml, (PyObject*)op, module); + if (unlikely(!op->func)) return NULL; +#endif + op->flags = flags; + __Pyx_CyFunction_weakreflist(op) = NULL; +#if !CYTHON_COMPILING_IN_LIMITED_API + cf->m_ml = ml; + cf->m_self = (PyObject *) op; +#endif + Py_XINCREF(closure); + op->func_closure = closure; +#if !CYTHON_COMPILING_IN_LIMITED_API + Py_XINCREF(module); + cf->m_module = module; +#endif + op->func_dict = NULL; + op->func_name = NULL; + Py_INCREF(qualname); + op->func_qualname = qualname; + op->func_doc = NULL; +#if PY_VERSION_HEX < 0x030900B1 || CYTHON_COMPILING_IN_LIMITED_API + op->func_classobj = NULL; +#else + ((PyCMethodObject*)op)->mm_class = NULL; +#endif + op->func_globals = globals; + Py_INCREF(op->func_globals); + Py_XINCREF(code); + op->func_code = code; + op->defaults_pyobjects = 0; + op->defaults_size = 0; + op->defaults = NULL; + op->defaults_tuple = NULL; + op->defaults_kwdict = NULL; + op->defaults_getter = NULL; + op->func_annotations = NULL; + op->func_is_coroutine = NULL; +#if CYTHON_METH_FASTCALL + switch (ml->ml_flags & (METH_VARARGS | METH_FASTCALL | METH_NOARGS | METH_O | METH_KEYWORDS | METH_METHOD)) { + case METH_NOARGS: + __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_NOARGS; + break; + case METH_O: + __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_O; + break; + case METH_METHOD | METH_FASTCALL | METH_KEYWORDS: + __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS_METHOD; + break; + case METH_FASTCALL | METH_KEYWORDS: + __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS; + break; + case METH_VARARGS | METH_KEYWORDS: + __Pyx_CyFunction_func_vectorcall(op) = NULL; + break; + default: + PyErr_SetString(PyExc_SystemError, "Bad call flags for CyFunction"); + Py_DECREF(op); + return NULL; + } +#endif + return (PyObject *) op; +} +static int +__Pyx_CyFunction_clear(__pyx_CyFunctionObject *m) +{ + Py_CLEAR(m->func_closure); +#if CYTHON_COMPILING_IN_LIMITED_API + Py_CLEAR(m->func); +#else + Py_CLEAR(((PyCFunctionObject*)m)->m_module); +#endif + Py_CLEAR(m->func_dict); + Py_CLEAR(m->func_name); + Py_CLEAR(m->func_qualname); + Py_CLEAR(m->func_doc); + Py_CLEAR(m->func_globals); + Py_CLEAR(m->func_code); +#if !CYTHON_COMPILING_IN_LIMITED_API +#if PY_VERSION_HEX < 0x030900B1 + Py_CLEAR(__Pyx_CyFunction_GetClassObj(m)); +#else + { + PyObject *cls = (PyObject*) ((PyCMethodObject *) (m))->mm_class; + ((PyCMethodObject *) (m))->mm_class = NULL; + Py_XDECREF(cls); + } +#endif +#endif + Py_CLEAR(m->defaults_tuple); + Py_CLEAR(m->defaults_kwdict); + Py_CLEAR(m->func_annotations); + Py_CLEAR(m->func_is_coroutine); + if (m->defaults) { + PyObject **pydefaults = __Pyx_CyFunction_Defaults(PyObject *, m); + int i; + for (i = 0; i < m->defaults_pyobjects; i++) + Py_XDECREF(pydefaults[i]); + PyObject_Free(m->defaults); + m->defaults = NULL; + } + return 0; +} +static void __Pyx__CyFunction_dealloc(__pyx_CyFunctionObject *m) +{ + if (__Pyx_CyFunction_weakreflist(m) != NULL) + PyObject_ClearWeakRefs((PyObject *) m); + __Pyx_CyFunction_clear(m); + __Pyx_PyHeapTypeObject_GC_Del(m); +} +static void __Pyx_CyFunction_dealloc(__pyx_CyFunctionObject *m) +{ + PyObject_GC_UnTrack(m); + __Pyx__CyFunction_dealloc(m); +} +static int __Pyx_CyFunction_traverse(__pyx_CyFunctionObject *m, visitproc visit, void *arg) +{ + Py_VISIT(m->func_closure); +#if CYTHON_COMPILING_IN_LIMITED_API + Py_VISIT(m->func); +#else + Py_VISIT(((PyCFunctionObject*)m)->m_module); +#endif + Py_VISIT(m->func_dict); + Py_VISIT(m->func_name); + Py_VISIT(m->func_qualname); + Py_VISIT(m->func_doc); + Py_VISIT(m->func_globals); + Py_VISIT(m->func_code); +#if !CYTHON_COMPILING_IN_LIMITED_API + Py_VISIT(__Pyx_CyFunction_GetClassObj(m)); +#endif + Py_VISIT(m->defaults_tuple); + Py_VISIT(m->defaults_kwdict); + Py_VISIT(m->func_is_coroutine); + if (m->defaults) { + PyObject **pydefaults = __Pyx_CyFunction_Defaults(PyObject *, m); + int i; + for (i = 0; i < m->defaults_pyobjects; i++) + Py_VISIT(pydefaults[i]); + } + return 0; +} +static PyObject* +__Pyx_CyFunction_repr(__pyx_CyFunctionObject *op) +{ +#if PY_MAJOR_VERSION >= 3 + return PyUnicode_FromFormat("", + op->func_qualname, (void *)op); +#else + return PyString_FromFormat("", + PyString_AsString(op->func_qualname), (void *)op); +#endif +} +static PyObject * __Pyx_CyFunction_CallMethod(PyObject *func, PyObject *self, PyObject *arg, PyObject *kw) { +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *f = ((__pyx_CyFunctionObject*)func)->func; + PyObject *py_name = NULL; + PyCFunction meth; + int flags; + meth = PyCFunction_GetFunction(f); + if (unlikely(!meth)) return NULL; + flags = PyCFunction_GetFlags(f); + if (unlikely(flags < 0)) return NULL; +#else + PyCFunctionObject* f = (PyCFunctionObject*)func; + PyCFunction meth = f->m_ml->ml_meth; + int flags = f->m_ml->ml_flags; +#endif + Py_ssize_t size; + switch (flags & (METH_VARARGS | METH_KEYWORDS | METH_NOARGS | METH_O)) { + case METH_VARARGS: + if (likely(kw == NULL || PyDict_Size(kw) == 0)) + return (*meth)(self, arg); + break; + case METH_VARARGS | METH_KEYWORDS: + return (*(PyCFunctionWithKeywords)(void*)meth)(self, arg, kw); + case METH_NOARGS: + if (likely(kw == NULL || PyDict_Size(kw) == 0)) { +#if CYTHON_ASSUME_SAFE_MACROS + size = PyTuple_GET_SIZE(arg); +#else + size = PyTuple_Size(arg); + if (unlikely(size < 0)) return NULL; +#endif + if (likely(size == 0)) + return (*meth)(self, NULL); +#if CYTHON_COMPILING_IN_LIMITED_API + py_name = __Pyx_CyFunction_get_name((__pyx_CyFunctionObject*)func, NULL); + if (!py_name) return NULL; + PyErr_Format(PyExc_TypeError, + "%.200S() takes no arguments (%" CYTHON_FORMAT_SSIZE_T "d given)", + py_name, size); + Py_DECREF(py_name); +#else + PyErr_Format(PyExc_TypeError, + "%.200s() takes no arguments (%" CYTHON_FORMAT_SSIZE_T "d given)", + f->m_ml->ml_name, size); +#endif + return NULL; + } + break; + case METH_O: + if (likely(kw == NULL || PyDict_Size(kw) == 0)) { +#if CYTHON_ASSUME_SAFE_MACROS + size = PyTuple_GET_SIZE(arg); +#else + size = PyTuple_Size(arg); + if (unlikely(size < 0)) return NULL; +#endif + if (likely(size == 1)) { + PyObject *result, *arg0; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + arg0 = PyTuple_GET_ITEM(arg, 0); + #else + arg0 = __Pyx_PySequence_ITEM(arg, 0); if (unlikely(!arg0)) return NULL; + #endif + result = (*meth)(self, arg0); + #if !(CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS) + Py_DECREF(arg0); + #endif + return result; + } +#if CYTHON_COMPILING_IN_LIMITED_API + py_name = __Pyx_CyFunction_get_name((__pyx_CyFunctionObject*)func, NULL); + if (!py_name) return NULL; + PyErr_Format(PyExc_TypeError, + "%.200S() takes exactly one argument (%" CYTHON_FORMAT_SSIZE_T "d given)", + py_name, size); + Py_DECREF(py_name); +#else + PyErr_Format(PyExc_TypeError, + "%.200s() takes exactly one argument (%" CYTHON_FORMAT_SSIZE_T "d given)", + f->m_ml->ml_name, size); +#endif + return NULL; + } + break; + default: + PyErr_SetString(PyExc_SystemError, "Bad call flags for CyFunction"); + return NULL; + } +#if CYTHON_COMPILING_IN_LIMITED_API + py_name = __Pyx_CyFunction_get_name((__pyx_CyFunctionObject*)func, NULL); + if (!py_name) return NULL; + PyErr_Format(PyExc_TypeError, "%.200S() takes no keyword arguments", + py_name); + Py_DECREF(py_name); +#else + PyErr_Format(PyExc_TypeError, "%.200s() takes no keyword arguments", + f->m_ml->ml_name); +#endif + return NULL; +} +static CYTHON_INLINE PyObject *__Pyx_CyFunction_Call(PyObject *func, PyObject *arg, PyObject *kw) { + PyObject *self, *result; +#if CYTHON_COMPILING_IN_LIMITED_API + self = PyCFunction_GetSelf(((__pyx_CyFunctionObject*)func)->func); + if (unlikely(!self) && PyErr_Occurred()) return NULL; +#else + self = ((PyCFunctionObject*)func)->m_self; +#endif + result = __Pyx_CyFunction_CallMethod(func, self, arg, kw); + return result; +} +static PyObject *__Pyx_CyFunction_CallAsMethod(PyObject *func, PyObject *args, PyObject *kw) { + PyObject *result; + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *) func; +#if CYTHON_METH_FASTCALL + __pyx_vectorcallfunc vc = __Pyx_CyFunction_func_vectorcall(cyfunc); + if (vc) { +#if CYTHON_ASSUME_SAFE_MACROS + return __Pyx_PyVectorcall_FastCallDict(func, vc, &PyTuple_GET_ITEM(args, 0), (size_t)PyTuple_GET_SIZE(args), kw); +#else + (void) &__Pyx_PyVectorcall_FastCallDict; + return PyVectorcall_Call(func, args, kw); +#endif + } +#endif + if ((cyfunc->flags & __Pyx_CYFUNCTION_CCLASS) && !(cyfunc->flags & __Pyx_CYFUNCTION_STATICMETHOD)) { + Py_ssize_t argc; + PyObject *new_args; + PyObject *self; +#if CYTHON_ASSUME_SAFE_MACROS + argc = PyTuple_GET_SIZE(args); +#else + argc = PyTuple_Size(args); + if (unlikely(!argc) < 0) return NULL; +#endif + new_args = PyTuple_GetSlice(args, 1, argc); + if (unlikely(!new_args)) + return NULL; + self = PyTuple_GetItem(args, 0); + if (unlikely(!self)) { + Py_DECREF(new_args); +#if PY_MAJOR_VERSION > 2 + PyErr_Format(PyExc_TypeError, + "unbound method %.200S() needs an argument", + cyfunc->func_qualname); +#else + PyErr_SetString(PyExc_TypeError, + "unbound method needs an argument"); +#endif + return NULL; + } + result = __Pyx_CyFunction_CallMethod(func, self, new_args, kw); + Py_DECREF(new_args); + } else { + result = __Pyx_CyFunction_Call(func, args, kw); + } + return result; +} +#if CYTHON_METH_FASTCALL +static CYTHON_INLINE int __Pyx_CyFunction_Vectorcall_CheckArgs(__pyx_CyFunctionObject *cyfunc, Py_ssize_t nargs, PyObject *kwnames) +{ + int ret = 0; + if ((cyfunc->flags & __Pyx_CYFUNCTION_CCLASS) && !(cyfunc->flags & __Pyx_CYFUNCTION_STATICMETHOD)) { + if (unlikely(nargs < 1)) { + PyErr_Format(PyExc_TypeError, "%.200s() needs an argument", + ((PyCFunctionObject*)cyfunc)->m_ml->ml_name); + return -1; + } + ret = 1; + } + if (unlikely(kwnames) && unlikely(PyTuple_GET_SIZE(kwnames))) { + PyErr_Format(PyExc_TypeError, + "%.200s() takes no keyword arguments", ((PyCFunctionObject*)cyfunc)->m_ml->ml_name); + return -1; + } + return ret; +} +static PyObject * __Pyx_CyFunction_Vectorcall_NOARGS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) +{ + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *)func; + PyMethodDef* def = ((PyCFunctionObject*)cyfunc)->m_ml; +#if CYTHON_BACKPORT_VECTORCALL + Py_ssize_t nargs = (Py_ssize_t)nargsf; +#else + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); +#endif + PyObject *self; + switch (__Pyx_CyFunction_Vectorcall_CheckArgs(cyfunc, nargs, kwnames)) { + case 1: + self = args[0]; + args += 1; + nargs -= 1; + break; + case 0: + self = ((PyCFunctionObject*)cyfunc)->m_self; + break; + default: + return NULL; + } + if (unlikely(nargs != 0)) { + PyErr_Format(PyExc_TypeError, + "%.200s() takes no arguments (%" CYTHON_FORMAT_SSIZE_T "d given)", + def->ml_name, nargs); + return NULL; + } + return def->ml_meth(self, NULL); +} +static PyObject * __Pyx_CyFunction_Vectorcall_O(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) +{ + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *)func; + PyMethodDef* def = ((PyCFunctionObject*)cyfunc)->m_ml; +#if CYTHON_BACKPORT_VECTORCALL + Py_ssize_t nargs = (Py_ssize_t)nargsf; +#else + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); +#endif + PyObject *self; + switch (__Pyx_CyFunction_Vectorcall_CheckArgs(cyfunc, nargs, kwnames)) { + case 1: + self = args[0]; + args += 1; + nargs -= 1; + break; + case 0: + self = ((PyCFunctionObject*)cyfunc)->m_self; + break; + default: + return NULL; + } + if (unlikely(nargs != 1)) { + PyErr_Format(PyExc_TypeError, + "%.200s() takes exactly one argument (%" CYTHON_FORMAT_SSIZE_T "d given)", + def->ml_name, nargs); + return NULL; + } + return def->ml_meth(self, args[0]); +} +static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) +{ + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *)func; + PyMethodDef* def = ((PyCFunctionObject*)cyfunc)->m_ml; +#if CYTHON_BACKPORT_VECTORCALL + Py_ssize_t nargs = (Py_ssize_t)nargsf; +#else + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); +#endif + PyObject *self; + switch (__Pyx_CyFunction_Vectorcall_CheckArgs(cyfunc, nargs, NULL)) { + case 1: + self = args[0]; + args += 1; + nargs -= 1; + break; + case 0: + self = ((PyCFunctionObject*)cyfunc)->m_self; + break; + default: + return NULL; + } + return ((_PyCFunctionFastWithKeywords)(void(*)(void))def->ml_meth)(self, args, nargs, kwnames); +} +static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS_METHOD(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) +{ + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *)func; + PyMethodDef* def = ((PyCFunctionObject*)cyfunc)->m_ml; + PyTypeObject *cls = (PyTypeObject *) __Pyx_CyFunction_GetClassObj(cyfunc); +#if CYTHON_BACKPORT_VECTORCALL + Py_ssize_t nargs = (Py_ssize_t)nargsf; +#else + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); +#endif + PyObject *self; + switch (__Pyx_CyFunction_Vectorcall_CheckArgs(cyfunc, nargs, NULL)) { + case 1: + self = args[0]; + args += 1; + nargs -= 1; + break; + case 0: + self = ((PyCFunctionObject*)cyfunc)->m_self; + break; + default: + return NULL; + } + return ((__Pyx_PyCMethod)(void(*)(void))def->ml_meth)(self, cls, args, (size_t)nargs, kwnames); +} +#endif +#if CYTHON_USE_TYPE_SPECS +static PyType_Slot __pyx_CyFunctionType_slots[] = { + {Py_tp_dealloc, (void *)__Pyx_CyFunction_dealloc}, + {Py_tp_repr, (void *)__Pyx_CyFunction_repr}, + {Py_tp_call, (void *)__Pyx_CyFunction_CallAsMethod}, + {Py_tp_traverse, (void *)__Pyx_CyFunction_traverse}, + {Py_tp_clear, (void *)__Pyx_CyFunction_clear}, + {Py_tp_methods, (void *)__pyx_CyFunction_methods}, + {Py_tp_members, (void *)__pyx_CyFunction_members}, + {Py_tp_getset, (void *)__pyx_CyFunction_getsets}, + {Py_tp_descr_get, (void *)__Pyx_PyMethod_New}, + {0, 0}, +}; +static PyType_Spec __pyx_CyFunctionType_spec = { + __PYX_TYPE_MODULE_PREFIX "cython_function_or_method", + sizeof(__pyx_CyFunctionObject), + 0, +#ifdef Py_TPFLAGS_METHOD_DESCRIPTOR + Py_TPFLAGS_METHOD_DESCRIPTOR | +#endif +#if (defined(_Py_TPFLAGS_HAVE_VECTORCALL) && CYTHON_METH_FASTCALL) + _Py_TPFLAGS_HAVE_VECTORCALL | +#endif + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, + __pyx_CyFunctionType_slots +}; +#else +static PyTypeObject __pyx_CyFunctionType_type = { + PyVarObject_HEAD_INIT(0, 0) + __PYX_TYPE_MODULE_PREFIX "cython_function_or_method", + sizeof(__pyx_CyFunctionObject), + 0, + (destructor) __Pyx_CyFunction_dealloc, +#if !CYTHON_METH_FASTCALL + 0, +#elif CYTHON_BACKPORT_VECTORCALL + (printfunc)offsetof(__pyx_CyFunctionObject, func_vectorcall), +#else + offsetof(PyCFunctionObject, vectorcall), +#endif + 0, + 0, +#if PY_MAJOR_VERSION < 3 + 0, +#else + 0, +#endif + (reprfunc) __Pyx_CyFunction_repr, + 0, + 0, + 0, + 0, + __Pyx_CyFunction_CallAsMethod, + 0, + 0, + 0, + 0, +#ifdef Py_TPFLAGS_METHOD_DESCRIPTOR + Py_TPFLAGS_METHOD_DESCRIPTOR | +#endif +#if defined(_Py_TPFLAGS_HAVE_VECTORCALL) && CYTHON_METH_FASTCALL + _Py_TPFLAGS_HAVE_VECTORCALL | +#endif + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, + 0, + (traverseproc) __Pyx_CyFunction_traverse, + (inquiry) __Pyx_CyFunction_clear, + 0, +#if PY_VERSION_HEX < 0x030500A0 + offsetof(__pyx_CyFunctionObject, func_weakreflist), +#else + offsetof(PyCFunctionObject, m_weakreflist), +#endif + 0, + 0, + __pyx_CyFunction_methods, + __pyx_CyFunction_members, + __pyx_CyFunction_getsets, + 0, + 0, + __Pyx_PyMethod_New, + 0, + offsetof(__pyx_CyFunctionObject, func_dict), + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, +#if PY_VERSION_HEX >= 0x030400a1 + 0, +#endif +#if PY_VERSION_HEX >= 0x030800b1 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) + 0, +#endif +#if __PYX_NEED_TP_PRINT_SLOT + 0, +#endif +#if PY_VERSION_HEX >= 0x030C0000 + 0, +#endif +#if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 + 0, +#endif +}; +#endif +static int __pyx_CyFunction_init(PyObject *module) { +#if CYTHON_USE_TYPE_SPECS + __pyx_CyFunctionType = __Pyx_FetchCommonTypeFromSpec(module, &__pyx_CyFunctionType_spec, NULL); +#else + CYTHON_UNUSED_VAR(module); + __pyx_CyFunctionType = __Pyx_FetchCommonType(&__pyx_CyFunctionType_type); +#endif + if (unlikely(__pyx_CyFunctionType == NULL)) { + return -1; + } + return 0; +} +static CYTHON_INLINE void *__Pyx_CyFunction_InitDefaults(PyObject *func, size_t size, int pyobjects) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->defaults = PyObject_Malloc(size); + if (unlikely(!m->defaults)) + return PyErr_NoMemory(); + memset(m->defaults, 0, size); + m->defaults_pyobjects = pyobjects; + m->defaults_size = size; + return m->defaults; +} +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsTuple(PyObject *func, PyObject *tuple) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->defaults_tuple = tuple; + Py_INCREF(tuple); +} +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsKwDict(PyObject *func, PyObject *dict) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->defaults_kwdict = dict; + Py_INCREF(dict); +} +static CYTHON_INLINE void __Pyx_CyFunction_SetAnnotationsDict(PyObject *func, PyObject *dict) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->func_annotations = dict; + Py_INCREF(dict); +} + +/* CythonFunction */ +static PyObject *__Pyx_CyFunction_New(PyMethodDef *ml, int flags, PyObject* qualname, + PyObject *closure, PyObject *module, PyObject* globals, PyObject* code) { + PyObject *op = __Pyx_CyFunction_Init( + PyObject_GC_New(__pyx_CyFunctionObject, __pyx_CyFunctionType), + ml, flags, qualname, closure, module, globals, code + ); + if (likely(op)) { + PyObject_GC_Track(op); + } + return op; +} + +/* GetNameInClass */ +static PyObject *__Pyx__GetNameInClass(PyObject *nmspace, PyObject *name) { + PyObject *result; + PyObject *dict; + assert(PyType_Check(nmspace)); +#if CYTHON_USE_TYPE_SLOTS + dict = ((PyTypeObject*)nmspace)->tp_dict; + Py_XINCREF(dict); +#else + dict = PyObject_GetAttr(nmspace, __pyx_n_s_dict); +#endif + if (likely(dict)) { + result = PyObject_GetItem(dict, name); + Py_DECREF(dict); + if (result) { + return result; + } + } + PyErr_Clear(); + __Pyx_GetModuleGlobalNameUncached(result, name); + return result; +} + +/* CLineInTraceback */ +#ifndef CYTHON_CLINE_IN_TRACEBACK +static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line) { + PyObject *use_cline; + PyObject *ptype, *pvalue, *ptraceback; +#if CYTHON_COMPILING_IN_CPYTHON + PyObject **cython_runtime_dict; +#endif + CYTHON_MAYBE_UNUSED_VAR(tstate); + if (unlikely(!__pyx_cython_runtime)) { + return c_line; + } + __Pyx_ErrFetchInState(tstate, &ptype, &pvalue, &ptraceback); +#if CYTHON_COMPILING_IN_CPYTHON + cython_runtime_dict = _PyObject_GetDictPtr(__pyx_cython_runtime); + if (likely(cython_runtime_dict)) { + __PYX_PY_DICT_LOOKUP_IF_MODIFIED( + use_cline, *cython_runtime_dict, + __Pyx_PyDict_GetItemStr(*cython_runtime_dict, __pyx_n_s_cline_in_traceback)) + } else +#endif + { + PyObject *use_cline_obj = __Pyx_PyObject_GetAttrStrNoError(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback); + if (use_cline_obj) { + use_cline = PyObject_Not(use_cline_obj) ? Py_False : Py_True; + Py_DECREF(use_cline_obj); + } else { + PyErr_Clear(); + use_cline = NULL; + } + } + if (!use_cline) { + c_line = 0; + (void) PyObject_SetAttr(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback, Py_False); + } + else if (use_cline == Py_False || (use_cline != Py_True && PyObject_Not(use_cline) != 0)) { + c_line = 0; + } + __Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback); + return c_line; +} +#endif + +/* CodeObjectCache */ +#if !CYTHON_COMPILING_IN_LIMITED_API +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { + int start = 0, mid = 0, end = count - 1; + if (end >= 0 && code_line > entries[end].code_line) { + return count; + } + while (start < end) { + mid = start + (end - start) / 2; + if (code_line < entries[mid].code_line) { + end = mid; + } else if (code_line > entries[mid].code_line) { + start = mid + 1; + } else { + return mid; + } + } + if (code_line <= entries[mid].code_line) { + return mid; + } else { + return mid + 1; + } +} +static PyCodeObject *__pyx_find_code_object(int code_line) { + PyCodeObject* code_object; + int pos; + if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { + return NULL; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { + return NULL; + } + code_object = __pyx_code_cache.entries[pos].code_object; + Py_INCREF(code_object); + return code_object; +} +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { + int pos, i; + __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; + if (unlikely(!code_line)) { + return; + } + if (unlikely(!entries)) { + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); + if (likely(entries)) { + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = 64; + __pyx_code_cache.count = 1; + entries[0].code_line = code_line; + entries[0].code_object = code_object; + Py_INCREF(code_object); + } + return; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { + PyCodeObject* tmp = entries[pos].code_object; + entries[pos].code_object = code_object; + Py_DECREF(tmp); + return; + } + if (__pyx_code_cache.count == __pyx_code_cache.max_count) { + int new_max = __pyx_code_cache.max_count + 64; + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( + __pyx_code_cache.entries, ((size_t)new_max) * sizeof(__Pyx_CodeObjectCacheEntry)); + if (unlikely(!entries)) { + return; + } + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = new_max; + } + for (i=__pyx_code_cache.count; i>pos; i--) { + entries[i] = entries[i-1]; + } + entries[pos].code_line = code_line; + entries[pos].code_object = code_object; + __pyx_code_cache.count++; + Py_INCREF(code_object); +} +#endif + +/* AddTraceback */ +#include "compile.h" +#include "frameobject.h" +#include "traceback.h" +#if PY_VERSION_HEX >= 0x030b00a6 && !CYTHON_COMPILING_IN_LIMITED_API + #ifndef Py_BUILD_CORE + #define Py_BUILD_CORE 1 + #endif + #include "internal/pycore_frame.h" +#endif +#if CYTHON_COMPILING_IN_LIMITED_API +static PyObject *__Pyx_PyCode_Replace_For_AddTraceback(PyObject *code, PyObject *scratch_dict, + PyObject *firstlineno, PyObject *name) { + PyObject *replace = NULL; + if (unlikely(PyDict_SetItemString(scratch_dict, "co_firstlineno", firstlineno))) return NULL; + if (unlikely(PyDict_SetItemString(scratch_dict, "co_name", name))) return NULL; + replace = PyObject_GetAttrString(code, "replace"); + if (likely(replace)) { + PyObject *result; + result = PyObject_Call(replace, __pyx_empty_tuple, scratch_dict); + Py_DECREF(replace); + return result; + } + PyErr_Clear(); + #if __PYX_LIMITED_VERSION_HEX < 0x030780000 + { + PyObject *compiled = NULL, *result = NULL; + if (unlikely(PyDict_SetItemString(scratch_dict, "code", code))) return NULL; + if (unlikely(PyDict_SetItemString(scratch_dict, "type", (PyObject*)(&PyType_Type)))) return NULL; + compiled = Py_CompileString( + "out = type(code)(\n" + " code.co_argcount, code.co_kwonlyargcount, code.co_nlocals, code.co_stacksize,\n" + " code.co_flags, code.co_code, code.co_consts, code.co_names,\n" + " code.co_varnames, code.co_filename, co_name, co_firstlineno,\n" + " code.co_lnotab)\n", "", Py_file_input); + if (!compiled) return NULL; + result = PyEval_EvalCode(compiled, scratch_dict, scratch_dict); + Py_DECREF(compiled); + if (!result) PyErr_Print(); + Py_DECREF(result); + result = PyDict_GetItemString(scratch_dict, "out"); + if (result) Py_INCREF(result); + return result; + } + #else + return NULL; + #endif +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyObject *code_object = NULL, *py_py_line = NULL, *py_funcname = NULL, *dict = NULL; + PyObject *replace = NULL, *getframe = NULL, *frame = NULL; + PyObject *exc_type, *exc_value, *exc_traceback; + int success = 0; + if (c_line) { + (void) __pyx_cfilenm; + (void) __Pyx_CLineForTraceback(__Pyx_PyThreadState_Current, c_line); + } + PyErr_Fetch(&exc_type, &exc_value, &exc_traceback); + code_object = Py_CompileString("_getframe()", filename, Py_eval_input); + if (unlikely(!code_object)) goto bad; + py_py_line = PyLong_FromLong(py_line); + if (unlikely(!py_py_line)) goto bad; + py_funcname = PyUnicode_FromString(funcname); + if (unlikely(!py_funcname)) goto bad; + dict = PyDict_New(); + if (unlikely(!dict)) goto bad; + { + PyObject *old_code_object = code_object; + code_object = __Pyx_PyCode_Replace_For_AddTraceback(code_object, dict, py_py_line, py_funcname); + Py_DECREF(old_code_object); + } + if (unlikely(!code_object)) goto bad; + getframe = PySys_GetObject("_getframe"); + if (unlikely(!getframe)) goto bad; + if (unlikely(PyDict_SetItemString(dict, "_getframe", getframe))) goto bad; + frame = PyEval_EvalCode(code_object, dict, dict); + if (unlikely(!frame) || frame == Py_None) goto bad; + success = 1; + bad: + PyErr_Restore(exc_type, exc_value, exc_traceback); + Py_XDECREF(code_object); + Py_XDECREF(py_py_line); + Py_XDECREF(py_funcname); + Py_XDECREF(dict); + Py_XDECREF(replace); + if (success) { + PyTraceBack_Here( + (struct _frame*)frame); + } + Py_XDECREF(frame); +} +#else +static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( + const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = NULL; + PyObject *py_funcname = NULL; + #if PY_MAJOR_VERSION < 3 + PyObject *py_srcfile = NULL; + py_srcfile = PyString_FromString(filename); + if (!py_srcfile) goto bad; + #endif + if (c_line) { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + if (!py_funcname) goto bad; + #else + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + if (!py_funcname) goto bad; + funcname = PyUnicode_AsUTF8(py_funcname); + if (!funcname) goto bad; + #endif + } + else { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromString(funcname); + if (!py_funcname) goto bad; + #endif + } + #if PY_MAJOR_VERSION < 3 + py_code = __Pyx_PyCode_New( + 0, + 0, + 0, + 0, + 0, + 0, + __pyx_empty_bytes, /*PyObject *code,*/ + __pyx_empty_tuple, /*PyObject *consts,*/ + __pyx_empty_tuple, /*PyObject *names,*/ + __pyx_empty_tuple, /*PyObject *varnames,*/ + __pyx_empty_tuple, /*PyObject *freevars,*/ + __pyx_empty_tuple, /*PyObject *cellvars,*/ + py_srcfile, /*PyObject *filename,*/ + py_funcname, /*PyObject *name,*/ + py_line, + __pyx_empty_bytes /*PyObject *lnotab*/ + ); + Py_DECREF(py_srcfile); + #else + py_code = PyCode_NewEmpty(filename, funcname, py_line); + #endif + Py_XDECREF(py_funcname); + return py_code; +bad: + Py_XDECREF(py_funcname); + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(py_srcfile); + #endif + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyFrameObject *py_frame = 0; + PyThreadState *tstate = __Pyx_PyThreadState_Current; + PyObject *ptype, *pvalue, *ptraceback; + if (c_line) { + c_line = __Pyx_CLineForTraceback(tstate, c_line); + } + py_code = __pyx_find_code_object(c_line ? -c_line : py_line); + if (!py_code) { + __Pyx_ErrFetchInState(tstate, &ptype, &pvalue, &ptraceback); + py_code = __Pyx_CreateCodeObjectForTraceback( + funcname, c_line, py_line, filename); + if (!py_code) { + /* If the code object creation fails, then we should clear the + fetched exception references and propagate the new exception */ + Py_XDECREF(ptype); + Py_XDECREF(pvalue); + Py_XDECREF(ptraceback); + goto bad; + } + __Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback); + __pyx_insert_code_object(c_line ? -c_line : py_line, py_code); + } + py_frame = PyFrame_New( + tstate, /*PyThreadState *tstate,*/ + py_code, /*PyCodeObject *code,*/ + __pyx_d, /*PyObject *globals,*/ + 0 /*PyObject *locals*/ + ); + if (!py_frame) goto bad; + __Pyx_PyFrame_SetLineNumber(py_frame, py_line); + PyTraceBack_Here(py_frame); +bad: + Py_XDECREF(py_code); + Py_XDECREF(py_frame); +} +#endif + +/* CIntFromPyVerify */ +#define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value)\ + __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 0) +#define __PYX_VERIFY_RETURN_INT_EXC(target_type, func_type, func_value)\ + __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 1) +#define __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, exc)\ + {\ + func_type value = func_value;\ + if (sizeof(target_type) < sizeof(func_type)) {\ + if (unlikely(value != (func_type) (target_type) value)) {\ + func_type zero = 0;\ + if (exc && unlikely(value == (func_type)-1 && PyErr_Occurred()))\ + return (target_type) -1;\ + if (is_unsigned && unlikely(value < zero))\ + goto raise_neg_overflow;\ + else\ + goto raise_overflow;\ + }\ + }\ + return (target_type) value;\ + } + +/* CIntToPy */ +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const long neg_one = (long) -1, const_zero = (long) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(long) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(long) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); +#ifdef HAVE_LONG_LONG + } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); +#endif + } + } else { + if (sizeof(long) <= sizeof(long)) { + return PyInt_FromLong((long) value); +#ifdef HAVE_LONG_LONG + } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { + return PyLong_FromLongLong((PY_LONG_LONG) value); +#endif + } + } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; +#if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030d0000 + return _PyLong_FromByteArray(bytes, sizeof(long), + little, !is_unsigned); +#else + PyObject *from_bytes, *result = NULL; + PyObject *py_bytes = NULL, *arg_tuple = NULL, *kwds = NULL, *order_str = NULL; + from_bytes = PyObject_GetAttrString((PyObject*)&PyLong_Type, "from_bytes"); + if (!from_bytes) return NULL; + py_bytes = PyBytes_FromStringAndSize((char*)bytes, sizeof(long)); + if (!py_bytes) goto limited_bad; + order_str = PyUnicode_FromString(little ? "little" : "big"); + if (!order_str) goto limited_bad; + arg_tuple = PyTuple_Pack(2, py_bytes, order_str); + if (!arg_tuple) goto limited_bad; + if (!is_unsigned) { + kwds = PyDict_New(); + if (!kwds) goto limited_bad; + if (PyDict_SetItemString(kwds, "signed", __Pyx_NewRef(Py_True))) goto limited_bad; + } + result = PyObject_Call(from_bytes, arg_tuple, kwds); + limited_bad: + Py_XDECREF(kwds); + Py_XDECREF(arg_tuple); + Py_XDECREF(order_str); + Py_XDECREF(py_bytes); + Py_XDECREF(from_bytes); + return result; +#endif + } +} + +/* CIntFromPy */ +static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const long neg_one = (long) -1, const_zero = (long) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if ((sizeof(long) < sizeof(long))) { + __PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG(x)) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + goto raise_neg_overflow; + } + return (long) val; + } + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_USE_PYLONG_INTERNALS + if (unlikely(__Pyx_PyLong_IsNeg(x))) { + goto raise_neg_overflow; + } else if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(long, __Pyx_compact_upylong, __Pyx_PyLong_CompactValueUnsigned(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_DigitCount(x)) { + case 2: + if ((8 * sizeof(long) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) >= 2 * PyLong_SHIFT)) { + return (long) (((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); + } + } + break; + case 3: + if ((8 * sizeof(long) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) >= 3 * PyLong_SHIFT)) { + return (long) (((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); + } + } + break; + case 4: + if ((8 * sizeof(long) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) >= 4 * PyLong_SHIFT)) { + return (long) (((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); + } + } + break; + } + } +#endif +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A7 + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (long) -1; + if (unlikely(result == 1)) + goto raise_neg_overflow; + } +#endif + if ((sizeof(long) <= sizeof(unsigned long))) { + __PYX_VERIFY_RETURN_INT_EXC(long, unsigned long, PyLong_AsUnsignedLong(x)) +#ifdef HAVE_LONG_LONG + } else if ((sizeof(long) <= sizeof(unsigned PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(long, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) +#endif + } + } else { +#if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(long, __Pyx_compact_pylong, __Pyx_PyLong_CompactValue(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_SignedDigitCount(x)) { + case -2: + if ((8 * sizeof(long) - 1 > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 2 * PyLong_SHIFT)) { + return (long) (((long)-1)*(((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case 2: + if ((8 * sizeof(long) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 2 * PyLong_SHIFT)) { + return (long) ((((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case -3: + if ((8 * sizeof(long) - 1 > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 3 * PyLong_SHIFT)) { + return (long) (((long)-1)*(((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case 3: + if ((8 * sizeof(long) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 3 * PyLong_SHIFT)) { + return (long) ((((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case -4: + if ((8 * sizeof(long) - 1 > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 4 * PyLong_SHIFT)) { + return (long) (((long)-1)*(((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case 4: + if ((8 * sizeof(long) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 4 * PyLong_SHIFT)) { + return (long) ((((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + } + } +#endif + if ((sizeof(long) <= sizeof(long))) { + __PYX_VERIFY_RETURN_INT_EXC(long, long, PyLong_AsLong(x)) +#ifdef HAVE_LONG_LONG + } else if ((sizeof(long) <= sizeof(PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(long, PY_LONG_LONG, PyLong_AsLongLong(x)) +#endif + } + } + { + long val; + PyObject *v = __Pyx_PyNumber_IntOrLong(x); +#if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } +#endif + if (likely(v)) { + int ret = -1; +#if PY_VERSION_HEX < 0x030d0000 && !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API) || defined(_PyLong_AsByteArray) + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); +#else + PyObject *stepval = NULL, *mask = NULL, *shift = NULL; + int bits, remaining_bits, is_negative = 0; + long idigit; + int chunk_size = (sizeof(long) < 8) ? 30 : 62; + if (unlikely(!PyLong_CheckExact(v))) { + PyObject *tmp = v; + v = PyNumber_Long(v); + assert(PyLong_CheckExact(v)); + Py_DECREF(tmp); + if (unlikely(!v)) return (long) -1; + } +#if CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030B0000 + if (Py_SIZE(x) == 0) + return (long) 0; + is_negative = Py_SIZE(x) < 0; +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (long) -1; + is_negative = result == 1; + } +#endif + if (is_unsigned && unlikely(is_negative)) { + goto raise_neg_overflow; + } else if (is_negative) { + stepval = PyNumber_Invert(v); + if (unlikely(!stepval)) + return (long) -1; + } else { + stepval = __Pyx_NewRef(v); + } + val = (long) 0; + mask = PyLong_FromLong((1L << chunk_size) - 1); if (unlikely(!mask)) goto done; + shift = PyLong_FromLong(chunk_size); if (unlikely(!shift)) goto done; + for (bits = 0; bits < (int) sizeof(long) * 8 - chunk_size; bits += chunk_size) { + PyObject *tmp, *digit; + digit = PyNumber_And(stepval, mask); + if (unlikely(!digit)) goto done; + idigit = PyLong_AsLong(digit); + Py_DECREF(digit); + if (unlikely(idigit < 0)) goto done; + tmp = PyNumber_Rshift(stepval, shift); + if (unlikely(!tmp)) goto done; + Py_DECREF(stepval); stepval = tmp; + val |= ((long) idigit) << bits; + #if CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030B0000 + if (Py_SIZE(stepval) == 0) + goto unpacking_done; + #endif + } + idigit = PyLong_AsLong(stepval); + if (unlikely(idigit < 0)) goto done; + remaining_bits = ((int) sizeof(long) * 8) - bits - (is_unsigned ? 0 : 1); + if (unlikely(idigit >= (1L << remaining_bits))) + goto raise_overflow; + val |= ((long) idigit) << bits; + #if CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030B0000 + unpacking_done: + #endif + if (!is_unsigned) { + if (unlikely(val & (((long) 1) << (sizeof(long) * 8 - 1)))) + goto raise_overflow; + if (is_negative) + val = ~val; + } + ret = 0; + done: + Py_XDECREF(shift); + Py_XDECREF(mask); + Py_XDECREF(stepval); +#endif + Py_DECREF(v); + if (likely(!ret)) + return val; + } + return (long) -1; + } + } else { + long val; + PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); + if (!tmp) return (long) -1; + val = __Pyx_PyInt_As_long(tmp); + Py_DECREF(tmp); + return val; + } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to long"); + return (long) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to long"); + return (long) -1; +} + +/* FormatTypeName */ +#if CYTHON_COMPILING_IN_LIMITED_API +static __Pyx_TypeName +__Pyx_PyType_GetName(PyTypeObject* tp) +{ + PyObject *name = __Pyx_PyObject_GetAttrStr((PyObject *)tp, + __pyx_n_s_name); + if (unlikely(name == NULL) || unlikely(!PyUnicode_Check(name))) { + PyErr_Clear(); + Py_XDECREF(name); + name = __Pyx_NewRef(__pyx_n_s__28); + } + return name; +} +#endif + +/* CIntFromPy */ +static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const int neg_one = (int) -1, const_zero = (int) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if ((sizeof(int) < sizeof(long))) { + __PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG(x)) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + goto raise_neg_overflow; + } + return (int) val; + } + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_USE_PYLONG_INTERNALS + if (unlikely(__Pyx_PyLong_IsNeg(x))) { + goto raise_neg_overflow; + } else if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(int, __Pyx_compact_upylong, __Pyx_PyLong_CompactValueUnsigned(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_DigitCount(x)) { + case 2: + if ((8 * sizeof(int) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) >= 2 * PyLong_SHIFT)) { + return (int) (((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); + } + } + break; + case 3: + if ((8 * sizeof(int) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) >= 3 * PyLong_SHIFT)) { + return (int) (((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); + } + } + break; + case 4: + if ((8 * sizeof(int) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) >= 4 * PyLong_SHIFT)) { + return (int) (((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); + } + } + break; + } + } +#endif +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A7 + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (int) -1; + if (unlikely(result == 1)) + goto raise_neg_overflow; + } +#endif + if ((sizeof(int) <= sizeof(unsigned long))) { + __PYX_VERIFY_RETURN_INT_EXC(int, unsigned long, PyLong_AsUnsignedLong(x)) +#ifdef HAVE_LONG_LONG + } else if ((sizeof(int) <= sizeof(unsigned PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(int, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) +#endif + } + } else { +#if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(int, __Pyx_compact_pylong, __Pyx_PyLong_CompactValue(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_SignedDigitCount(x)) { + case -2: + if ((8 * sizeof(int) - 1 > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 2 * PyLong_SHIFT)) { + return (int) (((int)-1)*(((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case 2: + if ((8 * sizeof(int) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 2 * PyLong_SHIFT)) { + return (int) ((((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case -3: + if ((8 * sizeof(int) - 1 > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 3 * PyLong_SHIFT)) { + return (int) (((int)-1)*(((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case 3: + if ((8 * sizeof(int) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 3 * PyLong_SHIFT)) { + return (int) ((((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case -4: + if ((8 * sizeof(int) - 1 > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 4 * PyLong_SHIFT)) { + return (int) (((int)-1)*(((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case 4: + if ((8 * sizeof(int) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 4 * PyLong_SHIFT)) { + return (int) ((((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + } + } +#endif + if ((sizeof(int) <= sizeof(long))) { + __PYX_VERIFY_RETURN_INT_EXC(int, long, PyLong_AsLong(x)) +#ifdef HAVE_LONG_LONG + } else if ((sizeof(int) <= sizeof(PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(int, PY_LONG_LONG, PyLong_AsLongLong(x)) +#endif + } + } + { + int val; + PyObject *v = __Pyx_PyNumber_IntOrLong(x); +#if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } +#endif + if (likely(v)) { + int ret = -1; +#if PY_VERSION_HEX < 0x030d0000 && !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API) || defined(_PyLong_AsByteArray) + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); +#else + PyObject *stepval = NULL, *mask = NULL, *shift = NULL; + int bits, remaining_bits, is_negative = 0; + long idigit; + int chunk_size = (sizeof(long) < 8) ? 30 : 62; + if (unlikely(!PyLong_CheckExact(v))) { + PyObject *tmp = v; + v = PyNumber_Long(v); + assert(PyLong_CheckExact(v)); + Py_DECREF(tmp); + if (unlikely(!v)) return (int) -1; + } +#if CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030B0000 + if (Py_SIZE(x) == 0) + return (int) 0; + is_negative = Py_SIZE(x) < 0; +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (int) -1; + is_negative = result == 1; + } +#endif + if (is_unsigned && unlikely(is_negative)) { + goto raise_neg_overflow; + } else if (is_negative) { + stepval = PyNumber_Invert(v); + if (unlikely(!stepval)) + return (int) -1; + } else { + stepval = __Pyx_NewRef(v); + } + val = (int) 0; + mask = PyLong_FromLong((1L << chunk_size) - 1); if (unlikely(!mask)) goto done; + shift = PyLong_FromLong(chunk_size); if (unlikely(!shift)) goto done; + for (bits = 0; bits < (int) sizeof(int) * 8 - chunk_size; bits += chunk_size) { + PyObject *tmp, *digit; + digit = PyNumber_And(stepval, mask); + if (unlikely(!digit)) goto done; + idigit = PyLong_AsLong(digit); + Py_DECREF(digit); + if (unlikely(idigit < 0)) goto done; + tmp = PyNumber_Rshift(stepval, shift); + if (unlikely(!tmp)) goto done; + Py_DECREF(stepval); stepval = tmp; + val |= ((int) idigit) << bits; + #if CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030B0000 + if (Py_SIZE(stepval) == 0) + goto unpacking_done; + #endif + } + idigit = PyLong_AsLong(stepval); + if (unlikely(idigit < 0)) goto done; + remaining_bits = ((int) sizeof(int) * 8) - bits - (is_unsigned ? 0 : 1); + if (unlikely(idigit >= (1L << remaining_bits))) + goto raise_overflow; + val |= ((int) idigit) << bits; + #if CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030B0000 + unpacking_done: + #endif + if (!is_unsigned) { + if (unlikely(val & (((int) 1) << (sizeof(int) * 8 - 1)))) + goto raise_overflow; + if (is_negative) + val = ~val; + } + ret = 0; + done: + Py_XDECREF(shift); + Py_XDECREF(mask); + Py_XDECREF(stepval); +#endif + Py_DECREF(v); + if (likely(!ret)) + return val; + } + return (int) -1; + } + } else { + int val; + PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); + if (!tmp) return (int) -1; + val = __Pyx_PyInt_As_int(tmp); + Py_DECREF(tmp); + return val; + } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to int"); + return (int) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to int"); + return (int) -1; +} + +/* FastTypeChecks */ +#if CYTHON_COMPILING_IN_CPYTHON +static int __Pyx_InBases(PyTypeObject *a, PyTypeObject *b) { + while (a) { + a = __Pyx_PyType_GetSlot(a, tp_base, PyTypeObject*); + if (a == b) + return 1; + } + return b == &PyBaseObject_Type; +} +static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b) { + PyObject *mro; + if (a == b) return 1; + mro = a->tp_mro; + if (likely(mro)) { + Py_ssize_t i, n; + n = PyTuple_GET_SIZE(mro); + for (i = 0; i < n; i++) { + if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b) + return 1; + } + return 0; + } + return __Pyx_InBases(a, b); +} +static CYTHON_INLINE int __Pyx_IsAnySubtype2(PyTypeObject *cls, PyTypeObject *a, PyTypeObject *b) { + PyObject *mro; + if (cls == a || cls == b) return 1; + mro = cls->tp_mro; + if (likely(mro)) { + Py_ssize_t i, n; + n = PyTuple_GET_SIZE(mro); + for (i = 0; i < n; i++) { + PyObject *base = PyTuple_GET_ITEM(mro, i); + if (base == (PyObject *)a || base == (PyObject *)b) + return 1; + } + return 0; + } + return __Pyx_InBases(cls, a) || __Pyx_InBases(cls, b); +} +#if PY_MAJOR_VERSION == 2 +static int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject* exc_type2) { + PyObject *exception, *value, *tb; + int res; + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + __Pyx_ErrFetch(&exception, &value, &tb); + res = exc_type1 ? PyObject_IsSubclass(err, exc_type1) : 0; + if (unlikely(res == -1)) { + PyErr_WriteUnraisable(err); + res = 0; + } + if (!res) { + res = PyObject_IsSubclass(err, exc_type2); + if (unlikely(res == -1)) { + PyErr_WriteUnraisable(err); + res = 0; + } + } + __Pyx_ErrRestore(exception, value, tb); + return res; +} +#else +static CYTHON_INLINE int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject *exc_type2) { + if (exc_type1) { + return __Pyx_IsAnySubtype2((PyTypeObject*)err, (PyTypeObject*)exc_type1, (PyTypeObject*)exc_type2); + } else { + return __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type2); + } +} +#endif +static int __Pyx_PyErr_GivenExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { + Py_ssize_t i, n; + assert(PyExceptionClass_Check(exc_type)); + n = PyTuple_GET_SIZE(tuple); +#if PY_MAJOR_VERSION >= 3 + for (i=0; i= 0x030B00a4 + _PyErr_StackItem *exc_info = tstate->exc_info; + tmp_value = exc_info->exc_value; + exc_info->exc_value = *value; + if (tmp_value == NULL || tmp_value == Py_None) { + Py_XDECREF(tmp_value); + tmp_value = NULL; + tmp_type = NULL; + tmp_tb = NULL; + } else { + tmp_type = (PyObject*) Py_TYPE(tmp_value); + Py_INCREF(tmp_type); + #if CYTHON_COMPILING_IN_CPYTHON + tmp_tb = ((PyBaseExceptionObject*) tmp_value)->traceback; + Py_XINCREF(tmp_tb); + #else + tmp_tb = PyException_GetTraceback(tmp_value); + #endif + } + #elif CYTHON_USE_EXC_INFO_STACK + _PyErr_StackItem *exc_info = tstate->exc_info; + tmp_type = exc_info->exc_type; + tmp_value = exc_info->exc_value; + tmp_tb = exc_info->exc_traceback; + exc_info->exc_type = *type; + exc_info->exc_value = *value; + exc_info->exc_traceback = *tb; + #else + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = *type; + tstate->exc_value = *value; + tstate->exc_traceback = *tb; + #endif + *type = tmp_type; + *value = tmp_value; + *tb = tmp_tb; +} +#else +static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb) { + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyErr_GetExcInfo(&tmp_type, &tmp_value, &tmp_tb); + PyErr_SetExcInfo(*type, *value, *tb); + *type = tmp_type; + *value = tmp_value; + *tb = tmp_tb; +} +#endif + +/* CoroutineBase */ +#include +#if PY_VERSION_HEX >= 0x030b00a6 + #ifndef Py_BUILD_CORE + #define Py_BUILD_CORE 1 + #endif + #include "internal/pycore_frame.h" +#endif +#define __Pyx_Coroutine_Undelegate(gen) Py_CLEAR((gen)->yieldfrom) +static int __Pyx_PyGen__FetchStopIterationValue(PyThreadState *__pyx_tstate, PyObject **pvalue) { + PyObject *et, *ev, *tb; + PyObject *value = NULL; + CYTHON_UNUSED_VAR(__pyx_tstate); + __Pyx_ErrFetch(&et, &ev, &tb); + if (!et) { + Py_XDECREF(tb); + Py_XDECREF(ev); + Py_INCREF(Py_None); + *pvalue = Py_None; + return 0; + } + if (likely(et == PyExc_StopIteration)) { + if (!ev) { + Py_INCREF(Py_None); + value = Py_None; + } +#if PY_VERSION_HEX >= 0x030300A0 + else if (likely(__Pyx_IS_TYPE(ev, (PyTypeObject*)PyExc_StopIteration))) { + value = ((PyStopIterationObject *)ev)->value; + Py_INCREF(value); + Py_DECREF(ev); + } +#endif + else if (unlikely(PyTuple_Check(ev))) { + if (PyTuple_GET_SIZE(ev) >= 1) { +#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + value = PyTuple_GET_ITEM(ev, 0); + Py_INCREF(value); +#else + value = PySequence_ITEM(ev, 0); +#endif + } else { + Py_INCREF(Py_None); + value = Py_None; + } + Py_DECREF(ev); + } + else if (!__Pyx_TypeCheck(ev, (PyTypeObject*)PyExc_StopIteration)) { + value = ev; + } + if (likely(value)) { + Py_XDECREF(tb); + Py_DECREF(et); + *pvalue = value; + return 0; + } + } else if (!__Pyx_PyErr_GivenExceptionMatches(et, PyExc_StopIteration)) { + __Pyx_ErrRestore(et, ev, tb); + return -1; + } + PyErr_NormalizeException(&et, &ev, &tb); + if (unlikely(!PyObject_TypeCheck(ev, (PyTypeObject*)PyExc_StopIteration))) { + __Pyx_ErrRestore(et, ev, tb); + return -1; + } + Py_XDECREF(tb); + Py_DECREF(et); +#if PY_VERSION_HEX >= 0x030300A0 + value = ((PyStopIterationObject *)ev)->value; + Py_INCREF(value); + Py_DECREF(ev); +#else + { + PyObject* args = __Pyx_PyObject_GetAttrStr(ev, __pyx_n_s_args); + Py_DECREF(ev); + if (likely(args)) { + value = PySequence_GetItem(args, 0); + Py_DECREF(args); + } + if (unlikely(!value)) { + __Pyx_ErrRestore(NULL, NULL, NULL); + Py_INCREF(Py_None); + value = Py_None; + } + } +#endif + *pvalue = value; + return 0; +} +static CYTHON_INLINE +void __Pyx_Coroutine_ExceptionClear(__Pyx_ExcInfoStruct *exc_state) { +#if PY_VERSION_HEX >= 0x030B00a4 + Py_CLEAR(exc_state->exc_value); +#else + PyObject *t, *v, *tb; + t = exc_state->exc_type; + v = exc_state->exc_value; + tb = exc_state->exc_traceback; + exc_state->exc_type = NULL; + exc_state->exc_value = NULL; + exc_state->exc_traceback = NULL; + Py_XDECREF(t); + Py_XDECREF(v); + Py_XDECREF(tb); +#endif +} +#define __Pyx_Coroutine_AlreadyRunningError(gen) (__Pyx__Coroutine_AlreadyRunningError(gen), (PyObject*)NULL) +static void __Pyx__Coroutine_AlreadyRunningError(__pyx_CoroutineObject *gen) { + const char *msg; + CYTHON_MAYBE_UNUSED_VAR(gen); + if ((0)) { + #ifdef __Pyx_Coroutine_USED + } else if (__Pyx_Coroutine_Check((PyObject*)gen)) { + msg = "coroutine already executing"; + #endif + #ifdef __Pyx_AsyncGen_USED + } else if (__Pyx_AsyncGen_CheckExact((PyObject*)gen)) { + msg = "async generator already executing"; + #endif + } else { + msg = "generator already executing"; + } + PyErr_SetString(PyExc_ValueError, msg); +} +#define __Pyx_Coroutine_NotStartedError(gen) (__Pyx__Coroutine_NotStartedError(gen), (PyObject*)NULL) +static void __Pyx__Coroutine_NotStartedError(PyObject *gen) { + const char *msg; + CYTHON_MAYBE_UNUSED_VAR(gen); + if ((0)) { + #ifdef __Pyx_Coroutine_USED + } else if (__Pyx_Coroutine_Check(gen)) { + msg = "can't send non-None value to a just-started coroutine"; + #endif + #ifdef __Pyx_AsyncGen_USED + } else if (__Pyx_AsyncGen_CheckExact(gen)) { + msg = "can't send non-None value to a just-started async generator"; + #endif + } else { + msg = "can't send non-None value to a just-started generator"; + } + PyErr_SetString(PyExc_TypeError, msg); +} +#define __Pyx_Coroutine_AlreadyTerminatedError(gen, value, closing) (__Pyx__Coroutine_AlreadyTerminatedError(gen, value, closing), (PyObject*)NULL) +static void __Pyx__Coroutine_AlreadyTerminatedError(PyObject *gen, PyObject *value, int closing) { + CYTHON_MAYBE_UNUSED_VAR(gen); + CYTHON_MAYBE_UNUSED_VAR(closing); + #ifdef __Pyx_Coroutine_USED + if (!closing && __Pyx_Coroutine_Check(gen)) { + PyErr_SetString(PyExc_RuntimeError, "cannot reuse already awaited coroutine"); + } else + #endif + if (value) { + #ifdef __Pyx_AsyncGen_USED + if (__Pyx_AsyncGen_CheckExact(gen)) + PyErr_SetNone(__Pyx_PyExc_StopAsyncIteration); + else + #endif + PyErr_SetNone(PyExc_StopIteration); + } +} +static +PyObject *__Pyx_Coroutine_SendEx(__pyx_CoroutineObject *self, PyObject *value, int closing) { + __Pyx_PyThreadState_declare + PyThreadState *tstate; + __Pyx_ExcInfoStruct *exc_state; + PyObject *retval; + assert(!self->is_running); + if (unlikely(self->resume_label == 0)) { + if (unlikely(value && value != Py_None)) { + return __Pyx_Coroutine_NotStartedError((PyObject*)self); + } + } + if (unlikely(self->resume_label == -1)) { + return __Pyx_Coroutine_AlreadyTerminatedError((PyObject*)self, value, closing); + } +#if CYTHON_FAST_THREAD_STATE + __Pyx_PyThreadState_assign + tstate = __pyx_tstate; +#else + tstate = __Pyx_PyThreadState_Current; +#endif + exc_state = &self->gi_exc_state; + if (exc_state->exc_value) { + #if CYTHON_COMPILING_IN_PYPY + #else + PyObject *exc_tb; + #if PY_VERSION_HEX >= 0x030B00a4 && !CYTHON_COMPILING_IN_CPYTHON + exc_tb = PyException_GetTraceback(exc_state->exc_value); + #elif PY_VERSION_HEX >= 0x030B00a4 + exc_tb = ((PyBaseExceptionObject*) exc_state->exc_value)->traceback; + #else + exc_tb = exc_state->exc_traceback; + #endif + if (exc_tb) { + PyTracebackObject *tb = (PyTracebackObject *) exc_tb; + PyFrameObject *f = tb->tb_frame; + assert(f->f_back == NULL); + #if PY_VERSION_HEX >= 0x030B00A1 + f->f_back = PyThreadState_GetFrame(tstate); + #else + Py_XINCREF(tstate->frame); + f->f_back = tstate->frame; + #endif + #if PY_VERSION_HEX >= 0x030B00a4 && !CYTHON_COMPILING_IN_CPYTHON + Py_DECREF(exc_tb); + #endif + } + #endif + } +#if CYTHON_USE_EXC_INFO_STACK + exc_state->previous_item = tstate->exc_info; + tstate->exc_info = exc_state; +#else + if (exc_state->exc_type) { + __Pyx_ExceptionSwap(&exc_state->exc_type, &exc_state->exc_value, &exc_state->exc_traceback); + } else { + __Pyx_Coroutine_ExceptionClear(exc_state); + __Pyx_ExceptionSave(&exc_state->exc_type, &exc_state->exc_value, &exc_state->exc_traceback); + } +#endif + self->is_running = 1; + retval = self->body(self, tstate, value); + self->is_running = 0; +#if CYTHON_USE_EXC_INFO_STACK + exc_state = &self->gi_exc_state; + tstate->exc_info = exc_state->previous_item; + exc_state->previous_item = NULL; + __Pyx_Coroutine_ResetFrameBackpointer(exc_state); +#endif + return retval; +} +static CYTHON_INLINE void __Pyx_Coroutine_ResetFrameBackpointer(__Pyx_ExcInfoStruct *exc_state) { +#if CYTHON_COMPILING_IN_PYPY + CYTHON_UNUSED_VAR(exc_state); +#else + PyObject *exc_tb; + #if PY_VERSION_HEX >= 0x030B00a4 + if (!exc_state->exc_value) return; + exc_tb = PyException_GetTraceback(exc_state->exc_value); + #else + exc_tb = exc_state->exc_traceback; + #endif + if (likely(exc_tb)) { + PyTracebackObject *tb = (PyTracebackObject *) exc_tb; + PyFrameObject *f = tb->tb_frame; + Py_CLEAR(f->f_back); + #if PY_VERSION_HEX >= 0x030B00a4 + Py_DECREF(exc_tb); + #endif + } +#endif +} +static CYTHON_INLINE +PyObject *__Pyx_Coroutine_MethodReturn(PyObject* gen, PyObject *retval) { + CYTHON_MAYBE_UNUSED_VAR(gen); + if (unlikely(!retval)) { + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + if (!__Pyx_PyErr_Occurred()) { + PyObject *exc = PyExc_StopIteration; + #ifdef __Pyx_AsyncGen_USED + if (__Pyx_AsyncGen_CheckExact(gen)) + exc = __Pyx_PyExc_StopAsyncIteration; + #endif + __Pyx_PyErr_SetNone(exc); + } + } + return retval; +} +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x03030000 && (defined(__linux__) || PY_VERSION_HEX >= 0x030600B3) +static CYTHON_INLINE +PyObject *__Pyx_PyGen_Send(PyGenObject *gen, PyObject *arg) { +#if PY_VERSION_HEX <= 0x030A00A1 + return _PyGen_Send(gen, arg); +#else + PyObject *result; + if (PyIter_Send((PyObject*)gen, arg ? arg : Py_None, &result) == PYGEN_RETURN) { + if (PyAsyncGen_CheckExact(gen)) { + assert(result == Py_None); + PyErr_SetNone(PyExc_StopAsyncIteration); + } + else if (result == Py_None) { + PyErr_SetNone(PyExc_StopIteration); + } + else { +#if PY_VERSION_HEX < 0x030d00A1 + _PyGen_SetStopIterationValue(result); +#else + if (!PyTuple_Check(result) && !PyExceptionInstance_Check(result)) { + PyErr_SetObject(PyExc_StopIteration, result); + } else { + PyObject *exc = __Pyx_PyObject_CallOneArg(PyExc_StopIteration, result); + if (likely(exc != NULL)) { + PyErr_SetObject(PyExc_StopIteration, exc); + Py_DECREF(exc); + } + } +#endif + } + Py_DECREF(result); + result = NULL; + } + return result; +#endif +} +#endif +static CYTHON_INLINE +PyObject *__Pyx_Coroutine_FinishDelegation(__pyx_CoroutineObject *gen) { + PyObject *ret; + PyObject *val = NULL; + __Pyx_Coroutine_Undelegate(gen); + __Pyx_PyGen__FetchStopIterationValue(__Pyx_PyThreadState_Current, &val); + ret = __Pyx_Coroutine_SendEx(gen, val, 0); + Py_XDECREF(val); + return ret; +} +static PyObject *__Pyx_Coroutine_Send(PyObject *self, PyObject *value) { + PyObject *retval; + __pyx_CoroutineObject *gen = (__pyx_CoroutineObject*) self; + PyObject *yf = gen->yieldfrom; + if (unlikely(gen->is_running)) + return __Pyx_Coroutine_AlreadyRunningError(gen); + if (yf) { + PyObject *ret; + gen->is_running = 1; + #ifdef __Pyx_Generator_USED + if (__Pyx_Generator_CheckExact(yf)) { + ret = __Pyx_Coroutine_Send(yf, value); + } else + #endif + #ifdef __Pyx_Coroutine_USED + if (__Pyx_Coroutine_Check(yf)) { + ret = __Pyx_Coroutine_Send(yf, value); + } else + #endif + #ifdef __Pyx_AsyncGen_USED + if (__pyx_PyAsyncGenASend_CheckExact(yf)) { + ret = __Pyx_async_gen_asend_send(yf, value); + } else + #endif + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x03030000 && (defined(__linux__) || PY_VERSION_HEX >= 0x030600B3) + if (PyGen_CheckExact(yf)) { + ret = __Pyx_PyGen_Send((PyGenObject*)yf, value == Py_None ? NULL : value); + } else + #endif + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x03050000 && defined(PyCoro_CheckExact) && (defined(__linux__) || PY_VERSION_HEX >= 0x030600B3) + if (PyCoro_CheckExact(yf)) { + ret = __Pyx_PyGen_Send((PyGenObject*)yf, value == Py_None ? NULL : value); + } else + #endif + { + if (value == Py_None) + ret = __Pyx_PyObject_GetIterNextFunc(yf)(yf); + else + ret = __Pyx_PyObject_CallMethod1(yf, __pyx_n_s_send, value); + } + gen->is_running = 0; + if (likely(ret)) { + return ret; + } + retval = __Pyx_Coroutine_FinishDelegation(gen); + } else { + retval = __Pyx_Coroutine_SendEx(gen, value, 0); + } + return __Pyx_Coroutine_MethodReturn(self, retval); +} +static int __Pyx_Coroutine_CloseIter(__pyx_CoroutineObject *gen, PyObject *yf) { + PyObject *retval = NULL; + int err = 0; + #ifdef __Pyx_Generator_USED + if (__Pyx_Generator_CheckExact(yf)) { + retval = __Pyx_Coroutine_Close(yf); + if (!retval) + return -1; + } else + #endif + #ifdef __Pyx_Coroutine_USED + if (__Pyx_Coroutine_Check(yf)) { + retval = __Pyx_Coroutine_Close(yf); + if (!retval) + return -1; + } else + if (__Pyx_CoroutineAwait_CheckExact(yf)) { + retval = __Pyx_CoroutineAwait_Close((__pyx_CoroutineAwaitObject*)yf, NULL); + if (!retval) + return -1; + } else + #endif + #ifdef __Pyx_AsyncGen_USED + if (__pyx_PyAsyncGenASend_CheckExact(yf)) { + retval = __Pyx_async_gen_asend_close(yf, NULL); + } else + if (__pyx_PyAsyncGenAThrow_CheckExact(yf)) { + retval = __Pyx_async_gen_athrow_close(yf, NULL); + } else + #endif + { + PyObject *meth; + gen->is_running = 1; + meth = __Pyx_PyObject_GetAttrStrNoError(yf, __pyx_n_s_close); + if (unlikely(!meth)) { + if (unlikely(PyErr_Occurred())) { + PyErr_WriteUnraisable(yf); + } + } else { + retval = __Pyx_PyObject_CallNoArg(meth); + Py_DECREF(meth); + if (unlikely(!retval)) + err = -1; + } + gen->is_running = 0; + } + Py_XDECREF(retval); + return err; +} +static PyObject *__Pyx_Generator_Next(PyObject *self) { + __pyx_CoroutineObject *gen = (__pyx_CoroutineObject*) self; + PyObject *yf = gen->yieldfrom; + if (unlikely(gen->is_running)) + return __Pyx_Coroutine_AlreadyRunningError(gen); + if (yf) { + PyObject *ret; + gen->is_running = 1; + #ifdef __Pyx_Generator_USED + if (__Pyx_Generator_CheckExact(yf)) { + ret = __Pyx_Generator_Next(yf); + } else + #endif + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x03030000 && (defined(__linux__) || PY_VERSION_HEX >= 0x030600B3) + if (PyGen_CheckExact(yf)) { + ret = __Pyx_PyGen_Send((PyGenObject*)yf, NULL); + } else + #endif + #ifdef __Pyx_Coroutine_USED + if (__Pyx_Coroutine_Check(yf)) { + ret = __Pyx_Coroutine_Send(yf, Py_None); + } else + #endif + ret = __Pyx_PyObject_GetIterNextFunc(yf)(yf); + gen->is_running = 0; + if (likely(ret)) { + return ret; + } + return __Pyx_Coroutine_FinishDelegation(gen); + } + return __Pyx_Coroutine_SendEx(gen, Py_None, 0); +} +static PyObject *__Pyx_Coroutine_Close_Method(PyObject *self, PyObject *arg) { + CYTHON_UNUSED_VAR(arg); + return __Pyx_Coroutine_Close(self); +} +static PyObject *__Pyx_Coroutine_Close(PyObject *self) { + __pyx_CoroutineObject *gen = (__pyx_CoroutineObject *) self; + PyObject *retval, *raised_exception; + PyObject *yf = gen->yieldfrom; + int err = 0; + if (unlikely(gen->is_running)) + return __Pyx_Coroutine_AlreadyRunningError(gen); + if (yf) { + Py_INCREF(yf); + err = __Pyx_Coroutine_CloseIter(gen, yf); + __Pyx_Coroutine_Undelegate(gen); + Py_DECREF(yf); + } + if (err == 0) + PyErr_SetNone(PyExc_GeneratorExit); + retval = __Pyx_Coroutine_SendEx(gen, NULL, 1); + if (unlikely(retval)) { + const char *msg; + Py_DECREF(retval); + if ((0)) { + #ifdef __Pyx_Coroutine_USED + } else if (__Pyx_Coroutine_Check(self)) { + msg = "coroutine ignored GeneratorExit"; + #endif + #ifdef __Pyx_AsyncGen_USED + } else if (__Pyx_AsyncGen_CheckExact(self)) { +#if PY_VERSION_HEX < 0x03060000 + msg = "async generator ignored GeneratorExit - might require Python 3.6+ finalisation (PEP 525)"; +#else + msg = "async generator ignored GeneratorExit"; +#endif + #endif + } else { + msg = "generator ignored GeneratorExit"; + } + PyErr_SetString(PyExc_RuntimeError, msg); + return NULL; + } + raised_exception = PyErr_Occurred(); + if (likely(!raised_exception || __Pyx_PyErr_GivenExceptionMatches2(raised_exception, PyExc_GeneratorExit, PyExc_StopIteration))) { + if (raised_exception) PyErr_Clear(); + Py_INCREF(Py_None); + return Py_None; + } + return NULL; +} +static PyObject *__Pyx__Coroutine_Throw(PyObject *self, PyObject *typ, PyObject *val, PyObject *tb, + PyObject *args, int close_on_genexit) { + __pyx_CoroutineObject *gen = (__pyx_CoroutineObject *) self; + PyObject *yf = gen->yieldfrom; + if (unlikely(gen->is_running)) + return __Pyx_Coroutine_AlreadyRunningError(gen); + if (yf) { + PyObject *ret; + Py_INCREF(yf); + if (__Pyx_PyErr_GivenExceptionMatches(typ, PyExc_GeneratorExit) && close_on_genexit) { + int err = __Pyx_Coroutine_CloseIter(gen, yf); + Py_DECREF(yf); + __Pyx_Coroutine_Undelegate(gen); + if (err < 0) + return __Pyx_Coroutine_MethodReturn(self, __Pyx_Coroutine_SendEx(gen, NULL, 0)); + goto throw_here; + } + gen->is_running = 1; + if (0 + #ifdef __Pyx_Generator_USED + || __Pyx_Generator_CheckExact(yf) + #endif + #ifdef __Pyx_Coroutine_USED + || __Pyx_Coroutine_Check(yf) + #endif + ) { + ret = __Pyx__Coroutine_Throw(yf, typ, val, tb, args, close_on_genexit); + #ifdef __Pyx_Coroutine_USED + } else if (__Pyx_CoroutineAwait_CheckExact(yf)) { + ret = __Pyx__Coroutine_Throw(((__pyx_CoroutineAwaitObject*)yf)->coroutine, typ, val, tb, args, close_on_genexit); + #endif + } else { + PyObject *meth = __Pyx_PyObject_GetAttrStrNoError(yf, __pyx_n_s_throw); + if (unlikely(!meth)) { + Py_DECREF(yf); + if (unlikely(PyErr_Occurred())) { + gen->is_running = 0; + return NULL; + } + __Pyx_Coroutine_Undelegate(gen); + gen->is_running = 0; + goto throw_here; + } + if (likely(args)) { + ret = __Pyx_PyObject_Call(meth, args, NULL); + } else { + PyObject *cargs[4] = {NULL, typ, val, tb}; + ret = __Pyx_PyObject_FastCall(meth, cargs+1, 3 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET); + } + Py_DECREF(meth); + } + gen->is_running = 0; + Py_DECREF(yf); + if (!ret) { + ret = __Pyx_Coroutine_FinishDelegation(gen); + } + return __Pyx_Coroutine_MethodReturn(self, ret); + } +throw_here: + __Pyx_Raise(typ, val, tb, NULL); + return __Pyx_Coroutine_MethodReturn(self, __Pyx_Coroutine_SendEx(gen, NULL, 0)); +} +static PyObject *__Pyx_Coroutine_Throw(PyObject *self, PyObject *args) { + PyObject *typ; + PyObject *val = NULL; + PyObject *tb = NULL; + if (unlikely(!PyArg_UnpackTuple(args, (char *)"throw", 1, 3, &typ, &val, &tb))) + return NULL; + return __Pyx__Coroutine_Throw(self, typ, val, tb, args, 1); +} +static CYTHON_INLINE int __Pyx_Coroutine_traverse_excstate(__Pyx_ExcInfoStruct *exc_state, visitproc visit, void *arg) { +#if PY_VERSION_HEX >= 0x030B00a4 + Py_VISIT(exc_state->exc_value); +#else + Py_VISIT(exc_state->exc_type); + Py_VISIT(exc_state->exc_value); + Py_VISIT(exc_state->exc_traceback); +#endif + return 0; +} +static int __Pyx_Coroutine_traverse(__pyx_CoroutineObject *gen, visitproc visit, void *arg) { + Py_VISIT(gen->closure); + Py_VISIT(gen->classobj); + Py_VISIT(gen->yieldfrom); + return __Pyx_Coroutine_traverse_excstate(&gen->gi_exc_state, visit, arg); +} +static int __Pyx_Coroutine_clear(PyObject *self) { + __pyx_CoroutineObject *gen = (__pyx_CoroutineObject *) self; + Py_CLEAR(gen->closure); + Py_CLEAR(gen->classobj); + Py_CLEAR(gen->yieldfrom); + __Pyx_Coroutine_ExceptionClear(&gen->gi_exc_state); +#ifdef __Pyx_AsyncGen_USED + if (__Pyx_AsyncGen_CheckExact(self)) { + Py_CLEAR(((__pyx_PyAsyncGenObject*)gen)->ag_finalizer); + } +#endif + Py_CLEAR(gen->gi_code); + Py_CLEAR(gen->gi_frame); + Py_CLEAR(gen->gi_name); + Py_CLEAR(gen->gi_qualname); + Py_CLEAR(gen->gi_modulename); + return 0; +} +static void __Pyx_Coroutine_dealloc(PyObject *self) { + __pyx_CoroutineObject *gen = (__pyx_CoroutineObject *) self; + PyObject_GC_UnTrack(gen); + if (gen->gi_weakreflist != NULL) + PyObject_ClearWeakRefs(self); + if (gen->resume_label >= 0) { + PyObject_GC_Track(self); +#if PY_VERSION_HEX >= 0x030400a1 && CYTHON_USE_TP_FINALIZE + if (unlikely(PyObject_CallFinalizerFromDealloc(self))) +#else + Py_TYPE(gen)->tp_del(self); + if (unlikely(Py_REFCNT(self) > 0)) +#endif + { + return; + } + PyObject_GC_UnTrack(self); + } +#ifdef __Pyx_AsyncGen_USED + if (__Pyx_AsyncGen_CheckExact(self)) { + /* We have to handle this case for asynchronous generators + right here, because this code has to be between UNTRACK + and GC_Del. */ + Py_CLEAR(((__pyx_PyAsyncGenObject*)self)->ag_finalizer); + } +#endif + __Pyx_Coroutine_clear(self); + __Pyx_PyHeapTypeObject_GC_Del(gen); +} +static void __Pyx_Coroutine_del(PyObject *self) { + PyObject *error_type, *error_value, *error_traceback; + __pyx_CoroutineObject *gen = (__pyx_CoroutineObject *) self; + __Pyx_PyThreadState_declare + if (gen->resume_label < 0) { + return; + } +#if !CYTHON_USE_TP_FINALIZE + assert(self->ob_refcnt == 0); + __Pyx_SET_REFCNT(self, 1); +#endif + __Pyx_PyThreadState_assign + __Pyx_ErrFetch(&error_type, &error_value, &error_traceback); +#ifdef __Pyx_AsyncGen_USED + if (__Pyx_AsyncGen_CheckExact(self)) { + __pyx_PyAsyncGenObject *agen = (__pyx_PyAsyncGenObject*)self; + PyObject *finalizer = agen->ag_finalizer; + if (finalizer && !agen->ag_closed) { + PyObject *res = __Pyx_PyObject_CallOneArg(finalizer, self); + if (unlikely(!res)) { + PyErr_WriteUnraisable(self); + } else { + Py_DECREF(res); + } + __Pyx_ErrRestore(error_type, error_value, error_traceback); + return; + } + } +#endif + if (unlikely(gen->resume_label == 0 && !error_value)) { +#ifdef __Pyx_Coroutine_USED +#ifdef __Pyx_Generator_USED + if (!__Pyx_Generator_CheckExact(self)) +#endif + { + PyObject_GC_UnTrack(self); +#if PY_MAJOR_VERSION >= 3 || defined(PyErr_WarnFormat) + if (unlikely(PyErr_WarnFormat(PyExc_RuntimeWarning, 1, "coroutine '%.50S' was never awaited", gen->gi_qualname) < 0)) + PyErr_WriteUnraisable(self); +#else + {PyObject *msg; + char *cmsg; + #if CYTHON_COMPILING_IN_PYPY + msg = NULL; + cmsg = (char*) "coroutine was never awaited"; + #else + char *cname; + PyObject *qualname; + qualname = gen->gi_qualname; + cname = PyString_AS_STRING(qualname); + msg = PyString_FromFormat("coroutine '%.50s' was never awaited", cname); + if (unlikely(!msg)) { + PyErr_Clear(); + cmsg = (char*) "coroutine was never awaited"; + } else { + cmsg = PyString_AS_STRING(msg); + } + #endif + if (unlikely(PyErr_WarnEx(PyExc_RuntimeWarning, cmsg, 1) < 0)) + PyErr_WriteUnraisable(self); + Py_XDECREF(msg);} +#endif + PyObject_GC_Track(self); + } +#endif + } else { + PyObject *res = __Pyx_Coroutine_Close(self); + if (unlikely(!res)) { + if (PyErr_Occurred()) + PyErr_WriteUnraisable(self); + } else { + Py_DECREF(res); + } + } + __Pyx_ErrRestore(error_type, error_value, error_traceback); +#if !CYTHON_USE_TP_FINALIZE + assert(Py_REFCNT(self) > 0); + if (likely(--self->ob_refcnt == 0)) { + return; + } + { + Py_ssize_t refcnt = Py_REFCNT(self); + _Py_NewReference(self); + __Pyx_SET_REFCNT(self, refcnt); + } +#if CYTHON_COMPILING_IN_CPYTHON + assert(PyType_IS_GC(Py_TYPE(self)) && + _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED); + _Py_DEC_REFTOTAL; +#endif +#ifdef COUNT_ALLOCS + --Py_TYPE(self)->tp_frees; + --Py_TYPE(self)->tp_allocs; +#endif +#endif +} +static PyObject * +__Pyx_Coroutine_get_name(__pyx_CoroutineObject *self, void *context) +{ + PyObject *name = self->gi_name; + CYTHON_UNUSED_VAR(context); + if (unlikely(!name)) name = Py_None; + Py_INCREF(name); + return name; +} +static int +__Pyx_Coroutine_set_name(__pyx_CoroutineObject *self, PyObject *value, void *context) +{ + CYTHON_UNUSED_VAR(context); +#if PY_MAJOR_VERSION >= 3 + if (unlikely(value == NULL || !PyUnicode_Check(value))) +#else + if (unlikely(value == NULL || !PyString_Check(value))) +#endif + { + PyErr_SetString(PyExc_TypeError, + "__name__ must be set to a string object"); + return -1; + } + Py_INCREF(value); + __Pyx_Py_XDECREF_SET(self->gi_name, value); + return 0; +} +static PyObject * +__Pyx_Coroutine_get_qualname(__pyx_CoroutineObject *self, void *context) +{ + PyObject *name = self->gi_qualname; + CYTHON_UNUSED_VAR(context); + if (unlikely(!name)) name = Py_None; + Py_INCREF(name); + return name; +} +static int +__Pyx_Coroutine_set_qualname(__pyx_CoroutineObject *self, PyObject *value, void *context) +{ + CYTHON_UNUSED_VAR(context); +#if PY_MAJOR_VERSION >= 3 + if (unlikely(value == NULL || !PyUnicode_Check(value))) +#else + if (unlikely(value == NULL || !PyString_Check(value))) +#endif + { + PyErr_SetString(PyExc_TypeError, + "__qualname__ must be set to a string object"); + return -1; + } + Py_INCREF(value); + __Pyx_Py_XDECREF_SET(self->gi_qualname, value); + return 0; +} +static PyObject * +__Pyx_Coroutine_get_frame(__pyx_CoroutineObject *self, void *context) +{ + PyObject *frame = self->gi_frame; + CYTHON_UNUSED_VAR(context); + if (!frame) { + if (unlikely(!self->gi_code)) { + Py_RETURN_NONE; + } + frame = (PyObject *) PyFrame_New( + PyThreadState_Get(), /*PyThreadState *tstate,*/ + (PyCodeObject*) self->gi_code, /*PyCodeObject *code,*/ + __pyx_d, /*PyObject *globals,*/ + 0 /*PyObject *locals*/ + ); + if (unlikely(!frame)) + return NULL; + self->gi_frame = frame; + } + Py_INCREF(frame); + return frame; +} +static __pyx_CoroutineObject *__Pyx__Coroutine_New( + PyTypeObject* type, __pyx_coroutine_body_t body, PyObject *code, PyObject *closure, + PyObject *name, PyObject *qualname, PyObject *module_name) { + __pyx_CoroutineObject *gen = PyObject_GC_New(__pyx_CoroutineObject, type); + if (unlikely(!gen)) + return NULL; + return __Pyx__Coroutine_NewInit(gen, body, code, closure, name, qualname, module_name); +} +static __pyx_CoroutineObject *__Pyx__Coroutine_NewInit( + __pyx_CoroutineObject *gen, __pyx_coroutine_body_t body, PyObject *code, PyObject *closure, + PyObject *name, PyObject *qualname, PyObject *module_name) { + gen->body = body; + gen->closure = closure; + Py_XINCREF(closure); + gen->is_running = 0; + gen->resume_label = 0; + gen->classobj = NULL; + gen->yieldfrom = NULL; + #if PY_VERSION_HEX >= 0x030B00a4 + gen->gi_exc_state.exc_value = NULL; + #else + gen->gi_exc_state.exc_type = NULL; + gen->gi_exc_state.exc_value = NULL; + gen->gi_exc_state.exc_traceback = NULL; + #endif +#if CYTHON_USE_EXC_INFO_STACK + gen->gi_exc_state.previous_item = NULL; +#endif + gen->gi_weakreflist = NULL; + Py_XINCREF(qualname); + gen->gi_qualname = qualname; + Py_XINCREF(name); + gen->gi_name = name; + Py_XINCREF(module_name); + gen->gi_modulename = module_name; + Py_XINCREF(code); + gen->gi_code = code; + gen->gi_frame = NULL; + PyObject_GC_Track(gen); + return gen; +} + +/* PatchModuleWithCoroutine */ +static PyObject* __Pyx_Coroutine_patch_module(PyObject* module, const char* py_code) { +#if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED) + int result; + PyObject *globals, *result_obj; + globals = PyDict_New(); if (unlikely(!globals)) goto ignore; + result = PyDict_SetItemString(globals, "_cython_coroutine_type", + #ifdef __Pyx_Coroutine_USED + (PyObject*)__pyx_CoroutineType); + #else + Py_None); + #endif + if (unlikely(result < 0)) goto ignore; + result = PyDict_SetItemString(globals, "_cython_generator_type", + #ifdef __Pyx_Generator_USED + (PyObject*)__pyx_GeneratorType); + #else + Py_None); + #endif + if (unlikely(result < 0)) goto ignore; + if (unlikely(PyDict_SetItemString(globals, "_module", module) < 0)) goto ignore; + if (unlikely(PyDict_SetItemString(globals, "__builtins__", __pyx_b) < 0)) goto ignore; + result_obj = PyRun_String(py_code, Py_file_input, globals, globals); + if (unlikely(!result_obj)) goto ignore; + Py_DECREF(result_obj); + Py_DECREF(globals); + return module; +ignore: + Py_XDECREF(globals); + PyErr_WriteUnraisable(module); + if (unlikely(PyErr_WarnEx(PyExc_RuntimeWarning, "Cython module failed to patch module with custom type", 1) < 0)) { + Py_DECREF(module); + module = NULL; + } +#else + py_code++; +#endif + return module; +} + +/* PatchGeneratorABC */ +#ifndef CYTHON_REGISTER_ABCS +#define CYTHON_REGISTER_ABCS 1 +#endif +#if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED) +static PyObject* __Pyx_patch_abc_module(PyObject *module); +static PyObject* __Pyx_patch_abc_module(PyObject *module) { + module = __Pyx_Coroutine_patch_module( + module, "" +"if _cython_generator_type is not None:\n" +" try: Generator = _module.Generator\n" +" except AttributeError: pass\n" +" else: Generator.register(_cython_generator_type)\n" +"if _cython_coroutine_type is not None:\n" +" try: Coroutine = _module.Coroutine\n" +" except AttributeError: pass\n" +" else: Coroutine.register(_cython_coroutine_type)\n" + ); + return module; +} +#endif +static int __Pyx_patch_abc(void) { +#if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED) + static int abc_patched = 0; + if (CYTHON_REGISTER_ABCS && !abc_patched) { + PyObject *module; + module = PyImport_ImportModule((PY_MAJOR_VERSION >= 3) ? "collections.abc" : "collections"); + if (unlikely(!module)) { + PyErr_WriteUnraisable(NULL); + if (unlikely(PyErr_WarnEx(PyExc_RuntimeWarning, + ((PY_MAJOR_VERSION >= 3) ? + "Cython module failed to register with collections.abc module" : + "Cython module failed to register with collections module"), 1) < 0)) { + return -1; + } + } else { + module = __Pyx_patch_abc_module(module); + abc_patched = 1; + if (unlikely(!module)) + return -1; + Py_DECREF(module); + } + module = PyImport_ImportModule("backports_abc"); + if (module) { + module = __Pyx_patch_abc_module(module); + Py_XDECREF(module); + } + if (!module) { + PyErr_Clear(); + } + } +#else + if ((0)) __Pyx_Coroutine_patch_module(NULL, NULL); +#endif + return 0; +} + +/* Generator */ +static PyMethodDef __pyx_Generator_methods[] = { + {"send", (PyCFunction) __Pyx_Coroutine_Send, METH_O, + (char*) PyDoc_STR("send(arg) -> send 'arg' into generator,\nreturn next yielded value or raise StopIteration.")}, + {"throw", (PyCFunction) __Pyx_Coroutine_Throw, METH_VARARGS, + (char*) PyDoc_STR("throw(typ[,val[,tb]]) -> raise exception in generator,\nreturn next yielded value or raise StopIteration.")}, + {"close", (PyCFunction) __Pyx_Coroutine_Close_Method, METH_NOARGS, + (char*) PyDoc_STR("close() -> raise GeneratorExit inside generator.")}, + {0, 0, 0, 0} +}; +static PyMemberDef __pyx_Generator_memberlist[] = { + {(char *) "gi_running", T_BOOL, offsetof(__pyx_CoroutineObject, is_running), READONLY, NULL}, + {(char*) "gi_yieldfrom", T_OBJECT, offsetof(__pyx_CoroutineObject, yieldfrom), READONLY, + (char*) PyDoc_STR("object being iterated by 'yield from', or None")}, + {(char*) "gi_code", T_OBJECT, offsetof(__pyx_CoroutineObject, gi_code), READONLY, NULL}, + {(char *) "__module__", T_OBJECT, offsetof(__pyx_CoroutineObject, gi_modulename), 0, 0}, +#if CYTHON_USE_TYPE_SPECS + {(char *) "__weaklistoffset__", T_PYSSIZET, offsetof(__pyx_CoroutineObject, gi_weakreflist), READONLY, 0}, +#endif + {0, 0, 0, 0, 0} +}; +static PyGetSetDef __pyx_Generator_getsets[] = { + {(char *) "__name__", (getter)__Pyx_Coroutine_get_name, (setter)__Pyx_Coroutine_set_name, + (char*) PyDoc_STR("name of the generator"), 0}, + {(char *) "__qualname__", (getter)__Pyx_Coroutine_get_qualname, (setter)__Pyx_Coroutine_set_qualname, + (char*) PyDoc_STR("qualified name of the generator"), 0}, + {(char *) "gi_frame", (getter)__Pyx_Coroutine_get_frame, NULL, + (char*) PyDoc_STR("Frame of the generator"), 0}, + {0, 0, 0, 0, 0} +}; +#if CYTHON_USE_TYPE_SPECS +static PyType_Slot __pyx_GeneratorType_slots[] = { + {Py_tp_dealloc, (void *)__Pyx_Coroutine_dealloc}, + {Py_tp_traverse, (void *)__Pyx_Coroutine_traverse}, + {Py_tp_iter, (void *)PyObject_SelfIter}, + {Py_tp_iternext, (void *)__Pyx_Generator_Next}, + {Py_tp_methods, (void *)__pyx_Generator_methods}, + {Py_tp_members, (void *)__pyx_Generator_memberlist}, + {Py_tp_getset, (void *)__pyx_Generator_getsets}, + {Py_tp_getattro, (void *) __Pyx_PyObject_GenericGetAttrNoDict}, +#if CYTHON_USE_TP_FINALIZE + {Py_tp_finalize, (void *)__Pyx_Coroutine_del}, +#endif + {0, 0}, +}; +static PyType_Spec __pyx_GeneratorType_spec = { + __PYX_TYPE_MODULE_PREFIX "generator", + sizeof(__pyx_CoroutineObject), + 0, + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_HAVE_FINALIZE, + __pyx_GeneratorType_slots +}; +#else +static PyTypeObject __pyx_GeneratorType_type = { + PyVarObject_HEAD_INIT(0, 0) + __PYX_TYPE_MODULE_PREFIX "generator", + sizeof(__pyx_CoroutineObject), + 0, + (destructor) __Pyx_Coroutine_dealloc, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_HAVE_FINALIZE, + 0, + (traverseproc) __Pyx_Coroutine_traverse, + 0, + 0, + offsetof(__pyx_CoroutineObject, gi_weakreflist), + 0, + (iternextfunc) __Pyx_Generator_Next, + __pyx_Generator_methods, + __pyx_Generator_memberlist, + __pyx_Generator_getsets, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, +#if CYTHON_USE_TP_FINALIZE + 0, +#else + __Pyx_Coroutine_del, +#endif + 0, +#if CYTHON_USE_TP_FINALIZE + __Pyx_Coroutine_del, +#elif PY_VERSION_HEX >= 0x030400a1 + 0, +#endif +#if PY_VERSION_HEX >= 0x030800b1 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) + 0, +#endif +#if __PYX_NEED_TP_PRINT_SLOT + 0, +#endif +#if PY_VERSION_HEX >= 0x030C0000 + 0, +#endif +#if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 + 0, +#endif +}; +#endif +static int __pyx_Generator_init(PyObject *module) { +#if CYTHON_USE_TYPE_SPECS + __pyx_GeneratorType = __Pyx_FetchCommonTypeFromSpec(module, &__pyx_GeneratorType_spec, NULL); +#else + CYTHON_UNUSED_VAR(module); + __pyx_GeneratorType_type.tp_getattro = __Pyx_PyObject_GenericGetAttrNoDict; + __pyx_GeneratorType_type.tp_iter = PyObject_SelfIter; + __pyx_GeneratorType = __Pyx_FetchCommonType(&__pyx_GeneratorType_type); +#endif + if (unlikely(!__pyx_GeneratorType)) { + return -1; + } + return 0; +} + +/* CheckBinaryVersion */ +static unsigned long __Pyx_get_runtime_version(void) { +#if __PYX_LIMITED_VERSION_HEX >= 0x030B00A4 + return Py_Version & ~0xFFUL; +#else + const char* rt_version = Py_GetVersion(); + unsigned long version = 0; + unsigned long factor = 0x01000000UL; + unsigned int digit = 0; + int i = 0; + while (factor) { + while ('0' <= rt_version[i] && rt_version[i] <= '9') { + digit = digit * 10 + (unsigned int) (rt_version[i] - '0'); + ++i; + } + version += factor * digit; + if (rt_version[i] != '.') + break; + digit = 0; + factor >>= 8; + ++i; + } + return version; +#endif +} +static int __Pyx_check_binary_version(unsigned long ct_version, unsigned long rt_version, int allow_newer) { + const unsigned long MAJOR_MINOR = 0xFFFF0000UL; + if ((rt_version & MAJOR_MINOR) == (ct_version & MAJOR_MINOR)) + return 0; + if (likely(allow_newer && (rt_version & MAJOR_MINOR) > (ct_version & MAJOR_MINOR))) + return 1; + { + char message[200]; + PyOS_snprintf(message, sizeof(message), + "compile time Python version %d.%d " + "of module '%.100s' " + "%s " + "runtime version %d.%d", + (int) (ct_version >> 24), (int) ((ct_version >> 16) & 0xFF), + __Pyx_MODULE_NAME, + (allow_newer) ? "was newer than" : "does not match", + (int) (rt_version >> 24), (int) ((rt_version >> 16) & 0xFF) + ); + return PyErr_WarnEx(NULL, message, 1); + } +} + +/* InitStrings */ +#if PY_MAJOR_VERSION >= 3 +static int __Pyx_InitString(__Pyx_StringTabEntry t, PyObject **str) { + if (t.is_unicode | t.is_str) { + if (t.intern) { + *str = PyUnicode_InternFromString(t.s); + } else if (t.encoding) { + *str = PyUnicode_Decode(t.s, t.n - 1, t.encoding, NULL); + } else { + *str = PyUnicode_FromStringAndSize(t.s, t.n - 1); + } + } else { + *str = PyBytes_FromStringAndSize(t.s, t.n - 1); + } + if (!*str) + return -1; + if (PyObject_Hash(*str) == -1) + return -1; + return 0; +} +#endif +static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { + while (t->p) { + #if PY_MAJOR_VERSION >= 3 + __Pyx_InitString(*t, t->p); + #else + if (t->is_unicode) { + *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL); + } else if (t->intern) { + *t->p = PyString_InternFromString(t->s); + } else { + *t->p = PyString_FromStringAndSize(t->s, t->n - 1); + } + if (!*t->p) + return -1; + if (PyObject_Hash(*t->p) == -1) + return -1; + #endif + ++t; + } + return 0; +} + +#include +static CYTHON_INLINE Py_ssize_t __Pyx_ssize_strlen(const char *s) { + size_t len = strlen(s); + if (unlikely(len > (size_t) PY_SSIZE_T_MAX)) { + PyErr_SetString(PyExc_OverflowError, "byte string is too long"); + return -1; + } + return (Py_ssize_t) len; +} +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { + Py_ssize_t len = __Pyx_ssize_strlen(c_str); + if (unlikely(len < 0)) return NULL; + return __Pyx_PyUnicode_FromStringAndSize(c_str, len); +} +static CYTHON_INLINE PyObject* __Pyx_PyByteArray_FromString(const char* c_str) { + Py_ssize_t len = __Pyx_ssize_strlen(c_str); + if (unlikely(len < 0)) return NULL; + return PyByteArray_FromStringAndSize(c_str, len); +} +static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject* o) { + Py_ssize_t ignore; + return __Pyx_PyObject_AsStringAndSize(o, &ignore); +} +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT +#if !CYTHON_PEP393_ENABLED +static const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { + char* defenc_c; + PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); + if (!defenc) return NULL; + defenc_c = PyBytes_AS_STRING(defenc); +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + { + char* end = defenc_c + PyBytes_GET_SIZE(defenc); + char* c; + for (c = defenc_c; c < end; c++) { + if ((unsigned char) (*c) >= 128) { + PyUnicode_AsASCIIString(o); + return NULL; + } + } + } +#endif + *length = PyBytes_GET_SIZE(defenc); + return defenc_c; +} +#else +static CYTHON_INLINE const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { + if (unlikely(__Pyx_PyUnicode_READY(o) == -1)) return NULL; +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + if (likely(PyUnicode_IS_ASCII(o))) { + *length = PyUnicode_GET_LENGTH(o); + return PyUnicode_AsUTF8(o); + } else { + PyUnicode_AsASCIIString(o); + return NULL; + } +#else + return PyUnicode_AsUTF8AndSize(o, length); +#endif +} +#endif +#endif +static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT + if ( +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + __Pyx_sys_getdefaultencoding_not_ascii && +#endif + PyUnicode_Check(o)) { + return __Pyx_PyUnicode_AsStringAndSize(o, length); + } else +#endif +#if (!CYTHON_COMPILING_IN_PYPY && !CYTHON_COMPILING_IN_LIMITED_API) || (defined(PyByteArray_AS_STRING) && defined(PyByteArray_GET_SIZE)) + if (PyByteArray_Check(o)) { + *length = PyByteArray_GET_SIZE(o); + return PyByteArray_AS_STRING(o); + } else +#endif + { + char* result; + int r = PyBytes_AsStringAndSize(o, &result, length); + if (unlikely(r < 0)) { + return NULL; + } else { + return result; + } + } +} +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { + int is_true = x == Py_True; + if (is_true | (x == Py_False) | (x == Py_None)) return is_true; + else return PyObject_IsTrue(x); +} +static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject* x) { + int retval; + if (unlikely(!x)) return -1; + retval = __Pyx_PyObject_IsTrue(x); + Py_DECREF(x); + return retval; +} +static PyObject* __Pyx_PyNumber_IntOrLongWrongResultType(PyObject* result, const char* type_name) { + __Pyx_TypeName result_type_name = __Pyx_PyType_GetName(Py_TYPE(result)); +#if PY_MAJOR_VERSION >= 3 + if (PyLong_Check(result)) { + if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1, + "__int__ returned non-int (type " __Pyx_FMT_TYPENAME "). " + "The ability to return an instance of a strict subclass of int is deprecated, " + "and may be removed in a future version of Python.", + result_type_name)) { + __Pyx_DECREF_TypeName(result_type_name); + Py_DECREF(result); + return NULL; + } + __Pyx_DECREF_TypeName(result_type_name); + return result; + } +#endif + PyErr_Format(PyExc_TypeError, + "__%.4s__ returned non-%.4s (type " __Pyx_FMT_TYPENAME ")", + type_name, type_name, result_type_name); + __Pyx_DECREF_TypeName(result_type_name); + Py_DECREF(result); + return NULL; +} +static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x) { +#if CYTHON_USE_TYPE_SLOTS + PyNumberMethods *m; +#endif + const char *name = NULL; + PyObject *res = NULL; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x) || PyLong_Check(x))) +#else + if (likely(PyLong_Check(x))) +#endif + return __Pyx_NewRef(x); +#if CYTHON_USE_TYPE_SLOTS + m = Py_TYPE(x)->tp_as_number; + #if PY_MAJOR_VERSION < 3 + if (m && m->nb_int) { + name = "int"; + res = m->nb_int(x); + } + else if (m && m->nb_long) { + name = "long"; + res = m->nb_long(x); + } + #else + if (likely(m && m->nb_int)) { + name = "int"; + res = m->nb_int(x); + } + #endif +#else + if (!PyBytes_CheckExact(x) && !PyUnicode_CheckExact(x)) { + res = PyNumber_Int(x); + } +#endif + if (likely(res)) { +#if PY_MAJOR_VERSION < 3 + if (unlikely(!PyInt_Check(res) && !PyLong_Check(res))) { +#else + if (unlikely(!PyLong_CheckExact(res))) { +#endif + return __Pyx_PyNumber_IntOrLongWrongResultType(res, name); + } + } + else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_TypeError, + "an integer is required"); + } + return res; +} +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { + Py_ssize_t ival; + PyObject *x; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_CheckExact(b))) { + if (sizeof(Py_ssize_t) >= sizeof(long)) + return PyInt_AS_LONG(b); + else + return PyInt_AsSsize_t(b); + } +#endif + if (likely(PyLong_CheckExact(b))) { + #if CYTHON_USE_PYLONG_INTERNALS + if (likely(__Pyx_PyLong_IsCompact(b))) { + return __Pyx_PyLong_CompactValue(b); + } else { + const digit* digits = __Pyx_PyLong_Digits(b); + const Py_ssize_t size = __Pyx_PyLong_SignedDigitCount(b); + switch (size) { + case 2: + if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { + return (Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case -2: + if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { + return -(Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case 3: + if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { + return (Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case -3: + if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { + return -(Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case 4: + if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { + return (Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case -4: + if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { + return -(Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + } + } + #endif + return PyLong_AsSsize_t(b); + } + x = PyNumber_Index(b); + if (!x) return -1; + ival = PyInt_AsSsize_t(x); + Py_DECREF(x); + return ival; +} +static CYTHON_INLINE Py_hash_t __Pyx_PyIndex_AsHash_t(PyObject* o) { + if (sizeof(Py_hash_t) == sizeof(Py_ssize_t)) { + return (Py_hash_t) __Pyx_PyIndex_AsSsize_t(o); +#if PY_MAJOR_VERSION < 3 + } else if (likely(PyInt_CheckExact(o))) { + return PyInt_AS_LONG(o); +#endif + } else { + Py_ssize_t ival; + PyObject *x; + x = PyNumber_Index(o); + if (!x) return -1; + ival = PyInt_AsLong(x); + Py_DECREF(x); + return ival; + } +} +static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b) { + return b ? __Pyx_NewRef(Py_True) : __Pyx_NewRef(Py_False); +} +static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { + return PyInt_FromSize_t(ival); +} + + +/* #### Code section: utility_code_pragmas_end ### */ +#ifdef _MSC_VER +#pragma warning( pop ) +#endif + + + +/* #### Code section: end ### */ +#endif /* Py_PYTHON_H */ diff --git a/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/_bbpe.pxd b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/_bbpe.pxd new file mode 100644 index 0000000000000000000000000000000000000000..d9e6e1093b016bb16d15794b96c0985386c1f001 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/_bbpe.pxd @@ -0,0 +1,9 @@ +from libcpp.string cimport string +from libcpp.vector cimport vector +from libcpp.utility cimport pair + +cdef extern from "merges.hh": + cdef cppclass Merges: + Merges(const vector[pair[string, string]]& merges) + vector[string] apply_merges(vector[string] pieces) const + vector[pair[string, string]] merges() const \ No newline at end of file diff --git a/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/_bbpe.pyx b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/_bbpe.pyx new file mode 100644 index 0000000000000000000000000000000000000000..00cc5662b52477ce93f47071df390466f44c19a7 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/_bbpe.pyx @@ -0,0 +1,174 @@ +# cython: infer_types + +from typing import Dict, Iterable, List, Optional, Tuple +from cython.operator cimport dereference as deref +from functools import lru_cache +from io import BytesIO +import json +from libcpp.memory cimport make_shared, shared_ptr +from pathlib import Path +import regex + + +# We need the same splitting pattern and byte -> string remapping as GPT-2, +# so these are taken directly from: +# +# https://github.com/openai/gpt-2/blob/master/src/encoder.py +# +# See the LICENSE file for licensing information. + + +SPLIT_PATTERN = r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""" + + +@lru_cache() +def bytes_to_unicode() -> Dict[int, bytes]: + """ + Returns list of utf-8 byte and a corresponding list of unicode strings. + The reversible bpe codes work on unicode strings. + This means you need a large # of unicode characters in your vocab if you want to avoid UNKs. + When you're at something like a 10B token dataset you end up needing around 5K for decent coverage. + This is a signficant percentage of your normal, say, 32K bpe vocab. + To avoid that, we want lookup tables between utf-8 bytes and unicode strings. + And avoids mapping to whitespace/control characters the bpe code barfs on. + """ + bs = ( + list(range(ord("!"), ord("~") + 1)) + + list(range(ord("¡"), ord("¬") + 1)) + + list(range(ord("®"), ord("ÿ") + 1)) + ) + cs = bs[:] + n = 0 + for b in range(2**8): + if b not in bs: + bs.append(b) + cs.append(2**8 + n) + n += 1 + cs = [chr(n).encode("utf-8") for n in cs] + return dict(zip(bs, cs)) + +cdef class ByteBPEProcessor: + cdef shared_ptr[Merges] _merges + cdef dict _byte_decoder + cdef dict _byte_encoder + cdef object _split_pattern + cdef dict _piece_to_id + cdef dict _id_to_piece + + def __init__(self, vocab: Dict[str, int], merges: List[Tuple[str, str]]): + self._byte_encoder = bytes_to_unicode() + self._byte_decoder = {v.decode("utf-8"): k for k, v in self._byte_encoder.items()} + self._split_pattern = regex.compile(SPLIT_PATTERN) + self._piece_to_id = vocab + self._id_to_piece = {v: k for k, v in vocab.items()} + cdef vector[pair[string, string]] c_merges + for p1, p2 in merges: + c_merges.push_back(pair[string, string](p1.encode('utf-8'), p2.encode('utf-8'))) + self._merges = make_shared[Merges](c_merges) + + def __copy__(self): + return ByteBPEProcessor(vocab=self.vocab, merges=self.merges) + + def __deepcopy__(self, memo): + # We don't need a deepcopy of the vocab and merges dicts as their + # contents will be copied into a backing store in the c'tor. + return ByteBPEProcessor(vocab=self.vocab, merges=self.merges) + + @staticmethod + def load_from_files(*, vocab: Path, merges: Path) -> ByteBPEProcessor: + """Construct a processor from the given vocabulary and merges files.""" + with open(vocab, encoding="utf-8") as f: + vocab = json.load(f) + with open(merges, encoding="utf-8") as f: + version = f.readline() + if not version.startswith("#version: 0.2"): + raise ValueError(f"Only version 0.2 of the merges format is supported, was: {version.strip()}") + merges = [] + for line in f: + merge = line.strip().split(" ") + if len(merge) != 2: + raise ValueError(f"Merge must consist of 2 items, was {len(merge)}: {line.strip()}") + merges.append(merge) + return ByteBPEProcessor(vocab, merges) + + def decode_from_ids(self, ids: Iterable[int]) -> str: + """ + Decode piece identifiers into string. + + ids (Iterable[int]): piece identifiers. + RETURNS (str): decoded string. + """ + decoded = BytesIO() + for piece_id in ids: + piece = self._id_to_piece.get(piece_id, None) + if piece is None: + raise ValueError(f"Unknown piece identifier: {piece_id}") + decoded.write(bytes([self._byte_decoder[cp] for cp in list(piece)])) + + return decoded.getvalue().decode("utf-8") + + def encode(self, text: str) -> Tuple[List[int], List[str]]: + """ + Split a text into pieces. + + text: The text to split. + RETURNS: A pair of pieces and piece identifiers. + """ + pieces = self.encode_as_pieces(text) + return self._pieces_to_ids(pieces), pieces + + def encode_as_ids(self, text: str) -> List[int]: + """ + Split a text into pieces, returning piece identifiers. + + text: The text to split. + RETURNS: Piece identifiers. + """ + pieces = self.encode_as_pieces(text) + return self._pieces_to_ids(pieces) + + def encode_as_pieces(self, text: str) -> List[str]: + """ + Split a text into pieces, returning piece pieces. + + text: The text to split. + RETURNS: Piece pieces. + """ + pieces = [] + for token in regex.findall(self._split_pattern, text): + token_bytes = [self._byte_encoder[b] for b in token.encode("utf-8")] + merged = deref(self._merges).apply_merges(token_bytes) + pieces.extend(merge.decode("utf-8") for merge in merged) + return pieces + + @property + def merges(self) -> List[Tuple[str, str]]: + """Get all merges.""" + merges_bytes = deref(self._merges).merges() + return [(m1.decode('utf-8'), m2.decode('utf-8')) for m1, m2 in merges_bytes] + + def piece_id(self, piece: str) -> Optional[int]: + """Get the identifier for a piece.""" + return self._piece_to_id.get(piece) + + @property + def vocab(self) -> Dict[str, int]: + """Get a copy of the vocabulary.""" + return dict(self._piece_to_id) + + def _pieces_to_ids(self, pieces): + piece_ids = [] + for piece in pieces: + piece_id = self._piece_to_id.get(piece) + if piece_id is None: + raise ValueError(f"Piece is not in vocabulary: {piece}") + piece_ids.append(piece_id) + + return piece_ids + + def __reduce__(self): + return (unpickle_byte_bpe_processor, (self.vocab, self.merges,)) + +def unpickle_byte_bpe_processor(vocab: Dict[str, int], + merges: List[Tuple[str, str]]) -> ByteBPEProcessor: + return ByteBPEProcessor(vocab, merges) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/_spp.cpp b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/_spp.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2a6212f3252c4a0935609637839fa7524db5eb32 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/_spp.cpp @@ -0,0 +1,13536 @@ +/* Generated by Cython 3.0.8 */ + +/* BEGIN: Cython Metadata +{ + "distutils": { + "depends": [ + "sentencepiece\\src\\builtin_pb\\sentencepiece.pb.h", + "sentencepiece\\src\\sentencepiece_processor.h" + ], + "include_dirs": [ + "curated_tokenizers", + "sentencepiece", + "sentencepiece/src", + "sentencepiece/src/builtin_pb", + "sentencepiece/third_party/protobuf-lite" + ], + "language": "c++", + "name": "curated_tokenizers._spp", + "sources": [ + "curated_tokenizers/_spp.pyx", + "sentencepiece/third_party/absl/flags/flag.cc", + "sentencepiece/third_party/absl/strings/string_view.cc", + "sentencepiece/third_party/protobuf-lite/arena.cc", + "sentencepiece/third_party/protobuf-lite/arenastring.cc", + "sentencepiece/third_party/protobuf-lite/bytestream.cc", + "sentencepiece/third_party/protobuf-lite/coded_stream.cc", + "sentencepiece/third_party/protobuf-lite/common.cc", + "sentencepiece/third_party/protobuf-lite/extension_set.cc", + "sentencepiece/third_party/protobuf-lite/generated_enum_util.cc", + "sentencepiece/third_party/protobuf-lite/generated_message_table_driven_lite.cc", + "sentencepiece/third_party/protobuf-lite/generated_message_util.cc", + "sentencepiece/third_party/protobuf-lite/implicit_weak_message.cc", + "sentencepiece/third_party/protobuf-lite/int128.cc", + "sentencepiece/third_party/protobuf-lite/io_win32.cc", + "sentencepiece/third_party/protobuf-lite/message_lite.cc", + "sentencepiece/third_party/protobuf-lite/parse_context.cc", + "sentencepiece/third_party/protobuf-lite/repeated_field.cc", + "sentencepiece/third_party/protobuf-lite/status.cc", + "sentencepiece/third_party/protobuf-lite/statusor.cc", + "sentencepiece/third_party/protobuf-lite/stringpiece.cc", + "sentencepiece/third_party/protobuf-lite/stringprintf.cc", + "sentencepiece/third_party/protobuf-lite/structurally_valid.cc", + "sentencepiece/third_party/protobuf-lite/strutil.cc", + "sentencepiece/third_party/protobuf-lite/time.cc", + "sentencepiece/third_party/protobuf-lite/wire_format_lite.cc", + "sentencepiece/third_party/protobuf-lite/zero_copy_stream.cc", + "sentencepiece/third_party/protobuf-lite/zero_copy_stream_impl.cc", + "sentencepiece/third_party/protobuf-lite/zero_copy_stream_impl_lite.cc", + "sentencepiece/src/bpe_model.cc", + "sentencepiece/src/char_model.cc", + "sentencepiece/src/error.cc", + "sentencepiece/src/filesystem.cc", + "sentencepiece/src/model_factory.cc", + "sentencepiece/src/model_interface.cc", + "sentencepiece/src/normalizer.cc", + "sentencepiece/src/sentencepiece_processor.cc", + "sentencepiece/src/unigram_model.cc", + "sentencepiece/src/util.cc", + "sentencepiece/src/word_model.cc", + "sentencepiece/src/builtin_pb/sentencepiece.pb.cc", + "sentencepiece/src/builtin_pb/sentencepiece_model.pb.cc" + ] + }, + "module_name": "curated_tokenizers._spp" +} +END: Cython Metadata */ + +#ifndef PY_SSIZE_T_CLEAN +#define PY_SSIZE_T_CLEAN +#endif /* PY_SSIZE_T_CLEAN */ +#if defined(CYTHON_LIMITED_API) && 0 + #ifndef Py_LIMITED_API + #if CYTHON_LIMITED_API+0 > 0x03030000 + #define Py_LIMITED_API CYTHON_LIMITED_API + #else + #define Py_LIMITED_API 0x03030000 + #endif + #endif +#endif + +#include "Python.h" +#ifndef Py_PYTHON_H + #error Python headers needed to compile C extensions, please install development version of Python. +#elif PY_VERSION_HEX < 0x02070000 || (0x03000000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x03030000) + #error Cython requires Python 2.7+ or Python 3.3+. +#else +#if defined(CYTHON_LIMITED_API) && CYTHON_LIMITED_API +#define __PYX_EXTRA_ABI_MODULE_NAME "limited" +#else +#define __PYX_EXTRA_ABI_MODULE_NAME "" +#endif +#define CYTHON_ABI "3_0_8" __PYX_EXTRA_ABI_MODULE_NAME +#define __PYX_ABI_MODULE_NAME "_cython_" CYTHON_ABI +#define __PYX_TYPE_MODULE_PREFIX __PYX_ABI_MODULE_NAME "." +#define CYTHON_HEX_VERSION 0x030008F0 +#define CYTHON_FUTURE_DIVISION 0 +#include +#ifndef offsetof + #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) +#endif +#if !defined(_WIN32) && !defined(WIN32) && !defined(MS_WINDOWS) + #ifndef __stdcall + #define __stdcall + #endif + #ifndef __cdecl + #define __cdecl + #endif + #ifndef __fastcall + #define __fastcall + #endif +#endif +#ifndef DL_IMPORT + #define DL_IMPORT(t) t +#endif +#ifndef DL_EXPORT + #define DL_EXPORT(t) t +#endif +#define __PYX_COMMA , +#ifndef HAVE_LONG_LONG + #define HAVE_LONG_LONG +#endif +#ifndef PY_LONG_LONG + #define PY_LONG_LONG LONG_LONG +#endif +#ifndef Py_HUGE_VAL + #define Py_HUGE_VAL HUGE_VAL +#endif +#define __PYX_LIMITED_VERSION_HEX PY_VERSION_HEX +#if defined(GRAALVM_PYTHON) + /* For very preliminary testing purposes. Most variables are set the same as PyPy. + The existence of this section does not imply that anything works or is even tested */ + #define CYTHON_COMPILING_IN_PYPY 0 + #define CYTHON_COMPILING_IN_CPYTHON 0 + #define CYTHON_COMPILING_IN_LIMITED_API 0 + #define CYTHON_COMPILING_IN_GRAAL 1 + #define CYTHON_COMPILING_IN_NOGIL 0 + #undef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 0 + #undef CYTHON_USE_TYPE_SPECS + #define CYTHON_USE_TYPE_SPECS 0 + #undef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 0 + #if PY_VERSION_HEX < 0x03050000 + #undef CYTHON_USE_ASYNC_SLOTS + #define CYTHON_USE_ASYNC_SLOTS 0 + #elif !defined(CYTHON_USE_ASYNC_SLOTS) + #define CYTHON_USE_ASYNC_SLOTS 1 + #endif + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #undef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 0 + #undef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #undef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 0 + #undef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 1 + #undef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 0 + #undef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 0 + #undef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 0 + #undef CYTHON_FAST_GIL + #define CYTHON_FAST_GIL 0 + #undef CYTHON_METH_FASTCALL + #define CYTHON_METH_FASTCALL 0 + #undef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 0 + #ifndef CYTHON_PEP487_INIT_SUBCLASS + #define CYTHON_PEP487_INIT_SUBCLASS (PY_MAJOR_VERSION >= 3) + #endif + #undef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #undef CYTHON_USE_MODULE_STATE + #define CYTHON_USE_MODULE_STATE 0 + #undef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE 0 + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #undef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 0 + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC 0 + #endif +#elif defined(PYPY_VERSION) + #define CYTHON_COMPILING_IN_PYPY 1 + #define CYTHON_COMPILING_IN_CPYTHON 0 + #define CYTHON_COMPILING_IN_LIMITED_API 0 + #define CYTHON_COMPILING_IN_GRAAL 0 + #define CYTHON_COMPILING_IN_NOGIL 0 + #undef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 0 + #ifndef CYTHON_USE_TYPE_SPECS + #define CYTHON_USE_TYPE_SPECS 0 + #endif + #undef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 0 + #if PY_VERSION_HEX < 0x03050000 + #undef CYTHON_USE_ASYNC_SLOTS + #define CYTHON_USE_ASYNC_SLOTS 0 + #elif !defined(CYTHON_USE_ASYNC_SLOTS) + #define CYTHON_USE_ASYNC_SLOTS 1 + #endif + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #undef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 0 + #undef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #undef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 0 + #undef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 1 + #undef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 0 + #undef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 0 + #undef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 0 + #undef CYTHON_FAST_GIL + #define CYTHON_FAST_GIL 0 + #undef CYTHON_METH_FASTCALL + #define CYTHON_METH_FASTCALL 0 + #undef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 0 + #ifndef CYTHON_PEP487_INIT_SUBCLASS + #define CYTHON_PEP487_INIT_SUBCLASS (PY_MAJOR_VERSION >= 3) + #endif + #if PY_VERSION_HEX < 0x03090000 + #undef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 0 + #elif !defined(CYTHON_PEP489_MULTI_PHASE_INIT) + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #endif + #undef CYTHON_USE_MODULE_STATE + #define CYTHON_USE_MODULE_STATE 0 + #undef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE (PY_VERSION_HEX >= 0x030400a1 && PYPY_VERSION_NUM >= 0x07030C00) + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #undef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 0 + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC 0 + #endif +#elif defined(CYTHON_LIMITED_API) + #ifdef Py_LIMITED_API + #undef __PYX_LIMITED_VERSION_HEX + #define __PYX_LIMITED_VERSION_HEX Py_LIMITED_API + #endif + #define CYTHON_COMPILING_IN_PYPY 0 + #define CYTHON_COMPILING_IN_CPYTHON 0 + #define CYTHON_COMPILING_IN_LIMITED_API 1 + #define CYTHON_COMPILING_IN_GRAAL 0 + #define CYTHON_COMPILING_IN_NOGIL 0 + #undef CYTHON_CLINE_IN_TRACEBACK + #define CYTHON_CLINE_IN_TRACEBACK 0 + #undef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 0 + #undef CYTHON_USE_TYPE_SPECS + #define CYTHON_USE_TYPE_SPECS 1 + #undef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 0 + #undef CYTHON_USE_ASYNC_SLOTS + #define CYTHON_USE_ASYNC_SLOTS 0 + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #undef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 0 + #ifndef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #endif + #undef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 0 + #ifndef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 0 + #endif + #undef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 0 + #undef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 0 + #undef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 0 + #undef CYTHON_FAST_GIL + #define CYTHON_FAST_GIL 0 + #undef CYTHON_METH_FASTCALL + #define CYTHON_METH_FASTCALL 0 + #undef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 0 + #ifndef CYTHON_PEP487_INIT_SUBCLASS + #define CYTHON_PEP487_INIT_SUBCLASS 1 + #endif + #undef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 0 + #undef CYTHON_USE_MODULE_STATE + #define CYTHON_USE_MODULE_STATE 1 + #ifndef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE 0 + #endif + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #undef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 0 + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC 0 + #endif +#elif defined(Py_GIL_DISABLED) || defined(Py_NOGIL) + #define CYTHON_COMPILING_IN_PYPY 0 + #define CYTHON_COMPILING_IN_CPYTHON 0 + #define CYTHON_COMPILING_IN_LIMITED_API 0 + #define CYTHON_COMPILING_IN_GRAAL 0 + #define CYTHON_COMPILING_IN_NOGIL 1 + #ifndef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 1 + #endif + #undef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 0 + #ifndef CYTHON_USE_ASYNC_SLOTS + #define CYTHON_USE_ASYNC_SLOTS 1 + #endif + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #ifndef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 1 + #endif + #undef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #undef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 0 + #ifndef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 0 + #endif + #ifndef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 1 + #endif + #ifndef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 1 + #endif + #undef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 0 + #undef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 0 + #ifndef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #endif + #ifndef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE 1 + #endif + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #undef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 0 +#else + #define CYTHON_COMPILING_IN_PYPY 0 + #define CYTHON_COMPILING_IN_CPYTHON 1 + #define CYTHON_COMPILING_IN_LIMITED_API 0 + #define CYTHON_COMPILING_IN_GRAAL 0 + #define CYTHON_COMPILING_IN_NOGIL 0 + #ifndef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 1 + #endif + #ifndef CYTHON_USE_TYPE_SPECS + #define CYTHON_USE_TYPE_SPECS 0 + #endif + #ifndef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 1 + #endif + #if PY_MAJOR_VERSION < 3 + #undef CYTHON_USE_ASYNC_SLOTS + #define CYTHON_USE_ASYNC_SLOTS 0 + #elif !defined(CYTHON_USE_ASYNC_SLOTS) + #define CYTHON_USE_ASYNC_SLOTS 1 + #endif + #ifndef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 1 + #endif + #ifndef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 1 + #endif + #ifndef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 1 + #endif + #if PY_VERSION_HEX < 0x030300F0 || PY_VERSION_HEX >= 0x030B00A2 + #undef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #elif !defined(CYTHON_USE_UNICODE_WRITER) + #define CYTHON_USE_UNICODE_WRITER 1 + #endif + #ifndef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 0 + #endif + #ifndef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 1 + #endif + #ifndef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 1 + #endif + #ifndef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 1 + #endif + #ifndef CYTHON_FAST_GIL + #define CYTHON_FAST_GIL (PY_MAJOR_VERSION < 3 || PY_VERSION_HEX >= 0x03060000 && PY_VERSION_HEX < 0x030C00A6) + #endif + #ifndef CYTHON_METH_FASTCALL + #define CYTHON_METH_FASTCALL (PY_VERSION_HEX >= 0x030700A1) + #endif + #ifndef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 1 + #endif + #ifndef CYTHON_PEP487_INIT_SUBCLASS + #define CYTHON_PEP487_INIT_SUBCLASS 1 + #endif + #if PY_VERSION_HEX < 0x03050000 + #undef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 0 + #elif !defined(CYTHON_PEP489_MULTI_PHASE_INIT) + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #endif + #ifndef CYTHON_USE_MODULE_STATE + #define CYTHON_USE_MODULE_STATE 0 + #endif + #if PY_VERSION_HEX < 0x030400a1 + #undef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE 0 + #elif !defined(CYTHON_USE_TP_FINALIZE) + #define CYTHON_USE_TP_FINALIZE 1 + #endif + #if PY_VERSION_HEX < 0x030600B1 + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #elif !defined(CYTHON_USE_DICT_VERSIONS) + #define CYTHON_USE_DICT_VERSIONS (PY_VERSION_HEX < 0x030C00A5) + #endif + #if PY_VERSION_HEX < 0x030700A3 + #undef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 0 + #elif !defined(CYTHON_USE_EXC_INFO_STACK) + #define CYTHON_USE_EXC_INFO_STACK 1 + #endif + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC 1 + #endif +#endif +#if !defined(CYTHON_FAST_PYCCALL) +#define CYTHON_FAST_PYCCALL (CYTHON_FAST_PYCALL && PY_VERSION_HEX >= 0x030600B1) +#endif +#if !defined(CYTHON_VECTORCALL) +#define CYTHON_VECTORCALL (CYTHON_FAST_PYCCALL && PY_VERSION_HEX >= 0x030800B1) +#endif +#define CYTHON_BACKPORT_VECTORCALL (CYTHON_METH_FASTCALL && PY_VERSION_HEX < 0x030800B1) +#if CYTHON_USE_PYLONG_INTERNALS + #if PY_MAJOR_VERSION < 3 + #include "longintrepr.h" + #endif + #undef SHIFT + #undef BASE + #undef MASK + #ifdef SIZEOF_VOID_P + enum { __pyx_check_sizeof_voidp = 1 / (int)(SIZEOF_VOID_P == sizeof(void*)) }; + #endif +#endif +#ifndef __has_attribute + #define __has_attribute(x) 0 +#endif +#ifndef __has_cpp_attribute + #define __has_cpp_attribute(x) 0 +#endif +#ifndef CYTHON_RESTRICT + #if defined(__GNUC__) + #define CYTHON_RESTRICT __restrict__ + #elif defined(_MSC_VER) && _MSC_VER >= 1400 + #define CYTHON_RESTRICT __restrict + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_RESTRICT restrict + #else + #define CYTHON_RESTRICT + #endif +#endif +#ifndef CYTHON_UNUSED + #if defined(__cplusplus) + /* for clang __has_cpp_attribute(maybe_unused) is true even before C++17 + * but leads to warnings with -pedantic, since it is a C++17 feature */ + #if ((defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) || __cplusplus >= 201703L) + #if __has_cpp_attribute(maybe_unused) + #define CYTHON_UNUSED [[maybe_unused]] + #endif + #endif + #endif +#endif +#ifndef CYTHON_UNUSED +# if defined(__GNUC__) +# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +#endif +#ifndef CYTHON_UNUSED_VAR +# if defined(__cplusplus) + template void CYTHON_UNUSED_VAR( const T& ) { } +# else +# define CYTHON_UNUSED_VAR(x) (void)(x) +# endif +#endif +#ifndef CYTHON_MAYBE_UNUSED_VAR + #define CYTHON_MAYBE_UNUSED_VAR(x) CYTHON_UNUSED_VAR(x) +#endif +#ifndef CYTHON_NCP_UNUSED +# if CYTHON_COMPILING_IN_CPYTHON +# define CYTHON_NCP_UNUSED +# else +# define CYTHON_NCP_UNUSED CYTHON_UNUSED +# endif +#endif +#ifndef CYTHON_USE_CPP_STD_MOVE + #if defined(__cplusplus) && (\ + __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1600)) + #define CYTHON_USE_CPP_STD_MOVE 1 + #else + #define CYTHON_USE_CPP_STD_MOVE 0 + #endif +#endif +#define __Pyx_void_to_None(void_result) ((void)(void_result), Py_INCREF(Py_None), Py_None) +#ifdef _MSC_VER + #ifndef _MSC_STDINT_H_ + #if _MSC_VER < 1300 + typedef unsigned char uint8_t; + typedef unsigned short uint16_t; + typedef unsigned int uint32_t; + #else + typedef unsigned __int8 uint8_t; + typedef unsigned __int16 uint16_t; + typedef unsigned __int32 uint32_t; + #endif + #endif + #if _MSC_VER < 1300 + #ifdef _WIN64 + typedef unsigned long long __pyx_uintptr_t; + #else + typedef unsigned int __pyx_uintptr_t; + #endif + #else + #ifdef _WIN64 + typedef unsigned __int64 __pyx_uintptr_t; + #else + typedef unsigned __int32 __pyx_uintptr_t; + #endif + #endif +#else + #include + typedef uintptr_t __pyx_uintptr_t; +#endif +#ifndef CYTHON_FALLTHROUGH + #if defined(__cplusplus) + /* for clang __has_cpp_attribute(fallthrough) is true even before C++17 + * but leads to warnings with -pedantic, since it is a C++17 feature */ + #if ((defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) || __cplusplus >= 201703L) + #if __has_cpp_attribute(fallthrough) + #define CYTHON_FALLTHROUGH [[fallthrough]] + #endif + #endif + #ifndef CYTHON_FALLTHROUGH + #if __has_cpp_attribute(clang::fallthrough) + #define CYTHON_FALLTHROUGH [[clang::fallthrough]] + #elif __has_cpp_attribute(gnu::fallthrough) + #define CYTHON_FALLTHROUGH [[gnu::fallthrough]] + #endif + #endif + #endif + #ifndef CYTHON_FALLTHROUGH + #if __has_attribute(fallthrough) + #define CYTHON_FALLTHROUGH __attribute__((fallthrough)) + #else + #define CYTHON_FALLTHROUGH + #endif + #endif + #if defined(__clang__) && defined(__apple_build_version__) + #if __apple_build_version__ < 7000000 + #undef CYTHON_FALLTHROUGH + #define CYTHON_FALLTHROUGH + #endif + #endif +#endif +#ifdef __cplusplus + template + struct __PYX_IS_UNSIGNED_IMPL {static const bool value = T(0) < T(-1);}; + #define __PYX_IS_UNSIGNED(type) (__PYX_IS_UNSIGNED_IMPL::value) +#else + #define __PYX_IS_UNSIGNED(type) (((type)-1) > 0) +#endif +#if CYTHON_COMPILING_IN_PYPY == 1 + #define __PYX_NEED_TP_PRINT_SLOT (PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x030A0000) +#else + #define __PYX_NEED_TP_PRINT_SLOT (PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000) +#endif +#define __PYX_REINTERPRET_FUNCION(func_pointer, other_pointer) ((func_pointer)(void(*)(void))(other_pointer)) + +#ifndef __cplusplus + #error "Cython files generated with the C++ option must be compiled with a C++ compiler." +#endif +#ifndef CYTHON_INLINE + #if defined(__clang__) + #define CYTHON_INLINE __inline__ __attribute__ ((__unused__)) + #else + #define CYTHON_INLINE inline + #endif +#endif +template +void __Pyx_call_destructor(T& x) { + x.~T(); +} +template +class __Pyx_FakeReference { + public: + __Pyx_FakeReference() : ptr(NULL) { } + __Pyx_FakeReference(const T& ref) : ptr(const_cast(&ref)) { } + T *operator->() { return ptr; } + T *operator&() { return ptr; } + operator T&() { return *ptr; } + template bool operator ==(const U& other) const { return *ptr == other; } + template bool operator !=(const U& other) const { return *ptr != other; } + template bool operator==(const __Pyx_FakeReference& other) const { return *ptr == *other.ptr; } + template bool operator!=(const __Pyx_FakeReference& other) const { return *ptr != *other.ptr; } + private: + T *ptr; +}; + +#define __PYX_BUILD_PY_SSIZE_T "n" +#define CYTHON_FORMAT_SSIZE_T "z" +#if PY_MAJOR_VERSION < 3 + #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" + #define __Pyx_DefaultClassType PyClass_Type + #define __Pyx_PyCode_New(a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ + PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#else + #define __Pyx_BUILTIN_MODULE_NAME "builtins" + #define __Pyx_DefaultClassType PyType_Type +#if CYTHON_COMPILING_IN_LIMITED_API + static CYTHON_INLINE PyObject* __Pyx_PyCode_New(int a, int p, int k, int l, int s, int f, + PyObject *code, PyObject *c, PyObject* n, PyObject *v, + PyObject *fv, PyObject *cell, PyObject* fn, + PyObject *name, int fline, PyObject *lnos) { + PyObject *exception_table = NULL; + PyObject *types_module=NULL, *code_type=NULL, *result=NULL; + #if __PYX_LIMITED_VERSION_HEX < 0x030B0000 + PyObject *version_info; + PyObject *py_minor_version = NULL; + #endif + long minor_version = 0; + PyObject *type, *value, *traceback; + PyErr_Fetch(&type, &value, &traceback); + #if __PYX_LIMITED_VERSION_HEX >= 0x030B0000 + minor_version = 11; + #else + if (!(version_info = PySys_GetObject("version_info"))) goto end; + if (!(py_minor_version = PySequence_GetItem(version_info, 1))) goto end; + minor_version = PyLong_AsLong(py_minor_version); + Py_DECREF(py_minor_version); + if (minor_version == -1 && PyErr_Occurred()) goto end; + #endif + if (!(types_module = PyImport_ImportModule("types"))) goto end; + if (!(code_type = PyObject_GetAttrString(types_module, "CodeType"))) goto end; + if (minor_version <= 7) { + (void)p; + result = PyObject_CallFunction(code_type, "iiiiiOOOOOOiOO", a, k, l, s, f, code, + c, n, v, fn, name, fline, lnos, fv, cell); + } else if (minor_version <= 10) { + result = PyObject_CallFunction(code_type, "iiiiiiOOOOOOiOO", a,p, k, l, s, f, code, + c, n, v, fn, name, fline, lnos, fv, cell); + } else { + if (!(exception_table = PyBytes_FromStringAndSize(NULL, 0))) goto end; + result = PyObject_CallFunction(code_type, "iiiiiiOOOOOOOiOO", a,p, k, l, s, f, code, + c, n, v, fn, name, name, fline, lnos, exception_table, fv, cell); + } + end: + Py_XDECREF(code_type); + Py_XDECREF(exception_table); + Py_XDECREF(types_module); + if (type) { + PyErr_Restore(type, value, traceback); + } + return result; + } + #ifndef CO_OPTIMIZED + #define CO_OPTIMIZED 0x0001 + #endif + #ifndef CO_NEWLOCALS + #define CO_NEWLOCALS 0x0002 + #endif + #ifndef CO_VARARGS + #define CO_VARARGS 0x0004 + #endif + #ifndef CO_VARKEYWORDS + #define CO_VARKEYWORDS 0x0008 + #endif + #ifndef CO_ASYNC_GENERATOR + #define CO_ASYNC_GENERATOR 0x0200 + #endif + #ifndef CO_GENERATOR + #define CO_GENERATOR 0x0020 + #endif + #ifndef CO_COROUTINE + #define CO_COROUTINE 0x0080 + #endif +#elif PY_VERSION_HEX >= 0x030B0000 + static CYTHON_INLINE PyCodeObject* __Pyx_PyCode_New(int a, int p, int k, int l, int s, int f, + PyObject *code, PyObject *c, PyObject* n, PyObject *v, + PyObject *fv, PyObject *cell, PyObject* fn, + PyObject *name, int fline, PyObject *lnos) { + PyCodeObject *result; + PyObject *empty_bytes = PyBytes_FromStringAndSize("", 0); + if (!empty_bytes) return NULL; + result = + #if PY_VERSION_HEX >= 0x030C0000 + PyUnstable_Code_NewWithPosOnlyArgs + #else + PyCode_NewWithPosOnlyArgs + #endif + (a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, name, fline, lnos, empty_bytes); + Py_DECREF(empty_bytes); + return result; + } +#elif PY_VERSION_HEX >= 0x030800B2 && !CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyCode_New(a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ + PyCode_NewWithPosOnlyArgs(a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#else + #define __Pyx_PyCode_New(a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ + PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#endif +#endif +#if PY_VERSION_HEX >= 0x030900A4 || defined(Py_IS_TYPE) + #define __Pyx_IS_TYPE(ob, type) Py_IS_TYPE(ob, type) +#else + #define __Pyx_IS_TYPE(ob, type) (((const PyObject*)ob)->ob_type == (type)) +#endif +#if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_Is) + #define __Pyx_Py_Is(x, y) Py_Is(x, y) +#else + #define __Pyx_Py_Is(x, y) ((x) == (y)) +#endif +#if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_IsNone) + #define __Pyx_Py_IsNone(ob) Py_IsNone(ob) +#else + #define __Pyx_Py_IsNone(ob) __Pyx_Py_Is((ob), Py_None) +#endif +#if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_IsTrue) + #define __Pyx_Py_IsTrue(ob) Py_IsTrue(ob) +#else + #define __Pyx_Py_IsTrue(ob) __Pyx_Py_Is((ob), Py_True) +#endif +#if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_IsFalse) + #define __Pyx_Py_IsFalse(ob) Py_IsFalse(ob) +#else + #define __Pyx_Py_IsFalse(ob) __Pyx_Py_Is((ob), Py_False) +#endif +#define __Pyx_NoneAsNull(obj) (__Pyx_Py_IsNone(obj) ? NULL : (obj)) +#if PY_VERSION_HEX >= 0x030900F0 && !CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyObject_GC_IsFinalized(o) PyObject_GC_IsFinalized(o) +#else + #define __Pyx_PyObject_GC_IsFinalized(o) _PyGC_FINALIZED(o) +#endif +#ifndef CO_COROUTINE + #define CO_COROUTINE 0x80 +#endif +#ifndef CO_ASYNC_GENERATOR + #define CO_ASYNC_GENERATOR 0x200 +#endif +#ifndef Py_TPFLAGS_CHECKTYPES + #define Py_TPFLAGS_CHECKTYPES 0 +#endif +#ifndef Py_TPFLAGS_HAVE_INDEX + #define Py_TPFLAGS_HAVE_INDEX 0 +#endif +#ifndef Py_TPFLAGS_HAVE_NEWBUFFER + #define Py_TPFLAGS_HAVE_NEWBUFFER 0 +#endif +#ifndef Py_TPFLAGS_HAVE_FINALIZE + #define Py_TPFLAGS_HAVE_FINALIZE 0 +#endif +#ifndef Py_TPFLAGS_SEQUENCE + #define Py_TPFLAGS_SEQUENCE 0 +#endif +#ifndef Py_TPFLAGS_MAPPING + #define Py_TPFLAGS_MAPPING 0 +#endif +#ifndef METH_STACKLESS + #define METH_STACKLESS 0 +#endif +#if PY_VERSION_HEX <= 0x030700A3 || !defined(METH_FASTCALL) + #ifndef METH_FASTCALL + #define METH_FASTCALL 0x80 + #endif + typedef PyObject *(*__Pyx_PyCFunctionFast) (PyObject *self, PyObject *const *args, Py_ssize_t nargs); + typedef PyObject *(*__Pyx_PyCFunctionFastWithKeywords) (PyObject *self, PyObject *const *args, + Py_ssize_t nargs, PyObject *kwnames); +#else + #define __Pyx_PyCFunctionFast _PyCFunctionFast + #define __Pyx_PyCFunctionFastWithKeywords _PyCFunctionFastWithKeywords +#endif +#if CYTHON_METH_FASTCALL + #define __Pyx_METH_FASTCALL METH_FASTCALL + #define __Pyx_PyCFunction_FastCall __Pyx_PyCFunctionFast + #define __Pyx_PyCFunction_FastCallWithKeywords __Pyx_PyCFunctionFastWithKeywords +#else + #define __Pyx_METH_FASTCALL METH_VARARGS + #define __Pyx_PyCFunction_FastCall PyCFunction + #define __Pyx_PyCFunction_FastCallWithKeywords PyCFunctionWithKeywords +#endif +#if CYTHON_VECTORCALL + #define __pyx_vectorcallfunc vectorcallfunc + #define __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET PY_VECTORCALL_ARGUMENTS_OFFSET + #define __Pyx_PyVectorcall_NARGS(n) PyVectorcall_NARGS((size_t)(n)) +#elif CYTHON_BACKPORT_VECTORCALL + typedef PyObject *(*__pyx_vectorcallfunc)(PyObject *callable, PyObject *const *args, + size_t nargsf, PyObject *kwnames); + #define __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET ((size_t)1 << (8 * sizeof(size_t) - 1)) + #define __Pyx_PyVectorcall_NARGS(n) ((Py_ssize_t)(((size_t)(n)) & ~__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)) +#else + #define __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET 0 + #define __Pyx_PyVectorcall_NARGS(n) ((Py_ssize_t)(n)) +#endif +#if PY_MAJOR_VERSION >= 0x030900B1 +#define __Pyx_PyCFunction_CheckExact(func) PyCFunction_CheckExact(func) +#else +#define __Pyx_PyCFunction_CheckExact(func) PyCFunction_Check(func) +#endif +#define __Pyx_CyOrPyCFunction_Check(func) PyCFunction_Check(func) +#if CYTHON_COMPILING_IN_CPYTHON +#define __Pyx_CyOrPyCFunction_GET_FUNCTION(func) (((PyCFunctionObject*)(func))->m_ml->ml_meth) +#elif !CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_CyOrPyCFunction_GET_FUNCTION(func) PyCFunction_GET_FUNCTION(func) +#endif +#if CYTHON_COMPILING_IN_CPYTHON +#define __Pyx_CyOrPyCFunction_GET_FLAGS(func) (((PyCFunctionObject*)(func))->m_ml->ml_flags) +static CYTHON_INLINE PyObject* __Pyx_CyOrPyCFunction_GET_SELF(PyObject *func) { + return (__Pyx_CyOrPyCFunction_GET_FLAGS(func) & METH_STATIC) ? NULL : ((PyCFunctionObject*)func)->m_self; +} +#endif +static CYTHON_INLINE int __Pyx__IsSameCFunction(PyObject *func, void *cfunc) { +#if CYTHON_COMPILING_IN_LIMITED_API + return PyCFunction_Check(func) && PyCFunction_GetFunction(func) == (PyCFunction) cfunc; +#else + return PyCFunction_Check(func) && PyCFunction_GET_FUNCTION(func) == (PyCFunction) cfunc; +#endif +} +#define __Pyx_IsSameCFunction(func, cfunc) __Pyx__IsSameCFunction(func, cfunc) +#if __PYX_LIMITED_VERSION_HEX < 0x030900B1 + #define __Pyx_PyType_FromModuleAndSpec(m, s, b) ((void)m, PyType_FromSpecWithBases(s, b)) + typedef PyObject *(*__Pyx_PyCMethod)(PyObject *, PyTypeObject *, PyObject *const *, size_t, PyObject *); +#else + #define __Pyx_PyType_FromModuleAndSpec(m, s, b) PyType_FromModuleAndSpec(m, s, b) + #define __Pyx_PyCMethod PyCMethod +#endif +#ifndef METH_METHOD + #define METH_METHOD 0x200 +#endif +#if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Malloc) + #define PyObject_Malloc(s) PyMem_Malloc(s) + #define PyObject_Free(p) PyMem_Free(p) + #define PyObject_Realloc(p) PyMem_Realloc(p) +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) + #define __Pyx_PyFrame_SetLineNumber(frame, lineno) +#else + #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) + #define __Pyx_PyFrame_SetLineNumber(frame, lineno) (frame)->f_lineno = (lineno) +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_PyThreadState_Current PyThreadState_Get() +#elif !CYTHON_FAST_THREAD_STATE + #define __Pyx_PyThreadState_Current PyThreadState_GET() +#elif PY_VERSION_HEX >= 0x030d00A1 + #define __Pyx_PyThreadState_Current PyThreadState_GetUnchecked() +#elif PY_VERSION_HEX >= 0x03060000 + #define __Pyx_PyThreadState_Current _PyThreadState_UncheckedGet() +#elif PY_VERSION_HEX >= 0x03000000 + #define __Pyx_PyThreadState_Current PyThreadState_GET() +#else + #define __Pyx_PyThreadState_Current _PyThreadState_Current +#endif +#if CYTHON_COMPILING_IN_LIMITED_API +static CYTHON_INLINE void *__Pyx_PyModule_GetState(PyObject *op) +{ + void *result; + result = PyModule_GetState(op); + if (!result) + Py_FatalError("Couldn't find the module state"); + return result; +} +#endif +#define __Pyx_PyObject_GetSlot(obj, name, func_ctype) __Pyx_PyType_GetSlot(Py_TYPE(obj), name, func_ctype) +#if CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_PyType_GetSlot(type, name, func_ctype) ((func_ctype) PyType_GetSlot((type), Py_##name)) +#else + #define __Pyx_PyType_GetSlot(type, name, func_ctype) ((type)->name) +#endif +#if PY_VERSION_HEX < 0x030700A2 && !defined(PyThread_tss_create) && !defined(Py_tss_NEEDS_INIT) +#include "pythread.h" +#define Py_tss_NEEDS_INIT 0 +typedef int Py_tss_t; +static CYTHON_INLINE int PyThread_tss_create(Py_tss_t *key) { + *key = PyThread_create_key(); + return 0; +} +static CYTHON_INLINE Py_tss_t * PyThread_tss_alloc(void) { + Py_tss_t *key = (Py_tss_t *)PyObject_Malloc(sizeof(Py_tss_t)); + *key = Py_tss_NEEDS_INIT; + return key; +} +static CYTHON_INLINE void PyThread_tss_free(Py_tss_t *key) { + PyObject_Free(key); +} +static CYTHON_INLINE int PyThread_tss_is_created(Py_tss_t *key) { + return *key != Py_tss_NEEDS_INIT; +} +static CYTHON_INLINE void PyThread_tss_delete(Py_tss_t *key) { + PyThread_delete_key(*key); + *key = Py_tss_NEEDS_INIT; +} +static CYTHON_INLINE int PyThread_tss_set(Py_tss_t *key, void *value) { + return PyThread_set_key_value(*key, value); +} +static CYTHON_INLINE void * PyThread_tss_get(Py_tss_t *key) { + return PyThread_get_key_value(*key); +} +#endif +#if PY_MAJOR_VERSION < 3 + #if CYTHON_COMPILING_IN_PYPY + #if PYPY_VERSION_NUM < 0x07030600 + #if defined(__cplusplus) && __cplusplus >= 201402L + [[deprecated("`with nogil:` inside a nogil function will not release the GIL in PyPy2 < 7.3.6")]] + #elif defined(__GNUC__) || defined(__clang__) + __attribute__ ((__deprecated__("`with nogil:` inside a nogil function will not release the GIL in PyPy2 < 7.3.6"))) + #elif defined(_MSC_VER) + __declspec(deprecated("`with nogil:` inside a nogil function will not release the GIL in PyPy2 < 7.3.6")) + #endif + static CYTHON_INLINE int PyGILState_Check(void) { + return 0; + } + #else // PYPY_VERSION_NUM < 0x07030600 + #endif // PYPY_VERSION_NUM < 0x07030600 + #else + static CYTHON_INLINE int PyGILState_Check(void) { + PyThreadState * tstate = _PyThreadState_Current; + return tstate && (tstate == PyGILState_GetThisThreadState()); + } + #endif +#endif +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030d0000 || defined(_PyDict_NewPresized) +#define __Pyx_PyDict_NewPresized(n) ((n <= 8) ? PyDict_New() : _PyDict_NewPresized(n)) +#else +#define __Pyx_PyDict_NewPresized(n) PyDict_New() +#endif +#if PY_MAJOR_VERSION >= 3 || CYTHON_FUTURE_DIVISION + #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) +#else + #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) +#endif +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX > 0x030600B4 && PY_VERSION_HEX < 0x030d0000 && CYTHON_USE_UNICODE_INTERNALS +#define __Pyx_PyDict_GetItemStrWithError(dict, name) _PyDict_GetItem_KnownHash(dict, name, ((PyASCIIObject *) name)->hash) +static CYTHON_INLINE PyObject * __Pyx_PyDict_GetItemStr(PyObject *dict, PyObject *name) { + PyObject *res = __Pyx_PyDict_GetItemStrWithError(dict, name); + if (res == NULL) PyErr_Clear(); + return res; +} +#elif PY_MAJOR_VERSION >= 3 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07020000) +#define __Pyx_PyDict_GetItemStrWithError PyDict_GetItemWithError +#define __Pyx_PyDict_GetItemStr PyDict_GetItem +#else +static CYTHON_INLINE PyObject * __Pyx_PyDict_GetItemStrWithError(PyObject *dict, PyObject *name) { +#if CYTHON_COMPILING_IN_PYPY + return PyDict_GetItem(dict, name); +#else + PyDictEntry *ep; + PyDictObject *mp = (PyDictObject*) dict; + long hash = ((PyStringObject *) name)->ob_shash; + assert(hash != -1); + ep = (mp->ma_lookup)(mp, name, hash); + if (ep == NULL) { + return NULL; + } + return ep->me_value; +#endif +} +#define __Pyx_PyDict_GetItemStr PyDict_GetItem +#endif +#if CYTHON_USE_TYPE_SLOTS + #define __Pyx_PyType_GetFlags(tp) (((PyTypeObject *)tp)->tp_flags) + #define __Pyx_PyType_HasFeature(type, feature) ((__Pyx_PyType_GetFlags(type) & (feature)) != 0) + #define __Pyx_PyObject_GetIterNextFunc(obj) (Py_TYPE(obj)->tp_iternext) +#else + #define __Pyx_PyType_GetFlags(tp) (PyType_GetFlags((PyTypeObject *)tp)) + #define __Pyx_PyType_HasFeature(type, feature) PyType_HasFeature(type, feature) + #define __Pyx_PyObject_GetIterNextFunc(obj) PyIter_Next +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_SetItemOnTypeDict(tp, k, v) PyObject_GenericSetAttr((PyObject*)tp, k, v) +#else + #define __Pyx_SetItemOnTypeDict(tp, k, v) PyDict_SetItem(tp->tp_dict, k, v) +#endif +#if CYTHON_USE_TYPE_SPECS && PY_VERSION_HEX >= 0x03080000 +#define __Pyx_PyHeapTypeObject_GC_Del(obj) {\ + PyTypeObject *type = Py_TYPE((PyObject*)obj);\ + assert(__Pyx_PyType_HasFeature(type, Py_TPFLAGS_HEAPTYPE));\ + PyObject_GC_Del(obj);\ + Py_DECREF(type);\ +} +#else +#define __Pyx_PyHeapTypeObject_GC_Del(obj) PyObject_GC_Del(obj) +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + #define CYTHON_PEP393_ENABLED 1 + #define __Pyx_PyUnicode_READY(op) (0) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GetLength(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_ReadChar(u, i) + #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) ((void)u, 1114111U) + #define __Pyx_PyUnicode_KIND(u) ((void)u, (0)) + #define __Pyx_PyUnicode_DATA(u) ((void*)u) + #define __Pyx_PyUnicode_READ(k, d, i) ((void)k, PyUnicode_ReadChar((PyObject*)(d), i)) + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GetLength(u)) +#elif PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) + #define CYTHON_PEP393_ENABLED 1 + #if PY_VERSION_HEX >= 0x030C0000 + #define __Pyx_PyUnicode_READY(op) (0) + #else + #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ?\ + 0 : _PyUnicode_Ready((PyObject *)(op))) + #endif + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) + #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) PyUnicode_MAX_CHAR_VALUE(u) + #define __Pyx_PyUnicode_KIND(u) ((int)PyUnicode_KIND(u)) + #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) + #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) + #define __Pyx_PyUnicode_WRITE(k, d, i, ch) PyUnicode_WRITE(k, d, i, (Py_UCS4) ch) + #if PY_VERSION_HEX >= 0x030C0000 + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_LENGTH(u)) + #else + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x03090000 + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : ((PyCompactUnicodeObject *)(u))->wstr_length)) + #else + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : PyUnicode_GET_SIZE(u))) + #endif + #endif +#else + #define CYTHON_PEP393_ENABLED 0 + #define PyUnicode_1BYTE_KIND 1 + #define PyUnicode_2BYTE_KIND 2 + #define PyUnicode_4BYTE_KIND 4 + #define __Pyx_PyUnicode_READY(op) (0) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) + #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) ((sizeof(Py_UNICODE) == 2) ? 65535U : 1114111U) + #define __Pyx_PyUnicode_KIND(u) ((int)sizeof(Py_UNICODE)) + #define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u)) + #define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i])) + #define __Pyx_PyUnicode_WRITE(k, d, i, ch) (((void)(k)), ((Py_UNICODE*)d)[i] = (Py_UNICODE) ch) + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_SIZE(u)) +#endif +#if CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) +#else + #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ?\ + PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) +#endif +#if CYTHON_COMPILING_IN_PYPY + #if !defined(PyUnicode_DecodeUnicodeEscape) + #define PyUnicode_DecodeUnicodeEscape(s, size, errors) PyUnicode_Decode(s, size, "unicode_escape", errors) + #endif + #if !defined(PyUnicode_Contains) || (PY_MAJOR_VERSION == 2 && PYPY_VERSION_NUM < 0x07030500) + #undef PyUnicode_Contains + #define PyUnicode_Contains(u, s) PySequence_Contains(u, s) + #endif + #if !defined(PyByteArray_Check) + #define PyByteArray_Check(obj) PyObject_TypeCheck(obj, &PyByteArray_Type) + #endif + #if !defined(PyObject_Format) + #define PyObject_Format(obj, fmt) PyObject_CallMethod(obj, "__format__", "O", fmt) + #endif +#endif +#define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyString_Check(b) && !PyString_CheckExact(b)))) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) +#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyUnicode_Check(b) && !PyUnicode_CheckExact(b)))) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b) +#else + #define __Pyx_PyString_Format(a, b) PyString_Format(a, b) +#endif +#if PY_MAJOR_VERSION < 3 && !defined(PyObject_ASCII) + #define PyObject_ASCII(o) PyObject_Repr(o) +#endif +#if PY_MAJOR_VERSION >= 3 + #define PyBaseString_Type PyUnicode_Type + #define PyStringObject PyUnicodeObject + #define PyString_Type PyUnicode_Type + #define PyString_Check PyUnicode_Check + #define PyString_CheckExact PyUnicode_CheckExact +#ifndef PyObject_Unicode + #define PyObject_Unicode PyObject_Str +#endif +#endif +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) + #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) +#else + #define __Pyx_PyBaseString_Check(obj) (PyString_Check(obj) || PyUnicode_Check(obj)) + #define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj)) +#endif +#if CYTHON_COMPILING_IN_CPYTHON + #define __Pyx_PySequence_ListKeepNew(obj)\ + (likely(PyList_CheckExact(obj) && Py_REFCNT(obj) == 1) ? __Pyx_NewRef(obj) : PySequence_List(obj)) +#else + #define __Pyx_PySequence_ListKeepNew(obj) PySequence_List(obj) +#endif +#ifndef PySet_CheckExact + #define PySet_CheckExact(obj) __Pyx_IS_TYPE(obj, &PySet_Type) +#endif +#if PY_VERSION_HEX >= 0x030900A4 + #define __Pyx_SET_REFCNT(obj, refcnt) Py_SET_REFCNT(obj, refcnt) + #define __Pyx_SET_SIZE(obj, size) Py_SET_SIZE(obj, size) +#else + #define __Pyx_SET_REFCNT(obj, refcnt) Py_REFCNT(obj) = (refcnt) + #define __Pyx_SET_SIZE(obj, size) Py_SIZE(obj) = (size) +#endif +#if CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_PySequence_ITEM(o, i) PySequence_ITEM(o, i) + #define __Pyx_PySequence_SIZE(seq) Py_SIZE(seq) + #define __Pyx_PyTuple_SET_ITEM(o, i, v) (PyTuple_SET_ITEM(o, i, v), (0)) + #define __Pyx_PyList_SET_ITEM(o, i, v) (PyList_SET_ITEM(o, i, v), (0)) + #define __Pyx_PyTuple_GET_SIZE(o) PyTuple_GET_SIZE(o) + #define __Pyx_PyList_GET_SIZE(o) PyList_GET_SIZE(o) + #define __Pyx_PySet_GET_SIZE(o) PySet_GET_SIZE(o) + #define __Pyx_PyBytes_GET_SIZE(o) PyBytes_GET_SIZE(o) + #define __Pyx_PyByteArray_GET_SIZE(o) PyByteArray_GET_SIZE(o) +#else + #define __Pyx_PySequence_ITEM(o, i) PySequence_GetItem(o, i) + #define __Pyx_PySequence_SIZE(seq) PySequence_Size(seq) + #define __Pyx_PyTuple_SET_ITEM(o, i, v) PyTuple_SetItem(o, i, v) + #define __Pyx_PyList_SET_ITEM(o, i, v) PyList_SetItem(o, i, v) + #define __Pyx_PyTuple_GET_SIZE(o) PyTuple_Size(o) + #define __Pyx_PyList_GET_SIZE(o) PyList_Size(o) + #define __Pyx_PySet_GET_SIZE(o) PySet_Size(o) + #define __Pyx_PyBytes_GET_SIZE(o) PyBytes_Size(o) + #define __Pyx_PyByteArray_GET_SIZE(o) PyByteArray_Size(o) +#endif +#if PY_VERSION_HEX >= 0x030d00A1 + #define __Pyx_PyImport_AddModuleRef(name) PyImport_AddModuleRef(name) +#else + static CYTHON_INLINE PyObject *__Pyx_PyImport_AddModuleRef(const char *name) { + PyObject *module = PyImport_AddModule(name); + Py_XINCREF(module); + return module; + } +#endif +#if PY_MAJOR_VERSION >= 3 + #define PyIntObject PyLongObject + #define PyInt_Type PyLong_Type + #define PyInt_Check(op) PyLong_Check(op) + #define PyInt_CheckExact(op) PyLong_CheckExact(op) + #define __Pyx_Py3Int_Check(op) PyLong_Check(op) + #define __Pyx_Py3Int_CheckExact(op) PyLong_CheckExact(op) + #define PyInt_FromString PyLong_FromString + #define PyInt_FromUnicode PyLong_FromUnicode + #define PyInt_FromLong PyLong_FromLong + #define PyInt_FromSize_t PyLong_FromSize_t + #define PyInt_FromSsize_t PyLong_FromSsize_t + #define PyInt_AsLong PyLong_AsLong + #define PyInt_AS_LONG PyLong_AS_LONG + #define PyInt_AsSsize_t PyLong_AsSsize_t + #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask + #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask + #define PyNumber_Int PyNumber_Long +#else + #define __Pyx_Py3Int_Check(op) (PyLong_Check(op) || PyInt_Check(op)) + #define __Pyx_Py3Int_CheckExact(op) (PyLong_CheckExact(op) || PyInt_CheckExact(op)) +#endif +#if PY_MAJOR_VERSION >= 3 + #define PyBoolObject PyLongObject +#endif +#if PY_MAJOR_VERSION >= 3 && CYTHON_COMPILING_IN_PYPY + #ifndef PyUnicode_InternFromString + #define PyUnicode_InternFromString(s) PyUnicode_FromString(s) + #endif +#endif +#if PY_VERSION_HEX < 0x030200A4 + typedef long Py_hash_t; + #define __Pyx_PyInt_FromHash_t PyInt_FromLong + #define __Pyx_PyInt_AsHash_t __Pyx_PyIndex_AsHash_t +#else + #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t + #define __Pyx_PyInt_AsHash_t __Pyx_PyIndex_AsSsize_t +#endif +#if CYTHON_USE_ASYNC_SLOTS + #if PY_VERSION_HEX >= 0x030500B1 + #define __Pyx_PyAsyncMethodsStruct PyAsyncMethods + #define __Pyx_PyType_AsAsync(obj) (Py_TYPE(obj)->tp_as_async) + #else + #define __Pyx_PyType_AsAsync(obj) ((__Pyx_PyAsyncMethodsStruct*) (Py_TYPE(obj)->tp_reserved)) + #endif +#else + #define __Pyx_PyType_AsAsync(obj) NULL +#endif +#ifndef __Pyx_PyAsyncMethodsStruct + typedef struct { + unaryfunc am_await; + unaryfunc am_aiter; + unaryfunc am_anext; + } __Pyx_PyAsyncMethodsStruct; +#endif + +#if defined(_WIN32) || defined(WIN32) || defined(MS_WINDOWS) + #if !defined(_USE_MATH_DEFINES) + #define _USE_MATH_DEFINES + #endif +#endif +#include +#ifdef NAN +#define __PYX_NAN() ((float) NAN) +#else +static CYTHON_INLINE float __PYX_NAN() { + float value; + memset(&value, 0xFF, sizeof(value)); + return value; +} +#endif +#if defined(__CYGWIN__) && defined(_LDBL_EQ_DBL) +#define __Pyx_truncl trunc +#else +#define __Pyx_truncl truncl +#endif + +#define __PYX_MARK_ERR_POS(f_index, lineno) \ + { __pyx_filename = __pyx_f[f_index]; (void)__pyx_filename; __pyx_lineno = lineno; (void)__pyx_lineno; __pyx_clineno = __LINE__; (void)__pyx_clineno; } +#define __PYX_ERR(f_index, lineno, Ln_error) \ + { __PYX_MARK_ERR_POS(f_index, lineno) goto Ln_error; } + +#ifdef CYTHON_EXTERN_C + #undef __PYX_EXTERN_C + #define __PYX_EXTERN_C CYTHON_EXTERN_C +#elif defined(__PYX_EXTERN_C) + #ifdef _MSC_VER + #pragma message ("Please do not define the '__PYX_EXTERN_C' macro externally. Use 'CYTHON_EXTERN_C' instead.") + #else + #warning Please do not define the '__PYX_EXTERN_C' macro externally. Use 'CYTHON_EXTERN_C' instead. + #endif +#else + #define __PYX_EXTERN_C extern "C++" +#endif + +#define __PYX_HAVE__curated_tokenizers___spp +#define __PYX_HAVE_API__curated_tokenizers___spp +/* Early includes */ +#include +#include "ios" +#include "new" +#include "stdexcept" +#include "typeinfo" +#include +#include +#include +#include +#include "builtin_pb/sentencepiece.pb.h" +#include "sentencepiece_processor.h" +#ifdef _OPENMP +#include +#endif /* _OPENMP */ + +#if defined(PYREX_WITHOUT_ASSERTIONS) && !defined(CYTHON_WITHOUT_ASSERTIONS) +#define CYTHON_WITHOUT_ASSERTIONS +#endif + +typedef struct {PyObject **p; const char *s; const Py_ssize_t n; const char* encoding; + const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; + +#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 +#define __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 0 +#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT (PY_MAJOR_VERSION >= 3 && __PYX_DEFAULT_STRING_ENCODING_IS_UTF8) +#define __PYX_DEFAULT_STRING_ENCODING "" +#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString +#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#define __Pyx_uchar_cast(c) ((unsigned char)c) +#define __Pyx_long_cast(x) ((long)x) +#define __Pyx_fits_Py_ssize_t(v, type, is_signed) (\ + (sizeof(type) < sizeof(Py_ssize_t)) ||\ + (sizeof(type) > sizeof(Py_ssize_t) &&\ + likely(v < (type)PY_SSIZE_T_MAX ||\ + v == (type)PY_SSIZE_T_MAX) &&\ + (!is_signed || likely(v > (type)PY_SSIZE_T_MIN ||\ + v == (type)PY_SSIZE_T_MIN))) ||\ + (sizeof(type) == sizeof(Py_ssize_t) &&\ + (is_signed || likely(v < (type)PY_SSIZE_T_MAX ||\ + v == (type)PY_SSIZE_T_MAX))) ) +static CYTHON_INLINE int __Pyx_is_valid_index(Py_ssize_t i, Py_ssize_t limit) { + return (size_t) i < (size_t) limit; +} +#if defined (__cplusplus) && __cplusplus >= 201103L + #include + #define __Pyx_sst_abs(value) std::abs(value) +#elif SIZEOF_INT >= SIZEOF_SIZE_T + #define __Pyx_sst_abs(value) abs(value) +#elif SIZEOF_LONG >= SIZEOF_SIZE_T + #define __Pyx_sst_abs(value) labs(value) +#elif defined (_MSC_VER) + #define __Pyx_sst_abs(value) ((Py_ssize_t)_abs64(value)) +#elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define __Pyx_sst_abs(value) llabs(value) +#elif defined (__GNUC__) + #define __Pyx_sst_abs(value) __builtin_llabs(value) +#else + #define __Pyx_sst_abs(value) ((value<0) ? -value : value) +#endif +static CYTHON_INLINE Py_ssize_t __Pyx_ssize_strlen(const char *s); +static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject*); +static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); +static CYTHON_INLINE PyObject* __Pyx_PyByteArray_FromString(const char*); +#define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) +#define __Pyx_PyBytes_FromString PyBytes_FromString +#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#else + #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize +#endif +#define __Pyx_PyBytes_AsWritableString(s) ((char*) PyBytes_AS_STRING(s)) +#define __Pyx_PyBytes_AsWritableSString(s) ((signed char*) PyBytes_AS_STRING(s)) +#define __Pyx_PyBytes_AsWritableUString(s) ((unsigned char*) PyBytes_AS_STRING(s)) +#define __Pyx_PyBytes_AsString(s) ((const char*) PyBytes_AS_STRING(s)) +#define __Pyx_PyBytes_AsSString(s) ((const signed char*) PyBytes_AS_STRING(s)) +#define __Pyx_PyBytes_AsUString(s) ((const unsigned char*) PyBytes_AS_STRING(s)) +#define __Pyx_PyObject_AsWritableString(s) ((char*)(__pyx_uintptr_t) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsWritableSString(s) ((signed char*)(__pyx_uintptr_t) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsWritableUString(s) ((unsigned char*)(__pyx_uintptr_t) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsSString(s) ((const signed char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsUString(s) ((const unsigned char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_FromCString(s) __Pyx_PyObject_FromString((const char*)s) +#define __Pyx_PyBytes_FromCString(s) __Pyx_PyBytes_FromString((const char*)s) +#define __Pyx_PyByteArray_FromCString(s) __Pyx_PyByteArray_FromString((const char*)s) +#define __Pyx_PyStr_FromCString(s) __Pyx_PyStr_FromString((const char*)s) +#define __Pyx_PyUnicode_FromCString(s) __Pyx_PyUnicode_FromString((const char*)s) +#if CYTHON_COMPILING_IN_LIMITED_API +static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const wchar_t *u) +{ + const wchar_t *u_end = u; + while (*u_end++) ; + return (size_t)(u_end - u - 1); +} +#else +static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) +{ + const Py_UNICODE *u_end = u; + while (*u_end++) ; + return (size_t)(u_end - u - 1); +} +#endif +#define __Pyx_PyUnicode_FromOrdinal(o) PyUnicode_FromOrdinal((int)o) +#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) +#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode +#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode +#define __Pyx_NewRef(obj) (Py_INCREF(obj), obj) +#define __Pyx_Owned_Py_None(b) __Pyx_NewRef(Py_None) +static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b); +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); +static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject*); +static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x); +#define __Pyx_PySequence_Tuple(obj)\ + (likely(PyTuple_CheckExact(obj)) ? __Pyx_NewRef(obj) : PySequence_Tuple(obj)) +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); +static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); +static CYTHON_INLINE Py_hash_t __Pyx_PyIndex_AsHash_t(PyObject*); +#if CYTHON_ASSUME_SAFE_MACROS +#define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) +#else +#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) +#endif +#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) +#if PY_MAJOR_VERSION >= 3 +#define __Pyx_PyNumber_Int(x) (PyLong_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Long(x)) +#else +#define __Pyx_PyNumber_Int(x) (PyInt_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Int(x)) +#endif +#if CYTHON_USE_PYLONG_INTERNALS + #if PY_VERSION_HEX >= 0x030C00A7 + #ifndef _PyLong_SIGN_MASK + #define _PyLong_SIGN_MASK 3 + #endif + #ifndef _PyLong_NON_SIZE_BITS + #define _PyLong_NON_SIZE_BITS 3 + #endif + #define __Pyx_PyLong_Sign(x) (((PyLongObject*)x)->long_value.lv_tag & _PyLong_SIGN_MASK) + #define __Pyx_PyLong_IsNeg(x) ((__Pyx_PyLong_Sign(x) & 2) != 0) + #define __Pyx_PyLong_IsNonNeg(x) (!__Pyx_PyLong_IsNeg(x)) + #define __Pyx_PyLong_IsZero(x) (__Pyx_PyLong_Sign(x) & 1) + #define __Pyx_PyLong_IsPos(x) (__Pyx_PyLong_Sign(x) == 0) + #define __Pyx_PyLong_CompactValueUnsigned(x) (__Pyx_PyLong_Digits(x)[0]) + #define __Pyx_PyLong_DigitCount(x) ((Py_ssize_t) (((PyLongObject*)x)->long_value.lv_tag >> _PyLong_NON_SIZE_BITS)) + #define __Pyx_PyLong_SignedDigitCount(x)\ + ((1 - (Py_ssize_t) __Pyx_PyLong_Sign(x)) * __Pyx_PyLong_DigitCount(x)) + #if defined(PyUnstable_Long_IsCompact) && defined(PyUnstable_Long_CompactValue) + #define __Pyx_PyLong_IsCompact(x) PyUnstable_Long_IsCompact((PyLongObject*) x) + #define __Pyx_PyLong_CompactValue(x) PyUnstable_Long_CompactValue((PyLongObject*) x) + #else + #define __Pyx_PyLong_IsCompact(x) (((PyLongObject*)x)->long_value.lv_tag < (2 << _PyLong_NON_SIZE_BITS)) + #define __Pyx_PyLong_CompactValue(x) ((1 - (Py_ssize_t) __Pyx_PyLong_Sign(x)) * (Py_ssize_t) __Pyx_PyLong_Digits(x)[0]) + #endif + typedef Py_ssize_t __Pyx_compact_pylong; + typedef size_t __Pyx_compact_upylong; + #else + #define __Pyx_PyLong_IsNeg(x) (Py_SIZE(x) < 0) + #define __Pyx_PyLong_IsNonNeg(x) (Py_SIZE(x) >= 0) + #define __Pyx_PyLong_IsZero(x) (Py_SIZE(x) == 0) + #define __Pyx_PyLong_IsPos(x) (Py_SIZE(x) > 0) + #define __Pyx_PyLong_CompactValueUnsigned(x) ((Py_SIZE(x) == 0) ? 0 : __Pyx_PyLong_Digits(x)[0]) + #define __Pyx_PyLong_DigitCount(x) __Pyx_sst_abs(Py_SIZE(x)) + #define __Pyx_PyLong_SignedDigitCount(x) Py_SIZE(x) + #define __Pyx_PyLong_IsCompact(x) (Py_SIZE(x) == 0 || Py_SIZE(x) == 1 || Py_SIZE(x) == -1) + #define __Pyx_PyLong_CompactValue(x)\ + ((Py_SIZE(x) == 0) ? (sdigit) 0 : ((Py_SIZE(x) < 0) ? -(sdigit)__Pyx_PyLong_Digits(x)[0] : (sdigit)__Pyx_PyLong_Digits(x)[0])) + typedef sdigit __Pyx_compact_pylong; + typedef digit __Pyx_compact_upylong; + #endif + #if PY_VERSION_HEX >= 0x030C00A5 + #define __Pyx_PyLong_Digits(x) (((PyLongObject*)x)->long_value.ob_digit) + #else + #define __Pyx_PyLong_Digits(x) (((PyLongObject*)x)->ob_digit) + #endif +#endif +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII +#include +static int __Pyx_sys_getdefaultencoding_not_ascii; +static int __Pyx_init_sys_getdefaultencoding_params(void) { + PyObject* sys; + PyObject* default_encoding = NULL; + PyObject* ascii_chars_u = NULL; + PyObject* ascii_chars_b = NULL; + const char* default_encoding_c; + sys = PyImport_ImportModule("sys"); + if (!sys) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) "getdefaultencoding", NULL); + Py_DECREF(sys); + if (!default_encoding) goto bad; + default_encoding_c = PyBytes_AsString(default_encoding); + if (!default_encoding_c) goto bad; + if (strcmp(default_encoding_c, "ascii") == 0) { + __Pyx_sys_getdefaultencoding_not_ascii = 0; + } else { + char ascii_chars[128]; + int c; + for (c = 0; c < 128; c++) { + ascii_chars[c] = (char) c; + } + __Pyx_sys_getdefaultencoding_not_ascii = 1; + ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); + if (!ascii_chars_u) goto bad; + ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); + if (!ascii_chars_b || !PyBytes_Check(ascii_chars_b) || memcmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { + PyErr_Format( + PyExc_ValueError, + "This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.", + default_encoding_c); + goto bad; + } + Py_DECREF(ascii_chars_u); + Py_DECREF(ascii_chars_b); + } + Py_DECREF(default_encoding); + return 0; +bad: + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return -1; +} +#endif +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) +#else +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT +#include +static char* __PYX_DEFAULT_STRING_ENCODING; +static int __Pyx_init_sys_getdefaultencoding_params(void) { + PyObject* sys; + PyObject* default_encoding = NULL; + char* default_encoding_c; + sys = PyImport_ImportModule("sys"); + if (!sys) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + Py_DECREF(sys); + if (!default_encoding) goto bad; + default_encoding_c = PyBytes_AsString(default_encoding); + if (!default_encoding_c) goto bad; + __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c) + 1); + if (!__PYX_DEFAULT_STRING_ENCODING) goto bad; + strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); + Py_DECREF(default_encoding); + return 0; +bad: + Py_XDECREF(default_encoding); + return -1; +} +#endif +#endif + + +/* Test for GCC > 2.95 */ +#if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))) + #define likely(x) __builtin_expect(!!(x), 1) + #define unlikely(x) __builtin_expect(!!(x), 0) +#else /* !__GNUC__ or GCC < 2.95 */ + #define likely(x) (x) + #define unlikely(x) (x) +#endif /* __GNUC__ */ +static CYTHON_INLINE void __Pyx_pretend_to_initialize(void* ptr) { (void)ptr; } + +#if !CYTHON_USE_MODULE_STATE +static PyObject *__pyx_m = NULL; +#endif +static int __pyx_lineno; +static int __pyx_clineno = 0; +static const char * __pyx_cfilenm = __FILE__; +static const char *__pyx_filename; + +/* #### Code section: filename_table ### */ + +static const char *__pyx_f[] = { + "curated_tokenizers\\\\_spp.pyx", + "", +}; +/* #### Code section: utility_code_proto_before_types ### */ +/* ForceInitThreads.proto */ +#ifndef __PYX_FORCE_INIT_THREADS + #define __PYX_FORCE_INIT_THREADS 0 +#endif + +/* #### Code section: numeric_typedefs ### */ +/* #### Code section: complex_type_declarations ### */ +/* #### Code section: type_declarations ### */ + +/*--- Type declarations ---*/ +struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor; + +/* "curated_tokenizers/_spp.pxd":56 + * cdef StatusCode kNotFound + * + * cdef class SentencePieceProcessor: # <<<<<<<<<<<<<< + * cdef shared_ptr[CSentencePieceProcessor] spp + * + */ +struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor { + PyObject_HEAD + struct __pyx_vtabstruct_18curated_tokenizers_4_spp_SentencePieceProcessor *__pyx_vtab; + std::shared_ptr spp; +}; + + + +/* "curated_tokenizers/_spp.pyx":4 + * from typing import List, Tuple + * + * cdef class SentencePieceProcessor: # <<<<<<<<<<<<<< + * def __cinit__(self): + * self.spp.reset(new CSentencePieceProcessor()) + */ + +struct __pyx_vtabstruct_18curated_tokenizers_4_spp_SentencePieceProcessor { + sentencepiece::SentencePieceText (*_encode)(struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *, PyObject *); +}; +static struct __pyx_vtabstruct_18curated_tokenizers_4_spp_SentencePieceProcessor *__pyx_vtabptr_18curated_tokenizers_4_spp_SentencePieceProcessor; +/* #### Code section: utility_code_proto ### */ + +/* --- Runtime support code (head) --- */ +/* Refnanny.proto */ +#ifndef CYTHON_REFNANNY + #define CYTHON_REFNANNY 0 +#endif +#if CYTHON_REFNANNY + typedef struct { + void (*INCREF)(void*, PyObject*, Py_ssize_t); + void (*DECREF)(void*, PyObject*, Py_ssize_t); + void (*GOTREF)(void*, PyObject*, Py_ssize_t); + void (*GIVEREF)(void*, PyObject*, Py_ssize_t); + void* (*SetupContext)(const char*, Py_ssize_t, const char*); + void (*FinishContext)(void**); + } __Pyx_RefNannyAPIStruct; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); + #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; +#ifdef WITH_THREAD + #define __Pyx_RefNannySetupContext(name, acquire_gil)\ + if (acquire_gil) {\ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), (__LINE__), (__FILE__));\ + PyGILState_Release(__pyx_gilstate_save);\ + } else {\ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), (__LINE__), (__FILE__));\ + } + #define __Pyx_RefNannyFinishContextNogil() {\ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ + __Pyx_RefNannyFinishContext();\ + PyGILState_Release(__pyx_gilstate_save);\ + } +#else + #define __Pyx_RefNannySetupContext(name, acquire_gil)\ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), (__LINE__), (__FILE__)) + #define __Pyx_RefNannyFinishContextNogil() __Pyx_RefNannyFinishContext() +#endif + #define __Pyx_RefNannyFinishContextNogil() {\ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ + __Pyx_RefNannyFinishContext();\ + PyGILState_Release(__pyx_gilstate_save);\ + } + #define __Pyx_RefNannyFinishContext()\ + __Pyx_RefNanny->FinishContext(&__pyx_refnanny) + #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) + #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) + #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) + #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) + #define __Pyx_XINCREF(r) do { if((r) == NULL); else {__Pyx_INCREF(r); }} while(0) + #define __Pyx_XDECREF(r) do { if((r) == NULL); else {__Pyx_DECREF(r); }} while(0) + #define __Pyx_XGOTREF(r) do { if((r) == NULL); else {__Pyx_GOTREF(r); }} while(0) + #define __Pyx_XGIVEREF(r) do { if((r) == NULL); else {__Pyx_GIVEREF(r);}} while(0) +#else + #define __Pyx_RefNannyDeclarations + #define __Pyx_RefNannySetupContext(name, acquire_gil) + #define __Pyx_RefNannyFinishContextNogil() + #define __Pyx_RefNannyFinishContext() + #define __Pyx_INCREF(r) Py_INCREF(r) + #define __Pyx_DECREF(r) Py_DECREF(r) + #define __Pyx_GOTREF(r) + #define __Pyx_GIVEREF(r) + #define __Pyx_XINCREF(r) Py_XINCREF(r) + #define __Pyx_XDECREF(r) Py_XDECREF(r) + #define __Pyx_XGOTREF(r) + #define __Pyx_XGIVEREF(r) +#endif +#define __Pyx_Py_XDECREF_SET(r, v) do {\ + PyObject *tmp = (PyObject *) r;\ + r = v; Py_XDECREF(tmp);\ + } while (0) +#define __Pyx_XDECREF_SET(r, v) do {\ + PyObject *tmp = (PyObject *) r;\ + r = v; __Pyx_XDECREF(tmp);\ + } while (0) +#define __Pyx_DECREF_SET(r, v) do {\ + PyObject *tmp = (PyObject *) r;\ + r = v; __Pyx_DECREF(tmp);\ + } while (0) +#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) +#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) + +/* PyErrExceptionMatches.proto */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_PyErr_ExceptionMatches(err) __Pyx_PyErr_ExceptionMatchesInState(__pyx_tstate, err) +static CYTHON_INLINE int __Pyx_PyErr_ExceptionMatchesInState(PyThreadState* tstate, PyObject* err); +#else +#define __Pyx_PyErr_ExceptionMatches(err) PyErr_ExceptionMatches(err) +#endif + +/* PyThreadStateGet.proto */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_PyThreadState_declare PyThreadState *__pyx_tstate; +#define __Pyx_PyThreadState_assign __pyx_tstate = __Pyx_PyThreadState_Current; +#if PY_VERSION_HEX >= 0x030C00A6 +#define __Pyx_PyErr_Occurred() (__pyx_tstate->current_exception != NULL) +#define __Pyx_PyErr_CurrentExceptionType() (__pyx_tstate->current_exception ? (PyObject*) Py_TYPE(__pyx_tstate->current_exception) : (PyObject*) NULL) +#else +#define __Pyx_PyErr_Occurred() (__pyx_tstate->curexc_type != NULL) +#define __Pyx_PyErr_CurrentExceptionType() (__pyx_tstate->curexc_type) +#endif +#else +#define __Pyx_PyThreadState_declare +#define __Pyx_PyThreadState_assign +#define __Pyx_PyErr_Occurred() (PyErr_Occurred() != NULL) +#define __Pyx_PyErr_CurrentExceptionType() PyErr_Occurred() +#endif + +/* PyErrFetchRestore.proto */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_PyErr_Clear() __Pyx_ErrRestore(NULL, NULL, NULL) +#define __Pyx_ErrRestoreWithState(type, value, tb) __Pyx_ErrRestoreInState(PyThreadState_GET(), type, value, tb) +#define __Pyx_ErrFetchWithState(type, value, tb) __Pyx_ErrFetchInState(PyThreadState_GET(), type, value, tb) +#define __Pyx_ErrRestore(type, value, tb) __Pyx_ErrRestoreInState(__pyx_tstate, type, value, tb) +#define __Pyx_ErrFetch(type, value, tb) __Pyx_ErrFetchInState(__pyx_tstate, type, value, tb) +static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); +static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A6 +#define __Pyx_PyErr_SetNone(exc) (Py_INCREF(exc), __Pyx_ErrRestore((exc), NULL, NULL)) +#else +#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) +#endif +#else +#define __Pyx_PyErr_Clear() PyErr_Clear() +#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) +#define __Pyx_ErrRestoreWithState(type, value, tb) PyErr_Restore(type, value, tb) +#define __Pyx_ErrFetchWithState(type, value, tb) PyErr_Fetch(type, value, tb) +#define __Pyx_ErrRestoreInState(tstate, type, value, tb) PyErr_Restore(type, value, tb) +#define __Pyx_ErrFetchInState(tstate, type, value, tb) PyErr_Fetch(type, value, tb) +#define __Pyx_ErrRestore(type, value, tb) PyErr_Restore(type, value, tb) +#define __Pyx_ErrFetch(type, value, tb) PyErr_Fetch(type, value, tb) +#endif + +/* PyObjectGetAttrStr.proto */ +#if CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name); +#else +#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) +#endif + +/* PyObjectGetAttrStrNoError.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStrNoError(PyObject* obj, PyObject* attr_name); + +/* GetBuiltinName.proto */ +static PyObject *__Pyx_GetBuiltinName(PyObject *name); + +/* TupleAndListFromArray.proto */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyList_FromArray(PyObject *const *src, Py_ssize_t n); +static CYTHON_INLINE PyObject* __Pyx_PyTuple_FromArray(PyObject *const *src, Py_ssize_t n); +#endif + +/* IncludeStringH.proto */ +#include + +/* BytesEquals.proto */ +static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals); + +/* UnicodeEquals.proto */ +static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); + +/* fastcall.proto */ +#if CYTHON_AVOID_BORROWED_REFS + #define __Pyx_Arg_VARARGS(args, i) PySequence_GetItem(args, i) +#elif CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_Arg_VARARGS(args, i) PyTuple_GET_ITEM(args, i) +#else + #define __Pyx_Arg_VARARGS(args, i) PyTuple_GetItem(args, i) +#endif +#if CYTHON_AVOID_BORROWED_REFS + #define __Pyx_Arg_NewRef_VARARGS(arg) __Pyx_NewRef(arg) + #define __Pyx_Arg_XDECREF_VARARGS(arg) Py_XDECREF(arg) +#else + #define __Pyx_Arg_NewRef_VARARGS(arg) arg + #define __Pyx_Arg_XDECREF_VARARGS(arg) +#endif +#define __Pyx_NumKwargs_VARARGS(kwds) PyDict_Size(kwds) +#define __Pyx_KwValues_VARARGS(args, nargs) NULL +#define __Pyx_GetKwValue_VARARGS(kw, kwvalues, s) __Pyx_PyDict_GetItemStrWithError(kw, s) +#define __Pyx_KwargsAsDict_VARARGS(kw, kwvalues) PyDict_Copy(kw) +#if CYTHON_METH_FASTCALL + #define __Pyx_Arg_FASTCALL(args, i) args[i] + #define __Pyx_NumKwargs_FASTCALL(kwds) PyTuple_GET_SIZE(kwds) + #define __Pyx_KwValues_FASTCALL(args, nargs) ((args) + (nargs)) + static CYTHON_INLINE PyObject * __Pyx_GetKwValue_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues, PyObject *s); +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030d0000 + CYTHON_UNUSED static PyObject *__Pyx_KwargsAsDict_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues); + #else + #define __Pyx_KwargsAsDict_FASTCALL(kw, kwvalues) _PyStack_AsDict(kwvalues, kw) + #endif + #define __Pyx_Arg_NewRef_FASTCALL(arg) arg /* no-op, __Pyx_Arg_FASTCALL is direct and this needs + to have the same reference counting */ + #define __Pyx_Arg_XDECREF_FASTCALL(arg) +#else + #define __Pyx_Arg_FASTCALL __Pyx_Arg_VARARGS + #define __Pyx_NumKwargs_FASTCALL __Pyx_NumKwargs_VARARGS + #define __Pyx_KwValues_FASTCALL __Pyx_KwValues_VARARGS + #define __Pyx_GetKwValue_FASTCALL __Pyx_GetKwValue_VARARGS + #define __Pyx_KwargsAsDict_FASTCALL __Pyx_KwargsAsDict_VARARGS + #define __Pyx_Arg_NewRef_FASTCALL(arg) __Pyx_Arg_NewRef_VARARGS(arg) + #define __Pyx_Arg_XDECREF_FASTCALL(arg) __Pyx_Arg_XDECREF_VARARGS(arg) +#endif +#if CYTHON_COMPILING_IN_CPYTHON && CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS +#define __Pyx_ArgsSlice_VARARGS(args, start, stop) __Pyx_PyTuple_FromArray(&__Pyx_Arg_VARARGS(args, start), stop - start) +#define __Pyx_ArgsSlice_FASTCALL(args, start, stop) __Pyx_PyTuple_FromArray(&__Pyx_Arg_FASTCALL(args, start), stop - start) +#else +#define __Pyx_ArgsSlice_VARARGS(args, start, stop) PyTuple_GetSlice(args, start, stop) +#define __Pyx_ArgsSlice_FASTCALL(args, start, stop) PyTuple_GetSlice(args, start, stop) +#endif + +/* RaiseArgTupleInvalid.proto */ +static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, + Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); + +/* KeywordStringCheck.proto */ +static int __Pyx_CheckKeywordStrings(PyObject *kw, const char* function_name, int kw_allowed); + +/* PyFunctionFastCall.proto */ +#if CYTHON_FAST_PYCALL +#if !CYTHON_VECTORCALL +#define __Pyx_PyFunction_FastCall(func, args, nargs)\ + __Pyx_PyFunction_FastCallDict((func), (args), (nargs), NULL) +static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, Py_ssize_t nargs, PyObject *kwargs); +#endif +#define __Pyx_BUILD_ASSERT_EXPR(cond)\ + (sizeof(char [1 - 2*!(cond)]) - 1) +#ifndef Py_MEMBER_SIZE +#define Py_MEMBER_SIZE(type, member) sizeof(((type *)0)->member) +#endif +#if !CYTHON_VECTORCALL +#if PY_VERSION_HEX >= 0x03080000 + #include "frameobject.h" +#if PY_VERSION_HEX >= 0x030b00a6 && !CYTHON_COMPILING_IN_LIMITED_API + #ifndef Py_BUILD_CORE + #define Py_BUILD_CORE 1 + #endif + #include "internal/pycore_frame.h" +#endif + #define __Pxy_PyFrame_Initialize_Offsets() + #define __Pyx_PyFrame_GetLocalsplus(frame) ((frame)->f_localsplus) +#else + static size_t __pyx_pyframe_localsplus_offset = 0; + #include "frameobject.h" + #define __Pxy_PyFrame_Initialize_Offsets()\ + ((void)__Pyx_BUILD_ASSERT_EXPR(sizeof(PyFrameObject) == offsetof(PyFrameObject, f_localsplus) + Py_MEMBER_SIZE(PyFrameObject, f_localsplus)),\ + (void)(__pyx_pyframe_localsplus_offset = ((size_t)PyFrame_Type.tp_basicsize) - Py_MEMBER_SIZE(PyFrameObject, f_localsplus))) + #define __Pyx_PyFrame_GetLocalsplus(frame)\ + (assert(__pyx_pyframe_localsplus_offset), (PyObject **)(((char *)(frame)) + __pyx_pyframe_localsplus_offset)) +#endif +#endif +#endif + +/* PyObjectCall.proto */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); +#else +#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) +#endif + +/* PyObjectCallMethO.proto */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg); +#endif + +/* PyObjectFastCall.proto */ +#define __Pyx_PyObject_FastCall(func, args, nargs) __Pyx_PyObject_FastCallDict(func, args, (size_t)(nargs), NULL) +static CYTHON_INLINE PyObject* __Pyx_PyObject_FastCallDict(PyObject *func, PyObject **args, size_t nargs, PyObject *kwargs); + +/* RaiseDoubleKeywords.proto */ +static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); + +/* ParseKeywords.proto */ +static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject *const *kwvalues, + PyObject **argnames[], + PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, + const char* function_name); + +/* PyObjectCallOneArg.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg); + +/* ArgTypeTest.proto */ +#define __Pyx_ArgTypeTest(obj, type, none_allowed, name, exact)\ + ((likely(__Pyx_IS_TYPE(obj, type) | (none_allowed && (obj == Py_None)))) ? 1 :\ + __Pyx__ArgTypeTest(obj, type, name, exact)) +static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact); + +/* UnpackUnboundCMethod.proto */ +typedef struct { + PyObject *type; + PyObject **method_name; + PyCFunction func; + PyObject *method; + int flag; +} __Pyx_CachedCFunction; + +/* CallUnboundCMethod1.proto */ +static PyObject* __Pyx__CallUnboundCMethod1(__Pyx_CachedCFunction* cfunc, PyObject* self, PyObject* arg); +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_CallUnboundCMethod1(__Pyx_CachedCFunction* cfunc, PyObject* self, PyObject* arg); +#else +#define __Pyx_CallUnboundCMethod1(cfunc, self, arg) __Pyx__CallUnboundCMethod1(cfunc, self, arg) +#endif + +/* RaiseException.proto */ +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); + +/* IncludeCppStringH.proto */ +#include + +/* decode_c_string_utf16.proto */ +static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16(const char *s, Py_ssize_t size, const char *errors) { + int byteorder = 0; + return PyUnicode_DecodeUTF16(s, size, errors, &byteorder); +} +static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16LE(const char *s, Py_ssize_t size, const char *errors) { + int byteorder = -1; + return PyUnicode_DecodeUTF16(s, size, errors, &byteorder); +} +static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16BE(const char *s, Py_ssize_t size, const char *errors) { + int byteorder = 1; + return PyUnicode_DecodeUTF16(s, size, errors, &byteorder); +} + +/* decode_c_bytes.proto */ +static CYTHON_INLINE PyObject* __Pyx_decode_c_bytes( + const char* cstring, Py_ssize_t length, Py_ssize_t start, Py_ssize_t stop, + const char* encoding, const char* errors, + PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)); + +/* decode_cpp_string.proto */ +static CYTHON_INLINE PyObject* __Pyx_decode_cpp_string( + std::string cppstring, Py_ssize_t start, Py_ssize_t stop, + const char* encoding, const char* errors, + PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) { + return __Pyx_decode_c_bytes( + cppstring.data(), cppstring.size(), start, stop, encoding, errors, decode_func); +} + +/* MoveIfSupported.proto */ +#if CYTHON_USE_CPP_STD_MOVE + #include + #define __PYX_STD_MOVE_IF_SUPPORTED(x) std::move(x) +#else + #define __PYX_STD_MOVE_IF_SUPPORTED(x) x +#endif + +/* ListAppend.proto */ +#if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS +static CYTHON_INLINE int __Pyx_PyList_Append(PyObject* list, PyObject* x) { + PyListObject* L = (PyListObject*) list; + Py_ssize_t len = Py_SIZE(list); + if (likely(L->allocated > len) & likely(len > (L->allocated >> 1))) { + Py_INCREF(x); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030d0000 + L->ob_item[len] = x; + #else + PyList_SET_ITEM(list, len, x); + #endif + __Pyx_SET_SIZE(list, len + 1); + return 0; + } + return PyList_Append(list, x); +} +#else +#define __Pyx_PyList_Append(L,x) PyList_Append(L,x) +#endif + +/* GCCDiagnostics.proto */ +#if !defined(__INTEL_COMPILER) && defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) +#define __Pyx_HAS_GCC_DIAGNOSTIC +#endif + +/* BuildPyUnicode.proto */ +static PyObject* __Pyx_PyUnicode_BuildFromAscii(Py_ssize_t ulength, char* chars, int clength, + int prepend_sign, char padding_char); + +/* CIntToPyUnicode.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_From_int(int value, Py_ssize_t width, char padding_char, char format_char); + +/* JoinPyUnicode.proto */ +static PyObject* __Pyx_PyUnicode_Join(PyObject* value_tuple, Py_ssize_t value_count, Py_ssize_t result_ulength, + Py_UCS4 max_char); + +/* PyDictVersioning.proto */ +#if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS +#define __PYX_DICT_VERSION_INIT ((PY_UINT64_T) -1) +#define __PYX_GET_DICT_VERSION(dict) (((PyDictObject*)(dict))->ma_version_tag) +#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var)\ + (version_var) = __PYX_GET_DICT_VERSION(dict);\ + (cache_var) = (value); +#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) {\ + static PY_UINT64_T __pyx_dict_version = 0;\ + static PyObject *__pyx_dict_cached_value = NULL;\ + if (likely(__PYX_GET_DICT_VERSION(DICT) == __pyx_dict_version)) {\ + (VAR) = __pyx_dict_cached_value;\ + } else {\ + (VAR) = __pyx_dict_cached_value = (LOOKUP);\ + __pyx_dict_version = __PYX_GET_DICT_VERSION(DICT);\ + }\ +} +static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj); +static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj); +static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version); +#else +#define __PYX_GET_DICT_VERSION(dict) (0) +#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var) +#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) (VAR) = (LOOKUP); +#endif + +/* GetModuleGlobalName.proto */ +#if CYTHON_USE_DICT_VERSIONS +#define __Pyx_GetModuleGlobalName(var, name) do {\ + static PY_UINT64_T __pyx_dict_version = 0;\ + static PyObject *__pyx_dict_cached_value = NULL;\ + (var) = (likely(__pyx_dict_version == __PYX_GET_DICT_VERSION(__pyx_d))) ?\ + (likely(__pyx_dict_cached_value) ? __Pyx_NewRef(__pyx_dict_cached_value) : __Pyx_GetBuiltinName(name)) :\ + __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ +} while(0) +#define __Pyx_GetModuleGlobalNameUncached(var, name) do {\ + PY_UINT64_T __pyx_dict_version;\ + PyObject *__pyx_dict_cached_value;\ + (var) = __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ +} while(0) +static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value); +#else +#define __Pyx_GetModuleGlobalName(var, name) (var) = __Pyx__GetModuleGlobalName(name) +#define __Pyx_GetModuleGlobalNameUncached(var, name) (var) = __Pyx__GetModuleGlobalName(name) +static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name); +#endif + +/* decode_c_string.proto */ +static CYTHON_INLINE PyObject* __Pyx_decode_c_string( + const char* cstring, Py_ssize_t start, Py_ssize_t stop, + const char* encoding, const char* errors, + PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)); + +/* IncludeStructmemberH.proto */ +#include + +/* FixUpExtensionType.proto */ +#if CYTHON_USE_TYPE_SPECS +static int __Pyx_fix_up_extension_type_from_spec(PyType_Spec *spec, PyTypeObject *type); +#endif + +/* PyObjectCallNoArg.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func); + +/* PyObjectGetMethod.proto */ +static int __Pyx_PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method); + +/* PyObjectCallMethod0.proto */ +static PyObject* __Pyx_PyObject_CallMethod0(PyObject* obj, PyObject* method_name); + +/* ValidateBasesTuple.proto */ +#if CYTHON_COMPILING_IN_CPYTHON || CYTHON_COMPILING_IN_LIMITED_API || CYTHON_USE_TYPE_SPECS +static int __Pyx_validate_bases_tuple(const char *type_name, Py_ssize_t dictoffset, PyObject *bases); +#endif + +/* PyType_Ready.proto */ +CYTHON_UNUSED static int __Pyx_PyType_Ready(PyTypeObject *t); + +/* PyObject_GenericGetAttrNoDict.proto */ +#if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 +static CYTHON_INLINE PyObject* __Pyx_PyObject_GenericGetAttrNoDict(PyObject* obj, PyObject* attr_name); +#else +#define __Pyx_PyObject_GenericGetAttrNoDict PyObject_GenericGetAttr +#endif + +/* PyObject_GenericGetAttr.proto */ +#if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 +static PyObject* __Pyx_PyObject_GenericGetAttr(PyObject* obj, PyObject* attr_name); +#else +#define __Pyx_PyObject_GenericGetAttr PyObject_GenericGetAttr +#endif + +/* SetVTable.proto */ +static int __Pyx_SetVtable(PyTypeObject* typeptr , void* vtable); + +/* GetVTable.proto */ +static void* __Pyx_GetVtable(PyTypeObject *type); + +/* MergeVTables.proto */ +#if !CYTHON_COMPILING_IN_LIMITED_API +static int __Pyx_MergeVtables(PyTypeObject *type); +#endif + +/* Import.proto */ +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); + +/* ImportFrom.proto */ +static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name); + +/* FetchSharedCythonModule.proto */ +static PyObject *__Pyx_FetchSharedCythonABIModule(void); + +/* FetchCommonType.proto */ +#if !CYTHON_USE_TYPE_SPECS +static PyTypeObject* __Pyx_FetchCommonType(PyTypeObject* type); +#else +static PyTypeObject* __Pyx_FetchCommonTypeFromSpec(PyObject *module, PyType_Spec *spec, PyObject *bases); +#endif + +/* PyMethodNew.proto */ +#if CYTHON_COMPILING_IN_LIMITED_API +static PyObject *__Pyx_PyMethod_New(PyObject *func, PyObject *self, PyObject *typ) { + PyObject *typesModule=NULL, *methodType=NULL, *result=NULL; + CYTHON_UNUSED_VAR(typ); + if (!self) + return __Pyx_NewRef(func); + typesModule = PyImport_ImportModule("types"); + if (!typesModule) return NULL; + methodType = PyObject_GetAttrString(typesModule, "MethodType"); + Py_DECREF(typesModule); + if (!methodType) return NULL; + result = PyObject_CallFunctionObjArgs(methodType, func, self, NULL); + Py_DECREF(methodType); + return result; +} +#elif PY_MAJOR_VERSION >= 3 +static PyObject *__Pyx_PyMethod_New(PyObject *func, PyObject *self, PyObject *typ) { + CYTHON_UNUSED_VAR(typ); + if (!self) + return __Pyx_NewRef(func); + return PyMethod_New(func, self); +} +#else + #define __Pyx_PyMethod_New PyMethod_New +#endif + +/* PyVectorcallFastCallDict.proto */ +#if CYTHON_METH_FASTCALL +static CYTHON_INLINE PyObject *__Pyx_PyVectorcall_FastCallDict(PyObject *func, __pyx_vectorcallfunc vc, PyObject *const *args, size_t nargs, PyObject *kw); +#endif + +/* CythonFunctionShared.proto */ +#define __Pyx_CyFunction_USED +#define __Pyx_CYFUNCTION_STATICMETHOD 0x01 +#define __Pyx_CYFUNCTION_CLASSMETHOD 0x02 +#define __Pyx_CYFUNCTION_CCLASS 0x04 +#define __Pyx_CYFUNCTION_COROUTINE 0x08 +#define __Pyx_CyFunction_GetClosure(f)\ + (((__pyx_CyFunctionObject *) (f))->func_closure) +#if PY_VERSION_HEX < 0x030900B1 || CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_CyFunction_GetClassObj(f)\ + (((__pyx_CyFunctionObject *) (f))->func_classobj) +#else + #define __Pyx_CyFunction_GetClassObj(f)\ + ((PyObject*) ((PyCMethodObject *) (f))->mm_class) +#endif +#define __Pyx_CyFunction_SetClassObj(f, classobj)\ + __Pyx__CyFunction_SetClassObj((__pyx_CyFunctionObject *) (f), (classobj)) +#define __Pyx_CyFunction_Defaults(type, f)\ + ((type *)(((__pyx_CyFunctionObject *) (f))->defaults)) +#define __Pyx_CyFunction_SetDefaultsGetter(f, g)\ + ((__pyx_CyFunctionObject *) (f))->defaults_getter = (g) +typedef struct { +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject_HEAD + PyObject *func; +#elif PY_VERSION_HEX < 0x030900B1 + PyCFunctionObject func; +#else + PyCMethodObject func; +#endif +#if CYTHON_BACKPORT_VECTORCALL + __pyx_vectorcallfunc func_vectorcall; +#endif +#if PY_VERSION_HEX < 0x030500A0 || CYTHON_COMPILING_IN_LIMITED_API + PyObject *func_weakreflist; +#endif + PyObject *func_dict; + PyObject *func_name; + PyObject *func_qualname; + PyObject *func_doc; + PyObject *func_globals; + PyObject *func_code; + PyObject *func_closure; +#if PY_VERSION_HEX < 0x030900B1 || CYTHON_COMPILING_IN_LIMITED_API + PyObject *func_classobj; +#endif + void *defaults; + int defaults_pyobjects; + size_t defaults_size; + int flags; + PyObject *defaults_tuple; + PyObject *defaults_kwdict; + PyObject *(*defaults_getter)(PyObject *); + PyObject *func_annotations; + PyObject *func_is_coroutine; +} __pyx_CyFunctionObject; +#undef __Pyx_CyOrPyCFunction_Check +#define __Pyx_CyFunction_Check(obj) __Pyx_TypeCheck(obj, __pyx_CyFunctionType) +#define __Pyx_CyOrPyCFunction_Check(obj) __Pyx_TypeCheck2(obj, __pyx_CyFunctionType, &PyCFunction_Type) +#define __Pyx_CyFunction_CheckExact(obj) __Pyx_IS_TYPE(obj, __pyx_CyFunctionType) +static CYTHON_INLINE int __Pyx__IsSameCyOrCFunction(PyObject *func, void *cfunc); +#undef __Pyx_IsSameCFunction +#define __Pyx_IsSameCFunction(func, cfunc) __Pyx__IsSameCyOrCFunction(func, cfunc) +static PyObject *__Pyx_CyFunction_Init(__pyx_CyFunctionObject* op, PyMethodDef *ml, + int flags, PyObject* qualname, + PyObject *closure, + PyObject *module, PyObject *globals, + PyObject* code); +static CYTHON_INLINE void __Pyx__CyFunction_SetClassObj(__pyx_CyFunctionObject* f, PyObject* classobj); +static CYTHON_INLINE void *__Pyx_CyFunction_InitDefaults(PyObject *m, + size_t size, + int pyobjects); +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsTuple(PyObject *m, + PyObject *tuple); +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsKwDict(PyObject *m, + PyObject *dict); +static CYTHON_INLINE void __Pyx_CyFunction_SetAnnotationsDict(PyObject *m, + PyObject *dict); +static int __pyx_CyFunction_init(PyObject *module); +#if CYTHON_METH_FASTCALL +static PyObject * __Pyx_CyFunction_Vectorcall_NOARGS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); +static PyObject * __Pyx_CyFunction_Vectorcall_O(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); +static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); +static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS_METHOD(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); +#if CYTHON_BACKPORT_VECTORCALL +#define __Pyx_CyFunction_func_vectorcall(f) (((__pyx_CyFunctionObject*)f)->func_vectorcall) +#else +#define __Pyx_CyFunction_func_vectorcall(f) (((PyCFunctionObject*)f)->vectorcall) +#endif +#endif + +/* CythonFunction.proto */ +static PyObject *__Pyx_CyFunction_New(PyMethodDef *ml, + int flags, PyObject* qualname, + PyObject *closure, + PyObject *module, PyObject *globals, + PyObject* code); + +/* GetNameInClass.proto */ +#define __Pyx_GetNameInClass(var, nmspace, name) (var) = __Pyx__GetNameInClass(nmspace, name) +static PyObject *__Pyx__GetNameInClass(PyObject *nmspace, PyObject *name); + +/* CLineInTraceback.proto */ +#ifdef CYTHON_CLINE_IN_TRACEBACK +#define __Pyx_CLineForTraceback(tstate, c_line) (((CYTHON_CLINE_IN_TRACEBACK)) ? c_line : 0) +#else +static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line); +#endif + +/* CodeObjectCache.proto */ +#if !CYTHON_COMPILING_IN_LIMITED_API +typedef struct { + PyCodeObject* code_object; + int code_line; +} __Pyx_CodeObjectCacheEntry; +struct __Pyx_CodeObjectCache { + int count; + int max_count; + __Pyx_CodeObjectCacheEntry* entries; +}; +static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); +static PyCodeObject *__pyx_find_code_object(int code_line); +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); +#endif + +/* AddTraceback.proto */ +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename); + +/* None.proto */ +#include + +/* CppExceptionConversion.proto */ +#ifndef __Pyx_CppExn2PyErr +#include +#include +#include +#include +static void __Pyx_CppExn2PyErr() { + try { + if (PyErr_Occurred()) + ; // let the latest Python exn pass through and ignore the current one + else + throw; + } catch (const std::bad_alloc& exn) { + PyErr_SetString(PyExc_MemoryError, exn.what()); + } catch (const std::bad_cast& exn) { + PyErr_SetString(PyExc_TypeError, exn.what()); + } catch (const std::bad_typeid& exn) { + PyErr_SetString(PyExc_TypeError, exn.what()); + } catch (const std::domain_error& exn) { + PyErr_SetString(PyExc_ValueError, exn.what()); + } catch (const std::invalid_argument& exn) { + PyErr_SetString(PyExc_ValueError, exn.what()); + } catch (const std::ios_base::failure& exn) { + PyErr_SetString(PyExc_IOError, exn.what()); + } catch (const std::out_of_range& exn) { + PyErr_SetString(PyExc_IndexError, exn.what()); + } catch (const std::overflow_error& exn) { + PyErr_SetString(PyExc_OverflowError, exn.what()); + } catch (const std::range_error& exn) { + PyErr_SetString(PyExc_ArithmeticError, exn.what()); + } catch (const std::underflow_error& exn) { + PyErr_SetString(PyExc_ArithmeticError, exn.what()); + } catch (const std::exception& exn) { + PyErr_SetString(PyExc_RuntimeError, exn.what()); + } + catch (...) + { + PyErr_SetString(PyExc_RuntimeError, "Unknown exception"); + } +} +#endif + +/* CIntFromPy.proto */ +static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); + +/* CIntToPy.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value); + +/* CIntToPy.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_uint32_t(uint32_t value); + +/* FormatTypeName.proto */ +#if CYTHON_COMPILING_IN_LIMITED_API +typedef PyObject *__Pyx_TypeName; +#define __Pyx_FMT_TYPENAME "%U" +static __Pyx_TypeName __Pyx_PyType_GetName(PyTypeObject* tp); +#define __Pyx_DECREF_TypeName(obj) Py_XDECREF(obj) +#else +typedef const char *__Pyx_TypeName; +#define __Pyx_FMT_TYPENAME "%.200s" +#define __Pyx_PyType_GetName(tp) ((tp)->tp_name) +#define __Pyx_DECREF_TypeName(obj) +#endif + +/* CIntToPy.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); + +/* CIntFromPy.proto */ +static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); + +/* FastTypeChecks.proto */ +#if CYTHON_COMPILING_IN_CPYTHON +#define __Pyx_TypeCheck(obj, type) __Pyx_IsSubtype(Py_TYPE(obj), (PyTypeObject *)type) +#define __Pyx_TypeCheck2(obj, type1, type2) __Pyx_IsAnySubtype2(Py_TYPE(obj), (PyTypeObject *)type1, (PyTypeObject *)type2) +static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b); +static CYTHON_INLINE int __Pyx_IsAnySubtype2(PyTypeObject *cls, PyTypeObject *a, PyTypeObject *b); +static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches(PyObject *err, PyObject *type); +static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *type1, PyObject *type2); +#else +#define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) +#define __Pyx_TypeCheck2(obj, type1, type2) (PyObject_TypeCheck(obj, (PyTypeObject *)type1) || PyObject_TypeCheck(obj, (PyTypeObject *)type2)) +#define __Pyx_PyErr_GivenExceptionMatches(err, type) PyErr_GivenExceptionMatches(err, type) +#define __Pyx_PyErr_GivenExceptionMatches2(err, type1, type2) (PyErr_GivenExceptionMatches(err, type1) || PyErr_GivenExceptionMatches(err, type2)) +#endif +#define __Pyx_PyErr_ExceptionMatches2(err1, err2) __Pyx_PyErr_GivenExceptionMatches2(__Pyx_PyErr_CurrentExceptionType(), err1, err2) +#define __Pyx_PyException_Check(obj) __Pyx_TypeCheck(obj, PyExc_Exception) + +/* CheckBinaryVersion.proto */ +static unsigned long __Pyx_get_runtime_version(void); +static int __Pyx_check_binary_version(unsigned long ct_version, unsigned long rt_version, int allow_newer); + +/* InitStrings.proto */ +static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); + +/* #### Code section: module_declarations ### */ +static sentencepiece::SentencePieceText __pyx_f_18curated_tokenizers_4_spp_22SentencePieceProcessor__encode(struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *__pyx_v_self, PyObject *__pyx_v_sentence); /* proto*/ + +/* Module declarations from "libc.stdint" */ + +/* Module declarations from "libcpp" */ + +/* Module declarations from "libcpp.memory" */ + +/* Module declarations from "libc.string" */ + +/* Module declarations from "libcpp.string" */ + +/* Module declarations from "libcpp.vector" */ + +/* Module declarations from "curated_tokenizers._spp" */ +static PyObject *__pyx_f_18curated_tokenizers_4_spp__check_status(sentencepiece::util::Status); /*proto*/ +static std::string __pyx_convert_string_from_py_std__in_string(PyObject *); /*proto*/ +static CYTHON_INLINE PyObject *__pyx_convert_PyObject_string_to_py_std__in_string(std::string const &); /*proto*/ +static CYTHON_INLINE PyObject *__pyx_convert_PyUnicode_string_to_py_std__in_string(std::string const &); /*proto*/ +static CYTHON_INLINE PyObject *__pyx_convert_PyStr_string_to_py_std__in_string(std::string const &); /*proto*/ +static CYTHON_INLINE PyObject *__pyx_convert_PyBytes_string_to_py_std__in_string(std::string const &); /*proto*/ +static CYTHON_INLINE PyObject *__pyx_convert_PyByteArray_string_to_py_std__in_string(std::string const &); /*proto*/ +/* #### Code section: typeinfo ### */ +/* #### Code section: before_global_var ### */ +#define __Pyx_MODULE_NAME "curated_tokenizers._spp" +extern int __pyx_module_is_main_curated_tokenizers___spp; +int __pyx_module_is_main_curated_tokenizers___spp = 0; + +/* Implementation of "curated_tokenizers._spp" */ +/* #### Code section: global_var ### */ +static PyObject *__pyx_builtin_staticmethod; +static PyObject *__pyx_builtin_id; +static PyObject *__pyx_builtin_TypeError; +static PyObject *__pyx_builtin_range; +static PyObject *__pyx_builtin_ValueError; +static PyObject *__pyx_builtin_OSError; +static PyObject *__pyx_builtin_RuntimeError; +/* #### Code section: string_decls ### */ +static const char __pyx_k__3[] = "."; +static const char __pyx_k_gc[] = "gc"; +static const char __pyx_k_id[] = "id"; +static const char __pyx_k__35[] = "?"; +static const char __pyx_k_got[] = "), got "; +static const char __pyx_k_ids[] = "ids"; +static const char __pyx_k_idx[] = "idx"; +static const char __pyx_k_int[] = "int"; +static const char __pyx_k_str[] = "str"; +static const char __pyx_k_List[] = "List"; +static const char __pyx_k_copy[] = "__copy__"; +static const char __pyx_k_dict[] = "__dict__"; +static const char __pyx_k_main[] = "__main__"; +static const char __pyx_k_memo[] = "memo"; +static const char __pyx_k_name[] = "__name__"; +static const char __pyx_k_self[] = "self"; +static const char __pyx_k_test[] = "__test__"; +static const char __pyx_k_text[] = "text"; +static const char __pyx_k_utf8[] = "utf8"; +static const char __pyx_k_Tuple[] = "Tuple"; +static const char __pyx_k_bytes[] = "bytes"; +static const char __pyx_k_c_ids[] = "c_ids"; +static const char __pyx_k_piece[] = "piece"; +static const char __pyx_k_range[] = "range"; +static const char __pyx_k_utf_8[] = "utf-8"; +static const char __pyx_k_bos_id[] = "bos_id"; +static const char __pyx_k_enable[] = "enable"; +static const char __pyx_k_encode[] = "encode"; +static const char __pyx_k_eos_id[] = "eos_id"; +static const char __pyx_k_import[] = "__import__"; +static const char __pyx_k_output[] = "output"; +static const char __pyx_k_pad_id[] = "pad_id"; +static const char __pyx_k_pieces[] = "pieces"; +static const char __pyx_k_reduce[] = "__reduce__"; +static const char __pyx_k_result[] = "result"; +static const char __pyx_k_return[] = "return"; +static const char __pyx_k_typing[] = "typing"; +static const char __pyx_k_unk_id[] = "unk_id"; +static const char __pyx_k_OSError[] = "OSError"; +static const char __pyx_k_disable[] = "disable"; +static const char __pyx_k_List_int[] = "List[int]"; +static const char __pyx_k_List_str[] = "List[str]"; +static const char __pyx_k_deepcopy[] = "__deepcopy__"; +static const char __pyx_k_filename[] = "filename"; +static const char __pyx_k_piece_id[] = "piece_id"; +static const char __pyx_k_protobuf[] = "protobuf"; +static const char __pyx_k_sentence[] = "sentence"; +static const char __pyx_k_TypeError[] = "TypeError"; +static const char __pyx_k_c_strings[] = "c_strings"; +static const char __pyx_k_from_file[] = "from_file"; +static const char __pyx_k_isenabled[] = "isenabled"; +static const char __pyx_k_processor[] = "processor"; +static const char __pyx_k_ValueError[] = "ValueError"; +static const char __pyx_k_piece_view[] = "piece_view"; +static const char __pyx_k_pyx_vtable[] = "__pyx_vtable__"; +static const char __pyx_k_serialized[] = "serialized"; +static const char __pyx_k_vocab_size[] = "vocab_size"; +static const char __pyx_k_id_to_piece[] = "id_to_piece"; +static const char __pyx_k_piece_bytes[] = "piece_bytes"; +static const char __pyx_k_piece_to_id[] = "piece_to_id"; +static const char __pyx_k_to_protobuf[] = "to_protobuf"; +static const char __pyx_k_RuntimeError[] = "RuntimeError"; +static const char __pyx_k_is_coroutine[] = "_is_coroutine"; +static const char __pyx_k_staticmethod[] = "staticmethod"; +static const char __pyx_k_encode_as_ids[] = "encode_as_ids"; +static const char __pyx_k_from_protobuf[] = "from_protobuf"; +static const char __pyx_k_protobuf_view[] = "protobuf_view"; +static const char __pyx_k_decode_from_ids[] = "decode_from_ids"; +static const char __pyx_k_encode_as_pieces[] = "encode_as_pieces"; +static const char __pyx_k_asyncio_coroutines[] = "asyncio.coroutines"; +static const char __pyx_k_cline_in_traceback[] = "cline_in_traceback"; +static const char __pyx_k_decode_from_pieces[] = "decode_from_pieces"; +static const char __pyx_k_SentencePieceProcessor[] = "SentencePieceProcessor"; +static const char __pyx_k_Tuple_List_int_List_str[] = "Tuple[List[int], List[str]]"; +static const char __pyx_k_curated_tokenizers__spp[] = "curated_tokenizers._spp"; +static const char __pyx_k_curated_tokenizers__spp_pyx[] = "curated_tokenizers\\_spp.pyx"; +static const char __pyx_k_piece_ID_must_be_in_range_0[] = "piece ID must be in range [0,"; +static const char __pyx_k_SentencePieceProcessor___copy[] = "SentencePieceProcessor.__copy__"; +static const char __pyx_k_SentencePieceProcessor_bos_id[] = "SentencePieceProcessor.bos_id"; +static const char __pyx_k_SentencePieceProcessor_encode[] = "SentencePieceProcessor.encode"; +static const char __pyx_k_SentencePieceProcessor_eos_id[] = "SentencePieceProcessor.eos_id"; +static const char __pyx_k_SentencePieceProcessor_pad_id[] = "SentencePieceProcessor.pad_id"; +static const char __pyx_k_SentencePieceProcessor_unk_id[] = "SentencePieceProcessor.unk_id"; +static const char __pyx_k_Pieces_must_be_of_type_int_when[] = "Pieces must be of type `int` when decoding from ids"; +static const char __pyx_k_Pieces_must_be_of_type_str_when[] = "Pieces must be of type `str` when decoding from pieces"; +static const char __pyx_k_SentencePieceProcessor___reduce[] = "SentencePieceProcessor.__reduce__"; +static const char __pyx_k_SentencePieceProcessor_piece_to[] = "SentencePieceProcessor.piece_to_id"; +static const char __pyx_k_SentencePieceProcessor___deepcop[] = "SentencePieceProcessor.__deepcopy__"; +static const char __pyx_k_SentencePieceProcessor_decode_fr[] = "SentencePieceProcessor.decode_from_ids"; +static const char __pyx_k_SentencePieceProcessor_encode_as[] = "SentencePieceProcessor.encode_as_ids"; +static const char __pyx_k_SentencePieceProcessor_from_file[] = "SentencePieceProcessor.from_file"; +static const char __pyx_k_SentencePieceProcessor_from_prot[] = "SentencePieceProcessor.from_protobuf"; +static const char __pyx_k_SentencePieceProcessor_id_to_pie[] = "SentencePieceProcessor.id_to_piece"; +static const char __pyx_k_SentencePieceProcessor_to_protob[] = "SentencePieceProcessor.to_protobuf"; +static const char __pyx_k_unpickle_sentence_piece_processo[] = "unpickle_sentence_piece_processor"; +static const char __pyx_k_SentencePieceProcessor_decode_fr_2[] = "SentencePieceProcessor.decode_from_pieces"; +static const char __pyx_k_SentencePieceProcessor_encode_as_2[] = "SentencePieceProcessor.encode_as_pieces"; +/* #### Code section: decls ### */ +static int __pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor___cinit__(struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *__pyx_v_self); /* proto */ +static int __pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_2__init__(CYTHON_UNUSED struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *__pyx_v_self); /* proto */ +static Py_ssize_t __pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_4__len__(struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_6__copy__(struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_8__deepcopy__(struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *__pyx_v_self, PyObject *__pyx_v_memo); /* proto */ +static PyObject *__pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_10from_file(PyObject *__pyx_v_filename); /* proto */ +static PyObject *__pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_12from_protobuf(PyObject *__pyx_v_protobuf); /* proto */ +static PyObject *__pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_14to_protobuf(struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_16decode_from_ids(struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *__pyx_v_self, PyObject *__pyx_v_ids); /* proto */ +static PyObject *__pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_18decode_from_pieces(struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *__pyx_v_self, PyObject *__pyx_v_pieces); /* proto */ +static PyObject *__pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_20encode(struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *__pyx_v_self, PyObject *__pyx_v_sentence); /* proto */ +static PyObject *__pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_22encode_as_ids(struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *__pyx_v_self, PyObject *__pyx_v_sentence); /* proto */ +static PyObject *__pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_24encode_as_pieces(struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *__pyx_v_self, PyObject *__pyx_v_sentence); /* proto */ +static PyObject *__pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_26piece_to_id(struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *__pyx_v_self, PyObject *__pyx_v_piece); /* proto */ +static PyObject *__pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_28id_to_piece(struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *__pyx_v_self, int __pyx_v_piece_id); /* proto */ +static PyObject *__pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_30bos_id(struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_32eos_id(struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_34pad_id(struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_36unk_id(struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_38__reduce__(struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_18curated_tokenizers_4_spp_unpickle_sentence_piece_processor(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_protobuf); /* proto */ +static PyObject *__pyx_tp_new_18curated_tokenizers_4_spp_SentencePieceProcessor(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static __Pyx_CachedCFunction __pyx_umethod_PyString_Type_encode = {0, 0, 0, 0, 0}; +/* #### Code section: late_includes ### */ +/* #### Code section: module_state ### */ +typedef struct { + PyObject *__pyx_d; + PyObject *__pyx_b; + PyObject *__pyx_cython_runtime; + PyObject *__pyx_empty_tuple; + PyObject *__pyx_empty_bytes; + PyObject *__pyx_empty_unicode; + #ifdef __Pyx_CyFunction_USED + PyTypeObject *__pyx_CyFunctionType; + #endif + #ifdef __Pyx_FusedFunction_USED + PyTypeObject *__pyx_FusedFunctionType; + #endif + #ifdef __Pyx_Generator_USED + PyTypeObject *__pyx_GeneratorType; + #endif + #ifdef __Pyx_IterableCoroutine_USED + PyTypeObject *__pyx_IterableCoroutineType; + #endif + #ifdef __Pyx_Coroutine_USED + PyTypeObject *__pyx_CoroutineAwaitType; + #endif + #ifdef __Pyx_Coroutine_USED + PyTypeObject *__pyx_CoroutineType; + #endif + #if CYTHON_USE_MODULE_STATE + #endif + #if CYTHON_USE_MODULE_STATE + #endif + #if CYTHON_USE_MODULE_STATE + #endif + #if CYTHON_USE_MODULE_STATE + #endif + #if CYTHON_USE_MODULE_STATE + #endif + #if CYTHON_USE_MODULE_STATE + #endif + #if CYTHON_USE_MODULE_STATE + PyObject *__pyx_type_18curated_tokenizers_4_spp_SentencePieceProcessor; + #endif + PyTypeObject *__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor; + PyObject *__pyx_n_s_List; + PyObject *__pyx_kp_s_List_int; + PyObject *__pyx_kp_s_List_str; + PyObject *__pyx_n_s_OSError; + PyObject *__pyx_kp_s_Pieces_must_be_of_type_int_when; + PyObject *__pyx_kp_s_Pieces_must_be_of_type_str_when; + PyObject *__pyx_n_s_RuntimeError; + PyObject *__pyx_n_s_SentencePieceProcessor; + PyObject *__pyx_n_s_SentencePieceProcessor___copy; + PyObject *__pyx_n_s_SentencePieceProcessor___deepcop; + PyObject *__pyx_n_s_SentencePieceProcessor___reduce; + PyObject *__pyx_n_s_SentencePieceProcessor_bos_id; + PyObject *__pyx_n_s_SentencePieceProcessor_decode_fr; + PyObject *__pyx_n_s_SentencePieceProcessor_decode_fr_2; + PyObject *__pyx_n_s_SentencePieceProcessor_encode; + PyObject *__pyx_n_s_SentencePieceProcessor_encode_as; + PyObject *__pyx_n_s_SentencePieceProcessor_encode_as_2; + PyObject *__pyx_n_s_SentencePieceProcessor_eos_id; + PyObject *__pyx_n_s_SentencePieceProcessor_from_file; + PyObject *__pyx_n_s_SentencePieceProcessor_from_prot; + PyObject *__pyx_n_s_SentencePieceProcessor_id_to_pie; + PyObject *__pyx_n_s_SentencePieceProcessor_pad_id; + PyObject *__pyx_n_s_SentencePieceProcessor_piece_to; + PyObject *__pyx_n_s_SentencePieceProcessor_to_protob; + PyObject *__pyx_n_s_SentencePieceProcessor_unk_id; + PyObject *__pyx_n_s_Tuple; + PyObject *__pyx_kp_s_Tuple_List_int_List_str; + PyObject *__pyx_n_s_TypeError; + PyObject *__pyx_n_s_ValueError; + PyObject *__pyx_kp_u__3; + PyObject *__pyx_n_s__35; + PyObject *__pyx_n_s_asyncio_coroutines; + PyObject *__pyx_n_s_bos_id; + PyObject *__pyx_n_s_bytes; + PyObject *__pyx_n_s_c_ids; + PyObject *__pyx_n_s_c_strings; + PyObject *__pyx_n_s_cline_in_traceback; + PyObject *__pyx_n_s_copy; + PyObject *__pyx_n_s_curated_tokenizers__spp; + PyObject *__pyx_kp_s_curated_tokenizers__spp_pyx; + PyObject *__pyx_n_s_decode_from_ids; + PyObject *__pyx_n_s_decode_from_pieces; + PyObject *__pyx_n_s_deepcopy; + PyObject *__pyx_n_s_dict; + PyObject *__pyx_kp_u_disable; + PyObject *__pyx_kp_u_enable; + PyObject *__pyx_n_s_encode; + PyObject *__pyx_n_s_encode_as_ids; + PyObject *__pyx_n_s_encode_as_pieces; + PyObject *__pyx_n_s_eos_id; + PyObject *__pyx_n_s_filename; + PyObject *__pyx_n_s_from_file; + PyObject *__pyx_n_s_from_protobuf; + PyObject *__pyx_kp_u_gc; + PyObject *__pyx_kp_u_got; + PyObject *__pyx_n_s_id; + PyObject *__pyx_n_s_id_to_piece; + PyObject *__pyx_n_s_ids; + PyObject *__pyx_n_s_idx; + PyObject *__pyx_n_s_import; + PyObject *__pyx_n_s_int; + PyObject *__pyx_n_s_is_coroutine; + PyObject *__pyx_kp_u_isenabled; + PyObject *__pyx_n_s_main; + PyObject *__pyx_n_s_memo; + PyObject *__pyx_n_s_name; + PyObject *__pyx_n_s_output; + PyObject *__pyx_n_s_pad_id; + PyObject *__pyx_n_s_piece; + PyObject *__pyx_kp_u_piece_ID_must_be_in_range_0; + PyObject *__pyx_n_s_piece_bytes; + PyObject *__pyx_n_s_piece_id; + PyObject *__pyx_n_s_piece_to_id; + PyObject *__pyx_n_s_piece_view; + PyObject *__pyx_n_s_pieces; + PyObject *__pyx_n_s_processor; + PyObject *__pyx_n_s_protobuf; + PyObject *__pyx_n_s_protobuf_view; + PyObject *__pyx_n_s_pyx_vtable; + PyObject *__pyx_n_s_range; + PyObject *__pyx_n_s_reduce; + PyObject *__pyx_n_s_result; + PyObject *__pyx_n_s_return; + PyObject *__pyx_n_s_self; + PyObject *__pyx_n_s_sentence; + PyObject *__pyx_n_s_serialized; + PyObject *__pyx_n_s_staticmethod; + PyObject *__pyx_n_s_str; + PyObject *__pyx_n_s_test; + PyObject *__pyx_n_s_text; + PyObject *__pyx_n_s_to_protobuf; + PyObject *__pyx_n_s_typing; + PyObject *__pyx_n_s_unk_id; + PyObject *__pyx_n_s_unpickle_sentence_piece_processo; + PyObject *__pyx_n_s_utf8; + PyObject *__pyx_kp_s_utf_8; + PyObject *__pyx_n_s_vocab_size; + PyObject *__pyx_tuple_; + PyObject *__pyx_tuple__2; + PyObject *__pyx_tuple__4; + PyObject *__pyx_tuple__6; + PyObject *__pyx_tuple__8; + PyObject *__pyx_tuple__10; + PyObject *__pyx_tuple__12; + PyObject *__pyx_tuple__14; + PyObject *__pyx_tuple__16; + PyObject *__pyx_tuple__18; + PyObject *__pyx_tuple__20; + PyObject *__pyx_tuple__22; + PyObject *__pyx_tuple__24; + PyObject *__pyx_tuple__26; + PyObject *__pyx_tuple__33; + PyObject *__pyx_codeobj__5; + PyObject *__pyx_codeobj__7; + PyObject *__pyx_codeobj__9; + PyObject *__pyx_codeobj__11; + PyObject *__pyx_codeobj__13; + PyObject *__pyx_codeobj__15; + PyObject *__pyx_codeobj__17; + PyObject *__pyx_codeobj__19; + PyObject *__pyx_codeobj__21; + PyObject *__pyx_codeobj__23; + PyObject *__pyx_codeobj__25; + PyObject *__pyx_codeobj__27; + PyObject *__pyx_codeobj__28; + PyObject *__pyx_codeobj__29; + PyObject *__pyx_codeobj__30; + PyObject *__pyx_codeobj__31; + PyObject *__pyx_codeobj__32; + PyObject *__pyx_codeobj__34; +} __pyx_mstate; + +#if CYTHON_USE_MODULE_STATE +#ifdef __cplusplus +namespace { + extern struct PyModuleDef __pyx_moduledef; +} /* anonymous namespace */ +#else +static struct PyModuleDef __pyx_moduledef; +#endif + +#define __pyx_mstate(o) ((__pyx_mstate *)__Pyx_PyModule_GetState(o)) + +#define __pyx_mstate_global (__pyx_mstate(PyState_FindModule(&__pyx_moduledef))) + +#define __pyx_m (PyState_FindModule(&__pyx_moduledef)) +#else +static __pyx_mstate __pyx_mstate_global_static = +#ifdef __cplusplus + {}; +#else + {0}; +#endif +static __pyx_mstate *__pyx_mstate_global = &__pyx_mstate_global_static; +#endif +/* #### Code section: module_state_clear ### */ +#if CYTHON_USE_MODULE_STATE +static int __pyx_m_clear(PyObject *m) { + __pyx_mstate *clear_module_state = __pyx_mstate(m); + if (!clear_module_state) return 0; + Py_CLEAR(clear_module_state->__pyx_d); + Py_CLEAR(clear_module_state->__pyx_b); + Py_CLEAR(clear_module_state->__pyx_cython_runtime); + Py_CLEAR(clear_module_state->__pyx_empty_tuple); + Py_CLEAR(clear_module_state->__pyx_empty_bytes); + Py_CLEAR(clear_module_state->__pyx_empty_unicode); + #ifdef __Pyx_CyFunction_USED + Py_CLEAR(clear_module_state->__pyx_CyFunctionType); + #endif + #ifdef __Pyx_FusedFunction_USED + Py_CLEAR(clear_module_state->__pyx_FusedFunctionType); + #endif + Py_CLEAR(clear_module_state->__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor); + Py_CLEAR(clear_module_state->__pyx_type_18curated_tokenizers_4_spp_SentencePieceProcessor); + Py_CLEAR(clear_module_state->__pyx_n_s_List); + Py_CLEAR(clear_module_state->__pyx_kp_s_List_int); + Py_CLEAR(clear_module_state->__pyx_kp_s_List_str); + Py_CLEAR(clear_module_state->__pyx_n_s_OSError); + Py_CLEAR(clear_module_state->__pyx_kp_s_Pieces_must_be_of_type_int_when); + Py_CLEAR(clear_module_state->__pyx_kp_s_Pieces_must_be_of_type_str_when); + Py_CLEAR(clear_module_state->__pyx_n_s_RuntimeError); + Py_CLEAR(clear_module_state->__pyx_n_s_SentencePieceProcessor); + Py_CLEAR(clear_module_state->__pyx_n_s_SentencePieceProcessor___copy); + Py_CLEAR(clear_module_state->__pyx_n_s_SentencePieceProcessor___deepcop); + Py_CLEAR(clear_module_state->__pyx_n_s_SentencePieceProcessor___reduce); + Py_CLEAR(clear_module_state->__pyx_n_s_SentencePieceProcessor_bos_id); + Py_CLEAR(clear_module_state->__pyx_n_s_SentencePieceProcessor_decode_fr); + Py_CLEAR(clear_module_state->__pyx_n_s_SentencePieceProcessor_decode_fr_2); + Py_CLEAR(clear_module_state->__pyx_n_s_SentencePieceProcessor_encode); + Py_CLEAR(clear_module_state->__pyx_n_s_SentencePieceProcessor_encode_as); + Py_CLEAR(clear_module_state->__pyx_n_s_SentencePieceProcessor_encode_as_2); + Py_CLEAR(clear_module_state->__pyx_n_s_SentencePieceProcessor_eos_id); + Py_CLEAR(clear_module_state->__pyx_n_s_SentencePieceProcessor_from_file); + Py_CLEAR(clear_module_state->__pyx_n_s_SentencePieceProcessor_from_prot); + Py_CLEAR(clear_module_state->__pyx_n_s_SentencePieceProcessor_id_to_pie); + Py_CLEAR(clear_module_state->__pyx_n_s_SentencePieceProcessor_pad_id); + Py_CLEAR(clear_module_state->__pyx_n_s_SentencePieceProcessor_piece_to); + Py_CLEAR(clear_module_state->__pyx_n_s_SentencePieceProcessor_to_protob); + Py_CLEAR(clear_module_state->__pyx_n_s_SentencePieceProcessor_unk_id); + Py_CLEAR(clear_module_state->__pyx_n_s_Tuple); + Py_CLEAR(clear_module_state->__pyx_kp_s_Tuple_List_int_List_str); + Py_CLEAR(clear_module_state->__pyx_n_s_TypeError); + Py_CLEAR(clear_module_state->__pyx_n_s_ValueError); + Py_CLEAR(clear_module_state->__pyx_kp_u__3); + Py_CLEAR(clear_module_state->__pyx_n_s__35); + Py_CLEAR(clear_module_state->__pyx_n_s_asyncio_coroutines); + Py_CLEAR(clear_module_state->__pyx_n_s_bos_id); + Py_CLEAR(clear_module_state->__pyx_n_s_bytes); + Py_CLEAR(clear_module_state->__pyx_n_s_c_ids); + Py_CLEAR(clear_module_state->__pyx_n_s_c_strings); + Py_CLEAR(clear_module_state->__pyx_n_s_cline_in_traceback); + Py_CLEAR(clear_module_state->__pyx_n_s_copy); + Py_CLEAR(clear_module_state->__pyx_n_s_curated_tokenizers__spp); + Py_CLEAR(clear_module_state->__pyx_kp_s_curated_tokenizers__spp_pyx); + Py_CLEAR(clear_module_state->__pyx_n_s_decode_from_ids); + Py_CLEAR(clear_module_state->__pyx_n_s_decode_from_pieces); + Py_CLEAR(clear_module_state->__pyx_n_s_deepcopy); + Py_CLEAR(clear_module_state->__pyx_n_s_dict); + Py_CLEAR(clear_module_state->__pyx_kp_u_disable); + Py_CLEAR(clear_module_state->__pyx_kp_u_enable); + Py_CLEAR(clear_module_state->__pyx_n_s_encode); + Py_CLEAR(clear_module_state->__pyx_n_s_encode_as_ids); + Py_CLEAR(clear_module_state->__pyx_n_s_encode_as_pieces); + Py_CLEAR(clear_module_state->__pyx_n_s_eos_id); + Py_CLEAR(clear_module_state->__pyx_n_s_filename); + Py_CLEAR(clear_module_state->__pyx_n_s_from_file); + Py_CLEAR(clear_module_state->__pyx_n_s_from_protobuf); + Py_CLEAR(clear_module_state->__pyx_kp_u_gc); + Py_CLEAR(clear_module_state->__pyx_kp_u_got); + Py_CLEAR(clear_module_state->__pyx_n_s_id); + Py_CLEAR(clear_module_state->__pyx_n_s_id_to_piece); + Py_CLEAR(clear_module_state->__pyx_n_s_ids); + Py_CLEAR(clear_module_state->__pyx_n_s_idx); + Py_CLEAR(clear_module_state->__pyx_n_s_import); + Py_CLEAR(clear_module_state->__pyx_n_s_int); + Py_CLEAR(clear_module_state->__pyx_n_s_is_coroutine); + Py_CLEAR(clear_module_state->__pyx_kp_u_isenabled); + Py_CLEAR(clear_module_state->__pyx_n_s_main); + Py_CLEAR(clear_module_state->__pyx_n_s_memo); + Py_CLEAR(clear_module_state->__pyx_n_s_name); + Py_CLEAR(clear_module_state->__pyx_n_s_output); + Py_CLEAR(clear_module_state->__pyx_n_s_pad_id); + Py_CLEAR(clear_module_state->__pyx_n_s_piece); + Py_CLEAR(clear_module_state->__pyx_kp_u_piece_ID_must_be_in_range_0); + Py_CLEAR(clear_module_state->__pyx_n_s_piece_bytes); + Py_CLEAR(clear_module_state->__pyx_n_s_piece_id); + Py_CLEAR(clear_module_state->__pyx_n_s_piece_to_id); + Py_CLEAR(clear_module_state->__pyx_n_s_piece_view); + Py_CLEAR(clear_module_state->__pyx_n_s_pieces); + Py_CLEAR(clear_module_state->__pyx_n_s_processor); + Py_CLEAR(clear_module_state->__pyx_n_s_protobuf); + Py_CLEAR(clear_module_state->__pyx_n_s_protobuf_view); + Py_CLEAR(clear_module_state->__pyx_n_s_pyx_vtable); + Py_CLEAR(clear_module_state->__pyx_n_s_range); + Py_CLEAR(clear_module_state->__pyx_n_s_reduce); + Py_CLEAR(clear_module_state->__pyx_n_s_result); + Py_CLEAR(clear_module_state->__pyx_n_s_return); + Py_CLEAR(clear_module_state->__pyx_n_s_self); + Py_CLEAR(clear_module_state->__pyx_n_s_sentence); + Py_CLEAR(clear_module_state->__pyx_n_s_serialized); + Py_CLEAR(clear_module_state->__pyx_n_s_staticmethod); + Py_CLEAR(clear_module_state->__pyx_n_s_str); + Py_CLEAR(clear_module_state->__pyx_n_s_test); + Py_CLEAR(clear_module_state->__pyx_n_s_text); + Py_CLEAR(clear_module_state->__pyx_n_s_to_protobuf); + Py_CLEAR(clear_module_state->__pyx_n_s_typing); + Py_CLEAR(clear_module_state->__pyx_n_s_unk_id); + Py_CLEAR(clear_module_state->__pyx_n_s_unpickle_sentence_piece_processo); + Py_CLEAR(clear_module_state->__pyx_n_s_utf8); + Py_CLEAR(clear_module_state->__pyx_kp_s_utf_8); + Py_CLEAR(clear_module_state->__pyx_n_s_vocab_size); + Py_CLEAR(clear_module_state->__pyx_tuple_); + Py_CLEAR(clear_module_state->__pyx_tuple__2); + Py_CLEAR(clear_module_state->__pyx_tuple__4); + Py_CLEAR(clear_module_state->__pyx_tuple__6); + Py_CLEAR(clear_module_state->__pyx_tuple__8); + Py_CLEAR(clear_module_state->__pyx_tuple__10); + Py_CLEAR(clear_module_state->__pyx_tuple__12); + Py_CLEAR(clear_module_state->__pyx_tuple__14); + Py_CLEAR(clear_module_state->__pyx_tuple__16); + Py_CLEAR(clear_module_state->__pyx_tuple__18); + Py_CLEAR(clear_module_state->__pyx_tuple__20); + Py_CLEAR(clear_module_state->__pyx_tuple__22); + Py_CLEAR(clear_module_state->__pyx_tuple__24); + Py_CLEAR(clear_module_state->__pyx_tuple__26); + Py_CLEAR(clear_module_state->__pyx_tuple__33); + Py_CLEAR(clear_module_state->__pyx_codeobj__5); + Py_CLEAR(clear_module_state->__pyx_codeobj__7); + Py_CLEAR(clear_module_state->__pyx_codeobj__9); + Py_CLEAR(clear_module_state->__pyx_codeobj__11); + Py_CLEAR(clear_module_state->__pyx_codeobj__13); + Py_CLEAR(clear_module_state->__pyx_codeobj__15); + Py_CLEAR(clear_module_state->__pyx_codeobj__17); + Py_CLEAR(clear_module_state->__pyx_codeobj__19); + Py_CLEAR(clear_module_state->__pyx_codeobj__21); + Py_CLEAR(clear_module_state->__pyx_codeobj__23); + Py_CLEAR(clear_module_state->__pyx_codeobj__25); + Py_CLEAR(clear_module_state->__pyx_codeobj__27); + Py_CLEAR(clear_module_state->__pyx_codeobj__28); + Py_CLEAR(clear_module_state->__pyx_codeobj__29); + Py_CLEAR(clear_module_state->__pyx_codeobj__30); + Py_CLEAR(clear_module_state->__pyx_codeobj__31); + Py_CLEAR(clear_module_state->__pyx_codeobj__32); + Py_CLEAR(clear_module_state->__pyx_codeobj__34); + return 0; +} +#endif +/* #### Code section: module_state_traverse ### */ +#if CYTHON_USE_MODULE_STATE +static int __pyx_m_traverse(PyObject *m, visitproc visit, void *arg) { + __pyx_mstate *traverse_module_state = __pyx_mstate(m); + if (!traverse_module_state) return 0; + Py_VISIT(traverse_module_state->__pyx_d); + Py_VISIT(traverse_module_state->__pyx_b); + Py_VISIT(traverse_module_state->__pyx_cython_runtime); + Py_VISIT(traverse_module_state->__pyx_empty_tuple); + Py_VISIT(traverse_module_state->__pyx_empty_bytes); + Py_VISIT(traverse_module_state->__pyx_empty_unicode); + #ifdef __Pyx_CyFunction_USED + Py_VISIT(traverse_module_state->__pyx_CyFunctionType); + #endif + #ifdef __Pyx_FusedFunction_USED + Py_VISIT(traverse_module_state->__pyx_FusedFunctionType); + #endif + Py_VISIT(traverse_module_state->__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor); + Py_VISIT(traverse_module_state->__pyx_type_18curated_tokenizers_4_spp_SentencePieceProcessor); + Py_VISIT(traverse_module_state->__pyx_n_s_List); + Py_VISIT(traverse_module_state->__pyx_kp_s_List_int); + Py_VISIT(traverse_module_state->__pyx_kp_s_List_str); + Py_VISIT(traverse_module_state->__pyx_n_s_OSError); + Py_VISIT(traverse_module_state->__pyx_kp_s_Pieces_must_be_of_type_int_when); + Py_VISIT(traverse_module_state->__pyx_kp_s_Pieces_must_be_of_type_str_when); + Py_VISIT(traverse_module_state->__pyx_n_s_RuntimeError); + Py_VISIT(traverse_module_state->__pyx_n_s_SentencePieceProcessor); + Py_VISIT(traverse_module_state->__pyx_n_s_SentencePieceProcessor___copy); + Py_VISIT(traverse_module_state->__pyx_n_s_SentencePieceProcessor___deepcop); + Py_VISIT(traverse_module_state->__pyx_n_s_SentencePieceProcessor___reduce); + Py_VISIT(traverse_module_state->__pyx_n_s_SentencePieceProcessor_bos_id); + Py_VISIT(traverse_module_state->__pyx_n_s_SentencePieceProcessor_decode_fr); + Py_VISIT(traverse_module_state->__pyx_n_s_SentencePieceProcessor_decode_fr_2); + Py_VISIT(traverse_module_state->__pyx_n_s_SentencePieceProcessor_encode); + Py_VISIT(traverse_module_state->__pyx_n_s_SentencePieceProcessor_encode_as); + Py_VISIT(traverse_module_state->__pyx_n_s_SentencePieceProcessor_encode_as_2); + Py_VISIT(traverse_module_state->__pyx_n_s_SentencePieceProcessor_eos_id); + Py_VISIT(traverse_module_state->__pyx_n_s_SentencePieceProcessor_from_file); + Py_VISIT(traverse_module_state->__pyx_n_s_SentencePieceProcessor_from_prot); + Py_VISIT(traverse_module_state->__pyx_n_s_SentencePieceProcessor_id_to_pie); + Py_VISIT(traverse_module_state->__pyx_n_s_SentencePieceProcessor_pad_id); + Py_VISIT(traverse_module_state->__pyx_n_s_SentencePieceProcessor_piece_to); + Py_VISIT(traverse_module_state->__pyx_n_s_SentencePieceProcessor_to_protob); + Py_VISIT(traverse_module_state->__pyx_n_s_SentencePieceProcessor_unk_id); + Py_VISIT(traverse_module_state->__pyx_n_s_Tuple); + Py_VISIT(traverse_module_state->__pyx_kp_s_Tuple_List_int_List_str); + Py_VISIT(traverse_module_state->__pyx_n_s_TypeError); + Py_VISIT(traverse_module_state->__pyx_n_s_ValueError); + Py_VISIT(traverse_module_state->__pyx_kp_u__3); + Py_VISIT(traverse_module_state->__pyx_n_s__35); + Py_VISIT(traverse_module_state->__pyx_n_s_asyncio_coroutines); + Py_VISIT(traverse_module_state->__pyx_n_s_bos_id); + Py_VISIT(traverse_module_state->__pyx_n_s_bytes); + Py_VISIT(traverse_module_state->__pyx_n_s_c_ids); + Py_VISIT(traverse_module_state->__pyx_n_s_c_strings); + Py_VISIT(traverse_module_state->__pyx_n_s_cline_in_traceback); + Py_VISIT(traverse_module_state->__pyx_n_s_copy); + Py_VISIT(traverse_module_state->__pyx_n_s_curated_tokenizers__spp); + Py_VISIT(traverse_module_state->__pyx_kp_s_curated_tokenizers__spp_pyx); + Py_VISIT(traverse_module_state->__pyx_n_s_decode_from_ids); + Py_VISIT(traverse_module_state->__pyx_n_s_decode_from_pieces); + Py_VISIT(traverse_module_state->__pyx_n_s_deepcopy); + Py_VISIT(traverse_module_state->__pyx_n_s_dict); + Py_VISIT(traverse_module_state->__pyx_kp_u_disable); + Py_VISIT(traverse_module_state->__pyx_kp_u_enable); + Py_VISIT(traverse_module_state->__pyx_n_s_encode); + Py_VISIT(traverse_module_state->__pyx_n_s_encode_as_ids); + Py_VISIT(traverse_module_state->__pyx_n_s_encode_as_pieces); + Py_VISIT(traverse_module_state->__pyx_n_s_eos_id); + Py_VISIT(traverse_module_state->__pyx_n_s_filename); + Py_VISIT(traverse_module_state->__pyx_n_s_from_file); + Py_VISIT(traverse_module_state->__pyx_n_s_from_protobuf); + Py_VISIT(traverse_module_state->__pyx_kp_u_gc); + Py_VISIT(traverse_module_state->__pyx_kp_u_got); + Py_VISIT(traverse_module_state->__pyx_n_s_id); + Py_VISIT(traverse_module_state->__pyx_n_s_id_to_piece); + Py_VISIT(traverse_module_state->__pyx_n_s_ids); + Py_VISIT(traverse_module_state->__pyx_n_s_idx); + Py_VISIT(traverse_module_state->__pyx_n_s_import); + Py_VISIT(traverse_module_state->__pyx_n_s_int); + Py_VISIT(traverse_module_state->__pyx_n_s_is_coroutine); + Py_VISIT(traverse_module_state->__pyx_kp_u_isenabled); + Py_VISIT(traverse_module_state->__pyx_n_s_main); + Py_VISIT(traverse_module_state->__pyx_n_s_memo); + Py_VISIT(traverse_module_state->__pyx_n_s_name); + Py_VISIT(traverse_module_state->__pyx_n_s_output); + Py_VISIT(traverse_module_state->__pyx_n_s_pad_id); + Py_VISIT(traverse_module_state->__pyx_n_s_piece); + Py_VISIT(traverse_module_state->__pyx_kp_u_piece_ID_must_be_in_range_0); + Py_VISIT(traverse_module_state->__pyx_n_s_piece_bytes); + Py_VISIT(traverse_module_state->__pyx_n_s_piece_id); + Py_VISIT(traverse_module_state->__pyx_n_s_piece_to_id); + Py_VISIT(traverse_module_state->__pyx_n_s_piece_view); + Py_VISIT(traverse_module_state->__pyx_n_s_pieces); + Py_VISIT(traverse_module_state->__pyx_n_s_processor); + Py_VISIT(traverse_module_state->__pyx_n_s_protobuf); + Py_VISIT(traverse_module_state->__pyx_n_s_protobuf_view); + Py_VISIT(traverse_module_state->__pyx_n_s_pyx_vtable); + Py_VISIT(traverse_module_state->__pyx_n_s_range); + Py_VISIT(traverse_module_state->__pyx_n_s_reduce); + Py_VISIT(traverse_module_state->__pyx_n_s_result); + Py_VISIT(traverse_module_state->__pyx_n_s_return); + Py_VISIT(traverse_module_state->__pyx_n_s_self); + Py_VISIT(traverse_module_state->__pyx_n_s_sentence); + Py_VISIT(traverse_module_state->__pyx_n_s_serialized); + Py_VISIT(traverse_module_state->__pyx_n_s_staticmethod); + Py_VISIT(traverse_module_state->__pyx_n_s_str); + Py_VISIT(traverse_module_state->__pyx_n_s_test); + Py_VISIT(traverse_module_state->__pyx_n_s_text); + Py_VISIT(traverse_module_state->__pyx_n_s_to_protobuf); + Py_VISIT(traverse_module_state->__pyx_n_s_typing); + Py_VISIT(traverse_module_state->__pyx_n_s_unk_id); + Py_VISIT(traverse_module_state->__pyx_n_s_unpickle_sentence_piece_processo); + Py_VISIT(traverse_module_state->__pyx_n_s_utf8); + Py_VISIT(traverse_module_state->__pyx_kp_s_utf_8); + Py_VISIT(traverse_module_state->__pyx_n_s_vocab_size); + Py_VISIT(traverse_module_state->__pyx_tuple_); + Py_VISIT(traverse_module_state->__pyx_tuple__2); + Py_VISIT(traverse_module_state->__pyx_tuple__4); + Py_VISIT(traverse_module_state->__pyx_tuple__6); + Py_VISIT(traverse_module_state->__pyx_tuple__8); + Py_VISIT(traverse_module_state->__pyx_tuple__10); + Py_VISIT(traverse_module_state->__pyx_tuple__12); + Py_VISIT(traverse_module_state->__pyx_tuple__14); + Py_VISIT(traverse_module_state->__pyx_tuple__16); + Py_VISIT(traverse_module_state->__pyx_tuple__18); + Py_VISIT(traverse_module_state->__pyx_tuple__20); + Py_VISIT(traverse_module_state->__pyx_tuple__22); + Py_VISIT(traverse_module_state->__pyx_tuple__24); + Py_VISIT(traverse_module_state->__pyx_tuple__26); + Py_VISIT(traverse_module_state->__pyx_tuple__33); + Py_VISIT(traverse_module_state->__pyx_codeobj__5); + Py_VISIT(traverse_module_state->__pyx_codeobj__7); + Py_VISIT(traverse_module_state->__pyx_codeobj__9); + Py_VISIT(traverse_module_state->__pyx_codeobj__11); + Py_VISIT(traverse_module_state->__pyx_codeobj__13); + Py_VISIT(traverse_module_state->__pyx_codeobj__15); + Py_VISIT(traverse_module_state->__pyx_codeobj__17); + Py_VISIT(traverse_module_state->__pyx_codeobj__19); + Py_VISIT(traverse_module_state->__pyx_codeobj__21); + Py_VISIT(traverse_module_state->__pyx_codeobj__23); + Py_VISIT(traverse_module_state->__pyx_codeobj__25); + Py_VISIT(traverse_module_state->__pyx_codeobj__27); + Py_VISIT(traverse_module_state->__pyx_codeobj__28); + Py_VISIT(traverse_module_state->__pyx_codeobj__29); + Py_VISIT(traverse_module_state->__pyx_codeobj__30); + Py_VISIT(traverse_module_state->__pyx_codeobj__31); + Py_VISIT(traverse_module_state->__pyx_codeobj__32); + Py_VISIT(traverse_module_state->__pyx_codeobj__34); + return 0; +} +#endif +/* #### Code section: module_state_defines ### */ +#define __pyx_d __pyx_mstate_global->__pyx_d +#define __pyx_b __pyx_mstate_global->__pyx_b +#define __pyx_cython_runtime __pyx_mstate_global->__pyx_cython_runtime +#define __pyx_empty_tuple __pyx_mstate_global->__pyx_empty_tuple +#define __pyx_empty_bytes __pyx_mstate_global->__pyx_empty_bytes +#define __pyx_empty_unicode __pyx_mstate_global->__pyx_empty_unicode +#ifdef __Pyx_CyFunction_USED +#define __pyx_CyFunctionType __pyx_mstate_global->__pyx_CyFunctionType +#endif +#ifdef __Pyx_FusedFunction_USED +#define __pyx_FusedFunctionType __pyx_mstate_global->__pyx_FusedFunctionType +#endif +#ifdef __Pyx_Generator_USED +#define __pyx_GeneratorType __pyx_mstate_global->__pyx_GeneratorType +#endif +#ifdef __Pyx_IterableCoroutine_USED +#define __pyx_IterableCoroutineType __pyx_mstate_global->__pyx_IterableCoroutineType +#endif +#ifdef __Pyx_Coroutine_USED +#define __pyx_CoroutineAwaitType __pyx_mstate_global->__pyx_CoroutineAwaitType +#endif +#ifdef __Pyx_Coroutine_USED +#define __pyx_CoroutineType __pyx_mstate_global->__pyx_CoroutineType +#endif +#if CYTHON_USE_MODULE_STATE +#endif +#if CYTHON_USE_MODULE_STATE +#endif +#if CYTHON_USE_MODULE_STATE +#endif +#if CYTHON_USE_MODULE_STATE +#endif +#if CYTHON_USE_MODULE_STATE +#endif +#if CYTHON_USE_MODULE_STATE +#endif +#if CYTHON_USE_MODULE_STATE +#define __pyx_type_18curated_tokenizers_4_spp_SentencePieceProcessor __pyx_mstate_global->__pyx_type_18curated_tokenizers_4_spp_SentencePieceProcessor +#endif +#define __pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor __pyx_mstate_global->__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor +#define __pyx_n_s_List __pyx_mstate_global->__pyx_n_s_List +#define __pyx_kp_s_List_int __pyx_mstate_global->__pyx_kp_s_List_int +#define __pyx_kp_s_List_str __pyx_mstate_global->__pyx_kp_s_List_str +#define __pyx_n_s_OSError __pyx_mstate_global->__pyx_n_s_OSError +#define __pyx_kp_s_Pieces_must_be_of_type_int_when __pyx_mstate_global->__pyx_kp_s_Pieces_must_be_of_type_int_when +#define __pyx_kp_s_Pieces_must_be_of_type_str_when __pyx_mstate_global->__pyx_kp_s_Pieces_must_be_of_type_str_when +#define __pyx_n_s_RuntimeError __pyx_mstate_global->__pyx_n_s_RuntimeError +#define __pyx_n_s_SentencePieceProcessor __pyx_mstate_global->__pyx_n_s_SentencePieceProcessor +#define __pyx_n_s_SentencePieceProcessor___copy __pyx_mstate_global->__pyx_n_s_SentencePieceProcessor___copy +#define __pyx_n_s_SentencePieceProcessor___deepcop __pyx_mstate_global->__pyx_n_s_SentencePieceProcessor___deepcop +#define __pyx_n_s_SentencePieceProcessor___reduce __pyx_mstate_global->__pyx_n_s_SentencePieceProcessor___reduce +#define __pyx_n_s_SentencePieceProcessor_bos_id __pyx_mstate_global->__pyx_n_s_SentencePieceProcessor_bos_id +#define __pyx_n_s_SentencePieceProcessor_decode_fr __pyx_mstate_global->__pyx_n_s_SentencePieceProcessor_decode_fr +#define __pyx_n_s_SentencePieceProcessor_decode_fr_2 __pyx_mstate_global->__pyx_n_s_SentencePieceProcessor_decode_fr_2 +#define __pyx_n_s_SentencePieceProcessor_encode __pyx_mstate_global->__pyx_n_s_SentencePieceProcessor_encode +#define __pyx_n_s_SentencePieceProcessor_encode_as __pyx_mstate_global->__pyx_n_s_SentencePieceProcessor_encode_as +#define __pyx_n_s_SentencePieceProcessor_encode_as_2 __pyx_mstate_global->__pyx_n_s_SentencePieceProcessor_encode_as_2 +#define __pyx_n_s_SentencePieceProcessor_eos_id __pyx_mstate_global->__pyx_n_s_SentencePieceProcessor_eos_id +#define __pyx_n_s_SentencePieceProcessor_from_file __pyx_mstate_global->__pyx_n_s_SentencePieceProcessor_from_file +#define __pyx_n_s_SentencePieceProcessor_from_prot __pyx_mstate_global->__pyx_n_s_SentencePieceProcessor_from_prot +#define __pyx_n_s_SentencePieceProcessor_id_to_pie __pyx_mstate_global->__pyx_n_s_SentencePieceProcessor_id_to_pie +#define __pyx_n_s_SentencePieceProcessor_pad_id __pyx_mstate_global->__pyx_n_s_SentencePieceProcessor_pad_id +#define __pyx_n_s_SentencePieceProcessor_piece_to __pyx_mstate_global->__pyx_n_s_SentencePieceProcessor_piece_to +#define __pyx_n_s_SentencePieceProcessor_to_protob __pyx_mstate_global->__pyx_n_s_SentencePieceProcessor_to_protob +#define __pyx_n_s_SentencePieceProcessor_unk_id __pyx_mstate_global->__pyx_n_s_SentencePieceProcessor_unk_id +#define __pyx_n_s_Tuple __pyx_mstate_global->__pyx_n_s_Tuple +#define __pyx_kp_s_Tuple_List_int_List_str __pyx_mstate_global->__pyx_kp_s_Tuple_List_int_List_str +#define __pyx_n_s_TypeError __pyx_mstate_global->__pyx_n_s_TypeError +#define __pyx_n_s_ValueError __pyx_mstate_global->__pyx_n_s_ValueError +#define __pyx_kp_u__3 __pyx_mstate_global->__pyx_kp_u__3 +#define __pyx_n_s__35 __pyx_mstate_global->__pyx_n_s__35 +#define __pyx_n_s_asyncio_coroutines __pyx_mstate_global->__pyx_n_s_asyncio_coroutines +#define __pyx_n_s_bos_id __pyx_mstate_global->__pyx_n_s_bos_id +#define __pyx_n_s_bytes __pyx_mstate_global->__pyx_n_s_bytes +#define __pyx_n_s_c_ids __pyx_mstate_global->__pyx_n_s_c_ids +#define __pyx_n_s_c_strings __pyx_mstate_global->__pyx_n_s_c_strings +#define __pyx_n_s_cline_in_traceback __pyx_mstate_global->__pyx_n_s_cline_in_traceback +#define __pyx_n_s_copy __pyx_mstate_global->__pyx_n_s_copy +#define __pyx_n_s_curated_tokenizers__spp __pyx_mstate_global->__pyx_n_s_curated_tokenizers__spp +#define __pyx_kp_s_curated_tokenizers__spp_pyx __pyx_mstate_global->__pyx_kp_s_curated_tokenizers__spp_pyx +#define __pyx_n_s_decode_from_ids __pyx_mstate_global->__pyx_n_s_decode_from_ids +#define __pyx_n_s_decode_from_pieces __pyx_mstate_global->__pyx_n_s_decode_from_pieces +#define __pyx_n_s_deepcopy __pyx_mstate_global->__pyx_n_s_deepcopy +#define __pyx_n_s_dict __pyx_mstate_global->__pyx_n_s_dict +#define __pyx_kp_u_disable __pyx_mstate_global->__pyx_kp_u_disable +#define __pyx_kp_u_enable __pyx_mstate_global->__pyx_kp_u_enable +#define __pyx_n_s_encode __pyx_mstate_global->__pyx_n_s_encode +#define __pyx_n_s_encode_as_ids __pyx_mstate_global->__pyx_n_s_encode_as_ids +#define __pyx_n_s_encode_as_pieces __pyx_mstate_global->__pyx_n_s_encode_as_pieces +#define __pyx_n_s_eos_id __pyx_mstate_global->__pyx_n_s_eos_id +#define __pyx_n_s_filename __pyx_mstate_global->__pyx_n_s_filename +#define __pyx_n_s_from_file __pyx_mstate_global->__pyx_n_s_from_file +#define __pyx_n_s_from_protobuf __pyx_mstate_global->__pyx_n_s_from_protobuf +#define __pyx_kp_u_gc __pyx_mstate_global->__pyx_kp_u_gc +#define __pyx_kp_u_got __pyx_mstate_global->__pyx_kp_u_got +#define __pyx_n_s_id __pyx_mstate_global->__pyx_n_s_id +#define __pyx_n_s_id_to_piece __pyx_mstate_global->__pyx_n_s_id_to_piece +#define __pyx_n_s_ids __pyx_mstate_global->__pyx_n_s_ids +#define __pyx_n_s_idx __pyx_mstate_global->__pyx_n_s_idx +#define __pyx_n_s_import __pyx_mstate_global->__pyx_n_s_import +#define __pyx_n_s_int __pyx_mstate_global->__pyx_n_s_int +#define __pyx_n_s_is_coroutine __pyx_mstate_global->__pyx_n_s_is_coroutine +#define __pyx_kp_u_isenabled __pyx_mstate_global->__pyx_kp_u_isenabled +#define __pyx_n_s_main __pyx_mstate_global->__pyx_n_s_main +#define __pyx_n_s_memo __pyx_mstate_global->__pyx_n_s_memo +#define __pyx_n_s_name __pyx_mstate_global->__pyx_n_s_name +#define __pyx_n_s_output __pyx_mstate_global->__pyx_n_s_output +#define __pyx_n_s_pad_id __pyx_mstate_global->__pyx_n_s_pad_id +#define __pyx_n_s_piece __pyx_mstate_global->__pyx_n_s_piece +#define __pyx_kp_u_piece_ID_must_be_in_range_0 __pyx_mstate_global->__pyx_kp_u_piece_ID_must_be_in_range_0 +#define __pyx_n_s_piece_bytes __pyx_mstate_global->__pyx_n_s_piece_bytes +#define __pyx_n_s_piece_id __pyx_mstate_global->__pyx_n_s_piece_id +#define __pyx_n_s_piece_to_id __pyx_mstate_global->__pyx_n_s_piece_to_id +#define __pyx_n_s_piece_view __pyx_mstate_global->__pyx_n_s_piece_view +#define __pyx_n_s_pieces __pyx_mstate_global->__pyx_n_s_pieces +#define __pyx_n_s_processor __pyx_mstate_global->__pyx_n_s_processor +#define __pyx_n_s_protobuf __pyx_mstate_global->__pyx_n_s_protobuf +#define __pyx_n_s_protobuf_view __pyx_mstate_global->__pyx_n_s_protobuf_view +#define __pyx_n_s_pyx_vtable __pyx_mstate_global->__pyx_n_s_pyx_vtable +#define __pyx_n_s_range __pyx_mstate_global->__pyx_n_s_range +#define __pyx_n_s_reduce __pyx_mstate_global->__pyx_n_s_reduce +#define __pyx_n_s_result __pyx_mstate_global->__pyx_n_s_result +#define __pyx_n_s_return __pyx_mstate_global->__pyx_n_s_return +#define __pyx_n_s_self __pyx_mstate_global->__pyx_n_s_self +#define __pyx_n_s_sentence __pyx_mstate_global->__pyx_n_s_sentence +#define __pyx_n_s_serialized __pyx_mstate_global->__pyx_n_s_serialized +#define __pyx_n_s_staticmethod __pyx_mstate_global->__pyx_n_s_staticmethod +#define __pyx_n_s_str __pyx_mstate_global->__pyx_n_s_str +#define __pyx_n_s_test __pyx_mstate_global->__pyx_n_s_test +#define __pyx_n_s_text __pyx_mstate_global->__pyx_n_s_text +#define __pyx_n_s_to_protobuf __pyx_mstate_global->__pyx_n_s_to_protobuf +#define __pyx_n_s_typing __pyx_mstate_global->__pyx_n_s_typing +#define __pyx_n_s_unk_id __pyx_mstate_global->__pyx_n_s_unk_id +#define __pyx_n_s_unpickle_sentence_piece_processo __pyx_mstate_global->__pyx_n_s_unpickle_sentence_piece_processo +#define __pyx_n_s_utf8 __pyx_mstate_global->__pyx_n_s_utf8 +#define __pyx_kp_s_utf_8 __pyx_mstate_global->__pyx_kp_s_utf_8 +#define __pyx_n_s_vocab_size __pyx_mstate_global->__pyx_n_s_vocab_size +#define __pyx_tuple_ __pyx_mstate_global->__pyx_tuple_ +#define __pyx_tuple__2 __pyx_mstate_global->__pyx_tuple__2 +#define __pyx_tuple__4 __pyx_mstate_global->__pyx_tuple__4 +#define __pyx_tuple__6 __pyx_mstate_global->__pyx_tuple__6 +#define __pyx_tuple__8 __pyx_mstate_global->__pyx_tuple__8 +#define __pyx_tuple__10 __pyx_mstate_global->__pyx_tuple__10 +#define __pyx_tuple__12 __pyx_mstate_global->__pyx_tuple__12 +#define __pyx_tuple__14 __pyx_mstate_global->__pyx_tuple__14 +#define __pyx_tuple__16 __pyx_mstate_global->__pyx_tuple__16 +#define __pyx_tuple__18 __pyx_mstate_global->__pyx_tuple__18 +#define __pyx_tuple__20 __pyx_mstate_global->__pyx_tuple__20 +#define __pyx_tuple__22 __pyx_mstate_global->__pyx_tuple__22 +#define __pyx_tuple__24 __pyx_mstate_global->__pyx_tuple__24 +#define __pyx_tuple__26 __pyx_mstate_global->__pyx_tuple__26 +#define __pyx_tuple__33 __pyx_mstate_global->__pyx_tuple__33 +#define __pyx_codeobj__5 __pyx_mstate_global->__pyx_codeobj__5 +#define __pyx_codeobj__7 __pyx_mstate_global->__pyx_codeobj__7 +#define __pyx_codeobj__9 __pyx_mstate_global->__pyx_codeobj__9 +#define __pyx_codeobj__11 __pyx_mstate_global->__pyx_codeobj__11 +#define __pyx_codeobj__13 __pyx_mstate_global->__pyx_codeobj__13 +#define __pyx_codeobj__15 __pyx_mstate_global->__pyx_codeobj__15 +#define __pyx_codeobj__17 __pyx_mstate_global->__pyx_codeobj__17 +#define __pyx_codeobj__19 __pyx_mstate_global->__pyx_codeobj__19 +#define __pyx_codeobj__21 __pyx_mstate_global->__pyx_codeobj__21 +#define __pyx_codeobj__23 __pyx_mstate_global->__pyx_codeobj__23 +#define __pyx_codeobj__25 __pyx_mstate_global->__pyx_codeobj__25 +#define __pyx_codeobj__27 __pyx_mstate_global->__pyx_codeobj__27 +#define __pyx_codeobj__28 __pyx_mstate_global->__pyx_codeobj__28 +#define __pyx_codeobj__29 __pyx_mstate_global->__pyx_codeobj__29 +#define __pyx_codeobj__30 __pyx_mstate_global->__pyx_codeobj__30 +#define __pyx_codeobj__31 __pyx_mstate_global->__pyx_codeobj__31 +#define __pyx_codeobj__32 __pyx_mstate_global->__pyx_codeobj__32 +#define __pyx_codeobj__34 __pyx_mstate_global->__pyx_codeobj__34 +/* #### Code section: module_code ### */ + +/* "string.from_py":13 + * + * @cname("__pyx_convert_string_from_py_std__in_string") + * cdef string __pyx_convert_string_from_py_std__in_string(object o) except *: # <<<<<<<<<<<<<< + * cdef Py_ssize_t length = 0 + * cdef const char* data = __Pyx_PyObject_AsStringAndSize(o, &length) + */ + +static std::string __pyx_convert_string_from_py_std__in_string(PyObject *__pyx_v_o) { + Py_ssize_t __pyx_v_length; + char const *__pyx_v_data; + std::string __pyx_r; + char const *__pyx_t_1; + std::string __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "string.from_py":14 + * @cname("__pyx_convert_string_from_py_std__in_string") + * cdef string __pyx_convert_string_from_py_std__in_string(object o) except *: + * cdef Py_ssize_t length = 0 # <<<<<<<<<<<<<< + * cdef const char* data = __Pyx_PyObject_AsStringAndSize(o, &length) + * return string(data, length) + */ + __pyx_v_length = 0; + + /* "string.from_py":15 + * cdef string __pyx_convert_string_from_py_std__in_string(object o) except *: + * cdef Py_ssize_t length = 0 + * cdef const char* data = __Pyx_PyObject_AsStringAndSize(o, &length) # <<<<<<<<<<<<<< + * return string(data, length) + * + */ + __pyx_t_1 = __Pyx_PyObject_AsStringAndSize(__pyx_v_o, (&__pyx_v_length)); if (unlikely(__pyx_t_1 == ((char const *)NULL))) __PYX_ERR(1, 15, __pyx_L1_error) + __pyx_v_data = __pyx_t_1; + + /* "string.from_py":16 + * cdef Py_ssize_t length = 0 + * cdef const char* data = __Pyx_PyObject_AsStringAndSize(o, &length) + * return string(data, length) # <<<<<<<<<<<<<< + * + * + */ + try { + __pyx_t_2 = std::string(__pyx_v_data, __pyx_v_length); + } catch(...) { + __Pyx_CppExn2PyErr(); + __PYX_ERR(1, 16, __pyx_L1_error) + } + __pyx_r = __pyx_t_2; + goto __pyx_L0; + + /* "string.from_py":13 + * + * @cname("__pyx_convert_string_from_py_std__in_string") + * cdef string __pyx_convert_string_from_py_std__in_string(object o) except *: # <<<<<<<<<<<<<< + * cdef Py_ssize_t length = 0 + * cdef const char* data = __Pyx_PyObject_AsStringAndSize(o, &length) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("string.from_py.__pyx_convert_string_from_py_std__in_string", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_pretend_to_initialize(&__pyx_r); + __pyx_L0:; + return __pyx_r; +} + +/* "string.to_py":31 + * + * @cname("__pyx_convert_PyObject_string_to_py_std__in_string") + * cdef inline object __pyx_convert_PyObject_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< + * return __Pyx_PyObject_FromStringAndSize(s.data(), s.size()) + * cdef extern from *: + */ + +static CYTHON_INLINE PyObject *__pyx_convert_PyObject_string_to_py_std__in_string(std::string const &__pyx_v_s) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__pyx_convert_PyObject_string_to_py_std__in_string", 1); + + /* "string.to_py":32 + * @cname("__pyx_convert_PyObject_string_to_py_std__in_string") + * cdef inline object __pyx_convert_PyObject_string_to_py_std__in_string(const string& s): + * return __Pyx_PyObject_FromStringAndSize(s.data(), s.size()) # <<<<<<<<<<<<<< + * cdef extern from *: + * cdef object __Pyx_PyUnicode_FromStringAndSize(const char*, size_t) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_FromStringAndSize(__pyx_v_s.data(), __pyx_v_s.size()); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 32, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "string.to_py":31 + * + * @cname("__pyx_convert_PyObject_string_to_py_std__in_string") + * cdef inline object __pyx_convert_PyObject_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< + * return __Pyx_PyObject_FromStringAndSize(s.data(), s.size()) + * cdef extern from *: + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("string.to_py.__pyx_convert_PyObject_string_to_py_std__in_string", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "string.to_py":37 + * + * @cname("__pyx_convert_PyUnicode_string_to_py_std__in_string") + * cdef inline object __pyx_convert_PyUnicode_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< + * return __Pyx_PyUnicode_FromStringAndSize(s.data(), s.size()) + * cdef extern from *: + */ + +static CYTHON_INLINE PyObject *__pyx_convert_PyUnicode_string_to_py_std__in_string(std::string const &__pyx_v_s) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__pyx_convert_PyUnicode_string_to_py_std__in_string", 1); + + /* "string.to_py":38 + * @cname("__pyx_convert_PyUnicode_string_to_py_std__in_string") + * cdef inline object __pyx_convert_PyUnicode_string_to_py_std__in_string(const string& s): + * return __Pyx_PyUnicode_FromStringAndSize(s.data(), s.size()) # <<<<<<<<<<<<<< + * cdef extern from *: + * cdef object __Pyx_PyStr_FromStringAndSize(const char*, size_t) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyUnicode_FromStringAndSize(__pyx_v_s.data(), __pyx_v_s.size()); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 38, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "string.to_py":37 + * + * @cname("__pyx_convert_PyUnicode_string_to_py_std__in_string") + * cdef inline object __pyx_convert_PyUnicode_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< + * return __Pyx_PyUnicode_FromStringAndSize(s.data(), s.size()) + * cdef extern from *: + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("string.to_py.__pyx_convert_PyUnicode_string_to_py_std__in_string", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "string.to_py":43 + * + * @cname("__pyx_convert_PyStr_string_to_py_std__in_string") + * cdef inline object __pyx_convert_PyStr_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< + * return __Pyx_PyStr_FromStringAndSize(s.data(), s.size()) + * cdef extern from *: + */ + +static CYTHON_INLINE PyObject *__pyx_convert_PyStr_string_to_py_std__in_string(std::string const &__pyx_v_s) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__pyx_convert_PyStr_string_to_py_std__in_string", 1); + + /* "string.to_py":44 + * @cname("__pyx_convert_PyStr_string_to_py_std__in_string") + * cdef inline object __pyx_convert_PyStr_string_to_py_std__in_string(const string& s): + * return __Pyx_PyStr_FromStringAndSize(s.data(), s.size()) # <<<<<<<<<<<<<< + * cdef extern from *: + * cdef object __Pyx_PyBytes_FromStringAndSize(const char*, size_t) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyStr_FromStringAndSize(__pyx_v_s.data(), __pyx_v_s.size()); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 44, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "string.to_py":43 + * + * @cname("__pyx_convert_PyStr_string_to_py_std__in_string") + * cdef inline object __pyx_convert_PyStr_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< + * return __Pyx_PyStr_FromStringAndSize(s.data(), s.size()) + * cdef extern from *: + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("string.to_py.__pyx_convert_PyStr_string_to_py_std__in_string", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "string.to_py":49 + * + * @cname("__pyx_convert_PyBytes_string_to_py_std__in_string") + * cdef inline object __pyx_convert_PyBytes_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< + * return __Pyx_PyBytes_FromStringAndSize(s.data(), s.size()) + * cdef extern from *: + */ + +static CYTHON_INLINE PyObject *__pyx_convert_PyBytes_string_to_py_std__in_string(std::string const &__pyx_v_s) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__pyx_convert_PyBytes_string_to_py_std__in_string", 1); + + /* "string.to_py":50 + * @cname("__pyx_convert_PyBytes_string_to_py_std__in_string") + * cdef inline object __pyx_convert_PyBytes_string_to_py_std__in_string(const string& s): + * return __Pyx_PyBytes_FromStringAndSize(s.data(), s.size()) # <<<<<<<<<<<<<< + * cdef extern from *: + * cdef object __Pyx_PyByteArray_FromStringAndSize(const char*, size_t) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyBytes_FromStringAndSize(__pyx_v_s.data(), __pyx_v_s.size()); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 50, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "string.to_py":49 + * + * @cname("__pyx_convert_PyBytes_string_to_py_std__in_string") + * cdef inline object __pyx_convert_PyBytes_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< + * return __Pyx_PyBytes_FromStringAndSize(s.data(), s.size()) + * cdef extern from *: + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("string.to_py.__pyx_convert_PyBytes_string_to_py_std__in_string", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "string.to_py":55 + * + * @cname("__pyx_convert_PyByteArray_string_to_py_std__in_string") + * cdef inline object __pyx_convert_PyByteArray_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< + * return __Pyx_PyByteArray_FromStringAndSize(s.data(), s.size()) + * + */ + +static CYTHON_INLINE PyObject *__pyx_convert_PyByteArray_string_to_py_std__in_string(std::string const &__pyx_v_s) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__pyx_convert_PyByteArray_string_to_py_std__in_string", 1); + + /* "string.to_py":56 + * @cname("__pyx_convert_PyByteArray_string_to_py_std__in_string") + * cdef inline object __pyx_convert_PyByteArray_string_to_py_std__in_string(const string& s): + * return __Pyx_PyByteArray_FromStringAndSize(s.data(), s.size()) # <<<<<<<<<<<<<< + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyByteArray_FromStringAndSize(__pyx_v_s.data(), __pyx_v_s.size()); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 56, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "string.to_py":55 + * + * @cname("__pyx_convert_PyByteArray_string_to_py_std__in_string") + * cdef inline object __pyx_convert_PyByteArray_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< + * return __Pyx_PyByteArray_FromStringAndSize(s.data(), s.size()) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("string.to_py.__pyx_convert_PyByteArray_string_to_py_std__in_string", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_spp.pyx":5 + * + * cdef class SentencePieceProcessor: + * def __cinit__(self): # <<<<<<<<<<<<<< + * self.spp.reset(new CSentencePieceProcessor()) + * + */ + +/* Python wrapper */ +static int __pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); + #if CYTHON_ASSUME_SAFE_MACROS + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return -1; + #endif + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 0, 0, __pyx_nargs); return -1;} + if (unlikely(__pyx_kwds) && __Pyx_NumKwargs_VARARGS(__pyx_kwds) && unlikely(!__Pyx_CheckKeywordStrings(__pyx_kwds, "__cinit__", 0))) return -1; + __pyx_r = __pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor___cinit__(((struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor___cinit__(struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *__pyx_v_self) { + int __pyx_r; + sentencepiece::SentencePieceProcessor *__pyx_t_1; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "curated_tokenizers/_spp.pyx":6 + * cdef class SentencePieceProcessor: + * def __cinit__(self): + * self.spp.reset(new CSentencePieceProcessor()) # <<<<<<<<<<<<<< + * + * def __init__(self): + */ + try { + __pyx_t_1 = new sentencepiece::SentencePieceProcessor(); + } catch(...) { + __Pyx_CppExn2PyErr(); + __PYX_ERR(0, 6, __pyx_L1_error) + } + __pyx_v_self->spp.reset(__pyx_t_1); + + /* "curated_tokenizers/_spp.pyx":5 + * + * cdef class SentencePieceProcessor: + * def __cinit__(self): # <<<<<<<<<<<<<< + * self.spp.reset(new CSentencePieceProcessor()) + * + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_AddTraceback("curated_tokenizers._spp.SentencePieceProcessor.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + return __pyx_r; +} + +/* "curated_tokenizers/_spp.pyx":8 + * self.spp.reset(new CSentencePieceProcessor()) + * + * def __init__(self): # <<<<<<<<<<<<<< + * pass + * + */ + +/* Python wrapper */ +static int __pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_3__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_3__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); + #if CYTHON_ASSUME_SAFE_MACROS + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return -1; + #endif + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { + __Pyx_RaiseArgtupleInvalid("__init__", 1, 0, 0, __pyx_nargs); return -1;} + if (unlikely(__pyx_kwds) && __Pyx_NumKwargs_VARARGS(__pyx_kwds) && unlikely(!__Pyx_CheckKeywordStrings(__pyx_kwds, "__init__", 0))) return -1; + __pyx_r = __pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_2__init__(((struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_2__init__(CYTHON_UNUSED struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *__pyx_v_self) { + int __pyx_r; + + /* function exit code */ + __pyx_r = 0; + return __pyx_r; +} + +/* "curated_tokenizers/_spp.pyx":11 + * pass + * + * def __len__(self): # <<<<<<<<<<<<<< + * _check_status(deref(self.spp).status()) + * return deref(self.spp).GetPieceSize() + */ + +/* Python wrapper */ +static Py_ssize_t __pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_5__len__(PyObject *__pyx_v_self); /*proto*/ +static Py_ssize_t __pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_5__len__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + Py_ssize_t __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__len__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_4__len__(((struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static Py_ssize_t __pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_4__len__(struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *__pyx_v_self) { + Py_ssize_t __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__len__", 1); + + /* "curated_tokenizers/_spp.pyx":12 + * + * def __len__(self): + * _check_status(deref(self.spp).status()) # <<<<<<<<<<<<<< + * return deref(self.spp).GetPieceSize() + * + */ + __pyx_t_1 = __pyx_f_18curated_tokenizers_4_spp__check_status((*__pyx_v_self->spp).status()); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 12, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "curated_tokenizers/_spp.pyx":13 + * def __len__(self): + * _check_status(deref(self.spp).status()) + * return deref(self.spp).GetPieceSize() # <<<<<<<<<<<<<< + * + * def __copy__(self): + */ + __pyx_r = (*__pyx_v_self->spp).GetPieceSize(); + goto __pyx_L0; + + /* "curated_tokenizers/_spp.pyx":11 + * pass + * + * def __len__(self): # <<<<<<<<<<<<<< + * _check_status(deref(self.spp).status()) + * return deref(self.spp).GetPieceSize() + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("curated_tokenizers._spp.SentencePieceProcessor.__len__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_spp.pyx":15 + * return deref(self.spp).GetPieceSize() + * + * def __copy__(self): # <<<<<<<<<<<<<< + * return SentencePieceProcessor.from_protobuf(self.to_protobuf()) + * + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_7__copy__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_6__copy__, "SentencePieceProcessor.__copy__(self)"); +static PyMethodDef __pyx_mdef_18curated_tokenizers_4_spp_22SentencePieceProcessor_7__copy__ = {"__copy__", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_7__copy__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_6__copy__}; +static PyObject *__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_7__copy__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__copy__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_MACROS + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { + __Pyx_RaiseArgtupleInvalid("__copy__", 1, 0, 0, __pyx_nargs); return NULL;} + if (unlikely(__pyx_kwds) && __Pyx_NumKwargs_FASTCALL(__pyx_kwds) && unlikely(!__Pyx_CheckKeywordStrings(__pyx_kwds, "__copy__", 0))) return NULL; + __pyx_r = __pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_6__copy__(((struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_6__copy__(struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + int __pyx_t_6; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__copy__", 1); + + /* "curated_tokenizers/_spp.pyx":16 + * + * def __copy__(self): + * return SentencePieceProcessor.from_protobuf(self.to_protobuf()) # <<<<<<<<<<<<<< + * + * def __deepcopy__(self, memo): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor), __pyx_n_s_from_protobuf); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 16, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_to_protobuf); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 16, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = NULL; + __pyx_t_6 = 0; + #if CYTHON_UNPACK_METHODS + if (likely(PyMethod_Check(__pyx_t_4))) { + __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_4); + if (likely(__pyx_t_5)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); + __Pyx_INCREF(__pyx_t_5); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_4, function); + __pyx_t_6 = 1; + } + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_5, NULL}; + __pyx_t_3 = __Pyx_PyObject_FastCall(__pyx_t_4, __pyx_callargs+1-__pyx_t_6, 0+__pyx_t_6); + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 16, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + } + __pyx_t_4 = NULL; + __pyx_t_6 = 0; + #if CYTHON_UNPACK_METHODS + if (likely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_2); + if (likely(__pyx_t_4)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_4); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_2, function); + __pyx_t_6 = 1; + } + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_t_3}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_2, __pyx_callargs+1-__pyx_t_6, 1+__pyx_t_6); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 16, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "curated_tokenizers/_spp.pyx":15 + * return deref(self.spp).GetPieceSize() + * + * def __copy__(self): # <<<<<<<<<<<<<< + * return SentencePieceProcessor.from_protobuf(self.to_protobuf()) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("curated_tokenizers._spp.SentencePieceProcessor.__copy__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_spp.pyx":18 + * return SentencePieceProcessor.from_protobuf(self.to_protobuf()) + * + * def __deepcopy__(self, memo): # <<<<<<<<<<<<<< + * result = SentencePieceProcessor.from_protobuf(self.to_protobuf()) + * memo[id(self)] = result + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_9__deepcopy__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_8__deepcopy__, "SentencePieceProcessor.__deepcopy__(self, memo)"); +static PyMethodDef __pyx_mdef_18curated_tokenizers_4_spp_22SentencePieceProcessor_9__deepcopy__ = {"__deepcopy__", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_9__deepcopy__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_8__deepcopy__}; +static PyObject *__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_9__deepcopy__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_memo = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__deepcopy__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_MACROS + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject **__pyx_pyargnames[] = {&__pyx_n_s_memo,0}; + if (__pyx_kwds) { + Py_ssize_t kw_args; + switch (__pyx_nargs) { + case 1: values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = __Pyx_NumKwargs_FASTCALL(__pyx_kwds); + switch (__pyx_nargs) { + case 0: + if (likely((values[0] = __Pyx_GetKwValue_FASTCALL(__pyx_kwds, __pyx_kwvalues, __pyx_n_s_memo)) != 0)) { + (void)__Pyx_Arg_NewRef_FASTCALL(values[0]); + kw_args--; + } + else if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 18, __pyx_L3_error) + else goto __pyx_L5_argtuple_error; + } + if (unlikely(kw_args > 0)) { + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values + 0, kwd_pos_args, "__deepcopy__") < 0)) __PYX_ERR(0, 18, __pyx_L3_error) + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + } + __pyx_v_memo = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__deepcopy__", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 18, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_AddTraceback("curated_tokenizers._spp.SentencePieceProcessor.__deepcopy__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_8__deepcopy__(((struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *)__pyx_v_self), __pyx_v_memo); + + /* function exit code */ + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_8__deepcopy__(struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *__pyx_v_self, PyObject *__pyx_v_memo) { + PyObject *__pyx_v_result = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + int __pyx_t_6; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__deepcopy__", 1); + + /* "curated_tokenizers/_spp.pyx":19 + * + * def __deepcopy__(self, memo): + * result = SentencePieceProcessor.from_protobuf(self.to_protobuf()) # <<<<<<<<<<<<<< + * memo[id(self)] = result + * return result + */ + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor), __pyx_n_s_from_protobuf); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 19, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_to_protobuf); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 19, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = NULL; + __pyx_t_6 = 0; + #if CYTHON_UNPACK_METHODS + if (likely(PyMethod_Check(__pyx_t_4))) { + __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_4); + if (likely(__pyx_t_5)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); + __Pyx_INCREF(__pyx_t_5); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_4, function); + __pyx_t_6 = 1; + } + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_5, NULL}; + __pyx_t_3 = __Pyx_PyObject_FastCall(__pyx_t_4, __pyx_callargs+1-__pyx_t_6, 0+__pyx_t_6); + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 19, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + } + __pyx_t_4 = NULL; + __pyx_t_6 = 0; + #if CYTHON_UNPACK_METHODS + if (likely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_2); + if (likely(__pyx_t_4)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_4); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_2, function); + __pyx_t_6 = 1; + } + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_t_3}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_2, __pyx_callargs+1-__pyx_t_6, 1+__pyx_t_6); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 19, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } + __pyx_v_result = __pyx_t_1; + __pyx_t_1 = 0; + + /* "curated_tokenizers/_spp.pyx":20 + * def __deepcopy__(self, memo): + * result = SentencePieceProcessor.from_protobuf(self.to_protobuf()) + * memo[id(self)] = result # <<<<<<<<<<<<<< + * return result + * + */ + __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_builtin_id, ((PyObject *)__pyx_v_self)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 20, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + if (unlikely((PyObject_SetItem(__pyx_v_memo, __pyx_t_1, __pyx_v_result) < 0))) __PYX_ERR(0, 20, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "curated_tokenizers/_spp.pyx":21 + * result = SentencePieceProcessor.from_protobuf(self.to_protobuf()) + * memo[id(self)] = result + * return result # <<<<<<<<<<<<<< + * + * @staticmethod + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_result); + __pyx_r = __pyx_v_result; + goto __pyx_L0; + + /* "curated_tokenizers/_spp.pyx":18 + * return SentencePieceProcessor.from_protobuf(self.to_protobuf()) + * + * def __deepcopy__(self, memo): # <<<<<<<<<<<<<< + * result = SentencePieceProcessor.from_protobuf(self.to_protobuf()) + * memo[id(self)] = result + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("curated_tokenizers._spp.SentencePieceProcessor.__deepcopy__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_spp.pyx":23 + * return result + * + * @staticmethod # <<<<<<<<<<<<<< + * def from_file(str filename): + * """ + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_11from_file(CYTHON_UNUSED PyObject *__pyx_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_10from_file, "SentencePieceProcessor.from_file(str filename)\n\n Constructs a SentencePieceProcessor by loading a serialized model from\n disk.\n\n filename (str): Path to model.\n "); +static PyMethodDef __pyx_mdef_18curated_tokenizers_4_spp_22SentencePieceProcessor_11from_file = {"from_file", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_11from_file, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_10from_file}; +static PyObject *__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_11from_file(CYTHON_UNUSED PyObject *__pyx_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_filename = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("from_file (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_MACROS + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject **__pyx_pyargnames[] = {&__pyx_n_s_filename,0}; + if (__pyx_kwds) { + Py_ssize_t kw_args; + switch (__pyx_nargs) { + case 1: values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = __Pyx_NumKwargs_FASTCALL(__pyx_kwds); + switch (__pyx_nargs) { + case 0: + if (likely((values[0] = __Pyx_GetKwValue_FASTCALL(__pyx_kwds, __pyx_kwvalues, __pyx_n_s_filename)) != 0)) { + (void)__Pyx_Arg_NewRef_FASTCALL(values[0]); + kw_args--; + } + else if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 23, __pyx_L3_error) + else goto __pyx_L5_argtuple_error; + } + if (unlikely(kw_args > 0)) { + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values + 0, kwd_pos_args, "from_file") < 0)) __PYX_ERR(0, 23, __pyx_L3_error) + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + } + __pyx_v_filename = ((PyObject*)values[0]); + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("from_file", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 23, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_AddTraceback("curated_tokenizers._spp.SentencePieceProcessor.from_file", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_filename), (&PyString_Type), 1, "filename", 1))) __PYX_ERR(0, 24, __pyx_L1_error) + __pyx_r = __pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_10from_file(__pyx_v_filename); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + __pyx_L0:; + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_10from_file(PyObject *__pyx_v_filename) { + struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *__pyx_v_processor = 0; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + std::string __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("from_file", 1); + + /* "curated_tokenizers/_spp.pyx":31 + * filename (str): Path to model. + * """ + * cdef SentencePieceProcessor processor = SentencePieceProcessor.__new__(SentencePieceProcessor) # <<<<<<<<<<<<<< + * _check_status(deref(processor.spp).Load(filename.encode("utf-8"))) + * return processor + */ + __pyx_t_1 = ((PyObject *)__pyx_tp_new_18curated_tokenizers_4_spp_SentencePieceProcessor(((PyTypeObject *)__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor), __pyx_empty_tuple, NULL)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 31, __pyx_L1_error) + __Pyx_GOTREF((PyObject *)__pyx_t_1); + __pyx_v_processor = ((struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "curated_tokenizers/_spp.pyx":32 + * """ + * cdef SentencePieceProcessor processor = SentencePieceProcessor.__new__(SentencePieceProcessor) + * _check_status(deref(processor.spp).Load(filename.encode("utf-8"))) # <<<<<<<<<<<<<< + * return processor + * + */ + __pyx_t_1 = __Pyx_CallUnboundCMethod1(&__pyx_umethod_PyString_Type_encode, __pyx_v_filename, __pyx_kp_s_utf_8); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 32, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __pyx_convert_string_from_py_std__in_string(__pyx_t_1); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 32, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __pyx_f_18curated_tokenizers_4_spp__check_status((*__pyx_v_processor->spp).Load(__pyx_t_2)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 32, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "curated_tokenizers/_spp.pyx":33 + * cdef SentencePieceProcessor processor = SentencePieceProcessor.__new__(SentencePieceProcessor) + * _check_status(deref(processor.spp).Load(filename.encode("utf-8"))) + * return processor # <<<<<<<<<<<<<< + * + * @staticmethod + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF((PyObject *)__pyx_v_processor); + __pyx_r = ((PyObject *)__pyx_v_processor); + goto __pyx_L0; + + /* "curated_tokenizers/_spp.pyx":23 + * return result + * + * @staticmethod # <<<<<<<<<<<<<< + * def from_file(str filename): + * """ + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("curated_tokenizers._spp.SentencePieceProcessor.from_file", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_processor); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_spp.pyx":35 + * return processor + * + * @staticmethod # <<<<<<<<<<<<<< + * def from_protobuf(bytes protobuf): + * """ + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_13from_protobuf(CYTHON_UNUSED PyObject *__pyx_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_12from_protobuf, "SentencePieceProcessor.from_protobuf(bytes protobuf)\n\n Constructs a SentencePieceProcessor by loading a serialized model from\n a protocol buffer.\n\n protobuf (bytes): Byte array representing the model's serialized\n protocol buffer.\n "); +static PyMethodDef __pyx_mdef_18curated_tokenizers_4_spp_22SentencePieceProcessor_13from_protobuf = {"from_protobuf", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_13from_protobuf, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_12from_protobuf}; +static PyObject *__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_13from_protobuf(CYTHON_UNUSED PyObject *__pyx_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_protobuf = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("from_protobuf (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_MACROS + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject **__pyx_pyargnames[] = {&__pyx_n_s_protobuf,0}; + if (__pyx_kwds) { + Py_ssize_t kw_args; + switch (__pyx_nargs) { + case 1: values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = __Pyx_NumKwargs_FASTCALL(__pyx_kwds); + switch (__pyx_nargs) { + case 0: + if (likely((values[0] = __Pyx_GetKwValue_FASTCALL(__pyx_kwds, __pyx_kwvalues, __pyx_n_s_protobuf)) != 0)) { + (void)__Pyx_Arg_NewRef_FASTCALL(values[0]); + kw_args--; + } + else if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 35, __pyx_L3_error) + else goto __pyx_L5_argtuple_error; + } + if (unlikely(kw_args > 0)) { + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values + 0, kwd_pos_args, "from_protobuf") < 0)) __PYX_ERR(0, 35, __pyx_L3_error) + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + } + __pyx_v_protobuf = ((PyObject*)values[0]); + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("from_protobuf", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 35, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_AddTraceback("curated_tokenizers._spp.SentencePieceProcessor.from_protobuf", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_protobuf), (&PyBytes_Type), 1, "protobuf", 1))) __PYX_ERR(0, 36, __pyx_L1_error) + __pyx_r = __pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_12from_protobuf(__pyx_v_protobuf); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + __pyx_L0:; + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_12from_protobuf(PyObject *__pyx_v_protobuf) { + struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *__pyx_v_processor = 0; + absl::string_view __pyx_v_protobuf_view; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + Py_ssize_t __pyx_t_2; + int __pyx_t_3; + char const *__pyx_t_4; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("from_protobuf", 1); + + /* "curated_tokenizers/_spp.pyx":44 + * protocol buffer. + * """ + * cdef SentencePieceProcessor processor = SentencePieceProcessor.__new__(SentencePieceProcessor) # <<<<<<<<<<<<<< + * if len(protobuf) == 0: + * # SentencePiece returns an empty protobuf for uninitialized models. + */ + __pyx_t_1 = ((PyObject *)__pyx_tp_new_18curated_tokenizers_4_spp_SentencePieceProcessor(((PyTypeObject *)__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor), __pyx_empty_tuple, NULL)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 44, __pyx_L1_error) + __Pyx_GOTREF((PyObject *)__pyx_t_1); + __pyx_v_processor = ((struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "curated_tokenizers/_spp.pyx":45 + * """ + * cdef SentencePieceProcessor processor = SentencePieceProcessor.__new__(SentencePieceProcessor) + * if len(protobuf) == 0: # <<<<<<<<<<<<<< + * # SentencePiece returns an empty protobuf for uninitialized models. + * return processor + */ + if (unlikely(__pyx_v_protobuf == Py_None)) { + PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); + __PYX_ERR(0, 45, __pyx_L1_error) + } + __pyx_t_2 = __Pyx_PyBytes_GET_SIZE(__pyx_v_protobuf); if (unlikely(__pyx_t_2 == ((Py_ssize_t)-1))) __PYX_ERR(0, 45, __pyx_L1_error) + __pyx_t_3 = (__pyx_t_2 == 0); + if (__pyx_t_3) { + + /* "curated_tokenizers/_spp.pyx":47 + * if len(protobuf) == 0: + * # SentencePiece returns an empty protobuf for uninitialized models. + * return processor # <<<<<<<<<<<<<< + * cdef string_view protobuf_view = string_view(protobuf, len(protobuf)) + * _check_status(deref(processor.spp).LoadFromSerializedProto(protobuf_view)) + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF((PyObject *)__pyx_v_processor); + __pyx_r = ((PyObject *)__pyx_v_processor); + goto __pyx_L0; + + /* "curated_tokenizers/_spp.pyx":45 + * """ + * cdef SentencePieceProcessor processor = SentencePieceProcessor.__new__(SentencePieceProcessor) + * if len(protobuf) == 0: # <<<<<<<<<<<<<< + * # SentencePiece returns an empty protobuf for uninitialized models. + * return processor + */ + } + + /* "curated_tokenizers/_spp.pyx":48 + * # SentencePiece returns an empty protobuf for uninitialized models. + * return processor + * cdef string_view protobuf_view = string_view(protobuf, len(protobuf)) # <<<<<<<<<<<<<< + * _check_status(deref(processor.spp).LoadFromSerializedProto(protobuf_view)) + * return processor + */ + if (unlikely(__pyx_v_protobuf == Py_None)) { + PyErr_SetString(PyExc_TypeError, "expected bytes, NoneType found"); + __PYX_ERR(0, 48, __pyx_L1_error) + } + __pyx_t_4 = __Pyx_PyBytes_AsString(__pyx_v_protobuf); if (unlikely((!__pyx_t_4) && PyErr_Occurred())) __PYX_ERR(0, 48, __pyx_L1_error) + if (unlikely(__pyx_v_protobuf == Py_None)) { + PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); + __PYX_ERR(0, 48, __pyx_L1_error) + } + __pyx_t_2 = __Pyx_PyBytes_GET_SIZE(__pyx_v_protobuf); if (unlikely(__pyx_t_2 == ((Py_ssize_t)-1))) __PYX_ERR(0, 48, __pyx_L1_error) + __pyx_v_protobuf_view = absl::string_view(__pyx_t_4, __pyx_t_2); + + /* "curated_tokenizers/_spp.pyx":49 + * return processor + * cdef string_view protobuf_view = string_view(protobuf, len(protobuf)) + * _check_status(deref(processor.spp).LoadFromSerializedProto(protobuf_view)) # <<<<<<<<<<<<<< + * return processor + * + */ + __pyx_t_1 = __pyx_f_18curated_tokenizers_4_spp__check_status((*__pyx_v_processor->spp).LoadFromSerializedProto(__pyx_v_protobuf_view)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 49, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "curated_tokenizers/_spp.pyx":50 + * cdef string_view protobuf_view = string_view(protobuf, len(protobuf)) + * _check_status(deref(processor.spp).LoadFromSerializedProto(protobuf_view)) + * return processor # <<<<<<<<<<<<<< + * + * def to_protobuf(self) -> bytes: + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF((PyObject *)__pyx_v_processor); + __pyx_r = ((PyObject *)__pyx_v_processor); + goto __pyx_L0; + + /* "curated_tokenizers/_spp.pyx":35 + * return processor + * + * @staticmethod # <<<<<<<<<<<<<< + * def from_protobuf(bytes protobuf): + * """ + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("curated_tokenizers._spp.SentencePieceProcessor.from_protobuf", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_processor); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_spp.pyx":52 + * return processor + * + * def to_protobuf(self) -> bytes: # <<<<<<<<<<<<<< + * """ + * Serializes the SentencePieceProcessor to a protocol buffer. + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_15to_protobuf(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_14to_protobuf, "SentencePieceProcessor.to_protobuf(self) -> bytes\n\n Serializes the SentencePieceProcessor to a protocol buffer.\n\n RETURNS (bytes): Byte array representing the model's serialized\n protocol buffer.\n "); +static PyMethodDef __pyx_mdef_18curated_tokenizers_4_spp_22SentencePieceProcessor_15to_protobuf = {"to_protobuf", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_15to_protobuf, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_14to_protobuf}; +static PyObject *__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_15to_protobuf(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("to_protobuf (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_MACROS + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { + __Pyx_RaiseArgtupleInvalid("to_protobuf", 1, 0, 0, __pyx_nargs); return NULL;} + if (unlikely(__pyx_kwds) && __Pyx_NumKwargs_FASTCALL(__pyx_kwds) && unlikely(!__Pyx_CheckKeywordStrings(__pyx_kwds, "to_protobuf", 0))) return NULL; + __pyx_r = __pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_14to_protobuf(((struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_14to_protobuf(struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *__pyx_v_self) { + std::string __pyx_v_serialized; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("to_protobuf", 1); + + /* "curated_tokenizers/_spp.pyx":59 + * protocol buffer. + * """ + * cdef string serialized = deref(self.spp).serialized_model_proto() # <<<<<<<<<<<<<< + * return bytes(serialized) + * + */ + __pyx_v_serialized = (*__pyx_v_self->spp).serialized_model_proto(); + + /* "curated_tokenizers/_spp.pyx":60 + * """ + * cdef string serialized = deref(self.spp).serialized_model_proto() + * return bytes(serialized) # <<<<<<<<<<<<<< + * + * def decode_from_ids(self, list ids) -> str: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __pyx_convert_PyBytes_string_to_py_std__in_string(__pyx_v_serialized); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 60, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_CallOneArg(((PyObject *)(&PyBytes_Type)), __pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 60, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "curated_tokenizers/_spp.pyx":52 + * return processor + * + * def to_protobuf(self) -> bytes: # <<<<<<<<<<<<<< + * """ + * Serializes the SentencePieceProcessor to a protocol buffer. + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("curated_tokenizers._spp.SentencePieceProcessor.to_protobuf", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_spp.pyx":62 + * return bytes(serialized) + * + * def decode_from_ids(self, list ids) -> str: # <<<<<<<<<<<<<< + * """ + * Decodes piece indentifiers to a string. Raises a `ValueError` if the + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_17decode_from_ids(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_16decode_from_ids, "SentencePieceProcessor.decode_from_ids(self, list ids) -> str\n\n Decodes piece indentifiers to a string. Raises a `ValueError` if the\n list elements are not integers.\n\n ids (List[int]): Piece IDs.\n RETURNS (str): Decoded string.\n "); +static PyMethodDef __pyx_mdef_18curated_tokenizers_4_spp_22SentencePieceProcessor_17decode_from_ids = {"decode_from_ids", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_17decode_from_ids, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_16decode_from_ids}; +static PyObject *__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_17decode_from_ids(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_ids = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("decode_from_ids (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_MACROS + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject **__pyx_pyargnames[] = {&__pyx_n_s_ids,0}; + if (__pyx_kwds) { + Py_ssize_t kw_args; + switch (__pyx_nargs) { + case 1: values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = __Pyx_NumKwargs_FASTCALL(__pyx_kwds); + switch (__pyx_nargs) { + case 0: + if (likely((values[0] = __Pyx_GetKwValue_FASTCALL(__pyx_kwds, __pyx_kwvalues, __pyx_n_s_ids)) != 0)) { + (void)__Pyx_Arg_NewRef_FASTCALL(values[0]); + kw_args--; + } + else if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 62, __pyx_L3_error) + else goto __pyx_L5_argtuple_error; + } + if (unlikely(kw_args > 0)) { + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values + 0, kwd_pos_args, "decode_from_ids") < 0)) __PYX_ERR(0, 62, __pyx_L3_error) + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + } + __pyx_v_ids = ((PyObject*)values[0]); + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("decode_from_ids", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 62, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_AddTraceback("curated_tokenizers._spp.SentencePieceProcessor.decode_from_ids", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_ids), (&PyList_Type), 1, "ids", 1))) __PYX_ERR(0, 62, __pyx_L1_error) + __pyx_r = __pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_16decode_from_ids(((struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *)__pyx_v_self), __pyx_v_ids); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + __pyx_L0:; + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_16decode_from_ids(struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *__pyx_v_self, PyObject *__pyx_v_ids) { + std::vector __pyx_v_c_ids; + PyObject *__pyx_v_piece_id = NULL; + std::string __pyx_v_output; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + Py_ssize_t __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + int __pyx_t_4; + int __pyx_t_5; + int __pyx_t_6; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("decode_from_ids", 1); + + /* "curated_tokenizers/_spp.pyx":71 + * """ + * cdef vector[int] c_ids + * for piece_id in ids: # <<<<<<<<<<<<<< + * if not isinstance(piece_id, int): + * raise TypeError("Pieces must be of type `int` when decoding from ids") + */ + if (unlikely(__pyx_v_ids == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); + __PYX_ERR(0, 71, __pyx_L1_error) + } + __pyx_t_1 = __pyx_v_ids; __Pyx_INCREF(__pyx_t_1); + __pyx_t_2 = 0; + for (;;) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_1); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 71, __pyx_L1_error) + #endif + if (__pyx_t_2 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_3 = PyList_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely((0 < 0))) __PYX_ERR(0, 71, __pyx_L1_error) + #else + __pyx_t_3 = __Pyx_PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 71, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + #endif + __Pyx_XDECREF_SET(__pyx_v_piece_id, __pyx_t_3); + __pyx_t_3 = 0; + + /* "curated_tokenizers/_spp.pyx":72 + * cdef vector[int] c_ids + * for piece_id in ids: + * if not isinstance(piece_id, int): # <<<<<<<<<<<<<< + * raise TypeError("Pieces must be of type `int` when decoding from ids") + * c_ids.push_back(piece_id) + */ + __pyx_t_4 = PyInt_Check(__pyx_v_piece_id); + __pyx_t_5 = (!__pyx_t_4); + if (unlikely(__pyx_t_5)) { + + /* "curated_tokenizers/_spp.pyx":73 + * for piece_id in ids: + * if not isinstance(piece_id, int): + * raise TypeError("Pieces must be of type `int` when decoding from ids") # <<<<<<<<<<<<<< + * c_ids.push_back(piece_id) + * cdef string output + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple_, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 73, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __PYX_ERR(0, 73, __pyx_L1_error) + + /* "curated_tokenizers/_spp.pyx":72 + * cdef vector[int] c_ids + * for piece_id in ids: + * if not isinstance(piece_id, int): # <<<<<<<<<<<<<< + * raise TypeError("Pieces must be of type `int` when decoding from ids") + * c_ids.push_back(piece_id) + */ + } + + /* "curated_tokenizers/_spp.pyx":74 + * if not isinstance(piece_id, int): + * raise TypeError("Pieces must be of type `int` when decoding from ids") + * c_ids.push_back(piece_id) # <<<<<<<<<<<<<< + * cdef string output + * _check_status(deref(self.spp).Decode(c_ids, &output)) + */ + __pyx_t_6 = __Pyx_PyInt_As_int(__pyx_v_piece_id); if (unlikely((__pyx_t_6 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 74, __pyx_L1_error) + try { + __pyx_v_c_ids.push_back(__pyx_t_6); + } catch(...) { + __Pyx_CppExn2PyErr(); + __PYX_ERR(0, 74, __pyx_L1_error) + } + + /* "curated_tokenizers/_spp.pyx":71 + * """ + * cdef vector[int] c_ids + * for piece_id in ids: # <<<<<<<<<<<<<< + * if not isinstance(piece_id, int): + * raise TypeError("Pieces must be of type `int` when decoding from ids") + */ + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "curated_tokenizers/_spp.pyx":76 + * c_ids.push_back(piece_id) + * cdef string output + * _check_status(deref(self.spp).Decode(c_ids, &output)) # <<<<<<<<<<<<<< + * return output.decode("utf-8") + * + */ + __pyx_t_1 = __pyx_f_18curated_tokenizers_4_spp__check_status((*__pyx_v_self->spp).Decode(__pyx_v_c_ids, (&__pyx_v_output))); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 76, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "curated_tokenizers/_spp.pyx":77 + * cdef string output + * _check_status(deref(self.spp).Decode(c_ids, &output)) + * return output.decode("utf-8") # <<<<<<<<<<<<<< + * + * def decode_from_pieces(self, list pieces) -> str: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_decode_cpp_string(__pyx_v_output, 0, PY_SSIZE_T_MAX, NULL, NULL, PyUnicode_DecodeUTF8); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 77, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "curated_tokenizers/_spp.pyx":62 + * return bytes(serialized) + * + * def decode_from_ids(self, list ids) -> str: # <<<<<<<<<<<<<< + * """ + * Decodes piece indentifiers to a string. Raises a `ValueError` if the + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("curated_tokenizers._spp.SentencePieceProcessor.decode_from_ids", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_piece_id); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_spp.pyx":79 + * return output.decode("utf-8") + * + * def decode_from_pieces(self, list pieces) -> str: # <<<<<<<<<<<<<< + * """ + * Decodes piece tokens to a string. Raises a `ValueError` if the + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_19decode_from_pieces(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_18decode_from_pieces, "SentencePieceProcessor.decode_from_pieces(self, list pieces) -> str\n\n Decodes piece tokens to a string. Raises a `ValueError` if the\n list elements are not strings.\n\n ids (List[str]): Piece tokens.\n RETURNS (str): Decoded string.\n "); +static PyMethodDef __pyx_mdef_18curated_tokenizers_4_spp_22SentencePieceProcessor_19decode_from_pieces = {"decode_from_pieces", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_19decode_from_pieces, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_18decode_from_pieces}; +static PyObject *__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_19decode_from_pieces(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_pieces = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("decode_from_pieces (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_MACROS + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject **__pyx_pyargnames[] = {&__pyx_n_s_pieces,0}; + if (__pyx_kwds) { + Py_ssize_t kw_args; + switch (__pyx_nargs) { + case 1: values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = __Pyx_NumKwargs_FASTCALL(__pyx_kwds); + switch (__pyx_nargs) { + case 0: + if (likely((values[0] = __Pyx_GetKwValue_FASTCALL(__pyx_kwds, __pyx_kwvalues, __pyx_n_s_pieces)) != 0)) { + (void)__Pyx_Arg_NewRef_FASTCALL(values[0]); + kw_args--; + } + else if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 79, __pyx_L3_error) + else goto __pyx_L5_argtuple_error; + } + if (unlikely(kw_args > 0)) { + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values + 0, kwd_pos_args, "decode_from_pieces") < 0)) __PYX_ERR(0, 79, __pyx_L3_error) + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + } + __pyx_v_pieces = ((PyObject*)values[0]); + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("decode_from_pieces", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 79, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_AddTraceback("curated_tokenizers._spp.SentencePieceProcessor.decode_from_pieces", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_pieces), (&PyList_Type), 1, "pieces", 1))) __PYX_ERR(0, 79, __pyx_L1_error) + __pyx_r = __pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_18decode_from_pieces(((struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *)__pyx_v_self), __pyx_v_pieces); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + __pyx_L0:; + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_18decode_from_pieces(struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *__pyx_v_self, PyObject *__pyx_v_pieces) { + std::vector __pyx_v_c_strings; + PyObject *__pyx_v_piece = NULL; + std::string __pyx_v_output; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + Py_ssize_t __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + int __pyx_t_4; + int __pyx_t_5; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + int __pyx_t_8; + std::string __pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("decode_from_pieces", 1); + + /* "curated_tokenizers/_spp.pyx":88 + * """ + * cdef vector[string] c_strings + * for piece in pieces: # <<<<<<<<<<<<<< + * if not isinstance(piece, str): + * raise TypeError("Pieces must be of type `str` when decoding from pieces") + */ + if (unlikely(__pyx_v_pieces == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); + __PYX_ERR(0, 88, __pyx_L1_error) + } + __pyx_t_1 = __pyx_v_pieces; __Pyx_INCREF(__pyx_t_1); + __pyx_t_2 = 0; + for (;;) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_1); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 88, __pyx_L1_error) + #endif + if (__pyx_t_2 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_3 = PyList_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely((0 < 0))) __PYX_ERR(0, 88, __pyx_L1_error) + #else + __pyx_t_3 = __Pyx_PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 88, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + #endif + __Pyx_XDECREF_SET(__pyx_v_piece, __pyx_t_3); + __pyx_t_3 = 0; + + /* "curated_tokenizers/_spp.pyx":89 + * cdef vector[string] c_strings + * for piece in pieces: + * if not isinstance(piece, str): # <<<<<<<<<<<<<< + * raise TypeError("Pieces must be of type `str` when decoding from pieces") + * c_strings.push_back(piece.encode("utf-8")) + */ + __pyx_t_4 = PyString_Check(__pyx_v_piece); + __pyx_t_5 = (!__pyx_t_4); + if (unlikely(__pyx_t_5)) { + + /* "curated_tokenizers/_spp.pyx":90 + * for piece in pieces: + * if not isinstance(piece, str): + * raise TypeError("Pieces must be of type `str` when decoding from pieces") # <<<<<<<<<<<<<< + * c_strings.push_back(piece.encode("utf-8")) + * cdef string output + */ + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__2, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 90, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __PYX_ERR(0, 90, __pyx_L1_error) + + /* "curated_tokenizers/_spp.pyx":89 + * cdef vector[string] c_strings + * for piece in pieces: + * if not isinstance(piece, str): # <<<<<<<<<<<<<< + * raise TypeError("Pieces must be of type `str` when decoding from pieces") + * c_strings.push_back(piece.encode("utf-8")) + */ + } + + /* "curated_tokenizers/_spp.pyx":91 + * if not isinstance(piece, str): + * raise TypeError("Pieces must be of type `str` when decoding from pieces") + * c_strings.push_back(piece.encode("utf-8")) # <<<<<<<<<<<<<< + * cdef string output + * _check_status(deref(self.spp).Decode(c_strings, &output)) + */ + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_piece, __pyx_n_s_encode); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 91, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = NULL; + __pyx_t_8 = 0; + #if CYTHON_UNPACK_METHODS + if (likely(PyMethod_Check(__pyx_t_6))) { + __pyx_t_7 = PyMethod_GET_SELF(__pyx_t_6); + if (likely(__pyx_t_7)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_6); + __Pyx_INCREF(__pyx_t_7); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_6, function); + __pyx_t_8 = 1; + } + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_7, __pyx_kp_s_utf_8}; + __pyx_t_3 = __Pyx_PyObject_FastCall(__pyx_t_6, __pyx_callargs+1-__pyx_t_8, 1+__pyx_t_8); + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 91, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + } + __pyx_t_9 = __pyx_convert_string_from_py_std__in_string(__pyx_t_3); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 91, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + try { + __pyx_v_c_strings.push_back(__pyx_t_9); + } catch(...) { + __Pyx_CppExn2PyErr(); + __PYX_ERR(0, 91, __pyx_L1_error) + } + + /* "curated_tokenizers/_spp.pyx":88 + * """ + * cdef vector[string] c_strings + * for piece in pieces: # <<<<<<<<<<<<<< + * if not isinstance(piece, str): + * raise TypeError("Pieces must be of type `str` when decoding from pieces") + */ + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "curated_tokenizers/_spp.pyx":93 + * c_strings.push_back(piece.encode("utf-8")) + * cdef string output + * _check_status(deref(self.spp).Decode(c_strings, &output)) # <<<<<<<<<<<<<< + * return output.decode("utf-8") + * + */ + __pyx_t_1 = __pyx_f_18curated_tokenizers_4_spp__check_status((*__pyx_v_self->spp).Decode(__pyx_v_c_strings, (&__pyx_v_output))); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 93, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "curated_tokenizers/_spp.pyx":94 + * cdef string output + * _check_status(deref(self.spp).Decode(c_strings, &output)) + * return output.decode("utf-8") # <<<<<<<<<<<<<< + * + * def encode(self, str sentence) -> Tuple[List[int], List[str]]: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_decode_cpp_string(__pyx_v_output, 0, PY_SSIZE_T_MAX, NULL, NULL, PyUnicode_DecodeUTF8); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 94, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "curated_tokenizers/_spp.pyx":79 + * return output.decode("utf-8") + * + * def decode_from_pieces(self, list pieces) -> str: # <<<<<<<<<<<<<< + * """ + * Decodes piece tokens to a string. Raises a `ValueError` if the + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_AddTraceback("curated_tokenizers._spp.SentencePieceProcessor.decode_from_pieces", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_piece); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_spp.pyx":96 + * return output.decode("utf-8") + * + * def encode(self, str sentence) -> Tuple[List[int], List[str]]: # <<<<<<<<<<<<<< + * """ + * Encodes a string to piece indentifiers and piece tokens. + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_21encode(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_20encode, "SentencePieceProcessor.encode(self, str sentence) -> Tuple[List[int], List[str]]\n\n Encodes a string to piece indentifiers and piece tokens.\n\n sentence (str): Text to encode.\n RETURNS (Tuple[List[int], List[str]]): Piece IDs and piece tokens\n corresponding to the input text.\n "); +static PyMethodDef __pyx_mdef_18curated_tokenizers_4_spp_22SentencePieceProcessor_21encode = {"encode", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_21encode, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_20encode}; +static PyObject *__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_21encode(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_sentence = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("encode (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_MACROS + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject **__pyx_pyargnames[] = {&__pyx_n_s_sentence,0}; + if (__pyx_kwds) { + Py_ssize_t kw_args; + switch (__pyx_nargs) { + case 1: values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = __Pyx_NumKwargs_FASTCALL(__pyx_kwds); + switch (__pyx_nargs) { + case 0: + if (likely((values[0] = __Pyx_GetKwValue_FASTCALL(__pyx_kwds, __pyx_kwvalues, __pyx_n_s_sentence)) != 0)) { + (void)__Pyx_Arg_NewRef_FASTCALL(values[0]); + kw_args--; + } + else if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 96, __pyx_L3_error) + else goto __pyx_L5_argtuple_error; + } + if (unlikely(kw_args > 0)) { + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values + 0, kwd_pos_args, "encode") < 0)) __PYX_ERR(0, 96, __pyx_L3_error) + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + } + __pyx_v_sentence = ((PyObject*)values[0]); + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("encode", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 96, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_AddTraceback("curated_tokenizers._spp.SentencePieceProcessor.encode", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_sentence), (&PyString_Type), 1, "sentence", 1))) __PYX_ERR(0, 96, __pyx_L1_error) + __pyx_r = __pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_20encode(((struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *)__pyx_v_self), __pyx_v_sentence); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + __pyx_L0:; + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_20encode(struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *__pyx_v_self, PyObject *__pyx_v_sentence) { + sentencepiece::SentencePieceText __pyx_v_text; + int __pyx_v_idx; + sentencepiece::SentencePieceText_SentencePiece __pyx_v_piece; + PyObject *__pyx_v_pieces = NULL; + PyObject *__pyx_v_ids = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + sentencepiece::SentencePieceText __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_t_3; + int __pyx_t_4; + int __pyx_t_5; + int __pyx_t_6; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("encode", 1); + + /* "curated_tokenizers/_spp.pyx":104 + * corresponding to the input text. + * """ + * cdef SentencePieceText text = self._encode(sentence) # <<<<<<<<<<<<<< + * + * cdef int idx + */ + __pyx_t_1 = ((struct __pyx_vtabstruct_18curated_tokenizers_4_spp_SentencePieceProcessor *)__pyx_v_self->__pyx_vtab)->_encode(__pyx_v_self, __pyx_v_sentence); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 104, __pyx_L1_error) + __pyx_v_text = __PYX_STD_MOVE_IF_SUPPORTED(__pyx_t_1); + + /* "curated_tokenizers/_spp.pyx":108 + * cdef int idx + * cdef SentencePieceText_SentencePiece piece + * pieces = [] # <<<<<<<<<<<<<< + * ids = [] + * for idx in range(text.pieces_size()): + */ + __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 108, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_v_pieces = ((PyObject*)__pyx_t_2); + __pyx_t_2 = 0; + + /* "curated_tokenizers/_spp.pyx":109 + * cdef SentencePieceText_SentencePiece piece + * pieces = [] + * ids = [] # <<<<<<<<<<<<<< + * for idx in range(text.pieces_size()): + * piece = text.pieces(idx) + */ + __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 109, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_v_ids = ((PyObject*)__pyx_t_2); + __pyx_t_2 = 0; + + /* "curated_tokenizers/_spp.pyx":110 + * pieces = [] + * ids = [] + * for idx in range(text.pieces_size()): # <<<<<<<<<<<<<< + * piece = text.pieces(idx) + * ids.append(piece.id()) + */ + __pyx_t_3 = __pyx_v_text.pieces_size(); + __pyx_t_4 = __pyx_t_3; + for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_4; __pyx_t_5+=1) { + __pyx_v_idx = __pyx_t_5; + + /* "curated_tokenizers/_spp.pyx":111 + * ids = [] + * for idx in range(text.pieces_size()): + * piece = text.pieces(idx) # <<<<<<<<<<<<<< + * ids.append(piece.id()) + * pieces.append(piece.piece().decode("utf-8")) + */ + __pyx_v_piece = __pyx_v_text.pieces(__pyx_v_idx); + + /* "curated_tokenizers/_spp.pyx":112 + * for idx in range(text.pieces_size()): + * piece = text.pieces(idx) + * ids.append(piece.id()) # <<<<<<<<<<<<<< + * pieces.append(piece.piece().decode("utf-8")) + * + */ + __pyx_t_2 = __Pyx_PyInt_From_uint32_t(__pyx_v_piece.id()); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 112, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_6 = __Pyx_PyList_Append(__pyx_v_ids, __pyx_t_2); if (unlikely(__pyx_t_6 == ((int)-1))) __PYX_ERR(0, 112, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "curated_tokenizers/_spp.pyx":113 + * piece = text.pieces(idx) + * ids.append(piece.id()) + * pieces.append(piece.piece().decode("utf-8")) # <<<<<<<<<<<<<< + * + * return ids, pieces + */ + __pyx_t_2 = __Pyx_decode_cpp_string(__pyx_v_piece.piece(), 0, PY_SSIZE_T_MAX, NULL, NULL, PyUnicode_DecodeUTF8); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 113, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_6 = __Pyx_PyList_Append(__pyx_v_pieces, __pyx_t_2); if (unlikely(__pyx_t_6 == ((int)-1))) __PYX_ERR(0, 113, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } + + /* "curated_tokenizers/_spp.pyx":115 + * pieces.append(piece.piece().decode("utf-8")) + * + * return ids, pieces # <<<<<<<<<<<<<< + * + * def encode_as_ids(self, str sentence) -> List[int]: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 115, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_v_ids); + __Pyx_GIVEREF(__pyx_v_ids); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_ids)) __PYX_ERR(0, 115, __pyx_L1_error); + __Pyx_INCREF(__pyx_v_pieces); + __Pyx_GIVEREF(__pyx_v_pieces); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_v_pieces)) __PYX_ERR(0, 115, __pyx_L1_error); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "curated_tokenizers/_spp.pyx":96 + * return output.decode("utf-8") + * + * def encode(self, str sentence) -> Tuple[List[int], List[str]]: # <<<<<<<<<<<<<< + * """ + * Encodes a string to piece indentifiers and piece tokens. + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("curated_tokenizers._spp.SentencePieceProcessor.encode", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_pieces); + __Pyx_XDECREF(__pyx_v_ids); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_spp.pyx":117 + * return ids, pieces + * + * def encode_as_ids(self, str sentence) -> List[int]: # <<<<<<<<<<<<<< + * """ + * Encodes a string to piece indentifiers. + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_23encode_as_ids(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_22encode_as_ids, "SentencePieceProcessor.encode_as_ids(self, str sentence) -> List[int]\n\n Encodes a string to piece indentifiers.\n\n sentence (str): Text to encode.\n RETURNS (List[int]): Piece IDs.\n "); +static PyMethodDef __pyx_mdef_18curated_tokenizers_4_spp_22SentencePieceProcessor_23encode_as_ids = {"encode_as_ids", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_23encode_as_ids, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_22encode_as_ids}; +static PyObject *__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_23encode_as_ids(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_sentence = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("encode_as_ids (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_MACROS + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject **__pyx_pyargnames[] = {&__pyx_n_s_sentence,0}; + if (__pyx_kwds) { + Py_ssize_t kw_args; + switch (__pyx_nargs) { + case 1: values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = __Pyx_NumKwargs_FASTCALL(__pyx_kwds); + switch (__pyx_nargs) { + case 0: + if (likely((values[0] = __Pyx_GetKwValue_FASTCALL(__pyx_kwds, __pyx_kwvalues, __pyx_n_s_sentence)) != 0)) { + (void)__Pyx_Arg_NewRef_FASTCALL(values[0]); + kw_args--; + } + else if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 117, __pyx_L3_error) + else goto __pyx_L5_argtuple_error; + } + if (unlikely(kw_args > 0)) { + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values + 0, kwd_pos_args, "encode_as_ids") < 0)) __PYX_ERR(0, 117, __pyx_L3_error) + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + } + __pyx_v_sentence = ((PyObject*)values[0]); + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("encode_as_ids", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 117, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_AddTraceback("curated_tokenizers._spp.SentencePieceProcessor.encode_as_ids", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_sentence), (&PyString_Type), 1, "sentence", 1))) __PYX_ERR(0, 117, __pyx_L1_error) + __pyx_r = __pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_22encode_as_ids(((struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *)__pyx_v_self), __pyx_v_sentence); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + __pyx_L0:; + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_22encode_as_ids(struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *__pyx_v_self, PyObject *__pyx_v_sentence) { + sentencepiece::SentencePieceText __pyx_v_text; + int __pyx_v_idx; + PyObject *__pyx_v_ids = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + sentencepiece::SentencePieceText __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_t_3; + int __pyx_t_4; + int __pyx_t_5; + int __pyx_t_6; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("encode_as_ids", 1); + + /* "curated_tokenizers/_spp.pyx":124 + * RETURNS (List[int]): Piece IDs. + * """ + * cdef SentencePieceText text = self._encode(sentence) # <<<<<<<<<<<<<< + * + * cdef int idx + */ + __pyx_t_1 = ((struct __pyx_vtabstruct_18curated_tokenizers_4_spp_SentencePieceProcessor *)__pyx_v_self->__pyx_vtab)->_encode(__pyx_v_self, __pyx_v_sentence); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 124, __pyx_L1_error) + __pyx_v_text = __PYX_STD_MOVE_IF_SUPPORTED(__pyx_t_1); + + /* "curated_tokenizers/_spp.pyx":127 + * + * cdef int idx + * ids = [] # <<<<<<<<<<<<<< + * for idx in range(text.pieces_size()): + * ids.append(text.pieces(idx).id()) + */ + __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 127, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_v_ids = ((PyObject*)__pyx_t_2); + __pyx_t_2 = 0; + + /* "curated_tokenizers/_spp.pyx":128 + * cdef int idx + * ids = [] + * for idx in range(text.pieces_size()): # <<<<<<<<<<<<<< + * ids.append(text.pieces(idx).id()) + * + */ + __pyx_t_3 = __pyx_v_text.pieces_size(); + __pyx_t_4 = __pyx_t_3; + for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_4; __pyx_t_5+=1) { + __pyx_v_idx = __pyx_t_5; + + /* "curated_tokenizers/_spp.pyx":129 + * ids = [] + * for idx in range(text.pieces_size()): + * ids.append(text.pieces(idx).id()) # <<<<<<<<<<<<<< + * + * return ids + */ + __pyx_t_2 = __Pyx_PyInt_From_uint32_t(__pyx_v_text.pieces(__pyx_v_idx).id()); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 129, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_6 = __Pyx_PyList_Append(__pyx_v_ids, __pyx_t_2); if (unlikely(__pyx_t_6 == ((int)-1))) __PYX_ERR(0, 129, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } + + /* "curated_tokenizers/_spp.pyx":131 + * ids.append(text.pieces(idx).id()) + * + * return ids # <<<<<<<<<<<<<< + * + * def encode_as_pieces(self, str sentence) -> List[str]: + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_ids); + __pyx_r = __pyx_v_ids; + goto __pyx_L0; + + /* "curated_tokenizers/_spp.pyx":117 + * return ids, pieces + * + * def encode_as_ids(self, str sentence) -> List[int]: # <<<<<<<<<<<<<< + * """ + * Encodes a string to piece indentifiers. + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("curated_tokenizers._spp.SentencePieceProcessor.encode_as_ids", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_ids); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_spp.pyx":133 + * return ids + * + * def encode_as_pieces(self, str sentence) -> List[str]: # <<<<<<<<<<<<<< + * """ + * Encodes a string to piece tokens. + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_25encode_as_pieces(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_24encode_as_pieces, "SentencePieceProcessor.encode_as_pieces(self, str sentence) -> List[str]\n\n Encodes a string to piece tokens.\n\n sentence (str): Text to encode.\n RETURNS (List[str]): Piece tokens.\n "); +static PyMethodDef __pyx_mdef_18curated_tokenizers_4_spp_22SentencePieceProcessor_25encode_as_pieces = {"encode_as_pieces", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_25encode_as_pieces, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_24encode_as_pieces}; +static PyObject *__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_25encode_as_pieces(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_sentence = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("encode_as_pieces (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_MACROS + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject **__pyx_pyargnames[] = {&__pyx_n_s_sentence,0}; + if (__pyx_kwds) { + Py_ssize_t kw_args; + switch (__pyx_nargs) { + case 1: values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = __Pyx_NumKwargs_FASTCALL(__pyx_kwds); + switch (__pyx_nargs) { + case 0: + if (likely((values[0] = __Pyx_GetKwValue_FASTCALL(__pyx_kwds, __pyx_kwvalues, __pyx_n_s_sentence)) != 0)) { + (void)__Pyx_Arg_NewRef_FASTCALL(values[0]); + kw_args--; + } + else if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 133, __pyx_L3_error) + else goto __pyx_L5_argtuple_error; + } + if (unlikely(kw_args > 0)) { + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values + 0, kwd_pos_args, "encode_as_pieces") < 0)) __PYX_ERR(0, 133, __pyx_L3_error) + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + } + __pyx_v_sentence = ((PyObject*)values[0]); + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("encode_as_pieces", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 133, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_AddTraceback("curated_tokenizers._spp.SentencePieceProcessor.encode_as_pieces", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_sentence), (&PyString_Type), 1, "sentence", 1))) __PYX_ERR(0, 133, __pyx_L1_error) + __pyx_r = __pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_24encode_as_pieces(((struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *)__pyx_v_self), __pyx_v_sentence); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + __pyx_L0:; + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_24encode_as_pieces(struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *__pyx_v_self, PyObject *__pyx_v_sentence) { + sentencepiece::SentencePieceText __pyx_v_text; + int __pyx_v_idx; + CYTHON_UNUSED sentencepiece::SentencePieceText_SentencePiece __pyx_v_piece; + PyObject *__pyx_v_pieces = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + sentencepiece::SentencePieceText __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_t_3; + int __pyx_t_4; + int __pyx_t_5; + int __pyx_t_6; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("encode_as_pieces", 1); + + /* "curated_tokenizers/_spp.pyx":140 + * RETURNS (List[str]): Piece tokens. + * """ + * cdef SentencePieceText text = self._encode(sentence) # <<<<<<<<<<<<<< + * + * cdef int idx + */ + __pyx_t_1 = ((struct __pyx_vtabstruct_18curated_tokenizers_4_spp_SentencePieceProcessor *)__pyx_v_self->__pyx_vtab)->_encode(__pyx_v_self, __pyx_v_sentence); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 140, __pyx_L1_error) + __pyx_v_text = __PYX_STD_MOVE_IF_SUPPORTED(__pyx_t_1); + + /* "curated_tokenizers/_spp.pyx":144 + * cdef int idx + * cdef SentencePieceText_SentencePiece piece + * pieces = [] # <<<<<<<<<<<<<< + * for idx in range(text.pieces_size()): + * piece = text.pieces(idx) + */ + __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 144, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_v_pieces = ((PyObject*)__pyx_t_2); + __pyx_t_2 = 0; + + /* "curated_tokenizers/_spp.pyx":145 + * cdef SentencePieceText_SentencePiece piece + * pieces = [] + * for idx in range(text.pieces_size()): # <<<<<<<<<<<<<< + * piece = text.pieces(idx) + * pieces.append(text.pieces(idx).piece().decode("utf-8")) + */ + __pyx_t_3 = __pyx_v_text.pieces_size(); + __pyx_t_4 = __pyx_t_3; + for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_4; __pyx_t_5+=1) { + __pyx_v_idx = __pyx_t_5; + + /* "curated_tokenizers/_spp.pyx":146 + * pieces = [] + * for idx in range(text.pieces_size()): + * piece = text.pieces(idx) # <<<<<<<<<<<<<< + * pieces.append(text.pieces(idx).piece().decode("utf-8")) + * + */ + __pyx_v_piece = __pyx_v_text.pieces(__pyx_v_idx); + + /* "curated_tokenizers/_spp.pyx":147 + * for idx in range(text.pieces_size()): + * piece = text.pieces(idx) + * pieces.append(text.pieces(idx).piece().decode("utf-8")) # <<<<<<<<<<<<<< + * + * return pieces + */ + __pyx_t_2 = __Pyx_decode_cpp_string(__pyx_v_text.pieces(__pyx_v_idx).piece(), 0, PY_SSIZE_T_MAX, NULL, NULL, PyUnicode_DecodeUTF8); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 147, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_6 = __Pyx_PyList_Append(__pyx_v_pieces, __pyx_t_2); if (unlikely(__pyx_t_6 == ((int)-1))) __PYX_ERR(0, 147, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } + + /* "curated_tokenizers/_spp.pyx":149 + * pieces.append(text.pieces(idx).piece().decode("utf-8")) + * + * return pieces # <<<<<<<<<<<<<< + * + * def piece_to_id(self, str piece) -> int: + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_pieces); + __pyx_r = __pyx_v_pieces; + goto __pyx_L0; + + /* "curated_tokenizers/_spp.pyx":133 + * return ids + * + * def encode_as_pieces(self, str sentence) -> List[str]: # <<<<<<<<<<<<<< + * """ + * Encodes a string to piece tokens. + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("curated_tokenizers._spp.SentencePieceProcessor.encode_as_pieces", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_pieces); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_spp.pyx":151 + * return pieces + * + * def piece_to_id(self, str piece) -> int: # <<<<<<<<<<<<<< + * """ + * Returns the piece identifier for a given piece token. Returns the + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_27piece_to_id(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_26piece_to_id, "SentencePieceProcessor.piece_to_id(self, str piece) -> int\n\n Returns the piece identifier for a given piece token. Returns the \n `unk` piece identifier if the piece token is OOV.\n\n piece (str): Piece token.\n RETURNS (int): Piece ID.\n "); +static PyMethodDef __pyx_mdef_18curated_tokenizers_4_spp_22SentencePieceProcessor_27piece_to_id = {"piece_to_id", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_27piece_to_id, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_26piece_to_id}; +static PyObject *__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_27piece_to_id(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_piece = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("piece_to_id (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_MACROS + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject **__pyx_pyargnames[] = {&__pyx_n_s_piece,0}; + if (__pyx_kwds) { + Py_ssize_t kw_args; + switch (__pyx_nargs) { + case 1: values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = __Pyx_NumKwargs_FASTCALL(__pyx_kwds); + switch (__pyx_nargs) { + case 0: + if (likely((values[0] = __Pyx_GetKwValue_FASTCALL(__pyx_kwds, __pyx_kwvalues, __pyx_n_s_piece)) != 0)) { + (void)__Pyx_Arg_NewRef_FASTCALL(values[0]); + kw_args--; + } + else if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 151, __pyx_L3_error) + else goto __pyx_L5_argtuple_error; + } + if (unlikely(kw_args > 0)) { + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values + 0, kwd_pos_args, "piece_to_id") < 0)) __PYX_ERR(0, 151, __pyx_L3_error) + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + } + __pyx_v_piece = ((PyObject*)values[0]); + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("piece_to_id", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 151, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_AddTraceback("curated_tokenizers._spp.SentencePieceProcessor.piece_to_id", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_piece), (&PyString_Type), 1, "piece", 1))) __PYX_ERR(0, 151, __pyx_L1_error) + __pyx_r = __pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_26piece_to_id(((struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *)__pyx_v_self), __pyx_v_piece); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + __pyx_L0:; + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_26piece_to_id(struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *__pyx_v_self, PyObject *__pyx_v_piece) { + PyObject *__pyx_v_piece_bytes = NULL; + absl::string_view __pyx_v_piece_view; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + char const *__pyx_t_2; + Py_ssize_t __pyx_t_3; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("piece_to_id", 1); + + /* "curated_tokenizers/_spp.pyx":159 + * RETURNS (int): Piece ID. + * """ + * piece_bytes = piece.encode("utf8") # <<<<<<<<<<<<<< + * cdef string_view piece_view = string_view(piece_bytes, len(piece_bytes)) + * _check_status(deref(self.spp).status()) + */ + __pyx_t_1 = __Pyx_CallUnboundCMethod1(&__pyx_umethod_PyString_Type_encode, __pyx_v_piece, __pyx_n_s_utf8); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 159, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_piece_bytes = __pyx_t_1; + __pyx_t_1 = 0; + + /* "curated_tokenizers/_spp.pyx":160 + * """ + * piece_bytes = piece.encode("utf8") + * cdef string_view piece_view = string_view(piece_bytes, len(piece_bytes)) # <<<<<<<<<<<<<< + * _check_status(deref(self.spp).status()) + * return deref(self.spp).PieceToId(piece_view) + */ + __pyx_t_2 = __Pyx_PyObject_AsString(__pyx_v_piece_bytes); if (unlikely((!__pyx_t_2) && PyErr_Occurred())) __PYX_ERR(0, 160, __pyx_L1_error) + __pyx_t_3 = PyObject_Length(__pyx_v_piece_bytes); if (unlikely(__pyx_t_3 == ((Py_ssize_t)-1))) __PYX_ERR(0, 160, __pyx_L1_error) + __pyx_v_piece_view = absl::string_view(__pyx_t_2, __pyx_t_3); + + /* "curated_tokenizers/_spp.pyx":161 + * piece_bytes = piece.encode("utf8") + * cdef string_view piece_view = string_view(piece_bytes, len(piece_bytes)) + * _check_status(deref(self.spp).status()) # <<<<<<<<<<<<<< + * return deref(self.spp).PieceToId(piece_view) + * + */ + __pyx_t_1 = __pyx_f_18curated_tokenizers_4_spp__check_status((*__pyx_v_self->spp).status()); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 161, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "curated_tokenizers/_spp.pyx":162 + * cdef string_view piece_view = string_view(piece_bytes, len(piece_bytes)) + * _check_status(deref(self.spp).status()) + * return deref(self.spp).PieceToId(piece_view) # <<<<<<<<<<<<<< + * + * def id_to_piece(self, int piece_id) -> str: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyInt_From_int((*__pyx_v_self->spp).PieceToId(__pyx_v_piece_view)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 162, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "curated_tokenizers/_spp.pyx":151 + * return pieces + * + * def piece_to_id(self, str piece) -> int: # <<<<<<<<<<<<<< + * """ + * Returns the piece identifier for a given piece token. Returns the + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("curated_tokenizers._spp.SentencePieceProcessor.piece_to_id", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_piece_bytes); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_spp.pyx":164 + * return deref(self.spp).PieceToId(piece_view) + * + * def id_to_piece(self, int piece_id) -> str: # <<<<<<<<<<<<<< + * """ + * Returns the piece token for a given piece identifier. Raises a `ValueError` + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_29id_to_piece(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_28id_to_piece, "SentencePieceProcessor.id_to_piece(self, int piece_id) -> str\n\n Returns the piece token for a given piece identifier. Raises a `ValueError` \n if the piece identifier is out-of-bounds.\n\n piece_id (int): Piece ID.\n RETURNS (str): Piece token.\n "); +static PyMethodDef __pyx_mdef_18curated_tokenizers_4_spp_22SentencePieceProcessor_29id_to_piece = {"id_to_piece", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_29id_to_piece, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_28id_to_piece}; +static PyObject *__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_29id_to_piece(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + int __pyx_v_piece_id; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("id_to_piece (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_MACROS + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject **__pyx_pyargnames[] = {&__pyx_n_s_piece_id,0}; + if (__pyx_kwds) { + Py_ssize_t kw_args; + switch (__pyx_nargs) { + case 1: values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = __Pyx_NumKwargs_FASTCALL(__pyx_kwds); + switch (__pyx_nargs) { + case 0: + if (likely((values[0] = __Pyx_GetKwValue_FASTCALL(__pyx_kwds, __pyx_kwvalues, __pyx_n_s_piece_id)) != 0)) { + (void)__Pyx_Arg_NewRef_FASTCALL(values[0]); + kw_args--; + } + else if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 164, __pyx_L3_error) + else goto __pyx_L5_argtuple_error; + } + if (unlikely(kw_args > 0)) { + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values + 0, kwd_pos_args, "id_to_piece") < 0)) __PYX_ERR(0, 164, __pyx_L3_error) + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + } + __pyx_v_piece_id = __Pyx_PyInt_As_int(values[0]); if (unlikely((__pyx_v_piece_id == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 164, __pyx_L3_error) + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("id_to_piece", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 164, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_AddTraceback("curated_tokenizers._spp.SentencePieceProcessor.id_to_piece", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_28id_to_piece(((struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *)__pyx_v_self), __pyx_v_piece_id); + + /* function exit code */ + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_28id_to_piece(struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *__pyx_v_self, int __pyx_v_piece_id) { + int __pyx_v_vocab_size; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + Py_ssize_t __pyx_t_4; + Py_UCS4 __pyx_t_5; + PyObject *__pyx_t_6 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("id_to_piece", 1); + + /* "curated_tokenizers/_spp.pyx":172 + * RETURNS (str): Piece token. + * """ + * _check_status(deref(self.spp).status()) # <<<<<<<<<<<<<< + * cdef int vocab_size = deref(self.spp).GetPieceSize() + * if not 0 <= piece_id < vocab_size: + */ + __pyx_t_1 = __pyx_f_18curated_tokenizers_4_spp__check_status((*__pyx_v_self->spp).status()); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 172, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "curated_tokenizers/_spp.pyx":173 + * """ + * _check_status(deref(self.spp).status()) + * cdef int vocab_size = deref(self.spp).GetPieceSize() # <<<<<<<<<<<<<< + * if not 0 <= piece_id < vocab_size: + * raise ValueError(f"piece ID must be in range [0,{vocab_size}), got {piece_id}") + */ + __pyx_v_vocab_size = (*__pyx_v_self->spp).GetPieceSize(); + + /* "curated_tokenizers/_spp.pyx":174 + * _check_status(deref(self.spp).status()) + * cdef int vocab_size = deref(self.spp).GetPieceSize() + * if not 0 <= piece_id < vocab_size: # <<<<<<<<<<<<<< + * raise ValueError(f"piece ID must be in range [0,{vocab_size}), got {piece_id}") + * return deref(self.spp).IdToPiece(piece_id).decode("utf8") + */ + __pyx_t_2 = (0 <= __pyx_v_piece_id); + if (__pyx_t_2) { + __pyx_t_2 = (__pyx_v_piece_id < __pyx_v_vocab_size); + } + __pyx_t_3 = (!__pyx_t_2); + if (unlikely(__pyx_t_3)) { + + /* "curated_tokenizers/_spp.pyx":175 + * cdef int vocab_size = deref(self.spp).GetPieceSize() + * if not 0 <= piece_id < vocab_size: + * raise ValueError(f"piece ID must be in range [0,{vocab_size}), got {piece_id}") # <<<<<<<<<<<<<< + * return deref(self.spp).IdToPiece(piece_id).decode("utf8") + * + */ + __pyx_t_1 = PyTuple_New(4); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 175, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = 0; + __pyx_t_5 = 127; + __Pyx_INCREF(__pyx_kp_u_piece_ID_must_be_in_range_0); + __pyx_t_4 += 29; + __Pyx_GIVEREF(__pyx_kp_u_piece_ID_must_be_in_range_0); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_kp_u_piece_ID_must_be_in_range_0); + __pyx_t_6 = __Pyx_PyUnicode_From_int(__pyx_v_vocab_size, 0, ' ', 'd'); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 175, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_4 += __Pyx_PyUnicode_GET_LENGTH(__pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_t_6); + __pyx_t_6 = 0; + __Pyx_INCREF(__pyx_kp_u_got); + __pyx_t_4 += 7; + __Pyx_GIVEREF(__pyx_kp_u_got); + PyTuple_SET_ITEM(__pyx_t_1, 2, __pyx_kp_u_got); + __pyx_t_6 = __Pyx_PyUnicode_From_int(__pyx_v_piece_id, 0, ' ', 'd'); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 175, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_4 += __Pyx_PyUnicode_GET_LENGTH(__pyx_t_6); + __Pyx_GIVEREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_1, 3, __pyx_t_6); + __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyUnicode_Join(__pyx_t_1, 4, __pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 175, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_builtin_ValueError, __pyx_t_6); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 175, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(0, 175, __pyx_L1_error) + + /* "curated_tokenizers/_spp.pyx":174 + * _check_status(deref(self.spp).status()) + * cdef int vocab_size = deref(self.spp).GetPieceSize() + * if not 0 <= piece_id < vocab_size: # <<<<<<<<<<<<<< + * raise ValueError(f"piece ID must be in range [0,{vocab_size}), got {piece_id}") + * return deref(self.spp).IdToPiece(piece_id).decode("utf8") + */ + } + + /* "curated_tokenizers/_spp.pyx":176 + * if not 0 <= piece_id < vocab_size: + * raise ValueError(f"piece ID must be in range [0,{vocab_size}), got {piece_id}") + * return deref(self.spp).IdToPiece(piece_id).decode("utf8") # <<<<<<<<<<<<<< + * + * def bos_id(self) -> int: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_decode_cpp_string((*__pyx_v_self->spp).IdToPiece(__pyx_v_piece_id), 0, PY_SSIZE_T_MAX, NULL, NULL, PyUnicode_DecodeUTF8); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 176, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "curated_tokenizers/_spp.pyx":164 + * return deref(self.spp).PieceToId(piece_view) + * + * def id_to_piece(self, int piece_id) -> str: # <<<<<<<<<<<<<< + * """ + * Returns the piece token for a given piece identifier. Raises a `ValueError` + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_AddTraceback("curated_tokenizers._spp.SentencePieceProcessor.id_to_piece", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_spp.pyx":178 + * return deref(self.spp).IdToPiece(piece_id).decode("utf8") + * + * def bos_id(self) -> int: # <<<<<<<<<<<<<< + * """Returns the piece identifier for the `bos` meta token.""" + * _check_status(deref(self.spp).status()) + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_31bos_id(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_30bos_id, "SentencePieceProcessor.bos_id(self) -> int\nReturns the piece identifier for the `bos` meta token."); +static PyMethodDef __pyx_mdef_18curated_tokenizers_4_spp_22SentencePieceProcessor_31bos_id = {"bos_id", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_31bos_id, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_30bos_id}; +static PyObject *__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_31bos_id(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("bos_id (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_MACROS + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { + __Pyx_RaiseArgtupleInvalid("bos_id", 1, 0, 0, __pyx_nargs); return NULL;} + if (unlikely(__pyx_kwds) && __Pyx_NumKwargs_FASTCALL(__pyx_kwds) && unlikely(!__Pyx_CheckKeywordStrings(__pyx_kwds, "bos_id", 0))) return NULL; + __pyx_r = __pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_30bos_id(((struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_30bos_id(struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("bos_id", 1); + + /* "curated_tokenizers/_spp.pyx":180 + * def bos_id(self) -> int: + * """Returns the piece identifier for the `bos` meta token.""" + * _check_status(deref(self.spp).status()) # <<<<<<<<<<<<<< + * return deref(self.spp).bos_id() + * + */ + __pyx_t_1 = __pyx_f_18curated_tokenizers_4_spp__check_status((*__pyx_v_self->spp).status()); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 180, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "curated_tokenizers/_spp.pyx":181 + * """Returns the piece identifier for the `bos` meta token.""" + * _check_status(deref(self.spp).status()) + * return deref(self.spp).bos_id() # <<<<<<<<<<<<<< + * + * def eos_id(self) -> int: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyInt_From_int((*__pyx_v_self->spp).bos_id()); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 181, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "curated_tokenizers/_spp.pyx":178 + * return deref(self.spp).IdToPiece(piece_id).decode("utf8") + * + * def bos_id(self) -> int: # <<<<<<<<<<<<<< + * """Returns the piece identifier for the `bos` meta token.""" + * _check_status(deref(self.spp).status()) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("curated_tokenizers._spp.SentencePieceProcessor.bos_id", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_spp.pyx":183 + * return deref(self.spp).bos_id() + * + * def eos_id(self) -> int: # <<<<<<<<<<<<<< + * """Returns the piece identifier for the `eos` meta token.""" + * _check_status(deref(self.spp).status()) + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_33eos_id(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_32eos_id, "SentencePieceProcessor.eos_id(self) -> int\nReturns the piece identifier for the `eos` meta token."); +static PyMethodDef __pyx_mdef_18curated_tokenizers_4_spp_22SentencePieceProcessor_33eos_id = {"eos_id", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_33eos_id, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_32eos_id}; +static PyObject *__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_33eos_id(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("eos_id (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_MACROS + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { + __Pyx_RaiseArgtupleInvalid("eos_id", 1, 0, 0, __pyx_nargs); return NULL;} + if (unlikely(__pyx_kwds) && __Pyx_NumKwargs_FASTCALL(__pyx_kwds) && unlikely(!__Pyx_CheckKeywordStrings(__pyx_kwds, "eos_id", 0))) return NULL; + __pyx_r = __pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_32eos_id(((struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_32eos_id(struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("eos_id", 1); + + /* "curated_tokenizers/_spp.pyx":185 + * def eos_id(self) -> int: + * """Returns the piece identifier for the `eos` meta token.""" + * _check_status(deref(self.spp).status()) # <<<<<<<<<<<<<< + * return deref(self.spp).eos_id() + * + */ + __pyx_t_1 = __pyx_f_18curated_tokenizers_4_spp__check_status((*__pyx_v_self->spp).status()); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 185, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "curated_tokenizers/_spp.pyx":186 + * """Returns the piece identifier for the `eos` meta token.""" + * _check_status(deref(self.spp).status()) + * return deref(self.spp).eos_id() # <<<<<<<<<<<<<< + * + * def pad_id(self) -> int: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyInt_From_int((*__pyx_v_self->spp).eos_id()); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 186, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "curated_tokenizers/_spp.pyx":183 + * return deref(self.spp).bos_id() + * + * def eos_id(self) -> int: # <<<<<<<<<<<<<< + * """Returns the piece identifier for the `eos` meta token.""" + * _check_status(deref(self.spp).status()) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("curated_tokenizers._spp.SentencePieceProcessor.eos_id", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_spp.pyx":188 + * return deref(self.spp).eos_id() + * + * def pad_id(self) -> int: # <<<<<<<<<<<<<< + * """Returns the piece identifier for the `pad` meta token.""" + * _check_status(deref(self.spp).status()) + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_35pad_id(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_34pad_id, "SentencePieceProcessor.pad_id(self) -> int\nReturns the piece identifier for the `pad` meta token."); +static PyMethodDef __pyx_mdef_18curated_tokenizers_4_spp_22SentencePieceProcessor_35pad_id = {"pad_id", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_35pad_id, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_34pad_id}; +static PyObject *__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_35pad_id(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("pad_id (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_MACROS + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { + __Pyx_RaiseArgtupleInvalid("pad_id", 1, 0, 0, __pyx_nargs); return NULL;} + if (unlikely(__pyx_kwds) && __Pyx_NumKwargs_FASTCALL(__pyx_kwds) && unlikely(!__Pyx_CheckKeywordStrings(__pyx_kwds, "pad_id", 0))) return NULL; + __pyx_r = __pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_34pad_id(((struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_34pad_id(struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("pad_id", 1); + + /* "curated_tokenizers/_spp.pyx":190 + * def pad_id(self) -> int: + * """Returns the piece identifier for the `pad` meta token.""" + * _check_status(deref(self.spp).status()) # <<<<<<<<<<<<<< + * return deref(self.spp).pad_id() + * + */ + __pyx_t_1 = __pyx_f_18curated_tokenizers_4_spp__check_status((*__pyx_v_self->spp).status()); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 190, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "curated_tokenizers/_spp.pyx":191 + * """Returns the piece identifier for the `pad` meta token.""" + * _check_status(deref(self.spp).status()) + * return deref(self.spp).pad_id() # <<<<<<<<<<<<<< + * + * def unk_id(self) -> int: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyInt_From_int((*__pyx_v_self->spp).pad_id()); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 191, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "curated_tokenizers/_spp.pyx":188 + * return deref(self.spp).eos_id() + * + * def pad_id(self) -> int: # <<<<<<<<<<<<<< + * """Returns the piece identifier for the `pad` meta token.""" + * _check_status(deref(self.spp).status()) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("curated_tokenizers._spp.SentencePieceProcessor.pad_id", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_spp.pyx":193 + * return deref(self.spp).pad_id() + * + * def unk_id(self) -> int: # <<<<<<<<<<<<<< + * """Returns the piece identifier for the `unk` meta token.""" + * _check_status(deref(self.spp).status()) + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_37unk_id(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_36unk_id, "SentencePieceProcessor.unk_id(self) -> int\nReturns the piece identifier for the `unk` meta token."); +static PyMethodDef __pyx_mdef_18curated_tokenizers_4_spp_22SentencePieceProcessor_37unk_id = {"unk_id", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_37unk_id, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_36unk_id}; +static PyObject *__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_37unk_id(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("unk_id (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_MACROS + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { + __Pyx_RaiseArgtupleInvalid("unk_id", 1, 0, 0, __pyx_nargs); return NULL;} + if (unlikely(__pyx_kwds) && __Pyx_NumKwargs_FASTCALL(__pyx_kwds) && unlikely(!__Pyx_CheckKeywordStrings(__pyx_kwds, "unk_id", 0))) return NULL; + __pyx_r = __pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_36unk_id(((struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_36unk_id(struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("unk_id", 1); + + /* "curated_tokenizers/_spp.pyx":195 + * def unk_id(self) -> int: + * """Returns the piece identifier for the `unk` meta token.""" + * _check_status(deref(self.spp).status()) # <<<<<<<<<<<<<< + * return deref(self.spp).unk_id() + * + */ + __pyx_t_1 = __pyx_f_18curated_tokenizers_4_spp__check_status((*__pyx_v_self->spp).status()); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 195, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "curated_tokenizers/_spp.pyx":196 + * """Returns the piece identifier for the `unk` meta token.""" + * _check_status(deref(self.spp).status()) + * return deref(self.spp).unk_id() # <<<<<<<<<<<<<< + * + * cdef SentencePieceText _encode(self, str sentence) except * : + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyInt_From_int((*__pyx_v_self->spp).unk_id()); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 196, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "curated_tokenizers/_spp.pyx":193 + * return deref(self.spp).pad_id() + * + * def unk_id(self) -> int: # <<<<<<<<<<<<<< + * """Returns the piece identifier for the `unk` meta token.""" + * _check_status(deref(self.spp).status()) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("curated_tokenizers._spp.SentencePieceProcessor.unk_id", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_spp.pyx":198 + * return deref(self.spp).unk_id() + * + * cdef SentencePieceText _encode(self, str sentence) except * : # <<<<<<<<<<<<<< + * sentence_bytes = sentence.encode("utf-8") + * cdef SentencePieceText text; + */ + +static sentencepiece::SentencePieceText __pyx_f_18curated_tokenizers_4_spp_22SentencePieceProcessor__encode(struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *__pyx_v_self, PyObject *__pyx_v_sentence) { + CYTHON_UNUSED PyObject *__pyx_v_sentence_bytes = NULL; + sentencepiece::SentencePieceText __pyx_v_text; + sentencepiece::SentencePieceText __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + std::string __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_encode", 1); + + /* "curated_tokenizers/_spp.pyx":199 + * + * cdef SentencePieceText _encode(self, str sentence) except * : + * sentence_bytes = sentence.encode("utf-8") # <<<<<<<<<<<<<< + * cdef SentencePieceText text; + * _check_status(deref(self.spp).Encode(sentence.encode("utf-8"), &text)) + */ + __pyx_t_1 = __Pyx_CallUnboundCMethod1(&__pyx_umethod_PyString_Type_encode, __pyx_v_sentence, __pyx_kp_s_utf_8); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 199, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_sentence_bytes = __pyx_t_1; + __pyx_t_1 = 0; + + /* "curated_tokenizers/_spp.pyx":201 + * sentence_bytes = sentence.encode("utf-8") + * cdef SentencePieceText text; + * _check_status(deref(self.spp).Encode(sentence.encode("utf-8"), &text)) # <<<<<<<<<<<<<< + * return text + * + */ + __pyx_t_1 = __Pyx_CallUnboundCMethod1(&__pyx_umethod_PyString_Type_encode, __pyx_v_sentence, __pyx_kp_s_utf_8); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 201, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __pyx_convert_string_from_py_std__in_string(__pyx_t_1); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 201, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __pyx_f_18curated_tokenizers_4_spp__check_status((*__pyx_v_self->spp).Encode(__pyx_t_2, (&__pyx_v_text))); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 201, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "curated_tokenizers/_spp.pyx":202 + * cdef SentencePieceText text; + * _check_status(deref(self.spp).Encode(sentence.encode("utf-8"), &text)) + * return text # <<<<<<<<<<<<<< + * + * def __reduce__(self): + */ + __pyx_r = __pyx_v_text; + goto __pyx_L0; + + /* "curated_tokenizers/_spp.pyx":198 + * return deref(self.spp).unk_id() + * + * cdef SentencePieceText _encode(self, str sentence) except * : # <<<<<<<<<<<<<< + * sentence_bytes = sentence.encode("utf-8") + * cdef SentencePieceText text; + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("curated_tokenizers._spp.SentencePieceProcessor._encode", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_pretend_to_initialize(&__pyx_r); + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_sentence_bytes); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_spp.pyx":204 + * return text + * + * def __reduce__(self): # <<<<<<<<<<<<<< + * return (unpickle_sentence_piece_processor, (self.to_protobuf(),)) + * + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_39__reduce__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_38__reduce__, "SentencePieceProcessor.__reduce__(self)"); +static PyMethodDef __pyx_mdef_18curated_tokenizers_4_spp_22SentencePieceProcessor_39__reduce__ = {"__reduce__", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_39__reduce__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_38__reduce__}; +static PyObject *__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_39__reduce__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__reduce__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_MACROS + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { + __Pyx_RaiseArgtupleInvalid("__reduce__", 1, 0, 0, __pyx_nargs); return NULL;} + if (unlikely(__pyx_kwds) && __Pyx_NumKwargs_FASTCALL(__pyx_kwds) && unlikely(!__Pyx_CheckKeywordStrings(__pyx_kwds, "__reduce__", 0))) return NULL; + __pyx_r = __pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_38__reduce__(((struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_18curated_tokenizers_4_spp_22SentencePieceProcessor_38__reduce__(struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__reduce__", 1); + + /* "curated_tokenizers/_spp.pyx":205 + * + * def __reduce__(self): + * return (unpickle_sentence_piece_processor, (self.to_protobuf(),)) # <<<<<<<<<<<<<< + * + * cdef _check_status(Status status): + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_unpickle_sentence_piece_processo); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 205, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_to_protobuf); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 205, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = NULL; + __pyx_t_5 = 0; + #if CYTHON_UNPACK_METHODS + if (likely(PyMethod_Check(__pyx_t_3))) { + __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_3); + if (likely(__pyx_t_4)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); + __Pyx_INCREF(__pyx_t_4); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_3, function); + __pyx_t_5 = 1; + } + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, NULL}; + __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_3, __pyx_callargs+1-__pyx_t_5, 0+__pyx_t_5); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 205, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + } + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 205, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_GIVEREF(__pyx_t_2); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_2)) __PYX_ERR(0, 205, __pyx_L1_error); + __pyx_t_2 = 0; + __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 205, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_GIVEREF(__pyx_t_1); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1)) __PYX_ERR(0, 205, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_3); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_3)) __PYX_ERR(0, 205, __pyx_L1_error); + __pyx_t_1 = 0; + __pyx_t_3 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "curated_tokenizers/_spp.pyx":204 + * return text + * + * def __reduce__(self): # <<<<<<<<<<<<<< + * return (unpickle_sentence_piece_processor, (self.to_protobuf(),)) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("curated_tokenizers._spp.SentencePieceProcessor.__reduce__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_spp.pyx":207 + * return (unpickle_sentence_piece_processor, (self.to_protobuf(),)) + * + * cdef _check_status(Status status): # <<<<<<<<<<<<<< + * cdef code = status.code() + * if code == kOk: + */ + +static PyObject *__pyx_f_18curated_tokenizers_4_spp__check_status(sentencepiece::util::Status __pyx_v_status) { + PyObject *__pyx_v_code = 0; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_t_3; + char const *__pyx_t_4; + Py_ssize_t __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_check_status", 1); + + /* "curated_tokenizers/_spp.pyx":208 + * + * cdef _check_status(Status status): + * cdef code = status.code() # <<<<<<<<<<<<<< + * if code == kOk: + * return + */ + __pyx_t_1 = __Pyx_PyInt_From_int(((int)__pyx_v_status.code())); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 208, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_code = __pyx_t_1; + __pyx_t_1 = 0; + + /* "curated_tokenizers/_spp.pyx":209 + * cdef _check_status(Status status): + * cdef code = status.code() + * if code == kOk: # <<<<<<<<<<<<<< + * return + * elif code == kNotFound: + */ + __pyx_t_1 = __Pyx_PyInt_From_int(((int)sentencepiece::util::StatusCode::kOk)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 209, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyObject_RichCompare(__pyx_v_code, __pyx_t_1, Py_EQ); __Pyx_XGOTREF(__pyx_t_2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 209, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 209, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (likely(__pyx_t_3)) { + + /* "curated_tokenizers/_spp.pyx":210 + * cdef code = status.code() + * if code == kOk: + * return # <<<<<<<<<<<<<< + * elif code == kNotFound: + * raise OSError(status.error_message().decode("utf-8")) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + + /* "curated_tokenizers/_spp.pyx":209 + * cdef _check_status(Status status): + * cdef code = status.code() + * if code == kOk: # <<<<<<<<<<<<<< + * return + * elif code == kNotFound: + */ + } + + /* "curated_tokenizers/_spp.pyx":211 + * if code == kOk: + * return + * elif code == kNotFound: # <<<<<<<<<<<<<< + * raise OSError(status.error_message().decode("utf-8")) + * elif code == kInternal: + */ + __pyx_t_2 = __Pyx_PyInt_From_int(((int)sentencepiece::util::StatusCode::kNotFound)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 211, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = PyObject_RichCompare(__pyx_v_code, __pyx_t_2, Py_EQ); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 211, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 211, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (unlikely(__pyx_t_3)) { + + /* "curated_tokenizers/_spp.pyx":212 + * return + * elif code == kNotFound: + * raise OSError(status.error_message().decode("utf-8")) # <<<<<<<<<<<<<< + * elif code == kInternal: + * raise RuntimeError(status.error_message().decode("utf-8")) + */ + __pyx_t_4 = __pyx_v_status.error_message(); + __pyx_t_5 = __Pyx_ssize_strlen(__pyx_t_4); if (unlikely(__pyx_t_5 == ((Py_ssize_t)-1))) __PYX_ERR(0, 212, __pyx_L1_error) + __pyx_t_1 = __Pyx_decode_c_string(__pyx_t_4, 0, __pyx_t_5, NULL, NULL, PyUnicode_DecodeUTF8); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 212, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_builtin_OSError, __pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 212, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __PYX_ERR(0, 212, __pyx_L1_error) + + /* "curated_tokenizers/_spp.pyx":211 + * if code == kOk: + * return + * elif code == kNotFound: # <<<<<<<<<<<<<< + * raise OSError(status.error_message().decode("utf-8")) + * elif code == kInternal: + */ + } + + /* "curated_tokenizers/_spp.pyx":213 + * elif code == kNotFound: + * raise OSError(status.error_message().decode("utf-8")) + * elif code == kInternal: # <<<<<<<<<<<<<< + * raise RuntimeError(status.error_message().decode("utf-8")) + * else: + */ + __pyx_t_2 = __Pyx_PyInt_From_int(((int)sentencepiece::util::StatusCode::kInternal)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 213, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = PyObject_RichCompare(__pyx_v_code, __pyx_t_2, Py_EQ); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 213, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 213, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (unlikely(__pyx_t_3)) { + + /* "curated_tokenizers/_spp.pyx":214 + * raise OSError(status.error_message().decode("utf-8")) + * elif code == kInternal: + * raise RuntimeError(status.error_message().decode("utf-8")) # <<<<<<<<<<<<<< + * else: + * raise ValueError(status.error_message().decode("utf-8")) + */ + __pyx_t_4 = __pyx_v_status.error_message(); + __pyx_t_5 = __Pyx_ssize_strlen(__pyx_t_4); if (unlikely(__pyx_t_5 == ((Py_ssize_t)-1))) __PYX_ERR(0, 214, __pyx_L1_error) + __pyx_t_1 = __Pyx_decode_c_string(__pyx_t_4, 0, __pyx_t_5, NULL, NULL, PyUnicode_DecodeUTF8); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 214, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_builtin_RuntimeError, __pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 214, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __PYX_ERR(0, 214, __pyx_L1_error) + + /* "curated_tokenizers/_spp.pyx":213 + * elif code == kNotFound: + * raise OSError(status.error_message().decode("utf-8")) + * elif code == kInternal: # <<<<<<<<<<<<<< + * raise RuntimeError(status.error_message().decode("utf-8")) + * else: + */ + } + + /* "curated_tokenizers/_spp.pyx":216 + * raise RuntimeError(status.error_message().decode("utf-8")) + * else: + * raise ValueError(status.error_message().decode("utf-8")) # <<<<<<<<<<<<<< + * + * def unpickle_sentence_piece_processor(protobuf: bytes) -> SentencePieceProcessor: + */ + /*else*/ { + __pyx_t_4 = __pyx_v_status.error_message(); + __pyx_t_5 = __Pyx_ssize_strlen(__pyx_t_4); if (unlikely(__pyx_t_5 == ((Py_ssize_t)-1))) __PYX_ERR(0, 216, __pyx_L1_error) + __pyx_t_2 = __Pyx_decode_c_string(__pyx_t_4, 0, __pyx_t_5, NULL, NULL, PyUnicode_DecodeUTF8); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 216, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_builtin_ValueError, __pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 216, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(0, 216, __pyx_L1_error) + } + + /* "curated_tokenizers/_spp.pyx":207 + * return (unpickle_sentence_piece_processor, (self.to_protobuf(),)) + * + * cdef _check_status(Status status): # <<<<<<<<<<<<<< + * cdef code = status.code() + * if code == kOk: + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("curated_tokenizers._spp._check_status", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_code); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_spp.pyx":218 + * raise ValueError(status.error_message().decode("utf-8")) + * + * def unpickle_sentence_piece_processor(protobuf: bytes) -> SentencePieceProcessor: # <<<<<<<<<<<<<< + * return SentencePieceProcessor.from_protobuf(protobuf) + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_18curated_tokenizers_4_spp_1unpickle_sentence_piece_processor(PyObject *__pyx_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_18curated_tokenizers_4_spp_unpickle_sentence_piece_processor, "unpickle_sentence_piece_processor(protobuf: bytes) -> SentencePieceProcessor"); +static PyMethodDef __pyx_mdef_18curated_tokenizers_4_spp_1unpickle_sentence_piece_processor = {"unpickle_sentence_piece_processor", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_4_spp_1unpickle_sentence_piece_processor, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_4_spp_unpickle_sentence_piece_processor}; +static PyObject *__pyx_pw_18curated_tokenizers_4_spp_1unpickle_sentence_piece_processor(PyObject *__pyx_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_protobuf = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("unpickle_sentence_piece_processor (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_MACROS + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject **__pyx_pyargnames[] = {&__pyx_n_s_protobuf,0}; + if (__pyx_kwds) { + Py_ssize_t kw_args; + switch (__pyx_nargs) { + case 1: values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = __Pyx_NumKwargs_FASTCALL(__pyx_kwds); + switch (__pyx_nargs) { + case 0: + if (likely((values[0] = __Pyx_GetKwValue_FASTCALL(__pyx_kwds, __pyx_kwvalues, __pyx_n_s_protobuf)) != 0)) { + (void)__Pyx_Arg_NewRef_FASTCALL(values[0]); + kw_args--; + } + else if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 218, __pyx_L3_error) + else goto __pyx_L5_argtuple_error; + } + if (unlikely(kw_args > 0)) { + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values + 0, kwd_pos_args, "unpickle_sentence_piece_processor") < 0)) __PYX_ERR(0, 218, __pyx_L3_error) + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + } + __pyx_v_protobuf = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("unpickle_sentence_piece_processor", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 218, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_AddTraceback("curated_tokenizers._spp.unpickle_sentence_piece_processor", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_18curated_tokenizers_4_spp_unpickle_sentence_piece_processor(__pyx_self, __pyx_v_protobuf); + + /* function exit code */ + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_18curated_tokenizers_4_spp_unpickle_sentence_piece_processor(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_protobuf) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_t_4; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("unpickle_sentence_piece_processor", 1); + + /* "curated_tokenizers/_spp.pyx":219 + * + * def unpickle_sentence_piece_processor(protobuf: bytes) -> SentencePieceProcessor: + * return SentencePieceProcessor.from_protobuf(protobuf) # <<<<<<<<<<<<<< + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor), __pyx_n_s_from_protobuf); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 219, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = NULL; + __pyx_t_4 = 0; + #if CYTHON_UNPACK_METHODS + if (likely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2); + if (likely(__pyx_t_3)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_2, function); + __pyx_t_4 = 1; + } + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_v_protobuf}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_2, __pyx_callargs+1-__pyx_t_4, 1+__pyx_t_4); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 219, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "curated_tokenizers/_spp.pyx":218 + * raise ValueError(status.error_message().decode("utf-8")) + * + * def unpickle_sentence_piece_processor(protobuf: bytes) -> SentencePieceProcessor: # <<<<<<<<<<<<<< + * return SentencePieceProcessor.from_protobuf(protobuf) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("curated_tokenizers._spp.unpickle_sentence_piece_processor", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} +static struct __pyx_vtabstruct_18curated_tokenizers_4_spp_SentencePieceProcessor __pyx_vtable_18curated_tokenizers_4_spp_SentencePieceProcessor; + +static PyObject *__pyx_tp_new_18curated_tokenizers_4_spp_SentencePieceProcessor(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { + struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *p; + PyObject *o; + #if CYTHON_COMPILING_IN_LIMITED_API + allocfunc alloc_func = (allocfunc)PyType_GetSlot(t, Py_tp_alloc); + o = alloc_func(t, 0); + #else + if (likely(!__Pyx_PyType_HasFeature(t, Py_TPFLAGS_IS_ABSTRACT))) { + o = (*t->tp_alloc)(t, 0); + } else { + o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); + } + if (unlikely(!o)) return 0; + #endif + p = ((struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *)o); + p->__pyx_vtab = __pyx_vtabptr_18curated_tokenizers_4_spp_SentencePieceProcessor; + new((void*)&(p->spp)) std::shared_ptr (); + if (unlikely(__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_1__cinit__(o, __pyx_empty_tuple, NULL) < 0)) goto bad; + return o; + bad: + Py_DECREF(o); o = 0; + return NULL; +} + +static void __pyx_tp_dealloc_18curated_tokenizers_4_spp_SentencePieceProcessor(PyObject *o) { + struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *p = (struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *)o; + #if CYTHON_USE_TP_FINALIZE + if (unlikely((PY_VERSION_HEX >= 0x03080000 || __Pyx_PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE)) && __Pyx_PyObject_GetSlot(o, tp_finalize, destructor)) && (!PyType_IS_GC(Py_TYPE(o)) || !__Pyx_PyObject_GC_IsFinalized(o))) { + if (__Pyx_PyObject_GetSlot(o, tp_dealloc, destructor) == __pyx_tp_dealloc_18curated_tokenizers_4_spp_SentencePieceProcessor) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + } + #endif + __Pyx_call_destructor(p->spp); + #if CYTHON_USE_TYPE_SLOTS || CYTHON_COMPILING_IN_PYPY + (*Py_TYPE(o)->tp_free)(o); + #else + { + freefunc tp_free = (freefunc)PyType_GetSlot(Py_TYPE(o), Py_tp_free); + if (tp_free) tp_free(o); + } + #endif +} + +static PyMethodDef __pyx_methods_18curated_tokenizers_4_spp_SentencePieceProcessor[] = { + {"__copy__", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_7__copy__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_6__copy__}, + {"__deepcopy__", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_9__deepcopy__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_8__deepcopy__}, + {"from_file", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_11from_file, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_10from_file}, + {"from_protobuf", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_13from_protobuf, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_12from_protobuf}, + {"to_protobuf", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_15to_protobuf, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_14to_protobuf}, + {"decode_from_ids", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_17decode_from_ids, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_16decode_from_ids}, + {"decode_from_pieces", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_19decode_from_pieces, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_18decode_from_pieces}, + {"encode", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_21encode, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_20encode}, + {"encode_as_ids", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_23encode_as_ids, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_22encode_as_ids}, + {"encode_as_pieces", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_25encode_as_pieces, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_24encode_as_pieces}, + {"piece_to_id", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_27piece_to_id, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_26piece_to_id}, + {"id_to_piece", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_29id_to_piece, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_28id_to_piece}, + {"bos_id", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_31bos_id, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_30bos_id}, + {"eos_id", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_33eos_id, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_32eos_id}, + {"pad_id", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_35pad_id, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_34pad_id}, + {"unk_id", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_37unk_id, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_36unk_id}, + {"__reduce__", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_39__reduce__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_4_spp_22SentencePieceProcessor_38__reduce__}, + {0, 0, 0, 0} +}; +#if CYTHON_USE_TYPE_SPECS +static PyType_Slot __pyx_type_18curated_tokenizers_4_spp_SentencePieceProcessor_slots[] = { + {Py_tp_dealloc, (void *)__pyx_tp_dealloc_18curated_tokenizers_4_spp_SentencePieceProcessor}, + {Py_sq_length, (void *)__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_5__len__}, + {Py_mp_length, (void *)__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_5__len__}, + {Py_tp_doc, (void *)PyDoc_STR("SentencePieceProcessor()")}, + {Py_tp_methods, (void *)__pyx_methods_18curated_tokenizers_4_spp_SentencePieceProcessor}, + {Py_tp_init, (void *)__pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_3__init__}, + {Py_tp_new, (void *)__pyx_tp_new_18curated_tokenizers_4_spp_SentencePieceProcessor}, + {0, 0}, +}; +static PyType_Spec __pyx_type_18curated_tokenizers_4_spp_SentencePieceProcessor_spec = { + "curated_tokenizers._spp.SentencePieceProcessor", + sizeof(struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor), + 0, + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, + __pyx_type_18curated_tokenizers_4_spp_SentencePieceProcessor_slots, +}; +#else + +static PySequenceMethods __pyx_tp_as_sequence_SentencePieceProcessor = { + __pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_5__len__, /*sq_length*/ + 0, /*sq_concat*/ + 0, /*sq_repeat*/ + 0, /*sq_item*/ + 0, /*sq_slice*/ + 0, /*sq_ass_item*/ + 0, /*sq_ass_slice*/ + 0, /*sq_contains*/ + 0, /*sq_inplace_concat*/ + 0, /*sq_inplace_repeat*/ +}; + +static PyMappingMethods __pyx_tp_as_mapping_SentencePieceProcessor = { + __pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_5__len__, /*mp_length*/ + 0, /*mp_subscript*/ + 0, /*mp_ass_subscript*/ +}; + +static PyTypeObject __pyx_type_18curated_tokenizers_4_spp_SentencePieceProcessor = { + PyVarObject_HEAD_INIT(0, 0) + "curated_tokenizers._spp.""SentencePieceProcessor", /*tp_name*/ + sizeof(struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_18curated_tokenizers_4_spp_SentencePieceProcessor, /*tp_dealloc*/ + #if PY_VERSION_HEX < 0x030800b4 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030800b4 + 0, /*tp_vectorcall_offset*/ + #endif + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #endif + #if PY_MAJOR_VERSION >= 3 + 0, /*tp_as_async*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + &__pyx_tp_as_sequence_SentencePieceProcessor, /*tp_as_sequence*/ + &__pyx_tp_as_mapping_SentencePieceProcessor, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ + PyDoc_STR("SentencePieceProcessor()"), /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_18curated_tokenizers_4_spp_SentencePieceProcessor, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + #if !CYTHON_USE_TYPE_SPECS + 0, /*tp_dictoffset*/ + #endif + __pyx_pw_18curated_tokenizers_4_spp_22SentencePieceProcessor_3__init__, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_18curated_tokenizers_4_spp_SentencePieceProcessor, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if PY_VERSION_HEX >= 0x030400a1 + #if CYTHON_USE_TP_FINALIZE + 0, /*tp_finalize*/ + #else + NULL, /*tp_finalize*/ + #endif + #endif + #if PY_VERSION_HEX >= 0x030800b1 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) + 0, /*tp_vectorcall*/ + #endif + #if __PYX_NEED_TP_PRINT_SLOT == 1 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030C0000 + 0, /*tp_watched*/ + #endif + #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 + 0, /*tp_pypy_flags*/ + #endif +}; +#endif + +static PyMethodDef __pyx_methods[] = { + {0, 0, 0, 0} +}; +#ifndef CYTHON_SMALL_CODE +#if defined(__clang__) + #define CYTHON_SMALL_CODE +#elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) + #define CYTHON_SMALL_CODE __attribute__((cold)) +#else + #define CYTHON_SMALL_CODE +#endif +#endif +/* #### Code section: pystring_table ### */ + +static int __Pyx_CreateStringTabAndInitStrings(void) { + __Pyx_StringTabEntry __pyx_string_tab[] = { + {&__pyx_n_s_List, __pyx_k_List, sizeof(__pyx_k_List), 0, 0, 1, 1}, + {&__pyx_kp_s_List_int, __pyx_k_List_int, sizeof(__pyx_k_List_int), 0, 0, 1, 0}, + {&__pyx_kp_s_List_str, __pyx_k_List_str, sizeof(__pyx_k_List_str), 0, 0, 1, 0}, + {&__pyx_n_s_OSError, __pyx_k_OSError, sizeof(__pyx_k_OSError), 0, 0, 1, 1}, + {&__pyx_kp_s_Pieces_must_be_of_type_int_when, __pyx_k_Pieces_must_be_of_type_int_when, sizeof(__pyx_k_Pieces_must_be_of_type_int_when), 0, 0, 1, 0}, + {&__pyx_kp_s_Pieces_must_be_of_type_str_when, __pyx_k_Pieces_must_be_of_type_str_when, sizeof(__pyx_k_Pieces_must_be_of_type_str_when), 0, 0, 1, 0}, + {&__pyx_n_s_RuntimeError, __pyx_k_RuntimeError, sizeof(__pyx_k_RuntimeError), 0, 0, 1, 1}, + {&__pyx_n_s_SentencePieceProcessor, __pyx_k_SentencePieceProcessor, sizeof(__pyx_k_SentencePieceProcessor), 0, 0, 1, 1}, + {&__pyx_n_s_SentencePieceProcessor___copy, __pyx_k_SentencePieceProcessor___copy, sizeof(__pyx_k_SentencePieceProcessor___copy), 0, 0, 1, 1}, + {&__pyx_n_s_SentencePieceProcessor___deepcop, __pyx_k_SentencePieceProcessor___deepcop, sizeof(__pyx_k_SentencePieceProcessor___deepcop), 0, 0, 1, 1}, + {&__pyx_n_s_SentencePieceProcessor___reduce, __pyx_k_SentencePieceProcessor___reduce, sizeof(__pyx_k_SentencePieceProcessor___reduce), 0, 0, 1, 1}, + {&__pyx_n_s_SentencePieceProcessor_bos_id, __pyx_k_SentencePieceProcessor_bos_id, sizeof(__pyx_k_SentencePieceProcessor_bos_id), 0, 0, 1, 1}, + {&__pyx_n_s_SentencePieceProcessor_decode_fr, __pyx_k_SentencePieceProcessor_decode_fr, sizeof(__pyx_k_SentencePieceProcessor_decode_fr), 0, 0, 1, 1}, + {&__pyx_n_s_SentencePieceProcessor_decode_fr_2, __pyx_k_SentencePieceProcessor_decode_fr_2, sizeof(__pyx_k_SentencePieceProcessor_decode_fr_2), 0, 0, 1, 1}, + {&__pyx_n_s_SentencePieceProcessor_encode, __pyx_k_SentencePieceProcessor_encode, sizeof(__pyx_k_SentencePieceProcessor_encode), 0, 0, 1, 1}, + {&__pyx_n_s_SentencePieceProcessor_encode_as, __pyx_k_SentencePieceProcessor_encode_as, sizeof(__pyx_k_SentencePieceProcessor_encode_as), 0, 0, 1, 1}, + {&__pyx_n_s_SentencePieceProcessor_encode_as_2, __pyx_k_SentencePieceProcessor_encode_as_2, sizeof(__pyx_k_SentencePieceProcessor_encode_as_2), 0, 0, 1, 1}, + {&__pyx_n_s_SentencePieceProcessor_eos_id, __pyx_k_SentencePieceProcessor_eos_id, sizeof(__pyx_k_SentencePieceProcessor_eos_id), 0, 0, 1, 1}, + {&__pyx_n_s_SentencePieceProcessor_from_file, __pyx_k_SentencePieceProcessor_from_file, sizeof(__pyx_k_SentencePieceProcessor_from_file), 0, 0, 1, 1}, + {&__pyx_n_s_SentencePieceProcessor_from_prot, __pyx_k_SentencePieceProcessor_from_prot, sizeof(__pyx_k_SentencePieceProcessor_from_prot), 0, 0, 1, 1}, + {&__pyx_n_s_SentencePieceProcessor_id_to_pie, __pyx_k_SentencePieceProcessor_id_to_pie, sizeof(__pyx_k_SentencePieceProcessor_id_to_pie), 0, 0, 1, 1}, + {&__pyx_n_s_SentencePieceProcessor_pad_id, __pyx_k_SentencePieceProcessor_pad_id, sizeof(__pyx_k_SentencePieceProcessor_pad_id), 0, 0, 1, 1}, + {&__pyx_n_s_SentencePieceProcessor_piece_to, __pyx_k_SentencePieceProcessor_piece_to, sizeof(__pyx_k_SentencePieceProcessor_piece_to), 0, 0, 1, 1}, + {&__pyx_n_s_SentencePieceProcessor_to_protob, __pyx_k_SentencePieceProcessor_to_protob, sizeof(__pyx_k_SentencePieceProcessor_to_protob), 0, 0, 1, 1}, + {&__pyx_n_s_SentencePieceProcessor_unk_id, __pyx_k_SentencePieceProcessor_unk_id, sizeof(__pyx_k_SentencePieceProcessor_unk_id), 0, 0, 1, 1}, + {&__pyx_n_s_Tuple, __pyx_k_Tuple, sizeof(__pyx_k_Tuple), 0, 0, 1, 1}, + {&__pyx_kp_s_Tuple_List_int_List_str, __pyx_k_Tuple_List_int_List_str, sizeof(__pyx_k_Tuple_List_int_List_str), 0, 0, 1, 0}, + {&__pyx_n_s_TypeError, __pyx_k_TypeError, sizeof(__pyx_k_TypeError), 0, 0, 1, 1}, + {&__pyx_n_s_ValueError, __pyx_k_ValueError, sizeof(__pyx_k_ValueError), 0, 0, 1, 1}, + {&__pyx_kp_u__3, __pyx_k__3, sizeof(__pyx_k__3), 0, 1, 0, 0}, + {&__pyx_n_s__35, __pyx_k__35, sizeof(__pyx_k__35), 0, 0, 1, 1}, + {&__pyx_n_s_asyncio_coroutines, __pyx_k_asyncio_coroutines, sizeof(__pyx_k_asyncio_coroutines), 0, 0, 1, 1}, + {&__pyx_n_s_bos_id, __pyx_k_bos_id, sizeof(__pyx_k_bos_id), 0, 0, 1, 1}, + {&__pyx_n_s_bytes, __pyx_k_bytes, sizeof(__pyx_k_bytes), 0, 0, 1, 1}, + {&__pyx_n_s_c_ids, __pyx_k_c_ids, sizeof(__pyx_k_c_ids), 0, 0, 1, 1}, + {&__pyx_n_s_c_strings, __pyx_k_c_strings, sizeof(__pyx_k_c_strings), 0, 0, 1, 1}, + {&__pyx_n_s_cline_in_traceback, __pyx_k_cline_in_traceback, sizeof(__pyx_k_cline_in_traceback), 0, 0, 1, 1}, + {&__pyx_n_s_copy, __pyx_k_copy, sizeof(__pyx_k_copy), 0, 0, 1, 1}, + {&__pyx_n_s_curated_tokenizers__spp, __pyx_k_curated_tokenizers__spp, sizeof(__pyx_k_curated_tokenizers__spp), 0, 0, 1, 1}, + {&__pyx_kp_s_curated_tokenizers__spp_pyx, __pyx_k_curated_tokenizers__spp_pyx, sizeof(__pyx_k_curated_tokenizers__spp_pyx), 0, 0, 1, 0}, + {&__pyx_n_s_decode_from_ids, __pyx_k_decode_from_ids, sizeof(__pyx_k_decode_from_ids), 0, 0, 1, 1}, + {&__pyx_n_s_decode_from_pieces, __pyx_k_decode_from_pieces, sizeof(__pyx_k_decode_from_pieces), 0, 0, 1, 1}, + {&__pyx_n_s_deepcopy, __pyx_k_deepcopy, sizeof(__pyx_k_deepcopy), 0, 0, 1, 1}, + {&__pyx_n_s_dict, __pyx_k_dict, sizeof(__pyx_k_dict), 0, 0, 1, 1}, + {&__pyx_kp_u_disable, __pyx_k_disable, sizeof(__pyx_k_disable), 0, 1, 0, 0}, + {&__pyx_kp_u_enable, __pyx_k_enable, sizeof(__pyx_k_enable), 0, 1, 0, 0}, + {&__pyx_n_s_encode, __pyx_k_encode, sizeof(__pyx_k_encode), 0, 0, 1, 1}, + {&__pyx_n_s_encode_as_ids, __pyx_k_encode_as_ids, sizeof(__pyx_k_encode_as_ids), 0, 0, 1, 1}, + {&__pyx_n_s_encode_as_pieces, __pyx_k_encode_as_pieces, sizeof(__pyx_k_encode_as_pieces), 0, 0, 1, 1}, + {&__pyx_n_s_eos_id, __pyx_k_eos_id, sizeof(__pyx_k_eos_id), 0, 0, 1, 1}, + {&__pyx_n_s_filename, __pyx_k_filename, sizeof(__pyx_k_filename), 0, 0, 1, 1}, + {&__pyx_n_s_from_file, __pyx_k_from_file, sizeof(__pyx_k_from_file), 0, 0, 1, 1}, + {&__pyx_n_s_from_protobuf, __pyx_k_from_protobuf, sizeof(__pyx_k_from_protobuf), 0, 0, 1, 1}, + {&__pyx_kp_u_gc, __pyx_k_gc, sizeof(__pyx_k_gc), 0, 1, 0, 0}, + {&__pyx_kp_u_got, __pyx_k_got, sizeof(__pyx_k_got), 0, 1, 0, 0}, + {&__pyx_n_s_id, __pyx_k_id, sizeof(__pyx_k_id), 0, 0, 1, 1}, + {&__pyx_n_s_id_to_piece, __pyx_k_id_to_piece, sizeof(__pyx_k_id_to_piece), 0, 0, 1, 1}, + {&__pyx_n_s_ids, __pyx_k_ids, sizeof(__pyx_k_ids), 0, 0, 1, 1}, + {&__pyx_n_s_idx, __pyx_k_idx, sizeof(__pyx_k_idx), 0, 0, 1, 1}, + {&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1}, + {&__pyx_n_s_int, __pyx_k_int, sizeof(__pyx_k_int), 0, 0, 1, 1}, + {&__pyx_n_s_is_coroutine, __pyx_k_is_coroutine, sizeof(__pyx_k_is_coroutine), 0, 0, 1, 1}, + {&__pyx_kp_u_isenabled, __pyx_k_isenabled, sizeof(__pyx_k_isenabled), 0, 1, 0, 0}, + {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, + {&__pyx_n_s_memo, __pyx_k_memo, sizeof(__pyx_k_memo), 0, 0, 1, 1}, + {&__pyx_n_s_name, __pyx_k_name, sizeof(__pyx_k_name), 0, 0, 1, 1}, + {&__pyx_n_s_output, __pyx_k_output, sizeof(__pyx_k_output), 0, 0, 1, 1}, + {&__pyx_n_s_pad_id, __pyx_k_pad_id, sizeof(__pyx_k_pad_id), 0, 0, 1, 1}, + {&__pyx_n_s_piece, __pyx_k_piece, sizeof(__pyx_k_piece), 0, 0, 1, 1}, + {&__pyx_kp_u_piece_ID_must_be_in_range_0, __pyx_k_piece_ID_must_be_in_range_0, sizeof(__pyx_k_piece_ID_must_be_in_range_0), 0, 1, 0, 0}, + {&__pyx_n_s_piece_bytes, __pyx_k_piece_bytes, sizeof(__pyx_k_piece_bytes), 0, 0, 1, 1}, + {&__pyx_n_s_piece_id, __pyx_k_piece_id, sizeof(__pyx_k_piece_id), 0, 0, 1, 1}, + {&__pyx_n_s_piece_to_id, __pyx_k_piece_to_id, sizeof(__pyx_k_piece_to_id), 0, 0, 1, 1}, + {&__pyx_n_s_piece_view, __pyx_k_piece_view, sizeof(__pyx_k_piece_view), 0, 0, 1, 1}, + {&__pyx_n_s_pieces, __pyx_k_pieces, sizeof(__pyx_k_pieces), 0, 0, 1, 1}, + {&__pyx_n_s_processor, __pyx_k_processor, sizeof(__pyx_k_processor), 0, 0, 1, 1}, + {&__pyx_n_s_protobuf, __pyx_k_protobuf, sizeof(__pyx_k_protobuf), 0, 0, 1, 1}, + {&__pyx_n_s_protobuf_view, __pyx_k_protobuf_view, sizeof(__pyx_k_protobuf_view), 0, 0, 1, 1}, + {&__pyx_n_s_pyx_vtable, __pyx_k_pyx_vtable, sizeof(__pyx_k_pyx_vtable), 0, 0, 1, 1}, + {&__pyx_n_s_range, __pyx_k_range, sizeof(__pyx_k_range), 0, 0, 1, 1}, + {&__pyx_n_s_reduce, __pyx_k_reduce, sizeof(__pyx_k_reduce), 0, 0, 1, 1}, + {&__pyx_n_s_result, __pyx_k_result, sizeof(__pyx_k_result), 0, 0, 1, 1}, + {&__pyx_n_s_return, __pyx_k_return, sizeof(__pyx_k_return), 0, 0, 1, 1}, + {&__pyx_n_s_self, __pyx_k_self, sizeof(__pyx_k_self), 0, 0, 1, 1}, + {&__pyx_n_s_sentence, __pyx_k_sentence, sizeof(__pyx_k_sentence), 0, 0, 1, 1}, + {&__pyx_n_s_serialized, __pyx_k_serialized, sizeof(__pyx_k_serialized), 0, 0, 1, 1}, + {&__pyx_n_s_staticmethod, __pyx_k_staticmethod, sizeof(__pyx_k_staticmethod), 0, 0, 1, 1}, + {&__pyx_n_s_str, __pyx_k_str, sizeof(__pyx_k_str), 0, 0, 1, 1}, + {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, + {&__pyx_n_s_text, __pyx_k_text, sizeof(__pyx_k_text), 0, 0, 1, 1}, + {&__pyx_n_s_to_protobuf, __pyx_k_to_protobuf, sizeof(__pyx_k_to_protobuf), 0, 0, 1, 1}, + {&__pyx_n_s_typing, __pyx_k_typing, sizeof(__pyx_k_typing), 0, 0, 1, 1}, + {&__pyx_n_s_unk_id, __pyx_k_unk_id, sizeof(__pyx_k_unk_id), 0, 0, 1, 1}, + {&__pyx_n_s_unpickle_sentence_piece_processo, __pyx_k_unpickle_sentence_piece_processo, sizeof(__pyx_k_unpickle_sentence_piece_processo), 0, 0, 1, 1}, + {&__pyx_n_s_utf8, __pyx_k_utf8, sizeof(__pyx_k_utf8), 0, 0, 1, 1}, + {&__pyx_kp_s_utf_8, __pyx_k_utf_8, sizeof(__pyx_k_utf_8), 0, 0, 1, 0}, + {&__pyx_n_s_vocab_size, __pyx_k_vocab_size, sizeof(__pyx_k_vocab_size), 0, 0, 1, 1}, + {0, 0, 0, 0, 0, 0, 0} + }; + return __Pyx_InitStrings(__pyx_string_tab); +} +/* #### Code section: cached_builtins ### */ +static CYTHON_SMALL_CODE int __Pyx_InitCachedBuiltins(void) { + __pyx_builtin_staticmethod = __Pyx_GetBuiltinName(__pyx_n_s_staticmethod); if (!__pyx_builtin_staticmethod) __PYX_ERR(0, 23, __pyx_L1_error) + __pyx_builtin_id = __Pyx_GetBuiltinName(__pyx_n_s_id); if (!__pyx_builtin_id) __PYX_ERR(0, 20, __pyx_L1_error) + __pyx_builtin_TypeError = __Pyx_GetBuiltinName(__pyx_n_s_TypeError); if (!__pyx_builtin_TypeError) __PYX_ERR(0, 73, __pyx_L1_error) + __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) __PYX_ERR(0, 110, __pyx_L1_error) + __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s_ValueError); if (!__pyx_builtin_ValueError) __PYX_ERR(0, 175, __pyx_L1_error) + __pyx_builtin_OSError = __Pyx_GetBuiltinName(__pyx_n_s_OSError); if (!__pyx_builtin_OSError) __PYX_ERR(0, 212, __pyx_L1_error) + __pyx_builtin_RuntimeError = __Pyx_GetBuiltinName(__pyx_n_s_RuntimeError); if (!__pyx_builtin_RuntimeError) __PYX_ERR(0, 214, __pyx_L1_error) + return 0; + __pyx_L1_error:; + return -1; +} +/* #### Code section: cached_constants ### */ + +static CYTHON_SMALL_CODE int __Pyx_InitCachedConstants(void) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); + + /* "curated_tokenizers/_spp.pyx":73 + * for piece_id in ids: + * if not isinstance(piece_id, int): + * raise TypeError("Pieces must be of type `int` when decoding from ids") # <<<<<<<<<<<<<< + * c_ids.push_back(piece_id) + * cdef string output + */ + __pyx_tuple_ = PyTuple_Pack(1, __pyx_kp_s_Pieces_must_be_of_type_int_when); if (unlikely(!__pyx_tuple_)) __PYX_ERR(0, 73, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple_); + __Pyx_GIVEREF(__pyx_tuple_); + + /* "curated_tokenizers/_spp.pyx":90 + * for piece in pieces: + * if not isinstance(piece, str): + * raise TypeError("Pieces must be of type `str` when decoding from pieces") # <<<<<<<<<<<<<< + * c_strings.push_back(piece.encode("utf-8")) + * cdef string output + */ + __pyx_tuple__2 = PyTuple_Pack(1, __pyx_kp_s_Pieces_must_be_of_type_str_when); if (unlikely(!__pyx_tuple__2)) __PYX_ERR(0, 90, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__2); + __Pyx_GIVEREF(__pyx_tuple__2); + + /* "curated_tokenizers/_spp.pyx":15 + * return deref(self.spp).GetPieceSize() + * + * def __copy__(self): # <<<<<<<<<<<<<< + * return SentencePieceProcessor.from_protobuf(self.to_protobuf()) + * + */ + __pyx_tuple__4 = PyTuple_Pack(1, __pyx_n_s_self); if (unlikely(!__pyx_tuple__4)) __PYX_ERR(0, 15, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__4); + __Pyx_GIVEREF(__pyx_tuple__4); + __pyx_codeobj__5 = (PyObject*)__Pyx_PyCode_New(1, 0, 0, 1, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__4, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_curated_tokenizers__spp_pyx, __pyx_n_s_copy, 15, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__5)) __PYX_ERR(0, 15, __pyx_L1_error) + + /* "curated_tokenizers/_spp.pyx":18 + * return SentencePieceProcessor.from_protobuf(self.to_protobuf()) + * + * def __deepcopy__(self, memo): # <<<<<<<<<<<<<< + * result = SentencePieceProcessor.from_protobuf(self.to_protobuf()) + * memo[id(self)] = result + */ + __pyx_tuple__6 = PyTuple_Pack(3, __pyx_n_s_self, __pyx_n_s_memo, __pyx_n_s_result); if (unlikely(!__pyx_tuple__6)) __PYX_ERR(0, 18, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__6); + __Pyx_GIVEREF(__pyx_tuple__6); + __pyx_codeobj__7 = (PyObject*)__Pyx_PyCode_New(2, 0, 0, 3, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__6, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_curated_tokenizers__spp_pyx, __pyx_n_s_deepcopy, 18, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__7)) __PYX_ERR(0, 18, __pyx_L1_error) + + /* "curated_tokenizers/_spp.pyx":23 + * return result + * + * @staticmethod # <<<<<<<<<<<<<< + * def from_file(str filename): + * """ + */ + __pyx_tuple__8 = PyTuple_Pack(2, __pyx_n_s_filename, __pyx_n_s_processor); if (unlikely(!__pyx_tuple__8)) __PYX_ERR(0, 23, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__8); + __Pyx_GIVEREF(__pyx_tuple__8); + __pyx_codeobj__9 = (PyObject*)__Pyx_PyCode_New(1, 0, 0, 2, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__8, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_curated_tokenizers__spp_pyx, __pyx_n_s_from_file, 23, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__9)) __PYX_ERR(0, 23, __pyx_L1_error) + + /* "curated_tokenizers/_spp.pyx":35 + * return processor + * + * @staticmethod # <<<<<<<<<<<<<< + * def from_protobuf(bytes protobuf): + * """ + */ + __pyx_tuple__10 = PyTuple_Pack(3, __pyx_n_s_protobuf, __pyx_n_s_processor, __pyx_n_s_protobuf_view); if (unlikely(!__pyx_tuple__10)) __PYX_ERR(0, 35, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__10); + __Pyx_GIVEREF(__pyx_tuple__10); + __pyx_codeobj__11 = (PyObject*)__Pyx_PyCode_New(1, 0, 0, 3, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__10, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_curated_tokenizers__spp_pyx, __pyx_n_s_from_protobuf, 35, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__11)) __PYX_ERR(0, 35, __pyx_L1_error) + + /* "curated_tokenizers/_spp.pyx":52 + * return processor + * + * def to_protobuf(self) -> bytes: # <<<<<<<<<<<<<< + * """ + * Serializes the SentencePieceProcessor to a protocol buffer. + */ + __pyx_tuple__12 = PyTuple_Pack(2, __pyx_n_s_self, __pyx_n_s_serialized); if (unlikely(!__pyx_tuple__12)) __PYX_ERR(0, 52, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__12); + __Pyx_GIVEREF(__pyx_tuple__12); + __pyx_codeobj__13 = (PyObject*)__Pyx_PyCode_New(1, 0, 0, 2, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__12, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_curated_tokenizers__spp_pyx, __pyx_n_s_to_protobuf, 52, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__13)) __PYX_ERR(0, 52, __pyx_L1_error) + + /* "curated_tokenizers/_spp.pyx":62 + * return bytes(serialized) + * + * def decode_from_ids(self, list ids) -> str: # <<<<<<<<<<<<<< + * """ + * Decodes piece indentifiers to a string. Raises a `ValueError` if the + */ + __pyx_tuple__14 = PyTuple_Pack(5, __pyx_n_s_self, __pyx_n_s_ids, __pyx_n_s_c_ids, __pyx_n_s_piece_id, __pyx_n_s_output); if (unlikely(!__pyx_tuple__14)) __PYX_ERR(0, 62, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__14); + __Pyx_GIVEREF(__pyx_tuple__14); + __pyx_codeobj__15 = (PyObject*)__Pyx_PyCode_New(2, 0, 0, 5, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__14, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_curated_tokenizers__spp_pyx, __pyx_n_s_decode_from_ids, 62, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__15)) __PYX_ERR(0, 62, __pyx_L1_error) + + /* "curated_tokenizers/_spp.pyx":79 + * return output.decode("utf-8") + * + * def decode_from_pieces(self, list pieces) -> str: # <<<<<<<<<<<<<< + * """ + * Decodes piece tokens to a string. Raises a `ValueError` if the + */ + __pyx_tuple__16 = PyTuple_Pack(5, __pyx_n_s_self, __pyx_n_s_pieces, __pyx_n_s_c_strings, __pyx_n_s_piece, __pyx_n_s_output); if (unlikely(!__pyx_tuple__16)) __PYX_ERR(0, 79, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__16); + __Pyx_GIVEREF(__pyx_tuple__16); + __pyx_codeobj__17 = (PyObject*)__Pyx_PyCode_New(2, 0, 0, 5, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__16, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_curated_tokenizers__spp_pyx, __pyx_n_s_decode_from_pieces, 79, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__17)) __PYX_ERR(0, 79, __pyx_L1_error) + + /* "curated_tokenizers/_spp.pyx":96 + * return output.decode("utf-8") + * + * def encode(self, str sentence) -> Tuple[List[int], List[str]]: # <<<<<<<<<<<<<< + * """ + * Encodes a string to piece indentifiers and piece tokens. + */ + __pyx_tuple__18 = PyTuple_Pack(7, __pyx_n_s_self, __pyx_n_s_sentence, __pyx_n_s_text, __pyx_n_s_idx, __pyx_n_s_piece, __pyx_n_s_pieces, __pyx_n_s_ids); if (unlikely(!__pyx_tuple__18)) __PYX_ERR(0, 96, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__18); + __Pyx_GIVEREF(__pyx_tuple__18); + __pyx_codeobj__19 = (PyObject*)__Pyx_PyCode_New(2, 0, 0, 7, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__18, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_curated_tokenizers__spp_pyx, __pyx_n_s_encode, 96, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__19)) __PYX_ERR(0, 96, __pyx_L1_error) + + /* "curated_tokenizers/_spp.pyx":117 + * return ids, pieces + * + * def encode_as_ids(self, str sentence) -> List[int]: # <<<<<<<<<<<<<< + * """ + * Encodes a string to piece indentifiers. + */ + __pyx_tuple__20 = PyTuple_Pack(5, __pyx_n_s_self, __pyx_n_s_sentence, __pyx_n_s_text, __pyx_n_s_idx, __pyx_n_s_ids); if (unlikely(!__pyx_tuple__20)) __PYX_ERR(0, 117, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__20); + __Pyx_GIVEREF(__pyx_tuple__20); + __pyx_codeobj__21 = (PyObject*)__Pyx_PyCode_New(2, 0, 0, 5, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__20, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_curated_tokenizers__spp_pyx, __pyx_n_s_encode_as_ids, 117, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__21)) __PYX_ERR(0, 117, __pyx_L1_error) + + /* "curated_tokenizers/_spp.pyx":133 + * return ids + * + * def encode_as_pieces(self, str sentence) -> List[str]: # <<<<<<<<<<<<<< + * """ + * Encodes a string to piece tokens. + */ + __pyx_tuple__22 = PyTuple_Pack(6, __pyx_n_s_self, __pyx_n_s_sentence, __pyx_n_s_text, __pyx_n_s_idx, __pyx_n_s_piece, __pyx_n_s_pieces); if (unlikely(!__pyx_tuple__22)) __PYX_ERR(0, 133, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__22); + __Pyx_GIVEREF(__pyx_tuple__22); + __pyx_codeobj__23 = (PyObject*)__Pyx_PyCode_New(2, 0, 0, 6, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__22, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_curated_tokenizers__spp_pyx, __pyx_n_s_encode_as_pieces, 133, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__23)) __PYX_ERR(0, 133, __pyx_L1_error) + + /* "curated_tokenizers/_spp.pyx":151 + * return pieces + * + * def piece_to_id(self, str piece) -> int: # <<<<<<<<<<<<<< + * """ + * Returns the piece identifier for a given piece token. Returns the + */ + __pyx_tuple__24 = PyTuple_Pack(4, __pyx_n_s_self, __pyx_n_s_piece, __pyx_n_s_piece_bytes, __pyx_n_s_piece_view); if (unlikely(!__pyx_tuple__24)) __PYX_ERR(0, 151, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__24); + __Pyx_GIVEREF(__pyx_tuple__24); + __pyx_codeobj__25 = (PyObject*)__Pyx_PyCode_New(2, 0, 0, 4, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__24, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_curated_tokenizers__spp_pyx, __pyx_n_s_piece_to_id, 151, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__25)) __PYX_ERR(0, 151, __pyx_L1_error) + + /* "curated_tokenizers/_spp.pyx":164 + * return deref(self.spp).PieceToId(piece_view) + * + * def id_to_piece(self, int piece_id) -> str: # <<<<<<<<<<<<<< + * """ + * Returns the piece token for a given piece identifier. Raises a `ValueError` + */ + __pyx_tuple__26 = PyTuple_Pack(3, __pyx_n_s_self, __pyx_n_s_piece_id, __pyx_n_s_vocab_size); if (unlikely(!__pyx_tuple__26)) __PYX_ERR(0, 164, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__26); + __Pyx_GIVEREF(__pyx_tuple__26); + __pyx_codeobj__27 = (PyObject*)__Pyx_PyCode_New(2, 0, 0, 3, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__26, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_curated_tokenizers__spp_pyx, __pyx_n_s_id_to_piece, 164, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__27)) __PYX_ERR(0, 164, __pyx_L1_error) + + /* "curated_tokenizers/_spp.pyx":178 + * return deref(self.spp).IdToPiece(piece_id).decode("utf8") + * + * def bos_id(self) -> int: # <<<<<<<<<<<<<< + * """Returns the piece identifier for the `bos` meta token.""" + * _check_status(deref(self.spp).status()) + */ + __pyx_codeobj__28 = (PyObject*)__Pyx_PyCode_New(1, 0, 0, 1, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__4, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_curated_tokenizers__spp_pyx, __pyx_n_s_bos_id, 178, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__28)) __PYX_ERR(0, 178, __pyx_L1_error) + + /* "curated_tokenizers/_spp.pyx":183 + * return deref(self.spp).bos_id() + * + * def eos_id(self) -> int: # <<<<<<<<<<<<<< + * """Returns the piece identifier for the `eos` meta token.""" + * _check_status(deref(self.spp).status()) + */ + __pyx_codeobj__29 = (PyObject*)__Pyx_PyCode_New(1, 0, 0, 1, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__4, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_curated_tokenizers__spp_pyx, __pyx_n_s_eos_id, 183, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__29)) __PYX_ERR(0, 183, __pyx_L1_error) + + /* "curated_tokenizers/_spp.pyx":188 + * return deref(self.spp).eos_id() + * + * def pad_id(self) -> int: # <<<<<<<<<<<<<< + * """Returns the piece identifier for the `pad` meta token.""" + * _check_status(deref(self.spp).status()) + */ + __pyx_codeobj__30 = (PyObject*)__Pyx_PyCode_New(1, 0, 0, 1, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__4, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_curated_tokenizers__spp_pyx, __pyx_n_s_pad_id, 188, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__30)) __PYX_ERR(0, 188, __pyx_L1_error) + + /* "curated_tokenizers/_spp.pyx":193 + * return deref(self.spp).pad_id() + * + * def unk_id(self) -> int: # <<<<<<<<<<<<<< + * """Returns the piece identifier for the `unk` meta token.""" + * _check_status(deref(self.spp).status()) + */ + __pyx_codeobj__31 = (PyObject*)__Pyx_PyCode_New(1, 0, 0, 1, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__4, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_curated_tokenizers__spp_pyx, __pyx_n_s_unk_id, 193, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__31)) __PYX_ERR(0, 193, __pyx_L1_error) + + /* "curated_tokenizers/_spp.pyx":204 + * return text + * + * def __reduce__(self): # <<<<<<<<<<<<<< + * return (unpickle_sentence_piece_processor, (self.to_protobuf(),)) + * + */ + __pyx_codeobj__32 = (PyObject*)__Pyx_PyCode_New(1, 0, 0, 1, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__4, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_curated_tokenizers__spp_pyx, __pyx_n_s_reduce, 204, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__32)) __PYX_ERR(0, 204, __pyx_L1_error) + + /* "curated_tokenizers/_spp.pyx":218 + * raise ValueError(status.error_message().decode("utf-8")) + * + * def unpickle_sentence_piece_processor(protobuf: bytes) -> SentencePieceProcessor: # <<<<<<<<<<<<<< + * return SentencePieceProcessor.from_protobuf(protobuf) + */ + __pyx_tuple__33 = PyTuple_Pack(1, __pyx_n_s_protobuf); if (unlikely(!__pyx_tuple__33)) __PYX_ERR(0, 218, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__33); + __Pyx_GIVEREF(__pyx_tuple__33); + __pyx_codeobj__34 = (PyObject*)__Pyx_PyCode_New(1, 0, 0, 1, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__33, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_curated_tokenizers__spp_pyx, __pyx_n_s_unpickle_sentence_piece_processo, 218, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__34)) __PYX_ERR(0, 218, __pyx_L1_error) + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_RefNannyFinishContext(); + return -1; +} +/* #### Code section: init_constants ### */ + +static CYTHON_SMALL_CODE int __Pyx_InitConstants(void) { + __pyx_umethod_PyString_Type_encode.type = (PyObject*)&PyString_Type; + __pyx_umethod_PyString_Type_encode.method_name = &__pyx_n_s_encode; + if (__Pyx_CreateStringTabAndInitStrings() < 0) __PYX_ERR(0, 1, __pyx_L1_error); + return 0; + __pyx_L1_error:; + return -1; +} +/* #### Code section: init_globals ### */ + +static CYTHON_SMALL_CODE int __Pyx_InitGlobals(void) { + return 0; +} +/* #### Code section: init_module ### */ + +static CYTHON_SMALL_CODE int __Pyx_modinit_global_init_code(void); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_variable_export_code(void); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_function_export_code(void); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_type_init_code(void); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_type_import_code(void); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_variable_import_code(void); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_function_import_code(void); /*proto*/ + +static int __Pyx_modinit_global_init_code(void) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__Pyx_modinit_global_init_code", 0); + /*--- Global init code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_variable_export_code(void) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__Pyx_modinit_variable_export_code", 0); + /*--- Variable export code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_function_export_code(void) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__Pyx_modinit_function_export_code", 0); + /*--- Function export code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_type_init_code(void) { + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__Pyx_modinit_type_init_code", 0); + /*--- Type init code ---*/ + __pyx_vtabptr_18curated_tokenizers_4_spp_SentencePieceProcessor = &__pyx_vtable_18curated_tokenizers_4_spp_SentencePieceProcessor; + __pyx_vtable_18curated_tokenizers_4_spp_SentencePieceProcessor._encode = (sentencepiece::SentencePieceText (*)(struct __pyx_obj_18curated_tokenizers_4_spp_SentencePieceProcessor *, PyObject *))__pyx_f_18curated_tokenizers_4_spp_22SentencePieceProcessor__encode; + #if CYTHON_USE_TYPE_SPECS + __pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor = (PyTypeObject *) __Pyx_PyType_FromModuleAndSpec(__pyx_m, &__pyx_type_18curated_tokenizers_4_spp_SentencePieceProcessor_spec, NULL); if (unlikely(!__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor)) __PYX_ERR(0, 4, __pyx_L1_error) + if (__Pyx_fix_up_extension_type_from_spec(&__pyx_type_18curated_tokenizers_4_spp_SentencePieceProcessor_spec, __pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor) < 0) __PYX_ERR(0, 4, __pyx_L1_error) + #else + __pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor = &__pyx_type_18curated_tokenizers_4_spp_SentencePieceProcessor; + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + #endif + #if !CYTHON_USE_TYPE_SPECS + if (__Pyx_PyType_Ready(__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor) < 0) __PYX_ERR(0, 4, __pyx_L1_error) + #endif + #if PY_MAJOR_VERSION < 3 + __pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor->tp_print = 0; + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor->tp_dictoffset && __pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor->tp_getattro == PyObject_GenericGetAttr)) { + __pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor->tp_getattro = __Pyx_PyObject_GenericGetAttr; + } + #endif + if (__Pyx_SetVtable(__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor, __pyx_vtabptr_18curated_tokenizers_4_spp_SentencePieceProcessor) < 0) __PYX_ERR(0, 4, __pyx_L1_error) + #if !CYTHON_COMPILING_IN_LIMITED_API + if (__Pyx_MergeVtables(__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor) < 0) __PYX_ERR(0, 4, __pyx_L1_error) + #endif + if (PyObject_SetAttr(__pyx_m, __pyx_n_s_SentencePieceProcessor, (PyObject *) __pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor) < 0) __PYX_ERR(0, 4, __pyx_L1_error) + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_RefNannyFinishContext(); + return -1; +} + +static int __Pyx_modinit_type_import_code(void) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__Pyx_modinit_type_import_code", 0); + /*--- Type import code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_variable_import_code(void) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__Pyx_modinit_variable_import_code", 0); + /*--- Variable import code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_function_import_code(void) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__Pyx_modinit_function_import_code", 0); + /*--- Function import code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + + +#if PY_MAJOR_VERSION >= 3 +#if CYTHON_PEP489_MULTI_PHASE_INIT +static PyObject* __pyx_pymod_create(PyObject *spec, PyModuleDef *def); /*proto*/ +static int __pyx_pymod_exec__spp(PyObject* module); /*proto*/ +static PyModuleDef_Slot __pyx_moduledef_slots[] = { + {Py_mod_create, (void*)__pyx_pymod_create}, + {Py_mod_exec, (void*)__pyx_pymod_exec__spp}, + {0, NULL} +}; +#endif + +#ifdef __cplusplus +namespace { + struct PyModuleDef __pyx_moduledef = + #else + static struct PyModuleDef __pyx_moduledef = + #endif + { + PyModuleDef_HEAD_INIT, + "_spp", + 0, /* m_doc */ + #if CYTHON_PEP489_MULTI_PHASE_INIT + 0, /* m_size */ + #elif CYTHON_USE_MODULE_STATE + sizeof(__pyx_mstate), /* m_size */ + #else + -1, /* m_size */ + #endif + __pyx_methods /* m_methods */, + #if CYTHON_PEP489_MULTI_PHASE_INIT + __pyx_moduledef_slots, /* m_slots */ + #else + NULL, /* m_reload */ + #endif + #if CYTHON_USE_MODULE_STATE + __pyx_m_traverse, /* m_traverse */ + __pyx_m_clear, /* m_clear */ + NULL /* m_free */ + #else + NULL, /* m_traverse */ + NULL, /* m_clear */ + NULL /* m_free */ + #endif + }; + #ifdef __cplusplus +} /* anonymous namespace */ +#endif +#endif + +#ifndef CYTHON_NO_PYINIT_EXPORT +#define __Pyx_PyMODINIT_FUNC PyMODINIT_FUNC +#elif PY_MAJOR_VERSION < 3 +#ifdef __cplusplus +#define __Pyx_PyMODINIT_FUNC extern "C" void +#else +#define __Pyx_PyMODINIT_FUNC void +#endif +#else +#ifdef __cplusplus +#define __Pyx_PyMODINIT_FUNC extern "C" PyObject * +#else +#define __Pyx_PyMODINIT_FUNC PyObject * +#endif +#endif + + +#if PY_MAJOR_VERSION < 3 +__Pyx_PyMODINIT_FUNC init_spp(void) CYTHON_SMALL_CODE; /*proto*/ +__Pyx_PyMODINIT_FUNC init_spp(void) +#else +__Pyx_PyMODINIT_FUNC PyInit__spp(void) CYTHON_SMALL_CODE; /*proto*/ +__Pyx_PyMODINIT_FUNC PyInit__spp(void) +#if CYTHON_PEP489_MULTI_PHASE_INIT +{ + return PyModuleDef_Init(&__pyx_moduledef); +} +static CYTHON_SMALL_CODE int __Pyx_check_single_interpreter(void) { + #if PY_VERSION_HEX >= 0x030700A1 + static PY_INT64_T main_interpreter_id = -1; + PY_INT64_T current_id = PyInterpreterState_GetID(PyThreadState_Get()->interp); + if (main_interpreter_id == -1) { + main_interpreter_id = current_id; + return (unlikely(current_id == -1)) ? -1 : 0; + } else if (unlikely(main_interpreter_id != current_id)) + #else + static PyInterpreterState *main_interpreter = NULL; + PyInterpreterState *current_interpreter = PyThreadState_Get()->interp; + if (!main_interpreter) { + main_interpreter = current_interpreter; + } else if (unlikely(main_interpreter != current_interpreter)) + #endif + { + PyErr_SetString( + PyExc_ImportError, + "Interpreter change detected - this module can only be loaded into one interpreter per process."); + return -1; + } + return 0; +} +#if CYTHON_COMPILING_IN_LIMITED_API +static CYTHON_SMALL_CODE int __Pyx_copy_spec_to_module(PyObject *spec, PyObject *module, const char* from_name, const char* to_name, int allow_none) +#else +static CYTHON_SMALL_CODE int __Pyx_copy_spec_to_module(PyObject *spec, PyObject *moddict, const char* from_name, const char* to_name, int allow_none) +#endif +{ + PyObject *value = PyObject_GetAttrString(spec, from_name); + int result = 0; + if (likely(value)) { + if (allow_none || value != Py_None) { +#if CYTHON_COMPILING_IN_LIMITED_API + result = PyModule_AddObject(module, to_name, value); +#else + result = PyDict_SetItemString(moddict, to_name, value); +#endif + } + Py_DECREF(value); + } else if (PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Clear(); + } else { + result = -1; + } + return result; +} +static CYTHON_SMALL_CODE PyObject* __pyx_pymod_create(PyObject *spec, PyModuleDef *def) { + PyObject *module = NULL, *moddict, *modname; + CYTHON_UNUSED_VAR(def); + if (__Pyx_check_single_interpreter()) + return NULL; + if (__pyx_m) + return __Pyx_NewRef(__pyx_m); + modname = PyObject_GetAttrString(spec, "name"); + if (unlikely(!modname)) goto bad; + module = PyModule_NewObject(modname); + Py_DECREF(modname); + if (unlikely(!module)) goto bad; +#if CYTHON_COMPILING_IN_LIMITED_API + moddict = module; +#else + moddict = PyModule_GetDict(module); + if (unlikely(!moddict)) goto bad; +#endif + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "loader", "__loader__", 1) < 0)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "origin", "__file__", 1) < 0)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "parent", "__package__", 1) < 0)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "submodule_search_locations", "__path__", 0) < 0)) goto bad; + return module; +bad: + Py_XDECREF(module); + return NULL; +} + + +static CYTHON_SMALL_CODE int __pyx_pymod_exec__spp(PyObject *__pyx_pyinit_module) +#endif +#endif +{ + int stringtab_initialized = 0; + #if CYTHON_USE_MODULE_STATE + int pystate_addmodule_run = 0; + #endif + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannyDeclarations + #if CYTHON_PEP489_MULTI_PHASE_INIT + if (__pyx_m) { + if (__pyx_m == __pyx_pyinit_module) return 0; + PyErr_SetString(PyExc_RuntimeError, "Module '_spp' has already been imported. Re-initialisation is not supported."); + return -1; + } + #elif PY_MAJOR_VERSION >= 3 + if (__pyx_m) return __Pyx_NewRef(__pyx_m); + #endif + /*--- Module creation code ---*/ + #if CYTHON_PEP489_MULTI_PHASE_INIT + __pyx_m = __pyx_pyinit_module; + Py_INCREF(__pyx_m); + #else + #if PY_MAJOR_VERSION < 3 + __pyx_m = Py_InitModule4("_spp", __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); + if (unlikely(!__pyx_m)) __PYX_ERR(0, 1, __pyx_L1_error) + #elif CYTHON_USE_MODULE_STATE + __pyx_t_1 = PyModule_Create(&__pyx_moduledef); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1, __pyx_L1_error) + { + int add_module_result = PyState_AddModule(__pyx_t_1, &__pyx_moduledef); + __pyx_t_1 = 0; /* transfer ownership from __pyx_t_1 to "_spp" pseudovariable */ + if (unlikely((add_module_result < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + pystate_addmodule_run = 1; + } + #else + __pyx_m = PyModule_Create(&__pyx_moduledef); + if (unlikely(!__pyx_m)) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + #endif + CYTHON_UNUSED_VAR(__pyx_t_1); + __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) __PYX_ERR(0, 1, __pyx_L1_error) + Py_INCREF(__pyx_d); + __pyx_b = __Pyx_PyImport_AddModuleRef(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_b)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_cython_runtime = __Pyx_PyImport_AddModuleRef((const char *) "cython_runtime"); if (unlikely(!__pyx_cython_runtime)) __PYX_ERR(0, 1, __pyx_L1_error) + if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #if CYTHON_REFNANNY +__Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); +if (!__Pyx_RefNanny) { + PyErr_Clear(); + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); + if (!__Pyx_RefNanny) + Py_FatalError("failed to import 'refnanny' module"); +} +#endif + __Pyx_RefNannySetupContext("__Pyx_PyMODINIT_FUNC PyInit__spp(void)", 0); + if (__Pyx_check_binary_version(__PYX_LIMITED_VERSION_HEX, __Pyx_get_runtime_version(), CYTHON_COMPILING_IN_LIMITED_API) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #ifdef __Pxy_PyFrame_Initialize_Offsets + __Pxy_PyFrame_Initialize_Offsets(); + #endif + __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_empty_unicode = PyUnicode_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_unicode)) __PYX_ERR(0, 1, __pyx_L1_error) + #ifdef __Pyx_CyFunction_USED + if (__pyx_CyFunction_init(__pyx_m) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + #ifdef __Pyx_FusedFunction_USED + if (__pyx_FusedFunction_init(__pyx_m) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + #ifdef __Pyx_Coroutine_USED + if (__pyx_Coroutine_init(__pyx_m) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + #ifdef __Pyx_Generator_USED + if (__pyx_Generator_init(__pyx_m) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + #ifdef __Pyx_AsyncGen_USED + if (__pyx_AsyncGen_init(__pyx_m) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + #ifdef __Pyx_StopAsyncIteration_USED + if (__pyx_StopAsyncIteration_init(__pyx_m) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + /*--- Library function declarations ---*/ + /*--- Threads initialization code ---*/ + #if defined(WITH_THREAD) && PY_VERSION_HEX < 0x030700F0 && defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS + PyEval_InitThreads(); + #endif + /*--- Initialize various global constants etc. ---*/ + if (__Pyx_InitConstants() < 0) __PYX_ERR(0, 1, __pyx_L1_error) + stringtab_initialized = 1; + if (__Pyx_InitGlobals() < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) + if (__Pyx_init_sys_getdefaultencoding_params() < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + if (__pyx_module_is_main_curated_tokenizers___spp) { + if (PyObject_SetAttr(__pyx_m, __pyx_n_s_name, __pyx_n_s_main) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + } + #if PY_MAJOR_VERSION >= 3 + { + PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) __PYX_ERR(0, 1, __pyx_L1_error) + if (!PyDict_GetItemString(modules, "curated_tokenizers._spp")) { + if (unlikely((PyDict_SetItemString(modules, "curated_tokenizers._spp", __pyx_m) < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + } + } + #endif + /*--- Builtin init code ---*/ + if (__Pyx_InitCachedBuiltins() < 0) __PYX_ERR(0, 1, __pyx_L1_error) + /*--- Constants init code ---*/ + if (__Pyx_InitCachedConstants() < 0) __PYX_ERR(0, 1, __pyx_L1_error) + /*--- Global type/function init code ---*/ + (void)__Pyx_modinit_global_init_code(); + (void)__Pyx_modinit_variable_export_code(); + (void)__Pyx_modinit_function_export_code(); + if (unlikely((__Pyx_modinit_type_init_code() < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + (void)__Pyx_modinit_type_import_code(); + (void)__Pyx_modinit_variable_import_code(); + (void)__Pyx_modinit_function_import_code(); + /*--- Execution code ---*/ + #if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED) + if (__Pyx_patch_abc() < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + + /* "curated_tokenizers/_spp.pyx":2 + * from cython.operator cimport dereference as deref + * from typing import List, Tuple # <<<<<<<<<<<<<< + * + * cdef class SentencePieceProcessor: + */ + __pyx_t_2 = PyList_New(2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 2, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_n_s_List); + __Pyx_GIVEREF(__pyx_n_s_List); + if (__Pyx_PyList_SET_ITEM(__pyx_t_2, 0, __pyx_n_s_List)) __PYX_ERR(0, 2, __pyx_L1_error); + __Pyx_INCREF(__pyx_n_s_Tuple); + __Pyx_GIVEREF(__pyx_n_s_Tuple); + if (__Pyx_PyList_SET_ITEM(__pyx_t_2, 1, __pyx_n_s_Tuple)) __PYX_ERR(0, 2, __pyx_L1_error); + __pyx_t_3 = __Pyx_Import(__pyx_n_s_typing, __pyx_t_2, -1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 2, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_3, __pyx_n_s_List); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 2, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_List, __pyx_t_2) < 0) __PYX_ERR(0, 2, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_3, __pyx_n_s_Tuple); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 2, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_Tuple, __pyx_t_2) < 0) __PYX_ERR(0, 2, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "curated_tokenizers/_spp.pyx":15 + * return deref(self.spp).GetPieceSize() + * + * def __copy__(self): # <<<<<<<<<<<<<< + * return SentencePieceProcessor.from_protobuf(self.to_protobuf()) + * + */ + __pyx_t_3 = __Pyx_CyFunction_New(&__pyx_mdef_18curated_tokenizers_4_spp_22SentencePieceProcessor_7__copy__, __Pyx_CYFUNCTION_CCLASS, __pyx_n_s_SentencePieceProcessor___copy, NULL, __pyx_n_s_curated_tokenizers__spp, __pyx_d, ((PyObject *)__pyx_codeobj__5)); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 15, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + if (__Pyx_SetItemOnTypeDict((PyObject *)__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor, __pyx_n_s_copy, __pyx_t_3) < 0) __PYX_ERR(0, 15, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + PyType_Modified(__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor); + + /* "curated_tokenizers/_spp.pyx":18 + * return SentencePieceProcessor.from_protobuf(self.to_protobuf()) + * + * def __deepcopy__(self, memo): # <<<<<<<<<<<<<< + * result = SentencePieceProcessor.from_protobuf(self.to_protobuf()) + * memo[id(self)] = result + */ + __pyx_t_3 = __Pyx_CyFunction_New(&__pyx_mdef_18curated_tokenizers_4_spp_22SentencePieceProcessor_9__deepcopy__, __Pyx_CYFUNCTION_CCLASS, __pyx_n_s_SentencePieceProcessor___deepcop, NULL, __pyx_n_s_curated_tokenizers__spp, __pyx_d, ((PyObject *)__pyx_codeobj__7)); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 18, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + if (__Pyx_SetItemOnTypeDict((PyObject *)__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor, __pyx_n_s_deepcopy, __pyx_t_3) < 0) __PYX_ERR(0, 18, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + PyType_Modified(__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor); + + /* "curated_tokenizers/_spp.pyx":23 + * return result + * + * @staticmethod # <<<<<<<<<<<<<< + * def from_file(str filename): + * """ + */ + __pyx_t_3 = __Pyx_CyFunction_New(&__pyx_mdef_18curated_tokenizers_4_spp_22SentencePieceProcessor_11from_file, __Pyx_CYFUNCTION_STATICMETHOD | __Pyx_CYFUNCTION_CCLASS, __pyx_n_s_SentencePieceProcessor_from_file, NULL, __pyx_n_s_curated_tokenizers__spp, __pyx_d, ((PyObject *)__pyx_codeobj__9)); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 23, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + if (__Pyx_SetItemOnTypeDict((PyObject *)__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor, __pyx_n_s_from_file, __pyx_t_3) < 0) __PYX_ERR(0, 23, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + PyType_Modified(__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor); + __Pyx_GetNameInClass(__pyx_t_3, (PyObject *)__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor, __pyx_n_s_from_file); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 23, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_builtin_staticmethod, __pyx_t_3); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 23, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__Pyx_SetItemOnTypeDict((PyObject *)__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor, __pyx_n_s_from_file, __pyx_t_2) < 0) __PYX_ERR(0, 23, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + PyType_Modified(__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor); + + /* "curated_tokenizers/_spp.pyx":35 + * return processor + * + * @staticmethod # <<<<<<<<<<<<<< + * def from_protobuf(bytes protobuf): + * """ + */ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_18curated_tokenizers_4_spp_22SentencePieceProcessor_13from_protobuf, __Pyx_CYFUNCTION_STATICMETHOD | __Pyx_CYFUNCTION_CCLASS, __pyx_n_s_SentencePieceProcessor_from_prot, NULL, __pyx_n_s_curated_tokenizers__spp, __pyx_d, ((PyObject *)__pyx_codeobj__11)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 35, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_SetItemOnTypeDict((PyObject *)__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor, __pyx_n_s_from_protobuf, __pyx_t_2) < 0) __PYX_ERR(0, 35, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + PyType_Modified(__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor); + __Pyx_GetNameInClass(__pyx_t_2, (PyObject *)__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor, __pyx_n_s_from_protobuf); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 35, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_builtin_staticmethod, __pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 35, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (__Pyx_SetItemOnTypeDict((PyObject *)__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor, __pyx_n_s_from_protobuf, __pyx_t_3) < 0) __PYX_ERR(0, 35, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + PyType_Modified(__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor); + + /* "curated_tokenizers/_spp.pyx":52 + * return processor + * + * def to_protobuf(self) -> bytes: # <<<<<<<<<<<<<< + * """ + * Serializes the SentencePieceProcessor to a protocol buffer. + */ + __pyx_t_3 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 52, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_return, __pyx_n_s_bytes) < 0) __PYX_ERR(0, 52, __pyx_L1_error) + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_18curated_tokenizers_4_spp_22SentencePieceProcessor_15to_protobuf, __Pyx_CYFUNCTION_CCLASS, __pyx_n_s_SentencePieceProcessor_to_protob, NULL, __pyx_n_s_curated_tokenizers__spp, __pyx_d, ((PyObject *)__pyx_codeobj__13)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 52, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_CyFunction_SetAnnotationsDict(__pyx_t_2, __pyx_t_3); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__Pyx_SetItemOnTypeDict((PyObject *)__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor, __pyx_n_s_to_protobuf, __pyx_t_2) < 0) __PYX_ERR(0, 52, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + PyType_Modified(__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor); + + /* "curated_tokenizers/_spp.pyx":62 + * return bytes(serialized) + * + * def decode_from_ids(self, list ids) -> str: # <<<<<<<<<<<<<< + * """ + * Decodes piece indentifiers to a string. Raises a `ValueError` if the + */ + __pyx_t_2 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 62, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_return, __pyx_n_s_str) < 0) __PYX_ERR(0, 62, __pyx_L1_error) + __pyx_t_3 = __Pyx_CyFunction_New(&__pyx_mdef_18curated_tokenizers_4_spp_22SentencePieceProcessor_17decode_from_ids, __Pyx_CYFUNCTION_CCLASS, __pyx_n_s_SentencePieceProcessor_decode_fr, NULL, __pyx_n_s_curated_tokenizers__spp, __pyx_d, ((PyObject *)__pyx_codeobj__15)); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 62, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_CyFunction_SetAnnotationsDict(__pyx_t_3, __pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (__Pyx_SetItemOnTypeDict((PyObject *)__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor, __pyx_n_s_decode_from_ids, __pyx_t_3) < 0) __PYX_ERR(0, 62, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + PyType_Modified(__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor); + + /* "curated_tokenizers/_spp.pyx":79 + * return output.decode("utf-8") + * + * def decode_from_pieces(self, list pieces) -> str: # <<<<<<<<<<<<<< + * """ + * Decodes piece tokens to a string. Raises a `ValueError` if the + */ + __pyx_t_3 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 79, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_return, __pyx_n_s_str) < 0) __PYX_ERR(0, 79, __pyx_L1_error) + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_18curated_tokenizers_4_spp_22SentencePieceProcessor_19decode_from_pieces, __Pyx_CYFUNCTION_CCLASS, __pyx_n_s_SentencePieceProcessor_decode_fr_2, NULL, __pyx_n_s_curated_tokenizers__spp, __pyx_d, ((PyObject *)__pyx_codeobj__17)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 79, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_CyFunction_SetAnnotationsDict(__pyx_t_2, __pyx_t_3); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__Pyx_SetItemOnTypeDict((PyObject *)__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor, __pyx_n_s_decode_from_pieces, __pyx_t_2) < 0) __PYX_ERR(0, 79, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + PyType_Modified(__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor); + + /* "curated_tokenizers/_spp.pyx":96 + * return output.decode("utf-8") + * + * def encode(self, str sentence) -> Tuple[List[int], List[str]]: # <<<<<<<<<<<<<< + * """ + * Encodes a string to piece indentifiers and piece tokens. + */ + __pyx_t_2 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 96, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_return, __pyx_kp_s_Tuple_List_int_List_str) < 0) __PYX_ERR(0, 96, __pyx_L1_error) + __pyx_t_3 = __Pyx_CyFunction_New(&__pyx_mdef_18curated_tokenizers_4_spp_22SentencePieceProcessor_21encode, __Pyx_CYFUNCTION_CCLASS, __pyx_n_s_SentencePieceProcessor_encode, NULL, __pyx_n_s_curated_tokenizers__spp, __pyx_d, ((PyObject *)__pyx_codeobj__19)); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 96, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_CyFunction_SetAnnotationsDict(__pyx_t_3, __pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (__Pyx_SetItemOnTypeDict((PyObject *)__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor, __pyx_n_s_encode, __pyx_t_3) < 0) __PYX_ERR(0, 96, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + PyType_Modified(__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor); + + /* "curated_tokenizers/_spp.pyx":117 + * return ids, pieces + * + * def encode_as_ids(self, str sentence) -> List[int]: # <<<<<<<<<<<<<< + * """ + * Encodes a string to piece indentifiers. + */ + __pyx_t_3 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 117, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_return, __pyx_kp_s_List_int) < 0) __PYX_ERR(0, 117, __pyx_L1_error) + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_18curated_tokenizers_4_spp_22SentencePieceProcessor_23encode_as_ids, __Pyx_CYFUNCTION_CCLASS, __pyx_n_s_SentencePieceProcessor_encode_as, NULL, __pyx_n_s_curated_tokenizers__spp, __pyx_d, ((PyObject *)__pyx_codeobj__21)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 117, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_CyFunction_SetAnnotationsDict(__pyx_t_2, __pyx_t_3); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__Pyx_SetItemOnTypeDict((PyObject *)__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor, __pyx_n_s_encode_as_ids, __pyx_t_2) < 0) __PYX_ERR(0, 117, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + PyType_Modified(__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor); + + /* "curated_tokenizers/_spp.pyx":133 + * return ids + * + * def encode_as_pieces(self, str sentence) -> List[str]: # <<<<<<<<<<<<<< + * """ + * Encodes a string to piece tokens. + */ + __pyx_t_2 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 133, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_return, __pyx_kp_s_List_str) < 0) __PYX_ERR(0, 133, __pyx_L1_error) + __pyx_t_3 = __Pyx_CyFunction_New(&__pyx_mdef_18curated_tokenizers_4_spp_22SentencePieceProcessor_25encode_as_pieces, __Pyx_CYFUNCTION_CCLASS, __pyx_n_s_SentencePieceProcessor_encode_as_2, NULL, __pyx_n_s_curated_tokenizers__spp, __pyx_d, ((PyObject *)__pyx_codeobj__23)); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 133, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_CyFunction_SetAnnotationsDict(__pyx_t_3, __pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (__Pyx_SetItemOnTypeDict((PyObject *)__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor, __pyx_n_s_encode_as_pieces, __pyx_t_3) < 0) __PYX_ERR(0, 133, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + PyType_Modified(__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor); + + /* "curated_tokenizers/_spp.pyx":151 + * return pieces + * + * def piece_to_id(self, str piece) -> int: # <<<<<<<<<<<<<< + * """ + * Returns the piece identifier for a given piece token. Returns the + */ + __pyx_t_3 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 151, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_return, __pyx_n_s_int) < 0) __PYX_ERR(0, 151, __pyx_L1_error) + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_18curated_tokenizers_4_spp_22SentencePieceProcessor_27piece_to_id, __Pyx_CYFUNCTION_CCLASS, __pyx_n_s_SentencePieceProcessor_piece_to, NULL, __pyx_n_s_curated_tokenizers__spp, __pyx_d, ((PyObject *)__pyx_codeobj__25)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 151, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_CyFunction_SetAnnotationsDict(__pyx_t_2, __pyx_t_3); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__Pyx_SetItemOnTypeDict((PyObject *)__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor, __pyx_n_s_piece_to_id, __pyx_t_2) < 0) __PYX_ERR(0, 151, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + PyType_Modified(__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor); + + /* "curated_tokenizers/_spp.pyx":164 + * return deref(self.spp).PieceToId(piece_view) + * + * def id_to_piece(self, int piece_id) -> str: # <<<<<<<<<<<<<< + * """ + * Returns the piece token for a given piece identifier. Raises a `ValueError` + */ + __pyx_t_2 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 164, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_return, __pyx_n_s_str) < 0) __PYX_ERR(0, 164, __pyx_L1_error) + __pyx_t_3 = __Pyx_CyFunction_New(&__pyx_mdef_18curated_tokenizers_4_spp_22SentencePieceProcessor_29id_to_piece, __Pyx_CYFUNCTION_CCLASS, __pyx_n_s_SentencePieceProcessor_id_to_pie, NULL, __pyx_n_s_curated_tokenizers__spp, __pyx_d, ((PyObject *)__pyx_codeobj__27)); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 164, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_CyFunction_SetAnnotationsDict(__pyx_t_3, __pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (__Pyx_SetItemOnTypeDict((PyObject *)__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor, __pyx_n_s_id_to_piece, __pyx_t_3) < 0) __PYX_ERR(0, 164, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + PyType_Modified(__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor); + + /* "curated_tokenizers/_spp.pyx":178 + * return deref(self.spp).IdToPiece(piece_id).decode("utf8") + * + * def bos_id(self) -> int: # <<<<<<<<<<<<<< + * """Returns the piece identifier for the `bos` meta token.""" + * _check_status(deref(self.spp).status()) + */ + __pyx_t_3 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 178, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_return, __pyx_n_s_int) < 0) __PYX_ERR(0, 178, __pyx_L1_error) + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_18curated_tokenizers_4_spp_22SentencePieceProcessor_31bos_id, __Pyx_CYFUNCTION_CCLASS, __pyx_n_s_SentencePieceProcessor_bos_id, NULL, __pyx_n_s_curated_tokenizers__spp, __pyx_d, ((PyObject *)__pyx_codeobj__28)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 178, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_CyFunction_SetAnnotationsDict(__pyx_t_2, __pyx_t_3); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__Pyx_SetItemOnTypeDict((PyObject *)__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor, __pyx_n_s_bos_id, __pyx_t_2) < 0) __PYX_ERR(0, 178, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + PyType_Modified(__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor); + + /* "curated_tokenizers/_spp.pyx":183 + * return deref(self.spp).bos_id() + * + * def eos_id(self) -> int: # <<<<<<<<<<<<<< + * """Returns the piece identifier for the `eos` meta token.""" + * _check_status(deref(self.spp).status()) + */ + __pyx_t_2 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 183, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_return, __pyx_n_s_int) < 0) __PYX_ERR(0, 183, __pyx_L1_error) + __pyx_t_3 = __Pyx_CyFunction_New(&__pyx_mdef_18curated_tokenizers_4_spp_22SentencePieceProcessor_33eos_id, __Pyx_CYFUNCTION_CCLASS, __pyx_n_s_SentencePieceProcessor_eos_id, NULL, __pyx_n_s_curated_tokenizers__spp, __pyx_d, ((PyObject *)__pyx_codeobj__29)); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 183, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_CyFunction_SetAnnotationsDict(__pyx_t_3, __pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (__Pyx_SetItemOnTypeDict((PyObject *)__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor, __pyx_n_s_eos_id, __pyx_t_3) < 0) __PYX_ERR(0, 183, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + PyType_Modified(__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor); + + /* "curated_tokenizers/_spp.pyx":188 + * return deref(self.spp).eos_id() + * + * def pad_id(self) -> int: # <<<<<<<<<<<<<< + * """Returns the piece identifier for the `pad` meta token.""" + * _check_status(deref(self.spp).status()) + */ + __pyx_t_3 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 188, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_return, __pyx_n_s_int) < 0) __PYX_ERR(0, 188, __pyx_L1_error) + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_18curated_tokenizers_4_spp_22SentencePieceProcessor_35pad_id, __Pyx_CYFUNCTION_CCLASS, __pyx_n_s_SentencePieceProcessor_pad_id, NULL, __pyx_n_s_curated_tokenizers__spp, __pyx_d, ((PyObject *)__pyx_codeobj__30)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 188, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_CyFunction_SetAnnotationsDict(__pyx_t_2, __pyx_t_3); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__Pyx_SetItemOnTypeDict((PyObject *)__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor, __pyx_n_s_pad_id, __pyx_t_2) < 0) __PYX_ERR(0, 188, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + PyType_Modified(__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor); + + /* "curated_tokenizers/_spp.pyx":193 + * return deref(self.spp).pad_id() + * + * def unk_id(self) -> int: # <<<<<<<<<<<<<< + * """Returns the piece identifier for the `unk` meta token.""" + * _check_status(deref(self.spp).status()) + */ + __pyx_t_2 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 193, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_return, __pyx_n_s_int) < 0) __PYX_ERR(0, 193, __pyx_L1_error) + __pyx_t_3 = __Pyx_CyFunction_New(&__pyx_mdef_18curated_tokenizers_4_spp_22SentencePieceProcessor_37unk_id, __Pyx_CYFUNCTION_CCLASS, __pyx_n_s_SentencePieceProcessor_unk_id, NULL, __pyx_n_s_curated_tokenizers__spp, __pyx_d, ((PyObject *)__pyx_codeobj__31)); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 193, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_CyFunction_SetAnnotationsDict(__pyx_t_3, __pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (__Pyx_SetItemOnTypeDict((PyObject *)__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor, __pyx_n_s_unk_id, __pyx_t_3) < 0) __PYX_ERR(0, 193, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + PyType_Modified(__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor); + + /* "curated_tokenizers/_spp.pyx":204 + * return text + * + * def __reduce__(self): # <<<<<<<<<<<<<< + * return (unpickle_sentence_piece_processor, (self.to_protobuf(),)) + * + */ + __pyx_t_3 = __Pyx_CyFunction_New(&__pyx_mdef_18curated_tokenizers_4_spp_22SentencePieceProcessor_39__reduce__, __Pyx_CYFUNCTION_CCLASS, __pyx_n_s_SentencePieceProcessor___reduce, NULL, __pyx_n_s_curated_tokenizers__spp, __pyx_d, ((PyObject *)__pyx_codeobj__32)); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 204, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + if (__Pyx_SetItemOnTypeDict((PyObject *)__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor, __pyx_n_s_reduce, __pyx_t_3) < 0) __PYX_ERR(0, 204, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + PyType_Modified(__pyx_ptype_18curated_tokenizers_4_spp_SentencePieceProcessor); + + /* "curated_tokenizers/_spp.pyx":218 + * raise ValueError(status.error_message().decode("utf-8")) + * + * def unpickle_sentence_piece_processor(protobuf: bytes) -> SentencePieceProcessor: # <<<<<<<<<<<<<< + * return SentencePieceProcessor.from_protobuf(protobuf) + */ + __pyx_t_3 = __Pyx_PyDict_NewPresized(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 218, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_protobuf, __pyx_n_s_bytes) < 0) __PYX_ERR(0, 218, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_return, __pyx_n_s_SentencePieceProcessor) < 0) __PYX_ERR(0, 218, __pyx_L1_error) + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_18curated_tokenizers_4_spp_1unpickle_sentence_piece_processor, 0, __pyx_n_s_unpickle_sentence_piece_processo, NULL, __pyx_n_s_curated_tokenizers__spp, __pyx_d, ((PyObject *)__pyx_codeobj__34)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 218, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_CyFunction_SetAnnotationsDict(__pyx_t_2, __pyx_t_3); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (PyDict_SetItem(__pyx_d, __pyx_n_s_unpickle_sentence_piece_processo, __pyx_t_2) < 0) __PYX_ERR(0, 218, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "curated_tokenizers/_spp.pyx":1 + * from cython.operator cimport dereference as deref # <<<<<<<<<<<<<< + * from typing import List, Tuple + * + */ + __pyx_t_2 = __Pyx_PyDict_NewPresized(0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_2) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /*--- Wrapped vars code ---*/ + + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + if (__pyx_m) { + if (__pyx_d && stringtab_initialized) { + __Pyx_AddTraceback("init curated_tokenizers._spp", __pyx_clineno, __pyx_lineno, __pyx_filename); + } + #if !CYTHON_USE_MODULE_STATE + Py_CLEAR(__pyx_m); + #else + Py_DECREF(__pyx_m); + if (pystate_addmodule_run) { + PyObject *tp, *value, *tb; + PyErr_Fetch(&tp, &value, &tb); + PyState_RemoveModule(&__pyx_moduledef); + PyErr_Restore(tp, value, tb); + } + #endif + } else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_ImportError, "init curated_tokenizers._spp"); + } + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + #if CYTHON_PEP489_MULTI_PHASE_INIT + return (__pyx_m != NULL) ? 0 : -1; + #elif PY_MAJOR_VERSION >= 3 + return __pyx_m; + #else + return; + #endif +} +/* #### Code section: cleanup_globals ### */ +/* #### Code section: cleanup_module ### */ +/* #### Code section: main_method ### */ +/* #### Code section: utility_code_pragmas ### */ +#ifdef _MSC_VER +#pragma warning( push ) +/* Warning 4127: conditional expression is constant + * Cython uses constant conditional expressions to allow in inline functions to be optimized at + * compile-time, so this warning is not useful + */ +#pragma warning( disable : 4127 ) +#endif + + + +/* #### Code section: utility_code_def ### */ + +/* --- Runtime support code --- */ +/* Refnanny */ +#if CYTHON_REFNANNY +static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { + PyObject *m = NULL, *p = NULL; + void *r = NULL; + m = PyImport_ImportModule(modname); + if (!m) goto end; + p = PyObject_GetAttrString(m, "RefNannyAPI"); + if (!p) goto end; + r = PyLong_AsVoidPtr(p); +end: + Py_XDECREF(p); + Py_XDECREF(m); + return (__Pyx_RefNannyAPIStruct *)r; +} +#endif + +/* PyErrExceptionMatches */ +#if CYTHON_FAST_THREAD_STATE +static int __Pyx_PyErr_ExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { + Py_ssize_t i, n; + n = PyTuple_GET_SIZE(tuple); +#if PY_MAJOR_VERSION >= 3 + for (i=0; i= 0x030C00A6 + PyObject *current_exception = tstate->current_exception; + if (unlikely(!current_exception)) return 0; + exc_type = (PyObject*) Py_TYPE(current_exception); + if (exc_type == err) return 1; +#else + exc_type = tstate->curexc_type; + if (exc_type == err) return 1; + if (unlikely(!exc_type)) return 0; +#endif + #if CYTHON_AVOID_BORROWED_REFS + Py_INCREF(exc_type); + #endif + if (unlikely(PyTuple_Check(err))) { + result = __Pyx_PyErr_ExceptionMatchesTuple(exc_type, err); + } else { + result = __Pyx_PyErr_GivenExceptionMatches(exc_type, err); + } + #if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(exc_type); + #endif + return result; +} +#endif + +/* PyErrFetchRestore */ +#if CYTHON_FAST_THREAD_STATE +static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { +#if PY_VERSION_HEX >= 0x030C00A6 + PyObject *tmp_value; + assert(type == NULL || (value != NULL && type == (PyObject*) Py_TYPE(value))); + if (value) { + #if CYTHON_COMPILING_IN_CPYTHON + if (unlikely(((PyBaseExceptionObject*) value)->traceback != tb)) + #endif + PyException_SetTraceback(value, tb); + } + tmp_value = tstate->current_exception; + tstate->current_exception = value; + Py_XDECREF(tmp_value); + Py_XDECREF(type); + Py_XDECREF(tb); +#else + PyObject *tmp_type, *tmp_value, *tmp_tb; + tmp_type = tstate->curexc_type; + tmp_value = tstate->curexc_value; + tmp_tb = tstate->curexc_traceback; + tstate->curexc_type = type; + tstate->curexc_value = value; + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#endif +} +static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { +#if PY_VERSION_HEX >= 0x030C00A6 + PyObject* exc_value; + exc_value = tstate->current_exception; + tstate->current_exception = 0; + *value = exc_value; + *type = NULL; + *tb = NULL; + if (exc_value) { + *type = (PyObject*) Py_TYPE(exc_value); + Py_INCREF(*type); + #if CYTHON_COMPILING_IN_CPYTHON + *tb = ((PyBaseExceptionObject*) exc_value)->traceback; + Py_XINCREF(*tb); + #else + *tb = PyException_GetTraceback(exc_value); + #endif + } +#else + *type = tstate->curexc_type; + *value = tstate->curexc_value; + *tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; +#endif +} +#endif + +/* PyObjectGetAttrStr */ +#if CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro)) + return tp->tp_getattro(obj, attr_name); +#if PY_MAJOR_VERSION < 3 + if (likely(tp->tp_getattr)) + return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); +#endif + return PyObject_GetAttr(obj, attr_name); +} +#endif + +/* PyObjectGetAttrStrNoError */ +#if __PYX_LIMITED_VERSION_HEX < 0x030d00A1 +static void __Pyx_PyObject_GetAttrStr_ClearAttributeError(void) { + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + if (likely(__Pyx_PyErr_ExceptionMatches(PyExc_AttributeError))) + __Pyx_PyErr_Clear(); +} +#endif +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStrNoError(PyObject* obj, PyObject* attr_name) { + PyObject *result; +#if __PYX_LIMITED_VERSION_HEX >= 0x030d00A1 + (void) PyObject_GetOptionalAttr(obj, attr_name, &result); + return result; +#else +#if CYTHON_COMPILING_IN_CPYTHON && CYTHON_USE_TYPE_SLOTS && PY_VERSION_HEX >= 0x030700B1 + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro == PyObject_GenericGetAttr)) { + return _PyObject_GenericGetAttrWithDict(obj, attr_name, NULL, 1); + } +#endif + result = __Pyx_PyObject_GetAttrStr(obj, attr_name); + if (unlikely(!result)) { + __Pyx_PyObject_GetAttrStr_ClearAttributeError(); + } + return result; +#endif +} + +/* GetBuiltinName */ +static PyObject *__Pyx_GetBuiltinName(PyObject *name) { + PyObject* result = __Pyx_PyObject_GetAttrStrNoError(__pyx_b, name); + if (unlikely(!result) && !PyErr_Occurred()) { + PyErr_Format(PyExc_NameError, +#if PY_MAJOR_VERSION >= 3 + "name '%U' is not defined", name); +#else + "name '%.200s' is not defined", PyString_AS_STRING(name)); +#endif + } + return result; +} + +/* TupleAndListFromArray */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE void __Pyx_copy_object_array(PyObject *const *CYTHON_RESTRICT src, PyObject** CYTHON_RESTRICT dest, Py_ssize_t length) { + PyObject *v; + Py_ssize_t i; + for (i = 0; i < length; i++) { + v = dest[i] = src[i]; + Py_INCREF(v); + } +} +static CYTHON_INLINE PyObject * +__Pyx_PyTuple_FromArray(PyObject *const *src, Py_ssize_t n) +{ + PyObject *res; + if (n <= 0) { + Py_INCREF(__pyx_empty_tuple); + return __pyx_empty_tuple; + } + res = PyTuple_New(n); + if (unlikely(res == NULL)) return NULL; + __Pyx_copy_object_array(src, ((PyTupleObject*)res)->ob_item, n); + return res; +} +static CYTHON_INLINE PyObject * +__Pyx_PyList_FromArray(PyObject *const *src, Py_ssize_t n) +{ + PyObject *res; + if (n <= 0) { + return PyList_New(0); + } + res = PyList_New(n); + if (unlikely(res == NULL)) return NULL; + __Pyx_copy_object_array(src, ((PyListObject*)res)->ob_item, n); + return res; +} +#endif + +/* BytesEquals */ +static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals) { +#if CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API + return PyObject_RichCompareBool(s1, s2, equals); +#else + if (s1 == s2) { + return (equals == Py_EQ); + } else if (PyBytes_CheckExact(s1) & PyBytes_CheckExact(s2)) { + const char *ps1, *ps2; + Py_ssize_t length = PyBytes_GET_SIZE(s1); + if (length != PyBytes_GET_SIZE(s2)) + return (equals == Py_NE); + ps1 = PyBytes_AS_STRING(s1); + ps2 = PyBytes_AS_STRING(s2); + if (ps1[0] != ps2[0]) { + return (equals == Py_NE); + } else if (length == 1) { + return (equals == Py_EQ); + } else { + int result; +#if CYTHON_USE_UNICODE_INTERNALS && (PY_VERSION_HEX < 0x030B0000) + Py_hash_t hash1, hash2; + hash1 = ((PyBytesObject*)s1)->ob_shash; + hash2 = ((PyBytesObject*)s2)->ob_shash; + if (hash1 != hash2 && hash1 != -1 && hash2 != -1) { + return (equals == Py_NE); + } +#endif + result = memcmp(ps1, ps2, (size_t)length); + return (equals == Py_EQ) ? (result == 0) : (result != 0); + } + } else if ((s1 == Py_None) & PyBytes_CheckExact(s2)) { + return (equals == Py_NE); + } else if ((s2 == Py_None) & PyBytes_CheckExact(s1)) { + return (equals == Py_NE); + } else { + int result; + PyObject* py_result = PyObject_RichCompare(s1, s2, equals); + if (!py_result) + return -1; + result = __Pyx_PyObject_IsTrue(py_result); + Py_DECREF(py_result); + return result; + } +#endif +} + +/* UnicodeEquals */ +static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals) { +#if CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API + return PyObject_RichCompareBool(s1, s2, equals); +#else +#if PY_MAJOR_VERSION < 3 + PyObject* owned_ref = NULL; +#endif + int s1_is_unicode, s2_is_unicode; + if (s1 == s2) { + goto return_eq; + } + s1_is_unicode = PyUnicode_CheckExact(s1); + s2_is_unicode = PyUnicode_CheckExact(s2); +#if PY_MAJOR_VERSION < 3 + if ((s1_is_unicode & (!s2_is_unicode)) && PyString_CheckExact(s2)) { + owned_ref = PyUnicode_FromObject(s2); + if (unlikely(!owned_ref)) + return -1; + s2 = owned_ref; + s2_is_unicode = 1; + } else if ((s2_is_unicode & (!s1_is_unicode)) && PyString_CheckExact(s1)) { + owned_ref = PyUnicode_FromObject(s1); + if (unlikely(!owned_ref)) + return -1; + s1 = owned_ref; + s1_is_unicode = 1; + } else if (((!s2_is_unicode) & (!s1_is_unicode))) { + return __Pyx_PyBytes_Equals(s1, s2, equals); + } +#endif + if (s1_is_unicode & s2_is_unicode) { + Py_ssize_t length; + int kind; + void *data1, *data2; + if (unlikely(__Pyx_PyUnicode_READY(s1) < 0) || unlikely(__Pyx_PyUnicode_READY(s2) < 0)) + return -1; + length = __Pyx_PyUnicode_GET_LENGTH(s1); + if (length != __Pyx_PyUnicode_GET_LENGTH(s2)) { + goto return_ne; + } +#if CYTHON_USE_UNICODE_INTERNALS + { + Py_hash_t hash1, hash2; + #if CYTHON_PEP393_ENABLED + hash1 = ((PyASCIIObject*)s1)->hash; + hash2 = ((PyASCIIObject*)s2)->hash; + #else + hash1 = ((PyUnicodeObject*)s1)->hash; + hash2 = ((PyUnicodeObject*)s2)->hash; + #endif + if (hash1 != hash2 && hash1 != -1 && hash2 != -1) { + goto return_ne; + } + } +#endif + kind = __Pyx_PyUnicode_KIND(s1); + if (kind != __Pyx_PyUnicode_KIND(s2)) { + goto return_ne; + } + data1 = __Pyx_PyUnicode_DATA(s1); + data2 = __Pyx_PyUnicode_DATA(s2); + if (__Pyx_PyUnicode_READ(kind, data1, 0) != __Pyx_PyUnicode_READ(kind, data2, 0)) { + goto return_ne; + } else if (length == 1) { + goto return_eq; + } else { + int result = memcmp(data1, data2, (size_t)(length * kind)); + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(owned_ref); + #endif + return (equals == Py_EQ) ? (result == 0) : (result != 0); + } + } else if ((s1 == Py_None) & s2_is_unicode) { + goto return_ne; + } else if ((s2 == Py_None) & s1_is_unicode) { + goto return_ne; + } else { + int result; + PyObject* py_result = PyObject_RichCompare(s1, s2, equals); + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(owned_ref); + #endif + if (!py_result) + return -1; + result = __Pyx_PyObject_IsTrue(py_result); + Py_DECREF(py_result); + return result; + } +return_eq: + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(owned_ref); + #endif + return (equals == Py_EQ); +return_ne: + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(owned_ref); + #endif + return (equals == Py_NE); +#endif +} + +/* fastcall */ +#if CYTHON_METH_FASTCALL +static CYTHON_INLINE PyObject * __Pyx_GetKwValue_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues, PyObject *s) +{ + Py_ssize_t i, n = PyTuple_GET_SIZE(kwnames); + for (i = 0; i < n; i++) + { + if (s == PyTuple_GET_ITEM(kwnames, i)) return kwvalues[i]; + } + for (i = 0; i < n; i++) + { + int eq = __Pyx_PyUnicode_Equals(s, PyTuple_GET_ITEM(kwnames, i), Py_EQ); + if (unlikely(eq != 0)) { + if (unlikely(eq < 0)) return NULL; + return kwvalues[i]; + } + } + return NULL; +} +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030d0000 +CYTHON_UNUSED static PyObject *__Pyx_KwargsAsDict_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues) { + Py_ssize_t i, nkwargs = PyTuple_GET_SIZE(kwnames); + PyObject *dict; + dict = PyDict_New(); + if (unlikely(!dict)) + return NULL; + for (i=0; irecursion_depth; + Py_DECREF(f); + --tstate->recursion_depth; + return result; +} +static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, Py_ssize_t nargs, PyObject *kwargs) { + PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func); + PyObject *globals = PyFunction_GET_GLOBALS(func); + PyObject *argdefs = PyFunction_GET_DEFAULTS(func); + PyObject *closure; +#if PY_MAJOR_VERSION >= 3 + PyObject *kwdefs; +#endif + PyObject *kwtuple, **k; + PyObject **d; + Py_ssize_t nd; + Py_ssize_t nk; + PyObject *result; + assert(kwargs == NULL || PyDict_Check(kwargs)); + nk = kwargs ? PyDict_Size(kwargs) : 0; + #if PY_MAJOR_VERSION < 3 + if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) { + return NULL; + } + #else + if (unlikely(Py_EnterRecursiveCall(" while calling a Python object"))) { + return NULL; + } + #endif + if ( +#if PY_MAJOR_VERSION >= 3 + co->co_kwonlyargcount == 0 && +#endif + likely(kwargs == NULL || nk == 0) && + co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) { + if (argdefs == NULL && co->co_argcount == nargs) { + result = __Pyx_PyFunction_FastCallNoKw(co, args, nargs, globals); + goto done; + } + else if (nargs == 0 && argdefs != NULL + && co->co_argcount == Py_SIZE(argdefs)) { + /* function called with no arguments, but all parameters have + a default value: use default values as arguments .*/ + args = &PyTuple_GET_ITEM(argdefs, 0); + result =__Pyx_PyFunction_FastCallNoKw(co, args, Py_SIZE(argdefs), globals); + goto done; + } + } + if (kwargs != NULL) { + Py_ssize_t pos, i; + kwtuple = PyTuple_New(2 * nk); + if (kwtuple == NULL) { + result = NULL; + goto done; + } + k = &PyTuple_GET_ITEM(kwtuple, 0); + pos = i = 0; + while (PyDict_Next(kwargs, &pos, &k[i], &k[i+1])) { + Py_INCREF(k[i]); + Py_INCREF(k[i+1]); + i += 2; + } + nk = i / 2; + } + else { + kwtuple = NULL; + k = NULL; + } + closure = PyFunction_GET_CLOSURE(func); +#if PY_MAJOR_VERSION >= 3 + kwdefs = PyFunction_GET_KW_DEFAULTS(func); +#endif + if (argdefs != NULL) { + d = &PyTuple_GET_ITEM(argdefs, 0); + nd = Py_SIZE(argdefs); + } + else { + d = NULL; + nd = 0; + } +#if PY_MAJOR_VERSION >= 3 + result = PyEval_EvalCodeEx((PyObject*)co, globals, (PyObject *)NULL, + args, (int)nargs, + k, (int)nk, + d, (int)nd, kwdefs, closure); +#else + result = PyEval_EvalCodeEx(co, globals, (PyObject *)NULL, + args, (int)nargs, + k, (int)nk, + d, (int)nd, closure); +#endif + Py_XDECREF(kwtuple); +done: + Py_LeaveRecursiveCall(); + return result; +} +#endif + +/* PyObjectCall */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { + PyObject *result; + ternaryfunc call = Py_TYPE(func)->tp_call; + if (unlikely(!call)) + return PyObject_Call(func, arg, kw); + #if PY_MAJOR_VERSION < 3 + if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) + return NULL; + #else + if (unlikely(Py_EnterRecursiveCall(" while calling a Python object"))) + return NULL; + #endif + result = (*call)(func, arg, kw); + Py_LeaveRecursiveCall(); + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + } + return result; +} +#endif + +/* PyObjectCallMethO */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg) { + PyObject *self, *result; + PyCFunction cfunc; + cfunc = __Pyx_CyOrPyCFunction_GET_FUNCTION(func); + self = __Pyx_CyOrPyCFunction_GET_SELF(func); + #if PY_MAJOR_VERSION < 3 + if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) + return NULL; + #else + if (unlikely(Py_EnterRecursiveCall(" while calling a Python object"))) + return NULL; + #endif + result = cfunc(self, arg); + Py_LeaveRecursiveCall(); + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + } + return result; +} +#endif + +/* PyObjectFastCall */ +#if PY_VERSION_HEX < 0x03090000 || CYTHON_COMPILING_IN_LIMITED_API +static PyObject* __Pyx_PyObject_FastCall_fallback(PyObject *func, PyObject **args, size_t nargs, PyObject *kwargs) { + PyObject *argstuple; + PyObject *result = 0; + size_t i; + argstuple = PyTuple_New((Py_ssize_t)nargs); + if (unlikely(!argstuple)) return NULL; + for (i = 0; i < nargs; i++) { + Py_INCREF(args[i]); + if (__Pyx_PyTuple_SET_ITEM(argstuple, (Py_ssize_t)i, args[i]) < 0) goto bad; + } + result = __Pyx_PyObject_Call(func, argstuple, kwargs); + bad: + Py_DECREF(argstuple); + return result; +} +#endif +static CYTHON_INLINE PyObject* __Pyx_PyObject_FastCallDict(PyObject *func, PyObject **args, size_t _nargs, PyObject *kwargs) { + Py_ssize_t nargs = __Pyx_PyVectorcall_NARGS(_nargs); +#if CYTHON_COMPILING_IN_CPYTHON + if (nargs == 0 && kwargs == NULL) { + if (__Pyx_CyOrPyCFunction_Check(func) && likely( __Pyx_CyOrPyCFunction_GET_FLAGS(func) & METH_NOARGS)) + return __Pyx_PyObject_CallMethO(func, NULL); + } + else if (nargs == 1 && kwargs == NULL) { + if (__Pyx_CyOrPyCFunction_Check(func) && likely( __Pyx_CyOrPyCFunction_GET_FLAGS(func) & METH_O)) + return __Pyx_PyObject_CallMethO(func, args[0]); + } +#endif + #if PY_VERSION_HEX < 0x030800B1 + #if CYTHON_FAST_PYCCALL + if (PyCFunction_Check(func)) { + if (kwargs) { + return _PyCFunction_FastCallDict(func, args, nargs, kwargs); + } else { + return _PyCFunction_FastCallKeywords(func, args, nargs, NULL); + } + } + #if PY_VERSION_HEX >= 0x030700A1 + if (!kwargs && __Pyx_IS_TYPE(func, &PyMethodDescr_Type)) { + return _PyMethodDescr_FastCallKeywords(func, args, nargs, NULL); + } + #endif + #endif + #if CYTHON_FAST_PYCALL + if (PyFunction_Check(func)) { + return __Pyx_PyFunction_FastCallDict(func, args, nargs, kwargs); + } + #endif + #endif + if (kwargs == NULL) { + #if CYTHON_VECTORCALL + #if PY_VERSION_HEX < 0x03090000 + vectorcallfunc f = _PyVectorcall_Function(func); + #else + vectorcallfunc f = PyVectorcall_Function(func); + #endif + if (f) { + return f(func, args, (size_t)nargs, NULL); + } + #elif defined(__Pyx_CyFunction_USED) && CYTHON_BACKPORT_VECTORCALL + if (__Pyx_CyFunction_CheckExact(func)) { + __pyx_vectorcallfunc f = __Pyx_CyFunction_func_vectorcall(func); + if (f) return f(func, args, (size_t)nargs, NULL); + } + #endif + } + if (nargs == 0) { + return __Pyx_PyObject_Call(func, __pyx_empty_tuple, kwargs); + } + #if PY_VERSION_HEX >= 0x03090000 && !CYTHON_COMPILING_IN_LIMITED_API + return PyObject_VectorcallDict(func, args, (size_t)nargs, kwargs); + #else + return __Pyx_PyObject_FastCall_fallback(func, args, (size_t)nargs, kwargs); + #endif +} + +/* RaiseDoubleKeywords */ +static void __Pyx_RaiseDoubleKeywordsError( + const char* func_name, + PyObject* kw_name) +{ + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION >= 3 + "%s() got multiple values for keyword argument '%U'", func_name, kw_name); + #else + "%s() got multiple values for keyword argument '%s'", func_name, + PyString_AsString(kw_name)); + #endif +} + +/* ParseKeywords */ +static int __Pyx_ParseOptionalKeywords( + PyObject *kwds, + PyObject *const *kwvalues, + PyObject **argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + const char* function_name) +{ + PyObject *key = 0, *value = 0; + Py_ssize_t pos = 0; + PyObject*** name; + PyObject*** first_kw_arg = argnames + num_pos_args; + int kwds_is_tuple = CYTHON_METH_FASTCALL && likely(PyTuple_Check(kwds)); + while (1) { + Py_XDECREF(key); key = NULL; + Py_XDECREF(value); value = NULL; + if (kwds_is_tuple) { + Py_ssize_t size; +#if CYTHON_ASSUME_SAFE_MACROS + size = PyTuple_GET_SIZE(kwds); +#else + size = PyTuple_Size(kwds); + if (size < 0) goto bad; +#endif + if (pos >= size) break; +#if CYTHON_AVOID_BORROWED_REFS + key = __Pyx_PySequence_ITEM(kwds, pos); + if (!key) goto bad; +#elif CYTHON_ASSUME_SAFE_MACROS + key = PyTuple_GET_ITEM(kwds, pos); +#else + key = PyTuple_GetItem(kwds, pos); + if (!key) goto bad; +#endif + value = kwvalues[pos]; + pos++; + } + else + { + if (!PyDict_Next(kwds, &pos, &key, &value)) break; +#if CYTHON_AVOID_BORROWED_REFS + Py_INCREF(key); +#endif + } + name = first_kw_arg; + while (*name && (**name != key)) name++; + if (*name) { + values[name-argnames] = value; +#if CYTHON_AVOID_BORROWED_REFS + Py_INCREF(value); + Py_DECREF(key); +#endif + key = NULL; + value = NULL; + continue; + } +#if !CYTHON_AVOID_BORROWED_REFS + Py_INCREF(key); +#endif + Py_INCREF(value); + name = first_kw_arg; + #if PY_MAJOR_VERSION < 3 + if (likely(PyString_Check(key))) { + while (*name) { + if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) + && _PyString_Eq(**name, key)) { + values[name-argnames] = value; +#if CYTHON_AVOID_BORROWED_REFS + value = NULL; +#endif + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + if ((**argname == key) || ( + (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) + && _PyString_Eq(**argname, key))) { + goto arg_passed_twice; + } + argname++; + } + } + } else + #endif + if (likely(PyUnicode_Check(key))) { + while (*name) { + int cmp = ( + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (__Pyx_PyUnicode_GET_LENGTH(**name) != __Pyx_PyUnicode_GET_LENGTH(key)) ? 1 : + #endif + PyUnicode_Compare(**name, key) + ); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) { + values[name-argnames] = value; +#if CYTHON_AVOID_BORROWED_REFS + value = NULL; +#endif + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + int cmp = (**argname == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (__Pyx_PyUnicode_GET_LENGTH(**argname) != __Pyx_PyUnicode_GET_LENGTH(key)) ? 1 : + #endif + PyUnicode_Compare(**argname, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) goto arg_passed_twice; + argname++; + } + } + } else + goto invalid_keyword_type; + if (kwds2) { + if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; + } else { + goto invalid_keyword; + } + } + Py_XDECREF(key); + Py_XDECREF(value); + return 0; +arg_passed_twice: + __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; +invalid_keyword_type: + PyErr_Format(PyExc_TypeError, + "%.200s() keywords must be strings", function_name); + goto bad; +invalid_keyword: + #if PY_MAJOR_VERSION < 3 + PyErr_Format(PyExc_TypeError, + "%.200s() got an unexpected keyword argument '%.200s'", + function_name, PyString_AsString(key)); + #else + PyErr_Format(PyExc_TypeError, + "%s() got an unexpected keyword argument '%U'", + function_name, key); + #endif +bad: + Py_XDECREF(key); + Py_XDECREF(value); + return -1; +} + +/* PyObjectCallOneArg */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { + PyObject *args[2] = {NULL, arg}; + return __Pyx_PyObject_FastCall(func, args+1, 1 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET); +} + +/* ArgTypeTest */ +static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact) +{ + __Pyx_TypeName type_name; + __Pyx_TypeName obj_type_name; + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); + return 0; + } + else if (exact) { + #if PY_MAJOR_VERSION == 2 + if ((type == &PyBaseString_Type) && likely(__Pyx_PyBaseString_CheckExact(obj))) return 1; + #endif + } + else { + if (likely(__Pyx_TypeCheck(obj, type))) return 1; + } + type_name = __Pyx_PyType_GetName(type); + obj_type_name = __Pyx_PyType_GetName(Py_TYPE(obj)); + PyErr_Format(PyExc_TypeError, + "Argument '%.200s' has incorrect type (expected " __Pyx_FMT_TYPENAME + ", got " __Pyx_FMT_TYPENAME ")", name, type_name, obj_type_name); + __Pyx_DECREF_TypeName(type_name); + __Pyx_DECREF_TypeName(obj_type_name); + return 0; +} + +/* UnpackUnboundCMethod */ +static PyObject *__Pyx_SelflessCall(PyObject *method, PyObject *args, PyObject *kwargs) { + PyObject *result; + PyObject *selfless_args = PyTuple_GetSlice(args, 1, PyTuple_Size(args)); + if (unlikely(!selfless_args)) return NULL; + result = PyObject_Call(method, selfless_args, kwargs); + Py_DECREF(selfless_args); + return result; +} +static PyMethodDef __Pyx_UnboundCMethod_Def = { + "CythonUnboundCMethod", + __PYX_REINTERPRET_FUNCION(PyCFunction, __Pyx_SelflessCall), + METH_VARARGS | METH_KEYWORDS, + NULL +}; +static int __Pyx_TryUnpackUnboundCMethod(__Pyx_CachedCFunction* target) { + PyObject *method; + method = __Pyx_PyObject_GetAttrStr(target->type, *target->method_name); + if (unlikely(!method)) + return -1; + target->method = method; +#if CYTHON_COMPILING_IN_CPYTHON + #if PY_MAJOR_VERSION >= 3 + if (likely(__Pyx_TypeCheck(method, &PyMethodDescr_Type))) + #else + if (likely(!__Pyx_CyOrPyCFunction_Check(method))) + #endif + { + PyMethodDescrObject *descr = (PyMethodDescrObject*) method; + target->func = descr->d_method->ml_meth; + target->flag = descr->d_method->ml_flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_STACKLESS); + } else +#endif +#if CYTHON_COMPILING_IN_PYPY +#else + if (PyCFunction_Check(method)) +#endif + { + PyObject *self; + int self_found; +#if CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_PYPY + self = PyObject_GetAttrString(method, "__self__"); + if (!self) { + PyErr_Clear(); + } +#else + self = PyCFunction_GET_SELF(method); +#endif + self_found = (self && self != Py_None); +#if CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_PYPY + Py_XDECREF(self); +#endif + if (self_found) { + PyObject *unbound_method = PyCFunction_New(&__Pyx_UnboundCMethod_Def, method); + if (unlikely(!unbound_method)) return -1; + Py_DECREF(method); + target->method = unbound_method; + } + } + return 0; +} + +/* CallUnboundCMethod1 */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_CallUnboundCMethod1(__Pyx_CachedCFunction* cfunc, PyObject* self, PyObject* arg) { + if (likely(cfunc->func)) { + int flag = cfunc->flag; + if (flag == METH_O) { + return (*(cfunc->func))(self, arg); + } else if ((PY_VERSION_HEX >= 0x030600B1) && flag == METH_FASTCALL) { + #if PY_VERSION_HEX >= 0x030700A0 + return (*(__Pyx_PyCFunctionFast)(void*)(PyCFunction)cfunc->func)(self, &arg, 1); + #else + return (*(__Pyx_PyCFunctionFastWithKeywords)(void*)(PyCFunction)cfunc->func)(self, &arg, 1, NULL); + #endif + } else if ((PY_VERSION_HEX >= 0x030700A0) && flag == (METH_FASTCALL | METH_KEYWORDS)) { + return (*(__Pyx_PyCFunctionFastWithKeywords)(void*)(PyCFunction)cfunc->func)(self, &arg, 1, NULL); + } + } + return __Pyx__CallUnboundCMethod1(cfunc, self, arg); +} +#endif +static PyObject* __Pyx__CallUnboundCMethod1(__Pyx_CachedCFunction* cfunc, PyObject* self, PyObject* arg){ + PyObject *args, *result = NULL; + if (unlikely(!cfunc->func && !cfunc->method) && unlikely(__Pyx_TryUnpackUnboundCMethod(cfunc) < 0)) return NULL; +#if CYTHON_COMPILING_IN_CPYTHON + if (cfunc->func && (cfunc->flag & METH_VARARGS)) { + args = PyTuple_New(1); + if (unlikely(!args)) goto bad; + Py_INCREF(arg); + PyTuple_SET_ITEM(args, 0, arg); + if (cfunc->flag & METH_KEYWORDS) + result = (*(PyCFunctionWithKeywords)(void*)(PyCFunction)cfunc->func)(self, args, NULL); + else + result = (*cfunc->func)(self, args); + } else { + args = PyTuple_New(2); + if (unlikely(!args)) goto bad; + Py_INCREF(self); + PyTuple_SET_ITEM(args, 0, self); + Py_INCREF(arg); + PyTuple_SET_ITEM(args, 1, arg); + result = __Pyx_PyObject_Call(cfunc->method, args, NULL); + } +#else + args = PyTuple_Pack(2, self, arg); + if (unlikely(!args)) goto bad; + result = __Pyx_PyObject_Call(cfunc->method, args, NULL); +#endif +bad: + Py_XDECREF(args); + return result; +} + +/* RaiseException */ +#if PY_MAJOR_VERSION < 3 +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { + __Pyx_PyThreadState_declare + CYTHON_UNUSED_VAR(cause); + Py_XINCREF(type); + if (!value || value == Py_None) + value = NULL; + else + Py_INCREF(value); + if (!tb || tb == Py_None) + tb = NULL; + else { + Py_INCREF(tb); + if (!PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto raise_error; + } + } + if (PyType_Check(type)) { +#if CYTHON_COMPILING_IN_PYPY + if (!value) { + Py_INCREF(Py_None); + value = Py_None; + } +#endif + PyErr_NormalizeException(&type, &value, &tb); + } else { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto raise_error; + } + value = type; + type = (PyObject*) Py_TYPE(type); + Py_INCREF(type); + if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto raise_error; + } + } + __Pyx_PyThreadState_assign + __Pyx_ErrRestore(type, value, tb); + return; +raise_error: + Py_XDECREF(value); + Py_XDECREF(type); + Py_XDECREF(tb); + return; +} +#else +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { + PyObject* owned_instance = NULL; + if (tb == Py_None) { + tb = 0; + } else if (tb && !PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto bad; + } + if (value == Py_None) + value = 0; + if (PyExceptionInstance_Check(type)) { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto bad; + } + value = type; + type = (PyObject*) Py_TYPE(value); + } else if (PyExceptionClass_Check(type)) { + PyObject *instance_class = NULL; + if (value && PyExceptionInstance_Check(value)) { + instance_class = (PyObject*) Py_TYPE(value); + if (instance_class != type) { + int is_subclass = PyObject_IsSubclass(instance_class, type); + if (!is_subclass) { + instance_class = NULL; + } else if (unlikely(is_subclass == -1)) { + goto bad; + } else { + type = instance_class; + } + } + } + if (!instance_class) { + PyObject *args; + if (!value) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } else + args = PyTuple_Pack(1, value); + if (!args) + goto bad; + owned_instance = PyObject_Call(type, args, NULL); + Py_DECREF(args); + if (!owned_instance) + goto bad; + value = owned_instance; + if (!PyExceptionInstance_Check(value)) { + PyErr_Format(PyExc_TypeError, + "calling %R should have returned an instance of " + "BaseException, not %R", + type, Py_TYPE(value)); + goto bad; + } + } + } else { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto bad; + } + if (cause) { + PyObject *fixed_cause; + if (cause == Py_None) { + fixed_cause = NULL; + } else if (PyExceptionClass_Check(cause)) { + fixed_cause = PyObject_CallObject(cause, NULL); + if (fixed_cause == NULL) + goto bad; + } else if (PyExceptionInstance_Check(cause)) { + fixed_cause = cause; + Py_INCREF(fixed_cause); + } else { + PyErr_SetString(PyExc_TypeError, + "exception causes must derive from " + "BaseException"); + goto bad; + } + PyException_SetCause(value, fixed_cause); + } + PyErr_SetObject(type, value); + if (tb) { + #if PY_VERSION_HEX >= 0x030C00A6 + PyException_SetTraceback(value, tb); + #elif CYTHON_FAST_THREAD_STATE + PyThreadState *tstate = __Pyx_PyThreadState_Current; + PyObject* tmp_tb = tstate->curexc_traceback; + if (tb != tmp_tb) { + Py_INCREF(tb); + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_tb); + } +#else + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyErr_Fetch(&tmp_type, &tmp_value, &tmp_tb); + Py_INCREF(tb); + PyErr_Restore(tmp_type, tmp_value, tb); + Py_XDECREF(tmp_tb); +#endif + } +bad: + Py_XDECREF(owned_instance); + return; +} +#endif + +/* decode_c_bytes */ +static CYTHON_INLINE PyObject* __Pyx_decode_c_bytes( + const char* cstring, Py_ssize_t length, Py_ssize_t start, Py_ssize_t stop, + const char* encoding, const char* errors, + PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) { + if (unlikely((start < 0) | (stop < 0))) { + if (start < 0) { + start += length; + if (start < 0) + start = 0; + } + if (stop < 0) + stop += length; + } + if (stop > length) + stop = length; + if (unlikely(stop <= start)) + return __Pyx_NewRef(__pyx_empty_unicode); + length = stop - start; + cstring += start; + if (decode_func) { + return decode_func(cstring, length, errors); + } else { + return PyUnicode_Decode(cstring, length, encoding, errors); + } +} + +/* CIntToDigits */ +static const char DIGIT_PAIRS_10[2*10*10+1] = { + "00010203040506070809" + "10111213141516171819" + "20212223242526272829" + "30313233343536373839" + "40414243444546474849" + "50515253545556575859" + "60616263646566676869" + "70717273747576777879" + "80818283848586878889" + "90919293949596979899" +}; +static const char DIGIT_PAIRS_8[2*8*8+1] = { + "0001020304050607" + "1011121314151617" + "2021222324252627" + "3031323334353637" + "4041424344454647" + "5051525354555657" + "6061626364656667" + "7071727374757677" +}; +static const char DIGITS_HEX[2*16+1] = { + "0123456789abcdef" + "0123456789ABCDEF" +}; + +/* BuildPyUnicode */ +static PyObject* __Pyx_PyUnicode_BuildFromAscii(Py_ssize_t ulength, char* chars, int clength, + int prepend_sign, char padding_char) { + PyObject *uval; + Py_ssize_t uoffset = ulength - clength; +#if CYTHON_USE_UNICODE_INTERNALS + Py_ssize_t i; +#if CYTHON_PEP393_ENABLED + void *udata; + uval = PyUnicode_New(ulength, 127); + if (unlikely(!uval)) return NULL; + udata = PyUnicode_DATA(uval); +#else + Py_UNICODE *udata; + uval = PyUnicode_FromUnicode(NULL, ulength); + if (unlikely(!uval)) return NULL; + udata = PyUnicode_AS_UNICODE(uval); +#endif + if (uoffset > 0) { + i = 0; + if (prepend_sign) { + __Pyx_PyUnicode_WRITE(PyUnicode_1BYTE_KIND, udata, 0, '-'); + i++; + } + for (; i < uoffset; i++) { + __Pyx_PyUnicode_WRITE(PyUnicode_1BYTE_KIND, udata, i, padding_char); + } + } + for (i=0; i < clength; i++) { + __Pyx_PyUnicode_WRITE(PyUnicode_1BYTE_KIND, udata, uoffset+i, chars[i]); + } +#else + { + PyObject *sign = NULL, *padding = NULL; + uval = NULL; + if (uoffset > 0) { + prepend_sign = !!prepend_sign; + if (uoffset > prepend_sign) { + padding = PyUnicode_FromOrdinal(padding_char); + if (likely(padding) && uoffset > prepend_sign + 1) { + PyObject *tmp; + PyObject *repeat = PyInt_FromSsize_t(uoffset - prepend_sign); + if (unlikely(!repeat)) goto done_or_error; + tmp = PyNumber_Multiply(padding, repeat); + Py_DECREF(repeat); + Py_DECREF(padding); + padding = tmp; + } + if (unlikely(!padding)) goto done_or_error; + } + if (prepend_sign) { + sign = PyUnicode_FromOrdinal('-'); + if (unlikely(!sign)) goto done_or_error; + } + } + uval = PyUnicode_DecodeASCII(chars, clength, NULL); + if (likely(uval) && padding) { + PyObject *tmp = PyNumber_Add(padding, uval); + Py_DECREF(uval); + uval = tmp; + } + if (likely(uval) && sign) { + PyObject *tmp = PyNumber_Add(sign, uval); + Py_DECREF(uval); + uval = tmp; + } +done_or_error: + Py_XDECREF(padding); + Py_XDECREF(sign); + } +#endif + return uval; +} + +/* CIntToPyUnicode */ +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_From_int(int value, Py_ssize_t width, char padding_char, char format_char) { + char digits[sizeof(int)*3+2]; + char *dpos, *end = digits + sizeof(int)*3+2; + const char *hex_digits = DIGITS_HEX; + Py_ssize_t length, ulength; + int prepend_sign, last_one_off; + int remaining; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const int neg_one = (int) -1, const_zero = (int) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (format_char == 'X') { + hex_digits += 16; + format_char = 'x'; + } + remaining = value; + last_one_off = 0; + dpos = end; + do { + int digit_pos; + switch (format_char) { + case 'o': + digit_pos = abs((int)(remaining % (8*8))); + remaining = (int) (remaining / (8*8)); + dpos -= 2; + memcpy(dpos, DIGIT_PAIRS_8 + digit_pos * 2, 2); + last_one_off = (digit_pos < 8); + break; + case 'd': + digit_pos = abs((int)(remaining % (10*10))); + remaining = (int) (remaining / (10*10)); + dpos -= 2; + memcpy(dpos, DIGIT_PAIRS_10 + digit_pos * 2, 2); + last_one_off = (digit_pos < 10); + break; + case 'x': + *(--dpos) = hex_digits[abs((int)(remaining % 16))]; + remaining = (int) (remaining / 16); + break; + default: + assert(0); + break; + } + } while (unlikely(remaining != 0)); + assert(!last_one_off || *dpos == '0'); + dpos += last_one_off; + length = end - dpos; + ulength = length; + prepend_sign = 0; + if (!is_unsigned && value <= neg_one) { + if (padding_char == ' ' || width <= length + 1) { + *(--dpos) = '-'; + ++length; + } else { + prepend_sign = 1; + } + ++ulength; + } + if (width > ulength) { + ulength = width; + } + if (ulength == 1) { + return PyUnicode_FromOrdinal(*dpos); + } + return __Pyx_PyUnicode_BuildFromAscii(ulength, dpos, (int) length, prepend_sign, padding_char); +} + +/* JoinPyUnicode */ +static PyObject* __Pyx_PyUnicode_Join(PyObject* value_tuple, Py_ssize_t value_count, Py_ssize_t result_ulength, + Py_UCS4 max_char) { +#if CYTHON_USE_UNICODE_INTERNALS && CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + PyObject *result_uval; + int result_ukind, kind_shift; + Py_ssize_t i, char_pos; + void *result_udata; + CYTHON_MAYBE_UNUSED_VAR(max_char); +#if CYTHON_PEP393_ENABLED + result_uval = PyUnicode_New(result_ulength, max_char); + if (unlikely(!result_uval)) return NULL; + result_ukind = (max_char <= 255) ? PyUnicode_1BYTE_KIND : (max_char <= 65535) ? PyUnicode_2BYTE_KIND : PyUnicode_4BYTE_KIND; + kind_shift = (result_ukind == PyUnicode_4BYTE_KIND) ? 2 : result_ukind - 1; + result_udata = PyUnicode_DATA(result_uval); +#else + result_uval = PyUnicode_FromUnicode(NULL, result_ulength); + if (unlikely(!result_uval)) return NULL; + result_ukind = sizeof(Py_UNICODE); + kind_shift = (result_ukind == 4) ? 2 : result_ukind - 1; + result_udata = PyUnicode_AS_UNICODE(result_uval); +#endif + assert(kind_shift == 2 || kind_shift == 1 || kind_shift == 0); + char_pos = 0; + for (i=0; i < value_count; i++) { + int ukind; + Py_ssize_t ulength; + void *udata; + PyObject *uval = PyTuple_GET_ITEM(value_tuple, i); + if (unlikely(__Pyx_PyUnicode_READY(uval))) + goto bad; + ulength = __Pyx_PyUnicode_GET_LENGTH(uval); + if (unlikely(!ulength)) + continue; + if (unlikely((PY_SSIZE_T_MAX >> kind_shift) - ulength < char_pos)) + goto overflow; + ukind = __Pyx_PyUnicode_KIND(uval); + udata = __Pyx_PyUnicode_DATA(uval); + if (!CYTHON_PEP393_ENABLED || ukind == result_ukind) { + memcpy((char *)result_udata + (char_pos << kind_shift), udata, (size_t) (ulength << kind_shift)); + } else { + #if PY_VERSION_HEX >= 0x030d0000 + if (unlikely(PyUnicode_CopyCharacters(result_uval, char_pos, uval, 0, ulength) < 0)) goto bad; + #elif CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030300F0 || defined(_PyUnicode_FastCopyCharacters) + _PyUnicode_FastCopyCharacters(result_uval, char_pos, uval, 0, ulength); + #else + Py_ssize_t j; + for (j=0; j < ulength; j++) { + Py_UCS4 uchar = __Pyx_PyUnicode_READ(ukind, udata, j); + __Pyx_PyUnicode_WRITE(result_ukind, result_udata, char_pos+j, uchar); + } + #endif + } + char_pos += ulength; + } + return result_uval; +overflow: + PyErr_SetString(PyExc_OverflowError, "join() result is too long for a Python string"); +bad: + Py_DECREF(result_uval); + return NULL; +#else + CYTHON_UNUSED_VAR(max_char); + CYTHON_UNUSED_VAR(result_ulength); + CYTHON_UNUSED_VAR(value_count); + return PyUnicode_Join(__pyx_empty_unicode, value_tuple); +#endif +} + +/* PyDictVersioning */ +#if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj) { + PyObject *dict = Py_TYPE(obj)->tp_dict; + return likely(dict) ? __PYX_GET_DICT_VERSION(dict) : 0; +} +static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj) { + PyObject **dictptr = NULL; + Py_ssize_t offset = Py_TYPE(obj)->tp_dictoffset; + if (offset) { +#if CYTHON_COMPILING_IN_CPYTHON + dictptr = (likely(offset > 0)) ? (PyObject **) ((char *)obj + offset) : _PyObject_GetDictPtr(obj); +#else + dictptr = _PyObject_GetDictPtr(obj); +#endif + } + return (dictptr && *dictptr) ? __PYX_GET_DICT_VERSION(*dictptr) : 0; +} +static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version) { + PyObject *dict = Py_TYPE(obj)->tp_dict; + if (unlikely(!dict) || unlikely(tp_dict_version != __PYX_GET_DICT_VERSION(dict))) + return 0; + return obj_dict_version == __Pyx_get_object_dict_version(obj); +} +#endif + +/* GetModuleGlobalName */ +#if CYTHON_USE_DICT_VERSIONS +static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value) +#else +static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name) +#endif +{ + PyObject *result; +#if !CYTHON_AVOID_BORROWED_REFS +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030500A1 && PY_VERSION_HEX < 0x030d0000 + result = _PyDict_GetItem_KnownHash(__pyx_d, name, ((PyASCIIObject *) name)->hash); + __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) + if (likely(result)) { + return __Pyx_NewRef(result); + } else if (unlikely(PyErr_Occurred())) { + return NULL; + } +#elif CYTHON_COMPILING_IN_LIMITED_API + if (unlikely(!__pyx_m)) { + return NULL; + } + result = PyObject_GetAttr(__pyx_m, name); + if (likely(result)) { + return result; + } +#else + result = PyDict_GetItem(__pyx_d, name); + __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) + if (likely(result)) { + return __Pyx_NewRef(result); + } +#endif +#else + result = PyObject_GetItem(__pyx_d, name); + __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) + if (likely(result)) { + return __Pyx_NewRef(result); + } + PyErr_Clear(); +#endif + return __Pyx_GetBuiltinName(name); +} + +/* decode_c_string */ +static CYTHON_INLINE PyObject* __Pyx_decode_c_string( + const char* cstring, Py_ssize_t start, Py_ssize_t stop, + const char* encoding, const char* errors, + PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) { + Py_ssize_t length; + if (unlikely((start < 0) | (stop < 0))) { + size_t slen = strlen(cstring); + if (unlikely(slen > (size_t) PY_SSIZE_T_MAX)) { + PyErr_SetString(PyExc_OverflowError, + "c-string too long to convert to Python"); + return NULL; + } + length = (Py_ssize_t) slen; + if (start < 0) { + start += length; + if (start < 0) + start = 0; + } + if (stop < 0) + stop += length; + } + if (unlikely(stop <= start)) + return __Pyx_NewRef(__pyx_empty_unicode); + length = stop - start; + cstring += start; + if (decode_func) { + return decode_func(cstring, length, errors); + } else { + return PyUnicode_Decode(cstring, length, encoding, errors); + } +} + +/* FixUpExtensionType */ +#if CYTHON_USE_TYPE_SPECS +static int __Pyx_fix_up_extension_type_from_spec(PyType_Spec *spec, PyTypeObject *type) { +#if PY_VERSION_HEX > 0x030900B1 || CYTHON_COMPILING_IN_LIMITED_API + CYTHON_UNUSED_VAR(spec); + CYTHON_UNUSED_VAR(type); +#else + const PyType_Slot *slot = spec->slots; + while (slot && slot->slot && slot->slot != Py_tp_members) + slot++; + if (slot && slot->slot == Py_tp_members) { + int changed = 0; +#if !(PY_VERSION_HEX <= 0x030900b1 && CYTHON_COMPILING_IN_CPYTHON) + const +#endif + PyMemberDef *memb = (PyMemberDef*) slot->pfunc; + while (memb && memb->name) { + if (memb->name[0] == '_' && memb->name[1] == '_') { +#if PY_VERSION_HEX < 0x030900b1 + if (strcmp(memb->name, "__weaklistoffset__") == 0) { + assert(memb->type == T_PYSSIZET); + assert(memb->flags == READONLY); + type->tp_weaklistoffset = memb->offset; + changed = 1; + } + else if (strcmp(memb->name, "__dictoffset__") == 0) { + assert(memb->type == T_PYSSIZET); + assert(memb->flags == READONLY); + type->tp_dictoffset = memb->offset; + changed = 1; + } +#if CYTHON_METH_FASTCALL + else if (strcmp(memb->name, "__vectorcalloffset__") == 0) { + assert(memb->type == T_PYSSIZET); + assert(memb->flags == READONLY); +#if PY_VERSION_HEX >= 0x030800b4 + type->tp_vectorcall_offset = memb->offset; +#else + type->tp_print = (printfunc) memb->offset; +#endif + changed = 1; + } +#endif +#else + if ((0)); +#endif +#if PY_VERSION_HEX <= 0x030900b1 && CYTHON_COMPILING_IN_CPYTHON + else if (strcmp(memb->name, "__module__") == 0) { + PyObject *descr; + assert(memb->type == T_OBJECT); + assert(memb->flags == 0 || memb->flags == READONLY); + descr = PyDescr_NewMember(type, memb); + if (unlikely(!descr)) + return -1; + if (unlikely(PyDict_SetItem(type->tp_dict, PyDescr_NAME(descr), descr) < 0)) { + Py_DECREF(descr); + return -1; + } + Py_DECREF(descr); + changed = 1; + } +#endif + } + memb++; + } + if (changed) + PyType_Modified(type); + } +#endif + return 0; +} +#endif + +/* PyObjectCallNoArg */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func) { + PyObject *arg[2] = {NULL, NULL}; + return __Pyx_PyObject_FastCall(func, arg + 1, 0 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET); +} + +/* PyObjectGetMethod */ +static int __Pyx_PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method) { + PyObject *attr; +#if CYTHON_UNPACK_METHODS && CYTHON_COMPILING_IN_CPYTHON && CYTHON_USE_PYTYPE_LOOKUP + __Pyx_TypeName type_name; + PyTypeObject *tp = Py_TYPE(obj); + PyObject *descr; + descrgetfunc f = NULL; + PyObject **dictptr, *dict; + int meth_found = 0; + assert (*method == NULL); + if (unlikely(tp->tp_getattro != PyObject_GenericGetAttr)) { + attr = __Pyx_PyObject_GetAttrStr(obj, name); + goto try_unpack; + } + if (unlikely(tp->tp_dict == NULL) && unlikely(PyType_Ready(tp) < 0)) { + return 0; + } + descr = _PyType_Lookup(tp, name); + if (likely(descr != NULL)) { + Py_INCREF(descr); +#if defined(Py_TPFLAGS_METHOD_DESCRIPTOR) && Py_TPFLAGS_METHOD_DESCRIPTOR + if (__Pyx_PyType_HasFeature(Py_TYPE(descr), Py_TPFLAGS_METHOD_DESCRIPTOR)) +#elif PY_MAJOR_VERSION >= 3 + #ifdef __Pyx_CyFunction_USED + if (likely(PyFunction_Check(descr) || __Pyx_IS_TYPE(descr, &PyMethodDescr_Type) || __Pyx_CyFunction_Check(descr))) + #else + if (likely(PyFunction_Check(descr) || __Pyx_IS_TYPE(descr, &PyMethodDescr_Type))) + #endif +#else + #ifdef __Pyx_CyFunction_USED + if (likely(PyFunction_Check(descr) || __Pyx_CyFunction_Check(descr))) + #else + if (likely(PyFunction_Check(descr))) + #endif +#endif + { + meth_found = 1; + } else { + f = Py_TYPE(descr)->tp_descr_get; + if (f != NULL && PyDescr_IsData(descr)) { + attr = f(descr, obj, (PyObject *)Py_TYPE(obj)); + Py_DECREF(descr); + goto try_unpack; + } + } + } + dictptr = _PyObject_GetDictPtr(obj); + if (dictptr != NULL && (dict = *dictptr) != NULL) { + Py_INCREF(dict); + attr = __Pyx_PyDict_GetItemStr(dict, name); + if (attr != NULL) { + Py_INCREF(attr); + Py_DECREF(dict); + Py_XDECREF(descr); + goto try_unpack; + } + Py_DECREF(dict); + } + if (meth_found) { + *method = descr; + return 1; + } + if (f != NULL) { + attr = f(descr, obj, (PyObject *)Py_TYPE(obj)); + Py_DECREF(descr); + goto try_unpack; + } + if (likely(descr != NULL)) { + *method = descr; + return 0; + } + type_name = __Pyx_PyType_GetName(tp); + PyErr_Format(PyExc_AttributeError, +#if PY_MAJOR_VERSION >= 3 + "'" __Pyx_FMT_TYPENAME "' object has no attribute '%U'", + type_name, name); +#else + "'" __Pyx_FMT_TYPENAME "' object has no attribute '%.400s'", + type_name, PyString_AS_STRING(name)); +#endif + __Pyx_DECREF_TypeName(type_name); + return 0; +#else + attr = __Pyx_PyObject_GetAttrStr(obj, name); + goto try_unpack; +#endif +try_unpack: +#if CYTHON_UNPACK_METHODS + if (likely(attr) && PyMethod_Check(attr) && likely(PyMethod_GET_SELF(attr) == obj)) { + PyObject *function = PyMethod_GET_FUNCTION(attr); + Py_INCREF(function); + Py_DECREF(attr); + *method = function; + return 1; + } +#endif + *method = attr; + return 0; +} + +/* PyObjectCallMethod0 */ +static PyObject* __Pyx_PyObject_CallMethod0(PyObject* obj, PyObject* method_name) { + PyObject *method = NULL, *result = NULL; + int is_method = __Pyx_PyObject_GetMethod(obj, method_name, &method); + if (likely(is_method)) { + result = __Pyx_PyObject_CallOneArg(method, obj); + Py_DECREF(method); + return result; + } + if (unlikely(!method)) goto bad; + result = __Pyx_PyObject_CallNoArg(method); + Py_DECREF(method); +bad: + return result; +} + +/* ValidateBasesTuple */ +#if CYTHON_COMPILING_IN_CPYTHON || CYTHON_COMPILING_IN_LIMITED_API || CYTHON_USE_TYPE_SPECS +static int __Pyx_validate_bases_tuple(const char *type_name, Py_ssize_t dictoffset, PyObject *bases) { + Py_ssize_t i, n; +#if CYTHON_ASSUME_SAFE_MACROS + n = PyTuple_GET_SIZE(bases); +#else + n = PyTuple_Size(bases); + if (n < 0) return -1; +#endif + for (i = 1; i < n; i++) + { +#if CYTHON_AVOID_BORROWED_REFS + PyObject *b0 = PySequence_GetItem(bases, i); + if (!b0) return -1; +#elif CYTHON_ASSUME_SAFE_MACROS + PyObject *b0 = PyTuple_GET_ITEM(bases, i); +#else + PyObject *b0 = PyTuple_GetItem(bases, i); + if (!b0) return -1; +#endif + PyTypeObject *b; +#if PY_MAJOR_VERSION < 3 + if (PyClass_Check(b0)) + { + PyErr_Format(PyExc_TypeError, "base class '%.200s' is an old-style class", + PyString_AS_STRING(((PyClassObject*)b0)->cl_name)); +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(b0); +#endif + return -1; + } +#endif + b = (PyTypeObject*) b0; + if (!__Pyx_PyType_HasFeature(b, Py_TPFLAGS_HEAPTYPE)) + { + __Pyx_TypeName b_name = __Pyx_PyType_GetName(b); + PyErr_Format(PyExc_TypeError, + "base class '" __Pyx_FMT_TYPENAME "' is not a heap type", b_name); + __Pyx_DECREF_TypeName(b_name); +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(b0); +#endif + return -1; + } + if (dictoffset == 0) + { + Py_ssize_t b_dictoffset = 0; +#if CYTHON_USE_TYPE_SLOTS || CYTHON_COMPILING_IN_PYPY + b_dictoffset = b->tp_dictoffset; +#else + PyObject *py_b_dictoffset = PyObject_GetAttrString((PyObject*)b, "__dictoffset__"); + if (!py_b_dictoffset) goto dictoffset_return; + b_dictoffset = PyLong_AsSsize_t(py_b_dictoffset); + Py_DECREF(py_b_dictoffset); + if (b_dictoffset == -1 && PyErr_Occurred()) goto dictoffset_return; +#endif + if (b_dictoffset) { + { + __Pyx_TypeName b_name = __Pyx_PyType_GetName(b); + PyErr_Format(PyExc_TypeError, + "extension type '%.200s' has no __dict__ slot, " + "but base type '" __Pyx_FMT_TYPENAME "' has: " + "either add 'cdef dict __dict__' to the extension type " + "or add '__slots__ = [...]' to the base type", + type_name, b_name); + __Pyx_DECREF_TypeName(b_name); + } +#if !(CYTHON_USE_TYPE_SLOTS || CYTHON_COMPILING_IN_PYPY) + dictoffset_return: +#endif +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(b0); +#endif + return -1; + } + } +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(b0); +#endif + } + return 0; +} +#endif + +/* PyType_Ready */ +static int __Pyx_PyType_Ready(PyTypeObject *t) { +#if CYTHON_USE_TYPE_SPECS || !(CYTHON_COMPILING_IN_CPYTHON || CYTHON_COMPILING_IN_LIMITED_API) || defined(PYSTON_MAJOR_VERSION) + (void)__Pyx_PyObject_CallMethod0; +#if CYTHON_USE_TYPE_SPECS + (void)__Pyx_validate_bases_tuple; +#endif + return PyType_Ready(t); +#else + int r; + PyObject *bases = __Pyx_PyType_GetSlot(t, tp_bases, PyObject*); + if (bases && unlikely(__Pyx_validate_bases_tuple(t->tp_name, t->tp_dictoffset, bases) == -1)) + return -1; +#if PY_VERSION_HEX >= 0x03050000 && !defined(PYSTON_MAJOR_VERSION) + { + int gc_was_enabled; + #if PY_VERSION_HEX >= 0x030A00b1 + gc_was_enabled = PyGC_Disable(); + (void)__Pyx_PyObject_CallMethod0; + #else + PyObject *ret, *py_status; + PyObject *gc = NULL; + #if PY_VERSION_HEX >= 0x030700a1 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM+0 >= 0x07030400) + gc = PyImport_GetModule(__pyx_kp_u_gc); + #endif + if (unlikely(!gc)) gc = PyImport_Import(__pyx_kp_u_gc); + if (unlikely(!gc)) return -1; + py_status = __Pyx_PyObject_CallMethod0(gc, __pyx_kp_u_isenabled); + if (unlikely(!py_status)) { + Py_DECREF(gc); + return -1; + } + gc_was_enabled = __Pyx_PyObject_IsTrue(py_status); + Py_DECREF(py_status); + if (gc_was_enabled > 0) { + ret = __Pyx_PyObject_CallMethod0(gc, __pyx_kp_u_disable); + if (unlikely(!ret)) { + Py_DECREF(gc); + return -1; + } + Py_DECREF(ret); + } else if (unlikely(gc_was_enabled == -1)) { + Py_DECREF(gc); + return -1; + } + #endif + t->tp_flags |= Py_TPFLAGS_HEAPTYPE; +#if PY_VERSION_HEX >= 0x030A0000 + t->tp_flags |= Py_TPFLAGS_IMMUTABLETYPE; +#endif +#else + (void)__Pyx_PyObject_CallMethod0; +#endif + r = PyType_Ready(t); +#if PY_VERSION_HEX >= 0x03050000 && !defined(PYSTON_MAJOR_VERSION) + t->tp_flags &= ~Py_TPFLAGS_HEAPTYPE; + #if PY_VERSION_HEX >= 0x030A00b1 + if (gc_was_enabled) + PyGC_Enable(); + #else + if (gc_was_enabled) { + PyObject *tp, *v, *tb; + PyErr_Fetch(&tp, &v, &tb); + ret = __Pyx_PyObject_CallMethod0(gc, __pyx_kp_u_enable); + if (likely(ret || r == -1)) { + Py_XDECREF(ret); + PyErr_Restore(tp, v, tb); + } else { + Py_XDECREF(tp); + Py_XDECREF(v); + Py_XDECREF(tb); + r = -1; + } + } + Py_DECREF(gc); + #endif + } +#endif + return r; +#endif +} + +/* PyObject_GenericGetAttrNoDict */ +#if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 +static PyObject *__Pyx_RaiseGenericGetAttributeError(PyTypeObject *tp, PyObject *attr_name) { + __Pyx_TypeName type_name = __Pyx_PyType_GetName(tp); + PyErr_Format(PyExc_AttributeError, +#if PY_MAJOR_VERSION >= 3 + "'" __Pyx_FMT_TYPENAME "' object has no attribute '%U'", + type_name, attr_name); +#else + "'" __Pyx_FMT_TYPENAME "' object has no attribute '%.400s'", + type_name, PyString_AS_STRING(attr_name)); +#endif + __Pyx_DECREF_TypeName(type_name); + return NULL; +} +static CYTHON_INLINE PyObject* __Pyx_PyObject_GenericGetAttrNoDict(PyObject* obj, PyObject* attr_name) { + PyObject *descr; + PyTypeObject *tp = Py_TYPE(obj); + if (unlikely(!PyString_Check(attr_name))) { + return PyObject_GenericGetAttr(obj, attr_name); + } + assert(!tp->tp_dictoffset); + descr = _PyType_Lookup(tp, attr_name); + if (unlikely(!descr)) { + return __Pyx_RaiseGenericGetAttributeError(tp, attr_name); + } + Py_INCREF(descr); + #if PY_MAJOR_VERSION < 3 + if (likely(PyType_HasFeature(Py_TYPE(descr), Py_TPFLAGS_HAVE_CLASS))) + #endif + { + descrgetfunc f = Py_TYPE(descr)->tp_descr_get; + if (unlikely(f)) { + PyObject *res = f(descr, obj, (PyObject *)tp); + Py_DECREF(descr); + return res; + } + } + return descr; +} +#endif + +/* PyObject_GenericGetAttr */ +#if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 +static PyObject* __Pyx_PyObject_GenericGetAttr(PyObject* obj, PyObject* attr_name) { + if (unlikely(Py_TYPE(obj)->tp_dictoffset)) { + return PyObject_GenericGetAttr(obj, attr_name); + } + return __Pyx_PyObject_GenericGetAttrNoDict(obj, attr_name); +} +#endif + +/* SetVTable */ +static int __Pyx_SetVtable(PyTypeObject *type, void *vtable) { + PyObject *ob = PyCapsule_New(vtable, 0, 0); + if (unlikely(!ob)) + goto bad; +#if CYTHON_COMPILING_IN_LIMITED_API + if (unlikely(PyObject_SetAttr((PyObject *) type, __pyx_n_s_pyx_vtable, ob) < 0)) +#else + if (unlikely(PyDict_SetItem(type->tp_dict, __pyx_n_s_pyx_vtable, ob) < 0)) +#endif + goto bad; + Py_DECREF(ob); + return 0; +bad: + Py_XDECREF(ob); + return -1; +} + +/* GetVTable */ +static void* __Pyx_GetVtable(PyTypeObject *type) { + void* ptr; +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *ob = PyObject_GetAttr((PyObject *)type, __pyx_n_s_pyx_vtable); +#else + PyObject *ob = PyObject_GetItem(type->tp_dict, __pyx_n_s_pyx_vtable); +#endif + if (!ob) + goto bad; + ptr = PyCapsule_GetPointer(ob, 0); + if (!ptr && !PyErr_Occurred()) + PyErr_SetString(PyExc_RuntimeError, "invalid vtable found for imported type"); + Py_DECREF(ob); + return ptr; +bad: + Py_XDECREF(ob); + return NULL; +} + +/* MergeVTables */ +#if !CYTHON_COMPILING_IN_LIMITED_API +static int __Pyx_MergeVtables(PyTypeObject *type) { + int i; + void** base_vtables; + __Pyx_TypeName tp_base_name; + __Pyx_TypeName base_name; + void* unknown = (void*)-1; + PyObject* bases = type->tp_bases; + int base_depth = 0; + { + PyTypeObject* base = type->tp_base; + while (base) { + base_depth += 1; + base = base->tp_base; + } + } + base_vtables = (void**) malloc(sizeof(void*) * (size_t)(base_depth + 1)); + base_vtables[0] = unknown; + for (i = 1; i < PyTuple_GET_SIZE(bases); i++) { + void* base_vtable = __Pyx_GetVtable(((PyTypeObject*)PyTuple_GET_ITEM(bases, i))); + if (base_vtable != NULL) { + int j; + PyTypeObject* base = type->tp_base; + for (j = 0; j < base_depth; j++) { + if (base_vtables[j] == unknown) { + base_vtables[j] = __Pyx_GetVtable(base); + base_vtables[j + 1] = unknown; + } + if (base_vtables[j] == base_vtable) { + break; + } else if (base_vtables[j] == NULL) { + goto bad; + } + base = base->tp_base; + } + } + } + PyErr_Clear(); + free(base_vtables); + return 0; +bad: + tp_base_name = __Pyx_PyType_GetName(type->tp_base); + base_name = __Pyx_PyType_GetName((PyTypeObject*)PyTuple_GET_ITEM(bases, i)); + PyErr_Format(PyExc_TypeError, + "multiple bases have vtable conflict: '" __Pyx_FMT_TYPENAME "' and '" __Pyx_FMT_TYPENAME "'", tp_base_name, base_name); + __Pyx_DECREF_TypeName(tp_base_name); + __Pyx_DECREF_TypeName(base_name); + free(base_vtables); + return -1; +} +#endif + +/* Import */ +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { + PyObject *module = 0; + PyObject *empty_dict = 0; + PyObject *empty_list = 0; + #if PY_MAJOR_VERSION < 3 + PyObject *py_import; + py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s_import); + if (unlikely(!py_import)) + goto bad; + if (!from_list) { + empty_list = PyList_New(0); + if (unlikely(!empty_list)) + goto bad; + from_list = empty_list; + } + #endif + empty_dict = PyDict_New(); + if (unlikely(!empty_dict)) + goto bad; + { + #if PY_MAJOR_VERSION >= 3 + if (level == -1) { + if (strchr(__Pyx_MODULE_NAME, '.') != NULL) { + module = PyImport_ImportModuleLevelObject( + name, __pyx_d, empty_dict, from_list, 1); + if (unlikely(!module)) { + if (unlikely(!PyErr_ExceptionMatches(PyExc_ImportError))) + goto bad; + PyErr_Clear(); + } + } + level = 0; + } + #endif + if (!module) { + #if PY_MAJOR_VERSION < 3 + PyObject *py_level = PyInt_FromLong(level); + if (unlikely(!py_level)) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, __pyx_d, empty_dict, from_list, py_level, (PyObject *)NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, __pyx_d, empty_dict, from_list, level); + #endif + } + } +bad: + Py_XDECREF(empty_dict); + Py_XDECREF(empty_list); + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(py_import); + #endif + return module; +} + +/* ImportFrom */ +static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name) { + PyObject* value = __Pyx_PyObject_GetAttrStr(module, name); + if (unlikely(!value) && PyErr_ExceptionMatches(PyExc_AttributeError)) { + const char* module_name_str = 0; + PyObject* module_name = 0; + PyObject* module_dot = 0; + PyObject* full_name = 0; + PyErr_Clear(); + module_name_str = PyModule_GetName(module); + if (unlikely(!module_name_str)) { goto modbad; } + module_name = PyUnicode_FromString(module_name_str); + if (unlikely(!module_name)) { goto modbad; } + module_dot = PyUnicode_Concat(module_name, __pyx_kp_u__3); + if (unlikely(!module_dot)) { goto modbad; } + full_name = PyUnicode_Concat(module_dot, name); + if (unlikely(!full_name)) { goto modbad; } + #if PY_VERSION_HEX < 0x030700A1 || (CYTHON_COMPILING_IN_PYPY && PYPY_VERSION_NUM < 0x07030400) + { + PyObject *modules = PyImport_GetModuleDict(); + if (unlikely(!modules)) + goto modbad; + value = PyObject_GetItem(modules, full_name); + } + #else + value = PyImport_GetModule(full_name); + #endif + modbad: + Py_XDECREF(full_name); + Py_XDECREF(module_dot); + Py_XDECREF(module_name); + } + if (unlikely(!value)) { + PyErr_Format(PyExc_ImportError, + #if PY_MAJOR_VERSION < 3 + "cannot import name %.230s", PyString_AS_STRING(name)); + #else + "cannot import name %S", name); + #endif + } + return value; +} + +/* FetchSharedCythonModule */ +static PyObject *__Pyx_FetchSharedCythonABIModule(void) { + return __Pyx_PyImport_AddModuleRef((char*) __PYX_ABI_MODULE_NAME); +} + +/* FetchCommonType */ +static int __Pyx_VerifyCachedType(PyObject *cached_type, + const char *name, + Py_ssize_t basicsize, + Py_ssize_t expected_basicsize) { + if (!PyType_Check(cached_type)) { + PyErr_Format(PyExc_TypeError, + "Shared Cython type %.200s is not a type object", name); + return -1; + } + if (basicsize != expected_basicsize) { + PyErr_Format(PyExc_TypeError, + "Shared Cython type %.200s has the wrong size, try recompiling", + name); + return -1; + } + return 0; +} +#if !CYTHON_USE_TYPE_SPECS +static PyTypeObject* __Pyx_FetchCommonType(PyTypeObject* type) { + PyObject* abi_module; + const char* object_name; + PyTypeObject *cached_type = NULL; + abi_module = __Pyx_FetchSharedCythonABIModule(); + if (!abi_module) return NULL; + object_name = strrchr(type->tp_name, '.'); + object_name = object_name ? object_name+1 : type->tp_name; + cached_type = (PyTypeObject*) PyObject_GetAttrString(abi_module, object_name); + if (cached_type) { + if (__Pyx_VerifyCachedType( + (PyObject *)cached_type, + object_name, + cached_type->tp_basicsize, + type->tp_basicsize) < 0) { + goto bad; + } + goto done; + } + if (!PyErr_ExceptionMatches(PyExc_AttributeError)) goto bad; + PyErr_Clear(); + if (PyType_Ready(type) < 0) goto bad; + if (PyObject_SetAttrString(abi_module, object_name, (PyObject *)type) < 0) + goto bad; + Py_INCREF(type); + cached_type = type; +done: + Py_DECREF(abi_module); + return cached_type; +bad: + Py_XDECREF(cached_type); + cached_type = NULL; + goto done; +} +#else +static PyTypeObject *__Pyx_FetchCommonTypeFromSpec(PyObject *module, PyType_Spec *spec, PyObject *bases) { + PyObject *abi_module, *cached_type = NULL; + const char* object_name = strrchr(spec->name, '.'); + object_name = object_name ? object_name+1 : spec->name; + abi_module = __Pyx_FetchSharedCythonABIModule(); + if (!abi_module) return NULL; + cached_type = PyObject_GetAttrString(abi_module, object_name); + if (cached_type) { + Py_ssize_t basicsize; +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *py_basicsize; + py_basicsize = PyObject_GetAttrString(cached_type, "__basicsize__"); + if (unlikely(!py_basicsize)) goto bad; + basicsize = PyLong_AsSsize_t(py_basicsize); + Py_DECREF(py_basicsize); + py_basicsize = 0; + if (unlikely(basicsize == (Py_ssize_t)-1) && PyErr_Occurred()) goto bad; +#else + basicsize = likely(PyType_Check(cached_type)) ? ((PyTypeObject*) cached_type)->tp_basicsize : -1; +#endif + if (__Pyx_VerifyCachedType( + cached_type, + object_name, + basicsize, + spec->basicsize) < 0) { + goto bad; + } + goto done; + } + if (!PyErr_ExceptionMatches(PyExc_AttributeError)) goto bad; + PyErr_Clear(); + CYTHON_UNUSED_VAR(module); + cached_type = __Pyx_PyType_FromModuleAndSpec(abi_module, spec, bases); + if (unlikely(!cached_type)) goto bad; + if (unlikely(__Pyx_fix_up_extension_type_from_spec(spec, (PyTypeObject *) cached_type) < 0)) goto bad; + if (PyObject_SetAttrString(abi_module, object_name, cached_type) < 0) goto bad; +done: + Py_DECREF(abi_module); + assert(cached_type == NULL || PyType_Check(cached_type)); + return (PyTypeObject *) cached_type; +bad: + Py_XDECREF(cached_type); + cached_type = NULL; + goto done; +} +#endif + +/* PyVectorcallFastCallDict */ +#if CYTHON_METH_FASTCALL +static PyObject *__Pyx_PyVectorcall_FastCallDict_kw(PyObject *func, __pyx_vectorcallfunc vc, PyObject *const *args, size_t nargs, PyObject *kw) +{ + PyObject *res = NULL; + PyObject *kwnames; + PyObject **newargs; + PyObject **kwvalues; + Py_ssize_t i, pos; + size_t j; + PyObject *key, *value; + unsigned long keys_are_strings; + Py_ssize_t nkw = PyDict_GET_SIZE(kw); + newargs = (PyObject **)PyMem_Malloc((nargs + (size_t)nkw) * sizeof(args[0])); + if (unlikely(newargs == NULL)) { + PyErr_NoMemory(); + return NULL; + } + for (j = 0; j < nargs; j++) newargs[j] = args[j]; + kwnames = PyTuple_New(nkw); + if (unlikely(kwnames == NULL)) { + PyMem_Free(newargs); + return NULL; + } + kwvalues = newargs + nargs; + pos = i = 0; + keys_are_strings = Py_TPFLAGS_UNICODE_SUBCLASS; + while (PyDict_Next(kw, &pos, &key, &value)) { + keys_are_strings &= Py_TYPE(key)->tp_flags; + Py_INCREF(key); + Py_INCREF(value); + PyTuple_SET_ITEM(kwnames, i, key); + kwvalues[i] = value; + i++; + } + if (unlikely(!keys_are_strings)) { + PyErr_SetString(PyExc_TypeError, "keywords must be strings"); + goto cleanup; + } + res = vc(func, newargs, nargs, kwnames); +cleanup: + Py_DECREF(kwnames); + for (i = 0; i < nkw; i++) + Py_DECREF(kwvalues[i]); + PyMem_Free(newargs); + return res; +} +static CYTHON_INLINE PyObject *__Pyx_PyVectorcall_FastCallDict(PyObject *func, __pyx_vectorcallfunc vc, PyObject *const *args, size_t nargs, PyObject *kw) +{ + if (likely(kw == NULL) || PyDict_GET_SIZE(kw) == 0) { + return vc(func, args, nargs, NULL); + } + return __Pyx_PyVectorcall_FastCallDict_kw(func, vc, args, nargs, kw); +} +#endif + +/* CythonFunctionShared */ +#if CYTHON_COMPILING_IN_LIMITED_API +static CYTHON_INLINE int __Pyx__IsSameCyOrCFunction(PyObject *func, void *cfunc) { + if (__Pyx_CyFunction_Check(func)) { + return PyCFunction_GetFunction(((__pyx_CyFunctionObject*)func)->func) == (PyCFunction) cfunc; + } else if (PyCFunction_Check(func)) { + return PyCFunction_GetFunction(func) == (PyCFunction) cfunc; + } + return 0; +} +#else +static CYTHON_INLINE int __Pyx__IsSameCyOrCFunction(PyObject *func, void *cfunc) { + return __Pyx_CyOrPyCFunction_Check(func) && __Pyx_CyOrPyCFunction_GET_FUNCTION(func) == (PyCFunction) cfunc; +} +#endif +static CYTHON_INLINE void __Pyx__CyFunction_SetClassObj(__pyx_CyFunctionObject* f, PyObject* classobj) { +#if PY_VERSION_HEX < 0x030900B1 || CYTHON_COMPILING_IN_LIMITED_API + __Pyx_Py_XDECREF_SET( + __Pyx_CyFunction_GetClassObj(f), + ((classobj) ? __Pyx_NewRef(classobj) : NULL)); +#else + __Pyx_Py_XDECREF_SET( + ((PyCMethodObject *) (f))->mm_class, + (PyTypeObject*)((classobj) ? __Pyx_NewRef(classobj) : NULL)); +#endif +} +static PyObject * +__Pyx_CyFunction_get_doc(__pyx_CyFunctionObject *op, void *closure) +{ + CYTHON_UNUSED_VAR(closure); + if (unlikely(op->func_doc == NULL)) { +#if CYTHON_COMPILING_IN_LIMITED_API + op->func_doc = PyObject_GetAttrString(op->func, "__doc__"); + if (unlikely(!op->func_doc)) return NULL; +#else + if (((PyCFunctionObject*)op)->m_ml->ml_doc) { +#if PY_MAJOR_VERSION >= 3 + op->func_doc = PyUnicode_FromString(((PyCFunctionObject*)op)->m_ml->ml_doc); +#else + op->func_doc = PyString_FromString(((PyCFunctionObject*)op)->m_ml->ml_doc); +#endif + if (unlikely(op->func_doc == NULL)) + return NULL; + } else { + Py_INCREF(Py_None); + return Py_None; + } +#endif + } + Py_INCREF(op->func_doc); + return op->func_doc; +} +static int +__Pyx_CyFunction_set_doc(__pyx_CyFunctionObject *op, PyObject *value, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (value == NULL) { + value = Py_None; + } + Py_INCREF(value); + __Pyx_Py_XDECREF_SET(op->func_doc, value); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_name(__pyx_CyFunctionObject *op, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (unlikely(op->func_name == NULL)) { +#if CYTHON_COMPILING_IN_LIMITED_API + op->func_name = PyObject_GetAttrString(op->func, "__name__"); +#elif PY_MAJOR_VERSION >= 3 + op->func_name = PyUnicode_InternFromString(((PyCFunctionObject*)op)->m_ml->ml_name); +#else + op->func_name = PyString_InternFromString(((PyCFunctionObject*)op)->m_ml->ml_name); +#endif + if (unlikely(op->func_name == NULL)) + return NULL; + } + Py_INCREF(op->func_name); + return op->func_name; +} +static int +__Pyx_CyFunction_set_name(__pyx_CyFunctionObject *op, PyObject *value, void *context) +{ + CYTHON_UNUSED_VAR(context); +#if PY_MAJOR_VERSION >= 3 + if (unlikely(value == NULL || !PyUnicode_Check(value))) +#else + if (unlikely(value == NULL || !PyString_Check(value))) +#endif + { + PyErr_SetString(PyExc_TypeError, + "__name__ must be set to a string object"); + return -1; + } + Py_INCREF(value); + __Pyx_Py_XDECREF_SET(op->func_name, value); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_qualname(__pyx_CyFunctionObject *op, void *context) +{ + CYTHON_UNUSED_VAR(context); + Py_INCREF(op->func_qualname); + return op->func_qualname; +} +static int +__Pyx_CyFunction_set_qualname(__pyx_CyFunctionObject *op, PyObject *value, void *context) +{ + CYTHON_UNUSED_VAR(context); +#if PY_MAJOR_VERSION >= 3 + if (unlikely(value == NULL || !PyUnicode_Check(value))) +#else + if (unlikely(value == NULL || !PyString_Check(value))) +#endif + { + PyErr_SetString(PyExc_TypeError, + "__qualname__ must be set to a string object"); + return -1; + } + Py_INCREF(value); + __Pyx_Py_XDECREF_SET(op->func_qualname, value); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_dict(__pyx_CyFunctionObject *op, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (unlikely(op->func_dict == NULL)) { + op->func_dict = PyDict_New(); + if (unlikely(op->func_dict == NULL)) + return NULL; + } + Py_INCREF(op->func_dict); + return op->func_dict; +} +static int +__Pyx_CyFunction_set_dict(__pyx_CyFunctionObject *op, PyObject *value, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (unlikely(value == NULL)) { + PyErr_SetString(PyExc_TypeError, + "function's dictionary may not be deleted"); + return -1; + } + if (unlikely(!PyDict_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "setting function's dictionary to a non-dict"); + return -1; + } + Py_INCREF(value); + __Pyx_Py_XDECREF_SET(op->func_dict, value); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_globals(__pyx_CyFunctionObject *op, void *context) +{ + CYTHON_UNUSED_VAR(context); + Py_INCREF(op->func_globals); + return op->func_globals; +} +static PyObject * +__Pyx_CyFunction_get_closure(__pyx_CyFunctionObject *op, void *context) +{ + CYTHON_UNUSED_VAR(op); + CYTHON_UNUSED_VAR(context); + Py_INCREF(Py_None); + return Py_None; +} +static PyObject * +__Pyx_CyFunction_get_code(__pyx_CyFunctionObject *op, void *context) +{ + PyObject* result = (op->func_code) ? op->func_code : Py_None; + CYTHON_UNUSED_VAR(context); + Py_INCREF(result); + return result; +} +static int +__Pyx_CyFunction_init_defaults(__pyx_CyFunctionObject *op) { + int result = 0; + PyObject *res = op->defaults_getter((PyObject *) op); + if (unlikely(!res)) + return -1; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + op->defaults_tuple = PyTuple_GET_ITEM(res, 0); + Py_INCREF(op->defaults_tuple); + op->defaults_kwdict = PyTuple_GET_ITEM(res, 1); + Py_INCREF(op->defaults_kwdict); + #else + op->defaults_tuple = __Pyx_PySequence_ITEM(res, 0); + if (unlikely(!op->defaults_tuple)) result = -1; + else { + op->defaults_kwdict = __Pyx_PySequence_ITEM(res, 1); + if (unlikely(!op->defaults_kwdict)) result = -1; + } + #endif + Py_DECREF(res); + return result; +} +static int +__Pyx_CyFunction_set_defaults(__pyx_CyFunctionObject *op, PyObject* value, void *context) { + CYTHON_UNUSED_VAR(context); + if (!value) { + value = Py_None; + } else if (unlikely(value != Py_None && !PyTuple_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__defaults__ must be set to a tuple object"); + return -1; + } + PyErr_WarnEx(PyExc_RuntimeWarning, "changes to cyfunction.__defaults__ will not " + "currently affect the values used in function calls", 1); + Py_INCREF(value); + __Pyx_Py_XDECREF_SET(op->defaults_tuple, value); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_defaults(__pyx_CyFunctionObject *op, void *context) { + PyObject* result = op->defaults_tuple; + CYTHON_UNUSED_VAR(context); + if (unlikely(!result)) { + if (op->defaults_getter) { + if (unlikely(__Pyx_CyFunction_init_defaults(op) < 0)) return NULL; + result = op->defaults_tuple; + } else { + result = Py_None; + } + } + Py_INCREF(result); + return result; +} +static int +__Pyx_CyFunction_set_kwdefaults(__pyx_CyFunctionObject *op, PyObject* value, void *context) { + CYTHON_UNUSED_VAR(context); + if (!value) { + value = Py_None; + } else if (unlikely(value != Py_None && !PyDict_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__kwdefaults__ must be set to a dict object"); + return -1; + } + PyErr_WarnEx(PyExc_RuntimeWarning, "changes to cyfunction.__kwdefaults__ will not " + "currently affect the values used in function calls", 1); + Py_INCREF(value); + __Pyx_Py_XDECREF_SET(op->defaults_kwdict, value); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_kwdefaults(__pyx_CyFunctionObject *op, void *context) { + PyObject* result = op->defaults_kwdict; + CYTHON_UNUSED_VAR(context); + if (unlikely(!result)) { + if (op->defaults_getter) { + if (unlikely(__Pyx_CyFunction_init_defaults(op) < 0)) return NULL; + result = op->defaults_kwdict; + } else { + result = Py_None; + } + } + Py_INCREF(result); + return result; +} +static int +__Pyx_CyFunction_set_annotations(__pyx_CyFunctionObject *op, PyObject* value, void *context) { + CYTHON_UNUSED_VAR(context); + if (!value || value == Py_None) { + value = NULL; + } else if (unlikely(!PyDict_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__annotations__ must be set to a dict object"); + return -1; + } + Py_XINCREF(value); + __Pyx_Py_XDECREF_SET(op->func_annotations, value); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_annotations(__pyx_CyFunctionObject *op, void *context) { + PyObject* result = op->func_annotations; + CYTHON_UNUSED_VAR(context); + if (unlikely(!result)) { + result = PyDict_New(); + if (unlikely(!result)) return NULL; + op->func_annotations = result; + } + Py_INCREF(result); + return result; +} +static PyObject * +__Pyx_CyFunction_get_is_coroutine(__pyx_CyFunctionObject *op, void *context) { + int is_coroutine; + CYTHON_UNUSED_VAR(context); + if (op->func_is_coroutine) { + return __Pyx_NewRef(op->func_is_coroutine); + } + is_coroutine = op->flags & __Pyx_CYFUNCTION_COROUTINE; +#if PY_VERSION_HEX >= 0x03050000 + if (is_coroutine) { + PyObject *module, *fromlist, *marker = __pyx_n_s_is_coroutine; + fromlist = PyList_New(1); + if (unlikely(!fromlist)) return NULL; + Py_INCREF(marker); +#if CYTHON_ASSUME_SAFE_MACROS + PyList_SET_ITEM(fromlist, 0, marker); +#else + if (unlikely(PyList_SetItem(fromlist, 0, marker) < 0)) { + Py_DECREF(marker); + Py_DECREF(fromlist); + return NULL; + } +#endif + module = PyImport_ImportModuleLevelObject(__pyx_n_s_asyncio_coroutines, NULL, NULL, fromlist, 0); + Py_DECREF(fromlist); + if (unlikely(!module)) goto ignore; + op->func_is_coroutine = __Pyx_PyObject_GetAttrStr(module, marker); + Py_DECREF(module); + if (likely(op->func_is_coroutine)) { + return __Pyx_NewRef(op->func_is_coroutine); + } +ignore: + PyErr_Clear(); + } +#endif + op->func_is_coroutine = __Pyx_PyBool_FromLong(is_coroutine); + return __Pyx_NewRef(op->func_is_coroutine); +} +#if CYTHON_COMPILING_IN_LIMITED_API +static PyObject * +__Pyx_CyFunction_get_module(__pyx_CyFunctionObject *op, void *context) { + CYTHON_UNUSED_VAR(context); + return PyObject_GetAttrString(op->func, "__module__"); +} +static int +__Pyx_CyFunction_set_module(__pyx_CyFunctionObject *op, PyObject* value, void *context) { + CYTHON_UNUSED_VAR(context); + return PyObject_SetAttrString(op->func, "__module__", value); +} +#endif +static PyGetSetDef __pyx_CyFunction_getsets[] = { + {(char *) "func_doc", (getter)__Pyx_CyFunction_get_doc, (setter)__Pyx_CyFunction_set_doc, 0, 0}, + {(char *) "__doc__", (getter)__Pyx_CyFunction_get_doc, (setter)__Pyx_CyFunction_set_doc, 0, 0}, + {(char *) "func_name", (getter)__Pyx_CyFunction_get_name, (setter)__Pyx_CyFunction_set_name, 0, 0}, + {(char *) "__name__", (getter)__Pyx_CyFunction_get_name, (setter)__Pyx_CyFunction_set_name, 0, 0}, + {(char *) "__qualname__", (getter)__Pyx_CyFunction_get_qualname, (setter)__Pyx_CyFunction_set_qualname, 0, 0}, + {(char *) "func_dict", (getter)__Pyx_CyFunction_get_dict, (setter)__Pyx_CyFunction_set_dict, 0, 0}, + {(char *) "__dict__", (getter)__Pyx_CyFunction_get_dict, (setter)__Pyx_CyFunction_set_dict, 0, 0}, + {(char *) "func_globals", (getter)__Pyx_CyFunction_get_globals, 0, 0, 0}, + {(char *) "__globals__", (getter)__Pyx_CyFunction_get_globals, 0, 0, 0}, + {(char *) "func_closure", (getter)__Pyx_CyFunction_get_closure, 0, 0, 0}, + {(char *) "__closure__", (getter)__Pyx_CyFunction_get_closure, 0, 0, 0}, + {(char *) "func_code", (getter)__Pyx_CyFunction_get_code, 0, 0, 0}, + {(char *) "__code__", (getter)__Pyx_CyFunction_get_code, 0, 0, 0}, + {(char *) "func_defaults", (getter)__Pyx_CyFunction_get_defaults, (setter)__Pyx_CyFunction_set_defaults, 0, 0}, + {(char *) "__defaults__", (getter)__Pyx_CyFunction_get_defaults, (setter)__Pyx_CyFunction_set_defaults, 0, 0}, + {(char *) "__kwdefaults__", (getter)__Pyx_CyFunction_get_kwdefaults, (setter)__Pyx_CyFunction_set_kwdefaults, 0, 0}, + {(char *) "__annotations__", (getter)__Pyx_CyFunction_get_annotations, (setter)__Pyx_CyFunction_set_annotations, 0, 0}, + {(char *) "_is_coroutine", (getter)__Pyx_CyFunction_get_is_coroutine, 0, 0, 0}, +#if CYTHON_COMPILING_IN_LIMITED_API + {"__module__", (getter)__Pyx_CyFunction_get_module, (setter)__Pyx_CyFunction_set_module, 0, 0}, +#endif + {0, 0, 0, 0, 0} +}; +static PyMemberDef __pyx_CyFunction_members[] = { +#if !CYTHON_COMPILING_IN_LIMITED_API + {(char *) "__module__", T_OBJECT, offsetof(PyCFunctionObject, m_module), 0, 0}, +#endif +#if CYTHON_USE_TYPE_SPECS + {(char *) "__dictoffset__", T_PYSSIZET, offsetof(__pyx_CyFunctionObject, func_dict), READONLY, 0}, +#if CYTHON_METH_FASTCALL +#if CYTHON_BACKPORT_VECTORCALL + {(char *) "__vectorcalloffset__", T_PYSSIZET, offsetof(__pyx_CyFunctionObject, func_vectorcall), READONLY, 0}, +#else +#if !CYTHON_COMPILING_IN_LIMITED_API + {(char *) "__vectorcalloffset__", T_PYSSIZET, offsetof(PyCFunctionObject, vectorcall), READONLY, 0}, +#endif +#endif +#endif +#if PY_VERSION_HEX < 0x030500A0 || CYTHON_COMPILING_IN_LIMITED_API + {(char *) "__weaklistoffset__", T_PYSSIZET, offsetof(__pyx_CyFunctionObject, func_weakreflist), READONLY, 0}, +#else + {(char *) "__weaklistoffset__", T_PYSSIZET, offsetof(PyCFunctionObject, m_weakreflist), READONLY, 0}, +#endif +#endif + {0, 0, 0, 0, 0} +}; +static PyObject * +__Pyx_CyFunction_reduce(__pyx_CyFunctionObject *m, PyObject *args) +{ + CYTHON_UNUSED_VAR(args); +#if PY_MAJOR_VERSION >= 3 + Py_INCREF(m->func_qualname); + return m->func_qualname; +#else + return PyString_FromString(((PyCFunctionObject*)m)->m_ml->ml_name); +#endif +} +static PyMethodDef __pyx_CyFunction_methods[] = { + {"__reduce__", (PyCFunction)__Pyx_CyFunction_reduce, METH_VARARGS, 0}, + {0, 0, 0, 0} +}; +#if PY_VERSION_HEX < 0x030500A0 || CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_CyFunction_weakreflist(cyfunc) ((cyfunc)->func_weakreflist) +#else +#define __Pyx_CyFunction_weakreflist(cyfunc) (((PyCFunctionObject*)cyfunc)->m_weakreflist) +#endif +static PyObject *__Pyx_CyFunction_Init(__pyx_CyFunctionObject *op, PyMethodDef *ml, int flags, PyObject* qualname, + PyObject *closure, PyObject *module, PyObject* globals, PyObject* code) { +#if !CYTHON_COMPILING_IN_LIMITED_API + PyCFunctionObject *cf = (PyCFunctionObject*) op; +#endif + if (unlikely(op == NULL)) + return NULL; +#if CYTHON_COMPILING_IN_LIMITED_API + op->func = PyCFunction_NewEx(ml, (PyObject*)op, module); + if (unlikely(!op->func)) return NULL; +#endif + op->flags = flags; + __Pyx_CyFunction_weakreflist(op) = NULL; +#if !CYTHON_COMPILING_IN_LIMITED_API + cf->m_ml = ml; + cf->m_self = (PyObject *) op; +#endif + Py_XINCREF(closure); + op->func_closure = closure; +#if !CYTHON_COMPILING_IN_LIMITED_API + Py_XINCREF(module); + cf->m_module = module; +#endif + op->func_dict = NULL; + op->func_name = NULL; + Py_INCREF(qualname); + op->func_qualname = qualname; + op->func_doc = NULL; +#if PY_VERSION_HEX < 0x030900B1 || CYTHON_COMPILING_IN_LIMITED_API + op->func_classobj = NULL; +#else + ((PyCMethodObject*)op)->mm_class = NULL; +#endif + op->func_globals = globals; + Py_INCREF(op->func_globals); + Py_XINCREF(code); + op->func_code = code; + op->defaults_pyobjects = 0; + op->defaults_size = 0; + op->defaults = NULL; + op->defaults_tuple = NULL; + op->defaults_kwdict = NULL; + op->defaults_getter = NULL; + op->func_annotations = NULL; + op->func_is_coroutine = NULL; +#if CYTHON_METH_FASTCALL + switch (ml->ml_flags & (METH_VARARGS | METH_FASTCALL | METH_NOARGS | METH_O | METH_KEYWORDS | METH_METHOD)) { + case METH_NOARGS: + __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_NOARGS; + break; + case METH_O: + __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_O; + break; + case METH_METHOD | METH_FASTCALL | METH_KEYWORDS: + __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS_METHOD; + break; + case METH_FASTCALL | METH_KEYWORDS: + __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS; + break; + case METH_VARARGS | METH_KEYWORDS: + __Pyx_CyFunction_func_vectorcall(op) = NULL; + break; + default: + PyErr_SetString(PyExc_SystemError, "Bad call flags for CyFunction"); + Py_DECREF(op); + return NULL; + } +#endif + return (PyObject *) op; +} +static int +__Pyx_CyFunction_clear(__pyx_CyFunctionObject *m) +{ + Py_CLEAR(m->func_closure); +#if CYTHON_COMPILING_IN_LIMITED_API + Py_CLEAR(m->func); +#else + Py_CLEAR(((PyCFunctionObject*)m)->m_module); +#endif + Py_CLEAR(m->func_dict); + Py_CLEAR(m->func_name); + Py_CLEAR(m->func_qualname); + Py_CLEAR(m->func_doc); + Py_CLEAR(m->func_globals); + Py_CLEAR(m->func_code); +#if !CYTHON_COMPILING_IN_LIMITED_API +#if PY_VERSION_HEX < 0x030900B1 + Py_CLEAR(__Pyx_CyFunction_GetClassObj(m)); +#else + { + PyObject *cls = (PyObject*) ((PyCMethodObject *) (m))->mm_class; + ((PyCMethodObject *) (m))->mm_class = NULL; + Py_XDECREF(cls); + } +#endif +#endif + Py_CLEAR(m->defaults_tuple); + Py_CLEAR(m->defaults_kwdict); + Py_CLEAR(m->func_annotations); + Py_CLEAR(m->func_is_coroutine); + if (m->defaults) { + PyObject **pydefaults = __Pyx_CyFunction_Defaults(PyObject *, m); + int i; + for (i = 0; i < m->defaults_pyobjects; i++) + Py_XDECREF(pydefaults[i]); + PyObject_Free(m->defaults); + m->defaults = NULL; + } + return 0; +} +static void __Pyx__CyFunction_dealloc(__pyx_CyFunctionObject *m) +{ + if (__Pyx_CyFunction_weakreflist(m) != NULL) + PyObject_ClearWeakRefs((PyObject *) m); + __Pyx_CyFunction_clear(m); + __Pyx_PyHeapTypeObject_GC_Del(m); +} +static void __Pyx_CyFunction_dealloc(__pyx_CyFunctionObject *m) +{ + PyObject_GC_UnTrack(m); + __Pyx__CyFunction_dealloc(m); +} +static int __Pyx_CyFunction_traverse(__pyx_CyFunctionObject *m, visitproc visit, void *arg) +{ + Py_VISIT(m->func_closure); +#if CYTHON_COMPILING_IN_LIMITED_API + Py_VISIT(m->func); +#else + Py_VISIT(((PyCFunctionObject*)m)->m_module); +#endif + Py_VISIT(m->func_dict); + Py_VISIT(m->func_name); + Py_VISIT(m->func_qualname); + Py_VISIT(m->func_doc); + Py_VISIT(m->func_globals); + Py_VISIT(m->func_code); +#if !CYTHON_COMPILING_IN_LIMITED_API + Py_VISIT(__Pyx_CyFunction_GetClassObj(m)); +#endif + Py_VISIT(m->defaults_tuple); + Py_VISIT(m->defaults_kwdict); + Py_VISIT(m->func_is_coroutine); + if (m->defaults) { + PyObject **pydefaults = __Pyx_CyFunction_Defaults(PyObject *, m); + int i; + for (i = 0; i < m->defaults_pyobjects; i++) + Py_VISIT(pydefaults[i]); + } + return 0; +} +static PyObject* +__Pyx_CyFunction_repr(__pyx_CyFunctionObject *op) +{ +#if PY_MAJOR_VERSION >= 3 + return PyUnicode_FromFormat("", + op->func_qualname, (void *)op); +#else + return PyString_FromFormat("", + PyString_AsString(op->func_qualname), (void *)op); +#endif +} +static PyObject * __Pyx_CyFunction_CallMethod(PyObject *func, PyObject *self, PyObject *arg, PyObject *kw) { +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *f = ((__pyx_CyFunctionObject*)func)->func; + PyObject *py_name = NULL; + PyCFunction meth; + int flags; + meth = PyCFunction_GetFunction(f); + if (unlikely(!meth)) return NULL; + flags = PyCFunction_GetFlags(f); + if (unlikely(flags < 0)) return NULL; +#else + PyCFunctionObject* f = (PyCFunctionObject*)func; + PyCFunction meth = f->m_ml->ml_meth; + int flags = f->m_ml->ml_flags; +#endif + Py_ssize_t size; + switch (flags & (METH_VARARGS | METH_KEYWORDS | METH_NOARGS | METH_O)) { + case METH_VARARGS: + if (likely(kw == NULL || PyDict_Size(kw) == 0)) + return (*meth)(self, arg); + break; + case METH_VARARGS | METH_KEYWORDS: + return (*(PyCFunctionWithKeywords)(void*)meth)(self, arg, kw); + case METH_NOARGS: + if (likely(kw == NULL || PyDict_Size(kw) == 0)) { +#if CYTHON_ASSUME_SAFE_MACROS + size = PyTuple_GET_SIZE(arg); +#else + size = PyTuple_Size(arg); + if (unlikely(size < 0)) return NULL; +#endif + if (likely(size == 0)) + return (*meth)(self, NULL); +#if CYTHON_COMPILING_IN_LIMITED_API + py_name = __Pyx_CyFunction_get_name((__pyx_CyFunctionObject*)func, NULL); + if (!py_name) return NULL; + PyErr_Format(PyExc_TypeError, + "%.200S() takes no arguments (%" CYTHON_FORMAT_SSIZE_T "d given)", + py_name, size); + Py_DECREF(py_name); +#else + PyErr_Format(PyExc_TypeError, + "%.200s() takes no arguments (%" CYTHON_FORMAT_SSIZE_T "d given)", + f->m_ml->ml_name, size); +#endif + return NULL; + } + break; + case METH_O: + if (likely(kw == NULL || PyDict_Size(kw) == 0)) { +#if CYTHON_ASSUME_SAFE_MACROS + size = PyTuple_GET_SIZE(arg); +#else + size = PyTuple_Size(arg); + if (unlikely(size < 0)) return NULL; +#endif + if (likely(size == 1)) { + PyObject *result, *arg0; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + arg0 = PyTuple_GET_ITEM(arg, 0); + #else + arg0 = __Pyx_PySequence_ITEM(arg, 0); if (unlikely(!arg0)) return NULL; + #endif + result = (*meth)(self, arg0); + #if !(CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS) + Py_DECREF(arg0); + #endif + return result; + } +#if CYTHON_COMPILING_IN_LIMITED_API + py_name = __Pyx_CyFunction_get_name((__pyx_CyFunctionObject*)func, NULL); + if (!py_name) return NULL; + PyErr_Format(PyExc_TypeError, + "%.200S() takes exactly one argument (%" CYTHON_FORMAT_SSIZE_T "d given)", + py_name, size); + Py_DECREF(py_name); +#else + PyErr_Format(PyExc_TypeError, + "%.200s() takes exactly one argument (%" CYTHON_FORMAT_SSIZE_T "d given)", + f->m_ml->ml_name, size); +#endif + return NULL; + } + break; + default: + PyErr_SetString(PyExc_SystemError, "Bad call flags for CyFunction"); + return NULL; + } +#if CYTHON_COMPILING_IN_LIMITED_API + py_name = __Pyx_CyFunction_get_name((__pyx_CyFunctionObject*)func, NULL); + if (!py_name) return NULL; + PyErr_Format(PyExc_TypeError, "%.200S() takes no keyword arguments", + py_name); + Py_DECREF(py_name); +#else + PyErr_Format(PyExc_TypeError, "%.200s() takes no keyword arguments", + f->m_ml->ml_name); +#endif + return NULL; +} +static CYTHON_INLINE PyObject *__Pyx_CyFunction_Call(PyObject *func, PyObject *arg, PyObject *kw) { + PyObject *self, *result; +#if CYTHON_COMPILING_IN_LIMITED_API + self = PyCFunction_GetSelf(((__pyx_CyFunctionObject*)func)->func); + if (unlikely(!self) && PyErr_Occurred()) return NULL; +#else + self = ((PyCFunctionObject*)func)->m_self; +#endif + result = __Pyx_CyFunction_CallMethod(func, self, arg, kw); + return result; +} +static PyObject *__Pyx_CyFunction_CallAsMethod(PyObject *func, PyObject *args, PyObject *kw) { + PyObject *result; + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *) func; +#if CYTHON_METH_FASTCALL + __pyx_vectorcallfunc vc = __Pyx_CyFunction_func_vectorcall(cyfunc); + if (vc) { +#if CYTHON_ASSUME_SAFE_MACROS + return __Pyx_PyVectorcall_FastCallDict(func, vc, &PyTuple_GET_ITEM(args, 0), (size_t)PyTuple_GET_SIZE(args), kw); +#else + (void) &__Pyx_PyVectorcall_FastCallDict; + return PyVectorcall_Call(func, args, kw); +#endif + } +#endif + if ((cyfunc->flags & __Pyx_CYFUNCTION_CCLASS) && !(cyfunc->flags & __Pyx_CYFUNCTION_STATICMETHOD)) { + Py_ssize_t argc; + PyObject *new_args; + PyObject *self; +#if CYTHON_ASSUME_SAFE_MACROS + argc = PyTuple_GET_SIZE(args); +#else + argc = PyTuple_Size(args); + if (unlikely(!argc) < 0) return NULL; +#endif + new_args = PyTuple_GetSlice(args, 1, argc); + if (unlikely(!new_args)) + return NULL; + self = PyTuple_GetItem(args, 0); + if (unlikely(!self)) { + Py_DECREF(new_args); +#if PY_MAJOR_VERSION > 2 + PyErr_Format(PyExc_TypeError, + "unbound method %.200S() needs an argument", + cyfunc->func_qualname); +#else + PyErr_SetString(PyExc_TypeError, + "unbound method needs an argument"); +#endif + return NULL; + } + result = __Pyx_CyFunction_CallMethod(func, self, new_args, kw); + Py_DECREF(new_args); + } else { + result = __Pyx_CyFunction_Call(func, args, kw); + } + return result; +} +#if CYTHON_METH_FASTCALL +static CYTHON_INLINE int __Pyx_CyFunction_Vectorcall_CheckArgs(__pyx_CyFunctionObject *cyfunc, Py_ssize_t nargs, PyObject *kwnames) +{ + int ret = 0; + if ((cyfunc->flags & __Pyx_CYFUNCTION_CCLASS) && !(cyfunc->flags & __Pyx_CYFUNCTION_STATICMETHOD)) { + if (unlikely(nargs < 1)) { + PyErr_Format(PyExc_TypeError, "%.200s() needs an argument", + ((PyCFunctionObject*)cyfunc)->m_ml->ml_name); + return -1; + } + ret = 1; + } + if (unlikely(kwnames) && unlikely(PyTuple_GET_SIZE(kwnames))) { + PyErr_Format(PyExc_TypeError, + "%.200s() takes no keyword arguments", ((PyCFunctionObject*)cyfunc)->m_ml->ml_name); + return -1; + } + return ret; +} +static PyObject * __Pyx_CyFunction_Vectorcall_NOARGS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) +{ + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *)func; + PyMethodDef* def = ((PyCFunctionObject*)cyfunc)->m_ml; +#if CYTHON_BACKPORT_VECTORCALL + Py_ssize_t nargs = (Py_ssize_t)nargsf; +#else + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); +#endif + PyObject *self; + switch (__Pyx_CyFunction_Vectorcall_CheckArgs(cyfunc, nargs, kwnames)) { + case 1: + self = args[0]; + args += 1; + nargs -= 1; + break; + case 0: + self = ((PyCFunctionObject*)cyfunc)->m_self; + break; + default: + return NULL; + } + if (unlikely(nargs != 0)) { + PyErr_Format(PyExc_TypeError, + "%.200s() takes no arguments (%" CYTHON_FORMAT_SSIZE_T "d given)", + def->ml_name, nargs); + return NULL; + } + return def->ml_meth(self, NULL); +} +static PyObject * __Pyx_CyFunction_Vectorcall_O(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) +{ + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *)func; + PyMethodDef* def = ((PyCFunctionObject*)cyfunc)->m_ml; +#if CYTHON_BACKPORT_VECTORCALL + Py_ssize_t nargs = (Py_ssize_t)nargsf; +#else + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); +#endif + PyObject *self; + switch (__Pyx_CyFunction_Vectorcall_CheckArgs(cyfunc, nargs, kwnames)) { + case 1: + self = args[0]; + args += 1; + nargs -= 1; + break; + case 0: + self = ((PyCFunctionObject*)cyfunc)->m_self; + break; + default: + return NULL; + } + if (unlikely(nargs != 1)) { + PyErr_Format(PyExc_TypeError, + "%.200s() takes exactly one argument (%" CYTHON_FORMAT_SSIZE_T "d given)", + def->ml_name, nargs); + return NULL; + } + return def->ml_meth(self, args[0]); +} +static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) +{ + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *)func; + PyMethodDef* def = ((PyCFunctionObject*)cyfunc)->m_ml; +#if CYTHON_BACKPORT_VECTORCALL + Py_ssize_t nargs = (Py_ssize_t)nargsf; +#else + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); +#endif + PyObject *self; + switch (__Pyx_CyFunction_Vectorcall_CheckArgs(cyfunc, nargs, NULL)) { + case 1: + self = args[0]; + args += 1; + nargs -= 1; + break; + case 0: + self = ((PyCFunctionObject*)cyfunc)->m_self; + break; + default: + return NULL; + } + return ((_PyCFunctionFastWithKeywords)(void(*)(void))def->ml_meth)(self, args, nargs, kwnames); +} +static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS_METHOD(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) +{ + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *)func; + PyMethodDef* def = ((PyCFunctionObject*)cyfunc)->m_ml; + PyTypeObject *cls = (PyTypeObject *) __Pyx_CyFunction_GetClassObj(cyfunc); +#if CYTHON_BACKPORT_VECTORCALL + Py_ssize_t nargs = (Py_ssize_t)nargsf; +#else + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); +#endif + PyObject *self; + switch (__Pyx_CyFunction_Vectorcall_CheckArgs(cyfunc, nargs, NULL)) { + case 1: + self = args[0]; + args += 1; + nargs -= 1; + break; + case 0: + self = ((PyCFunctionObject*)cyfunc)->m_self; + break; + default: + return NULL; + } + return ((__Pyx_PyCMethod)(void(*)(void))def->ml_meth)(self, cls, args, (size_t)nargs, kwnames); +} +#endif +#if CYTHON_USE_TYPE_SPECS +static PyType_Slot __pyx_CyFunctionType_slots[] = { + {Py_tp_dealloc, (void *)__Pyx_CyFunction_dealloc}, + {Py_tp_repr, (void *)__Pyx_CyFunction_repr}, + {Py_tp_call, (void *)__Pyx_CyFunction_CallAsMethod}, + {Py_tp_traverse, (void *)__Pyx_CyFunction_traverse}, + {Py_tp_clear, (void *)__Pyx_CyFunction_clear}, + {Py_tp_methods, (void *)__pyx_CyFunction_methods}, + {Py_tp_members, (void *)__pyx_CyFunction_members}, + {Py_tp_getset, (void *)__pyx_CyFunction_getsets}, + {Py_tp_descr_get, (void *)__Pyx_PyMethod_New}, + {0, 0}, +}; +static PyType_Spec __pyx_CyFunctionType_spec = { + __PYX_TYPE_MODULE_PREFIX "cython_function_or_method", + sizeof(__pyx_CyFunctionObject), + 0, +#ifdef Py_TPFLAGS_METHOD_DESCRIPTOR + Py_TPFLAGS_METHOD_DESCRIPTOR | +#endif +#if (defined(_Py_TPFLAGS_HAVE_VECTORCALL) && CYTHON_METH_FASTCALL) + _Py_TPFLAGS_HAVE_VECTORCALL | +#endif + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, + __pyx_CyFunctionType_slots +}; +#else +static PyTypeObject __pyx_CyFunctionType_type = { + PyVarObject_HEAD_INIT(0, 0) + __PYX_TYPE_MODULE_PREFIX "cython_function_or_method", + sizeof(__pyx_CyFunctionObject), + 0, + (destructor) __Pyx_CyFunction_dealloc, +#if !CYTHON_METH_FASTCALL + 0, +#elif CYTHON_BACKPORT_VECTORCALL + (printfunc)offsetof(__pyx_CyFunctionObject, func_vectorcall), +#else + offsetof(PyCFunctionObject, vectorcall), +#endif + 0, + 0, +#if PY_MAJOR_VERSION < 3 + 0, +#else + 0, +#endif + (reprfunc) __Pyx_CyFunction_repr, + 0, + 0, + 0, + 0, + __Pyx_CyFunction_CallAsMethod, + 0, + 0, + 0, + 0, +#ifdef Py_TPFLAGS_METHOD_DESCRIPTOR + Py_TPFLAGS_METHOD_DESCRIPTOR | +#endif +#if defined(_Py_TPFLAGS_HAVE_VECTORCALL) && CYTHON_METH_FASTCALL + _Py_TPFLAGS_HAVE_VECTORCALL | +#endif + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, + 0, + (traverseproc) __Pyx_CyFunction_traverse, + (inquiry) __Pyx_CyFunction_clear, + 0, +#if PY_VERSION_HEX < 0x030500A0 + offsetof(__pyx_CyFunctionObject, func_weakreflist), +#else + offsetof(PyCFunctionObject, m_weakreflist), +#endif + 0, + 0, + __pyx_CyFunction_methods, + __pyx_CyFunction_members, + __pyx_CyFunction_getsets, + 0, + 0, + __Pyx_PyMethod_New, + 0, + offsetof(__pyx_CyFunctionObject, func_dict), + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, +#if PY_VERSION_HEX >= 0x030400a1 + 0, +#endif +#if PY_VERSION_HEX >= 0x030800b1 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) + 0, +#endif +#if __PYX_NEED_TP_PRINT_SLOT + 0, +#endif +#if PY_VERSION_HEX >= 0x030C0000 + 0, +#endif +#if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 + 0, +#endif +}; +#endif +static int __pyx_CyFunction_init(PyObject *module) { +#if CYTHON_USE_TYPE_SPECS + __pyx_CyFunctionType = __Pyx_FetchCommonTypeFromSpec(module, &__pyx_CyFunctionType_spec, NULL); +#else + CYTHON_UNUSED_VAR(module); + __pyx_CyFunctionType = __Pyx_FetchCommonType(&__pyx_CyFunctionType_type); +#endif + if (unlikely(__pyx_CyFunctionType == NULL)) { + return -1; + } + return 0; +} +static CYTHON_INLINE void *__Pyx_CyFunction_InitDefaults(PyObject *func, size_t size, int pyobjects) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->defaults = PyObject_Malloc(size); + if (unlikely(!m->defaults)) + return PyErr_NoMemory(); + memset(m->defaults, 0, size); + m->defaults_pyobjects = pyobjects; + m->defaults_size = size; + return m->defaults; +} +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsTuple(PyObject *func, PyObject *tuple) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->defaults_tuple = tuple; + Py_INCREF(tuple); +} +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsKwDict(PyObject *func, PyObject *dict) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->defaults_kwdict = dict; + Py_INCREF(dict); +} +static CYTHON_INLINE void __Pyx_CyFunction_SetAnnotationsDict(PyObject *func, PyObject *dict) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->func_annotations = dict; + Py_INCREF(dict); +} + +/* CythonFunction */ +static PyObject *__Pyx_CyFunction_New(PyMethodDef *ml, int flags, PyObject* qualname, + PyObject *closure, PyObject *module, PyObject* globals, PyObject* code) { + PyObject *op = __Pyx_CyFunction_Init( + PyObject_GC_New(__pyx_CyFunctionObject, __pyx_CyFunctionType), + ml, flags, qualname, closure, module, globals, code + ); + if (likely(op)) { + PyObject_GC_Track(op); + } + return op; +} + +/* GetNameInClass */ +static PyObject *__Pyx__GetNameInClass(PyObject *nmspace, PyObject *name) { + PyObject *result; + PyObject *dict; + assert(PyType_Check(nmspace)); +#if CYTHON_USE_TYPE_SLOTS + dict = ((PyTypeObject*)nmspace)->tp_dict; + Py_XINCREF(dict); +#else + dict = PyObject_GetAttr(nmspace, __pyx_n_s_dict); +#endif + if (likely(dict)) { + result = PyObject_GetItem(dict, name); + Py_DECREF(dict); + if (result) { + return result; + } + } + PyErr_Clear(); + __Pyx_GetModuleGlobalNameUncached(result, name); + return result; +} + +/* CLineInTraceback */ +#ifndef CYTHON_CLINE_IN_TRACEBACK +static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line) { + PyObject *use_cline; + PyObject *ptype, *pvalue, *ptraceback; +#if CYTHON_COMPILING_IN_CPYTHON + PyObject **cython_runtime_dict; +#endif + CYTHON_MAYBE_UNUSED_VAR(tstate); + if (unlikely(!__pyx_cython_runtime)) { + return c_line; + } + __Pyx_ErrFetchInState(tstate, &ptype, &pvalue, &ptraceback); +#if CYTHON_COMPILING_IN_CPYTHON + cython_runtime_dict = _PyObject_GetDictPtr(__pyx_cython_runtime); + if (likely(cython_runtime_dict)) { + __PYX_PY_DICT_LOOKUP_IF_MODIFIED( + use_cline, *cython_runtime_dict, + __Pyx_PyDict_GetItemStr(*cython_runtime_dict, __pyx_n_s_cline_in_traceback)) + } else +#endif + { + PyObject *use_cline_obj = __Pyx_PyObject_GetAttrStrNoError(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback); + if (use_cline_obj) { + use_cline = PyObject_Not(use_cline_obj) ? Py_False : Py_True; + Py_DECREF(use_cline_obj); + } else { + PyErr_Clear(); + use_cline = NULL; + } + } + if (!use_cline) { + c_line = 0; + (void) PyObject_SetAttr(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback, Py_False); + } + else if (use_cline == Py_False || (use_cline != Py_True && PyObject_Not(use_cline) != 0)) { + c_line = 0; + } + __Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback); + return c_line; +} +#endif + +/* CodeObjectCache */ +#if !CYTHON_COMPILING_IN_LIMITED_API +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { + int start = 0, mid = 0, end = count - 1; + if (end >= 0 && code_line > entries[end].code_line) { + return count; + } + while (start < end) { + mid = start + (end - start) / 2; + if (code_line < entries[mid].code_line) { + end = mid; + } else if (code_line > entries[mid].code_line) { + start = mid + 1; + } else { + return mid; + } + } + if (code_line <= entries[mid].code_line) { + return mid; + } else { + return mid + 1; + } +} +static PyCodeObject *__pyx_find_code_object(int code_line) { + PyCodeObject* code_object; + int pos; + if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { + return NULL; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { + return NULL; + } + code_object = __pyx_code_cache.entries[pos].code_object; + Py_INCREF(code_object); + return code_object; +} +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { + int pos, i; + __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; + if (unlikely(!code_line)) { + return; + } + if (unlikely(!entries)) { + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); + if (likely(entries)) { + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = 64; + __pyx_code_cache.count = 1; + entries[0].code_line = code_line; + entries[0].code_object = code_object; + Py_INCREF(code_object); + } + return; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { + PyCodeObject* tmp = entries[pos].code_object; + entries[pos].code_object = code_object; + Py_DECREF(tmp); + return; + } + if (__pyx_code_cache.count == __pyx_code_cache.max_count) { + int new_max = __pyx_code_cache.max_count + 64; + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( + __pyx_code_cache.entries, ((size_t)new_max) * sizeof(__Pyx_CodeObjectCacheEntry)); + if (unlikely(!entries)) { + return; + } + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = new_max; + } + for (i=__pyx_code_cache.count; i>pos; i--) { + entries[i] = entries[i-1]; + } + entries[pos].code_line = code_line; + entries[pos].code_object = code_object; + __pyx_code_cache.count++; + Py_INCREF(code_object); +} +#endif + +/* AddTraceback */ +#include "compile.h" +#include "frameobject.h" +#include "traceback.h" +#if PY_VERSION_HEX >= 0x030b00a6 && !CYTHON_COMPILING_IN_LIMITED_API + #ifndef Py_BUILD_CORE + #define Py_BUILD_CORE 1 + #endif + #include "internal/pycore_frame.h" +#endif +#if CYTHON_COMPILING_IN_LIMITED_API +static PyObject *__Pyx_PyCode_Replace_For_AddTraceback(PyObject *code, PyObject *scratch_dict, + PyObject *firstlineno, PyObject *name) { + PyObject *replace = NULL; + if (unlikely(PyDict_SetItemString(scratch_dict, "co_firstlineno", firstlineno))) return NULL; + if (unlikely(PyDict_SetItemString(scratch_dict, "co_name", name))) return NULL; + replace = PyObject_GetAttrString(code, "replace"); + if (likely(replace)) { + PyObject *result; + result = PyObject_Call(replace, __pyx_empty_tuple, scratch_dict); + Py_DECREF(replace); + return result; + } + PyErr_Clear(); + #if __PYX_LIMITED_VERSION_HEX < 0x030780000 + { + PyObject *compiled = NULL, *result = NULL; + if (unlikely(PyDict_SetItemString(scratch_dict, "code", code))) return NULL; + if (unlikely(PyDict_SetItemString(scratch_dict, "type", (PyObject*)(&PyType_Type)))) return NULL; + compiled = Py_CompileString( + "out = type(code)(\n" + " code.co_argcount, code.co_kwonlyargcount, code.co_nlocals, code.co_stacksize,\n" + " code.co_flags, code.co_code, code.co_consts, code.co_names,\n" + " code.co_varnames, code.co_filename, co_name, co_firstlineno,\n" + " code.co_lnotab)\n", "", Py_file_input); + if (!compiled) return NULL; + result = PyEval_EvalCode(compiled, scratch_dict, scratch_dict); + Py_DECREF(compiled); + if (!result) PyErr_Print(); + Py_DECREF(result); + result = PyDict_GetItemString(scratch_dict, "out"); + if (result) Py_INCREF(result); + return result; + } + #else + return NULL; + #endif +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyObject *code_object = NULL, *py_py_line = NULL, *py_funcname = NULL, *dict = NULL; + PyObject *replace = NULL, *getframe = NULL, *frame = NULL; + PyObject *exc_type, *exc_value, *exc_traceback; + int success = 0; + if (c_line) { + (void) __pyx_cfilenm; + (void) __Pyx_CLineForTraceback(__Pyx_PyThreadState_Current, c_line); + } + PyErr_Fetch(&exc_type, &exc_value, &exc_traceback); + code_object = Py_CompileString("_getframe()", filename, Py_eval_input); + if (unlikely(!code_object)) goto bad; + py_py_line = PyLong_FromLong(py_line); + if (unlikely(!py_py_line)) goto bad; + py_funcname = PyUnicode_FromString(funcname); + if (unlikely(!py_funcname)) goto bad; + dict = PyDict_New(); + if (unlikely(!dict)) goto bad; + { + PyObject *old_code_object = code_object; + code_object = __Pyx_PyCode_Replace_For_AddTraceback(code_object, dict, py_py_line, py_funcname); + Py_DECREF(old_code_object); + } + if (unlikely(!code_object)) goto bad; + getframe = PySys_GetObject("_getframe"); + if (unlikely(!getframe)) goto bad; + if (unlikely(PyDict_SetItemString(dict, "_getframe", getframe))) goto bad; + frame = PyEval_EvalCode(code_object, dict, dict); + if (unlikely(!frame) || frame == Py_None) goto bad; + success = 1; + bad: + PyErr_Restore(exc_type, exc_value, exc_traceback); + Py_XDECREF(code_object); + Py_XDECREF(py_py_line); + Py_XDECREF(py_funcname); + Py_XDECREF(dict); + Py_XDECREF(replace); + if (success) { + PyTraceBack_Here( + (struct _frame*)frame); + } + Py_XDECREF(frame); +} +#else +static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( + const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = NULL; + PyObject *py_funcname = NULL; + #if PY_MAJOR_VERSION < 3 + PyObject *py_srcfile = NULL; + py_srcfile = PyString_FromString(filename); + if (!py_srcfile) goto bad; + #endif + if (c_line) { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + if (!py_funcname) goto bad; + #else + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + if (!py_funcname) goto bad; + funcname = PyUnicode_AsUTF8(py_funcname); + if (!funcname) goto bad; + #endif + } + else { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromString(funcname); + if (!py_funcname) goto bad; + #endif + } + #if PY_MAJOR_VERSION < 3 + py_code = __Pyx_PyCode_New( + 0, + 0, + 0, + 0, + 0, + 0, + __pyx_empty_bytes, /*PyObject *code,*/ + __pyx_empty_tuple, /*PyObject *consts,*/ + __pyx_empty_tuple, /*PyObject *names,*/ + __pyx_empty_tuple, /*PyObject *varnames,*/ + __pyx_empty_tuple, /*PyObject *freevars,*/ + __pyx_empty_tuple, /*PyObject *cellvars,*/ + py_srcfile, /*PyObject *filename,*/ + py_funcname, /*PyObject *name,*/ + py_line, + __pyx_empty_bytes /*PyObject *lnotab*/ + ); + Py_DECREF(py_srcfile); + #else + py_code = PyCode_NewEmpty(filename, funcname, py_line); + #endif + Py_XDECREF(py_funcname); + return py_code; +bad: + Py_XDECREF(py_funcname); + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(py_srcfile); + #endif + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyFrameObject *py_frame = 0; + PyThreadState *tstate = __Pyx_PyThreadState_Current; + PyObject *ptype, *pvalue, *ptraceback; + if (c_line) { + c_line = __Pyx_CLineForTraceback(tstate, c_line); + } + py_code = __pyx_find_code_object(c_line ? -c_line : py_line); + if (!py_code) { + __Pyx_ErrFetchInState(tstate, &ptype, &pvalue, &ptraceback); + py_code = __Pyx_CreateCodeObjectForTraceback( + funcname, c_line, py_line, filename); + if (!py_code) { + /* If the code object creation fails, then we should clear the + fetched exception references and propagate the new exception */ + Py_XDECREF(ptype); + Py_XDECREF(pvalue); + Py_XDECREF(ptraceback); + goto bad; + } + __Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback); + __pyx_insert_code_object(c_line ? -c_line : py_line, py_code); + } + py_frame = PyFrame_New( + tstate, /*PyThreadState *tstate,*/ + py_code, /*PyCodeObject *code,*/ + __pyx_d, /*PyObject *globals,*/ + 0 /*PyObject *locals*/ + ); + if (!py_frame) goto bad; + __Pyx_PyFrame_SetLineNumber(py_frame, py_line); + PyTraceBack_Here(py_frame); +bad: + Py_XDECREF(py_code); + Py_XDECREF(py_frame); +} +#endif + +/* CIntFromPyVerify */ +#define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value)\ + __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 0) +#define __PYX_VERIFY_RETURN_INT_EXC(target_type, func_type, func_value)\ + __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 1) +#define __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, exc)\ + {\ + func_type value = func_value;\ + if (sizeof(target_type) < sizeof(func_type)) {\ + if (unlikely(value != (func_type) (target_type) value)) {\ + func_type zero = 0;\ + if (exc && unlikely(value == (func_type)-1 && PyErr_Occurred()))\ + return (target_type) -1;\ + if (is_unsigned && unlikely(value < zero))\ + goto raise_neg_overflow;\ + else\ + goto raise_overflow;\ + }\ + }\ + return (target_type) value;\ + } + +/* CIntFromPy */ +static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const int neg_one = (int) -1, const_zero = (int) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if ((sizeof(int) < sizeof(long))) { + __PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG(x)) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + goto raise_neg_overflow; + } + return (int) val; + } + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_USE_PYLONG_INTERNALS + if (unlikely(__Pyx_PyLong_IsNeg(x))) { + goto raise_neg_overflow; + } else if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(int, __Pyx_compact_upylong, __Pyx_PyLong_CompactValueUnsigned(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_DigitCount(x)) { + case 2: + if ((8 * sizeof(int) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) >= 2 * PyLong_SHIFT)) { + return (int) (((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); + } + } + break; + case 3: + if ((8 * sizeof(int) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) >= 3 * PyLong_SHIFT)) { + return (int) (((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); + } + } + break; + case 4: + if ((8 * sizeof(int) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) >= 4 * PyLong_SHIFT)) { + return (int) (((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); + } + } + break; + } + } +#endif +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A7 + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (int) -1; + if (unlikely(result == 1)) + goto raise_neg_overflow; + } +#endif + if ((sizeof(int) <= sizeof(unsigned long))) { + __PYX_VERIFY_RETURN_INT_EXC(int, unsigned long, PyLong_AsUnsignedLong(x)) +#ifdef HAVE_LONG_LONG + } else if ((sizeof(int) <= sizeof(unsigned PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(int, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) +#endif + } + } else { +#if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(int, __Pyx_compact_pylong, __Pyx_PyLong_CompactValue(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_SignedDigitCount(x)) { + case -2: + if ((8 * sizeof(int) - 1 > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 2 * PyLong_SHIFT)) { + return (int) (((int)-1)*(((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case 2: + if ((8 * sizeof(int) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 2 * PyLong_SHIFT)) { + return (int) ((((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case -3: + if ((8 * sizeof(int) - 1 > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 3 * PyLong_SHIFT)) { + return (int) (((int)-1)*(((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case 3: + if ((8 * sizeof(int) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 3 * PyLong_SHIFT)) { + return (int) ((((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case -4: + if ((8 * sizeof(int) - 1 > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 4 * PyLong_SHIFT)) { + return (int) (((int)-1)*(((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case 4: + if ((8 * sizeof(int) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 4 * PyLong_SHIFT)) { + return (int) ((((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + } + } +#endif + if ((sizeof(int) <= sizeof(long))) { + __PYX_VERIFY_RETURN_INT_EXC(int, long, PyLong_AsLong(x)) +#ifdef HAVE_LONG_LONG + } else if ((sizeof(int) <= sizeof(PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(int, PY_LONG_LONG, PyLong_AsLongLong(x)) +#endif + } + } + { + int val; + PyObject *v = __Pyx_PyNumber_IntOrLong(x); +#if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } +#endif + if (likely(v)) { + int ret = -1; +#if PY_VERSION_HEX < 0x030d0000 && !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API) || defined(_PyLong_AsByteArray) + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); +#else + PyObject *stepval = NULL, *mask = NULL, *shift = NULL; + int bits, remaining_bits, is_negative = 0; + long idigit; + int chunk_size = (sizeof(long) < 8) ? 30 : 62; + if (unlikely(!PyLong_CheckExact(v))) { + PyObject *tmp = v; + v = PyNumber_Long(v); + assert(PyLong_CheckExact(v)); + Py_DECREF(tmp); + if (unlikely(!v)) return (int) -1; + } +#if CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030B0000 + if (Py_SIZE(x) == 0) + return (int) 0; + is_negative = Py_SIZE(x) < 0; +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (int) -1; + is_negative = result == 1; + } +#endif + if (is_unsigned && unlikely(is_negative)) { + goto raise_neg_overflow; + } else if (is_negative) { + stepval = PyNumber_Invert(v); + if (unlikely(!stepval)) + return (int) -1; + } else { + stepval = __Pyx_NewRef(v); + } + val = (int) 0; + mask = PyLong_FromLong((1L << chunk_size) - 1); if (unlikely(!mask)) goto done; + shift = PyLong_FromLong(chunk_size); if (unlikely(!shift)) goto done; + for (bits = 0; bits < (int) sizeof(int) * 8 - chunk_size; bits += chunk_size) { + PyObject *tmp, *digit; + digit = PyNumber_And(stepval, mask); + if (unlikely(!digit)) goto done; + idigit = PyLong_AsLong(digit); + Py_DECREF(digit); + if (unlikely(idigit < 0)) goto done; + tmp = PyNumber_Rshift(stepval, shift); + if (unlikely(!tmp)) goto done; + Py_DECREF(stepval); stepval = tmp; + val |= ((int) idigit) << bits; + #if CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030B0000 + if (Py_SIZE(stepval) == 0) + goto unpacking_done; + #endif + } + idigit = PyLong_AsLong(stepval); + if (unlikely(idigit < 0)) goto done; + remaining_bits = ((int) sizeof(int) * 8) - bits - (is_unsigned ? 0 : 1); + if (unlikely(idigit >= (1L << remaining_bits))) + goto raise_overflow; + val |= ((int) idigit) << bits; + #if CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030B0000 + unpacking_done: + #endif + if (!is_unsigned) { + if (unlikely(val & (((int) 1) << (sizeof(int) * 8 - 1)))) + goto raise_overflow; + if (is_negative) + val = ~val; + } + ret = 0; + done: + Py_XDECREF(shift); + Py_XDECREF(mask); + Py_XDECREF(stepval); +#endif + Py_DECREF(v); + if (likely(!ret)) + return val; + } + return (int) -1; + } + } else { + int val; + PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); + if (!tmp) return (int) -1; + val = __Pyx_PyInt_As_int(tmp); + Py_DECREF(tmp); + return val; + } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to int"); + return (int) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to int"); + return (int) -1; +} + +/* CIntToPy */ +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const int neg_one = (int) -1, const_zero = (int) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(int) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(int) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); +#ifdef HAVE_LONG_LONG + } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); +#endif + } + } else { + if (sizeof(int) <= sizeof(long)) { + return PyInt_FromLong((long) value); +#ifdef HAVE_LONG_LONG + } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { + return PyLong_FromLongLong((PY_LONG_LONG) value); +#endif + } + } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; +#if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030d0000 + return _PyLong_FromByteArray(bytes, sizeof(int), + little, !is_unsigned); +#else + PyObject *from_bytes, *result = NULL; + PyObject *py_bytes = NULL, *arg_tuple = NULL, *kwds = NULL, *order_str = NULL; + from_bytes = PyObject_GetAttrString((PyObject*)&PyLong_Type, "from_bytes"); + if (!from_bytes) return NULL; + py_bytes = PyBytes_FromStringAndSize((char*)bytes, sizeof(int)); + if (!py_bytes) goto limited_bad; + order_str = PyUnicode_FromString(little ? "little" : "big"); + if (!order_str) goto limited_bad; + arg_tuple = PyTuple_Pack(2, py_bytes, order_str); + if (!arg_tuple) goto limited_bad; + if (!is_unsigned) { + kwds = PyDict_New(); + if (!kwds) goto limited_bad; + if (PyDict_SetItemString(kwds, "signed", __Pyx_NewRef(Py_True))) goto limited_bad; + } + result = PyObject_Call(from_bytes, arg_tuple, kwds); + limited_bad: + Py_XDECREF(kwds); + Py_XDECREF(arg_tuple); + Py_XDECREF(order_str); + Py_XDECREF(py_bytes); + Py_XDECREF(from_bytes); + return result; +#endif + } +} + +/* CIntToPy */ +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_uint32_t(uint32_t value) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const uint32_t neg_one = (uint32_t) -1, const_zero = (uint32_t) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(uint32_t) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(uint32_t) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); +#ifdef HAVE_LONG_LONG + } else if (sizeof(uint32_t) <= sizeof(unsigned PY_LONG_LONG)) { + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); +#endif + } + } else { + if (sizeof(uint32_t) <= sizeof(long)) { + return PyInt_FromLong((long) value); +#ifdef HAVE_LONG_LONG + } else if (sizeof(uint32_t) <= sizeof(PY_LONG_LONG)) { + return PyLong_FromLongLong((PY_LONG_LONG) value); +#endif + } + } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; +#if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030d0000 + return _PyLong_FromByteArray(bytes, sizeof(uint32_t), + little, !is_unsigned); +#else + PyObject *from_bytes, *result = NULL; + PyObject *py_bytes = NULL, *arg_tuple = NULL, *kwds = NULL, *order_str = NULL; + from_bytes = PyObject_GetAttrString((PyObject*)&PyLong_Type, "from_bytes"); + if (!from_bytes) return NULL; + py_bytes = PyBytes_FromStringAndSize((char*)bytes, sizeof(uint32_t)); + if (!py_bytes) goto limited_bad; + order_str = PyUnicode_FromString(little ? "little" : "big"); + if (!order_str) goto limited_bad; + arg_tuple = PyTuple_Pack(2, py_bytes, order_str); + if (!arg_tuple) goto limited_bad; + if (!is_unsigned) { + kwds = PyDict_New(); + if (!kwds) goto limited_bad; + if (PyDict_SetItemString(kwds, "signed", __Pyx_NewRef(Py_True))) goto limited_bad; + } + result = PyObject_Call(from_bytes, arg_tuple, kwds); + limited_bad: + Py_XDECREF(kwds); + Py_XDECREF(arg_tuple); + Py_XDECREF(order_str); + Py_XDECREF(py_bytes); + Py_XDECREF(from_bytes); + return result; +#endif + } +} + +/* FormatTypeName */ +#if CYTHON_COMPILING_IN_LIMITED_API +static __Pyx_TypeName +__Pyx_PyType_GetName(PyTypeObject* tp) +{ + PyObject *name = __Pyx_PyObject_GetAttrStr((PyObject *)tp, + __pyx_n_s_name); + if (unlikely(name == NULL) || unlikely(!PyUnicode_Check(name))) { + PyErr_Clear(); + Py_XDECREF(name); + name = __Pyx_NewRef(__pyx_n_s__35); + } + return name; +} +#endif + +/* CIntToPy */ +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const long neg_one = (long) -1, const_zero = (long) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(long) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(long) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); +#ifdef HAVE_LONG_LONG + } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); +#endif + } + } else { + if (sizeof(long) <= sizeof(long)) { + return PyInt_FromLong((long) value); +#ifdef HAVE_LONG_LONG + } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { + return PyLong_FromLongLong((PY_LONG_LONG) value); +#endif + } + } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; +#if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030d0000 + return _PyLong_FromByteArray(bytes, sizeof(long), + little, !is_unsigned); +#else + PyObject *from_bytes, *result = NULL; + PyObject *py_bytes = NULL, *arg_tuple = NULL, *kwds = NULL, *order_str = NULL; + from_bytes = PyObject_GetAttrString((PyObject*)&PyLong_Type, "from_bytes"); + if (!from_bytes) return NULL; + py_bytes = PyBytes_FromStringAndSize((char*)bytes, sizeof(long)); + if (!py_bytes) goto limited_bad; + order_str = PyUnicode_FromString(little ? "little" : "big"); + if (!order_str) goto limited_bad; + arg_tuple = PyTuple_Pack(2, py_bytes, order_str); + if (!arg_tuple) goto limited_bad; + if (!is_unsigned) { + kwds = PyDict_New(); + if (!kwds) goto limited_bad; + if (PyDict_SetItemString(kwds, "signed", __Pyx_NewRef(Py_True))) goto limited_bad; + } + result = PyObject_Call(from_bytes, arg_tuple, kwds); + limited_bad: + Py_XDECREF(kwds); + Py_XDECREF(arg_tuple); + Py_XDECREF(order_str); + Py_XDECREF(py_bytes); + Py_XDECREF(from_bytes); + return result; +#endif + } +} + +/* CIntFromPy */ +static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const long neg_one = (long) -1, const_zero = (long) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if ((sizeof(long) < sizeof(long))) { + __PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG(x)) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + goto raise_neg_overflow; + } + return (long) val; + } + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_USE_PYLONG_INTERNALS + if (unlikely(__Pyx_PyLong_IsNeg(x))) { + goto raise_neg_overflow; + } else if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(long, __Pyx_compact_upylong, __Pyx_PyLong_CompactValueUnsigned(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_DigitCount(x)) { + case 2: + if ((8 * sizeof(long) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) >= 2 * PyLong_SHIFT)) { + return (long) (((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); + } + } + break; + case 3: + if ((8 * sizeof(long) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) >= 3 * PyLong_SHIFT)) { + return (long) (((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); + } + } + break; + case 4: + if ((8 * sizeof(long) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) >= 4 * PyLong_SHIFT)) { + return (long) (((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); + } + } + break; + } + } +#endif +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A7 + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (long) -1; + if (unlikely(result == 1)) + goto raise_neg_overflow; + } +#endif + if ((sizeof(long) <= sizeof(unsigned long))) { + __PYX_VERIFY_RETURN_INT_EXC(long, unsigned long, PyLong_AsUnsignedLong(x)) +#ifdef HAVE_LONG_LONG + } else if ((sizeof(long) <= sizeof(unsigned PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(long, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) +#endif + } + } else { +#if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(long, __Pyx_compact_pylong, __Pyx_PyLong_CompactValue(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_SignedDigitCount(x)) { + case -2: + if ((8 * sizeof(long) - 1 > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 2 * PyLong_SHIFT)) { + return (long) (((long)-1)*(((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case 2: + if ((8 * sizeof(long) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 2 * PyLong_SHIFT)) { + return (long) ((((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case -3: + if ((8 * sizeof(long) - 1 > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 3 * PyLong_SHIFT)) { + return (long) (((long)-1)*(((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case 3: + if ((8 * sizeof(long) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 3 * PyLong_SHIFT)) { + return (long) ((((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case -4: + if ((8 * sizeof(long) - 1 > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 4 * PyLong_SHIFT)) { + return (long) (((long)-1)*(((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case 4: + if ((8 * sizeof(long) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 4 * PyLong_SHIFT)) { + return (long) ((((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + } + } +#endif + if ((sizeof(long) <= sizeof(long))) { + __PYX_VERIFY_RETURN_INT_EXC(long, long, PyLong_AsLong(x)) +#ifdef HAVE_LONG_LONG + } else if ((sizeof(long) <= sizeof(PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(long, PY_LONG_LONG, PyLong_AsLongLong(x)) +#endif + } + } + { + long val; + PyObject *v = __Pyx_PyNumber_IntOrLong(x); +#if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } +#endif + if (likely(v)) { + int ret = -1; +#if PY_VERSION_HEX < 0x030d0000 && !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API) || defined(_PyLong_AsByteArray) + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); +#else + PyObject *stepval = NULL, *mask = NULL, *shift = NULL; + int bits, remaining_bits, is_negative = 0; + long idigit; + int chunk_size = (sizeof(long) < 8) ? 30 : 62; + if (unlikely(!PyLong_CheckExact(v))) { + PyObject *tmp = v; + v = PyNumber_Long(v); + assert(PyLong_CheckExact(v)); + Py_DECREF(tmp); + if (unlikely(!v)) return (long) -1; + } +#if CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030B0000 + if (Py_SIZE(x) == 0) + return (long) 0; + is_negative = Py_SIZE(x) < 0; +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (long) -1; + is_negative = result == 1; + } +#endif + if (is_unsigned && unlikely(is_negative)) { + goto raise_neg_overflow; + } else if (is_negative) { + stepval = PyNumber_Invert(v); + if (unlikely(!stepval)) + return (long) -1; + } else { + stepval = __Pyx_NewRef(v); + } + val = (long) 0; + mask = PyLong_FromLong((1L << chunk_size) - 1); if (unlikely(!mask)) goto done; + shift = PyLong_FromLong(chunk_size); if (unlikely(!shift)) goto done; + for (bits = 0; bits < (int) sizeof(long) * 8 - chunk_size; bits += chunk_size) { + PyObject *tmp, *digit; + digit = PyNumber_And(stepval, mask); + if (unlikely(!digit)) goto done; + idigit = PyLong_AsLong(digit); + Py_DECREF(digit); + if (unlikely(idigit < 0)) goto done; + tmp = PyNumber_Rshift(stepval, shift); + if (unlikely(!tmp)) goto done; + Py_DECREF(stepval); stepval = tmp; + val |= ((long) idigit) << bits; + #if CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030B0000 + if (Py_SIZE(stepval) == 0) + goto unpacking_done; + #endif + } + idigit = PyLong_AsLong(stepval); + if (unlikely(idigit < 0)) goto done; + remaining_bits = ((int) sizeof(long) * 8) - bits - (is_unsigned ? 0 : 1); + if (unlikely(idigit >= (1L << remaining_bits))) + goto raise_overflow; + val |= ((long) idigit) << bits; + #if CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030B0000 + unpacking_done: + #endif + if (!is_unsigned) { + if (unlikely(val & (((long) 1) << (sizeof(long) * 8 - 1)))) + goto raise_overflow; + if (is_negative) + val = ~val; + } + ret = 0; + done: + Py_XDECREF(shift); + Py_XDECREF(mask); + Py_XDECREF(stepval); +#endif + Py_DECREF(v); + if (likely(!ret)) + return val; + } + return (long) -1; + } + } else { + long val; + PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); + if (!tmp) return (long) -1; + val = __Pyx_PyInt_As_long(tmp); + Py_DECREF(tmp); + return val; + } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to long"); + return (long) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to long"); + return (long) -1; +} + +/* FastTypeChecks */ +#if CYTHON_COMPILING_IN_CPYTHON +static int __Pyx_InBases(PyTypeObject *a, PyTypeObject *b) { + while (a) { + a = __Pyx_PyType_GetSlot(a, tp_base, PyTypeObject*); + if (a == b) + return 1; + } + return b == &PyBaseObject_Type; +} +static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b) { + PyObject *mro; + if (a == b) return 1; + mro = a->tp_mro; + if (likely(mro)) { + Py_ssize_t i, n; + n = PyTuple_GET_SIZE(mro); + for (i = 0; i < n; i++) { + if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b) + return 1; + } + return 0; + } + return __Pyx_InBases(a, b); +} +static CYTHON_INLINE int __Pyx_IsAnySubtype2(PyTypeObject *cls, PyTypeObject *a, PyTypeObject *b) { + PyObject *mro; + if (cls == a || cls == b) return 1; + mro = cls->tp_mro; + if (likely(mro)) { + Py_ssize_t i, n; + n = PyTuple_GET_SIZE(mro); + for (i = 0; i < n; i++) { + PyObject *base = PyTuple_GET_ITEM(mro, i); + if (base == (PyObject *)a || base == (PyObject *)b) + return 1; + } + return 0; + } + return __Pyx_InBases(cls, a) || __Pyx_InBases(cls, b); +} +#if PY_MAJOR_VERSION == 2 +static int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject* exc_type2) { + PyObject *exception, *value, *tb; + int res; + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + __Pyx_ErrFetch(&exception, &value, &tb); + res = exc_type1 ? PyObject_IsSubclass(err, exc_type1) : 0; + if (unlikely(res == -1)) { + PyErr_WriteUnraisable(err); + res = 0; + } + if (!res) { + res = PyObject_IsSubclass(err, exc_type2); + if (unlikely(res == -1)) { + PyErr_WriteUnraisable(err); + res = 0; + } + } + __Pyx_ErrRestore(exception, value, tb); + return res; +} +#else +static CYTHON_INLINE int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject *exc_type2) { + if (exc_type1) { + return __Pyx_IsAnySubtype2((PyTypeObject*)err, (PyTypeObject*)exc_type1, (PyTypeObject*)exc_type2); + } else { + return __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type2); + } +} +#endif +static int __Pyx_PyErr_GivenExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { + Py_ssize_t i, n; + assert(PyExceptionClass_Check(exc_type)); + n = PyTuple_GET_SIZE(tuple); +#if PY_MAJOR_VERSION >= 3 + for (i=0; i= 0x030B00A4 + return Py_Version & ~0xFFUL; +#else + const char* rt_version = Py_GetVersion(); + unsigned long version = 0; + unsigned long factor = 0x01000000UL; + unsigned int digit = 0; + int i = 0; + while (factor) { + while ('0' <= rt_version[i] && rt_version[i] <= '9') { + digit = digit * 10 + (unsigned int) (rt_version[i] - '0'); + ++i; + } + version += factor * digit; + if (rt_version[i] != '.') + break; + digit = 0; + factor >>= 8; + ++i; + } + return version; +#endif +} +static int __Pyx_check_binary_version(unsigned long ct_version, unsigned long rt_version, int allow_newer) { + const unsigned long MAJOR_MINOR = 0xFFFF0000UL; + if ((rt_version & MAJOR_MINOR) == (ct_version & MAJOR_MINOR)) + return 0; + if (likely(allow_newer && (rt_version & MAJOR_MINOR) > (ct_version & MAJOR_MINOR))) + return 1; + { + char message[200]; + PyOS_snprintf(message, sizeof(message), + "compile time Python version %d.%d " + "of module '%.100s' " + "%s " + "runtime version %d.%d", + (int) (ct_version >> 24), (int) ((ct_version >> 16) & 0xFF), + __Pyx_MODULE_NAME, + (allow_newer) ? "was newer than" : "does not match", + (int) (rt_version >> 24), (int) ((rt_version >> 16) & 0xFF) + ); + return PyErr_WarnEx(NULL, message, 1); + } +} + +/* InitStrings */ +#if PY_MAJOR_VERSION >= 3 +static int __Pyx_InitString(__Pyx_StringTabEntry t, PyObject **str) { + if (t.is_unicode | t.is_str) { + if (t.intern) { + *str = PyUnicode_InternFromString(t.s); + } else if (t.encoding) { + *str = PyUnicode_Decode(t.s, t.n - 1, t.encoding, NULL); + } else { + *str = PyUnicode_FromStringAndSize(t.s, t.n - 1); + } + } else { + *str = PyBytes_FromStringAndSize(t.s, t.n - 1); + } + if (!*str) + return -1; + if (PyObject_Hash(*str) == -1) + return -1; + return 0; +} +#endif +static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { + while (t->p) { + #if PY_MAJOR_VERSION >= 3 + __Pyx_InitString(*t, t->p); + #else + if (t->is_unicode) { + *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL); + } else if (t->intern) { + *t->p = PyString_InternFromString(t->s); + } else { + *t->p = PyString_FromStringAndSize(t->s, t->n - 1); + } + if (!*t->p) + return -1; + if (PyObject_Hash(*t->p) == -1) + return -1; + #endif + ++t; + } + return 0; +} + +#include +static CYTHON_INLINE Py_ssize_t __Pyx_ssize_strlen(const char *s) { + size_t len = strlen(s); + if (unlikely(len > (size_t) PY_SSIZE_T_MAX)) { + PyErr_SetString(PyExc_OverflowError, "byte string is too long"); + return -1; + } + return (Py_ssize_t) len; +} +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { + Py_ssize_t len = __Pyx_ssize_strlen(c_str); + if (unlikely(len < 0)) return NULL; + return __Pyx_PyUnicode_FromStringAndSize(c_str, len); +} +static CYTHON_INLINE PyObject* __Pyx_PyByteArray_FromString(const char* c_str) { + Py_ssize_t len = __Pyx_ssize_strlen(c_str); + if (unlikely(len < 0)) return NULL; + return PyByteArray_FromStringAndSize(c_str, len); +} +static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject* o) { + Py_ssize_t ignore; + return __Pyx_PyObject_AsStringAndSize(o, &ignore); +} +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT +#if !CYTHON_PEP393_ENABLED +static const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { + char* defenc_c; + PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); + if (!defenc) return NULL; + defenc_c = PyBytes_AS_STRING(defenc); +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + { + char* end = defenc_c + PyBytes_GET_SIZE(defenc); + char* c; + for (c = defenc_c; c < end; c++) { + if ((unsigned char) (*c) >= 128) { + PyUnicode_AsASCIIString(o); + return NULL; + } + } + } +#endif + *length = PyBytes_GET_SIZE(defenc); + return defenc_c; +} +#else +static CYTHON_INLINE const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { + if (unlikely(__Pyx_PyUnicode_READY(o) == -1)) return NULL; +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + if (likely(PyUnicode_IS_ASCII(o))) { + *length = PyUnicode_GET_LENGTH(o); + return PyUnicode_AsUTF8(o); + } else { + PyUnicode_AsASCIIString(o); + return NULL; + } +#else + return PyUnicode_AsUTF8AndSize(o, length); +#endif +} +#endif +#endif +static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT + if ( +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + __Pyx_sys_getdefaultencoding_not_ascii && +#endif + PyUnicode_Check(o)) { + return __Pyx_PyUnicode_AsStringAndSize(o, length); + } else +#endif +#if (!CYTHON_COMPILING_IN_PYPY && !CYTHON_COMPILING_IN_LIMITED_API) || (defined(PyByteArray_AS_STRING) && defined(PyByteArray_GET_SIZE)) + if (PyByteArray_Check(o)) { + *length = PyByteArray_GET_SIZE(o); + return PyByteArray_AS_STRING(o); + } else +#endif + { + char* result; + int r = PyBytes_AsStringAndSize(o, &result, length); + if (unlikely(r < 0)) { + return NULL; + } else { + return result; + } + } +} +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { + int is_true = x == Py_True; + if (is_true | (x == Py_False) | (x == Py_None)) return is_true; + else return PyObject_IsTrue(x); +} +static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject* x) { + int retval; + if (unlikely(!x)) return -1; + retval = __Pyx_PyObject_IsTrue(x); + Py_DECREF(x); + return retval; +} +static PyObject* __Pyx_PyNumber_IntOrLongWrongResultType(PyObject* result, const char* type_name) { + __Pyx_TypeName result_type_name = __Pyx_PyType_GetName(Py_TYPE(result)); +#if PY_MAJOR_VERSION >= 3 + if (PyLong_Check(result)) { + if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1, + "__int__ returned non-int (type " __Pyx_FMT_TYPENAME "). " + "The ability to return an instance of a strict subclass of int is deprecated, " + "and may be removed in a future version of Python.", + result_type_name)) { + __Pyx_DECREF_TypeName(result_type_name); + Py_DECREF(result); + return NULL; + } + __Pyx_DECREF_TypeName(result_type_name); + return result; + } +#endif + PyErr_Format(PyExc_TypeError, + "__%.4s__ returned non-%.4s (type " __Pyx_FMT_TYPENAME ")", + type_name, type_name, result_type_name); + __Pyx_DECREF_TypeName(result_type_name); + Py_DECREF(result); + return NULL; +} +static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x) { +#if CYTHON_USE_TYPE_SLOTS + PyNumberMethods *m; +#endif + const char *name = NULL; + PyObject *res = NULL; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x) || PyLong_Check(x))) +#else + if (likely(PyLong_Check(x))) +#endif + return __Pyx_NewRef(x); +#if CYTHON_USE_TYPE_SLOTS + m = Py_TYPE(x)->tp_as_number; + #if PY_MAJOR_VERSION < 3 + if (m && m->nb_int) { + name = "int"; + res = m->nb_int(x); + } + else if (m && m->nb_long) { + name = "long"; + res = m->nb_long(x); + } + #else + if (likely(m && m->nb_int)) { + name = "int"; + res = m->nb_int(x); + } + #endif +#else + if (!PyBytes_CheckExact(x) && !PyUnicode_CheckExact(x)) { + res = PyNumber_Int(x); + } +#endif + if (likely(res)) { +#if PY_MAJOR_VERSION < 3 + if (unlikely(!PyInt_Check(res) && !PyLong_Check(res))) { +#else + if (unlikely(!PyLong_CheckExact(res))) { +#endif + return __Pyx_PyNumber_IntOrLongWrongResultType(res, name); + } + } + else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_TypeError, + "an integer is required"); + } + return res; +} +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { + Py_ssize_t ival; + PyObject *x; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_CheckExact(b))) { + if (sizeof(Py_ssize_t) >= sizeof(long)) + return PyInt_AS_LONG(b); + else + return PyInt_AsSsize_t(b); + } +#endif + if (likely(PyLong_CheckExact(b))) { + #if CYTHON_USE_PYLONG_INTERNALS + if (likely(__Pyx_PyLong_IsCompact(b))) { + return __Pyx_PyLong_CompactValue(b); + } else { + const digit* digits = __Pyx_PyLong_Digits(b); + const Py_ssize_t size = __Pyx_PyLong_SignedDigitCount(b); + switch (size) { + case 2: + if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { + return (Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case -2: + if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { + return -(Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case 3: + if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { + return (Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case -3: + if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { + return -(Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case 4: + if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { + return (Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case -4: + if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { + return -(Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + } + } + #endif + return PyLong_AsSsize_t(b); + } + x = PyNumber_Index(b); + if (!x) return -1; + ival = PyInt_AsSsize_t(x); + Py_DECREF(x); + return ival; +} +static CYTHON_INLINE Py_hash_t __Pyx_PyIndex_AsHash_t(PyObject* o) { + if (sizeof(Py_hash_t) == sizeof(Py_ssize_t)) { + return (Py_hash_t) __Pyx_PyIndex_AsSsize_t(o); +#if PY_MAJOR_VERSION < 3 + } else if (likely(PyInt_CheckExact(o))) { + return PyInt_AS_LONG(o); +#endif + } else { + Py_ssize_t ival; + PyObject *x; + x = PyNumber_Index(o); + if (!x) return -1; + ival = PyInt_AsLong(x); + Py_DECREF(x); + return ival; + } +} +static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b) { + return b ? __Pyx_NewRef(Py_True) : __Pyx_NewRef(Py_False); +} +static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { + return PyInt_FromSize_t(ival); +} + + +/* #### Code section: utility_code_pragmas_end ### */ +#ifdef _MSC_VER +#pragma warning( pop ) +#endif + + + +/* #### Code section: end ### */ +#endif /* Py_PYTHON_H */ diff --git a/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/_spp.pxd b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/_spp.pxd new file mode 100644 index 0000000000000000000000000000000000000000..6265889aa2dfc225c922a72dc4a7755d905e20dc --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/_spp.pxd @@ -0,0 +1,59 @@ +from libc.stdint cimport uint32_t +from libcpp.memory cimport shared_ptr +from libcpp.string cimport string +from libcpp.vector cimport vector + +cdef extern from "builtin_pb/sentencepiece.pb.h" namespace "sentencepiece": + cdef cppclass SentencePieceText_SentencePiece: + uint32_t id() const + const string & piece() const + + cdef cppclass SentencePieceText: + const SentencePieceText_SentencePiece& pieces(int index) const; + int pieces_size() const + + +cdef extern from "sentencepiece_processor.h" namespace "sentencepiece": + cdef cppclass CSentencePieceProcessor "sentencepiece::SentencePieceProcessor": + SentencePieceProcessor() + string EncodeAsSerializedProto(const string& filename) + Status Decode(const vector[int]& ids, string *detokenized) + Status Decode(const vector[string]& ids, string *detokenized) + Status Encode(const string& input, SentencePieceText * spt) + int GetPieceSize() const + Status Load(const string& filename) + Status LoadFromSerializedProto(string_view serialized); + Status status() const + int bos_id() const + int eos_id() const + int pad_id() const + int unk_id() const + string serialized_model_proto() const + int PieceToId(string_view piece) const + const string &IdToPiece(int id) const + + +cdef extern from "sentencepiece_processor.h" namespace "absl": + cdef cppclass string_view: + string_view() + string_view(const char * data, size_t len) + + +cdef extern from "sentencepiece_processor.h" namespace "sentencepiece::util": + # Cython 3.0 has support for C++ enum classes. Until then, work around it. + cdef cppclass StatusCode: + pass + + cdef cppclass Status: + StatusCode code() const + const char * error_message() const + +cdef extern from "sentencepiece_processor.h" namespace "sentencepiece::util::StatusCode": + cdef StatusCode kOk + cdef StatusCode kInternal + cdef StatusCode kNotFound + +cdef class SentencePieceProcessor: + cdef shared_ptr[CSentencePieceProcessor] spp + + cdef SentencePieceText _encode(self, str sentence) except * diff --git a/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/_spp.pyx b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/_spp.pyx new file mode 100644 index 0000000000000000000000000000000000000000..feca700819843ab4c7d5383a6f0bce5ec055f2e0 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/_spp.pyx @@ -0,0 +1,219 @@ +from cython.operator cimport dereference as deref +from typing import List, Tuple + +cdef class SentencePieceProcessor: + def __cinit__(self): + self.spp.reset(new CSentencePieceProcessor()) + + def __init__(self): + pass + + def __len__(self): + _check_status(deref(self.spp).status()) + return deref(self.spp).GetPieceSize() + + def __copy__(self): + return SentencePieceProcessor.from_protobuf(self.to_protobuf()) + + def __deepcopy__(self, memo): + result = SentencePieceProcessor.from_protobuf(self.to_protobuf()) + memo[id(self)] = result + return result + + @staticmethod + def from_file(str filename): + """ + Constructs a SentencePieceProcessor by loading a serialized model from + disk. + + filename (str): Path to model. + """ + cdef SentencePieceProcessor processor = SentencePieceProcessor.__new__(SentencePieceProcessor) + _check_status(deref(processor.spp).Load(filename.encode("utf-8"))) + return processor + + @staticmethod + def from_protobuf(bytes protobuf): + """ + Constructs a SentencePieceProcessor by loading a serialized model from + a protocol buffer. + + protobuf (bytes): Byte array representing the model's serialized + protocol buffer. + """ + cdef SentencePieceProcessor processor = SentencePieceProcessor.__new__(SentencePieceProcessor) + if len(protobuf) == 0: + # SentencePiece returns an empty protobuf for uninitialized models. + return processor + cdef string_view protobuf_view = string_view(protobuf, len(protobuf)) + _check_status(deref(processor.spp).LoadFromSerializedProto(protobuf_view)) + return processor + + def to_protobuf(self) -> bytes: + """ + Serializes the SentencePieceProcessor to a protocol buffer. + + RETURNS (bytes): Byte array representing the model's serialized + protocol buffer. + """ + cdef string serialized = deref(self.spp).serialized_model_proto() + return bytes(serialized) + + def decode_from_ids(self, list ids) -> str: + """ + Decodes piece indentifiers to a string. Raises a `ValueError` if the + list elements are not integers. + + ids (List[int]): Piece IDs. + RETURNS (str): Decoded string. + """ + cdef vector[int] c_ids + for piece_id in ids: + if not isinstance(piece_id, int): + raise TypeError("Pieces must be of type `int` when decoding from ids") + c_ids.push_back(piece_id) + cdef string output + _check_status(deref(self.spp).Decode(c_ids, &output)) + return output.decode("utf-8") + + def decode_from_pieces(self, list pieces) -> str: + """ + Decodes piece tokens to a string. Raises a `ValueError` if the + list elements are not strings. + + ids (List[str]): Piece tokens. + RETURNS (str): Decoded string. + """ + cdef vector[string] c_strings + for piece in pieces: + if not isinstance(piece, str): + raise TypeError("Pieces must be of type `str` when decoding from pieces") + c_strings.push_back(piece.encode("utf-8")) + cdef string output + _check_status(deref(self.spp).Decode(c_strings, &output)) + return output.decode("utf-8") + + def encode(self, str sentence) -> Tuple[List[int], List[str]]: + """ + Encodes a string to piece indentifiers and piece tokens. + + sentence (str): Text to encode. + RETURNS (Tuple[List[int], List[str]]): Piece IDs and piece tokens + corresponding to the input text. + """ + cdef SentencePieceText text = self._encode(sentence) + + cdef int idx + cdef SentencePieceText_SentencePiece piece + pieces = [] + ids = [] + for idx in range(text.pieces_size()): + piece = text.pieces(idx) + ids.append(piece.id()) + pieces.append(piece.piece().decode("utf-8")) + + return ids, pieces + + def encode_as_ids(self, str sentence) -> List[int]: + """ + Encodes a string to piece indentifiers. + + sentence (str): Text to encode. + RETURNS (List[int]): Piece IDs. + """ + cdef SentencePieceText text = self._encode(sentence) + + cdef int idx + ids = [] + for idx in range(text.pieces_size()): + ids.append(text.pieces(idx).id()) + + return ids + + def encode_as_pieces(self, str sentence) -> List[str]: + """ + Encodes a string to piece tokens. + + sentence (str): Text to encode. + RETURNS (List[str]): Piece tokens. + """ + cdef SentencePieceText text = self._encode(sentence) + + cdef int idx + cdef SentencePieceText_SentencePiece piece + pieces = [] + for idx in range(text.pieces_size()): + piece = text.pieces(idx) + pieces.append(text.pieces(idx).piece().decode("utf-8")) + + return pieces + + def piece_to_id(self, str piece) -> int: + """ + Returns the piece identifier for a given piece token. Returns the + `unk` piece identifier if the piece token is OOV. + + piece (str): Piece token. + RETURNS (int): Piece ID. + """ + piece_bytes = piece.encode("utf8") + cdef string_view piece_view = string_view(piece_bytes, len(piece_bytes)) + _check_status(deref(self.spp).status()) + return deref(self.spp).PieceToId(piece_view) + + def id_to_piece(self, int piece_id) -> str: + """ + Returns the piece token for a given piece identifier. Raises a `ValueError` + if the piece identifier is out-of-bounds. + + piece_id (int): Piece ID. + RETURNS (str): Piece token. + """ + _check_status(deref(self.spp).status()) + cdef int vocab_size = deref(self.spp).GetPieceSize() + if not 0 <= piece_id < vocab_size: + raise ValueError(f"piece ID must be in range [0,{vocab_size}), got {piece_id}") + return deref(self.spp).IdToPiece(piece_id).decode("utf8") + + def bos_id(self) -> int: + """Returns the piece identifier for the `bos` meta token.""" + _check_status(deref(self.spp).status()) + return deref(self.spp).bos_id() + + def eos_id(self) -> int: + """Returns the piece identifier for the `eos` meta token.""" + _check_status(deref(self.spp).status()) + return deref(self.spp).eos_id() + + def pad_id(self) -> int: + """Returns the piece identifier for the `pad` meta token.""" + _check_status(deref(self.spp).status()) + return deref(self.spp).pad_id() + + def unk_id(self) -> int: + """Returns the piece identifier for the `unk` meta token.""" + _check_status(deref(self.spp).status()) + return deref(self.spp).unk_id() + + cdef SentencePieceText _encode(self, str sentence) except * : + sentence_bytes = sentence.encode("utf-8") + cdef SentencePieceText text; + _check_status(deref(self.spp).Encode(sentence.encode("utf-8"), &text)) + return text + + def __reduce__(self): + return (unpickle_sentence_piece_processor, (self.to_protobuf(),)) + +cdef _check_status(Status status): + cdef code = status.code() + if code == kOk: + return + elif code == kNotFound: + raise OSError(status.error_message().decode("utf-8")) + elif code == kInternal: + raise RuntimeError(status.error_message().decode("utf-8")) + else: + raise ValueError(status.error_message().decode("utf-8")) + +def unpickle_sentence_piece_processor(protobuf: bytes) -> SentencePieceProcessor: + return SentencePieceProcessor.from_protobuf(protobuf) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/_wordpiece.cp312-win_amd64.pyd b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/_wordpiece.cp312-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..347b974305ad0938ff7ff5d7bbd52e9bd2e1c309 Binary files /dev/null and b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/_wordpiece.cp312-win_amd64.pyd differ diff --git a/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/_wordpiece.cpp b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/_wordpiece.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e93327f6c32b34aae59e3db6b2adebbc2b6937d0 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/_wordpiece.cpp @@ -0,0 +1,12736 @@ +/* Generated by Cython 3.0.8 */ + +/* BEGIN: Cython Metadata +{ + "distutils": { + "depends": [ + "curated_tokenizers\\wordpiece.hh" + ], + "include_dirs": [ + "curated_tokenizers" + ], + "language": "c++", + "name": "curated_tokenizers._wordpiece", + "sources": [ + "curated_tokenizers/_wordpiece.pyx", + "curated_tokenizers/wordpiece.cc" + ] + }, + "module_name": "curated_tokenizers._wordpiece" +} +END: Cython Metadata */ + +#ifndef PY_SSIZE_T_CLEAN +#define PY_SSIZE_T_CLEAN +#endif /* PY_SSIZE_T_CLEAN */ +#if defined(CYTHON_LIMITED_API) && 0 + #ifndef Py_LIMITED_API + #if CYTHON_LIMITED_API+0 > 0x03030000 + #define Py_LIMITED_API CYTHON_LIMITED_API + #else + #define Py_LIMITED_API 0x03030000 + #endif + #endif +#endif + +#include "Python.h" +#ifndef Py_PYTHON_H + #error Python headers needed to compile C extensions, please install development version of Python. +#elif PY_VERSION_HEX < 0x02070000 || (0x03000000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x03030000) + #error Cython requires Python 2.7+ or Python 3.3+. +#else +#if defined(CYTHON_LIMITED_API) && CYTHON_LIMITED_API +#define __PYX_EXTRA_ABI_MODULE_NAME "limited" +#else +#define __PYX_EXTRA_ABI_MODULE_NAME "" +#endif +#define CYTHON_ABI "3_0_8" __PYX_EXTRA_ABI_MODULE_NAME +#define __PYX_ABI_MODULE_NAME "_cython_" CYTHON_ABI +#define __PYX_TYPE_MODULE_PREFIX __PYX_ABI_MODULE_NAME "." +#define CYTHON_HEX_VERSION 0x030008F0 +#define CYTHON_FUTURE_DIVISION 0 +#include +#ifndef offsetof + #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) +#endif +#if !defined(_WIN32) && !defined(WIN32) && !defined(MS_WINDOWS) + #ifndef __stdcall + #define __stdcall + #endif + #ifndef __cdecl + #define __cdecl + #endif + #ifndef __fastcall + #define __fastcall + #endif +#endif +#ifndef DL_IMPORT + #define DL_IMPORT(t) t +#endif +#ifndef DL_EXPORT + #define DL_EXPORT(t) t +#endif +#define __PYX_COMMA , +#ifndef HAVE_LONG_LONG + #define HAVE_LONG_LONG +#endif +#ifndef PY_LONG_LONG + #define PY_LONG_LONG LONG_LONG +#endif +#ifndef Py_HUGE_VAL + #define Py_HUGE_VAL HUGE_VAL +#endif +#define __PYX_LIMITED_VERSION_HEX PY_VERSION_HEX +#if defined(GRAALVM_PYTHON) + /* For very preliminary testing purposes. Most variables are set the same as PyPy. + The existence of this section does not imply that anything works or is even tested */ + #define CYTHON_COMPILING_IN_PYPY 0 + #define CYTHON_COMPILING_IN_CPYTHON 0 + #define CYTHON_COMPILING_IN_LIMITED_API 0 + #define CYTHON_COMPILING_IN_GRAAL 1 + #define CYTHON_COMPILING_IN_NOGIL 0 + #undef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 0 + #undef CYTHON_USE_TYPE_SPECS + #define CYTHON_USE_TYPE_SPECS 0 + #undef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 0 + #if PY_VERSION_HEX < 0x03050000 + #undef CYTHON_USE_ASYNC_SLOTS + #define CYTHON_USE_ASYNC_SLOTS 0 + #elif !defined(CYTHON_USE_ASYNC_SLOTS) + #define CYTHON_USE_ASYNC_SLOTS 1 + #endif + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #undef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 0 + #undef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #undef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 0 + #undef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 1 + #undef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 0 + #undef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 0 + #undef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 0 + #undef CYTHON_FAST_GIL + #define CYTHON_FAST_GIL 0 + #undef CYTHON_METH_FASTCALL + #define CYTHON_METH_FASTCALL 0 + #undef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 0 + #ifndef CYTHON_PEP487_INIT_SUBCLASS + #define CYTHON_PEP487_INIT_SUBCLASS (PY_MAJOR_VERSION >= 3) + #endif + #undef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #undef CYTHON_USE_MODULE_STATE + #define CYTHON_USE_MODULE_STATE 0 + #undef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE 0 + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #undef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 0 + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC 0 + #endif +#elif defined(PYPY_VERSION) + #define CYTHON_COMPILING_IN_PYPY 1 + #define CYTHON_COMPILING_IN_CPYTHON 0 + #define CYTHON_COMPILING_IN_LIMITED_API 0 + #define CYTHON_COMPILING_IN_GRAAL 0 + #define CYTHON_COMPILING_IN_NOGIL 0 + #undef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 0 + #ifndef CYTHON_USE_TYPE_SPECS + #define CYTHON_USE_TYPE_SPECS 0 + #endif + #undef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 0 + #if PY_VERSION_HEX < 0x03050000 + #undef CYTHON_USE_ASYNC_SLOTS + #define CYTHON_USE_ASYNC_SLOTS 0 + #elif !defined(CYTHON_USE_ASYNC_SLOTS) + #define CYTHON_USE_ASYNC_SLOTS 1 + #endif + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #undef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 0 + #undef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #undef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 0 + #undef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 1 + #undef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 0 + #undef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 0 + #undef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 0 + #undef CYTHON_FAST_GIL + #define CYTHON_FAST_GIL 0 + #undef CYTHON_METH_FASTCALL + #define CYTHON_METH_FASTCALL 0 + #undef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 0 + #ifndef CYTHON_PEP487_INIT_SUBCLASS + #define CYTHON_PEP487_INIT_SUBCLASS (PY_MAJOR_VERSION >= 3) + #endif + #if PY_VERSION_HEX < 0x03090000 + #undef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 0 + #elif !defined(CYTHON_PEP489_MULTI_PHASE_INIT) + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #endif + #undef CYTHON_USE_MODULE_STATE + #define CYTHON_USE_MODULE_STATE 0 + #undef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE (PY_VERSION_HEX >= 0x030400a1 && PYPY_VERSION_NUM >= 0x07030C00) + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #undef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 0 + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC 0 + #endif +#elif defined(CYTHON_LIMITED_API) + #ifdef Py_LIMITED_API + #undef __PYX_LIMITED_VERSION_HEX + #define __PYX_LIMITED_VERSION_HEX Py_LIMITED_API + #endif + #define CYTHON_COMPILING_IN_PYPY 0 + #define CYTHON_COMPILING_IN_CPYTHON 0 + #define CYTHON_COMPILING_IN_LIMITED_API 1 + #define CYTHON_COMPILING_IN_GRAAL 0 + #define CYTHON_COMPILING_IN_NOGIL 0 + #undef CYTHON_CLINE_IN_TRACEBACK + #define CYTHON_CLINE_IN_TRACEBACK 0 + #undef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 0 + #undef CYTHON_USE_TYPE_SPECS + #define CYTHON_USE_TYPE_SPECS 1 + #undef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 0 + #undef CYTHON_USE_ASYNC_SLOTS + #define CYTHON_USE_ASYNC_SLOTS 0 + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #undef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 0 + #ifndef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #endif + #undef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 0 + #ifndef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 0 + #endif + #undef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 0 + #undef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 0 + #undef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 0 + #undef CYTHON_FAST_GIL + #define CYTHON_FAST_GIL 0 + #undef CYTHON_METH_FASTCALL + #define CYTHON_METH_FASTCALL 0 + #undef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 0 + #ifndef CYTHON_PEP487_INIT_SUBCLASS + #define CYTHON_PEP487_INIT_SUBCLASS 1 + #endif + #undef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 0 + #undef CYTHON_USE_MODULE_STATE + #define CYTHON_USE_MODULE_STATE 1 + #ifndef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE 0 + #endif + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #undef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 0 + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC 0 + #endif +#elif defined(Py_GIL_DISABLED) || defined(Py_NOGIL) + #define CYTHON_COMPILING_IN_PYPY 0 + #define CYTHON_COMPILING_IN_CPYTHON 0 + #define CYTHON_COMPILING_IN_LIMITED_API 0 + #define CYTHON_COMPILING_IN_GRAAL 0 + #define CYTHON_COMPILING_IN_NOGIL 1 + #ifndef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 1 + #endif + #undef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 0 + #ifndef CYTHON_USE_ASYNC_SLOTS + #define CYTHON_USE_ASYNC_SLOTS 1 + #endif + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #ifndef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 1 + #endif + #undef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #undef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 0 + #ifndef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 0 + #endif + #ifndef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 1 + #endif + #ifndef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 1 + #endif + #undef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 0 + #undef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 0 + #ifndef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #endif + #ifndef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE 1 + #endif + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #undef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 0 +#else + #define CYTHON_COMPILING_IN_PYPY 0 + #define CYTHON_COMPILING_IN_CPYTHON 1 + #define CYTHON_COMPILING_IN_LIMITED_API 0 + #define CYTHON_COMPILING_IN_GRAAL 0 + #define CYTHON_COMPILING_IN_NOGIL 0 + #ifndef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 1 + #endif + #ifndef CYTHON_USE_TYPE_SPECS + #define CYTHON_USE_TYPE_SPECS 0 + #endif + #ifndef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 1 + #endif + #if PY_MAJOR_VERSION < 3 + #undef CYTHON_USE_ASYNC_SLOTS + #define CYTHON_USE_ASYNC_SLOTS 0 + #elif !defined(CYTHON_USE_ASYNC_SLOTS) + #define CYTHON_USE_ASYNC_SLOTS 1 + #endif + #ifndef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 1 + #endif + #ifndef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 1 + #endif + #ifndef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 1 + #endif + #if PY_VERSION_HEX < 0x030300F0 || PY_VERSION_HEX >= 0x030B00A2 + #undef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #elif !defined(CYTHON_USE_UNICODE_WRITER) + #define CYTHON_USE_UNICODE_WRITER 1 + #endif + #ifndef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 0 + #endif + #ifndef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 1 + #endif + #ifndef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 1 + #endif + #ifndef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 1 + #endif + #ifndef CYTHON_FAST_GIL + #define CYTHON_FAST_GIL (PY_MAJOR_VERSION < 3 || PY_VERSION_HEX >= 0x03060000 && PY_VERSION_HEX < 0x030C00A6) + #endif + #ifndef CYTHON_METH_FASTCALL + #define CYTHON_METH_FASTCALL (PY_VERSION_HEX >= 0x030700A1) + #endif + #ifndef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 1 + #endif + #ifndef CYTHON_PEP487_INIT_SUBCLASS + #define CYTHON_PEP487_INIT_SUBCLASS 1 + #endif + #if PY_VERSION_HEX < 0x03050000 + #undef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 0 + #elif !defined(CYTHON_PEP489_MULTI_PHASE_INIT) + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #endif + #ifndef CYTHON_USE_MODULE_STATE + #define CYTHON_USE_MODULE_STATE 0 + #endif + #if PY_VERSION_HEX < 0x030400a1 + #undef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE 0 + #elif !defined(CYTHON_USE_TP_FINALIZE) + #define CYTHON_USE_TP_FINALIZE 1 + #endif + #if PY_VERSION_HEX < 0x030600B1 + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #elif !defined(CYTHON_USE_DICT_VERSIONS) + #define CYTHON_USE_DICT_VERSIONS (PY_VERSION_HEX < 0x030C00A5) + #endif + #if PY_VERSION_HEX < 0x030700A3 + #undef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 0 + #elif !defined(CYTHON_USE_EXC_INFO_STACK) + #define CYTHON_USE_EXC_INFO_STACK 1 + #endif + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC 1 + #endif +#endif +#if !defined(CYTHON_FAST_PYCCALL) +#define CYTHON_FAST_PYCCALL (CYTHON_FAST_PYCALL && PY_VERSION_HEX >= 0x030600B1) +#endif +#if !defined(CYTHON_VECTORCALL) +#define CYTHON_VECTORCALL (CYTHON_FAST_PYCCALL && PY_VERSION_HEX >= 0x030800B1) +#endif +#define CYTHON_BACKPORT_VECTORCALL (CYTHON_METH_FASTCALL && PY_VERSION_HEX < 0x030800B1) +#if CYTHON_USE_PYLONG_INTERNALS + #if PY_MAJOR_VERSION < 3 + #include "longintrepr.h" + #endif + #undef SHIFT + #undef BASE + #undef MASK + #ifdef SIZEOF_VOID_P + enum { __pyx_check_sizeof_voidp = 1 / (int)(SIZEOF_VOID_P == sizeof(void*)) }; + #endif +#endif +#ifndef __has_attribute + #define __has_attribute(x) 0 +#endif +#ifndef __has_cpp_attribute + #define __has_cpp_attribute(x) 0 +#endif +#ifndef CYTHON_RESTRICT + #if defined(__GNUC__) + #define CYTHON_RESTRICT __restrict__ + #elif defined(_MSC_VER) && _MSC_VER >= 1400 + #define CYTHON_RESTRICT __restrict + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_RESTRICT restrict + #else + #define CYTHON_RESTRICT + #endif +#endif +#ifndef CYTHON_UNUSED + #if defined(__cplusplus) + /* for clang __has_cpp_attribute(maybe_unused) is true even before C++17 + * but leads to warnings with -pedantic, since it is a C++17 feature */ + #if ((defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) || __cplusplus >= 201703L) + #if __has_cpp_attribute(maybe_unused) + #define CYTHON_UNUSED [[maybe_unused]] + #endif + #endif + #endif +#endif +#ifndef CYTHON_UNUSED +# if defined(__GNUC__) +# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +#endif +#ifndef CYTHON_UNUSED_VAR +# if defined(__cplusplus) + template void CYTHON_UNUSED_VAR( const T& ) { } +# else +# define CYTHON_UNUSED_VAR(x) (void)(x) +# endif +#endif +#ifndef CYTHON_MAYBE_UNUSED_VAR + #define CYTHON_MAYBE_UNUSED_VAR(x) CYTHON_UNUSED_VAR(x) +#endif +#ifndef CYTHON_NCP_UNUSED +# if CYTHON_COMPILING_IN_CPYTHON +# define CYTHON_NCP_UNUSED +# else +# define CYTHON_NCP_UNUSED CYTHON_UNUSED +# endif +#endif +#ifndef CYTHON_USE_CPP_STD_MOVE + #if defined(__cplusplus) && (\ + __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1600)) + #define CYTHON_USE_CPP_STD_MOVE 1 + #else + #define CYTHON_USE_CPP_STD_MOVE 0 + #endif +#endif +#define __Pyx_void_to_None(void_result) ((void)(void_result), Py_INCREF(Py_None), Py_None) +#ifdef _MSC_VER + #ifndef _MSC_STDINT_H_ + #if _MSC_VER < 1300 + typedef unsigned char uint8_t; + typedef unsigned short uint16_t; + typedef unsigned int uint32_t; + #else + typedef unsigned __int8 uint8_t; + typedef unsigned __int16 uint16_t; + typedef unsigned __int32 uint32_t; + #endif + #endif + #if _MSC_VER < 1300 + #ifdef _WIN64 + typedef unsigned long long __pyx_uintptr_t; + #else + typedef unsigned int __pyx_uintptr_t; + #endif + #else + #ifdef _WIN64 + typedef unsigned __int64 __pyx_uintptr_t; + #else + typedef unsigned __int32 __pyx_uintptr_t; + #endif + #endif +#else + #include + typedef uintptr_t __pyx_uintptr_t; +#endif +#ifndef CYTHON_FALLTHROUGH + #if defined(__cplusplus) + /* for clang __has_cpp_attribute(fallthrough) is true even before C++17 + * but leads to warnings with -pedantic, since it is a C++17 feature */ + #if ((defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) || __cplusplus >= 201703L) + #if __has_cpp_attribute(fallthrough) + #define CYTHON_FALLTHROUGH [[fallthrough]] + #endif + #endif + #ifndef CYTHON_FALLTHROUGH + #if __has_cpp_attribute(clang::fallthrough) + #define CYTHON_FALLTHROUGH [[clang::fallthrough]] + #elif __has_cpp_attribute(gnu::fallthrough) + #define CYTHON_FALLTHROUGH [[gnu::fallthrough]] + #endif + #endif + #endif + #ifndef CYTHON_FALLTHROUGH + #if __has_attribute(fallthrough) + #define CYTHON_FALLTHROUGH __attribute__((fallthrough)) + #else + #define CYTHON_FALLTHROUGH + #endif + #endif + #if defined(__clang__) && defined(__apple_build_version__) + #if __apple_build_version__ < 7000000 + #undef CYTHON_FALLTHROUGH + #define CYTHON_FALLTHROUGH + #endif + #endif +#endif +#ifdef __cplusplus + template + struct __PYX_IS_UNSIGNED_IMPL {static const bool value = T(0) < T(-1);}; + #define __PYX_IS_UNSIGNED(type) (__PYX_IS_UNSIGNED_IMPL::value) +#else + #define __PYX_IS_UNSIGNED(type) (((type)-1) > 0) +#endif +#if CYTHON_COMPILING_IN_PYPY == 1 + #define __PYX_NEED_TP_PRINT_SLOT (PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x030A0000) +#else + #define __PYX_NEED_TP_PRINT_SLOT (PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000) +#endif +#define __PYX_REINTERPRET_FUNCION(func_pointer, other_pointer) ((func_pointer)(void(*)(void))(other_pointer)) + +#ifndef __cplusplus + #error "Cython files generated with the C++ option must be compiled with a C++ compiler." +#endif +#ifndef CYTHON_INLINE + #if defined(__clang__) + #define CYTHON_INLINE __inline__ __attribute__ ((__unused__)) + #else + #define CYTHON_INLINE inline + #endif +#endif +template +void __Pyx_call_destructor(T& x) { + x.~T(); +} +template +class __Pyx_FakeReference { + public: + __Pyx_FakeReference() : ptr(NULL) { } + __Pyx_FakeReference(const T& ref) : ptr(const_cast(&ref)) { } + T *operator->() { return ptr; } + T *operator&() { return ptr; } + operator T&() { return *ptr; } + template bool operator ==(const U& other) const { return *ptr == other; } + template bool operator !=(const U& other) const { return *ptr != other; } + template bool operator==(const __Pyx_FakeReference& other) const { return *ptr == *other.ptr; } + template bool operator!=(const __Pyx_FakeReference& other) const { return *ptr != *other.ptr; } + private: + T *ptr; +}; + +#define __PYX_BUILD_PY_SSIZE_T "n" +#define CYTHON_FORMAT_SSIZE_T "z" +#if PY_MAJOR_VERSION < 3 + #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" + #define __Pyx_DefaultClassType PyClass_Type + #define __Pyx_PyCode_New(a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ + PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#else + #define __Pyx_BUILTIN_MODULE_NAME "builtins" + #define __Pyx_DefaultClassType PyType_Type +#if CYTHON_COMPILING_IN_LIMITED_API + static CYTHON_INLINE PyObject* __Pyx_PyCode_New(int a, int p, int k, int l, int s, int f, + PyObject *code, PyObject *c, PyObject* n, PyObject *v, + PyObject *fv, PyObject *cell, PyObject* fn, + PyObject *name, int fline, PyObject *lnos) { + PyObject *exception_table = NULL; + PyObject *types_module=NULL, *code_type=NULL, *result=NULL; + #if __PYX_LIMITED_VERSION_HEX < 0x030B0000 + PyObject *version_info; + PyObject *py_minor_version = NULL; + #endif + long minor_version = 0; + PyObject *type, *value, *traceback; + PyErr_Fetch(&type, &value, &traceback); + #if __PYX_LIMITED_VERSION_HEX >= 0x030B0000 + minor_version = 11; + #else + if (!(version_info = PySys_GetObject("version_info"))) goto end; + if (!(py_minor_version = PySequence_GetItem(version_info, 1))) goto end; + minor_version = PyLong_AsLong(py_minor_version); + Py_DECREF(py_minor_version); + if (minor_version == -1 && PyErr_Occurred()) goto end; + #endif + if (!(types_module = PyImport_ImportModule("types"))) goto end; + if (!(code_type = PyObject_GetAttrString(types_module, "CodeType"))) goto end; + if (minor_version <= 7) { + (void)p; + result = PyObject_CallFunction(code_type, "iiiiiOOOOOOiOO", a, k, l, s, f, code, + c, n, v, fn, name, fline, lnos, fv, cell); + } else if (minor_version <= 10) { + result = PyObject_CallFunction(code_type, "iiiiiiOOOOOOiOO", a,p, k, l, s, f, code, + c, n, v, fn, name, fline, lnos, fv, cell); + } else { + if (!(exception_table = PyBytes_FromStringAndSize(NULL, 0))) goto end; + result = PyObject_CallFunction(code_type, "iiiiiiOOOOOOOiOO", a,p, k, l, s, f, code, + c, n, v, fn, name, name, fline, lnos, exception_table, fv, cell); + } + end: + Py_XDECREF(code_type); + Py_XDECREF(exception_table); + Py_XDECREF(types_module); + if (type) { + PyErr_Restore(type, value, traceback); + } + return result; + } + #ifndef CO_OPTIMIZED + #define CO_OPTIMIZED 0x0001 + #endif + #ifndef CO_NEWLOCALS + #define CO_NEWLOCALS 0x0002 + #endif + #ifndef CO_VARARGS + #define CO_VARARGS 0x0004 + #endif + #ifndef CO_VARKEYWORDS + #define CO_VARKEYWORDS 0x0008 + #endif + #ifndef CO_ASYNC_GENERATOR + #define CO_ASYNC_GENERATOR 0x0200 + #endif + #ifndef CO_GENERATOR + #define CO_GENERATOR 0x0020 + #endif + #ifndef CO_COROUTINE + #define CO_COROUTINE 0x0080 + #endif +#elif PY_VERSION_HEX >= 0x030B0000 + static CYTHON_INLINE PyCodeObject* __Pyx_PyCode_New(int a, int p, int k, int l, int s, int f, + PyObject *code, PyObject *c, PyObject* n, PyObject *v, + PyObject *fv, PyObject *cell, PyObject* fn, + PyObject *name, int fline, PyObject *lnos) { + PyCodeObject *result; + PyObject *empty_bytes = PyBytes_FromStringAndSize("", 0); + if (!empty_bytes) return NULL; + result = + #if PY_VERSION_HEX >= 0x030C0000 + PyUnstable_Code_NewWithPosOnlyArgs + #else + PyCode_NewWithPosOnlyArgs + #endif + (a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, name, fline, lnos, empty_bytes); + Py_DECREF(empty_bytes); + return result; + } +#elif PY_VERSION_HEX >= 0x030800B2 && !CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyCode_New(a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ + PyCode_NewWithPosOnlyArgs(a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#else + #define __Pyx_PyCode_New(a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ + PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#endif +#endif +#if PY_VERSION_HEX >= 0x030900A4 || defined(Py_IS_TYPE) + #define __Pyx_IS_TYPE(ob, type) Py_IS_TYPE(ob, type) +#else + #define __Pyx_IS_TYPE(ob, type) (((const PyObject*)ob)->ob_type == (type)) +#endif +#if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_Is) + #define __Pyx_Py_Is(x, y) Py_Is(x, y) +#else + #define __Pyx_Py_Is(x, y) ((x) == (y)) +#endif +#if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_IsNone) + #define __Pyx_Py_IsNone(ob) Py_IsNone(ob) +#else + #define __Pyx_Py_IsNone(ob) __Pyx_Py_Is((ob), Py_None) +#endif +#if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_IsTrue) + #define __Pyx_Py_IsTrue(ob) Py_IsTrue(ob) +#else + #define __Pyx_Py_IsTrue(ob) __Pyx_Py_Is((ob), Py_True) +#endif +#if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_IsFalse) + #define __Pyx_Py_IsFalse(ob) Py_IsFalse(ob) +#else + #define __Pyx_Py_IsFalse(ob) __Pyx_Py_Is((ob), Py_False) +#endif +#define __Pyx_NoneAsNull(obj) (__Pyx_Py_IsNone(obj) ? NULL : (obj)) +#if PY_VERSION_HEX >= 0x030900F0 && !CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyObject_GC_IsFinalized(o) PyObject_GC_IsFinalized(o) +#else + #define __Pyx_PyObject_GC_IsFinalized(o) _PyGC_FINALIZED(o) +#endif +#ifndef CO_COROUTINE + #define CO_COROUTINE 0x80 +#endif +#ifndef CO_ASYNC_GENERATOR + #define CO_ASYNC_GENERATOR 0x200 +#endif +#ifndef Py_TPFLAGS_CHECKTYPES + #define Py_TPFLAGS_CHECKTYPES 0 +#endif +#ifndef Py_TPFLAGS_HAVE_INDEX + #define Py_TPFLAGS_HAVE_INDEX 0 +#endif +#ifndef Py_TPFLAGS_HAVE_NEWBUFFER + #define Py_TPFLAGS_HAVE_NEWBUFFER 0 +#endif +#ifndef Py_TPFLAGS_HAVE_FINALIZE + #define Py_TPFLAGS_HAVE_FINALIZE 0 +#endif +#ifndef Py_TPFLAGS_SEQUENCE + #define Py_TPFLAGS_SEQUENCE 0 +#endif +#ifndef Py_TPFLAGS_MAPPING + #define Py_TPFLAGS_MAPPING 0 +#endif +#ifndef METH_STACKLESS + #define METH_STACKLESS 0 +#endif +#if PY_VERSION_HEX <= 0x030700A3 || !defined(METH_FASTCALL) + #ifndef METH_FASTCALL + #define METH_FASTCALL 0x80 + #endif + typedef PyObject *(*__Pyx_PyCFunctionFast) (PyObject *self, PyObject *const *args, Py_ssize_t nargs); + typedef PyObject *(*__Pyx_PyCFunctionFastWithKeywords) (PyObject *self, PyObject *const *args, + Py_ssize_t nargs, PyObject *kwnames); +#else + #define __Pyx_PyCFunctionFast _PyCFunctionFast + #define __Pyx_PyCFunctionFastWithKeywords _PyCFunctionFastWithKeywords +#endif +#if CYTHON_METH_FASTCALL + #define __Pyx_METH_FASTCALL METH_FASTCALL + #define __Pyx_PyCFunction_FastCall __Pyx_PyCFunctionFast + #define __Pyx_PyCFunction_FastCallWithKeywords __Pyx_PyCFunctionFastWithKeywords +#else + #define __Pyx_METH_FASTCALL METH_VARARGS + #define __Pyx_PyCFunction_FastCall PyCFunction + #define __Pyx_PyCFunction_FastCallWithKeywords PyCFunctionWithKeywords +#endif +#if CYTHON_VECTORCALL + #define __pyx_vectorcallfunc vectorcallfunc + #define __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET PY_VECTORCALL_ARGUMENTS_OFFSET + #define __Pyx_PyVectorcall_NARGS(n) PyVectorcall_NARGS((size_t)(n)) +#elif CYTHON_BACKPORT_VECTORCALL + typedef PyObject *(*__pyx_vectorcallfunc)(PyObject *callable, PyObject *const *args, + size_t nargsf, PyObject *kwnames); + #define __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET ((size_t)1 << (8 * sizeof(size_t) - 1)) + #define __Pyx_PyVectorcall_NARGS(n) ((Py_ssize_t)(((size_t)(n)) & ~__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)) +#else + #define __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET 0 + #define __Pyx_PyVectorcall_NARGS(n) ((Py_ssize_t)(n)) +#endif +#if PY_MAJOR_VERSION >= 0x030900B1 +#define __Pyx_PyCFunction_CheckExact(func) PyCFunction_CheckExact(func) +#else +#define __Pyx_PyCFunction_CheckExact(func) PyCFunction_Check(func) +#endif +#define __Pyx_CyOrPyCFunction_Check(func) PyCFunction_Check(func) +#if CYTHON_COMPILING_IN_CPYTHON +#define __Pyx_CyOrPyCFunction_GET_FUNCTION(func) (((PyCFunctionObject*)(func))->m_ml->ml_meth) +#elif !CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_CyOrPyCFunction_GET_FUNCTION(func) PyCFunction_GET_FUNCTION(func) +#endif +#if CYTHON_COMPILING_IN_CPYTHON +#define __Pyx_CyOrPyCFunction_GET_FLAGS(func) (((PyCFunctionObject*)(func))->m_ml->ml_flags) +static CYTHON_INLINE PyObject* __Pyx_CyOrPyCFunction_GET_SELF(PyObject *func) { + return (__Pyx_CyOrPyCFunction_GET_FLAGS(func) & METH_STATIC) ? NULL : ((PyCFunctionObject*)func)->m_self; +} +#endif +static CYTHON_INLINE int __Pyx__IsSameCFunction(PyObject *func, void *cfunc) { +#if CYTHON_COMPILING_IN_LIMITED_API + return PyCFunction_Check(func) && PyCFunction_GetFunction(func) == (PyCFunction) cfunc; +#else + return PyCFunction_Check(func) && PyCFunction_GET_FUNCTION(func) == (PyCFunction) cfunc; +#endif +} +#define __Pyx_IsSameCFunction(func, cfunc) __Pyx__IsSameCFunction(func, cfunc) +#if __PYX_LIMITED_VERSION_HEX < 0x030900B1 + #define __Pyx_PyType_FromModuleAndSpec(m, s, b) ((void)m, PyType_FromSpecWithBases(s, b)) + typedef PyObject *(*__Pyx_PyCMethod)(PyObject *, PyTypeObject *, PyObject *const *, size_t, PyObject *); +#else + #define __Pyx_PyType_FromModuleAndSpec(m, s, b) PyType_FromModuleAndSpec(m, s, b) + #define __Pyx_PyCMethod PyCMethod +#endif +#ifndef METH_METHOD + #define METH_METHOD 0x200 +#endif +#if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Malloc) + #define PyObject_Malloc(s) PyMem_Malloc(s) + #define PyObject_Free(p) PyMem_Free(p) + #define PyObject_Realloc(p) PyMem_Realloc(p) +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) + #define __Pyx_PyFrame_SetLineNumber(frame, lineno) +#else + #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) + #define __Pyx_PyFrame_SetLineNumber(frame, lineno) (frame)->f_lineno = (lineno) +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_PyThreadState_Current PyThreadState_Get() +#elif !CYTHON_FAST_THREAD_STATE + #define __Pyx_PyThreadState_Current PyThreadState_GET() +#elif PY_VERSION_HEX >= 0x030d00A1 + #define __Pyx_PyThreadState_Current PyThreadState_GetUnchecked() +#elif PY_VERSION_HEX >= 0x03060000 + #define __Pyx_PyThreadState_Current _PyThreadState_UncheckedGet() +#elif PY_VERSION_HEX >= 0x03000000 + #define __Pyx_PyThreadState_Current PyThreadState_GET() +#else + #define __Pyx_PyThreadState_Current _PyThreadState_Current +#endif +#if CYTHON_COMPILING_IN_LIMITED_API +static CYTHON_INLINE void *__Pyx_PyModule_GetState(PyObject *op) +{ + void *result; + result = PyModule_GetState(op); + if (!result) + Py_FatalError("Couldn't find the module state"); + return result; +} +#endif +#define __Pyx_PyObject_GetSlot(obj, name, func_ctype) __Pyx_PyType_GetSlot(Py_TYPE(obj), name, func_ctype) +#if CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_PyType_GetSlot(type, name, func_ctype) ((func_ctype) PyType_GetSlot((type), Py_##name)) +#else + #define __Pyx_PyType_GetSlot(type, name, func_ctype) ((type)->name) +#endif +#if PY_VERSION_HEX < 0x030700A2 && !defined(PyThread_tss_create) && !defined(Py_tss_NEEDS_INIT) +#include "pythread.h" +#define Py_tss_NEEDS_INIT 0 +typedef int Py_tss_t; +static CYTHON_INLINE int PyThread_tss_create(Py_tss_t *key) { + *key = PyThread_create_key(); + return 0; +} +static CYTHON_INLINE Py_tss_t * PyThread_tss_alloc(void) { + Py_tss_t *key = (Py_tss_t *)PyObject_Malloc(sizeof(Py_tss_t)); + *key = Py_tss_NEEDS_INIT; + return key; +} +static CYTHON_INLINE void PyThread_tss_free(Py_tss_t *key) { + PyObject_Free(key); +} +static CYTHON_INLINE int PyThread_tss_is_created(Py_tss_t *key) { + return *key != Py_tss_NEEDS_INIT; +} +static CYTHON_INLINE void PyThread_tss_delete(Py_tss_t *key) { + PyThread_delete_key(*key); + *key = Py_tss_NEEDS_INIT; +} +static CYTHON_INLINE int PyThread_tss_set(Py_tss_t *key, void *value) { + return PyThread_set_key_value(*key, value); +} +static CYTHON_INLINE void * PyThread_tss_get(Py_tss_t *key) { + return PyThread_get_key_value(*key); +} +#endif +#if PY_MAJOR_VERSION < 3 + #if CYTHON_COMPILING_IN_PYPY + #if PYPY_VERSION_NUM < 0x07030600 + #if defined(__cplusplus) && __cplusplus >= 201402L + [[deprecated("`with nogil:` inside a nogil function will not release the GIL in PyPy2 < 7.3.6")]] + #elif defined(__GNUC__) || defined(__clang__) + __attribute__ ((__deprecated__("`with nogil:` inside a nogil function will not release the GIL in PyPy2 < 7.3.6"))) + #elif defined(_MSC_VER) + __declspec(deprecated("`with nogil:` inside a nogil function will not release the GIL in PyPy2 < 7.3.6")) + #endif + static CYTHON_INLINE int PyGILState_Check(void) { + return 0; + } + #else // PYPY_VERSION_NUM < 0x07030600 + #endif // PYPY_VERSION_NUM < 0x07030600 + #else + static CYTHON_INLINE int PyGILState_Check(void) { + PyThreadState * tstate = _PyThreadState_Current; + return tstate && (tstate == PyGILState_GetThisThreadState()); + } + #endif +#endif +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030d0000 || defined(_PyDict_NewPresized) +#define __Pyx_PyDict_NewPresized(n) ((n <= 8) ? PyDict_New() : _PyDict_NewPresized(n)) +#else +#define __Pyx_PyDict_NewPresized(n) PyDict_New() +#endif +#if PY_MAJOR_VERSION >= 3 || CYTHON_FUTURE_DIVISION + #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) +#else + #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) +#endif +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX > 0x030600B4 && PY_VERSION_HEX < 0x030d0000 && CYTHON_USE_UNICODE_INTERNALS +#define __Pyx_PyDict_GetItemStrWithError(dict, name) _PyDict_GetItem_KnownHash(dict, name, ((PyASCIIObject *) name)->hash) +static CYTHON_INLINE PyObject * __Pyx_PyDict_GetItemStr(PyObject *dict, PyObject *name) { + PyObject *res = __Pyx_PyDict_GetItemStrWithError(dict, name); + if (res == NULL) PyErr_Clear(); + return res; +} +#elif PY_MAJOR_VERSION >= 3 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07020000) +#define __Pyx_PyDict_GetItemStrWithError PyDict_GetItemWithError +#define __Pyx_PyDict_GetItemStr PyDict_GetItem +#else +static CYTHON_INLINE PyObject * __Pyx_PyDict_GetItemStrWithError(PyObject *dict, PyObject *name) { +#if CYTHON_COMPILING_IN_PYPY + return PyDict_GetItem(dict, name); +#else + PyDictEntry *ep; + PyDictObject *mp = (PyDictObject*) dict; + long hash = ((PyStringObject *) name)->ob_shash; + assert(hash != -1); + ep = (mp->ma_lookup)(mp, name, hash); + if (ep == NULL) { + return NULL; + } + return ep->me_value; +#endif +} +#define __Pyx_PyDict_GetItemStr PyDict_GetItem +#endif +#if CYTHON_USE_TYPE_SLOTS + #define __Pyx_PyType_GetFlags(tp) (((PyTypeObject *)tp)->tp_flags) + #define __Pyx_PyType_HasFeature(type, feature) ((__Pyx_PyType_GetFlags(type) & (feature)) != 0) + #define __Pyx_PyObject_GetIterNextFunc(obj) (Py_TYPE(obj)->tp_iternext) +#else + #define __Pyx_PyType_GetFlags(tp) (PyType_GetFlags((PyTypeObject *)tp)) + #define __Pyx_PyType_HasFeature(type, feature) PyType_HasFeature(type, feature) + #define __Pyx_PyObject_GetIterNextFunc(obj) PyIter_Next +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_SetItemOnTypeDict(tp, k, v) PyObject_GenericSetAttr((PyObject*)tp, k, v) +#else + #define __Pyx_SetItemOnTypeDict(tp, k, v) PyDict_SetItem(tp->tp_dict, k, v) +#endif +#if CYTHON_USE_TYPE_SPECS && PY_VERSION_HEX >= 0x03080000 +#define __Pyx_PyHeapTypeObject_GC_Del(obj) {\ + PyTypeObject *type = Py_TYPE((PyObject*)obj);\ + assert(__Pyx_PyType_HasFeature(type, Py_TPFLAGS_HEAPTYPE));\ + PyObject_GC_Del(obj);\ + Py_DECREF(type);\ +} +#else +#define __Pyx_PyHeapTypeObject_GC_Del(obj) PyObject_GC_Del(obj) +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + #define CYTHON_PEP393_ENABLED 1 + #define __Pyx_PyUnicode_READY(op) (0) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GetLength(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_ReadChar(u, i) + #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) ((void)u, 1114111U) + #define __Pyx_PyUnicode_KIND(u) ((void)u, (0)) + #define __Pyx_PyUnicode_DATA(u) ((void*)u) + #define __Pyx_PyUnicode_READ(k, d, i) ((void)k, PyUnicode_ReadChar((PyObject*)(d), i)) + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GetLength(u)) +#elif PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) + #define CYTHON_PEP393_ENABLED 1 + #if PY_VERSION_HEX >= 0x030C0000 + #define __Pyx_PyUnicode_READY(op) (0) + #else + #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ?\ + 0 : _PyUnicode_Ready((PyObject *)(op))) + #endif + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) + #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) PyUnicode_MAX_CHAR_VALUE(u) + #define __Pyx_PyUnicode_KIND(u) ((int)PyUnicode_KIND(u)) + #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) + #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) + #define __Pyx_PyUnicode_WRITE(k, d, i, ch) PyUnicode_WRITE(k, d, i, (Py_UCS4) ch) + #if PY_VERSION_HEX >= 0x030C0000 + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_LENGTH(u)) + #else + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x03090000 + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : ((PyCompactUnicodeObject *)(u))->wstr_length)) + #else + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : PyUnicode_GET_SIZE(u))) + #endif + #endif +#else + #define CYTHON_PEP393_ENABLED 0 + #define PyUnicode_1BYTE_KIND 1 + #define PyUnicode_2BYTE_KIND 2 + #define PyUnicode_4BYTE_KIND 4 + #define __Pyx_PyUnicode_READY(op) (0) + #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) + #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) + #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) ((sizeof(Py_UNICODE) == 2) ? 65535U : 1114111U) + #define __Pyx_PyUnicode_KIND(u) ((int)sizeof(Py_UNICODE)) + #define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u)) + #define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i])) + #define __Pyx_PyUnicode_WRITE(k, d, i, ch) (((void)(k)), ((Py_UNICODE*)d)[i] = (Py_UNICODE) ch) + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_SIZE(u)) +#endif +#if CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) +#else + #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ?\ + PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) +#endif +#if CYTHON_COMPILING_IN_PYPY + #if !defined(PyUnicode_DecodeUnicodeEscape) + #define PyUnicode_DecodeUnicodeEscape(s, size, errors) PyUnicode_Decode(s, size, "unicode_escape", errors) + #endif + #if !defined(PyUnicode_Contains) || (PY_MAJOR_VERSION == 2 && PYPY_VERSION_NUM < 0x07030500) + #undef PyUnicode_Contains + #define PyUnicode_Contains(u, s) PySequence_Contains(u, s) + #endif + #if !defined(PyByteArray_Check) + #define PyByteArray_Check(obj) PyObject_TypeCheck(obj, &PyByteArray_Type) + #endif + #if !defined(PyObject_Format) + #define PyObject_Format(obj, fmt) PyObject_CallMethod(obj, "__format__", "O", fmt) + #endif +#endif +#define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyString_Check(b) && !PyString_CheckExact(b)))) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) +#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyUnicode_Check(b) && !PyUnicode_CheckExact(b)))) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b) +#else + #define __Pyx_PyString_Format(a, b) PyString_Format(a, b) +#endif +#if PY_MAJOR_VERSION < 3 && !defined(PyObject_ASCII) + #define PyObject_ASCII(o) PyObject_Repr(o) +#endif +#if PY_MAJOR_VERSION >= 3 + #define PyBaseString_Type PyUnicode_Type + #define PyStringObject PyUnicodeObject + #define PyString_Type PyUnicode_Type + #define PyString_Check PyUnicode_Check + #define PyString_CheckExact PyUnicode_CheckExact +#ifndef PyObject_Unicode + #define PyObject_Unicode PyObject_Str +#endif +#endif +#if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) + #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) +#else + #define __Pyx_PyBaseString_Check(obj) (PyString_Check(obj) || PyUnicode_Check(obj)) + #define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj)) +#endif +#if CYTHON_COMPILING_IN_CPYTHON + #define __Pyx_PySequence_ListKeepNew(obj)\ + (likely(PyList_CheckExact(obj) && Py_REFCNT(obj) == 1) ? __Pyx_NewRef(obj) : PySequence_List(obj)) +#else + #define __Pyx_PySequence_ListKeepNew(obj) PySequence_List(obj) +#endif +#ifndef PySet_CheckExact + #define PySet_CheckExact(obj) __Pyx_IS_TYPE(obj, &PySet_Type) +#endif +#if PY_VERSION_HEX >= 0x030900A4 + #define __Pyx_SET_REFCNT(obj, refcnt) Py_SET_REFCNT(obj, refcnt) + #define __Pyx_SET_SIZE(obj, size) Py_SET_SIZE(obj, size) +#else + #define __Pyx_SET_REFCNT(obj, refcnt) Py_REFCNT(obj) = (refcnt) + #define __Pyx_SET_SIZE(obj, size) Py_SIZE(obj) = (size) +#endif +#if CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_PySequence_ITEM(o, i) PySequence_ITEM(o, i) + #define __Pyx_PySequence_SIZE(seq) Py_SIZE(seq) + #define __Pyx_PyTuple_SET_ITEM(o, i, v) (PyTuple_SET_ITEM(o, i, v), (0)) + #define __Pyx_PyList_SET_ITEM(o, i, v) (PyList_SET_ITEM(o, i, v), (0)) + #define __Pyx_PyTuple_GET_SIZE(o) PyTuple_GET_SIZE(o) + #define __Pyx_PyList_GET_SIZE(o) PyList_GET_SIZE(o) + #define __Pyx_PySet_GET_SIZE(o) PySet_GET_SIZE(o) + #define __Pyx_PyBytes_GET_SIZE(o) PyBytes_GET_SIZE(o) + #define __Pyx_PyByteArray_GET_SIZE(o) PyByteArray_GET_SIZE(o) +#else + #define __Pyx_PySequence_ITEM(o, i) PySequence_GetItem(o, i) + #define __Pyx_PySequence_SIZE(seq) PySequence_Size(seq) + #define __Pyx_PyTuple_SET_ITEM(o, i, v) PyTuple_SetItem(o, i, v) + #define __Pyx_PyList_SET_ITEM(o, i, v) PyList_SetItem(o, i, v) + #define __Pyx_PyTuple_GET_SIZE(o) PyTuple_Size(o) + #define __Pyx_PyList_GET_SIZE(o) PyList_Size(o) + #define __Pyx_PySet_GET_SIZE(o) PySet_Size(o) + #define __Pyx_PyBytes_GET_SIZE(o) PyBytes_Size(o) + #define __Pyx_PyByteArray_GET_SIZE(o) PyByteArray_Size(o) +#endif +#if PY_VERSION_HEX >= 0x030d00A1 + #define __Pyx_PyImport_AddModuleRef(name) PyImport_AddModuleRef(name) +#else + static CYTHON_INLINE PyObject *__Pyx_PyImport_AddModuleRef(const char *name) { + PyObject *module = PyImport_AddModule(name); + Py_XINCREF(module); + return module; + } +#endif +#if PY_MAJOR_VERSION >= 3 + #define PyIntObject PyLongObject + #define PyInt_Type PyLong_Type + #define PyInt_Check(op) PyLong_Check(op) + #define PyInt_CheckExact(op) PyLong_CheckExact(op) + #define __Pyx_Py3Int_Check(op) PyLong_Check(op) + #define __Pyx_Py3Int_CheckExact(op) PyLong_CheckExact(op) + #define PyInt_FromString PyLong_FromString + #define PyInt_FromUnicode PyLong_FromUnicode + #define PyInt_FromLong PyLong_FromLong + #define PyInt_FromSize_t PyLong_FromSize_t + #define PyInt_FromSsize_t PyLong_FromSsize_t + #define PyInt_AsLong PyLong_AsLong + #define PyInt_AS_LONG PyLong_AS_LONG + #define PyInt_AsSsize_t PyLong_AsSsize_t + #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask + #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask + #define PyNumber_Int PyNumber_Long +#else + #define __Pyx_Py3Int_Check(op) (PyLong_Check(op) || PyInt_Check(op)) + #define __Pyx_Py3Int_CheckExact(op) (PyLong_CheckExact(op) || PyInt_CheckExact(op)) +#endif +#if PY_MAJOR_VERSION >= 3 + #define PyBoolObject PyLongObject +#endif +#if PY_MAJOR_VERSION >= 3 && CYTHON_COMPILING_IN_PYPY + #ifndef PyUnicode_InternFromString + #define PyUnicode_InternFromString(s) PyUnicode_FromString(s) + #endif +#endif +#if PY_VERSION_HEX < 0x030200A4 + typedef long Py_hash_t; + #define __Pyx_PyInt_FromHash_t PyInt_FromLong + #define __Pyx_PyInt_AsHash_t __Pyx_PyIndex_AsHash_t +#else + #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t + #define __Pyx_PyInt_AsHash_t __Pyx_PyIndex_AsSsize_t +#endif +#if CYTHON_USE_ASYNC_SLOTS + #if PY_VERSION_HEX >= 0x030500B1 + #define __Pyx_PyAsyncMethodsStruct PyAsyncMethods + #define __Pyx_PyType_AsAsync(obj) (Py_TYPE(obj)->tp_as_async) + #else + #define __Pyx_PyType_AsAsync(obj) ((__Pyx_PyAsyncMethodsStruct*) (Py_TYPE(obj)->tp_reserved)) + #endif +#else + #define __Pyx_PyType_AsAsync(obj) NULL +#endif +#ifndef __Pyx_PyAsyncMethodsStruct + typedef struct { + unaryfunc am_await; + unaryfunc am_aiter; + unaryfunc am_anext; + } __Pyx_PyAsyncMethodsStruct; +#endif + +#if defined(_WIN32) || defined(WIN32) || defined(MS_WINDOWS) + #if !defined(_USE_MATH_DEFINES) + #define _USE_MATH_DEFINES + #endif +#endif +#include +#ifdef NAN +#define __PYX_NAN() ((float) NAN) +#else +static CYTHON_INLINE float __PYX_NAN() { + float value; + memset(&value, 0xFF, sizeof(value)); + return value; +} +#endif +#if defined(__CYGWIN__) && defined(_LDBL_EQ_DBL) +#define __Pyx_truncl trunc +#else +#define __Pyx_truncl truncl +#endif + +#define __PYX_MARK_ERR_POS(f_index, lineno) \ + { __pyx_filename = __pyx_f[f_index]; (void)__pyx_filename; __pyx_lineno = lineno; (void)__pyx_lineno; __pyx_clineno = __LINE__; (void)__pyx_clineno; } +#define __PYX_ERR(f_index, lineno, Ln_error) \ + { __PYX_MARK_ERR_POS(f_index, lineno) goto Ln_error; } + +#ifdef CYTHON_EXTERN_C + #undef __PYX_EXTERN_C + #define __PYX_EXTERN_C CYTHON_EXTERN_C +#elif defined(__PYX_EXTERN_C) + #ifdef _MSC_VER + #pragma message ("Please do not define the '__PYX_EXTERN_C' macro externally. Use 'CYTHON_EXTERN_C' instead.") + #else + #warning Please do not define the '__PYX_EXTERN_C' macro externally. Use 'CYTHON_EXTERN_C' instead. + #endif +#else + #define __PYX_EXTERN_C extern "C++" +#endif + +#define __PYX_HAVE__curated_tokenizers___wordpiece +#define __PYX_HAVE_API__curated_tokenizers___wordpiece +/* Early includes */ +#include +#include +#include "ios" +#include "new" +#include "stdexcept" +#include "typeinfo" +#include + + #if __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1600) + // move should be defined for these versions of MSVC, but __cplusplus isn't set usefully + #include + + namespace cython_std { + template typename std::remove_reference::type&& move(T& t) noexcept { return std::move(t); } + template typename std::remove_reference::type&& move(T&& t) noexcept { return std::move(t); } + } + + #endif + +#include +#include +#include "wordpiece.hh" +#ifdef _OPENMP +#include +#endif /* _OPENMP */ + +#if defined(PYREX_WITHOUT_ASSERTIONS) && !defined(CYTHON_WITHOUT_ASSERTIONS) +#define CYTHON_WITHOUT_ASSERTIONS +#endif + +typedef struct {PyObject **p; const char *s; const Py_ssize_t n; const char* encoding; + const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; + +#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 +#define __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 0 +#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT (PY_MAJOR_VERSION >= 3 && __PYX_DEFAULT_STRING_ENCODING_IS_UTF8) +#define __PYX_DEFAULT_STRING_ENCODING "" +#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString +#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#define __Pyx_uchar_cast(c) ((unsigned char)c) +#define __Pyx_long_cast(x) ((long)x) +#define __Pyx_fits_Py_ssize_t(v, type, is_signed) (\ + (sizeof(type) < sizeof(Py_ssize_t)) ||\ + (sizeof(type) > sizeof(Py_ssize_t) &&\ + likely(v < (type)PY_SSIZE_T_MAX ||\ + v == (type)PY_SSIZE_T_MAX) &&\ + (!is_signed || likely(v > (type)PY_SSIZE_T_MIN ||\ + v == (type)PY_SSIZE_T_MIN))) ||\ + (sizeof(type) == sizeof(Py_ssize_t) &&\ + (is_signed || likely(v < (type)PY_SSIZE_T_MAX ||\ + v == (type)PY_SSIZE_T_MAX))) ) +static CYTHON_INLINE int __Pyx_is_valid_index(Py_ssize_t i, Py_ssize_t limit) { + return (size_t) i < (size_t) limit; +} +#if defined (__cplusplus) && __cplusplus >= 201103L + #include + #define __Pyx_sst_abs(value) std::abs(value) +#elif SIZEOF_INT >= SIZEOF_SIZE_T + #define __Pyx_sst_abs(value) abs(value) +#elif SIZEOF_LONG >= SIZEOF_SIZE_T + #define __Pyx_sst_abs(value) labs(value) +#elif defined (_MSC_VER) + #define __Pyx_sst_abs(value) ((Py_ssize_t)_abs64(value)) +#elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define __Pyx_sst_abs(value) llabs(value) +#elif defined (__GNUC__) + #define __Pyx_sst_abs(value) __builtin_llabs(value) +#else + #define __Pyx_sst_abs(value) ((value<0) ? -value : value) +#endif +static CYTHON_INLINE Py_ssize_t __Pyx_ssize_strlen(const char *s); +static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject*); +static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); +static CYTHON_INLINE PyObject* __Pyx_PyByteArray_FromString(const char*); +#define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) +#define __Pyx_PyBytes_FromString PyBytes_FromString +#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); +#if PY_MAJOR_VERSION < 3 + #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#else + #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString + #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize +#endif +#define __Pyx_PyBytes_AsWritableString(s) ((char*) PyBytes_AS_STRING(s)) +#define __Pyx_PyBytes_AsWritableSString(s) ((signed char*) PyBytes_AS_STRING(s)) +#define __Pyx_PyBytes_AsWritableUString(s) ((unsigned char*) PyBytes_AS_STRING(s)) +#define __Pyx_PyBytes_AsString(s) ((const char*) PyBytes_AS_STRING(s)) +#define __Pyx_PyBytes_AsSString(s) ((const signed char*) PyBytes_AS_STRING(s)) +#define __Pyx_PyBytes_AsUString(s) ((const unsigned char*) PyBytes_AS_STRING(s)) +#define __Pyx_PyObject_AsWritableString(s) ((char*)(__pyx_uintptr_t) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsWritableSString(s) ((signed char*)(__pyx_uintptr_t) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsWritableUString(s) ((unsigned char*)(__pyx_uintptr_t) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsSString(s) ((const signed char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsUString(s) ((const unsigned char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_FromCString(s) __Pyx_PyObject_FromString((const char*)s) +#define __Pyx_PyBytes_FromCString(s) __Pyx_PyBytes_FromString((const char*)s) +#define __Pyx_PyByteArray_FromCString(s) __Pyx_PyByteArray_FromString((const char*)s) +#define __Pyx_PyStr_FromCString(s) __Pyx_PyStr_FromString((const char*)s) +#define __Pyx_PyUnicode_FromCString(s) __Pyx_PyUnicode_FromString((const char*)s) +#if CYTHON_COMPILING_IN_LIMITED_API +static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const wchar_t *u) +{ + const wchar_t *u_end = u; + while (*u_end++) ; + return (size_t)(u_end - u - 1); +} +#else +static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) +{ + const Py_UNICODE *u_end = u; + while (*u_end++) ; + return (size_t)(u_end - u - 1); +} +#endif +#define __Pyx_PyUnicode_FromOrdinal(o) PyUnicode_FromOrdinal((int)o) +#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) +#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode +#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode +#define __Pyx_NewRef(obj) (Py_INCREF(obj), obj) +#define __Pyx_Owned_Py_None(b) __Pyx_NewRef(Py_None) +static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b); +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); +static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject*); +static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x); +#define __Pyx_PySequence_Tuple(obj)\ + (likely(PyTuple_CheckExact(obj)) ? __Pyx_NewRef(obj) : PySequence_Tuple(obj)) +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); +static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); +static CYTHON_INLINE Py_hash_t __Pyx_PyIndex_AsHash_t(PyObject*); +#if CYTHON_ASSUME_SAFE_MACROS +#define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) +#else +#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) +#endif +#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) +#if PY_MAJOR_VERSION >= 3 +#define __Pyx_PyNumber_Int(x) (PyLong_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Long(x)) +#else +#define __Pyx_PyNumber_Int(x) (PyInt_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Int(x)) +#endif +#if CYTHON_USE_PYLONG_INTERNALS + #if PY_VERSION_HEX >= 0x030C00A7 + #ifndef _PyLong_SIGN_MASK + #define _PyLong_SIGN_MASK 3 + #endif + #ifndef _PyLong_NON_SIZE_BITS + #define _PyLong_NON_SIZE_BITS 3 + #endif + #define __Pyx_PyLong_Sign(x) (((PyLongObject*)x)->long_value.lv_tag & _PyLong_SIGN_MASK) + #define __Pyx_PyLong_IsNeg(x) ((__Pyx_PyLong_Sign(x) & 2) != 0) + #define __Pyx_PyLong_IsNonNeg(x) (!__Pyx_PyLong_IsNeg(x)) + #define __Pyx_PyLong_IsZero(x) (__Pyx_PyLong_Sign(x) & 1) + #define __Pyx_PyLong_IsPos(x) (__Pyx_PyLong_Sign(x) == 0) + #define __Pyx_PyLong_CompactValueUnsigned(x) (__Pyx_PyLong_Digits(x)[0]) + #define __Pyx_PyLong_DigitCount(x) ((Py_ssize_t) (((PyLongObject*)x)->long_value.lv_tag >> _PyLong_NON_SIZE_BITS)) + #define __Pyx_PyLong_SignedDigitCount(x)\ + ((1 - (Py_ssize_t) __Pyx_PyLong_Sign(x)) * __Pyx_PyLong_DigitCount(x)) + #if defined(PyUnstable_Long_IsCompact) && defined(PyUnstable_Long_CompactValue) + #define __Pyx_PyLong_IsCompact(x) PyUnstable_Long_IsCompact((PyLongObject*) x) + #define __Pyx_PyLong_CompactValue(x) PyUnstable_Long_CompactValue((PyLongObject*) x) + #else + #define __Pyx_PyLong_IsCompact(x) (((PyLongObject*)x)->long_value.lv_tag < (2 << _PyLong_NON_SIZE_BITS)) + #define __Pyx_PyLong_CompactValue(x) ((1 - (Py_ssize_t) __Pyx_PyLong_Sign(x)) * (Py_ssize_t) __Pyx_PyLong_Digits(x)[0]) + #endif + typedef Py_ssize_t __Pyx_compact_pylong; + typedef size_t __Pyx_compact_upylong; + #else + #define __Pyx_PyLong_IsNeg(x) (Py_SIZE(x) < 0) + #define __Pyx_PyLong_IsNonNeg(x) (Py_SIZE(x) >= 0) + #define __Pyx_PyLong_IsZero(x) (Py_SIZE(x) == 0) + #define __Pyx_PyLong_IsPos(x) (Py_SIZE(x) > 0) + #define __Pyx_PyLong_CompactValueUnsigned(x) ((Py_SIZE(x) == 0) ? 0 : __Pyx_PyLong_Digits(x)[0]) + #define __Pyx_PyLong_DigitCount(x) __Pyx_sst_abs(Py_SIZE(x)) + #define __Pyx_PyLong_SignedDigitCount(x) Py_SIZE(x) + #define __Pyx_PyLong_IsCompact(x) (Py_SIZE(x) == 0 || Py_SIZE(x) == 1 || Py_SIZE(x) == -1) + #define __Pyx_PyLong_CompactValue(x)\ + ((Py_SIZE(x) == 0) ? (sdigit) 0 : ((Py_SIZE(x) < 0) ? -(sdigit)__Pyx_PyLong_Digits(x)[0] : (sdigit)__Pyx_PyLong_Digits(x)[0])) + typedef sdigit __Pyx_compact_pylong; + typedef digit __Pyx_compact_upylong; + #endif + #if PY_VERSION_HEX >= 0x030C00A5 + #define __Pyx_PyLong_Digits(x) (((PyLongObject*)x)->long_value.ob_digit) + #else + #define __Pyx_PyLong_Digits(x) (((PyLongObject*)x)->ob_digit) + #endif +#endif +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII +#include +static int __Pyx_sys_getdefaultencoding_not_ascii; +static int __Pyx_init_sys_getdefaultencoding_params(void) { + PyObject* sys; + PyObject* default_encoding = NULL; + PyObject* ascii_chars_u = NULL; + PyObject* ascii_chars_b = NULL; + const char* default_encoding_c; + sys = PyImport_ImportModule("sys"); + if (!sys) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) "getdefaultencoding", NULL); + Py_DECREF(sys); + if (!default_encoding) goto bad; + default_encoding_c = PyBytes_AsString(default_encoding); + if (!default_encoding_c) goto bad; + if (strcmp(default_encoding_c, "ascii") == 0) { + __Pyx_sys_getdefaultencoding_not_ascii = 0; + } else { + char ascii_chars[128]; + int c; + for (c = 0; c < 128; c++) { + ascii_chars[c] = (char) c; + } + __Pyx_sys_getdefaultencoding_not_ascii = 1; + ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); + if (!ascii_chars_u) goto bad; + ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); + if (!ascii_chars_b || !PyBytes_Check(ascii_chars_b) || memcmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { + PyErr_Format( + PyExc_ValueError, + "This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.", + default_encoding_c); + goto bad; + } + Py_DECREF(ascii_chars_u); + Py_DECREF(ascii_chars_b); + } + Py_DECREF(default_encoding); + return 0; +bad: + Py_XDECREF(default_encoding); + Py_XDECREF(ascii_chars_u); + Py_XDECREF(ascii_chars_b); + return -1; +} +#endif +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) +#else +#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) +#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT +#include +static char* __PYX_DEFAULT_STRING_ENCODING; +static int __Pyx_init_sys_getdefaultencoding_params(void) { + PyObject* sys; + PyObject* default_encoding = NULL; + char* default_encoding_c; + sys = PyImport_ImportModule("sys"); + if (!sys) goto bad; + default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + Py_DECREF(sys); + if (!default_encoding) goto bad; + default_encoding_c = PyBytes_AsString(default_encoding); + if (!default_encoding_c) goto bad; + __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c) + 1); + if (!__PYX_DEFAULT_STRING_ENCODING) goto bad; + strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); + Py_DECREF(default_encoding); + return 0; +bad: + Py_XDECREF(default_encoding); + return -1; +} +#endif +#endif + + +/* Test for GCC > 2.95 */ +#if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))) + #define likely(x) __builtin_expect(!!(x), 1) + #define unlikely(x) __builtin_expect(!!(x), 0) +#else /* !__GNUC__ or GCC < 2.95 */ + #define likely(x) (x) + #define unlikely(x) (x) +#endif /* __GNUC__ */ +static CYTHON_INLINE void __Pyx_pretend_to_initialize(void* ptr) { (void)ptr; } + +#if !CYTHON_USE_MODULE_STATE +static PyObject *__pyx_m = NULL; +#endif +static int __pyx_lineno; +static int __pyx_clineno = 0; +static const char * __pyx_cfilenm = __FILE__; +static const char *__pyx_filename; + +/* #### Code section: filename_table ### */ + +static const char *__pyx_f[] = { + "curated_tokenizers\\\\_wordpiece.pyx", + "", +}; +/* #### Code section: utility_code_proto_before_types ### */ +/* ForceInitThreads.proto */ +#ifndef __PYX_FORCE_INIT_THREADS + #define __PYX_FORCE_INIT_THREADS 0 +#endif + +/* #### Code section: numeric_typedefs ### */ +/* #### Code section: complex_type_declarations ### */ +/* #### Code section: type_declarations ### */ + +/*--- Type declarations ---*/ +struct __pyx_obj_18curated_tokenizers_10_wordpiece_WordPieceProcessor; +struct __pyx_t_18curated_tokenizers_10_wordpiece_PieceMatch; + +/* "curated_tokenizers/_wordpiece.pyx":5 + * from libcpp cimport pair + * + * cdef struct PieceMatch: # <<<<<<<<<<<<<< + * bint found + * int prefix_len + */ +struct __pyx_t_18curated_tokenizers_10_wordpiece_PieceMatch { + int found; + int prefix_len; + int piece_id; +}; + +/* "curated_tokenizers/_wordpiece.pyx":10 + * int piece_id + * + * cdef class WordPieceProcessor: # <<<<<<<<<<<<<< + * cdef PieceStorage _pieces + * + */ +struct __pyx_obj_18curated_tokenizers_10_wordpiece_WordPieceProcessor { + PyObject_HEAD + struct __pyx_vtabstruct_18curated_tokenizers_10_wordpiece_WordPieceProcessor *__pyx_vtab; + PieceStorage _pieces; +}; + + + +struct __pyx_vtabstruct_18curated_tokenizers_10_wordpiece_WordPieceProcessor { + struct __pyx_t_18curated_tokenizers_10_wordpiece_PieceMatch (*_find_longest_prefix)(struct __pyx_obj_18curated_tokenizers_10_wordpiece_WordPieceProcessor *, PyObject *, int); +}; +static struct __pyx_vtabstruct_18curated_tokenizers_10_wordpiece_WordPieceProcessor *__pyx_vtabptr_18curated_tokenizers_10_wordpiece_WordPieceProcessor; +/* #### Code section: utility_code_proto ### */ + +/* --- Runtime support code (head) --- */ +/* Refnanny.proto */ +#ifndef CYTHON_REFNANNY + #define CYTHON_REFNANNY 0 +#endif +#if CYTHON_REFNANNY + typedef struct { + void (*INCREF)(void*, PyObject*, Py_ssize_t); + void (*DECREF)(void*, PyObject*, Py_ssize_t); + void (*GOTREF)(void*, PyObject*, Py_ssize_t); + void (*GIVEREF)(void*, PyObject*, Py_ssize_t); + void* (*SetupContext)(const char*, Py_ssize_t, const char*); + void (*FinishContext)(void**); + } __Pyx_RefNannyAPIStruct; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); + #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; +#ifdef WITH_THREAD + #define __Pyx_RefNannySetupContext(name, acquire_gil)\ + if (acquire_gil) {\ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), (__LINE__), (__FILE__));\ + PyGILState_Release(__pyx_gilstate_save);\ + } else {\ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), (__LINE__), (__FILE__));\ + } + #define __Pyx_RefNannyFinishContextNogil() {\ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ + __Pyx_RefNannyFinishContext();\ + PyGILState_Release(__pyx_gilstate_save);\ + } +#else + #define __Pyx_RefNannySetupContext(name, acquire_gil)\ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), (__LINE__), (__FILE__)) + #define __Pyx_RefNannyFinishContextNogil() __Pyx_RefNannyFinishContext() +#endif + #define __Pyx_RefNannyFinishContextNogil() {\ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ + __Pyx_RefNannyFinishContext();\ + PyGILState_Release(__pyx_gilstate_save);\ + } + #define __Pyx_RefNannyFinishContext()\ + __Pyx_RefNanny->FinishContext(&__pyx_refnanny) + #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) + #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) + #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) + #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) + #define __Pyx_XINCREF(r) do { if((r) == NULL); else {__Pyx_INCREF(r); }} while(0) + #define __Pyx_XDECREF(r) do { if((r) == NULL); else {__Pyx_DECREF(r); }} while(0) + #define __Pyx_XGOTREF(r) do { if((r) == NULL); else {__Pyx_GOTREF(r); }} while(0) + #define __Pyx_XGIVEREF(r) do { if((r) == NULL); else {__Pyx_GIVEREF(r);}} while(0) +#else + #define __Pyx_RefNannyDeclarations + #define __Pyx_RefNannySetupContext(name, acquire_gil) + #define __Pyx_RefNannyFinishContextNogil() + #define __Pyx_RefNannyFinishContext() + #define __Pyx_INCREF(r) Py_INCREF(r) + #define __Pyx_DECREF(r) Py_DECREF(r) + #define __Pyx_GOTREF(r) + #define __Pyx_GIVEREF(r) + #define __Pyx_XINCREF(r) Py_XINCREF(r) + #define __Pyx_XDECREF(r) Py_XDECREF(r) + #define __Pyx_XGOTREF(r) + #define __Pyx_XGIVEREF(r) +#endif +#define __Pyx_Py_XDECREF_SET(r, v) do {\ + PyObject *tmp = (PyObject *) r;\ + r = v; Py_XDECREF(tmp);\ + } while (0) +#define __Pyx_XDECREF_SET(r, v) do {\ + PyObject *tmp = (PyObject *) r;\ + r = v; __Pyx_XDECREF(tmp);\ + } while (0) +#define __Pyx_DECREF_SET(r, v) do {\ + PyObject *tmp = (PyObject *) r;\ + r = v; __Pyx_DECREF(tmp);\ + } while (0) +#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) +#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) + +/* PyErrExceptionMatches.proto */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_PyErr_ExceptionMatches(err) __Pyx_PyErr_ExceptionMatchesInState(__pyx_tstate, err) +static CYTHON_INLINE int __Pyx_PyErr_ExceptionMatchesInState(PyThreadState* tstate, PyObject* err); +#else +#define __Pyx_PyErr_ExceptionMatches(err) PyErr_ExceptionMatches(err) +#endif + +/* PyThreadStateGet.proto */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_PyThreadState_declare PyThreadState *__pyx_tstate; +#define __Pyx_PyThreadState_assign __pyx_tstate = __Pyx_PyThreadState_Current; +#if PY_VERSION_HEX >= 0x030C00A6 +#define __Pyx_PyErr_Occurred() (__pyx_tstate->current_exception != NULL) +#define __Pyx_PyErr_CurrentExceptionType() (__pyx_tstate->current_exception ? (PyObject*) Py_TYPE(__pyx_tstate->current_exception) : (PyObject*) NULL) +#else +#define __Pyx_PyErr_Occurred() (__pyx_tstate->curexc_type != NULL) +#define __Pyx_PyErr_CurrentExceptionType() (__pyx_tstate->curexc_type) +#endif +#else +#define __Pyx_PyThreadState_declare +#define __Pyx_PyThreadState_assign +#define __Pyx_PyErr_Occurred() (PyErr_Occurred() != NULL) +#define __Pyx_PyErr_CurrentExceptionType() PyErr_Occurred() +#endif + +/* PyErrFetchRestore.proto */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_PyErr_Clear() __Pyx_ErrRestore(NULL, NULL, NULL) +#define __Pyx_ErrRestoreWithState(type, value, tb) __Pyx_ErrRestoreInState(PyThreadState_GET(), type, value, tb) +#define __Pyx_ErrFetchWithState(type, value, tb) __Pyx_ErrFetchInState(PyThreadState_GET(), type, value, tb) +#define __Pyx_ErrRestore(type, value, tb) __Pyx_ErrRestoreInState(__pyx_tstate, type, value, tb) +#define __Pyx_ErrFetch(type, value, tb) __Pyx_ErrFetchInState(__pyx_tstate, type, value, tb) +static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); +static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A6 +#define __Pyx_PyErr_SetNone(exc) (Py_INCREF(exc), __Pyx_ErrRestore((exc), NULL, NULL)) +#else +#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) +#endif +#else +#define __Pyx_PyErr_Clear() PyErr_Clear() +#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) +#define __Pyx_ErrRestoreWithState(type, value, tb) PyErr_Restore(type, value, tb) +#define __Pyx_ErrFetchWithState(type, value, tb) PyErr_Fetch(type, value, tb) +#define __Pyx_ErrRestoreInState(tstate, type, value, tb) PyErr_Restore(type, value, tb) +#define __Pyx_ErrFetchInState(tstate, type, value, tb) PyErr_Fetch(type, value, tb) +#define __Pyx_ErrRestore(type, value, tb) PyErr_Restore(type, value, tb) +#define __Pyx_ErrFetch(type, value, tb) PyErr_Fetch(type, value, tb) +#endif + +/* PyObjectGetAttrStr.proto */ +#if CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name); +#else +#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) +#endif + +/* PyObjectGetAttrStrNoError.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStrNoError(PyObject* obj, PyObject* attr_name); + +/* GetBuiltinName.proto */ +static PyObject *__Pyx_GetBuiltinName(PyObject *name); + +/* TupleAndListFromArray.proto */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyList_FromArray(PyObject *const *src, Py_ssize_t n); +static CYTHON_INLINE PyObject* __Pyx_PyTuple_FromArray(PyObject *const *src, Py_ssize_t n); +#endif + +/* IncludeStringH.proto */ +#include + +/* BytesEquals.proto */ +static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals); + +/* UnicodeEquals.proto */ +static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); + +/* fastcall.proto */ +#if CYTHON_AVOID_BORROWED_REFS + #define __Pyx_Arg_VARARGS(args, i) PySequence_GetItem(args, i) +#elif CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_Arg_VARARGS(args, i) PyTuple_GET_ITEM(args, i) +#else + #define __Pyx_Arg_VARARGS(args, i) PyTuple_GetItem(args, i) +#endif +#if CYTHON_AVOID_BORROWED_REFS + #define __Pyx_Arg_NewRef_VARARGS(arg) __Pyx_NewRef(arg) + #define __Pyx_Arg_XDECREF_VARARGS(arg) Py_XDECREF(arg) +#else + #define __Pyx_Arg_NewRef_VARARGS(arg) arg + #define __Pyx_Arg_XDECREF_VARARGS(arg) +#endif +#define __Pyx_NumKwargs_VARARGS(kwds) PyDict_Size(kwds) +#define __Pyx_KwValues_VARARGS(args, nargs) NULL +#define __Pyx_GetKwValue_VARARGS(kw, kwvalues, s) __Pyx_PyDict_GetItemStrWithError(kw, s) +#define __Pyx_KwargsAsDict_VARARGS(kw, kwvalues) PyDict_Copy(kw) +#if CYTHON_METH_FASTCALL + #define __Pyx_Arg_FASTCALL(args, i) args[i] + #define __Pyx_NumKwargs_FASTCALL(kwds) PyTuple_GET_SIZE(kwds) + #define __Pyx_KwValues_FASTCALL(args, nargs) ((args) + (nargs)) + static CYTHON_INLINE PyObject * __Pyx_GetKwValue_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues, PyObject *s); +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030d0000 + CYTHON_UNUSED static PyObject *__Pyx_KwargsAsDict_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues); + #else + #define __Pyx_KwargsAsDict_FASTCALL(kw, kwvalues) _PyStack_AsDict(kwvalues, kw) + #endif + #define __Pyx_Arg_NewRef_FASTCALL(arg) arg /* no-op, __Pyx_Arg_FASTCALL is direct and this needs + to have the same reference counting */ + #define __Pyx_Arg_XDECREF_FASTCALL(arg) +#else + #define __Pyx_Arg_FASTCALL __Pyx_Arg_VARARGS + #define __Pyx_NumKwargs_FASTCALL __Pyx_NumKwargs_VARARGS + #define __Pyx_KwValues_FASTCALL __Pyx_KwValues_VARARGS + #define __Pyx_GetKwValue_FASTCALL __Pyx_GetKwValue_VARARGS + #define __Pyx_KwargsAsDict_FASTCALL __Pyx_KwargsAsDict_VARARGS + #define __Pyx_Arg_NewRef_FASTCALL(arg) __Pyx_Arg_NewRef_VARARGS(arg) + #define __Pyx_Arg_XDECREF_FASTCALL(arg) __Pyx_Arg_XDECREF_VARARGS(arg) +#endif +#if CYTHON_COMPILING_IN_CPYTHON && CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS +#define __Pyx_ArgsSlice_VARARGS(args, start, stop) __Pyx_PyTuple_FromArray(&__Pyx_Arg_VARARGS(args, start), stop - start) +#define __Pyx_ArgsSlice_FASTCALL(args, start, stop) __Pyx_PyTuple_FromArray(&__Pyx_Arg_FASTCALL(args, start), stop - start) +#else +#define __Pyx_ArgsSlice_VARARGS(args, start, stop) PyTuple_GetSlice(args, start, stop) +#define __Pyx_ArgsSlice_FASTCALL(args, start, stop) PyTuple_GetSlice(args, start, stop) +#endif + +/* RaiseDoubleKeywords.proto */ +static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); + +/* ParseKeywords.proto */ +static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject *const *kwvalues, + PyObject **argnames[], + PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, + const char* function_name); + +/* RaiseArgTupleInvalid.proto */ +static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, + Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); + +/* PyIntBinop.proto */ +#if !CYTHON_COMPILING_IN_PYPY +static PyObject* __Pyx_PyInt_AddObjC(PyObject *op1, PyObject *op2, long intval, int inplace, int zerodivision_check); +#else +#define __Pyx_PyInt_AddObjC(op1, op2, intval, inplace, zerodivision_check)\ + (inplace ? PyNumber_InPlaceAdd(op1, op2) : PyNumber_Add(op1, op2)) +#endif + +/* PyFunctionFastCall.proto */ +#if CYTHON_FAST_PYCALL +#if !CYTHON_VECTORCALL +#define __Pyx_PyFunction_FastCall(func, args, nargs)\ + __Pyx_PyFunction_FastCallDict((func), (args), (nargs), NULL) +static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, Py_ssize_t nargs, PyObject *kwargs); +#endif +#define __Pyx_BUILD_ASSERT_EXPR(cond)\ + (sizeof(char [1 - 2*!(cond)]) - 1) +#ifndef Py_MEMBER_SIZE +#define Py_MEMBER_SIZE(type, member) sizeof(((type *)0)->member) +#endif +#if !CYTHON_VECTORCALL +#if PY_VERSION_HEX >= 0x03080000 + #include "frameobject.h" +#if PY_VERSION_HEX >= 0x030b00a6 && !CYTHON_COMPILING_IN_LIMITED_API + #ifndef Py_BUILD_CORE + #define Py_BUILD_CORE 1 + #endif + #include "internal/pycore_frame.h" +#endif + #define __Pxy_PyFrame_Initialize_Offsets() + #define __Pyx_PyFrame_GetLocalsplus(frame) ((frame)->f_localsplus) +#else + static size_t __pyx_pyframe_localsplus_offset = 0; + #include "frameobject.h" + #define __Pxy_PyFrame_Initialize_Offsets()\ + ((void)__Pyx_BUILD_ASSERT_EXPR(sizeof(PyFrameObject) == offsetof(PyFrameObject, f_localsplus) + Py_MEMBER_SIZE(PyFrameObject, f_localsplus)),\ + (void)(__pyx_pyframe_localsplus_offset = ((size_t)PyFrame_Type.tp_basicsize) - Py_MEMBER_SIZE(PyFrameObject, f_localsplus))) + #define __Pyx_PyFrame_GetLocalsplus(frame)\ + (assert(__pyx_pyframe_localsplus_offset), (PyObject **)(((char *)(frame)) + __pyx_pyframe_localsplus_offset)) +#endif +#endif +#endif + +/* PyObjectCall.proto */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); +#else +#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) +#endif + +/* PyObjectCallMethO.proto */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg); +#endif + +/* PyObjectFastCall.proto */ +#define __Pyx_PyObject_FastCall(func, args, nargs) __Pyx_PyObject_FastCallDict(func, args, (size_t)(nargs), NULL) +static CYTHON_INLINE PyObject* __Pyx_PyObject_FastCallDict(PyObject *func, PyObject **args, size_t nargs, PyObject *kwargs); + +/* SliceObject.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetSlice( + PyObject* obj, Py_ssize_t cstart, Py_ssize_t cstop, + PyObject** py_start, PyObject** py_stop, PyObject** py_slice, + int has_cstart, int has_cstop, int wraparound); + +/* KeywordStringCheck.proto */ +static int __Pyx_CheckKeywordStrings(PyObject *kw, const char* function_name, int kw_allowed); + +/* PyObjectCallOneArg.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg); + +/* RaiseUnexpectedTypeError.proto */ +static int __Pyx_RaiseUnexpectedTypeError(const char *expected, PyObject *obj); + +/* ListAppend.proto */ +#if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS +static CYTHON_INLINE int __Pyx_PyList_Append(PyObject* list, PyObject* x) { + PyListObject* L = (PyListObject*) list; + Py_ssize_t len = Py_SIZE(list); + if (likely(L->allocated > len) & likely(len > (L->allocated >> 1))) { + Py_INCREF(x); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030d0000 + L->ob_item[len] = x; + #else + PyList_SET_ITEM(list, len, x); + #endif + __Pyx_SET_SIZE(list, len + 1); + return 0; + } + return PyList_Append(list, x); +} +#else +#define __Pyx_PyList_Append(L,x) PyList_Append(L,x) +#endif + +/* PyObjectFormatSimple.proto */ +#if CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyObject_FormatSimple(s, f) (\ + likely(PyUnicode_CheckExact(s)) ? (Py_INCREF(s), s) :\ + PyObject_Format(s, f)) +#elif PY_MAJOR_VERSION < 3 + #define __Pyx_PyObject_FormatSimple(s, f) (\ + likely(PyUnicode_CheckExact(s)) ? (Py_INCREF(s), s) :\ + likely(PyString_CheckExact(s)) ? PyUnicode_FromEncodedObject(s, NULL, "strict") :\ + PyObject_Format(s, f)) +#elif CYTHON_USE_TYPE_SLOTS + #define __Pyx_PyObject_FormatSimple(s, f) (\ + likely(PyUnicode_CheckExact(s)) ? (Py_INCREF(s), s) :\ + likely(PyLong_CheckExact(s)) ? PyLong_Type.tp_repr(s) :\ + likely(PyFloat_CheckExact(s)) ? PyFloat_Type.tp_repr(s) :\ + PyObject_Format(s, f)) +#else + #define __Pyx_PyObject_FormatSimple(s, f) (\ + likely(PyUnicode_CheckExact(s)) ? (Py_INCREF(s), s) :\ + PyObject_Format(s, f)) +#endif + +/* UnicodeConcatInPlace.proto */ +# if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 + #if CYTHON_REFNANNY + #define __Pyx_PyUnicode_ConcatInPlace(left, right) __Pyx_PyUnicode_ConcatInPlaceImpl(&left, right, __pyx_refnanny) + #else + #define __Pyx_PyUnicode_ConcatInPlace(left, right) __Pyx_PyUnicode_ConcatInPlaceImpl(&left, right) + #endif + static CYTHON_INLINE PyObject *__Pyx_PyUnicode_ConcatInPlaceImpl(PyObject **p_left, PyObject *right + #if CYTHON_REFNANNY + , void* __pyx_refnanny + #endif + ); +#else +#define __Pyx_PyUnicode_ConcatInPlace __Pyx_PyUnicode_Concat +#endif +#define __Pyx_PyUnicode_ConcatInPlaceSafe(left, right) ((unlikely((left) == Py_None) || unlikely((right) == Py_None)) ?\ + PyNumber_InPlaceAdd(left, right) : __Pyx_PyUnicode_ConcatInPlace(left, right)) + +/* ListCompAppend.proto */ +#if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS +static CYTHON_INLINE int __Pyx_ListComp_Append(PyObject* list, PyObject* x) { + PyListObject* L = (PyListObject*) list; + Py_ssize_t len = Py_SIZE(list); + if (likely(L->allocated > len)) { + Py_INCREF(x); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030d0000 + L->ob_item[len] = x; + #else + PyList_SET_ITEM(list, len, x); + #endif + __Pyx_SET_SIZE(list, len + 1); + return 0; + } + return PyList_Append(list, x); +} +#else +#define __Pyx_ListComp_Append(L,x) PyList_Append(L,x) +#endif + +/* GetItemInt.proto */ +#define __Pyx_GetItemInt(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ + __Pyx_GetItemInt_Fast(o, (Py_ssize_t)i, is_list, wraparound, boundscheck) :\ + (is_list ? (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL) :\ + __Pyx_GetItemInt_Generic(o, to_py_func(i)))) +#define __Pyx_GetItemInt_List(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ + __Pyx_GetItemInt_List_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) :\ + (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck); +#define __Pyx_GetItemInt_Tuple(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ + __Pyx_GetItemInt_Tuple_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) :\ + (PyErr_SetString(PyExc_IndexError, "tuple index out of range"), (PyObject*)NULL)) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck); +static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j); +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, + int is_list, int wraparound, int boundscheck); + +/* PyObjectCall2Args.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2); + +/* PyObjectGetMethod.proto */ +static int __Pyx_PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method); + +/* PyObjectCallMethod1.proto */ +static PyObject* __Pyx_PyObject_CallMethod1(PyObject* obj, PyObject* method_name, PyObject* arg); + +/* StringJoin.proto */ +#if PY_MAJOR_VERSION < 3 +#define __Pyx_PyString_Join __Pyx_PyBytes_Join +#define __Pyx_PyBaseString_Join(s, v) (PyUnicode_CheckExact(s) ? PyUnicode_Join(s, v) : __Pyx_PyBytes_Join(s, v)) +#else +#define __Pyx_PyString_Join PyUnicode_Join +#define __Pyx_PyBaseString_Join PyUnicode_Join +#endif +static CYTHON_INLINE PyObject* __Pyx_PyBytes_Join(PyObject* sep, PyObject* values); + +/* IncludeCppStringH.proto */ +#include + +/* decode_c_string_utf16.proto */ +static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16(const char *s, Py_ssize_t size, const char *errors) { + int byteorder = 0; + return PyUnicode_DecodeUTF16(s, size, errors, &byteorder); +} +static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16LE(const char *s, Py_ssize_t size, const char *errors) { + int byteorder = -1; + return PyUnicode_DecodeUTF16(s, size, errors, &byteorder); +} +static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16BE(const char *s, Py_ssize_t size, const char *errors) { + int byteorder = 1; + return PyUnicode_DecodeUTF16(s, size, errors, &byteorder); +} + +/* decode_c_bytes.proto */ +static CYTHON_INLINE PyObject* __Pyx_decode_c_bytes( + const char* cstring, Py_ssize_t length, Py_ssize_t start, Py_ssize_t stop, + const char* encoding, const char* errors, + PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)); + +/* decode_cpp_string.proto */ +static CYTHON_INLINE PyObject* __Pyx_decode_cpp_string( + std::string cppstring, Py_ssize_t start, Py_ssize_t stop, + const char* encoding, const char* errors, + PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) { + return __Pyx_decode_c_bytes( + cppstring.data(), cppstring.size(), start, stop, encoding, errors, decode_func); +} + +/* PyObjectLookupSpecial.proto */ +#if CYTHON_USE_PYTYPE_LOOKUP && CYTHON_USE_TYPE_SLOTS +#define __Pyx_PyObject_LookupSpecialNoError(obj, attr_name) __Pyx__PyObject_LookupSpecial(obj, attr_name, 0) +#define __Pyx_PyObject_LookupSpecial(obj, attr_name) __Pyx__PyObject_LookupSpecial(obj, attr_name, 1) +static CYTHON_INLINE PyObject* __Pyx__PyObject_LookupSpecial(PyObject* obj, PyObject* attr_name, int with_error); +#else +#define __Pyx_PyObject_LookupSpecialNoError(o,n) __Pyx_PyObject_GetAttrStrNoError(o,n) +#define __Pyx_PyObject_LookupSpecial(o,n) __Pyx_PyObject_GetAttrStr(o,n) +#endif + +/* GetTopmostException.proto */ +#if CYTHON_USE_EXC_INFO_STACK && CYTHON_FAST_THREAD_STATE +static _PyErr_StackItem * __Pyx_PyErr_GetTopmostException(PyThreadState *tstate); +#endif + +/* SaveResetException.proto */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_ExceptionSave(type, value, tb) __Pyx__ExceptionSave(__pyx_tstate, type, value, tb) +static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); +#define __Pyx_ExceptionReset(type, value, tb) __Pyx__ExceptionReset(__pyx_tstate, type, value, tb) +static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); +#else +#define __Pyx_ExceptionSave(type, value, tb) PyErr_GetExcInfo(type, value, tb) +#define __Pyx_ExceptionReset(type, value, tb) PyErr_SetExcInfo(type, value, tb) +#endif + +/* GetException.proto */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_GetException(type, value, tb) __Pyx__GetException(__pyx_tstate, type, value, tb) +static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); +#else +static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); +#endif + +/* RaiseUnboundLocalError.proto */ +static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname); + +/* SetItemInt.proto */ +#define __Pyx_SetItemInt(o, i, v, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ + __Pyx_SetItemInt_Fast(o, (Py_ssize_t)i, v, is_list, wraparound, boundscheck) :\ + (is_list ? (PyErr_SetString(PyExc_IndexError, "list assignment index out of range"), -1) :\ + __Pyx_SetItemInt_Generic(o, to_py_func(i), v))) +static int __Pyx_SetItemInt_Generic(PyObject *o, PyObject *j, PyObject *v); +static CYTHON_INLINE int __Pyx_SetItemInt_Fast(PyObject *o, Py_ssize_t i, PyObject *v, + int is_list, int wraparound, int boundscheck); + +/* PyDictVersioning.proto */ +#if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS +#define __PYX_DICT_VERSION_INIT ((PY_UINT64_T) -1) +#define __PYX_GET_DICT_VERSION(dict) (((PyDictObject*)(dict))->ma_version_tag) +#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var)\ + (version_var) = __PYX_GET_DICT_VERSION(dict);\ + (cache_var) = (value); +#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) {\ + static PY_UINT64_T __pyx_dict_version = 0;\ + static PyObject *__pyx_dict_cached_value = NULL;\ + if (likely(__PYX_GET_DICT_VERSION(DICT) == __pyx_dict_version)) {\ + (VAR) = __pyx_dict_cached_value;\ + } else {\ + (VAR) = __pyx_dict_cached_value = (LOOKUP);\ + __pyx_dict_version = __PYX_GET_DICT_VERSION(DICT);\ + }\ +} +static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj); +static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj); +static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version); +#else +#define __PYX_GET_DICT_VERSION(dict) (0) +#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var) +#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) (VAR) = (LOOKUP); +#endif + +/* GetModuleGlobalName.proto */ +#if CYTHON_USE_DICT_VERSIONS +#define __Pyx_GetModuleGlobalName(var, name) do {\ + static PY_UINT64_T __pyx_dict_version = 0;\ + static PyObject *__pyx_dict_cached_value = NULL;\ + (var) = (likely(__pyx_dict_version == __PYX_GET_DICT_VERSION(__pyx_d))) ?\ + (likely(__pyx_dict_cached_value) ? __Pyx_NewRef(__pyx_dict_cached_value) : __Pyx_GetBuiltinName(name)) :\ + __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ +} while(0) +#define __Pyx_GetModuleGlobalNameUncached(var, name) do {\ + PY_UINT64_T __pyx_dict_version;\ + PyObject *__pyx_dict_cached_value;\ + (var) = __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ +} while(0) +static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value); +#else +#define __Pyx_GetModuleGlobalName(var, name) (var) = __Pyx__GetModuleGlobalName(name) +#define __Pyx_GetModuleGlobalNameUncached(var, name) (var) = __Pyx__GetModuleGlobalName(name) +static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name); +#endif + +/* IncludeStructmemberH.proto */ +#include + +/* FixUpExtensionType.proto */ +#if CYTHON_USE_TYPE_SPECS +static int __Pyx_fix_up_extension_type_from_spec(PyType_Spec *spec, PyTypeObject *type); +#endif + +/* PyObjectCallNoArg.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func); + +/* PyObjectCallMethod0.proto */ +static PyObject* __Pyx_PyObject_CallMethod0(PyObject* obj, PyObject* method_name); + +/* ValidateBasesTuple.proto */ +#if CYTHON_COMPILING_IN_CPYTHON || CYTHON_COMPILING_IN_LIMITED_API || CYTHON_USE_TYPE_SPECS +static int __Pyx_validate_bases_tuple(const char *type_name, Py_ssize_t dictoffset, PyObject *bases); +#endif + +/* PyType_Ready.proto */ +CYTHON_UNUSED static int __Pyx_PyType_Ready(PyTypeObject *t); + +/* PyObject_GenericGetAttrNoDict.proto */ +#if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 +static CYTHON_INLINE PyObject* __Pyx_PyObject_GenericGetAttrNoDict(PyObject* obj, PyObject* attr_name); +#else +#define __Pyx_PyObject_GenericGetAttrNoDict PyObject_GenericGetAttr +#endif + +/* PyObject_GenericGetAttr.proto */ +#if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 +static PyObject* __Pyx_PyObject_GenericGetAttr(PyObject* obj, PyObject* attr_name); +#else +#define __Pyx_PyObject_GenericGetAttr PyObject_GenericGetAttr +#endif + +/* SetVTable.proto */ +static int __Pyx_SetVtable(PyTypeObject* typeptr , void* vtable); + +/* GetVTable.proto */ +static void* __Pyx_GetVtable(PyTypeObject *type); + +/* MergeVTables.proto */ +#if !CYTHON_COMPILING_IN_LIMITED_API +static int __Pyx_MergeVtables(PyTypeObject *type); +#endif + +/* Import.proto */ +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); + +/* ImportFrom.proto */ +static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name); + +/* FetchSharedCythonModule.proto */ +static PyObject *__Pyx_FetchSharedCythonABIModule(void); + +/* FetchCommonType.proto */ +#if !CYTHON_USE_TYPE_SPECS +static PyTypeObject* __Pyx_FetchCommonType(PyTypeObject* type); +#else +static PyTypeObject* __Pyx_FetchCommonTypeFromSpec(PyObject *module, PyType_Spec *spec, PyObject *bases); +#endif + +/* PyMethodNew.proto */ +#if CYTHON_COMPILING_IN_LIMITED_API +static PyObject *__Pyx_PyMethod_New(PyObject *func, PyObject *self, PyObject *typ) { + PyObject *typesModule=NULL, *methodType=NULL, *result=NULL; + CYTHON_UNUSED_VAR(typ); + if (!self) + return __Pyx_NewRef(func); + typesModule = PyImport_ImportModule("types"); + if (!typesModule) return NULL; + methodType = PyObject_GetAttrString(typesModule, "MethodType"); + Py_DECREF(typesModule); + if (!methodType) return NULL; + result = PyObject_CallFunctionObjArgs(methodType, func, self, NULL); + Py_DECREF(methodType); + return result; +} +#elif PY_MAJOR_VERSION >= 3 +static PyObject *__Pyx_PyMethod_New(PyObject *func, PyObject *self, PyObject *typ) { + CYTHON_UNUSED_VAR(typ); + if (!self) + return __Pyx_NewRef(func); + return PyMethod_New(func, self); +} +#else + #define __Pyx_PyMethod_New PyMethod_New +#endif + +/* PyVectorcallFastCallDict.proto */ +#if CYTHON_METH_FASTCALL +static CYTHON_INLINE PyObject *__Pyx_PyVectorcall_FastCallDict(PyObject *func, __pyx_vectorcallfunc vc, PyObject *const *args, size_t nargs, PyObject *kw); +#endif + +/* CythonFunctionShared.proto */ +#define __Pyx_CyFunction_USED +#define __Pyx_CYFUNCTION_STATICMETHOD 0x01 +#define __Pyx_CYFUNCTION_CLASSMETHOD 0x02 +#define __Pyx_CYFUNCTION_CCLASS 0x04 +#define __Pyx_CYFUNCTION_COROUTINE 0x08 +#define __Pyx_CyFunction_GetClosure(f)\ + (((__pyx_CyFunctionObject *) (f))->func_closure) +#if PY_VERSION_HEX < 0x030900B1 || CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_CyFunction_GetClassObj(f)\ + (((__pyx_CyFunctionObject *) (f))->func_classobj) +#else + #define __Pyx_CyFunction_GetClassObj(f)\ + ((PyObject*) ((PyCMethodObject *) (f))->mm_class) +#endif +#define __Pyx_CyFunction_SetClassObj(f, classobj)\ + __Pyx__CyFunction_SetClassObj((__pyx_CyFunctionObject *) (f), (classobj)) +#define __Pyx_CyFunction_Defaults(type, f)\ + ((type *)(((__pyx_CyFunctionObject *) (f))->defaults)) +#define __Pyx_CyFunction_SetDefaultsGetter(f, g)\ + ((__pyx_CyFunctionObject *) (f))->defaults_getter = (g) +typedef struct { +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject_HEAD + PyObject *func; +#elif PY_VERSION_HEX < 0x030900B1 + PyCFunctionObject func; +#else + PyCMethodObject func; +#endif +#if CYTHON_BACKPORT_VECTORCALL + __pyx_vectorcallfunc func_vectorcall; +#endif +#if PY_VERSION_HEX < 0x030500A0 || CYTHON_COMPILING_IN_LIMITED_API + PyObject *func_weakreflist; +#endif + PyObject *func_dict; + PyObject *func_name; + PyObject *func_qualname; + PyObject *func_doc; + PyObject *func_globals; + PyObject *func_code; + PyObject *func_closure; +#if PY_VERSION_HEX < 0x030900B1 || CYTHON_COMPILING_IN_LIMITED_API + PyObject *func_classobj; +#endif + void *defaults; + int defaults_pyobjects; + size_t defaults_size; + int flags; + PyObject *defaults_tuple; + PyObject *defaults_kwdict; + PyObject *(*defaults_getter)(PyObject *); + PyObject *func_annotations; + PyObject *func_is_coroutine; +} __pyx_CyFunctionObject; +#undef __Pyx_CyOrPyCFunction_Check +#define __Pyx_CyFunction_Check(obj) __Pyx_TypeCheck(obj, __pyx_CyFunctionType) +#define __Pyx_CyOrPyCFunction_Check(obj) __Pyx_TypeCheck2(obj, __pyx_CyFunctionType, &PyCFunction_Type) +#define __Pyx_CyFunction_CheckExact(obj) __Pyx_IS_TYPE(obj, __pyx_CyFunctionType) +static CYTHON_INLINE int __Pyx__IsSameCyOrCFunction(PyObject *func, void *cfunc); +#undef __Pyx_IsSameCFunction +#define __Pyx_IsSameCFunction(func, cfunc) __Pyx__IsSameCyOrCFunction(func, cfunc) +static PyObject *__Pyx_CyFunction_Init(__pyx_CyFunctionObject* op, PyMethodDef *ml, + int flags, PyObject* qualname, + PyObject *closure, + PyObject *module, PyObject *globals, + PyObject* code); +static CYTHON_INLINE void __Pyx__CyFunction_SetClassObj(__pyx_CyFunctionObject* f, PyObject* classobj); +static CYTHON_INLINE void *__Pyx_CyFunction_InitDefaults(PyObject *m, + size_t size, + int pyobjects); +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsTuple(PyObject *m, + PyObject *tuple); +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsKwDict(PyObject *m, + PyObject *dict); +static CYTHON_INLINE void __Pyx_CyFunction_SetAnnotationsDict(PyObject *m, + PyObject *dict); +static int __pyx_CyFunction_init(PyObject *module); +#if CYTHON_METH_FASTCALL +static PyObject * __Pyx_CyFunction_Vectorcall_NOARGS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); +static PyObject * __Pyx_CyFunction_Vectorcall_O(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); +static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); +static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS_METHOD(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); +#if CYTHON_BACKPORT_VECTORCALL +#define __Pyx_CyFunction_func_vectorcall(f) (((__pyx_CyFunctionObject*)f)->func_vectorcall) +#else +#define __Pyx_CyFunction_func_vectorcall(f) (((PyCFunctionObject*)f)->vectorcall) +#endif +#endif + +/* CythonFunction.proto */ +static PyObject *__Pyx_CyFunction_New(PyMethodDef *ml, + int flags, PyObject* qualname, + PyObject *closure, + PyObject *module, PyObject *globals, + PyObject* code); + +/* GetNameInClass.proto */ +#define __Pyx_GetNameInClass(var, nmspace, name) (var) = __Pyx__GetNameInClass(nmspace, name) +static PyObject *__Pyx__GetNameInClass(PyObject *nmspace, PyObject *name); + +/* CLineInTraceback.proto */ +#ifdef CYTHON_CLINE_IN_TRACEBACK +#define __Pyx_CLineForTraceback(tstate, c_line) (((CYTHON_CLINE_IN_TRACEBACK)) ? c_line : 0) +#else +static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line); +#endif + +/* CodeObjectCache.proto */ +#if !CYTHON_COMPILING_IN_LIMITED_API +typedef struct { + PyCodeObject* code_object; + int code_line; +} __Pyx_CodeObjectCacheEntry; +struct __Pyx_CodeObjectCache { + int count; + int max_count; + __Pyx_CodeObjectCacheEntry* entries; +}; +static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); +static PyCodeObject *__pyx_find_code_object(int code_line); +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); +#endif + +/* AddTraceback.proto */ +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename); + +/* None.proto */ +#include + +/* GCCDiagnostics.proto */ +#if !defined(__INTEL_COMPILER) && defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) +#define __Pyx_HAS_GCC_DIAGNOSTIC +#endif + +/* CppExceptionConversion.proto */ +#ifndef __Pyx_CppExn2PyErr +#include +#include +#include +#include +static void __Pyx_CppExn2PyErr() { + try { + if (PyErr_Occurred()) + ; // let the latest Python exn pass through and ignore the current one + else + throw; + } catch (const std::bad_alloc& exn) { + PyErr_SetString(PyExc_MemoryError, exn.what()); + } catch (const std::bad_cast& exn) { + PyErr_SetString(PyExc_TypeError, exn.what()); + } catch (const std::bad_typeid& exn) { + PyErr_SetString(PyExc_TypeError, exn.what()); + } catch (const std::domain_error& exn) { + PyErr_SetString(PyExc_ValueError, exn.what()); + } catch (const std::invalid_argument& exn) { + PyErr_SetString(PyExc_ValueError, exn.what()); + } catch (const std::ios_base::failure& exn) { + PyErr_SetString(PyExc_IOError, exn.what()); + } catch (const std::out_of_range& exn) { + PyErr_SetString(PyExc_IndexError, exn.what()); + } catch (const std::overflow_error& exn) { + PyErr_SetString(PyExc_OverflowError, exn.what()); + } catch (const std::range_error& exn) { + PyErr_SetString(PyExc_ArithmeticError, exn.what()); + } catch (const std::underflow_error& exn) { + PyErr_SetString(PyExc_ArithmeticError, exn.what()); + } catch (const std::exception& exn) { + PyErr_SetString(PyExc_RuntimeError, exn.what()); + } + catch (...) + { + PyErr_SetString(PyExc_RuntimeError, "Unknown exception"); + } +} +#endif + +/* CIntToPy.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value); + +/* CIntToPy.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); + +/* CIntFromPy.proto */ +static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); + +/* CIntFromPy.proto */ +static CYTHON_INLINE size_t __Pyx_PyInt_As_size_t(PyObject *); + +/* FormatTypeName.proto */ +#if CYTHON_COMPILING_IN_LIMITED_API +typedef PyObject *__Pyx_TypeName; +#define __Pyx_FMT_TYPENAME "%U" +static __Pyx_TypeName __Pyx_PyType_GetName(PyTypeObject* tp); +#define __Pyx_DECREF_TypeName(obj) Py_XDECREF(obj) +#else +typedef const char *__Pyx_TypeName; +#define __Pyx_FMT_TYPENAME "%.200s" +#define __Pyx_PyType_GetName(tp) ((tp)->tp_name) +#define __Pyx_DECREF_TypeName(obj) +#endif + +/* CIntFromPy.proto */ +static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); + +/* FastTypeChecks.proto */ +#if CYTHON_COMPILING_IN_CPYTHON +#define __Pyx_TypeCheck(obj, type) __Pyx_IsSubtype(Py_TYPE(obj), (PyTypeObject *)type) +#define __Pyx_TypeCheck2(obj, type1, type2) __Pyx_IsAnySubtype2(Py_TYPE(obj), (PyTypeObject *)type1, (PyTypeObject *)type2) +static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b); +static CYTHON_INLINE int __Pyx_IsAnySubtype2(PyTypeObject *cls, PyTypeObject *a, PyTypeObject *b); +static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches(PyObject *err, PyObject *type); +static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *type1, PyObject *type2); +#else +#define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) +#define __Pyx_TypeCheck2(obj, type1, type2) (PyObject_TypeCheck(obj, (PyTypeObject *)type1) || PyObject_TypeCheck(obj, (PyTypeObject *)type2)) +#define __Pyx_PyErr_GivenExceptionMatches(err, type) PyErr_GivenExceptionMatches(err, type) +#define __Pyx_PyErr_GivenExceptionMatches2(err, type1, type2) (PyErr_GivenExceptionMatches(err, type1) || PyErr_GivenExceptionMatches(err, type2)) +#endif +#define __Pyx_PyErr_ExceptionMatches2(err1, err2) __Pyx_PyErr_GivenExceptionMatches2(__Pyx_PyErr_CurrentExceptionType(), err1, err2) +#define __Pyx_PyException_Check(obj) __Pyx_TypeCheck(obj, PyExc_Exception) + +/* CheckBinaryVersion.proto */ +static unsigned long __Pyx_get_runtime_version(void); +static int __Pyx_check_binary_version(unsigned long ct_version, unsigned long rt_version, int allow_newer); + +/* InitStrings.proto */ +static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); + +/* #### Code section: module_declarations ### */ +static struct __pyx_t_18curated_tokenizers_10_wordpiece_PieceMatch __pyx_f_18curated_tokenizers_10_wordpiece_18WordPieceProcessor__find_longest_prefix(struct __pyx_obj_18curated_tokenizers_10_wordpiece_WordPieceProcessor *__pyx_v_self, PyObject *__pyx_v_token, int __pyx_v_is_initial); /* proto*/ + +/* Module declarations from "libc.string" */ + +/* Module declarations from "libcpp.string" */ + +/* Module declarations from "libcpp.utility" */ + +/* Module declarations from "libcpp.unordered_map" */ + +/* Module declarations from "libcpp.vector" */ + +/* Module declarations from "libcpp" */ + +/* Module declarations from "libcpp.pair" */ + +/* Module declarations from "curated_tokenizers._wordpiece" */ +static std::string __pyx_convert_string_from_py_std__in_string(PyObject *); /*proto*/ +static CYTHON_INLINE PyObject *__pyx_convert_PyObject_string_to_py_std__in_string(std::string const &); /*proto*/ +static CYTHON_INLINE PyObject *__pyx_convert_PyUnicode_string_to_py_std__in_string(std::string const &); /*proto*/ +static CYTHON_INLINE PyObject *__pyx_convert_PyStr_string_to_py_std__in_string(std::string const &); /*proto*/ +static CYTHON_INLINE PyObject *__pyx_convert_PyBytes_string_to_py_std__in_string(std::string const &); /*proto*/ +static CYTHON_INLINE PyObject *__pyx_convert_PyByteArray_string_to_py_std__in_string(std::string const &); /*proto*/ +/* #### Code section: typeinfo ### */ +/* #### Code section: before_global_var ### */ +#define __Pyx_MODULE_NAME "curated_tokenizers._wordpiece" +extern int __pyx_module_is_main_curated_tokenizers___wordpiece; +int __pyx_module_is_main_curated_tokenizers___wordpiece = 0; + +/* Implementation of "curated_tokenizers._wordpiece" */ +/* #### Code section: global_var ### */ +static PyObject *__pyx_builtin_staticmethod; +static PyObject *__pyx_builtin_enumerate; +static PyObject *__pyx_builtin_open; +static PyObject *__pyx_builtin_range; +static PyObject *__pyx_builtin_reversed; +/* #### Code section: string_decls ### */ +static const char __pyx_k_[] = "##"; +static const char __pyx_k_f[] = "f"; +static const char __pyx_k_i[] = "i"; +static const char __pyx_k__3[] = ""; +static const char __pyx_k__5[] = "."; +static const char __pyx_k_gc[] = "gc"; +static const char __pyx_k_id[] = "id"; +static const char __pyx_k__26[] = "?"; +static const char __pyx_k_int[] = "int"; +static const char __pyx_k_str[] = "str"; +static const char __pyx_k_List[] = "List"; +static const char __pyx_k_bool[] = "bool"; +static const char __pyx_k_copy[] = "__copy__"; +static const char __pyx_k_dict[] = "__dict__"; +static const char __pyx_k_exit[] = "__exit__"; +static const char __pyx_k_join[] = "join"; +static const char __pyx_k_line[] = "line"; +static const char __pyx_k_main[] = "__main__"; +static const char __pyx_k_memo[] = "memo"; +static const char __pyx_k_name[] = "__name__"; +static const char __pyx_k_open[] = "open"; +static const char __pyx_k_self[] = "self"; +static const char __pyx_k_test[] = "__test__"; +static const char __pyx_k_utf8[] = "utf8"; +static const char __pyx_k_Tuple[] = "Tuple"; +static const char __pyx_k_enter[] = "__enter__"; +static const char __pyx_k_match[] = "match"; +static const char __pyx_k_piece[] = "piece"; +static const char __pyx_k_range[] = "range"; +static const char __pyx_k_strip[] = "strip"; +static const char __pyx_k_token[] = "token"; +static const char __pyx_k_decode[] = "decode"; +static const char __pyx_k_enable[] = "enable"; +static const char __pyx_k_encode[] = "encode"; +static const char __pyx_k_import[] = "__import__"; +static const char __pyx_k_pieces[] = "pieces"; +static const char __pyx_k_prefix[] = "prefix"; +static const char __pyx_k_reduce[] = "__reduce__"; +static const char __pyx_k_return[] = "return"; +static const char __pyx_k_typing[] = "typing"; +static const char __pyx_k_disable[] = "disable"; +static const char __pyx_k_to_list[] = "to_list"; +static const char __pyx_k_Iterable[] = "Iterable"; +static const char __pyx_k_List_str[] = "List[str]"; +static const char __pyx_k_deepcopy[] = "__deepcopy__"; +static const char __pyx_k_encoding[] = "encoding"; +static const char __pyx_k_filename[] = "filename"; +static const char __pyx_k_reversed[] = "reversed"; +static const char __pyx_k_enumerate[] = "enumerate"; +static const char __pyx_k_from_file[] = "from_file"; +static const char __pyx_k_isenabled[] = "isenabled"; +static const char __pyx_k_ptr_piece[] = "ptr_piece"; +static const char __pyx_k_token_ids[] = "token_ids"; +static const char __pyx_k_is_initial[] = "is_initial"; +static const char __pyx_k_pyx_vtable[] = "__pyx_vtable__"; +static const char __pyx_k_startswith[] = "startswith"; +static const char __pyx_k_get_initial[] = "get_initial"; +static const char __pyx_k_id_to_piece[] = "id_to_piece"; +static const char __pyx_k_Iterable_int[] = "Iterable[int]"; +static const char __pyx_k_is_coroutine[] = "_is_coroutine"; +static const char __pyx_k_staticmethod[] = "staticmethod"; +static const char __pyx_k_token_pieces[] = "token_pieces"; +static const char __pyx_k_Tuple_str_bool[] = "Tuple[str, bool]"; +static const char __pyx_k_is_valid_piece_id[] = "is_valid_piece_id"; +static const char __pyx_k_WordPieceProcessor[] = "WordPieceProcessor"; +static const char __pyx_k_asyncio_coroutines[] = "asyncio.coroutines"; +static const char __pyx_k_cline_in_traceback[] = "cline_in_traceback"; +static const char __pyx_k_Tuple_List_int_List_str[] = "Tuple[List[int], List[str]]"; +static const char __pyx_k_WordPieceProcessor___copy[] = "WordPieceProcessor.__copy__"; +static const char __pyx_k_WordPieceProcessor_decode[] = "WordPieceProcessor.decode"; +static const char __pyx_k_WordPieceProcessor_encode[] = "WordPieceProcessor.encode"; +static const char __pyx_k_WordPieceProcessor_to_list[] = "WordPieceProcessor.to_list"; +static const char __pyx_k_WordPieceProcessor___reduce[] = "WordPieceProcessor.__reduce__"; +static const char __pyx_k_WordPieceProcessor_from_file[] = "WordPieceProcessor.from_file"; +static const char __pyx_k_unpickle_wordpiece_processor[] = "unpickle_wordpiece_processor"; +static const char __pyx_k_WordPieceProcessor___deepcopy[] = "WordPieceProcessor.__deepcopy__"; +static const char __pyx_k_curated_tokenizers__wordpiece[] = "curated_tokenizers._wordpiece"; +static const char __pyx_k_WordPieceProcessor_get_initial[] = "WordPieceProcessor.get_initial"; +static const char __pyx_k_WordPieceProcessor_id_to_piece[] = "WordPieceProcessor.id_to_piece"; +static const char __pyx_k_WordPieceProcessor_is_valid_piec[] = "WordPieceProcessor.is_valid_piece_id"; +static const char __pyx_k_curated_tokenizers__wordpiece_py[] = "curated_tokenizers\\_wordpiece.pyx"; +/* #### Code section: decls ### */ +static int __pyx_pf_18curated_tokenizers_10_wordpiece_18WordPieceProcessor___init__(struct __pyx_obj_18curated_tokenizers_10_wordpiece_WordPieceProcessor *__pyx_v_self, PyObject *__pyx_v_pieces); /* proto */ +static PyObject *__pyx_pf_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_2__copy__(struct __pyx_obj_18curated_tokenizers_10_wordpiece_WordPieceProcessor *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_4__deepcopy__(struct __pyx_obj_18curated_tokenizers_10_wordpiece_WordPieceProcessor *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v_memo); /* proto */ +static PyObject *__pyx_pf_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_6encode(struct __pyx_obj_18curated_tokenizers_10_wordpiece_WordPieceProcessor *__pyx_v_self, PyObject *__pyx_v_token); /* proto */ +static PyObject *__pyx_pf_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_8decode(struct __pyx_obj_18curated_tokenizers_10_wordpiece_WordPieceProcessor *__pyx_v_self, PyObject *__pyx_v_pieces); /* proto */ +static PyObject *__pyx_pf_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_10get_initial(struct __pyx_obj_18curated_tokenizers_10_wordpiece_WordPieceProcessor *__pyx_v_self, PyObject *__pyx_v_piece); /* proto */ +static PyObject *__pyx_pf_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_12id_to_piece(struct __pyx_obj_18curated_tokenizers_10_wordpiece_WordPieceProcessor *__pyx_v_self, PyObject *__pyx_v_piece); /* proto */ +static PyObject *__pyx_pf_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_14is_valid_piece_id(struct __pyx_obj_18curated_tokenizers_10_wordpiece_WordPieceProcessor *__pyx_v_self, PyObject *__pyx_v_piece); /* proto */ +static PyObject *__pyx_pf_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_16from_file(PyObject *__pyx_v_filename); /* proto */ +static PyObject *__pyx_pf_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_18to_list(struct __pyx_obj_18curated_tokenizers_10_wordpiece_WordPieceProcessor *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_20__reduce__(struct __pyx_obj_18curated_tokenizers_10_wordpiece_WordPieceProcessor *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_18curated_tokenizers_10_wordpiece_unpickle_wordpiece_processor(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_pieces); /* proto */ +static PyObject *__pyx_tp_new_18curated_tokenizers_10_wordpiece_WordPieceProcessor(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +/* #### Code section: late_includes ### */ +/* #### Code section: module_state ### */ +typedef struct { + PyObject *__pyx_d; + PyObject *__pyx_b; + PyObject *__pyx_cython_runtime; + PyObject *__pyx_empty_tuple; + PyObject *__pyx_empty_bytes; + PyObject *__pyx_empty_unicode; + #ifdef __Pyx_CyFunction_USED + PyTypeObject *__pyx_CyFunctionType; + #endif + #ifdef __Pyx_FusedFunction_USED + PyTypeObject *__pyx_FusedFunctionType; + #endif + #ifdef __Pyx_Generator_USED + PyTypeObject *__pyx_GeneratorType; + #endif + #ifdef __Pyx_IterableCoroutine_USED + PyTypeObject *__pyx_IterableCoroutineType; + #endif + #ifdef __Pyx_Coroutine_USED + PyTypeObject *__pyx_CoroutineAwaitType; + #endif + #ifdef __Pyx_Coroutine_USED + PyTypeObject *__pyx_CoroutineType; + #endif + #if CYTHON_USE_MODULE_STATE + #endif + #if CYTHON_USE_MODULE_STATE + #endif + #if CYTHON_USE_MODULE_STATE + #endif + #if CYTHON_USE_MODULE_STATE + #endif + #if CYTHON_USE_MODULE_STATE + #endif + #if CYTHON_USE_MODULE_STATE + #endif + #if CYTHON_USE_MODULE_STATE + #endif + #if CYTHON_USE_MODULE_STATE + PyObject *__pyx_type_18curated_tokenizers_10_wordpiece_WordPieceProcessor; + #endif + PyTypeObject *__pyx_ptype_18curated_tokenizers_10_wordpiece_WordPieceProcessor; + PyObject *__pyx_kp_s_; + PyObject *__pyx_kp_u_; + PyObject *__pyx_n_s_Iterable; + PyObject *__pyx_kp_s_Iterable_int; + PyObject *__pyx_n_s_List; + PyObject *__pyx_kp_s_List_str; + PyObject *__pyx_n_s_Tuple; + PyObject *__pyx_kp_s_Tuple_List_int_List_str; + PyObject *__pyx_kp_s_Tuple_str_bool; + PyObject *__pyx_n_s_WordPieceProcessor; + PyObject *__pyx_n_s_WordPieceProcessor___copy; + PyObject *__pyx_n_s_WordPieceProcessor___deepcopy; + PyObject *__pyx_n_s_WordPieceProcessor___reduce; + PyObject *__pyx_n_s_WordPieceProcessor_decode; + PyObject *__pyx_n_s_WordPieceProcessor_encode; + PyObject *__pyx_n_s_WordPieceProcessor_from_file; + PyObject *__pyx_n_s_WordPieceProcessor_get_initial; + PyObject *__pyx_n_s_WordPieceProcessor_id_to_piece; + PyObject *__pyx_n_s_WordPieceProcessor_is_valid_piec; + PyObject *__pyx_n_s_WordPieceProcessor_to_list; + PyObject *__pyx_n_s__26; + PyObject *__pyx_kp_s__3; + PyObject *__pyx_kp_u__5; + PyObject *__pyx_n_s_asyncio_coroutines; + PyObject *__pyx_n_s_bool; + PyObject *__pyx_n_s_cline_in_traceback; + PyObject *__pyx_n_s_copy; + PyObject *__pyx_n_s_curated_tokenizers__wordpiece; + PyObject *__pyx_kp_s_curated_tokenizers__wordpiece_py; + PyObject *__pyx_n_s_decode; + PyObject *__pyx_n_s_deepcopy; + PyObject *__pyx_n_s_dict; + PyObject *__pyx_kp_u_disable; + PyObject *__pyx_kp_u_enable; + PyObject *__pyx_n_s_encode; + PyObject *__pyx_n_s_encoding; + PyObject *__pyx_n_s_enter; + PyObject *__pyx_n_s_enumerate; + PyObject *__pyx_n_s_exit; + PyObject *__pyx_n_s_f; + PyObject *__pyx_n_s_filename; + PyObject *__pyx_n_s_from_file; + PyObject *__pyx_kp_u_gc; + PyObject *__pyx_n_s_get_initial; + PyObject *__pyx_n_s_i; + PyObject *__pyx_n_s_id; + PyObject *__pyx_n_s_id_to_piece; + PyObject *__pyx_n_s_import; + PyObject *__pyx_n_s_int; + PyObject *__pyx_n_s_is_coroutine; + PyObject *__pyx_n_s_is_initial; + PyObject *__pyx_n_s_is_valid_piece_id; + PyObject *__pyx_kp_u_isenabled; + PyObject *__pyx_n_s_join; + PyObject *__pyx_n_s_line; + PyObject *__pyx_n_s_main; + PyObject *__pyx_n_s_match; + PyObject *__pyx_n_s_memo; + PyObject *__pyx_n_s_name; + PyObject *__pyx_n_s_open; + PyObject *__pyx_n_s_piece; + PyObject *__pyx_n_s_pieces; + PyObject *__pyx_n_s_prefix; + PyObject *__pyx_n_s_ptr_piece; + PyObject *__pyx_n_s_pyx_vtable; + PyObject *__pyx_n_s_range; + PyObject *__pyx_n_s_reduce; + PyObject *__pyx_n_s_return; + PyObject *__pyx_n_s_reversed; + PyObject *__pyx_n_s_self; + PyObject *__pyx_n_s_startswith; + PyObject *__pyx_n_s_staticmethod; + PyObject *__pyx_n_s_str; + PyObject *__pyx_n_s_strip; + PyObject *__pyx_n_s_test; + PyObject *__pyx_n_s_to_list; + PyObject *__pyx_n_s_token; + PyObject *__pyx_n_s_token_ids; + PyObject *__pyx_n_s_token_pieces; + PyObject *__pyx_n_s_typing; + PyObject *__pyx_n_s_unpickle_wordpiece_processor; + PyObject *__pyx_n_s_utf8; + PyObject *__pyx_int_0; + PyObject *__pyx_int_1; + PyObject *__pyx_int_2; + PyObject *__pyx_int_neg_1; + PyObject *__pyx_slice__2; + PyObject *__pyx_tuple__4; + PyObject *__pyx_tuple__6; + PyObject *__pyx_tuple__8; + PyObject *__pyx_tuple__10; + PyObject *__pyx_tuple__12; + PyObject *__pyx_tuple__14; + PyObject *__pyx_tuple__16; + PyObject *__pyx_tuple__19; + PyObject *__pyx_tuple__21; + PyObject *__pyx_tuple__24; + PyObject *__pyx_codeobj__7; + PyObject *__pyx_codeobj__9; + PyObject *__pyx_codeobj__11; + PyObject *__pyx_codeobj__13; + PyObject *__pyx_codeobj__15; + PyObject *__pyx_codeobj__17; + PyObject *__pyx_codeobj__18; + PyObject *__pyx_codeobj__20; + PyObject *__pyx_codeobj__22; + PyObject *__pyx_codeobj__23; + PyObject *__pyx_codeobj__25; +} __pyx_mstate; + +#if CYTHON_USE_MODULE_STATE +#ifdef __cplusplus +namespace { + extern struct PyModuleDef __pyx_moduledef; +} /* anonymous namespace */ +#else +static struct PyModuleDef __pyx_moduledef; +#endif + +#define __pyx_mstate(o) ((__pyx_mstate *)__Pyx_PyModule_GetState(o)) + +#define __pyx_mstate_global (__pyx_mstate(PyState_FindModule(&__pyx_moduledef))) + +#define __pyx_m (PyState_FindModule(&__pyx_moduledef)) +#else +static __pyx_mstate __pyx_mstate_global_static = +#ifdef __cplusplus + {}; +#else + {0}; +#endif +static __pyx_mstate *__pyx_mstate_global = &__pyx_mstate_global_static; +#endif +/* #### Code section: module_state_clear ### */ +#if CYTHON_USE_MODULE_STATE +static int __pyx_m_clear(PyObject *m) { + __pyx_mstate *clear_module_state = __pyx_mstate(m); + if (!clear_module_state) return 0; + Py_CLEAR(clear_module_state->__pyx_d); + Py_CLEAR(clear_module_state->__pyx_b); + Py_CLEAR(clear_module_state->__pyx_cython_runtime); + Py_CLEAR(clear_module_state->__pyx_empty_tuple); + Py_CLEAR(clear_module_state->__pyx_empty_bytes); + Py_CLEAR(clear_module_state->__pyx_empty_unicode); + #ifdef __Pyx_CyFunction_USED + Py_CLEAR(clear_module_state->__pyx_CyFunctionType); + #endif + #ifdef __Pyx_FusedFunction_USED + Py_CLEAR(clear_module_state->__pyx_FusedFunctionType); + #endif + Py_CLEAR(clear_module_state->__pyx_ptype_18curated_tokenizers_10_wordpiece_WordPieceProcessor); + Py_CLEAR(clear_module_state->__pyx_type_18curated_tokenizers_10_wordpiece_WordPieceProcessor); + Py_CLEAR(clear_module_state->__pyx_kp_s_); + Py_CLEAR(clear_module_state->__pyx_kp_u_); + Py_CLEAR(clear_module_state->__pyx_n_s_Iterable); + Py_CLEAR(clear_module_state->__pyx_kp_s_Iterable_int); + Py_CLEAR(clear_module_state->__pyx_n_s_List); + Py_CLEAR(clear_module_state->__pyx_kp_s_List_str); + Py_CLEAR(clear_module_state->__pyx_n_s_Tuple); + Py_CLEAR(clear_module_state->__pyx_kp_s_Tuple_List_int_List_str); + Py_CLEAR(clear_module_state->__pyx_kp_s_Tuple_str_bool); + Py_CLEAR(clear_module_state->__pyx_n_s_WordPieceProcessor); + Py_CLEAR(clear_module_state->__pyx_n_s_WordPieceProcessor___copy); + Py_CLEAR(clear_module_state->__pyx_n_s_WordPieceProcessor___deepcopy); + Py_CLEAR(clear_module_state->__pyx_n_s_WordPieceProcessor___reduce); + Py_CLEAR(clear_module_state->__pyx_n_s_WordPieceProcessor_decode); + Py_CLEAR(clear_module_state->__pyx_n_s_WordPieceProcessor_encode); + Py_CLEAR(clear_module_state->__pyx_n_s_WordPieceProcessor_from_file); + Py_CLEAR(clear_module_state->__pyx_n_s_WordPieceProcessor_get_initial); + Py_CLEAR(clear_module_state->__pyx_n_s_WordPieceProcessor_id_to_piece); + Py_CLEAR(clear_module_state->__pyx_n_s_WordPieceProcessor_is_valid_piec); + Py_CLEAR(clear_module_state->__pyx_n_s_WordPieceProcessor_to_list); + Py_CLEAR(clear_module_state->__pyx_n_s__26); + Py_CLEAR(clear_module_state->__pyx_kp_s__3); + Py_CLEAR(clear_module_state->__pyx_kp_u__5); + Py_CLEAR(clear_module_state->__pyx_n_s_asyncio_coroutines); + Py_CLEAR(clear_module_state->__pyx_n_s_bool); + Py_CLEAR(clear_module_state->__pyx_n_s_cline_in_traceback); + Py_CLEAR(clear_module_state->__pyx_n_s_copy); + Py_CLEAR(clear_module_state->__pyx_n_s_curated_tokenizers__wordpiece); + Py_CLEAR(clear_module_state->__pyx_kp_s_curated_tokenizers__wordpiece_py); + Py_CLEAR(clear_module_state->__pyx_n_s_decode); + Py_CLEAR(clear_module_state->__pyx_n_s_deepcopy); + Py_CLEAR(clear_module_state->__pyx_n_s_dict); + Py_CLEAR(clear_module_state->__pyx_kp_u_disable); + Py_CLEAR(clear_module_state->__pyx_kp_u_enable); + Py_CLEAR(clear_module_state->__pyx_n_s_encode); + Py_CLEAR(clear_module_state->__pyx_n_s_encoding); + Py_CLEAR(clear_module_state->__pyx_n_s_enter); + Py_CLEAR(clear_module_state->__pyx_n_s_enumerate); + Py_CLEAR(clear_module_state->__pyx_n_s_exit); + Py_CLEAR(clear_module_state->__pyx_n_s_f); + Py_CLEAR(clear_module_state->__pyx_n_s_filename); + Py_CLEAR(clear_module_state->__pyx_n_s_from_file); + Py_CLEAR(clear_module_state->__pyx_kp_u_gc); + Py_CLEAR(clear_module_state->__pyx_n_s_get_initial); + Py_CLEAR(clear_module_state->__pyx_n_s_i); + Py_CLEAR(clear_module_state->__pyx_n_s_id); + Py_CLEAR(clear_module_state->__pyx_n_s_id_to_piece); + Py_CLEAR(clear_module_state->__pyx_n_s_import); + Py_CLEAR(clear_module_state->__pyx_n_s_int); + Py_CLEAR(clear_module_state->__pyx_n_s_is_coroutine); + Py_CLEAR(clear_module_state->__pyx_n_s_is_initial); + Py_CLEAR(clear_module_state->__pyx_n_s_is_valid_piece_id); + Py_CLEAR(clear_module_state->__pyx_kp_u_isenabled); + Py_CLEAR(clear_module_state->__pyx_n_s_join); + Py_CLEAR(clear_module_state->__pyx_n_s_line); + Py_CLEAR(clear_module_state->__pyx_n_s_main); + Py_CLEAR(clear_module_state->__pyx_n_s_match); + Py_CLEAR(clear_module_state->__pyx_n_s_memo); + Py_CLEAR(clear_module_state->__pyx_n_s_name); + Py_CLEAR(clear_module_state->__pyx_n_s_open); + Py_CLEAR(clear_module_state->__pyx_n_s_piece); + Py_CLEAR(clear_module_state->__pyx_n_s_pieces); + Py_CLEAR(clear_module_state->__pyx_n_s_prefix); + Py_CLEAR(clear_module_state->__pyx_n_s_ptr_piece); + Py_CLEAR(clear_module_state->__pyx_n_s_pyx_vtable); + Py_CLEAR(clear_module_state->__pyx_n_s_range); + Py_CLEAR(clear_module_state->__pyx_n_s_reduce); + Py_CLEAR(clear_module_state->__pyx_n_s_return); + Py_CLEAR(clear_module_state->__pyx_n_s_reversed); + Py_CLEAR(clear_module_state->__pyx_n_s_self); + Py_CLEAR(clear_module_state->__pyx_n_s_startswith); + Py_CLEAR(clear_module_state->__pyx_n_s_staticmethod); + Py_CLEAR(clear_module_state->__pyx_n_s_str); + Py_CLEAR(clear_module_state->__pyx_n_s_strip); + Py_CLEAR(clear_module_state->__pyx_n_s_test); + Py_CLEAR(clear_module_state->__pyx_n_s_to_list); + Py_CLEAR(clear_module_state->__pyx_n_s_token); + Py_CLEAR(clear_module_state->__pyx_n_s_token_ids); + Py_CLEAR(clear_module_state->__pyx_n_s_token_pieces); + Py_CLEAR(clear_module_state->__pyx_n_s_typing); + Py_CLEAR(clear_module_state->__pyx_n_s_unpickle_wordpiece_processor); + Py_CLEAR(clear_module_state->__pyx_n_s_utf8); + Py_CLEAR(clear_module_state->__pyx_int_0); + Py_CLEAR(clear_module_state->__pyx_int_1); + Py_CLEAR(clear_module_state->__pyx_int_2); + Py_CLEAR(clear_module_state->__pyx_int_neg_1); + Py_CLEAR(clear_module_state->__pyx_slice__2); + Py_CLEAR(clear_module_state->__pyx_tuple__4); + Py_CLEAR(clear_module_state->__pyx_tuple__6); + Py_CLEAR(clear_module_state->__pyx_tuple__8); + Py_CLEAR(clear_module_state->__pyx_tuple__10); + Py_CLEAR(clear_module_state->__pyx_tuple__12); + Py_CLEAR(clear_module_state->__pyx_tuple__14); + Py_CLEAR(clear_module_state->__pyx_tuple__16); + Py_CLEAR(clear_module_state->__pyx_tuple__19); + Py_CLEAR(clear_module_state->__pyx_tuple__21); + Py_CLEAR(clear_module_state->__pyx_tuple__24); + Py_CLEAR(clear_module_state->__pyx_codeobj__7); + Py_CLEAR(clear_module_state->__pyx_codeobj__9); + Py_CLEAR(clear_module_state->__pyx_codeobj__11); + Py_CLEAR(clear_module_state->__pyx_codeobj__13); + Py_CLEAR(clear_module_state->__pyx_codeobj__15); + Py_CLEAR(clear_module_state->__pyx_codeobj__17); + Py_CLEAR(clear_module_state->__pyx_codeobj__18); + Py_CLEAR(clear_module_state->__pyx_codeobj__20); + Py_CLEAR(clear_module_state->__pyx_codeobj__22); + Py_CLEAR(clear_module_state->__pyx_codeobj__23); + Py_CLEAR(clear_module_state->__pyx_codeobj__25); + return 0; +} +#endif +/* #### Code section: module_state_traverse ### */ +#if CYTHON_USE_MODULE_STATE +static int __pyx_m_traverse(PyObject *m, visitproc visit, void *arg) { + __pyx_mstate *traverse_module_state = __pyx_mstate(m); + if (!traverse_module_state) return 0; + Py_VISIT(traverse_module_state->__pyx_d); + Py_VISIT(traverse_module_state->__pyx_b); + Py_VISIT(traverse_module_state->__pyx_cython_runtime); + Py_VISIT(traverse_module_state->__pyx_empty_tuple); + Py_VISIT(traverse_module_state->__pyx_empty_bytes); + Py_VISIT(traverse_module_state->__pyx_empty_unicode); + #ifdef __Pyx_CyFunction_USED + Py_VISIT(traverse_module_state->__pyx_CyFunctionType); + #endif + #ifdef __Pyx_FusedFunction_USED + Py_VISIT(traverse_module_state->__pyx_FusedFunctionType); + #endif + Py_VISIT(traverse_module_state->__pyx_ptype_18curated_tokenizers_10_wordpiece_WordPieceProcessor); + Py_VISIT(traverse_module_state->__pyx_type_18curated_tokenizers_10_wordpiece_WordPieceProcessor); + Py_VISIT(traverse_module_state->__pyx_kp_s_); + Py_VISIT(traverse_module_state->__pyx_kp_u_); + Py_VISIT(traverse_module_state->__pyx_n_s_Iterable); + Py_VISIT(traverse_module_state->__pyx_kp_s_Iterable_int); + Py_VISIT(traverse_module_state->__pyx_n_s_List); + Py_VISIT(traverse_module_state->__pyx_kp_s_List_str); + Py_VISIT(traverse_module_state->__pyx_n_s_Tuple); + Py_VISIT(traverse_module_state->__pyx_kp_s_Tuple_List_int_List_str); + Py_VISIT(traverse_module_state->__pyx_kp_s_Tuple_str_bool); + Py_VISIT(traverse_module_state->__pyx_n_s_WordPieceProcessor); + Py_VISIT(traverse_module_state->__pyx_n_s_WordPieceProcessor___copy); + Py_VISIT(traverse_module_state->__pyx_n_s_WordPieceProcessor___deepcopy); + Py_VISIT(traverse_module_state->__pyx_n_s_WordPieceProcessor___reduce); + Py_VISIT(traverse_module_state->__pyx_n_s_WordPieceProcessor_decode); + Py_VISIT(traverse_module_state->__pyx_n_s_WordPieceProcessor_encode); + Py_VISIT(traverse_module_state->__pyx_n_s_WordPieceProcessor_from_file); + Py_VISIT(traverse_module_state->__pyx_n_s_WordPieceProcessor_get_initial); + Py_VISIT(traverse_module_state->__pyx_n_s_WordPieceProcessor_id_to_piece); + Py_VISIT(traverse_module_state->__pyx_n_s_WordPieceProcessor_is_valid_piec); + Py_VISIT(traverse_module_state->__pyx_n_s_WordPieceProcessor_to_list); + Py_VISIT(traverse_module_state->__pyx_n_s__26); + Py_VISIT(traverse_module_state->__pyx_kp_s__3); + Py_VISIT(traverse_module_state->__pyx_kp_u__5); + Py_VISIT(traverse_module_state->__pyx_n_s_asyncio_coroutines); + Py_VISIT(traverse_module_state->__pyx_n_s_bool); + Py_VISIT(traverse_module_state->__pyx_n_s_cline_in_traceback); + Py_VISIT(traverse_module_state->__pyx_n_s_copy); + Py_VISIT(traverse_module_state->__pyx_n_s_curated_tokenizers__wordpiece); + Py_VISIT(traverse_module_state->__pyx_kp_s_curated_tokenizers__wordpiece_py); + Py_VISIT(traverse_module_state->__pyx_n_s_decode); + Py_VISIT(traverse_module_state->__pyx_n_s_deepcopy); + Py_VISIT(traverse_module_state->__pyx_n_s_dict); + Py_VISIT(traverse_module_state->__pyx_kp_u_disable); + Py_VISIT(traverse_module_state->__pyx_kp_u_enable); + Py_VISIT(traverse_module_state->__pyx_n_s_encode); + Py_VISIT(traverse_module_state->__pyx_n_s_encoding); + Py_VISIT(traverse_module_state->__pyx_n_s_enter); + Py_VISIT(traverse_module_state->__pyx_n_s_enumerate); + Py_VISIT(traverse_module_state->__pyx_n_s_exit); + Py_VISIT(traverse_module_state->__pyx_n_s_f); + Py_VISIT(traverse_module_state->__pyx_n_s_filename); + Py_VISIT(traverse_module_state->__pyx_n_s_from_file); + Py_VISIT(traverse_module_state->__pyx_kp_u_gc); + Py_VISIT(traverse_module_state->__pyx_n_s_get_initial); + Py_VISIT(traverse_module_state->__pyx_n_s_i); + Py_VISIT(traverse_module_state->__pyx_n_s_id); + Py_VISIT(traverse_module_state->__pyx_n_s_id_to_piece); + Py_VISIT(traverse_module_state->__pyx_n_s_import); + Py_VISIT(traverse_module_state->__pyx_n_s_int); + Py_VISIT(traverse_module_state->__pyx_n_s_is_coroutine); + Py_VISIT(traverse_module_state->__pyx_n_s_is_initial); + Py_VISIT(traverse_module_state->__pyx_n_s_is_valid_piece_id); + Py_VISIT(traverse_module_state->__pyx_kp_u_isenabled); + Py_VISIT(traverse_module_state->__pyx_n_s_join); + Py_VISIT(traverse_module_state->__pyx_n_s_line); + Py_VISIT(traverse_module_state->__pyx_n_s_main); + Py_VISIT(traverse_module_state->__pyx_n_s_match); + Py_VISIT(traverse_module_state->__pyx_n_s_memo); + Py_VISIT(traverse_module_state->__pyx_n_s_name); + Py_VISIT(traverse_module_state->__pyx_n_s_open); + Py_VISIT(traverse_module_state->__pyx_n_s_piece); + Py_VISIT(traverse_module_state->__pyx_n_s_pieces); + Py_VISIT(traverse_module_state->__pyx_n_s_prefix); + Py_VISIT(traverse_module_state->__pyx_n_s_ptr_piece); + Py_VISIT(traverse_module_state->__pyx_n_s_pyx_vtable); + Py_VISIT(traverse_module_state->__pyx_n_s_range); + Py_VISIT(traverse_module_state->__pyx_n_s_reduce); + Py_VISIT(traverse_module_state->__pyx_n_s_return); + Py_VISIT(traverse_module_state->__pyx_n_s_reversed); + Py_VISIT(traverse_module_state->__pyx_n_s_self); + Py_VISIT(traverse_module_state->__pyx_n_s_startswith); + Py_VISIT(traverse_module_state->__pyx_n_s_staticmethod); + Py_VISIT(traverse_module_state->__pyx_n_s_str); + Py_VISIT(traverse_module_state->__pyx_n_s_strip); + Py_VISIT(traverse_module_state->__pyx_n_s_test); + Py_VISIT(traverse_module_state->__pyx_n_s_to_list); + Py_VISIT(traverse_module_state->__pyx_n_s_token); + Py_VISIT(traverse_module_state->__pyx_n_s_token_ids); + Py_VISIT(traverse_module_state->__pyx_n_s_token_pieces); + Py_VISIT(traverse_module_state->__pyx_n_s_typing); + Py_VISIT(traverse_module_state->__pyx_n_s_unpickle_wordpiece_processor); + Py_VISIT(traverse_module_state->__pyx_n_s_utf8); + Py_VISIT(traverse_module_state->__pyx_int_0); + Py_VISIT(traverse_module_state->__pyx_int_1); + Py_VISIT(traverse_module_state->__pyx_int_2); + Py_VISIT(traverse_module_state->__pyx_int_neg_1); + Py_VISIT(traverse_module_state->__pyx_slice__2); + Py_VISIT(traverse_module_state->__pyx_tuple__4); + Py_VISIT(traverse_module_state->__pyx_tuple__6); + Py_VISIT(traverse_module_state->__pyx_tuple__8); + Py_VISIT(traverse_module_state->__pyx_tuple__10); + Py_VISIT(traverse_module_state->__pyx_tuple__12); + Py_VISIT(traverse_module_state->__pyx_tuple__14); + Py_VISIT(traverse_module_state->__pyx_tuple__16); + Py_VISIT(traverse_module_state->__pyx_tuple__19); + Py_VISIT(traverse_module_state->__pyx_tuple__21); + Py_VISIT(traverse_module_state->__pyx_tuple__24); + Py_VISIT(traverse_module_state->__pyx_codeobj__7); + Py_VISIT(traverse_module_state->__pyx_codeobj__9); + Py_VISIT(traverse_module_state->__pyx_codeobj__11); + Py_VISIT(traverse_module_state->__pyx_codeobj__13); + Py_VISIT(traverse_module_state->__pyx_codeobj__15); + Py_VISIT(traverse_module_state->__pyx_codeobj__17); + Py_VISIT(traverse_module_state->__pyx_codeobj__18); + Py_VISIT(traverse_module_state->__pyx_codeobj__20); + Py_VISIT(traverse_module_state->__pyx_codeobj__22); + Py_VISIT(traverse_module_state->__pyx_codeobj__23); + Py_VISIT(traverse_module_state->__pyx_codeobj__25); + return 0; +} +#endif +/* #### Code section: module_state_defines ### */ +#define __pyx_d __pyx_mstate_global->__pyx_d +#define __pyx_b __pyx_mstate_global->__pyx_b +#define __pyx_cython_runtime __pyx_mstate_global->__pyx_cython_runtime +#define __pyx_empty_tuple __pyx_mstate_global->__pyx_empty_tuple +#define __pyx_empty_bytes __pyx_mstate_global->__pyx_empty_bytes +#define __pyx_empty_unicode __pyx_mstate_global->__pyx_empty_unicode +#ifdef __Pyx_CyFunction_USED +#define __pyx_CyFunctionType __pyx_mstate_global->__pyx_CyFunctionType +#endif +#ifdef __Pyx_FusedFunction_USED +#define __pyx_FusedFunctionType __pyx_mstate_global->__pyx_FusedFunctionType +#endif +#ifdef __Pyx_Generator_USED +#define __pyx_GeneratorType __pyx_mstate_global->__pyx_GeneratorType +#endif +#ifdef __Pyx_IterableCoroutine_USED +#define __pyx_IterableCoroutineType __pyx_mstate_global->__pyx_IterableCoroutineType +#endif +#ifdef __Pyx_Coroutine_USED +#define __pyx_CoroutineAwaitType __pyx_mstate_global->__pyx_CoroutineAwaitType +#endif +#ifdef __Pyx_Coroutine_USED +#define __pyx_CoroutineType __pyx_mstate_global->__pyx_CoroutineType +#endif +#if CYTHON_USE_MODULE_STATE +#endif +#if CYTHON_USE_MODULE_STATE +#endif +#if CYTHON_USE_MODULE_STATE +#endif +#if CYTHON_USE_MODULE_STATE +#endif +#if CYTHON_USE_MODULE_STATE +#endif +#if CYTHON_USE_MODULE_STATE +#endif +#if CYTHON_USE_MODULE_STATE +#endif +#if CYTHON_USE_MODULE_STATE +#define __pyx_type_18curated_tokenizers_10_wordpiece_WordPieceProcessor __pyx_mstate_global->__pyx_type_18curated_tokenizers_10_wordpiece_WordPieceProcessor +#endif +#define __pyx_ptype_18curated_tokenizers_10_wordpiece_WordPieceProcessor __pyx_mstate_global->__pyx_ptype_18curated_tokenizers_10_wordpiece_WordPieceProcessor +#define __pyx_kp_s_ __pyx_mstate_global->__pyx_kp_s_ +#define __pyx_kp_u_ __pyx_mstate_global->__pyx_kp_u_ +#define __pyx_n_s_Iterable __pyx_mstate_global->__pyx_n_s_Iterable +#define __pyx_kp_s_Iterable_int __pyx_mstate_global->__pyx_kp_s_Iterable_int +#define __pyx_n_s_List __pyx_mstate_global->__pyx_n_s_List +#define __pyx_kp_s_List_str __pyx_mstate_global->__pyx_kp_s_List_str +#define __pyx_n_s_Tuple __pyx_mstate_global->__pyx_n_s_Tuple +#define __pyx_kp_s_Tuple_List_int_List_str __pyx_mstate_global->__pyx_kp_s_Tuple_List_int_List_str +#define __pyx_kp_s_Tuple_str_bool __pyx_mstate_global->__pyx_kp_s_Tuple_str_bool +#define __pyx_n_s_WordPieceProcessor __pyx_mstate_global->__pyx_n_s_WordPieceProcessor +#define __pyx_n_s_WordPieceProcessor___copy __pyx_mstate_global->__pyx_n_s_WordPieceProcessor___copy +#define __pyx_n_s_WordPieceProcessor___deepcopy __pyx_mstate_global->__pyx_n_s_WordPieceProcessor___deepcopy +#define __pyx_n_s_WordPieceProcessor___reduce __pyx_mstate_global->__pyx_n_s_WordPieceProcessor___reduce +#define __pyx_n_s_WordPieceProcessor_decode __pyx_mstate_global->__pyx_n_s_WordPieceProcessor_decode +#define __pyx_n_s_WordPieceProcessor_encode __pyx_mstate_global->__pyx_n_s_WordPieceProcessor_encode +#define __pyx_n_s_WordPieceProcessor_from_file __pyx_mstate_global->__pyx_n_s_WordPieceProcessor_from_file +#define __pyx_n_s_WordPieceProcessor_get_initial __pyx_mstate_global->__pyx_n_s_WordPieceProcessor_get_initial +#define __pyx_n_s_WordPieceProcessor_id_to_piece __pyx_mstate_global->__pyx_n_s_WordPieceProcessor_id_to_piece +#define __pyx_n_s_WordPieceProcessor_is_valid_piec __pyx_mstate_global->__pyx_n_s_WordPieceProcessor_is_valid_piec +#define __pyx_n_s_WordPieceProcessor_to_list __pyx_mstate_global->__pyx_n_s_WordPieceProcessor_to_list +#define __pyx_n_s__26 __pyx_mstate_global->__pyx_n_s__26 +#define __pyx_kp_s__3 __pyx_mstate_global->__pyx_kp_s__3 +#define __pyx_kp_u__5 __pyx_mstate_global->__pyx_kp_u__5 +#define __pyx_n_s_asyncio_coroutines __pyx_mstate_global->__pyx_n_s_asyncio_coroutines +#define __pyx_n_s_bool __pyx_mstate_global->__pyx_n_s_bool +#define __pyx_n_s_cline_in_traceback __pyx_mstate_global->__pyx_n_s_cline_in_traceback +#define __pyx_n_s_copy __pyx_mstate_global->__pyx_n_s_copy +#define __pyx_n_s_curated_tokenizers__wordpiece __pyx_mstate_global->__pyx_n_s_curated_tokenizers__wordpiece +#define __pyx_kp_s_curated_tokenizers__wordpiece_py __pyx_mstate_global->__pyx_kp_s_curated_tokenizers__wordpiece_py +#define __pyx_n_s_decode __pyx_mstate_global->__pyx_n_s_decode +#define __pyx_n_s_deepcopy __pyx_mstate_global->__pyx_n_s_deepcopy +#define __pyx_n_s_dict __pyx_mstate_global->__pyx_n_s_dict +#define __pyx_kp_u_disable __pyx_mstate_global->__pyx_kp_u_disable +#define __pyx_kp_u_enable __pyx_mstate_global->__pyx_kp_u_enable +#define __pyx_n_s_encode __pyx_mstate_global->__pyx_n_s_encode +#define __pyx_n_s_encoding __pyx_mstate_global->__pyx_n_s_encoding +#define __pyx_n_s_enter __pyx_mstate_global->__pyx_n_s_enter +#define __pyx_n_s_enumerate __pyx_mstate_global->__pyx_n_s_enumerate +#define __pyx_n_s_exit __pyx_mstate_global->__pyx_n_s_exit +#define __pyx_n_s_f __pyx_mstate_global->__pyx_n_s_f +#define __pyx_n_s_filename __pyx_mstate_global->__pyx_n_s_filename +#define __pyx_n_s_from_file __pyx_mstate_global->__pyx_n_s_from_file +#define __pyx_kp_u_gc __pyx_mstate_global->__pyx_kp_u_gc +#define __pyx_n_s_get_initial __pyx_mstate_global->__pyx_n_s_get_initial +#define __pyx_n_s_i __pyx_mstate_global->__pyx_n_s_i +#define __pyx_n_s_id __pyx_mstate_global->__pyx_n_s_id +#define __pyx_n_s_id_to_piece __pyx_mstate_global->__pyx_n_s_id_to_piece +#define __pyx_n_s_import __pyx_mstate_global->__pyx_n_s_import +#define __pyx_n_s_int __pyx_mstate_global->__pyx_n_s_int +#define __pyx_n_s_is_coroutine __pyx_mstate_global->__pyx_n_s_is_coroutine +#define __pyx_n_s_is_initial __pyx_mstate_global->__pyx_n_s_is_initial +#define __pyx_n_s_is_valid_piece_id __pyx_mstate_global->__pyx_n_s_is_valid_piece_id +#define __pyx_kp_u_isenabled __pyx_mstate_global->__pyx_kp_u_isenabled +#define __pyx_n_s_join __pyx_mstate_global->__pyx_n_s_join +#define __pyx_n_s_line __pyx_mstate_global->__pyx_n_s_line +#define __pyx_n_s_main __pyx_mstate_global->__pyx_n_s_main +#define __pyx_n_s_match __pyx_mstate_global->__pyx_n_s_match +#define __pyx_n_s_memo __pyx_mstate_global->__pyx_n_s_memo +#define __pyx_n_s_name __pyx_mstate_global->__pyx_n_s_name +#define __pyx_n_s_open __pyx_mstate_global->__pyx_n_s_open +#define __pyx_n_s_piece __pyx_mstate_global->__pyx_n_s_piece +#define __pyx_n_s_pieces __pyx_mstate_global->__pyx_n_s_pieces +#define __pyx_n_s_prefix __pyx_mstate_global->__pyx_n_s_prefix +#define __pyx_n_s_ptr_piece __pyx_mstate_global->__pyx_n_s_ptr_piece +#define __pyx_n_s_pyx_vtable __pyx_mstate_global->__pyx_n_s_pyx_vtable +#define __pyx_n_s_range __pyx_mstate_global->__pyx_n_s_range +#define __pyx_n_s_reduce __pyx_mstate_global->__pyx_n_s_reduce +#define __pyx_n_s_return __pyx_mstate_global->__pyx_n_s_return +#define __pyx_n_s_reversed __pyx_mstate_global->__pyx_n_s_reversed +#define __pyx_n_s_self __pyx_mstate_global->__pyx_n_s_self +#define __pyx_n_s_startswith __pyx_mstate_global->__pyx_n_s_startswith +#define __pyx_n_s_staticmethod __pyx_mstate_global->__pyx_n_s_staticmethod +#define __pyx_n_s_str __pyx_mstate_global->__pyx_n_s_str +#define __pyx_n_s_strip __pyx_mstate_global->__pyx_n_s_strip +#define __pyx_n_s_test __pyx_mstate_global->__pyx_n_s_test +#define __pyx_n_s_to_list __pyx_mstate_global->__pyx_n_s_to_list +#define __pyx_n_s_token __pyx_mstate_global->__pyx_n_s_token +#define __pyx_n_s_token_ids __pyx_mstate_global->__pyx_n_s_token_ids +#define __pyx_n_s_token_pieces __pyx_mstate_global->__pyx_n_s_token_pieces +#define __pyx_n_s_typing __pyx_mstate_global->__pyx_n_s_typing +#define __pyx_n_s_unpickle_wordpiece_processor __pyx_mstate_global->__pyx_n_s_unpickle_wordpiece_processor +#define __pyx_n_s_utf8 __pyx_mstate_global->__pyx_n_s_utf8 +#define __pyx_int_0 __pyx_mstate_global->__pyx_int_0 +#define __pyx_int_1 __pyx_mstate_global->__pyx_int_1 +#define __pyx_int_2 __pyx_mstate_global->__pyx_int_2 +#define __pyx_int_neg_1 __pyx_mstate_global->__pyx_int_neg_1 +#define __pyx_slice__2 __pyx_mstate_global->__pyx_slice__2 +#define __pyx_tuple__4 __pyx_mstate_global->__pyx_tuple__4 +#define __pyx_tuple__6 __pyx_mstate_global->__pyx_tuple__6 +#define __pyx_tuple__8 __pyx_mstate_global->__pyx_tuple__8 +#define __pyx_tuple__10 __pyx_mstate_global->__pyx_tuple__10 +#define __pyx_tuple__12 __pyx_mstate_global->__pyx_tuple__12 +#define __pyx_tuple__14 __pyx_mstate_global->__pyx_tuple__14 +#define __pyx_tuple__16 __pyx_mstate_global->__pyx_tuple__16 +#define __pyx_tuple__19 __pyx_mstate_global->__pyx_tuple__19 +#define __pyx_tuple__21 __pyx_mstate_global->__pyx_tuple__21 +#define __pyx_tuple__24 __pyx_mstate_global->__pyx_tuple__24 +#define __pyx_codeobj__7 __pyx_mstate_global->__pyx_codeobj__7 +#define __pyx_codeobj__9 __pyx_mstate_global->__pyx_codeobj__9 +#define __pyx_codeobj__11 __pyx_mstate_global->__pyx_codeobj__11 +#define __pyx_codeobj__13 __pyx_mstate_global->__pyx_codeobj__13 +#define __pyx_codeobj__15 __pyx_mstate_global->__pyx_codeobj__15 +#define __pyx_codeobj__17 __pyx_mstate_global->__pyx_codeobj__17 +#define __pyx_codeobj__18 __pyx_mstate_global->__pyx_codeobj__18 +#define __pyx_codeobj__20 __pyx_mstate_global->__pyx_codeobj__20 +#define __pyx_codeobj__22 __pyx_mstate_global->__pyx_codeobj__22 +#define __pyx_codeobj__23 __pyx_mstate_global->__pyx_codeobj__23 +#define __pyx_codeobj__25 __pyx_mstate_global->__pyx_codeobj__25 +/* #### Code section: module_code ### */ + +/* "string.from_py":13 + * + * @cname("__pyx_convert_string_from_py_std__in_string") + * cdef string __pyx_convert_string_from_py_std__in_string(object o) except *: # <<<<<<<<<<<<<< + * cdef Py_ssize_t length = 0 + * cdef const char* data = __Pyx_PyObject_AsStringAndSize(o, &length) + */ + +static std::string __pyx_convert_string_from_py_std__in_string(PyObject *__pyx_v_o) { + Py_ssize_t __pyx_v_length; + char const *__pyx_v_data; + std::string __pyx_r; + char const *__pyx_t_1; + std::string __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "string.from_py":14 + * @cname("__pyx_convert_string_from_py_std__in_string") + * cdef string __pyx_convert_string_from_py_std__in_string(object o) except *: + * cdef Py_ssize_t length = 0 # <<<<<<<<<<<<<< + * cdef const char* data = __Pyx_PyObject_AsStringAndSize(o, &length) + * return string(data, length) + */ + __pyx_v_length = 0; + + /* "string.from_py":15 + * cdef string __pyx_convert_string_from_py_std__in_string(object o) except *: + * cdef Py_ssize_t length = 0 + * cdef const char* data = __Pyx_PyObject_AsStringAndSize(o, &length) # <<<<<<<<<<<<<< + * return string(data, length) + * + */ + __pyx_t_1 = __Pyx_PyObject_AsStringAndSize(__pyx_v_o, (&__pyx_v_length)); if (unlikely(__pyx_t_1 == ((char const *)NULL))) __PYX_ERR(1, 15, __pyx_L1_error) + __pyx_v_data = __pyx_t_1; + + /* "string.from_py":16 + * cdef Py_ssize_t length = 0 + * cdef const char* data = __Pyx_PyObject_AsStringAndSize(o, &length) + * return string(data, length) # <<<<<<<<<<<<<< + * + * + */ + try { + __pyx_t_2 = std::string(__pyx_v_data, __pyx_v_length); + } catch(...) { + __Pyx_CppExn2PyErr(); + __PYX_ERR(1, 16, __pyx_L1_error) + } + __pyx_r = __pyx_t_2; + goto __pyx_L0; + + /* "string.from_py":13 + * + * @cname("__pyx_convert_string_from_py_std__in_string") + * cdef string __pyx_convert_string_from_py_std__in_string(object o) except *: # <<<<<<<<<<<<<< + * cdef Py_ssize_t length = 0 + * cdef const char* data = __Pyx_PyObject_AsStringAndSize(o, &length) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("string.from_py.__pyx_convert_string_from_py_std__in_string", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_pretend_to_initialize(&__pyx_r); + __pyx_L0:; + return __pyx_r; +} + +/* "string.to_py":31 + * + * @cname("__pyx_convert_PyObject_string_to_py_std__in_string") + * cdef inline object __pyx_convert_PyObject_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< + * return __Pyx_PyObject_FromStringAndSize(s.data(), s.size()) + * cdef extern from *: + */ + +static CYTHON_INLINE PyObject *__pyx_convert_PyObject_string_to_py_std__in_string(std::string const &__pyx_v_s) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__pyx_convert_PyObject_string_to_py_std__in_string", 1); + + /* "string.to_py":32 + * @cname("__pyx_convert_PyObject_string_to_py_std__in_string") + * cdef inline object __pyx_convert_PyObject_string_to_py_std__in_string(const string& s): + * return __Pyx_PyObject_FromStringAndSize(s.data(), s.size()) # <<<<<<<<<<<<<< + * cdef extern from *: + * cdef object __Pyx_PyUnicode_FromStringAndSize(const char*, size_t) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_FromStringAndSize(__pyx_v_s.data(), __pyx_v_s.size()); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 32, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "string.to_py":31 + * + * @cname("__pyx_convert_PyObject_string_to_py_std__in_string") + * cdef inline object __pyx_convert_PyObject_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< + * return __Pyx_PyObject_FromStringAndSize(s.data(), s.size()) + * cdef extern from *: + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("string.to_py.__pyx_convert_PyObject_string_to_py_std__in_string", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "string.to_py":37 + * + * @cname("__pyx_convert_PyUnicode_string_to_py_std__in_string") + * cdef inline object __pyx_convert_PyUnicode_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< + * return __Pyx_PyUnicode_FromStringAndSize(s.data(), s.size()) + * cdef extern from *: + */ + +static CYTHON_INLINE PyObject *__pyx_convert_PyUnicode_string_to_py_std__in_string(std::string const &__pyx_v_s) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__pyx_convert_PyUnicode_string_to_py_std__in_string", 1); + + /* "string.to_py":38 + * @cname("__pyx_convert_PyUnicode_string_to_py_std__in_string") + * cdef inline object __pyx_convert_PyUnicode_string_to_py_std__in_string(const string& s): + * return __Pyx_PyUnicode_FromStringAndSize(s.data(), s.size()) # <<<<<<<<<<<<<< + * cdef extern from *: + * cdef object __Pyx_PyStr_FromStringAndSize(const char*, size_t) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyUnicode_FromStringAndSize(__pyx_v_s.data(), __pyx_v_s.size()); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 38, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "string.to_py":37 + * + * @cname("__pyx_convert_PyUnicode_string_to_py_std__in_string") + * cdef inline object __pyx_convert_PyUnicode_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< + * return __Pyx_PyUnicode_FromStringAndSize(s.data(), s.size()) + * cdef extern from *: + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("string.to_py.__pyx_convert_PyUnicode_string_to_py_std__in_string", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "string.to_py":43 + * + * @cname("__pyx_convert_PyStr_string_to_py_std__in_string") + * cdef inline object __pyx_convert_PyStr_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< + * return __Pyx_PyStr_FromStringAndSize(s.data(), s.size()) + * cdef extern from *: + */ + +static CYTHON_INLINE PyObject *__pyx_convert_PyStr_string_to_py_std__in_string(std::string const &__pyx_v_s) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__pyx_convert_PyStr_string_to_py_std__in_string", 1); + + /* "string.to_py":44 + * @cname("__pyx_convert_PyStr_string_to_py_std__in_string") + * cdef inline object __pyx_convert_PyStr_string_to_py_std__in_string(const string& s): + * return __Pyx_PyStr_FromStringAndSize(s.data(), s.size()) # <<<<<<<<<<<<<< + * cdef extern from *: + * cdef object __Pyx_PyBytes_FromStringAndSize(const char*, size_t) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyStr_FromStringAndSize(__pyx_v_s.data(), __pyx_v_s.size()); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 44, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "string.to_py":43 + * + * @cname("__pyx_convert_PyStr_string_to_py_std__in_string") + * cdef inline object __pyx_convert_PyStr_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< + * return __Pyx_PyStr_FromStringAndSize(s.data(), s.size()) + * cdef extern from *: + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("string.to_py.__pyx_convert_PyStr_string_to_py_std__in_string", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "string.to_py":49 + * + * @cname("__pyx_convert_PyBytes_string_to_py_std__in_string") + * cdef inline object __pyx_convert_PyBytes_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< + * return __Pyx_PyBytes_FromStringAndSize(s.data(), s.size()) + * cdef extern from *: + */ + +static CYTHON_INLINE PyObject *__pyx_convert_PyBytes_string_to_py_std__in_string(std::string const &__pyx_v_s) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__pyx_convert_PyBytes_string_to_py_std__in_string", 1); + + /* "string.to_py":50 + * @cname("__pyx_convert_PyBytes_string_to_py_std__in_string") + * cdef inline object __pyx_convert_PyBytes_string_to_py_std__in_string(const string& s): + * return __Pyx_PyBytes_FromStringAndSize(s.data(), s.size()) # <<<<<<<<<<<<<< + * cdef extern from *: + * cdef object __Pyx_PyByteArray_FromStringAndSize(const char*, size_t) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyBytes_FromStringAndSize(__pyx_v_s.data(), __pyx_v_s.size()); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 50, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "string.to_py":49 + * + * @cname("__pyx_convert_PyBytes_string_to_py_std__in_string") + * cdef inline object __pyx_convert_PyBytes_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< + * return __Pyx_PyBytes_FromStringAndSize(s.data(), s.size()) + * cdef extern from *: + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("string.to_py.__pyx_convert_PyBytes_string_to_py_std__in_string", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "string.to_py":55 + * + * @cname("__pyx_convert_PyByteArray_string_to_py_std__in_string") + * cdef inline object __pyx_convert_PyByteArray_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< + * return __Pyx_PyByteArray_FromStringAndSize(s.data(), s.size()) + * + */ + +static CYTHON_INLINE PyObject *__pyx_convert_PyByteArray_string_to_py_std__in_string(std::string const &__pyx_v_s) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__pyx_convert_PyByteArray_string_to_py_std__in_string", 1); + + /* "string.to_py":56 + * @cname("__pyx_convert_PyByteArray_string_to_py_std__in_string") + * cdef inline object __pyx_convert_PyByteArray_string_to_py_std__in_string(const string& s): + * return __Pyx_PyByteArray_FromStringAndSize(s.data(), s.size()) # <<<<<<<<<<<<<< + * + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyByteArray_FromStringAndSize(__pyx_v_s.data(), __pyx_v_s.size()); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 56, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "string.to_py":55 + * + * @cname("__pyx_convert_PyByteArray_string_to_py_std__in_string") + * cdef inline object __pyx_convert_PyByteArray_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< + * return __Pyx_PyByteArray_FromStringAndSize(s.data(), s.size()) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("string.to_py.__pyx_convert_PyByteArray_string_to_py_std__in_string", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_wordpiece.pyx":13 + * cdef PieceStorage _pieces + * + * def __init__(self, pieces: List[str]): # <<<<<<<<<<<<<< + * self._pieces = PieceStorage() + * + */ + +/* Python wrapper */ +static int __pyx_pw_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_pieces = 0; + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); + #if CYTHON_ASSUME_SAFE_MACROS + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return -1; + #endif + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + { + PyObject **__pyx_pyargnames[] = {&__pyx_n_s_pieces,0}; + if (__pyx_kwds) { + Py_ssize_t kw_args; + switch (__pyx_nargs) { + case 1: values[0] = __Pyx_Arg_VARARGS(__pyx_args, 0); + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = __Pyx_NumKwargs_VARARGS(__pyx_kwds); + switch (__pyx_nargs) { + case 0: + if (likely((values[0] = __Pyx_GetKwValue_VARARGS(__pyx_kwds, __pyx_kwvalues, __pyx_n_s_pieces)) != 0)) { + (void)__Pyx_Arg_NewRef_VARARGS(values[0]); + kw_args--; + } + else if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 13, __pyx_L3_error) + else goto __pyx_L5_argtuple_error; + } + if (unlikely(kw_args > 0)) { + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values + 0, kwd_pos_args, "__init__") < 0)) __PYX_ERR(0, 13, __pyx_L3_error) + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_Arg_VARARGS(__pyx_args, 0); + } + __pyx_v_pieces = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__init__", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 13, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_VARARGS(values[__pyx_temp]); + } + } + __Pyx_AddTraceback("curated_tokenizers._wordpiece.WordPieceProcessor.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_18curated_tokenizers_10_wordpiece_18WordPieceProcessor___init__(((struct __pyx_obj_18curated_tokenizers_10_wordpiece_WordPieceProcessor *)__pyx_v_self), __pyx_v_pieces); + + /* function exit code */ + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_VARARGS(values[__pyx_temp]); + } + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_18curated_tokenizers_10_wordpiece_18WordPieceProcessor___init__(struct __pyx_obj_18curated_tokenizers_10_wordpiece_WordPieceProcessor *__pyx_v_self, PyObject *__pyx_v_pieces) { + CYTHON_UNUSED PyObject *__pyx_v_idx = NULL; + PyObject *__pyx_v_piece = NULL; + int __pyx_v_is_initial; + PyObject *__pyx_v_byte_array = NULL; + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + Py_ssize_t __pyx_t_3; + PyObject *(*__pyx_t_4)(PyObject *); + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + int __pyx_t_8; + int __pyx_t_9; + PyObject *__pyx_t_10 = NULL; + std::string __pyx_t_11; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__init__", 1); + + /* "curated_tokenizers/_wordpiece.pyx":14 + * + * def __init__(self, pieces: List[str]): + * self._pieces = PieceStorage() # <<<<<<<<<<<<<< + * + * for idx, piece in enumerate(pieces): + */ + __pyx_v_self->_pieces = PieceStorage(); + + /* "curated_tokenizers/_wordpiece.pyx":16 + * self._pieces = PieceStorage() + * + * for idx, piece in enumerate(pieces): # <<<<<<<<<<<<<< + * is_initial = not piece.startswith("##") + * byte_array = piece[2:].encode('utf8') if not is_initial else piece.encode('utf8') + */ + __Pyx_INCREF(__pyx_int_0); + __pyx_t_1 = __pyx_int_0; + if (likely(PyList_CheckExact(__pyx_v_pieces)) || PyTuple_CheckExact(__pyx_v_pieces)) { + __pyx_t_2 = __pyx_v_pieces; __Pyx_INCREF(__pyx_t_2); + __pyx_t_3 = 0; + __pyx_t_4 = NULL; + } else { + __pyx_t_3 = -1; __pyx_t_2 = PyObject_GetIter(__pyx_v_pieces); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 16, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = __Pyx_PyObject_GetIterNextFunc(__pyx_t_2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 16, __pyx_L1_error) + } + for (;;) { + if (likely(!__pyx_t_4)) { + if (likely(PyList_CheckExact(__pyx_t_2))) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_2); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 16, __pyx_L1_error) + #endif + if (__pyx_t_3 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_5 = PyList_GET_ITEM(__pyx_t_2, __pyx_t_3); __Pyx_INCREF(__pyx_t_5); __pyx_t_3++; if (unlikely((0 < 0))) __PYX_ERR(0, 16, __pyx_L1_error) + #else + __pyx_t_5 = __Pyx_PySequence_ITEM(__pyx_t_2, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 16, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + #endif + } else { + { + Py_ssize_t __pyx_temp = __Pyx_PyTuple_GET_SIZE(__pyx_t_2); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 16, __pyx_L1_error) + #endif + if (__pyx_t_3 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_5 = PyTuple_GET_ITEM(__pyx_t_2, __pyx_t_3); __Pyx_INCREF(__pyx_t_5); __pyx_t_3++; if (unlikely((0 < 0))) __PYX_ERR(0, 16, __pyx_L1_error) + #else + __pyx_t_5 = __Pyx_PySequence_ITEM(__pyx_t_2, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 16, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + #endif + } + } else { + __pyx_t_5 = __pyx_t_4(__pyx_t_2); + if (unlikely(!__pyx_t_5)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else __PYX_ERR(0, 16, __pyx_L1_error) + } + break; + } + __Pyx_GOTREF(__pyx_t_5); + } + __Pyx_XDECREF_SET(__pyx_v_piece, __pyx_t_5); + __pyx_t_5 = 0; + __Pyx_INCREF(__pyx_t_1); + __Pyx_XDECREF_SET(__pyx_v_idx, __pyx_t_1); + __pyx_t_5 = __Pyx_PyInt_AddObjC(__pyx_t_1, __pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 16, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_1); + __pyx_t_1 = __pyx_t_5; + __pyx_t_5 = 0; + + /* "curated_tokenizers/_wordpiece.pyx":17 + * + * for idx, piece in enumerate(pieces): + * is_initial = not piece.startswith("##") # <<<<<<<<<<<<<< + * byte_array = piece[2:].encode('utf8') if not is_initial else piece.encode('utf8') + * self._pieces.add_piece(byte_array, is_initial) + */ + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_piece, __pyx_n_s_startswith); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 17, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = NULL; + __pyx_t_8 = 0; + #if CYTHON_UNPACK_METHODS + if (likely(PyMethod_Check(__pyx_t_6))) { + __pyx_t_7 = PyMethod_GET_SELF(__pyx_t_6); + if (likely(__pyx_t_7)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_6); + __Pyx_INCREF(__pyx_t_7); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_6, function); + __pyx_t_8 = 1; + } + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_7, __pyx_kp_s_}; + __pyx_t_5 = __Pyx_PyObject_FastCall(__pyx_t_6, __pyx_callargs+1-__pyx_t_8, 1+__pyx_t_8); + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 17, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + } + __pyx_t_9 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely((__pyx_t_9 < 0))) __PYX_ERR(0, 17, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_v_is_initial = (!__pyx_t_9); + + /* "curated_tokenizers/_wordpiece.pyx":18 + * for idx, piece in enumerate(pieces): + * is_initial = not piece.startswith("##") + * byte_array = piece[2:].encode('utf8') if not is_initial else piece.encode('utf8') # <<<<<<<<<<<<<< + * self._pieces.add_piece(byte_array, is_initial) + * + */ + __pyx_t_9 = (!__pyx_v_is_initial); + if (__pyx_t_9) { + __pyx_t_7 = __Pyx_PyObject_GetSlice(__pyx_v_piece, 2, 0, NULL, NULL, &__pyx_slice__2, 1, 0, 1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 18, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_10 = __Pyx_PyObject_GetAttrStr(__pyx_t_7, __pyx_n_s_encode); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 18, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_7 = NULL; + __pyx_t_8 = 0; + #if CYTHON_UNPACK_METHODS + if (likely(PyMethod_Check(__pyx_t_10))) { + __pyx_t_7 = PyMethod_GET_SELF(__pyx_t_10); + if (likely(__pyx_t_7)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_10); + __Pyx_INCREF(__pyx_t_7); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_10, function); + __pyx_t_8 = 1; + } + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_7, __pyx_n_s_utf8}; + __pyx_t_6 = __Pyx_PyObject_FastCall(__pyx_t_10, __pyx_callargs+1-__pyx_t_8, 1+__pyx_t_8); + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 18, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + } + __pyx_t_5 = __pyx_t_6; + __pyx_t_6 = 0; + } else { + __pyx_t_10 = __Pyx_PyObject_GetAttrStr(__pyx_v_piece, __pyx_n_s_encode); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 18, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __pyx_t_7 = NULL; + __pyx_t_8 = 0; + #if CYTHON_UNPACK_METHODS + if (likely(PyMethod_Check(__pyx_t_10))) { + __pyx_t_7 = PyMethod_GET_SELF(__pyx_t_10); + if (likely(__pyx_t_7)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_10); + __Pyx_INCREF(__pyx_t_7); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_10, function); + __pyx_t_8 = 1; + } + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_7, __pyx_n_s_utf8}; + __pyx_t_6 = __Pyx_PyObject_FastCall(__pyx_t_10, __pyx_callargs+1-__pyx_t_8, 1+__pyx_t_8); + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 18, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + } + __pyx_t_5 = __pyx_t_6; + __pyx_t_6 = 0; + } + __Pyx_XDECREF_SET(__pyx_v_byte_array, __pyx_t_5); + __pyx_t_5 = 0; + + /* "curated_tokenizers/_wordpiece.pyx":19 + * is_initial = not piece.startswith("##") + * byte_array = piece[2:].encode('utf8') if not is_initial else piece.encode('utf8') + * self._pieces.add_piece(byte_array, is_initial) # <<<<<<<<<<<<<< + * + * def __copy__(self): + */ + __pyx_t_11 = __pyx_convert_string_from_py_std__in_string(__pyx_v_byte_array); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 19, __pyx_L1_error) + __pyx_v_self->_pieces.add_piece(__pyx_t_11, __pyx_v_is_initial); + + /* "curated_tokenizers/_wordpiece.pyx":16 + * self._pieces = PieceStorage() + * + * for idx, piece in enumerate(pieces): # <<<<<<<<<<<<<< + * is_initial = not piece.startswith("##") + * byte_array = piece[2:].encode('utf8') if not is_initial else piece.encode('utf8') + */ + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "curated_tokenizers/_wordpiece.pyx":13 + * cdef PieceStorage _pieces + * + * def __init__(self, pieces: List[str]): # <<<<<<<<<<<<<< + * self._pieces = PieceStorage() + * + */ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_10); + __Pyx_AddTraceback("curated_tokenizers._wordpiece.WordPieceProcessor.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_idx); + __Pyx_XDECREF(__pyx_v_piece); + __Pyx_XDECREF(__pyx_v_byte_array); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_wordpiece.pyx":21 + * self._pieces.add_piece(byte_array, is_initial) + * + * def __copy__(self): # <<<<<<<<<<<<<< + * # This is essentially a deepcopy, but there's no better way to do it. + * return WordPieceProcessor(self.to_list()) + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_3__copy__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_2__copy__, "WordPieceProcessor.__copy__(self)"); +static PyMethodDef __pyx_mdef_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_3__copy__ = {"__copy__", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_3__copy__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_2__copy__}; +static PyObject *__pyx_pw_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_3__copy__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__copy__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_MACROS + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { + __Pyx_RaiseArgtupleInvalid("__copy__", 1, 0, 0, __pyx_nargs); return NULL;} + if (unlikely(__pyx_kwds) && __Pyx_NumKwargs_FASTCALL(__pyx_kwds) && unlikely(!__Pyx_CheckKeywordStrings(__pyx_kwds, "__copy__", 0))) return NULL; + __pyx_r = __pyx_pf_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_2__copy__(((struct __pyx_obj_18curated_tokenizers_10_wordpiece_WordPieceProcessor *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_2__copy__(struct __pyx_obj_18curated_tokenizers_10_wordpiece_WordPieceProcessor *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_t_4; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__copy__", 1); + + /* "curated_tokenizers/_wordpiece.pyx":23 + * def __copy__(self): + * # This is essentially a deepcopy, but there's no better way to do it. + * return WordPieceProcessor(self.to_list()) # <<<<<<<<<<<<<< + * + * def __deepcopy__(self, memo): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_to_list); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 23, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = NULL; + __pyx_t_4 = 0; + #if CYTHON_UNPACK_METHODS + if (likely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2); + if (likely(__pyx_t_3)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_2, function); + __pyx_t_4 = 1; + } + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, NULL}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_2, __pyx_callargs+1-__pyx_t_4, 0+__pyx_t_4); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 23, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } + __pyx_t_2 = __Pyx_PyObject_CallOneArg(((PyObject *)__pyx_ptype_18curated_tokenizers_10_wordpiece_WordPieceProcessor), __pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 23, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "curated_tokenizers/_wordpiece.pyx":21 + * self._pieces.add_piece(byte_array, is_initial) + * + * def __copy__(self): # <<<<<<<<<<<<<< + * # This is essentially a deepcopy, but there's no better way to do it. + * return WordPieceProcessor(self.to_list()) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("curated_tokenizers._wordpiece.WordPieceProcessor.__copy__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_wordpiece.pyx":25 + * return WordPieceProcessor(self.to_list()) + * + * def __deepcopy__(self, memo): # <<<<<<<<<<<<<< + * return WordPieceProcessor(self.to_list()) + * + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_5__deepcopy__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_4__deepcopy__, "WordPieceProcessor.__deepcopy__(self, memo)"); +static PyMethodDef __pyx_mdef_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_5__deepcopy__ = {"__deepcopy__", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_5__deepcopy__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_4__deepcopy__}; +static PyObject *__pyx_pw_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_5__deepcopy__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + CYTHON_UNUSED PyObject *__pyx_v_memo = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__deepcopy__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_MACROS + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject **__pyx_pyargnames[] = {&__pyx_n_s_memo,0}; + if (__pyx_kwds) { + Py_ssize_t kw_args; + switch (__pyx_nargs) { + case 1: values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = __Pyx_NumKwargs_FASTCALL(__pyx_kwds); + switch (__pyx_nargs) { + case 0: + if (likely((values[0] = __Pyx_GetKwValue_FASTCALL(__pyx_kwds, __pyx_kwvalues, __pyx_n_s_memo)) != 0)) { + (void)__Pyx_Arg_NewRef_FASTCALL(values[0]); + kw_args--; + } + else if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 25, __pyx_L3_error) + else goto __pyx_L5_argtuple_error; + } + if (unlikely(kw_args > 0)) { + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values + 0, kwd_pos_args, "__deepcopy__") < 0)) __PYX_ERR(0, 25, __pyx_L3_error) + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + } + __pyx_v_memo = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__deepcopy__", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 25, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_AddTraceback("curated_tokenizers._wordpiece.WordPieceProcessor.__deepcopy__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_4__deepcopy__(((struct __pyx_obj_18curated_tokenizers_10_wordpiece_WordPieceProcessor *)__pyx_v_self), __pyx_v_memo); + + /* function exit code */ + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_4__deepcopy__(struct __pyx_obj_18curated_tokenizers_10_wordpiece_WordPieceProcessor *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v_memo) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_t_4; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__deepcopy__", 1); + + /* "curated_tokenizers/_wordpiece.pyx":26 + * + * def __deepcopy__(self, memo): + * return WordPieceProcessor(self.to_list()) # <<<<<<<<<<<<<< + * + * def encode(self, token: str) -> Tuple[List[int], List[str]]: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_to_list); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 26, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = NULL; + __pyx_t_4 = 0; + #if CYTHON_UNPACK_METHODS + if (likely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2); + if (likely(__pyx_t_3)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_2, function); + __pyx_t_4 = 1; + } + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, NULL}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_2, __pyx_callargs+1-__pyx_t_4, 0+__pyx_t_4); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 26, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } + __pyx_t_2 = __Pyx_PyObject_CallOneArg(((PyObject *)__pyx_ptype_18curated_tokenizers_10_wordpiece_WordPieceProcessor), __pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 26, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "curated_tokenizers/_wordpiece.pyx":25 + * return WordPieceProcessor(self.to_list()) + * + * def __deepcopy__(self, memo): # <<<<<<<<<<<<<< + * return WordPieceProcessor(self.to_list()) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("curated_tokenizers._wordpiece.WordPieceProcessor.__deepcopy__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_wordpiece.pyx":28 + * return WordPieceProcessor(self.to_list()) + * + * def encode(self, token: str) -> Tuple[List[int], List[str]]: # <<<<<<<<<<<<<< + * """ + * Encode a token using word pieces. The piece identifiers are + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_7encode(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_6encode, "WordPieceProcessor.encode(self, token: str) -> Tuple[List[int], List[str]]\n\n Encode a token using word pieces. The piece identifiers are\n returned. If no piece could be found for a suffix, the special\n piece identifier `-1` is used.\n\n token (str): The token to encode as pieces.\n RETURNS (Tuple[List[int], List[str]]): Piece identifiers and token pieces.\n "); +static PyMethodDef __pyx_mdef_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_7encode = {"encode", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_7encode, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_6encode}; +static PyObject *__pyx_pw_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_7encode(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_token = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("encode (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_MACROS + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject **__pyx_pyargnames[] = {&__pyx_n_s_token,0}; + if (__pyx_kwds) { + Py_ssize_t kw_args; + switch (__pyx_nargs) { + case 1: values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = __Pyx_NumKwargs_FASTCALL(__pyx_kwds); + switch (__pyx_nargs) { + case 0: + if (likely((values[0] = __Pyx_GetKwValue_FASTCALL(__pyx_kwds, __pyx_kwvalues, __pyx_n_s_token)) != 0)) { + (void)__Pyx_Arg_NewRef_FASTCALL(values[0]); + kw_args--; + } + else if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 28, __pyx_L3_error) + else goto __pyx_L5_argtuple_error; + } + if (unlikely(kw_args > 0)) { + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values + 0, kwd_pos_args, "encode") < 0)) __PYX_ERR(0, 28, __pyx_L3_error) + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + } + __pyx_v_token = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("encode", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 28, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_AddTraceback("curated_tokenizers._wordpiece.WordPieceProcessor.encode", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_6encode(((struct __pyx_obj_18curated_tokenizers_10_wordpiece_WordPieceProcessor *)__pyx_v_self), __pyx_v_token); + + /* function exit code */ + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_6encode(struct __pyx_obj_18curated_tokenizers_10_wordpiece_WordPieceProcessor *__pyx_v_self, PyObject *__pyx_v_token) { + PyObject *__pyx_v_token_ids = NULL; + PyObject *__pyx_v_token_pieces = NULL; + PyObject *__pyx_v_prefix = NULL; + struct __pyx_t_18curated_tokenizers_10_wordpiece_PieceMatch __pyx_v_match; + int __pyx_v_is_initial; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + struct __pyx_t_18curated_tokenizers_10_wordpiece_PieceMatch __pyx_t_3; + int __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("encode", 0); + __Pyx_INCREF(__pyx_v_token); + + /* "curated_tokenizers/_wordpiece.pyx":37 + * RETURNS (Tuple[List[int], List[str]]): Piece identifiers and token pieces. + * """ + * token_ids = [] # <<<<<<<<<<<<<< + * token_pieces = [] + * prefix = "" + */ + __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 37, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_token_ids = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + + /* "curated_tokenizers/_wordpiece.pyx":38 + * """ + * token_ids = [] + * token_pieces = [] # <<<<<<<<<<<<<< + * prefix = "" + * cdef PieceMatch match + */ + __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 38, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_token_pieces = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + + /* "curated_tokenizers/_wordpiece.pyx":39 + * token_ids = [] + * token_pieces = [] + * prefix = "" # <<<<<<<<<<<<<< + * cdef PieceMatch match + * is_initial = True + */ + __Pyx_INCREF(__pyx_kp_s__3); + __pyx_v_prefix = __pyx_kp_s__3; + + /* "curated_tokenizers/_wordpiece.pyx":41 + * prefix = "" + * cdef PieceMatch match + * is_initial = True # <<<<<<<<<<<<<< + * while token: + * match = self._find_longest_prefix(token, is_initial) + */ + __pyx_v_is_initial = 1; + + /* "curated_tokenizers/_wordpiece.pyx":42 + * cdef PieceMatch match + * is_initial = True + * while token: # <<<<<<<<<<<<<< + * match = self._find_longest_prefix(token, is_initial) + * if not match.found: + */ + while (1) { + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_v_token); if (unlikely((__pyx_t_2 < 0))) __PYX_ERR(0, 42, __pyx_L1_error) + if (!__pyx_t_2) break; + + /* "curated_tokenizers/_wordpiece.pyx":43 + * is_initial = True + * while token: + * match = self._find_longest_prefix(token, is_initial) # <<<<<<<<<<<<<< + * if not match.found: + * token_ids.append(-1) + */ + if (!(likely(PyString_CheckExact(__pyx_v_token))||((__pyx_v_token) == Py_None) || __Pyx_RaiseUnexpectedTypeError("str", __pyx_v_token))) __PYX_ERR(0, 43, __pyx_L1_error) + __pyx_t_3 = ((struct __pyx_vtabstruct_18curated_tokenizers_10_wordpiece_WordPieceProcessor *)__pyx_v_self->__pyx_vtab)->_find_longest_prefix(__pyx_v_self, ((PyObject*)__pyx_v_token), __pyx_v_is_initial); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 43, __pyx_L1_error) + __pyx_v_match = __pyx_t_3; + + /* "curated_tokenizers/_wordpiece.pyx":44 + * while token: + * match = self._find_longest_prefix(token, is_initial) + * if not match.found: # <<<<<<<<<<<<<< + * token_ids.append(-1) + * token_pieces.append(None) + */ + __pyx_t_2 = (!__pyx_v_match.found); + if (__pyx_t_2) { + + /* "curated_tokenizers/_wordpiece.pyx":45 + * match = self._find_longest_prefix(token, is_initial) + * if not match.found: + * token_ids.append(-1) # <<<<<<<<<<<<<< + * token_pieces.append(None) + * return token_ids, token_pieces + */ + __pyx_t_4 = __Pyx_PyList_Append(__pyx_v_token_ids, __pyx_int_neg_1); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(0, 45, __pyx_L1_error) + + /* "curated_tokenizers/_wordpiece.pyx":46 + * if not match.found: + * token_ids.append(-1) + * token_pieces.append(None) # <<<<<<<<<<<<<< + * return token_ids, token_pieces + * token_ids.append(match.piece_id) + */ + __pyx_t_4 = __Pyx_PyList_Append(__pyx_v_token_pieces, Py_None); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(0, 46, __pyx_L1_error) + + /* "curated_tokenizers/_wordpiece.pyx":47 + * token_ids.append(-1) + * token_pieces.append(None) + * return token_ids, token_pieces # <<<<<<<<<<<<<< + * token_ids.append(match.piece_id) + * token_pieces.append(f"{prefix}{token[:match.prefix_len]}") + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 47, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_token_ids); + __Pyx_GIVEREF(__pyx_v_token_ids); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_token_ids)) __PYX_ERR(0, 47, __pyx_L1_error); + __Pyx_INCREF(__pyx_v_token_pieces); + __Pyx_GIVEREF(__pyx_v_token_pieces); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_token_pieces)) __PYX_ERR(0, 47, __pyx_L1_error); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "curated_tokenizers/_wordpiece.pyx":44 + * while token: + * match = self._find_longest_prefix(token, is_initial) + * if not match.found: # <<<<<<<<<<<<<< + * token_ids.append(-1) + * token_pieces.append(None) + */ + } + + /* "curated_tokenizers/_wordpiece.pyx":48 + * token_pieces.append(None) + * return token_ids, token_pieces + * token_ids.append(match.piece_id) # <<<<<<<<<<<<<< + * token_pieces.append(f"{prefix}{token[:match.prefix_len]}") + * token = token[match.prefix_len:] + */ + __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_match.piece_id); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 48, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = __Pyx_PyList_Append(__pyx_v_token_ids, __pyx_t_1); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(0, 48, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "curated_tokenizers/_wordpiece.pyx":49 + * return token_ids, token_pieces + * token_ids.append(match.piece_id) + * token_pieces.append(f"{prefix}{token[:match.prefix_len]}") # <<<<<<<<<<<<<< + * token = token[match.prefix_len:] + * is_initial = False + */ + __pyx_t_1 = __Pyx_PyObject_FormatSimple(__pyx_v_prefix, __pyx_empty_unicode); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 49, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_5 = __Pyx_PyObject_GetSlice(__pyx_v_token, 0, __pyx_v_match.prefix_len, NULL, NULL, NULL, 0, 1, 1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 49, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = __Pyx_PyObject_FormatSimple(__pyx_t_5, __pyx_empty_unicode); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 49, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = __Pyx_PyUnicode_ConcatInPlace(__pyx_t_1, __pyx_t_6); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 49, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_4 = __Pyx_PyList_Append(__pyx_v_token_pieces, __pyx_t_5); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(0, 49, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "curated_tokenizers/_wordpiece.pyx":50 + * token_ids.append(match.piece_id) + * token_pieces.append(f"{prefix}{token[:match.prefix_len]}") + * token = token[match.prefix_len:] # <<<<<<<<<<<<<< + * is_initial = False + * prefix = "##" + */ + __pyx_t_5 = __Pyx_PyObject_GetSlice(__pyx_v_token, __pyx_v_match.prefix_len, 0, NULL, NULL, NULL, 1, 0, 1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 50, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF_SET(__pyx_v_token, __pyx_t_5); + __pyx_t_5 = 0; + + /* "curated_tokenizers/_wordpiece.pyx":51 + * token_pieces.append(f"{prefix}{token[:match.prefix_len]}") + * token = token[match.prefix_len:] + * is_initial = False # <<<<<<<<<<<<<< + * prefix = "##" + * return token_ids, token_pieces + */ + __pyx_v_is_initial = 0; + + /* "curated_tokenizers/_wordpiece.pyx":52 + * token = token[match.prefix_len:] + * is_initial = False + * prefix = "##" # <<<<<<<<<<<<<< + * return token_ids, token_pieces + * + */ + __Pyx_INCREF(__pyx_kp_s_); + __Pyx_DECREF_SET(__pyx_v_prefix, __pyx_kp_s_); + } + + /* "curated_tokenizers/_wordpiece.pyx":53 + * is_initial = False + * prefix = "##" + * return token_ids, token_pieces # <<<<<<<<<<<<<< + * + * def decode(self, pieces: Iterable[int]) -> str: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 53, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_INCREF(__pyx_v_token_ids); + __Pyx_GIVEREF(__pyx_v_token_ids); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_token_ids)) __PYX_ERR(0, 53, __pyx_L1_error); + __Pyx_INCREF(__pyx_v_token_pieces); + __Pyx_GIVEREF(__pyx_v_token_pieces); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_v_token_pieces)) __PYX_ERR(0, 53, __pyx_L1_error); + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L0; + + /* "curated_tokenizers/_wordpiece.pyx":28 + * return WordPieceProcessor(self.to_list()) + * + * def encode(self, token: str) -> Tuple[List[int], List[str]]: # <<<<<<<<<<<<<< + * """ + * Encode a token using word pieces. The piece identifiers are + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_AddTraceback("curated_tokenizers._wordpiece.WordPieceProcessor.encode", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_token_ids); + __Pyx_XDECREF(__pyx_v_token_pieces); + __Pyx_XDECREF(__pyx_v_prefix); + __Pyx_XDECREF(__pyx_v_token); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_wordpiece.pyx":55 + * return token_ids, token_pieces + * + * def decode(self, pieces: Iterable[int]) -> str: # <<<<<<<<<<<<<< + * """ + * Decode token piece identifiers into string. Raises a `RuntimeError` + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_9decode(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_8decode, "WordPieceProcessor.decode(self, pieces: Iterable[int]) -> str\n\n Decode token piece identifiers into string. Raises a `RuntimeError` \n if any of the identifiers are invalid.\n\n ids (Iterable[int]): Piece IDs.\n RETURNS (str): Decoded string.\n "); +static PyMethodDef __pyx_mdef_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_9decode = {"decode", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_9decode, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_8decode}; +static PyObject *__pyx_pw_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_9decode(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_pieces = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("decode (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_MACROS + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject **__pyx_pyargnames[] = {&__pyx_n_s_pieces,0}; + if (__pyx_kwds) { + Py_ssize_t kw_args; + switch (__pyx_nargs) { + case 1: values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = __Pyx_NumKwargs_FASTCALL(__pyx_kwds); + switch (__pyx_nargs) { + case 0: + if (likely((values[0] = __Pyx_GetKwValue_FASTCALL(__pyx_kwds, __pyx_kwvalues, __pyx_n_s_pieces)) != 0)) { + (void)__Pyx_Arg_NewRef_FASTCALL(values[0]); + kw_args--; + } + else if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 55, __pyx_L3_error) + else goto __pyx_L5_argtuple_error; + } + if (unlikely(kw_args > 0)) { + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values + 0, kwd_pos_args, "decode") < 0)) __PYX_ERR(0, 55, __pyx_L3_error) + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + } + __pyx_v_pieces = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("decode", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 55, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_AddTraceback("curated_tokenizers._wordpiece.WordPieceProcessor.decode", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_8decode(((struct __pyx_obj_18curated_tokenizers_10_wordpiece_WordPieceProcessor *)__pyx_v_self), __pyx_v_pieces); + + /* function exit code */ + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_8decode(struct __pyx_obj_18curated_tokenizers_10_wordpiece_WordPieceProcessor *__pyx_v_self, PyObject *__pyx_v_pieces) { + PyObject *__pyx_v_token_pieces = NULL; + PyObject *__pyx_v_id = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + Py_ssize_t __pyx_t_3; + PyObject *(*__pyx_t_4)(PyObject *); + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + int __pyx_t_8; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("decode", 1); + + /* "curated_tokenizers/_wordpiece.pyx":63 + * RETURNS (str): Decoded string. + * """ + * token_pieces = [self.id_to_piece(id)[0] for id in pieces] # <<<<<<<<<<<<<< + * return "".join(token_pieces) + * + */ + __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 63, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + if (likely(PyList_CheckExact(__pyx_v_pieces)) || PyTuple_CheckExact(__pyx_v_pieces)) { + __pyx_t_2 = __pyx_v_pieces; __Pyx_INCREF(__pyx_t_2); + __pyx_t_3 = 0; + __pyx_t_4 = NULL; + } else { + __pyx_t_3 = -1; __pyx_t_2 = PyObject_GetIter(__pyx_v_pieces); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 63, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = __Pyx_PyObject_GetIterNextFunc(__pyx_t_2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 63, __pyx_L1_error) + } + for (;;) { + if (likely(!__pyx_t_4)) { + if (likely(PyList_CheckExact(__pyx_t_2))) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_2); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 63, __pyx_L1_error) + #endif + if (__pyx_t_3 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_5 = PyList_GET_ITEM(__pyx_t_2, __pyx_t_3); __Pyx_INCREF(__pyx_t_5); __pyx_t_3++; if (unlikely((0 < 0))) __PYX_ERR(0, 63, __pyx_L1_error) + #else + __pyx_t_5 = __Pyx_PySequence_ITEM(__pyx_t_2, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 63, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + #endif + } else { + { + Py_ssize_t __pyx_temp = __Pyx_PyTuple_GET_SIZE(__pyx_t_2); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 63, __pyx_L1_error) + #endif + if (__pyx_t_3 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_5 = PyTuple_GET_ITEM(__pyx_t_2, __pyx_t_3); __Pyx_INCREF(__pyx_t_5); __pyx_t_3++; if (unlikely((0 < 0))) __PYX_ERR(0, 63, __pyx_L1_error) + #else + __pyx_t_5 = __Pyx_PySequence_ITEM(__pyx_t_2, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 63, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + #endif + } + } else { + __pyx_t_5 = __pyx_t_4(__pyx_t_2); + if (unlikely(!__pyx_t_5)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else __PYX_ERR(0, 63, __pyx_L1_error) + } + break; + } + __Pyx_GOTREF(__pyx_t_5); + } + __Pyx_XDECREF_SET(__pyx_v_id, __pyx_t_5); + __pyx_t_5 = 0; + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_id_to_piece); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 63, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = NULL; + __pyx_t_8 = 0; + #if CYTHON_UNPACK_METHODS + if (likely(PyMethod_Check(__pyx_t_6))) { + __pyx_t_7 = PyMethod_GET_SELF(__pyx_t_6); + if (likely(__pyx_t_7)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_6); + __Pyx_INCREF(__pyx_t_7); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_6, function); + __pyx_t_8 = 1; + } + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_7, __pyx_v_id}; + __pyx_t_5 = __Pyx_PyObject_FastCall(__pyx_t_6, __pyx_callargs+1-__pyx_t_8, 1+__pyx_t_8); + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 63, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + } + __pyx_t_6 = __Pyx_GetItemInt(__pyx_t_5, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 63, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(__Pyx_ListComp_Append(__pyx_t_1, (PyObject*)__pyx_t_6))) __PYX_ERR(0, 63, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v_token_pieces = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + + /* "curated_tokenizers/_wordpiece.pyx":64 + * """ + * token_pieces = [self.id_to_piece(id)[0] for id in pieces] + * return "".join(token_pieces) # <<<<<<<<<<<<<< + * + * def get_initial(self, piece: str) -> int: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyString_Join(__pyx_kp_s__3, __pyx_v_token_pieces); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 64, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "curated_tokenizers/_wordpiece.pyx":55 + * return token_ids, token_pieces + * + * def decode(self, pieces: Iterable[int]) -> str: # <<<<<<<<<<<<<< + * """ + * Decode token piece identifiers into string. Raises a `RuntimeError` + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_AddTraceback("curated_tokenizers._wordpiece.WordPieceProcessor.decode", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_token_pieces); + __Pyx_XDECREF(__pyx_v_id); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_wordpiece.pyx":66 + * return "".join(token_pieces) + * + * def get_initial(self, piece: str) -> int: # <<<<<<<<<<<<<< + * """ + * Returns the ID for the given initial piece. Raises a `RuntimeError` if + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_11get_initial(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_10get_initial, "WordPieceProcessor.get_initial(self, piece: str) -> int\n\n Returns the ID for the given initial piece. Raises a `RuntimeError` if \n the string isn't an initial piece.\n\n piece (str): Initial piece string.\n RETURNS (int): Piece ID.\n "); +static PyMethodDef __pyx_mdef_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_11get_initial = {"get_initial", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_11get_initial, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_10get_initial}; +static PyObject *__pyx_pw_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_11get_initial(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_piece = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("get_initial (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_MACROS + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject **__pyx_pyargnames[] = {&__pyx_n_s_piece,0}; + if (__pyx_kwds) { + Py_ssize_t kw_args; + switch (__pyx_nargs) { + case 1: values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = __Pyx_NumKwargs_FASTCALL(__pyx_kwds); + switch (__pyx_nargs) { + case 0: + if (likely((values[0] = __Pyx_GetKwValue_FASTCALL(__pyx_kwds, __pyx_kwvalues, __pyx_n_s_piece)) != 0)) { + (void)__Pyx_Arg_NewRef_FASTCALL(values[0]); + kw_args--; + } + else if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 66, __pyx_L3_error) + else goto __pyx_L5_argtuple_error; + } + if (unlikely(kw_args > 0)) { + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values + 0, kwd_pos_args, "get_initial") < 0)) __PYX_ERR(0, 66, __pyx_L3_error) + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + } + __pyx_v_piece = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("get_initial", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 66, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_AddTraceback("curated_tokenizers._wordpiece.WordPieceProcessor.get_initial", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_10get_initial(((struct __pyx_obj_18curated_tokenizers_10_wordpiece_WordPieceProcessor *)__pyx_v_self), __pyx_v_piece); + + /* function exit code */ + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_10get_initial(struct __pyx_obj_18curated_tokenizers_10_wordpiece_WordPieceProcessor *__pyx_v_self, PyObject *__pyx_v_piece) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_t_4; + std::string __pyx_t_5; + size_t __pyx_t_6; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_initial", 1); + + /* "curated_tokenizers/_wordpiece.pyx":74 + * RETURNS (int): Piece ID. + * """ + * return self._pieces.piece_to_id(Piece(piece.encode('utf8'), True)) # <<<<<<<<<<<<<< + * + * def id_to_piece(self, piece: int) -> Tuple[str, bool]: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_piece, __pyx_n_s_encode); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 74, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = NULL; + __pyx_t_4 = 0; + #if CYTHON_UNPACK_METHODS + if (likely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2); + if (likely(__pyx_t_3)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_2, function); + __pyx_t_4 = 1; + } + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_n_s_utf8}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_2, __pyx_callargs+1-__pyx_t_4, 1+__pyx_t_4); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 74, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } + __pyx_t_5 = __pyx_convert_string_from_py_std__in_string(__pyx_t_1); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 74, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + try { + __pyx_t_6 = __pyx_v_self->_pieces.piece_to_id(Piece(__pyx_t_5, 1)); + } catch(...) { + __Pyx_CppExn2PyErr(); + __PYX_ERR(0, 74, __pyx_L1_error) + } + __pyx_t_1 = __Pyx_PyInt_FromSize_t(__pyx_t_6); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 74, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "curated_tokenizers/_wordpiece.pyx":66 + * return "".join(token_pieces) + * + * def get_initial(self, piece: str) -> int: # <<<<<<<<<<<<<< + * """ + * Returns the ID for the given initial piece. Raises a `RuntimeError` if + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("curated_tokenizers._wordpiece.WordPieceProcessor.get_initial", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_wordpiece.pyx":76 + * return self._pieces.piece_to_id(Piece(piece.encode('utf8'), True)) + * + * def id_to_piece(self, piece: int) -> Tuple[str, bool]: # <<<<<<<<<<<<<< + * """ + * Returns the piece string (without any prefix) for a given piece identifier + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_13id_to_piece(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_12id_to_piece, "WordPieceProcessor.id_to_piece(self, piece: int) -> Tuple[str, bool]\n\n Returns the piece string (without any prefix) for a given piece identifier \n and a boolean identifying if it is an initial piece. Raises a `RuntimeError` if \n any of the identifiers are invalid.\n\n piece (int): Piece ID.\n RETURNS (Tuple[str, bool]): Piece string and a boolean identifying if\n it is an initial piece.\n "); +static PyMethodDef __pyx_mdef_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_13id_to_piece = {"id_to_piece", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_13id_to_piece, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_12id_to_piece}; +static PyObject *__pyx_pw_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_13id_to_piece(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_piece = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("id_to_piece (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_MACROS + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject **__pyx_pyargnames[] = {&__pyx_n_s_piece,0}; + if (__pyx_kwds) { + Py_ssize_t kw_args; + switch (__pyx_nargs) { + case 1: values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = __Pyx_NumKwargs_FASTCALL(__pyx_kwds); + switch (__pyx_nargs) { + case 0: + if (likely((values[0] = __Pyx_GetKwValue_FASTCALL(__pyx_kwds, __pyx_kwvalues, __pyx_n_s_piece)) != 0)) { + (void)__Pyx_Arg_NewRef_FASTCALL(values[0]); + kw_args--; + } + else if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 76, __pyx_L3_error) + else goto __pyx_L5_argtuple_error; + } + if (unlikely(kw_args > 0)) { + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values + 0, kwd_pos_args, "id_to_piece") < 0)) __PYX_ERR(0, 76, __pyx_L3_error) + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + } + __pyx_v_piece = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("id_to_piece", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 76, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_AddTraceback("curated_tokenizers._wordpiece.WordPieceProcessor.id_to_piece", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_12id_to_piece(((struct __pyx_obj_18curated_tokenizers_10_wordpiece_WordPieceProcessor *)__pyx_v_self), __pyx_v_piece); + + /* function exit code */ + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_12id_to_piece(struct __pyx_obj_18curated_tokenizers_10_wordpiece_WordPieceProcessor *__pyx_v_self, PyObject *__pyx_v_piece) { + Piece const *__pyx_v_ptr_piece; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + __Pyx_FakeReference __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("id_to_piece", 1); + + /* "curated_tokenizers/_wordpiece.pyx":86 + * it is an initial piece. + * """ + * cdef const Piece* ptr_piece = &self._pieces.id_to_piece(piece) # <<<<<<<<<<<<<< + * return (ptr_piece[0].piece.decode('utf8'), ptr_piece[0].is_initial) + * + */ + __pyx_t_1 = __Pyx_PyInt_As_int(__pyx_v_piece); if (unlikely((__pyx_t_1 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 86, __pyx_L1_error) + try { + __pyx_t_2 = __pyx_v_self->_pieces.id_to_piece(__pyx_t_1); + } catch(...) { + __Pyx_CppExn2PyErr(); + __PYX_ERR(0, 86, __pyx_L1_error) + } + __pyx_v_ptr_piece = (&__pyx_t_2); + + /* "curated_tokenizers/_wordpiece.pyx":87 + * """ + * cdef const Piece* ptr_piece = &self._pieces.id_to_piece(piece) + * return (ptr_piece[0].piece.decode('utf8'), ptr_piece[0].is_initial) # <<<<<<<<<<<<<< + * + * def is_valid_piece_id(self, piece: int) -> bool: + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = __Pyx_decode_cpp_string((__pyx_v_ptr_piece[0]).piece, 0, PY_SSIZE_T_MAX, NULL, NULL, PyUnicode_DecodeUTF8); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 87, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_PyBool_FromLong((__pyx_v_ptr_piece[0]).is_initial); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 87, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 87, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_GIVEREF(__pyx_t_3); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_3)) __PYX_ERR(0, 87, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_4); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_4)) __PYX_ERR(0, 87, __pyx_L1_error); + __pyx_t_3 = 0; + __pyx_t_4 = 0; + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L0; + + /* "curated_tokenizers/_wordpiece.pyx":76 + * return self._pieces.piece_to_id(Piece(piece.encode('utf8'), True)) + * + * def id_to_piece(self, piece: int) -> Tuple[str, bool]: # <<<<<<<<<<<<<< + * """ + * Returns the piece string (without any prefix) for a given piece identifier + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("curated_tokenizers._wordpiece.WordPieceProcessor.id_to_piece", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_wordpiece.pyx":89 + * return (ptr_piece[0].piece.decode('utf8'), ptr_piece[0].is_initial) + * + * def is_valid_piece_id(self, piece: int) -> bool: # <<<<<<<<<<<<<< + * """ + * Returns True if the piece identifier is valid, False otherwise. + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_15is_valid_piece_id(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_14is_valid_piece_id, "WordPieceProcessor.is_valid_piece_id(self, piece: int) -> bool\n\n Returns True if the piece identifier is valid, False otherwise.\n\n piece (int): Piece ID.\n RETURNS (bool): Is valid.\n "); +static PyMethodDef __pyx_mdef_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_15is_valid_piece_id = {"is_valid_piece_id", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_15is_valid_piece_id, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_14is_valid_piece_id}; +static PyObject *__pyx_pw_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_15is_valid_piece_id(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_piece = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("is_valid_piece_id (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_MACROS + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject **__pyx_pyargnames[] = {&__pyx_n_s_piece,0}; + if (__pyx_kwds) { + Py_ssize_t kw_args; + switch (__pyx_nargs) { + case 1: values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = __Pyx_NumKwargs_FASTCALL(__pyx_kwds); + switch (__pyx_nargs) { + case 0: + if (likely((values[0] = __Pyx_GetKwValue_FASTCALL(__pyx_kwds, __pyx_kwvalues, __pyx_n_s_piece)) != 0)) { + (void)__Pyx_Arg_NewRef_FASTCALL(values[0]); + kw_args--; + } + else if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 89, __pyx_L3_error) + else goto __pyx_L5_argtuple_error; + } + if (unlikely(kw_args > 0)) { + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values + 0, kwd_pos_args, "is_valid_piece_id") < 0)) __PYX_ERR(0, 89, __pyx_L3_error) + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + } + __pyx_v_piece = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("is_valid_piece_id", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 89, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_AddTraceback("curated_tokenizers._wordpiece.WordPieceProcessor.is_valid_piece_id", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_14is_valid_piece_id(((struct __pyx_obj_18curated_tokenizers_10_wordpiece_WordPieceProcessor *)__pyx_v_self), __pyx_v_piece); + + /* function exit code */ + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_14is_valid_piece_id(struct __pyx_obj_18curated_tokenizers_10_wordpiece_WordPieceProcessor *__pyx_v_self, PyObject *__pyx_v_piece) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("is_valid_piece_id", 1); + + /* "curated_tokenizers/_wordpiece.pyx":96 + * RETURNS (bool): Is valid. + * """ + * return 0 <= piece <= self._pieces.size() - 1 # <<<<<<<<<<<<<< + * + * @staticmethod + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyObject_RichCompare(__pyx_int_0, __pyx_v_piece, Py_LE); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 96, __pyx_L1_error) + if (__Pyx_PyObject_IsTrue(__pyx_t_1)) { + __Pyx_DECREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyInt_FromSize_t((__pyx_v_self->_pieces.size() - 1)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 96, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = PyObject_RichCompare(__pyx_v_piece, __pyx_t_2, Py_LE); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 96, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "curated_tokenizers/_wordpiece.pyx":89 + * return (ptr_piece[0].piece.decode('utf8'), ptr_piece[0].is_initial) + * + * def is_valid_piece_id(self, piece: int) -> bool: # <<<<<<<<<<<<<< + * """ + * Returns True if the piece identifier is valid, False otherwise. + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("curated_tokenizers._wordpiece.WordPieceProcessor.is_valid_piece_id", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_wordpiece.pyx":98 + * return 0 <= piece <= self._pieces.size() - 1 + * + * @staticmethod # <<<<<<<<<<<<<< + * def from_file(filename: str) -> WordPieceProcessor: + * with open(filename, encoding="utf8") as f: + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_17from_file(CYTHON_UNUSED PyObject *__pyx_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_16from_file, "WordPieceProcessor.from_file(filename: str) -> WordPieceProcessor"); +static PyMethodDef __pyx_mdef_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_17from_file = {"from_file", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_17from_file, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_16from_file}; +static PyObject *__pyx_pw_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_17from_file(CYTHON_UNUSED PyObject *__pyx_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_filename = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("from_file (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_MACROS + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject **__pyx_pyargnames[] = {&__pyx_n_s_filename,0}; + if (__pyx_kwds) { + Py_ssize_t kw_args; + switch (__pyx_nargs) { + case 1: values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = __Pyx_NumKwargs_FASTCALL(__pyx_kwds); + switch (__pyx_nargs) { + case 0: + if (likely((values[0] = __Pyx_GetKwValue_FASTCALL(__pyx_kwds, __pyx_kwvalues, __pyx_n_s_filename)) != 0)) { + (void)__Pyx_Arg_NewRef_FASTCALL(values[0]); + kw_args--; + } + else if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 98, __pyx_L3_error) + else goto __pyx_L5_argtuple_error; + } + if (unlikely(kw_args > 0)) { + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values + 0, kwd_pos_args, "from_file") < 0)) __PYX_ERR(0, 98, __pyx_L3_error) + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + } + __pyx_v_filename = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("from_file", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 98, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_AddTraceback("curated_tokenizers._wordpiece.WordPieceProcessor.from_file", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_16from_file(__pyx_v_filename); + + /* function exit code */ + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_16from_file(PyObject *__pyx_v_filename) { + PyObject *__pyx_v_f = NULL; + PyObject *__pyx_v_pieces = NULL; + PyObject *__pyx_v_line = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + int __pyx_t_6; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + Py_ssize_t __pyx_t_10; + PyObject *(*__pyx_t_11)(PyObject *); + PyObject *__pyx_t_12 = NULL; + PyObject *__pyx_t_13 = NULL; + int __pyx_t_14; + int __pyx_t_15; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("from_file", 1); + + /* "curated_tokenizers/_wordpiece.pyx":100 + * @staticmethod + * def from_file(filename: str) -> WordPieceProcessor: + * with open(filename, encoding="utf8") as f: # <<<<<<<<<<<<<< + * pieces = [line.strip() for line in f] + * return WordPieceProcessor(pieces) + */ + /*with:*/ { + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 100, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_filename); + __Pyx_GIVEREF(__pyx_v_filename); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_filename)) __PYX_ERR(0, 100, __pyx_L1_error); + __pyx_t_2 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 100, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_encoding, __pyx_n_s_utf8) < 0) __PYX_ERR(0, 100, __pyx_L1_error) + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_open, __pyx_t_1, __pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 100, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_4 = __Pyx_PyObject_LookupSpecial(__pyx_t_3, __pyx_n_s_exit); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 100, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_1 = __Pyx_PyObject_LookupSpecial(__pyx_t_3, __pyx_n_s_enter); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 100, __pyx_L3_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_5 = NULL; + __pyx_t_6 = 0; + #if CYTHON_UNPACK_METHODS + if (likely(PyMethod_Check(__pyx_t_1))) { + __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_1); + if (likely(__pyx_t_5)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_1); + __Pyx_INCREF(__pyx_t_5); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_1, function); + __pyx_t_6 = 1; + } + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_5, NULL}; + __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_1, __pyx_callargs+1-__pyx_t_6, 0+__pyx_t_6); + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 100, __pyx_L3_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } + __pyx_t_1 = __pyx_t_2; + __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + /*try:*/ { + { + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + __Pyx_ExceptionSave(&__pyx_t_7, &__pyx_t_8, &__pyx_t_9); + __Pyx_XGOTREF(__pyx_t_7); + __Pyx_XGOTREF(__pyx_t_8); + __Pyx_XGOTREF(__pyx_t_9); + /*try:*/ { + __pyx_v_f = __pyx_t_1; + __pyx_t_1 = 0; + + /* "curated_tokenizers/_wordpiece.pyx":101 + * def from_file(filename: str) -> WordPieceProcessor: + * with open(filename, encoding="utf8") as f: + * pieces = [line.strip() for line in f] # <<<<<<<<<<<<<< + * return WordPieceProcessor(pieces) + * + */ + __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 101, __pyx_L7_error) + __Pyx_GOTREF(__pyx_t_1); + if (likely(PyList_CheckExact(__pyx_v_f)) || PyTuple_CheckExact(__pyx_v_f)) { + __pyx_t_3 = __pyx_v_f; __Pyx_INCREF(__pyx_t_3); + __pyx_t_10 = 0; + __pyx_t_11 = NULL; + } else { + __pyx_t_10 = -1; __pyx_t_3 = PyObject_GetIter(__pyx_v_f); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 101, __pyx_L7_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_11 = __Pyx_PyObject_GetIterNextFunc(__pyx_t_3); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 101, __pyx_L7_error) + } + for (;;) { + if (likely(!__pyx_t_11)) { + if (likely(PyList_CheckExact(__pyx_t_3))) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_3); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 101, __pyx_L7_error) + #endif + if (__pyx_t_10 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_2 = PyList_GET_ITEM(__pyx_t_3, __pyx_t_10); __Pyx_INCREF(__pyx_t_2); __pyx_t_10++; if (unlikely((0 < 0))) __PYX_ERR(0, 101, __pyx_L7_error) + #else + __pyx_t_2 = __Pyx_PySequence_ITEM(__pyx_t_3, __pyx_t_10); __pyx_t_10++; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 101, __pyx_L7_error) + __Pyx_GOTREF(__pyx_t_2); + #endif + } else { + { + Py_ssize_t __pyx_temp = __Pyx_PyTuple_GET_SIZE(__pyx_t_3); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 101, __pyx_L7_error) + #endif + if (__pyx_t_10 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_2 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_10); __Pyx_INCREF(__pyx_t_2); __pyx_t_10++; if (unlikely((0 < 0))) __PYX_ERR(0, 101, __pyx_L7_error) + #else + __pyx_t_2 = __Pyx_PySequence_ITEM(__pyx_t_3, __pyx_t_10); __pyx_t_10++; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 101, __pyx_L7_error) + __Pyx_GOTREF(__pyx_t_2); + #endif + } + } else { + __pyx_t_2 = __pyx_t_11(__pyx_t_3); + if (unlikely(!__pyx_t_2)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else __PYX_ERR(0, 101, __pyx_L7_error) + } + break; + } + __Pyx_GOTREF(__pyx_t_2); + } + __Pyx_XDECREF_SET(__pyx_v_line, __pyx_t_2); + __pyx_t_2 = 0; + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_line, __pyx_n_s_strip); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 101, __pyx_L7_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_12 = NULL; + __pyx_t_6 = 0; + #if CYTHON_UNPACK_METHODS + if (likely(PyMethod_Check(__pyx_t_5))) { + __pyx_t_12 = PyMethod_GET_SELF(__pyx_t_5); + if (likely(__pyx_t_12)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_5); + __Pyx_INCREF(__pyx_t_12); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_5, function); + __pyx_t_6 = 1; + } + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_12, NULL}; + __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_5, __pyx_callargs+1-__pyx_t_6, 0+__pyx_t_6); + __Pyx_XDECREF(__pyx_t_12); __pyx_t_12 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 101, __pyx_L7_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + } + if (unlikely(__Pyx_ListComp_Append(__pyx_t_1, (PyObject*)__pyx_t_2))) __PYX_ERR(0, 101, __pyx_L7_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_pieces = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + + /* "curated_tokenizers/_wordpiece.pyx":100 + * @staticmethod + * def from_file(filename: str) -> WordPieceProcessor: + * with open(filename, encoding="utf8") as f: # <<<<<<<<<<<<<< + * pieces = [line.strip() for line in f] + * return WordPieceProcessor(pieces) + */ + } + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; + goto __pyx_L12_try_end; + __pyx_L7_error:; + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_XDECREF(__pyx_t_12); __pyx_t_12 = 0; + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + /*except:*/ { + __Pyx_AddTraceback("curated_tokenizers._wordpiece.WordPieceProcessor.from_file", __pyx_clineno, __pyx_lineno, __pyx_filename); + if (__Pyx_GetException(&__pyx_t_1, &__pyx_t_3, &__pyx_t_2) < 0) __PYX_ERR(0, 100, __pyx_L9_except_error) + __Pyx_XGOTREF(__pyx_t_1); + __Pyx_XGOTREF(__pyx_t_3); + __Pyx_XGOTREF(__pyx_t_2); + __pyx_t_5 = PyTuple_Pack(3, __pyx_t_1, __pyx_t_3, __pyx_t_2); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 100, __pyx_L9_except_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_13 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_5, NULL); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_13)) __PYX_ERR(0, 100, __pyx_L9_except_error) + __Pyx_GOTREF(__pyx_t_13); + __pyx_t_14 = __Pyx_PyObject_IsTrue(__pyx_t_13); + __Pyx_DECREF(__pyx_t_13); __pyx_t_13 = 0; + if (__pyx_t_14 < 0) __PYX_ERR(0, 100, __pyx_L9_except_error) + __pyx_t_15 = (!__pyx_t_14); + if (unlikely(__pyx_t_15)) { + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_2); + __Pyx_ErrRestoreWithState(__pyx_t_1, __pyx_t_3, __pyx_t_2); + __pyx_t_1 = 0; __pyx_t_3 = 0; __pyx_t_2 = 0; + __PYX_ERR(0, 100, __pyx_L9_except_error) + } + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + goto __pyx_L8_exception_handled; + } + __pyx_L9_except_error:; + __Pyx_XGIVEREF(__pyx_t_7); + __Pyx_XGIVEREF(__pyx_t_8); + __Pyx_XGIVEREF(__pyx_t_9); + __Pyx_ExceptionReset(__pyx_t_7, __pyx_t_8, __pyx_t_9); + goto __pyx_L1_error; + __pyx_L8_exception_handled:; + __Pyx_XGIVEREF(__pyx_t_7); + __Pyx_XGIVEREF(__pyx_t_8); + __Pyx_XGIVEREF(__pyx_t_9); + __Pyx_ExceptionReset(__pyx_t_7, __pyx_t_8, __pyx_t_9); + __pyx_L12_try_end:; + } + } + /*finally:*/ { + /*normal exit:*/{ + if (__pyx_t_4) { + __pyx_t_9 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_tuple__4, NULL); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 100, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + } + goto __pyx_L6; + } + __pyx_L6:; + } + goto __pyx_L19; + __pyx_L3_error:; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + goto __pyx_L1_error; + __pyx_L19:; + } + + /* "curated_tokenizers/_wordpiece.pyx":102 + * with open(filename, encoding="utf8") as f: + * pieces = [line.strip() for line in f] + * return WordPieceProcessor(pieces) # <<<<<<<<<<<<<< + * + * def to_list(self): + */ + __Pyx_XDECREF(__pyx_r); + if (unlikely(!__pyx_v_pieces)) { __Pyx_RaiseUnboundLocalError("pieces"); __PYX_ERR(0, 102, __pyx_L1_error) } + __pyx_t_2 = __Pyx_PyObject_CallOneArg(((PyObject *)__pyx_ptype_18curated_tokenizers_10_wordpiece_WordPieceProcessor), __pyx_v_pieces); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 102, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "curated_tokenizers/_wordpiece.pyx":98 + * return 0 <= piece <= self._pieces.size() - 1 + * + * @staticmethod # <<<<<<<<<<<<<< + * def from_file(filename: str) -> WordPieceProcessor: + * with open(filename, encoding="utf8") as f: + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_12); + __Pyx_AddTraceback("curated_tokenizers._wordpiece.WordPieceProcessor.from_file", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_f); + __Pyx_XDECREF(__pyx_v_pieces); + __Pyx_XDECREF(__pyx_v_line); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_wordpiece.pyx":104 + * return WordPieceProcessor(pieces) + * + * def to_list(self): # <<<<<<<<<<<<<< + * pieces = [None] * self._pieces.size() + * cdef Piece piece + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_19to_list(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_18to_list, "WordPieceProcessor.to_list(self)"); +static PyMethodDef __pyx_mdef_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_19to_list = {"to_list", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_19to_list, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_18to_list}; +static PyObject *__pyx_pw_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_19to_list(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("to_list (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_MACROS + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { + __Pyx_RaiseArgtupleInvalid("to_list", 1, 0, 0, __pyx_nargs); return NULL;} + if (unlikely(__pyx_kwds) && __Pyx_NumKwargs_FASTCALL(__pyx_kwds) && unlikely(!__Pyx_CheckKeywordStrings(__pyx_kwds, "to_list", 0))) return NULL; + __pyx_r = __pyx_pf_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_18to_list(((struct __pyx_obj_18curated_tokenizers_10_wordpiece_WordPieceProcessor *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_18to_list(struct __pyx_obj_18curated_tokenizers_10_wordpiece_WordPieceProcessor *__pyx_v_self) { + PyObject *__pyx_v_pieces = NULL; + Piece __pyx_v_piece; + size_t __pyx_v_i; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + size_t __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + size_t __pyx_t_3; + size_t __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("to_list", 1); + + /* "curated_tokenizers/_wordpiece.pyx":105 + * + * def to_list(self): + * pieces = [None] * self._pieces.size() # <<<<<<<<<<<<<< + * cdef Piece piece + * for i in range(self._pieces.size()): + */ + __pyx_t_1 = __pyx_v_self->_pieces.size(); + __pyx_t_2 = PyList_New(1 * (__pyx_t_1)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 105, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + { Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < __pyx_t_1; __pyx_temp++) { + __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(Py_None); + if (__Pyx_PyList_SET_ITEM(__pyx_t_2, __pyx_temp, Py_None)) __PYX_ERR(0, 105, __pyx_L1_error); + } + } + __pyx_v_pieces = ((PyObject*)__pyx_t_2); + __pyx_t_2 = 0; + + /* "curated_tokenizers/_wordpiece.pyx":107 + * pieces = [None] * self._pieces.size() + * cdef Piece piece + * for i in range(self._pieces.size()): # <<<<<<<<<<<<<< + * piece = self._pieces._id_to_piece[i] + * if piece.is_initial: + */ + __pyx_t_1 = __pyx_v_self->_pieces.size(); + __pyx_t_3 = __pyx_t_1; + for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { + __pyx_v_i = __pyx_t_4; + + /* "curated_tokenizers/_wordpiece.pyx":108 + * cdef Piece piece + * for i in range(self._pieces.size()): + * piece = self._pieces._id_to_piece[i] # <<<<<<<<<<<<<< + * if piece.is_initial: + * pieces[i] = piece.piece.decode('utf8') + */ + __pyx_v_piece = (__pyx_v_self->_pieces._id_to_piece[__pyx_v_i]); + + /* "curated_tokenizers/_wordpiece.pyx":109 + * for i in range(self._pieces.size()): + * piece = self._pieces._id_to_piece[i] + * if piece.is_initial: # <<<<<<<<<<<<<< + * pieces[i] = piece.piece.decode('utf8') + * else: + */ + if (__pyx_v_piece.is_initial) { + + /* "curated_tokenizers/_wordpiece.pyx":110 + * piece = self._pieces._id_to_piece[i] + * if piece.is_initial: + * pieces[i] = piece.piece.decode('utf8') # <<<<<<<<<<<<<< + * else: + * pieces[i] = f"##{piece.piece.decode('utf8')}" + */ + __pyx_t_2 = __Pyx_decode_cpp_string(__pyx_v_piece.piece, 0, PY_SSIZE_T_MAX, NULL, NULL, PyUnicode_DecodeUTF8); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 110, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (unlikely((__Pyx_SetItemInt(__pyx_v_pieces, __pyx_v_i, __pyx_t_2, size_t, 0, __Pyx_PyInt_FromSize_t, 1, 0, 1) < 0))) __PYX_ERR(0, 110, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "curated_tokenizers/_wordpiece.pyx":109 + * for i in range(self._pieces.size()): + * piece = self._pieces._id_to_piece[i] + * if piece.is_initial: # <<<<<<<<<<<<<< + * pieces[i] = piece.piece.decode('utf8') + * else: + */ + goto __pyx_L5; + } + + /* "curated_tokenizers/_wordpiece.pyx":112 + * pieces[i] = piece.piece.decode('utf8') + * else: + * pieces[i] = f"##{piece.piece.decode('utf8')}" # <<<<<<<<<<<<<< + * + * return pieces + */ + /*else*/ { + __pyx_t_2 = __Pyx_decode_cpp_string(__pyx_v_piece.piece, 0, PY_SSIZE_T_MAX, NULL, NULL, PyUnicode_DecodeUTF8); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 112, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_5 = __Pyx_PyUnicode_Concat(__pyx_kp_u_, __pyx_t_2); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 112, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely((__Pyx_SetItemInt(__pyx_v_pieces, __pyx_v_i, __pyx_t_5, size_t, 0, __Pyx_PyInt_FromSize_t, 1, 0, 1) < 0))) __PYX_ERR(0, 112, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + } + __pyx_L5:; + } + + /* "curated_tokenizers/_wordpiece.pyx":114 + * pieces[i] = f"##{piece.piece.decode('utf8')}" + * + * return pieces # <<<<<<<<<<<<<< + * + * cdef PieceMatch _find_longest_prefix(self, str token, bint is_initial): + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_pieces); + __pyx_r = __pyx_v_pieces; + goto __pyx_L0; + + /* "curated_tokenizers/_wordpiece.pyx":104 + * return WordPieceProcessor(pieces) + * + * def to_list(self): # <<<<<<<<<<<<<< + * pieces = [None] * self._pieces.size() + * cdef Piece piece + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("curated_tokenizers._wordpiece.WordPieceProcessor.to_list", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_pieces); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_wordpiece.pyx":116 + * return pieces + * + * cdef PieceMatch _find_longest_prefix(self, str token, bint is_initial): # <<<<<<<<<<<<<< + * cdef PieceMatch match + * match.found = False + */ + +static struct __pyx_t_18curated_tokenizers_10_wordpiece_PieceMatch __pyx_f_18curated_tokenizers_10_wordpiece_18WordPieceProcessor__find_longest_prefix(struct __pyx_obj_18curated_tokenizers_10_wordpiece_WordPieceProcessor *__pyx_v_self, PyObject *__pyx_v_token, int __pyx_v_is_initial) { + struct __pyx_t_18curated_tokenizers_10_wordpiece_PieceMatch __pyx_v_match; + Piece __pyx_v_piece; + Py_ssize_t __pyx_v_prefix_len; + int __pyx_v_idx; + struct __pyx_t_18curated_tokenizers_10_wordpiece_PieceMatch __pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + Py_ssize_t __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + int __pyx_t_6; + std::string __pyx_t_7; + int __pyx_t_8; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("_find_longest_prefix", 1); + + /* "curated_tokenizers/_wordpiece.pyx":118 + * cdef PieceMatch _find_longest_prefix(self, str token, bint is_initial): + * cdef PieceMatch match + * match.found = False # <<<<<<<<<<<<<< + * + * cdef Piece piece + */ + __pyx_v_match.found = 0; + + /* "curated_tokenizers/_wordpiece.pyx":121 + * + * cdef Piece piece + * for prefix_len in reversed(range(len(token) + 1)): # <<<<<<<<<<<<<< + * piece = Piece(token[:prefix_len].encode("utf8"), is_initial) + * idx = self._pieces.try_piece_to_id(piece) + */ + __pyx_t_1 = PyObject_Length(__pyx_v_token); if (unlikely(__pyx_t_1 == ((Py_ssize_t)-1))) __PYX_ERR(0, 121, __pyx_L1_error) + for (__pyx_t_2 = (__pyx_t_1 + 1)-1; __pyx_t_2 >= 0; __pyx_t_2-=1) { + __pyx_v_prefix_len = __pyx_t_2; + + /* "curated_tokenizers/_wordpiece.pyx":122 + * cdef Piece piece + * for prefix_len in reversed(range(len(token) + 1)): + * piece = Piece(token[:prefix_len].encode("utf8"), is_initial) # <<<<<<<<<<<<<< + * idx = self._pieces.try_piece_to_id(piece) + * if idx != -1: + */ + if (unlikely(__pyx_v_token == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); + __PYX_ERR(0, 122, __pyx_L1_error) + } + __pyx_t_4 = PySequence_GetSlice(__pyx_v_token, 0, __pyx_v_prefix_len); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 122, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_encode); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 122, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = NULL; + __pyx_t_6 = 0; + #if CYTHON_UNPACK_METHODS + if (likely(PyMethod_Check(__pyx_t_5))) { + __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_5); + if (likely(__pyx_t_4)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_5); + __Pyx_INCREF(__pyx_t_4); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_5, function); + __pyx_t_6 = 1; + } + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_n_s_utf8}; + __pyx_t_3 = __Pyx_PyObject_FastCall(__pyx_t_5, __pyx_callargs+1-__pyx_t_6, 1+__pyx_t_6); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 122, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + } + __pyx_t_7 = __pyx_convert_string_from_py_std__in_string(__pyx_t_3); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 122, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_piece = Piece(__pyx_t_7, __pyx_v_is_initial); + + /* "curated_tokenizers/_wordpiece.pyx":123 + * for prefix_len in reversed(range(len(token) + 1)): + * piece = Piece(token[:prefix_len].encode("utf8"), is_initial) + * idx = self._pieces.try_piece_to_id(piece) # <<<<<<<<<<<<<< + * if idx != -1: + * match.found = True + */ + __pyx_v_idx = __pyx_v_self->_pieces.try_piece_to_id(__pyx_v_piece); + + /* "curated_tokenizers/_wordpiece.pyx":124 + * piece = Piece(token[:prefix_len].encode("utf8"), is_initial) + * idx = self._pieces.try_piece_to_id(piece) + * if idx != -1: # <<<<<<<<<<<<<< + * match.found = True + * match.prefix_len = prefix_len + */ + __pyx_t_8 = (__pyx_v_idx != -1L); + if (__pyx_t_8) { + + /* "curated_tokenizers/_wordpiece.pyx":125 + * idx = self._pieces.try_piece_to_id(piece) + * if idx != -1: + * match.found = True # <<<<<<<<<<<<<< + * match.prefix_len = prefix_len + * match.piece_id = idx + */ + __pyx_v_match.found = 1; + + /* "curated_tokenizers/_wordpiece.pyx":126 + * if idx != -1: + * match.found = True + * match.prefix_len = prefix_len # <<<<<<<<<<<<<< + * match.piece_id = idx + * return match + */ + __pyx_v_match.prefix_len = __pyx_v_prefix_len; + + /* "curated_tokenizers/_wordpiece.pyx":127 + * match.found = True + * match.prefix_len = prefix_len + * match.piece_id = idx # <<<<<<<<<<<<<< + * return match + * + */ + __pyx_v_match.piece_id = __pyx_v_idx; + + /* "curated_tokenizers/_wordpiece.pyx":128 + * match.prefix_len = prefix_len + * match.piece_id = idx + * return match # <<<<<<<<<<<<<< + * + * return match + */ + __pyx_r = __pyx_v_match; + goto __pyx_L0; + + /* "curated_tokenizers/_wordpiece.pyx":124 + * piece = Piece(token[:prefix_len].encode("utf8"), is_initial) + * idx = self._pieces.try_piece_to_id(piece) + * if idx != -1: # <<<<<<<<<<<<<< + * match.found = True + * match.prefix_len = prefix_len + */ + } + } + + /* "curated_tokenizers/_wordpiece.pyx":130 + * return match + * + * return match # <<<<<<<<<<<<<< + * + * def __reduce__(self): + */ + __pyx_r = __pyx_v_match; + goto __pyx_L0; + + /* "curated_tokenizers/_wordpiece.pyx":116 + * return pieces + * + * cdef PieceMatch _find_longest_prefix(self, str token, bint is_initial): # <<<<<<<<<<<<<< + * cdef PieceMatch match + * match.found = False + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("curated_tokenizers._wordpiece.WordPieceProcessor._find_longest_prefix", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_pretend_to_initialize(&__pyx_r); + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_wordpiece.pyx":132 + * return match + * + * def __reduce__(self): # <<<<<<<<<<<<<< + * return (unpickle_wordpiece_processor, (self.to_list(),)) + * + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_21__reduce__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_20__reduce__, "WordPieceProcessor.__reduce__(self)"); +static PyMethodDef __pyx_mdef_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_21__reduce__ = {"__reduce__", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_21__reduce__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_20__reduce__}; +static PyObject *__pyx_pw_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_21__reduce__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__reduce__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_MACROS + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { + __Pyx_RaiseArgtupleInvalid("__reduce__", 1, 0, 0, __pyx_nargs); return NULL;} + if (unlikely(__pyx_kwds) && __Pyx_NumKwargs_FASTCALL(__pyx_kwds) && unlikely(!__Pyx_CheckKeywordStrings(__pyx_kwds, "__reduce__", 0))) return NULL; + __pyx_r = __pyx_pf_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_20__reduce__(((struct __pyx_obj_18curated_tokenizers_10_wordpiece_WordPieceProcessor *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_20__reduce__(struct __pyx_obj_18curated_tokenizers_10_wordpiece_WordPieceProcessor *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + int __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__reduce__", 1); + + /* "curated_tokenizers/_wordpiece.pyx":133 + * + * def __reduce__(self): + * return (unpickle_wordpiece_processor, (self.to_list(),)) # <<<<<<<<<<<<<< + * + * def unpickle_wordpiece_processor(pieces: List[str]) -> WordPieceProcessor: + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_unpickle_wordpiece_processor); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 133, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_to_list); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 133, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = NULL; + __pyx_t_5 = 0; + #if CYTHON_UNPACK_METHODS + if (likely(PyMethod_Check(__pyx_t_3))) { + __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_3); + if (likely(__pyx_t_4)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); + __Pyx_INCREF(__pyx_t_4); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_3, function); + __pyx_t_5 = 1; + } + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, NULL}; + __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_3, __pyx_callargs+1-__pyx_t_5, 0+__pyx_t_5); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 133, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + } + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 133, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_GIVEREF(__pyx_t_2); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_2)) __PYX_ERR(0, 133, __pyx_L1_error); + __pyx_t_2 = 0; + __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 133, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_GIVEREF(__pyx_t_1); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1)) __PYX_ERR(0, 133, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_3); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_3)) __PYX_ERR(0, 133, __pyx_L1_error); + __pyx_t_1 = 0; + __pyx_t_3 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* "curated_tokenizers/_wordpiece.pyx":132 + * return match + * + * def __reduce__(self): # <<<<<<<<<<<<<< + * return (unpickle_wordpiece_processor, (self.to_list(),)) + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("curated_tokenizers._wordpiece.WordPieceProcessor.__reduce__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "curated_tokenizers/_wordpiece.pyx":135 + * return (unpickle_wordpiece_processor, (self.to_list(),)) + * + * def unpickle_wordpiece_processor(pieces: List[str]) -> WordPieceProcessor: # <<<<<<<<<<<<<< + * return WordPieceProcessor(pieces) + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_18curated_tokenizers_10_wordpiece_1unpickle_wordpiece_processor(PyObject *__pyx_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_18curated_tokenizers_10_wordpiece_unpickle_wordpiece_processor, "unpickle_wordpiece_processor(pieces: List[str]) -> WordPieceProcessor"); +static PyMethodDef __pyx_mdef_18curated_tokenizers_10_wordpiece_1unpickle_wordpiece_processor = {"unpickle_wordpiece_processor", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_10_wordpiece_1unpickle_wordpiece_processor, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_10_wordpiece_unpickle_wordpiece_processor}; +static PyObject *__pyx_pw_18curated_tokenizers_10_wordpiece_1unpickle_wordpiece_processor(PyObject *__pyx_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_pieces = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("unpickle_wordpiece_processor (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_MACROS + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject **__pyx_pyargnames[] = {&__pyx_n_s_pieces,0}; + if (__pyx_kwds) { + Py_ssize_t kw_args; + switch (__pyx_nargs) { + case 1: values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = __Pyx_NumKwargs_FASTCALL(__pyx_kwds); + switch (__pyx_nargs) { + case 0: + if (likely((values[0] = __Pyx_GetKwValue_FASTCALL(__pyx_kwds, __pyx_kwvalues, __pyx_n_s_pieces)) != 0)) { + (void)__Pyx_Arg_NewRef_FASTCALL(values[0]); + kw_args--; + } + else if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 135, __pyx_L3_error) + else goto __pyx_L5_argtuple_error; + } + if (unlikely(kw_args > 0)) { + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values + 0, kwd_pos_args, "unpickle_wordpiece_processor") < 0)) __PYX_ERR(0, 135, __pyx_L3_error) + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_Arg_FASTCALL(__pyx_args, 0); + } + __pyx_v_pieces = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("unpickle_wordpiece_processor", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 135, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_AddTraceback("curated_tokenizers._wordpiece.unpickle_wordpiece_processor", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_18curated_tokenizers_10_wordpiece_unpickle_wordpiece_processor(__pyx_self, __pyx_v_pieces); + + /* function exit code */ + { + Py_ssize_t __pyx_temp; + for (__pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + __Pyx_Arg_XDECREF_FASTCALL(values[__pyx_temp]); + } + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_18curated_tokenizers_10_wordpiece_unpickle_wordpiece_processor(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_pieces) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("unpickle_wordpiece_processor", 1); + + /* "curated_tokenizers/_wordpiece.pyx":136 + * + * def unpickle_wordpiece_processor(pieces: List[str]) -> WordPieceProcessor: + * return WordPieceProcessor(pieces) # <<<<<<<<<<<<<< + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_CallOneArg(((PyObject *)__pyx_ptype_18curated_tokenizers_10_wordpiece_WordPieceProcessor), __pyx_v_pieces); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 136, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; + + /* "curated_tokenizers/_wordpiece.pyx":135 + * return (unpickle_wordpiece_processor, (self.to_list(),)) + * + * def unpickle_wordpiece_processor(pieces: List[str]) -> WordPieceProcessor: # <<<<<<<<<<<<<< + * return WordPieceProcessor(pieces) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("curated_tokenizers._wordpiece.unpickle_wordpiece_processor", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} +static struct __pyx_vtabstruct_18curated_tokenizers_10_wordpiece_WordPieceProcessor __pyx_vtable_18curated_tokenizers_10_wordpiece_WordPieceProcessor; + +static PyObject *__pyx_tp_new_18curated_tokenizers_10_wordpiece_WordPieceProcessor(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { + struct __pyx_obj_18curated_tokenizers_10_wordpiece_WordPieceProcessor *p; + PyObject *o; + #if CYTHON_COMPILING_IN_LIMITED_API + allocfunc alloc_func = (allocfunc)PyType_GetSlot(t, Py_tp_alloc); + o = alloc_func(t, 0); + #else + if (likely(!__Pyx_PyType_HasFeature(t, Py_TPFLAGS_IS_ABSTRACT))) { + o = (*t->tp_alloc)(t, 0); + } else { + o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); + } + if (unlikely(!o)) return 0; + #endif + p = ((struct __pyx_obj_18curated_tokenizers_10_wordpiece_WordPieceProcessor *)o); + p->__pyx_vtab = __pyx_vtabptr_18curated_tokenizers_10_wordpiece_WordPieceProcessor; + new((void*)&(p->_pieces)) PieceStorage(); + return o; +} + +static void __pyx_tp_dealloc_18curated_tokenizers_10_wordpiece_WordPieceProcessor(PyObject *o) { + struct __pyx_obj_18curated_tokenizers_10_wordpiece_WordPieceProcessor *p = (struct __pyx_obj_18curated_tokenizers_10_wordpiece_WordPieceProcessor *)o; + #if CYTHON_USE_TP_FINALIZE + if (unlikely((PY_VERSION_HEX >= 0x03080000 || __Pyx_PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE)) && __Pyx_PyObject_GetSlot(o, tp_finalize, destructor)) && (!PyType_IS_GC(Py_TYPE(o)) || !__Pyx_PyObject_GC_IsFinalized(o))) { + if (__Pyx_PyObject_GetSlot(o, tp_dealloc, destructor) == __pyx_tp_dealloc_18curated_tokenizers_10_wordpiece_WordPieceProcessor) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + } + #endif + __Pyx_call_destructor(p->_pieces); + #if CYTHON_USE_TYPE_SLOTS || CYTHON_COMPILING_IN_PYPY + (*Py_TYPE(o)->tp_free)(o); + #else + { + freefunc tp_free = (freefunc)PyType_GetSlot(Py_TYPE(o), Py_tp_free); + if (tp_free) tp_free(o); + } + #endif +} + +static PyMethodDef __pyx_methods_18curated_tokenizers_10_wordpiece_WordPieceProcessor[] = { + {"__copy__", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_3__copy__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_2__copy__}, + {"__deepcopy__", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_5__deepcopy__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_4__deepcopy__}, + {"encode", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_7encode, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_6encode}, + {"decode", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_9decode, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_8decode}, + {"get_initial", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_11get_initial, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_10get_initial}, + {"id_to_piece", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_13id_to_piece, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_12id_to_piece}, + {"is_valid_piece_id", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_15is_valid_piece_id, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_14is_valid_piece_id}, + {"from_file", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_17from_file, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_16from_file}, + {"to_list", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_19to_list, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_18to_list}, + {"__reduce__", (PyCFunction)(void*)(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_21__reduce__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_20__reduce__}, + {0, 0, 0, 0} +}; +#if CYTHON_USE_TYPE_SPECS +static PyType_Slot __pyx_type_18curated_tokenizers_10_wordpiece_WordPieceProcessor_slots[] = { + {Py_tp_dealloc, (void *)__pyx_tp_dealloc_18curated_tokenizers_10_wordpiece_WordPieceProcessor}, + {Py_tp_doc, (void *)PyDoc_STR("WordPieceProcessor(pieces: List[str])")}, + {Py_tp_methods, (void *)__pyx_methods_18curated_tokenizers_10_wordpiece_WordPieceProcessor}, + {Py_tp_init, (void *)__pyx_pw_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_1__init__}, + {Py_tp_new, (void *)__pyx_tp_new_18curated_tokenizers_10_wordpiece_WordPieceProcessor}, + {0, 0}, +}; +static PyType_Spec __pyx_type_18curated_tokenizers_10_wordpiece_WordPieceProcessor_spec = { + "curated_tokenizers._wordpiece.WordPieceProcessor", + sizeof(struct __pyx_obj_18curated_tokenizers_10_wordpiece_WordPieceProcessor), + 0, + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, + __pyx_type_18curated_tokenizers_10_wordpiece_WordPieceProcessor_slots, +}; +#else + +static PyTypeObject __pyx_type_18curated_tokenizers_10_wordpiece_WordPieceProcessor = { + PyVarObject_HEAD_INIT(0, 0) + "curated_tokenizers._wordpiece.""WordPieceProcessor", /*tp_name*/ + sizeof(struct __pyx_obj_18curated_tokenizers_10_wordpiece_WordPieceProcessor), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_18curated_tokenizers_10_wordpiece_WordPieceProcessor, /*tp_dealloc*/ + #if PY_VERSION_HEX < 0x030800b4 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030800b4 + 0, /*tp_vectorcall_offset*/ + #endif + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + #if PY_MAJOR_VERSION < 3 + 0, /*tp_compare*/ + #endif + #if PY_MAJOR_VERSION >= 3 + 0, /*tp_as_async*/ + #endif + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ + PyDoc_STR("WordPieceProcessor(pieces: List[str])"), /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_18curated_tokenizers_10_wordpiece_WordPieceProcessor, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + #if !CYTHON_USE_TYPE_SPECS + 0, /*tp_dictoffset*/ + #endif + __pyx_pw_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_1__init__, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_18curated_tokenizers_10_wordpiece_WordPieceProcessor, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if PY_VERSION_HEX >= 0x030400a1 + #if CYTHON_USE_TP_FINALIZE + 0, /*tp_finalize*/ + #else + NULL, /*tp_finalize*/ + #endif + #endif + #if PY_VERSION_HEX >= 0x030800b1 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) + 0, /*tp_vectorcall*/ + #endif + #if __PYX_NEED_TP_PRINT_SLOT == 1 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030C0000 + 0, /*tp_watched*/ + #endif + #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 + 0, /*tp_pypy_flags*/ + #endif +}; +#endif + +static PyMethodDef __pyx_methods[] = { + {0, 0, 0, 0} +}; +#ifndef CYTHON_SMALL_CODE +#if defined(__clang__) + #define CYTHON_SMALL_CODE +#elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) + #define CYTHON_SMALL_CODE __attribute__((cold)) +#else + #define CYTHON_SMALL_CODE +#endif +#endif +/* #### Code section: pystring_table ### */ + +static int __Pyx_CreateStringTabAndInitStrings(void) { + __Pyx_StringTabEntry __pyx_string_tab[] = { + {&__pyx_kp_s_, __pyx_k_, sizeof(__pyx_k_), 0, 0, 1, 0}, + {&__pyx_kp_u_, __pyx_k_, sizeof(__pyx_k_), 0, 1, 0, 0}, + {&__pyx_n_s_Iterable, __pyx_k_Iterable, sizeof(__pyx_k_Iterable), 0, 0, 1, 1}, + {&__pyx_kp_s_Iterable_int, __pyx_k_Iterable_int, sizeof(__pyx_k_Iterable_int), 0, 0, 1, 0}, + {&__pyx_n_s_List, __pyx_k_List, sizeof(__pyx_k_List), 0, 0, 1, 1}, + {&__pyx_kp_s_List_str, __pyx_k_List_str, sizeof(__pyx_k_List_str), 0, 0, 1, 0}, + {&__pyx_n_s_Tuple, __pyx_k_Tuple, sizeof(__pyx_k_Tuple), 0, 0, 1, 1}, + {&__pyx_kp_s_Tuple_List_int_List_str, __pyx_k_Tuple_List_int_List_str, sizeof(__pyx_k_Tuple_List_int_List_str), 0, 0, 1, 0}, + {&__pyx_kp_s_Tuple_str_bool, __pyx_k_Tuple_str_bool, sizeof(__pyx_k_Tuple_str_bool), 0, 0, 1, 0}, + {&__pyx_n_s_WordPieceProcessor, __pyx_k_WordPieceProcessor, sizeof(__pyx_k_WordPieceProcessor), 0, 0, 1, 1}, + {&__pyx_n_s_WordPieceProcessor___copy, __pyx_k_WordPieceProcessor___copy, sizeof(__pyx_k_WordPieceProcessor___copy), 0, 0, 1, 1}, + {&__pyx_n_s_WordPieceProcessor___deepcopy, __pyx_k_WordPieceProcessor___deepcopy, sizeof(__pyx_k_WordPieceProcessor___deepcopy), 0, 0, 1, 1}, + {&__pyx_n_s_WordPieceProcessor___reduce, __pyx_k_WordPieceProcessor___reduce, sizeof(__pyx_k_WordPieceProcessor___reduce), 0, 0, 1, 1}, + {&__pyx_n_s_WordPieceProcessor_decode, __pyx_k_WordPieceProcessor_decode, sizeof(__pyx_k_WordPieceProcessor_decode), 0, 0, 1, 1}, + {&__pyx_n_s_WordPieceProcessor_encode, __pyx_k_WordPieceProcessor_encode, sizeof(__pyx_k_WordPieceProcessor_encode), 0, 0, 1, 1}, + {&__pyx_n_s_WordPieceProcessor_from_file, __pyx_k_WordPieceProcessor_from_file, sizeof(__pyx_k_WordPieceProcessor_from_file), 0, 0, 1, 1}, + {&__pyx_n_s_WordPieceProcessor_get_initial, __pyx_k_WordPieceProcessor_get_initial, sizeof(__pyx_k_WordPieceProcessor_get_initial), 0, 0, 1, 1}, + {&__pyx_n_s_WordPieceProcessor_id_to_piece, __pyx_k_WordPieceProcessor_id_to_piece, sizeof(__pyx_k_WordPieceProcessor_id_to_piece), 0, 0, 1, 1}, + {&__pyx_n_s_WordPieceProcessor_is_valid_piec, __pyx_k_WordPieceProcessor_is_valid_piec, sizeof(__pyx_k_WordPieceProcessor_is_valid_piec), 0, 0, 1, 1}, + {&__pyx_n_s_WordPieceProcessor_to_list, __pyx_k_WordPieceProcessor_to_list, sizeof(__pyx_k_WordPieceProcessor_to_list), 0, 0, 1, 1}, + {&__pyx_n_s__26, __pyx_k__26, sizeof(__pyx_k__26), 0, 0, 1, 1}, + {&__pyx_kp_s__3, __pyx_k__3, sizeof(__pyx_k__3), 0, 0, 1, 0}, + {&__pyx_kp_u__5, __pyx_k__5, sizeof(__pyx_k__5), 0, 1, 0, 0}, + {&__pyx_n_s_asyncio_coroutines, __pyx_k_asyncio_coroutines, sizeof(__pyx_k_asyncio_coroutines), 0, 0, 1, 1}, + {&__pyx_n_s_bool, __pyx_k_bool, sizeof(__pyx_k_bool), 0, 0, 1, 1}, + {&__pyx_n_s_cline_in_traceback, __pyx_k_cline_in_traceback, sizeof(__pyx_k_cline_in_traceback), 0, 0, 1, 1}, + {&__pyx_n_s_copy, __pyx_k_copy, sizeof(__pyx_k_copy), 0, 0, 1, 1}, + {&__pyx_n_s_curated_tokenizers__wordpiece, __pyx_k_curated_tokenizers__wordpiece, sizeof(__pyx_k_curated_tokenizers__wordpiece), 0, 0, 1, 1}, + {&__pyx_kp_s_curated_tokenizers__wordpiece_py, __pyx_k_curated_tokenizers__wordpiece_py, sizeof(__pyx_k_curated_tokenizers__wordpiece_py), 0, 0, 1, 0}, + {&__pyx_n_s_decode, __pyx_k_decode, sizeof(__pyx_k_decode), 0, 0, 1, 1}, + {&__pyx_n_s_deepcopy, __pyx_k_deepcopy, sizeof(__pyx_k_deepcopy), 0, 0, 1, 1}, + {&__pyx_n_s_dict, __pyx_k_dict, sizeof(__pyx_k_dict), 0, 0, 1, 1}, + {&__pyx_kp_u_disable, __pyx_k_disable, sizeof(__pyx_k_disable), 0, 1, 0, 0}, + {&__pyx_kp_u_enable, __pyx_k_enable, sizeof(__pyx_k_enable), 0, 1, 0, 0}, + {&__pyx_n_s_encode, __pyx_k_encode, sizeof(__pyx_k_encode), 0, 0, 1, 1}, + {&__pyx_n_s_encoding, __pyx_k_encoding, sizeof(__pyx_k_encoding), 0, 0, 1, 1}, + {&__pyx_n_s_enter, __pyx_k_enter, sizeof(__pyx_k_enter), 0, 0, 1, 1}, + {&__pyx_n_s_enumerate, __pyx_k_enumerate, sizeof(__pyx_k_enumerate), 0, 0, 1, 1}, + {&__pyx_n_s_exit, __pyx_k_exit, sizeof(__pyx_k_exit), 0, 0, 1, 1}, + {&__pyx_n_s_f, __pyx_k_f, sizeof(__pyx_k_f), 0, 0, 1, 1}, + {&__pyx_n_s_filename, __pyx_k_filename, sizeof(__pyx_k_filename), 0, 0, 1, 1}, + {&__pyx_n_s_from_file, __pyx_k_from_file, sizeof(__pyx_k_from_file), 0, 0, 1, 1}, + {&__pyx_kp_u_gc, __pyx_k_gc, sizeof(__pyx_k_gc), 0, 1, 0, 0}, + {&__pyx_n_s_get_initial, __pyx_k_get_initial, sizeof(__pyx_k_get_initial), 0, 0, 1, 1}, + {&__pyx_n_s_i, __pyx_k_i, sizeof(__pyx_k_i), 0, 0, 1, 1}, + {&__pyx_n_s_id, __pyx_k_id, sizeof(__pyx_k_id), 0, 0, 1, 1}, + {&__pyx_n_s_id_to_piece, __pyx_k_id_to_piece, sizeof(__pyx_k_id_to_piece), 0, 0, 1, 1}, + {&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1}, + {&__pyx_n_s_int, __pyx_k_int, sizeof(__pyx_k_int), 0, 0, 1, 1}, + {&__pyx_n_s_is_coroutine, __pyx_k_is_coroutine, sizeof(__pyx_k_is_coroutine), 0, 0, 1, 1}, + {&__pyx_n_s_is_initial, __pyx_k_is_initial, sizeof(__pyx_k_is_initial), 0, 0, 1, 1}, + {&__pyx_n_s_is_valid_piece_id, __pyx_k_is_valid_piece_id, sizeof(__pyx_k_is_valid_piece_id), 0, 0, 1, 1}, + {&__pyx_kp_u_isenabled, __pyx_k_isenabled, sizeof(__pyx_k_isenabled), 0, 1, 0, 0}, + {&__pyx_n_s_join, __pyx_k_join, sizeof(__pyx_k_join), 0, 0, 1, 1}, + {&__pyx_n_s_line, __pyx_k_line, sizeof(__pyx_k_line), 0, 0, 1, 1}, + {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, + {&__pyx_n_s_match, __pyx_k_match, sizeof(__pyx_k_match), 0, 0, 1, 1}, + {&__pyx_n_s_memo, __pyx_k_memo, sizeof(__pyx_k_memo), 0, 0, 1, 1}, + {&__pyx_n_s_name, __pyx_k_name, sizeof(__pyx_k_name), 0, 0, 1, 1}, + {&__pyx_n_s_open, __pyx_k_open, sizeof(__pyx_k_open), 0, 0, 1, 1}, + {&__pyx_n_s_piece, __pyx_k_piece, sizeof(__pyx_k_piece), 0, 0, 1, 1}, + {&__pyx_n_s_pieces, __pyx_k_pieces, sizeof(__pyx_k_pieces), 0, 0, 1, 1}, + {&__pyx_n_s_prefix, __pyx_k_prefix, sizeof(__pyx_k_prefix), 0, 0, 1, 1}, + {&__pyx_n_s_ptr_piece, __pyx_k_ptr_piece, sizeof(__pyx_k_ptr_piece), 0, 0, 1, 1}, + {&__pyx_n_s_pyx_vtable, __pyx_k_pyx_vtable, sizeof(__pyx_k_pyx_vtable), 0, 0, 1, 1}, + {&__pyx_n_s_range, __pyx_k_range, sizeof(__pyx_k_range), 0, 0, 1, 1}, + {&__pyx_n_s_reduce, __pyx_k_reduce, sizeof(__pyx_k_reduce), 0, 0, 1, 1}, + {&__pyx_n_s_return, __pyx_k_return, sizeof(__pyx_k_return), 0, 0, 1, 1}, + {&__pyx_n_s_reversed, __pyx_k_reversed, sizeof(__pyx_k_reversed), 0, 0, 1, 1}, + {&__pyx_n_s_self, __pyx_k_self, sizeof(__pyx_k_self), 0, 0, 1, 1}, + {&__pyx_n_s_startswith, __pyx_k_startswith, sizeof(__pyx_k_startswith), 0, 0, 1, 1}, + {&__pyx_n_s_staticmethod, __pyx_k_staticmethod, sizeof(__pyx_k_staticmethod), 0, 0, 1, 1}, + {&__pyx_n_s_str, __pyx_k_str, sizeof(__pyx_k_str), 0, 0, 1, 1}, + {&__pyx_n_s_strip, __pyx_k_strip, sizeof(__pyx_k_strip), 0, 0, 1, 1}, + {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, + {&__pyx_n_s_to_list, __pyx_k_to_list, sizeof(__pyx_k_to_list), 0, 0, 1, 1}, + {&__pyx_n_s_token, __pyx_k_token, sizeof(__pyx_k_token), 0, 0, 1, 1}, + {&__pyx_n_s_token_ids, __pyx_k_token_ids, sizeof(__pyx_k_token_ids), 0, 0, 1, 1}, + {&__pyx_n_s_token_pieces, __pyx_k_token_pieces, sizeof(__pyx_k_token_pieces), 0, 0, 1, 1}, + {&__pyx_n_s_typing, __pyx_k_typing, sizeof(__pyx_k_typing), 0, 0, 1, 1}, + {&__pyx_n_s_unpickle_wordpiece_processor, __pyx_k_unpickle_wordpiece_processor, sizeof(__pyx_k_unpickle_wordpiece_processor), 0, 0, 1, 1}, + {&__pyx_n_s_utf8, __pyx_k_utf8, sizeof(__pyx_k_utf8), 0, 0, 1, 1}, + {0, 0, 0, 0, 0, 0, 0} + }; + return __Pyx_InitStrings(__pyx_string_tab); +} +/* #### Code section: cached_builtins ### */ +static CYTHON_SMALL_CODE int __Pyx_InitCachedBuiltins(void) { + __pyx_builtin_staticmethod = __Pyx_GetBuiltinName(__pyx_n_s_staticmethod); if (!__pyx_builtin_staticmethod) __PYX_ERR(0, 98, __pyx_L1_error) + __pyx_builtin_enumerate = __Pyx_GetBuiltinName(__pyx_n_s_enumerate); if (!__pyx_builtin_enumerate) __PYX_ERR(0, 16, __pyx_L1_error) + __pyx_builtin_open = __Pyx_GetBuiltinName(__pyx_n_s_open); if (!__pyx_builtin_open) __PYX_ERR(0, 100, __pyx_L1_error) + __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) __PYX_ERR(0, 107, __pyx_L1_error) + __pyx_builtin_reversed = __Pyx_GetBuiltinName(__pyx_n_s_reversed); if (!__pyx_builtin_reversed) __PYX_ERR(0, 121, __pyx_L1_error) + return 0; + __pyx_L1_error:; + return -1; +} +/* #### Code section: cached_constants ### */ + +static CYTHON_SMALL_CODE int __Pyx_InitCachedConstants(void) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); + + /* "curated_tokenizers/_wordpiece.pyx":18 + * for idx, piece in enumerate(pieces): + * is_initial = not piece.startswith("##") + * byte_array = piece[2:].encode('utf8') if not is_initial else piece.encode('utf8') # <<<<<<<<<<<<<< + * self._pieces.add_piece(byte_array, is_initial) + * + */ + __pyx_slice__2 = PySlice_New(__pyx_int_2, Py_None, Py_None); if (unlikely(!__pyx_slice__2)) __PYX_ERR(0, 18, __pyx_L1_error) + __Pyx_GOTREF(__pyx_slice__2); + __Pyx_GIVEREF(__pyx_slice__2); + + /* "curated_tokenizers/_wordpiece.pyx":100 + * @staticmethod + * def from_file(filename: str) -> WordPieceProcessor: + * with open(filename, encoding="utf8") as f: # <<<<<<<<<<<<<< + * pieces = [line.strip() for line in f] + * return WordPieceProcessor(pieces) + */ + __pyx_tuple__4 = PyTuple_Pack(3, Py_None, Py_None, Py_None); if (unlikely(!__pyx_tuple__4)) __PYX_ERR(0, 100, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__4); + __Pyx_GIVEREF(__pyx_tuple__4); + + /* "curated_tokenizers/_wordpiece.pyx":21 + * self._pieces.add_piece(byte_array, is_initial) + * + * def __copy__(self): # <<<<<<<<<<<<<< + * # This is essentially a deepcopy, but there's no better way to do it. + * return WordPieceProcessor(self.to_list()) + */ + __pyx_tuple__6 = PyTuple_Pack(1, __pyx_n_s_self); if (unlikely(!__pyx_tuple__6)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__6); + __Pyx_GIVEREF(__pyx_tuple__6); + __pyx_codeobj__7 = (PyObject*)__Pyx_PyCode_New(1, 0, 0, 1, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__6, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_curated_tokenizers__wordpiece_py, __pyx_n_s_copy, 21, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__7)) __PYX_ERR(0, 21, __pyx_L1_error) + + /* "curated_tokenizers/_wordpiece.pyx":25 + * return WordPieceProcessor(self.to_list()) + * + * def __deepcopy__(self, memo): # <<<<<<<<<<<<<< + * return WordPieceProcessor(self.to_list()) + * + */ + __pyx_tuple__8 = PyTuple_Pack(2, __pyx_n_s_self, __pyx_n_s_memo); if (unlikely(!__pyx_tuple__8)) __PYX_ERR(0, 25, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__8); + __Pyx_GIVEREF(__pyx_tuple__8); + __pyx_codeobj__9 = (PyObject*)__Pyx_PyCode_New(2, 0, 0, 2, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__8, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_curated_tokenizers__wordpiece_py, __pyx_n_s_deepcopy, 25, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__9)) __PYX_ERR(0, 25, __pyx_L1_error) + + /* "curated_tokenizers/_wordpiece.pyx":28 + * return WordPieceProcessor(self.to_list()) + * + * def encode(self, token: str) -> Tuple[List[int], List[str]]: # <<<<<<<<<<<<<< + * """ + * Encode a token using word pieces. The piece identifiers are + */ + __pyx_tuple__10 = PyTuple_Pack(7, __pyx_n_s_self, __pyx_n_s_token, __pyx_n_s_token_ids, __pyx_n_s_token_pieces, __pyx_n_s_prefix, __pyx_n_s_match, __pyx_n_s_is_initial); if (unlikely(!__pyx_tuple__10)) __PYX_ERR(0, 28, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__10); + __Pyx_GIVEREF(__pyx_tuple__10); + __pyx_codeobj__11 = (PyObject*)__Pyx_PyCode_New(2, 0, 0, 7, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__10, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_curated_tokenizers__wordpiece_py, __pyx_n_s_encode, 28, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__11)) __PYX_ERR(0, 28, __pyx_L1_error) + + /* "curated_tokenizers/_wordpiece.pyx":55 + * return token_ids, token_pieces + * + * def decode(self, pieces: Iterable[int]) -> str: # <<<<<<<<<<<<<< + * """ + * Decode token piece identifiers into string. Raises a `RuntimeError` + */ + __pyx_tuple__12 = PyTuple_Pack(4, __pyx_n_s_self, __pyx_n_s_pieces, __pyx_n_s_token_pieces, __pyx_n_s_id); if (unlikely(!__pyx_tuple__12)) __PYX_ERR(0, 55, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__12); + __Pyx_GIVEREF(__pyx_tuple__12); + __pyx_codeobj__13 = (PyObject*)__Pyx_PyCode_New(2, 0, 0, 4, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__12, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_curated_tokenizers__wordpiece_py, __pyx_n_s_decode, 55, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__13)) __PYX_ERR(0, 55, __pyx_L1_error) + + /* "curated_tokenizers/_wordpiece.pyx":66 + * return "".join(token_pieces) + * + * def get_initial(self, piece: str) -> int: # <<<<<<<<<<<<<< + * """ + * Returns the ID for the given initial piece. Raises a `RuntimeError` if + */ + __pyx_tuple__14 = PyTuple_Pack(2, __pyx_n_s_self, __pyx_n_s_piece); if (unlikely(!__pyx_tuple__14)) __PYX_ERR(0, 66, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__14); + __Pyx_GIVEREF(__pyx_tuple__14); + __pyx_codeobj__15 = (PyObject*)__Pyx_PyCode_New(2, 0, 0, 2, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__14, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_curated_tokenizers__wordpiece_py, __pyx_n_s_get_initial, 66, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__15)) __PYX_ERR(0, 66, __pyx_L1_error) + + /* "curated_tokenizers/_wordpiece.pyx":76 + * return self._pieces.piece_to_id(Piece(piece.encode('utf8'), True)) + * + * def id_to_piece(self, piece: int) -> Tuple[str, bool]: # <<<<<<<<<<<<<< + * """ + * Returns the piece string (without any prefix) for a given piece identifier + */ + __pyx_tuple__16 = PyTuple_Pack(3, __pyx_n_s_self, __pyx_n_s_piece, __pyx_n_s_ptr_piece); if (unlikely(!__pyx_tuple__16)) __PYX_ERR(0, 76, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__16); + __Pyx_GIVEREF(__pyx_tuple__16); + __pyx_codeobj__17 = (PyObject*)__Pyx_PyCode_New(2, 0, 0, 3, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__16, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_curated_tokenizers__wordpiece_py, __pyx_n_s_id_to_piece, 76, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__17)) __PYX_ERR(0, 76, __pyx_L1_error) + + /* "curated_tokenizers/_wordpiece.pyx":89 + * return (ptr_piece[0].piece.decode('utf8'), ptr_piece[0].is_initial) + * + * def is_valid_piece_id(self, piece: int) -> bool: # <<<<<<<<<<<<<< + * """ + * Returns True if the piece identifier is valid, False otherwise. + */ + __pyx_codeobj__18 = (PyObject*)__Pyx_PyCode_New(2, 0, 0, 2, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__14, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_curated_tokenizers__wordpiece_py, __pyx_n_s_is_valid_piece_id, 89, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__18)) __PYX_ERR(0, 89, __pyx_L1_error) + + /* "curated_tokenizers/_wordpiece.pyx":98 + * return 0 <= piece <= self._pieces.size() - 1 + * + * @staticmethod # <<<<<<<<<<<<<< + * def from_file(filename: str) -> WordPieceProcessor: + * with open(filename, encoding="utf8") as f: + */ + __pyx_tuple__19 = PyTuple_Pack(4, __pyx_n_s_filename, __pyx_n_s_f, __pyx_n_s_pieces, __pyx_n_s_line); if (unlikely(!__pyx_tuple__19)) __PYX_ERR(0, 98, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__19); + __Pyx_GIVEREF(__pyx_tuple__19); + __pyx_codeobj__20 = (PyObject*)__Pyx_PyCode_New(1, 0, 0, 4, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__19, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_curated_tokenizers__wordpiece_py, __pyx_n_s_from_file, 98, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__20)) __PYX_ERR(0, 98, __pyx_L1_error) + + /* "curated_tokenizers/_wordpiece.pyx":104 + * return WordPieceProcessor(pieces) + * + * def to_list(self): # <<<<<<<<<<<<<< + * pieces = [None] * self._pieces.size() + * cdef Piece piece + */ + __pyx_tuple__21 = PyTuple_Pack(4, __pyx_n_s_self, __pyx_n_s_pieces, __pyx_n_s_piece, __pyx_n_s_i); if (unlikely(!__pyx_tuple__21)) __PYX_ERR(0, 104, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__21); + __Pyx_GIVEREF(__pyx_tuple__21); + __pyx_codeobj__22 = (PyObject*)__Pyx_PyCode_New(1, 0, 0, 4, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__21, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_curated_tokenizers__wordpiece_py, __pyx_n_s_to_list, 104, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__22)) __PYX_ERR(0, 104, __pyx_L1_error) + + /* "curated_tokenizers/_wordpiece.pyx":132 + * return match + * + * def __reduce__(self): # <<<<<<<<<<<<<< + * return (unpickle_wordpiece_processor, (self.to_list(),)) + * + */ + __pyx_codeobj__23 = (PyObject*)__Pyx_PyCode_New(1, 0, 0, 1, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__6, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_curated_tokenizers__wordpiece_py, __pyx_n_s_reduce, 132, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__23)) __PYX_ERR(0, 132, __pyx_L1_error) + + /* "curated_tokenizers/_wordpiece.pyx":135 + * return (unpickle_wordpiece_processor, (self.to_list(),)) + * + * def unpickle_wordpiece_processor(pieces: List[str]) -> WordPieceProcessor: # <<<<<<<<<<<<<< + * return WordPieceProcessor(pieces) + */ + __pyx_tuple__24 = PyTuple_Pack(1, __pyx_n_s_pieces); if (unlikely(!__pyx_tuple__24)) __PYX_ERR(0, 135, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__24); + __Pyx_GIVEREF(__pyx_tuple__24); + __pyx_codeobj__25 = (PyObject*)__Pyx_PyCode_New(1, 0, 0, 1, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__24, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_curated_tokenizers__wordpiece_py, __pyx_n_s_unpickle_wordpiece_processor, 135, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__25)) __PYX_ERR(0, 135, __pyx_L1_error) + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_RefNannyFinishContext(); + return -1; +} +/* #### Code section: init_constants ### */ + +static CYTHON_SMALL_CODE int __Pyx_InitConstants(void) { + if (__Pyx_CreateStringTabAndInitStrings() < 0) __PYX_ERR(0, 1, __pyx_L1_error); + __pyx_int_0 = PyInt_FromLong(0); if (unlikely(!__pyx_int_0)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_int_1 = PyInt_FromLong(1); if (unlikely(!__pyx_int_1)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_int_2 = PyInt_FromLong(2); if (unlikely(!__pyx_int_2)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_int_neg_1 = PyInt_FromLong(-1); if (unlikely(!__pyx_int_neg_1)) __PYX_ERR(0, 1, __pyx_L1_error) + return 0; + __pyx_L1_error:; + return -1; +} +/* #### Code section: init_globals ### */ + +static CYTHON_SMALL_CODE int __Pyx_InitGlobals(void) { + return 0; +} +/* #### Code section: init_module ### */ + +static CYTHON_SMALL_CODE int __Pyx_modinit_global_init_code(void); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_variable_export_code(void); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_function_export_code(void); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_type_init_code(void); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_type_import_code(void); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_variable_import_code(void); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_function_import_code(void); /*proto*/ + +static int __Pyx_modinit_global_init_code(void) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__Pyx_modinit_global_init_code", 0); + /*--- Global init code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_variable_export_code(void) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__Pyx_modinit_variable_export_code", 0); + /*--- Variable export code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_function_export_code(void) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__Pyx_modinit_function_export_code", 0); + /*--- Function export code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_type_init_code(void) { + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__Pyx_modinit_type_init_code", 0); + /*--- Type init code ---*/ + __pyx_vtabptr_18curated_tokenizers_10_wordpiece_WordPieceProcessor = &__pyx_vtable_18curated_tokenizers_10_wordpiece_WordPieceProcessor; + __pyx_vtable_18curated_tokenizers_10_wordpiece_WordPieceProcessor._find_longest_prefix = (struct __pyx_t_18curated_tokenizers_10_wordpiece_PieceMatch (*)(struct __pyx_obj_18curated_tokenizers_10_wordpiece_WordPieceProcessor *, PyObject *, int))__pyx_f_18curated_tokenizers_10_wordpiece_18WordPieceProcessor__find_longest_prefix; + #if CYTHON_USE_TYPE_SPECS + __pyx_ptype_18curated_tokenizers_10_wordpiece_WordPieceProcessor = (PyTypeObject *) __Pyx_PyType_FromModuleAndSpec(__pyx_m, &__pyx_type_18curated_tokenizers_10_wordpiece_WordPieceProcessor_spec, NULL); if (unlikely(!__pyx_ptype_18curated_tokenizers_10_wordpiece_WordPieceProcessor)) __PYX_ERR(0, 10, __pyx_L1_error) + if (__Pyx_fix_up_extension_type_from_spec(&__pyx_type_18curated_tokenizers_10_wordpiece_WordPieceProcessor_spec, __pyx_ptype_18curated_tokenizers_10_wordpiece_WordPieceProcessor) < 0) __PYX_ERR(0, 10, __pyx_L1_error) + #else + __pyx_ptype_18curated_tokenizers_10_wordpiece_WordPieceProcessor = &__pyx_type_18curated_tokenizers_10_wordpiece_WordPieceProcessor; + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + #endif + #if !CYTHON_USE_TYPE_SPECS + if (__Pyx_PyType_Ready(__pyx_ptype_18curated_tokenizers_10_wordpiece_WordPieceProcessor) < 0) __PYX_ERR(0, 10, __pyx_L1_error) + #endif + #if PY_MAJOR_VERSION < 3 + __pyx_ptype_18curated_tokenizers_10_wordpiece_WordPieceProcessor->tp_print = 0; + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_ptype_18curated_tokenizers_10_wordpiece_WordPieceProcessor->tp_dictoffset && __pyx_ptype_18curated_tokenizers_10_wordpiece_WordPieceProcessor->tp_getattro == PyObject_GenericGetAttr)) { + __pyx_ptype_18curated_tokenizers_10_wordpiece_WordPieceProcessor->tp_getattro = __Pyx_PyObject_GenericGetAttr; + } + #endif + if (__Pyx_SetVtable(__pyx_ptype_18curated_tokenizers_10_wordpiece_WordPieceProcessor, __pyx_vtabptr_18curated_tokenizers_10_wordpiece_WordPieceProcessor) < 0) __PYX_ERR(0, 10, __pyx_L1_error) + #if !CYTHON_COMPILING_IN_LIMITED_API + if (__Pyx_MergeVtables(__pyx_ptype_18curated_tokenizers_10_wordpiece_WordPieceProcessor) < 0) __PYX_ERR(0, 10, __pyx_L1_error) + #endif + if (PyObject_SetAttr(__pyx_m, __pyx_n_s_WordPieceProcessor, (PyObject *) __pyx_ptype_18curated_tokenizers_10_wordpiece_WordPieceProcessor) < 0) __PYX_ERR(0, 10, __pyx_L1_error) + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_RefNannyFinishContext(); + return -1; +} + +static int __Pyx_modinit_type_import_code(void) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__Pyx_modinit_type_import_code", 0); + /*--- Type import code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_variable_import_code(void) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__Pyx_modinit_variable_import_code", 0); + /*--- Variable import code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_function_import_code(void) { + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__Pyx_modinit_function_import_code", 0); + /*--- Function import code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + + +#if PY_MAJOR_VERSION >= 3 +#if CYTHON_PEP489_MULTI_PHASE_INIT +static PyObject* __pyx_pymod_create(PyObject *spec, PyModuleDef *def); /*proto*/ +static int __pyx_pymod_exec__wordpiece(PyObject* module); /*proto*/ +static PyModuleDef_Slot __pyx_moduledef_slots[] = { + {Py_mod_create, (void*)__pyx_pymod_create}, + {Py_mod_exec, (void*)__pyx_pymod_exec__wordpiece}, + {0, NULL} +}; +#endif + +#ifdef __cplusplus +namespace { + struct PyModuleDef __pyx_moduledef = + #else + static struct PyModuleDef __pyx_moduledef = + #endif + { + PyModuleDef_HEAD_INIT, + "_wordpiece", + 0, /* m_doc */ + #if CYTHON_PEP489_MULTI_PHASE_INIT + 0, /* m_size */ + #elif CYTHON_USE_MODULE_STATE + sizeof(__pyx_mstate), /* m_size */ + #else + -1, /* m_size */ + #endif + __pyx_methods /* m_methods */, + #if CYTHON_PEP489_MULTI_PHASE_INIT + __pyx_moduledef_slots, /* m_slots */ + #else + NULL, /* m_reload */ + #endif + #if CYTHON_USE_MODULE_STATE + __pyx_m_traverse, /* m_traverse */ + __pyx_m_clear, /* m_clear */ + NULL /* m_free */ + #else + NULL, /* m_traverse */ + NULL, /* m_clear */ + NULL /* m_free */ + #endif + }; + #ifdef __cplusplus +} /* anonymous namespace */ +#endif +#endif + +#ifndef CYTHON_NO_PYINIT_EXPORT +#define __Pyx_PyMODINIT_FUNC PyMODINIT_FUNC +#elif PY_MAJOR_VERSION < 3 +#ifdef __cplusplus +#define __Pyx_PyMODINIT_FUNC extern "C" void +#else +#define __Pyx_PyMODINIT_FUNC void +#endif +#else +#ifdef __cplusplus +#define __Pyx_PyMODINIT_FUNC extern "C" PyObject * +#else +#define __Pyx_PyMODINIT_FUNC PyObject * +#endif +#endif + + +#if PY_MAJOR_VERSION < 3 +__Pyx_PyMODINIT_FUNC init_wordpiece(void) CYTHON_SMALL_CODE; /*proto*/ +__Pyx_PyMODINIT_FUNC init_wordpiece(void) +#else +__Pyx_PyMODINIT_FUNC PyInit__wordpiece(void) CYTHON_SMALL_CODE; /*proto*/ +__Pyx_PyMODINIT_FUNC PyInit__wordpiece(void) +#if CYTHON_PEP489_MULTI_PHASE_INIT +{ + return PyModuleDef_Init(&__pyx_moduledef); +} +static CYTHON_SMALL_CODE int __Pyx_check_single_interpreter(void) { + #if PY_VERSION_HEX >= 0x030700A1 + static PY_INT64_T main_interpreter_id = -1; + PY_INT64_T current_id = PyInterpreterState_GetID(PyThreadState_Get()->interp); + if (main_interpreter_id == -1) { + main_interpreter_id = current_id; + return (unlikely(current_id == -1)) ? -1 : 0; + } else if (unlikely(main_interpreter_id != current_id)) + #else + static PyInterpreterState *main_interpreter = NULL; + PyInterpreterState *current_interpreter = PyThreadState_Get()->interp; + if (!main_interpreter) { + main_interpreter = current_interpreter; + } else if (unlikely(main_interpreter != current_interpreter)) + #endif + { + PyErr_SetString( + PyExc_ImportError, + "Interpreter change detected - this module can only be loaded into one interpreter per process."); + return -1; + } + return 0; +} +#if CYTHON_COMPILING_IN_LIMITED_API +static CYTHON_SMALL_CODE int __Pyx_copy_spec_to_module(PyObject *spec, PyObject *module, const char* from_name, const char* to_name, int allow_none) +#else +static CYTHON_SMALL_CODE int __Pyx_copy_spec_to_module(PyObject *spec, PyObject *moddict, const char* from_name, const char* to_name, int allow_none) +#endif +{ + PyObject *value = PyObject_GetAttrString(spec, from_name); + int result = 0; + if (likely(value)) { + if (allow_none || value != Py_None) { +#if CYTHON_COMPILING_IN_LIMITED_API + result = PyModule_AddObject(module, to_name, value); +#else + result = PyDict_SetItemString(moddict, to_name, value); +#endif + } + Py_DECREF(value); + } else if (PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Clear(); + } else { + result = -1; + } + return result; +} +static CYTHON_SMALL_CODE PyObject* __pyx_pymod_create(PyObject *spec, PyModuleDef *def) { + PyObject *module = NULL, *moddict, *modname; + CYTHON_UNUSED_VAR(def); + if (__Pyx_check_single_interpreter()) + return NULL; + if (__pyx_m) + return __Pyx_NewRef(__pyx_m); + modname = PyObject_GetAttrString(spec, "name"); + if (unlikely(!modname)) goto bad; + module = PyModule_NewObject(modname); + Py_DECREF(modname); + if (unlikely(!module)) goto bad; +#if CYTHON_COMPILING_IN_LIMITED_API + moddict = module; +#else + moddict = PyModule_GetDict(module); + if (unlikely(!moddict)) goto bad; +#endif + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "loader", "__loader__", 1) < 0)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "origin", "__file__", 1) < 0)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "parent", "__package__", 1) < 0)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "submodule_search_locations", "__path__", 0) < 0)) goto bad; + return module; +bad: + Py_XDECREF(module); + return NULL; +} + + +static CYTHON_SMALL_CODE int __pyx_pymod_exec__wordpiece(PyObject *__pyx_pyinit_module) +#endif +#endif +{ + int stringtab_initialized = 0; + #if CYTHON_USE_MODULE_STATE + int pystate_addmodule_run = 0; + #endif + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannyDeclarations + #if CYTHON_PEP489_MULTI_PHASE_INIT + if (__pyx_m) { + if (__pyx_m == __pyx_pyinit_module) return 0; + PyErr_SetString(PyExc_RuntimeError, "Module '_wordpiece' has already been imported. Re-initialisation is not supported."); + return -1; + } + #elif PY_MAJOR_VERSION >= 3 + if (__pyx_m) return __Pyx_NewRef(__pyx_m); + #endif + /*--- Module creation code ---*/ + #if CYTHON_PEP489_MULTI_PHASE_INIT + __pyx_m = __pyx_pyinit_module; + Py_INCREF(__pyx_m); + #else + #if PY_MAJOR_VERSION < 3 + __pyx_m = Py_InitModule4("_wordpiece", __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); + if (unlikely(!__pyx_m)) __PYX_ERR(0, 1, __pyx_L1_error) + #elif CYTHON_USE_MODULE_STATE + __pyx_t_1 = PyModule_Create(&__pyx_moduledef); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1, __pyx_L1_error) + { + int add_module_result = PyState_AddModule(__pyx_t_1, &__pyx_moduledef); + __pyx_t_1 = 0; /* transfer ownership from __pyx_t_1 to "_wordpiece" pseudovariable */ + if (unlikely((add_module_result < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + pystate_addmodule_run = 1; + } + #else + __pyx_m = PyModule_Create(&__pyx_moduledef); + if (unlikely(!__pyx_m)) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + #endif + CYTHON_UNUSED_VAR(__pyx_t_1); + __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) __PYX_ERR(0, 1, __pyx_L1_error) + Py_INCREF(__pyx_d); + __pyx_b = __Pyx_PyImport_AddModuleRef(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_b)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_cython_runtime = __Pyx_PyImport_AddModuleRef((const char *) "cython_runtime"); if (unlikely(!__pyx_cython_runtime)) __PYX_ERR(0, 1, __pyx_L1_error) + if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #if CYTHON_REFNANNY +__Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); +if (!__Pyx_RefNanny) { + PyErr_Clear(); + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); + if (!__Pyx_RefNanny) + Py_FatalError("failed to import 'refnanny' module"); +} +#endif + __Pyx_RefNannySetupContext("__Pyx_PyMODINIT_FUNC PyInit__wordpiece(void)", 0); + if (__Pyx_check_binary_version(__PYX_LIMITED_VERSION_HEX, __Pyx_get_runtime_version(), CYTHON_COMPILING_IN_LIMITED_API) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #ifdef __Pxy_PyFrame_Initialize_Offsets + __Pxy_PyFrame_Initialize_Offsets(); + #endif + __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_empty_unicode = PyUnicode_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_unicode)) __PYX_ERR(0, 1, __pyx_L1_error) + #ifdef __Pyx_CyFunction_USED + if (__pyx_CyFunction_init(__pyx_m) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + #ifdef __Pyx_FusedFunction_USED + if (__pyx_FusedFunction_init(__pyx_m) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + #ifdef __Pyx_Coroutine_USED + if (__pyx_Coroutine_init(__pyx_m) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + #ifdef __Pyx_Generator_USED + if (__pyx_Generator_init(__pyx_m) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + #ifdef __Pyx_AsyncGen_USED + if (__pyx_AsyncGen_init(__pyx_m) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + #ifdef __Pyx_StopAsyncIteration_USED + if (__pyx_StopAsyncIteration_init(__pyx_m) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + /*--- Library function declarations ---*/ + /*--- Threads initialization code ---*/ + #if defined(WITH_THREAD) && PY_VERSION_HEX < 0x030700F0 && defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS + PyEval_InitThreads(); + #endif + /*--- Initialize various global constants etc. ---*/ + if (__Pyx_InitConstants() < 0) __PYX_ERR(0, 1, __pyx_L1_error) + stringtab_initialized = 1; + if (__Pyx_InitGlobals() < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) + if (__Pyx_init_sys_getdefaultencoding_params() < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + if (__pyx_module_is_main_curated_tokenizers___wordpiece) { + if (PyObject_SetAttr(__pyx_m, __pyx_n_s_name, __pyx_n_s_main) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + } + #if PY_MAJOR_VERSION >= 3 + { + PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) __PYX_ERR(0, 1, __pyx_L1_error) + if (!PyDict_GetItemString(modules, "curated_tokenizers._wordpiece")) { + if (unlikely((PyDict_SetItemString(modules, "curated_tokenizers._wordpiece", __pyx_m) < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + } + } + #endif + /*--- Builtin init code ---*/ + if (__Pyx_InitCachedBuiltins() < 0) __PYX_ERR(0, 1, __pyx_L1_error) + /*--- Constants init code ---*/ + if (__Pyx_InitCachedConstants() < 0) __PYX_ERR(0, 1, __pyx_L1_error) + /*--- Global type/function init code ---*/ + (void)__Pyx_modinit_global_init_code(); + (void)__Pyx_modinit_variable_export_code(); + (void)__Pyx_modinit_function_export_code(); + if (unlikely((__Pyx_modinit_type_init_code() < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + (void)__Pyx_modinit_type_import_code(); + (void)__Pyx_modinit_variable_import_code(); + (void)__Pyx_modinit_function_import_code(); + /*--- Execution code ---*/ + #if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED) + if (__Pyx_patch_abc() < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + + /* "curated_tokenizers/_wordpiece.pyx":1 + * from typing import List, Tuple, Iterable # <<<<<<<<<<<<<< + * from cython.operator cimport dereference as deref + * from libcpp cimport pair + */ + __pyx_t_2 = PyList_New(3); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_n_s_List); + __Pyx_GIVEREF(__pyx_n_s_List); + if (__Pyx_PyList_SET_ITEM(__pyx_t_2, 0, __pyx_n_s_List)) __PYX_ERR(0, 1, __pyx_L1_error); + __Pyx_INCREF(__pyx_n_s_Tuple); + __Pyx_GIVEREF(__pyx_n_s_Tuple); + if (__Pyx_PyList_SET_ITEM(__pyx_t_2, 1, __pyx_n_s_Tuple)) __PYX_ERR(0, 1, __pyx_L1_error); + __Pyx_INCREF(__pyx_n_s_Iterable); + __Pyx_GIVEREF(__pyx_n_s_Iterable); + if (__Pyx_PyList_SET_ITEM(__pyx_t_2, 2, __pyx_n_s_Iterable)) __PYX_ERR(0, 1, __pyx_L1_error); + __pyx_t_3 = __Pyx_Import(__pyx_n_s_typing, __pyx_t_2, -1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_3, __pyx_n_s_List); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_List, __pyx_t_2) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_3, __pyx_n_s_Tuple); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_Tuple, __pyx_t_2) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_3, __pyx_n_s_Iterable); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_Iterable, __pyx_t_2) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "curated_tokenizers/_wordpiece.pyx":21 + * self._pieces.add_piece(byte_array, is_initial) + * + * def __copy__(self): # <<<<<<<<<<<<<< + * # This is essentially a deepcopy, but there's no better way to do it. + * return WordPieceProcessor(self.to_list()) + */ + __pyx_t_3 = __Pyx_CyFunction_New(&__pyx_mdef_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_3__copy__, __Pyx_CYFUNCTION_CCLASS, __pyx_n_s_WordPieceProcessor___copy, NULL, __pyx_n_s_curated_tokenizers__wordpiece, __pyx_d, ((PyObject *)__pyx_codeobj__7)); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + if (__Pyx_SetItemOnTypeDict((PyObject *)__pyx_ptype_18curated_tokenizers_10_wordpiece_WordPieceProcessor, __pyx_n_s_copy, __pyx_t_3) < 0) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + PyType_Modified(__pyx_ptype_18curated_tokenizers_10_wordpiece_WordPieceProcessor); + + /* "curated_tokenizers/_wordpiece.pyx":25 + * return WordPieceProcessor(self.to_list()) + * + * def __deepcopy__(self, memo): # <<<<<<<<<<<<<< + * return WordPieceProcessor(self.to_list()) + * + */ + __pyx_t_3 = __Pyx_CyFunction_New(&__pyx_mdef_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_5__deepcopy__, __Pyx_CYFUNCTION_CCLASS, __pyx_n_s_WordPieceProcessor___deepcopy, NULL, __pyx_n_s_curated_tokenizers__wordpiece, __pyx_d, ((PyObject *)__pyx_codeobj__9)); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 25, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + if (__Pyx_SetItemOnTypeDict((PyObject *)__pyx_ptype_18curated_tokenizers_10_wordpiece_WordPieceProcessor, __pyx_n_s_deepcopy, __pyx_t_3) < 0) __PYX_ERR(0, 25, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + PyType_Modified(__pyx_ptype_18curated_tokenizers_10_wordpiece_WordPieceProcessor); + + /* "curated_tokenizers/_wordpiece.pyx":28 + * return WordPieceProcessor(self.to_list()) + * + * def encode(self, token: str) -> Tuple[List[int], List[str]]: # <<<<<<<<<<<<<< + * """ + * Encode a token using word pieces. The piece identifiers are + */ + __pyx_t_3 = __Pyx_PyDict_NewPresized(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 28, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_token, __pyx_n_s_str) < 0) __PYX_ERR(0, 28, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_return, __pyx_kp_s_Tuple_List_int_List_str) < 0) __PYX_ERR(0, 28, __pyx_L1_error) + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_7encode, __Pyx_CYFUNCTION_CCLASS, __pyx_n_s_WordPieceProcessor_encode, NULL, __pyx_n_s_curated_tokenizers__wordpiece, __pyx_d, ((PyObject *)__pyx_codeobj__11)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 28, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_CyFunction_SetAnnotationsDict(__pyx_t_2, __pyx_t_3); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__Pyx_SetItemOnTypeDict((PyObject *)__pyx_ptype_18curated_tokenizers_10_wordpiece_WordPieceProcessor, __pyx_n_s_encode, __pyx_t_2) < 0) __PYX_ERR(0, 28, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + PyType_Modified(__pyx_ptype_18curated_tokenizers_10_wordpiece_WordPieceProcessor); + + /* "curated_tokenizers/_wordpiece.pyx":55 + * return token_ids, token_pieces + * + * def decode(self, pieces: Iterable[int]) -> str: # <<<<<<<<<<<<<< + * """ + * Decode token piece identifiers into string. Raises a `RuntimeError` + */ + __pyx_t_2 = __Pyx_PyDict_NewPresized(2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 55, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_pieces, __pyx_kp_s_Iterable_int) < 0) __PYX_ERR(0, 55, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_return, __pyx_n_s_str) < 0) __PYX_ERR(0, 55, __pyx_L1_error) + __pyx_t_3 = __Pyx_CyFunction_New(&__pyx_mdef_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_9decode, __Pyx_CYFUNCTION_CCLASS, __pyx_n_s_WordPieceProcessor_decode, NULL, __pyx_n_s_curated_tokenizers__wordpiece, __pyx_d, ((PyObject *)__pyx_codeobj__13)); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 55, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_CyFunction_SetAnnotationsDict(__pyx_t_3, __pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (__Pyx_SetItemOnTypeDict((PyObject *)__pyx_ptype_18curated_tokenizers_10_wordpiece_WordPieceProcessor, __pyx_n_s_decode, __pyx_t_3) < 0) __PYX_ERR(0, 55, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + PyType_Modified(__pyx_ptype_18curated_tokenizers_10_wordpiece_WordPieceProcessor); + + /* "curated_tokenizers/_wordpiece.pyx":66 + * return "".join(token_pieces) + * + * def get_initial(self, piece: str) -> int: # <<<<<<<<<<<<<< + * """ + * Returns the ID for the given initial piece. Raises a `RuntimeError` if + */ + __pyx_t_3 = __Pyx_PyDict_NewPresized(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 66, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_piece, __pyx_n_s_str) < 0) __PYX_ERR(0, 66, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_return, __pyx_n_s_int) < 0) __PYX_ERR(0, 66, __pyx_L1_error) + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_11get_initial, __Pyx_CYFUNCTION_CCLASS, __pyx_n_s_WordPieceProcessor_get_initial, NULL, __pyx_n_s_curated_tokenizers__wordpiece, __pyx_d, ((PyObject *)__pyx_codeobj__15)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 66, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_CyFunction_SetAnnotationsDict(__pyx_t_2, __pyx_t_3); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__Pyx_SetItemOnTypeDict((PyObject *)__pyx_ptype_18curated_tokenizers_10_wordpiece_WordPieceProcessor, __pyx_n_s_get_initial, __pyx_t_2) < 0) __PYX_ERR(0, 66, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + PyType_Modified(__pyx_ptype_18curated_tokenizers_10_wordpiece_WordPieceProcessor); + + /* "curated_tokenizers/_wordpiece.pyx":76 + * return self._pieces.piece_to_id(Piece(piece.encode('utf8'), True)) + * + * def id_to_piece(self, piece: int) -> Tuple[str, bool]: # <<<<<<<<<<<<<< + * """ + * Returns the piece string (without any prefix) for a given piece identifier + */ + __pyx_t_2 = __Pyx_PyDict_NewPresized(2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 76, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_piece, __pyx_n_s_int) < 0) __PYX_ERR(0, 76, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_return, __pyx_kp_s_Tuple_str_bool) < 0) __PYX_ERR(0, 76, __pyx_L1_error) + __pyx_t_3 = __Pyx_CyFunction_New(&__pyx_mdef_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_13id_to_piece, __Pyx_CYFUNCTION_CCLASS, __pyx_n_s_WordPieceProcessor_id_to_piece, NULL, __pyx_n_s_curated_tokenizers__wordpiece, __pyx_d, ((PyObject *)__pyx_codeobj__17)); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 76, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_CyFunction_SetAnnotationsDict(__pyx_t_3, __pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (__Pyx_SetItemOnTypeDict((PyObject *)__pyx_ptype_18curated_tokenizers_10_wordpiece_WordPieceProcessor, __pyx_n_s_id_to_piece, __pyx_t_3) < 0) __PYX_ERR(0, 76, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + PyType_Modified(__pyx_ptype_18curated_tokenizers_10_wordpiece_WordPieceProcessor); + + /* "curated_tokenizers/_wordpiece.pyx":89 + * return (ptr_piece[0].piece.decode('utf8'), ptr_piece[0].is_initial) + * + * def is_valid_piece_id(self, piece: int) -> bool: # <<<<<<<<<<<<<< + * """ + * Returns True if the piece identifier is valid, False otherwise. + */ + __pyx_t_3 = __Pyx_PyDict_NewPresized(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 89, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_piece, __pyx_n_s_int) < 0) __PYX_ERR(0, 89, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_return, __pyx_n_s_bool) < 0) __PYX_ERR(0, 89, __pyx_L1_error) + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_15is_valid_piece_id, __Pyx_CYFUNCTION_CCLASS, __pyx_n_s_WordPieceProcessor_is_valid_piec, NULL, __pyx_n_s_curated_tokenizers__wordpiece, __pyx_d, ((PyObject *)__pyx_codeobj__18)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 89, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_CyFunction_SetAnnotationsDict(__pyx_t_2, __pyx_t_3); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__Pyx_SetItemOnTypeDict((PyObject *)__pyx_ptype_18curated_tokenizers_10_wordpiece_WordPieceProcessor, __pyx_n_s_is_valid_piece_id, __pyx_t_2) < 0) __PYX_ERR(0, 89, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + PyType_Modified(__pyx_ptype_18curated_tokenizers_10_wordpiece_WordPieceProcessor); + + /* "curated_tokenizers/_wordpiece.pyx":98 + * return 0 <= piece <= self._pieces.size() - 1 + * + * @staticmethod # <<<<<<<<<<<<<< + * def from_file(filename: str) -> WordPieceProcessor: + * with open(filename, encoding="utf8") as f: + */ + __pyx_t_2 = __Pyx_PyDict_NewPresized(2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 98, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_filename, __pyx_n_s_str) < 0) __PYX_ERR(0, 98, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_return, __pyx_n_s_WordPieceProcessor) < 0) __PYX_ERR(0, 98, __pyx_L1_error) + __pyx_t_3 = __Pyx_CyFunction_New(&__pyx_mdef_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_17from_file, __Pyx_CYFUNCTION_STATICMETHOD | __Pyx_CYFUNCTION_CCLASS, __pyx_n_s_WordPieceProcessor_from_file, NULL, __pyx_n_s_curated_tokenizers__wordpiece, __pyx_d, ((PyObject *)__pyx_codeobj__20)); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 98, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_CyFunction_SetAnnotationsDict(__pyx_t_3, __pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (__Pyx_SetItemOnTypeDict((PyObject *)__pyx_ptype_18curated_tokenizers_10_wordpiece_WordPieceProcessor, __pyx_n_s_from_file, __pyx_t_3) < 0) __PYX_ERR(0, 98, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + PyType_Modified(__pyx_ptype_18curated_tokenizers_10_wordpiece_WordPieceProcessor); + __Pyx_GetNameInClass(__pyx_t_3, (PyObject *)__pyx_ptype_18curated_tokenizers_10_wordpiece_WordPieceProcessor, __pyx_n_s_from_file); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 98, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_builtin_staticmethod, __pyx_t_3); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 98, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__Pyx_SetItemOnTypeDict((PyObject *)__pyx_ptype_18curated_tokenizers_10_wordpiece_WordPieceProcessor, __pyx_n_s_from_file, __pyx_t_2) < 0) __PYX_ERR(0, 98, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + PyType_Modified(__pyx_ptype_18curated_tokenizers_10_wordpiece_WordPieceProcessor); + + /* "curated_tokenizers/_wordpiece.pyx":104 + * return WordPieceProcessor(pieces) + * + * def to_list(self): # <<<<<<<<<<<<<< + * pieces = [None] * self._pieces.size() + * cdef Piece piece + */ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_19to_list, __Pyx_CYFUNCTION_CCLASS, __pyx_n_s_WordPieceProcessor_to_list, NULL, __pyx_n_s_curated_tokenizers__wordpiece, __pyx_d, ((PyObject *)__pyx_codeobj__22)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 104, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_SetItemOnTypeDict((PyObject *)__pyx_ptype_18curated_tokenizers_10_wordpiece_WordPieceProcessor, __pyx_n_s_to_list, __pyx_t_2) < 0) __PYX_ERR(0, 104, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + PyType_Modified(__pyx_ptype_18curated_tokenizers_10_wordpiece_WordPieceProcessor); + + /* "curated_tokenizers/_wordpiece.pyx":132 + * return match + * + * def __reduce__(self): # <<<<<<<<<<<<<< + * return (unpickle_wordpiece_processor, (self.to_list(),)) + * + */ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_18curated_tokenizers_10_wordpiece_18WordPieceProcessor_21__reduce__, __Pyx_CYFUNCTION_CCLASS, __pyx_n_s_WordPieceProcessor___reduce, NULL, __pyx_n_s_curated_tokenizers__wordpiece, __pyx_d, ((PyObject *)__pyx_codeobj__23)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 132, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_SetItemOnTypeDict((PyObject *)__pyx_ptype_18curated_tokenizers_10_wordpiece_WordPieceProcessor, __pyx_n_s_reduce, __pyx_t_2) < 0) __PYX_ERR(0, 132, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + PyType_Modified(__pyx_ptype_18curated_tokenizers_10_wordpiece_WordPieceProcessor); + + /* "curated_tokenizers/_wordpiece.pyx":135 + * return (unpickle_wordpiece_processor, (self.to_list(),)) + * + * def unpickle_wordpiece_processor(pieces: List[str]) -> WordPieceProcessor: # <<<<<<<<<<<<<< + * return WordPieceProcessor(pieces) + */ + __pyx_t_2 = __Pyx_PyDict_NewPresized(2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 135, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_pieces, __pyx_kp_s_List_str) < 0) __PYX_ERR(0, 135, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_return, __pyx_n_s_WordPieceProcessor) < 0) __PYX_ERR(0, 135, __pyx_L1_error) + __pyx_t_3 = __Pyx_CyFunction_New(&__pyx_mdef_18curated_tokenizers_10_wordpiece_1unpickle_wordpiece_processor, 0, __pyx_n_s_unpickle_wordpiece_processor, NULL, __pyx_n_s_curated_tokenizers__wordpiece, __pyx_d, ((PyObject *)__pyx_codeobj__25)); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 135, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_CyFunction_SetAnnotationsDict(__pyx_t_3, __pyx_t_2); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (PyDict_SetItem(__pyx_d, __pyx_n_s_unpickle_wordpiece_processor, __pyx_t_3) < 0) __PYX_ERR(0, 135, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "curated_tokenizers/_wordpiece.pyx":1 + * from typing import List, Tuple, Iterable # <<<<<<<<<<<<<< + * from cython.operator cimport dereference as deref + * from libcpp cimport pair + */ + __pyx_t_3 = __Pyx_PyDict_NewPresized(0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_3) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /*--- Wrapped vars code ---*/ + + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + if (__pyx_m) { + if (__pyx_d && stringtab_initialized) { + __Pyx_AddTraceback("init curated_tokenizers._wordpiece", __pyx_clineno, __pyx_lineno, __pyx_filename); + } + #if !CYTHON_USE_MODULE_STATE + Py_CLEAR(__pyx_m); + #else + Py_DECREF(__pyx_m); + if (pystate_addmodule_run) { + PyObject *tp, *value, *tb; + PyErr_Fetch(&tp, &value, &tb); + PyState_RemoveModule(&__pyx_moduledef); + PyErr_Restore(tp, value, tb); + } + #endif + } else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_ImportError, "init curated_tokenizers._wordpiece"); + } + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + #if CYTHON_PEP489_MULTI_PHASE_INIT + return (__pyx_m != NULL) ? 0 : -1; + #elif PY_MAJOR_VERSION >= 3 + return __pyx_m; + #else + return; + #endif +} +/* #### Code section: cleanup_globals ### */ +/* #### Code section: cleanup_module ### */ +/* #### Code section: main_method ### */ +/* #### Code section: utility_code_pragmas ### */ +#ifdef _MSC_VER +#pragma warning( push ) +/* Warning 4127: conditional expression is constant + * Cython uses constant conditional expressions to allow in inline functions to be optimized at + * compile-time, so this warning is not useful + */ +#pragma warning( disable : 4127 ) +#endif + + + +/* #### Code section: utility_code_def ### */ + +/* --- Runtime support code --- */ +/* Refnanny */ +#if CYTHON_REFNANNY +static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { + PyObject *m = NULL, *p = NULL; + void *r = NULL; + m = PyImport_ImportModule(modname); + if (!m) goto end; + p = PyObject_GetAttrString(m, "RefNannyAPI"); + if (!p) goto end; + r = PyLong_AsVoidPtr(p); +end: + Py_XDECREF(p); + Py_XDECREF(m); + return (__Pyx_RefNannyAPIStruct *)r; +} +#endif + +/* PyErrExceptionMatches */ +#if CYTHON_FAST_THREAD_STATE +static int __Pyx_PyErr_ExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { + Py_ssize_t i, n; + n = PyTuple_GET_SIZE(tuple); +#if PY_MAJOR_VERSION >= 3 + for (i=0; i= 0x030C00A6 + PyObject *current_exception = tstate->current_exception; + if (unlikely(!current_exception)) return 0; + exc_type = (PyObject*) Py_TYPE(current_exception); + if (exc_type == err) return 1; +#else + exc_type = tstate->curexc_type; + if (exc_type == err) return 1; + if (unlikely(!exc_type)) return 0; +#endif + #if CYTHON_AVOID_BORROWED_REFS + Py_INCREF(exc_type); + #endif + if (unlikely(PyTuple_Check(err))) { + result = __Pyx_PyErr_ExceptionMatchesTuple(exc_type, err); + } else { + result = __Pyx_PyErr_GivenExceptionMatches(exc_type, err); + } + #if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(exc_type); + #endif + return result; +} +#endif + +/* PyErrFetchRestore */ +#if CYTHON_FAST_THREAD_STATE +static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { +#if PY_VERSION_HEX >= 0x030C00A6 + PyObject *tmp_value; + assert(type == NULL || (value != NULL && type == (PyObject*) Py_TYPE(value))); + if (value) { + #if CYTHON_COMPILING_IN_CPYTHON + if (unlikely(((PyBaseExceptionObject*) value)->traceback != tb)) + #endif + PyException_SetTraceback(value, tb); + } + tmp_value = tstate->current_exception; + tstate->current_exception = value; + Py_XDECREF(tmp_value); + Py_XDECREF(type); + Py_XDECREF(tb); +#else + PyObject *tmp_type, *tmp_value, *tmp_tb; + tmp_type = tstate->curexc_type; + tmp_value = tstate->curexc_value; + tmp_tb = tstate->curexc_traceback; + tstate->curexc_type = type; + tstate->curexc_value = value; + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#endif +} +static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { +#if PY_VERSION_HEX >= 0x030C00A6 + PyObject* exc_value; + exc_value = tstate->current_exception; + tstate->current_exception = 0; + *value = exc_value; + *type = NULL; + *tb = NULL; + if (exc_value) { + *type = (PyObject*) Py_TYPE(exc_value); + Py_INCREF(*type); + #if CYTHON_COMPILING_IN_CPYTHON + *tb = ((PyBaseExceptionObject*) exc_value)->traceback; + Py_XINCREF(*tb); + #else + *tb = PyException_GetTraceback(exc_value); + #endif + } +#else + *type = tstate->curexc_type; + *value = tstate->curexc_value; + *tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; +#endif +} +#endif + +/* PyObjectGetAttrStr */ +#if CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro)) + return tp->tp_getattro(obj, attr_name); +#if PY_MAJOR_VERSION < 3 + if (likely(tp->tp_getattr)) + return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); +#endif + return PyObject_GetAttr(obj, attr_name); +} +#endif + +/* PyObjectGetAttrStrNoError */ +#if __PYX_LIMITED_VERSION_HEX < 0x030d00A1 +static void __Pyx_PyObject_GetAttrStr_ClearAttributeError(void) { + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + if (likely(__Pyx_PyErr_ExceptionMatches(PyExc_AttributeError))) + __Pyx_PyErr_Clear(); +} +#endif +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStrNoError(PyObject* obj, PyObject* attr_name) { + PyObject *result; +#if __PYX_LIMITED_VERSION_HEX >= 0x030d00A1 + (void) PyObject_GetOptionalAttr(obj, attr_name, &result); + return result; +#else +#if CYTHON_COMPILING_IN_CPYTHON && CYTHON_USE_TYPE_SLOTS && PY_VERSION_HEX >= 0x030700B1 + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro == PyObject_GenericGetAttr)) { + return _PyObject_GenericGetAttrWithDict(obj, attr_name, NULL, 1); + } +#endif + result = __Pyx_PyObject_GetAttrStr(obj, attr_name); + if (unlikely(!result)) { + __Pyx_PyObject_GetAttrStr_ClearAttributeError(); + } + return result; +#endif +} + +/* GetBuiltinName */ +static PyObject *__Pyx_GetBuiltinName(PyObject *name) { + PyObject* result = __Pyx_PyObject_GetAttrStrNoError(__pyx_b, name); + if (unlikely(!result) && !PyErr_Occurred()) { + PyErr_Format(PyExc_NameError, +#if PY_MAJOR_VERSION >= 3 + "name '%U' is not defined", name); +#else + "name '%.200s' is not defined", PyString_AS_STRING(name)); +#endif + } + return result; +} + +/* TupleAndListFromArray */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE void __Pyx_copy_object_array(PyObject *const *CYTHON_RESTRICT src, PyObject** CYTHON_RESTRICT dest, Py_ssize_t length) { + PyObject *v; + Py_ssize_t i; + for (i = 0; i < length; i++) { + v = dest[i] = src[i]; + Py_INCREF(v); + } +} +static CYTHON_INLINE PyObject * +__Pyx_PyTuple_FromArray(PyObject *const *src, Py_ssize_t n) +{ + PyObject *res; + if (n <= 0) { + Py_INCREF(__pyx_empty_tuple); + return __pyx_empty_tuple; + } + res = PyTuple_New(n); + if (unlikely(res == NULL)) return NULL; + __Pyx_copy_object_array(src, ((PyTupleObject*)res)->ob_item, n); + return res; +} +static CYTHON_INLINE PyObject * +__Pyx_PyList_FromArray(PyObject *const *src, Py_ssize_t n) +{ + PyObject *res; + if (n <= 0) { + return PyList_New(0); + } + res = PyList_New(n); + if (unlikely(res == NULL)) return NULL; + __Pyx_copy_object_array(src, ((PyListObject*)res)->ob_item, n); + return res; +} +#endif + +/* BytesEquals */ +static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals) { +#if CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API + return PyObject_RichCompareBool(s1, s2, equals); +#else + if (s1 == s2) { + return (equals == Py_EQ); + } else if (PyBytes_CheckExact(s1) & PyBytes_CheckExact(s2)) { + const char *ps1, *ps2; + Py_ssize_t length = PyBytes_GET_SIZE(s1); + if (length != PyBytes_GET_SIZE(s2)) + return (equals == Py_NE); + ps1 = PyBytes_AS_STRING(s1); + ps2 = PyBytes_AS_STRING(s2); + if (ps1[0] != ps2[0]) { + return (equals == Py_NE); + } else if (length == 1) { + return (equals == Py_EQ); + } else { + int result; +#if CYTHON_USE_UNICODE_INTERNALS && (PY_VERSION_HEX < 0x030B0000) + Py_hash_t hash1, hash2; + hash1 = ((PyBytesObject*)s1)->ob_shash; + hash2 = ((PyBytesObject*)s2)->ob_shash; + if (hash1 != hash2 && hash1 != -1 && hash2 != -1) { + return (equals == Py_NE); + } +#endif + result = memcmp(ps1, ps2, (size_t)length); + return (equals == Py_EQ) ? (result == 0) : (result != 0); + } + } else if ((s1 == Py_None) & PyBytes_CheckExact(s2)) { + return (equals == Py_NE); + } else if ((s2 == Py_None) & PyBytes_CheckExact(s1)) { + return (equals == Py_NE); + } else { + int result; + PyObject* py_result = PyObject_RichCompare(s1, s2, equals); + if (!py_result) + return -1; + result = __Pyx_PyObject_IsTrue(py_result); + Py_DECREF(py_result); + return result; + } +#endif +} + +/* UnicodeEquals */ +static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals) { +#if CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API + return PyObject_RichCompareBool(s1, s2, equals); +#else +#if PY_MAJOR_VERSION < 3 + PyObject* owned_ref = NULL; +#endif + int s1_is_unicode, s2_is_unicode; + if (s1 == s2) { + goto return_eq; + } + s1_is_unicode = PyUnicode_CheckExact(s1); + s2_is_unicode = PyUnicode_CheckExact(s2); +#if PY_MAJOR_VERSION < 3 + if ((s1_is_unicode & (!s2_is_unicode)) && PyString_CheckExact(s2)) { + owned_ref = PyUnicode_FromObject(s2); + if (unlikely(!owned_ref)) + return -1; + s2 = owned_ref; + s2_is_unicode = 1; + } else if ((s2_is_unicode & (!s1_is_unicode)) && PyString_CheckExact(s1)) { + owned_ref = PyUnicode_FromObject(s1); + if (unlikely(!owned_ref)) + return -1; + s1 = owned_ref; + s1_is_unicode = 1; + } else if (((!s2_is_unicode) & (!s1_is_unicode))) { + return __Pyx_PyBytes_Equals(s1, s2, equals); + } +#endif + if (s1_is_unicode & s2_is_unicode) { + Py_ssize_t length; + int kind; + void *data1, *data2; + if (unlikely(__Pyx_PyUnicode_READY(s1) < 0) || unlikely(__Pyx_PyUnicode_READY(s2) < 0)) + return -1; + length = __Pyx_PyUnicode_GET_LENGTH(s1); + if (length != __Pyx_PyUnicode_GET_LENGTH(s2)) { + goto return_ne; + } +#if CYTHON_USE_UNICODE_INTERNALS + { + Py_hash_t hash1, hash2; + #if CYTHON_PEP393_ENABLED + hash1 = ((PyASCIIObject*)s1)->hash; + hash2 = ((PyASCIIObject*)s2)->hash; + #else + hash1 = ((PyUnicodeObject*)s1)->hash; + hash2 = ((PyUnicodeObject*)s2)->hash; + #endif + if (hash1 != hash2 && hash1 != -1 && hash2 != -1) { + goto return_ne; + } + } +#endif + kind = __Pyx_PyUnicode_KIND(s1); + if (kind != __Pyx_PyUnicode_KIND(s2)) { + goto return_ne; + } + data1 = __Pyx_PyUnicode_DATA(s1); + data2 = __Pyx_PyUnicode_DATA(s2); + if (__Pyx_PyUnicode_READ(kind, data1, 0) != __Pyx_PyUnicode_READ(kind, data2, 0)) { + goto return_ne; + } else if (length == 1) { + goto return_eq; + } else { + int result = memcmp(data1, data2, (size_t)(length * kind)); + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(owned_ref); + #endif + return (equals == Py_EQ) ? (result == 0) : (result != 0); + } + } else if ((s1 == Py_None) & s2_is_unicode) { + goto return_ne; + } else if ((s2 == Py_None) & s1_is_unicode) { + goto return_ne; + } else { + int result; + PyObject* py_result = PyObject_RichCompare(s1, s2, equals); + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(owned_ref); + #endif + if (!py_result) + return -1; + result = __Pyx_PyObject_IsTrue(py_result); + Py_DECREF(py_result); + return result; + } +return_eq: + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(owned_ref); + #endif + return (equals == Py_EQ); +return_ne: + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(owned_ref); + #endif + return (equals == Py_NE); +#endif +} + +/* fastcall */ +#if CYTHON_METH_FASTCALL +static CYTHON_INLINE PyObject * __Pyx_GetKwValue_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues, PyObject *s) +{ + Py_ssize_t i, n = PyTuple_GET_SIZE(kwnames); + for (i = 0; i < n; i++) + { + if (s == PyTuple_GET_ITEM(kwnames, i)) return kwvalues[i]; + } + for (i = 0; i < n; i++) + { + int eq = __Pyx_PyUnicode_Equals(s, PyTuple_GET_ITEM(kwnames, i), Py_EQ); + if (unlikely(eq != 0)) { + if (unlikely(eq < 0)) return NULL; + return kwvalues[i]; + } + } + return NULL; +} +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030d0000 +CYTHON_UNUSED static PyObject *__Pyx_KwargsAsDict_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues) { + Py_ssize_t i, nkwargs = PyTuple_GET_SIZE(kwnames); + PyObject *dict; + dict = PyDict_New(); + if (unlikely(!dict)) + return NULL; + for (i=0; i= 3 + "%s() got multiple values for keyword argument '%U'", func_name, kw_name); + #else + "%s() got multiple values for keyword argument '%s'", func_name, + PyString_AsString(kw_name)); + #endif +} + +/* ParseKeywords */ +static int __Pyx_ParseOptionalKeywords( + PyObject *kwds, + PyObject *const *kwvalues, + PyObject **argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + const char* function_name) +{ + PyObject *key = 0, *value = 0; + Py_ssize_t pos = 0; + PyObject*** name; + PyObject*** first_kw_arg = argnames + num_pos_args; + int kwds_is_tuple = CYTHON_METH_FASTCALL && likely(PyTuple_Check(kwds)); + while (1) { + Py_XDECREF(key); key = NULL; + Py_XDECREF(value); value = NULL; + if (kwds_is_tuple) { + Py_ssize_t size; +#if CYTHON_ASSUME_SAFE_MACROS + size = PyTuple_GET_SIZE(kwds); +#else + size = PyTuple_Size(kwds); + if (size < 0) goto bad; +#endif + if (pos >= size) break; +#if CYTHON_AVOID_BORROWED_REFS + key = __Pyx_PySequence_ITEM(kwds, pos); + if (!key) goto bad; +#elif CYTHON_ASSUME_SAFE_MACROS + key = PyTuple_GET_ITEM(kwds, pos); +#else + key = PyTuple_GetItem(kwds, pos); + if (!key) goto bad; +#endif + value = kwvalues[pos]; + pos++; + } + else + { + if (!PyDict_Next(kwds, &pos, &key, &value)) break; +#if CYTHON_AVOID_BORROWED_REFS + Py_INCREF(key); +#endif + } + name = first_kw_arg; + while (*name && (**name != key)) name++; + if (*name) { + values[name-argnames] = value; +#if CYTHON_AVOID_BORROWED_REFS + Py_INCREF(value); + Py_DECREF(key); +#endif + key = NULL; + value = NULL; + continue; + } +#if !CYTHON_AVOID_BORROWED_REFS + Py_INCREF(key); +#endif + Py_INCREF(value); + name = first_kw_arg; + #if PY_MAJOR_VERSION < 3 + if (likely(PyString_Check(key))) { + while (*name) { + if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) + && _PyString_Eq(**name, key)) { + values[name-argnames] = value; +#if CYTHON_AVOID_BORROWED_REFS + value = NULL; +#endif + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + if ((**argname == key) || ( + (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) + && _PyString_Eq(**argname, key))) { + goto arg_passed_twice; + } + argname++; + } + } + } else + #endif + if (likely(PyUnicode_Check(key))) { + while (*name) { + int cmp = ( + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (__Pyx_PyUnicode_GET_LENGTH(**name) != __Pyx_PyUnicode_GET_LENGTH(key)) ? 1 : + #endif + PyUnicode_Compare(**name, key) + ); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) { + values[name-argnames] = value; +#if CYTHON_AVOID_BORROWED_REFS + value = NULL; +#endif + break; + } + name++; + } + if (*name) continue; + else { + PyObject*** argname = argnames; + while (argname != first_kw_arg) { + int cmp = (**argname == key) ? 0 : + #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 + (__Pyx_PyUnicode_GET_LENGTH(**argname) != __Pyx_PyUnicode_GET_LENGTH(key)) ? 1 : + #endif + PyUnicode_Compare(**argname, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) goto arg_passed_twice; + argname++; + } + } + } else + goto invalid_keyword_type; + if (kwds2) { + if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; + } else { + goto invalid_keyword; + } + } + Py_XDECREF(key); + Py_XDECREF(value); + return 0; +arg_passed_twice: + __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; +invalid_keyword_type: + PyErr_Format(PyExc_TypeError, + "%.200s() keywords must be strings", function_name); + goto bad; +invalid_keyword: + #if PY_MAJOR_VERSION < 3 + PyErr_Format(PyExc_TypeError, + "%.200s() got an unexpected keyword argument '%.200s'", + function_name, PyString_AsString(key)); + #else + PyErr_Format(PyExc_TypeError, + "%s() got an unexpected keyword argument '%U'", + function_name, key); + #endif +bad: + Py_XDECREF(key); + Py_XDECREF(value); + return -1; +} + +/* RaiseArgTupleInvalid */ +static void __Pyx_RaiseArgtupleInvalid( + const char* func_name, + int exact, + Py_ssize_t num_min, + Py_ssize_t num_max, + Py_ssize_t num_found) +{ + Py_ssize_t num_expected; + const char *more_or_less; + if (num_found < num_min) { + num_expected = num_min; + more_or_less = "at least"; + } else { + num_expected = num_max; + more_or_less = "at most"; + } + if (exact) { + more_or_less = "exactly"; + } + PyErr_Format(PyExc_TypeError, + "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", + func_name, more_or_less, num_expected, + (num_expected == 1) ? "" : "s", num_found); +} + +/* PyIntBinop */ +#if !CYTHON_COMPILING_IN_PYPY +static PyObject* __Pyx_PyInt_AddObjC(PyObject *op1, PyObject *op2, long intval, int inplace, int zerodivision_check) { + CYTHON_MAYBE_UNUSED_VAR(intval); + CYTHON_MAYBE_UNUSED_VAR(inplace); + CYTHON_UNUSED_VAR(zerodivision_check); + #if PY_MAJOR_VERSION < 3 + if (likely(PyInt_CheckExact(op1))) { + const long b = intval; + long x; + long a = PyInt_AS_LONG(op1); + + x = (long)((unsigned long)a + (unsigned long)b); + if (likely((x^a) >= 0 || (x^b) >= 0)) + return PyInt_FromLong(x); + return PyLong_Type.tp_as_number->nb_add(op1, op2); + } + #endif + #if CYTHON_USE_PYLONG_INTERNALS + if (likely(PyLong_CheckExact(op1))) { + const long b = intval; + long a, x; +#ifdef HAVE_LONG_LONG + const PY_LONG_LONG llb = intval; + PY_LONG_LONG lla, llx; +#endif + if (unlikely(__Pyx_PyLong_IsZero(op1))) { + return __Pyx_NewRef(op2); + } + if (likely(__Pyx_PyLong_IsCompact(op1))) { + a = __Pyx_PyLong_CompactValue(op1); + } else { + const digit* digits = __Pyx_PyLong_Digits(op1); + const Py_ssize_t size = __Pyx_PyLong_SignedDigitCount(op1); + switch (size) { + case -2: + if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { + a = -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + break; + #ifdef HAVE_LONG_LONG + } else if (8 * sizeof(PY_LONG_LONG) - 1 > 2 * PyLong_SHIFT) { + lla = -(PY_LONG_LONG) (((((unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + goto long_long; + #endif + } + CYTHON_FALLTHROUGH; + case 2: + if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { + a = (long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + break; + #ifdef HAVE_LONG_LONG + } else if (8 * sizeof(PY_LONG_LONG) - 1 > 2 * PyLong_SHIFT) { + lla = (PY_LONG_LONG) (((((unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + goto long_long; + #endif + } + CYTHON_FALLTHROUGH; + case -3: + if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { + a = -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + break; + #ifdef HAVE_LONG_LONG + } else if (8 * sizeof(PY_LONG_LONG) - 1 > 3 * PyLong_SHIFT) { + lla = -(PY_LONG_LONG) (((((((unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + goto long_long; + #endif + } + CYTHON_FALLTHROUGH; + case 3: + if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { + a = (long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + break; + #ifdef HAVE_LONG_LONG + } else if (8 * sizeof(PY_LONG_LONG) - 1 > 3 * PyLong_SHIFT) { + lla = (PY_LONG_LONG) (((((((unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + goto long_long; + #endif + } + CYTHON_FALLTHROUGH; + case -4: + if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { + a = -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + break; + #ifdef HAVE_LONG_LONG + } else if (8 * sizeof(PY_LONG_LONG) - 1 > 4 * PyLong_SHIFT) { + lla = -(PY_LONG_LONG) (((((((((unsigned PY_LONG_LONG)digits[3]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + goto long_long; + #endif + } + CYTHON_FALLTHROUGH; + case 4: + if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { + a = (long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + break; + #ifdef HAVE_LONG_LONG + } else if (8 * sizeof(PY_LONG_LONG) - 1 > 4 * PyLong_SHIFT) { + lla = (PY_LONG_LONG) (((((((((unsigned PY_LONG_LONG)digits[3]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + goto long_long; + #endif + } + CYTHON_FALLTHROUGH; + default: return PyLong_Type.tp_as_number->nb_add(op1, op2); + } + } + x = a + b; + return PyLong_FromLong(x); +#ifdef HAVE_LONG_LONG + long_long: + llx = lla + llb; + return PyLong_FromLongLong(llx); +#endif + + + } + #endif + if (PyFloat_CheckExact(op1)) { + const long b = intval; +#if CYTHON_COMPILING_IN_LIMITED_API + double a = __pyx_PyFloat_AsDouble(op1); +#else + double a = PyFloat_AS_DOUBLE(op1); +#endif + double result; + + PyFPE_START_PROTECT("add", return NULL) + result = ((double)a) + (double)b; + PyFPE_END_PROTECT(result) + return PyFloat_FromDouble(result); + } + return (inplace ? PyNumber_InPlaceAdd : PyNumber_Add)(op1, op2); +} +#endif + +/* PyFunctionFastCall */ +#if CYTHON_FAST_PYCALL && !CYTHON_VECTORCALL +static PyObject* __Pyx_PyFunction_FastCallNoKw(PyCodeObject *co, PyObject **args, Py_ssize_t na, + PyObject *globals) { + PyFrameObject *f; + PyThreadState *tstate = __Pyx_PyThreadState_Current; + PyObject **fastlocals; + Py_ssize_t i; + PyObject *result; + assert(globals != NULL); + /* XXX Perhaps we should create a specialized + PyFrame_New() that doesn't take locals, but does + take builtins without sanity checking them. + */ + assert(tstate != NULL); + f = PyFrame_New(tstate, co, globals, NULL); + if (f == NULL) { + return NULL; + } + fastlocals = __Pyx_PyFrame_GetLocalsplus(f); + for (i = 0; i < na; i++) { + Py_INCREF(*args); + fastlocals[i] = *args++; + } + result = PyEval_EvalFrameEx(f,0); + ++tstate->recursion_depth; + Py_DECREF(f); + --tstate->recursion_depth; + return result; +} +static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, Py_ssize_t nargs, PyObject *kwargs) { + PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func); + PyObject *globals = PyFunction_GET_GLOBALS(func); + PyObject *argdefs = PyFunction_GET_DEFAULTS(func); + PyObject *closure; +#if PY_MAJOR_VERSION >= 3 + PyObject *kwdefs; +#endif + PyObject *kwtuple, **k; + PyObject **d; + Py_ssize_t nd; + Py_ssize_t nk; + PyObject *result; + assert(kwargs == NULL || PyDict_Check(kwargs)); + nk = kwargs ? PyDict_Size(kwargs) : 0; + #if PY_MAJOR_VERSION < 3 + if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) { + return NULL; + } + #else + if (unlikely(Py_EnterRecursiveCall(" while calling a Python object"))) { + return NULL; + } + #endif + if ( +#if PY_MAJOR_VERSION >= 3 + co->co_kwonlyargcount == 0 && +#endif + likely(kwargs == NULL || nk == 0) && + co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) { + if (argdefs == NULL && co->co_argcount == nargs) { + result = __Pyx_PyFunction_FastCallNoKw(co, args, nargs, globals); + goto done; + } + else if (nargs == 0 && argdefs != NULL + && co->co_argcount == Py_SIZE(argdefs)) { + /* function called with no arguments, but all parameters have + a default value: use default values as arguments .*/ + args = &PyTuple_GET_ITEM(argdefs, 0); + result =__Pyx_PyFunction_FastCallNoKw(co, args, Py_SIZE(argdefs), globals); + goto done; + } + } + if (kwargs != NULL) { + Py_ssize_t pos, i; + kwtuple = PyTuple_New(2 * nk); + if (kwtuple == NULL) { + result = NULL; + goto done; + } + k = &PyTuple_GET_ITEM(kwtuple, 0); + pos = i = 0; + while (PyDict_Next(kwargs, &pos, &k[i], &k[i+1])) { + Py_INCREF(k[i]); + Py_INCREF(k[i+1]); + i += 2; + } + nk = i / 2; + } + else { + kwtuple = NULL; + k = NULL; + } + closure = PyFunction_GET_CLOSURE(func); +#if PY_MAJOR_VERSION >= 3 + kwdefs = PyFunction_GET_KW_DEFAULTS(func); +#endif + if (argdefs != NULL) { + d = &PyTuple_GET_ITEM(argdefs, 0); + nd = Py_SIZE(argdefs); + } + else { + d = NULL; + nd = 0; + } +#if PY_MAJOR_VERSION >= 3 + result = PyEval_EvalCodeEx((PyObject*)co, globals, (PyObject *)NULL, + args, (int)nargs, + k, (int)nk, + d, (int)nd, kwdefs, closure); +#else + result = PyEval_EvalCodeEx(co, globals, (PyObject *)NULL, + args, (int)nargs, + k, (int)nk, + d, (int)nd, closure); +#endif + Py_XDECREF(kwtuple); +done: + Py_LeaveRecursiveCall(); + return result; +} +#endif + +/* PyObjectCall */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { + PyObject *result; + ternaryfunc call = Py_TYPE(func)->tp_call; + if (unlikely(!call)) + return PyObject_Call(func, arg, kw); + #if PY_MAJOR_VERSION < 3 + if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) + return NULL; + #else + if (unlikely(Py_EnterRecursiveCall(" while calling a Python object"))) + return NULL; + #endif + result = (*call)(func, arg, kw); + Py_LeaveRecursiveCall(); + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + } + return result; +} +#endif + +/* PyObjectCallMethO */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg) { + PyObject *self, *result; + PyCFunction cfunc; + cfunc = __Pyx_CyOrPyCFunction_GET_FUNCTION(func); + self = __Pyx_CyOrPyCFunction_GET_SELF(func); + #if PY_MAJOR_VERSION < 3 + if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) + return NULL; + #else + if (unlikely(Py_EnterRecursiveCall(" while calling a Python object"))) + return NULL; + #endif + result = cfunc(self, arg); + Py_LeaveRecursiveCall(); + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + } + return result; +} +#endif + +/* PyObjectFastCall */ +#if PY_VERSION_HEX < 0x03090000 || CYTHON_COMPILING_IN_LIMITED_API +static PyObject* __Pyx_PyObject_FastCall_fallback(PyObject *func, PyObject **args, size_t nargs, PyObject *kwargs) { + PyObject *argstuple; + PyObject *result = 0; + size_t i; + argstuple = PyTuple_New((Py_ssize_t)nargs); + if (unlikely(!argstuple)) return NULL; + for (i = 0; i < nargs; i++) { + Py_INCREF(args[i]); + if (__Pyx_PyTuple_SET_ITEM(argstuple, (Py_ssize_t)i, args[i]) < 0) goto bad; + } + result = __Pyx_PyObject_Call(func, argstuple, kwargs); + bad: + Py_DECREF(argstuple); + return result; +} +#endif +static CYTHON_INLINE PyObject* __Pyx_PyObject_FastCallDict(PyObject *func, PyObject **args, size_t _nargs, PyObject *kwargs) { + Py_ssize_t nargs = __Pyx_PyVectorcall_NARGS(_nargs); +#if CYTHON_COMPILING_IN_CPYTHON + if (nargs == 0 && kwargs == NULL) { + if (__Pyx_CyOrPyCFunction_Check(func) && likely( __Pyx_CyOrPyCFunction_GET_FLAGS(func) & METH_NOARGS)) + return __Pyx_PyObject_CallMethO(func, NULL); + } + else if (nargs == 1 && kwargs == NULL) { + if (__Pyx_CyOrPyCFunction_Check(func) && likely( __Pyx_CyOrPyCFunction_GET_FLAGS(func) & METH_O)) + return __Pyx_PyObject_CallMethO(func, args[0]); + } +#endif + #if PY_VERSION_HEX < 0x030800B1 + #if CYTHON_FAST_PYCCALL + if (PyCFunction_Check(func)) { + if (kwargs) { + return _PyCFunction_FastCallDict(func, args, nargs, kwargs); + } else { + return _PyCFunction_FastCallKeywords(func, args, nargs, NULL); + } + } + #if PY_VERSION_HEX >= 0x030700A1 + if (!kwargs && __Pyx_IS_TYPE(func, &PyMethodDescr_Type)) { + return _PyMethodDescr_FastCallKeywords(func, args, nargs, NULL); + } + #endif + #endif + #if CYTHON_FAST_PYCALL + if (PyFunction_Check(func)) { + return __Pyx_PyFunction_FastCallDict(func, args, nargs, kwargs); + } + #endif + #endif + if (kwargs == NULL) { + #if CYTHON_VECTORCALL + #if PY_VERSION_HEX < 0x03090000 + vectorcallfunc f = _PyVectorcall_Function(func); + #else + vectorcallfunc f = PyVectorcall_Function(func); + #endif + if (f) { + return f(func, args, (size_t)nargs, NULL); + } + #elif defined(__Pyx_CyFunction_USED) && CYTHON_BACKPORT_VECTORCALL + if (__Pyx_CyFunction_CheckExact(func)) { + __pyx_vectorcallfunc f = __Pyx_CyFunction_func_vectorcall(func); + if (f) return f(func, args, (size_t)nargs, NULL); + } + #endif + } + if (nargs == 0) { + return __Pyx_PyObject_Call(func, __pyx_empty_tuple, kwargs); + } + #if PY_VERSION_HEX >= 0x03090000 && !CYTHON_COMPILING_IN_LIMITED_API + return PyObject_VectorcallDict(func, args, (size_t)nargs, kwargs); + #else + return __Pyx_PyObject_FastCall_fallback(func, args, (size_t)nargs, kwargs); + #endif +} + +/* SliceObject */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetSlice(PyObject* obj, + Py_ssize_t cstart, Py_ssize_t cstop, + PyObject** _py_start, PyObject** _py_stop, PyObject** _py_slice, + int has_cstart, int has_cstop, int wraparound) { + __Pyx_TypeName obj_type_name; +#if CYTHON_USE_TYPE_SLOTS + PyMappingMethods* mp; +#if PY_MAJOR_VERSION < 3 + PySequenceMethods* ms = Py_TYPE(obj)->tp_as_sequence; + if (likely(ms && ms->sq_slice)) { + if (!has_cstart) { + if (_py_start && (*_py_start != Py_None)) { + cstart = __Pyx_PyIndex_AsSsize_t(*_py_start); + if ((cstart == (Py_ssize_t)-1) && PyErr_Occurred()) goto bad; + } else + cstart = 0; + } + if (!has_cstop) { + if (_py_stop && (*_py_stop != Py_None)) { + cstop = __Pyx_PyIndex_AsSsize_t(*_py_stop); + if ((cstop == (Py_ssize_t)-1) && PyErr_Occurred()) goto bad; + } else + cstop = PY_SSIZE_T_MAX; + } + if (wraparound && unlikely((cstart < 0) | (cstop < 0)) && likely(ms->sq_length)) { + Py_ssize_t l = ms->sq_length(obj); + if (likely(l >= 0)) { + if (cstop < 0) { + cstop += l; + if (cstop < 0) cstop = 0; + } + if (cstart < 0) { + cstart += l; + if (cstart < 0) cstart = 0; + } + } else { + if (!PyErr_ExceptionMatches(PyExc_OverflowError)) + goto bad; + PyErr_Clear(); + } + } + return ms->sq_slice(obj, cstart, cstop); + } +#else + CYTHON_UNUSED_VAR(wraparound); +#endif + mp = Py_TYPE(obj)->tp_as_mapping; + if (likely(mp && mp->mp_subscript)) +#else + CYTHON_UNUSED_VAR(wraparound); +#endif + { + PyObject* result; + PyObject *py_slice, *py_start, *py_stop; + if (_py_slice) { + py_slice = *_py_slice; + } else { + PyObject* owned_start = NULL; + PyObject* owned_stop = NULL; + if (_py_start) { + py_start = *_py_start; + } else { + if (has_cstart) { + owned_start = py_start = PyInt_FromSsize_t(cstart); + if (unlikely(!py_start)) goto bad; + } else + py_start = Py_None; + } + if (_py_stop) { + py_stop = *_py_stop; + } else { + if (has_cstop) { + owned_stop = py_stop = PyInt_FromSsize_t(cstop); + if (unlikely(!py_stop)) { + Py_XDECREF(owned_start); + goto bad; + } + } else + py_stop = Py_None; + } + py_slice = PySlice_New(py_start, py_stop, Py_None); + Py_XDECREF(owned_start); + Py_XDECREF(owned_stop); + if (unlikely(!py_slice)) goto bad; + } +#if CYTHON_USE_TYPE_SLOTS + result = mp->mp_subscript(obj, py_slice); +#else + result = PyObject_GetItem(obj, py_slice); +#endif + if (!_py_slice) { + Py_DECREF(py_slice); + } + return result; + } + obj_type_name = __Pyx_PyType_GetName(Py_TYPE(obj)); + PyErr_Format(PyExc_TypeError, + "'" __Pyx_FMT_TYPENAME "' object is unsliceable", obj_type_name); + __Pyx_DECREF_TypeName(obj_type_name); +bad: + return NULL; +} + +/* KeywordStringCheck */ +static int __Pyx_CheckKeywordStrings( + PyObject *kw, + const char* function_name, + int kw_allowed) +{ + PyObject* key = 0; + Py_ssize_t pos = 0; +#if CYTHON_COMPILING_IN_PYPY + if (!kw_allowed && PyDict_Next(kw, &pos, &key, 0)) + goto invalid_keyword; + return 1; +#else + if (CYTHON_METH_FASTCALL && likely(PyTuple_Check(kw))) { + Py_ssize_t kwsize; +#if CYTHON_ASSUME_SAFE_MACROS + kwsize = PyTuple_GET_SIZE(kw); +#else + kwsize = PyTuple_Size(kw); + if (kwsize < 0) return 0; +#endif + if (unlikely(kwsize == 0)) + return 1; + if (!kw_allowed) { +#if CYTHON_ASSUME_SAFE_MACROS + key = PyTuple_GET_ITEM(kw, 0); +#else + key = PyTuple_GetItem(kw, pos); + if (!key) return 0; +#endif + goto invalid_keyword; + } +#if PY_VERSION_HEX < 0x03090000 + for (pos = 0; pos < kwsize; pos++) { +#if CYTHON_ASSUME_SAFE_MACROS + key = PyTuple_GET_ITEM(kw, pos); +#else + key = PyTuple_GetItem(kw, pos); + if (!key) return 0; +#endif + if (unlikely(!PyUnicode_Check(key))) + goto invalid_keyword_type; + } +#endif + return 1; + } + while (PyDict_Next(kw, &pos, &key, 0)) { + #if PY_MAJOR_VERSION < 3 + if (unlikely(!PyString_Check(key))) + #endif + if (unlikely(!PyUnicode_Check(key))) + goto invalid_keyword_type; + } + if (!kw_allowed && unlikely(key)) + goto invalid_keyword; + return 1; +invalid_keyword_type: + PyErr_Format(PyExc_TypeError, + "%.200s() keywords must be strings", function_name); + return 0; +#endif +invalid_keyword: + #if PY_MAJOR_VERSION < 3 + PyErr_Format(PyExc_TypeError, + "%.200s() got an unexpected keyword argument '%.200s'", + function_name, PyString_AsString(key)); + #else + PyErr_Format(PyExc_TypeError, + "%s() got an unexpected keyword argument '%U'", + function_name, key); + #endif + return 0; +} + +/* PyObjectCallOneArg */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { + PyObject *args[2] = {NULL, arg}; + return __Pyx_PyObject_FastCall(func, args+1, 1 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET); +} + +/* RaiseUnexpectedTypeError */ +static int +__Pyx_RaiseUnexpectedTypeError(const char *expected, PyObject *obj) +{ + __Pyx_TypeName obj_type_name = __Pyx_PyType_GetName(Py_TYPE(obj)); + PyErr_Format(PyExc_TypeError, "Expected %s, got " __Pyx_FMT_TYPENAME, + expected, obj_type_name); + __Pyx_DECREF_TypeName(obj_type_name); + return 0; +} + +/* UnicodeConcatInPlace */ +# if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 +static int +__Pyx_unicode_modifiable(PyObject *unicode) +{ + if (Py_REFCNT(unicode) != 1) + return 0; + if (!PyUnicode_CheckExact(unicode)) + return 0; + if (PyUnicode_CHECK_INTERNED(unicode)) + return 0; + return 1; +} +static CYTHON_INLINE PyObject *__Pyx_PyUnicode_ConcatInPlaceImpl(PyObject **p_left, PyObject *right + #if CYTHON_REFNANNY + , void* __pyx_refnanny + #endif + ) { + PyObject *left = *p_left; + Py_ssize_t left_len, right_len, new_len; + if (unlikely(__Pyx_PyUnicode_READY(left) == -1)) + return NULL; + if (unlikely(__Pyx_PyUnicode_READY(right) == -1)) + return NULL; + left_len = PyUnicode_GET_LENGTH(left); + if (left_len == 0) { + Py_INCREF(right); + return right; + } + right_len = PyUnicode_GET_LENGTH(right); + if (right_len == 0) { + Py_INCREF(left); + return left; + } + if (unlikely(left_len > PY_SSIZE_T_MAX - right_len)) { + PyErr_SetString(PyExc_OverflowError, + "strings are too large to concat"); + return NULL; + } + new_len = left_len + right_len; + if (__Pyx_unicode_modifiable(left) + && PyUnicode_CheckExact(right) + && PyUnicode_KIND(right) <= PyUnicode_KIND(left) + && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right))) { + int ret; + __Pyx_GIVEREF(*p_left); + ret = PyUnicode_Resize(p_left, new_len); + __Pyx_GOTREF(*p_left); + if (unlikely(ret != 0)) + return NULL; + #if PY_VERSION_HEX >= 0x030d0000 + if (unlikely(PyUnicode_CopyCharacters(*p_left, left_len, right, 0, right_len) < 0)) return NULL; + #else + _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len); + #endif + __Pyx_INCREF(*p_left); + __Pyx_GIVEREF(*p_left); + return *p_left; + } else { + return __Pyx_PyUnicode_Concat(left, right); + } + } +#endif + +/* GetItemInt */ +static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { + PyObject *r; + if (unlikely(!j)) return NULL; + r = PyObject_GetItem(o, j); + Py_DECREF(j); + return r; +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + CYTHON_NCP_UNUSED int wraparound, + CYTHON_NCP_UNUSED int boundscheck) { +#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + Py_ssize_t wrapped_i = i; + if (wraparound & unlikely(i < 0)) { + wrapped_i += PyList_GET_SIZE(o); + } + if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, PyList_GET_SIZE(o)))) { + PyObject *r = PyList_GET_ITEM(o, wrapped_i); + Py_INCREF(r); + return r; + } + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +#else + return PySequence_GetItem(o, i); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + CYTHON_NCP_UNUSED int wraparound, + CYTHON_NCP_UNUSED int boundscheck) { +#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + Py_ssize_t wrapped_i = i; + if (wraparound & unlikely(i < 0)) { + wrapped_i += PyTuple_GET_SIZE(o); + } + if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, PyTuple_GET_SIZE(o)))) { + PyObject *r = PyTuple_GET_ITEM(o, wrapped_i); + Py_INCREF(r); + return r; + } + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +#else + return PySequence_GetItem(o, i); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, int is_list, + CYTHON_NCP_UNUSED int wraparound, + CYTHON_NCP_UNUSED int boundscheck) { +#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS && CYTHON_USE_TYPE_SLOTS + if (is_list || PyList_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); + if ((!boundscheck) || (likely(__Pyx_is_valid_index(n, PyList_GET_SIZE(o))))) { + PyObject *r = PyList_GET_ITEM(o, n); + Py_INCREF(r); + return r; + } + } + else if (PyTuple_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); + if ((!boundscheck) || likely(__Pyx_is_valid_index(n, PyTuple_GET_SIZE(o)))) { + PyObject *r = PyTuple_GET_ITEM(o, n); + Py_INCREF(r); + return r; + } + } else { + PyMappingMethods *mm = Py_TYPE(o)->tp_as_mapping; + PySequenceMethods *sm = Py_TYPE(o)->tp_as_sequence; + if (mm && mm->mp_subscript) { + PyObject *r, *key = PyInt_FromSsize_t(i); + if (unlikely(!key)) return NULL; + r = mm->mp_subscript(o, key); + Py_DECREF(key); + return r; + } + if (likely(sm && sm->sq_item)) { + if (wraparound && unlikely(i < 0) && likely(sm->sq_length)) { + Py_ssize_t l = sm->sq_length(o); + if (likely(l >= 0)) { + i += l; + } else { + if (!PyErr_ExceptionMatches(PyExc_OverflowError)) + return NULL; + PyErr_Clear(); + } + } + return sm->sq_item(o, i); + } + } +#else + if (is_list || !PyMapping_Check(o)) { + return PySequence_GetItem(o, i); + } +#endif + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +} + +/* PyObjectCall2Args */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2) { + PyObject *args[3] = {NULL, arg1, arg2}; + return __Pyx_PyObject_FastCall(function, args+1, 2 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET); +} + +/* PyObjectGetMethod */ +static int __Pyx_PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method) { + PyObject *attr; +#if CYTHON_UNPACK_METHODS && CYTHON_COMPILING_IN_CPYTHON && CYTHON_USE_PYTYPE_LOOKUP + __Pyx_TypeName type_name; + PyTypeObject *tp = Py_TYPE(obj); + PyObject *descr; + descrgetfunc f = NULL; + PyObject **dictptr, *dict; + int meth_found = 0; + assert (*method == NULL); + if (unlikely(tp->tp_getattro != PyObject_GenericGetAttr)) { + attr = __Pyx_PyObject_GetAttrStr(obj, name); + goto try_unpack; + } + if (unlikely(tp->tp_dict == NULL) && unlikely(PyType_Ready(tp) < 0)) { + return 0; + } + descr = _PyType_Lookup(tp, name); + if (likely(descr != NULL)) { + Py_INCREF(descr); +#if defined(Py_TPFLAGS_METHOD_DESCRIPTOR) && Py_TPFLAGS_METHOD_DESCRIPTOR + if (__Pyx_PyType_HasFeature(Py_TYPE(descr), Py_TPFLAGS_METHOD_DESCRIPTOR)) +#elif PY_MAJOR_VERSION >= 3 + #ifdef __Pyx_CyFunction_USED + if (likely(PyFunction_Check(descr) || __Pyx_IS_TYPE(descr, &PyMethodDescr_Type) || __Pyx_CyFunction_Check(descr))) + #else + if (likely(PyFunction_Check(descr) || __Pyx_IS_TYPE(descr, &PyMethodDescr_Type))) + #endif +#else + #ifdef __Pyx_CyFunction_USED + if (likely(PyFunction_Check(descr) || __Pyx_CyFunction_Check(descr))) + #else + if (likely(PyFunction_Check(descr))) + #endif +#endif + { + meth_found = 1; + } else { + f = Py_TYPE(descr)->tp_descr_get; + if (f != NULL && PyDescr_IsData(descr)) { + attr = f(descr, obj, (PyObject *)Py_TYPE(obj)); + Py_DECREF(descr); + goto try_unpack; + } + } + } + dictptr = _PyObject_GetDictPtr(obj); + if (dictptr != NULL && (dict = *dictptr) != NULL) { + Py_INCREF(dict); + attr = __Pyx_PyDict_GetItemStr(dict, name); + if (attr != NULL) { + Py_INCREF(attr); + Py_DECREF(dict); + Py_XDECREF(descr); + goto try_unpack; + } + Py_DECREF(dict); + } + if (meth_found) { + *method = descr; + return 1; + } + if (f != NULL) { + attr = f(descr, obj, (PyObject *)Py_TYPE(obj)); + Py_DECREF(descr); + goto try_unpack; + } + if (likely(descr != NULL)) { + *method = descr; + return 0; + } + type_name = __Pyx_PyType_GetName(tp); + PyErr_Format(PyExc_AttributeError, +#if PY_MAJOR_VERSION >= 3 + "'" __Pyx_FMT_TYPENAME "' object has no attribute '%U'", + type_name, name); +#else + "'" __Pyx_FMT_TYPENAME "' object has no attribute '%.400s'", + type_name, PyString_AS_STRING(name)); +#endif + __Pyx_DECREF_TypeName(type_name); + return 0; +#else + attr = __Pyx_PyObject_GetAttrStr(obj, name); + goto try_unpack; +#endif +try_unpack: +#if CYTHON_UNPACK_METHODS + if (likely(attr) && PyMethod_Check(attr) && likely(PyMethod_GET_SELF(attr) == obj)) { + PyObject *function = PyMethod_GET_FUNCTION(attr); + Py_INCREF(function); + Py_DECREF(attr); + *method = function; + return 1; + } +#endif + *method = attr; + return 0; +} + +/* PyObjectCallMethod1 */ +#if !(CYTHON_VECTORCALL && __PYX_LIMITED_VERSION_HEX >= 0x030C00A2) +static PyObject* __Pyx__PyObject_CallMethod1(PyObject* method, PyObject* arg) { + PyObject *result = __Pyx_PyObject_CallOneArg(method, arg); + Py_DECREF(method); + return result; +} +#endif +static PyObject* __Pyx_PyObject_CallMethod1(PyObject* obj, PyObject* method_name, PyObject* arg) { +#if CYTHON_VECTORCALL && __PYX_LIMITED_VERSION_HEX >= 0x030C00A2 + PyObject *args[2] = {obj, arg}; + (void) __Pyx_PyObject_GetMethod; + (void) __Pyx_PyObject_CallOneArg; + (void) __Pyx_PyObject_Call2Args; + return PyObject_VectorcallMethod(method_name, args, 2 | PY_VECTORCALL_ARGUMENTS_OFFSET, NULL); +#else + PyObject *method = NULL, *result; + int is_method = __Pyx_PyObject_GetMethod(obj, method_name, &method); + if (likely(is_method)) { + result = __Pyx_PyObject_Call2Args(method, obj, arg); + Py_DECREF(method); + return result; + } + if (unlikely(!method)) return NULL; + return __Pyx__PyObject_CallMethod1(method, arg); +#endif +} + +/* StringJoin */ +static CYTHON_INLINE PyObject* __Pyx_PyBytes_Join(PyObject* sep, PyObject* values) { + (void) __Pyx_PyObject_CallMethod1; +#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION < 3 + return _PyString_Join(sep, values); +#elif CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030d0000 + return _PyBytes_Join(sep, values); +#else + return __Pyx_PyObject_CallMethod1(sep, __pyx_n_s_join, values); +#endif +} + +/* decode_c_bytes */ +static CYTHON_INLINE PyObject* __Pyx_decode_c_bytes( + const char* cstring, Py_ssize_t length, Py_ssize_t start, Py_ssize_t stop, + const char* encoding, const char* errors, + PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) { + if (unlikely((start < 0) | (stop < 0))) { + if (start < 0) { + start += length; + if (start < 0) + start = 0; + } + if (stop < 0) + stop += length; + } + if (stop > length) + stop = length; + if (unlikely(stop <= start)) + return __Pyx_NewRef(__pyx_empty_unicode); + length = stop - start; + cstring += start; + if (decode_func) { + return decode_func(cstring, length, errors); + } else { + return PyUnicode_Decode(cstring, length, encoding, errors); + } +} + +/* PyObjectLookupSpecial */ +#if CYTHON_USE_PYTYPE_LOOKUP && CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE PyObject* __Pyx__PyObject_LookupSpecial(PyObject* obj, PyObject* attr_name, int with_error) { + PyObject *res; + PyTypeObject *tp = Py_TYPE(obj); +#if PY_MAJOR_VERSION < 3 + if (unlikely(PyInstance_Check(obj))) + return with_error ? __Pyx_PyObject_GetAttrStr(obj, attr_name) : __Pyx_PyObject_GetAttrStrNoError(obj, attr_name); +#endif + res = _PyType_Lookup(tp, attr_name); + if (likely(res)) { + descrgetfunc f = Py_TYPE(res)->tp_descr_get; + if (!f) { + Py_INCREF(res); + } else { + res = f(res, obj, (PyObject *)tp); + } + } else if (with_error) { + PyErr_SetObject(PyExc_AttributeError, attr_name); + } + return res; +} +#endif + +/* GetTopmostException */ +#if CYTHON_USE_EXC_INFO_STACK && CYTHON_FAST_THREAD_STATE +static _PyErr_StackItem * +__Pyx_PyErr_GetTopmostException(PyThreadState *tstate) +{ + _PyErr_StackItem *exc_info = tstate->exc_info; + while ((exc_info->exc_value == NULL || exc_info->exc_value == Py_None) && + exc_info->previous_item != NULL) + { + exc_info = exc_info->previous_item; + } + return exc_info; +} +#endif + +/* SaveResetException */ +#if CYTHON_FAST_THREAD_STATE +static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { + #if CYTHON_USE_EXC_INFO_STACK && PY_VERSION_HEX >= 0x030B00a4 + _PyErr_StackItem *exc_info = __Pyx_PyErr_GetTopmostException(tstate); + PyObject *exc_value = exc_info->exc_value; + if (exc_value == NULL || exc_value == Py_None) { + *value = NULL; + *type = NULL; + *tb = NULL; + } else { + *value = exc_value; + Py_INCREF(*value); + *type = (PyObject*) Py_TYPE(exc_value); + Py_INCREF(*type); + *tb = PyException_GetTraceback(exc_value); + } + #elif CYTHON_USE_EXC_INFO_STACK + _PyErr_StackItem *exc_info = __Pyx_PyErr_GetTopmostException(tstate); + *type = exc_info->exc_type; + *value = exc_info->exc_value; + *tb = exc_info->exc_traceback; + Py_XINCREF(*type); + Py_XINCREF(*value); + Py_XINCREF(*tb); + #else + *type = tstate->exc_type; + *value = tstate->exc_value; + *tb = tstate->exc_traceback; + Py_XINCREF(*type); + Py_XINCREF(*value); + Py_XINCREF(*tb); + #endif +} +static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { + #if CYTHON_USE_EXC_INFO_STACK && PY_VERSION_HEX >= 0x030B00a4 + _PyErr_StackItem *exc_info = tstate->exc_info; + PyObject *tmp_value = exc_info->exc_value; + exc_info->exc_value = value; + Py_XDECREF(tmp_value); + Py_XDECREF(type); + Py_XDECREF(tb); + #else + PyObject *tmp_type, *tmp_value, *tmp_tb; + #if CYTHON_USE_EXC_INFO_STACK + _PyErr_StackItem *exc_info = tstate->exc_info; + tmp_type = exc_info->exc_type; + tmp_value = exc_info->exc_value; + tmp_tb = exc_info->exc_traceback; + exc_info->exc_type = type; + exc_info->exc_value = value; + exc_info->exc_traceback = tb; + #else + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = type; + tstate->exc_value = value; + tstate->exc_traceback = tb; + #endif + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); + #endif +} +#endif + +/* GetException */ +#if CYTHON_FAST_THREAD_STATE +static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) +#else +static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) +#endif +{ + PyObject *local_type = NULL, *local_value, *local_tb = NULL; +#if CYTHON_FAST_THREAD_STATE + PyObject *tmp_type, *tmp_value, *tmp_tb; + #if PY_VERSION_HEX >= 0x030C00A6 + local_value = tstate->current_exception; + tstate->current_exception = 0; + if (likely(local_value)) { + local_type = (PyObject*) Py_TYPE(local_value); + Py_INCREF(local_type); + local_tb = PyException_GetTraceback(local_value); + } + #else + local_type = tstate->curexc_type; + local_value = tstate->curexc_value; + local_tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; + #endif +#else + PyErr_Fetch(&local_type, &local_value, &local_tb); +#endif + PyErr_NormalizeException(&local_type, &local_value, &local_tb); +#if CYTHON_FAST_THREAD_STATE && PY_VERSION_HEX >= 0x030C00A6 + if (unlikely(tstate->current_exception)) +#elif CYTHON_FAST_THREAD_STATE + if (unlikely(tstate->curexc_type)) +#else + if (unlikely(PyErr_Occurred())) +#endif + goto bad; + #if PY_MAJOR_VERSION >= 3 + if (local_tb) { + if (unlikely(PyException_SetTraceback(local_value, local_tb) < 0)) + goto bad; + } + #endif + Py_XINCREF(local_tb); + Py_XINCREF(local_type); + Py_XINCREF(local_value); + *type = local_type; + *value = local_value; + *tb = local_tb; +#if CYTHON_FAST_THREAD_STATE + #if CYTHON_USE_EXC_INFO_STACK + { + _PyErr_StackItem *exc_info = tstate->exc_info; + #if PY_VERSION_HEX >= 0x030B00a4 + tmp_value = exc_info->exc_value; + exc_info->exc_value = local_value; + tmp_type = NULL; + tmp_tb = NULL; + Py_XDECREF(local_type); + Py_XDECREF(local_tb); + #else + tmp_type = exc_info->exc_type; + tmp_value = exc_info->exc_value; + tmp_tb = exc_info->exc_traceback; + exc_info->exc_type = local_type; + exc_info->exc_value = local_value; + exc_info->exc_traceback = local_tb; + #endif + } + #else + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = local_type; + tstate->exc_value = local_value; + tstate->exc_traceback = local_tb; + #endif + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#else + PyErr_SetExcInfo(local_type, local_value, local_tb); +#endif + return 0; +bad: + *type = 0; + *value = 0; + *tb = 0; + Py_XDECREF(local_type); + Py_XDECREF(local_value); + Py_XDECREF(local_tb); + return -1; +} + +/* RaiseUnboundLocalError */ +static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname) { + PyErr_Format(PyExc_UnboundLocalError, "local variable '%s' referenced before assignment", varname); +} + +/* SetItemInt */ +static int __Pyx_SetItemInt_Generic(PyObject *o, PyObject *j, PyObject *v) { + int r; + if (unlikely(!j)) return -1; + r = PyObject_SetItem(o, j, v); + Py_DECREF(j); + return r; +} +static CYTHON_INLINE int __Pyx_SetItemInt_Fast(PyObject *o, Py_ssize_t i, PyObject *v, int is_list, + CYTHON_NCP_UNUSED int wraparound, CYTHON_NCP_UNUSED int boundscheck) { +#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS && CYTHON_USE_TYPE_SLOTS + if (is_list || PyList_CheckExact(o)) { + Py_ssize_t n = (!wraparound) ? i : ((likely(i >= 0)) ? i : i + PyList_GET_SIZE(o)); + if ((!boundscheck) || likely(__Pyx_is_valid_index(n, PyList_GET_SIZE(o)))) { + PyObject* old = PyList_GET_ITEM(o, n); + Py_INCREF(v); + PyList_SET_ITEM(o, n, v); + Py_DECREF(old); + return 1; + } + } else { + PyMappingMethods *mm = Py_TYPE(o)->tp_as_mapping; + PySequenceMethods *sm = Py_TYPE(o)->tp_as_sequence; + if (mm && mm->mp_ass_subscript) { + int r; + PyObject *key = PyInt_FromSsize_t(i); + if (unlikely(!key)) return -1; + r = mm->mp_ass_subscript(o, key, v); + Py_DECREF(key); + return r; + } + if (likely(sm && sm->sq_ass_item)) { + if (wraparound && unlikely(i < 0) && likely(sm->sq_length)) { + Py_ssize_t l = sm->sq_length(o); + if (likely(l >= 0)) { + i += l; + } else { + if (!PyErr_ExceptionMatches(PyExc_OverflowError)) + return -1; + PyErr_Clear(); + } + } + return sm->sq_ass_item(o, i, v); + } + } +#else + if (is_list || !PyMapping_Check(o)) + { + return PySequence_SetItem(o, i, v); + } +#endif + return __Pyx_SetItemInt_Generic(o, PyInt_FromSsize_t(i), v); +} + +/* PyDictVersioning */ +#if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj) { + PyObject *dict = Py_TYPE(obj)->tp_dict; + return likely(dict) ? __PYX_GET_DICT_VERSION(dict) : 0; +} +static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj) { + PyObject **dictptr = NULL; + Py_ssize_t offset = Py_TYPE(obj)->tp_dictoffset; + if (offset) { +#if CYTHON_COMPILING_IN_CPYTHON + dictptr = (likely(offset > 0)) ? (PyObject **) ((char *)obj + offset) : _PyObject_GetDictPtr(obj); +#else + dictptr = _PyObject_GetDictPtr(obj); +#endif + } + return (dictptr && *dictptr) ? __PYX_GET_DICT_VERSION(*dictptr) : 0; +} +static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version) { + PyObject *dict = Py_TYPE(obj)->tp_dict; + if (unlikely(!dict) || unlikely(tp_dict_version != __PYX_GET_DICT_VERSION(dict))) + return 0; + return obj_dict_version == __Pyx_get_object_dict_version(obj); +} +#endif + +/* GetModuleGlobalName */ +#if CYTHON_USE_DICT_VERSIONS +static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value) +#else +static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name) +#endif +{ + PyObject *result; +#if !CYTHON_AVOID_BORROWED_REFS +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030500A1 && PY_VERSION_HEX < 0x030d0000 + result = _PyDict_GetItem_KnownHash(__pyx_d, name, ((PyASCIIObject *) name)->hash); + __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) + if (likely(result)) { + return __Pyx_NewRef(result); + } else if (unlikely(PyErr_Occurred())) { + return NULL; + } +#elif CYTHON_COMPILING_IN_LIMITED_API + if (unlikely(!__pyx_m)) { + return NULL; + } + result = PyObject_GetAttr(__pyx_m, name); + if (likely(result)) { + return result; + } +#else + result = PyDict_GetItem(__pyx_d, name); + __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) + if (likely(result)) { + return __Pyx_NewRef(result); + } +#endif +#else + result = PyObject_GetItem(__pyx_d, name); + __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) + if (likely(result)) { + return __Pyx_NewRef(result); + } + PyErr_Clear(); +#endif + return __Pyx_GetBuiltinName(name); +} + +/* FixUpExtensionType */ +#if CYTHON_USE_TYPE_SPECS +static int __Pyx_fix_up_extension_type_from_spec(PyType_Spec *spec, PyTypeObject *type) { +#if PY_VERSION_HEX > 0x030900B1 || CYTHON_COMPILING_IN_LIMITED_API + CYTHON_UNUSED_VAR(spec); + CYTHON_UNUSED_VAR(type); +#else + const PyType_Slot *slot = spec->slots; + while (slot && slot->slot && slot->slot != Py_tp_members) + slot++; + if (slot && slot->slot == Py_tp_members) { + int changed = 0; +#if !(PY_VERSION_HEX <= 0x030900b1 && CYTHON_COMPILING_IN_CPYTHON) + const +#endif + PyMemberDef *memb = (PyMemberDef*) slot->pfunc; + while (memb && memb->name) { + if (memb->name[0] == '_' && memb->name[1] == '_') { +#if PY_VERSION_HEX < 0x030900b1 + if (strcmp(memb->name, "__weaklistoffset__") == 0) { + assert(memb->type == T_PYSSIZET); + assert(memb->flags == READONLY); + type->tp_weaklistoffset = memb->offset; + changed = 1; + } + else if (strcmp(memb->name, "__dictoffset__") == 0) { + assert(memb->type == T_PYSSIZET); + assert(memb->flags == READONLY); + type->tp_dictoffset = memb->offset; + changed = 1; + } +#if CYTHON_METH_FASTCALL + else if (strcmp(memb->name, "__vectorcalloffset__") == 0) { + assert(memb->type == T_PYSSIZET); + assert(memb->flags == READONLY); +#if PY_VERSION_HEX >= 0x030800b4 + type->tp_vectorcall_offset = memb->offset; +#else + type->tp_print = (printfunc) memb->offset; +#endif + changed = 1; + } +#endif +#else + if ((0)); +#endif +#if PY_VERSION_HEX <= 0x030900b1 && CYTHON_COMPILING_IN_CPYTHON + else if (strcmp(memb->name, "__module__") == 0) { + PyObject *descr; + assert(memb->type == T_OBJECT); + assert(memb->flags == 0 || memb->flags == READONLY); + descr = PyDescr_NewMember(type, memb); + if (unlikely(!descr)) + return -1; + if (unlikely(PyDict_SetItem(type->tp_dict, PyDescr_NAME(descr), descr) < 0)) { + Py_DECREF(descr); + return -1; + } + Py_DECREF(descr); + changed = 1; + } +#endif + } + memb++; + } + if (changed) + PyType_Modified(type); + } +#endif + return 0; +} +#endif + +/* PyObjectCallNoArg */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func) { + PyObject *arg[2] = {NULL, NULL}; + return __Pyx_PyObject_FastCall(func, arg + 1, 0 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET); +} + +/* PyObjectCallMethod0 */ +static PyObject* __Pyx_PyObject_CallMethod0(PyObject* obj, PyObject* method_name) { + PyObject *method = NULL, *result = NULL; + int is_method = __Pyx_PyObject_GetMethod(obj, method_name, &method); + if (likely(is_method)) { + result = __Pyx_PyObject_CallOneArg(method, obj); + Py_DECREF(method); + return result; + } + if (unlikely(!method)) goto bad; + result = __Pyx_PyObject_CallNoArg(method); + Py_DECREF(method); +bad: + return result; +} + +/* ValidateBasesTuple */ +#if CYTHON_COMPILING_IN_CPYTHON || CYTHON_COMPILING_IN_LIMITED_API || CYTHON_USE_TYPE_SPECS +static int __Pyx_validate_bases_tuple(const char *type_name, Py_ssize_t dictoffset, PyObject *bases) { + Py_ssize_t i, n; +#if CYTHON_ASSUME_SAFE_MACROS + n = PyTuple_GET_SIZE(bases); +#else + n = PyTuple_Size(bases); + if (n < 0) return -1; +#endif + for (i = 1; i < n; i++) + { +#if CYTHON_AVOID_BORROWED_REFS + PyObject *b0 = PySequence_GetItem(bases, i); + if (!b0) return -1; +#elif CYTHON_ASSUME_SAFE_MACROS + PyObject *b0 = PyTuple_GET_ITEM(bases, i); +#else + PyObject *b0 = PyTuple_GetItem(bases, i); + if (!b0) return -1; +#endif + PyTypeObject *b; +#if PY_MAJOR_VERSION < 3 + if (PyClass_Check(b0)) + { + PyErr_Format(PyExc_TypeError, "base class '%.200s' is an old-style class", + PyString_AS_STRING(((PyClassObject*)b0)->cl_name)); +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(b0); +#endif + return -1; + } +#endif + b = (PyTypeObject*) b0; + if (!__Pyx_PyType_HasFeature(b, Py_TPFLAGS_HEAPTYPE)) + { + __Pyx_TypeName b_name = __Pyx_PyType_GetName(b); + PyErr_Format(PyExc_TypeError, + "base class '" __Pyx_FMT_TYPENAME "' is not a heap type", b_name); + __Pyx_DECREF_TypeName(b_name); +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(b0); +#endif + return -1; + } + if (dictoffset == 0) + { + Py_ssize_t b_dictoffset = 0; +#if CYTHON_USE_TYPE_SLOTS || CYTHON_COMPILING_IN_PYPY + b_dictoffset = b->tp_dictoffset; +#else + PyObject *py_b_dictoffset = PyObject_GetAttrString((PyObject*)b, "__dictoffset__"); + if (!py_b_dictoffset) goto dictoffset_return; + b_dictoffset = PyLong_AsSsize_t(py_b_dictoffset); + Py_DECREF(py_b_dictoffset); + if (b_dictoffset == -1 && PyErr_Occurred()) goto dictoffset_return; +#endif + if (b_dictoffset) { + { + __Pyx_TypeName b_name = __Pyx_PyType_GetName(b); + PyErr_Format(PyExc_TypeError, + "extension type '%.200s' has no __dict__ slot, " + "but base type '" __Pyx_FMT_TYPENAME "' has: " + "either add 'cdef dict __dict__' to the extension type " + "or add '__slots__ = [...]' to the base type", + type_name, b_name); + __Pyx_DECREF_TypeName(b_name); + } +#if !(CYTHON_USE_TYPE_SLOTS || CYTHON_COMPILING_IN_PYPY) + dictoffset_return: +#endif +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(b0); +#endif + return -1; + } + } +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(b0); +#endif + } + return 0; +} +#endif + +/* PyType_Ready */ +static int __Pyx_PyType_Ready(PyTypeObject *t) { +#if CYTHON_USE_TYPE_SPECS || !(CYTHON_COMPILING_IN_CPYTHON || CYTHON_COMPILING_IN_LIMITED_API) || defined(PYSTON_MAJOR_VERSION) + (void)__Pyx_PyObject_CallMethod0; +#if CYTHON_USE_TYPE_SPECS + (void)__Pyx_validate_bases_tuple; +#endif + return PyType_Ready(t); +#else + int r; + PyObject *bases = __Pyx_PyType_GetSlot(t, tp_bases, PyObject*); + if (bases && unlikely(__Pyx_validate_bases_tuple(t->tp_name, t->tp_dictoffset, bases) == -1)) + return -1; +#if PY_VERSION_HEX >= 0x03050000 && !defined(PYSTON_MAJOR_VERSION) + { + int gc_was_enabled; + #if PY_VERSION_HEX >= 0x030A00b1 + gc_was_enabled = PyGC_Disable(); + (void)__Pyx_PyObject_CallMethod0; + #else + PyObject *ret, *py_status; + PyObject *gc = NULL; + #if PY_VERSION_HEX >= 0x030700a1 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM+0 >= 0x07030400) + gc = PyImport_GetModule(__pyx_kp_u_gc); + #endif + if (unlikely(!gc)) gc = PyImport_Import(__pyx_kp_u_gc); + if (unlikely(!gc)) return -1; + py_status = __Pyx_PyObject_CallMethod0(gc, __pyx_kp_u_isenabled); + if (unlikely(!py_status)) { + Py_DECREF(gc); + return -1; + } + gc_was_enabled = __Pyx_PyObject_IsTrue(py_status); + Py_DECREF(py_status); + if (gc_was_enabled > 0) { + ret = __Pyx_PyObject_CallMethod0(gc, __pyx_kp_u_disable); + if (unlikely(!ret)) { + Py_DECREF(gc); + return -1; + } + Py_DECREF(ret); + } else if (unlikely(gc_was_enabled == -1)) { + Py_DECREF(gc); + return -1; + } + #endif + t->tp_flags |= Py_TPFLAGS_HEAPTYPE; +#if PY_VERSION_HEX >= 0x030A0000 + t->tp_flags |= Py_TPFLAGS_IMMUTABLETYPE; +#endif +#else + (void)__Pyx_PyObject_CallMethod0; +#endif + r = PyType_Ready(t); +#if PY_VERSION_HEX >= 0x03050000 && !defined(PYSTON_MAJOR_VERSION) + t->tp_flags &= ~Py_TPFLAGS_HEAPTYPE; + #if PY_VERSION_HEX >= 0x030A00b1 + if (gc_was_enabled) + PyGC_Enable(); + #else + if (gc_was_enabled) { + PyObject *tp, *v, *tb; + PyErr_Fetch(&tp, &v, &tb); + ret = __Pyx_PyObject_CallMethod0(gc, __pyx_kp_u_enable); + if (likely(ret || r == -1)) { + Py_XDECREF(ret); + PyErr_Restore(tp, v, tb); + } else { + Py_XDECREF(tp); + Py_XDECREF(v); + Py_XDECREF(tb); + r = -1; + } + } + Py_DECREF(gc); + #endif + } +#endif + return r; +#endif +} + +/* PyObject_GenericGetAttrNoDict */ +#if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 +static PyObject *__Pyx_RaiseGenericGetAttributeError(PyTypeObject *tp, PyObject *attr_name) { + __Pyx_TypeName type_name = __Pyx_PyType_GetName(tp); + PyErr_Format(PyExc_AttributeError, +#if PY_MAJOR_VERSION >= 3 + "'" __Pyx_FMT_TYPENAME "' object has no attribute '%U'", + type_name, attr_name); +#else + "'" __Pyx_FMT_TYPENAME "' object has no attribute '%.400s'", + type_name, PyString_AS_STRING(attr_name)); +#endif + __Pyx_DECREF_TypeName(type_name); + return NULL; +} +static CYTHON_INLINE PyObject* __Pyx_PyObject_GenericGetAttrNoDict(PyObject* obj, PyObject* attr_name) { + PyObject *descr; + PyTypeObject *tp = Py_TYPE(obj); + if (unlikely(!PyString_Check(attr_name))) { + return PyObject_GenericGetAttr(obj, attr_name); + } + assert(!tp->tp_dictoffset); + descr = _PyType_Lookup(tp, attr_name); + if (unlikely(!descr)) { + return __Pyx_RaiseGenericGetAttributeError(tp, attr_name); + } + Py_INCREF(descr); + #if PY_MAJOR_VERSION < 3 + if (likely(PyType_HasFeature(Py_TYPE(descr), Py_TPFLAGS_HAVE_CLASS))) + #endif + { + descrgetfunc f = Py_TYPE(descr)->tp_descr_get; + if (unlikely(f)) { + PyObject *res = f(descr, obj, (PyObject *)tp); + Py_DECREF(descr); + return res; + } + } + return descr; +} +#endif + +/* PyObject_GenericGetAttr */ +#if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 +static PyObject* __Pyx_PyObject_GenericGetAttr(PyObject* obj, PyObject* attr_name) { + if (unlikely(Py_TYPE(obj)->tp_dictoffset)) { + return PyObject_GenericGetAttr(obj, attr_name); + } + return __Pyx_PyObject_GenericGetAttrNoDict(obj, attr_name); +} +#endif + +/* SetVTable */ +static int __Pyx_SetVtable(PyTypeObject *type, void *vtable) { + PyObject *ob = PyCapsule_New(vtable, 0, 0); + if (unlikely(!ob)) + goto bad; +#if CYTHON_COMPILING_IN_LIMITED_API + if (unlikely(PyObject_SetAttr((PyObject *) type, __pyx_n_s_pyx_vtable, ob) < 0)) +#else + if (unlikely(PyDict_SetItem(type->tp_dict, __pyx_n_s_pyx_vtable, ob) < 0)) +#endif + goto bad; + Py_DECREF(ob); + return 0; +bad: + Py_XDECREF(ob); + return -1; +} + +/* GetVTable */ +static void* __Pyx_GetVtable(PyTypeObject *type) { + void* ptr; +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *ob = PyObject_GetAttr((PyObject *)type, __pyx_n_s_pyx_vtable); +#else + PyObject *ob = PyObject_GetItem(type->tp_dict, __pyx_n_s_pyx_vtable); +#endif + if (!ob) + goto bad; + ptr = PyCapsule_GetPointer(ob, 0); + if (!ptr && !PyErr_Occurred()) + PyErr_SetString(PyExc_RuntimeError, "invalid vtable found for imported type"); + Py_DECREF(ob); + return ptr; +bad: + Py_XDECREF(ob); + return NULL; +} + +/* MergeVTables */ +#if !CYTHON_COMPILING_IN_LIMITED_API +static int __Pyx_MergeVtables(PyTypeObject *type) { + int i; + void** base_vtables; + __Pyx_TypeName tp_base_name; + __Pyx_TypeName base_name; + void* unknown = (void*)-1; + PyObject* bases = type->tp_bases; + int base_depth = 0; + { + PyTypeObject* base = type->tp_base; + while (base) { + base_depth += 1; + base = base->tp_base; + } + } + base_vtables = (void**) malloc(sizeof(void*) * (size_t)(base_depth + 1)); + base_vtables[0] = unknown; + for (i = 1; i < PyTuple_GET_SIZE(bases); i++) { + void* base_vtable = __Pyx_GetVtable(((PyTypeObject*)PyTuple_GET_ITEM(bases, i))); + if (base_vtable != NULL) { + int j; + PyTypeObject* base = type->tp_base; + for (j = 0; j < base_depth; j++) { + if (base_vtables[j] == unknown) { + base_vtables[j] = __Pyx_GetVtable(base); + base_vtables[j + 1] = unknown; + } + if (base_vtables[j] == base_vtable) { + break; + } else if (base_vtables[j] == NULL) { + goto bad; + } + base = base->tp_base; + } + } + } + PyErr_Clear(); + free(base_vtables); + return 0; +bad: + tp_base_name = __Pyx_PyType_GetName(type->tp_base); + base_name = __Pyx_PyType_GetName((PyTypeObject*)PyTuple_GET_ITEM(bases, i)); + PyErr_Format(PyExc_TypeError, + "multiple bases have vtable conflict: '" __Pyx_FMT_TYPENAME "' and '" __Pyx_FMT_TYPENAME "'", tp_base_name, base_name); + __Pyx_DECREF_TypeName(tp_base_name); + __Pyx_DECREF_TypeName(base_name); + free(base_vtables); + return -1; +} +#endif + +/* Import */ +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { + PyObject *module = 0; + PyObject *empty_dict = 0; + PyObject *empty_list = 0; + #if PY_MAJOR_VERSION < 3 + PyObject *py_import; + py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s_import); + if (unlikely(!py_import)) + goto bad; + if (!from_list) { + empty_list = PyList_New(0); + if (unlikely(!empty_list)) + goto bad; + from_list = empty_list; + } + #endif + empty_dict = PyDict_New(); + if (unlikely(!empty_dict)) + goto bad; + { + #if PY_MAJOR_VERSION >= 3 + if (level == -1) { + if (strchr(__Pyx_MODULE_NAME, '.') != NULL) { + module = PyImport_ImportModuleLevelObject( + name, __pyx_d, empty_dict, from_list, 1); + if (unlikely(!module)) { + if (unlikely(!PyErr_ExceptionMatches(PyExc_ImportError))) + goto bad; + PyErr_Clear(); + } + } + level = 0; + } + #endif + if (!module) { + #if PY_MAJOR_VERSION < 3 + PyObject *py_level = PyInt_FromLong(level); + if (unlikely(!py_level)) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, __pyx_d, empty_dict, from_list, py_level, (PyObject *)NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, __pyx_d, empty_dict, from_list, level); + #endif + } + } +bad: + Py_XDECREF(empty_dict); + Py_XDECREF(empty_list); + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(py_import); + #endif + return module; +} + +/* ImportFrom */ +static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name) { + PyObject* value = __Pyx_PyObject_GetAttrStr(module, name); + if (unlikely(!value) && PyErr_ExceptionMatches(PyExc_AttributeError)) { + const char* module_name_str = 0; + PyObject* module_name = 0; + PyObject* module_dot = 0; + PyObject* full_name = 0; + PyErr_Clear(); + module_name_str = PyModule_GetName(module); + if (unlikely(!module_name_str)) { goto modbad; } + module_name = PyUnicode_FromString(module_name_str); + if (unlikely(!module_name)) { goto modbad; } + module_dot = PyUnicode_Concat(module_name, __pyx_kp_u__5); + if (unlikely(!module_dot)) { goto modbad; } + full_name = PyUnicode_Concat(module_dot, name); + if (unlikely(!full_name)) { goto modbad; } + #if PY_VERSION_HEX < 0x030700A1 || (CYTHON_COMPILING_IN_PYPY && PYPY_VERSION_NUM < 0x07030400) + { + PyObject *modules = PyImport_GetModuleDict(); + if (unlikely(!modules)) + goto modbad; + value = PyObject_GetItem(modules, full_name); + } + #else + value = PyImport_GetModule(full_name); + #endif + modbad: + Py_XDECREF(full_name); + Py_XDECREF(module_dot); + Py_XDECREF(module_name); + } + if (unlikely(!value)) { + PyErr_Format(PyExc_ImportError, + #if PY_MAJOR_VERSION < 3 + "cannot import name %.230s", PyString_AS_STRING(name)); + #else + "cannot import name %S", name); + #endif + } + return value; +} + +/* FetchSharedCythonModule */ +static PyObject *__Pyx_FetchSharedCythonABIModule(void) { + return __Pyx_PyImport_AddModuleRef((char*) __PYX_ABI_MODULE_NAME); +} + +/* FetchCommonType */ +static int __Pyx_VerifyCachedType(PyObject *cached_type, + const char *name, + Py_ssize_t basicsize, + Py_ssize_t expected_basicsize) { + if (!PyType_Check(cached_type)) { + PyErr_Format(PyExc_TypeError, + "Shared Cython type %.200s is not a type object", name); + return -1; + } + if (basicsize != expected_basicsize) { + PyErr_Format(PyExc_TypeError, + "Shared Cython type %.200s has the wrong size, try recompiling", + name); + return -1; + } + return 0; +} +#if !CYTHON_USE_TYPE_SPECS +static PyTypeObject* __Pyx_FetchCommonType(PyTypeObject* type) { + PyObject* abi_module; + const char* object_name; + PyTypeObject *cached_type = NULL; + abi_module = __Pyx_FetchSharedCythonABIModule(); + if (!abi_module) return NULL; + object_name = strrchr(type->tp_name, '.'); + object_name = object_name ? object_name+1 : type->tp_name; + cached_type = (PyTypeObject*) PyObject_GetAttrString(abi_module, object_name); + if (cached_type) { + if (__Pyx_VerifyCachedType( + (PyObject *)cached_type, + object_name, + cached_type->tp_basicsize, + type->tp_basicsize) < 0) { + goto bad; + } + goto done; + } + if (!PyErr_ExceptionMatches(PyExc_AttributeError)) goto bad; + PyErr_Clear(); + if (PyType_Ready(type) < 0) goto bad; + if (PyObject_SetAttrString(abi_module, object_name, (PyObject *)type) < 0) + goto bad; + Py_INCREF(type); + cached_type = type; +done: + Py_DECREF(abi_module); + return cached_type; +bad: + Py_XDECREF(cached_type); + cached_type = NULL; + goto done; +} +#else +static PyTypeObject *__Pyx_FetchCommonTypeFromSpec(PyObject *module, PyType_Spec *spec, PyObject *bases) { + PyObject *abi_module, *cached_type = NULL; + const char* object_name = strrchr(spec->name, '.'); + object_name = object_name ? object_name+1 : spec->name; + abi_module = __Pyx_FetchSharedCythonABIModule(); + if (!abi_module) return NULL; + cached_type = PyObject_GetAttrString(abi_module, object_name); + if (cached_type) { + Py_ssize_t basicsize; +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *py_basicsize; + py_basicsize = PyObject_GetAttrString(cached_type, "__basicsize__"); + if (unlikely(!py_basicsize)) goto bad; + basicsize = PyLong_AsSsize_t(py_basicsize); + Py_DECREF(py_basicsize); + py_basicsize = 0; + if (unlikely(basicsize == (Py_ssize_t)-1) && PyErr_Occurred()) goto bad; +#else + basicsize = likely(PyType_Check(cached_type)) ? ((PyTypeObject*) cached_type)->tp_basicsize : -1; +#endif + if (__Pyx_VerifyCachedType( + cached_type, + object_name, + basicsize, + spec->basicsize) < 0) { + goto bad; + } + goto done; + } + if (!PyErr_ExceptionMatches(PyExc_AttributeError)) goto bad; + PyErr_Clear(); + CYTHON_UNUSED_VAR(module); + cached_type = __Pyx_PyType_FromModuleAndSpec(abi_module, spec, bases); + if (unlikely(!cached_type)) goto bad; + if (unlikely(__Pyx_fix_up_extension_type_from_spec(spec, (PyTypeObject *) cached_type) < 0)) goto bad; + if (PyObject_SetAttrString(abi_module, object_name, cached_type) < 0) goto bad; +done: + Py_DECREF(abi_module); + assert(cached_type == NULL || PyType_Check(cached_type)); + return (PyTypeObject *) cached_type; +bad: + Py_XDECREF(cached_type); + cached_type = NULL; + goto done; +} +#endif + +/* PyVectorcallFastCallDict */ +#if CYTHON_METH_FASTCALL +static PyObject *__Pyx_PyVectorcall_FastCallDict_kw(PyObject *func, __pyx_vectorcallfunc vc, PyObject *const *args, size_t nargs, PyObject *kw) +{ + PyObject *res = NULL; + PyObject *kwnames; + PyObject **newargs; + PyObject **kwvalues; + Py_ssize_t i, pos; + size_t j; + PyObject *key, *value; + unsigned long keys_are_strings; + Py_ssize_t nkw = PyDict_GET_SIZE(kw); + newargs = (PyObject **)PyMem_Malloc((nargs + (size_t)nkw) * sizeof(args[0])); + if (unlikely(newargs == NULL)) { + PyErr_NoMemory(); + return NULL; + } + for (j = 0; j < nargs; j++) newargs[j] = args[j]; + kwnames = PyTuple_New(nkw); + if (unlikely(kwnames == NULL)) { + PyMem_Free(newargs); + return NULL; + } + kwvalues = newargs + nargs; + pos = i = 0; + keys_are_strings = Py_TPFLAGS_UNICODE_SUBCLASS; + while (PyDict_Next(kw, &pos, &key, &value)) { + keys_are_strings &= Py_TYPE(key)->tp_flags; + Py_INCREF(key); + Py_INCREF(value); + PyTuple_SET_ITEM(kwnames, i, key); + kwvalues[i] = value; + i++; + } + if (unlikely(!keys_are_strings)) { + PyErr_SetString(PyExc_TypeError, "keywords must be strings"); + goto cleanup; + } + res = vc(func, newargs, nargs, kwnames); +cleanup: + Py_DECREF(kwnames); + for (i = 0; i < nkw; i++) + Py_DECREF(kwvalues[i]); + PyMem_Free(newargs); + return res; +} +static CYTHON_INLINE PyObject *__Pyx_PyVectorcall_FastCallDict(PyObject *func, __pyx_vectorcallfunc vc, PyObject *const *args, size_t nargs, PyObject *kw) +{ + if (likely(kw == NULL) || PyDict_GET_SIZE(kw) == 0) { + return vc(func, args, nargs, NULL); + } + return __Pyx_PyVectorcall_FastCallDict_kw(func, vc, args, nargs, kw); +} +#endif + +/* CythonFunctionShared */ +#if CYTHON_COMPILING_IN_LIMITED_API +static CYTHON_INLINE int __Pyx__IsSameCyOrCFunction(PyObject *func, void *cfunc) { + if (__Pyx_CyFunction_Check(func)) { + return PyCFunction_GetFunction(((__pyx_CyFunctionObject*)func)->func) == (PyCFunction) cfunc; + } else if (PyCFunction_Check(func)) { + return PyCFunction_GetFunction(func) == (PyCFunction) cfunc; + } + return 0; +} +#else +static CYTHON_INLINE int __Pyx__IsSameCyOrCFunction(PyObject *func, void *cfunc) { + return __Pyx_CyOrPyCFunction_Check(func) && __Pyx_CyOrPyCFunction_GET_FUNCTION(func) == (PyCFunction) cfunc; +} +#endif +static CYTHON_INLINE void __Pyx__CyFunction_SetClassObj(__pyx_CyFunctionObject* f, PyObject* classobj) { +#if PY_VERSION_HEX < 0x030900B1 || CYTHON_COMPILING_IN_LIMITED_API + __Pyx_Py_XDECREF_SET( + __Pyx_CyFunction_GetClassObj(f), + ((classobj) ? __Pyx_NewRef(classobj) : NULL)); +#else + __Pyx_Py_XDECREF_SET( + ((PyCMethodObject *) (f))->mm_class, + (PyTypeObject*)((classobj) ? __Pyx_NewRef(classobj) : NULL)); +#endif +} +static PyObject * +__Pyx_CyFunction_get_doc(__pyx_CyFunctionObject *op, void *closure) +{ + CYTHON_UNUSED_VAR(closure); + if (unlikely(op->func_doc == NULL)) { +#if CYTHON_COMPILING_IN_LIMITED_API + op->func_doc = PyObject_GetAttrString(op->func, "__doc__"); + if (unlikely(!op->func_doc)) return NULL; +#else + if (((PyCFunctionObject*)op)->m_ml->ml_doc) { +#if PY_MAJOR_VERSION >= 3 + op->func_doc = PyUnicode_FromString(((PyCFunctionObject*)op)->m_ml->ml_doc); +#else + op->func_doc = PyString_FromString(((PyCFunctionObject*)op)->m_ml->ml_doc); +#endif + if (unlikely(op->func_doc == NULL)) + return NULL; + } else { + Py_INCREF(Py_None); + return Py_None; + } +#endif + } + Py_INCREF(op->func_doc); + return op->func_doc; +} +static int +__Pyx_CyFunction_set_doc(__pyx_CyFunctionObject *op, PyObject *value, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (value == NULL) { + value = Py_None; + } + Py_INCREF(value); + __Pyx_Py_XDECREF_SET(op->func_doc, value); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_name(__pyx_CyFunctionObject *op, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (unlikely(op->func_name == NULL)) { +#if CYTHON_COMPILING_IN_LIMITED_API + op->func_name = PyObject_GetAttrString(op->func, "__name__"); +#elif PY_MAJOR_VERSION >= 3 + op->func_name = PyUnicode_InternFromString(((PyCFunctionObject*)op)->m_ml->ml_name); +#else + op->func_name = PyString_InternFromString(((PyCFunctionObject*)op)->m_ml->ml_name); +#endif + if (unlikely(op->func_name == NULL)) + return NULL; + } + Py_INCREF(op->func_name); + return op->func_name; +} +static int +__Pyx_CyFunction_set_name(__pyx_CyFunctionObject *op, PyObject *value, void *context) +{ + CYTHON_UNUSED_VAR(context); +#if PY_MAJOR_VERSION >= 3 + if (unlikely(value == NULL || !PyUnicode_Check(value))) +#else + if (unlikely(value == NULL || !PyString_Check(value))) +#endif + { + PyErr_SetString(PyExc_TypeError, + "__name__ must be set to a string object"); + return -1; + } + Py_INCREF(value); + __Pyx_Py_XDECREF_SET(op->func_name, value); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_qualname(__pyx_CyFunctionObject *op, void *context) +{ + CYTHON_UNUSED_VAR(context); + Py_INCREF(op->func_qualname); + return op->func_qualname; +} +static int +__Pyx_CyFunction_set_qualname(__pyx_CyFunctionObject *op, PyObject *value, void *context) +{ + CYTHON_UNUSED_VAR(context); +#if PY_MAJOR_VERSION >= 3 + if (unlikely(value == NULL || !PyUnicode_Check(value))) +#else + if (unlikely(value == NULL || !PyString_Check(value))) +#endif + { + PyErr_SetString(PyExc_TypeError, + "__qualname__ must be set to a string object"); + return -1; + } + Py_INCREF(value); + __Pyx_Py_XDECREF_SET(op->func_qualname, value); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_dict(__pyx_CyFunctionObject *op, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (unlikely(op->func_dict == NULL)) { + op->func_dict = PyDict_New(); + if (unlikely(op->func_dict == NULL)) + return NULL; + } + Py_INCREF(op->func_dict); + return op->func_dict; +} +static int +__Pyx_CyFunction_set_dict(__pyx_CyFunctionObject *op, PyObject *value, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (unlikely(value == NULL)) { + PyErr_SetString(PyExc_TypeError, + "function's dictionary may not be deleted"); + return -1; + } + if (unlikely(!PyDict_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "setting function's dictionary to a non-dict"); + return -1; + } + Py_INCREF(value); + __Pyx_Py_XDECREF_SET(op->func_dict, value); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_globals(__pyx_CyFunctionObject *op, void *context) +{ + CYTHON_UNUSED_VAR(context); + Py_INCREF(op->func_globals); + return op->func_globals; +} +static PyObject * +__Pyx_CyFunction_get_closure(__pyx_CyFunctionObject *op, void *context) +{ + CYTHON_UNUSED_VAR(op); + CYTHON_UNUSED_VAR(context); + Py_INCREF(Py_None); + return Py_None; +} +static PyObject * +__Pyx_CyFunction_get_code(__pyx_CyFunctionObject *op, void *context) +{ + PyObject* result = (op->func_code) ? op->func_code : Py_None; + CYTHON_UNUSED_VAR(context); + Py_INCREF(result); + return result; +} +static int +__Pyx_CyFunction_init_defaults(__pyx_CyFunctionObject *op) { + int result = 0; + PyObject *res = op->defaults_getter((PyObject *) op); + if (unlikely(!res)) + return -1; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + op->defaults_tuple = PyTuple_GET_ITEM(res, 0); + Py_INCREF(op->defaults_tuple); + op->defaults_kwdict = PyTuple_GET_ITEM(res, 1); + Py_INCREF(op->defaults_kwdict); + #else + op->defaults_tuple = __Pyx_PySequence_ITEM(res, 0); + if (unlikely(!op->defaults_tuple)) result = -1; + else { + op->defaults_kwdict = __Pyx_PySequence_ITEM(res, 1); + if (unlikely(!op->defaults_kwdict)) result = -1; + } + #endif + Py_DECREF(res); + return result; +} +static int +__Pyx_CyFunction_set_defaults(__pyx_CyFunctionObject *op, PyObject* value, void *context) { + CYTHON_UNUSED_VAR(context); + if (!value) { + value = Py_None; + } else if (unlikely(value != Py_None && !PyTuple_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__defaults__ must be set to a tuple object"); + return -1; + } + PyErr_WarnEx(PyExc_RuntimeWarning, "changes to cyfunction.__defaults__ will not " + "currently affect the values used in function calls", 1); + Py_INCREF(value); + __Pyx_Py_XDECREF_SET(op->defaults_tuple, value); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_defaults(__pyx_CyFunctionObject *op, void *context) { + PyObject* result = op->defaults_tuple; + CYTHON_UNUSED_VAR(context); + if (unlikely(!result)) { + if (op->defaults_getter) { + if (unlikely(__Pyx_CyFunction_init_defaults(op) < 0)) return NULL; + result = op->defaults_tuple; + } else { + result = Py_None; + } + } + Py_INCREF(result); + return result; +} +static int +__Pyx_CyFunction_set_kwdefaults(__pyx_CyFunctionObject *op, PyObject* value, void *context) { + CYTHON_UNUSED_VAR(context); + if (!value) { + value = Py_None; + } else if (unlikely(value != Py_None && !PyDict_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__kwdefaults__ must be set to a dict object"); + return -1; + } + PyErr_WarnEx(PyExc_RuntimeWarning, "changes to cyfunction.__kwdefaults__ will not " + "currently affect the values used in function calls", 1); + Py_INCREF(value); + __Pyx_Py_XDECREF_SET(op->defaults_kwdict, value); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_kwdefaults(__pyx_CyFunctionObject *op, void *context) { + PyObject* result = op->defaults_kwdict; + CYTHON_UNUSED_VAR(context); + if (unlikely(!result)) { + if (op->defaults_getter) { + if (unlikely(__Pyx_CyFunction_init_defaults(op) < 0)) return NULL; + result = op->defaults_kwdict; + } else { + result = Py_None; + } + } + Py_INCREF(result); + return result; +} +static int +__Pyx_CyFunction_set_annotations(__pyx_CyFunctionObject *op, PyObject* value, void *context) { + CYTHON_UNUSED_VAR(context); + if (!value || value == Py_None) { + value = NULL; + } else if (unlikely(!PyDict_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__annotations__ must be set to a dict object"); + return -1; + } + Py_XINCREF(value); + __Pyx_Py_XDECREF_SET(op->func_annotations, value); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_annotations(__pyx_CyFunctionObject *op, void *context) { + PyObject* result = op->func_annotations; + CYTHON_UNUSED_VAR(context); + if (unlikely(!result)) { + result = PyDict_New(); + if (unlikely(!result)) return NULL; + op->func_annotations = result; + } + Py_INCREF(result); + return result; +} +static PyObject * +__Pyx_CyFunction_get_is_coroutine(__pyx_CyFunctionObject *op, void *context) { + int is_coroutine; + CYTHON_UNUSED_VAR(context); + if (op->func_is_coroutine) { + return __Pyx_NewRef(op->func_is_coroutine); + } + is_coroutine = op->flags & __Pyx_CYFUNCTION_COROUTINE; +#if PY_VERSION_HEX >= 0x03050000 + if (is_coroutine) { + PyObject *module, *fromlist, *marker = __pyx_n_s_is_coroutine; + fromlist = PyList_New(1); + if (unlikely(!fromlist)) return NULL; + Py_INCREF(marker); +#if CYTHON_ASSUME_SAFE_MACROS + PyList_SET_ITEM(fromlist, 0, marker); +#else + if (unlikely(PyList_SetItem(fromlist, 0, marker) < 0)) { + Py_DECREF(marker); + Py_DECREF(fromlist); + return NULL; + } +#endif + module = PyImport_ImportModuleLevelObject(__pyx_n_s_asyncio_coroutines, NULL, NULL, fromlist, 0); + Py_DECREF(fromlist); + if (unlikely(!module)) goto ignore; + op->func_is_coroutine = __Pyx_PyObject_GetAttrStr(module, marker); + Py_DECREF(module); + if (likely(op->func_is_coroutine)) { + return __Pyx_NewRef(op->func_is_coroutine); + } +ignore: + PyErr_Clear(); + } +#endif + op->func_is_coroutine = __Pyx_PyBool_FromLong(is_coroutine); + return __Pyx_NewRef(op->func_is_coroutine); +} +#if CYTHON_COMPILING_IN_LIMITED_API +static PyObject * +__Pyx_CyFunction_get_module(__pyx_CyFunctionObject *op, void *context) { + CYTHON_UNUSED_VAR(context); + return PyObject_GetAttrString(op->func, "__module__"); +} +static int +__Pyx_CyFunction_set_module(__pyx_CyFunctionObject *op, PyObject* value, void *context) { + CYTHON_UNUSED_VAR(context); + return PyObject_SetAttrString(op->func, "__module__", value); +} +#endif +static PyGetSetDef __pyx_CyFunction_getsets[] = { + {(char *) "func_doc", (getter)__Pyx_CyFunction_get_doc, (setter)__Pyx_CyFunction_set_doc, 0, 0}, + {(char *) "__doc__", (getter)__Pyx_CyFunction_get_doc, (setter)__Pyx_CyFunction_set_doc, 0, 0}, + {(char *) "func_name", (getter)__Pyx_CyFunction_get_name, (setter)__Pyx_CyFunction_set_name, 0, 0}, + {(char *) "__name__", (getter)__Pyx_CyFunction_get_name, (setter)__Pyx_CyFunction_set_name, 0, 0}, + {(char *) "__qualname__", (getter)__Pyx_CyFunction_get_qualname, (setter)__Pyx_CyFunction_set_qualname, 0, 0}, + {(char *) "func_dict", (getter)__Pyx_CyFunction_get_dict, (setter)__Pyx_CyFunction_set_dict, 0, 0}, + {(char *) "__dict__", (getter)__Pyx_CyFunction_get_dict, (setter)__Pyx_CyFunction_set_dict, 0, 0}, + {(char *) "func_globals", (getter)__Pyx_CyFunction_get_globals, 0, 0, 0}, + {(char *) "__globals__", (getter)__Pyx_CyFunction_get_globals, 0, 0, 0}, + {(char *) "func_closure", (getter)__Pyx_CyFunction_get_closure, 0, 0, 0}, + {(char *) "__closure__", (getter)__Pyx_CyFunction_get_closure, 0, 0, 0}, + {(char *) "func_code", (getter)__Pyx_CyFunction_get_code, 0, 0, 0}, + {(char *) "__code__", (getter)__Pyx_CyFunction_get_code, 0, 0, 0}, + {(char *) "func_defaults", (getter)__Pyx_CyFunction_get_defaults, (setter)__Pyx_CyFunction_set_defaults, 0, 0}, + {(char *) "__defaults__", (getter)__Pyx_CyFunction_get_defaults, (setter)__Pyx_CyFunction_set_defaults, 0, 0}, + {(char *) "__kwdefaults__", (getter)__Pyx_CyFunction_get_kwdefaults, (setter)__Pyx_CyFunction_set_kwdefaults, 0, 0}, + {(char *) "__annotations__", (getter)__Pyx_CyFunction_get_annotations, (setter)__Pyx_CyFunction_set_annotations, 0, 0}, + {(char *) "_is_coroutine", (getter)__Pyx_CyFunction_get_is_coroutine, 0, 0, 0}, +#if CYTHON_COMPILING_IN_LIMITED_API + {"__module__", (getter)__Pyx_CyFunction_get_module, (setter)__Pyx_CyFunction_set_module, 0, 0}, +#endif + {0, 0, 0, 0, 0} +}; +static PyMemberDef __pyx_CyFunction_members[] = { +#if !CYTHON_COMPILING_IN_LIMITED_API + {(char *) "__module__", T_OBJECT, offsetof(PyCFunctionObject, m_module), 0, 0}, +#endif +#if CYTHON_USE_TYPE_SPECS + {(char *) "__dictoffset__", T_PYSSIZET, offsetof(__pyx_CyFunctionObject, func_dict), READONLY, 0}, +#if CYTHON_METH_FASTCALL +#if CYTHON_BACKPORT_VECTORCALL + {(char *) "__vectorcalloffset__", T_PYSSIZET, offsetof(__pyx_CyFunctionObject, func_vectorcall), READONLY, 0}, +#else +#if !CYTHON_COMPILING_IN_LIMITED_API + {(char *) "__vectorcalloffset__", T_PYSSIZET, offsetof(PyCFunctionObject, vectorcall), READONLY, 0}, +#endif +#endif +#endif +#if PY_VERSION_HEX < 0x030500A0 || CYTHON_COMPILING_IN_LIMITED_API + {(char *) "__weaklistoffset__", T_PYSSIZET, offsetof(__pyx_CyFunctionObject, func_weakreflist), READONLY, 0}, +#else + {(char *) "__weaklistoffset__", T_PYSSIZET, offsetof(PyCFunctionObject, m_weakreflist), READONLY, 0}, +#endif +#endif + {0, 0, 0, 0, 0} +}; +static PyObject * +__Pyx_CyFunction_reduce(__pyx_CyFunctionObject *m, PyObject *args) +{ + CYTHON_UNUSED_VAR(args); +#if PY_MAJOR_VERSION >= 3 + Py_INCREF(m->func_qualname); + return m->func_qualname; +#else + return PyString_FromString(((PyCFunctionObject*)m)->m_ml->ml_name); +#endif +} +static PyMethodDef __pyx_CyFunction_methods[] = { + {"__reduce__", (PyCFunction)__Pyx_CyFunction_reduce, METH_VARARGS, 0}, + {0, 0, 0, 0} +}; +#if PY_VERSION_HEX < 0x030500A0 || CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_CyFunction_weakreflist(cyfunc) ((cyfunc)->func_weakreflist) +#else +#define __Pyx_CyFunction_weakreflist(cyfunc) (((PyCFunctionObject*)cyfunc)->m_weakreflist) +#endif +static PyObject *__Pyx_CyFunction_Init(__pyx_CyFunctionObject *op, PyMethodDef *ml, int flags, PyObject* qualname, + PyObject *closure, PyObject *module, PyObject* globals, PyObject* code) { +#if !CYTHON_COMPILING_IN_LIMITED_API + PyCFunctionObject *cf = (PyCFunctionObject*) op; +#endif + if (unlikely(op == NULL)) + return NULL; +#if CYTHON_COMPILING_IN_LIMITED_API + op->func = PyCFunction_NewEx(ml, (PyObject*)op, module); + if (unlikely(!op->func)) return NULL; +#endif + op->flags = flags; + __Pyx_CyFunction_weakreflist(op) = NULL; +#if !CYTHON_COMPILING_IN_LIMITED_API + cf->m_ml = ml; + cf->m_self = (PyObject *) op; +#endif + Py_XINCREF(closure); + op->func_closure = closure; +#if !CYTHON_COMPILING_IN_LIMITED_API + Py_XINCREF(module); + cf->m_module = module; +#endif + op->func_dict = NULL; + op->func_name = NULL; + Py_INCREF(qualname); + op->func_qualname = qualname; + op->func_doc = NULL; +#if PY_VERSION_HEX < 0x030900B1 || CYTHON_COMPILING_IN_LIMITED_API + op->func_classobj = NULL; +#else + ((PyCMethodObject*)op)->mm_class = NULL; +#endif + op->func_globals = globals; + Py_INCREF(op->func_globals); + Py_XINCREF(code); + op->func_code = code; + op->defaults_pyobjects = 0; + op->defaults_size = 0; + op->defaults = NULL; + op->defaults_tuple = NULL; + op->defaults_kwdict = NULL; + op->defaults_getter = NULL; + op->func_annotations = NULL; + op->func_is_coroutine = NULL; +#if CYTHON_METH_FASTCALL + switch (ml->ml_flags & (METH_VARARGS | METH_FASTCALL | METH_NOARGS | METH_O | METH_KEYWORDS | METH_METHOD)) { + case METH_NOARGS: + __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_NOARGS; + break; + case METH_O: + __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_O; + break; + case METH_METHOD | METH_FASTCALL | METH_KEYWORDS: + __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS_METHOD; + break; + case METH_FASTCALL | METH_KEYWORDS: + __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS; + break; + case METH_VARARGS | METH_KEYWORDS: + __Pyx_CyFunction_func_vectorcall(op) = NULL; + break; + default: + PyErr_SetString(PyExc_SystemError, "Bad call flags for CyFunction"); + Py_DECREF(op); + return NULL; + } +#endif + return (PyObject *) op; +} +static int +__Pyx_CyFunction_clear(__pyx_CyFunctionObject *m) +{ + Py_CLEAR(m->func_closure); +#if CYTHON_COMPILING_IN_LIMITED_API + Py_CLEAR(m->func); +#else + Py_CLEAR(((PyCFunctionObject*)m)->m_module); +#endif + Py_CLEAR(m->func_dict); + Py_CLEAR(m->func_name); + Py_CLEAR(m->func_qualname); + Py_CLEAR(m->func_doc); + Py_CLEAR(m->func_globals); + Py_CLEAR(m->func_code); +#if !CYTHON_COMPILING_IN_LIMITED_API +#if PY_VERSION_HEX < 0x030900B1 + Py_CLEAR(__Pyx_CyFunction_GetClassObj(m)); +#else + { + PyObject *cls = (PyObject*) ((PyCMethodObject *) (m))->mm_class; + ((PyCMethodObject *) (m))->mm_class = NULL; + Py_XDECREF(cls); + } +#endif +#endif + Py_CLEAR(m->defaults_tuple); + Py_CLEAR(m->defaults_kwdict); + Py_CLEAR(m->func_annotations); + Py_CLEAR(m->func_is_coroutine); + if (m->defaults) { + PyObject **pydefaults = __Pyx_CyFunction_Defaults(PyObject *, m); + int i; + for (i = 0; i < m->defaults_pyobjects; i++) + Py_XDECREF(pydefaults[i]); + PyObject_Free(m->defaults); + m->defaults = NULL; + } + return 0; +} +static void __Pyx__CyFunction_dealloc(__pyx_CyFunctionObject *m) +{ + if (__Pyx_CyFunction_weakreflist(m) != NULL) + PyObject_ClearWeakRefs((PyObject *) m); + __Pyx_CyFunction_clear(m); + __Pyx_PyHeapTypeObject_GC_Del(m); +} +static void __Pyx_CyFunction_dealloc(__pyx_CyFunctionObject *m) +{ + PyObject_GC_UnTrack(m); + __Pyx__CyFunction_dealloc(m); +} +static int __Pyx_CyFunction_traverse(__pyx_CyFunctionObject *m, visitproc visit, void *arg) +{ + Py_VISIT(m->func_closure); +#if CYTHON_COMPILING_IN_LIMITED_API + Py_VISIT(m->func); +#else + Py_VISIT(((PyCFunctionObject*)m)->m_module); +#endif + Py_VISIT(m->func_dict); + Py_VISIT(m->func_name); + Py_VISIT(m->func_qualname); + Py_VISIT(m->func_doc); + Py_VISIT(m->func_globals); + Py_VISIT(m->func_code); +#if !CYTHON_COMPILING_IN_LIMITED_API + Py_VISIT(__Pyx_CyFunction_GetClassObj(m)); +#endif + Py_VISIT(m->defaults_tuple); + Py_VISIT(m->defaults_kwdict); + Py_VISIT(m->func_is_coroutine); + if (m->defaults) { + PyObject **pydefaults = __Pyx_CyFunction_Defaults(PyObject *, m); + int i; + for (i = 0; i < m->defaults_pyobjects; i++) + Py_VISIT(pydefaults[i]); + } + return 0; +} +static PyObject* +__Pyx_CyFunction_repr(__pyx_CyFunctionObject *op) +{ +#if PY_MAJOR_VERSION >= 3 + return PyUnicode_FromFormat("", + op->func_qualname, (void *)op); +#else + return PyString_FromFormat("", + PyString_AsString(op->func_qualname), (void *)op); +#endif +} +static PyObject * __Pyx_CyFunction_CallMethod(PyObject *func, PyObject *self, PyObject *arg, PyObject *kw) { +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *f = ((__pyx_CyFunctionObject*)func)->func; + PyObject *py_name = NULL; + PyCFunction meth; + int flags; + meth = PyCFunction_GetFunction(f); + if (unlikely(!meth)) return NULL; + flags = PyCFunction_GetFlags(f); + if (unlikely(flags < 0)) return NULL; +#else + PyCFunctionObject* f = (PyCFunctionObject*)func; + PyCFunction meth = f->m_ml->ml_meth; + int flags = f->m_ml->ml_flags; +#endif + Py_ssize_t size; + switch (flags & (METH_VARARGS | METH_KEYWORDS | METH_NOARGS | METH_O)) { + case METH_VARARGS: + if (likely(kw == NULL || PyDict_Size(kw) == 0)) + return (*meth)(self, arg); + break; + case METH_VARARGS | METH_KEYWORDS: + return (*(PyCFunctionWithKeywords)(void*)meth)(self, arg, kw); + case METH_NOARGS: + if (likely(kw == NULL || PyDict_Size(kw) == 0)) { +#if CYTHON_ASSUME_SAFE_MACROS + size = PyTuple_GET_SIZE(arg); +#else + size = PyTuple_Size(arg); + if (unlikely(size < 0)) return NULL; +#endif + if (likely(size == 0)) + return (*meth)(self, NULL); +#if CYTHON_COMPILING_IN_LIMITED_API + py_name = __Pyx_CyFunction_get_name((__pyx_CyFunctionObject*)func, NULL); + if (!py_name) return NULL; + PyErr_Format(PyExc_TypeError, + "%.200S() takes no arguments (%" CYTHON_FORMAT_SSIZE_T "d given)", + py_name, size); + Py_DECREF(py_name); +#else + PyErr_Format(PyExc_TypeError, + "%.200s() takes no arguments (%" CYTHON_FORMAT_SSIZE_T "d given)", + f->m_ml->ml_name, size); +#endif + return NULL; + } + break; + case METH_O: + if (likely(kw == NULL || PyDict_Size(kw) == 0)) { +#if CYTHON_ASSUME_SAFE_MACROS + size = PyTuple_GET_SIZE(arg); +#else + size = PyTuple_Size(arg); + if (unlikely(size < 0)) return NULL; +#endif + if (likely(size == 1)) { + PyObject *result, *arg0; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + arg0 = PyTuple_GET_ITEM(arg, 0); + #else + arg0 = __Pyx_PySequence_ITEM(arg, 0); if (unlikely(!arg0)) return NULL; + #endif + result = (*meth)(self, arg0); + #if !(CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS) + Py_DECREF(arg0); + #endif + return result; + } +#if CYTHON_COMPILING_IN_LIMITED_API + py_name = __Pyx_CyFunction_get_name((__pyx_CyFunctionObject*)func, NULL); + if (!py_name) return NULL; + PyErr_Format(PyExc_TypeError, + "%.200S() takes exactly one argument (%" CYTHON_FORMAT_SSIZE_T "d given)", + py_name, size); + Py_DECREF(py_name); +#else + PyErr_Format(PyExc_TypeError, + "%.200s() takes exactly one argument (%" CYTHON_FORMAT_SSIZE_T "d given)", + f->m_ml->ml_name, size); +#endif + return NULL; + } + break; + default: + PyErr_SetString(PyExc_SystemError, "Bad call flags for CyFunction"); + return NULL; + } +#if CYTHON_COMPILING_IN_LIMITED_API + py_name = __Pyx_CyFunction_get_name((__pyx_CyFunctionObject*)func, NULL); + if (!py_name) return NULL; + PyErr_Format(PyExc_TypeError, "%.200S() takes no keyword arguments", + py_name); + Py_DECREF(py_name); +#else + PyErr_Format(PyExc_TypeError, "%.200s() takes no keyword arguments", + f->m_ml->ml_name); +#endif + return NULL; +} +static CYTHON_INLINE PyObject *__Pyx_CyFunction_Call(PyObject *func, PyObject *arg, PyObject *kw) { + PyObject *self, *result; +#if CYTHON_COMPILING_IN_LIMITED_API + self = PyCFunction_GetSelf(((__pyx_CyFunctionObject*)func)->func); + if (unlikely(!self) && PyErr_Occurred()) return NULL; +#else + self = ((PyCFunctionObject*)func)->m_self; +#endif + result = __Pyx_CyFunction_CallMethod(func, self, arg, kw); + return result; +} +static PyObject *__Pyx_CyFunction_CallAsMethod(PyObject *func, PyObject *args, PyObject *kw) { + PyObject *result; + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *) func; +#if CYTHON_METH_FASTCALL + __pyx_vectorcallfunc vc = __Pyx_CyFunction_func_vectorcall(cyfunc); + if (vc) { +#if CYTHON_ASSUME_SAFE_MACROS + return __Pyx_PyVectorcall_FastCallDict(func, vc, &PyTuple_GET_ITEM(args, 0), (size_t)PyTuple_GET_SIZE(args), kw); +#else + (void) &__Pyx_PyVectorcall_FastCallDict; + return PyVectorcall_Call(func, args, kw); +#endif + } +#endif + if ((cyfunc->flags & __Pyx_CYFUNCTION_CCLASS) && !(cyfunc->flags & __Pyx_CYFUNCTION_STATICMETHOD)) { + Py_ssize_t argc; + PyObject *new_args; + PyObject *self; +#if CYTHON_ASSUME_SAFE_MACROS + argc = PyTuple_GET_SIZE(args); +#else + argc = PyTuple_Size(args); + if (unlikely(!argc) < 0) return NULL; +#endif + new_args = PyTuple_GetSlice(args, 1, argc); + if (unlikely(!new_args)) + return NULL; + self = PyTuple_GetItem(args, 0); + if (unlikely(!self)) { + Py_DECREF(new_args); +#if PY_MAJOR_VERSION > 2 + PyErr_Format(PyExc_TypeError, + "unbound method %.200S() needs an argument", + cyfunc->func_qualname); +#else + PyErr_SetString(PyExc_TypeError, + "unbound method needs an argument"); +#endif + return NULL; + } + result = __Pyx_CyFunction_CallMethod(func, self, new_args, kw); + Py_DECREF(new_args); + } else { + result = __Pyx_CyFunction_Call(func, args, kw); + } + return result; +} +#if CYTHON_METH_FASTCALL +static CYTHON_INLINE int __Pyx_CyFunction_Vectorcall_CheckArgs(__pyx_CyFunctionObject *cyfunc, Py_ssize_t nargs, PyObject *kwnames) +{ + int ret = 0; + if ((cyfunc->flags & __Pyx_CYFUNCTION_CCLASS) && !(cyfunc->flags & __Pyx_CYFUNCTION_STATICMETHOD)) { + if (unlikely(nargs < 1)) { + PyErr_Format(PyExc_TypeError, "%.200s() needs an argument", + ((PyCFunctionObject*)cyfunc)->m_ml->ml_name); + return -1; + } + ret = 1; + } + if (unlikely(kwnames) && unlikely(PyTuple_GET_SIZE(kwnames))) { + PyErr_Format(PyExc_TypeError, + "%.200s() takes no keyword arguments", ((PyCFunctionObject*)cyfunc)->m_ml->ml_name); + return -1; + } + return ret; +} +static PyObject * __Pyx_CyFunction_Vectorcall_NOARGS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) +{ + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *)func; + PyMethodDef* def = ((PyCFunctionObject*)cyfunc)->m_ml; +#if CYTHON_BACKPORT_VECTORCALL + Py_ssize_t nargs = (Py_ssize_t)nargsf; +#else + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); +#endif + PyObject *self; + switch (__Pyx_CyFunction_Vectorcall_CheckArgs(cyfunc, nargs, kwnames)) { + case 1: + self = args[0]; + args += 1; + nargs -= 1; + break; + case 0: + self = ((PyCFunctionObject*)cyfunc)->m_self; + break; + default: + return NULL; + } + if (unlikely(nargs != 0)) { + PyErr_Format(PyExc_TypeError, + "%.200s() takes no arguments (%" CYTHON_FORMAT_SSIZE_T "d given)", + def->ml_name, nargs); + return NULL; + } + return def->ml_meth(self, NULL); +} +static PyObject * __Pyx_CyFunction_Vectorcall_O(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) +{ + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *)func; + PyMethodDef* def = ((PyCFunctionObject*)cyfunc)->m_ml; +#if CYTHON_BACKPORT_VECTORCALL + Py_ssize_t nargs = (Py_ssize_t)nargsf; +#else + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); +#endif + PyObject *self; + switch (__Pyx_CyFunction_Vectorcall_CheckArgs(cyfunc, nargs, kwnames)) { + case 1: + self = args[0]; + args += 1; + nargs -= 1; + break; + case 0: + self = ((PyCFunctionObject*)cyfunc)->m_self; + break; + default: + return NULL; + } + if (unlikely(nargs != 1)) { + PyErr_Format(PyExc_TypeError, + "%.200s() takes exactly one argument (%" CYTHON_FORMAT_SSIZE_T "d given)", + def->ml_name, nargs); + return NULL; + } + return def->ml_meth(self, args[0]); +} +static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) +{ + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *)func; + PyMethodDef* def = ((PyCFunctionObject*)cyfunc)->m_ml; +#if CYTHON_BACKPORT_VECTORCALL + Py_ssize_t nargs = (Py_ssize_t)nargsf; +#else + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); +#endif + PyObject *self; + switch (__Pyx_CyFunction_Vectorcall_CheckArgs(cyfunc, nargs, NULL)) { + case 1: + self = args[0]; + args += 1; + nargs -= 1; + break; + case 0: + self = ((PyCFunctionObject*)cyfunc)->m_self; + break; + default: + return NULL; + } + return ((_PyCFunctionFastWithKeywords)(void(*)(void))def->ml_meth)(self, args, nargs, kwnames); +} +static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS_METHOD(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) +{ + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *)func; + PyMethodDef* def = ((PyCFunctionObject*)cyfunc)->m_ml; + PyTypeObject *cls = (PyTypeObject *) __Pyx_CyFunction_GetClassObj(cyfunc); +#if CYTHON_BACKPORT_VECTORCALL + Py_ssize_t nargs = (Py_ssize_t)nargsf; +#else + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); +#endif + PyObject *self; + switch (__Pyx_CyFunction_Vectorcall_CheckArgs(cyfunc, nargs, NULL)) { + case 1: + self = args[0]; + args += 1; + nargs -= 1; + break; + case 0: + self = ((PyCFunctionObject*)cyfunc)->m_self; + break; + default: + return NULL; + } + return ((__Pyx_PyCMethod)(void(*)(void))def->ml_meth)(self, cls, args, (size_t)nargs, kwnames); +} +#endif +#if CYTHON_USE_TYPE_SPECS +static PyType_Slot __pyx_CyFunctionType_slots[] = { + {Py_tp_dealloc, (void *)__Pyx_CyFunction_dealloc}, + {Py_tp_repr, (void *)__Pyx_CyFunction_repr}, + {Py_tp_call, (void *)__Pyx_CyFunction_CallAsMethod}, + {Py_tp_traverse, (void *)__Pyx_CyFunction_traverse}, + {Py_tp_clear, (void *)__Pyx_CyFunction_clear}, + {Py_tp_methods, (void *)__pyx_CyFunction_methods}, + {Py_tp_members, (void *)__pyx_CyFunction_members}, + {Py_tp_getset, (void *)__pyx_CyFunction_getsets}, + {Py_tp_descr_get, (void *)__Pyx_PyMethod_New}, + {0, 0}, +}; +static PyType_Spec __pyx_CyFunctionType_spec = { + __PYX_TYPE_MODULE_PREFIX "cython_function_or_method", + sizeof(__pyx_CyFunctionObject), + 0, +#ifdef Py_TPFLAGS_METHOD_DESCRIPTOR + Py_TPFLAGS_METHOD_DESCRIPTOR | +#endif +#if (defined(_Py_TPFLAGS_HAVE_VECTORCALL) && CYTHON_METH_FASTCALL) + _Py_TPFLAGS_HAVE_VECTORCALL | +#endif + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, + __pyx_CyFunctionType_slots +}; +#else +static PyTypeObject __pyx_CyFunctionType_type = { + PyVarObject_HEAD_INIT(0, 0) + __PYX_TYPE_MODULE_PREFIX "cython_function_or_method", + sizeof(__pyx_CyFunctionObject), + 0, + (destructor) __Pyx_CyFunction_dealloc, +#if !CYTHON_METH_FASTCALL + 0, +#elif CYTHON_BACKPORT_VECTORCALL + (printfunc)offsetof(__pyx_CyFunctionObject, func_vectorcall), +#else + offsetof(PyCFunctionObject, vectorcall), +#endif + 0, + 0, +#if PY_MAJOR_VERSION < 3 + 0, +#else + 0, +#endif + (reprfunc) __Pyx_CyFunction_repr, + 0, + 0, + 0, + 0, + __Pyx_CyFunction_CallAsMethod, + 0, + 0, + 0, + 0, +#ifdef Py_TPFLAGS_METHOD_DESCRIPTOR + Py_TPFLAGS_METHOD_DESCRIPTOR | +#endif +#if defined(_Py_TPFLAGS_HAVE_VECTORCALL) && CYTHON_METH_FASTCALL + _Py_TPFLAGS_HAVE_VECTORCALL | +#endif + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, + 0, + (traverseproc) __Pyx_CyFunction_traverse, + (inquiry) __Pyx_CyFunction_clear, + 0, +#if PY_VERSION_HEX < 0x030500A0 + offsetof(__pyx_CyFunctionObject, func_weakreflist), +#else + offsetof(PyCFunctionObject, m_weakreflist), +#endif + 0, + 0, + __pyx_CyFunction_methods, + __pyx_CyFunction_members, + __pyx_CyFunction_getsets, + 0, + 0, + __Pyx_PyMethod_New, + 0, + offsetof(__pyx_CyFunctionObject, func_dict), + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, +#if PY_VERSION_HEX >= 0x030400a1 + 0, +#endif +#if PY_VERSION_HEX >= 0x030800b1 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) + 0, +#endif +#if __PYX_NEED_TP_PRINT_SLOT + 0, +#endif +#if PY_VERSION_HEX >= 0x030C0000 + 0, +#endif +#if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 + 0, +#endif +}; +#endif +static int __pyx_CyFunction_init(PyObject *module) { +#if CYTHON_USE_TYPE_SPECS + __pyx_CyFunctionType = __Pyx_FetchCommonTypeFromSpec(module, &__pyx_CyFunctionType_spec, NULL); +#else + CYTHON_UNUSED_VAR(module); + __pyx_CyFunctionType = __Pyx_FetchCommonType(&__pyx_CyFunctionType_type); +#endif + if (unlikely(__pyx_CyFunctionType == NULL)) { + return -1; + } + return 0; +} +static CYTHON_INLINE void *__Pyx_CyFunction_InitDefaults(PyObject *func, size_t size, int pyobjects) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->defaults = PyObject_Malloc(size); + if (unlikely(!m->defaults)) + return PyErr_NoMemory(); + memset(m->defaults, 0, size); + m->defaults_pyobjects = pyobjects; + m->defaults_size = size; + return m->defaults; +} +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsTuple(PyObject *func, PyObject *tuple) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->defaults_tuple = tuple; + Py_INCREF(tuple); +} +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsKwDict(PyObject *func, PyObject *dict) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->defaults_kwdict = dict; + Py_INCREF(dict); +} +static CYTHON_INLINE void __Pyx_CyFunction_SetAnnotationsDict(PyObject *func, PyObject *dict) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->func_annotations = dict; + Py_INCREF(dict); +} + +/* CythonFunction */ +static PyObject *__Pyx_CyFunction_New(PyMethodDef *ml, int flags, PyObject* qualname, + PyObject *closure, PyObject *module, PyObject* globals, PyObject* code) { + PyObject *op = __Pyx_CyFunction_Init( + PyObject_GC_New(__pyx_CyFunctionObject, __pyx_CyFunctionType), + ml, flags, qualname, closure, module, globals, code + ); + if (likely(op)) { + PyObject_GC_Track(op); + } + return op; +} + +/* GetNameInClass */ +static PyObject *__Pyx__GetNameInClass(PyObject *nmspace, PyObject *name) { + PyObject *result; + PyObject *dict; + assert(PyType_Check(nmspace)); +#if CYTHON_USE_TYPE_SLOTS + dict = ((PyTypeObject*)nmspace)->tp_dict; + Py_XINCREF(dict); +#else + dict = PyObject_GetAttr(nmspace, __pyx_n_s_dict); +#endif + if (likely(dict)) { + result = PyObject_GetItem(dict, name); + Py_DECREF(dict); + if (result) { + return result; + } + } + PyErr_Clear(); + __Pyx_GetModuleGlobalNameUncached(result, name); + return result; +} + +/* CLineInTraceback */ +#ifndef CYTHON_CLINE_IN_TRACEBACK +static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line) { + PyObject *use_cline; + PyObject *ptype, *pvalue, *ptraceback; +#if CYTHON_COMPILING_IN_CPYTHON + PyObject **cython_runtime_dict; +#endif + CYTHON_MAYBE_UNUSED_VAR(tstate); + if (unlikely(!__pyx_cython_runtime)) { + return c_line; + } + __Pyx_ErrFetchInState(tstate, &ptype, &pvalue, &ptraceback); +#if CYTHON_COMPILING_IN_CPYTHON + cython_runtime_dict = _PyObject_GetDictPtr(__pyx_cython_runtime); + if (likely(cython_runtime_dict)) { + __PYX_PY_DICT_LOOKUP_IF_MODIFIED( + use_cline, *cython_runtime_dict, + __Pyx_PyDict_GetItemStr(*cython_runtime_dict, __pyx_n_s_cline_in_traceback)) + } else +#endif + { + PyObject *use_cline_obj = __Pyx_PyObject_GetAttrStrNoError(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback); + if (use_cline_obj) { + use_cline = PyObject_Not(use_cline_obj) ? Py_False : Py_True; + Py_DECREF(use_cline_obj); + } else { + PyErr_Clear(); + use_cline = NULL; + } + } + if (!use_cline) { + c_line = 0; + (void) PyObject_SetAttr(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback, Py_False); + } + else if (use_cline == Py_False || (use_cline != Py_True && PyObject_Not(use_cline) != 0)) { + c_line = 0; + } + __Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback); + return c_line; +} +#endif + +/* CodeObjectCache */ +#if !CYTHON_COMPILING_IN_LIMITED_API +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { + int start = 0, mid = 0, end = count - 1; + if (end >= 0 && code_line > entries[end].code_line) { + return count; + } + while (start < end) { + mid = start + (end - start) / 2; + if (code_line < entries[mid].code_line) { + end = mid; + } else if (code_line > entries[mid].code_line) { + start = mid + 1; + } else { + return mid; + } + } + if (code_line <= entries[mid].code_line) { + return mid; + } else { + return mid + 1; + } +} +static PyCodeObject *__pyx_find_code_object(int code_line) { + PyCodeObject* code_object; + int pos; + if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { + return NULL; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { + return NULL; + } + code_object = __pyx_code_cache.entries[pos].code_object; + Py_INCREF(code_object); + return code_object; +} +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { + int pos, i; + __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; + if (unlikely(!code_line)) { + return; + } + if (unlikely(!entries)) { + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); + if (likely(entries)) { + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = 64; + __pyx_code_cache.count = 1; + entries[0].code_line = code_line; + entries[0].code_object = code_object; + Py_INCREF(code_object); + } + return; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { + PyCodeObject* tmp = entries[pos].code_object; + entries[pos].code_object = code_object; + Py_DECREF(tmp); + return; + } + if (__pyx_code_cache.count == __pyx_code_cache.max_count) { + int new_max = __pyx_code_cache.max_count + 64; + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( + __pyx_code_cache.entries, ((size_t)new_max) * sizeof(__Pyx_CodeObjectCacheEntry)); + if (unlikely(!entries)) { + return; + } + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = new_max; + } + for (i=__pyx_code_cache.count; i>pos; i--) { + entries[i] = entries[i-1]; + } + entries[pos].code_line = code_line; + entries[pos].code_object = code_object; + __pyx_code_cache.count++; + Py_INCREF(code_object); +} +#endif + +/* AddTraceback */ +#include "compile.h" +#include "frameobject.h" +#include "traceback.h" +#if PY_VERSION_HEX >= 0x030b00a6 && !CYTHON_COMPILING_IN_LIMITED_API + #ifndef Py_BUILD_CORE + #define Py_BUILD_CORE 1 + #endif + #include "internal/pycore_frame.h" +#endif +#if CYTHON_COMPILING_IN_LIMITED_API +static PyObject *__Pyx_PyCode_Replace_For_AddTraceback(PyObject *code, PyObject *scratch_dict, + PyObject *firstlineno, PyObject *name) { + PyObject *replace = NULL; + if (unlikely(PyDict_SetItemString(scratch_dict, "co_firstlineno", firstlineno))) return NULL; + if (unlikely(PyDict_SetItemString(scratch_dict, "co_name", name))) return NULL; + replace = PyObject_GetAttrString(code, "replace"); + if (likely(replace)) { + PyObject *result; + result = PyObject_Call(replace, __pyx_empty_tuple, scratch_dict); + Py_DECREF(replace); + return result; + } + PyErr_Clear(); + #if __PYX_LIMITED_VERSION_HEX < 0x030780000 + { + PyObject *compiled = NULL, *result = NULL; + if (unlikely(PyDict_SetItemString(scratch_dict, "code", code))) return NULL; + if (unlikely(PyDict_SetItemString(scratch_dict, "type", (PyObject*)(&PyType_Type)))) return NULL; + compiled = Py_CompileString( + "out = type(code)(\n" + " code.co_argcount, code.co_kwonlyargcount, code.co_nlocals, code.co_stacksize,\n" + " code.co_flags, code.co_code, code.co_consts, code.co_names,\n" + " code.co_varnames, code.co_filename, co_name, co_firstlineno,\n" + " code.co_lnotab)\n", "", Py_file_input); + if (!compiled) return NULL; + result = PyEval_EvalCode(compiled, scratch_dict, scratch_dict); + Py_DECREF(compiled); + if (!result) PyErr_Print(); + Py_DECREF(result); + result = PyDict_GetItemString(scratch_dict, "out"); + if (result) Py_INCREF(result); + return result; + } + #else + return NULL; + #endif +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyObject *code_object = NULL, *py_py_line = NULL, *py_funcname = NULL, *dict = NULL; + PyObject *replace = NULL, *getframe = NULL, *frame = NULL; + PyObject *exc_type, *exc_value, *exc_traceback; + int success = 0; + if (c_line) { + (void) __pyx_cfilenm; + (void) __Pyx_CLineForTraceback(__Pyx_PyThreadState_Current, c_line); + } + PyErr_Fetch(&exc_type, &exc_value, &exc_traceback); + code_object = Py_CompileString("_getframe()", filename, Py_eval_input); + if (unlikely(!code_object)) goto bad; + py_py_line = PyLong_FromLong(py_line); + if (unlikely(!py_py_line)) goto bad; + py_funcname = PyUnicode_FromString(funcname); + if (unlikely(!py_funcname)) goto bad; + dict = PyDict_New(); + if (unlikely(!dict)) goto bad; + { + PyObject *old_code_object = code_object; + code_object = __Pyx_PyCode_Replace_For_AddTraceback(code_object, dict, py_py_line, py_funcname); + Py_DECREF(old_code_object); + } + if (unlikely(!code_object)) goto bad; + getframe = PySys_GetObject("_getframe"); + if (unlikely(!getframe)) goto bad; + if (unlikely(PyDict_SetItemString(dict, "_getframe", getframe))) goto bad; + frame = PyEval_EvalCode(code_object, dict, dict); + if (unlikely(!frame) || frame == Py_None) goto bad; + success = 1; + bad: + PyErr_Restore(exc_type, exc_value, exc_traceback); + Py_XDECREF(code_object); + Py_XDECREF(py_py_line); + Py_XDECREF(py_funcname); + Py_XDECREF(dict); + Py_XDECREF(replace); + if (success) { + PyTraceBack_Here( + (struct _frame*)frame); + } + Py_XDECREF(frame); +} +#else +static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( + const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = NULL; + PyObject *py_funcname = NULL; + #if PY_MAJOR_VERSION < 3 + PyObject *py_srcfile = NULL; + py_srcfile = PyString_FromString(filename); + if (!py_srcfile) goto bad; + #endif + if (c_line) { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + if (!py_funcname) goto bad; + #else + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + if (!py_funcname) goto bad; + funcname = PyUnicode_AsUTF8(py_funcname); + if (!funcname) goto bad; + #endif + } + else { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromString(funcname); + if (!py_funcname) goto bad; + #endif + } + #if PY_MAJOR_VERSION < 3 + py_code = __Pyx_PyCode_New( + 0, + 0, + 0, + 0, + 0, + 0, + __pyx_empty_bytes, /*PyObject *code,*/ + __pyx_empty_tuple, /*PyObject *consts,*/ + __pyx_empty_tuple, /*PyObject *names,*/ + __pyx_empty_tuple, /*PyObject *varnames,*/ + __pyx_empty_tuple, /*PyObject *freevars,*/ + __pyx_empty_tuple, /*PyObject *cellvars,*/ + py_srcfile, /*PyObject *filename,*/ + py_funcname, /*PyObject *name,*/ + py_line, + __pyx_empty_bytes /*PyObject *lnotab*/ + ); + Py_DECREF(py_srcfile); + #else + py_code = PyCode_NewEmpty(filename, funcname, py_line); + #endif + Py_XDECREF(py_funcname); + return py_code; +bad: + Py_XDECREF(py_funcname); + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(py_srcfile); + #endif + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyFrameObject *py_frame = 0; + PyThreadState *tstate = __Pyx_PyThreadState_Current; + PyObject *ptype, *pvalue, *ptraceback; + if (c_line) { + c_line = __Pyx_CLineForTraceback(tstate, c_line); + } + py_code = __pyx_find_code_object(c_line ? -c_line : py_line); + if (!py_code) { + __Pyx_ErrFetchInState(tstate, &ptype, &pvalue, &ptraceback); + py_code = __Pyx_CreateCodeObjectForTraceback( + funcname, c_line, py_line, filename); + if (!py_code) { + /* If the code object creation fails, then we should clear the + fetched exception references and propagate the new exception */ + Py_XDECREF(ptype); + Py_XDECREF(pvalue); + Py_XDECREF(ptraceback); + goto bad; + } + __Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback); + __pyx_insert_code_object(c_line ? -c_line : py_line, py_code); + } + py_frame = PyFrame_New( + tstate, /*PyThreadState *tstate,*/ + py_code, /*PyCodeObject *code,*/ + __pyx_d, /*PyObject *globals,*/ + 0 /*PyObject *locals*/ + ); + if (!py_frame) goto bad; + __Pyx_PyFrame_SetLineNumber(py_frame, py_line); + PyTraceBack_Here(py_frame); +bad: + Py_XDECREF(py_code); + Py_XDECREF(py_frame); +} +#endif + +/* CIntFromPyVerify */ +#define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value)\ + __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 0) +#define __PYX_VERIFY_RETURN_INT_EXC(target_type, func_type, func_value)\ + __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 1) +#define __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, exc)\ + {\ + func_type value = func_value;\ + if (sizeof(target_type) < sizeof(func_type)) {\ + if (unlikely(value != (func_type) (target_type) value)) {\ + func_type zero = 0;\ + if (exc && unlikely(value == (func_type)-1 && PyErr_Occurred()))\ + return (target_type) -1;\ + if (is_unsigned && unlikely(value < zero))\ + goto raise_neg_overflow;\ + else\ + goto raise_overflow;\ + }\ + }\ + return (target_type) value;\ + } + +/* CIntToPy */ +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const int neg_one = (int) -1, const_zero = (int) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(int) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(int) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); +#ifdef HAVE_LONG_LONG + } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); +#endif + } + } else { + if (sizeof(int) <= sizeof(long)) { + return PyInt_FromLong((long) value); +#ifdef HAVE_LONG_LONG + } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { + return PyLong_FromLongLong((PY_LONG_LONG) value); +#endif + } + } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; +#if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030d0000 + return _PyLong_FromByteArray(bytes, sizeof(int), + little, !is_unsigned); +#else + PyObject *from_bytes, *result = NULL; + PyObject *py_bytes = NULL, *arg_tuple = NULL, *kwds = NULL, *order_str = NULL; + from_bytes = PyObject_GetAttrString((PyObject*)&PyLong_Type, "from_bytes"); + if (!from_bytes) return NULL; + py_bytes = PyBytes_FromStringAndSize((char*)bytes, sizeof(int)); + if (!py_bytes) goto limited_bad; + order_str = PyUnicode_FromString(little ? "little" : "big"); + if (!order_str) goto limited_bad; + arg_tuple = PyTuple_Pack(2, py_bytes, order_str); + if (!arg_tuple) goto limited_bad; + if (!is_unsigned) { + kwds = PyDict_New(); + if (!kwds) goto limited_bad; + if (PyDict_SetItemString(kwds, "signed", __Pyx_NewRef(Py_True))) goto limited_bad; + } + result = PyObject_Call(from_bytes, arg_tuple, kwds); + limited_bad: + Py_XDECREF(kwds); + Py_XDECREF(arg_tuple); + Py_XDECREF(order_str); + Py_XDECREF(py_bytes); + Py_XDECREF(from_bytes); + return result; +#endif + } +} + +/* CIntToPy */ +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const long neg_one = (long) -1, const_zero = (long) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(long) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(long) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); +#ifdef HAVE_LONG_LONG + } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); +#endif + } + } else { + if (sizeof(long) <= sizeof(long)) { + return PyInt_FromLong((long) value); +#ifdef HAVE_LONG_LONG + } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { + return PyLong_FromLongLong((PY_LONG_LONG) value); +#endif + } + } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; +#if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030d0000 + return _PyLong_FromByteArray(bytes, sizeof(long), + little, !is_unsigned); +#else + PyObject *from_bytes, *result = NULL; + PyObject *py_bytes = NULL, *arg_tuple = NULL, *kwds = NULL, *order_str = NULL; + from_bytes = PyObject_GetAttrString((PyObject*)&PyLong_Type, "from_bytes"); + if (!from_bytes) return NULL; + py_bytes = PyBytes_FromStringAndSize((char*)bytes, sizeof(long)); + if (!py_bytes) goto limited_bad; + order_str = PyUnicode_FromString(little ? "little" : "big"); + if (!order_str) goto limited_bad; + arg_tuple = PyTuple_Pack(2, py_bytes, order_str); + if (!arg_tuple) goto limited_bad; + if (!is_unsigned) { + kwds = PyDict_New(); + if (!kwds) goto limited_bad; + if (PyDict_SetItemString(kwds, "signed", __Pyx_NewRef(Py_True))) goto limited_bad; + } + result = PyObject_Call(from_bytes, arg_tuple, kwds); + limited_bad: + Py_XDECREF(kwds); + Py_XDECREF(arg_tuple); + Py_XDECREF(order_str); + Py_XDECREF(py_bytes); + Py_XDECREF(from_bytes); + return result; +#endif + } +} + +/* CIntFromPy */ +static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const int neg_one = (int) -1, const_zero = (int) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if ((sizeof(int) < sizeof(long))) { + __PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG(x)) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + goto raise_neg_overflow; + } + return (int) val; + } + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_USE_PYLONG_INTERNALS + if (unlikely(__Pyx_PyLong_IsNeg(x))) { + goto raise_neg_overflow; + } else if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(int, __Pyx_compact_upylong, __Pyx_PyLong_CompactValueUnsigned(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_DigitCount(x)) { + case 2: + if ((8 * sizeof(int) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) >= 2 * PyLong_SHIFT)) { + return (int) (((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); + } + } + break; + case 3: + if ((8 * sizeof(int) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) >= 3 * PyLong_SHIFT)) { + return (int) (((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); + } + } + break; + case 4: + if ((8 * sizeof(int) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) >= 4 * PyLong_SHIFT)) { + return (int) (((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); + } + } + break; + } + } +#endif +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A7 + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (int) -1; + if (unlikely(result == 1)) + goto raise_neg_overflow; + } +#endif + if ((sizeof(int) <= sizeof(unsigned long))) { + __PYX_VERIFY_RETURN_INT_EXC(int, unsigned long, PyLong_AsUnsignedLong(x)) +#ifdef HAVE_LONG_LONG + } else if ((sizeof(int) <= sizeof(unsigned PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(int, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) +#endif + } + } else { +#if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(int, __Pyx_compact_pylong, __Pyx_PyLong_CompactValue(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_SignedDigitCount(x)) { + case -2: + if ((8 * sizeof(int) - 1 > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 2 * PyLong_SHIFT)) { + return (int) (((int)-1)*(((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case 2: + if ((8 * sizeof(int) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 2 * PyLong_SHIFT)) { + return (int) ((((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case -3: + if ((8 * sizeof(int) - 1 > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 3 * PyLong_SHIFT)) { + return (int) (((int)-1)*(((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case 3: + if ((8 * sizeof(int) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 3 * PyLong_SHIFT)) { + return (int) ((((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case -4: + if ((8 * sizeof(int) - 1 > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 4 * PyLong_SHIFT)) { + return (int) (((int)-1)*(((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case 4: + if ((8 * sizeof(int) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 4 * PyLong_SHIFT)) { + return (int) ((((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + } + } +#endif + if ((sizeof(int) <= sizeof(long))) { + __PYX_VERIFY_RETURN_INT_EXC(int, long, PyLong_AsLong(x)) +#ifdef HAVE_LONG_LONG + } else if ((sizeof(int) <= sizeof(PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(int, PY_LONG_LONG, PyLong_AsLongLong(x)) +#endif + } + } + { + int val; + PyObject *v = __Pyx_PyNumber_IntOrLong(x); +#if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } +#endif + if (likely(v)) { + int ret = -1; +#if PY_VERSION_HEX < 0x030d0000 && !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API) || defined(_PyLong_AsByteArray) + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); +#else + PyObject *stepval = NULL, *mask = NULL, *shift = NULL; + int bits, remaining_bits, is_negative = 0; + long idigit; + int chunk_size = (sizeof(long) < 8) ? 30 : 62; + if (unlikely(!PyLong_CheckExact(v))) { + PyObject *tmp = v; + v = PyNumber_Long(v); + assert(PyLong_CheckExact(v)); + Py_DECREF(tmp); + if (unlikely(!v)) return (int) -1; + } +#if CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030B0000 + if (Py_SIZE(x) == 0) + return (int) 0; + is_negative = Py_SIZE(x) < 0; +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (int) -1; + is_negative = result == 1; + } +#endif + if (is_unsigned && unlikely(is_negative)) { + goto raise_neg_overflow; + } else if (is_negative) { + stepval = PyNumber_Invert(v); + if (unlikely(!stepval)) + return (int) -1; + } else { + stepval = __Pyx_NewRef(v); + } + val = (int) 0; + mask = PyLong_FromLong((1L << chunk_size) - 1); if (unlikely(!mask)) goto done; + shift = PyLong_FromLong(chunk_size); if (unlikely(!shift)) goto done; + for (bits = 0; bits < (int) sizeof(int) * 8 - chunk_size; bits += chunk_size) { + PyObject *tmp, *digit; + digit = PyNumber_And(stepval, mask); + if (unlikely(!digit)) goto done; + idigit = PyLong_AsLong(digit); + Py_DECREF(digit); + if (unlikely(idigit < 0)) goto done; + tmp = PyNumber_Rshift(stepval, shift); + if (unlikely(!tmp)) goto done; + Py_DECREF(stepval); stepval = tmp; + val |= ((int) idigit) << bits; + #if CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030B0000 + if (Py_SIZE(stepval) == 0) + goto unpacking_done; + #endif + } + idigit = PyLong_AsLong(stepval); + if (unlikely(idigit < 0)) goto done; + remaining_bits = ((int) sizeof(int) * 8) - bits - (is_unsigned ? 0 : 1); + if (unlikely(idigit >= (1L << remaining_bits))) + goto raise_overflow; + val |= ((int) idigit) << bits; + #if CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030B0000 + unpacking_done: + #endif + if (!is_unsigned) { + if (unlikely(val & (((int) 1) << (sizeof(int) * 8 - 1)))) + goto raise_overflow; + if (is_negative) + val = ~val; + } + ret = 0; + done: + Py_XDECREF(shift); + Py_XDECREF(mask); + Py_XDECREF(stepval); +#endif + Py_DECREF(v); + if (likely(!ret)) + return val; + } + return (int) -1; + } + } else { + int val; + PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); + if (!tmp) return (int) -1; + val = __Pyx_PyInt_As_int(tmp); + Py_DECREF(tmp); + return val; + } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to int"); + return (int) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to int"); + return (int) -1; +} + +/* CIntFromPy */ +static CYTHON_INLINE size_t __Pyx_PyInt_As_size_t(PyObject *x) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const size_t neg_one = (size_t) -1, const_zero = (size_t) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if ((sizeof(size_t) < sizeof(long))) { + __PYX_VERIFY_RETURN_INT(size_t, long, PyInt_AS_LONG(x)) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + goto raise_neg_overflow; + } + return (size_t) val; + } + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_USE_PYLONG_INTERNALS + if (unlikely(__Pyx_PyLong_IsNeg(x))) { + goto raise_neg_overflow; + } else if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(size_t, __Pyx_compact_upylong, __Pyx_PyLong_CompactValueUnsigned(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_DigitCount(x)) { + case 2: + if ((8 * sizeof(size_t) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(size_t, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(size_t) >= 2 * PyLong_SHIFT)) { + return (size_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + } + break; + case 3: + if ((8 * sizeof(size_t) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(size_t, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(size_t) >= 3 * PyLong_SHIFT)) { + return (size_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + } + break; + case 4: + if ((8 * sizeof(size_t) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(size_t, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(size_t) >= 4 * PyLong_SHIFT)) { + return (size_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + } + break; + } + } +#endif +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A7 + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (size_t) -1; + if (unlikely(result == 1)) + goto raise_neg_overflow; + } +#endif + if ((sizeof(size_t) <= sizeof(unsigned long))) { + __PYX_VERIFY_RETURN_INT_EXC(size_t, unsigned long, PyLong_AsUnsignedLong(x)) +#ifdef HAVE_LONG_LONG + } else if ((sizeof(size_t) <= sizeof(unsigned PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(size_t, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) +#endif + } + } else { +#if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(size_t, __Pyx_compact_pylong, __Pyx_PyLong_CompactValue(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_SignedDigitCount(x)) { + case -2: + if ((8 * sizeof(size_t) - 1 > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(size_t, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(size_t) - 1 > 2 * PyLong_SHIFT)) { + return (size_t) (((size_t)-1)*(((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]))); + } + } + break; + case 2: + if ((8 * sizeof(size_t) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(size_t, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(size_t) - 1 > 2 * PyLong_SHIFT)) { + return (size_t) ((((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]))); + } + } + break; + case -3: + if ((8 * sizeof(size_t) - 1 > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(size_t, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(size_t) - 1 > 3 * PyLong_SHIFT)) { + return (size_t) (((size_t)-1)*(((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]))); + } + } + break; + case 3: + if ((8 * sizeof(size_t) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(size_t, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(size_t) - 1 > 3 * PyLong_SHIFT)) { + return (size_t) ((((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]))); + } + } + break; + case -4: + if ((8 * sizeof(size_t) - 1 > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(size_t, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(size_t) - 1 > 4 * PyLong_SHIFT)) { + return (size_t) (((size_t)-1)*(((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]))); + } + } + break; + case 4: + if ((8 * sizeof(size_t) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(size_t, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(size_t) - 1 > 4 * PyLong_SHIFT)) { + return (size_t) ((((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]))); + } + } + break; + } + } +#endif + if ((sizeof(size_t) <= sizeof(long))) { + __PYX_VERIFY_RETURN_INT_EXC(size_t, long, PyLong_AsLong(x)) +#ifdef HAVE_LONG_LONG + } else if ((sizeof(size_t) <= sizeof(PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(size_t, PY_LONG_LONG, PyLong_AsLongLong(x)) +#endif + } + } + { + size_t val; + PyObject *v = __Pyx_PyNumber_IntOrLong(x); +#if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } +#endif + if (likely(v)) { + int ret = -1; +#if PY_VERSION_HEX < 0x030d0000 && !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API) || defined(_PyLong_AsByteArray) + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); +#else + PyObject *stepval = NULL, *mask = NULL, *shift = NULL; + int bits, remaining_bits, is_negative = 0; + long idigit; + int chunk_size = (sizeof(long) < 8) ? 30 : 62; + if (unlikely(!PyLong_CheckExact(v))) { + PyObject *tmp = v; + v = PyNumber_Long(v); + assert(PyLong_CheckExact(v)); + Py_DECREF(tmp); + if (unlikely(!v)) return (size_t) -1; + } +#if CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030B0000 + if (Py_SIZE(x) == 0) + return (size_t) 0; + is_negative = Py_SIZE(x) < 0; +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (size_t) -1; + is_negative = result == 1; + } +#endif + if (is_unsigned && unlikely(is_negative)) { + goto raise_neg_overflow; + } else if (is_negative) { + stepval = PyNumber_Invert(v); + if (unlikely(!stepval)) + return (size_t) -1; + } else { + stepval = __Pyx_NewRef(v); + } + val = (size_t) 0; + mask = PyLong_FromLong((1L << chunk_size) - 1); if (unlikely(!mask)) goto done; + shift = PyLong_FromLong(chunk_size); if (unlikely(!shift)) goto done; + for (bits = 0; bits < (int) sizeof(size_t) * 8 - chunk_size; bits += chunk_size) { + PyObject *tmp, *digit; + digit = PyNumber_And(stepval, mask); + if (unlikely(!digit)) goto done; + idigit = PyLong_AsLong(digit); + Py_DECREF(digit); + if (unlikely(idigit < 0)) goto done; + tmp = PyNumber_Rshift(stepval, shift); + if (unlikely(!tmp)) goto done; + Py_DECREF(stepval); stepval = tmp; + val |= ((size_t) idigit) << bits; + #if CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030B0000 + if (Py_SIZE(stepval) == 0) + goto unpacking_done; + #endif + } + idigit = PyLong_AsLong(stepval); + if (unlikely(idigit < 0)) goto done; + remaining_bits = ((int) sizeof(size_t) * 8) - bits - (is_unsigned ? 0 : 1); + if (unlikely(idigit >= (1L << remaining_bits))) + goto raise_overflow; + val |= ((size_t) idigit) << bits; + #if CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030B0000 + unpacking_done: + #endif + if (!is_unsigned) { + if (unlikely(val & (((size_t) 1) << (sizeof(size_t) * 8 - 1)))) + goto raise_overflow; + if (is_negative) + val = ~val; + } + ret = 0; + done: + Py_XDECREF(shift); + Py_XDECREF(mask); + Py_XDECREF(stepval); +#endif + Py_DECREF(v); + if (likely(!ret)) + return val; + } + return (size_t) -1; + } + } else { + size_t val; + PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); + if (!tmp) return (size_t) -1; + val = __Pyx_PyInt_As_size_t(tmp); + Py_DECREF(tmp); + return val; + } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to size_t"); + return (size_t) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to size_t"); + return (size_t) -1; +} + +/* FormatTypeName */ +#if CYTHON_COMPILING_IN_LIMITED_API +static __Pyx_TypeName +__Pyx_PyType_GetName(PyTypeObject* tp) +{ + PyObject *name = __Pyx_PyObject_GetAttrStr((PyObject *)tp, + __pyx_n_s_name); + if (unlikely(name == NULL) || unlikely(!PyUnicode_Check(name))) { + PyErr_Clear(); + Py_XDECREF(name); + name = __Pyx_NewRef(__pyx_n_s__26); + } + return name; +} +#endif + +/* CIntFromPy */ +static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const long neg_one = (long) -1, const_zero = (long) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if ((sizeof(long) < sizeof(long))) { + __PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG(x)) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + goto raise_neg_overflow; + } + return (long) val; + } + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_USE_PYLONG_INTERNALS + if (unlikely(__Pyx_PyLong_IsNeg(x))) { + goto raise_neg_overflow; + } else if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(long, __Pyx_compact_upylong, __Pyx_PyLong_CompactValueUnsigned(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_DigitCount(x)) { + case 2: + if ((8 * sizeof(long) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) >= 2 * PyLong_SHIFT)) { + return (long) (((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); + } + } + break; + case 3: + if ((8 * sizeof(long) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) >= 3 * PyLong_SHIFT)) { + return (long) (((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); + } + } + break; + case 4: + if ((8 * sizeof(long) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) >= 4 * PyLong_SHIFT)) { + return (long) (((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); + } + } + break; + } + } +#endif +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A7 + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (long) -1; + if (unlikely(result == 1)) + goto raise_neg_overflow; + } +#endif + if ((sizeof(long) <= sizeof(unsigned long))) { + __PYX_VERIFY_RETURN_INT_EXC(long, unsigned long, PyLong_AsUnsignedLong(x)) +#ifdef HAVE_LONG_LONG + } else if ((sizeof(long) <= sizeof(unsigned PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(long, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) +#endif + } + } else { +#if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(long, __Pyx_compact_pylong, __Pyx_PyLong_CompactValue(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_SignedDigitCount(x)) { + case -2: + if ((8 * sizeof(long) - 1 > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 2 * PyLong_SHIFT)) { + return (long) (((long)-1)*(((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case 2: + if ((8 * sizeof(long) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 2 * PyLong_SHIFT)) { + return (long) ((((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case -3: + if ((8 * sizeof(long) - 1 > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 3 * PyLong_SHIFT)) { + return (long) (((long)-1)*(((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case 3: + if ((8 * sizeof(long) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 3 * PyLong_SHIFT)) { + return (long) ((((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case -4: + if ((8 * sizeof(long) - 1 > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 4 * PyLong_SHIFT)) { + return (long) (((long)-1)*(((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case 4: + if ((8 * sizeof(long) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 4 * PyLong_SHIFT)) { + return (long) ((((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + } + } +#endif + if ((sizeof(long) <= sizeof(long))) { + __PYX_VERIFY_RETURN_INT_EXC(long, long, PyLong_AsLong(x)) +#ifdef HAVE_LONG_LONG + } else if ((sizeof(long) <= sizeof(PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(long, PY_LONG_LONG, PyLong_AsLongLong(x)) +#endif + } + } + { + long val; + PyObject *v = __Pyx_PyNumber_IntOrLong(x); +#if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } +#endif + if (likely(v)) { + int ret = -1; +#if PY_VERSION_HEX < 0x030d0000 && !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API) || defined(_PyLong_AsByteArray) + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); +#else + PyObject *stepval = NULL, *mask = NULL, *shift = NULL; + int bits, remaining_bits, is_negative = 0; + long idigit; + int chunk_size = (sizeof(long) < 8) ? 30 : 62; + if (unlikely(!PyLong_CheckExact(v))) { + PyObject *tmp = v; + v = PyNumber_Long(v); + assert(PyLong_CheckExact(v)); + Py_DECREF(tmp); + if (unlikely(!v)) return (long) -1; + } +#if CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030B0000 + if (Py_SIZE(x) == 0) + return (long) 0; + is_negative = Py_SIZE(x) < 0; +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (long) -1; + is_negative = result == 1; + } +#endif + if (is_unsigned && unlikely(is_negative)) { + goto raise_neg_overflow; + } else if (is_negative) { + stepval = PyNumber_Invert(v); + if (unlikely(!stepval)) + return (long) -1; + } else { + stepval = __Pyx_NewRef(v); + } + val = (long) 0; + mask = PyLong_FromLong((1L << chunk_size) - 1); if (unlikely(!mask)) goto done; + shift = PyLong_FromLong(chunk_size); if (unlikely(!shift)) goto done; + for (bits = 0; bits < (int) sizeof(long) * 8 - chunk_size; bits += chunk_size) { + PyObject *tmp, *digit; + digit = PyNumber_And(stepval, mask); + if (unlikely(!digit)) goto done; + idigit = PyLong_AsLong(digit); + Py_DECREF(digit); + if (unlikely(idigit < 0)) goto done; + tmp = PyNumber_Rshift(stepval, shift); + if (unlikely(!tmp)) goto done; + Py_DECREF(stepval); stepval = tmp; + val |= ((long) idigit) << bits; + #if CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030B0000 + if (Py_SIZE(stepval) == 0) + goto unpacking_done; + #endif + } + idigit = PyLong_AsLong(stepval); + if (unlikely(idigit < 0)) goto done; + remaining_bits = ((int) sizeof(long) * 8) - bits - (is_unsigned ? 0 : 1); + if (unlikely(idigit >= (1L << remaining_bits))) + goto raise_overflow; + val |= ((long) idigit) << bits; + #if CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030B0000 + unpacking_done: + #endif + if (!is_unsigned) { + if (unlikely(val & (((long) 1) << (sizeof(long) * 8 - 1)))) + goto raise_overflow; + if (is_negative) + val = ~val; + } + ret = 0; + done: + Py_XDECREF(shift); + Py_XDECREF(mask); + Py_XDECREF(stepval); +#endif + Py_DECREF(v); + if (likely(!ret)) + return val; + } + return (long) -1; + } + } else { + long val; + PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); + if (!tmp) return (long) -1; + val = __Pyx_PyInt_As_long(tmp); + Py_DECREF(tmp); + return val; + } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to long"); + return (long) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to long"); + return (long) -1; +} + +/* FastTypeChecks */ +#if CYTHON_COMPILING_IN_CPYTHON +static int __Pyx_InBases(PyTypeObject *a, PyTypeObject *b) { + while (a) { + a = __Pyx_PyType_GetSlot(a, tp_base, PyTypeObject*); + if (a == b) + return 1; + } + return b == &PyBaseObject_Type; +} +static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b) { + PyObject *mro; + if (a == b) return 1; + mro = a->tp_mro; + if (likely(mro)) { + Py_ssize_t i, n; + n = PyTuple_GET_SIZE(mro); + for (i = 0; i < n; i++) { + if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b) + return 1; + } + return 0; + } + return __Pyx_InBases(a, b); +} +static CYTHON_INLINE int __Pyx_IsAnySubtype2(PyTypeObject *cls, PyTypeObject *a, PyTypeObject *b) { + PyObject *mro; + if (cls == a || cls == b) return 1; + mro = cls->tp_mro; + if (likely(mro)) { + Py_ssize_t i, n; + n = PyTuple_GET_SIZE(mro); + for (i = 0; i < n; i++) { + PyObject *base = PyTuple_GET_ITEM(mro, i); + if (base == (PyObject *)a || base == (PyObject *)b) + return 1; + } + return 0; + } + return __Pyx_InBases(cls, a) || __Pyx_InBases(cls, b); +} +#if PY_MAJOR_VERSION == 2 +static int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject* exc_type2) { + PyObject *exception, *value, *tb; + int res; + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + __Pyx_ErrFetch(&exception, &value, &tb); + res = exc_type1 ? PyObject_IsSubclass(err, exc_type1) : 0; + if (unlikely(res == -1)) { + PyErr_WriteUnraisable(err); + res = 0; + } + if (!res) { + res = PyObject_IsSubclass(err, exc_type2); + if (unlikely(res == -1)) { + PyErr_WriteUnraisable(err); + res = 0; + } + } + __Pyx_ErrRestore(exception, value, tb); + return res; +} +#else +static CYTHON_INLINE int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject *exc_type2) { + if (exc_type1) { + return __Pyx_IsAnySubtype2((PyTypeObject*)err, (PyTypeObject*)exc_type1, (PyTypeObject*)exc_type2); + } else { + return __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type2); + } +} +#endif +static int __Pyx_PyErr_GivenExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { + Py_ssize_t i, n; + assert(PyExceptionClass_Check(exc_type)); + n = PyTuple_GET_SIZE(tuple); +#if PY_MAJOR_VERSION >= 3 + for (i=0; i= 0x030B00A4 + return Py_Version & ~0xFFUL; +#else + const char* rt_version = Py_GetVersion(); + unsigned long version = 0; + unsigned long factor = 0x01000000UL; + unsigned int digit = 0; + int i = 0; + while (factor) { + while ('0' <= rt_version[i] && rt_version[i] <= '9') { + digit = digit * 10 + (unsigned int) (rt_version[i] - '0'); + ++i; + } + version += factor * digit; + if (rt_version[i] != '.') + break; + digit = 0; + factor >>= 8; + ++i; + } + return version; +#endif +} +static int __Pyx_check_binary_version(unsigned long ct_version, unsigned long rt_version, int allow_newer) { + const unsigned long MAJOR_MINOR = 0xFFFF0000UL; + if ((rt_version & MAJOR_MINOR) == (ct_version & MAJOR_MINOR)) + return 0; + if (likely(allow_newer && (rt_version & MAJOR_MINOR) > (ct_version & MAJOR_MINOR))) + return 1; + { + char message[200]; + PyOS_snprintf(message, sizeof(message), + "compile time Python version %d.%d " + "of module '%.100s' " + "%s " + "runtime version %d.%d", + (int) (ct_version >> 24), (int) ((ct_version >> 16) & 0xFF), + __Pyx_MODULE_NAME, + (allow_newer) ? "was newer than" : "does not match", + (int) (rt_version >> 24), (int) ((rt_version >> 16) & 0xFF) + ); + return PyErr_WarnEx(NULL, message, 1); + } +} + +/* InitStrings */ +#if PY_MAJOR_VERSION >= 3 +static int __Pyx_InitString(__Pyx_StringTabEntry t, PyObject **str) { + if (t.is_unicode | t.is_str) { + if (t.intern) { + *str = PyUnicode_InternFromString(t.s); + } else if (t.encoding) { + *str = PyUnicode_Decode(t.s, t.n - 1, t.encoding, NULL); + } else { + *str = PyUnicode_FromStringAndSize(t.s, t.n - 1); + } + } else { + *str = PyBytes_FromStringAndSize(t.s, t.n - 1); + } + if (!*str) + return -1; + if (PyObject_Hash(*str) == -1) + return -1; + return 0; +} +#endif +static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { + while (t->p) { + #if PY_MAJOR_VERSION >= 3 + __Pyx_InitString(*t, t->p); + #else + if (t->is_unicode) { + *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL); + } else if (t->intern) { + *t->p = PyString_InternFromString(t->s); + } else { + *t->p = PyString_FromStringAndSize(t->s, t->n - 1); + } + if (!*t->p) + return -1; + if (PyObject_Hash(*t->p) == -1) + return -1; + #endif + ++t; + } + return 0; +} + +#include +static CYTHON_INLINE Py_ssize_t __Pyx_ssize_strlen(const char *s) { + size_t len = strlen(s); + if (unlikely(len > (size_t) PY_SSIZE_T_MAX)) { + PyErr_SetString(PyExc_OverflowError, "byte string is too long"); + return -1; + } + return (Py_ssize_t) len; +} +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { + Py_ssize_t len = __Pyx_ssize_strlen(c_str); + if (unlikely(len < 0)) return NULL; + return __Pyx_PyUnicode_FromStringAndSize(c_str, len); +} +static CYTHON_INLINE PyObject* __Pyx_PyByteArray_FromString(const char* c_str) { + Py_ssize_t len = __Pyx_ssize_strlen(c_str); + if (unlikely(len < 0)) return NULL; + return PyByteArray_FromStringAndSize(c_str, len); +} +static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject* o) { + Py_ssize_t ignore; + return __Pyx_PyObject_AsStringAndSize(o, &ignore); +} +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT +#if !CYTHON_PEP393_ENABLED +static const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { + char* defenc_c; + PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); + if (!defenc) return NULL; + defenc_c = PyBytes_AS_STRING(defenc); +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + { + char* end = defenc_c + PyBytes_GET_SIZE(defenc); + char* c; + for (c = defenc_c; c < end; c++) { + if ((unsigned char) (*c) >= 128) { + PyUnicode_AsASCIIString(o); + return NULL; + } + } + } +#endif + *length = PyBytes_GET_SIZE(defenc); + return defenc_c; +} +#else +static CYTHON_INLINE const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { + if (unlikely(__Pyx_PyUnicode_READY(o) == -1)) return NULL; +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + if (likely(PyUnicode_IS_ASCII(o))) { + *length = PyUnicode_GET_LENGTH(o); + return PyUnicode_AsUTF8(o); + } else { + PyUnicode_AsASCIIString(o); + return NULL; + } +#else + return PyUnicode_AsUTF8AndSize(o, length); +#endif +} +#endif +#endif +static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT + if ( +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + __Pyx_sys_getdefaultencoding_not_ascii && +#endif + PyUnicode_Check(o)) { + return __Pyx_PyUnicode_AsStringAndSize(o, length); + } else +#endif +#if (!CYTHON_COMPILING_IN_PYPY && !CYTHON_COMPILING_IN_LIMITED_API) || (defined(PyByteArray_AS_STRING) && defined(PyByteArray_GET_SIZE)) + if (PyByteArray_Check(o)) { + *length = PyByteArray_GET_SIZE(o); + return PyByteArray_AS_STRING(o); + } else +#endif + { + char* result; + int r = PyBytes_AsStringAndSize(o, &result, length); + if (unlikely(r < 0)) { + return NULL; + } else { + return result; + } + } +} +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { + int is_true = x == Py_True; + if (is_true | (x == Py_False) | (x == Py_None)) return is_true; + else return PyObject_IsTrue(x); +} +static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject* x) { + int retval; + if (unlikely(!x)) return -1; + retval = __Pyx_PyObject_IsTrue(x); + Py_DECREF(x); + return retval; +} +static PyObject* __Pyx_PyNumber_IntOrLongWrongResultType(PyObject* result, const char* type_name) { + __Pyx_TypeName result_type_name = __Pyx_PyType_GetName(Py_TYPE(result)); +#if PY_MAJOR_VERSION >= 3 + if (PyLong_Check(result)) { + if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1, + "__int__ returned non-int (type " __Pyx_FMT_TYPENAME "). " + "The ability to return an instance of a strict subclass of int is deprecated, " + "and may be removed in a future version of Python.", + result_type_name)) { + __Pyx_DECREF_TypeName(result_type_name); + Py_DECREF(result); + return NULL; + } + __Pyx_DECREF_TypeName(result_type_name); + return result; + } +#endif + PyErr_Format(PyExc_TypeError, + "__%.4s__ returned non-%.4s (type " __Pyx_FMT_TYPENAME ")", + type_name, type_name, result_type_name); + __Pyx_DECREF_TypeName(result_type_name); + Py_DECREF(result); + return NULL; +} +static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x) { +#if CYTHON_USE_TYPE_SLOTS + PyNumberMethods *m; +#endif + const char *name = NULL; + PyObject *res = NULL; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x) || PyLong_Check(x))) +#else + if (likely(PyLong_Check(x))) +#endif + return __Pyx_NewRef(x); +#if CYTHON_USE_TYPE_SLOTS + m = Py_TYPE(x)->tp_as_number; + #if PY_MAJOR_VERSION < 3 + if (m && m->nb_int) { + name = "int"; + res = m->nb_int(x); + } + else if (m && m->nb_long) { + name = "long"; + res = m->nb_long(x); + } + #else + if (likely(m && m->nb_int)) { + name = "int"; + res = m->nb_int(x); + } + #endif +#else + if (!PyBytes_CheckExact(x) && !PyUnicode_CheckExact(x)) { + res = PyNumber_Int(x); + } +#endif + if (likely(res)) { +#if PY_MAJOR_VERSION < 3 + if (unlikely(!PyInt_Check(res) && !PyLong_Check(res))) { +#else + if (unlikely(!PyLong_CheckExact(res))) { +#endif + return __Pyx_PyNumber_IntOrLongWrongResultType(res, name); + } + } + else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_TypeError, + "an integer is required"); + } + return res; +} +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { + Py_ssize_t ival; + PyObject *x; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_CheckExact(b))) { + if (sizeof(Py_ssize_t) >= sizeof(long)) + return PyInt_AS_LONG(b); + else + return PyInt_AsSsize_t(b); + } +#endif + if (likely(PyLong_CheckExact(b))) { + #if CYTHON_USE_PYLONG_INTERNALS + if (likely(__Pyx_PyLong_IsCompact(b))) { + return __Pyx_PyLong_CompactValue(b); + } else { + const digit* digits = __Pyx_PyLong_Digits(b); + const Py_ssize_t size = __Pyx_PyLong_SignedDigitCount(b); + switch (size) { + case 2: + if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { + return (Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case -2: + if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { + return -(Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case 3: + if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { + return (Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case -3: + if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { + return -(Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case 4: + if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { + return (Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case -4: + if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { + return -(Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + } + } + #endif + return PyLong_AsSsize_t(b); + } + x = PyNumber_Index(b); + if (!x) return -1; + ival = PyInt_AsSsize_t(x); + Py_DECREF(x); + return ival; +} +static CYTHON_INLINE Py_hash_t __Pyx_PyIndex_AsHash_t(PyObject* o) { + if (sizeof(Py_hash_t) == sizeof(Py_ssize_t)) { + return (Py_hash_t) __Pyx_PyIndex_AsSsize_t(o); +#if PY_MAJOR_VERSION < 3 + } else if (likely(PyInt_CheckExact(o))) { + return PyInt_AS_LONG(o); +#endif + } else { + Py_ssize_t ival; + PyObject *x; + x = PyNumber_Index(o); + if (!x) return -1; + ival = PyInt_AsLong(x); + Py_DECREF(x); + return ival; + } +} +static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b) { + return b ? __Pyx_NewRef(Py_True) : __Pyx_NewRef(Py_False); +} +static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { + return PyInt_FromSize_t(ival); +} + + +/* #### Code section: utility_code_pragmas_end ### */ +#ifdef _MSC_VER +#pragma warning( pop ) +#endif + + + +/* #### Code section: end ### */ +#endif /* Py_PYTHON_H */ diff --git a/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/_wordpiece.pxd b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/_wordpiece.pxd new file mode 100644 index 0000000000000000000000000000000000000000..842f35217683a9583bcdf79e3ac58da1175cc376 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/_wordpiece.pxd @@ -0,0 +1,22 @@ +from cython cimport size_t +from libcpp.string cimport string +from libcpp.unordered_map cimport unordered_map +from libcpp.vector cimport vector + +cdef extern from "wordpiece.hh": + cdef cppclass Piece: + string piece + bint is_initial + Piece() + Piece(const string& piece, bint initial) + + cdef cppclass PieceStorage: + vector[Piece] _id_to_piece + + PieceStorage() + void add_piece(const string &piece, const bint is_initial) + size_t size() + const Piece &id_to_piece(const int id) except + + size_t piece_to_id(const Piece &piece) except + + int try_piece_to_id(const Piece &piece) + diff --git a/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/_wordpiece.pyx b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/_wordpiece.pyx new file mode 100644 index 0000000000000000000000000000000000000000..18b74e5b5eadba6ebe315d8dcc19ae28c10bde36 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/_wordpiece.pyx @@ -0,0 +1,136 @@ +from typing import List, Tuple, Iterable +from cython.operator cimport dereference as deref +from libcpp cimport pair + +cdef struct PieceMatch: + bint found + int prefix_len + int piece_id + +cdef class WordPieceProcessor: + cdef PieceStorage _pieces + + def __init__(self, pieces: List[str]): + self._pieces = PieceStorage() + + for idx, piece in enumerate(pieces): + is_initial = not piece.startswith("##") + byte_array = piece[2:].encode('utf8') if not is_initial else piece.encode('utf8') + self._pieces.add_piece(byte_array, is_initial) + + def __copy__(self): + # This is essentially a deepcopy, but there's no better way to do it. + return WordPieceProcessor(self.to_list()) + + def __deepcopy__(self, memo): + return WordPieceProcessor(self.to_list()) + + def encode(self, token: str) -> Tuple[List[int], List[str]]: + """ + Encode a token using word pieces. The piece identifiers are + returned. If no piece could be found for a suffix, the special + piece identifier `-1` is used. + + token (str): The token to encode as pieces. + RETURNS (Tuple[List[int], List[str]]): Piece identifiers and token pieces. + """ + token_ids = [] + token_pieces = [] + prefix = "" + cdef PieceMatch match + is_initial = True + while token: + match = self._find_longest_prefix(token, is_initial) + if not match.found: + token_ids.append(-1) + token_pieces.append(None) + return token_ids, token_pieces + token_ids.append(match.piece_id) + token_pieces.append(f"{prefix}{token[:match.prefix_len]}") + token = token[match.prefix_len:] + is_initial = False + prefix = "##" + return token_ids, token_pieces + + def decode(self, pieces: Iterable[int]) -> str: + """ + Decode token piece identifiers into string. Raises a `RuntimeError` + if any of the identifiers are invalid. + + ids (Iterable[int]): Piece IDs. + RETURNS (str): Decoded string. + """ + token_pieces = [self.id_to_piece(id)[0] for id in pieces] + return "".join(token_pieces) + + def get_initial(self, piece: str) -> int: + """ + Returns the ID for the given initial piece. Raises a `RuntimeError` if + the string isn't an initial piece. + + piece (str): Initial piece string. + RETURNS (int): Piece ID. + """ + return self._pieces.piece_to_id(Piece(piece.encode('utf8'), True)) + + def id_to_piece(self, piece: int) -> Tuple[str, bool]: + """ + Returns the piece string (without any prefix) for a given piece identifier + and a boolean identifying if it is an initial piece. Raises a `RuntimeError` if + any of the identifiers are invalid. + + piece (int): Piece ID. + RETURNS (Tuple[str, bool]): Piece string and a boolean identifying if + it is an initial piece. + """ + cdef const Piece* ptr_piece = &self._pieces.id_to_piece(piece) + return (ptr_piece[0].piece.decode('utf8'), ptr_piece[0].is_initial) + + def is_valid_piece_id(self, piece: int) -> bool: + """ + Returns True if the piece identifier is valid, False otherwise. + + piece (int): Piece ID. + RETURNS (bool): Is valid. + """ + return 0 <= piece <= self._pieces.size() - 1 + + @staticmethod + def from_file(filename: str) -> WordPieceProcessor: + with open(filename, encoding="utf8") as f: + pieces = [line.strip() for line in f] + return WordPieceProcessor(pieces) + + def to_list(self): + pieces = [None] * self._pieces.size() + cdef Piece piece + for i in range(self._pieces.size()): + piece = self._pieces._id_to_piece[i] + if piece.is_initial: + pieces[i] = piece.piece.decode('utf8') + else: + pieces[i] = f"##{piece.piece.decode('utf8')}" + + return pieces + + cdef PieceMatch _find_longest_prefix(self, str token, bint is_initial): + cdef PieceMatch match + match.found = False + + cdef Piece piece + for prefix_len in reversed(range(len(token) + 1)): + piece = Piece(token[:prefix_len].encode("utf8"), is_initial) + idx = self._pieces.try_piece_to_id(piece) + if idx != -1: + match.found = True + match.prefix_len = prefix_len + match.piece_id = idx + return match + + return match + + def __reduce__(self): + return (unpickle_wordpiece_processor, (self.to_list(),)) + +def unpickle_wordpiece_processor(pieces: List[str]) -> WordPieceProcessor: + return WordPieceProcessor(pieces) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/config.h b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/config.h new file mode 100644 index 0000000000000000000000000000000000000000..bac41193cc7ecd57f551e97b7938f78d8405836c --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/config.h @@ -0,0 +1,9 @@ +#ifndef CONFIG_H_ +#define CONFIG_H_ + +#define VERSION "0.1.96" +#define PACKAGE "sentencepiece" +#define PACKAGE_STRING "sentencepiece" + + +#endif // CONFIG_H_ diff --git a/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/merges.cc b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/merges.cc new file mode 100644 index 0000000000000000000000000000000000000000..b6669bd81bc490db0c541f609e7fc3e5f44f89a6 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/merges.cc @@ -0,0 +1,75 @@ +#include +#include +#include +#include + +#include "merges.hh" + +Merges::Merges(std::vector const &merges) { + for (size_t i = 0; i < merges.size(); i++) { + _merges[merges[i]] = i; + } +} + +std::vector Merges::apply_merges(std::vector pieces) const { + // This function could be optimized more, e.g.: + // + // * Use an LRU cache for frequent inputs. + // * Keep a priority queue of merges rather than reconstucting + // a pair list each iteration. + // + // But let's see if performance is actually an issue in practice. + + while (pieces.size() != 1) { + auto best_pair = find_best_pair(pieces); + if (best_pair.first.empty() && best_pair.second.empty()) { + break; + } + + std::vector new_pieces; + for (size_t i = 0; i < pieces.size();) { + if (i < pieces.size() - 1 && pieces[i] == best_pair.first && pieces[i+1] == best_pair.second) { + // Merge + new_pieces.emplace_back(pieces[i] + pieces[i + 1]); + i += 2; + } else { + // Copy + new_pieces.emplace_back(pieces[i]); + ++i; + } + + } + + pieces = new_pieces; + } + + return pieces; +} + +string_pair Merges::find_best_pair(std::vector const &pieces) const { + string_pair best_pair; + size_t best_rank = _merges.size(); + for (size_t i = 0; i < pieces.size() - 1; ++i) { + auto cur_pair = std::make_pair(pieces[i], pieces[i + 1]); + auto iter = _merges.find(cur_pair); + if (iter == _merges.end()) { + continue; + } + + if (iter->second < best_rank) { + best_pair = cur_pair; + best_rank = iter->second; + } + } + + return best_pair; +} + +std::vector> Merges::merges() const { + std::vector> merges(_merges.size()); + for (auto const &merge: _merges) { + merges[merge.second] = merge.first; + } + + return merges; +} \ No newline at end of file diff --git a/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/merges.hh b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/merges.hh new file mode 100644 index 0000000000000000000000000000000000000000..fa77a7f1e74ddf29149732de74ea544789fe7bd5 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/merges.hh @@ -0,0 +1,44 @@ +#pragma once + +#include +#include +#include +#include + +#include "util.hh" + +typedef std::pair string_pair; + +struct PairHash { + template + size_t operator()(std::pair const &pair) const { + size_t seed = 0; + hash_combine(seed, pair.first); + hash_combine(seed, pair.second); + return seed; + } +}; + +class Merges { +public: + Merges(std::vector const &merges); + + /** + * Apply merges to the given an initial set of pieces (usually string + * representations of bytes). + * + * @param pieces The pieces to merge + * @return std::vector Pieces after applying merges. + */ + std::vector apply_merges(std::vector pieces) const; + + /** + * Get all merges used by the BBPE instance. + * + * @return std::vector> + */ + std::vector> merges() const; +private: + string_pair find_best_pair(std::vector const &pieces) const; + std::unordered_map _merges; +}; \ No newline at end of file diff --git a/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/py.typed b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/util.hh b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/util.hh new file mode 100644 index 0000000000000000000000000000000000000000..08d9c0d05f2cb0f2d08b293fa742145d94eca227 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/util.hh @@ -0,0 +1,13 @@ +#pragma once + +#include + +// Hash combine function from Boost, see +// https://www.boost.org/doc/libs/1_55_0/doc/html/hash/combine.html +// for usage information. +template +inline void hash_combine(std::size_t& seed, const T& v) +{ + std::hash hasher; + seed ^= hasher(v) + 0x9e3779b9 + (seed<<6) + (seed>>2); +} diff --git a/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/wordpiece.cc b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/wordpiece.cc new file mode 100644 index 0000000000000000000000000000000000000000..0753c13ffdc6ff4fee863c04a1baf7fa5a4b18bb --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/wordpiece.cc @@ -0,0 +1,38 @@ +#include + +#include "wordpiece.hh" + +void PieceStorage::add_piece(const std::string &piece, const bool is_initial) { + _id_to_piece.emplace_back(piece, is_initial); + _piece_to_id.emplace(std::move(Piece(piece, is_initial)), _id_to_piece.size() - 1); +} + +size_t PieceStorage::size() const { + return _id_to_piece.size(); +} + +const Piece &PieceStorage::id_to_piece(const int id) const { + if (id < 0 || id >= size()) { + throw std::runtime_error("invalid piece ID '" + std::to_string(id) + "'"); + } + + return _id_to_piece[id]; +} + +size_t PieceStorage::piece_to_id(const Piece &piece) const { + const auto idx = _piece_to_id.find(piece); + if (idx != _piece_to_id.cend()) { + return idx->second; + } else { + throw std::runtime_error("unknown piece '(" + piece.piece + ", " + std::to_string(piece.is_initial) + ")'"); + } +} + +int PieceStorage::try_piece_to_id(const Piece &piece) const { + const auto idx = _piece_to_id.find(piece); + if (idx != _piece_to_id.cend()) { + return idx->second; + } else { + return -1; + } +} \ No newline at end of file diff --git a/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/wordpiece.hh b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/wordpiece.hh new file mode 100644 index 0000000000000000000000000000000000000000..c3fe13386e98903297792990bb33369582b78efc --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers/wordpiece.hh @@ -0,0 +1,41 @@ +#pragma once + +#include +#include +#include + +#include "util.hh" + +struct Piece { + std::string piece; + bool is_initial; + + Piece() + : piece(), is_initial(false) {} + Piece(const std::string &piece, bool initial) + : piece(piece), is_initial(initial) {} + + bool operator==(const Piece &rhs) const { + return piece == rhs.piece && is_initial == rhs.is_initial; + } +}; + +struct PieceHash { + size_t operator()(const Piece &piece) const { + size_t seed = 0; + hash_combine(seed, piece.piece); + hash_combine(seed, piece.is_initial); + return seed; + } +}; + +struct PieceStorage { + std::vector _id_to_piece; + std::unordered_map _piece_to_id; + + void add_piece(const std::string &piece, const bool is_initial); + size_t size() const; + const Piece &id_to_piece(const int id) const; + size_t piece_to_id(const Piece &piece) const; + int try_piece_to_id(const Piece &piece) const; +}; \ No newline at end of file diff --git a/TTS/Kokoro/.venv/Lib/site-packages/curated_transformers-0.1.1.dist-info/INSTALLER b/TTS/Kokoro/.venv/Lib/site-packages/curated_transformers-0.1.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/curated_transformers-0.1.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/TTS/Kokoro/.venv/Lib/site-packages/curated_transformers-0.1.1.dist-info/LICENSE b/TTS/Kokoro/.venv/Lib/site-packages/curated_transformers-0.1.1.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..343b5417ecc47d5de2e3905a88765c0e9a0228f8 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/curated_transformers-0.1.1.dist-info/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (C) 2021-2023 ExplosionAI GmbH + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/TTS/Kokoro/.venv/Lib/site-packages/curated_transformers-0.1.1.dist-info/METADATA b/TTS/Kokoro/.venv/Lib/site-packages/curated_transformers-0.1.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..39cdcddcc0f3b7a8191b2d82daa24f1648f58a68 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/curated_transformers-0.1.1.dist-info/METADATA @@ -0,0 +1,39 @@ +Metadata-Version: 2.1 +Name: curated-transformers +Version: 0.1.1 +Summary: Curated transformer models +Home-page: https://github.com/explosion/curated-transformers +Author: Explosion +Author-email: contact@explosion.ai +License: MIT +Requires-Python: >=3.6 +Description-Content-Type: text/markdown +License-File: LICENSE +Requires-Dist: torch (>=1.12.0) + +# 🤖 Curated transformers + +This Python package provides a curated set of PyTorch transformer models, +composed of reusable modules. Curated transformers currently supports the +following model types: + +- ALBERT +- BERT +- CamemBERT +- RoBERTa +- XLM-RoBERTa + +spaCy integration for curated transformers is provided by the +[`spacy-curated-transformers`](https://github.com/explosion/spacy-curated-transformers) +package. + +## ⚠️ Warning: experimental package + +This package is experimental and it is possible that models and APIs will +change in incompatible ways. + +## ⏳ Install + +```bash +pip install curated-transformers +``` diff --git a/TTS/Kokoro/.venv/Lib/site-packages/curated_transformers-0.1.1.dist-info/RECORD b/TTS/Kokoro/.venv/Lib/site-packages/curated_transformers-0.1.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..9e4373042c31791b26aa4ed3ad0475472addb274 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/curated_transformers-0.1.1.dist-info/RECORD @@ -0,0 +1,77 @@ +curated_transformers-0.1.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +curated_transformers-0.1.1.dist-info/LICENSE,sha256=5PJDH0A-oNINEIu-HwYVpMo7a3ZeLbr66TkI05htFTo,1088 +curated_transformers-0.1.1.dist-info/METADATA,sha256=aQ9pNu3KfMHrxPMngUb9RJSdNzHu6BBAxmQnVHmpjLc,965 +curated_transformers-0.1.1.dist-info/RECORD,, +curated_transformers-0.1.1.dist-info/WHEEL,sha256=a-zpFRIJzOq5QfuhBzbhiA1eHTzNCJn8OdRvhdNX0Rk,110 +curated_transformers-0.1.1.dist-info/top_level.txt,sha256=sGuZUwZG6Rjvmz4vhQ-Sauoxe0TFK6IGavqan9vjTdk,21 +curated_transformers-0.1.1.dist-info/zip-safe,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1 +curated_transformers/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +curated_transformers/__pycache__/__init__.cpython-312.pyc,, +curated_transformers/__pycache__/_compat.cpython-312.pyc,, +curated_transformers/__pycache__/errors.cpython-312.pyc,, +curated_transformers/_compat.py,sha256=ekfQMGP05EAR_wT1QpIJQ6HmSk5jBjQN9vUy7Ieg9ps,313 +curated_transformers/errors.py,sha256=8MExwH2wzlxOyxLNKJMBfABGE4hK7fX4DWI9ghP0Hg0,4688 +curated_transformers/models/__init__.py,sha256=T3IhjJ4XoCqYnDc08RR8NzT_rotcPgAnRAc3ObDfqlU,194 +curated_transformers/models/__pycache__/__init__.cpython-312.pyc,, +curated_transformers/models/__pycache__/activations.cpython-312.pyc,, +curated_transformers/models/__pycache__/attention.cpython-312.pyc,, +curated_transformers/models/__pycache__/curated_transformer.cpython-312.pyc,, +curated_transformers/models/__pycache__/embeddings.cpython-312.pyc,, +curated_transformers/models/__pycache__/hf_util.cpython-312.pyc,, +curated_transformers/models/__pycache__/output.cpython-312.pyc,, +curated_transformers/models/__pycache__/scalar_weight.cpython-312.pyc,, +curated_transformers/models/activations.py,sha256=LRYI8yQx_pVIuR0LTDqpV-gWy4xnbKsH8PYQy81Vrgc,583 +curated_transformers/models/albert/__init__.py,sha256=hdMqimj5KduWdlCIRPS5ou-rMTYGWs47BPiKdKDKeRw,105 +curated_transformers/models/albert/__pycache__/__init__.cpython-312.pyc,, +curated_transformers/models/albert/__pycache__/config.cpython-312.pyc,, +curated_transformers/models/albert/__pycache__/encoder.cpython-312.pyc,, +curated_transformers/models/albert/__pycache__/layer_group.cpython-312.pyc,, +curated_transformers/models/albert/config.py,sha256=_twv3E4OzJwngRhIUcJyDuq3UXbbSEcjDCV8HJproI8,2251 +curated_transformers/models/albert/encoder.py,sha256=YMDhCoBoxPnMx_Y2_MG_99Ub03I-8zdblB-x859N20w,2362 +curated_transformers/models/albert/layer_group.py,sha256=khBTW4YITZZJISEVchwSp-wKdcYKoYytNelWzeIB6CM,949 +curated_transformers/models/attention.py,sha256=WLAKwpJyeCGJjXth7IS4iXP8Ml2QNzr1q2Dwy6XCL14,2258 +curated_transformers/models/bert/__init__.py,sha256=9RaAyyLpbnKkZQprIKIwHMfo7tgA7WKlWsDBEHXQD-s,183 +curated_transformers/models/bert/__pycache__/__init__.cpython-312.pyc,, +curated_transformers/models/bert/__pycache__/config.cpython-312.pyc,, +curated_transformers/models/bert/__pycache__/embeddings.cpython-312.pyc,, +curated_transformers/models/bert/__pycache__/encoder.cpython-312.pyc,, +curated_transformers/models/bert/__pycache__/layer.cpython-312.pyc,, +curated_transformers/models/bert/config.py,sha256=gwUOI1RRcoLHsZ4wDGGtX5VCfJfHxGdvAQZDlPjci8c,3795 +curated_transformers/models/bert/embeddings.py,sha256=SBrisTMfhoNuzf-GCjTScinLWkJ_ifhu0--u3VDhnYo,2624 +curated_transformers/models/bert/encoder.py,sha256=XCuEfGV1bYheWgZrllD8Pva2160kZtNFF5zxWuHIvbk,1738 +curated_transformers/models/bert/layer.py,sha256=N8vUlDnG7hzA1WTFfpFajpAQEssUAJ13shXDnpTYkyc,4774 +curated_transformers/models/curated_transformer.py,sha256=o2EUfW-EgywhSXEC3bPz4x7qxRzg9p6azQw6_Tc_B4k,1239 +curated_transformers/models/embeddings.py,sha256=-n8UTSChlhkNlWAMXrE3CWEuEwrXrHnc0mhexDhvzNM,891 +curated_transformers/models/hf_util.py,sha256=bFjzOd6jvv0IiZRzkm1c2GDAnlYg04kPonjXjguhSpg,10980 +curated_transformers/models/output.py,sha256=P3W9Kd_T7xpPuuOJD-5WdrYomHSevIBC_trWycopFDU,1556 +curated_transformers/models/roberta/__init__.py,sha256=1PfYJM9u-bVnBjYTj-jtCyTnNQ0Sq4rlBxi-pk57Rxk,70 +curated_transformers/models/roberta/__pycache__/__init__.cpython-312.pyc,, +curated_transformers/models/roberta/__pycache__/config.cpython-312.pyc,, +curated_transformers/models/roberta/__pycache__/embeddings.cpython-312.pyc,, +curated_transformers/models/roberta/__pycache__/encoder.cpython-312.pyc,, +curated_transformers/models/roberta/config.py,sha256=mnYZM9iTAyvZ7WtwP6QrEjv-dwY5OQp9puHLWW9W5cw,641 +curated_transformers/models/roberta/embeddings.py,sha256=jCXsfcN6iuzLsjzF7H_VV71qNO0DGXQsP1fKnBkBUDw,1392 +curated_transformers/models/roberta/encoder.py,sha256=Tbw5lHEqisgvVd3hsyqcxZR5N0bGDZqm-S9ZA5WKzIc,1780 +curated_transformers/models/scalar_weight.py,sha256=TG79croea-gVUidHurasuREFaKFiaFE9_YP3eM6XmJM,1881 +curated_transformers/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +curated_transformers/tests/__pycache__/__init__.cpython-312.pyc,, +curated_transformers/tests/__pycache__/conftest.cpython-312.pyc,, +curated_transformers/tests/__pycache__/enable_gpu.cpython-312.pyc,, +curated_transformers/tests/__pycache__/util.cpython-312.pyc,, +curated_transformers/tests/conftest.py,sha256=37PMzX_CNEzkmeG2fL5EfeDyI1Bdkc_43Kz-fg_J4lM,1254 +curated_transformers/tests/enable_gpu.py,sha256=uvDfkkk3z7Texr1t2zWSKyC2bMz0YpRxAXf7ufTasYQ,94 +curated_transformers/tests/models/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +curated_transformers/tests/models/__pycache__/__init__.cpython-312.pyc,, +curated_transformers/tests/models/__pycache__/test_hf_model.cpython-312.pyc,, +curated_transformers/tests/models/__pycache__/test_torchscript.cpython-312.pyc,, +curated_transformers/tests/models/albert/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +curated_transformers/tests/models/albert/__pycache__/__init__.cpython-312.pyc,, +curated_transformers/tests/models/albert/__pycache__/test_encoder.cpython-312.pyc,, +curated_transformers/tests/models/albert/test_encoder.py,sha256=6bBURi9U8LmcPoJUyyJkAmf-00PFMqOiQ06vEEd2xBo,280 +curated_transformers/tests/models/test_hf_model.py,sha256=56l1uRI2d7HU4JOnD878yUxIT5gUw9qDfySCWDyQSrc,2969 +curated_transformers/tests/models/test_torchscript.py,sha256=KU_pmK3YVMoVPqAURodx-9ENaQ3SOc6d1N98f9Q29FU,1441 +curated_transformers/tests/tokenization/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +curated_transformers/tests/tokenization/__pycache__/__init__.cpython-312.pyc,, +curated_transformers/tests/util.py,sha256=ZteHt8Ig15PMiG3c8Y6uGAaY9ekxoiD-VImR8DZ4qdM,482 +curated_transformers/tokenization/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +curated_transformers/tokenization/__pycache__/__init__.cpython-312.pyc,, diff --git a/TTS/Kokoro/.venv/Lib/site-packages/curated_transformers-0.1.1.dist-info/WHEEL b/TTS/Kokoro/.venv/Lib/site-packages/curated_transformers-0.1.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..f771c29b873190987cd5295252cd7430a9c28d71 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/curated_transformers-0.1.1.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.40.0) +Root-Is-Purelib: true +Tag: py2-none-any +Tag: py3-none-any + diff --git a/TTS/Kokoro/.venv/Lib/site-packages/curated_transformers-0.1.1.dist-info/top_level.txt b/TTS/Kokoro/.venv/Lib/site-packages/curated_transformers-0.1.1.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..66c9348d196d314022e6c15bc02ace20dc3eac1d --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/curated_transformers-0.1.1.dist-info/top_level.txt @@ -0,0 +1 @@ +curated_transformers diff --git a/TTS/Kokoro/.venv/Lib/site-packages/curated_transformers-0.1.1.dist-info/zip-safe b/TTS/Kokoro/.venv/Lib/site-packages/curated_transformers-0.1.1.dist-info/zip-safe new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/curated_transformers-0.1.1.dist-info/zip-safe @@ -0,0 +1 @@ + diff --git a/TTS/Kokoro/.venv/Lib/site-packages/curated_transformers/__init__.py b/TTS/Kokoro/.venv/Lib/site-packages/curated_transformers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/TTS/Kokoro/.venv/Lib/site-packages/curated_transformers/_compat.py b/TTS/Kokoro/.venv/Lib/site-packages/curated_transformers/_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..e8d8070d3ff593098cfdd960e3badd331172e513 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/curated_transformers/_compat.py @@ -0,0 +1,15 @@ +try: + import transformers + + has_hf_transformers = True +except ImportError: + transformers = None # type: ignore + has_hf_transformers = False + +try: + import huggingface_hub + + has_huggingface_hub = True +except ImportError: + huggingface_hub = None # type: ignore + has_huggingface_hub = False diff --git a/TTS/Kokoro/.venv/Lib/site-packages/curated_transformers/errors.py b/TTS/Kokoro/.venv/Lib/site-packages/curated_transformers/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..f0a2ea67808a2162a92a64fd8b3373d69c4498bb --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/curated_transformers/errors.py @@ -0,0 +1,76 @@ +class ErrorsWithCodes(type): + def __getattribute__(self, code): + msg = super().__getattribute__(code) + if code.startswith("__"): # python system attributes like __class__ + return msg + else: + return "(curated-transformers) [{code}] {msg}".format(code=code, msg=msg) + + +# fmt: off + +class Warnings(metaclass=ErrorsWithCodes): + W001 = ("Skipping transfomer pipe with TorchScript model - Model " + "is likely already quantized") + + +class Errors(metaclass=ErrorsWithCodes): + E001 = ("Attempting to quantize a transformer pipe with a " + "non-PyTorch model ('{model_name}'). Quantization " + "is only supported by PyTorch-specific curated " + "transformer models") + E002 = ("The number of hidden layers ({num_hidden_layers}) in the " + "ALBERT encoder must be divisable by number of hidden groups " + "({num_hidden_groups})") + E003 = ("The hidden width of the transformer ({hidden_width}) must be " + "divisible by the number of self-attention heads ({num_heads})") + E004 = ("The point-wise feed-forward network in the transformer only " + "supports the following activation functions: {activation_funcs}") + E007 = ("Attempting to load the weights of an unsupported Hugging " + "Face `transformers` model ({unsupported_model}). Currently " + "supported models: {supported_models}") + E008 = ("The number of layers in the scalar weighting listener model ({num_layers_scalar_weight})" + "needs to be the same as the number of hidden layers in the " + "transformer ({num_layers_transformer}). You can use the config's " + "interpolation functionality to link the former's `num_layers` " + "parameter with the latter") + E009 = ("At least one sequence in the transformer's input has a length " + "of {seq_len}, which is larger than the model's maximum sequence " + "length of {max_seq_len} tokens") + E010 = ("Curated transformers do not currently support listener replacement") + E011 = ("`{loader_name}` requires the Hugging Face `transformers` package to be installed") + E012 = ("`{listener_name}` requires the upstream transformer pipe to output " + "all hidden layer outputs. This can be enabled by setting the pipe's " + "`all_layer_outputs` parameter to `True` in the pipeline config") + E013 = ("The target pipe names for gradual transformer unfreezing contain both the " + "wild-card operator ('*') and individual names. Use either of the two but not both") + E014 = ("Model '{model_name}' received an unexpected input of type '{input_type}'. " + "It can only wrap/be chained with models whose outputs are of type " + "`TransformerModelOutput` (in almost all cases, models of type `TorchTransformerModelT`)") + E015 = ("Input passed to the `ScalarWeight` model do not have the same number " + "layers. Distinct layer counts: {layer_counts}") + E016 = ("Input passed to the `ScalarWeight` model do not have the same width. " + "Distinct widths: {hidden_widths}") + E017 = ("Span extractor stride ({stride}) must be within [window_size / 2, " + "window_size] ([{half_window_size}, {window_size}])") + E018 = ("Span extractor batch size must be greater than zero") + E019 = ("Byte-BPE piece encoder vocabulary doesn't contain '{piece}' piece") + E020 = ("Character piece encoder vocabulary is not available. Use a loader " + "to initialize the encoder.") + E021 = ("Attempting to use the `CharEncoderLoader` piece encoder loader with an " + "incompatible model ('{model_name}'). It can only be used with the " + "`CharEncoder` piece encoder") + E022 = ("Attempting to load an unsupported Hugging Face tokenizer " + "({unsupported_tokenizer}). Currently supported tokenizers: " + "{supported_tokenizers}") + E023 = ("Japanese BERT models currently only support character subword encoding") + E024 = ("Attempting to initialize an incompatible piece encoder ('{model_name}') " + "with the Hugging Face Japanese BERT tokenizer. It can only be used with the " + "`CharEncoder` piece encoder") + E025 = ("Attempting to perform gradual unfreezing of a non-transformer pipe " + "('{pipe_name}'}. Only transformer pipes support this feature") + E026 = ("Attempting to load the weights of a Hugging Face `transformers` model " + "into an unsupported curated encoder ({unsupported_encoder}). Currently " + "supported encoders: {supported_encoders}") + +# fmt: on diff --git a/TTS/Kokoro/.venv/Lib/site-packages/cymem-2.0.13.dist-info/INSTALLER b/TTS/Kokoro/.venv/Lib/site-packages/cymem-2.0.13.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/cymem-2.0.13.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/TTS/Kokoro/.venv/Lib/site-packages/cymem-2.0.13.dist-info/METADATA b/TTS/Kokoro/.venv/Lib/site-packages/cymem-2.0.13.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..b8db3b19af055819284e1ffbad430f16d6727a83 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/cymem-2.0.13.dist-info/METADATA @@ -0,0 +1,260 @@ +Metadata-Version: 2.4 +Name: cymem +Version: 2.0.13 +Summary: Manage calls to calloc/free through Cython +Home-page: https://github.com/explosion/cymem +Author: Matthew Honnibal +Author-email: matt@explosion.ai +License: MIT +Classifier: Environment :: Console +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Science/Research +Classifier: License :: OSI Approved :: MIT License +Classifier: Operating System :: POSIX :: Linux +Classifier: Operating System :: MacOS :: MacOS X +Classifier: Operating System :: Microsoft :: Windows +Classifier: Programming Language :: Cython +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: Free Threading :: 2 - Beta +Classifier: Topic :: Scientific/Engineering +Requires-Python: >=3.9,<3.15 +Description-Content-Type: text/markdown +License-File: LICENSE +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: description-content-type +Dynamic: home-page +Dynamic: license +Dynamic: license-file +Dynamic: requires-python +Dynamic: summary + + + +# cymem: A Cython Memory Helper + +cymem provides two small memory-management helpers for Cython. They make it easy +to tie memory to a Python object's life-cycle, so that the memory is freed when +the object is garbage collected. + +[![tests](https://github.com/explosion/cymem/actions/workflows/tests.yml/badge.svg)](https://github.com/explosion/cymem/actions/workflows/tests.yml) +[![pypi Version](https://img.shields.io/pypi/v/cymem.svg?style=flat-square&logo=pypi&logoColor=white)](https://pypi.python.org/pypi/cymem) +[![conda Version](https://img.shields.io/conda/vn/conda-forge/cymem.svg?style=flat-square&logo=conda-forge&logoColor=white)](https://anaconda.org/conda-forge/cymem) +[![Python wheels](https://img.shields.io/badge/wheels-%E2%9C%93-4c1.svg?longCache=true&style=flat-square&logo=python&logoColor=white)](https://github.com/explosion/wheelwright/releases) + +## Overview + +The most useful is `cymem.Pool`, which acts as a thin wrapper around the calloc +function: + +```python +from cymem.cymem cimport Pool +cdef Pool mem = Pool() +data1 = mem.alloc(10, sizeof(int)) +data2 = mem.alloc(12, sizeof(float)) +``` + +The `Pool` object saves the memory addresses internally, and frees them when the +object is garbage collected. Typically you'll attach the `Pool` to some cdef'd +class. This is particularly handy for deeply nested structs, which have +complicated initialization functions. Just pass the `Pool` object into the +initializer, and you don't have to worry about freeing your struct at all — all +of the calls to `Pool.alloc` will be automatically freed when the `Pool` +expires. + +## Installation + +Installation is via [pip](https://pypi.python.org/pypi/pip), and requires +[Cython](http://cython.org). Before installing, make sure that your `pip`, +`setuptools` and `wheel` are up to date. + +```bash +pip install -U pip setuptools wheel +pip install cymem +``` + +## Example Use Case: An array of structs + +Let's say we want a sequence of sparse matrices. We need fast access, and a +Python list isn't performing well enough. So, we want a C-array or C++ vector, +which means we need the sparse matrix to be a C-level struct — it can't be a +Python class. We can write this easily enough in Cython: + +```python +"""Example without Cymem + +To use an array of structs, we must carefully walk the data structure when +we deallocate it. +""" + +from libc.stdlib cimport calloc, free + +cdef struct SparseRow: + size_t length + size_t* indices + double* values + +cdef struct SparseMatrix: + size_t length + SparseRow* rows + +cdef class MatrixArray: + cdef size_t length + cdef SparseMatrix** matrices + + def __cinit__(self, list py_matrices): + self.length = 0 + self.matrices = NULL + + def __init__(self, list py_matrices): + self.length = len(py_matrices) + self.matrices = calloc(len(py_matrices), sizeof(SparseMatrix*)) + + for i, py_matrix in enumerate(py_matrices): + self.matrices[i] = sparse_matrix_init(py_matrix) + + def __dealloc__(self): + for i in range(self.length): + sparse_matrix_free(self.matrices[i]) + free(self.matrices) + + +cdef SparseMatrix* sparse_matrix_init(list py_matrix) except NULL: + sm = calloc(1, sizeof(SparseMatrix)) + sm.length = len(py_matrix) + sm.rows = calloc(sm.length, sizeof(SparseRow)) + cdef size_t i, j + cdef dict py_row + cdef size_t idx + cdef double value + for i, py_row in enumerate(py_matrix): + sm.rows[i].length = len(py_row) + sm.rows[i].indices = calloc(sm.rows[i].length, sizeof(size_t)) + sm.rows[i].values = calloc(sm.rows[i].length, sizeof(double)) + for j, (idx, value) in enumerate(py_row.items()): + sm.rows[i].indices[j] = idx + sm.rows[i].values[j] = value + return sm + + +cdef void* sparse_matrix_free(SparseMatrix* sm) except *: + cdef size_t i + for i in range(sm.length): + free(sm.rows[i].indices) + free(sm.rows[i].values) + free(sm.rows) + free(sm) +``` + +We wrap the data structure in a Python ref-counted class at as low a level as we +can, given our performance constraints. This allows us to allocate and free the +memory in the `__cinit__` and `__dealloc__` Cython special methods. + +However, it's very easy to make mistakes when writing the `__dealloc__` and +`sparse_matrix_free` functions, leading to memory leaks. cymem prevents you from +writing these deallocators at all. Instead, you write as follows: + +```python +"""Example with Cymem. + +Memory allocation is hidden behind the Pool class, which remembers the +addresses it gives out. When the Pool object is garbage collected, all of +its addresses are freed. + +We don't need to write MatrixArray.__dealloc__ or sparse_matrix_free, +eliminating a common class of bugs. +""" +from cymem.cymem cimport Pool + +cdef struct SparseRow: + size_t length + size_t* indices + double* values + +cdef struct SparseMatrix: + size_t length + SparseRow* rows + + +cdef class MatrixArray: + cdef size_t length + cdef SparseMatrix** matrices + cdef Pool mem + + def __cinit__(self, list py_matrices): + self.mem = None + self.length = 0 + self.matrices = NULL + + def __init__(self, list py_matrices): + self.mem = Pool() + self.length = len(py_matrices) + self.matrices = self.mem.alloc(self.length, sizeof(SparseMatrix*)) + for i, py_matrix in enumerate(py_matrices): + self.matrices[i] = sparse_matrix_init(self.mem, py_matrix) + +cdef SparseMatrix* sparse_matrix_init_cymem(Pool mem, list py_matrix) except NULL: + sm = mem.alloc(1, sizeof(SparseMatrix)) + sm.length = len(py_matrix) + sm.rows = mem.alloc(sm.length, sizeof(SparseRow)) + cdef size_t i, j + cdef dict py_row + cdef size_t idx + cdef double value + for i, py_row in enumerate(py_matrix): + sm.rows[i].length = len(py_row) + sm.rows[i].indices = mem.alloc(sm.rows[i].length, sizeof(size_t)) + sm.rows[i].values = mem.alloc(sm.rows[i].length, sizeof(double)) + for j, (idx, value) in enumerate(py_row.items()): + sm.rows[i].indices[j] = idx + sm.rows[i].values[j] = value + return sm +``` + +All that the `Pool` class does is remember the addresses it gives out. When the +`MatrixArray` object is garbage-collected, the `Pool` object will also be +garbage collected, which triggers a call to `Pool.__dealloc__`. The `Pool` then +frees all of its addresses. This saves you from walking back over your nested +data structures to free them, eliminating a common class of errors. + +## Custom Allocators + +Sometimes external C libraries use private functions to allocate and free +objects, but we'd still like the laziness of the `Pool`. + +```python +from cymem.cymem cimport Pool, WrapMalloc, WrapFree +cdef Pool mem = Pool(WrapMalloc(priv_malloc), WrapFree(priv_free)) +``` + +## Thread Safety + +As of version 2.0.12, `cymem.Pool` is thread-safe when used with CPython 3.13+ +free-threaded builds (PEP 703). All operations on the Pool, including `alloc()`, +`free()`, and `realloc()`, can be safely called from multiple threads concurrently. + +**Key guarantees:** +- Multiple threads can safely call `alloc()`, `free()`, and `realloc()` on the + same `Pool` instance. +- The Pool's internal bookkeeping (`addresses` dict and `size` accounting) is + protected from race conditions. Reading the internal state without + holding a lock on the `Pool` instance via a critical section is not + thread-safe. + +**Important notes:** +- Individual Pool instances are thread-safe, but you are still responsible for + proper synchronization when accessing the memory contents themselves. Note + that holding a lock on the Pool itself is typically not the right approach: + since malloc is thread-safe, memory allocated by separate calls to `alloc` + can be safely accessed concurrently without locking. You should only + synchronize access to specific memory regions that are being shared across + threads, using fine-grained locks appropriate to your use case rather than a + coarse-grained lock on the entire `Pool`. +- Custom memory allocators need to be thread-safe themselves. diff --git a/TTS/Kokoro/.venv/Lib/site-packages/cymem-2.0.13.dist-info/RECORD b/TTS/Kokoro/.venv/Lib/site-packages/cymem-2.0.13.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..2b366d7bcb0f2946ff222bf9344933d1b38933d0 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/cymem-2.0.13.dist-info/RECORD @@ -0,0 +1,18 @@ +cymem-2.0.13.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +cymem-2.0.13.dist-info/METADATA,sha256=2V2NyiDZgR48dhsHTY83VOsFRF_olqSPGaS_se0RkJU,9938 +cymem-2.0.13.dist-info/RECORD,, +cymem-2.0.13.dist-info/WHEEL,sha256=8UP9x9puWI0P1V_d7K2oMTBqfeLNm21CTzZ_Ptr0NXU,101 +cymem-2.0.13.dist-info/licenses/LICENSE,sha256=ieU_0BdR7bQeHJPUvhdfhgrXQkVdOS_WqJITVwzV4Sw,1132 +cymem-2.0.13.dist-info/top_level.txt,sha256=dCYwCFWTj_NE7Z9zFrrKqAcWuUCtg52zKRI4l_Wrr7Q,6 +cymem/__init__.pxd,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +cymem/__init__.py,sha256=5x1XCRB8b70rovUrFDvsWm5GT-SK5CaMfFdKZNep3UM,22 +cymem/__pycache__/__init__.cpython-312.pyc,, +cymem/__pycache__/about.cpython-312.pyc,, +cymem/about.py,sha256=ITCGkSaylYWYL3zNUNuWH2c1mNUivWA3PXpaVPmNmng,240 +cymem/cymem.cp312-win_amd64.pyd,sha256=HT3d3s4AD2OD7YrwFzGvGI0z4J--77oKokeGWv9j8VE,68608 +cymem/cymem.pxd,sha256=Y9nLCNoG6FjU7g5OIXPtxRzoaqhNFQmIU3X8Zpa4u8k,810 +cymem/cymem.pyx,sha256=G7lXe4Jy52shRuG_jlTimlmtLFyEYfzn2-3Iv54XP5s,7811 +cymem/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +cymem/tests/__pycache__/__init__.cpython-312.pyc,, +cymem/tests/__pycache__/test_import.cpython-312.pyc,, +cymem/tests/test_import.py,sha256=VTQa6tB9U_k1oIP6IQUMiwutvZXUU0G4CH3XtbeXn88,275 diff --git a/TTS/Kokoro/.venv/Lib/site-packages/cymem-2.0.13.dist-info/WHEEL b/TTS/Kokoro/.venv/Lib/site-packages/cymem-2.0.13.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..10ac2c23843796b65786bc9aba179a906c8bcc88 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/cymem-2.0.13.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: false +Tag: cp312-cp312-win_amd64 + diff --git a/TTS/Kokoro/.venv/Lib/site-packages/cymem-2.0.13.dist-info/top_level.txt b/TTS/Kokoro/.venv/Lib/site-packages/cymem-2.0.13.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..2fb2d5eb412737b88557fada185990cfc736c254 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/cymem-2.0.13.dist-info/top_level.txt @@ -0,0 +1 @@ +cymem diff --git a/TTS/Kokoro/.venv/Lib/site-packages/cymem/__init__.pxd b/TTS/Kokoro/.venv/Lib/site-packages/cymem/__init__.pxd new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/TTS/Kokoro/.venv/Lib/site-packages/cymem/__init__.py b/TTS/Kokoro/.venv/Lib/site-packages/cymem/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..13030b90f196c2af0864fd6d382be87a4fffd878 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/cymem/__init__.py @@ -0,0 +1 @@ +from .about import * diff --git a/TTS/Kokoro/.venv/Lib/site-packages/cymem/about.py b/TTS/Kokoro/.venv/Lib/site-packages/cymem/about.py new file mode 100644 index 0000000000000000000000000000000000000000..b45700b3d5596c6eebb842303e514760ff976cfe --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/cymem/about.py @@ -0,0 +1,7 @@ +__title__ = "cymem" +__version__ = "2.0.13" +__summary__ = "Manage calls to calloc/free through Cython" +__uri__ = "https://github.com/explosion/cymem" +__author__ = "Matthew Honnibal" +__email__ = "matt@explosion.ai" +__license__ = "MIT" diff --git a/TTS/Kokoro/.venv/Lib/site-packages/cymem/cymem.cp312-win_amd64.pyd b/TTS/Kokoro/.venv/Lib/site-packages/cymem/cymem.cp312-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..7380e1b279c4650c1cf070e8b42f4e1c63fab43f Binary files /dev/null and b/TTS/Kokoro/.venv/Lib/site-packages/cymem/cymem.cp312-win_amd64.pyd differ diff --git a/TTS/Kokoro/.venv/Lib/site-packages/cymem/cymem.pxd b/TTS/Kokoro/.venv/Lib/site-packages/cymem/cymem.pxd new file mode 100644 index 0000000000000000000000000000000000000000..e06e8be2b1e0ef58deeeb4d791d02289ec8c84aa --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/cymem/cymem.pxd @@ -0,0 +1,31 @@ +ctypedef void* (*malloc_t)(size_t n) +ctypedef void (*free_t)(void *p) + +cdef class PyMalloc: + cdef malloc_t malloc + cdef void _set(self, malloc_t malloc) + +cdef PyMalloc WrapMalloc(malloc_t malloc) + +cdef class PyFree: + cdef free_t free + cdef void _set(self, free_t free) + +cdef PyFree WrapFree(free_t free) + +cdef class Pool: + cdef readonly size_t size + cdef readonly dict addresses + cdef readonly list refs + cdef readonly PyMalloc pymalloc + cdef readonly PyFree pyfree + + cdef void* alloc(self, size_t number, size_t size) except NULL + cdef void free(self, void* addr) except * + cdef void* realloc(self, void* addr, size_t n) except NULL + + +cdef class Address: + cdef void* ptr + cdef readonly PyMalloc pymalloc + cdef readonly PyFree pyfree diff --git a/TTS/Kokoro/.venv/Lib/site-packages/cymem/cymem.pyx b/TTS/Kokoro/.venv/Lib/site-packages/cymem/cymem.pyx new file mode 100644 index 0000000000000000000000000000000000000000..a3cd60d0f3d88471cbb541a612bf3c6f4d3baa98 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/cymem/cymem.pyx @@ -0,0 +1,196 @@ +# cython: embedsignature=True, freethreading_compatible=True + +cimport cython +from cpython.mem cimport PyMem_Malloc, PyMem_Free +from libc.string cimport memset +from libc.string cimport memcpy +import warnings + +WARN_ZERO_ALLOC = False + +cdef class PyMalloc: + cdef void _set(self, malloc_t malloc): + self.malloc = malloc + +cdef PyMalloc WrapMalloc(malloc_t malloc): + cdef PyMalloc o = PyMalloc() + o._set(malloc) + return o + +cdef class PyFree: + cdef void _set(self, free_t free): + self.free = free + +cdef PyFree WrapFree(free_t free): + cdef PyFree o = PyFree() + o._set(free) + return o + +Default_Malloc = WrapMalloc(PyMem_Malloc) +Default_Free = WrapFree(PyMem_Free) + +cdef class Pool: + """Track allocated memory addresses, and free them all when the Pool is + garbage collected. This provides an easy way to avoid memory leaks, and + removes the need for deallocation functions for complicated structs. + + >>> from cymem.cymem cimport Pool + >>> cdef Pool mem = Pool() + >>> data1 = mem.alloc(10, sizeof(int)) + >>> data2 = mem.alloc(12, sizeof(float)) + + Attributes: + size (size_t): The current size (in bytes) allocated by the pool. + addresses (dict): The currently allocated addresses and their sizes. Read-only. + pymalloc (PyMalloc): The allocator to use (default uses PyMem_Malloc). + pyfree (PyFree): The free to use (default uses PyMem_Free). + + Thread-safety: + All public methods in this class can be safely called from multiple threads. + Testing the thread-safety of this class can be done by checking out the repository + at https://github.com/lysnikolaou/test-cymem-threadsafety and following the + instructions on the README. + """ + + def __cinit__(self, PyMalloc pymalloc=Default_Malloc, + PyFree pyfree=Default_Free): + # size, addresses and refs are mutable. note that operations on + # dicts and lists are atomic. + self.size = 0 + self.addresses = {} + self.refs = [] + + # pymalloc and pyfree are immutable. + self.pymalloc = pymalloc + self.pyfree = pyfree + + def __dealloc__(self): + # No need for locking here since the methods will be unreachable + # by the time __dealloc__ is called + cdef size_t addr + if self.addresses is not None: + for addr in self.addresses: + if addr != 0: + self.pyfree.free(addr) + + cdef void* alloc(self, size_t number, size_t elem_size) except NULL: + """Allocate a 0-initialized number*elem_size-byte block of memory, and + remember its address. The block will be freed when the Pool is garbage + collected. Throw warning when allocating zero-length size and + WARN_ZERO_ALLOC was set to True. + """ + if WARN_ZERO_ALLOC and (number == 0 or elem_size == 0): + warnings.warn("Allocating zero bytes") + cdef void* p = self.pymalloc.malloc(number * elem_size) + if p == NULL: + raise MemoryError("Error assigning %d bytes" % (number * elem_size)) + memset(p, 0, number * elem_size) + + # We need a critical section here so that addresses and size get + # updated atomically. If we were to acquire a critical section on self, + # mutating the dictionary would try to acquire a critical section on + # the dictionary and therefore release the critical section on self. + # Acquiring a critical section on self.addresses works because that's + # the only C API that gets called inside the block and acquiring the + # critical section on the top-most held lock does not release it. + with cython.critical_section(self.addresses): + self.addresses[p] = number * elem_size + self.size += number * elem_size + return p + + cdef void* realloc(self, void* p, size_t new_size) except NULL: + """Resizes the memory block pointed to by p to new_size bytes, returning + a non-NULL pointer to the new block. new_size must be larger than the + original. + + If p is not in the Pool or new_size isn't larger than the previous size, + a ValueError is raised. + """ + cdef size_t old_size + cdef void* new_ptr + + new_ptr = self.pymalloc.malloc(new_size) + if new_ptr == NULL: + raise MemoryError("Error reallocating to %d bytes" % new_size) + + # See comment in alloc on why we're acquiring a critical section on + # self.addresses instead of self. + with cython.critical_section(self.addresses): + try: + old_size = self.addresses.pop(p) + except KeyError: + self.pyfree.free(new_ptr) + raise ValueError("Pointer %d not found in Pool %s" % (p, self.addresses)) + + if old_size >= new_size: + self.addresses[p] = old_size + self.pyfree.free(new_ptr) + raise ValueError("Realloc requires new_size > previous size") + + memcpy(new_ptr, p, old_size) + memset( new_ptr + old_size, 0, new_size - old_size) + self.size += new_size - old_size + self.addresses[new_ptr] = new_size + + self.pyfree.free(p) + return new_ptr + + cdef void free(self, void* p) except *: + """Frees the memory block pointed to by p, which must have been returned + by a previous call to Pool.alloc. You don't necessarily need to free + memory addresses manually --- you can instead let the Pool be garbage + collected, at which point all the memory will be freed. + + If p is not in Pool.addresses, a KeyError is raised. + """ + cdef size_t size + + # See comment in alloc on why we're acquiring a critical section on + # self.addresses instead of self. + with cython.critical_section(self.addresses): + size = self.addresses.pop(p) + self.size -= size + self.pyfree.free(p) + + def own_pyref(self, object py_ref): + # Calling append here is atomic, no critical section needed. + self.refs.append(py_ref) + + +cdef class Address: + """A block of number * size-bytes of 0-initialized memory, tied to a Python + ref-counted object. When the object is garbage collected, the memory is freed. + + >>> from cymem.cymem cimport Address + >>> cdef Address address = Address(10, sizeof(double)) + >>> d10 = address.ptr + + Args: + number (size_t): The number of elements in the memory block. + elem_size (size_t): The size of each element. + + Attributes: + ptr (void*): Pointer to the memory block. + addr (size_t): Read-only size_t cast of the pointer. + pymalloc (PyMalloc): The allocator to use (default uses PyMem_Malloc). + pyfree (PyFree): The free to use (default uses PyMem_Free). + """ + def __cinit__(self, size_t number, size_t elem_size, + PyMalloc pymalloc=Default_Malloc, PyFree pyfree=Default_Free): + self.ptr = NULL + self.pymalloc = pymalloc + self.pyfree = pyfree + + def __init__(self, size_t number, size_t elem_size): + self.ptr = self.pymalloc.malloc(number * elem_size) + if self.ptr == NULL: + raise MemoryError("Error assigning %d bytes" % number * elem_size) + memset(self.ptr, 0, number * elem_size) + + @property + def addr(self): + return self.ptr + + def __dealloc__(self): + if self.ptr != NULL: + self.pyfree.free(self.ptr) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/dateutil/__init__.py b/TTS/Kokoro/.venv/Lib/site-packages/dateutil/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a2c19c06fe14476a9bfa4f1f60de7a997a41191c --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/dateutil/__init__.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- +import sys + +try: + from ._version import version as __version__ +except ImportError: + __version__ = 'unknown' + +__all__ = ['easter', 'parser', 'relativedelta', 'rrule', 'tz', + 'utils', 'zoneinfo'] + +def __getattr__(name): + import importlib + + if name in __all__: + return importlib.import_module("." + name, __name__) + raise AttributeError( + "module {!r} has not attribute {!r}".format(__name__, name) + ) + + +def __dir__(): + # __dir__ should include all the lazy-importable modules as well. + return [x for x in globals() if x not in sys.modules] + __all__ diff --git a/TTS/Kokoro/.venv/Lib/site-packages/dateutil/_common.py b/TTS/Kokoro/.venv/Lib/site-packages/dateutil/_common.py new file mode 100644 index 0000000000000000000000000000000000000000..4eb2659bd2986125fcfb4afea5bae9efc2dcd1a0 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/dateutil/_common.py @@ -0,0 +1,43 @@ +""" +Common code used in multiple modules. +""" + + +class weekday(object): + __slots__ = ["weekday", "n"] + + def __init__(self, weekday, n=None): + self.weekday = weekday + self.n = n + + def __call__(self, n): + if n == self.n: + return self + else: + return self.__class__(self.weekday, n) + + def __eq__(self, other): + try: + if self.weekday != other.weekday or self.n != other.n: + return False + except AttributeError: + return False + return True + + def __hash__(self): + return hash(( + self.weekday, + self.n, + )) + + def __ne__(self, other): + return not (self == other) + + def __repr__(self): + s = ("MO", "TU", "WE", "TH", "FR", "SA", "SU")[self.weekday] + if not self.n: + return s + else: + return "%s(%+d)" % (s, self.n) + +# vim:ts=4:sw=4:et diff --git a/TTS/Kokoro/.venv/Lib/site-packages/dateutil/_version.py b/TTS/Kokoro/.venv/Lib/site-packages/dateutil/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..ddda98098527a73348e694c2edb691fd625475fc --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/dateutil/_version.py @@ -0,0 +1,4 @@ +# file generated by setuptools_scm +# don't change, don't track in version control +__version__ = version = '2.9.0.post0' +__version_tuple__ = version_tuple = (2, 9, 0) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/dateutil/easter.py b/TTS/Kokoro/.venv/Lib/site-packages/dateutil/easter.py new file mode 100644 index 0000000000000000000000000000000000000000..f74d1f7442473997245ac683b8a269a3574d1ba4 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/dateutil/easter.py @@ -0,0 +1,89 @@ +# -*- coding: utf-8 -*- +""" +This module offers a generic Easter computing method for any given year, using +Western, Orthodox or Julian algorithms. +""" + +import datetime + +__all__ = ["easter", "EASTER_JULIAN", "EASTER_ORTHODOX", "EASTER_WESTERN"] + +EASTER_JULIAN = 1 +EASTER_ORTHODOX = 2 +EASTER_WESTERN = 3 + + +def easter(year, method=EASTER_WESTERN): + """ + This method was ported from the work done by GM Arts, + on top of the algorithm by Claus Tondering, which was + based in part on the algorithm of Ouding (1940), as + quoted in "Explanatory Supplement to the Astronomical + Almanac", P. Kenneth Seidelmann, editor. + + This algorithm implements three different Easter + calculation methods: + + 1. Original calculation in Julian calendar, valid in + dates after 326 AD + 2. Original method, with date converted to Gregorian + calendar, valid in years 1583 to 4099 + 3. Revised method, in Gregorian calendar, valid in + years 1583 to 4099 as well + + These methods are represented by the constants: + + * ``EASTER_JULIAN = 1`` + * ``EASTER_ORTHODOX = 2`` + * ``EASTER_WESTERN = 3`` + + The default method is method 3. + + More about the algorithm may be found at: + + `GM Arts: Easter Algorithms `_ + + and + + `The Calendar FAQ: Easter `_ + + """ + + if not (1 <= method <= 3): + raise ValueError("invalid method") + + # g - Golden year - 1 + # c - Century + # h - (23 - Epact) mod 30 + # i - Number of days from March 21 to Paschal Full Moon + # j - Weekday for PFM (0=Sunday, etc) + # p - Number of days from March 21 to Sunday on or before PFM + # (-6 to 28 methods 1 & 3, to 56 for method 2) + # e - Extra days to add for method 2 (converting Julian + # date to Gregorian date) + + y = year + g = y % 19 + e = 0 + if method < 3: + # Old method + i = (19*g + 15) % 30 + j = (y + y//4 + i) % 7 + if method == 2: + # Extra dates to convert Julian to Gregorian date + e = 10 + if y > 1600: + e = e + y//100 - 16 - (y//100 - 16)//4 + else: + # New method + c = y//100 + h = (c - c//4 - (8*c + 13)//25 + 19*g + 15) % 30 + i = h - (h//28)*(1 - (h//28)*(29//(h + 1))*((21 - g)//11)) + j = (y + y//4 + i + 2 - c + c//4) % 7 + + # p can be from -6 to 56 corresponding to dates 22 March to 23 May + # (later dates apply to method 2, although 23 May never actually occurs) + p = i - j + e + d = 1 + (p + 27 + (p + 6)//40) % 31 + m = 3 + (p + 26)//30 + return datetime.date(int(y), int(m), int(d)) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/dateutil/relativedelta.py b/TTS/Kokoro/.venv/Lib/site-packages/dateutil/relativedelta.py new file mode 100644 index 0000000000000000000000000000000000000000..cd323a549e0f182541ebcde2d2ea1adfbbd9701e --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/dateutil/relativedelta.py @@ -0,0 +1,599 @@ +# -*- coding: utf-8 -*- +import datetime +import calendar + +import operator +from math import copysign + +from six import integer_types +from warnings import warn + +from ._common import weekday + +MO, TU, WE, TH, FR, SA, SU = weekdays = tuple(weekday(x) for x in range(7)) + +__all__ = ["relativedelta", "MO", "TU", "WE", "TH", "FR", "SA", "SU"] + + +class relativedelta(object): + """ + The relativedelta type is designed to be applied to an existing datetime and + can replace specific components of that datetime, or represents an interval + of time. + + It is based on the specification of the excellent work done by M.-A. Lemburg + in his + `mx.DateTime `_ extension. + However, notice that this type does *NOT* implement the same algorithm as + his work. Do *NOT* expect it to behave like mx.DateTime's counterpart. + + There are two different ways to build a relativedelta instance. The + first one is passing it two date/datetime classes:: + + relativedelta(datetime1, datetime2) + + The second one is passing it any number of the following keyword arguments:: + + relativedelta(arg1=x,arg2=y,arg3=z...) + + year, month, day, hour, minute, second, microsecond: + Absolute information (argument is singular); adding or subtracting a + relativedelta with absolute information does not perform an arithmetic + operation, but rather REPLACES the corresponding value in the + original datetime with the value(s) in relativedelta. + + years, months, weeks, days, hours, minutes, seconds, microseconds: + Relative information, may be negative (argument is plural); adding + or subtracting a relativedelta with relative information performs + the corresponding arithmetic operation on the original datetime value + with the information in the relativedelta. + + weekday: + One of the weekday instances (MO, TU, etc) available in the + relativedelta module. These instances may receive a parameter N, + specifying the Nth weekday, which could be positive or negative + (like MO(+1) or MO(-2)). Not specifying it is the same as specifying + +1. You can also use an integer, where 0=MO. This argument is always + relative e.g. if the calculated date is already Monday, using MO(1) + or MO(-1) won't change the day. To effectively make it absolute, use + it in combination with the day argument (e.g. day=1, MO(1) for first + Monday of the month). + + leapdays: + Will add given days to the date found, if year is a leap + year, and the date found is post 28 of february. + + yearday, nlyearday: + Set the yearday or the non-leap year day (jump leap days). + These are converted to day/month/leapdays information. + + There are relative and absolute forms of the keyword + arguments. The plural is relative, and the singular is + absolute. For each argument in the order below, the absolute form + is applied first (by setting each attribute to that value) and + then the relative form (by adding the value to the attribute). + + The order of attributes considered when this relativedelta is + added to a datetime is: + + 1. Year + 2. Month + 3. Day + 4. Hours + 5. Minutes + 6. Seconds + 7. Microseconds + + Finally, weekday is applied, using the rule described above. + + For example + + >>> from datetime import datetime + >>> from dateutil.relativedelta import relativedelta, MO + >>> dt = datetime(2018, 4, 9, 13, 37, 0) + >>> delta = relativedelta(hours=25, day=1, weekday=MO(1)) + >>> dt + delta + datetime.datetime(2018, 4, 2, 14, 37) + + First, the day is set to 1 (the first of the month), then 25 hours + are added, to get to the 2nd day and 14th hour, finally the + weekday is applied, but since the 2nd is already a Monday there is + no effect. + + """ + + def __init__(self, dt1=None, dt2=None, + years=0, months=0, days=0, leapdays=0, weeks=0, + hours=0, minutes=0, seconds=0, microseconds=0, + year=None, month=None, day=None, weekday=None, + yearday=None, nlyearday=None, + hour=None, minute=None, second=None, microsecond=None): + + if dt1 and dt2: + # datetime is a subclass of date. So both must be date + if not (isinstance(dt1, datetime.date) and + isinstance(dt2, datetime.date)): + raise TypeError("relativedelta only diffs datetime/date") + + # We allow two dates, or two datetimes, so we coerce them to be + # of the same type + if (isinstance(dt1, datetime.datetime) != + isinstance(dt2, datetime.datetime)): + if not isinstance(dt1, datetime.datetime): + dt1 = datetime.datetime.fromordinal(dt1.toordinal()) + elif not isinstance(dt2, datetime.datetime): + dt2 = datetime.datetime.fromordinal(dt2.toordinal()) + + self.years = 0 + self.months = 0 + self.days = 0 + self.leapdays = 0 + self.hours = 0 + self.minutes = 0 + self.seconds = 0 + self.microseconds = 0 + self.year = None + self.month = None + self.day = None + self.weekday = None + self.hour = None + self.minute = None + self.second = None + self.microsecond = None + self._has_time = 0 + + # Get year / month delta between the two + months = (dt1.year - dt2.year) * 12 + (dt1.month - dt2.month) + self._set_months(months) + + # Remove the year/month delta so the timedelta is just well-defined + # time units (seconds, days and microseconds) + dtm = self.__radd__(dt2) + + # If we've overshot our target, make an adjustment + if dt1 < dt2: + compare = operator.gt + increment = 1 + else: + compare = operator.lt + increment = -1 + + while compare(dt1, dtm): + months += increment + self._set_months(months) + dtm = self.__radd__(dt2) + + # Get the timedelta between the "months-adjusted" date and dt1 + delta = dt1 - dtm + self.seconds = delta.seconds + delta.days * 86400 + self.microseconds = delta.microseconds + else: + # Check for non-integer values in integer-only quantities + if any(x is not None and x != int(x) for x in (years, months)): + raise ValueError("Non-integer years and months are " + "ambiguous and not currently supported.") + + # Relative information + self.years = int(years) + self.months = int(months) + self.days = days + weeks * 7 + self.leapdays = leapdays + self.hours = hours + self.minutes = minutes + self.seconds = seconds + self.microseconds = microseconds + + # Absolute information + self.year = year + self.month = month + self.day = day + self.hour = hour + self.minute = minute + self.second = second + self.microsecond = microsecond + + if any(x is not None and int(x) != x + for x in (year, month, day, hour, + minute, second, microsecond)): + # For now we'll deprecate floats - later it'll be an error. + warn("Non-integer value passed as absolute information. " + + "This is not a well-defined condition and will raise " + + "errors in future versions.", DeprecationWarning) + + if isinstance(weekday, integer_types): + self.weekday = weekdays[weekday] + else: + self.weekday = weekday + + yday = 0 + if nlyearday: + yday = nlyearday + elif yearday: + yday = yearday + if yearday > 59: + self.leapdays = -1 + if yday: + ydayidx = [31, 59, 90, 120, 151, 181, 212, + 243, 273, 304, 334, 366] + for idx, ydays in enumerate(ydayidx): + if yday <= ydays: + self.month = idx+1 + if idx == 0: + self.day = yday + else: + self.day = yday-ydayidx[idx-1] + break + else: + raise ValueError("invalid year day (%d)" % yday) + + self._fix() + + def _fix(self): + if abs(self.microseconds) > 999999: + s = _sign(self.microseconds) + div, mod = divmod(self.microseconds * s, 1000000) + self.microseconds = mod * s + self.seconds += div * s + if abs(self.seconds) > 59: + s = _sign(self.seconds) + div, mod = divmod(self.seconds * s, 60) + self.seconds = mod * s + self.minutes += div * s + if abs(self.minutes) > 59: + s = _sign(self.minutes) + div, mod = divmod(self.minutes * s, 60) + self.minutes = mod * s + self.hours += div * s + if abs(self.hours) > 23: + s = _sign(self.hours) + div, mod = divmod(self.hours * s, 24) + self.hours = mod * s + self.days += div * s + if abs(self.months) > 11: + s = _sign(self.months) + div, mod = divmod(self.months * s, 12) + self.months = mod * s + self.years += div * s + if (self.hours or self.minutes or self.seconds or self.microseconds + or self.hour is not None or self.minute is not None or + self.second is not None or self.microsecond is not None): + self._has_time = 1 + else: + self._has_time = 0 + + @property + def weeks(self): + return int(self.days / 7.0) + + @weeks.setter + def weeks(self, value): + self.days = self.days - (self.weeks * 7) + value * 7 + + def _set_months(self, months): + self.months = months + if abs(self.months) > 11: + s = _sign(self.months) + div, mod = divmod(self.months * s, 12) + self.months = mod * s + self.years = div * s + else: + self.years = 0 + + def normalized(self): + """ + Return a version of this object represented entirely using integer + values for the relative attributes. + + >>> relativedelta(days=1.5, hours=2).normalized() + relativedelta(days=+1, hours=+14) + + :return: + Returns a :class:`dateutil.relativedelta.relativedelta` object. + """ + # Cascade remainders down (rounding each to roughly nearest microsecond) + days = int(self.days) + + hours_f = round(self.hours + 24 * (self.days - days), 11) + hours = int(hours_f) + + minutes_f = round(self.minutes + 60 * (hours_f - hours), 10) + minutes = int(minutes_f) + + seconds_f = round(self.seconds + 60 * (minutes_f - minutes), 8) + seconds = int(seconds_f) + + microseconds = round(self.microseconds + 1e6 * (seconds_f - seconds)) + + # Constructor carries overflow back up with call to _fix() + return self.__class__(years=self.years, months=self.months, + days=days, hours=hours, minutes=minutes, + seconds=seconds, microseconds=microseconds, + leapdays=self.leapdays, year=self.year, + month=self.month, day=self.day, + weekday=self.weekday, hour=self.hour, + minute=self.minute, second=self.second, + microsecond=self.microsecond) + + def __add__(self, other): + if isinstance(other, relativedelta): + return self.__class__(years=other.years + self.years, + months=other.months + self.months, + days=other.days + self.days, + hours=other.hours + self.hours, + minutes=other.minutes + self.minutes, + seconds=other.seconds + self.seconds, + microseconds=(other.microseconds + + self.microseconds), + leapdays=other.leapdays or self.leapdays, + year=(other.year if other.year is not None + else self.year), + month=(other.month if other.month is not None + else self.month), + day=(other.day if other.day is not None + else self.day), + weekday=(other.weekday if other.weekday is not None + else self.weekday), + hour=(other.hour if other.hour is not None + else self.hour), + minute=(other.minute if other.minute is not None + else self.minute), + second=(other.second if other.second is not None + else self.second), + microsecond=(other.microsecond if other.microsecond + is not None else + self.microsecond)) + if isinstance(other, datetime.timedelta): + return self.__class__(years=self.years, + months=self.months, + days=self.days + other.days, + hours=self.hours, + minutes=self.minutes, + seconds=self.seconds + other.seconds, + microseconds=self.microseconds + other.microseconds, + leapdays=self.leapdays, + year=self.year, + month=self.month, + day=self.day, + weekday=self.weekday, + hour=self.hour, + minute=self.minute, + second=self.second, + microsecond=self.microsecond) + if not isinstance(other, datetime.date): + return NotImplemented + elif self._has_time and not isinstance(other, datetime.datetime): + other = datetime.datetime.fromordinal(other.toordinal()) + year = (self.year or other.year)+self.years + month = self.month or other.month + if self.months: + assert 1 <= abs(self.months) <= 12 + month += self.months + if month > 12: + year += 1 + month -= 12 + elif month < 1: + year -= 1 + month += 12 + day = min(calendar.monthrange(year, month)[1], + self.day or other.day) + repl = {"year": year, "month": month, "day": day} + for attr in ["hour", "minute", "second", "microsecond"]: + value = getattr(self, attr) + if value is not None: + repl[attr] = value + days = self.days + if self.leapdays and month > 2 and calendar.isleap(year): + days += self.leapdays + ret = (other.replace(**repl) + + datetime.timedelta(days=days, + hours=self.hours, + minutes=self.minutes, + seconds=self.seconds, + microseconds=self.microseconds)) + if self.weekday: + weekday, nth = self.weekday.weekday, self.weekday.n or 1 + jumpdays = (abs(nth) - 1) * 7 + if nth > 0: + jumpdays += (7 - ret.weekday() + weekday) % 7 + else: + jumpdays += (ret.weekday() - weekday) % 7 + jumpdays *= -1 + ret += datetime.timedelta(days=jumpdays) + return ret + + def __radd__(self, other): + return self.__add__(other) + + def __rsub__(self, other): + return self.__neg__().__radd__(other) + + def __sub__(self, other): + if not isinstance(other, relativedelta): + return NotImplemented # In case the other object defines __rsub__ + return self.__class__(years=self.years - other.years, + months=self.months - other.months, + days=self.days - other.days, + hours=self.hours - other.hours, + minutes=self.minutes - other.minutes, + seconds=self.seconds - other.seconds, + microseconds=self.microseconds - other.microseconds, + leapdays=self.leapdays or other.leapdays, + year=(self.year if self.year is not None + else other.year), + month=(self.month if self.month is not None else + other.month), + day=(self.day if self.day is not None else + other.day), + weekday=(self.weekday if self.weekday is not None else + other.weekday), + hour=(self.hour if self.hour is not None else + other.hour), + minute=(self.minute if self.minute is not None else + other.minute), + second=(self.second if self.second is not None else + other.second), + microsecond=(self.microsecond if self.microsecond + is not None else + other.microsecond)) + + def __abs__(self): + return self.__class__(years=abs(self.years), + months=abs(self.months), + days=abs(self.days), + hours=abs(self.hours), + minutes=abs(self.minutes), + seconds=abs(self.seconds), + microseconds=abs(self.microseconds), + leapdays=self.leapdays, + year=self.year, + month=self.month, + day=self.day, + weekday=self.weekday, + hour=self.hour, + minute=self.minute, + second=self.second, + microsecond=self.microsecond) + + def __neg__(self): + return self.__class__(years=-self.years, + months=-self.months, + days=-self.days, + hours=-self.hours, + minutes=-self.minutes, + seconds=-self.seconds, + microseconds=-self.microseconds, + leapdays=self.leapdays, + year=self.year, + month=self.month, + day=self.day, + weekday=self.weekday, + hour=self.hour, + minute=self.minute, + second=self.second, + microsecond=self.microsecond) + + def __bool__(self): + return not (not self.years and + not self.months and + not self.days and + not self.hours and + not self.minutes and + not self.seconds and + not self.microseconds and + not self.leapdays and + self.year is None and + self.month is None and + self.day is None and + self.weekday is None and + self.hour is None and + self.minute is None and + self.second is None and + self.microsecond is None) + # Compatibility with Python 2.x + __nonzero__ = __bool__ + + def __mul__(self, other): + try: + f = float(other) + except TypeError: + return NotImplemented + + return self.__class__(years=int(self.years * f), + months=int(self.months * f), + days=int(self.days * f), + hours=int(self.hours * f), + minutes=int(self.minutes * f), + seconds=int(self.seconds * f), + microseconds=int(self.microseconds * f), + leapdays=self.leapdays, + year=self.year, + month=self.month, + day=self.day, + weekday=self.weekday, + hour=self.hour, + minute=self.minute, + second=self.second, + microsecond=self.microsecond) + + __rmul__ = __mul__ + + def __eq__(self, other): + if not isinstance(other, relativedelta): + return NotImplemented + if self.weekday or other.weekday: + if not self.weekday or not other.weekday: + return False + if self.weekday.weekday != other.weekday.weekday: + return False + n1, n2 = self.weekday.n, other.weekday.n + if n1 != n2 and not ((not n1 or n1 == 1) and (not n2 or n2 == 1)): + return False + return (self.years == other.years and + self.months == other.months and + self.days == other.days and + self.hours == other.hours and + self.minutes == other.minutes and + self.seconds == other.seconds and + self.microseconds == other.microseconds and + self.leapdays == other.leapdays and + self.year == other.year and + self.month == other.month and + self.day == other.day and + self.hour == other.hour and + self.minute == other.minute and + self.second == other.second and + self.microsecond == other.microsecond) + + def __hash__(self): + return hash(( + self.weekday, + self.years, + self.months, + self.days, + self.hours, + self.minutes, + self.seconds, + self.microseconds, + self.leapdays, + self.year, + self.month, + self.day, + self.hour, + self.minute, + self.second, + self.microsecond, + )) + + def __ne__(self, other): + return not self.__eq__(other) + + def __div__(self, other): + try: + reciprocal = 1 / float(other) + except TypeError: + return NotImplemented + + return self.__mul__(reciprocal) + + __truediv__ = __div__ + + def __repr__(self): + l = [] + for attr in ["years", "months", "days", "leapdays", + "hours", "minutes", "seconds", "microseconds"]: + value = getattr(self, attr) + if value: + l.append("{attr}={value:+g}".format(attr=attr, value=value)) + for attr in ["year", "month", "day", "weekday", + "hour", "minute", "second", "microsecond"]: + value = getattr(self, attr) + if value is not None: + l.append("{attr}={value}".format(attr=attr, value=repr(value))) + return "{classname}({attrs})".format(classname=self.__class__.__name__, + attrs=", ".join(l)) + + +def _sign(x): + return int(copysign(1, x)) + +# vim:ts=4:sw=4:et diff --git a/TTS/Kokoro/.venv/Lib/site-packages/dateutil/rrule.py b/TTS/Kokoro/.venv/Lib/site-packages/dateutil/rrule.py new file mode 100644 index 0000000000000000000000000000000000000000..571a0d2bc886a7ea4c06196b2f52e740c2ed6e9f --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/dateutil/rrule.py @@ -0,0 +1,1737 @@ +# -*- coding: utf-8 -*- +""" +The rrule module offers a small, complete, and very fast, implementation of +the recurrence rules documented in the +`iCalendar RFC `_, +including support for caching of results. +""" +import calendar +import datetime +import heapq +import itertools +import re +import sys +from functools import wraps +# For warning about deprecation of until and count +from warnings import warn + +from six import advance_iterator, integer_types + +from six.moves import _thread, range + +from ._common import weekday as weekdaybase + +try: + from math import gcd +except ImportError: + from fractions import gcd + +__all__ = ["rrule", "rruleset", "rrulestr", + "YEARLY", "MONTHLY", "WEEKLY", "DAILY", + "HOURLY", "MINUTELY", "SECONDLY", + "MO", "TU", "WE", "TH", "FR", "SA", "SU"] + +# Every mask is 7 days longer to handle cross-year weekly periods. +M366MASK = tuple([1]*31+[2]*29+[3]*31+[4]*30+[5]*31+[6]*30 + + [7]*31+[8]*31+[9]*30+[10]*31+[11]*30+[12]*31+[1]*7) +M365MASK = list(M366MASK) +M29, M30, M31 = list(range(1, 30)), list(range(1, 31)), list(range(1, 32)) +MDAY366MASK = tuple(M31+M29+M31+M30+M31+M30+M31+M31+M30+M31+M30+M31+M31[:7]) +MDAY365MASK = list(MDAY366MASK) +M29, M30, M31 = list(range(-29, 0)), list(range(-30, 0)), list(range(-31, 0)) +NMDAY366MASK = tuple(M31+M29+M31+M30+M31+M30+M31+M31+M30+M31+M30+M31+M31[:7]) +NMDAY365MASK = list(NMDAY366MASK) +M366RANGE = (0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366) +M365RANGE = (0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365) +WDAYMASK = [0, 1, 2, 3, 4, 5, 6]*55 +del M29, M30, M31, M365MASK[59], MDAY365MASK[59], NMDAY365MASK[31] +MDAY365MASK = tuple(MDAY365MASK) +M365MASK = tuple(M365MASK) + +FREQNAMES = ['YEARLY', 'MONTHLY', 'WEEKLY', 'DAILY', 'HOURLY', 'MINUTELY', 'SECONDLY'] + +(YEARLY, + MONTHLY, + WEEKLY, + DAILY, + HOURLY, + MINUTELY, + SECONDLY) = list(range(7)) + +# Imported on demand. +easter = None +parser = None + + +class weekday(weekdaybase): + """ + This version of weekday does not allow n = 0. + """ + def __init__(self, wkday, n=None): + if n == 0: + raise ValueError("Can't create weekday with n==0") + + super(weekday, self).__init__(wkday, n) + + +MO, TU, WE, TH, FR, SA, SU = weekdays = tuple(weekday(x) for x in range(7)) + + +def _invalidates_cache(f): + """ + Decorator for rruleset methods which may invalidate the + cached length. + """ + @wraps(f) + def inner_func(self, *args, **kwargs): + rv = f(self, *args, **kwargs) + self._invalidate_cache() + return rv + + return inner_func + + +class rrulebase(object): + def __init__(self, cache=False): + if cache: + self._cache = [] + self._cache_lock = _thread.allocate_lock() + self._invalidate_cache() + else: + self._cache = None + self._cache_complete = False + self._len = None + + def __iter__(self): + if self._cache_complete: + return iter(self._cache) + elif self._cache is None: + return self._iter() + else: + return self._iter_cached() + + def _invalidate_cache(self): + if self._cache is not None: + self._cache = [] + self._cache_complete = False + self._cache_gen = self._iter() + + if self._cache_lock.locked(): + self._cache_lock.release() + + self._len = None + + def _iter_cached(self): + i = 0 + gen = self._cache_gen + cache = self._cache + acquire = self._cache_lock.acquire + release = self._cache_lock.release + while gen: + if i == len(cache): + acquire() + if self._cache_complete: + break + try: + for j in range(10): + cache.append(advance_iterator(gen)) + except StopIteration: + self._cache_gen = gen = None + self._cache_complete = True + break + release() + yield cache[i] + i += 1 + while i < self._len: + yield cache[i] + i += 1 + + def __getitem__(self, item): + if self._cache_complete: + return self._cache[item] + elif isinstance(item, slice): + if item.step and item.step < 0: + return list(iter(self))[item] + else: + return list(itertools.islice(self, + item.start or 0, + item.stop or sys.maxsize, + item.step or 1)) + elif item >= 0: + gen = iter(self) + try: + for i in range(item+1): + res = advance_iterator(gen) + except StopIteration: + raise IndexError + return res + else: + return list(iter(self))[item] + + def __contains__(self, item): + if self._cache_complete: + return item in self._cache + else: + for i in self: + if i == item: + return True + elif i > item: + return False + return False + + # __len__() introduces a large performance penalty. + def count(self): + """ Returns the number of recurrences in this set. It will have go + through the whole recurrence, if this hasn't been done before. """ + if self._len is None: + for x in self: + pass + return self._len + + def before(self, dt, inc=False): + """ Returns the last recurrence before the given datetime instance. The + inc keyword defines what happens if dt is an occurrence. With + inc=True, if dt itself is an occurrence, it will be returned. """ + if self._cache_complete: + gen = self._cache + else: + gen = self + last = None + if inc: + for i in gen: + if i > dt: + break + last = i + else: + for i in gen: + if i >= dt: + break + last = i + return last + + def after(self, dt, inc=False): + """ Returns the first recurrence after the given datetime instance. The + inc keyword defines what happens if dt is an occurrence. With + inc=True, if dt itself is an occurrence, it will be returned. """ + if self._cache_complete: + gen = self._cache + else: + gen = self + if inc: + for i in gen: + if i >= dt: + return i + else: + for i in gen: + if i > dt: + return i + return None + + def xafter(self, dt, count=None, inc=False): + """ + Generator which yields up to `count` recurrences after the given + datetime instance, equivalent to `after`. + + :param dt: + The datetime at which to start generating recurrences. + + :param count: + The maximum number of recurrences to generate. If `None` (default), + dates are generated until the recurrence rule is exhausted. + + :param inc: + If `dt` is an instance of the rule and `inc` is `True`, it is + included in the output. + + :yields: Yields a sequence of `datetime` objects. + """ + + if self._cache_complete: + gen = self._cache + else: + gen = self + + # Select the comparison function + if inc: + comp = lambda dc, dtc: dc >= dtc + else: + comp = lambda dc, dtc: dc > dtc + + # Generate dates + n = 0 + for d in gen: + if comp(d, dt): + if count is not None: + n += 1 + if n > count: + break + + yield d + + def between(self, after, before, inc=False, count=1): + """ Returns all the occurrences of the rrule between after and before. + The inc keyword defines what happens if after and/or before are + themselves occurrences. With inc=True, they will be included in the + list, if they are found in the recurrence set. """ + if self._cache_complete: + gen = self._cache + else: + gen = self + started = False + l = [] + if inc: + for i in gen: + if i > before: + break + elif not started: + if i >= after: + started = True + l.append(i) + else: + l.append(i) + else: + for i in gen: + if i >= before: + break + elif not started: + if i > after: + started = True + l.append(i) + else: + l.append(i) + return l + + +class rrule(rrulebase): + """ + That's the base of the rrule operation. It accepts all the keywords + defined in the RFC as its constructor parameters (except byday, + which was renamed to byweekday) and more. The constructor prototype is:: + + rrule(freq) + + Where freq must be one of YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, + or SECONDLY. + + .. note:: + Per RFC section 3.3.10, recurrence instances falling on invalid dates + and times are ignored rather than coerced: + + Recurrence rules may generate recurrence instances with an invalid + date (e.g., February 30) or nonexistent local time (e.g., 1:30 AM + on a day where the local time is moved forward by an hour at 1:00 + AM). Such recurrence instances MUST be ignored and MUST NOT be + counted as part of the recurrence set. + + This can lead to possibly surprising behavior when, for example, the + start date occurs at the end of the month: + + >>> from dateutil.rrule import rrule, MONTHLY + >>> from datetime import datetime + >>> start_date = datetime(2014, 12, 31) + >>> list(rrule(freq=MONTHLY, count=4, dtstart=start_date)) + ... # doctest: +NORMALIZE_WHITESPACE + [datetime.datetime(2014, 12, 31, 0, 0), + datetime.datetime(2015, 1, 31, 0, 0), + datetime.datetime(2015, 3, 31, 0, 0), + datetime.datetime(2015, 5, 31, 0, 0)] + + Additionally, it supports the following keyword arguments: + + :param dtstart: + The recurrence start. Besides being the base for the recurrence, + missing parameters in the final recurrence instances will also be + extracted from this date. If not given, datetime.now() will be used + instead. + :param interval: + The interval between each freq iteration. For example, when using + YEARLY, an interval of 2 means once every two years, but with HOURLY, + it means once every two hours. The default interval is 1. + :param wkst: + The week start day. Must be one of the MO, TU, WE constants, or an + integer, specifying the first day of the week. This will affect + recurrences based on weekly periods. The default week start is got + from calendar.firstweekday(), and may be modified by + calendar.setfirstweekday(). + :param count: + If given, this determines how many occurrences will be generated. + + .. note:: + As of version 2.5.0, the use of the keyword ``until`` in conjunction + with ``count`` is deprecated, to make sure ``dateutil`` is fully + compliant with `RFC-5545 Sec. 3.3.10 `_. Therefore, ``until`` and ``count`` + **must not** occur in the same call to ``rrule``. + :param until: + If given, this must be a datetime instance specifying the upper-bound + limit of the recurrence. The last recurrence in the rule is the greatest + datetime that is less than or equal to the value specified in the + ``until`` parameter. + + .. note:: + As of version 2.5.0, the use of the keyword ``until`` in conjunction + with ``count`` is deprecated, to make sure ``dateutil`` is fully + compliant with `RFC-5545 Sec. 3.3.10 `_. Therefore, ``until`` and ``count`` + **must not** occur in the same call to ``rrule``. + :param bysetpos: + If given, it must be either an integer, or a sequence of integers, + positive or negative. Each given integer will specify an occurrence + number, corresponding to the nth occurrence of the rule inside the + frequency period. For example, a bysetpos of -1 if combined with a + MONTHLY frequency, and a byweekday of (MO, TU, WE, TH, FR), will + result in the last work day of every month. + :param bymonth: + If given, it must be either an integer, or a sequence of integers, + meaning the months to apply the recurrence to. + :param bymonthday: + If given, it must be either an integer, or a sequence of integers, + meaning the month days to apply the recurrence to. + :param byyearday: + If given, it must be either an integer, or a sequence of integers, + meaning the year days to apply the recurrence to. + :param byeaster: + If given, it must be either an integer, or a sequence of integers, + positive or negative. Each integer will define an offset from the + Easter Sunday. Passing the offset 0 to byeaster will yield the Easter + Sunday itself. This is an extension to the RFC specification. + :param byweekno: + If given, it must be either an integer, or a sequence of integers, + meaning the week numbers to apply the recurrence to. Week numbers + have the meaning described in ISO8601, that is, the first week of + the year is that containing at least four days of the new year. + :param byweekday: + If given, it must be either an integer (0 == MO), a sequence of + integers, one of the weekday constants (MO, TU, etc), or a sequence + of these constants. When given, these variables will define the + weekdays where the recurrence will be applied. It's also possible to + use an argument n for the weekday instances, which will mean the nth + occurrence of this weekday in the period. For example, with MONTHLY, + or with YEARLY and BYMONTH, using FR(+1) in byweekday will specify the + first friday of the month where the recurrence happens. Notice that in + the RFC documentation, this is specified as BYDAY, but was renamed to + avoid the ambiguity of that keyword. + :param byhour: + If given, it must be either an integer, or a sequence of integers, + meaning the hours to apply the recurrence to. + :param byminute: + If given, it must be either an integer, or a sequence of integers, + meaning the minutes to apply the recurrence to. + :param bysecond: + If given, it must be either an integer, or a sequence of integers, + meaning the seconds to apply the recurrence to. + :param cache: + If given, it must be a boolean value specifying to enable or disable + caching of results. If you will use the same rrule instance multiple + times, enabling caching will improve the performance considerably. + """ + def __init__(self, freq, dtstart=None, + interval=1, wkst=None, count=None, until=None, bysetpos=None, + bymonth=None, bymonthday=None, byyearday=None, byeaster=None, + byweekno=None, byweekday=None, + byhour=None, byminute=None, bysecond=None, + cache=False): + super(rrule, self).__init__(cache) + global easter + if not dtstart: + if until and until.tzinfo: + dtstart = datetime.datetime.now(tz=until.tzinfo).replace(microsecond=0) + else: + dtstart = datetime.datetime.now().replace(microsecond=0) + elif not isinstance(dtstart, datetime.datetime): + dtstart = datetime.datetime.fromordinal(dtstart.toordinal()) + else: + dtstart = dtstart.replace(microsecond=0) + self._dtstart = dtstart + self._tzinfo = dtstart.tzinfo + self._freq = freq + self._interval = interval + self._count = count + + # Cache the original byxxx rules, if they are provided, as the _byxxx + # attributes do not necessarily map to the inputs, and this can be + # a problem in generating the strings. Only store things if they've + # been supplied (the string retrieval will just use .get()) + self._original_rule = {} + + if until and not isinstance(until, datetime.datetime): + until = datetime.datetime.fromordinal(until.toordinal()) + self._until = until + + if self._dtstart and self._until: + if (self._dtstart.tzinfo is not None) != (self._until.tzinfo is not None): + # According to RFC5545 Section 3.3.10: + # https://tools.ietf.org/html/rfc5545#section-3.3.10 + # + # > If the "DTSTART" property is specified as a date with UTC + # > time or a date with local time and time zone reference, + # > then the UNTIL rule part MUST be specified as a date with + # > UTC time. + raise ValueError( + 'RRULE UNTIL values must be specified in UTC when DTSTART ' + 'is timezone-aware' + ) + + if count is not None and until: + warn("Using both 'count' and 'until' is inconsistent with RFC 5545" + " and has been deprecated in dateutil. Future versions will " + "raise an error.", DeprecationWarning) + + if wkst is None: + self._wkst = calendar.firstweekday() + elif isinstance(wkst, integer_types): + self._wkst = wkst + else: + self._wkst = wkst.weekday + + if bysetpos is None: + self._bysetpos = None + elif isinstance(bysetpos, integer_types): + if bysetpos == 0 or not (-366 <= bysetpos <= 366): + raise ValueError("bysetpos must be between 1 and 366, " + "or between -366 and -1") + self._bysetpos = (bysetpos,) + else: + self._bysetpos = tuple(bysetpos) + for pos in self._bysetpos: + if pos == 0 or not (-366 <= pos <= 366): + raise ValueError("bysetpos must be between 1 and 366, " + "or between -366 and -1") + + if self._bysetpos: + self._original_rule['bysetpos'] = self._bysetpos + + if (byweekno is None and byyearday is None and bymonthday is None and + byweekday is None and byeaster is None): + if freq == YEARLY: + if bymonth is None: + bymonth = dtstart.month + self._original_rule['bymonth'] = None + bymonthday = dtstart.day + self._original_rule['bymonthday'] = None + elif freq == MONTHLY: + bymonthday = dtstart.day + self._original_rule['bymonthday'] = None + elif freq == WEEKLY: + byweekday = dtstart.weekday() + self._original_rule['byweekday'] = None + + # bymonth + if bymonth is None: + self._bymonth = None + else: + if isinstance(bymonth, integer_types): + bymonth = (bymonth,) + + self._bymonth = tuple(sorted(set(bymonth))) + + if 'bymonth' not in self._original_rule: + self._original_rule['bymonth'] = self._bymonth + + # byyearday + if byyearday is None: + self._byyearday = None + else: + if isinstance(byyearday, integer_types): + byyearday = (byyearday,) + + self._byyearday = tuple(sorted(set(byyearday))) + self._original_rule['byyearday'] = self._byyearday + + # byeaster + if byeaster is not None: + if not easter: + from dateutil import easter + if isinstance(byeaster, integer_types): + self._byeaster = (byeaster,) + else: + self._byeaster = tuple(sorted(byeaster)) + + self._original_rule['byeaster'] = self._byeaster + else: + self._byeaster = None + + # bymonthday + if bymonthday is None: + self._bymonthday = () + self._bynmonthday = () + else: + if isinstance(bymonthday, integer_types): + bymonthday = (bymonthday,) + + bymonthday = set(bymonthday) # Ensure it's unique + + self._bymonthday = tuple(sorted(x for x in bymonthday if x > 0)) + self._bynmonthday = tuple(sorted(x for x in bymonthday if x < 0)) + + # Storing positive numbers first, then negative numbers + if 'bymonthday' not in self._original_rule: + self._original_rule['bymonthday'] = tuple( + itertools.chain(self._bymonthday, self._bynmonthday)) + + # byweekno + if byweekno is None: + self._byweekno = None + else: + if isinstance(byweekno, integer_types): + byweekno = (byweekno,) + + self._byweekno = tuple(sorted(set(byweekno))) + + self._original_rule['byweekno'] = self._byweekno + + # byweekday / bynweekday + if byweekday is None: + self._byweekday = None + self._bynweekday = None + else: + # If it's one of the valid non-sequence types, convert to a + # single-element sequence before the iterator that builds the + # byweekday set. + if isinstance(byweekday, integer_types) or hasattr(byweekday, "n"): + byweekday = (byweekday,) + + self._byweekday = set() + self._bynweekday = set() + for wday in byweekday: + if isinstance(wday, integer_types): + self._byweekday.add(wday) + elif not wday.n or freq > MONTHLY: + self._byweekday.add(wday.weekday) + else: + self._bynweekday.add((wday.weekday, wday.n)) + + if not self._byweekday: + self._byweekday = None + elif not self._bynweekday: + self._bynweekday = None + + if self._byweekday is not None: + self._byweekday = tuple(sorted(self._byweekday)) + orig_byweekday = [weekday(x) for x in self._byweekday] + else: + orig_byweekday = () + + if self._bynweekday is not None: + self._bynweekday = tuple(sorted(self._bynweekday)) + orig_bynweekday = [weekday(*x) for x in self._bynweekday] + else: + orig_bynweekday = () + + if 'byweekday' not in self._original_rule: + self._original_rule['byweekday'] = tuple(itertools.chain( + orig_byweekday, orig_bynweekday)) + + # byhour + if byhour is None: + if freq < HOURLY: + self._byhour = {dtstart.hour} + else: + self._byhour = None + else: + if isinstance(byhour, integer_types): + byhour = (byhour,) + + if freq == HOURLY: + self._byhour = self.__construct_byset(start=dtstart.hour, + byxxx=byhour, + base=24) + else: + self._byhour = set(byhour) + + self._byhour = tuple(sorted(self._byhour)) + self._original_rule['byhour'] = self._byhour + + # byminute + if byminute is None: + if freq < MINUTELY: + self._byminute = {dtstart.minute} + else: + self._byminute = None + else: + if isinstance(byminute, integer_types): + byminute = (byminute,) + + if freq == MINUTELY: + self._byminute = self.__construct_byset(start=dtstart.minute, + byxxx=byminute, + base=60) + else: + self._byminute = set(byminute) + + self._byminute = tuple(sorted(self._byminute)) + self._original_rule['byminute'] = self._byminute + + # bysecond + if bysecond is None: + if freq < SECONDLY: + self._bysecond = ((dtstart.second,)) + else: + self._bysecond = None + else: + if isinstance(bysecond, integer_types): + bysecond = (bysecond,) + + self._bysecond = set(bysecond) + + if freq == SECONDLY: + self._bysecond = self.__construct_byset(start=dtstart.second, + byxxx=bysecond, + base=60) + else: + self._bysecond = set(bysecond) + + self._bysecond = tuple(sorted(self._bysecond)) + self._original_rule['bysecond'] = self._bysecond + + if self._freq >= HOURLY: + self._timeset = None + else: + self._timeset = [] + for hour in self._byhour: + for minute in self._byminute: + for second in self._bysecond: + self._timeset.append( + datetime.time(hour, minute, second, + tzinfo=self._tzinfo)) + self._timeset.sort() + self._timeset = tuple(self._timeset) + + def __str__(self): + """ + Output a string that would generate this RRULE if passed to rrulestr. + This is mostly compatible with RFC5545, except for the + dateutil-specific extension BYEASTER. + """ + + output = [] + h, m, s = [None] * 3 + if self._dtstart: + output.append(self._dtstart.strftime('DTSTART:%Y%m%dT%H%M%S')) + h, m, s = self._dtstart.timetuple()[3:6] + + parts = ['FREQ=' + FREQNAMES[self._freq]] + if self._interval != 1: + parts.append('INTERVAL=' + str(self._interval)) + + if self._wkst: + parts.append('WKST=' + repr(weekday(self._wkst))[0:2]) + + if self._count is not None: + parts.append('COUNT=' + str(self._count)) + + if self._until: + parts.append(self._until.strftime('UNTIL=%Y%m%dT%H%M%S')) + + if self._original_rule.get('byweekday') is not None: + # The str() method on weekday objects doesn't generate + # RFC5545-compliant strings, so we should modify that. + original_rule = dict(self._original_rule) + wday_strings = [] + for wday in original_rule['byweekday']: + if wday.n: + wday_strings.append('{n:+d}{wday}'.format( + n=wday.n, + wday=repr(wday)[0:2])) + else: + wday_strings.append(repr(wday)) + + original_rule['byweekday'] = wday_strings + else: + original_rule = self._original_rule + + partfmt = '{name}={vals}' + for name, key in [('BYSETPOS', 'bysetpos'), + ('BYMONTH', 'bymonth'), + ('BYMONTHDAY', 'bymonthday'), + ('BYYEARDAY', 'byyearday'), + ('BYWEEKNO', 'byweekno'), + ('BYDAY', 'byweekday'), + ('BYHOUR', 'byhour'), + ('BYMINUTE', 'byminute'), + ('BYSECOND', 'bysecond'), + ('BYEASTER', 'byeaster')]: + value = original_rule.get(key) + if value: + parts.append(partfmt.format(name=name, vals=(','.join(str(v) + for v in value)))) + + output.append('RRULE:' + ';'.join(parts)) + return '\n'.join(output) + + def replace(self, **kwargs): + """Return new rrule with same attributes except for those attributes given new + values by whichever keyword arguments are specified.""" + new_kwargs = {"interval": self._interval, + "count": self._count, + "dtstart": self._dtstart, + "freq": self._freq, + "until": self._until, + "wkst": self._wkst, + "cache": False if self._cache is None else True } + new_kwargs.update(self._original_rule) + new_kwargs.update(kwargs) + return rrule(**new_kwargs) + + def _iter(self): + year, month, day, hour, minute, second, weekday, yearday, _ = \ + self._dtstart.timetuple() + + # Some local variables to speed things up a bit + freq = self._freq + interval = self._interval + wkst = self._wkst + until = self._until + bymonth = self._bymonth + byweekno = self._byweekno + byyearday = self._byyearday + byweekday = self._byweekday + byeaster = self._byeaster + bymonthday = self._bymonthday + bynmonthday = self._bynmonthday + bysetpos = self._bysetpos + byhour = self._byhour + byminute = self._byminute + bysecond = self._bysecond + + ii = _iterinfo(self) + ii.rebuild(year, month) + + getdayset = {YEARLY: ii.ydayset, + MONTHLY: ii.mdayset, + WEEKLY: ii.wdayset, + DAILY: ii.ddayset, + HOURLY: ii.ddayset, + MINUTELY: ii.ddayset, + SECONDLY: ii.ddayset}[freq] + + if freq < HOURLY: + timeset = self._timeset + else: + gettimeset = {HOURLY: ii.htimeset, + MINUTELY: ii.mtimeset, + SECONDLY: ii.stimeset}[freq] + if ((freq >= HOURLY and + self._byhour and hour not in self._byhour) or + (freq >= MINUTELY and + self._byminute and minute not in self._byminute) or + (freq >= SECONDLY and + self._bysecond and second not in self._bysecond)): + timeset = () + else: + timeset = gettimeset(hour, minute, second) + + total = 0 + count = self._count + while True: + # Get dayset with the right frequency + dayset, start, end = getdayset(year, month, day) + + # Do the "hard" work ;-) + filtered = False + for i in dayset[start:end]: + if ((bymonth and ii.mmask[i] not in bymonth) or + (byweekno and not ii.wnomask[i]) or + (byweekday and ii.wdaymask[i] not in byweekday) or + (ii.nwdaymask and not ii.nwdaymask[i]) or + (byeaster and not ii.eastermask[i]) or + ((bymonthday or bynmonthday) and + ii.mdaymask[i] not in bymonthday and + ii.nmdaymask[i] not in bynmonthday) or + (byyearday and + ((i < ii.yearlen and i+1 not in byyearday and + -ii.yearlen+i not in byyearday) or + (i >= ii.yearlen and i+1-ii.yearlen not in byyearday and + -ii.nextyearlen+i-ii.yearlen not in byyearday)))): + dayset[i] = None + filtered = True + + # Output results + if bysetpos and timeset: + poslist = [] + for pos in bysetpos: + if pos < 0: + daypos, timepos = divmod(pos, len(timeset)) + else: + daypos, timepos = divmod(pos-1, len(timeset)) + try: + i = [x for x in dayset[start:end] + if x is not None][daypos] + time = timeset[timepos] + except IndexError: + pass + else: + date = datetime.date.fromordinal(ii.yearordinal+i) + res = datetime.datetime.combine(date, time) + if res not in poslist: + poslist.append(res) + poslist.sort() + for res in poslist: + if until and res > until: + self._len = total + return + elif res >= self._dtstart: + if count is not None: + count -= 1 + if count < 0: + self._len = total + return + total += 1 + yield res + else: + for i in dayset[start:end]: + if i is not None: + date = datetime.date.fromordinal(ii.yearordinal + i) + for time in timeset: + res = datetime.datetime.combine(date, time) + if until and res > until: + self._len = total + return + elif res >= self._dtstart: + if count is not None: + count -= 1 + if count < 0: + self._len = total + return + + total += 1 + yield res + + # Handle frequency and interval + fixday = False + if freq == YEARLY: + year += interval + if year > datetime.MAXYEAR: + self._len = total + return + ii.rebuild(year, month) + elif freq == MONTHLY: + month += interval + if month > 12: + div, mod = divmod(month, 12) + month = mod + year += div + if month == 0: + month = 12 + year -= 1 + if year > datetime.MAXYEAR: + self._len = total + return + ii.rebuild(year, month) + elif freq == WEEKLY: + if wkst > weekday: + day += -(weekday+1+(6-wkst))+self._interval*7 + else: + day += -(weekday-wkst)+self._interval*7 + weekday = wkst + fixday = True + elif freq == DAILY: + day += interval + fixday = True + elif freq == HOURLY: + if filtered: + # Jump to one iteration before next day + hour += ((23-hour)//interval)*interval + + if byhour: + ndays, hour = self.__mod_distance(value=hour, + byxxx=self._byhour, + base=24) + else: + ndays, hour = divmod(hour+interval, 24) + + if ndays: + day += ndays + fixday = True + + timeset = gettimeset(hour, minute, second) + elif freq == MINUTELY: + if filtered: + # Jump to one iteration before next day + minute += ((1439-(hour*60+minute))//interval)*interval + + valid = False + rep_rate = (24*60) + for j in range(rep_rate // gcd(interval, rep_rate)): + if byminute: + nhours, minute = \ + self.__mod_distance(value=minute, + byxxx=self._byminute, + base=60) + else: + nhours, minute = divmod(minute+interval, 60) + + div, hour = divmod(hour+nhours, 24) + if div: + day += div + fixday = True + filtered = False + + if not byhour or hour in byhour: + valid = True + break + + if not valid: + raise ValueError('Invalid combination of interval and ' + + 'byhour resulting in empty rule.') + + timeset = gettimeset(hour, minute, second) + elif freq == SECONDLY: + if filtered: + # Jump to one iteration before next day + second += (((86399 - (hour * 3600 + minute * 60 + second)) + // interval) * interval) + + rep_rate = (24 * 3600) + valid = False + for j in range(0, rep_rate // gcd(interval, rep_rate)): + if bysecond: + nminutes, second = \ + self.__mod_distance(value=second, + byxxx=self._bysecond, + base=60) + else: + nminutes, second = divmod(second+interval, 60) + + div, minute = divmod(minute+nminutes, 60) + if div: + hour += div + div, hour = divmod(hour, 24) + if div: + day += div + fixday = True + + if ((not byhour or hour in byhour) and + (not byminute or minute in byminute) and + (not bysecond or second in bysecond)): + valid = True + break + + if not valid: + raise ValueError('Invalid combination of interval, ' + + 'byhour and byminute resulting in empty' + + ' rule.') + + timeset = gettimeset(hour, minute, second) + + if fixday and day > 28: + daysinmonth = calendar.monthrange(year, month)[1] + if day > daysinmonth: + while day > daysinmonth: + day -= daysinmonth + month += 1 + if month == 13: + month = 1 + year += 1 + if year > datetime.MAXYEAR: + self._len = total + return + daysinmonth = calendar.monthrange(year, month)[1] + ii.rebuild(year, month) + + def __construct_byset(self, start, byxxx, base): + """ + If a `BYXXX` sequence is passed to the constructor at the same level as + `FREQ` (e.g. `FREQ=HOURLY,BYHOUR={2,4,7},INTERVAL=3`), there are some + specifications which cannot be reached given some starting conditions. + + This occurs whenever the interval is not coprime with the base of a + given unit and the difference between the starting position and the + ending position is not coprime with the greatest common denominator + between the interval and the base. For example, with a FREQ of hourly + starting at 17:00 and an interval of 4, the only valid values for + BYHOUR would be {21, 1, 5, 9, 13, 17}, because 4 and 24 are not + coprime. + + :param start: + Specifies the starting position. + :param byxxx: + An iterable containing the list of allowed values. + :param base: + The largest allowable value for the specified frequency (e.g. + 24 hours, 60 minutes). + + This does not preserve the type of the iterable, returning a set, since + the values should be unique and the order is irrelevant, this will + speed up later lookups. + + In the event of an empty set, raises a :exception:`ValueError`, as this + results in an empty rrule. + """ + + cset = set() + + # Support a single byxxx value. + if isinstance(byxxx, integer_types): + byxxx = (byxxx, ) + + for num in byxxx: + i_gcd = gcd(self._interval, base) + # Use divmod rather than % because we need to wrap negative nums. + if i_gcd == 1 or divmod(num - start, i_gcd)[1] == 0: + cset.add(num) + + if len(cset) == 0: + raise ValueError("Invalid rrule byxxx generates an empty set.") + + return cset + + def __mod_distance(self, value, byxxx, base): + """ + Calculates the next value in a sequence where the `FREQ` parameter is + specified along with a `BYXXX` parameter at the same "level" + (e.g. `HOURLY` specified with `BYHOUR`). + + :param value: + The old value of the component. + :param byxxx: + The `BYXXX` set, which should have been generated by + `rrule._construct_byset`, or something else which checks that a + valid rule is present. + :param base: + The largest allowable value for the specified frequency (e.g. + 24 hours, 60 minutes). + + If a valid value is not found after `base` iterations (the maximum + number before the sequence would start to repeat), this raises a + :exception:`ValueError`, as no valid values were found. + + This returns a tuple of `divmod(n*interval, base)`, where `n` is the + smallest number of `interval` repetitions until the next specified + value in `byxxx` is found. + """ + accumulator = 0 + for ii in range(1, base + 1): + # Using divmod() over % to account for negative intervals + div, value = divmod(value + self._interval, base) + accumulator += div + if value in byxxx: + return (accumulator, value) + + +class _iterinfo(object): + __slots__ = ["rrule", "lastyear", "lastmonth", + "yearlen", "nextyearlen", "yearordinal", "yearweekday", + "mmask", "mrange", "mdaymask", "nmdaymask", + "wdaymask", "wnomask", "nwdaymask", "eastermask"] + + def __init__(self, rrule): + for attr in self.__slots__: + setattr(self, attr, None) + self.rrule = rrule + + def rebuild(self, year, month): + # Every mask is 7 days longer to handle cross-year weekly periods. + rr = self.rrule + if year != self.lastyear: + self.yearlen = 365 + calendar.isleap(year) + self.nextyearlen = 365 + calendar.isleap(year + 1) + firstyday = datetime.date(year, 1, 1) + self.yearordinal = firstyday.toordinal() + self.yearweekday = firstyday.weekday() + + wday = datetime.date(year, 1, 1).weekday() + if self.yearlen == 365: + self.mmask = M365MASK + self.mdaymask = MDAY365MASK + self.nmdaymask = NMDAY365MASK + self.wdaymask = WDAYMASK[wday:] + self.mrange = M365RANGE + else: + self.mmask = M366MASK + self.mdaymask = MDAY366MASK + self.nmdaymask = NMDAY366MASK + self.wdaymask = WDAYMASK[wday:] + self.mrange = M366RANGE + + if not rr._byweekno: + self.wnomask = None + else: + self.wnomask = [0]*(self.yearlen+7) + # no1wkst = firstwkst = self.wdaymask.index(rr._wkst) + no1wkst = firstwkst = (7-self.yearweekday+rr._wkst) % 7 + if no1wkst >= 4: + no1wkst = 0 + # Number of days in the year, plus the days we got + # from last year. + wyearlen = self.yearlen+(self.yearweekday-rr._wkst) % 7 + else: + # Number of days in the year, minus the days we + # left in last year. + wyearlen = self.yearlen-no1wkst + div, mod = divmod(wyearlen, 7) + numweeks = div+mod//4 + for n in rr._byweekno: + if n < 0: + n += numweeks+1 + if not (0 < n <= numweeks): + continue + if n > 1: + i = no1wkst+(n-1)*7 + if no1wkst != firstwkst: + i -= 7-firstwkst + else: + i = no1wkst + for j in range(7): + self.wnomask[i] = 1 + i += 1 + if self.wdaymask[i] == rr._wkst: + break + if 1 in rr._byweekno: + # Check week number 1 of next year as well + # TODO: Check -numweeks for next year. + i = no1wkst+numweeks*7 + if no1wkst != firstwkst: + i -= 7-firstwkst + if i < self.yearlen: + # If week starts in next year, we + # don't care about it. + for j in range(7): + self.wnomask[i] = 1 + i += 1 + if self.wdaymask[i] == rr._wkst: + break + if no1wkst: + # Check last week number of last year as + # well. If no1wkst is 0, either the year + # started on week start, or week number 1 + # got days from last year, so there are no + # days from last year's last week number in + # this year. + if -1 not in rr._byweekno: + lyearweekday = datetime.date(year-1, 1, 1).weekday() + lno1wkst = (7-lyearweekday+rr._wkst) % 7 + lyearlen = 365+calendar.isleap(year-1) + if lno1wkst >= 4: + lno1wkst = 0 + lnumweeks = 52+(lyearlen + + (lyearweekday-rr._wkst) % 7) % 7//4 + else: + lnumweeks = 52+(self.yearlen-no1wkst) % 7//4 + else: + lnumweeks = -1 + if lnumweeks in rr._byweekno: + for i in range(no1wkst): + self.wnomask[i] = 1 + + if (rr._bynweekday and (month != self.lastmonth or + year != self.lastyear)): + ranges = [] + if rr._freq == YEARLY: + if rr._bymonth: + for month in rr._bymonth: + ranges.append(self.mrange[month-1:month+1]) + else: + ranges = [(0, self.yearlen)] + elif rr._freq == MONTHLY: + ranges = [self.mrange[month-1:month+1]] + if ranges: + # Weekly frequency won't get here, so we may not + # care about cross-year weekly periods. + self.nwdaymask = [0]*self.yearlen + for first, last in ranges: + last -= 1 + for wday, n in rr._bynweekday: + if n < 0: + i = last+(n+1)*7 + i -= (self.wdaymask[i]-wday) % 7 + else: + i = first+(n-1)*7 + i += (7-self.wdaymask[i]+wday) % 7 + if first <= i <= last: + self.nwdaymask[i] = 1 + + if rr._byeaster: + self.eastermask = [0]*(self.yearlen+7) + eyday = easter.easter(year).toordinal()-self.yearordinal + for offset in rr._byeaster: + self.eastermask[eyday+offset] = 1 + + self.lastyear = year + self.lastmonth = month + + def ydayset(self, year, month, day): + return list(range(self.yearlen)), 0, self.yearlen + + def mdayset(self, year, month, day): + dset = [None]*self.yearlen + start, end = self.mrange[month-1:month+1] + for i in range(start, end): + dset[i] = i + return dset, start, end + + def wdayset(self, year, month, day): + # We need to handle cross-year weeks here. + dset = [None]*(self.yearlen+7) + i = datetime.date(year, month, day).toordinal()-self.yearordinal + start = i + for j in range(7): + dset[i] = i + i += 1 + # if (not (0 <= i < self.yearlen) or + # self.wdaymask[i] == self.rrule._wkst): + # This will cross the year boundary, if necessary. + if self.wdaymask[i] == self.rrule._wkst: + break + return dset, start, i + + def ddayset(self, year, month, day): + dset = [None] * self.yearlen + i = datetime.date(year, month, day).toordinal() - self.yearordinal + dset[i] = i + return dset, i, i + 1 + + def htimeset(self, hour, minute, second): + tset = [] + rr = self.rrule + for minute in rr._byminute: + for second in rr._bysecond: + tset.append(datetime.time(hour, minute, second, + tzinfo=rr._tzinfo)) + tset.sort() + return tset + + def mtimeset(self, hour, minute, second): + tset = [] + rr = self.rrule + for second in rr._bysecond: + tset.append(datetime.time(hour, minute, second, tzinfo=rr._tzinfo)) + tset.sort() + return tset + + def stimeset(self, hour, minute, second): + return (datetime.time(hour, minute, second, + tzinfo=self.rrule._tzinfo),) + + +class rruleset(rrulebase): + """ The rruleset type allows more complex recurrence setups, mixing + multiple rules, dates, exclusion rules, and exclusion dates. The type + constructor takes the following keyword arguments: + + :param cache: If True, caching of results will be enabled, improving + performance of multiple queries considerably. """ + + class _genitem(object): + def __init__(self, genlist, gen): + try: + self.dt = advance_iterator(gen) + genlist.append(self) + except StopIteration: + pass + self.genlist = genlist + self.gen = gen + + def __next__(self): + try: + self.dt = advance_iterator(self.gen) + except StopIteration: + if self.genlist[0] is self: + heapq.heappop(self.genlist) + else: + self.genlist.remove(self) + heapq.heapify(self.genlist) + + next = __next__ + + def __lt__(self, other): + return self.dt < other.dt + + def __gt__(self, other): + return self.dt > other.dt + + def __eq__(self, other): + return self.dt == other.dt + + def __ne__(self, other): + return self.dt != other.dt + + def __init__(self, cache=False): + super(rruleset, self).__init__(cache) + self._rrule = [] + self._rdate = [] + self._exrule = [] + self._exdate = [] + + @_invalidates_cache + def rrule(self, rrule): + """ Include the given :py:class:`rrule` instance in the recurrence set + generation. """ + self._rrule.append(rrule) + + @_invalidates_cache + def rdate(self, rdate): + """ Include the given :py:class:`datetime` instance in the recurrence + set generation. """ + self._rdate.append(rdate) + + @_invalidates_cache + def exrule(self, exrule): + """ Include the given rrule instance in the recurrence set exclusion + list. Dates which are part of the given recurrence rules will not + be generated, even if some inclusive rrule or rdate matches them. + """ + self._exrule.append(exrule) + + @_invalidates_cache + def exdate(self, exdate): + """ Include the given datetime instance in the recurrence set + exclusion list. Dates included that way will not be generated, + even if some inclusive rrule or rdate matches them. """ + self._exdate.append(exdate) + + def _iter(self): + rlist = [] + self._rdate.sort() + self._genitem(rlist, iter(self._rdate)) + for gen in [iter(x) for x in self._rrule]: + self._genitem(rlist, gen) + exlist = [] + self._exdate.sort() + self._genitem(exlist, iter(self._exdate)) + for gen in [iter(x) for x in self._exrule]: + self._genitem(exlist, gen) + lastdt = None + total = 0 + heapq.heapify(rlist) + heapq.heapify(exlist) + while rlist: + ritem = rlist[0] + if not lastdt or lastdt != ritem.dt: + while exlist and exlist[0] < ritem: + exitem = exlist[0] + advance_iterator(exitem) + if exlist and exlist[0] is exitem: + heapq.heapreplace(exlist, exitem) + if not exlist or ritem != exlist[0]: + total += 1 + yield ritem.dt + lastdt = ritem.dt + advance_iterator(ritem) + if rlist and rlist[0] is ritem: + heapq.heapreplace(rlist, ritem) + self._len = total + + + + +class _rrulestr(object): + """ Parses a string representation of a recurrence rule or set of + recurrence rules. + + :param s: + Required, a string defining one or more recurrence rules. + + :param dtstart: + If given, used as the default recurrence start if not specified in the + rule string. + + :param cache: + If set ``True`` caching of results will be enabled, improving + performance of multiple queries considerably. + + :param unfold: + If set ``True`` indicates that a rule string is split over more + than one line and should be joined before processing. + + :param forceset: + If set ``True`` forces a :class:`dateutil.rrule.rruleset` to + be returned. + + :param compatible: + If set ``True`` forces ``unfold`` and ``forceset`` to be ``True``. + + :param ignoretz: + If set ``True``, time zones in parsed strings are ignored and a naive + :class:`datetime.datetime` object is returned. + + :param tzids: + If given, a callable or mapping used to retrieve a + :class:`datetime.tzinfo` from a string representation. + Defaults to :func:`dateutil.tz.gettz`. + + :param tzinfos: + Additional time zone names / aliases which may be present in a string + representation. See :func:`dateutil.parser.parse` for more + information. + + :return: + Returns a :class:`dateutil.rrule.rruleset` or + :class:`dateutil.rrule.rrule` + """ + + _freq_map = {"YEARLY": YEARLY, + "MONTHLY": MONTHLY, + "WEEKLY": WEEKLY, + "DAILY": DAILY, + "HOURLY": HOURLY, + "MINUTELY": MINUTELY, + "SECONDLY": SECONDLY} + + _weekday_map = {"MO": 0, "TU": 1, "WE": 2, "TH": 3, + "FR": 4, "SA": 5, "SU": 6} + + def _handle_int(self, rrkwargs, name, value, **kwargs): + rrkwargs[name.lower()] = int(value) + + def _handle_int_list(self, rrkwargs, name, value, **kwargs): + rrkwargs[name.lower()] = [int(x) for x in value.split(',')] + + _handle_INTERVAL = _handle_int + _handle_COUNT = _handle_int + _handle_BYSETPOS = _handle_int_list + _handle_BYMONTH = _handle_int_list + _handle_BYMONTHDAY = _handle_int_list + _handle_BYYEARDAY = _handle_int_list + _handle_BYEASTER = _handle_int_list + _handle_BYWEEKNO = _handle_int_list + _handle_BYHOUR = _handle_int_list + _handle_BYMINUTE = _handle_int_list + _handle_BYSECOND = _handle_int_list + + def _handle_FREQ(self, rrkwargs, name, value, **kwargs): + rrkwargs["freq"] = self._freq_map[value] + + def _handle_UNTIL(self, rrkwargs, name, value, **kwargs): + global parser + if not parser: + from dateutil import parser + try: + rrkwargs["until"] = parser.parse(value, + ignoretz=kwargs.get("ignoretz"), + tzinfos=kwargs.get("tzinfos")) + except ValueError: + raise ValueError("invalid until date") + + def _handle_WKST(self, rrkwargs, name, value, **kwargs): + rrkwargs["wkst"] = self._weekday_map[value] + + def _handle_BYWEEKDAY(self, rrkwargs, name, value, **kwargs): + """ + Two ways to specify this: +1MO or MO(+1) + """ + l = [] + for wday in value.split(','): + if '(' in wday: + # If it's of the form TH(+1), etc. + splt = wday.split('(') + w = splt[0] + n = int(splt[1][:-1]) + elif len(wday): + # If it's of the form +1MO + for i in range(len(wday)): + if wday[i] not in '+-0123456789': + break + n = wday[:i] or None + w = wday[i:] + if n: + n = int(n) + else: + raise ValueError("Invalid (empty) BYDAY specification.") + + l.append(weekdays[self._weekday_map[w]](n)) + rrkwargs["byweekday"] = l + + _handle_BYDAY = _handle_BYWEEKDAY + + def _parse_rfc_rrule(self, line, + dtstart=None, + cache=False, + ignoretz=False, + tzinfos=None): + if line.find(':') != -1: + name, value = line.split(':') + if name != "RRULE": + raise ValueError("unknown parameter name") + else: + value = line + rrkwargs = {} + for pair in value.split(';'): + name, value = pair.split('=') + name = name.upper() + value = value.upper() + try: + getattr(self, "_handle_"+name)(rrkwargs, name, value, + ignoretz=ignoretz, + tzinfos=tzinfos) + except AttributeError: + raise ValueError("unknown parameter '%s'" % name) + except (KeyError, ValueError): + raise ValueError("invalid '%s': %s" % (name, value)) + return rrule(dtstart=dtstart, cache=cache, **rrkwargs) + + def _parse_date_value(self, date_value, parms, rule_tzids, + ignoretz, tzids, tzinfos): + global parser + if not parser: + from dateutil import parser + + datevals = [] + value_found = False + TZID = None + + for parm in parms: + if parm.startswith("TZID="): + try: + tzkey = rule_tzids[parm.split('TZID=')[-1]] + except KeyError: + continue + if tzids is None: + from . import tz + tzlookup = tz.gettz + elif callable(tzids): + tzlookup = tzids + else: + tzlookup = getattr(tzids, 'get', None) + if tzlookup is None: + msg = ('tzids must be a callable, mapping, or None, ' + 'not %s' % tzids) + raise ValueError(msg) + + TZID = tzlookup(tzkey) + continue + + # RFC 5445 3.8.2.4: The VALUE parameter is optional, but may be found + # only once. + if parm not in {"VALUE=DATE-TIME", "VALUE=DATE"}: + raise ValueError("unsupported parm: " + parm) + else: + if value_found: + msg = ("Duplicate value parameter found in: " + parm) + raise ValueError(msg) + value_found = True + + for datestr in date_value.split(','): + date = parser.parse(datestr, ignoretz=ignoretz, tzinfos=tzinfos) + if TZID is not None: + if date.tzinfo is None: + date = date.replace(tzinfo=TZID) + else: + raise ValueError('DTSTART/EXDATE specifies multiple timezone') + datevals.append(date) + + return datevals + + def _parse_rfc(self, s, + dtstart=None, + cache=False, + unfold=False, + forceset=False, + compatible=False, + ignoretz=False, + tzids=None, + tzinfos=None): + global parser + if compatible: + forceset = True + unfold = True + + TZID_NAMES = dict(map( + lambda x: (x.upper(), x), + re.findall('TZID=(?P[^:]+):', s) + )) + s = s.upper() + if not s.strip(): + raise ValueError("empty string") + if unfold: + lines = s.splitlines() + i = 0 + while i < len(lines): + line = lines[i].rstrip() + if not line: + del lines[i] + elif i > 0 and line[0] == " ": + lines[i-1] += line[1:] + del lines[i] + else: + i += 1 + else: + lines = s.split() + if (not forceset and len(lines) == 1 and (s.find(':') == -1 or + s.startswith('RRULE:'))): + return self._parse_rfc_rrule(lines[0], cache=cache, + dtstart=dtstart, ignoretz=ignoretz, + tzinfos=tzinfos) + else: + rrulevals = [] + rdatevals = [] + exrulevals = [] + exdatevals = [] + for line in lines: + if not line: + continue + if line.find(':') == -1: + name = "RRULE" + value = line + else: + name, value = line.split(':', 1) + parms = name.split(';') + if not parms: + raise ValueError("empty property name") + name = parms[0] + parms = parms[1:] + if name == "RRULE": + for parm in parms: + raise ValueError("unsupported RRULE parm: "+parm) + rrulevals.append(value) + elif name == "RDATE": + for parm in parms: + if parm != "VALUE=DATE-TIME": + raise ValueError("unsupported RDATE parm: "+parm) + rdatevals.append(value) + elif name == "EXRULE": + for parm in parms: + raise ValueError("unsupported EXRULE parm: "+parm) + exrulevals.append(value) + elif name == "EXDATE": + exdatevals.extend( + self._parse_date_value(value, parms, + TZID_NAMES, ignoretz, + tzids, tzinfos) + ) + elif name == "DTSTART": + dtvals = self._parse_date_value(value, parms, TZID_NAMES, + ignoretz, tzids, tzinfos) + if len(dtvals) != 1: + raise ValueError("Multiple DTSTART values specified:" + + value) + dtstart = dtvals[0] + else: + raise ValueError("unsupported property: "+name) + if (forceset or len(rrulevals) > 1 or rdatevals + or exrulevals or exdatevals): + if not parser and (rdatevals or exdatevals): + from dateutil import parser + rset = rruleset(cache=cache) + for value in rrulevals: + rset.rrule(self._parse_rfc_rrule(value, dtstart=dtstart, + ignoretz=ignoretz, + tzinfos=tzinfos)) + for value in rdatevals: + for datestr in value.split(','): + rset.rdate(parser.parse(datestr, + ignoretz=ignoretz, + tzinfos=tzinfos)) + for value in exrulevals: + rset.exrule(self._parse_rfc_rrule(value, dtstart=dtstart, + ignoretz=ignoretz, + tzinfos=tzinfos)) + for value in exdatevals: + rset.exdate(value) + if compatible and dtstart: + rset.rdate(dtstart) + return rset + else: + return self._parse_rfc_rrule(rrulevals[0], + dtstart=dtstart, + cache=cache, + ignoretz=ignoretz, + tzinfos=tzinfos) + + def __call__(self, s, **kwargs): + return self._parse_rfc(s, **kwargs) + + +rrulestr = _rrulestr() + +# vim:ts=4:sw=4:et diff --git a/TTS/Kokoro/.venv/Lib/site-packages/dateutil/tzwin.py b/TTS/Kokoro/.venv/Lib/site-packages/dateutil/tzwin.py new file mode 100644 index 0000000000000000000000000000000000000000..cebc673e40fc376653ebf037e96f0a6d0b33e906 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/dateutil/tzwin.py @@ -0,0 +1,2 @@ +# tzwin has moved to dateutil.tz.win +from .tz.win import * diff --git a/TTS/Kokoro/.venv/Lib/site-packages/dateutil/utils.py b/TTS/Kokoro/.venv/Lib/site-packages/dateutil/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..dd2d245a0bebcd5fc37ac20526aabbd5358dab0e --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/dateutil/utils.py @@ -0,0 +1,71 @@ +# -*- coding: utf-8 -*- +""" +This module offers general convenience and utility functions for dealing with +datetimes. + +.. versionadded:: 2.7.0 +""" +from __future__ import unicode_literals + +from datetime import datetime, time + + +def today(tzinfo=None): + """ + Returns a :py:class:`datetime` representing the current day at midnight + + :param tzinfo: + The time zone to attach (also used to determine the current day). + + :return: + A :py:class:`datetime.datetime` object representing the current day + at midnight. + """ + + dt = datetime.now(tzinfo) + return datetime.combine(dt.date(), time(0, tzinfo=tzinfo)) + + +def default_tzinfo(dt, tzinfo): + """ + Sets the ``tzinfo`` parameter on naive datetimes only + + This is useful for example when you are provided a datetime that may have + either an implicit or explicit time zone, such as when parsing a time zone + string. + + .. doctest:: + + >>> from dateutil.tz import tzoffset + >>> from dateutil.parser import parse + >>> from dateutil.utils import default_tzinfo + >>> dflt_tz = tzoffset("EST", -18000) + >>> print(default_tzinfo(parse('2014-01-01 12:30 UTC'), dflt_tz)) + 2014-01-01 12:30:00+00:00 + >>> print(default_tzinfo(parse('2014-01-01 12:30'), dflt_tz)) + 2014-01-01 12:30:00-05:00 + + :param dt: + The datetime on which to replace the time zone + + :param tzinfo: + The :py:class:`datetime.tzinfo` subclass instance to assign to + ``dt`` if (and only if) it is naive. + + :return: + Returns an aware :py:class:`datetime.datetime`. + """ + if dt.tzinfo is not None: + return dt + else: + return dt.replace(tzinfo=tzinfo) + + +def within_delta(dt1, dt2, delta): + """ + Useful for comparing two datetimes that may have a negligible difference + to be considered equal. + """ + delta = abs(delta) + difference = dt1 - dt2 + return -delta <= difference <= delta diff --git a/TTS/Kokoro/.venv/Lib/site-packages/dlinfo-2.0.0.dist-info/INSTALLER b/TTS/Kokoro/.venv/Lib/site-packages/dlinfo-2.0.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/dlinfo-2.0.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/TTS/Kokoro/.venv/Lib/site-packages/dlinfo-2.0.0.dist-info/LICENSE b/TTS/Kokoro/.venv/Lib/site-packages/dlinfo-2.0.0.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d11af6b56efc2364b5a7a150c9ad439602975d40 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/dlinfo-2.0.0.dist-info/LICENSE @@ -0,0 +1,7 @@ +Copyright 2019 Catalysts GmbH, a Cloudflight Company + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/TTS/Kokoro/.venv/Lib/site-packages/dlinfo-2.0.0.dist-info/METADATA b/TTS/Kokoro/.venv/Lib/site-packages/dlinfo-2.0.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..9022ea3e01aa5fa9434e335d6d323e87c1048e9d --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/dlinfo-2.0.0.dist-info/METADATA @@ -0,0 +1,43 @@ +Metadata-Version: 2.1 +Name: dlinfo +Version: 2.0.0 +Summary: Python wrapper for libc's dlinfo and dyld_find on Mac +Home-page: https://github.com/fphammerle/python-dlinfo +Maintainer: Fabian Peter Hammerle +Maintainer-email: fabian.dlinfo@hammerle.me +License: MIT +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Operating System :: MacOS :: MacOS X +Classifier: Operating System :: POSIX :: Linux +Requires-Python: >=3.9 +License-File: LICENSE + +python-dlinfo +============= + +Python wrapper for libc's dlinfo + +Install +------- + +.. code:: sh + + pip install dlinfo + # or + pipenv install dlinfo + +Usage +----- + +.. code:: python + + >>> from dlinfo import DLInfo + >>> lib = ctypes.cdll.LoadLibrary(ctypes.util.find_library('c')) + >>> dlinfo = DLInfo(lib) + >>> dlinfo.path + '/lib/x86_64-linux-gnu/libc.so.6' diff --git a/TTS/Kokoro/.venv/Lib/site-packages/dlinfo-2.0.0.dist-info/RECORD b/TTS/Kokoro/.venv/Lib/site-packages/dlinfo-2.0.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..1ef8328614997840b8deabb426b608ea542288cc --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/dlinfo-2.0.0.dist-info/RECORD @@ -0,0 +1,12 @@ +dlinfo-2.0.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +dlinfo-2.0.0.dist-info/LICENSE,sha256=H9hqUp3q1-1XMLNmCAu9EGZdWIkT_S2c5Q6zoWEJX7k,1098 +dlinfo-2.0.0.dist-info/METADATA,sha256=OAw2-t1rNPAdqmpKtRN5zSVjtH-f-_QPfHALsKaN8Tg,1070 +dlinfo-2.0.0.dist-info/RECORD,, +dlinfo-2.0.0.dist-info/WHEEL,sha256=2wepM1nk4DS4eFpYrW1TTqPcoGNfHhhO_i5m4cOimbo,92 +dlinfo-2.0.0.dist-info/top_level.txt,sha256=JZ0mAh2JRPwKUx0iZgbGA9bPo3zUXdZ7JLWl4TAUxiE,7 +dlinfo/__init__.py,sha256=muJlk1jFQBz5e70hI5N8ntlaKybPu4890HoRu1MKZ_M,192 +dlinfo/__pycache__/__init__.cpython-312.pyc,, +dlinfo/__pycache__/_glibc.cpython-312.pyc,, +dlinfo/__pycache__/_macosx.cpython-312.pyc,, +dlinfo/_glibc.py,sha256=PYEb2ZLL29xAodLRHaCcu2Bg3F7lLMyxI1Fqw93dKqo,1278 +dlinfo/_macosx.py,sha256=h8lOieLm7-hoIYhzipyFHuj52JGewYVAvGafwcYoAWI,523 diff --git a/TTS/Kokoro/.venv/Lib/site-packages/dlinfo-2.0.0.dist-info/WHEEL b/TTS/Kokoro/.venv/Lib/site-packages/dlinfo-2.0.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..57e3d840d59a650ac5bccbad5baeec47d155f0ad --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/dlinfo-2.0.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.38.4) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/TTS/Kokoro/.venv/Lib/site-packages/dlinfo-2.0.0.dist-info/top_level.txt b/TTS/Kokoro/.venv/Lib/site-packages/dlinfo-2.0.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..2b64bdc01719e834fd16dd5aeba7311785a4bdf5 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/dlinfo-2.0.0.dist-info/top_level.txt @@ -0,0 +1 @@ +dlinfo diff --git a/TTS/Kokoro/.venv/Lib/site-packages/dlinfo/__init__.py b/TTS/Kokoro/.venv/Lib/site-packages/dlinfo/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1dfcd87a7e6e290d78ee0840a256de187579b40a --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/dlinfo/__init__.py @@ -0,0 +1,9 @@ +__all__ = ['DLInfo'] + +import sys + +# pylint: disable=import-private-name; internal +if sys.platform == 'darwin': + from dlinfo._macosx import DLInfo +else: + from dlinfo._glibc import DLInfo diff --git a/TTS/Kokoro/.venv/Lib/site-packages/dlinfo/_glibc.py b/TTS/Kokoro/.venv/Lib/site-packages/dlinfo/_glibc.py new file mode 100644 index 0000000000000000000000000000000000000000..88cb089929712bf6a4561eafc6fe0aebaeba2283 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/dlinfo/_glibc.py @@ -0,0 +1,44 @@ +import ctypes +import ctypes.util +import sys + +# dlfcn.h +_RTLD_DI_LINKMAP = 2 + + +class _LinkMap(ctypes.Structure): # pylint: disable=too-few-public-methods + # link.h + _fields_ = [ + ('l_addr', ctypes.c_void_p), + ('l_name', ctypes.c_char_p), + ('l_ld', ctypes.c_void_p), + ('l_next', ctypes.c_void_p), + ('l_previous', ctypes.c_void_p), + ] + + +_LIBDL = ctypes.cdll.LoadLibrary(ctypes.util.find_library('dl')) +_DLINFO = _LIBDL.dlinfo +_DLINFO.argtypes = ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p +_DLINFO.restype = ctypes.c_int + + +class DLInfo: # pylint: disable=too-few-public-methods + + """ + >>> lib = ctypes.cdll.LoadLibrary(ctypes.util.find_library('c')) + >>> dlinfo = DLInfo(lib) + >>> dlinfo.path + '/lib/x86_64-linux-gnu/libc.so.6' + """ + + def __init__(self, cdll: ctypes.CDLL): + _linkmap = ctypes.c_void_p() + # pylint: disable=protected-access + if _DLINFO(cdll._handle, _RTLD_DI_LINKMAP, ctypes.byref(_linkmap)) != 0: # pragma: no cover + raise RuntimeError(f"dlinfo on {cdll._name} failed") + self._linkmap = ctypes.cast(_linkmap, ctypes.POINTER(_LinkMap)) + + @property + def path(self) -> str: + return self._linkmap.contents.l_name.decode(sys.getdefaultencoding()) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/dlinfo/_macosx.py b/TTS/Kokoro/.venv/Lib/site-packages/dlinfo/_macosx.py new file mode 100644 index 0000000000000000000000000000000000000000..cb559e0336d7ab3d9fc4706a5379335772b973a4 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/dlinfo/_macosx.py @@ -0,0 +1,21 @@ +import ctypes +# pylint: disable=import-error,no-name-in-module +from ctypes.macholib.dyld import dyld_find + + +class DLInfo: # pylint: disable=too-few-public-methods + + """ + >>> lib = ctypes.cdll.LoadLibrary(ctypes.util.find_library('c')) + >>> dlinfo = DLInfo(lib) + >>> dlinfo.path + '/usr/lib/libc.dylib' + """ + + def __init__(self, cdll: ctypes.CDLL): + self._cdll = cdll + + @property + def path(self) -> str: + # pylint: disable=protected-access + return dyld_find(self._cdll._name) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/docopt-0.6.2.dist-info/INSTALLER b/TTS/Kokoro/.venv/Lib/site-packages/docopt-0.6.2.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/docopt-0.6.2.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/TTS/Kokoro/.venv/Lib/site-packages/docopt-0.6.2.dist-info/METADATA b/TTS/Kokoro/.venv/Lib/site-packages/docopt-0.6.2.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..c834a5df58cef931249c880cb86c1b7b8de9d50e --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/docopt-0.6.2.dist-info/METADATA @@ -0,0 +1,476 @@ +Metadata-Version: 2.4 +Name: docopt +Version: 0.6.2 +Summary: Pythonic argument parser, that will make you smile +Home-page: http://docopt.org +Author: Vladimir Keleshev +Author-email: vladimir@keleshev.com +License: MIT +Keywords: option arguments parsing optparse argparse getopt +Classifier: Development Status :: 3 - Alpha +Classifier: Topic :: Utilities +Classifier: Programming Language :: Python :: 2.5 +Classifier: Programming Language :: Python :: 2.6 +Classifier: Programming Language :: Python :: 2.7 +Classifier: Programming Language :: Python :: 3.2 +Classifier: Programming Language :: Python :: 3.3 +Classifier: License :: OSI Approved :: MIT License +License-File: LICENSE-MIT +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: home-page +Dynamic: keywords +Dynamic: license +Dynamic: license-file +Dynamic: summary + +``docopt`` creates *beautiful* command-line interfaces +====================================================================== + +Video introduction to **docopt**: `PyCon UK 2012: Create *beautiful* +command-line interfaces with Python `_ + + New in version 0.6.1: + + - Fix issue `#85 `_ + which caused improper handling of ``[options]`` shortcut + if it was present several times. + + New in version 0.6.0: + + - New argument ``options_first``, disallows interspersing options + and arguments. If you supply ``options_first=True`` to + ``docopt``, it will interpret all arguments as positional + arguments after first positional argument. + + - If option with argument could be repeated, its default value + will be interpreted as space-separated list. E.g. with + ``[default: ./here ./there]`` will be interpreted as + ``['./here', './there']``. + + Breaking changes: + + - Meaning of ``[options]`` shortcut slightly changed. Previously + it ment *"any known option"*. Now it means *"any option not in + usage-pattern"*. This avoids the situation when an option is + allowed to be repeated unintentionaly. + + - ``argv`` is ``None`` by default, not ``sys.argv[1:]``. + This allows ``docopt`` to always use the *latest* ``sys.argv``, + not ``sys.argv`` during import time. + +Isn't it awesome how ``optparse`` and ``argparse`` generate help +messages based on your code?! + +*Hell no!* You know what's awesome? It's when the option parser *is* +generated based on the beautiful help message that you write yourself! +This way you don't need to write this stupid repeatable parser-code, +and instead can write only the help message--*the way you want it*. + +**docopt** helps you create most beautiful command-line interfaces +*easily*: + +.. code:: python + + """Naval Fate. + + Usage: + naval_fate.py ship new ... + naval_fate.py ship move [--speed=] + naval_fate.py ship shoot + naval_fate.py mine (set|remove) [--moored | --drifting] + naval_fate.py (-h | --help) + naval_fate.py --version + + Options: + -h --help Show this screen. + --version Show version. + --speed= Speed in knots [default: 10]. + --moored Moored (anchored) mine. + --drifting Drifting mine. + + """ + from docopt import docopt + + + if __name__ == '__main__': + arguments = docopt(__doc__, version='Naval Fate 2.0') + print(arguments) + +Beat that! The option parser is generated based on the docstring above +that is passed to ``docopt`` function. ``docopt`` parses the usage +pattern (``"Usage: ..."``) and option descriptions (lines starting +with dash "``-``") and ensures that the program invocation matches the +usage pattern; it parses options, arguments and commands based on +that. The basic idea is that *a good help message has all necessary +information in it to make a parser*. + +Also, `PEP 257 `_ recommends +putting help message in the module docstrings. + +Installation +====================================================================== + +Use `pip `_ or easy_install:: + + pip install docopt==0.6.2 + +Alternatively, you can just drop ``docopt.py`` file into your +project--it is self-contained. + +**docopt** is tested with Python 2.5, 2.6, 2.7, 3.2, 3.3 and PyPy. + +API +====================================================================== + +.. code:: python + + from docopt import docopt + +.. code:: python + + docopt(doc, argv=None, help=True, version=None, options_first=False) + +``docopt`` takes 1 required and 4 optional arguments: + +- ``doc`` could be a module docstring (``__doc__``) or some other + string that contains a **help message** that will be parsed to + create the option parser. The simple rules of how to write such a + help message are given in next sections. Here is a quick example of + such a string: + +.. code:: python + + """Usage: my_program.py [-hso FILE] [--quiet | --verbose] [INPUT ...] + + -h --help show this + -s --sorted sorted output + -o FILE specify output file [default: ./test.txt] + --quiet print less text + --verbose print more text + + """ + +- ``argv`` is an optional argument vector; by default ``docopt`` uses + the argument vector passed to your program (``sys.argv[1:]``). + Alternatively you can supply a list of strings like ``['--verbose', + '-o', 'hai.txt']``. + +- ``help``, by default ``True``, specifies whether the parser should + automatically print the help message (supplied as ``doc``) and + terminate, in case ``-h`` or ``--help`` option is encountered + (options should exist in usage pattern, more on that below). If you + want to handle ``-h`` or ``--help`` options manually (as other + options), set ``help=False``. + +- ``version``, by default ``None``, is an optional argument that + specifies the version of your program. If supplied, then, (assuming + ``--version`` option is mentioned in usage pattern) when parser + encounters the ``--version`` option, it will print the supplied + version and terminate. ``version`` could be any printable object, + but most likely a string, e.g. ``"2.1.0rc1"``. + + Note, when ``docopt`` is set to automatically handle ``-h``, + ``--help`` and ``--version`` options, you still need to mention + them in usage pattern for this to work. Also, for your users to + know about them. + +- ``options_first``, by default ``False``. If set to ``True`` will + disallow mixing options and positional argument. I.e. after first + positional argument, all arguments will be interpreted as positional + even if the look like options. This can be used for strict + compatibility with POSIX, or if you want to dispatch your arguments + to other programs. + +The **return** value is a simple dictionary with options, arguments +and commands as keys, spelled exactly like in your help message. Long +versions of options are given priority. For example, if you invoke the +top example as:: + + naval_fate.py ship Guardian move 100 150 --speed=15 + +the return dictionary will be: + +.. code:: python + + {'--drifting': False, 'mine': False, + '--help': False, 'move': True, + '--moored': False, 'new': False, + '--speed': '15', 'remove': False, + '--version': False, 'set': False, + '': ['Guardian'], 'ship': True, + '': '100', 'shoot': False, + '': '150'} + +Help message format +====================================================================== + +Help message consists of 2 parts: + +- Usage pattern, e.g.:: + + Usage: my_program.py [-hso FILE] [--quiet | --verbose] [INPUT ...] + +- Option descriptions, e.g.:: + + -h --help show this + -s --sorted sorted output + -o FILE specify output file [default: ./test.txt] + --quiet print less text + --verbose print more text + +Their format is described below; other text is ignored. + +Usage pattern format +---------------------------------------------------------------------- + +**Usage pattern** is a substring of ``doc`` that starts with +``usage:`` (case *insensitive*) and ends with a *visibly* empty line. +Minimum example: + +.. code:: python + + """Usage: my_program.py + + """ + +The first word after ``usage:`` is interpreted as your program's name. +You can specify your program's name several times to signify several +exclusive patterns: + +.. code:: python + + """Usage: my_program.py FILE + my_program.py COUNT FILE + + """ + +Each pattern can consist of the following elements: + +- ****, **ARGUMENTS**. Arguments are specified as either + upper-case words, e.g. ``my_program.py CONTENT-PATH`` or words + surrounded by angular brackets: ``my_program.py ``. +- **--options**. Options are words started with dash (``-``), e.g. + ``--output``, ``-o``. You can "stack" several of one-letter + options, e.g. ``-oiv`` which will be the same as ``-o -i -v``. The + options can have arguments, e.g. ``--input=FILE`` or ``-i FILE`` or + even ``-iFILE``. However it is important that you specify option + descriptions if you want for option to have an argument, a default + value, or specify synonymous short/long versions of option (see next + section on option descriptions). +- **commands** are words that do *not* follow the described above + conventions of ``--options`` or ```` or ``ARGUMENTS``, + plus two special commands: dash "``-``" and double dash "``--``" + (see below). + +Use the following constructs to specify patterns: + +- **[ ]** (brackets) **optional** elements. e.g.: ``my_program.py + [-hvqo FILE]`` +- **( )** (parens) **required** elements. All elements that are *not* + put in **[ ]** are also required, e.g.: ``my_program.py + --path= ...`` is the same as ``my_program.py + (--path= ...)``. (Note, "required options" might be not + a good idea for your users). +- **|** (pipe) **mutualy exclusive** elements. Group them using **( + )** if one of the mutually exclusive elements is required: + ``my_program.py (--clockwise | --counter-clockwise) TIME``. Group + them using **[ ]** if none of the mutually-exclusive elements are + required: ``my_program.py [--left | --right]``. +- **...** (ellipsis) **one or more** elements. To specify that + arbitrary number of repeating elements could be accepted, use + ellipsis (``...``), e.g. ``my_program.py FILE ...`` means one or + more ``FILE``-s are accepted. If you want to accept zero or more + elements, use brackets, e.g.: ``my_program.py [FILE ...]``. Ellipsis + works as a unary operator on the expression to the left. +- **[options]** (case sensitive) shortcut for any options. You can + use it if you want to specify that the usage pattern could be + provided with any options defined below in the option-descriptions + and do not want to enumerate them all in usage-pattern. - + "``[--]``". Double dash "``--``" is used by convention to separate + positional arguments that can be mistaken for options. In order to + support this convention add "``[--]``" to you usage patterns. - + "``[-]``". Single dash "``-``" is used by convention to signify that + ``stdin`` is used instead of a file. To support this add "``[-]``" + to you usage patterns. "``-``" act as a normal command. + +If your pattern allows to match argument-less option (a flag) several +times:: + + Usage: my_program.py [-v | -vv | -vvv] + +then number of occurences of the option will be counted. I.e. +``args['-v']`` will be ``2`` if program was invoked as ``my_program +-vv``. Same works for commands. + +If your usage patterns allows to match same-named option with argument +or positional argument several times, the matched arguments will be +collected into a list:: + + Usage: my_program.py --path=... + +I.e. invoked with ``my_program.py file1 file2 --path=./here +--path=./there`` the returned dict will contain ``args[''] == +['file1', 'file2']`` and ``args['--path'] == ['./here', './there']``. + + +Option descriptions format +---------------------------------------------------------------------- + +**Option descriptions** consist of a list of options that you put +below your usage patterns. + +It is necessary to list option descriptions in order to specify: + +- synonymous short and long options, +- if an option has an argument, +- if option's argument has a default value. + +The rules are as follows: + +- Every line in ``doc`` that starts with ``-`` or ``--`` (not counting + spaces) is treated as an option description, e.g.:: + + Options: + --verbose # GOOD + -o FILE # GOOD + Other: --bad # BAD, line does not start with dash "-" + +- To specify that option has an argument, put a word describing that + argument after space (or equals "``=``" sign) as shown below. Follow + either or UPPER-CASE convention for options' + arguments. You can use comma if you want to separate options. In + the example below, both lines are valid, however you are recommended + to stick to a single style.:: + + -o FILE --output=FILE # without comma, with "=" sign + -i , --input # with comma, wihtout "=" sing + +- Use two spaces to separate options with their informal description:: + + --verbose More text. # BAD, will be treated as if verbose option had + # an argument "More", so use 2 spaces instead + -q Quit. # GOOD + -o FILE Output file. # GOOD + --stdout Use stdout. # GOOD, 2 spaces + +- If you want to set a default value for an option with an argument, + put it into the option-description, in form ``[default: + ]``:: + + --coefficient=K The K coefficient [default: 2.95] + --output=FILE Output file [default: test.txt] + --directory=DIR Some directory [default: ./] + +- If the option is not repeatable, the value inside ``[default: ...]`` + will be interpeted as string. If it *is* repeatable, it will be + splited into a list on whitespace:: + + Usage: my_program.py [--repeatable= --repeatable=] + [--another-repeatable=]... + [--not-repeatable=] + + # will be ['./here', './there'] + --repeatable= [default: ./here ./there] + + # will be ['./here'] + --another-repeatable= [default: ./here] + + # will be './here ./there', because it is not repeatable + --not-repeatable= [default: ./here ./there] + +Examples +---------------------------------------------------------------------- + +We have an extensive list of `examples +`_ which cover +every aspect of functionality of **docopt**. Try them out, read the +source if in doubt. + +Subparsers, multi-level help and *huge* applications (like git) +---------------------------------------------------------------------- + +If you want to split your usage-pattern into several, implement +multi-level help (whith separate help-screen for each subcommand), +want to interface with existing scripts that don't use **docopt**, or +you're building the next "git", you will need the new ``options_first`` +parameter (described in API section above). To get you started quickly +we implemented a subset of git command-line interface as an example: +`examples/git +`_ + + +Data validation +---------------------------------------------------------------------- + +**docopt** does one thing and does it well: it implements your +command-line interface. However it does not validate the input data. +On the other hand there are libraries like `python schema +`_ which make validating data a +breeze. Take a look at `validation_example.py +`_ +which uses **schema** to validate data and report an error to the +user. + +Development +====================================================================== + +We would *love* to hear what you think about **docopt** on our `issues +page `_ + +Make pull requrests, report bugs, suggest ideas and discuss +**docopt**. You can also drop a line directly to +. + +Porting ``docopt`` to other languages +====================================================================== + +We think **docopt** is so good, we want to share it beyond the Python +community! + +The follosing ports are available: + +- `Ruby port `_ +- `CoffeeScript port `_ +- `Lua port `_ +- `PHP port `_ + +But you can always create a port for your favorite language! You are +encouraged to use the Python version as a reference implementation. A +Language-agnostic test suite is bundled with `Python implementation +`_. + +Porting discussion is on `issues page +`_. + +Changelog +====================================================================== + +**docopt** follows `semantic versioning `_. The +first release with stable API will be 1.0.0 (soon). Until then, you +are encouraged to specify explicitly the version in your dependency +tools, e.g.:: + + pip install docopt==0.6.2 + +- 0.6.2 `Wheel `_ support. +- 0.6.1 Bugfix release. +- 0.6.0 ``options_first`` parameter. + **Breaking changes**: Corrected ``[options]`` meaning. + ``argv`` defaults to ``None``. +- 0.5.0 Repeated options/commands are counted or accumulated into a + list. +- 0.4.2 Bugfix release. +- 0.4.0 Option descriptions become optional, + support for "``--``" and "``-``" commands. +- 0.3.0 Support for (sub)commands like `git remote add`. + Introduce ``[options]`` shortcut for any options. + **Breaking changes**: ``docopt`` returns dictionary. +- 0.2.0 Usage pattern matching. Positional arguments parsing based on + usage patterns. + **Breaking changes**: ``docopt`` returns namespace (for arguments), + not list. Usage pattern is formalized. +- 0.1.0 Initial release. Options-parsing only (based on options + description). diff --git a/TTS/Kokoro/.venv/Lib/site-packages/docopt-0.6.2.dist-info/RECORD b/TTS/Kokoro/.venv/Lib/site-packages/docopt-0.6.2.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..b19cffefb49f23a62c0a3467de8c5fb9a4c2458b --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/docopt-0.6.2.dist-info/RECORD @@ -0,0 +1,8 @@ +__pycache__/docopt.cpython-312.pyc,, +docopt-0.6.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +docopt-0.6.2.dist-info/METADATA,sha256=j9w9jha0HcvU9brgebVqvwkWUByd3y6YDmlxtrlMTtU,18584 +docopt-0.6.2.dist-info/RECORD,, +docopt-0.6.2.dist-info/WHEEL,sha256=uC7DnXjtoKy23CNUXRq6ohLsm8FbS2C_ECfYYzqZHVY,109 +docopt-0.6.2.dist-info/licenses/LICENSE-MIT,sha256=PV33j1kv8kM8PGzkmECRt_SXBZ3bjGsIoGG6SON7Z_I,1097 +docopt-0.6.2.dist-info/top_level.txt,sha256=xAvL2ywTOdLde8wxTVye1299j65YdK3cM5963wNy5SU,7 +docopt.py,sha256=RMZQ69gz2FLIcx-j8MV1lQYwliIwDkwZVKVA14VyzFQ,19946 diff --git a/TTS/Kokoro/.venv/Lib/site-packages/docopt-0.6.2.dist-info/WHEEL b/TTS/Kokoro/.venv/Lib/site-packages/docopt-0.6.2.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..d621b60efac08a13ac5aa02530b59aca57daa1ad --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/docopt-0.6.2.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: setuptools (82.0.0) +Root-Is-Purelib: true +Tag: py2-none-any +Tag: py3-none-any + diff --git a/TTS/Kokoro/.venv/Lib/site-packages/docopt-0.6.2.dist-info/top_level.txt b/TTS/Kokoro/.venv/Lib/site-packages/docopt-0.6.2.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..e5ed2a091377ac8e9dd079b53b18a89fbf93a2ab --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/docopt-0.6.2.dist-info/top_level.txt @@ -0,0 +1 @@ +docopt diff --git a/TTS/Kokoro/.venv/Lib/site-packages/espeakng_loader-0.2.4.dist-info/INSTALLER b/TTS/Kokoro/.venv/Lib/site-packages/espeakng_loader-0.2.4.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/espeakng_loader-0.2.4.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/TTS/Kokoro/.venv/Lib/site-packages/espeakng_loader-0.2.4.dist-info/METADATA b/TTS/Kokoro/.venv/Lib/site-packages/espeakng_loader-0.2.4.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..0aea8e9dae3958244baf46e6fd531a54d0b84b16 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/espeakng_loader-0.2.4.dist-info/METADATA @@ -0,0 +1,49 @@ +Metadata-Version: 2.4 +Name: espeakng-loader +Version: 0.2.4 +Summary: A Python package that provides shared library loader for eSpeak NG +Author-email: thewh1teagle <61390950+thewh1teagle@users.noreply.github.com> +Requires-Python: >=3.6 +Description-Content-Type: text/markdown + +# espeakng-loader + +This package loads the espeak-ng shared library so it will be available for other libraries. + +## Platforms + +- Linux (x86-64, arm64) +- Windows (x86-64, arm64) +- macOS (x86-64, arm) + +## Install + +```console +pip install espeakng-loader +``` + +## Usage + +```python +from espeakng_loader import get_library_path, load_library, make_library_available + +library_path = get_library_path() # Pass it to the library +# Or use load_library() for load it directly +# Or use make_library_available() for making it available for other libraries +``` + +## Usage with [phonemizer](https://github.com/bootphon/phonemizer) + +Note: please use `phonemizer-fork` instead of `phonemizer` package until [#191](https://github.com/bootphon/phonemizer/pull/191) merged. + +```python +from phonemizer.backend.espeak.wrapper import EspeakWrapper +from phonemizer import phonemize +import espeakng_loader + +EspeakWrapper.set_library(espeakng_loader.get_library_path()) +EspeakWrapper.set_data_path(espeakng_loader.get_data_path()) + +phonemes = phonemize('Hello') +print('Phonemes: ', phonemes) +``` diff --git a/TTS/Kokoro/.venv/Lib/site-packages/espeakng_loader-0.2.4.dist-info/RECORD b/TTS/Kokoro/.venv/Lib/site-packages/espeakng_loader-0.2.4.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..0615cddda910478d621dbabd66ab13bdafed80c3 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/espeakng_loader-0.2.4.dist-info/RECORD @@ -0,0 +1,371 @@ +espeakng_loader-0.2.4.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +espeakng_loader-0.2.4.dist-info/METADATA,sha256=3XpK_eu-Ib5czneyLacsd52juhXhuafdK9QB1Of1FO4,1343 +espeakng_loader-0.2.4.dist-info/RECORD,, +espeakng_loader-0.2.4.dist-info/WHEEL,sha256=Vhj7RpPOKCXcsr4rUs7q4pISuo5nT6VsOuaQwH9GILY,94 +espeakng_loader/__init__.py,sha256=PxXwxKrj97puXbgUCPJZmF5RX30L53QGCWoZ0inAVIs,1527 +espeakng_loader/__pycache__/__init__.cpython-312.pyc,, +espeakng_loader/espeak-ng-data/af_dict,sha256=JXKdO_TEoPCNpgrqnrWgzzUmMPg_qxqww5Vbd0DaF3Y,121473 +espeakng_loader/espeak-ng-data/am_dict,sha256=mVQ2WGBoLHVsjERZV306oKt3rQy6Z5i3RgM62lw9S-o,63878 +espeakng_loader/espeak-ng-data/an_dict,sha256=bPOM7bZpOq3knlpdJ6PJJRalM1Elv4X8rlgoLmb7gv0,6691 +espeakng_loader/espeak-ng-data/ar_dict,sha256=cjFkJueXd3_k35Qgk1o7anmzfX4_OUhTe6cc17IbJUE,478165 +espeakng_loader/espeak-ng-data/as_dict,sha256=D5yffphTDbZqpumIou4I6KDwp-CWk7zs_LkLXLZ9_xA,5005 +espeakng_loader/espeak-ng-data/az_dict,sha256=41Ky3PgRZi159L6qoMd1BwbPZpwECf2BWpvQJEsa38c,43773 +espeakng_loader/espeak-ng-data/ba_dict,sha256=JGyMZVzu1D2f9Epl3l-TPxYlVInQsYGxpGqD4f1aA1Q,2098 +espeakng_loader/espeak-ng-data/be_dict,sha256=Iy-w3r_I_cqbjySUdw_yNTX3-Ie767AXir_8JDSQ55g,2652 +espeakng_loader/espeak-ng-data/bg_dict,sha256=j6Ot7I4Yo-aVsrvqHUeAGC4XIi2Ln42pkIojeCj2sGM,87051 +espeakng_loader/espeak-ng-data/bn_dict,sha256=Vipk7F6jGWIuwihsED1BECIqFxISmjqfB_LqFKZgA4o,89979 +espeakng_loader/espeak-ng-data/bpy_dict,sha256=pDIdm6gL1g9J4L7lquV_GunEm3ocPUujhDOP6b87apI,5226 +espeakng_loader/espeak-ng-data/bs_dict,sha256=1d9WT1Ea8IKIRxloXbhuxN8jRnzwEs4l6JhUC6-d5ls,47068 +espeakng_loader/espeak-ng-data/ca_dict,sha256=WfD5TQPLY0GhuVL_c12PDQyxATalk0YlWNt8_I7lMY0,310331 +espeakng_loader/espeak-ng-data/chr_dict,sha256=GFOYDGcwFTJ77T1OX36Iwu472KkivN0jKmSXJ36QO84,2859 +espeakng_loader/espeak-ng-data/cmn_dict,sha256=KkHdq3IT0ChKmE3va0DHLLxAs0bTIg2wjGrjJPRtWao,1566347 +espeakng_loader/espeak-ng-data/cs_dict,sha256=YeZJzfAznp6CSL3N-oixnCzRKe8h5TCt_hhgEVQgaB0,50455 +espeakng_loader/espeak-ng-data/cv_dict,sha256=gmCDfI8Y--WHCQXrsoUN_RjiUhUK1shouW2dLGOY6oo,1344 +espeakng_loader/espeak-ng-data/cy_dict,sha256=MddMytIYq4C3lWbK640hvPD-QzJu18Q3-nNtObheYD4,43130 +espeakng_loader/espeak-ng-data/da_dict,sha256=rmwt1PD004NCkYp3ap4sRtkZVy8CM2yGT4Q_97Jiyvg,245287 +espeakng_loader/espeak-ng-data/de_dict,sha256=dV2cqwAwWwTAdBQZkO8DORkYNd50bfoHSTbhlPOlrVQ,69277 +espeakng_loader/espeak-ng-data/el_dict,sha256=XZ91l1ATHad30v1PBqpgLtdG048nuE3ZotSlUPLNRS4,72841 +espeakng_loader/espeak-ng-data/en_dict,sha256=EFP3SjSvOKu2-9ZLeDjay8ZVpofEjOG7Zj02ShJ7Bd4,168204 +espeakng_loader/espeak-ng-data/eo_dict,sha256=hJ8GGr3dU4i6wRKzLm9790fhXhs65T_pEHk4Hv__TMk,4666 +espeakng_loader/espeak-ng-data/es_dict,sha256=58Y0fkB9XBTyg-6toYuGxtVgsDti9TZZRzEJu_8JZ1c,49285 +espeakng_loader/espeak-ng-data/et_dict,sha256=Gmc0tOa8nemkyUz7Q0hz4Kf0rk7IlUmzE3rlSRz2Vdo,44263 +espeakng_loader/espeak-ng-data/eu_dict,sha256=dipu_2NVLvcs2Ivx6S3FqCPrN41Qy4XHkX6MW7oHkTc,48841 +espeakng_loader/espeak-ng-data/fa_dict,sha256=46pudRo0TaeSSw7YceBqavsFP2v-h9_XkU_6JOkM0Dw,292907 +espeakng_loader/espeak-ng-data/fi_dict,sha256=3amZQ3vUs3p_dACiIwqs4SAKUpBqsLH_NQfUSrGdZLE,43928 +espeakng_loader/espeak-ng-data/fr_dict,sha256=45mrkkxNEL7vH8MQsw6lbk3f2LS2S47ZeOnGU5TUmy0,63727 +espeakng_loader/espeak-ng-data/ga_dict,sha256=stsD0h95ALaX19u4vshVzREX6YZ_GYhPrxHE32JmWfU,52673 +espeakng_loader/espeak-ng-data/gd_dict,sha256=6StH3PmgATY__uHmKGP68mT_XxbhDNnPHx6DyonKFKo,49121 +espeakng_loader/espeak-ng-data/gn_dict,sha256=dkDfJysZKmi6QBKUv5GXq0bQsUHaejWK0Zhuf3fn8po,3248 +espeakng_loader/espeak-ng-data/grc_dict,sha256=SId5STmT0iGwnnE-EEoiGsG7NXZfgmrMJtPTwao6Ne0,3433 +espeakng_loader/espeak-ng-data/gu_dict,sha256=yx-_tTurLsbZ5EzZ0SzLm4DeSfJ013IxQ4nEd-71MP0,82480 +espeakng_loader/espeak-ng-data/hak_dict,sha256=4wdcfSgflaLOImTAHtvQnpYss-0pQAdmxdIRagihhcg,3335 +espeakng_loader/espeak-ng-data/haw_dict,sha256=K053thyt_F7mIqqLHSOUHjYQHZvb-NgJ4PobRC0sP3Q,2443 +espeakng_loader/espeak-ng-data/he_dict,sha256=8YxArQp2EknRzNACEMA4s_Y6lIUYIZYkxvW6oZ6Sg8g,10665 +espeakng_loader/espeak-ng-data/hi_dict,sha256=WmjJUyYk5XrIRbJs4eLlA0xPY1O-3kbsvlflg-yO_9Y,92143 +espeakng_loader/espeak-ng-data/hr_dict,sha256=X5j88F-XM1pUNqipZDZ32m8Vjyqe4dQb3aFyWxuzUn4,49388 +espeakng_loader/espeak-ng-data/ht_dict,sha256=1XchnRXCk5bbJUrtlYNYRW7BUBzfYstMpUE3UvLufME,1803 +espeakng_loader/espeak-ng-data/hu_dict,sha256=-eOlF0zonEjK-Thlvc4qfZL6PaCdQUdmgCBULtvoe4c,177886 +espeakng_loader/espeak-ng-data/hy_dict,sha256=i4CK2PHUyuMrO3hbltHiezryjjL03d_tfJPhKdY7JYc,62263 +espeakng_loader/espeak-ng-data/ia_dict,sha256=HGZWA6gr64HgzvKHjJtEZCrm1RnjAfu9BjJuAzJf6_M,331275 +espeakng_loader/espeak-ng-data/id_dict,sha256=j7PyP4D3HwIyGc7nAyIj8_aIbMUEDrTIxQf3nRuE6Y0,43458 +espeakng_loader/espeak-ng-data/intonations,sha256=AxoQW_a7LrzXOixXnM-0JGmycmbbAHivZa4pj9NYiyE,2312 +espeakng_loader/espeak-ng-data/io_dict,sha256=DZ1plf6tHM3VUS95CeyPnvyMzJf1ydI-yuazunf_rb8,2165 +espeakng_loader/espeak-ng-data/is_dict,sha256=juq1sco_dTYogfrj3jMW_K_ygReaTFH86wCY8R6tluA,44354 +espeakng_loader/espeak-ng-data/it_dict,sha256=fOW2tOLuJRUWcIWEJnpBOjwCsvoHy1J6LrQh-7s7Es8,154408 +espeakng_loader/espeak-ng-data/ja_dict,sha256=NQhLgWohsnUQUWWf6HFo6yOXBwvaF14Eo8h5KqCHq0I,47652 +espeakng_loader/espeak-ng-data/jbo_dict,sha256=cSmEF94eX9B98nUnCl1Hyoggy4yfXcIVbAcLejrnmZw,2243 +espeakng_loader/espeak-ng-data/ka_dict,sha256=yGJJRxEKE77nLU_BWwYCYATfP0DBbHuRfSfjacoSKjI,87775 +espeakng_loader/espeak-ng-data/kk_dict,sha256=iNwBBmKaV9CspQc6-xHbGgRHmRhTVQiKetQzHINq_9M,1859 +espeakng_loader/espeak-ng-data/kl_dict,sha256=7EQZZNf71GIrtigyeQPVxsmZyV1Tmy4GGITez5WsMOM,2838 +espeakng_loader/espeak-ng-data/kn_dict,sha256=xR4DhZN7QHs2wC_SyF3-zcXKxBE5juinTsoVs1YXr2Q,87828 +espeakng_loader/espeak-ng-data/ko_dict,sha256=ejOK7f1_nAleXfWAvtXufG7HNAKypFiBoj4qMPKvZK8,47523 +espeakng_loader/espeak-ng-data/kok_dict,sha256=UmWd7AHRsRm_71a2IkMPVSXFCvAUTJ-WiMs8IswC7TE,6394 +espeakng_loader/espeak-ng-data/ku_dict,sha256=Zd4cVCno0ZN3Wzb88WmmD7u5lk7xOkobq3_wzoVcrSA,2265 +espeakng_loader/espeak-ng-data/ky_dict,sha256=3vRCf9QHBnPAc7iSx7Ip-MPxfrHfNr6i7HGI3c-00Oo,64977 +espeakng_loader/espeak-ng-data/la_dict,sha256=F4GN1WeTb94DJAT7vWF3hEufX8WpFUgPVnJyFHk2-Rc,3806 +espeakng_loader/espeak-ng-data/lang/aav/vi,sha256=MZnJgPniOoiiqmk81jG_T8sPNAjEJyvAG3rA_45513g,111 +espeakng_loader/espeak-ng-data/lang/aav/vi-VN-x-central,sha256=s1HxPG7Q2jdWHfJfRVeYcv-YY5IK1muU4nMnosYRdVs,143 +espeakng_loader/espeak-ng-data/lang/aav/vi-VN-x-south,sha256=wKCiyJTNV7C7rPnvTvuNib-vn-sWSDDhU59ZnnzE4CE,142 +espeakng_loader/espeak-ng-data/lang/art/eo,sha256=AlS5PIr3nZZmp2Z8qLM7IaVFMBLaTqCs15ZgqWlfidQ,41 +espeakng_loader/espeak-ng-data/lang/art/ia,sha256=j7EXGAMPiykUb3c8pGK4OKbGYPFmkz628UmMNh8ulYs,29 +espeakng_loader/espeak-ng-data/lang/art/io,sha256=joORx_QLf50jB_r_gBikDdK0SN9L1YGilQ7oOToAzr8,50 +espeakng_loader/espeak-ng-data/lang/art/jbo,sha256=2VKd6C3MvZX4PB3kAfTqZhYJveZEVG6e9CEkG3BDwA4,69 +espeakng_loader/espeak-ng-data/lang/art/lfn,sha256=OUh0_ZAi43zcMHwzhugfHAwTOo6cX9_3SIi1GfLG1kg,135 +espeakng_loader/espeak-ng-data/lang/art/piqd,sha256=0aVZtxTNjdDqnkbEV04GxPRRlX-xe_OblFqJuVhvi5c,56 +espeakng_loader/espeak-ng-data/lang/art/py,sha256=WeVLlehXFBf0PbN6f9fjUa9OIqjCUM-2avOU-O1sTpw,140 +espeakng_loader/espeak-ng-data/lang/art/qdb,sha256=Urg_xPKUWA66vXHfZBq1vuxrMIdYo0WLSXEkc3WJp9g,57 +espeakng_loader/espeak-ng-data/lang/art/qya,sha256=eK4_TXAgip9p4sJqajtdso1-alh0D66Tf1Hdf8n66xs,173 +espeakng_loader/espeak-ng-data/lang/art/sjn,sha256=YdhZdLaEHfv8yMuSrQdCaWy4emqF1aKP6ZiV5G753m8,175 +espeakng_loader/espeak-ng-data/lang/art/xex,sha256=mUMADkPuzqomJZsjJTdVdTvDwmb2DvDyLJ0INMMYpqA,103 +espeakng_loader/espeak-ng-data/lang/azc/nci,sha256=e_cMsY6Wk5j3RCi5HGlKRIPq69ZzPsxDfrhxS79__3Y,114 +espeakng_loader/espeak-ng-data/lang/bat/lt,sha256=dpHHyh55_JcoxwoNIoMOsROgEkv5aAfioazjxr8ML4k,28 +espeakng_loader/espeak-ng-data/lang/bat/ltg,sha256=vnFsu9y1_jGe7Yir1KRMMymgbh3EaMg2PT9DzKJoOhE,312 +espeakng_loader/espeak-ng-data/lang/bat/lv,sha256=8IqAHazMrOYvW5AWZCjpDgiIGNkt1fkzPrvoNLDyHBY,229 +espeakng_loader/espeak-ng-data/lang/bnt/sw,sha256=Jx3Siz7EGt7qU_EUYkm6bKthVyljqydDBBEU2VeE42g,41 +espeakng_loader/espeak-ng-data/lang/bnt/tn,sha256=IkOh_CCN_cN-FU6DfA54KvwyXUrPuswicYt_BVg6zpI,42 +espeakng_loader/espeak-ng-data/lang/ccs/ka,sha256=aHiLmdunuCzfj8ndBRNL1yzyHwtMB7E7Z7bwNuYpTLo,124 +espeakng_loader/espeak-ng-data/lang/cel/cy,sha256=Z7wztKZgQeY0PfuY4ZUNEInuy2hzHzRvzE9HzQfnmXA,37 +espeakng_loader/espeak-ng-data/lang/cel/ga,sha256=KcLMVzbOsr2e90VpTUq_ftNjozVp3750WBHUcDt7bM4,66 +espeakng_loader/espeak-ng-data/lang/cel/gd,sha256=faC6RkV5w2cIkQmCbsFcJYShdBfMpKLGba4DGNM-MSg,51 +espeakng_loader/espeak-ng-data/lang/cus/om,sha256=t8Vj8e_9g8CPPSKftaE9B0UTuFFlzkNZpnTvMMpxeGs,39 +espeakng_loader/espeak-ng-data/lang/dra/kn,sha256=yYilIm-ifuZ2i0VWbOmZztmkto-OeSMrMj1ZA_S7Ilg,55 +espeakng_loader/espeak-ng-data/lang/dra/ml,sha256=qn4fHyObpVqKee0fNUTppRuU7-U5Jd5g1P9zcnNmC1w,57 +espeakng_loader/espeak-ng-data/lang/dra/ta,sha256=W8IT6xY7vwacv-Ty6ffn23GnGdjAqW6VQB2UyZKWDtc,51 +espeakng_loader/espeak-ng-data/lang/dra/te,sha256=F2ykqB_rIYE5Pt_z4tXAJTy1Ijk5LEuAnGFQHWDGmBE,70 +espeakng_loader/espeak-ng-data/lang/esx/kl,sha256=0Iz2_2C5nmws7aVJvLsaV1gJFdak1Qx_D111KJ2ftFo,30 +espeakng_loader/espeak-ng-data/lang/eu,sha256=oW5OTZuRCm4loqVZE8gSutxPw8vs4LjUmmSvESeC1aU,54 +espeakng_loader/espeak-ng-data/lang/gmq/da,sha256=6N1eDTD_BpSn7oOfqo7TXAFeuSenN6uh8SDAAAVpLq8,43 +espeakng_loader/espeak-ng-data/lang/gmq/fo,sha256=xOn6_LoAdOVM5doak3lwdqOBHk3VBsdRKnBjw6WTRDQ,104 +espeakng_loader/espeak-ng-data/lang/gmq/is,sha256=FsB35iIqz8dwIEb6NXm7XWtX7OmGRiKeE74iM_n9y9c,27 +espeakng_loader/espeak-ng-data/lang/gmq/nb,sha256=1HlmYhMS-5VXBTn0RpgvbeuY_UbZtx_sSgAFprrOj0Y,87 +espeakng_loader/espeak-ng-data/lang/gmq/sv,sha256=AnJ9OyX8gkCb0s0eu0RP2y1dPz3n92uV_J7ZFkw-WcM,25 +espeakng_loader/espeak-ng-data/lang/gmw/af,sha256=-4zMBfXq4XVLWqfpLLkZ3v3QgQtw7sGffHfPg25R2wk,123 +espeakng_loader/espeak-ng-data/lang/gmw/de,sha256=88ypL5S3D4wlop7gpMnOTH8QIiQVMuBkf6K39pi_EE4,42 +espeakng_loader/espeak-ng-data/lang/gmw/en,sha256=RgXVMwgB3jZBxuNm0V8SnqH1_7zociZCq6AazgernIM,140 +espeakng_loader/espeak-ng-data/lang/gmw/en-029,sha256=-uuMsgEFZ3X3M6y9kIxmVV_le_AcsGOSDxePOJy_hdM,335 +espeakng_loader/espeak-ng-data/lang/gmw/en-GB-scotland,sha256=HOQoLB9DhduvADXnmbKrHunpo6tIKRAFlKMEdye1I1M,295 +espeakng_loader/espeak-ng-data/lang/gmw/en-GB-x-gbclan,sha256=IEDhdvH38nvc6Bwy1-KxZiRJ1U0mSv08DthxuOQrbkY,238 +espeakng_loader/espeak-ng-data/lang/gmw/en-GB-x-gbcwmd,sha256=knpauJHGWzC0QmsVHRYjoBAk9rdzo4SXuhyQzXepV0c,188 +espeakng_loader/espeak-ng-data/lang/gmw/en-GB-x-rp,sha256=0GJa9_WFYbG4z5b9f5Pu5lU7yz6tuQIK4HV7-W5RFeU,249 +espeakng_loader/espeak-ng-data/lang/gmw/en-Shaw,sha256=PrH6AqMmM8yPxmgjuLySNanxDf9x19ePOA8V_A8OffU,119 +espeakng_loader/espeak-ng-data/lang/gmw/en-US,sha256=QVNMKiLfXdTxBS_54aM6Pqe_9aJrXAK9rVuo3bdSRwQ,257 +espeakng_loader/espeak-ng-data/lang/gmw/en-US-nyc,sha256=6O6RaDdtH32efc2nxGRMNsUpqL6oFuY4CJU2TbRuouM,271 +espeakng_loader/espeak-ng-data/lang/gmw/lb,sha256=BxvrDnaa_royF3eW_A8Thr3ImjI0vtK_cg52y_c_W5k,31 +espeakng_loader/espeak-ng-data/lang/gmw/nl,sha256=Vq4E-uKK6Tce1tsoGTGJ5O6WK6gjbwvN7vagbqTe43Q,23 +espeakng_loader/espeak-ng-data/lang/grk/el,sha256=C1KcmYrwfHK_UWtXUHCUZPYljFbGkWuLjwyEO-mDb8o,23 +espeakng_loader/espeak-ng-data/lang/grk/grc,sha256=MZ-VCxrXsfN--qOQVAv5V73awW0FV6bDra_yfgxk4S4,99 +espeakng_loader/espeak-ng-data/lang/inc/as,sha256=P1j1Yo95KwClrm6P47-GlvZK8oOOVyN5ndurYCegs3g,42 +espeakng_loader/espeak-ng-data/lang/inc/bn,sha256=vDziM4S50Ls7rAagnZD2kPrjKkkty7Aw8OVrpntdZWw,25 +espeakng_loader/espeak-ng-data/lang/inc/bpy,sha256=5SjRGJuZW5SWbO9MwYJGnMVPfajvxYYDdcTs8YbOYUY,39 +espeakng_loader/espeak-ng-data/lang/inc/gu,sha256=-TinVdJwdFGIws8qrLoGZCqWu3O6KgMlOEEhudXsVAc,42 +espeakng_loader/espeak-ng-data/lang/inc/hi,sha256=PBw_kW9X8tbWy_eSPA85o2rCFA4qad3_zpF9e4vzzKs,23 +espeakng_loader/espeak-ng-data/lang/inc/kok,sha256=gQ7iP7vpwYagNrwS9OXA3mdKEy4uCZybPeziocnNsoo,26 +espeakng_loader/espeak-ng-data/lang/inc/mr,sha256=KQY_86UlfQ09fCFd_UwU3u054dSPFYlCAuZxJFlyDv0,41 +espeakng_loader/espeak-ng-data/lang/inc/ne,sha256=1T_aCC7BdO8z7Tw0aPyXPEO073GsqMGijLNEZo9IONw,37 +espeakng_loader/espeak-ng-data/lang/inc/or,sha256=m1Lt59GWWfiEhU3j3_Ell6lvTW7Hy0FG0vja0UU8dC8,39 +espeakng_loader/espeak-ng-data/lang/inc/pa,sha256=7tPPR3-B0TVZ27NnJW-VMrINrRQywVsgbHdyF7j1cMo,25 +espeakng_loader/espeak-ng-data/lang/inc/sd,sha256=Zb_g43eZAp1Co3DrYnzKWqQQi5Z_umyBQYeNaTyQNhk,66 +espeakng_loader/espeak-ng-data/lang/inc/si,sha256=jwmTs1ulsHXDiudmQJcSVuVgq_vXIbYI0WpIWIkyWW0,55 +espeakng_loader/espeak-ng-data/lang/inc/ur,sha256=W3r3R0-sJlx719JpERmUoJYQ-VRpBpj1WoYT8_qXMxg,94 +espeakng_loader/espeak-ng-data/lang/ine/hy,sha256=tq1hKQecScqRXDAF7LdKAr9dacu8jsP44Pa5Scs6do8,61 +espeakng_loader/espeak-ng-data/lang/ine/hyw,sha256=JvioY8dLPRnJxC_PFq5RUcEqxS74-rNsrh5fDUrTDmo,365 +espeakng_loader/espeak-ng-data/lang/ine/sq,sha256=hl_ekBe1r4KsuETl-Xk5mP7UIqIIrYqvne2srTvyevE,103 +espeakng_loader/espeak-ng-data/lang/ira/fa,sha256=DcfpO-TR-99_9S3i_ovNwjME5thuAStKuCdtYmtdmAw,90 +espeakng_loader/espeak-ng-data/lang/ira/fa-Latn,sha256=oEz47-2Nsawzswbx-Mb0JzPazofJ_J80otIns7spHig,269 +espeakng_loader/espeak-ng-data/lang/ira/ku,sha256=V9s6IQ1zQSpJ6WHb7ZsnB39ce5Z6GaDrn5Nj6ksWzqU,40 +espeakng_loader/espeak-ng-data/lang/iro/chr,sha256=8OL7hUkwbAf1cdPnfImx0-kCLUSNWOXUJEQeAczOiL4,569 +espeakng_loader/espeak-ng-data/lang/itc/la,sha256=tw0TomQ1LrotIqXQ7yFzCElQnRj3J3MgsAilbezG78I,297 +espeakng_loader/espeak-ng-data/lang/jpx/ja,sha256=b9mARFvFLg9ZMGKSn1tigxRIq6riqSc5vrpJ3yenl0M,52 +espeakng_loader/espeak-ng-data/lang/ko,sha256=wt-_iNmqKsm_LzDpLiYBIOTywhEjoCJlAUrpjVnVd04,51 +espeakng_loader/espeak-ng-data/lang/map/haw,sha256=sZ8i77ZxQ1TY0TYPRJ4F8PhNUNb6PJj8_WGeobS6iZY,42 +espeakng_loader/espeak-ng-data/lang/miz/mto,sha256=4zq6XoFZcw9iAEsiUY1ifHlvfQOUMeXZIXtJjxA0GXY,183 +espeakng_loader/espeak-ng-data/lang/myn/quc,sha256=dqdbd8ZyxDK1a4TVFzENaqdcSz-d5YDikBmYBDZhdOo,210 +espeakng_loader/espeak-ng-data/lang/poz/id,sha256=zh_N2rPnVqfNuj3QCa0kzVfh_eKc45Vpg1XaJOMqYHU,134 +espeakng_loader/espeak-ng-data/lang/poz/mi,sha256=IUbPOGjHm4U7teQd2_YR1RtLChQIcZnxYZQxNWK5iYc,367 +espeakng_loader/espeak-ng-data/lang/poz/ms,sha256=ipZRgu4MWkE1cZfAXPBH0huWdEd1pXo0TYMalh4wNRs,430 +espeakng_loader/espeak-ng-data/lang/qu,sha256=MGnkQ-zzQhvLOzW4ZOGon6lGWvBy-G7t1GpBWZCrpuY,88 +espeakng_loader/espeak-ng-data/lang/roa/an,sha256=_4qpfFUobMkFMcrV3zzTYWWruhFQKoTVOw_Nkj-WXyM,27 +espeakng_loader/espeak-ng-data/lang/roa/ca,sha256=CNhwGzKoIBg1HDSU1jYNFU72SkYi5kyKYKLmFakWTd4,38 +espeakng_loader/espeak-ng-data/lang/roa/ca-ba,sha256=peemF8_lKWLdoeytlIhFO3rx2lPOHhkaQRSxlX0s-bY,80 +espeakng_loader/espeak-ng-data/lang/roa/ca-nw,sha256=Z31MswP9KkHIIu4gWB42QeFP9xkvand9zjAHJGehCz4,73 +espeakng_loader/espeak-ng-data/lang/roa/ca-va,sha256=J5IFvpNEectBSiVGK6__kzw8J_V82OO2YF1H2qhnKKk,81 +espeakng_loader/espeak-ng-data/lang/roa/es,sha256=lmqgFepWRtefDKSAfPXaczmqvTeCtVz6XrDYw_yPxYg,63 +espeakng_loader/espeak-ng-data/lang/roa/es-419,sha256=_w-ERXrEDjvPYdbeWAKDEr504ObLw7dC8xs85ynCqgw,167 +espeakng_loader/espeak-ng-data/lang/roa/fr,sha256=lfRINLSMB12tE-rOVNLJj_ebgaoAdN1n7rr2bCkJ7vg,79 +espeakng_loader/espeak-ng-data/lang/roa/fr-BE,sha256=cklqMW5HuZf4k1ALiVPcAaELhqLUI44TwSYPULR9eSo,84 +espeakng_loader/espeak-ng-data/lang/roa/fr-CH,sha256=tEmw_ZnZzZMmH-HGuBZEi5m0oQQgvuPzAeZpVorQ3lU,86 +espeakng_loader/espeak-ng-data/lang/roa/ht,sha256=OJvfPphKL5O3Bguq2CRS2sZbg79EgtOIRSWhdq4OBSQ,140 +espeakng_loader/espeak-ng-data/lang/roa/it,sha256=DZBp65qW2xxVwTGyu30fUlXGj73cIZn_0ylbUlGaMlY,109 +espeakng_loader/espeak-ng-data/lang/roa/pap,sha256=QaW16RSCpUmKZnEcBYc6Y0u9QYeGsLoDcDLfhGNEz8E,62 +espeakng_loader/espeak-ng-data/lang/roa/pt,sha256=pEBgBy95DkGRLFe31S97ZDjEOD4Nq9sFL2_beqzCNJM,95 +espeakng_loader/espeak-ng-data/lang/roa/pt-BR,sha256=hN1ONMlw-tvjIhHq3s_fqrUkMkecCRHkMwDaiKMzmLo,109 +espeakng_loader/espeak-ng-data/lang/roa/ro,sha256=sSrxD_w_icuHdnynAcb-oN74pxLeY0JqnD0L8kMkZ_g,26 +espeakng_loader/espeak-ng-data/lang/sai/gn,sha256=_4LS0WPT4GrbWAJU2JAS5omyYVxGV5iDVig4q0AftdU,47 +espeakng_loader/espeak-ng-data/lang/sem/am,sha256=WXCxa_hlUo7panjAhJgkS8j1Qhj8Kt1Jlxaw4MCZafs,41 +espeakng_loader/espeak-ng-data/lang/sem/ar,sha256=Q_QY-BQOWnvXCWlj2iDMupJH9r4fzbCMtT3Xln3XLu4,50 +espeakng_loader/espeak-ng-data/lang/sem/he,sha256=3pGV50O5H7f773STvV3cytFMOApY1a63wdEdNBnvO4Y,40 +espeakng_loader/espeak-ng-data/lang/sem/mt,sha256=0j84-uMlO2-0LjM2dgq0guZ2iTaSRVRlRIvJ-8CsPoM,41 +espeakng_loader/espeak-ng-data/lang/sem/ti,sha256=KEW4jagor3UogoQ1mpDhsGJtP3ilR-cav8admG0Ahko,93 +espeakng_loader/espeak-ng-data/lang/sit/cmn,sha256=oTCjjjtiJzXCQByzf2cZ9GmV6EoTNykYXO-aVD7AsHI,686 +espeakng_loader/espeak-ng-data/lang/sit/cmn-Latn-pinyin,sha256=FML8CX2ygEFraIwr-X3i5dpTLCeXVAIP3nv2zWJM3RA,161 +espeakng_loader/espeak-ng-data/lang/sit/hak,sha256=wDwwtD4LCr36aJRFuvn0QmZKA3MVSl0Mp1oz0w9Gru0,128 +espeakng_loader/espeak-ng-data/lang/sit/my,sha256=S1riVmy_MKpZIHAgRp4Jgy5mp4g4GHiPJTmWxTQwPco,56 +espeakng_loader/espeak-ng-data/lang/sit/yue,sha256=g_PaySr1tKrswRlRVpiml5UkviNrKOqPECTscH2Z6ls,194 +espeakng_loader/espeak-ng-data/lang/sit/yue-Latn-jyutping,sha256=xW1Fu5qc2X77OO2r4xx90_6wUYzJAKrGqJHctr2OtCg,213 +espeakng_loader/espeak-ng-data/lang/tai/shn,sha256=8Wvy3iGdOummrsJjzpxoTZzT5hJY0Ex5SNsHV8Z-LJY,92 +espeakng_loader/espeak-ng-data/lang/tai/th,sha256=bIrICYaN5lngZnPx_CtW2_Rjf_mYDaekcmuEZHi0z-Y,37 +espeakng_loader/espeak-ng-data/lang/trk/az,sha256=UrQkMy3kxEPz6cXOTeWu1vv9QhJp_IJXVt_GvL1-Gtg,45 +espeakng_loader/espeak-ng-data/lang/trk/ba,sha256=oMw6Bik5Ygk8ZlM_nBz_vM8IOi62ZnUfJ3igKlMW2Yw,25 +espeakng_loader/espeak-ng-data/lang/trk/cv,sha256=lLr2us9YHMIDN0ccWZ-F7LviEfC4R2NR_xlFDGVB6pI,40 +espeakng_loader/espeak-ng-data/lang/trk/kaa,sha256=IQ-5-6Zpyc6Nzyi5gCfFB3RHPjkG5-e3nrlvqv_sAxE,28 +espeakng_loader/espeak-ng-data/lang/trk/kk,sha256=Ihn01t4Pux3JmCFXxvPMX0yKvl_LYFkIqdEFS5iAzVE,40 +espeakng_loader/espeak-ng-data/lang/trk/ky,sha256=gjnf6L3G1HJYgPUZK06vZF-DnkDK39FFpECcg4esLVk,43 +espeakng_loader/espeak-ng-data/lang/trk/nog,sha256=4OJ_5h1Aa29KSHn7j4GhS8ZZlxBmZpM5kbgYx9efq8E,39 +espeakng_loader/espeak-ng-data/lang/trk/tk,sha256=14JjOYwTURmQmtY6Pstv_jr_CDgyEpNN0DaVIiqXhtA,25 +espeakng_loader/espeak-ng-data/lang/trk/tr,sha256=SQ61ovd3ovM5bzqCTtgCG9d6lL6AEhRBFGG95miXOMk,25 +espeakng_loader/espeak-ng-data/lang/trk/tt,sha256=i5YXqbbFb0ov4vWdnOVUJoNxllZ5YnFvkzD3CUj4-bA,23 +espeakng_loader/espeak-ng-data/lang/trk/ug,sha256=ZdDNvJbvq02ePNAJVEB1KjHcf0Je3TugpTxN0z6sXWM,24 +espeakng_loader/espeak-ng-data/lang/trk/uz,sha256=BP1xHf2h4A0X3IsbJQwk1wzDxJiyfjXTEGWsR0QaZ1k,39 +espeakng_loader/espeak-ng-data/lang/urj/et,sha256=Wcd3R8R3TlSmOrdNLGqVvDxbWwpQ03gfGHvR_DphPeU,237 +espeakng_loader/espeak-ng-data/lang/urj/fi,sha256=YfWOw7ultVo5Kv9-z4qE0CQgCuqkBLVVP8-0d3CTaSg,237 +espeakng_loader/espeak-ng-data/lang/urj/hu,sha256=xXVCHSrjlwZdNa8OtPed_06F80Ncz0Xah09Gs_7hM4s,73 +espeakng_loader/espeak-ng-data/lang/urj/smj,sha256=PXCd7He7Yzrw1XuJZo26qnLZvoaIEY1pCffUV77BKlA,45 +espeakng_loader/espeak-ng-data/lang/zle/be,sha256=W-sALRWja_PQ12TtDUg8daHfaQnqo7EP5fZUZwDJv-w,52 +espeakng_loader/espeak-ng-data/lang/zle/ru,sha256=n1LQCiearqpFp4a0_TqYs06V_tv4I_jNuf7MEzl1HTo,57 +espeakng_loader/espeak-ng-data/lang/zle/ru-LV,sha256=mA43lmfMuUq-M7nJxmDAiADj8x42_kqTlVE5irmEV64,280 +espeakng_loader/espeak-ng-data/lang/zle/ru-cl,sha256=IA6jRbUF7J57iDhJCurxgir0EDNCmurk6mgVkEf1n5A,91 +espeakng_loader/espeak-ng-data/lang/zle/uk,sha256=3z0an3e6wFMecvh745jZ6x6QO9b4OdTwT_7Fq7TjRjQ,97 +espeakng_loader/espeak-ng-data/lang/zls/bg,sha256=m5GszMsNU7sqe_IZIoRrpYx0vAgrpxrjK_EssNCS-FM,111 +espeakng_loader/espeak-ng-data/lang/zls/bs,sha256=CCDnx4to-9r4bYPHgs3eGQG2QtHNvq5Bgcb19eIeXok,230 +espeakng_loader/espeak-ng-data/lang/zls/hr,sha256=zvPvBBHGbxVObIL33s2Vvv-oy_vpUzNWWN-fElvdYJY,262 +espeakng_loader/espeak-ng-data/lang/zls/mk,sha256=bbws-4mZFBvQeCzUY9SIBGgWEIgZDGtMlBL0NVLcOeI,28 +espeakng_loader/espeak-ng-data/lang/zls/sl,sha256=4cK9H3XA7rhvZBgkctX1l84j5krXR4wkjC91tpRlWUI,43 +espeakng_loader/espeak-ng-data/lang/zls/sr,sha256=DgdlKNNWb25ZuAfhbidN7lBeiKbUd9oYirjsRC6uRPQ,250 +espeakng_loader/espeak-ng-data/lang/zlw/cs,sha256=FHfNulujvOhdtVmsy72KJLhrP22dmYi8WH6JNXwcRDE,23 +espeakng_loader/espeak-ng-data/lang/zlw/pl,sha256=g8WGorckskufmNIa3lAiESxGWsRGygmTAoaYDOrhx4E,38 +espeakng_loader/espeak-ng-data/lang/zlw/sk,sha256=9G_2c8fVjBZGCWwXTVjaNAR9iT0NKZPbyiYM5Uq-d-8,24 +espeakng_loader/espeak-ng-data/lb_dict,sha256=2BmgYrlyIzTxh1QNNTD6wd42XNIA1KRm9ezM1-PAV3I,687931 +espeakng_loader/espeak-ng-data/lfn_dict,sha256=ECgbxAT0KRZaMwuADrZGdON6E10bTGieV_sdnoJ9aSQ,2793 +espeakng_loader/espeak-ng-data/lt_dict,sha256=aO9Vq6lUXSfOc-fUrKHC-lHSw9PWJhUvvCK_WpD7_xE,49890 +espeakng_loader/espeak-ng-data/lv_dict,sha256=PiRsdrfakkI1_7dZJQcIZeZp2izj5B6YOV6Zvh-Nufc,66337 +espeakng_loader/espeak-ng-data/mi_dict,sha256=QBYh_fYdpH0FE-gCeRNKNRXO2JiqrdUgW4LM7Q8t8EI,1346 +espeakng_loader/espeak-ng-data/mk_dict,sha256=5JYP9OdOEJb_HDvMq2LOBCn6T6pyXlRs1dM-Q_RSJb4,63859 +espeakng_loader/espeak-ng-data/ml_dict,sha256=sSaHVXw4-bzRdBeFQlPd3jeB47DBb5Rw1zIgWBjnzTg,92345 +espeakng_loader/espeak-ng-data/mr_dict,sha256=9xKnUl2xCO-Xaa7lP90c0UHw3zcneJJGkbiWI6pvwi8,87391 +espeakng_loader/espeak-ng-data/ms_dict,sha256=dLAYlzhbofAY3kTAJoBI-lvliLu7cCqQC7NcaRpGZwc,53541 +espeakng_loader/espeak-ng-data/mt_dict,sha256=H3Z2G9_UgamEsV0HUi3yPJRE9Kwh6pZxkX4Iu_-n-NM,4384 +espeakng_loader/espeak-ng-data/mto_dict,sha256=bVHLa-lZ26BF1B09Y_9mKnNj4Sh8zixjOwcSlc5V1WA,3960 +espeakng_loader/espeak-ng-data/my_dict,sha256=S-VK9rCdfL3YNFZavyF1l7jbzvHQ9tA41LiLSouvHzI,95948 +espeakng_loader/espeak-ng-data/nci_dict,sha256=OMcgHncmyNUI-PhhE0nLxE_MRoSg_uTbcoXYPoCKW2k,1534 +espeakng_loader/espeak-ng-data/ne_dict,sha256=Q4McP1PqbpOcrDe1rlvXouqCN6pG8OfyRBq3cqPFHbo,95377 +espeakng_loader/espeak-ng-data/nl_dict,sha256=-fJwp7YgTzItm3lDRg_jEP57yRjdXUvBrKyNso-pAtE,65396 +espeakng_loader/espeak-ng-data/no_dict,sha256=Q7go-MFwnnq7I6DMZBb7MuSBTj8f8dtLryk1v3x3yf8,4178 +espeakng_loader/espeak-ng-data/nog_dict,sha256=i5ITmKLxkHtDwHuWpyJ32NPYVF44WVXuuuXzQKrjO9I,3294 +espeakng_loader/espeak-ng-data/om_dict,sha256=NiTmfvjZwg2JTbCtzKzMYe6FKXfLd9X-WAHntKUo_PU,2302 +espeakng_loader/espeak-ng-data/or_dict,sha256=4N1zfpEE2mOifYbNRkz3dkg3YlsVExabjSj8ob08jDs,89246 +espeakng_loader/espeak-ng-data/pa_dict,sha256=zuDior-xZuYC_4ThhTUaisMRVxzN9G4YMceiUkVWPBA,79953 +espeakng_loader/espeak-ng-data/pap_dict,sha256=dwA5u_TqjFo__d2YxIMcoCyfOeH_az3ncp-nGo87wPE,2128 +espeakng_loader/espeak-ng-data/phondata,sha256=oLZDsVXLaxJijZ54ZbV9n8oNNYRGFPJZSl4AnIDIC7Q,554740 +espeakng_loader/espeak-ng-data/phondata-manifest,sha256=JS3eyX1c3UfJg6Dbcfgvs2NcOxsiKwcPHbMteUP0JrI,21866 +espeakng_loader/espeak-ng-data/phonindex,sha256=OE5fpvcUulNWxYAIJJt4aZwxwa0ESyQwaNJj-4BrfXM,43316 +espeakng_loader/espeak-ng-data/phontab,sha256=G0BpBmfh6aobpeUjR3PHmefnLqdRQm5RUEI9U8PyT6I,58652 +espeakng_loader/espeak-ng-data/piqd_dict,sha256=MwBKNiEMMyka74qDjUd2Z-7Xr1L_UJMVKJE3mxd0GI0,1710 +espeakng_loader/espeak-ng-data/pl_dict,sha256=Ta7Yt_znutbGkKjwQPJUtt5dI464fPAYikb2uKcDCTM,76620 +espeakng_loader/espeak-ng-data/pt_dict,sha256=lMaJFT4S6cXg7L9gUYqT67LqD76AXGPZf6hMQzMUJOk,76389 +espeakng_loader/espeak-ng-data/py_dict,sha256=IlU0iHlUeUDotJ4MobgEUnSPFCy24mfknKsFYMcgEpo,2409 +espeakng_loader/espeak-ng-data/qdb_dict,sha256=ybfzB__lT0qvMjKQ7KHGIFcpGQNbDrJo5clPXXpDAFg,3028 +espeakng_loader/espeak-ng-data/qu_dict,sha256=1QZZwqFPQ-Af3vC2aOsIMCWgDKxIG0nfsGjgIg4O2UU,1919 +espeakng_loader/espeak-ng-data/quc_dict,sha256=RYwcptz6KI6iWEkV0gbFEnUSUBF02CZV3izwMTeObf0,1450 +espeakng_loader/espeak-ng-data/qya_dict,sha256=5Wril-usJu1sd6lxiBLgh_C9GYJB2sPA2WTzZRCYR4M,1939 +espeakng_loader/espeak-ng-data/ro_dict,sha256=sU9ohmsEQMSw2V-32jt__TxZtpPoWT0YhHT6v8mhEX0,68538 +espeakng_loader/espeak-ng-data/ru_dict,sha256=X-NeB54fxE_u1kKazYwS5M2XStQ-lvGWgBjE2Spt3dY,8538195 +espeakng_loader/espeak-ng-data/sd_dict,sha256=OYyHa1IhOm591Uxo0FYNKhwWTGv7I7nsHARCZs3PIhc,59928 +espeakng_loader/espeak-ng-data/shn_dict,sha256=ZTqFeYG_RYK0nGGXZXP0scR9DUHolByGhR_iJire-1E,88172 +espeakng_loader/espeak-ng-data/si_dict,sha256=okFDfUtk_TKKxKPnhslGXGBIj2-jHLugQVP2KM3GHyc,85384 +espeakng_loader/espeak-ng-data/sjn_dict,sha256=63BRAUQjD2eRV02GuuCRi0GRsHbdZsVV5q49Vjfarfc,1783 +espeakng_loader/espeak-ng-data/sk_dict,sha256=WLm8EcmpXYHpaWYkI2cAn40Cq3o_j0_XfjWB7UFZ8Kg,50002 +espeakng_loader/espeak-ng-data/sl_dict,sha256=nLK8v2FqXn3XynaefSIqSMYTKZ7x125EwIsAL4wihho,45047 +espeakng_loader/espeak-ng-data/smj_dict,sha256=gVJwzjilnBku9aqIARGdmz7Zc9niPfptqNXSfe1anNY,35095 +espeakng_loader/espeak-ng-data/sq_dict,sha256=a3S--UwzGUB8J-RNlE52XQNqiLMLTBfzC7wYLb_8xM4,45003 +espeakng_loader/espeak-ng-data/sr_dict,sha256=dwyunFFuSK94lmKfr0q--vBB4f1K4YQBGq0HuXGW9hM,46832 +espeakng_loader/espeak-ng-data/sv_dict,sha256=Vl8FixTxyJxr-kT8NwB5OIajnHgY8QN60fSWH6dRdQk,47836 +espeakng_loader/espeak-ng-data/sw_dict,sha256=N1-rLM0NZpF3rUBrILDNtYUaHobwk2cvJPcsKf7IqBU,47804 +espeakng_loader/espeak-ng-data/ta_dict,sha256=jz2FXI16Na0OKyK8fBWogw5fwjVJKJTl20BFhlUHbs0,209553 +espeakng_loader/espeak-ng-data/te_dict,sha256=ZAQHxmpbuXVnEkMyXeYWwiH5C7KELTo2J4-stowHcvg,94837 +espeakng_loader/espeak-ng-data/th_dict,sha256=3V0-YmijgZIPIcdp9S2vOo5hCug_eZXlbxXp1N4Y1lM,2301 +espeakng_loader/espeak-ng-data/ti_dict,sha256=zTTxiJw6VrLMWmtJw6b89sM8L7Jeon-p4ougK3L83Mo,57920 +espeakng_loader/espeak-ng-data/tk_dict,sha256=s81KJG8BTwVk7J7655cxwP5z_-HNFhc1ndjVNE7j-cg,20868 +espeakng_loader/espeak-ng-data/tn_dict,sha256=Z_aNwzbnxluUbJVBTMiuls0Q0kF4O_hXs_mQrHMiGys,3072 +espeakng_loader/espeak-ng-data/tr_dict,sha256=MRsFVwWfLate4vqrtRNh9QMzaPDipUxL3-RecwZ08m4,46793 +espeakng_loader/espeak-ng-data/tt_dict,sha256=YNE404Mw5Ep4tCJMvqRSv8oivOZzTIzj9kDAIWzhQAE,2121 +espeakng_loader/espeak-ng-data/ug_dict,sha256=fEVn_-a9jVIktrP9j6tlsTQyVGNuYijXOK46cIQo6Oc,2070 +espeakng_loader/espeak-ng-data/uk_dict,sha256=p3m7D1HOXOu2UKTiKCFi_IxEYJIQorqnAPgfPoPm4Qw,3492 +espeakng_loader/espeak-ng-data/ur_dict,sha256=dLYOQzH1MoEMz8cHUa0Hq0QGR1UKLSWCP0RmOg36hvs,133556 +espeakng_loader/espeak-ng-data/uz_dict,sha256=eQ1CrEF7Jt17G7_tS-cjKcFu0YOd119V98li63vVhXo,2540 +espeakng_loader/espeak-ng-data/vi_dict,sha256=97CQgRudpJeTnIUpaYjiJ3JFljdHS7tbbBD6M7p2zBA,52608 +espeakng_loader/espeak-ng-data/voices/!v/Alex,sha256=HPmHRWf0-oEJMp8ITprZ7XiPsjYimJIdCgSleyTxFB8,128 +espeakng_loader/espeak-ng-data/voices/!v/Alicia,sha256=bT9g7IZnBunUq32ip57tuMEbUPY2IPh-WDF_MW6j1Y4,474 +espeakng_loader/espeak-ng-data/voices/!v/Andrea,sha256=bKUnNOws98QZ0tOtfDRJzRoXdjQsTRUuoSxbHnKAHok,357 +espeakng_loader/espeak-ng-data/voices/!v/Andy,sha256=DhO6GpQM2d9-ZTWMNkRcl0Dz118TYMf3xxq590tF7co,320 +espeakng_loader/espeak-ng-data/voices/!v/Annie,sha256=QPD4KcXG56v0oCoh8SilcnVtb2aTAUwm0JpcKe3l7DM,315 +espeakng_loader/espeak-ng-data/voices/!v/AnxiousAndy,sha256=ff4Sb1F7dsx4JpYY2-4sMNMkvqlGC0AJOHVuyTmV6vg,361 +espeakng_loader/espeak-ng-data/voices/!v/Demonic,sha256=JBsOeDYr0yCLtYa2W99SMw4egyL48ibEeQxKvrR8-wk,3858 +espeakng_loader/espeak-ng-data/voices/!v/Denis,sha256=oJ_p96TkeNK6HhOcKZVjPiuZ3pq9qqgjB5VFmbDj1v0,305 +espeakng_loader/espeak-ng-data/voices/!v/Diogo,sha256=pKF8RT0TJCtIeDwkeBa_-NLPe8iTHD-CN4h9iKKIGxg,379 +espeakng_loader/espeak-ng-data/voices/!v/Gene,sha256=BiWNrmgM3iEipJOdvU8j7U6hRbdHUGi_fdTUZgkK_So,281 +espeakng_loader/espeak-ng-data/voices/!v/Gene2,sha256=vNswOSlu6jc5jkQj3Ju2hJzanFyBK4NwLrxJaCxkn1c,283 +espeakng_loader/espeak-ng-data/voices/!v/Henrique,sha256=XGvxz1trx8fUjyqDaK40jG_2QjLAR_QPnZpuaCS0zmo,381 +espeakng_loader/espeak-ng-data/voices/!v/Hugo,sha256=kGrL74kNxNpny1S1sN3CyrfuMIqV01DImfCwy2qD3V8,378 +espeakng_loader/espeak-ng-data/voices/!v/Jacky,sha256=QYhO2bZhYK61oNxBg3Cln-OerQAT2T4CPm1gfvAcGm4,267 +espeakng_loader/espeak-ng-data/voices/!v/Lee,sha256=oVhIh83bQMEOBJkvt3ACW1Lma3BQRlYJT4CXXx1rv2s,338 +espeakng_loader/espeak-ng-data/voices/!v/Marco,sha256=BAJWdzYMAnDwlLu2cWuDyChJAvbam0lr7bv1kJY4Nfs,467 +espeakng_loader/espeak-ng-data/voices/!v/Mario,sha256=qUrGXRMgMN9JboqjZNXN5fLq-ktrOuNhopAdUSxgKdg,270 +espeakng_loader/espeak-ng-data/voices/!v/Michael,sha256=RAm-I-9f7fTIv_v6qKgCo0KCTX6X8dkpODNqJfkvDr4,270 +espeakng_loader/espeak-ng-data/voices/!v/Mike,sha256=iZmyZGBsCvI9NGqHfhDKBap1f36kM-bPyzvvUKVros8,112 +espeakng_loader/espeak-ng-data/voices/!v/Mr serious,sha256=eUq9eN6wfOmwNBnSD3dE30wBUdWr_3mBIX6dCSai8kA,3193 +espeakng_loader/espeak-ng-data/voices/!v/Nguyen,sha256=Tz1VfZwEUID1YCKpbls2WcTRyqX6HXAuEtPva-wuOkU,280 +espeakng_loader/espeak-ng-data/voices/!v/Reed,sha256=cn28P2v_C-TdfQQ49m07uCz_aO0UjPUstY5zMUquweQ,202 +espeakng_loader/espeak-ng-data/voices/!v/RicishayMax,sha256=fdx6V3EczXpzZUDxQnGtrfHi4EIpQeyqfMQ6uH-OIBc,233 +espeakng_loader/espeak-ng-data/voices/!v/RicishayMax2,sha256=PeXkFNSy7wgqe5dLt-3pSTfpO1uHPSsveSixnTB0UYA,435 +espeakng_loader/espeak-ng-data/voices/!v/RicishayMax3,sha256=NtIFULaKjCKdNNlWZXt9ZCkpli9-XU_d1jlq-eU3i1Y,435 +espeakng_loader/espeak-ng-data/voices/!v/Storm,sha256=6BfH0c4Q3lJ-vBnAg19YDLWEw659NtMKT0FEgmAue4k,420 +espeakng_loader/espeak-ng-data/voices/!v/Tweaky,sha256=w00cHYt5Is64hrla1qtTTKBI-cR-GWmOwqrlzwwyzbw,3189 +espeakng_loader/espeak-ng-data/voices/!v/UniRobot,sha256=I9ulLC0cszLbYiUwSBjYVIjxEKZo3c2_1_BDiv43eUs,417 +espeakng_loader/espeak-ng-data/voices/!v/adam,sha256=sh779W_X1YRw585HWcbvnyOUlwayafLXd4MiBGWO4N0,75 +espeakng_loader/espeak-ng-data/voices/!v/anika,sha256=IodxzoTK0WoIngsj7-Lmnt8l8at8DLOlDTZqxw6C-70,493 +espeakng_loader/espeak-ng-data/voices/!v/anikaRobot,sha256=O6ckvmqrL8GghLJc2xb0aSUOud5MbAkkoYeI0CRvwy8,512 +espeakng_loader/espeak-ng-data/voices/!v/announcer,sha256=SvamdIxyDLuqwePcrBe7O8ekxVNJnsfuaeBU21GlDeM,300 +espeakng_loader/espeak-ng-data/voices/!v/antonio,sha256=yQR3CAzZqpw4R3DA7BiQHQHphR8bx9FVJqJWWjsMTaU,381 +espeakng_loader/espeak-ng-data/voices/!v/aunty,sha256=Cu3k0cphTzLDSPPXKOq1gyLM0BboUxI0_cPfzwDjK_E,358 +espeakng_loader/espeak-ng-data/voices/!v/belinda,sha256=m9eRtxFYIOJa2oK0kRE01RFugji0_U0hTfzPFiV2FBw,340 +espeakng_loader/espeak-ng-data/voices/!v/benjamin,sha256=P6ELDYZfx1H9nI7R2rrEu5sBHqK5UGTU0lqMcZ93hdg,201 +espeakng_loader/espeak-ng-data/voices/!v/boris,sha256=8j0KbuLut-M0BQbWHUIraR-wT06Yl36hXB4O5XFYRtU,224 +espeakng_loader/espeak-ng-data/voices/!v/caleb,sha256=vN4UXscT6ubTRRpvJdu9wLZ1b9ROngkreu-J8s_yW-g,57 +espeakng_loader/espeak-ng-data/voices/!v/croak,sha256=KQaixve3aH2y8chiFkqbgENdWvw7oW10YZcov4w6jKc,93 +espeakng_loader/espeak-ng-data/voices/!v/david,sha256=ULXLX2GlD1_1KZ3SLl1kVEZ0bbw2kJWV9q5HusC9qcM,112 +espeakng_loader/espeak-ng-data/voices/!v/ed,sha256=Et22NVtAouOaO2zvZqK_TbFaJQRXabMwqaOzRKYIAm0,287 +espeakng_loader/espeak-ng-data/voices/!v/edward,sha256=t6EryyrygMQOS-QoC2dQAQJGGe1SkmLb8-gZ21O1sxA,151 +espeakng_loader/espeak-ng-data/voices/!v/edward2,sha256=WdFm963-5FFaSSmTQF6VQyiJBQqqR7bNfq7rRX-8oic,152 +espeakng_loader/espeak-ng-data/voices/!v/f1,sha256=fN70U8awOR1QoCuPNTkub0EknOpl3xAhr_1opkkXuF8,324 +espeakng_loader/espeak-ng-data/voices/!v/f2,sha256=YrF_bI-UrdAxDbAy9eRjwTUQxf-D7x8h6IlMy_ALAOM,357 +espeakng_loader/espeak-ng-data/voices/!v/f3,sha256=0DQu6M7r4wR4MXdGNNI06QKB7HPOKu2N0L3ZFcz1APw,375 +espeakng_loader/espeak-ng-data/voices/!v/f4,sha256=_54pB6gYkg47l2IyyQ6rrycP_w3guKR5r5o2M-m3kh8,350 +espeakng_loader/espeak-ng-data/voices/!v/f5,sha256=bHZAbZRUDVne4W3hFSDDcSSh9t_CNpgeSDh3B18CcbM,432 +espeakng_loader/espeak-ng-data/voices/!v/fast,sha256=-i-cKRjzUUmQN_a_-yUpTZt4GyeF2XcqiuMpPAwAN_4,149 +espeakng_loader/espeak-ng-data/voices/!v/grandma,sha256=4DPVe6mwmJcf25lcE4MPnHCSBq3QgcWG2q7DI_9po5I,263 +espeakng_loader/espeak-ng-data/voices/!v/grandpa,sha256=8lYniHuV6LzKxebOmcuXxuNCkP8L-Rn-vmSpmHE4eW0,256 +espeakng_loader/espeak-ng-data/voices/!v/gustave,sha256=X6ic-GJc1GC5MJdI7KAZq1syWgTcy9KfGpsqAMqi6Eg,253 +espeakng_loader/espeak-ng-data/voices/!v/ian,sha256=wHIseVTT5lguP1s_WEFAZ1qwYKw8bKxd0Rp0WS21VQo,3168 +espeakng_loader/espeak-ng-data/voices/!v/iven,sha256=EKud6DZf979aIGIdCPGiAZ1L9VIfPG9lRHySVgV0Bsg,261 +espeakng_loader/espeak-ng-data/voices/!v/iven2,sha256=-Ugw5avhGNxMCQljDWZje6KnyUlXJ5wx_XjjEzdAVM0,279 +espeakng_loader/espeak-ng-data/voices/!v/iven3,sha256=J8zy0ve7jx_yjHBcOc9v9XXrJFjDmlGO0zdBrZwa8lI,262 +espeakng_loader/espeak-ng-data/voices/!v/iven4,sha256=EbPUbAHUMH7ty2C9jbzHOkDz64bCiRdtb9W7QYIjuS8,261 +espeakng_loader/espeak-ng-data/voices/!v/john,sha256=v7zBzsM-8Fgf3rSVX7zQ2CSl1L5Uk9cx5KLvf487pnA,3186 +espeakng_loader/espeak-ng-data/voices/!v/kaukovalta,sha256=ufYBYUWDXDmZvNWHK4pTRCcpvZA1kXgeozQHRrO0lWs,361 +espeakng_loader/espeak-ng-data/voices/!v/klatt,sha256=mrttBdDKNUgxxXDhQyPdToIUWbUxZtljlYdaSLrNveI,38 +espeakng_loader/espeak-ng-data/voices/!v/klatt2,sha256=r6tmKlWVNTL_jW-cYVuCTs7If3rvZ5CljEzLxFBadCo,38 +espeakng_loader/espeak-ng-data/voices/!v/klatt3,sha256=8cDNFHvWVvbEgwszQclpRINDjEOuoVyYLcwZRduzNLk,39 +espeakng_loader/espeak-ng-data/voices/!v/klatt4,sha256=NFnBWqj6fXIYrDQ4jfwIM8hQ_8kjATlJMIwvZD89qtI,39 +espeakng_loader/espeak-ng-data/voices/!v/klatt5,sha256=RDl9goJFSil0B40lUJyqRwvOsJPkhOcnhDpRR7QZPmA,39 +espeakng_loader/espeak-ng-data/voices/!v/klatt6,sha256=fTkwzZfvegcy8uGfU_hOSA8tRB0mM5Bke5K7C0xkXQU,39 +espeakng_loader/espeak-ng-data/voices/!v/linda,sha256=3wa0wp9ZUwNOeBXqcGLjVpFyZvj6tXb3bANgRVJcjig,350 +espeakng_loader/espeak-ng-data/voices/!v/m1,sha256=fy3gI73-GGUdLQRT0uf_XorenwlJEqeSRzNt3JD9d4M,335 +espeakng_loader/espeak-ng-data/voices/!v/m2,sha256=brkl62aRYhpt5myHWWxu2HnICgQhWpqEN9_8KPz6FN0,264 +espeakng_loader/espeak-ng-data/voices/!v/m3,sha256=ekrIcjh0OYFN3WX14f9zAXEil1kR32tdxixXCeb9thE,300 +espeakng_loader/espeak-ng-data/voices/!v/m4,sha256=a--CzqNTjaEka3osIDIG6QFVy7Svhvqo7wM2bDEZzu4,290 +espeakng_loader/espeak-ng-data/voices/!v/m5,sha256=CFkO9843YwpoddnL4gDcRzqQVLQYQoeAik_RyOJ90Co,262 +espeakng_loader/espeak-ng-data/voices/!v/m6,sha256=_A4Br0WKltQ_VYeAENOry72oXoRpIrJTYaeNJ8OpygA,188 +espeakng_loader/espeak-ng-data/voices/!v/m7,sha256=vfxUo1WMqY-coIJHnFIRA0qCTYch25GAT513hn22-rM,254 +espeakng_loader/espeak-ng-data/voices/!v/m8,sha256=BgEwVA4vrl-Kz7GbzU7z3F3I-NITTFArtXryd_1MxJE,284 +espeakng_loader/espeak-ng-data/voices/!v/marcelo,sha256=MjipM6F8QMYc3ThcDnQr9UxCwAj0EQ1LA1OmrnKl0aA,251 +espeakng_loader/espeak-ng-data/voices/!v/max,sha256=yI9wpgoZ52pndN-9dmS-Y5uaqKpYfGgINMMF_6Q0qq8,225 +espeakng_loader/espeak-ng-data/voices/!v/michel,sha256=wAaK2ct5Lft4rtvf-cPOxo5Qg3NrrgwzvxkIgYYQEIc,404 +espeakng_loader/espeak-ng-data/voices/!v/miguel,sha256=nIwrvp-6bR8G62PuZ9mNfruIRrK_E4R6mzWckLqfqP4,382 +espeakng_loader/espeak-ng-data/voices/!v/mike2,sha256=J068XfJSsyWOiZbxJ2E3ss-dblAG4RRaUXKZcoTx26A,188 +espeakng_loader/espeak-ng-data/voices/!v/norbert,sha256=NbmSPhXK82KAVCJwKCvSOSxthu9duai-e-ks4iQaRss,3189 +espeakng_loader/espeak-ng-data/voices/!v/pablo,sha256=BTqFyKbX56D2QyoxWP5z-prM8GIC5dacJz1OW66Lr8g,3142 +espeakng_loader/espeak-ng-data/voices/!v/paul,sha256=dfuAmL6iiFlRPebOAzCSMHOC1vIEVecbBRGT38B5PV4,284 +espeakng_loader/espeak-ng-data/voices/!v/pedro,sha256=dCl5K6gz-iRGvsbbeQBo9YYrntCZOSACzQ5yTsarKmY,352 +espeakng_loader/espeak-ng-data/voices/!v/quincy,sha256=6ZRb7ntPMkAiGGb0l78lEaiG7XcC2DiWiKA8LqEgyvA,354 +espeakng_loader/espeak-ng-data/voices/!v/rob,sha256=-__82wr7Ljtw-IbAIoL-riJQnXf-bnED2vkH96NWWV0,265 +espeakng_loader/espeak-ng-data/voices/!v/robert,sha256=cmBPha_lu1Klzn40J7GW4ePkJqFKZOLZO2YX4kikZBc,274 +espeakng_loader/espeak-ng-data/voices/!v/robosoft,sha256=zigg7dNJ8_vHNL_pQJVRjxDsvv2zBFYBCfNxBvn00vo,451 +espeakng_loader/espeak-ng-data/voices/!v/robosoft2,sha256=JJpE9AabMjZA5rUy_2qbww3KNfX5pfZmtkeTfLxYxoU,454 +espeakng_loader/espeak-ng-data/voices/!v/robosoft3,sha256=-FQ-_hgBnHNeutmdHKtOBuDv1WWsJpqJVBXf6_NCw4M,455 +espeakng_loader/espeak-ng-data/voices/!v/robosoft4,sha256=1fco4NCp0n9gTzToNeBZWQ_QFBH9RnyRMotXPHWXuy0,447 +espeakng_loader/espeak-ng-data/voices/!v/robosoft5,sha256=OdoO_hdo4U7v4FpwGfq0Fnlbv_siL84jrX-WOZFEf3s,445 +espeakng_loader/espeak-ng-data/voices/!v/robosoft6,sha256=RkJpcddsNCZlgBM_rSwmq4KTlaccFxPmIF2dRrCHFnI,287 +espeakng_loader/espeak-ng-data/voices/!v/robosoft7,sha256=4ZwQRSWdnPsHjCKdXRNy98Wvlx0OJTakG4nEDKPiPt4,410 +espeakng_loader/espeak-ng-data/voices/!v/robosoft8,sha256=OJIwRhZHg2wbZsUZOcCkk-P7yB4revwBxviLj52iHis,243 +espeakng_loader/espeak-ng-data/voices/!v/sandro,sha256=G4w2o841ony7q_RnnfAmTNN_THm2aqH0wxDrMbnIBJA,530 +espeakng_loader/espeak-ng-data/voices/!v/shelby,sha256=XpZWUEW83VtC560Oqyu9Zwxnz1yePyrGtQswWA-5K-Q,280 +espeakng_loader/espeak-ng-data/voices/!v/steph,sha256=eBhq7dzkxEk0jzaARrJmU3WxpJLpSNc5JJsMlk8IKGE,364 +espeakng_loader/espeak-ng-data/voices/!v/steph2,sha256=yohBS0hVP-0f1Ak4lUipTqkM8oLWNA48uWjIU4oqwuw,367 +espeakng_loader/espeak-ng-data/voices/!v/steph3,sha256=p9eWIRtpabqSIT-J3lSwU4kDBq93RCTuOPsCrORehS0,377 +espeakng_loader/espeak-ng-data/voices/!v/travis,sha256=fVo0vgV3juhQ2XsEkaYtt2g8BY1mD_KvxxwIyHNg8w0,383 +espeakng_loader/espeak-ng-data/voices/!v/victor,sha256=qICoCDrF6q35T3HGO1HzTBQm1L_gom9nYd3sXG6aXHY,253 +espeakng_loader/espeak-ng-data/voices/!v/whisper,sha256=HjU0yEN2iJjOpHo_g7L9kXIMB3W0OOpcATRnaUCmbpY,186 +espeakng_loader/espeak-ng-data/voices/!v/whisperf,sha256=f-pCsQEU8b_SAEGB5rDrYmmXzKmHiT4j0ktcYWqsidc,392 +espeakng_loader/espeak-ng-data/voices/!v/zac,sha256=7a9Qiyz7_WCIoWPcx41faiaFCn05paDlEosJUm9Wtts,275 +espeakng_loader/espeak-ng-data/yue_dict,sha256=HSavogMDRph3IQer__G1OsvuMENHAKTSt13umJUViPg,563571 +espeakng_loader/espeak-ng.dll,sha256=ZG04esvHrCqkXjYlqgCmg1rl1Eb_iwdIKYw5ALTd4lg,419328 diff --git a/TTS/Kokoro/.venv/Lib/site-packages/espeakng_loader-0.2.4.dist-info/WHEEL b/TTS/Kokoro/.venv/Lib/site-packages/espeakng_loader-0.2.4.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..299f6f5a94ed6ae38bc43f462d4bc53732cfacc1 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/espeakng_loader-0.2.4.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.27.0 +Root-Is-Purelib: false +Tag: py3-none-win_amd64 diff --git a/TTS/Kokoro/.venv/Lib/site-packages/espeakng_loader/__init__.py b/TTS/Kokoro/.venv/Lib/site-packages/espeakng_loader/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b552c609866ac20521e88fb1e96963639cceaa75 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/espeakng_loader/__init__.py @@ -0,0 +1,45 @@ +from pathlib import Path +import ctypes +import platform +import os + +def get_library_path(): + ext = ".dll" if platform.system() == "Windows" else ".so" if platform.system() == "Linux" else ".dylib" + lib_name = "espeak-ng" + ext if platform.system() == "Windows" else 'libespeak-ng' + ext + return str(Path(__file__).parent / lib_name) + +def get_data_path(): + data_path = Path(__file__).parent / 'espeak-ng-data' + if not data_path.exists(): + raise RuntimeError(f'data path not exists at {data_path}') + return str(data_path) + +def load_library(): + """ + Load the shared library. + """ + try: + lib_path = get_library_path() + lib = ctypes.CDLL(lib_path) + return lib + except OSError as e: + print(f"Error loading shared library from {lib_path}: {e}") + return None + +def make_library_available(): + """ + Add the directory containing the shared library to the system's library path. + """ + lib = get_library_path() + lib_dir = str(Path(lib).parent) + # Windows + if platform.system() == "Windows": + os.add_dll_directory(lib_dir) + # Linux + elif platform.system() == "Linux": + os.environ["LD_LIBRARY_PATH"] = lib_dir + ":" + os.environ.get("LD_LIBRARY_PATH", "") + # MacOS + elif platform.system() == "Darwin": + os.environ["DYLD_LIBRARY_PATH"] = lib_dir + ":" + os.environ.get("DYLD_LIBRARY_PATH", "") + else: + raise Exception(f"Unsupported platform: {platform.system()}") \ No newline at end of file diff --git a/TTS/Kokoro/.venv/Lib/site-packages/fastapi/background.py b/TTS/Kokoro/.venv/Lib/site-packages/fastapi/background.py new file mode 100644 index 0000000000000000000000000000000000000000..7677058c438105d599233d441e8e7de81225a697 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/fastapi/background.py @@ -0,0 +1,61 @@ +from collections.abc import Callable +from typing import Annotated, Any + +from annotated_doc import Doc +from starlette.background import BackgroundTasks as StarletteBackgroundTasks +from typing_extensions import ParamSpec + +P = ParamSpec("P") + + +class BackgroundTasks(StarletteBackgroundTasks): + """ + A collection of background tasks that will be called after a response has been + sent to the client. + + Read more about it in the + [FastAPI docs for Background Tasks](https://fastapi.tiangolo.com/tutorial/background-tasks/). + + ## Example + + ```python + from fastapi import BackgroundTasks, FastAPI + + app = FastAPI() + + + def write_notification(email: str, message=""): + with open("log.txt", mode="w") as email_file: + content = f"notification for {email}: {message}" + email_file.write(content) + + + @app.post("/send-notification/{email}") + async def send_notification(email: str, background_tasks: BackgroundTasks): + background_tasks.add_task(write_notification, email, message="some notification") + return {"message": "Notification sent in the background"} + ``` + """ + + def add_task( + self, + func: Annotated[ + Callable[P, Any], + Doc( + """ + The function to call after the response is sent. + + It can be a regular `def` function or an `async def` function. + """ + ), + ], + *args: P.args, + **kwargs: P.kwargs, + ) -> None: + """ + Add a function to be called in the background after the response is sent. + + Read more about it in the + [FastAPI docs for Background Tasks](https://fastapi.tiangolo.com/tutorial/background-tasks/). + """ + return super().add_task(func, *args, **kwargs) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/fastapi/cli.py b/TTS/Kokoro/.venv/Lib/site-packages/fastapi/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..8d3301e9daf73b474162d712f4b87f54ccd97a16 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/fastapi/cli.py @@ -0,0 +1,13 @@ +try: + from fastapi_cli.cli import main as cli_main + +except ImportError: # pragma: no cover + cli_main = None # type: ignore + + +def main() -> None: + if not cli_main: # type: ignore[truthy-function] + message = 'To use the fastapi command, please install "fastapi[standard]":\n\n\tpip install "fastapi[standard]"\n' + print(message) + raise RuntimeError(message) # noqa: B904 + cli_main() diff --git a/TTS/Kokoro/.venv/Lib/site-packages/fastapi/concurrency.py b/TTS/Kokoro/.venv/Lib/site-packages/fastapi/concurrency.py new file mode 100644 index 0000000000000000000000000000000000000000..76a5a2eb128bc8c22d61d986ab2cdc434178dd24 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/fastapi/concurrency.py @@ -0,0 +1,41 @@ +from collections.abc import AsyncGenerator +from contextlib import AbstractContextManager +from contextlib import asynccontextmanager as asynccontextmanager +from typing import TypeVar + +import anyio.to_thread +from anyio import CapacityLimiter +from starlette.concurrency import iterate_in_threadpool as iterate_in_threadpool # noqa +from starlette.concurrency import run_in_threadpool as run_in_threadpool # noqa +from starlette.concurrency import ( # noqa + run_until_first_complete as run_until_first_complete, +) + +_T = TypeVar("_T") + + +@asynccontextmanager +async def contextmanager_in_threadpool( + cm: AbstractContextManager[_T], +) -> AsyncGenerator[_T, None]: + # blocking __exit__ from running waiting on a free thread + # can create race conditions/deadlocks if the context manager itself + # has its own internal pool (e.g. a database connection pool) + # to avoid this we let __exit__ run without a capacity limit + # since we're creating a new limiter for each call, any non-zero limit + # works (1 is arbitrary) + exit_limiter = CapacityLimiter(1) + try: + yield await run_in_threadpool(cm.__enter__) + except Exception as e: + ok = bool( + await anyio.to_thread.run_sync( + cm.__exit__, type(e), e, e.__traceback__, limiter=exit_limiter + ) + ) + if not ok: + raise e + else: + await anyio.to_thread.run_sync( + cm.__exit__, None, None, None, limiter=exit_limiter + ) diff --git a/TTS/Kokoro/.venv/Lib/site-packages/fastapi/datastructures.py b/TTS/Kokoro/.venv/Lib/site-packages/fastapi/datastructures.py new file mode 100644 index 0000000000000000000000000000000000000000..479e1a7c3be29cf2f30e10928aea8fad63623090 --- /dev/null +++ b/TTS/Kokoro/.venv/Lib/site-packages/fastapi/datastructures.py @@ -0,0 +1,181 @@ +from collections.abc import Callable, Mapping +from typing import ( + Annotated, + Any, + BinaryIO, + TypeVar, + cast, +) + +from annotated_doc import Doc +from pydantic import GetJsonSchemaHandler +from starlette.datastructures import URL as URL # noqa: F401 +from starlette.datastructures import Address as Address # noqa: F401 +from starlette.datastructures import FormData as FormData # noqa: F401 +from starlette.datastructures import Headers as Headers # noqa: F401 +from starlette.datastructures import QueryParams as QueryParams # noqa: F401 +from starlette.datastructures import State as State # noqa: F401 +from starlette.datastructures import UploadFile as StarletteUploadFile + + +class UploadFile(StarletteUploadFile): + """ + A file uploaded in a request. + + Define it as a *path operation function* (or dependency) parameter. + + If you are using a regular `def` function, you can use the `upload_file.file` + attribute to access the raw standard Python file (blocking, not async), useful and + needed for non-async code. + + Read more about it in the + [FastAPI docs for Request Files](https://fastapi.tiangolo.com/tutorial/request-files/). + + ## Example + + ```python + from typing import Annotated + + from fastapi import FastAPI, File, UploadFile + + app = FastAPI() + + + @app.post("/files/") + async def create_file(file: Annotated[bytes, File()]): + return {"file_size": len(file)} + + + @app.post("/uploadfile/") + async def create_upload_file(file: UploadFile): + return {"filename": file.filename} + ``` + """ + + file: Annotated[ + BinaryIO, + Doc("The standard Python file object (non-async)."), + ] + filename: Annotated[str | None, Doc("The original file name.")] + size: Annotated[int | None, Doc("The size of the file in bytes.")] + headers: Annotated[Headers, Doc("The headers of the request.")] + content_type: Annotated[ + str | None, Doc("The content type of the request, from the headers.") + ] + + async def write( + self, + data: Annotated[ + bytes, + Doc( + """ + The bytes to write to the file. + """ + ), + ], + ) -> None: + """ + Write some bytes to the file. + + You normally wouldn't use this from a file you read in a request. + + To be awaitable, compatible with async, this is run in threadpool. + """ + return await super().write(data) + + async def read( + self, + size: Annotated[ + int, + Doc( + """ + The number of bytes to read from the file. + """ + ), + ] = -1, + ) -> bytes: + """ + Read some bytes from the file. + + To be awaitable, compatible with async, this is run in threadpool. + """ + return await super().read(size) + + async def seek( + self, + offset: Annotated[ + int, + Doc( + """ + The position in bytes to seek to in the file. + """ + ), + ], + ) -> None: + """ + Move to a position in the file. + + Any next read or write will be done from that position. + + To be awaitable, compatible with async, this is run in threadpool. + """ + return await super().seek(offset) + + async def close(self) -> None: + """ + Close the file. + + To be awaitable, compatible with async, this is run in threadpool. + """ + return await super().close() + + @classmethod + def _validate(cls, __input_value: Any, _: Any) -> "UploadFile": + if not isinstance(__input_value, StarletteUploadFile): + raise ValueError(f"Expected UploadFile, received: {type(__input_value)}") + return cast(UploadFile, __input_value) + + @classmethod + def __get_pydantic_json_schema__( + cls, core_schema: Mapping[str, Any], handler: GetJsonSchemaHandler + ) -> dict[str, Any]: + return {"type": "string", "contentMediaType": "application/octet-stream"} + + @classmethod + def __get_pydantic_core_schema__( + cls, source: type[Any], handler: Callable[[Any], Mapping[str, Any]] + ) -> Mapping[str, Any]: + from ._compat.v2 import with_info_plain_validator_function + + return with_info_plain_validator_function(cls._validate) + + +class DefaultPlaceholder: + """ + You shouldn't use this class directly. + + It's used internally to recognize when a default value has been overwritten, even + if the overridden default value was truthy. + """ + + def __init__(self, value: Any): + self.value = value + + def __bool__(self) -> bool: + return bool(self.value) + + def __eq__(self, o: object) -> bool: + return isinstance(o, DefaultPlaceholder) and o.value == self.value + + +DefaultType = TypeVar("DefaultType") + + +def Default(value: DefaultType) -> DefaultType: + """ + You shouldn't use this function directly. + + It's used internally to recognize when a default value has been overwritten, even + if the overridden default value was truthy. + """ + return DefaultPlaceholder(value) # type: ignore