Upload folder using huggingface_hub (part 7)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +7 -0
- .venv/lib/python3.12/site-packages/fsspec-2026.7.0.dist-info/INSTALLER +1 -0
- .venv/lib/python3.12/site-packages/fsspec-2026.7.0.dist-info/METADATA +257 -0
- .venv/lib/python3.12/site-packages/fsspec-2026.7.0.dist-info/RECORD +119 -0
- .venv/lib/python3.12/site-packages/fsspec-2026.7.0.dist-info/WHEEL +4 -0
- .venv/lib/python3.12/site-packages/fsspec-2026.7.0.dist-info/licenses/LICENSE +29 -0
- .venv/lib/python3.12/site-packages/fsspec/caching.py +1025 -0
- .venv/lib/python3.12/site-packages/fsspec/callbacks.py +324 -0
- .venv/lib/python3.12/site-packages/fsspec/compression.py +185 -0
- .venv/lib/python3.12/site-packages/fsspec/config.py +131 -0
- .venv/lib/python3.12/site-packages/fsspec/conftest.py +125 -0
- .venv/lib/python3.12/site-packages/fsspec/core.py +760 -0
- .venv/lib/python3.12/site-packages/fsspec/dircache.py +98 -0
- .venv/lib/python3.12/site-packages/fsspec/exceptions.py +18 -0
- .venv/lib/python3.12/site-packages/fsspec/fuse.py +324 -0
- .venv/lib/python3.12/site-packages/fsspec/generic.py +396 -0
- .venv/lib/python3.12/site-packages/fsspec/gui.py +417 -0
- .venv/lib/python3.12/site-packages/fsspec/implementations/__init__.py +0 -0
- .venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/__init__.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/arrow.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/asyn_wrapper.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/cache_mapper.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/cache_metadata.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/cached.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/chained.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/dask.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/data.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/dbfs.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/dirfs.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/ftp.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/gist.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/git.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/github.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/http.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/http_sync.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/jupyter.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/libarchive.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/local.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/memory.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/reference.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/sftp.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/smb.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/tar.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/webhdfs.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/zip.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/fsspec/implementations/arrow.py +322 -0
- .venv/lib/python3.12/site-packages/fsspec/implementations/asyn_wrapper.py +124 -0
- .venv/lib/python3.12/site-packages/fsspec/implementations/cache_mapper.py +75 -0
- .venv/lib/python3.12/site-packages/fsspec/implementations/cache_metadata.py +217 -0
- .venv/lib/python3.12/site-packages/fsspec/implementations/cached.py +1040 -0
.gitattributes
CHANGED
|
@@ -169,3 +169,10 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 169 |
.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/otTables.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 170 |
.venv/lib/python3.12/site-packages/fontTools/varLib/instancer/__pycache__/__init__.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 171 |
.venv/lib/python3.12/site-packages/fontTools/varLib/iup.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/otTables.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 170 |
.venv/lib/python3.12/site-packages/fontTools/varLib/instancer/__pycache__/__init__.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 171 |
.venv/lib/python3.12/site-packages/fontTools/varLib/iup.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 172 |
+
.venv/lib/python3.12/site-packages/jinja2/__pycache__/compiler.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 173 |
+
.venv/lib/python3.12/site-packages/kiwisolver/_cext.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 174 |
+
.venv/lib/python3.12/site-packages/lxml/_elementpath.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 175 |
+
.venv/lib/python3.12/site-packages/lxml/builder.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 176 |
+
.venv/lib/python3.12/site-packages/lxml/etree.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 177 |
+
.venv/lib/python3.12/site-packages/lxml/html/_difflib.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 178 |
+
.venv/lib/python3.12/site-packages/lxml/html/diff.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
.venv/lib/python3.12/site-packages/fsspec-2026.7.0.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
pip
|
.venv/lib/python3.12/site-packages/fsspec-2026.7.0.dist-info/METADATA
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
Metadata-Version: 2.4
|
| 2 |
+
Name: fsspec
|
| 3 |
+
Version: 2026.7.0
|
| 4 |
+
Summary: File-system specification
|
| 5 |
+
Project-URL: Changelog, https://filesystem-spec.readthedocs.io/en/latest/changelog.html
|
| 6 |
+
Project-URL: Documentation, https://filesystem-spec.readthedocs.io/en/latest/
|
| 7 |
+
Project-URL: Homepage, https://github.com/fsspec/filesystem_spec
|
| 8 |
+
Maintainer-email: Martin Durant <mdurant@anaconda.com>
|
| 9 |
+
License-Expression: BSD-3-Clause
|
| 10 |
+
License-File: LICENSE
|
| 11 |
+
Keywords: file
|
| 12 |
+
Classifier: Development Status :: 4 - Beta
|
| 13 |
+
Classifier: Intended Audience :: Developers
|
| 14 |
+
Classifier: Operating System :: OS Independent
|
| 15 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 16 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 17 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 18 |
+
Classifier: Programming Language :: Python :: 3.13
|
| 19 |
+
Classifier: Programming Language :: Python :: 3.14
|
| 20 |
+
Requires-Python: >=3.10
|
| 21 |
+
Provides-Extra: abfs
|
| 22 |
+
Requires-Dist: adlfs; extra == 'abfs'
|
| 23 |
+
Provides-Extra: adl
|
| 24 |
+
Requires-Dist: adlfs; extra == 'adl'
|
| 25 |
+
Provides-Extra: arrow
|
| 26 |
+
Requires-Dist: pyarrow>=1; extra == 'arrow'
|
| 27 |
+
Provides-Extra: dask
|
| 28 |
+
Requires-Dist: dask; extra == 'dask'
|
| 29 |
+
Requires-Dist: distributed; extra == 'dask'
|
| 30 |
+
Provides-Extra: dev
|
| 31 |
+
Requires-Dist: pre-commit; extra == 'dev'
|
| 32 |
+
Requires-Dist: ruff>=0.5; extra == 'dev'
|
| 33 |
+
Provides-Extra: doc
|
| 34 |
+
Requires-Dist: numpydoc; extra == 'doc'
|
| 35 |
+
Requires-Dist: sphinx; extra == 'doc'
|
| 36 |
+
Requires-Dist: sphinx-design; extra == 'doc'
|
| 37 |
+
Requires-Dist: sphinx-rtd-theme; extra == 'doc'
|
| 38 |
+
Requires-Dist: yarl; extra == 'doc'
|
| 39 |
+
Provides-Extra: dropbox
|
| 40 |
+
Requires-Dist: dropbox; extra == 'dropbox'
|
| 41 |
+
Requires-Dist: dropboxdrivefs; extra == 'dropbox'
|
| 42 |
+
Requires-Dist: requests; extra == 'dropbox'
|
| 43 |
+
Provides-Extra: entrypoints
|
| 44 |
+
Provides-Extra: full
|
| 45 |
+
Requires-Dist: adlfs; extra == 'full'
|
| 46 |
+
Requires-Dist: aiohttp!=4.0.0a0,!=4.0.0a1; extra == 'full'
|
| 47 |
+
Requires-Dist: dask; extra == 'full'
|
| 48 |
+
Requires-Dist: distributed; extra == 'full'
|
| 49 |
+
Requires-Dist: dropbox; extra == 'full'
|
| 50 |
+
Requires-Dist: dropboxdrivefs; extra == 'full'
|
| 51 |
+
Requires-Dist: fusepy; extra == 'full'
|
| 52 |
+
Requires-Dist: gcsfs>=2026.4.0; extra == 'full'
|
| 53 |
+
Requires-Dist: libarchive-c; extra == 'full'
|
| 54 |
+
Requires-Dist: ocifs; extra == 'full'
|
| 55 |
+
Requires-Dist: panel; extra == 'full'
|
| 56 |
+
Requires-Dist: paramiko; extra == 'full'
|
| 57 |
+
Requires-Dist: pyarrow>=1; extra == 'full'
|
| 58 |
+
Requires-Dist: pygit2; extra == 'full'
|
| 59 |
+
Requires-Dist: requests; extra == 'full'
|
| 60 |
+
Requires-Dist: s3fs>=2026.6.0; extra == 'full'
|
| 61 |
+
Requires-Dist: smbprotocol; extra == 'full'
|
| 62 |
+
Requires-Dist: tqdm; extra == 'full'
|
| 63 |
+
Provides-Extra: fuse
|
| 64 |
+
Requires-Dist: fusepy; extra == 'fuse'
|
| 65 |
+
Provides-Extra: gcs
|
| 66 |
+
Requires-Dist: gcsfs>=2026.4.0; extra == 'gcs'
|
| 67 |
+
Provides-Extra: git
|
| 68 |
+
Requires-Dist: pygit2; extra == 'git'
|
| 69 |
+
Provides-Extra: github
|
| 70 |
+
Requires-Dist: requests; extra == 'github'
|
| 71 |
+
Provides-Extra: gs
|
| 72 |
+
Requires-Dist: gcsfs>=2026.4.0; extra == 'gs'
|
| 73 |
+
Provides-Extra: gui
|
| 74 |
+
Requires-Dist: panel; extra == 'gui'
|
| 75 |
+
Provides-Extra: hdfs
|
| 76 |
+
Requires-Dist: pyarrow>=1; extra == 'hdfs'
|
| 77 |
+
Provides-Extra: http
|
| 78 |
+
Requires-Dist: aiohttp!=4.0.0a0,!=4.0.0a1; extra == 'http'
|
| 79 |
+
Provides-Extra: libarchive
|
| 80 |
+
Requires-Dist: libarchive-c; extra == 'libarchive'
|
| 81 |
+
Provides-Extra: oci
|
| 82 |
+
Requires-Dist: ocifs; extra == 'oci'
|
| 83 |
+
Provides-Extra: s3
|
| 84 |
+
Requires-Dist: s3fs>=2026.6.0; extra == 's3'
|
| 85 |
+
Provides-Extra: sftp
|
| 86 |
+
Requires-Dist: paramiko; extra == 'sftp'
|
| 87 |
+
Provides-Extra: smb
|
| 88 |
+
Requires-Dist: smbprotocol; extra == 'smb'
|
| 89 |
+
Provides-Extra: ssh
|
| 90 |
+
Requires-Dist: paramiko; extra == 'ssh'
|
| 91 |
+
Provides-Extra: test
|
| 92 |
+
Requires-Dist: aiohttp!=4.0.0a0,!=4.0.0a1; extra == 'test'
|
| 93 |
+
Requires-Dist: numpy; extra == 'test'
|
| 94 |
+
Requires-Dist: pytest; extra == 'test'
|
| 95 |
+
Requires-Dist: pytest-asyncio!=0.22.0; extra == 'test'
|
| 96 |
+
Requires-Dist: pytest-benchmark; extra == 'test'
|
| 97 |
+
Requires-Dist: pytest-cov; extra == 'test'
|
| 98 |
+
Requires-Dist: pytest-mock; extra == 'test'
|
| 99 |
+
Requires-Dist: pytest-recording; extra == 'test'
|
| 100 |
+
Requires-Dist: pytest-rerunfailures; extra == 'test'
|
| 101 |
+
Requires-Dist: requests; extra == 'test'
|
| 102 |
+
Provides-Extra: test-downstream
|
| 103 |
+
Requires-Dist: aiobotocore<3.0.0,>=2.5.4; extra == 'test-downstream'
|
| 104 |
+
Requires-Dist: dask[dataframe,test]; extra == 'test-downstream'
|
| 105 |
+
Requires-Dist: moto[server]<5,>4; extra == 'test-downstream'
|
| 106 |
+
Requires-Dist: pytest-timeout; extra == 'test-downstream'
|
| 107 |
+
Requires-Dist: xarray; extra == 'test-downstream'
|
| 108 |
+
Provides-Extra: test-full
|
| 109 |
+
Requires-Dist: adlfs; extra == 'test-full'
|
| 110 |
+
Requires-Dist: aiohttp!=4.0.0a0,!=4.0.0a1; extra == 'test-full'
|
| 111 |
+
Requires-Dist: backports-zstd; (python_version < '3.14') and extra == 'test-full'
|
| 112 |
+
Requires-Dist: cloudpickle; extra == 'test-full'
|
| 113 |
+
Requires-Dist: dask; extra == 'test-full'
|
| 114 |
+
Requires-Dist: distributed; extra == 'test-full'
|
| 115 |
+
Requires-Dist: dropbox; extra == 'test-full'
|
| 116 |
+
Requires-Dist: dropboxdrivefs; extra == 'test-full'
|
| 117 |
+
Requires-Dist: fastparquet; extra == 'test-full'
|
| 118 |
+
Requires-Dist: fusepy; extra == 'test-full'
|
| 119 |
+
Requires-Dist: gcsfs>=2026.4.0; extra == 'test-full'
|
| 120 |
+
Requires-Dist: jinja2; extra == 'test-full'
|
| 121 |
+
Requires-Dist: kerchunk; extra == 'test-full'
|
| 122 |
+
Requires-Dist: libarchive-c; extra == 'test-full'
|
| 123 |
+
Requires-Dist: lz4; extra == 'test-full'
|
| 124 |
+
Requires-Dist: notebook; extra == 'test-full'
|
| 125 |
+
Requires-Dist: numpy; extra == 'test-full'
|
| 126 |
+
Requires-Dist: ocifs; extra == 'test-full'
|
| 127 |
+
Requires-Dist: pandas<3.0.0; extra == 'test-full'
|
| 128 |
+
Requires-Dist: panel; extra == 'test-full'
|
| 129 |
+
Requires-Dist: paramiko; extra == 'test-full'
|
| 130 |
+
Requires-Dist: pyarrow>=1; extra == 'test-full'
|
| 131 |
+
Requires-Dist: pyftpdlib; extra == 'test-full'
|
| 132 |
+
Requires-Dist: pygit2; extra == 'test-full'
|
| 133 |
+
Requires-Dist: pytest; extra == 'test-full'
|
| 134 |
+
Requires-Dist: pytest-asyncio!=0.22.0; extra == 'test-full'
|
| 135 |
+
Requires-Dist: pytest-benchmark; extra == 'test-full'
|
| 136 |
+
Requires-Dist: pytest-cov; extra == 'test-full'
|
| 137 |
+
Requires-Dist: pytest-mock; extra == 'test-full'
|
| 138 |
+
Requires-Dist: pytest-recording; extra == 'test-full'
|
| 139 |
+
Requires-Dist: pytest-rerunfailures; extra == 'test-full'
|
| 140 |
+
Requires-Dist: python-snappy; extra == 'test-full'
|
| 141 |
+
Requires-Dist: requests; extra == 'test-full'
|
| 142 |
+
Requires-Dist: s3fs>=2026.6.0; extra == 'test-full'
|
| 143 |
+
Requires-Dist: smbprotocol; extra == 'test-full'
|
| 144 |
+
Requires-Dist: tqdm; extra == 'test-full'
|
| 145 |
+
Requires-Dist: urllib3; extra == 'test-full'
|
| 146 |
+
Requires-Dist: zarr<3.2.0; extra == 'test-full'
|
| 147 |
+
Requires-Dist: zstandard; (python_version < '3.14') and extra == 'test-full'
|
| 148 |
+
Provides-Extra: tqdm
|
| 149 |
+
Requires-Dist: tqdm; extra == 'tqdm'
|
| 150 |
+
Description-Content-Type: text/markdown
|
| 151 |
+
|
| 152 |
+
# filesystem_spec
|
| 153 |
+
|
| 154 |
+
[](https://pypi.python.org/pypi/fsspec/)
|
| 155 |
+
[](https://anaconda.org/conda-forge/fsspec)
|
| 156 |
+

|
| 157 |
+
[](https://filesystem-spec.readthedocs.io/en/latest/?badge=latest)
|
| 158 |
+
|
| 159 |
+
A specification for pythonic filesystems.
|
| 160 |
+
|
| 161 |
+
## Install
|
| 162 |
+
|
| 163 |
+
```bash
|
| 164 |
+
pip install fsspec
|
| 165 |
+
```
|
| 166 |
+
|
| 167 |
+
would install the base fsspec. Various optionally supported features might require specification of custom
|
| 168 |
+
extra require, e.g. `pip install fsspec[ssh]` will install dependencies for `ssh` backends support.
|
| 169 |
+
Use `pip install fsspec[full]` for installation of all known extra dependencies.
|
| 170 |
+
|
| 171 |
+
Up-to-date package also provided through conda-forge distribution:
|
| 172 |
+
|
| 173 |
+
```bash
|
| 174 |
+
conda install -c conda-forge fsspec
|
| 175 |
+
```
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
## Purpose
|
| 179 |
+
|
| 180 |
+
To produce a template or specification for a file-system interface, that specific implementations should follow,
|
| 181 |
+
so that applications making use of them can rely on a common behaviour and not have to worry about the specific
|
| 182 |
+
internal implementation decisions with any given backend. Many such implementations are included in this package,
|
| 183 |
+
or in sister projects such as `s3fs` and `gcsfs`.
|
| 184 |
+
|
| 185 |
+
In addition, if this is well-designed, then additional functionality, such as a key-value store or FUSE
|
| 186 |
+
mounting of the file-system implementation may be available for all implementations "for free".
|
| 187 |
+
|
| 188 |
+
## Documentation
|
| 189 |
+
|
| 190 |
+
Please refer to [RTD](https://filesystem-spec.readthedocs.io/en/latest/?badge=latest)
|
| 191 |
+
|
| 192 |
+
## Develop
|
| 193 |
+
|
| 194 |
+
fsspec uses GitHub Actions for CI. Environment files can be found
|
| 195 |
+
in the "ci/" directory. Note that the main environment is called "py38",
|
| 196 |
+
but it is expected that the version of python installed be adjustable at
|
| 197 |
+
CI runtime. For local use, pick a version suitable for you.
|
| 198 |
+
|
| 199 |
+
```bash
|
| 200 |
+
# For a new environment (mamba / conda).
|
| 201 |
+
mamba create -n fsspec -c conda-forge python=3.10 -y
|
| 202 |
+
conda activate fsspec
|
| 203 |
+
|
| 204 |
+
# Standard dev install with docs and tests.
|
| 205 |
+
pip install -e ".[dev,doc,test]"
|
| 206 |
+
|
| 207 |
+
# Full tests except for downstream
|
| 208 |
+
pip install s3fs
|
| 209 |
+
pip uninstall s3fs
|
| 210 |
+
pip install -e .[dev,doc,test_full]
|
| 211 |
+
pip install s3fs --no-deps
|
| 212 |
+
pytest -v
|
| 213 |
+
|
| 214 |
+
# Downstream tests.
|
| 215 |
+
sh install_s3fs.sh
|
| 216 |
+
# Windows powershell.
|
| 217 |
+
install_s3fs.sh
|
| 218 |
+
```
|
| 219 |
+
|
| 220 |
+
### Testing
|
| 221 |
+
|
| 222 |
+
Tests can be run in the dev environment, if activated, via ``pytest fsspec``.
|
| 223 |
+
|
| 224 |
+
The full fsspec suite requires a system-level docker, docker-compose, and fuse
|
| 225 |
+
installation. If only making changes to one backend implementation, it is
|
| 226 |
+
not generally necessary to run all tests locally.
|
| 227 |
+
|
| 228 |
+
It is expected that contributors ensure that any change to fsspec does not
|
| 229 |
+
cause issues or regressions for either other fsspec-related packages such
|
| 230 |
+
as gcsfs and s3fs, nor for downstream users of fsspec. The "downstream" CI
|
| 231 |
+
run and corresponding environment file run a set of tests from the dask
|
| 232 |
+
test suite, and very minimal tests against pandas and zarr from the
|
| 233 |
+
test_downstream.py module in this repo.
|
| 234 |
+
|
| 235 |
+
### Code Formatting
|
| 236 |
+
|
| 237 |
+
fsspec uses [Black](https://black.readthedocs.io/en/stable) to ensure
|
| 238 |
+
a consistent code format throughout the project.
|
| 239 |
+
Run ``black fsspec`` from the root of the filesystem_spec repository to
|
| 240 |
+
auto-format your code. Additionally, many editors have plugins that will apply
|
| 241 |
+
``black`` as you edit files. ``black`` is included in the ``tox`` environments.
|
| 242 |
+
|
| 243 |
+
Optionally, you may wish to setup [pre-commit hooks](https://pre-commit.com) to
|
| 244 |
+
automatically run ``black`` when you make a git commit.
|
| 245 |
+
Run ``pre-commit install --install-hooks`` from the root of the
|
| 246 |
+
filesystem_spec repository to setup pre-commit hooks. ``black`` will now be run
|
| 247 |
+
before you commit, reformatting any changed files. You can format without
|
| 248 |
+
committing via ``pre-commit run`` or skip these checks with ``git commit
|
| 249 |
+
--no-verify``.
|
| 250 |
+
|
| 251 |
+
## Support
|
| 252 |
+
|
| 253 |
+
Work on this repository is supported in part by:
|
| 254 |
+
|
| 255 |
+
"Anaconda, Inc. - Advancing AI through open source."
|
| 256 |
+
|
| 257 |
+
<a href="https://anaconda.com/"><img src="https://camo.githubusercontent.com/b8555ef2222598ed37ce38ac86955febbd25de7619931bb7dd3c58432181d3b6/68747470733a2f2f626565776172652e6f72672f636f6d6d756e6974792f6d656d626572732f616e61636f6e64612f616e61636f6e64612d6c617267652e706e67" alt="anaconda logo" width="40%"/></a>
|
.venv/lib/python3.12/site-packages/fsspec-2026.7.0.dist-info/RECORD
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fsspec-2026.7.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
| 2 |
+
fsspec-2026.7.0.dist-info/METADATA,sha256=iLFldYXeFOO7gqpSeKqVlbMKpMp06tBz2JUGFcgICZ0,10561
|
| 3 |
+
fsspec-2026.7.0.dist-info/RECORD,,
|
| 4 |
+
fsspec-2026.7.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
|
| 5 |
+
fsspec-2026.7.0.dist-info/licenses/LICENSE,sha256=LcNUls5TpzB5FcAIqESq1T53K0mzTN0ARFBnaRQH7JQ,1513
|
| 6 |
+
fsspec/__init__.py,sha256=xFcoHBD17fc5KamKUQAIA0rePGjLqIN1WBAd9NAoAi8,2111
|
| 7 |
+
fsspec/__pycache__/__init__.cpython-312.pyc,,
|
| 8 |
+
fsspec/__pycache__/_version.cpython-312.pyc,,
|
| 9 |
+
fsspec/__pycache__/archive.cpython-312.pyc,,
|
| 10 |
+
fsspec/__pycache__/asyn.cpython-312.pyc,,
|
| 11 |
+
fsspec/__pycache__/caching.cpython-312.pyc,,
|
| 12 |
+
fsspec/__pycache__/callbacks.cpython-312.pyc,,
|
| 13 |
+
fsspec/__pycache__/compression.cpython-312.pyc,,
|
| 14 |
+
fsspec/__pycache__/config.cpython-312.pyc,,
|
| 15 |
+
fsspec/__pycache__/conftest.cpython-312.pyc,,
|
| 16 |
+
fsspec/__pycache__/core.cpython-312.pyc,,
|
| 17 |
+
fsspec/__pycache__/dircache.cpython-312.pyc,,
|
| 18 |
+
fsspec/__pycache__/exceptions.cpython-312.pyc,,
|
| 19 |
+
fsspec/__pycache__/fuse.cpython-312.pyc,,
|
| 20 |
+
fsspec/__pycache__/generic.cpython-312.pyc,,
|
| 21 |
+
fsspec/__pycache__/gui.cpython-312.pyc,,
|
| 22 |
+
fsspec/__pycache__/json.cpython-312.pyc,,
|
| 23 |
+
fsspec/__pycache__/mapping.cpython-312.pyc,,
|
| 24 |
+
fsspec/__pycache__/parquet.cpython-312.pyc,,
|
| 25 |
+
fsspec/__pycache__/registry.cpython-312.pyc,,
|
| 26 |
+
fsspec/__pycache__/spec.cpython-312.pyc,,
|
| 27 |
+
fsspec/__pycache__/transaction.cpython-312.pyc,,
|
| 28 |
+
fsspec/__pycache__/utils.cpython-312.pyc,,
|
| 29 |
+
fsspec/_version.py,sha256=XYrsnKX7E2XNoSiwqs7ALMtioidXl8y8KSliz3pL7S0,526
|
| 30 |
+
fsspec/archive.py,sha256=vM6t_lgV6lBWbBYwpm3S4ofBQFQxUPr5KkDQrrQcQro,2411
|
| 31 |
+
fsspec/asyn.py,sha256=V1Kig3HVzgWwZ-VtUYhys3QfdmiWRLG7EcP1E1PwM6M,39105
|
| 32 |
+
fsspec/caching.py,sha256=Glmc9tDtS8Ctp44sd7mJURJYq7sHkH_yD480q6IgbxE,34777
|
| 33 |
+
fsspec/callbacks.py,sha256=BDIwLzK6rr_0V5ch557fSzsivCElpdqhXr5dZ9Te-EE,9210
|
| 34 |
+
fsspec/compression.py,sha256=3v_Fe39gzRRWfaeXpzNjAGPqgTzmETYRCo3qHVqD3po,5132
|
| 35 |
+
fsspec/config.py,sha256=mHKzAgjXa_LwqtO_VoTJJ568VqwYkbK3gUp4J6JZJp4,4238
|
| 36 |
+
fsspec/conftest.py,sha256=uWfm_Qs5alPRxOhRpDfQ0-1jqSJ54pni4y96IxOREXM,3446
|
| 37 |
+
fsspec/core.py,sha256=EapTTO4bGR9G12rC90FiaBRemMhqo0ypx3ZqXj1zVuk,24189
|
| 38 |
+
fsspec/dircache.py,sha256=YzogWJrhEastHU7vWz-cJiJ7sdtLXFXhEpInGKd4EcM,2717
|
| 39 |
+
fsspec/exceptions.py,sha256=pauSLDMxzTJMOjvX1WEUK0cMyFkrFxpWJsyFywav7A8,331
|
| 40 |
+
fsspec/fuse.py,sha256=Q-3NOOyLqBfYa4Db5E19z_ZY36zzYHtIs1mOUasItBQ,10177
|
| 41 |
+
fsspec/generic.py,sha256=-LIADa9qRN79bfa3Hl9m3HaN6rlU2GNivawLNmybqxE,13752
|
| 42 |
+
fsspec/gui.py,sha256=CQ7QsrTpaDlWSLNOpwNoJc7khOcYXIZxmrAJN9bHWQU,14002
|
| 43 |
+
fsspec/implementations/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 44 |
+
fsspec/implementations/__pycache__/__init__.cpython-312.pyc,,
|
| 45 |
+
fsspec/implementations/__pycache__/arrow.cpython-312.pyc,,
|
| 46 |
+
fsspec/implementations/__pycache__/asyn_wrapper.cpython-312.pyc,,
|
| 47 |
+
fsspec/implementations/__pycache__/cache_mapper.cpython-312.pyc,,
|
| 48 |
+
fsspec/implementations/__pycache__/cache_metadata.cpython-312.pyc,,
|
| 49 |
+
fsspec/implementations/__pycache__/cached.cpython-312.pyc,,
|
| 50 |
+
fsspec/implementations/__pycache__/chained.cpython-312.pyc,,
|
| 51 |
+
fsspec/implementations/__pycache__/dask.cpython-312.pyc,,
|
| 52 |
+
fsspec/implementations/__pycache__/data.cpython-312.pyc,,
|
| 53 |
+
fsspec/implementations/__pycache__/dbfs.cpython-312.pyc,,
|
| 54 |
+
fsspec/implementations/__pycache__/dirfs.cpython-312.pyc,,
|
| 55 |
+
fsspec/implementations/__pycache__/ftp.cpython-312.pyc,,
|
| 56 |
+
fsspec/implementations/__pycache__/gist.cpython-312.pyc,,
|
| 57 |
+
fsspec/implementations/__pycache__/git.cpython-312.pyc,,
|
| 58 |
+
fsspec/implementations/__pycache__/github.cpython-312.pyc,,
|
| 59 |
+
fsspec/implementations/__pycache__/http.cpython-312.pyc,,
|
| 60 |
+
fsspec/implementations/__pycache__/http_sync.cpython-312.pyc,,
|
| 61 |
+
fsspec/implementations/__pycache__/jupyter.cpython-312.pyc,,
|
| 62 |
+
fsspec/implementations/__pycache__/libarchive.cpython-312.pyc,,
|
| 63 |
+
fsspec/implementations/__pycache__/local.cpython-312.pyc,,
|
| 64 |
+
fsspec/implementations/__pycache__/memory.cpython-312.pyc,,
|
| 65 |
+
fsspec/implementations/__pycache__/reference.cpython-312.pyc,,
|
| 66 |
+
fsspec/implementations/__pycache__/sftp.cpython-312.pyc,,
|
| 67 |
+
fsspec/implementations/__pycache__/smb.cpython-312.pyc,,
|
| 68 |
+
fsspec/implementations/__pycache__/tar.cpython-312.pyc,,
|
| 69 |
+
fsspec/implementations/__pycache__/webhdfs.cpython-312.pyc,,
|
| 70 |
+
fsspec/implementations/__pycache__/zip.cpython-312.pyc,,
|
| 71 |
+
fsspec/implementations/arrow.py,sha256=HSXhExZ3HKNkWEm6m36h2jrbVilt3u8MvJI60u1_6fU,9236
|
| 72 |
+
fsspec/implementations/asyn_wrapper.py,sha256=3lfJkGs6D_AwRBdxTSYlL-RCVdaXBZ9Itys2P5o5Si0,3738
|
| 73 |
+
fsspec/implementations/cache_mapper.py,sha256=W4wlxyPxZbSp9ItJ0pYRVBMh6bw9eFypgP6kUYuuiI4,2421
|
| 74 |
+
fsspec/implementations/cache_metadata.py,sha256=EPhQV27lgPlYREYprDET1vcMed15pVNMit-Ta1ljoyE,7942
|
| 75 |
+
fsspec/implementations/cached.py,sha256=A_QyiukZzVznBWSZgMXSLd6h6K7k-ueroqnsoVY4bZg,37134
|
| 76 |
+
fsspec/implementations/chained.py,sha256=iGivpNaHUFjB_ea0-HAPhcmm6CL8qnDf270PSj7JwuE,680
|
| 77 |
+
fsspec/implementations/dask.py,sha256=CXZbJzIVOhKV8ILcxuy3bTvcacCueAbyQxmvAkbPkrk,4466
|
| 78 |
+
fsspec/implementations/data.py,sha256=9tMcy1fyX1auvzFX2aANPK9CfPoarnxTCDLhX12usvs,2131
|
| 79 |
+
fsspec/implementations/dbfs.py,sha256=yHuLUGNmQd5pUCt9vpXleQNpjOpIZZwVZA08YauQU4U,16249
|
| 80 |
+
fsspec/implementations/dirfs.py,sha256=KaIHW18i4-eNqdv7NR9qXEvoobQ88trGCNrqb4XW9ew,13449
|
| 81 |
+
fsspec/implementations/ftp.py,sha256=S_y5XOv_QhBiYBw430qzFB5MfS9AzxNBOs3f87XehC0,13539
|
| 82 |
+
fsspec/implementations/gist.py,sha256=Y6jTDrE-wuTwvpPyAQDuuOMBGxlajafKWoB1_yX6jdY,8528
|
| 83 |
+
fsspec/implementations/git.py,sha256=qBDWMz5LNllPqVjr5jf_1FuNha4P5lyQI3IlhYg-wUE,3731
|
| 84 |
+
fsspec/implementations/github.py,sha256=aCsZL8UvXZgdkcB1RUs3DdLeNrjLKcFsFYeQFDWbBFo,11653
|
| 85 |
+
fsspec/implementations/http.py,sha256=1uWwxllOjPe8mQD54IrCYQJHU1YaAXh_cDmXBk-AoQ8,30894
|
| 86 |
+
fsspec/implementations/http_sync.py,sha256=UmBqd938ebwVjYgVtzg-ysG3ZoGhIJw0wFtQAfxV3Aw,30332
|
| 87 |
+
fsspec/implementations/jupyter.py,sha256=q1PlQ66AAswGFyr8MFKWyobaV2YekMWRtqENBDQtD28,4002
|
| 88 |
+
fsspec/implementations/libarchive.py,sha256=SpIA1F-zf7kb2-VYUVuhMrXTBOhBxUXKgEW1RaAdDoA,7098
|
| 89 |
+
fsspec/implementations/local.py,sha256=jpvvSYj8RaocLB8YuHjGlWOTMJAJNTnUBj9D_Zn32BA,17216
|
| 90 |
+
fsspec/implementations/memory.py,sha256=fXUYjKF1xr4_9FX26vDCazEhmFbE7Om4xUufIOQe2vA,14088
|
| 91 |
+
fsspec/implementations/reference.py,sha256=YKLzPBF6bLpOnHY9iM0MR5JLGRi5CB6x1cWIgMb6Ahg,49974
|
| 92 |
+
fsspec/implementations/sftp.py,sha256=v7t-LpD4hEycHnw1kbepyoNgrhClshXQXitFuY4mBWE,5951
|
| 93 |
+
fsspec/implementations/smb.py,sha256=5fhu8h06nOLBPh2c48aT7WBRqh9cEcbIwtyu06wTjec,15236
|
| 94 |
+
fsspec/implementations/tar.py,sha256=adO9r_Badc4ucfApmK-mrvbv1re0_qoxwBjgnSMIrh0,4601
|
| 95 |
+
fsspec/implementations/webhdfs.py,sha256=osF2m0nhDil6sbMzYW_4DZzhxF4ygtb59XDiybd9Fyg,17589
|
| 96 |
+
fsspec/implementations/zip.py,sha256=GPDJh4UtUNJmaqijUQ0eiEZIGpwusQjkIcbhsrmLSi0,6263
|
| 97 |
+
fsspec/json.py,sha256=4EBZ-xOmRiyxmIqPIwxmDImosRQ7io7qBM2xjJPsEE4,3768
|
| 98 |
+
fsspec/mapping.py,sha256=m2ndB_gtRBXYmNJg0Ie1-BVR75TFleHmIQBzC-yWhjU,8343
|
| 99 |
+
fsspec/parquet.py,sha256=0SzfswUTc2k5nAj7xZNYPPyvUkFNXznFRXXtBRhr-iE,20506
|
| 100 |
+
fsspec/registry.py,sha256=KeDNL9HOyHX_D4D4qQGAI-Y3DQhiLeUC1VK2I81NZaE,12344
|
| 101 |
+
fsspec/spec.py,sha256=3LTaRdAhOTIPCetwPCS9HC6MR1VlcdfLVBh4mWFrXns,79674
|
| 102 |
+
fsspec/tests/abstract/__init__.py,sha256=V0-8FqQPfHlHZ3xomJ0hyWl6t1QvqsDnQFJYHeSTlEw,10197
|
| 103 |
+
fsspec/tests/abstract/__pycache__/__init__.cpython-312.pyc,,
|
| 104 |
+
fsspec/tests/abstract/__pycache__/common.cpython-312.pyc,,
|
| 105 |
+
fsspec/tests/abstract/__pycache__/copy.cpython-312.pyc,,
|
| 106 |
+
fsspec/tests/abstract/__pycache__/get.cpython-312.pyc,,
|
| 107 |
+
fsspec/tests/abstract/__pycache__/mv.cpython-312.pyc,,
|
| 108 |
+
fsspec/tests/abstract/__pycache__/open.cpython-312.pyc,,
|
| 109 |
+
fsspec/tests/abstract/__pycache__/pipe.cpython-312.pyc,,
|
| 110 |
+
fsspec/tests/abstract/__pycache__/put.cpython-312.pyc,,
|
| 111 |
+
fsspec/tests/abstract/common.py,sha256=1GQwNo5AONzAnzZj0fWgn8NJPLXALehbsuGxS3FzWVU,4973
|
| 112 |
+
fsspec/tests/abstract/copy.py,sha256=gU5-d97U3RSde35Vp4RxPY4rWwL744HiSrJ8IBOp9-8,19967
|
| 113 |
+
fsspec/tests/abstract/get.py,sha256=vNR4HztvTR7Cj56AMo7_tx7TeYz1Jgr_2Wb8Lv-UiBY,20755
|
| 114 |
+
fsspec/tests/abstract/mv.py,sha256=k8eUEBIrRrGMsBY5OOaDXdGnQUKGwDIfQyduB6YD3Ns,1982
|
| 115 |
+
fsspec/tests/abstract/open.py,sha256=Fi2PBPYLbRqysF8cFm0rwnB41kMdQVYjq8cGyDXp3BU,329
|
| 116 |
+
fsspec/tests/abstract/pipe.py,sha256=LFzIrLCB5GLXf9rzFKJmE8AdG7LQ_h4bJo70r8FLPqM,402
|
| 117 |
+
fsspec/tests/abstract/put.py,sha256=7aih17OKB_IZZh1Mkq1eBDIjobhtMQmI8x-Pw-S_aZk,21201
|
| 118 |
+
fsspec/transaction.py,sha256=xliRG6U2Zf3khG4xcw9WiB-yAoqJSHEGK_VjHOdtgo0,2398
|
| 119 |
+
fsspec/utils.py,sha256=T6x7JS-qHGdZ6hMPrT1tH6_41lHFw88g3WxgNIItYPc,24114
|
.venv/lib/python3.12/site-packages/fsspec-2026.7.0.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: hatchling 1.31.0
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py3-none-any
|
.venv/lib/python3.12/site-packages/fsspec-2026.7.0.dist-info/licenses/LICENSE
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
BSD 3-Clause License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2018, Martin Durant
|
| 4 |
+
All rights reserved.
|
| 5 |
+
|
| 6 |
+
Redistribution and use in source and binary forms, with or without
|
| 7 |
+
modification, are permitted provided that the following conditions are met:
|
| 8 |
+
|
| 9 |
+
* Redistributions of source code must retain the above copyright notice, this
|
| 10 |
+
list of conditions and the following disclaimer.
|
| 11 |
+
|
| 12 |
+
* Redistributions in binary form must reproduce the above copyright notice,
|
| 13 |
+
this list of conditions and the following disclaimer in the documentation
|
| 14 |
+
and/or other materials provided with the distribution.
|
| 15 |
+
|
| 16 |
+
* Neither the name of the copyright holder nor the names of its
|
| 17 |
+
contributors may be used to endorse or promote products derived from
|
| 18 |
+
this software without specific prior written permission.
|
| 19 |
+
|
| 20 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
| 21 |
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
| 22 |
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
| 23 |
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
| 24 |
+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
| 25 |
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
| 26 |
+
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
| 27 |
+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
| 28 |
+
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
| 29 |
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
.venv/lib/python3.12/site-packages/fsspec/caching.py
ADDED
|
@@ -0,0 +1,1025 @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|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import collections
|
| 4 |
+
import functools
|
| 5 |
+
import logging
|
| 6 |
+
import math
|
| 7 |
+
import os
|
| 8 |
+
import threading
|
| 9 |
+
from collections import OrderedDict
|
| 10 |
+
from collections.abc import Callable
|
| 11 |
+
from concurrent.futures import Future, ThreadPoolExecutor
|
| 12 |
+
from itertools import groupby
|
| 13 |
+
from operator import itemgetter
|
| 14 |
+
from typing import TYPE_CHECKING, Any, ClassVar, Generic, NamedTuple, TypeVar
|
| 15 |
+
|
| 16 |
+
if TYPE_CHECKING:
|
| 17 |
+
import mmap
|
| 18 |
+
|
| 19 |
+
from typing_extensions import ParamSpec
|
| 20 |
+
|
| 21 |
+
P = ParamSpec("P")
|
| 22 |
+
else:
|
| 23 |
+
P = TypeVar("P")
|
| 24 |
+
|
| 25 |
+
T = TypeVar("T")
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
logger = logging.getLogger("fsspec.caching")
|
| 29 |
+
|
| 30 |
+
Fetcher = Callable[[int, int], bytes] # Maps (start, end) to bytes
|
| 31 |
+
MultiFetcher = Callable[[list[int, int]], bytes] # Maps [(start, end)] to bytes
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class BaseCache:
|
| 35 |
+
"""Pass-though cache: doesn't keep anything, calls every time
|
| 36 |
+
|
| 37 |
+
Acts as base class for other cachers
|
| 38 |
+
|
| 39 |
+
Parameters
|
| 40 |
+
----------
|
| 41 |
+
blocksize: int
|
| 42 |
+
How far to read ahead in numbers of bytes
|
| 43 |
+
fetcher: func
|
| 44 |
+
Function of the form f(start, end) which gets bytes from remote as
|
| 45 |
+
specified
|
| 46 |
+
size: int
|
| 47 |
+
How big this file is
|
| 48 |
+
"""
|
| 49 |
+
|
| 50 |
+
name: ClassVar[str] = "none"
|
| 51 |
+
|
| 52 |
+
def __init__(self, blocksize: int, fetcher: Fetcher, size: int) -> None:
|
| 53 |
+
self.blocksize = blocksize
|
| 54 |
+
self.nblocks = 0
|
| 55 |
+
self.fetcher = fetcher
|
| 56 |
+
self.size = size
|
| 57 |
+
self.hit_count = 0
|
| 58 |
+
self.miss_count = 0
|
| 59 |
+
# the bytes that we actually requested
|
| 60 |
+
self.total_requested_bytes = 0
|
| 61 |
+
|
| 62 |
+
def _fetch(self, start: int | None, stop: int | None) -> bytes:
|
| 63 |
+
if start is None:
|
| 64 |
+
start = 0
|
| 65 |
+
if stop is None:
|
| 66 |
+
stop = self.size
|
| 67 |
+
if start >= self.size or start >= stop:
|
| 68 |
+
return b""
|
| 69 |
+
return self.fetcher(start, stop)
|
| 70 |
+
|
| 71 |
+
def _reset_stats(self) -> None:
|
| 72 |
+
"""Reset hit and miss counts for a more ganular report e.g. by file."""
|
| 73 |
+
self.hit_count = 0
|
| 74 |
+
self.miss_count = 0
|
| 75 |
+
self.total_requested_bytes = 0
|
| 76 |
+
|
| 77 |
+
def _log_stats(self) -> str:
|
| 78 |
+
"""Return a formatted string of the cache statistics."""
|
| 79 |
+
if self.hit_count == 0 and self.miss_count == 0:
|
| 80 |
+
# a cache that does nothing, this is for logs only
|
| 81 |
+
return ""
|
| 82 |
+
return f" , {self.name}: {self.hit_count} hits, {self.miss_count} misses, {self.total_requested_bytes} total requested bytes"
|
| 83 |
+
|
| 84 |
+
def __repr__(self) -> str:
|
| 85 |
+
# TODO: use rich for better formatting
|
| 86 |
+
return f"""
|
| 87 |
+
<{self.__class__.__name__}:
|
| 88 |
+
block size : {self.blocksize}
|
| 89 |
+
block count : {self.nblocks}
|
| 90 |
+
file size : {self.size}
|
| 91 |
+
cache hits : {self.hit_count}
|
| 92 |
+
cache misses: {self.miss_count}
|
| 93 |
+
total requested bytes: {self.total_requested_bytes}>
|
| 94 |
+
"""
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class MMapCache(BaseCache):
|
| 98 |
+
"""memory-mapped sparse file cache
|
| 99 |
+
|
| 100 |
+
Opens temporary file, which is filled blocks-wise when data is requested.
|
| 101 |
+
Ensure there is enough disc space in the temporary location.
|
| 102 |
+
|
| 103 |
+
This cache method might only work on posix
|
| 104 |
+
|
| 105 |
+
Parameters
|
| 106 |
+
----------
|
| 107 |
+
blocksize: int
|
| 108 |
+
How far to read ahead in numbers of bytes
|
| 109 |
+
fetcher: Fetcher
|
| 110 |
+
Function of the form f(start, end) which gets bytes from remote as
|
| 111 |
+
specified
|
| 112 |
+
size: int
|
| 113 |
+
How big this file is
|
| 114 |
+
location: str
|
| 115 |
+
Where to create the temporary file. If None, a temporary file is
|
| 116 |
+
created using tempfile.TemporaryFile().
|
| 117 |
+
blocks: set[int]
|
| 118 |
+
Set of block numbers that have already been fetched. If None, an empty
|
| 119 |
+
set is created.
|
| 120 |
+
multi_fetcher: MultiFetcher
|
| 121 |
+
Function of the form f([(start, end)]) which gets bytes from remote
|
| 122 |
+
as specified. This function is used to fetch multiple blocks at once.
|
| 123 |
+
If not specified, the fetcher function is used instead.
|
| 124 |
+
"""
|
| 125 |
+
|
| 126 |
+
name = "mmap"
|
| 127 |
+
|
| 128 |
+
def __init__(
|
| 129 |
+
self,
|
| 130 |
+
blocksize: int,
|
| 131 |
+
fetcher: Fetcher,
|
| 132 |
+
size: int,
|
| 133 |
+
location: str | None = None,
|
| 134 |
+
blocks: set[int] | None = None,
|
| 135 |
+
multi_fetcher: MultiFetcher | None = None,
|
| 136 |
+
) -> None:
|
| 137 |
+
super().__init__(blocksize, fetcher, size)
|
| 138 |
+
self.blocks = set() if blocks is None else blocks
|
| 139 |
+
self.location = location
|
| 140 |
+
self.multi_fetcher = multi_fetcher
|
| 141 |
+
self.cache = self._makefile()
|
| 142 |
+
|
| 143 |
+
def _makefile(self) -> mmap.mmap | bytearray:
|
| 144 |
+
import mmap
|
| 145 |
+
import tempfile
|
| 146 |
+
|
| 147 |
+
if self.size == 0:
|
| 148 |
+
return bytearray()
|
| 149 |
+
|
| 150 |
+
# posix version
|
| 151 |
+
if self.location is None or not os.path.exists(self.location):
|
| 152 |
+
if self.location is None:
|
| 153 |
+
fd = tempfile.TemporaryFile()
|
| 154 |
+
self.blocks = set()
|
| 155 |
+
else:
|
| 156 |
+
fd = open(self.location, "wb+")
|
| 157 |
+
fd.seek(self.size - 1)
|
| 158 |
+
fd.write(b"1")
|
| 159 |
+
fd.flush()
|
| 160 |
+
else:
|
| 161 |
+
fd = open(self.location, "r+b")
|
| 162 |
+
|
| 163 |
+
return mmap.mmap(fd.fileno(), self.size)
|
| 164 |
+
|
| 165 |
+
def _fetch(self, start: int | None, end: int | None) -> bytes:
|
| 166 |
+
logger.debug(f"MMap cache fetching {start}-{end}")
|
| 167 |
+
if start is None:
|
| 168 |
+
start = 0
|
| 169 |
+
if end is None:
|
| 170 |
+
end = self.size
|
| 171 |
+
if start >= self.size or start >= end:
|
| 172 |
+
return b""
|
| 173 |
+
start_block = start // self.blocksize
|
| 174 |
+
end_block = end // self.blocksize
|
| 175 |
+
block_range = range(start_block, end_block + 1)
|
| 176 |
+
# Determine which blocks need to be fetched. This sequence is sorted by construction.
|
| 177 |
+
need = (i for i in block_range if i not in self.blocks)
|
| 178 |
+
# Count the number of blocks already cached
|
| 179 |
+
self.hit_count += sum(1 for i in block_range if i in self.blocks)
|
| 180 |
+
|
| 181 |
+
ranges = []
|
| 182 |
+
|
| 183 |
+
# Consolidate needed blocks.
|
| 184 |
+
# Algorithm adapted from Python 2.x itertools documentation.
|
| 185 |
+
# We are grouping an enumerated sequence of blocks. By comparing when the difference
|
| 186 |
+
# between an ascending range (provided by enumerate) and the needed block numbers
|
| 187 |
+
# we can detect when the block number skips values. The key computes this difference.
|
| 188 |
+
# Whenever the difference changes, we know that we have previously cached block(s),
|
| 189 |
+
# and a new group is started. In other words, this algorithm neatly groups
|
| 190 |
+
# runs of consecutive block numbers so they can be fetched together.
|
| 191 |
+
for _, _blocks in groupby(enumerate(need), key=lambda x: x[0] - x[1]):
|
| 192 |
+
# Extract the blocks from the enumerated sequence
|
| 193 |
+
_blocks = tuple(map(itemgetter(1), _blocks))
|
| 194 |
+
# Compute start of first block
|
| 195 |
+
sstart = _blocks[0] * self.blocksize
|
| 196 |
+
# Compute the end of the last block. Last block may not be full size.
|
| 197 |
+
send = min(_blocks[-1] * self.blocksize + self.blocksize, self.size)
|
| 198 |
+
|
| 199 |
+
# Fetch bytes (could be multiple consecutive blocks)
|
| 200 |
+
self.total_requested_bytes += send - sstart
|
| 201 |
+
logger.debug(
|
| 202 |
+
f"MMap get blocks {_blocks[0]}-{_blocks[-1]} ({sstart}-{send})"
|
| 203 |
+
)
|
| 204 |
+
ranges.append((sstart, send))
|
| 205 |
+
|
| 206 |
+
# Update set of cached blocks
|
| 207 |
+
self.blocks.update(_blocks)
|
| 208 |
+
# Update cache statistics with number of blocks we had to cache
|
| 209 |
+
self.miss_count += len(_blocks)
|
| 210 |
+
|
| 211 |
+
if not ranges:
|
| 212 |
+
return self.cache[start:end]
|
| 213 |
+
|
| 214 |
+
if self.multi_fetcher:
|
| 215 |
+
logger.debug(f"MMap get blocks {ranges}")
|
| 216 |
+
for idx, r in enumerate(self.multi_fetcher(ranges)):
|
| 217 |
+
sstart, send = ranges[idx]
|
| 218 |
+
logger.debug(f"MMap copy block ({sstart}-{send}")
|
| 219 |
+
self.cache[sstart:send] = r
|
| 220 |
+
else:
|
| 221 |
+
for sstart, send in ranges:
|
| 222 |
+
logger.debug(f"MMap get block ({sstart}-{send}")
|
| 223 |
+
self.cache[sstart:send] = self.fetcher(sstart, send)
|
| 224 |
+
|
| 225 |
+
return self.cache[start:end]
|
| 226 |
+
|
| 227 |
+
def __getstate__(self) -> dict[str, Any]:
|
| 228 |
+
state = self.__dict__.copy()
|
| 229 |
+
# Remove the unpicklable entries.
|
| 230 |
+
del state["cache"]
|
| 231 |
+
return state
|
| 232 |
+
|
| 233 |
+
def __setstate__(self, state: dict[str, Any]) -> None:
|
| 234 |
+
# Restore instance attributes
|
| 235 |
+
self.__dict__.update(state)
|
| 236 |
+
self.cache = self._makefile()
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
class ReadAheadCache(BaseCache):
|
| 240 |
+
"""Cache which reads only when we get beyond a block of data
|
| 241 |
+
|
| 242 |
+
This is a much simpler version of BytesCache, and does not attempt to
|
| 243 |
+
fill holes in the cache or keep fragments alive. It is best suited to
|
| 244 |
+
many small reads in a sequential order (e.g., reading lines from a file).
|
| 245 |
+
"""
|
| 246 |
+
|
| 247 |
+
name = "readahead"
|
| 248 |
+
|
| 249 |
+
def __init__(self, blocksize: int, fetcher: Fetcher, size: int) -> None:
|
| 250 |
+
super().__init__(blocksize, fetcher, size)
|
| 251 |
+
self.cache = b""
|
| 252 |
+
self.start = 0
|
| 253 |
+
self.end = 0
|
| 254 |
+
|
| 255 |
+
def _fetch(self, start: int | None, end: int | None) -> bytes:
|
| 256 |
+
if start is None:
|
| 257 |
+
start = 0
|
| 258 |
+
if end is None or end > self.size:
|
| 259 |
+
end = self.size
|
| 260 |
+
if start >= self.size or start >= end:
|
| 261 |
+
return b""
|
| 262 |
+
l = end - start
|
| 263 |
+
if start >= self.start and end <= self.end:
|
| 264 |
+
# cache hit
|
| 265 |
+
self.hit_count += 1
|
| 266 |
+
return self.cache[start - self.start : end - self.start]
|
| 267 |
+
elif self.start <= start < self.end:
|
| 268 |
+
# partial hit
|
| 269 |
+
self.miss_count += 1
|
| 270 |
+
part = self.cache[start - self.start :]
|
| 271 |
+
l -= len(part)
|
| 272 |
+
start = self.end
|
| 273 |
+
else:
|
| 274 |
+
# miss
|
| 275 |
+
self.miss_count += 1
|
| 276 |
+
part = b""
|
| 277 |
+
end = min(self.size, end + self.blocksize)
|
| 278 |
+
self.total_requested_bytes += end - start
|
| 279 |
+
self.cache = self.fetcher(start, end) # new block replaces old
|
| 280 |
+
self.start = start
|
| 281 |
+
self.end = self.start + len(self.cache)
|
| 282 |
+
return part + self.cache[:l]
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
class FirstChunkCache(BaseCache):
|
| 286 |
+
"""Caches the first block of a file only
|
| 287 |
+
|
| 288 |
+
This may be useful for file types where the metadata is stored in the header,
|
| 289 |
+
but is randomly accessed.
|
| 290 |
+
"""
|
| 291 |
+
|
| 292 |
+
name = "first"
|
| 293 |
+
|
| 294 |
+
def __init__(self, blocksize: int, fetcher: Fetcher, size: int) -> None:
|
| 295 |
+
if blocksize > size:
|
| 296 |
+
# this will buffer the whole thing
|
| 297 |
+
blocksize = size
|
| 298 |
+
super().__init__(blocksize, fetcher, size)
|
| 299 |
+
self.cache: bytes | None = None
|
| 300 |
+
|
| 301 |
+
def _fetch(self, start: int | None, end: int | None) -> bytes:
|
| 302 |
+
start = start or 0
|
| 303 |
+
if start > self.size:
|
| 304 |
+
logger.debug("FirstChunkCache: requested start > file size")
|
| 305 |
+
return b""
|
| 306 |
+
|
| 307 |
+
if end is None:
|
| 308 |
+
end = self.size
|
| 309 |
+
end = min(end, self.size)
|
| 310 |
+
|
| 311 |
+
if start < self.blocksize:
|
| 312 |
+
if self.cache is None:
|
| 313 |
+
self.miss_count += 1
|
| 314 |
+
if end > self.blocksize:
|
| 315 |
+
self.total_requested_bytes += end
|
| 316 |
+
data = self.fetcher(0, end)
|
| 317 |
+
self.cache = data[: self.blocksize]
|
| 318 |
+
return data[start:]
|
| 319 |
+
self.cache = self.fetcher(0, self.blocksize)
|
| 320 |
+
self.total_requested_bytes += self.blocksize
|
| 321 |
+
part = self.cache[start:end]
|
| 322 |
+
if end > self.blocksize:
|
| 323 |
+
self.total_requested_bytes += end - self.blocksize
|
| 324 |
+
part += self.fetcher(self.blocksize, end)
|
| 325 |
+
self.hit_count += 1
|
| 326 |
+
return part
|
| 327 |
+
else:
|
| 328 |
+
self.miss_count += 1
|
| 329 |
+
self.total_requested_bytes += end - start
|
| 330 |
+
return self.fetcher(start, end)
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
class BlockCache(BaseCache):
|
| 334 |
+
"""
|
| 335 |
+
Cache holding memory as a set of blocks.
|
| 336 |
+
|
| 337 |
+
Requests are only ever made ``blocksize`` at a time, and are
|
| 338 |
+
stored in an LRU cache. The least recently accessed block is
|
| 339 |
+
discarded when more than ``maxblocks`` are stored.
|
| 340 |
+
|
| 341 |
+
Parameters
|
| 342 |
+
----------
|
| 343 |
+
blocksize : int
|
| 344 |
+
The number of bytes to store in each block.
|
| 345 |
+
Requests are only ever made for ``blocksize``, so this
|
| 346 |
+
should balance the overhead of making a request against
|
| 347 |
+
the granularity of the blocks.
|
| 348 |
+
fetcher : Callable
|
| 349 |
+
size : int
|
| 350 |
+
The total size of the file being cached.
|
| 351 |
+
maxblocks : int
|
| 352 |
+
The maximum number of blocks to cache for. The maximum memory
|
| 353 |
+
use for this cache is then ``blocksize * maxblocks``.
|
| 354 |
+
"""
|
| 355 |
+
|
| 356 |
+
name = "blockcache"
|
| 357 |
+
|
| 358 |
+
def __init__(
|
| 359 |
+
self, blocksize: int, fetcher: Fetcher, size: int, maxblocks: int = 32
|
| 360 |
+
) -> None:
|
| 361 |
+
super().__init__(blocksize, fetcher, size)
|
| 362 |
+
self.nblocks = math.ceil(size / blocksize)
|
| 363 |
+
self.maxblocks = maxblocks
|
| 364 |
+
self._fetch_block_cached = functools.lru_cache(maxblocks)(self._fetch_block)
|
| 365 |
+
|
| 366 |
+
def cache_info(self):
|
| 367 |
+
"""
|
| 368 |
+
The statistics on the block cache.
|
| 369 |
+
|
| 370 |
+
Returns
|
| 371 |
+
-------
|
| 372 |
+
NamedTuple
|
| 373 |
+
Returned directly from the LRU Cache used internally.
|
| 374 |
+
"""
|
| 375 |
+
return self._fetch_block_cached.cache_info()
|
| 376 |
+
|
| 377 |
+
def __getstate__(self) -> dict[str, Any]:
|
| 378 |
+
state = self.__dict__
|
| 379 |
+
del state["_fetch_block_cached"]
|
| 380 |
+
return state
|
| 381 |
+
|
| 382 |
+
def __setstate__(self, state: dict[str, Any]) -> None:
|
| 383 |
+
self.__dict__.update(state)
|
| 384 |
+
self._fetch_block_cached = functools.lru_cache(state["maxblocks"])(
|
| 385 |
+
self._fetch_block
|
| 386 |
+
)
|
| 387 |
+
|
| 388 |
+
def _fetch(self, start: int | None, end: int | None) -> bytes:
|
| 389 |
+
if start is None:
|
| 390 |
+
start = 0
|
| 391 |
+
if end is None or end > self.size:
|
| 392 |
+
end = self.size
|
| 393 |
+
if start >= self.size or start >= end:
|
| 394 |
+
return b""
|
| 395 |
+
|
| 396 |
+
return self._read_cache(
|
| 397 |
+
start, end, start // self.blocksize, (end - 1) // self.blocksize
|
| 398 |
+
)
|
| 399 |
+
|
| 400 |
+
def _fetch_block(self, block_number: int) -> bytes:
|
| 401 |
+
"""
|
| 402 |
+
Fetch the block of data for `block_number`.
|
| 403 |
+
"""
|
| 404 |
+
if block_number > self.nblocks:
|
| 405 |
+
raise ValueError(
|
| 406 |
+
f"'block_number={block_number}' is greater than "
|
| 407 |
+
f"the number of blocks ({self.nblocks})"
|
| 408 |
+
)
|
| 409 |
+
|
| 410 |
+
start = block_number * self.blocksize
|
| 411 |
+
end = start + self.blocksize
|
| 412 |
+
self.total_requested_bytes += end - start
|
| 413 |
+
self.miss_count += 1
|
| 414 |
+
logger.info("BlockCache fetching block %d", block_number)
|
| 415 |
+
block_contents = super()._fetch(start, end)
|
| 416 |
+
return block_contents
|
| 417 |
+
|
| 418 |
+
def _read_cache(
|
| 419 |
+
self, start: int, end: int, start_block_number: int, end_block_number: int
|
| 420 |
+
) -> bytes:
|
| 421 |
+
"""
|
| 422 |
+
Read from our block cache.
|
| 423 |
+
|
| 424 |
+
Parameters
|
| 425 |
+
----------
|
| 426 |
+
start, end : int
|
| 427 |
+
The start and end byte positions.
|
| 428 |
+
start_block_number, end_block_number : int
|
| 429 |
+
The start and end block numbers.
|
| 430 |
+
"""
|
| 431 |
+
start_pos = start % self.blocksize
|
| 432 |
+
end_pos = end % self.blocksize
|
| 433 |
+
if end_pos == 0:
|
| 434 |
+
end_pos = self.blocksize
|
| 435 |
+
|
| 436 |
+
self.hit_count += 1
|
| 437 |
+
if start_block_number == end_block_number:
|
| 438 |
+
block: bytes = self._fetch_block_cached(start_block_number)
|
| 439 |
+
return block[start_pos:end_pos]
|
| 440 |
+
|
| 441 |
+
else:
|
| 442 |
+
# read from the initial
|
| 443 |
+
out = [self._fetch_block_cached(start_block_number)[start_pos:]]
|
| 444 |
+
|
| 445 |
+
# intermediate blocks
|
| 446 |
+
# Note: it'd be nice to combine these into one big request. However
|
| 447 |
+
# that doesn't play nicely with our LRU cache.
|
| 448 |
+
out.extend(
|
| 449 |
+
map(
|
| 450 |
+
self._fetch_block_cached,
|
| 451 |
+
range(start_block_number + 1, end_block_number),
|
| 452 |
+
)
|
| 453 |
+
)
|
| 454 |
+
|
| 455 |
+
# final block
|
| 456 |
+
out.append(self._fetch_block_cached(end_block_number)[:end_pos])
|
| 457 |
+
|
| 458 |
+
return b"".join(out)
|
| 459 |
+
|
| 460 |
+
|
| 461 |
+
class BytesCache(BaseCache):
|
| 462 |
+
"""Cache which holds data in a in-memory bytes object
|
| 463 |
+
|
| 464 |
+
Implements read-ahead by the block size, for semi-random reads progressing
|
| 465 |
+
through the file.
|
| 466 |
+
|
| 467 |
+
Parameters
|
| 468 |
+
----------
|
| 469 |
+
trim: bool
|
| 470 |
+
As we read more data, whether to discard the start of the buffer when
|
| 471 |
+
we are more than a blocksize ahead of it.
|
| 472 |
+
"""
|
| 473 |
+
|
| 474 |
+
name: ClassVar[str] = "bytes"
|
| 475 |
+
|
| 476 |
+
def __init__(
|
| 477 |
+
self, blocksize: int, fetcher: Fetcher, size: int, trim: bool = True
|
| 478 |
+
) -> None:
|
| 479 |
+
super().__init__(blocksize, fetcher, size)
|
| 480 |
+
self.cache = b""
|
| 481 |
+
self.start: int | None = None
|
| 482 |
+
self.end: int | None = None
|
| 483 |
+
self.trim = trim
|
| 484 |
+
|
| 485 |
+
def _fetch(self, start: int | None, end: int | None) -> bytes:
|
| 486 |
+
# TODO: only set start/end after fetch, in case it fails?
|
| 487 |
+
# is this where retry logic might go?
|
| 488 |
+
if start is None:
|
| 489 |
+
start = 0
|
| 490 |
+
if end is None:
|
| 491 |
+
end = self.size
|
| 492 |
+
if start >= self.size or start >= end:
|
| 493 |
+
return b""
|
| 494 |
+
if (
|
| 495 |
+
self.start is not None
|
| 496 |
+
and start >= self.start
|
| 497 |
+
and self.end is not None
|
| 498 |
+
and end < self.end
|
| 499 |
+
):
|
| 500 |
+
# cache hit: we have all the required data
|
| 501 |
+
offset = start - self.start
|
| 502 |
+
self.hit_count += 1
|
| 503 |
+
return self.cache[offset : offset + end - start]
|
| 504 |
+
|
| 505 |
+
if self.blocksize:
|
| 506 |
+
bend = min(self.size, end + self.blocksize)
|
| 507 |
+
else:
|
| 508 |
+
bend = end
|
| 509 |
+
|
| 510 |
+
if bend == start or start > self.size:
|
| 511 |
+
return b""
|
| 512 |
+
|
| 513 |
+
if (self.start is None or start < self.start) and (
|
| 514 |
+
self.end is None or end > self.end
|
| 515 |
+
):
|
| 516 |
+
# First read, or extending both before and after
|
| 517 |
+
self.total_requested_bytes += bend - start
|
| 518 |
+
self.miss_count += 1
|
| 519 |
+
self.cache = self.fetcher(start, bend)
|
| 520 |
+
self.start = start
|
| 521 |
+
else:
|
| 522 |
+
assert self.start is not None
|
| 523 |
+
assert self.end is not None
|
| 524 |
+
self.miss_count += 1
|
| 525 |
+
|
| 526 |
+
if start < self.start:
|
| 527 |
+
if self.end is None or self.end - end > self.blocksize:
|
| 528 |
+
self.total_requested_bytes += bend - start
|
| 529 |
+
self.cache = self.fetcher(start, bend)
|
| 530 |
+
self.start = start
|
| 531 |
+
else:
|
| 532 |
+
self.total_requested_bytes += self.start - start
|
| 533 |
+
new = self.fetcher(start, self.start)
|
| 534 |
+
self.start = start
|
| 535 |
+
self.cache = new + self.cache
|
| 536 |
+
elif self.end is not None and bend > self.end:
|
| 537 |
+
if self.end > self.size:
|
| 538 |
+
pass
|
| 539 |
+
elif end - self.end > self.blocksize:
|
| 540 |
+
self.total_requested_bytes += bend - start
|
| 541 |
+
self.cache = self.fetcher(start, bend)
|
| 542 |
+
self.start = start
|
| 543 |
+
else:
|
| 544 |
+
self.total_requested_bytes += bend - self.end
|
| 545 |
+
new = self.fetcher(self.end, bend)
|
| 546 |
+
self.cache = self.cache + new
|
| 547 |
+
|
| 548 |
+
self.end = self.start + len(self.cache)
|
| 549 |
+
offset = start - self.start
|
| 550 |
+
out = self.cache[offset : offset + end - start]
|
| 551 |
+
if self.trim:
|
| 552 |
+
num = (self.end - self.start) // (self.blocksize + 1)
|
| 553 |
+
if num > 1:
|
| 554 |
+
self.start += self.blocksize * num
|
| 555 |
+
self.cache = self.cache[self.blocksize * num :]
|
| 556 |
+
return out
|
| 557 |
+
|
| 558 |
+
def __len__(self) -> int:
|
| 559 |
+
return len(self.cache)
|
| 560 |
+
|
| 561 |
+
|
| 562 |
+
class AllBytes(BaseCache):
|
| 563 |
+
"""Cache entire contents of the file"""
|
| 564 |
+
|
| 565 |
+
name: ClassVar[str] = "all"
|
| 566 |
+
|
| 567 |
+
def __init__(
|
| 568 |
+
self,
|
| 569 |
+
blocksize: int | None = None,
|
| 570 |
+
fetcher: Fetcher | None = None,
|
| 571 |
+
size: int | None = None,
|
| 572 |
+
data: bytes | None = None,
|
| 573 |
+
) -> None:
|
| 574 |
+
super().__init__(blocksize, fetcher, size) # type: ignore[arg-type]
|
| 575 |
+
if data is None:
|
| 576 |
+
self.miss_count += 1
|
| 577 |
+
self.total_requested_bytes += self.size
|
| 578 |
+
data = self.fetcher(0, self.size)
|
| 579 |
+
self.data = data
|
| 580 |
+
|
| 581 |
+
def _fetch(self, start: int | None, stop: int | None) -> bytes:
|
| 582 |
+
self.hit_count += 1
|
| 583 |
+
return self.data[start:stop]
|
| 584 |
+
|
| 585 |
+
|
| 586 |
+
class KnownPartsOfAFile(BaseCache):
|
| 587 |
+
"""
|
| 588 |
+
Cache holding known file parts.
|
| 589 |
+
|
| 590 |
+
Parameters
|
| 591 |
+
----------
|
| 592 |
+
blocksize: int
|
| 593 |
+
How far to read ahead in numbers of bytes
|
| 594 |
+
fetcher: func
|
| 595 |
+
Function of the form f(start, end) which gets bytes from remote as
|
| 596 |
+
specified
|
| 597 |
+
size: int
|
| 598 |
+
How big this file is
|
| 599 |
+
data: dict
|
| 600 |
+
A dictionary mapping explicit `(start, stop)` file-offset tuples
|
| 601 |
+
with known bytes.
|
| 602 |
+
strict: bool, default True
|
| 603 |
+
Whether to fetch reads that go beyond a known byte-range boundary.
|
| 604 |
+
If `False`, any read that ends outside a known part will be zero
|
| 605 |
+
padded. Note that zero padding will not be used for reads that
|
| 606 |
+
begin outside a known byte-range.
|
| 607 |
+
"""
|
| 608 |
+
|
| 609 |
+
name: ClassVar[str] = "parts"
|
| 610 |
+
|
| 611 |
+
def __init__(
|
| 612 |
+
self,
|
| 613 |
+
blocksize: int,
|
| 614 |
+
fetcher: Fetcher,
|
| 615 |
+
size: int,
|
| 616 |
+
data: dict[tuple[int, int], bytes] | None = None,
|
| 617 |
+
strict: bool = False,
|
| 618 |
+
**_: Any,
|
| 619 |
+
):
|
| 620 |
+
super().__init__(blocksize, fetcher, size)
|
| 621 |
+
self.strict = strict
|
| 622 |
+
|
| 623 |
+
# simple consolidation of contiguous blocks
|
| 624 |
+
if data:
|
| 625 |
+
old_offsets = sorted(data.keys())
|
| 626 |
+
offsets = [old_offsets[0]]
|
| 627 |
+
blocks = [data.pop(old_offsets[0])]
|
| 628 |
+
for start, stop in old_offsets[1:]:
|
| 629 |
+
start0, stop0 = offsets[-1]
|
| 630 |
+
if start == stop0:
|
| 631 |
+
offsets[-1] = (start0, stop)
|
| 632 |
+
blocks[-1] += data.pop((start, stop))
|
| 633 |
+
else:
|
| 634 |
+
offsets.append((start, stop))
|
| 635 |
+
blocks.append(data.pop((start, stop)))
|
| 636 |
+
|
| 637 |
+
self.data = dict(zip(offsets, blocks))
|
| 638 |
+
else:
|
| 639 |
+
self.data = {}
|
| 640 |
+
|
| 641 |
+
@property
|
| 642 |
+
def size(self):
|
| 643 |
+
return sum(_[1] - _[0] for _ in self.data)
|
| 644 |
+
|
| 645 |
+
@size.setter
|
| 646 |
+
def size(self, value):
|
| 647 |
+
pass
|
| 648 |
+
|
| 649 |
+
@property
|
| 650 |
+
def nblocks(self):
|
| 651 |
+
return len(self.data)
|
| 652 |
+
|
| 653 |
+
@nblocks.setter
|
| 654 |
+
def nblocks(self, value):
|
| 655 |
+
pass
|
| 656 |
+
|
| 657 |
+
def _fetch(self, start: int | None, stop: int | None) -> bytes:
|
| 658 |
+
logger.debug("Known parts request %s %s", start, stop)
|
| 659 |
+
if start is None:
|
| 660 |
+
start = 0
|
| 661 |
+
if stop is None:
|
| 662 |
+
stop = self.size
|
| 663 |
+
self.total_requested_bytes += stop - start
|
| 664 |
+
out = b""
|
| 665 |
+
started = False
|
| 666 |
+
loc_old = 0
|
| 667 |
+
for loc0, loc1 in sorted(self.data):
|
| 668 |
+
if (loc0 <= start < loc1) and (loc0 <= stop <= loc1):
|
| 669 |
+
# entirely within the block
|
| 670 |
+
off = start - loc0
|
| 671 |
+
self.hit_count += 1
|
| 672 |
+
return self.data[(loc0, loc1)][off : off + stop - start]
|
| 673 |
+
if stop <= loc0:
|
| 674 |
+
break
|
| 675 |
+
if started and loc0 > loc_old:
|
| 676 |
+
# a gap where we need data
|
| 677 |
+
self.miss_count += 1
|
| 678 |
+
if self.strict:
|
| 679 |
+
raise ValueError
|
| 680 |
+
out += b"\x00" * (loc0 - loc_old)
|
| 681 |
+
if loc0 <= start < loc1:
|
| 682 |
+
# found the start
|
| 683 |
+
self.hit_count += 1
|
| 684 |
+
off = start - loc0
|
| 685 |
+
out = self.data[(loc0, loc1)][off : off + stop - start]
|
| 686 |
+
started = True
|
| 687 |
+
elif start < loc0 and stop > loc1:
|
| 688 |
+
# the whole block
|
| 689 |
+
self.hit_count += 1
|
| 690 |
+
out += self.data[(loc0, loc1)]
|
| 691 |
+
elif loc0 <= stop <= loc1:
|
| 692 |
+
# end block
|
| 693 |
+
self.hit_count += 1
|
| 694 |
+
out = out + self.data[(loc0, loc1)][: stop - loc0]
|
| 695 |
+
return out
|
| 696 |
+
loc_old = loc1
|
| 697 |
+
self.miss_count += 1
|
| 698 |
+
if started and not self.strict:
|
| 699 |
+
out = out + b"\x00" * (stop - loc_old)
|
| 700 |
+
return out
|
| 701 |
+
raise ValueError
|
| 702 |
+
|
| 703 |
+
|
| 704 |
+
class UpdatableLRU(Generic[P, T]):
|
| 705 |
+
"""
|
| 706 |
+
Custom implementation of LRU cache that allows updating keys
|
| 707 |
+
|
| 708 |
+
Used by BackgroundBlockCache
|
| 709 |
+
"""
|
| 710 |
+
|
| 711 |
+
class CacheInfo(NamedTuple):
|
| 712 |
+
hits: int
|
| 713 |
+
misses: int
|
| 714 |
+
maxsize: int
|
| 715 |
+
currsize: int
|
| 716 |
+
|
| 717 |
+
def __init__(self, func: Callable[P, T], max_size: int = 128) -> None:
|
| 718 |
+
self._cache: OrderedDict[Any, T] = collections.OrderedDict()
|
| 719 |
+
self._func = func
|
| 720 |
+
self._max_size = max_size
|
| 721 |
+
self._hits = 0
|
| 722 |
+
self._misses = 0
|
| 723 |
+
self._lock = threading.Lock()
|
| 724 |
+
|
| 725 |
+
def __call__(self, *args: P.args, **kwargs: P.kwargs) -> T:
|
| 726 |
+
if kwargs:
|
| 727 |
+
raise TypeError(f"Got unexpected keyword argument {kwargs.keys()}")
|
| 728 |
+
with self._lock:
|
| 729 |
+
if args in self._cache:
|
| 730 |
+
self._cache.move_to_end(args)
|
| 731 |
+
self._hits += 1
|
| 732 |
+
return self._cache[args]
|
| 733 |
+
|
| 734 |
+
result = self._func(*args, **kwargs)
|
| 735 |
+
|
| 736 |
+
with self._lock:
|
| 737 |
+
self._cache[args] = result
|
| 738 |
+
self._misses += 1
|
| 739 |
+
if len(self._cache) > self._max_size:
|
| 740 |
+
self._cache.popitem(last=False)
|
| 741 |
+
|
| 742 |
+
return result
|
| 743 |
+
|
| 744 |
+
def is_key_cached(self, *args: Any) -> bool:
|
| 745 |
+
with self._lock:
|
| 746 |
+
return args in self._cache
|
| 747 |
+
|
| 748 |
+
def add_key(self, result: T, *args: Any) -> None:
|
| 749 |
+
with self._lock:
|
| 750 |
+
self._cache[args] = result
|
| 751 |
+
if len(self._cache) > self._max_size:
|
| 752 |
+
self._cache.popitem(last=False)
|
| 753 |
+
|
| 754 |
+
def cache_info(self) -> UpdatableLRU.CacheInfo:
|
| 755 |
+
with self._lock:
|
| 756 |
+
return self.CacheInfo(
|
| 757 |
+
maxsize=self._max_size,
|
| 758 |
+
currsize=len(self._cache),
|
| 759 |
+
hits=self._hits,
|
| 760 |
+
misses=self._misses,
|
| 761 |
+
)
|
| 762 |
+
|
| 763 |
+
|
| 764 |
+
class BackgroundBlockCache(BaseCache):
|
| 765 |
+
"""
|
| 766 |
+
Cache holding memory as a set of blocks with pre-loading of
|
| 767 |
+
the next block in the background.
|
| 768 |
+
|
| 769 |
+
Requests are only ever made ``blocksize`` at a time, and are
|
| 770 |
+
stored in an LRU cache. The least recently accessed block is
|
| 771 |
+
discarded when more than ``maxblocks`` are stored. If the
|
| 772 |
+
next block is not in cache, it is loaded in a separate thread
|
| 773 |
+
in non-blocking way.
|
| 774 |
+
|
| 775 |
+
Parameters
|
| 776 |
+
----------
|
| 777 |
+
blocksize : int
|
| 778 |
+
The number of bytes to store in each block.
|
| 779 |
+
Requests are only ever made for ``blocksize``, so this
|
| 780 |
+
should balance the overhead of making a request against
|
| 781 |
+
the granularity of the blocks.
|
| 782 |
+
fetcher : Callable
|
| 783 |
+
size : int
|
| 784 |
+
The total size of the file being cached.
|
| 785 |
+
maxblocks : int
|
| 786 |
+
The maximum number of blocks to cache for. The maximum memory
|
| 787 |
+
use for this cache is then ``blocksize * maxblocks``.
|
| 788 |
+
"""
|
| 789 |
+
|
| 790 |
+
name: ClassVar[str] = "background"
|
| 791 |
+
|
| 792 |
+
def __init__(
|
| 793 |
+
self, blocksize: int, fetcher: Fetcher, size: int, maxblocks: int = 32
|
| 794 |
+
) -> None:
|
| 795 |
+
super().__init__(blocksize, fetcher, size)
|
| 796 |
+
self.nblocks = math.ceil(size / blocksize)
|
| 797 |
+
self.maxblocks = maxblocks
|
| 798 |
+
self._fetch_block_cached = UpdatableLRU(self._fetch_block, maxblocks)
|
| 799 |
+
|
| 800 |
+
self._thread_executor = ThreadPoolExecutor(max_workers=1)
|
| 801 |
+
self._fetch_future_block_number: int | None = None
|
| 802 |
+
self._fetch_future: Future[bytes] | None = None
|
| 803 |
+
self._fetch_future_lock = threading.Lock()
|
| 804 |
+
self._closed = False
|
| 805 |
+
|
| 806 |
+
def cache_info(self) -> UpdatableLRU.CacheInfo:
|
| 807 |
+
"""
|
| 808 |
+
The statistics on the block cache.
|
| 809 |
+
|
| 810 |
+
Returns
|
| 811 |
+
-------
|
| 812 |
+
NamedTuple
|
| 813 |
+
Returned directly from the LRU Cache used internally.
|
| 814 |
+
"""
|
| 815 |
+
return self._fetch_block_cached.cache_info()
|
| 816 |
+
|
| 817 |
+
def close(self) -> None:
|
| 818 |
+
"""Cancel pending work and shut down the background worker."""
|
| 819 |
+
with self._fetch_future_lock:
|
| 820 |
+
if self._closed:
|
| 821 |
+
return
|
| 822 |
+
self._closed = True
|
| 823 |
+
future = self._fetch_future
|
| 824 |
+
self._fetch_future = None
|
| 825 |
+
self._fetch_future_block_number = None
|
| 826 |
+
|
| 827 |
+
if future is not None:
|
| 828 |
+
future.cancel()
|
| 829 |
+
self._thread_executor.shutdown(wait=True, cancel_futures=True)
|
| 830 |
+
|
| 831 |
+
# UpdatableLRU stores a bound method and otherwise forms a reference cycle.
|
| 832 |
+
del self._fetch_block_cached
|
| 833 |
+
|
| 834 |
+
def __getstate__(self) -> dict[str, Any]:
|
| 835 |
+
state = self.__dict__
|
| 836 |
+
del state["_fetch_block_cached"]
|
| 837 |
+
del state["_thread_executor"]
|
| 838 |
+
del state["_fetch_future_block_number"]
|
| 839 |
+
del state["_fetch_future"]
|
| 840 |
+
del state["_fetch_future_lock"]
|
| 841 |
+
return state
|
| 842 |
+
|
| 843 |
+
def __setstate__(self, state) -> None:
|
| 844 |
+
self.__dict__.update(state)
|
| 845 |
+
self._fetch_block_cached = UpdatableLRU(self._fetch_block, state["maxblocks"])
|
| 846 |
+
self._thread_executor = ThreadPoolExecutor(max_workers=1)
|
| 847 |
+
self._fetch_future_block_number = None
|
| 848 |
+
self._fetch_future = None
|
| 849 |
+
self._fetch_future_lock = threading.Lock()
|
| 850 |
+
self._closed = False
|
| 851 |
+
|
| 852 |
+
def _fetch(self, start: int | None, end: int | None) -> bytes:
|
| 853 |
+
if start is None:
|
| 854 |
+
start = 0
|
| 855 |
+
if end is None or end > self.size:
|
| 856 |
+
end = self.size
|
| 857 |
+
if start >= self.size or start >= end:
|
| 858 |
+
return b""
|
| 859 |
+
|
| 860 |
+
# byte position -> block numbers
|
| 861 |
+
start_block_number = start // self.blocksize
|
| 862 |
+
end_block_number = end // self.blocksize
|
| 863 |
+
|
| 864 |
+
fetch_future_block_number = None
|
| 865 |
+
fetch_future = None
|
| 866 |
+
with self._fetch_future_lock:
|
| 867 |
+
# Background thread is running. Check we we can or must join it.
|
| 868 |
+
if self._fetch_future is not None:
|
| 869 |
+
assert self._fetch_future_block_number is not None
|
| 870 |
+
if self._fetch_future.done():
|
| 871 |
+
logger.info("BlockCache joined background fetch without waiting.")
|
| 872 |
+
self._fetch_block_cached.add_key(
|
| 873 |
+
self._fetch_future.result(), self._fetch_future_block_number
|
| 874 |
+
)
|
| 875 |
+
# Cleanup the fetch variables. Done with fetching the block.
|
| 876 |
+
self._fetch_future_block_number = None
|
| 877 |
+
self._fetch_future = None
|
| 878 |
+
else:
|
| 879 |
+
# Must join if we need the block for the current fetch
|
| 880 |
+
must_join = bool(
|
| 881 |
+
start_block_number
|
| 882 |
+
<= self._fetch_future_block_number
|
| 883 |
+
<= end_block_number
|
| 884 |
+
)
|
| 885 |
+
if must_join:
|
| 886 |
+
# Copy to the local variables to release lock
|
| 887 |
+
# before waiting for result
|
| 888 |
+
fetch_future_block_number = self._fetch_future_block_number
|
| 889 |
+
fetch_future = self._fetch_future
|
| 890 |
+
|
| 891 |
+
# Cleanup the fetch variables. Have a local copy.
|
| 892 |
+
self._fetch_future_block_number = None
|
| 893 |
+
self._fetch_future = None
|
| 894 |
+
|
| 895 |
+
# Need to wait for the future for the current read
|
| 896 |
+
if fetch_future is not None:
|
| 897 |
+
logger.info("BlockCache waiting for background fetch.")
|
| 898 |
+
# Wait until result and put it in cache
|
| 899 |
+
self._fetch_block_cached.add_key(
|
| 900 |
+
fetch_future.result(), fetch_future_block_number
|
| 901 |
+
)
|
| 902 |
+
|
| 903 |
+
# these are cached, so safe to do multiple calls for the same start and end.
|
| 904 |
+
for block_number in range(start_block_number, end_block_number + 1):
|
| 905 |
+
self._fetch_block_cached(block_number)
|
| 906 |
+
|
| 907 |
+
# fetch next block in the background if nothing is running in the background,
|
| 908 |
+
# the block is within file and it is not already cached
|
| 909 |
+
end_block_plus_1 = end_block_number + 1
|
| 910 |
+
with self._fetch_future_lock:
|
| 911 |
+
if (
|
| 912 |
+
self._fetch_future is None
|
| 913 |
+
and end_block_plus_1 <= self.nblocks
|
| 914 |
+
and not self._fetch_block_cached.is_key_cached(end_block_plus_1)
|
| 915 |
+
):
|
| 916 |
+
self._fetch_future_block_number = end_block_plus_1
|
| 917 |
+
self._fetch_future = self._thread_executor.submit(
|
| 918 |
+
self._fetch_block, end_block_plus_1, "async"
|
| 919 |
+
)
|
| 920 |
+
|
| 921 |
+
return self._read_cache(
|
| 922 |
+
start,
|
| 923 |
+
end,
|
| 924 |
+
start_block_number=start_block_number,
|
| 925 |
+
end_block_number=end_block_number,
|
| 926 |
+
)
|
| 927 |
+
|
| 928 |
+
def _fetch_block(self, block_number: int, log_info: str = "sync") -> bytes:
|
| 929 |
+
"""
|
| 930 |
+
Fetch the block of data for `block_number`.
|
| 931 |
+
"""
|
| 932 |
+
if block_number > self.nblocks:
|
| 933 |
+
raise ValueError(
|
| 934 |
+
f"'block_number={block_number}' is greater than "
|
| 935 |
+
f"the number of blocks ({self.nblocks})"
|
| 936 |
+
)
|
| 937 |
+
|
| 938 |
+
start = block_number * self.blocksize
|
| 939 |
+
end = start + self.blocksize
|
| 940 |
+
logger.info("BlockCache fetching block (%s) %d", log_info, block_number)
|
| 941 |
+
self.total_requested_bytes += end - start
|
| 942 |
+
self.miss_count += 1
|
| 943 |
+
block_contents = super()._fetch(start, end)
|
| 944 |
+
return block_contents
|
| 945 |
+
|
| 946 |
+
def _read_cache(
|
| 947 |
+
self, start: int, end: int, start_block_number: int, end_block_number: int
|
| 948 |
+
) -> bytes:
|
| 949 |
+
"""
|
| 950 |
+
Read from our block cache.
|
| 951 |
+
|
| 952 |
+
Parameters
|
| 953 |
+
----------
|
| 954 |
+
start, end : int
|
| 955 |
+
The start and end byte positions.
|
| 956 |
+
start_block_number, end_block_number : int
|
| 957 |
+
The start and end block numbers.
|
| 958 |
+
"""
|
| 959 |
+
start_pos = start % self.blocksize
|
| 960 |
+
end_pos = end % self.blocksize
|
| 961 |
+
|
| 962 |
+
# kind of pointless to count this as a hit, but it is
|
| 963 |
+
self.hit_count += 1
|
| 964 |
+
|
| 965 |
+
if start_block_number == end_block_number:
|
| 966 |
+
block = self._fetch_block_cached(start_block_number)
|
| 967 |
+
return block[start_pos:end_pos]
|
| 968 |
+
|
| 969 |
+
else:
|
| 970 |
+
# read from the initial
|
| 971 |
+
out = [self._fetch_block_cached(start_block_number)[start_pos:]]
|
| 972 |
+
|
| 973 |
+
# intermediate blocks
|
| 974 |
+
# Note: it'd be nice to combine these into one big request. However
|
| 975 |
+
# that doesn't play nicely with our LRU cache.
|
| 976 |
+
out.extend(
|
| 977 |
+
map(
|
| 978 |
+
self._fetch_block_cached,
|
| 979 |
+
range(start_block_number + 1, end_block_number),
|
| 980 |
+
)
|
| 981 |
+
)
|
| 982 |
+
|
| 983 |
+
# final block
|
| 984 |
+
out.append(self._fetch_block_cached(end_block_number)[:end_pos])
|
| 985 |
+
|
| 986 |
+
return b"".join(out)
|
| 987 |
+
|
| 988 |
+
|
| 989 |
+
caches: dict[str | None, type[BaseCache]] = {
|
| 990 |
+
# one custom case
|
| 991 |
+
None: BaseCache,
|
| 992 |
+
}
|
| 993 |
+
|
| 994 |
+
|
| 995 |
+
def register_cache(cls: type[BaseCache], clobber: bool = False) -> None:
|
| 996 |
+
"""'Register' cache implementation.
|
| 997 |
+
|
| 998 |
+
Parameters
|
| 999 |
+
----------
|
| 1000 |
+
clobber: bool, optional
|
| 1001 |
+
If set to True (default is False) - allow to overwrite existing
|
| 1002 |
+
entry.
|
| 1003 |
+
|
| 1004 |
+
Raises
|
| 1005 |
+
------
|
| 1006 |
+
ValueError
|
| 1007 |
+
"""
|
| 1008 |
+
name = cls.name
|
| 1009 |
+
if not clobber and name in caches:
|
| 1010 |
+
raise ValueError(f"Cache with name {name!r} is already known: {caches[name]}")
|
| 1011 |
+
caches[name] = cls
|
| 1012 |
+
|
| 1013 |
+
|
| 1014 |
+
for c in (
|
| 1015 |
+
BaseCache,
|
| 1016 |
+
MMapCache,
|
| 1017 |
+
BytesCache,
|
| 1018 |
+
ReadAheadCache,
|
| 1019 |
+
BlockCache,
|
| 1020 |
+
FirstChunkCache,
|
| 1021 |
+
AllBytes,
|
| 1022 |
+
KnownPartsOfAFile,
|
| 1023 |
+
BackgroundBlockCache,
|
| 1024 |
+
):
|
| 1025 |
+
register_cache(c)
|
.venv/lib/python3.12/site-packages/fsspec/callbacks.py
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from functools import wraps
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class Callback:
|
| 5 |
+
"""
|
| 6 |
+
Base class and interface for callback mechanism
|
| 7 |
+
|
| 8 |
+
This class can be used directly for monitoring file transfers by
|
| 9 |
+
providing ``callback=Callback(hooks=...)`` (see the ``hooks`` argument,
|
| 10 |
+
below), or subclassed for more specialised behaviour.
|
| 11 |
+
|
| 12 |
+
Parameters
|
| 13 |
+
----------
|
| 14 |
+
size: int (optional)
|
| 15 |
+
Nominal quantity for the value that corresponds to a complete
|
| 16 |
+
transfer, e.g., total number of tiles or total number of
|
| 17 |
+
bytes
|
| 18 |
+
value: int (0)
|
| 19 |
+
Starting internal counter value
|
| 20 |
+
hooks: dict or None
|
| 21 |
+
A dict of named functions to be called on each update. The signature
|
| 22 |
+
of these must be ``f(size, value, **kwargs)``
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
def __init__(self, size=None, value=0, hooks=None, **kwargs):
|
| 26 |
+
self.size = size
|
| 27 |
+
self.value = value
|
| 28 |
+
self.hooks = hooks or {}
|
| 29 |
+
self.kw = kwargs
|
| 30 |
+
|
| 31 |
+
def __enter__(self):
|
| 32 |
+
return self
|
| 33 |
+
|
| 34 |
+
def __exit__(self, *exc_args):
|
| 35 |
+
self.close()
|
| 36 |
+
|
| 37 |
+
def close(self):
|
| 38 |
+
"""Close callback."""
|
| 39 |
+
|
| 40 |
+
def branched(self, path_1, path_2, **kwargs):
|
| 41 |
+
"""
|
| 42 |
+
Return callback for child transfers
|
| 43 |
+
|
| 44 |
+
If this callback is operating at a higher level, e.g., put, which may
|
| 45 |
+
trigger transfers that can also be monitored. The function returns a callback
|
| 46 |
+
that has to be passed to the child method, e.g., put_file,
|
| 47 |
+
as `callback=` argument.
|
| 48 |
+
|
| 49 |
+
The implementation uses `callback.branch` for compatibility.
|
| 50 |
+
When implementing callbacks, it is recommended to override this function instead
|
| 51 |
+
of `branch` and avoid calling `super().branched(...)`.
|
| 52 |
+
|
| 53 |
+
Prefer using this function over `branch`.
|
| 54 |
+
|
| 55 |
+
Parameters
|
| 56 |
+
----------
|
| 57 |
+
path_1: str
|
| 58 |
+
Child's source path
|
| 59 |
+
path_2: str
|
| 60 |
+
Child's destination path
|
| 61 |
+
**kwargs:
|
| 62 |
+
Arbitrary keyword arguments
|
| 63 |
+
|
| 64 |
+
Returns
|
| 65 |
+
-------
|
| 66 |
+
callback: Callback
|
| 67 |
+
A callback instance to be passed to the child method
|
| 68 |
+
"""
|
| 69 |
+
self.branch(path_1, path_2, kwargs)
|
| 70 |
+
# mutate kwargs so that we can force the caller to pass "callback=" explicitly
|
| 71 |
+
return kwargs.pop("callback", DEFAULT_CALLBACK)
|
| 72 |
+
|
| 73 |
+
def branch_coro(self, fn):
|
| 74 |
+
"""
|
| 75 |
+
Wraps a coroutine, and pass a new child callback to it.
|
| 76 |
+
"""
|
| 77 |
+
|
| 78 |
+
@wraps(fn)
|
| 79 |
+
async def func(path1, path2: str, **kwargs):
|
| 80 |
+
with self.branched(path1, path2, **kwargs) as child:
|
| 81 |
+
return await fn(path1, path2, callback=child, **kwargs)
|
| 82 |
+
|
| 83 |
+
return func
|
| 84 |
+
|
| 85 |
+
def set_size(self, size):
|
| 86 |
+
"""
|
| 87 |
+
Set the internal maximum size attribute
|
| 88 |
+
|
| 89 |
+
Usually called if not initially set at instantiation. Note that this
|
| 90 |
+
triggers a ``call()``.
|
| 91 |
+
|
| 92 |
+
Parameters
|
| 93 |
+
----------
|
| 94 |
+
size: int
|
| 95 |
+
"""
|
| 96 |
+
self.size = size
|
| 97 |
+
self.call()
|
| 98 |
+
|
| 99 |
+
def absolute_update(self, value):
|
| 100 |
+
"""
|
| 101 |
+
Set the internal value state
|
| 102 |
+
|
| 103 |
+
Triggers ``call()``
|
| 104 |
+
|
| 105 |
+
Parameters
|
| 106 |
+
----------
|
| 107 |
+
value: int
|
| 108 |
+
"""
|
| 109 |
+
self.value = value
|
| 110 |
+
self.call()
|
| 111 |
+
|
| 112 |
+
def relative_update(self, inc=1):
|
| 113 |
+
"""
|
| 114 |
+
Delta increment the internal counter
|
| 115 |
+
|
| 116 |
+
Triggers ``call()``
|
| 117 |
+
|
| 118 |
+
Parameters
|
| 119 |
+
----------
|
| 120 |
+
inc: int
|
| 121 |
+
"""
|
| 122 |
+
self.value += inc
|
| 123 |
+
self.call()
|
| 124 |
+
|
| 125 |
+
def call(self, hook_name=None, **kwargs):
|
| 126 |
+
"""
|
| 127 |
+
Execute hook(s) with current state
|
| 128 |
+
|
| 129 |
+
Each function is passed the internal size and current value
|
| 130 |
+
|
| 131 |
+
Parameters
|
| 132 |
+
----------
|
| 133 |
+
hook_name: str or None
|
| 134 |
+
If given, execute on this hook
|
| 135 |
+
kwargs: passed on to (all) hook(s)
|
| 136 |
+
"""
|
| 137 |
+
if not self.hooks:
|
| 138 |
+
return
|
| 139 |
+
kw = self.kw.copy()
|
| 140 |
+
kw.update(kwargs)
|
| 141 |
+
if hook_name:
|
| 142 |
+
if hook_name not in self.hooks:
|
| 143 |
+
return
|
| 144 |
+
return self.hooks[hook_name](self.size, self.value, **kw)
|
| 145 |
+
for hook in self.hooks.values() or []:
|
| 146 |
+
hook(self.size, self.value, **kw)
|
| 147 |
+
|
| 148 |
+
def wrap(self, iterable):
|
| 149 |
+
"""
|
| 150 |
+
Wrap an iterable to call ``relative_update`` on each iterations
|
| 151 |
+
|
| 152 |
+
Parameters
|
| 153 |
+
----------
|
| 154 |
+
iterable: Iterable
|
| 155 |
+
The iterable that is being wrapped
|
| 156 |
+
"""
|
| 157 |
+
for item in iterable:
|
| 158 |
+
self.relative_update()
|
| 159 |
+
yield item
|
| 160 |
+
|
| 161 |
+
def branch(self, path_1, path_2, kwargs):
|
| 162 |
+
"""
|
| 163 |
+
Set callbacks for child transfers
|
| 164 |
+
|
| 165 |
+
If this callback is operating at a higher level, e.g., put, which may
|
| 166 |
+
trigger transfers that can also be monitored. The passed kwargs are
|
| 167 |
+
to be *mutated* to add ``callback=``, if this class supports branching
|
| 168 |
+
to children.
|
| 169 |
+
|
| 170 |
+
Parameters
|
| 171 |
+
----------
|
| 172 |
+
path_1: str
|
| 173 |
+
Child's source path
|
| 174 |
+
path_2: str
|
| 175 |
+
Child's destination path
|
| 176 |
+
kwargs: dict
|
| 177 |
+
arguments passed to child method, e.g., put_file.
|
| 178 |
+
|
| 179 |
+
Returns
|
| 180 |
+
-------
|
| 181 |
+
|
| 182 |
+
"""
|
| 183 |
+
return None
|
| 184 |
+
|
| 185 |
+
def no_op(self, *_, **__):
|
| 186 |
+
pass
|
| 187 |
+
|
| 188 |
+
def __getattr__(self, item):
|
| 189 |
+
"""
|
| 190 |
+
If undefined methods are called on this class, nothing happens
|
| 191 |
+
"""
|
| 192 |
+
return self.no_op
|
| 193 |
+
|
| 194 |
+
@classmethod
|
| 195 |
+
def as_callback(cls, maybe_callback=None):
|
| 196 |
+
"""Transform callback=... into Callback instance
|
| 197 |
+
|
| 198 |
+
For the special value of ``None``, return the global instance of
|
| 199 |
+
``NoOpCallback``. This is an alternative to including
|
| 200 |
+
``callback=DEFAULT_CALLBACK`` directly in a method signature.
|
| 201 |
+
"""
|
| 202 |
+
if maybe_callback is None:
|
| 203 |
+
return DEFAULT_CALLBACK
|
| 204 |
+
return maybe_callback
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
class NoOpCallback(Callback):
|
| 208 |
+
"""
|
| 209 |
+
This implementation of Callback does exactly nothing
|
| 210 |
+
"""
|
| 211 |
+
|
| 212 |
+
def call(self, *args, **kwargs):
|
| 213 |
+
return None
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
class DotPrinterCallback(Callback):
|
| 217 |
+
"""
|
| 218 |
+
Simple example Callback implementation
|
| 219 |
+
|
| 220 |
+
Almost identical to Callback with a hook that prints a char; here we
|
| 221 |
+
demonstrate how the outer layer may print "#" and the inner layer "."
|
| 222 |
+
"""
|
| 223 |
+
|
| 224 |
+
def __init__(self, chr_to_print="#", **kwargs):
|
| 225 |
+
self.chr = chr_to_print
|
| 226 |
+
super().__init__(**kwargs)
|
| 227 |
+
|
| 228 |
+
def branch(self, path_1, path_2, kwargs):
|
| 229 |
+
"""Mutate kwargs to add new instance with different print char"""
|
| 230 |
+
kwargs["callback"] = DotPrinterCallback(".")
|
| 231 |
+
|
| 232 |
+
def call(self, **kwargs):
|
| 233 |
+
"""Just outputs a character"""
|
| 234 |
+
print(self.chr, end="")
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
class TqdmCallback(Callback):
|
| 238 |
+
"""
|
| 239 |
+
A callback to display a progress bar using tqdm
|
| 240 |
+
|
| 241 |
+
Parameters
|
| 242 |
+
----------
|
| 243 |
+
tqdm_kwargs : dict, (optional)
|
| 244 |
+
Any argument accepted by the tqdm constructor.
|
| 245 |
+
See the `tqdm doc <https://tqdm.github.io/docs/tqdm/#__init__>`_.
|
| 246 |
+
Will be forwarded to `tqdm_cls`.
|
| 247 |
+
tqdm_cls: (optional)
|
| 248 |
+
subclass of `tqdm.tqdm`. If not passed, it will default to `tqdm.tqdm`.
|
| 249 |
+
|
| 250 |
+
Examples
|
| 251 |
+
--------
|
| 252 |
+
>>> import fsspec
|
| 253 |
+
>>> from fsspec.callbacks import TqdmCallback
|
| 254 |
+
>>> fs = fsspec.filesystem("memory")
|
| 255 |
+
>>> path2distant_data = "/your-path"
|
| 256 |
+
>>> fs.upload(
|
| 257 |
+
".",
|
| 258 |
+
path2distant_data,
|
| 259 |
+
recursive=True,
|
| 260 |
+
callback=TqdmCallback(),
|
| 261 |
+
)
|
| 262 |
+
|
| 263 |
+
You can forward args to tqdm using the ``tqdm_kwargs`` parameter.
|
| 264 |
+
|
| 265 |
+
>>> fs.upload(
|
| 266 |
+
".",
|
| 267 |
+
path2distant_data,
|
| 268 |
+
recursive=True,
|
| 269 |
+
callback=TqdmCallback(tqdm_kwargs={"desc": "Your tqdm description"}),
|
| 270 |
+
)
|
| 271 |
+
|
| 272 |
+
You can also customize the progress bar by passing a subclass of `tqdm`.
|
| 273 |
+
|
| 274 |
+
.. code-block:: python
|
| 275 |
+
|
| 276 |
+
class TqdmFormat(tqdm):
|
| 277 |
+
'''Provides a `total_time` format parameter'''
|
| 278 |
+
@property
|
| 279 |
+
def format_dict(self):
|
| 280 |
+
d = super().format_dict
|
| 281 |
+
total_time = d["elapsed"] * (d["total"] or 0) / max(d["n"], 1)
|
| 282 |
+
d.update(total_time=self.format_interval(total_time) + " in total")
|
| 283 |
+
return d
|
| 284 |
+
|
| 285 |
+
>>> with TqdmCallback(
|
| 286 |
+
tqdm_kwargs={
|
| 287 |
+
"desc": "desc",
|
| 288 |
+
"bar_format": "{total_time}: {percentage:.0f}%|{bar}{r_bar}",
|
| 289 |
+
},
|
| 290 |
+
tqdm_cls=TqdmFormat,
|
| 291 |
+
) as callback:
|
| 292 |
+
fs.upload(".", path2distant_data, recursive=True, callback=callback)
|
| 293 |
+
"""
|
| 294 |
+
|
| 295 |
+
def __init__(self, tqdm_kwargs=None, *args, **kwargs):
|
| 296 |
+
try:
|
| 297 |
+
from tqdm import tqdm
|
| 298 |
+
|
| 299 |
+
except ImportError as exce:
|
| 300 |
+
raise ImportError(
|
| 301 |
+
"Using TqdmCallback requires tqdm to be installed"
|
| 302 |
+
) from exce
|
| 303 |
+
|
| 304 |
+
self._tqdm_cls = kwargs.pop("tqdm_cls", tqdm)
|
| 305 |
+
self._tqdm_kwargs = tqdm_kwargs or {}
|
| 306 |
+
self.tqdm = None
|
| 307 |
+
super().__init__(*args, **kwargs)
|
| 308 |
+
|
| 309 |
+
def call(self, *args, **kwargs):
|
| 310 |
+
if self.tqdm is None:
|
| 311 |
+
self.tqdm = self._tqdm_cls(total=self.size, **self._tqdm_kwargs)
|
| 312 |
+
self.tqdm.total = self.size
|
| 313 |
+
self.tqdm.update(self.value - self.tqdm.n)
|
| 314 |
+
|
| 315 |
+
def close(self):
|
| 316 |
+
if self.tqdm is not None:
|
| 317 |
+
self.tqdm.close()
|
| 318 |
+
self.tqdm = None
|
| 319 |
+
|
| 320 |
+
def __del__(self):
|
| 321 |
+
return self.close()
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
DEFAULT_CALLBACK = _DEFAULT_CALLBACK = NoOpCallback()
|
.venv/lib/python3.12/site-packages/fsspec/compression.py
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Helper functions for a standard streaming compression API"""
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
from zipfile import ZipFile
|
| 5 |
+
|
| 6 |
+
import fsspec.utils
|
| 7 |
+
from fsspec.spec import AbstractBufferedFile
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def noop_file(file, mode, **kwargs):
|
| 11 |
+
return file
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
# TODO: files should also be available as contexts
|
| 15 |
+
# should be functions of the form func(infile, mode=, **kwargs) -> file-like
|
| 16 |
+
compr = {None: noop_file}
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def register_compression(name, callback, extensions, force=False):
|
| 20 |
+
"""Register an "inferable" file compression type.
|
| 21 |
+
|
| 22 |
+
Registers transparent file compression type for use with fsspec.open.
|
| 23 |
+
Compression can be specified by name in open, or "infer"-ed for any files
|
| 24 |
+
ending with the given extensions.
|
| 25 |
+
|
| 26 |
+
Args:
|
| 27 |
+
name: (str) The compression type name. Eg. "gzip".
|
| 28 |
+
callback: A callable of form (infile, mode, **kwargs) -> file-like.
|
| 29 |
+
Accepts an input file-like object, the target mode and kwargs.
|
| 30 |
+
Returns a wrapped file-like object.
|
| 31 |
+
extensions: (str, Iterable[str]) A file extension, or list of file
|
| 32 |
+
extensions for which to infer this compression scheme. Eg. "gz".
|
| 33 |
+
force: (bool) Force re-registration of compression type or extensions.
|
| 34 |
+
|
| 35 |
+
Raises:
|
| 36 |
+
ValueError: If name or extensions already registered, and not force.
|
| 37 |
+
|
| 38 |
+
"""
|
| 39 |
+
if isinstance(extensions, str):
|
| 40 |
+
extensions = [extensions]
|
| 41 |
+
|
| 42 |
+
# Validate registration
|
| 43 |
+
if name in compr and not force:
|
| 44 |
+
raise ValueError(f"Duplicate compression registration: {name}")
|
| 45 |
+
|
| 46 |
+
for ext in extensions:
|
| 47 |
+
if ext in fsspec.utils.compressions and not force:
|
| 48 |
+
raise ValueError(f"Duplicate compression file extension: {ext} ({name})")
|
| 49 |
+
|
| 50 |
+
compr[name] = callback
|
| 51 |
+
|
| 52 |
+
for ext in extensions:
|
| 53 |
+
fsspec.utils.compressions[ext] = name
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def unzip(infile, mode="rb", filename=None, **kwargs):
|
| 57 |
+
if "r" not in mode:
|
| 58 |
+
filename = filename or "file"
|
| 59 |
+
z = ZipFile(infile, mode="w", **kwargs)
|
| 60 |
+
fo = z.open(filename, mode="w")
|
| 61 |
+
fo.close = lambda closer=fo.close: closer() or z.close()
|
| 62 |
+
return fo
|
| 63 |
+
z = ZipFile(infile)
|
| 64 |
+
if filename is None:
|
| 65 |
+
filename = z.namelist()[0]
|
| 66 |
+
return z.open(filename, mode="r", **kwargs)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
register_compression("zip", unzip, "zip")
|
| 70 |
+
|
| 71 |
+
try:
|
| 72 |
+
from bz2 import BZ2File
|
| 73 |
+
except ImportError:
|
| 74 |
+
pass
|
| 75 |
+
else:
|
| 76 |
+
register_compression("bz2", BZ2File, "bz2")
|
| 77 |
+
|
| 78 |
+
try: # pragma: no cover
|
| 79 |
+
from isal import igzip
|
| 80 |
+
|
| 81 |
+
def isal(infile, mode="rb", **kwargs):
|
| 82 |
+
return igzip.IGzipFile(fileobj=infile, mode=mode, **kwargs)
|
| 83 |
+
|
| 84 |
+
register_compression("gzip", isal, "gz")
|
| 85 |
+
except ImportError:
|
| 86 |
+
from gzip import GzipFile
|
| 87 |
+
|
| 88 |
+
register_compression(
|
| 89 |
+
"gzip", lambda f, **kwargs: GzipFile(fileobj=f, **kwargs), "gz"
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
try:
|
| 93 |
+
from lzma import LZMAFile
|
| 94 |
+
|
| 95 |
+
register_compression("lzma", LZMAFile, "lzma")
|
| 96 |
+
register_compression("xz", LZMAFile, "xz")
|
| 97 |
+
except ImportError:
|
| 98 |
+
pass
|
| 99 |
+
|
| 100 |
+
try:
|
| 101 |
+
import lzmaffi
|
| 102 |
+
|
| 103 |
+
register_compression("lzma", lzmaffi.LZMAFile, "lzma", force=True)
|
| 104 |
+
register_compression("xz", lzmaffi.LZMAFile, "xz", force=True)
|
| 105 |
+
except ImportError:
|
| 106 |
+
pass
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class SnappyFile(AbstractBufferedFile):
|
| 110 |
+
def __init__(self, infile, mode, **kwargs):
|
| 111 |
+
import snappy
|
| 112 |
+
|
| 113 |
+
super().__init__(
|
| 114 |
+
fs=None, path="snappy", mode=mode.strip("b") + "b", size=999999999, **kwargs
|
| 115 |
+
)
|
| 116 |
+
self.infile = infile
|
| 117 |
+
if "r" in mode:
|
| 118 |
+
self.codec = snappy.StreamDecompressor()
|
| 119 |
+
else:
|
| 120 |
+
self.codec = snappy.StreamCompressor()
|
| 121 |
+
|
| 122 |
+
def _upload_chunk(self, final=False):
|
| 123 |
+
self.buffer.seek(0)
|
| 124 |
+
out = self.codec.add_chunk(self.buffer.read())
|
| 125 |
+
self.infile.write(out)
|
| 126 |
+
return True
|
| 127 |
+
|
| 128 |
+
def seek(self, loc, whence=0):
|
| 129 |
+
raise NotImplementedError("SnappyFile is not seekable")
|
| 130 |
+
|
| 131 |
+
def seekable(self):
|
| 132 |
+
return False
|
| 133 |
+
|
| 134 |
+
def _fetch_range(self, start, end):
|
| 135 |
+
"""Get the specified set of bytes from remote"""
|
| 136 |
+
data = self.infile.read(end - start)
|
| 137 |
+
return self.codec.decompress(data)
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
try:
|
| 141 |
+
import snappy
|
| 142 |
+
|
| 143 |
+
snappy.compress(b"")
|
| 144 |
+
# Snappy may use the .sz file extension, but this is not part of the
|
| 145 |
+
# standard implementation.
|
| 146 |
+
register_compression("snappy", SnappyFile, [])
|
| 147 |
+
|
| 148 |
+
except (ImportError, NameError, AttributeError):
|
| 149 |
+
pass
|
| 150 |
+
|
| 151 |
+
try:
|
| 152 |
+
import lz4.frame
|
| 153 |
+
|
| 154 |
+
register_compression("lz4", lz4.frame.open, "lz4")
|
| 155 |
+
except ImportError:
|
| 156 |
+
pass
|
| 157 |
+
|
| 158 |
+
try:
|
| 159 |
+
if sys.version_info >= (3, 14):
|
| 160 |
+
from compression import zstd
|
| 161 |
+
else:
|
| 162 |
+
from backports import zstd
|
| 163 |
+
|
| 164 |
+
register_compression("zstd", zstd.ZstdFile, "zst")
|
| 165 |
+
except ImportError:
|
| 166 |
+
try:
|
| 167 |
+
import zstandard as zstd
|
| 168 |
+
|
| 169 |
+
def zstandard_file(infile, mode="rb"):
|
| 170 |
+
if "r" in mode:
|
| 171 |
+
cctx = zstd.ZstdDecompressor()
|
| 172 |
+
return cctx.stream_reader(infile)
|
| 173 |
+
else:
|
| 174 |
+
cctx = zstd.ZstdCompressor(level=10)
|
| 175 |
+
return cctx.stream_writer(infile)
|
| 176 |
+
|
| 177 |
+
register_compression("zstd", zstandard_file, "zst")
|
| 178 |
+
except ImportError:
|
| 179 |
+
pass
|
| 180 |
+
pass
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def available_compressions():
|
| 184 |
+
"""Return a list of the implemented compressions."""
|
| 185 |
+
return list(compr)
|
.venv/lib/python3.12/site-packages/fsspec/config.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import configparser
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
import warnings
|
| 7 |
+
from typing import Any
|
| 8 |
+
|
| 9 |
+
conf: dict[str, dict[str, Any]] = {}
|
| 10 |
+
default_conf_dir = os.path.join(os.path.expanduser("~"), ".config/fsspec")
|
| 11 |
+
conf_dir = os.environ.get("FSSPEC_CONFIG_DIR", default_conf_dir)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def set_conf_env(conf_dict, envdict=os.environ):
|
| 15 |
+
"""Set config values from environment variables
|
| 16 |
+
|
| 17 |
+
Looks for variables of the form ``FSSPEC_<protocol>`` and
|
| 18 |
+
``FSSPEC_<protocol>_<kwarg>``. For ``FSSPEC_<protocol>`` the value is parsed
|
| 19 |
+
as a json dictionary and used to ``update`` the config of the
|
| 20 |
+
corresponding protocol. For ``FSSPEC_<protocol>_<kwarg>`` there is no
|
| 21 |
+
attempt to convert the string value, but the kwarg keys will be lower-cased.
|
| 22 |
+
|
| 23 |
+
The ``FSSPEC_<protocol>_<kwarg>`` variables are applied after the
|
| 24 |
+
``FSSPEC_<protocol>`` ones.
|
| 25 |
+
|
| 26 |
+
Parameters
|
| 27 |
+
----------
|
| 28 |
+
conf_dict : dict(str, dict)
|
| 29 |
+
This dict will be mutated
|
| 30 |
+
envdict : dict-like(str, str)
|
| 31 |
+
Source for the values - usually the real environment
|
| 32 |
+
"""
|
| 33 |
+
envdict = dict(envdict)
|
| 34 |
+
kwarg_keys = []
|
| 35 |
+
for key in envdict:
|
| 36 |
+
if key.startswith("FSSPEC_") and len(key) > 7 and key[7] != "_":
|
| 37 |
+
try:
|
| 38 |
+
value = json.loads(envdict[key])
|
| 39 |
+
envdict[key] = value
|
| 40 |
+
except json.decoder.JSONDecodeError:
|
| 41 |
+
value = envdict[key]
|
| 42 |
+
if key.count("_") > 1:
|
| 43 |
+
kwarg_keys.append(key)
|
| 44 |
+
continue
|
| 45 |
+
else:
|
| 46 |
+
if isinstance(value, dict):
|
| 47 |
+
_, proto = key.split("_", 1)
|
| 48 |
+
conf_dict.setdefault(proto.lower(), {}).update(value)
|
| 49 |
+
else:
|
| 50 |
+
warnings.warn(
|
| 51 |
+
f"Ignoring environment variable {key} due to not being a dict:"
|
| 52 |
+
f" {type(value)}"
|
| 53 |
+
)
|
| 54 |
+
elif key.startswith("FSSPEC"):
|
| 55 |
+
warnings.warn(
|
| 56 |
+
f"Ignoring environment variable {key} due to having an unexpected name"
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
for key in kwarg_keys:
|
| 60 |
+
_, proto, kwarg = key.split("_", 2)
|
| 61 |
+
conf_dict.setdefault(proto.lower(), {})[kwarg.lower()] = envdict[key]
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def set_conf_files(cdir, conf_dict):
|
| 65 |
+
"""Set config values from files
|
| 66 |
+
|
| 67 |
+
Scans for INI and JSON files in the given dictionary, and uses their
|
| 68 |
+
contents to set the config. In case of repeated values, later values
|
| 69 |
+
win.
|
| 70 |
+
|
| 71 |
+
In the case of INI files, all values are strings, and these will not
|
| 72 |
+
be converted.
|
| 73 |
+
|
| 74 |
+
Parameters
|
| 75 |
+
----------
|
| 76 |
+
cdir : str
|
| 77 |
+
Directory to search
|
| 78 |
+
conf_dict : dict(str, dict)
|
| 79 |
+
This dict will be mutated
|
| 80 |
+
"""
|
| 81 |
+
if not os.path.isdir(cdir):
|
| 82 |
+
return
|
| 83 |
+
allfiles = sorted(os.listdir(cdir))
|
| 84 |
+
for fn in allfiles:
|
| 85 |
+
if fn.endswith(".ini"):
|
| 86 |
+
ini = configparser.ConfigParser()
|
| 87 |
+
ini.read(os.path.join(cdir, fn))
|
| 88 |
+
for key in ini:
|
| 89 |
+
if key == "DEFAULT":
|
| 90 |
+
continue
|
| 91 |
+
conf_dict.setdefault(key, {}).update(dict(ini[key]))
|
| 92 |
+
if fn.endswith(".json"):
|
| 93 |
+
with open(os.path.join(cdir, fn)) as f:
|
| 94 |
+
js = json.load(f)
|
| 95 |
+
for key in js:
|
| 96 |
+
conf_dict.setdefault(key, {}).update(dict(js[key]))
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def apply_config(cls, kwargs, conf_dict=None):
|
| 100 |
+
"""Supply default values for kwargs when instantiating class
|
| 101 |
+
|
| 102 |
+
Augments the passed kwargs, by finding entries in the config dict
|
| 103 |
+
which match the classes ``.protocol`` attribute (one or more str)
|
| 104 |
+
|
| 105 |
+
Parameters
|
| 106 |
+
----------
|
| 107 |
+
cls : file system implementation
|
| 108 |
+
kwargs : dict
|
| 109 |
+
conf_dict : dict of dict
|
| 110 |
+
Typically this is the global configuration
|
| 111 |
+
|
| 112 |
+
Returns
|
| 113 |
+
-------
|
| 114 |
+
dict : the modified set of kwargs
|
| 115 |
+
"""
|
| 116 |
+
if conf_dict is None:
|
| 117 |
+
conf_dict = conf
|
| 118 |
+
protos = cls.protocol if isinstance(cls.protocol, (tuple, list)) else [cls.protocol]
|
| 119 |
+
kw = {}
|
| 120 |
+
for proto in protos:
|
| 121 |
+
# default kwargs from the current state of the config
|
| 122 |
+
if proto in conf_dict:
|
| 123 |
+
kw.update(conf_dict[proto])
|
| 124 |
+
# explicit kwargs always win
|
| 125 |
+
kw.update(**kwargs)
|
| 126 |
+
kwargs = kw
|
| 127 |
+
return kwargs
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
set_conf_files(conf_dir, conf)
|
| 131 |
+
set_conf_env(conf)
|
.venv/lib/python3.12/site-packages/fsspec/conftest.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import shutil
|
| 3 |
+
import subprocess
|
| 4 |
+
import sys
|
| 5 |
+
import time
|
| 6 |
+
from collections import deque
|
| 7 |
+
from collections.abc import Generator, Sequence
|
| 8 |
+
|
| 9 |
+
import pytest
|
| 10 |
+
|
| 11 |
+
import fsspec
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@pytest.fixture()
|
| 15 |
+
def m():
|
| 16 |
+
"""
|
| 17 |
+
Fixture providing a memory filesystem.
|
| 18 |
+
"""
|
| 19 |
+
m = fsspec.filesystem("memory")
|
| 20 |
+
m.store.clear()
|
| 21 |
+
m.pseudo_dirs.clear()
|
| 22 |
+
m.pseudo_dirs.append("")
|
| 23 |
+
try:
|
| 24 |
+
yield m
|
| 25 |
+
finally:
|
| 26 |
+
m.store.clear()
|
| 27 |
+
m.pseudo_dirs.clear()
|
| 28 |
+
m.pseudo_dirs.append("")
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class InstanceCacheInspector:
|
| 32 |
+
"""
|
| 33 |
+
Helper class to inspect instance caches of filesystem classes in tests.
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
def clear(self) -> None:
|
| 37 |
+
"""
|
| 38 |
+
Clear instance caches of all currently imported filesystem classes.
|
| 39 |
+
"""
|
| 40 |
+
classes = deque([fsspec.spec.AbstractFileSystem])
|
| 41 |
+
while classes:
|
| 42 |
+
cls = classes.popleft()
|
| 43 |
+
cls.clear_instance_cache()
|
| 44 |
+
classes.extend(cls.__subclasses__())
|
| 45 |
+
|
| 46 |
+
def gather_counts(self, *, omit_zero: bool = True) -> dict[str, int]:
|
| 47 |
+
"""
|
| 48 |
+
Gather counts of filesystem instances in the instance caches
|
| 49 |
+
of all currently imported filesystem classes.
|
| 50 |
+
|
| 51 |
+
Parameters
|
| 52 |
+
----------
|
| 53 |
+
omit_zero:
|
| 54 |
+
Whether to omit instance types with no cached instances.
|
| 55 |
+
"""
|
| 56 |
+
out: dict[str, int] = {}
|
| 57 |
+
classes = deque([fsspec.spec.AbstractFileSystem])
|
| 58 |
+
while classes:
|
| 59 |
+
cls = classes.popleft()
|
| 60 |
+
count = len(cls._cache) # there is no public interface for the cache
|
| 61 |
+
# note: skip intermediate AbstractFileSystem subclasses
|
| 62 |
+
# if they proxy the protocol attribute via a property.
|
| 63 |
+
if isinstance(cls.protocol, (Sequence, str)):
|
| 64 |
+
key = cls.protocol if isinstance(cls.protocol, str) else cls.protocol[0]
|
| 65 |
+
if count or not omit_zero:
|
| 66 |
+
out[key] = count
|
| 67 |
+
classes.extend(cls.__subclasses__())
|
| 68 |
+
return out
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
@pytest.fixture(scope="function", autouse=True)
|
| 72 |
+
def instance_caches() -> Generator[InstanceCacheInspector, None, None]:
|
| 73 |
+
"""
|
| 74 |
+
Fixture to ensure empty filesystem instance caches before and after a test.
|
| 75 |
+
|
| 76 |
+
Used by default for all tests.
|
| 77 |
+
Clears caches of all imported filesystem classes.
|
| 78 |
+
Can be used to write test assertions about instance caches.
|
| 79 |
+
|
| 80 |
+
Usage:
|
| 81 |
+
|
| 82 |
+
def test_something(instance_caches):
|
| 83 |
+
# Test code here
|
| 84 |
+
fsspec.open("file://abc")
|
| 85 |
+
fsspec.open("memory://foo/bar")
|
| 86 |
+
|
| 87 |
+
# Test assertion
|
| 88 |
+
assert instance_caches.gather_counts() == {"file": 1, "memory": 1}
|
| 89 |
+
|
| 90 |
+
Returns
|
| 91 |
+
-------
|
| 92 |
+
instance_caches: An instance cache inspector for clearing and inspecting caches.
|
| 93 |
+
"""
|
| 94 |
+
ic = InstanceCacheInspector()
|
| 95 |
+
|
| 96 |
+
ic.clear()
|
| 97 |
+
try:
|
| 98 |
+
yield ic
|
| 99 |
+
finally:
|
| 100 |
+
ic.clear()
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
@pytest.fixture(scope="function")
|
| 104 |
+
def ftp_writable(tmpdir):
|
| 105 |
+
"""
|
| 106 |
+
Fixture providing a writable FTP filesystem.
|
| 107 |
+
"""
|
| 108 |
+
pytest.importorskip("pyftpdlib")
|
| 109 |
+
|
| 110 |
+
d = str(tmpdir)
|
| 111 |
+
with open(os.path.join(d, "out"), "wb") as f:
|
| 112 |
+
f.write(b"hello" * 10000)
|
| 113 |
+
P = subprocess.Popen(
|
| 114 |
+
[sys.executable, "-m", "pyftpdlib", "-d", d, "-u", "user", "-P", "pass", "-w"]
|
| 115 |
+
)
|
| 116 |
+
try:
|
| 117 |
+
time.sleep(1)
|
| 118 |
+
yield "localhost", 2121, "user", "pass"
|
| 119 |
+
finally:
|
| 120 |
+
P.terminate()
|
| 121 |
+
P.wait()
|
| 122 |
+
try:
|
| 123 |
+
shutil.rmtree(tmpdir)
|
| 124 |
+
except Exception:
|
| 125 |
+
pass
|
.venv/lib/python3.12/site-packages/fsspec/core.py
ADDED
|
@@ -0,0 +1,760 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import io
|
| 4 |
+
import logging
|
| 5 |
+
import os
|
| 6 |
+
import re
|
| 7 |
+
from glob import has_magic
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
# for backwards compat, we export cache things from here too
|
| 11 |
+
from fsspec.caching import ( # noqa: F401
|
| 12 |
+
BaseCache,
|
| 13 |
+
BlockCache,
|
| 14 |
+
BytesCache,
|
| 15 |
+
MMapCache,
|
| 16 |
+
ReadAheadCache,
|
| 17 |
+
caches,
|
| 18 |
+
)
|
| 19 |
+
from fsspec.compression import compr
|
| 20 |
+
from fsspec.config import conf
|
| 21 |
+
from fsspec.registry import available_protocols, filesystem, get_filesystem_class
|
| 22 |
+
from fsspec.utils import (
|
| 23 |
+
_unstrip_protocol,
|
| 24 |
+
build_name_function,
|
| 25 |
+
infer_compression,
|
| 26 |
+
stringify_path,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
logger = logging.getLogger("fsspec")
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class OpenFile:
|
| 33 |
+
"""
|
| 34 |
+
File-like object to be used in a context
|
| 35 |
+
|
| 36 |
+
Can layer (buffered) text-mode and compression over any file-system, which
|
| 37 |
+
are typically binary-only.
|
| 38 |
+
|
| 39 |
+
These instances are safe to serialize, as the low-level file object
|
| 40 |
+
is not created until invoked using ``with``.
|
| 41 |
+
|
| 42 |
+
Parameters
|
| 43 |
+
----------
|
| 44 |
+
fs: FileSystem
|
| 45 |
+
The file system to use for opening the file. Should be a subclass or duck-type
|
| 46 |
+
with ``fsspec.spec.AbstractFileSystem``
|
| 47 |
+
path: str
|
| 48 |
+
Location to open
|
| 49 |
+
mode: str like 'rb', optional
|
| 50 |
+
Mode of the opened file
|
| 51 |
+
compression: str or None, optional
|
| 52 |
+
Compression to apply
|
| 53 |
+
encoding: str or None, optional
|
| 54 |
+
The encoding to use if opened in text mode.
|
| 55 |
+
errors: str or None, optional
|
| 56 |
+
How to handle encoding errors if opened in text mode.
|
| 57 |
+
newline: None or str
|
| 58 |
+
Passed to TextIOWrapper in text mode, how to handle line endings.
|
| 59 |
+
autoopen: bool
|
| 60 |
+
If True, calls open() immediately. Mostly used by pickle
|
| 61 |
+
pos: int
|
| 62 |
+
If given and autoopen is True, seek to this location immediately
|
| 63 |
+
"""
|
| 64 |
+
|
| 65 |
+
def __init__(
|
| 66 |
+
self,
|
| 67 |
+
fs,
|
| 68 |
+
path,
|
| 69 |
+
mode="rb",
|
| 70 |
+
compression=None,
|
| 71 |
+
encoding=None,
|
| 72 |
+
errors=None,
|
| 73 |
+
newline=None,
|
| 74 |
+
):
|
| 75 |
+
self.fs = fs
|
| 76 |
+
self.path = path
|
| 77 |
+
self.mode = mode
|
| 78 |
+
self.compression = get_compression(path, compression)
|
| 79 |
+
self.encoding = encoding
|
| 80 |
+
self.errors = errors
|
| 81 |
+
self.newline = newline
|
| 82 |
+
self.fobjects = []
|
| 83 |
+
|
| 84 |
+
def __reduce__(self):
|
| 85 |
+
return (
|
| 86 |
+
OpenFile,
|
| 87 |
+
(
|
| 88 |
+
self.fs,
|
| 89 |
+
self.path,
|
| 90 |
+
self.mode,
|
| 91 |
+
self.compression,
|
| 92 |
+
self.encoding,
|
| 93 |
+
self.errors,
|
| 94 |
+
self.newline,
|
| 95 |
+
),
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
def __repr__(self):
|
| 99 |
+
return f"<OpenFile '{self.path}'>"
|
| 100 |
+
|
| 101 |
+
def __enter__(self):
|
| 102 |
+
mode = self.mode.replace("t", "").replace("b", "") + "b"
|
| 103 |
+
|
| 104 |
+
try:
|
| 105 |
+
f = self.fs.open(self.path, mode=mode)
|
| 106 |
+
except FileNotFoundError as e:
|
| 107 |
+
if has_magic(self.path):
|
| 108 |
+
raise FileNotFoundError(
|
| 109 |
+
"%s not found. The URL contains glob characters: you maybe needed\n"
|
| 110 |
+
"to pass expand=True in fsspec.open() or the storage_options of \n"
|
| 111 |
+
"your library. You can also set the config value 'open_expand'\n"
|
| 112 |
+
"before import, or fsspec.core.DEFAULT_EXPAND at runtime, to True.",
|
| 113 |
+
self.path,
|
| 114 |
+
) from e
|
| 115 |
+
raise
|
| 116 |
+
|
| 117 |
+
self.fobjects = [f]
|
| 118 |
+
|
| 119 |
+
if self.compression is not None:
|
| 120 |
+
compress = compr[self.compression]
|
| 121 |
+
f = compress(f, mode=mode[0])
|
| 122 |
+
self.fobjects.append(f)
|
| 123 |
+
|
| 124 |
+
if "b" not in self.mode:
|
| 125 |
+
# assume, for example, that 'r' is equivalent to 'rt' as in builtin
|
| 126 |
+
f = PickleableTextIOWrapper(
|
| 127 |
+
f, encoding=self.encoding, errors=self.errors, newline=self.newline
|
| 128 |
+
)
|
| 129 |
+
self.fobjects.append(f)
|
| 130 |
+
|
| 131 |
+
return self.fobjects[-1]
|
| 132 |
+
|
| 133 |
+
def __exit__(self, *args):
|
| 134 |
+
self.close()
|
| 135 |
+
|
| 136 |
+
@property
|
| 137 |
+
def full_name(self):
|
| 138 |
+
return _unstrip_protocol(self.path, self.fs)
|
| 139 |
+
|
| 140 |
+
def open(self):
|
| 141 |
+
"""Materialise this as a real open file without context
|
| 142 |
+
|
| 143 |
+
The OpenFile object should be explicitly closed to avoid enclosed file
|
| 144 |
+
instances persisting. You must, therefore, keep a reference to the OpenFile
|
| 145 |
+
during the life of the file-like it generates.
|
| 146 |
+
"""
|
| 147 |
+
return self.__enter__()
|
| 148 |
+
|
| 149 |
+
def close(self):
|
| 150 |
+
"""Close all encapsulated file objects"""
|
| 151 |
+
for f in reversed(self.fobjects):
|
| 152 |
+
if "r" not in self.mode and not f.closed:
|
| 153 |
+
f.flush()
|
| 154 |
+
f.close()
|
| 155 |
+
self.fobjects.clear()
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
class OpenFiles(list):
|
| 159 |
+
"""List of OpenFile instances
|
| 160 |
+
|
| 161 |
+
Can be used in a single context, which opens and closes all of the
|
| 162 |
+
contained files. Normal list access to get the elements works as
|
| 163 |
+
normal.
|
| 164 |
+
|
| 165 |
+
A special case is made for caching filesystems - the files will
|
| 166 |
+
be down/uploaded together at the start or end of the context, and
|
| 167 |
+
this may happen concurrently, if the target filesystem supports it.
|
| 168 |
+
"""
|
| 169 |
+
|
| 170 |
+
def __init__(self, *args, mode="rb", fs=None):
|
| 171 |
+
self.mode = mode
|
| 172 |
+
self.fs = fs
|
| 173 |
+
self.files = []
|
| 174 |
+
super().__init__(*args)
|
| 175 |
+
|
| 176 |
+
def __enter__(self):
|
| 177 |
+
if self.fs is None:
|
| 178 |
+
raise ValueError("Context has already been used")
|
| 179 |
+
|
| 180 |
+
fs = self.fs
|
| 181 |
+
while True:
|
| 182 |
+
if hasattr(fs, "open_many"):
|
| 183 |
+
# check for concurrent cache download; or set up for upload
|
| 184 |
+
self.files = fs.open_many(self)
|
| 185 |
+
return self.files
|
| 186 |
+
if hasattr(fs, "fs") and fs.fs is not None:
|
| 187 |
+
fs = fs.fs
|
| 188 |
+
else:
|
| 189 |
+
break
|
| 190 |
+
return [s.__enter__() for s in self]
|
| 191 |
+
|
| 192 |
+
def __exit__(self, *args):
|
| 193 |
+
fs = self.fs
|
| 194 |
+
[s.__exit__(*args) for s in self]
|
| 195 |
+
if "r" not in self.mode:
|
| 196 |
+
while True:
|
| 197 |
+
if hasattr(fs, "open_many"):
|
| 198 |
+
# check for concurrent cache upload
|
| 199 |
+
fs.commit_many(self.files)
|
| 200 |
+
return
|
| 201 |
+
if hasattr(fs, "fs") and fs.fs is not None:
|
| 202 |
+
fs = fs.fs
|
| 203 |
+
else:
|
| 204 |
+
break
|
| 205 |
+
|
| 206 |
+
def __getitem__(self, item):
|
| 207 |
+
out = super().__getitem__(item)
|
| 208 |
+
if isinstance(item, slice):
|
| 209 |
+
return OpenFiles(out, mode=self.mode, fs=self.fs)
|
| 210 |
+
return out
|
| 211 |
+
|
| 212 |
+
def __repr__(self):
|
| 213 |
+
return f"<List of {len(self)} OpenFile instances>"
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def open_files(
|
| 217 |
+
urlpath,
|
| 218 |
+
mode="rb",
|
| 219 |
+
compression=None,
|
| 220 |
+
encoding="utf8",
|
| 221 |
+
errors=None,
|
| 222 |
+
name_function=None,
|
| 223 |
+
num=1,
|
| 224 |
+
protocol=None,
|
| 225 |
+
newline=None,
|
| 226 |
+
auto_mkdir=True,
|
| 227 |
+
expand=True,
|
| 228 |
+
**kwargs,
|
| 229 |
+
):
|
| 230 |
+
"""Given a path or paths, return a list of ``OpenFile`` objects.
|
| 231 |
+
|
| 232 |
+
For writing, a str path must contain the "*" character, which will be filled
|
| 233 |
+
in by increasing numbers, e.g., "part*" -> "part1", "part2" if num=2.
|
| 234 |
+
|
| 235 |
+
For either reading or writing, can instead provide explicit list of paths.
|
| 236 |
+
|
| 237 |
+
Parameters
|
| 238 |
+
----------
|
| 239 |
+
urlpath: string or list
|
| 240 |
+
Absolute or relative filepath(s). Prefix with a protocol like ``s3://``
|
| 241 |
+
to read from alternative filesystems. To read from multiple files you
|
| 242 |
+
can pass a globstring or a list of paths, with the caveat that they
|
| 243 |
+
must all have the same protocol.
|
| 244 |
+
mode: 'rb', 'wt', etc.
|
| 245 |
+
compression: string or None
|
| 246 |
+
If given, open file using compression codec. Can either be a compression
|
| 247 |
+
name (a key in ``fsspec.compression.compr``) or "infer" to guess the
|
| 248 |
+
compression from the filename suffix.
|
| 249 |
+
encoding: str
|
| 250 |
+
For text mode only
|
| 251 |
+
errors: None or str
|
| 252 |
+
Passed to TextIOWrapper in text mode
|
| 253 |
+
name_function: function or None
|
| 254 |
+
if opening a set of files for writing, those files do not yet exist,
|
| 255 |
+
so we need to generate their names by formatting the urlpath for
|
| 256 |
+
each sequence number
|
| 257 |
+
num: int [1]
|
| 258 |
+
if writing mode, number of files we expect to create (passed to
|
| 259 |
+
name+function)
|
| 260 |
+
protocol: str or None
|
| 261 |
+
If given, overrides the protocol found in the URL.
|
| 262 |
+
newline: bytes or None
|
| 263 |
+
Used for line terminator in text mode. If None, uses system default;
|
| 264 |
+
if blank, uses no translation.
|
| 265 |
+
auto_mkdir: bool (True)
|
| 266 |
+
If in write mode, this will ensure the target directory exists before
|
| 267 |
+
writing, by calling ``fs.mkdirs(exist_ok=True)``.
|
| 268 |
+
expand: bool
|
| 269 |
+
**kwargs: dict
|
| 270 |
+
Extra options that make sense to a particular storage connection, e.g.
|
| 271 |
+
host, port, username, password, etc.
|
| 272 |
+
|
| 273 |
+
Examples
|
| 274 |
+
--------
|
| 275 |
+
>>> files = open_files('2015-*-*.csv') # doctest: +SKIP
|
| 276 |
+
>>> files = open_files(
|
| 277 |
+
... 's3://bucket/2015-*-*.csv.gz', compression='gzip'
|
| 278 |
+
... ) # doctest: +SKIP
|
| 279 |
+
|
| 280 |
+
Returns
|
| 281 |
+
-------
|
| 282 |
+
An ``OpenFiles`` instance, which is a list of ``OpenFile`` objects that can
|
| 283 |
+
be used as a single context
|
| 284 |
+
|
| 285 |
+
Notes
|
| 286 |
+
-----
|
| 287 |
+
For a full list of the available protocols and the implementations that
|
| 288 |
+
they map across to see the latest online documentation:
|
| 289 |
+
|
| 290 |
+
- For implementations built into ``fsspec`` see
|
| 291 |
+
https://filesystem-spec.readthedocs.io/en/latest/api.html#built-in-implementations
|
| 292 |
+
- For implementations in separate packages see
|
| 293 |
+
https://filesystem-spec.readthedocs.io/en/latest/api.html#other-known-implementations
|
| 294 |
+
"""
|
| 295 |
+
fs, fs_token, paths = get_fs_token_paths(
|
| 296 |
+
urlpath,
|
| 297 |
+
mode,
|
| 298 |
+
num=num,
|
| 299 |
+
name_function=name_function,
|
| 300 |
+
storage_options=kwargs,
|
| 301 |
+
protocol=protocol,
|
| 302 |
+
expand=expand,
|
| 303 |
+
)
|
| 304 |
+
if fs.protocol == "file":
|
| 305 |
+
fs.auto_mkdir = auto_mkdir
|
| 306 |
+
elif "r" not in mode and auto_mkdir:
|
| 307 |
+
parents = {fs._parent(path) for path in paths}
|
| 308 |
+
for parent in parents:
|
| 309 |
+
try:
|
| 310 |
+
fs.makedirs(parent, exist_ok=True)
|
| 311 |
+
except PermissionError:
|
| 312 |
+
pass
|
| 313 |
+
return OpenFiles(
|
| 314 |
+
[
|
| 315 |
+
OpenFile(
|
| 316 |
+
fs,
|
| 317 |
+
path,
|
| 318 |
+
mode=mode,
|
| 319 |
+
compression=compression,
|
| 320 |
+
encoding=encoding,
|
| 321 |
+
errors=errors,
|
| 322 |
+
newline=newline,
|
| 323 |
+
)
|
| 324 |
+
for path in paths
|
| 325 |
+
],
|
| 326 |
+
mode=mode,
|
| 327 |
+
fs=fs,
|
| 328 |
+
)
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
def _un_chain(path, kwargs):
|
| 332 |
+
# Avoid a circular import
|
| 333 |
+
from fsspec.implementations.chained import ChainedFileSystem
|
| 334 |
+
|
| 335 |
+
if "::" in path:
|
| 336 |
+
x = re.compile(".*[^a-z]+.*") # test for non protocol-like single word
|
| 337 |
+
known_protocols = set(available_protocols())
|
| 338 |
+
bits = []
|
| 339 |
+
|
| 340 |
+
# split on '::', then ensure each bit has a protocol
|
| 341 |
+
for p in path.split("::"):
|
| 342 |
+
if p in known_protocols:
|
| 343 |
+
bits.append(p + "://")
|
| 344 |
+
elif "://" in p or x.match(p):
|
| 345 |
+
bits.append(p)
|
| 346 |
+
else:
|
| 347 |
+
bits.append(p + "://")
|
| 348 |
+
else:
|
| 349 |
+
bits = [path]
|
| 350 |
+
|
| 351 |
+
# [[url, protocol, kwargs], ...]
|
| 352 |
+
out = []
|
| 353 |
+
previous_bit = None
|
| 354 |
+
kwargs = kwargs.copy()
|
| 355 |
+
|
| 356 |
+
for bit in reversed(bits):
|
| 357 |
+
protocol = kwargs.pop("protocol", None) or split_protocol(bit)[0] or "file"
|
| 358 |
+
cls = get_filesystem_class(protocol)
|
| 359 |
+
extra_kwargs = cls._get_kwargs_from_urls(bit)
|
| 360 |
+
kws = kwargs.pop(protocol, {})
|
| 361 |
+
|
| 362 |
+
if bit is bits[0]:
|
| 363 |
+
kws.update(kwargs)
|
| 364 |
+
|
| 365 |
+
kw = dict(
|
| 366 |
+
**{k: v for k, v in extra_kwargs.items() if k not in kws or v != kws[k]},
|
| 367 |
+
**kws,
|
| 368 |
+
)
|
| 369 |
+
bit = cls._strip_protocol(bit)
|
| 370 |
+
|
| 371 |
+
if (
|
| 372 |
+
"target_protocol" not in kw
|
| 373 |
+
and issubclass(cls, ChainedFileSystem)
|
| 374 |
+
and not bit
|
| 375 |
+
):
|
| 376 |
+
# replace bit if we are chaining and no path given
|
| 377 |
+
bit = previous_bit
|
| 378 |
+
|
| 379 |
+
out.append((bit, protocol, kw))
|
| 380 |
+
previous_bit = bit
|
| 381 |
+
|
| 382 |
+
out.reverse()
|
| 383 |
+
return out
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
def url_to_fs(url, **kwargs):
|
| 387 |
+
"""
|
| 388 |
+
Turn fully-qualified and potentially chained URL into filesystem instance
|
| 389 |
+
|
| 390 |
+
Parameters
|
| 391 |
+
----------
|
| 392 |
+
url : str
|
| 393 |
+
The fsspec-compatible URL
|
| 394 |
+
**kwargs: dict
|
| 395 |
+
Extra options that make sense to a particular storage connection, e.g.
|
| 396 |
+
host, port, username, password, etc.
|
| 397 |
+
|
| 398 |
+
Returns
|
| 399 |
+
-------
|
| 400 |
+
filesystem : FileSystem
|
| 401 |
+
The new filesystem discovered from ``url`` and created with
|
| 402 |
+
``**kwargs``.
|
| 403 |
+
urlpath : str
|
| 404 |
+
The file-systems-specific URL for ``url``.
|
| 405 |
+
"""
|
| 406 |
+
url = stringify_path(url)
|
| 407 |
+
# non-FS arguments that appear in fsspec.open()
|
| 408 |
+
# inspect could keep this in sync with open()'s signature
|
| 409 |
+
known_kwargs = {
|
| 410 |
+
"compression",
|
| 411 |
+
"encoding",
|
| 412 |
+
"errors",
|
| 413 |
+
"expand",
|
| 414 |
+
"mode",
|
| 415 |
+
"name_function",
|
| 416 |
+
"newline",
|
| 417 |
+
"num",
|
| 418 |
+
}
|
| 419 |
+
kwargs = {k: v for k, v in kwargs.items() if k not in known_kwargs}
|
| 420 |
+
chain = _un_chain(url, kwargs)
|
| 421 |
+
inkwargs = {}
|
| 422 |
+
# Reverse iterate the chain, creating a nested target_* structure
|
| 423 |
+
for i, ch in enumerate(reversed(chain)):
|
| 424 |
+
urls, protocol, kw = ch
|
| 425 |
+
if i == len(chain) - 1:
|
| 426 |
+
inkwargs = dict(**kw, **inkwargs)
|
| 427 |
+
continue
|
| 428 |
+
inkwargs["target_options"] = dict(**kw, **inkwargs)
|
| 429 |
+
inkwargs["target_protocol"] = protocol
|
| 430 |
+
inkwargs["fo"] = urls
|
| 431 |
+
urlpath, protocol, _ = chain[0]
|
| 432 |
+
fs = filesystem(protocol, **inkwargs)
|
| 433 |
+
return fs, urlpath
|
| 434 |
+
|
| 435 |
+
|
| 436 |
+
DEFAULT_EXPAND = conf.get("open_expand", False)
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
def open(
|
| 440 |
+
urlpath,
|
| 441 |
+
mode="rb",
|
| 442 |
+
compression=None,
|
| 443 |
+
encoding="utf8",
|
| 444 |
+
errors=None,
|
| 445 |
+
protocol=None,
|
| 446 |
+
newline=None,
|
| 447 |
+
expand=None,
|
| 448 |
+
**kwargs,
|
| 449 |
+
):
|
| 450 |
+
"""Given a path or paths, return one ``OpenFile`` object.
|
| 451 |
+
|
| 452 |
+
Parameters
|
| 453 |
+
----------
|
| 454 |
+
urlpath: string or list
|
| 455 |
+
Absolute or relative filepath. Prefix with a protocol like ``s3://``
|
| 456 |
+
to read from alternative filesystems. Should not include glob
|
| 457 |
+
character(s).
|
| 458 |
+
mode: 'rb', 'wt', etc.
|
| 459 |
+
compression: string or None
|
| 460 |
+
If given, open file using compression codec. Can either be a compression
|
| 461 |
+
name (a key in ``fsspec.compression.compr``) or "infer" to guess the
|
| 462 |
+
compression from the filename suffix.
|
| 463 |
+
encoding: str
|
| 464 |
+
For text mode only
|
| 465 |
+
errors: None or str
|
| 466 |
+
Passed to TextIOWrapper in text mode
|
| 467 |
+
protocol: str or None
|
| 468 |
+
If given, overrides the protocol found in the URL.
|
| 469 |
+
newline: bytes or None
|
| 470 |
+
Used for line terminator in text mode. If None, uses system default;
|
| 471 |
+
if blank, uses no translation.
|
| 472 |
+
expand: bool or None
|
| 473 |
+
Whether to regard file paths containing special glob characters as needing
|
| 474 |
+
expansion (finding the first match) or absolute. Setting False allows using
|
| 475 |
+
paths which do embed such characters. If None (default), this argument
|
| 476 |
+
takes its value from the DEFAULT_EXPAND module variable, which takes
|
| 477 |
+
its initial value from the "open_expand" config value at startup, which will
|
| 478 |
+
be False if not set.
|
| 479 |
+
**kwargs: dict
|
| 480 |
+
Extra options that make sense to a particular storage connection, e.g.
|
| 481 |
+
host, port, username, password, etc.
|
| 482 |
+
|
| 483 |
+
Examples
|
| 484 |
+
--------
|
| 485 |
+
>>> openfile = open('2015-01-01.csv') # doctest: +SKIP
|
| 486 |
+
>>> openfile = open(
|
| 487 |
+
... 's3://bucket/2015-01-01.csv.gz', compression='gzip'
|
| 488 |
+
... ) # doctest: +SKIP
|
| 489 |
+
>>> with openfile as f:
|
| 490 |
+
... df = pd.read_csv(f) # doctest: +SKIP
|
| 491 |
+
...
|
| 492 |
+
|
| 493 |
+
Returns
|
| 494 |
+
-------
|
| 495 |
+
``OpenFile`` object.
|
| 496 |
+
|
| 497 |
+
Notes
|
| 498 |
+
-----
|
| 499 |
+
For a full list of the available protocols and the implementations that
|
| 500 |
+
they map across to see the latest online documentation:
|
| 501 |
+
|
| 502 |
+
- For implementations built into ``fsspec`` see
|
| 503 |
+
https://filesystem-spec.readthedocs.io/en/latest/api.html#built-in-implementations
|
| 504 |
+
- For implementations in separate packages see
|
| 505 |
+
https://filesystem-spec.readthedocs.io/en/latest/api.html#other-known-implementations
|
| 506 |
+
"""
|
| 507 |
+
expand = DEFAULT_EXPAND if expand is None else expand
|
| 508 |
+
out = open_files(
|
| 509 |
+
urlpath=[urlpath],
|
| 510 |
+
mode=mode,
|
| 511 |
+
compression=compression,
|
| 512 |
+
encoding=encoding,
|
| 513 |
+
errors=errors,
|
| 514 |
+
protocol=protocol,
|
| 515 |
+
newline=newline,
|
| 516 |
+
expand=expand,
|
| 517 |
+
**kwargs,
|
| 518 |
+
)
|
| 519 |
+
if not out:
|
| 520 |
+
raise FileNotFoundError(urlpath)
|
| 521 |
+
return out[0]
|
| 522 |
+
|
| 523 |
+
|
| 524 |
+
def open_local(
|
| 525 |
+
url: str | list[str] | Path | list[Path],
|
| 526 |
+
mode: str = "rb",
|
| 527 |
+
**storage_options: dict,
|
| 528 |
+
) -> str | list[str]:
|
| 529 |
+
"""Open file(s) which can be resolved to local
|
| 530 |
+
|
| 531 |
+
For files which either are local, or get downloaded upon open
|
| 532 |
+
(e.g., by file caching)
|
| 533 |
+
|
| 534 |
+
Parameters
|
| 535 |
+
----------
|
| 536 |
+
url: str or list(str)
|
| 537 |
+
mode: str
|
| 538 |
+
Must be read mode
|
| 539 |
+
storage_options:
|
| 540 |
+
passed on to FS for or used by open_files (e.g., compression)
|
| 541 |
+
"""
|
| 542 |
+
if "r" not in mode:
|
| 543 |
+
raise ValueError("Can only ensure local files when reading")
|
| 544 |
+
of = open_files(url, mode=mode, **storage_options)
|
| 545 |
+
if not getattr(of[0].fs, "local_file", False):
|
| 546 |
+
raise ValueError(
|
| 547 |
+
"open_local can only be used on a filesystem which"
|
| 548 |
+
" has attribute local_file=True"
|
| 549 |
+
)
|
| 550 |
+
with of as files:
|
| 551 |
+
paths = [f.name for f in files]
|
| 552 |
+
if (isinstance(url, str) and not has_magic(url)) or isinstance(url, Path):
|
| 553 |
+
return paths[0]
|
| 554 |
+
return paths
|
| 555 |
+
|
| 556 |
+
|
| 557 |
+
def get_compression(urlpath, compression):
|
| 558 |
+
if compression == "infer":
|
| 559 |
+
compression = infer_compression(urlpath)
|
| 560 |
+
if compression is not None and compression not in compr:
|
| 561 |
+
raise ValueError(f"Compression type {compression} not supported")
|
| 562 |
+
return compression
|
| 563 |
+
|
| 564 |
+
|
| 565 |
+
def split_protocol(urlpath):
|
| 566 |
+
"""Return protocol, path pair"""
|
| 567 |
+
urlpath = stringify_path(urlpath)
|
| 568 |
+
if "://" in urlpath:
|
| 569 |
+
protocol, path = urlpath.split("://", 1)
|
| 570 |
+
if len(protocol) > 1:
|
| 571 |
+
# excludes Windows paths
|
| 572 |
+
return protocol, path
|
| 573 |
+
if urlpath.startswith("data:"):
|
| 574 |
+
return urlpath.split(":", 1)
|
| 575 |
+
return None, urlpath
|
| 576 |
+
|
| 577 |
+
|
| 578 |
+
def strip_protocol(urlpath):
|
| 579 |
+
"""Return only path part of full URL, according to appropriate backend"""
|
| 580 |
+
protocol, _ = split_protocol(urlpath)
|
| 581 |
+
cls = get_filesystem_class(protocol)
|
| 582 |
+
return cls._strip_protocol(urlpath)
|
| 583 |
+
|
| 584 |
+
|
| 585 |
+
def expand_paths_if_needed(paths, mode, num, fs, name_function):
|
| 586 |
+
"""Expand paths if they have a ``*`` in them (write mode) or any of ``*?[]``
|
| 587 |
+
in them (read mode).
|
| 588 |
+
|
| 589 |
+
:param paths: list of paths
|
| 590 |
+
mode: str
|
| 591 |
+
Mode in which to open files.
|
| 592 |
+
num: int
|
| 593 |
+
If opening in writing mode, number of files we expect to create.
|
| 594 |
+
fs: filesystem object
|
| 595 |
+
name_function: callable
|
| 596 |
+
If opening in writing mode, this callable is used to generate path
|
| 597 |
+
names. Names are generated for each partition by
|
| 598 |
+
``urlpath.replace('*', name_function(partition_index))``.
|
| 599 |
+
:return: list of paths
|
| 600 |
+
"""
|
| 601 |
+
expanded_paths = []
|
| 602 |
+
paths = list(paths)
|
| 603 |
+
|
| 604 |
+
if "w" in mode or "x" in mode: # write mode
|
| 605 |
+
if sum(1 for p in paths if "*" in p) > 1:
|
| 606 |
+
raise ValueError(
|
| 607 |
+
"When writing data, only one filename mask can be specified."
|
| 608 |
+
)
|
| 609 |
+
num = max(num, len(paths))
|
| 610 |
+
|
| 611 |
+
for curr_path in paths:
|
| 612 |
+
if "*" in curr_path:
|
| 613 |
+
# expand using name_function
|
| 614 |
+
expanded_paths.extend(_expand_paths(curr_path, name_function, num))
|
| 615 |
+
else:
|
| 616 |
+
expanded_paths.append(curr_path)
|
| 617 |
+
# if we generated more paths that asked for, trim the list
|
| 618 |
+
if len(expanded_paths) > num:
|
| 619 |
+
expanded_paths = expanded_paths[:num]
|
| 620 |
+
|
| 621 |
+
else: # read mode
|
| 622 |
+
for curr_path in paths:
|
| 623 |
+
if has_magic(curr_path):
|
| 624 |
+
# expand using glob
|
| 625 |
+
expanded_paths.extend(fs.glob(curr_path))
|
| 626 |
+
else:
|
| 627 |
+
expanded_paths.append(curr_path)
|
| 628 |
+
|
| 629 |
+
return expanded_paths
|
| 630 |
+
|
| 631 |
+
|
| 632 |
+
def get_fs_token_paths(
|
| 633 |
+
urlpath,
|
| 634 |
+
mode="rb",
|
| 635 |
+
num=1,
|
| 636 |
+
name_function=None,
|
| 637 |
+
storage_options=None,
|
| 638 |
+
protocol=None,
|
| 639 |
+
expand=True,
|
| 640 |
+
):
|
| 641 |
+
"""Filesystem, deterministic token, and paths from a urlpath and options.
|
| 642 |
+
|
| 643 |
+
Parameters
|
| 644 |
+
----------
|
| 645 |
+
urlpath: string or iterable
|
| 646 |
+
Absolute or relative filepath, URL (may include protocols like
|
| 647 |
+
``s3://``), or globstring pointing to data.
|
| 648 |
+
mode: str, optional
|
| 649 |
+
Mode in which to open files.
|
| 650 |
+
num: int, optional
|
| 651 |
+
If opening in writing mode, number of files we expect to create.
|
| 652 |
+
name_function: callable, optional
|
| 653 |
+
If opening in writing mode, this callable is used to generate path
|
| 654 |
+
names. Names are generated for each partition by
|
| 655 |
+
``urlpath.replace('*', name_function(partition_index))``.
|
| 656 |
+
storage_options: dict, optional
|
| 657 |
+
Additional keywords to pass to the filesystem class.
|
| 658 |
+
protocol: str or None
|
| 659 |
+
To override the protocol specifier in the URL
|
| 660 |
+
expand: bool
|
| 661 |
+
Expand string paths for writing, assuming the path is a directory
|
| 662 |
+
"""
|
| 663 |
+
if isinstance(urlpath, (list, tuple, set)):
|
| 664 |
+
if not urlpath:
|
| 665 |
+
raise ValueError("empty urlpath sequence")
|
| 666 |
+
urlpath0 = stringify_path(next(iter(urlpath)))
|
| 667 |
+
else:
|
| 668 |
+
urlpath0 = stringify_path(urlpath)
|
| 669 |
+
storage_options = storage_options or {}
|
| 670 |
+
if protocol:
|
| 671 |
+
storage_options["protocol"] = protocol
|
| 672 |
+
chain = _un_chain(urlpath0, storage_options or {})
|
| 673 |
+
inkwargs = {}
|
| 674 |
+
# Reverse iterate the chain, creating a nested target_* structure
|
| 675 |
+
for i, ch in enumerate(reversed(chain)):
|
| 676 |
+
urls, nested_protocol, kw = ch
|
| 677 |
+
if i == len(chain) - 1:
|
| 678 |
+
inkwargs = dict(**kw, **inkwargs)
|
| 679 |
+
continue
|
| 680 |
+
inkwargs["target_options"] = dict(**kw, **inkwargs)
|
| 681 |
+
inkwargs["target_protocol"] = nested_protocol
|
| 682 |
+
inkwargs["fo"] = urls
|
| 683 |
+
paths, protocol, _ = chain[0]
|
| 684 |
+
fs = filesystem(protocol, **inkwargs)
|
| 685 |
+
if isinstance(urlpath, (list, tuple, set)):
|
| 686 |
+
pchains = [
|
| 687 |
+
_un_chain(stringify_path(u), storage_options or {})[0] for u in urlpath
|
| 688 |
+
]
|
| 689 |
+
if len({pc[1] for pc in pchains}) > 1:
|
| 690 |
+
raise ValueError("Protocol mismatch getting fs from %s", urlpath)
|
| 691 |
+
paths = [pc[0] for pc in pchains]
|
| 692 |
+
else:
|
| 693 |
+
paths = fs._strip_protocol(paths)
|
| 694 |
+
if isinstance(paths, (list, tuple, set)):
|
| 695 |
+
if expand:
|
| 696 |
+
paths = expand_paths_if_needed(paths, mode, num, fs, name_function)
|
| 697 |
+
elif not isinstance(paths, list):
|
| 698 |
+
paths = list(paths)
|
| 699 |
+
else:
|
| 700 |
+
if ("w" in mode or "x" in mode) and expand:
|
| 701 |
+
paths = _expand_paths(paths, name_function, num)
|
| 702 |
+
elif "*" in paths:
|
| 703 |
+
paths = [f for f in sorted(fs.glob(paths)) if not fs.isdir(f)]
|
| 704 |
+
else:
|
| 705 |
+
paths = [paths]
|
| 706 |
+
|
| 707 |
+
return fs, fs._fs_token, paths
|
| 708 |
+
|
| 709 |
+
|
| 710 |
+
def _expand_paths(path, name_function, num):
|
| 711 |
+
if isinstance(path, str):
|
| 712 |
+
if path.count("*") > 1:
|
| 713 |
+
raise ValueError("Output path spec must contain exactly one '*'.")
|
| 714 |
+
elif "*" not in path:
|
| 715 |
+
path = os.path.join(path, "*.part")
|
| 716 |
+
|
| 717 |
+
if name_function is None:
|
| 718 |
+
name_function = build_name_function(num - 1)
|
| 719 |
+
|
| 720 |
+
paths = [path.replace("*", name_function(i)) for i in range(num)]
|
| 721 |
+
if paths != sorted(paths):
|
| 722 |
+
logger.warning(
|
| 723 |
+
"In order to preserve order between partitions"
|
| 724 |
+
" paths created with ``name_function`` should "
|
| 725 |
+
"sort to partition order"
|
| 726 |
+
)
|
| 727 |
+
elif isinstance(path, (tuple, list)):
|
| 728 |
+
assert len(path) == num
|
| 729 |
+
paths = list(path)
|
| 730 |
+
else:
|
| 731 |
+
raise ValueError(
|
| 732 |
+
"Path should be either\n"
|
| 733 |
+
"1. A list of paths: ['foo.json', 'bar.json', ...]\n"
|
| 734 |
+
"2. A directory: 'foo/\n"
|
| 735 |
+
"3. A path with a '*' in it: 'foo.*.json'"
|
| 736 |
+
)
|
| 737 |
+
return paths
|
| 738 |
+
|
| 739 |
+
|
| 740 |
+
class PickleableTextIOWrapper(io.TextIOWrapper):
|
| 741 |
+
"""TextIOWrapper cannot be pickled. This solves it.
|
| 742 |
+
|
| 743 |
+
Requires that ``buffer`` be pickleable, which all instances of
|
| 744 |
+
AbstractBufferedFile are.
|
| 745 |
+
"""
|
| 746 |
+
|
| 747 |
+
def __init__(
|
| 748 |
+
self,
|
| 749 |
+
buffer,
|
| 750 |
+
encoding=None,
|
| 751 |
+
errors=None,
|
| 752 |
+
newline=None,
|
| 753 |
+
line_buffering=False,
|
| 754 |
+
write_through=False,
|
| 755 |
+
):
|
| 756 |
+
self.args = buffer, encoding, errors, newline, line_buffering, write_through
|
| 757 |
+
super().__init__(*self.args)
|
| 758 |
+
|
| 759 |
+
def __reduce__(self):
|
| 760 |
+
return PickleableTextIOWrapper, self.args
|
.venv/lib/python3.12/site-packages/fsspec/dircache.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import time
|
| 2 |
+
from collections.abc import MutableMapping
|
| 3 |
+
from functools import lru_cache
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class DirCache(MutableMapping):
|
| 7 |
+
"""
|
| 8 |
+
Caching of directory listings, in a structure like::
|
| 9 |
+
|
| 10 |
+
{"path0": [
|
| 11 |
+
{"name": "path0/file0",
|
| 12 |
+
"size": 123,
|
| 13 |
+
"type": "file",
|
| 14 |
+
...
|
| 15 |
+
},
|
| 16 |
+
{"name": "path0/file1",
|
| 17 |
+
},
|
| 18 |
+
...
|
| 19 |
+
],
|
| 20 |
+
"path1": [...]
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
Parameters to this class control listing expiry or indeed turn
|
| 24 |
+
caching off
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
def __init__(
|
| 28 |
+
self,
|
| 29 |
+
use_listings_cache=True,
|
| 30 |
+
listings_expiry_time=None,
|
| 31 |
+
max_paths=None,
|
| 32 |
+
**kwargs,
|
| 33 |
+
):
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
Parameters
|
| 37 |
+
----------
|
| 38 |
+
use_listings_cache: bool
|
| 39 |
+
If False, this cache never returns items, but always reports KeyError,
|
| 40 |
+
and setting items has no effect
|
| 41 |
+
listings_expiry_time: int or float (optional)
|
| 42 |
+
Time in seconds that a listing is considered valid. If None,
|
| 43 |
+
listings do not expire.
|
| 44 |
+
max_paths: int (optional)
|
| 45 |
+
The number of most recent listings that are considered valid; 'recent'
|
| 46 |
+
refers to when the entry was set.
|
| 47 |
+
"""
|
| 48 |
+
self._cache = {}
|
| 49 |
+
self._times = {}
|
| 50 |
+
if max_paths:
|
| 51 |
+
self._q = lru_cache(max_paths + 1)(lambda key: self._cache.pop(key, None))
|
| 52 |
+
self.use_listings_cache = use_listings_cache
|
| 53 |
+
self.listings_expiry_time = listings_expiry_time
|
| 54 |
+
self.max_paths = max_paths
|
| 55 |
+
|
| 56 |
+
def __getitem__(self, item):
|
| 57 |
+
if self.listings_expiry_time is not None:
|
| 58 |
+
if self._times.get(item, 0) - time.time() < -self.listings_expiry_time:
|
| 59 |
+
del self._cache[item]
|
| 60 |
+
if self.max_paths:
|
| 61 |
+
self._q(item)
|
| 62 |
+
return self._cache[item] # maybe raises KeyError
|
| 63 |
+
|
| 64 |
+
def clear(self):
|
| 65 |
+
self._cache.clear()
|
| 66 |
+
|
| 67 |
+
def __len__(self):
|
| 68 |
+
return len(self._cache)
|
| 69 |
+
|
| 70 |
+
def __contains__(self, item):
|
| 71 |
+
try:
|
| 72 |
+
self[item]
|
| 73 |
+
return True
|
| 74 |
+
except KeyError:
|
| 75 |
+
return False
|
| 76 |
+
|
| 77 |
+
def __setitem__(self, key, value):
|
| 78 |
+
if not self.use_listings_cache:
|
| 79 |
+
return
|
| 80 |
+
if self.max_paths:
|
| 81 |
+
self._q(key)
|
| 82 |
+
self._cache[key] = value
|
| 83 |
+
if self.listings_expiry_time is not None:
|
| 84 |
+
self._times[key] = time.time()
|
| 85 |
+
|
| 86 |
+
def __delitem__(self, key):
|
| 87 |
+
del self._cache[key]
|
| 88 |
+
|
| 89 |
+
def __iter__(self):
|
| 90 |
+
entries = list(self._cache)
|
| 91 |
+
|
| 92 |
+
return (k for k in entries if k in self)
|
| 93 |
+
|
| 94 |
+
def __reduce__(self):
|
| 95 |
+
return (
|
| 96 |
+
DirCache,
|
| 97 |
+
(self.use_listings_cache, self.listings_expiry_time, self.max_paths),
|
| 98 |
+
)
|
.venv/lib/python3.12/site-packages/fsspec/exceptions.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
fsspec user-defined exception classes
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import asyncio
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class BlocksizeMismatchError(ValueError):
|
| 9 |
+
"""
|
| 10 |
+
Raised when a cached file is opened with a different blocksize than it was
|
| 11 |
+
written with
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class FSTimeoutError(asyncio.TimeoutError):
|
| 16 |
+
"""
|
| 17 |
+
Raised when a fsspec function timed out occurs
|
| 18 |
+
"""
|
.venv/lib/python3.12/site-packages/fsspec/fuse.py
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import logging
|
| 3 |
+
import os
|
| 4 |
+
import stat
|
| 5 |
+
import threading
|
| 6 |
+
import time
|
| 7 |
+
from errno import EIO, ENOENT
|
| 8 |
+
|
| 9 |
+
from fuse import FUSE, FuseOSError, LoggingMixIn, Operations
|
| 10 |
+
|
| 11 |
+
from fsspec import __version__
|
| 12 |
+
from fsspec.core import url_to_fs
|
| 13 |
+
|
| 14 |
+
logger = logging.getLogger("fsspec.fuse")
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class FUSEr(Operations):
|
| 18 |
+
def __init__(self, fs, path, ready_file=False):
|
| 19 |
+
self.fs = fs
|
| 20 |
+
self.cache = {}
|
| 21 |
+
self.root = path.rstrip("/") + "/"
|
| 22 |
+
self.counter = 0
|
| 23 |
+
logger.info("Starting FUSE at %s", path)
|
| 24 |
+
self._ready_file = ready_file
|
| 25 |
+
|
| 26 |
+
def getattr(self, path, fh=None):
|
| 27 |
+
logger.debug("getattr %s", path)
|
| 28 |
+
if self._ready_file and path in ["/.fuse_ready", ".fuse_ready"]:
|
| 29 |
+
return {"type": "file", "st_size": 5}
|
| 30 |
+
|
| 31 |
+
path = "".join([self.root, path.lstrip("/")]).rstrip("/")
|
| 32 |
+
try:
|
| 33 |
+
info = self.fs.info(path)
|
| 34 |
+
except FileNotFoundError as exc:
|
| 35 |
+
raise FuseOSError(ENOENT) from exc
|
| 36 |
+
|
| 37 |
+
data = {"st_uid": info.get("uid", 1000), "st_gid": info.get("gid", 1000)}
|
| 38 |
+
perm = info.get("mode", 0o777)
|
| 39 |
+
|
| 40 |
+
if info["type"] != "file":
|
| 41 |
+
data["st_mode"] = stat.S_IFDIR | perm
|
| 42 |
+
data["st_size"] = 0
|
| 43 |
+
data["st_blksize"] = 0
|
| 44 |
+
else:
|
| 45 |
+
data["st_mode"] = stat.S_IFREG | perm
|
| 46 |
+
data["st_size"] = info["size"]
|
| 47 |
+
data["st_blksize"] = 5 * 2**20
|
| 48 |
+
data["st_nlink"] = 1
|
| 49 |
+
data["st_atime"] = info["atime"] if "atime" in info else time.time()
|
| 50 |
+
data["st_ctime"] = info["ctime"] if "ctime" in info else time.time()
|
| 51 |
+
data["st_mtime"] = info["mtime"] if "mtime" in info else time.time()
|
| 52 |
+
return data
|
| 53 |
+
|
| 54 |
+
def readdir(self, path, fh):
|
| 55 |
+
logger.debug("readdir %s", path)
|
| 56 |
+
path = "".join([self.root, path.lstrip("/")])
|
| 57 |
+
files = self.fs.ls(path, False)
|
| 58 |
+
files = [os.path.basename(f.rstrip("/")) for f in files]
|
| 59 |
+
return [".", ".."] + files
|
| 60 |
+
|
| 61 |
+
def mkdir(self, path, mode):
|
| 62 |
+
path = "".join([self.root, path.lstrip("/")])
|
| 63 |
+
self.fs.mkdir(path)
|
| 64 |
+
return 0
|
| 65 |
+
|
| 66 |
+
def rmdir(self, path):
|
| 67 |
+
path = "".join([self.root, path.lstrip("/")])
|
| 68 |
+
self.fs.rmdir(path)
|
| 69 |
+
return 0
|
| 70 |
+
|
| 71 |
+
def read(self, path, size, offset, fh):
|
| 72 |
+
logger.debug("read %s", (path, size, offset))
|
| 73 |
+
if self._ready_file and path in ["/.fuse_ready", ".fuse_ready"]:
|
| 74 |
+
# status indicator
|
| 75 |
+
return b"ready"
|
| 76 |
+
|
| 77 |
+
f = self.cache[fh]
|
| 78 |
+
f.seek(offset)
|
| 79 |
+
out = f.read(size)
|
| 80 |
+
return out
|
| 81 |
+
|
| 82 |
+
def write(self, path, data, offset, fh):
|
| 83 |
+
logger.debug("write %s", (path, offset))
|
| 84 |
+
f = self.cache[fh]
|
| 85 |
+
f.seek(offset)
|
| 86 |
+
f.write(data)
|
| 87 |
+
return len(data)
|
| 88 |
+
|
| 89 |
+
def create(self, path, flags, fi=None):
|
| 90 |
+
logger.debug("create %s", (path, flags))
|
| 91 |
+
fn = "".join([self.root, path.lstrip("/")])
|
| 92 |
+
self.fs.touch(fn) # OS will want to get attributes immediately
|
| 93 |
+
f = self.fs.open(fn, "wb")
|
| 94 |
+
self.cache[self.counter] = f
|
| 95 |
+
self.counter += 1
|
| 96 |
+
return self.counter - 1
|
| 97 |
+
|
| 98 |
+
def open(self, path, flags):
|
| 99 |
+
logger.debug("open %s", (path, flags))
|
| 100 |
+
fn = "".join([self.root, path.lstrip("/")])
|
| 101 |
+
if flags % 2 == 0:
|
| 102 |
+
# read
|
| 103 |
+
mode = "rb"
|
| 104 |
+
else:
|
| 105 |
+
# write/create
|
| 106 |
+
mode = "wb"
|
| 107 |
+
self.cache[self.counter] = self.fs.open(fn, mode)
|
| 108 |
+
self.counter += 1
|
| 109 |
+
return self.counter - 1
|
| 110 |
+
|
| 111 |
+
def truncate(self, path, length, fh=None):
|
| 112 |
+
fn = "".join([self.root, path.lstrip("/")])
|
| 113 |
+
if length != 0:
|
| 114 |
+
raise NotImplementedError
|
| 115 |
+
# maybe should be no-op since open with write sets size to zero anyway
|
| 116 |
+
self.fs.touch(fn)
|
| 117 |
+
|
| 118 |
+
def unlink(self, path):
|
| 119 |
+
fn = "".join([self.root, path.lstrip("/")])
|
| 120 |
+
try:
|
| 121 |
+
self.fs.rm(fn, False)
|
| 122 |
+
except (OSError, FileNotFoundError) as exc:
|
| 123 |
+
raise FuseOSError(EIO) from exc
|
| 124 |
+
|
| 125 |
+
def release(self, path, fh):
|
| 126 |
+
try:
|
| 127 |
+
if fh in self.cache:
|
| 128 |
+
f = self.cache[fh]
|
| 129 |
+
f.close()
|
| 130 |
+
self.cache.pop(fh)
|
| 131 |
+
except Exception as e:
|
| 132 |
+
print(e)
|
| 133 |
+
return 0
|
| 134 |
+
|
| 135 |
+
def chmod(self, path, mode):
|
| 136 |
+
if hasattr(self.fs, "chmod"):
|
| 137 |
+
path = "".join([self.root, path.lstrip("/")])
|
| 138 |
+
return self.fs.chmod(path, mode)
|
| 139 |
+
raise NotImplementedError
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def run(
|
| 143 |
+
fs,
|
| 144 |
+
path,
|
| 145 |
+
mount_point,
|
| 146 |
+
foreground=True,
|
| 147 |
+
threads=False,
|
| 148 |
+
ready_file=False,
|
| 149 |
+
ops_class=FUSEr,
|
| 150 |
+
):
|
| 151 |
+
"""Mount stuff in a local directory
|
| 152 |
+
|
| 153 |
+
This uses fusepy to make it appear as if a given path on an fsspec
|
| 154 |
+
instance is in fact resident within the local file-system.
|
| 155 |
+
|
| 156 |
+
This requires that fusepy by installed, and that FUSE be available on
|
| 157 |
+
the system (typically requiring a package to be installed with
|
| 158 |
+
apt, yum, brew, etc.).
|
| 159 |
+
|
| 160 |
+
Parameters
|
| 161 |
+
----------
|
| 162 |
+
fs: file-system instance
|
| 163 |
+
From one of the compatible implementations
|
| 164 |
+
path: str
|
| 165 |
+
Location on that file-system to regard as the root directory to
|
| 166 |
+
mount. Note that you typically should include the terminating "/"
|
| 167 |
+
character.
|
| 168 |
+
mount_point: str
|
| 169 |
+
An empty directory on the local file-system where the contents of
|
| 170 |
+
the remote path will appear.
|
| 171 |
+
foreground: bool
|
| 172 |
+
Whether or not calling this function will block. Operation will
|
| 173 |
+
typically be more stable if True.
|
| 174 |
+
threads: bool
|
| 175 |
+
Whether or not to create threads when responding to file operations
|
| 176 |
+
within the mounter directory. Operation will typically be more
|
| 177 |
+
stable if False.
|
| 178 |
+
ready_file: bool
|
| 179 |
+
Whether the FUSE process is ready. The ``.fuse_ready`` file will
|
| 180 |
+
exist in the ``mount_point`` directory if True. Debugging purpose.
|
| 181 |
+
ops_class: FUSEr or Subclass of FUSEr
|
| 182 |
+
To override the default behavior of FUSEr. For Example, logging
|
| 183 |
+
to file.
|
| 184 |
+
|
| 185 |
+
"""
|
| 186 |
+
func = lambda: FUSE(
|
| 187 |
+
ops_class(fs, path, ready_file=ready_file),
|
| 188 |
+
mount_point,
|
| 189 |
+
nothreads=not threads,
|
| 190 |
+
foreground=foreground,
|
| 191 |
+
)
|
| 192 |
+
if not foreground:
|
| 193 |
+
th = threading.Thread(target=func)
|
| 194 |
+
th.daemon = True
|
| 195 |
+
th.start()
|
| 196 |
+
return th
|
| 197 |
+
else: # pragma: no cover
|
| 198 |
+
try:
|
| 199 |
+
func()
|
| 200 |
+
except KeyboardInterrupt:
|
| 201 |
+
pass
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def main(args):
|
| 205 |
+
"""Mount filesystem from chained URL to MOUNT_POINT.
|
| 206 |
+
|
| 207 |
+
Examples:
|
| 208 |
+
|
| 209 |
+
python3 -m fsspec.fuse memory /usr/share /tmp/mem
|
| 210 |
+
|
| 211 |
+
python3 -m fsspec.fuse local /tmp/source /tmp/local \\
|
| 212 |
+
-l /tmp/fsspecfuse.log
|
| 213 |
+
|
| 214 |
+
You can also mount chained-URLs and use special settings:
|
| 215 |
+
|
| 216 |
+
python3 -m fsspec.fuse 'filecache::zip::file://data.zip' \\
|
| 217 |
+
/ /tmp/zip \\
|
| 218 |
+
-o 'filecache-cache_storage=/tmp/simplecache'
|
| 219 |
+
|
| 220 |
+
You can specify the type of the setting by using `[int]` or `[bool]`,
|
| 221 |
+
(`true`, `yes`, `1` represents the Boolean value `True`):
|
| 222 |
+
|
| 223 |
+
python3 -m fsspec.fuse 'simplecache::ftp://ftp1.at.proftpd.org' \\
|
| 224 |
+
/historic/packages/RPMS /tmp/ftp \\
|
| 225 |
+
-o 'simplecache-cache_storage=/tmp/simplecache' \\
|
| 226 |
+
-o 'simplecache-check_files=false[bool]' \\
|
| 227 |
+
-o 'ftp-listings_expiry_time=60[int]' \\
|
| 228 |
+
-o 'ftp-username=anonymous' \\
|
| 229 |
+
-o 'ftp-password=xieyanbo'
|
| 230 |
+
"""
|
| 231 |
+
|
| 232 |
+
class RawDescriptionArgumentParser(argparse.ArgumentParser):
|
| 233 |
+
def format_help(self):
|
| 234 |
+
usage = super().format_help()
|
| 235 |
+
parts = usage.split("\n\n")
|
| 236 |
+
parts[1] = self.description.rstrip()
|
| 237 |
+
return "\n\n".join(parts)
|
| 238 |
+
|
| 239 |
+
parser = RawDescriptionArgumentParser(prog="fsspec.fuse", description=main.__doc__)
|
| 240 |
+
parser.add_argument("--version", action="version", version=__version__)
|
| 241 |
+
parser.add_argument("url", type=str, help="fs url")
|
| 242 |
+
parser.add_argument("source_path", type=str, help="source directory in fs")
|
| 243 |
+
parser.add_argument("mount_point", type=str, help="local directory")
|
| 244 |
+
parser.add_argument(
|
| 245 |
+
"-o",
|
| 246 |
+
"--option",
|
| 247 |
+
action="append",
|
| 248 |
+
help="Any options of protocol included in the chained URL",
|
| 249 |
+
)
|
| 250 |
+
parser.add_argument(
|
| 251 |
+
"-l", "--log-file", type=str, help="Logging FUSE debug info (Default: '')"
|
| 252 |
+
)
|
| 253 |
+
parser.add_argument(
|
| 254 |
+
"-f",
|
| 255 |
+
"--foreground",
|
| 256 |
+
action="store_false",
|
| 257 |
+
help="Running in foreground or not (Default: False)",
|
| 258 |
+
)
|
| 259 |
+
parser.add_argument(
|
| 260 |
+
"-t",
|
| 261 |
+
"--threads",
|
| 262 |
+
action="store_false",
|
| 263 |
+
help="Running with threads support (Default: False)",
|
| 264 |
+
)
|
| 265 |
+
parser.add_argument(
|
| 266 |
+
"-r",
|
| 267 |
+
"--ready-file",
|
| 268 |
+
action="store_false",
|
| 269 |
+
help="The `.fuse_ready` file will exist after FUSE is ready. "
|
| 270 |
+
"(Debugging purpose, Default: False)",
|
| 271 |
+
)
|
| 272 |
+
args = parser.parse_args(args)
|
| 273 |
+
|
| 274 |
+
kwargs = {}
|
| 275 |
+
for item in args.option or []:
|
| 276 |
+
key, sep, value = item.partition("=")
|
| 277 |
+
if not sep:
|
| 278 |
+
parser.error(message=f"Wrong option: {item!r}")
|
| 279 |
+
val = value.lower()
|
| 280 |
+
if val.endswith("[int]"):
|
| 281 |
+
value = int(value[: -len("[int]")])
|
| 282 |
+
elif val.endswith("[bool]"):
|
| 283 |
+
value = val[: -len("[bool]")] in ["1", "yes", "true"]
|
| 284 |
+
|
| 285 |
+
if "-" in key:
|
| 286 |
+
fs_name, setting_name = key.split("-", 1)
|
| 287 |
+
if fs_name in kwargs:
|
| 288 |
+
kwargs[fs_name][setting_name] = value
|
| 289 |
+
else:
|
| 290 |
+
kwargs[fs_name] = {setting_name: value}
|
| 291 |
+
else:
|
| 292 |
+
kwargs[key] = value
|
| 293 |
+
|
| 294 |
+
if args.log_file:
|
| 295 |
+
logging.basicConfig(
|
| 296 |
+
level=logging.DEBUG,
|
| 297 |
+
filename=args.log_file,
|
| 298 |
+
format="%(asctime)s %(message)s",
|
| 299 |
+
)
|
| 300 |
+
|
| 301 |
+
class LoggingFUSEr(FUSEr, LoggingMixIn):
|
| 302 |
+
pass
|
| 303 |
+
|
| 304 |
+
fuser = LoggingFUSEr
|
| 305 |
+
else:
|
| 306 |
+
fuser = FUSEr
|
| 307 |
+
|
| 308 |
+
fs, url_path = url_to_fs(args.url, **kwargs)
|
| 309 |
+
logger.debug("Mounting %s to %s", url_path, str(args.mount_point))
|
| 310 |
+
run(
|
| 311 |
+
fs,
|
| 312 |
+
args.source_path,
|
| 313 |
+
args.mount_point,
|
| 314 |
+
foreground=args.foreground,
|
| 315 |
+
threads=args.threads,
|
| 316 |
+
ready_file=args.ready_file,
|
| 317 |
+
ops_class=fuser,
|
| 318 |
+
)
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
if __name__ == "__main__":
|
| 322 |
+
import sys
|
| 323 |
+
|
| 324 |
+
main(sys.argv[1:])
|
.venv/lib/python3.12/site-packages/fsspec/generic.py
ADDED
|
@@ -0,0 +1,396 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import inspect
|
| 4 |
+
import logging
|
| 5 |
+
import os
|
| 6 |
+
import shutil
|
| 7 |
+
import uuid
|
| 8 |
+
|
| 9 |
+
from .asyn import AsyncFileSystem, _run_coros_in_chunks, sync_wrapper
|
| 10 |
+
from .callbacks import DEFAULT_CALLBACK
|
| 11 |
+
from .core import filesystem, get_filesystem_class, split_protocol, url_to_fs
|
| 12 |
+
|
| 13 |
+
_generic_fs = {}
|
| 14 |
+
logger = logging.getLogger("fsspec.generic")
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def set_generic_fs(protocol, **storage_options):
|
| 18 |
+
"""Populate the dict used for method=="generic" lookups"""
|
| 19 |
+
_generic_fs[protocol] = filesystem(protocol, **storage_options)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _resolve_fs(url, method, protocol=None, storage_options=None):
|
| 23 |
+
"""Pick instance of backend FS"""
|
| 24 |
+
url = url[0] if isinstance(url, (list, tuple)) else url
|
| 25 |
+
protocol = protocol or split_protocol(url)[0]
|
| 26 |
+
storage_options = storage_options or {}
|
| 27 |
+
if method == "default":
|
| 28 |
+
return filesystem(protocol)
|
| 29 |
+
if method == "generic":
|
| 30 |
+
return _generic_fs[protocol]
|
| 31 |
+
if method == "current":
|
| 32 |
+
cls = get_filesystem_class(protocol)
|
| 33 |
+
return cls.current()
|
| 34 |
+
if method == "options":
|
| 35 |
+
fs, _ = url_to_fs(url, **storage_options.get(protocol, {}))
|
| 36 |
+
return fs
|
| 37 |
+
raise ValueError(f"Unknown FS resolution method: {method}")
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def rsync(
|
| 41 |
+
source,
|
| 42 |
+
destination,
|
| 43 |
+
delete_missing=False,
|
| 44 |
+
source_field="size",
|
| 45 |
+
dest_field="size",
|
| 46 |
+
update_cond="different",
|
| 47 |
+
inst_kwargs=None,
|
| 48 |
+
fs=None,
|
| 49 |
+
**kwargs,
|
| 50 |
+
):
|
| 51 |
+
"""Sync files between two directory trees
|
| 52 |
+
|
| 53 |
+
(experimental)
|
| 54 |
+
|
| 55 |
+
Parameters
|
| 56 |
+
----------
|
| 57 |
+
source: str
|
| 58 |
+
Root of the directory tree to take files from. This must be a directory, but
|
| 59 |
+
do not include any terminating "/" character
|
| 60 |
+
destination: str
|
| 61 |
+
Root path to copy into. The contents of this location should be
|
| 62 |
+
identical to the contents of ``source`` when done. This will be made a
|
| 63 |
+
directory, and the terminal "/" should not be included.
|
| 64 |
+
delete_missing: bool
|
| 65 |
+
If there are paths in the destination that don't exist in the
|
| 66 |
+
source and this is True, delete them. Otherwise, leave them alone.
|
| 67 |
+
source_field: str | callable
|
| 68 |
+
If ``update_field`` is "different", this is the key in the info
|
| 69 |
+
of source files to consider for difference. Maybe a function of the
|
| 70 |
+
info dict.
|
| 71 |
+
dest_field: str | callable
|
| 72 |
+
If ``update_field`` is "different", this is the key in the info
|
| 73 |
+
of destination files to consider for difference. May be a function of
|
| 74 |
+
the info dict.
|
| 75 |
+
update_cond: "different"|"always"|"never"
|
| 76 |
+
If "always", every file is copied, regardless of whether it exists in
|
| 77 |
+
the destination. If "never", files that exist in the destination are
|
| 78 |
+
not copied again. If "different" (default), only copy if the info
|
| 79 |
+
fields given by ``source_field`` and ``dest_field`` (usually "size")
|
| 80 |
+
are different. Other comparisons may be added in the future.
|
| 81 |
+
inst_kwargs: dict|None
|
| 82 |
+
If ``fs`` is None, use this set of keyword arguments to make a
|
| 83 |
+
GenericFileSystem instance
|
| 84 |
+
fs: GenericFileSystem|None
|
| 85 |
+
Instance to use if explicitly given. The instance defines how to
|
| 86 |
+
to make downstream file system instances from paths.
|
| 87 |
+
|
| 88 |
+
Returns
|
| 89 |
+
-------
|
| 90 |
+
dict of the copy operations that were performed, {source: destination}
|
| 91 |
+
"""
|
| 92 |
+
fs = fs or GenericFileSystem(**(inst_kwargs or {}))
|
| 93 |
+
source = fs._strip_protocol(source)
|
| 94 |
+
destination = fs._strip_protocol(destination)
|
| 95 |
+
allfiles = fs.find(source, withdirs=True, detail=True)
|
| 96 |
+
if not fs.isdir(source):
|
| 97 |
+
raise ValueError("Can only rsync on a directory")
|
| 98 |
+
otherfiles = fs.find(destination, withdirs=True, detail=True)
|
| 99 |
+
dirs = [
|
| 100 |
+
a
|
| 101 |
+
for a, v in allfiles.items()
|
| 102 |
+
if v["type"] == "directory" and a.replace(source, destination) not in otherfiles
|
| 103 |
+
]
|
| 104 |
+
logger.debug(f"{len(dirs)} directories to create")
|
| 105 |
+
if dirs:
|
| 106 |
+
fs.make_many_dirs(
|
| 107 |
+
[dirn.replace(source, destination) for dirn in dirs], exist_ok=True
|
| 108 |
+
)
|
| 109 |
+
allfiles = {a: v for a, v in allfiles.items() if v["type"] == "file"}
|
| 110 |
+
logger.debug(f"{len(allfiles)} files to consider for copy")
|
| 111 |
+
to_delete = [
|
| 112 |
+
o
|
| 113 |
+
for o, v in otherfiles.items()
|
| 114 |
+
if o.replace(destination, source) not in allfiles and v["type"] == "file"
|
| 115 |
+
]
|
| 116 |
+
for k, v in allfiles.copy().items():
|
| 117 |
+
otherfile = k.replace(source, destination)
|
| 118 |
+
if otherfile in otherfiles:
|
| 119 |
+
if update_cond == "always":
|
| 120 |
+
allfiles[k] = otherfile
|
| 121 |
+
elif update_cond == "never":
|
| 122 |
+
allfiles.pop(k)
|
| 123 |
+
elif update_cond == "different":
|
| 124 |
+
inf1 = source_field(v) if callable(source_field) else v[source_field]
|
| 125 |
+
v2 = otherfiles[otherfile]
|
| 126 |
+
inf2 = dest_field(v2) if callable(dest_field) else v2[dest_field]
|
| 127 |
+
if inf1 != inf2:
|
| 128 |
+
# details mismatch, make copy
|
| 129 |
+
allfiles[k] = otherfile
|
| 130 |
+
else:
|
| 131 |
+
# details match, don't copy
|
| 132 |
+
allfiles.pop(k)
|
| 133 |
+
else:
|
| 134 |
+
# file not in target yet
|
| 135 |
+
allfiles[k] = otherfile
|
| 136 |
+
logger.debug(f"{len(allfiles)} files to copy")
|
| 137 |
+
if allfiles:
|
| 138 |
+
source_files, target_files = zip(*allfiles.items())
|
| 139 |
+
fs.cp(source_files, target_files, **kwargs)
|
| 140 |
+
logger.debug(f"{len(to_delete)} files to delete")
|
| 141 |
+
if delete_missing and to_delete:
|
| 142 |
+
fs.rm(to_delete)
|
| 143 |
+
return allfiles
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
class GenericFileSystem(AsyncFileSystem):
|
| 147 |
+
"""Wrapper over all other FS types
|
| 148 |
+
|
| 149 |
+
<experimental!>
|
| 150 |
+
|
| 151 |
+
This implementation is a single unified interface to be able to run FS operations
|
| 152 |
+
over generic URLs, and dispatch to the specific implementations using the URL
|
| 153 |
+
protocol prefix.
|
| 154 |
+
|
| 155 |
+
Note: instances of this FS are always async, even if you never use it with any async
|
| 156 |
+
backend.
|
| 157 |
+
"""
|
| 158 |
+
|
| 159 |
+
protocol = "generic" # there is no real reason to ever use a protocol with this FS
|
| 160 |
+
|
| 161 |
+
def __init__(self, default_method="default", storage_options=None, **kwargs):
|
| 162 |
+
"""
|
| 163 |
+
|
| 164 |
+
Parameters
|
| 165 |
+
----------
|
| 166 |
+
default_method: str (optional)
|
| 167 |
+
Defines how to configure backend FS instances. Options are:
|
| 168 |
+
- "default": instantiate like FSClass(), with no
|
| 169 |
+
extra arguments; this is the default instance of that FS, and can be
|
| 170 |
+
configured via the config system
|
| 171 |
+
- "generic": takes instances from the `_generic_fs` dict in this module,
|
| 172 |
+
which you must populate before use. Keys are by protocol
|
| 173 |
+
- "options": expects storage_options, a dict mapping protocol to
|
| 174 |
+
kwargs to use when constructing the filesystem
|
| 175 |
+
- "current": takes the most recently instantiated version of each FS
|
| 176 |
+
"""
|
| 177 |
+
self.method = default_method
|
| 178 |
+
self.st_opts = storage_options
|
| 179 |
+
super().__init__(**kwargs)
|
| 180 |
+
|
| 181 |
+
def _parent(self, path):
|
| 182 |
+
fs = _resolve_fs(path, self.method, storage_options=self.st_opts)
|
| 183 |
+
return fs.unstrip_protocol(fs._parent(path))
|
| 184 |
+
|
| 185 |
+
def _strip_protocol(self, path):
|
| 186 |
+
# normalization only
|
| 187 |
+
fs = _resolve_fs(path, self.method, storage_options=self.st_opts)
|
| 188 |
+
return fs.unstrip_protocol(fs._strip_protocol(path))
|
| 189 |
+
|
| 190 |
+
async def _find(self, path, maxdepth=None, withdirs=False, detail=False, **kwargs):
|
| 191 |
+
fs = _resolve_fs(path, self.method, storage_options=self.st_opts)
|
| 192 |
+
if fs.async_impl:
|
| 193 |
+
out = await fs._find(
|
| 194 |
+
path, maxdepth=maxdepth, withdirs=withdirs, detail=True, **kwargs
|
| 195 |
+
)
|
| 196 |
+
else:
|
| 197 |
+
out = fs.find(
|
| 198 |
+
path, maxdepth=maxdepth, withdirs=withdirs, detail=True, **kwargs
|
| 199 |
+
)
|
| 200 |
+
result = {}
|
| 201 |
+
for k, v in out.items():
|
| 202 |
+
v = v.copy() # don't corrupt target FS dircache
|
| 203 |
+
name = fs.unstrip_protocol(k)
|
| 204 |
+
v["name"] = name
|
| 205 |
+
result[name] = v
|
| 206 |
+
if detail:
|
| 207 |
+
return result
|
| 208 |
+
return list(result)
|
| 209 |
+
|
| 210 |
+
async def _info(self, url, **kwargs):
|
| 211 |
+
fs = _resolve_fs(url, self.method, storage_options=self.st_opts)
|
| 212 |
+
if fs.async_impl:
|
| 213 |
+
out = await fs._info(url, **kwargs)
|
| 214 |
+
else:
|
| 215 |
+
out = fs.info(url, **kwargs)
|
| 216 |
+
out = out.copy() # don't edit originals
|
| 217 |
+
out["name"] = fs.unstrip_protocol(out["name"])
|
| 218 |
+
return out
|
| 219 |
+
|
| 220 |
+
async def _ls(
|
| 221 |
+
self,
|
| 222 |
+
url,
|
| 223 |
+
detail=True,
|
| 224 |
+
**kwargs,
|
| 225 |
+
):
|
| 226 |
+
fs = _resolve_fs(url, self.method, storage_options=self.st_opts)
|
| 227 |
+
if fs.async_impl:
|
| 228 |
+
out = await fs._ls(url, detail=True, **kwargs)
|
| 229 |
+
else:
|
| 230 |
+
out = fs.ls(url, detail=True, **kwargs)
|
| 231 |
+
out = [o.copy() for o in out] # don't edit originals
|
| 232 |
+
for o in out:
|
| 233 |
+
o["name"] = fs.unstrip_protocol(o["name"])
|
| 234 |
+
if detail:
|
| 235 |
+
return out
|
| 236 |
+
else:
|
| 237 |
+
return [o["name"] for o in out]
|
| 238 |
+
|
| 239 |
+
async def _cat_file(
|
| 240 |
+
self,
|
| 241 |
+
url,
|
| 242 |
+
**kwargs,
|
| 243 |
+
):
|
| 244 |
+
fs = _resolve_fs(url, self.method, storage_options=self.st_opts)
|
| 245 |
+
if fs.async_impl:
|
| 246 |
+
return await fs._cat_file(url, **kwargs)
|
| 247 |
+
else:
|
| 248 |
+
return fs.cat_file(url, **kwargs)
|
| 249 |
+
|
| 250 |
+
async def _pipe_file(
|
| 251 |
+
self,
|
| 252 |
+
path,
|
| 253 |
+
value,
|
| 254 |
+
**kwargs,
|
| 255 |
+
):
|
| 256 |
+
fs = _resolve_fs(path, self.method, storage_options=self.st_opts)
|
| 257 |
+
if fs.async_impl:
|
| 258 |
+
return await fs._pipe_file(path, value, **kwargs)
|
| 259 |
+
else:
|
| 260 |
+
return fs.pipe_file(path, value, **kwargs)
|
| 261 |
+
|
| 262 |
+
async def _rm(self, url, **kwargs):
|
| 263 |
+
urls = url
|
| 264 |
+
if isinstance(urls, str):
|
| 265 |
+
urls = [urls]
|
| 266 |
+
fs = _resolve_fs(urls[0], self.method, storage_options=self.st_opts)
|
| 267 |
+
if fs.async_impl:
|
| 268 |
+
await fs._rm(urls, **kwargs)
|
| 269 |
+
else:
|
| 270 |
+
fs.rm(url, **kwargs)
|
| 271 |
+
|
| 272 |
+
async def _makedirs(self, path, exist_ok=False):
|
| 273 |
+
logger.debug("Make dir %s", path)
|
| 274 |
+
fs = _resolve_fs(path, self.method, storage_options=self.st_opts)
|
| 275 |
+
if fs.async_impl:
|
| 276 |
+
await fs._makedirs(path, exist_ok=exist_ok)
|
| 277 |
+
else:
|
| 278 |
+
fs.makedirs(path, exist_ok=exist_ok)
|
| 279 |
+
|
| 280 |
+
def rsync(self, source, destination, **kwargs):
|
| 281 |
+
"""Sync files between two directory trees
|
| 282 |
+
|
| 283 |
+
See `func:rsync` for more details.
|
| 284 |
+
"""
|
| 285 |
+
rsync(source, destination, fs=self, **kwargs)
|
| 286 |
+
|
| 287 |
+
async def _cp_file(
|
| 288 |
+
self,
|
| 289 |
+
url,
|
| 290 |
+
url2,
|
| 291 |
+
blocksize=2**20,
|
| 292 |
+
callback=DEFAULT_CALLBACK,
|
| 293 |
+
tempdir: str | None = None,
|
| 294 |
+
**kwargs,
|
| 295 |
+
):
|
| 296 |
+
fs = _resolve_fs(url, self.method, storage_options=self.st_opts)
|
| 297 |
+
fs2 = _resolve_fs(url2, self.method, storage_options=self.st_opts)
|
| 298 |
+
if fs is fs2:
|
| 299 |
+
# pure remote
|
| 300 |
+
if fs.async_impl:
|
| 301 |
+
return await fs._copy(url, url2, **kwargs)
|
| 302 |
+
else:
|
| 303 |
+
return fs.copy(url, url2, **kwargs)
|
| 304 |
+
await copy_file_op(fs, [url], fs2, [url2], tempdir, 1, on_error="raise")
|
| 305 |
+
|
| 306 |
+
async def _make_many_dirs(self, urls, exist_ok=True):
|
| 307 |
+
fs = _resolve_fs(urls[0], self.method, storage_options=self.st_opts)
|
| 308 |
+
if fs.async_impl:
|
| 309 |
+
coros = [fs._makedirs(u, exist_ok=exist_ok) for u in urls]
|
| 310 |
+
await _run_coros_in_chunks(coros)
|
| 311 |
+
else:
|
| 312 |
+
for u in urls:
|
| 313 |
+
fs.makedirs(u, exist_ok=exist_ok)
|
| 314 |
+
|
| 315 |
+
make_many_dirs = sync_wrapper(_make_many_dirs)
|
| 316 |
+
|
| 317 |
+
async def _copy(
|
| 318 |
+
self,
|
| 319 |
+
path1: list[str],
|
| 320 |
+
path2: list[str],
|
| 321 |
+
recursive: bool = False,
|
| 322 |
+
on_error: str = "ignore",
|
| 323 |
+
maxdepth: int | None = None,
|
| 324 |
+
batch_size: int | None = None,
|
| 325 |
+
tempdir: str | None = None,
|
| 326 |
+
**kwargs,
|
| 327 |
+
):
|
| 328 |
+
# TODO: special case for one FS being local, which can use get/put
|
| 329 |
+
# TODO: special case for one being memFS, which can use cat/pipe
|
| 330 |
+
if recursive:
|
| 331 |
+
raise NotImplementedError("Please use fsspec.generic.rsync")
|
| 332 |
+
path1 = [path1] if isinstance(path1, str) else path1
|
| 333 |
+
path2 = [path2] if isinstance(path2, str) else path2
|
| 334 |
+
|
| 335 |
+
fs = _resolve_fs(path1, self.method, storage_options=self.st_opts)
|
| 336 |
+
fs2 = _resolve_fs(path2, self.method, storage_options=self.st_opts)
|
| 337 |
+
|
| 338 |
+
if fs is fs2:
|
| 339 |
+
if fs.async_impl:
|
| 340 |
+
return await fs._copy(path1, path2, **kwargs)
|
| 341 |
+
else:
|
| 342 |
+
return fs.copy(path1, path2, **kwargs)
|
| 343 |
+
|
| 344 |
+
await copy_file_op(
|
| 345 |
+
fs, path1, fs2, path2, tempdir, batch_size, on_error=on_error
|
| 346 |
+
)
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
async def copy_file_op(
|
| 350 |
+
fs1, url1, fs2, url2, tempdir=None, batch_size=20, on_error="ignore"
|
| 351 |
+
):
|
| 352 |
+
import tempfile
|
| 353 |
+
|
| 354 |
+
tempdir = tempdir or tempfile.mkdtemp()
|
| 355 |
+
try:
|
| 356 |
+
coros = [
|
| 357 |
+
_copy_file_op(
|
| 358 |
+
fs1,
|
| 359 |
+
u1,
|
| 360 |
+
fs2,
|
| 361 |
+
u2,
|
| 362 |
+
os.path.join(tempdir, uuid.uuid4().hex),
|
| 363 |
+
)
|
| 364 |
+
for u1, u2 in zip(url1, url2)
|
| 365 |
+
]
|
| 366 |
+
out = await _run_coros_in_chunks(
|
| 367 |
+
coros, batch_size=batch_size, return_exceptions=True
|
| 368 |
+
)
|
| 369 |
+
finally:
|
| 370 |
+
shutil.rmtree(tempdir)
|
| 371 |
+
if on_error == "return":
|
| 372 |
+
return out
|
| 373 |
+
elif on_error == "raise":
|
| 374 |
+
for o in out:
|
| 375 |
+
if isinstance(o, Exception):
|
| 376 |
+
raise o
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
async def _copy_file_op(fs1, url1, fs2, url2, local, on_error="ignore"):
|
| 380 |
+
if fs1.async_impl:
|
| 381 |
+
await fs1._get_file(url1, local)
|
| 382 |
+
else:
|
| 383 |
+
fs1.get_file(url1, local)
|
| 384 |
+
if fs2.async_impl:
|
| 385 |
+
await fs2._put_file(local, url2)
|
| 386 |
+
else:
|
| 387 |
+
fs2.put_file(local, url2)
|
| 388 |
+
os.unlink(local)
|
| 389 |
+
logger.debug("Copy %s -> %s; done", url1, url2)
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
async def maybe_await(cor):
|
| 393 |
+
if inspect.iscoroutine(cor):
|
| 394 |
+
return await cor
|
| 395 |
+
else:
|
| 396 |
+
return cor
|
.venv/lib/python3.12/site-packages/fsspec/gui.py
ADDED
|
@@ -0,0 +1,417 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import ast
|
| 2 |
+
import contextlib
|
| 3 |
+
import logging
|
| 4 |
+
import os
|
| 5 |
+
import re
|
| 6 |
+
from collections.abc import Sequence
|
| 7 |
+
from typing import ClassVar
|
| 8 |
+
|
| 9 |
+
import panel as pn
|
| 10 |
+
|
| 11 |
+
from .core import OpenFile, get_filesystem_class, split_protocol
|
| 12 |
+
from .registry import known_implementations
|
| 13 |
+
|
| 14 |
+
pn.extension()
|
| 15 |
+
logger = logging.getLogger("fsspec.gui")
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class SigSlot:
|
| 19 |
+
"""Signal-slot mixin, for Panel event passing
|
| 20 |
+
|
| 21 |
+
Include this class in a widget manager's superclasses to be able to
|
| 22 |
+
register events and callbacks on Panel widgets managed by that class.
|
| 23 |
+
|
| 24 |
+
The method ``_register`` should be called as widgets are added, and external
|
| 25 |
+
code should call ``connect`` to associate callbacks.
|
| 26 |
+
|
| 27 |
+
By default, all signals emit a DEBUG logging statement.
|
| 28 |
+
"""
|
| 29 |
+
|
| 30 |
+
# names of signals that this class may emit each of which must be
|
| 31 |
+
# set by _register for any new instance
|
| 32 |
+
signals: ClassVar[Sequence[str]] = []
|
| 33 |
+
# names of actions that this class may respond to
|
| 34 |
+
slots: ClassVar[Sequence[str]] = []
|
| 35 |
+
|
| 36 |
+
# each of which must be a method name
|
| 37 |
+
|
| 38 |
+
def __init__(self):
|
| 39 |
+
self._ignoring_events = False
|
| 40 |
+
self._sigs = {}
|
| 41 |
+
self._map = {}
|
| 42 |
+
self._setup()
|
| 43 |
+
|
| 44 |
+
def _setup(self):
|
| 45 |
+
"""Create GUI elements and register signals"""
|
| 46 |
+
self.panel = pn.pane.PaneBase()
|
| 47 |
+
# no signals to set up in the base class
|
| 48 |
+
|
| 49 |
+
def _register(
|
| 50 |
+
self, widget, name, thing="value", log_level=logging.DEBUG, auto=False
|
| 51 |
+
):
|
| 52 |
+
"""Watch the given attribute of a widget and assign it a named event
|
| 53 |
+
|
| 54 |
+
This is normally called at the time a widget is instantiated, in the
|
| 55 |
+
class which owns it.
|
| 56 |
+
|
| 57 |
+
Parameters
|
| 58 |
+
----------
|
| 59 |
+
widget : pn.layout.Panel or None
|
| 60 |
+
Widget to watch. If None, an anonymous signal not associated with
|
| 61 |
+
any widget.
|
| 62 |
+
name : str
|
| 63 |
+
Name of this event
|
| 64 |
+
thing : str
|
| 65 |
+
Attribute of the given widget to watch
|
| 66 |
+
log_level : int
|
| 67 |
+
When the signal is triggered, a logging event of the given level
|
| 68 |
+
will be fired in the dfviz logger.
|
| 69 |
+
auto : bool
|
| 70 |
+
If True, automatically connects with a method in this class of the
|
| 71 |
+
same name.
|
| 72 |
+
"""
|
| 73 |
+
if name not in self.signals:
|
| 74 |
+
raise ValueError(f"Attempt to assign an undeclared signal: {name}")
|
| 75 |
+
self._sigs[name] = {
|
| 76 |
+
"widget": widget,
|
| 77 |
+
"callbacks": [],
|
| 78 |
+
"thing": thing,
|
| 79 |
+
"log": log_level,
|
| 80 |
+
}
|
| 81 |
+
wn = "-".join(
|
| 82 |
+
[
|
| 83 |
+
getattr(widget, "name", str(widget)) if widget is not None else "none",
|
| 84 |
+
thing,
|
| 85 |
+
]
|
| 86 |
+
)
|
| 87 |
+
self._map[wn] = name
|
| 88 |
+
if widget is not None:
|
| 89 |
+
widget.param.watch(self._signal, thing, onlychanged=True)
|
| 90 |
+
if auto and hasattr(self, name):
|
| 91 |
+
self.connect(name, getattr(self, name))
|
| 92 |
+
|
| 93 |
+
def _repr_mimebundle_(self, *args, **kwargs):
|
| 94 |
+
"""Display in a notebook or a server"""
|
| 95 |
+
try:
|
| 96 |
+
return self.panel._repr_mimebundle_(*args, **kwargs)
|
| 97 |
+
except (ValueError, AttributeError) as exc:
|
| 98 |
+
raise NotImplementedError(
|
| 99 |
+
"Panel does not seem to be set up properly"
|
| 100 |
+
) from exc
|
| 101 |
+
|
| 102 |
+
def connect(self, signal, slot):
|
| 103 |
+
"""Associate call back with given event
|
| 104 |
+
|
| 105 |
+
The callback must be a function which takes the "new" value of the
|
| 106 |
+
watched attribute as the only parameter. If the callback return False,
|
| 107 |
+
this cancels any further processing of the given event.
|
| 108 |
+
|
| 109 |
+
Alternatively, the callback can be a string, in which case it means
|
| 110 |
+
emitting the correspondingly-named event (i.e., connect to self)
|
| 111 |
+
"""
|
| 112 |
+
self._sigs[signal]["callbacks"].append(slot)
|
| 113 |
+
|
| 114 |
+
def _signal(self, event):
|
| 115 |
+
"""This is called by a an action on a widget
|
| 116 |
+
|
| 117 |
+
Within an self.ignore_events context, nothing happens.
|
| 118 |
+
|
| 119 |
+
Tests can execute this method by directly changing the values of
|
| 120 |
+
widget components.
|
| 121 |
+
"""
|
| 122 |
+
if not self._ignoring_events:
|
| 123 |
+
wn = "-".join([event.obj.name, event.name])
|
| 124 |
+
if wn in self._map and self._map[wn] in self._sigs:
|
| 125 |
+
self._emit(self._map[wn], event.new)
|
| 126 |
+
|
| 127 |
+
@contextlib.contextmanager
|
| 128 |
+
def ignore_events(self):
|
| 129 |
+
"""Temporarily turn off events processing in this instance
|
| 130 |
+
|
| 131 |
+
(does not propagate to children)
|
| 132 |
+
"""
|
| 133 |
+
self._ignoring_events = True
|
| 134 |
+
try:
|
| 135 |
+
yield
|
| 136 |
+
finally:
|
| 137 |
+
self._ignoring_events = False
|
| 138 |
+
|
| 139 |
+
def _emit(self, sig, value=None):
|
| 140 |
+
"""An event happened, call its callbacks
|
| 141 |
+
|
| 142 |
+
This method can be used in tests to simulate message passing without
|
| 143 |
+
directly changing visual elements.
|
| 144 |
+
|
| 145 |
+
Calling of callbacks will halt whenever one returns False.
|
| 146 |
+
"""
|
| 147 |
+
logger.log(self._sigs[sig]["log"], f"{sig}: {value}")
|
| 148 |
+
for callback in self._sigs[sig]["callbacks"]:
|
| 149 |
+
if isinstance(callback, str):
|
| 150 |
+
self._emit(callback)
|
| 151 |
+
else:
|
| 152 |
+
try:
|
| 153 |
+
# running callbacks should not break the interface
|
| 154 |
+
ret = callback(value)
|
| 155 |
+
if ret is False:
|
| 156 |
+
break
|
| 157 |
+
except Exception as e:
|
| 158 |
+
logger.exception(
|
| 159 |
+
"Exception (%s) while executing callback for signal: %s",
|
| 160 |
+
e,
|
| 161 |
+
sig,
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
def show(self, threads=False):
|
| 165 |
+
"""Open a new browser tab and display this instance's interface"""
|
| 166 |
+
self.panel.show(threads=threads, verbose=False)
|
| 167 |
+
return self
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
class SingleSelect(SigSlot):
|
| 171 |
+
"""A multiselect which only allows you to select one item for an event"""
|
| 172 |
+
|
| 173 |
+
signals = ["_selected", "selected"] # the first is internal
|
| 174 |
+
slots = ["set_options", "set_selection", "add", "clear", "select"]
|
| 175 |
+
|
| 176 |
+
def __init__(self, **kwargs):
|
| 177 |
+
self.kwargs = kwargs
|
| 178 |
+
super().__init__()
|
| 179 |
+
|
| 180 |
+
def _setup(self):
|
| 181 |
+
self.panel = pn.widgets.MultiSelect(**self.kwargs)
|
| 182 |
+
self._register(self.panel, "_selected", "value")
|
| 183 |
+
self._register(None, "selected")
|
| 184 |
+
self.connect("_selected", self.select_one)
|
| 185 |
+
|
| 186 |
+
def _signal(self, *args, **kwargs):
|
| 187 |
+
super()._signal(*args, **kwargs)
|
| 188 |
+
|
| 189 |
+
def select_one(self, *_):
|
| 190 |
+
with self.ignore_events():
|
| 191 |
+
val = [self.panel.value[-1]] if self.panel.value else []
|
| 192 |
+
self.panel.value = val
|
| 193 |
+
self._emit("selected", self.panel.value)
|
| 194 |
+
|
| 195 |
+
def set_options(self, options):
|
| 196 |
+
self.panel.options = options
|
| 197 |
+
|
| 198 |
+
def clear(self):
|
| 199 |
+
self.panel.options = []
|
| 200 |
+
|
| 201 |
+
@property
|
| 202 |
+
def value(self):
|
| 203 |
+
return self.panel.value
|
| 204 |
+
|
| 205 |
+
def set_selection(self, selection):
|
| 206 |
+
self.panel.value = [selection]
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
class FileSelector(SigSlot):
|
| 210 |
+
"""Panel-based graphical file selector widget
|
| 211 |
+
|
| 212 |
+
Instances of this widget are interactive and can be displayed in jupyter by having
|
| 213 |
+
them as the output of a cell, or in a separate browser tab using ``.show()``.
|
| 214 |
+
"""
|
| 215 |
+
|
| 216 |
+
signals = [
|
| 217 |
+
"protocol_changed",
|
| 218 |
+
"selection_changed",
|
| 219 |
+
"directory_entered",
|
| 220 |
+
"home_clicked",
|
| 221 |
+
"up_clicked",
|
| 222 |
+
"go_clicked",
|
| 223 |
+
"filters_changed",
|
| 224 |
+
]
|
| 225 |
+
slots = ["set_filters", "go_home"]
|
| 226 |
+
|
| 227 |
+
def __init__(self, url=None, filters=None, ignore=None, kwargs=None):
|
| 228 |
+
"""
|
| 229 |
+
|
| 230 |
+
Parameters
|
| 231 |
+
----------
|
| 232 |
+
url : str (optional)
|
| 233 |
+
Initial value of the URL to populate the dialog; should include protocol
|
| 234 |
+
filters : list(str) (optional)
|
| 235 |
+
File endings to include in the listings. If not included, all files are
|
| 236 |
+
allowed. Does not affect directories.
|
| 237 |
+
If given, the endings will appear as checkboxes in the interface
|
| 238 |
+
ignore : list(str) (optional)
|
| 239 |
+
Regex(s) of file basename patterns to ignore, e.g., "\\." for typical
|
| 240 |
+
hidden files on posix
|
| 241 |
+
kwargs : dict (optional)
|
| 242 |
+
To pass to file system instance
|
| 243 |
+
"""
|
| 244 |
+
if url:
|
| 245 |
+
self.init_protocol, url = split_protocol(url)
|
| 246 |
+
else:
|
| 247 |
+
self.init_protocol, url = "file", os.getcwd()
|
| 248 |
+
self.init_url = url
|
| 249 |
+
self.init_kwargs = (kwargs if isinstance(kwargs, str) else str(kwargs)) or "{}"
|
| 250 |
+
self.filters = filters
|
| 251 |
+
self.ignore = [re.compile(i) for i in ignore or []]
|
| 252 |
+
self._fs = None
|
| 253 |
+
super().__init__()
|
| 254 |
+
|
| 255 |
+
def _setup(self):
|
| 256 |
+
self.url = pn.widgets.TextInput(
|
| 257 |
+
name="url",
|
| 258 |
+
value=self.init_url,
|
| 259 |
+
align="end",
|
| 260 |
+
sizing_mode="stretch_width",
|
| 261 |
+
width_policy="max",
|
| 262 |
+
)
|
| 263 |
+
self.protocol = pn.widgets.Select(
|
| 264 |
+
options=sorted(known_implementations),
|
| 265 |
+
value=self.init_protocol,
|
| 266 |
+
name="protocol",
|
| 267 |
+
align="center",
|
| 268 |
+
)
|
| 269 |
+
self.kwargs = pn.widgets.TextInput(
|
| 270 |
+
name="kwargs", value=self.init_kwargs, align="center"
|
| 271 |
+
)
|
| 272 |
+
self.go = pn.widgets.Button(name="⇨", align="end", width=45)
|
| 273 |
+
self.main = SingleSelect(size=10)
|
| 274 |
+
self.home = pn.widgets.Button(name="🏠", width=40, height=30, align="end")
|
| 275 |
+
self.up = pn.widgets.Button(name="‹", width=30, height=30, align="end")
|
| 276 |
+
|
| 277 |
+
self._register(self.protocol, "protocol_changed", auto=True)
|
| 278 |
+
self._register(self.go, "go_clicked", "clicks", auto=True)
|
| 279 |
+
self._register(self.up, "up_clicked", "clicks", auto=True)
|
| 280 |
+
self._register(self.home, "home_clicked", "clicks", auto=True)
|
| 281 |
+
self._register(None, "selection_changed")
|
| 282 |
+
self.main.connect("selected", self.selection_changed)
|
| 283 |
+
self._register(None, "directory_entered")
|
| 284 |
+
self.prev_protocol = self.protocol.value
|
| 285 |
+
self.prev_kwargs = self.storage_options
|
| 286 |
+
|
| 287 |
+
self.filter_sel = pn.widgets.CheckBoxGroup(
|
| 288 |
+
value=[], options=[], inline=False, align="end", width_policy="min"
|
| 289 |
+
)
|
| 290 |
+
self._register(self.filter_sel, "filters_changed", auto=True)
|
| 291 |
+
|
| 292 |
+
self.panel = pn.Column(
|
| 293 |
+
pn.Row(self.protocol, self.kwargs),
|
| 294 |
+
pn.Row(self.home, self.up, self.url, self.go, self.filter_sel),
|
| 295 |
+
self.main.panel,
|
| 296 |
+
)
|
| 297 |
+
self.set_filters(self.filters)
|
| 298 |
+
self.go_clicked()
|
| 299 |
+
|
| 300 |
+
def set_filters(self, filters=None):
|
| 301 |
+
self.filters = filters
|
| 302 |
+
if filters:
|
| 303 |
+
self.filter_sel.options = filters
|
| 304 |
+
self.filter_sel.value = filters
|
| 305 |
+
else:
|
| 306 |
+
self.filter_sel.options = []
|
| 307 |
+
self.filter_sel.value = []
|
| 308 |
+
|
| 309 |
+
@property
|
| 310 |
+
def storage_options(self):
|
| 311 |
+
"""Value of the kwargs box as a dictionary"""
|
| 312 |
+
return ast.literal_eval(self.kwargs.value) or {}
|
| 313 |
+
|
| 314 |
+
@property
|
| 315 |
+
def fs(self):
|
| 316 |
+
"""Current filesystem instance"""
|
| 317 |
+
if self._fs is None:
|
| 318 |
+
cls = get_filesystem_class(self.protocol.value)
|
| 319 |
+
self._fs = cls(**self.storage_options)
|
| 320 |
+
return self._fs
|
| 321 |
+
|
| 322 |
+
@property
|
| 323 |
+
def urlpath(self):
|
| 324 |
+
"""URL of currently selected item"""
|
| 325 |
+
return (
|
| 326 |
+
(f"{self.protocol.value}://{self.main.value[0]}")
|
| 327 |
+
if self.main.value
|
| 328 |
+
else None
|
| 329 |
+
)
|
| 330 |
+
|
| 331 |
+
def open_file(self, mode="rb", compression=None, encoding=None):
|
| 332 |
+
"""Create OpenFile instance for the currently selected item
|
| 333 |
+
|
| 334 |
+
For example, in a notebook you might do something like
|
| 335 |
+
|
| 336 |
+
.. code-block::
|
| 337 |
+
|
| 338 |
+
[ ]: sel = FileSelector(); sel
|
| 339 |
+
|
| 340 |
+
# user selects their file
|
| 341 |
+
|
| 342 |
+
[ ]: with sel.open_file('rb') as f:
|
| 343 |
+
... out = f.read()
|
| 344 |
+
|
| 345 |
+
Parameters
|
| 346 |
+
----------
|
| 347 |
+
mode: str (optional)
|
| 348 |
+
Open mode for the file.
|
| 349 |
+
compression: str (optional)
|
| 350 |
+
The interact with the file as compressed. Set to 'infer' to guess
|
| 351 |
+
compression from the file ending
|
| 352 |
+
encoding: str (optional)
|
| 353 |
+
If using text mode, use this encoding; defaults to UTF8.
|
| 354 |
+
"""
|
| 355 |
+
if self.urlpath is None:
|
| 356 |
+
raise ValueError("No file selected")
|
| 357 |
+
return OpenFile(self.fs, self.urlpath, mode, compression, encoding)
|
| 358 |
+
|
| 359 |
+
def filters_changed(self, values):
|
| 360 |
+
self.filters = values
|
| 361 |
+
self.go_clicked()
|
| 362 |
+
|
| 363 |
+
def selection_changed(self, *_):
|
| 364 |
+
if self.urlpath is None:
|
| 365 |
+
return
|
| 366 |
+
if self.fs.isdir(self.urlpath):
|
| 367 |
+
self.url.value = self.fs._strip_protocol(self.urlpath)
|
| 368 |
+
self.go_clicked()
|
| 369 |
+
|
| 370 |
+
def go_clicked(self, *_):
|
| 371 |
+
if (
|
| 372 |
+
self.prev_protocol != self.protocol.value
|
| 373 |
+
or self.prev_kwargs != self.storage_options
|
| 374 |
+
):
|
| 375 |
+
self._fs = None # causes fs to be recreated
|
| 376 |
+
self.prev_protocol = self.protocol.value
|
| 377 |
+
self.prev_kwargs = self.storage_options
|
| 378 |
+
listing = sorted(
|
| 379 |
+
self.fs.ls(self.url.value, detail=True), key=lambda x: x["name"]
|
| 380 |
+
)
|
| 381 |
+
listing = [
|
| 382 |
+
l
|
| 383 |
+
for l in listing
|
| 384 |
+
if not any(i.match(l["name"].rsplit("/", 1)[-1]) for i in self.ignore)
|
| 385 |
+
]
|
| 386 |
+
folders = {
|
| 387 |
+
"📁 " + o["name"].rsplit("/", 1)[-1]: o["name"]
|
| 388 |
+
for o in listing
|
| 389 |
+
if o["type"] == "directory"
|
| 390 |
+
}
|
| 391 |
+
files = {
|
| 392 |
+
"📄 " + o["name"].rsplit("/", 1)[-1]: o["name"]
|
| 393 |
+
for o in listing
|
| 394 |
+
if o["type"] == "file"
|
| 395 |
+
}
|
| 396 |
+
if self.filters:
|
| 397 |
+
files = {
|
| 398 |
+
k: v
|
| 399 |
+
for k, v in files.items()
|
| 400 |
+
if any(v.endswith(ext) for ext in self.filters)
|
| 401 |
+
}
|
| 402 |
+
self.main.set_options(dict(**folders, **files))
|
| 403 |
+
|
| 404 |
+
def protocol_changed(self, *_):
|
| 405 |
+
self._fs = None
|
| 406 |
+
self.main.options = []
|
| 407 |
+
self.url.value = ""
|
| 408 |
+
|
| 409 |
+
def home_clicked(self, *_):
|
| 410 |
+
self.protocol.value = self.init_protocol
|
| 411 |
+
self.kwargs.value = self.init_kwargs
|
| 412 |
+
self.url.value = self.init_url
|
| 413 |
+
self.go_clicked()
|
| 414 |
+
|
| 415 |
+
def up_clicked(self, *_):
|
| 416 |
+
self.url.value = self.fs._parent(self.url.value)
|
| 417 |
+
self.go_clicked()
|
.venv/lib/python3.12/site-packages/fsspec/implementations/__init__.py
ADDED
|
File without changes
|
.venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (197 Bytes). View file
|
|
|
.venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/arrow.cpython-312.pyc
ADDED
|
Binary file (14.7 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/asyn_wrapper.cpython-312.pyc
ADDED
|
Binary file (5.63 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/cache_mapper.cpython-312.pyc
ADDED
|
Binary file (4 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/cache_metadata.cpython-312.pyc
ADDED
|
Binary file (10.6 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/cached.cpython-312.pyc
ADDED
|
Binary file (48.7 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/chained.cpython-312.pyc
ADDED
|
Binary file (1.09 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/dask.cpython-312.pyc
ADDED
|
Binary file (7.11 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/data.cpython-312.pyc
ADDED
|
Binary file (3.64 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/dbfs.cpython-312.pyc
ADDED
|
Binary file (19.5 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/dirfs.cpython-312.pyc
ADDED
|
Binary file (26.3 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/ftp.cpython-312.pyc
ADDED
|
Binary file (19.8 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/gist.cpython-312.pyc
ADDED
|
Binary file (9.9 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/git.cpython-312.pyc
ADDED
|
Binary file (5.91 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/github.cpython-312.pyc
ADDED
|
Binary file (14.5 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/http.cpython-312.pyc
ADDED
|
Binary file (42.8 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/http_sync.cpython-312.pyc
ADDED
|
Binary file (40.2 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/jupyter.cpython-312.pyc
ADDED
|
Binary file (6.82 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/libarchive.cpython-312.pyc
ADDED
|
Binary file (8.68 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/local.cpython-312.pyc
ADDED
|
Binary file (26.2 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/memory.cpython-312.pyc
ADDED
|
Binary file (16.8 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/reference.cpython-312.pyc
ADDED
|
Binary file (65.6 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/sftp.cpython-312.pyc
ADDED
|
Binary file (10.3 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/smb.cpython-312.pyc
ADDED
|
Binary file (19.2 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/tar.cpython-312.pyc
ADDED
|
Binary file (5.36 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/webhdfs.cpython-312.pyc
ADDED
|
Binary file (23.9 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/fsspec/implementations/__pycache__/zip.cpython-312.pyc
ADDED
|
Binary file (8.25 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/fsspec/implementations/arrow.py
ADDED
|
@@ -0,0 +1,322 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import errno
|
| 2 |
+
import io
|
| 3 |
+
import os
|
| 4 |
+
import secrets
|
| 5 |
+
import shutil
|
| 6 |
+
from contextlib import suppress
|
| 7 |
+
from functools import cached_property, wraps
|
| 8 |
+
from urllib.parse import parse_qs
|
| 9 |
+
|
| 10 |
+
from fsspec.spec import AbstractFileSystem
|
| 11 |
+
from fsspec.utils import (
|
| 12 |
+
get_package_version_without_import,
|
| 13 |
+
infer_storage_options,
|
| 14 |
+
mirror_from,
|
| 15 |
+
tokenize,
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def wrap_exceptions(func):
|
| 20 |
+
@wraps(func)
|
| 21 |
+
def wrapper(*args, **kwargs):
|
| 22 |
+
try:
|
| 23 |
+
return func(*args, **kwargs)
|
| 24 |
+
except OSError as exception:
|
| 25 |
+
if not exception.args:
|
| 26 |
+
raise
|
| 27 |
+
|
| 28 |
+
message, *args = exception.args
|
| 29 |
+
if isinstance(message, str) and "does not exist" in message:
|
| 30 |
+
raise FileNotFoundError(errno.ENOENT, message) from exception
|
| 31 |
+
else:
|
| 32 |
+
raise
|
| 33 |
+
|
| 34 |
+
return wrapper
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
PYARROW_VERSION = None
|
| 38 |
+
_EMPTY_ROOT_MARKER_FILESYSTEMS = {"gcs", "s3"}
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class ArrowFSWrapper(AbstractFileSystem):
|
| 42 |
+
"""FSSpec-compatible wrapper of pyarrow.fs.FileSystem.
|
| 43 |
+
|
| 44 |
+
Parameters
|
| 45 |
+
----------
|
| 46 |
+
fs : pyarrow.fs.FileSystem
|
| 47 |
+
|
| 48 |
+
"""
|
| 49 |
+
|
| 50 |
+
root_marker = "/"
|
| 51 |
+
|
| 52 |
+
def __init__(self, fs, **kwargs):
|
| 53 |
+
global PYARROW_VERSION
|
| 54 |
+
PYARROW_VERSION = get_package_version_without_import("pyarrow")
|
| 55 |
+
self.fs = fs
|
| 56 |
+
if fs.type_name in _EMPTY_ROOT_MARKER_FILESYSTEMS:
|
| 57 |
+
self.root_marker = ""
|
| 58 |
+
super().__init__(**kwargs)
|
| 59 |
+
|
| 60 |
+
@property
|
| 61 |
+
def protocol(self):
|
| 62 |
+
return self.fs.type_name
|
| 63 |
+
|
| 64 |
+
@cached_property
|
| 65 |
+
def fsid(self):
|
| 66 |
+
return "hdfs_" + tokenize(self.fs.host, self.fs.port)
|
| 67 |
+
|
| 68 |
+
def _parent(self, path):
|
| 69 |
+
if self.root_marker:
|
| 70 |
+
return super()._parent(path)
|
| 71 |
+
|
| 72 |
+
path = self._strip_protocol(path).lstrip("/")
|
| 73 |
+
return path.rsplit("/", 1)[0] if "/" in path else ""
|
| 74 |
+
|
| 75 |
+
@classmethod
|
| 76 |
+
def _strip_protocol(cls, path):
|
| 77 |
+
ops = infer_storage_options(path)
|
| 78 |
+
path = ops["path"]
|
| 79 |
+
if path.startswith("//"):
|
| 80 |
+
# special case for "hdfs://path" (without the triple slash)
|
| 81 |
+
path = path[1:]
|
| 82 |
+
return path
|
| 83 |
+
|
| 84 |
+
def ls(self, path, detail=False, **kwargs):
|
| 85 |
+
path = self._strip_protocol(path)
|
| 86 |
+
from pyarrow.fs import FileSelector
|
| 87 |
+
|
| 88 |
+
try:
|
| 89 |
+
entries = [
|
| 90 |
+
self._make_entry(entry)
|
| 91 |
+
for entry in self.fs.get_file_info(FileSelector(path))
|
| 92 |
+
]
|
| 93 |
+
except (FileNotFoundError, NotADirectoryError):
|
| 94 |
+
entries = [self.info(path, **kwargs)]
|
| 95 |
+
if detail:
|
| 96 |
+
return entries
|
| 97 |
+
else:
|
| 98 |
+
return [entry["name"] for entry in entries]
|
| 99 |
+
|
| 100 |
+
def info(self, path, **kwargs):
|
| 101 |
+
path = self._strip_protocol(path)
|
| 102 |
+
[info] = self.fs.get_file_info([path])
|
| 103 |
+
return self._make_entry(info)
|
| 104 |
+
|
| 105 |
+
def exists(self, path):
|
| 106 |
+
path = self._strip_protocol(path)
|
| 107 |
+
try:
|
| 108 |
+
self.info(path)
|
| 109 |
+
except FileNotFoundError:
|
| 110 |
+
return False
|
| 111 |
+
else:
|
| 112 |
+
return True
|
| 113 |
+
|
| 114 |
+
def _make_entry(self, info):
|
| 115 |
+
from pyarrow.fs import FileType
|
| 116 |
+
|
| 117 |
+
if info.type is FileType.Directory:
|
| 118 |
+
kind = "directory"
|
| 119 |
+
elif info.type is FileType.File:
|
| 120 |
+
kind = "file"
|
| 121 |
+
elif info.type is FileType.NotFound:
|
| 122 |
+
raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), info.path)
|
| 123 |
+
else:
|
| 124 |
+
kind = "other"
|
| 125 |
+
|
| 126 |
+
return {
|
| 127 |
+
"name": info.path,
|
| 128 |
+
"size": info.size,
|
| 129 |
+
"type": kind,
|
| 130 |
+
"mtime": info.mtime,
|
| 131 |
+
}
|
| 132 |
+
|
| 133 |
+
@wrap_exceptions
|
| 134 |
+
def cp_file(self, path1, path2, **kwargs):
|
| 135 |
+
path1 = self._strip_protocol(path1).rstrip("/")
|
| 136 |
+
path2 = self._strip_protocol(path2).rstrip("/")
|
| 137 |
+
|
| 138 |
+
with self._open(path1, "rb") as lstream:
|
| 139 |
+
tmp_fname = f"{path2}.tmp.{secrets.token_hex(6)}"
|
| 140 |
+
try:
|
| 141 |
+
with self.open(tmp_fname, "wb") as rstream:
|
| 142 |
+
shutil.copyfileobj(lstream, rstream)
|
| 143 |
+
self.fs.move(tmp_fname, path2)
|
| 144 |
+
except BaseException:
|
| 145 |
+
with suppress(FileNotFoundError):
|
| 146 |
+
self.fs.delete_file(tmp_fname)
|
| 147 |
+
raise
|
| 148 |
+
|
| 149 |
+
@wrap_exceptions
|
| 150 |
+
def mv(self, path1, path2, **kwargs):
|
| 151 |
+
path1 = self._strip_protocol(path1).rstrip("/")
|
| 152 |
+
path2 = self._strip_protocol(path2).rstrip("/")
|
| 153 |
+
self.fs.move(path1, path2)
|
| 154 |
+
|
| 155 |
+
@wrap_exceptions
|
| 156 |
+
def rm_file(self, path):
|
| 157 |
+
path = self._strip_protocol(path)
|
| 158 |
+
self.fs.delete_file(path)
|
| 159 |
+
|
| 160 |
+
@wrap_exceptions
|
| 161 |
+
def rm(self, path, recursive=False, maxdepth=None):
|
| 162 |
+
path = self._strip_protocol(path).rstrip("/")
|
| 163 |
+
if self.isdir(path):
|
| 164 |
+
if recursive:
|
| 165 |
+
self.fs.delete_dir(path)
|
| 166 |
+
else:
|
| 167 |
+
raise ValueError("Can't delete directories without recursive=False")
|
| 168 |
+
else:
|
| 169 |
+
self.fs.delete_file(path)
|
| 170 |
+
|
| 171 |
+
@wrap_exceptions
|
| 172 |
+
def _open(self, path, mode="rb", block_size=None, seekable=True, **kwargs):
|
| 173 |
+
if mode == "rb":
|
| 174 |
+
if seekable:
|
| 175 |
+
method = self.fs.open_input_file
|
| 176 |
+
else:
|
| 177 |
+
method = self.fs.open_input_stream
|
| 178 |
+
elif mode == "wb":
|
| 179 |
+
method = self.fs.open_output_stream
|
| 180 |
+
elif mode == "ab":
|
| 181 |
+
method = self.fs.open_append_stream
|
| 182 |
+
else:
|
| 183 |
+
raise ValueError(f"unsupported mode for Arrow filesystem: {mode!r}")
|
| 184 |
+
|
| 185 |
+
_kwargs = {}
|
| 186 |
+
if mode != "rb" or not seekable:
|
| 187 |
+
if int(PYARROW_VERSION.split(".")[0]) >= 4:
|
| 188 |
+
# disable compression auto-detection
|
| 189 |
+
_kwargs["compression"] = None
|
| 190 |
+
stream = method(path, **_kwargs)
|
| 191 |
+
|
| 192 |
+
return ArrowFile(self, stream, path, mode, block_size, **kwargs)
|
| 193 |
+
|
| 194 |
+
@wrap_exceptions
|
| 195 |
+
def mkdir(self, path, create_parents=True, **kwargs):
|
| 196 |
+
path = self._strip_protocol(path)
|
| 197 |
+
if create_parents:
|
| 198 |
+
self.makedirs(path, exist_ok=True)
|
| 199 |
+
else:
|
| 200 |
+
self.fs.create_dir(path, recursive=False)
|
| 201 |
+
|
| 202 |
+
@wrap_exceptions
|
| 203 |
+
def makedirs(self, path, exist_ok=False):
|
| 204 |
+
path = self._strip_protocol(path)
|
| 205 |
+
self.fs.create_dir(path, recursive=True)
|
| 206 |
+
|
| 207 |
+
@wrap_exceptions
|
| 208 |
+
def rmdir(self, path):
|
| 209 |
+
path = self._strip_protocol(path)
|
| 210 |
+
self.fs.delete_dir(path)
|
| 211 |
+
|
| 212 |
+
@wrap_exceptions
|
| 213 |
+
def modified(self, path):
|
| 214 |
+
path = self._strip_protocol(path)
|
| 215 |
+
return self.fs.get_file_info(path).mtime
|
| 216 |
+
|
| 217 |
+
def cat_file(self, path, start=None, end=None, **kwargs):
|
| 218 |
+
kwargs.setdefault("seekable", start not in [None, 0])
|
| 219 |
+
return super().cat_file(path, start, end, **kwargs)
|
| 220 |
+
|
| 221 |
+
def get_file(self, rpath, lpath, **kwargs):
|
| 222 |
+
kwargs.setdefault("seekable", False)
|
| 223 |
+
super().get_file(rpath, lpath, **kwargs)
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
@mirror_from(
|
| 227 |
+
"stream",
|
| 228 |
+
[
|
| 229 |
+
"read",
|
| 230 |
+
"seek",
|
| 231 |
+
"tell",
|
| 232 |
+
"write",
|
| 233 |
+
"readable",
|
| 234 |
+
"writable",
|
| 235 |
+
"close",
|
| 236 |
+
"seekable",
|
| 237 |
+
],
|
| 238 |
+
)
|
| 239 |
+
class ArrowFile(io.IOBase):
|
| 240 |
+
def __init__(self, fs, stream, path, mode, block_size=None, **kwargs):
|
| 241 |
+
self.path = path
|
| 242 |
+
self.mode = mode
|
| 243 |
+
|
| 244 |
+
self.fs = fs
|
| 245 |
+
self.stream = stream
|
| 246 |
+
|
| 247 |
+
self.blocksize = self.block_size = block_size
|
| 248 |
+
self.kwargs = kwargs
|
| 249 |
+
|
| 250 |
+
def __enter__(self):
|
| 251 |
+
return self
|
| 252 |
+
|
| 253 |
+
@property
|
| 254 |
+
def size(self):
|
| 255 |
+
if self.stream.seekable():
|
| 256 |
+
return self.stream.size()
|
| 257 |
+
return None
|
| 258 |
+
|
| 259 |
+
def __exit__(self, *args):
|
| 260 |
+
return self.close()
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
class HadoopFileSystem(ArrowFSWrapper):
|
| 264 |
+
"""A wrapper on top of the pyarrow.fs.HadoopFileSystem
|
| 265 |
+
to connect it's interface with fsspec"""
|
| 266 |
+
|
| 267 |
+
protocol = "hdfs"
|
| 268 |
+
|
| 269 |
+
def __init__(
|
| 270 |
+
self,
|
| 271 |
+
host="default",
|
| 272 |
+
port=0,
|
| 273 |
+
user=None,
|
| 274 |
+
kerb_ticket=None,
|
| 275 |
+
replication=3,
|
| 276 |
+
extra_conf=None,
|
| 277 |
+
**kwargs,
|
| 278 |
+
):
|
| 279 |
+
"""
|
| 280 |
+
|
| 281 |
+
Parameters
|
| 282 |
+
----------
|
| 283 |
+
host: str
|
| 284 |
+
Hostname, IP or "default" to try to read from Hadoop config
|
| 285 |
+
port: int
|
| 286 |
+
Port to connect on, or default from Hadoop config if 0
|
| 287 |
+
user: str or None
|
| 288 |
+
If given, connect as this username
|
| 289 |
+
kerb_ticket: str or None
|
| 290 |
+
If given, use this ticket for authentication
|
| 291 |
+
replication: int
|
| 292 |
+
set replication factor of file for write operations. default value is 3.
|
| 293 |
+
extra_conf: None or dict
|
| 294 |
+
Passed on to HadoopFileSystem
|
| 295 |
+
"""
|
| 296 |
+
from pyarrow.fs import HadoopFileSystem
|
| 297 |
+
|
| 298 |
+
fs = HadoopFileSystem(
|
| 299 |
+
host=host,
|
| 300 |
+
port=port,
|
| 301 |
+
user=user,
|
| 302 |
+
kerb_ticket=kerb_ticket,
|
| 303 |
+
replication=replication,
|
| 304 |
+
extra_conf=extra_conf,
|
| 305 |
+
)
|
| 306 |
+
super().__init__(fs=fs, **kwargs)
|
| 307 |
+
|
| 308 |
+
@staticmethod
|
| 309 |
+
def _get_kwargs_from_urls(path):
|
| 310 |
+
ops = infer_storage_options(path)
|
| 311 |
+
out = {}
|
| 312 |
+
if ops.get("host", None):
|
| 313 |
+
out["host"] = ops["host"]
|
| 314 |
+
if ops.get("username", None):
|
| 315 |
+
out["user"] = ops["username"]
|
| 316 |
+
if ops.get("port", None):
|
| 317 |
+
out["port"] = ops["port"]
|
| 318 |
+
if ops.get("url_query", None):
|
| 319 |
+
queries = parse_qs(ops["url_query"])
|
| 320 |
+
if queries.get("replication", None):
|
| 321 |
+
out["replication"] = int(queries["replication"][0])
|
| 322 |
+
return out
|
.venv/lib/python3.12/site-packages/fsspec/implementations/asyn_wrapper.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import functools
|
| 3 |
+
import inspect
|
| 4 |
+
|
| 5 |
+
import fsspec
|
| 6 |
+
from fsspec.asyn import AsyncFileSystem, running_async
|
| 7 |
+
|
| 8 |
+
from .chained import ChainedFileSystem
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def async_wrapper(func, obj=None, semaphore=None):
|
| 12 |
+
"""
|
| 13 |
+
Wraps a synchronous function to make it awaitable.
|
| 14 |
+
|
| 15 |
+
Parameters
|
| 16 |
+
----------
|
| 17 |
+
func : callable
|
| 18 |
+
The synchronous function to wrap.
|
| 19 |
+
obj : object, optional
|
| 20 |
+
The instance to bind the function to, if applicable.
|
| 21 |
+
semaphore : asyncio.Semaphore, optional
|
| 22 |
+
A semaphore to limit concurrent calls.
|
| 23 |
+
|
| 24 |
+
Returns
|
| 25 |
+
-------
|
| 26 |
+
coroutine
|
| 27 |
+
An awaitable version of the function.
|
| 28 |
+
"""
|
| 29 |
+
|
| 30 |
+
@functools.wraps(func)
|
| 31 |
+
async def wrapper(*args, **kwargs):
|
| 32 |
+
if semaphore:
|
| 33 |
+
async with semaphore:
|
| 34 |
+
return await asyncio.to_thread(func, *args, **kwargs)
|
| 35 |
+
return await asyncio.to_thread(func, *args, **kwargs)
|
| 36 |
+
|
| 37 |
+
return wrapper
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class AsyncFileSystemWrapper(AsyncFileSystem, ChainedFileSystem):
|
| 41 |
+
"""
|
| 42 |
+
A wrapper class to convert a synchronous filesystem into an asynchronous one.
|
| 43 |
+
|
| 44 |
+
This class takes an existing synchronous filesystem implementation and wraps all
|
| 45 |
+
its methods to provide an asynchronous interface.
|
| 46 |
+
|
| 47 |
+
Parameters
|
| 48 |
+
----------
|
| 49 |
+
sync_fs : AbstractFileSystem
|
| 50 |
+
The synchronous filesystem instance to wrap.
|
| 51 |
+
"""
|
| 52 |
+
|
| 53 |
+
protocol = "asyncwrapper", "async_wrapper"
|
| 54 |
+
cachable = False
|
| 55 |
+
|
| 56 |
+
def __init__(
|
| 57 |
+
self,
|
| 58 |
+
fs=None,
|
| 59 |
+
asynchronous=None,
|
| 60 |
+
target_protocol=None,
|
| 61 |
+
target_options=None,
|
| 62 |
+
semaphore=None,
|
| 63 |
+
max_concurrent_tasks=None,
|
| 64 |
+
**kwargs,
|
| 65 |
+
):
|
| 66 |
+
if asynchronous is None:
|
| 67 |
+
asynchronous = running_async()
|
| 68 |
+
super().__init__(asynchronous=asynchronous, **kwargs)
|
| 69 |
+
if fs is not None:
|
| 70 |
+
self.sync_fs = fs
|
| 71 |
+
else:
|
| 72 |
+
self.sync_fs = fsspec.filesystem(target_protocol, **target_options)
|
| 73 |
+
self.protocol = self.sync_fs.protocol
|
| 74 |
+
self.semaphore = semaphore
|
| 75 |
+
self._wrap_all_sync_methods()
|
| 76 |
+
|
| 77 |
+
@property
|
| 78 |
+
def fsid(self):
|
| 79 |
+
return f"async_{self.sync_fs.fsid}"
|
| 80 |
+
|
| 81 |
+
def _wrap_all_sync_methods(self):
|
| 82 |
+
"""
|
| 83 |
+
Wrap all synchronous methods of the underlying filesystem with asynchronous versions.
|
| 84 |
+
"""
|
| 85 |
+
excluded_methods = {"open"}
|
| 86 |
+
for method_name in dir(self.sync_fs):
|
| 87 |
+
if method_name.startswith("_") or method_name in excluded_methods:
|
| 88 |
+
continue
|
| 89 |
+
|
| 90 |
+
attr = inspect.getattr_static(self.sync_fs, method_name)
|
| 91 |
+
if isinstance(attr, property):
|
| 92 |
+
continue
|
| 93 |
+
|
| 94 |
+
method = getattr(self.sync_fs, method_name)
|
| 95 |
+
if callable(method) and not inspect.iscoroutinefunction(method):
|
| 96 |
+
async_method = async_wrapper(method, obj=self, semaphore=self.semaphore)
|
| 97 |
+
setattr(self, f"_{method_name}", async_method)
|
| 98 |
+
|
| 99 |
+
@classmethod
|
| 100 |
+
def wrap_class(cls, sync_fs_class):
|
| 101 |
+
"""
|
| 102 |
+
Create a new class that can be used to instantiate an AsyncFileSystemWrapper
|
| 103 |
+
with lazy instantiation of the underlying synchronous filesystem.
|
| 104 |
+
|
| 105 |
+
Parameters
|
| 106 |
+
----------
|
| 107 |
+
sync_fs_class : type
|
| 108 |
+
The class of the synchronous filesystem to wrap.
|
| 109 |
+
|
| 110 |
+
Returns
|
| 111 |
+
-------
|
| 112 |
+
type
|
| 113 |
+
A new class that wraps the provided synchronous filesystem class.
|
| 114 |
+
"""
|
| 115 |
+
|
| 116 |
+
class GeneratedAsyncFileSystemWrapper(cls):
|
| 117 |
+
def __init__(self, *args, **kwargs):
|
| 118 |
+
sync_fs = sync_fs_class(*args, **kwargs)
|
| 119 |
+
super().__init__(sync_fs)
|
| 120 |
+
|
| 121 |
+
GeneratedAsyncFileSystemWrapper.__name__ = (
|
| 122 |
+
f"Async{sync_fs_class.__name__}Wrapper"
|
| 123 |
+
)
|
| 124 |
+
return GeneratedAsyncFileSystemWrapper
|
.venv/lib/python3.12/site-packages/fsspec/implementations/cache_mapper.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import abc
|
| 4 |
+
import hashlib
|
| 5 |
+
|
| 6 |
+
from fsspec.implementations.local import make_path_posix
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class AbstractCacheMapper(abc.ABC):
|
| 10 |
+
"""Abstract super-class for mappers from remote URLs to local cached
|
| 11 |
+
basenames.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
@abc.abstractmethod
|
| 15 |
+
def __call__(self, path: str) -> str: ...
|
| 16 |
+
|
| 17 |
+
def __eq__(self, other: object) -> bool:
|
| 18 |
+
# Identity only depends on class. When derived classes have attributes
|
| 19 |
+
# they will need to be included.
|
| 20 |
+
return isinstance(other, type(self))
|
| 21 |
+
|
| 22 |
+
def __hash__(self) -> int:
|
| 23 |
+
# Identity only depends on class. When derived classes have attributes
|
| 24 |
+
# they will need to be included.
|
| 25 |
+
return hash(type(self))
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class BasenameCacheMapper(AbstractCacheMapper):
|
| 29 |
+
"""Cache mapper that uses the basename of the remote URL and a fixed number
|
| 30 |
+
of directory levels above this.
|
| 31 |
+
|
| 32 |
+
The default is zero directory levels, meaning different paths with the same
|
| 33 |
+
basename will have the same cached basename.
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
def __init__(self, directory_levels: int = 0):
|
| 37 |
+
if directory_levels < 0:
|
| 38 |
+
raise ValueError(
|
| 39 |
+
"BasenameCacheMapper requires zero or positive directory_levels"
|
| 40 |
+
)
|
| 41 |
+
self.directory_levels = directory_levels
|
| 42 |
+
|
| 43 |
+
# Separator for directories when encoded as strings.
|
| 44 |
+
self._separator = "_@_"
|
| 45 |
+
|
| 46 |
+
def __call__(self, path: str) -> str:
|
| 47 |
+
path = make_path_posix(path)
|
| 48 |
+
prefix, *bits = path.rsplit("/", self.directory_levels + 1)
|
| 49 |
+
if bits:
|
| 50 |
+
return self._separator.join(bits)
|
| 51 |
+
else:
|
| 52 |
+
return prefix # No separator found, simple filename
|
| 53 |
+
|
| 54 |
+
def __eq__(self, other: object) -> bool:
|
| 55 |
+
return super().__eq__(other) and self.directory_levels == other.directory_levels
|
| 56 |
+
|
| 57 |
+
def __hash__(self) -> int:
|
| 58 |
+
return super().__hash__() ^ hash(self.directory_levels)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
class HashCacheMapper(AbstractCacheMapper):
|
| 62 |
+
"""Cache mapper that uses a hash of the remote URL."""
|
| 63 |
+
|
| 64 |
+
def __call__(self, path: str) -> str:
|
| 65 |
+
return hashlib.sha256(path.encode()).hexdigest()
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def create_cache_mapper(same_names: bool) -> AbstractCacheMapper:
|
| 69 |
+
"""Factory method to create cache mapper for backward compatibility with
|
| 70 |
+
``CachingFileSystem`` constructor using ``same_names`` kwarg.
|
| 71 |
+
"""
|
| 72 |
+
if same_names:
|
| 73 |
+
return BasenameCacheMapper()
|
| 74 |
+
else:
|
| 75 |
+
return HashCacheMapper()
|
.venv/lib/python3.12/site-packages/fsspec/implementations/cache_metadata.py
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
| 7 |
+
from fsspec.utils import atomic_write
|
| 8 |
+
|
| 9 |
+
try:
|
| 10 |
+
import ujson as json
|
| 11 |
+
except ImportError:
|
| 12 |
+
if not TYPE_CHECKING:
|
| 13 |
+
import json
|
| 14 |
+
|
| 15 |
+
if TYPE_CHECKING:
|
| 16 |
+
from collections.abc import Iterator
|
| 17 |
+
from typing import Any, Literal, TypeAlias
|
| 18 |
+
|
| 19 |
+
from .cached import CachingFileSystem
|
| 20 |
+
|
| 21 |
+
Detail: TypeAlias = dict[str, Any]
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class CacheMetadata:
|
| 25 |
+
"""Cache metadata.
|
| 26 |
+
|
| 27 |
+
All reading and writing of cache metadata is performed by this class,
|
| 28 |
+
accessing the cached files and blocks is not.
|
| 29 |
+
|
| 30 |
+
Metadata is stored in a single file per storage directory in JSON format.
|
| 31 |
+
For backward compatibility. No longer supports pickle.
|
| 32 |
+
"""
|
| 33 |
+
|
| 34 |
+
def __init__(self, storage: list[str]):
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
Parameters
|
| 38 |
+
----------
|
| 39 |
+
storage: list[str]
|
| 40 |
+
Directories containing cached files, must be at least one. Metadata
|
| 41 |
+
is stored in the last of these directories by convention.
|
| 42 |
+
"""
|
| 43 |
+
if not storage:
|
| 44 |
+
raise ValueError("CacheMetadata expects at least one storage location")
|
| 45 |
+
|
| 46 |
+
self._storage = storage
|
| 47 |
+
self.cached_files: list[Detail] = [{}]
|
| 48 |
+
|
| 49 |
+
def _load(self, fn: str) -> Detail:
|
| 50 |
+
"""Low-level function to load metadata from specific file"""
|
| 51 |
+
with open(fn, "r") as f:
|
| 52 |
+
loaded = json.load(f)
|
| 53 |
+
for c in loaded.values():
|
| 54 |
+
if isinstance(c.get("blocks"), list):
|
| 55 |
+
c["blocks"] = set(c["blocks"])
|
| 56 |
+
return loaded
|
| 57 |
+
|
| 58 |
+
def _save(self, metadata_to_save: Detail, fn: str) -> None:
|
| 59 |
+
"""Low-level function to save metadata to specific file"""
|
| 60 |
+
with atomic_write(fn, mode="w") as f:
|
| 61 |
+
json.dump(metadata_to_save, f)
|
| 62 |
+
|
| 63 |
+
def _scan_locations(
|
| 64 |
+
self, writable_only: bool = False
|
| 65 |
+
) -> Iterator[tuple[str, str, bool]]:
|
| 66 |
+
"""Yield locations (filenames) where metadata is stored, and whether
|
| 67 |
+
writable or not.
|
| 68 |
+
|
| 69 |
+
Parameters
|
| 70 |
+
----------
|
| 71 |
+
writable: bool
|
| 72 |
+
Set to True to only yield writable locations.
|
| 73 |
+
|
| 74 |
+
Returns
|
| 75 |
+
-------
|
| 76 |
+
Yields (str, str, bool)
|
| 77 |
+
"""
|
| 78 |
+
n = len(self._storage)
|
| 79 |
+
for i, storage in enumerate(self._storage):
|
| 80 |
+
writable = i == n - 1
|
| 81 |
+
if writable_only and not writable:
|
| 82 |
+
continue
|
| 83 |
+
yield os.path.join(storage, "cache"), storage, writable
|
| 84 |
+
|
| 85 |
+
def check_file(
|
| 86 |
+
self, path: str, cfs: CachingFileSystem | None
|
| 87 |
+
) -> Literal[False] | tuple[Detail, str]:
|
| 88 |
+
"""If path is in cache return its details, otherwise return ``False``.
|
| 89 |
+
|
| 90 |
+
If the optional CachingFileSystem is specified then it is used to
|
| 91 |
+
perform extra checks to reject possible matches, such as if they are
|
| 92 |
+
too old.
|
| 93 |
+
"""
|
| 94 |
+
for (fn, base, _), cache in zip(self._scan_locations(), self.cached_files):
|
| 95 |
+
if path not in cache:
|
| 96 |
+
continue
|
| 97 |
+
detail = cache[path].copy()
|
| 98 |
+
|
| 99 |
+
if cfs is not None:
|
| 100 |
+
if cfs.check_files and detail["uid"] != cfs.fs.ukey(path):
|
| 101 |
+
# Wrong file as determined by hash of file properties
|
| 102 |
+
continue
|
| 103 |
+
if cfs.expiry and time.time() - detail["time"] > cfs.expiry:
|
| 104 |
+
# Cached file has expired
|
| 105 |
+
continue
|
| 106 |
+
|
| 107 |
+
fn = os.path.join(base, detail["fn"])
|
| 108 |
+
if os.path.exists(fn):
|
| 109 |
+
return detail, fn
|
| 110 |
+
return False
|
| 111 |
+
|
| 112 |
+
def clear_expired(self, expiry_time: int) -> tuple[list[str], bool]:
|
| 113 |
+
"""Remove expired metadata from the cache.
|
| 114 |
+
|
| 115 |
+
Returns names of files corresponding to expired metadata and a boolean
|
| 116 |
+
flag indicating whether the writable cache is empty. Caller is
|
| 117 |
+
responsible for deleting the expired files.
|
| 118 |
+
"""
|
| 119 |
+
expired_files = []
|
| 120 |
+
for path, detail in self.cached_files[-1].copy().items():
|
| 121 |
+
if time.time() - detail["time"] > expiry_time:
|
| 122 |
+
fn = detail.get("fn", "")
|
| 123 |
+
if not fn:
|
| 124 |
+
raise RuntimeError(
|
| 125 |
+
f"Cache metadata does not contain 'fn' for {path}"
|
| 126 |
+
)
|
| 127 |
+
fn = os.path.join(self._storage[-1], fn)
|
| 128 |
+
expired_files.append(fn)
|
| 129 |
+
self.cached_files[-1].pop(path)
|
| 130 |
+
|
| 131 |
+
if self.cached_files[-1]:
|
| 132 |
+
cache_path = os.path.join(self._storage[-1], "cache")
|
| 133 |
+
self._save(self.cached_files[-1], cache_path)
|
| 134 |
+
|
| 135 |
+
writable_cache_empty = not self.cached_files[-1]
|
| 136 |
+
return expired_files, writable_cache_empty
|
| 137 |
+
|
| 138 |
+
def load(self) -> None:
|
| 139 |
+
"""Load all metadata from disk and store in ``self.cached_files``"""
|
| 140 |
+
cached_files = []
|
| 141 |
+
for fn, _, _ in self._scan_locations():
|
| 142 |
+
if os.path.exists(fn):
|
| 143 |
+
# TODO: consolidate blocks here
|
| 144 |
+
cached_files.append(self._load(fn))
|
| 145 |
+
else:
|
| 146 |
+
cached_files.append({})
|
| 147 |
+
self.cached_files = cached_files or [{}]
|
| 148 |
+
|
| 149 |
+
def on_close_cached_file(self, f: Any, path: str) -> None:
|
| 150 |
+
"""Perform side-effect actions on closing a cached file.
|
| 151 |
+
|
| 152 |
+
The actual closing of the file is the responsibility of the caller.
|
| 153 |
+
"""
|
| 154 |
+
# File must be writable, so in self.cached_files[-1]
|
| 155 |
+
c = self.cached_files[-1][path]
|
| 156 |
+
if c["blocks"] is not True and len(c["blocks"]) * f.blocksize >= f.size:
|
| 157 |
+
c["blocks"] = True
|
| 158 |
+
|
| 159 |
+
def pop_file(self, path: str) -> str | None:
|
| 160 |
+
"""Remove metadata of cached file.
|
| 161 |
+
|
| 162 |
+
If path is in the cache, return the filename of the cached file,
|
| 163 |
+
otherwise return ``None``. Caller is responsible for deleting the
|
| 164 |
+
cached file.
|
| 165 |
+
"""
|
| 166 |
+
details = self.check_file(path, None)
|
| 167 |
+
if not details:
|
| 168 |
+
return None
|
| 169 |
+
_, fn = details
|
| 170 |
+
if fn.startswith(self._storage[-1]):
|
| 171 |
+
self.cached_files[-1].pop(path)
|
| 172 |
+
self.save()
|
| 173 |
+
else:
|
| 174 |
+
raise PermissionError(
|
| 175 |
+
"Can only delete cached file in last, writable cache location"
|
| 176 |
+
)
|
| 177 |
+
return fn
|
| 178 |
+
|
| 179 |
+
def save(self) -> None:
|
| 180 |
+
"""Save metadata to disk"""
|
| 181 |
+
for (fn, _, writable), cache in zip(self._scan_locations(), self.cached_files):
|
| 182 |
+
if not writable:
|
| 183 |
+
continue
|
| 184 |
+
|
| 185 |
+
if os.path.exists(fn):
|
| 186 |
+
cached_files = self._load(fn)
|
| 187 |
+
for k, c in cached_files.items():
|
| 188 |
+
if k in cache:
|
| 189 |
+
if c["blocks"] is True or cache[k]["blocks"] is True:
|
| 190 |
+
c["blocks"] = True
|
| 191 |
+
else:
|
| 192 |
+
# self.cached_files[*][*]["blocks"] must continue to
|
| 193 |
+
# point to the same set object so that updates
|
| 194 |
+
# performed by MMapCache are propagated back to
|
| 195 |
+
# self.cached_files.
|
| 196 |
+
blocks = cache[k]["blocks"]
|
| 197 |
+
blocks.update(c["blocks"])
|
| 198 |
+
c["blocks"] = blocks
|
| 199 |
+
c["time"] = max(c["time"], cache[k]["time"])
|
| 200 |
+
c["uid"] = cache[k]["uid"]
|
| 201 |
+
|
| 202 |
+
# Files can be added to cache after it was written once
|
| 203 |
+
for k, c in cache.items():
|
| 204 |
+
if k not in cached_files:
|
| 205 |
+
cached_files[k] = c
|
| 206 |
+
else:
|
| 207 |
+
cached_files = cache
|
| 208 |
+
cache = {k: v.copy() for k, v in cached_files.items()}
|
| 209 |
+
for c in cache.values():
|
| 210 |
+
if isinstance(c["blocks"], set):
|
| 211 |
+
c["blocks"] = list(c["blocks"])
|
| 212 |
+
self._save(cache, fn)
|
| 213 |
+
self.cached_files[-1] = cached_files
|
| 214 |
+
|
| 215 |
+
def update_file(self, path: str, detail: Detail) -> None:
|
| 216 |
+
"""Update metadata for specific file in memory, do not save"""
|
| 217 |
+
self.cached_files[-1][path] = detail
|
.venv/lib/python3.12/site-packages/fsspec/implementations/cached.py
ADDED
|
@@ -0,0 +1,1040 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import inspect
|
| 4 |
+
import logging
|
| 5 |
+
import os
|
| 6 |
+
import tempfile
|
| 7 |
+
import time
|
| 8 |
+
import weakref
|
| 9 |
+
from collections.abc import Callable
|
| 10 |
+
from shutil import rmtree
|
| 11 |
+
from typing import TYPE_CHECKING, Any, ClassVar
|
| 12 |
+
|
| 13 |
+
from fsspec import filesystem
|
| 14 |
+
from fsspec.callbacks import DEFAULT_CALLBACK
|
| 15 |
+
from fsspec.compression import compr
|
| 16 |
+
from fsspec.core import BaseCache, MMapCache
|
| 17 |
+
from fsspec.exceptions import BlocksizeMismatchError
|
| 18 |
+
from fsspec.implementations.cache_mapper import create_cache_mapper
|
| 19 |
+
from fsspec.implementations.cache_metadata import CacheMetadata
|
| 20 |
+
from fsspec.implementations.chained import ChainedFileSystem
|
| 21 |
+
from fsspec.implementations.local import LocalFileSystem
|
| 22 |
+
from fsspec.spec import AbstractBufferedFile
|
| 23 |
+
from fsspec.transaction import Transaction
|
| 24 |
+
from fsspec.utils import infer_compression
|
| 25 |
+
|
| 26 |
+
if TYPE_CHECKING:
|
| 27 |
+
from fsspec.implementations.cache_mapper import AbstractCacheMapper
|
| 28 |
+
|
| 29 |
+
logger = logging.getLogger("fsspec.cached")
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class WriteCachedTransaction(Transaction):
|
| 33 |
+
def complete(self, commit=True):
|
| 34 |
+
rpaths = [f.path for f in self.files]
|
| 35 |
+
lpaths = [f.fn for f in self.files]
|
| 36 |
+
if commit:
|
| 37 |
+
self.fs.put(lpaths, rpaths)
|
| 38 |
+
self.files.clear()
|
| 39 |
+
self.fs._intrans = False
|
| 40 |
+
self.fs._transaction = None
|
| 41 |
+
self.fs = None # break cycle
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class CachingFileSystem(ChainedFileSystem):
|
| 45 |
+
"""Locally caching filesystem, layer over any other FS
|
| 46 |
+
|
| 47 |
+
This class implements chunk-wise local storage of remote files, for quick
|
| 48 |
+
access after the initial download. The files are stored in a given
|
| 49 |
+
directory with hashes of URLs for the filenames. If no directory is given,
|
| 50 |
+
a temporary one is used, which should be cleaned up by the OS after the
|
| 51 |
+
process ends. The files themselves are sparse (as implemented in
|
| 52 |
+
:class:`~fsspec.caching.MMapCache`), so only the data which is accessed
|
| 53 |
+
takes up space.
|
| 54 |
+
|
| 55 |
+
Restrictions:
|
| 56 |
+
|
| 57 |
+
- the block-size must be the same for each access of a given file, unless
|
| 58 |
+
all blocks of the file have already been read
|
| 59 |
+
- caching can only be applied to file-systems which produce files
|
| 60 |
+
derived from fsspec.spec.AbstractBufferedFile ; LocalFileSystem is also
|
| 61 |
+
allowed, for testing
|
| 62 |
+
"""
|
| 63 |
+
|
| 64 |
+
protocol: ClassVar[str | tuple[str, ...]] = ("blockcache", "cached")
|
| 65 |
+
_strip_tokenize_options = ("fo",)
|
| 66 |
+
|
| 67 |
+
def __init__(
|
| 68 |
+
self,
|
| 69 |
+
target_protocol=None,
|
| 70 |
+
cache_storage="TMP",
|
| 71 |
+
cache_check=10,
|
| 72 |
+
check_files=False,
|
| 73 |
+
expiry_time=604800,
|
| 74 |
+
target_options=None,
|
| 75 |
+
fs=None,
|
| 76 |
+
same_names: bool | None = None,
|
| 77 |
+
compression=None,
|
| 78 |
+
cache_mapper: AbstractCacheMapper | None = None,
|
| 79 |
+
cache_storage_mode=None,
|
| 80 |
+
**kwargs,
|
| 81 |
+
):
|
| 82 |
+
"""
|
| 83 |
+
|
| 84 |
+
Parameters
|
| 85 |
+
----------
|
| 86 |
+
target_protocol: str (optional)
|
| 87 |
+
Target filesystem protocol. Provide either this or ``fs``.
|
| 88 |
+
cache_storage: str or list(str)
|
| 89 |
+
Location to store files. If "TMP", this is a temporary directory,
|
| 90 |
+
and will be cleaned up by the OS when this process ends (or later).
|
| 91 |
+
If a list, each location will be tried in the order given, but
|
| 92 |
+
only the last will be considered writable.
|
| 93 |
+
cache_check: int
|
| 94 |
+
Number of seconds between reload of cache metadata
|
| 95 |
+
check_files: bool
|
| 96 |
+
Whether to explicitly see if the UID of the remote file matches
|
| 97 |
+
the stored one before using. Warning: some file systems such as
|
| 98 |
+
HTTP cannot reliably give a unique hash of the contents of some
|
| 99 |
+
path, so be sure to set this option to False.
|
| 100 |
+
expiry_time: int
|
| 101 |
+
The time in seconds after which a local copy is considered useless.
|
| 102 |
+
Set to falsy to prevent expiry. The default is equivalent to one
|
| 103 |
+
week.
|
| 104 |
+
target_options: dict or None
|
| 105 |
+
Passed to the instantiation of the FS, if fs is None.
|
| 106 |
+
fs: filesystem instance
|
| 107 |
+
The target filesystem to run against. Provide this or ``protocol``.
|
| 108 |
+
same_names: bool (optional)
|
| 109 |
+
By default, target URLs are hashed using a ``HashCacheMapper`` so
|
| 110 |
+
that files from different backends with the same basename do not
|
| 111 |
+
conflict. If this argument is ``true``, a ``BasenameCacheMapper``
|
| 112 |
+
is used instead. Other cache mapper options are available by using
|
| 113 |
+
the ``cache_mapper`` keyword argument. Only one of this and
|
| 114 |
+
``cache_mapper`` should be specified.
|
| 115 |
+
compression: str (optional)
|
| 116 |
+
To decompress on download. Can be 'infer' (guess from the URL name),
|
| 117 |
+
one of the entries in ``fsspec.compression.compr``, or None for no
|
| 118 |
+
decompression.
|
| 119 |
+
cache_mapper: AbstractCacheMapper (optional)
|
| 120 |
+
The object use to map from original filenames to cached filenames.
|
| 121 |
+
Only one of this and ``same_names`` should be specified.
|
| 122 |
+
cache_storage_mode: int (optional)
|
| 123 |
+
Permission mode used when creating the cache storage directory,
|
| 124 |
+
e.g. ``0o700``. The default of ``None`` leaves the directory at
|
| 125 |
+
the system default (governed by the umask), which is the existing
|
| 126 |
+
behaviour. Pass an octal mode such as ``0o700`` to keep the cache
|
| 127 |
+
directory, and so the cached data files within it, readable by the
|
| 128 |
+
owner only.
|
| 129 |
+
"""
|
| 130 |
+
super().__init__(**kwargs)
|
| 131 |
+
if fs is None and target_protocol is None:
|
| 132 |
+
raise ValueError(
|
| 133 |
+
"Please provide filesystem instance(fs) or target_protocol"
|
| 134 |
+
)
|
| 135 |
+
if not (fs is None) ^ (target_protocol is None):
|
| 136 |
+
raise ValueError(
|
| 137 |
+
"Both filesystems (fs) and target_protocol may not be both given."
|
| 138 |
+
)
|
| 139 |
+
if cache_storage == "TMP":
|
| 140 |
+
tempdir = tempfile.mkdtemp()
|
| 141 |
+
storage = [tempdir]
|
| 142 |
+
weakref.finalize(self, self._remove_tempdir, tempdir)
|
| 143 |
+
else:
|
| 144 |
+
if isinstance(cache_storage, str):
|
| 145 |
+
storage = [cache_storage]
|
| 146 |
+
else:
|
| 147 |
+
storage = cache_storage
|
| 148 |
+
self.cache_storage_mode = cache_storage_mode
|
| 149 |
+
self._makedirs(storage[-1])
|
| 150 |
+
self.storage = storage
|
| 151 |
+
self.kwargs = target_options or {}
|
| 152 |
+
self.cache_check = cache_check
|
| 153 |
+
self.check_files = check_files
|
| 154 |
+
self.expiry = expiry_time
|
| 155 |
+
self.compression = compression
|
| 156 |
+
|
| 157 |
+
# Size of cache in bytes. If None then the size is unknown and will be
|
| 158 |
+
# recalculated the next time cache_size() is called. On writes to the
|
| 159 |
+
# cache this is reset to None.
|
| 160 |
+
self._cache_size = None
|
| 161 |
+
|
| 162 |
+
if same_names is not None and cache_mapper is not None:
|
| 163 |
+
raise ValueError(
|
| 164 |
+
"Cannot specify both same_names and cache_mapper in "
|
| 165 |
+
"CachingFileSystem.__init__"
|
| 166 |
+
)
|
| 167 |
+
if cache_mapper is not None:
|
| 168 |
+
self._mapper = cache_mapper
|
| 169 |
+
else:
|
| 170 |
+
self._mapper = create_cache_mapper(
|
| 171 |
+
same_names if same_names is not None else False
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
self.target_protocol = (
|
| 175 |
+
target_protocol
|
| 176 |
+
if isinstance(target_protocol, str)
|
| 177 |
+
else (fs.protocol if isinstance(fs.protocol, str) else fs.protocol[0])
|
| 178 |
+
)
|
| 179 |
+
self._metadata = CacheMetadata(self.storage)
|
| 180 |
+
self.load_cache()
|
| 181 |
+
self.fs = fs if fs is not None else filesystem(target_protocol, **self.kwargs)
|
| 182 |
+
|
| 183 |
+
def _strip_protocol(path):
|
| 184 |
+
# acts as a method, since each instance has a difference target
|
| 185 |
+
return self.fs._strip_protocol(type(self)._strip_protocol(path))
|
| 186 |
+
|
| 187 |
+
self._strip_protocol: Callable = _strip_protocol
|
| 188 |
+
|
| 189 |
+
@staticmethod
|
| 190 |
+
def _remove_tempdir(tempdir):
|
| 191 |
+
try:
|
| 192 |
+
rmtree(tempdir)
|
| 193 |
+
except Exception:
|
| 194 |
+
pass
|
| 195 |
+
|
| 196 |
+
def _makedirs(self, path):
|
| 197 |
+
if self.cache_storage_mode is None:
|
| 198 |
+
os.makedirs(path, exist_ok=True)
|
| 199 |
+
else:
|
| 200 |
+
os.makedirs(path, exist_ok=True, mode=self.cache_storage_mode)
|
| 201 |
+
|
| 202 |
+
def _mkcache(self):
|
| 203 |
+
self._makedirs(self.storage[-1])
|
| 204 |
+
|
| 205 |
+
def cache_size(self):
|
| 206 |
+
"""Return size of cache in bytes.
|
| 207 |
+
|
| 208 |
+
If more than one cache directory is in use, only the size of the last
|
| 209 |
+
one (the writable cache directory) is returned.
|
| 210 |
+
"""
|
| 211 |
+
if self._cache_size is None:
|
| 212 |
+
cache_dir = self.storage[-1]
|
| 213 |
+
self._cache_size = filesystem("file").du(cache_dir, withdirs=True)
|
| 214 |
+
return self._cache_size
|
| 215 |
+
|
| 216 |
+
def load_cache(self):
|
| 217 |
+
"""Read set of stored blocks from file"""
|
| 218 |
+
self._metadata.load()
|
| 219 |
+
self._mkcache()
|
| 220 |
+
self.last_cache = time.time()
|
| 221 |
+
|
| 222 |
+
def save_cache(self):
|
| 223 |
+
"""Save set of stored blocks from file"""
|
| 224 |
+
self._mkcache()
|
| 225 |
+
self._metadata.save()
|
| 226 |
+
self.last_cache = time.time()
|
| 227 |
+
self._cache_size = None
|
| 228 |
+
|
| 229 |
+
def _check_cache(self):
|
| 230 |
+
"""Reload caches if time elapsed or any disappeared"""
|
| 231 |
+
self._mkcache()
|
| 232 |
+
if not self.cache_check:
|
| 233 |
+
# explicitly told not to bother checking
|
| 234 |
+
return
|
| 235 |
+
timecond = time.time() - self.last_cache > self.cache_check
|
| 236 |
+
existcond = all(os.path.exists(storage) for storage in self.storage)
|
| 237 |
+
if timecond or not existcond:
|
| 238 |
+
self.load_cache()
|
| 239 |
+
|
| 240 |
+
def _check_file(self, path):
|
| 241 |
+
"""Is path in cache and still valid"""
|
| 242 |
+
path = self._strip_protocol(path)
|
| 243 |
+
self._check_cache()
|
| 244 |
+
return self._metadata.check_file(path, self)
|
| 245 |
+
|
| 246 |
+
def clear_cache(self):
|
| 247 |
+
"""Remove all files and metadata from the cache
|
| 248 |
+
|
| 249 |
+
In the case of multiple cache locations, this clears only the last one,
|
| 250 |
+
which is assumed to be the read/write one.
|
| 251 |
+
"""
|
| 252 |
+
rmtree(self.storage[-1])
|
| 253 |
+
self.load_cache()
|
| 254 |
+
self._cache_size = None
|
| 255 |
+
|
| 256 |
+
def clear_expired_cache(self, expiry_time=None):
|
| 257 |
+
"""Remove all expired files and metadata from the cache
|
| 258 |
+
|
| 259 |
+
In the case of multiple cache locations, this clears only the last one,
|
| 260 |
+
which is assumed to be the read/write one.
|
| 261 |
+
|
| 262 |
+
Parameters
|
| 263 |
+
----------
|
| 264 |
+
expiry_time: int
|
| 265 |
+
The time in seconds after which a local copy is considered useless.
|
| 266 |
+
If not defined the default is equivalent to the attribute from the
|
| 267 |
+
file caching instantiation.
|
| 268 |
+
"""
|
| 269 |
+
|
| 270 |
+
if not expiry_time:
|
| 271 |
+
expiry_time = self.expiry
|
| 272 |
+
|
| 273 |
+
self._check_cache()
|
| 274 |
+
|
| 275 |
+
expired_files, writable_cache_empty = self._metadata.clear_expired(expiry_time)
|
| 276 |
+
for fn in expired_files:
|
| 277 |
+
if os.path.exists(fn):
|
| 278 |
+
os.remove(fn)
|
| 279 |
+
|
| 280 |
+
if writable_cache_empty:
|
| 281 |
+
rmtree(self.storage[-1])
|
| 282 |
+
self.load_cache()
|
| 283 |
+
|
| 284 |
+
self._cache_size = None
|
| 285 |
+
|
| 286 |
+
def pop_from_cache(self, path):
|
| 287 |
+
"""Remove cached version of given file
|
| 288 |
+
|
| 289 |
+
Deletes local copy of the given (remote) path. If it is found in a cache
|
| 290 |
+
location which is not the last, it is assumed to be read-only, and
|
| 291 |
+
raises PermissionError
|
| 292 |
+
"""
|
| 293 |
+
path = self._strip_protocol(path)
|
| 294 |
+
fn = self._metadata.pop_file(path)
|
| 295 |
+
if fn is not None:
|
| 296 |
+
os.remove(fn)
|
| 297 |
+
self._cache_size = None
|
| 298 |
+
|
| 299 |
+
def _open(
|
| 300 |
+
self,
|
| 301 |
+
path,
|
| 302 |
+
mode="rb",
|
| 303 |
+
block_size=None,
|
| 304 |
+
autocommit=True,
|
| 305 |
+
cache_options=None,
|
| 306 |
+
**kwargs,
|
| 307 |
+
):
|
| 308 |
+
"""Wrap the target _open
|
| 309 |
+
|
| 310 |
+
If the whole file exists in the cache, just open it locally and
|
| 311 |
+
return that.
|
| 312 |
+
|
| 313 |
+
Otherwise, open the file on the target FS, and make it have a mmap
|
| 314 |
+
cache pointing to the location which we determine, in our cache.
|
| 315 |
+
The ``blocks`` instance is shared, so as the mmap cache instance
|
| 316 |
+
updates, so does the entry in our ``cached_files`` attribute.
|
| 317 |
+
We monkey-patch this file, so that when it closes, we call
|
| 318 |
+
``close_and_update`` to save the state of the blocks.
|
| 319 |
+
"""
|
| 320 |
+
path = self._strip_protocol(path)
|
| 321 |
+
|
| 322 |
+
path = self.fs._strip_protocol(path)
|
| 323 |
+
if "r" not in mode:
|
| 324 |
+
return self.fs._open(
|
| 325 |
+
path,
|
| 326 |
+
mode=mode,
|
| 327 |
+
block_size=block_size,
|
| 328 |
+
autocommit=autocommit,
|
| 329 |
+
cache_options=cache_options,
|
| 330 |
+
**kwargs,
|
| 331 |
+
)
|
| 332 |
+
detail = self._check_file(path)
|
| 333 |
+
if detail:
|
| 334 |
+
# file is in cache
|
| 335 |
+
detail, fn = detail
|
| 336 |
+
hash, blocks = detail["fn"], detail["blocks"]
|
| 337 |
+
if blocks is True:
|
| 338 |
+
# stored file is complete
|
| 339 |
+
logger.debug("Opening local copy of %s", path)
|
| 340 |
+
return open(fn, mode)
|
| 341 |
+
# TODO: action where partial file exists in read-only cache
|
| 342 |
+
logger.debug("Opening partially cached copy of %s", path)
|
| 343 |
+
else:
|
| 344 |
+
hash = self._mapper(path)
|
| 345 |
+
fn = os.path.join(self.storage[-1], hash)
|
| 346 |
+
blocks = set()
|
| 347 |
+
detail = {
|
| 348 |
+
"original": path,
|
| 349 |
+
"fn": hash,
|
| 350 |
+
"blocks": blocks,
|
| 351 |
+
"time": time.time(),
|
| 352 |
+
"uid": self.fs.ukey(path),
|
| 353 |
+
}
|
| 354 |
+
self._metadata.update_file(path, detail)
|
| 355 |
+
logger.debug("Creating local sparse file for %s", path)
|
| 356 |
+
|
| 357 |
+
# explicitly submitting the size to the open call will avoid extra
|
| 358 |
+
# operations when opening. This is particularly relevant
|
| 359 |
+
# for any file that is read over a network, e.g. S3.
|
| 360 |
+
size = detail.get("size")
|
| 361 |
+
|
| 362 |
+
# call target filesystems open
|
| 363 |
+
self._mkcache()
|
| 364 |
+
f = self.fs._open(
|
| 365 |
+
path,
|
| 366 |
+
mode=mode,
|
| 367 |
+
block_size=block_size,
|
| 368 |
+
autocommit=autocommit,
|
| 369 |
+
cache_options=cache_options,
|
| 370 |
+
cache_type="none",
|
| 371 |
+
size=size,
|
| 372 |
+
**kwargs,
|
| 373 |
+
)
|
| 374 |
+
|
| 375 |
+
# set size if not already set
|
| 376 |
+
if size is None:
|
| 377 |
+
detail["size"] = f.size
|
| 378 |
+
self._metadata.update_file(path, detail)
|
| 379 |
+
|
| 380 |
+
if self.compression:
|
| 381 |
+
comp = (
|
| 382 |
+
infer_compression(path)
|
| 383 |
+
if self.compression == "infer"
|
| 384 |
+
else self.compression
|
| 385 |
+
)
|
| 386 |
+
f = compr[comp](f, mode="rb")
|
| 387 |
+
if "blocksize" in detail:
|
| 388 |
+
if detail["blocksize"] != f.blocksize:
|
| 389 |
+
raise BlocksizeMismatchError(
|
| 390 |
+
f"Cached file must be reopened with same block"
|
| 391 |
+
f" size as original (old: {detail['blocksize']},"
|
| 392 |
+
f" new {f.blocksize})"
|
| 393 |
+
)
|
| 394 |
+
else:
|
| 395 |
+
detail["blocksize"] = f.blocksize
|
| 396 |
+
|
| 397 |
+
def _fetch_ranges(ranges):
|
| 398 |
+
return self.fs.cat_ranges(
|
| 399 |
+
[path] * len(ranges),
|
| 400 |
+
[r[0] for r in ranges],
|
| 401 |
+
[r[1] for r in ranges],
|
| 402 |
+
**kwargs,
|
| 403 |
+
)
|
| 404 |
+
|
| 405 |
+
multi_fetcher = None if self.compression else _fetch_ranges
|
| 406 |
+
f.cache = MMapCache(
|
| 407 |
+
f.blocksize, f._fetch_range, f.size, fn, blocks, multi_fetcher=multi_fetcher
|
| 408 |
+
)
|
| 409 |
+
close = f.close
|
| 410 |
+
f.close = lambda: self.close_and_update(f, close)
|
| 411 |
+
self.save_cache()
|
| 412 |
+
return f
|
| 413 |
+
|
| 414 |
+
def _parent(self, path):
|
| 415 |
+
return self.fs._parent(path)
|
| 416 |
+
|
| 417 |
+
def hash_name(self, path: str, *args: Any) -> str:
|
| 418 |
+
# Kept for backward compatibility with downstream libraries.
|
| 419 |
+
# Ignores extra arguments, previously same_name boolean.
|
| 420 |
+
return self._mapper(path)
|
| 421 |
+
|
| 422 |
+
def close_and_update(self, f, close):
|
| 423 |
+
"""Called when a file is closing, so store the set of blocks"""
|
| 424 |
+
if f.closed:
|
| 425 |
+
return
|
| 426 |
+
path = self._strip_protocol(f.path)
|
| 427 |
+
self._metadata.on_close_cached_file(f, path)
|
| 428 |
+
try:
|
| 429 |
+
logger.debug("going to save")
|
| 430 |
+
self.save_cache()
|
| 431 |
+
logger.debug("saved")
|
| 432 |
+
except OSError:
|
| 433 |
+
logger.debug("Cache saving failed while closing file")
|
| 434 |
+
except NameError:
|
| 435 |
+
logger.debug("Cache save failed due to interpreter shutdown")
|
| 436 |
+
close()
|
| 437 |
+
f.closed = True
|
| 438 |
+
|
| 439 |
+
def ls(self, path, detail=True, **kwargs):
|
| 440 |
+
return self.fs.ls(path, detail, **kwargs)
|
| 441 |
+
|
| 442 |
+
def __getattribute__(self, item):
|
| 443 |
+
if item in {
|
| 444 |
+
"load_cache",
|
| 445 |
+
"_get_cached_file_before_open",
|
| 446 |
+
"_open",
|
| 447 |
+
"save_cache",
|
| 448 |
+
"close_and_update",
|
| 449 |
+
"__init__",
|
| 450 |
+
"__getattribute__",
|
| 451 |
+
"__reduce__",
|
| 452 |
+
"_make_local_details",
|
| 453 |
+
"open",
|
| 454 |
+
"cat",
|
| 455 |
+
"cat_file",
|
| 456 |
+
"_cat_file",
|
| 457 |
+
"cat_ranges",
|
| 458 |
+
"_cat_ranges",
|
| 459 |
+
"get",
|
| 460 |
+
"read_block",
|
| 461 |
+
"tail",
|
| 462 |
+
"head",
|
| 463 |
+
"info",
|
| 464 |
+
"ls",
|
| 465 |
+
"exists",
|
| 466 |
+
"isfile",
|
| 467 |
+
"isdir",
|
| 468 |
+
"_check_file",
|
| 469 |
+
"_check_cache",
|
| 470 |
+
"_makedirs",
|
| 471 |
+
"_mkcache",
|
| 472 |
+
"clear_cache",
|
| 473 |
+
"clear_expired_cache",
|
| 474 |
+
"pop_from_cache",
|
| 475 |
+
"local_file",
|
| 476 |
+
"_paths_from_path",
|
| 477 |
+
"get_mapper",
|
| 478 |
+
"open_many",
|
| 479 |
+
"commit_many",
|
| 480 |
+
"hash_name",
|
| 481 |
+
"__hash__",
|
| 482 |
+
"__eq__",
|
| 483 |
+
"to_json",
|
| 484 |
+
"to_dict",
|
| 485 |
+
"cache_size",
|
| 486 |
+
"pipe_file",
|
| 487 |
+
"pipe",
|
| 488 |
+
"start_transaction",
|
| 489 |
+
"end_transaction",
|
| 490 |
+
}:
|
| 491 |
+
# all the methods defined in this class. Note `open` here, since
|
| 492 |
+
# it calls `_open`, but is actually in superclass
|
| 493 |
+
if hasattr(type(self), item):
|
| 494 |
+
return lambda *args, **kw: getattr(type(self), item).__get__(self)(
|
| 495 |
+
*args, **kw
|
| 496 |
+
)
|
| 497 |
+
# method is in the whitelist but not defined on this subclass;
|
| 498 |
+
# fall through to delegate to the wrapped filesystem below
|
| 499 |
+
if item in ["__reduce_ex__"]:
|
| 500 |
+
raise AttributeError
|
| 501 |
+
if item in ["transaction"]:
|
| 502 |
+
# property
|
| 503 |
+
return type(self).transaction.__get__(self)
|
| 504 |
+
if item in {"_cache", "transaction_type", "protocol"}:
|
| 505 |
+
# class attributes
|
| 506 |
+
return getattr(type(self), item)
|
| 507 |
+
if item == "__class__":
|
| 508 |
+
return type(self)
|
| 509 |
+
d = object.__getattribute__(self, "__dict__")
|
| 510 |
+
fs = d.get("fs", None) # fs is not immediately defined
|
| 511 |
+
if item in d:
|
| 512 |
+
return d[item]
|
| 513 |
+
elif fs is not None:
|
| 514 |
+
if item in fs.__dict__:
|
| 515 |
+
# attribute of instance
|
| 516 |
+
return fs.__dict__[item]
|
| 517 |
+
# attributed belonging to the target filesystem
|
| 518 |
+
cls = type(fs)
|
| 519 |
+
m = getattr(cls, item)
|
| 520 |
+
if (inspect.isfunction(m) or inspect.isdatadescriptor(m)) and (
|
| 521 |
+
not hasattr(m, "__self__") or m.__self__ is None
|
| 522 |
+
):
|
| 523 |
+
# instance method
|
| 524 |
+
return m.__get__(fs, cls)
|
| 525 |
+
return m # class method or attribute
|
| 526 |
+
else:
|
| 527 |
+
# attributes of the superclass, while target is being set up
|
| 528 |
+
return super().__getattribute__(item)
|
| 529 |
+
|
| 530 |
+
def __eq__(self, other):
|
| 531 |
+
"""Test for equality."""
|
| 532 |
+
if self is other:
|
| 533 |
+
return True
|
| 534 |
+
if not isinstance(other, type(self)):
|
| 535 |
+
return False
|
| 536 |
+
return (
|
| 537 |
+
self.storage == other.storage
|
| 538 |
+
and self.kwargs == other.kwargs
|
| 539 |
+
and self.cache_check == other.cache_check
|
| 540 |
+
and self.check_files == other.check_files
|
| 541 |
+
and self.expiry == other.expiry
|
| 542 |
+
and self.compression == other.compression
|
| 543 |
+
and self._mapper == other._mapper
|
| 544 |
+
and self.target_protocol == other.target_protocol
|
| 545 |
+
)
|
| 546 |
+
|
| 547 |
+
def __hash__(self):
|
| 548 |
+
"""Calculate hash."""
|
| 549 |
+
return (
|
| 550 |
+
hash(tuple(self.storage))
|
| 551 |
+
^ hash(str(self.kwargs))
|
| 552 |
+
^ hash(self.cache_check)
|
| 553 |
+
^ hash(self.check_files)
|
| 554 |
+
^ hash(self.expiry)
|
| 555 |
+
^ hash(self.compression)
|
| 556 |
+
^ hash(self._mapper)
|
| 557 |
+
^ hash(self.target_protocol)
|
| 558 |
+
)
|
| 559 |
+
|
| 560 |
+
|
| 561 |
+
class WholeFileCacheFileSystem(CachingFileSystem):
|
| 562 |
+
"""Caches whole remote files on first access
|
| 563 |
+
|
| 564 |
+
This class is intended as a layer over any other file system, and
|
| 565 |
+
will make a local copy of each file accessed, so that all subsequent
|
| 566 |
+
reads are local. This is similar to ``CachingFileSystem``, but without
|
| 567 |
+
the block-wise functionality and so can work even when sparse files
|
| 568 |
+
are not allowed. See its docstring for definition of the init
|
| 569 |
+
arguments.
|
| 570 |
+
|
| 571 |
+
The class still needs access to the remote store for listing files,
|
| 572 |
+
and may refresh cached files.
|
| 573 |
+
"""
|
| 574 |
+
|
| 575 |
+
protocol = "filecache"
|
| 576 |
+
local_file = True
|
| 577 |
+
|
| 578 |
+
def open_many(self, open_files, **kwargs):
|
| 579 |
+
paths = [of.path for of in open_files]
|
| 580 |
+
if "r" in open_files.mode:
|
| 581 |
+
self._mkcache()
|
| 582 |
+
else:
|
| 583 |
+
return [
|
| 584 |
+
LocalTempFile(
|
| 585 |
+
self.fs,
|
| 586 |
+
path,
|
| 587 |
+
mode=open_files.mode,
|
| 588 |
+
fn=os.path.join(self.storage[-1], self._mapper(path)),
|
| 589 |
+
**kwargs,
|
| 590 |
+
)
|
| 591 |
+
for path in paths
|
| 592 |
+
]
|
| 593 |
+
|
| 594 |
+
if self.compression:
|
| 595 |
+
raise NotImplementedError
|
| 596 |
+
details = [self._check_file(sp) for sp in paths]
|
| 597 |
+
downpath = [p for p, d in zip(paths, details) if not d]
|
| 598 |
+
downfn0 = [
|
| 599 |
+
os.path.join(self.storage[-1], self._mapper(p))
|
| 600 |
+
for p, d in zip(paths, details)
|
| 601 |
+
] # keep these path names for opening later
|
| 602 |
+
downfn = [fn for fn, d in zip(downfn0, details) if not d]
|
| 603 |
+
if downpath:
|
| 604 |
+
# skip if all files are already cached and up to date
|
| 605 |
+
self.fs.get(downpath, downfn)
|
| 606 |
+
|
| 607 |
+
# update metadata - only happens when downloads are successful
|
| 608 |
+
newdetail = [
|
| 609 |
+
{
|
| 610 |
+
"original": path,
|
| 611 |
+
"fn": self._mapper(path),
|
| 612 |
+
"blocks": True,
|
| 613 |
+
"time": time.time(),
|
| 614 |
+
"uid": self.fs.ukey(path),
|
| 615 |
+
}
|
| 616 |
+
for path in downpath
|
| 617 |
+
]
|
| 618 |
+
for path, detail in zip(downpath, newdetail):
|
| 619 |
+
self._metadata.update_file(path, detail)
|
| 620 |
+
self.save_cache()
|
| 621 |
+
|
| 622 |
+
def firstpart(fn):
|
| 623 |
+
# helper to adapt both whole-file and simple-cache
|
| 624 |
+
return fn[1] if isinstance(fn, tuple) else fn
|
| 625 |
+
|
| 626 |
+
return [
|
| 627 |
+
open(firstpart(fn0) if fn0 else fn1, mode=open_files.mode)
|
| 628 |
+
for fn0, fn1 in zip(details, downfn0)
|
| 629 |
+
]
|
| 630 |
+
|
| 631 |
+
def commit_many(self, open_files):
|
| 632 |
+
self.fs.put([f.fn for f in open_files], [f.path for f in open_files])
|
| 633 |
+
[f.close() for f in open_files]
|
| 634 |
+
for f in open_files:
|
| 635 |
+
# in case autocommit is off, and so close did not already delete
|
| 636 |
+
try:
|
| 637 |
+
os.remove(f.name)
|
| 638 |
+
except FileNotFoundError:
|
| 639 |
+
pass
|
| 640 |
+
self._cache_size = None
|
| 641 |
+
|
| 642 |
+
def _make_local_details(self, path):
|
| 643 |
+
hash = self._mapper(path)
|
| 644 |
+
fn = os.path.join(self.storage[-1], hash)
|
| 645 |
+
detail = {
|
| 646 |
+
"original": path,
|
| 647 |
+
"fn": hash,
|
| 648 |
+
"blocks": True,
|
| 649 |
+
"time": time.time(),
|
| 650 |
+
"uid": self.fs.ukey(path),
|
| 651 |
+
}
|
| 652 |
+
self._metadata.update_file(path, detail)
|
| 653 |
+
logger.debug("Copying %s to local cache", path)
|
| 654 |
+
return fn
|
| 655 |
+
|
| 656 |
+
def cat(
|
| 657 |
+
self,
|
| 658 |
+
path,
|
| 659 |
+
recursive=False,
|
| 660 |
+
on_error="raise",
|
| 661 |
+
callback=DEFAULT_CALLBACK,
|
| 662 |
+
**kwargs,
|
| 663 |
+
):
|
| 664 |
+
paths = self.expand_path(
|
| 665 |
+
path, recursive=recursive, maxdepth=kwargs.get("maxdepth")
|
| 666 |
+
)
|
| 667 |
+
getpaths = []
|
| 668 |
+
storepaths = []
|
| 669 |
+
fns = []
|
| 670 |
+
out = {}
|
| 671 |
+
for p in paths.copy():
|
| 672 |
+
try:
|
| 673 |
+
detail = self._check_file(p)
|
| 674 |
+
if not detail:
|
| 675 |
+
fn = self._make_local_details(p)
|
| 676 |
+
getpaths.append(p)
|
| 677 |
+
storepaths.append(fn)
|
| 678 |
+
else:
|
| 679 |
+
detail, fn = detail if isinstance(detail, tuple) else (None, detail)
|
| 680 |
+
fns.append(fn)
|
| 681 |
+
except Exception as e:
|
| 682 |
+
if on_error == "raise":
|
| 683 |
+
raise
|
| 684 |
+
if on_error == "return":
|
| 685 |
+
out[p] = e
|
| 686 |
+
paths.remove(p)
|
| 687 |
+
|
| 688 |
+
if getpaths:
|
| 689 |
+
self.fs.get(getpaths, storepaths)
|
| 690 |
+
self.save_cache()
|
| 691 |
+
|
| 692 |
+
callback.set_size(len(paths))
|
| 693 |
+
for p, fn in zip(paths, fns):
|
| 694 |
+
with open(fn, "rb") as f:
|
| 695 |
+
out[p] = f.read()
|
| 696 |
+
callback.relative_update(1)
|
| 697 |
+
if isinstance(path, str) and len(paths) == 1 and recursive is False:
|
| 698 |
+
out = out[paths[0]]
|
| 699 |
+
return out
|
| 700 |
+
|
| 701 |
+
def _get_cached_file_before_open(self, path, **kwargs):
|
| 702 |
+
fn = self._make_local_details(path)
|
| 703 |
+
# call target filesystems open
|
| 704 |
+
self._mkcache()
|
| 705 |
+
if self.compression:
|
| 706 |
+
with self.fs._open(path, mode="rb", **kwargs) as f, open(fn, "wb") as f2:
|
| 707 |
+
if isinstance(f, AbstractBufferedFile):
|
| 708 |
+
# want no type of caching if just downloading whole thing
|
| 709 |
+
f.cache = BaseCache(0, f.cache.fetcher, f.size)
|
| 710 |
+
comp = (
|
| 711 |
+
infer_compression(path)
|
| 712 |
+
if self.compression == "infer"
|
| 713 |
+
else self.compression
|
| 714 |
+
)
|
| 715 |
+
f = compr[comp](f, mode="rb")
|
| 716 |
+
data = True
|
| 717 |
+
while data:
|
| 718 |
+
block = getattr(f, "blocksize", 5 * 2**20)
|
| 719 |
+
data = f.read(block)
|
| 720 |
+
f2.write(data)
|
| 721 |
+
else:
|
| 722 |
+
self.fs.get_file(path, fn)
|
| 723 |
+
self.save_cache()
|
| 724 |
+
|
| 725 |
+
def _open(self, path, mode="rb", **kwargs):
|
| 726 |
+
path = self._strip_protocol(path)
|
| 727 |
+
# For read (or append), (try) download from remote
|
| 728 |
+
if "r" in mode or "a" in mode:
|
| 729 |
+
if not self._check_file(path):
|
| 730 |
+
if self.fs.exists(path):
|
| 731 |
+
self._get_cached_file_before_open(path, **kwargs)
|
| 732 |
+
elif "r" in mode:
|
| 733 |
+
raise FileNotFoundError(path)
|
| 734 |
+
|
| 735 |
+
detail, fn = self._check_file(path)
|
| 736 |
+
_, blocks = detail["fn"], detail["blocks"]
|
| 737 |
+
if blocks is True:
|
| 738 |
+
logger.debug("Opening local copy of %s", path)
|
| 739 |
+
else:
|
| 740 |
+
raise ValueError(
|
| 741 |
+
f"Attempt to open partially cached file {path}"
|
| 742 |
+
f" as a wholly cached file"
|
| 743 |
+
)
|
| 744 |
+
|
| 745 |
+
# Just reading does not need special file handling
|
| 746 |
+
if "r" in mode and "+" not in mode:
|
| 747 |
+
# In order to support downstream filesystems to be able to
|
| 748 |
+
# infer the compression from the original filename, like
|
| 749 |
+
# the `TarFileSystem`, let's extend the `io.BufferedReader`
|
| 750 |
+
# fileobject protocol by adding a dedicated attribute
|
| 751 |
+
# `original`.
|
| 752 |
+
f = open(fn, mode)
|
| 753 |
+
f.original = detail.get("original")
|
| 754 |
+
return f
|
| 755 |
+
|
| 756 |
+
hash = self._mapper(path)
|
| 757 |
+
fn = os.path.join(self.storage[-1], hash)
|
| 758 |
+
user_specified_kwargs = {
|
| 759 |
+
k: v
|
| 760 |
+
for k, v in kwargs.items()
|
| 761 |
+
# those kwargs were added by open(), we don't want them
|
| 762 |
+
if k not in ["autocommit", "block_size", "cache_options"]
|
| 763 |
+
}
|
| 764 |
+
return LocalTempFile(self, path, mode=mode, fn=fn, **user_specified_kwargs)
|
| 765 |
+
|
| 766 |
+
async def _cat_file(self, path, start=None, end=None, **kwargs):
|
| 767 |
+
logger.debug("async cat_file %s", path)
|
| 768 |
+
path = self._strip_protocol(path)
|
| 769 |
+
sha = self._mapper(path)
|
| 770 |
+
fn = self._check_file(path)
|
| 771 |
+
|
| 772 |
+
if not fn:
|
| 773 |
+
fn = os.path.join(self.storage[-1], sha)
|
| 774 |
+
await self.fs._get_file(path, fn, **kwargs)
|
| 775 |
+
|
| 776 |
+
with open(fn, "rb") as f: # noqa ASYNC230
|
| 777 |
+
if start:
|
| 778 |
+
f.seek(start)
|
| 779 |
+
size = -1 if end is None else end - f.tell()
|
| 780 |
+
return f.read(size)
|
| 781 |
+
|
| 782 |
+
async def _cat_ranges(
|
| 783 |
+
self, paths, starts, ends, max_gap=None, on_error="return", **kwargs
|
| 784 |
+
):
|
| 785 |
+
logger.debug("async cat ranges %s", paths)
|
| 786 |
+
lpaths = []
|
| 787 |
+
rset = set()
|
| 788 |
+
download = []
|
| 789 |
+
rpaths = []
|
| 790 |
+
for p in paths:
|
| 791 |
+
fn = self._check_file(p)
|
| 792 |
+
if fn is None and p not in rset:
|
| 793 |
+
sha = self._mapper(p)
|
| 794 |
+
fn = os.path.join(self.storage[-1], sha)
|
| 795 |
+
download.append(fn)
|
| 796 |
+
rset.add(p)
|
| 797 |
+
rpaths.append(p)
|
| 798 |
+
lpaths.append(fn)
|
| 799 |
+
if download:
|
| 800 |
+
await self.fs._get(rpaths, download, on_error=on_error)
|
| 801 |
+
|
| 802 |
+
return LocalFileSystem().cat_ranges(
|
| 803 |
+
lpaths, starts, ends, max_gap=max_gap, on_error=on_error, **kwargs
|
| 804 |
+
)
|
| 805 |
+
|
| 806 |
+
|
| 807 |
+
class SimpleCacheFileSystem(WholeFileCacheFileSystem):
|
| 808 |
+
"""Caches whole remote files on first access
|
| 809 |
+
|
| 810 |
+
This class is intended as a layer over any other file system, and
|
| 811 |
+
will make a local copy of each file accessed, so that all subsequent
|
| 812 |
+
reads are local. This implementation only copies whole files, and
|
| 813 |
+
does not keep any metadata about the download time or file details.
|
| 814 |
+
It is therefore safer to use in multi-threaded/concurrent situations.
|
| 815 |
+
|
| 816 |
+
This is the only of the caching filesystems that supports write: you will
|
| 817 |
+
be given a real local open file, and upon close and commit, it will be
|
| 818 |
+
uploaded to the target filesystem; the writability or the target URL is
|
| 819 |
+
not checked until that time.
|
| 820 |
+
|
| 821 |
+
"""
|
| 822 |
+
|
| 823 |
+
protocol = "simplecache"
|
| 824 |
+
local_file = True
|
| 825 |
+
transaction_type = WriteCachedTransaction
|
| 826 |
+
|
| 827 |
+
def __init__(self, **kwargs):
|
| 828 |
+
kw = kwargs.copy()
|
| 829 |
+
for key in ["cache_check", "expiry_time", "check_files"]:
|
| 830 |
+
kw[key] = False
|
| 831 |
+
super().__init__(**kw)
|
| 832 |
+
for storage in self.storage:
|
| 833 |
+
if not os.path.exists(storage):
|
| 834 |
+
self._makedirs(storage)
|
| 835 |
+
|
| 836 |
+
def _check_file(self, path):
|
| 837 |
+
self._check_cache()
|
| 838 |
+
sha = self._mapper(path)
|
| 839 |
+
for storage in self.storage:
|
| 840 |
+
fn = os.path.join(storage, sha)
|
| 841 |
+
if os.path.exists(fn):
|
| 842 |
+
return fn
|
| 843 |
+
|
| 844 |
+
def save_cache(self):
|
| 845 |
+
pass
|
| 846 |
+
|
| 847 |
+
def load_cache(self):
|
| 848 |
+
pass
|
| 849 |
+
|
| 850 |
+
def pipe_file(self, path, value=None, **kwargs):
|
| 851 |
+
if self._intrans:
|
| 852 |
+
with self.open(path, "wb") as f:
|
| 853 |
+
f.write(value)
|
| 854 |
+
else:
|
| 855 |
+
super().pipe_file(path, value)
|
| 856 |
+
|
| 857 |
+
def ls(self, path, detail=True, **kwargs):
|
| 858 |
+
path = self._strip_protocol(path)
|
| 859 |
+
details = []
|
| 860 |
+
try:
|
| 861 |
+
details = self.fs.ls(
|
| 862 |
+
path, detail=True, **kwargs
|
| 863 |
+
).copy() # don't edit original!
|
| 864 |
+
except FileNotFoundError as e:
|
| 865 |
+
ex = e
|
| 866 |
+
else:
|
| 867 |
+
ex = None
|
| 868 |
+
if self._intrans:
|
| 869 |
+
path1 = path.rstrip("/") + "/"
|
| 870 |
+
for f in self.transaction.files:
|
| 871 |
+
if f.path == path:
|
| 872 |
+
details.append(
|
| 873 |
+
{"name": path, "size": f.size or f.tell(), "type": "file"}
|
| 874 |
+
)
|
| 875 |
+
elif f.path.startswith(path1):
|
| 876 |
+
if f.path.count("/") == path1.count("/"):
|
| 877 |
+
details.append(
|
| 878 |
+
{"name": f.path, "size": f.size or f.tell(), "type": "file"}
|
| 879 |
+
)
|
| 880 |
+
else:
|
| 881 |
+
dname = "/".join(f.path.split("/")[: path1.count("/") + 1])
|
| 882 |
+
details.append({"name": dname, "size": 0, "type": "directory"})
|
| 883 |
+
if ex is not None and not details:
|
| 884 |
+
raise ex
|
| 885 |
+
if detail:
|
| 886 |
+
return details
|
| 887 |
+
return sorted(_["name"] for _ in details)
|
| 888 |
+
|
| 889 |
+
def info(self, path, **kwargs):
|
| 890 |
+
path = self._strip_protocol(path)
|
| 891 |
+
if self._intrans:
|
| 892 |
+
f = [_ for _ in self.transaction.files if _.path == path]
|
| 893 |
+
if f:
|
| 894 |
+
size = os.path.getsize(f[0].fn) if f[0].closed else f[0].tell()
|
| 895 |
+
return {"name": path, "size": size, "type": "file"}
|
| 896 |
+
f = any(_.path.startswith(path + "/") for _ in self.transaction.files)
|
| 897 |
+
if f:
|
| 898 |
+
return {"name": path, "size": 0, "type": "directory"}
|
| 899 |
+
return self.fs.info(path, **kwargs)
|
| 900 |
+
|
| 901 |
+
def pipe(self, path, value=None, **kwargs):
|
| 902 |
+
if isinstance(path, str):
|
| 903 |
+
self.pipe_file(self._strip_protocol(path), value, **kwargs)
|
| 904 |
+
elif isinstance(path, dict):
|
| 905 |
+
for k, v in path.items():
|
| 906 |
+
self.pipe_file(self._strip_protocol(k), v, **kwargs)
|
| 907 |
+
else:
|
| 908 |
+
raise ValueError("path must be str or dict")
|
| 909 |
+
|
| 910 |
+
def cat_ranges(
|
| 911 |
+
self, paths, starts, ends, max_gap=None, on_error="return", **kwargs
|
| 912 |
+
):
|
| 913 |
+
logger.debug("cat ranges %s", paths)
|
| 914 |
+
lpaths = [self._check_file(p) for p in paths]
|
| 915 |
+
rpaths = [p for l, p in zip(lpaths, paths) if l is False]
|
| 916 |
+
lpaths = [l for l, p in zip(lpaths, paths) if l is False]
|
| 917 |
+
self.fs.get(rpaths, lpaths)
|
| 918 |
+
paths = [self._check_file(p) for p in paths]
|
| 919 |
+
return LocalFileSystem().cat_ranges(
|
| 920 |
+
paths, starts, ends, max_gap=max_gap, on_error=on_error, **kwargs
|
| 921 |
+
)
|
| 922 |
+
|
| 923 |
+
def _get_cached_file_before_open(self, path, **kwargs):
|
| 924 |
+
sha = self._mapper(path)
|
| 925 |
+
fn = os.path.join(self.storage[-1], sha)
|
| 926 |
+
logger.debug("Copying %s to local cache", path)
|
| 927 |
+
|
| 928 |
+
self._mkcache()
|
| 929 |
+
self._cache_size = None
|
| 930 |
+
|
| 931 |
+
if self.compression:
|
| 932 |
+
with self.fs._open(path, mode="rb", **kwargs) as f, open(fn, "wb") as f2:
|
| 933 |
+
if isinstance(f, AbstractBufferedFile):
|
| 934 |
+
# want no type of caching if just downloading whole thing
|
| 935 |
+
f.cache = BaseCache(0, f.cache.fetcher, f.size)
|
| 936 |
+
comp = (
|
| 937 |
+
infer_compression(path)
|
| 938 |
+
if self.compression == "infer"
|
| 939 |
+
else self.compression
|
| 940 |
+
)
|
| 941 |
+
f = compr[comp](f, mode="rb")
|
| 942 |
+
data = True
|
| 943 |
+
while data:
|
| 944 |
+
block = getattr(f, "blocksize", 5 * 2**20)
|
| 945 |
+
data = f.read(block)
|
| 946 |
+
f2.write(data)
|
| 947 |
+
else:
|
| 948 |
+
self.fs.get_file(path, fn)
|
| 949 |
+
|
| 950 |
+
def _open(self, path, mode="rb", **kwargs):
|
| 951 |
+
path = self._strip_protocol(path)
|
| 952 |
+
sha = self._mapper(path)
|
| 953 |
+
|
| 954 |
+
# For read (or append), (try) download from remote
|
| 955 |
+
if "r" in mode or "a" in mode:
|
| 956 |
+
if not self._check_file(path):
|
| 957 |
+
# append does not require an existing file but read does
|
| 958 |
+
if self.fs.exists(path):
|
| 959 |
+
self._get_cached_file_before_open(path, **kwargs)
|
| 960 |
+
elif "r" in mode:
|
| 961 |
+
raise FileNotFoundError(path)
|
| 962 |
+
|
| 963 |
+
fn = self._check_file(path)
|
| 964 |
+
# Just reading does not need special file handling
|
| 965 |
+
if "r" in mode and "+" not in mode:
|
| 966 |
+
return open(fn, mode)
|
| 967 |
+
|
| 968 |
+
fn = os.path.join(self.storage[-1], sha)
|
| 969 |
+
user_specified_kwargs = {
|
| 970 |
+
k: v
|
| 971 |
+
for k, v in kwargs.items()
|
| 972 |
+
if k not in ["autocommit", "block_size", "cache_options"]
|
| 973 |
+
} # those were added by open()
|
| 974 |
+
return LocalTempFile(
|
| 975 |
+
self,
|
| 976 |
+
path,
|
| 977 |
+
mode=mode,
|
| 978 |
+
autocommit=not self._intrans,
|
| 979 |
+
fn=fn,
|
| 980 |
+
**user_specified_kwargs,
|
| 981 |
+
)
|
| 982 |
+
|
| 983 |
+
|
| 984 |
+
class LocalTempFile:
|
| 985 |
+
"""A temporary local file, which will be uploaded on commit"""
|
| 986 |
+
|
| 987 |
+
def __init__(self, fs, path, fn, mode="wb", autocommit=True, seek=0, **kwargs):
|
| 988 |
+
self.fn = fn
|
| 989 |
+
self.fh = open(fn, mode)
|
| 990 |
+
self.mode = mode
|
| 991 |
+
if seek:
|
| 992 |
+
self.fh.seek(seek)
|
| 993 |
+
self.path = path
|
| 994 |
+
self.size = None
|
| 995 |
+
self.fs = fs
|
| 996 |
+
self.closed = False
|
| 997 |
+
self.autocommit = autocommit
|
| 998 |
+
self.kwargs = kwargs
|
| 999 |
+
|
| 1000 |
+
def __reduce__(self):
|
| 1001 |
+
# always open in r+b to allow continuing writing at a location
|
| 1002 |
+
return (
|
| 1003 |
+
LocalTempFile,
|
| 1004 |
+
(self.fs, self.path, self.fn, "r+b", self.autocommit, self.tell()),
|
| 1005 |
+
)
|
| 1006 |
+
|
| 1007 |
+
def __enter__(self):
|
| 1008 |
+
return self.fh
|
| 1009 |
+
|
| 1010 |
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
| 1011 |
+
self.close()
|
| 1012 |
+
|
| 1013 |
+
def close(self):
|
| 1014 |
+
# self.size = self.fh.tell()
|
| 1015 |
+
if self.closed:
|
| 1016 |
+
return
|
| 1017 |
+
self.fh.close()
|
| 1018 |
+
self.closed = True
|
| 1019 |
+
if self.autocommit:
|
| 1020 |
+
self.commit()
|
| 1021 |
+
|
| 1022 |
+
def discard(self):
|
| 1023 |
+
self.fh.close()
|
| 1024 |
+
os.remove(self.fn)
|
| 1025 |
+
|
| 1026 |
+
def commit(self):
|
| 1027 |
+
# calling put() with list arguments avoids path expansion and additional operations
|
| 1028 |
+
# like isdir()
|
| 1029 |
+
self.fs.put([self.fn], [self.path], **self.kwargs)
|
| 1030 |
+
# we do not delete the local copy, it's still in the cache.
|
| 1031 |
+
|
| 1032 |
+
@property
|
| 1033 |
+
def name(self):
|
| 1034 |
+
return self.fn
|
| 1035 |
+
|
| 1036 |
+
def __repr__(self) -> str:
|
| 1037 |
+
return f"LocalTempFile: {self.path}"
|
| 1038 |
+
|
| 1039 |
+
def __getattr__(self, item):
|
| 1040 |
+
return getattr(self.fh, item)
|