Instructions to use giancap61/AXEL-AI_Virtual_Race_Engineer with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- llama.cpp
How to use giancap61/AXEL-AI_Virtual_Race_Engineer with llama.cpp:
Install (macOS, Linux)
curl -LsSf https://llama.app/install.sh | sh # Start a local OpenAI-compatible server with a web UI: llama serve -hf giancap61/AXEL-AI_Virtual_Race_Engineer:Q5_K_M # Run inference directly in the terminal: llama cli -hf giancap61/AXEL-AI_Virtual_Race_Engineer:Q5_K_M
Install from WinGet (Windows)
winget install llama.cpp # Start a local OpenAI-compatible server with a web UI: llama serve -hf giancap61/AXEL-AI_Virtual_Race_Engineer:Q5_K_M # Run inference directly in the terminal: llama cli -hf giancap61/AXEL-AI_Virtual_Race_Engineer:Q5_K_M
Build from source code
git clone https://github.com/ggml-org/llama.cpp.git cd llama.cpp cmake -B build cmake --build build -j --target llama-app # Start a local OpenAI-compatible server with a web UI: ./build/bin/llama serve -hf giancap61/AXEL-AI_Virtual_Race_Engineer:Q5_K_M # Run inference directly in the terminal: ./build/bin/llama cli -hf giancap61/AXEL-AI_Virtual_Race_Engineer:Q5_K_M
Use Docker
docker model run hf.co/giancap61/AXEL-AI_Virtual_Race_Engineer:Q5_K_M
- Llama new
- LM Studio
- Jan
- Ollama
How to use giancap61/AXEL-AI_Virtual_Race_Engineer with Ollama:
ollama run hf.co/giancap61/AXEL-AI_Virtual_Race_Engineer:Q5_K_M
- Unsloth Desktop
- Pi
How to use giancap61/AXEL-AI_Virtual_Race_Engineer with Pi:
Start the llama.cpp server
# Install llama.cpp: brew install llama.cpp # Start a local OpenAI-compatible server: llama serve -hf giancap61/AXEL-AI_Virtual_Race_Engineer:Q5_K_M
Configure the model in Pi
# Install Pi: npm install -g @earendil-works/pi-coding-agent # Add to ~/.pi/agent/models.json: { "providers": { "llama-cpp": { "baseUrl": "http://localhost:9931/v1", "api": "openai-completions", "apiKey": "none", "models": [ { "id": "giancap61/AXEL-AI_Virtual_Race_Engineer:Q5_K_M" } ] } } }Run Pi
# Start Pi in your project directory: pi
- Docker Model Runner
How to use giancap61/AXEL-AI_Virtual_Race_Engineer with Docker Model Runner:
docker model run hf.co/giancap61/AXEL-AI_Virtual_Race_Engineer:Q5_K_M
- Lemonade
How to use giancap61/AXEL-AI_Virtual_Race_Engineer with Lemonade:
Pull the model
# Download Lemonade from https://lemonade-server.ai/ lemonade pull giancap61/AXEL-AI_Virtual_Race_Engineer:Q5_K_M
Run and chat with the model
lemonade run user.AXEL-AI_Virtual_Race_Engineer-Q5_K_M
List all available models
lemonade list
- Hermes Agent
How to use giancap61/AXEL-AI_Virtual_Race_Engineer with Hermes Agent:
Start the llama.cpp server
# Install llama.cpp: brew install llama.cpp # Start a local OpenAI-compatible server: llama serve -hf giancap61/AXEL-AI_Virtual_Race_Engineer:Q5_K_M
Configure Hermes
# Install Hermes: curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash hermes setup # Point Hermes at the local server: hermes config set model.provider custom hermes config set model.base_url http://127.0.0.1:9931/v1 hermes config set model.default giancap61/AXEL-AI_Virtual_Race_Engineer:Q5_K_M
Run Hermes
hermes
- Atomic Chat
- OpenClaw
How to use giancap61/AXEL-AI_Virtual_Race_Engineer with OpenClaw:
Start the llama.cpp server
# Install llama.cpp: brew install llama.cpp # Start a local OpenAI-compatible server: llama serve -hf giancap61/AXEL-AI_Virtual_Race_Engineer:Q5_K_M
Configure OpenClaw
# Install OpenClaw: npm install -g openclaw@latest # Register the local server and set it as the default model: openclaw onboard --non-interactive --mode local \ --auth-choice custom-api-key \ --custom-base-url http://127.0.0.1:9931/v1 \ --custom-model-id "giancap61/AXEL-AI_Virtual_Race_Engineer:Q5_K_M" \ --custom-provider-id llama-cpp \ --custom-compatibility openai \ --custom-text-input \ --accept-risk \ --skip-health
Run OpenClaw
openclaw agent --local --agent main --message "Hello from Hugging Face"
Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib-0.23.0.dist-info/INSTALLER +1 -0
- TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib-0.23.0.dist-info/METADATA +259 -0
- TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib-0.23.0.dist-info/RECORD +64 -0
- TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib-0.23.0.dist-info/WHEEL +4 -0
- TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib/__init__.py +57 -0
- TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib/cloudpath.py +1721 -0
- TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib/enums.py +44 -0
- TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib/exceptions.py +87 -0
- TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib/patches.py +388 -0
- TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib/py.typed +0 -0
- TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib/url_utils.py +31 -0
- TTS/Kokoro/.venv/Lib/site-packages/colorama-0.4.6.dist-info/INSTALLER +1 -0
- TTS/Kokoro/.venv/Lib/site-packages/colorama-0.4.6.dist-info/METADATA +441 -0
- TTS/Kokoro/.venv/Lib/site-packages/colorama-0.4.6.dist-info/RECORD +31 -0
- TTS/Kokoro/.venv/Lib/site-packages/colorama-0.4.6.dist-info/WHEEL +5 -0
- TTS/Kokoro/.venv/Lib/site-packages/colorama/__init__.py +7 -0
- TTS/Kokoro/.venv/Lib/site-packages/colorama/ansi.py +102 -0
- TTS/Kokoro/.venv/Lib/site-packages/colorama/ansitowin32.py +277 -0
- TTS/Kokoro/.venv/Lib/site-packages/colorama/initialise.py +121 -0
- TTS/Kokoro/.venv/Lib/site-packages/colorama/win32.py +180 -0
- TTS/Kokoro/.venv/Lib/site-packages/colorama/winterm.py +195 -0
- TTS/Kokoro/.venv/Lib/site-packages/confection-0.1.5.dist-info/INSTALLER +1 -0
- TTS/Kokoro/.venv/Lib/site-packages/confection-0.1.5.dist-info/LICENSE +21 -0
- TTS/Kokoro/.venv/Lib/site-packages/confection-0.1.5.dist-info/METADATA +416 -0
- TTS/Kokoro/.venv/Lib/site-packages/confection-0.1.5.dist-info/RECORD +22 -0
- TTS/Kokoro/.venv/Lib/site-packages/confection-0.1.5.dist-info/WHEEL +5 -0
- TTS/Kokoro/.venv/Lib/site-packages/confection-0.1.5.dist-info/top_level.txt +1 -0
- TTS/Kokoro/.venv/Lib/site-packages/confection-0.1.5.dist-info/zip-safe +1 -0
- TTS/Kokoro/.venv/Lib/site-packages/confection/__init__.py +1095 -0
- TTS/Kokoro/.venv/Lib/site-packages/confection/py.typed +0 -0
- TTS/Kokoro/.venv/Lib/site-packages/confection/util.py +143 -0
- TTS/Kokoro/.venv/Lib/site-packages/csvw-3.7.0.dist-info/INSTALLER +1 -0
- TTS/Kokoro/.venv/Lib/site-packages/csvw-3.7.0.dist-info/LICENSE +201 -0
- TTS/Kokoro/.venv/Lib/site-packages/csvw-3.7.0.dist-info/METADATA +301 -0
- TTS/Kokoro/.venv/Lib/site-packages/csvw-3.7.0.dist-info/RECORD +33 -0
- TTS/Kokoro/.venv/Lib/site-packages/csvw-3.7.0.dist-info/WHEEL +6 -0
- TTS/Kokoro/.venv/Lib/site-packages/csvw-3.7.0.dist-info/entry_points.txt +7 -0
- TTS/Kokoro/.venv/Lib/site-packages/csvw-3.7.0.dist-info/top_level.txt +1 -0
- TTS/Kokoro/.venv/Lib/site-packages/csvw/__init__.py +27 -0
- TTS/Kokoro/.venv/Lib/site-packages/csvw/__main__.py +163 -0
- TTS/Kokoro/.venv/Lib/site-packages/csvw/datatypes.py +1280 -0
- TTS/Kokoro/.venv/Lib/site-packages/csvw/db.py +581 -0
- TTS/Kokoro/.venv/Lib/site-packages/csvw/dsv.py +458 -0
- TTS/Kokoro/.venv/Lib/site-packages/csvw/dsv_dialects.py +160 -0
- TTS/Kokoro/.venv/Lib/site-packages/csvw/frictionless.py +224 -0
- TTS/Kokoro/.venv/Lib/site-packages/csvw/jsonld.py +189 -0
- TTS/Kokoro/.venv/Lib/site-packages/csvw/metadata.py +1873 -0
- TTS/Kokoro/.venv/Lib/site-packages/csvw/utils.py +230 -0
- TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers-0.0.9.dist-info/INSTALLER +1 -0
- TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers-0.0.9.dist-info/LICENSE +52 -0
TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib-0.23.0.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
pip
|
TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib-0.23.0.dist-info/METADATA
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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keywords: pathlib,cloud storage,s3,azure blob storage,google cloud storage
|
| 6 |
+
Author-email: DrivenData <info@drivendata.org>
|
| 7 |
+
Requires-Python: >=3.9
|
| 8 |
+
Description-Content-Type: text/markdown
|
| 9 |
+
Classifier: Intended Audience :: Developers
|
| 10 |
+
Classifier: License :: OSI Approved :: MIT License
|
| 11 |
+
Classifier: Operating System :: OS Independent
|
| 12 |
+
Classifier: Programming Language :: Python :: 3
|
| 13 |
+
Classifier: Programming Language :: Python :: 3.9
|
| 14 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 15 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 16 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 17 |
+
Classifier: Programming Language :: Python :: 3.13
|
| 18 |
+
Classifier: Programming Language :: Python :: 3.14
|
| 19 |
+
License-File: LICENSE
|
| 20 |
+
Requires-Dist: typing-extensions>4 ; python_version < '3.11'
|
| 21 |
+
Requires-Dist: cloudpathlib[azure] ; extra == "all"
|
| 22 |
+
Requires-Dist: cloudpathlib[gs] ; extra == "all"
|
| 23 |
+
Requires-Dist: cloudpathlib[s3] ; extra == "all"
|
| 24 |
+
Requires-Dist: azure-storage-blob>=12 ; extra == "azure"
|
| 25 |
+
Requires-Dist: azure-storage-file-datalake>=12 ; extra == "azure"
|
| 26 |
+
Requires-Dist: google-cloud-storage ; extra == "gs"
|
| 27 |
+
Requires-Dist: boto3>=1.34.0 ; extra == "s3"
|
| 28 |
+
Project-URL: Bug Tracker, https://github.com/drivendataorg/cloudpathlib/issues
|
| 29 |
+
Project-URL: Changelog, https://cloudpathlib.drivendata.org/stable/changelog/
|
| 30 |
+
Project-URL: Documentation, https://cloudpathlib.drivendata.org/
|
| 31 |
+
Project-URL: Repository, https://github.com/drivendataorg/cloudpathlib
|
| 32 |
+
Provides-Extra: all
|
| 33 |
+
Provides-Extra: azure
|
| 34 |
+
Provides-Extra: gs
|
| 35 |
+
Provides-Extra: s3
|
| 36 |
+
|
| 37 |
+

|
| 38 |
+
|
| 39 |
+
<h1></h1>
|
| 40 |
+
|
| 41 |
+
[](https://cloudpathlib.drivendata.org/)
|
| 42 |
+
[](https://pypi.org/project/cloudpathlib/)
|
| 43 |
+
[](https://anaconda.org/conda-forge/cloudpathlib)
|
| 44 |
+
[](https://github.com/conda-forge/cloudpathlib-feedstock)
|
| 45 |
+
[](https://github.com/drivendataorg/cloudpathlib/actions/workflows/tests.yml?query=branch%3Amaster)
|
| 46 |
+
[](https://codecov.io/gh/drivendataorg/cloudpathlib)
|
| 47 |
+
|
| 48 |
+
> 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.
|
| 49 |
+
|
| 50 |
+
A Python library with classes that mimic `pathlib.Path`'s interface for URIs from different cloud storage services.
|
| 51 |
+
|
| 52 |
+
```python
|
| 53 |
+
with CloudPath("s3://bucket/filename.txt").open("w+") as f:
|
| 54 |
+
f.write("Send my changes to the cloud!")
|
| 55 |
+
```
|
| 56 |
+
|
| 57 |
+
## Why use cloudpathlib?
|
| 58 |
+
|
| 59 |
+
- **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.
|
| 60 |
+
- **Supported clouds**: AWS S3, Google Cloud Storage, and Azure Blob Storage are implemented. FTP is on the way.
|
| 61 |
+
- **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.
|
| 62 |
+
- **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.
|
| 63 |
+
- **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.
|
| 64 |
+
- **Tested**: Comprehensive test suite and code coverage.
|
| 65 |
+
- **Testability**: Local filesystem implementations that can be used to easily mock cloud storage in your unit tests.
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
## Installation
|
| 69 |
+
|
| 70 |
+
`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.
|
| 71 |
+
|
| 72 |
+
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:
|
| 73 |
+
|
| 74 |
+
```bash
|
| 75 |
+
pip install cloudpathlib[s3,gs,azure]
|
| 76 |
+
```
|
| 77 |
+
|
| 78 |
+
With some shells, you may need to use quotes:
|
| 79 |
+
|
| 80 |
+
```bash
|
| 81 |
+
pip install "cloudpathlib[s3,gs,azure]"
|
| 82 |
+
```
|
| 83 |
+
|
| 84 |
+
Currently supported cloud storage services are: `azure`, `gs`, `s3`. You can also use `all` to install all available services' dependencies.
|
| 85 |
+
|
| 86 |
+
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.
|
| 87 |
+
|
| 88 |
+
### conda
|
| 89 |
+
|
| 90 |
+
`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:
|
| 91 |
+
|
| 92 |
+
```bash
|
| 93 |
+
conda install cloudpathlib-s3 -c conda-forge
|
| 94 |
+
```
|
| 95 |
+
|
| 96 |
+
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.
|
| 97 |
+
|
| 98 |
+
### Development version
|
| 99 |
+
|
| 100 |
+
You can get latest development version from GitHub:
|
| 101 |
+
|
| 102 |
+
```bash
|
| 103 |
+
pip install https://github.com/drivendataorg/cloudpathlib.git#egg=cloudpathlib[all]
|
| 104 |
+
```
|
| 105 |
+
|
| 106 |
+
Note that you similarly need to specify cloud service dependencies, such as `all` in the above example command.
|
| 107 |
+
|
| 108 |
+
## Quick usage
|
| 109 |
+
|
| 110 |
+
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.
|
| 111 |
+
|
| 112 |
+
```python
|
| 113 |
+
from cloudpathlib import CloudPath
|
| 114 |
+
|
| 115 |
+
# dispatches to S3Path based on prefix
|
| 116 |
+
root_dir = CloudPath("s3://drivendata-public-assets/")
|
| 117 |
+
root_dir
|
| 118 |
+
#> S3Path('s3://drivendata-public-assets/')
|
| 119 |
+
|
| 120 |
+
# there's only one file, but globbing works in nested folder
|
| 121 |
+
for f in root_dir.glob('**/*.txt'):
|
| 122 |
+
text_data = f.read_text()
|
| 123 |
+
print(f)
|
| 124 |
+
print(text_data)
|
| 125 |
+
#> s3://drivendata-public-assets/odsc-west-2019/DATA_DICTIONARY.txt
|
| 126 |
+
#> Eviction Lab Data Dictionary
|
| 127 |
+
#>
|
| 128 |
+
#> Additional information in our FAQ evictionlab.org/help-faq/
|
| 129 |
+
#> Full methodology evictionlab.org/methods/
|
| 130 |
+
#>
|
| 131 |
+
#> ... (additional text output truncated)
|
| 132 |
+
|
| 133 |
+
# use / to join paths (and, in this case, create a new file)
|
| 134 |
+
new_file_copy = root_dir / "nested_dir/copy_file.txt"
|
| 135 |
+
new_file_copy
|
| 136 |
+
#> S3Path('s3://drivendata-public-assets/nested_dir/copy_file.txt')
|
| 137 |
+
|
| 138 |
+
# show things work and the file does not exist yet
|
| 139 |
+
new_file_copy.exists()
|
| 140 |
+
#> False
|
| 141 |
+
|
| 142 |
+
# writing text data to the new file in the cloud
|
| 143 |
+
new_file_copy.write_text(text_data)
|
| 144 |
+
#> 6933
|
| 145 |
+
|
| 146 |
+
# file now listed
|
| 147 |
+
list(root_dir.glob('**/*.txt'))
|
| 148 |
+
#> [S3Path('s3://drivendata-public-assets/nested_dir/copy_file.txt'),
|
| 149 |
+
#> S3Path('s3://drivendata-public-assets/odsc-west-2019/DATA_DICTIONARY.txt')]
|
| 150 |
+
|
| 151 |
+
# but, we can remove it
|
| 152 |
+
new_file_copy.unlink()
|
| 153 |
+
|
| 154 |
+
# no longer there
|
| 155 |
+
list(root_dir.glob('**/*.txt'))
|
| 156 |
+
#> [S3Path('s3://drivendata-public-assets/odsc-west-2019/DATA_DICTIONARY.txt')]
|
| 157 |
+
```
|
| 158 |
+
|
| 159 |
+
## Supported methods and properties
|
| 160 |
+
|
| 161 |
+
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.
|
| 162 |
+
|
| 163 |
+
| Methods + properties | `AzureBlobPath` | `GSPath` | `HttpsPath` | `S3Path` |
|
| 164 |
+
|:-----------------------|:------------------|:-----------|:--------------|:-----------|
|
| 165 |
+
| `absolute` | ✅ | ✅ | ✅ | ✅ |
|
| 166 |
+
| `anchor` | ✅ | ✅ | ✅ | ✅ |
|
| 167 |
+
| `as_uri` | ✅ | ✅ | ✅ | ✅ |
|
| 168 |
+
| `drive` | ✅ | ✅ | ✅ | ✅ |
|
| 169 |
+
| `exists` | ✅ | ✅ | ✅ | ✅ |
|
| 170 |
+
| `glob` | ✅ | ✅ | ✅ | ✅ |
|
| 171 |
+
| `is_absolute` | ✅ | ✅ | ✅ | ✅ |
|
| 172 |
+
| `is_dir` | ✅ | ✅ | ✅ | ✅ |
|
| 173 |
+
| `is_file` | ✅ | ✅ | ✅ | ✅ |
|
| 174 |
+
| `is_junction` | ✅ | ✅ | ✅ | ✅ |
|
| 175 |
+
| `is_relative_to` | ✅ | ✅ | ✅ | ✅ |
|
| 176 |
+
| `iterdir` | ✅ | ✅ | ✅ | ✅ |
|
| 177 |
+
| `joinpath` | ✅ | ✅ | ✅ | ✅ |
|
| 178 |
+
| `match` | ✅ | ✅ | ✅ | ✅ |
|
| 179 |
+
| `mkdir` | ✅ | ✅ | ✅ | ✅ |
|
| 180 |
+
| `name` | ✅ | ✅ | ✅ | ✅ |
|
| 181 |
+
| `open` | ✅ | ✅ | ✅ | ✅ |
|
| 182 |
+
| `parent` | ✅ | ✅ | ✅ | ✅ |
|
| 183 |
+
| `parents` | ✅ | ✅ | ✅ | ✅ |
|
| 184 |
+
| `parts` | ✅ | ✅ | ✅ | ✅ |
|
| 185 |
+
| `read_bytes` | ✅ | ✅ | ✅ | ✅ |
|
| 186 |
+
| `read_text` | ✅ | ✅ | ✅ | ✅ |
|
| 187 |
+
| `relative_to` | ✅ | ✅ | ✅ | ✅ |
|
| 188 |
+
| `rename` | ✅ | ✅ | ✅ | ✅ |
|
| 189 |
+
| `replace` | ✅ | ✅ | ✅ | ✅ |
|
| 190 |
+
| `resolve` | ✅ | ✅ | ✅ | ✅ |
|
| 191 |
+
| `rglob` | ✅ | ✅ | ✅ | ✅ |
|
| 192 |
+
| `rmdir` | ✅ | ✅ | ✅ | ✅ |
|
| 193 |
+
| `samefile` | ✅ | ✅ | ✅ | ✅ |
|
| 194 |
+
| `stat` | ✅ | ✅ | ✅ | ✅ |
|
| 195 |
+
| `stem` | ✅ | ✅ | ✅ | ✅ |
|
| 196 |
+
| `suffix` | ✅ | ✅ | ✅ | ✅ |
|
| 197 |
+
| `suffixes` | ✅ | ✅ | ✅ | ✅ |
|
| 198 |
+
| `touch` | ✅ | ✅ | ✅ | ✅ |
|
| 199 |
+
| `unlink` | ✅ | ✅ | ✅ | ✅ |
|
| 200 |
+
| `walk` | ✅ | ✅ | ✅ | ✅ |
|
| 201 |
+
| `with_name` | ✅ | ✅ | ✅ | ✅ |
|
| 202 |
+
| `with_segments` | ✅ | ✅ | ✅ | ✅ |
|
| 203 |
+
| `with_stem` | ✅ | ✅ | ✅ | ✅ |
|
| 204 |
+
| `with_suffix` | ✅ | ✅ | ✅ | ✅ |
|
| 205 |
+
| `write_bytes` | ✅ | ✅ | ✅ | ✅ |
|
| 206 |
+
| `write_text` | ✅ | ✅ | ✅ | ✅ |
|
| 207 |
+
| `as_posix` | ❌ | ❌ | ❌ | ❌ |
|
| 208 |
+
| `chmod` | ❌ | ❌ | ❌ | ❌ |
|
| 209 |
+
| `cwd` | ❌ | ❌ | ❌ | ❌ |
|
| 210 |
+
| `expanduser` | ❌ | ❌ | ❌ | ❌ |
|
| 211 |
+
| `group` | ❌ | ❌ | ❌ | ❌ |
|
| 212 |
+
| `hardlink_to` | ❌ | ❌ | ❌ | ❌ |
|
| 213 |
+
| `home` | ❌ | ❌ | ❌ | ❌ |
|
| 214 |
+
| `is_block_device` | ❌ | ❌ | ❌ | ❌ |
|
| 215 |
+
| `is_char_device` | ❌ | ❌ | ❌ | ❌ |
|
| 216 |
+
| `is_fifo` | ❌ | ❌ | ❌ | ❌ |
|
| 217 |
+
| `is_mount` | ❌ | ❌ | ❌ | ❌ |
|
| 218 |
+
| `is_reserved` | ❌ | ❌ | ❌ | ❌ |
|
| 219 |
+
| `is_socket` | ❌ | ❌ | ❌ | ❌ |
|
| 220 |
+
| `is_symlink` | ❌ | ❌ | ❌ | ❌ |
|
| 221 |
+
| `lchmod` | ❌ | ❌ | ❌ | ❌ |
|
| 222 |
+
| `lstat` | ❌ | ❌ | ❌ | ❌ |
|
| 223 |
+
| `owner` | ❌ | ❌ | ❌ | ❌ |
|
| 224 |
+
| `readlink` | ❌ | ❌ | ❌ | ❌ |
|
| 225 |
+
| `root` | ❌ | ❌ | ❌ | ❌ |
|
| 226 |
+
| `symlink_to` | ❌ | ❌ | ❌ | ❌ |
|
| 227 |
+
| `as_url` | ✅ | ✅ | ✅ | ✅ |
|
| 228 |
+
| `clear_cache` | ✅ | ✅ | ✅ | ✅ |
|
| 229 |
+
| `client` | ✅ | ✅ | ✅ | ✅ |
|
| 230 |
+
| `cloud_prefix` | ✅ | ✅ | ✅ | ✅ |
|
| 231 |
+
| `copy` | ✅ | ✅ | ✅ | ✅ |
|
| 232 |
+
| `copytree` | ✅ | ✅ | ✅ | ✅ |
|
| 233 |
+
| `download_to` | ✅ | ✅ | ✅ | ✅ |
|
| 234 |
+
| `from_uri` | ✅ | ✅ | ✅ | ✅ |
|
| 235 |
+
| `fspath` | ✅ | ✅ | ✅ | ✅ |
|
| 236 |
+
| `full_match` | ✅ | ✅ | ✅ | ✅ |
|
| 237 |
+
| `is_valid_cloudpath` | ✅ | ✅ | ✅ | ✅ |
|
| 238 |
+
| `parser` | ✅ | ✅ | ✅ | ✅ |
|
| 239 |
+
| `rmtree` | ✅ | ✅ | ✅ | ✅ |
|
| 240 |
+
| `upload_from` | ✅ | ✅ | ✅ | ✅ |
|
| 241 |
+
| `validate` | ✅ | ✅ | ✅ | ✅ |
|
| 242 |
+
| `etag` | ✅ | ✅ | ❌ | ✅ |
|
| 243 |
+
| `blob` | ✅ | ✅ | ❌ | ❌ |
|
| 244 |
+
| `bucket` | ❌ | ✅ | ❌ | ✅ |
|
| 245 |
+
| `md5` | ✅ | ✅ | ❌ | ❌ |
|
| 246 |
+
| `container` | ✅ | ❌ | ❌ | ❌ |
|
| 247 |
+
| `delete` | ❌ | ❌ | ✅ | ❌ |
|
| 248 |
+
| `get` | ❌ | ❌ | ✅ | ❌ |
|
| 249 |
+
| `head` | ❌ | ❌ | ✅ | ❌ |
|
| 250 |
+
| `key` | ❌ | ❌ | ❌ | ✅ |
|
| 251 |
+
| `parsed_url` | ❌ | ❌ | ✅ | ❌ |
|
| 252 |
+
| `post` | ❌ | ❌ | ✅ | ❌ |
|
| 253 |
+
| `put` | ❌ | ❌ | ✅ | ❌ |
|
| 254 |
+
|
| 255 |
+
----
|
| 256 |
+
|
| 257 |
+
<sup>Icon made by <a href="https://www.flaticon.com/authors/srip" title="srip">srip</a> from <a href="https://www.flaticon.com/" title="Flaticon">www.flaticon.com</a>.</sup>
|
| 258 |
+
<br /><sup>Sample code block generated using the [reprexpy package](https://github.com/crew102/reprexpy).</sup>
|
| 259 |
+
|
TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib-0.23.0.dist-info/RECORD
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
cloudpathlib-0.23.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
| 2 |
+
cloudpathlib-0.23.0.dist-info/METADATA,sha256=eVWbDCUsZPr6k_xykJQPmQ7BY6FX1Rv1loVecL7HKRk,16601
|
| 3 |
+
cloudpathlib-0.23.0.dist-info/RECORD,,
|
| 4 |
+
cloudpathlib-0.23.0.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82
|
| 5 |
+
cloudpathlib-0.23.0.dist-info/licenses/LICENSE,sha256=erAfpsP7WZARylUBfp8J-eZ7ho-0IXNqZlmS23cSwTU,1072
|
| 6 |
+
cloudpathlib/__init__.py,sha256=H9UblguOpsq5xvIbJhVjKd0H-KguDrYJLJ5jEMUBRfs,1359
|
| 7 |
+
cloudpathlib/__pycache__/__init__.cpython-312.pyc,,
|
| 8 |
+
cloudpathlib/__pycache__/anypath.cpython-312.pyc,,
|
| 9 |
+
cloudpathlib/__pycache__/client.cpython-312.pyc,,
|
| 10 |
+
cloudpathlib/__pycache__/cloudpath.cpython-312.pyc,,
|
| 11 |
+
cloudpathlib/__pycache__/cloudpath_info.cpython-312.pyc,,
|
| 12 |
+
cloudpathlib/__pycache__/enums.cpython-312.pyc,,
|
| 13 |
+
cloudpathlib/__pycache__/exceptions.cpython-312.pyc,,
|
| 14 |
+
cloudpathlib/__pycache__/patches.cpython-312.pyc,,
|
| 15 |
+
cloudpathlib/__pycache__/url_utils.cpython-312.pyc,,
|
| 16 |
+
cloudpathlib/anypath.py,sha256=0QmVGO4t6L7Uj7YuVeLikAU4BNcRtJnhjgMLa980Xyg,3510
|
| 17 |
+
cloudpathlib/azure/__init__.py,sha256=eykD2Bqbxyd1NSesyu7_KYslm_5X0OqJpUjZtRX9AYc,139
|
| 18 |
+
cloudpathlib/azure/__pycache__/__init__.cpython-312.pyc,,
|
| 19 |
+
cloudpathlib/azure/__pycache__/azblobclient.cpython-312.pyc,,
|
| 20 |
+
cloudpathlib/azure/__pycache__/azblobpath.cpython-312.pyc,,
|
| 21 |
+
cloudpathlib/azure/azblobclient.py,sha256=k1tvM84N_GK9k5LFsu1fT9FmP_2OkEDWIvChUyxt-vE,22543
|
| 22 |
+
cloudpathlib/azure/azblobpath.py,sha256=hyS3bCXpaZu20RW5hiMgobwWJPEjto_h8RO1i3bL20Y,3703
|
| 23 |
+
cloudpathlib/client.py,sha256=HkPiqBsDkmPR7JlYngtUs-rZSqZPoELCtIfRfV3mfqI,6415
|
| 24 |
+
cloudpathlib/cloudpath.py,sha256=2en2kXLThnywc-H4_ZtAgFIHwQS7YXwJtnf6MMR9uyo,60715
|
| 25 |
+
cloudpathlib/cloudpath_info.py,sha256=aDBcd69tn-qSfiN_pUhIWsxony6Ul5heNyx9MhF5bqA,861
|
| 26 |
+
cloudpathlib/enums.py,sha256=87MNSRcBpXOUD56UIOIZgUerSug2PpH0WBipTkfRUAM,1900
|
| 27 |
+
cloudpathlib/exceptions.py,sha256=OkmReEp1jPRPbkBZNlxo7vKmRSEa3lhTbsewJY47Vd4,1872
|
| 28 |
+
cloudpathlib/gs/__init__.py,sha256=H8poYrpJdGM4Hp16jRJT0iXOW_Zh_6klt0KGoTo8a-o,103
|
| 29 |
+
cloudpathlib/gs/__pycache__/__init__.cpython-312.pyc,,
|
| 30 |
+
cloudpathlib/gs/__pycache__/gsclient.cpython-312.pyc,,
|
| 31 |
+
cloudpathlib/gs/__pycache__/gspath.cpython-312.pyc,,
|
| 32 |
+
cloudpathlib/gs/gsclient.py,sha256=uzG57yjDpBxwgthLfUBfLVYhB91UTYb-tvKNyBWjbrQ,14172
|
| 33 |
+
cloudpathlib/gs/gspath.py,sha256=6eEh6fapPO53SqrFVnSOlHC7MbMtyJ8RNdnCrlSm_gI,3249
|
| 34 |
+
cloudpathlib/http/__init__.py,sha256=HTUt82vdwozNfizoYAcM8RRsJMhKbuvJoYPQshyGBlY,175
|
| 35 |
+
cloudpathlib/http/__pycache__/__init__.cpython-312.pyc,,
|
| 36 |
+
cloudpathlib/http/__pycache__/httpclient.cpython-312.pyc,,
|
| 37 |
+
cloudpathlib/http/__pycache__/httppath.cpython-312.pyc,,
|
| 38 |
+
cloudpathlib/http/httpclient.py,sha256=7vJf10V_w_kg_zk729bmKMe9Emuh0fA9kwV4KoKKGzc,9495
|
| 39 |
+
cloudpathlib/http/httppath.py,sha256=Esld5MwPuuzm8QEaOCm1N5wUOxDD5gAb8mEV3rF_CsM,5635
|
| 40 |
+
cloudpathlib/legacy/__pycache__/glob.cpython-312.pyc,,
|
| 41 |
+
cloudpathlib/legacy/glob.py,sha256=Y2K1WjE6nGTa5td5IDYNxhow9OvzQn9e6v6MHhYYIXo,7465
|
| 42 |
+
cloudpathlib/local/__init__.py,sha256=RK8a8rHM-6IajTPSKpf0EaHKCPYdkmuCR56WlkSAOqQ,1004
|
| 43 |
+
cloudpathlib/local/__pycache__/__init__.cpython-312.pyc,,
|
| 44 |
+
cloudpathlib/local/__pycache__/localclient.cpython-312.pyc,,
|
| 45 |
+
cloudpathlib/local/__pycache__/localpath.cpython-312.pyc,,
|
| 46 |
+
cloudpathlib/local/implementations/__init__.py,sha256=SkIsKSSos4oqz8o_BKsHJ5mgBXVo2SEE_WYIqmSvjws,479
|
| 47 |
+
cloudpathlib/local/implementations/__pycache__/__init__.cpython-312.pyc,,
|
| 48 |
+
cloudpathlib/local/implementations/__pycache__/azure.cpython-312.pyc,,
|
| 49 |
+
cloudpathlib/local/implementations/__pycache__/gs.cpython-312.pyc,,
|
| 50 |
+
cloudpathlib/local/implementations/__pycache__/s3.cpython-312.pyc,,
|
| 51 |
+
cloudpathlib/local/implementations/azure.py,sha256=GR_2VLWLub_IGjbwQqwaxEzs_EH09Ih4Jo_O_RoTeDA,2451
|
| 52 |
+
cloudpathlib/local/implementations/gs.py,sha256=jB6--dGZ6aentk9fY2fqX8XEdnTLAj_D-_TCgGIk2qo,1694
|
| 53 |
+
cloudpathlib/local/implementations/s3.py,sha256=DaKsXbNU651GHANdVCXvh8Ceb4eN7o1ZTtZCXyYC3Fc,1614
|
| 54 |
+
cloudpathlib/local/localclient.py,sha256=ku8c7jlY8StTrGJ-2xFxfCort5Smwt7pVYynTTXjVKE,8832
|
| 55 |
+
cloudpathlib/local/localpath.py,sha256=6PgLWw4w5hgC3OfTi4V2nal1aWAniijcjzTU-IsvnZ0,1043
|
| 56 |
+
cloudpathlib/patches.py,sha256=mbk_7_aC6FTWGdcsJoEAHQ0oQ5WSMOP7Nv9e6zJhbhw,11457
|
| 57 |
+
cloudpathlib/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 58 |
+
cloudpathlib/s3/__init__.py,sha256=o4aATyl9nVQ46JSKpIBLBPnbyiZ5NcmD2txYPAuIR2E,103
|
| 59 |
+
cloudpathlib/s3/__pycache__/__init__.cpython-312.pyc,,
|
| 60 |
+
cloudpathlib/s3/__pycache__/s3client.cpython-312.pyc,,
|
| 61 |
+
cloudpathlib/s3/__pycache__/s3path.cpython-312.pyc,,
|
| 62 |
+
cloudpathlib/s3/s3client.py,sha256=e2CIx_NZnuRCtYMNub6Td6j32rZ9NQgHroMkJRjz-LQ,17311
|
| 63 |
+
cloudpathlib/s3/s3path.py,sha256=YKDI6yn0joSrldfr1hQSiuqqlaDUBQlHHo5kjc5J8NY,2996
|
| 64 |
+
cloudpathlib/url_utils.py,sha256=fAO9RFq9NBMV8qBvkmcE3DBMAPAtW5Pl7XuXB9i49b8,1211
|
TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib-0.23.0.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: flit 3.12.0
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py3-none-any
|
TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib/__init__.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
from .anypath import AnyPath
|
| 5 |
+
from .azure.azblobclient import AzureBlobClient
|
| 6 |
+
from .azure.azblobpath import AzureBlobPath
|
| 7 |
+
from .cloudpath import CloudPath, implementation_registry
|
| 8 |
+
from .patches import patch_open, patch_os_functions, patch_glob, patch_all_builtins
|
| 9 |
+
from .gs.gsclient import GSClient
|
| 10 |
+
from .gs.gspath import GSPath
|
| 11 |
+
from .http.httpclient import HttpClient, HttpsClient
|
| 12 |
+
from .http.httppath import HttpPath, HttpsPath
|
| 13 |
+
from .s3.s3client import S3Client
|
| 14 |
+
from .s3.s3path import S3Path
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
if sys.version_info[:2] >= (3, 8):
|
| 18 |
+
import importlib.metadata as importlib_metadata
|
| 19 |
+
else:
|
| 20 |
+
import importlib_metadata
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
__version__ = importlib_metadata.version(__name__.split(".", 1)[0])
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
__all__ = [
|
| 27 |
+
"AnyPath",
|
| 28 |
+
"AzureBlobClient",
|
| 29 |
+
"AzureBlobPath",
|
| 30 |
+
"CloudPath",
|
| 31 |
+
"implementation_registry",
|
| 32 |
+
"GSClient",
|
| 33 |
+
"GSPath",
|
| 34 |
+
"HttpClient",
|
| 35 |
+
"HttpsClient",
|
| 36 |
+
"HttpPath",
|
| 37 |
+
"HttpsPath",
|
| 38 |
+
"patch_open",
|
| 39 |
+
"patch_glob",
|
| 40 |
+
"patch_os_functions",
|
| 41 |
+
"patch_all_builtins",
|
| 42 |
+
"S3Client",
|
| 43 |
+
"S3Path",
|
| 44 |
+
]
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
if bool(os.environ.get("CLOUDPATHLIB_PATCH_OPEN", "")):
|
| 48 |
+
patch_open()
|
| 49 |
+
|
| 50 |
+
if bool(os.environ.get("CLOUDPATHLIB_PATCH_OS", "")):
|
| 51 |
+
patch_os_functions()
|
| 52 |
+
|
| 53 |
+
if bool(os.environ.get("CLOUDPATHLIB_PATCH_GLOB", "")):
|
| 54 |
+
patch_glob()
|
| 55 |
+
|
| 56 |
+
if bool(os.environ.get("CLOUDPATHLIB_PATCH_ALL", "")):
|
| 57 |
+
patch_all_builtins()
|
TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib/cloudpath.py
ADDED
|
@@ -0,0 +1,1721 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import abc
|
| 2 |
+
from collections import defaultdict
|
| 3 |
+
import collections.abc
|
| 4 |
+
from contextlib import contextmanager
|
| 5 |
+
from io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOWrapper
|
| 6 |
+
import os
|
| 7 |
+
from pathlib import ( # type: ignore
|
| 8 |
+
Path,
|
| 9 |
+
PosixPath,
|
| 10 |
+
PurePosixPath,
|
| 11 |
+
WindowsPath,
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
import shutil
|
| 15 |
+
import sys
|
| 16 |
+
from types import MethodType
|
| 17 |
+
from typing import (
|
| 18 |
+
BinaryIO,
|
| 19 |
+
Literal,
|
| 20 |
+
overload,
|
| 21 |
+
Any,
|
| 22 |
+
Callable,
|
| 23 |
+
Container,
|
| 24 |
+
Iterable,
|
| 25 |
+
IO,
|
| 26 |
+
Dict,
|
| 27 |
+
Generator,
|
| 28 |
+
List,
|
| 29 |
+
Optional,
|
| 30 |
+
Tuple,
|
| 31 |
+
Type,
|
| 32 |
+
TYPE_CHECKING,
|
| 33 |
+
TypeVar,
|
| 34 |
+
Union,
|
| 35 |
+
cast,
|
| 36 |
+
)
|
| 37 |
+
from urllib.parse import urlparse
|
| 38 |
+
from warnings import warn
|
| 39 |
+
|
| 40 |
+
if TYPE_CHECKING:
|
| 41 |
+
from _typeshed import (
|
| 42 |
+
OpenBinaryMode,
|
| 43 |
+
OpenBinaryModeReading,
|
| 44 |
+
OpenBinaryModeUpdating,
|
| 45 |
+
OpenBinaryModeWriting,
|
| 46 |
+
OpenTextMode,
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
if sys.version_info >= (3, 10):
|
| 50 |
+
from typing import TypeGuard
|
| 51 |
+
else:
|
| 52 |
+
from typing_extensions import TypeGuard
|
| 53 |
+
|
| 54 |
+
if sys.version_info >= (3, 11):
|
| 55 |
+
from typing import Self
|
| 56 |
+
else:
|
| 57 |
+
from typing_extensions import Self
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
if sys.version_info < (3, 12):
|
| 61 |
+
from pathlib import _posix_flavour # type: ignore[attr-defined] # noqa: F811
|
| 62 |
+
from pathlib import _make_selector as _make_selector_pathlib # type: ignore[attr-defined] # noqa: F811
|
| 63 |
+
from pathlib import _PathParents # type: ignore[attr-defined]
|
| 64 |
+
|
| 65 |
+
def _make_selector(pattern_parts, _flavour, case_sensitive=True): # noqa: F811
|
| 66 |
+
return _make_selector_pathlib(tuple(pattern_parts), _flavour)
|
| 67 |
+
|
| 68 |
+
elif sys.version_info[:2] == (3, 12):
|
| 69 |
+
from pathlib import _PathParents # type: ignore[attr-defined]
|
| 70 |
+
from pathlib import posixpath as _posix_flavour # type: ignore[attr-defined]
|
| 71 |
+
from pathlib import _make_selector # type: ignore[attr-defined]
|
| 72 |
+
elif sys.version_info[:2] == (3, 13):
|
| 73 |
+
from pathlib._local import _PathParents
|
| 74 |
+
import posixpath as _posix_flavour # type: ignore[attr-defined] # noqa: F811
|
| 75 |
+
|
| 76 |
+
from .legacy.glob import _make_selector # noqa: F811
|
| 77 |
+
elif sys.version_info >= (3, 14):
|
| 78 |
+
from pathlib import _PathParents # type: ignore[attr-defined]
|
| 79 |
+
import posixpath as _posix_flavour # type: ignore[attr-defined]
|
| 80 |
+
from .legacy.glob import _make_selector # noqa: F811
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
from cloudpathlib.enums import FileCacheMode
|
| 84 |
+
|
| 85 |
+
from . import anypath
|
| 86 |
+
from .exceptions import (
|
| 87 |
+
ClientMismatchError,
|
| 88 |
+
CloudPathFileExistsError,
|
| 89 |
+
CloudPathFileNotFoundError,
|
| 90 |
+
CloudPathIsADirectoryError,
|
| 91 |
+
CloudPathNotADirectoryError,
|
| 92 |
+
CloudPathNotExistsError,
|
| 93 |
+
CloudPathNotImplementedError,
|
| 94 |
+
DirectoryNotEmptyError,
|
| 95 |
+
IncompleteImplementationError,
|
| 96 |
+
InvalidPrefixError,
|
| 97 |
+
MissingDependenciesError,
|
| 98 |
+
NoStatError,
|
| 99 |
+
OverwriteDirtyFileError,
|
| 100 |
+
OverwriteNewerCloudError,
|
| 101 |
+
OverwriteNewerLocalError,
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
if TYPE_CHECKING:
|
| 106 |
+
from .client import Client
|
| 107 |
+
|
| 108 |
+
from .cloudpath_info import CloudPathInfo
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
class CloudImplementation:
|
| 112 |
+
name: str
|
| 113 |
+
dependencies_loaded: bool = True
|
| 114 |
+
_client_class: Type["Client"]
|
| 115 |
+
_path_class: Type["CloudPath"]
|
| 116 |
+
|
| 117 |
+
def validate_completeness(self) -> None:
|
| 118 |
+
expected = ["client_class", "path_class"]
|
| 119 |
+
missing = [cls for cls in expected if getattr(self, f"_{cls}") is None]
|
| 120 |
+
if missing:
|
| 121 |
+
raise IncompleteImplementationError(
|
| 122 |
+
f"Implementation is missing registered components: {missing}"
|
| 123 |
+
)
|
| 124 |
+
if not self.dependencies_loaded:
|
| 125 |
+
raise MissingDependenciesError(
|
| 126 |
+
f"Missing dependencies for {self._client_class.__name__}. You can install them "
|
| 127 |
+
f"with 'pip install cloudpathlib[{self.name}]'."
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
@property
|
| 131 |
+
def client_class(self) -> Type["Client"]:
|
| 132 |
+
self.validate_completeness()
|
| 133 |
+
return self._client_class
|
| 134 |
+
|
| 135 |
+
@property
|
| 136 |
+
def path_class(self) -> Type["CloudPath"]:
|
| 137 |
+
self.validate_completeness()
|
| 138 |
+
return self._path_class
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
implementation_registry: Dict[str, CloudImplementation] = defaultdict(CloudImplementation)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
T = TypeVar("T")
|
| 145 |
+
CloudPathT = TypeVar("CloudPathT", bound="CloudPath")
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def register_path_class(key: str) -> Callable[[Type[CloudPathT]], Type[CloudPathT]]:
|
| 149 |
+
def decorator(cls: Type[CloudPathT]) -> Type[CloudPathT]:
|
| 150 |
+
if not issubclass(cls, CloudPath):
|
| 151 |
+
raise TypeError("Only subclasses of CloudPath can be registered.")
|
| 152 |
+
implementation_registry[key]._path_class = cls
|
| 153 |
+
cls._cloud_meta = implementation_registry[key]
|
| 154 |
+
return cls
|
| 155 |
+
|
| 156 |
+
return decorator
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
class CloudPathMeta(abc.ABCMeta):
|
| 160 |
+
@overload
|
| 161 |
+
def __call__(
|
| 162 |
+
cls: Type[T], cloud_path: CloudPathT, *args: Any, **kwargs: Any
|
| 163 |
+
) -> CloudPathT: ...
|
| 164 |
+
|
| 165 |
+
@overload
|
| 166 |
+
def __call__(
|
| 167 |
+
cls: Type[T], cloud_path: Union[str, "CloudPath"], *args: Any, **kwargs: Any
|
| 168 |
+
) -> T: ...
|
| 169 |
+
|
| 170 |
+
def __call__(
|
| 171 |
+
cls: Type[T], cloud_path: Union[str, CloudPathT], *args: Any, **kwargs: Any
|
| 172 |
+
) -> Union[T, "CloudPath", CloudPathT]:
|
| 173 |
+
# cls is a class that is the instance of this metaclass, e.g., CloudPath
|
| 174 |
+
if not issubclass(cls, CloudPath):
|
| 175 |
+
raise TypeError(
|
| 176 |
+
f"Only subclasses of {CloudPath.__name__} can be instantiated from its meta class."
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
# Dispatch to subclass if base CloudPath
|
| 180 |
+
if cls is CloudPath:
|
| 181 |
+
for implementation in implementation_registry.values():
|
| 182 |
+
path_class = implementation._path_class
|
| 183 |
+
if path_class is not None and path_class.is_valid_cloudpath(
|
| 184 |
+
cloud_path, raise_on_error=False
|
| 185 |
+
):
|
| 186 |
+
# Instantiate path_class instance
|
| 187 |
+
new_obj = object.__new__(path_class)
|
| 188 |
+
path_class.__init__(new_obj, cloud_path, *args, **kwargs) # type: ignore[type-var]
|
| 189 |
+
return new_obj
|
| 190 |
+
valid_prefixes = [
|
| 191 |
+
impl._path_class.cloud_prefix
|
| 192 |
+
for impl in implementation_registry.values()
|
| 193 |
+
if impl._path_class is not None
|
| 194 |
+
]
|
| 195 |
+
raise InvalidPrefixError(
|
| 196 |
+
f"Path {cloud_path} does not begin with a known prefix {valid_prefixes}."
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
new_obj = object.__new__(cls)
|
| 200 |
+
cls.__init__(new_obj, cloud_path, *args, **kwargs) # type: ignore[type-var]
|
| 201 |
+
return new_obj
|
| 202 |
+
|
| 203 |
+
def __init__(cls, name: str, bases: Tuple[type, ...], dic: Dict[str, Any]) -> None:
|
| 204 |
+
# Copy docstring from pathlib.Path
|
| 205 |
+
for attr in dir(cls):
|
| 206 |
+
if (
|
| 207 |
+
not attr.startswith("_")
|
| 208 |
+
and hasattr(Path, attr)
|
| 209 |
+
and getattr(getattr(Path, attr), "__doc__", None)
|
| 210 |
+
):
|
| 211 |
+
docstring = getattr(Path, attr).__doc__ + " _(Docstring copied from pathlib.Path)_"
|
| 212 |
+
|
| 213 |
+
if isinstance(getattr(cls, attr), (MethodType)):
|
| 214 |
+
getattr(cls, attr).__func__.__doc__ = docstring
|
| 215 |
+
else:
|
| 216 |
+
getattr(cls, attr).__doc__ = docstring
|
| 217 |
+
|
| 218 |
+
if isinstance(getattr(cls, attr), property):
|
| 219 |
+
# Properties have __doc__ duplicated under fget, and at least some parsers
|
| 220 |
+
# read it from there.
|
| 221 |
+
getattr(cls, attr).fget.__doc__ = docstring
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
# Abstract base class
|
| 225 |
+
class CloudPath(metaclass=CloudPathMeta):
|
| 226 |
+
"""Base class for cloud storage file URIs, in the style of the Python standard library's
|
| 227 |
+
[`pathlib` module](https://docs.python.org/3/library/pathlib.html). Instances represent a path
|
| 228 |
+
in cloud storage with filesystem path semantics, and convenient methods allow for basic
|
| 229 |
+
operations like joining, reading, writing, iterating over contents, etc. `CloudPath` almost
|
| 230 |
+
entirely mimics the [`pathlib.Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)
|
| 231 |
+
interface, so most familiar properties and methods should be available and behave in the
|
| 232 |
+
expected way.
|
| 233 |
+
|
| 234 |
+
Analogous to the way `pathlib.Path` works, instantiating `CloudPath` will instead create an
|
| 235 |
+
instance of an appropriate subclass that implements a particular cloud storage service, such as
|
| 236 |
+
[`S3Path`](../s3path). This dispatching behavior is based on the URI scheme part of a cloud
|
| 237 |
+
storage URI (e.g., `"s3://"`).
|
| 238 |
+
"""
|
| 239 |
+
|
| 240 |
+
_cloud_meta: CloudImplementation
|
| 241 |
+
cloud_prefix: str
|
| 242 |
+
|
| 243 |
+
def __init__(
|
| 244 |
+
self,
|
| 245 |
+
cloud_path: Union[str, Self, "CloudPath"],
|
| 246 |
+
*parts: str,
|
| 247 |
+
client: Optional["Client"] = None,
|
| 248 |
+
) -> None:
|
| 249 |
+
# handle if local file gets opened. must be set at the top of the method in case any code
|
| 250 |
+
# below raises an exception, this prevents __del__ from raising an AttributeError
|
| 251 |
+
self._handle: Optional[IO] = None
|
| 252 |
+
self._client: Optional["Client"] = None
|
| 253 |
+
|
| 254 |
+
if parts:
|
| 255 |
+
# ensure first part ends in "/"; (sometimes it is just prefix, sometimes a longer path)
|
| 256 |
+
if not str(cloud_path).endswith("/"):
|
| 257 |
+
cloud_path = str(cloud_path) + "/"
|
| 258 |
+
|
| 259 |
+
cloud_path = str(cloud_path) + "/".join(p.strip("/") for p in parts)
|
| 260 |
+
|
| 261 |
+
self.is_valid_cloudpath(cloud_path, raise_on_error=True)
|
| 262 |
+
self._cloud_meta.validate_completeness()
|
| 263 |
+
|
| 264 |
+
# versions of the raw string that provide useful methods
|
| 265 |
+
self._str = str(cloud_path)
|
| 266 |
+
self._url = urlparse(self._str)
|
| 267 |
+
self._path = PurePosixPath(f"/{self._no_prefix}")
|
| 268 |
+
|
| 269 |
+
# setup client
|
| 270 |
+
if client is None:
|
| 271 |
+
if isinstance(cloud_path, CloudPath):
|
| 272 |
+
self._client = cloud_path.client
|
| 273 |
+
else:
|
| 274 |
+
self._client = client
|
| 275 |
+
|
| 276 |
+
if client is not None and not isinstance(client, self._cloud_meta.client_class):
|
| 277 |
+
raise ClientMismatchError(
|
| 278 |
+
f"Client of type [{client.__class__}] is not valid for cloud path of type "
|
| 279 |
+
f"[{self.__class__}]; must be instance of [{self._cloud_meta.client_class}], or "
|
| 280 |
+
f"None to use default client for this cloud path class."
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
# track if local has been written to, if so it may need to be uploaded
|
| 284 |
+
self._dirty = False
|
| 285 |
+
|
| 286 |
+
@property
|
| 287 |
+
def client(self):
|
| 288 |
+
if getattr(self, "_client", None) is None:
|
| 289 |
+
self._client = self._cloud_meta.client_class.get_default_client()
|
| 290 |
+
|
| 291 |
+
return self._client
|
| 292 |
+
|
| 293 |
+
def __del__(self) -> None:
|
| 294 |
+
# make sure that file handle to local path is closed
|
| 295 |
+
if self._handle is not None and self._local.exists():
|
| 296 |
+
self._handle.close()
|
| 297 |
+
|
| 298 |
+
# ensure file removed from cache when cloudpath object deleted
|
| 299 |
+
client = getattr(self, "_client", None)
|
| 300 |
+
if getattr(client, "file_cache_mode", None) == FileCacheMode.cloudpath_object:
|
| 301 |
+
self.clear_cache()
|
| 302 |
+
|
| 303 |
+
def __getstate__(self) -> Dict[str, Any]:
|
| 304 |
+
state = self.__dict__.copy()
|
| 305 |
+
|
| 306 |
+
# don't pickle client
|
| 307 |
+
if "_client" in state:
|
| 308 |
+
del state["_client"]
|
| 309 |
+
|
| 310 |
+
return state
|
| 311 |
+
|
| 312 |
+
def __setstate__(self, state: Dict[str, Any]) -> None:
|
| 313 |
+
self.__dict__.update(state)
|
| 314 |
+
|
| 315 |
+
@property
|
| 316 |
+
def _no_prefix(self) -> str:
|
| 317 |
+
return self._str[len(self.anchor) :]
|
| 318 |
+
|
| 319 |
+
@property
|
| 320 |
+
def _no_prefix_no_drive(self) -> str:
|
| 321 |
+
return self._str[len(self.anchor) + len(self.drive) :]
|
| 322 |
+
|
| 323 |
+
@overload
|
| 324 |
+
@classmethod
|
| 325 |
+
def is_valid_cloudpath(
|
| 326 |
+
cls, path: "CloudPath", raise_on_error: bool = ...
|
| 327 |
+
) -> TypeGuard[Self]: ...
|
| 328 |
+
|
| 329 |
+
@overload
|
| 330 |
+
@classmethod
|
| 331 |
+
def is_valid_cloudpath(cls, path: str, raise_on_error: bool = ...) -> bool: ...
|
| 332 |
+
|
| 333 |
+
@classmethod
|
| 334 |
+
def is_valid_cloudpath(
|
| 335 |
+
cls, path: Union[str, "CloudPath"], raise_on_error: bool = False
|
| 336 |
+
) -> Union[bool, TypeGuard[Self]]:
|
| 337 |
+
valid = str(path).lower().startswith(cls.cloud_prefix.lower())
|
| 338 |
+
|
| 339 |
+
if raise_on_error and not valid:
|
| 340 |
+
raise InvalidPrefixError(
|
| 341 |
+
f"'{path}' is not a valid path since it does not start with '{cls.cloud_prefix}'"
|
| 342 |
+
)
|
| 343 |
+
|
| 344 |
+
return valid
|
| 345 |
+
|
| 346 |
+
def __repr__(self) -> str:
|
| 347 |
+
return f"{self.__class__.__name__}('{self}')"
|
| 348 |
+
|
| 349 |
+
def __str__(self) -> str:
|
| 350 |
+
return self._str
|
| 351 |
+
|
| 352 |
+
def __hash__(self) -> int:
|
| 353 |
+
return hash((type(self).__name__, str(self)))
|
| 354 |
+
|
| 355 |
+
def __eq__(self, other: Any) -> bool:
|
| 356 |
+
return isinstance(other, type(self)) and str(self) == str(other)
|
| 357 |
+
|
| 358 |
+
def __fspath__(self) -> str:
|
| 359 |
+
if self.is_file():
|
| 360 |
+
self._refresh_cache()
|
| 361 |
+
return str(self._local)
|
| 362 |
+
|
| 363 |
+
def __lt__(self, other: Any) -> bool:
|
| 364 |
+
if not isinstance(other, type(self)):
|
| 365 |
+
return NotImplemented
|
| 366 |
+
return self.parts < other.parts
|
| 367 |
+
|
| 368 |
+
def __le__(self, other: Any) -> bool:
|
| 369 |
+
if not isinstance(other, type(self)):
|
| 370 |
+
return NotImplemented
|
| 371 |
+
return self.parts <= other.parts
|
| 372 |
+
|
| 373 |
+
def __gt__(self, other: Any) -> bool:
|
| 374 |
+
if not isinstance(other, type(self)):
|
| 375 |
+
return NotImplemented
|
| 376 |
+
return self.parts > other.parts
|
| 377 |
+
|
| 378 |
+
def __ge__(self, other: Any) -> bool:
|
| 379 |
+
if not isinstance(other, type(self)):
|
| 380 |
+
return NotImplemented
|
| 381 |
+
return self.parts >= other.parts
|
| 382 |
+
|
| 383 |
+
# ====================== NOT IMPLEMENTED ======================
|
| 384 |
+
# as_posix - no cloud equivalent; not needed since we assume url separator
|
| 385 |
+
# chmod - permission changing should be explicitly done per client with methods
|
| 386 |
+
# that make sense for the client permission options
|
| 387 |
+
# cwd - no cloud equivalent
|
| 388 |
+
# expanduser - no cloud equivalent
|
| 389 |
+
# group - should be implemented with client-specific permissions
|
| 390 |
+
# home - no cloud equivalent
|
| 391 |
+
# is_block_device - no cloud equivalent
|
| 392 |
+
# is_char_device - no cloud equivalent
|
| 393 |
+
# is_fifo - no cloud equivalent
|
| 394 |
+
# is_mount - no cloud equivalent
|
| 395 |
+
# is_reserved - no cloud equivalent
|
| 396 |
+
# is_socket - no cloud equivalent
|
| 397 |
+
# is_symlink - no cloud equivalent
|
| 398 |
+
# lchmod - no cloud equivalent
|
| 399 |
+
# lstat - no cloud equivalent
|
| 400 |
+
# owner - no cloud equivalent
|
| 401 |
+
# readlink - no cloud equivalent
|
| 402 |
+
# root - drive already has the bucket and anchor/prefix has the scheme, so nothing to store here
|
| 403 |
+
# symlink_to - no cloud equivalent
|
| 404 |
+
# link_to - no cloud equivalent
|
| 405 |
+
# hardlink_to - no cloud equivalent
|
| 406 |
+
|
| 407 |
+
# ====================== REQUIRED, NOT GENERIC ======================
|
| 408 |
+
# Methods that must be implemented, but have no generic application
|
| 409 |
+
@property
|
| 410 |
+
@abc.abstractmethod
|
| 411 |
+
def drive(self) -> str:
|
| 412 |
+
"""For example "bucket" on S3 or "container" on Azure; needs to be defined for each class"""
|
| 413 |
+
pass
|
| 414 |
+
|
| 415 |
+
@abc.abstractmethod
|
| 416 |
+
def mkdir(
|
| 417 |
+
self, parents: bool = False, exist_ok: bool = False, mode: Optional[Any] = None
|
| 418 |
+
) -> None:
|
| 419 |
+
"""Should be implemented using the client API without requiring a dir is downloaded"""
|
| 420 |
+
pass
|
| 421 |
+
|
| 422 |
+
@abc.abstractmethod
|
| 423 |
+
def touch(self, exist_ok: bool = True, mode: Optional[Any] = None) -> None:
|
| 424 |
+
"""Should be implemented using the client API to create and update modified time"""
|
| 425 |
+
pass
|
| 426 |
+
|
| 427 |
+
def as_url(self, presign: bool = False, expire_seconds: int = 60 * 60) -> str:
|
| 428 |
+
if presign:
|
| 429 |
+
url = self.client._generate_presigned_url(self, expire_seconds=expire_seconds)
|
| 430 |
+
else:
|
| 431 |
+
url = self.client._get_public_url(self)
|
| 432 |
+
return url
|
| 433 |
+
|
| 434 |
+
# ====================== IMPLEMENTED FROM SCRATCH ======================
|
| 435 |
+
# Methods with their own implementations that work generically
|
| 436 |
+
def __rtruediv__(self, other: Any) -> None:
|
| 437 |
+
raise ValueError(
|
| 438 |
+
"Cannot change a cloud path's root since all paths are absolute; create a new path instead."
|
| 439 |
+
)
|
| 440 |
+
|
| 441 |
+
@property
|
| 442 |
+
def anchor(self) -> str:
|
| 443 |
+
return self.cloud_prefix
|
| 444 |
+
|
| 445 |
+
def as_uri(self) -> str:
|
| 446 |
+
return str(self)
|
| 447 |
+
|
| 448 |
+
def exists(self, follow_symlinks=True) -> bool:
|
| 449 |
+
return self.client._exists(self)
|
| 450 |
+
|
| 451 |
+
def is_dir(self, follow_symlinks=True) -> bool:
|
| 452 |
+
return self.client._is_file_or_dir(self) == "dir"
|
| 453 |
+
|
| 454 |
+
def is_file(self, follow_symlinks=True) -> bool:
|
| 455 |
+
return self.client._is_file_or_dir(self) == "file"
|
| 456 |
+
|
| 457 |
+
@property
|
| 458 |
+
def fspath(self) -> str:
|
| 459 |
+
return self.__fspath__()
|
| 460 |
+
|
| 461 |
+
@classmethod
|
| 462 |
+
def from_uri(cls, uri: str) -> Self:
|
| 463 |
+
return cls(uri)
|
| 464 |
+
|
| 465 |
+
def _glob_checks(self, pattern: Union[str, os.PathLike]) -> str:
|
| 466 |
+
if isinstance(pattern, os.PathLike):
|
| 467 |
+
if isinstance(pattern, CloudPath):
|
| 468 |
+
str_pattern = str(pattern.relative_to(self))
|
| 469 |
+
else:
|
| 470 |
+
str_pattern = os.fspath(pattern)
|
| 471 |
+
else:
|
| 472 |
+
str_pattern = str(pattern)
|
| 473 |
+
|
| 474 |
+
if ".." in str_pattern:
|
| 475 |
+
raise CloudPathNotImplementedError(
|
| 476 |
+
"Relative paths with '..' not supported in glob patterns."
|
| 477 |
+
)
|
| 478 |
+
|
| 479 |
+
if str_pattern.startswith(self.cloud_prefix) or str_pattern.startswith("/"):
|
| 480 |
+
raise CloudPathNotImplementedError("Non-relative patterns are unsupported")
|
| 481 |
+
|
| 482 |
+
if self.drive == "":
|
| 483 |
+
raise CloudPathNotImplementedError(
|
| 484 |
+
".glob is only supported within a bucket or container; you can use `.iterdir` to list buckets; for example, CloudPath('s3://').iterdir()"
|
| 485 |
+
)
|
| 486 |
+
|
| 487 |
+
return str_pattern
|
| 488 |
+
|
| 489 |
+
def _build_subtree(self, recursive):
|
| 490 |
+
# build a tree structure for all files out of default dicts
|
| 491 |
+
Tree: Callable = lambda: defaultdict(Tree)
|
| 492 |
+
|
| 493 |
+
def _build_tree(trunk, branch, nodes, is_dir):
|
| 494 |
+
"""Utility to build a tree from nested defaultdicts with a generator
|
| 495 |
+
of nodes (parts) of a path."""
|
| 496 |
+
next_branch = next(nodes, None)
|
| 497 |
+
|
| 498 |
+
if next_branch is None:
|
| 499 |
+
trunk[branch] = Tree() if is_dir else None # leaf node
|
| 500 |
+
|
| 501 |
+
else:
|
| 502 |
+
_build_tree(trunk[branch], next_branch, nodes, is_dir)
|
| 503 |
+
|
| 504 |
+
file_tree = Tree()
|
| 505 |
+
|
| 506 |
+
for f, is_dir in self.client._list_dir(self, recursive=recursive):
|
| 507 |
+
parts = str(f.relative_to(self)).split("/")
|
| 508 |
+
|
| 509 |
+
# skip self
|
| 510 |
+
if len(parts) == 1 and parts[0] == ".":
|
| 511 |
+
continue
|
| 512 |
+
|
| 513 |
+
nodes = (p for p in parts)
|
| 514 |
+
_build_tree(file_tree, next(nodes, None), nodes, is_dir)
|
| 515 |
+
|
| 516 |
+
return dict(file_tree) # freeze as normal dict before passing in
|
| 517 |
+
|
| 518 |
+
def _glob(self, selector, recursive: bool) -> Generator[Self, None, None]:
|
| 519 |
+
file_tree = self._build_subtree(recursive)
|
| 520 |
+
|
| 521 |
+
root = _CloudPathSelectable(
|
| 522 |
+
self.name,
|
| 523 |
+
[], # nothing above self will be returned, so initial parents is empty
|
| 524 |
+
file_tree,
|
| 525 |
+
)
|
| 526 |
+
|
| 527 |
+
for p in selector.select_from(root):
|
| 528 |
+
# select_from returns self.name/... so strip before joining
|
| 529 |
+
yield (self / str(p)[len(self.name) + 1 :])
|
| 530 |
+
|
| 531 |
+
def glob(
|
| 532 |
+
self,
|
| 533 |
+
pattern: Union[str, os.PathLike],
|
| 534 |
+
case_sensitive: Optional[bool] = None,
|
| 535 |
+
recurse_symlinks: bool = True,
|
| 536 |
+
) -> Generator[Self, None, None]:
|
| 537 |
+
pattern = self._glob_checks(pattern)
|
| 538 |
+
|
| 539 |
+
pattern_parts = PurePosixPath(pattern).parts
|
| 540 |
+
selector = _make_selector(
|
| 541 |
+
tuple(pattern_parts), _posix_flavour, case_sensitive=case_sensitive
|
| 542 |
+
)
|
| 543 |
+
|
| 544 |
+
yield from self._glob(
|
| 545 |
+
selector,
|
| 546 |
+
"/" in pattern
|
| 547 |
+
or "**"
|
| 548 |
+
in pattern, # recursive listing needed if explicit ** or any sub folder in pattern
|
| 549 |
+
)
|
| 550 |
+
|
| 551 |
+
def rglob(
|
| 552 |
+
self,
|
| 553 |
+
pattern: Union[str, os.PathLike],
|
| 554 |
+
case_sensitive: Optional[bool] = None,
|
| 555 |
+
recurse_symlinks: bool = True,
|
| 556 |
+
) -> Generator[Self, None, None]:
|
| 557 |
+
pattern = self._glob_checks(pattern)
|
| 558 |
+
|
| 559 |
+
pattern_parts = PurePosixPath(pattern).parts
|
| 560 |
+
selector = _make_selector(
|
| 561 |
+
("**",) + tuple(pattern_parts), _posix_flavour, case_sensitive=case_sensitive
|
| 562 |
+
)
|
| 563 |
+
|
| 564 |
+
yield from self._glob(selector, True)
|
| 565 |
+
|
| 566 |
+
def iterdir(self) -> Generator[Self, None, None]:
|
| 567 |
+
for f, _ in self.client._list_dir(self, recursive=False):
|
| 568 |
+
if f != self: # iterdir does not include itself in pathlib
|
| 569 |
+
yield f
|
| 570 |
+
|
| 571 |
+
@staticmethod
|
| 572 |
+
def _walk_results_from_tree(root, tree, top_down=True):
|
| 573 |
+
"""Utility to yield tuples in the form expected by `.walk` from the file
|
| 574 |
+
tree constructed by `_build_substree`.
|
| 575 |
+
"""
|
| 576 |
+
dirs = []
|
| 577 |
+
files = []
|
| 578 |
+
for item, branch in tree.items():
|
| 579 |
+
files.append(item) if branch is None else dirs.append(item)
|
| 580 |
+
|
| 581 |
+
if top_down:
|
| 582 |
+
yield root, dirs, files
|
| 583 |
+
|
| 584 |
+
for dir in dirs:
|
| 585 |
+
yield from CloudPath._walk_results_from_tree(root / dir, tree[dir], top_down=top_down)
|
| 586 |
+
|
| 587 |
+
if not top_down:
|
| 588 |
+
yield root, dirs, files
|
| 589 |
+
|
| 590 |
+
def walk(
|
| 591 |
+
self,
|
| 592 |
+
top_down: bool = True,
|
| 593 |
+
on_error: Optional[Callable] = None,
|
| 594 |
+
follow_symlinks: bool = False,
|
| 595 |
+
) -> Generator[Tuple[Self, List[str], List[str]], None, None]:
|
| 596 |
+
try:
|
| 597 |
+
file_tree = self._build_subtree(recursive=True) # walking is always recursive
|
| 598 |
+
yield from self._walk_results_from_tree(self, file_tree, top_down=top_down)
|
| 599 |
+
|
| 600 |
+
except Exception as e:
|
| 601 |
+
if on_error is not None:
|
| 602 |
+
on_error(e)
|
| 603 |
+
else:
|
| 604 |
+
raise
|
| 605 |
+
|
| 606 |
+
@overload
|
| 607 |
+
def open(
|
| 608 |
+
self,
|
| 609 |
+
mode: "OpenTextMode" = "r",
|
| 610 |
+
buffering: int = -1,
|
| 611 |
+
encoding: Optional[str] = None,
|
| 612 |
+
errors: Optional[str] = None,
|
| 613 |
+
newline: Optional[str] = None,
|
| 614 |
+
force_overwrite_from_cloud: Optional[bool] = None,
|
| 615 |
+
force_overwrite_to_cloud: Optional[bool] = None,
|
| 616 |
+
) -> "TextIOWrapper": ...
|
| 617 |
+
|
| 618 |
+
@overload
|
| 619 |
+
def open(
|
| 620 |
+
self,
|
| 621 |
+
mode: "OpenBinaryMode",
|
| 622 |
+
buffering: Literal[0],
|
| 623 |
+
encoding: None = None,
|
| 624 |
+
errors: None = None,
|
| 625 |
+
newline: None = None,
|
| 626 |
+
force_overwrite_from_cloud: Optional[bool] = None,
|
| 627 |
+
force_overwrite_to_cloud: Optional[bool] = None,
|
| 628 |
+
) -> "FileIO": ...
|
| 629 |
+
|
| 630 |
+
@overload
|
| 631 |
+
def open(
|
| 632 |
+
self,
|
| 633 |
+
mode: "OpenBinaryModeUpdating",
|
| 634 |
+
buffering: Literal[-1, 1] = -1,
|
| 635 |
+
encoding: None = None,
|
| 636 |
+
errors: None = None,
|
| 637 |
+
newline: None = None,
|
| 638 |
+
force_overwrite_from_cloud: Optional[bool] = None,
|
| 639 |
+
force_overwrite_to_cloud: Optional[bool] = None,
|
| 640 |
+
) -> "BufferedRandom": ...
|
| 641 |
+
|
| 642 |
+
@overload
|
| 643 |
+
def open(
|
| 644 |
+
self,
|
| 645 |
+
mode: "OpenBinaryModeWriting",
|
| 646 |
+
buffering: Literal[-1, 1] = -1,
|
| 647 |
+
encoding: None = None,
|
| 648 |
+
errors: None = None,
|
| 649 |
+
newline: None = None,
|
| 650 |
+
force_overwrite_from_cloud: Optional[bool] = None,
|
| 651 |
+
force_overwrite_to_cloud: Optional[bool] = None,
|
| 652 |
+
) -> "BufferedWriter": ...
|
| 653 |
+
|
| 654 |
+
@overload
|
| 655 |
+
def open(
|
| 656 |
+
self,
|
| 657 |
+
mode: "OpenBinaryModeReading",
|
| 658 |
+
buffering: Literal[-1, 1] = -1,
|
| 659 |
+
encoding: None = None,
|
| 660 |
+
errors: None = None,
|
| 661 |
+
newline: None = None,
|
| 662 |
+
force_overwrite_from_cloud: Optional[bool] = None,
|
| 663 |
+
force_overwrite_to_cloud: Optional[bool] = None,
|
| 664 |
+
) -> "BufferedReader": ...
|
| 665 |
+
|
| 666 |
+
@overload
|
| 667 |
+
def open(
|
| 668 |
+
self,
|
| 669 |
+
mode: "OpenBinaryMode",
|
| 670 |
+
buffering: int = -1,
|
| 671 |
+
encoding: None = None,
|
| 672 |
+
errors: None = None,
|
| 673 |
+
newline: None = None,
|
| 674 |
+
force_overwrite_from_cloud: Optional[bool] = None,
|
| 675 |
+
force_overwrite_to_cloud: Optional[bool] = None,
|
| 676 |
+
) -> "BinaryIO": ...
|
| 677 |
+
|
| 678 |
+
@overload
|
| 679 |
+
def open(
|
| 680 |
+
self,
|
| 681 |
+
mode: str,
|
| 682 |
+
buffering: int = -1,
|
| 683 |
+
encoding: Optional[str] = None,
|
| 684 |
+
errors: Optional[str] = None,
|
| 685 |
+
newline: Optional[str] = None,
|
| 686 |
+
force_overwrite_from_cloud: Optional[bool] = None,
|
| 687 |
+
force_overwrite_to_cloud: Optional[bool] = None,
|
| 688 |
+
) -> "IO[Any]": ...
|
| 689 |
+
|
| 690 |
+
def open(
|
| 691 |
+
self,
|
| 692 |
+
mode: str = "r",
|
| 693 |
+
buffering: int = -1,
|
| 694 |
+
encoding: Optional[str] = None,
|
| 695 |
+
errors: Optional[str] = None,
|
| 696 |
+
newline: Optional[str] = None,
|
| 697 |
+
force_overwrite_from_cloud: Optional[bool] = None, # extra kwarg not in pathlib
|
| 698 |
+
force_overwrite_to_cloud: Optional[bool] = None, # extra kwarg not in pathlib
|
| 699 |
+
) -> "IO[Any]":
|
| 700 |
+
# if trying to call open on a directory that exists
|
| 701 |
+
exists_on_cloud = self.exists()
|
| 702 |
+
|
| 703 |
+
if exists_on_cloud and not self.is_file():
|
| 704 |
+
raise CloudPathIsADirectoryError(
|
| 705 |
+
f"Cannot open directory, only files. Tried to open ({self})"
|
| 706 |
+
)
|
| 707 |
+
|
| 708 |
+
if not exists_on_cloud and any(m in mode for m in ("r", "a")):
|
| 709 |
+
raise CloudPathFileNotFoundError(
|
| 710 |
+
f"File opened for read or append, but it does not exist on cloud: {self}"
|
| 711 |
+
)
|
| 712 |
+
|
| 713 |
+
if mode == "x" and self.exists():
|
| 714 |
+
raise CloudPathFileExistsError(f"Cannot open existing file ({self}) for creation.")
|
| 715 |
+
|
| 716 |
+
# TODO: consider streaming from client rather than DLing entire file to cache
|
| 717 |
+
self._refresh_cache(force_overwrite_from_cloud=force_overwrite_from_cloud)
|
| 718 |
+
|
| 719 |
+
# create any directories that may be needed if the file is new
|
| 720 |
+
if not self._local.exists():
|
| 721 |
+
self._local.parent.mkdir(parents=True, exist_ok=True)
|
| 722 |
+
original_mtime = 0.0
|
| 723 |
+
else:
|
| 724 |
+
original_mtime = self._local.stat().st_mtime
|
| 725 |
+
|
| 726 |
+
buffer = self._local.open(
|
| 727 |
+
mode=mode,
|
| 728 |
+
buffering=buffering,
|
| 729 |
+
encoding=encoding,
|
| 730 |
+
errors=errors,
|
| 731 |
+
newline=newline,
|
| 732 |
+
)
|
| 733 |
+
|
| 734 |
+
# write modes need special on closing the buffer
|
| 735 |
+
if any(m in mode for m in ("w", "+", "x", "a")):
|
| 736 |
+
# dirty, handle, patch close
|
| 737 |
+
wrapped_close = buffer.close
|
| 738 |
+
|
| 739 |
+
# since we are pretending this is a cloud file, upload it to the cloud
|
| 740 |
+
# when the buffer is closed
|
| 741 |
+
def _patched_close_upload(*args, **kwargs) -> None:
|
| 742 |
+
wrapped_close(*args, **kwargs)
|
| 743 |
+
|
| 744 |
+
# we should be idempotent and not upload again if
|
| 745 |
+
# we already ran our close method patch
|
| 746 |
+
if not self._dirty:
|
| 747 |
+
return
|
| 748 |
+
|
| 749 |
+
# original mtime should match what was in the cloud; because of system clocks or rounding
|
| 750 |
+
# by the cloud provider, the new version in our cache is "older" than the original version;
|
| 751 |
+
# explicitly set the new modified time to be after the original modified time.
|
| 752 |
+
if self._local.stat().st_mtime < original_mtime:
|
| 753 |
+
new_mtime = original_mtime + 1
|
| 754 |
+
os.utime(self._local, times=(new_mtime, new_mtime))
|
| 755 |
+
|
| 756 |
+
self._upload_local_to_cloud(force_overwrite_to_cloud=force_overwrite_to_cloud)
|
| 757 |
+
self._dirty = False
|
| 758 |
+
|
| 759 |
+
buffer.close = _patched_close_upload # type: ignore
|
| 760 |
+
|
| 761 |
+
# keep reference in case we need to close when __del__ is called on this object
|
| 762 |
+
self._handle = buffer
|
| 763 |
+
|
| 764 |
+
# opened for write, so mark dirty
|
| 765 |
+
self._dirty = True
|
| 766 |
+
|
| 767 |
+
# if we don't want any cache around, remove the cache
|
| 768 |
+
# as soon as the file is closed
|
| 769 |
+
if self.client.file_cache_mode == FileCacheMode.close_file:
|
| 770 |
+
# this may be _patched_close_upload, in which case we need to
|
| 771 |
+
# make sure to call that first so the file gets uploaded
|
| 772 |
+
wrapped_close_for_cache = buffer.close
|
| 773 |
+
|
| 774 |
+
def _patched_close_empty_cache(*args, **kwargs):
|
| 775 |
+
wrapped_close_for_cache(*args, **kwargs)
|
| 776 |
+
|
| 777 |
+
# remove local file as last step on closing
|
| 778 |
+
self.clear_cache()
|
| 779 |
+
|
| 780 |
+
buffer.close = _patched_close_empty_cache # type: ignore
|
| 781 |
+
|
| 782 |
+
return buffer
|
| 783 |
+
|
| 784 |
+
def replace(self, target: Self) -> Self:
|
| 785 |
+
if type(self) is not type(target):
|
| 786 |
+
raise TypeError(
|
| 787 |
+
f"The target based to rename must be an instantiated class of type: {type(self)}"
|
| 788 |
+
)
|
| 789 |
+
|
| 790 |
+
if self.is_dir():
|
| 791 |
+
raise CloudPathIsADirectoryError(
|
| 792 |
+
f"Path {self} is a directory; rename/replace the files recursively."
|
| 793 |
+
)
|
| 794 |
+
|
| 795 |
+
if target == self:
|
| 796 |
+
# Request is to replace/rename this with the same path - nothing to do
|
| 797 |
+
return self
|
| 798 |
+
|
| 799 |
+
if target.exists():
|
| 800 |
+
target.unlink()
|
| 801 |
+
|
| 802 |
+
self.client._move_file(self, target)
|
| 803 |
+
return target
|
| 804 |
+
|
| 805 |
+
def rename(self, target: Self) -> Self:
|
| 806 |
+
# for cloud services replace == rename since we don't just rename,
|
| 807 |
+
# we actually move files
|
| 808 |
+
return self.replace(target)
|
| 809 |
+
|
| 810 |
+
def rmdir(self) -> None:
|
| 811 |
+
if self.is_file():
|
| 812 |
+
raise CloudPathNotADirectoryError(
|
| 813 |
+
f"Path {self} is a file; call unlink instead of rmdir."
|
| 814 |
+
)
|
| 815 |
+
try:
|
| 816 |
+
next(self.iterdir())
|
| 817 |
+
raise DirectoryNotEmptyError(
|
| 818 |
+
f"Directory not empty: '{self}'. Use rmtree to delete recursively."
|
| 819 |
+
)
|
| 820 |
+
except StopIteration:
|
| 821 |
+
pass
|
| 822 |
+
self.client._remove(self)
|
| 823 |
+
|
| 824 |
+
def samefile(self, other_path: Union[str, os.PathLike]) -> bool:
|
| 825 |
+
# all cloud paths are absolute and the paths are used for hash
|
| 826 |
+
return self == other_path
|
| 827 |
+
|
| 828 |
+
def unlink(self, missing_ok: bool = True) -> None:
|
| 829 |
+
# Note: missing_ok defaults to False in pathlib, but changing the default now would be a breaking change.
|
| 830 |
+
if self.is_dir():
|
| 831 |
+
raise CloudPathIsADirectoryError(
|
| 832 |
+
f"Path {self} is a directory; call rmdir instead of unlink."
|
| 833 |
+
)
|
| 834 |
+
self.client._remove(self, missing_ok)
|
| 835 |
+
|
| 836 |
+
def write_bytes(self, data: bytes) -> int:
|
| 837 |
+
"""Open the file in bytes mode, write to it, and close the file.
|
| 838 |
+
|
| 839 |
+
NOTE: vendored from pathlib since we override open
|
| 840 |
+
https://github.com/python/cpython/blob/3.8/Lib/pathlib.py#L1235-L1242
|
| 841 |
+
"""
|
| 842 |
+
# type-check for the buffer interface before truncating the file
|
| 843 |
+
view = memoryview(data)
|
| 844 |
+
with self.open(mode="wb") as f:
|
| 845 |
+
return f.write(view)
|
| 846 |
+
|
| 847 |
+
def write_text(
|
| 848 |
+
self,
|
| 849 |
+
data: str,
|
| 850 |
+
encoding: Optional[str] = None,
|
| 851 |
+
errors: Optional[str] = None,
|
| 852 |
+
newline: Optional[str] = None,
|
| 853 |
+
) -> int:
|
| 854 |
+
"""Open the file in text mode, write to it, and close the file.
|
| 855 |
+
|
| 856 |
+
NOTE: vendored from pathlib since we override open
|
| 857 |
+
https://github.com/python/cpython/blob/3.10/Lib/pathlib.py#L1146-L1155
|
| 858 |
+
"""
|
| 859 |
+
if not isinstance(data, str):
|
| 860 |
+
raise TypeError("data must be str, not %s" % data.__class__.__name__)
|
| 861 |
+
|
| 862 |
+
with self.open(mode="w", encoding=encoding, errors=errors, newline=newline) as f:
|
| 863 |
+
return f.write(data)
|
| 864 |
+
|
| 865 |
+
def read_bytes(self) -> bytes:
|
| 866 |
+
with self.open(mode="rb") as f:
|
| 867 |
+
return f.read()
|
| 868 |
+
|
| 869 |
+
def read_text(
|
| 870 |
+
self,
|
| 871 |
+
encoding: Optional[str] = None,
|
| 872 |
+
errors: Optional[str] = None,
|
| 873 |
+
newline: Optional[str] = None,
|
| 874 |
+
) -> str:
|
| 875 |
+
with self.open(mode="r", encoding=encoding, errors=errors, newline=newline) as f:
|
| 876 |
+
return f.read()
|
| 877 |
+
|
| 878 |
+
def is_junction(self):
|
| 879 |
+
return False # only windows paths can be junctions, not cloudpaths
|
| 880 |
+
|
| 881 |
+
# ====================== DISPATCHED TO POSIXPATH FOR PURE PATHS ======================
|
| 882 |
+
# Methods that are dispatched to exactly how pathlib.PurePosixPath would calculate it on
|
| 883 |
+
# self._path for pure paths (does not matter if file exists);
|
| 884 |
+
# see the next session for ones that require a real file to exist
|
| 885 |
+
def _dispatch_to_path(self, func: str, *args, **kwargs) -> Any:
|
| 886 |
+
"""Some functions we can just dispatch to the pathlib version
|
| 887 |
+
We want to do this explicitly so we don't have to support all
|
| 888 |
+
of pathlib and subclasses can override individually if necessary.
|
| 889 |
+
"""
|
| 890 |
+
path_version = self._path.__getattribute__(func)
|
| 891 |
+
|
| 892 |
+
# Path functions should be called so the results are calculated
|
| 893 |
+
if callable(path_version):
|
| 894 |
+
path_version = path_version(*args, **kwargs)
|
| 895 |
+
|
| 896 |
+
# Paths should always be resolved and then converted to the same client + class as this one
|
| 897 |
+
if isinstance(path_version, PurePosixPath):
|
| 898 |
+
# always resolve since cloud paths must be absolute
|
| 899 |
+
path_version = _resolve(path_version)
|
| 900 |
+
return self._new_cloudpath(path_version)
|
| 901 |
+
|
| 902 |
+
# When sequence of PurePosixPath, we want to convert to sequence of CloudPaths
|
| 903 |
+
if (
|
| 904 |
+
isinstance(path_version, collections.abc.Sequence)
|
| 905 |
+
and len(path_version) > 0
|
| 906 |
+
and isinstance(path_version[0], PurePosixPath)
|
| 907 |
+
):
|
| 908 |
+
sequence_class = (
|
| 909 |
+
type(path_version) if not isinstance(path_version, _PathParents) else tuple
|
| 910 |
+
)
|
| 911 |
+
return sequence_class( # type: ignore
|
| 912 |
+
self._new_cloudpath(_resolve(p)) for p in path_version if _resolve(p) != p.root
|
| 913 |
+
)
|
| 914 |
+
|
| 915 |
+
# when pathlib returns something else, we probably just want that thing
|
| 916 |
+
# cases this should include: str, empty sequence, sequence of str, ...
|
| 917 |
+
else:
|
| 918 |
+
return path_version
|
| 919 |
+
|
| 920 |
+
def __truediv__(self, other: Union[str, PurePosixPath]) -> Self:
|
| 921 |
+
if not isinstance(other, (str, PurePosixPath)):
|
| 922 |
+
return NotImplemented
|
| 923 |
+
|
| 924 |
+
return self._dispatch_to_path("__truediv__", other)
|
| 925 |
+
|
| 926 |
+
def joinpath(self, *pathsegments: Union[str, os.PathLike]) -> Self:
|
| 927 |
+
return self._dispatch_to_path("joinpath", *pathsegments)
|
| 928 |
+
|
| 929 |
+
def absolute(self) -> Self:
|
| 930 |
+
return self
|
| 931 |
+
|
| 932 |
+
def is_absolute(self) -> bool:
|
| 933 |
+
return True
|
| 934 |
+
|
| 935 |
+
def resolve(self, strict: bool = False) -> Self:
|
| 936 |
+
return self
|
| 937 |
+
|
| 938 |
+
def relative_to(self, other: Self, walk_up: bool = False) -> PurePosixPath:
|
| 939 |
+
# We don't dispatch regularly since this never returns a cloud path (since it is relative, and cloud paths are
|
| 940 |
+
# absolute)
|
| 941 |
+
if not isinstance(other, CloudPath):
|
| 942 |
+
raise ValueError(f"{self} is a cloud path, but {other} is not")
|
| 943 |
+
if self.anchor != other.anchor:
|
| 944 |
+
raise ValueError(
|
| 945 |
+
f"{self} is a {self.anchor} path, but {other} is a {other.anchor} path"
|
| 946 |
+
)
|
| 947 |
+
|
| 948 |
+
kwargs = dict(walk_up=walk_up)
|
| 949 |
+
|
| 950 |
+
if sys.version_info < (3, 12):
|
| 951 |
+
kwargs.pop("walk_up")
|
| 952 |
+
|
| 953 |
+
return self._path.relative_to(other._path, **kwargs) # type: ignore[call-arg]
|
| 954 |
+
|
| 955 |
+
def is_relative_to(self, other: Self) -> bool:
|
| 956 |
+
try:
|
| 957 |
+
self.relative_to(other)
|
| 958 |
+
return True
|
| 959 |
+
except ValueError:
|
| 960 |
+
return False
|
| 961 |
+
|
| 962 |
+
@property
|
| 963 |
+
def name(self) -> str:
|
| 964 |
+
return self._dispatch_to_path("name")
|
| 965 |
+
|
| 966 |
+
def full_match(self, pattern: str, case_sensitive: Optional[bool] = None) -> bool:
|
| 967 |
+
if sys.version_info < (3, 13):
|
| 968 |
+
raise NotImplementedError("full_match requires Python 3.13 or higher")
|
| 969 |
+
|
| 970 |
+
# strip scheme from start of pattern before testing
|
| 971 |
+
if pattern.startswith(self.anchor + self.drive):
|
| 972 |
+
pattern = pattern[len(self.anchor + self.drive) :]
|
| 973 |
+
elif pattern.startswith(self.anchor):
|
| 974 |
+
# for http paths, keep leading slash
|
| 975 |
+
pattern = pattern[len(self.anchor) - 1 :]
|
| 976 |
+
|
| 977 |
+
# remove drive, which is kept on normal dispatch to pathlib
|
| 978 |
+
return PurePosixPath(self._no_prefix_no_drive).full_match( # type: ignore[attr-defined]
|
| 979 |
+
pattern, case_sensitive=case_sensitive
|
| 980 |
+
)
|
| 981 |
+
|
| 982 |
+
def match(self, path_pattern: str, case_sensitive: Optional[bool] = None) -> bool:
|
| 983 |
+
# strip scheme from start of pattern before testing
|
| 984 |
+
if path_pattern.startswith(self.anchor + self.drive + "/"):
|
| 985 |
+
path_pattern = path_pattern[len(self.anchor + self.drive + "/") :]
|
| 986 |
+
|
| 987 |
+
kwargs = dict(case_sensitive=case_sensitive)
|
| 988 |
+
|
| 989 |
+
if sys.version_info < (3, 12):
|
| 990 |
+
kwargs.pop("case_sensitive")
|
| 991 |
+
|
| 992 |
+
return self._dispatch_to_path("match", path_pattern, **kwargs)
|
| 993 |
+
|
| 994 |
+
@property
|
| 995 |
+
def parser(self) -> Self:
|
| 996 |
+
if sys.version_info < (3, 13):
|
| 997 |
+
raise NotImplementedError("parser requires Python 3.13 or higher")
|
| 998 |
+
|
| 999 |
+
return self._dispatch_to_path("parser")
|
| 1000 |
+
|
| 1001 |
+
@property
|
| 1002 |
+
def parent(self) -> Self:
|
| 1003 |
+
return self._dispatch_to_path("parent")
|
| 1004 |
+
|
| 1005 |
+
@property
|
| 1006 |
+
def parents(self) -> Tuple[Self, ...]:
|
| 1007 |
+
return self._dispatch_to_path("parents")
|
| 1008 |
+
|
| 1009 |
+
@property
|
| 1010 |
+
def parts(self) -> Tuple[str, ...]:
|
| 1011 |
+
parts = self._dispatch_to_path("parts")
|
| 1012 |
+
if parts[0] == "/":
|
| 1013 |
+
parts = parts[1:]
|
| 1014 |
+
|
| 1015 |
+
return (self.anchor, *parts)
|
| 1016 |
+
|
| 1017 |
+
@property
|
| 1018 |
+
def stem(self) -> str:
|
| 1019 |
+
return self._dispatch_to_path("stem")
|
| 1020 |
+
|
| 1021 |
+
@property
|
| 1022 |
+
def suffix(self) -> str:
|
| 1023 |
+
return self._dispatch_to_path("suffix")
|
| 1024 |
+
|
| 1025 |
+
@property
|
| 1026 |
+
def suffixes(self) -> List[str]:
|
| 1027 |
+
return self._dispatch_to_path("suffixes")
|
| 1028 |
+
|
| 1029 |
+
def with_stem(self, stem: str) -> Self:
|
| 1030 |
+
try:
|
| 1031 |
+
return self._dispatch_to_path("with_stem", stem)
|
| 1032 |
+
except AttributeError:
|
| 1033 |
+
# with_stem was only added in python 3.9, so we fallback for compatibility
|
| 1034 |
+
return self.with_name(stem + self.suffix)
|
| 1035 |
+
|
| 1036 |
+
def with_name(self, name: str) -> Self:
|
| 1037 |
+
return self._dispatch_to_path("with_name", name)
|
| 1038 |
+
|
| 1039 |
+
def with_segments(self, *pathsegments) -> Self:
|
| 1040 |
+
"""Create a new CloudPath with the same client out of the given segments.
|
| 1041 |
+
The first segment will be interpreted as the bucket/container name.
|
| 1042 |
+
"""
|
| 1043 |
+
return self._new_cloudpath("/".join(pathsegments))
|
| 1044 |
+
|
| 1045 |
+
def with_suffix(self, suffix: str) -> Self:
|
| 1046 |
+
return self._dispatch_to_path("with_suffix", suffix)
|
| 1047 |
+
|
| 1048 |
+
# ====================== DISPATCHED TO LOCAL CACHE FOR CONCRETE PATHS ======================
|
| 1049 |
+
# Items that can be executed on the cached file on the local filesystem
|
| 1050 |
+
def _dispatch_to_local_cache_path(self, func: str, *args, **kwargs) -> Any:
|
| 1051 |
+
self._refresh_cache()
|
| 1052 |
+
|
| 1053 |
+
path_version = self._local.__getattribute__(func)
|
| 1054 |
+
|
| 1055 |
+
# Path functions should be called so the results are calculated
|
| 1056 |
+
if callable(path_version):
|
| 1057 |
+
path_version = path_version(*args, **kwargs)
|
| 1058 |
+
|
| 1059 |
+
# Paths should always be resolved and then converted to the same client + class as this one
|
| 1060 |
+
if isinstance(path_version, (PosixPath, WindowsPath)):
|
| 1061 |
+
# always resolve since cloud paths must be absolute
|
| 1062 |
+
path_version = path_version.resolve()
|
| 1063 |
+
return self._new_cloudpath(path_version)
|
| 1064 |
+
|
| 1065 |
+
# when pathlib returns a string, etc. we probably just want that thing
|
| 1066 |
+
else:
|
| 1067 |
+
return path_version
|
| 1068 |
+
|
| 1069 |
+
def stat(self, follow_symlinks: bool = True) -> os.stat_result:
|
| 1070 |
+
"""Note: for many clients, we may want to override so we don't incur
|
| 1071 |
+
network costs since many of these properties are available as
|
| 1072 |
+
API calls.
|
| 1073 |
+
"""
|
| 1074 |
+
warn(
|
| 1075 |
+
f"stat not implemented as API call for {self.__class__} so file must be downloaded to "
|
| 1076 |
+
f"calculate stats; this may take a long time depending on filesize"
|
| 1077 |
+
)
|
| 1078 |
+
return self._dispatch_to_local_cache_path("stat", follow_symlinks=follow_symlinks)
|
| 1079 |
+
|
| 1080 |
+
def info(self) -> "CloudPathInfo":
|
| 1081 |
+
"""Return a CloudPathInfo object for this path."""
|
| 1082 |
+
return CloudPathInfo(self)
|
| 1083 |
+
|
| 1084 |
+
# =========== public cloud methods, not in pathlib ===============
|
| 1085 |
+
def download_to(self, destination: Union[str, os.PathLike]) -> Path:
|
| 1086 |
+
destination = Path(destination)
|
| 1087 |
+
|
| 1088 |
+
if not self.exists():
|
| 1089 |
+
raise CloudPathNotExistsError(f"Cannot download because path does not exist: {self}")
|
| 1090 |
+
|
| 1091 |
+
if self.is_file():
|
| 1092 |
+
if destination.is_dir():
|
| 1093 |
+
destination = destination / self.name
|
| 1094 |
+
return self.client._download_file(self, destination)
|
| 1095 |
+
else:
|
| 1096 |
+
destination.mkdir(exist_ok=True)
|
| 1097 |
+
for f in self.iterdir():
|
| 1098 |
+
rel = str(self)
|
| 1099 |
+
if not rel.endswith("/"):
|
| 1100 |
+
rel = rel + "/"
|
| 1101 |
+
|
| 1102 |
+
rel_dest = str(f)[len(rel) :]
|
| 1103 |
+
f.download_to(destination / rel_dest)
|
| 1104 |
+
|
| 1105 |
+
return destination
|
| 1106 |
+
|
| 1107 |
+
def rmtree(self) -> None:
|
| 1108 |
+
"""Delete an entire directory tree."""
|
| 1109 |
+
if self.is_file():
|
| 1110 |
+
raise CloudPathNotADirectoryError(
|
| 1111 |
+
f"Path {self} is a file; call unlink instead of rmtree."
|
| 1112 |
+
)
|
| 1113 |
+
self.client._remove(self)
|
| 1114 |
+
|
| 1115 |
+
def upload_from(
|
| 1116 |
+
self,
|
| 1117 |
+
source: Union[str, os.PathLike],
|
| 1118 |
+
force_overwrite_to_cloud: Optional[bool] = None,
|
| 1119 |
+
) -> Self:
|
| 1120 |
+
"""Upload a file or directory to the cloud path."""
|
| 1121 |
+
source = Path(source)
|
| 1122 |
+
|
| 1123 |
+
if source.is_dir():
|
| 1124 |
+
for p in source.iterdir():
|
| 1125 |
+
(self / p.name).upload_from(p, force_overwrite_to_cloud=force_overwrite_to_cloud)
|
| 1126 |
+
|
| 1127 |
+
return self
|
| 1128 |
+
|
| 1129 |
+
else:
|
| 1130 |
+
if self.exists() and self.is_dir():
|
| 1131 |
+
dst = self / source.name
|
| 1132 |
+
else:
|
| 1133 |
+
dst = self
|
| 1134 |
+
|
| 1135 |
+
dst._upload_file_to_cloud(source, force_overwrite_to_cloud=force_overwrite_to_cloud)
|
| 1136 |
+
|
| 1137 |
+
return dst
|
| 1138 |
+
|
| 1139 |
+
def _copy(
|
| 1140 |
+
self,
|
| 1141 |
+
target: Union[str, os.PathLike, "CloudPath"],
|
| 1142 |
+
follow_symlinks: bool = True,
|
| 1143 |
+
preserve_metadata: bool = False,
|
| 1144 |
+
force_overwrite_to_cloud: Optional[bool] = None,
|
| 1145 |
+
remove_src: bool = False,
|
| 1146 |
+
) -> Union[Path, Self]:
|
| 1147 |
+
if not self.exists():
|
| 1148 |
+
raise ValueError(f"Path {self} must exist to copy.")
|
| 1149 |
+
|
| 1150 |
+
destination = anypath.to_anypath(target)
|
| 1151 |
+
|
| 1152 |
+
if self.is_dir():
|
| 1153 |
+
result = self.copytree(
|
| 1154 |
+
destination, # type: ignore[arg-type]
|
| 1155 |
+
force_overwrite_to_cloud=force_overwrite_to_cloud,
|
| 1156 |
+
)
|
| 1157 |
+
return cast(Union[Path, Self], result)
|
| 1158 |
+
|
| 1159 |
+
if not isinstance(destination, CloudPath):
|
| 1160 |
+
return self.download_to(destination)
|
| 1161 |
+
|
| 1162 |
+
# if same client, use cloud-native _move_file on client to avoid downloading
|
| 1163 |
+
if self.client is destination.client:
|
| 1164 |
+
if destination.exists() and destination.is_dir():
|
| 1165 |
+
destination = destination / self.name
|
| 1166 |
+
|
| 1167 |
+
if force_overwrite_to_cloud is None:
|
| 1168 |
+
force_overwrite_to_cloud = os.environ.get(
|
| 1169 |
+
"CLOUDPATHLIB_FORCE_OVERWRITE_TO_CLOUD", "False"
|
| 1170 |
+
).lower() in ["1", "true"]
|
| 1171 |
+
|
| 1172 |
+
if (
|
| 1173 |
+
not force_overwrite_to_cloud
|
| 1174 |
+
and destination.exists()
|
| 1175 |
+
and destination.stat().st_mtime >= self.stat().st_mtime
|
| 1176 |
+
):
|
| 1177 |
+
raise OverwriteNewerCloudError(
|
| 1178 |
+
f"File ({destination}) is newer than ({self}). "
|
| 1179 |
+
f"To overwrite "
|
| 1180 |
+
f"pass `force_overwrite_to_cloud=True`."
|
| 1181 |
+
)
|
| 1182 |
+
|
| 1183 |
+
return cast(Self, self.client._move_file(self, destination, remove_src=remove_src))
|
| 1184 |
+
|
| 1185 |
+
else:
|
| 1186 |
+
if not destination.exists() or destination.is_file():
|
| 1187 |
+
return cast(
|
| 1188 |
+
Union[Path, Self],
|
| 1189 |
+
destination.upload_from(
|
| 1190 |
+
self.fspath, force_overwrite_to_cloud=force_overwrite_to_cloud
|
| 1191 |
+
),
|
| 1192 |
+
)
|
| 1193 |
+
else:
|
| 1194 |
+
return cast(
|
| 1195 |
+
Union[Path, Self],
|
| 1196 |
+
(destination / self.name).upload_from(
|
| 1197 |
+
self.fspath, force_overwrite_to_cloud=force_overwrite_to_cloud
|
| 1198 |
+
),
|
| 1199 |
+
)
|
| 1200 |
+
|
| 1201 |
+
@overload
|
| 1202 |
+
def copy(
|
| 1203 |
+
self,
|
| 1204 |
+
target: Self,
|
| 1205 |
+
follow_symlinks=True,
|
| 1206 |
+
preserve_metadata=False,
|
| 1207 |
+
force_overwrite_to_cloud: Optional[bool] = None,
|
| 1208 |
+
) -> Self: ...
|
| 1209 |
+
|
| 1210 |
+
@overload
|
| 1211 |
+
def copy(
|
| 1212 |
+
self,
|
| 1213 |
+
target: Path,
|
| 1214 |
+
follow_symlinks=True,
|
| 1215 |
+
preserve_metadata=False,
|
| 1216 |
+
force_overwrite_to_cloud: Optional[bool] = None,
|
| 1217 |
+
) -> Path: ...
|
| 1218 |
+
|
| 1219 |
+
@overload
|
| 1220 |
+
def copy(
|
| 1221 |
+
self,
|
| 1222 |
+
target: str,
|
| 1223 |
+
follow_symlinks=True,
|
| 1224 |
+
preserve_metadata=False,
|
| 1225 |
+
force_overwrite_to_cloud: Optional[bool] = None,
|
| 1226 |
+
) -> Union[Path, "CloudPath"]: ...
|
| 1227 |
+
|
| 1228 |
+
def copy(
|
| 1229 |
+
self,
|
| 1230 |
+
target: Union[str, os.PathLike, Self],
|
| 1231 |
+
follow_symlinks: bool = True,
|
| 1232 |
+
preserve_metadata: bool = False,
|
| 1233 |
+
force_overwrite_to_cloud: Optional[bool] = None,
|
| 1234 |
+
) -> Union[Path, Self]:
|
| 1235 |
+
"""Copy self to target folder or file, if self is a file."""
|
| 1236 |
+
return self._copy(
|
| 1237 |
+
target,
|
| 1238 |
+
follow_symlinks=follow_symlinks,
|
| 1239 |
+
preserve_metadata=preserve_metadata,
|
| 1240 |
+
force_overwrite_to_cloud=force_overwrite_to_cloud,
|
| 1241 |
+
remove_src=False,
|
| 1242 |
+
)
|
| 1243 |
+
|
| 1244 |
+
@overload
|
| 1245 |
+
def copy_into(
|
| 1246 |
+
self,
|
| 1247 |
+
target_dir: Self,
|
| 1248 |
+
follow_symlinks: bool = True,
|
| 1249 |
+
preserve_metadata: bool = False,
|
| 1250 |
+
force_overwrite_to_cloud: Optional[bool] = None,
|
| 1251 |
+
) -> Self: ...
|
| 1252 |
+
|
| 1253 |
+
@overload
|
| 1254 |
+
def copy_into(
|
| 1255 |
+
self,
|
| 1256 |
+
target_dir: Path,
|
| 1257 |
+
follow_symlinks: bool = True,
|
| 1258 |
+
preserve_metadata: bool = False,
|
| 1259 |
+
force_overwrite_to_cloud: Optional[bool] = None,
|
| 1260 |
+
) -> Path: ...
|
| 1261 |
+
|
| 1262 |
+
@overload
|
| 1263 |
+
def copy_into(
|
| 1264 |
+
self,
|
| 1265 |
+
target_dir: str,
|
| 1266 |
+
follow_symlinks: bool = True,
|
| 1267 |
+
preserve_metadata: bool = False,
|
| 1268 |
+
force_overwrite_to_cloud: Optional[bool] = None,
|
| 1269 |
+
) -> Union[Path, "CloudPath"]: ...
|
| 1270 |
+
|
| 1271 |
+
def copy_into(
|
| 1272 |
+
self,
|
| 1273 |
+
target_dir: Union[str, os.PathLike, Self],
|
| 1274 |
+
follow_symlinks: bool = True,
|
| 1275 |
+
preserve_metadata: bool = False,
|
| 1276 |
+
force_overwrite_to_cloud: Optional[bool] = None,
|
| 1277 |
+
) -> Union[Path, Self]:
|
| 1278 |
+
"""Copy self into target directory, preserving the filename."""
|
| 1279 |
+
target_path = anypath.to_anypath(target_dir) / self.name
|
| 1280 |
+
|
| 1281 |
+
result = self._copy(
|
| 1282 |
+
target_path,
|
| 1283 |
+
follow_symlinks=follow_symlinks,
|
| 1284 |
+
preserve_metadata=preserve_metadata,
|
| 1285 |
+
force_overwrite_to_cloud=force_overwrite_to_cloud,
|
| 1286 |
+
remove_src=False,
|
| 1287 |
+
)
|
| 1288 |
+
return cast(Union[Path, Self], result)
|
| 1289 |
+
|
| 1290 |
+
@overload
|
| 1291 |
+
def copytree(
|
| 1292 |
+
self,
|
| 1293 |
+
destination: Self,
|
| 1294 |
+
force_overwrite_to_cloud: Optional[bool] = None,
|
| 1295 |
+
ignore: Optional[Callable[[str, Iterable[str]], Container[str]]] = None,
|
| 1296 |
+
) -> Self: ...
|
| 1297 |
+
|
| 1298 |
+
@overload
|
| 1299 |
+
def copytree(
|
| 1300 |
+
self,
|
| 1301 |
+
destination: Path,
|
| 1302 |
+
force_overwrite_to_cloud: Optional[bool] = None,
|
| 1303 |
+
ignore: Optional[Callable[[str, Iterable[str]], Container[str]]] = None,
|
| 1304 |
+
) -> Path: ...
|
| 1305 |
+
|
| 1306 |
+
@overload
|
| 1307 |
+
def copytree(
|
| 1308 |
+
self,
|
| 1309 |
+
destination: Union[str, os.PathLike, Self],
|
| 1310 |
+
force_overwrite_to_cloud: Optional[bool] = None,
|
| 1311 |
+
ignore: Optional[Callable[[str, Iterable[str]], Container[str]]] = None,
|
| 1312 |
+
) -> Union[Path, "CloudPath"]: ...
|
| 1313 |
+
|
| 1314 |
+
def copytree(self, destination, force_overwrite_to_cloud=None, ignore=None):
|
| 1315 |
+
"""Copy self to a directory, if self is a directory."""
|
| 1316 |
+
if not self.is_dir():
|
| 1317 |
+
raise CloudPathNotADirectoryError(
|
| 1318 |
+
f"Origin path {self} must be a directory. To copy a single file use the method copy."
|
| 1319 |
+
)
|
| 1320 |
+
|
| 1321 |
+
destination = anypath.to_anypath(destination)
|
| 1322 |
+
|
| 1323 |
+
if destination.exists() and destination.is_file():
|
| 1324 |
+
raise CloudPathFileExistsError(
|
| 1325 |
+
f"Destination path {destination} of copytree must be a directory."
|
| 1326 |
+
)
|
| 1327 |
+
|
| 1328 |
+
contents = list(self.iterdir())
|
| 1329 |
+
|
| 1330 |
+
if ignore is not None:
|
| 1331 |
+
ignored_names = ignore(self._no_prefix_no_drive, [x.name for x in contents])
|
| 1332 |
+
else:
|
| 1333 |
+
ignored_names = set()
|
| 1334 |
+
|
| 1335 |
+
destination.mkdir(parents=True, exist_ok=True)
|
| 1336 |
+
|
| 1337 |
+
for subpath in contents:
|
| 1338 |
+
if subpath.name in ignored_names:
|
| 1339 |
+
continue
|
| 1340 |
+
if subpath.is_file():
|
| 1341 |
+
subpath.copy(
|
| 1342 |
+
destination / subpath.name, force_overwrite_to_cloud=force_overwrite_to_cloud
|
| 1343 |
+
)
|
| 1344 |
+
elif subpath.is_dir():
|
| 1345 |
+
subpath.copytree(
|
| 1346 |
+
destination / (subpath.name + ("" if subpath.name.endswith("/") else "/")),
|
| 1347 |
+
force_overwrite_to_cloud=force_overwrite_to_cloud,
|
| 1348 |
+
ignore=ignore,
|
| 1349 |
+
)
|
| 1350 |
+
|
| 1351 |
+
return destination
|
| 1352 |
+
|
| 1353 |
+
@overload
|
| 1354 |
+
def move(
|
| 1355 |
+
self,
|
| 1356 |
+
target: Self,
|
| 1357 |
+
follow_symlinks: bool = True,
|
| 1358 |
+
preserve_metadata: bool = False,
|
| 1359 |
+
force_overwrite_to_cloud: Optional[bool] = None,
|
| 1360 |
+
) -> Self: ...
|
| 1361 |
+
|
| 1362 |
+
@overload
|
| 1363 |
+
def move(
|
| 1364 |
+
self,
|
| 1365 |
+
target: Path,
|
| 1366 |
+
follow_symlinks: bool = True,
|
| 1367 |
+
preserve_metadata: bool = False,
|
| 1368 |
+
force_overwrite_to_cloud: Optional[bool] = None,
|
| 1369 |
+
) -> Path: ...
|
| 1370 |
+
|
| 1371 |
+
@overload
|
| 1372 |
+
def move(
|
| 1373 |
+
self,
|
| 1374 |
+
target: str,
|
| 1375 |
+
follow_symlinks: bool = True,
|
| 1376 |
+
preserve_metadata: bool = False,
|
| 1377 |
+
force_overwrite_to_cloud: Optional[bool] = None,
|
| 1378 |
+
) -> Union[Path, "CloudPath"]: ...
|
| 1379 |
+
|
| 1380 |
+
def move(
|
| 1381 |
+
self,
|
| 1382 |
+
target: Union[str, os.PathLike, Self],
|
| 1383 |
+
follow_symlinks: bool = True,
|
| 1384 |
+
preserve_metadata: bool = False,
|
| 1385 |
+
force_overwrite_to_cloud: Optional[bool] = None,
|
| 1386 |
+
) -> Union[Path, Self]:
|
| 1387 |
+
"""Move self to target location, removing the source."""
|
| 1388 |
+
return self._copy(
|
| 1389 |
+
target,
|
| 1390 |
+
follow_symlinks=follow_symlinks,
|
| 1391 |
+
preserve_metadata=preserve_metadata,
|
| 1392 |
+
force_overwrite_to_cloud=force_overwrite_to_cloud,
|
| 1393 |
+
remove_src=True,
|
| 1394 |
+
)
|
| 1395 |
+
|
| 1396 |
+
@overload
|
| 1397 |
+
def move_into(
|
| 1398 |
+
self,
|
| 1399 |
+
target_dir: Self,
|
| 1400 |
+
follow_symlinks: bool = True,
|
| 1401 |
+
preserve_metadata: bool = False,
|
| 1402 |
+
force_overwrite_to_cloud: Optional[bool] = None,
|
| 1403 |
+
) -> Self: ...
|
| 1404 |
+
|
| 1405 |
+
@overload
|
| 1406 |
+
def move_into(
|
| 1407 |
+
self,
|
| 1408 |
+
target_dir: Path,
|
| 1409 |
+
follow_symlinks: bool = True,
|
| 1410 |
+
preserve_metadata: bool = False,
|
| 1411 |
+
force_overwrite_to_cloud: Optional[bool] = None,
|
| 1412 |
+
) -> Path: ...
|
| 1413 |
+
|
| 1414 |
+
@overload
|
| 1415 |
+
def move_into(
|
| 1416 |
+
self,
|
| 1417 |
+
target_dir: str,
|
| 1418 |
+
follow_symlinks: bool = True,
|
| 1419 |
+
preserve_metadata: bool = False,
|
| 1420 |
+
force_overwrite_to_cloud: Optional[bool] = None,
|
| 1421 |
+
) -> Union[Path, "CloudPath"]: ...
|
| 1422 |
+
|
| 1423 |
+
def move_into(
|
| 1424 |
+
self,
|
| 1425 |
+
target_dir: Union[str, os.PathLike, Self],
|
| 1426 |
+
follow_symlinks: bool = True,
|
| 1427 |
+
preserve_metadata: bool = False,
|
| 1428 |
+
force_overwrite_to_cloud: Optional[bool] = None,
|
| 1429 |
+
) -> Union[Path, Self]:
|
| 1430 |
+
"""Move self into target directory, preserving the filename and removing the source."""
|
| 1431 |
+
target_path = anypath.to_anypath(target_dir) / self.name
|
| 1432 |
+
|
| 1433 |
+
result = self._copy(
|
| 1434 |
+
target_path,
|
| 1435 |
+
follow_symlinks=follow_symlinks,
|
| 1436 |
+
preserve_metadata=preserve_metadata,
|
| 1437 |
+
force_overwrite_to_cloud=force_overwrite_to_cloud,
|
| 1438 |
+
remove_src=True,
|
| 1439 |
+
)
|
| 1440 |
+
return cast(Union[Path, Self], result)
|
| 1441 |
+
|
| 1442 |
+
def clear_cache(self):
|
| 1443 |
+
"""Removes cache if it exists"""
|
| 1444 |
+
if self._local.exists():
|
| 1445 |
+
if self._local.is_file():
|
| 1446 |
+
self._local.unlink()
|
| 1447 |
+
else:
|
| 1448 |
+
shutil.rmtree(self._local)
|
| 1449 |
+
|
| 1450 |
+
# =========== private cloud methods ===============
|
| 1451 |
+
@property
|
| 1452 |
+
def _local(self) -> Path:
|
| 1453 |
+
"""Cached local version of the file."""
|
| 1454 |
+
return self.client._local_cache_dir / self._no_prefix
|
| 1455 |
+
|
| 1456 |
+
def _new_cloudpath(self, path: Union[str, os.PathLike], *parts: str) -> Self:
|
| 1457 |
+
"""Use the scheme, client, cache dir of this cloudpath to instantiate
|
| 1458 |
+
a new cloudpath of the same type with the path passed.
|
| 1459 |
+
|
| 1460 |
+
Used to make results of iterdir and joins have a unified client + cache.
|
| 1461 |
+
"""
|
| 1462 |
+
path = str(path)
|
| 1463 |
+
|
| 1464 |
+
# strip initial "/" if path has one
|
| 1465 |
+
if path.startswith("/"):
|
| 1466 |
+
path = path[1:]
|
| 1467 |
+
|
| 1468 |
+
# add prefix/anchor if it is not already
|
| 1469 |
+
if not path.startswith(self.anchor):
|
| 1470 |
+
path = f"{self.anchor}{path}"
|
| 1471 |
+
|
| 1472 |
+
return self.client.CloudPath(path, *parts)
|
| 1473 |
+
|
| 1474 |
+
def _refresh_cache(self, force_overwrite_from_cloud: Optional[bool] = None) -> None:
|
| 1475 |
+
try:
|
| 1476 |
+
stats = self.stat()
|
| 1477 |
+
except NoStatError:
|
| 1478 |
+
# nothing to cache if the file does not exist; happens when creating
|
| 1479 |
+
# new files that will be uploaded
|
| 1480 |
+
return
|
| 1481 |
+
|
| 1482 |
+
if force_overwrite_from_cloud is None:
|
| 1483 |
+
force_overwrite_from_cloud = os.environ.get(
|
| 1484 |
+
"CLOUDPATHLIB_FORCE_OVERWRITE_FROM_CLOUD", "False"
|
| 1485 |
+
).lower() in ["1", "true"]
|
| 1486 |
+
|
| 1487 |
+
# if not exist or cloud newer
|
| 1488 |
+
if (
|
| 1489 |
+
force_overwrite_from_cloud
|
| 1490 |
+
or not self._local.exists()
|
| 1491 |
+
or (self._local.stat().st_mtime < stats.st_mtime)
|
| 1492 |
+
):
|
| 1493 |
+
# ensure there is a home for the file
|
| 1494 |
+
self._local.parent.mkdir(parents=True, exist_ok=True)
|
| 1495 |
+
self.download_to(self._local)
|
| 1496 |
+
|
| 1497 |
+
# force cache time to match cloud times
|
| 1498 |
+
os.utime(self._local, times=(stats.st_mtime, stats.st_mtime))
|
| 1499 |
+
|
| 1500 |
+
if self._dirty:
|
| 1501 |
+
raise OverwriteDirtyFileError(
|
| 1502 |
+
f"Local file ({self._local}) for cloud path ({self}) has been changed by your code, but "
|
| 1503 |
+
f"is being requested for download from cloud. Either (1) push your changes to the cloud, "
|
| 1504 |
+
f"(2) remove the local file, or (3) pass `force_overwrite_from_cloud=True` to "
|
| 1505 |
+
f"overwrite; or set env var CLOUDPATHLIB_FORCE_OVERWRITE_FROM_CLOUD=1."
|
| 1506 |
+
)
|
| 1507 |
+
|
| 1508 |
+
# if local newer but not dirty, it was updated
|
| 1509 |
+
# by a separate process; do not overwrite unless forced to
|
| 1510 |
+
if self._local.stat().st_mtime > stats.st_mtime:
|
| 1511 |
+
raise OverwriteNewerLocalError(
|
| 1512 |
+
f"Local file ({self._local}) for cloud path ({self}) is newer on disk, but "
|
| 1513 |
+
f"is being requested for download from cloud. Either (1) push your changes to the cloud, "
|
| 1514 |
+
f"(2) remove the local file, or (3) pass `force_overwrite_from_cloud=True` to "
|
| 1515 |
+
f"overwrite; or set env var CLOUDPATHLIB_FORCE_OVERWRITE_FROM_CLOUD=1."
|
| 1516 |
+
)
|
| 1517 |
+
|
| 1518 |
+
def _upload_local_to_cloud(
|
| 1519 |
+
self,
|
| 1520 |
+
force_overwrite_to_cloud: Optional[bool] = None,
|
| 1521 |
+
) -> Self:
|
| 1522 |
+
"""Uploads cache file at self._local to the cloud"""
|
| 1523 |
+
# We should never try to be syncing entire directories; we should only
|
| 1524 |
+
# cache and upload individual files.
|
| 1525 |
+
if self._local.is_dir():
|
| 1526 |
+
raise ValueError("Only individual files can be uploaded to the cloud")
|
| 1527 |
+
|
| 1528 |
+
uploaded = self._upload_file_to_cloud(
|
| 1529 |
+
self._local, force_overwrite_to_cloud=force_overwrite_to_cloud
|
| 1530 |
+
)
|
| 1531 |
+
|
| 1532 |
+
# force cache time to match cloud times
|
| 1533 |
+
stats = self.stat()
|
| 1534 |
+
os.utime(self._local, times=(stats.st_mtime, stats.st_mtime))
|
| 1535 |
+
|
| 1536 |
+
# reset dirty and handle now that this is uploaded
|
| 1537 |
+
self._dirty = False
|
| 1538 |
+
self._handle = None
|
| 1539 |
+
|
| 1540 |
+
return uploaded
|
| 1541 |
+
|
| 1542 |
+
def _upload_file_to_cloud(
|
| 1543 |
+
self,
|
| 1544 |
+
local_path: Path,
|
| 1545 |
+
force_overwrite_to_cloud: Optional[bool] = None,
|
| 1546 |
+
) -> Self:
|
| 1547 |
+
"""Uploads file at `local_path` to the cloud if there is not a newer file
|
| 1548 |
+
already there.
|
| 1549 |
+
"""
|
| 1550 |
+
if force_overwrite_to_cloud is None:
|
| 1551 |
+
force_overwrite_to_cloud = os.environ.get(
|
| 1552 |
+
"CLOUDPATHLIB_FORCE_OVERWRITE_TO_CLOUD", "False"
|
| 1553 |
+
).lower() in ["1", "true"]
|
| 1554 |
+
|
| 1555 |
+
if force_overwrite_to_cloud:
|
| 1556 |
+
# If we are overwriting no need to perform any checks, so we can save time
|
| 1557 |
+
self.client._upload_file(
|
| 1558 |
+
local_path,
|
| 1559 |
+
self,
|
| 1560 |
+
)
|
| 1561 |
+
return self
|
| 1562 |
+
|
| 1563 |
+
try:
|
| 1564 |
+
stats = self.stat()
|
| 1565 |
+
except NoStatError:
|
| 1566 |
+
stats = None
|
| 1567 |
+
|
| 1568 |
+
# if cloud does not exist or local is newer, do the upload
|
| 1569 |
+
if not stats or (local_path.stat().st_mtime > stats.st_mtime):
|
| 1570 |
+
self.client._upload_file(
|
| 1571 |
+
local_path,
|
| 1572 |
+
self,
|
| 1573 |
+
)
|
| 1574 |
+
|
| 1575 |
+
return self
|
| 1576 |
+
|
| 1577 |
+
# cloud is newer and we are not overwriting
|
| 1578 |
+
raise OverwriteNewerCloudError(
|
| 1579 |
+
f"Local file ({self._local}) for cloud path ({self}) is newer in the cloud disk, but "
|
| 1580 |
+
f"is being requested to be uploaded to the cloud. Either (1) redownload changes from the cloud or "
|
| 1581 |
+
f"(2) pass `force_overwrite_to_cloud=True` to "
|
| 1582 |
+
f"overwrite; or set env var CLOUDPATHLIB_FORCE_OVERWRITE_TO_CLOUD=1."
|
| 1583 |
+
)
|
| 1584 |
+
|
| 1585 |
+
# =========== pydantic integration special methods ===============
|
| 1586 |
+
@classmethod
|
| 1587 |
+
def __get_pydantic_core_schema__(cls, _source_type: Any, _handler):
|
| 1588 |
+
"""Pydantic special method. See
|
| 1589 |
+
https://docs.pydantic.dev/2.0/usage/types/custom/"""
|
| 1590 |
+
try:
|
| 1591 |
+
from pydantic_core import core_schema
|
| 1592 |
+
|
| 1593 |
+
return core_schema.no_info_after_validator_function(
|
| 1594 |
+
cls.validate,
|
| 1595 |
+
core_schema.any_schema(),
|
| 1596 |
+
)
|
| 1597 |
+
except ImportError:
|
| 1598 |
+
return None
|
| 1599 |
+
|
| 1600 |
+
@classmethod
|
| 1601 |
+
def validate(cls, v: str) -> Self:
|
| 1602 |
+
"""Used as a Pydantic validator. See
|
| 1603 |
+
https://docs.pydantic.dev/2.0/usage/types/custom/"""
|
| 1604 |
+
return cls(v)
|
| 1605 |
+
|
| 1606 |
+
@classmethod
|
| 1607 |
+
def __get_validators__(cls) -> Generator[Callable[[Any], Self], None, None]:
|
| 1608 |
+
"""Pydantic special method. See
|
| 1609 |
+
https://pydantic-docs.helpmanual.io/usage/types/#custom-data-types"""
|
| 1610 |
+
yield cls._validate
|
| 1611 |
+
|
| 1612 |
+
@classmethod
|
| 1613 |
+
def _validate(cls, value: Any) -> Self:
|
| 1614 |
+
"""Used as a Pydantic validator. See
|
| 1615 |
+
https://pydantic-docs.helpmanual.io/usage/types/#custom-data-types"""
|
| 1616 |
+
return cls(value)
|
| 1617 |
+
|
| 1618 |
+
|
| 1619 |
+
# The function resolve is not available on Pure paths because it removes relative
|
| 1620 |
+
# paths and symlinks. We _just_ want the relative path resolution for
|
| 1621 |
+
# cloud paths, so the other logic is removed. Also, we can assume that
|
| 1622 |
+
# cloud paths are absolute.
|
| 1623 |
+
#
|
| 1624 |
+
# Based on resolve from pathlib:
|
| 1625 |
+
# https://github.com/python/cpython/blob/3.8/Lib/pathlib.py#L316-L359
|
| 1626 |
+
def _resolve(path: PurePosixPath) -> str:
|
| 1627 |
+
sep = "/"
|
| 1628 |
+
|
| 1629 |
+
# rebuild path from parts
|
| 1630 |
+
newpath = ""
|
| 1631 |
+
for name in str(path).split(sep):
|
| 1632 |
+
if not name or name == ".":
|
| 1633 |
+
# current dir, nothing to add
|
| 1634 |
+
continue
|
| 1635 |
+
if name == "..":
|
| 1636 |
+
# parent dir, drop right-most part
|
| 1637 |
+
newpath, _, _ = newpath.rpartition(sep)
|
| 1638 |
+
continue
|
| 1639 |
+
newpath = newpath + sep + name
|
| 1640 |
+
|
| 1641 |
+
return newpath or sep
|
| 1642 |
+
|
| 1643 |
+
|
| 1644 |
+
# These objects are used to wrap CloudPaths in a context where we can use
|
| 1645 |
+
# the python pathlib implementations for `glob` and `rglob`, which depend
|
| 1646 |
+
# on the Selector created by the `_make_selector` method being passed
|
| 1647 |
+
# an object like the below when `select_from` is called. We implement these methods
|
| 1648 |
+
# in a simple wrapper to use the same glob recursion and pattern logic without
|
| 1649 |
+
# rolling our own.
|
| 1650 |
+
#
|
| 1651 |
+
# Designed to be compatible when used by these selector implementations from pathlib:
|
| 1652 |
+
# https://github.com/python/cpython/blob/3.10/Lib/pathlib.py#L385-L500
|
| 1653 |
+
class _CloudPathSelectableAccessor:
|
| 1654 |
+
def __init__(self, scandir_func: Callable) -> None:
|
| 1655 |
+
self.scandir = scandir_func
|
| 1656 |
+
|
| 1657 |
+
|
| 1658 |
+
class _CloudPathSelectable:
|
| 1659 |
+
def __init__(
|
| 1660 |
+
self,
|
| 1661 |
+
name: str,
|
| 1662 |
+
parents: List[str],
|
| 1663 |
+
children: Any, # Nested dictionaries as tree
|
| 1664 |
+
exists: bool = True,
|
| 1665 |
+
) -> None:
|
| 1666 |
+
self._name = name
|
| 1667 |
+
self._all_children = children
|
| 1668 |
+
self._parents = parents
|
| 1669 |
+
self._exists = exists
|
| 1670 |
+
|
| 1671 |
+
self._accessor = _CloudPathSelectableAccessor(self.scandir)
|
| 1672 |
+
|
| 1673 |
+
def __repr__(self) -> str:
|
| 1674 |
+
return "/".join(self._parents + [self.name])
|
| 1675 |
+
|
| 1676 |
+
def is_dir(self, follow_symlinks: bool = False) -> bool:
|
| 1677 |
+
return self._all_children is not None
|
| 1678 |
+
|
| 1679 |
+
def exists(self) -> bool:
|
| 1680 |
+
return self._exists
|
| 1681 |
+
|
| 1682 |
+
def is_symlink(self) -> bool:
|
| 1683 |
+
return False
|
| 1684 |
+
|
| 1685 |
+
@property
|
| 1686 |
+
def name(self) -> str:
|
| 1687 |
+
return self._name
|
| 1688 |
+
|
| 1689 |
+
def _make_child_relpath(self, part):
|
| 1690 |
+
# pathlib internals shortcut; makes a relative path, even if it doesn't actually exist
|
| 1691 |
+
return _CloudPathSelectable(
|
| 1692 |
+
part,
|
| 1693 |
+
self._parents + [self.name],
|
| 1694 |
+
self._all_children.get(part, None),
|
| 1695 |
+
exists=part in self._all_children,
|
| 1696 |
+
)
|
| 1697 |
+
|
| 1698 |
+
@staticmethod
|
| 1699 |
+
@contextmanager
|
| 1700 |
+
def scandir(
|
| 1701 |
+
root: "_CloudPathSelectable",
|
| 1702 |
+
) -> Generator[Generator["_CloudPathSelectable", None, None], None, None]:
|
| 1703 |
+
yield (
|
| 1704 |
+
_CloudPathSelectable(child, root._parents + [root._name], grand_children)
|
| 1705 |
+
for child, grand_children in root._all_children.items()
|
| 1706 |
+
)
|
| 1707 |
+
|
| 1708 |
+
_scandir = scandir # Py 3.11 compatibility
|
| 1709 |
+
|
| 1710 |
+
def walk(self):
|
| 1711 |
+
# split into dirs and files
|
| 1712 |
+
dirs_files = defaultdict(list)
|
| 1713 |
+
with self.scandir(self) as items:
|
| 1714 |
+
for child in items:
|
| 1715 |
+
dirs_files[child.is_dir()].append(child)
|
| 1716 |
+
|
| 1717 |
+
# top-down, so yield self before recursive call
|
| 1718 |
+
yield self, [f.name for f in dirs_files[True]], [f.name for f in dirs_files[False]]
|
| 1719 |
+
|
| 1720 |
+
for child_dir in dirs_files[True]:
|
| 1721 |
+
yield from child_dir.walk()
|
TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib/enums.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from enum import Enum
|
| 2 |
+
import os
|
| 3 |
+
from typing import Optional
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class FileCacheMode(str, Enum):
|
| 7 |
+
"""Enumeration of the modes available for for the cloudpathlib file cache.
|
| 8 |
+
|
| 9 |
+
Attributes:
|
| 10 |
+
persistent (str): Cache is not removed by `cloudpathlib`.
|
| 11 |
+
tmp_dir (str): Cache is stored in a
|
| 12 |
+
[`TemporaryDirectory`](https://docs.python.org/3/library/tempfile.html#tempfile.TemporaryDirectory)
|
| 13 |
+
which is removed when the Client object is garbage collected (or by the OS at some point if not).
|
| 14 |
+
cloudpath_object (str): Cache for a `CloudPath` object is removed when `__del__` for that object is
|
| 15 |
+
called by Python garbage collection.
|
| 16 |
+
close_file (str): Cache for a `CloudPath` file is removed as soon as the file is closed. Note: you must
|
| 17 |
+
use `CloudPath.open` whenever opening the file for this method to function.
|
| 18 |
+
|
| 19 |
+
Modes can be set by passing them to the Client or by setting the `CLOUDPATHLIB_FILE_CACHE_MODE`
|
| 20 |
+
environment variable.
|
| 21 |
+
|
| 22 |
+
For more detail, see the [caching documentation page](../../caching).
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
persistent = "persistent" # cache stays as long as dir on OS does
|
| 26 |
+
tmp_dir = "tmp_dir" # DEFAULT: handled by deleting client, Python, or OS (usually on machine restart)
|
| 27 |
+
cloudpath_object = "cloudpath_object" # __del__ called on the CloudPath object
|
| 28 |
+
close_file = "close_file" # cache is cleared when file is closed
|
| 29 |
+
|
| 30 |
+
@classmethod
|
| 31 |
+
def from_environment(cls) -> Optional["FileCacheMode"]:
|
| 32 |
+
"""Parses the environment variable `CLOUDPATHLIB_FILE_CACHE_MODE` into
|
| 33 |
+
an instance of this Enum.
|
| 34 |
+
|
| 35 |
+
Returns:
|
| 36 |
+
FileCacheMode enum value if the env var is defined, else None.
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
env_string = os.environ.get("CLOUDPATHLIB_FILE_CACHE_MODE", "").lower()
|
| 40 |
+
|
| 41 |
+
if not env_string:
|
| 42 |
+
return None
|
| 43 |
+
else:
|
| 44 |
+
return cls(env_string)
|
TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib/exceptions.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""This module contains all custom exceptions in the `cloudpathlib` library. All exceptions
|
| 2 |
+
subclass the [`CloudPathException` base exception][cloudpathlib.exceptions.CloudPathException] to
|
| 3 |
+
facilitate catching any exception from this library.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class CloudPathException(Exception):
|
| 8 |
+
"""Base exception for all cloudpathlib custom exceptions."""
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class AnyPathTypeError(CloudPathException, TypeError):
|
| 12 |
+
pass
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class ClientMismatchError(CloudPathException, ValueError):
|
| 16 |
+
pass
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class CloudPathFileExistsError(CloudPathException, FileExistsError):
|
| 20 |
+
pass
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class CloudPathNotExistsError(CloudPathException):
|
| 24 |
+
pass
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class CloudPathFileNotFoundError(CloudPathException, FileNotFoundError):
|
| 28 |
+
pass
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class CloudPathIsADirectoryError(CloudPathException, IsADirectoryError):
|
| 32 |
+
pass
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class CloudPathNotADirectoryError(CloudPathException, NotADirectoryError):
|
| 36 |
+
pass
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class CloudPathNotImplementedError(CloudPathException, NotImplementedError):
|
| 40 |
+
pass
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class DirectoryNotEmptyError(CloudPathException):
|
| 44 |
+
pass
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class IncompleteImplementationError(CloudPathException, NotImplementedError):
|
| 48 |
+
pass
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class InvalidPrefixError(CloudPathException, ValueError):
|
| 52 |
+
pass
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class InvalidConfigurationException(CloudPathException, ValueError):
|
| 56 |
+
pass
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class MissingCredentialsError(CloudPathException):
|
| 60 |
+
pass
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class MissingDependenciesError(CloudPathException, ModuleNotFoundError):
|
| 64 |
+
pass
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class NoStatError(CloudPathException):
|
| 68 |
+
"""Used if stats cannot be retrieved; e.g., file does not exist
|
| 69 |
+
or for some backends path is a directory (which doesn't have
|
| 70 |
+
stats available).
|
| 71 |
+
"""
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class OverwriteDirtyFileError(CloudPathException):
|
| 75 |
+
pass
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class OverwriteNewerCloudError(CloudPathException):
|
| 79 |
+
pass
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class OverwriteNewerLocalError(CloudPathException):
|
| 83 |
+
pass
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
class InvalidGlobArgumentsError(CloudPathException):
|
| 87 |
+
pass
|
TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib/patches.py
ADDED
|
@@ -0,0 +1,388 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import builtins
|
| 2 |
+
import glob
|
| 3 |
+
import os
|
| 4 |
+
import os.path
|
| 5 |
+
|
| 6 |
+
from cloudpathlib.exceptions import InvalidGlobArgumentsError
|
| 7 |
+
|
| 8 |
+
from .cloudpath import CloudPath
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def _check_first_arg(*args, **kwargs):
|
| 12 |
+
return isinstance(args[0], CloudPath)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def _check_first_arg_first_index(*args, **kwargs):
|
| 16 |
+
return isinstance(args[0][0], CloudPath)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def _check_first_arg_or_root_dir(*args, **kwargs):
|
| 20 |
+
return isinstance(args[0], CloudPath) or isinstance(kwargs.get("root_dir", None), CloudPath)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _patch_factory(original_version, cpl_version, cpl_check=_check_first_arg):
|
| 24 |
+
_original = original_version
|
| 25 |
+
|
| 26 |
+
def _patched_version(*args, **kwargs):
|
| 27 |
+
if cpl_check(*args, **kwargs):
|
| 28 |
+
return cpl_version(*args, **kwargs)
|
| 29 |
+
else:
|
| 30 |
+
return _original(*args, **kwargs)
|
| 31 |
+
|
| 32 |
+
original_version = _patched_version
|
| 33 |
+
return _patched_version
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class _OpenPatch:
|
| 37 |
+
def __init__(self, original_open=None):
|
| 38 |
+
if original_open is None:
|
| 39 |
+
original_open = builtins.open
|
| 40 |
+
|
| 41 |
+
self._orig_open = original_open
|
| 42 |
+
self._orig_fspath = CloudPath.__fspath__
|
| 43 |
+
self.patched = _patch_factory(
|
| 44 |
+
original_open,
|
| 45 |
+
CloudPath.open,
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
# patch immediately so a plain call works
|
| 49 |
+
builtins.open = self.patched
|
| 50 |
+
CloudPath.__fspath__ = lambda x: x
|
| 51 |
+
|
| 52 |
+
def __enter__(self):
|
| 53 |
+
return builtins.open
|
| 54 |
+
|
| 55 |
+
def __exit__(self, exc_type, exc_value, traceback):
|
| 56 |
+
builtins.open = self._orig_open
|
| 57 |
+
CloudPath.__fspath__ = self._orig_fspath
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def patch_open(original_open=None):
|
| 61 |
+
return _OpenPatch(original_open)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _cloudpath_fspath(path):
|
| 65 |
+
return path # no op, since methods should all handle cloudpaths when patched
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def _cloudpath_os_listdir(path="."):
|
| 69 |
+
return list(path.iterdir())
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def _cloudpath_lstat(path, *, dir_fd=None):
|
| 73 |
+
return path.stat()
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def _cloudpath_mkdir(path, *, dir_fd=None):
|
| 77 |
+
return path.mkdir()
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def _cloudpath_os_makedirs(name, mode=0o777, exist_ok=False):
|
| 81 |
+
return CloudPath.mkdir(name, parents=True, exist_ok=exist_ok)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def _cloudpath_os_remove(path, *, dir_fd=None):
|
| 85 |
+
return path.unlink(missing_ok=False) # os.remove raises if missing
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def _cloudpath_os_removedirs(name):
|
| 89 |
+
for d in name.parents:
|
| 90 |
+
d.rmdir()
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def _cloudpath_os_rename(src, dst, *, src_dir_fd=None, dst_dir_fd=None):
|
| 94 |
+
return src.rename(dst)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def _cloudpath_os_renames(old, new):
|
| 98 |
+
old.rename(new) # move file
|
| 99 |
+
_cloudpath_os_removedirs(old) # remove previous directories if empty
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def _cloudpath_os_replace(src, dst, *, src_dir_fd=None, dst_dir_fd=None):
|
| 103 |
+
return src.rename(dst)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def _cloudpath_os_rmdir(path, *, dir_fd=None):
|
| 107 |
+
return path.rmdir()
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def _cloudpath_os_scandir(path="."):
|
| 111 |
+
return path.iterdir()
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def _cloudpath_os_stat(path, *, dir_fd=None, follow_symlinks=True):
|
| 115 |
+
return path.stat()
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def _cloudpath_os_unlink(path, *, dir_fd=None):
|
| 119 |
+
return path.unlink()
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def _cloudpath_os_walk(top, topdown=True, onerror=None, followlinks=False):
|
| 123 |
+
# pathlib.Path.walk returns dirs and files as string, not Path objects
|
| 124 |
+
# we follow the same convention, but since these could get used downstream,
|
| 125 |
+
# this method may need to be changed to return absolute CloudPath objects
|
| 126 |
+
# if it becomes a compatibility problem with major downstream libraries
|
| 127 |
+
yield from top.walk(top_down=topdown, on_error=onerror, follow_symlinks=followlinks)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def _cloudpath_os_path_basename(path):
|
| 131 |
+
return path.name
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def __common(parts):
|
| 135 |
+
i = 0
|
| 136 |
+
|
| 137 |
+
try:
|
| 138 |
+
while all(item[i] == parts[0][i] for item in parts[1:]):
|
| 139 |
+
i += 1
|
| 140 |
+
except IndexError:
|
| 141 |
+
pass
|
| 142 |
+
|
| 143 |
+
return parts[0][:i]
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def _cloudpath_os_path_commonpath(paths):
|
| 147 |
+
common = __common([p.parts for p in paths])
|
| 148 |
+
return paths[0].client.CloudPath(*common)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def _cloudpath_os_path_commonprefix(list):
|
| 152 |
+
common = __common([str(p) for p in list])
|
| 153 |
+
return common
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def _cloudpath_os_path_dirname(path):
|
| 157 |
+
return path.parent
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def _cloudpath_os_path_getatime(path):
|
| 161 |
+
return (path.stat().st_atime,)
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def _cloudpath_os_path_getmtime(path):
|
| 165 |
+
return (path.stat().st_mtime,)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def _cloudpath_os_path_getctime(path):
|
| 169 |
+
return (path.stat().st_ctime,)
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def _cloudpath_os_path_getsize(path):
|
| 173 |
+
return (path.stat().st_size,)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def _cloudpath_os_path_join(path, *paths):
|
| 177 |
+
for p in paths:
|
| 178 |
+
path /= p
|
| 179 |
+
return path
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def _cloudpath_os_path_split(path):
|
| 183 |
+
return path.parent, path.name
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def _cloudpath_os_path_splitext(path):
|
| 187 |
+
return str(path)[: -len(path.suffix)], path.suffix
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
class _OSPatch:
|
| 191 |
+
def __init__(self):
|
| 192 |
+
os_level = [
|
| 193 |
+
("fspath", os.fspath, _cloudpath_fspath),
|
| 194 |
+
("listdir", os.listdir, _cloudpath_os_listdir),
|
| 195 |
+
("lstat", os.lstat, _cloudpath_lstat),
|
| 196 |
+
("mkdir", os.mkdir, _cloudpath_mkdir),
|
| 197 |
+
("makedirs", os.makedirs, _cloudpath_os_makedirs),
|
| 198 |
+
("remove", os.remove, _cloudpath_os_remove),
|
| 199 |
+
("removedirs", os.removedirs, _cloudpath_os_removedirs),
|
| 200 |
+
("rename", os.rename, _cloudpath_os_rename),
|
| 201 |
+
("renames", os.renames, _cloudpath_os_renames),
|
| 202 |
+
("replace", os.replace, _cloudpath_os_replace),
|
| 203 |
+
("rmdir", os.rmdir, _cloudpath_os_rmdir),
|
| 204 |
+
("scandir", os.scandir, _cloudpath_os_scandir),
|
| 205 |
+
("stat", os.stat, _cloudpath_os_stat),
|
| 206 |
+
("unlink", os.unlink, _cloudpath_os_unlink),
|
| 207 |
+
("walk", os.walk, _cloudpath_os_walk),
|
| 208 |
+
]
|
| 209 |
+
|
| 210 |
+
self.os_originals = {}
|
| 211 |
+
|
| 212 |
+
for name, original, cloud in os_level:
|
| 213 |
+
self.os_originals[name] = original
|
| 214 |
+
patched = _patch_factory(original, cloud)
|
| 215 |
+
setattr(os, name, patched)
|
| 216 |
+
|
| 217 |
+
os_path_level = [
|
| 218 |
+
("basename", os.path.basename, _cloudpath_os_path_basename, _check_first_arg),
|
| 219 |
+
(
|
| 220 |
+
"commonpath",
|
| 221 |
+
os.path.commonpath,
|
| 222 |
+
_cloudpath_os_path_commonpath,
|
| 223 |
+
_check_first_arg_first_index,
|
| 224 |
+
),
|
| 225 |
+
(
|
| 226 |
+
"commonprefix",
|
| 227 |
+
os.path.commonprefix,
|
| 228 |
+
_cloudpath_os_path_commonprefix,
|
| 229 |
+
_check_first_arg_first_index,
|
| 230 |
+
),
|
| 231 |
+
("dirname", os.path.dirname, _cloudpath_os_path_dirname, _check_first_arg),
|
| 232 |
+
("exists", os.path.exists, CloudPath.exists, _check_first_arg),
|
| 233 |
+
("getatime", os.path.getatime, _cloudpath_os_path_getatime, _check_first_arg),
|
| 234 |
+
("getmtime", os.path.getmtime, _cloudpath_os_path_getmtime, _check_first_arg),
|
| 235 |
+
("getctime", os.path.getctime, _cloudpath_os_path_getctime, _check_first_arg),
|
| 236 |
+
("getsize", os.path.getsize, _cloudpath_os_path_getsize, _check_first_arg),
|
| 237 |
+
("isfile", os.path.isfile, CloudPath.is_file, _check_first_arg),
|
| 238 |
+
("isdir", os.path.isdir, CloudPath.is_dir, _check_first_arg),
|
| 239 |
+
("join", os.path.join, _cloudpath_os_path_join, _check_first_arg),
|
| 240 |
+
("split", os.path.split, _cloudpath_os_path_split, _check_first_arg),
|
| 241 |
+
("splitext", os.path.splitext, _cloudpath_os_path_splitext, _check_first_arg),
|
| 242 |
+
]
|
| 243 |
+
|
| 244 |
+
self.os_path_originals = {}
|
| 245 |
+
|
| 246 |
+
for name, original, cloud, check in os_path_level:
|
| 247 |
+
self.os_path_originals[name] = original
|
| 248 |
+
patched = _patch_factory(original, cloud, cpl_check=check)
|
| 249 |
+
setattr(os.path, name, patched)
|
| 250 |
+
|
| 251 |
+
def __enter__(self):
|
| 252 |
+
return
|
| 253 |
+
|
| 254 |
+
def __exit__(self, exc_type, exc_value, traceback):
|
| 255 |
+
for name, original in self.os_originals.items():
|
| 256 |
+
setattr(os, name, original)
|
| 257 |
+
|
| 258 |
+
for name, original in self.os_path_originals.items():
|
| 259 |
+
setattr(os.path, name, original)
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def patch_os_functions():
|
| 263 |
+
return _OSPatch()
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
def _get_root_dir_pattern_from_pathname(pathname):
|
| 267 |
+
# get first wildcard
|
| 268 |
+
for i, part in enumerate(pathname.parts):
|
| 269 |
+
if "*" in part or "?" in part or "[" in part:
|
| 270 |
+
root_parts = pathname.parts[:i]
|
| 271 |
+
pattern_parts = pathname.parts[i:]
|
| 272 |
+
break
|
| 273 |
+
else:
|
| 274 |
+
# No wildcards found, treat the entire path as root_dir with empty pattern
|
| 275 |
+
root_parts = pathname.parts
|
| 276 |
+
pattern_parts = []
|
| 277 |
+
|
| 278 |
+
root_dir = pathname._new_cloudpath(*root_parts)
|
| 279 |
+
|
| 280 |
+
# Handle empty pattern case - use "*" to match all files in directory
|
| 281 |
+
if not pattern_parts:
|
| 282 |
+
pattern = "*"
|
| 283 |
+
else:
|
| 284 |
+
pattern = "/".join(pattern_parts)
|
| 285 |
+
|
| 286 |
+
return root_dir, pattern
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
def _cloudpath_glob_iglob(
|
| 290 |
+
pathname, *, root_dir=None, dir_fd=None, recursive=False, include_hidden=False
|
| 291 |
+
):
|
| 292 |
+
# if both are cloudpath, root_dir and pathname must share a parent, otherwise we don't know
|
| 293 |
+
# where to start the pattern
|
| 294 |
+
if isinstance(pathname, CloudPath) and isinstance(root_dir, CloudPath):
|
| 295 |
+
if not pathname.is_relative_to(root_dir):
|
| 296 |
+
raise InvalidGlobArgumentsError(
|
| 297 |
+
f"If both are CloudPaths, root_dir ({root_dir}) must be a parent of pathname ({pathname})."
|
| 298 |
+
)
|
| 299 |
+
|
| 300 |
+
else:
|
| 301 |
+
pattern = pathname.relative_to(root_dir)
|
| 302 |
+
|
| 303 |
+
elif isinstance(pathname, CloudPath):
|
| 304 |
+
if root_dir is not None:
|
| 305 |
+
raise InvalidGlobArgumentsError(
|
| 306 |
+
"If pathname is a CloudPath, root_dir must also be a CloudPath or None."
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
root_dir, pattern = _get_root_dir_pattern_from_pathname(pathname)
|
| 310 |
+
|
| 311 |
+
elif isinstance(root_dir, CloudPath):
|
| 312 |
+
pattern = pathname
|
| 313 |
+
|
| 314 |
+
else:
|
| 315 |
+
raise InvalidGlobArgumentsError(
|
| 316 |
+
"At least one of pathname or root_dir must be a CloudPath."
|
| 317 |
+
)
|
| 318 |
+
|
| 319 |
+
# CloudPath automatically detects recursive patterns from ** or / in the pattern
|
| 320 |
+
# No need to pass recursive parameter
|
| 321 |
+
return root_dir.glob(pattern)
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
def _cloudpath_glob_glob(
|
| 325 |
+
pathname, *, root_dir=None, dir_fd=None, recursive=False, include_hidden=False
|
| 326 |
+
):
|
| 327 |
+
return list(
|
| 328 |
+
_cloudpath_glob_iglob(
|
| 329 |
+
pathname,
|
| 330 |
+
root_dir=root_dir,
|
| 331 |
+
dir_fd=dir_fd,
|
| 332 |
+
recursive=recursive,
|
| 333 |
+
include_hidden=include_hidden,
|
| 334 |
+
)
|
| 335 |
+
)
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
class _GlobPatch:
|
| 339 |
+
def __init__(self):
|
| 340 |
+
self.original_glob = glob.glob
|
| 341 |
+
self.original_iglob = glob.iglob
|
| 342 |
+
|
| 343 |
+
self.patched_glob = _patch_factory(
|
| 344 |
+
self.original_glob,
|
| 345 |
+
_cloudpath_glob_glob,
|
| 346 |
+
cpl_check=_check_first_arg_or_root_dir,
|
| 347 |
+
)
|
| 348 |
+
|
| 349 |
+
self.patched_iglob = _patch_factory(
|
| 350 |
+
self.original_iglob,
|
| 351 |
+
_cloudpath_glob_iglob,
|
| 352 |
+
cpl_check=_check_first_arg_or_root_dir,
|
| 353 |
+
)
|
| 354 |
+
|
| 355 |
+
def __enter__(self):
|
| 356 |
+
glob.glob = self.patched_glob
|
| 357 |
+
glob.iglob = self.patched_iglob
|
| 358 |
+
return
|
| 359 |
+
|
| 360 |
+
def __exit__(self, exc_type, exc_value, traceback):
|
| 361 |
+
glob.glob = self.original_glob
|
| 362 |
+
glob.iglob = self.original_iglob
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
def patch_glob():
|
| 366 |
+
return _GlobPatch()
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
class _PatchAllBuiltins:
|
| 370 |
+
def __init__(self):
|
| 371 |
+
self.patch_open = patch_open()
|
| 372 |
+
self.patch_os_functions = patch_os_functions()
|
| 373 |
+
self.patch_glob = patch_glob()
|
| 374 |
+
|
| 375 |
+
def __enter__(self):
|
| 376 |
+
self.patch_open.__enter__()
|
| 377 |
+
self.patch_os_functions.__enter__()
|
| 378 |
+
self.patch_glob.__enter__()
|
| 379 |
+
return
|
| 380 |
+
|
| 381 |
+
def __exit__(self, exc_type, exc_value, traceback):
|
| 382 |
+
self.patch_open.__exit__(exc_type, exc_value, traceback)
|
| 383 |
+
self.patch_os_functions.__exit__(exc_type, exc_value, traceback)
|
| 384 |
+
self.patch_glob.__exit__(exc_type, exc_value, traceback)
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
def patch_all_builtins():
|
| 388 |
+
return _PatchAllBuiltins()
|
TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib/py.typed
ADDED
|
File without changes
|
TTS/Kokoro/.venv/Lib/site-packages/cloudpathlib/url_utils.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import PureWindowsPath, Path
|
| 2 |
+
from urllib.request import url2pathname
|
| 3 |
+
from urllib.parse import urlparse, unquote
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def path_from_fileurl(urlstr, **kwargs):
|
| 7 |
+
"""
|
| 8 |
+
Take a file:// url and return a Path.
|
| 9 |
+
|
| 10 |
+
Adapted from:
|
| 11 |
+
https://github.com/AcademySoftwareFoundation/OpenTimelineIO/blob/4c17494dee2e515aedc8623741556fae3e4afe72/src/py-opentimelineio/opentimelineio/url_utils.py#L43-L72
|
| 12 |
+
"""
|
| 13 |
+
# explicitly unquote first in case drive colon is url encoded
|
| 14 |
+
unquoted = unquote(urlstr)
|
| 15 |
+
|
| 16 |
+
# Parse provided URL
|
| 17 |
+
parsed_result = urlparse(unquoted)
|
| 18 |
+
|
| 19 |
+
# Convert the parsed URL to a path
|
| 20 |
+
filepath = Path(url2pathname(parsed_result.path), **kwargs)
|
| 21 |
+
|
| 22 |
+
# If the network location is a window drive, reassemble the path
|
| 23 |
+
if PureWindowsPath(parsed_result.netloc).drive:
|
| 24 |
+
filepath = Path(parsed_result.netloc + parsed_result.path, **kwargs)
|
| 25 |
+
|
| 26 |
+
# Otherwise check if the specified index is a windows drive, then offset the path
|
| 27 |
+
elif len(filepath.parts) > 1 and PureWindowsPath(filepath.parts[1]).drive:
|
| 28 |
+
# Remove leading "/" if/when `request.url2pathname` yields "/S:/path/file.ext"
|
| 29 |
+
filepath = Path(*filepath.parts[1:], **kwargs)
|
| 30 |
+
|
| 31 |
+
return filepath
|
TTS/Kokoro/.venv/Lib/site-packages/colorama-0.4.6.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
pip
|
TTS/Kokoro/.venv/Lib/site-packages/colorama-0.4.6.dist-info/METADATA
ADDED
|
@@ -0,0 +1,441 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.1
|
| 2 |
+
Name: colorama
|
| 3 |
+
Version: 0.4.6
|
| 4 |
+
Summary: Cross-platform colored terminal text.
|
| 5 |
+
Project-URL: Homepage, https://github.com/tartley/colorama
|
| 6 |
+
Author-email: Jonathan Hartley <tartley@tartley.com>
|
| 7 |
+
License-File: LICENSE.txt
|
| 8 |
+
Keywords: ansi,color,colour,crossplatform,terminal,text,windows,xplatform
|
| 9 |
+
Classifier: Development Status :: 5 - Production/Stable
|
| 10 |
+
Classifier: Environment :: Console
|
| 11 |
+
Classifier: Intended Audience :: Developers
|
| 12 |
+
Classifier: License :: OSI Approved :: BSD License
|
| 13 |
+
Classifier: Operating System :: OS Independent
|
| 14 |
+
Classifier: Programming Language :: Python
|
| 15 |
+
Classifier: Programming Language :: Python :: 2
|
| 16 |
+
Classifier: Programming Language :: Python :: 2.7
|
| 17 |
+
Classifier: Programming Language :: Python :: 3
|
| 18 |
+
Classifier: Programming Language :: Python :: 3.7
|
| 19 |
+
Classifier: Programming Language :: Python :: 3.8
|
| 20 |
+
Classifier: Programming Language :: Python :: 3.9
|
| 21 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 22 |
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
| 23 |
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
| 24 |
+
Classifier: Topic :: Terminals
|
| 25 |
+
Requires-Python: !=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,>=2.7
|
| 26 |
+
Description-Content-Type: text/x-rst
|
| 27 |
+
|
| 28 |
+
.. image:: https://img.shields.io/pypi/v/colorama.svg
|
| 29 |
+
:target: https://pypi.org/project/colorama/
|
| 30 |
+
:alt: Latest Version
|
| 31 |
+
|
| 32 |
+
.. image:: https://img.shields.io/pypi/pyversions/colorama.svg
|
| 33 |
+
:target: https://pypi.org/project/colorama/
|
| 34 |
+
:alt: Supported Python versions
|
| 35 |
+
|
| 36 |
+
.. image:: https://github.com/tartley/colorama/actions/workflows/test.yml/badge.svg
|
| 37 |
+
:target: https://github.com/tartley/colorama/actions/workflows/test.yml
|
| 38 |
+
:alt: Build Status
|
| 39 |
+
|
| 40 |
+
Colorama
|
| 41 |
+
========
|
| 42 |
+
|
| 43 |
+
Makes ANSI escape character sequences (for producing colored terminal text and
|
| 44 |
+
cursor positioning) work under MS Windows.
|
| 45 |
+
|
| 46 |
+
.. |donate| image:: https://www.paypalobjects.com/en_US/i/btn/btn_donate_SM.gif
|
| 47 |
+
:target: https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=2MZ9D2GMLYCUJ&item_name=Colorama¤cy_code=USD
|
| 48 |
+
:alt: Donate with Paypal
|
| 49 |
+
|
| 50 |
+
`PyPI for releases <https://pypi.org/project/colorama/>`_ |
|
| 51 |
+
`Github for source <https://github.com/tartley/colorama>`_ |
|
| 52 |
+
`Colorama for enterprise on Tidelift <https://github.com/tartley/colorama/blob/master/ENTERPRISE.md>`_
|
| 53 |
+
|
| 54 |
+
If you find Colorama useful, please |donate| to the authors. Thank you!
|
| 55 |
+
|
| 56 |
+
Installation
|
| 57 |
+
------------
|
| 58 |
+
|
| 59 |
+
Tested on CPython 2.7, 3.7, 3.8, 3.9 and 3.10 and Pypy 2.7 and 3.8.
|
| 60 |
+
|
| 61 |
+
No requirements other than the standard library.
|
| 62 |
+
|
| 63 |
+
.. code-block:: bash
|
| 64 |
+
|
| 65 |
+
pip install colorama
|
| 66 |
+
# or
|
| 67 |
+
conda install -c anaconda colorama
|
| 68 |
+
|
| 69 |
+
Description
|
| 70 |
+
-----------
|
| 71 |
+
|
| 72 |
+
ANSI escape character sequences have long been used to produce colored terminal
|
| 73 |
+
text and cursor positioning on Unix and Macs. Colorama makes this work on
|
| 74 |
+
Windows, too, by wrapping ``stdout``, stripping ANSI sequences it finds (which
|
| 75 |
+
would appear as gobbledygook in the output), and converting them into the
|
| 76 |
+
appropriate win32 calls to modify the state of the terminal. On other platforms,
|
| 77 |
+
Colorama does nothing.
|
| 78 |
+
|
| 79 |
+
This has the upshot of providing a simple cross-platform API for printing
|
| 80 |
+
colored terminal text from Python, and has the happy side-effect that existing
|
| 81 |
+
applications or libraries which use ANSI sequences to produce colored output on
|
| 82 |
+
Linux or Macs can now also work on Windows, simply by calling
|
| 83 |
+
``colorama.just_fix_windows_console()`` (since v0.4.6) or ``colorama.init()``
|
| 84 |
+
(all versions, but may have other side-effects – see below).
|
| 85 |
+
|
| 86 |
+
An alternative approach is to install ``ansi.sys`` on Windows machines, which
|
| 87 |
+
provides the same behaviour for all applications running in terminals. Colorama
|
| 88 |
+
is intended for situations where that isn't easy (e.g., maybe your app doesn't
|
| 89 |
+
have an installer.)
|
| 90 |
+
|
| 91 |
+
Demo scripts in the source code repository print some colored text using
|
| 92 |
+
ANSI sequences. Compare their output under Gnome-terminal's built in ANSI
|
| 93 |
+
handling, versus on Windows Command-Prompt using Colorama:
|
| 94 |
+
|
| 95 |
+
.. image:: https://github.com/tartley/colorama/raw/master/screenshots/ubuntu-demo.png
|
| 96 |
+
:width: 661
|
| 97 |
+
:height: 357
|
| 98 |
+
:alt: ANSI sequences on Ubuntu under gnome-terminal.
|
| 99 |
+
|
| 100 |
+
.. image:: https://github.com/tartley/colorama/raw/master/screenshots/windows-demo.png
|
| 101 |
+
:width: 668
|
| 102 |
+
:height: 325
|
| 103 |
+
:alt: Same ANSI sequences on Windows, using Colorama.
|
| 104 |
+
|
| 105 |
+
These screenshots show that, on Windows, Colorama does not support ANSI 'dim
|
| 106 |
+
text'; it looks the same as 'normal text'.
|
| 107 |
+
|
| 108 |
+
Usage
|
| 109 |
+
-----
|
| 110 |
+
|
| 111 |
+
Initialisation
|
| 112 |
+
..............
|
| 113 |
+
|
| 114 |
+
If the only thing you want from Colorama is to get ANSI escapes to work on
|
| 115 |
+
Windows, then run:
|
| 116 |
+
|
| 117 |
+
.. code-block:: python
|
| 118 |
+
|
| 119 |
+
from colorama import just_fix_windows_console
|
| 120 |
+
just_fix_windows_console()
|
| 121 |
+
|
| 122 |
+
If you're on a recent version of Windows 10 or better, and your stdout/stderr
|
| 123 |
+
are pointing to a Windows console, then this will flip the magic configuration
|
| 124 |
+
switch to enable Windows' built-in ANSI support.
|
| 125 |
+
|
| 126 |
+
If you're on an older version of Windows, and your stdout/stderr are pointing to
|
| 127 |
+
a Windows console, then this will wrap ``sys.stdout`` and/or ``sys.stderr`` in a
|
| 128 |
+
magic file object that intercepts ANSI escape sequences and issues the
|
| 129 |
+
appropriate Win32 calls to emulate them.
|
| 130 |
+
|
| 131 |
+
In all other circumstances, it does nothing whatsoever. Basically the idea is
|
| 132 |
+
that this makes Windows act like Unix with respect to ANSI escape handling.
|
| 133 |
+
|
| 134 |
+
It's safe to call this function multiple times. It's safe to call this function
|
| 135 |
+
on non-Windows platforms, but it won't do anything. It's safe to call this
|
| 136 |
+
function when one or both of your stdout/stderr are redirected to a file – it
|
| 137 |
+
won't do anything to those streams.
|
| 138 |
+
|
| 139 |
+
Alternatively, you can use the older interface with more features (but also more
|
| 140 |
+
potential footguns):
|
| 141 |
+
|
| 142 |
+
.. code-block:: python
|
| 143 |
+
|
| 144 |
+
from colorama import init
|
| 145 |
+
init()
|
| 146 |
+
|
| 147 |
+
This does the same thing as ``just_fix_windows_console``, except for the
|
| 148 |
+
following differences:
|
| 149 |
+
|
| 150 |
+
- It's not safe to call ``init`` multiple times; you can end up with multiple
|
| 151 |
+
layers of wrapping and broken ANSI support.
|
| 152 |
+
|
| 153 |
+
- Colorama will apply a heuristic to guess whether stdout/stderr support ANSI,
|
| 154 |
+
and if it thinks they don't, then it will wrap ``sys.stdout`` and
|
| 155 |
+
``sys.stderr`` in a magic file object that strips out ANSI escape sequences
|
| 156 |
+
before printing them. This happens on all platforms, and can be convenient if
|
| 157 |
+
you want to write your code to emit ANSI escape sequences unconditionally, and
|
| 158 |
+
let Colorama decide whether they should actually be output. But note that
|
| 159 |
+
Colorama's heuristic is not particularly clever.
|
| 160 |
+
|
| 161 |
+
- ``init`` also accepts explicit keyword args to enable/disable various
|
| 162 |
+
functionality – see below.
|
| 163 |
+
|
| 164 |
+
To stop using Colorama before your program exits, simply call ``deinit()``.
|
| 165 |
+
This will restore ``stdout`` and ``stderr`` to their original values, so that
|
| 166 |
+
Colorama is disabled. To resume using Colorama again, call ``reinit()``; it is
|
| 167 |
+
cheaper than calling ``init()`` again (but does the same thing).
|
| 168 |
+
|
| 169 |
+
Most users should depend on ``colorama >= 0.4.6``, and use
|
| 170 |
+
``just_fix_windows_console``. The old ``init`` interface will be supported
|
| 171 |
+
indefinitely for backwards compatibility, but we don't plan to fix any issues
|
| 172 |
+
with it, also for backwards compatibility.
|
| 173 |
+
|
| 174 |
+
Colored Output
|
| 175 |
+
..............
|
| 176 |
+
|
| 177 |
+
Cross-platform printing of colored text can then be done using Colorama's
|
| 178 |
+
constant shorthand for ANSI escape sequences. These are deliberately
|
| 179 |
+
rudimentary, see below.
|
| 180 |
+
|
| 181 |
+
.. code-block:: python
|
| 182 |
+
|
| 183 |
+
from colorama import Fore, Back, Style
|
| 184 |
+
print(Fore.RED + 'some red text')
|
| 185 |
+
print(Back.GREEN + 'and with a green background')
|
| 186 |
+
print(Style.DIM + 'and in dim text')
|
| 187 |
+
print(Style.RESET_ALL)
|
| 188 |
+
print('back to normal now')
|
| 189 |
+
|
| 190 |
+
...or simply by manually printing ANSI sequences from your own code:
|
| 191 |
+
|
| 192 |
+
.. code-block:: python
|
| 193 |
+
|
| 194 |
+
print('\033[31m' + 'some red text')
|
| 195 |
+
print('\033[39m') # and reset to default color
|
| 196 |
+
|
| 197 |
+
...or, Colorama can be used in conjunction with existing ANSI libraries
|
| 198 |
+
such as the venerable `Termcolor <https://pypi.org/project/termcolor/>`_
|
| 199 |
+
the fabulous `Blessings <https://pypi.org/project/blessings/>`_,
|
| 200 |
+
or the incredible `_Rich <https://pypi.org/project/rich/>`_.
|
| 201 |
+
|
| 202 |
+
If you wish Colorama's Fore, Back and Style constants were more capable,
|
| 203 |
+
then consider using one of the above highly capable libraries to generate
|
| 204 |
+
colors, etc, and use Colorama just for its primary purpose: to convert
|
| 205 |
+
those ANSI sequences to also work on Windows:
|
| 206 |
+
|
| 207 |
+
SIMILARLY, do not send PRs adding the generation of new ANSI types to Colorama.
|
| 208 |
+
We are only interested in converting ANSI codes to win32 API calls, not
|
| 209 |
+
shortcuts like the above to generate ANSI characters.
|
| 210 |
+
|
| 211 |
+
.. code-block:: python
|
| 212 |
+
|
| 213 |
+
from colorama import just_fix_windows_console
|
| 214 |
+
from termcolor import colored
|
| 215 |
+
|
| 216 |
+
# use Colorama to make Termcolor work on Windows too
|
| 217 |
+
just_fix_windows_console()
|
| 218 |
+
|
| 219 |
+
# then use Termcolor for all colored text output
|
| 220 |
+
print(colored('Hello, World!', 'green', 'on_red'))
|
| 221 |
+
|
| 222 |
+
Available formatting constants are::
|
| 223 |
+
|
| 224 |
+
Fore: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET.
|
| 225 |
+
Back: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET.
|
| 226 |
+
Style: DIM, NORMAL, BRIGHT, RESET_ALL
|
| 227 |
+
|
| 228 |
+
``Style.RESET_ALL`` resets foreground, background, and brightness. Colorama will
|
| 229 |
+
perform this reset automatically on program exit.
|
| 230 |
+
|
| 231 |
+
These are fairly well supported, but not part of the standard::
|
| 232 |
+
|
| 233 |
+
Fore: LIGHTBLACK_EX, LIGHTRED_EX, LIGHTGREEN_EX, LIGHTYELLOW_EX, LIGHTBLUE_EX, LIGHTMAGENTA_EX, LIGHTCYAN_EX, LIGHTWHITE_EX
|
| 234 |
+
Back: LIGHTBLACK_EX, LIGHTRED_EX, LIGHTGREEN_EX, LIGHTYELLOW_EX, LIGHTBLUE_EX, LIGHTMAGENTA_EX, LIGHTCYAN_EX, LIGHTWHITE_EX
|
| 235 |
+
|
| 236 |
+
Cursor Positioning
|
| 237 |
+
..................
|
| 238 |
+
|
| 239 |
+
ANSI codes to reposition the cursor are supported. See ``demos/demo06.py`` for
|
| 240 |
+
an example of how to generate them.
|
| 241 |
+
|
| 242 |
+
Init Keyword Args
|
| 243 |
+
.................
|
| 244 |
+
|
| 245 |
+
``init()`` accepts some ``**kwargs`` to override default behaviour.
|
| 246 |
+
|
| 247 |
+
init(autoreset=False):
|
| 248 |
+
If you find yourself repeatedly sending reset sequences to turn off color
|
| 249 |
+
changes at the end of every print, then ``init(autoreset=True)`` will
|
| 250 |
+
automate that:
|
| 251 |
+
|
| 252 |
+
.. code-block:: python
|
| 253 |
+
|
| 254 |
+
from colorama import init
|
| 255 |
+
init(autoreset=True)
|
| 256 |
+
print(Fore.RED + 'some red text')
|
| 257 |
+
print('automatically back to default color again')
|
| 258 |
+
|
| 259 |
+
init(strip=None):
|
| 260 |
+
Pass ``True`` or ``False`` to override whether ANSI codes should be
|
| 261 |
+
stripped from the output. The default behaviour is to strip if on Windows
|
| 262 |
+
or if output is redirected (not a tty).
|
| 263 |
+
|
| 264 |
+
init(convert=None):
|
| 265 |
+
Pass ``True`` or ``False`` to override whether to convert ANSI codes in the
|
| 266 |
+
output into win32 calls. The default behaviour is to convert if on Windows
|
| 267 |
+
and output is to a tty (terminal).
|
| 268 |
+
|
| 269 |
+
init(wrap=True):
|
| 270 |
+
On Windows, Colorama works by replacing ``sys.stdout`` and ``sys.stderr``
|
| 271 |
+
with proxy objects, which override the ``.write()`` method to do their work.
|
| 272 |
+
If this wrapping causes you problems, then this can be disabled by passing
|
| 273 |
+
``init(wrap=False)``. The default behaviour is to wrap if ``autoreset`` or
|
| 274 |
+
``strip`` or ``convert`` are True.
|
| 275 |
+
|
| 276 |
+
When wrapping is disabled, colored printing on non-Windows platforms will
|
| 277 |
+
continue to work as normal. To do cross-platform colored output, you can
|
| 278 |
+
use Colorama's ``AnsiToWin32`` proxy directly:
|
| 279 |
+
|
| 280 |
+
.. code-block:: python
|
| 281 |
+
|
| 282 |
+
import sys
|
| 283 |
+
from colorama import init, AnsiToWin32
|
| 284 |
+
init(wrap=False)
|
| 285 |
+
stream = AnsiToWin32(sys.stderr).stream
|
| 286 |
+
|
| 287 |
+
# Python 2
|
| 288 |
+
print >>stream, Fore.BLUE + 'blue text on stderr'
|
| 289 |
+
|
| 290 |
+
# Python 3
|
| 291 |
+
print(Fore.BLUE + 'blue text on stderr', file=stream)
|
| 292 |
+
|
| 293 |
+
Recognised ANSI Sequences
|
| 294 |
+
.........................
|
| 295 |
+
|
| 296 |
+
ANSI sequences generally take the form::
|
| 297 |
+
|
| 298 |
+
ESC [ <param> ; <param> ... <command>
|
| 299 |
+
|
| 300 |
+
Where ``<param>`` is an integer, and ``<command>`` is a single letter. Zero or
|
| 301 |
+
more params are passed to a ``<command>``. If no params are passed, it is
|
| 302 |
+
generally synonymous with passing a single zero. No spaces exist in the
|
| 303 |
+
sequence; they have been inserted here simply to read more easily.
|
| 304 |
+
|
| 305 |
+
The only ANSI sequences that Colorama converts into win32 calls are::
|
| 306 |
+
|
| 307 |
+
ESC [ 0 m # reset all (colors and brightness)
|
| 308 |
+
ESC [ 1 m # bright
|
| 309 |
+
ESC [ 2 m # dim (looks same as normal brightness)
|
| 310 |
+
ESC [ 22 m # normal brightness
|
| 311 |
+
|
| 312 |
+
# FOREGROUND:
|
| 313 |
+
ESC [ 30 m # black
|
| 314 |
+
ESC [ 31 m # red
|
| 315 |
+
ESC [ 32 m # green
|
| 316 |
+
ESC [ 33 m # yellow
|
| 317 |
+
ESC [ 34 m # blue
|
| 318 |
+
ESC [ 35 m # magenta
|
| 319 |
+
ESC [ 36 m # cyan
|
| 320 |
+
ESC [ 37 m # white
|
| 321 |
+
ESC [ 39 m # reset
|
| 322 |
+
|
| 323 |
+
# BACKGROUND
|
| 324 |
+
ESC [ 40 m # black
|
| 325 |
+
ESC [ 41 m # red
|
| 326 |
+
ESC [ 42 m # green
|
| 327 |
+
ESC [ 43 m # yellow
|
| 328 |
+
ESC [ 44 m # blue
|
| 329 |
+
ESC [ 45 m # magenta
|
| 330 |
+
ESC [ 46 m # cyan
|
| 331 |
+
ESC [ 47 m # white
|
| 332 |
+
ESC [ 49 m # reset
|
| 333 |
+
|
| 334 |
+
# cursor positioning
|
| 335 |
+
ESC [ y;x H # position cursor at x across, y down
|
| 336 |
+
ESC [ y;x f # position cursor at x across, y down
|
| 337 |
+
ESC [ n A # move cursor n lines up
|
| 338 |
+
ESC [ n B # move cursor n lines down
|
| 339 |
+
ESC [ n C # move cursor n characters forward
|
| 340 |
+
ESC [ n D # move cursor n characters backward
|
| 341 |
+
|
| 342 |
+
# clear the screen
|
| 343 |
+
ESC [ mode J # clear the screen
|
| 344 |
+
|
| 345 |
+
# clear the line
|
| 346 |
+
ESC [ mode K # clear the line
|
| 347 |
+
|
| 348 |
+
Multiple numeric params to the ``'m'`` command can be combined into a single
|
| 349 |
+
sequence::
|
| 350 |
+
|
| 351 |
+
ESC [ 36 ; 45 ; 1 m # bright cyan text on magenta background
|
| 352 |
+
|
| 353 |
+
All other ANSI sequences of the form ``ESC [ <param> ; <param> ... <command>``
|
| 354 |
+
are silently stripped from the output on Windows.
|
| 355 |
+
|
| 356 |
+
Any other form of ANSI sequence, such as single-character codes or alternative
|
| 357 |
+
initial characters, are not recognised or stripped. It would be cool to add
|
| 358 |
+
them though. Let me know if it would be useful for you, via the Issues on
|
| 359 |
+
GitHub.
|
| 360 |
+
|
| 361 |
+
Status & Known Problems
|
| 362 |
+
-----------------------
|
| 363 |
+
|
| 364 |
+
I've personally only tested it on Windows XP (CMD, Console2), Ubuntu
|
| 365 |
+
(gnome-terminal, xterm), and OS X.
|
| 366 |
+
|
| 367 |
+
Some valid ANSI sequences aren't recognised.
|
| 368 |
+
|
| 369 |
+
If you're hacking on the code, see `README-hacking.md`_. ESPECIALLY, see the
|
| 370 |
+
explanation there of why we do not want PRs that allow Colorama to generate new
|
| 371 |
+
types of ANSI codes.
|
| 372 |
+
|
| 373 |
+
See outstanding issues and wish-list:
|
| 374 |
+
https://github.com/tartley/colorama/issues
|
| 375 |
+
|
| 376 |
+
If anything doesn't work for you, or doesn't do what you expected or hoped for,
|
| 377 |
+
I'd love to hear about it on that issues list, would be delighted by patches,
|
| 378 |
+
and would be happy to grant commit access to anyone who submits a working patch
|
| 379 |
+
or two.
|
| 380 |
+
|
| 381 |
+
.. _README-hacking.md: README-hacking.md
|
| 382 |
+
|
| 383 |
+
License
|
| 384 |
+
-------
|
| 385 |
+
|
| 386 |
+
Copyright Jonathan Hartley & Arnon Yaari, 2013-2020. BSD 3-Clause license; see
|
| 387 |
+
LICENSE file.
|
| 388 |
+
|
| 389 |
+
Professional support
|
| 390 |
+
--------------------
|
| 391 |
+
|
| 392 |
+
.. |tideliftlogo| image:: https://cdn2.hubspot.net/hubfs/4008838/website/logos/logos_for_download/Tidelift_primary-shorthand-logo.png
|
| 393 |
+
:alt: Tidelift
|
| 394 |
+
:target: https://tidelift.com/subscription/pkg/pypi-colorama?utm_source=pypi-colorama&utm_medium=referral&utm_campaign=readme
|
| 395 |
+
|
| 396 |
+
.. list-table::
|
| 397 |
+
:widths: 10 100
|
| 398 |
+
|
| 399 |
+
* - |tideliftlogo|
|
| 400 |
+
- Professional support for colorama is available as part of the
|
| 401 |
+
`Tidelift Subscription`_.
|
| 402 |
+
Tidelift gives software development teams a single source for purchasing
|
| 403 |
+
and maintaining their software, with professional grade assurances from
|
| 404 |
+
the experts who know it best, while seamlessly integrating with existing
|
| 405 |
+
tools.
|
| 406 |
+
|
| 407 |
+
.. _Tidelift Subscription: https://tidelift.com/subscription/pkg/pypi-colorama?utm_source=pypi-colorama&utm_medium=referral&utm_campaign=readme
|
| 408 |
+
|
| 409 |
+
Thanks
|
| 410 |
+
------
|
| 411 |
+
|
| 412 |
+
See the CHANGELOG for more thanks!
|
| 413 |
+
|
| 414 |
+
* Marc Schlaich (schlamar) for a ``setup.py`` fix for Python2.5.
|
| 415 |
+
* Marc Abramowitz, reported & fixed a crash on exit with closed ``stdout``,
|
| 416 |
+
providing a solution to issue #7's setuptools/distutils debate,
|
| 417 |
+
and other fixes.
|
| 418 |
+
* User 'eryksun', for guidance on correctly instantiating ``ctypes.windll``.
|
| 419 |
+
* Matthew McCormick for politely pointing out a longstanding crash on non-Win.
|
| 420 |
+
* Ben Hoyt, for a magnificent fix under 64-bit Windows.
|
| 421 |
+
* Jesse at Empty Square for submitting a fix for examples in the README.
|
| 422 |
+
* User 'jamessp', an observant documentation fix for cursor positioning.
|
| 423 |
+
* User 'vaal1239', Dave Mckee & Lackner Kristof for a tiny but much-needed Win7
|
| 424 |
+
fix.
|
| 425 |
+
* Julien Stuyck, for wisely suggesting Python3 compatible updates to README.
|
| 426 |
+
* Daniel Griffith for multiple fabulous patches.
|
| 427 |
+
* Oscar Lesta for a valuable fix to stop ANSI chars being sent to non-tty
|
| 428 |
+
output.
|
| 429 |
+
* Roger Binns, for many suggestions, valuable feedback, & bug reports.
|
| 430 |
+
* Tim Golden for thought and much appreciated feedback on the initial idea.
|
| 431 |
+
* User 'Zearin' for updates to the README file.
|
| 432 |
+
* John Szakmeister for adding support for light colors
|
| 433 |
+
* Charles Merriam for adding documentation to demos
|
| 434 |
+
* Jurko for a fix on 64-bit Windows CPython2.5 w/o ctypes
|
| 435 |
+
* Florian Bruhin for a fix when stdout or stderr are None
|
| 436 |
+
* Thomas Weininger for fixing ValueError on Windows
|
| 437 |
+
* Remi Rampin for better Github integration and fixes to the README file
|
| 438 |
+
* Simeon Visser for closing a file handle using 'with' and updating classifiers
|
| 439 |
+
to include Python 3.3 and 3.4
|
| 440 |
+
* Andy Neff for fixing RESET of LIGHT_EX colors.
|
| 441 |
+
* Jonathan Hartley for the initial idea and implementation.
|
TTS/Kokoro/.venv/Lib/site-packages/colorama-0.4.6.dist-info/RECORD
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
colorama-0.4.6.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
| 2 |
+
colorama-0.4.6.dist-info/METADATA,sha256=e67SnrUMOym9sz_4TjF3vxvAV4T3aF7NyqRHHH3YEMw,17158
|
| 3 |
+
colorama-0.4.6.dist-info/RECORD,,
|
| 4 |
+
colorama-0.4.6.dist-info/WHEEL,sha256=cdcF4Fbd0FPtw2EMIOwH-3rSOTUdTCeOSXRMD1iLUb8,105
|
| 5 |
+
colorama-0.4.6.dist-info/licenses/LICENSE.txt,sha256=ysNcAmhuXQSlpxQL-zs25zrtSWZW6JEQLkKIhteTAxg,1491
|
| 6 |
+
colorama/__init__.py,sha256=wePQA4U20tKgYARySLEC047ucNX-g8pRLpYBuiHlLb8,266
|
| 7 |
+
colorama/__pycache__/__init__.cpython-312.pyc,,
|
| 8 |
+
colorama/__pycache__/ansi.cpython-312.pyc,,
|
| 9 |
+
colorama/__pycache__/ansitowin32.cpython-312.pyc,,
|
| 10 |
+
colorama/__pycache__/initialise.cpython-312.pyc,,
|
| 11 |
+
colorama/__pycache__/win32.cpython-312.pyc,,
|
| 12 |
+
colorama/__pycache__/winterm.cpython-312.pyc,,
|
| 13 |
+
colorama/ansi.py,sha256=Top4EeEuaQdBWdteKMEcGOTeKeF19Q-Wo_6_Cj5kOzQ,2522
|
| 14 |
+
colorama/ansitowin32.py,sha256=vPNYa3OZbxjbuFyaVo0Tmhmy1FZ1lKMWCnT7odXpItk,11128
|
| 15 |
+
colorama/initialise.py,sha256=-hIny86ClXo39ixh5iSCfUIa2f_h_bgKRDW7gqs-KLU,3325
|
| 16 |
+
colorama/tests/__init__.py,sha256=MkgPAEzGQd-Rq0w0PZXSX2LadRWhUECcisJY8lSrm4Q,75
|
| 17 |
+
colorama/tests/__pycache__/__init__.cpython-312.pyc,,
|
| 18 |
+
colorama/tests/__pycache__/ansi_test.cpython-312.pyc,,
|
| 19 |
+
colorama/tests/__pycache__/ansitowin32_test.cpython-312.pyc,,
|
| 20 |
+
colorama/tests/__pycache__/initialise_test.cpython-312.pyc,,
|
| 21 |
+
colorama/tests/__pycache__/isatty_test.cpython-312.pyc,,
|
| 22 |
+
colorama/tests/__pycache__/utils.cpython-312.pyc,,
|
| 23 |
+
colorama/tests/__pycache__/winterm_test.cpython-312.pyc,,
|
| 24 |
+
colorama/tests/ansi_test.py,sha256=FeViDrUINIZcr505PAxvU4AjXz1asEiALs9GXMhwRaE,2839
|
| 25 |
+
colorama/tests/ansitowin32_test.py,sha256=RN7AIhMJ5EqDsYaCjVo-o4u8JzDD4ukJbmevWKS70rY,10678
|
| 26 |
+
colorama/tests/initialise_test.py,sha256=BbPy-XfyHwJ6zKozuQOvNvQZzsx9vdb_0bYXn7hsBTc,6741
|
| 27 |
+
colorama/tests/isatty_test.py,sha256=Pg26LRpv0yQDB5Ac-sxgVXG7hsA1NYvapFgApZfYzZg,1866
|
| 28 |
+
colorama/tests/utils.py,sha256=1IIRylG39z5-dzq09R_ngufxyPZxgldNbrxKxUGwGKE,1079
|
| 29 |
+
colorama/tests/winterm_test.py,sha256=qoWFPEjym5gm2RuMwpf3pOis3a5r_PJZFCzK254JL8A,3709
|
| 30 |
+
colorama/win32.py,sha256=YQOKwMTwtGBbsY4dL5HYTvwTeP9wIQra5MvPNddpxZs,6181
|
| 31 |
+
colorama/winterm.py,sha256=XCQFDHjPi6AHYNdZwy0tA02H-Jh48Jp-HvCjeLeLp3U,7134
|
TTS/Kokoro/.venv/Lib/site-packages/colorama-0.4.6.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: hatchling 1.11.1
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py2-none-any
|
| 5 |
+
Tag: py3-none-any
|
TTS/Kokoro/.venv/Lib/site-packages/colorama/__init__.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
|
| 2 |
+
from .initialise import init, deinit, reinit, colorama_text, just_fix_windows_console
|
| 3 |
+
from .ansi import Fore, Back, Style, Cursor
|
| 4 |
+
from .ansitowin32 import AnsiToWin32
|
| 5 |
+
|
| 6 |
+
__version__ = '0.4.6'
|
| 7 |
+
|
TTS/Kokoro/.venv/Lib/site-packages/colorama/ansi.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
|
| 2 |
+
'''
|
| 3 |
+
This module generates ANSI character codes to printing colors to terminals.
|
| 4 |
+
See: http://en.wikipedia.org/wiki/ANSI_escape_code
|
| 5 |
+
'''
|
| 6 |
+
|
| 7 |
+
CSI = '\033['
|
| 8 |
+
OSC = '\033]'
|
| 9 |
+
BEL = '\a'
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def code_to_chars(code):
|
| 13 |
+
return CSI + str(code) + 'm'
|
| 14 |
+
|
| 15 |
+
def set_title(title):
|
| 16 |
+
return OSC + '2;' + title + BEL
|
| 17 |
+
|
| 18 |
+
def clear_screen(mode=2):
|
| 19 |
+
return CSI + str(mode) + 'J'
|
| 20 |
+
|
| 21 |
+
def clear_line(mode=2):
|
| 22 |
+
return CSI + str(mode) + 'K'
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class AnsiCodes(object):
|
| 26 |
+
def __init__(self):
|
| 27 |
+
# the subclasses declare class attributes which are numbers.
|
| 28 |
+
# Upon instantiation we define instance attributes, which are the same
|
| 29 |
+
# as the class attributes but wrapped with the ANSI escape sequence
|
| 30 |
+
for name in dir(self):
|
| 31 |
+
if not name.startswith('_'):
|
| 32 |
+
value = getattr(self, name)
|
| 33 |
+
setattr(self, name, code_to_chars(value))
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class AnsiCursor(object):
|
| 37 |
+
def UP(self, n=1):
|
| 38 |
+
return CSI + str(n) + 'A'
|
| 39 |
+
def DOWN(self, n=1):
|
| 40 |
+
return CSI + str(n) + 'B'
|
| 41 |
+
def FORWARD(self, n=1):
|
| 42 |
+
return CSI + str(n) + 'C'
|
| 43 |
+
def BACK(self, n=1):
|
| 44 |
+
return CSI + str(n) + 'D'
|
| 45 |
+
def POS(self, x=1, y=1):
|
| 46 |
+
return CSI + str(y) + ';' + str(x) + 'H'
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class AnsiFore(AnsiCodes):
|
| 50 |
+
BLACK = 30
|
| 51 |
+
RED = 31
|
| 52 |
+
GREEN = 32
|
| 53 |
+
YELLOW = 33
|
| 54 |
+
BLUE = 34
|
| 55 |
+
MAGENTA = 35
|
| 56 |
+
CYAN = 36
|
| 57 |
+
WHITE = 37
|
| 58 |
+
RESET = 39
|
| 59 |
+
|
| 60 |
+
# These are fairly well supported, but not part of the standard.
|
| 61 |
+
LIGHTBLACK_EX = 90
|
| 62 |
+
LIGHTRED_EX = 91
|
| 63 |
+
LIGHTGREEN_EX = 92
|
| 64 |
+
LIGHTYELLOW_EX = 93
|
| 65 |
+
LIGHTBLUE_EX = 94
|
| 66 |
+
LIGHTMAGENTA_EX = 95
|
| 67 |
+
LIGHTCYAN_EX = 96
|
| 68 |
+
LIGHTWHITE_EX = 97
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class AnsiBack(AnsiCodes):
|
| 72 |
+
BLACK = 40
|
| 73 |
+
RED = 41
|
| 74 |
+
GREEN = 42
|
| 75 |
+
YELLOW = 43
|
| 76 |
+
BLUE = 44
|
| 77 |
+
MAGENTA = 45
|
| 78 |
+
CYAN = 46
|
| 79 |
+
WHITE = 47
|
| 80 |
+
RESET = 49
|
| 81 |
+
|
| 82 |
+
# These are fairly well supported, but not part of the standard.
|
| 83 |
+
LIGHTBLACK_EX = 100
|
| 84 |
+
LIGHTRED_EX = 101
|
| 85 |
+
LIGHTGREEN_EX = 102
|
| 86 |
+
LIGHTYELLOW_EX = 103
|
| 87 |
+
LIGHTBLUE_EX = 104
|
| 88 |
+
LIGHTMAGENTA_EX = 105
|
| 89 |
+
LIGHTCYAN_EX = 106
|
| 90 |
+
LIGHTWHITE_EX = 107
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
class AnsiStyle(AnsiCodes):
|
| 94 |
+
BRIGHT = 1
|
| 95 |
+
DIM = 2
|
| 96 |
+
NORMAL = 22
|
| 97 |
+
RESET_ALL = 0
|
| 98 |
+
|
| 99 |
+
Fore = AnsiFore()
|
| 100 |
+
Back = AnsiBack()
|
| 101 |
+
Style = AnsiStyle()
|
| 102 |
+
Cursor = AnsiCursor()
|
TTS/Kokoro/.venv/Lib/site-packages/colorama/ansitowin32.py
ADDED
|
@@ -0,0 +1,277 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
|
| 2 |
+
import re
|
| 3 |
+
import sys
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
from .ansi import AnsiFore, AnsiBack, AnsiStyle, Style, BEL
|
| 7 |
+
from .winterm import enable_vt_processing, WinTerm, WinColor, WinStyle
|
| 8 |
+
from .win32 import windll, winapi_test
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
winterm = None
|
| 12 |
+
if windll is not None:
|
| 13 |
+
winterm = WinTerm()
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class StreamWrapper(object):
|
| 17 |
+
'''
|
| 18 |
+
Wraps a stream (such as stdout), acting as a transparent proxy for all
|
| 19 |
+
attribute access apart from method 'write()', which is delegated to our
|
| 20 |
+
Converter instance.
|
| 21 |
+
'''
|
| 22 |
+
def __init__(self, wrapped, converter):
|
| 23 |
+
# double-underscore everything to prevent clashes with names of
|
| 24 |
+
# attributes on the wrapped stream object.
|
| 25 |
+
self.__wrapped = wrapped
|
| 26 |
+
self.__convertor = converter
|
| 27 |
+
|
| 28 |
+
def __getattr__(self, name):
|
| 29 |
+
return getattr(self.__wrapped, name)
|
| 30 |
+
|
| 31 |
+
def __enter__(self, *args, **kwargs):
|
| 32 |
+
# special method lookup bypasses __getattr__/__getattribute__, see
|
| 33 |
+
# https://stackoverflow.com/questions/12632894/why-doesnt-getattr-work-with-exit
|
| 34 |
+
# thus, contextlib magic methods are not proxied via __getattr__
|
| 35 |
+
return self.__wrapped.__enter__(*args, **kwargs)
|
| 36 |
+
|
| 37 |
+
def __exit__(self, *args, **kwargs):
|
| 38 |
+
return self.__wrapped.__exit__(*args, **kwargs)
|
| 39 |
+
|
| 40 |
+
def __setstate__(self, state):
|
| 41 |
+
self.__dict__ = state
|
| 42 |
+
|
| 43 |
+
def __getstate__(self):
|
| 44 |
+
return self.__dict__
|
| 45 |
+
|
| 46 |
+
def write(self, text):
|
| 47 |
+
self.__convertor.write(text)
|
| 48 |
+
|
| 49 |
+
def isatty(self):
|
| 50 |
+
stream = self.__wrapped
|
| 51 |
+
if 'PYCHARM_HOSTED' in os.environ:
|
| 52 |
+
if stream is not None and (stream is sys.__stdout__ or stream is sys.__stderr__):
|
| 53 |
+
return True
|
| 54 |
+
try:
|
| 55 |
+
stream_isatty = stream.isatty
|
| 56 |
+
except AttributeError:
|
| 57 |
+
return False
|
| 58 |
+
else:
|
| 59 |
+
return stream_isatty()
|
| 60 |
+
|
| 61 |
+
@property
|
| 62 |
+
def closed(self):
|
| 63 |
+
stream = self.__wrapped
|
| 64 |
+
try:
|
| 65 |
+
return stream.closed
|
| 66 |
+
# AttributeError in the case that the stream doesn't support being closed
|
| 67 |
+
# ValueError for the case that the stream has already been detached when atexit runs
|
| 68 |
+
except (AttributeError, ValueError):
|
| 69 |
+
return True
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
class AnsiToWin32(object):
|
| 73 |
+
'''
|
| 74 |
+
Implements a 'write()' method which, on Windows, will strip ANSI character
|
| 75 |
+
sequences from the text, and if outputting to a tty, will convert them into
|
| 76 |
+
win32 function calls.
|
| 77 |
+
'''
|
| 78 |
+
ANSI_CSI_RE = re.compile('\001?\033\\[((?:\\d|;)*)([a-zA-Z])\002?') # Control Sequence Introducer
|
| 79 |
+
ANSI_OSC_RE = re.compile('\001?\033\\]([^\a]*)(\a)\002?') # Operating System Command
|
| 80 |
+
|
| 81 |
+
def __init__(self, wrapped, convert=None, strip=None, autoreset=False):
|
| 82 |
+
# The wrapped stream (normally sys.stdout or sys.stderr)
|
| 83 |
+
self.wrapped = wrapped
|
| 84 |
+
|
| 85 |
+
# should we reset colors to defaults after every .write()
|
| 86 |
+
self.autoreset = autoreset
|
| 87 |
+
|
| 88 |
+
# create the proxy wrapping our output stream
|
| 89 |
+
self.stream = StreamWrapper(wrapped, self)
|
| 90 |
+
|
| 91 |
+
on_windows = os.name == 'nt'
|
| 92 |
+
# We test if the WinAPI works, because even if we are on Windows
|
| 93 |
+
# we may be using a terminal that doesn't support the WinAPI
|
| 94 |
+
# (e.g. Cygwin Terminal). In this case it's up to the terminal
|
| 95 |
+
# to support the ANSI codes.
|
| 96 |
+
conversion_supported = on_windows and winapi_test()
|
| 97 |
+
try:
|
| 98 |
+
fd = wrapped.fileno()
|
| 99 |
+
except Exception:
|
| 100 |
+
fd = -1
|
| 101 |
+
system_has_native_ansi = not on_windows or enable_vt_processing(fd)
|
| 102 |
+
have_tty = not self.stream.closed and self.stream.isatty()
|
| 103 |
+
need_conversion = conversion_supported and not system_has_native_ansi
|
| 104 |
+
|
| 105 |
+
# should we strip ANSI sequences from our output?
|
| 106 |
+
if strip is None:
|
| 107 |
+
strip = need_conversion or not have_tty
|
| 108 |
+
self.strip = strip
|
| 109 |
+
|
| 110 |
+
# should we should convert ANSI sequences into win32 calls?
|
| 111 |
+
if convert is None:
|
| 112 |
+
convert = need_conversion and have_tty
|
| 113 |
+
self.convert = convert
|
| 114 |
+
|
| 115 |
+
# dict of ansi codes to win32 functions and parameters
|
| 116 |
+
self.win32_calls = self.get_win32_calls()
|
| 117 |
+
|
| 118 |
+
# are we wrapping stderr?
|
| 119 |
+
self.on_stderr = self.wrapped is sys.stderr
|
| 120 |
+
|
| 121 |
+
def should_wrap(self):
|
| 122 |
+
'''
|
| 123 |
+
True if this class is actually needed. If false, then the output
|
| 124 |
+
stream will not be affected, nor will win32 calls be issued, so
|
| 125 |
+
wrapping stdout is not actually required. This will generally be
|
| 126 |
+
False on non-Windows platforms, unless optional functionality like
|
| 127 |
+
autoreset has been requested using kwargs to init()
|
| 128 |
+
'''
|
| 129 |
+
return self.convert or self.strip or self.autoreset
|
| 130 |
+
|
| 131 |
+
def get_win32_calls(self):
|
| 132 |
+
if self.convert and winterm:
|
| 133 |
+
return {
|
| 134 |
+
AnsiStyle.RESET_ALL: (winterm.reset_all, ),
|
| 135 |
+
AnsiStyle.BRIGHT: (winterm.style, WinStyle.BRIGHT),
|
| 136 |
+
AnsiStyle.DIM: (winterm.style, WinStyle.NORMAL),
|
| 137 |
+
AnsiStyle.NORMAL: (winterm.style, WinStyle.NORMAL),
|
| 138 |
+
AnsiFore.BLACK: (winterm.fore, WinColor.BLACK),
|
| 139 |
+
AnsiFore.RED: (winterm.fore, WinColor.RED),
|
| 140 |
+
AnsiFore.GREEN: (winterm.fore, WinColor.GREEN),
|
| 141 |
+
AnsiFore.YELLOW: (winterm.fore, WinColor.YELLOW),
|
| 142 |
+
AnsiFore.BLUE: (winterm.fore, WinColor.BLUE),
|
| 143 |
+
AnsiFore.MAGENTA: (winterm.fore, WinColor.MAGENTA),
|
| 144 |
+
AnsiFore.CYAN: (winterm.fore, WinColor.CYAN),
|
| 145 |
+
AnsiFore.WHITE: (winterm.fore, WinColor.GREY),
|
| 146 |
+
AnsiFore.RESET: (winterm.fore, ),
|
| 147 |
+
AnsiFore.LIGHTBLACK_EX: (winterm.fore, WinColor.BLACK, True),
|
| 148 |
+
AnsiFore.LIGHTRED_EX: (winterm.fore, WinColor.RED, True),
|
| 149 |
+
AnsiFore.LIGHTGREEN_EX: (winterm.fore, WinColor.GREEN, True),
|
| 150 |
+
AnsiFore.LIGHTYELLOW_EX: (winterm.fore, WinColor.YELLOW, True),
|
| 151 |
+
AnsiFore.LIGHTBLUE_EX: (winterm.fore, WinColor.BLUE, True),
|
| 152 |
+
AnsiFore.LIGHTMAGENTA_EX: (winterm.fore, WinColor.MAGENTA, True),
|
| 153 |
+
AnsiFore.LIGHTCYAN_EX: (winterm.fore, WinColor.CYAN, True),
|
| 154 |
+
AnsiFore.LIGHTWHITE_EX: (winterm.fore, WinColor.GREY, True),
|
| 155 |
+
AnsiBack.BLACK: (winterm.back, WinColor.BLACK),
|
| 156 |
+
AnsiBack.RED: (winterm.back, WinColor.RED),
|
| 157 |
+
AnsiBack.GREEN: (winterm.back, WinColor.GREEN),
|
| 158 |
+
AnsiBack.YELLOW: (winterm.back, WinColor.YELLOW),
|
| 159 |
+
AnsiBack.BLUE: (winterm.back, WinColor.BLUE),
|
| 160 |
+
AnsiBack.MAGENTA: (winterm.back, WinColor.MAGENTA),
|
| 161 |
+
AnsiBack.CYAN: (winterm.back, WinColor.CYAN),
|
| 162 |
+
AnsiBack.WHITE: (winterm.back, WinColor.GREY),
|
| 163 |
+
AnsiBack.RESET: (winterm.back, ),
|
| 164 |
+
AnsiBack.LIGHTBLACK_EX: (winterm.back, WinColor.BLACK, True),
|
| 165 |
+
AnsiBack.LIGHTRED_EX: (winterm.back, WinColor.RED, True),
|
| 166 |
+
AnsiBack.LIGHTGREEN_EX: (winterm.back, WinColor.GREEN, True),
|
| 167 |
+
AnsiBack.LIGHTYELLOW_EX: (winterm.back, WinColor.YELLOW, True),
|
| 168 |
+
AnsiBack.LIGHTBLUE_EX: (winterm.back, WinColor.BLUE, True),
|
| 169 |
+
AnsiBack.LIGHTMAGENTA_EX: (winterm.back, WinColor.MAGENTA, True),
|
| 170 |
+
AnsiBack.LIGHTCYAN_EX: (winterm.back, WinColor.CYAN, True),
|
| 171 |
+
AnsiBack.LIGHTWHITE_EX: (winterm.back, WinColor.GREY, True),
|
| 172 |
+
}
|
| 173 |
+
return dict()
|
| 174 |
+
|
| 175 |
+
def write(self, text):
|
| 176 |
+
if self.strip or self.convert:
|
| 177 |
+
self.write_and_convert(text)
|
| 178 |
+
else:
|
| 179 |
+
self.wrapped.write(text)
|
| 180 |
+
self.wrapped.flush()
|
| 181 |
+
if self.autoreset:
|
| 182 |
+
self.reset_all()
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def reset_all(self):
|
| 186 |
+
if self.convert:
|
| 187 |
+
self.call_win32('m', (0,))
|
| 188 |
+
elif not self.strip and not self.stream.closed:
|
| 189 |
+
self.wrapped.write(Style.RESET_ALL)
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def write_and_convert(self, text):
|
| 193 |
+
'''
|
| 194 |
+
Write the given text to our wrapped stream, stripping any ANSI
|
| 195 |
+
sequences from the text, and optionally converting them into win32
|
| 196 |
+
calls.
|
| 197 |
+
'''
|
| 198 |
+
cursor = 0
|
| 199 |
+
text = self.convert_osc(text)
|
| 200 |
+
for match in self.ANSI_CSI_RE.finditer(text):
|
| 201 |
+
start, end = match.span()
|
| 202 |
+
self.write_plain_text(text, cursor, start)
|
| 203 |
+
self.convert_ansi(*match.groups())
|
| 204 |
+
cursor = end
|
| 205 |
+
self.write_plain_text(text, cursor, len(text))
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def write_plain_text(self, text, start, end):
|
| 209 |
+
if start < end:
|
| 210 |
+
self.wrapped.write(text[start:end])
|
| 211 |
+
self.wrapped.flush()
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def convert_ansi(self, paramstring, command):
|
| 215 |
+
if self.convert:
|
| 216 |
+
params = self.extract_params(command, paramstring)
|
| 217 |
+
self.call_win32(command, params)
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def extract_params(self, command, paramstring):
|
| 221 |
+
if command in 'Hf':
|
| 222 |
+
params = tuple(int(p) if len(p) != 0 else 1 for p in paramstring.split(';'))
|
| 223 |
+
while len(params) < 2:
|
| 224 |
+
# defaults:
|
| 225 |
+
params = params + (1,)
|
| 226 |
+
else:
|
| 227 |
+
params = tuple(int(p) for p in paramstring.split(';') if len(p) != 0)
|
| 228 |
+
if len(params) == 0:
|
| 229 |
+
# defaults:
|
| 230 |
+
if command in 'JKm':
|
| 231 |
+
params = (0,)
|
| 232 |
+
elif command in 'ABCD':
|
| 233 |
+
params = (1,)
|
| 234 |
+
|
| 235 |
+
return params
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def call_win32(self, command, params):
|
| 239 |
+
if command == 'm':
|
| 240 |
+
for param in params:
|
| 241 |
+
if param in self.win32_calls:
|
| 242 |
+
func_args = self.win32_calls[param]
|
| 243 |
+
func = func_args[0]
|
| 244 |
+
args = func_args[1:]
|
| 245 |
+
kwargs = dict(on_stderr=self.on_stderr)
|
| 246 |
+
func(*args, **kwargs)
|
| 247 |
+
elif command in 'J':
|
| 248 |
+
winterm.erase_screen(params[0], on_stderr=self.on_stderr)
|
| 249 |
+
elif command in 'K':
|
| 250 |
+
winterm.erase_line(params[0], on_stderr=self.on_stderr)
|
| 251 |
+
elif command in 'Hf': # cursor position - absolute
|
| 252 |
+
winterm.set_cursor_position(params, on_stderr=self.on_stderr)
|
| 253 |
+
elif command in 'ABCD': # cursor position - relative
|
| 254 |
+
n = params[0]
|
| 255 |
+
# A - up, B - down, C - forward, D - back
|
| 256 |
+
x, y = {'A': (0, -n), 'B': (0, n), 'C': (n, 0), 'D': (-n, 0)}[command]
|
| 257 |
+
winterm.cursor_adjust(x, y, on_stderr=self.on_stderr)
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def convert_osc(self, text):
|
| 261 |
+
for match in self.ANSI_OSC_RE.finditer(text):
|
| 262 |
+
start, end = match.span()
|
| 263 |
+
text = text[:start] + text[end:]
|
| 264 |
+
paramstring, command = match.groups()
|
| 265 |
+
if command == BEL:
|
| 266 |
+
if paramstring.count(";") == 1:
|
| 267 |
+
params = paramstring.split(";")
|
| 268 |
+
# 0 - change title and icon (we will only change title)
|
| 269 |
+
# 1 - change icon (we don't support this)
|
| 270 |
+
# 2 - change title
|
| 271 |
+
if params[0] in '02':
|
| 272 |
+
winterm.set_title(params[1])
|
| 273 |
+
return text
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def flush(self):
|
| 277 |
+
self.wrapped.flush()
|
TTS/Kokoro/.venv/Lib/site-packages/colorama/initialise.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
|
| 2 |
+
import atexit
|
| 3 |
+
import contextlib
|
| 4 |
+
import sys
|
| 5 |
+
|
| 6 |
+
from .ansitowin32 import AnsiToWin32
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def _wipe_internal_state_for_tests():
|
| 10 |
+
global orig_stdout, orig_stderr
|
| 11 |
+
orig_stdout = None
|
| 12 |
+
orig_stderr = None
|
| 13 |
+
|
| 14 |
+
global wrapped_stdout, wrapped_stderr
|
| 15 |
+
wrapped_stdout = None
|
| 16 |
+
wrapped_stderr = None
|
| 17 |
+
|
| 18 |
+
global atexit_done
|
| 19 |
+
atexit_done = False
|
| 20 |
+
|
| 21 |
+
global fixed_windows_console
|
| 22 |
+
fixed_windows_console = False
|
| 23 |
+
|
| 24 |
+
try:
|
| 25 |
+
# no-op if it wasn't registered
|
| 26 |
+
atexit.unregister(reset_all)
|
| 27 |
+
except AttributeError:
|
| 28 |
+
# python 2: no atexit.unregister. Oh well, we did our best.
|
| 29 |
+
pass
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def reset_all():
|
| 33 |
+
if AnsiToWin32 is not None: # Issue #74: objects might become None at exit
|
| 34 |
+
AnsiToWin32(orig_stdout).reset_all()
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def init(autoreset=False, convert=None, strip=None, wrap=True):
|
| 38 |
+
|
| 39 |
+
if not wrap and any([autoreset, convert, strip]):
|
| 40 |
+
raise ValueError('wrap=False conflicts with any other arg=True')
|
| 41 |
+
|
| 42 |
+
global wrapped_stdout, wrapped_stderr
|
| 43 |
+
global orig_stdout, orig_stderr
|
| 44 |
+
|
| 45 |
+
orig_stdout = sys.stdout
|
| 46 |
+
orig_stderr = sys.stderr
|
| 47 |
+
|
| 48 |
+
if sys.stdout is None:
|
| 49 |
+
wrapped_stdout = None
|
| 50 |
+
else:
|
| 51 |
+
sys.stdout = wrapped_stdout = \
|
| 52 |
+
wrap_stream(orig_stdout, convert, strip, autoreset, wrap)
|
| 53 |
+
if sys.stderr is None:
|
| 54 |
+
wrapped_stderr = None
|
| 55 |
+
else:
|
| 56 |
+
sys.stderr = wrapped_stderr = \
|
| 57 |
+
wrap_stream(orig_stderr, convert, strip, autoreset, wrap)
|
| 58 |
+
|
| 59 |
+
global atexit_done
|
| 60 |
+
if not atexit_done:
|
| 61 |
+
atexit.register(reset_all)
|
| 62 |
+
atexit_done = True
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def deinit():
|
| 66 |
+
if orig_stdout is not None:
|
| 67 |
+
sys.stdout = orig_stdout
|
| 68 |
+
if orig_stderr is not None:
|
| 69 |
+
sys.stderr = orig_stderr
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def just_fix_windows_console():
|
| 73 |
+
global fixed_windows_console
|
| 74 |
+
|
| 75 |
+
if sys.platform != "win32":
|
| 76 |
+
return
|
| 77 |
+
if fixed_windows_console:
|
| 78 |
+
return
|
| 79 |
+
if wrapped_stdout is not None or wrapped_stderr is not None:
|
| 80 |
+
# Someone already ran init() and it did stuff, so we won't second-guess them
|
| 81 |
+
return
|
| 82 |
+
|
| 83 |
+
# On newer versions of Windows, AnsiToWin32.__init__ will implicitly enable the
|
| 84 |
+
# native ANSI support in the console as a side-effect. We only need to actually
|
| 85 |
+
# replace sys.stdout/stderr if we're in the old-style conversion mode.
|
| 86 |
+
new_stdout = AnsiToWin32(sys.stdout, convert=None, strip=None, autoreset=False)
|
| 87 |
+
if new_stdout.convert:
|
| 88 |
+
sys.stdout = new_stdout
|
| 89 |
+
new_stderr = AnsiToWin32(sys.stderr, convert=None, strip=None, autoreset=False)
|
| 90 |
+
if new_stderr.convert:
|
| 91 |
+
sys.stderr = new_stderr
|
| 92 |
+
|
| 93 |
+
fixed_windows_console = True
|
| 94 |
+
|
| 95 |
+
@contextlib.contextmanager
|
| 96 |
+
def colorama_text(*args, **kwargs):
|
| 97 |
+
init(*args, **kwargs)
|
| 98 |
+
try:
|
| 99 |
+
yield
|
| 100 |
+
finally:
|
| 101 |
+
deinit()
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def reinit():
|
| 105 |
+
if wrapped_stdout is not None:
|
| 106 |
+
sys.stdout = wrapped_stdout
|
| 107 |
+
if wrapped_stderr is not None:
|
| 108 |
+
sys.stderr = wrapped_stderr
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def wrap_stream(stream, convert, strip, autoreset, wrap):
|
| 112 |
+
if wrap:
|
| 113 |
+
wrapper = AnsiToWin32(stream,
|
| 114 |
+
convert=convert, strip=strip, autoreset=autoreset)
|
| 115 |
+
if wrapper.should_wrap():
|
| 116 |
+
stream = wrapper.stream
|
| 117 |
+
return stream
|
| 118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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
|
| 2 |
+
|
| 3 |
+
# from winbase.h
|
| 4 |
+
STDOUT = -11
|
| 5 |
+
STDERR = -12
|
| 6 |
+
|
| 7 |
+
ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004
|
| 8 |
+
|
| 9 |
+
try:
|
| 10 |
+
import ctypes
|
| 11 |
+
from ctypes import LibraryLoader
|
| 12 |
+
windll = LibraryLoader(ctypes.WinDLL)
|
| 13 |
+
from ctypes import wintypes
|
| 14 |
+
except (AttributeError, ImportError):
|
| 15 |
+
windll = None
|
| 16 |
+
SetConsoleTextAttribute = lambda *_: None
|
| 17 |
+
winapi_test = lambda *_: None
|
| 18 |
+
else:
|
| 19 |
+
from ctypes import byref, Structure, c_char, POINTER
|
| 20 |
+
|
| 21 |
+
COORD = wintypes._COORD
|
| 22 |
+
|
| 23 |
+
class CONSOLE_SCREEN_BUFFER_INFO(Structure):
|
| 24 |
+
"""struct in wincon.h."""
|
| 25 |
+
_fields_ = [
|
| 26 |
+
("dwSize", COORD),
|
| 27 |
+
("dwCursorPosition", COORD),
|
| 28 |
+
("wAttributes", wintypes.WORD),
|
| 29 |
+
("srWindow", wintypes.SMALL_RECT),
|
| 30 |
+
("dwMaximumWindowSize", COORD),
|
| 31 |
+
]
|
| 32 |
+
def __str__(self):
|
| 33 |
+
return '(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)' % (
|
| 34 |
+
self.dwSize.Y, self.dwSize.X
|
| 35 |
+
, self.dwCursorPosition.Y, self.dwCursorPosition.X
|
| 36 |
+
, self.wAttributes
|
| 37 |
+
, self.srWindow.Top, self.srWindow.Left, self.srWindow.Bottom, self.srWindow.Right
|
| 38 |
+
, self.dwMaximumWindowSize.Y, self.dwMaximumWindowSize.X
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
_GetStdHandle = windll.kernel32.GetStdHandle
|
| 42 |
+
_GetStdHandle.argtypes = [
|
| 43 |
+
wintypes.DWORD,
|
| 44 |
+
]
|
| 45 |
+
_GetStdHandle.restype = wintypes.HANDLE
|
| 46 |
+
|
| 47 |
+
_GetConsoleScreenBufferInfo = windll.kernel32.GetConsoleScreenBufferInfo
|
| 48 |
+
_GetConsoleScreenBufferInfo.argtypes = [
|
| 49 |
+
wintypes.HANDLE,
|
| 50 |
+
POINTER(CONSOLE_SCREEN_BUFFER_INFO),
|
| 51 |
+
]
|
| 52 |
+
_GetConsoleScreenBufferInfo.restype = wintypes.BOOL
|
| 53 |
+
|
| 54 |
+
_SetConsoleTextAttribute = windll.kernel32.SetConsoleTextAttribute
|
| 55 |
+
_SetConsoleTextAttribute.argtypes = [
|
| 56 |
+
wintypes.HANDLE,
|
| 57 |
+
wintypes.WORD,
|
| 58 |
+
]
|
| 59 |
+
_SetConsoleTextAttribute.restype = wintypes.BOOL
|
| 60 |
+
|
| 61 |
+
_SetConsoleCursorPosition = windll.kernel32.SetConsoleCursorPosition
|
| 62 |
+
_SetConsoleCursorPosition.argtypes = [
|
| 63 |
+
wintypes.HANDLE,
|
| 64 |
+
COORD,
|
| 65 |
+
]
|
| 66 |
+
_SetConsoleCursorPosition.restype = wintypes.BOOL
|
| 67 |
+
|
| 68 |
+
_FillConsoleOutputCharacterA = windll.kernel32.FillConsoleOutputCharacterA
|
| 69 |
+
_FillConsoleOutputCharacterA.argtypes = [
|
| 70 |
+
wintypes.HANDLE,
|
| 71 |
+
c_char,
|
| 72 |
+
wintypes.DWORD,
|
| 73 |
+
COORD,
|
| 74 |
+
POINTER(wintypes.DWORD),
|
| 75 |
+
]
|
| 76 |
+
_FillConsoleOutputCharacterA.restype = wintypes.BOOL
|
| 77 |
+
|
| 78 |
+
_FillConsoleOutputAttribute = windll.kernel32.FillConsoleOutputAttribute
|
| 79 |
+
_FillConsoleOutputAttribute.argtypes = [
|
| 80 |
+
wintypes.HANDLE,
|
| 81 |
+
wintypes.WORD,
|
| 82 |
+
wintypes.DWORD,
|
| 83 |
+
COORD,
|
| 84 |
+
POINTER(wintypes.DWORD),
|
| 85 |
+
]
|
| 86 |
+
_FillConsoleOutputAttribute.restype = wintypes.BOOL
|
| 87 |
+
|
| 88 |
+
_SetConsoleTitleW = windll.kernel32.SetConsoleTitleW
|
| 89 |
+
_SetConsoleTitleW.argtypes = [
|
| 90 |
+
wintypes.LPCWSTR
|
| 91 |
+
]
|
| 92 |
+
_SetConsoleTitleW.restype = wintypes.BOOL
|
| 93 |
+
|
| 94 |
+
_GetConsoleMode = windll.kernel32.GetConsoleMode
|
| 95 |
+
_GetConsoleMode.argtypes = [
|
| 96 |
+
wintypes.HANDLE,
|
| 97 |
+
POINTER(wintypes.DWORD)
|
| 98 |
+
]
|
| 99 |
+
_GetConsoleMode.restype = wintypes.BOOL
|
| 100 |
+
|
| 101 |
+
_SetConsoleMode = windll.kernel32.SetConsoleMode
|
| 102 |
+
_SetConsoleMode.argtypes = [
|
| 103 |
+
wintypes.HANDLE,
|
| 104 |
+
wintypes.DWORD
|
| 105 |
+
]
|
| 106 |
+
_SetConsoleMode.restype = wintypes.BOOL
|
| 107 |
+
|
| 108 |
+
def _winapi_test(handle):
|
| 109 |
+
csbi = CONSOLE_SCREEN_BUFFER_INFO()
|
| 110 |
+
success = _GetConsoleScreenBufferInfo(
|
| 111 |
+
handle, byref(csbi))
|
| 112 |
+
return bool(success)
|
| 113 |
+
|
| 114 |
+
def winapi_test():
|
| 115 |
+
return any(_winapi_test(h) for h in
|
| 116 |
+
(_GetStdHandle(STDOUT), _GetStdHandle(STDERR)))
|
| 117 |
+
|
| 118 |
+
def GetConsoleScreenBufferInfo(stream_id=STDOUT):
|
| 119 |
+
handle = _GetStdHandle(stream_id)
|
| 120 |
+
csbi = CONSOLE_SCREEN_BUFFER_INFO()
|
| 121 |
+
success = _GetConsoleScreenBufferInfo(
|
| 122 |
+
handle, byref(csbi))
|
| 123 |
+
return csbi
|
| 124 |
+
|
| 125 |
+
def SetConsoleTextAttribute(stream_id, attrs):
|
| 126 |
+
handle = _GetStdHandle(stream_id)
|
| 127 |
+
return _SetConsoleTextAttribute(handle, attrs)
|
| 128 |
+
|
| 129 |
+
def SetConsoleCursorPosition(stream_id, position, adjust=True):
|
| 130 |
+
position = COORD(*position)
|
| 131 |
+
# If the position is out of range, do nothing.
|
| 132 |
+
if position.Y <= 0 or position.X <= 0:
|
| 133 |
+
return
|
| 134 |
+
# Adjust for Windows' SetConsoleCursorPosition:
|
| 135 |
+
# 1. being 0-based, while ANSI is 1-based.
|
| 136 |
+
# 2. expecting (x,y), while ANSI uses (y,x).
|
| 137 |
+
adjusted_position = COORD(position.Y - 1, position.X - 1)
|
| 138 |
+
if adjust:
|
| 139 |
+
# Adjust for viewport's scroll position
|
| 140 |
+
sr = GetConsoleScreenBufferInfo(STDOUT).srWindow
|
| 141 |
+
adjusted_position.Y += sr.Top
|
| 142 |
+
adjusted_position.X += sr.Left
|
| 143 |
+
# Resume normal processing
|
| 144 |
+
handle = _GetStdHandle(stream_id)
|
| 145 |
+
return _SetConsoleCursorPosition(handle, adjusted_position)
|
| 146 |
+
|
| 147 |
+
def FillConsoleOutputCharacter(stream_id, char, length, start):
|
| 148 |
+
handle = _GetStdHandle(stream_id)
|
| 149 |
+
char = c_char(char.encode())
|
| 150 |
+
length = wintypes.DWORD(length)
|
| 151 |
+
num_written = wintypes.DWORD(0)
|
| 152 |
+
# Note that this is hard-coded for ANSI (vs wide) bytes.
|
| 153 |
+
success = _FillConsoleOutputCharacterA(
|
| 154 |
+
handle, char, length, start, byref(num_written))
|
| 155 |
+
return num_written.value
|
| 156 |
+
|
| 157 |
+
def FillConsoleOutputAttribute(stream_id, attr, length, start):
|
| 158 |
+
''' FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten )'''
|
| 159 |
+
handle = _GetStdHandle(stream_id)
|
| 160 |
+
attribute = wintypes.WORD(attr)
|
| 161 |
+
length = wintypes.DWORD(length)
|
| 162 |
+
num_written = wintypes.DWORD(0)
|
| 163 |
+
# Note that this is hard-coded for ANSI (vs wide) bytes.
|
| 164 |
+
return _FillConsoleOutputAttribute(
|
| 165 |
+
handle, attribute, length, start, byref(num_written))
|
| 166 |
+
|
| 167 |
+
def SetConsoleTitle(title):
|
| 168 |
+
return _SetConsoleTitleW(title)
|
| 169 |
+
|
| 170 |
+
def GetConsoleMode(handle):
|
| 171 |
+
mode = wintypes.DWORD()
|
| 172 |
+
success = _GetConsoleMode(handle, byref(mode))
|
| 173 |
+
if not success:
|
| 174 |
+
raise ctypes.WinError()
|
| 175 |
+
return mode.value
|
| 176 |
+
|
| 177 |
+
def SetConsoleMode(handle, mode):
|
| 178 |
+
success = _SetConsoleMode(handle, mode)
|
| 179 |
+
if not success:
|
| 180 |
+
raise ctypes.WinError()
|
TTS/Kokoro/.venv/Lib/site-packages/colorama/winterm.py
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
|
| 2 |
+
try:
|
| 3 |
+
from msvcrt import get_osfhandle
|
| 4 |
+
except ImportError:
|
| 5 |
+
def get_osfhandle(_):
|
| 6 |
+
raise OSError("This isn't windows!")
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
from . import win32
|
| 10 |
+
|
| 11 |
+
# from wincon.h
|
| 12 |
+
class WinColor(object):
|
| 13 |
+
BLACK = 0
|
| 14 |
+
BLUE = 1
|
| 15 |
+
GREEN = 2
|
| 16 |
+
CYAN = 3
|
| 17 |
+
RED = 4
|
| 18 |
+
MAGENTA = 5
|
| 19 |
+
YELLOW = 6
|
| 20 |
+
GREY = 7
|
| 21 |
+
|
| 22 |
+
# from wincon.h
|
| 23 |
+
class WinStyle(object):
|
| 24 |
+
NORMAL = 0x00 # dim text, dim background
|
| 25 |
+
BRIGHT = 0x08 # bright text, dim background
|
| 26 |
+
BRIGHT_BACKGROUND = 0x80 # dim text, bright background
|
| 27 |
+
|
| 28 |
+
class WinTerm(object):
|
| 29 |
+
|
| 30 |
+
def __init__(self):
|
| 31 |
+
self._default = win32.GetConsoleScreenBufferInfo(win32.STDOUT).wAttributes
|
| 32 |
+
self.set_attrs(self._default)
|
| 33 |
+
self._default_fore = self._fore
|
| 34 |
+
self._default_back = self._back
|
| 35 |
+
self._default_style = self._style
|
| 36 |
+
# In order to emulate LIGHT_EX in windows, we borrow the BRIGHT style.
|
| 37 |
+
# So that LIGHT_EX colors and BRIGHT style do not clobber each other,
|
| 38 |
+
# we track them separately, since LIGHT_EX is overwritten by Fore/Back
|
| 39 |
+
# and BRIGHT is overwritten by Style codes.
|
| 40 |
+
self._light = 0
|
| 41 |
+
|
| 42 |
+
def get_attrs(self):
|
| 43 |
+
return self._fore + self._back * 16 + (self._style | self._light)
|
| 44 |
+
|
| 45 |
+
def set_attrs(self, value):
|
| 46 |
+
self._fore = value & 7
|
| 47 |
+
self._back = (value >> 4) & 7
|
| 48 |
+
self._style = value & (WinStyle.BRIGHT | WinStyle.BRIGHT_BACKGROUND)
|
| 49 |
+
|
| 50 |
+
def reset_all(self, on_stderr=None):
|
| 51 |
+
self.set_attrs(self._default)
|
| 52 |
+
self.set_console(attrs=self._default)
|
| 53 |
+
self._light = 0
|
| 54 |
+
|
| 55 |
+
def fore(self, fore=None, light=False, on_stderr=False):
|
| 56 |
+
if fore is None:
|
| 57 |
+
fore = self._default_fore
|
| 58 |
+
self._fore = fore
|
| 59 |
+
# Emulate LIGHT_EX with BRIGHT Style
|
| 60 |
+
if light:
|
| 61 |
+
self._light |= WinStyle.BRIGHT
|
| 62 |
+
else:
|
| 63 |
+
self._light &= ~WinStyle.BRIGHT
|
| 64 |
+
self.set_console(on_stderr=on_stderr)
|
| 65 |
+
|
| 66 |
+
def back(self, back=None, light=False, on_stderr=False):
|
| 67 |
+
if back is None:
|
| 68 |
+
back = self._default_back
|
| 69 |
+
self._back = back
|
| 70 |
+
# Emulate LIGHT_EX with BRIGHT_BACKGROUND Style
|
| 71 |
+
if light:
|
| 72 |
+
self._light |= WinStyle.BRIGHT_BACKGROUND
|
| 73 |
+
else:
|
| 74 |
+
self._light &= ~WinStyle.BRIGHT_BACKGROUND
|
| 75 |
+
self.set_console(on_stderr=on_stderr)
|
| 76 |
+
|
| 77 |
+
def style(self, style=None, on_stderr=False):
|
| 78 |
+
if style is None:
|
| 79 |
+
style = self._default_style
|
| 80 |
+
self._style = style
|
| 81 |
+
self.set_console(on_stderr=on_stderr)
|
| 82 |
+
|
| 83 |
+
def set_console(self, attrs=None, on_stderr=False):
|
| 84 |
+
if attrs is None:
|
| 85 |
+
attrs = self.get_attrs()
|
| 86 |
+
handle = win32.STDOUT
|
| 87 |
+
if on_stderr:
|
| 88 |
+
handle = win32.STDERR
|
| 89 |
+
win32.SetConsoleTextAttribute(handle, attrs)
|
| 90 |
+
|
| 91 |
+
def get_position(self, handle):
|
| 92 |
+
position = win32.GetConsoleScreenBufferInfo(handle).dwCursorPosition
|
| 93 |
+
# Because Windows coordinates are 0-based,
|
| 94 |
+
# and win32.SetConsoleCursorPosition expects 1-based.
|
| 95 |
+
position.X += 1
|
| 96 |
+
position.Y += 1
|
| 97 |
+
return position
|
| 98 |
+
|
| 99 |
+
def set_cursor_position(self, position=None, on_stderr=False):
|
| 100 |
+
if position is None:
|
| 101 |
+
# I'm not currently tracking the position, so there is no default.
|
| 102 |
+
# position = self.get_position()
|
| 103 |
+
return
|
| 104 |
+
handle = win32.STDOUT
|
| 105 |
+
if on_stderr:
|
| 106 |
+
handle = win32.STDERR
|
| 107 |
+
win32.SetConsoleCursorPosition(handle, position)
|
| 108 |
+
|
| 109 |
+
def cursor_adjust(self, x, y, on_stderr=False):
|
| 110 |
+
handle = win32.STDOUT
|
| 111 |
+
if on_stderr:
|
| 112 |
+
handle = win32.STDERR
|
| 113 |
+
position = self.get_position(handle)
|
| 114 |
+
adjusted_position = (position.Y + y, position.X + x)
|
| 115 |
+
win32.SetConsoleCursorPosition(handle, adjusted_position, adjust=False)
|
| 116 |
+
|
| 117 |
+
def erase_screen(self, mode=0, on_stderr=False):
|
| 118 |
+
# 0 should clear from the cursor to the end of the screen.
|
| 119 |
+
# 1 should clear from the cursor to the beginning of the screen.
|
| 120 |
+
# 2 should clear the entire screen, and move cursor to (1,1)
|
| 121 |
+
handle = win32.STDOUT
|
| 122 |
+
if on_stderr:
|
| 123 |
+
handle = win32.STDERR
|
| 124 |
+
csbi = win32.GetConsoleScreenBufferInfo(handle)
|
| 125 |
+
# get the number of character cells in the current buffer
|
| 126 |
+
cells_in_screen = csbi.dwSize.X * csbi.dwSize.Y
|
| 127 |
+
# get number of character cells before current cursor position
|
| 128 |
+
cells_before_cursor = csbi.dwSize.X * csbi.dwCursorPosition.Y + csbi.dwCursorPosition.X
|
| 129 |
+
if mode == 0:
|
| 130 |
+
from_coord = csbi.dwCursorPosition
|
| 131 |
+
cells_to_erase = cells_in_screen - cells_before_cursor
|
| 132 |
+
elif mode == 1:
|
| 133 |
+
from_coord = win32.COORD(0, 0)
|
| 134 |
+
cells_to_erase = cells_before_cursor
|
| 135 |
+
elif mode == 2:
|
| 136 |
+
from_coord = win32.COORD(0, 0)
|
| 137 |
+
cells_to_erase = cells_in_screen
|
| 138 |
+
else:
|
| 139 |
+
# invalid mode
|
| 140 |
+
return
|
| 141 |
+
# fill the entire screen with blanks
|
| 142 |
+
win32.FillConsoleOutputCharacter(handle, ' ', cells_to_erase, from_coord)
|
| 143 |
+
# now set the buffer's attributes accordingly
|
| 144 |
+
win32.FillConsoleOutputAttribute(handle, self.get_attrs(), cells_to_erase, from_coord)
|
| 145 |
+
if mode == 2:
|
| 146 |
+
# put the cursor where needed
|
| 147 |
+
win32.SetConsoleCursorPosition(handle, (1, 1))
|
| 148 |
+
|
| 149 |
+
def erase_line(self, mode=0, on_stderr=False):
|
| 150 |
+
# 0 should clear from the cursor to the end of the line.
|
| 151 |
+
# 1 should clear from the cursor to the beginning of the line.
|
| 152 |
+
# 2 should clear the entire line.
|
| 153 |
+
handle = win32.STDOUT
|
| 154 |
+
if on_stderr:
|
| 155 |
+
handle = win32.STDERR
|
| 156 |
+
csbi = win32.GetConsoleScreenBufferInfo(handle)
|
| 157 |
+
if mode == 0:
|
| 158 |
+
from_coord = csbi.dwCursorPosition
|
| 159 |
+
cells_to_erase = csbi.dwSize.X - csbi.dwCursorPosition.X
|
| 160 |
+
elif mode == 1:
|
| 161 |
+
from_coord = win32.COORD(0, csbi.dwCursorPosition.Y)
|
| 162 |
+
cells_to_erase = csbi.dwCursorPosition.X
|
| 163 |
+
elif mode == 2:
|
| 164 |
+
from_coord = win32.COORD(0, csbi.dwCursorPosition.Y)
|
| 165 |
+
cells_to_erase = csbi.dwSize.X
|
| 166 |
+
else:
|
| 167 |
+
# invalid mode
|
| 168 |
+
return
|
| 169 |
+
# fill the entire screen with blanks
|
| 170 |
+
win32.FillConsoleOutputCharacter(handle, ' ', cells_to_erase, from_coord)
|
| 171 |
+
# now set the buffer's attributes accordingly
|
| 172 |
+
win32.FillConsoleOutputAttribute(handle, self.get_attrs(), cells_to_erase, from_coord)
|
| 173 |
+
|
| 174 |
+
def set_title(self, title):
|
| 175 |
+
win32.SetConsoleTitle(title)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def enable_vt_processing(fd):
|
| 179 |
+
if win32.windll is None or not win32.winapi_test():
|
| 180 |
+
return False
|
| 181 |
+
|
| 182 |
+
try:
|
| 183 |
+
handle = get_osfhandle(fd)
|
| 184 |
+
mode = win32.GetConsoleMode(handle)
|
| 185 |
+
win32.SetConsoleMode(
|
| 186 |
+
handle,
|
| 187 |
+
mode | win32.ENABLE_VIRTUAL_TERMINAL_PROCESSING,
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
mode = win32.GetConsoleMode(handle)
|
| 191 |
+
if mode & win32.ENABLE_VIRTUAL_TERMINAL_PROCESSING:
|
| 192 |
+
return True
|
| 193 |
+
# Can get TypeError in testsuite where 'fd' is a Mock()
|
| 194 |
+
except (OSError, TypeError):
|
| 195 |
+
return False
|
TTS/Kokoro/.venv/Lib/site-packages/confection-0.1.5.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
pip
|
TTS/Kokoro/.venv/Lib/site-packages/confection-0.1.5.dist-info/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2019 ExplosionAI GmbH
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
TTS/Kokoro/.venv/Lib/site-packages/confection-0.1.5.dist-info/METADATA
ADDED
|
@@ -0,0 +1,416 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.1
|
| 2 |
+
Name: confection
|
| 3 |
+
Version: 0.1.5
|
| 4 |
+
Summary: The sweetest config system for Python
|
| 5 |
+
Home-page: https://github.com/explosion/confection
|
| 6 |
+
Author: Explosion
|
| 7 |
+
Author-email: contact@explosion.ai
|
| 8 |
+
License: MIT
|
| 9 |
+
Classifier: Development Status :: 5 - Production/Stable
|
| 10 |
+
Classifier: Environment :: Console
|
| 11 |
+
Classifier: Intended Audience :: Developers
|
| 12 |
+
Classifier: Intended Audience :: Science/Research
|
| 13 |
+
Classifier: License :: OSI Approved :: MIT License
|
| 14 |
+
Classifier: Operating System :: POSIX :: Linux
|
| 15 |
+
Classifier: Operating System :: MacOS :: MacOS X
|
| 16 |
+
Classifier: Operating System :: Microsoft :: Windows
|
| 17 |
+
Classifier: Programming Language :: Python :: 3
|
| 18 |
+
Classifier: Programming Language :: Python :: 3.6
|
| 19 |
+
Classifier: Programming Language :: Python :: 3.7
|
| 20 |
+
Classifier: Programming Language :: Python :: 3.8
|
| 21 |
+
Classifier: Programming Language :: Python :: 3.9
|
| 22 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 23 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 24 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 25 |
+
Classifier: Topic :: Scientific/Engineering
|
| 26 |
+
Requires-Python: >=3.6
|
| 27 |
+
Description-Content-Type: text/markdown
|
| 28 |
+
License-File: LICENSE
|
| 29 |
+
Requires-Dist: pydantic !=1.8,!=1.8.1,<3.0.0,>=1.7.4
|
| 30 |
+
Requires-Dist: srsly <3.0.0,>=2.4.0
|
| 31 |
+
Requires-Dist: typing-extensions <5.0.0,>=3.7.4.1 ; python_version < "3.8"
|
| 32 |
+
|
| 33 |
+
<a href="https://explosion.ai"><img src="https://explosion.ai/assets/img/logo.svg" width="125" height="125" align="right" /></a>
|
| 34 |
+
|
| 35 |
+
# Confection: The sweetest config system for Python
|
| 36 |
+
|
| 37 |
+
`confection` :candy: is a lightweight library that offers a **configuration
|
| 38 |
+
system** letting you conveniently describe arbitrary trees of objects.
|
| 39 |
+
|
| 40 |
+
Configuration is a huge challenge for machine-learning code because you may want
|
| 41 |
+
to expose almost any detail of any function as a hyperparameter. The setting you
|
| 42 |
+
want to expose might be arbitrarily far down in your call stack, so it might
|
| 43 |
+
need to pass all the way through the CLI or REST API, through any number of
|
| 44 |
+
intermediate functions, affecting the interface of everything along the way. And
|
| 45 |
+
then once those settings are added, they become hard to remove later. Default
|
| 46 |
+
values also become hard to change without breaking backwards compatibility.
|
| 47 |
+
|
| 48 |
+
To solve this problem, `confection` offers a config system that lets you easily
|
| 49 |
+
describe arbitrary trees of objects. The objects can be created via function
|
| 50 |
+
calls you register using a simple decorator syntax. You can even version the
|
| 51 |
+
functions you create, allowing you to make improvements without breaking
|
| 52 |
+
backwards compatibility. The most similar config system we’re aware of is
|
| 53 |
+
[Gin](https://github.com/google/gin-config), which uses a similar syntax, and
|
| 54 |
+
also allows you to link the configuration system to functions in your code using
|
| 55 |
+
a decorator. `confection`'s config system is simpler and emphasizes a different
|
| 56 |
+
workflow via a subset of Gin’s functionality.
|
| 57 |
+
|
| 58 |
+
[](https://github.com/explosion/confection/actions/workflows/tests.yml)
|
| 59 |
+
[](https://github.com/explosion/confection/releases)
|
| 60 |
+
[](https://pypi.org/project/confection/)
|
| 61 |
+
[](https://anaconda.org/conda-forge/confection)
|
| 62 |
+
[](https://github.com/ambv/black)
|
| 63 |
+
|
| 64 |
+
## ⏳ Installation
|
| 65 |
+
|
| 66 |
+
```bash
|
| 67 |
+
pip install confection
|
| 68 |
+
```
|
| 69 |
+
|
| 70 |
+
```bash
|
| 71 |
+
conda install -c conda-forge confection
|
| 72 |
+
```
|
| 73 |
+
|
| 74 |
+
## 👩💻 Usage
|
| 75 |
+
|
| 76 |
+
The configuration system parses a `.cfg` file like
|
| 77 |
+
|
| 78 |
+
```ini
|
| 79 |
+
[training]
|
| 80 |
+
patience = 10
|
| 81 |
+
dropout = 0.2
|
| 82 |
+
use_vectors = false
|
| 83 |
+
|
| 84 |
+
[training.logging]
|
| 85 |
+
level = "INFO"
|
| 86 |
+
|
| 87 |
+
[nlp]
|
| 88 |
+
# This uses the value of training.use_vectors
|
| 89 |
+
use_vectors = ${training.use_vectors}
|
| 90 |
+
lang = "en"
|
| 91 |
+
```
|
| 92 |
+
|
| 93 |
+
and resolves it to a `Dict`:
|
| 94 |
+
|
| 95 |
+
```json
|
| 96 |
+
{
|
| 97 |
+
"training": {
|
| 98 |
+
"patience": 10,
|
| 99 |
+
"dropout": 0.2,
|
| 100 |
+
"use_vectors": false,
|
| 101 |
+
"logging": {
|
| 102 |
+
"level": "INFO"
|
| 103 |
+
}
|
| 104 |
+
},
|
| 105 |
+
"nlp": {
|
| 106 |
+
"use_vectors": false,
|
| 107 |
+
"lang": "en"
|
| 108 |
+
}
|
| 109 |
+
}
|
| 110 |
+
```
|
| 111 |
+
|
| 112 |
+
The config is divided into sections, with the section name in square brackets –
|
| 113 |
+
for example, `[training]`. Within the sections, config values can be assigned to
|
| 114 |
+
keys using `=`. Values can also be referenced from other sections using the dot
|
| 115 |
+
notation and placeholders indicated by the dollar sign and curly braces. For
|
| 116 |
+
example, `${training.use_vectors}` will receive the value of use_vectors in the
|
| 117 |
+
training block. This is useful for settings that are shared across components.
|
| 118 |
+
|
| 119 |
+
The config format has three main differences from Python’s built-in
|
| 120 |
+
`configparser`:
|
| 121 |
+
|
| 122 |
+
1. JSON-formatted values. `confection` passes all values through `json.loads` to
|
| 123 |
+
interpret them. You can use atomic values like strings, floats, integers or
|
| 124 |
+
booleans, or you can use complex objects such as lists or maps.
|
| 125 |
+
2. Structured sections. `confection` uses a dot notation to build nested
|
| 126 |
+
sections. If you have a section named `[section.subsection]`, `confection`
|
| 127 |
+
will parse that into a nested structure, placing subsection within section.
|
| 128 |
+
3. References to registry functions. If a key starts with `@`, `confection` will
|
| 129 |
+
interpret its value as the name of a function registry, load the function
|
| 130 |
+
registered for that name and pass in the rest of the block as arguments. If
|
| 131 |
+
type hints are available on the function, the argument values (and return
|
| 132 |
+
value of the function) will be validated against them. This lets you express
|
| 133 |
+
complex configurations, like a training pipeline where `batch_size` is
|
| 134 |
+
populated by a function that yields floats.
|
| 135 |
+
|
| 136 |
+
There’s no pre-defined scheme you have to follow; how you set up the top-level
|
| 137 |
+
sections is up to you. At the end of it, you’ll receive a dictionary with the
|
| 138 |
+
values that you can use in your script – whether it’s complete initialized
|
| 139 |
+
functions, or just basic settings.
|
| 140 |
+
|
| 141 |
+
For instance, let’s say you want to define a new optimizer. You'd define its
|
| 142 |
+
arguments in `config.cfg` like so:
|
| 143 |
+
|
| 144 |
+
```ini
|
| 145 |
+
[optimizer]
|
| 146 |
+
@optimizers = "my_cool_optimizer.v1"
|
| 147 |
+
learn_rate = 0.001
|
| 148 |
+
gamma = 1e-8
|
| 149 |
+
```
|
| 150 |
+
|
| 151 |
+
To load and parse this configuration using a `catalogue` registry (install
|
| 152 |
+
[`catalogue`](https://github.com/explosion/catalogue) separately):
|
| 153 |
+
|
| 154 |
+
```python
|
| 155 |
+
import dataclasses
|
| 156 |
+
from typing import Union, Iterable
|
| 157 |
+
import catalogue
|
| 158 |
+
from confection import registry, Config
|
| 159 |
+
|
| 160 |
+
# Create a new registry.
|
| 161 |
+
registry.optimizers = catalogue.create("confection", "optimizers", entry_points=False)
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
# Define a dummy optimizer class.
|
| 165 |
+
@dataclasses.dataclass
|
| 166 |
+
class MyCoolOptimizer:
|
| 167 |
+
learn_rate: float
|
| 168 |
+
gamma: float
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
@registry.optimizers.register("my_cool_optimizer.v1")
|
| 172 |
+
def make_my_optimizer(learn_rate: Union[float, Iterable[float]], gamma: float):
|
| 173 |
+
return MyCoolOptimizer(learn_rate, gamma)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
# Load the config file from disk, resolve it and fetch the instantiated optimizer object.
|
| 177 |
+
config = Config().from_disk("./config.cfg")
|
| 178 |
+
resolved = registry.resolve(config)
|
| 179 |
+
optimizer = resolved["optimizer"] # MyCoolOptimizer(learn_rate=0.001, gamma=1e-08)
|
| 180 |
+
```
|
| 181 |
+
|
| 182 |
+
> ⚠️ Caution: Type-checkers such as `mypy` will mark adding new attributes to `registry` this way - i. e.
|
| 183 |
+
> `registry.new_attr = ...` - as errors. This is because a new attribute is added to the class after initialization. If
|
| 184 |
+
> you are using typecheckers, you can either ignore this (e. g. with `# type: ignore` for `mypy`) or use a typesafe
|
| 185 |
+
> alternative: instead of `registry.new_attr = ...`, use `setattr(registry, "new_attr", ...)`.
|
| 186 |
+
|
| 187 |
+
Under the hood, `confection` will look up the `"my_cool_optimizer.v1"` function
|
| 188 |
+
in the "optimizers" registry and then call it with the arguments `learn_rate`
|
| 189 |
+
and `gamma`. If the function has type annotations, it will also validate the
|
| 190 |
+
input. For instance, if `learn_rate` is annotated as a float and the config
|
| 191 |
+
defines a string, `confection` will raise an error.
|
| 192 |
+
|
| 193 |
+
The Thinc documentation offers further information on the configuration system:
|
| 194 |
+
|
| 195 |
+
- [recursive blocks](https://thinc.ai/docs/usage-config#registry-recursive)
|
| 196 |
+
- [defining variable positional arguments](https://thinc.ai/docs/usage-config#registries-args)
|
| 197 |
+
- [using interpolation](https://thinc.ai/docs/usage-config#config-interpolation)
|
| 198 |
+
- [using custom registries](https://thinc.ai/docs/usage-config#registries-custom)
|
| 199 |
+
- [advanced type annotations with Pydantic](https://thinc.ai/docs/usage-config#advanced-types)
|
| 200 |
+
- [using base schemas](https://thinc.ai/docs/usage-config#advanced-types-base-schema)
|
| 201 |
+
- [filling a configuration with defaults](https://thinc.ai/docs/usage-config#advanced-types-fill-defaults)
|
| 202 |
+
|
| 203 |
+
## 🎛 API
|
| 204 |
+
|
| 205 |
+
### <kbd>class</kbd> `Config`
|
| 206 |
+
|
| 207 |
+
This class holds the model and training
|
| 208 |
+
[configuration](https://thinc.ai/docs/usage-config) and can load and save the
|
| 209 |
+
INI-style configuration format from/to a string, file or bytes. The `Config`
|
| 210 |
+
class is a subclass of `dict` and uses Python’s `ConfigParser` under the hood.
|
| 211 |
+
|
| 212 |
+
#### <sup><kbd>method</kbd> `Config.__init__`</sup>
|
| 213 |
+
|
| 214 |
+
Initialize a new `Config` object with optional data.
|
| 215 |
+
|
| 216 |
+
```python
|
| 217 |
+
from confection import Config
|
| 218 |
+
config = Config({"training": {"patience": 10, "dropout": 0.2}})
|
| 219 |
+
```
|
| 220 |
+
|
| 221 |
+
| Argument | Type | Description |
|
| 222 |
+
| ----------------- | ----------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
| 223 |
+
| `data` | `Optional[Union[Dict[str, Any], Config]]` | Optional data to initialize the config with. |
|
| 224 |
+
| `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. |
|
| 225 |
+
| `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`. |
|
| 226 |
+
|
| 227 |
+
#### <sup><kbd>method</kbd> `Config.from_str`</sup>
|
| 228 |
+
|
| 229 |
+
Load the config from a string.
|
| 230 |
+
|
| 231 |
+
```python
|
| 232 |
+
from confection import Config
|
| 233 |
+
|
| 234 |
+
config_str = """
|
| 235 |
+
[training]
|
| 236 |
+
patience = 10
|
| 237 |
+
dropout = 0.2
|
| 238 |
+
"""
|
| 239 |
+
config = Config().from_str(config_str)
|
| 240 |
+
print(config["training"]) # {'patience': 10, 'dropout': 0.2}}
|
| 241 |
+
```
|
| 242 |
+
|
| 243 |
+
| Argument | Type | Description |
|
| 244 |
+
| ------------- | ---------------- | -------------------------------------------------------------------------------------------------------------------- |
|
| 245 |
+
| `text` | `str` | The string config to load. |
|
| 246 |
+
| `interpolate` | `bool` | Whether to interpolate variables like `${section.key}`. Defaults to `True`. |
|
| 247 |
+
| `overrides` | `Dict[str, Any]` | Overrides for values and sections. Keys are provided in dot notation, e.g. `"training.dropout"` mapped to the value. |
|
| 248 |
+
| **RETURNS** | `Config` | The loaded config. |
|
| 249 |
+
|
| 250 |
+
#### <sup><kbd>method</kbd> `Config.to_str`</sup>
|
| 251 |
+
|
| 252 |
+
Load the config from a string.
|
| 253 |
+
|
| 254 |
+
```python
|
| 255 |
+
from confection import Config
|
| 256 |
+
|
| 257 |
+
config = Config({"training": {"patience": 10, "dropout": 0.2}})
|
| 258 |
+
print(config.to_str()) # '[training]\npatience = 10\n\ndropout = 0.2'
|
| 259 |
+
```
|
| 260 |
+
|
| 261 |
+
| Argument | Type | Description |
|
| 262 |
+
| ------------- | ------ | --------------------------------------------------------------------------- |
|
| 263 |
+
| `interpolate` | `bool` | Whether to interpolate variables like `${section.key}`. Defaults to `True`. |
|
| 264 |
+
| **RETURNS** | `str` | The string config. |
|
| 265 |
+
|
| 266 |
+
#### <sup><kbd>method</kbd> `Config.to_bytes`</sup>
|
| 267 |
+
|
| 268 |
+
Serialize the config to a byte string.
|
| 269 |
+
|
| 270 |
+
```python
|
| 271 |
+
from confection import Config
|
| 272 |
+
|
| 273 |
+
config = Config({"training": {"patience": 10, "dropout": 0.2}})
|
| 274 |
+
config_bytes = config.to_bytes()
|
| 275 |
+
print(config_bytes) # b'[training]\npatience = 10\n\ndropout = 0.2'
|
| 276 |
+
```
|
| 277 |
+
|
| 278 |
+
| Argument | Type | Description |
|
| 279 |
+
| ------------- | ---------------- | -------------------------------------------------------------------------------------------------------------------- |
|
| 280 |
+
| `interpolate` | `bool` | Whether to interpolate variables like `${section.key}`. Defaults to `True`. |
|
| 281 |
+
| `overrides` | `Dict[str, Any]` | Overrides for values and sections. Keys are provided in dot notation, e.g. `"training.dropout"` mapped to the value. |
|
| 282 |
+
| **RETURNS** | `str` | The serialized config. |
|
| 283 |
+
|
| 284 |
+
#### <sup><kbd>method</kbd> `Config.from_bytes`</sup>
|
| 285 |
+
|
| 286 |
+
Load the config from a byte string.
|
| 287 |
+
|
| 288 |
+
```python
|
| 289 |
+
from confection import Config
|
| 290 |
+
|
| 291 |
+
config = Config({"training": {"patience": 10, "dropout": 0.2}})
|
| 292 |
+
config_bytes = config.to_bytes()
|
| 293 |
+
new_config = Config().from_bytes(config_bytes)
|
| 294 |
+
```
|
| 295 |
+
|
| 296 |
+
| Argument | Type | Description |
|
| 297 |
+
| ------------- | -------- | --------------------------------------------------------------------------- |
|
| 298 |
+
| `bytes_data` | `bool` | The data to load. |
|
| 299 |
+
| `interpolate` | `bool` | Whether to interpolate variables like `${section.key}`. Defaults to `True`. |
|
| 300 |
+
| **RETURNS** | `Config` | The loaded config. |
|
| 301 |
+
|
| 302 |
+
#### <sup><kbd>method</kbd> `Config.to_disk`</sup>
|
| 303 |
+
|
| 304 |
+
Serialize the config to a file.
|
| 305 |
+
|
| 306 |
+
```python
|
| 307 |
+
from confection import Config
|
| 308 |
+
|
| 309 |
+
config = Config({"training": {"patience": 10, "dropout": 0.2}})
|
| 310 |
+
config.to_disk("./config.cfg")
|
| 311 |
+
```
|
| 312 |
+
|
| 313 |
+
| Argument | Type | Description |
|
| 314 |
+
| ------------- | ------------------ | --------------------------------------------------------------------------- |
|
| 315 |
+
| `path` | `Union[Path, str]` | The file path. |
|
| 316 |
+
| `interpolate` | `bool` | Whether to interpolate variables like `${section.key}`. Defaults to `True`. |
|
| 317 |
+
|
| 318 |
+
#### <sup><kbd>method</kbd> `Config.from_disk`</sup>
|
| 319 |
+
|
| 320 |
+
Load the config from a file.
|
| 321 |
+
|
| 322 |
+
```python
|
| 323 |
+
from confection import Config
|
| 324 |
+
|
| 325 |
+
config = Config({"training": {"patience": 10, "dropout": 0.2}})
|
| 326 |
+
config.to_disk("./config.cfg")
|
| 327 |
+
new_config = Config().from_disk("./config.cfg")
|
| 328 |
+
```
|
| 329 |
+
|
| 330 |
+
| Argument | Type | Description |
|
| 331 |
+
| ------------- | ------------------ | -------------------------------------------------------------------------------------------------------------------- |
|
| 332 |
+
| `path` | `Union[Path, str]` | The file path. |
|
| 333 |
+
| `interpolate` | `bool` | Whether to interpolate variables like `${section.key}`. Defaults to `True`. |
|
| 334 |
+
| `overrides` | `Dict[str, Any]` | Overrides for values and sections. Keys are provided in dot notation, e.g. `"training.dropout"` mapped to the value. |
|
| 335 |
+
| **RETURNS** | `Config` | The loaded config. |
|
| 336 |
+
|
| 337 |
+
#### <sup><kbd>method</kbd> `Config.copy`</sup>
|
| 338 |
+
|
| 339 |
+
Deep-copy the config.
|
| 340 |
+
|
| 341 |
+
| Argument | Type | Description |
|
| 342 |
+
| ----------- | -------- | ------------------ |
|
| 343 |
+
| **RETURNS** | `Config` | The copied config. |
|
| 344 |
+
|
| 345 |
+
#### <sup><kbd>method</kbd> `Config.interpolate`</sup>
|
| 346 |
+
|
| 347 |
+
Interpolate variables like `${section.value}` or `${section.subsection}` and
|
| 348 |
+
return a copy of the config with interpolated values. Can be used if a config is
|
| 349 |
+
loaded with `interpolate=False`, e.g. via `Config.from_str`.
|
| 350 |
+
|
| 351 |
+
```python
|
| 352 |
+
from confection import Config
|
| 353 |
+
|
| 354 |
+
config_str = """
|
| 355 |
+
[hyper_params]
|
| 356 |
+
dropout = 0.2
|
| 357 |
+
|
| 358 |
+
[training]
|
| 359 |
+
dropout = ${hyper_params.dropout}
|
| 360 |
+
"""
|
| 361 |
+
config = Config().from_str(config_str, interpolate=False)
|
| 362 |
+
print(config["training"]) # {'dropout': '${hyper_params.dropout}'}}
|
| 363 |
+
config = config.interpolate()
|
| 364 |
+
print(config["training"]) # {'dropout': 0.2}}
|
| 365 |
+
```
|
| 366 |
+
|
| 367 |
+
| Argument | Type | Description |
|
| 368 |
+
| ----------- | -------- | ---------------------------------------------- |
|
| 369 |
+
| **RETURNS** | `Config` | A copy of the config with interpolated values. |
|
| 370 |
+
|
| 371 |
+
##### <sup><kbd>method</kbd> `Config.merge`</sup>
|
| 372 |
+
|
| 373 |
+
Deep-merge two config objects, using the current config as the default. Only
|
| 374 |
+
merges sections and dictionaries and not other values like lists. Values that
|
| 375 |
+
are provided in the updates are overwritten in the base config, and any new
|
| 376 |
+
values or sections are added. If a config value is a variable like
|
| 377 |
+
`${section.key}` (e.g. if the config was loaded with `interpolate=False)`, **the
|
| 378 |
+
variable is preferred**, even if the updates provide a different value. This
|
| 379 |
+
ensures that variable references aren’t destroyed by a merge.
|
| 380 |
+
|
| 381 |
+
> :warning: Note that blocks that refer to registered functions using the `@`
|
| 382 |
+
> syntax are only merged if they are referring to the same functions. Otherwise,
|
| 383 |
+
> merging could easily produce invalid configs, since different functions can
|
| 384 |
+
> take different arguments. If a block refers to a different function, it’s
|
| 385 |
+
> overwritten.
|
| 386 |
+
|
| 387 |
+
```python
|
| 388 |
+
from confection import Config
|
| 389 |
+
|
| 390 |
+
base_config_str = """
|
| 391 |
+
[training]
|
| 392 |
+
patience = 10
|
| 393 |
+
dropout = 0.2
|
| 394 |
+
"""
|
| 395 |
+
update_config_str = """
|
| 396 |
+
[training]
|
| 397 |
+
dropout = 0.1
|
| 398 |
+
max_epochs = 2000
|
| 399 |
+
"""
|
| 400 |
+
|
| 401 |
+
base_config = Config().from_str(base_config_str)
|
| 402 |
+
update_config = Config().from_str(update_config_str)
|
| 403 |
+
merged = Config(base_config).merge(update_config)
|
| 404 |
+
print(merged["training"]) # {'patience': 10, 'dropout': 0.1, 'max_epochs': 2000}
|
| 405 |
+
```
|
| 406 |
+
|
| 407 |
+
| Argument | Type | Description |
|
| 408 |
+
| ----------- | ------------------------------- | --------------------------------------------------- |
|
| 409 |
+
| `overrides` | `Union[Dict[str, Any], Config]` | The updates to merge into the config. |
|
| 410 |
+
| **RETURNS** | `Config` | A new config instance containing the merged config. |
|
| 411 |
+
|
| 412 |
+
### Config Attributes
|
| 413 |
+
|
| 414 |
+
| Argument | Type | Description |
|
| 415 |
+
| ----------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
| 416 |
+
| `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`. |
|
TTS/Kokoro/.venv/Lib/site-packages/confection-0.1.5.dist-info/RECORD
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
confection-0.1.5.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
| 2 |
+
confection-0.1.5.dist-info/LICENSE,sha256=9_dOqC-aENfOK6Bd1-RgyMK7QqbMfZrnGrNWYbX3HJs,1073
|
| 3 |
+
confection-0.1.5.dist-info/METADATA,sha256=E4IAhPzCjN22pZCJlF2sfzw02BfE3kchnaZhv-H_ulM,19597
|
| 4 |
+
confection-0.1.5.dist-info/RECORD,,
|
| 5 |
+
confection-0.1.5.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
|
| 6 |
+
confection-0.1.5.dist-info/top_level.txt,sha256=IW0MglPluqVnP26bD2x7YDauBNEgafciyjlKd7s2dzM,11
|
| 7 |
+
confection-0.1.5.dist-info/zip-safe,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
|
| 8 |
+
confection/__init__.py,sha256=wuhtsxT6aFk0XEou9P-MmxInKUS5a7eEghCIyvbXYHs,47656
|
| 9 |
+
confection/__pycache__/__init__.cpython-312.pyc,,
|
| 10 |
+
confection/__pycache__/util.cpython-312.pyc,,
|
| 11 |
+
confection/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 12 |
+
confection/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 13 |
+
confection/tests/__pycache__/__init__.cpython-312.pyc,,
|
| 14 |
+
confection/tests/__pycache__/conftest.cpython-312.pyc,,
|
| 15 |
+
confection/tests/__pycache__/test_config.cpython-312.pyc,,
|
| 16 |
+
confection/tests/__pycache__/test_frozen_structures.cpython-312.pyc,,
|
| 17 |
+
confection/tests/__pycache__/util.cpython-312.pyc,,
|
| 18 |
+
confection/tests/conftest.py,sha256=06QImBbGxE7pAv3x8JMehJN9xvGD8Y9n71MhYQIMN2Y,489
|
| 19 |
+
confection/tests/test_config.py,sha256=pknGSLihotM7iLi0KYeCfOTx1uHWxaXcKWCyjxzLY_I,54505
|
| 20 |
+
confection/tests/test_frozen_structures.py,sha256=OJyqk-xY4hu8yDrAbX8cSpvA9FlLpl49GISh1cmQ2cY,1713
|
| 21 |
+
confection/tests/util.py,sha256=CSUh9wOm5OMAdjbDP4vDT0GOdHGT8RgYCq8CUhx1SLk,3686
|
| 22 |
+
confection/util.py,sha256=0iohHQdDgFd8ec57mhj41zA7wihKvTPcXKLv7JoKLbo,4300
|
TTS/Kokoro/.venv/Lib/site-packages/confection-0.1.5.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: bdist_wheel (0.43.0)
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py3-none-any
|
| 5 |
+
|
TTS/Kokoro/.venv/Lib/site-packages/confection-0.1.5.dist-info/top_level.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
confection
|
TTS/Kokoro/.venv/Lib/site-packages/confection-0.1.5.dist-info/zip-safe
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
|
TTS/Kokoro/.venv/Lib/site-packages/confection/__init__.py
ADDED
|
@@ -0,0 +1,1095 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy
|
| 2 |
+
import inspect
|
| 3 |
+
import io
|
| 4 |
+
import re
|
| 5 |
+
import warnings
|
| 6 |
+
from configparser import (
|
| 7 |
+
MAX_INTERPOLATION_DEPTH,
|
| 8 |
+
ConfigParser,
|
| 9 |
+
ExtendedInterpolation,
|
| 10 |
+
InterpolationDepthError,
|
| 11 |
+
InterpolationMissingOptionError,
|
| 12 |
+
InterpolationSyntaxError,
|
| 13 |
+
NoOptionError,
|
| 14 |
+
NoSectionError,
|
| 15 |
+
ParsingError,
|
| 16 |
+
)
|
| 17 |
+
from dataclasses import dataclass
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
from types import GeneratorType
|
| 20 |
+
from typing import (
|
| 21 |
+
Any,
|
| 22 |
+
Callable,
|
| 23 |
+
Dict,
|
| 24 |
+
Iterable,
|
| 25 |
+
List,
|
| 26 |
+
Mapping,
|
| 27 |
+
Optional,
|
| 28 |
+
Sequence,
|
| 29 |
+
Tuple,
|
| 30 |
+
Type,
|
| 31 |
+
Union,
|
| 32 |
+
cast,
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
import srsly
|
| 36 |
+
|
| 37 |
+
try:
|
| 38 |
+
from pydantic.v1 import BaseModel, Extra, ValidationError, create_model
|
| 39 |
+
from pydantic.v1.fields import ModelField
|
| 40 |
+
from pydantic.v1.main import ModelMetaclass
|
| 41 |
+
except ImportError:
|
| 42 |
+
from pydantic import BaseModel, create_model, ValidationError, Extra # type: ignore
|
| 43 |
+
from pydantic.main import ModelMetaclass # type: ignore
|
| 44 |
+
from pydantic.fields import ModelField # type: ignore
|
| 45 |
+
|
| 46 |
+
from .util import SimpleFrozenDict, SimpleFrozenList # noqa: F401
|
| 47 |
+
|
| 48 |
+
# Field used for positional arguments, e.g. [section.*.xyz]. The alias is
|
| 49 |
+
# required for the schema (shouldn't clash with user-defined arg names)
|
| 50 |
+
ARGS_FIELD = "*"
|
| 51 |
+
ARGS_FIELD_ALIAS = "VARIABLE_POSITIONAL_ARGS"
|
| 52 |
+
# Aliases for fields that would otherwise shadow pydantic attributes. Can be any
|
| 53 |
+
# string, so we're using name + space so it looks the same in error messages etc.
|
| 54 |
+
RESERVED_FIELDS = {"validate": "validate\u0020"}
|
| 55 |
+
# Internal prefix used to mark section references for custom interpolation
|
| 56 |
+
SECTION_PREFIX = "__SECTION__:"
|
| 57 |
+
# Values that shouldn't be loaded during interpolation because it'd cause
|
| 58 |
+
# even explicit string values to be incorrectly parsed as bools/None etc.
|
| 59 |
+
JSON_EXCEPTIONS = ("true", "false", "null")
|
| 60 |
+
# Regex to detect whether a value contains a variable
|
| 61 |
+
VARIABLE_RE = re.compile(r"\$\{[\w\.:]+\}")
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class CustomInterpolation(ExtendedInterpolation):
|
| 65 |
+
def before_read(self, parser, section, option, value):
|
| 66 |
+
# If we're dealing with a quoted string as the interpolation value,
|
| 67 |
+
# make sure we load and unquote it so we don't end up with '"value"'
|
| 68 |
+
try:
|
| 69 |
+
json_value = srsly.json_loads(value)
|
| 70 |
+
if isinstance(json_value, str) and json_value not in JSON_EXCEPTIONS:
|
| 71 |
+
value = json_value
|
| 72 |
+
except ValueError:
|
| 73 |
+
if value and value[0] == value[-1] == "'":
|
| 74 |
+
warnings.warn(
|
| 75 |
+
f"The value [{value}] seems to be single-quoted, but values "
|
| 76 |
+
"use JSON formatting, which requires double quotes."
|
| 77 |
+
)
|
| 78 |
+
except Exception:
|
| 79 |
+
pass
|
| 80 |
+
return super().before_read(parser, section, option, value)
|
| 81 |
+
|
| 82 |
+
def before_get(self, parser, section, option, value, defaults):
|
| 83 |
+
# Mostly copy-pasted from the built-in configparser implementation.
|
| 84 |
+
L = []
|
| 85 |
+
self.interpolate(parser, option, L, value, section, defaults, 1)
|
| 86 |
+
return "".join(L)
|
| 87 |
+
|
| 88 |
+
def interpolate(self, parser, option, accum, rest, section, map, depth):
|
| 89 |
+
# Mostly copy-pasted from the built-in configparser implementation.
|
| 90 |
+
# We need to overwrite this method so we can add special handling for
|
| 91 |
+
# block references :( All values produced here should be strings –
|
| 92 |
+
# we need to wait until the whole config is interpreted anyways so
|
| 93 |
+
# filling in incomplete values here is pointless. All we need is the
|
| 94 |
+
# section reference so we can fetch it later.
|
| 95 |
+
rawval = parser.get(section, option, raw=True, fallback=rest)
|
| 96 |
+
if depth > MAX_INTERPOLATION_DEPTH:
|
| 97 |
+
raise InterpolationDepthError(option, section, rawval)
|
| 98 |
+
while rest:
|
| 99 |
+
p = rest.find("$")
|
| 100 |
+
if p < 0:
|
| 101 |
+
accum.append(rest)
|
| 102 |
+
return
|
| 103 |
+
if p > 0:
|
| 104 |
+
accum.append(rest[:p])
|
| 105 |
+
rest = rest[p:]
|
| 106 |
+
# p is no longer used
|
| 107 |
+
c = rest[1:2]
|
| 108 |
+
if c == "$":
|
| 109 |
+
accum.append("$")
|
| 110 |
+
rest = rest[2:]
|
| 111 |
+
elif c == "{":
|
| 112 |
+
# We want to treat both ${a:b} and ${a.b} the same
|
| 113 |
+
m = self._KEYCRE.match(rest)
|
| 114 |
+
if m is None:
|
| 115 |
+
err = f"bad interpolation variable reference {rest}"
|
| 116 |
+
raise InterpolationSyntaxError(option, section, err)
|
| 117 |
+
orig_var = m.group(1)
|
| 118 |
+
path = orig_var.replace(":", ".").rsplit(".", 1)
|
| 119 |
+
rest = rest[m.end() :]
|
| 120 |
+
sect = section
|
| 121 |
+
opt = option
|
| 122 |
+
try:
|
| 123 |
+
if len(path) == 1:
|
| 124 |
+
opt = parser.optionxform(path[0])
|
| 125 |
+
if opt in map:
|
| 126 |
+
v = map[opt]
|
| 127 |
+
else:
|
| 128 |
+
# We have block reference, store it as a special key
|
| 129 |
+
section_name = parser[parser.optionxform(path[0])]._name
|
| 130 |
+
v = self._get_section_name(section_name)
|
| 131 |
+
elif len(path) == 2:
|
| 132 |
+
sect = path[0]
|
| 133 |
+
opt = parser.optionxform(path[1])
|
| 134 |
+
fallback = "__FALLBACK__"
|
| 135 |
+
v = parser.get(sect, opt, raw=True, fallback=fallback)
|
| 136 |
+
# If a variable doesn't exist, try again and treat the
|
| 137 |
+
# reference as a section
|
| 138 |
+
if v == fallback:
|
| 139 |
+
v = self._get_section_name(parser[f"{sect}.{opt}"]._name)
|
| 140 |
+
else:
|
| 141 |
+
err = f"More than one ':' found: {rest}"
|
| 142 |
+
raise InterpolationSyntaxError(option, section, err)
|
| 143 |
+
except (KeyError, NoSectionError, NoOptionError):
|
| 144 |
+
raise InterpolationMissingOptionError(
|
| 145 |
+
option, section, rawval, orig_var
|
| 146 |
+
) from None
|
| 147 |
+
if "$" in v:
|
| 148 |
+
new_map = dict(parser.items(sect, raw=True))
|
| 149 |
+
self.interpolate(parser, opt, accum, v, sect, new_map, depth + 1)
|
| 150 |
+
else:
|
| 151 |
+
accum.append(v)
|
| 152 |
+
else:
|
| 153 |
+
err = "'$' must be followed by '$' or '{', found: %r" % (rest,)
|
| 154 |
+
raise InterpolationSyntaxError(option, section, err)
|
| 155 |
+
|
| 156 |
+
def _get_section_name(self, name: str) -> str:
|
| 157 |
+
"""Generate the name of a section. Note that we use a quoted string here
|
| 158 |
+
so we can use section references within lists and load the list as
|
| 159 |
+
JSON. Since section references can't be used within strings, we don't
|
| 160 |
+
need the quoted vs. unquoted distinction like we do for variables.
|
| 161 |
+
|
| 162 |
+
Examples (assuming section = {"foo": 1}):
|
| 163 |
+
- value: ${section.foo} -> value: 1
|
| 164 |
+
- value: "hello ${section.foo}" -> value: "hello 1"
|
| 165 |
+
- value: ${section} -> value: {"foo": 1}
|
| 166 |
+
- value: "${section}" -> value: {"foo": 1}
|
| 167 |
+
- value: "hello ${section}" -> invalid
|
| 168 |
+
"""
|
| 169 |
+
return f'"{SECTION_PREFIX}{name}"'
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def get_configparser(interpolate: bool = True):
|
| 173 |
+
config = ConfigParser(interpolation=CustomInterpolation() if interpolate else None)
|
| 174 |
+
# Preserve case of keys: https://stackoverflow.com/a/1611877/6400719
|
| 175 |
+
config.optionxform = str # type: ignore
|
| 176 |
+
return config
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
class Config(dict):
|
| 180 |
+
"""This class holds the model and training configuration and can load and
|
| 181 |
+
save the TOML-style configuration format from/to a string, file or bytes.
|
| 182 |
+
The Config class is a subclass of dict and uses Python's ConfigParser
|
| 183 |
+
under the hood.
|
| 184 |
+
"""
|
| 185 |
+
|
| 186 |
+
is_interpolated: bool
|
| 187 |
+
|
| 188 |
+
def __init__(
|
| 189 |
+
self,
|
| 190 |
+
data: Optional[Union[Dict[str, Any], "ConfigParser", "Config"]] = None,
|
| 191 |
+
*,
|
| 192 |
+
is_interpolated: Optional[bool] = None,
|
| 193 |
+
section_order: Optional[List[str]] = None,
|
| 194 |
+
) -> None:
|
| 195 |
+
"""Initialize a new Config object with optional data."""
|
| 196 |
+
dict.__init__(self)
|
| 197 |
+
if data is None:
|
| 198 |
+
data = {}
|
| 199 |
+
if not isinstance(data, (dict, Config, ConfigParser)):
|
| 200 |
+
raise ValueError(
|
| 201 |
+
f"Can't initialize Config with data. Expected dict, Config or "
|
| 202 |
+
f"ConfigParser but got: {type(data)}"
|
| 203 |
+
)
|
| 204 |
+
# Whether the config has been interpolated. We can use this to check
|
| 205 |
+
# whether we need to interpolate again when it's resolved. We assume
|
| 206 |
+
# that a config is interpolated by default.
|
| 207 |
+
if is_interpolated is not None:
|
| 208 |
+
self.is_interpolated = is_interpolated
|
| 209 |
+
elif isinstance(data, Config):
|
| 210 |
+
self.is_interpolated = data.is_interpolated
|
| 211 |
+
else:
|
| 212 |
+
self.is_interpolated = True
|
| 213 |
+
if section_order is not None:
|
| 214 |
+
self.section_order = section_order
|
| 215 |
+
elif isinstance(data, Config):
|
| 216 |
+
self.section_order = data.section_order
|
| 217 |
+
else:
|
| 218 |
+
self.section_order = []
|
| 219 |
+
# Update with data
|
| 220 |
+
self.update(self._sort(data))
|
| 221 |
+
|
| 222 |
+
def interpolate(self) -> "Config":
|
| 223 |
+
"""Interpolate a config. Returns a copy of the object."""
|
| 224 |
+
# This is currently the most effective way because we need our custom
|
| 225 |
+
# to_str logic to run in order to re-serialize the values so we can
|
| 226 |
+
# interpolate them again. ConfigParser.read_dict will just call str()
|
| 227 |
+
# on all values, which isn't enough.
|
| 228 |
+
return Config().from_str(self.to_str())
|
| 229 |
+
|
| 230 |
+
def interpret_config(self, config: "ConfigParser") -> None:
|
| 231 |
+
"""Interpret a config, parse nested sections and parse the values
|
| 232 |
+
as JSON. Mostly used internally and modifies the config in place.
|
| 233 |
+
"""
|
| 234 |
+
self._validate_sections(config)
|
| 235 |
+
# Sort sections by depth, so that we can iterate breadth-first. This
|
| 236 |
+
# allows us to check that we're not expanding an undefined block.
|
| 237 |
+
get_depth = lambda item: len(item[0].split("."))
|
| 238 |
+
for section, values in sorted(config.items(), key=get_depth):
|
| 239 |
+
if section == "DEFAULT":
|
| 240 |
+
# Skip [DEFAULT] section so it doesn't cause validation error
|
| 241 |
+
continue
|
| 242 |
+
parts = section.split(".")
|
| 243 |
+
node = self
|
| 244 |
+
for part in parts[:-1]:
|
| 245 |
+
if part == "*":
|
| 246 |
+
node = node.setdefault(part, {})
|
| 247 |
+
elif part not in node:
|
| 248 |
+
err_title = (
|
| 249 |
+
"Error parsing config section. Perhaps a section name is wrong?"
|
| 250 |
+
)
|
| 251 |
+
err = [{"loc": parts, "msg": f"Section '{part}' is not defined"}]
|
| 252 |
+
raise ConfigValidationError(
|
| 253 |
+
config=self, errors=err, title=err_title
|
| 254 |
+
)
|
| 255 |
+
else:
|
| 256 |
+
node = node[part]
|
| 257 |
+
if not isinstance(node, dict):
|
| 258 |
+
# Happens if both value *and* subsection were defined for a key
|
| 259 |
+
err = [{"loc": parts, "msg": "found conflicting values"}]
|
| 260 |
+
err_cfg = f"{self}\n{({part: dict(values)})}"
|
| 261 |
+
raise ConfigValidationError(config=err_cfg, errors=err)
|
| 262 |
+
# Set the default section
|
| 263 |
+
node = node.setdefault(parts[-1], {})
|
| 264 |
+
if not isinstance(node, dict):
|
| 265 |
+
# Happens if both value *and* subsection were defined for a key
|
| 266 |
+
err = [{"loc": parts, "msg": "found conflicting values"}]
|
| 267 |
+
err_cfg = f"{self}\n{({part: dict(values)})}"
|
| 268 |
+
raise ConfigValidationError(config=err_cfg, errors=err)
|
| 269 |
+
try:
|
| 270 |
+
keys_values = list(values.items())
|
| 271 |
+
except InterpolationMissingOptionError as e:
|
| 272 |
+
raise ConfigValidationError(desc=f"{e}") from None
|
| 273 |
+
for key, value in keys_values:
|
| 274 |
+
config_v = config.get(section, key)
|
| 275 |
+
node[key] = self._interpret_value(config_v)
|
| 276 |
+
self.replace_section_refs(self)
|
| 277 |
+
|
| 278 |
+
def replace_section_refs(
|
| 279 |
+
self, config: Union[Dict[str, Any], "Config"], parent: str = ""
|
| 280 |
+
) -> None:
|
| 281 |
+
"""Replace references to section blocks in the final config."""
|
| 282 |
+
for key, value in config.items():
|
| 283 |
+
key_parent = f"{parent}.{key}".strip(".")
|
| 284 |
+
if isinstance(value, dict):
|
| 285 |
+
self.replace_section_refs(value, parent=key_parent)
|
| 286 |
+
elif isinstance(value, list):
|
| 287 |
+
config[key] = [
|
| 288 |
+
self._get_section_ref(v, parent=[parent, key]) for v in value
|
| 289 |
+
]
|
| 290 |
+
else:
|
| 291 |
+
config[key] = self._get_section_ref(value, parent=[parent, key])
|
| 292 |
+
|
| 293 |
+
def _interpret_value(self, value: Any) -> Any:
|
| 294 |
+
"""Interpret a single config value."""
|
| 295 |
+
result = try_load_json(value)
|
| 296 |
+
# If value is a string and it contains a variable, use original value
|
| 297 |
+
# (not interpreted string, which could lead to double quotes:
|
| 298 |
+
# ${x.y} -> "${x.y}" -> "'${x.y}'"). Make sure to check it's a string,
|
| 299 |
+
# so we're not keeping lists as strings.
|
| 300 |
+
# NOTE: This currently can't handle uninterpolated values like [${x.y}]!
|
| 301 |
+
if isinstance(result, str) and VARIABLE_RE.search(value):
|
| 302 |
+
result = value
|
| 303 |
+
return result
|
| 304 |
+
|
| 305 |
+
def _get_section_ref(self, value: Any, *, parent: List[str] = []) -> Any:
|
| 306 |
+
"""Get a single section reference."""
|
| 307 |
+
if isinstance(value, str) and value.startswith(f'"{SECTION_PREFIX}'):
|
| 308 |
+
value = try_load_json(value)
|
| 309 |
+
if isinstance(value, str) and value.startswith(SECTION_PREFIX):
|
| 310 |
+
parts = value.replace(SECTION_PREFIX, "").split(".")
|
| 311 |
+
result = self
|
| 312 |
+
for item in parts:
|
| 313 |
+
try:
|
| 314 |
+
result = result[item]
|
| 315 |
+
except (KeyError, TypeError): # This should never happen
|
| 316 |
+
err_title = "Error parsing reference to config section"
|
| 317 |
+
err_msg = f"Section '{'.'.join(parts)}' is not defined"
|
| 318 |
+
err = [{"loc": parts, "msg": err_msg}]
|
| 319 |
+
raise ConfigValidationError(
|
| 320 |
+
config=self, errors=err, title=err_title
|
| 321 |
+
) from None
|
| 322 |
+
return result
|
| 323 |
+
elif isinstance(value, str) and SECTION_PREFIX in value:
|
| 324 |
+
# String value references a section (either a dict or return
|
| 325 |
+
# value of promise). We can't allow this, since variables are
|
| 326 |
+
# always interpolated *before* configs are resolved.
|
| 327 |
+
err_desc = (
|
| 328 |
+
"Can't reference whole sections or return values of function "
|
| 329 |
+
"blocks inside a string or list\n\nYou can change your variable to "
|
| 330 |
+
"reference a value instead. Keep in mind that it's not "
|
| 331 |
+
"possible to interpolate the return value of a registered "
|
| 332 |
+
"function, since variables are interpolated when the config "
|
| 333 |
+
"is loaded, and registered functions are resolved afterwards."
|
| 334 |
+
)
|
| 335 |
+
err = [{"loc": parent, "msg": "uses section variable in string or list"}]
|
| 336 |
+
raise ConfigValidationError(errors=err, desc=err_desc)
|
| 337 |
+
return value
|
| 338 |
+
|
| 339 |
+
def copy(self) -> "Config":
|
| 340 |
+
"""Deepcopy the config."""
|
| 341 |
+
try:
|
| 342 |
+
config = copy.deepcopy(self)
|
| 343 |
+
except Exception as e:
|
| 344 |
+
raise ValueError(f"Couldn't deep-copy config: {e}") from e
|
| 345 |
+
return Config(
|
| 346 |
+
config,
|
| 347 |
+
is_interpolated=self.is_interpolated,
|
| 348 |
+
section_order=self.section_order,
|
| 349 |
+
)
|
| 350 |
+
|
| 351 |
+
def merge(
|
| 352 |
+
self, updates: Union[Dict[str, Any], "Config"], remove_extra: bool = False
|
| 353 |
+
) -> "Config":
|
| 354 |
+
"""Deep merge the config with updates, using current as defaults."""
|
| 355 |
+
defaults = self.copy()
|
| 356 |
+
updates = Config(updates).copy()
|
| 357 |
+
merged = deep_merge_configs(updates, defaults, remove_extra=remove_extra)
|
| 358 |
+
return Config(
|
| 359 |
+
merged,
|
| 360 |
+
is_interpolated=defaults.is_interpolated and updates.is_interpolated,
|
| 361 |
+
section_order=defaults.section_order,
|
| 362 |
+
)
|
| 363 |
+
|
| 364 |
+
def _sort(
|
| 365 |
+
self, data: Union["Config", "ConfigParser", Dict[str, Any]]
|
| 366 |
+
) -> Dict[str, Any]:
|
| 367 |
+
"""Sort sections using the currently defined sort order. Sort
|
| 368 |
+
sections by index on section order, if available, then alphabetic, and
|
| 369 |
+
account for subsections, which should always follow their parent.
|
| 370 |
+
"""
|
| 371 |
+
sort_map = {section: i for i, section in enumerate(self.section_order)}
|
| 372 |
+
sort_key = lambda x: (
|
| 373 |
+
sort_map.get(x[0].split(".")[0], len(sort_map)),
|
| 374 |
+
_mask_positional_args(x[0]),
|
| 375 |
+
)
|
| 376 |
+
return dict(sorted(data.items(), key=sort_key))
|
| 377 |
+
|
| 378 |
+
def _set_overrides(self, config: "ConfigParser", overrides: Dict[str, Any]) -> None:
|
| 379 |
+
"""Set overrides in the ConfigParser before config is interpreted."""
|
| 380 |
+
err_title = "Error parsing config overrides"
|
| 381 |
+
for key, value in overrides.items():
|
| 382 |
+
err_msg = "not a section value that can be overridden"
|
| 383 |
+
err = [{"loc": key.split("."), "msg": err_msg}]
|
| 384 |
+
if "." not in key:
|
| 385 |
+
raise ConfigValidationError(errors=err, title=err_title)
|
| 386 |
+
section, option = key.rsplit(".", 1)
|
| 387 |
+
# Check for section and accept if option not in config[section]
|
| 388 |
+
if section not in config:
|
| 389 |
+
raise ConfigValidationError(errors=err, title=err_title)
|
| 390 |
+
config.set(section, option, try_dump_json(value, overrides))
|
| 391 |
+
|
| 392 |
+
def _validate_sections(self, config: "ConfigParser") -> None:
|
| 393 |
+
# If the config defines top-level properties that are not sections (e.g.
|
| 394 |
+
# if config was constructed from dict), those values would be added as
|
| 395 |
+
# [DEFAULTS] and included in *every other section*. This is usually not
|
| 396 |
+
# what we want and it can lead to very confusing results.
|
| 397 |
+
default_section = config.defaults()
|
| 398 |
+
if default_section:
|
| 399 |
+
err_title = "Found config values without a top-level section"
|
| 400 |
+
err_msg = "not part of a section"
|
| 401 |
+
err = [{"loc": [k], "msg": err_msg} for k in default_section]
|
| 402 |
+
raise ConfigValidationError(errors=err, title=err_title)
|
| 403 |
+
|
| 404 |
+
def from_str(
|
| 405 |
+
self, text: str, *, interpolate: bool = True, overrides: Dict[str, Any] = {}
|
| 406 |
+
) -> "Config":
|
| 407 |
+
"""Load the config from a string."""
|
| 408 |
+
config = get_configparser(interpolate=interpolate)
|
| 409 |
+
if overrides:
|
| 410 |
+
config = get_configparser(interpolate=False)
|
| 411 |
+
try:
|
| 412 |
+
config.read_string(text)
|
| 413 |
+
except ParsingError as e:
|
| 414 |
+
desc = f"Make sure the sections and values are formatted correctly.\n\n{e}"
|
| 415 |
+
raise ConfigValidationError(desc=desc) from None
|
| 416 |
+
config._sections = self._sort(config._sections)
|
| 417 |
+
self._set_overrides(config, overrides)
|
| 418 |
+
self.clear()
|
| 419 |
+
self.interpret_config(config)
|
| 420 |
+
if overrides and interpolate:
|
| 421 |
+
# do the interpolation. Avoids recursion because the new call from_str call will have overrides as empty
|
| 422 |
+
self = self.interpolate()
|
| 423 |
+
self.is_interpolated = interpolate
|
| 424 |
+
return self
|
| 425 |
+
|
| 426 |
+
def to_str(self, *, interpolate: bool = True) -> str:
|
| 427 |
+
"""Write the config to a string."""
|
| 428 |
+
flattened = get_configparser(interpolate=interpolate)
|
| 429 |
+
queue: List[Tuple[tuple, "Config"]] = [(tuple(), self)]
|
| 430 |
+
for path, node in queue:
|
| 431 |
+
section_name = ".".join(path)
|
| 432 |
+
is_kwarg = path and path[-1] != "*"
|
| 433 |
+
if is_kwarg and not flattened.has_section(section_name):
|
| 434 |
+
# Always create sections for non-'*' sections, not only if
|
| 435 |
+
# they have leaf entries, as we don't want to expand
|
| 436 |
+
# blocks that are undefined
|
| 437 |
+
flattened.add_section(section_name)
|
| 438 |
+
for key, value in node.items():
|
| 439 |
+
if hasattr(value, "items"):
|
| 440 |
+
# Reference to a function with no arguments, serialize
|
| 441 |
+
# inline as a dict and don't create new section
|
| 442 |
+
if registry.is_promise(value) and len(value) == 1 and is_kwarg:
|
| 443 |
+
flattened.set(section_name, key, try_dump_json(value, node))
|
| 444 |
+
else:
|
| 445 |
+
queue.append((path + (key,), value))
|
| 446 |
+
else:
|
| 447 |
+
flattened.set(section_name, key, try_dump_json(value, node))
|
| 448 |
+
# Order so subsection follow parent (not all sections, then all subs etc.)
|
| 449 |
+
flattened._sections = self._sort(flattened._sections)
|
| 450 |
+
self._validate_sections(flattened)
|
| 451 |
+
string_io = io.StringIO()
|
| 452 |
+
flattened.write(string_io)
|
| 453 |
+
return string_io.getvalue().strip()
|
| 454 |
+
|
| 455 |
+
def to_bytes(self, *, interpolate: bool = True) -> bytes:
|
| 456 |
+
"""Serialize the config to a byte string."""
|
| 457 |
+
return self.to_str(interpolate=interpolate).encode("utf8")
|
| 458 |
+
|
| 459 |
+
def from_bytes(
|
| 460 |
+
self,
|
| 461 |
+
bytes_data: bytes,
|
| 462 |
+
*,
|
| 463 |
+
interpolate: bool = True,
|
| 464 |
+
overrides: Dict[str, Any] = {},
|
| 465 |
+
) -> "Config":
|
| 466 |
+
"""Load the config from a byte string."""
|
| 467 |
+
return self.from_str(
|
| 468 |
+
bytes_data.decode("utf8"), interpolate=interpolate, overrides=overrides
|
| 469 |
+
)
|
| 470 |
+
|
| 471 |
+
def to_disk(self, path: Union[str, Path], *, interpolate: bool = True):
|
| 472 |
+
"""Serialize the config to a file."""
|
| 473 |
+
path = Path(path) if isinstance(path, str) else path
|
| 474 |
+
with path.open("w", encoding="utf8") as file_:
|
| 475 |
+
file_.write(self.to_str(interpolate=interpolate))
|
| 476 |
+
|
| 477 |
+
def from_disk(
|
| 478 |
+
self,
|
| 479 |
+
path: Union[str, Path],
|
| 480 |
+
*,
|
| 481 |
+
interpolate: bool = True,
|
| 482 |
+
overrides: Dict[str, Any] = {},
|
| 483 |
+
) -> "Config":
|
| 484 |
+
"""Load config from a file."""
|
| 485 |
+
path = Path(path) if isinstance(path, str) else path
|
| 486 |
+
with path.open("r", encoding="utf8") as file_:
|
| 487 |
+
text = file_.read()
|
| 488 |
+
return self.from_str(text, interpolate=interpolate, overrides=overrides)
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
def _mask_positional_args(name: str) -> List[Optional[str]]:
|
| 492 |
+
"""Create a section name representation that masks names
|
| 493 |
+
of positional arguments to retain their order in sorts."""
|
| 494 |
+
|
| 495 |
+
stable_name = cast(List[Optional[str]], name.split("."))
|
| 496 |
+
|
| 497 |
+
# Remove names of sections that are a positional argument.
|
| 498 |
+
for i in range(1, len(stable_name)):
|
| 499 |
+
if stable_name[i - 1] == "*":
|
| 500 |
+
stable_name[i] = None
|
| 501 |
+
|
| 502 |
+
return stable_name
|
| 503 |
+
|
| 504 |
+
|
| 505 |
+
def try_load_json(value: str) -> Any:
|
| 506 |
+
"""Load a JSON string if possible, otherwise default to original value."""
|
| 507 |
+
try:
|
| 508 |
+
return srsly.json_loads(value)
|
| 509 |
+
except Exception:
|
| 510 |
+
return value
|
| 511 |
+
|
| 512 |
+
|
| 513 |
+
def try_dump_json(value: Any, data: Union[Dict[str, dict], Config, str] = "") -> str:
|
| 514 |
+
"""Dump a config value as JSON and output user-friendly error if it fails."""
|
| 515 |
+
# Special case if we have a variable: it's already a string so don't dump
|
| 516 |
+
# to preserve ${x:y} vs. "${x:y}"
|
| 517 |
+
if isinstance(value, str) and VARIABLE_RE.search(value):
|
| 518 |
+
return value
|
| 519 |
+
if isinstance(value, str) and value.replace(".", "", 1).isdigit():
|
| 520 |
+
# Work around values that are strings but numbers
|
| 521 |
+
value = f'"{value}"'
|
| 522 |
+
try:
|
| 523 |
+
value = srsly.json_dumps(value)
|
| 524 |
+
value = re.sub(r"\$([^{])", "$$\1", value)
|
| 525 |
+
value = re.sub(r"\$$", "$$", value)
|
| 526 |
+
return value
|
| 527 |
+
except Exception as e:
|
| 528 |
+
err_msg = (
|
| 529 |
+
f"Couldn't serialize config value of type {type(value)}: {e}. Make "
|
| 530 |
+
f"sure all values in your config are JSON-serializable. If you want "
|
| 531 |
+
f"to include Python objects, use a registered function that returns "
|
| 532 |
+
f"the object instead."
|
| 533 |
+
)
|
| 534 |
+
raise ConfigValidationError(config=data, desc=err_msg) from e
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
def deep_merge_configs(
|
| 538 |
+
config: Union[Dict[str, Any], Config],
|
| 539 |
+
defaults: Union[Dict[str, Any], Config],
|
| 540 |
+
*,
|
| 541 |
+
remove_extra: bool = False,
|
| 542 |
+
) -> Union[Dict[str, Any], Config]:
|
| 543 |
+
"""Deep merge two configs."""
|
| 544 |
+
if remove_extra:
|
| 545 |
+
# Filter out values in the original config that are not in defaults
|
| 546 |
+
keys = list(config.keys())
|
| 547 |
+
for key in keys:
|
| 548 |
+
if key not in defaults:
|
| 549 |
+
del config[key]
|
| 550 |
+
for key, value in defaults.items():
|
| 551 |
+
if isinstance(value, dict):
|
| 552 |
+
node = config.setdefault(key, {})
|
| 553 |
+
if not isinstance(node, dict):
|
| 554 |
+
continue
|
| 555 |
+
value_promises = [k for k in value if k.startswith("@")]
|
| 556 |
+
value_promise = value_promises[0] if value_promises else None
|
| 557 |
+
node_promises = [k for k in node if k.startswith("@")] if node else []
|
| 558 |
+
node_promise = node_promises[0] if node_promises else None
|
| 559 |
+
# We only update the block from defaults if it refers to the same
|
| 560 |
+
# registered function
|
| 561 |
+
if (
|
| 562 |
+
value_promise
|
| 563 |
+
and node_promise
|
| 564 |
+
and (
|
| 565 |
+
value_promise in node
|
| 566 |
+
and node[value_promise] != value[value_promise]
|
| 567 |
+
)
|
| 568 |
+
):
|
| 569 |
+
continue
|
| 570 |
+
if node_promise and (
|
| 571 |
+
node_promise not in value or node[node_promise] != value[node_promise]
|
| 572 |
+
):
|
| 573 |
+
continue
|
| 574 |
+
defaults = deep_merge_configs(node, value, remove_extra=remove_extra)
|
| 575 |
+
elif key not in config:
|
| 576 |
+
config[key] = value
|
| 577 |
+
return config
|
| 578 |
+
|
| 579 |
+
|
| 580 |
+
class ConfigValidationError(ValueError):
|
| 581 |
+
def __init__(
|
| 582 |
+
self,
|
| 583 |
+
*,
|
| 584 |
+
config: Optional[Union[Config, Dict[str, Dict[str, Any]], str]] = None,
|
| 585 |
+
errors: Union[Sequence[Mapping[str, Any]], Iterable[Dict[str, Any]]] = tuple(),
|
| 586 |
+
title: Optional[str] = "Config validation error",
|
| 587 |
+
desc: Optional[str] = None,
|
| 588 |
+
parent: Optional[str] = None,
|
| 589 |
+
show_config: bool = True,
|
| 590 |
+
) -> None:
|
| 591 |
+
"""Custom error for validating configs.
|
| 592 |
+
|
| 593 |
+
config (Union[Config, Dict[str, Dict[str, Any]], str]): The
|
| 594 |
+
config the validation error refers to.
|
| 595 |
+
errors (Union[Sequence[Mapping[str, Any]], Iterable[Dict[str, Any]]]):
|
| 596 |
+
A list of errors as dicts with keys "loc" (list of strings
|
| 597 |
+
describing the path of the value), "msg" (validation message
|
| 598 |
+
to show) and optional "type" (mostly internals).
|
| 599 |
+
Same format as produced by pydantic's validation error (e.errors()).
|
| 600 |
+
title (str): The error title.
|
| 601 |
+
desc (str): Optional error description, displayed below the title.
|
| 602 |
+
parent (str): Optional parent to use as prefix for all error locations.
|
| 603 |
+
For example, parent "element" will result in "element -> a -> b".
|
| 604 |
+
show_config (bool): Whether to print the whole config with the error.
|
| 605 |
+
|
| 606 |
+
ATTRIBUTES:
|
| 607 |
+
config (Union[Config, Dict[str, Dict[str, Any]], str]): The config.
|
| 608 |
+
errors (Iterable[Dict[str, Any]]): The errors.
|
| 609 |
+
error_types (Set[str]): All "type" values defined in the errors, if
|
| 610 |
+
available. This is most relevant for the pydantic errors that define
|
| 611 |
+
types like "type_error.integer". This attribute makes it easy to
|
| 612 |
+
check if a config validation error includes errors of a certain
|
| 613 |
+
type, e.g. to log additional information or custom help messages.
|
| 614 |
+
title (str): The title.
|
| 615 |
+
desc (str): The description.
|
| 616 |
+
parent (str): The parent.
|
| 617 |
+
show_config (bool): Whether to show the config.
|
| 618 |
+
text (str): The formatted error text.
|
| 619 |
+
"""
|
| 620 |
+
self.config = config
|
| 621 |
+
self.errors = errors
|
| 622 |
+
self.title = title
|
| 623 |
+
self.desc = desc
|
| 624 |
+
self.parent = parent
|
| 625 |
+
self.show_config = show_config
|
| 626 |
+
self.error_types = set()
|
| 627 |
+
for error in self.errors:
|
| 628 |
+
err_type = error.get("type")
|
| 629 |
+
if err_type:
|
| 630 |
+
self.error_types.add(err_type)
|
| 631 |
+
self.text = self._format()
|
| 632 |
+
ValueError.__init__(self, self.text)
|
| 633 |
+
|
| 634 |
+
@classmethod
|
| 635 |
+
def from_error(
|
| 636 |
+
cls,
|
| 637 |
+
err: "ConfigValidationError",
|
| 638 |
+
title: Optional[str] = None,
|
| 639 |
+
desc: Optional[str] = None,
|
| 640 |
+
parent: Optional[str] = None,
|
| 641 |
+
show_config: Optional[bool] = None,
|
| 642 |
+
) -> "ConfigValidationError":
|
| 643 |
+
"""Create a new ConfigValidationError based on an existing error, e.g.
|
| 644 |
+
to re-raise it with different settings. If no overrides are provided,
|
| 645 |
+
the values from the original error are used.
|
| 646 |
+
|
| 647 |
+
err (ConfigValidationError): The original error.
|
| 648 |
+
title (str): Overwrite error title.
|
| 649 |
+
desc (str): Overwrite error description.
|
| 650 |
+
parent (str): Overwrite error parent.
|
| 651 |
+
show_config (bool): Overwrite whether to show config.
|
| 652 |
+
RETURNS (ConfigValidationError): The new error.
|
| 653 |
+
"""
|
| 654 |
+
return cls(
|
| 655 |
+
config=err.config,
|
| 656 |
+
errors=err.errors,
|
| 657 |
+
title=title if title is not None else err.title,
|
| 658 |
+
desc=desc if desc is not None else err.desc,
|
| 659 |
+
parent=parent if parent is not None else err.parent,
|
| 660 |
+
show_config=show_config if show_config is not None else err.show_config,
|
| 661 |
+
)
|
| 662 |
+
|
| 663 |
+
def _format(self) -> str:
|
| 664 |
+
"""Format the error message."""
|
| 665 |
+
loc_divider = "->"
|
| 666 |
+
data = []
|
| 667 |
+
for error in self.errors:
|
| 668 |
+
err_loc = f" {loc_divider} ".join([str(p) for p in error.get("loc", [])])
|
| 669 |
+
if self.parent:
|
| 670 |
+
err_loc = f"{self.parent} {loc_divider} {err_loc}"
|
| 671 |
+
data.append((err_loc, error.get("msg")))
|
| 672 |
+
result = []
|
| 673 |
+
if self.title:
|
| 674 |
+
result.append(self.title)
|
| 675 |
+
if self.desc:
|
| 676 |
+
result.append(self.desc)
|
| 677 |
+
if data:
|
| 678 |
+
result.append("\n".join([f"{entry[0]}\t{entry[1]}" for entry in data]))
|
| 679 |
+
if self.config and self.show_config:
|
| 680 |
+
result.append(f"{self.config}")
|
| 681 |
+
return "\n\n" + "\n".join(result)
|
| 682 |
+
|
| 683 |
+
|
| 684 |
+
def alias_generator(name: str) -> str:
|
| 685 |
+
"""Generate field aliases in promise schema."""
|
| 686 |
+
# Underscore fields are not allowed in model, so use alias
|
| 687 |
+
if name == ARGS_FIELD_ALIAS:
|
| 688 |
+
return ARGS_FIELD
|
| 689 |
+
# Auto-alias fields that shadow base model attributes
|
| 690 |
+
if name in RESERVED_FIELDS:
|
| 691 |
+
return RESERVED_FIELDS[name]
|
| 692 |
+
return name
|
| 693 |
+
|
| 694 |
+
|
| 695 |
+
def copy_model_field(field: ModelField, type_: Any) -> ModelField:
|
| 696 |
+
"""Copy a model field and assign a new type, e.g. to accept an Any type
|
| 697 |
+
even though the original value is typed differently.
|
| 698 |
+
"""
|
| 699 |
+
return ModelField(
|
| 700 |
+
name=field.name,
|
| 701 |
+
type_=type_,
|
| 702 |
+
class_validators=field.class_validators,
|
| 703 |
+
model_config=field.model_config,
|
| 704 |
+
default=field.default,
|
| 705 |
+
default_factory=field.default_factory,
|
| 706 |
+
required=field.required,
|
| 707 |
+
alias=field.alias,
|
| 708 |
+
)
|
| 709 |
+
|
| 710 |
+
|
| 711 |
+
class EmptySchema(BaseModel):
|
| 712 |
+
class Config:
|
| 713 |
+
extra = "allow"
|
| 714 |
+
arbitrary_types_allowed = True
|
| 715 |
+
|
| 716 |
+
|
| 717 |
+
class _PromiseSchemaConfig:
|
| 718 |
+
extra = "forbid"
|
| 719 |
+
arbitrary_types_allowed = True
|
| 720 |
+
alias_generator = alias_generator
|
| 721 |
+
|
| 722 |
+
|
| 723 |
+
@dataclass
|
| 724 |
+
class Promise:
|
| 725 |
+
registry: str
|
| 726 |
+
name: str
|
| 727 |
+
args: List[str]
|
| 728 |
+
kwargs: Dict[str, Any]
|
| 729 |
+
|
| 730 |
+
|
| 731 |
+
class registry:
|
| 732 |
+
@classmethod
|
| 733 |
+
def has(cls, registry_name: str, func_name: str) -> bool:
|
| 734 |
+
"""Check whether a function is available in a registry."""
|
| 735 |
+
if not hasattr(cls, registry_name):
|
| 736 |
+
return False
|
| 737 |
+
reg = getattr(cls, registry_name)
|
| 738 |
+
return func_name in reg
|
| 739 |
+
|
| 740 |
+
@classmethod
|
| 741 |
+
def get(cls, registry_name: str, func_name: str) -> Callable:
|
| 742 |
+
"""Get a registered function from a given registry."""
|
| 743 |
+
if not hasattr(cls, registry_name):
|
| 744 |
+
raise ValueError(f"Unknown registry: '{registry_name}'")
|
| 745 |
+
reg = getattr(cls, registry_name)
|
| 746 |
+
func = reg.get(func_name)
|
| 747 |
+
if func is None:
|
| 748 |
+
raise ValueError(f"Could not find '{func_name}' in '{registry_name}'")
|
| 749 |
+
return func
|
| 750 |
+
|
| 751 |
+
@classmethod
|
| 752 |
+
def resolve(
|
| 753 |
+
cls,
|
| 754 |
+
config: Union[Config, Dict[str, Dict[str, Any]]],
|
| 755 |
+
*,
|
| 756 |
+
schema: Type[BaseModel] = EmptySchema,
|
| 757 |
+
overrides: Dict[str, Any] = {},
|
| 758 |
+
validate: bool = True,
|
| 759 |
+
) -> Dict[str, Any]:
|
| 760 |
+
resolved, _ = cls._make(
|
| 761 |
+
config, schema=schema, overrides=overrides, validate=validate, resolve=True
|
| 762 |
+
)
|
| 763 |
+
return resolved
|
| 764 |
+
|
| 765 |
+
@classmethod
|
| 766 |
+
def fill(
|
| 767 |
+
cls,
|
| 768 |
+
config: Union[Config, Dict[str, Dict[str, Any]]],
|
| 769 |
+
*,
|
| 770 |
+
schema: Type[BaseModel] = EmptySchema,
|
| 771 |
+
overrides: Dict[str, Any] = {},
|
| 772 |
+
validate: bool = True,
|
| 773 |
+
):
|
| 774 |
+
_, filled = cls._make(
|
| 775 |
+
config, schema=schema, overrides=overrides, validate=validate, resolve=False
|
| 776 |
+
)
|
| 777 |
+
return filled
|
| 778 |
+
|
| 779 |
+
@classmethod
|
| 780 |
+
def _make(
|
| 781 |
+
cls,
|
| 782 |
+
config: Union[Config, Dict[str, Dict[str, Any]]],
|
| 783 |
+
*,
|
| 784 |
+
schema: Type[BaseModel] = EmptySchema,
|
| 785 |
+
overrides: Dict[str, Any] = {},
|
| 786 |
+
resolve: bool = True,
|
| 787 |
+
validate: bool = True,
|
| 788 |
+
) -> Tuple[Dict[str, Any], Config]:
|
| 789 |
+
"""Unpack a config dictionary and create two versions of the config:
|
| 790 |
+
a resolved version with objects from the registry created recursively,
|
| 791 |
+
and a filled version with all references to registry functions left
|
| 792 |
+
intact, but filled with all values and defaults based on the type
|
| 793 |
+
annotations. If validate=True, the config will be validated against the
|
| 794 |
+
type annotations of the registered functions referenced in the config
|
| 795 |
+
(if available) and/or the schema (if available).
|
| 796 |
+
"""
|
| 797 |
+
# Valid: {"optimizer": {"@optimizers": "my_cool_optimizer", "rate": 1.0}}
|
| 798 |
+
# Invalid: {"@optimizers": "my_cool_optimizer", "rate": 1.0}
|
| 799 |
+
if cls.is_promise(config):
|
| 800 |
+
err_msg = "The top-level config object can't be a reference to a registered function."
|
| 801 |
+
raise ConfigValidationError(config=config, errors=[{"msg": err_msg}])
|
| 802 |
+
# If a Config was loaded with interpolate=False, we assume it needs to
|
| 803 |
+
# be interpolated first, otherwise we take it at face value
|
| 804 |
+
is_interpolated = not isinstance(config, Config) or config.is_interpolated
|
| 805 |
+
section_order = config.section_order if isinstance(config, Config) else None
|
| 806 |
+
orig_config = config
|
| 807 |
+
if not is_interpolated:
|
| 808 |
+
config = Config(orig_config).interpolate()
|
| 809 |
+
filled, _, resolved = cls._fill(
|
| 810 |
+
config, schema, validate=validate, overrides=overrides, resolve=resolve
|
| 811 |
+
)
|
| 812 |
+
filled = Config(filled, section_order=section_order)
|
| 813 |
+
# Check that overrides didn't include invalid properties not in config
|
| 814 |
+
if validate:
|
| 815 |
+
cls._validate_overrides(filled, overrides)
|
| 816 |
+
# Merge the original config back to preserve variables if we started
|
| 817 |
+
# with a config that wasn't interpolated. Here, we prefer variables to
|
| 818 |
+
# allow auto-filling a non-interpolated config without destroying
|
| 819 |
+
# variable references.
|
| 820 |
+
if not is_interpolated:
|
| 821 |
+
filled = filled.merge(
|
| 822 |
+
Config(orig_config, is_interpolated=False), remove_extra=True
|
| 823 |
+
)
|
| 824 |
+
return dict(resolved), filled
|
| 825 |
+
|
| 826 |
+
@classmethod
|
| 827 |
+
def _fill(
|
| 828 |
+
cls,
|
| 829 |
+
config: Union[Config, Dict[str, Dict[str, Any]]],
|
| 830 |
+
schema: Type[BaseModel] = EmptySchema,
|
| 831 |
+
*,
|
| 832 |
+
validate: bool = True,
|
| 833 |
+
resolve: bool = True,
|
| 834 |
+
parent: str = "",
|
| 835 |
+
overrides: Dict[str, Dict[str, Any]] = {},
|
| 836 |
+
) -> Tuple[
|
| 837 |
+
Union[Dict[str, Any], Config], Union[Dict[str, Any], Config], Dict[str, Any]
|
| 838 |
+
]:
|
| 839 |
+
"""Build three representations of the config:
|
| 840 |
+
1. All promises are preserved (just like config user would provide).
|
| 841 |
+
2. Promises are replaced by their return values. This is the validation
|
| 842 |
+
copy and will be parsed by pydantic. It lets us include hacks to
|
| 843 |
+
work around problems (e.g. handling of generators).
|
| 844 |
+
3. Final copy with promises replaced by their return values.
|
| 845 |
+
"""
|
| 846 |
+
filled: Dict[str, Any] = {}
|
| 847 |
+
validation: Dict[str, Any] = {}
|
| 848 |
+
final: Dict[str, Any] = {}
|
| 849 |
+
for key, value in config.items():
|
| 850 |
+
# If the field name is reserved, we use its alias for validation
|
| 851 |
+
v_key = RESERVED_FIELDS.get(key, key)
|
| 852 |
+
key_parent = f"{parent}.{key}".strip(".")
|
| 853 |
+
if key_parent in overrides:
|
| 854 |
+
value = overrides[key_parent]
|
| 855 |
+
config[key] = value
|
| 856 |
+
if cls.is_promise(value):
|
| 857 |
+
if key in schema.__fields__ and not resolve:
|
| 858 |
+
# If we're not resolving the config, make sure that the field
|
| 859 |
+
# expecting the promise is typed Any so it doesn't fail
|
| 860 |
+
# validation if it doesn't receive the function return value
|
| 861 |
+
field = schema.__fields__[key]
|
| 862 |
+
schema.__fields__[key] = copy_model_field(field, Any)
|
| 863 |
+
promise_schema = cls.make_promise_schema(value, resolve=resolve)
|
| 864 |
+
filled[key], validation[v_key], final[key] = cls._fill(
|
| 865 |
+
value,
|
| 866 |
+
promise_schema,
|
| 867 |
+
validate=validate,
|
| 868 |
+
resolve=resolve,
|
| 869 |
+
parent=key_parent,
|
| 870 |
+
overrides=overrides,
|
| 871 |
+
)
|
| 872 |
+
reg_name, func_name = cls.get_constructor(final[key])
|
| 873 |
+
args, kwargs = cls.parse_args(final[key])
|
| 874 |
+
if resolve:
|
| 875 |
+
# Call the function and populate the field value. We can't
|
| 876 |
+
# just create an instance of the type here, since this
|
| 877 |
+
# wouldn't work for generics / more complex custom types
|
| 878 |
+
getter = cls.get(reg_name, func_name)
|
| 879 |
+
# We don't want to try/except this and raise our own error
|
| 880 |
+
# here, because we want the traceback if the function fails.
|
| 881 |
+
getter_result = getter(*args, **kwargs)
|
| 882 |
+
else:
|
| 883 |
+
# We're not resolving and calling the function, so replace
|
| 884 |
+
# the getter_result with a Promise class
|
| 885 |
+
getter_result = Promise(
|
| 886 |
+
registry=reg_name, name=func_name, args=args, kwargs=kwargs
|
| 887 |
+
)
|
| 888 |
+
validation[v_key] = getter_result
|
| 889 |
+
final[key] = getter_result
|
| 890 |
+
if isinstance(validation[v_key], GeneratorType):
|
| 891 |
+
# If value is a generator we can't validate type without
|
| 892 |
+
# consuming it (which doesn't work if it's infinite – see
|
| 893 |
+
# schedule for examples). So we skip it.
|
| 894 |
+
validation[v_key] = []
|
| 895 |
+
elif hasattr(value, "items"):
|
| 896 |
+
field_type = EmptySchema
|
| 897 |
+
if key in schema.__fields__:
|
| 898 |
+
field = schema.__fields__[key]
|
| 899 |
+
field_type = field.type_
|
| 900 |
+
if not isinstance(field.type_, ModelMetaclass):
|
| 901 |
+
# If we don't have a pydantic schema and just a type
|
| 902 |
+
field_type = EmptySchema
|
| 903 |
+
filled[key], validation[v_key], final[key] = cls._fill(
|
| 904 |
+
value,
|
| 905 |
+
field_type,
|
| 906 |
+
validate=validate,
|
| 907 |
+
resolve=resolve,
|
| 908 |
+
parent=key_parent,
|
| 909 |
+
overrides=overrides,
|
| 910 |
+
)
|
| 911 |
+
if key == ARGS_FIELD and isinstance(validation[v_key], dict):
|
| 912 |
+
# If the value of variable positional args is a dict (e.g.
|
| 913 |
+
# created via config blocks), only use its values
|
| 914 |
+
validation[v_key] = list(validation[v_key].values())
|
| 915 |
+
final[key] = list(final[key].values())
|
| 916 |
+
|
| 917 |
+
if ARGS_FIELD_ALIAS in schema.__fields__ and not resolve:
|
| 918 |
+
# If we're not resolving the config, make sure that the field
|
| 919 |
+
# expecting the promise is typed Any so it doesn't fail
|
| 920 |
+
# validation if it doesn't receive the function return value
|
| 921 |
+
field = schema.__fields__[ARGS_FIELD_ALIAS]
|
| 922 |
+
schema.__fields__[ARGS_FIELD_ALIAS] = copy_model_field(
|
| 923 |
+
field, Any
|
| 924 |
+
)
|
| 925 |
+
else:
|
| 926 |
+
filled[key] = value
|
| 927 |
+
# Prevent pydantic from consuming generator if part of a union
|
| 928 |
+
validation[v_key] = (
|
| 929 |
+
value if not isinstance(value, GeneratorType) else []
|
| 930 |
+
)
|
| 931 |
+
final[key] = value
|
| 932 |
+
# Now that we've filled in all of the promises, update with defaults
|
| 933 |
+
# from schema, and validate if validation is enabled
|
| 934 |
+
exclude = []
|
| 935 |
+
if validate:
|
| 936 |
+
try:
|
| 937 |
+
result = schema.parse_obj(validation)
|
| 938 |
+
except ValidationError as e:
|
| 939 |
+
raise ConfigValidationError(
|
| 940 |
+
config=config, errors=e.errors(), parent=parent
|
| 941 |
+
) from None
|
| 942 |
+
else:
|
| 943 |
+
# Same as parse_obj, but without validation
|
| 944 |
+
result = schema.construct(**validation)
|
| 945 |
+
# If our schema doesn't allow extra values, we need to filter them
|
| 946 |
+
# manually because .construct doesn't parse anything
|
| 947 |
+
if schema.Config.extra in (Extra.forbid, Extra.ignore):
|
| 948 |
+
fields = schema.__fields__.keys()
|
| 949 |
+
# If we have a reserved field, we need to use its alias
|
| 950 |
+
field_set = [
|
| 951 |
+
k if k != ARGS_FIELD else ARGS_FIELD_ALIAS
|
| 952 |
+
for k in result.__fields_set__
|
| 953 |
+
]
|
| 954 |
+
exclude = [k for k in field_set if k not in fields]
|
| 955 |
+
exclude_validation = set([ARGS_FIELD_ALIAS, *RESERVED_FIELDS.keys()])
|
| 956 |
+
validation.update(result.dict(exclude=exclude_validation))
|
| 957 |
+
filled, final = cls._update_from_parsed(validation, filled, final)
|
| 958 |
+
if exclude:
|
| 959 |
+
filled = {k: v for k, v in filled.items() if k not in exclude}
|
| 960 |
+
validation = {k: v for k, v in validation.items() if k not in exclude}
|
| 961 |
+
final = {k: v for k, v in final.items() if k not in exclude}
|
| 962 |
+
return filled, validation, final
|
| 963 |
+
|
| 964 |
+
@classmethod
|
| 965 |
+
def _update_from_parsed(
|
| 966 |
+
cls, validation: Dict[str, Any], filled: Dict[str, Any], final: Dict[str, Any]
|
| 967 |
+
):
|
| 968 |
+
"""Update the final result with the parsed config like converted
|
| 969 |
+
values recursively.
|
| 970 |
+
"""
|
| 971 |
+
for key, value in validation.items():
|
| 972 |
+
if key in RESERVED_FIELDS.values():
|
| 973 |
+
continue # skip aliases for reserved fields
|
| 974 |
+
if key not in filled:
|
| 975 |
+
filled[key] = value
|
| 976 |
+
if key not in final:
|
| 977 |
+
final[key] = value
|
| 978 |
+
if isinstance(value, dict):
|
| 979 |
+
filled[key], final[key] = cls._update_from_parsed(
|
| 980 |
+
value, filled[key], final[key]
|
| 981 |
+
)
|
| 982 |
+
# Update final config with parsed value if they're not equal (in
|
| 983 |
+
# value and in type) but not if it's a generator because we had to
|
| 984 |
+
# replace that to validate it correctly
|
| 985 |
+
elif key == ARGS_FIELD:
|
| 986 |
+
continue # don't substitute if list of positional args
|
| 987 |
+
# Check numpy first, just in case. Use stringified type so that numpy dependency can be ditched.
|
| 988 |
+
elif str(type(value)) == "<class 'numpy.ndarray'>":
|
| 989 |
+
final[key] = value
|
| 990 |
+
elif (
|
| 991 |
+
value != final[key] or not isinstance(type(value), type(final[key]))
|
| 992 |
+
) and not isinstance(final[key], GeneratorType):
|
| 993 |
+
final[key] = value
|
| 994 |
+
return filled, final
|
| 995 |
+
|
| 996 |
+
@classmethod
|
| 997 |
+
def _validate_overrides(cls, filled: Config, overrides: Dict[str, Any]):
|
| 998 |
+
"""Validate overrides against a filled config to make sure there are
|
| 999 |
+
no references to properties that don't exist and weren't used."""
|
| 1000 |
+
error_msg = "Invalid override: config value doesn't exist"
|
| 1001 |
+
errors = []
|
| 1002 |
+
for override_key in overrides.keys():
|
| 1003 |
+
if not cls._is_in_config(override_key, filled):
|
| 1004 |
+
errors.append({"msg": error_msg, "loc": [override_key]})
|
| 1005 |
+
if errors:
|
| 1006 |
+
raise ConfigValidationError(config=filled, errors=errors)
|
| 1007 |
+
|
| 1008 |
+
@classmethod
|
| 1009 |
+
def _is_in_config(cls, prop: str, config: Union[Dict[str, Any], Config]):
|
| 1010 |
+
"""Check whether a nested config property like "section.subsection.key"
|
| 1011 |
+
is in a given config."""
|
| 1012 |
+
tree = prop.split(".")
|
| 1013 |
+
obj = dict(config)
|
| 1014 |
+
while tree:
|
| 1015 |
+
key = tree.pop(0)
|
| 1016 |
+
if isinstance(obj, dict) and key in obj:
|
| 1017 |
+
obj = obj[key]
|
| 1018 |
+
else:
|
| 1019 |
+
return False
|
| 1020 |
+
return True
|
| 1021 |
+
|
| 1022 |
+
@classmethod
|
| 1023 |
+
def is_promise(cls, obj: Any) -> bool:
|
| 1024 |
+
"""Check whether an object is a "promise", i.e. contains a reference
|
| 1025 |
+
to a registered function (via a key starting with `"@"`.
|
| 1026 |
+
"""
|
| 1027 |
+
if not hasattr(obj, "keys"):
|
| 1028 |
+
return False
|
| 1029 |
+
id_keys = [k for k in obj.keys() if k.startswith("@")]
|
| 1030 |
+
if len(id_keys):
|
| 1031 |
+
return True
|
| 1032 |
+
return False
|
| 1033 |
+
|
| 1034 |
+
@classmethod
|
| 1035 |
+
def get_constructor(cls, obj: Dict[str, Any]) -> Tuple[str, str]:
|
| 1036 |
+
id_keys = [k for k in obj.keys() if k.startswith("@")]
|
| 1037 |
+
if len(id_keys) != 1:
|
| 1038 |
+
err_msg = f"A block can only contain one function registry reference. Got: {id_keys}"
|
| 1039 |
+
raise ConfigValidationError(config=obj, errors=[{"msg": err_msg}])
|
| 1040 |
+
else:
|
| 1041 |
+
key = id_keys[0]
|
| 1042 |
+
value = obj[key]
|
| 1043 |
+
return (key[1:], value)
|
| 1044 |
+
|
| 1045 |
+
@classmethod
|
| 1046 |
+
def parse_args(cls, obj: Dict[str, Any]) -> Tuple[List[Any], Dict[str, Any]]:
|
| 1047 |
+
args = []
|
| 1048 |
+
kwargs = {}
|
| 1049 |
+
for key, value in obj.items():
|
| 1050 |
+
if not key.startswith("@"):
|
| 1051 |
+
if key == ARGS_FIELD:
|
| 1052 |
+
args = value
|
| 1053 |
+
elif key in RESERVED_FIELDS.values():
|
| 1054 |
+
continue
|
| 1055 |
+
else:
|
| 1056 |
+
kwargs[key] = value
|
| 1057 |
+
return args, kwargs
|
| 1058 |
+
|
| 1059 |
+
@classmethod
|
| 1060 |
+
def make_promise_schema(
|
| 1061 |
+
cls, obj: Dict[str, Any], *, resolve: bool = True
|
| 1062 |
+
) -> Type[BaseModel]:
|
| 1063 |
+
"""Create a schema for a promise dict (referencing a registry function)
|
| 1064 |
+
by inspecting the function signature.
|
| 1065 |
+
"""
|
| 1066 |
+
reg_name, func_name = cls.get_constructor(obj)
|
| 1067 |
+
if not resolve and not cls.has(reg_name, func_name):
|
| 1068 |
+
return EmptySchema
|
| 1069 |
+
func = cls.get(reg_name, func_name)
|
| 1070 |
+
# Read the argument annotations and defaults from the function signature
|
| 1071 |
+
id_keys = [k for k in obj.keys() if k.startswith("@")]
|
| 1072 |
+
sig_args: Dict[str, Any] = {id_keys[0]: (str, ...)}
|
| 1073 |
+
for param in inspect.signature(func).parameters.values():
|
| 1074 |
+
# If no annotation is specified assume it's anything
|
| 1075 |
+
annotation = param.annotation if param.annotation != param.empty else Any
|
| 1076 |
+
# If no default value is specified assume that it's required
|
| 1077 |
+
default = param.default if param.default != param.empty else ...
|
| 1078 |
+
# Handle spread arguments and use their annotation as Sequence[whatever]
|
| 1079 |
+
if param.kind == param.VAR_POSITIONAL:
|
| 1080 |
+
spread_annot = Sequence[annotation] # type: ignore
|
| 1081 |
+
sig_args[ARGS_FIELD_ALIAS] = (spread_annot, default)
|
| 1082 |
+
else:
|
| 1083 |
+
name = RESERVED_FIELDS.get(param.name, param.name)
|
| 1084 |
+
sig_args[name] = (annotation, default)
|
| 1085 |
+
sig_args["__config__"] = _PromiseSchemaConfig
|
| 1086 |
+
return create_model("ArgModel", **sig_args)
|
| 1087 |
+
|
| 1088 |
+
|
| 1089 |
+
__all__ = [
|
| 1090 |
+
"Config",
|
| 1091 |
+
"registry",
|
| 1092 |
+
"ConfigValidationError",
|
| 1093 |
+
"SimpleFrozenDict",
|
| 1094 |
+
"SimpleFrozenList",
|
| 1095 |
+
]
|
TTS/Kokoro/.venv/Lib/site-packages/confection/py.typed
ADDED
|
File without changes
|
TTS/Kokoro/.venv/Lib/site-packages/confection/util.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import functools
|
| 2 |
+
import sys
|
| 3 |
+
from copy import deepcopy
|
| 4 |
+
from typing import Any, Callable, Iterator, TypeVar
|
| 5 |
+
|
| 6 |
+
if sys.version_info < (3, 8):
|
| 7 |
+
# Ignoring type for mypy to avoid "Incompatible import" error (https://github.com/python/mypy/issues/4427).
|
| 8 |
+
from typing_extensions import Protocol # type: ignore
|
| 9 |
+
else:
|
| 10 |
+
from typing import Protocol
|
| 11 |
+
|
| 12 |
+
_DIn = TypeVar("_DIn")
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class Decorator(Protocol):
|
| 16 |
+
"""Protocol to mark a function as returning its child with identical signature."""
|
| 17 |
+
|
| 18 |
+
def __call__(self, name: str) -> Callable[[_DIn], _DIn]:
|
| 19 |
+
...
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
# This is how functools.partials seems to do it, too, to retain the return type
|
| 23 |
+
PartialT = TypeVar("PartialT")
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def partial(
|
| 27 |
+
func: Callable[..., PartialT], *args: Any, **kwargs: Any
|
| 28 |
+
) -> Callable[..., PartialT]:
|
| 29 |
+
"""Wrapper around functools.partial that retains docstrings and can include
|
| 30 |
+
other workarounds if needed.
|
| 31 |
+
"""
|
| 32 |
+
partial_func = functools.partial(func, *args, **kwargs)
|
| 33 |
+
partial_func.__doc__ = func.__doc__
|
| 34 |
+
return partial_func
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class Generator(Iterator):
|
| 38 |
+
"""Custom generator type. Used to annotate function arguments that accept
|
| 39 |
+
generators so they can be validated by pydantic (which doesn't support
|
| 40 |
+
iterators/iterables otherwise).
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
@classmethod
|
| 44 |
+
def __get_validators__(cls):
|
| 45 |
+
yield cls.validate
|
| 46 |
+
|
| 47 |
+
@classmethod
|
| 48 |
+
def validate(cls, v):
|
| 49 |
+
if not hasattr(v, "__iter__") and not hasattr(v, "__next__"):
|
| 50 |
+
raise TypeError("not a valid iterator")
|
| 51 |
+
return v
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
DEFAULT_FROZEN_DICT_ERROR = (
|
| 55 |
+
"Can't write to frozen dictionary. This is likely an internal "
|
| 56 |
+
"error. Are you writing to a default function argument?"
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
DEFAULT_FROZEN_LIST_ERROR = (
|
| 60 |
+
"Can't write to frozen list. Maybe you're trying to modify a computed "
|
| 61 |
+
"property or default function argument?"
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class SimpleFrozenDict(dict):
|
| 66 |
+
"""Simplified implementation of a frozen dict, mainly used as default
|
| 67 |
+
function or method argument (for arguments that should default to empty
|
| 68 |
+
dictionary). Will raise an error if the user attempts to add to dict.
|
| 69 |
+
"""
|
| 70 |
+
|
| 71 |
+
def __init__(
|
| 72 |
+
self,
|
| 73 |
+
*args,
|
| 74 |
+
error: str = DEFAULT_FROZEN_DICT_ERROR,
|
| 75 |
+
**kwargs,
|
| 76 |
+
) -> None:
|
| 77 |
+
"""Initialize the frozen dict. Can be initialized with pre-defined
|
| 78 |
+
values.
|
| 79 |
+
|
| 80 |
+
error (str): The error message when user tries to assign to dict.
|
| 81 |
+
"""
|
| 82 |
+
super().__init__(*args, **kwargs)
|
| 83 |
+
self.error = error
|
| 84 |
+
|
| 85 |
+
def __setitem__(self, key, value):
|
| 86 |
+
raise NotImplementedError(self.error)
|
| 87 |
+
|
| 88 |
+
def pop(self, key, default=None):
|
| 89 |
+
raise NotImplementedError(self.error)
|
| 90 |
+
|
| 91 |
+
def update(self, other):
|
| 92 |
+
raise NotImplementedError(self.error)
|
| 93 |
+
|
| 94 |
+
def __deepcopy__(self, memo):
|
| 95 |
+
return self.__class__(deepcopy({k: v for k, v in self.items()}))
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class SimpleFrozenList(list):
|
| 99 |
+
"""Wrapper class around a list that lets us raise custom errors if certain
|
| 100 |
+
attributes/methods are accessed. Mostly used for properties that return an
|
| 101 |
+
immutable list (and that we don't want to convert to a tuple to not break
|
| 102 |
+
too much backwards compatibility). If a user accidentally calls
|
| 103 |
+
frozen_list.append(), we can raise a more helpful error.
|
| 104 |
+
"""
|
| 105 |
+
|
| 106 |
+
def __init__(
|
| 107 |
+
self,
|
| 108 |
+
*args,
|
| 109 |
+
error: str = DEFAULT_FROZEN_LIST_ERROR,
|
| 110 |
+
) -> None:
|
| 111 |
+
"""Initialize the frozen list.
|
| 112 |
+
|
| 113 |
+
error (str): The error message when user tries to mutate the list.
|
| 114 |
+
"""
|
| 115 |
+
self.error = error
|
| 116 |
+
super().__init__(*args)
|
| 117 |
+
|
| 118 |
+
def append(self, *args, **kwargs):
|
| 119 |
+
raise NotImplementedError(self.error)
|
| 120 |
+
|
| 121 |
+
def clear(self, *args, **kwargs):
|
| 122 |
+
raise NotImplementedError(self.error)
|
| 123 |
+
|
| 124 |
+
def extend(self, *args, **kwargs):
|
| 125 |
+
raise NotImplementedError(self.error)
|
| 126 |
+
|
| 127 |
+
def insert(self, *args, **kwargs):
|
| 128 |
+
raise NotImplementedError(self.error)
|
| 129 |
+
|
| 130 |
+
def pop(self, *args, **kwargs):
|
| 131 |
+
raise NotImplementedError(self.error)
|
| 132 |
+
|
| 133 |
+
def remove(self, *args, **kwargs):
|
| 134 |
+
raise NotImplementedError(self.error)
|
| 135 |
+
|
| 136 |
+
def reverse(self, *args, **kwargs):
|
| 137 |
+
raise NotImplementedError(self.error)
|
| 138 |
+
|
| 139 |
+
def sort(self, *args, **kwargs):
|
| 140 |
+
raise NotImplementedError(self.error)
|
| 141 |
+
|
| 142 |
+
def __deepcopy__(self, memo):
|
| 143 |
+
return self.__class__(deepcopy(v) for v in self)
|
TTS/Kokoro/.venv/Lib/site-packages/csvw-3.7.0.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
pip
|
TTS/Kokoro/.venv/Lib/site-packages/csvw-3.7.0.dist-info/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Apache License
|
| 2 |
+
Version 2.0, January 2004
|
| 3 |
+
http://www.apache.org/licenses/
|
| 4 |
+
|
| 5 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 6 |
+
|
| 7 |
+
1. Definitions.
|
| 8 |
+
|
| 9 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 10 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 11 |
+
|
| 12 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 13 |
+
the copyright owner that is granting the License.
|
| 14 |
+
|
| 15 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 16 |
+
other entities that control, are controlled by, or are under common
|
| 17 |
+
control with that entity. For the purposes of this definition,
|
| 18 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 19 |
+
direction or management of such entity, whether by contract or
|
| 20 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 21 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 22 |
+
|
| 23 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 24 |
+
exercising permissions granted by this License.
|
| 25 |
+
|
| 26 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 27 |
+
including but not limited to software source code, documentation
|
| 28 |
+
source, and configuration files.
|
| 29 |
+
|
| 30 |
+
"Object" form shall mean any form resulting from mechanical
|
| 31 |
+
transformation or translation of a Source form, including but
|
| 32 |
+
not limited to compiled object code, generated documentation,
|
| 33 |
+
and conversions to other media types.
|
| 34 |
+
|
| 35 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 36 |
+
Object form, made available under the License, as indicated by a
|
| 37 |
+
copyright notice that is included in or attached to the work
|
| 38 |
+
(an example is provided in the Appendix below).
|
| 39 |
+
|
| 40 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 41 |
+
form, that is based on (or derived from) the Work and for which the
|
| 42 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 43 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 44 |
+
of this License, Derivative Works shall not include works that remain
|
| 45 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 46 |
+
the Work and Derivative Works thereof.
|
| 47 |
+
|
| 48 |
+
"Contribution" shall mean any work of authorship, including
|
| 49 |
+
the original version of the Work and any modifications or additions
|
| 50 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 51 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 52 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 53 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 54 |
+
means any form of electronic, verbal, or written communication sent
|
| 55 |
+
to the Licensor or its representatives, including but not limited to
|
| 56 |
+
communication on electronic mailing lists, source code control systems,
|
| 57 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 58 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 59 |
+
excluding communication that is conspicuously marked or otherwise
|
| 60 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 61 |
+
|
| 62 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 63 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 64 |
+
subsequently incorporated within the Work.
|
| 65 |
+
|
| 66 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 67 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 68 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 69 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 70 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 71 |
+
Work and such Derivative Works in Source or Object form.
|
| 72 |
+
|
| 73 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 74 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 75 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 76 |
+
(except as stated in this section) patent license to make, have made,
|
| 77 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 78 |
+
where such license applies only to those patent claims licensable
|
| 79 |
+
by such Contributor that are necessarily infringed by their
|
| 80 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 81 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 82 |
+
institute patent litigation against any entity (including a
|
| 83 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 84 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 85 |
+
or contributory patent infringement, then any patent licenses
|
| 86 |
+
granted to You under this License for that Work shall terminate
|
| 87 |
+
as of the date such litigation is filed.
|
| 88 |
+
|
| 89 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 90 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 91 |
+
modifications, and in Source or Object form, provided that You
|
| 92 |
+
meet the following conditions:
|
| 93 |
+
|
| 94 |
+
(a) You must give any other recipients of the Work or
|
| 95 |
+
Derivative Works a copy of this License; and
|
| 96 |
+
|
| 97 |
+
(b) You must cause any modified files to carry prominent notices
|
| 98 |
+
stating that You changed the files; and
|
| 99 |
+
|
| 100 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 101 |
+
that You distribute, all copyright, patent, trademark, and
|
| 102 |
+
attribution notices from the Source form of the Work,
|
| 103 |
+
excluding those notices that do not pertain to any part of
|
| 104 |
+
the Derivative Works; and
|
| 105 |
+
|
| 106 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 107 |
+
distribution, then any Derivative Works that You distribute must
|
| 108 |
+
include a readable copy of the attribution notices contained
|
| 109 |
+
within such NOTICE file, excluding those notices that do not
|
| 110 |
+
pertain to any part of the Derivative Works, in at least one
|
| 111 |
+
of the following places: within a NOTICE text file distributed
|
| 112 |
+
as part of the Derivative Works; within the Source form or
|
| 113 |
+
documentation, if provided along with the Derivative Works; or,
|
| 114 |
+
within a display generated by the Derivative Works, if and
|
| 115 |
+
wherever such third-party notices normally appear. The contents
|
| 116 |
+
of the NOTICE file are for informational purposes only and
|
| 117 |
+
do not modify the License. You may add Your own attribution
|
| 118 |
+
notices within Derivative Works that You distribute, alongside
|
| 119 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 120 |
+
that such additional attribution notices cannot be construed
|
| 121 |
+
as modifying the License.
|
| 122 |
+
|
| 123 |
+
You may add Your own copyright statement to Your modifications and
|
| 124 |
+
may provide additional or different license terms and conditions
|
| 125 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 126 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 127 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 128 |
+
the conditions stated in this License.
|
| 129 |
+
|
| 130 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 131 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 132 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 133 |
+
this License, without any additional terms or conditions.
|
| 134 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 135 |
+
the terms of any separate license agreement you may have executed
|
| 136 |
+
with Licensor regarding such Contributions.
|
| 137 |
+
|
| 138 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 139 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 140 |
+
except as required for reasonable and customary use in describing the
|
| 141 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 142 |
+
|
| 143 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 144 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 145 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 146 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 147 |
+
implied, including, without limitation, any warranties or conditions
|
| 148 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 149 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 150 |
+
appropriateness of using or redistributing the Work and assume any
|
| 151 |
+
risks associated with Your exercise of permissions under this License.
|
| 152 |
+
|
| 153 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 154 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 155 |
+
unless required by applicable law (such as deliberate and grossly
|
| 156 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 157 |
+
liable to You for damages, including any direct, indirect, special,
|
| 158 |
+
incidental, or consequential damages of any character arising as a
|
| 159 |
+
result of this License or out of the use or inability to use the
|
| 160 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 161 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 162 |
+
other commercial damages or losses), even if such Contributor
|
| 163 |
+
has been advised of the possibility of such damages.
|
| 164 |
+
|
| 165 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 166 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 167 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 168 |
+
or other liability obligations and/or rights consistent with this
|
| 169 |
+
License. However, in accepting such obligations, You may act only
|
| 170 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 171 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 172 |
+
defend, and hold each Contributor harmless for any liability
|
| 173 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 174 |
+
of your accepting any such warranty or additional liability.
|
| 175 |
+
|
| 176 |
+
END OF TERMS AND CONDITIONS
|
| 177 |
+
|
| 178 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 179 |
+
|
| 180 |
+
To apply the Apache License to your work, attach the following
|
| 181 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 182 |
+
replaced with your own identifying information. (Don't include
|
| 183 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 184 |
+
comment syntax for the file format. We also recommend that a
|
| 185 |
+
file or class name and description of purpose be included on the
|
| 186 |
+
same "printed page" as the copyright notice for easier
|
| 187 |
+
identification within third-party archives.
|
| 188 |
+
|
| 189 |
+
Copyright [yyyy] [name of copyright owner]
|
| 190 |
+
|
| 191 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 192 |
+
you may not use this file except in compliance with the License.
|
| 193 |
+
You may obtain a copy of the License at
|
| 194 |
+
|
| 195 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 196 |
+
|
| 197 |
+
Unless required by applicable law or agreed to in writing, software
|
| 198 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 199 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 200 |
+
See the License for the specific language governing permissions and
|
| 201 |
+
limitations under the License.
|
TTS/Kokoro/.venv/Lib/site-packages/csvw-3.7.0.dist-info/METADATA
ADDED
|
@@ -0,0 +1,301 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.1
|
| 2 |
+
Name: csvw
|
| 3 |
+
Version: 3.7.0
|
| 4 |
+
Summary: Python library to work with CSVW described tabular data
|
| 5 |
+
Home-page: https://github.com/cldf/csvw
|
| 6 |
+
Author: Robert Forkel
|
| 7 |
+
Author-email: robert_forkel@eva.mpg.de
|
| 8 |
+
License: Apache 2.0
|
| 9 |
+
Project-URL: Bug Tracker, https://github.com/cldf/csvw/issues
|
| 10 |
+
Keywords: csv,w3c,tabular-data
|
| 11 |
+
Platform: any
|
| 12 |
+
Classifier: Development Status :: 5 - Production/Stable
|
| 13 |
+
Classifier: Intended Audience :: Developers
|
| 14 |
+
Classifier: Intended Audience :: Science/Research
|
| 15 |
+
Classifier: Natural Language :: English
|
| 16 |
+
Classifier: Operating System :: OS Independent
|
| 17 |
+
Classifier: Programming Language :: Python :: 3
|
| 18 |
+
Classifier: Programming Language :: Python :: 3.8
|
| 19 |
+
Classifier: Programming Language :: Python :: 3.9
|
| 20 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 21 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 22 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 23 |
+
Classifier: Programming Language :: Python :: 3.13
|
| 24 |
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
| 25 |
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
| 26 |
+
Classifier: License :: OSI Approved :: Apache Software License
|
| 27 |
+
Requires-Python: >=3.8
|
| 28 |
+
Description-Content-Type: text/markdown
|
| 29 |
+
License-File: LICENSE
|
| 30 |
+
Requires-Dist: attrs>=18.1
|
| 31 |
+
Requires-Dist: isodate
|
| 32 |
+
Requires-Dist: python-dateutil
|
| 33 |
+
Requires-Dist: rfc3986<2
|
| 34 |
+
Requires-Dist: uritemplate>=3.0.0
|
| 35 |
+
Requires-Dist: babel
|
| 36 |
+
Requires-Dist: requests
|
| 37 |
+
Requires-Dist: language-tags
|
| 38 |
+
Requires-Dist: rdflib
|
| 39 |
+
Requires-Dist: termcolor
|
| 40 |
+
Requires-Dist: jsonschema
|
| 41 |
+
Provides-Extra: dev
|
| 42 |
+
Requires-Dist: flake8; extra == "dev"
|
| 43 |
+
Requires-Dist: wheel; extra == "dev"
|
| 44 |
+
Requires-Dist: twine; extra == "dev"
|
| 45 |
+
Requires-Dist: build; extra == "dev"
|
| 46 |
+
Provides-Extra: docs
|
| 47 |
+
Requires-Dist: sphinx<7; extra == "docs"
|
| 48 |
+
Requires-Dist: sphinx-autodoc-typehints; extra == "docs"
|
| 49 |
+
Requires-Dist: sphinx-rtd-theme; extra == "docs"
|
| 50 |
+
Provides-Extra: test
|
| 51 |
+
Requires-Dist: frictionless; extra == "test"
|
| 52 |
+
Requires-Dist: pytest>=5; extra == "test"
|
| 53 |
+
Requires-Dist: pytest-mock; extra == "test"
|
| 54 |
+
Requires-Dist: requests-mock; extra == "test"
|
| 55 |
+
Requires-Dist: pytest-cov; extra == "test"
|
| 56 |
+
|
| 57 |
+
# csvw
|
| 58 |
+
|
| 59 |
+
[](https://github.com/cldf/csvw/actions?query=workflow%3Atests)
|
| 60 |
+
[](https://pypi.org/project/csvw)
|
| 61 |
+
[](https://csvw.readthedocs.io/en/latest/?badge=latest)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
This package provides
|
| 65 |
+
- a Python API to read and write relational, tabular data according to the [CSV on the Web](https://csvw.org/) specification and
|
| 66 |
+
- commandline tools for reading and validating CSVW data.
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
## Links
|
| 70 |
+
|
| 71 |
+
- GitHub: https://github.com/cldf/csvw
|
| 72 |
+
- PyPI: https://pypi.org/project/csvw
|
| 73 |
+
- Issue Tracker: https://github.com/cldf/csvw/issues
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
## Installation
|
| 77 |
+
|
| 78 |
+
This package runs under Python >=3.8, use pip to install:
|
| 79 |
+
|
| 80 |
+
```bash
|
| 81 |
+
$ pip install csvw
|
| 82 |
+
```
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
## CLI
|
| 86 |
+
|
| 87 |
+
### `csvw2json`
|
| 88 |
+
|
| 89 |
+
Converting CSVW data [to JSON](https://www.w3.org/TR/csv2json/)
|
| 90 |
+
|
| 91 |
+
```shell
|
| 92 |
+
$ csvw2json tests/fixtures/zipped-metadata.json
|
| 93 |
+
{
|
| 94 |
+
"tables": [
|
| 95 |
+
{
|
| 96 |
+
"url": "tests/fixtures/zipped.csv",
|
| 97 |
+
"row": [
|
| 98 |
+
{
|
| 99 |
+
"url": "tests/fixtures/zipped.csv#row=2",
|
| 100 |
+
"rownum": 1,
|
| 101 |
+
"describes": [
|
| 102 |
+
{
|
| 103 |
+
"ID": "abc",
|
| 104 |
+
"Value": "the value"
|
| 105 |
+
}
|
| 106 |
+
]
|
| 107 |
+
},
|
| 108 |
+
{
|
| 109 |
+
"url": "tests/fixtures/zipped.csv#row=3",
|
| 110 |
+
"rownum": 2,
|
| 111 |
+
"describes": [
|
| 112 |
+
{
|
| 113 |
+
"ID": "cde",
|
| 114 |
+
"Value": "another one"
|
| 115 |
+
}
|
| 116 |
+
]
|
| 117 |
+
}
|
| 118 |
+
]
|
| 119 |
+
}
|
| 120 |
+
]
|
| 121 |
+
}
|
| 122 |
+
```
|
| 123 |
+
|
| 124 |
+
### `csvwvalidate`
|
| 125 |
+
|
| 126 |
+
Validating CSVW data
|
| 127 |
+
|
| 128 |
+
```shell
|
| 129 |
+
$ csvwvalidate tests/fixtures/zipped-metadata.json
|
| 130 |
+
OK
|
| 131 |
+
```
|
| 132 |
+
|
| 133 |
+
### `csvwdescribe`
|
| 134 |
+
|
| 135 |
+
Describing tabular-data files with CSVW metadata
|
| 136 |
+
|
| 137 |
+
```shell
|
| 138 |
+
$ csvwdescribe --delimiter "|" tests/fixtures/frictionless-data.csv
|
| 139 |
+
{
|
| 140 |
+
"@context": "http://www.w3.org/ns/csvw",
|
| 141 |
+
"dc:conformsTo": "data-package",
|
| 142 |
+
"tables": [
|
| 143 |
+
{
|
| 144 |
+
"dialect": {
|
| 145 |
+
"delimiter": "|"
|
| 146 |
+
},
|
| 147 |
+
"tableSchema": {
|
| 148 |
+
"columns": [
|
| 149 |
+
{
|
| 150 |
+
"datatype": "string",
|
| 151 |
+
"name": "FK"
|
| 152 |
+
},
|
| 153 |
+
{
|
| 154 |
+
"datatype": "integer",
|
| 155 |
+
"name": "Year"
|
| 156 |
+
},
|
| 157 |
+
{
|
| 158 |
+
"datatype": "string",
|
| 159 |
+
"name": "Location name"
|
| 160 |
+
},
|
| 161 |
+
{
|
| 162 |
+
"datatype": "string",
|
| 163 |
+
"name": "Value"
|
| 164 |
+
},
|
| 165 |
+
{
|
| 166 |
+
"datatype": "string",
|
| 167 |
+
"name": "binary"
|
| 168 |
+
},
|
| 169 |
+
{
|
| 170 |
+
"datatype": "string",
|
| 171 |
+
"name": "anyURI"
|
| 172 |
+
},
|
| 173 |
+
{
|
| 174 |
+
"datatype": "string",
|
| 175 |
+
"name": "email"
|
| 176 |
+
},
|
| 177 |
+
{
|
| 178 |
+
"datatype": "string",
|
| 179 |
+
"name": "boolean"
|
| 180 |
+
},
|
| 181 |
+
{
|
| 182 |
+
"datatype": {
|
| 183 |
+
"dc:format": "application/json",
|
| 184 |
+
"base": "json"
|
| 185 |
+
},
|
| 186 |
+
"name": "array"
|
| 187 |
+
},
|
| 188 |
+
{
|
| 189 |
+
"datatype": {
|
| 190 |
+
"dc:format": "application/json",
|
| 191 |
+
"base": "json"
|
| 192 |
+
},
|
| 193 |
+
"name": "geojson"
|
| 194 |
+
}
|
| 195 |
+
]
|
| 196 |
+
},
|
| 197 |
+
"url": "tests/fixtures/frictionless-data.csv"
|
| 198 |
+
}
|
| 199 |
+
]
|
| 200 |
+
}
|
| 201 |
+
```
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
## Python API
|
| 205 |
+
|
| 206 |
+
Find the Python API documentation at [csvw.readthedocs.io](https://csvw.readthedocs.io/en/latest/).
|
| 207 |
+
|
| 208 |
+
A quick example for using `csvw` from Python code:
|
| 209 |
+
|
| 210 |
+
```python
|
| 211 |
+
import json
|
| 212 |
+
from csvw import CSVW
|
| 213 |
+
data = CSVW('https://raw.githubusercontent.com/cldf/csvw/master/tests/fixtures/test.tsv')
|
| 214 |
+
print(json.dumps(data.to_json(minimal=True), indent=4))
|
| 215 |
+
[
|
| 216 |
+
{
|
| 217 |
+
"province": "Hello",
|
| 218 |
+
"territory": "world",
|
| 219 |
+
"precinct": "1"
|
| 220 |
+
}
|
| 221 |
+
]
|
| 222 |
+
```
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
## Known limitations
|
| 226 |
+
|
| 227 |
+
- We read **all** data which is specified as UTF-8 encoded using the
|
| 228 |
+
[`utf-8-sig` codecs](https://docs.python.org/3/library/codecs.html#module-encodings.utf_8_sig).
|
| 229 |
+
Thus, if such data starts with `U+FEFF` this will be interpreted as [BOM](https://en.wikipedia.org/wiki/Byte_order_mark)
|
| 230 |
+
and skipped.
|
| 231 |
+
- Low level CSV parsing is delegated to the `csv` module in Python's standard library. Thus, if a `commentPrefix`
|
| 232 |
+
is specified in a `Dialect` instance, this will lead to skipping rows where the first value starts
|
| 233 |
+
with `commentPrefix`, **even if the value was quoted**.
|
| 234 |
+
- Also, cell content containing `escapechar` may not be round-tripped as expected (when specifying
|
| 235 |
+
`escapechar` or a `csvw.Dialect` with `quoteChar` but `doubleQuote==False`),
|
| 236 |
+
when minimal quoting is specified. This is due to inconsistent `csv` behaviour
|
| 237 |
+
across Python versions (see https://bugs.python.org/issue44861).
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
## CSVW conformance
|
| 241 |
+
|
| 242 |
+
While we use the CSVW specification as guideline, this package does not (and
|
| 243 |
+
probably never will) implement the full extent of this spec.
|
| 244 |
+
|
| 245 |
+
- When CSV files with a header are read, columns are not matched in order with
|
| 246 |
+
column descriptions in the `tableSchema`, but instead are matched based on the
|
| 247 |
+
CSV column header and the column descriptions' `name` and `titles` atributes.
|
| 248 |
+
This allows for more flexibility, because columns in the CSV file may be
|
| 249 |
+
re-ordered without invalidating the metadata. A stricter matching can be forced
|
| 250 |
+
by specifying `"header": false` and `"skipRows": 1` in the table's dialect
|
| 251 |
+
description.
|
| 252 |
+
|
| 253 |
+
However, `csvw.CSVW` works correctly for
|
| 254 |
+
- 269 out of 270 [JSON tests](https://w3c.github.io/csvw/tests/#manifest-json),
|
| 255 |
+
- 280 out of 282 [validation tests](https://w3c.github.io/csvw/tests/#manifest-validation),
|
| 256 |
+
- 10 out of 18 [non-normative tests](https://w3c.github.io/csvw/tests/#manifest-nonnorm)
|
| 257 |
+
|
| 258 |
+
from the [CSVW Test suites](https://w3c.github.io/csvw/tests/).
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
## Compatibility with [Frictionless Data Specs](https://specs.frictionlessdata.io/)
|
| 262 |
+
|
| 263 |
+
A CSVW-described dataset is basically equivalent to a Frictionless DataPackage where all
|
| 264 |
+
[Data Resources](https://specs.frictionlessdata.io/data-resource/) are [Tabular Data](https://specs.frictionlessdata.io/tabular-data-resource/).
|
| 265 |
+
Thus, the `csvw` package provides some conversion functionality. To
|
| 266 |
+
"read CSVW data from a Data Package", there's the `csvw.TableGroup.from_frictionless_datapackage` method:
|
| 267 |
+
```python
|
| 268 |
+
from csvw import TableGroup
|
| 269 |
+
tg = TableGroup.from_frictionless_datapackage('PATH/TO/datapackage.json')
|
| 270 |
+
```
|
| 271 |
+
To convert the metadata, the `TableGroup` can then be serialzed:
|
| 272 |
+
```python
|
| 273 |
+
tg.to_file('csvw-metadata.json')
|
| 274 |
+
```
|
| 275 |
+
|
| 276 |
+
Note that the CSVW metadata file must be written to the Data Package's directory
|
| 277 |
+
to make sure relative paths to data resources work.
|
| 278 |
+
|
| 279 |
+
This functionality - together with the schema inference capabilities
|
| 280 |
+
of [`frictionless describe`](https://framework.frictionlessdata.io/docs/guides/describing-data/) - provides
|
| 281 |
+
a convenient way to bootstrap CSVW metadata for a set of "raw" CSV
|
| 282 |
+
files, implemented in the [`csvwdescribe` command described above](#csvwdescribe).
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
## See also
|
| 286 |
+
|
| 287 |
+
- https://www.w3.org/2013/csvw/wiki/Main_Page
|
| 288 |
+
- https://csvw.org
|
| 289 |
+
- https://github.com/CLARIAH/COW
|
| 290 |
+
- https://github.com/CLARIAH/ruminator
|
| 291 |
+
- https://github.com/bloomberg/pycsvw
|
| 292 |
+
- https://specs.frictionlessdata.io/table-schema/
|
| 293 |
+
- https://github.com/theodi/csvlint.rb
|
| 294 |
+
- https://github.com/ruby-rdf/rdf-tabular
|
| 295 |
+
- https://github.com/rdf-ext/rdf-parser-csvw
|
| 296 |
+
- https://github.com/Robsteranium/csvwr
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
## License
|
| 300 |
+
|
| 301 |
+
This package is distributed under the [Apache 2.0 license](https://opensource.org/licenses/Apache-2.0).
|
TTS/Kokoro/.venv/Lib/site-packages/csvw-3.7.0.dist-info/RECORD
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
../../Scripts/csvw2datasette.exe,sha256=dqEjTZxR5Dcu1mKKRIZw3bPEtofwEPS4NIcpyyYJ5Uk,108396
|
| 2 |
+
../../Scripts/csvw2json.exe,sha256=-sQdGj1yfarDuHeXBZHCR-Z5glgEeR6exPX0Qi3tFlI,108386
|
| 3 |
+
../../Scripts/csvw2markdown.exe,sha256=CW1sVb9mZC3F5kj5YKQFIa8-XawSSMpg5CcE0fLqpjQ,108394
|
| 4 |
+
../../Scripts/csvw2sqlite.exe,sha256=aKviCAO96DS7KKXahS2BJSFoER6HnCSarn0xxov4AT0,108390
|
| 5 |
+
../../Scripts/csvwdescribe.exe,sha256=cAugtD9btqFSJ3CBEDSw6u1qC-D21ILGus8pEo6DbGY,108392
|
| 6 |
+
../../Scripts/csvwvalidate.exe,sha256=KA4jH8fu8R2Q5CZnoz-Sl5li8BMkguPaW1wwqbog364,108392
|
| 7 |
+
csvw-3.7.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
| 8 |
+
csvw-3.7.0.dist-info/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
|
| 9 |
+
csvw-3.7.0.dist-info/METADATA,sha256=VNInfVEiobvxNhBkU0khBflyNe9HclL-V2RoTi6DLJs,10159
|
| 10 |
+
csvw-3.7.0.dist-info/RECORD,,
|
| 11 |
+
csvw-3.7.0.dist-info/WHEEL,sha256=TJ49d73sNs10F0aze1W_bTW2P_X7-F4YXOlBqoqA-jY,109
|
| 12 |
+
csvw-3.7.0.dist-info/entry_points.txt,sha256=fk9IQtAGIpAeWAXe3I3xGNozh4ww_7b80c_vD2GFuEI,268
|
| 13 |
+
csvw-3.7.0.dist-info/top_level.txt,sha256=mkl3l5vQaigdnccNcB3IT5J_Puu2Rp5PVYHqoUOh0Vo,5
|
| 14 |
+
csvw/__init__.py,sha256=tuw2tzIid2s-ErfZD6uyB9FRDeJG45GwOk3oenFOpwI,781
|
| 15 |
+
csvw/__main__.py,sha256=h0R5f7kWgvjg8VwBPJRpiTROGY91ZgplGfZZkbGKn5U,5618
|
| 16 |
+
csvw/__pycache__/__init__.cpython-312.pyc,,
|
| 17 |
+
csvw/__pycache__/__main__.cpython-312.pyc,,
|
| 18 |
+
csvw/__pycache__/datatypes.cpython-312.pyc,,
|
| 19 |
+
csvw/__pycache__/db.cpython-312.pyc,,
|
| 20 |
+
csvw/__pycache__/dsv.cpython-312.pyc,,
|
| 21 |
+
csvw/__pycache__/dsv_dialects.cpython-312.pyc,,
|
| 22 |
+
csvw/__pycache__/frictionless.cpython-312.pyc,,
|
| 23 |
+
csvw/__pycache__/jsonld.cpython-312.pyc,,
|
| 24 |
+
csvw/__pycache__/metadata.cpython-312.pyc,,
|
| 25 |
+
csvw/__pycache__/utils.cpython-312.pyc,,
|
| 26 |
+
csvw/datatypes.py,sha256=gKWd-WmoDgyoprmUioU3W7nsMu4N52cP1o45HyeJ3QQ,38609
|
| 27 |
+
csvw/db.py,sha256=2iyFhMmioPJwww447wN1S6o1TcpW0Vz5cnR4zAfxwSU,25011
|
| 28 |
+
csvw/dsv.py,sha256=WfbotNzcT9Q4k9Mqofqu3F8ARTYrVPetPNceJLQRDRM,16870
|
| 29 |
+
csvw/dsv_dialects.py,sha256=TUVi-gtYXC-OhHQbZZykpvnOfHgghsFKk0wE7jokAaQ,5177
|
| 30 |
+
csvw/frictionless.py,sha256=YuC36bL7Bs3elZ-MIpLBpcNIkKCt49jA0-VqGyNW4-0,8284
|
| 31 |
+
csvw/jsonld.py,sha256=U6qp_gBXAMeBnwdgMsPHeUB6-NCZYWbv_BrH3EJGX2Q,6501
|
| 32 |
+
csvw/metadata.py,sha256=UMtUxjycvGCgY23U93wzlHzU8QX1oIpg1F3de-jcK4w,73653
|
| 33 |
+
csvw/utils.py,sha256=46wWXpjmpd7esW96MeCPydqCMQoXYxmblalwKmbnzrc,8280
|
TTS/Kokoro/.venv/Lib/site-packages/csvw-3.7.0.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: setuptools (75.2.0)
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py2-none-any
|
| 5 |
+
Tag: py3-none-any
|
| 6 |
+
|
TTS/Kokoro/.venv/Lib/site-packages/csvw-3.7.0.dist-info/entry_points.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[console_scripts]
|
| 2 |
+
csvw2datasette = csvw.__main__:csvw2datasette
|
| 3 |
+
csvw2json = csvw.__main__:csvw2json
|
| 4 |
+
csvw2markdown = csvw.__main__:csvw2markdown
|
| 5 |
+
csvw2sqlite = csvw.__main__:csvw2sqlite
|
| 6 |
+
csvwdescribe = csvw.__main__:csvwdescribe
|
| 7 |
+
csvwvalidate = csvw.__main__:csvwvalidate
|
TTS/Kokoro/.venv/Lib/site-packages/csvw-3.7.0.dist-info/top_level.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
csvw
|
TTS/Kokoro/.venv/Lib/site-packages/csvw/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# csvw - https://w3c.github.io/csvw/primer/
|
| 2 |
+
|
| 3 |
+
from .metadata import (
|
| 4 |
+
TableGroup, Table, Column, ForeignKey, Link, NaturalLanguage, Datatype, URITemplate, CSVW,
|
| 5 |
+
Dialect)
|
| 6 |
+
|
| 7 |
+
from .dsv import (UnicodeWriter,
|
| 8 |
+
UnicodeReader, UnicodeReaderWithLineNumber, UnicodeDictReader, NamedTupleReader,
|
| 9 |
+
iterrows, rewrite)
|
| 10 |
+
|
| 11 |
+
__all__ = [
|
| 12 |
+
'TableGroup',
|
| 13 |
+
'Table', 'Column', 'ForeignKey',
|
| 14 |
+
'Link', 'NaturalLanguage',
|
| 15 |
+
'Datatype',
|
| 16 |
+
'URITemplate',
|
| 17 |
+
'Dialect', 'UnicodeWriter',
|
| 18 |
+
'UnicodeReader', 'UnicodeReaderWithLineNumber', 'UnicodeDictReader', 'NamedTupleReader',
|
| 19 |
+
'iterrows', 'rewrite',
|
| 20 |
+
'CSVW',
|
| 21 |
+
]
|
| 22 |
+
|
| 23 |
+
__title__ = 'csvw'
|
| 24 |
+
__version__ = '3.7.0'
|
| 25 |
+
__author__ = 'Robert Forkel'
|
| 26 |
+
__license__ = 'Apache 2.0, see LICENSE'
|
| 27 |
+
__copyright__ = 'Copyright (c) 2025 Robert Forkel'
|
TTS/Kokoro/.venv/Lib/site-packages/csvw/__main__.py
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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csvw import CSVW, TableGroup
|
| 11 |
+
from csvw.db import Database
|
| 12 |
+
from csvw.utils import metadata2markdown
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def parsed_args(desc, args, *argspecs):
|
| 16 |
+
if args is None: # pragma: no cover
|
| 17 |
+
parser = argparse.ArgumentParser(description=desc)
|
| 18 |
+
for kw, kwargs in argspecs:
|
| 19 |
+
parser.add_argument(*kw, **kwargs)
|
| 20 |
+
return parser.parse_args()
|
| 21 |
+
return args
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def exit(ret, test=False):
|
| 25 |
+
if test:
|
| 26 |
+
return ret
|
| 27 |
+
sys.exit(ret) # pragma: no cover
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def csvwdescribe(args=None, test=False):
|
| 31 |
+
frictionless = shutil.which('frictionless')
|
| 32 |
+
if not frictionless: # pragma: no cover
|
| 33 |
+
raise ValueError('The frictionless command must be installed for this functionality!\n'
|
| 34 |
+
'Run `pip install frictionless` and try again.')
|
| 35 |
+
|
| 36 |
+
args = parsed_args(
|
| 37 |
+
"Describe a (set of) CSV file(s) with basic CSVW metadata.",
|
| 38 |
+
args,
|
| 39 |
+
(['--delimiter'], dict(default=None)),
|
| 40 |
+
(['csv'], dict(nargs='+', help="CSV files to describe as CSVW TableGroup")),
|
| 41 |
+
)
|
| 42 |
+
fargs = ['describe', '--json']
|
| 43 |
+
if args.delimiter:
|
| 44 |
+
fargs.extend(['--dialect', '{"delimiter": "%s"}' % args.delimiter])
|
| 45 |
+
onefile = False
|
| 46 |
+
if len(args.csv) == 1 and '*' not in args.csv[0]:
|
| 47 |
+
onefile = True
|
| 48 |
+
# Make sure we infer a tabular-data schema even if the file suffix does not suggest a CSV
|
| 49 |
+
# file.
|
| 50 |
+
fargs.extend(['--format', 'csv'])
|
| 51 |
+
else:
|
| 52 |
+
fargs.extend(['--type', 'package'])
|
| 53 |
+
|
| 54 |
+
dp = json.loads(subprocess.check_output([frictionless] + fargs + args.csv))
|
| 55 |
+
if onefile:
|
| 56 |
+
dp = dict(resources=[dp], profile='data-package')
|
| 57 |
+
|
| 58 |
+
tg = TableGroup.from_frictionless_datapackage(dp)
|
| 59 |
+
print(json.dumps(tg.asdict(), indent=4))
|
| 60 |
+
return exit(0, test=test)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def csvwvalidate(args=None, test=False):
|
| 64 |
+
args = parsed_args(
|
| 65 |
+
"Validate a (set of) CSV file(s) described by CSVW metadata.",
|
| 66 |
+
args,
|
| 67 |
+
(['url'], dict(help='URL or local path to CSV or JSON metadata file.')),
|
| 68 |
+
(['-v', '--verbose'], dict(action='store_true', default=False)),
|
| 69 |
+
)
|
| 70 |
+
ret = 0
|
| 71 |
+
try:
|
| 72 |
+
csvw = CSVW(args.url, validate=True)
|
| 73 |
+
if csvw.is_valid:
|
| 74 |
+
print(colored('OK', 'green', attrs=['bold']))
|
| 75 |
+
else:
|
| 76 |
+
ret = 1
|
| 77 |
+
print(colored('FAIL', 'red', attrs=['bold']))
|
| 78 |
+
if args.verbose:
|
| 79 |
+
for w in csvw.warnings:
|
| 80 |
+
print(colored(str(w.message), 'blue'))
|
| 81 |
+
except ValueError as e:
|
| 82 |
+
ret = 2
|
| 83 |
+
print(colored('FAIL', 'red', attrs=['bold']))
|
| 84 |
+
if args.verbose:
|
| 85 |
+
print(colored(str(e), 'blue'))
|
| 86 |
+
return exit(ret, test=test)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def csvw2datasette(args=None, test=False):
|
| 90 |
+
args = parsed_args(
|
| 91 |
+
"Convert CSVW to data for datasette (https://datasette.io/).",
|
| 92 |
+
args,
|
| 93 |
+
(['url'], dict(help='URL or local path to CSV or JSON metadata file.')),
|
| 94 |
+
(['-o', '--outdir'], dict(type=pathlib.Path, default=pathlib.Path('.'))),
|
| 95 |
+
)
|
| 96 |
+
dbname, mdname = 'datasette.db', 'datasette-metadata.json'
|
| 97 |
+
csvw = CSVW(args.url)
|
| 98 |
+
db = Database(csvw.tablegroup, fname=args.outdir / dbname)
|
| 99 |
+
db.write_from_tg()
|
| 100 |
+
md = {}
|
| 101 |
+
for k in ['title', 'description', 'license']:
|
| 102 |
+
if 'dc:{}'.format(k) in csvw.common_props:
|
| 103 |
+
md[k] = csvw.common_props['dc:{}'.format(k)]
|
| 104 |
+
# FIXME: flesh out, see https://docs.datasette.io/en/stable/metadata.html
|
| 105 |
+
args.outdir.joinpath(mdname).write_text(json.dumps(md, indent=4))
|
| 106 |
+
print("""Run
|
| 107 |
+
datasette {} --metadata {}
|
| 108 |
+
and open your browser at
|
| 109 |
+
http://localhost:8001/
|
| 110 |
+
to browse the data.
|
| 111 |
+
""".format(args.outdir / dbname, args.outdir / mdname))
|
| 112 |
+
return exit(0, test=test)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def csvw2json(args=None, test=False):
|
| 116 |
+
args = parsed_args(
|
| 117 |
+
"Convert CSVW to JSON, see https://w3c.github.io/csvw/csv2json/",
|
| 118 |
+
args,
|
| 119 |
+
(['url'], dict(help='URL or local path to CSV or JSON metadata file.')),
|
| 120 |
+
)
|
| 121 |
+
csvw = CSVW(args.url)
|
| 122 |
+
print(json.dumps(csvw.to_json(), indent=4))
|
| 123 |
+
return exit(0, test=test)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def csvw2sqlite(args=None, test=False): # pragma: no cover
|
| 127 |
+
args = parsed_args(
|
| 128 |
+
"Convert CSVW to JSON, see https://w3c.github.io/csvw/csv2json/",
|
| 129 |
+
args,
|
| 130 |
+
(
|
| 131 |
+
['url'],
|
| 132 |
+
dict(help='URL or local path to CSVW metadata file describing a TableGroup.\n\n'
|
| 133 |
+
'Note that not all valid CSVW datasets can be converted to SQLite. One '
|
| 134 |
+
'limitation is that all tables which are referenced by foreign keys must '
|
| 135 |
+
'have a primary key.')),
|
| 136 |
+
(
|
| 137 |
+
['output'],
|
| 138 |
+
dict(help='Path for the generated SQLite database file.')),
|
| 139 |
+
)
|
| 140 |
+
tg = TableGroup.from_file(args.url)
|
| 141 |
+
db = Database(tg, args.output)
|
| 142 |
+
db.write_from_tg(_force=True)
|
| 143 |
+
return exit(0, test=test)
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def csvw2markdown(args=None, test=False):
|
| 147 |
+
args = parsed_args(
|
| 148 |
+
"Convert CSVW to JSON, see https://w3c.github.io/csvw/csv2json/",
|
| 149 |
+
args,
|
| 150 |
+
(
|
| 151 |
+
['url'],
|
| 152 |
+
dict(help='URL or local path to CSVW metadata file describing a TableGroup.\n\n'
|
| 153 |
+
'Note that not all valid CSVW datasets can be converted to SQLite. One '
|
| 154 |
+
'limitation is that all tables which are referenced by foreign keys must '
|
| 155 |
+
'have a primary key.')),
|
| 156 |
+
)
|
| 157 |
+
tg = TableGroup.from_file(args.url)
|
| 158 |
+
print(metadata2markdown(tg, link_files=True))
|
| 159 |
+
return exit(0, test=test)
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
if __name__ == '__main__': # pragma: no cover
|
| 163 |
+
csvw2json()
|
TTS/Kokoro/.venv/Lib/site-packages/csvw/datatypes.py
ADDED
|
@@ -0,0 +1,1280 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
We model the hierarchy of basic datatypes using a class hierarchy.
|
| 3 |
+
|
| 4 |
+
`Derived datatypes <https://www.w3.org/TR/tabular-metadata/#derived-datatypes>`_ are implemented
|
| 5 |
+
via :class:`csvw.Datatype` which is
|
| 6 |
+
`composed of <https://realpython.com/inheritance-composition-python/#whats-composition>`_
|
| 7 |
+
a basic datatype and additional behaviour.
|
| 8 |
+
|
| 9 |
+
.. seealso:: http://w3c.github.io/csvw/metadata/#datatypes
|
| 10 |
+
"""
|
| 11 |
+
import re
|
| 12 |
+
import json as _json
|
| 13 |
+
import math
|
| 14 |
+
import base64
|
| 15 |
+
import typing
|
| 16 |
+
import decimal as _decimal
|
| 17 |
+
import binascii
|
| 18 |
+
import datetime
|
| 19 |
+
import warnings
|
| 20 |
+
import itertools
|
| 21 |
+
import collections
|
| 22 |
+
|
| 23 |
+
import isodate
|
| 24 |
+
import rfc3986
|
| 25 |
+
import dateutil.parser
|
| 26 |
+
import babel.numbers
|
| 27 |
+
import babel.dates
|
| 28 |
+
import jsonschema
|
| 29 |
+
|
| 30 |
+
if typing.TYPE_CHECKING: # pragma: no cover
|
| 31 |
+
import csvw
|
| 32 |
+
|
| 33 |
+
__all__ = ['DATATYPES']
|
| 34 |
+
|
| 35 |
+
DATATYPES = {}
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def register(cls):
|
| 39 |
+
DATATYPES[cls.name] = cls
|
| 40 |
+
return cls
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def to_binary(s, encoding='utf-8'):
|
| 44 |
+
if not isinstance(s, bytes):
|
| 45 |
+
return bytes(s, encoding=encoding)
|
| 46 |
+
return s # pragma: no cover
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@register
|
| 50 |
+
class anyAtomicType:
|
| 51 |
+
"""
|
| 52 |
+
A basic datatype consists of
|
| 53 |
+
|
| 54 |
+
- a bag of attributes, most importantly a `name` which matches the name or alias of one of the \
|
| 55 |
+
`CSVW built-in datatypes <https://www.w3.org/TR/tabular-metadata/#built-in-datatypes>`_
|
| 56 |
+
- three staticmethods controlling marshalling and unmarshalling of Python objects to strings.
|
| 57 |
+
|
| 58 |
+
Theses methods are orchestrated from :class:`csvw.Datatype` in its `read` and `formatted`
|
| 59 |
+
methods.
|
| 60 |
+
"""
|
| 61 |
+
name = 'any'
|
| 62 |
+
minmax = False
|
| 63 |
+
example = 'x'
|
| 64 |
+
|
| 65 |
+
@classmethod
|
| 66 |
+
def value_error(cls, v):
|
| 67 |
+
raise ValueError('invalid lexical value for {}: {}'.format(cls.name, v))
|
| 68 |
+
|
| 69 |
+
def __str__(self) -> str:
|
| 70 |
+
return self.name
|
| 71 |
+
|
| 72 |
+
@staticmethod
|
| 73 |
+
def derived_description(datatype: "csvw.Datatype") -> dict:
|
| 74 |
+
return {}
|
| 75 |
+
|
| 76 |
+
@staticmethod
|
| 77 |
+
def to_python(v: str, **kw) -> object:
|
| 78 |
+
return v # pragma: no cover
|
| 79 |
+
|
| 80 |
+
@staticmethod
|
| 81 |
+
def to_string(v: object, **kw) -> str:
|
| 82 |
+
return '{}'.format(v)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
@register
|
| 86 |
+
class string(anyAtomicType):
|
| 87 |
+
"""
|
| 88 |
+
Maps to `str`.
|
| 89 |
+
|
| 90 |
+
The lexical and value spaces of xs:string are the set of all possible strings composed of
|
| 91 |
+
any character allowed in a XML 1.0 document without any treatment done on whitespaces.
|
| 92 |
+
"""
|
| 93 |
+
name = 'string'
|
| 94 |
+
|
| 95 |
+
@staticmethod
|
| 96 |
+
def derived_description(datatype: "csvw.Datatype") -> dict:
|
| 97 |
+
if datatype.format:
|
| 98 |
+
# We wrap a regex specified as `format` property into a group and add `$` to
|
| 99 |
+
# make sure the whole string is matched when validating.
|
| 100 |
+
try:
|
| 101 |
+
return {'regex': re.compile(r'({})$'.format(datatype.format))}
|
| 102 |
+
except re.error:
|
| 103 |
+
warnings.warn('Invalid regex pattern as datatype format')
|
| 104 |
+
return {}
|
| 105 |
+
|
| 106 |
+
@staticmethod
|
| 107 |
+
def to_python(v, regex=None):
|
| 108 |
+
if regex and not regex.match(v):
|
| 109 |
+
string.value_error(v)
|
| 110 |
+
return v
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
@register
|
| 114 |
+
class anyURI(string):
|
| 115 |
+
"""
|
| 116 |
+
Maps to `rfc3986.URIReference`.
|
| 117 |
+
|
| 118 |
+
This datatype corresponds normatively to the XLink href attribute. Its value space includes
|
| 119 |
+
the URIs defined by the RFCs `2396 <https://datatracker.ietf.org/doc/html/rfc2396>`_ and
|
| 120 |
+
`2732 <https://datatracker.ietf.org/doc/html/rfc2732>`_, but its lexical space doesn’t
|
| 121 |
+
require the character escapes needed to include non-ASCII characters in URIs.
|
| 122 |
+
|
| 123 |
+
.. note::
|
| 124 |
+
|
| 125 |
+
We normalize URLs according to the rules in
|
| 126 |
+
`RFC 3986 <https://datatracker.ietf.org/doc/html/rfc3986#section-6.2>`_ when serializing
|
| 127 |
+
to `str`. Thus roundtripping isn't guaranteed.
|
| 128 |
+
"""
|
| 129 |
+
name = 'anyURI'
|
| 130 |
+
|
| 131 |
+
@staticmethod
|
| 132 |
+
def to_python(v, regex=None):
|
| 133 |
+
res = string.to_python(v, regex=regex)
|
| 134 |
+
return rfc3986.URIReference.from_string(res.encode('utf-8'))
|
| 135 |
+
|
| 136 |
+
@staticmethod
|
| 137 |
+
def to_string(v, **kw):
|
| 138 |
+
if hasattr(v, 'geturl'):
|
| 139 |
+
# Presumably a `urllib.parse.ParseResult`.
|
| 140 |
+
return v.geturl()
|
| 141 |
+
if hasattr(v, 'unsplit'):
|
| 142 |
+
# Presumable a `rfc3986.URIReference`
|
| 143 |
+
return v.unsplit()
|
| 144 |
+
assert isinstance(v, str)
|
| 145 |
+
return rfc3986.normalize_uri(v)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
@register
|
| 149 |
+
class NMTOKEN(string):
|
| 150 |
+
"""
|
| 151 |
+
Maps to `str`
|
| 152 |
+
|
| 153 |
+
The lexical and value spaces of xs:NMTOKEN are the set of XML 1.0 “name tokens,” i.e.,
|
| 154 |
+
tokens composed of characters, digits, “.”, “:”, “-”, and the characters defined by Unicode,
|
| 155 |
+
such as “combining” or “extender”.
|
| 156 |
+
|
| 157 |
+
This type is usually called a “token.”
|
| 158 |
+
|
| 159 |
+
Valid values include "Snoopy", "CMS", "1950-10-04", or "0836217462".
|
| 160 |
+
|
| 161 |
+
Invalid values include "brought classical music to the Peanuts strip" (spaces are forbidden)
|
| 162 |
+
or "bold,brash" (commas are forbidden).
|
| 163 |
+
"""
|
| 164 |
+
name = "NMTOKEN"
|
| 165 |
+
|
| 166 |
+
@staticmethod
|
| 167 |
+
def to_python(v, regex=None):
|
| 168 |
+
v = string.to_python(v, regex=regex)
|
| 169 |
+
if not re.fullmatch(r'[\w.:-]*', v):
|
| 170 |
+
NMTOKEN.value_error(v)
|
| 171 |
+
return v
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
@register
|
| 175 |
+
class base64Binary(anyAtomicType):
|
| 176 |
+
"""
|
| 177 |
+
Maps to `bytes`
|
| 178 |
+
"""
|
| 179 |
+
name = 'base64Binary'
|
| 180 |
+
example = 'YWJj'
|
| 181 |
+
|
| 182 |
+
@staticmethod
|
| 183 |
+
def to_python(v, **kw):
|
| 184 |
+
try:
|
| 185 |
+
res = to_binary(v, encoding='ascii')
|
| 186 |
+
except UnicodeEncodeError:
|
| 187 |
+
base64Binary.value_error(v[:10])
|
| 188 |
+
try:
|
| 189 |
+
res = base64.decodebytes(res)
|
| 190 |
+
except Exception:
|
| 191 |
+
raise ValueError('invalid base64 encoding')
|
| 192 |
+
return res
|
| 193 |
+
|
| 194 |
+
@staticmethod
|
| 195 |
+
def to_string(v, **kw):
|
| 196 |
+
return base64.encodebytes(v).decode().strip()
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
@register
|
| 200 |
+
class _binary(base64Binary):
|
| 201 |
+
"""
|
| 202 |
+
Maps to `bytes`. Alias for :class:`base64Binary`
|
| 203 |
+
"""
|
| 204 |
+
name = 'binary'
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
@register
|
| 208 |
+
class hexBinary(anyAtomicType):
|
| 209 |
+
"""
|
| 210 |
+
Maps to `bytes`.
|
| 211 |
+
|
| 212 |
+
.. note::
|
| 213 |
+
|
| 214 |
+
We normalize to uppercase hex digits when seriializing to `str`. Thus, roundtripping is
|
| 215 |
+
limited.
|
| 216 |
+
"""
|
| 217 |
+
name = 'hexBinary'
|
| 218 |
+
example = 'ab'
|
| 219 |
+
|
| 220 |
+
@staticmethod
|
| 221 |
+
def to_python(v, **kw):
|
| 222 |
+
try:
|
| 223 |
+
res = to_binary(v, encoding='ascii')
|
| 224 |
+
except UnicodeEncodeError:
|
| 225 |
+
hexBinary.value_error(v[:10])
|
| 226 |
+
try:
|
| 227 |
+
res = binascii.unhexlify(res)
|
| 228 |
+
except (binascii.Error, TypeError):
|
| 229 |
+
raise ValueError('invalid hexBinary encoding')
|
| 230 |
+
return res
|
| 231 |
+
|
| 232 |
+
@staticmethod
|
| 233 |
+
def to_string(v, **kw):
|
| 234 |
+
return binascii.hexlify(v).decode().upper()
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
@register
|
| 238 |
+
class boolean(anyAtomicType):
|
| 239 |
+
"""
|
| 240 |
+
Maps to `bool`.
|
| 241 |
+
|
| 242 |
+
.. code-block:: python
|
| 243 |
+
|
| 244 |
+
>>> from csvw import Datatype
|
| 245 |
+
>>> dt = Datatype.fromvalue({"base": "boolean", "format": "Yea|Nay"})
|
| 246 |
+
>>> dt.read('Nay')
|
| 247 |
+
False
|
| 248 |
+
>>> dt.formatted(True)
|
| 249 |
+
'Yea'
|
| 250 |
+
|
| 251 |
+
.. seealso:: `<https://www.w3.org/TR/tabular-data-model/#formats-for-booleans>`_
|
| 252 |
+
"""
|
| 253 |
+
|
| 254 |
+
name = 'boolean'
|
| 255 |
+
example = 'false'
|
| 256 |
+
|
| 257 |
+
@staticmethod
|
| 258 |
+
def derived_description(datatype: "csvw.Datatype") -> dict:
|
| 259 |
+
if datatype.format and isinstance(datatype.format, str) and datatype.format.count('|') == 1:
|
| 260 |
+
true, false = [[v] for v in datatype.format.split('|')]
|
| 261 |
+
else:
|
| 262 |
+
if datatype.format and (
|
| 263 |
+
(not isinstance(datatype.format, str)) or (datatype.format.count('|') != 1)):
|
| 264 |
+
warnings.warn('Invalid format spec for boolean')
|
| 265 |
+
true, false = ['true', '1'], ['false', '0']
|
| 266 |
+
return {'true': true, 'false': false}
|
| 267 |
+
|
| 268 |
+
@staticmethod
|
| 269 |
+
def to_python(s, true=('true', '1'), false=('false', '0')):
|
| 270 |
+
if isinstance(s, bool) or s is None:
|
| 271 |
+
return s
|
| 272 |
+
if s in true:
|
| 273 |
+
return True
|
| 274 |
+
if s in false:
|
| 275 |
+
return False
|
| 276 |
+
raise boolean.value_error(s)
|
| 277 |
+
|
| 278 |
+
@staticmethod
|
| 279 |
+
def to_string(v, true=('true', '1'), false=('false', '0')):
|
| 280 |
+
return (true if v else false)[0]
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def with_tz(v, func, args, kw):
|
| 284 |
+
tz_pattern = re.compile('(Z|[+-][0-2][0-9]:[0-5][0-9])$')
|
| 285 |
+
tz = tz_pattern.search(v)
|
| 286 |
+
if tz:
|
| 287 |
+
v = v[:tz.start()]
|
| 288 |
+
tz = tz.groups()[0]
|
| 289 |
+
res = func(v, *args, **kw)
|
| 290 |
+
if tz:
|
| 291 |
+
dt = dateutil.parser.parse('{}{}'.format(datetime.datetime.now(), tz))
|
| 292 |
+
res = datetime.datetime(
|
| 293 |
+
res.year, res.month, res.day, res.hour, res.minute, res.second, res.microsecond,
|
| 294 |
+
dt.tzinfo)
|
| 295 |
+
return res
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
@register
|
| 299 |
+
class dateTime(anyAtomicType):
|
| 300 |
+
"""
|
| 301 |
+
Maps to `datetime.datetime`.
|
| 302 |
+
"""
|
| 303 |
+
name = 'datetime'
|
| 304 |
+
minmax = True
|
| 305 |
+
example = '2018-12-10T20:20:20'
|
| 306 |
+
|
| 307 |
+
@staticmethod
|
| 308 |
+
def derived_description(datatype: "csvw.Datatype") -> dict:
|
| 309 |
+
return dt_format_and_regex(datatype.format)
|
| 310 |
+
|
| 311 |
+
@staticmethod
|
| 312 |
+
def _parse(v, cls, regex, tz_marker=None):
|
| 313 |
+
v = v.strip()
|
| 314 |
+
try:
|
| 315 |
+
comps = regex.match(v).groupdict()
|
| 316 |
+
except AttributeError: # pragma: no cover
|
| 317 |
+
dateTime.value_error(v)
|
| 318 |
+
if comps.get('extramicroseconds'):
|
| 319 |
+
raise ValueError('Extra microseconds')
|
| 320 |
+
if comps.get('microsecond'):
|
| 321 |
+
# We have to convert decimal fractions of seconds to microseconds.
|
| 322 |
+
# This is done by first chopping off anything under 6 decimal places,
|
| 323 |
+
# then (in case we got less precision) right-padding with 0 to get a
|
| 324 |
+
# 6-digit number.
|
| 325 |
+
comps['microsecond'] = comps['microsecond'][:6].ljust(6, '0')
|
| 326 |
+
if cls == datetime.datetime and 'year' not in comps:
|
| 327 |
+
d = datetime.date.today()
|
| 328 |
+
for a in ['year', 'month', 'day']:
|
| 329 |
+
comps[a] = getattr(d, a)
|
| 330 |
+
res = cls(**{k: int(v) for k, v in comps.items() if v is not None})
|
| 331 |
+
if tz_marker:
|
| 332 |
+
# Let dateutils take care of parsing the timezone info:
|
| 333 |
+
res = res.replace(tzinfo=dateutil.parser.parse(v).tzinfo)
|
| 334 |
+
return res
|
| 335 |
+
|
| 336 |
+
@staticmethod
|
| 337 |
+
def to_python(v, regex=None, fmt=None, tz_marker=None, pattern=None):
|
| 338 |
+
if pattern and regex:
|
| 339 |
+
match = regex.match(v)
|
| 340 |
+
if not match:
|
| 341 |
+
raise ValueError('{} -- {} -- {}'.format(pattern, v, regex)) # pragma:
|
| 342 |
+
try:
|
| 343 |
+
return dateutil.parser.isoparse(v)
|
| 344 |
+
except ValueError:
|
| 345 |
+
return dateTime._parse(v, datetime.datetime, regex, tz_marker=tz_marker)
|
| 346 |
+
|
| 347 |
+
@staticmethod
|
| 348 |
+
def to_string(v, regex=None, fmt=None, tz_marker=None, pattern=None):
|
| 349 |
+
if pattern:
|
| 350 |
+
return babel.dates.format_datetime(v, tzinfo=v.tzinfo, format=pattern)
|
| 351 |
+
return v.isoformat()
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
@register
|
| 355 |
+
class _dateTime(dateTime):
|
| 356 |
+
"""
|
| 357 |
+
Maps to `datetime.datetime`. Alias for :class:`dateTime`
|
| 358 |
+
"""
|
| 359 |
+
name = 'dateTime'
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
@register
|
| 363 |
+
class date(dateTime):
|
| 364 |
+
"""
|
| 365 |
+
Maps to `datetime.datetime` (in order to be able to preserve timezone information).
|
| 366 |
+
"""
|
| 367 |
+
name = 'date'
|
| 368 |
+
example = '2018-12-10'
|
| 369 |
+
|
| 370 |
+
@staticmethod
|
| 371 |
+
def derived_description(datatype: "csvw.Datatype") -> dict:
|
| 372 |
+
try:
|
| 373 |
+
return dt_format_and_regex(datatype.format or 'yyyy-MM-dd')
|
| 374 |
+
except ValueError:
|
| 375 |
+
warnings.warn('Invalid date format')
|
| 376 |
+
return dt_format_and_regex('yyyy-MM-dd')
|
| 377 |
+
|
| 378 |
+
@staticmethod
|
| 379 |
+
def to_python(v, regex=None, fmt=None, tz_marker=None, pattern=None):
|
| 380 |
+
return with_tz(
|
| 381 |
+
v.strip(), dateTime.to_python, [], dict(regex=regex, fmt=fmt, pattern=pattern))
|
| 382 |
+
|
| 383 |
+
@staticmethod
|
| 384 |
+
def to_string(v, regex=None, fmt=None, tz_marker=None, pattern=None):
|
| 385 |
+
from babel.dates import format_date
|
| 386 |
+
if pattern:
|
| 387 |
+
return format_date(v, format=pattern, locale='en')
|
| 388 |
+
return dateTime.to_string(v, regex=regex, fmt=fmt, tz_marker=tz_marker, pattern=pattern)
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
@register
|
| 392 |
+
class dateTimeStamp(dateTime):
|
| 393 |
+
"""
|
| 394 |
+
Maps to `datetime.datetime`.
|
| 395 |
+
"""
|
| 396 |
+
name = 'dateTimeStamp'
|
| 397 |
+
example = '2018-12-10T20:20:20'
|
| 398 |
+
|
| 399 |
+
@staticmethod
|
| 400 |
+
def derived_description(datatype: "csvw.Datatype") -> dict:
|
| 401 |
+
res = dt_format_and_regex(datatype.format or 'yyyy-MM-ddTHH:mm:ss.SSSSSSXXX')
|
| 402 |
+
if not res['tz_marker']:
|
| 403 |
+
raise ValueError('dateTimeStamp must have timezone marker')
|
| 404 |
+
return res
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
@register
|
| 408 |
+
class _time(dateTime):
|
| 409 |
+
"""
|
| 410 |
+
Maps to `datetime.datetime` (in order to be able to preserve timezone information).
|
| 411 |
+
"""
|
| 412 |
+
name = 'time'
|
| 413 |
+
example = '20:20:20'
|
| 414 |
+
|
| 415 |
+
@staticmethod
|
| 416 |
+
def derived_description(datatype: "csvw.Datatype") -> dict:
|
| 417 |
+
return dt_format_and_regex(datatype.format or 'HH:mm:ss', no_date=True)
|
| 418 |
+
|
| 419 |
+
@staticmethod
|
| 420 |
+
def to_python(v, regex=None, fmt=None, tz_marker=None, pattern=None):
|
| 421 |
+
if pattern and 'x' in pattern.lower():
|
| 422 |
+
return dateutil.parser.parse('{}T{}'.format(datetime.date.today().isoformat(), v))
|
| 423 |
+
assert regex is not None
|
| 424 |
+
return with_tz(v, dateTime._parse, [datetime.datetime, regex], dict(tz_marker=tz_marker))
|
| 425 |
+
|
| 426 |
+
@staticmethod
|
| 427 |
+
def to_string(v, regex=None, fmt=None, tz_marker=None, pattern=None):
|
| 428 |
+
return babel.dates.format_time(v, tzinfo=v.tzinfo, format=pattern)
|
| 429 |
+
|
| 430 |
+
|
| 431 |
+
@register
|
| 432 |
+
class duration(anyAtomicType):
|
| 433 |
+
"""
|
| 434 |
+
Maps to `datetime.timedelta`.
|
| 435 |
+
|
| 436 |
+
.. code-block: python
|
| 437 |
+
|
| 438 |
+
>>> from csvw import Datatype
|
| 439 |
+
>>> dt = Datatype.fromvalue("datetime")
|
| 440 |
+
>>> duration = Datatype.fromvalue("duration")
|
| 441 |
+
>>> dt.formatted(dt.read("2022-06-24T12:00:00") + duration.read("P1MT2H"))
|
| 442 |
+
'2022-07-24T14:00:00'
|
| 443 |
+
|
| 444 |
+
"""
|
| 445 |
+
name = 'duration'
|
| 446 |
+
example = 'P3Y6M4DT12H30M5S'
|
| 447 |
+
|
| 448 |
+
@staticmethod
|
| 449 |
+
def derived_description(datatype: "csvw.Datatype") -> dict:
|
| 450 |
+
return {'format': datatype.format}
|
| 451 |
+
|
| 452 |
+
@staticmethod
|
| 453 |
+
def to_python(v, format=None, **kw):
|
| 454 |
+
if format and not re.match(format, v):
|
| 455 |
+
raise ValueError
|
| 456 |
+
return isodate.parse_duration(v)
|
| 457 |
+
|
| 458 |
+
@staticmethod
|
| 459 |
+
def to_string(v, format=None, **kw):
|
| 460 |
+
return isodate.duration_isoformat(v)
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
@register
|
| 464 |
+
class dayTimeDuration(duration):
|
| 465 |
+
"""
|
| 466 |
+
Maps to `datetime.timedelta`.
|
| 467 |
+
"""
|
| 468 |
+
name = 'dayTimeDuration'
|
| 469 |
+
|
| 470 |
+
|
| 471 |
+
@register
|
| 472 |
+
class yearMonthDuration(duration):
|
| 473 |
+
"""
|
| 474 |
+
Maps to `datetime.timedelta`.
|
| 475 |
+
"""
|
| 476 |
+
name = 'yearMonthDuration'
|
| 477 |
+
|
| 478 |
+
|
| 479 |
+
@register
|
| 480 |
+
class decimal(anyAtomicType):
|
| 481 |
+
"""
|
| 482 |
+
Maps to `decimal.Decimal`.
|
| 483 |
+
|
| 484 |
+
xs:decimal is the datatype that represents the set of all the decimal numbers with
|
| 485 |
+
arbitrary lengths. Its lexical space allows any number of insignificant leading and
|
| 486 |
+
trailing zeros (after the decimal point).
|
| 487 |
+
|
| 488 |
+
There is no support for scientific notations.
|
| 489 |
+
|
| 490 |
+
Valid values include: "123.456", "+1234.456", "-1234.456", "-.456", or "-456".
|
| 491 |
+
|
| 492 |
+
The following values would be invalid: [...] "1234.456E+2" (scientific notation ("E+2")
|
| 493 |
+
is forbidden).
|
| 494 |
+
|
| 495 |
+
XML-Schema restricts the lexical space by disallowing "thousand separator" and forcing the
|
| 496 |
+
decimal separator to be ".". But these limitations can be overcome within CSVW using a
|
| 497 |
+
`derived datatype <https://www.w3.org/TR/tabular-data-model/#formats-for-numeric-types>`_:
|
| 498 |
+
|
| 499 |
+
.. code-block:: python
|
| 500 |
+
|
| 501 |
+
>>> from csvw import Datatype
|
| 502 |
+
>>> dt = Datatype.fromvalue(
|
| 503 |
+
... {"base": "decimal", "format": {"groupChar": ".", "decimalChar": ","}})
|
| 504 |
+
>>> dt.read("1.234,5")
|
| 505 |
+
Decimal('1234.5')
|
| 506 |
+
|
| 507 |
+
.. note::
|
| 508 |
+
|
| 509 |
+
While mapping to `decimal.Decimal` rather than `float` makes handling of the Python object
|
| 510 |
+
somewhat cumbersome, it makes sure we can roundtrip values correctly.
|
| 511 |
+
"""
|
| 512 |
+
name = 'decimal'
|
| 513 |
+
minmax = True
|
| 514 |
+
example = '5'
|
| 515 |
+
|
| 516 |
+
_special = {
|
| 517 |
+
'INF': 'Infinity',
|
| 518 |
+
'-INF': '-Infinity',
|
| 519 |
+
'NaN': 'NaN',
|
| 520 |
+
}
|
| 521 |
+
_reverse_special = {v: k for k, v in _special.items()}
|
| 522 |
+
|
| 523 |
+
@staticmethod
|
| 524 |
+
def derived_description(datatype: "csvw.Datatype") -> dict:
|
| 525 |
+
if datatype.format:
|
| 526 |
+
return datatype.format if isinstance(datatype.format, dict) \
|
| 527 |
+
else {'pattern': datatype.format}
|
| 528 |
+
return {}
|
| 529 |
+
|
| 530 |
+
@staticmethod
|
| 531 |
+
def to_python(v, pattern=None, decimalChar=None, groupChar=None):
|
| 532 |
+
if isinstance(v, str) and 'e' in v.lower():
|
| 533 |
+
raise ValueError('Invalid value for decimal')
|
| 534 |
+
|
| 535 |
+
if isinstance(v, str) and re.search('{0}{0}+'.format(re.escape(groupChar or ',')), v):
|
| 536 |
+
raise ValueError('Invalid value for decimal')
|
| 537 |
+
|
| 538 |
+
if groupChar is None and pattern and ',' in pattern:
|
| 539 |
+
groupChar = ','
|
| 540 |
+
if decimalChar is None and pattern and '.' in pattern:
|
| 541 |
+
decimalChar = '.'
|
| 542 |
+
if pattern and not NumberPattern(pattern).is_valid(
|
| 543 |
+
v.replace(groupChar or ',', ',').replace(decimalChar or '.', '.')):
|
| 544 |
+
raise ValueError(
|
| 545 |
+
'Invalid value "{}" for decimal with pattern "{}"'.format(v, pattern))
|
| 546 |
+
|
| 547 |
+
factor = 1
|
| 548 |
+
if isinstance(v, str):
|
| 549 |
+
if v in decimal._special:
|
| 550 |
+
warnings.warn('Invalid special value for decimal')
|
| 551 |
+
return _decimal.Decimal(decimal._special[v])
|
| 552 |
+
if groupChar:
|
| 553 |
+
v = v.replace(groupChar, '')
|
| 554 |
+
if decimalChar and decimalChar != '.':
|
| 555 |
+
v = v.replace(decimalChar, '.')
|
| 556 |
+
for c, factor in [('%', _decimal.Decimal('0.01')), ('‰', _decimal.Decimal('0.001'))]:
|
| 557 |
+
if c in v:
|
| 558 |
+
v = v.replace(c, '')
|
| 559 |
+
break
|
| 560 |
+
else:
|
| 561 |
+
factor = 1
|
| 562 |
+
try:
|
| 563 |
+
return _decimal.Decimal(v) * factor
|
| 564 |
+
except (TypeError, _decimal.InvalidOperation):
|
| 565 |
+
decimal.value_error(v)
|
| 566 |
+
|
| 567 |
+
@staticmethod
|
| 568 |
+
def to_string(v, pattern=None, decimalChar=None, groupChar=None):
|
| 569 |
+
if '{}'.format(v) in decimal._reverse_special:
|
| 570 |
+
return decimal._reverse_special['{}'.format(v)]
|
| 571 |
+
|
| 572 |
+
if pattern:
|
| 573 |
+
v = babel.numbers.format_decimal(v, pattern, 'en')
|
| 574 |
+
if decimalChar:
|
| 575 |
+
v = v.replace('.', decimalChar)
|
| 576 |
+
if groupChar:
|
| 577 |
+
v = v.replace(',', groupChar)
|
| 578 |
+
return v
|
| 579 |
+
|
| 580 |
+
fmt = '{}' if groupChar is None else '{:,}'
|
| 581 |
+
try:
|
| 582 |
+
neg = v < 0
|
| 583 |
+
except TypeError:
|
| 584 |
+
neg = None
|
| 585 |
+
v = fmt.format(v)
|
| 586 |
+
if 'e' in v.lower(): # detect scientific notation
|
| 587 |
+
digits, exp = v.lower().split('e')
|
| 588 |
+
digits = digits.replace('.', '').replace('-', '')
|
| 589 |
+
exp = int(exp)
|
| 590 |
+
zero_padding = '0' * (abs(int(exp)) - 1)
|
| 591 |
+
sign = '-' if neg else ''
|
| 592 |
+
return '{}{}{}.0'.format(sign, digits, zero_padding) if exp > 0 else (
|
| 593 |
+
'{}0.{}{}'.format(sign, zero_padding, digits))
|
| 594 |
+
|
| 595 |
+
if groupChar or decimalChar:
|
| 596 |
+
def repl(m):
|
| 597 |
+
if m.group('c') == ',':
|
| 598 |
+
return groupChar
|
| 599 |
+
if m.group('c') == '.':
|
| 600 |
+
return decimalChar
|
| 601 |
+
r = '(?P<c>[{}])'.format(re.escape((decimalChar or '') + (groupChar or '')))
|
| 602 |
+
v = re.sub(r, repl, v)
|
| 603 |
+
return v
|
| 604 |
+
|
| 605 |
+
|
| 606 |
+
@register
|
| 607 |
+
class integer(decimal):
|
| 608 |
+
"""
|
| 609 |
+
Maps to `int`.
|
| 610 |
+
"""
|
| 611 |
+
name = 'integer'
|
| 612 |
+
range = None
|
| 613 |
+
|
| 614 |
+
@classmethod
|
| 615 |
+
def to_python(cls, v, **kw):
|
| 616 |
+
res = decimal.to_python(v, **kw)
|
| 617 |
+
numerator, denominator = res.as_integer_ratio()
|
| 618 |
+
if denominator == 1:
|
| 619 |
+
if cls.range and not (cls.range[0] <= numerator <= cls.range[1]):
|
| 620 |
+
raise ValueError("{} must be an integer between {} and {}, but got ".format(
|
| 621 |
+
cls.name, cls.range[0], cls.range[1]), v)
|
| 622 |
+
return numerator
|
| 623 |
+
raise ValueError('Invalid value for integer')
|
| 624 |
+
|
| 625 |
+
|
| 626 |
+
@register
|
| 627 |
+
class _int(integer):
|
| 628 |
+
"""
|
| 629 |
+
Maps to `int`. Alias for :class:`integer`.
|
| 630 |
+
"""
|
| 631 |
+
name = 'int'
|
| 632 |
+
|
| 633 |
+
|
| 634 |
+
@register
|
| 635 |
+
class unsignedInt(integer):
|
| 636 |
+
"""
|
| 637 |
+
Maps to `int`.
|
| 638 |
+
|
| 639 |
+
The value space of xs:unsignedInt is the integers between 0 and 4294967295, i.e., the
|
| 640 |
+
unsigned values that can fit in a word of 32 bits. Its lexical space allows an optional “+”
|
| 641 |
+
sign and leading zeros before the significant digits.
|
| 642 |
+
|
| 643 |
+
The decimal point (even when followed only by insignificant zeros) is forbidden.
|
| 644 |
+
|
| 645 |
+
Valid values include "4294967295", "0", "+0000000000000000000005", or "1".
|
| 646 |
+
|
| 647 |
+
Invalid values include "-1" and "1.".
|
| 648 |
+
"""
|
| 649 |
+
name = 'unsignedInt'
|
| 650 |
+
range = (0, 4294967295)
|
| 651 |
+
|
| 652 |
+
|
| 653 |
+
@register
|
| 654 |
+
class unsignedShort(integer):
|
| 655 |
+
"""
|
| 656 |
+
Maps to `int`.
|
| 657 |
+
|
| 658 |
+
The value space of xs:unsignedShort is the integers between 0 and 65535, i.e., the unsigned
|
| 659 |
+
values that can fit in a word of 16 bits. Its lexical space allows an optional “+” sign and
|
| 660 |
+
leading zeros before the significant digits.
|
| 661 |
+
|
| 662 |
+
The decimal point (even when followed only by insignificant zeros) is forbidden.
|
| 663 |
+
|
| 664 |
+
Valid values include "65535", "0", "+0000000000000000000005", or "1".
|
| 665 |
+
|
| 666 |
+
Invalid values include "-1" and "1." .
|
| 667 |
+
"""
|
| 668 |
+
name = 'unsignedShort'
|
| 669 |
+
range = (0, 65535)
|
| 670 |
+
|
| 671 |
+
|
| 672 |
+
@register
|
| 673 |
+
class unsignedLong(integer):
|
| 674 |
+
"""
|
| 675 |
+
Maps to `int`.
|
| 676 |
+
|
| 677 |
+
The value space of xs:unsignedLong is the integers between 0 and 18446744073709551615, i.e.,
|
| 678 |
+
the unsigned values that can fit in a word of 64 bits. Its lexical space allows an optional
|
| 679 |
+
“+” sign and leading zeros before the significant digits.
|
| 680 |
+
|
| 681 |
+
The decimal point (even when followed only by insignificant zeros) is forbidden.
|
| 682 |
+
|
| 683 |
+
Valid values include "18446744073709551615", "0", "+0000000000000000000005", or "1".
|
| 684 |
+
|
| 685 |
+
Invalid values include "-1" and "1.".
|
| 686 |
+
"""
|
| 687 |
+
name = 'unsignedLong'
|
| 688 |
+
range = (0, 18446744073709551615)
|
| 689 |
+
|
| 690 |
+
|
| 691 |
+
@register
|
| 692 |
+
class unsignedByte(integer):
|
| 693 |
+
"""
|
| 694 |
+
Maps to `int`.
|
| 695 |
+
|
| 696 |
+
The value space of xs:unsignedByte is the integers between 0 and 255, i.e., the unsigned
|
| 697 |
+
values that can fit in a word of 8 bits. Its lexical space allows an optional “+” sign and
|
| 698 |
+
leading zeros before the significant digits.
|
| 699 |
+
|
| 700 |
+
The lexical space does not allow values expressed in other numeration bases (such as
|
| 701 |
+
hexadecimal, octal, or binary).
|
| 702 |
+
|
| 703 |
+
The decimal point (even when followed only by insignificant zeros) is forbidden.
|
| 704 |
+
|
| 705 |
+
Valid values include "255", "0", "+0000000000000000000005", or "1".
|
| 706 |
+
|
| 707 |
+
Invalid values include "-1" and "1.".
|
| 708 |
+
"""
|
| 709 |
+
name = 'unsignedByte'
|
| 710 |
+
range = (0, 255)
|
| 711 |
+
|
| 712 |
+
|
| 713 |
+
@register
|
| 714 |
+
class short(integer):
|
| 715 |
+
"""
|
| 716 |
+
Maps to `int`.
|
| 717 |
+
|
| 718 |
+
The value space of xs:short is the set of common short integers (16 bits), i.e., the
|
| 719 |
+
integers between -32768 and 32767; its lexical space allows any number of insignificant
|
| 720 |
+
leading zeros.
|
| 721 |
+
|
| 722 |
+
The decimal point (even when followed only by insignificant zeros) is forbidden.
|
| 723 |
+
|
| 724 |
+
Valid values include "-32768", "0", "-0000000000000000000005", or "32767".
|
| 725 |
+
|
| 726 |
+
Invalid values include "32768" and "1.".
|
| 727 |
+
"""
|
| 728 |
+
name = 'short'
|
| 729 |
+
range = (-32768, 32767)
|
| 730 |
+
|
| 731 |
+
|
| 732 |
+
@register
|
| 733 |
+
class long(integer):
|
| 734 |
+
"""
|
| 735 |
+
Maps to `int`.
|
| 736 |
+
|
| 737 |
+
The value space of xs:long is the set of common double-size integers (64 bits), i.e., the
|
| 738 |
+
integers between -9223372036854775808 and 9223372036854775807; its lexical space allows any
|
| 739 |
+
number of insignificant leading zeros.
|
| 740 |
+
|
| 741 |
+
The decimal point (even when followed only by insignificant zeros) is forbidden.
|
| 742 |
+
|
| 743 |
+
Valid values for xs:long include "-9223372036854775808", "0", "-0000000000000000000005", or
|
| 744 |
+
"9223372036854775807".
|
| 745 |
+
|
| 746 |
+
Invalid values include "9223372036854775808" and "1.".
|
| 747 |
+
"""
|
| 748 |
+
name = 'long'
|
| 749 |
+
range = (-9223372036854775808, 9223372036854775807)
|
| 750 |
+
|
| 751 |
+
|
| 752 |
+
@register
|
| 753 |
+
class byte(integer):
|
| 754 |
+
"""
|
| 755 |
+
Maps to `int`.
|
| 756 |
+
|
| 757 |
+
The value space of xs:byte is the integers between -128 and 127, i.e., the signed values
|
| 758 |
+
that can fit in a word of 8 bits. Its lexical space allows an optional sign and leading
|
| 759 |
+
zeros before the significant digits.
|
| 760 |
+
|
| 761 |
+
The lexical space does not allow values expressed in other numeration bases (such as
|
| 762 |
+
hexadecimal, octal, or binary).
|
| 763 |
+
|
| 764 |
+
Valid values for byte include 27, -34, +105, and 0.
|
| 765 |
+
|
| 766 |
+
Invalid values include 0A, 1524, and INF.
|
| 767 |
+
"""
|
| 768 |
+
name = 'byte'
|
| 769 |
+
range = (-128, 127)
|
| 770 |
+
|
| 771 |
+
|
| 772 |
+
@register
|
| 773 |
+
class nonNegativeInteger(integer):
|
| 774 |
+
"""
|
| 775 |
+
Maps to `int`.
|
| 776 |
+
"""
|
| 777 |
+
name = 'nonNegativeInteger'
|
| 778 |
+
range = (0, math.inf)
|
| 779 |
+
|
| 780 |
+
|
| 781 |
+
@register
|
| 782 |
+
class positiveInteger(integer):
|
| 783 |
+
"""
|
| 784 |
+
Maps to `int`.
|
| 785 |
+
"""
|
| 786 |
+
name = 'positiveInteger'
|
| 787 |
+
range = (1, math.inf)
|
| 788 |
+
|
| 789 |
+
|
| 790 |
+
@register
|
| 791 |
+
class nonPositiveInteger(integer):
|
| 792 |
+
"""
|
| 793 |
+
Maps to `int`.
|
| 794 |
+
"""
|
| 795 |
+
name = 'nonPositiveInteger'
|
| 796 |
+
example = '-5'
|
| 797 |
+
range = (-math.inf, 0)
|
| 798 |
+
|
| 799 |
+
|
| 800 |
+
@register
|
| 801 |
+
class negativeInteger(integer):
|
| 802 |
+
"""
|
| 803 |
+
Maps to `int`.
|
| 804 |
+
"""
|
| 805 |
+
name = 'negativeInteger'
|
| 806 |
+
example = '-5'
|
| 807 |
+
range = (-math.inf, -1)
|
| 808 |
+
|
| 809 |
+
|
| 810 |
+
@register
|
| 811 |
+
class _float(anyAtomicType):
|
| 812 |
+
"""
|
| 813 |
+
Maps to `float`.
|
| 814 |
+
|
| 815 |
+
.. note::
|
| 816 |
+
|
| 817 |
+
Due to the well known issues with representing floating point numbers, roundtripping may
|
| 818 |
+
not work correctly.
|
| 819 |
+
|
| 820 |
+
.. seealso:: `<https://docs.python.org/3/tutorial/floatingpoint.html>`_
|
| 821 |
+
"""
|
| 822 |
+
name = 'float'
|
| 823 |
+
minmax = True
|
| 824 |
+
example = '5.3'
|
| 825 |
+
|
| 826 |
+
@staticmethod
|
| 827 |
+
def derived_description(datatype: "csvw.Datatype") -> dict:
|
| 828 |
+
if datatype.format:
|
| 829 |
+
return datatype.format if isinstance(datatype.format, dict) \
|
| 830 |
+
else {'pattern': datatype.format}
|
| 831 |
+
return {}
|
| 832 |
+
|
| 833 |
+
@staticmethod
|
| 834 |
+
def to_python(v, pattern=None, **kw):
|
| 835 |
+
if pattern and not NumberPattern(pattern).is_valid(v):
|
| 836 |
+
raise ValueError(
|
| 837 |
+
'Invalid value "{}" for number with pattern "{}"'.format(v, pattern))
|
| 838 |
+
|
| 839 |
+
try:
|
| 840 |
+
return float(v)
|
| 841 |
+
except (TypeError, ValueError):
|
| 842 |
+
_float.value_error(v)
|
| 843 |
+
|
| 844 |
+
@staticmethod
|
| 845 |
+
def to_string(v, **kw):
|
| 846 |
+
return '{}'.format(v)
|
| 847 |
+
|
| 848 |
+
|
| 849 |
+
@register
|
| 850 |
+
class number(_float):
|
| 851 |
+
"""
|
| 852 |
+
Maps to `float`.
|
| 853 |
+
"""
|
| 854 |
+
name = 'number'
|
| 855 |
+
|
| 856 |
+
|
| 857 |
+
@register
|
| 858 |
+
class double(_float):
|
| 859 |
+
"""
|
| 860 |
+
Maps to `float`.
|
| 861 |
+
"""
|
| 862 |
+
name = 'double'
|
| 863 |
+
|
| 864 |
+
|
| 865 |
+
@register
|
| 866 |
+
class normalizedString(string):
|
| 867 |
+
"""
|
| 868 |
+
Maps to `str`.
|
| 869 |
+
|
| 870 |
+
The lexical space of xs:normalizedString is unconstrained (any valid XML character may be
|
| 871 |
+
used), and its value space is the set of strings after whitespace replacement (i.e., after
|
| 872 |
+
any occurrence of #x9 (tab), #xA (linefeed), and #xD (carriage return) have been replaced
|
| 873 |
+
by an occurrence of #x20 (space) without any whitespace collapsing).
|
| 874 |
+
|
| 875 |
+
.. note::
|
| 876 |
+
|
| 877 |
+
The CSVW test suite (specifically in `test036 <https://w3c.github.io/csvw/tests/#test036>`_
|
| 878 |
+
and `test037 <https://w3c.github.io/csvw/tests/#test037>`_) requires that `normalizedString`
|
| 879 |
+
is also trimmed, i.e. stripped from leading and trailing whitespace. So that's we do.
|
| 880 |
+
"""
|
| 881 |
+
name = 'normalizedString'
|
| 882 |
+
|
| 883 |
+
@staticmethod
|
| 884 |
+
def to_python(v, regex=None):
|
| 885 |
+
if v:
|
| 886 |
+
for c in '\r\n\t':
|
| 887 |
+
v = v.replace(c, ' ')
|
| 888 |
+
v = v.strip()
|
| 889 |
+
return string.to_python(v, '')
|
| 890 |
+
|
| 891 |
+
|
| 892 |
+
@register
|
| 893 |
+
class QName(string):
|
| 894 |
+
"""
|
| 895 |
+
Maps to `str`.
|
| 896 |
+
"""
|
| 897 |
+
name = 'QName'
|
| 898 |
+
|
| 899 |
+
|
| 900 |
+
@register
|
| 901 |
+
class gDay(string):
|
| 902 |
+
"""
|
| 903 |
+
Maps to `str`.
|
| 904 |
+
"""
|
| 905 |
+
name = 'gDay'
|
| 906 |
+
|
| 907 |
+
|
| 908 |
+
@register
|
| 909 |
+
class gMonth(string):
|
| 910 |
+
"""
|
| 911 |
+
Maps to `str`.
|
| 912 |
+
"""
|
| 913 |
+
name = 'gMonth'
|
| 914 |
+
|
| 915 |
+
|
| 916 |
+
@register
|
| 917 |
+
class gMonthDay(string):
|
| 918 |
+
"""
|
| 919 |
+
Maps to `str`.
|
| 920 |
+
"""
|
| 921 |
+
name = 'gMonthDay'
|
| 922 |
+
|
| 923 |
+
|
| 924 |
+
@register
|
| 925 |
+
class gYear(string):
|
| 926 |
+
"""
|
| 927 |
+
Maps to `str`.
|
| 928 |
+
"""
|
| 929 |
+
name = 'gYear'
|
| 930 |
+
|
| 931 |
+
|
| 932 |
+
@register
|
| 933 |
+
class gYearMonth(string):
|
| 934 |
+
"""
|
| 935 |
+
Maps to `str`.
|
| 936 |
+
"""
|
| 937 |
+
name = 'gYearMonth'
|
| 938 |
+
|
| 939 |
+
|
| 940 |
+
@register
|
| 941 |
+
class xml(string):
|
| 942 |
+
"""
|
| 943 |
+
Maps to `str`.
|
| 944 |
+
"""
|
| 945 |
+
name = 'xml'
|
| 946 |
+
|
| 947 |
+
|
| 948 |
+
@register
|
| 949 |
+
class html(string):
|
| 950 |
+
"""
|
| 951 |
+
Maps to `str`.
|
| 952 |
+
"""
|
| 953 |
+
name = 'html'
|
| 954 |
+
|
| 955 |
+
|
| 956 |
+
@register
|
| 957 |
+
class json(string):
|
| 958 |
+
"""
|
| 959 |
+
Maps to `str`, `list` or `dict`, i.e. to the result of `json.loads`.
|
| 960 |
+
|
| 961 |
+
.. code-block:: python
|
| 962 |
+
|
| 963 |
+
>>> from csvw import Datatype
|
| 964 |
+
>>> dt = Datatype.fromvalue("json")
|
| 965 |
+
>>> d = dt.read("{}")
|
| 966 |
+
>>> d["a"] = '123'
|
| 967 |
+
>>> dt.formatted(d)
|
| 968 |
+
'{"a": "123"}'
|
| 969 |
+
|
| 970 |
+
Additional constraints on JSON data can be imposed by specifying
|
| 971 |
+
`JSON Schema <https://json-schema.org/>`_ documents as `format` annotation:
|
| 972 |
+
|
| 973 |
+
.. code-block:: python
|
| 974 |
+
|
| 975 |
+
>>> from csvw import Datatype
|
| 976 |
+
>>> dt = Datatype.fromvalue({"base": "json", "format": '{"type": "object"}'})
|
| 977 |
+
>>> dt.read('{}')
|
| 978 |
+
OrderedDict()
|
| 979 |
+
>>> dt.read('4')
|
| 980 |
+
...
|
| 981 |
+
jsonschema.exceptions.ValidationError: 4 is not of type 'object'
|
| 982 |
+
...
|
| 983 |
+
ValueError: invalid lexical value for json: 4
|
| 984 |
+
|
| 985 |
+
.. note::
|
| 986 |
+
|
| 987 |
+
To ensure proper roundtripping, we load the JSON strings using the
|
| 988 |
+
`object_pairs_hook=collections.OrderedDict` keyword.
|
| 989 |
+
"""
|
| 990 |
+
name = 'json'
|
| 991 |
+
example = '{"a": [1,2]}'
|
| 992 |
+
|
| 993 |
+
@staticmethod
|
| 994 |
+
def derived_description(datatype: "csvw.Datatype") -> dict:
|
| 995 |
+
if datatype.format:
|
| 996 |
+
try:
|
| 997 |
+
schema = _json.loads(datatype.format)
|
| 998 |
+
try:
|
| 999 |
+
jsonschema.validate({}, schema=schema)
|
| 1000 |
+
return {'schema': schema}
|
| 1001 |
+
except jsonschema.ValidationError:
|
| 1002 |
+
return {'schema': schema}
|
| 1003 |
+
except jsonschema.SchemaError:
|
| 1004 |
+
warnings.warn('Invalid JSON schema as datatype format')
|
| 1005 |
+
except _json.JSONDecodeError:
|
| 1006 |
+
pass
|
| 1007 |
+
return {}
|
| 1008 |
+
|
| 1009 |
+
# FIXME: ignored **kw?
|
| 1010 |
+
# why not just to_python = staticmethod(_json.loads)?
|
| 1011 |
+
@staticmethod
|
| 1012 |
+
def to_python(v, schema=None, **kw):
|
| 1013 |
+
res = _json.loads(v, object_pairs_hook=collections.OrderedDict)
|
| 1014 |
+
if schema:
|
| 1015 |
+
try:
|
| 1016 |
+
jsonschema.validate(res, schema=schema)
|
| 1017 |
+
except jsonschema.ValidationError:
|
| 1018 |
+
json.value_error(v)
|
| 1019 |
+
return res
|
| 1020 |
+
|
| 1021 |
+
@staticmethod
|
| 1022 |
+
def to_string(v, **kw):
|
| 1023 |
+
return _json.dumps(v)
|
| 1024 |
+
|
| 1025 |
+
|
| 1026 |
+
def dt_format_and_regex(fmt, no_date=False):
|
| 1027 |
+
"""
|
| 1028 |
+
|
| 1029 |
+
.. seealso:: http://w3c.github.io/csvw/syntax/#formats-for-dates-and-times
|
| 1030 |
+
"""
|
| 1031 |
+
if fmt is None:
|
| 1032 |
+
return {'fmt': None, 'tz_marker': None, 'regex': None, 'pattern': None}
|
| 1033 |
+
|
| 1034 |
+
if isinstance(fmt, dict) and list(fmt.keys()) == ['pattern']:
|
| 1035 |
+
fmt = fmt['pattern']
|
| 1036 |
+
|
| 1037 |
+
pattern = fmt
|
| 1038 |
+
|
| 1039 |
+
# First, we strip off an optional timezone marker:
|
| 1040 |
+
tz_marker = None
|
| 1041 |
+
match = re.search('(?P<marker> ?[xX]{1,3})$', fmt)
|
| 1042 |
+
if match:
|
| 1043 |
+
tz_marker = match.group('marker')
|
| 1044 |
+
if len(set(tz_marker.strip())) != 1: # mixing x and X is not allowed!
|
| 1045 |
+
raise ValueError(fmt)
|
| 1046 |
+
fmt = fmt[:match.start()]
|
| 1047 |
+
|
| 1048 |
+
date_patterns = {
|
| 1049 |
+
"yyyy-MM-dd", # e.g., 2015-03-22
|
| 1050 |
+
"yyyyMMdd", # e.g., 20150322
|
| 1051 |
+
"dd-MM-yyyy", # e.g., 22-03-2015
|
| 1052 |
+
"d-M-yyyy", # e.g., 22-3-2015
|
| 1053 |
+
"MM-dd-yyyy", # e.g., 03-22-2015
|
| 1054 |
+
"M-d-yyyy", # e.g., 3-22-2015
|
| 1055 |
+
"dd/MM/yyyy", # e.g., 22/03/2015
|
| 1056 |
+
"d/M/yyyy", # e.g., 22/3/2015
|
| 1057 |
+
"MM/dd/yyyy", # e.g., 03/22/2015
|
| 1058 |
+
"M/d/yyyy", # e.g., 3/22/2015
|
| 1059 |
+
"dd.MM.yyyy", # e.g., 22.03.2015
|
| 1060 |
+
"d.M.yyyy", # e.g., 22.3.2015
|
| 1061 |
+
"MM.dd.yyyy", # e.g., 03.22.2015
|
| 1062 |
+
"M.d.yyyy", # e.g., 3.22.2015
|
| 1063 |
+
}
|
| 1064 |
+
|
| 1065 |
+
time_patterns = {"HH:mm:ss", "HHmmss", "HH:mm", "HHmm"}
|
| 1066 |
+
|
| 1067 |
+
# We map dateTime component markers to corresponding fromat specs and regular
|
| 1068 |
+
# expressions used for formatting and parsing.
|
| 1069 |
+
translate = {
|
| 1070 |
+
'yyyy': ('{dt.year:04d}', '(?P<year>[0-9]{4})'),
|
| 1071 |
+
'MM': ('{dt.month:02d}', '(?P<month>[0-9]{2})'),
|
| 1072 |
+
'dd': ('{dt.day:02d}', '(?P<day>[0-9]{2})'),
|
| 1073 |
+
'M': ('{dt.month}', '(?P<month>[0-9]{1,2})'),
|
| 1074 |
+
'd': ('{dt.day}', '(?P<day>[0-9]{1,2})'),
|
| 1075 |
+
'HH': ('{dt.hour:02d}', '(?P<hour>[0-9]{2})'),
|
| 1076 |
+
'mm': ('{dt.minute:02d}', '(?P<minute>[0-9]{2})'),
|
| 1077 |
+
'ss': ('{dt.second:02d}', '(?P<second>[0-9]{2})'),
|
| 1078 |
+
}
|
| 1079 |
+
|
| 1080 |
+
for dt_sep in ' T': # Only a single space or "T" may separate date and time format.
|
| 1081 |
+
# Since space or "T" isn't allowed anywhere else in the format, checking whether
|
| 1082 |
+
# we are dealing with a date or dateTime format is simple:
|
| 1083 |
+
if dt_sep in fmt:
|
| 1084 |
+
break
|
| 1085 |
+
else:
|
| 1086 |
+
dt_sep = None
|
| 1087 |
+
|
| 1088 |
+
if dt_sep:
|
| 1089 |
+
dfmt, tfmt = fmt.split(dt_sep)
|
| 1090 |
+
elif no_date:
|
| 1091 |
+
dfmt, tfmt = None, fmt
|
| 1092 |
+
else:
|
| 1093 |
+
dfmt, tfmt = fmt, None
|
| 1094 |
+
|
| 1095 |
+
msecs = None # The maximal number of decimal places for fractions of seconds.
|
| 1096 |
+
if tfmt and '.' in tfmt: # There is a microseconds marker.
|
| 1097 |
+
tfmt, msecs = tfmt.split('.') # Strip it off ...
|
| 1098 |
+
if set(msecs) != {'S'}: # ... make sure it's valid ...
|
| 1099 |
+
raise ValueError(fmt)
|
| 1100 |
+
msecs = len(msecs) # ... and store it's length.
|
| 1101 |
+
|
| 1102 |
+
# Now we can check whether the bare date and time formats are valid:
|
| 1103 |
+
if (dfmt and dfmt not in date_patterns) or (tfmt and tfmt not in time_patterns):
|
| 1104 |
+
raise ValueError(fmt)
|
| 1105 |
+
|
| 1106 |
+
regex, format = '', '' # Initialize the output.
|
| 1107 |
+
|
| 1108 |
+
if dfmt:
|
| 1109 |
+
for d_sep in '.-/': # Determine the separator used for date components.
|
| 1110 |
+
if d_sep in dfmt:
|
| 1111 |
+
break
|
| 1112 |
+
else:
|
| 1113 |
+
d_sep = None
|
| 1114 |
+
|
| 1115 |
+
if d_sep:
|
| 1116 |
+
# Iterate over date components, converting them to string format specs and regular
|
| 1117 |
+
# expressions.
|
| 1118 |
+
for i, part in enumerate(dfmt.split(d_sep)):
|
| 1119 |
+
if i > 0:
|
| 1120 |
+
format += d_sep
|
| 1121 |
+
regex += re.escape(d_sep)
|
| 1122 |
+
f, r = translate[part]
|
| 1123 |
+
format += f
|
| 1124 |
+
regex += r
|
| 1125 |
+
else:
|
| 1126 |
+
for _, chars in itertools.groupby(dfmt, lambda k: k):
|
| 1127 |
+
f, r = translate[''.join(chars)]
|
| 1128 |
+
format += f
|
| 1129 |
+
regex += r
|
| 1130 |
+
|
| 1131 |
+
if dt_sep:
|
| 1132 |
+
format += dt_sep
|
| 1133 |
+
regex += re.escape(dt_sep)
|
| 1134 |
+
|
| 1135 |
+
if tfmt:
|
| 1136 |
+
# For time components the only valid separator is ":".
|
| 1137 |
+
if ':' in tfmt:
|
| 1138 |
+
for i, part in enumerate(tfmt.split(':')):
|
| 1139 |
+
if i > 0:
|
| 1140 |
+
format += ':'
|
| 1141 |
+
regex += re.escape(':')
|
| 1142 |
+
f, r = translate[part]
|
| 1143 |
+
format += f
|
| 1144 |
+
regex += r
|
| 1145 |
+
else:
|
| 1146 |
+
for _, chars in itertools.groupby(tfmt, lambda k: k):
|
| 1147 |
+
f, r = translate[''.join(chars)]
|
| 1148 |
+
format += f
|
| 1149 |
+
regex += r
|
| 1150 |
+
|
| 1151 |
+
# Fractions of seconds are a bit of a problem, because datetime objects only offer
|
| 1152 |
+
# microseconds.
|
| 1153 |
+
if msecs:
|
| 1154 |
+
format += '.{microsecond:.%s}' % msecs
|
| 1155 |
+
regex += r'(\.(?P<microsecond>[0-9]{1,%s})(?![0-9]))?' % msecs
|
| 1156 |
+
regex += r'(\.(?P<extramicroseconds>[0-9]{%s,})(?![0-9]))?' % (msecs + 1,)
|
| 1157 |
+
|
| 1158 |
+
return {'regex': re.compile(regex), 'fmt': format, 'tz_marker': tz_marker, 'pattern': pattern}
|
| 1159 |
+
|
| 1160 |
+
|
| 1161 |
+
class NumberPattern:
|
| 1162 |
+
"""
|
| 1163 |
+
Implementations MUST recognise number format patterns containing the symbols 0, #, the specified
|
| 1164 |
+
decimalChar (or "." if unspecified), the specified groupChar (or "," if unspecified), E, +, %
|
| 1165 |
+
and ‰.
|
| 1166 |
+
|
| 1167 |
+
The number of # placeholder characters before the decimal do not matter, since no limit is
|
| 1168 |
+
placed on the maximum number of digits. There should, however, be at least one zero someplace
|
| 1169 |
+
in the pattern.
|
| 1170 |
+
"""
|
| 1171 |
+
|
| 1172 |
+
def __init__(self, pattern):
|
| 1173 |
+
assert pattern.count(';') <= 1
|
| 1174 |
+
self.positive, _, self.negative = pattern.partition(';')
|
| 1175 |
+
if not self.negative:
|
| 1176 |
+
self.negative = '-' + self.positive.replace('+', '')
|
| 1177 |
+
|
| 1178 |
+
@property
|
| 1179 |
+
def primary_grouping_size(self):
|
| 1180 |
+
comps = self.positive.split('.')[0].split(',')
|
| 1181 |
+
if len(comps) > 1:
|
| 1182 |
+
return comps[-1].count('#') + comps[-1].count('0')
|
| 1183 |
+
|
| 1184 |
+
@property
|
| 1185 |
+
def secondary_grouping_size(self):
|
| 1186 |
+
comps = self.positive.split('.')[0].split(',')
|
| 1187 |
+
if len(comps) > 2:
|
| 1188 |
+
return comps[1].count('#') + comps[1].count('0')
|
| 1189 |
+
return self.primary_grouping_size
|
| 1190 |
+
|
| 1191 |
+
@property
|
| 1192 |
+
def min_digits_before_decimal_point(self):
|
| 1193 |
+
integral_part = self.positive.split('.')[0]
|
| 1194 |
+
match = re.search('([0]+)$', integral_part)
|
| 1195 |
+
if match:
|
| 1196 |
+
return len(match.groups()[0])
|
| 1197 |
+
|
| 1198 |
+
@property
|
| 1199 |
+
def exponent_digits(self):
|
| 1200 |
+
_, _, exponent = self.positive.lower().partition('e')
|
| 1201 |
+
i = 0
|
| 1202 |
+
for c in exponent:
|
| 1203 |
+
if c in '0#':
|
| 1204 |
+
i += 1
|
| 1205 |
+
elif c in ',':
|
| 1206 |
+
continue
|
| 1207 |
+
else:
|
| 1208 |
+
break
|
| 1209 |
+
return i
|
| 1210 |
+
|
| 1211 |
+
@property
|
| 1212 |
+
def decimal_digits(self):
|
| 1213 |
+
i = 0
|
| 1214 |
+
_, _, decimal_part = self.positive.partition('.')
|
| 1215 |
+
for c in decimal_part:
|
| 1216 |
+
if c in '#0':
|
| 1217 |
+
i += 1
|
| 1218 |
+
if c == 'E':
|
| 1219 |
+
break
|
| 1220 |
+
return i
|
| 1221 |
+
|
| 1222 |
+
@property
|
| 1223 |
+
def significant_decimal_digits(self):
|
| 1224 |
+
i = 0
|
| 1225 |
+
_, _, decimal_part = self.positive.partition('.')
|
| 1226 |
+
for c in decimal_part:
|
| 1227 |
+
if c == '0':
|
| 1228 |
+
i += 1
|
| 1229 |
+
if c in ['E', '#']:
|
| 1230 |
+
break
|
| 1231 |
+
return i
|
| 1232 |
+
|
| 1233 |
+
def is_valid(self, s):
|
| 1234 |
+
def digits(ss):
|
| 1235 |
+
return [c for c in ss if c not in '.,E+-%‰']
|
| 1236 |
+
|
| 1237 |
+
integral_part, _, decimal_part = s.partition('.')
|
| 1238 |
+
decimal_part, _, exponent = decimal_part.lower().partition('e')
|
| 1239 |
+
groups = integral_part.split(',')
|
| 1240 |
+
significant, leadingzero, skip = [], False, True
|
| 1241 |
+
for c in ''.join(groups):
|
| 1242 |
+
if c in ['+', '-', '%', # fixme: permil
|
| 1243 |
+
]:
|
| 1244 |
+
continue
|
| 1245 |
+
if c == '0' and skip:
|
| 1246 |
+
leadingzero = True
|
| 1247 |
+
continue
|
| 1248 |
+
if c != '0':
|
| 1249 |
+
skip = False
|
| 1250 |
+
significant.append(c)
|
| 1251 |
+
if not significant and leadingzero:
|
| 1252 |
+
significant = ['0']
|
| 1253 |
+
if self.min_digits_before_decimal_point and \
|
| 1254 |
+
len(significant) < self.min_digits_before_decimal_point:
|
| 1255 |
+
return False
|
| 1256 |
+
if self.primary_grouping_size and groups:
|
| 1257 |
+
if len(digits(groups[-1])) > self.primary_grouping_size:
|
| 1258 |
+
return False
|
| 1259 |
+
if len(groups) > 1 and len(digits(groups[-1])) < self.primary_grouping_size:
|
| 1260 |
+
return False
|
| 1261 |
+
if self.secondary_grouping_size and len(groups) > 1:
|
| 1262 |
+
for i, group in enumerate(groups[:-1]):
|
| 1263 |
+
if i == 0:
|
| 1264 |
+
if len(digits(group)) > self.secondary_grouping_size:
|
| 1265 |
+
return False
|
| 1266 |
+
else:
|
| 1267 |
+
if len(digits(group)) != self.secondary_grouping_size:
|
| 1268 |
+
return False
|
| 1269 |
+
if decimal_part:
|
| 1270 |
+
if len(digits(decimal_part)) > self.decimal_digits:
|
| 1271 |
+
return False
|
| 1272 |
+
if self.significant_decimal_digits:
|
| 1273 |
+
if (not decimal_part) or (len(digits(decimal_part)) < self.significant_decimal_digits):
|
| 1274 |
+
return False
|
| 1275 |
+
|
| 1276 |
+
if self.exponent_digits and 'e' in s.lower():
|
| 1277 |
+
if len(digits(s.lower().split('e')[-1])) > self.exponent_digits:
|
| 1278 |
+
return False
|
| 1279 |
+
|
| 1280 |
+
return True
|
TTS/Kokoro/.venv/Lib/site-packages/csvw/db.py
ADDED
|
@@ -0,0 +1,581 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
SQLite as alternative storage backend for a TableGroup's data.
|
| 3 |
+
|
| 4 |
+
For the most part, translation of a TableGroup's tableSchema to SQL works as expected:
|
| 5 |
+
|
| 6 |
+
- each table is converted to a `CREATE TABLE` statement
|
| 7 |
+
- each column specifies a column in the corresponding `CREATE TABLE` statement
|
| 8 |
+
- `foreignKey` constraints are added according to the corresponding `tableSchema` property.
|
| 9 |
+
|
| 10 |
+
List-valued foreignKeys are supported as follows: For each pair of tables related through a
|
| 11 |
+
list-valued foreign key, an association table is created. To make it possible to distinguish
|
| 12 |
+
multiple list-valued foreign keys between the same two tables, the association table has
|
| 13 |
+
a column `context`, which stores the name of the foreign key column from which a row in the
|
| 14 |
+
assocation table was created.
|
| 15 |
+
|
| 16 |
+
Other list-valued columns work in two different ways: If the atomic datatype is `string`, the
|
| 17 |
+
specified separator is used to create a concatenated string representation in the database field.
|
| 18 |
+
Otherwise, the list of values is serialized as JSON.
|
| 19 |
+
|
| 20 |
+
SQL table and column names can be customized by passing a translator callable when instantiating
|
| 21 |
+
a :class:`Database`.
|
| 22 |
+
|
| 23 |
+
SQLite support has the following limitations:
|
| 24 |
+
|
| 25 |
+
- regex constraints on strings (as specified via a :class:`csvw.Datatype`'s format attribute) are
|
| 26 |
+
not enforced by the database.
|
| 27 |
+
"""
|
| 28 |
+
import json
|
| 29 |
+
import typing
|
| 30 |
+
import decimal
|
| 31 |
+
import pathlib
|
| 32 |
+
import sqlite3
|
| 33 |
+
import functools
|
| 34 |
+
import contextlib
|
| 35 |
+
import collections
|
| 36 |
+
|
| 37 |
+
import attr
|
| 38 |
+
|
| 39 |
+
import csvw
|
| 40 |
+
from csvw.datatypes import DATATYPES
|
| 41 |
+
from csvw.metadata import TableGroup
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def identity(s):
|
| 45 |
+
return s
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
TYPE_MAP = {
|
| 49 |
+
'string': (
|
| 50 |
+
'TEXT',
|
| 51 |
+
identity,
|
| 52 |
+
identity),
|
| 53 |
+
'integer': (
|
| 54 |
+
'INTEGER',
|
| 55 |
+
identity,
|
| 56 |
+
identity),
|
| 57 |
+
'boolean': (
|
| 58 |
+
'INTEGER',
|
| 59 |
+
lambda s: s if s is None else int(s),
|
| 60 |
+
lambda s: s if s is None else bool(s)),
|
| 61 |
+
'decimal': (
|
| 62 |
+
'REAL',
|
| 63 |
+
lambda s: s if s is None else float(s),
|
| 64 |
+
lambda s: s if s is None else decimal.Decimal(s)),
|
| 65 |
+
'hexBinary': (
|
| 66 |
+
'BLOB',
|
| 67 |
+
identity,
|
| 68 |
+
identity),
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
class SchemaTranslator(typing.Protocol):
|
| 73 |
+
def __call__(self, table: str, column: typing.Optional[str] = None) -> str:
|
| 74 |
+
... # pragma: no cover
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class ColumnTranslator(typing.Protocol):
|
| 78 |
+
def __call__(self, column: str) -> str:
|
| 79 |
+
... # pragma: no cover
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def quoted(*names):
|
| 83 |
+
return ','.join('`{0}`'.format(name) for name in names)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def insert(db: sqlite3.Connection,
|
| 87 |
+
translate: SchemaTranslator,
|
| 88 |
+
table: str,
|
| 89 |
+
keys: typing.Sequence[str],
|
| 90 |
+
*rows: list,
|
| 91 |
+
single: typing.Optional[bool] = False):
|
| 92 |
+
"""
|
| 93 |
+
Insert a sequence of rows into a table.
|
| 94 |
+
|
| 95 |
+
:param db: Database connection.
|
| 96 |
+
:param translate: Callable translating table and column names to proper schema object names.
|
| 97 |
+
:param table: Untranslated table name.
|
| 98 |
+
:param keys: Untranslated column names.
|
| 99 |
+
:param rows: Sequence of rows to insert.
|
| 100 |
+
:param single: Flag signaling whether to insert all rows at once using `executemany` or one at \
|
| 101 |
+
a time, allowing for more focused debugging output in case of errors.
|
| 102 |
+
"""
|
| 103 |
+
if rows:
|
| 104 |
+
sql = "INSERT INTO {0} ({1}) VALUES ({2})".format(
|
| 105 |
+
quoted(translate(table)),
|
| 106 |
+
quoted(*[translate(table, k) for k in keys]),
|
| 107 |
+
','.join(['?' for _ in keys]))
|
| 108 |
+
try:
|
| 109 |
+
db.executemany(sql, rows)
|
| 110 |
+
except: # noqa: E722 - this is purely for debugging.
|
| 111 |
+
if not single:
|
| 112 |
+
for row in rows:
|
| 113 |
+
insert(db, translate, table, keys, row, single=True)
|
| 114 |
+
else:
|
| 115 |
+
print(sql)
|
| 116 |
+
print(rows)
|
| 117 |
+
raise
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def select(db: sqlite3.Connection, table: str) -> typing.Tuple[typing.List[str], typing.Sequence]:
|
| 121 |
+
cu = db.execute("SELECT * FROM {0}".format(quoted(table)))
|
| 122 |
+
cols = [d[0] for d in cu.description]
|
| 123 |
+
return cols, list(cu.fetchall())
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
@attr.s
|
| 127 |
+
class ColSpec:
|
| 128 |
+
"""
|
| 129 |
+
A `ColSpec` captures sufficient information about a :class:`csvw.Column` for the DB schema.
|
| 130 |
+
"""
|
| 131 |
+
name = attr.ib()
|
| 132 |
+
csvw_type = attr.ib(default='string', converter=lambda s: s if s else 'string')
|
| 133 |
+
separator = attr.ib(default=None)
|
| 134 |
+
db_type = attr.ib(default=None)
|
| 135 |
+
convert = attr.ib(default=None)
|
| 136 |
+
read = attr.ib(default=None)
|
| 137 |
+
required = attr.ib(default=False)
|
| 138 |
+
csvw = attr.ib(default=None)
|
| 139 |
+
|
| 140 |
+
def __attrs_post_init__(self):
|
| 141 |
+
if self.csvw_type in TYPE_MAP:
|
| 142 |
+
self.db_type, self.convert, self.read = TYPE_MAP[self.csvw_type]
|
| 143 |
+
else:
|
| 144 |
+
self.db_type = 'TEXT'
|
| 145 |
+
self.convert = DATATYPES[self.csvw_type].to_string
|
| 146 |
+
self.read = DATATYPES[self.csvw_type].to_python
|
| 147 |
+
if self.separator and self.db_type != 'TEXT':
|
| 148 |
+
self.db_type = 'TEXT'
|
| 149 |
+
|
| 150 |
+
def check(self, translate: ColumnTranslator) -> typing.Optional[str]:
|
| 151 |
+
"""
|
| 152 |
+
We try to convert as many data constraints as possible into SQLite CHECK constraints.
|
| 153 |
+
|
| 154 |
+
:param translate: Callable to translate column names between CSVW metadata and DB schema.
|
| 155 |
+
:return: A string suitable as argument of an SQL CHECK constraint.
|
| 156 |
+
"""
|
| 157 |
+
if not self.csvw:
|
| 158 |
+
return
|
| 159 |
+
c, cname = self.csvw, translate(self.name)
|
| 160 |
+
constraints = []
|
| 161 |
+
if (c.minimum is not None) or (c.maximum is not None):
|
| 162 |
+
func = {
|
| 163 |
+
'date': 'date',
|
| 164 |
+
'datetime': 'datetime',
|
| 165 |
+
}.get(self.csvw_type)
|
| 166 |
+
if c.minimum is not None:
|
| 167 |
+
if func:
|
| 168 |
+
constraints.append("{2}(`{0}`) >= {2}('{1}')".format(cname, c.minimum, func))
|
| 169 |
+
else:
|
| 170 |
+
constraints.append('`{0}` >= {1}'.format(cname, c.minimum))
|
| 171 |
+
if c.maximum is not None:
|
| 172 |
+
if func:
|
| 173 |
+
constraints.append("{2}(`{0}`) <= {2}('{1}')".format(cname, c.maximum, func))
|
| 174 |
+
else:
|
| 175 |
+
constraints.append('`{0}` <= {1}'.format(cname, c.maximum))
|
| 176 |
+
elif any(cc is not None for cc in [c.length, c.minLength, c.maxLength]):
|
| 177 |
+
if c.length:
|
| 178 |
+
constraints.append('length(`{0}`) = {1}'.format(cname, c.length))
|
| 179 |
+
if c.minLength:
|
| 180 |
+
constraints.append('length(`{0}`) >= {1}'.format(cname, c.minLength))
|
| 181 |
+
if c.maxLength:
|
| 182 |
+
constraints.append('length(`{0}`) <= {1}'.format(cname, c.maxLength))
|
| 183 |
+
return ' AND '.join(constraints)
|
| 184 |
+
|
| 185 |
+
def sql(self, translate: ColumnTranslator) -> str:
|
| 186 |
+
_check = self.check(translate)
|
| 187 |
+
return '`{0}` {1}{2}{3}'.format(
|
| 188 |
+
translate(self.name),
|
| 189 |
+
self.db_type,
|
| 190 |
+
' NOT NULL' if self.required else '',
|
| 191 |
+
' CHECK ({0})'.format(_check) if _check else '')
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
@attr.s
|
| 195 |
+
class TableSpec(object):
|
| 196 |
+
"""
|
| 197 |
+
A `TableSpec` captures sufficient information about a :class:`csvw.Table` for the DB schema.
|
| 198 |
+
|
| 199 |
+
.. note::
|
| 200 |
+
|
| 201 |
+
We support "light-weight" many-to-many relationships by allowing list-valued foreign key
|
| 202 |
+
columns in CSVW. In the database these columns are turned into an associative table, adding
|
| 203 |
+
the name of the column as value a `context` column. Thus, multiple columns in a table my be
|
| 204 |
+
specified as targets of many-to-many relations with the same table.
|
| 205 |
+
|
| 206 |
+
.. seealso:: `<https://en.wikipedia.org/wiki/Associative_entity>`_
|
| 207 |
+
"""
|
| 208 |
+
name = attr.ib()
|
| 209 |
+
columns = attr.ib(default=attr.Factory(list))
|
| 210 |
+
foreign_keys = attr.ib(default=attr.Factory(list))
|
| 211 |
+
many_to_many = attr.ib(default=attr.Factory(collections.OrderedDict))
|
| 212 |
+
primary_key = attr.ib(default=None)
|
| 213 |
+
|
| 214 |
+
@classmethod
|
| 215 |
+
def from_table_metadata(cls,
|
| 216 |
+
table: csvw.Table,
|
| 217 |
+
drop_self_referential_fks: typing.Optional[bool] = True) -> 'TableSpec':
|
| 218 |
+
"""
|
| 219 |
+
Create a `TableSpec` from the schema description of a `csvw.metadata.Table`.
|
| 220 |
+
|
| 221 |
+
:param table: `csvw.metadata.Table` instance.
|
| 222 |
+
:param drop_self_referential_fks: Flag signaling whether to drop self-referential foreign \
|
| 223 |
+
keys. This may be necessary, if the order of rows in a CSVW table does not guarantee \
|
| 224 |
+
referential integrity when inserted in order (e.g. an eralier row refering to a later one).
|
| 225 |
+
:return: `TableSpec` instance.
|
| 226 |
+
"""
|
| 227 |
+
spec = cls(name=table.local_name, primary_key=table.tableSchema.primaryKey)
|
| 228 |
+
list_valued = {c.header for c in table.tableSchema.columns if c.separator}
|
| 229 |
+
for fk in table.tableSchema.foreignKeys:
|
| 230 |
+
# We only support Foreign Key references between tables!
|
| 231 |
+
if not fk.reference.schemaReference:
|
| 232 |
+
if len(fk.columnReference) == 1 and fk.columnReference[0] in list_valued:
|
| 233 |
+
# List-valued foreign keys are turned into a many-to-many relation!
|
| 234 |
+
assert len(fk.reference.columnReference) == 1, \
|
| 235 |
+
'Composite key {0} in table {1} referenced'.format(
|
| 236 |
+
fk.reference.columnReference,
|
| 237 |
+
fk.reference.resource)
|
| 238 |
+
assert spec.primary_key and len(spec.primary_key) == 1, \
|
| 239 |
+
'Table {0} referenced by list-valued foreign key must have non-composite ' \
|
| 240 |
+
'primary key'.format(spec.name)
|
| 241 |
+
spec.many_to_many[fk.columnReference[0]] = TableSpec.association_table(
|
| 242 |
+
spec.name,
|
| 243 |
+
spec.primary_key[0],
|
| 244 |
+
fk.reference.resource.string,
|
| 245 |
+
fk.reference.columnReference[0],
|
| 246 |
+
)
|
| 247 |
+
elif not (drop_self_referential_fks and fk.reference.resource.string == spec.name):
|
| 248 |
+
spec.foreign_keys.append((
|
| 249 |
+
sorted(fk.columnReference),
|
| 250 |
+
fk.reference.resource.string,
|
| 251 |
+
sorted(fk.reference.columnReference),
|
| 252 |
+
))
|
| 253 |
+
for c in table.tableSchema.columns:
|
| 254 |
+
if c.header not in spec.many_to_many:
|
| 255 |
+
datatype = c.inherit('datatype')
|
| 256 |
+
spec.columns.append(ColSpec(
|
| 257 |
+
name=c.header,
|
| 258 |
+
csvw_type=datatype.base if datatype else datatype,
|
| 259 |
+
separator=c.inherit('separator'),
|
| 260 |
+
required=c.inherit('required'),
|
| 261 |
+
csvw=c.inherit('datatype'),
|
| 262 |
+
))
|
| 263 |
+
return spec
|
| 264 |
+
|
| 265 |
+
@classmethod
|
| 266 |
+
def association_table(cls, atable, apk, btable, bpk) -> 'TableSpec':
|
| 267 |
+
"""
|
| 268 |
+
List-valued foreignKeys are supported as follows: For each pair of tables related through a
|
| 269 |
+
list-valued foreign key, an association table is created. To make it possible to distinguish
|
| 270 |
+
multiple list-valued foreign keys between the same two tables, the association table has
|
| 271 |
+
a column `context`, which stores the name of the foreign key column from which a row in the
|
| 272 |
+
assocation table was created.
|
| 273 |
+
"""
|
| 274 |
+
afk = ColSpec('{0}_{1}'.format(atable, apk))
|
| 275 |
+
bfk = ColSpec('{0}_{1}'.format(btable, bpk))
|
| 276 |
+
if afk.name == bfk.name:
|
| 277 |
+
afk.name += '_1'
|
| 278 |
+
bfk.name += '_2'
|
| 279 |
+
return cls(
|
| 280 |
+
name='{0}_{1}'.format(atable, btable),
|
| 281 |
+
columns=[afk, bfk, ColSpec('context')],
|
| 282 |
+
foreign_keys=[
|
| 283 |
+
([afk.name], atable, [apk]),
|
| 284 |
+
([bfk.name], btable, [bpk]),
|
| 285 |
+
]
|
| 286 |
+
)
|
| 287 |
+
|
| 288 |
+
def sql(self, translate: SchemaTranslator) -> str:
|
| 289 |
+
"""
|
| 290 |
+
:param translate:
|
| 291 |
+
:return: The SQL statement to create the table.
|
| 292 |
+
"""
|
| 293 |
+
col_translate = functools.partial(translate, self.name)
|
| 294 |
+
clauses = [col.sql(col_translate) for col in self.columns]
|
| 295 |
+
if self.primary_key:
|
| 296 |
+
clauses.append('PRIMARY KEY({0})'.format(quoted(
|
| 297 |
+
*[col_translate(c) for c in self.primary_key])))
|
| 298 |
+
for fk, ref, refcols in self.foreign_keys:
|
| 299 |
+
clauses.append('FOREIGN KEY({0}) REFERENCES {1}({2}) ON DELETE CASCADE'.format(
|
| 300 |
+
quoted(*[col_translate(c) for c in fk]),
|
| 301 |
+
quoted(translate(ref)),
|
| 302 |
+
quoted(*[translate(ref, c) for c in refcols])))
|
| 303 |
+
return "CREATE TABLE IF NOT EXISTS `{0}` (\n {1}\n)".format(
|
| 304 |
+
translate(self.name), ',\n '.join(clauses))
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
def schema(tg: csvw.TableGroup,
|
| 308 |
+
drop_self_referential_fks: typing.Optional[bool] = True) -> typing.List[TableSpec]:
|
| 309 |
+
"""
|
| 310 |
+
Convert the table and column descriptions of a `TableGroup` into specifications for the
|
| 311 |
+
DB schema.
|
| 312 |
+
|
| 313 |
+
:param tg: CSVW TableGroup.
|
| 314 |
+
:param drop_self_referential_fks: Flag signaling whether to drop self-referential foreign \
|
| 315 |
+
keys. This may be necessary, if the order of rows in a CSVW table does not guarantee \
|
| 316 |
+
referential integrity when inserted in order (e.g. an eralier row refering to a later one).
|
| 317 |
+
:return: A pair (tables, reference_tables).
|
| 318 |
+
"""
|
| 319 |
+
tables = {}
|
| 320 |
+
for tname, table in tg.tabledict.items():
|
| 321 |
+
t = TableSpec.from_table_metadata(
|
| 322 |
+
table, drop_self_referential_fks=drop_self_referential_fks)
|
| 323 |
+
tables[t.name] = t
|
| 324 |
+
for at in t.many_to_many.values():
|
| 325 |
+
tables[at.name] = at
|
| 326 |
+
|
| 327 |
+
# We must determine the order in which tables must be created!
|
| 328 |
+
ordered = collections.OrderedDict()
|
| 329 |
+
i = 0
|
| 330 |
+
|
| 331 |
+
# We loop through the tables repeatedly, and whenever we find one, which has all
|
| 332 |
+
# referenced tables already in ordered, we move it from tables to ordered.
|
| 333 |
+
while tables and i < 100:
|
| 334 |
+
i += 1
|
| 335 |
+
for table in list(tables.keys()):
|
| 336 |
+
if all((ref[1] in ordered) or ref[1] == table for ref in tables[table].foreign_keys):
|
| 337 |
+
# All referenced tables are already created (or self-referential).
|
| 338 |
+
ordered[table] = tables.pop(table)
|
| 339 |
+
break
|
| 340 |
+
if tables: # pragma: no cover
|
| 341 |
+
raise ValueError('there seem to be cyclic dependencies between the tables')
|
| 342 |
+
|
| 343 |
+
return list(ordered.values())
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
class Database(object):
|
| 347 |
+
"""
|
| 348 |
+
Represents a SQLite database associated with a :class:`csvw.TableGroup` instance.
|
| 349 |
+
|
| 350 |
+
:param tg: `TableGroup` instance defining the schema of the database.
|
| 351 |
+
:param fname: Path to which to write the database file.
|
| 352 |
+
:param translate: Schema object name translator.
|
| 353 |
+
:param drop_self_referential_fks: Flag signaling whether to drop or enforce self-referential \
|
| 354 |
+
foreign-key constraints.
|
| 355 |
+
|
| 356 |
+
.. warning::
|
| 357 |
+
|
| 358 |
+
We write rows of a table to the database sequentially. Since CSVW does not require ordering
|
| 359 |
+
rows in tables such that self-referential foreign-key constraints are satisfied at each row,
|
| 360 |
+
we don't enforce self-referential foreign-keys by default in order to not trigger "false"
|
| 361 |
+
integrity errors. If data in a CSVW Table is known to be ordered appropriately, `False`
|
| 362 |
+
should be passed as `drop_self_referential_fks` keyword parameter to enforce
|
| 363 |
+
self-referential foreign-keys.
|
| 364 |
+
"""
|
| 365 |
+
def __init__(
|
| 366 |
+
self,
|
| 367 |
+
tg: TableGroup,
|
| 368 |
+
fname: typing.Optional[typing.Union[pathlib.Path, str]] = None,
|
| 369 |
+
translate: typing.Optional[SchemaTranslator] = None,
|
| 370 |
+
drop_self_referential_fks: typing.Optional[bool] = True,
|
| 371 |
+
):
|
| 372 |
+
self.translate = translate or Database.name_translator
|
| 373 |
+
self.fname = pathlib.Path(fname) if fname else None
|
| 374 |
+
self.init_schema(tg, drop_self_referential_fks=drop_self_referential_fks)
|
| 375 |
+
self._connection = None # For in-memory dbs we need to keep the connection!
|
| 376 |
+
|
| 377 |
+
def init_schema(self, tg, drop_self_referential_fks=True):
|
| 378 |
+
self.tg = tg
|
| 379 |
+
self.tables = schema(
|
| 380 |
+
self.tg, drop_self_referential_fks=drop_self_referential_fks) if self.tg else []
|
| 381 |
+
|
| 382 |
+
@property
|
| 383 |
+
def tdict(self) -> typing.Dict[str, TableSpec]:
|
| 384 |
+
return {t.name: t for t in self.tables}
|
| 385 |
+
|
| 386 |
+
@staticmethod
|
| 387 |
+
def name_translator(table: str, column: typing.Optional[str] = None) -> str:
|
| 388 |
+
"""
|
| 389 |
+
A callable with this signature can be passed into DB creation to control the names
|
| 390 |
+
of the schema objects.
|
| 391 |
+
|
| 392 |
+
:param table: CSVW name of the table before translation
|
| 393 |
+
:param column: CSVW name of a column of `table` before translation
|
| 394 |
+
:return: Translated table name if `column is None` else translated column name
|
| 395 |
+
"""
|
| 396 |
+
# By default, no translation is done:
|
| 397 |
+
return column or table
|
| 398 |
+
|
| 399 |
+
def connection(self) -> typing.Union[sqlite3.Connection, contextlib.closing]:
|
| 400 |
+
if self.fname:
|
| 401 |
+
return contextlib.closing(sqlite3.connect(str(self.fname)))
|
| 402 |
+
if not self._connection:
|
| 403 |
+
self._connection = sqlite3.connect(':memory:')
|
| 404 |
+
return self._connection
|
| 405 |
+
|
| 406 |
+
def select_many_to_many(self, db, table, context) -> dict:
|
| 407 |
+
if context is not None:
|
| 408 |
+
context_sql = "WHERE context = '{0}'".format(context)
|
| 409 |
+
else:
|
| 410 |
+
context_sql = ''
|
| 411 |
+
sql = """\
|
| 412 |
+
SELECT {0}, group_concat({1}, ' '), group_concat(COALESCE(context, ''), '||')
|
| 413 |
+
FROM {2} {3} GROUP BY {0}""".format(
|
| 414 |
+
quoted(self.translate(table.name, table.columns[0].name)),
|
| 415 |
+
quoted(self.translate(table.name, table.columns[1].name)),
|
| 416 |
+
quoted(self.translate(table.name)),
|
| 417 |
+
context_sql)
|
| 418 |
+
cu = db.execute(sql)
|
| 419 |
+
return {
|
| 420 |
+
r[0]: [(k, v) if context is None else k
|
| 421 |
+
for k, v in zip(r[1].split(), r[2].split('||'))] for r in cu.fetchall()}
|
| 422 |
+
|
| 423 |
+
def separator(self, tname: str, cname: str) -> typing.Optional[str]:
|
| 424 |
+
"""
|
| 425 |
+
:return: separator for the column specified by db schema names `tname` and `cname`.
|
| 426 |
+
"""
|
| 427 |
+
for name in self.tdict:
|
| 428 |
+
if self.translate(name) == tname:
|
| 429 |
+
for col in self.tdict[name].columns:
|
| 430 |
+
if self.translate(name, col.name) == cname:
|
| 431 |
+
return col.separator
|
| 432 |
+
|
| 433 |
+
def split_value(self, tname, cname, value) -> typing.Union[typing.List[str], str, None]:
|
| 434 |
+
sep = self.separator(tname, cname)
|
| 435 |
+
return (value or '').split(sep) if sep else value
|
| 436 |
+
|
| 437 |
+
def read(self) -> typing.Dict[str, typing.List[typing.OrderedDict]]:
|
| 438 |
+
"""
|
| 439 |
+
:return: A `dict` where keys are SQL table names corresponding to CSVW tables and values \
|
| 440 |
+
are lists of rows, represented as dicts where keys are the SQL column names.
|
| 441 |
+
"""
|
| 442 |
+
res = collections.defaultdict(list)
|
| 443 |
+
with self.connection() as conn:
|
| 444 |
+
for tname in self.tg.tabledict:
|
| 445 |
+
#
|
| 446 |
+
# FIXME: how much do we want to use DB types? Probably as much as possible!
|
| 447 |
+
# Thus we need to convert on write **and** read!
|
| 448 |
+
#
|
| 449 |
+
convert, seps, refs = {}, {}, collections.defaultdict(dict)
|
| 450 |
+
table = self.tdict[tname] # The TableSpec object.
|
| 451 |
+
|
| 452 |
+
# Assemble the conversion dictionary:
|
| 453 |
+
for col in table.columns:
|
| 454 |
+
convert[self.translate(tname, col.name)] = [col.name, identity]
|
| 455 |
+
if col.csvw_type in TYPE_MAP:
|
| 456 |
+
convert[self.translate(tname, col.name)][1] = TYPE_MAP[col.csvw_type][2]
|
| 457 |
+
else:
|
| 458 |
+
convert[self.translate(tname, col.name)][1] = \
|
| 459 |
+
DATATYPES[col.csvw_type].to_python
|
| 460 |
+
if col.separator:
|
| 461 |
+
if col.csvw_type == 'string':
|
| 462 |
+
seps[self.translate(tname, col.name)] = col.separator
|
| 463 |
+
else:
|
| 464 |
+
seps[self.translate(tname, col.name)] = 'json'
|
| 465 |
+
|
| 466 |
+
# Retrieve the many-to-many relations:
|
| 467 |
+
for col, at in table.many_to_many.items():
|
| 468 |
+
for pk, v in self.select_many_to_many(conn, at, col).items():
|
| 469 |
+
refs[pk][self.translate(tname, col)] = v
|
| 470 |
+
|
| 471 |
+
cols, rows = select(conn, self.translate(tname))
|
| 472 |
+
for row in rows:
|
| 473 |
+
d = collections.OrderedDict()
|
| 474 |
+
for k, v in zip(cols, row):
|
| 475 |
+
if k in seps:
|
| 476 |
+
if v is None:
|
| 477 |
+
d[k] = None
|
| 478 |
+
elif not v:
|
| 479 |
+
d[k] = []
|
| 480 |
+
elif seps[k] == 'json':
|
| 481 |
+
d[k] = json.loads(v)
|
| 482 |
+
else:
|
| 483 |
+
d[k] = [convert[k][1](v_) for v_ in (v or '').split(seps[k])]
|
| 484 |
+
else:
|
| 485 |
+
d[k] = convert[k][1](v) if v is not None else None
|
| 486 |
+
pk = d[self.translate(tname, table.primary_key[0])] \
|
| 487 |
+
if table.primary_key and len(table.primary_key) == 1 else None
|
| 488 |
+
d.update({k: [] for k in table.many_to_many})
|
| 489 |
+
d.update(refs.get(pk, {}))
|
| 490 |
+
res[self.translate(tname)].append(d)
|
| 491 |
+
return res
|
| 492 |
+
|
| 493 |
+
def association_table_context(self, table, column, fkey):
|
| 494 |
+
"""
|
| 495 |
+
Context for association tables is created calling this method.
|
| 496 |
+
|
| 497 |
+
Note: If a custom value for the `context` column is created by overwriting this method,
|
| 498 |
+
`select_many_to_many` must be adapted accordingly, to make sure the custom
|
| 499 |
+
context is retrieved when reading the data from the db.
|
| 500 |
+
|
| 501 |
+
:param table:
|
| 502 |
+
:param column:
|
| 503 |
+
:param fkey:
|
| 504 |
+
:return: a pair (foreign key, context)
|
| 505 |
+
"""
|
| 506 |
+
# The default implementation takes the column name as context:
|
| 507 |
+
return fkey, column
|
| 508 |
+
|
| 509 |
+
def write_from_tg(self, _force=False, _exists_ok=False, _skip_extra=False):
|
| 510 |
+
return self.write(
|
| 511 |
+
force=_force,
|
| 512 |
+
_exists_ok=_exists_ok,
|
| 513 |
+
_skip_extra=_skip_extra,
|
| 514 |
+
**self.tg.read())
|
| 515 |
+
|
| 516 |
+
def write(self, *, force=False, _exists_ok=False, _skip_extra=False, **items):
|
| 517 |
+
"""
|
| 518 |
+
Creates a db file with the core schema.
|
| 519 |
+
|
| 520 |
+
:param force: If `True` an existing db file will be overwritten.
|
| 521 |
+
"""
|
| 522 |
+
if self.fname and self.fname.exists():
|
| 523 |
+
if not force:
|
| 524 |
+
raise ValueError('db file already exists, use force=True to overwrite')
|
| 525 |
+
else:
|
| 526 |
+
self.fname.unlink()
|
| 527 |
+
|
| 528 |
+
with self.connection() as db:
|
| 529 |
+
for table in self.tables:
|
| 530 |
+
db.execute(table.sql(translate=self.translate))
|
| 531 |
+
|
| 532 |
+
db.execute('PRAGMA foreign_keys = ON;')
|
| 533 |
+
db.commit()
|
| 534 |
+
|
| 535 |
+
refs = collections.defaultdict(list) # collects rows in association tables.
|
| 536 |
+
for t in self.tables:
|
| 537 |
+
if t.name not in items:
|
| 538 |
+
continue
|
| 539 |
+
rows, keys = [], []
|
| 540 |
+
cols = {c.name: c for c in t.columns}
|
| 541 |
+
for i, row in enumerate(items[t.name]):
|
| 542 |
+
pk = row[t.primary_key[0]] \
|
| 543 |
+
if t.primary_key and len(t.primary_key) == 1 else None
|
| 544 |
+
values = []
|
| 545 |
+
for k, v in row.items():
|
| 546 |
+
if k in t.many_to_many:
|
| 547 |
+
assert pk
|
| 548 |
+
at = t.many_to_many[k]
|
| 549 |
+
atkey = tuple([at.name] + [c.name for c in at.columns])
|
| 550 |
+
# We distinguish None - meaning NULL - and [] - meaning no items - as
|
| 551 |
+
# values of list-valued columns.
|
| 552 |
+
for vv in (v or []):
|
| 553 |
+
fkey, context = self.association_table_context(t, k, vv)
|
| 554 |
+
refs[atkey].append((pk, fkey, context))
|
| 555 |
+
else:
|
| 556 |
+
if k not in cols:
|
| 557 |
+
if _skip_extra:
|
| 558 |
+
continue
|
| 559 |
+
else:
|
| 560 |
+
raise ValueError(
|
| 561 |
+
'unspecified column {0} found in data'.format(k))
|
| 562 |
+
col = cols[k]
|
| 563 |
+
if isinstance(v, list):
|
| 564 |
+
# Note: This assumes list-valued columns are of datatype string!
|
| 565 |
+
if col.csvw_type == 'string':
|
| 566 |
+
v = (col.separator or ';').join(
|
| 567 |
+
col.convert(vv) or '' for vv in v)
|
| 568 |
+
else:
|
| 569 |
+
v = json.dumps(v)
|
| 570 |
+
else:
|
| 571 |
+
v = col.convert(v) if v is not None else None
|
| 572 |
+
if i == 0:
|
| 573 |
+
keys.append(col.name)
|
| 574 |
+
values.append(v)
|
| 575 |
+
rows.append(tuple(values))
|
| 576 |
+
insert(db, self.translate, t.name, keys, *rows)
|
| 577 |
+
|
| 578 |
+
for atkey, rows in refs.items():
|
| 579 |
+
insert(db, self.translate, atkey[0], atkey[1:], *rows)
|
| 580 |
+
|
| 581 |
+
db.commit()
|
TTS/Kokoro/.venv/Lib/site-packages/csvw/dsv.py
ADDED
|
@@ -0,0 +1,458 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Support for reading delimiter-separated value files.
|
| 2 |
+
|
| 3 |
+
This module contains unicode aware replacements for :func:`csv.reader`
|
| 4 |
+
and :func:`csv.writer`. It was stolen/extracted from the ``csvkit``
|
| 5 |
+
project to allow re-use when the whole ``csvkit`` package isn't
|
| 6 |
+
required.
|
| 7 |
+
|
| 8 |
+
The original implementations were largely copied from
|
| 9 |
+
`examples in the csv module documentation <http://docs.python.org/library/csv.html\
|
| 10 |
+
#examples>`_.
|
| 11 |
+
|
| 12 |
+
.. seealso:: http://en.wikipedia.org/wiki/Delimiter-separated_values
|
| 13 |
+
"""
|
| 14 |
+
import io
|
| 15 |
+
import csv
|
| 16 |
+
import codecs
|
| 17 |
+
import shutil
|
| 18 |
+
import typing
|
| 19 |
+
import pathlib
|
| 20 |
+
import tempfile
|
| 21 |
+
import warnings
|
| 22 |
+
import functools
|
| 23 |
+
import collections
|
| 24 |
+
|
| 25 |
+
from . import utils
|
| 26 |
+
from .dsv_dialects import Dialect
|
| 27 |
+
|
| 28 |
+
__all__ = [
|
| 29 |
+
'UnicodeWriter',
|
| 30 |
+
'UnicodeReader', 'UnicodeReaderWithLineNumber', 'UnicodeDictReader', 'NamedTupleReader',
|
| 31 |
+
'iterrows',
|
| 32 |
+
'rewrite', 'add_rows', 'filter_rows_as_dict',
|
| 33 |
+
]
|
| 34 |
+
|
| 35 |
+
LINES_OR_PATH = typing.Union[str, pathlib.Path, typing.IO, typing.Iterable[str]]
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def normalize_encoding(encoding: str) -> str:
|
| 39 |
+
return codecs.lookup(encoding).name
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class UnicodeWriter:
|
| 43 |
+
"""
|
| 44 |
+
Write Unicode data to a csv file.
|
| 45 |
+
|
| 46 |
+
:param f: The target to which to write the data; a local path specified as `str` or \
|
| 47 |
+
`pathlib.Path` or `None`, in which case the data, formatted as DSV can be retrieved \
|
| 48 |
+
via :meth:`~UnicodeWriter.read`
|
| 49 |
+
:param dialect: Either a dialect name as recognized by `csv.writer` or a \
|
| 50 |
+
:class:`~Dialect` instance for dialect customization beyond what can be done with \
|
| 51 |
+
`csv.writer`.
|
| 52 |
+
:param kw: Keyword arguments passed through to `csv.writer`.
|
| 53 |
+
|
| 54 |
+
.. code-block:: python
|
| 55 |
+
|
| 56 |
+
>>> from csvw import UnicodeWriter
|
| 57 |
+
>>> with UnicodeWriter('data.tsv', delimiter='\t') as writer:
|
| 58 |
+
... writer.writerow(['ä', 'ö', 'ü'])
|
| 59 |
+
"""
|
| 60 |
+
|
| 61 |
+
def __init__(
|
| 62 |
+
self,
|
| 63 |
+
f: typing.Optional[typing.Union[str, pathlib.Path]] = None,
|
| 64 |
+
dialect: typing.Optional[typing.Union[Dialect, str]] = None,
|
| 65 |
+
**kw):
|
| 66 |
+
self.f = f
|
| 67 |
+
self.encoding = kw.pop('encoding', 'utf-8')
|
| 68 |
+
if isinstance(dialect, Dialect):
|
| 69 |
+
self.encoding = dialect.python_encoding
|
| 70 |
+
self.kw = dialect.as_python_formatting_parameters()
|
| 71 |
+
self.kw.update(kw)
|
| 72 |
+
else:
|
| 73 |
+
self.kw = kw
|
| 74 |
+
if dialect:
|
| 75 |
+
self.kw['dialect'] = dialect
|
| 76 |
+
self.encoding = normalize_encoding(self.encoding)
|
| 77 |
+
self.escapechar = self.kw.get('escapechar')
|
| 78 |
+
if self.escapechar and self.kw.get('quoting') != csv.QUOTE_NONE:
|
| 79 |
+
# work around https://bugs.python.org/issue12178
|
| 80 |
+
# (csv.writer doesn't escape escapechar while csv.reader expects it)
|
| 81 |
+
def _escapedoubled(row,
|
| 82 |
+
_type=str,
|
| 83 |
+
_old=self.escapechar,
|
| 84 |
+
_new=2 * self.escapechar):
|
| 85 |
+
return [s.replace(_old, _new) if isinstance(s, _type) else s for s in row]
|
| 86 |
+
else:
|
| 87 |
+
def _escapedoubled(row):
|
| 88 |
+
return row
|
| 89 |
+
self._escapedoubled = _escapedoubled
|
| 90 |
+
self._close = False
|
| 91 |
+
self._rows_written = 0
|
| 92 |
+
|
| 93 |
+
def __enter__(self):
|
| 94 |
+
if isinstance(self.f, (str, pathlib.Path)):
|
| 95 |
+
if isinstance(self.f, pathlib.Path):
|
| 96 |
+
self.f = str(self.f)
|
| 97 |
+
|
| 98 |
+
self.f = io.open(self.f, 'wt', encoding=self.encoding, newline='')
|
| 99 |
+
self._close = True
|
| 100 |
+
elif self.f is None:
|
| 101 |
+
self.f = io.StringIO(newline='')
|
| 102 |
+
|
| 103 |
+
self.writer = csv.writer(self.f, **self.kw)
|
| 104 |
+
return self
|
| 105 |
+
|
| 106 |
+
def read(self) -> typing.Optional[bytes]:
|
| 107 |
+
"""
|
| 108 |
+
If the writer has been initialized passing `None` as target, the CSV data as `bytes` can be
|
| 109 |
+
retrieved calling this method.
|
| 110 |
+
"""
|
| 111 |
+
if hasattr(self.f, 'seek'):
|
| 112 |
+
self.f.seek(0)
|
| 113 |
+
if hasattr(self.f, 'read'):
|
| 114 |
+
return self.f.read().encode('utf-8')
|
| 115 |
+
|
| 116 |
+
def __exit__(self, type, value, traceback):
|
| 117 |
+
if self._close:
|
| 118 |
+
self.f.close()
|
| 119 |
+
|
| 120 |
+
def writerow(self, row: typing.Iterable[typing.Union[str, None]]):
|
| 121 |
+
self.writer.writerow(self._escapedoubled(row))
|
| 122 |
+
self._rows_written += 1
|
| 123 |
+
|
| 124 |
+
def writerows(self, rows: typing.Iterable[typing.Union[tuple, list, dict]]):
|
| 125 |
+
"""
|
| 126 |
+
Writes each row in `rows` formatted as CSV row. This behaves as
|
| 127 |
+
[`csvwriter.writerows`](https://docs.python.org/3/library/csv.html#csv.csvwriter.writerows)
|
| 128 |
+
except when an iterable of `dict` objects is passed. In that case, it is assumed that all
|
| 129 |
+
items in `rows` are `dict`s and all have the same keys in the same order (as what would
|
| 130 |
+
be read by `UnicodeDictReader`). Then, the keys of the first item are written as header row
|
| 131 |
+
and the values of each row are written as subsequent rows.
|
| 132 |
+
|
| 133 |
+
:param rows: The data to be written.
|
| 134 |
+
"""
|
| 135 |
+
for i, row in enumerate(rows):
|
| 136 |
+
if isinstance(row, dict):
|
| 137 |
+
if i == 0 and not self._rows_written:
|
| 138 |
+
# We write a header row.
|
| 139 |
+
self.writerow(row.keys())
|
| 140 |
+
row = row.values()
|
| 141 |
+
self.writerow(row)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
class UnicodeReader:
|
| 145 |
+
"""
|
| 146 |
+
Read Unicode data from a csv file.
|
| 147 |
+
|
| 148 |
+
:param f: The source from which to read the data; a local path specified as `str` or \
|
| 149 |
+
`pathlib.Path`, a file-like object or a `list` of lines.
|
| 150 |
+
:param dialect: Either a dialect name as recognized by `csv.reader` or a \
|
| 151 |
+
:class:`~Dialect` instance for dialect customization beyond what can be done with \
|
| 152 |
+
`csv.writer`.
|
| 153 |
+
:param kw: Keyword arguments passed through to `csv.reader`.
|
| 154 |
+
|
| 155 |
+
.. code-block:: python
|
| 156 |
+
|
| 157 |
+
>>> with UnicodeReader('tests/fixtures/frictionless-data.csv', delimiter='|') as reader:
|
| 158 |
+
... for row in reader:
|
| 159 |
+
... print(row)
|
| 160 |
+
... break
|
| 161 |
+
...
|
| 162 |
+
['FK', 'Year', 'Location name', 'Value', 'binary', 'anyURI', 'email', 'boolean', 'array',
|
| 163 |
+
'geojson']
|
| 164 |
+
"""
|
| 165 |
+
def __init__(
|
| 166 |
+
self,
|
| 167 |
+
f: LINES_OR_PATH,
|
| 168 |
+
dialect: typing.Optional[typing.Union[Dialect, str]] = None,
|
| 169 |
+
**kw):
|
| 170 |
+
self.f = f
|
| 171 |
+
self.encoding = normalize_encoding(kw.pop('encoding', 'utf-8-sig'))
|
| 172 |
+
self.newline = kw.pop('lineterminator', None)
|
| 173 |
+
self.dialect = dialect if isinstance(dialect, Dialect) else None
|
| 174 |
+
if self.dialect:
|
| 175 |
+
self.encoding = self.dialect.python_encoding
|
| 176 |
+
self.kw = dialect.as_python_formatting_parameters()
|
| 177 |
+
self.kw.update(kw)
|
| 178 |
+
else:
|
| 179 |
+
self.kw = kw
|
| 180 |
+
if dialect:
|
| 181 |
+
self.kw['dialect'] = dialect
|
| 182 |
+
self._close = False
|
| 183 |
+
self.comments = []
|
| 184 |
+
|
| 185 |
+
# We potentially screw people with valid CSV files where the content - presumably the
|
| 186 |
+
# header - starts with 0xfeff. But the chance of irritating people trying to read Excel
|
| 187 |
+
# exported CSV with the defaults seems way bigger - and anyone with CSV column names
|
| 188 |
+
# starting with 0xfeff will run into more trouble down the line anyway ...
|
| 189 |
+
if self.encoding == 'utf-8':
|
| 190 |
+
self.encoding = 'utf-8-sig'
|
| 191 |
+
|
| 192 |
+
# encoding of self.reader rows: differs from source encoding
|
| 193 |
+
# where we need to recode from non-8bit clean source encoding
|
| 194 |
+
# to utf-8 first to feed into the (byte-based) PY2 csv.reader
|
| 195 |
+
self._reader_encoding = self.encoding
|
| 196 |
+
|
| 197 |
+
def __enter__(self):
|
| 198 |
+
if isinstance(self.f, (str, pathlib.Path)):
|
| 199 |
+
if isinstance(self.f, pathlib.Path):
|
| 200 |
+
self.f = str(self.f)
|
| 201 |
+
|
| 202 |
+
self.f = io.open(self.f, mode='rt', encoding=self.encoding, newline=self.newline or '')
|
| 203 |
+
self._close = True
|
| 204 |
+
elif not hasattr(self.f, 'read'):
|
| 205 |
+
lines = []
|
| 206 |
+
for line in self.f:
|
| 207 |
+
lines.append(line.decode(self.encoding) if isinstance(line, bytes) else line)
|
| 208 |
+
self.f = lines
|
| 209 |
+
self.reader = csv.reader(self.f, **self.kw)
|
| 210 |
+
self.lineno = -1
|
| 211 |
+
return self
|
| 212 |
+
|
| 213 |
+
def _next_row(self):
|
| 214 |
+
self.lineno += 1
|
| 215 |
+
row = [
|
| 216 |
+
s if isinstance(s, str) else s.decode(self._reader_encoding)
|
| 217 |
+
for s in next(self.reader)]
|
| 218 |
+
self.lineno += sum([list(s).count('\n') for s in row])
|
| 219 |
+
return row
|
| 220 |
+
|
| 221 |
+
def __next__(self):
|
| 222 |
+
row = self._next_row()
|
| 223 |
+
if self.dialect:
|
| 224 |
+
while (row and self.dialect.commentPrefix and # noqa: W504
|
| 225 |
+
row[0].startswith(self.dialect.commentPrefix)) or \
|
| 226 |
+
((not row or set(row) == {''}) and self.dialect.skipBlankRows) or \
|
| 227 |
+
(self.lineno < self.dialect.skipRows):
|
| 228 |
+
if (row and self.dialect.commentPrefix and # noqa: W504
|
| 229 |
+
row[0].startswith(self.dialect.commentPrefix)) or \
|
| 230 |
+
(row and self.lineno < self.dialect.skipRows):
|
| 231 |
+
self.comments.append((
|
| 232 |
+
self.lineno,
|
| 233 |
+
self.dialect.delimiter.join(row).lstrip(self.dialect.commentPrefix).strip(),
|
| 234 |
+
))
|
| 235 |
+
row = self._next_row()
|
| 236 |
+
row = [self.dialect.trimmer(s) for s in row][self.dialect.skipColumns:]
|
| 237 |
+
return row
|
| 238 |
+
|
| 239 |
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
| 240 |
+
if self._close:
|
| 241 |
+
self.f.close()
|
| 242 |
+
|
| 243 |
+
def __iter__(self):
|
| 244 |
+
return self
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
class UnicodeReaderWithLineNumber(UnicodeReader):
|
| 248 |
+
"""
|
| 249 |
+
A `UnicodeReader` yielding (lineno, row) pairs, where "lineno" is the 1-based number of the
|
| 250 |
+
the **text line** where the (possibly multi-line) row data starts in the DSV file.
|
| 251 |
+
"""
|
| 252 |
+
def __next__(self):
|
| 253 |
+
"""
|
| 254 |
+
:return: a pair (1-based line number in the input, row)
|
| 255 |
+
"""
|
| 256 |
+
# Retrieve the row, thereby incrementing the line number:
|
| 257 |
+
row = super(UnicodeReaderWithLineNumber, self).__next__()
|
| 258 |
+
return self.lineno + 1, row
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
class UnicodeDictReader(UnicodeReader):
|
| 262 |
+
"""
|
| 263 |
+
A `UnicodeReader` yielding one `dict` per row.
|
| 264 |
+
|
| 265 |
+
:param f: As for :class:`UnicodeReader`
|
| 266 |
+
:param fieldnames:
|
| 267 |
+
|
| 268 |
+
.. code-block:: python
|
| 269 |
+
|
| 270 |
+
>>> with UnicodeDictReader(
|
| 271 |
+
... 'tests/fixtures/frictionless-data.csv',
|
| 272 |
+
... dialect=Dialect(delimiter='|', header=False),
|
| 273 |
+
... fieldnames=[str(i) for i in range(1, 11)]) as reader:
|
| 274 |
+
... for row in reader:
|
| 275 |
+
... print(row)
|
| 276 |
+
... break
|
| 277 |
+
...
|
| 278 |
+
OrderedDict([('1', 'FK'), ('2', 'Year'), ('3', 'Location name'), ('4', 'Value'),
|
| 279 |
+
('5', 'binary'), ('6', 'anyURI'), ('7', 'email'), ('8', 'boolean'), ('9', 'array'),
|
| 280 |
+
('10', 'geojson')])
|
| 281 |
+
|
| 282 |
+
"""
|
| 283 |
+
|
| 284 |
+
def __init__(self, f, fieldnames=None, restkey=None, restval=None, **kw):
|
| 285 |
+
self._fieldnames = fieldnames # list of keys for the dict
|
| 286 |
+
self.restkey = restkey # key to catch long rows
|
| 287 |
+
self.restval = restval # default value for short rows
|
| 288 |
+
self.line_num = 0
|
| 289 |
+
super(UnicodeDictReader, self).__init__(f, **kw)
|
| 290 |
+
|
| 291 |
+
@property
|
| 292 |
+
def fieldnames(self):
|
| 293 |
+
if self._fieldnames is None:
|
| 294 |
+
try:
|
| 295 |
+
self._fieldnames = super(UnicodeDictReader, self).__next__()
|
| 296 |
+
except StopIteration:
|
| 297 |
+
pass
|
| 298 |
+
self.line_num = self.reader.line_num
|
| 299 |
+
if self._fieldnames:
|
| 300 |
+
if len(set(self._fieldnames)) != len(self._fieldnames):
|
| 301 |
+
warnings.warn('Duplicate column names!')
|
| 302 |
+
return self._fieldnames
|
| 303 |
+
|
| 304 |
+
def __next__(self) -> collections.OrderedDict:
|
| 305 |
+
if self.line_num == 0:
|
| 306 |
+
# Used only for its side effect.
|
| 307 |
+
self.fieldnames
|
| 308 |
+
row = super(UnicodeDictReader, self).__next__()
|
| 309 |
+
self.line_num = self.reader.line_num
|
| 310 |
+
|
| 311 |
+
# unlike the basic reader, we prefer not to return blanks,
|
| 312 |
+
# because we will typically wind up with a dict full of None
|
| 313 |
+
# values
|
| 314 |
+
while row == []:
|
| 315 |
+
row = super(UnicodeDictReader, self).__next__()
|
| 316 |
+
return self.item(row)
|
| 317 |
+
|
| 318 |
+
def item(self, row) -> collections.OrderedDict:
|
| 319 |
+
d = collections.OrderedDict((k, v) for k, v in zip(self.fieldnames, row))
|
| 320 |
+
lf = len(self.fieldnames)
|
| 321 |
+
lr = len(row)
|
| 322 |
+
if lf < lr:
|
| 323 |
+
d[self.restkey] = row[lf:]
|
| 324 |
+
elif lf > lr:
|
| 325 |
+
for key in self.fieldnames[lr:]:
|
| 326 |
+
d[key] = self.restval
|
| 327 |
+
return d
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
class NamedTupleReader(UnicodeDictReader):
|
| 331 |
+
"""
|
| 332 |
+
A `UnicodeReader` yielding one `namedtuple` per row.
|
| 333 |
+
|
| 334 |
+
.. note::
|
| 335 |
+
|
| 336 |
+
This reader has some limitations, notably that fieldnames must be normalized to be
|
| 337 |
+
admissible Python names, but also bad performance (compared with `UnicodeDictReader`).
|
| 338 |
+
"""
|
| 339 |
+
|
| 340 |
+
_normalize_fieldname = staticmethod(utils.normalize_name)
|
| 341 |
+
|
| 342 |
+
@functools.cached_property
|
| 343 |
+
def cls(self):
|
| 344 |
+
fieldnames = list(map(self._normalize_fieldname, self.fieldnames))
|
| 345 |
+
return collections.namedtuple('Row', fieldnames)
|
| 346 |
+
|
| 347 |
+
def item(self, row):
|
| 348 |
+
d = UnicodeDictReader.item(self, row)
|
| 349 |
+
for name in self.fieldnames:
|
| 350 |
+
d.setdefault(name, None)
|
| 351 |
+
return self.cls(
|
| 352 |
+
**{self._normalize_fieldname(k): v for k, v in d.items() if k in self.fieldnames})
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
def iterrows(lines_or_file: LINES_OR_PATH,
|
| 356 |
+
namedtuples: typing.Optional[bool] = False,
|
| 357 |
+
dicts: typing.Optional[bool] = False,
|
| 358 |
+
encoding: typing.Optional[str] = 'utf-8',
|
| 359 |
+
**kw) -> typing.Generator:
|
| 360 |
+
"""Convenience factory function for csv reader.
|
| 361 |
+
|
| 362 |
+
:param lines_or_file: Content to be read. Either a file handle, a file path or a list\
|
| 363 |
+
of strings.
|
| 364 |
+
:param namedtuples: Yield namedtuples.
|
| 365 |
+
:param dicts: Yield dicts.
|
| 366 |
+
:param encoding: Encoding of the content.
|
| 367 |
+
:param kw: Keyword parameters are passed through to csv.reader.
|
| 368 |
+
:return: A generator over the rows.
|
| 369 |
+
"""
|
| 370 |
+
if namedtuples and dicts:
|
| 371 |
+
raise ValueError('either namedtuples or dicts can be chosen as output format')
|
| 372 |
+
elif namedtuples:
|
| 373 |
+
_reader = NamedTupleReader
|
| 374 |
+
elif dicts:
|
| 375 |
+
_reader = UnicodeDictReader
|
| 376 |
+
else:
|
| 377 |
+
_reader = UnicodeReader
|
| 378 |
+
|
| 379 |
+
with _reader(lines_or_file, encoding=encoding, **kw) as r:
|
| 380 |
+
for item in r:
|
| 381 |
+
yield item
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
reader = iterrows
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
def rewrite(fname: typing.Union[str, pathlib.Path],
|
| 388 |
+
visitor: typing.Callable[[int, typing.List[str]], typing.Union[None, typing.List[str]]],
|
| 389 |
+
**kw):
|
| 390 |
+
"""Utility function to rewrite rows in dsv files.
|
| 391 |
+
|
| 392 |
+
:param fname: Path of the dsv file to operate on.
|
| 393 |
+
:param visitor: A callable that takes a line-number and a row as input and returns a \
|
| 394 |
+
(modified) row or None to filter out the row.
|
| 395 |
+
:param kw: Keyword parameters are passed through to csv.reader/csv.writer.
|
| 396 |
+
"""
|
| 397 |
+
fname = utils.ensure_path(fname)
|
| 398 |
+
assert fname.is_file()
|
| 399 |
+
with tempfile.NamedTemporaryFile(delete=False) as fp:
|
| 400 |
+
tmp = pathlib.Path(fp.name)
|
| 401 |
+
|
| 402 |
+
with UnicodeReader(fname, **kw) as reader_:
|
| 403 |
+
with UnicodeWriter(tmp, **kw) as writer:
|
| 404 |
+
for i, row in enumerate(reader_):
|
| 405 |
+
row = visitor(i, row)
|
| 406 |
+
if row is not None:
|
| 407 |
+
writer.writerow(row)
|
| 408 |
+
shutil.move(str(tmp), str(fname)) # Path.replace is Python 3.3+
|
| 409 |
+
|
| 410 |
+
|
| 411 |
+
def add_rows(fname: typing.Union[str, pathlib.Path], *rows: typing.List[str]):
|
| 412 |
+
with tempfile.NamedTemporaryFile(delete=False) as fp:
|
| 413 |
+
tmp = pathlib.Path(fp.name)
|
| 414 |
+
|
| 415 |
+
fname = utils.ensure_path(fname)
|
| 416 |
+
with UnicodeWriter(tmp) as writer:
|
| 417 |
+
if fname.exists():
|
| 418 |
+
with UnicodeReader(fname) as reader_:
|
| 419 |
+
for row in reader_:
|
| 420 |
+
writer.writerow(row)
|
| 421 |
+
writer.writerows(rows)
|
| 422 |
+
shutil.move(str(tmp), str(fname)) # Path.replace is Python 3.3+
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
def filter_rows_as_dict(fname: typing.Union[str, pathlib.Path],
|
| 426 |
+
filter_: typing.Callable[[dict], bool],
|
| 427 |
+
**kw) -> int:
|
| 428 |
+
"""Rewrite a dsv file, filtering the rows.
|
| 429 |
+
|
| 430 |
+
:param fname: Path to dsv file
|
| 431 |
+
:param filter_: callable which accepts a `dict` with a row's data as single argument\
|
| 432 |
+
returning a `Boolean` indicating whether to keep the row (`True`) or to discard it \
|
| 433 |
+
`False`.
|
| 434 |
+
:param kw: Keyword arguments to be passed `UnicodeReader` and `UnicodeWriter`.
|
| 435 |
+
:return: The number of rows that have been removed.
|
| 436 |
+
"""
|
| 437 |
+
filter_ = DictFilter(filter_)
|
| 438 |
+
rewrite(fname, filter_, **kw)
|
| 439 |
+
return filter_.removed
|
| 440 |
+
|
| 441 |
+
|
| 442 |
+
class DictFilter(object):
|
| 443 |
+
|
| 444 |
+
def __init__(self, filter_):
|
| 445 |
+
self.header = None
|
| 446 |
+
self.filter = filter_
|
| 447 |
+
self.removed = 0
|
| 448 |
+
|
| 449 |
+
def __call__(self, i, row):
|
| 450 |
+
if i == 0:
|
| 451 |
+
self.header = row
|
| 452 |
+
return row
|
| 453 |
+
if row:
|
| 454 |
+
item = dict(zip(self.header, row))
|
| 455 |
+
if self.filter(item):
|
| 456 |
+
return row
|
| 457 |
+
else:
|
| 458 |
+
self.removed += 1
|
TTS/Kokoro/.venv/Lib/site-packages/csvw/dsv_dialects.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
DSV data can be surprisingly diverse. While Python's `csv` module offers out-of-the-box support
|
| 3 |
+
for the basic formatting parameters, CSVW recognizes a couple more, like `skipColumns` or
|
| 4 |
+
`skipRows`.
|
| 5 |
+
|
| 6 |
+
.. seealso::
|
| 7 |
+
|
| 8 |
+
- `<https://www.w3.org/TR/2015/REC-tabular-metadata-20151217/#dialect-descriptions>`_
|
| 9 |
+
- `<https://docs.python.org/3/library/csv.html#dialects-and-formatting-parameters>`_
|
| 10 |
+
- `<https://specs.frictionlessdata.io/csv-dialect/>`_
|
| 11 |
+
"""
|
| 12 |
+
import attr
|
| 13 |
+
import warnings
|
| 14 |
+
import functools
|
| 15 |
+
|
| 16 |
+
from . import utils
|
| 17 |
+
|
| 18 |
+
__all__ = ['Dialect']
|
| 19 |
+
|
| 20 |
+
ENCODING_MAP = {
|
| 21 |
+
'UTF-8-BOM': 'utf-8-sig', # Recognize the name of this encoding in R.
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# FIXME: replace with attrs.validators.ge(0) from attrs 21.3.0
|
| 26 |
+
def _non_negative(instance, attribute, value):
|
| 27 |
+
if value < 0: # pragma: no cover
|
| 28 |
+
raise ValueError('{0} is not a valid {1}'.format(value, attribute.name))
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
non_negative_int = [attr.validators.instance_of(int), _non_negative]
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def convert_encoding(s):
|
| 35 |
+
s = utils.converter(str, 'utf-8', s)
|
| 36 |
+
try:
|
| 37 |
+
_ = 'x'.encode(ENCODING_MAP.get(s, s))
|
| 38 |
+
return s
|
| 39 |
+
except LookupError:
|
| 40 |
+
warnings.warn('Invalid value for property: {}'.format(s))
|
| 41 |
+
return 'utf-8'
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@attr.s
|
| 45 |
+
class Dialect(object):
|
| 46 |
+
"""
|
| 47 |
+
A CSV dialect specification.
|
| 48 |
+
|
| 49 |
+
.. seealso:: `<https://www.w3.org/TR/2015/REC-tabular-metadata-20151217/#dialect-descriptions>`_
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
encoding = attr.ib(
|
| 53 |
+
default='utf-8',
|
| 54 |
+
converter=convert_encoding,
|
| 55 |
+
validator=attr.validators.instance_of(str))
|
| 56 |
+
|
| 57 |
+
lineTerminators = attr.ib(
|
| 58 |
+
converter=functools.partial(utils.converter, list, ['\r\n', '\n']),
|
| 59 |
+
default=attr.Factory(lambda: ['\r\n', '\n']))
|
| 60 |
+
|
| 61 |
+
quoteChar = attr.ib(
|
| 62 |
+
converter=functools.partial(utils.converter, str, '"', allow_none=True),
|
| 63 |
+
default='"',
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
doubleQuote = attr.ib(
|
| 67 |
+
default=True,
|
| 68 |
+
converter=functools.partial(utils.converter, bool, True),
|
| 69 |
+
validator=attr.validators.instance_of(bool))
|
| 70 |
+
|
| 71 |
+
skipRows = attr.ib(
|
| 72 |
+
default=0,
|
| 73 |
+
converter=functools.partial(utils.converter, int, 0, cond=lambda s: s >= 0),
|
| 74 |
+
validator=non_negative_int)
|
| 75 |
+
|
| 76 |
+
commentPrefix = attr.ib(
|
| 77 |
+
default='#',
|
| 78 |
+
converter=functools.partial(utils.converter, str, '#', allow_none=True),
|
| 79 |
+
validator=attr.validators.optional(attr.validators.instance_of(str)))
|
| 80 |
+
|
| 81 |
+
header = attr.ib(
|
| 82 |
+
default=True,
|
| 83 |
+
converter=functools.partial(utils.converter, bool, True),
|
| 84 |
+
validator=attr.validators.instance_of(bool))
|
| 85 |
+
|
| 86 |
+
headerRowCount = attr.ib(
|
| 87 |
+
default=1,
|
| 88 |
+
converter=functools.partial(utils.converter, int, 1, cond=lambda s: s >= 0),
|
| 89 |
+
validator=non_negative_int)
|
| 90 |
+
|
| 91 |
+
delimiter = attr.ib(
|
| 92 |
+
default=',',
|
| 93 |
+
converter=functools.partial(utils.converter, str, ','),
|
| 94 |
+
validator=attr.validators.instance_of(str))
|
| 95 |
+
|
| 96 |
+
skipColumns = attr.ib(
|
| 97 |
+
default=0,
|
| 98 |
+
converter=functools.partial(utils.converter, int, 0, cond=lambda s: s >= 0),
|
| 99 |
+
validator=non_negative_int)
|
| 100 |
+
|
| 101 |
+
skipBlankRows = attr.ib(
|
| 102 |
+
default=False,
|
| 103 |
+
converter=functools.partial(utils.converter, bool, False),
|
| 104 |
+
validator=attr.validators.instance_of(bool))
|
| 105 |
+
|
| 106 |
+
skipInitialSpace = attr.ib(
|
| 107 |
+
default=False,
|
| 108 |
+
converter=functools.partial(utils.converter, bool, False),
|
| 109 |
+
validator=attr.validators.instance_of(bool))
|
| 110 |
+
|
| 111 |
+
trim = attr.ib(
|
| 112 |
+
default='false',
|
| 113 |
+
validator=attr.validators.in_(['true', 'false', 'start', 'end']),
|
| 114 |
+
converter=lambda v: functools.partial(
|
| 115 |
+
utils.converter,
|
| 116 |
+
(str, bool), 'false')('{0}'.format(v).lower() if isinstance(v, bool) else v))
|
| 117 |
+
|
| 118 |
+
def updated(self, **kw):
|
| 119 |
+
res = self.__class__(**attr.asdict(self))
|
| 120 |
+
for k, v in kw.items():
|
| 121 |
+
setattr(res, k, v)
|
| 122 |
+
return res
|
| 123 |
+
|
| 124 |
+
@functools.cached_property
|
| 125 |
+
def escape_character(self):
|
| 126 |
+
return None if self.quoteChar is None else ('"' if self.doubleQuote else '\\')
|
| 127 |
+
|
| 128 |
+
@functools.cached_property
|
| 129 |
+
def line_terminators(self):
|
| 130 |
+
return [self.lineTerminators] \
|
| 131 |
+
if isinstance(self.lineTerminators, str) else self.lineTerminators
|
| 132 |
+
|
| 133 |
+
@functools.cached_property
|
| 134 |
+
def trimmer(self):
|
| 135 |
+
return {
|
| 136 |
+
'true': lambda s: s.strip(),
|
| 137 |
+
'false': lambda s: s,
|
| 138 |
+
'start': lambda s: s.lstrip(),
|
| 139 |
+
'end': lambda s: s.rstrip()
|
| 140 |
+
}[self.trim]
|
| 141 |
+
|
| 142 |
+
def asdict(self, omit_defaults=True):
|
| 143 |
+
return utils.attr_asdict(self, omit_defaults=omit_defaults)
|
| 144 |
+
|
| 145 |
+
@property
|
| 146 |
+
def python_encoding(self):
|
| 147 |
+
return ENCODING_MAP.get(self.encoding, self.encoding)
|
| 148 |
+
|
| 149 |
+
def as_python_formatting_parameters(self):
|
| 150 |
+
return {
|
| 151 |
+
'delimiter': self.delimiter,
|
| 152 |
+
'doublequote': self.doubleQuote,
|
| 153 |
+
# We have to hack around incompatible ways escape char is interpreted in csvw
|
| 154 |
+
# and python's csv lib:
|
| 155 |
+
'escapechar': self.escape_character if not self.doubleQuote else None,
|
| 156 |
+
'lineterminator': self.line_terminators[0],
|
| 157 |
+
'quotechar': self.quoteChar,
|
| 158 |
+
'skipinitialspace': self.skipInitialSpace,
|
| 159 |
+
'strict': True,
|
| 160 |
+
}
|
TTS/Kokoro/.venv/Lib/site-packages/csvw/frictionless.py
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Functionality to convert tabular data in Frictionless Data Packages to CSVW.
|
| 3 |
+
|
| 4 |
+
We translate [table schemas](https://specs.frictionlessdata.io/table-schema/) defined
|
| 5 |
+
for [data resources](https://specs.frictionlessdata.io/data-resource/) in a
|
| 6 |
+
[data package](https://specs.frictionlessdata.io/data-package/) to a CVSW TableGroup.
|
| 7 |
+
|
| 8 |
+
This functionality can be used together with the `frictionless describe` command to add
|
| 9 |
+
CSVW metadata to "raw" CSV tables.
|
| 10 |
+
"""
|
| 11 |
+
import json
|
| 12 |
+
import pathlib
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def convert_column_spec(spec):
|
| 16 |
+
"""
|
| 17 |
+
https://specs.frictionlessdata.io/table-schema/#field-descriptors
|
| 18 |
+
|
| 19 |
+
:param spec:
|
| 20 |
+
:return:
|
| 21 |
+
"""
|
| 22 |
+
typemap = {
|
| 23 |
+
'year': 'gYear',
|
| 24 |
+
'yearmonth': 'gYearMonth',
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
titles = [t for t in [spec.get('title')] if t]
|
| 28 |
+
|
| 29 |
+
res = {'name': spec['name'], 'datatype': {'base': 'string'}}
|
| 30 |
+
if 'type' in spec:
|
| 31 |
+
if spec['type'] == 'string' and spec.get('format') == 'binary':
|
| 32 |
+
res['datatype']['base'] = 'binary'
|
| 33 |
+
elif spec['type'] == 'string' and spec.get('format') == 'uri':
|
| 34 |
+
res['datatype']['base'] = 'anyURI'
|
| 35 |
+
elif spec['type'] in typemap:
|
| 36 |
+
res['datatype']['base'] = typemap[spec['type']]
|
| 37 |
+
elif spec['type'] in [
|
| 38 |
+
'string', 'number', 'integer', 'boolean', 'date', 'time', 'datetime', 'duration',
|
| 39 |
+
]:
|
| 40 |
+
res['datatype']['base'] = spec['type']
|
| 41 |
+
if spec['type'] == 'string' and spec.get('format'):
|
| 42 |
+
res['datatype']['dc:format'] = spec['format']
|
| 43 |
+
if spec['type'] == 'boolean' and spec.get('trueValues') and spec.get('falseValues'):
|
| 44 |
+
res['datatype']['format'] = '{}|{}'.format(
|
| 45 |
+
spec['trueValues'][0], spec['falseValues'][0])
|
| 46 |
+
if spec['type'] in ['number', 'integer']:
|
| 47 |
+
if spec.get('bareNumber') is True: # pragma: no cover
|
| 48 |
+
raise NotImplementedError(
|
| 49 |
+
'bareNumber is not supported in CSVW. It may be possible to translate to '
|
| 50 |
+
'a number pattern, though. See '
|
| 51 |
+
'https://www.w3.org/TR/2015/REC-tabular-data-model-20151217/'
|
| 52 |
+
'#formats-for-numeric-types')
|
| 53 |
+
if any(prop in spec for prop in ['decimalChar', 'groupChar']):
|
| 54 |
+
res['datatype']['format'] = {}
|
| 55 |
+
for p in ['decimalChar', 'groupChar']:
|
| 56 |
+
if spec.get(p):
|
| 57 |
+
res['datatype']['format'][p] = spec[p]
|
| 58 |
+
elif spec['type'] in ['object', 'array']:
|
| 59 |
+
res['datatype']['base'] = 'json'
|
| 60 |
+
res['datatype']['dc:format'] = 'application/json'
|
| 61 |
+
elif spec['type'] == 'geojson':
|
| 62 |
+
res['datatype']['base'] = 'json'
|
| 63 |
+
res['datatype']['dc:format'] = 'application/geo+json'
|
| 64 |
+
|
| 65 |
+
if titles:
|
| 66 |
+
res['titles'] = titles
|
| 67 |
+
if 'description' in spec:
|
| 68 |
+
res['dc:description'] = [spec['description']]
|
| 69 |
+
if 'rdfType' in spec:
|
| 70 |
+
res['propertyUrl'] = spec['rdfType']
|
| 71 |
+
|
| 72 |
+
constraints = spec.get('constraints', {})
|
| 73 |
+
for prop in ['required', 'minLength', 'maxLength', 'minimum', 'maximum']:
|
| 74 |
+
if prop in constraints:
|
| 75 |
+
res['datatype'][prop] = constraints[prop]
|
| 76 |
+
if ('pattern' in constraints) and ('format' not in res['datatype']):
|
| 77 |
+
res['datatype']['format'] = constraints['pattern']
|
| 78 |
+
# FIXME: we could transform the "enum" constraint for string into
|
| 79 |
+
# a regular expression in the "format" property.
|
| 80 |
+
return res
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def convert_foreignKey(rsc_name, fk, resource_map):
|
| 84 |
+
"""
|
| 85 |
+
https://specs.frictionlessdata.io/table-schema/#foreign-keys
|
| 86 |
+
"""
|
| 87 |
+
# Rename "fields" to "columnReference" and map resource name to url (resolving self-referential
|
| 88 |
+
# foreign keys).
|
| 89 |
+
return dict(
|
| 90 |
+
columnReference=fk['fields'],
|
| 91 |
+
reference=dict(
|
| 92 |
+
columnReference=fk['reference']['fields'],
|
| 93 |
+
resource=resource_map[fk['reference']['resource'] or rsc_name],
|
| 94 |
+
)
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def convert_table_schema(rsc_name, schema, resource_map):
|
| 99 |
+
"""
|
| 100 |
+
:param rsc_name: `name` property of the resource the schema belongs to. Needed to resolve \
|
| 101 |
+
self-referential foreign keys.
|
| 102 |
+
:param schema: `dict` parsed from JSON representing a frictionless Table Schema object.
|
| 103 |
+
:param resource_map: `dict` mapping resource names to resource paths, needed to convert foreign\
|
| 104 |
+
key constraints.
|
| 105 |
+
:return: `dict` suitable for instantiating a `csvw.metadata.Schema` object.
|
| 106 |
+
"""
|
| 107 |
+
res = dict(
|
| 108 |
+
columns=[convert_column_spec(f) for f in schema['fields']],
|
| 109 |
+
)
|
| 110 |
+
for prop in [
|
| 111 |
+
('missingValues', 'null'),
|
| 112 |
+
'primaryKey',
|
| 113 |
+
'foreignKeys',
|
| 114 |
+
]:
|
| 115 |
+
if isinstance(prop, tuple):
|
| 116 |
+
prop, toprop = prop
|
| 117 |
+
else:
|
| 118 |
+
toprop = prop
|
| 119 |
+
if prop in schema:
|
| 120 |
+
res[toprop] = schema[prop]
|
| 121 |
+
if prop == 'foreignKeys':
|
| 122 |
+
res[toprop] = [convert_foreignKey(rsc_name, fk, resource_map) for fk in res[toprop]]
|
| 123 |
+
return res
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def convert_dialect(rsc):
|
| 127 |
+
"""
|
| 128 |
+
Limitations: lineTerminator is not supported.
|
| 129 |
+
|
| 130 |
+
https://specs.frictionlessdata.io/csv-dialect/
|
| 131 |
+
"""
|
| 132 |
+
d = rsc.get('dialect', {})
|
| 133 |
+
# Work around https://github.com/frictionlessdata/frictionless-py/issues/1506
|
| 134 |
+
if 'csv' in d:
|
| 135 |
+
d = d['csv']
|
| 136 |
+
res = {}
|
| 137 |
+
if d.get('delimiter'):
|
| 138 |
+
res['delimiter'] = d['delimiter']
|
| 139 |
+
if rsc.get('encoding'):
|
| 140 |
+
res['encoding'] = rsc['encoding']
|
| 141 |
+
for prop in [
|
| 142 |
+
'delimiter',
|
| 143 |
+
'quoteChar',
|
| 144 |
+
'doubleQuote',
|
| 145 |
+
'skipInitialSpace',
|
| 146 |
+
'header',
|
| 147 |
+
]:
|
| 148 |
+
if prop in d:
|
| 149 |
+
res[prop] = d[prop]
|
| 150 |
+
if 'commentChar' in d:
|
| 151 |
+
res['commentPrefix'] = d['commentChar']
|
| 152 |
+
return res
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
class DataPackage:
|
| 156 |
+
def __init__(self, spec, directory=None):
|
| 157 |
+
if isinstance(spec, DataPackage):
|
| 158 |
+
self.json = spec.json
|
| 159 |
+
self.dir = spec.dir
|
| 160 |
+
return
|
| 161 |
+
if isinstance(spec, dict):
|
| 162 |
+
# already a parsed JSON object
|
| 163 |
+
self.dir = pathlib.Path(directory or '.')
|
| 164 |
+
elif isinstance(spec, pathlib.Path):
|
| 165 |
+
self.dir = directory or spec.parent
|
| 166 |
+
spec = json.loads(spec.read_text(encoding='utf8'))
|
| 167 |
+
else: # assume a JSON formatted string
|
| 168 |
+
spec = json.loads(spec)
|
| 169 |
+
self.dir = pathlib.Path(directory or '.')
|
| 170 |
+
|
| 171 |
+
self.json = spec
|
| 172 |
+
|
| 173 |
+
def to_tablegroup(self, cls=None):
|
| 174 |
+
from csvw import TableGroup
|
| 175 |
+
|
| 176 |
+
md = {'@context': "http://www.w3.org/ns/csvw"}
|
| 177 |
+
# Package metadata:
|
| 178 |
+
md['dc:replaces'] = json.dumps(self.json)
|
| 179 |
+
|
| 180 |
+
# version,
|
| 181 |
+
# image,
|
| 182 |
+
|
| 183 |
+
for flprop, csvwprop in [
|
| 184 |
+
('id', 'dc:identifier'),
|
| 185 |
+
('licenses', 'dc:license'),
|
| 186 |
+
('title', 'dc:title'),
|
| 187 |
+
('homepage', 'dcat:accessURL'),
|
| 188 |
+
('description', 'dc:description'),
|
| 189 |
+
('sources', 'dc:source'),
|
| 190 |
+
('contributors', 'dc:contributor'),
|
| 191 |
+
('profile', 'dc:conformsTo'),
|
| 192 |
+
('keywords', 'dc:subject'),
|
| 193 |
+
('created', 'dc:created'),
|
| 194 |
+
]:
|
| 195 |
+
if flprop in self.json:
|
| 196 |
+
md[csvwprop] = self.json[flprop]
|
| 197 |
+
|
| 198 |
+
if 'name' in self.json:
|
| 199 |
+
if 'id' not in self.json:
|
| 200 |
+
md['dc:identifier'] = self.json['name']
|
| 201 |
+
elif 'title' not in self.json:
|
| 202 |
+
md['dc:title'] = self.json['name']
|
| 203 |
+
|
| 204 |
+
# Data Resource metadata:
|
| 205 |
+
resources = [rsc for rsc in self.json.get('resources', []) if 'path' in rsc]
|
| 206 |
+
resource_map = {rsc['name']: rsc['path'] for rsc in resources if 'name' in rsc}
|
| 207 |
+
for rsc in resources:
|
| 208 |
+
schema = rsc.get('schema')
|
| 209 |
+
if schema and \
|
| 210 |
+
rsc.get('scheme') == 'file' and \
|
| 211 |
+
rsc.get('format') == 'csv':
|
| 212 |
+
# Table Schema:
|
| 213 |
+
md.setdefault('tables', [])
|
| 214 |
+
table = dict(
|
| 215 |
+
url=rsc['path'],
|
| 216 |
+
tableSchema=convert_table_schema(rsc.get('name'), schema, resource_map),
|
| 217 |
+
dialect=convert_dialect(rsc),
|
| 218 |
+
)
|
| 219 |
+
md['tables'].append(table)
|
| 220 |
+
|
| 221 |
+
cls = cls or TableGroup
|
| 222 |
+
res = cls.fromvalue(md)
|
| 223 |
+
res._fname = self.dir / 'csvw-metadata.json'
|
| 224 |
+
return res
|
TTS/Kokoro/.venv/Lib/site-packages/csvw/jsonld.py
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
import json
|
| 3 |
+
import math
|
| 4 |
+
import typing
|
| 5 |
+
import decimal
|
| 6 |
+
import pathlib
|
| 7 |
+
import datetime
|
| 8 |
+
import collections
|
| 9 |
+
|
| 10 |
+
import attr
|
| 11 |
+
from rdflib import Graph, URIRef, Literal
|
| 12 |
+
from rfc3986 import URIReference
|
| 13 |
+
from isodate.duration import Duration
|
| 14 |
+
|
| 15 |
+
from .utils import is_url
|
| 16 |
+
|
| 17 |
+
__all__ = ['group_triples', 'to_json', 'Triple', 'format_value']
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def format_value(value, col):
|
| 21 |
+
"""
|
| 22 |
+
Format values as JSON-LD literals.
|
| 23 |
+
"""
|
| 24 |
+
if isinstance(value, (datetime.date, datetime.datetime, datetime.time)):
|
| 25 |
+
res = value.isoformat()
|
| 26 |
+
if col and col.datatype.base == 'time':
|
| 27 |
+
res = res.split('T')[-1]
|
| 28 |
+
if col and col.datatype.base == 'date':
|
| 29 |
+
res = re.sub('T[0-9.:]+', '', res)
|
| 30 |
+
if isinstance(value, (datetime.datetime, datetime.time)):
|
| 31 |
+
stamp, _, milliseconds = res.partition('.')
|
| 32 |
+
return '{}.{}'.format(stamp, milliseconds.rstrip('0')) if milliseconds \
|
| 33 |
+
else stamp.replace('+00:00', 'Z')
|
| 34 |
+
return res # pragma: no cover
|
| 35 |
+
if isinstance(value, datetime.timedelta):
|
| 36 |
+
return col.datatype.formatted(value)
|
| 37 |
+
if isinstance(value, Duration):
|
| 38 |
+
return col.datatype.formatted(value)
|
| 39 |
+
if isinstance(value, decimal.Decimal):
|
| 40 |
+
value = float(value)
|
| 41 |
+
if isinstance(value, URIReference):
|
| 42 |
+
return value.unsplit()
|
| 43 |
+
if isinstance(value, bytes):
|
| 44 |
+
return col.datatype.formatted(value)
|
| 45 |
+
if isinstance(value, pathlib.Path):
|
| 46 |
+
return str(value)
|
| 47 |
+
if isinstance(value, float):
|
| 48 |
+
return 'NaN' if math.isnan(value) else (
|
| 49 |
+
'{}INF'.format('-' if value < 0 else '') if math.isinf(value) else value)
|
| 50 |
+
return value
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
@attr.s
|
| 54 |
+
class Triple:
|
| 55 |
+
"""
|
| 56 |
+
A table cell's data as RDF triple.
|
| 57 |
+
"""
|
| 58 |
+
about = attr.ib()
|
| 59 |
+
property = attr.ib()
|
| 60 |
+
value = attr.ib()
|
| 61 |
+
|
| 62 |
+
def as_rdflib_triple(self):
|
| 63 |
+
return (
|
| 64 |
+
URIRef(self.about),
|
| 65 |
+
URIRef(self.property),
|
| 66 |
+
URIRef(self.value) if is_url(self.value) else Literal(self.value))
|
| 67 |
+
|
| 68 |
+
@classmethod
|
| 69 |
+
def from_col(cls, table, col, row, prop, val, rownum):
|
| 70 |
+
"""
|
| 71 |
+
|
| 72 |
+
"""
|
| 73 |
+
_name = col.header if col else None
|
| 74 |
+
|
| 75 |
+
propertyUrl = col.propertyUrl if col else table.inherit('propertyUrl')
|
| 76 |
+
if propertyUrl:
|
| 77 |
+
prop = table.expand(propertyUrl, row, _row=rownum, _name=_name, qname=True)
|
| 78 |
+
|
| 79 |
+
is_type = prop == 'rdf:type'
|
| 80 |
+
valueUrl = col.valueUrl if col else table.inherit('valueUrl')
|
| 81 |
+
if valueUrl:
|
| 82 |
+
val = table.expand(valueUrl, row, _row=rownum, _name=_name, qname=is_type)
|
| 83 |
+
val = format_value(val, col)
|
| 84 |
+
s = None
|
| 85 |
+
aboutUrl = col.aboutUrl if col else None
|
| 86 |
+
if aboutUrl:
|
| 87 |
+
s = table.expand(aboutUrl, row, _row=rownum, _name=_name) or s
|
| 88 |
+
return cls(about=s, property=prop, value=val)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def frame(data: list) -> list:
|
| 92 |
+
"""
|
| 93 |
+
Inline referenced items to force a deterministic graph layout.
|
| 94 |
+
|
| 95 |
+
.. see:: https://w3c.github.io/json-ld-framing/#introduction
|
| 96 |
+
"""
|
| 97 |
+
items, refs = collections.OrderedDict(), {}
|
| 98 |
+
for item in data:
|
| 99 |
+
itemid = item.get('@id')
|
| 100 |
+
if itemid:
|
| 101 |
+
items[itemid] = item
|
| 102 |
+
for vs in item.values():
|
| 103 |
+
for v in [vs] if not isinstance(vs, list) else vs:
|
| 104 |
+
if isinstance(v, dict):
|
| 105 |
+
refid = v.get('@id')
|
| 106 |
+
if refid:
|
| 107 |
+
refs.setdefault(refid, (v, []))[1].append(item)
|
| 108 |
+
for ref, subjects in refs.values():
|
| 109 |
+
if len(subjects) == 1 and ref['@id'] in items:
|
| 110 |
+
ref.update(items.pop(ref['@id']))
|
| 111 |
+
return list(items.values())
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def to_json(obj, flatten_list=False):
|
| 115 |
+
"""
|
| 116 |
+
Simplify JSON-LD data by refactoring trivial objects.
|
| 117 |
+
"""
|
| 118 |
+
if isinstance(obj, dict):
|
| 119 |
+
if '@value' in obj:
|
| 120 |
+
obj = obj['@value']
|
| 121 |
+
if len(obj) == 1 and '@id' in obj:
|
| 122 |
+
obj = obj['@id']
|
| 123 |
+
if isinstance(obj, dict):
|
| 124 |
+
return {
|
| 125 |
+
'@type' if k == 'rdf:type' else k: to_json(v, flatten_list=flatten_list)
|
| 126 |
+
for k, v in obj.items()}
|
| 127 |
+
if isinstance(obj, list):
|
| 128 |
+
if len(obj) == 1 and flatten_list:
|
| 129 |
+
return to_json(obj[0], flatten_list=flatten_list)
|
| 130 |
+
return [to_json(v, flatten_list=flatten_list) for v in obj]
|
| 131 |
+
return obj
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def group_triples(triples: typing.Iterable[Triple]) -> typing.List[dict]:
|
| 135 |
+
"""
|
| 136 |
+
Group and frame triples into a `list` of JSON objects.
|
| 137 |
+
"""
|
| 138 |
+
merged = []
|
| 139 |
+
for triple in triples:
|
| 140 |
+
if isinstance(triple.value, list):
|
| 141 |
+
for t in merged:
|
| 142 |
+
if t.property == triple.property and isinstance(t.value, list):
|
| 143 |
+
t.value.extend(triple.value)
|
| 144 |
+
break
|
| 145 |
+
else:
|
| 146 |
+
merged.append(triple)
|
| 147 |
+
else:
|
| 148 |
+
merged.append(triple)
|
| 149 |
+
|
| 150 |
+
grouped = collections.OrderedDict()
|
| 151 |
+
triples = []
|
| 152 |
+
# First pass: get top-level properties.
|
| 153 |
+
for triple in merged:
|
| 154 |
+
if triple.about is None and triple.property == '@id':
|
| 155 |
+
grouped[triple.property] = triple.value
|
| 156 |
+
else:
|
| 157 |
+
if not triple.about:
|
| 158 |
+
# For test48
|
| 159 |
+
if triple.property in grouped:
|
| 160 |
+
if not isinstance(grouped[triple.property], list):
|
| 161 |
+
grouped[triple.property] = [grouped[triple.property]]
|
| 162 |
+
grouped[triple.property].append(triple.value)
|
| 163 |
+
else:
|
| 164 |
+
grouped[triple.property] = triple.value
|
| 165 |
+
else:
|
| 166 |
+
triples.append(triple)
|
| 167 |
+
if not triples:
|
| 168 |
+
return [grouped]
|
| 169 |
+
|
| 170 |
+
g = Graph()
|
| 171 |
+
for triple in triples:
|
| 172 |
+
g.add(triple.as_rdflib_triple())
|
| 173 |
+
if '@id' in grouped:
|
| 174 |
+
for prop, val in grouped.items():
|
| 175 |
+
if prop != '@id':
|
| 176 |
+
g.add(Triple(about=grouped['@id'], property=prop, value=val).as_rdflib_triple())
|
| 177 |
+
res = g.serialize(format='json-ld')
|
| 178 |
+
# Frame and simplify the resulting objects, augment with list index:
|
| 179 |
+
res = [(i, to_json(v, flatten_list=True)) for i, v in enumerate(frame(json.loads(res)))]
|
| 180 |
+
# Sort the objects making sure the one with the row's aboutUrl as @id comes first:
|
| 181 |
+
res = [k[1] for k in sorted(
|
| 182 |
+
res, key=lambda o: -1 if o[1].get('@id') == grouped.get('@id') else o[0])]
|
| 183 |
+
# If there's no aboutUrl for the row and we have only one object from triples, we just merge
|
| 184 |
+
# the properties into a single object.
|
| 185 |
+
if grouped and ('@id' not in grouped) and len(res) == 1:
|
| 186 |
+
grouped.update(res[0])
|
| 187 |
+
return [grouped]
|
| 188 |
+
|
| 189 |
+
return res
|
TTS/Kokoro/.venv/Lib/site-packages/csvw/metadata.py
ADDED
|
@@ -0,0 +1,1873 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# metadata.py
|
| 2 |
+
|
| 3 |
+
"""Functionality to read and write metadata for CSV files.
|
| 4 |
+
|
| 5 |
+
This module implements (partially) the W3C recommendation
|
| 6 |
+
"Metadata Vocabulary for Tabular Data".
|
| 7 |
+
|
| 8 |
+
.. seealso:: https://www.w3.org/TR/tabular-metadata/
|
| 9 |
+
"""
|
| 10 |
+
import io
|
| 11 |
+
import re
|
| 12 |
+
import json
|
| 13 |
+
import shutil
|
| 14 |
+
import decimal
|
| 15 |
+
import pathlib
|
| 16 |
+
import typing
|
| 17 |
+
import zipfile
|
| 18 |
+
import operator
|
| 19 |
+
import warnings
|
| 20 |
+
import functools
|
| 21 |
+
import itertools
|
| 22 |
+
import contextlib
|
| 23 |
+
import collections
|
| 24 |
+
from urllib.parse import urljoin, urlparse, urlunparse
|
| 25 |
+
|
| 26 |
+
from language_tags import tags
|
| 27 |
+
import attr
|
| 28 |
+
import requests
|
| 29 |
+
import uritemplate
|
| 30 |
+
|
| 31 |
+
from . import utils
|
| 32 |
+
from .datatypes import DATATYPES
|
| 33 |
+
from .dsv import Dialect as BaseDialect, UnicodeReaderWithLineNumber, UnicodeWriter
|
| 34 |
+
from .frictionless import DataPackage
|
| 35 |
+
from . import jsonld
|
| 36 |
+
|
| 37 |
+
DEFAULT = object()
|
| 38 |
+
|
| 39 |
+
__all__ = [
|
| 40 |
+
'TableGroup',
|
| 41 |
+
'Table', 'Column', 'ForeignKey',
|
| 42 |
+
'Link', 'NaturalLanguage',
|
| 43 |
+
'Datatype',
|
| 44 |
+
'is_url',
|
| 45 |
+
'CSVW',
|
| 46 |
+
]
|
| 47 |
+
|
| 48 |
+
NAMESPACES = {
|
| 49 |
+
'csvw': 'http://www.w3.org/ns/csvw#',
|
| 50 |
+
'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
|
| 51 |
+
'rdfs': 'http://www.w3.org/2000/01/rdf-schema#',
|
| 52 |
+
'xsd': 'http://www.w3.org/2001/XMLSchema#',
|
| 53 |
+
'dc': 'http://purl.org/dc/terms/',
|
| 54 |
+
'dcat': 'http://www.w3.org/ns/dcat#',
|
| 55 |
+
'prov': 'http://www.w3.org/ns/prov#',
|
| 56 |
+
'schema': 'http://schema.org/',
|
| 57 |
+
"as": "https://www.w3.org/ns/activitystreams#",
|
| 58 |
+
"cc": "http://creativecommons.org/ns#",
|
| 59 |
+
"ctag": "http://commontag.org/ns#",
|
| 60 |
+
"dc11": "http://purl.org/dc/elements/1.1/",
|
| 61 |
+
"dctypes": "http://purl.org/dc/dcmitype/",
|
| 62 |
+
"dqv": "http://www.w3.org/ns/dqv#",
|
| 63 |
+
"duv": "https://www.w3.org/ns/duv#",
|
| 64 |
+
"foaf": "http://xmlns.com/foaf/0.1/",
|
| 65 |
+
"gr": "http://purl.org/goodrelations/v1#",
|
| 66 |
+
"grddl": "http://www.w3.org/2003/g/data-view#",
|
| 67 |
+
"ical": "http://www.w3.org/2002/12/cal/icaltzd#",
|
| 68 |
+
"jsonld": "http://www.w3.org/ns/json-ld#",
|
| 69 |
+
"ldp": "http://www.w3.org/ns/ldp#",
|
| 70 |
+
"ma": "http://www.w3.org/ns/ma-ont#",
|
| 71 |
+
"oa": "http://www.w3.org/ns/oa#",
|
| 72 |
+
"odrl": "http://www.w3.org/ns/odrl/2/",
|
| 73 |
+
"og": "http://ogp.me/ns#",
|
| 74 |
+
"org": "http://www.w3.org/ns/org#",
|
| 75 |
+
"owl": "http://www.w3.org/2002/07/owl#",
|
| 76 |
+
"qb": "http://purl.org/linked-data/cube#",
|
| 77 |
+
"rdfa": "http://www.w3.org/ns/rdfa#",
|
| 78 |
+
"rev": "http://purl.org/stuff/rev#",
|
| 79 |
+
"rif": "http://www.w3.org/2007/rif#",
|
| 80 |
+
"rr": "http://www.w3.org/ns/r2rml#",
|
| 81 |
+
"sd": "http://www.w3.org/ns/sparql-service-description#",
|
| 82 |
+
"sioc": "http://rdfs.org/sioc/ns#",
|
| 83 |
+
"skos": "http://www.w3.org/2004/02/skos/core#",
|
| 84 |
+
"skosxl": "http://www.w3.org/2008/05/skos-xl#",
|
| 85 |
+
"sosa": "http://www.w3.org/ns/sosa/",
|
| 86 |
+
"ssn": "http://www.w3.org/ns/ssn/",
|
| 87 |
+
"time": "http://www.w3.org/2006/time#",
|
| 88 |
+
"v": "http://rdf.data-vocabulary.org/#",
|
| 89 |
+
"vcard": "http://www.w3.org/2006/vcard/ns#",
|
| 90 |
+
"void": "http://rdfs.org/ns/void#",
|
| 91 |
+
"wdr": "http://www.w3.org/2007/05/powder#",
|
| 92 |
+
"wrds": "http://www.w3.org/2007/05/powder-s#",
|
| 93 |
+
"xhv": "http://www.w3.org/1999/xhtml/vocab#",
|
| 94 |
+
"xml": "http://www.w3.org/XML/1998/namespace",
|
| 95 |
+
}
|
| 96 |
+
CSVW_TERMS = """Cell
|
| 97 |
+
Column
|
| 98 |
+
Datatype
|
| 99 |
+
Dialect
|
| 100 |
+
Direction
|
| 101 |
+
ForeignKey
|
| 102 |
+
JSON
|
| 103 |
+
NumericFormat
|
| 104 |
+
Row
|
| 105 |
+
Schema
|
| 106 |
+
Table
|
| 107 |
+
TableGroup
|
| 108 |
+
TableReference
|
| 109 |
+
Transformation
|
| 110 |
+
aboutUrl
|
| 111 |
+
base
|
| 112 |
+
columnReference
|
| 113 |
+
columns
|
| 114 |
+
commentPrefix
|
| 115 |
+
datatype
|
| 116 |
+
decimalChar
|
| 117 |
+
default
|
| 118 |
+
delimiter
|
| 119 |
+
describes
|
| 120 |
+
dialect
|
| 121 |
+
doubleQuote
|
| 122 |
+
encoding
|
| 123 |
+
foreignKeys
|
| 124 |
+
format
|
| 125 |
+
groupChar
|
| 126 |
+
header
|
| 127 |
+
headerRowCount
|
| 128 |
+
json
|
| 129 |
+
lang
|
| 130 |
+
length
|
| 131 |
+
lineTerminators
|
| 132 |
+
maxExclusive
|
| 133 |
+
maxInclusive
|
| 134 |
+
maxLength
|
| 135 |
+
maximum
|
| 136 |
+
minExclusive
|
| 137 |
+
minInclusive
|
| 138 |
+
minLength
|
| 139 |
+
minimum
|
| 140 |
+
name
|
| 141 |
+
notes
|
| 142 |
+
null
|
| 143 |
+
ordered
|
| 144 |
+
pattern
|
| 145 |
+
primaryKey
|
| 146 |
+
propertyUrl
|
| 147 |
+
quoteChar
|
| 148 |
+
reference
|
| 149 |
+
referencedRows
|
| 150 |
+
required
|
| 151 |
+
resource
|
| 152 |
+
row
|
| 153 |
+
rowTitles
|
| 154 |
+
rownum
|
| 155 |
+
schemaReference
|
| 156 |
+
scriptFormat
|
| 157 |
+
separator
|
| 158 |
+
skipBlankRows
|
| 159 |
+
skipColumns
|
| 160 |
+
skipInitialSpace
|
| 161 |
+
skipRows
|
| 162 |
+
source
|
| 163 |
+
suppressOutput
|
| 164 |
+
tableDirection
|
| 165 |
+
tableSchema
|
| 166 |
+
tables
|
| 167 |
+
targetFormat
|
| 168 |
+
textDirection
|
| 169 |
+
titles
|
| 170 |
+
transformations
|
| 171 |
+
trim
|
| 172 |
+
uriTemplate
|
| 173 |
+
url
|
| 174 |
+
valueUrl
|
| 175 |
+
virtual""".split()
|
| 176 |
+
is_url = utils.is_url
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
class Invalid:
|
| 180 |
+
pass
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
INVALID = Invalid()
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
@attr.s
|
| 187 |
+
class Dialect(BaseDialect):
|
| 188 |
+
"""
|
| 189 |
+
The spec is ambiguous regarding a default for the commentPrefix property:
|
| 190 |
+
|
| 191 |
+
> commentPrefix
|
| 192 |
+
> An atomic property that sets the comment prefix flag to the single provided value, which
|
| 193 |
+
> MUST be a string. The default is "#".
|
| 194 |
+
|
| 195 |
+
vs.
|
| 196 |
+
|
| 197 |
+
> comment prefix
|
| 198 |
+
> A string that, when it appears at the beginning of a row, indicates that the row is a
|
| 199 |
+
> comment that should be associated as a rdfs:comment annotation to the table. This is set
|
| 200 |
+
> by the commentPrefix property of a dialect description. The default is null, which means
|
| 201 |
+
> no rows are treated as comments. A value other than null may mean that the source numbers
|
| 202 |
+
> of rows are different from their numbers.
|
| 203 |
+
|
| 204 |
+
So, in order to pass the number formatting tests, with column names like `##.#`, we chose
|
| 205 |
+
the second reading - i.e. by default no rows are treated as comments.
|
| 206 |
+
"""
|
| 207 |
+
commentPrefix = attr.ib(
|
| 208 |
+
default=None,
|
| 209 |
+
converter=functools.partial(utils.converter, str, None, allow_none=True),
|
| 210 |
+
validator=attr.validators.optional(attr.validators.instance_of(str)))
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def json_open(filename, mode='r', encoding='utf-8'):
|
| 214 |
+
assert encoding == 'utf-8'
|
| 215 |
+
return io.open(filename, mode, encoding=encoding)
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def get_json(fname) -> typing.Union[list, dict]:
|
| 219 |
+
fname = str(fname)
|
| 220 |
+
if is_url(fname):
|
| 221 |
+
return requests.get(fname).json(object_pairs_hook=collections.OrderedDict)
|
| 222 |
+
with json_open(fname) as f:
|
| 223 |
+
return json.load(f, object_pairs_hook=collections.OrderedDict)
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def log_or_raise(msg, log=None, level='warning', exception_cls=ValueError):
|
| 227 |
+
if log:
|
| 228 |
+
getattr(log, level)(msg)
|
| 229 |
+
else:
|
| 230 |
+
raise exception_cls(msg)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def nolog(level='warning'):
|
| 234 |
+
from types import MethodType
|
| 235 |
+
|
| 236 |
+
class Log(object):
|
| 237 |
+
pass
|
| 238 |
+
|
| 239 |
+
log = Log()
|
| 240 |
+
setattr(log, level, MethodType(lambda *args, **kw: None, log))
|
| 241 |
+
return log
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
class URITemplate(uritemplate.URITemplate):
|
| 245 |
+
|
| 246 |
+
def __eq__(self, other):
|
| 247 |
+
if isinstance(other, str):
|
| 248 |
+
return self.uri == other
|
| 249 |
+
if not hasattr(other, 'uri'):
|
| 250 |
+
return False
|
| 251 |
+
return super(URITemplate, self).__eq__(other)
|
| 252 |
+
|
| 253 |
+
def asdict(self, **kw):
|
| 254 |
+
return '{}'.format(self)
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def uri_template_property():
|
| 258 |
+
"""
|
| 259 |
+
|
| 260 |
+
Note: We do not currently provide support for supplying the "_" variables like "_row"
|
| 261 |
+
when expanding a URI template.
|
| 262 |
+
|
| 263 |
+
.. seealso:: http://w3c.github.io/csvw/metadata/#uri-template-properties
|
| 264 |
+
"""
|
| 265 |
+
def converter_uriTemplate(v):
|
| 266 |
+
if v is None:
|
| 267 |
+
return None
|
| 268 |
+
if not isinstance(v, str):
|
| 269 |
+
warnings.warn('Invalid value for aboutUrl property')
|
| 270 |
+
return INVALID
|
| 271 |
+
return URITemplate(v)
|
| 272 |
+
|
| 273 |
+
return attr.ib(
|
| 274 |
+
default=None,
|
| 275 |
+
validator=attr.validators.optional(attr.validators.instance_of((URITemplate, Invalid))),
|
| 276 |
+
converter=converter_uriTemplate)
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
class Link:
|
| 280 |
+
"""
|
| 281 |
+
|
| 282 |
+
.. seealso:: http://w3c.github.io/csvw/metadata/#link-properties
|
| 283 |
+
"""
|
| 284 |
+
|
| 285 |
+
def __init__(self, string: typing.Union[str, pathlib.Path]):
|
| 286 |
+
if not isinstance(string, (str, pathlib.Path)):
|
| 287 |
+
raise ValueError('Invalid value for link property')
|
| 288 |
+
self.string = string
|
| 289 |
+
|
| 290 |
+
def __str__(self):
|
| 291 |
+
return self.string
|
| 292 |
+
|
| 293 |
+
def asdict(self, omit_defaults=True):
|
| 294 |
+
return self.string
|
| 295 |
+
|
| 296 |
+
def __eq__(self, other):
|
| 297 |
+
# FIXME: Only naive, un-resolved comparison is supported at the moment.
|
| 298 |
+
return self.string == other.string if isinstance(other, Link) else False
|
| 299 |
+
|
| 300 |
+
def resolve(self, base):
|
| 301 |
+
"""
|
| 302 |
+
Resolve a `Link` relative to `base`.
|
| 303 |
+
|
| 304 |
+
:param base:
|
| 305 |
+
:return: Either a string, representing a URL, or a `pathlib.Path` object, representing \
|
| 306 |
+
a local file.
|
| 307 |
+
"""
|
| 308 |
+
if hasattr(base, 'joinpath'):
|
| 309 |
+
if is_url(self.string):
|
| 310 |
+
return self.string
|
| 311 |
+
return (base if base.is_dir() else base.parent) / self.string
|
| 312 |
+
return urljoin(base, self.string)
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
def link_property(required=False):
|
| 316 |
+
return attr.ib(
|
| 317 |
+
default=None,
|
| 318 |
+
validator=attr.validators.optional(attr.validators.instance_of(Link)),
|
| 319 |
+
converter=lambda v: v if v is None else Link(v))
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
class NaturalLanguage(collections.OrderedDict):
|
| 323 |
+
"""
|
| 324 |
+
|
| 325 |
+
.. seealso:: http://w3c.github.io/csvw/metadata/#natural-language-properties
|
| 326 |
+
"""
|
| 327 |
+
|
| 328 |
+
def __init__(self, value):
|
| 329 |
+
super(NaturalLanguage, self).__init__()
|
| 330 |
+
self.value = value
|
| 331 |
+
if isinstance(self.value, str):
|
| 332 |
+
self[None] = [self.value]
|
| 333 |
+
elif isinstance(self.value, (list, tuple)):
|
| 334 |
+
if not all(isinstance(v, str) for v in self.value):
|
| 335 |
+
warnings.warn('titles with array values containing non-string values are ignored')
|
| 336 |
+
else:
|
| 337 |
+
self[None] = list(self.value)
|
| 338 |
+
elif isinstance(self.value, dict):
|
| 339 |
+
for k, v in self.value.items():
|
| 340 |
+
if not tags.check(k):
|
| 341 |
+
raise ValueError('Invalid language tag for NaturalLanguage')
|
| 342 |
+
if not isinstance(v, (list, tuple)):
|
| 343 |
+
v = [v]
|
| 344 |
+
titles = []
|
| 345 |
+
for vv in v:
|
| 346 |
+
if isinstance(vv, str):
|
| 347 |
+
titles.append(vv)
|
| 348 |
+
else:
|
| 349 |
+
warnings.warn('Title with value which is not a string is ignored')
|
| 350 |
+
self[k] = titles
|
| 351 |
+
else:
|
| 352 |
+
raise ValueError('invalid value type for NaturalLanguage')
|
| 353 |
+
|
| 354 |
+
def asdict(self, omit_defaults=True):
|
| 355 |
+
if list(self) == [None]:
|
| 356 |
+
if len(self[None]) == 1:
|
| 357 |
+
return self.getfirst()
|
| 358 |
+
return self[None]
|
| 359 |
+
return collections.OrderedDict(
|
| 360 |
+
('und' if k is None else k, v[0] if len(v) == 1 else v)
|
| 361 |
+
for k, v in self.items())
|
| 362 |
+
|
| 363 |
+
def add(self, string, lang=None):
|
| 364 |
+
if lang not in self:
|
| 365 |
+
self[lang] = []
|
| 366 |
+
self[lang].append(string)
|
| 367 |
+
|
| 368 |
+
def __str__(self):
|
| 369 |
+
return self.getfirst() or next(iter(self.values()))[0]
|
| 370 |
+
|
| 371 |
+
def getfirst(self, lang=None):
|
| 372 |
+
return self.get(lang, [None])[0]
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def valid_id_property(v):
|
| 376 |
+
if not isinstance(v, str):
|
| 377 |
+
warnings.warn('Inconsistent link property')
|
| 378 |
+
return None
|
| 379 |
+
if v.startswith('_'):
|
| 380 |
+
raise ValueError('Invalid @id property: {}'.format(v))
|
| 381 |
+
return v
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
def valid_common_property(v):
|
| 385 |
+
if isinstance(v, dict):
|
| 386 |
+
if not {k[1:] for k in v if k.startswith('@')}.issubset(
|
| 387 |
+
{'id', 'language', 'type', 'value'}):
|
| 388 |
+
raise ValueError(
|
| 389 |
+
"Aside from @value, @type, @language, and @id, the properties used on an object "
|
| 390 |
+
"MUST NOT start with @.")
|
| 391 |
+
if '@value' in v:
|
| 392 |
+
if len(v) > 1:
|
| 393 |
+
if len(v) > 2 \
|
| 394 |
+
or set(v.keys()) not in [{'@value', '@language'}, {'@value', '@type'}] \
|
| 395 |
+
or not isinstance(v['@value'], (str, bool, int, decimal.Decimal)):
|
| 396 |
+
raise ValueError(
|
| 397 |
+
"If a @value property is used on an object, that object MUST NOT have "
|
| 398 |
+
"any other properties aside from either @type or @language, and MUST "
|
| 399 |
+
"NOT have both @type and @language as properties. The value of the "
|
| 400 |
+
"@value property MUST be a string, number, or boolean value.")
|
| 401 |
+
if '@language' in v and '@value' not in v:
|
| 402 |
+
raise ValueError(
|
| 403 |
+
"A @language property MUST NOT be used on an object unless it also has a "
|
| 404 |
+
"@value property.")
|
| 405 |
+
if '@id' in v:
|
| 406 |
+
v['@id'] = valid_id_property(v['@id'])
|
| 407 |
+
if '@language' in v:
|
| 408 |
+
if not (isinstance(v['@language'], str) and tags.check(v['@language'])):
|
| 409 |
+
warnings.warn('Invalid language tag')
|
| 410 |
+
del v['@language']
|
| 411 |
+
if '@type' in v:
|
| 412 |
+
vv = v['@type']
|
| 413 |
+
if isinstance(vv, str):
|
| 414 |
+
if vv.startswith('_:'):
|
| 415 |
+
raise ValueError(
|
| 416 |
+
'The value of any @id or @type contained within a metadata document '
|
| 417 |
+
'MUST NOT be a blank node.')
|
| 418 |
+
if not is_url(vv) and \
|
| 419 |
+
not any(vv == ns or vv.startswith(ns + ':') for ns in NAMESPACES) and \
|
| 420 |
+
vv not in CSVW_TERMS:
|
| 421 |
+
raise ValueError(
|
| 422 |
+
'The value of any member of @type MUST be either a term defined in '
|
| 423 |
+
'[csvw-context], a prefixed name where the prefix is a term defined in '
|
| 424 |
+
'[csvw-context], or an absolute URL.')
|
| 425 |
+
elif not isinstance(vv, (list, dict)):
|
| 426 |
+
raise ValueError('Invalid datatype for @type')
|
| 427 |
+
return {k: valid_common_property(vv) for k, vv in v.items()}
|
| 428 |
+
if isinstance(v, list):
|
| 429 |
+
return [valid_common_property(vv) for vv in v]
|
| 430 |
+
return v
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
@attr.s
|
| 434 |
+
class DescriptionBase:
|
| 435 |
+
"""Container for
|
| 436 |
+
- common properties (see http://w3c.github.io/csvw/metadata/#common-properties)
|
| 437 |
+
- @-properties.
|
| 438 |
+
"""
|
| 439 |
+
|
| 440 |
+
common_props = attr.ib(default=attr.Factory(dict))
|
| 441 |
+
at_props = attr.ib(default=attr.Factory(dict))
|
| 442 |
+
|
| 443 |
+
@classmethod
|
| 444 |
+
def partition_properties(cls,
|
| 445 |
+
d: typing.Union[dict, typing.Any],
|
| 446 |
+
type_name: typing.Optional[str] = None,
|
| 447 |
+
strict=True) -> typing.Union[dict, None]:
|
| 448 |
+
if d and not isinstance(d, dict):
|
| 449 |
+
return
|
| 450 |
+
fields = attr.fields_dict(cls)
|
| 451 |
+
type_name = type_name or cls.__name__
|
| 452 |
+
c, a, dd = {}, {}, {}
|
| 453 |
+
for k, v in (d or {}).items():
|
| 454 |
+
if k.startswith('@'):
|
| 455 |
+
if k == '@id':
|
| 456 |
+
v = valid_id_property(v)
|
| 457 |
+
if k == '@type' and v != type_name:
|
| 458 |
+
raise ValueError('Invalid @type property {} for {}'.format(v, type_name))
|
| 459 |
+
a[k[1:]] = v
|
| 460 |
+
elif ':' in k:
|
| 461 |
+
c[k] = valid_common_property(v)
|
| 462 |
+
else:
|
| 463 |
+
if strict and (k not in fields):
|
| 464 |
+
warnings.warn('Invalid property {} for {}'.format(k, type_name))
|
| 465 |
+
else:
|
| 466 |
+
dd[k] = v
|
| 467 |
+
return dict(common_props=c, at_props=a, **dd)
|
| 468 |
+
|
| 469 |
+
@classmethod
|
| 470 |
+
def fromvalue(cls, d: dict):
|
| 471 |
+
return cls(**cls.partition_properties(d))
|
| 472 |
+
|
| 473 |
+
def _iter_dict_items(self, omit_defaults):
|
| 474 |
+
def _asdict_single(v):
|
| 475 |
+
return v.asdict(omit_defaults=omit_defaults) if hasattr(v, 'asdict') else v
|
| 476 |
+
|
| 477 |
+
def _asdict_multiple(v):
|
| 478 |
+
if isinstance(v, (list, tuple)):
|
| 479 |
+
return [_asdict_single(vv) for vv in v]
|
| 480 |
+
return _asdict_single(v)
|
| 481 |
+
|
| 482 |
+
for k, v in sorted(self.at_props.items()):
|
| 483 |
+
yield '@' + k, _asdict_multiple(v)
|
| 484 |
+
|
| 485 |
+
for k, v in sorted(self.common_props.items()):
|
| 486 |
+
yield k, _asdict_multiple(v)
|
| 487 |
+
|
| 488 |
+
for k, v in utils.attr_asdict(self, omit_defaults=omit_defaults).items():
|
| 489 |
+
if k not in ('common_props', 'at_props'):
|
| 490 |
+
yield k, _asdict_multiple(v)
|
| 491 |
+
|
| 492 |
+
def asdict(self, omit_defaults=True) -> dict:
|
| 493 |
+
# Note: The `null` property is the only inherited, list-valued property where the default
|
| 494 |
+
# is not the empty list. Thus, to allow setting it to empty, we must treat `null` as
|
| 495 |
+
# special case here.
|
| 496 |
+
# See also https://www.w3.org/TR/tabular-metadata/#dfn-inherited-property
|
| 497 |
+
return collections.OrderedDict(
|
| 498 |
+
(k, v) for k, v in self._iter_dict_items(omit_defaults)
|
| 499 |
+
if (k == 'null' or (v not in ([], {}))))
|
| 500 |
+
|
| 501 |
+
|
| 502 |
+
def optional_int():
|
| 503 |
+
return attr.ib(
|
| 504 |
+
default=None,
|
| 505 |
+
validator=attr.validators.optional(attr.validators.instance_of(int)),
|
| 506 |
+
converter=lambda v: v if v is None else int(v))
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
@attr.s
|
| 510 |
+
class Datatype(DescriptionBase):
|
| 511 |
+
"""
|
| 512 |
+
A datatype description
|
| 513 |
+
|
| 514 |
+
Cells within tables may be annotated with a datatype which indicates the type of the values
|
| 515 |
+
obtained by parsing the string value of the cell.
|
| 516 |
+
|
| 517 |
+
.. seealso:: `<https://www.w3.org/TR/tabular-metadata/#datatypes>`_
|
| 518 |
+
"""
|
| 519 |
+
|
| 520 |
+
base = attr.ib(
|
| 521 |
+
default=None,
|
| 522 |
+
converter=functools.partial(
|
| 523 |
+
utils.converter,
|
| 524 |
+
str, 'string', allow_none=True, cond=lambda ss: ss is None or ss in DATATYPES),
|
| 525 |
+
validator=attr.validators.optional(attr.validators.in_(DATATYPES)))
|
| 526 |
+
format = attr.ib(default=None)
|
| 527 |
+
length = optional_int()
|
| 528 |
+
minLength = optional_int()
|
| 529 |
+
maxLength = optional_int()
|
| 530 |
+
minimum = attr.ib(default=None)
|
| 531 |
+
maximum = attr.ib(default=None)
|
| 532 |
+
minInclusive = attr.ib(default=None)
|
| 533 |
+
maxInclusive = attr.ib(default=None)
|
| 534 |
+
minExclusive = attr.ib(default=None)
|
| 535 |
+
maxExclusive = attr.ib(default=None)
|
| 536 |
+
|
| 537 |
+
@classmethod
|
| 538 |
+
def fromvalue(cls, v: typing.Union[str, dict, 'Datatype']) -> 'Datatype':
|
| 539 |
+
"""
|
| 540 |
+
:param v: Initialization data for `cls`; either a single string that is the main datatype \
|
| 541 |
+
of the values of the cell or a datatype description object, i.e. a `dict` or a `cls` \
|
| 542 |
+
instance.
|
| 543 |
+
:return: An instance of `cls`
|
| 544 |
+
"""
|
| 545 |
+
if isinstance(v, str):
|
| 546 |
+
return cls(base=v)
|
| 547 |
+
|
| 548 |
+
if isinstance(v, dict):
|
| 549 |
+
v.setdefault('base', 'string')
|
| 550 |
+
return cls(**cls.partition_properties(v))
|
| 551 |
+
|
| 552 |
+
if isinstance(v, cls):
|
| 553 |
+
return v
|
| 554 |
+
|
| 555 |
+
raise ValueError(v)
|
| 556 |
+
|
| 557 |
+
def __attrs_post_init__(self):
|
| 558 |
+
for attr_ in [
|
| 559 |
+
'minimum', 'maximum', 'minInclusive', 'maxInclusive', 'minExclusive', 'maxExclusive'
|
| 560 |
+
]:
|
| 561 |
+
if getattr(self, attr_) is not None:
|
| 562 |
+
setattr(self, attr_, self.parse(getattr(self, attr_)))
|
| 563 |
+
|
| 564 |
+
if self.length is not None:
|
| 565 |
+
if self.minLength is not None and self.length < self.minLength:
|
| 566 |
+
raise ValueError('minLength > length')
|
| 567 |
+
|
| 568 |
+
if self.maxLength is not None:
|
| 569 |
+
if self.length > self.maxLength:
|
| 570 |
+
raise ValueError('maxLength < length')
|
| 571 |
+
|
| 572 |
+
if self.minLength is not None and self.maxLength is not None \
|
| 573 |
+
and self.minLength > self.maxLength:
|
| 574 |
+
raise ValueError('minLength > maxLength')
|
| 575 |
+
|
| 576 |
+
if not isinstance(self.derived_description, dict):
|
| 577 |
+
raise ValueError() # pragma: no cover
|
| 578 |
+
|
| 579 |
+
if not isinstance(
|
| 580 |
+
self.basetype(),
|
| 581 |
+
tuple((DATATYPES[name] for name in ['decimal', 'float', 'datetime', 'duration']))):
|
| 582 |
+
if any([getattr(self, at) for at in
|
| 583 |
+
'minimum maximum minExclusive maxExclusive minInclusive maxInclusive'.split()]):
|
| 584 |
+
raise ValueError(
|
| 585 |
+
'Applications MUST raise an error if minimum, minInclusive, maximum, '
|
| 586 |
+
'maxInclusive, minExclusive, or maxExclusive are specified and the base '
|
| 587 |
+
'datatype is not a numeric, date/time, or duration type.')
|
| 588 |
+
|
| 589 |
+
if not isinstance(
|
| 590 |
+
self.basetype(),
|
| 591 |
+
(DATATYPES['string'], DATATYPES['base64Binary'], DATATYPES['hexBinary'])):
|
| 592 |
+
if self.length or self.minLength or self.maxLength:
|
| 593 |
+
raise ValueError(
|
| 594 |
+
'Applications MUST raise an error if length, maxLength, or minLength are '
|
| 595 |
+
'specified and the base datatype is not string or one of its subtypes, or a '
|
| 596 |
+
'binary type.')
|
| 597 |
+
|
| 598 |
+
if (self.minInclusive and self.minExclusive) or (self.maxInclusive and self.maxExclusive):
|
| 599 |
+
raise ValueError(
|
| 600 |
+
'Applications MUST raise an error if both minInclusive and minExclusive are '
|
| 601 |
+
'specified, or if both maxInclusive and maxExclusive are specified.')
|
| 602 |
+
|
| 603 |
+
if (self.minInclusive and self.maxExclusive and self.maxExclusive <= self.minInclusive) or \
|
| 604 |
+
(self.minInclusive and self.maxInclusive and self.maxInclusive < self.minInclusive):
|
| 605 |
+
raise ValueError('')
|
| 606 |
+
|
| 607 |
+
if (self.minExclusive and self.maxExclusive and self.maxExclusive <= self.minExclusive) or (
|
| 608 |
+
self.minExclusive and self.maxInclusive and self.maxInclusive <= self.minExclusive):
|
| 609 |
+
raise ValueError('')
|
| 610 |
+
|
| 611 |
+
if 'id' in self.at_props and any(
|
| 612 |
+
self.at_props['id'] == NAMESPACES['xsd'] + dt for dt in DATATYPES):
|
| 613 |
+
raise ValueError('datatype @id MUST NOT be the URL of a built-in datatype.')
|
| 614 |
+
|
| 615 |
+
if isinstance(self.basetype(), DATATYPES['decimal']) and \
|
| 616 |
+
'pattern' in self.derived_description:
|
| 617 |
+
if not set(self.derived_description['pattern']).issubset(set('#0.,;%‰E-+')):
|
| 618 |
+
self.format = None
|
| 619 |
+
warnings.warn('Invalid number pattern')
|
| 620 |
+
|
| 621 |
+
def asdict(self, omit_defaults=True):
|
| 622 |
+
res = DescriptionBase.asdict(self, omit_defaults=omit_defaults)
|
| 623 |
+
for attr_ in [
|
| 624 |
+
'minimum', 'maximum', 'minInclusive', 'maxInclusive', 'minExclusive', 'maxExclusive'
|
| 625 |
+
]:
|
| 626 |
+
if attr_ in res:
|
| 627 |
+
res[attr_] = self.formatted(res[attr_])
|
| 628 |
+
if len(res) == 1 and 'base' in res:
|
| 629 |
+
return res['base']
|
| 630 |
+
return res
|
| 631 |
+
|
| 632 |
+
@property
|
| 633 |
+
def basetype(self):
|
| 634 |
+
return DATATYPES[self.base]
|
| 635 |
+
|
| 636 |
+
@property
|
| 637 |
+
def derived_description(self):
|
| 638 |
+
return self.basetype.derived_description(self)
|
| 639 |
+
|
| 640 |
+
def formatted(self, v):
|
| 641 |
+
return self.basetype.to_string(v, **self.derived_description)
|
| 642 |
+
|
| 643 |
+
def parse(self, v):
|
| 644 |
+
if v is None:
|
| 645 |
+
return v
|
| 646 |
+
return self.basetype.to_python(v, **self.derived_description)
|
| 647 |
+
|
| 648 |
+
def validate(self, v):
|
| 649 |
+
if v is None:
|
| 650 |
+
return v
|
| 651 |
+
try:
|
| 652 |
+
l_ = len(v or '')
|
| 653 |
+
if self.length is not None and l_ != self.length:
|
| 654 |
+
raise ValueError('value must have length {}'.format(self.length))
|
| 655 |
+
if self.minLength is not None and l_ < self.minLength:
|
| 656 |
+
raise ValueError('value must have at least length {}'.format(self.minLength))
|
| 657 |
+
if self.maxLength is not None and l_ > self.maxLength:
|
| 658 |
+
raise ValueError('value must have at most length {}'.format(self.maxLength))
|
| 659 |
+
except TypeError:
|
| 660 |
+
pass
|
| 661 |
+
if self.basetype.minmax:
|
| 662 |
+
if self.minimum is not None and v < self.minimum:
|
| 663 |
+
raise ValueError('value must be >= {}'.format(self.minimum))
|
| 664 |
+
if self.minInclusive is not None and v < self.minInclusive:
|
| 665 |
+
raise ValueError('value must be >= {}'.format(self.minInclusive))
|
| 666 |
+
if self.minExclusive is not None and v <= self.minExclusive:
|
| 667 |
+
raise ValueError('value must be > {}'.format(self.minExclusive))
|
| 668 |
+
if self.maximum is not None and v > self.maximum:
|
| 669 |
+
raise ValueError('value must be <= {}'.format(self.maximum))
|
| 670 |
+
if self.maxInclusive is not None and v > self.maxInclusive:
|
| 671 |
+
raise ValueError('value must be <= {}'.format(self.maxInclusive))
|
| 672 |
+
if self.maxExclusive is not None and v >= self.maxExclusive:
|
| 673 |
+
raise ValueError('value must be < {}'.format(self.maxExclusive))
|
| 674 |
+
return v
|
| 675 |
+
|
| 676 |
+
def read(self, v):
|
| 677 |
+
return self.validate(self.parse(v))
|
| 678 |
+
|
| 679 |
+
|
| 680 |
+
def converter_null(v):
|
| 681 |
+
res = [] if v is None else (v if isinstance(v, list) else [v])
|
| 682 |
+
if not all(isinstance(vv, str) for vv in res):
|
| 683 |
+
warnings.warn('Invalid null property')
|
| 684 |
+
return [""]
|
| 685 |
+
return res
|
| 686 |
+
|
| 687 |
+
|
| 688 |
+
def converter_lang(v):
|
| 689 |
+
if not tags.check(v):
|
| 690 |
+
warnings.warn('Invalid language tag')
|
| 691 |
+
return 'und'
|
| 692 |
+
return v
|
| 693 |
+
|
| 694 |
+
|
| 695 |
+
@attr.s
|
| 696 |
+
class Description(DescriptionBase):
|
| 697 |
+
"""Adds support for inherited properties.
|
| 698 |
+
|
| 699 |
+
.. seealso:: http://w3c.github.io/csvw/metadata/#inherited-properties
|
| 700 |
+
"""
|
| 701 |
+
|
| 702 |
+
# To be able to resolve inheritance chains, we also provide a place to store a
|
| 703 |
+
# reference to the containing object. Note that this attribute is ignored when judging
|
| 704 |
+
# equality between objects. Thus, identically specified columns of different tables will be
|
| 705 |
+
# considered equal.
|
| 706 |
+
_parent = attr.ib(default=None, repr=False, eq=False)
|
| 707 |
+
|
| 708 |
+
aboutUrl = uri_template_property()
|
| 709 |
+
datatype = attr.ib(
|
| 710 |
+
default=None,
|
| 711 |
+
converter=lambda v: v if not v else Datatype.fromvalue(v))
|
| 712 |
+
default = attr.ib(
|
| 713 |
+
default="",
|
| 714 |
+
converter=functools.partial(utils.converter, str, "", allow_list=False),
|
| 715 |
+
)
|
| 716 |
+
lang = attr.ib(default="und", converter=converter_lang)
|
| 717 |
+
null = attr.ib(default=attr.Factory(lambda: [""]), converter=converter_null)
|
| 718 |
+
ordered = attr.ib(
|
| 719 |
+
default=None,
|
| 720 |
+
converter=functools.partial(utils.converter, bool, False, allow_none=True),
|
| 721 |
+
)
|
| 722 |
+
propertyUrl = uri_template_property()
|
| 723 |
+
required = attr.ib(default=None)
|
| 724 |
+
separator = attr.ib(
|
| 725 |
+
converter=functools.partial(utils.converter, str, None, allow_none=True),
|
| 726 |
+
default=None,
|
| 727 |
+
)
|
| 728 |
+
textDirection = attr.ib(
|
| 729 |
+
default=None,
|
| 730 |
+
converter=functools.partial(
|
| 731 |
+
utils.converter,
|
| 732 |
+
str, None, allow_none=True, cond=lambda v: v in [None, "ltr", "rtl", "auto", "inherit"])
|
| 733 |
+
)
|
| 734 |
+
valueUrl = uri_template_property()
|
| 735 |
+
|
| 736 |
+
def inherit(self, attr):
|
| 737 |
+
v = getattr(self, attr)
|
| 738 |
+
if v is None and self._parent:
|
| 739 |
+
return self._parent.inherit(attr) if hasattr(self._parent, 'inherit') \
|
| 740 |
+
else getattr(self._parent, attr)
|
| 741 |
+
return v
|
| 742 |
+
|
| 743 |
+
def inherit_null(self):
|
| 744 |
+
if self.null == [""]:
|
| 745 |
+
if self._parent and hasattr(self._parent, 'inherit_null'):
|
| 746 |
+
return self._parent.inherit_null()
|
| 747 |
+
return self.null
|
| 748 |
+
|
| 749 |
+
|
| 750 |
+
def converter_titles(v):
|
| 751 |
+
try:
|
| 752 |
+
return v if v is None else NaturalLanguage(v)
|
| 753 |
+
except ValueError:
|
| 754 |
+
warnings.warn('Invalid titles property')
|
| 755 |
+
return None
|
| 756 |
+
|
| 757 |
+
|
| 758 |
+
@attr.s
|
| 759 |
+
class Column(Description):
|
| 760 |
+
"""
|
| 761 |
+
A column description is an object that describes a single column.
|
| 762 |
+
|
| 763 |
+
The description provides additional human-readable documentation for a column, as well as
|
| 764 |
+
additional information that may be used to validate the cells within the column, create a
|
| 765 |
+
user interface for data entry, or inform conversion into other formats.
|
| 766 |
+
|
| 767 |
+
.. seealso:: `<https://www.w3.org/TR/tabular-metadata/#columns>`_
|
| 768 |
+
"""
|
| 769 |
+
name = attr.ib(
|
| 770 |
+
default=None,
|
| 771 |
+
converter=functools.partial(utils.converter, str, None, allow_none=True)
|
| 772 |
+
)
|
| 773 |
+
suppressOutput = attr.ib(
|
| 774 |
+
default=False,
|
| 775 |
+
converter=functools.partial(utils.converter, bool, False))
|
| 776 |
+
titles = attr.ib(
|
| 777 |
+
default=None,
|
| 778 |
+
validator=attr.validators.optional(attr.validators.instance_of(NaturalLanguage)),
|
| 779 |
+
converter=converter_titles)
|
| 780 |
+
virtual = attr.ib(default=False, converter=functools.partial(utils.converter, bool, False))
|
| 781 |
+
_number = attr.ib(default=None, repr=False)
|
| 782 |
+
|
| 783 |
+
def __str__(self):
|
| 784 |
+
return self.name or \
|
| 785 |
+
(self.titles and self.titles.getfirst()) or \
|
| 786 |
+
'_col.{}'.format(self._number)
|
| 787 |
+
|
| 788 |
+
def has_title(self, v):
|
| 789 |
+
if self.name and self.name == v:
|
| 790 |
+
return True
|
| 791 |
+
for tag, titles in (self.titles or {}).items():
|
| 792 |
+
if v in titles:
|
| 793 |
+
return tag or 'und'
|
| 794 |
+
return False
|
| 795 |
+
|
| 796 |
+
@property
|
| 797 |
+
def header(self):
|
| 798 |
+
return '{}'.format(self)
|
| 799 |
+
|
| 800 |
+
def read(self, v, strict=True):
|
| 801 |
+
required = self.inherit('required')
|
| 802 |
+
null = self.inherit_null()
|
| 803 |
+
default = self.inherit('default')
|
| 804 |
+
separator = self.inherit('separator')
|
| 805 |
+
datatype = self.inherit('datatype')
|
| 806 |
+
|
| 807 |
+
if not v:
|
| 808 |
+
v = default
|
| 809 |
+
|
| 810 |
+
if required and v in null:
|
| 811 |
+
if not strict:
|
| 812 |
+
warnings.warn('required column value is missing')
|
| 813 |
+
raise ValueError('required column value is missing')
|
| 814 |
+
|
| 815 |
+
if separator:
|
| 816 |
+
if not v:
|
| 817 |
+
v = []
|
| 818 |
+
elif v in null:
|
| 819 |
+
v = None
|
| 820 |
+
else:
|
| 821 |
+
v = (vv or default for vv in v.split(separator))
|
| 822 |
+
v = [None if vv in null else vv for vv in v]
|
| 823 |
+
elif v in null:
|
| 824 |
+
v = None
|
| 825 |
+
|
| 826 |
+
if datatype:
|
| 827 |
+
if isinstance(v, list):
|
| 828 |
+
try:
|
| 829 |
+
return [datatype.read(vv) for vv in v]
|
| 830 |
+
except ValueError:
|
| 831 |
+
if not strict:
|
| 832 |
+
warnings.warn('Invalid value for list element.')
|
| 833 |
+
return v
|
| 834 |
+
raise
|
| 835 |
+
return datatype.read(v)
|
| 836 |
+
return v
|
| 837 |
+
|
| 838 |
+
def write(self, v):
|
| 839 |
+
sep = self.inherit('separator')
|
| 840 |
+
null = self.inherit_null()
|
| 841 |
+
datatype = self.inherit('datatype')
|
| 842 |
+
|
| 843 |
+
def fmt(v):
|
| 844 |
+
if v is None:
|
| 845 |
+
return null[0]
|
| 846 |
+
if datatype:
|
| 847 |
+
return datatype.formatted(v)
|
| 848 |
+
return v
|
| 849 |
+
|
| 850 |
+
if sep:
|
| 851 |
+
return sep.join(fmt(vv) for vv in v or [])
|
| 852 |
+
return fmt(v)
|
| 853 |
+
|
| 854 |
+
|
| 855 |
+
def column_reference():
|
| 856 |
+
return attr.ib(
|
| 857 |
+
default=None,
|
| 858 |
+
validator=attr.validators.optional(attr.validators.instance_of(list)),
|
| 859 |
+
converter=lambda v: v if isinstance(v, list) or v is None else [v])
|
| 860 |
+
|
| 861 |
+
|
| 862 |
+
@attr.s
|
| 863 |
+
class Reference:
|
| 864 |
+
|
| 865 |
+
resource = link_property()
|
| 866 |
+
schemaReference = link_property()
|
| 867 |
+
columnReference = column_reference()
|
| 868 |
+
|
| 869 |
+
def __attrs_post_init__(self):
|
| 870 |
+
if self.resource is not None and self.schemaReference is not None:
|
| 871 |
+
raise ValueError(self)
|
| 872 |
+
|
| 873 |
+
|
| 874 |
+
@attr.s
|
| 875 |
+
class ForeignKey:
|
| 876 |
+
|
| 877 |
+
columnReference = column_reference()
|
| 878 |
+
reference = attr.ib(default=None)
|
| 879 |
+
|
| 880 |
+
@classmethod
|
| 881 |
+
def fromdict(cls, d):
|
| 882 |
+
if isinstance(d, dict):
|
| 883 |
+
try:
|
| 884 |
+
_ = Reference(**d['reference'])
|
| 885 |
+
except TypeError:
|
| 886 |
+
raise ValueError('Invalid reference property')
|
| 887 |
+
if not set(d.keys()).issubset({'columnReference', 'reference'}):
|
| 888 |
+
raise ValueError('Invalid foreignKey spec')
|
| 889 |
+
kw = dict(d, reference=Reference(**d['reference']))
|
| 890 |
+
return cls(**kw)
|
| 891 |
+
|
| 892 |
+
def asdict(self, **kw):
|
| 893 |
+
res = utils.attr_asdict(self, **kw)
|
| 894 |
+
res['reference'] = utils.attr_asdict(res['reference'], **kw)
|
| 895 |
+
return res
|
| 896 |
+
|
| 897 |
+
|
| 898 |
+
def converter_foreignKeys(v):
|
| 899 |
+
res = []
|
| 900 |
+
for d in functools.partial(utils.converter, dict, None)(v):
|
| 901 |
+
try:
|
| 902 |
+
res.append(ForeignKey.fromdict(d))
|
| 903 |
+
except TypeError:
|
| 904 |
+
warnings.warn('Invalid foreignKeys spec')
|
| 905 |
+
return res
|
| 906 |
+
|
| 907 |
+
|
| 908 |
+
@attr.s
|
| 909 |
+
class Schema(Description):
|
| 910 |
+
"""
|
| 911 |
+
A schema description is an object that encodes the information about a schema, which describes
|
| 912 |
+
the structure of a table.
|
| 913 |
+
|
| 914 |
+
:ivar columns: `list` of :class:`Column` descriptions.
|
| 915 |
+
:ivar foreignKeys: `list` of :class:`ForeignKey` descriptions.
|
| 916 |
+
|
| 917 |
+
.. seealso:: `<https://www.w3.org/TR/tabular-metadata/#schemas>`_
|
| 918 |
+
"""
|
| 919 |
+
columns = attr.ib(
|
| 920 |
+
default=attr.Factory(list),
|
| 921 |
+
converter=lambda v: [
|
| 922 |
+
Column.fromvalue(c) for c in functools.partial(utils.converter, dict, None)(
|
| 923 |
+
functools.partial(utils.converter, list, [])(v))])
|
| 924 |
+
foreignKeys = attr.ib(
|
| 925 |
+
default=attr.Factory(list),
|
| 926 |
+
converter=lambda v: [] if v is None else converter_foreignKeys(v))
|
| 927 |
+
primaryKey = column_reference()
|
| 928 |
+
rowTitles = attr.ib(
|
| 929 |
+
default=attr.Factory(list),
|
| 930 |
+
converter=lambda v: v if isinstance(v, list) else [v],
|
| 931 |
+
)
|
| 932 |
+
|
| 933 |
+
def __attrs_post_init__(self):
|
| 934 |
+
virtual, seen, names = False, set(), set()
|
| 935 |
+
for i, col in enumerate(self.columns):
|
| 936 |
+
if col.name and (col.name.startswith('_') or re.search(r'\s', col.name)):
|
| 937 |
+
warnings.warn('Invalid column name')
|
| 938 |
+
if col.virtual: # first virtual column sets the flag
|
| 939 |
+
virtual = True
|
| 940 |
+
elif virtual: # non-virtual column after virtual column!
|
| 941 |
+
raise ValueError('no non-virtual column allowed after virtual columns')
|
| 942 |
+
if not virtual:
|
| 943 |
+
if col.header in seen:
|
| 944 |
+
warnings.warn('Duplicate column name!')
|
| 945 |
+
if col.name:
|
| 946 |
+
if col.name in names:
|
| 947 |
+
raise ValueError('Duplicate column name {}'.format(col.name))
|
| 948 |
+
names.add(col.name)
|
| 949 |
+
seen.add(col.header)
|
| 950 |
+
col._parent = self
|
| 951 |
+
col._number = i + 1
|
| 952 |
+
for colref in self.primaryKey or []:
|
| 953 |
+
col = self.columndict.get(colref)
|
| 954 |
+
if col and not col.name:
|
| 955 |
+
warnings.warn('A primaryKey referenced column MUST have a `name` property')
|
| 956 |
+
self.primaryKey = None
|
| 957 |
+
|
| 958 |
+
@classmethod
|
| 959 |
+
def fromvalue(cls, v):
|
| 960 |
+
if isinstance(v, str):
|
| 961 |
+
try:
|
| 962 |
+
# The schema is referenced with a URL
|
| 963 |
+
v = requests.get(v).json()
|
| 964 |
+
except: # pragma: no cover # noqa: E722
|
| 965 |
+
return v
|
| 966 |
+
if not isinstance(v, dict):
|
| 967 |
+
if isinstance(v, int):
|
| 968 |
+
warnings.warn('Invalid value for tableSchema property')
|
| 969 |
+
v = {}
|
| 970 |
+
return cls(**cls.partition_properties(v))
|
| 971 |
+
|
| 972 |
+
@property
|
| 973 |
+
def columndict(self):
|
| 974 |
+
return {c.header: c for c in self.columns}
|
| 975 |
+
|
| 976 |
+
def get_column(self, name, strict=False):
|
| 977 |
+
col = self.columndict.get(name)
|
| 978 |
+
assert (not strict) or (col and col.name)
|
| 979 |
+
if not col:
|
| 980 |
+
for c in self.columns:
|
| 981 |
+
if c.titles and c.titles.getfirst() == name:
|
| 982 |
+
return c
|
| 983 |
+
if c.propertyUrl and c.propertyUrl.uri == name:
|
| 984 |
+
return c
|
| 985 |
+
return col
|
| 986 |
+
|
| 987 |
+
|
| 988 |
+
def dialect_props(d):
|
| 989 |
+
if not isinstance(d, dict):
|
| 990 |
+
warnings.warn('Invalid dialect spec')
|
| 991 |
+
return {}
|
| 992 |
+
partitioned = Description.partition_properties(d, type_name='Dialect', strict=False)
|
| 993 |
+
del partitioned['at_props']
|
| 994 |
+
del partitioned['common_props']
|
| 995 |
+
if partitioned.get('headerRowCount'):
|
| 996 |
+
partitioned['header'] = True
|
| 997 |
+
return partitioned
|
| 998 |
+
|
| 999 |
+
|
| 1000 |
+
def valid_transformations(instance, attribute, value):
|
| 1001 |
+
if not isinstance(value, list):
|
| 1002 |
+
warnings.warn('Invalid transformations property')
|
| 1003 |
+
for tr in value:
|
| 1004 |
+
Description.partition_properties(tr, type_name='Template')
|
| 1005 |
+
|
| 1006 |
+
|
| 1007 |
+
@attr.s
|
| 1008 |
+
class TableLike(Description):
|
| 1009 |
+
"""
|
| 1010 |
+
A CSVW description object as encountered "in the wild", i.e. identified by URL on the web or
|
| 1011 |
+
as file on disk.
|
| 1012 |
+
|
| 1013 |
+
Since `TableLike` objects may be instantiated from "externally referenced" objects
|
| 1014 |
+
(via file paths or URLs), they have the necessary means to resolve
|
| 1015 |
+
`link properties <https://www.w3.org/TR/tabular-metadata/#link-properties>`_
|
| 1016 |
+
|
| 1017 |
+
.. code-block:: python
|
| 1018 |
+
|
| 1019 |
+
>>> from csvw import Table, TableGroup, Link
|
| 1020 |
+
>>> t = Table.from_file('tests/fixtures/csv.txt-table-metadata.json')
|
| 1021 |
+
>>> Link('abc.txt').resolve(t.base)
|
| 1022 |
+
PosixPath('tests/fixtures/abc.txt')
|
| 1023 |
+
>>> tg = TableGroup.from_url(
|
| 1024 |
+
... 'https://raw.githubusercontent.com/cldf/csvw/master/tests/fixtures/'
|
| 1025 |
+
... 'csv.txt-metadata.json')
|
| 1026 |
+
>>> str(tg.tables[0].url)
|
| 1027 |
+
'csv.txt'
|
| 1028 |
+
>>> tg.tables[0].url.resolve(tg.base)
|
| 1029 |
+
'https://raw.githubusercontent.com/cldf/csvw/master/tests/fixtures/csv.txt'
|
| 1030 |
+
|
| 1031 |
+
and `URI template properties <https://www.w3.org/TR/tabular-metadata/#uri-template-properties>`_
|
| 1032 |
+
(see :meth:`~TableLike.expand`).
|
| 1033 |
+
"""
|
| 1034 |
+
dialect = attr.ib(
|
| 1035 |
+
default=None,
|
| 1036 |
+
converter=lambda v: v if (v is None or isinstance(v, str))
|
| 1037 |
+
else Dialect(**dialect_props(v)))
|
| 1038 |
+
notes = attr.ib(default=attr.Factory(list))
|
| 1039 |
+
tableDirection = attr.ib(
|
| 1040 |
+
default='auto',
|
| 1041 |
+
converter=functools.partial(
|
| 1042 |
+
utils.converter, str, 'auto', cond=lambda s: s in ['rtl', 'ltr', 'auto']),
|
| 1043 |
+
validator=attr.validators.in_(['rtl', 'ltr', 'auto']))
|
| 1044 |
+
tableSchema = attr.ib(
|
| 1045 |
+
default=None,
|
| 1046 |
+
converter=lambda v: Schema.fromvalue(v))
|
| 1047 |
+
transformations = attr.ib(
|
| 1048 |
+
validator=valid_transformations,
|
| 1049 |
+
default=attr.Factory(list),
|
| 1050 |
+
)
|
| 1051 |
+
url = link_property()
|
| 1052 |
+
_fname = attr.ib(default=None) # The path of the metadata file.
|
| 1053 |
+
|
| 1054 |
+
def __attrs_post_init__(self):
|
| 1055 |
+
if isinstance(self.dialect, str):
|
| 1056 |
+
self.dialect = Dialect(**dialect_props(get_json(Link(self.dialect).resolve(self.base))))
|
| 1057 |
+
if self.tableSchema and not (isinstance(self.tableSchema, str)):
|
| 1058 |
+
self.tableSchema._parent = self
|
| 1059 |
+
if 'id' in self.at_props and self.at_props['id'] is None:
|
| 1060 |
+
self.at_props['id'] = self.base
|
| 1061 |
+
ctx = self.at_props.get('context')
|
| 1062 |
+
if isinstance(ctx, list):
|
| 1063 |
+
for obj in ctx:
|
| 1064 |
+
if (isinstance(obj, dict) and not set(obj.keys()).issubset({'@base', '@language'}))\
|
| 1065 |
+
or (isinstance(obj, str) and obj != 'http://www.w3.org/ns/csvw'):
|
| 1066 |
+
raise ValueError(
|
| 1067 |
+
'The @context MUST have one of the following values: An array composed '
|
| 1068 |
+
'of a string followed by an object, where the string is '
|
| 1069 |
+
'http://www.w3.org/ns/csvw and the object represents a local context '
|
| 1070 |
+
'definition, which is restricted to contain either or both of'
|
| 1071 |
+
'@base and @language.')
|
| 1072 |
+
if isinstance(obj, dict) and '@language' in obj:
|
| 1073 |
+
if not tags.check(obj['@language']):
|
| 1074 |
+
warnings.warn('Invalid value for @language property')
|
| 1075 |
+
del obj['@language']
|
| 1076 |
+
|
| 1077 |
+
def get_column(self, spec):
|
| 1078 |
+
return self.tableSchema.get_column(spec) if self.tableSchema else None
|
| 1079 |
+
|
| 1080 |
+
@classmethod
|
| 1081 |
+
def from_file(cls, fname: typing.Union[str, pathlib.Path], data=None) -> 'TableLike':
|
| 1082 |
+
"""
|
| 1083 |
+
Instantiate a CSVW Table or TableGroup description from a metadata file.
|
| 1084 |
+
"""
|
| 1085 |
+
if is_url(str(fname)):
|
| 1086 |
+
return cls.from_url(str(fname), data=data)
|
| 1087 |
+
res = cls.fromvalue(data or get_json(fname))
|
| 1088 |
+
res._fname = pathlib.Path(fname)
|
| 1089 |
+
return res
|
| 1090 |
+
|
| 1091 |
+
@classmethod
|
| 1092 |
+
def from_url(cls, url: str, data=None) -> 'TableLike':
|
| 1093 |
+
"""
|
| 1094 |
+
Instantiate a CSVW Table or TableGroup description from a metadata file specified by URL.
|
| 1095 |
+
"""
|
| 1096 |
+
data = data or get_json(url)
|
| 1097 |
+
url = urlparse(url)
|
| 1098 |
+
data.setdefault('@base', urlunparse((url.scheme, url.netloc, url.path, '', '', '')))
|
| 1099 |
+
for table in data.get('tables', [data]):
|
| 1100 |
+
if isinstance(table, dict) and isinstance(table.get('tableSchema'), str):
|
| 1101 |
+
table['tableSchema'] = Link(table['tableSchema']).resolve(data['@base'])
|
| 1102 |
+
res = cls.fromvalue(data)
|
| 1103 |
+
return res
|
| 1104 |
+
|
| 1105 |
+
def to_file(self, fname: typing.Union[str, pathlib.Path], omit_defaults=True) -> pathlib.Path:
|
| 1106 |
+
"""
|
| 1107 |
+
Write a CSVW Table or TableGroup description as JSON object to a local file.
|
| 1108 |
+
|
| 1109 |
+
:param omit_defaults: The CSVW spec specifies defaults for most properties of most \
|
| 1110 |
+
description objects. If `omit_defaults==True`, these properties will be pruned from \
|
| 1111 |
+
the JSON object.
|
| 1112 |
+
"""
|
| 1113 |
+
fname = utils.ensure_path(fname)
|
| 1114 |
+
data = self.asdict(omit_defaults=omit_defaults)
|
| 1115 |
+
with json_open(str(fname), 'w') as f:
|
| 1116 |
+
json.dump(data, f, indent=4, separators=(',', ': '))
|
| 1117 |
+
return fname
|
| 1118 |
+
|
| 1119 |
+
@property
|
| 1120 |
+
def base(self) -> typing.Union[str, pathlib.Path]:
|
| 1121 |
+
"""
|
| 1122 |
+
The "base" to resolve relative links against.
|
| 1123 |
+
"""
|
| 1124 |
+
at_props = self._parent.at_props if self._parent else self.at_props
|
| 1125 |
+
ctxbase = None
|
| 1126 |
+
for obj in self.at_props.get('context', []):
|
| 1127 |
+
if isinstance(obj, dict) and '@base' in obj:
|
| 1128 |
+
ctxbase = obj['@base']
|
| 1129 |
+
if 'base' in at_props:
|
| 1130 |
+
if ctxbase:
|
| 1131 |
+
# If present, its value MUST be a string that is interpreted as a URL which is
|
| 1132 |
+
# resolved against the location of the metadata document to provide the
|
| 1133 |
+
# **base URL** for other URLs in the metadata document.
|
| 1134 |
+
return Link(ctxbase).resolve(at_props['base'])
|
| 1135 |
+
return at_props['base']
|
| 1136 |
+
return self._parent._fname.parent if (self._parent and self._parent._fname) else \
|
| 1137 |
+
(self._fname.parent if self._fname else None)
|
| 1138 |
+
|
| 1139 |
+
def expand(self, tmpl: URITemplate, row: dict, _row, _name=None, qname=False) -> str:
|
| 1140 |
+
"""
|
| 1141 |
+
Expand a `URITemplate` using `row`, `_row` and `_name` as context and resolving the result
|
| 1142 |
+
against `TableLike.url`.
|
| 1143 |
+
|
| 1144 |
+
.. code-block:: python
|
| 1145 |
+
|
| 1146 |
+
>>> from csvw import URITemplate, TableGroup
|
| 1147 |
+
>>> tg = TableGroup.from_url(
|
| 1148 |
+
... 'https://raw.githubusercontent.com/cldf/csvw/master/tests/fixtures/'
|
| 1149 |
+
... 'csv.txt-metadata.json')
|
| 1150 |
+
>>> tg.expand(URITemplate('/path?{a}{#b}'), dict(a='1', b='2'), None)
|
| 1151 |
+
'https://raw.githubusercontent.com/path?1#2'
|
| 1152 |
+
|
| 1153 |
+
"""
|
| 1154 |
+
if tmpl is INVALID:
|
| 1155 |
+
return self.url.resolve(self.base)
|
| 1156 |
+
|
| 1157 |
+
for prefix, url in NAMESPACES.items():
|
| 1158 |
+
if tmpl.uri.startswith(prefix + ':'):
|
| 1159 |
+
# If the URI Template is a QName, we expand it to a URL to prevent `Link.resolve`
|
| 1160 |
+
# from turning it into a local path.
|
| 1161 |
+
res = '{}{}'.format(url, tmpl.uri.split(':')[1])
|
| 1162 |
+
break
|
| 1163 |
+
else:
|
| 1164 |
+
res = Link(
|
| 1165 |
+
tmpl.expand(
|
| 1166 |
+
_row=_row,
|
| 1167 |
+
_name=_name,
|
| 1168 |
+
**{_k: _v for _k, _v in row.items() if isinstance(_k, str)}
|
| 1169 |
+
)).resolve(self.url.resolve(self.base) if self.url else self.base)
|
| 1170 |
+
if not isinstance(res, pathlib.Path):
|
| 1171 |
+
if qname:
|
| 1172 |
+
for prefix, url in NAMESPACES.items():
|
| 1173 |
+
if res.startswith(url):
|
| 1174 |
+
res = res.replace(url, prefix + ':')
|
| 1175 |
+
break
|
| 1176 |
+
return res
|
| 1177 |
+
|
| 1178 |
+
|
| 1179 |
+
@attr.s
|
| 1180 |
+
class Table(TableLike):
|
| 1181 |
+
"""
|
| 1182 |
+
A table description is an object that describes a table within a CSV file.
|
| 1183 |
+
|
| 1184 |
+
`Table` objects provide access to schema manipulation either by manipulating the `tableSchema`
|
| 1185 |
+
property directly or via higher-level methods like :meth:`~Table.add_foreign_key`
|
| 1186 |
+
|
| 1187 |
+
`Table` objects also mediate read/write access to the actual data through
|
| 1188 |
+
|
| 1189 |
+
- :meth:`~Table.write`
|
| 1190 |
+
- :meth:`~Table.iterdicts`
|
| 1191 |
+
|
| 1192 |
+
.. seealso:: `<https://www.w3.org/TR/tabular-metadata/#tables>`_
|
| 1193 |
+
"""
|
| 1194 |
+
suppressOutput = attr.ib(default=False)
|
| 1195 |
+
_comments = []
|
| 1196 |
+
|
| 1197 |
+
def add_foreign_key(self, colref, ref_resource, ref_colref):
|
| 1198 |
+
"""
|
| 1199 |
+
Add a foreign key constraint to `tableSchema.foreignKeys`.
|
| 1200 |
+
|
| 1201 |
+
:param colref: Column reference for the foreign key.
|
| 1202 |
+
:param ref_resource: Referenced table.
|
| 1203 |
+
:param ref_colref: Column reference of the key in the referenced table.
|
| 1204 |
+
"""
|
| 1205 |
+
colref = [colref] if not isinstance(colref, (tuple, list)) else colref
|
| 1206 |
+
if not all(col in [c.name for c in self.tableSchema.columns] for col in colref):
|
| 1207 |
+
raise ValueError('unknown column in foreignKey {0}'.format(colref))
|
| 1208 |
+
|
| 1209 |
+
self.tableSchema.foreignKeys.append(ForeignKey.fromdict({
|
| 1210 |
+
'columnReference': colref,
|
| 1211 |
+
'reference': {'resource': ref_resource, 'columnReference': ref_colref}
|
| 1212 |
+
}))
|
| 1213 |
+
|
| 1214 |
+
def __attrs_post_init__(self):
|
| 1215 |
+
TableLike.__attrs_post_init__(self)
|
| 1216 |
+
if not self.url:
|
| 1217 |
+
raise ValueError('url property is required for Tables')
|
| 1218 |
+
|
| 1219 |
+
@property
|
| 1220 |
+
def local_name(self) -> typing.Union[str, None]:
|
| 1221 |
+
return self.url.string if self.url else None
|
| 1222 |
+
|
| 1223 |
+
def _get_dialect(self) -> Dialect:
|
| 1224 |
+
return self.dialect or (self._parent and self._parent.dialect) or Dialect()
|
| 1225 |
+
|
| 1226 |
+
def write(self,
|
| 1227 |
+
items: typing.Iterable[typing.Union[dict, list, tuple]],
|
| 1228 |
+
fname: typing.Optional[typing.Union[str, pathlib.Path]] = DEFAULT,
|
| 1229 |
+
base: typing.Optional[typing.Union[str, pathlib.Path]] = None,
|
| 1230 |
+
strict: typing.Optional[bool] = False,
|
| 1231 |
+
_zipped: typing.Optional[bool] = False) -> typing.Union[str, int]:
|
| 1232 |
+
"""
|
| 1233 |
+
Write row items to a CSV file according to the table schema.
|
| 1234 |
+
|
| 1235 |
+
:param items: Iterator of `dict` storing the data per row.
|
| 1236 |
+
:param fname: Name of the file to which to write the data.
|
| 1237 |
+
:param base: Base directory relative to which to interpret table urls.
|
| 1238 |
+
:param strict: Flag signaling to use strict mode when writing. This will raise `ValueError`\
|
| 1239 |
+
if any row (dict) passed in `items` contains unspecified fieldnames.
|
| 1240 |
+
:param _zipped: Flag signaling whether the resulting data file should be zipped.
|
| 1241 |
+
:return: The CSV content if `fname==None` else the number of rows written.
|
| 1242 |
+
"""
|
| 1243 |
+
dialect = self._get_dialect()
|
| 1244 |
+
non_virtual_cols = [c for c in self.tableSchema.columns if not c.virtual]
|
| 1245 |
+
if fname is DEFAULT:
|
| 1246 |
+
fname = self.url.resolve(pathlib.Path(base) if base else self.base)
|
| 1247 |
+
|
| 1248 |
+
rowcount = 0
|
| 1249 |
+
with UnicodeWriter(fname, dialect=dialect) as writer:
|
| 1250 |
+
if dialect.header:
|
| 1251 |
+
writer.writerow([c.header for c in non_virtual_cols])
|
| 1252 |
+
for item in items:
|
| 1253 |
+
if isinstance(item, (list, tuple)):
|
| 1254 |
+
row = [col.write(item[i]) for i, col in enumerate(non_virtual_cols)]
|
| 1255 |
+
else:
|
| 1256 |
+
if strict:
|
| 1257 |
+
add = set(item.keys()) - {'{}'.format(col) for col in non_virtual_cols}
|
| 1258 |
+
if add:
|
| 1259 |
+
raise ValueError("dict contains fields not in fieldnames: {}".format(
|
| 1260 |
+
', '.join("'{}'".format(field) for field in add)))
|
| 1261 |
+
row = [
|
| 1262 |
+
col.write(item.get(
|
| 1263 |
+
col.header, item.get('{}'.format(col))))
|
| 1264 |
+
for col in non_virtual_cols]
|
| 1265 |
+
rowcount += 1
|
| 1266 |
+
writer.writerow(row)
|
| 1267 |
+
if fname is None:
|
| 1268 |
+
return writer.read()
|
| 1269 |
+
if fname and _zipped:
|
| 1270 |
+
fpath = pathlib.Path(fname)
|
| 1271 |
+
with zipfile.ZipFile(
|
| 1272 |
+
str(fpath.parent.joinpath(fpath.name + '.zip')),
|
| 1273 |
+
'w',
|
| 1274 |
+
compression=zipfile.ZIP_DEFLATED
|
| 1275 |
+
) as zipf:
|
| 1276 |
+
zipf.write(str(fpath), arcname=fpath.name)
|
| 1277 |
+
fpath.unlink()
|
| 1278 |
+
return rowcount
|
| 1279 |
+
|
| 1280 |
+
def check_primary_key(self, log=None, items=None) -> bool:
|
| 1281 |
+
success = True
|
| 1282 |
+
if items is not None:
|
| 1283 |
+
warnings.warn('the items argument of check_primary_key '
|
| 1284 |
+
'is deprecated (its content will be ignored)') # pragma: no cover
|
| 1285 |
+
if self.tableSchema.primaryKey:
|
| 1286 |
+
get_pk = operator.itemgetter(*self.tableSchema.primaryKey)
|
| 1287 |
+
seen = set()
|
| 1288 |
+
# Read all rows in the table, ignoring errors:
|
| 1289 |
+
for fname, lineno, row in self.iterdicts(log=nolog(), with_metadata=True):
|
| 1290 |
+
pk = get_pk(row)
|
| 1291 |
+
if pk in seen:
|
| 1292 |
+
log_or_raise(
|
| 1293 |
+
'{0}:{1} duplicate primary key: {2}'.format(fname, lineno, pk),
|
| 1294 |
+
log=log)
|
| 1295 |
+
success = False
|
| 1296 |
+
else:
|
| 1297 |
+
seen.add(pk)
|
| 1298 |
+
return success
|
| 1299 |
+
|
| 1300 |
+
def __iter__(self):
|
| 1301 |
+
return self.iterdicts()
|
| 1302 |
+
|
| 1303 |
+
def iterdicts(
|
| 1304 |
+
self,
|
| 1305 |
+
log=None,
|
| 1306 |
+
with_metadata=False,
|
| 1307 |
+
fname=None,
|
| 1308 |
+
_Row=collections.OrderedDict,
|
| 1309 |
+
strict=True,
|
| 1310 |
+
) -> typing.Generator[dict, None, None]:
|
| 1311 |
+
"""Iterate over the rows of the table
|
| 1312 |
+
|
| 1313 |
+
Create an iterator that maps the information in each row to a `dict` whose keys are
|
| 1314 |
+
the column names of the table and whose values are the values in the corresponding
|
| 1315 |
+
table cells, or for virtual columns (which have no values) the valueUrl for that
|
| 1316 |
+
column. This includes columns not specified in the table specification.
|
| 1317 |
+
|
| 1318 |
+
Note: If the resolved data filename does not exist - but there is a zip file of the form
|
| 1319 |
+
`fname+'.zip'`, we try to read the data from this file after unzipping.
|
| 1320 |
+
|
| 1321 |
+
:param log: Logger object (default None) The object that reports parsing errors.\
|
| 1322 |
+
If none is given, parsing errors raise ValueError instead.
|
| 1323 |
+
:param bool with_metadata: (default False) Also yield fname and lineno
|
| 1324 |
+
:param fname: file-like, pathlib.Path, or str (default None)\
|
| 1325 |
+
The file to be read. Defaults to inheriting from a parent object, if one exists.
|
| 1326 |
+
:param strict: Flag signaling whether data is read strictly - i.e. raising `ValueError` \
|
| 1327 |
+
when invalid data is encountered - or not - i.e. only issueing a warning and returning \
|
| 1328 |
+
invalid data as `str` as provided by the undelying DSV reader.
|
| 1329 |
+
:return: A generator of dicts or triples (fname, lineno, dict) if with_metadata
|
| 1330 |
+
"""
|
| 1331 |
+
dialect = self._get_dialect()
|
| 1332 |
+
fname = fname or self.url.resolve(self.base)
|
| 1333 |
+
colnames, virtualcols, requiredcols = [], [], set()
|
| 1334 |
+
for col in self.tableSchema.columns:
|
| 1335 |
+
if col.virtual:
|
| 1336 |
+
if col.valueUrl:
|
| 1337 |
+
virtualcols.append((col.header, col.valueUrl))
|
| 1338 |
+
else:
|
| 1339 |
+
colnames.append(col.header)
|
| 1340 |
+
if col.required:
|
| 1341 |
+
requiredcols.add(col.header)
|
| 1342 |
+
|
| 1343 |
+
with contextlib.ExitStack() as stack:
|
| 1344 |
+
if is_url(fname):
|
| 1345 |
+
handle = io.TextIOWrapper(
|
| 1346 |
+
io.BytesIO(requests.get(str(fname)).content), encoding=dialect.encoding)
|
| 1347 |
+
else:
|
| 1348 |
+
handle = fname
|
| 1349 |
+
fpath = pathlib.Path(fname)
|
| 1350 |
+
if not fpath.exists():
|
| 1351 |
+
zipfname = fpath.parent.joinpath(fpath.name + '.zip')
|
| 1352 |
+
if zipfname.exists():
|
| 1353 |
+
zipf = stack.enter_context(zipfile.ZipFile(str(zipfname)))
|
| 1354 |
+
handle = io.TextIOWrapper(
|
| 1355 |
+
zipf.open([n for n in zipf.namelist() if n.endswith(fpath.name)][0]),
|
| 1356 |
+
encoding=dialect.encoding)
|
| 1357 |
+
|
| 1358 |
+
reader = stack.enter_context(UnicodeReaderWithLineNumber(handle, dialect=dialect))
|
| 1359 |
+
reader = iter(reader)
|
| 1360 |
+
|
| 1361 |
+
# If the data file has a header row, this row overrides the header as
|
| 1362 |
+
# specified in the metadata.
|
| 1363 |
+
if dialect.header:
|
| 1364 |
+
try:
|
| 1365 |
+
_, header = next(reader)
|
| 1366 |
+
if not strict:
|
| 1367 |
+
if self.tableSchema.columns and len(self.tableSchema.columns) < len(header):
|
| 1368 |
+
warnings.warn('Column number mismatch')
|
| 1369 |
+
for name, col in zip(header, self.tableSchema.columns):
|
| 1370 |
+
res = col.has_title(name)
|
| 1371 |
+
if (not col.name) and not res:
|
| 1372 |
+
warnings.warn('Incompatible table models')
|
| 1373 |
+
if isinstance(res, str) and res.split('-')[0] not in [
|
| 1374 |
+
'und', (self.lang or 'und').split('-')[0]]:
|
| 1375 |
+
warnings.warn('Incompatible column titles')
|
| 1376 |
+
except StopIteration: # pragma: no cover
|
| 1377 |
+
return
|
| 1378 |
+
else:
|
| 1379 |
+
header = colnames
|
| 1380 |
+
|
| 1381 |
+
# If columns in the data are ordered as in the spec, we can match values to
|
| 1382 |
+
# columns by index, rather than looking up columns by name.
|
| 1383 |
+
if (header == colnames) or \
|
| 1384 |
+
(len(self.tableSchema.columns) >= len(header) and not strict):
|
| 1385 |
+
# Note that virtual columns are only allowed to come **after** regular ones,
|
| 1386 |
+
# so we can simply zip the whole columns list, and silently ignore surplus
|
| 1387 |
+
# virtual columns.
|
| 1388 |
+
header_cols = list(zip(header, self.tableSchema.columns))
|
| 1389 |
+
elif not strict and self.tableSchema.columns and \
|
| 1390 |
+
(len(self.tableSchema.columns) < len(header)):
|
| 1391 |
+
header_cols = []
|
| 1392 |
+
for i, cname in enumerate(header):
|
| 1393 |
+
try:
|
| 1394 |
+
header_cols.append((cname, self.tableSchema.columns[i]))
|
| 1395 |
+
except IndexError:
|
| 1396 |
+
header_cols.append((
|
| 1397 |
+
'_col.{}'.format(i + 1),
|
| 1398 |
+
Column.fromvalue({'name': '_col.{}'.format(i + 1)})))
|
| 1399 |
+
else:
|
| 1400 |
+
header_cols = [(h, self.tableSchema.get_column(h)) for h in header]
|
| 1401 |
+
header_cols = [(j, h, c) for j, (h, c) in enumerate(header_cols)]
|
| 1402 |
+
missing = requiredcols - set(c.header for j, h, c in header_cols if c)
|
| 1403 |
+
if missing:
|
| 1404 |
+
raise ValueError('{0} is missing required columns {1}'.format(fname, missing))
|
| 1405 |
+
|
| 1406 |
+
for lineno, row in reader:
|
| 1407 |
+
required = {h: j for j, h, c in header_cols if c and c.required}
|
| 1408 |
+
res = _Row()
|
| 1409 |
+
error = False
|
| 1410 |
+
if (not header_cols) and row:
|
| 1411 |
+
header_cols = [
|
| 1412 |
+
(i,
|
| 1413 |
+
'_col.{}'.format(i + 1),
|
| 1414 |
+
Column.fromvalue({'name': '_col.{}'.format(i + 1)}))
|
| 1415 |
+
for i, _ in enumerate(row)]
|
| 1416 |
+
for (j, k, col), v in zip(header_cols, row):
|
| 1417 |
+
# see http://w3c.github.io/csvw/syntax/#parsing-cells
|
| 1418 |
+
if col:
|
| 1419 |
+
try:
|
| 1420 |
+
res[col.header] = col.read(v, strict=strict)
|
| 1421 |
+
except ValueError as e:
|
| 1422 |
+
if not strict:
|
| 1423 |
+
warnings.warn(
|
| 1424 |
+
'Invalid column value: {} {}; {}'.format(v, col.datatype, e))
|
| 1425 |
+
res[col.header] = v
|
| 1426 |
+
else:
|
| 1427 |
+
log_or_raise(
|
| 1428 |
+
'{0}:{1}:{2} {3}: {4}'.format(fname, lineno, j + 1, k, e),
|
| 1429 |
+
log=log)
|
| 1430 |
+
error = True
|
| 1431 |
+
if k in required:
|
| 1432 |
+
del required[k]
|
| 1433 |
+
else:
|
| 1434 |
+
if strict:
|
| 1435 |
+
warnings.warn(
|
| 1436 |
+
'Unspecified column "{0}" in table {1}'.format(k, self.local_name))
|
| 1437 |
+
res[k] = v
|
| 1438 |
+
|
| 1439 |
+
for k, j in required.items():
|
| 1440 |
+
if k not in res:
|
| 1441 |
+
log_or_raise(
|
| 1442 |
+
'{0}:{1}:{2} {3}: {4}'.format(
|
| 1443 |
+
fname, lineno, j + 1, k, 'required column value is missing'),
|
| 1444 |
+
log=log)
|
| 1445 |
+
error = True
|
| 1446 |
+
|
| 1447 |
+
# Augment result with regular columns not provided in the data:
|
| 1448 |
+
for key in colnames:
|
| 1449 |
+
res.setdefault(key, None)
|
| 1450 |
+
|
| 1451 |
+
# Augment result with virtual columns:
|
| 1452 |
+
for key, valueUrl in virtualcols:
|
| 1453 |
+
res[key] = valueUrl.expand(**res)
|
| 1454 |
+
|
| 1455 |
+
if not error:
|
| 1456 |
+
if with_metadata:
|
| 1457 |
+
yield fname, lineno, res
|
| 1458 |
+
else:
|
| 1459 |
+
yield res
|
| 1460 |
+
self._comments = reader.comments
|
| 1461 |
+
|
| 1462 |
+
|
| 1463 |
+
def converter_tables(v):
|
| 1464 |
+
res = []
|
| 1465 |
+
for vv in v:
|
| 1466 |
+
if not isinstance(vv, (dict, Table)):
|
| 1467 |
+
warnings.warn('Invalid value for Table spec')
|
| 1468 |
+
else:
|
| 1469 |
+
res.append(Table.fromvalue(vv) if isinstance(vv, dict) else vv)
|
| 1470 |
+
return res
|
| 1471 |
+
|
| 1472 |
+
|
| 1473 |
+
@attr.s
|
| 1474 |
+
class TableGroup(TableLike):
|
| 1475 |
+
"""
|
| 1476 |
+
A table group description is an object that describes a group of tables.
|
| 1477 |
+
|
| 1478 |
+
A `TableGroup` delegates most of its responsibilities to the `Table` objects listed in its
|
| 1479 |
+
`tables` property. For convenience, `TableGroup` provides methods to
|
| 1480 |
+
- read data from all tables: :meth:`TableGroup.read`
|
| 1481 |
+
- write data for all tables: :meth:`TableGroup.write`
|
| 1482 |
+
|
| 1483 |
+
It also provides a method to check the referential integrity of data in related tables via
|
| 1484 |
+
:meth:`TableGroup.check_referential_integrity`
|
| 1485 |
+
|
| 1486 |
+
.. seealso:: `<https://www.w3.org/TR/tabular-metadata/#table-groups>`_
|
| 1487 |
+
"""
|
| 1488 |
+
tables = attr.ib(repr=False, default=attr.Factory(list), converter=converter_tables)
|
| 1489 |
+
|
| 1490 |
+
def __attrs_post_init__(self):
|
| 1491 |
+
TableLike.__attrs_post_init__(self)
|
| 1492 |
+
for table in self.tables:
|
| 1493 |
+
table._parent = self
|
| 1494 |
+
|
| 1495 |
+
@classmethod
|
| 1496 |
+
def from_frictionless_datapackage(cls, dp):
|
| 1497 |
+
return DataPackage(dp).to_tablegroup(cls)
|
| 1498 |
+
|
| 1499 |
+
def read(self):
|
| 1500 |
+
"""
|
| 1501 |
+
Read all data of a TableGroup
|
| 1502 |
+
"""
|
| 1503 |
+
return {tname: list(t.iterdicts()) for tname, t in self.tabledict.items()}
|
| 1504 |
+
|
| 1505 |
+
def write(self,
|
| 1506 |
+
fname: typing.Union[str, pathlib.Path],
|
| 1507 |
+
strict: typing.Optional[bool] = False,
|
| 1508 |
+
_zipped: typing.Optional[bool] = False,
|
| 1509 |
+
**items: typing.Iterable[typing.Union[list, tuple, dict]]):
|
| 1510 |
+
"""
|
| 1511 |
+
Write a TableGroup's data and metadata to files.
|
| 1512 |
+
|
| 1513 |
+
:param fname: Filename for the metadata file.
|
| 1514 |
+
:param items: Keyword arguments are used to pass iterables of rows per table, where the \
|
| 1515 |
+
table URL is specified as keyword.
|
| 1516 |
+
"""
|
| 1517 |
+
fname = pathlib.Path(fname)
|
| 1518 |
+
for tname, rows in items.items():
|
| 1519 |
+
self.tabledict[tname].write(rows, base=fname.parent, strict=strict, _zipped=_zipped)
|
| 1520 |
+
self.to_file(fname)
|
| 1521 |
+
|
| 1522 |
+
def copy(self, dest: typing.Union[pathlib.Path, str]):
|
| 1523 |
+
"""
|
| 1524 |
+
Write a TableGroup's data and metadata to files relative to `dest`, adapting the `base`
|
| 1525 |
+
attribute.
|
| 1526 |
+
|
| 1527 |
+
:param dest:
|
| 1528 |
+
:return:
|
| 1529 |
+
"""
|
| 1530 |
+
dest = pathlib.Path(dest)
|
| 1531 |
+
for table in self.tables:
|
| 1532 |
+
shutil.copy(str(table.url.resolve(self.base)), str(table.url.resolve(dest)))
|
| 1533 |
+
self._fname = dest / self._fname.name
|
| 1534 |
+
self.to_file(self._fname)
|
| 1535 |
+
|
| 1536 |
+
@property
|
| 1537 |
+
def tabledict(self) -> typing.Dict[str, Table]:
|
| 1538 |
+
return {t.local_name: t for t in self.tables}
|
| 1539 |
+
|
| 1540 |
+
def foreign_keys(self) -> typing.List[typing.Tuple[Table, list, Table, list]]:
|
| 1541 |
+
return [
|
| 1542 |
+
(
|
| 1543 |
+
self.tabledict[fk.reference.resource.string],
|
| 1544 |
+
fk.reference.columnReference,
|
| 1545 |
+
t,
|
| 1546 |
+
fk.columnReference)
|
| 1547 |
+
for t in self.tables for fk in t.tableSchema.foreignKeys
|
| 1548 |
+
if not fk.reference.schemaReference]
|
| 1549 |
+
|
| 1550 |
+
def validate_schema(self, strict=False):
|
| 1551 |
+
try:
|
| 1552 |
+
for st, sc, tt, tc in self.foreign_keys():
|
| 1553 |
+
if len(sc) != len(tc):
|
| 1554 |
+
raise ValueError(
|
| 1555 |
+
'Foreign key error: non-matching number of columns in source and target')
|
| 1556 |
+
for scol, tcol in zip(sc, tc):
|
| 1557 |
+
scolumn = st.tableSchema.get_column(scol, strict=strict)
|
| 1558 |
+
tcolumn = tt.tableSchema.get_column(tcol, strict=strict)
|
| 1559 |
+
if not (scolumn and tcolumn):
|
| 1560 |
+
raise ValueError(
|
| 1561 |
+
'Foregin key error: missing column "{}" or "{}"'.format(scol, tcol))
|
| 1562 |
+
if scolumn.datatype and tcolumn.datatype and \
|
| 1563 |
+
scolumn.datatype.base != tcolumn.datatype.base:
|
| 1564 |
+
raise ValueError(
|
| 1565 |
+
'Foregin key error: non-matching datatype "{}:{}" or "{}:{}"'.format(
|
| 1566 |
+
scol, scolumn.datatype.base, tcol, tcolumn.datatype.base))
|
| 1567 |
+
except (KeyError, AssertionError) as e:
|
| 1568 |
+
raise ValueError('Foreign key error: missing table "{}" referenced'.format(e))
|
| 1569 |
+
|
| 1570 |
+
def check_referential_integrity(self, data=None, log=None, strict=False):
|
| 1571 |
+
"""
|
| 1572 |
+
Strict validation does not allow for nullable foreign key columns.
|
| 1573 |
+
"""
|
| 1574 |
+
if data is not None:
|
| 1575 |
+
warnings.warn('the data argument of check_referential_integrity '
|
| 1576 |
+
'is deprecated (its content will be ignored)') # pragma: no cover
|
| 1577 |
+
if strict:
|
| 1578 |
+
for t in self.tables:
|
| 1579 |
+
for fk in t.tableSchema.foreignKeys:
|
| 1580 |
+
for row in t:
|
| 1581 |
+
if any(row.get(col) is None for col in fk.columnReference):
|
| 1582 |
+
raise ValueError('Foreign key column is null: {} {}'.format(
|
| 1583 |
+
[row.get(col) for col in fk.columnReference], fk.columnReference))
|
| 1584 |
+
try:
|
| 1585 |
+
self.validate_schema()
|
| 1586 |
+
success = True
|
| 1587 |
+
except ValueError as e:
|
| 1588 |
+
success = False
|
| 1589 |
+
log_or_raise(str(e), log=log, level='error')
|
| 1590 |
+
fkeys = self.foreign_keys()
|
| 1591 |
+
# FIXME: We only support Foreign Key references between tables!
|
| 1592 |
+
fkeys = sorted(fkeys, key=lambda x: (x[0].local_name, x[1], x[2].local_name))
|
| 1593 |
+
# Grouping by local_name of tables - even though we'd like to have the table objects
|
| 1594 |
+
# around, too. This it to prevent going down the rabbit hole of comparing table objects
|
| 1595 |
+
# for equality, when comparison of the string names is enough.
|
| 1596 |
+
for _, grp in itertools.groupby(fkeys, lambda x: x[0].local_name):
|
| 1597 |
+
grp = list(grp)
|
| 1598 |
+
table = grp[0][0]
|
| 1599 |
+
t_fkeys = [(key, [(child, ref) for _, _, child, ref in kgrp])
|
| 1600 |
+
for key, kgrp in itertools.groupby(grp, lambda x: x[1])]
|
| 1601 |
+
get_seen = [(operator.itemgetter(*key), set()) for key, _ in t_fkeys]
|
| 1602 |
+
for row in table.iterdicts(log=log):
|
| 1603 |
+
for get, seen in get_seen:
|
| 1604 |
+
if get(row) in seen:
|
| 1605 |
+
# column references for a foreign key are not unique!
|
| 1606 |
+
if strict:
|
| 1607 |
+
success = False
|
| 1608 |
+
seen.add(get(row))
|
| 1609 |
+
for (key, children), (_, seen) in zip(t_fkeys, get_seen):
|
| 1610 |
+
single_column = (len(key) == 1)
|
| 1611 |
+
for child, ref in children:
|
| 1612 |
+
get_ref = operator.itemgetter(*ref)
|
| 1613 |
+
for fname, lineno, item in child.iterdicts(log=log, with_metadata=True):
|
| 1614 |
+
colref = get_ref(item)
|
| 1615 |
+
if colref is None:
|
| 1616 |
+
continue
|
| 1617 |
+
elif single_column and isinstance(colref, list):
|
| 1618 |
+
# We allow list-valued columns as foreign key columns in case
|
| 1619 |
+
# it's not a composite key. If a foreign key is list-valued, we
|
| 1620 |
+
# check for a matching row for each of the values in the list.
|
| 1621 |
+
colrefs = colref
|
| 1622 |
+
else:
|
| 1623 |
+
colrefs = [colref]
|
| 1624 |
+
for colref in colrefs:
|
| 1625 |
+
if not single_column and None in colref: # pragma: no cover
|
| 1626 |
+
# TODO: raise if any(c is not None for c in colref)?
|
| 1627 |
+
continue
|
| 1628 |
+
elif colref not in seen:
|
| 1629 |
+
log_or_raise(
|
| 1630 |
+
'{0}:{1} Key `{2}` not found in table {3}'.format(
|
| 1631 |
+
fname,
|
| 1632 |
+
lineno,
|
| 1633 |
+
colref,
|
| 1634 |
+
table.url.string),
|
| 1635 |
+
log=log)
|
| 1636 |
+
success = False
|
| 1637 |
+
return success
|
| 1638 |
+
|
| 1639 |
+
|
| 1640 |
+
class CSVW:
|
| 1641 |
+
"""
|
| 1642 |
+
Python API to read CSVW described data and convert it to JSON.
|
| 1643 |
+
"""
|
| 1644 |
+
def __init__(self, url: str, md_url: typing.Optional[str] = None, validate: bool = False):
|
| 1645 |
+
self.warnings = []
|
| 1646 |
+
w = None
|
| 1647 |
+
with contextlib.ExitStack() as stack:
|
| 1648 |
+
if validate:
|
| 1649 |
+
w = stack.enter_context(warnings.catch_warnings(record=True))
|
| 1650 |
+
|
| 1651 |
+
no_header = False
|
| 1652 |
+
try:
|
| 1653 |
+
md = get_json(md_url or url)
|
| 1654 |
+
# The URL could be read as JSON document, thus, the user supplied us with overriding
|
| 1655 |
+
# metadata as per https://w3c.github.io/csvw/syntax/#overriding-metadata
|
| 1656 |
+
except json.decoder.JSONDecodeError:
|
| 1657 |
+
# So we got a CSV file, no JSON. Let's locate metadata using the other methods.
|
| 1658 |
+
md, no_header = self.locate_metadata(url)
|
| 1659 |
+
|
| 1660 |
+
self.no_metadata = set(md.keys()) == {'@context', 'url'}
|
| 1661 |
+
if "http://www.w3.org/ns/csvw" not in md.get('@context', ''):
|
| 1662 |
+
raise ValueError('Invalid or no @context')
|
| 1663 |
+
if 'tables' in md:
|
| 1664 |
+
if not md['tables'] or not isinstance(md['tables'], list):
|
| 1665 |
+
raise ValueError('Invalid TableGroup with empty tables property')
|
| 1666 |
+
if is_url(url):
|
| 1667 |
+
self.t = TableGroup.from_url(url, data=md)
|
| 1668 |
+
self.t.validate_schema(strict=True)
|
| 1669 |
+
else:
|
| 1670 |
+
self.t = TableGroup.from_file(url, data=md)
|
| 1671 |
+
else:
|
| 1672 |
+
if is_url(url):
|
| 1673 |
+
self.t = Table.from_url(url, data=md)
|
| 1674 |
+
if no_header:
|
| 1675 |
+
if self.t.dialect:
|
| 1676 |
+
self.t.dialect.header = False # pragma: no cover
|
| 1677 |
+
else:
|
| 1678 |
+
self.t.dialect = Dialect(header=False)
|
| 1679 |
+
else:
|
| 1680 |
+
self.t = Table.from_file(url, data=md)
|
| 1681 |
+
self.tables = self.t.tables if isinstance(self.t, TableGroup) else [self.t]
|
| 1682 |
+
for table in self.tables:
|
| 1683 |
+
for col in table.tableSchema.columns:
|
| 1684 |
+
if col.name and (re.search(r'\s', col.name) or col.name.startswith('_')):
|
| 1685 |
+
col.name = None
|
| 1686 |
+
self.common_props = self.t.common_props
|
| 1687 |
+
if w:
|
| 1688 |
+
self.warnings.extend(w)
|
| 1689 |
+
|
| 1690 |
+
@property
|
| 1691 |
+
def is_valid(self) -> bool:
|
| 1692 |
+
"""
|
| 1693 |
+
Performs CSVW validation.
|
| 1694 |
+
|
| 1695 |
+
.. note::
|
| 1696 |
+
|
| 1697 |
+
For this to also catch problems during metadata location, the
|
| 1698 |
+
`CSVW` instance must be initialized with `validate=True`.
|
| 1699 |
+
"""
|
| 1700 |
+
if self.warnings:
|
| 1701 |
+
return False
|
| 1702 |
+
with warnings.catch_warnings(record=True) as w:
|
| 1703 |
+
for table in self.tables:
|
| 1704 |
+
for _ in table.iterdicts(strict=False):
|
| 1705 |
+
pass
|
| 1706 |
+
if not table.check_primary_key(): # pragma: no cover
|
| 1707 |
+
warnings.warn('Duplicate primary key')
|
| 1708 |
+
if not self.tablegroup.check_referential_integrity(strict=True):
|
| 1709 |
+
warnings.warn('Referential integrity check failed')
|
| 1710 |
+
if w:
|
| 1711 |
+
self.warnings.extend(w)
|
| 1712 |
+
return not bool(self.warnings)
|
| 1713 |
+
|
| 1714 |
+
@property
|
| 1715 |
+
def tablegroup(self):
|
| 1716 |
+
return self.t if isinstance(self.t, TableGroup) else \
|
| 1717 |
+
TableGroup(at_props={'base': self.t.base}, tables=self.tables)
|
| 1718 |
+
|
| 1719 |
+
@staticmethod
|
| 1720 |
+
def locate_metadata(url=None) -> typing.Tuple[dict, bool]:
|
| 1721 |
+
"""
|
| 1722 |
+
Implements metadata discovery as specified in
|
| 1723 |
+
`§5. Locating Metadata <https://w3c.github.io/csvw/syntax/#locating-metadata>`_
|
| 1724 |
+
"""
|
| 1725 |
+
def describes(md, url):
|
| 1726 |
+
for table in md.get('tables', [md]):
|
| 1727 |
+
# FIXME: We check whether the metadata describes a CSV file just superficially,
|
| 1728 |
+
# by comparing the last path components of the respective URLs.
|
| 1729 |
+
if url.split('/')[-1] == table['url'].split('/')[-1]:
|
| 1730 |
+
return True
|
| 1731 |
+
return False
|
| 1732 |
+
|
| 1733 |
+
no_header = False
|
| 1734 |
+
if url and is_url(url):
|
| 1735 |
+
# §5.2 Link Header
|
| 1736 |
+
# https://w3c.github.io/csvw/syntax/#link-header
|
| 1737 |
+
res = requests.head(url)
|
| 1738 |
+
no_header = bool(re.search(r'header\s*=\s*absent', res.headers.get('content-type', '')))
|
| 1739 |
+
desc = res.links.get('describedby')
|
| 1740 |
+
if desc and desc['type'] in [
|
| 1741 |
+
"application/csvm+json", "application/ld+json", "application/json"]:
|
| 1742 |
+
md = get_json(Link(desc['url']).resolve(url))
|
| 1743 |
+
if describes(md, url):
|
| 1744 |
+
return md, no_header
|
| 1745 |
+
else:
|
| 1746 |
+
warnings.warn('Ignoring linked metadata because it does not reference the data')
|
| 1747 |
+
|
| 1748 |
+
# §5.3 Default Locations and Site-wide Location Configuration
|
| 1749 |
+
# https://w3c.github.io/csvw/syntax/
|
| 1750 |
+
# #default-locations-and-site-wide-location-configuration
|
| 1751 |
+
res = requests.get(Link('/.well-known/csvm').resolve(url))
|
| 1752 |
+
locs = res.text if res.status_code == 200 else '{+url}-metadata.json\ncsv-metadata.json'
|
| 1753 |
+
for line in locs.split('\n'):
|
| 1754 |
+
res = requests.get(Link(URITemplate(line).expand(url=url)).resolve(url))
|
| 1755 |
+
if res.status_code == 200:
|
| 1756 |
+
try:
|
| 1757 |
+
md = res.json()
|
| 1758 |
+
if describes(md, url):
|
| 1759 |
+
return md, no_header
|
| 1760 |
+
warnings.warn('Ignoring metadata because it does not reference the data')
|
| 1761 |
+
except json.JSONDecodeError:
|
| 1762 |
+
pass
|
| 1763 |
+
|
| 1764 |
+
# §5.4 Embedded Metadata
|
| 1765 |
+
# https://w3c.github.io/csvw/syntax/#embedded-metadata
|
| 1766 |
+
# We only recognize column names read from the first row of a CSV file.
|
| 1767 |
+
elif url:
|
| 1768 |
+
# Default Locations for local files:
|
| 1769 |
+
if pathlib.Path(str(url) + '-metadata.json').exists():
|
| 1770 |
+
return get_json(pathlib.Path(str(url) + '-metadata.json')), no_header
|
| 1771 |
+
res = {
|
| 1772 |
+
'@context': "http://www.w3.org/ns/csvw",
|
| 1773 |
+
'url': url,
|
| 1774 |
+
}
|
| 1775 |
+
if not is_url(url or ''):
|
| 1776 |
+
# No metadata detected for a local CSV file. To make table reading work, we set the
|
| 1777 |
+
# directory as @base and the filename as url property of the description.
|
| 1778 |
+
p = pathlib.Path(url)
|
| 1779 |
+
res['@base'] = str(p)
|
| 1780 |
+
res['url'] = p.name
|
| 1781 |
+
return res, no_header
|
| 1782 |
+
|
| 1783 |
+
def to_json(self, minimal=False):
|
| 1784 |
+
"""
|
| 1785 |
+
Implements algorithm described in `<https://w3c.github.io/csvw/csv2json/#standard-mode>`_
|
| 1786 |
+
"""
|
| 1787 |
+
res = collections.OrderedDict()
|
| 1788 |
+
# Insert any notes and non-core annotations specified for the group of tables into object
|
| 1789 |
+
# G according to the rules provided in § 5. JSON-LD to JSON.
|
| 1790 |
+
if self.t.common_props and not isinstance(self.t, Table):
|
| 1791 |
+
res.update(jsonld.to_json(self.t.common_props, flatten_list=True))
|
| 1792 |
+
res['tables'] = [
|
| 1793 |
+
self._table_to_json(table) for table in self.tables if not table.suppressOutput]
|
| 1794 |
+
if minimal:
|
| 1795 |
+
return list(
|
| 1796 |
+
itertools.chain(*[[r['describes'][0] for r in t['row']] for t in res['tables']]))
|
| 1797 |
+
|
| 1798 |
+
return res
|
| 1799 |
+
|
| 1800 |
+
def _table_to_json(self, table):
|
| 1801 |
+
res = collections.OrderedDict()
|
| 1802 |
+
# FIXME: id
|
| 1803 |
+
res['url'] = str(table.url.resolve(table.base))
|
| 1804 |
+
if 'id' in table.at_props:
|
| 1805 |
+
res['@id'] = table.at_props['id']
|
| 1806 |
+
if table.notes:
|
| 1807 |
+
res['notes'] = jsonld.to_json(table.notes)
|
| 1808 |
+
# Insert any notes and non-core annotations specified for the group of tables into object
|
| 1809 |
+
# G according to the rules provided in § 5. JSON-LD to JSON.
|
| 1810 |
+
res.update(jsonld.to_json(table.common_props))
|
| 1811 |
+
|
| 1812 |
+
cols = collections.OrderedDict([(col.header, col) for col in table.tableSchema.columns])
|
| 1813 |
+
for col in cols.values():
|
| 1814 |
+
col.propertyUrl = col.inherit('propertyUrl')
|
| 1815 |
+
col.valueUrl = col.inherit('valueUrl')
|
| 1816 |
+
|
| 1817 |
+
row = [
|
| 1818 |
+
self._row_to_json(table, cols, row, rownum, rowsourcenum)
|
| 1819 |
+
for rownum, (_, rowsourcenum, row) in enumerate(
|
| 1820 |
+
table.iterdicts(with_metadata=True, strict=False), start=1)
|
| 1821 |
+
]
|
| 1822 |
+
if table._comments:
|
| 1823 |
+
res['rdfs:comment'] = [c[1] for c in table._comments]
|
| 1824 |
+
res['row'] = row
|
| 1825 |
+
return res
|
| 1826 |
+
|
| 1827 |
+
def _row_to_json(self, table, cols, row, rownum, rowsourcenum):
|
| 1828 |
+
res = collections.OrderedDict()
|
| 1829 |
+
res['url'] = '{}#row={}'.format(table.url.resolve(table.base), rowsourcenum)
|
| 1830 |
+
res['rownum'] = rownum
|
| 1831 |
+
if table.tableSchema.rowTitles:
|
| 1832 |
+
res['titles'] = [
|
| 1833 |
+
t for t in [row.get(name) for name in table.tableSchema.rowTitles] if t]
|
| 1834 |
+
if len(res['titles']) == 1:
|
| 1835 |
+
res['titles'] = res['titles'][0]
|
| 1836 |
+
# Insert any notes and non-core annotations specified for the group of tables into object
|
| 1837 |
+
# G according to the rules provided in § 5. JSON-LD to JSON.
|
| 1838 |
+
|
| 1839 |
+
res['describes'] = self._describes(table, cols, row, rownum)
|
| 1840 |
+
return res
|
| 1841 |
+
|
| 1842 |
+
def _describes(self, table, cols, row, rownum):
|
| 1843 |
+
triples = []
|
| 1844 |
+
|
| 1845 |
+
aboutUrl = table.tableSchema.inherit('aboutUrl')
|
| 1846 |
+
if aboutUrl:
|
| 1847 |
+
triples.append(jsonld.Triple(
|
| 1848 |
+
about=None, property='@id', value=table.expand(aboutUrl, row, _row=rownum)))
|
| 1849 |
+
|
| 1850 |
+
for i, (k, v) in enumerate(row.items(), start=1):
|
| 1851 |
+
col = cols.get(k)
|
| 1852 |
+
if col and (col.suppressOutput or col.virtual):
|
| 1853 |
+
continue
|
| 1854 |
+
|
| 1855 |
+
# Skip null values:
|
| 1856 |
+
null = col.inherit_null() if col else table.inherit_null()
|
| 1857 |
+
if (null and v in null) or v == "" or (v is None) or \
|
| 1858 |
+
(col and col.separator and v == []):
|
| 1859 |
+
continue
|
| 1860 |
+
|
| 1861 |
+
triples.append(jsonld.Triple.from_col(
|
| 1862 |
+
table,
|
| 1863 |
+
col,
|
| 1864 |
+
row,
|
| 1865 |
+
'_col.{}'.format(i)
|
| 1866 |
+
if (not table.tableSchema.columns and not self.no_metadata) else k,
|
| 1867 |
+
v,
|
| 1868 |
+
rownum))
|
| 1869 |
+
|
| 1870 |
+
for col in table.tableSchema.columns:
|
| 1871 |
+
if col.virtual:
|
| 1872 |
+
triples.append(jsonld.Triple.from_col(table, col, row, col.header, None, rownum))
|
| 1873 |
+
return jsonld.group_triples(triples)
|
TTS/Kokoro/.venv/Lib/site-packages/csvw/utils.py
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
import copy
|
| 3 |
+
import html
|
| 4 |
+
import json
|
| 5 |
+
import string
|
| 6 |
+
import keyword
|
| 7 |
+
import pathlib
|
| 8 |
+
import warnings
|
| 9 |
+
import collections
|
| 10 |
+
import unicodedata
|
| 11 |
+
|
| 12 |
+
import attr
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def is_url(s):
|
| 16 |
+
return re.match(r'https?://', str(s))
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def converter(type_, default, s, allow_none=False, cond=None, allow_list=True):
|
| 20 |
+
if allow_list and type_ != list and isinstance(s, list):
|
| 21 |
+
return [v for v in [converter(type_, None, ss, cond=cond) for ss in s] if v is not None]
|
| 22 |
+
|
| 23 |
+
if allow_none and s is None:
|
| 24 |
+
return s
|
| 25 |
+
if not isinstance(s, type_) or (type_ == int and isinstance(s, bool)) or (cond and not cond(s)):
|
| 26 |
+
warnings.warn('Invalid value for property: {}'.format(s))
|
| 27 |
+
return default
|
| 28 |
+
return s
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def ensure_path(fname):
|
| 32 |
+
if not isinstance(fname, pathlib.Path):
|
| 33 |
+
assert isinstance(fname, str)
|
| 34 |
+
return pathlib.Path(fname)
|
| 35 |
+
return fname
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def attr_defaults(cls):
|
| 39 |
+
res = collections.OrderedDict()
|
| 40 |
+
for field in attr.fields(cls):
|
| 41 |
+
default = field.default
|
| 42 |
+
if isinstance(default, attr.Factory):
|
| 43 |
+
default = default.factory()
|
| 44 |
+
res[field.name] = default
|
| 45 |
+
return res
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def attr_asdict(obj, omit_defaults=True, omit_private=True):
|
| 49 |
+
defs = attr_defaults(obj.__class__)
|
| 50 |
+
res = collections.OrderedDict()
|
| 51 |
+
for field in attr.fields(obj.__class__):
|
| 52 |
+
if not (omit_private and field.name.startswith('_')):
|
| 53 |
+
value = getattr(obj, field.name)
|
| 54 |
+
if not (omit_defaults and value == defs[field.name]):
|
| 55 |
+
if hasattr(value, 'asdict'):
|
| 56 |
+
value = value.asdict(omit_defaults=True)
|
| 57 |
+
res[field.name] = value
|
| 58 |
+
return res
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def normalize_name(s):
|
| 62 |
+
"""Convert a string into a valid python attribute name.
|
| 63 |
+
This function is called to convert ASCII strings to something that can pass as
|
| 64 |
+
python attribute name, to be used with namedtuples.
|
| 65 |
+
|
| 66 |
+
>>> str(normalize_name('class'))
|
| 67 |
+
'class_'
|
| 68 |
+
>>> str(normalize_name('a-name'))
|
| 69 |
+
'a_name'
|
| 70 |
+
>>> str(normalize_name('a n\u00e4me'))
|
| 71 |
+
'a_name'
|
| 72 |
+
>>> str(normalize_name('Name'))
|
| 73 |
+
'Name'
|
| 74 |
+
>>> str(normalize_name(''))
|
| 75 |
+
'_'
|
| 76 |
+
>>> str(normalize_name('1'))
|
| 77 |
+
'_1'
|
| 78 |
+
"""
|
| 79 |
+
s = s.replace('-', '_').replace('.', '_').replace(' ', '_')
|
| 80 |
+
if s in keyword.kwlist:
|
| 81 |
+
return s + '_'
|
| 82 |
+
s = '_'.join(slug(ss, lowercase=False) for ss in s.split('_'))
|
| 83 |
+
if not s:
|
| 84 |
+
s = '_'
|
| 85 |
+
if s[0] not in string.ascii_letters + '_':
|
| 86 |
+
s = '_' + s
|
| 87 |
+
return s
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def slug(s, remove_whitespace=True, lowercase=True):
|
| 91 |
+
"""Condensed version of s, containing only lowercase alphanumeric characters.
|
| 92 |
+
|
| 93 |
+
>>> str(slug('A B. \u00e4C'))
|
| 94 |
+
'abac'
|
| 95 |
+
"""
|
| 96 |
+
res = ''.join(c for c in unicodedata.normalize('NFD', s)
|
| 97 |
+
if unicodedata.category(c) != 'Mn')
|
| 98 |
+
if lowercase:
|
| 99 |
+
res = res.lower()
|
| 100 |
+
for c in string.punctuation:
|
| 101 |
+
res = res.replace(c, '')
|
| 102 |
+
res = re.sub(r'\s+', '' if remove_whitespace else ' ', res)
|
| 103 |
+
res = res.encode('ascii', 'ignore').decode('ascii')
|
| 104 |
+
assert re.match('[ A-Za-z0-9]*$', res)
|
| 105 |
+
return res
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def qname2url(qname):
|
| 109 |
+
for prefix, uri in {
|
| 110 |
+
'csvw': 'http://www.w3.org/ns/csvw#',
|
| 111 |
+
'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
|
| 112 |
+
'rdfs': 'http://www.w3.org/2000/01/rdf-schema#',
|
| 113 |
+
'xsd': 'http://www.w3.org/2001/XMLSchema#',
|
| 114 |
+
'dc': 'http://purl.org/dc/terms/',
|
| 115 |
+
'dcat': 'http://www.w3.org/ns/dcat#',
|
| 116 |
+
'prov': 'http://www.w3.org/ns/prov#',
|
| 117 |
+
}.items():
|
| 118 |
+
if qname.startswith(prefix + ':'):
|
| 119 |
+
return qname.replace(prefix + ':', uri)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def metadata2markdown(tg, link_files=False) -> str:
|
| 123 |
+
"""
|
| 124 |
+
Render the metadata of a dataset as markdown.
|
| 125 |
+
|
| 126 |
+
:param link_files: If True, links to data files will be added, assuming the markdown is stored \
|
| 127 |
+
in the same directory as the metadata file.
|
| 128 |
+
:return: `str` with markdown formatted text
|
| 129 |
+
"""
|
| 130 |
+
def qname2link(qname, html=False):
|
| 131 |
+
url = qname2url(qname)
|
| 132 |
+
if url:
|
| 133 |
+
if html:
|
| 134 |
+
return '<a href="{}">{}</a>'.format(url, qname)
|
| 135 |
+
return '[{}]({})'.format(qname, url)
|
| 136 |
+
return qname
|
| 137 |
+
|
| 138 |
+
def htmlify(obj, key=None):
|
| 139 |
+
"""
|
| 140 |
+
For inclusion in tables we must use HTML for lists.
|
| 141 |
+
"""
|
| 142 |
+
if isinstance(obj, list):
|
| 143 |
+
return '<ol>{}</ol>'.format(
|
| 144 |
+
''.join('<li>{}</li>'.format(htmlify(item, key=key)) for item in obj))
|
| 145 |
+
if isinstance(obj, dict):
|
| 146 |
+
items = []
|
| 147 |
+
for k, v in obj.items():
|
| 148 |
+
items.append('<dt>{}</dt><dd>{}</dd>'.format(
|
| 149 |
+
qname2link(k, html=True), html.escape(str(v))))
|
| 150 |
+
return '<dl>{}</dl>'.format(''.join(items))
|
| 151 |
+
return str(obj)
|
| 152 |
+
|
| 153 |
+
def properties(props):
|
| 154 |
+
props = {k: v for k, v in copy.deepcopy(props).items() if v}
|
| 155 |
+
res = []
|
| 156 |
+
desc = props.pop('dc:description', None)
|
| 157 |
+
if desc:
|
| 158 |
+
res.append(desc + '\n')
|
| 159 |
+
img = props.pop('https://schema.org/image', None)
|
| 160 |
+
if img:
|
| 161 |
+
if isinstance(img, str): # pragma: no cover
|
| 162 |
+
img = {'contentUrl': img}
|
| 163 |
+
res.append('\n'.format(
|
| 164 |
+
img.get('https://schema.org/caption') or '',
|
| 165 |
+
img.get('https://schema.org/contentUrl')))
|
| 166 |
+
if props:
|
| 167 |
+
res.append('property | value\n --- | ---')
|
| 168 |
+
for k, v in props.items():
|
| 169 |
+
res.append('{} | {}'.format(qname2link(k), htmlify(v, key=k)))
|
| 170 |
+
return '\n'.join(res) + '\n'
|
| 171 |
+
|
| 172 |
+
def colrow(col, fks, pk):
|
| 173 |
+
dt = '`{}`'.format(col.datatype.base if col.datatype else 'string')
|
| 174 |
+
if col.datatype:
|
| 175 |
+
if col.datatype.format:
|
| 176 |
+
if re.fullmatch(r'[\w\s]+(\|[\w\s]+)*', col.datatype.format):
|
| 177 |
+
dt += '<br>Valid choices:<br>'
|
| 178 |
+
dt += ''.join(' `{}`'.format(w) for w in col.datatype.format.split('|'))
|
| 179 |
+
elif col.datatype.base == 'string':
|
| 180 |
+
dt += '<br>Regex: `{}`'.format(col.datatype.format)
|
| 181 |
+
if col.datatype.minimum:
|
| 182 |
+
dt += '<br>≥ {}'.format(col.datatype.minimum)
|
| 183 |
+
if col.datatype.maximum:
|
| 184 |
+
dt += '<br>≤ {}'.format(col.datatype.maximum)
|
| 185 |
+
if col.separator:
|
| 186 |
+
dt = 'list of {} (separated by `{}`)'.format(dt, col.separator)
|
| 187 |
+
desc = col.common_props.get('dc:description', '').replace('\n', ' ')
|
| 188 |
+
|
| 189 |
+
if pk and col.name in pk:
|
| 190 |
+
desc = (desc + '<br>') if desc else desc
|
| 191 |
+
desc += 'Primary key'
|
| 192 |
+
|
| 193 |
+
if col.name in fks:
|
| 194 |
+
desc = (desc + '<br>') if desc else desc
|
| 195 |
+
desc += 'References [{}::{}](#table-{})'.format(
|
| 196 |
+
fks[col.name][1], fks[col.name][0], slug(fks[col.name][1]))
|
| 197 |
+
|
| 198 |
+
return ' | '.join([
|
| 199 |
+
'[{}]({})'.format(col.name, col.propertyUrl)
|
| 200 |
+
if col.propertyUrl else '`{}`'.format(col.name),
|
| 201 |
+
dt,
|
| 202 |
+
desc,
|
| 203 |
+
])
|
| 204 |
+
|
| 205 |
+
res = ['# {}\n'.format(tg.common_props.get('dc:title', 'Dataset'))]
|
| 206 |
+
if tg._fname and link_files:
|
| 207 |
+
res.append('> [!NOTE]\n> Described by [{0}]({0}).\n'.format(tg._fname.name))
|
| 208 |
+
|
| 209 |
+
res.append(properties({k: v for k, v in tg.common_props.items() if k != 'dc:title'}))
|
| 210 |
+
|
| 211 |
+
for table in tg.tables:
|
| 212 |
+
fks = {
|
| 213 |
+
fk.columnReference[0]: (fk.reference.columnReference[0], fk.reference.resource.string)
|
| 214 |
+
for fk in table.tableSchema.foreignKeys if len(fk.columnReference) == 1}
|
| 215 |
+
header = '## <a name="table-{}"></a>Table '.format(slug(table.url.string))
|
| 216 |
+
if link_files and tg._fname and tg._fname.parent.joinpath(table.url.string).exists():
|
| 217 |
+
header += '[{0}]({0})\n'.format(table.url.string)
|
| 218 |
+
else: # pragma: no cover
|
| 219 |
+
header += table.url.string
|
| 220 |
+
res.append('\n' + header + '\n')
|
| 221 |
+
res.append(properties(table.common_props))
|
| 222 |
+
dialect = table.inherit('dialect')
|
| 223 |
+
if dialect.asdict():
|
| 224 |
+
res.append('\n**CSV dialect**: `{}`\n'.format(json.dumps(dialect.asdict())))
|
| 225 |
+
res.append('\n### Columns\n')
|
| 226 |
+
res.append('Name/Property | Datatype | Description')
|
| 227 |
+
res.append(' --- | --- | --- ')
|
| 228 |
+
for col in table.tableSchema.columns:
|
| 229 |
+
res.append(colrow(col, fks, table.tableSchema.primaryKey))
|
| 230 |
+
return '\n'.join(res)
|
TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers-0.0.9.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
pip
|
TTS/Kokoro/.venv/Lib/site-packages/curated_tokenizers-0.0.9.dist-info/LICENSE
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
The MIT License (MIT)
|
| 2 |
+
|
| 3 |
+
Copyright (C) 2022 ExplosionAI GmbH
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in
|
| 13 |
+
all copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
| 21 |
+
THE SOFTWARE.
|
| 22 |
+
|
| 23 |
+
---
|
| 24 |
+
|
| 25 |
+
The BPE byte mapping and split pattern in ByteBPEProcessor were taken directly
|
| 26 |
+
from GPT-2 to ensure identical splittings. The following nice notice applies
|
| 27 |
+
to this code:
|
| 28 |
+
|
| 29 |
+
Software Copyright (c) 2019 OpenAI
|
| 30 |
+
|
| 31 |
+
We don’t claim ownership of the content you create with GPT-2, so it is yours to
|
| 32 |
+
do with as you please. We only ask that you use GPT-2 responsibly and clearly
|
| 33 |
+
indicate your content was created using GPT-2.
|
| 34 |
+
|
| 35 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
| 36 |
+
this software and associated documentation files (the "Software"), to deal in
|
| 37 |
+
the Software without restriction, including without limitation the rights to
|
| 38 |
+
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
| 39 |
+
the Software, and to permit persons to whom the Software is furnished to do so,
|
| 40 |
+
subject to the following conditions:
|
| 41 |
+
|
| 42 |
+
The above copyright notice and this permission notice shall be included in all
|
| 43 |
+
copies or substantial portions of the Software. The above copyright notice and
|
| 44 |
+
this permission notice need not be included with content created by the
|
| 45 |
+
Software.
|
| 46 |
+
|
| 47 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 48 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
| 49 |
+
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
| 50 |
+
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
| 51 |
+
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
| 52 |
+
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|