Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .cache/uv/archive-v0/-f_0_DZnf30ScnbSOEDOA/tqdm-4.70.0.dist-info/METADATA +1600 -0
- .cache/uv/archive-v0/-f_0_DZnf30ScnbSOEDOA/tqdm-4.70.0.dist-info/RECORD +39 -0
- .cache/uv/archive-v0/-f_0_DZnf30ScnbSOEDOA/tqdm-4.70.0.dist-info/WHEEL +5 -0
- .cache/uv/archive-v0/-f_0_DZnf30ScnbSOEDOA/tqdm-4.70.0.dist-info/entry_points.txt +2 -0
- .cache/uv/archive-v0/-f_0_DZnf30ScnbSOEDOA/tqdm-4.70.0.dist-info/top_level.txt +1 -0
- .cache/uv/archive-v0/-f_0_DZnf30ScnbSOEDOA/tqdm/autonotebook.py +38 -0
- .cache/uv/archive-v0/-f_0_DZnf30ScnbSOEDOA/tqdm/cli.py +324 -0
- .cache/uv/archive-v0/-f_0_DZnf30ScnbSOEDOA/tqdm/completion.sh +19 -0
- .cache/uv/archive-v0/-f_0_DZnf30ScnbSOEDOA/tqdm/dask.py +44 -0
- .cache/uv/archive-v0/-f_0_DZnf30ScnbSOEDOA/tqdm/rich.py +154 -0
- .cache/uv/archive-v0/-f_0_DZnf30ScnbSOEDOA/tqdm/std.py +1533 -0
- .cache/uv/archive-v0/-f_0_DZnf30ScnbSOEDOA/tqdm/tk.py +196 -0
- .cache/uv/archive-v0/-f_0_DZnf30ScnbSOEDOA/tqdm/tqdm.1 +241 -0
- .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/__init__.py +75 -0
- .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/_version.py +24 -0
- .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/asyn.py +1171 -0
- .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/caching.py +1025 -0
- .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/callbacks.py +324 -0
- .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/compression.py +185 -0
- .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/core.py +760 -0
- .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/exceptions.py +18 -0
- .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/gui.py +417 -0
- .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/__init__.py +0 -0
- .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/arrow.py +322 -0
- .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/asyn_wrapper.py +124 -0
- .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/cache_mapper.py +75 -0
- .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/cache_metadata.py +217 -0
- .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/cached.py +1040 -0
- .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/chained.py +23 -0
- .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/dask.py +152 -0
- .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/data.py +71 -0
- .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/dbfs.py +497 -0
- .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/dirfs.py +426 -0
- .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/ftp.py +442 -0
- .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/gist.py +241 -0
- .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/git.py +114 -0
- .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/github.py +333 -0
- .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/http.py +902 -0
- .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/http_sync.py +937 -0
- .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/jupyter.py +129 -0
- .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/libarchive.py +213 -0
- .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/memory.py +393 -0
- .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/sftp.py +187 -0
- .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/webhdfs.py +503 -0
- .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/registry.py +337 -0
- .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/tests/abstract/__init__.py +290 -0
- .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/tests/abstract/common.py +175 -0
- .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/tests/abstract/copy.py +557 -0
- .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/tests/abstract/get.py +587 -0
- .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/tests/abstract/mv.py +57 -0
.cache/uv/archive-v0/-f_0_DZnf30ScnbSOEDOA/tqdm-4.70.0.dist-info/METADATA
ADDED
|
@@ -0,0 +1,1600 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.4
|
| 2 |
+
Name: tqdm
|
| 3 |
+
Version: 4.70.0
|
| 4 |
+
Summary: Fast, Extensible Progress Meter
|
| 5 |
+
Maintainer-email: tqdm developers <devs@tqdm.ml>
|
| 6 |
+
License: MPL-2.0 AND MIT
|
| 7 |
+
Project-URL: homepage, https://tqdm.github.io
|
| 8 |
+
Project-URL: repository, https://github.com/tqdm/tqdm
|
| 9 |
+
Project-URL: changelog, https://tqdm.github.io/releases
|
| 10 |
+
Project-URL: wiki, https://github.com/tqdm/tqdm/wiki
|
| 11 |
+
Keywords: progressbar,progressmeter,progress,bar,meter,rate,eta,console,terminal,time
|
| 12 |
+
Classifier: Development Status :: 5 - Production/Stable
|
| 13 |
+
Classifier: Environment :: Console
|
| 14 |
+
Classifier: Environment :: MacOS X
|
| 15 |
+
Classifier: Environment :: Other Environment
|
| 16 |
+
Classifier: Environment :: Win32 (MS Windows)
|
| 17 |
+
Classifier: Environment :: X11 Applications
|
| 18 |
+
Classifier: Framework :: IPython
|
| 19 |
+
Classifier: Framework :: Jupyter
|
| 20 |
+
Classifier: Intended Audience :: Developers
|
| 21 |
+
Classifier: Intended Audience :: Education
|
| 22 |
+
Classifier: Intended Audience :: End Users/Desktop
|
| 23 |
+
Classifier: Intended Audience :: Other Audience
|
| 24 |
+
Classifier: Intended Audience :: System Administrators
|
| 25 |
+
Classifier: Operating System :: MacOS
|
| 26 |
+
Classifier: Operating System :: MacOS :: MacOS X
|
| 27 |
+
Classifier: Operating System :: Microsoft
|
| 28 |
+
Classifier: Operating System :: Microsoft :: MS-DOS
|
| 29 |
+
Classifier: Operating System :: Microsoft :: Windows
|
| 30 |
+
Classifier: Operating System :: POSIX
|
| 31 |
+
Classifier: Operating System :: POSIX :: BSD
|
| 32 |
+
Classifier: Operating System :: POSIX :: BSD :: FreeBSD
|
| 33 |
+
Classifier: Operating System :: POSIX :: Linux
|
| 34 |
+
Classifier: Operating System :: POSIX :: SunOS/Solaris
|
| 35 |
+
Classifier: Operating System :: Unix
|
| 36 |
+
Classifier: Programming Language :: Python
|
| 37 |
+
Classifier: Programming Language :: Python :: 3
|
| 38 |
+
Classifier: Programming Language :: Python :: 3.8
|
| 39 |
+
Classifier: Programming Language :: Python :: 3.9
|
| 40 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 41 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 42 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 43 |
+
Classifier: Programming Language :: Python :: 3.13
|
| 44 |
+
Classifier: Programming Language :: Python :: 3.14
|
| 45 |
+
Classifier: Programming Language :: Python :: 3 :: Only
|
| 46 |
+
Classifier: Programming Language :: Python :: Implementation
|
| 47 |
+
Classifier: Programming Language :: Python :: Implementation :: IronPython
|
| 48 |
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
| 49 |
+
Classifier: Programming Language :: Unix Shell
|
| 50 |
+
Classifier: Topic :: Desktop Environment
|
| 51 |
+
Classifier: Topic :: Education :: Computer Aided Instruction (CAI)
|
| 52 |
+
Classifier: Topic :: Education :: Testing
|
| 53 |
+
Classifier: Topic :: Office/Business
|
| 54 |
+
Classifier: Topic :: Other/Nonlisted Topic
|
| 55 |
+
Classifier: Topic :: Software Development :: Build Tools
|
| 56 |
+
Classifier: Topic :: Software Development :: Libraries
|
| 57 |
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
| 58 |
+
Classifier: Topic :: Software Development :: Pre-processors
|
| 59 |
+
Classifier: Topic :: Software Development :: User Interfaces
|
| 60 |
+
Classifier: Topic :: System :: Installation/Setup
|
| 61 |
+
Classifier: Topic :: System :: Logging
|
| 62 |
+
Classifier: Topic :: System :: Monitoring
|
| 63 |
+
Classifier: Topic :: System :: Shells
|
| 64 |
+
Classifier: Topic :: Terminals
|
| 65 |
+
Classifier: Topic :: Utilities
|
| 66 |
+
Requires-Python: >=3.8
|
| 67 |
+
Description-Content-Type: text/x-rst
|
| 68 |
+
License-File: LICENCE
|
| 69 |
+
Requires-Dist: colorama; platform_system == "Windows"
|
| 70 |
+
Provides-Extra: discord
|
| 71 |
+
Requires-Dist: requests; extra == "discord"
|
| 72 |
+
Requires-Dist: envwrap; extra == "discord"
|
| 73 |
+
Provides-Extra: slack
|
| 74 |
+
Requires-Dist: slack-sdk; extra == "slack"
|
| 75 |
+
Requires-Dist: envwrap; extra == "slack"
|
| 76 |
+
Provides-Extra: telegram
|
| 77 |
+
Requires-Dist: requests; extra == "telegram"
|
| 78 |
+
Requires-Dist: envwrap; extra == "telegram"
|
| 79 |
+
Provides-Extra: notebook
|
| 80 |
+
Requires-Dist: ipywidgets>=6; extra == "notebook"
|
| 81 |
+
Dynamic: license-file
|
| 82 |
+
|
| 83 |
+
|Logo|
|
| 84 |
+
|
| 85 |
+
tqdm
|
| 86 |
+
====
|
| 87 |
+
|
| 88 |
+
|Py-Versions| |Versions| |Conda-Forge-Status| |Docker| |Snapcraft|
|
| 89 |
+
|
| 90 |
+
|Build-Status| |Coverage-Status| |Branch-Coverage-Status| |Codacy-Grade| |Libraries-Rank| |PyPI-Downloads|
|
| 91 |
+
|
| 92 |
+
|LICENCE| |OpenHub-Status| |colab-demo| |binder-demo| |awesome-python|
|
| 93 |
+
|
| 94 |
+
``tqdm`` derives from the Arabic word *taqaddum* (تقدّم) which can mean "progress,"
|
| 95 |
+
and is an abbreviation for "I love you so much" in Spanish (*te quiero demasiado*).
|
| 96 |
+
|
| 97 |
+
Instantly make your loops show a smart progress meter - just wrap any
|
| 98 |
+
iterable with ``tqdm(iterable)``, and you're done!
|
| 99 |
+
|
| 100 |
+
.. code:: python
|
| 101 |
+
|
| 102 |
+
from tqdm import tqdm
|
| 103 |
+
for i in tqdm(range(10000)):
|
| 104 |
+
...
|
| 105 |
+
|
| 106 |
+
``76%|████████████████████████ | 7568/10000 [00:33<00:10, 229.00it/s]``
|
| 107 |
+
|
| 108 |
+
``trange(N)`` can also be used as a convenient shortcut for
|
| 109 |
+
``tqdm(range(N))``.
|
| 110 |
+
|
| 111 |
+
|Screenshot|
|
| 112 |
+
|Video| |Slides| |Merch|
|
| 113 |
+
|
| 114 |
+
It can also be executed as a module with pipes:
|
| 115 |
+
|
| 116 |
+
.. code:: sh
|
| 117 |
+
|
| 118 |
+
$ seq 9999999 | tqdm --bytes | wc -l
|
| 119 |
+
75.2MB [00:00, 217MB/s]
|
| 120 |
+
9999999
|
| 121 |
+
|
| 122 |
+
$ tar -zcf - docs/ | tqdm --bytes --total `du -sb docs/ | cut -f1` \
|
| 123 |
+
> backup.tgz
|
| 124 |
+
32%|██████████▍ | 8.89G/27.9G [00:42<01:31, 223MB/s]
|
| 125 |
+
|
| 126 |
+
Overhead is low -- about 60ns per iteration (80ns with ``tqdm.gui``), and is
|
| 127 |
+
unit tested against performance regression.
|
| 128 |
+
By comparison, the well-established
|
| 129 |
+
`ProgressBar <https://github.com/niltonvolpato/python-progressbar>`__ has
|
| 130 |
+
an 800ns/iter overhead.
|
| 131 |
+
|
| 132 |
+
In addition to its low overhead, ``tqdm`` uses smart algorithms to predict
|
| 133 |
+
the remaining time and to skip unnecessary iteration displays, which allows
|
| 134 |
+
for a negligible overhead in most cases.
|
| 135 |
+
|
| 136 |
+
``tqdm`` works on any platform
|
| 137 |
+
(Linux, Windows, Mac, FreeBSD, NetBSD, Solaris/SunOS),
|
| 138 |
+
in any console or in a GUI, and is also friendly with IPython/Jupyter notebooks.
|
| 139 |
+
|
| 140 |
+
``tqdm`` does not require any dependencies (not even ``curses``!), just
|
| 141 |
+
Python and an environment supporting ``carriage return \r`` and
|
| 142 |
+
``line feed \n`` control characters.
|
| 143 |
+
|
| 144 |
+
**Featured Sponsors**
|
| 145 |
+
|
| 146 |
+
======== ================================================
|
| 147 |
+
|OpenAI| Your Logo Here
|
| 148 |
+
======== ================================================
|
| 149 |
+
OpenAI `Sponsors <https://github.com/sponsors/tqdm>`__
|
| 150 |
+
======== ================================================
|
| 151 |
+
|
| 152 |
+
.. |OpenAI| image:: https://avatars.githubusercontent.com/u/14957082?s=96
|
| 153 |
+
:target: https://openai.com
|
| 154 |
+
|
| 155 |
+
------------------------------------------
|
| 156 |
+
|
| 157 |
+
.. contents:: Table of contents
|
| 158 |
+
:backlinks: top
|
| 159 |
+
:local:
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
Installation
|
| 163 |
+
------------
|
| 164 |
+
|
| 165 |
+
Latest PyPI stable release
|
| 166 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 167 |
+
|
| 168 |
+
|Versions| |PyPI-Downloads| |Libraries-Dependents|
|
| 169 |
+
|
| 170 |
+
.. code:: sh
|
| 171 |
+
|
| 172 |
+
pip install tqdm
|
| 173 |
+
|
| 174 |
+
Latest development release on GitHub
|
| 175 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 176 |
+
|
| 177 |
+
|GitHub-Status| |GitHub-Stars| |GitHub-Commits| |GitHub-Forks| |GitHub-Updated|
|
| 178 |
+
|
| 179 |
+
Pull and install pre-release ``devel`` branch:
|
| 180 |
+
|
| 181 |
+
.. code:: sh
|
| 182 |
+
|
| 183 |
+
pip install "git+https://github.com/tqdm/tqdm.git@devel#egg=tqdm"
|
| 184 |
+
|
| 185 |
+
Latest Conda release
|
| 186 |
+
~~~~~~~~~~~~~~~~~~~~
|
| 187 |
+
|
| 188 |
+
|Conda-Forge-Status|
|
| 189 |
+
|
| 190 |
+
.. code:: sh
|
| 191 |
+
|
| 192 |
+
conda install -c conda-forge tqdm
|
| 193 |
+
|
| 194 |
+
Latest Snapcraft release
|
| 195 |
+
~~~~~~~~~~~~~~~~~~~~~~~~
|
| 196 |
+
|
| 197 |
+
|Snapcraft|
|
| 198 |
+
|
| 199 |
+
There are 3 channels to choose from:
|
| 200 |
+
|
| 201 |
+
.. code:: sh
|
| 202 |
+
|
| 203 |
+
snap install tqdm # implies --stable, i.e. latest tagged release
|
| 204 |
+
snap install tqdm --candidate # master branch
|
| 205 |
+
snap install tqdm --edge # devel branch
|
| 206 |
+
|
| 207 |
+
Note that ``snap`` binaries are purely for CLI use (not ``import``-able), and
|
| 208 |
+
automatically set up ``bash`` tab-completion.
|
| 209 |
+
|
| 210 |
+
Latest Docker release
|
| 211 |
+
~~~~~~~~~~~~~~~~~~~~~
|
| 212 |
+
|
| 213 |
+
|Docker|
|
| 214 |
+
|
| 215 |
+
.. code:: sh
|
| 216 |
+
|
| 217 |
+
docker pull tqdm/tqdm
|
| 218 |
+
docker run -i --rm tqdm/tqdm --help
|
| 219 |
+
|
| 220 |
+
Other
|
| 221 |
+
~~~~~
|
| 222 |
+
|
| 223 |
+
There are other (unofficial) places where ``tqdm`` may be downloaded, particularly for CLI use:
|
| 224 |
+
|
| 225 |
+
|Repology|
|
| 226 |
+
|
| 227 |
+
.. |Repology| image:: https://repology.org/badge/tiny-repos/python:tqdm.svg
|
| 228 |
+
:target: https://repology.org/project/python:tqdm/versions
|
| 229 |
+
|
| 230 |
+
Changelog
|
| 231 |
+
---------
|
| 232 |
+
|
| 233 |
+
The list of all changes is available either on GitHub's Releases:
|
| 234 |
+
|GitHub-Status|, on the
|
| 235 |
+
`wiki <https://github.com/tqdm/tqdm/wiki/Releases>`__, or on the
|
| 236 |
+
`website <https://tqdm.github.io/releases>`__.
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
Usage
|
| 240 |
+
-----
|
| 241 |
+
|
| 242 |
+
``tqdm`` is very versatile and can be used in a number of ways.
|
| 243 |
+
The three main ones are given below.
|
| 244 |
+
|
| 245 |
+
Iterable-based
|
| 246 |
+
~~~~~~~~~~~~~~
|
| 247 |
+
|
| 248 |
+
Wrap ``tqdm()`` around any iterable:
|
| 249 |
+
|
| 250 |
+
.. code:: python
|
| 251 |
+
|
| 252 |
+
from tqdm import tqdm
|
| 253 |
+
from time import sleep
|
| 254 |
+
|
| 255 |
+
text = ""
|
| 256 |
+
for char in tqdm(["a", "b", "c", "d"]):
|
| 257 |
+
sleep(0.25)
|
| 258 |
+
text = text + char
|
| 259 |
+
|
| 260 |
+
``trange(i)`` is a special optimised instance of ``tqdm(range(i))``:
|
| 261 |
+
|
| 262 |
+
.. code:: python
|
| 263 |
+
|
| 264 |
+
from tqdm import trange
|
| 265 |
+
|
| 266 |
+
for i in trange(100):
|
| 267 |
+
sleep(0.01)
|
| 268 |
+
|
| 269 |
+
Instantiation outside of the loop allows for manual control over ``tqdm()``:
|
| 270 |
+
|
| 271 |
+
.. code:: python
|
| 272 |
+
|
| 273 |
+
pbar = tqdm(["a", "b", "c", "d"])
|
| 274 |
+
for char in pbar:
|
| 275 |
+
sleep(0.25)
|
| 276 |
+
pbar.set_description("Processing %s" % char)
|
| 277 |
+
|
| 278 |
+
Manual
|
| 279 |
+
~~~~~~
|
| 280 |
+
|
| 281 |
+
Manual control of ``tqdm()`` updates using a ``with`` statement:
|
| 282 |
+
|
| 283 |
+
.. code:: python
|
| 284 |
+
|
| 285 |
+
with tqdm(total=100) as pbar:
|
| 286 |
+
for i in range(10):
|
| 287 |
+
sleep(0.1)
|
| 288 |
+
pbar.update(10)
|
| 289 |
+
|
| 290 |
+
If the optional variable ``total`` (or an iterable with ``len()``) is
|
| 291 |
+
provided, predictive stats are displayed.
|
| 292 |
+
|
| 293 |
+
``with`` is also optional (you can just assign ``tqdm()`` to a variable,
|
| 294 |
+
but in this case don't forget to ``del`` or ``close()`` at the end:
|
| 295 |
+
|
| 296 |
+
.. code:: python
|
| 297 |
+
|
| 298 |
+
pbar = tqdm(total=100)
|
| 299 |
+
for i in range(10):
|
| 300 |
+
sleep(0.1)
|
| 301 |
+
pbar.update(10)
|
| 302 |
+
pbar.close()
|
| 303 |
+
|
| 304 |
+
Module
|
| 305 |
+
~~~~~~
|
| 306 |
+
|
| 307 |
+
Perhaps the most wonderful use of ``tqdm`` is in a script or on the command
|
| 308 |
+
line. Simply inserting ``tqdm`` (or ``python -m tqdm``) between pipes will pass
|
| 309 |
+
through all ``stdin`` to ``stdout`` while printing progress to ``stderr``.
|
| 310 |
+
|
| 311 |
+
The example below demonstrate counting the number of lines in all Python files
|
| 312 |
+
in the current directory, with timing information included.
|
| 313 |
+
|
| 314 |
+
.. code:: sh
|
| 315 |
+
|
| 316 |
+
$ time find . -name '*.py' -type f -exec cat \{} \; | wc -l
|
| 317 |
+
857365
|
| 318 |
+
|
| 319 |
+
real 0m3.458s
|
| 320 |
+
user 0m0.274s
|
| 321 |
+
sys 0m3.325s
|
| 322 |
+
|
| 323 |
+
$ time find . -name '*.py' -type f -exec cat \{} \; | tqdm | wc -l
|
| 324 |
+
857366it [00:03, 246471.31it/s]
|
| 325 |
+
857365
|
| 326 |
+
|
| 327 |
+
real 0m3.585s
|
| 328 |
+
user 0m0.862s
|
| 329 |
+
sys 0m3.358s
|
| 330 |
+
|
| 331 |
+
Note that the usual arguments for ``tqdm`` can also be specified.
|
| 332 |
+
|
| 333 |
+
.. code:: sh
|
| 334 |
+
|
| 335 |
+
$ find . -name '*.py' -type f -exec cat \{} \; |
|
| 336 |
+
tqdm --unit loc --unit_scale --total 857366 >> /dev/null
|
| 337 |
+
100%|█████████████████████████████████| 857K/857K [00:04<00:00, 246Kloc/s]
|
| 338 |
+
|
| 339 |
+
Backing up a large directory?
|
| 340 |
+
|
| 341 |
+
.. code:: sh
|
| 342 |
+
|
| 343 |
+
$ tar -zcf - docs/ | tqdm --bytes --total `du -sb docs/ | cut -f1` \
|
| 344 |
+
> backup.tgz
|
| 345 |
+
44%|██████████████▊ | 153M/352M [00:14<00:18, 11.0MB/s]
|
| 346 |
+
|
| 347 |
+
This can be beautified further:
|
| 348 |
+
|
| 349 |
+
.. code:: sh
|
| 350 |
+
|
| 351 |
+
$ BYTES=$(du -sb docs/ | cut -f1)
|
| 352 |
+
$ tar -cf - docs/ \
|
| 353 |
+
| tqdm --bytes --total "$BYTES" --desc Processing | gzip \
|
| 354 |
+
| tqdm --bytes --total "$BYTES" --desc Compressed --position 1 \
|
| 355 |
+
> ~/backup.tgz
|
| 356 |
+
Processing: 100%|██████████████████████| 352M/352M [00:14<00:00, 30.2MB/s]
|
| 357 |
+
Compressed: 42%|█████████▎ | 148M/352M [00:14<00:19, 10.9MB/s]
|
| 358 |
+
|
| 359 |
+
Or done on a file level using 7-zip:
|
| 360 |
+
|
| 361 |
+
.. code:: sh
|
| 362 |
+
|
| 363 |
+
$ 7z a -bd -r backup.7z docs/ | grep Compressing \
|
| 364 |
+
| tqdm --total $(find docs/ -type f | wc -l) --unit files \
|
| 365 |
+
| grep -v Compressing
|
| 366 |
+
100%|██████████████████████████▉| 15327/15327 [01:00<00:00, 712.96files/s]
|
| 367 |
+
|
| 368 |
+
Pre-existing CLI programs already outputting basic progress information will
|
| 369 |
+
benefit from ``tqdm``'s ``--update`` and ``--update_to`` flags:
|
| 370 |
+
|
| 371 |
+
.. code:: sh
|
| 372 |
+
|
| 373 |
+
$ seq 3 0.1 5 | tqdm --total 5 --update_to --null
|
| 374 |
+
100%|████████████████████████████████████| 5.0/5 [00:00<00:00, 9673.21it/s]
|
| 375 |
+
$ seq 10 | tqdm --update --null # 1 + 2 + ... + 10 = 55 iterations
|
| 376 |
+
55it [00:00, 90006.52it/s]
|
| 377 |
+
|
| 378 |
+
FAQ and Known Issues
|
| 379 |
+
--------------------
|
| 380 |
+
|
| 381 |
+
|GitHub-Issues|
|
| 382 |
+
|
| 383 |
+
The most common issues relate to excessive output on multiple lines, instead
|
| 384 |
+
of a neat one-line progress bar.
|
| 385 |
+
|
| 386 |
+
- Consoles in general: require support for carriage return (``CR``, ``\r``).
|
| 387 |
+
|
| 388 |
+
* Some cloud logging consoles which don't support ``\r`` properly
|
| 389 |
+
(`cloudwatch <https://github.com/tqdm/tqdm/issues/966>`__,
|
| 390 |
+
`K8s <https://github.com/tqdm/tqdm/issues/1319>`__) may benefit from
|
| 391 |
+
``export TQDM_POSITION=-1``.
|
| 392 |
+
|
| 393 |
+
- Nested progress bars:
|
| 394 |
+
|
| 395 |
+
* Consoles in general: require support for moving cursors up to the
|
| 396 |
+
previous line. For example,
|
| 397 |
+
`IDLE <https://github.com/tqdm/tqdm/issues/191#issuecomment-230168030>`__,
|
| 398 |
+
`ConEmu <https://github.com/tqdm/tqdm/issues/254>`__ and
|
| 399 |
+
`PyCharm <https://github.com/tqdm/tqdm/issues/203>`__ (also
|
| 400 |
+
`here <https://github.com/tqdm/tqdm/issues/208>`__,
|
| 401 |
+
`here <https://github.com/tqdm/tqdm/issues/307>`__, and
|
| 402 |
+
`here <https://github.com/tqdm/tqdm/issues/454#issuecomment-335416815>`__)
|
| 403 |
+
lack full support.
|
| 404 |
+
* Windows: additionally may require the Python module ``colorama``
|
| 405 |
+
to ensure nested bars stay within their respective lines.
|
| 406 |
+
|
| 407 |
+
- Unicode:
|
| 408 |
+
|
| 409 |
+
* Environments which report that they support unicode will have solid smooth
|
| 410 |
+
progress bars. The fallback is an ``ascii``-only bar.
|
| 411 |
+
* Windows consoles often only partially support unicode and thus
|
| 412 |
+
`often require explicit ascii=True <https://github.com/tqdm/tqdm/issues/454#issuecomment-335416815>`__
|
| 413 |
+
(also `here <https://github.com/tqdm/tqdm/issues/499>`__). This is due to
|
| 414 |
+
either normal-width unicode characters being incorrectly displayed as
|
| 415 |
+
"wide", or some unicode characters not rendering.
|
| 416 |
+
|
| 417 |
+
- Wrapping generators:
|
| 418 |
+
|
| 419 |
+
* Generator wrapper functions tend to hide the length of iterables.
|
| 420 |
+
``tqdm`` does not.
|
| 421 |
+
* Replace ``tqdm(enumerate(...))`` with ``enumerate(tqdm(...))`` or
|
| 422 |
+
``tqdm(enumerate(x), total=len(x), ...)``.
|
| 423 |
+
The same applies to ``numpy.ndenumerate``.
|
| 424 |
+
* Replace ``tqdm(zip(a, b))`` with ``zip(tqdm(a), b)`` or even
|
| 425 |
+
``zip(tqdm(a), tqdm(b))``.
|
| 426 |
+
* The same applies to ``itertools``.
|
| 427 |
+
* Some useful convenience functions can be found under ``tqdm.contrib``.
|
| 428 |
+
|
| 429 |
+
- `No intermediate output in docker-compose <https://github.com/tqdm/tqdm/issues/771>`__:
|
| 430 |
+
use ``docker-compose run`` instead of ``docker-compose up`` and ``tty: true``.
|
| 431 |
+
|
| 432 |
+
- Overriding defaults via environment variables:
|
| 433 |
+
e.g. in CI/cloud jobs, ``export TQDM_MININTERVAL=5`` to avoid log spam.
|
| 434 |
+
This override logic is handled by the ``tqdm.utils.envwrap`` decorator
|
| 435 |
+
(useful independent of ``tqdm``).
|
| 436 |
+
|
| 437 |
+
If you come across any other difficulties, browse and file |GitHub-Issues|.
|
| 438 |
+
|
| 439 |
+
Documentation
|
| 440 |
+
-------------
|
| 441 |
+
|
| 442 |
+
|Py-Versions| |README-Hits| (Since 19 May 2016)
|
| 443 |
+
|
| 444 |
+
.. code:: python
|
| 445 |
+
|
| 446 |
+
class tqdm():
|
| 447 |
+
"""
|
| 448 |
+
Decorate an iterable object, returning an iterator which acts exactly
|
| 449 |
+
like the original iterable, but prints a dynamically updating
|
| 450 |
+
progress bar every time a value is requested.
|
| 451 |
+
"""
|
| 452 |
+
|
| 453 |
+
@envwrap("tqdm") # override defaults via env vars
|
| 454 |
+
def __init__(self, iterable=None, desc=None, total=None, leave=True,
|
| 455 |
+
file=None, ncols=None, mininterval=0.1,
|
| 456 |
+
maxinterval=10.0, miniters=None, ascii=None, disable=False,
|
| 457 |
+
unit='it', unit_scale=False, dynamic_ncols=False,
|
| 458 |
+
smoothing=0.3, bar_format=None, initial=0, position=None,
|
| 459 |
+
postfix=None, unit_divisor=1000, write_bytes=False,
|
| 460 |
+
lock_args=None, nrows=None, colour=None, delay=0):
|
| 461 |
+
|
| 462 |
+
Parameters
|
| 463 |
+
~~~~~~~~~~
|
| 464 |
+
|
| 465 |
+
* iterable : iterable, optional
|
| 466 |
+
Iterable to decorate with a progress bar.
|
| 467 |
+
Leave blank to manually manage the updates.
|
| 468 |
+
* desc : str, optional
|
| 469 |
+
Prefix for the progress bar.
|
| 470 |
+
* total : int or float, optional
|
| 471 |
+
The number of expected iterations. If unspecified,
|
| 472 |
+
len(iterable) is used if possible. If float("inf") or as a last
|
| 473 |
+
resort, only basic progress statistics are displayed
|
| 474 |
+
(no ETA, no progress bar).
|
| 475 |
+
If ``gui`` is True and this parameter needs subsequent updating,
|
| 476 |
+
specify an initial arbitrary large positive number,
|
| 477 |
+
e.g. 9e9.
|
| 478 |
+
* leave : bool, optional
|
| 479 |
+
If [default: True], keeps all traces of the progress bar
|
| 480 |
+
upon termination of iteration.
|
| 481 |
+
If ``None``, will leave only if ``position`` is ``0``.
|
| 482 |
+
* file : ``io.TextIOWrapper`` or ``io.StringIO``, optional
|
| 483 |
+
Specifies where to output the progress messages
|
| 484 |
+
(default: sys.stderr). Uses ``file.write(str)`` and ``file.flush()``
|
| 485 |
+
methods. For encoding, see ``write_bytes``.
|
| 486 |
+
* ncols : int, optional
|
| 487 |
+
The width of the entire output message. If specified,
|
| 488 |
+
dynamically resizes the progress bar to stay within this bound.
|
| 489 |
+
If unspecified, attempts to use environment width. The
|
| 490 |
+
fallback is a meter width of 10 and no limit for the counter and
|
| 491 |
+
statistics. If 0, will not print any meter (only stats).
|
| 492 |
+
* mininterval : float, optional
|
| 493 |
+
Minimum progress display update interval [default: 0.1] seconds.
|
| 494 |
+
* maxinterval : float, optional
|
| 495 |
+
Maximum progress display update interval [default: 10] seconds.
|
| 496 |
+
Automatically adjusts ``miniters`` to correspond to ``mininterval``
|
| 497 |
+
after long display update lag. Only works if ``dynamic_miniters``
|
| 498 |
+
or monitor thread is enabled.
|
| 499 |
+
* miniters : int or float, optional
|
| 500 |
+
Minimum progress display update interval, in iterations.
|
| 501 |
+
If 0 and ``dynamic_miniters``, will automatically adjust to equal
|
| 502 |
+
``mininterval`` (more CPU efficient, good for tight loops).
|
| 503 |
+
If > 0, will skip display of specified number of iterations.
|
| 504 |
+
Tweak this and ``mininterval`` to get very efficient loops.
|
| 505 |
+
If your progress is erratic with both fast and slow iterations
|
| 506 |
+
(network, skipping items, etc) you should set miniters=1.
|
| 507 |
+
* ascii : bool or str, optional
|
| 508 |
+
If unspecified or False, use unicode (smooth blocks) to fill
|
| 509 |
+
the meter. The fallback is to use ASCII characters " 123456789#".
|
| 510 |
+
* disable : bool, optional
|
| 511 |
+
Whether to disable the entire progress bar wrapper
|
| 512 |
+
[default: False]. If set to None, disable on non-TTY.
|
| 513 |
+
* unit : str, optional
|
| 514 |
+
String that will be used to define the unit of each iteration
|
| 515 |
+
[default: it].
|
| 516 |
+
* unit_scale : bool or int or float, optional
|
| 517 |
+
If 1 or True, the number of iterations will be reduced/scaled
|
| 518 |
+
automatically and a metric prefix following the
|
| 519 |
+
International System of Units standard will be added
|
| 520 |
+
(kilo, mega, etc.) [default: False]. If any other non-zero
|
| 521 |
+
number, will scale ``total`` and ``n``.
|
| 522 |
+
* dynamic_ncols : bool, optional
|
| 523 |
+
If set, constantly alters ``ncols`` and ``nrows`` to the
|
| 524 |
+
environment (allowing for window resizes) [default: False].
|
| 525 |
+
* smoothing : float, optional
|
| 526 |
+
Exponential moving average smoothing factor for speed estimates
|
| 527 |
+
(ignored in GUI mode). Ranges from 0 (average speed) to 1
|
| 528 |
+
(current/instantaneous speed) [default: 0.3].
|
| 529 |
+
* bar_format : str, optional
|
| 530 |
+
Specify a custom bar string formatting. May impact performance.
|
| 531 |
+
[default: '{l_bar}{bar}{r_bar}'], where
|
| 532 |
+
l_bar='{desc}: {percentage:3.0f}%|' and
|
| 533 |
+
r_bar='| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, '
|
| 534 |
+
'{rate_fmt}{postfix}]'
|
| 535 |
+
Possible vars: l_bar, bar, r_bar, n, n_fmt, total, total_fmt,
|
| 536 |
+
percentage, elapsed, elapsed_s, ncols, nrows, desc, unit,
|
| 537 |
+
rate, rate_fmt, rate_noinv, rate_noinv_fmt,
|
| 538 |
+
rate_inv, rate_inv_fmt, postfix, unit_divisor,
|
| 539 |
+
remaining, remaining_s, eta.
|
| 540 |
+
Note that a trailing ": " is automatically removed after {desc}
|
| 541 |
+
if the latter is empty.
|
| 542 |
+
* initial : int or float, optional
|
| 543 |
+
The initial counter value. Useful when restarting a progress
|
| 544 |
+
bar [default: 0]. If using float, consider specifying ``{n:.3f}``
|
| 545 |
+
or similar in ``bar_format``, or specifying ``unit_scale``.
|
| 546 |
+
* position : int, optional
|
| 547 |
+
Specify the line offset to print this bar (starting from 0)
|
| 548 |
+
Automatic if unspecified.
|
| 549 |
+
Useful to manage multiple bars at once (eg, from threads).
|
| 550 |
+
* postfix : dict or ``*``, optional
|
| 551 |
+
Specify additional stats to display at the end of the bar.
|
| 552 |
+
Calls ``set_postfix(**postfix)`` if possible (dict).
|
| 553 |
+
* unit_divisor : float, optional
|
| 554 |
+
[default: 1000], ignored unless ``unit_scale`` is True.
|
| 555 |
+
* write_bytes : bool, optional
|
| 556 |
+
Whether to write bytes. If (default: False) will write unicode.
|
| 557 |
+
* lock_args : tuple, optional
|
| 558 |
+
Passed to ``refresh`` for intermediate output
|
| 559 |
+
(initialisation, iterating, and updating).
|
| 560 |
+
* nrows : int, optional
|
| 561 |
+
The screen height. If specified, hides nested bars outside this
|
| 562 |
+
bound. If unspecified, attempts to use environment height.
|
| 563 |
+
The fallback is 20.
|
| 564 |
+
* colour : str, optional
|
| 565 |
+
Bar colour (e.g. 'green', '#00ff00').
|
| 566 |
+
* delay : float, optional
|
| 567 |
+
Don't display until [default: 0] seconds have elapsed.
|
| 568 |
+
|
| 569 |
+
Extra CLI Options
|
| 570 |
+
~~~~~~~~~~~~~~~~~
|
| 571 |
+
|
| 572 |
+
* delim : chr, optional
|
| 573 |
+
Delimiting character [default: '\n']. Use '\0' for null.
|
| 574 |
+
N.B.: on Windows systems, Python converts '\n' to '\r\n'.
|
| 575 |
+
* buf_size : int, optional
|
| 576 |
+
String buffer size in bytes [default: 256]
|
| 577 |
+
used when ``delim`` is specified.
|
| 578 |
+
* bytes : bool, optional
|
| 579 |
+
If true, will count bytes, ignore ``delim``, and default
|
| 580 |
+
``unit_scale`` to True, ``unit_divisor`` to 1024, and ``unit`` to 'B'.
|
| 581 |
+
* tee : bool, optional
|
| 582 |
+
If true, passes ``stdin`` to both ``stderr`` and ``stdout``.
|
| 583 |
+
* update : bool, optional
|
| 584 |
+
If true, will treat input as newly elapsed iterations,
|
| 585 |
+
i.e. numbers to pass to ``update()``. Note that this is slow
|
| 586 |
+
(~2e5 it/s) since every input must be decoded as a number.
|
| 587 |
+
* update_to : bool, optional
|
| 588 |
+
If true, will treat input as total elapsed iterations,
|
| 589 |
+
i.e. numbers to assign to ``self.n``. Note that this is slow
|
| 590 |
+
(~2e5 it/s) since every input must be decoded as a number.
|
| 591 |
+
* null : bool, optional
|
| 592 |
+
If true, will discard input (no stdout).
|
| 593 |
+
* manpath : str, optional
|
| 594 |
+
Directory in which to install tqdm man pages.
|
| 595 |
+
* comppath : str, optional
|
| 596 |
+
Directory in which to place tqdm completion.
|
| 597 |
+
* log : str, optional
|
| 598 |
+
CRITICAL|FATAL|ERROR|WARN(ING)|[default: 'INFO']|DEBUG|NOTSET.
|
| 599 |
+
|
| 600 |
+
Returns
|
| 601 |
+
~~~~~~~
|
| 602 |
+
|
| 603 |
+
* out : decorated iterator.
|
| 604 |
+
|
| 605 |
+
.. code:: python
|
| 606 |
+
|
| 607 |
+
class tqdm():
|
| 608 |
+
def update(self, n=1):
|
| 609 |
+
"""
|
| 610 |
+
Manually update the progress bar, useful for streams
|
| 611 |
+
such as reading files.
|
| 612 |
+
E.g.:
|
| 613 |
+
>>> t = tqdm(total=filesize) # Initialise
|
| 614 |
+
>>> for current_buffer in stream:
|
| 615 |
+
... ...
|
| 616 |
+
... t.update(len(current_buffer))
|
| 617 |
+
>>> t.close()
|
| 618 |
+
The last line is highly recommended, but possibly not necessary if
|
| 619 |
+
`t.update()` will be called in such a way that `filesize` will be
|
| 620 |
+
exactly reached and printed.
|
| 621 |
+
|
| 622 |
+
Parameters
|
| 623 |
+
----------
|
| 624 |
+
n : int or float, optional
|
| 625 |
+
Increment to add to the internal counter of iterations
|
| 626 |
+
[default: 1]. If using float, consider specifying `{n:.3f}`
|
| 627 |
+
or similar in `bar_format`, or specifying `unit_scale`.
|
| 628 |
+
|
| 629 |
+
Returns
|
| 630 |
+
-------
|
| 631 |
+
out : bool or None
|
| 632 |
+
True if a `display()` was triggered.
|
| 633 |
+
"""
|
| 634 |
+
|
| 635 |
+
def close(self):
|
| 636 |
+
"""Cleanup and (if leave=False) close the progress bar."""
|
| 637 |
+
|
| 638 |
+
def clear(self, nomove=False):
|
| 639 |
+
"""Clear current bar display."""
|
| 640 |
+
|
| 641 |
+
def refresh(self):
|
| 642 |
+
"""
|
| 643 |
+
Force refresh the display of this bar.
|
| 644 |
+
|
| 645 |
+
Parameters
|
| 646 |
+
----------
|
| 647 |
+
nolock : bool, optional
|
| 648 |
+
If `True`, does not lock.
|
| 649 |
+
If [default: `False`]: calls `acquire()` on internal lock.
|
| 650 |
+
lock_args : tuple, optional
|
| 651 |
+
Passed to internal lock's `acquire()`.
|
| 652 |
+
If specified, will only `display()` if `acquire()` returns `True`.
|
| 653 |
+
"""
|
| 654 |
+
|
| 655 |
+
def unpause(self):
|
| 656 |
+
"""Restart tqdm timer from last print time."""
|
| 657 |
+
|
| 658 |
+
def reset(self, total=None):
|
| 659 |
+
"""
|
| 660 |
+
Resets to 0 iterations for repeated use.
|
| 661 |
+
|
| 662 |
+
Consider combining with `leave=True`.
|
| 663 |
+
|
| 664 |
+
Parameters
|
| 665 |
+
----------
|
| 666 |
+
total : int or float, optional. Total to use for the new bar.
|
| 667 |
+
"""
|
| 668 |
+
|
| 669 |
+
def set_description(self, desc=None, refresh=True):
|
| 670 |
+
"""
|
| 671 |
+
Set/modify description of the progress bar.
|
| 672 |
+
|
| 673 |
+
Parameters
|
| 674 |
+
----------
|
| 675 |
+
desc : str, optional
|
| 676 |
+
refresh : bool, optional
|
| 677 |
+
Forces refresh [default: True].
|
| 678 |
+
"""
|
| 679 |
+
|
| 680 |
+
def set_postfix(self, ordered_dict=None, refresh=True, **tqdm_kwargs):
|
| 681 |
+
"""
|
| 682 |
+
Set/modify postfix (additional stats)
|
| 683 |
+
with automatic formatting based on datatype.
|
| 684 |
+
|
| 685 |
+
Parameters
|
| 686 |
+
----------
|
| 687 |
+
ordered_dict : dict or OrderedDict, optional
|
| 688 |
+
refresh : bool, optional
|
| 689 |
+
Forces refresh [default: True].
|
| 690 |
+
kwargs : dict, optional
|
| 691 |
+
"""
|
| 692 |
+
|
| 693 |
+
@classmethod
|
| 694 |
+
def write(cls, s, file=sys.stdout, end="\n"):
|
| 695 |
+
"""Print a message via tqdm (without overlap with bars)."""
|
| 696 |
+
|
| 697 |
+
@property
|
| 698 |
+
def format_dict(self):
|
| 699 |
+
"""Public API for read-only member access."""
|
| 700 |
+
|
| 701 |
+
def display(self, msg=None, pos=None):
|
| 702 |
+
"""
|
| 703 |
+
Use `self.sp` to display `msg` in the specified `pos`.
|
| 704 |
+
|
| 705 |
+
Consider overloading this function when inheriting to use e.g.:
|
| 706 |
+
`self.some_frontend(**self.format_dict)` instead of `self.sp`.
|
| 707 |
+
|
| 708 |
+
Parameters
|
| 709 |
+
----------
|
| 710 |
+
msg : str, optional. What to display (default: `repr(self)`).
|
| 711 |
+
pos : int, optional. Position to `moveto`
|
| 712 |
+
(default: `abs(self.pos)`).
|
| 713 |
+
"""
|
| 714 |
+
|
| 715 |
+
@classmethod
|
| 716 |
+
@contextmanager
|
| 717 |
+
def wrapattr(cls, stream, method, total=None, bytes=True, **tqdm_kwargs):
|
| 718 |
+
"""
|
| 719 |
+
stream : file-like object.
|
| 720 |
+
method : str, "read" or "write". The result of `read()` and
|
| 721 |
+
the first argument of `write()` should have a `len()`.
|
| 722 |
+
|
| 723 |
+
>>> with tqdm.wrapattr(file_obj, "read", total=file_obj.size) as fobj:
|
| 724 |
+
... while True:
|
| 725 |
+
... chunk = fobj.read(chunk_size)
|
| 726 |
+
... if not chunk:
|
| 727 |
+
... break
|
| 728 |
+
"""
|
| 729 |
+
|
| 730 |
+
@classmethod
|
| 731 |
+
def pandas(cls, *targs, **tqdm_kwargs):
|
| 732 |
+
"""Registers the current `tqdm` class with `pandas`."""
|
| 733 |
+
|
| 734 |
+
def trange(*args, **tqdm_kwargs):
|
| 735 |
+
"""Shortcut for `tqdm(range(*args), **tqdm_kwargs)`."""
|
| 736 |
+
|
| 737 |
+
Convenience Functions
|
| 738 |
+
~~~~~~~~~~~~~~~~~~~~~
|
| 739 |
+
|
| 740 |
+
.. code:: python
|
| 741 |
+
|
| 742 |
+
def tqdm.contrib.tenumerate(iterable, start=0, total=None,
|
| 743 |
+
tqdm_class=tqdm.auto.tqdm, **tqdm_kwargs):
|
| 744 |
+
"""Equivalent of `numpy.ndenumerate` or builtin `enumerate`."""
|
| 745 |
+
|
| 746 |
+
def tqdm.contrib.tzip(iter1, *iter2plus, **tqdm_kwargs):
|
| 747 |
+
"""Equivalent of builtin `zip`."""
|
| 748 |
+
|
| 749 |
+
def tqdm.contrib.tmap(function, *sequences, **tqdm_kwargs):
|
| 750 |
+
"""Equivalent of builtin `map`."""
|
| 751 |
+
|
| 752 |
+
Submodules
|
| 753 |
+
~~~~~~~~~~
|
| 754 |
+
|
| 755 |
+
.. code:: python
|
| 756 |
+
|
| 757 |
+
class tqdm.notebook.tqdm(tqdm.tqdm):
|
| 758 |
+
"""IPython/Jupyter Notebook widget."""
|
| 759 |
+
|
| 760 |
+
class tqdm.auto.tqdm(tqdm.tqdm):
|
| 761 |
+
"""Automatically chooses between `tqdm.notebook` and `tqdm.tqdm`."""
|
| 762 |
+
|
| 763 |
+
class tqdm.asyncio.tqdm(tqdm.tqdm):
|
| 764 |
+
"""Asynchronous version."""
|
| 765 |
+
@classmethod
|
| 766 |
+
def as_completed(cls, fs, *, loop=None, timeout=None, total=None,
|
| 767 |
+
**tqdm_kwargs):
|
| 768 |
+
"""Wrapper for `asyncio.as_completed`."""
|
| 769 |
+
|
| 770 |
+
class tqdm.gui.tqdm(tqdm.tqdm):
|
| 771 |
+
"""Matplotlib GUI version."""
|
| 772 |
+
|
| 773 |
+
class tqdm.tk.tqdm(tqdm.tqdm):
|
| 774 |
+
"""Tkinter GUI version."""
|
| 775 |
+
|
| 776 |
+
class tqdm.rich.tqdm(tqdm.tqdm):
|
| 777 |
+
"""`rich.progress` version."""
|
| 778 |
+
|
| 779 |
+
class tqdm.keras.TqdmCallback(keras.callbacks.Callback):
|
| 780 |
+
"""Keras callback for epoch and batch progress."""
|
| 781 |
+
|
| 782 |
+
class tqdm.dask.TqdmCallback(dask.callbacks.Callback):
|
| 783 |
+
"""Dask callback for task progress."""
|
| 784 |
+
|
| 785 |
+
|
| 786 |
+
``contrib``
|
| 787 |
+
+++++++++++
|
| 788 |
+
|
| 789 |
+
The ``tqdm.contrib`` package also contains experimental modules:
|
| 790 |
+
|
| 791 |
+
- `tqdm.contrib.itertools <https://tqdm.github.io/docs/contrib.itertools/>`_: Thin wrappers around ``itertools``
|
| 792 |
+
- `tqdm.contrib.concurrent <https://tqdm.github.io/docs/contrib.concurrent/>`_: Thin wrappers around ``concurrent.futures``
|
| 793 |
+
- `tqdm.contrib.slack <https://tqdm.github.io/docs/contrib.slack/>`_: Posts to `Slack <https://slack.com>`__ bots
|
| 794 |
+
- `tqdm.contrib.discord <https://tqdm.github.io/docs/contrib.discord/>`_: Posts to `Discord <https://discord.com>`__ bots
|
| 795 |
+
- `tqdm.contrib.telegram <https://tqdm.github.io/docs/contrib.telegram/>`_: Posts to `Telegram <https://telegram.org>`__ bots
|
| 796 |
+
- `tqdm.contrib.bells <https://tqdm.github.io/docs/shortcuts/>`_: Automagically enables all optional features
|
| 797 |
+
|
| 798 |
+
* ``auto``, ``pandas``, ``slack``, ``discord``, ``telegram``
|
| 799 |
+
|
| 800 |
+
.. image:: https://tqdm.github.io/img/screenshot-discord.png
|
| 801 |
+
:alt: Screenshot of `tqdm.contrib.discord` in action
|
| 802 |
+
|
| 803 |
+
Examples and Advanced Usage
|
| 804 |
+
---------------------------
|
| 805 |
+
|
| 806 |
+
- See the `examples <https://github.com/tqdm/tqdm/tree/master/examples>`__
|
| 807 |
+
folder;
|
| 808 |
+
- import the module and run ``help()``;
|
| 809 |
+
- consult the `wiki <https://github.com/tqdm/tqdm/wiki>`__;
|
| 810 |
+
|
| 811 |
+
* this has an
|
| 812 |
+
`excellent article <https://github.com/tqdm/tqdm/wiki/How-to-make-a-great-Progress-Bar>`__
|
| 813 |
+
on how to make a **great** progress bar;
|
| 814 |
+
|
| 815 |
+
- check out the `slides from PyData London <https://tqdm.github.io/PyData2019/slides.html>`__, or
|
| 816 |
+
- run the |binder-demo|.
|
| 817 |
+
|
| 818 |
+
Description and additional stats
|
| 819 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 820 |
+
|
| 821 |
+
Custom information can be displayed and updated dynamically on ``tqdm`` bars
|
| 822 |
+
with the ``desc`` and ``postfix`` arguments:
|
| 823 |
+
|
| 824 |
+
.. code:: python
|
| 825 |
+
|
| 826 |
+
from tqdm import tqdm, trange
|
| 827 |
+
from random import random, randint
|
| 828 |
+
from time import sleep
|
| 829 |
+
|
| 830 |
+
with trange(10) as t:
|
| 831 |
+
for i in t:
|
| 832 |
+
# Description will be displayed on the left
|
| 833 |
+
t.set_description('GEN %i' % i)
|
| 834 |
+
# Postfix will be displayed on the right,
|
| 835 |
+
# formatted automatically based on argument's datatype
|
| 836 |
+
t.set_postfix(loss=random(), gen=randint(1,999), str='h',
|
| 837 |
+
lst=[1, 2])
|
| 838 |
+
sleep(0.1)
|
| 839 |
+
|
| 840 |
+
with tqdm(total=10, bar_format="{postfix[0]} {postfix[1][value]:>8.2g}",
|
| 841 |
+
postfix=["Batch", {"value": 0}]) as t:
|
| 842 |
+
for i in range(10):
|
| 843 |
+
sleep(0.1)
|
| 844 |
+
t.postfix[1]["value"] = i / 2
|
| 845 |
+
t.update()
|
| 846 |
+
|
| 847 |
+
Points to remember when using ``{postfix[...]}`` in the ``bar_format`` string:
|
| 848 |
+
|
| 849 |
+
- ``postfix`` also needs to be passed as an initial argument in a compatible
|
| 850 |
+
format, and
|
| 851 |
+
- ``postfix`` will be auto-converted to a string if it is a ``dict``-like
|
| 852 |
+
object. To prevent this behaviour, insert an extra item into the dictionary
|
| 853 |
+
where the key is not a string.
|
| 854 |
+
|
| 855 |
+
Additional ``bar_format`` parameters may also be defined by overriding
|
| 856 |
+
``format_dict``, and the bar itself may be modified using ``ascii``:
|
| 857 |
+
|
| 858 |
+
.. code:: python
|
| 859 |
+
|
| 860 |
+
from tqdm import tqdm
|
| 861 |
+
class TqdmExtraFormat(tqdm):
|
| 862 |
+
"""Provides a `total_time` format parameter"""
|
| 863 |
+
@property
|
| 864 |
+
def format_dict(self):
|
| 865 |
+
d = super().format_dict
|
| 866 |
+
total_time = d["elapsed"] * (d["total"] or 0) / max(d["n"], 1)
|
| 867 |
+
d.update(total_time=self.format_interval(total_time) + " in total")
|
| 868 |
+
return d
|
| 869 |
+
|
| 870 |
+
for i in TqdmExtraFormat(
|
| 871 |
+
range(9), ascii=" .oO0",
|
| 872 |
+
bar_format="{total_time}: {percentage:.0f}%|{bar}{r_bar}"):
|
| 873 |
+
if i == 4:
|
| 874 |
+
break
|
| 875 |
+
|
| 876 |
+
.. code::
|
| 877 |
+
|
| 878 |
+
00:00 in total: 44%|0000. | 4/9 [00:00<00:00, 962.93it/s]
|
| 879 |
+
|
| 880 |
+
Note that ``{bar}`` also supports a format specifier ``[width][type]``.
|
| 881 |
+
|
| 882 |
+
- ``width``
|
| 883 |
+
|
| 884 |
+
* unspecified (default): automatic to fill ``ncols``
|
| 885 |
+
* ``int >= 0``: fixed width overriding ``ncols`` logic
|
| 886 |
+
* ``int < 0``: subtract from the automatic default
|
| 887 |
+
|
| 888 |
+
- ``type``
|
| 889 |
+
|
| 890 |
+
* ``a``: ascii (``ascii=True`` override)
|
| 891 |
+
* ``u``: unicode (``ascii=False`` override)
|
| 892 |
+
* ``b``: blank (``ascii=" "`` override)
|
| 893 |
+
|
| 894 |
+
This means a fixed bar with right-justified text may be created by using:
|
| 895 |
+
``bar_format="{l_bar}{bar:10}|{bar:-10b}right-justified"``
|
| 896 |
+
|
| 897 |
+
Nested progress bars
|
| 898 |
+
~~~~~~~~~~~~~~~~~~~~
|
| 899 |
+
|
| 900 |
+
``tqdm`` supports nested progress bars. Here's an example:
|
| 901 |
+
|
| 902 |
+
.. code:: python
|
| 903 |
+
|
| 904 |
+
from tqdm.auto import trange
|
| 905 |
+
from time import sleep
|
| 906 |
+
|
| 907 |
+
for i in trange(4, desc='1st loop'):
|
| 908 |
+
for j in trange(5, desc='2nd loop'):
|
| 909 |
+
for k in trange(50, desc='3rd loop', leave=False):
|
| 910 |
+
sleep(0.01)
|
| 911 |
+
|
| 912 |
+
For manual control over positioning (e.g. for multi-processing use),
|
| 913 |
+
you may specify ``position=n`` where ``n=0`` for the outermost bar,
|
| 914 |
+
``n=1`` for the next, and so on.
|
| 915 |
+
However, it's best to check if ``tqdm`` can work without manual ``position``
|
| 916 |
+
first.
|
| 917 |
+
|
| 918 |
+
.. code:: python
|
| 919 |
+
|
| 920 |
+
from time import sleep
|
| 921 |
+
from tqdm import trange, tqdm
|
| 922 |
+
from multiprocessing import Pool, RLock, freeze_support
|
| 923 |
+
|
| 924 |
+
L = list(range(9))
|
| 925 |
+
|
| 926 |
+
def progresser(n):
|
| 927 |
+
interval = 0.001 / (n + 2)
|
| 928 |
+
total = 5000
|
| 929 |
+
text = f"#{n}, est. {interval * total:<04.2}s"
|
| 930 |
+
for _ in trange(total, desc=text, position=n):
|
| 931 |
+
sleep(interval)
|
| 932 |
+
|
| 933 |
+
if __name__ == '__main__':
|
| 934 |
+
freeze_support() # for Windows support
|
| 935 |
+
tqdm.set_lock(RLock()) # for managing output contention
|
| 936 |
+
p = Pool(initializer=tqdm.set_lock, initargs=(tqdm.get_lock(),))
|
| 937 |
+
p.map(progresser, L)
|
| 938 |
+
|
| 939 |
+
Note that in Python 3, ``tqdm.write`` is thread-safe:
|
| 940 |
+
|
| 941 |
+
.. code:: python
|
| 942 |
+
|
| 943 |
+
from time import sleep
|
| 944 |
+
from tqdm import tqdm, trange
|
| 945 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 946 |
+
|
| 947 |
+
L = list(range(9))
|
| 948 |
+
|
| 949 |
+
def progresser(n):
|
| 950 |
+
interval = 0.001 / (n + 2)
|
| 951 |
+
total = 5000
|
| 952 |
+
text = f"#{n}, est. {interval * total:<04.2}s"
|
| 953 |
+
for _ in trange(total, desc=text):
|
| 954 |
+
sleep(interval)
|
| 955 |
+
if n == 6:
|
| 956 |
+
tqdm.write("n == 6 completed.")
|
| 957 |
+
tqdm.write("`tqdm.write()` is thread-safe in py3!")
|
| 958 |
+
|
| 959 |
+
if __name__ == '__main__':
|
| 960 |
+
with ThreadPoolExecutor() as p:
|
| 961 |
+
p.map(progresser, L)
|
| 962 |
+
|
| 963 |
+
Hooks and callbacks
|
| 964 |
+
~~~~~~~~~~~~~~~~~~~
|
| 965 |
+
|
| 966 |
+
``tqdm`` can easily support callbacks/hooks and manual updates.
|
| 967 |
+
Here's an example with ``urllib``:
|
| 968 |
+
|
| 969 |
+
**``urllib.urlretrieve`` documentation**
|
| 970 |
+
|
| 971 |
+
| [...]
|
| 972 |
+
| If present, the hook function will be called once
|
| 973 |
+
| on establishment of the network connection and once after each block read
|
| 974 |
+
| thereafter. The hook will be passed three arguments; a count of blocks
|
| 975 |
+
| transferred so far, a block size in bytes, and the total size of the file.
|
| 976 |
+
| [...]
|
| 977 |
+
|
| 978 |
+
.. code:: python
|
| 979 |
+
|
| 980 |
+
import urllib, os
|
| 981 |
+
from tqdm import tqdm
|
| 982 |
+
urllib = getattr(urllib, 'request', urllib)
|
| 983 |
+
|
| 984 |
+
class TqdmUpTo(tqdm):
|
| 985 |
+
"""Provides `update_to(n)` which uses `tqdm.update(delta_n)`."""
|
| 986 |
+
def update_to(self, b=1, bsize=1, tsize=None):
|
| 987 |
+
"""
|
| 988 |
+
b : int, optional
|
| 989 |
+
Number of blocks transferred so far [default: 1].
|
| 990 |
+
bsize : int, optional
|
| 991 |
+
Size of each block (in tqdm units) [default: 1].
|
| 992 |
+
tsize : int, optional
|
| 993 |
+
Total size (in tqdm units). If [default: None] remains unchanged.
|
| 994 |
+
"""
|
| 995 |
+
if tsize is not None:
|
| 996 |
+
self.total = tsize
|
| 997 |
+
return self.update(b * bsize - self.n) # also sets self.n = b * bsize
|
| 998 |
+
|
| 999 |
+
eg_link = "https://cgi.cdcl.ml/matryoshka.zip"
|
| 1000 |
+
with TqdmUpTo(unit='B', unit_scale=True, unit_divisor=1024, miniters=1,
|
| 1001 |
+
desc=eg_link.split('/')[-1]) as t: # all optional kwargs
|
| 1002 |
+
urllib.urlretrieve(eg_link, filename=os.devnull,
|
| 1003 |
+
reporthook=t.update_to, data=None)
|
| 1004 |
+
t.total = t.n
|
| 1005 |
+
|
| 1006 |
+
Inspired by `twine#242 <https://github.com/pypa/twine/pull/242>`__.
|
| 1007 |
+
Functional alternative in
|
| 1008 |
+
`examples/tqdm_wget.py <https://github.com/tqdm/tqdm/blob/master/examples/tqdm_wget.py>`__.
|
| 1009 |
+
|
| 1010 |
+
It is recommend to use ``miniters=1`` whenever there is potentially
|
| 1011 |
+
large differences in iteration speed (e.g. downloading a file over
|
| 1012 |
+
a patchy connection).
|
| 1013 |
+
|
| 1014 |
+
**Wrapping read/write methods**
|
| 1015 |
+
|
| 1016 |
+
To measure throughput through a file-like object's ``read`` or ``write``
|
| 1017 |
+
methods, use ``CallbackIOWrapper``:
|
| 1018 |
+
|
| 1019 |
+
.. code:: python
|
| 1020 |
+
|
| 1021 |
+
from tqdm.auto import tqdm
|
| 1022 |
+
from tqdm.utils import CallbackIOWrapper
|
| 1023 |
+
|
| 1024 |
+
with tqdm(total=file_obj.size,
|
| 1025 |
+
unit='B', unit_scale=True, unit_divisor=1024) as t:
|
| 1026 |
+
fobj = CallbackIOWrapper(t.update, file_obj, "read")
|
| 1027 |
+
while True:
|
| 1028 |
+
chunk = fobj.read(chunk_size)
|
| 1029 |
+
if not chunk:
|
| 1030 |
+
break
|
| 1031 |
+
t.reset()
|
| 1032 |
+
# ... continue to use `t` for something else
|
| 1033 |
+
|
| 1034 |
+
Alternatively, use the even simpler ``wrapattr`` convenience function,
|
| 1035 |
+
which would condense both the ``urllib`` and ``CallbackIOWrapper`` examples
|
| 1036 |
+
down to:
|
| 1037 |
+
|
| 1038 |
+
.. code:: python
|
| 1039 |
+
|
| 1040 |
+
import urllib, os
|
| 1041 |
+
from tqdm import tqdm
|
| 1042 |
+
|
| 1043 |
+
eg_link = "https://cgi.cdcl.ml/matryoshka.zip"
|
| 1044 |
+
response = getattr(urllib, 'request', urllib).urlopen(eg_link)
|
| 1045 |
+
with tqdm.wrapattr(open(os.devnull, "wb"), "write",
|
| 1046 |
+
miniters=1, desc=eg_link.split('/')[-1],
|
| 1047 |
+
total=getattr(response, 'length', None)) as fout:
|
| 1048 |
+
for chunk in response:
|
| 1049 |
+
fout.write(chunk)
|
| 1050 |
+
|
| 1051 |
+
The ``requests`` equivalent is nearly identical:
|
| 1052 |
+
|
| 1053 |
+
.. code:: python
|
| 1054 |
+
|
| 1055 |
+
import requests, os
|
| 1056 |
+
from tqdm import tqdm
|
| 1057 |
+
|
| 1058 |
+
eg_link = "https://cgi.cdcl.ml/matryoshka.zip"
|
| 1059 |
+
response = requests.get(eg_link, stream=True)
|
| 1060 |
+
with tqdm.wrapattr(open(os.devnull, "wb"), "write",
|
| 1061 |
+
miniters=1, desc=eg_link.split('/')[-1],
|
| 1062 |
+
total=int(response.headers.get('content-length', 0))) as fout:
|
| 1063 |
+
for chunk in response.iter_content(chunk_size=4096):
|
| 1064 |
+
fout.write(chunk)
|
| 1065 |
+
|
| 1066 |
+
**Custom callback**
|
| 1067 |
+
|
| 1068 |
+
``tqdm`` is known for intelligently skipping unnecessary displays. To make a
|
| 1069 |
+
custom callback take advantage of this, simply use the return value of
|
| 1070 |
+
``update()``. This is set to ``True`` if a ``display()`` was triggered.
|
| 1071 |
+
|
| 1072 |
+
.. code:: python
|
| 1073 |
+
|
| 1074 |
+
from tqdm.auto import tqdm as std_tqdm
|
| 1075 |
+
|
| 1076 |
+
def external_callback(*args, **kwargs):
|
| 1077 |
+
...
|
| 1078 |
+
|
| 1079 |
+
class TqdmExt(std_tqdm):
|
| 1080 |
+
def update(self, n=1):
|
| 1081 |
+
displayed = super().update(n)
|
| 1082 |
+
if displayed:
|
| 1083 |
+
external_callback(**self.format_dict)
|
| 1084 |
+
return displayed
|
| 1085 |
+
|
| 1086 |
+
``asyncio``
|
| 1087 |
+
~~~~~~~~~~~
|
| 1088 |
+
|
| 1089 |
+
Note that ``break`` isn't currently caught by asynchronous iterators.
|
| 1090 |
+
This means that ``tqdm`` cannot clean up after itself in this case:
|
| 1091 |
+
|
| 1092 |
+
.. code:: python
|
| 1093 |
+
|
| 1094 |
+
from tqdm.asyncio import tqdm
|
| 1095 |
+
|
| 1096 |
+
async for i in tqdm(range(9)):
|
| 1097 |
+
if i == 2:
|
| 1098 |
+
break
|
| 1099 |
+
|
| 1100 |
+
Instead, either call ``pbar.close()`` manually or use the context manager syntax:
|
| 1101 |
+
|
| 1102 |
+
.. code:: python
|
| 1103 |
+
|
| 1104 |
+
from tqdm.asyncio import tqdm
|
| 1105 |
+
|
| 1106 |
+
with tqdm(range(9)) as pbar:
|
| 1107 |
+
async for i in pbar:
|
| 1108 |
+
if i == 2:
|
| 1109 |
+
break
|
| 1110 |
+
|
| 1111 |
+
Pandas Integration
|
| 1112 |
+
~~~~~~~~~~~~~~~~~~
|
| 1113 |
+
|
| 1114 |
+
Due to popular demand we've added support for ``pandas`` -- here's an example
|
| 1115 |
+
for ``DataFrame.progress_apply`` and ``DataFrameGroupBy.progress_apply``:
|
| 1116 |
+
|
| 1117 |
+
.. code:: python
|
| 1118 |
+
|
| 1119 |
+
import pandas as pd
|
| 1120 |
+
import numpy as np
|
| 1121 |
+
from tqdm import tqdm
|
| 1122 |
+
|
| 1123 |
+
df = pd.DataFrame(np.random.randint(0, 100, (100000, 6)))
|
| 1124 |
+
|
| 1125 |
+
# Register `pandas.progress_apply` and `pandas.Series.map_apply` with `tqdm`
|
| 1126 |
+
# (can use `tqdm.gui.tqdm`, `tqdm.notebook.tqdm`, optional kwargs, etc.)
|
| 1127 |
+
tqdm.pandas(desc="my bar!")
|
| 1128 |
+
|
| 1129 |
+
# Now you can use `progress_apply` instead of `apply`
|
| 1130 |
+
# and `progress_map` instead of `map`
|
| 1131 |
+
df.progress_apply(lambda x: x**2)
|
| 1132 |
+
# can also groupby:
|
| 1133 |
+
# df.groupby(0).progress_apply(lambda x: x**2)
|
| 1134 |
+
|
| 1135 |
+
In case you're interested in how this works (and how to modify it for your
|
| 1136 |
+
own callbacks), see the
|
| 1137 |
+
`examples <https://github.com/tqdm/tqdm/tree/master/examples>`__
|
| 1138 |
+
folder or import the module and run ``help()``.
|
| 1139 |
+
|
| 1140 |
+
Keras Integration
|
| 1141 |
+
~~~~~~~~~~~~~~~~~
|
| 1142 |
+
|
| 1143 |
+
A ``keras`` callback is also available:
|
| 1144 |
+
|
| 1145 |
+
.. code:: python
|
| 1146 |
+
|
| 1147 |
+
from tqdm.keras import TqdmCallback
|
| 1148 |
+
|
| 1149 |
+
...
|
| 1150 |
+
|
| 1151 |
+
model.fit(..., verbose=0, callbacks=[TqdmCallback()])
|
| 1152 |
+
|
| 1153 |
+
Dask Integration
|
| 1154 |
+
~~~~~~~~~~~~~~~~
|
| 1155 |
+
|
| 1156 |
+
A ``dask`` callback is also available:
|
| 1157 |
+
|
| 1158 |
+
.. code:: python
|
| 1159 |
+
|
| 1160 |
+
from tqdm.dask import TqdmCallback
|
| 1161 |
+
|
| 1162 |
+
with TqdmCallback(desc="compute"):
|
| 1163 |
+
...
|
| 1164 |
+
arr.compute()
|
| 1165 |
+
|
| 1166 |
+
# or use callback globally
|
| 1167 |
+
cb = TqdmCallback(desc="global")
|
| 1168 |
+
cb.register()
|
| 1169 |
+
arr.compute()
|
| 1170 |
+
|
| 1171 |
+
IPython/Jupyter Integration
|
| 1172 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 1173 |
+
|
| 1174 |
+
IPython/Jupyter is supported via the ``tqdm.notebook`` submodule:
|
| 1175 |
+
|
| 1176 |
+
.. code:: python
|
| 1177 |
+
|
| 1178 |
+
from tqdm.notebook import trange, tqdm
|
| 1179 |
+
from time import sleep
|
| 1180 |
+
|
| 1181 |
+
for i in trange(3, desc='1st loop'):
|
| 1182 |
+
for j in tqdm(range(100), desc='2nd loop'):
|
| 1183 |
+
sleep(0.01)
|
| 1184 |
+
|
| 1185 |
+
In addition to ``tqdm`` features, the submodule provides a native Jupyter
|
| 1186 |
+
widget (compatible with IPython v1-v4 and Jupyter), fully working nested bars
|
| 1187 |
+
and colour hints (blue: normal, green: completed, red: error/interrupt,
|
| 1188 |
+
light blue: no ETA); as demonstrated below.
|
| 1189 |
+
|
| 1190 |
+
|Screenshot-Jupyter1|
|
| 1191 |
+
|Screenshot-Jupyter2|
|
| 1192 |
+
|Screenshot-Jupyter3|
|
| 1193 |
+
|
| 1194 |
+
The ``notebook`` version supports percentage or pixels for overall width
|
| 1195 |
+
(e.g.: ``ncols='100%'`` or ``ncols='480px'``).
|
| 1196 |
+
|
| 1197 |
+
It is also possible to let ``tqdm`` automatically choose between
|
| 1198 |
+
console or notebook versions by using the ``autonotebook`` submodule:
|
| 1199 |
+
|
| 1200 |
+
.. code:: python
|
| 1201 |
+
|
| 1202 |
+
from tqdm.autonotebook import tqdm
|
| 1203 |
+
tqdm.pandas()
|
| 1204 |
+
|
| 1205 |
+
Note that this will issue a ``TqdmExperimentalWarning`` if run in a notebook
|
| 1206 |
+
since it is not meant to be possible to distinguish between ``jupyter notebook``
|
| 1207 |
+
and ``jupyter console``. Use ``auto`` instead of ``autonotebook`` to suppress
|
| 1208 |
+
this warning.
|
| 1209 |
+
|
| 1210 |
+
Note that notebooks will display the bar in the cell where it was created.
|
| 1211 |
+
This may be a different cell from the one where it is used.
|
| 1212 |
+
If this is not desired, either
|
| 1213 |
+
|
| 1214 |
+
- delay the creation of the bar to the cell where it must be displayed, or
|
| 1215 |
+
- create the bar with ``display=False``, and in a later cell call
|
| 1216 |
+
``display(bar.container)``:
|
| 1217 |
+
|
| 1218 |
+
.. code:: python
|
| 1219 |
+
|
| 1220 |
+
from tqdm.notebook import tqdm
|
| 1221 |
+
pbar = tqdm(..., display=False)
|
| 1222 |
+
|
| 1223 |
+
.. code:: python
|
| 1224 |
+
|
| 1225 |
+
# different cell
|
| 1226 |
+
display(pbar.container)
|
| 1227 |
+
|
| 1228 |
+
The ``keras`` callback has a ``display()`` method which can be used likewise:
|
| 1229 |
+
|
| 1230 |
+
.. code:: python
|
| 1231 |
+
|
| 1232 |
+
from tqdm.keras import TqdmCallback
|
| 1233 |
+
cbk = TqdmCallback(display=False)
|
| 1234 |
+
|
| 1235 |
+
.. code:: python
|
| 1236 |
+
|
| 1237 |
+
# different cell
|
| 1238 |
+
cbk.display()
|
| 1239 |
+
model.fit(..., verbose=0, callbacks=[cbk])
|
| 1240 |
+
|
| 1241 |
+
Another possibility is to have a single bar (near the top of the notebook)
|
| 1242 |
+
which is constantly re-used (using ``reset()`` rather than ``close()``).
|
| 1243 |
+
For this reason, the notebook version (unlike the CLI version) does not
|
| 1244 |
+
automatically call ``close()`` upon ``Exception``.
|
| 1245 |
+
|
| 1246 |
+
.. code:: python
|
| 1247 |
+
|
| 1248 |
+
from tqdm.notebook import tqdm
|
| 1249 |
+
pbar = tqdm()
|
| 1250 |
+
|
| 1251 |
+
.. code:: python
|
| 1252 |
+
|
| 1253 |
+
# different cell
|
| 1254 |
+
iterable = range(100)
|
| 1255 |
+
pbar.reset(total=len(iterable)) # initialise with new `total`
|
| 1256 |
+
for i in iterable:
|
| 1257 |
+
pbar.update()
|
| 1258 |
+
pbar.refresh() # force print final status but don't `close()`
|
| 1259 |
+
|
| 1260 |
+
Custom Integration
|
| 1261 |
+
~~~~~~~~~~~~~~~~~~
|
| 1262 |
+
|
| 1263 |
+
To change the default arguments (such as making ``dynamic_ncols=True``),
|
| 1264 |
+
simply use built-in Python magic:
|
| 1265 |
+
|
| 1266 |
+
.. code:: python
|
| 1267 |
+
|
| 1268 |
+
from functools import partial
|
| 1269 |
+
from tqdm import tqdm as std_tqdm
|
| 1270 |
+
tqdm = partial(std_tqdm, dynamic_ncols=True)
|
| 1271 |
+
|
| 1272 |
+
For further customisation,
|
| 1273 |
+
``tqdm`` may be inherited from to create custom callbacks (as with the
|
| 1274 |
+
``TqdmUpTo`` example `above <#hooks-and-callbacks>`__) or for custom frontends
|
| 1275 |
+
(e.g. GUIs such as notebook or plotting packages). In the latter case:
|
| 1276 |
+
|
| 1277 |
+
1. ``def __init__()`` to call ``super().__init__(..., gui=True)`` to disable
|
| 1278 |
+
terminal ``status_printer`` creation.
|
| 1279 |
+
2. Redefine: ``close()``, ``clear()``, ``display()``.
|
| 1280 |
+
|
| 1281 |
+
Consider overloading ``display()`` to use e.g.
|
| 1282 |
+
``self.frontend(**self.format_dict)`` instead of ``self.sp(repr(self))``.
|
| 1283 |
+
|
| 1284 |
+
Some submodule examples of inheritance:
|
| 1285 |
+
|
| 1286 |
+
- `tqdm/notebook.py <https://github.com/tqdm/tqdm/blob/master/tqdm/notebook.py>`__
|
| 1287 |
+
- `tqdm/gui.py <https://github.com/tqdm/tqdm/blob/master/tqdm/gui.py>`__
|
| 1288 |
+
- `tqdm/tk.py <https://github.com/tqdm/tqdm/blob/master/tqdm/tk.py>`__
|
| 1289 |
+
- `tqdm/contrib/slack.py <https://github.com/tqdm/tqdm/blob/master/tqdm/contrib/slack.py>`__
|
| 1290 |
+
- `tqdm/contrib/discord.py <https://github.com/tqdm/tqdm/blob/master/tqdm/contrib/discord.py>`__
|
| 1291 |
+
- `tqdm/contrib/telegram.py <https://github.com/tqdm/tqdm/blob/master/tqdm/contrib/telegram.py>`__
|
| 1292 |
+
|
| 1293 |
+
Dynamic Monitor/Meter
|
| 1294 |
+
~~~~~~~~~~~~~~~~~~~~~
|
| 1295 |
+
|
| 1296 |
+
You can use a ``tqdm`` as a meter which is not monotonically increasing.
|
| 1297 |
+
This could be because ``n`` decreases (e.g. a CPU usage monitor) or ``total``
|
| 1298 |
+
changes.
|
| 1299 |
+
|
| 1300 |
+
One example would be recursively searching for files. The ``total`` is the
|
| 1301 |
+
number of objects found so far, while ``n`` is the number of those objects which
|
| 1302 |
+
are files (rather than folders):
|
| 1303 |
+
|
| 1304 |
+
.. code:: python
|
| 1305 |
+
|
| 1306 |
+
from tqdm import tqdm
|
| 1307 |
+
import os.path
|
| 1308 |
+
|
| 1309 |
+
def find_files_recursively(path, show_progress=True):
|
| 1310 |
+
files = []
|
| 1311 |
+
# total=1 assumes `path` is a file
|
| 1312 |
+
t = tqdm(total=1, unit="file", disable=not show_progress)
|
| 1313 |
+
if not os.path.exists(path):
|
| 1314 |
+
raise IOError("Cannot find:" + path)
|
| 1315 |
+
|
| 1316 |
+
def append_found_file(f):
|
| 1317 |
+
files.append(f)
|
| 1318 |
+
t.update()
|
| 1319 |
+
|
| 1320 |
+
def list_found_dir(path):
|
| 1321 |
+
"""returns os.listdir(path) assuming os.path.isdir(path)"""
|
| 1322 |
+
listing = os.listdir(path)
|
| 1323 |
+
# subtract 1 since a "file" we found was actually this directory
|
| 1324 |
+
t.total += len(listing) - 1
|
| 1325 |
+
# fancy way to give info without forcing a refresh
|
| 1326 |
+
t.set_postfix(dir=path[-10:], refresh=False)
|
| 1327 |
+
t.update(0) # may trigger a refresh
|
| 1328 |
+
return listing
|
| 1329 |
+
|
| 1330 |
+
def recursively_search(path):
|
| 1331 |
+
if os.path.isdir(path):
|
| 1332 |
+
for f in list_found_dir(path):
|
| 1333 |
+
recursively_search(os.path.join(path, f))
|
| 1334 |
+
else:
|
| 1335 |
+
append_found_file(path)
|
| 1336 |
+
|
| 1337 |
+
recursively_search(path)
|
| 1338 |
+
t.set_postfix(dir=path)
|
| 1339 |
+
t.close()
|
| 1340 |
+
return files
|
| 1341 |
+
|
| 1342 |
+
Using ``update(0)`` is a handy way to let ``tqdm`` decide when to trigger a
|
| 1343 |
+
display refresh to avoid console spamming.
|
| 1344 |
+
|
| 1345 |
+
Writing messages
|
| 1346 |
+
~~~~~~~~~~~~~~~~
|
| 1347 |
+
|
| 1348 |
+
This is a work in progress (see
|
| 1349 |
+
`#737 <https://github.com/tqdm/tqdm/issues/737>`__).
|
| 1350 |
+
|
| 1351 |
+
Since ``tqdm`` uses a simple printing mechanism to display progress bars,
|
| 1352 |
+
you should not write any message in the terminal using ``print()`` while
|
| 1353 |
+
a progress bar is open.
|
| 1354 |
+
|
| 1355 |
+
To write messages in the terminal without any collision with ``tqdm`` bar
|
| 1356 |
+
display, a ``.write()`` method is provided:
|
| 1357 |
+
|
| 1358 |
+
.. code:: python
|
| 1359 |
+
|
| 1360 |
+
from tqdm.auto import tqdm, trange
|
| 1361 |
+
from time import sleep
|
| 1362 |
+
|
| 1363 |
+
bar = trange(10)
|
| 1364 |
+
for i in bar:
|
| 1365 |
+
# Print using tqdm class method .write()
|
| 1366 |
+
sleep(0.1)
|
| 1367 |
+
if not (i % 3):
|
| 1368 |
+
tqdm.write("Done task %i" % i)
|
| 1369 |
+
# Can also use bar.write()
|
| 1370 |
+
|
| 1371 |
+
By default, this will print to standard output ``sys.stdout``. but you can
|
| 1372 |
+
specify any file-like object using the ``file`` argument. For example, this
|
| 1373 |
+
can be used to redirect the messages writing to a log file or class.
|
| 1374 |
+
|
| 1375 |
+
Redirecting writing
|
| 1376 |
+
~~~~~~~~~~~~~~~~~~~
|
| 1377 |
+
|
| 1378 |
+
If using a library that can print messages to the console, editing the library
|
| 1379 |
+
by replacing ``print()`` with ``tqdm.write()`` may not be desirable.
|
| 1380 |
+
In that case, redirecting ``sys.stdout`` to ``tqdm.write()`` is an option.
|
| 1381 |
+
|
| 1382 |
+
To redirect ``sys.stdout``, create a file-like class that will write
|
| 1383 |
+
any input string to ``tqdm.write()``, and supply the arguments
|
| 1384 |
+
``file=sys.stdout, dynamic_ncols=True``.
|
| 1385 |
+
|
| 1386 |
+
A reusable canonical example is given below:
|
| 1387 |
+
|
| 1388 |
+
.. code:: python
|
| 1389 |
+
|
| 1390 |
+
from time import sleep
|
| 1391 |
+
import contextlib
|
| 1392 |
+
import sys
|
| 1393 |
+
from tqdm import tqdm
|
| 1394 |
+
from tqdm.contrib import DummyTqdmFile
|
| 1395 |
+
|
| 1396 |
+
|
| 1397 |
+
@contextlib.contextmanager
|
| 1398 |
+
def std_out_err_redirect_tqdm():
|
| 1399 |
+
orig_out_err = sys.stdout, sys.stderr
|
| 1400 |
+
try:
|
| 1401 |
+
sys.stdout, sys.stderr = map(DummyTqdmFile, orig_out_err)
|
| 1402 |
+
yield orig_out_err[0]
|
| 1403 |
+
# Relay exceptions
|
| 1404 |
+
except Exception as exc:
|
| 1405 |
+
raise exc
|
| 1406 |
+
# Always restore sys.stdout/err if necessary
|
| 1407 |
+
finally:
|
| 1408 |
+
sys.stdout, sys.stderr = orig_out_err
|
| 1409 |
+
|
| 1410 |
+
def some_fun(i):
|
| 1411 |
+
print("Fee, fi, fo,".split()[i])
|
| 1412 |
+
|
| 1413 |
+
# Redirect stdout to tqdm.write() (don't forget the `as save_stdout`)
|
| 1414 |
+
with std_out_err_redirect_tqdm() as orig_stdout:
|
| 1415 |
+
# tqdm needs the original stdout
|
| 1416 |
+
# and dynamic_ncols=True to autodetect console width
|
| 1417 |
+
for i in tqdm(range(3), file=orig_stdout, dynamic_ncols=True):
|
| 1418 |
+
sleep(.5)
|
| 1419 |
+
some_fun(i)
|
| 1420 |
+
|
| 1421 |
+
# After the `with`, printing is restored
|
| 1422 |
+
print("Done!")
|
| 1423 |
+
|
| 1424 |
+
Redirecting ``logging``
|
| 1425 |
+
~~~~~~~~~~~~~~~~~~~~~~~
|
| 1426 |
+
|
| 1427 |
+
Similar to ``sys.stdout``/``sys.stderr`` as detailed above, console ``logging``
|
| 1428 |
+
may also be redirected to ``tqdm.write()``.
|
| 1429 |
+
|
| 1430 |
+
Warning: if also redirecting ``sys.stdout``/``sys.stderr``, make sure to
|
| 1431 |
+
redirect ``logging`` first if needed.
|
| 1432 |
+
|
| 1433 |
+
Helper methods are available in ``tqdm.contrib.logging``. For example:
|
| 1434 |
+
|
| 1435 |
+
.. code:: python
|
| 1436 |
+
|
| 1437 |
+
import logging
|
| 1438 |
+
from tqdm import trange
|
| 1439 |
+
from tqdm.contrib.logging import logging_redirect_tqdm
|
| 1440 |
+
|
| 1441 |
+
LOG = logging.getLogger(__name__)
|
| 1442 |
+
|
| 1443 |
+
if __name__ == '__main__':
|
| 1444 |
+
logging.basicConfig(level=logging.INFO)
|
| 1445 |
+
with logging_redirect_tqdm():
|
| 1446 |
+
for i in trange(9):
|
| 1447 |
+
if i == 4:
|
| 1448 |
+
LOG.info("console logging redirected to `tqdm.write()`")
|
| 1449 |
+
# logging restored
|
| 1450 |
+
|
| 1451 |
+
Monitoring thread, intervals and miniters
|
| 1452 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 1453 |
+
|
| 1454 |
+
``tqdm`` implements a few tricks to increase efficiency and reduce overhead.
|
| 1455 |
+
|
| 1456 |
+
- Avoid unnecessary frequent bar refreshing: ``mininterval`` defines how long
|
| 1457 |
+
to wait between each refresh. ``tqdm`` always gets updated in the background,
|
| 1458 |
+
but it will display only every ``mininterval``.
|
| 1459 |
+
- Reduce number of calls to check system clock/time.
|
| 1460 |
+
- ``mininterval`` is more intuitive to configure than ``miniters``.
|
| 1461 |
+
A clever adjustment system ``dynamic_miniters`` will automatically adjust
|
| 1462 |
+
``miniters`` to the amount of iterations that fit into time ``mininterval``.
|
| 1463 |
+
Essentially, ``tqdm`` will check if it's time to print without actually
|
| 1464 |
+
checking time. This behaviour can be still be bypassed by manually setting
|
| 1465 |
+
``miniters``.
|
| 1466 |
+
|
| 1467 |
+
However, consider a case with a combination of fast and slow iterations.
|
| 1468 |
+
After a few fast iterations, ``dynamic_miniters`` will set ``miniters`` to a
|
| 1469 |
+
large number. When iteration rate subsequently slows, ``miniters`` will
|
| 1470 |
+
remain large and thus reduce display update frequency. To address this:
|
| 1471 |
+
|
| 1472 |
+
- ``maxinterval`` defines the maximum time between display refreshes.
|
| 1473 |
+
A concurrent monitoring thread checks for overdue updates and forces one
|
| 1474 |
+
where necessary.
|
| 1475 |
+
|
| 1476 |
+
The monitoring thread should not have a noticeable overhead, and guarantees
|
| 1477 |
+
updates at least every 10 seconds by default.
|
| 1478 |
+
This value can be directly changed by setting the ``monitor_interval`` of
|
| 1479 |
+
any ``tqdm`` instance (i.e. ``t = tqdm.tqdm(...); t.monitor_interval = 2``).
|
| 1480 |
+
The monitor thread may be disabled application-wide by setting
|
| 1481 |
+
``tqdm.tqdm.monitor_interval = 0`` before instantiation of any ``tqdm`` bar.
|
| 1482 |
+
|
| 1483 |
+
|
| 1484 |
+
Merch
|
| 1485 |
+
-----
|
| 1486 |
+
|
| 1487 |
+
You can buy `tqdm branded merch <https://tqdm.github.io/merch>`__ now!
|
| 1488 |
+
|
| 1489 |
+
Contributions
|
| 1490 |
+
-------------
|
| 1491 |
+
|
| 1492 |
+
|GitHub-Commits| |GitHub-Issues| |GitHub-PRs| |OpenHub-Status| |GitHub-Contributions| |CII Best Practices|
|
| 1493 |
+
|
| 1494 |
+
All source code is hosted on `GitHub <https://github.com/tqdm/tqdm>`__.
|
| 1495 |
+
Contributions are welcome.
|
| 1496 |
+
|
| 1497 |
+
See the
|
| 1498 |
+
`CONTRIBUTING <https://github.com/tqdm/tqdm/blob/master/CONTRIBUTING.md>`__
|
| 1499 |
+
file for more information.
|
| 1500 |
+
|
| 1501 |
+
Developers who have contributed more that 5 *loc* (surviving lines of code):
|
| 1502 |
+
|
| 1503 |
+
|git-fame|
|
| 1504 |
+
|
| 1505 |
+
Honourable mentions:
|
| 1506 |
+
|
| 1507 |
+
- Casper da Costa-Luis `casperdcl <https://github.com/casperdcl>`__ primary maintainer |Gift-Casper|
|
| 1508 |
+
- Stephen Larroque `lrq3000 <https://github.com/lrq3000>`__ maintainer
|
| 1509 |
+
- Hadrien Mary `hadim <https://github.com/hadim>`__ maintainer
|
| 1510 |
+
- Mikhail Korobov `kmike <https://github.com/kmike>`__ maintainer
|
| 1511 |
+
- Noam Yorav-Raphael `noamraph <https://github.com/noamraph>`__ original author
|
| 1512 |
+
|
| 1513 |
+
Ports to Other Languages
|
| 1514 |
+
~~~~~~~~~~~~~~~~~~~~~~~~
|
| 1515 |
+
|
| 1516 |
+
A list is available on
|
| 1517 |
+
`this wiki page <https://github.com/tqdm/tqdm/wiki/tqdm-ports>`__.
|
| 1518 |
+
|
| 1519 |
+
|
| 1520 |
+
LICENCE
|
| 1521 |
+
-------
|
| 1522 |
+
|
| 1523 |
+
Open Source (OSI approved): |LICENCE|
|
| 1524 |
+
|
| 1525 |
+
Citation information: |DOI|
|
| 1526 |
+
|
| 1527 |
+
|README-Hits| (Since 19 May 2016)
|
| 1528 |
+
|
| 1529 |
+
.. |Logo| image:: https://tqdm.github.io/img/logo.gif
|
| 1530 |
+
.. |Screenshot| image:: https://tqdm.github.io/img/tqdm.gif
|
| 1531 |
+
.. |Video| image:: https://tqdm.github.io/img/video.jpg
|
| 1532 |
+
:target: https://tqdm.github.io/video
|
| 1533 |
+
.. |Slides| image:: https://tqdm.github.io/img/slides.jpg
|
| 1534 |
+
:target: https://tqdm.github.io/PyData2019/slides.html
|
| 1535 |
+
.. |Merch| image:: https://tqdm.github.io/img/merch.jpg
|
| 1536 |
+
:target: https://tqdm.github.io/merch
|
| 1537 |
+
.. |Build-Status| image:: https://img.shields.io/github/actions/workflow/status/tqdm/tqdm/test.yml?branch=master&label=tqdm&logo=GitHub
|
| 1538 |
+
:target: https://github.com/tqdm/tqdm/actions/workflows/test.yml
|
| 1539 |
+
.. |Coverage-Status| image:: https://img.shields.io/coveralls/github/tqdm/tqdm/master?logo=coveralls
|
| 1540 |
+
:target: https://coveralls.io/github/tqdm/tqdm
|
| 1541 |
+
.. |Branch-Coverage-Status| image:: https://codecov.io/gh/tqdm/tqdm/branch/master/graph/badge.svg
|
| 1542 |
+
:target: https://codecov.io/gh/tqdm/tqdm
|
| 1543 |
+
.. |Codacy-Grade| image:: https://app.codacy.com/project/badge/Grade/3f965571598f44549c7818f29cdcf177
|
| 1544 |
+
:target: https://app.codacy.com/gh/tqdm/tqdm/dashboard
|
| 1545 |
+
.. |CII Best Practices| image:: https://bestpractices.coreinfrastructure.org/projects/3264/badge
|
| 1546 |
+
:target: https://bestpractices.coreinfrastructure.org/projects/3264
|
| 1547 |
+
.. |GitHub-Status| image:: https://img.shields.io/github/tag/tqdm/tqdm.svg?maxAge=86400&logo=github&logoColor=white
|
| 1548 |
+
:target: https://github.com/tqdm/tqdm/releases
|
| 1549 |
+
.. |GitHub-Forks| image:: https://img.shields.io/github/forks/tqdm/tqdm.svg?logo=github&logoColor=white
|
| 1550 |
+
:target: https://github.com/tqdm/tqdm/network
|
| 1551 |
+
.. |GitHub-Stars| image:: https://img.shields.io/github/stars/tqdm/tqdm.svg?logo=github&logoColor=white
|
| 1552 |
+
:target: https://github.com/tqdm/tqdm/stargazers
|
| 1553 |
+
.. |GitHub-Commits| image:: https://img.shields.io/github/commit-activity/y/tqdm/tqdm.svg?logo=git&logoColor=white
|
| 1554 |
+
:target: https://github.com/tqdm/tqdm/graphs/commit-activity
|
| 1555 |
+
.. |GitHub-Issues| image:: https://img.shields.io/github/issues-closed/tqdm/tqdm.svg?logo=github&logoColor=white
|
| 1556 |
+
:target: https://github.com/tqdm/tqdm/issues?q=
|
| 1557 |
+
.. |GitHub-PRs| image:: https://img.shields.io/github/issues-pr-closed/tqdm/tqdm.svg?logo=github&logoColor=white
|
| 1558 |
+
:target: https://github.com/tqdm/tqdm/pulls
|
| 1559 |
+
.. |GitHub-Contributions| image:: https://img.shields.io/github/contributors/tqdm/tqdm.svg?logo=github&logoColor=white
|
| 1560 |
+
:target: https://github.com/tqdm/tqdm/graphs/contributors
|
| 1561 |
+
.. |GitHub-Updated| image:: https://img.shields.io/github/last-commit/tqdm/tqdm/master.svg?logo=github&logoColor=white&label=pushed
|
| 1562 |
+
:target: https://github.com/tqdm/tqdm/pulse
|
| 1563 |
+
.. |git-fame| image:: https://git-fame.cdcl.ml/gh/tqdm/tqdm?min=5&w=1&M=1&C=1&excl=(png|gif|jpg)$&enum=1
|
| 1564 |
+
:alt: git-fame.cdcl.ml/gh/tqdm/tqdm
|
| 1565 |
+
:target: https://git-fame.cdcl.ml/gh/tqdm/tqdm?w=1&M=1&C=1&excl=(png|gif|jpg)$&enum=1
|
| 1566 |
+
.. |Gift-Casper| image:: https://img.shields.io/badge/sponsor-casper-ff69b4.svg
|
| 1567 |
+
:target: https://cdcl.ml/sponsor
|
| 1568 |
+
.. |Versions| image:: https://img.shields.io/pypi/v/tqdm.svg
|
| 1569 |
+
:target: https://tqdm.github.io/releases
|
| 1570 |
+
.. |PyPI-Downloads| image:: https://static.pepy.tech/personalized-badge/tqdm?left_text=downloads%2Fmonth
|
| 1571 |
+
:target: https://pepy.tech/project/tqdm
|
| 1572 |
+
.. |Py-Versions| image:: https://img.shields.io/pypi/pyversions/tqdm.svg?logo=python&logoColor=white
|
| 1573 |
+
:target: https://pypi.org/project/tqdm
|
| 1574 |
+
.. |Conda-Forge-Status| image:: https://img.shields.io/conda/v/conda-forge/tqdm.svg?label=conda-forge&logo=conda-forge
|
| 1575 |
+
:target: https://anaconda.org/conda-forge/tqdm
|
| 1576 |
+
.. |Snapcraft| image:: https://img.shields.io/badge/snap-install-82BEA0.svg?logo=snapcraft
|
| 1577 |
+
:target: https://snapcraft.io/tqdm
|
| 1578 |
+
.. |Docker| image:: https://img.shields.io/badge/docker-pull-blue.svg?logo=docker&logoColor=white
|
| 1579 |
+
:target: https://hub.docker.com/r/tqdm/tqdm
|
| 1580 |
+
.. |Libraries-Rank| image:: https://img.shields.io/librariesio/sourcerank/pypi/tqdm.svg?logo=koding&logoColor=white
|
| 1581 |
+
:target: https://libraries.io/pypi/tqdm
|
| 1582 |
+
.. |Libraries-Dependents| image:: https://img.shields.io/librariesio/dependent-repos/pypi/tqdm.svg?logo=koding&logoColor=white
|
| 1583 |
+
:target: https://github.com/tqdm/tqdm/network/dependents
|
| 1584 |
+
.. |OpenHub-Status| image:: https://www.openhub.net/p/tqdm/widgets/project_thin_badge?format=gif
|
| 1585 |
+
:target: https://www.openhub.net/p/tqdm?ref=Thin+badge
|
| 1586 |
+
.. |awesome-python| image:: https://awesome.re/mentioned-badge.svg
|
| 1587 |
+
:target: https://github.com/vinta/awesome-python
|
| 1588 |
+
.. |LICENCE| image:: https://img.shields.io/pypi/l/tqdm.svg
|
| 1589 |
+
:target: https://raw.githubusercontent.com/tqdm/tqdm/master/LICENCE
|
| 1590 |
+
.. |DOI| image:: https://img.shields.io/badge/DOI-10.5281/zenodo.595120-blue.svg
|
| 1591 |
+
:target: https://doi.org/10.5281/zenodo.595120
|
| 1592 |
+
.. |colab-demo| image:: https://colab.research.google.com/assets/colab-badge.svg
|
| 1593 |
+
:target: https://colab.research.google.com/github/tqdm/tqdm/blob/master/DEMO.ipynb
|
| 1594 |
+
.. |binder-demo| image:: https://mybinder.org/badge_logo.svg
|
| 1595 |
+
:target: https://mybinder.org/v2/gh/tqdm/tqdm/master?filepath=DEMO.ipynb
|
| 1596 |
+
.. |Screenshot-Jupyter1| image:: https://tqdm.github.io/img/jupyter-1.gif
|
| 1597 |
+
.. |Screenshot-Jupyter2| image:: https://tqdm.github.io/img/jupyter-2.gif
|
| 1598 |
+
.. |Screenshot-Jupyter3| image:: https://tqdm.github.io/img/jupyter-3.gif
|
| 1599 |
+
.. |README-Hits| image:: https://cgi.cdcl.ml/hits?q=tqdm&style=social&r=https://github.com/tqdm/tqdm&l=https://tqdm.github.io/img/favicon.png&f=https://tqdm.github.io/img/logo.gif
|
| 1600 |
+
:target: https://cgi.cdcl.ml/hits?q=tqdm&a=plot&r=https://github.com/tqdm/tqdm&l=https://tqdm.github.io/img/favicon.png&f=https://tqdm.github.io/img/logo.gif&style=social
|
.cache/uv/archive-v0/-f_0_DZnf30ScnbSOEDOA/tqdm-4.70.0.dist-info/RECORD
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
tqdm/__init__.py,sha256=9mQNYSSqP99JasubEC1POJLMmhkkBH6cJZxPIR5G2pQ,1572
|
| 2 |
+
tqdm/__main__.py,sha256=bYt9eEaoRQWdejEHFD8REx9jxVEdZptECFsV7F49Ink,30
|
| 3 |
+
tqdm/_main.py,sha256=9ySvgmi_2Sw4CAo5UDW0Q2dxfTryboEWGHohfCJz0sA,283
|
| 4 |
+
tqdm/_monitor.py,sha256=1VcavuotYSN6K-1jbpNuy6HYtr3mwo5Nh_jZMQ-jg3A,4013
|
| 5 |
+
tqdm/_tqdm.py,sha256=LfLCuJ6bpsVo9xilmtBXyEm1vGnUCFrliW85j3J-nD4,283
|
| 6 |
+
tqdm/_tqdm_gui.py,sha256=03Hc8KayxJveieI5-0-2NGiDpLvw9jZekofJUV7CCwk,287
|
| 7 |
+
tqdm/_tqdm_notebook.py,sha256=BuHiLuxu6uEfZFaPJW3RPpPaxaVctEQA3kdSJSDL1hw,307
|
| 8 |
+
tqdm/_tqdm_pandas.py,sha256=c9jptUgigN6axRDhRd4Rif98Tmxeopc1nFNFhIpbFUE,888
|
| 9 |
+
tqdm/_utils.py,sha256=CfLztxFY-QRiNfxQCqAb2N8E13uauIM95RSQiFlaEuE,559
|
| 10 |
+
tqdm/asyncio.py,sha256=IpcGo6ZFwc6KKHYj5s7h4kaRiogcabJ6PcqHj6jdy0I,3196
|
| 11 |
+
tqdm/auto.py,sha256=nDZflj6p2zKkjBCNBourrhS81zYfZy1_dQvbckrdW8o,871
|
| 12 |
+
tqdm/autonotebook.py,sha256=2pNgGCJDsesNNyYnmSve8BNQLiGSgo97SsPoMXCrNRQ,1440
|
| 13 |
+
tqdm/cli.py,sha256=t1j_PqI0SuMyhJGoBxMPCXY-UTbfjciaAQYxAU_f_V0,11011
|
| 14 |
+
tqdm/completion.sh,sha256=j79KbSmpIj_E11jfTfBXrGnUTzKXVpQ1vGVQvsyDRl4,946
|
| 15 |
+
tqdm/dask.py,sha256=9Ei58eVqTossRLhAfWyUFCduXYKjmLmwkaXIy-CHYfs,1319
|
| 16 |
+
tqdm/gui.py,sha256=maQ7jgB5leWHwxMlbBv08hpe5lytvmH0hEARu22GRdU,5481
|
| 17 |
+
tqdm/keras.py,sha256=ugd80-xCxMqnrbx_DEOpmj6c2Sh1xoVtQ8V9-bw29eo,4396
|
| 18 |
+
tqdm/notebook.py,sha256=6xkUTcYRsFxN4_BSUYYZ51kAgI7ycnT0HLpP9HukEqg,10888
|
| 19 |
+
tqdm/rich.py,sha256=J04yq6y2Ur9012zC7PkczA1t7cDjet88hmBkrAv-s2s,5255
|
| 20 |
+
tqdm/std.py,sha256=t-7qDtaeZoxAw9_K7JWxYe7Wbn1c_GRsO4HEkluaYB0,58074
|
| 21 |
+
tqdm/tk.py,sha256=3VsB1MDAkCItaWu7CmMb2CoTLMiqmDiEgNi3yiqQ5GY,6702
|
| 22 |
+
tqdm/tqdm.1,sha256=MLg9qjeHThZpPEQbWVrf5P5gOXMKHE_X606FSOBI9eU,7538
|
| 23 |
+
tqdm/utils.py,sha256=o_f0V32H_wrn0XmRno3j9pJ9xlp5xL0fHT3gtqL-k58,9746
|
| 24 |
+
tqdm/version.py,sha256=0uH4TLe8I8H71x29dlmtEZBObLT3b5IW-nytF3V0IVw,233
|
| 25 |
+
tqdm/contrib/__init__.py,sha256=1GMYYE866WCvlHg5MdmzOvPsQj4ZuMlXzz8xcRcJD60,2479
|
| 26 |
+
tqdm/contrib/bells.py,sha256=IaxC2YW57xHDinxdUDQHvSego0HSTdDTExQQENvSB_k,921
|
| 27 |
+
tqdm/contrib/concurrent.py,sha256=XAgKYE2of1XIOEsD-gtrK82xQzDA1PEwvIpP_jcEuTs,9849
|
| 28 |
+
tqdm/contrib/discord.py,sha256=LPjxDbmfiYtw3OAm_WhtwbX9BVYDlPc8lJ96aY3YZDE,5337
|
| 29 |
+
tqdm/contrib/itertools.py,sha256=MA9-Jvb3ToseppInvev2iF4bokN7GQy4Q4LgjUyYdA4,2949
|
| 30 |
+
tqdm/contrib/logging.py,sha256=0nFn2C7qUUiKPB19qTGuS9Lfja8aiFW0u9kybRdG0hU,3902
|
| 31 |
+
tqdm/contrib/slack.py,sha256=sC182v7xBkfGftnDeUmQALMOfwQzU3ZiNf1Q_XA1DjI,4049
|
| 32 |
+
tqdm/contrib/telegram.py,sha256=ybTraGjUQx5m443TsX6pJ7Uxrpsh1m4a43BTWVl_4e4,5081
|
| 33 |
+
tqdm/contrib/utils_worker.py,sha256=vaxyJyagYwOCQXLUMd86bCbI4sPqZysuMGbDSGmvEWo,1199
|
| 34 |
+
tqdm-4.70.0.dist-info/licenses/LICENCE,sha256=_P-Hw6R86AKKhRKqGC1PzwrRyQVE7nXPmzQ2hMrBlN4,1985
|
| 35 |
+
tqdm-4.70.0.dist-info/METADATA,sha256=DZW4W5BCj4d2r8SpKxfFCU947pjRULMlWsvN9OnVeUE,57344
|
| 36 |
+
tqdm-4.70.0.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
|
| 37 |
+
tqdm-4.70.0.dist-info/entry_points.txt,sha256=ReJCH7Ui3Zyh6M16E4OhsZ1oU7WtMXCfbtoyBhGO29Y,39
|
| 38 |
+
tqdm-4.70.0.dist-info/top_level.txt,sha256=NLiUJNfmc9At15s7JURiwvqMEjUi9G5PMGRrmMYzNSM,5
|
| 39 |
+
tqdm-4.70.0.dist-info/RECORD,,
|
.cache/uv/archive-v0/-f_0_DZnf30ScnbSOEDOA/tqdm-4.70.0.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: setuptools (83.0.0)
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py3-none-any
|
| 5 |
+
|
.cache/uv/archive-v0/-f_0_DZnf30ScnbSOEDOA/tqdm-4.70.0.dist-info/entry_points.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[console_scripts]
|
| 2 |
+
tqdm = tqdm.cli:main
|
.cache/uv/archive-v0/-f_0_DZnf30ScnbSOEDOA/tqdm-4.70.0.dist-info/top_level.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
tqdm
|
.cache/uv/archive-v0/-f_0_DZnf30ScnbSOEDOA/tqdm/autonotebook.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Automatically choose between `tqdm.notebook` and `tqdm.std`.
|
| 3 |
+
|
| 4 |
+
Usage:
|
| 5 |
+
>>> from tqdm.autonotebook import trange, tqdm
|
| 6 |
+
>>> for i in trange(10):
|
| 7 |
+
... ...
|
| 8 |
+
"""
|
| 9 |
+
import os
|
| 10 |
+
import sys
|
| 11 |
+
from warnings import warn
|
| 12 |
+
|
| 13 |
+
try:
|
| 14 |
+
if 'ipykernel.zmqshell' in sys.modules:
|
| 15 |
+
if any(i == 'QT_API' or i.startswith('SPYDER') for i in os.environ):
|
| 16 |
+
raise ImportError("console") # jupyter-qtconsole/spyder
|
| 17 |
+
ipy = sys.modules['IPython'].get_ipython().__class__.__name__.lower()
|
| 18 |
+
if 'qt' in ipy or 'spyder' in ipy:
|
| 19 |
+
raise ImportError("console") # older jupyter-qtconsole/spyder
|
| 20 |
+
# jupyter-notebook/jupyterlab/vscode/binder/colab
|
| 21 |
+
elif 'IPython.utils._process_emscripten' in sys.modules:
|
| 22 |
+
pass # jupyterlite (pyodide)/jupyterlite-xeus
|
| 23 |
+
else:
|
| 24 |
+
raise ImportError("console") # ipython/jupyter-console
|
| 25 |
+
from .notebook import WARN_NOIPYW, IProgress
|
| 26 |
+
if IProgress is None:
|
| 27 |
+
from .std import TqdmWarning
|
| 28 |
+
warn(WARN_NOIPYW, TqdmWarning, stacklevel=2)
|
| 29 |
+
raise ImportError('ipywidgets')
|
| 30 |
+
except Exception:
|
| 31 |
+
from .std import tqdm, trange
|
| 32 |
+
else: # pragma: no cover
|
| 33 |
+
from .notebook import tqdm, trange
|
| 34 |
+
from .std import TqdmExperimentalWarning
|
| 35 |
+
warn("Using `tqdm.autonotebook.tqdm` in notebook mode."
|
| 36 |
+
" Use `tqdm.tqdm` instead to force console mode"
|
| 37 |
+
" (e.g. in jupyter console)", TqdmExperimentalWarning, stacklevel=2)
|
| 38 |
+
__all__ = ["tqdm", "trange"]
|
.cache/uv/archive-v0/-f_0_DZnf30ScnbSOEDOA/tqdm/cli.py
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
from textwrap import indent
|
| 9 |
+
|
| 10 |
+
from .std import TqdmKeyError, TqdmTypeError, tqdm
|
| 11 |
+
from .version import __version__
|
| 12 |
+
|
| 13 |
+
__all__ = ["main"]
|
| 14 |
+
log = logging.getLogger(__name__)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def cast(val, typ):
|
| 18 |
+
log.debug((val, typ))
|
| 19 |
+
if " or " in typ:
|
| 20 |
+
for t in typ.split(" or "):
|
| 21 |
+
try:
|
| 22 |
+
return cast(val, t)
|
| 23 |
+
except TqdmTypeError:
|
| 24 |
+
pass
|
| 25 |
+
raise TqdmTypeError(f"{val} : {typ}")
|
| 26 |
+
|
| 27 |
+
# sys.stderr.write('\ndebug | `val:type`: `' + val + ':' + typ + '`.\n')
|
| 28 |
+
if typ == 'bool':
|
| 29 |
+
if (val == 'True') or (val == ''):
|
| 30 |
+
return True
|
| 31 |
+
if val == 'False':
|
| 32 |
+
return False
|
| 33 |
+
raise TqdmTypeError(val + ' : ' + typ)
|
| 34 |
+
if typ == 'chr':
|
| 35 |
+
if len(val) == 1:
|
| 36 |
+
return val.encode()
|
| 37 |
+
if re.match(r"^\\\w+$", val):
|
| 38 |
+
return literal_eval(f'"{val}"').encode()
|
| 39 |
+
raise TqdmTypeError(f"{val} : {typ}")
|
| 40 |
+
if typ == 'str':
|
| 41 |
+
return val
|
| 42 |
+
if typ == 'int':
|
| 43 |
+
try:
|
| 44 |
+
return int(val)
|
| 45 |
+
except ValueError as exc:
|
| 46 |
+
raise TqdmTypeError(f"{val} : {typ}") from exc
|
| 47 |
+
if typ == 'float':
|
| 48 |
+
try:
|
| 49 |
+
return float(val)
|
| 50 |
+
except ValueError as exc:
|
| 51 |
+
raise TqdmTypeError(f"{val} : {typ}") from exc
|
| 52 |
+
raise TqdmTypeError(f"{val} : {typ}")
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def posix_pipe(fin, fout, delim=b'\\n', buf_size=256,
|
| 56 |
+
callback=lambda float: None, callback_len=True):
|
| 57 |
+
"""
|
| 58 |
+
Params
|
| 59 |
+
------
|
| 60 |
+
fin : binary file with `read(buf_size : int)` method
|
| 61 |
+
fout : binary file with `write` (and optionally `flush`) methods.
|
| 62 |
+
callback : function(float), e.g.: `tqdm.update`
|
| 63 |
+
callback_len : If (default: True) do `callback(len(buffer))`.
|
| 64 |
+
Otherwise, do `callback(data) for data in buffer.split(delim)`.
|
| 65 |
+
"""
|
| 66 |
+
fp_write = fout.write
|
| 67 |
+
|
| 68 |
+
if not delim:
|
| 69 |
+
while True:
|
| 70 |
+
tmp = fin.read(buf_size)
|
| 71 |
+
|
| 72 |
+
# flush at EOF
|
| 73 |
+
if not tmp:
|
| 74 |
+
getattr(fout, 'flush', lambda: None)()
|
| 75 |
+
return
|
| 76 |
+
|
| 77 |
+
fp_write(tmp)
|
| 78 |
+
callback(len(tmp))
|
| 79 |
+
# return
|
| 80 |
+
|
| 81 |
+
buf = b''
|
| 82 |
+
len_delim = len(delim)
|
| 83 |
+
# n = 0
|
| 84 |
+
while True:
|
| 85 |
+
tmp = fin.read(buf_size)
|
| 86 |
+
|
| 87 |
+
# flush at EOF
|
| 88 |
+
if not tmp:
|
| 89 |
+
if buf:
|
| 90 |
+
fp_write(buf)
|
| 91 |
+
if callback_len:
|
| 92 |
+
# n += 1 + buf.count(delim)
|
| 93 |
+
callback(1 + buf.count(delim))
|
| 94 |
+
else:
|
| 95 |
+
for i in buf.split(delim):
|
| 96 |
+
callback(i)
|
| 97 |
+
getattr(fout, 'flush', lambda: None)()
|
| 98 |
+
return # n
|
| 99 |
+
|
| 100 |
+
while True:
|
| 101 |
+
i = tmp.find(delim)
|
| 102 |
+
if i < 0:
|
| 103 |
+
buf += tmp
|
| 104 |
+
break
|
| 105 |
+
fp_write(buf + tmp[:i + len(delim)])
|
| 106 |
+
# n += 1
|
| 107 |
+
callback(1 if callback_len else (buf + tmp[:i]))
|
| 108 |
+
buf = b''
|
| 109 |
+
tmp = tmp[i + len_delim:]
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
# ((opt, type), ... )
|
| 113 |
+
RE_OPTS = re.compile(r'\n {4}(\S+)\s{2,}:\s*([^,]+)')
|
| 114 |
+
# better split method assuming no positional args
|
| 115 |
+
RE_SHLEX = re.compile(r'\s*(?<!\S)--?([^\s=]+)(\s+|=|$)')
|
| 116 |
+
|
| 117 |
+
# TODO: add custom support for some of the following?
|
| 118 |
+
UNSUPPORTED_OPTS = ('iterable', 'gui', 'out', 'file')
|
| 119 |
+
|
| 120 |
+
# The 8 leading spaces are required for consistency
|
| 121 |
+
CLI_EXTRA_DOC = r"""
|
| 122 |
+
Extra CLI Options
|
| 123 |
+
-----------------
|
| 124 |
+
name : type, optional
|
| 125 |
+
TODO: find out why this is needed.
|
| 126 |
+
delim : chr, optional
|
| 127 |
+
Delimiting character [default: '\n']. Use '\0' for null.
|
| 128 |
+
N.B.: on Windows systems, Python converts '\n' to '\r\n'.
|
| 129 |
+
buf_size : int, optional
|
| 130 |
+
String buffer size in bytes [default: 256]
|
| 131 |
+
used when `delim` is specified.
|
| 132 |
+
bytes : bool, optional
|
| 133 |
+
If true, will count bytes, ignore `delim`, and default
|
| 134 |
+
`unit_scale` to True, `unit_divisor` to 1024, and `unit` to 'B'.
|
| 135 |
+
tee : bool, optional
|
| 136 |
+
If true, passes `stdin` to both `stderr` and `stdout`.
|
| 137 |
+
update : bool, optional
|
| 138 |
+
If true, will treat input as newly elapsed iterations,
|
| 139 |
+
i.e. numbers to pass to `update()`. Note that this is slow
|
| 140 |
+
(~2e5 it/s) since every input must be decoded as a number.
|
| 141 |
+
update_to : bool, optional
|
| 142 |
+
If true, will treat input as total elapsed iterations,
|
| 143 |
+
i.e. numbers to assign to `self.n`. Note that this is slow
|
| 144 |
+
(~2e5 it/s) since every input must be decoded as a number.
|
| 145 |
+
null : bool, optional
|
| 146 |
+
If true, will discard input (no stdout).
|
| 147 |
+
manpath : str, optional
|
| 148 |
+
Directory in which to install tqdm man pages.
|
| 149 |
+
comppath : str, optional
|
| 150 |
+
Directory in which to place tqdm completion.
|
| 151 |
+
log : str, optional
|
| 152 |
+
CRITICAL|FATAL|ERROR|WARN(ING)|[default: 'INFO']|DEBUG|NOTSET.
|
| 153 |
+
"""
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def main(fp=sys.stderr, argv=None):
|
| 157 |
+
"""
|
| 158 |
+
Parameters (internal use only)
|
| 159 |
+
---------
|
| 160 |
+
fp : file-like object for tqdm
|
| 161 |
+
argv : list (default: sys.argv[1:])
|
| 162 |
+
"""
|
| 163 |
+
if argv is None:
|
| 164 |
+
argv = sys.argv[1:]
|
| 165 |
+
try:
|
| 166 |
+
log_idx = argv.index('--log')
|
| 167 |
+
except ValueError:
|
| 168 |
+
for i in argv:
|
| 169 |
+
if i.startswith('--log='):
|
| 170 |
+
logLevel = i[len('--log='):]
|
| 171 |
+
break
|
| 172 |
+
else:
|
| 173 |
+
logLevel = 'INFO'
|
| 174 |
+
else:
|
| 175 |
+
# argv.pop(log_idx)
|
| 176 |
+
# logLevel = argv.pop(log_idx)
|
| 177 |
+
logLevel = argv[log_idx + 1]
|
| 178 |
+
logging.basicConfig(level=getattr(logging, logLevel),
|
| 179 |
+
format="%(levelname)s:%(module)s:%(lineno)d:%(message)s")
|
| 180 |
+
|
| 181 |
+
# py<3.13 doesn't dedent docstrings
|
| 182 |
+
d = (tqdm.__doc__ if sys.version_info < (3, 13)
|
| 183 |
+
else indent(tqdm.__doc__, " ")) + CLI_EXTRA_DOC
|
| 184 |
+
|
| 185 |
+
opt_types = dict(RE_OPTS.findall(d))
|
| 186 |
+
# opt_types['delim'] = 'chr'
|
| 187 |
+
|
| 188 |
+
for o in UNSUPPORTED_OPTS:
|
| 189 |
+
opt_types.pop(o)
|
| 190 |
+
|
| 191 |
+
log.debug(sorted(opt_types.items()))
|
| 192 |
+
|
| 193 |
+
# d = RE_OPTS.sub(r' --\1=<\1> : \2', d)
|
| 194 |
+
split = RE_OPTS.split(d)
|
| 195 |
+
opt_types_desc = zip(split[1::3], split[2::3], split[3::3])
|
| 196 |
+
d = ''.join(('\n --{0} : {2}{3}' if otd[1] == 'bool' else
|
| 197 |
+
'\n --{0}=<{1}> : {2}{3}').format(
|
| 198 |
+
otd[0].replace('_', '-'), otd[0], *otd[1:])
|
| 199 |
+
for otd in opt_types_desc if otd[0] not in UNSUPPORTED_OPTS)
|
| 200 |
+
|
| 201 |
+
help_short = "Usage:\n tqdm [--help | options]\n"
|
| 202 |
+
d = help_short + """
|
| 203 |
+
Options:
|
| 204 |
+
-h, --help Print this help and exit.
|
| 205 |
+
-v, --version Print version and exit.
|
| 206 |
+
""" + d.strip('\n') + '\n'
|
| 207 |
+
|
| 208 |
+
# opts = docopt(d, version=__version__)
|
| 209 |
+
if any(v in argv for v in ('-v', '--version')):
|
| 210 |
+
sys.stdout.write(__version__ + '\n')
|
| 211 |
+
sys.exit(0)
|
| 212 |
+
elif any(v in argv for v in ('-h', '--help')):
|
| 213 |
+
sys.stdout.write(d + '\n')
|
| 214 |
+
sys.exit(0)
|
| 215 |
+
elif argv and argv[0][:2] != '--':
|
| 216 |
+
sys.stderr.write(f"Error:Unknown argument:{argv[0]}\n{help_short}")
|
| 217 |
+
|
| 218 |
+
argv = RE_SHLEX.split(' '.join(["tqdm"] + argv))
|
| 219 |
+
opts = dict(zip(argv[1::3], argv[3::3]))
|
| 220 |
+
|
| 221 |
+
log.debug(opts)
|
| 222 |
+
opts.pop('log', True)
|
| 223 |
+
|
| 224 |
+
tqdm_args = {'file': fp}
|
| 225 |
+
try:
|
| 226 |
+
for (o, v) in opts.items():
|
| 227 |
+
o = o.replace('-', '_')
|
| 228 |
+
try:
|
| 229 |
+
tqdm_args[o] = cast(v, opt_types[o])
|
| 230 |
+
except KeyError as e:
|
| 231 |
+
raise TqdmKeyError(str(e))
|
| 232 |
+
log.debug('args:' + str(tqdm_args))
|
| 233 |
+
|
| 234 |
+
delim_per_char = tqdm_args.pop('bytes', False)
|
| 235 |
+
update = tqdm_args.pop('update', False)
|
| 236 |
+
update_to = tqdm_args.pop('update_to', False)
|
| 237 |
+
if sum((delim_per_char, update, update_to)) > 1:
|
| 238 |
+
raise TqdmKeyError("Can only have one of --bytes --update --update_to")
|
| 239 |
+
except Exception:
|
| 240 |
+
fp.write("\nError:\n" + help_short)
|
| 241 |
+
stdin, stdout_write = sys.stdin, sys.stdout.write
|
| 242 |
+
for i in stdin:
|
| 243 |
+
stdout_write(i)
|
| 244 |
+
raise
|
| 245 |
+
else:
|
| 246 |
+
buf_size = tqdm_args.pop('buf_size', 256)
|
| 247 |
+
delim = tqdm_args.pop('delim', b'\\n')
|
| 248 |
+
tee = tqdm_args.pop('tee', False)
|
| 249 |
+
manpath = tqdm_args.pop('manpath', None)
|
| 250 |
+
comppath = tqdm_args.pop('comppath', None)
|
| 251 |
+
if tqdm_args.pop('null', False):
|
| 252 |
+
class stdout:
|
| 253 |
+
@staticmethod
|
| 254 |
+
def write(_):
|
| 255 |
+
pass
|
| 256 |
+
else:
|
| 257 |
+
stdout = sys.stdout
|
| 258 |
+
stdout = getattr(stdout, 'buffer', stdout)
|
| 259 |
+
stdin = getattr(sys.stdin, 'buffer', sys.stdin)
|
| 260 |
+
if manpath or comppath:
|
| 261 |
+
try: # py<3.9
|
| 262 |
+
import importlib_resources as resources
|
| 263 |
+
except ImportError:
|
| 264 |
+
from importlib import resources
|
| 265 |
+
from pathlib import Path
|
| 266 |
+
|
| 267 |
+
def cp(name, dst):
|
| 268 |
+
"""copy resource `name` to `dst`"""
|
| 269 |
+
fi = resources.files('tqdm') / name
|
| 270 |
+
dst.write_bytes(fi.read_bytes())
|
| 271 |
+
log.info("written:%s", dst)
|
| 272 |
+
if manpath is not None:
|
| 273 |
+
cp('tqdm.1', Path(manpath) / 'tqdm.1')
|
| 274 |
+
if comppath is not None:
|
| 275 |
+
cp('completion.sh', Path(comppath) / 'tqdm_completion.sh')
|
| 276 |
+
sys.exit(0)
|
| 277 |
+
if tee:
|
| 278 |
+
stdout_write = stdout.write
|
| 279 |
+
fp_write = getattr(fp, 'buffer', fp).write
|
| 280 |
+
|
| 281 |
+
class stdout: # pylint: disable=function-redefined
|
| 282 |
+
@staticmethod
|
| 283 |
+
def write(x):
|
| 284 |
+
with tqdm.external_write_mode(file=fp):
|
| 285 |
+
fp_write(x)
|
| 286 |
+
stdout_write(x)
|
| 287 |
+
if delim_per_char:
|
| 288 |
+
tqdm_args.setdefault('unit', 'B')
|
| 289 |
+
tqdm_args.setdefault('unit_scale', True)
|
| 290 |
+
tqdm_args.setdefault('unit_divisor', 1024)
|
| 291 |
+
log.debug(tqdm_args)
|
| 292 |
+
with tqdm(**tqdm_args) as t:
|
| 293 |
+
posix_pipe(stdin, stdout, '', buf_size, t.update)
|
| 294 |
+
elif delim == b'\\n':
|
| 295 |
+
log.debug(tqdm_args)
|
| 296 |
+
write = stdout.write
|
| 297 |
+
if update or update_to:
|
| 298 |
+
with tqdm(**tqdm_args) as t:
|
| 299 |
+
if update:
|
| 300 |
+
def callback(i):
|
| 301 |
+
t.update(literal_eval(i.decode()))
|
| 302 |
+
else: # update_to
|
| 303 |
+
def callback(i):
|
| 304 |
+
t.update(literal_eval(i.decode()) - t.n)
|
| 305 |
+
for i in stdin:
|
| 306 |
+
write(i)
|
| 307 |
+
callback(i)
|
| 308 |
+
else:
|
| 309 |
+
for i in tqdm(stdin, **tqdm_args):
|
| 310 |
+
write(i)
|
| 311 |
+
else:
|
| 312 |
+
log.debug(tqdm_args)
|
| 313 |
+
with tqdm(**tqdm_args) as t:
|
| 314 |
+
callback_len = False
|
| 315 |
+
if update:
|
| 316 |
+
def callback(i):
|
| 317 |
+
t.update(literal_eval(i.decode()))
|
| 318 |
+
elif update_to:
|
| 319 |
+
def callback(i):
|
| 320 |
+
t.update(literal_eval(i.decode()) - t.n)
|
| 321 |
+
else:
|
| 322 |
+
callback = t.update
|
| 323 |
+
callback_len = True
|
| 324 |
+
posix_pipe(stdin, stdout, delim, buf_size, callback, callback_len)
|
.cache/uv/archive-v0/-f_0_DZnf30ScnbSOEDOA/tqdm/completion.sh
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
_tqdm(){
|
| 3 |
+
local cur prv
|
| 4 |
+
cur="${COMP_WORDS[COMP_CWORD]}"
|
| 5 |
+
prv="${COMP_WORDS[COMP_CWORD - 1]}"
|
| 6 |
+
|
| 7 |
+
case ${prv} in
|
| 8 |
+
--bar_format|--buf_size|--colour|--comppath|--delay|--delim|--desc|--initial|--lock_args|--manpath|--maxinterval|--mininterval|--miniters|--ncols|--nrows|--position|--postfix|--smoothing|--total|--unit|--unit_divisor)
|
| 9 |
+
# await user input
|
| 10 |
+
;;
|
| 11 |
+
"--log")
|
| 12 |
+
COMPREPLY=($(compgen -W 'CRITICAL FATAL ERROR WARN WARNING INFO DEBUG NOTSET' -- ${cur}))
|
| 13 |
+
;;
|
| 14 |
+
*)
|
| 15 |
+
COMPREPLY=($(compgen -W '--ascii --bar_format --buf_size --bytes --colour --comppath --delay --delim --desc --disable --dynamic_ncols --help --initial --leave --lock_args --log --manpath --maxinterval --mininterval --miniters --ncols --nrows --null --position --postfix --smoothing --tee --total --unit --unit_divisor --unit_scale --update --update_to --version --write_bytes -h -v' -- ${cur}))
|
| 16 |
+
;;
|
| 17 |
+
esac
|
| 18 |
+
}
|
| 19 |
+
complete -F _tqdm tqdm
|
.cache/uv/archive-v0/-f_0_DZnf30ScnbSOEDOA/tqdm/dask.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from functools import partial
|
| 2 |
+
|
| 3 |
+
from dask.callbacks import Callback
|
| 4 |
+
|
| 5 |
+
from .auto import tqdm as tqdm_auto
|
| 6 |
+
|
| 7 |
+
__author__ = {"github.com/": ["casperdcl"]}
|
| 8 |
+
__all__ = ['TqdmCallback']
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class TqdmCallback(Callback):
|
| 12 |
+
"""Dask callback for task progress."""
|
| 13 |
+
def __init__(self, start=None, pretask=None, tqdm_class=tqdm_auto,
|
| 14 |
+
**tqdm_kwargs):
|
| 15 |
+
"""
|
| 16 |
+
Parameters
|
| 17 |
+
----------
|
| 18 |
+
tqdm_class : optional
|
| 19 |
+
`tqdm` class to use for bars [default: `tqdm.auto.tqdm`].
|
| 20 |
+
tqdm_kwargs : optional
|
| 21 |
+
Any other arguments used for all bars.
|
| 22 |
+
"""
|
| 23 |
+
super().__init__(start=start, pretask=pretask)
|
| 24 |
+
if tqdm_kwargs:
|
| 25 |
+
tqdm_class = partial(tqdm_class, **tqdm_kwargs)
|
| 26 |
+
self.tqdm_class = tqdm_class
|
| 27 |
+
|
| 28 |
+
def _start_state(self, _, state):
|
| 29 |
+
self.pbar = self.tqdm_class(total=sum(
|
| 30 |
+
len(state[k]) for k in ['ready', 'waiting', 'running', 'finished']))
|
| 31 |
+
|
| 32 |
+
def _posttask(self, *_, **__):
|
| 33 |
+
self.pbar.update()
|
| 34 |
+
|
| 35 |
+
def _finish(self, *_, **__):
|
| 36 |
+
self.pbar.close()
|
| 37 |
+
|
| 38 |
+
def display(self):
|
| 39 |
+
"""Displays in the current cell in Notebooks."""
|
| 40 |
+
container = getattr(self.bar, 'container', None)
|
| 41 |
+
if container is None:
|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
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
`rich.progress` decorator for iterators.
|
| 3 |
+
|
| 4 |
+
Usage:
|
| 5 |
+
>>> from tqdm.rich import trange, tqdm
|
| 6 |
+
>>> for i in trange(10):
|
| 7 |
+
... ...
|
| 8 |
+
"""
|
| 9 |
+
from warnings import warn
|
| 10 |
+
|
| 11 |
+
from rich.progress import (
|
| 12 |
+
BarColumn, Progress, ProgressColumn, Text, TimeElapsedColumn, TimeRemainingColumn, filesize)
|
| 13 |
+
|
| 14 |
+
from .std import TqdmExperimentalWarning
|
| 15 |
+
from .std import tqdm as std_tqdm
|
| 16 |
+
|
| 17 |
+
__author__ = {"github.com/": ["casperdcl"]}
|
| 18 |
+
__all__ = ['tqdm_rich', 'trrange', 'tqdm', 'trange']
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class FractionColumn(ProgressColumn):
|
| 22 |
+
"""Renders completed/total, e.g. '0.5/2.3 G'."""
|
| 23 |
+
def __init__(self, unit_scale=False, unit_divisor=1000):
|
| 24 |
+
self.unit_scale = unit_scale
|
| 25 |
+
self.unit_divisor = unit_divisor
|
| 26 |
+
super().__init__()
|
| 27 |
+
|
| 28 |
+
def render(self, task):
|
| 29 |
+
"""Calculate common unit for completed and total."""
|
| 30 |
+
completed = int(task.completed)
|
| 31 |
+
# total is None when the iterable has no length (e.g. a generator)
|
| 32 |
+
total = int(task.total) if task.total is not None else None
|
| 33 |
+
base = total if total is not None else completed
|
| 34 |
+
if self.unit_scale:
|
| 35 |
+
unit, suffix = filesize.pick_unit_and_suffix(
|
| 36 |
+
base,
|
| 37 |
+
["", "K", "M", "G", "T", "P", "E", "Z", "Y"],
|
| 38 |
+
self.unit_divisor,
|
| 39 |
+
)
|
| 40 |
+
else:
|
| 41 |
+
unit, suffix = filesize.pick_unit_and_suffix(base, [""], 1)
|
| 42 |
+
precision = 0 if unit == 1 else 1
|
| 43 |
+
total_str = f"{total/unit:,.{precision}f}" if total is not None else "?"
|
| 44 |
+
return Text(
|
| 45 |
+
f"{completed/unit:,.{precision}f}/{total_str} {suffix}",
|
| 46 |
+
style="progress.download")
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class RateColumn(ProgressColumn):
|
| 50 |
+
"""Renders human readable transfer speed."""
|
| 51 |
+
def __init__(self, unit="", unit_scale=False, unit_divisor=1000):
|
| 52 |
+
self.unit = unit
|
| 53 |
+
self.unit_scale = unit_scale
|
| 54 |
+
self.unit_divisor = unit_divisor
|
| 55 |
+
super().__init__()
|
| 56 |
+
|
| 57 |
+
def render(self, task):
|
| 58 |
+
"""Show data transfer speed."""
|
| 59 |
+
speed = task.speed
|
| 60 |
+
if speed is None:
|
| 61 |
+
return Text(f"? {self.unit}/s", style="progress.data.speed")
|
| 62 |
+
if self.unit_scale:
|
| 63 |
+
unit, suffix = filesize.pick_unit_and_suffix(
|
| 64 |
+
speed,
|
| 65 |
+
["", "K", "M", "G", "T", "P", "E", "Z", "Y"],
|
| 66 |
+
self.unit_divisor,
|
| 67 |
+
)
|
| 68 |
+
else:
|
| 69 |
+
unit, suffix = filesize.pick_unit_and_suffix(speed, [""], 1)
|
| 70 |
+
precision = 0 if unit == 1 else 1
|
| 71 |
+
return Text(f"{speed/unit:,.{precision}f} {suffix}{self.unit}/s",
|
| 72 |
+
style="progress.data.speed")
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class tqdm_rich(std_tqdm): # pragma: no cover
|
| 76 |
+
"""Experimental rich.progress GUI version of tqdm!"""
|
| 77 |
+
# TODO: @classmethod: write()?
|
| 78 |
+
def __init__(self, *args, **kwargs):
|
| 79 |
+
"""
|
| 80 |
+
This class accepts the following parameters *in addition* to
|
| 81 |
+
the parameters accepted by `tqdm`.
|
| 82 |
+
|
| 83 |
+
Parameters
|
| 84 |
+
----------
|
| 85 |
+
progress : tuple, optional
|
| 86 |
+
arguments for `rich.progress.Progress()`.
|
| 87 |
+
options : dict, optional
|
| 88 |
+
keyword arguments for `rich.progress.Progress()`.
|
| 89 |
+
"""
|
| 90 |
+
kwargs = kwargs.copy()
|
| 91 |
+
kwargs['gui'] = True
|
| 92 |
+
# convert disable = None to False
|
| 93 |
+
kwargs['disable'] = bool(kwargs.get('disable', False))
|
| 94 |
+
progress = kwargs.pop('progress', None)
|
| 95 |
+
options = kwargs.pop('options', {}).copy()
|
| 96 |
+
super().__init__(*args, **kwargs)
|
| 97 |
+
|
| 98 |
+
if self.disable:
|
| 99 |
+
return
|
| 100 |
+
|
| 101 |
+
warn("rich is experimental/alpha", TqdmExperimentalWarning, stacklevel=2)
|
| 102 |
+
d = self.format_dict
|
| 103 |
+
if progress is None:
|
| 104 |
+
progress = (
|
| 105 |
+
"[progress.description]{task.description}"
|
| 106 |
+
"[progress.percentage]{task.percentage:>4.0f}%",
|
| 107 |
+
BarColumn(bar_width=None),
|
| 108 |
+
FractionColumn(
|
| 109 |
+
unit_scale=d['unit_scale'], unit_divisor=d['unit_divisor']),
|
| 110 |
+
"[", TimeElapsedColumn(), "<", TimeRemainingColumn(),
|
| 111 |
+
",", RateColumn(unit=d['unit'], unit_scale=d['unit_scale'],
|
| 112 |
+
unit_divisor=d['unit_divisor']), "]"
|
| 113 |
+
)
|
| 114 |
+
options.setdefault('transient', not self.leave)
|
| 115 |
+
self._prog = Progress(*progress, **options)
|
| 116 |
+
self._prog.__enter__()
|
| 117 |
+
self._task_id = self._prog.add_task(self.desc or "", **d)
|
| 118 |
+
|
| 119 |
+
def close(self):
|
| 120 |
+
if self.disable:
|
| 121 |
+
return
|
| 122 |
+
self.display() # print 100%, vis #1306
|
| 123 |
+
super().close()
|
| 124 |
+
self._prog.__exit__(None, None, None)
|
| 125 |
+
|
| 126 |
+
def clear(self, *_, **__):
|
| 127 |
+
pass
|
| 128 |
+
|
| 129 |
+
def display(self, *_, **__):
|
| 130 |
+
if not hasattr(self, '_task_id'):
|
| 131 |
+
return
|
| 132 |
+
self._prog.update(self._task_id, completed=self.n, description=self.desc)
|
| 133 |
+
|
| 134 |
+
def reset(self, total=None):
|
| 135 |
+
"""
|
| 136 |
+
Resets to 0 iterations for repeated use.
|
| 137 |
+
|
| 138 |
+
Parameters
|
| 139 |
+
----------
|
| 140 |
+
total : int or float, optional. Total to use for the new bar.
|
| 141 |
+
"""
|
| 142 |
+
if hasattr(self, '_prog'):
|
| 143 |
+
self._prog.reset(total=total)
|
| 144 |
+
super().reset(total=total)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def trrange(*args, **kwargs):
|
| 148 |
+
"""Shortcut for `tqdm.rich.tqdm(range(*args), **kwargs)`."""
|
| 149 |
+
return tqdm_rich(range(*args), **kwargs)
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
# Aliases
|
| 153 |
+
tqdm = tqdm_rich
|
| 154 |
+
trange = trrange
|
.cache/uv/archive-v0/-f_0_DZnf30ScnbSOEDOA/tqdm/std.py
ADDED
|
@@ -0,0 +1,1533 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Customisable progress bar decorator for iterators.
|
| 3 |
+
Includes a default `range` iterator printing to `stderr`.
|
| 4 |
+
|
| 5 |
+
Usage:
|
| 6 |
+
>>> from tqdm import trange, tqdm
|
| 7 |
+
>>> for i in trange(10):
|
| 8 |
+
... ...
|
| 9 |
+
"""
|
| 10 |
+
import sys
|
| 11 |
+
from collections import OrderedDict, defaultdict
|
| 12 |
+
from contextlib import contextmanager
|
| 13 |
+
from datetime import datetime, timedelta, timezone
|
| 14 |
+
from numbers import Number
|
| 15 |
+
from time import time
|
| 16 |
+
from warnings import warn
|
| 17 |
+
from weakref import WeakSet
|
| 18 |
+
|
| 19 |
+
from ._monitor import TMonitor
|
| 20 |
+
from .utils import (
|
| 21 |
+
CallbackIOWrapper, Comparable, DisableOnWriteError, FormatReplace, SimpleTextIOWrapper,
|
| 22 |
+
_is_ascii, _screen_shape_wrapper, _supports_unicode, _term_move_up, disp_len, disp_trim,
|
| 23 |
+
envwrap)
|
| 24 |
+
|
| 25 |
+
__author__ = "https://github.com/tqdm/tqdm#contributions"
|
| 26 |
+
__all__ = ['tqdm', 'trange',
|
| 27 |
+
'TqdmTypeError', 'TqdmKeyError', 'TqdmWarning',
|
| 28 |
+
'TqdmExperimentalWarning', 'TqdmDeprecationWarning',
|
| 29 |
+
'TqdmMonitorWarning']
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class TqdmTypeError(TypeError):
|
| 33 |
+
pass
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class TqdmKeyError(KeyError):
|
| 37 |
+
pass
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class TqdmWarning(Warning):
|
| 41 |
+
"""base class for all tqdm warnings.
|
| 42 |
+
|
| 43 |
+
Used for non-external-code-breaking errors, such as garbled printing.
|
| 44 |
+
"""
|
| 45 |
+
def __init__(self, msg, fp_write=None): # noqa: B042
|
| 46 |
+
if fp_write is not None:
|
| 47 |
+
fp_write("\n" + self.__class__.__name__ + ": " + str(msg).rstrip() + '\n')
|
| 48 |
+
else:
|
| 49 |
+
super().__init__(msg)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class TqdmExperimentalWarning(TqdmWarning, FutureWarning):
|
| 53 |
+
"""beta feature, unstable API and behaviour"""
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class TqdmDeprecationWarning(TqdmWarning, DeprecationWarning):
|
| 57 |
+
"""may be removed in a future release"""
|
| 58 |
+
# not suppressed if raised
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
class TqdmMonitorWarning(TqdmWarning, RuntimeWarning):
|
| 62 |
+
"""tqdm monitor errors which do not affect external functionality"""
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def TRLock(*args, **kwargs):
|
| 66 |
+
"""threading RLock"""
|
| 67 |
+
try:
|
| 68 |
+
from threading import RLock
|
| 69 |
+
return RLock(*args, **kwargs)
|
| 70 |
+
except (ImportError, OSError): # pragma: no cover
|
| 71 |
+
pass
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class TqdmDefaultWriteLock:
|
| 75 |
+
"""
|
| 76 |
+
Provide a default write lock for thread and multiprocessing safety.
|
| 77 |
+
Works only on platforms supporting `fork` (so Windows is excluded).
|
| 78 |
+
You must initialise a `tqdm` or `TqdmDefaultWriteLock` instance
|
| 79 |
+
before forking in order for the write lock to work.
|
| 80 |
+
On Windows, you need to supply the lock from the parent to the children as
|
| 81 |
+
an argument to joblib or the parallelism lib you use.
|
| 82 |
+
"""
|
| 83 |
+
# global thread lock so no setup required for multithreading.
|
| 84 |
+
# NB: Do not create multiprocessing lock as it sets the multiprocessing
|
| 85 |
+
# context, disallowing `spawn()`/`forkserver()`
|
| 86 |
+
th_lock = TRLock()
|
| 87 |
+
|
| 88 |
+
def __init__(self):
|
| 89 |
+
# Create global parallelism locks to avoid racing issues with parallel
|
| 90 |
+
# bars works only if fork available (Linux/MacOSX, but not Windows)
|
| 91 |
+
cls = type(self)
|
| 92 |
+
root_lock = cls.th_lock
|
| 93 |
+
if root_lock is not None:
|
| 94 |
+
root_lock.acquire()
|
| 95 |
+
cls.create_mp_lock()
|
| 96 |
+
self.locks = [lk for lk in [cls.mp_lock, cls.th_lock] if lk is not None]
|
| 97 |
+
if root_lock is not None:
|
| 98 |
+
root_lock.release()
|
| 99 |
+
|
| 100 |
+
def acquire(self, *a, **k):
|
| 101 |
+
for lock in self.locks:
|
| 102 |
+
lock.acquire(*a, **k)
|
| 103 |
+
|
| 104 |
+
def release(self):
|
| 105 |
+
for lock in self.locks[::-1]: # Release in inverse order of acquisition
|
| 106 |
+
lock.release()
|
| 107 |
+
|
| 108 |
+
def __enter__(self):
|
| 109 |
+
self.acquire()
|
| 110 |
+
|
| 111 |
+
def __exit__(self, *exc):
|
| 112 |
+
self.release()
|
| 113 |
+
|
| 114 |
+
@classmethod
|
| 115 |
+
def create_mp_lock(cls):
|
| 116 |
+
if not hasattr(cls, 'mp_lock'):
|
| 117 |
+
try:
|
| 118 |
+
from multiprocessing import RLock
|
| 119 |
+
cls.mp_lock = RLock()
|
| 120 |
+
except (ImportError, OSError): # pragma: no cover
|
| 121 |
+
cls.mp_lock = None
|
| 122 |
+
|
| 123 |
+
@classmethod
|
| 124 |
+
def create_th_lock(cls):
|
| 125 |
+
assert hasattr(cls, 'th_lock')
|
| 126 |
+
warn("create_th_lock not needed anymore", TqdmDeprecationWarning, stacklevel=2)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
class Bar:
|
| 130 |
+
"""
|
| 131 |
+
`str.format`-able bar with format specifiers: `[width][type]`
|
| 132 |
+
|
| 133 |
+
- `width`
|
| 134 |
+
+ unspecified (default): use `self.default_len`
|
| 135 |
+
+ `int >= 0`: overrides `self.default_len`
|
| 136 |
+
+ `int < 0`: subtract from `self.default_len`
|
| 137 |
+
- `type`
|
| 138 |
+
+ `a`: ascii (`charset=self.ASCII` override)
|
| 139 |
+
+ `u`: unicode (`charset=self.UTF` override)
|
| 140 |
+
+ `b`: blank (`charset=" "` override)
|
| 141 |
+
"""
|
| 142 |
+
ASCII = " 123456789#"
|
| 143 |
+
UTF = " " + ''.join(map(chr, range(0x258F, 0x2587, -1)))
|
| 144 |
+
BLANK = " "
|
| 145 |
+
COLOUR_RESET = '\x1b[0m'
|
| 146 |
+
COLOUR_RGB = '\x1b[38;2;%d;%d;%dm'
|
| 147 |
+
COLOURS = {'BLACK': '\x1b[30m', 'RED': '\x1b[31m', 'GREEN': '\x1b[32m',
|
| 148 |
+
'YELLOW': '\x1b[33m', 'BLUE': '\x1b[34m', 'MAGENTA': '\x1b[35m',
|
| 149 |
+
'CYAN': '\x1b[36m', 'WHITE': '\x1b[37m'}
|
| 150 |
+
|
| 151 |
+
def __init__(self, frac, default_len=10, charset=UTF, colour=None):
|
| 152 |
+
if not 0 <= frac <= 1:
|
| 153 |
+
warn("clamping frac to range [0, 1]", TqdmWarning, stacklevel=2)
|
| 154 |
+
frac = max(0, min(1, frac))
|
| 155 |
+
assert default_len > 0
|
| 156 |
+
self.frac = frac
|
| 157 |
+
self.default_len = default_len
|
| 158 |
+
self.charset = charset
|
| 159 |
+
self.colour = colour
|
| 160 |
+
|
| 161 |
+
@property
|
| 162 |
+
def colour(self):
|
| 163 |
+
return self._colour
|
| 164 |
+
|
| 165 |
+
@colour.setter
|
| 166 |
+
def colour(self, value):
|
| 167 |
+
if not value:
|
| 168 |
+
self._colour = None
|
| 169 |
+
return
|
| 170 |
+
try:
|
| 171 |
+
if value.upper() in self.COLOURS:
|
| 172 |
+
self._colour = self.COLOURS[value.upper()]
|
| 173 |
+
elif value[0] == '#' and len(value) == 7:
|
| 174 |
+
self._colour = self.COLOUR_RGB % tuple(
|
| 175 |
+
int(i, 16) for i in (value[1:3], value[3:5], value[5:7]))
|
| 176 |
+
else:
|
| 177 |
+
raise KeyError
|
| 178 |
+
except (KeyError, AttributeError):
|
| 179 |
+
warn(f"Unknown colour ({value}); valid choices:"
|
| 180 |
+
f" [hex (#00ff00), {', '.join(self.COLOURS)}]", TqdmWarning, stacklevel=2)
|
| 181 |
+
self._colour = None
|
| 182 |
+
|
| 183 |
+
def __format__(self, format_spec):
|
| 184 |
+
if format_spec:
|
| 185 |
+
_type = format_spec[-1].lower()
|
| 186 |
+
try:
|
| 187 |
+
charset = {'a': self.ASCII, 'u': self.UTF, 'b': self.BLANK}[_type]
|
| 188 |
+
except KeyError:
|
| 189 |
+
charset = self.charset
|
| 190 |
+
else:
|
| 191 |
+
format_spec = format_spec[:-1]
|
| 192 |
+
if format_spec:
|
| 193 |
+
N_BARS = int(format_spec)
|
| 194 |
+
if N_BARS < 0:
|
| 195 |
+
N_BARS += self.default_len
|
| 196 |
+
else:
|
| 197 |
+
N_BARS = self.default_len
|
| 198 |
+
else:
|
| 199 |
+
charset = self.charset
|
| 200 |
+
N_BARS = self.default_len
|
| 201 |
+
|
| 202 |
+
nsyms = len(charset) - 1
|
| 203 |
+
bar_length, frac_bar_length = divmod(int(self.frac * N_BARS * nsyms), nsyms)
|
| 204 |
+
|
| 205 |
+
res = charset[-1] * bar_length
|
| 206 |
+
if bar_length < N_BARS: # whitespace padding
|
| 207 |
+
res = res + charset[frac_bar_length] + charset[0] * (N_BARS - bar_length - 1)
|
| 208 |
+
return self.colour + res + self.COLOUR_RESET if self.colour else res
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
class EMA:
|
| 212 |
+
"""
|
| 213 |
+
Exponential moving average: smoothing to give progressively lower
|
| 214 |
+
weights to older values.
|
| 215 |
+
|
| 216 |
+
Parameters
|
| 217 |
+
----------
|
| 218 |
+
smoothing : float, optional
|
| 219 |
+
Smoothing factor in range [0, 1], [default: 0.3].
|
| 220 |
+
Increase to give more weight to recent values.
|
| 221 |
+
Ranges from 0 (yields old value) to 1 (yields new value).
|
| 222 |
+
"""
|
| 223 |
+
def __init__(self, smoothing=0.3):
|
| 224 |
+
self.alpha = smoothing
|
| 225 |
+
self.last = 0
|
| 226 |
+
self.calls = 0
|
| 227 |
+
|
| 228 |
+
def __call__(self, x=None):
|
| 229 |
+
"""
|
| 230 |
+
Parameters
|
| 231 |
+
----------
|
| 232 |
+
x : float
|
| 233 |
+
New value to include in EMA.
|
| 234 |
+
"""
|
| 235 |
+
beta = 1 - self.alpha
|
| 236 |
+
if x is not None:
|
| 237 |
+
self.last = self.alpha * x + beta * self.last
|
| 238 |
+
self.calls += 1
|
| 239 |
+
return self.last / (1 - beta ** self.calls) if self.calls else self.last
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
class tqdm(Comparable):
|
| 243 |
+
"""
|
| 244 |
+
Decorate an iterable object, returning an iterator which acts exactly
|
| 245 |
+
like the original iterable, but prints a dynamically updating
|
| 246 |
+
progress bar every time a value is requested.
|
| 247 |
+
|
| 248 |
+
Parameters
|
| 249 |
+
----------
|
| 250 |
+
iterable : iterable, optional
|
| 251 |
+
Iterable to decorate with a progress bar.
|
| 252 |
+
Leave blank to manually manage the updates.
|
| 253 |
+
desc : str, optional
|
| 254 |
+
Prefix for the progress bar.
|
| 255 |
+
total : int or float, optional
|
| 256 |
+
The number of expected iterations. If unspecified,
|
| 257 |
+
len(iterable) is used if possible. If float("inf") or as a last
|
| 258 |
+
resort, only basic progress statistics are displayed
|
| 259 |
+
(no ETA, no progress bar).
|
| 260 |
+
If `gui` is True and this parameter needs subsequent updating,
|
| 261 |
+
specify an initial arbitrary large positive number,
|
| 262 |
+
e.g. 9e9.
|
| 263 |
+
leave : bool, optional
|
| 264 |
+
If [default: True], keeps all traces of the progress bar
|
| 265 |
+
upon termination of iteration.
|
| 266 |
+
If `None`, will leave only if `position` is `0`.
|
| 267 |
+
file : `io.TextIOWrapper` or `io.StringIO`, optional
|
| 268 |
+
Specifies where to output the progress messages
|
| 269 |
+
(default: sys.stderr). Uses `file.write(str)` and `file.flush()`
|
| 270 |
+
methods. For encoding, see `write_bytes`.
|
| 271 |
+
ncols : int, optional
|
| 272 |
+
The width of the entire output message. If specified,
|
| 273 |
+
dynamically resizes the progress bar to stay within this bound.
|
| 274 |
+
If unspecified, attempts to use environment width. The
|
| 275 |
+
fallback is a meter width of 10 and no limit for the counter and
|
| 276 |
+
statistics. If 0, will not print any meter (only stats).
|
| 277 |
+
mininterval : float, optional
|
| 278 |
+
Minimum progress display update interval [default: 0.1] seconds.
|
| 279 |
+
maxinterval : float, optional
|
| 280 |
+
Maximum progress display update interval [default: 10] seconds.
|
| 281 |
+
Automatically adjusts `miniters` to correspond to `mininterval`
|
| 282 |
+
after long display update lag. Only works if `dynamic_miniters`
|
| 283 |
+
or monitor thread is enabled.
|
| 284 |
+
miniters : int or float, optional
|
| 285 |
+
Minimum progress display update interval, in iterations.
|
| 286 |
+
If 0 and `dynamic_miniters`, will automatically adjust to equal
|
| 287 |
+
`mininterval` (more CPU efficient, good for tight loops).
|
| 288 |
+
If > 0, will skip display of specified number of iterations.
|
| 289 |
+
Tweak this and `mininterval` to get very efficient loops.
|
| 290 |
+
If your progress is erratic with both fast and slow iterations
|
| 291 |
+
(network, skipping items, etc) you should set miniters=1.
|
| 292 |
+
ascii : bool or str, optional
|
| 293 |
+
If unspecified or False, use unicode (smooth blocks) to fill
|
| 294 |
+
the meter. The fallback is to use ASCII characters " 123456789#".
|
| 295 |
+
disable : bool, optional
|
| 296 |
+
Whether to disable the entire progress bar wrapper
|
| 297 |
+
[default: False]. If set to None, disable on non-TTY.
|
| 298 |
+
unit : str, optional
|
| 299 |
+
String that will be used to define the unit of each iteration
|
| 300 |
+
[default: it].
|
| 301 |
+
unit_scale : bool or int or float, optional
|
| 302 |
+
If 1 or True, the number of iterations will be reduced/scaled
|
| 303 |
+
automatically and a metric prefix following the
|
| 304 |
+
International System of Units standard will be added
|
| 305 |
+
(kilo, mega, etc.) [default: False]. If any other non-zero
|
| 306 |
+
number, will scale `total` and `n`.
|
| 307 |
+
dynamic_ncols : bool, optional
|
| 308 |
+
If set, constantly alters `ncols` and `nrows` to the
|
| 309 |
+
environment (allowing for window resizes) [default: False].
|
| 310 |
+
smoothing : float, optional
|
| 311 |
+
Exponential moving average smoothing factor for speed estimates
|
| 312 |
+
(ignored in GUI mode). Ranges from 0 (average speed) to 1
|
| 313 |
+
(current/instantaneous speed) [default: 0.3].
|
| 314 |
+
bar_format : str, optional
|
| 315 |
+
Specify a custom bar string formatting. May impact performance.
|
| 316 |
+
[default: '{l_bar}{bar}{r_bar}'], where
|
| 317 |
+
l_bar='{desc}: {percentage:3.0f}%|' and
|
| 318 |
+
r_bar='| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, '
|
| 319 |
+
'{rate_fmt}{postfix}]'
|
| 320 |
+
Possible vars: l_bar, bar, r_bar, n, n_fmt, total, total_fmt,
|
| 321 |
+
percentage, elapsed, elapsed_s, ncols, nrows, desc, unit,
|
| 322 |
+
rate, rate_fmt, rate_noinv, rate_noinv_fmt,
|
| 323 |
+
rate_inv, rate_inv_fmt, postfix, unit_divisor,
|
| 324 |
+
remaining, remaining_s, eta.
|
| 325 |
+
Note that a trailing ": " is automatically removed after {desc}
|
| 326 |
+
if the latter is empty.
|
| 327 |
+
initial : int or float, optional
|
| 328 |
+
The initial counter value. Useful when restarting a progress
|
| 329 |
+
bar [default: 0]. If using float, consider specifying `{n:.3f}`
|
| 330 |
+
or similar in `bar_format`, or specifying `unit_scale`.
|
| 331 |
+
position : int, optional
|
| 332 |
+
Specify the line offset to print this bar (starting from 0)
|
| 333 |
+
Automatic if unspecified.
|
| 334 |
+
Useful to manage multiple bars at once (eg, from threads).
|
| 335 |
+
postfix : dict or *, optional
|
| 336 |
+
Specify additional stats to display at the end of the bar.
|
| 337 |
+
Calls `set_postfix(**postfix)` if possible (dict).
|
| 338 |
+
unit_divisor : float, optional
|
| 339 |
+
[default: 1000], ignored unless `unit_scale` is True.
|
| 340 |
+
write_bytes : bool, optional
|
| 341 |
+
Whether to write bytes. If (default: False) will write unicode.
|
| 342 |
+
lock_args : tuple, optional
|
| 343 |
+
Passed to `refresh` for intermediate output
|
| 344 |
+
(initialisation, iterating, and updating).
|
| 345 |
+
nrows : int, optional
|
| 346 |
+
The screen height. If specified, hides nested bars outside this
|
| 347 |
+
bound. If unspecified, attempts to use environment height.
|
| 348 |
+
The fallback is 20.
|
| 349 |
+
colour : str, optional
|
| 350 |
+
Bar colour (e.g. 'green', '#00ff00').
|
| 351 |
+
delay : float, optional
|
| 352 |
+
Don't display until [default: 0] seconds have elapsed.
|
| 353 |
+
gui : bool, optional
|
| 354 |
+
WARNING: internal parameter - do not use.
|
| 355 |
+
Use tqdm.gui.tqdm(...) instead. If set, will attempt to use
|
| 356 |
+
matplotlib animations for a graphical output [default: False].
|
| 357 |
+
|
| 358 |
+
Returns
|
| 359 |
+
-------
|
| 360 |
+
out : decorated iterator.
|
| 361 |
+
"""
|
| 362 |
+
|
| 363 |
+
monitor_interval = 10 # set to 0 to disable the thread
|
| 364 |
+
monitor = None
|
| 365 |
+
_instances = WeakSet()
|
| 366 |
+
|
| 367 |
+
@staticmethod
|
| 368 |
+
def format_sizeof(num, suffix='', divisor=1000):
|
| 369 |
+
"""
|
| 370 |
+
Formats a number (greater than unity) with SI Order of Magnitude
|
| 371 |
+
prefixes.
|
| 372 |
+
|
| 373 |
+
Parameters
|
| 374 |
+
----------
|
| 375 |
+
num : float
|
| 376 |
+
Number ( >= 1) to format.
|
| 377 |
+
suffix : str, optional
|
| 378 |
+
Post-postfix [default: ''].
|
| 379 |
+
divisor : float, optional
|
| 380 |
+
Divisor between prefixes [default: 1000].
|
| 381 |
+
|
| 382 |
+
Returns
|
| 383 |
+
-------
|
| 384 |
+
out : str
|
| 385 |
+
Number with Order of Magnitude SI unit postfix.
|
| 386 |
+
"""
|
| 387 |
+
for unit in ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z']:
|
| 388 |
+
if abs(num) < 999.5:
|
| 389 |
+
if abs(num) < 99.95:
|
| 390 |
+
if abs(num) < 9.995:
|
| 391 |
+
return f'{num:1.2f}{unit}{suffix}'
|
| 392 |
+
return f'{num:2.1f}{unit}{suffix}'
|
| 393 |
+
return f'{num:3.0f}{unit}{suffix}'
|
| 394 |
+
num /= divisor
|
| 395 |
+
return f'{num:3.1f}Y{suffix}'
|
| 396 |
+
|
| 397 |
+
@staticmethod
|
| 398 |
+
def format_interval(t):
|
| 399 |
+
"""
|
| 400 |
+
Formats a number of seconds as a clock time, [H:]MM:SS
|
| 401 |
+
|
| 402 |
+
Parameters
|
| 403 |
+
----------
|
| 404 |
+
t : int
|
| 405 |
+
Number of seconds.
|
| 406 |
+
|
| 407 |
+
Returns
|
| 408 |
+
-------
|
| 409 |
+
out : str
|
| 410 |
+
[H:]MM:SS
|
| 411 |
+
"""
|
| 412 |
+
sign = '-' if t < 0 else ''
|
| 413 |
+
mins, s = divmod(abs(int(t)), 60)
|
| 414 |
+
h, m = divmod(mins, 60)
|
| 415 |
+
return f'{sign}{h:d}:{m:02d}:{s:02d}' if h else f'{sign}{m:02d}:{s:02d}'
|
| 416 |
+
|
| 417 |
+
@staticmethod
|
| 418 |
+
def format_num(n):
|
| 419 |
+
"""
|
| 420 |
+
Intelligent scientific notation (.3g).
|
| 421 |
+
|
| 422 |
+
Parameters
|
| 423 |
+
----------
|
| 424 |
+
n : int or float or Numeric
|
| 425 |
+
A Number.
|
| 426 |
+
|
| 427 |
+
Returns
|
| 428 |
+
-------
|
| 429 |
+
out : str
|
| 430 |
+
Formatted number.
|
| 431 |
+
"""
|
| 432 |
+
f = f'{n:.3g}'.replace('e+0', 'e+').replace('e-0', 'e-')
|
| 433 |
+
n = str(n)
|
| 434 |
+
return f if len(f) < len(n) else n
|
| 435 |
+
|
| 436 |
+
@staticmethod
|
| 437 |
+
def status_printer(file):
|
| 438 |
+
"""
|
| 439 |
+
Manage the printing and in-place updating of a line of characters.
|
| 440 |
+
Note that if the string is longer than a line, then in-place
|
| 441 |
+
updating may not work (it will print a new line at each refresh).
|
| 442 |
+
"""
|
| 443 |
+
fp = file
|
| 444 |
+
fp_flush = getattr(fp, 'flush', lambda: None) # pragma: no cover
|
| 445 |
+
if fp in (sys.stderr, sys.stdout):
|
| 446 |
+
getattr(sys.stderr, 'flush', lambda: None)()
|
| 447 |
+
getattr(sys.stdout, 'flush', lambda: None)()
|
| 448 |
+
|
| 449 |
+
def fp_write(s):
|
| 450 |
+
fp.write(str(s))
|
| 451 |
+
fp_flush()
|
| 452 |
+
|
| 453 |
+
last_len = [0]
|
| 454 |
+
|
| 455 |
+
def print_status(s):
|
| 456 |
+
len_s = disp_len(s)
|
| 457 |
+
fp_write('\r' + s + (' ' * max(last_len[0] - len_s, 0)))
|
| 458 |
+
last_len[0] = len_s
|
| 459 |
+
|
| 460 |
+
return print_status
|
| 461 |
+
|
| 462 |
+
@staticmethod
|
| 463 |
+
def format_meter(n, total, elapsed, ncols=None, prefix='',
|
| 464 |
+
ascii=False, # pylint: disable=redefined-builtin
|
| 465 |
+
unit='it', unit_scale=False, rate=None, bar_format=None, postfix=None,
|
| 466 |
+
unit_divisor=1000, initial=0, colour=None, **extra_kwargs):
|
| 467 |
+
"""
|
| 468 |
+
Return a string-based progress bar given some parameters
|
| 469 |
+
|
| 470 |
+
Parameters
|
| 471 |
+
----------
|
| 472 |
+
n : int or float
|
| 473 |
+
Number of finished iterations.
|
| 474 |
+
total : int or float
|
| 475 |
+
The expected total number of iterations. If meaningless (None),
|
| 476 |
+
only basic progress statistics are displayed (no ETA).
|
| 477 |
+
elapsed : float
|
| 478 |
+
Number of seconds passed since start.
|
| 479 |
+
ncols : int, optional
|
| 480 |
+
The width of the entire output message. If specified,
|
| 481 |
+
dynamically resizes `{bar}` to stay within this bound
|
| 482 |
+
[default: None]. If `0`, will not print any bar (only stats).
|
| 483 |
+
The fallback is `{bar:10}`.
|
| 484 |
+
prefix : str, optional
|
| 485 |
+
Prefix message (included in total width) [default: ''].
|
| 486 |
+
Use as {desc} in bar_format string.
|
| 487 |
+
ascii : bool, optional or str, optional
|
| 488 |
+
If not set, use unicode (smooth blocks) to fill the meter
|
| 489 |
+
[default: False]. The fallback is to use ASCII characters
|
| 490 |
+
" 123456789#".
|
| 491 |
+
unit : str, optional
|
| 492 |
+
The iteration unit [default: 'it'].
|
| 493 |
+
unit_scale : bool or int or float, optional
|
| 494 |
+
If 1 or True, the number of iterations will be printed with an
|
| 495 |
+
appropriate SI metric prefix (k = 10^3, M = 10^6, etc.)
|
| 496 |
+
[default: False]. If any other non-zero number, will scale
|
| 497 |
+
`total` and `n`.
|
| 498 |
+
rate : float, optional
|
| 499 |
+
Manual override for iteration rate.
|
| 500 |
+
If [default: None], uses n/elapsed.
|
| 501 |
+
bar_format : str, optional
|
| 502 |
+
Specify a custom bar string formatting. May impact performance.
|
| 503 |
+
[default: '{l_bar}{bar}{r_bar}'], where
|
| 504 |
+
l_bar='{desc}: {percentage:3.0f}%|' and
|
| 505 |
+
r_bar='| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, '
|
| 506 |
+
'{rate_fmt}{postfix}]'
|
| 507 |
+
Possible vars: l_bar, bar, r_bar, n, n_fmt, total, total_fmt,
|
| 508 |
+
percentage, elapsed, elapsed_s, ncols, nrows, desc, unit,
|
| 509 |
+
rate, rate_fmt, rate_noinv, rate_noinv_fmt,
|
| 510 |
+
rate_inv, rate_inv_fmt, postfix, unit_divisor,
|
| 511 |
+
remaining, remaining_s, eta.
|
| 512 |
+
Note that a trailing ": " is automatically removed after {desc}
|
| 513 |
+
if the latter is empty.
|
| 514 |
+
postfix : *, optional
|
| 515 |
+
Similar to `prefix`, but placed at the end
|
| 516 |
+
(e.g. for additional stats).
|
| 517 |
+
Note: postfix is usually a string (not a dict) for this method,
|
| 518 |
+
and will if possible be set to postfix = ', ' + postfix.
|
| 519 |
+
However other types are supported (#382).
|
| 520 |
+
unit_divisor : float, optional
|
| 521 |
+
[default: 1000], ignored unless `unit_scale` is True.
|
| 522 |
+
initial : int or float, optional
|
| 523 |
+
The initial counter value [default: 0].
|
| 524 |
+
colour : str, optional
|
| 525 |
+
Bar colour (e.g. 'green', '#00ff00').
|
| 526 |
+
|
| 527 |
+
Returns
|
| 528 |
+
-------
|
| 529 |
+
out : Formatted meter and stats, ready to display.
|
| 530 |
+
"""
|
| 531 |
+
|
| 532 |
+
# sanity check: total
|
| 533 |
+
if total and (n >= (total + 0.5) or total == float("inf")):
|
| 534 |
+
# allow float imprecision (#849) or inf (#651)
|
| 535 |
+
total = None
|
| 536 |
+
|
| 537 |
+
# apply custom scale if necessary
|
| 538 |
+
if unit_scale and unit_scale not in (True, 1):
|
| 539 |
+
if total:
|
| 540 |
+
total *= unit_scale
|
| 541 |
+
n *= unit_scale
|
| 542 |
+
if rate:
|
| 543 |
+
rate *= unit_scale # by default rate = self.avg_dn / self.avg_dt
|
| 544 |
+
unit_scale = False
|
| 545 |
+
|
| 546 |
+
elapsed_str = tqdm.format_interval(elapsed)
|
| 547 |
+
|
| 548 |
+
# if unspecified, attempt to use rate = average speed
|
| 549 |
+
# (we allow manual override since predicting time is an arcane art)
|
| 550 |
+
if rate is None and elapsed:
|
| 551 |
+
rate = (n - initial) / elapsed
|
| 552 |
+
inv_rate = 1 / rate if rate else None
|
| 553 |
+
format_sizeof = tqdm.format_sizeof
|
| 554 |
+
rate_noinv_fmt = ((format_sizeof(rate) if unit_scale else f'{rate:5.2f}')
|
| 555 |
+
if rate else '?') + unit + '/s'
|
| 556 |
+
rate_inv_fmt = (
|
| 557 |
+
(format_sizeof(inv_rate) if unit_scale else f'{inv_rate:5.2f}')
|
| 558 |
+
if inv_rate else '?') + 's/' + unit
|
| 559 |
+
rate_fmt = rate_inv_fmt if inv_rate and inv_rate > 1 else rate_noinv_fmt
|
| 560 |
+
|
| 561 |
+
if unit_scale:
|
| 562 |
+
n_fmt = format_sizeof(n, divisor=unit_divisor)
|
| 563 |
+
total_fmt = format_sizeof(total, divisor=unit_divisor) if total is not None else '?'
|
| 564 |
+
else:
|
| 565 |
+
n_fmt = str(n)
|
| 566 |
+
total_fmt = str(total) if total is not None else '?'
|
| 567 |
+
|
| 568 |
+
try:
|
| 569 |
+
postfix = ', ' + postfix if postfix else ''
|
| 570 |
+
except TypeError:
|
| 571 |
+
pass
|
| 572 |
+
|
| 573 |
+
remaining = (total - n) / rate if rate and total else 0
|
| 574 |
+
remaining_str = tqdm.format_interval(remaining) if rate else '?'
|
| 575 |
+
try:
|
| 576 |
+
eta_dt = (datetime.now() + timedelta(seconds=remaining)
|
| 577 |
+
if rate and total else datetime.fromtimestamp(0, timezone.utc))
|
| 578 |
+
except OverflowError:
|
| 579 |
+
eta_dt = datetime.max
|
| 580 |
+
|
| 581 |
+
# format the stats displayed to the left and right sides of the bar
|
| 582 |
+
if prefix:
|
| 583 |
+
# old prefix setup work around
|
| 584 |
+
bool_prefix_colon_already = (prefix[-2:] == ": ")
|
| 585 |
+
l_bar = prefix if bool_prefix_colon_already else prefix + ": "
|
| 586 |
+
else:
|
| 587 |
+
l_bar = ''
|
| 588 |
+
|
| 589 |
+
r_bar = f'| {n_fmt}/{total_fmt} [{elapsed_str}<{remaining_str}, {rate_fmt}{postfix}]'
|
| 590 |
+
|
| 591 |
+
# Custom bar formatting
|
| 592 |
+
# Populate a dict with all available progress indicators
|
| 593 |
+
format_dict = {
|
| 594 |
+
# slight extension of self.format_dict
|
| 595 |
+
'n': n, 'n_fmt': n_fmt, 'total': total, 'total_fmt': total_fmt,
|
| 596 |
+
'elapsed': elapsed_str, 'elapsed_s': elapsed,
|
| 597 |
+
'ncols': ncols, 'desc': prefix or '', 'unit': unit,
|
| 598 |
+
'rate': inv_rate if inv_rate and inv_rate > 1 else rate,
|
| 599 |
+
'rate_fmt': rate_fmt, 'rate_noinv': rate,
|
| 600 |
+
'rate_noinv_fmt': rate_noinv_fmt, 'rate_inv': inv_rate,
|
| 601 |
+
'rate_inv_fmt': rate_inv_fmt,
|
| 602 |
+
'postfix': postfix, 'unit_divisor': unit_divisor,
|
| 603 |
+
'colour': colour,
|
| 604 |
+
# plus more useful definitions
|
| 605 |
+
'remaining': remaining_str, 'remaining_s': remaining,
|
| 606 |
+
'l_bar': l_bar, 'r_bar': r_bar, 'eta': eta_dt,
|
| 607 |
+
**extra_kwargs}
|
| 608 |
+
|
| 609 |
+
# total is known: we can predict some stats
|
| 610 |
+
if total:
|
| 611 |
+
# fractional and percentage progress
|
| 612 |
+
frac = n / total
|
| 613 |
+
percentage = frac * 100
|
| 614 |
+
|
| 615 |
+
l_bar += f'{percentage:3.0f}%|'
|
| 616 |
+
|
| 617 |
+
if ncols == 0:
|
| 618 |
+
return l_bar[:-1] + r_bar[1:]
|
| 619 |
+
|
| 620 |
+
format_dict.update(l_bar=l_bar)
|
| 621 |
+
if bar_format:
|
| 622 |
+
format_dict.update(percentage=percentage)
|
| 623 |
+
|
| 624 |
+
# auto-remove colon for empty `{desc}`
|
| 625 |
+
if not prefix:
|
| 626 |
+
bar_format = bar_format.replace("{desc}: ", '')
|
| 627 |
+
else:
|
| 628 |
+
bar_format = "{l_bar}{bar}{r_bar}"
|
| 629 |
+
|
| 630 |
+
full_bar = FormatReplace()
|
| 631 |
+
nobar = bar_format.format(bar=full_bar, **format_dict) # no `{bar}`
|
| 632 |
+
if not full_bar.format_called:
|
| 633 |
+
return disp_trim(nobar, ncols) if ncols else nobar
|
| 634 |
+
|
| 635 |
+
# Formatting progress bar space available for bar's display
|
| 636 |
+
full_bar = Bar(frac,
|
| 637 |
+
max(1, ncols - disp_len(nobar)) if ncols else 10,
|
| 638 |
+
charset=Bar.ASCII if ascii is True else ascii or Bar.UTF,
|
| 639 |
+
colour=colour)
|
| 640 |
+
if not _is_ascii(full_bar.charset) and _is_ascii(bar_format):
|
| 641 |
+
bar_format = str(bar_format)
|
| 642 |
+
res = bar_format.format(bar=full_bar, **format_dict)
|
| 643 |
+
return disp_trim(res, ncols) if ncols else res
|
| 644 |
+
|
| 645 |
+
elif bar_format:
|
| 646 |
+
# user-specified bar_format but no total
|
| 647 |
+
l_bar += '|'
|
| 648 |
+
format_dict.update(l_bar=l_bar, percentage=0)
|
| 649 |
+
full_bar = FormatReplace()
|
| 650 |
+
nobar = bar_format.format(bar=full_bar, **format_dict)
|
| 651 |
+
if not full_bar.format_called:
|
| 652 |
+
return disp_trim(nobar, ncols) if ncols else nobar
|
| 653 |
+
full_bar = Bar(0,
|
| 654 |
+
max(1, ncols - disp_len(nobar)) if ncols else 10,
|
| 655 |
+
charset=Bar.BLANK, colour=colour)
|
| 656 |
+
res = bar_format.format(bar=full_bar, **format_dict)
|
| 657 |
+
return disp_trim(res, ncols) if ncols else res
|
| 658 |
+
else:
|
| 659 |
+
# no total: no bar & ETA, just progress stats
|
| 660 |
+
res = (f'{(prefix + ": ") if prefix else ""}'
|
| 661 |
+
f'{n_fmt}{unit} [{elapsed_str}, {rate_fmt}{postfix}]')
|
| 662 |
+
return disp_trim(res, ncols) if ncols else res
|
| 663 |
+
|
| 664 |
+
def __new__(cls, *_, **__):
|
| 665 |
+
instance = object.__new__(cls)
|
| 666 |
+
with cls.get_lock(): # also constructs lock if non-existent
|
| 667 |
+
cls._instances.add(instance)
|
| 668 |
+
# create monitoring thread
|
| 669 |
+
if cls.monitor_interval and (cls.monitor is None
|
| 670 |
+
or not cls.monitor.report()):
|
| 671 |
+
try:
|
| 672 |
+
cls.monitor = TMonitor(cls, cls.monitor_interval)
|
| 673 |
+
except Exception as e: # pragma: nocover
|
| 674 |
+
warn("tqdm:disabling monitor support"
|
| 675 |
+
" (monitor_interval = 0) due to:\n" + str(e),
|
| 676 |
+
TqdmMonitorWarning, stacklevel=2)
|
| 677 |
+
cls.monitor_interval = 0
|
| 678 |
+
return instance
|
| 679 |
+
|
| 680 |
+
@classmethod
|
| 681 |
+
def _get_free_pos(cls, instance=None):
|
| 682 |
+
"""Skips specified instance."""
|
| 683 |
+
positions = {abs(inst.pos) for inst in cls._instances
|
| 684 |
+
if inst is not instance and hasattr(inst, "pos")}
|
| 685 |
+
return min(set(range(len(positions) + 1)).difference(positions))
|
| 686 |
+
|
| 687 |
+
@classmethod
|
| 688 |
+
def _decr_instances(cls, instance):
|
| 689 |
+
"""
|
| 690 |
+
Remove from list and reposition another unfixed bar
|
| 691 |
+
to fill the new gap.
|
| 692 |
+
|
| 693 |
+
This means that by default (where all nested bars are unfixed),
|
| 694 |
+
order is not maintained but screen flicker/blank space is minimised.
|
| 695 |
+
(tqdm<=4.44.1 moved ALL subsequent unfixed bars up.)
|
| 696 |
+
"""
|
| 697 |
+
with cls._lock:
|
| 698 |
+
try:
|
| 699 |
+
cls._instances.remove(instance)
|
| 700 |
+
except KeyError:
|
| 701 |
+
# if not instance.gui: # pragma: no cover
|
| 702 |
+
# raise
|
| 703 |
+
pass # py2: maybe magically removed already
|
| 704 |
+
# else:
|
| 705 |
+
if not instance.gui:
|
| 706 |
+
last = (instance.nrows or 20) - 1
|
| 707 |
+
# find unfixed (`pos >= 0`) overflow (`pos >= nrows - 1`)
|
| 708 |
+
instances = list(filter(
|
| 709 |
+
lambda i: hasattr(i, "pos") and last <= i.pos,
|
| 710 |
+
cls._instances))
|
| 711 |
+
# set first found to current `pos`
|
| 712 |
+
if instances:
|
| 713 |
+
inst = min(instances, key=lambda i: i.pos)
|
| 714 |
+
inst.clear(nolock=True)
|
| 715 |
+
inst.pos = abs(instance.pos)
|
| 716 |
+
|
| 717 |
+
@classmethod
|
| 718 |
+
def write(cls, s, file=None, end="\n", nolock=False):
|
| 719 |
+
"""Print a message via tqdm (without overlap with bars)."""
|
| 720 |
+
fp = file if file is not None else sys.stdout
|
| 721 |
+
if fp is None:
|
| 722 |
+
return
|
| 723 |
+
with cls.external_write_mode(file=file, nolock=nolock):
|
| 724 |
+
# Write the message
|
| 725 |
+
fp.write(s)
|
| 726 |
+
fp.write(end)
|
| 727 |
+
|
| 728 |
+
@classmethod
|
| 729 |
+
@contextmanager
|
| 730 |
+
def external_write_mode(cls, file=None, nolock=False):
|
| 731 |
+
"""
|
| 732 |
+
Disable tqdm within context and refresh tqdm when exits.
|
| 733 |
+
Useful when writing to standard output stream
|
| 734 |
+
"""
|
| 735 |
+
fp = file if file is not None else sys.stdout
|
| 736 |
+
if fp is None:
|
| 737 |
+
yield
|
| 738 |
+
return
|
| 739 |
+
|
| 740 |
+
try:
|
| 741 |
+
if not nolock:
|
| 742 |
+
cls.get_lock().acquire()
|
| 743 |
+
# Clear all bars
|
| 744 |
+
inst_cleared = []
|
| 745 |
+
for inst in getattr(cls, '_instances', []):
|
| 746 |
+
# Clear instance if in the target output file
|
| 747 |
+
# or if write output + tqdm output are both either
|
| 748 |
+
# sys.stdout or sys.stderr (because both are mixed in terminal)
|
| 749 |
+
if hasattr(inst, "start_t") and (inst.fp == fp or all(
|
| 750 |
+
f in (sys.stdout, sys.stderr) for f in (fp, inst.fp))):
|
| 751 |
+
inst.clear(nolock=True)
|
| 752 |
+
inst_cleared.append(inst)
|
| 753 |
+
yield
|
| 754 |
+
# Force refresh display of bars we cleared
|
| 755 |
+
for inst in inst_cleared:
|
| 756 |
+
inst.refresh(nolock=True)
|
| 757 |
+
finally:
|
| 758 |
+
if not nolock:
|
| 759 |
+
cls._lock.release()
|
| 760 |
+
|
| 761 |
+
@classmethod
|
| 762 |
+
def set_lock(cls, lock):
|
| 763 |
+
"""Set the global lock."""
|
| 764 |
+
cls._lock = lock
|
| 765 |
+
|
| 766 |
+
@classmethod
|
| 767 |
+
def get_lock(cls):
|
| 768 |
+
"""Get the global lock. Construct it if it does not exist."""
|
| 769 |
+
if not hasattr(cls, '_lock'):
|
| 770 |
+
cls._lock = TqdmDefaultWriteLock()
|
| 771 |
+
return cls._lock
|
| 772 |
+
|
| 773 |
+
@classmethod
|
| 774 |
+
def pandas(cls, **tqdm_kwargs):
|
| 775 |
+
"""
|
| 776 |
+
Registers the current `tqdm` class with
|
| 777 |
+
pandas.core.
|
| 778 |
+
( frame.DataFrame
|
| 779 |
+
| series.Series
|
| 780 |
+
| groupby.(generic.)DataFrameGroupBy
|
| 781 |
+
| groupby.(generic.)SeriesGroupBy
|
| 782 |
+
).progress_apply
|
| 783 |
+
|
| 784 |
+
A new instance will be created every time `progress_apply` is called,
|
| 785 |
+
and each instance will automatically `close()` upon completion.
|
| 786 |
+
|
| 787 |
+
Parameters
|
| 788 |
+
----------
|
| 789 |
+
tqdm_kwargs : arguments for the tqdm instance
|
| 790 |
+
|
| 791 |
+
Examples
|
| 792 |
+
--------
|
| 793 |
+
>>> import pandas as pd
|
| 794 |
+
>>> import numpy as np
|
| 795 |
+
>>> from tqdm import tqdm
|
| 796 |
+
>>> from tqdm.gui import tqdm as tqdm_gui
|
| 797 |
+
>>>
|
| 798 |
+
>>> df = pd.DataFrame(np.random.randint(0, 100, (100000, 6)))
|
| 799 |
+
>>> tqdm.pandas(ncols=50) # can use tqdm_gui, optional kwargs, etc
|
| 800 |
+
>>> # Now you can use `progress_apply` instead of `apply`
|
| 801 |
+
>>> df.groupby(0).progress_apply(lambda x: x**2)
|
| 802 |
+
|
| 803 |
+
References
|
| 804 |
+
----------
|
| 805 |
+
<https://stackoverflow.com/questions/18603270/\
|
| 806 |
+
progress-indicator-during-pandas-operations-python>
|
| 807 |
+
"""
|
| 808 |
+
from warnings import catch_warnings, simplefilter
|
| 809 |
+
|
| 810 |
+
from pandas.core.frame import DataFrame
|
| 811 |
+
from pandas.core.series import Series
|
| 812 |
+
try:
|
| 813 |
+
with catch_warnings():
|
| 814 |
+
simplefilter("ignore", category=FutureWarning)
|
| 815 |
+
from pandas import Panel
|
| 816 |
+
except ImportError: # pandas>=1.2.0
|
| 817 |
+
Panel = None
|
| 818 |
+
Rolling, Expanding = None, None
|
| 819 |
+
try: # pandas>=1.0.0
|
| 820 |
+
from pandas.core.window.rolling import _Rolling_and_Expanding
|
| 821 |
+
except ImportError:
|
| 822 |
+
try: # pandas>=0.18.0
|
| 823 |
+
from pandas.core.window import _Rolling_and_Expanding
|
| 824 |
+
except ImportError: # pandas>=1.2.0
|
| 825 |
+
try: # pandas>=1.2.0
|
| 826 |
+
from pandas.core.window.expanding import Expanding
|
| 827 |
+
from pandas.core.window.rolling import Rolling
|
| 828 |
+
_Rolling_and_Expanding = Rolling, Expanding
|
| 829 |
+
except ImportError: # pragma: no cover
|
| 830 |
+
_Rolling_and_Expanding = None
|
| 831 |
+
try: # pandas>=0.25.0
|
| 832 |
+
from pandas.core.groupby.generic import SeriesGroupBy # , NDFrameGroupBy
|
| 833 |
+
from pandas.core.groupby.generic import DataFrameGroupBy
|
| 834 |
+
except ImportError: # pragma: no cover
|
| 835 |
+
try: # pandas>=0.23.0
|
| 836 |
+
from pandas.core.groupby.groupby import DataFrameGroupBy, SeriesGroupBy
|
| 837 |
+
except ImportError:
|
| 838 |
+
from pandas.core.groupby import DataFrameGroupBy, SeriesGroupBy
|
| 839 |
+
try: # pandas>=0.23.0
|
| 840 |
+
from pandas.core.groupby.groupby import GroupBy
|
| 841 |
+
except ImportError: # pragma: no cover
|
| 842 |
+
from pandas.core.groupby import GroupBy
|
| 843 |
+
|
| 844 |
+
try: # pandas>=0.23.0
|
| 845 |
+
from pandas.core.groupby.groupby import PanelGroupBy
|
| 846 |
+
except ImportError:
|
| 847 |
+
try:
|
| 848 |
+
from pandas.core.groupby import PanelGroupBy
|
| 849 |
+
except ImportError: # pandas>=0.25.0
|
| 850 |
+
PanelGroupBy = None
|
| 851 |
+
|
| 852 |
+
tqdm_kwargs = tqdm_kwargs.copy()
|
| 853 |
+
deprecated_t = [tqdm_kwargs.pop('deprecated_t', None)]
|
| 854 |
+
|
| 855 |
+
def inner_generator(df_function='apply'):
|
| 856 |
+
def inner(df, func, *args, **kwargs):
|
| 857 |
+
"""
|
| 858 |
+
Parameters
|
| 859 |
+
----------
|
| 860 |
+
df : (DataFrame|Series)[GroupBy]
|
| 861 |
+
Data (may be grouped).
|
| 862 |
+
func : function
|
| 863 |
+
To be applied on the (grouped) data.
|
| 864 |
+
**kwargs : optional
|
| 865 |
+
Transmitted to `df.apply()`.
|
| 866 |
+
"""
|
| 867 |
+
|
| 868 |
+
# Precompute total iterations
|
| 869 |
+
total = tqdm_kwargs.pop("total", getattr(df, 'ngroups', None))
|
| 870 |
+
if total is None: # not grouped
|
| 871 |
+
if df_function == 'applymap':
|
| 872 |
+
total = df.size
|
| 873 |
+
elif isinstance(df, Series):
|
| 874 |
+
total = len(df)
|
| 875 |
+
elif (_Rolling_and_Expanding is None or
|
| 876 |
+
not isinstance(df, _Rolling_and_Expanding)):
|
| 877 |
+
# DataFrame or Panel
|
| 878 |
+
axis = kwargs.get('axis', 0)
|
| 879 |
+
if axis == 'index':
|
| 880 |
+
axis = 0
|
| 881 |
+
elif axis == 'columns':
|
| 882 |
+
axis = 1
|
| 883 |
+
# when axis=0, total is shape[axis1]
|
| 884 |
+
total = df.size // df.shape[axis]
|
| 885 |
+
|
| 886 |
+
# Init bar
|
| 887 |
+
if deprecated_t[0] is not None:
|
| 888 |
+
t = deprecated_t[0]
|
| 889 |
+
deprecated_t[0] = None
|
| 890 |
+
else:
|
| 891 |
+
t = cls(total=total, **tqdm_kwargs)
|
| 892 |
+
|
| 893 |
+
if len(args) > 0:
|
| 894 |
+
# *args intentionally not supported (see #244, #299)
|
| 895 |
+
TqdmDeprecationWarning(
|
| 896 |
+
"Except func, normal arguments are intentionally" +
|
| 897 |
+
" not supported by" +
|
| 898 |
+
" `(DataFrame|Series|GroupBy).progress_apply`." +
|
| 899 |
+
" Use keyword arguments instead.",
|
| 900 |
+
fp_write=getattr(t.fp, 'write', sys.stderr.write))
|
| 901 |
+
|
| 902 |
+
try: # pandas>=1.3.0,<3.0
|
| 903 |
+
from pandas.core.common import is_builtin_func
|
| 904 |
+
except ImportError: # pandas<1.3.0
|
| 905 |
+
is_builtin_func = getattr(df, '_is_builtin_func', lambda f: f)
|
| 906 |
+
try:
|
| 907 |
+
func = is_builtin_func(func)
|
| 908 |
+
except TypeError:
|
| 909 |
+
pass
|
| 910 |
+
|
| 911 |
+
# Define bar updating wrapper
|
| 912 |
+
def wrapper(*args, **kwargs):
|
| 913 |
+
# update tbar correctly
|
| 914 |
+
# it seems `pandas apply` calls `func` twice
|
| 915 |
+
# on the first column/row to decide whether it can
|
| 916 |
+
# take a fast or slow code path; so stop when t.total==t.n
|
| 917 |
+
t.update(n=1 if not t.total or t.n < t.total else 0)
|
| 918 |
+
return func(*args, **kwargs)
|
| 919 |
+
|
| 920 |
+
# Apply the provided function (in **kwargs)
|
| 921 |
+
# on the df using our wrapper (which provides bar updating)
|
| 922 |
+
try:
|
| 923 |
+
return getattr(df, df_function)(wrapper, **kwargs)
|
| 924 |
+
finally:
|
| 925 |
+
t.close()
|
| 926 |
+
|
| 927 |
+
return inner
|
| 928 |
+
|
| 929 |
+
# Monkeypatch pandas to provide easy methods
|
| 930 |
+
# Enable custom tqdm progress in pandas!
|
| 931 |
+
Series.progress_apply = inner_generator()
|
| 932 |
+
SeriesGroupBy.progress_apply = inner_generator()
|
| 933 |
+
Series.progress_map = inner_generator('map')
|
| 934 |
+
SeriesGroupBy.progress_map = inner_generator('map')
|
| 935 |
+
|
| 936 |
+
DataFrame.progress_apply = inner_generator()
|
| 937 |
+
DataFrameGroupBy.progress_apply = inner_generator()
|
| 938 |
+
DataFrame.progress_applymap = inner_generator('applymap')
|
| 939 |
+
DataFrame.progress_map = inner_generator('map')
|
| 940 |
+
DataFrameGroupBy.progress_map = inner_generator('map')
|
| 941 |
+
|
| 942 |
+
if Panel is not None:
|
| 943 |
+
Panel.progress_apply = inner_generator()
|
| 944 |
+
if PanelGroupBy is not None:
|
| 945 |
+
PanelGroupBy.progress_apply = inner_generator()
|
| 946 |
+
|
| 947 |
+
GroupBy.progress_apply = inner_generator()
|
| 948 |
+
GroupBy.progress_aggregate = inner_generator('aggregate')
|
| 949 |
+
GroupBy.progress_transform = inner_generator('transform')
|
| 950 |
+
|
| 951 |
+
if Rolling is not None and Expanding is not None:
|
| 952 |
+
Rolling.progress_apply = inner_generator()
|
| 953 |
+
Expanding.progress_apply = inner_generator()
|
| 954 |
+
elif _Rolling_and_Expanding is not None:
|
| 955 |
+
_Rolling_and_Expanding.progress_apply = inner_generator()
|
| 956 |
+
|
| 957 |
+
# override defaults via env vars
|
| 958 |
+
@envwrap("tqdm", is_method=True, types={'total': float, 'ncols': int, 'miniters': float,
|
| 959 |
+
'position': int, 'nrows': int})
|
| 960 |
+
def __init__(self, iterable=None, desc=None, total=None, leave=True, file=None,
|
| 961 |
+
ncols=None, mininterval=0.1, maxinterval=10.0, miniters=None,
|
| 962 |
+
ascii=None, # pylint: disable=redefined-builtin
|
| 963 |
+
disable=False, unit='it', unit_scale=False, dynamic_ncols=False, smoothing=0.3,
|
| 964 |
+
bar_format=None, initial=0, position=None, postfix=None, unit_divisor=1000,
|
| 965 |
+
write_bytes=False, lock_args=None, nrows=None, colour=None, delay=0.0, gui=False,
|
| 966 |
+
**kwargs):
|
| 967 |
+
"""see tqdm.tqdm for arguments"""
|
| 968 |
+
if file is None:
|
| 969 |
+
file = sys.stderr
|
| 970 |
+
|
| 971 |
+
if write_bytes:
|
| 972 |
+
# Despite coercing unicode into bytes, py2 sys.std* streams
|
| 973 |
+
# should have bytes written to them.
|
| 974 |
+
file = SimpleTextIOWrapper(
|
| 975 |
+
file, encoding=getattr(file, 'encoding', None) or 'utf-8')
|
| 976 |
+
|
| 977 |
+
file = DisableOnWriteError(file, tqdm_instance=self)
|
| 978 |
+
|
| 979 |
+
if disable is None and hasattr(file, "isatty") and not file.isatty():
|
| 980 |
+
disable = True
|
| 981 |
+
|
| 982 |
+
if total is None and iterable is not None:
|
| 983 |
+
try:
|
| 984 |
+
total = len(iterable)
|
| 985 |
+
except (TypeError, AttributeError):
|
| 986 |
+
total = None
|
| 987 |
+
if total == float("inf"):
|
| 988 |
+
total = None # same as unknown
|
| 989 |
+
|
| 990 |
+
if disable:
|
| 991 |
+
self.iterable = iterable
|
| 992 |
+
self.disable = disable
|
| 993 |
+
with self._lock:
|
| 994 |
+
self.pos = self._get_free_pos(self)
|
| 995 |
+
self._instances.remove(self)
|
| 996 |
+
self.n = initial
|
| 997 |
+
self.total = total
|
| 998 |
+
self.leave = leave
|
| 999 |
+
return
|
| 1000 |
+
|
| 1001 |
+
if kwargs:
|
| 1002 |
+
self.disable = True
|
| 1003 |
+
with self._lock:
|
| 1004 |
+
self.pos = self._get_free_pos(self)
|
| 1005 |
+
self._instances.remove(self)
|
| 1006 |
+
raise (
|
| 1007 |
+
TqdmDeprecationWarning(
|
| 1008 |
+
"`nested` is deprecated and automated.\n"
|
| 1009 |
+
"Use `position` instead for manual control.\n",
|
| 1010 |
+
fp_write=getattr(file, 'write', sys.stderr.write))
|
| 1011 |
+
if "nested" in kwargs else
|
| 1012 |
+
TqdmKeyError("Unknown argument(s): " + str(kwargs)))
|
| 1013 |
+
|
| 1014 |
+
# Preprocess the arguments
|
| 1015 |
+
if (
|
| 1016 |
+
(ncols is None or nrows is None) and (file in (sys.stderr, sys.stdout))
|
| 1017 |
+
) or dynamic_ncols: # pragma: no cover
|
| 1018 |
+
if dynamic_ncols:
|
| 1019 |
+
dynamic_ncols = _screen_shape_wrapper()
|
| 1020 |
+
if dynamic_ncols:
|
| 1021 |
+
ncols, nrows = dynamic_ncols(file)
|
| 1022 |
+
else:
|
| 1023 |
+
_dynamic_ncols = _screen_shape_wrapper()
|
| 1024 |
+
if _dynamic_ncols:
|
| 1025 |
+
_ncols, _nrows = _dynamic_ncols(file)
|
| 1026 |
+
if ncols is None:
|
| 1027 |
+
ncols = _ncols
|
| 1028 |
+
if nrows is None:
|
| 1029 |
+
nrows = _nrows
|
| 1030 |
+
|
| 1031 |
+
if miniters is None:
|
| 1032 |
+
miniters = 0
|
| 1033 |
+
dynamic_miniters = True
|
| 1034 |
+
else:
|
| 1035 |
+
dynamic_miniters = False
|
| 1036 |
+
|
| 1037 |
+
if mininterval is None:
|
| 1038 |
+
mininterval = 0
|
| 1039 |
+
|
| 1040 |
+
if maxinterval is None:
|
| 1041 |
+
maxinterval = 0
|
| 1042 |
+
|
| 1043 |
+
if ascii is None:
|
| 1044 |
+
ascii = not _supports_unicode(file)
|
| 1045 |
+
|
| 1046 |
+
if bar_format and ascii is not True and not _is_ascii(ascii):
|
| 1047 |
+
# Convert bar format into unicode since terminal uses unicode
|
| 1048 |
+
bar_format = str(bar_format)
|
| 1049 |
+
|
| 1050 |
+
if smoothing is None:
|
| 1051 |
+
smoothing = 0
|
| 1052 |
+
|
| 1053 |
+
# Store the arguments
|
| 1054 |
+
self.iterable = iterable
|
| 1055 |
+
self.desc = desc or ''
|
| 1056 |
+
self.total = total
|
| 1057 |
+
self.leave = leave
|
| 1058 |
+
self.fp = file
|
| 1059 |
+
self.ncols = ncols
|
| 1060 |
+
self.nrows = nrows
|
| 1061 |
+
self.mininterval = mininterval
|
| 1062 |
+
self.maxinterval = maxinterval
|
| 1063 |
+
self.miniters = miniters
|
| 1064 |
+
self.dynamic_miniters = dynamic_miniters
|
| 1065 |
+
self.ascii = ascii
|
| 1066 |
+
self.disable = disable
|
| 1067 |
+
self.unit = unit
|
| 1068 |
+
self.unit_scale = unit_scale
|
| 1069 |
+
self.unit_divisor = unit_divisor
|
| 1070 |
+
self.initial = initial
|
| 1071 |
+
self.lock_args = lock_args
|
| 1072 |
+
self.delay = delay
|
| 1073 |
+
self.gui = gui
|
| 1074 |
+
self.dynamic_ncols = dynamic_ncols
|
| 1075 |
+
self.smoothing = smoothing
|
| 1076 |
+
self._ema_dn = EMA(smoothing)
|
| 1077 |
+
self._ema_dt = EMA(smoothing)
|
| 1078 |
+
self._ema_miniters = EMA(smoothing)
|
| 1079 |
+
self.bar_format = bar_format
|
| 1080 |
+
self.postfix = None
|
| 1081 |
+
self.colour = colour
|
| 1082 |
+
self._time = time
|
| 1083 |
+
if postfix:
|
| 1084 |
+
try:
|
| 1085 |
+
self.set_postfix(refresh=False, **postfix)
|
| 1086 |
+
except TypeError:
|
| 1087 |
+
self.postfix = postfix
|
| 1088 |
+
|
| 1089 |
+
# Init the iterations counters
|
| 1090 |
+
self.last_print_n = initial
|
| 1091 |
+
self.n = initial
|
| 1092 |
+
|
| 1093 |
+
# if nested, at initial sp() call we replace '\r' by '\n' to
|
| 1094 |
+
# not overwrite the outer progress bar
|
| 1095 |
+
with self._lock:
|
| 1096 |
+
# mark fixed positions as negative
|
| 1097 |
+
self.pos = self._get_free_pos(self) if position is None else -position
|
| 1098 |
+
|
| 1099 |
+
if not gui:
|
| 1100 |
+
# Initialize the screen printer
|
| 1101 |
+
self.sp = self.status_printer(self.fp)
|
| 1102 |
+
if delay <= 0:
|
| 1103 |
+
self.refresh(lock_args=self.lock_args)
|
| 1104 |
+
|
| 1105 |
+
# Init the time counter
|
| 1106 |
+
self.last_print_t = self._time()
|
| 1107 |
+
# NB: Avoid race conditions by setting start_t at the very end of init
|
| 1108 |
+
self.start_t = self.last_print_t
|
| 1109 |
+
|
| 1110 |
+
def __bool__(self):
|
| 1111 |
+
if self.total is not None:
|
| 1112 |
+
return self.total > 0
|
| 1113 |
+
if self.iterable is None:
|
| 1114 |
+
raise TypeError('bool() undefined when iterable == total == None')
|
| 1115 |
+
return bool(self.iterable)
|
| 1116 |
+
|
| 1117 |
+
def __len__(self):
|
| 1118 |
+
return (
|
| 1119 |
+
self.total if self.iterable is None
|
| 1120 |
+
else self.iterable.shape[0] if hasattr(self.iterable, "shape")
|
| 1121 |
+
else len(self.iterable) if hasattr(self.iterable, "__len__")
|
| 1122 |
+
else self.iterable.__length_hint__() if hasattr(self.iterable, "__length_hint__")
|
| 1123 |
+
else getattr(self, "total", None))
|
| 1124 |
+
|
| 1125 |
+
def __reversed__(self):
|
| 1126 |
+
try:
|
| 1127 |
+
orig = self.iterable
|
| 1128 |
+
except AttributeError:
|
| 1129 |
+
raise TypeError("'tqdm' object is not reversible")
|
| 1130 |
+
else:
|
| 1131 |
+
self.iterable = reversed(self.iterable)
|
| 1132 |
+
return self.__iter__()
|
| 1133 |
+
finally:
|
| 1134 |
+
self.iterable = orig
|
| 1135 |
+
|
| 1136 |
+
def __contains__(self, item):
|
| 1137 |
+
contains = getattr(self.iterable, '__contains__', None)
|
| 1138 |
+
return (contains(item) if contains is not None # pylint: disable=not-callable
|
| 1139 |
+
else item in self.__iter__())
|
| 1140 |
+
|
| 1141 |
+
def __enter__(self):
|
| 1142 |
+
return self
|
| 1143 |
+
|
| 1144 |
+
def __exit__(self, exc_type, exc_value, traceback):
|
| 1145 |
+
try:
|
| 1146 |
+
self.close()
|
| 1147 |
+
except AttributeError:
|
| 1148 |
+
# maybe eager thread cleanup upon external error
|
| 1149 |
+
if (exc_type, exc_value, traceback) == (None, None, None):
|
| 1150 |
+
raise
|
| 1151 |
+
warn("AttributeError ignored", TqdmWarning, stacklevel=2)
|
| 1152 |
+
|
| 1153 |
+
def __del__(self):
|
| 1154 |
+
self.close()
|
| 1155 |
+
|
| 1156 |
+
def __str__(self):
|
| 1157 |
+
return self.format_meter(**self.format_dict)
|
| 1158 |
+
|
| 1159 |
+
@property
|
| 1160 |
+
def _comparable(self):
|
| 1161 |
+
return abs(getattr(self, "pos", 1 << 31))
|
| 1162 |
+
|
| 1163 |
+
def __hash__(self):
|
| 1164 |
+
return id(self)
|
| 1165 |
+
|
| 1166 |
+
def __iter__(self):
|
| 1167 |
+
"""Backward-compatibility to use: for x in tqdm(iterable)"""
|
| 1168 |
+
|
| 1169 |
+
# Inlining instance variables as locals (speed optimisation)
|
| 1170 |
+
iterable = self.iterable
|
| 1171 |
+
|
| 1172 |
+
# If the bar is disabled, then just walk the iterable
|
| 1173 |
+
# (note: keep this check outside the loop for performance)
|
| 1174 |
+
if self.disable:
|
| 1175 |
+
for obj in iterable:
|
| 1176 |
+
yield obj
|
| 1177 |
+
return
|
| 1178 |
+
|
| 1179 |
+
mininterval = self.mininterval
|
| 1180 |
+
last_print_t = self.last_print_t
|
| 1181 |
+
last_print_n = self.last_print_n
|
| 1182 |
+
min_start_t = self.start_t + self.delay
|
| 1183 |
+
n = self.n
|
| 1184 |
+
time = self._time
|
| 1185 |
+
|
| 1186 |
+
try:
|
| 1187 |
+
for obj in iterable:
|
| 1188 |
+
yield obj
|
| 1189 |
+
# Update and possibly print the progress bar.
|
| 1190 |
+
# Note: does not call self.update(1) for speed optimisation.
|
| 1191 |
+
n += 1
|
| 1192 |
+
|
| 1193 |
+
if n - last_print_n >= self.miniters:
|
| 1194 |
+
cur_t = time()
|
| 1195 |
+
dt = cur_t - last_print_t
|
| 1196 |
+
if dt >= mininterval and cur_t >= min_start_t:
|
| 1197 |
+
self.update(n - last_print_n)
|
| 1198 |
+
last_print_n = self.last_print_n
|
| 1199 |
+
last_print_t = self.last_print_t
|
| 1200 |
+
finally:
|
| 1201 |
+
self.n = n
|
| 1202 |
+
self.close()
|
| 1203 |
+
|
| 1204 |
+
def update(self, n=1):
|
| 1205 |
+
"""
|
| 1206 |
+
Manually update the progress bar, useful for streams
|
| 1207 |
+
such as reading files.
|
| 1208 |
+
E.g.:
|
| 1209 |
+
>>> t = tqdm(total=filesize) # Initialise
|
| 1210 |
+
>>> for current_buffer in stream:
|
| 1211 |
+
... ...
|
| 1212 |
+
... t.update(len(current_buffer))
|
| 1213 |
+
>>> t.close()
|
| 1214 |
+
The last line is highly recommended, but possibly not necessary if
|
| 1215 |
+
`t.update()` will be called in such a way that `filesize` will be
|
| 1216 |
+
exactly reached and printed.
|
| 1217 |
+
|
| 1218 |
+
Parameters
|
| 1219 |
+
----------
|
| 1220 |
+
n : int or float, optional
|
| 1221 |
+
Increment to add to the internal counter of iterations
|
| 1222 |
+
[default: 1]. If using float, consider specifying `{n:.3f}`
|
| 1223 |
+
or similar in `bar_format`, or specifying `unit_scale`.
|
| 1224 |
+
|
| 1225 |
+
Returns
|
| 1226 |
+
-------
|
| 1227 |
+
out : bool or None
|
| 1228 |
+
True if a `display()` was triggered.
|
| 1229 |
+
"""
|
| 1230 |
+
if self.disable:
|
| 1231 |
+
return
|
| 1232 |
+
|
| 1233 |
+
if n < 0:
|
| 1234 |
+
self.last_print_n += n # for auto-refresh logic to work
|
| 1235 |
+
self.n += n
|
| 1236 |
+
|
| 1237 |
+
# check counter first to reduce calls to time()
|
| 1238 |
+
if self.n - self.last_print_n >= self.miniters:
|
| 1239 |
+
cur_t = self._time()
|
| 1240 |
+
dt = cur_t - self.last_print_t
|
| 1241 |
+
if dt >= self.mininterval and cur_t >= self.start_t + self.delay:
|
| 1242 |
+
cur_t = self._time()
|
| 1243 |
+
dn = self.n - self.last_print_n # >= n
|
| 1244 |
+
if self.smoothing and dt and dn:
|
| 1245 |
+
# EMA (not just overall average)
|
| 1246 |
+
self._ema_dn(dn)
|
| 1247 |
+
self._ema_dt(dt)
|
| 1248 |
+
self.refresh(lock_args=self.lock_args)
|
| 1249 |
+
if self.dynamic_miniters:
|
| 1250 |
+
# If no `miniters` was specified, adjust automatically to the
|
| 1251 |
+
# maximum iteration rate seen so far between two prints.
|
| 1252 |
+
# e.g.: After running `tqdm.update(5)`, subsequent
|
| 1253 |
+
# calls to `tqdm.update()` will only cause an update after
|
| 1254 |
+
# at least 5 more iterations.
|
| 1255 |
+
if self.maxinterval and dt >= self.maxinterval:
|
| 1256 |
+
self.miniters = dn * (self.mininterval or self.maxinterval) / dt
|
| 1257 |
+
elif self.smoothing:
|
| 1258 |
+
# EMA miniters update
|
| 1259 |
+
self.miniters = self._ema_miniters(
|
| 1260 |
+
dn * (self.mininterval / dt if self.mininterval and dt
|
| 1261 |
+
else 1))
|
| 1262 |
+
else:
|
| 1263 |
+
# max iters between two prints
|
| 1264 |
+
self.miniters = max(self.miniters, dn)
|
| 1265 |
+
|
| 1266 |
+
# Store old values for next call
|
| 1267 |
+
self.last_print_n = self.n
|
| 1268 |
+
self.last_print_t = cur_t
|
| 1269 |
+
return True
|
| 1270 |
+
|
| 1271 |
+
def close(self):
|
| 1272 |
+
"""Cleanup and (if leave=False) close the progress bar."""
|
| 1273 |
+
if getattr(self, 'disable', True):
|
| 1274 |
+
return
|
| 1275 |
+
|
| 1276 |
+
# Prevent multiple closures
|
| 1277 |
+
self.disable = True
|
| 1278 |
+
|
| 1279 |
+
# decrement instance pos and remove from internal set
|
| 1280 |
+
pos = abs(self.pos)
|
| 1281 |
+
self._decr_instances(self)
|
| 1282 |
+
|
| 1283 |
+
if not hasattr(self, 'last_print_t'):
|
| 1284 |
+
return
|
| 1285 |
+
if self.last_print_t < self.start_t + self.delay:
|
| 1286 |
+
# haven't ever displayed; nothing to clear
|
| 1287 |
+
return
|
| 1288 |
+
|
| 1289 |
+
# GUI mode
|
| 1290 |
+
if getattr(self, 'sp', None) is None:
|
| 1291 |
+
return
|
| 1292 |
+
|
| 1293 |
+
# annoyingly, _supports_unicode isn't good enough
|
| 1294 |
+
def fp_write(s):
|
| 1295 |
+
self.fp.write(str(s))
|
| 1296 |
+
|
| 1297 |
+
try:
|
| 1298 |
+
fp_write('')
|
| 1299 |
+
except ValueError as e:
|
| 1300 |
+
if 'closed' in str(e):
|
| 1301 |
+
return
|
| 1302 |
+
raise # pragma: no cover
|
| 1303 |
+
|
| 1304 |
+
leave = pos == 0 if self.leave is None else self.leave
|
| 1305 |
+
|
| 1306 |
+
with self._lock:
|
| 1307 |
+
if leave:
|
| 1308 |
+
# stats for overall rate (no weighted average)
|
| 1309 |
+
self._ema_dt = lambda: None
|
| 1310 |
+
self.display(pos=0)
|
| 1311 |
+
fp_write('\n')
|
| 1312 |
+
else:
|
| 1313 |
+
# clear previous display
|
| 1314 |
+
if self.display(msg='', pos=pos) and not pos:
|
| 1315 |
+
fp_write('\r')
|
| 1316 |
+
|
| 1317 |
+
def clear(self, nolock=False):
|
| 1318 |
+
"""Clear current bar display."""
|
| 1319 |
+
if self.disable:
|
| 1320 |
+
return
|
| 1321 |
+
|
| 1322 |
+
if not nolock:
|
| 1323 |
+
self._lock.acquire()
|
| 1324 |
+
pos = abs(self.pos)
|
| 1325 |
+
if pos < (self.nrows or 20):
|
| 1326 |
+
self.moveto(pos)
|
| 1327 |
+
self.sp('')
|
| 1328 |
+
self.fp.write('\r') # place cursor back at the beginning of line
|
| 1329 |
+
self.moveto(-pos)
|
| 1330 |
+
if not nolock:
|
| 1331 |
+
self._lock.release()
|
| 1332 |
+
|
| 1333 |
+
def refresh(self, nolock=False, lock_args=None):
|
| 1334 |
+
"""
|
| 1335 |
+
Force refresh the display of this bar.
|
| 1336 |
+
|
| 1337 |
+
Parameters
|
| 1338 |
+
----------
|
| 1339 |
+
nolock : bool, optional
|
| 1340 |
+
If `True`, does not lock.
|
| 1341 |
+
If [default: `False`]: calls `acquire()` on internal lock.
|
| 1342 |
+
lock_args : tuple, optional
|
| 1343 |
+
Passed to internal lock's `acquire()`.
|
| 1344 |
+
If specified, will only `display()` if `acquire()` returns `True`.
|
| 1345 |
+
"""
|
| 1346 |
+
if self.disable:
|
| 1347 |
+
return
|
| 1348 |
+
|
| 1349 |
+
if not nolock:
|
| 1350 |
+
if lock_args:
|
| 1351 |
+
if not self._lock.acquire(*lock_args):
|
| 1352 |
+
return False
|
| 1353 |
+
else:
|
| 1354 |
+
self._lock.acquire()
|
| 1355 |
+
self.display()
|
| 1356 |
+
if not nolock:
|
| 1357 |
+
self._lock.release()
|
| 1358 |
+
return True
|
| 1359 |
+
|
| 1360 |
+
def unpause(self):
|
| 1361 |
+
"""Restart tqdm timer from last print time."""
|
| 1362 |
+
if self.disable:
|
| 1363 |
+
return
|
| 1364 |
+
cur_t = self._time()
|
| 1365 |
+
self.start_t += cur_t - self.last_print_t
|
| 1366 |
+
self.last_print_t = cur_t
|
| 1367 |
+
|
| 1368 |
+
def reset(self, total=None):
|
| 1369 |
+
"""
|
| 1370 |
+
Resets to 0 iterations for repeated use.
|
| 1371 |
+
|
| 1372 |
+
Consider combining with `leave=True`.
|
| 1373 |
+
|
| 1374 |
+
Parameters
|
| 1375 |
+
----------
|
| 1376 |
+
total : int or float, optional. Total to use for the new bar.
|
| 1377 |
+
"""
|
| 1378 |
+
self.n = 0
|
| 1379 |
+
if total is not None:
|
| 1380 |
+
self.total = None if total == float("inf") else total
|
| 1381 |
+
if self.disable:
|
| 1382 |
+
return
|
| 1383 |
+
self.last_print_n = 0
|
| 1384 |
+
self.last_print_t = self.start_t = self._time()
|
| 1385 |
+
self._ema_dn = EMA(self.smoothing)
|
| 1386 |
+
self._ema_dt = EMA(self.smoothing)
|
| 1387 |
+
self._ema_miniters = EMA(self.smoothing)
|
| 1388 |
+
self.refresh()
|
| 1389 |
+
|
| 1390 |
+
def set_description(self, desc=None, refresh=True):
|
| 1391 |
+
"""
|
| 1392 |
+
Set/modify description of the progress bar.
|
| 1393 |
+
|
| 1394 |
+
Parameters
|
| 1395 |
+
----------
|
| 1396 |
+
desc : str, optional
|
| 1397 |
+
refresh : bool, optional
|
| 1398 |
+
Forces refresh [default: True].
|
| 1399 |
+
"""
|
| 1400 |
+
self.desc = desc + ': ' if desc else ''
|
| 1401 |
+
if refresh:
|
| 1402 |
+
self.refresh()
|
| 1403 |
+
|
| 1404 |
+
def set_description_str(self, desc=None, refresh=True):
|
| 1405 |
+
"""Set/modify description without ': ' appended."""
|
| 1406 |
+
self.desc = desc or ''
|
| 1407 |
+
if refresh:
|
| 1408 |
+
self.refresh()
|
| 1409 |
+
|
| 1410 |
+
def set_postfix(self, ordered_dict=None, refresh=True, **kwargs):
|
| 1411 |
+
"""
|
| 1412 |
+
Set/modify postfix (additional stats)
|
| 1413 |
+
with automatic formatting based on datatype.
|
| 1414 |
+
|
| 1415 |
+
Parameters
|
| 1416 |
+
----------
|
| 1417 |
+
ordered_dict : dict or OrderedDict, optional
|
| 1418 |
+
refresh : bool, optional
|
| 1419 |
+
Forces refresh [default: True].
|
| 1420 |
+
kwargs : dict, optional
|
| 1421 |
+
"""
|
| 1422 |
+
# Sort in alphabetical order to be more deterministic
|
| 1423 |
+
postfix = OrderedDict([] if ordered_dict is None else ordered_dict)
|
| 1424 |
+
for key in sorted(kwargs.keys()):
|
| 1425 |
+
postfix[key] = kwargs[key]
|
| 1426 |
+
# Preprocess stats according to datatype
|
| 1427 |
+
for key in postfix.keys():
|
| 1428 |
+
# Number: limit the length of the string
|
| 1429 |
+
if isinstance(postfix[key], Number):
|
| 1430 |
+
postfix[key] = self.format_num(postfix[key])
|
| 1431 |
+
# Else for any other type, try to get the string conversion
|
| 1432 |
+
elif not isinstance(postfix[key], str):
|
| 1433 |
+
postfix[key] = str(postfix[key])
|
| 1434 |
+
# Else if it's a string, don't need to preprocess anything
|
| 1435 |
+
# Stitch together to get the final postfix
|
| 1436 |
+
self.postfix = ', '.join(key + '=' + postfix[key].strip()
|
| 1437 |
+
for key in postfix.keys())
|
| 1438 |
+
if refresh:
|
| 1439 |
+
self.refresh()
|
| 1440 |
+
|
| 1441 |
+
def set_postfix_str(self, s='', refresh=True):
|
| 1442 |
+
"""
|
| 1443 |
+
Postfix without dictionary expansion, similar to prefix handling.
|
| 1444 |
+
"""
|
| 1445 |
+
self.postfix = str(s)
|
| 1446 |
+
if refresh:
|
| 1447 |
+
self.refresh()
|
| 1448 |
+
|
| 1449 |
+
def moveto(self, n):
|
| 1450 |
+
# TODO: private method
|
| 1451 |
+
self.fp.write('\n' * n + _term_move_up() * -n)
|
| 1452 |
+
getattr(self.fp, 'flush', lambda: None)()
|
| 1453 |
+
|
| 1454 |
+
@property
|
| 1455 |
+
def format_dict(self):
|
| 1456 |
+
"""Public API for read-only member access."""
|
| 1457 |
+
if self.disable and not hasattr(self, 'unit'):
|
| 1458 |
+
return defaultdict(lambda: None, {
|
| 1459 |
+
'n': self.n, 'total': self.total, 'elapsed': 0, 'unit': 'it'})
|
| 1460 |
+
if self.dynamic_ncols:
|
| 1461 |
+
self.ncols, self.nrows = self.dynamic_ncols(self.fp)
|
| 1462 |
+
return {
|
| 1463 |
+
'n': self.n, 'total': self.total,
|
| 1464 |
+
'elapsed': self._time() - self.start_t if hasattr(self, 'start_t') else 0,
|
| 1465 |
+
'ncols': self.ncols, 'nrows': self.nrows, 'prefix': self.desc,
|
| 1466 |
+
'ascii': self.ascii, 'unit': self.unit, 'unit_scale': self.unit_scale,
|
| 1467 |
+
'rate': self._ema_dn() / self._ema_dt() if self._ema_dt() else None,
|
| 1468 |
+
'bar_format': self.bar_format, 'postfix': self.postfix,
|
| 1469 |
+
'unit_divisor': self.unit_divisor, 'initial': self.initial,
|
| 1470 |
+
'colour': self.colour}
|
| 1471 |
+
|
| 1472 |
+
def display(self, msg=None, pos=None):
|
| 1473 |
+
"""
|
| 1474 |
+
Use `self.sp` to display `msg` in the specified `pos`.
|
| 1475 |
+
|
| 1476 |
+
Consider overloading this function when inheriting to use e.g.:
|
| 1477 |
+
`self.some_frontend(**self.format_dict)` instead of `self.sp`.
|
| 1478 |
+
|
| 1479 |
+
Parameters
|
| 1480 |
+
----------
|
| 1481 |
+
msg : str, optional. What to display (default: `repr(self)`).
|
| 1482 |
+
pos : int, optional. Position to `moveto`
|
| 1483 |
+
(default: `abs(self.pos)`).
|
| 1484 |
+
"""
|
| 1485 |
+
if pos is None:
|
| 1486 |
+
pos = abs(self.pos)
|
| 1487 |
+
|
| 1488 |
+
nrows = self.nrows or 20
|
| 1489 |
+
if pos >= nrows - 1:
|
| 1490 |
+
if pos >= nrows:
|
| 1491 |
+
return False
|
| 1492 |
+
if msg or msg is None: # override at `nrows - 1`
|
| 1493 |
+
msg = " ... (more hidden) ..."
|
| 1494 |
+
|
| 1495 |
+
if not hasattr(self, "sp"):
|
| 1496 |
+
raise TqdmDeprecationWarning(
|
| 1497 |
+
"Please use `tqdm.gui.tqdm(...)`"
|
| 1498 |
+
" instead of `tqdm(..., gui=True)`\n",
|
| 1499 |
+
fp_write=getattr(self.fp, 'write', sys.stderr.write))
|
| 1500 |
+
|
| 1501 |
+
if pos:
|
| 1502 |
+
self.moveto(pos)
|
| 1503 |
+
self.sp(self.__str__() if msg is None else msg)
|
| 1504 |
+
if pos:
|
| 1505 |
+
self.moveto(-pos)
|
| 1506 |
+
return True
|
| 1507 |
+
|
| 1508 |
+
@classmethod
|
| 1509 |
+
@contextmanager
|
| 1510 |
+
def wrapattr(cls, stream, method, total=None, bytes=True, # pylint: disable=redefined-builtin
|
| 1511 |
+
**tqdm_kwargs):
|
| 1512 |
+
"""
|
| 1513 |
+
stream : file-like object.
|
| 1514 |
+
method : str, "read" or "write". The result of `read()` and
|
| 1515 |
+
the first argument of `write()` should have a `len()`.
|
| 1516 |
+
|
| 1517 |
+
>>> with tqdm.wrapattr(file_obj, "read", total=file_obj.size) as fobj:
|
| 1518 |
+
... while True:
|
| 1519 |
+
... chunk = fobj.read(chunk_size)
|
| 1520 |
+
... if not chunk:
|
| 1521 |
+
... break
|
| 1522 |
+
"""
|
| 1523 |
+
with cls(total=total, **tqdm_kwargs) as t:
|
| 1524 |
+
if bytes:
|
| 1525 |
+
t.unit = "B"
|
| 1526 |
+
t.unit_scale = True
|
| 1527 |
+
t.unit_divisor = 1024
|
| 1528 |
+
yield CallbackIOWrapper(t.update, stream, method)
|
| 1529 |
+
|
| 1530 |
+
|
| 1531 |
+
def trange(*args, **kwargs):
|
| 1532 |
+
"""Shortcut for tqdm(range(*args), **kwargs)."""
|
| 1533 |
+
return tqdm(range(*args), **kwargs)
|
.cache/uv/archive-v0/-f_0_DZnf30ScnbSOEDOA/tqdm/tk.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Tkinter GUI progress bar decorator for iterators.
|
| 3 |
+
|
| 4 |
+
Usage:
|
| 5 |
+
>>> from tqdm.tk import trange, tqdm
|
| 6 |
+
>>> for i in trange(10):
|
| 7 |
+
... ...
|
| 8 |
+
"""
|
| 9 |
+
import re
|
| 10 |
+
import sys
|
| 11 |
+
import tkinter
|
| 12 |
+
import tkinter.ttk as ttk
|
| 13 |
+
from warnings import warn
|
| 14 |
+
|
| 15 |
+
from .std import TqdmExperimentalWarning, TqdmWarning
|
| 16 |
+
from .std import tqdm as std_tqdm
|
| 17 |
+
|
| 18 |
+
__author__ = {"github.com/": ["richardsheridan", "casperdcl"]}
|
| 19 |
+
__all__ = ['tqdm_tk', 'ttkrange', 'tqdm', 'trange']
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class tqdm_tk(std_tqdm): # pragma: no cover
|
| 23 |
+
"""
|
| 24 |
+
Experimental Tkinter GUI version of tqdm!
|
| 25 |
+
|
| 26 |
+
Note: Window interactivity suffers if `tqdm_tk` is not running within
|
| 27 |
+
a Tkinter mainloop and values are generated infrequently. In this case,
|
| 28 |
+
consider calling `tqdm_tk.refresh()` frequently in the Tk thread.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
# TODO: @classmethod: write()?
|
| 32 |
+
|
| 33 |
+
def __init__(self, *args, **kwargs):
|
| 34 |
+
"""
|
| 35 |
+
This class accepts the following parameters *in addition* to
|
| 36 |
+
the parameters accepted by `tqdm`.
|
| 37 |
+
|
| 38 |
+
Parameters
|
| 39 |
+
----------
|
| 40 |
+
grab : bool, optional
|
| 41 |
+
Grab the input across all windows of the process.
|
| 42 |
+
tk_parent : `tkinter.Wm`, optional
|
| 43 |
+
Parent Tk window.
|
| 44 |
+
cancel_callback : Callable, optional
|
| 45 |
+
Create a cancel button and set `cancel_callback` to be called
|
| 46 |
+
when the cancel or window close button is clicked.
|
| 47 |
+
"""
|
| 48 |
+
kwargs = kwargs.copy()
|
| 49 |
+
kwargs['gui'] = True
|
| 50 |
+
# convert disable = None to False
|
| 51 |
+
kwargs['disable'] = bool(kwargs.get('disable', False))
|
| 52 |
+
self._warn_leave = 'leave' in kwargs
|
| 53 |
+
grab = kwargs.pop('grab', False)
|
| 54 |
+
tk_parent = kwargs.pop('tk_parent', None)
|
| 55 |
+
self._cancel_callback = kwargs.pop('cancel_callback', None)
|
| 56 |
+
super().__init__(*args, **kwargs)
|
| 57 |
+
|
| 58 |
+
if self.disable:
|
| 59 |
+
return
|
| 60 |
+
|
| 61 |
+
if tk_parent is None: # Discover parent widget
|
| 62 |
+
try:
|
| 63 |
+
tk_parent = tkinter._default_root
|
| 64 |
+
except AttributeError:
|
| 65 |
+
raise AttributeError(
|
| 66 |
+
"`tk_parent` required when using `tkinter.NoDefaultRoot()`")
|
| 67 |
+
if tk_parent is None: # use new default root window as display
|
| 68 |
+
self._tk_window = tkinter.Tk()
|
| 69 |
+
else: # some other windows already exist
|
| 70 |
+
self._tk_window = tkinter.Toplevel()
|
| 71 |
+
else:
|
| 72 |
+
self._tk_window = tkinter.Toplevel(tk_parent)
|
| 73 |
+
|
| 74 |
+
warn("GUI is experimental/alpha", TqdmExperimentalWarning, stacklevel=2)
|
| 75 |
+
self._tk_dispatching = self._tk_dispatching_helper()
|
| 76 |
+
|
| 77 |
+
self._tk_window.protocol("WM_DELETE_WINDOW", self.cancel)
|
| 78 |
+
self._tk_window.wm_title(self.desc)
|
| 79 |
+
self._tk_window.wm_attributes("-topmost", 1)
|
| 80 |
+
self._tk_window.after(0, lambda: self._tk_window.wm_attributes("-topmost", 0))
|
| 81 |
+
self._tk_n_var = tkinter.DoubleVar(self._tk_window, value=0)
|
| 82 |
+
self._tk_text_var = tkinter.StringVar(self._tk_window)
|
| 83 |
+
pbar_frame = ttk.Frame(self._tk_window, padding=5)
|
| 84 |
+
pbar_frame.pack()
|
| 85 |
+
_tk_label = ttk.Label(pbar_frame, textvariable=self._tk_text_var,
|
| 86 |
+
wraplength=600, anchor="center", justify="center")
|
| 87 |
+
_tk_label.pack()
|
| 88 |
+
self._tk_pbar = ttk.Progressbar(
|
| 89 |
+
pbar_frame, variable=self._tk_n_var, length=450)
|
| 90 |
+
if self.total is not None:
|
| 91 |
+
self._tk_pbar.configure(maximum=self.total)
|
| 92 |
+
else:
|
| 93 |
+
self._tk_pbar.configure(mode="indeterminate")
|
| 94 |
+
self._tk_pbar.pack()
|
| 95 |
+
if self._cancel_callback is not None:
|
| 96 |
+
_tk_button = ttk.Button(pbar_frame, text="Cancel", command=self.cancel)
|
| 97 |
+
_tk_button.pack()
|
| 98 |
+
if grab:
|
| 99 |
+
self._tk_window.grab_set()
|
| 100 |
+
|
| 101 |
+
def close(self):
|
| 102 |
+
if self.disable:
|
| 103 |
+
return
|
| 104 |
+
|
| 105 |
+
self.disable = True
|
| 106 |
+
|
| 107 |
+
with self.get_lock():
|
| 108 |
+
self._instances.remove(self)
|
| 109 |
+
|
| 110 |
+
def _close():
|
| 111 |
+
self._tk_window.after('idle', self._tk_window.destroy)
|
| 112 |
+
if not self._tk_dispatching:
|
| 113 |
+
self._tk_window.update()
|
| 114 |
+
|
| 115 |
+
self._tk_window.protocol("WM_DELETE_WINDOW", _close)
|
| 116 |
+
|
| 117 |
+
# if leave is set but we are self-dispatching, the left window is
|
| 118 |
+
# totally unresponsive unless the user manually dispatches
|
| 119 |
+
if not self.leave:
|
| 120 |
+
_close()
|
| 121 |
+
elif not self._tk_dispatching:
|
| 122 |
+
if self._warn_leave:
|
| 123 |
+
warn("leave flag ignored if not in tkinter mainloop",
|
| 124 |
+
TqdmWarning, stacklevel=2)
|
| 125 |
+
_close()
|
| 126 |
+
|
| 127 |
+
def clear(self, *_, **__):
|
| 128 |
+
pass
|
| 129 |
+
|
| 130 |
+
def display(self, *_, **__):
|
| 131 |
+
self._tk_n_var.set(self.n)
|
| 132 |
+
d = self.format_dict
|
| 133 |
+
# remove {bar}
|
| 134 |
+
d['bar_format'] = (d['bar_format'] or "{l_bar}<bar/>{r_bar}").replace(
|
| 135 |
+
"{bar}", "<bar/>")
|
| 136 |
+
msg = self.format_meter(**d)
|
| 137 |
+
if '<bar/>' in msg:
|
| 138 |
+
msg = "".join(re.split(r'\|?<bar/>\|?', msg, maxsplit=1))
|
| 139 |
+
self._tk_text_var.set(msg)
|
| 140 |
+
if not self._tk_dispatching:
|
| 141 |
+
self._tk_window.update()
|
| 142 |
+
|
| 143 |
+
def set_description(self, desc=None, refresh=True):
|
| 144 |
+
self.set_description_str(desc, refresh)
|
| 145 |
+
|
| 146 |
+
def set_description_str(self, desc=None, refresh=True):
|
| 147 |
+
self.desc = desc
|
| 148 |
+
if not self.disable:
|
| 149 |
+
self._tk_window.wm_title(desc)
|
| 150 |
+
if refresh and not self._tk_dispatching:
|
| 151 |
+
self._tk_window.update()
|
| 152 |
+
|
| 153 |
+
def cancel(self):
|
| 154 |
+
"""
|
| 155 |
+
`cancel_callback()` followed by `close()`
|
| 156 |
+
when close/cancel buttons clicked.
|
| 157 |
+
"""
|
| 158 |
+
if self._cancel_callback is not None:
|
| 159 |
+
self._cancel_callback()
|
| 160 |
+
self.close()
|
| 161 |
+
|
| 162 |
+
def reset(self, total=None):
|
| 163 |
+
"""
|
| 164 |
+
Resets to 0 iterations for repeated use.
|
| 165 |
+
|
| 166 |
+
Parameters
|
| 167 |
+
----------
|
| 168 |
+
total : int or float, optional. Total to use for the new bar.
|
| 169 |
+
"""
|
| 170 |
+
if hasattr(self, '_tk_pbar'):
|
| 171 |
+
if total is None:
|
| 172 |
+
self._tk_pbar.configure(maximum=100, mode="indeterminate")
|
| 173 |
+
else:
|
| 174 |
+
self._tk_pbar.configure(maximum=total, mode="determinate")
|
| 175 |
+
super().reset(total=total)
|
| 176 |
+
|
| 177 |
+
@staticmethod
|
| 178 |
+
def _tk_dispatching_helper():
|
| 179 |
+
"""determine if Tkinter mainloop is dispatching events"""
|
| 180 |
+
codes = {tkinter.mainloop.__code__, tkinter.Misc.mainloop.__code__}
|
| 181 |
+
for frame in sys._current_frames().values():
|
| 182 |
+
while frame:
|
| 183 |
+
if frame.f_code in codes:
|
| 184 |
+
return True
|
| 185 |
+
frame = frame.f_back
|
| 186 |
+
return False
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def ttkrange(*args, **kwargs):
|
| 190 |
+
"""Shortcut for `tqdm.tk.tqdm(range(*args), **kwargs)`."""
|
| 191 |
+
return tqdm_tk(range(*args), **kwargs)
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
# Aliases
|
| 195 |
+
tqdm = tqdm_tk
|
| 196 |
+
trange = ttkrange
|
.cache/uv/archive-v0/-f_0_DZnf30ScnbSOEDOA/tqdm/tqdm.1
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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9 |
+
.UE \c
|
| 10 |
+
\&.
|
| 11 |
+
Can be used as a pipe:
|
| 12 |
+
.IP
|
| 13 |
+
.EX
|
| 14 |
+
$ \f[I]# count lines of code\f[R]
|
| 15 |
+
$ cat *.py \f[B]|\f[R] tqdm \f[B]|\f[R] wc \-l
|
| 16 |
+
327it [00:00, 981773.38it/s]
|
| 17 |
+
327
|
| 18 |
+
|
| 19 |
+
$ \f[I]# find all files\f[R]
|
| 20 |
+
$ find . \-name \(dq*.py\(dq \f[B]|\f[R] tqdm \f[B]|\f[R] wc \-l
|
| 21 |
+
432it [00:00, 833842.30it/s]
|
| 22 |
+
432
|
| 23 |
+
|
| 24 |
+
\f[I]# ... and more info\f[R]
|
| 25 |
+
$ find . \-name \(aq*.py\(aq \-exec wc \-l \(rs{} \(rs; \(rs
|
| 26 |
+
\f[B]|\f[R] tqdm \-\-total 432 \-\-unit files \-\-desc counting \(rs
|
| 27 |
+
\f[B]|\f[R] awk \(aq{ sum += $1 }; END { print sum }\(aq
|
| 28 |
+
counting: 100%\f[B]|\f[R]█████████\f[B]|\f[R] 432/432 [00:00<00:00, 794361.83files/s]
|
| 29 |
+
131998
|
| 30 |
+
.EE
|
| 31 |
+
.SH OPTIONS
|
| 32 |
+
.TP
|
| 33 |
+
\-h, \-\-help
|
| 34 |
+
Print this help and exit.
|
| 35 |
+
.TP
|
| 36 |
+
\-v, \-\-version
|
| 37 |
+
Print version and exit.
|
| 38 |
+
.TP
|
| 39 |
+
\-\-desc=\f[I]desc\f[R]
|
| 40 |
+
str, optional.
|
| 41 |
+
Prefix for the progress bar.
|
| 42 |
+
.TP
|
| 43 |
+
\-\-total=\f[I]total\f[R]
|
| 44 |
+
int or float, optional.
|
| 45 |
+
The number of expected iterations.
|
| 46 |
+
If unspecified, len(iterable) is used if possible.
|
| 47 |
+
If float(\(lqinf\(rq) or as a last resort, only basic progress
|
| 48 |
+
statistics are displayed (no ETA, no progress bar).
|
| 49 |
+
If \f[CR]gui\f[R] is True and this parameter needs subsequent updating,
|
| 50 |
+
specify an initial arbitrary large positive number, e.g.\ 9e9.
|
| 51 |
+
.TP
|
| 52 |
+
\-\-leave
|
| 53 |
+
bool, optional.
|
| 54 |
+
If [default: True], keeps all traces of the progress bar upon
|
| 55 |
+
termination of iteration.
|
| 56 |
+
If \f[CR]None\f[R], will leave only if \f[CR]position\f[R] is
|
| 57 |
+
\f[CR]0\f[R].
|
| 58 |
+
.TP
|
| 59 |
+
\-\-ncols=\f[I]ncols\f[R]
|
| 60 |
+
int, optional.
|
| 61 |
+
The width of the entire output message.
|
| 62 |
+
If specified, dynamically resizes the progress bar to stay within this
|
| 63 |
+
bound.
|
| 64 |
+
If unspecified, attempts to use environment width.
|
| 65 |
+
The fallback is a meter width of 10 and no limit for the counter and
|
| 66 |
+
statistics.
|
| 67 |
+
If 0, will not print any meter (only stats).
|
| 68 |
+
.TP
|
| 69 |
+
\-\-mininterval=\f[I]mininterval\f[R]
|
| 70 |
+
float, optional.
|
| 71 |
+
Minimum progress display update interval [default: 0.1] seconds.
|
| 72 |
+
.TP
|
| 73 |
+
\-\-maxinterval=\f[I]maxinterval\f[R]
|
| 74 |
+
float, optional.
|
| 75 |
+
Maximum progress display update interval [default: 10] seconds.
|
| 76 |
+
Automatically adjusts \f[CR]miniters\f[R] to correspond to
|
| 77 |
+
\f[CR]mininterval\f[R] after long display update lag.
|
| 78 |
+
Only works if \f[CR]dynamic_miniters\f[R] or monitor thread is enabled.
|
| 79 |
+
.TP
|
| 80 |
+
\-\-miniters=\f[I]miniters\f[R]
|
| 81 |
+
int or float, optional.
|
| 82 |
+
Minimum progress display update interval, in iterations.
|
| 83 |
+
If 0 and \f[CR]dynamic_miniters\f[R], will automatically adjust to equal
|
| 84 |
+
\f[CR]mininterval\f[R] (more CPU efficient, good for tight loops).
|
| 85 |
+
If > 0, will skip display of specified number of iterations.
|
| 86 |
+
Tweak this and \f[CR]mininterval\f[R] to get very efficient loops.
|
| 87 |
+
If your progress is erratic with both fast and slow iterations (network,
|
| 88 |
+
skipping items, etc) you should set miniters=1.
|
| 89 |
+
.TP
|
| 90 |
+
\-\-ascii=\f[I]ascii\f[R]
|
| 91 |
+
bool or str, optional.
|
| 92 |
+
If unspecified or False, use unicode (smooth blocks) to fill the meter.
|
| 93 |
+
The fallback is to use ASCII characters \(rq 123456789#\(lq.
|
| 94 |
+
.TP
|
| 95 |
+
\-\-disable
|
| 96 |
+
bool, optional.
|
| 97 |
+
Whether to disable the entire progress bar wrapper [default: False].
|
| 98 |
+
If set to None, disable on non\-TTY.
|
| 99 |
+
.TP
|
| 100 |
+
\-\-unit=\f[I]unit\f[R]
|
| 101 |
+
str, optional.
|
| 102 |
+
String that will be used to define the unit of each iteration [default:
|
| 103 |
+
it].
|
| 104 |
+
.TP
|
| 105 |
+
\-\-unit\-scale=\f[I]unit_scale\f[R]
|
| 106 |
+
bool or int or float, optional.
|
| 107 |
+
If 1 or True, the number of iterations will be reduced/scaled
|
| 108 |
+
automatically and a metric prefix following the International System of
|
| 109 |
+
Units standard will be added (kilo, mega, etc.)
|
| 110 |
+
[default: False].
|
| 111 |
+
If any other non\-zero number, will scale \f[CR]total\f[R] and
|
| 112 |
+
\f[CR]n\f[R].
|
| 113 |
+
.TP
|
| 114 |
+
\-\-dynamic\-ncols
|
| 115 |
+
bool, optional.
|
| 116 |
+
If set, constantly alters \f[CR]ncols\f[R] and \f[CR]nrows\f[R] to the
|
| 117 |
+
environment (allowing for window resizes) [default: False].
|
| 118 |
+
.TP
|
| 119 |
+
\-\-smoothing=\f[I]smoothing\f[R]
|
| 120 |
+
float, optional.
|
| 121 |
+
Exponential moving average smoothing factor for speed estimates (ignored
|
| 122 |
+
in GUI mode).
|
| 123 |
+
Ranges from 0 (average speed) to 1 (current/instantaneous speed)
|
| 124 |
+
[default: 0.3].
|
| 125 |
+
.TP
|
| 126 |
+
\-\-bar\-format=\f[I]bar_format\f[R]
|
| 127 |
+
str, optional.
|
| 128 |
+
Specify a custom bar string formatting.
|
| 129 |
+
May impact performance.
|
| 130 |
+
[default: `{l_bar}{bar}{r_bar}'], where l_bar=`{desc}:
|
| 131 |
+
{percentage:3.0f}%|' and r_bar=`| {n_fmt}/{total_fmt}
|
| 132 |
+
[{elapsed}<{remaining}, \(cq \(cq{rate_fmt}{postfix}]' Possible vars:
|
| 133 |
+
l_bar, bar, r_bar, n, n_fmt, total, total_fmt, percentage, elapsed,
|
| 134 |
+
elapsed_s, ncols, nrows, desc, unit, rate, rate_fmt, rate_noinv,
|
| 135 |
+
rate_noinv_fmt, rate_inv, rate_inv_fmt, postfix, unit_divisor,
|
| 136 |
+
remaining, remaining_s, eta.
|
| 137 |
+
Note that a trailing \(lq:\(rq is automatically removed after {desc} if
|
| 138 |
+
the latter is empty.
|
| 139 |
+
.TP
|
| 140 |
+
\-\-initial=\f[I]initial\f[R]
|
| 141 |
+
int or float, optional.
|
| 142 |
+
The initial counter value.
|
| 143 |
+
Useful when restarting a progress bar [default: 0].
|
| 144 |
+
If using float, consider specifying \f[CR]{n:.3f}\f[R] or similar in
|
| 145 |
+
\f[CR]bar_format\f[R], or specifying \f[CR]unit_scale\f[R].
|
| 146 |
+
.TP
|
| 147 |
+
\-\-position=\f[I]position\f[R]
|
| 148 |
+
int, optional.
|
| 149 |
+
Specify the line offset to print this bar (starting from 0) Automatic if
|
| 150 |
+
unspecified.
|
| 151 |
+
Useful to manage multiple bars at once (eg, from threads).
|
| 152 |
+
.TP
|
| 153 |
+
\-\-postfix=\f[I]postfix\f[R]
|
| 154 |
+
dict or *, optional.
|
| 155 |
+
Specify additional stats to display at the end of the bar.
|
| 156 |
+
Calls \f[CR]set_postfix(**postfix)\f[R] if possible (dict).
|
| 157 |
+
.TP
|
| 158 |
+
\-\-unit\-divisor=\f[I]unit_divisor\f[R]
|
| 159 |
+
float, optional.
|
| 160 |
+
[default: 1000], ignored unless \f[CR]unit_scale\f[R] is True.
|
| 161 |
+
.TP
|
| 162 |
+
\-\-write\-bytes
|
| 163 |
+
bool, optional.
|
| 164 |
+
Whether to write bytes.
|
| 165 |
+
If (default: False) will write unicode.
|
| 166 |
+
.TP
|
| 167 |
+
\-\-lock\-args=\f[I]lock_args\f[R]
|
| 168 |
+
tuple, optional.
|
| 169 |
+
Passed to \f[CR]refresh\f[R] for intermediate output (initialisation,
|
| 170 |
+
iterating, and updating).
|
| 171 |
+
.TP
|
| 172 |
+
\-\-nrows=\f[I]nrows\f[R]
|
| 173 |
+
int, optional.
|
| 174 |
+
The screen height.
|
| 175 |
+
If specified, hides nested bars outside this bound.
|
| 176 |
+
If unspecified, attempts to use environment height.
|
| 177 |
+
The fallback is 20.
|
| 178 |
+
.TP
|
| 179 |
+
\-\-colour=\f[I]colour\f[R]
|
| 180 |
+
str, optional.
|
| 181 |
+
Bar colour (e.g.\ `green', `#00ff00').
|
| 182 |
+
.TP
|
| 183 |
+
\-\-delay=\f[I]delay\f[R]
|
| 184 |
+
float, optional.
|
| 185 |
+
Don\(cqt display until [default: 0] seconds have elapsed.
|
| 186 |
+
.TP
|
| 187 |
+
\-\-delim=\f[I]delim\f[R]
|
| 188 |
+
chr, optional.
|
| 189 |
+
Delimiting character [default: `\(rsn'].
|
| 190 |
+
Use `\(rs0' for null.
|
| 191 |
+
N.B.: on Windows systems, Python converts `\(rsn' to `\(rsr\(rsn'.
|
| 192 |
+
.TP
|
| 193 |
+
\-\-buf\-size=\f[I]buf_size\f[R]
|
| 194 |
+
int, optional.
|
| 195 |
+
String buffer size in bytes [default: 256] used when \f[CR]delim\f[R] is
|
| 196 |
+
specified.
|
| 197 |
+
.TP
|
| 198 |
+
\-\-bytes
|
| 199 |
+
bool, optional.
|
| 200 |
+
If true, will count bytes, ignore \f[CR]delim\f[R], and default
|
| 201 |
+
\f[CR]unit_scale\f[R] to True, \f[CR]unit_divisor\f[R] to 1024, and
|
| 202 |
+
\f[CR]unit\f[R] to `B'.
|
| 203 |
+
.TP
|
| 204 |
+
\-\-tee
|
| 205 |
+
bool, optional.
|
| 206 |
+
If true, passes \f[CR]stdin\f[R] to both \f[CR]stderr\f[R] and
|
| 207 |
+
\f[CR]stdout\f[R].
|
| 208 |
+
.TP
|
| 209 |
+
\-\-update
|
| 210 |
+
bool, optional.
|
| 211 |
+
If true, will treat input as newly elapsed iterations, i.e.\ numbers to
|
| 212 |
+
pass to \f[CR]update()\f[R].
|
| 213 |
+
Note that this is slow (\(ti2e5 it/s) since every input must be decoded
|
| 214 |
+
as a number.
|
| 215 |
+
.TP
|
| 216 |
+
\-\-update\-to
|
| 217 |
+
bool, optional.
|
| 218 |
+
If true, will treat input as total elapsed iterations, i.e.\ numbers to
|
| 219 |
+
assign to \f[CR]self.n\f[R].
|
| 220 |
+
Note that this is slow (\(ti2e5 it/s) since every input must be decoded
|
| 221 |
+
as a number.
|
| 222 |
+
.TP
|
| 223 |
+
\-\-null
|
| 224 |
+
bool, optional.
|
| 225 |
+
If true, will discard input (no stdout).
|
| 226 |
+
.TP
|
| 227 |
+
\-\-manpath=\f[I]manpath\f[R]
|
| 228 |
+
str, optional.
|
| 229 |
+
Directory in which to install tqdm man pages.
|
| 230 |
+
.TP
|
| 231 |
+
\-\-comppath=\f[I]comppath\f[R]
|
| 232 |
+
str, optional.
|
| 233 |
+
Directory in which to place tqdm completion.
|
| 234 |
+
.TP
|
| 235 |
+
\-\-log=\f[I]log\f[R]
|
| 236 |
+
str, optional.
|
| 237 |
+
CRITICAL|FATAL|ERROR|WARN(ING)|[default: `INFO']|DEBUG|NOTSET.
|
| 238 |
+
.SH AUTHORS
|
| 239 |
+
tqdm developers \c
|
| 240 |
+
.UR https://github.com/tqdm
|
| 241 |
+
.UE \c.
|
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/__init__.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from . import caching
|
| 2 |
+
from .callbacks import Callback
|
| 3 |
+
from .compression import available_compressions
|
| 4 |
+
from .core import get_fs_token_paths, open, open_files, open_local, url_to_fs
|
| 5 |
+
from .exceptions import FSTimeoutError
|
| 6 |
+
from .mapping import FSMap, get_mapper
|
| 7 |
+
from .registry import (
|
| 8 |
+
available_protocols,
|
| 9 |
+
filesystem,
|
| 10 |
+
get_filesystem_class,
|
| 11 |
+
register_implementation,
|
| 12 |
+
registry,
|
| 13 |
+
)
|
| 14 |
+
from .spec import AbstractFileSystem
|
| 15 |
+
|
| 16 |
+
try:
|
| 17 |
+
from ._version import __version__ # noqa: F401
|
| 18 |
+
except ImportError:
|
| 19 |
+
__version__ = "unknown"
|
| 20 |
+
|
| 21 |
+
__all__ = [
|
| 22 |
+
"AbstractFileSystem",
|
| 23 |
+
"FSTimeoutError",
|
| 24 |
+
"FSMap",
|
| 25 |
+
"filesystem",
|
| 26 |
+
"register_implementation",
|
| 27 |
+
"get_filesystem_class",
|
| 28 |
+
"get_fs_token_paths",
|
| 29 |
+
"get_mapper",
|
| 30 |
+
"open",
|
| 31 |
+
"open_files",
|
| 32 |
+
"open_local",
|
| 33 |
+
"registry",
|
| 34 |
+
"caching",
|
| 35 |
+
"Callback",
|
| 36 |
+
"available_protocols",
|
| 37 |
+
"available_compressions",
|
| 38 |
+
"url_to_fs",
|
| 39 |
+
]
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def process_entries():
|
| 43 |
+
try:
|
| 44 |
+
from importlib.metadata import entry_points
|
| 45 |
+
except ImportError:
|
| 46 |
+
return
|
| 47 |
+
if entry_points is not None:
|
| 48 |
+
try:
|
| 49 |
+
eps = entry_points()
|
| 50 |
+
except TypeError:
|
| 51 |
+
pass # importlib-metadata < 0.8
|
| 52 |
+
else:
|
| 53 |
+
if hasattr(eps, "select"): # Python 3.10+ / importlib_metadata >= 3.9.0
|
| 54 |
+
specs = eps.select(group="fsspec.specs")
|
| 55 |
+
else:
|
| 56 |
+
specs = eps.get("fsspec.specs", [])
|
| 57 |
+
registered_names = {}
|
| 58 |
+
for spec in specs:
|
| 59 |
+
err_msg = f"Unable to load filesystem from {spec}"
|
| 60 |
+
name = spec.name
|
| 61 |
+
if name in registered_names:
|
| 62 |
+
continue
|
| 63 |
+
registered_names[name] = True
|
| 64 |
+
register_implementation(
|
| 65 |
+
name,
|
| 66 |
+
spec.value.replace(":", "."),
|
| 67 |
+
errtxt=err_msg,
|
| 68 |
+
# We take our implementations as the ones to overload with if
|
| 69 |
+
# for some reason we encounter some, may be the same, already
|
| 70 |
+
# registered
|
| 71 |
+
clobber=True,
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
process_entries()
|
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/_version.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# file generated by vcs-versioning
|
| 2 |
+
# don't change, don't track in version control
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
__all__ = [
|
| 6 |
+
"__version__",
|
| 7 |
+
"__version_tuple__",
|
| 8 |
+
"version",
|
| 9 |
+
"version_tuple",
|
| 10 |
+
"__commit_id__",
|
| 11 |
+
"commit_id",
|
| 12 |
+
]
|
| 13 |
+
|
| 14 |
+
version: str
|
| 15 |
+
__version__: str
|
| 16 |
+
__version_tuple__: tuple[int | str, ...]
|
| 17 |
+
version_tuple: tuple[int | str, ...]
|
| 18 |
+
commit_id: str | None
|
| 19 |
+
__commit_id__: str | None
|
| 20 |
+
|
| 21 |
+
__version__ = version = '2026.7.0'
|
| 22 |
+
__version_tuple__ = version_tuple = (2026, 7, 0)
|
| 23 |
+
|
| 24 |
+
__commit_id__ = commit_id = None
|
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/asyn.py
ADDED
|
@@ -0,0 +1,1171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import asyncio.events
|
| 3 |
+
import functools
|
| 4 |
+
import inspect
|
| 5 |
+
import io
|
| 6 |
+
import numbers
|
| 7 |
+
import os
|
| 8 |
+
import re
|
| 9 |
+
import threading
|
| 10 |
+
from collections.abc import Iterable
|
| 11 |
+
from glob import has_magic
|
| 12 |
+
from typing import TYPE_CHECKING
|
| 13 |
+
|
| 14 |
+
from .callbacks import DEFAULT_CALLBACK
|
| 15 |
+
from .exceptions import FSTimeoutError
|
| 16 |
+
from .implementations.local import LocalFileSystem, make_path_posix, trailing_sep
|
| 17 |
+
from .spec import AbstractBufferedFile, AbstractFileSystem
|
| 18 |
+
from .utils import glob_translate, is_exception, other_paths
|
| 19 |
+
|
| 20 |
+
private = re.compile("_[^_]")
|
| 21 |
+
iothread = [None] # dedicated fsspec IO thread
|
| 22 |
+
loop = [None] # global event loop for any non-async instance
|
| 23 |
+
_lock = None # global lock placeholder
|
| 24 |
+
get_running_loop = asyncio.get_running_loop
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def get_lock():
|
| 28 |
+
"""Allocate or return a threading lock.
|
| 29 |
+
|
| 30 |
+
The lock is allocated on first use to allow setting one lock per forked process.
|
| 31 |
+
"""
|
| 32 |
+
global _lock
|
| 33 |
+
if not _lock:
|
| 34 |
+
_lock = threading.Lock()
|
| 35 |
+
return _lock
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def reset_lock():
|
| 39 |
+
"""Reset the global lock.
|
| 40 |
+
|
| 41 |
+
This should be called only on the init of a forked process to reset the lock to
|
| 42 |
+
None, enabling the new forked process to get a new lock.
|
| 43 |
+
"""
|
| 44 |
+
global _lock
|
| 45 |
+
|
| 46 |
+
iothread[0] = None
|
| 47 |
+
loop[0] = None
|
| 48 |
+
_lock = None
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
async def _runner(event, coro, result, timeout=None):
|
| 52 |
+
timeout = timeout if timeout else None # convert 0 or 0.0 to None
|
| 53 |
+
if timeout is not None:
|
| 54 |
+
coro = asyncio.wait_for(coro, timeout=timeout)
|
| 55 |
+
try:
|
| 56 |
+
result[0] = await coro
|
| 57 |
+
except Exception as ex:
|
| 58 |
+
result[0] = ex
|
| 59 |
+
finally:
|
| 60 |
+
event.set()
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def sync(loop, func, *args, timeout=None, **kwargs):
|
| 64 |
+
"""
|
| 65 |
+
Make loop run coroutine until it returns. Runs in other thread
|
| 66 |
+
|
| 67 |
+
Examples
|
| 68 |
+
--------
|
| 69 |
+
>>> fsspec.asyn.sync(fsspec.asyn.get_loop(), func, *args,
|
| 70 |
+
timeout=timeout, **kwargs)
|
| 71 |
+
"""
|
| 72 |
+
timeout = timeout if timeout else None # convert 0 or 0.0 to None
|
| 73 |
+
# NB: if the loop is not running *yet*, it is OK to submit work
|
| 74 |
+
# and we will wait for it
|
| 75 |
+
if loop is None or loop.is_closed():
|
| 76 |
+
raise RuntimeError("Loop is not running")
|
| 77 |
+
try:
|
| 78 |
+
loop0 = asyncio.events.get_running_loop()
|
| 79 |
+
if loop0 is loop:
|
| 80 |
+
raise NotImplementedError("Calling sync() from within a running loop")
|
| 81 |
+
except NotImplementedError:
|
| 82 |
+
raise
|
| 83 |
+
except RuntimeError:
|
| 84 |
+
pass
|
| 85 |
+
coro = func(*args, **kwargs)
|
| 86 |
+
result = [None]
|
| 87 |
+
event = threading.Event()
|
| 88 |
+
asyncio.run_coroutine_threadsafe(_runner(event, coro, result, timeout), loop)
|
| 89 |
+
while True:
|
| 90 |
+
# this loops allows thread to get interrupted
|
| 91 |
+
if event.wait(1):
|
| 92 |
+
break
|
| 93 |
+
if timeout is not None:
|
| 94 |
+
timeout -= 1
|
| 95 |
+
if timeout < 0:
|
| 96 |
+
raise FSTimeoutError
|
| 97 |
+
|
| 98 |
+
return_result = result[0]
|
| 99 |
+
if isinstance(return_result, asyncio.TimeoutError):
|
| 100 |
+
# suppress asyncio.TimeoutError, raise FSTimeoutError
|
| 101 |
+
raise FSTimeoutError from return_result
|
| 102 |
+
elif isinstance(return_result, BaseException):
|
| 103 |
+
raise return_result
|
| 104 |
+
else:
|
| 105 |
+
return return_result
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def sync_wrapper(func, obj=None):
|
| 109 |
+
"""Given a function, make so can be called in blocking contexts
|
| 110 |
+
|
| 111 |
+
Leave obj=None if defining within a class. Pass the instance if attaching
|
| 112 |
+
as an attribute of the instance.
|
| 113 |
+
"""
|
| 114 |
+
|
| 115 |
+
@functools.wraps(func)
|
| 116 |
+
def wrapper(*args, **kwargs):
|
| 117 |
+
self = obj or args[0]
|
| 118 |
+
return sync(self.loop, func, *args, **kwargs)
|
| 119 |
+
|
| 120 |
+
return wrapper
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def async_gen_wrapper(func, obj=None):
|
| 124 |
+
"""Given a async generator, make so can be called in blocking contexts"""
|
| 125 |
+
|
| 126 |
+
@functools.wraps(func)
|
| 127 |
+
def wrapper(*args, **kwargs):
|
| 128 |
+
self = obj or args[0]
|
| 129 |
+
gen = func(*args, **kwargs)
|
| 130 |
+
while True:
|
| 131 |
+
try:
|
| 132 |
+
yield sync(self.loop, gen.__anext__)
|
| 133 |
+
except StopAsyncIteration:
|
| 134 |
+
break
|
| 135 |
+
|
| 136 |
+
return wrapper
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def get_loop():
|
| 140 |
+
"""Create or return the default fsspec IO loop
|
| 141 |
+
|
| 142 |
+
The loop will be running on a separate thread.
|
| 143 |
+
"""
|
| 144 |
+
if loop[0] is None:
|
| 145 |
+
with get_lock():
|
| 146 |
+
# repeat the check just in case the loop got filled between the
|
| 147 |
+
# previous two calls from another thread
|
| 148 |
+
if loop[0] is None:
|
| 149 |
+
loop[0] = asyncio.new_event_loop()
|
| 150 |
+
th = threading.Thread(target=loop[0].run_forever, name="fsspecIO")
|
| 151 |
+
th.daemon = True
|
| 152 |
+
th.start()
|
| 153 |
+
iothread[0] = th
|
| 154 |
+
return loop[0]
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def reset_after_fork():
|
| 158 |
+
global lock
|
| 159 |
+
loop[0] = None
|
| 160 |
+
iothread[0] = None
|
| 161 |
+
lock = None
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
if hasattr(os, "register_at_fork"):
|
| 165 |
+
# should be posix; this will do nothing for spawn or forkserver subprocesses
|
| 166 |
+
os.register_at_fork(after_in_child=reset_after_fork)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
if TYPE_CHECKING:
|
| 170 |
+
import resource
|
| 171 |
+
|
| 172 |
+
ResourceError = resource.error
|
| 173 |
+
else:
|
| 174 |
+
try:
|
| 175 |
+
import resource
|
| 176 |
+
except ImportError:
|
| 177 |
+
resource = None
|
| 178 |
+
ResourceError = OSError
|
| 179 |
+
else:
|
| 180 |
+
ResourceError = getattr(resource, "error", OSError)
|
| 181 |
+
|
| 182 |
+
_DEFAULT_BATCH_SIZE = 128
|
| 183 |
+
_NOFILES_DEFAULT_BATCH_SIZE = 1280
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def _get_batch_size(nofiles=False):
|
| 187 |
+
from fsspec.config import conf
|
| 188 |
+
|
| 189 |
+
if nofiles:
|
| 190 |
+
if "nofiles_gather_batch_size" in conf:
|
| 191 |
+
return conf["nofiles_gather_batch_size"]
|
| 192 |
+
else:
|
| 193 |
+
if "gather_batch_size" in conf:
|
| 194 |
+
return conf["gather_batch_size"]
|
| 195 |
+
if nofiles:
|
| 196 |
+
return _NOFILES_DEFAULT_BATCH_SIZE
|
| 197 |
+
if resource is None:
|
| 198 |
+
return _DEFAULT_BATCH_SIZE
|
| 199 |
+
|
| 200 |
+
try:
|
| 201 |
+
soft_limit, _ = resource.getrlimit(resource.RLIMIT_NOFILE)
|
| 202 |
+
except (ImportError, ValueError, ResourceError):
|
| 203 |
+
return _DEFAULT_BATCH_SIZE
|
| 204 |
+
|
| 205 |
+
if soft_limit == resource.RLIM_INFINITY:
|
| 206 |
+
return -1
|
| 207 |
+
else:
|
| 208 |
+
return soft_limit // 8
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def running_async() -> bool:
|
| 212 |
+
"""Being executed by an event loop?"""
|
| 213 |
+
try:
|
| 214 |
+
asyncio.get_running_loop()
|
| 215 |
+
return True
|
| 216 |
+
except RuntimeError:
|
| 217 |
+
return False
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
async def _run_coros_in_chunks(
|
| 221 |
+
coros,
|
| 222 |
+
batch_size=None,
|
| 223 |
+
callback=DEFAULT_CALLBACK,
|
| 224 |
+
timeout=None,
|
| 225 |
+
return_exceptions=False,
|
| 226 |
+
nofiles=False,
|
| 227 |
+
):
|
| 228 |
+
"""Run the given coroutines in chunks.
|
| 229 |
+
|
| 230 |
+
Parameters
|
| 231 |
+
----------
|
| 232 |
+
coros: list of coroutines to run
|
| 233 |
+
batch_size: int or None
|
| 234 |
+
Number of coroutines to submit/wait on simultaneously.
|
| 235 |
+
If -1, then it will not be any throttling. If
|
| 236 |
+
None, it will be inferred from _get_batch_size()
|
| 237 |
+
callback: fsspec.callbacks.Callback instance
|
| 238 |
+
Gets a relative_update when each coroutine completes
|
| 239 |
+
timeout: number or None
|
| 240 |
+
If given, each coroutine times out after this time. Note that, since
|
| 241 |
+
there are multiple batches, the total run time of this function will in
|
| 242 |
+
general be longer
|
| 243 |
+
return_exceptions: bool
|
| 244 |
+
Same meaning as in asyncio.gather
|
| 245 |
+
nofiles: bool
|
| 246 |
+
If inferring the batch_size, does this operation involve local files?
|
| 247 |
+
If yes, you normally expect smaller batches.
|
| 248 |
+
"""
|
| 249 |
+
|
| 250 |
+
if batch_size is None:
|
| 251 |
+
batch_size = _get_batch_size(nofiles=nofiles)
|
| 252 |
+
|
| 253 |
+
if batch_size == -1:
|
| 254 |
+
batch_size = len(coros)
|
| 255 |
+
elif batch_size <= 0:
|
| 256 |
+
raise ValueError
|
| 257 |
+
|
| 258 |
+
async def _run_coro(coro, i):
|
| 259 |
+
try:
|
| 260 |
+
return await asyncio.wait_for(coro, timeout=timeout), i
|
| 261 |
+
except Exception as e:
|
| 262 |
+
if not return_exceptions:
|
| 263 |
+
raise
|
| 264 |
+
return e, i
|
| 265 |
+
finally:
|
| 266 |
+
callback.relative_update(1)
|
| 267 |
+
|
| 268 |
+
i = 0
|
| 269 |
+
n = len(coros)
|
| 270 |
+
results = [None] * n
|
| 271 |
+
pending = set()
|
| 272 |
+
|
| 273 |
+
while pending or i < n:
|
| 274 |
+
while len(pending) < batch_size and i < n:
|
| 275 |
+
pending.add(asyncio.ensure_future(_run_coro(coros[i], i)))
|
| 276 |
+
i += 1
|
| 277 |
+
|
| 278 |
+
if not pending:
|
| 279 |
+
break
|
| 280 |
+
|
| 281 |
+
done, pending = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)
|
| 282 |
+
first_exc = None
|
| 283 |
+
while done:
|
| 284 |
+
task = done.pop()
|
| 285 |
+
try:
|
| 286 |
+
result, k = await task
|
| 287 |
+
results[k] = result
|
| 288 |
+
except Exception as exc:
|
| 289 |
+
if first_exc is None:
|
| 290 |
+
first_exc = exc
|
| 291 |
+
|
| 292 |
+
if first_exc is not None:
|
| 293 |
+
for task in pending:
|
| 294 |
+
task.cancel()
|
| 295 |
+
if pending:
|
| 296 |
+
await asyncio.gather(*pending, return_exceptions=True)
|
| 297 |
+
raise first_exc
|
| 298 |
+
|
| 299 |
+
return results
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
# these methods should be implemented as async by any async-able backend
|
| 303 |
+
async_methods = [
|
| 304 |
+
"_ls",
|
| 305 |
+
"_cat_file",
|
| 306 |
+
"_get_file",
|
| 307 |
+
"_put_file",
|
| 308 |
+
"_rm_file",
|
| 309 |
+
"_cp_file",
|
| 310 |
+
"_pipe_file",
|
| 311 |
+
"_expand_path",
|
| 312 |
+
"_info",
|
| 313 |
+
"_isfile",
|
| 314 |
+
"_isdir",
|
| 315 |
+
"_exists",
|
| 316 |
+
"_walk",
|
| 317 |
+
"_glob",
|
| 318 |
+
"_find",
|
| 319 |
+
"_du",
|
| 320 |
+
"_size",
|
| 321 |
+
"_mkdir",
|
| 322 |
+
"_makedirs",
|
| 323 |
+
]
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
class AsyncFileSystem(AbstractFileSystem):
|
| 327 |
+
"""Async file operations, default implementations
|
| 328 |
+
|
| 329 |
+
Passes bulk operations to asyncio.gather for concurrent operation.
|
| 330 |
+
|
| 331 |
+
Implementations that have concurrent batch operations and/or async methods
|
| 332 |
+
should inherit from this class instead of AbstractFileSystem. Docstrings are
|
| 333 |
+
copied from the un-underscored method in AbstractFileSystem, if not given.
|
| 334 |
+
"""
|
| 335 |
+
|
| 336 |
+
# note that methods do not have docstring here; they will be copied
|
| 337 |
+
# for _* methods and inferred for overridden methods.
|
| 338 |
+
|
| 339 |
+
async_impl = True
|
| 340 |
+
mirror_sync_methods = True
|
| 341 |
+
disable_throttling = False
|
| 342 |
+
|
| 343 |
+
def __init__(self, *args, asynchronous=False, loop=None, batch_size=None, **kwargs):
|
| 344 |
+
self.asynchronous = asynchronous
|
| 345 |
+
self._pid = os.getpid()
|
| 346 |
+
if not asynchronous:
|
| 347 |
+
self._loop = loop or get_loop()
|
| 348 |
+
else:
|
| 349 |
+
self._loop = None
|
| 350 |
+
self.batch_size = batch_size
|
| 351 |
+
super().__init__(*args, **kwargs)
|
| 352 |
+
|
| 353 |
+
@property
|
| 354 |
+
def loop(self):
|
| 355 |
+
if self._pid != os.getpid():
|
| 356 |
+
raise RuntimeError("This class is not fork-safe")
|
| 357 |
+
return self._loop
|
| 358 |
+
|
| 359 |
+
async def _rm_file(self, path, **kwargs):
|
| 360 |
+
if (
|
| 361 |
+
inspect.iscoroutinefunction(self._rm)
|
| 362 |
+
and type(self)._rm is not AsyncFileSystem._rm
|
| 363 |
+
):
|
| 364 |
+
return await self._rm(path, recursive=False, batch_size=1, **kwargs)
|
| 365 |
+
raise NotImplementedError
|
| 366 |
+
|
| 367 |
+
async def _rm(self, path, recursive=False, batch_size=None, **kwargs):
|
| 368 |
+
# TODO: implement on_error
|
| 369 |
+
batch_size = batch_size or self.batch_size
|
| 370 |
+
path = await self._expand_path(path, recursive=recursive)
|
| 371 |
+
return await _run_coros_in_chunks(
|
| 372 |
+
[self._rm_file(p, **kwargs) for p in reversed(path)],
|
| 373 |
+
batch_size=batch_size,
|
| 374 |
+
nofiles=True,
|
| 375 |
+
)
|
| 376 |
+
|
| 377 |
+
async def _cp_file(self, path1, path2, **kwargs):
|
| 378 |
+
raise NotImplementedError
|
| 379 |
+
|
| 380 |
+
async def _mv_file(self, path1, path2):
|
| 381 |
+
await self._cp_file(path1, path2)
|
| 382 |
+
await self._rm_file(path1)
|
| 383 |
+
|
| 384 |
+
async def _copy(
|
| 385 |
+
self,
|
| 386 |
+
path1,
|
| 387 |
+
path2,
|
| 388 |
+
recursive=False,
|
| 389 |
+
on_error=None,
|
| 390 |
+
maxdepth=None,
|
| 391 |
+
batch_size=None,
|
| 392 |
+
**kwargs,
|
| 393 |
+
):
|
| 394 |
+
if on_error is None and recursive:
|
| 395 |
+
on_error = "ignore"
|
| 396 |
+
elif on_error is None:
|
| 397 |
+
on_error = "raise"
|
| 398 |
+
|
| 399 |
+
if isinstance(path1, list) and isinstance(path2, list):
|
| 400 |
+
# No need to expand paths when both source and destination
|
| 401 |
+
# are provided as lists
|
| 402 |
+
paths1 = path1
|
| 403 |
+
paths2 = path2
|
| 404 |
+
else:
|
| 405 |
+
source_is_str = isinstance(path1, str)
|
| 406 |
+
paths1 = await self._expand_path(
|
| 407 |
+
path1, maxdepth=maxdepth, recursive=recursive
|
| 408 |
+
)
|
| 409 |
+
if source_is_str and (not recursive or maxdepth is not None):
|
| 410 |
+
# Non-recursive glob does not copy directories
|
| 411 |
+
paths1 = [
|
| 412 |
+
p for p in paths1 if not (trailing_sep(p) or await self._isdir(p))
|
| 413 |
+
]
|
| 414 |
+
if not paths1:
|
| 415 |
+
return
|
| 416 |
+
|
| 417 |
+
source_is_file = len(paths1) == 1
|
| 418 |
+
dest_is_dir = isinstance(path2, str) and (
|
| 419 |
+
trailing_sep(path2) or await self._isdir(path2)
|
| 420 |
+
)
|
| 421 |
+
|
| 422 |
+
exists = source_is_str and (
|
| 423 |
+
(has_magic(path1) and source_is_file)
|
| 424 |
+
or (not has_magic(path1) and dest_is_dir and not trailing_sep(path1))
|
| 425 |
+
)
|
| 426 |
+
paths2 = other_paths(
|
| 427 |
+
paths1,
|
| 428 |
+
path2,
|
| 429 |
+
exists=exists,
|
| 430 |
+
flatten=not source_is_str,
|
| 431 |
+
)
|
| 432 |
+
|
| 433 |
+
batch_size = batch_size or self.batch_size
|
| 434 |
+
coros = [self._cp_file(p1, p2, **kwargs) for p1, p2 in zip(paths1, paths2)]
|
| 435 |
+
result = await _run_coros_in_chunks(
|
| 436 |
+
coros, batch_size=batch_size, return_exceptions=True, nofiles=True
|
| 437 |
+
)
|
| 438 |
+
|
| 439 |
+
for ex in filter(is_exception, result):
|
| 440 |
+
if on_error == "ignore" and isinstance(ex, FileNotFoundError):
|
| 441 |
+
continue
|
| 442 |
+
raise ex
|
| 443 |
+
|
| 444 |
+
async def _pipe_file(self, path, value, mode="overwrite", **kwargs):
|
| 445 |
+
raise NotImplementedError
|
| 446 |
+
|
| 447 |
+
async def _pipe(self, path, value=None, batch_size=None, **kwargs):
|
| 448 |
+
if isinstance(path, str):
|
| 449 |
+
path = {path: value}
|
| 450 |
+
batch_size = batch_size or self.batch_size
|
| 451 |
+
return await _run_coros_in_chunks(
|
| 452 |
+
[self._pipe_file(k, v, **kwargs) for k, v in path.items()],
|
| 453 |
+
batch_size=batch_size,
|
| 454 |
+
nofiles=True,
|
| 455 |
+
)
|
| 456 |
+
|
| 457 |
+
async def _process_limits(self, url, start, end):
|
| 458 |
+
"""Helper for "Range"-based _cat_file"""
|
| 459 |
+
size = None
|
| 460 |
+
suff = False
|
| 461 |
+
if start is not None and start < 0:
|
| 462 |
+
# if start is negative and end None, end is the "suffix length"
|
| 463 |
+
if end is None:
|
| 464 |
+
end = -start
|
| 465 |
+
start = ""
|
| 466 |
+
suff = True
|
| 467 |
+
else:
|
| 468 |
+
size = size or (await self._info(url))["size"]
|
| 469 |
+
start = size + start
|
| 470 |
+
elif start is None:
|
| 471 |
+
start = 0
|
| 472 |
+
if not suff:
|
| 473 |
+
if end is not None and end < 0:
|
| 474 |
+
if start is not None:
|
| 475 |
+
size = size or (await self._info(url))["size"]
|
| 476 |
+
end = size + end
|
| 477 |
+
elif end is None:
|
| 478 |
+
end = ""
|
| 479 |
+
if isinstance(end, numbers.Integral):
|
| 480 |
+
end -= 1 # bytes range is inclusive
|
| 481 |
+
return f"bytes={start}-{end}"
|
| 482 |
+
|
| 483 |
+
async def _cat_file(self, path, start=None, end=None, **kwargs):
|
| 484 |
+
raise NotImplementedError
|
| 485 |
+
|
| 486 |
+
async def _cat(
|
| 487 |
+
self, path, recursive=False, on_error="raise", batch_size=None, **kwargs
|
| 488 |
+
):
|
| 489 |
+
paths = await self._expand_path(path, recursive=recursive)
|
| 490 |
+
coros = [self._cat_file(path, **kwargs) for path in paths]
|
| 491 |
+
batch_size = batch_size or self.batch_size
|
| 492 |
+
out = await _run_coros_in_chunks(
|
| 493 |
+
coros, batch_size=batch_size, nofiles=True, return_exceptions=True
|
| 494 |
+
)
|
| 495 |
+
if on_error == "raise":
|
| 496 |
+
ex = next(filter(is_exception, out), False)
|
| 497 |
+
if ex:
|
| 498 |
+
raise ex
|
| 499 |
+
if (
|
| 500 |
+
len(paths) > 1
|
| 501 |
+
or isinstance(path, list)
|
| 502 |
+
or paths[0] != self._strip_protocol(path)
|
| 503 |
+
):
|
| 504 |
+
return {
|
| 505 |
+
k: v
|
| 506 |
+
for k, v in zip(paths, out)
|
| 507 |
+
if on_error != "omit" or not is_exception(v)
|
| 508 |
+
}
|
| 509 |
+
else:
|
| 510 |
+
return out[0]
|
| 511 |
+
|
| 512 |
+
async def _cat_ranges(
|
| 513 |
+
self,
|
| 514 |
+
paths,
|
| 515 |
+
starts,
|
| 516 |
+
ends,
|
| 517 |
+
max_gap=None,
|
| 518 |
+
batch_size=None,
|
| 519 |
+
on_error="return",
|
| 520 |
+
**kwargs,
|
| 521 |
+
):
|
| 522 |
+
"""Get the contents of byte ranges from one or more files
|
| 523 |
+
|
| 524 |
+
Parameters
|
| 525 |
+
----------
|
| 526 |
+
paths: list
|
| 527 |
+
A list of of filepaths on this filesystems
|
| 528 |
+
starts, ends: int or list
|
| 529 |
+
Bytes limits of the read. If using a single int, the same value will be
|
| 530 |
+
used to read all the specified files.
|
| 531 |
+
on_error: "return" or "raise"
|
| 532 |
+
If "return" (default), any per-range exception is placed in the output
|
| 533 |
+
list at the corresponding position. Otherwise the first such exception
|
| 534 |
+
is raised. Matches ``AbstractFileSystem.cat_ranges``.
|
| 535 |
+
"""
|
| 536 |
+
if max_gap is not None:
|
| 537 |
+
# use utils.merge_offset_ranges
|
| 538 |
+
raise NotImplementedError
|
| 539 |
+
if not isinstance(paths, list):
|
| 540 |
+
raise TypeError
|
| 541 |
+
if not isinstance(starts, Iterable):
|
| 542 |
+
starts = [starts] * len(paths)
|
| 543 |
+
if not isinstance(ends, Iterable):
|
| 544 |
+
ends = [ends] * len(paths)
|
| 545 |
+
if len(starts) != len(paths) or len(ends) != len(paths):
|
| 546 |
+
raise ValueError
|
| 547 |
+
coros = [
|
| 548 |
+
self._cat_file(p, start=s, end=e, **kwargs)
|
| 549 |
+
for p, s, e in zip(paths, starts, ends)
|
| 550 |
+
]
|
| 551 |
+
batch_size = batch_size or self.batch_size
|
| 552 |
+
out = await _run_coros_in_chunks(
|
| 553 |
+
coros, batch_size=batch_size, nofiles=True, return_exceptions=True
|
| 554 |
+
)
|
| 555 |
+
if on_error != "return":
|
| 556 |
+
ex = next(filter(is_exception, out), None)
|
| 557 |
+
if ex is not None:
|
| 558 |
+
raise ex
|
| 559 |
+
return out
|
| 560 |
+
|
| 561 |
+
async def _put_file(self, lpath, rpath, mode="overwrite", **kwargs):
|
| 562 |
+
raise NotImplementedError
|
| 563 |
+
|
| 564 |
+
async def _put(
|
| 565 |
+
self,
|
| 566 |
+
lpath,
|
| 567 |
+
rpath,
|
| 568 |
+
recursive=False,
|
| 569 |
+
callback=DEFAULT_CALLBACK,
|
| 570 |
+
batch_size=None,
|
| 571 |
+
maxdepth=None,
|
| 572 |
+
**kwargs,
|
| 573 |
+
):
|
| 574 |
+
"""Copy file(s) from local.
|
| 575 |
+
|
| 576 |
+
Copies a specific file or tree of files (if recursive=True). If rpath
|
| 577 |
+
ends with a "/", it will be assumed to be a directory, and target files
|
| 578 |
+
will go within.
|
| 579 |
+
|
| 580 |
+
The put_file method will be called concurrently on a batch of files. The
|
| 581 |
+
batch_size option can configure the amount of futures that can be executed
|
| 582 |
+
at the same time. If it is -1, then all the files will be uploaded concurrently.
|
| 583 |
+
The default can be set for this instance by passing "batch_size" in the
|
| 584 |
+
constructor, or for all instances by setting the "gather_batch_size" key
|
| 585 |
+
in ``fsspec.config.conf``, falling back to 1/8th of the system limit .
|
| 586 |
+
"""
|
| 587 |
+
if isinstance(lpath, list) and isinstance(rpath, list):
|
| 588 |
+
# No need to expand paths when both source and destination
|
| 589 |
+
# are provided as lists
|
| 590 |
+
rpaths = rpath
|
| 591 |
+
lpaths = lpath
|
| 592 |
+
else:
|
| 593 |
+
source_is_str = isinstance(lpath, str)
|
| 594 |
+
if source_is_str:
|
| 595 |
+
lpath = make_path_posix(lpath)
|
| 596 |
+
fs = LocalFileSystem()
|
| 597 |
+
lpaths = fs.expand_path(lpath, recursive=recursive, maxdepth=maxdepth)
|
| 598 |
+
if source_is_str and (not recursive or maxdepth is not None):
|
| 599 |
+
# Non-recursive glob does not copy directories
|
| 600 |
+
lpaths = [p for p in lpaths if not (trailing_sep(p) or fs.isdir(p))]
|
| 601 |
+
if not lpaths:
|
| 602 |
+
return
|
| 603 |
+
|
| 604 |
+
source_is_file = len(lpaths) == 1
|
| 605 |
+
dest_is_dir = isinstance(rpath, str) and (
|
| 606 |
+
trailing_sep(rpath) or await self._isdir(rpath)
|
| 607 |
+
)
|
| 608 |
+
|
| 609 |
+
rpath = self._strip_protocol(rpath)
|
| 610 |
+
exists = source_is_str and (
|
| 611 |
+
(has_magic(lpath) and source_is_file)
|
| 612 |
+
or (not has_magic(lpath) and dest_is_dir and not trailing_sep(lpath))
|
| 613 |
+
)
|
| 614 |
+
rpaths = other_paths(
|
| 615 |
+
lpaths,
|
| 616 |
+
rpath,
|
| 617 |
+
exists=exists,
|
| 618 |
+
flatten=not source_is_str,
|
| 619 |
+
)
|
| 620 |
+
|
| 621 |
+
is_dir = {l: os.path.isdir(l) for l in lpaths}
|
| 622 |
+
rdirs = [r for l, r in zip(lpaths, rpaths) if is_dir[l]]
|
| 623 |
+
file_pairs = [(l, r) for l, r in zip(lpaths, rpaths) if not is_dir[l]]
|
| 624 |
+
|
| 625 |
+
await asyncio.gather(*[self._makedirs(d, exist_ok=True) for d in rdirs])
|
| 626 |
+
batch_size = batch_size or self.batch_size
|
| 627 |
+
|
| 628 |
+
coros = []
|
| 629 |
+
callback.set_size(len(file_pairs))
|
| 630 |
+
for lfile, rfile in file_pairs:
|
| 631 |
+
put_file = callback.branch_coro(self._put_file)
|
| 632 |
+
coros.append(put_file(lfile, rfile, **kwargs))
|
| 633 |
+
|
| 634 |
+
return await _run_coros_in_chunks(
|
| 635 |
+
coros, batch_size=batch_size, callback=callback
|
| 636 |
+
)
|
| 637 |
+
|
| 638 |
+
async def _get_file(self, rpath, lpath, **kwargs):
|
| 639 |
+
raise NotImplementedError
|
| 640 |
+
|
| 641 |
+
async def _get(
|
| 642 |
+
self,
|
| 643 |
+
rpath,
|
| 644 |
+
lpath,
|
| 645 |
+
recursive=False,
|
| 646 |
+
callback=DEFAULT_CALLBACK,
|
| 647 |
+
maxdepth=None,
|
| 648 |
+
**kwargs,
|
| 649 |
+
):
|
| 650 |
+
"""Copy file(s) to local.
|
| 651 |
+
|
| 652 |
+
Copies a specific file or tree of files (if recursive=True). If lpath
|
| 653 |
+
ends with a "/", it will be assumed to be a directory, and target files
|
| 654 |
+
will go within. Can submit a list of paths, which may be glob-patterns
|
| 655 |
+
and will be expanded.
|
| 656 |
+
|
| 657 |
+
The get_file method will be called concurrently on a batch of files. The
|
| 658 |
+
batch_size option can configure the amount of futures that can be executed
|
| 659 |
+
at the same time. If it is -1, then all the files will be uploaded concurrently.
|
| 660 |
+
The default can be set for this instance by passing "batch_size" in the
|
| 661 |
+
constructor, or for all instances by setting the "gather_batch_size" key
|
| 662 |
+
in ``fsspec.config.conf``, falling back to 1/8th of the system limit .
|
| 663 |
+
"""
|
| 664 |
+
if isinstance(lpath, list) and isinstance(rpath, list):
|
| 665 |
+
# No need to expand paths when both source and destination
|
| 666 |
+
# are provided as lists
|
| 667 |
+
rpaths = rpath
|
| 668 |
+
lpaths = lpath
|
| 669 |
+
else:
|
| 670 |
+
source_is_str = isinstance(rpath, str)
|
| 671 |
+
# First check for rpath trailing slash as _strip_protocol removes it.
|
| 672 |
+
source_not_trailing_sep = source_is_str and not trailing_sep(rpath)
|
| 673 |
+
rpath = self._strip_protocol(rpath)
|
| 674 |
+
rpaths = await self._expand_path(
|
| 675 |
+
rpath, recursive=recursive, maxdepth=maxdepth
|
| 676 |
+
)
|
| 677 |
+
if source_is_str and (not recursive or maxdepth is not None):
|
| 678 |
+
# Non-recursive glob does not copy directories
|
| 679 |
+
rpaths = [
|
| 680 |
+
p for p in rpaths if not (trailing_sep(p) or await self._isdir(p))
|
| 681 |
+
]
|
| 682 |
+
if not rpaths:
|
| 683 |
+
return
|
| 684 |
+
|
| 685 |
+
lpath = make_path_posix(lpath)
|
| 686 |
+
source_is_file = len(rpaths) == 1
|
| 687 |
+
dest_is_dir = isinstance(lpath, str) and (
|
| 688 |
+
trailing_sep(lpath) or LocalFileSystem().isdir(lpath)
|
| 689 |
+
)
|
| 690 |
+
|
| 691 |
+
exists = source_is_str and (
|
| 692 |
+
(has_magic(rpath) and source_is_file)
|
| 693 |
+
or (not has_magic(rpath) and dest_is_dir and source_not_trailing_sep)
|
| 694 |
+
)
|
| 695 |
+
lpaths = other_paths(
|
| 696 |
+
rpaths,
|
| 697 |
+
lpath,
|
| 698 |
+
exists=exists,
|
| 699 |
+
flatten=not source_is_str,
|
| 700 |
+
)
|
| 701 |
+
|
| 702 |
+
[os.makedirs(os.path.dirname(lp), exist_ok=True) for lp in lpaths]
|
| 703 |
+
batch_size = kwargs.pop("batch_size", self.batch_size)
|
| 704 |
+
|
| 705 |
+
coros = []
|
| 706 |
+
callback.set_size(len(lpaths))
|
| 707 |
+
for lpath, rpath in zip(lpaths, rpaths):
|
| 708 |
+
get_file = callback.branch_coro(self._get_file)
|
| 709 |
+
coros.append(get_file(rpath, lpath, **kwargs))
|
| 710 |
+
return await _run_coros_in_chunks(
|
| 711 |
+
coros, batch_size=batch_size, callback=callback
|
| 712 |
+
)
|
| 713 |
+
|
| 714 |
+
async def _isfile(self, path):
|
| 715 |
+
try:
|
| 716 |
+
return (await self._info(path))["type"] == "file"
|
| 717 |
+
except: # noqa: E722
|
| 718 |
+
return False
|
| 719 |
+
|
| 720 |
+
async def _isdir(self, path):
|
| 721 |
+
try:
|
| 722 |
+
return (await self._info(path))["type"] == "directory"
|
| 723 |
+
except OSError:
|
| 724 |
+
return False
|
| 725 |
+
|
| 726 |
+
async def _size(self, path):
|
| 727 |
+
return (await self._info(path)).get("size", None)
|
| 728 |
+
|
| 729 |
+
async def _sizes(self, paths, batch_size=None):
|
| 730 |
+
batch_size = batch_size or self.batch_size
|
| 731 |
+
return await _run_coros_in_chunks(
|
| 732 |
+
[self._size(p) for p in paths], batch_size=batch_size
|
| 733 |
+
)
|
| 734 |
+
|
| 735 |
+
async def _exists(self, path, **kwargs):
|
| 736 |
+
try:
|
| 737 |
+
await self._info(path, **kwargs)
|
| 738 |
+
return True
|
| 739 |
+
except FileNotFoundError:
|
| 740 |
+
return False
|
| 741 |
+
|
| 742 |
+
async def _info(self, path, **kwargs):
|
| 743 |
+
raise NotImplementedError
|
| 744 |
+
|
| 745 |
+
async def _ls(self, path, detail=True, **kwargs):
|
| 746 |
+
raise NotImplementedError
|
| 747 |
+
|
| 748 |
+
async def _walk(self, path, maxdepth=None, topdown=True, on_error="omit", **kwargs):
|
| 749 |
+
if maxdepth is not None and maxdepth < 1:
|
| 750 |
+
raise ValueError("maxdepth must be at least 1")
|
| 751 |
+
|
| 752 |
+
path = self._strip_protocol(path)
|
| 753 |
+
full_dirs = {}
|
| 754 |
+
dirs = {}
|
| 755 |
+
files = {}
|
| 756 |
+
|
| 757 |
+
detail = kwargs.pop("detail", False)
|
| 758 |
+
try:
|
| 759 |
+
listing = await self._ls(path, detail=True, **kwargs)
|
| 760 |
+
except (FileNotFoundError, OSError) as e:
|
| 761 |
+
if on_error == "raise":
|
| 762 |
+
raise
|
| 763 |
+
elif callable(on_error):
|
| 764 |
+
on_error(e)
|
| 765 |
+
if detail:
|
| 766 |
+
yield path, {}, {}
|
| 767 |
+
else:
|
| 768 |
+
yield path, [], []
|
| 769 |
+
return
|
| 770 |
+
|
| 771 |
+
for info in listing:
|
| 772 |
+
# each info name must be at least [path]/part , but here
|
| 773 |
+
# we check also for names like [path]/part/
|
| 774 |
+
pathname = info["name"].rstrip("/")
|
| 775 |
+
name = pathname.rsplit("/", 1)[-1]
|
| 776 |
+
if info["type"] == "directory" and pathname != path:
|
| 777 |
+
# do not include "self" path
|
| 778 |
+
full_dirs[name] = pathname
|
| 779 |
+
dirs[name] = info
|
| 780 |
+
elif pathname == path:
|
| 781 |
+
# file-like with same name as give path
|
| 782 |
+
files[""] = info
|
| 783 |
+
else:
|
| 784 |
+
files[name] = info
|
| 785 |
+
|
| 786 |
+
if not detail:
|
| 787 |
+
dirs = list(dirs)
|
| 788 |
+
files = list(files)
|
| 789 |
+
|
| 790 |
+
if topdown:
|
| 791 |
+
# Yield before recursion if walking top down
|
| 792 |
+
yield path, dirs, files
|
| 793 |
+
|
| 794 |
+
if maxdepth is not None:
|
| 795 |
+
maxdepth -= 1
|
| 796 |
+
if maxdepth < 1:
|
| 797 |
+
if not topdown:
|
| 798 |
+
yield path, dirs, files
|
| 799 |
+
return
|
| 800 |
+
|
| 801 |
+
for d in dirs:
|
| 802 |
+
async for _ in self._walk(
|
| 803 |
+
full_dirs[d],
|
| 804 |
+
maxdepth=maxdepth,
|
| 805 |
+
detail=detail,
|
| 806 |
+
topdown=topdown,
|
| 807 |
+
**kwargs,
|
| 808 |
+
):
|
| 809 |
+
yield _
|
| 810 |
+
|
| 811 |
+
if not topdown:
|
| 812 |
+
# Yield after recursion if walking bottom up
|
| 813 |
+
yield path, dirs, files
|
| 814 |
+
|
| 815 |
+
async def _glob(self, path, maxdepth=None, **kwargs):
|
| 816 |
+
if maxdepth is not None and maxdepth < 1:
|
| 817 |
+
raise ValueError("maxdepth must be at least 1")
|
| 818 |
+
|
| 819 |
+
import re
|
| 820 |
+
|
| 821 |
+
seps = (os.path.sep, os.path.altsep) if os.path.altsep else (os.path.sep,)
|
| 822 |
+
ends_with_sep = path.endswith(seps) # _strip_protocol strips trailing slash
|
| 823 |
+
path = self._strip_protocol(path)
|
| 824 |
+
append_slash_to_dirname = ends_with_sep or path.endswith(
|
| 825 |
+
tuple(sep + "**" for sep in seps)
|
| 826 |
+
)
|
| 827 |
+
idx_star = path.find("*") if path.find("*") >= 0 else len(path)
|
| 828 |
+
idx_qmark = path.find("?") if path.find("?") >= 0 else len(path)
|
| 829 |
+
idx_brace = path.find("[") if path.find("[") >= 0 else len(path)
|
| 830 |
+
|
| 831 |
+
min_idx = min(idx_star, idx_qmark, idx_brace)
|
| 832 |
+
|
| 833 |
+
detail = kwargs.pop("detail", False)
|
| 834 |
+
withdirs = kwargs.pop("withdirs", True)
|
| 835 |
+
|
| 836 |
+
if not has_magic(path):
|
| 837 |
+
if await self._exists(path, **kwargs):
|
| 838 |
+
if not detail:
|
| 839 |
+
return [path]
|
| 840 |
+
else:
|
| 841 |
+
return {path: await self._info(path, **kwargs)}
|
| 842 |
+
else:
|
| 843 |
+
if not detail:
|
| 844 |
+
return [] # glob of non-existent returns empty
|
| 845 |
+
else:
|
| 846 |
+
return {}
|
| 847 |
+
elif "/" in path[:min_idx]:
|
| 848 |
+
first_wildcard_idx = min_idx
|
| 849 |
+
min_idx = path[:min_idx].rindex("/")
|
| 850 |
+
root = path[
|
| 851 |
+
: min_idx + 1
|
| 852 |
+
] # everything up to the last / before the first wildcard
|
| 853 |
+
prefix = path[
|
| 854 |
+
min_idx + 1 : first_wildcard_idx
|
| 855 |
+
] # stem between last "/" and first wildcard
|
| 856 |
+
depth = path[min_idx + 1 :].count("/") + 1
|
| 857 |
+
else:
|
| 858 |
+
root = ""
|
| 859 |
+
prefix = path[:min_idx] # stem up to the first wildcard
|
| 860 |
+
depth = path[min_idx + 1 :].count("/") + 1
|
| 861 |
+
|
| 862 |
+
if "**" in path:
|
| 863 |
+
if maxdepth is not None:
|
| 864 |
+
idx_double_stars = path.find("**")
|
| 865 |
+
depth_double_stars = path[idx_double_stars:].count("/") + 1
|
| 866 |
+
depth = depth - depth_double_stars + maxdepth
|
| 867 |
+
else:
|
| 868 |
+
depth = None
|
| 869 |
+
|
| 870 |
+
# Pass the filename stem as prefix= so backends that support it such as
|
| 871 |
+
# gcsfs, s3fs and adlfs can filter server-side up to the first wildcard.
|
| 872 |
+
if prefix:
|
| 873 |
+
kwargs["prefix"] = prefix
|
| 874 |
+
allpaths = await self._find(
|
| 875 |
+
root, maxdepth=depth, withdirs=withdirs, detail=True, **kwargs
|
| 876 |
+
)
|
| 877 |
+
|
| 878 |
+
pattern = glob_translate(path + ("/" if ends_with_sep else ""))
|
| 879 |
+
pattern = re.compile(pattern)
|
| 880 |
+
|
| 881 |
+
out = {
|
| 882 |
+
p: info
|
| 883 |
+
for p, info in sorted(allpaths.items())
|
| 884 |
+
if pattern.match(
|
| 885 |
+
p + "/"
|
| 886 |
+
if append_slash_to_dirname and info["type"] == "directory"
|
| 887 |
+
else p
|
| 888 |
+
)
|
| 889 |
+
}
|
| 890 |
+
|
| 891 |
+
if detail:
|
| 892 |
+
return out
|
| 893 |
+
else:
|
| 894 |
+
return list(out)
|
| 895 |
+
|
| 896 |
+
async def _du(self, path, total=True, maxdepth=None, **kwargs):
|
| 897 |
+
sizes = {}
|
| 898 |
+
# async for?
|
| 899 |
+
for f in await self._find(path, maxdepth=maxdepth, **kwargs):
|
| 900 |
+
info = await self._info(f)
|
| 901 |
+
sizes[info["name"]] = info["size"]
|
| 902 |
+
if total:
|
| 903 |
+
return sum(sizes.values())
|
| 904 |
+
else:
|
| 905 |
+
return sizes
|
| 906 |
+
|
| 907 |
+
async def _find(self, path, maxdepth=None, withdirs=False, **kwargs):
|
| 908 |
+
path = self._strip_protocol(path)
|
| 909 |
+
out = {}
|
| 910 |
+
detail = kwargs.pop("detail", False)
|
| 911 |
+
|
| 912 |
+
# Add the root directory if withdirs is requested
|
| 913 |
+
# This is needed for posix glob compliance
|
| 914 |
+
if withdirs and path != "" and await self._isdir(path):
|
| 915 |
+
out[path] = await self._info(path)
|
| 916 |
+
|
| 917 |
+
# async for?
|
| 918 |
+
async for _, dirs, files in self._walk(path, maxdepth, detail=True, **kwargs):
|
| 919 |
+
if withdirs:
|
| 920 |
+
files.update(dirs)
|
| 921 |
+
out.update({info["name"]: info for name, info in files.items()})
|
| 922 |
+
if not out and (await self._isfile(path)):
|
| 923 |
+
# walk works on directories, but find should also return [path]
|
| 924 |
+
# when path happens to be a file
|
| 925 |
+
out[path] = {}
|
| 926 |
+
names = sorted(out)
|
| 927 |
+
if not detail:
|
| 928 |
+
return names
|
| 929 |
+
else:
|
| 930 |
+
return {name: out[name] for name in names}
|
| 931 |
+
|
| 932 |
+
async def _expand_path(
|
| 933 |
+
self, path, recursive=False, maxdepth=None, assume_literal=False
|
| 934 |
+
):
|
| 935 |
+
if maxdepth is not None and maxdepth < 1:
|
| 936 |
+
raise ValueError("maxdepth must be at least 1")
|
| 937 |
+
|
| 938 |
+
if isinstance(path, str):
|
| 939 |
+
out = await self._expand_path([path], recursive, maxdepth)
|
| 940 |
+
else:
|
| 941 |
+
out = set()
|
| 942 |
+
path = [self._strip_protocol(p) for p in path]
|
| 943 |
+
for p in path: # can gather here
|
| 944 |
+
if not assume_literal and has_magic(p):
|
| 945 |
+
bit = set(await self._glob(p, maxdepth=maxdepth))
|
| 946 |
+
out |= bit
|
| 947 |
+
if recursive:
|
| 948 |
+
# glob call above expanded one depth so if maxdepth is defined
|
| 949 |
+
# then decrement it in expand_path call below. If it is zero
|
| 950 |
+
# after decrementing then avoid expand_path call.
|
| 951 |
+
if maxdepth is not None and maxdepth <= 1:
|
| 952 |
+
continue
|
| 953 |
+
out |= set(
|
| 954 |
+
await self._expand_path(
|
| 955 |
+
list(bit),
|
| 956 |
+
recursive=recursive,
|
| 957 |
+
maxdepth=maxdepth - 1 if maxdepth is not None else None,
|
| 958 |
+
assume_literal=True,
|
| 959 |
+
)
|
| 960 |
+
)
|
| 961 |
+
continue
|
| 962 |
+
elif recursive:
|
| 963 |
+
rec = set(await self._find(p, maxdepth=maxdepth, withdirs=True))
|
| 964 |
+
out |= rec
|
| 965 |
+
if p not in out and (recursive is False or (await self._exists(p))):
|
| 966 |
+
# should only check once, for the root
|
| 967 |
+
out.add(p)
|
| 968 |
+
if not out:
|
| 969 |
+
raise FileNotFoundError(path)
|
| 970 |
+
return sorted(out)
|
| 971 |
+
|
| 972 |
+
async def _mkdir(self, path, create_parents=True, **kwargs):
|
| 973 |
+
pass # not necessary to implement, may not have directories
|
| 974 |
+
|
| 975 |
+
async def _makedirs(self, path, exist_ok=False):
|
| 976 |
+
pass # not necessary to implement, may not have directories
|
| 977 |
+
|
| 978 |
+
async def open_async(self, path, mode="rb", **kwargs):
|
| 979 |
+
if "b" not in mode or kwargs.get("compression"):
|
| 980 |
+
raise ValueError
|
| 981 |
+
raise NotImplementedError
|
| 982 |
+
|
| 983 |
+
|
| 984 |
+
def mirror_sync_methods(obj):
|
| 985 |
+
"""Populate sync and async methods for obj
|
| 986 |
+
|
| 987 |
+
For each method will create a sync version if the name refers to an async method
|
| 988 |
+
(coroutine) and there is no override in the child class; will create an async
|
| 989 |
+
method for the corresponding sync method if there is no implementation.
|
| 990 |
+
|
| 991 |
+
Uses the methods specified in
|
| 992 |
+
- async_methods: the set that an implementation is expected to provide
|
| 993 |
+
- default_async_methods: that can be derived from their sync version in
|
| 994 |
+
AbstractFileSystem
|
| 995 |
+
- AsyncFileSystem: async-specific default coroutines
|
| 996 |
+
"""
|
| 997 |
+
from fsspec import AbstractFileSystem
|
| 998 |
+
|
| 999 |
+
for method in set(async_methods + dir(AsyncFileSystem)):
|
| 1000 |
+
if not method.startswith("_"):
|
| 1001 |
+
continue
|
| 1002 |
+
smethod = method[1:]
|
| 1003 |
+
if private.match(method):
|
| 1004 |
+
isco = inspect.iscoroutinefunction(getattr(obj, method, None))
|
| 1005 |
+
unsync = getattr(getattr(obj, smethod, False), "__func__", None)
|
| 1006 |
+
is_default = unsync is getattr(AbstractFileSystem, smethod, "")
|
| 1007 |
+
if isco and is_default:
|
| 1008 |
+
mth = sync_wrapper(getattr(obj, method), obj=obj)
|
| 1009 |
+
elif inspect.isasyncgenfunction(getattr(obj, method, None)) and is_default:
|
| 1010 |
+
mth = async_gen_wrapper(getattr(obj, method), obj=obj)
|
| 1011 |
+
else:
|
| 1012 |
+
continue
|
| 1013 |
+
setattr(obj, smethod, mth)
|
| 1014 |
+
if not mth.__doc__:
|
| 1015 |
+
mth.__doc__ = getattr(
|
| 1016 |
+
getattr(AbstractFileSystem, smethod, None), "__doc__", ""
|
| 1017 |
+
)
|
| 1018 |
+
|
| 1019 |
+
|
| 1020 |
+
class FSSpecCoroutineCancel(Exception):
|
| 1021 |
+
pass
|
| 1022 |
+
|
| 1023 |
+
|
| 1024 |
+
def _dump_running_tasks(
|
| 1025 |
+
printout=True, cancel=True, exc=FSSpecCoroutineCancel, with_task=False
|
| 1026 |
+
):
|
| 1027 |
+
import traceback
|
| 1028 |
+
|
| 1029 |
+
tasks = [t for t in asyncio.tasks.all_tasks(loop[0]) if not t.done()]
|
| 1030 |
+
if printout:
|
| 1031 |
+
[task.print_stack() for task in tasks]
|
| 1032 |
+
out = [
|
| 1033 |
+
{
|
| 1034 |
+
"locals": task._coro.cr_frame.f_locals,
|
| 1035 |
+
"file": task._coro.cr_frame.f_code.co_filename,
|
| 1036 |
+
"firstline": task._coro.cr_frame.f_code.co_firstlineno,
|
| 1037 |
+
"linelo": task._coro.cr_frame.f_lineno,
|
| 1038 |
+
"stack": traceback.format_stack(task._coro.cr_frame),
|
| 1039 |
+
"task": task if with_task else None,
|
| 1040 |
+
}
|
| 1041 |
+
for task in tasks
|
| 1042 |
+
]
|
| 1043 |
+
if cancel:
|
| 1044 |
+
for t in tasks:
|
| 1045 |
+
cbs = t._callbacks
|
| 1046 |
+
t.cancel()
|
| 1047 |
+
asyncio.futures.Future.set_exception(t, exc)
|
| 1048 |
+
asyncio.futures.Future.cancel(t)
|
| 1049 |
+
[cb[0](t) for cb in cbs] # cancels any dependent concurrent.futures
|
| 1050 |
+
try:
|
| 1051 |
+
t._coro.throw(exc) # exits coro, unless explicitly handled
|
| 1052 |
+
except exc:
|
| 1053 |
+
pass
|
| 1054 |
+
return out
|
| 1055 |
+
|
| 1056 |
+
|
| 1057 |
+
class AbstractAsyncStreamedFile(AbstractBufferedFile):
|
| 1058 |
+
# no read buffering, and always auto-commit
|
| 1059 |
+
# TODO: readahead might still be useful here, but needs async version
|
| 1060 |
+
|
| 1061 |
+
async def read(self, length=-1):
|
| 1062 |
+
"""
|
| 1063 |
+
Return data from cache, or fetch pieces as necessary
|
| 1064 |
+
|
| 1065 |
+
Parameters
|
| 1066 |
+
----------
|
| 1067 |
+
length: int (-1)
|
| 1068 |
+
Number of bytes to read; if <0, all remaining bytes.
|
| 1069 |
+
"""
|
| 1070 |
+
length = -1 if length is None else int(length)
|
| 1071 |
+
if self.mode != "rb":
|
| 1072 |
+
raise ValueError("File not in read mode")
|
| 1073 |
+
if length < 0:
|
| 1074 |
+
length = self.size - self.loc
|
| 1075 |
+
if self.closed:
|
| 1076 |
+
raise ValueError("I/O operation on closed file.")
|
| 1077 |
+
if length == 0:
|
| 1078 |
+
# don't even bother calling fetch
|
| 1079 |
+
return b""
|
| 1080 |
+
out = await self._fetch_range(self.loc, self.loc + length)
|
| 1081 |
+
self.loc += len(out)
|
| 1082 |
+
return out
|
| 1083 |
+
|
| 1084 |
+
async def write(self, data):
|
| 1085 |
+
"""
|
| 1086 |
+
Write data to buffer.
|
| 1087 |
+
|
| 1088 |
+
Buffer only sent on flush() or if buffer is greater than
|
| 1089 |
+
or equal to blocksize.
|
| 1090 |
+
|
| 1091 |
+
Parameters
|
| 1092 |
+
----------
|
| 1093 |
+
data: bytes
|
| 1094 |
+
Set of bytes to be written.
|
| 1095 |
+
"""
|
| 1096 |
+
if self.mode not in {"wb", "ab"}:
|
| 1097 |
+
raise ValueError("File not in write mode")
|
| 1098 |
+
if self.closed:
|
| 1099 |
+
raise ValueError("I/O operation on closed file.")
|
| 1100 |
+
if self.forced:
|
| 1101 |
+
raise ValueError("This file has been force-flushed, can only close")
|
| 1102 |
+
out = self.buffer.write(data)
|
| 1103 |
+
self.loc += out
|
| 1104 |
+
if self.buffer.tell() >= self.blocksize:
|
| 1105 |
+
await self.flush()
|
| 1106 |
+
return out
|
| 1107 |
+
|
| 1108 |
+
async def close(self):
|
| 1109 |
+
"""Close file
|
| 1110 |
+
|
| 1111 |
+
Finalizes writes, discards cache
|
| 1112 |
+
"""
|
| 1113 |
+
if getattr(self, "_unclosable", False):
|
| 1114 |
+
return
|
| 1115 |
+
if self.closed:
|
| 1116 |
+
return
|
| 1117 |
+
if self.mode == "rb":
|
| 1118 |
+
self.cache = None
|
| 1119 |
+
else:
|
| 1120 |
+
if not self.forced:
|
| 1121 |
+
await self.flush(force=True)
|
| 1122 |
+
|
| 1123 |
+
if self.fs is not None:
|
| 1124 |
+
self.fs.invalidate_cache(self.path)
|
| 1125 |
+
self.fs.invalidate_cache(self.fs._parent(self.path))
|
| 1126 |
+
|
| 1127 |
+
self.closed = True
|
| 1128 |
+
|
| 1129 |
+
async def flush(self, force=False):
|
| 1130 |
+
if self.closed:
|
| 1131 |
+
raise ValueError("Flush on closed file")
|
| 1132 |
+
if force and self.forced:
|
| 1133 |
+
raise ValueError("Force flush cannot be called more than once")
|
| 1134 |
+
if force:
|
| 1135 |
+
self.forced = True
|
| 1136 |
+
|
| 1137 |
+
if self.mode not in {"wb", "ab"}:
|
| 1138 |
+
# no-op to flush on read-mode
|
| 1139 |
+
return
|
| 1140 |
+
|
| 1141 |
+
if not force and self.buffer.tell() < self.blocksize:
|
| 1142 |
+
# Defer write on small block
|
| 1143 |
+
return
|
| 1144 |
+
|
| 1145 |
+
if self.offset is None:
|
| 1146 |
+
# Initialize a multipart upload
|
| 1147 |
+
self.offset = 0
|
| 1148 |
+
try:
|
| 1149 |
+
await self._initiate_upload()
|
| 1150 |
+
except:
|
| 1151 |
+
self.closed = True
|
| 1152 |
+
raise
|
| 1153 |
+
|
| 1154 |
+
if await self._upload_chunk(final=force) is not False:
|
| 1155 |
+
self.offset += self.buffer.seek(0, 2)
|
| 1156 |
+
self.buffer = io.BytesIO()
|
| 1157 |
+
|
| 1158 |
+
async def __aenter__(self):
|
| 1159 |
+
return self
|
| 1160 |
+
|
| 1161 |
+
async def __aexit__(self, exc_type, exc_val, exc_tb):
|
| 1162 |
+
await self.close()
|
| 1163 |
+
|
| 1164 |
+
async def _fetch_range(self, start, end):
|
| 1165 |
+
raise NotImplementedError
|
| 1166 |
+
|
| 1167 |
+
async def _initiate_upload(self):
|
| 1168 |
+
pass
|
| 1169 |
+
|
| 1170 |
+
async def _upload_chunk(self, final=False):
|
| 1171 |
+
raise NotImplementedError
|
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/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)
|
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/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()
|
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/compression.py
AD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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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)
|
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/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
|
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/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 |
+
"""
|
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/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()
|
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/__init__.py
ADDED
|
File without changes
|
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/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
|
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/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
|
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/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()
|
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/cache_metadata.py
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import time
|
| 5 |
+
from typing import TYPE_CHECKING
|
| 6 |
+
|
| 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
|
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/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)
|
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/chained.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import ClassVar
|
| 2 |
+
|
| 3 |
+
from fsspec import AbstractFileSystem
|
| 4 |
+
|
| 5 |
+
__all__ = ("ChainedFileSystem",)
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class ChainedFileSystem(AbstractFileSystem):
|
| 9 |
+
"""Chained filesystem base class.
|
| 10 |
+
|
| 11 |
+
A chained filesystem is designed to be layered over another FS.
|
| 12 |
+
This is useful to implement things like caching.
|
| 13 |
+
|
| 14 |
+
This base class does very little on its own, but is used as a marker
|
| 15 |
+
that the class is designed for chaining.
|
| 16 |
+
|
| 17 |
+
Right now this is only used in `url_to_fs` to provide the path argument
|
| 18 |
+
(`fo`) to the chained filesystem from the underlying filesystem.
|
| 19 |
+
|
| 20 |
+
Additional functionality may be added in the future.
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
protocol: ClassVar[str] = "chained"
|
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/dask.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import dask
|
| 2 |
+
from distributed.client import Client, _get_global_client
|
| 3 |
+
from distributed.worker import Worker
|
| 4 |
+
|
| 5 |
+
from fsspec import filesystem
|
| 6 |
+
from fsspec.spec import AbstractBufferedFile, AbstractFileSystem
|
| 7 |
+
from fsspec.utils import infer_storage_options
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def _get_client(client):
|
| 11 |
+
if client is None:
|
| 12 |
+
return _get_global_client()
|
| 13 |
+
elif isinstance(client, Client):
|
| 14 |
+
return client
|
| 15 |
+
else:
|
| 16 |
+
# e.g., connection string
|
| 17 |
+
return Client(client)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _in_worker():
|
| 21 |
+
return bool(Worker._instances)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class DaskWorkerFileSystem(AbstractFileSystem):
|
| 25 |
+
"""View files accessible to a worker as any other remote file-system
|
| 26 |
+
|
| 27 |
+
When instances are run on the worker, uses the real filesystem. When
|
| 28 |
+
run on the client, they call the worker to provide information or data.
|
| 29 |
+
|
| 30 |
+
**Warning** this implementation is experimental, and read-only for now.
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
def __init__(
|
| 34 |
+
self, target_protocol=None, target_options=None, fs=None, client=None, **kwargs
|
| 35 |
+
):
|
| 36 |
+
super().__init__(**kwargs)
|
| 37 |
+
if not (fs is None) ^ (target_protocol is None):
|
| 38 |
+
raise ValueError(
|
| 39 |
+
"Please provide one of filesystem instance (fs) or"
|
| 40 |
+
" target_protocol, not both"
|
| 41 |
+
)
|
| 42 |
+
self.target_protocol = target_protocol
|
| 43 |
+
self.target_options = target_options
|
| 44 |
+
self.worker = None
|
| 45 |
+
self.client = client
|
| 46 |
+
self.fs = fs
|
| 47 |
+
self._determine_worker()
|
| 48 |
+
|
| 49 |
+
@staticmethod
|
| 50 |
+
def _get_kwargs_from_urls(path):
|
| 51 |
+
so = infer_storage_options(path)
|
| 52 |
+
if "host" in so and "port" in so:
|
| 53 |
+
return {"client": f"{so['host']}:{so['port']}"}
|
| 54 |
+
else:
|
| 55 |
+
return {}
|
| 56 |
+
|
| 57 |
+
def _determine_worker(self):
|
| 58 |
+
if _in_worker():
|
| 59 |
+
self.worker = True
|
| 60 |
+
if self.fs is None:
|
| 61 |
+
self.fs = filesystem(
|
| 62 |
+
self.target_protocol, **(self.target_options or {})
|
| 63 |
+
)
|
| 64 |
+
else:
|
| 65 |
+
self.worker = False
|
| 66 |
+
self.client = _get_client(self.client)
|
| 67 |
+
self.rfs = dask.delayed(self)
|
| 68 |
+
|
| 69 |
+
def mkdir(self, *args, **kwargs):
|
| 70 |
+
if self.worker:
|
| 71 |
+
self.fs.mkdir(*args, **kwargs)
|
| 72 |
+
else:
|
| 73 |
+
self.rfs.mkdir(*args, **kwargs).compute()
|
| 74 |
+
|
| 75 |
+
def rm(self, *args, **kwargs):
|
| 76 |
+
if self.worker:
|
| 77 |
+
self.fs.rm(*args, **kwargs)
|
| 78 |
+
else:
|
| 79 |
+
self.rfs.rm(*args, **kwargs).compute()
|
| 80 |
+
|
| 81 |
+
def copy(self, *args, **kwargs):
|
| 82 |
+
if self.worker:
|
| 83 |
+
self.fs.copy(*args, **kwargs)
|
| 84 |
+
else:
|
| 85 |
+
self.rfs.copy(*args, **kwargs).compute()
|
| 86 |
+
|
| 87 |
+
def mv(self, *args, **kwargs):
|
| 88 |
+
if self.worker:
|
| 89 |
+
self.fs.mv(*args, **kwargs)
|
| 90 |
+
else:
|
| 91 |
+
self.rfs.mv(*args, **kwargs).compute()
|
| 92 |
+
|
| 93 |
+
def ls(self, *args, **kwargs):
|
| 94 |
+
if self.worker:
|
| 95 |
+
return self.fs.ls(*args, **kwargs)
|
| 96 |
+
else:
|
| 97 |
+
return self.rfs.ls(*args, **kwargs).compute()
|
| 98 |
+
|
| 99 |
+
def _open(
|
| 100 |
+
self,
|
| 101 |
+
path,
|
| 102 |
+
mode="rb",
|
| 103 |
+
block_size=None,
|
| 104 |
+
autocommit=True,
|
| 105 |
+
cache_options=None,
|
| 106 |
+
**kwargs,
|
| 107 |
+
):
|
| 108 |
+
if self.worker:
|
| 109 |
+
return self.fs._open(
|
| 110 |
+
path,
|
| 111 |
+
mode=mode,
|
| 112 |
+
block_size=block_size,
|
| 113 |
+
autocommit=autocommit,
|
| 114 |
+
cache_options=cache_options,
|
| 115 |
+
**kwargs,
|
| 116 |
+
)
|
| 117 |
+
else:
|
| 118 |
+
return DaskFile(
|
| 119 |
+
fs=self,
|
| 120 |
+
path=path,
|
| 121 |
+
mode=mode,
|
| 122 |
+
block_size=block_size,
|
| 123 |
+
autocommit=autocommit,
|
| 124 |
+
cache_options=cache_options,
|
| 125 |
+
**kwargs,
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
def fetch_range(self, path, mode, start, end):
|
| 129 |
+
if self.worker:
|
| 130 |
+
with self._open(path, mode) as f:
|
| 131 |
+
f.seek(start)
|
| 132 |
+
return f.read(end - start)
|
| 133 |
+
else:
|
| 134 |
+
return self.rfs.fetch_range(path, mode, start, end).compute()
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
class DaskFile(AbstractBufferedFile):
|
| 138 |
+
def __init__(self, mode="rb", **kwargs):
|
| 139 |
+
if mode != "rb":
|
| 140 |
+
raise ValueError('Remote dask files can only be opened in "rb" mode')
|
| 141 |
+
super().__init__(**kwargs)
|
| 142 |
+
|
| 143 |
+
def _upload_chunk(self, final=False):
|
| 144 |
+
pass
|
| 145 |
+
|
| 146 |
+
def _initiate_upload(self):
|
| 147 |
+
"""Create remote file/upload"""
|
| 148 |
+
pass
|
| 149 |
+
|
| 150 |
+
def _fetch_range(self, start, end):
|
| 151 |
+
"""Get the specified set of bytes from remote"""
|
| 152 |
+
return self.fs.fetch_range(self.path, self.mode, start, end)
|
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/data.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
import io
|
| 3 |
+
from urllib.parse import unquote
|
| 4 |
+
|
| 5 |
+
from fsspec import AbstractFileSystem
|
| 6 |
+
from fsspec.utils import stringify_path
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class DataFileSystem(AbstractFileSystem):
|
| 10 |
+
"""A handy decoder for data-URLs
|
| 11 |
+
|
| 12 |
+
Example
|
| 13 |
+
-------
|
| 14 |
+
>>> with fsspec.open("data:,Hello%2C%20World%21") as f:
|
| 15 |
+
... print(f.read())
|
| 16 |
+
b"Hello, World!"
|
| 17 |
+
|
| 18 |
+
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
protocol = "data"
|
| 22 |
+
|
| 23 |
+
def __init__(self, **kwargs):
|
| 24 |
+
"""No parameters for this filesystem"""
|
| 25 |
+
super().__init__(**kwargs)
|
| 26 |
+
|
| 27 |
+
@classmethod
|
| 28 |
+
def _strip_protocol(cls, path):
|
| 29 |
+
if isinstance(path, list):
|
| 30 |
+
return [cls._strip_protocol(p) for p in path]
|
| 31 |
+
path = stringify_path(path)
|
| 32 |
+
if path.startswith("data://"):
|
| 33 |
+
path = path[7:]
|
| 34 |
+
elif path.startswith("data:"):
|
| 35 |
+
path = path[5:]
|
| 36 |
+
# Do NOT strip trailing slashes, as they may be meaningful base64 characters
|
| 37 |
+
# or percent-encoded data content
|
| 38 |
+
return path
|
| 39 |
+
|
| 40 |
+
def cat_file(self, path, start=None, end=None, **kwargs):
|
| 41 |
+
pref, data = path.split(",", 1)
|
| 42 |
+
if pref.endswith("base64"):
|
| 43 |
+
return base64.b64decode(data)[start:end]
|
| 44 |
+
return unquote(data).encode()[start:end]
|
| 45 |
+
|
| 46 |
+
def info(self, path, **kwargs):
|
| 47 |
+
pref, name = path.split(",", 1)
|
| 48 |
+
data = self.cat_file(path)
|
| 49 |
+
mime = pref.split(":", 1)[1].split(";", 1)[0]
|
| 50 |
+
return {"name": name, "size": len(data), "type": "file", "mimetype": mime}
|
| 51 |
+
|
| 52 |
+
def _open(
|
| 53 |
+
self,
|
| 54 |
+
path,
|
| 55 |
+
mode="rb",
|
| 56 |
+
block_size=None,
|
| 57 |
+
autocommit=True,
|
| 58 |
+
cache_options=None,
|
| 59 |
+
**kwargs,
|
| 60 |
+
):
|
| 61 |
+
if "r" not in mode:
|
| 62 |
+
raise ValueError("Read only filesystem")
|
| 63 |
+
return io.BytesIO(self.cat_file(path))
|
| 64 |
+
|
| 65 |
+
@staticmethod
|
| 66 |
+
def encode(data: bytes, mime: str | None = None):
|
| 67 |
+
"""Format the given data into data-URL syntax
|
| 68 |
+
|
| 69 |
+
This version always base64 encodes, even when the data is ascii/url-safe.
|
| 70 |
+
"""
|
| 71 |
+
return f"data:{mime or ''};base64,{base64.b64encode(data).decode()}"
|
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/dbfs.py
ADDED
|
@@ -0,0 +1,497 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import base64
|
| 4 |
+
import urllib
|
| 5 |
+
|
| 6 |
+
import requests
|
| 7 |
+
from requests.adapters import HTTPAdapter, Retry
|
| 8 |
+
from typing_extensions import override
|
| 9 |
+
|
| 10 |
+
from fsspec import AbstractFileSystem
|
| 11 |
+
from fsspec.spec import AbstractBufferedFile
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class DatabricksException(Exception):
|
| 15 |
+
"""
|
| 16 |
+
Helper class for exceptions raised in this module.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
def __init__(self, error_code, message, details=None):
|
| 20 |
+
"""Create a new DatabricksException"""
|
| 21 |
+
super().__init__(message)
|
| 22 |
+
|
| 23 |
+
self.error_code = error_code
|
| 24 |
+
self.message = message
|
| 25 |
+
self.details = details
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class DatabricksFileSystem(AbstractFileSystem):
|
| 29 |
+
"""
|
| 30 |
+
Get access to the Databricks filesystem implementation over HTTP.
|
| 31 |
+
Can be used inside and outside of a databricks cluster.
|
| 32 |
+
"""
|
| 33 |
+
|
| 34 |
+
def __init__(self, instance, token, **kwargs):
|
| 35 |
+
"""
|
| 36 |
+
Create a new DatabricksFileSystem.
|
| 37 |
+
|
| 38 |
+
Parameters
|
| 39 |
+
----------
|
| 40 |
+
instance: str
|
| 41 |
+
The instance URL of the databricks cluster.
|
| 42 |
+
For example for an Azure databricks cluster, this
|
| 43 |
+
has the form adb-<some-number>.<two digits>.azuredatabricks.net.
|
| 44 |
+
token: str
|
| 45 |
+
Your personal token. Find out more
|
| 46 |
+
here: https://docs.databricks.com/dev-tools/api/latest/authentication.html
|
| 47 |
+
"""
|
| 48 |
+
self.instance = instance
|
| 49 |
+
self.token = token
|
| 50 |
+
self.session = requests.Session()
|
| 51 |
+
self.retries = Retry(
|
| 52 |
+
total=10,
|
| 53 |
+
backoff_factor=0.05,
|
| 54 |
+
status_forcelist=[408, 429, 500, 502, 503, 504],
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
self.session.mount("https://", HTTPAdapter(max_retries=self.retries))
|
| 58 |
+
self.session.headers.update({"Authorization": f"Bearer {self.token}"})
|
| 59 |
+
|
| 60 |
+
super().__init__(**kwargs)
|
| 61 |
+
|
| 62 |
+
@override
|
| 63 |
+
def _ls_from_cache(self, path) -> list[dict[str, str | int]] | None:
|
| 64 |
+
"""Check cache for listing
|
| 65 |
+
|
| 66 |
+
Returns listing, if found (may be empty list for a directory that
|
| 67 |
+
exists but contains nothing), None if not in cache.
|
| 68 |
+
"""
|
| 69 |
+
self.dircache.pop(path.rstrip("/"), None)
|
| 70 |
+
|
| 71 |
+
parent = self._parent(path)
|
| 72 |
+
if parent in self.dircache:
|
| 73 |
+
for entry in self.dircache[parent]:
|
| 74 |
+
if entry["name"] == path.rstrip("/"):
|
| 75 |
+
if entry["type"] != "directory":
|
| 76 |
+
return [entry]
|
| 77 |
+
return []
|
| 78 |
+
raise FileNotFoundError(path)
|
| 79 |
+
|
| 80 |
+
def ls(self, path, detail=True, **kwargs):
|
| 81 |
+
"""
|
| 82 |
+
List the contents of the given path.
|
| 83 |
+
|
| 84 |
+
Parameters
|
| 85 |
+
----------
|
| 86 |
+
path: str
|
| 87 |
+
Absolute path
|
| 88 |
+
detail: bool
|
| 89 |
+
Return not only the list of filenames,
|
| 90 |
+
but also additional information on file sizes
|
| 91 |
+
and types.
|
| 92 |
+
"""
|
| 93 |
+
try:
|
| 94 |
+
out = self._ls_from_cache(path)
|
| 95 |
+
except FileNotFoundError:
|
| 96 |
+
# This happens if the `path`'s parent was cached, but `path` is not
|
| 97 |
+
# there. This suggests that `path` is new since the parent was
|
| 98 |
+
# cached. Attempt to invalidate parent's cache before continuing.
|
| 99 |
+
self.dircache.pop(self._parent(path), None)
|
| 100 |
+
out = None
|
| 101 |
+
|
| 102 |
+
if not out:
|
| 103 |
+
try:
|
| 104 |
+
r = self._send_to_api(
|
| 105 |
+
method="get", endpoint="list", json={"path": path}
|
| 106 |
+
)
|
| 107 |
+
except DatabricksException as e:
|
| 108 |
+
if e.error_code == "RESOURCE_DOES_NOT_EXIST":
|
| 109 |
+
raise FileNotFoundError(e.message) from e
|
| 110 |
+
|
| 111 |
+
raise
|
| 112 |
+
files = r.get("files", [])
|
| 113 |
+
out = [
|
| 114 |
+
{
|
| 115 |
+
"name": o["path"],
|
| 116 |
+
"type": "directory" if o["is_dir"] else "file",
|
| 117 |
+
"size": o["file_size"],
|
| 118 |
+
}
|
| 119 |
+
for o in files
|
| 120 |
+
]
|
| 121 |
+
self.dircache[path] = out
|
| 122 |
+
|
| 123 |
+
if detail:
|
| 124 |
+
return out
|
| 125 |
+
return [o["name"] for o in out]
|
| 126 |
+
|
| 127 |
+
def makedirs(self, path, exist_ok=True):
|
| 128 |
+
"""
|
| 129 |
+
Create a given absolute path and all of its parents.
|
| 130 |
+
|
| 131 |
+
Parameters
|
| 132 |
+
----------
|
| 133 |
+
path: str
|
| 134 |
+
Absolute path to create
|
| 135 |
+
exist_ok: bool
|
| 136 |
+
If false, checks if the folder
|
| 137 |
+
exists before creating it (and raises an
|
| 138 |
+
Exception if this is the case)
|
| 139 |
+
"""
|
| 140 |
+
if not exist_ok:
|
| 141 |
+
try:
|
| 142 |
+
# If the following succeeds, the path is already present
|
| 143 |
+
self._send_to_api(
|
| 144 |
+
method="get", endpoint="get-status", json={"path": path}
|
| 145 |
+
)
|
| 146 |
+
raise FileExistsError(f"Path {path} already exists")
|
| 147 |
+
except DatabricksException as e:
|
| 148 |
+
if e.error_code == "RESOURCE_DOES_NOT_EXIST":
|
| 149 |
+
pass
|
| 150 |
+
|
| 151 |
+
try:
|
| 152 |
+
self._send_to_api(method="post", endpoint="mkdirs", json={"path": path})
|
| 153 |
+
except DatabricksException as e:
|
| 154 |
+
if e.error_code == "RESOURCE_ALREADY_EXISTS":
|
| 155 |
+
raise FileExistsError(e.message) from e
|
| 156 |
+
|
| 157 |
+
raise
|
| 158 |
+
self.invalidate_cache(self._parent(path))
|
| 159 |
+
|
| 160 |
+
def mkdir(self, path, create_parents=True, **kwargs):
|
| 161 |
+
"""
|
| 162 |
+
Create a given absolute path and all of its parents.
|
| 163 |
+
|
| 164 |
+
Parameters
|
| 165 |
+
----------
|
| 166 |
+
path: str
|
| 167 |
+
Absolute path to create
|
| 168 |
+
create_parents: bool
|
| 169 |
+
Whether to create all parents or not.
|
| 170 |
+
"False" is not implemented so far.
|
| 171 |
+
"""
|
| 172 |
+
if not create_parents:
|
| 173 |
+
raise NotImplementedError
|
| 174 |
+
|
| 175 |
+
self.mkdirs(path, **kwargs)
|
| 176 |
+
|
| 177 |
+
def rm(self, path, recursive=False, **kwargs):
|
| 178 |
+
"""
|
| 179 |
+
Remove the file or folder at the given absolute path.
|
| 180 |
+
|
| 181 |
+
Parameters
|
| 182 |
+
----------
|
| 183 |
+
path: str
|
| 184 |
+
Absolute path what to remove
|
| 185 |
+
recursive: bool
|
| 186 |
+
Recursively delete all files in a folder.
|
| 187 |
+
"""
|
| 188 |
+
try:
|
| 189 |
+
self._send_to_api(
|
| 190 |
+
method="post",
|
| 191 |
+
endpoint="delete",
|
| 192 |
+
json={"path": path, "recursive": recursive},
|
| 193 |
+
)
|
| 194 |
+
except DatabricksException as e:
|
| 195 |
+
# This is not really an exception, it just means
|
| 196 |
+
# not everything was deleted so far
|
| 197 |
+
if e.error_code == "PARTIAL_DELETE":
|
| 198 |
+
self.rm(path=path, recursive=recursive)
|
| 199 |
+
elif e.error_code == "IO_ERROR":
|
| 200 |
+
# Using the same exception as the os module would use here
|
| 201 |
+
raise OSError(e.message) from e
|
| 202 |
+
|
| 203 |
+
raise
|
| 204 |
+
self.invalidate_cache(self._parent(path))
|
| 205 |
+
|
| 206 |
+
def mv(
|
| 207 |
+
self, source_path, destination_path, recursive=False, maxdepth=None, **kwargs
|
| 208 |
+
):
|
| 209 |
+
"""
|
| 210 |
+
Move a source to a destination path.
|
| 211 |
+
|
| 212 |
+
A note from the original [databricks API manual]
|
| 213 |
+
(https://docs.databricks.com/dev-tools/api/latest/dbfs.html#move).
|
| 214 |
+
|
| 215 |
+
When moving a large number of files the API call will time out after
|
| 216 |
+
approximately 60s, potentially resulting in partially moved data.
|
| 217 |
+
Therefore, for operations that move more than 10k files, we strongly
|
| 218 |
+
discourage using the DBFS REST API.
|
| 219 |
+
|
| 220 |
+
Parameters
|
| 221 |
+
----------
|
| 222 |
+
source_path: str
|
| 223 |
+
From where to move (absolute path)
|
| 224 |
+
destination_path: str
|
| 225 |
+
To where to move (absolute path)
|
| 226 |
+
recursive: bool
|
| 227 |
+
Not implemented to far.
|
| 228 |
+
maxdepth:
|
| 229 |
+
Not implemented to far.
|
| 230 |
+
"""
|
| 231 |
+
if recursive:
|
| 232 |
+
raise NotImplementedError
|
| 233 |
+
if maxdepth:
|
| 234 |
+
raise NotImplementedError
|
| 235 |
+
|
| 236 |
+
try:
|
| 237 |
+
self._send_to_api(
|
| 238 |
+
method="post",
|
| 239 |
+
endpoint="move",
|
| 240 |
+
json={"source_path": source_path, "destination_path": destination_path},
|
| 241 |
+
)
|
| 242 |
+
except DatabricksException as e:
|
| 243 |
+
if e.error_code == "RESOURCE_DOES_NOT_EXIST":
|
| 244 |
+
raise FileNotFoundError(e.message) from e
|
| 245 |
+
elif e.error_code == "RESOURCE_ALREADY_EXISTS":
|
| 246 |
+
raise FileExistsError(e.message) from e
|
| 247 |
+
|
| 248 |
+
raise
|
| 249 |
+
self.invalidate_cache(self._parent(source_path))
|
| 250 |
+
self.invalidate_cache(self._parent(destination_path))
|
| 251 |
+
|
| 252 |
+
def _open(self, path, mode="rb", block_size="default", **kwargs):
|
| 253 |
+
"""
|
| 254 |
+
Overwrite the base class method to make sure to create a DBFile.
|
| 255 |
+
All arguments are copied from the base method.
|
| 256 |
+
|
| 257 |
+
Only the default blocksize is allowed.
|
| 258 |
+
"""
|
| 259 |
+
return DatabricksFile(self, path, mode=mode, block_size=block_size, **kwargs)
|
| 260 |
+
|
| 261 |
+
def _send_to_api(self, method, endpoint, json):
|
| 262 |
+
"""
|
| 263 |
+
Send the given json to the DBFS API
|
| 264 |
+
using a get or post request (specified by the argument `method`).
|
| 265 |
+
|
| 266 |
+
Parameters
|
| 267 |
+
----------
|
| 268 |
+
method: str
|
| 269 |
+
Which http method to use for communication; "get" or "post".
|
| 270 |
+
endpoint: str
|
| 271 |
+
Where to send the request to (last part of the API URL)
|
| 272 |
+
json: dict
|
| 273 |
+
Dictionary of information to send
|
| 274 |
+
"""
|
| 275 |
+
if method == "post":
|
| 276 |
+
session_call = self.session.post
|
| 277 |
+
elif method == "get":
|
| 278 |
+
session_call = self.session.get
|
| 279 |
+
else:
|
| 280 |
+
raise ValueError(f"Do not understand method {method}")
|
| 281 |
+
|
| 282 |
+
url = urllib.parse.urljoin(f"https://{self.instance}/api/2.0/dbfs/", endpoint)
|
| 283 |
+
|
| 284 |
+
r = session_call(url, json=json)
|
| 285 |
+
|
| 286 |
+
# The DBFS API will return a json, also in case of an exception.
|
| 287 |
+
# We want to preserve this information as good as possible.
|
| 288 |
+
try:
|
| 289 |
+
r.raise_for_status()
|
| 290 |
+
except requests.HTTPError as e:
|
| 291 |
+
# try to extract json error message
|
| 292 |
+
# if that fails, fall back to the original exception
|
| 293 |
+
try:
|
| 294 |
+
exception_json = e.response.json()
|
| 295 |
+
except Exception:
|
| 296 |
+
raise e from None
|
| 297 |
+
|
| 298 |
+
raise DatabricksException(**exception_json) from e
|
| 299 |
+
|
| 300 |
+
return r.json()
|
| 301 |
+
|
| 302 |
+
def _create_handle(self, path, overwrite=True):
|
| 303 |
+
"""
|
| 304 |
+
Internal function to create a handle, which can be used to
|
| 305 |
+
write blocks of a file to DBFS.
|
| 306 |
+
A handle has a unique identifier which needs to be passed
|
| 307 |
+
whenever written during this transaction.
|
| 308 |
+
The handle is active for 10 minutes - after that a new
|
| 309 |
+
write transaction needs to be created.
|
| 310 |
+
Make sure to close the handle after you are finished.
|
| 311 |
+
|
| 312 |
+
Parameters
|
| 313 |
+
----------
|
| 314 |
+
path: str
|
| 315 |
+
Absolute path for this file.
|
| 316 |
+
overwrite: bool
|
| 317 |
+
If a file already exist at this location, either overwrite
|
| 318 |
+
it or raise an exception.
|
| 319 |
+
"""
|
| 320 |
+
try:
|
| 321 |
+
r = self._send_to_api(
|
| 322 |
+
method="post",
|
| 323 |
+
endpoint="create",
|
| 324 |
+
json={"path": path, "overwrite": overwrite},
|
| 325 |
+
)
|
| 326 |
+
return r["handle"]
|
| 327 |
+
except DatabricksException as e:
|
| 328 |
+
if e.error_code == "RESOURCE_ALREADY_EXISTS":
|
| 329 |
+
raise FileExistsError(e.message) from e
|
| 330 |
+
|
| 331 |
+
raise
|
| 332 |
+
|
| 333 |
+
def _close_handle(self, handle):
|
| 334 |
+
"""
|
| 335 |
+
Close a handle, which was opened by :func:`_create_handle`.
|
| 336 |
+
|
| 337 |
+
Parameters
|
| 338 |
+
----------
|
| 339 |
+
handle: str
|
| 340 |
+
Which handle to close.
|
| 341 |
+
"""
|
| 342 |
+
try:
|
| 343 |
+
self._send_to_api(method="post", endpoint="close", json={"handle": handle})
|
| 344 |
+
except DatabricksException as e:
|
| 345 |
+
if e.error_code == "RESOURCE_DOES_NOT_EXIST":
|
| 346 |
+
raise FileNotFoundError(e.message) from e
|
| 347 |
+
|
| 348 |
+
raise
|
| 349 |
+
|
| 350 |
+
def _add_data(self, handle, data):
|
| 351 |
+
"""
|
| 352 |
+
Upload data to an already opened file handle
|
| 353 |
+
(opened by :func:`_create_handle`).
|
| 354 |
+
The maximal allowed data size is 1MB after
|
| 355 |
+
conversion to base64.
|
| 356 |
+
Remember to close the handle when you are finished.
|
| 357 |
+
|
| 358 |
+
Parameters
|
| 359 |
+
----------
|
| 360 |
+
handle: str
|
| 361 |
+
Which handle to upload data to.
|
| 362 |
+
data: bytes
|
| 363 |
+
Block of data to add to the handle.
|
| 364 |
+
"""
|
| 365 |
+
data = base64.b64encode(data).decode()
|
| 366 |
+
try:
|
| 367 |
+
self._send_to_api(
|
| 368 |
+
method="post",
|
| 369 |
+
endpoint="add-block",
|
| 370 |
+
json={"handle": handle, "data": data},
|
| 371 |
+
)
|
| 372 |
+
except DatabricksException as e:
|
| 373 |
+
if e.error_code == "RESOURCE_DOES_NOT_EXIST":
|
| 374 |
+
raise FileNotFoundError(e.message) from e
|
| 375 |
+
elif e.error_code == "MAX_BLOCK_SIZE_EXCEEDED":
|
| 376 |
+
raise ValueError(e.message) from e
|
| 377 |
+
|
| 378 |
+
raise
|
| 379 |
+
|
| 380 |
+
def _get_data(self, path, start, end):
|
| 381 |
+
"""
|
| 382 |
+
Download data in bytes from a given absolute path in a block
|
| 383 |
+
from [start, start+length].
|
| 384 |
+
The maximum number of allowed bytes to read is 1MB.
|
| 385 |
+
|
| 386 |
+
Parameters
|
| 387 |
+
----------
|
| 388 |
+
path: str
|
| 389 |
+
Absolute path to download data from
|
| 390 |
+
start: int
|
| 391 |
+
Start position of the block
|
| 392 |
+
end: int
|
| 393 |
+
End position of the block
|
| 394 |
+
"""
|
| 395 |
+
try:
|
| 396 |
+
r = self._send_to_api(
|
| 397 |
+
method="get",
|
| 398 |
+
endpoint="read",
|
| 399 |
+
json={"path": path, "offset": start, "length": end - start},
|
| 400 |
+
)
|
| 401 |
+
return base64.b64decode(r["data"])
|
| 402 |
+
except DatabricksException as e:
|
| 403 |
+
if e.error_code == "RESOURCE_DOES_NOT_EXIST":
|
| 404 |
+
raise FileNotFoundError(e.message) from e
|
| 405 |
+
elif e.error_code in ["INVALID_PARAMETER_VALUE", "MAX_READ_SIZE_EXCEEDED"]:
|
| 406 |
+
raise ValueError(e.message) from e
|
| 407 |
+
|
| 408 |
+
raise
|
| 409 |
+
|
| 410 |
+
def invalidate_cache(self, path=None):
|
| 411 |
+
if path is None:
|
| 412 |
+
self.dircache.clear()
|
| 413 |
+
else:
|
| 414 |
+
self.dircache.pop(path, None)
|
| 415 |
+
super().invalidate_cache(path)
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
class DatabricksFile(AbstractBufferedFile):
|
| 419 |
+
"""
|
| 420 |
+
Helper class for files referenced in the DatabricksFileSystem.
|
| 421 |
+
"""
|
| 422 |
+
|
| 423 |
+
DEFAULT_BLOCK_SIZE = 1 * 2**20 # only allowed block size
|
| 424 |
+
|
| 425 |
+
def __init__(
|
| 426 |
+
self,
|
| 427 |
+
fs,
|
| 428 |
+
path,
|
| 429 |
+
mode="rb",
|
| 430 |
+
block_size="default",
|
| 431 |
+
autocommit=True,
|
| 432 |
+
cache_type="readahead",
|
| 433 |
+
cache_options=None,
|
| 434 |
+
**kwargs,
|
| 435 |
+
):
|
| 436 |
+
"""
|
| 437 |
+
Create a new instance of the DatabricksFile.
|
| 438 |
+
|
| 439 |
+
The blocksize needs to be the default one.
|
| 440 |
+
"""
|
| 441 |
+
if block_size is None or block_size == "default":
|
| 442 |
+
block_size = self.DEFAULT_BLOCK_SIZE
|
| 443 |
+
|
| 444 |
+
if block_size != self.DEFAULT_BLOCK_SIZE:
|
| 445 |
+
raise ValueError(
|
| 446 |
+
f"Only the default block size is allowed, not {block_size}"
|
| 447 |
+
)
|
| 448 |
+
|
| 449 |
+
super().__init__(
|
| 450 |
+
fs,
|
| 451 |
+
path,
|
| 452 |
+
mode=mode,
|
| 453 |
+
block_size=block_size,
|
| 454 |
+
autocommit=autocommit,
|
| 455 |
+
cache_type=cache_type,
|
| 456 |
+
cache_options=cache_options or {},
|
| 457 |
+
**kwargs,
|
| 458 |
+
)
|
| 459 |
+
|
| 460 |
+
def _initiate_upload(self):
|
| 461 |
+
"""Internal function to start a file upload"""
|
| 462 |
+
self.handle = self.fs._create_handle(self.path)
|
| 463 |
+
|
| 464 |
+
def _upload_chunk(self, final=False):
|
| 465 |
+
"""Internal function to add a chunk of data to a started upload"""
|
| 466 |
+
self.buffer.seek(0)
|
| 467 |
+
data = self.buffer.getvalue()
|
| 468 |
+
|
| 469 |
+
data_chunks = [
|
| 470 |
+
data[start:end] for start, end in self._to_sized_blocks(len(data))
|
| 471 |
+
]
|
| 472 |
+
|
| 473 |
+
for data_chunk in data_chunks:
|
| 474 |
+
self.fs._add_data(handle=self.handle, data=data_chunk)
|
| 475 |
+
|
| 476 |
+
if final:
|
| 477 |
+
self.fs._close_handle(handle=self.handle)
|
| 478 |
+
return True
|
| 479 |
+
|
| 480 |
+
def _fetch_range(self, start, end):
|
| 481 |
+
"""Internal function to download a block of data"""
|
| 482 |
+
return_buffer = b""
|
| 483 |
+
length = end - start
|
| 484 |
+
for chunk_start, chunk_end in self._to_sized_blocks(length, start):
|
| 485 |
+
return_buffer += self.fs._get_data(
|
| 486 |
+
path=self.path, start=chunk_start, end=chunk_end
|
| 487 |
+
)
|
| 488 |
+
|
| 489 |
+
return return_buffer
|
| 490 |
+
|
| 491 |
+
def _to_sized_blocks(self, length, start=0):
|
| 492 |
+
"""Helper function to split a range from 0 to total_length into blocksizes"""
|
| 493 |
+
end = start + length
|
| 494 |
+
for data_chunk in range(start, end, self.blocksize):
|
| 495 |
+
data_start = data_chunk
|
| 496 |
+
data_end = min(end, data_chunk + self.blocksize)
|
| 497 |
+
yield data_start, data_end
|
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/dirfs.py
ADDED
|
@@ -0,0 +1,426 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .. import filesystem
|
| 2 |
+
from ..asyn import AsyncFileSystem
|
| 3 |
+
from .chained import ChainedFileSystem
|
| 4 |
+
from .local import LocalFileSystem
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def _escapes_root(path):
|
| 8 |
+
"""Whether a relative path would resolve above its root via ".." segments."""
|
| 9 |
+
depth = 0
|
| 10 |
+
for part in path.split("/"):
|
| 11 |
+
if part == "..":
|
| 12 |
+
depth -= 1
|
| 13 |
+
if depth < 0:
|
| 14 |
+
return True
|
| 15 |
+
elif part and part != ".":
|
| 16 |
+
depth += 1
|
| 17 |
+
return False
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class DirFileSystem(AsyncFileSystem, ChainedFileSystem):
|
| 21 |
+
"""Directory prefix filesystem
|
| 22 |
+
|
| 23 |
+
The DirFileSystem is a filesystem-wrapper. It assumes every path it is dealing with
|
| 24 |
+
is relative to the `path`. After performing the necessary paths operation it
|
| 25 |
+
delegates everything to the wrapped filesystem.
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
protocol = "dir"
|
| 29 |
+
|
| 30 |
+
def __init__(
|
| 31 |
+
self,
|
| 32 |
+
path=None,
|
| 33 |
+
fs=None,
|
| 34 |
+
fo=None,
|
| 35 |
+
target_protocol=None,
|
| 36 |
+
target_options=None,
|
| 37 |
+
**storage_options,
|
| 38 |
+
):
|
| 39 |
+
"""
|
| 40 |
+
Parameters
|
| 41 |
+
----------
|
| 42 |
+
path: str
|
| 43 |
+
Path to the directory.
|
| 44 |
+
fs: AbstractFileSystem
|
| 45 |
+
An instantiated filesystem to wrap.
|
| 46 |
+
target_protocol, target_options:
|
| 47 |
+
if fs is none, construct it from these
|
| 48 |
+
fo: str
|
| 49 |
+
Alternate for path; do not provide both
|
| 50 |
+
"""
|
| 51 |
+
super().__init__(**storage_options)
|
| 52 |
+
if fs is None:
|
| 53 |
+
fs = filesystem(protocol=target_protocol, **(target_options or {}))
|
| 54 |
+
path = path or fo
|
| 55 |
+
|
| 56 |
+
if self.asynchronous and not fs.async_impl:
|
| 57 |
+
raise ValueError("can't use asynchronous with non-async fs")
|
| 58 |
+
|
| 59 |
+
if fs.async_impl and self.asynchronous != fs.asynchronous:
|
| 60 |
+
raise ValueError("both dirfs and fs should be in the same sync/async mode")
|
| 61 |
+
|
| 62 |
+
self.path = fs._strip_protocol(path)
|
| 63 |
+
self.fs = fs
|
| 64 |
+
|
| 65 |
+
def _join(self, path):
|
| 66 |
+
if isinstance(path, str):
|
| 67 |
+
if not self.path:
|
| 68 |
+
return path
|
| 69 |
+
if not path:
|
| 70 |
+
return self.path
|
| 71 |
+
path = self._strip_protocol(path)
|
| 72 |
+
# ".." only navigates above the root on filesystems that resolve it
|
| 73 |
+
# against a real directory tree; on object stores it is a literal
|
| 74 |
+
# path part, so only guard the local case here.
|
| 75 |
+
if isinstance(self.fs, LocalFileSystem) and _escapes_root(path):
|
| 76 |
+
raise ValueError(
|
| 77 |
+
f"path {path!r} escapes the {self.path!r} root of the filesystem"
|
| 78 |
+
)
|
| 79 |
+
return self.fs.sep.join((self.path, path))
|
| 80 |
+
if isinstance(path, dict):
|
| 81 |
+
return {self._join(_path): value for _path, value in path.items()}
|
| 82 |
+
return [self._join(_path) for _path in path]
|
| 83 |
+
|
| 84 |
+
def _relpath(self, path):
|
| 85 |
+
if isinstance(path, str):
|
| 86 |
+
if not self.path:
|
| 87 |
+
return path
|
| 88 |
+
# We need to account for S3FileSystem returning paths that do not
|
| 89 |
+
# start with a '/'
|
| 90 |
+
if path == self.path or (
|
| 91 |
+
self.path.startswith(self.fs.sep) and path == self.path[1:]
|
| 92 |
+
):
|
| 93 |
+
return ""
|
| 94 |
+
prefix = self.path + self.fs.sep
|
| 95 |
+
if self.path.startswith(self.fs.sep) and not path.startswith(self.fs.sep):
|
| 96 |
+
prefix = prefix[1:]
|
| 97 |
+
assert path.startswith(prefix)
|
| 98 |
+
return path[len(prefix) :]
|
| 99 |
+
return [self._relpath(_path) for _path in path]
|
| 100 |
+
|
| 101 |
+
# Wrappers below
|
| 102 |
+
|
| 103 |
+
@property
|
| 104 |
+
def sep(self):
|
| 105 |
+
return self.fs.sep
|
| 106 |
+
|
| 107 |
+
async def set_session(self, *args, **kwargs):
|
| 108 |
+
return await self.fs.set_session(*args, **kwargs)
|
| 109 |
+
|
| 110 |
+
async def _rm_file(self, path, **kwargs):
|
| 111 |
+
return await self.fs._rm_file(self._join(path), **kwargs)
|
| 112 |
+
|
| 113 |
+
def rm_file(self, path, **kwargs):
|
| 114 |
+
return self.fs.rm_file(self._join(path), **kwargs)
|
| 115 |
+
|
| 116 |
+
async def _rm(self, path, *args, **kwargs):
|
| 117 |
+
return await self.fs._rm(self._join(path), *args, **kwargs)
|
| 118 |
+
|
| 119 |
+
def rm(self, path, *args, **kwargs):
|
| 120 |
+
return self.fs.rm(self._join(path), *args, **kwargs)
|
| 121 |
+
|
| 122 |
+
def delete(self, path, recursive=False, maxdepth=None):
|
| 123 |
+
return self.fs.delete(self._join(path), recursive=recursive, maxdepth=maxdepth)
|
| 124 |
+
|
| 125 |
+
async def _cp_file(self, path1, path2, **kwargs):
|
| 126 |
+
return await self.fs._cp_file(self._join(path1), self._join(path2), **kwargs)
|
| 127 |
+
|
| 128 |
+
def cp_file(self, path1, path2, **kwargs):
|
| 129 |
+
return self.fs.cp_file(self._join(path1), self._join(path2), **kwargs)
|
| 130 |
+
|
| 131 |
+
async def _copy(
|
| 132 |
+
self,
|
| 133 |
+
path1,
|
| 134 |
+
path2,
|
| 135 |
+
*args,
|
| 136 |
+
**kwargs,
|
| 137 |
+
):
|
| 138 |
+
return await self.fs._copy(
|
| 139 |
+
self._join(path1),
|
| 140 |
+
self._join(path2),
|
| 141 |
+
*args,
|
| 142 |
+
**kwargs,
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
def copy(self, path1, path2, *args, **kwargs):
|
| 146 |
+
return self.fs.copy(
|
| 147 |
+
self._join(path1),
|
| 148 |
+
self._join(path2),
|
| 149 |
+
*args,
|
| 150 |
+
**kwargs,
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
async def _pipe(self, path, *args, **kwargs):
|
| 154 |
+
return await self.fs._pipe(self._join(path), *args, **kwargs)
|
| 155 |
+
|
| 156 |
+
def pipe(self, path, *args, **kwargs):
|
| 157 |
+
return self.fs.pipe(self._join(path), *args, **kwargs)
|
| 158 |
+
|
| 159 |
+
async def _pipe_file(self, path, *args, **kwargs):
|
| 160 |
+
return await self.fs._pipe_file(self._join(path), *args, **kwargs)
|
| 161 |
+
|
| 162 |
+
def pipe_file(self, path, *args, **kwargs):
|
| 163 |
+
return self.fs.pipe_file(self._join(path), *args, **kwargs)
|
| 164 |
+
|
| 165 |
+
def write_text(
|
| 166 |
+
self, path, value, encoding=None, errors=None, newline=None, **kwargs
|
| 167 |
+
):
|
| 168 |
+
return self.fs.write_text(
|
| 169 |
+
self._join(path),
|
| 170 |
+
value,
|
| 171 |
+
encoding=encoding,
|
| 172 |
+
errors=errors,
|
| 173 |
+
newline=newline,
|
| 174 |
+
**kwargs,
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
async def _cat_file(self, path, *args, **kwargs):
|
| 178 |
+
return await self.fs._cat_file(self._join(path), *args, **kwargs)
|
| 179 |
+
|
| 180 |
+
def cat_file(self, path, *args, **kwargs):
|
| 181 |
+
return self.fs.cat_file(self._join(path), *args, **kwargs)
|
| 182 |
+
|
| 183 |
+
async def _cat(self, path, *args, **kwargs):
|
| 184 |
+
ret = await self.fs._cat(
|
| 185 |
+
self._join(path),
|
| 186 |
+
*args,
|
| 187 |
+
**kwargs,
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
if isinstance(ret, dict):
|
| 191 |
+
return {self._relpath(key): value for key, value in ret.items()}
|
| 192 |
+
|
| 193 |
+
return ret
|
| 194 |
+
|
| 195 |
+
def cat(self, path, *args, **kwargs):
|
| 196 |
+
ret = self.fs.cat(
|
| 197 |
+
self._join(path),
|
| 198 |
+
*args,
|
| 199 |
+
**kwargs,
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
if isinstance(ret, dict):
|
| 203 |
+
return {self._relpath(key): value for key, value in ret.items()}
|
| 204 |
+
|
| 205 |
+
return ret
|
| 206 |
+
|
| 207 |
+
async def _put_file(self, lpath, rpath, **kwargs):
|
| 208 |
+
return await self.fs._put_file(lpath, self._join(rpath), **kwargs)
|
| 209 |
+
|
| 210 |
+
def put_file(self, lpath, rpath, **kwargs):
|
| 211 |
+
return self.fs.put_file(lpath, self._join(rpath), **kwargs)
|
| 212 |
+
|
| 213 |
+
async def _put(
|
| 214 |
+
self,
|
| 215 |
+
lpath,
|
| 216 |
+
rpath,
|
| 217 |
+
*args,
|
| 218 |
+
**kwargs,
|
| 219 |
+
):
|
| 220 |
+
return await self.fs._put(
|
| 221 |
+
lpath,
|
| 222 |
+
self._join(rpath),
|
| 223 |
+
*args,
|
| 224 |
+
**kwargs,
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
def put(self, lpath, rpath, *args, **kwargs):
|
| 228 |
+
return self.fs.put(
|
| 229 |
+
lpath,
|
| 230 |
+
self._join(rpath),
|
| 231 |
+
*args,
|
| 232 |
+
**kwargs,
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
async def _get_file(self, rpath, lpath, **kwargs):
|
| 236 |
+
return await self.fs._get_file(self._join(rpath), lpath, **kwargs)
|
| 237 |
+
|
| 238 |
+
def get_file(self, rpath, lpath, **kwargs):
|
| 239 |
+
return self.fs.get_file(self._join(rpath), lpath, **kwargs)
|
| 240 |
+
|
| 241 |
+
async def _get(self, rpath, *args, **kwargs):
|
| 242 |
+
return await self.fs._get(self._join(rpath), *args, **kwargs)
|
| 243 |
+
|
| 244 |
+
def get(self, rpath, *args, **kwargs):
|
| 245 |
+
return self.fs.get(self._join(rpath), *args, **kwargs)
|
| 246 |
+
|
| 247 |
+
async def _isfile(self, path):
|
| 248 |
+
return await self.fs._isfile(self._join(path))
|
| 249 |
+
|
| 250 |
+
def isfile(self, path):
|
| 251 |
+
return self.fs.isfile(self._join(path))
|
| 252 |
+
|
| 253 |
+
async def _isdir(self, path):
|
| 254 |
+
return await self.fs._isdir(self._join(path))
|
| 255 |
+
|
| 256 |
+
def isdir(self, path):
|
| 257 |
+
return self.fs.isdir(self._join(path))
|
| 258 |
+
|
| 259 |
+
async def _size(self, path):
|
| 260 |
+
return await self.fs._size(self._join(path))
|
| 261 |
+
|
| 262 |
+
def size(self, path):
|
| 263 |
+
return self.fs.size(self._join(path))
|
| 264 |
+
|
| 265 |
+
async def _exists(self, path):
|
| 266 |
+
return await self.fs._exists(self._join(path))
|
| 267 |
+
|
| 268 |
+
def exists(self, path):
|
| 269 |
+
return self.fs.exists(self._join(path))
|
| 270 |
+
|
| 271 |
+
async def _info(self, path, **kwargs):
|
| 272 |
+
info = await self.fs._info(self._join(path), **kwargs)
|
| 273 |
+
info = info.copy()
|
| 274 |
+
info["name"] = self._relpath(info["name"])
|
| 275 |
+
return info
|
| 276 |
+
|
| 277 |
+
def info(self, path, **kwargs):
|
| 278 |
+
info = self.fs.info(self._join(path), **kwargs)
|
| 279 |
+
info = info.copy()
|
| 280 |
+
info["name"] = self._relpath(info["name"])
|
| 281 |
+
return info
|
| 282 |
+
|
| 283 |
+
async def _ls(self, path, detail=True, **kwargs):
|
| 284 |
+
ret = (await self.fs._ls(self._join(path), detail=detail, **kwargs)).copy()
|
| 285 |
+
if detail:
|
| 286 |
+
out = []
|
| 287 |
+
for entry in ret:
|
| 288 |
+
entry = entry.copy()
|
| 289 |
+
entry["name"] = self._relpath(entry["name"])
|
| 290 |
+
out.append(entry)
|
| 291 |
+
return out
|
| 292 |
+
|
| 293 |
+
return self._relpath(ret)
|
| 294 |
+
|
| 295 |
+
def ls(self, path, detail=True, **kwargs):
|
| 296 |
+
ret = self.fs.ls(self._join(path), detail=detail, **kwargs).copy()
|
| 297 |
+
if detail:
|
| 298 |
+
out = []
|
| 299 |
+
for entry in ret:
|
| 300 |
+
entry = entry.copy()
|
| 301 |
+
entry["name"] = self._relpath(entry["name"])
|
| 302 |
+
out.append(entry)
|
| 303 |
+
return out
|
| 304 |
+
|
| 305 |
+
return self._relpath(ret)
|
| 306 |
+
|
| 307 |
+
async def _walk(self, path, *args, **kwargs):
|
| 308 |
+
async for root, dirs, files in self.fs._walk(self._join(path), *args, **kwargs):
|
| 309 |
+
yield self._relpath(root), dirs, files
|
| 310 |
+
|
| 311 |
+
def walk(self, path, *args, **kwargs):
|
| 312 |
+
for root, dirs, files in self.fs.walk(self._join(path), *args, **kwargs):
|
| 313 |
+
yield self._relpath(root), dirs, files
|
| 314 |
+
|
| 315 |
+
async def _glob(self, path, **kwargs):
|
| 316 |
+
detail = kwargs.get("detail", False)
|
| 317 |
+
ret = await self.fs._glob(self._join(path), **kwargs)
|
| 318 |
+
if detail:
|
| 319 |
+
return {self._relpath(path): info for path, info in ret.items()}
|
| 320 |
+
return self._relpath(ret)
|
| 321 |
+
|
| 322 |
+
def glob(self, path, **kwargs):
|
| 323 |
+
detail = kwargs.get("detail", False)
|
| 324 |
+
ret = self.fs.glob(self._join(path), **kwargs)
|
| 325 |
+
if detail:
|
| 326 |
+
return {self._relpath(path): info for path, info in ret.items()}
|
| 327 |
+
return self._relpath(ret)
|
| 328 |
+
|
| 329 |
+
async def _du(self, path, *args, **kwargs):
|
| 330 |
+
total = kwargs.get("total", True)
|
| 331 |
+
ret = await self.fs._du(self._join(path), *args, **kwargs)
|
| 332 |
+
if total:
|
| 333 |
+
return ret
|
| 334 |
+
|
| 335 |
+
return {self._relpath(path): size for path, size in ret.items()}
|
| 336 |
+
|
| 337 |
+
def du(self, path, *args, **kwargs):
|
| 338 |
+
total = kwargs.get("total", True)
|
| 339 |
+
ret = self.fs.du(self._join(path), *args, **kwargs)
|
| 340 |
+
if total:
|
| 341 |
+
return ret
|
| 342 |
+
|
| 343 |
+
return {self._relpath(path): size for path, size in ret.items()}
|
| 344 |
+
|
| 345 |
+
async def _find(self, path, *args, **kwargs):
|
| 346 |
+
detail = kwargs.get("detail", False)
|
| 347 |
+
ret = await self.fs._find(self._join(path), *args, **kwargs)
|
| 348 |
+
if detail:
|
| 349 |
+
return {self._relpath(path): info for path, info in ret.items()}
|
| 350 |
+
return self._relpath(ret)
|
| 351 |
+
|
| 352 |
+
def find(self, path, *args, **kwargs):
|
| 353 |
+
detail = kwargs.get("detail", False)
|
| 354 |
+
ret = self.fs.find(self._join(path), *args, **kwargs)
|
| 355 |
+
if detail:
|
| 356 |
+
return {self._relpath(path): info for path, info in ret.items()}
|
| 357 |
+
return self._relpath(ret)
|
| 358 |
+
|
| 359 |
+
async def _expand_path(self, path, *args, **kwargs):
|
| 360 |
+
return self._relpath(
|
| 361 |
+
await self.fs._expand_path(self._join(path), *args, **kwargs)
|
| 362 |
+
)
|
| 363 |
+
|
| 364 |
+
def expand_path(self, path, *args, **kwargs):
|
| 365 |
+
return self._relpath(self.fs.expand_path(self._join(path), *args, **kwargs))
|
| 366 |
+
|
| 367 |
+
async def _mkdir(self, path, *args, **kwargs):
|
| 368 |
+
return await self.fs._mkdir(self._join(path), *args, **kwargs)
|
| 369 |
+
|
| 370 |
+
def mkdir(self, path, *args, **kwargs):
|
| 371 |
+
return self.fs.mkdir(self._join(path), *args, **kwargs)
|
| 372 |
+
|
| 373 |
+
async def _makedirs(self, path, *args, **kwargs):
|
| 374 |
+
return await self.fs._makedirs(self._join(path), *args, **kwargs)
|
| 375 |
+
|
| 376 |
+
def makedirs(self, path, *args, **kwargs):
|
| 377 |
+
return self.fs.makedirs(self._join(path), *args, **kwargs)
|
| 378 |
+
|
| 379 |
+
def rmdir(self, path):
|
| 380 |
+
return self.fs.rmdir(self._join(path))
|
| 381 |
+
|
| 382 |
+
def mv(self, path1, path2, **kwargs):
|
| 383 |
+
return self.fs.mv(
|
| 384 |
+
self._join(path1),
|
| 385 |
+
self._join(path2),
|
| 386 |
+
**kwargs,
|
| 387 |
+
)
|
| 388 |
+
|
| 389 |
+
def touch(self, path, **kwargs):
|
| 390 |
+
return self.fs.touch(self._join(path), **kwargs)
|
| 391 |
+
|
| 392 |
+
def created(self, path):
|
| 393 |
+
return self.fs.created(self._join(path))
|
| 394 |
+
|
| 395 |
+
def modified(self, path):
|
| 396 |
+
return self.fs.modified(self._join(path))
|
| 397 |
+
|
| 398 |
+
def sign(self, path, *args, **kwargs):
|
| 399 |
+
return self.fs.sign(self._join(path), *args, **kwargs)
|
| 400 |
+
|
| 401 |
+
def __repr__(self):
|
| 402 |
+
return f"{self.__class__.__qualname__}(path='{self.path}', fs={self.fs})"
|
| 403 |
+
|
| 404 |
+
def open(
|
| 405 |
+
self,
|
| 406 |
+
path,
|
| 407 |
+
*args,
|
| 408 |
+
**kwargs,
|
| 409 |
+
):
|
| 410 |
+
return self.fs.open(
|
| 411 |
+
self._join(path),
|
| 412 |
+
*args,
|
| 413 |
+
**kwargs,
|
| 414 |
+
)
|
| 415 |
+
|
| 416 |
+
async def open_async(
|
| 417 |
+
self,
|
| 418 |
+
path,
|
| 419 |
+
*args,
|
| 420 |
+
**kwargs,
|
| 421 |
+
):
|
| 422 |
+
return await self.fs.open_async(
|
| 423 |
+
self._join(path),
|
| 424 |
+
*args,
|
| 425 |
+
**kwargs,
|
| 426 |
+
)
|
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/ftp.py
ADDED
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import ssl
|
| 3 |
+
import uuid
|
| 4 |
+
from ftplib import FTP, FTP_TLS, Error, error_perm
|
| 5 |
+
from typing import Any
|
| 6 |
+
|
| 7 |
+
from ..spec import AbstractBufferedFile, AbstractFileSystem
|
| 8 |
+
from ..utils import infer_storage_options, isfilelike
|
| 9 |
+
|
| 10 |
+
SECURITY_PROTOCOL_MAP = {
|
| 11 |
+
"tls": ssl.PROTOCOL_TLS,
|
| 12 |
+
"sslv23": ssl.PROTOCOL_SSLv23,
|
| 13 |
+
}
|
| 14 |
+
for protocol in ["TLSv1", "TLSv1_1", "TLSv1_2"]:
|
| 15 |
+
if hasattr(ssl, f"PROTOCOL_{protocol}"):
|
| 16 |
+
SECURITY_PROTOCOL_MAP[protocol.lower()] = getattr(ssl, f"PROTOCOL_{protocol}")
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class ImplicitFTPTLS(FTP_TLS):
|
| 20 |
+
"""
|
| 21 |
+
FTP_TLS subclass that automatically wraps sockets in SSL
|
| 22 |
+
to support implicit FTPS.
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
def __init__(self, *args, **kwargs):
|
| 26 |
+
super().__init__(*args, **kwargs)
|
| 27 |
+
self._sock = None
|
| 28 |
+
|
| 29 |
+
@property
|
| 30 |
+
def sock(self):
|
| 31 |
+
"""Return the socket."""
|
| 32 |
+
return self._sock
|
| 33 |
+
|
| 34 |
+
@sock.setter
|
| 35 |
+
def sock(self, value):
|
| 36 |
+
"""When modifying the socket, ensure that it is ssl wrapped."""
|
| 37 |
+
if value is not None and not isinstance(value, ssl.SSLSocket):
|
| 38 |
+
value = self.context.wrap_socket(value)
|
| 39 |
+
self._sock = value
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class FTPFileSystem(AbstractFileSystem):
|
| 43 |
+
"""A filesystem over classic FTP"""
|
| 44 |
+
|
| 45 |
+
root_marker = "/"
|
| 46 |
+
cachable = False
|
| 47 |
+
protocol = "ftp"
|
| 48 |
+
|
| 49 |
+
def __init__(
|
| 50 |
+
self,
|
| 51 |
+
host,
|
| 52 |
+
port=21,
|
| 53 |
+
username=None,
|
| 54 |
+
password=None,
|
| 55 |
+
acct=None,
|
| 56 |
+
block_size=None,
|
| 57 |
+
tempdir=None,
|
| 58 |
+
timeout=30,
|
| 59 |
+
encoding="utf-8",
|
| 60 |
+
tls=False,
|
| 61 |
+
**kwargs,
|
| 62 |
+
):
|
| 63 |
+
"""
|
| 64 |
+
You can use _get_kwargs_from_urls to get some kwargs from
|
| 65 |
+
a reasonable FTP url.
|
| 66 |
+
|
| 67 |
+
Authentication will be anonymous if username/password are not
|
| 68 |
+
given.
|
| 69 |
+
|
| 70 |
+
Parameters
|
| 71 |
+
----------
|
| 72 |
+
host: str
|
| 73 |
+
The remote server name/ip to connect to
|
| 74 |
+
port: int
|
| 75 |
+
Port to connect with
|
| 76 |
+
username: str or None
|
| 77 |
+
If authenticating, the user's identifier
|
| 78 |
+
password: str of None
|
| 79 |
+
User's password on the server, if using
|
| 80 |
+
acct: str or None
|
| 81 |
+
Some servers also need an "account" string for auth
|
| 82 |
+
block_size: int or None
|
| 83 |
+
If given, the read-ahead or write buffer size.
|
| 84 |
+
tempdir: str
|
| 85 |
+
Directory on remote to put temporary files when in a transaction
|
| 86 |
+
timeout: int
|
| 87 |
+
Timeout of the ftp connection in seconds
|
| 88 |
+
encoding: str
|
| 89 |
+
Encoding to use for directories and filenames in FTP connection
|
| 90 |
+
tls: bool or str
|
| 91 |
+
Enable FTP-TLS for secure connections:
|
| 92 |
+
- False: Plain FTP (default)
|
| 93 |
+
- True: Explicit TLS (FTPS with AUTH TLS command)
|
| 94 |
+
- "tls": Auto-negotiate highest protocol
|
| 95 |
+
- "tlsv1": TLS v1.0
|
| 96 |
+
- "tlsv1_1": TLS v1.1
|
| 97 |
+
- "tlsv1_2": TLS v1.2
|
| 98 |
+
"""
|
| 99 |
+
super().__init__(**kwargs)
|
| 100 |
+
self.host = host
|
| 101 |
+
self.port = port
|
| 102 |
+
self.tempdir = tempdir or "/tmp"
|
| 103 |
+
self.cred = username or "", password or "", acct or ""
|
| 104 |
+
self.timeout = timeout
|
| 105 |
+
self.encoding = encoding
|
| 106 |
+
if block_size is not None:
|
| 107 |
+
self.blocksize = block_size
|
| 108 |
+
else:
|
| 109 |
+
self.blocksize = 2**16
|
| 110 |
+
self.tls = tls
|
| 111 |
+
self._connect()
|
| 112 |
+
if isinstance(self.tls, bool) and self.tls:
|
| 113 |
+
self.ftp.prot_p()
|
| 114 |
+
|
| 115 |
+
def _connect(self):
|
| 116 |
+
security = None
|
| 117 |
+
if self.tls:
|
| 118 |
+
if isinstance(self.tls, str):
|
| 119 |
+
ftp_cls = ImplicitFTPTLS
|
| 120 |
+
security = SECURITY_PROTOCOL_MAP.get(
|
| 121 |
+
self.tls,
|
| 122 |
+
f"Not supported {self.tls} protocol",
|
| 123 |
+
)
|
| 124 |
+
if isinstance(security, str):
|
| 125 |
+
raise ValueError(security)
|
| 126 |
+
else:
|
| 127 |
+
ftp_cls = FTP_TLS
|
| 128 |
+
else:
|
| 129 |
+
ftp_cls = FTP
|
| 130 |
+
self.ftp = ftp_cls(timeout=self.timeout, encoding=self.encoding)
|
| 131 |
+
if security:
|
| 132 |
+
self.ftp.ssl_version = security
|
| 133 |
+
self.ftp.connect(self.host, self.port)
|
| 134 |
+
self.ftp.login(*self.cred)
|
| 135 |
+
|
| 136 |
+
@classmethod
|
| 137 |
+
def _strip_protocol(cls, path):
|
| 138 |
+
return "/" + infer_storage_options(path)["path"].lstrip("/").rstrip("/")
|
| 139 |
+
|
| 140 |
+
@staticmethod
|
| 141 |
+
def _get_kwargs_from_urls(urlpath):
|
| 142 |
+
out = infer_storage_options(urlpath)
|
| 143 |
+
out.pop("path", None)
|
| 144 |
+
out.pop("protocol", None)
|
| 145 |
+
return out
|
| 146 |
+
|
| 147 |
+
def ls(self, path, detail=True, **kwargs):
|
| 148 |
+
path = self._strip_protocol(path)
|
| 149 |
+
out = []
|
| 150 |
+
if path not in self.dircache:
|
| 151 |
+
try:
|
| 152 |
+
try:
|
| 153 |
+
out = [
|
| 154 |
+
(fn, details)
|
| 155 |
+
for (fn, details) in self.ftp.mlsd(path)
|
| 156 |
+
if fn not in [".", ".."]
|
| 157 |
+
and details["type"] not in ["pdir", "cdir"]
|
| 158 |
+
]
|
| 159 |
+
except error_perm:
|
| 160 |
+
out = _mlsd2(self.ftp, path) # Not platform independent
|
| 161 |
+
for fn, details in out:
|
| 162 |
+
details["name"] = "/".join(
|
| 163 |
+
["" if path == "/" else path, fn.lstrip("/")]
|
| 164 |
+
)
|
| 165 |
+
if details["type"] == "file":
|
| 166 |
+
details["size"] = int(details["size"])
|
| 167 |
+
else:
|
| 168 |
+
details["size"] = 0
|
| 169 |
+
if details["type"] == "dir":
|
| 170 |
+
details["type"] = "directory"
|
| 171 |
+
self.dircache[path] = out
|
| 172 |
+
except Error:
|
| 173 |
+
try:
|
| 174 |
+
info = self.info(path)
|
| 175 |
+
if info["type"] == "file":
|
| 176 |
+
out = [(path, info)]
|
| 177 |
+
except (Error, IndexError) as exc:
|
| 178 |
+
raise FileNotFoundError(path) from exc
|
| 179 |
+
files = self.dircache.get(path, out)
|
| 180 |
+
if not detail:
|
| 181 |
+
return sorted([fn for fn, details in files])
|
| 182 |
+
return [details for fn, details in files]
|
| 183 |
+
|
| 184 |
+
def info(self, path, **kwargs):
|
| 185 |
+
# implement with direct method
|
| 186 |
+
path = self._strip_protocol(path)
|
| 187 |
+
if path == "/":
|
| 188 |
+
# special case, since this dir has no real entry
|
| 189 |
+
return {"name": "/", "size": 0, "type": "directory"}
|
| 190 |
+
files = self.ls(self._parent(path).lstrip("/"), True)
|
| 191 |
+
try:
|
| 192 |
+
out = next(f for f in files if f["name"] == path)
|
| 193 |
+
except StopIteration as exc:
|
| 194 |
+
raise FileNotFoundError(path) from exc
|
| 195 |
+
return out
|
| 196 |
+
|
| 197 |
+
def get_file(self, rpath, lpath, **kwargs):
|
| 198 |
+
if self.isdir(rpath):
|
| 199 |
+
if not os.path.exists(lpath):
|
| 200 |
+
os.mkdir(lpath)
|
| 201 |
+
return
|
| 202 |
+
if isfilelike(lpath):
|
| 203 |
+
outfile = lpath
|
| 204 |
+
else:
|
| 205 |
+
outfile = open(lpath, "wb")
|
| 206 |
+
|
| 207 |
+
def cb(x):
|
| 208 |
+
outfile.write(x)
|
| 209 |
+
|
| 210 |
+
self.ftp.retrbinary(
|
| 211 |
+
f"RETR {rpath}",
|
| 212 |
+
blocksize=self.blocksize,
|
| 213 |
+
callback=cb,
|
| 214 |
+
)
|
| 215 |
+
if not isfilelike(lpath):
|
| 216 |
+
outfile.close()
|
| 217 |
+
|
| 218 |
+
def cat_file(self, path, start=None, end=None, **kwargs):
|
| 219 |
+
if end is not None:
|
| 220 |
+
return super().cat_file(path, start, end, **kwargs)
|
| 221 |
+
out = []
|
| 222 |
+
|
| 223 |
+
def cb(x):
|
| 224 |
+
out.append(x)
|
| 225 |
+
|
| 226 |
+
try:
|
| 227 |
+
self.ftp.retrbinary(
|
| 228 |
+
f"RETR {path}",
|
| 229 |
+
blocksize=self.blocksize,
|
| 230 |
+
rest=start,
|
| 231 |
+
callback=cb,
|
| 232 |
+
)
|
| 233 |
+
except (Error, error_perm) as orig_exc:
|
| 234 |
+
raise FileNotFoundError(path) from orig_exc
|
| 235 |
+
return b"".join(out)
|
| 236 |
+
|
| 237 |
+
def _open(
|
| 238 |
+
self,
|
| 239 |
+
path,
|
| 240 |
+
mode="rb",
|
| 241 |
+
block_size=None,
|
| 242 |
+
cache_options=None,
|
| 243 |
+
autocommit=True,
|
| 244 |
+
**kwargs,
|
| 245 |
+
):
|
| 246 |
+
path = self._strip_protocol(path)
|
| 247 |
+
block_size = block_size or self.blocksize
|
| 248 |
+
return FTPFile(
|
| 249 |
+
self,
|
| 250 |
+
path,
|
| 251 |
+
mode=mode,
|
| 252 |
+
block_size=block_size,
|
| 253 |
+
tempdir=self.tempdir,
|
| 254 |
+
autocommit=autocommit,
|
| 255 |
+
cache_options=cache_options,
|
| 256 |
+
)
|
| 257 |
+
|
| 258 |
+
def _rm(self, path):
|
| 259 |
+
path = self._strip_protocol(path)
|
| 260 |
+
self.ftp.delete(path)
|
| 261 |
+
self.invalidate_cache(self._parent(path))
|
| 262 |
+
|
| 263 |
+
def rm(self, path, recursive=False, maxdepth=None):
|
| 264 |
+
paths = self.expand_path(path, recursive=recursive, maxdepth=maxdepth)
|
| 265 |
+
for p in reversed(paths):
|
| 266 |
+
if self.isfile(p):
|
| 267 |
+
self.rm_file(p)
|
| 268 |
+
else:
|
| 269 |
+
self.rmdir(p)
|
| 270 |
+
|
| 271 |
+
def mkdir(self, path: str, create_parents: bool = True, **kwargs: Any) -> None:
|
| 272 |
+
path = self._strip_protocol(path)
|
| 273 |
+
parent = self._parent(path)
|
| 274 |
+
if parent != self.root_marker and not self.exists(parent) and create_parents:
|
| 275 |
+
self.mkdir(parent, create_parents=create_parents)
|
| 276 |
+
|
| 277 |
+
self.ftp.mkd(path)
|
| 278 |
+
self.invalidate_cache(self._parent(path))
|
| 279 |
+
|
| 280 |
+
def makedirs(self, path: str, exist_ok: bool = False) -> None:
|
| 281 |
+
path = self._strip_protocol(path)
|
| 282 |
+
if self.exists(path):
|
| 283 |
+
# NB: "/" does not "exist" as it has no directory entry
|
| 284 |
+
if not exist_ok:
|
| 285 |
+
raise FileExistsError(f"{path} exists without `exist_ok`")
|
| 286 |
+
# exists_ok=True -> no-op
|
| 287 |
+
else:
|
| 288 |
+
self.mkdir(path, create_parents=True)
|
| 289 |
+
|
| 290 |
+
def rmdir(self, path):
|
| 291 |
+
path = self._strip_protocol(path)
|
| 292 |
+
self.ftp.rmd(path)
|
| 293 |
+
self.invalidate_cache(self._parent(path))
|
| 294 |
+
|
| 295 |
+
def mv(self, path1, path2, **kwargs):
|
| 296 |
+
path1 = self._strip_protocol(path1)
|
| 297 |
+
path2 = self._strip_protocol(path2)
|
| 298 |
+
self.ftp.rename(path1, path2)
|
| 299 |
+
self.invalidate_cache(self._parent(path1))
|
| 300 |
+
self.invalidate_cache(self._parent(path2))
|
| 301 |
+
|
| 302 |
+
def __del__(self):
|
| 303 |
+
self.ftp.close()
|
| 304 |
+
|
| 305 |
+
def invalidate_cache(self, path=None):
|
| 306 |
+
if path is None:
|
| 307 |
+
self.dircache.clear()
|
| 308 |
+
else:
|
| 309 |
+
self.dircache.pop(path, None)
|
| 310 |
+
super().invalidate_cache(path)
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
class TransferDone(Exception):
|
| 314 |
+
"""Internal exception to break out of transfer"""
|
| 315 |
+
|
| 316 |
+
pass
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
class FTPFile(AbstractBufferedFile):
|
| 320 |
+
"""Interact with a remote FTP file with read/write buffering"""
|
| 321 |
+
|
| 322 |
+
def __init__(
|
| 323 |
+
self,
|
| 324 |
+
fs,
|
| 325 |
+
path,
|
| 326 |
+
mode="rb",
|
| 327 |
+
block_size="default",
|
| 328 |
+
autocommit=True,
|
| 329 |
+
cache_type="readahead",
|
| 330 |
+
cache_options=None,
|
| 331 |
+
**kwargs,
|
| 332 |
+
):
|
| 333 |
+
super().__init__(
|
| 334 |
+
fs,
|
| 335 |
+
path,
|
| 336 |
+
mode=mode,
|
| 337 |
+
block_size=block_size,
|
| 338 |
+
autocommit=autocommit,
|
| 339 |
+
cache_type=cache_type,
|
| 340 |
+
cache_options=cache_options,
|
| 341 |
+
**kwargs,
|
| 342 |
+
)
|
| 343 |
+
if not autocommit:
|
| 344 |
+
self.target = self.path
|
| 345 |
+
self.path = "/".join([kwargs["tempdir"], str(uuid.uuid4())])
|
| 346 |
+
|
| 347 |
+
def commit(self):
|
| 348 |
+
self.fs.mv(self.path, self.target)
|
| 349 |
+
|
| 350 |
+
def discard(self):
|
| 351 |
+
self.fs.rm(self.path)
|
| 352 |
+
|
| 353 |
+
def _fetch_range(self, start, end):
|
| 354 |
+
"""Get bytes between given byte limits
|
| 355 |
+
|
| 356 |
+
Implemented by raising an exception in the fetch callback when the
|
| 357 |
+
number of bytes received reaches the requested amount.
|
| 358 |
+
|
| 359 |
+
Will fail if the server does not respect the REST command on
|
| 360 |
+
retrieve requests.
|
| 361 |
+
"""
|
| 362 |
+
out = []
|
| 363 |
+
total = [0]
|
| 364 |
+
|
| 365 |
+
def callback(x):
|
| 366 |
+
total[0] += len(x)
|
| 367 |
+
if total[0] > end - start:
|
| 368 |
+
out.append(x[: (end - start) - total[0]])
|
| 369 |
+
if end < self.size:
|
| 370 |
+
raise TransferDone
|
| 371 |
+
else:
|
| 372 |
+
out.append(x)
|
| 373 |
+
|
| 374 |
+
if total[0] == end - start and end < self.size:
|
| 375 |
+
raise TransferDone
|
| 376 |
+
|
| 377 |
+
try:
|
| 378 |
+
self.fs.ftp.retrbinary(
|
| 379 |
+
f"RETR {self.path}",
|
| 380 |
+
blocksize=self.blocksize,
|
| 381 |
+
rest=start,
|
| 382 |
+
callback=callback,
|
| 383 |
+
)
|
| 384 |
+
except TransferDone:
|
| 385 |
+
try:
|
| 386 |
+
# stop transfer, we got enough bytes for this block
|
| 387 |
+
self.fs.ftp.abort()
|
| 388 |
+
self.fs.ftp.getmultiline()
|
| 389 |
+
except Error:
|
| 390 |
+
self.fs._connect()
|
| 391 |
+
|
| 392 |
+
return b"".join(out)
|
| 393 |
+
|
| 394 |
+
def _upload_chunk(self, final=False):
|
| 395 |
+
self.buffer.seek(0)
|
| 396 |
+
self.fs.ftp.storbinary(
|
| 397 |
+
f"STOR {self.path}", self.buffer, blocksize=self.blocksize, rest=self.offset
|
| 398 |
+
)
|
| 399 |
+
return True
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
def _mlsd2(ftp, path="."):
|
| 403 |
+
"""
|
| 404 |
+
Fall back to using `dir` instead of `mlsd` if not supported.
|
| 405 |
+
|
| 406 |
+
This parses a Linux style `ls -l` response to `dir`, but the response may
|
| 407 |
+
be platform dependent.
|
| 408 |
+
|
| 409 |
+
Parameters
|
| 410 |
+
----------
|
| 411 |
+
ftp: ftplib.FTP
|
| 412 |
+
path: str
|
| 413 |
+
Expects to be given path, but defaults to ".".
|
| 414 |
+
"""
|
| 415 |
+
lines = []
|
| 416 |
+
minfo = []
|
| 417 |
+
ftp.dir(path, lines.append)
|
| 418 |
+
for line in lines:
|
| 419 |
+
split_line = line.split(maxsplit=8)
|
| 420 |
+
if len(split_line) < 9:
|
| 421 |
+
continue
|
| 422 |
+
name = split_line[8]
|
| 423 |
+
unix_mode = split_line[0]
|
| 424 |
+
if unix_mode[0] == "l" and " -> " in name:
|
| 425 |
+
# Symbolic link: "<name> -> <target>"; keep only the link name.
|
| 426 |
+
name = name.split(" -> ", 1)[0]
|
| 427 |
+
this = (
|
| 428 |
+
name,
|
| 429 |
+
{
|
| 430 |
+
"modify": " ".join(split_line[5:8]),
|
| 431 |
+
"unix.owner": split_line[2],
|
| 432 |
+
"unix.group": split_line[3],
|
| 433 |
+
"unix.mode": unix_mode,
|
| 434 |
+
"size": split_line[4],
|
| 435 |
+
},
|
| 436 |
+
)
|
| 437 |
+
if this[1]["unix.mode"][0] == "d":
|
| 438 |
+
this[1]["type"] = "dir"
|
| 439 |
+
else:
|
| 440 |
+
this[1]["type"] = "file"
|
| 441 |
+
minfo.append(this)
|
| 442 |
+
return minfo
|
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/gist.py
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import requests
|
| 2 |
+
|
| 3 |
+
from ..spec import AbstractFileSystem
|
| 4 |
+
from ..utils import infer_storage_options
|
| 5 |
+
from .memory import MemoryFile
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class GistFileSystem(AbstractFileSystem):
|
| 9 |
+
"""
|
| 10 |
+
Interface to files in a single GitHub Gist.
|
| 11 |
+
|
| 12 |
+
Provides read-only access to a gist's files. Gists do not contain
|
| 13 |
+
subdirectories, so file listing is straightforward.
|
| 14 |
+
|
| 15 |
+
Parameters
|
| 16 |
+
----------
|
| 17 |
+
gist_id: str
|
| 18 |
+
The ID of the gist you want to access (the long hex value from the URL).
|
| 19 |
+
filenames: list[str] (optional)
|
| 20 |
+
If provided, only make a file system representing these files, and do not fetch
|
| 21 |
+
the list of all files for this gist.
|
| 22 |
+
sha: str (optional)
|
| 23 |
+
If provided, fetch a particular revision of the gist. If omitted,
|
| 24 |
+
the latest revision is used.
|
| 25 |
+
username: str (optional)
|
| 26 |
+
GitHub username for authentication.
|
| 27 |
+
token: str (optional)
|
| 28 |
+
GitHub personal access token (required if username is given), or.
|
| 29 |
+
timeout: (float, float) or float, optional
|
| 30 |
+
Connect and read timeouts for requests (default 60s each).
|
| 31 |
+
kwargs: dict
|
| 32 |
+
Stored on `self.request_kw` and passed to `requests.get` when fetching Gist
|
| 33 |
+
metadata or reading ("opening") a file.
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
protocol = "gist"
|
| 37 |
+
gist_url = "https://api.github.com/gists/{gist_id}"
|
| 38 |
+
gist_rev_url = "https://api.github.com/gists/{gist_id}/{sha}"
|
| 39 |
+
|
| 40 |
+
def __init__(
|
| 41 |
+
self,
|
| 42 |
+
gist_id,
|
| 43 |
+
filenames=None,
|
| 44 |
+
sha=None,
|
| 45 |
+
username=None,
|
| 46 |
+
token=None,
|
| 47 |
+
timeout=None,
|
| 48 |
+
**kwargs,
|
| 49 |
+
):
|
| 50 |
+
super().__init__()
|
| 51 |
+
self.gist_id = gist_id
|
| 52 |
+
self.filenames = filenames
|
| 53 |
+
self.sha = sha # revision of the gist (optional)
|
| 54 |
+
if username is not None and token is None:
|
| 55 |
+
raise ValueError("User auth requires a token")
|
| 56 |
+
self.username = username
|
| 57 |
+
self.token = token
|
| 58 |
+
self.request_kw = kwargs
|
| 59 |
+
# Default timeouts to 60s connect/read if none provided
|
| 60 |
+
self.timeout = timeout if timeout is not None else (60, 60)
|
| 61 |
+
|
| 62 |
+
# We use a single-level "directory" cache, because a gist is essentially flat
|
| 63 |
+
self.dircache[""] = self._fetch_file_list()
|
| 64 |
+
|
| 65 |
+
@property
|
| 66 |
+
def kw(self):
|
| 67 |
+
"""Auth parameters passed to 'requests' if we have username/token."""
|
| 68 |
+
kw = {
|
| 69 |
+
"headers": {
|
| 70 |
+
"Accept": "application/vnd.github+json",
|
| 71 |
+
"X-GitHub-Api-Version": "2022-11-28",
|
| 72 |
+
}
|
| 73 |
+
}
|
| 74 |
+
kw.update(self.request_kw)
|
| 75 |
+
if self.username and self.token:
|
| 76 |
+
kw["auth"] = (self.username, self.token)
|
| 77 |
+
elif self.token:
|
| 78 |
+
kw["headers"]["Authorization"] = f"Bearer {self.token}"
|
| 79 |
+
return kw
|
| 80 |
+
|
| 81 |
+
def _fetch_gist_metadata(self):
|
| 82 |
+
"""
|
| 83 |
+
Fetch the JSON metadata for this gist (possibly for a specific revision).
|
| 84 |
+
"""
|
| 85 |
+
if self.sha:
|
| 86 |
+
url = self.gist_rev_url.format(gist_id=self.gist_id, sha=self.sha)
|
| 87 |
+
else:
|
| 88 |
+
url = self.gist_url.format(gist_id=self.gist_id)
|
| 89 |
+
|
| 90 |
+
r = requests.get(url, timeout=self.timeout, **self.kw)
|
| 91 |
+
if r.status_code == 404:
|
| 92 |
+
raise FileNotFoundError(
|
| 93 |
+
f"Gist not found: {self.gist_id}@{self.sha or 'latest'}"
|
| 94 |
+
)
|
| 95 |
+
r.raise_for_status()
|
| 96 |
+
return r.json()
|
| 97 |
+
|
| 98 |
+
def _fetch_file_list(self):
|
| 99 |
+
"""
|
| 100 |
+
Returns a list of dicts describing each file in the gist. These get stored
|
| 101 |
+
in self.dircache[""].
|
| 102 |
+
"""
|
| 103 |
+
meta = self._fetch_gist_metadata()
|
| 104 |
+
if self.filenames:
|
| 105 |
+
available_files = meta.get("files", {})
|
| 106 |
+
files = {}
|
| 107 |
+
for fn in self.filenames:
|
| 108 |
+
if fn not in available_files:
|
| 109 |
+
raise FileNotFoundError(fn)
|
| 110 |
+
files[fn] = available_files[fn]
|
| 111 |
+
else:
|
| 112 |
+
files = meta.get("files", {})
|
| 113 |
+
|
| 114 |
+
out = []
|
| 115 |
+
for fname, finfo in files.items():
|
| 116 |
+
if finfo is None:
|
| 117 |
+
# Occasionally GitHub returns a file entry with null if it was deleted
|
| 118 |
+
continue
|
| 119 |
+
# Build a directory entry
|
| 120 |
+
out.append(
|
| 121 |
+
{
|
| 122 |
+
"name": fname, # file's name
|
| 123 |
+
"type": "file", # gists have no subdirectories
|
| 124 |
+
"size": finfo.get("size", 0), # file size in bytes
|
| 125 |
+
"raw_url": finfo.get("raw_url"),
|
| 126 |
+
}
|
| 127 |
+
)
|
| 128 |
+
return out
|
| 129 |
+
|
| 130 |
+
@classmethod
|
| 131 |
+
def _strip_protocol(cls, path):
|
| 132 |
+
"""
|
| 133 |
+
Remove 'gist://' from the path, if present.
|
| 134 |
+
"""
|
| 135 |
+
# The default infer_storage_options can handle gist://username:token@id/file
|
| 136 |
+
# or gist://id/file, but let's ensure we handle a normal usage too.
|
| 137 |
+
# We'll just strip the protocol prefix if it exists.
|
| 138 |
+
path = infer_storage_options(path).get("path", path)
|
| 139 |
+
return path.lstrip("/")
|
| 140 |
+
|
| 141 |
+
@staticmethod
|
| 142 |
+
def _get_kwargs_from_urls(path):
|
| 143 |
+
"""
|
| 144 |
+
Parse 'gist://' style URLs into GistFileSystem constructor kwargs.
|
| 145 |
+
For example:
|
| 146 |
+
gist://:TOKEN@<gist_id>/file.txt
|
| 147 |
+
gist://username:TOKEN@<gist_id>/file.txt
|
| 148 |
+
"""
|
| 149 |
+
so = infer_storage_options(path)
|
| 150 |
+
out = {}
|
| 151 |
+
if "username" in so and so["username"]:
|
| 152 |
+
out["username"] = so["username"]
|
| 153 |
+
if "password" in so and so["password"]:
|
| 154 |
+
out["token"] = so["password"]
|
| 155 |
+
if "host" in so and so["host"]:
|
| 156 |
+
# We interpret 'host' as the gist ID
|
| 157 |
+
out["gist_id"] = so["host"]
|
| 158 |
+
|
| 159 |
+
# Extract SHA and filename from path
|
| 160 |
+
if "path" in so and so["path"]:
|
| 161 |
+
path_parts = so["path"].rsplit("/", 2)[-2:]
|
| 162 |
+
if len(path_parts) == 2:
|
| 163 |
+
if path_parts[0]: # SHA present
|
| 164 |
+
out["sha"] = path_parts[0]
|
| 165 |
+
if path_parts[1]: # filename also present
|
| 166 |
+
out["filenames"] = [path_parts[1]]
|
| 167 |
+
|
| 168 |
+
return out
|
| 169 |
+
|
| 170 |
+
def ls(self, path="", detail=False, **kwargs):
|
| 171 |
+
"""
|
| 172 |
+
List files in the gist. Gists are single-level, so any 'path' is basically
|
| 173 |
+
the filename, or empty for all files.
|
| 174 |
+
|
| 175 |
+
Parameters
|
| 176 |
+
----------
|
| 177 |
+
path : str, optional
|
| 178 |
+
The filename to list. If empty, returns all files in the gist.
|
| 179 |
+
detail : bool, default False
|
| 180 |
+
If True, return a list of dicts; if False, return a list of filenames.
|
| 181 |
+
"""
|
| 182 |
+
path = self._strip_protocol(path or "")
|
| 183 |
+
# If path is empty, return all
|
| 184 |
+
if path == "":
|
| 185 |
+
results = self.dircache[""]
|
| 186 |
+
else:
|
| 187 |
+
# We want just the single file with this name
|
| 188 |
+
all_files = self.dircache[""]
|
| 189 |
+
results = [f for f in all_files if f["name"] == path]
|
| 190 |
+
if not results:
|
| 191 |
+
raise FileNotFoundError(path)
|
| 192 |
+
if detail:
|
| 193 |
+
return results
|
| 194 |
+
else:
|
| 195 |
+
return sorted(f["name"] for f in results)
|
| 196 |
+
|
| 197 |
+
def _open(self, path, mode="rb", block_size=None, **kwargs):
|
| 198 |
+
"""
|
| 199 |
+
Read a single file from the gist.
|
| 200 |
+
"""
|
| 201 |
+
if mode != "rb":
|
| 202 |
+
raise NotImplementedError("GitHub Gist FS is read-only (no write).")
|
| 203 |
+
|
| 204 |
+
path = self._strip_protocol(path)
|
| 205 |
+
# Find the file entry in our dircache
|
| 206 |
+
matches = [f for f in self.dircache[""] if f["name"] == path]
|
| 207 |
+
if not matches:
|
| 208 |
+
raise FileNotFoundError(path)
|
| 209 |
+
finfo = matches[0]
|
| 210 |
+
|
| 211 |
+
raw_url = finfo.get("raw_url")
|
| 212 |
+
if not raw_url:
|
| 213 |
+
raise FileNotFoundError(f"No raw_url for file: {path}")
|
| 214 |
+
|
| 215 |
+
r = requests.get(raw_url, timeout=self.timeout, **self.kw)
|
| 216 |
+
if r.status_code == 404:
|
| 217 |
+
raise FileNotFoundError(path)
|
| 218 |
+
r.raise_for_status()
|
| 219 |
+
return MemoryFile(path, None, r.content)
|
| 220 |
+
|
| 221 |
+
def cat(self, path, recursive=False, on_error="raise", **kwargs):
|
| 222 |
+
"""
|
| 223 |
+
Return {path: contents} for the given file or files. If 'recursive' is True,
|
| 224 |
+
and path is empty, returns all files in the gist.
|
| 225 |
+
"""
|
| 226 |
+
paths = self.expand_path(path, recursive=recursive)
|
| 227 |
+
out = {}
|
| 228 |
+
for p in paths:
|
| 229 |
+
try:
|
| 230 |
+
with self.open(p, "rb") as f:
|
| 231 |
+
out[p] = f.read()
|
| 232 |
+
except FileNotFoundError as e:
|
| 233 |
+
if on_error == "raise":
|
| 234 |
+
raise e
|
| 235 |
+
elif on_error == "omit":
|
| 236 |
+
pass # skip
|
| 237 |
+
else:
|
| 238 |
+
out[p] = e
|
| 239 |
+
if len(paths) == 1 and paths[0] == path:
|
| 240 |
+
return out[path]
|
| 241 |
+
return out
|
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/git.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
import pygit2
|
| 4 |
+
|
| 5 |
+
from fsspec.spec import AbstractFileSystem
|
| 6 |
+
|
| 7 |
+
from .memory import MemoryFile
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class GitFileSystem(AbstractFileSystem):
|
| 11 |
+
"""Browse the files of a local git repo at any hash/tag/branch
|
| 12 |
+
|
| 13 |
+
(experimental backend)
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
root_marker = ""
|
| 17 |
+
cachable = True
|
| 18 |
+
|
| 19 |
+
def __init__(self, path=None, fo=None, ref=None, **kwargs):
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
Parameters
|
| 23 |
+
----------
|
| 24 |
+
path: str (optional)
|
| 25 |
+
Local location of the repo (uses current directory if not given).
|
| 26 |
+
May be deprecated in favour of ``fo``. When used with a higher
|
| 27 |
+
level function such as fsspec.open(), may be of the form
|
| 28 |
+
"git://[path-to-repo[:]][ref@]path/to/file" (but the actual
|
| 29 |
+
file path should not contain "@" or ":").
|
| 30 |
+
fo: str (optional)
|
| 31 |
+
Same as ``path``, but passed as part of a chained URL. This one
|
| 32 |
+
takes precedence if both are given.
|
| 33 |
+
ref: str (optional)
|
| 34 |
+
Reference to work with, could be a hash, tag or branch name. Defaults
|
| 35 |
+
to current working tree. Note that ``ls`` and ``open`` also take hash,
|
| 36 |
+
so this becomes the default for those operations
|
| 37 |
+
kwargs
|
| 38 |
+
"""
|
| 39 |
+
super().__init__(**kwargs)
|
| 40 |
+
self.repo = pygit2.Repository(fo or path or os.getcwd())
|
| 41 |
+
self.ref = ref or "master"
|
| 42 |
+
|
| 43 |
+
@classmethod
|
| 44 |
+
def _strip_protocol(cls, path):
|
| 45 |
+
path = super()._strip_protocol(path).lstrip("/")
|
| 46 |
+
if ":" in path:
|
| 47 |
+
path = path.split(":", 1)[1]
|
| 48 |
+
if "@" in path:
|
| 49 |
+
path = path.split("@", 1)[1]
|
| 50 |
+
return path.lstrip("/")
|
| 51 |
+
|
| 52 |
+
def _path_to_object(self, path, ref):
|
| 53 |
+
comm, ref = self.repo.resolve_refish(ref or self.ref)
|
| 54 |
+
parts = path.split("/")
|
| 55 |
+
tree = comm.tree
|
| 56 |
+
for part in parts:
|
| 57 |
+
if part and isinstance(tree, pygit2.Tree):
|
| 58 |
+
if part not in tree:
|
| 59 |
+
raise FileNotFoundError(path)
|
| 60 |
+
tree = tree[part]
|
| 61 |
+
return tree
|
| 62 |
+
|
| 63 |
+
@staticmethod
|
| 64 |
+
def _get_kwargs_from_urls(path):
|
| 65 |
+
path = path.removeprefix("git://")
|
| 66 |
+
out = {}
|
| 67 |
+
if ":" in path:
|
| 68 |
+
out["path"], path = path.split(":", 1)
|
| 69 |
+
if "@" in path:
|
| 70 |
+
out["ref"], path = path.split("@", 1)
|
| 71 |
+
return out
|
| 72 |
+
|
| 73 |
+
@staticmethod
|
| 74 |
+
def _object_to_info(obj, path=None):
|
| 75 |
+
# obj.name and obj.filemode are None for the root tree!
|
| 76 |
+
is_dir = isinstance(obj, pygit2.Tree)
|
| 77 |
+
return {
|
| 78 |
+
"type": "directory" if is_dir else "file",
|
| 79 |
+
"name": (
|
| 80 |
+
"/".join([path, obj.name or ""]).lstrip("/") if path else obj.name
|
| 81 |
+
),
|
| 82 |
+
"hex": str(obj.id),
|
| 83 |
+
"mode": "100644" if obj.filemode is None else f"{obj.filemode:o}",
|
| 84 |
+
"size": 0 if is_dir else obj.size,
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
def ls(self, path, detail=True, ref=None, **kwargs):
|
| 88 |
+
tree = self._path_to_object(self._strip_protocol(path), ref)
|
| 89 |
+
return [
|
| 90 |
+
GitFileSystem._object_to_info(obj, path)
|
| 91 |
+
if detail
|
| 92 |
+
else GitFileSystem._object_to_info(obj, path)["name"]
|
| 93 |
+
for obj in (tree if isinstance(tree, pygit2.Tree) else [tree])
|
| 94 |
+
]
|
| 95 |
+
|
| 96 |
+
def info(self, path, ref=None, **kwargs):
|
| 97 |
+
tree = self._path_to_object(self._strip_protocol(path), ref)
|
| 98 |
+
return GitFileSystem._object_to_info(tree, path)
|
| 99 |
+
|
| 100 |
+
def ukey(self, path, ref=None):
|
| 101 |
+
return self.info(path, ref=ref)["hex"]
|
| 102 |
+
|
| 103 |
+
def _open(
|
| 104 |
+
self,
|
| 105 |
+
path,
|
| 106 |
+
mode="rb",
|
| 107 |
+
block_size=None,
|
| 108 |
+
autocommit=True,
|
| 109 |
+
cache_options=None,
|
| 110 |
+
ref=None,
|
| 111 |
+
**kwargs,
|
| 112 |
+
):
|
| 113 |
+
obj = self._path_to_object(path, ref or self.ref)
|
| 114 |
+
return MemoryFile(data=obj.data)
|
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/github.py
ADDED
|
@@ -0,0 +1,333 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
class GithubFileSystem(AbstractFileSystem):
|
| 12 |
+
"""Interface to files in github
|
| 13 |
+
|
| 14 |
+
An instance of this class provides the files residing within a remote github
|
| 15 |
+
repository. You may specify a point in the repos history, by SHA, branch
|
| 16 |
+
or tag (default is current master).
|
| 17 |
+
|
| 18 |
+
For files less than 1 MB in size, file content is returned directly in a
|
| 19 |
+
MemoryFile. For larger files, or for files tracked by git-lfs, file content
|
| 20 |
+
is returned as an HTTPFile wrapping the ``download_url`` provided by the
|
| 21 |
+
GitHub API.
|
| 22 |
+
|
| 23 |
+
When using fsspec.open, allows URIs of the form:
|
| 24 |
+
|
| 25 |
+
- "github://path/file", in which case you must specify org, repo and
|
| 26 |
+
may specify sha in the extra args
|
| 27 |
+
- 'github://org:repo@/precip/catalog.yml', where the org and repo are
|
| 28 |
+
part of the URI
|
| 29 |
+
- 'github://org:repo@sha/precip/catalog.yml', where the sha is also included
|
| 30 |
+
|
| 31 |
+
``sha`` can be the full or abbreviated hex of the commit you want to fetch
|
| 32 |
+
from, or a branch or tag name (so long as it doesn't contain special characters
|
| 33 |
+
like "/", "?", which would have to be HTTP-encoded).
|
| 34 |
+
|
| 35 |
+
For authorised access, you must provide username and token, which can be made
|
| 36 |
+
at https://github.com/settings/tokens
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
url = "https://api.github.com/repos/{org}/{repo}/git/trees/{sha}"
|
| 40 |
+
content_url = "https://api.github.com/repos/{org}/{repo}/contents/{path}?ref={sha}"
|
| 41 |
+
protocol = "github"
|
| 42 |
+
timeout = (60, 60) # connect, read timeouts
|
| 43 |
+
|
| 44 |
+
def __init__(
|
| 45 |
+
self, org, repo, sha=None, username=None, token=None, timeout=None, **kwargs
|
| 46 |
+
):
|
| 47 |
+
super().__init__(**kwargs)
|
| 48 |
+
self.org = org
|
| 49 |
+
self.repo = repo
|
| 50 |
+
if (username is None) ^ (token is None):
|
| 51 |
+
raise ValueError("Auth required both username and token")
|
| 52 |
+
self.username = username
|
| 53 |
+
self.token = token
|
| 54 |
+
if timeout is not None:
|
| 55 |
+
self.timeout = timeout
|
| 56 |
+
if sha is None:
|
| 57 |
+
# look up default branch (not necessarily "master")
|
| 58 |
+
u = "https://api.github.com/repos/{org}/{repo}"
|
| 59 |
+
r = requests.get(
|
| 60 |
+
u.format(org=org, repo=repo), timeout=self.timeout, **self.kw
|
| 61 |
+
)
|
| 62 |
+
r.raise_for_status()
|
| 63 |
+
sha = r.json()["default_branch"]
|
| 64 |
+
|
| 65 |
+
self.root = sha
|
| 66 |
+
self.ls("")
|
| 67 |
+
try:
|
| 68 |
+
from .http import HTTPFileSystem
|
| 69 |
+
|
| 70 |
+
self.http_fs = HTTPFileSystem(**kwargs)
|
| 71 |
+
except ImportError:
|
| 72 |
+
self.http_fs = None
|
| 73 |
+
|
| 74 |
+
@property
|
| 75 |
+
def kw(self):
|
| 76 |
+
if self.username:
|
| 77 |
+
return {"auth": (self.username, self.token)}
|
| 78 |
+
return {}
|
| 79 |
+
|
| 80 |
+
@classmethod
|
| 81 |
+
def repos(cls, org_or_user, is_org=True):
|
| 82 |
+
"""List repo names for given org or user
|
| 83 |
+
|
| 84 |
+
This may become the top level of the FS
|
| 85 |
+
|
| 86 |
+
Parameters
|
| 87 |
+
----------
|
| 88 |
+
org_or_user: str
|
| 89 |
+
Name of the github org or user to query
|
| 90 |
+
is_org: bool (default True)
|
| 91 |
+
Whether the name is an organisation (True) or user (False)
|
| 92 |
+
|
| 93 |
+
Returns
|
| 94 |
+
-------
|
| 95 |
+
List of string
|
| 96 |
+
"""
|
| 97 |
+
r = requests.get(
|
| 98 |
+
f"https://api.github.com/{['users', 'orgs'][is_org]}/{org_or_user}/repos",
|
| 99 |
+
timeout=cls.timeout,
|
| 100 |
+
)
|
| 101 |
+
r.raise_for_status()
|
| 102 |
+
return [repo["name"] for repo in r.json()]
|
| 103 |
+
|
| 104 |
+
@property
|
| 105 |
+
def tags(self):
|
| 106 |
+
"""Names of tags in the repo"""
|
| 107 |
+
r = requests.get(
|
| 108 |
+
f"https://api.github.com/repos/{self.org}/{self.repo}/tags",
|
| 109 |
+
timeout=self.timeout,
|
| 110 |
+
**self.kw,
|
| 111 |
+
)
|
| 112 |
+
r.raise_for_status()
|
| 113 |
+
return [t["name"] for t in r.json()]
|
| 114 |
+
|
| 115 |
+
@property
|
| 116 |
+
def branches(self):
|
| 117 |
+
"""Names of branches in the repo"""
|
| 118 |
+
r = requests.get(
|
| 119 |
+
f"https://api.github.com/repos/{self.org}/{self.repo}/branches",
|
| 120 |
+
timeout=self.timeout,
|
| 121 |
+
**self.kw,
|
| 122 |
+
)
|
| 123 |
+
r.raise_for_status()
|
| 124 |
+
return [t["name"] for t in r.json()]
|
| 125 |
+
|
| 126 |
+
@property
|
| 127 |
+
def refs(self):
|
| 128 |
+
"""Named references, tags and branches"""
|
| 129 |
+
return {"tags": self.tags, "branches": self.branches}
|
| 130 |
+
|
| 131 |
+
def ls(self, path, detail=False, sha=None, _sha=None, **kwargs):
|
| 132 |
+
"""List files at given path
|
| 133 |
+
|
| 134 |
+
Parameters
|
| 135 |
+
----------
|
| 136 |
+
path: str
|
| 137 |
+
Location to list, relative to repo root
|
| 138 |
+
detail: bool
|
| 139 |
+
If True, returns list of dicts, one per file; if False, returns
|
| 140 |
+
list of full filenames only
|
| 141 |
+
sha: str (optional)
|
| 142 |
+
List at the given point in the repo history, branch or tag name or commit
|
| 143 |
+
SHA
|
| 144 |
+
_sha: str (optional)
|
| 145 |
+
List this specific tree object (used internally to descend into trees)
|
| 146 |
+
"""
|
| 147 |
+
path = self._strip_protocol(path)
|
| 148 |
+
if path == "":
|
| 149 |
+
_sha = sha or self.root
|
| 150 |
+
if _sha is None:
|
| 151 |
+
parts = path.rstrip("/").split("/")
|
| 152 |
+
so_far = ""
|
| 153 |
+
_sha = sha or self.root
|
| 154 |
+
for part in parts:
|
| 155 |
+
out = self.ls(so_far, True, sha=sha, _sha=_sha)
|
| 156 |
+
so_far += "/" + part if so_far else part
|
| 157 |
+
out = [o for o in out if o["name"] == so_far]
|
| 158 |
+
if not out:
|
| 159 |
+
raise FileNotFoundError(path)
|
| 160 |
+
out = out[0]
|
| 161 |
+
if out["type"] == "file":
|
| 162 |
+
if detail:
|
| 163 |
+
return [out]
|
| 164 |
+
else:
|
| 165 |
+
return path
|
| 166 |
+
_sha = out["sha"]
|
| 167 |
+
if path not in self.dircache or sha not in [self.root, None]:
|
| 168 |
+
r = requests.get(
|
| 169 |
+
self.url.format(org=self.org, repo=self.repo, sha=_sha),
|
| 170 |
+
timeout=self.timeout,
|
| 171 |
+
**self.kw,
|
| 172 |
+
)
|
| 173 |
+
if r.status_code == 404:
|
| 174 |
+
raise FileNotFoundError(path)
|
| 175 |
+
r.raise_for_status()
|
| 176 |
+
types = {"blob": "file", "tree": "directory"}
|
| 177 |
+
out = [
|
| 178 |
+
{
|
| 179 |
+
"name": path + "/" + f["path"] if path else f["path"],
|
| 180 |
+
"mode": f["mode"],
|
| 181 |
+
"type": types[f["type"]],
|
| 182 |
+
"size": f.get("size", 0),
|
| 183 |
+
"sha": f["sha"],
|
| 184 |
+
}
|
| 185 |
+
for f in r.json()["tree"]
|
| 186 |
+
if f["type"] in types
|
| 187 |
+
]
|
| 188 |
+
if sha in [self.root, None]:
|
| 189 |
+
self.dircache[path] = out
|
| 190 |
+
else:
|
| 191 |
+
out = self.dircache[path]
|
| 192 |
+
if detail:
|
| 193 |
+
return out
|
| 194 |
+
else:
|
| 195 |
+
return sorted([f["name"] for f in out])
|
| 196 |
+
|
| 197 |
+
def invalidate_cache(self, path=None):
|
| 198 |
+
self.dircache.clear()
|
| 199 |
+
|
| 200 |
+
@classmethod
|
| 201 |
+
def _strip_protocol(cls, path):
|
| 202 |
+
opts = infer_storage_options(path)
|
| 203 |
+
if "username" not in opts:
|
| 204 |
+
return super()._strip_protocol(path)
|
| 205 |
+
return opts["path"].lstrip("/")
|
| 206 |
+
|
| 207 |
+
@staticmethod
|
| 208 |
+
def _get_kwargs_from_urls(path):
|
| 209 |
+
opts = infer_storage_options(path)
|
| 210 |
+
if "username" not in opts:
|
| 211 |
+
return {}
|
| 212 |
+
out = {"org": opts["username"], "repo": opts["password"]}
|
| 213 |
+
if opts["host"]:
|
| 214 |
+
out["sha"] = opts["host"]
|
| 215 |
+
return out
|
| 216 |
+
|
| 217 |
+
def _open(
|
| 218 |
+
self,
|
| 219 |
+
path,
|
| 220 |
+
mode="rb",
|
| 221 |
+
block_size=None,
|
| 222 |
+
cache_options=None,
|
| 223 |
+
sha=None,
|
| 224 |
+
**kwargs,
|
| 225 |
+
):
|
| 226 |
+
if mode != "rb":
|
| 227 |
+
raise NotImplementedError
|
| 228 |
+
|
| 229 |
+
# construct a url to hit the GitHub API's repo contents API
|
| 230 |
+
url = self.content_url.format(
|
| 231 |
+
org=self.org, repo=self.repo, path=path, sha=sha or self.root
|
| 232 |
+
)
|
| 233 |
+
|
| 234 |
+
# make a request to this API, and parse the response as JSON
|
| 235 |
+
r = requests.get(url, timeout=self.timeout, **self.kw)
|
| 236 |
+
if r.status_code == 404:
|
| 237 |
+
raise FileNotFoundError(path)
|
| 238 |
+
r.raise_for_status()
|
| 239 |
+
content_json = r.json()
|
| 240 |
+
|
| 241 |
+
# if the response's content key is not empty, try to parse it as base64
|
| 242 |
+
if content_json["content"]:
|
| 243 |
+
content = base64.b64decode(content_json["content"])
|
| 244 |
+
|
| 245 |
+
# as long as the content does not start with the string
|
| 246 |
+
# "version https://git-lfs.github.com/"
|
| 247 |
+
# then it is probably not a git-lfs pointer and we can just return
|
| 248 |
+
# the content directly
|
| 249 |
+
if not content.startswith(b"version https://git-lfs.github.com/"):
|
| 250 |
+
return MemoryFile(None, None, content)
|
| 251 |
+
|
| 252 |
+
# we land here if the content was not present in the first response
|
| 253 |
+
# (regular file over 1MB or git-lfs tracked file)
|
| 254 |
+
# in this case, we get let the HTTPFileSystem handle the download
|
| 255 |
+
if self.http_fs is None:
|
| 256 |
+
raise ImportError(
|
| 257 |
+
"Please install fsspec[http] to access github files >1 MB "
|
| 258 |
+
"or git-lfs tracked files."
|
| 259 |
+
)
|
| 260 |
+
return self.http_fs.open(
|
| 261 |
+
content_json["download_url"],
|
| 262 |
+
mode=mode,
|
| 263 |
+
block_size=block_size,
|
| 264 |
+
cache_options=cache_options,
|
| 265 |
+
**kwargs,
|
| 266 |
+
)
|
| 267 |
+
|
| 268 |
+
def rm(self, path, recursive=False, maxdepth=None, message=None):
|
| 269 |
+
path = self.expand_path(path, recursive=recursive, maxdepth=maxdepth)
|
| 270 |
+
for p in reversed(path):
|
| 271 |
+
self.rm_file(p, message=message)
|
| 272 |
+
|
| 273 |
+
def rm_file(self, path, message=None, **kwargs):
|
| 274 |
+
"""
|
| 275 |
+
Remove a file from a specified branch using a given commit message.
|
| 276 |
+
|
| 277 |
+
Since Github DELETE operation requires a branch name, and we can't reliably
|
| 278 |
+
determine whether the provided SHA refers to a branch, tag, or commit, we
|
| 279 |
+
assume it's a branch. If it's not, the user will encounter an error when
|
| 280 |
+
attempting to retrieve the file SHA or delete the file.
|
| 281 |
+
|
| 282 |
+
Parameters
|
| 283 |
+
----------
|
| 284 |
+
path: str
|
| 285 |
+
The file's location relative to the repository root.
|
| 286 |
+
message: str, optional
|
| 287 |
+
The commit message for the deletion.
|
| 288 |
+
"""
|
| 289 |
+
|
| 290 |
+
if not self.username:
|
| 291 |
+
raise ValueError("Authentication required")
|
| 292 |
+
|
| 293 |
+
path = self._strip_protocol(path)
|
| 294 |
+
|
| 295 |
+
# Attempt to get SHA from cache or Github API
|
| 296 |
+
sha = self._get_sha_from_cache(path)
|
| 297 |
+
if not sha:
|
| 298 |
+
url = self.content_url.format(
|
| 299 |
+
org=self.org, repo=self.repo, path=path.lstrip("/"), sha=self.root
|
| 300 |
+
)
|
| 301 |
+
r = requests.get(url, timeout=self.timeout, **self.kw)
|
| 302 |
+
if r.status_code == 404:
|
| 303 |
+
raise FileNotFoundError(path)
|
| 304 |
+
r.raise_for_status()
|
| 305 |
+
sha = r.json()["sha"]
|
| 306 |
+
|
| 307 |
+
# Delete the file
|
| 308 |
+
delete_url = self.content_url.format(
|
| 309 |
+
org=self.org, repo=self.repo, path=path, sha=self.root
|
| 310 |
+
)
|
| 311 |
+
branch = self.root
|
| 312 |
+
data = {
|
| 313 |
+
"message": message or f"Delete {path}",
|
| 314 |
+
"sha": sha,
|
| 315 |
+
**({"branch": branch} if branch else {}),
|
| 316 |
+
}
|
| 317 |
+
|
| 318 |
+
r = requests.delete(delete_url, json=data, timeout=self.timeout, **self.kw)
|
| 319 |
+
error_message = r.json().get("message", "")
|
| 320 |
+
if re.search(r"Branch .+ not found", error_message):
|
| 321 |
+
error = "Remove only works when the filesystem is initialised from a branch or default (None)"
|
| 322 |
+
raise ValueError(error)
|
| 323 |
+
r.raise_for_status()
|
| 324 |
+
|
| 325 |
+
self.invalidate_cache(path)
|
| 326 |
+
|
| 327 |
+
def _get_sha_from_cache(self, path):
|
| 328 |
+
for entries in self.dircache.values():
|
| 329 |
+
for entry in entries:
|
| 330 |
+
entry_path = entry.get("name")
|
| 331 |
+
if entry_path and entry_path == path and "sha" in entry:
|
| 332 |
+
return entry["sha"]
|
| 333 |
+
return None
|
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/http.py
ADDED
|
@@ -0,0 +1,902 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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5 |
+
import weakref
|
| 6 |
+
from copy import copy
|
| 7 |
+
from urllib.parse import urlparse
|
| 8 |
+
|
| 9 |
+
import aiohttp
|
| 10 |
+
import yarl
|
| 11 |
+
|
| 12 |
+
from fsspec.asyn import AbstractAsyncStreamedFile, AsyncFileSystem, sync, sync_wrapper
|
| 13 |
+
from fsspec.callbacks import DEFAULT_CALLBACK
|
| 14 |
+
from fsspec.exceptions import FSTimeoutError
|
| 15 |
+
from fsspec.spec import AbstractBufferedFile
|
| 16 |
+
from fsspec.utils import (
|
| 17 |
+
DEFAULT_BLOCK_SIZE,
|
| 18 |
+
glob_translate,
|
| 19 |
+
isfilelike,
|
| 20 |
+
nullcontext,
|
| 21 |
+
tokenize,
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
from ..caching import AllBytes
|
| 25 |
+
|
| 26 |
+
# https://stackoverflow.com/a/15926317/3821154
|
| 27 |
+
ex = re.compile(r"""<(a|A)\s+(?:[^>]*?\s+)?(href|HREF)=["'](?P<url>[^"']+)""")
|
| 28 |
+
ex2 = re.compile(r"""(?P<url>http[s]?://[-a-zA-Z0-9@:%_+.~#?&/=]+)""")
|
| 29 |
+
logger = logging.getLogger("fsspec.http")
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
async def get_client(**kwargs):
|
| 33 |
+
return aiohttp.ClientSession(**kwargs)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class HTTPFileSystem(AsyncFileSystem):
|
| 37 |
+
"""
|
| 38 |
+
Simple File-System for fetching data via HTTP(S)
|
| 39 |
+
|
| 40 |
+
``ls()`` is implemented by loading the parent page and doing a regex
|
| 41 |
+
match on the result. If simple_link=True, anything of the form
|
| 42 |
+
"http(s)://server.com/stuff?thing=other"; otherwise only links within
|
| 43 |
+
HTML href tags will be used.
|
| 44 |
+
|
| 45 |
+
URLs are passed unfiltered to aiohttp, so all addresses are accessible. Where URLs are
|
| 46 |
+
supplied by a user, the calling application may wish to filter to prevent scanning.
|
| 47 |
+
"""
|
| 48 |
+
|
| 49 |
+
protocol = ("http", "https")
|
| 50 |
+
sep = "/"
|
| 51 |
+
|
| 52 |
+
def __init__(
|
| 53 |
+
self,
|
| 54 |
+
simple_links=True,
|
| 55 |
+
block_size=None,
|
| 56 |
+
same_scheme=True,
|
| 57 |
+
size_policy=None,
|
| 58 |
+
cache_type="bytes",
|
| 59 |
+
cache_options=None,
|
| 60 |
+
asynchronous=False,
|
| 61 |
+
loop=None,
|
| 62 |
+
client_kwargs=None,
|
| 63 |
+
get_client=get_client,
|
| 64 |
+
encoded=False,
|
| 65 |
+
**storage_options,
|
| 66 |
+
):
|
| 67 |
+
"""
|
| 68 |
+
NB: if this is called async, you must await set_client
|
| 69 |
+
|
| 70 |
+
Parameters
|
| 71 |
+
----------
|
| 72 |
+
block_size: int
|
| 73 |
+
Blocks to read bytes; if 0, will default to raw requests file-like
|
| 74 |
+
objects instead of HTTPFile instances
|
| 75 |
+
simple_links: bool
|
| 76 |
+
If True, will consider both HTML <a> tags and anything that looks
|
| 77 |
+
like a URL; if False, will consider only the former.
|
| 78 |
+
same_scheme: True
|
| 79 |
+
When doing ls/glob, if this is True, only consider paths that have
|
| 80 |
+
http/https matching the input URLs.
|
| 81 |
+
size_policy: this argument is deprecated
|
| 82 |
+
client_kwargs: dict
|
| 83 |
+
Passed to aiohttp.ClientSession, see
|
| 84 |
+
https://docs.aiohttp.org/en/stable/client_reference.html
|
| 85 |
+
For example, ``{'auth': aiohttp.BasicAuth('user', 'pass')}``
|
| 86 |
+
get_client: Callable[..., aiohttp.ClientSession]
|
| 87 |
+
A callable, which takes keyword arguments and constructs
|
| 88 |
+
an aiohttp.ClientSession. Its state will be managed by
|
| 89 |
+
the HTTPFileSystem class.
|
| 90 |
+
storage_options: key-value
|
| 91 |
+
Any other parameters passed on to requests
|
| 92 |
+
cache_type, cache_options: defaults used in open()
|
| 93 |
+
"""
|
| 94 |
+
super().__init__(self, asynchronous=asynchronous, loop=loop, **storage_options)
|
| 95 |
+
self.block_size = block_size if block_size is not None else DEFAULT_BLOCK_SIZE
|
| 96 |
+
self.simple_links = simple_links
|
| 97 |
+
self.same_schema = same_scheme
|
| 98 |
+
self.cache_type = cache_type
|
| 99 |
+
self.cache_options = cache_options
|
| 100 |
+
self.client_kwargs = client_kwargs or {}
|
| 101 |
+
self.get_client = get_client
|
| 102 |
+
self.encoded = encoded
|
| 103 |
+
self.kwargs = storage_options
|
| 104 |
+
self._session = None
|
| 105 |
+
|
| 106 |
+
# Clean caching-related parameters from `storage_options`
|
| 107 |
+
# before propagating them as `request_options` through `self.kwargs`.
|
| 108 |
+
# TODO: Maybe rename `self.kwargs` to `self.request_options` to make
|
| 109 |
+
# it clearer.
|
| 110 |
+
request_options = copy(storage_options)
|
| 111 |
+
self.use_listings_cache = request_options.pop("use_listings_cache", False)
|
| 112 |
+
request_options.pop("listings_expiry_time", None)
|
| 113 |
+
request_options.pop("max_paths", None)
|
| 114 |
+
request_options.pop("skip_instance_cache", None)
|
| 115 |
+
self.kwargs = request_options
|
| 116 |
+
|
| 117 |
+
@property
|
| 118 |
+
def fsid(self):
|
| 119 |
+
return "http"
|
| 120 |
+
|
| 121 |
+
def encode_url(self, url):
|
| 122 |
+
return yarl.URL(url, encoded=self.encoded)
|
| 123 |
+
|
| 124 |
+
@staticmethod
|
| 125 |
+
def close_session(loop, session):
|
| 126 |
+
if loop is not None and loop.is_running():
|
| 127 |
+
try:
|
| 128 |
+
sync(loop, session.close, timeout=0.1)
|
| 129 |
+
return
|
| 130 |
+
except (TimeoutError, FSTimeoutError, NotImplementedError):
|
| 131 |
+
pass
|
| 132 |
+
connector = getattr(session, "_connector", None)
|
| 133 |
+
if connector is not None:
|
| 134 |
+
# close after loop is dead
|
| 135 |
+
connector._close()
|
| 136 |
+
|
| 137 |
+
async def set_session(self):
|
| 138 |
+
if self._session is None:
|
| 139 |
+
self._session = await self.get_client(loop=self.loop, **self.client_kwargs)
|
| 140 |
+
if not self.asynchronous:
|
| 141 |
+
weakref.finalize(self, self.close_session, self.loop, self._session)
|
| 142 |
+
return self._session
|
| 143 |
+
|
| 144 |
+
@classmethod
|
| 145 |
+
def _strip_protocol(cls, path):
|
| 146 |
+
"""For HTTP, we always want to keep the full URL"""
|
| 147 |
+
return path
|
| 148 |
+
|
| 149 |
+
@classmethod
|
| 150 |
+
def _parent(cls, path):
|
| 151 |
+
# override, since _strip_protocol is different for URLs
|
| 152 |
+
par = super()._parent(path)
|
| 153 |
+
if len(par) > 7: # "http://..."
|
| 154 |
+
return par
|
| 155 |
+
return ""
|
| 156 |
+
|
| 157 |
+
async def _ls_real(self, url, detail=True, **kwargs):
|
| 158 |
+
# ignoring URL-encoded arguments
|
| 159 |
+
kw = self.kwargs.copy()
|
| 160 |
+
kw.update(kwargs)
|
| 161 |
+
logger.debug(url)
|
| 162 |
+
session = await self.set_session()
|
| 163 |
+
async with session.get(self.encode_url(url), **self.kwargs) as r:
|
| 164 |
+
self._raise_not_found_for_status(r, url)
|
| 165 |
+
|
| 166 |
+
if "Content-Type" in r.headers:
|
| 167 |
+
mimetype = r.headers["Content-Type"].partition(";")[0]
|
| 168 |
+
else:
|
| 169 |
+
mimetype = None
|
| 170 |
+
|
| 171 |
+
if mimetype in ("text/html", None):
|
| 172 |
+
try:
|
| 173 |
+
text = await r.text(errors="ignore")
|
| 174 |
+
if self.simple_links:
|
| 175 |
+
links = ex2.findall(text) + [u[2] for u in ex.findall(text)]
|
| 176 |
+
else:
|
| 177 |
+
links = [u[2] for u in ex.findall(text)]
|
| 178 |
+
except UnicodeDecodeError:
|
| 179 |
+
links = [] # binary, not HTML
|
| 180 |
+
else:
|
| 181 |
+
links = []
|
| 182 |
+
|
| 183 |
+
out = set()
|
| 184 |
+
parts = urlparse(url)
|
| 185 |
+
for l in links:
|
| 186 |
+
if isinstance(l, tuple):
|
| 187 |
+
l = l[1]
|
| 188 |
+
if l.startswith("/") and len(l) > 1:
|
| 189 |
+
# absolute URL on this server
|
| 190 |
+
l = f"{parts.scheme}://{parts.netloc}{l}"
|
| 191 |
+
if l.startswith("http"):
|
| 192 |
+
if self.same_schema and l.startswith(url.rstrip("/") + "/"):
|
| 193 |
+
out.add(l)
|
| 194 |
+
elif l.replace("https", "http").startswith(
|
| 195 |
+
url.replace("https", "http").rstrip("/") + "/"
|
| 196 |
+
):
|
| 197 |
+
# allowed to cross http <-> https
|
| 198 |
+
out.add(l)
|
| 199 |
+
else:
|
| 200 |
+
if l not in ["..", "../"]:
|
| 201 |
+
# Ignore FTP-like "parent"
|
| 202 |
+
out.add("/".join([url.rstrip("/"), l.lstrip("/")]))
|
| 203 |
+
if not out and url.endswith("/"):
|
| 204 |
+
out = await self._ls_real(url.rstrip("/"), detail=False)
|
| 205 |
+
if detail:
|
| 206 |
+
return [
|
| 207 |
+
{
|
| 208 |
+
"name": u,
|
| 209 |
+
"size": None,
|
| 210 |
+
"type": "directory" if u.endswith("/") else "file",
|
| 211 |
+
}
|
| 212 |
+
for u in out
|
| 213 |
+
]
|
| 214 |
+
else:
|
| 215 |
+
return sorted(out)
|
| 216 |
+
|
| 217 |
+
async def _ls(self, url, detail=True, **kwargs):
|
| 218 |
+
if self.use_listings_cache and url in self.dircache:
|
| 219 |
+
out = self.dircache[url]
|
| 220 |
+
else:
|
| 221 |
+
out = await self._ls_real(url, detail=detail, **kwargs)
|
| 222 |
+
self.dircache[url] = out
|
| 223 |
+
return out
|
| 224 |
+
|
| 225 |
+
ls = sync_wrapper(_ls)
|
| 226 |
+
|
| 227 |
+
def _raise_not_found_for_status(self, response, url):
|
| 228 |
+
"""
|
| 229 |
+
Raises FileNotFoundError for 404s, otherwise uses raise_for_status.
|
| 230 |
+
"""
|
| 231 |
+
if response.status == 404:
|
| 232 |
+
raise FileNotFoundError(url)
|
| 233 |
+
response.raise_for_status()
|
| 234 |
+
|
| 235 |
+
async def _cat_file(self, url, start=None, end=None, **kwargs):
|
| 236 |
+
kw = self.kwargs.copy()
|
| 237 |
+
kw.update(kwargs)
|
| 238 |
+
logger.debug(url)
|
| 239 |
+
|
| 240 |
+
if start is not None or end is not None:
|
| 241 |
+
if start == end:
|
| 242 |
+
return b""
|
| 243 |
+
headers = kw.pop("headers", {}).copy()
|
| 244 |
+
|
| 245 |
+
headers["Range"] = await self._process_limits(url, start, end)
|
| 246 |
+
kw["headers"] = headers
|
| 247 |
+
session = await self.set_session()
|
| 248 |
+
async with session.get(self.encode_url(url), **kw) as r:
|
| 249 |
+
out = await r.read()
|
| 250 |
+
self._raise_not_found_for_status(r, url)
|
| 251 |
+
return out
|
| 252 |
+
|
| 253 |
+
async def _get_file(
|
| 254 |
+
self, rpath, lpath, chunk_size=5 * 2**20, callback=DEFAULT_CALLBACK, **kwargs
|
| 255 |
+
):
|
| 256 |
+
kw = self.kwargs.copy()
|
| 257 |
+
kw.update(kwargs)
|
| 258 |
+
logger.debug(rpath)
|
| 259 |
+
session = await self.set_session()
|
| 260 |
+
async with session.get(self.encode_url(rpath), **kw) as r:
|
| 261 |
+
try:
|
| 262 |
+
size = int(r.headers["content-length"])
|
| 263 |
+
except (ValueError, KeyError):
|
| 264 |
+
size = None
|
| 265 |
+
|
| 266 |
+
callback.set_size(size)
|
| 267 |
+
self._raise_not_found_for_status(r, rpath)
|
| 268 |
+
if isfilelike(lpath):
|
| 269 |
+
outfile = lpath
|
| 270 |
+
else:
|
| 271 |
+
outfile = open(lpath, "wb") # noqa: ASYNC230
|
| 272 |
+
|
| 273 |
+
try:
|
| 274 |
+
chunk = True
|
| 275 |
+
while chunk:
|
| 276 |
+
chunk = await r.content.read(chunk_size)
|
| 277 |
+
outfile.write(chunk)
|
| 278 |
+
callback.relative_update(len(chunk))
|
| 279 |
+
finally:
|
| 280 |
+
if not isfilelike(lpath):
|
| 281 |
+
outfile.close()
|
| 282 |
+
|
| 283 |
+
async def _put_file(
|
| 284 |
+
self,
|
| 285 |
+
lpath,
|
| 286 |
+
rpath,
|
| 287 |
+
chunk_size=5 * 2**20,
|
| 288 |
+
callback=DEFAULT_CALLBACK,
|
| 289 |
+
method="post",
|
| 290 |
+
mode="overwrite",
|
| 291 |
+
**kwargs,
|
| 292 |
+
):
|
| 293 |
+
if mode != "overwrite":
|
| 294 |
+
raise NotImplementedError("Exclusive write")
|
| 295 |
+
|
| 296 |
+
async def gen_chunks():
|
| 297 |
+
# Support passing arbitrary file-like objects
|
| 298 |
+
# and use them instead of streams.
|
| 299 |
+
if isinstance(lpath, io.IOBase):
|
| 300 |
+
context = nullcontext(lpath)
|
| 301 |
+
use_seek = False # might not support seeking
|
| 302 |
+
else:
|
| 303 |
+
context = open(lpath, "rb") # noqa: ASYNC230
|
| 304 |
+
use_seek = True
|
| 305 |
+
|
| 306 |
+
with context as f:
|
| 307 |
+
if use_seek:
|
| 308 |
+
callback.set_size(f.seek(0, 2))
|
| 309 |
+
f.seek(0)
|
| 310 |
+
else:
|
| 311 |
+
callback.set_size(getattr(f, "size", None))
|
| 312 |
+
|
| 313 |
+
chunk = f.read(chunk_size)
|
| 314 |
+
while chunk:
|
| 315 |
+
yield chunk
|
| 316 |
+
callback.relative_update(len(chunk))
|
| 317 |
+
chunk = f.read(chunk_size)
|
| 318 |
+
|
| 319 |
+
kw = self.kwargs.copy()
|
| 320 |
+
kw.update(kwargs)
|
| 321 |
+
session = await self.set_session()
|
| 322 |
+
|
| 323 |
+
method = method.lower()
|
| 324 |
+
if method not in ("post", "put"):
|
| 325 |
+
raise ValueError(
|
| 326 |
+
f"method has to be either 'post' or 'put', not: {method!r}"
|
| 327 |
+
)
|
| 328 |
+
|
| 329 |
+
meth = getattr(session, method)
|
| 330 |
+
async with meth(self.encode_url(rpath), data=gen_chunks(), **kw) as resp:
|
| 331 |
+
self._raise_not_found_for_status(resp, rpath)
|
| 332 |
+
|
| 333 |
+
async def _exists(self, path, strict=False, **kwargs):
|
| 334 |
+
kw = self.kwargs.copy()
|
| 335 |
+
kw.update(kwargs)
|
| 336 |
+
try:
|
| 337 |
+
logger.debug(path)
|
| 338 |
+
session = await self.set_session()
|
| 339 |
+
r = await session.get(self.encode_url(path), **kw)
|
| 340 |
+
async with r:
|
| 341 |
+
if strict:
|
| 342 |
+
self._raise_not_found_for_status(r, path)
|
| 343 |
+
return r.status < 400
|
| 344 |
+
except FileNotFoundError:
|
| 345 |
+
return False
|
| 346 |
+
except aiohttp.ClientError:
|
| 347 |
+
if strict:
|
| 348 |
+
raise
|
| 349 |
+
return False
|
| 350 |
+
|
| 351 |
+
async def _isfile(self, path, **kwargs):
|
| 352 |
+
return await self._exists(path, **kwargs)
|
| 353 |
+
|
| 354 |
+
def _open(
|
| 355 |
+
self,
|
| 356 |
+
path,
|
| 357 |
+
mode="rb",
|
| 358 |
+
block_size=None,
|
| 359 |
+
autocommit=None, # XXX: This differs from the base class.
|
| 360 |
+
cache_type=None,
|
| 361 |
+
cache_options=None,
|
| 362 |
+
size=None,
|
| 363 |
+
**kwargs,
|
| 364 |
+
):
|
| 365 |
+
"""Make a file-like object
|
| 366 |
+
|
| 367 |
+
Parameters
|
| 368 |
+
----------
|
| 369 |
+
path: str
|
| 370 |
+
Full URL with protocol
|
| 371 |
+
mode: string
|
| 372 |
+
must be "rb"
|
| 373 |
+
block_size: int or None
|
| 374 |
+
Bytes to download in one request; use instance value if None. If
|
| 375 |
+
zero, will return a streaming Requests file-like instance.
|
| 376 |
+
kwargs: key-value
|
| 377 |
+
Any other parameters, passed to requests calls
|
| 378 |
+
"""
|
| 379 |
+
if mode != "rb":
|
| 380 |
+
raise NotImplementedError
|
| 381 |
+
block_size = block_size if block_size is not None else self.block_size
|
| 382 |
+
kw = self.kwargs.copy()
|
| 383 |
+
kw["asynchronous"] = self.asynchronous
|
| 384 |
+
kw.update(kwargs)
|
| 385 |
+
info = {}
|
| 386 |
+
size = size or info.update(self.info(path, **kwargs)) or info["size"]
|
| 387 |
+
session = sync(self.loop, self.set_session)
|
| 388 |
+
if block_size and size and info.get("partial", True):
|
| 389 |
+
return HTTPFile(
|
| 390 |
+
self,
|
| 391 |
+
path,
|
| 392 |
+
session=session,
|
| 393 |
+
block_size=block_size,
|
| 394 |
+
mode=mode,
|
| 395 |
+
size=size,
|
| 396 |
+
cache_type=cache_type or self.cache_type,
|
| 397 |
+
cache_options=cache_options or self.cache_options,
|
| 398 |
+
loop=self.loop,
|
| 399 |
+
**kw,
|
| 400 |
+
)
|
| 401 |
+
else:
|
| 402 |
+
return HTTPStreamFile(
|
| 403 |
+
self,
|
| 404 |
+
path,
|
| 405 |
+
mode=mode,
|
| 406 |
+
loop=self.loop,
|
| 407 |
+
session=session,
|
| 408 |
+
**kw,
|
| 409 |
+
)
|
| 410 |
+
|
| 411 |
+
async def open_async(self, path, mode="rb", size=None, **kwargs):
|
| 412 |
+
session = await self.set_session()
|
| 413 |
+
if size is None:
|
| 414 |
+
try:
|
| 415 |
+
size = (await self._info(path, **kwargs))["size"]
|
| 416 |
+
except FileNotFoundError:
|
| 417 |
+
pass
|
| 418 |
+
return AsyncStreamFile(
|
| 419 |
+
self,
|
| 420 |
+
path,
|
| 421 |
+
loop=self.loop,
|
| 422 |
+
session=session,
|
| 423 |
+
size=size,
|
| 424 |
+
**kwargs,
|
| 425 |
+
)
|
| 426 |
+
|
| 427 |
+
def ukey(self, url):
|
| 428 |
+
"""Unique identifier; assume HTTP files are static, unchanging"""
|
| 429 |
+
return tokenize(url, self.kwargs, self.protocol)
|
| 430 |
+
|
| 431 |
+
async def _info(self, url, **kwargs):
|
| 432 |
+
"""Get info of URL
|
| 433 |
+
|
| 434 |
+
Tries to access location via HEAD, and then GET methods, but does
|
| 435 |
+
not fetch the data.
|
| 436 |
+
|
| 437 |
+
It is possible that the server does not supply any size information, in
|
| 438 |
+
which case size will be given as None (and certain operations on the
|
| 439 |
+
corresponding file will not work).
|
| 440 |
+
"""
|
| 441 |
+
info = {}
|
| 442 |
+
session = await self.set_session()
|
| 443 |
+
|
| 444 |
+
for policy in ["head", "get"]:
|
| 445 |
+
try:
|
| 446 |
+
info.update(
|
| 447 |
+
await _file_info(
|
| 448 |
+
self.encode_url(url),
|
| 449 |
+
size_policy=policy,
|
| 450 |
+
session=session,
|
| 451 |
+
**self.kwargs,
|
| 452 |
+
**kwargs,
|
| 453 |
+
)
|
| 454 |
+
)
|
| 455 |
+
if info.get("size") is not None:
|
| 456 |
+
break
|
| 457 |
+
except Exception as exc:
|
| 458 |
+
if policy == "get":
|
| 459 |
+
# If get failed, then raise a FileNotFoundError
|
| 460 |
+
raise FileNotFoundError(url) from exc
|
| 461 |
+
logger.debug("", exc_info=exc)
|
| 462 |
+
|
| 463 |
+
return {"name": url, "size": None, **info, "type": "file"}
|
| 464 |
+
|
| 465 |
+
async def _glob(self, path, maxdepth=None, **kwargs):
|
| 466 |
+
"""
|
| 467 |
+
Find files by glob-matching.
|
| 468 |
+
|
| 469 |
+
This implementation is idntical to the one in AbstractFileSystem,
|
| 470 |
+
but "?" is not considered as a character for globbing, because it is
|
| 471 |
+
so common in URLs, often identifying the "query" part.
|
| 472 |
+
"""
|
| 473 |
+
if maxdepth is not None and maxdepth < 1:
|
| 474 |
+
raise ValueError("maxdepth must be at least 1")
|
| 475 |
+
import re
|
| 476 |
+
|
| 477 |
+
ends_with_slash = path.endswith("/") # _strip_protocol strips trailing slash
|
| 478 |
+
path = self._strip_protocol(path)
|
| 479 |
+
append_slash_to_dirname = ends_with_slash or path.endswith(("/**", "/*"))
|
| 480 |
+
idx_star = path.find("*") if path.find("*") >= 0 else len(path)
|
| 481 |
+
idx_brace = path.find("[") if path.find("[") >= 0 else len(path)
|
| 482 |
+
|
| 483 |
+
min_idx = min(idx_star, idx_brace)
|
| 484 |
+
|
| 485 |
+
detail = kwargs.pop("detail", False)
|
| 486 |
+
|
| 487 |
+
if not has_magic(path):
|
| 488 |
+
if await self._exists(path, **kwargs):
|
| 489 |
+
if not detail:
|
| 490 |
+
return [path]
|
| 491 |
+
else:
|
| 492 |
+
return {path: await self._info(path, **kwargs)}
|
| 493 |
+
else:
|
| 494 |
+
if not detail:
|
| 495 |
+
return [] # glob of non-existent returns empty
|
| 496 |
+
else:
|
| 497 |
+
return {}
|
| 498 |
+
elif "/" in path[:min_idx]:
|
| 499 |
+
min_idx = path[:min_idx].rindex("/")
|
| 500 |
+
root = path[: min_idx + 1]
|
| 501 |
+
depth = path[min_idx + 1 :].count("/") + 1
|
| 502 |
+
else:
|
| 503 |
+
root = ""
|
| 504 |
+
depth = path[min_idx + 1 :].count("/") + 1
|
| 505 |
+
|
| 506 |
+
if "**" in path:
|
| 507 |
+
if maxdepth is not None:
|
| 508 |
+
idx_double_stars = path.find("**")
|
| 509 |
+
depth_double_stars = path[idx_double_stars:].count("/") + 1
|
| 510 |
+
depth = depth - depth_double_stars + maxdepth
|
| 511 |
+
else:
|
| 512 |
+
depth = None
|
| 513 |
+
|
| 514 |
+
allpaths = await self._find(
|
| 515 |
+
root, maxdepth=depth, withdirs=True, detail=True, **kwargs
|
| 516 |
+
)
|
| 517 |
+
|
| 518 |
+
pattern = glob_translate(path + ("/" if ends_with_slash else ""))
|
| 519 |
+
pattern = re.compile(pattern)
|
| 520 |
+
|
| 521 |
+
out = {
|
| 522 |
+
(
|
| 523 |
+
p.rstrip("/")
|
| 524 |
+
if not append_slash_to_dirname
|
| 525 |
+
and info["type"] == "directory"
|
| 526 |
+
and p.endswith("/")
|
| 527 |
+
else p
|
| 528 |
+
): info
|
| 529 |
+
for p, info in sorted(allpaths.items())
|
| 530 |
+
if pattern.match(p.rstrip("/"))
|
| 531 |
+
}
|
| 532 |
+
|
| 533 |
+
if detail:
|
| 534 |
+
return out
|
| 535 |
+
else:
|
| 536 |
+
return list(out)
|
| 537 |
+
|
| 538 |
+
async def _isdir(self, path):
|
| 539 |
+
# override, since all URLs are (also) files
|
| 540 |
+
try:
|
| 541 |
+
return bool(await self._ls(path))
|
| 542 |
+
except (FileNotFoundError, ValueError):
|
| 543 |
+
return False
|
| 544 |
+
|
| 545 |
+
async def _pipe_file(self, path, value, mode="overwrite", **kwargs):
|
| 546 |
+
"""
|
| 547 |
+
Write bytes to a remote file over HTTP.
|
| 548 |
+
|
| 549 |
+
Parameters
|
| 550 |
+
----------
|
| 551 |
+
path : str
|
| 552 |
+
Target URL where the data should be written
|
| 553 |
+
value : bytes
|
| 554 |
+
Data to be written
|
| 555 |
+
mode : str
|
| 556 |
+
How to write to the file - 'overwrite' or 'append'
|
| 557 |
+
**kwargs : dict
|
| 558 |
+
Additional parameters to pass to the HTTP request
|
| 559 |
+
"""
|
| 560 |
+
url = self._strip_protocol(path)
|
| 561 |
+
headers = kwargs.pop("headers", {})
|
| 562 |
+
headers["Content-Length"] = str(len(value))
|
| 563 |
+
|
| 564 |
+
session = await self.set_session()
|
| 565 |
+
|
| 566 |
+
async with session.put(
|
| 567 |
+
self.encode_url(url), data=value, headers=headers, **kwargs
|
| 568 |
+
) as r:
|
| 569 |
+
r.raise_for_status()
|
| 570 |
+
|
| 571 |
+
|
| 572 |
+
class HTTPFile(AbstractBufferedFile):
|
| 573 |
+
"""
|
| 574 |
+
A file-like object pointing to a remote HTTP(S) resource
|
| 575 |
+
|
| 576 |
+
Supports only reading, with read-ahead of a predetermined block-size.
|
| 577 |
+
|
| 578 |
+
In the case that the server does not supply the filesize, only reading of
|
| 579 |
+
the complete file in one go is supported.
|
| 580 |
+
|
| 581 |
+
Parameters
|
| 582 |
+
----------
|
| 583 |
+
url: str
|
| 584 |
+
Full URL of the remote resource, including the protocol
|
| 585 |
+
session: aiohttp.ClientSession or None
|
| 586 |
+
All calls will be made within this session, to avoid restarting
|
| 587 |
+
connections where the server allows this
|
| 588 |
+
block_size: int or None
|
| 589 |
+
The amount of read-ahead to do, in bytes. Default is 5MB, or the value
|
| 590 |
+
configured for the FileSystem creating this file
|
| 591 |
+
size: None or int
|
| 592 |
+
If given, this is the size of the file in bytes, and we don't attempt
|
| 593 |
+
to call the server to find the value.
|
| 594 |
+
kwargs: all other key-values are passed to requests calls.
|
| 595 |
+
"""
|
| 596 |
+
|
| 597 |
+
def __init__(
|
| 598 |
+
self,
|
| 599 |
+
fs,
|
| 600 |
+
url,
|
| 601 |
+
session=None,
|
| 602 |
+
block_size=None,
|
| 603 |
+
mode="rb",
|
| 604 |
+
cache_type="bytes",
|
| 605 |
+
cache_options=None,
|
| 606 |
+
size=None,
|
| 607 |
+
loop=None,
|
| 608 |
+
asynchronous=False,
|
| 609 |
+
**kwargs,
|
| 610 |
+
):
|
| 611 |
+
if mode != "rb":
|
| 612 |
+
raise NotImplementedError("File mode not supported")
|
| 613 |
+
self.asynchronous = asynchronous
|
| 614 |
+
self.loop = loop
|
| 615 |
+
self.url = url
|
| 616 |
+
self.session = session
|
| 617 |
+
self.details = {"name": url, "size": size, "type": "file"}
|
| 618 |
+
super().__init__(
|
| 619 |
+
fs=fs,
|
| 620 |
+
path=url,
|
| 621 |
+
mode=mode,
|
| 622 |
+
block_size=block_size,
|
| 623 |
+
cache_type=cache_type,
|
| 624 |
+
cache_options=cache_options,
|
| 625 |
+
**kwargs,
|
| 626 |
+
)
|
| 627 |
+
|
| 628 |
+
def read(self, length=-1):
|
| 629 |
+
"""Read bytes from file
|
| 630 |
+
|
| 631 |
+
Parameters
|
| 632 |
+
----------
|
| 633 |
+
length: int
|
| 634 |
+
Read up to this many bytes. If negative, read all content to end of
|
| 635 |
+
file. If the server has not supplied the filesize, attempting to
|
| 636 |
+
read only part of the data will raise a ValueError.
|
| 637 |
+
"""
|
| 638 |
+
if (
|
| 639 |
+
(length < 0 and self.loc == 0) # explicit read all
|
| 640 |
+
# but not when the size is known and fits into a block anyways
|
| 641 |
+
and not (self.size is not None and self.size <= self.blocksize)
|
| 642 |
+
):
|
| 643 |
+
self._fetch_all()
|
| 644 |
+
if self.size is None:
|
| 645 |
+
if length < 0:
|
| 646 |
+
self._fetch_all()
|
| 647 |
+
else:
|
| 648 |
+
length = min(self.size - self.loc, length)
|
| 649 |
+
return super().read(length)
|
| 650 |
+
|
| 651 |
+
async def async_fetch_all(self):
|
| 652 |
+
"""Read whole file in one shot, without caching
|
| 653 |
+
|
| 654 |
+
This is only called when position is still at zero,
|
| 655 |
+
and read() is called without a byte-count.
|
| 656 |
+
"""
|
| 657 |
+
logger.debug(f"Fetch all for {self}")
|
| 658 |
+
if not isinstance(self.cache, AllBytes):
|
| 659 |
+
r = await self.session.get(self.fs.encode_url(self.url), **self.kwargs)
|
| 660 |
+
async with r:
|
| 661 |
+
r.raise_for_status()
|
| 662 |
+
out = await r.read()
|
| 663 |
+
self.cache = AllBytes(
|
| 664 |
+
size=len(out), fetcher=None, blocksize=None, data=out
|
| 665 |
+
)
|
| 666 |
+
self.size = len(out)
|
| 667 |
+
|
| 668 |
+
_fetch_all = sync_wrapper(async_fetch_all)
|
| 669 |
+
|
| 670 |
+
def _parse_content_range(self, headers):
|
| 671 |
+
"""Parse the Content-Range header"""
|
| 672 |
+
s = headers.get("Content-Range", "")
|
| 673 |
+
m = re.match(r"bytes (\d+-\d+|\*)/(\d+|\*)", s)
|
| 674 |
+
if not m:
|
| 675 |
+
return None, None, None
|
| 676 |
+
|
| 677 |
+
if m[1] == "*":
|
| 678 |
+
start = end = None
|
| 679 |
+
else:
|
| 680 |
+
start, end = [int(x) for x in m[1].split("-")]
|
| 681 |
+
total = None if m[2] == "*" else int(m[2])
|
| 682 |
+
return start, end, total
|
| 683 |
+
|
| 684 |
+
async def async_fetch_range(self, start, end):
|
| 685 |
+
"""Download a block of data
|
| 686 |
+
|
| 687 |
+
The expectation is that the server returns only the requested bytes,
|
| 688 |
+
with HTTP code 206. If this is not the case, we first check the headers,
|
| 689 |
+
and then stream the output - if the data size is bigger than we
|
| 690 |
+
requested, an exception is raised.
|
| 691 |
+
"""
|
| 692 |
+
logger.debug(f"Fetch range for {self}: {start}-{end}")
|
| 693 |
+
kwargs = self.kwargs.copy()
|
| 694 |
+
headers = kwargs.pop("headers", {}).copy()
|
| 695 |
+
headers["Range"] = f"bytes={start}-{end - 1}"
|
| 696 |
+
logger.debug(f"{self.url} : {headers['Range']}")
|
| 697 |
+
r = await self.session.get(
|
| 698 |
+
self.fs.encode_url(self.url), headers=headers, **kwargs
|
| 699 |
+
)
|
| 700 |
+
async with r:
|
| 701 |
+
if r.status == 416:
|
| 702 |
+
# range request outside file
|
| 703 |
+
return b""
|
| 704 |
+
r.raise_for_status()
|
| 705 |
+
|
| 706 |
+
# If the server has handled the range request, it should reply
|
| 707 |
+
# with status 206 (partial content). But we'll guess that a suitable
|
| 708 |
+
# Content-Range header or a Content-Length no more than the
|
| 709 |
+
# requested range also mean we have got the desired range.
|
| 710 |
+
response_is_range = (
|
| 711 |
+
r.status == 206
|
| 712 |
+
or self._parse_content_range(r.headers)[0] == start
|
| 713 |
+
or int(r.headers.get("Content-Length", end + 1)) <= end - start
|
| 714 |
+
)
|
| 715 |
+
|
| 716 |
+
if response_is_range:
|
| 717 |
+
# partial content, as expected
|
| 718 |
+
out = await r.read()
|
| 719 |
+
elif start > 0:
|
| 720 |
+
raise ValueError(
|
| 721 |
+
"The HTTP server doesn't appear to support range requests. "
|
| 722 |
+
"Only reading this file from the beginning is supported. "
|
| 723 |
+
"Open with block_size=0 for a streaming file interface."
|
| 724 |
+
)
|
| 725 |
+
else:
|
| 726 |
+
# Response is not a range, but we want the start of the file,
|
| 727 |
+
# so we can read the required amount anyway.
|
| 728 |
+
cl = 0
|
| 729 |
+
out = []
|
| 730 |
+
while True:
|
| 731 |
+
chunk = await r.content.read(2**20)
|
| 732 |
+
# data size unknown, let's read until we have enough
|
| 733 |
+
if chunk:
|
| 734 |
+
out.append(chunk)
|
| 735 |
+
cl += len(chunk)
|
| 736 |
+
if cl > end - start:
|
| 737 |
+
break
|
| 738 |
+
else:
|
| 739 |
+
break
|
| 740 |
+
out = b"".join(out)[: end - start]
|
| 741 |
+
return out
|
| 742 |
+
|
| 743 |
+
_fetch_range = sync_wrapper(async_fetch_range)
|
| 744 |
+
|
| 745 |
+
|
| 746 |
+
magic_check = re.compile("([*[])")
|
| 747 |
+
|
| 748 |
+
|
| 749 |
+
def has_magic(s):
|
| 750 |
+
match = magic_check.search(s)
|
| 751 |
+
return match is not None
|
| 752 |
+
|
| 753 |
+
|
| 754 |
+
class HTTPStreamFile(AbstractBufferedFile):
|
| 755 |
+
def __init__(self, fs, url, mode="rb", loop=None, session=None, **kwargs):
|
| 756 |
+
self.asynchronous = kwargs.pop("asynchronous", False)
|
| 757 |
+
self.url = url
|
| 758 |
+
self.loop = loop
|
| 759 |
+
self.session = session
|
| 760 |
+
if mode != "rb":
|
| 761 |
+
raise ValueError
|
| 762 |
+
self.details = {"name": url, "size": None}
|
| 763 |
+
super().__init__(fs=fs, path=url, mode=mode, cache_type="none", **kwargs)
|
| 764 |
+
|
| 765 |
+
async def cor():
|
| 766 |
+
r = await self.session.get(self.fs.encode_url(url), **kwargs).__aenter__()
|
| 767 |
+
self.fs._raise_not_found_for_status(r, url)
|
| 768 |
+
return r
|
| 769 |
+
|
| 770 |
+
self.r = sync(self.loop, cor)
|
| 771 |
+
self.loop = fs.loop
|
| 772 |
+
|
| 773 |
+
def seek(self, loc, whence=0):
|
| 774 |
+
if loc == 0 and whence == 1:
|
| 775 |
+
return
|
| 776 |
+
if loc == self.loc and whence == 0:
|
| 777 |
+
return
|
| 778 |
+
raise ValueError("Cannot seek streaming HTTP file")
|
| 779 |
+
|
| 780 |
+
async def _read(self, num=-1):
|
| 781 |
+
out = await self.r.content.read(num)
|
| 782 |
+
self.loc += len(out)
|
| 783 |
+
return out
|
| 784 |
+
|
| 785 |
+
read = sync_wrapper(_read)
|
| 786 |
+
|
| 787 |
+
async def _close(self):
|
| 788 |
+
self.r.close()
|
| 789 |
+
|
| 790 |
+
def close(self):
|
| 791 |
+
asyncio.run_coroutine_threadsafe(self._close(), self.loop)
|
| 792 |
+
super().close()
|
| 793 |
+
|
| 794 |
+
|
| 795 |
+
class AsyncStreamFile(AbstractAsyncStreamedFile):
|
| 796 |
+
def __init__(
|
| 797 |
+
self, fs, url, mode="rb", loop=None, session=None, size=None, **kwargs
|
| 798 |
+
):
|
| 799 |
+
self.url = url
|
| 800 |
+
self.session = session
|
| 801 |
+
self.r = None
|
| 802 |
+
if mode != "rb":
|
| 803 |
+
raise ValueError
|
| 804 |
+
self.details = {"name": url, "size": None}
|
| 805 |
+
self.kwargs = kwargs
|
| 806 |
+
super().__init__(fs=fs, path=url, mode=mode, cache_type="none")
|
| 807 |
+
self.size = size
|
| 808 |
+
|
| 809 |
+
async def read(self, num=-1):
|
| 810 |
+
if self.r is None:
|
| 811 |
+
r = await self.session.get(
|
| 812 |
+
self.fs.encode_url(self.url), **self.kwargs
|
| 813 |
+
).__aenter__()
|
| 814 |
+
self.fs._raise_not_found_for_status(r, self.url)
|
| 815 |
+
self.r = r
|
| 816 |
+
out = await self.r.content.read(num)
|
| 817 |
+
self.loc += len(out)
|
| 818 |
+
return out
|
| 819 |
+
|
| 820 |
+
async def close(self):
|
| 821 |
+
if self.r is not None:
|
| 822 |
+
self.r.close()
|
| 823 |
+
self.r = None
|
| 824 |
+
await super().close()
|
| 825 |
+
|
| 826 |
+
|
| 827 |
+
async def get_range(session, url, start, end, file=None, **kwargs):
|
| 828 |
+
# explicit get a range when we know it must be safe
|
| 829 |
+
kwargs = kwargs.copy()
|
| 830 |
+
headers = kwargs.pop("headers", {}).copy()
|
| 831 |
+
headers["Range"] = f"bytes={start}-{end - 1}"
|
| 832 |
+
r = await session.get(url, headers=headers, **kwargs)
|
| 833 |
+
r.raise_for_status()
|
| 834 |
+
async with r:
|
| 835 |
+
out = await r.read()
|
| 836 |
+
if file:
|
| 837 |
+
with open(file, "r+b") as f: # noqa: ASYNC230
|
| 838 |
+
f.seek(start)
|
| 839 |
+
f.write(out)
|
| 840 |
+
else:
|
| 841 |
+
return out
|
| 842 |
+
|
| 843 |
+
|
| 844 |
+
async def _file_info(url, session, size_policy="head", **kwargs):
|
| 845 |
+
"""Call HEAD on the server to get details about the file (size/checksum etc.)
|
| 846 |
+
|
| 847 |
+
Default operation is to explicitly allow redirects and use encoding
|
| 848 |
+
'identity' (no compression) to get the true size of the target.
|
| 849 |
+
"""
|
| 850 |
+
logger.debug("Retrieve file size for %s", url)
|
| 851 |
+
kwargs = kwargs.copy()
|
| 852 |
+
ar = kwargs.pop("allow_redirects", True)
|
| 853 |
+
head = kwargs.get("headers", {}).copy()
|
| 854 |
+
head["Accept-Encoding"] = "identity"
|
| 855 |
+
kwargs["headers"] = head
|
| 856 |
+
|
| 857 |
+
info = {}
|
| 858 |
+
if size_policy == "head":
|
| 859 |
+
r = await session.head(url, allow_redirects=ar, **kwargs)
|
| 860 |
+
elif size_policy == "get":
|
| 861 |
+
r = await session.get(url, allow_redirects=ar, **kwargs)
|
| 862 |
+
else:
|
| 863 |
+
raise TypeError(f'size_policy must be "head" or "get", got {size_policy}')
|
| 864 |
+
async with r:
|
| 865 |
+
r.raise_for_status()
|
| 866 |
+
|
| 867 |
+
if "Content-Length" in r.headers:
|
| 868 |
+
# Some servers may choose to ignore Accept-Encoding and return
|
| 869 |
+
# compressed content, in which case the returned size is unreliable.
|
| 870 |
+
if "Content-Encoding" not in r.headers or r.headers["Content-Encoding"] in [
|
| 871 |
+
"identity",
|
| 872 |
+
"",
|
| 873 |
+
]:
|
| 874 |
+
info["size"] = int(r.headers["Content-Length"])
|
| 875 |
+
elif "Content-Range" in r.headers:
|
| 876 |
+
info["size"] = int(r.headers["Content-Range"].split("/")[1])
|
| 877 |
+
|
| 878 |
+
if "Content-Type" in r.headers:
|
| 879 |
+
info["mimetype"] = r.headers["Content-Type"].partition(";")[0]
|
| 880 |
+
|
| 881 |
+
if r.headers.get("Accept-Ranges") == "none":
|
| 882 |
+
# Some servers may explicitly discourage partial content requests, but
|
| 883 |
+
# the lack of "Accept-Ranges" does not always indicate they would fail
|
| 884 |
+
info["partial"] = False
|
| 885 |
+
|
| 886 |
+
info["url"] = str(r.url)
|
| 887 |
+
|
| 888 |
+
for checksum_field in ["ETag", "Content-MD5", "Digest", "Last-Modified"]:
|
| 889 |
+
if r.headers.get(checksum_field):
|
| 890 |
+
info[checksum_field] = r.headers[checksum_field]
|
| 891 |
+
|
| 892 |
+
return info
|
| 893 |
+
|
| 894 |
+
|
| 895 |
+
async def _file_size(url, session=None, *args, **kwargs):
|
| 896 |
+
if session is None:
|
| 897 |
+
session = await get_client()
|
| 898 |
+
info = await _file_info(url, session=session, *args, **kwargs)
|
| 899 |
+
return info.get("size")
|
| 900 |
+
|
| 901 |
+
|
| 902 |
+
file_size = sync_wrapper(_file_size)
|
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/http_sync.py
ADDED
|
@@ -0,0 +1,937 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""This file is largely copied from http.py"""
|
| 2 |
+
|
| 3 |
+
import io
|
| 4 |
+
import logging
|
| 5 |
+
import re
|
| 6 |
+
import urllib.error
|
| 7 |
+
import urllib.parse
|
| 8 |
+
from copy import copy
|
| 9 |
+
from json import dumps, loads
|
| 10 |
+
from urllib.parse import urlparse
|
| 11 |
+
|
| 12 |
+
try:
|
| 13 |
+
import yarl
|
| 14 |
+
except (ImportError, ModuleNotFoundError, OSError):
|
| 15 |
+
yarl = False
|
| 16 |
+
|
| 17 |
+
from fsspec.callbacks import _DEFAULT_CALLBACK
|
| 18 |
+
from fsspec.registry import register_implementation
|
| 19 |
+
from fsspec.spec import AbstractBufferedFile, AbstractFileSystem
|
| 20 |
+
from fsspec.utils import DEFAULT_BLOCK_SIZE, isfilelike, nullcontext, tokenize
|
| 21 |
+
|
| 22 |
+
from ..caching import AllBytes
|
| 23 |
+
|
| 24 |
+
# https://stackoverflow.com/a/15926317/3821154
|
| 25 |
+
ex = re.compile(r"""<(a|A)\s+(?:[^>]*?\s+)?(href|HREF)=["'](?P<url>[^"']+)""")
|
| 26 |
+
ex2 = re.compile(r"""(?P<url>http[s]?://[-a-zA-Z0-9@:%_+.~#?&/=]+)""")
|
| 27 |
+
logger = logging.getLogger("fsspec.http")
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class JsHttpException(urllib.error.HTTPError): ...
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class StreamIO(io.BytesIO):
|
| 34 |
+
# fake class, so you can set attributes on it
|
| 35 |
+
# will eventually actually stream
|
| 36 |
+
...
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class ResponseProxy:
|
| 40 |
+
"""Looks like a requests response"""
|
| 41 |
+
|
| 42 |
+
def __init__(self, req, stream=False):
|
| 43 |
+
self.request = req
|
| 44 |
+
self.stream = stream
|
| 45 |
+
self._data = None
|
| 46 |
+
self._headers = None
|
| 47 |
+
|
| 48 |
+
@property
|
| 49 |
+
def raw(self):
|
| 50 |
+
if self._data is None:
|
| 51 |
+
b = self.request.response.to_bytes()
|
| 52 |
+
if self.stream:
|
| 53 |
+
self._data = StreamIO(b)
|
| 54 |
+
else:
|
| 55 |
+
self._data = b
|
| 56 |
+
return self._data
|
| 57 |
+
|
| 58 |
+
def close(self):
|
| 59 |
+
if hasattr(self, "_data"):
|
| 60 |
+
del self._data
|
| 61 |
+
|
| 62 |
+
@property
|
| 63 |
+
def headers(self):
|
| 64 |
+
if self._headers is None:
|
| 65 |
+
self._headers = dict(
|
| 66 |
+
[
|
| 67 |
+
_.split(": ")
|
| 68 |
+
for _ in self.request.getAllResponseHeaders().strip().split("\r\n")
|
| 69 |
+
]
|
| 70 |
+
)
|
| 71 |
+
return self._headers
|
| 72 |
+
|
| 73 |
+
@property
|
| 74 |
+
def status_code(self):
|
| 75 |
+
return int(self.request.status)
|
| 76 |
+
|
| 77 |
+
def raise_for_status(self):
|
| 78 |
+
if not self.ok:
|
| 79 |
+
raise JsHttpException(
|
| 80 |
+
self.url, self.status_code, self.reason, self.headers, None
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
def iter_content(self, chunksize, *_, **__):
|
| 84 |
+
while True:
|
| 85 |
+
out = self.raw.read(chunksize)
|
| 86 |
+
if out:
|
| 87 |
+
yield out
|
| 88 |
+
else:
|
| 89 |
+
break
|
| 90 |
+
|
| 91 |
+
@property
|
| 92 |
+
def reason(self):
|
| 93 |
+
return self.request.statusText
|
| 94 |
+
|
| 95 |
+
@property
|
| 96 |
+
def ok(self):
|
| 97 |
+
return self.status_code < 400
|
| 98 |
+
|
| 99 |
+
@property
|
| 100 |
+
def url(self):
|
| 101 |
+
return self.request.response.responseURL
|
| 102 |
+
|
| 103 |
+
@property
|
| 104 |
+
def text(self):
|
| 105 |
+
# TODO: encoding from headers
|
| 106 |
+
return self.content.decode()
|
| 107 |
+
|
| 108 |
+
@property
|
| 109 |
+
def content(self):
|
| 110 |
+
self.stream = False
|
| 111 |
+
return self.raw
|
| 112 |
+
|
| 113 |
+
def json(self):
|
| 114 |
+
return loads(self.text)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
class RequestsSessionShim:
|
| 118 |
+
def __init__(self):
|
| 119 |
+
self.headers = {}
|
| 120 |
+
|
| 121 |
+
def request(
|
| 122 |
+
self,
|
| 123 |
+
method,
|
| 124 |
+
url,
|
| 125 |
+
params=None,
|
| 126 |
+
data=None,
|
| 127 |
+
headers=None,
|
| 128 |
+
cookies=None,
|
| 129 |
+
files=None,
|
| 130 |
+
auth=None,
|
| 131 |
+
timeout=None,
|
| 132 |
+
allow_redirects=None,
|
| 133 |
+
proxies=None,
|
| 134 |
+
hooks=None,
|
| 135 |
+
stream=None,
|
| 136 |
+
verify=None,
|
| 137 |
+
cert=None,
|
| 138 |
+
json=None,
|
| 139 |
+
):
|
| 140 |
+
from js import Blob, XMLHttpRequest
|
| 141 |
+
|
| 142 |
+
logger.debug("JS request: %s %s", method, url)
|
| 143 |
+
|
| 144 |
+
if cert or verify or proxies or files or cookies or hooks:
|
| 145 |
+
raise NotImplementedError
|
| 146 |
+
if data and json:
|
| 147 |
+
raise ValueError("Use json= or data=, not both")
|
| 148 |
+
req = XMLHttpRequest.new()
|
| 149 |
+
extra = auth if auth else ()
|
| 150 |
+
if params:
|
| 151 |
+
url = f"{url}?{urllib.parse.urlencode(params)}"
|
| 152 |
+
req.open(method, url, False, *extra)
|
| 153 |
+
if timeout:
|
| 154 |
+
req.timeout = timeout
|
| 155 |
+
if headers:
|
| 156 |
+
for k, v in headers.items():
|
| 157 |
+
req.setRequestHeader(k, v)
|
| 158 |
+
|
| 159 |
+
req.setRequestHeader("Accept", "application/octet-stream")
|
| 160 |
+
req.responseType = "arraybuffer"
|
| 161 |
+
if json:
|
| 162 |
+
blob = Blob.new([dumps(data)], {type: "application/json"})
|
| 163 |
+
req.send(blob)
|
| 164 |
+
elif data:
|
| 165 |
+
if isinstance(data, io.IOBase):
|
| 166 |
+
data = data.read()
|
| 167 |
+
blob = Blob.new([data], {type: "application/octet-stream"})
|
| 168 |
+
req.send(blob)
|
| 169 |
+
else:
|
| 170 |
+
req.send(None)
|
| 171 |
+
return ResponseProxy(req, stream=stream)
|
| 172 |
+
|
| 173 |
+
def get(self, url, **kwargs):
|
| 174 |
+
return self.request("GET", url, **kwargs)
|
| 175 |
+
|
| 176 |
+
def head(self, url, **kwargs):
|
| 177 |
+
return self.request("HEAD", url, **kwargs)
|
| 178 |
+
|
| 179 |
+
def post(self, url, **kwargs):
|
| 180 |
+
return self.request("POST}", url, **kwargs)
|
| 181 |
+
|
| 182 |
+
def put(self, url, **kwargs):
|
| 183 |
+
return self.request("PUT", url, **kwargs)
|
| 184 |
+
|
| 185 |
+
def patch(self, url, **kwargs):
|
| 186 |
+
return self.request("PATCH", url, **kwargs)
|
| 187 |
+
|
| 188 |
+
def delete(self, url, **kwargs):
|
| 189 |
+
return self.request("DELETE", url, **kwargs)
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
class HTTPFileSystem(AbstractFileSystem):
|
| 193 |
+
"""
|
| 194 |
+
Simple File-System for fetching data via HTTP(S)
|
| 195 |
+
|
| 196 |
+
This is the BLOCKING version of the normal HTTPFileSystem. It uses
|
| 197 |
+
requests in normal python and the JS runtime in pyodide.
|
| 198 |
+
|
| 199 |
+
***This implementation is extremely experimental, do not use unless
|
| 200 |
+
you are testing pyodide/pyscript integration***
|
| 201 |
+
"""
|
| 202 |
+
|
| 203 |
+
protocol = ("http", "https", "sync-http", "sync-https")
|
| 204 |
+
sep = "/"
|
| 205 |
+
|
| 206 |
+
def __init__(
|
| 207 |
+
self,
|
| 208 |
+
simple_links=True,
|
| 209 |
+
block_size=None,
|
| 210 |
+
same_scheme=True,
|
| 211 |
+
cache_type="readahead",
|
| 212 |
+
cache_options=None,
|
| 213 |
+
client_kwargs=None,
|
| 214 |
+
encoded=False,
|
| 215 |
+
**storage_options,
|
| 216 |
+
):
|
| 217 |
+
"""
|
| 218 |
+
|
| 219 |
+
Parameters
|
| 220 |
+
----------
|
| 221 |
+
block_size: int
|
| 222 |
+
Blocks to read bytes; if 0, will default to raw requests file-like
|
| 223 |
+
objects instead of HTTPFile instances
|
| 224 |
+
simple_links: bool
|
| 225 |
+
If True, will consider both HTML <a> tags and anything that looks
|
| 226 |
+
like a URL; if False, will consider only the former.
|
| 227 |
+
same_scheme: True
|
| 228 |
+
When doing ls/glob, if this is True, only consider paths that have
|
| 229 |
+
http/https matching the input URLs.
|
| 230 |
+
size_policy: this argument is deprecated
|
| 231 |
+
client_kwargs: dict
|
| 232 |
+
Passed to aiohttp.ClientSession, see
|
| 233 |
+
https://docs.aiohttp.org/en/stable/client_reference.html
|
| 234 |
+
For example, ``{'auth': aiohttp.BasicAuth('user', 'pass')}``
|
| 235 |
+
storage_options: key-value
|
| 236 |
+
Any other parameters passed on to requests
|
| 237 |
+
cache_type, cache_options: defaults used in open
|
| 238 |
+
"""
|
| 239 |
+
super().__init__(self, **storage_options)
|
| 240 |
+
self.block_size = block_size if block_size is not None else DEFAULT_BLOCK_SIZE
|
| 241 |
+
self.simple_links = simple_links
|
| 242 |
+
self.same_schema = same_scheme
|
| 243 |
+
self.cache_type = cache_type
|
| 244 |
+
self.cache_options = cache_options
|
| 245 |
+
self.client_kwargs = client_kwargs or {}
|
| 246 |
+
self.encoded = encoded
|
| 247 |
+
self.kwargs = storage_options
|
| 248 |
+
|
| 249 |
+
try:
|
| 250 |
+
import js # noqa: F401
|
| 251 |
+
|
| 252 |
+
logger.debug("Starting JS session")
|
| 253 |
+
self.session = RequestsSessionShim()
|
| 254 |
+
self.js = True
|
| 255 |
+
except Exception as e:
|
| 256 |
+
import requests
|
| 257 |
+
|
| 258 |
+
logger.debug("Starting cpython session because of: %s", e)
|
| 259 |
+
self.session = requests.Session(**(client_kwargs or {}))
|
| 260 |
+
self.js = False
|
| 261 |
+
|
| 262 |
+
request_options = copy(storage_options)
|
| 263 |
+
self.use_listings_cache = request_options.pop("use_listings_cache", False)
|
| 264 |
+
request_options.pop("listings_expiry_time", None)
|
| 265 |
+
request_options.pop("max_paths", None)
|
| 266 |
+
request_options.pop("skip_instance_cache", None)
|
| 267 |
+
self.kwargs = request_options
|
| 268 |
+
|
| 269 |
+
@property
|
| 270 |
+
def fsid(self):
|
| 271 |
+
return "sync-http"
|
| 272 |
+
|
| 273 |
+
def encode_url(self, url):
|
| 274 |
+
if yarl:
|
| 275 |
+
return yarl.URL(url, encoded=self.encoded)
|
| 276 |
+
return url
|
| 277 |
+
|
| 278 |
+
@classmethod
|
| 279 |
+
def _strip_protocol(cls, path: str) -> str:
|
| 280 |
+
"""For HTTP, we always want to keep the full URL"""
|
| 281 |
+
path = path.replace("sync-http://", "http://").replace(
|
| 282 |
+
"sync-https://", "https://"
|
| 283 |
+
)
|
| 284 |
+
return path
|
| 285 |
+
|
| 286 |
+
@classmethod
|
| 287 |
+
def _parent(cls, path):
|
| 288 |
+
# override, since _strip_protocol is different for URLs
|
| 289 |
+
par = super()._parent(path)
|
| 290 |
+
if len(par) > 7: # "http://..."
|
| 291 |
+
return par
|
| 292 |
+
return ""
|
| 293 |
+
|
| 294 |
+
def _ls_real(self, url, detail=True, **kwargs):
|
| 295 |
+
# ignoring URL-encoded arguments
|
| 296 |
+
kw = self.kwargs.copy()
|
| 297 |
+
kw.update(kwargs)
|
| 298 |
+
logger.debug(url)
|
| 299 |
+
r = self.session.get(self.encode_url(url), **self.kwargs)
|
| 300 |
+
self._raise_not_found_for_status(r, url)
|
| 301 |
+
text = r.text
|
| 302 |
+
if self.simple_links:
|
| 303 |
+
links = ex2.findall(text) + [u[2] for u in ex.findall(text)]
|
| 304 |
+
else:
|
| 305 |
+
links = [u[2] for u in ex.findall(text)]
|
| 306 |
+
out = set()
|
| 307 |
+
parts = urlparse(url)
|
| 308 |
+
for l in links:
|
| 309 |
+
if isinstance(l, tuple):
|
| 310 |
+
l = l[1]
|
| 311 |
+
if l.startswith("/") and len(l) > 1:
|
| 312 |
+
# absolute URL on this server
|
| 313 |
+
l = parts.scheme + "://" + parts.netloc + l
|
| 314 |
+
if l.startswith("http"):
|
| 315 |
+
if self.same_schema and l.startswith(url.rstrip("/") + "/"):
|
| 316 |
+
out.add(l)
|
| 317 |
+
elif l.replace("https", "http").startswith(
|
| 318 |
+
url.replace("https", "http").rstrip("/") + "/"
|
| 319 |
+
):
|
| 320 |
+
# allowed to cross http <-> https
|
| 321 |
+
out.add(l)
|
| 322 |
+
else:
|
| 323 |
+
if l not in ["..", "../"]:
|
| 324 |
+
# Ignore FTP-like "parent"
|
| 325 |
+
out.add("/".join([url.rstrip("/"), l.lstrip("/")]))
|
| 326 |
+
if not out and url.endswith("/"):
|
| 327 |
+
out = self._ls_real(url.rstrip("/"), detail=False)
|
| 328 |
+
if detail:
|
| 329 |
+
return [
|
| 330 |
+
{
|
| 331 |
+
"name": u,
|
| 332 |
+
"size": None,
|
| 333 |
+
"type": "directory" if u.endswith("/") else "file",
|
| 334 |
+
}
|
| 335 |
+
for u in out
|
| 336 |
+
]
|
| 337 |
+
else:
|
| 338 |
+
return sorted(out)
|
| 339 |
+
|
| 340 |
+
def ls(self, url, detail=True, **kwargs):
|
| 341 |
+
if self.use_listings_cache and url in self.dircache:
|
| 342 |
+
out = self.dircache[url]
|
| 343 |
+
else:
|
| 344 |
+
out = self._ls_real(url, detail=detail, **kwargs)
|
| 345 |
+
self.dircache[url] = out
|
| 346 |
+
return out
|
| 347 |
+
|
| 348 |
+
def _raise_not_found_for_status(self, response, url):
|
| 349 |
+
"""
|
| 350 |
+
Raises FileNotFoundError for 404s, otherwise uses raise_for_status.
|
| 351 |
+
"""
|
| 352 |
+
if response.status_code == 404:
|
| 353 |
+
raise FileNotFoundError(url)
|
| 354 |
+
response.raise_for_status()
|
| 355 |
+
|
| 356 |
+
def cat_file(self, url, start=None, end=None, **kwargs):
|
| 357 |
+
kw = self.kwargs.copy()
|
| 358 |
+
kw.update(kwargs)
|
| 359 |
+
logger.debug(url)
|
| 360 |
+
|
| 361 |
+
if start is not None or end is not None:
|
| 362 |
+
if start == end:
|
| 363 |
+
return b""
|
| 364 |
+
headers = kw.pop("headers", {}).copy()
|
| 365 |
+
|
| 366 |
+
headers["Range"] = self._process_limits(url, start, end)
|
| 367 |
+
kw["headers"] = headers
|
| 368 |
+
r = self.session.get(self.encode_url(url), **kw)
|
| 369 |
+
self._raise_not_found_for_status(r, url)
|
| 370 |
+
return r.content
|
| 371 |
+
|
| 372 |
+
def get_file(
|
| 373 |
+
self, rpath, lpath, chunk_size=5 * 2**20, callback=_DEFAULT_CALLBACK, **kwargs
|
| 374 |
+
):
|
| 375 |
+
kw = self.kwargs.copy()
|
| 376 |
+
kw.update(kwargs)
|
| 377 |
+
logger.debug(rpath)
|
| 378 |
+
r = self.session.get(self.encode_url(rpath), **kw)
|
| 379 |
+
try:
|
| 380 |
+
size = int(
|
| 381 |
+
r.headers.get("content-length", None)
|
| 382 |
+
or r.headers.get("Content-Length", None)
|
| 383 |
+
)
|
| 384 |
+
except (ValueError, KeyError, TypeError):
|
| 385 |
+
size = None
|
| 386 |
+
|
| 387 |
+
callback.set_size(size)
|
| 388 |
+
self._raise_not_found_for_status(r, rpath)
|
| 389 |
+
if not isfilelike(lpath):
|
| 390 |
+
lpath = open(lpath, "wb")
|
| 391 |
+
for chunk in r.iter_content(chunk_size, decode_unicode=False):
|
| 392 |
+
lpath.write(chunk)
|
| 393 |
+
callback.relative_update(len(chunk))
|
| 394 |
+
|
| 395 |
+
def put_file(
|
| 396 |
+
self,
|
| 397 |
+
lpath,
|
| 398 |
+
rpath,
|
| 399 |
+
chunk_size=5 * 2**20,
|
| 400 |
+
callback=_DEFAULT_CALLBACK,
|
| 401 |
+
method="post",
|
| 402 |
+
**kwargs,
|
| 403 |
+
):
|
| 404 |
+
def gen_chunks():
|
| 405 |
+
# Support passing arbitrary file-like objects
|
| 406 |
+
# and use them instead of streams.
|
| 407 |
+
if isinstance(lpath, io.IOBase):
|
| 408 |
+
context = nullcontext(lpath)
|
| 409 |
+
use_seek = False # might not support seeking
|
| 410 |
+
else:
|
| 411 |
+
context = open(lpath, "rb")
|
| 412 |
+
use_seek = True
|
| 413 |
+
|
| 414 |
+
with context as f:
|
| 415 |
+
if use_seek:
|
| 416 |
+
callback.set_size(f.seek(0, 2))
|
| 417 |
+
f.seek(0)
|
| 418 |
+
else:
|
| 419 |
+
callback.set_size(getattr(f, "size", None))
|
| 420 |
+
|
| 421 |
+
chunk = f.read(chunk_size)
|
| 422 |
+
while chunk:
|
| 423 |
+
yield chunk
|
| 424 |
+
callback.relative_update(len(chunk))
|
| 425 |
+
chunk = f.read(chunk_size)
|
| 426 |
+
|
| 427 |
+
kw = self.kwargs.copy()
|
| 428 |
+
kw.update(kwargs)
|
| 429 |
+
|
| 430 |
+
method = method.lower()
|
| 431 |
+
if method not in ("post", "put"):
|
| 432 |
+
raise ValueError(
|
| 433 |
+
f"method has to be either 'post' or 'put', not: {method!r}"
|
| 434 |
+
)
|
| 435 |
+
|
| 436 |
+
meth = getattr(self.session, method)
|
| 437 |
+
resp = meth(rpath, data=gen_chunks(), **kw)
|
| 438 |
+
self._raise_not_found_for_status(resp, rpath)
|
| 439 |
+
|
| 440 |
+
def _process_limits(self, url, start, end):
|
| 441 |
+
"""Helper for "Range"-based _cat_file"""
|
| 442 |
+
size = None
|
| 443 |
+
suff = False
|
| 444 |
+
if start is not None and start < 0:
|
| 445 |
+
# if start is negative and end None, end is the "suffix length"
|
| 446 |
+
if end is None:
|
| 447 |
+
end = -start
|
| 448 |
+
start = ""
|
| 449 |
+
suff = True
|
| 450 |
+
else:
|
| 451 |
+
size = size or self.info(url)["size"]
|
| 452 |
+
start = size + start
|
| 453 |
+
elif start is None:
|
| 454 |
+
start = 0
|
| 455 |
+
if not suff:
|
| 456 |
+
if end is not None and end < 0:
|
| 457 |
+
if start is not None:
|
| 458 |
+
size = size or self.info(url)["size"]
|
| 459 |
+
end = size + end
|
| 460 |
+
elif end is None:
|
| 461 |
+
end = ""
|
| 462 |
+
if isinstance(end, int):
|
| 463 |
+
end -= 1 # bytes range is inclusive
|
| 464 |
+
return f"bytes={start}-{end}"
|
| 465 |
+
|
| 466 |
+
def exists(self, path, strict=False, **kwargs):
|
| 467 |
+
kw = self.kwargs.copy()
|
| 468 |
+
kw.update(kwargs)
|
| 469 |
+
try:
|
| 470 |
+
logger.debug(path)
|
| 471 |
+
r = self.session.get(self.encode_url(path), **kw)
|
| 472 |
+
if strict:
|
| 473 |
+
self._raise_not_found_for_status(r, path)
|
| 474 |
+
return r.status_code < 400
|
| 475 |
+
except FileNotFoundError:
|
| 476 |
+
return False
|
| 477 |
+
except Exception:
|
| 478 |
+
if strict:
|
| 479 |
+
raise
|
| 480 |
+
return False
|
| 481 |
+
|
| 482 |
+
def isfile(self, path, **kwargs):
|
| 483 |
+
return self.exists(path, **kwargs)
|
| 484 |
+
|
| 485 |
+
def _open(
|
| 486 |
+
self,
|
| 487 |
+
path,
|
| 488 |
+
mode="rb",
|
| 489 |
+
block_size=None,
|
| 490 |
+
autocommit=None, # XXX: This differs from the base class.
|
| 491 |
+
cache_type=None,
|
| 492 |
+
cache_options=None,
|
| 493 |
+
size=None,
|
| 494 |
+
**kwargs,
|
| 495 |
+
):
|
| 496 |
+
"""Make a file-like object
|
| 497 |
+
|
| 498 |
+
Parameters
|
| 499 |
+
----------
|
| 500 |
+
path: str
|
| 501 |
+
Full URL with protocol
|
| 502 |
+
mode: string
|
| 503 |
+
must be "rb"
|
| 504 |
+
block_size: int or None
|
| 505 |
+
Bytes to download in one request; use instance value if None. If
|
| 506 |
+
zero, will return a streaming Requests file-like instance.
|
| 507 |
+
kwargs: key-value
|
| 508 |
+
Any other parameters, passed to requests calls
|
| 509 |
+
"""
|
| 510 |
+
if mode != "rb":
|
| 511 |
+
raise NotImplementedError
|
| 512 |
+
block_size = block_size if block_size is not None else self.block_size
|
| 513 |
+
kw = self.kwargs.copy()
|
| 514 |
+
kw.update(kwargs)
|
| 515 |
+
size = size or self.info(path, **kwargs)["size"]
|
| 516 |
+
if block_size and size:
|
| 517 |
+
return HTTPFile(
|
| 518 |
+
self,
|
| 519 |
+
path,
|
| 520 |
+
session=self.session,
|
| 521 |
+
block_size=block_size,
|
| 522 |
+
mode=mode,
|
| 523 |
+
size=size,
|
| 524 |
+
cache_type=cache_type or self.cache_type,
|
| 525 |
+
cache_options=cache_options or self.cache_options,
|
| 526 |
+
**kw,
|
| 527 |
+
)
|
| 528 |
+
else:
|
| 529 |
+
return HTTPStreamFile(
|
| 530 |
+
self,
|
| 531 |
+
path,
|
| 532 |
+
mode=mode,
|
| 533 |
+
session=self.session,
|
| 534 |
+
**kw,
|
| 535 |
+
)
|
| 536 |
+
|
| 537 |
+
def ukey(self, url):
|
| 538 |
+
"""Unique identifier; assume HTTP files are static, unchanging"""
|
| 539 |
+
return tokenize(url, self.kwargs, self.protocol)
|
| 540 |
+
|
| 541 |
+
def info(self, url, **kwargs):
|
| 542 |
+
"""Get info of URL
|
| 543 |
+
|
| 544 |
+
Tries to access location via HEAD, and then GET methods, but does
|
| 545 |
+
not fetch the data.
|
| 546 |
+
|
| 547 |
+
It is possible that the server does not supply any size information, in
|
| 548 |
+
which case size will be given as None (and certain operations on the
|
| 549 |
+
corresponding file will not work).
|
| 550 |
+
"""
|
| 551 |
+
info = {}
|
| 552 |
+
for policy in ["head", "get"]:
|
| 553 |
+
try:
|
| 554 |
+
info.update(
|
| 555 |
+
_file_info(
|
| 556 |
+
self.encode_url(url),
|
| 557 |
+
size_policy=policy,
|
| 558 |
+
session=self.session,
|
| 559 |
+
**self.kwargs,
|
| 560 |
+
**kwargs,
|
| 561 |
+
)
|
| 562 |
+
)
|
| 563 |
+
if info.get("size") is not None:
|
| 564 |
+
break
|
| 565 |
+
except Exception as exc:
|
| 566 |
+
if policy == "get":
|
| 567 |
+
# If get failed, then raise a FileNotFoundError
|
| 568 |
+
raise FileNotFoundError(url) from exc
|
| 569 |
+
logger.debug(str(exc))
|
| 570 |
+
|
| 571 |
+
return {"name": url, "size": None, **info, "type": "file"}
|
| 572 |
+
|
| 573 |
+
def glob(self, path, maxdepth=None, **kwargs):
|
| 574 |
+
"""
|
| 575 |
+
Find files by glob-matching.
|
| 576 |
+
|
| 577 |
+
This implementation is idntical to the one in AbstractFileSystem,
|
| 578 |
+
but "?" is not considered as a character for globbing, because it is
|
| 579 |
+
so common in URLs, often identifying the "query" part.
|
| 580 |
+
"""
|
| 581 |
+
import re
|
| 582 |
+
|
| 583 |
+
ends = path.endswith("/")
|
| 584 |
+
path = self._strip_protocol(path)
|
| 585 |
+
indstar = path.find("*") if path.find("*") >= 0 else len(path)
|
| 586 |
+
indbrace = path.find("[") if path.find("[") >= 0 else len(path)
|
| 587 |
+
|
| 588 |
+
ind = min(indstar, indbrace)
|
| 589 |
+
|
| 590 |
+
detail = kwargs.pop("detail", False)
|
| 591 |
+
|
| 592 |
+
if not has_magic(path):
|
| 593 |
+
root = path
|
| 594 |
+
depth = 1
|
| 595 |
+
if ends:
|
| 596 |
+
path += "/*"
|
| 597 |
+
elif self.exists(path):
|
| 598 |
+
if not detail:
|
| 599 |
+
return [path]
|
| 600 |
+
else:
|
| 601 |
+
return {path: self.info(path)}
|
| 602 |
+
else:
|
| 603 |
+
if not detail:
|
| 604 |
+
return [] # glob of non-existent returns empty
|
| 605 |
+
else:
|
| 606 |
+
return {}
|
| 607 |
+
elif "/" in path[:ind]:
|
| 608 |
+
ind2 = path[:ind].rindex("/")
|
| 609 |
+
root = path[: ind2 + 1]
|
| 610 |
+
depth = None if "**" in path else path[ind2 + 1 :].count("/") + 1
|
| 611 |
+
else:
|
| 612 |
+
root = ""
|
| 613 |
+
depth = None if "**" in path else path[ind + 1 :].count("/") + 1
|
| 614 |
+
|
| 615 |
+
allpaths = self.find(
|
| 616 |
+
root, maxdepth=maxdepth or depth, withdirs=True, detail=True, **kwargs
|
| 617 |
+
)
|
| 618 |
+
# Escape characters special to python regex, leaving our supported
|
| 619 |
+
# special characters in place.
|
| 620 |
+
# See https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html
|
| 621 |
+
# for shell globbing details.
|
| 622 |
+
pattern = (
|
| 623 |
+
"^"
|
| 624 |
+
+ (
|
| 625 |
+
path.replace("\\", r"\\")
|
| 626 |
+
.replace(".", r"\.")
|
| 627 |
+
.replace("+", r"\+")
|
| 628 |
+
.replace("//", "/")
|
| 629 |
+
.replace("(", r"\(")
|
| 630 |
+
.replace(")", r"\)")
|
| 631 |
+
.replace("|", r"\|")
|
| 632 |
+
.replace("^", r"\^")
|
| 633 |
+
.replace("$", r"\$")
|
| 634 |
+
.replace("{", r"\{")
|
| 635 |
+
.replace("}", r"\}")
|
| 636 |
+
.rstrip("/")
|
| 637 |
+
)
|
| 638 |
+
+ "$"
|
| 639 |
+
)
|
| 640 |
+
pattern = re.sub("[*]{2}", "=PLACEHOLDER=", pattern)
|
| 641 |
+
pattern = re.sub("[*]", "[^/]*", pattern)
|
| 642 |
+
pattern = re.compile(pattern.replace("=PLACEHOLDER=", ".*"))
|
| 643 |
+
out = {
|
| 644 |
+
p: allpaths[p]
|
| 645 |
+
for p in sorted(allpaths)
|
| 646 |
+
if pattern.match(p.replace("//", "/").rstrip("/"))
|
| 647 |
+
}
|
| 648 |
+
if detail:
|
| 649 |
+
return out
|
| 650 |
+
else:
|
| 651 |
+
return list(out)
|
| 652 |
+
|
| 653 |
+
def isdir(self, path):
|
| 654 |
+
# override, since all URLs are (also) files
|
| 655 |
+
try:
|
| 656 |
+
return bool(self.ls(path))
|
| 657 |
+
except (FileNotFoundError, ValueError):
|
| 658 |
+
return False
|
| 659 |
+
|
| 660 |
+
|
| 661 |
+
class HTTPFile(AbstractBufferedFile):
|
| 662 |
+
"""
|
| 663 |
+
A file-like object pointing to a remove HTTP(S) resource
|
| 664 |
+
|
| 665 |
+
Supports only reading, with read-ahead of a predermined block-size.
|
| 666 |
+
|
| 667 |
+
In the case that the server does not supply the filesize, only reading of
|
| 668 |
+
the complete file in one go is supported.
|
| 669 |
+
|
| 670 |
+
Parameters
|
| 671 |
+
----------
|
| 672 |
+
url: str
|
| 673 |
+
Full URL of the remote resource, including the protocol
|
| 674 |
+
session: requests.Session or None
|
| 675 |
+
All calls will be made within this session, to avoid restarting
|
| 676 |
+
connections where the server allows this
|
| 677 |
+
block_size: int or None
|
| 678 |
+
The amount of read-ahead to do, in bytes. Default is 5MB, or the value
|
| 679 |
+
configured for the FileSystem creating this file
|
| 680 |
+
size: None or int
|
| 681 |
+
If given, this is the size of the file in bytes, and we don't attempt
|
| 682 |
+
to call the server to find the value.
|
| 683 |
+
kwargs: all other key-values are passed to requests calls.
|
| 684 |
+
"""
|
| 685 |
+
|
| 686 |
+
def __init__(
|
| 687 |
+
self,
|
| 688 |
+
fs,
|
| 689 |
+
url,
|
| 690 |
+
session=None,
|
| 691 |
+
block_size=None,
|
| 692 |
+
mode="rb",
|
| 693 |
+
cache_type="bytes",
|
| 694 |
+
cache_options=None,
|
| 695 |
+
size=None,
|
| 696 |
+
**kwargs,
|
| 697 |
+
):
|
| 698 |
+
if mode != "rb":
|
| 699 |
+
raise NotImplementedError("File mode not supported")
|
| 700 |
+
self.url = url
|
| 701 |
+
self.session = session
|
| 702 |
+
self.details = {"name": url, "size": size, "type": "file"}
|
| 703 |
+
super().__init__(
|
| 704 |
+
fs=fs,
|
| 705 |
+
path=url,
|
| 706 |
+
mode=mode,
|
| 707 |
+
block_size=block_size,
|
| 708 |
+
cache_type=cache_type,
|
| 709 |
+
cache_options=cache_options,
|
| 710 |
+
**kwargs,
|
| 711 |
+
)
|
| 712 |
+
|
| 713 |
+
def read(self, length=-1):
|
| 714 |
+
"""Read bytes from file
|
| 715 |
+
|
| 716 |
+
Parameters
|
| 717 |
+
----------
|
| 718 |
+
length: int
|
| 719 |
+
Read up to this many bytes. If negative, read all content to end of
|
| 720 |
+
file. If the server has not supplied the filesize, attempting to
|
| 721 |
+
read only part of the data will raise a ValueError.
|
| 722 |
+
"""
|
| 723 |
+
if (
|
| 724 |
+
(length < 0 and self.loc == 0) # explicit read all
|
| 725 |
+
# but not when the size is known and fits into a block anyways
|
| 726 |
+
and not (self.size is not None and self.size <= self.blocksize)
|
| 727 |
+
):
|
| 728 |
+
self._fetch_all()
|
| 729 |
+
if self.size is None:
|
| 730 |
+
if length < 0:
|
| 731 |
+
self._fetch_all()
|
| 732 |
+
else:
|
| 733 |
+
length = min(self.size - self.loc, length)
|
| 734 |
+
return super().read(length)
|
| 735 |
+
|
| 736 |
+
def _fetch_all(self):
|
| 737 |
+
"""Read whole file in one shot, without caching
|
| 738 |
+
|
| 739 |
+
This is only called when position is still at zero,
|
| 740 |
+
and read() is called without a byte-count.
|
| 741 |
+
"""
|
| 742 |
+
logger.debug(f"Fetch all for {self}")
|
| 743 |
+
if not isinstance(self.cache, AllBytes):
|
| 744 |
+
r = self.session.get(self.fs.encode_url(self.url), **self.kwargs)
|
| 745 |
+
r.raise_for_status()
|
| 746 |
+
out = r.content
|
| 747 |
+
self.cache = AllBytes(size=len(out), fetcher=None, blocksize=None, data=out)
|
| 748 |
+
self.size = len(out)
|
| 749 |
+
|
| 750 |
+
def _parse_content_range(self, headers):
|
| 751 |
+
"""Parse the Content-Range header"""
|
| 752 |
+
s = headers.get("Content-Range", "")
|
| 753 |
+
m = re.match(r"bytes (\d+-\d+|\*)/(\d+|\*)", s)
|
| 754 |
+
if not m:
|
| 755 |
+
return None, None, None
|
| 756 |
+
|
| 757 |
+
if m[1] == "*":
|
| 758 |
+
start = end = None
|
| 759 |
+
else:
|
| 760 |
+
start, end = [int(x) for x in m[1].split("-")]
|
| 761 |
+
total = None if m[2] == "*" else int(m[2])
|
| 762 |
+
return start, end, total
|
| 763 |
+
|
| 764 |
+
def _fetch_range(self, start, end):
|
| 765 |
+
"""Download a block of data
|
| 766 |
+
|
| 767 |
+
The expectation is that the server returns only the requested bytes,
|
| 768 |
+
with HTTP code 206. If this is not the case, we first check the headers,
|
| 769 |
+
and then stream the output - if the data size is bigger than we
|
| 770 |
+
requested, an exception is raised.
|
| 771 |
+
"""
|
| 772 |
+
logger.debug(f"Fetch range for {self}: {start}-{end}")
|
| 773 |
+
kwargs = self.kwargs.copy()
|
| 774 |
+
headers = kwargs.pop("headers", {}).copy()
|
| 775 |
+
headers["Range"] = f"bytes={start}-{end - 1}"
|
| 776 |
+
logger.debug("%s : %s", self.url, headers["Range"])
|
| 777 |
+
r = self.session.get(self.fs.encode_url(self.url), headers=headers, **kwargs)
|
| 778 |
+
if r.status_code == 416:
|
| 779 |
+
# range request outside file
|
| 780 |
+
return b""
|
| 781 |
+
r.raise_for_status()
|
| 782 |
+
|
| 783 |
+
# If the server has handled the range request, it should reply
|
| 784 |
+
# with status 206 (partial content). But we'll guess that a suitable
|
| 785 |
+
# Content-Range header or a Content-Length no more than the
|
| 786 |
+
# requested range also mean we have got the desired range.
|
| 787 |
+
cl = r.headers.get("Content-Length", r.headers.get("content-length", end + 1))
|
| 788 |
+
response_is_range = (
|
| 789 |
+
r.status_code == 206
|
| 790 |
+
or self._parse_content_range(r.headers)[0] == start
|
| 791 |
+
or int(cl) <= end - start
|
| 792 |
+
)
|
| 793 |
+
|
| 794 |
+
if response_is_range:
|
| 795 |
+
# partial content, as expected
|
| 796 |
+
out = r.content
|
| 797 |
+
elif start > 0:
|
| 798 |
+
raise ValueError(
|
| 799 |
+
"The HTTP server doesn't appear to support range requests. "
|
| 800 |
+
"Only reading this file from the beginning is supported. "
|
| 801 |
+
"Open with block_size=0 for a streaming file interface."
|
| 802 |
+
)
|
| 803 |
+
else:
|
| 804 |
+
# Response is not a range, but we want the start of the file,
|
| 805 |
+
# so we can read the required amount anyway.
|
| 806 |
+
cl = 0
|
| 807 |
+
out = []
|
| 808 |
+
for chunk in r.iter_content(2**20, False):
|
| 809 |
+
out.append(chunk)
|
| 810 |
+
cl += len(chunk)
|
| 811 |
+
out = b"".join(out)[: end - start]
|
| 812 |
+
return out
|
| 813 |
+
|
| 814 |
+
|
| 815 |
+
magic_check = re.compile("([*[])")
|
| 816 |
+
|
| 817 |
+
|
| 818 |
+
def has_magic(s):
|
| 819 |
+
match = magic_check.search(s)
|
| 820 |
+
return match is not None
|
| 821 |
+
|
| 822 |
+
|
| 823 |
+
class HTTPStreamFile(AbstractBufferedFile):
|
| 824 |
+
def __init__(self, fs, url, mode="rb", session=None, **kwargs):
|
| 825 |
+
self.url = url
|
| 826 |
+
self.session = session
|
| 827 |
+
if mode != "rb":
|
| 828 |
+
raise ValueError
|
| 829 |
+
self.details = {"name": url, "size": None}
|
| 830 |
+
super().__init__(fs=fs, path=url, mode=mode, cache_type="readahead", **kwargs)
|
| 831 |
+
|
| 832 |
+
r = self.session.get(self.fs.encode_url(url), stream=True, **kwargs)
|
| 833 |
+
self.fs._raise_not_found_for_status(r, url)
|
| 834 |
+
self.it = r.iter_content(1024, False)
|
| 835 |
+
self.leftover = b""
|
| 836 |
+
|
| 837 |
+
self.r = r
|
| 838 |
+
|
| 839 |
+
def seek(self, *args, **kwargs):
|
| 840 |
+
raise ValueError("Cannot seek streaming HTTP file")
|
| 841 |
+
|
| 842 |
+
def read(self, num=-1):
|
| 843 |
+
bufs = [self.leftover]
|
| 844 |
+
leng = len(self.leftover)
|
| 845 |
+
while leng < num or num < 0:
|
| 846 |
+
try:
|
| 847 |
+
out = self.it.__next__()
|
| 848 |
+
except StopIteration:
|
| 849 |
+
break
|
| 850 |
+
if out:
|
| 851 |
+
bufs.append(out)
|
| 852 |
+
else:
|
| 853 |
+
break
|
| 854 |
+
leng += len(out)
|
| 855 |
+
out = b"".join(bufs)
|
| 856 |
+
if num >= 0:
|
| 857 |
+
self.leftover = out[num:]
|
| 858 |
+
out = out[:num]
|
| 859 |
+
else:
|
| 860 |
+
self.leftover = b""
|
| 861 |
+
self.loc += len(out)
|
| 862 |
+
return out
|
| 863 |
+
|
| 864 |
+
def close(self):
|
| 865 |
+
self.r.close()
|
| 866 |
+
self.closed = True
|
| 867 |
+
|
| 868 |
+
|
| 869 |
+
def get_range(session, url, start, end, **kwargs):
|
| 870 |
+
# explicit get a range when we know it must be safe
|
| 871 |
+
kwargs = kwargs.copy()
|
| 872 |
+
headers = kwargs.pop("headers", {}).copy()
|
| 873 |
+
headers["Range"] = f"bytes={start}-{end - 1}"
|
| 874 |
+
r = session.get(url, headers=headers, **kwargs)
|
| 875 |
+
r.raise_for_status()
|
| 876 |
+
return r.content
|
| 877 |
+
|
| 878 |
+
|
| 879 |
+
def _file_info(url, session, size_policy="head", **kwargs):
|
| 880 |
+
"""Call HEAD on the server to get details about the file (size/checksum etc.)
|
| 881 |
+
|
| 882 |
+
Default operation is to explicitly allow redirects and use encoding
|
| 883 |
+
'identity' (no compression) to get the true size of the target.
|
| 884 |
+
"""
|
| 885 |
+
logger.debug("Retrieve file size for %s", url)
|
| 886 |
+
kwargs = kwargs.copy()
|
| 887 |
+
ar = kwargs.pop("allow_redirects", True)
|
| 888 |
+
head = kwargs.get("headers", {}).copy()
|
| 889 |
+
# TODO: not allowed in JS
|
| 890 |
+
# head["Accept-Encoding"] = "identity"
|
| 891 |
+
kwargs["headers"] = head
|
| 892 |
+
|
| 893 |
+
info = {}
|
| 894 |
+
if size_policy == "head":
|
| 895 |
+
r = session.head(url, allow_redirects=ar, **kwargs)
|
| 896 |
+
elif size_policy == "get":
|
| 897 |
+
r = session.get(url, allow_redirects=ar, **kwargs)
|
| 898 |
+
else:
|
| 899 |
+
raise TypeError(f'size_policy must be "head" or "get", got {size_policy}')
|
| 900 |
+
r.raise_for_status()
|
| 901 |
+
|
| 902 |
+
# TODO:
|
| 903 |
+
# recognise lack of 'Accept-Ranges',
|
| 904 |
+
# or 'Accept-Ranges': 'none' (not 'bytes')
|
| 905 |
+
# to mean streaming only, no random access => return None
|
| 906 |
+
if "Content-Length" in r.headers:
|
| 907 |
+
info["size"] = int(r.headers["Content-Length"])
|
| 908 |
+
elif "Content-Range" in r.headers:
|
| 909 |
+
info["size"] = int(r.headers["Content-Range"].split("/")[1])
|
| 910 |
+
elif "content-length" in r.headers:
|
| 911 |
+
info["size"] = int(r.headers["content-length"])
|
| 912 |
+
elif "content-range" in r.headers:
|
| 913 |
+
info["size"] = int(r.headers["content-range"].split("/")[1])
|
| 914 |
+
|
| 915 |
+
for checksum_field in ["ETag", "Content-MD5", "Digest"]:
|
| 916 |
+
if r.headers.get(checksum_field):
|
| 917 |
+
info[checksum_field] = r.headers[checksum_field]
|
| 918 |
+
|
| 919 |
+
return info
|
| 920 |
+
|
| 921 |
+
|
| 922 |
+
# importing this is enough to register it
|
| 923 |
+
def register():
|
| 924 |
+
register_implementation("http", HTTPFileSystem, clobber=True)
|
| 925 |
+
register_implementation("https", HTTPFileSystem, clobber=True)
|
| 926 |
+
register_implementation("sync-http", HTTPFileSystem, clobber=True)
|
| 927 |
+
register_implementation("sync-https", HTTPFileSystem, clobber=True)
|
| 928 |
+
|
| 929 |
+
|
| 930 |
+
register()
|
| 931 |
+
|
| 932 |
+
|
| 933 |
+
def unregister():
|
| 934 |
+
from fsspec.implementations.http import HTTPFileSystem
|
| 935 |
+
|
| 936 |
+
register_implementation("http", HTTPFileSystem, clobber=True)
|
| 937 |
+
register_implementation("https", HTTPFileSystem, clobber=True)
|
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/jupyter.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
import io
|
| 3 |
+
import re
|
| 4 |
+
|
| 5 |
+
import requests
|
| 6 |
+
|
| 7 |
+
import fsspec
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class JupyterFileSystem(fsspec.AbstractFileSystem):
|
| 11 |
+
"""View of the files as seen by a Jupyter server (notebook or lab)"""
|
| 12 |
+
|
| 13 |
+
protocol = ("jupyter", "jlab")
|
| 14 |
+
|
| 15 |
+
def __init__(self, url, tok=None, **kwargs):
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
Parameters
|
| 19 |
+
----------
|
| 20 |
+
url : str
|
| 21 |
+
Base URL of the server, like "http://127.0.0.1:8888". May include
|
| 22 |
+
token in the string, which is given by the process when starting up
|
| 23 |
+
tok : str
|
| 24 |
+
If the token is obtained separately, can be given here
|
| 25 |
+
kwargs
|
| 26 |
+
"""
|
| 27 |
+
if "?" in url:
|
| 28 |
+
if tok is None:
|
| 29 |
+
try:
|
| 30 |
+
tok = re.findall("token=([a-z0-9]+)", url)[0]
|
| 31 |
+
except IndexError as e:
|
| 32 |
+
raise ValueError("Could not determine token") from e
|
| 33 |
+
url = url.split("?", 1)[0]
|
| 34 |
+
self.url = url.rstrip("/") + "/api/contents"
|
| 35 |
+
self.session = requests.Session()
|
| 36 |
+
if tok:
|
| 37 |
+
self.session.headers["Authorization"] = f"token {tok}"
|
| 38 |
+
|
| 39 |
+
super().__init__(**kwargs)
|
| 40 |
+
|
| 41 |
+
def ls(self, path, detail=True, **kwargs):
|
| 42 |
+
path = self._strip_protocol(path)
|
| 43 |
+
r = self.session.get(f"{self.url}/{path}")
|
| 44 |
+
if r.status_code == 404:
|
| 45 |
+
raise FileNotFoundError(path)
|
| 46 |
+
r.raise_for_status()
|
| 47 |
+
out = r.json()
|
| 48 |
+
|
| 49 |
+
if out["type"] == "directory":
|
| 50 |
+
out = out["content"]
|
| 51 |
+
else:
|
| 52 |
+
out = [out]
|
| 53 |
+
for o in out:
|
| 54 |
+
o["name"] = o.pop("path")
|
| 55 |
+
o.pop("content")
|
| 56 |
+
if o["type"] == "notebook":
|
| 57 |
+
o["type"] = "file"
|
| 58 |
+
if detail:
|
| 59 |
+
return out
|
| 60 |
+
return [o["name"] for o in out]
|
| 61 |
+
|
| 62 |
+
def cat_file(self, path, start=None, end=None, **kwargs):
|
| 63 |
+
path = self._strip_protocol(path)
|
| 64 |
+
r = self.session.get(f"{self.url}/{path}")
|
| 65 |
+
if r.status_code == 404:
|
| 66 |
+
raise FileNotFoundError(path)
|
| 67 |
+
r.raise_for_status()
|
| 68 |
+
out = r.json()
|
| 69 |
+
if out["format"] == "text":
|
| 70 |
+
# data should be binary
|
| 71 |
+
b = out["content"].encode()
|
| 72 |
+
else:
|
| 73 |
+
b = base64.b64decode(out["content"])
|
| 74 |
+
return b[start:end]
|
| 75 |
+
|
| 76 |
+
def pipe_file(self, path, value, **_):
|
| 77 |
+
path = self._strip_protocol(path)
|
| 78 |
+
json = {
|
| 79 |
+
"name": path.rsplit("/", 1)[-1],
|
| 80 |
+
"path": path,
|
| 81 |
+
"size": len(value),
|
| 82 |
+
"content": base64.b64encode(value).decode(),
|
| 83 |
+
"format": "base64",
|
| 84 |
+
"type": "file",
|
| 85 |
+
}
|
| 86 |
+
self.session.put(f"{self.url}/{path}", json=json)
|
| 87 |
+
|
| 88 |
+
def mkdir(self, path, create_parents=True, **kwargs):
|
| 89 |
+
path = self._strip_protocol(path)
|
| 90 |
+
if create_parents and "/" in path:
|
| 91 |
+
self.mkdir(path.rsplit("/", 1)[0], True)
|
| 92 |
+
json = {
|
| 93 |
+
"name": path.rsplit("/", 1)[-1],
|
| 94 |
+
"path": path,
|
| 95 |
+
"size": None,
|
| 96 |
+
"content": None,
|
| 97 |
+
"type": "directory",
|
| 98 |
+
}
|
| 99 |
+
self.session.put(f"{self.url}/{path}", json=json)
|
| 100 |
+
|
| 101 |
+
def mv(self, path1, path2, recursive=False, maxdepth=None, **kwargs):
|
| 102 |
+
if path1 == path2:
|
| 103 |
+
return
|
| 104 |
+
self.session.patch(f"{self.url}/{path1}", json={"path": path2})
|
| 105 |
+
|
| 106 |
+
def _rm(self, path):
|
| 107 |
+
path = self._strip_protocol(path)
|
| 108 |
+
self.session.delete(f"{self.url}/{path}")
|
| 109 |
+
|
| 110 |
+
def _open(self, path, mode="rb", **kwargs):
|
| 111 |
+
path = self._strip_protocol(path)
|
| 112 |
+
if mode == "rb":
|
| 113 |
+
data = self.cat_file(path)
|
| 114 |
+
return io.BytesIO(data)
|
| 115 |
+
else:
|
| 116 |
+
return SimpleFileWriter(self, path, mode="wb")
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
class SimpleFileWriter(fsspec.spec.AbstractBufferedFile):
|
| 120 |
+
def _upload_chunk(self, final=False):
|
| 121 |
+
"""Never uploads a chunk until file is done
|
| 122 |
+
|
| 123 |
+
Not suitable for large files
|
| 124 |
+
"""
|
| 125 |
+
if final is False:
|
| 126 |
+
return False
|
| 127 |
+
self.buffer.seek(0)
|
| 128 |
+
data = self.buffer.read()
|
| 129 |
+
self.fs.pipe_file(self.path, data)
|
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/libarchive.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
| 2 |
+
from ctypes import (
|
| 3 |
+
CFUNCTYPE,
|
| 4 |
+
POINTER,
|
| 5 |
+
c_int,
|
| 6 |
+
c_longlong,
|
| 7 |
+
c_void_p,
|
| 8 |
+
cast,
|
| 9 |
+
create_string_buffer,
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
import libarchive
|
| 13 |
+
import libarchive.ffi as ffi
|
| 14 |
+
|
| 15 |
+
from fsspec import open_files
|
| 16 |
+
from fsspec.archive import AbstractArchiveFileSystem
|
| 17 |
+
from fsspec.implementations.memory import MemoryFile
|
| 18 |
+
from fsspec.utils import DEFAULT_BLOCK_SIZE
|
| 19 |
+
|
| 20 |
+
# Libarchive requires seekable files or memory only for certain archive
|
| 21 |
+
# types. However, since we read the directory first to cache the contents
|
| 22 |
+
# and also allow random access to any file, the file-like object needs
|
| 23 |
+
# to be seekable no matter what.
|
| 24 |
+
|
| 25 |
+
# Seek call-backs (not provided in the libarchive python wrapper)
|
| 26 |
+
SEEK_CALLBACK = CFUNCTYPE(c_longlong, c_int, c_void_p, c_longlong, c_int)
|
| 27 |
+
read_set_seek_callback = ffi.ffi(
|
| 28 |
+
"read_set_seek_callback", [ffi.c_archive_p, SEEK_CALLBACK], c_int, ffi.check_int
|
| 29 |
+
)
|
| 30 |
+
new_api = hasattr(ffi, "NO_OPEN_CB")
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
@contextmanager
|
| 34 |
+
def custom_reader(file, format_name="all", filter_name="all", block_size=ffi.page_size):
|
| 35 |
+
"""Read an archive from a seekable file-like object.
|
| 36 |
+
|
| 37 |
+
The `file` object must support the standard `readinto` and 'seek' methods.
|
| 38 |
+
"""
|
| 39 |
+
buf = create_string_buffer(block_size)
|
| 40 |
+
buf_p = cast(buf, c_void_p)
|
| 41 |
+
|
| 42 |
+
def read_func(archive_p, context, ptrptr):
|
| 43 |
+
# readinto the buffer, returns number of bytes read
|
| 44 |
+
length = file.readinto(buf)
|
| 45 |
+
# write the address of the buffer into the pointer
|
| 46 |
+
ptrptr = cast(ptrptr, POINTER(c_void_p))
|
| 47 |
+
ptrptr[0] = buf_p
|
| 48 |
+
# tell libarchive how much data was written into the buffer
|
| 49 |
+
return length
|
| 50 |
+
|
| 51 |
+
def seek_func(archive_p, context, offset, whence):
|
| 52 |
+
file.seek(offset, whence)
|
| 53 |
+
# tell libarchvie the current position
|
| 54 |
+
return file.tell()
|
| 55 |
+
|
| 56 |
+
read_cb = ffi.READ_CALLBACK(read_func)
|
| 57 |
+
seek_cb = SEEK_CALLBACK(seek_func)
|
| 58 |
+
|
| 59 |
+
if new_api:
|
| 60 |
+
open_cb = ffi.NO_OPEN_CB
|
| 61 |
+
close_cb = ffi.NO_CLOSE_CB
|
| 62 |
+
else:
|
| 63 |
+
open_cb = libarchive.read.OPEN_CALLBACK(ffi.VOID_CB)
|
| 64 |
+
close_cb = libarchive.read.CLOSE_CALLBACK(ffi.VOID_CB)
|
| 65 |
+
|
| 66 |
+
with libarchive.read.new_archive_read(format_name, filter_name) as archive_p:
|
| 67 |
+
read_set_seek_callback(archive_p, seek_cb)
|
| 68 |
+
ffi.read_open(archive_p, None, open_cb, read_cb, close_cb)
|
| 69 |
+
yield libarchive.read.ArchiveRead(archive_p)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
class LibArchiveFileSystem(AbstractArchiveFileSystem):
|
| 73 |
+
"""Compressed archives as a file-system (read-only)
|
| 74 |
+
|
| 75 |
+
Supports the following formats:
|
| 76 |
+
tar, pax , cpio, ISO9660, zip, mtree, shar, ar, raw, xar, lha/lzh, rar
|
| 77 |
+
Microsoft CAB, 7-Zip, WARC
|
| 78 |
+
|
| 79 |
+
See the libarchive documentation for further restrictions.
|
| 80 |
+
https://www.libarchive.org/
|
| 81 |
+
|
| 82 |
+
Keeps file object open while instance lives. It only works in seekable
|
| 83 |
+
file-like objects. In case the filesystem does not support this kind of
|
| 84 |
+
file object, it is recommended to cache locally.
|
| 85 |
+
|
| 86 |
+
This class is pickleable, but not necessarily thread-safe (depends on the
|
| 87 |
+
platform). See libarchive documentation for details.
|
| 88 |
+
"""
|
| 89 |
+
|
| 90 |
+
root_marker = ""
|
| 91 |
+
protocol = "libarchive"
|
| 92 |
+
cachable = False
|
| 93 |
+
|
| 94 |
+
def __init__(
|
| 95 |
+
self,
|
| 96 |
+
fo="",
|
| 97 |
+
mode="r",
|
| 98 |
+
target_protocol=None,
|
| 99 |
+
target_options=None,
|
| 100 |
+
block_size=DEFAULT_BLOCK_SIZE,
|
| 101 |
+
**kwargs,
|
| 102 |
+
):
|
| 103 |
+
"""
|
| 104 |
+
Parameters
|
| 105 |
+
----------
|
| 106 |
+
fo: str or file-like
|
| 107 |
+
Contains ZIP, and must exist. If a str, will fetch file using
|
| 108 |
+
:meth:`~fsspec.open_files`, which must return one file exactly.
|
| 109 |
+
mode: str
|
| 110 |
+
Currently, only 'r' accepted
|
| 111 |
+
target_protocol: str (optional)
|
| 112 |
+
If ``fo`` is a string, this value can be used to override the
|
| 113 |
+
FS protocol inferred from a URL
|
| 114 |
+
target_options: dict (optional)
|
| 115 |
+
Kwargs passed when instantiating the target FS, if ``fo`` is
|
| 116 |
+
a string.
|
| 117 |
+
"""
|
| 118 |
+
super().__init__(self, **kwargs)
|
| 119 |
+
if mode != "r":
|
| 120 |
+
raise ValueError("Only read from archive files accepted")
|
| 121 |
+
if isinstance(fo, str):
|
| 122 |
+
files = open_files(fo, protocol=target_protocol, **(target_options or {}))
|
| 123 |
+
if len(files) != 1:
|
| 124 |
+
raise ValueError(
|
| 125 |
+
f'Path "{fo}" did not resolve to exactly one file: "{files}"'
|
| 126 |
+
)
|
| 127 |
+
fo = files[0]
|
| 128 |
+
self.of = fo
|
| 129 |
+
self.fo = fo.__enter__() # the whole instance is a context
|
| 130 |
+
self.block_size = block_size
|
| 131 |
+
self.dir_cache = None
|
| 132 |
+
|
| 133 |
+
@contextmanager
|
| 134 |
+
def _open_archive(self):
|
| 135 |
+
self.fo.seek(0)
|
| 136 |
+
with custom_reader(self.fo, block_size=self.block_size) as arc:
|
| 137 |
+
yield arc
|
| 138 |
+
|
| 139 |
+
@classmethod
|
| 140 |
+
def _strip_protocol(cls, path):
|
| 141 |
+
# file paths are always relative to the archive root
|
| 142 |
+
return super()._strip_protocol(path).lstrip("/")
|
| 143 |
+
|
| 144 |
+
def _get_dirs(self):
|
| 145 |
+
fields = {
|
| 146 |
+
"name": "pathname",
|
| 147 |
+
"size": "size",
|
| 148 |
+
"created": "ctime",
|
| 149 |
+
"mode": "mode",
|
| 150 |
+
"uid": "uid",
|
| 151 |
+
"gid": "gid",
|
| 152 |
+
"mtime": "mtime",
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
if self.dir_cache is not None:
|
| 156 |
+
return
|
| 157 |
+
|
| 158 |
+
self.dir_cache = {}
|
| 159 |
+
list_names = []
|
| 160 |
+
with self._open_archive() as arc:
|
| 161 |
+
for entry in arc:
|
| 162 |
+
if not entry.isdir and not entry.isfile:
|
| 163 |
+
# Skip symbolic links, fifo entries, etc.
|
| 164 |
+
continue
|
| 165 |
+
self.dir_cache.update(
|
| 166 |
+
{
|
| 167 |
+
dirname: {"name": dirname, "size": 0, "type": "directory"}
|
| 168 |
+
for dirname in self._all_dirnames(set(entry.name))
|
| 169 |
+
}
|
| 170 |
+
)
|
| 171 |
+
f = {key: getattr(entry, fields[key]) for key in fields}
|
| 172 |
+
f["type"] = "directory" if entry.isdir else "file"
|
| 173 |
+
list_names.append(entry.name)
|
| 174 |
+
|
| 175 |
+
self.dir_cache[f["name"]] = f
|
| 176 |
+
# libarchive does not seem to return an entry for the directories (at least
|
| 177 |
+
# not in all formats), so get the directories names from the files names
|
| 178 |
+
self.dir_cache.update(
|
| 179 |
+
{
|
| 180 |
+
dirname: {"name": dirname, "size": 0, "type": "directory"}
|
| 181 |
+
for dirname in self._all_dirnames(list_names)
|
| 182 |
+
}
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
+
def _open(
|
| 186 |
+
self,
|
| 187 |
+
path,
|
| 188 |
+
mode="rb",
|
| 189 |
+
block_size=None,
|
| 190 |
+
autocommit=True,
|
| 191 |
+
cache_options=None,
|
| 192 |
+
**kwargs,
|
| 193 |
+
):
|
| 194 |
+
path = self._strip_protocol(path)
|
| 195 |
+
if mode != "rb":
|
| 196 |
+
raise NotImplementedError
|
| 197 |
+
|
| 198 |
+
data = b""
|
| 199 |
+
with self._open_archive() as arc:
|
| 200 |
+
for entry in arc:
|
| 201 |
+
if entry.pathname != path:
|
| 202 |
+
continue
|
| 203 |
+
|
| 204 |
+
if entry.size == 0:
|
| 205 |
+
# empty file, so there are no blocks
|
| 206 |
+
break
|
| 207 |
+
|
| 208 |
+
for block in entry.get_blocks(entry.size):
|
| 209 |
+
data = block
|
| 210 |
+
break
|
| 211 |
+
else:
|
| 212 |
+
raise ValueError
|
| 213 |
+
return MemoryFile(fs=self, path=path, data=data)
|
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/memory.py
ADDED
|
@@ -0,0 +1,393 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
from datetime import datetime, timezone
|
| 5 |
+
from errno import ENOTEMPTY
|
| 6 |
+
from io import BytesIO
|
| 7 |
+
from pathlib import PurePath, PureWindowsPath
|
| 8 |
+
from typing import Any, ClassVar
|
| 9 |
+
|
| 10 |
+
from fsspec import AbstractFileSystem
|
| 11 |
+
from fsspec.implementations.local import LocalFileSystem
|
| 12 |
+
from fsspec.utils import stringify_path
|
| 13 |
+
|
| 14 |
+
logger = logging.getLogger("fsspec.memoryfs")
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class MemoryFileSystem(AbstractFileSystem):
|
| 18 |
+
"""A filesystem based on a dict of BytesIO objects
|
| 19 |
+
|
| 20 |
+
This is a global filesystem so instances of this class all point to the same
|
| 21 |
+
in memory filesystem.
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
store: ClassVar[dict[str, Any]] = {} # global, do not overwrite!
|
| 25 |
+
pseudo_dirs = [""] # global, do not overwrite!
|
| 26 |
+
protocol = "memory"
|
| 27 |
+
root_marker = "/"
|
| 28 |
+
|
| 29 |
+
@classmethod
|
| 30 |
+
def _strip_protocol(cls, path):
|
| 31 |
+
if isinstance(path, PurePath):
|
| 32 |
+
if isinstance(path, PureWindowsPath):
|
| 33 |
+
return LocalFileSystem._strip_protocol(path)
|
| 34 |
+
else:
|
| 35 |
+
path = stringify_path(path)
|
| 36 |
+
|
| 37 |
+
path = path.removeprefix("memory://")
|
| 38 |
+
if "::" in path or "://" in path:
|
| 39 |
+
return path.rstrip("/")
|
| 40 |
+
path = path.lstrip("/").rstrip("/")
|
| 41 |
+
return "/" + path if path else ""
|
| 42 |
+
|
| 43 |
+
def find(self, path, maxdepth=None, withdirs=False, detail=False, **kwargs):
|
| 44 |
+
# The base implementation calls ls() once per directory, and each ls()
|
| 45 |
+
# scans the whole (global) store, giving O(n_dirs * n_entries) behaviour
|
| 46 |
+
# for a tree. Since the store is a flat mapping of every path, the same
|
| 47 |
+
# result can be produced with a single pass over it.
|
| 48 |
+
if maxdepth is not None and maxdepth < 1:
|
| 49 |
+
raise ValueError("maxdepth must be at least 1")
|
| 50 |
+
path = self._strip_protocol(path)
|
| 51 |
+
if path in self.store:
|
| 52 |
+
# path is itself a file
|
| 53 |
+
if not detail:
|
| 54 |
+
return [path]
|
| 55 |
+
filelike = self.store[path]
|
| 56 |
+
return {
|
| 57 |
+
path: {
|
| 58 |
+
"name": path,
|
| 59 |
+
"size": filelike.size,
|
| 60 |
+
"type": "file",
|
| 61 |
+
"created": filelike.created.timestamp(),
|
| 62 |
+
}
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
# Uniform prefix so that the search root "" (the filesystem root) and a
|
| 66 |
+
# nested path are handled the same way; rel depth is rel.count("/") + 1.
|
| 67 |
+
prefix = path + "/" if path else "/"
|
| 68 |
+
out = {}
|
| 69 |
+
dirs = {}
|
| 70 |
+
|
| 71 |
+
def add_ancestor_dirs(name):
|
| 72 |
+
# Register every directory implied between ``path`` and ``name`` that
|
| 73 |
+
# is within maxdepth, mirroring how walk() surfaces implied dirs.
|
| 74 |
+
idx = name.rfind("/")
|
| 75 |
+
while idx > len(path):
|
| 76 |
+
parent = name[:idx]
|
| 77 |
+
if parent in dirs:
|
| 78 |
+
break
|
| 79 |
+
rel = parent[len(prefix) :]
|
| 80 |
+
if maxdepth is None or rel.count("/") + 1 <= maxdepth:
|
| 81 |
+
dirs[parent] = {"name": parent, "size": 0, "type": "directory"}
|
| 82 |
+
idx = parent.rfind("/")
|
| 83 |
+
|
| 84 |
+
# `store` is shared by every MemoryFileSystem instance, so iterate a
|
| 85 |
+
# snapshot: a concurrent create/delete would otherwise raise
|
| 86 |
+
# "dictionary changed size during iteration". ls() does the same.
|
| 87 |
+
for name, filelike in tuple(self.store.items()):
|
| 88 |
+
if not name.startswith(prefix):
|
| 89 |
+
continue
|
| 90 |
+
rel = name[len(prefix) :]
|
| 91 |
+
if withdirs:
|
| 92 |
+
add_ancestor_dirs(name)
|
| 93 |
+
if maxdepth is not None and rel.count("/") + 1 > maxdepth:
|
| 94 |
+
continue
|
| 95 |
+
out[name] = {
|
| 96 |
+
"name": name,
|
| 97 |
+
"size": filelike.size,
|
| 98 |
+
"type": "file",
|
| 99 |
+
"created": filelike.created.timestamp(),
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
if withdirs:
|
| 103 |
+
# Explicitly-created (possibly empty) directories live in pseudo_dirs.
|
| 104 |
+
for pdir in self.pseudo_dirs:
|
| 105 |
+
if pdir and pdir.startswith(prefix):
|
| 106 |
+
add_ancestor_dirs(pdir + "/")
|
| 107 |
+
out.update(dirs)
|
| 108 |
+
# Mirror the base find(): include the search root itself when it is
|
| 109 |
+
# a directory (needed for posix glob compliance).
|
| 110 |
+
if path != "" and self.isdir(path):
|
| 111 |
+
out[path] = self.info(path)
|
| 112 |
+
|
| 113 |
+
names = sorted(out)
|
| 114 |
+
return {name: out[name] for name in names} if detail else names
|
| 115 |
+
|
| 116 |
+
def ls(self, path, detail=True, **kwargs):
|
| 117 |
+
path = self._strip_protocol(path)
|
| 118 |
+
if path in self.store:
|
| 119 |
+
# there is a key with this exact name
|
| 120 |
+
if not detail:
|
| 121 |
+
return [path]
|
| 122 |
+
return [
|
| 123 |
+
{
|
| 124 |
+
"name": path,
|
| 125 |
+
"size": self.store[path].size,
|
| 126 |
+
"type": "file",
|
| 127 |
+
"created": self.store[path].created.timestamp(),
|
| 128 |
+
}
|
| 129 |
+
]
|
| 130 |
+
paths = set()
|
| 131 |
+
starter = path + "/"
|
| 132 |
+
out = []
|
| 133 |
+
for p2 in tuple(self.store):
|
| 134 |
+
if p2.startswith(starter):
|
| 135 |
+
if "/" not in p2[len(starter) :]:
|
| 136 |
+
# exact child
|
| 137 |
+
out.append(
|
| 138 |
+
{
|
| 139 |
+
"name": p2,
|
| 140 |
+
"size": self.store[p2].size,
|
| 141 |
+
"type": "file",
|
| 142 |
+
"created": self.store[p2].created.timestamp(),
|
| 143 |
+
}
|
| 144 |
+
)
|
| 145 |
+
elif len(p2) > len(starter):
|
| 146 |
+
# implied child directory
|
| 147 |
+
ppath = starter + p2[len(starter) :].split("/", 1)[0]
|
| 148 |
+
if ppath not in paths:
|
| 149 |
+
out = out or []
|
| 150 |
+
out.append(
|
| 151 |
+
{
|
| 152 |
+
"name": ppath,
|
| 153 |
+
"size": 0,
|
| 154 |
+
"type": "directory",
|
| 155 |
+
}
|
| 156 |
+
)
|
| 157 |
+
paths.add(ppath)
|
| 158 |
+
for p2 in self.pseudo_dirs:
|
| 159 |
+
if p2.startswith(starter):
|
| 160 |
+
if "/" not in p2[len(starter) :]:
|
| 161 |
+
# exact child pdir
|
| 162 |
+
if p2 not in paths:
|
| 163 |
+
out.append({"name": p2, "size": 0, "type": "directory"})
|
| 164 |
+
paths.add(p2)
|
| 165 |
+
else:
|
| 166 |
+
# directory implied by deeper pdir
|
| 167 |
+
ppath = starter + p2[len(starter) :].split("/", 1)[0]
|
| 168 |
+
if ppath not in paths:
|
| 169 |
+
out.append({"name": ppath, "size": 0, "type": "directory"})
|
| 170 |
+
paths.add(ppath)
|
| 171 |
+
if not out:
|
| 172 |
+
if path in self.pseudo_dirs:
|
| 173 |
+
# empty dir
|
| 174 |
+
return []
|
| 175 |
+
raise FileNotFoundError(path)
|
| 176 |
+
if detail:
|
| 177 |
+
return out
|
| 178 |
+
return sorted([f["name"] for f in out])
|
| 179 |
+
|
| 180 |
+
def mkdir(self, path, create_parents=True, **kwargs):
|
| 181 |
+
path = self._strip_protocol(path)
|
| 182 |
+
if path in self.store or path in self.pseudo_dirs:
|
| 183 |
+
raise FileExistsError(path)
|
| 184 |
+
if self._parent(path).strip("/") and self.isfile(self._parent(path)):
|
| 185 |
+
raise NotADirectoryError(self._parent(path))
|
| 186 |
+
if create_parents and self._parent(path).strip("/"):
|
| 187 |
+
try:
|
| 188 |
+
self.mkdir(self._parent(path), create_parents, **kwargs)
|
| 189 |
+
except FileExistsError:
|
| 190 |
+
pass
|
| 191 |
+
if path and path not in self.pseudo_dirs:
|
| 192 |
+
self.pseudo_dirs.append(path)
|
| 193 |
+
|
| 194 |
+
def makedirs(self, path, exist_ok=False):
|
| 195 |
+
try:
|
| 196 |
+
self.mkdir(path, create_parents=True)
|
| 197 |
+
except FileExistsError:
|
| 198 |
+
if not exist_ok:
|
| 199 |
+
raise
|
| 200 |
+
|
| 201 |
+
def pipe_file(self, path, value, mode="overwrite", **kwargs):
|
| 202 |
+
"""Set the bytes of given file
|
| 203 |
+
|
| 204 |
+
Avoids copies of the data if possible
|
| 205 |
+
"""
|
| 206 |
+
mode = "xb" if mode == "create" else "wb"
|
| 207 |
+
self.open(path, mode=mode, data=value)
|
| 208 |
+
|
| 209 |
+
def rmdir(self, path):
|
| 210 |
+
path = self._strip_protocol(path)
|
| 211 |
+
if path == "":
|
| 212 |
+
# silently avoid deleting FS root
|
| 213 |
+
return
|
| 214 |
+
if path in self.pseudo_dirs:
|
| 215 |
+
if not self.ls(path):
|
| 216 |
+
self.pseudo_dirs.remove(path)
|
| 217 |
+
else:
|
| 218 |
+
raise OSError(ENOTEMPTY, "Directory not empty", path)
|
| 219 |
+
else:
|
| 220 |
+
raise FileNotFoundError(path)
|
| 221 |
+
|
| 222 |
+
def info(self, path, **kwargs):
|
| 223 |
+
logger.debug("info: %s", path)
|
| 224 |
+
path = self._strip_protocol(path)
|
| 225 |
+
if path in self.pseudo_dirs or any(
|
| 226 |
+
p.startswith(path + "/") for p in list(self.store) + self.pseudo_dirs
|
| 227 |
+
):
|
| 228 |
+
return {
|
| 229 |
+
"name": path,
|
| 230 |
+
"size": 0,
|
| 231 |
+
"type": "directory",
|
| 232 |
+
}
|
| 233 |
+
elif path in self.store:
|
| 234 |
+
filelike = self.store[path]
|
| 235 |
+
return {
|
| 236 |
+
"name": path,
|
| 237 |
+
"size": filelike.size,
|
| 238 |
+
"type": "file",
|
| 239 |
+
"created": getattr(filelike, "created", None),
|
| 240 |
+
}
|
| 241 |
+
else:
|
| 242 |
+
raise FileNotFoundError(path)
|
| 243 |
+
|
| 244 |
+
def _open(
|
| 245 |
+
self,
|
| 246 |
+
path,
|
| 247 |
+
mode="rb",
|
| 248 |
+
block_size=None,
|
| 249 |
+
autocommit=True,
|
| 250 |
+
cache_options=None,
|
| 251 |
+
**kwargs,
|
| 252 |
+
):
|
| 253 |
+
path = self._strip_protocol(path)
|
| 254 |
+
if "x" in mode and self.exists(path):
|
| 255 |
+
raise FileExistsError
|
| 256 |
+
if path in self.pseudo_dirs:
|
| 257 |
+
raise IsADirectoryError(path)
|
| 258 |
+
parent = path
|
| 259 |
+
while len(parent) > 1:
|
| 260 |
+
parent = self._parent(parent)
|
| 261 |
+
if self.isfile(parent):
|
| 262 |
+
raise FileExistsError(parent)
|
| 263 |
+
if mode in ["rb", "ab", "r+b", "a+b"]:
|
| 264 |
+
if path in self.store:
|
| 265 |
+
f = self.store[path]
|
| 266 |
+
if "a" in mode:
|
| 267 |
+
# position at the end of file
|
| 268 |
+
f.seek(0, 2)
|
| 269 |
+
else:
|
| 270 |
+
# position at the beginning of file
|
| 271 |
+
f.seek(0)
|
| 272 |
+
return f
|
| 273 |
+
elif "a" in mode:
|
| 274 |
+
# append modes create the file if it does not exist, matching
|
| 275 |
+
# builtin open() and LocalFileSystem
|
| 276 |
+
m = MemoryFile(self, path, kwargs.get("data"))
|
| 277 |
+
if not self._intrans:
|
| 278 |
+
m.commit()
|
| 279 |
+
# position at the end of file, like the existing-file path above
|
| 280 |
+
m.seek(0, 2)
|
| 281 |
+
return m
|
| 282 |
+
else:
|
| 283 |
+
raise FileNotFoundError(path)
|
| 284 |
+
elif mode in {"wb", "w+b", "xb", "x+b"}:
|
| 285 |
+
if "x" in mode and self.exists(path):
|
| 286 |
+
raise FileExistsError
|
| 287 |
+
m = MemoryFile(self, path, kwargs.get("data"))
|
| 288 |
+
if not self._intrans:
|
| 289 |
+
m.commit()
|
| 290 |
+
return m
|
| 291 |
+
else:
|
| 292 |
+
name = self.__class__.__name__
|
| 293 |
+
raise ValueError(f"unsupported file mode for {name}: {mode!r}")
|
| 294 |
+
|
| 295 |
+
def cp_file(self, path1, path2, **kwargs):
|
| 296 |
+
path1 = self._strip_protocol(path1)
|
| 297 |
+
path2 = self._strip_protocol(path2)
|
| 298 |
+
if self.isfile(path1):
|
| 299 |
+
self.store[path2] = MemoryFile(
|
| 300 |
+
self, path2, self.store[path1].getvalue()
|
| 301 |
+
) # implicit copy
|
| 302 |
+
elif self.isdir(path1):
|
| 303 |
+
if path2 not in self.pseudo_dirs:
|
| 304 |
+
self.pseudo_dirs.append(path2)
|
| 305 |
+
else:
|
| 306 |
+
raise FileNotFoundError(path1)
|
| 307 |
+
|
| 308 |
+
def cat_file(self, path, start=None, end=None, **kwargs):
|
| 309 |
+
logger.debug("cat: %s", path)
|
| 310 |
+
path = self._strip_protocol(path)
|
| 311 |
+
try:
|
| 312 |
+
return bytes(self.store[path].getbuffer()[start:end])
|
| 313 |
+
except KeyError as e:
|
| 314 |
+
raise FileNotFoundError(path) from e
|
| 315 |
+
|
| 316 |
+
def _rm(self, path):
|
| 317 |
+
path = self._strip_protocol(path)
|
| 318 |
+
try:
|
| 319 |
+
del self.store[path]
|
| 320 |
+
except KeyError as e:
|
| 321 |
+
raise FileNotFoundError(path) from e
|
| 322 |
+
|
| 323 |
+
def modified(self, path):
|
| 324 |
+
path = self._strip_protocol(path)
|
| 325 |
+
try:
|
| 326 |
+
return self.store[path].modified
|
| 327 |
+
except KeyError as e:
|
| 328 |
+
raise FileNotFoundError(path) from e
|
| 329 |
+
|
| 330 |
+
def created(self, path):
|
| 331 |
+
path = self._strip_protocol(path)
|
| 332 |
+
try:
|
| 333 |
+
return self.store[path].created
|
| 334 |
+
except KeyError as e:
|
| 335 |
+
raise FileNotFoundError(path) from e
|
| 336 |
+
|
| 337 |
+
def isfile(self, path):
|
| 338 |
+
path = self._strip_protocol(path)
|
| 339 |
+
return path in self.store
|
| 340 |
+
|
| 341 |
+
def rm(self, path, recursive=False, maxdepth=None):
|
| 342 |
+
if isinstance(path, str):
|
| 343 |
+
path = self._strip_protocol(path)
|
| 344 |
+
else:
|
| 345 |
+
path = [self._strip_protocol(p) for p in path]
|
| 346 |
+
paths = self.expand_path(path, recursive=recursive, maxdepth=maxdepth)
|
| 347 |
+
for p in reversed(paths):
|
| 348 |
+
if self.isfile(p):
|
| 349 |
+
self.rm_file(p)
|
| 350 |
+
# If the expanded path doesn't exist, it is only because the expanded
|
| 351 |
+
# path was a directory that does not exist in self.pseudo_dirs. This
|
| 352 |
+
# is possible if you directly create files without making the
|
| 353 |
+
# directories first.
|
| 354 |
+
elif not self.exists(p):
|
| 355 |
+
continue
|
| 356 |
+
else:
|
| 357 |
+
self.rmdir(p)
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
class MemoryFile(BytesIO):
|
| 361 |
+
"""A BytesIO which can't close and works as a context manager
|
| 362 |
+
|
| 363 |
+
Can initialise with data. Each path should only be active once at any moment.
|
| 364 |
+
|
| 365 |
+
No need to provide fs, path if auto-committing (default)
|
| 366 |
+
"""
|
| 367 |
+
|
| 368 |
+
def __init__(self, fs=None, path=None, data=None):
|
| 369 |
+
logger.debug("open file %s", path)
|
| 370 |
+
self.fs = fs
|
| 371 |
+
self.path = path
|
| 372 |
+
self.created = datetime.now(tz=timezone.utc)
|
| 373 |
+
self.modified = datetime.now(tz=timezone.utc)
|
| 374 |
+
if data:
|
| 375 |
+
super().__init__(data)
|
| 376 |
+
self.seek(0)
|
| 377 |
+
|
| 378 |
+
@property
|
| 379 |
+
def size(self):
|
| 380 |
+
return self.getbuffer().nbytes
|
| 381 |
+
|
| 382 |
+
def __enter__(self):
|
| 383 |
+
return self
|
| 384 |
+
|
| 385 |
+
def close(self):
|
| 386 |
+
pass
|
| 387 |
+
|
| 388 |
+
def discard(self):
|
| 389 |
+
pass
|
| 390 |
+
|
| 391 |
+
def commit(self):
|
| 392 |
+
self.fs.store[self.path] = self
|
| 393 |
+
self.modified = datetime.now(tz=timezone.utc)
|
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/sftp.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
| 1 |
+
import datetime
|
| 2 |
+
import logging
|
| 3 |
+
import os
|
| 4 |
+
import types
|
| 5 |
+
import uuid
|
| 6 |
+
from stat import S_ISDIR, S_ISLNK
|
| 7 |
+
|
| 8 |
+
import paramiko
|
| 9 |
+
|
| 10 |
+
from .. import AbstractFileSystem
|
| 11 |
+
from ..utils import infer_storage_options
|
| 12 |
+
|
| 13 |
+
logger = logging.getLogger("fsspec.sftp")
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class SFTPFileSystem(AbstractFileSystem):
|
| 17 |
+
"""Files over SFTP/SSH
|
| 18 |
+
|
| 19 |
+
Peer-to-peer filesystem over SSH using paramiko.
|
| 20 |
+
|
| 21 |
+
Note: if using this with the ``open`` or ``open_files``, with full URLs,
|
| 22 |
+
there is no way to tell if a path is relative, so all paths are assumed
|
| 23 |
+
to be absolute.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
protocol = "sftp", "ssh"
|
| 27 |
+
|
| 28 |
+
def __init__(self, host, **ssh_kwargs):
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
Parameters
|
| 32 |
+
----------
|
| 33 |
+
host: str
|
| 34 |
+
Hostname or IP as a string
|
| 35 |
+
temppath: str
|
| 36 |
+
Location on the server to put files, when within a transaction
|
| 37 |
+
ssh_kwargs: dict
|
| 38 |
+
Parameters passed on to connection. See details in
|
| 39 |
+
https://docs.paramiko.org/en/3.3/api/client.html#paramiko.client.SSHClient.connect
|
| 40 |
+
May include port, username, password...
|
| 41 |
+
"""
|
| 42 |
+
if self._cached:
|
| 43 |
+
return
|
| 44 |
+
super().__init__(**ssh_kwargs)
|
| 45 |
+
self.temppath = ssh_kwargs.pop("temppath", "/tmp") # remote temp directory
|
| 46 |
+
self.host = host
|
| 47 |
+
self.ssh_kwargs = ssh_kwargs
|
| 48 |
+
self._connect()
|
| 49 |
+
|
| 50 |
+
def _connect(self):
|
| 51 |
+
logger.debug("Connecting to SFTP server %s", self.host)
|
| 52 |
+
self.client = paramiko.SSHClient()
|
| 53 |
+
self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
| 54 |
+
self.client.connect(self.host, **self.ssh_kwargs)
|
| 55 |
+
self.ftp = self.client.open_sftp()
|
| 56 |
+
|
| 57 |
+
@classmethod
|
| 58 |
+
def _strip_protocol(cls, path):
|
| 59 |
+
return infer_storage_options(path)["path"]
|
| 60 |
+
|
| 61 |
+
@staticmethod
|
| 62 |
+
def _get_kwargs_from_urls(urlpath):
|
| 63 |
+
out = infer_storage_options(urlpath)
|
| 64 |
+
out.pop("path", None)
|
| 65 |
+
out.pop("protocol", None)
|
| 66 |
+
return out
|
| 67 |
+
|
| 68 |
+
def mkdir(self, path, create_parents=True, mode=511):
|
| 69 |
+
path = self._strip_protocol(path)
|
| 70 |
+
logger.debug("Creating folder %s", path)
|
| 71 |
+
if self.exists(path):
|
| 72 |
+
raise FileExistsError(f"File exists: {path}")
|
| 73 |
+
|
| 74 |
+
if create_parents:
|
| 75 |
+
self.makedirs(path)
|
| 76 |
+
else:
|
| 77 |
+
self.ftp.mkdir(path, mode)
|
| 78 |
+
|
| 79 |
+
def makedirs(self, path, exist_ok=False, mode=511):
|
| 80 |
+
if self.exists(path) and not exist_ok:
|
| 81 |
+
raise FileExistsError(f"File exists: {path}")
|
| 82 |
+
|
| 83 |
+
parts = path.split("/")
|
| 84 |
+
new_path = "/" if path[:1] == "/" else ""
|
| 85 |
+
|
| 86 |
+
for part in parts:
|
| 87 |
+
if part:
|
| 88 |
+
new_path = f"{new_path}/{part}" if new_path else part
|
| 89 |
+
if not self.exists(new_path):
|
| 90 |
+
self.ftp.mkdir(new_path, mode)
|
| 91 |
+
|
| 92 |
+
def rmdir(self, path):
|
| 93 |
+
path = self._strip_protocol(path)
|
| 94 |
+
logger.debug("Removing folder %s", path)
|
| 95 |
+
self.ftp.rmdir(path)
|
| 96 |
+
|
| 97 |
+
def info(self, path):
|
| 98 |
+
path = self._strip_protocol(path)
|
| 99 |
+
stat = self._decode_stat(self.ftp.stat(path))
|
| 100 |
+
stat["name"] = path
|
| 101 |
+
return stat
|
| 102 |
+
|
| 103 |
+
@staticmethod
|
| 104 |
+
def _decode_stat(stat, parent_path=None):
|
| 105 |
+
if S_ISDIR(stat.st_mode):
|
| 106 |
+
t = "directory"
|
| 107 |
+
elif S_ISLNK(stat.st_mode):
|
| 108 |
+
t = "link"
|
| 109 |
+
else:
|
| 110 |
+
t = "file"
|
| 111 |
+
out = {
|
| 112 |
+
"name": "",
|
| 113 |
+
"size": stat.st_size,
|
| 114 |
+
"type": t,
|
| 115 |
+
"uid": stat.st_uid,
|
| 116 |
+
"gid": stat.st_gid,
|
| 117 |
+
"time": datetime.datetime.fromtimestamp(
|
| 118 |
+
stat.st_atime, tz=datetime.timezone.utc
|
| 119 |
+
),
|
| 120 |
+
"mtime": datetime.datetime.fromtimestamp(
|
| 121 |
+
stat.st_mtime, tz=datetime.timezone.utc
|
| 122 |
+
),
|
| 123 |
+
}
|
| 124 |
+
if parent_path:
|
| 125 |
+
out["name"] = "/".join([parent_path.rstrip("/"), stat.filename])
|
| 126 |
+
return out
|
| 127 |
+
|
| 128 |
+
def ls(self, path, detail=False):
|
| 129 |
+
path = self._strip_protocol(path)
|
| 130 |
+
logger.debug("Listing folder %s", path)
|
| 131 |
+
stats = [self._decode_stat(stat, path) for stat in self.ftp.listdir_iter(path)]
|
| 132 |
+
if detail:
|
| 133 |
+
return stats
|
| 134 |
+
else:
|
| 135 |
+
paths = [stat["name"] for stat in stats]
|
| 136 |
+
return sorted(paths)
|
| 137 |
+
|
| 138 |
+
def put_file(self, lpath, rpath, callback=None, **kwargs):
|
| 139 |
+
self.mkdirs(self._parent(os.fspath(rpath)), exist_ok=True)
|
| 140 |
+
logger.debug("Put file %s into %s", lpath, rpath)
|
| 141 |
+
self.ftp.put(lpath, rpath)
|
| 142 |
+
|
| 143 |
+
def get_file(self, rpath, lpath, **kwargs):
|
| 144 |
+
if self.isdir(rpath):
|
| 145 |
+
os.makedirs(lpath, exist_ok=True)
|
| 146 |
+
else:
|
| 147 |
+
self.ftp.get(self._strip_protocol(rpath), lpath)
|
| 148 |
+
|
| 149 |
+
def _open(self, path, mode="rb", block_size=None, **kwargs):
|
| 150 |
+
"""
|
| 151 |
+
block_size: int or None
|
| 152 |
+
If 0, no buffering, if 1, line buffering, if >1, buffer that many
|
| 153 |
+
bytes, if None use default from paramiko.
|
| 154 |
+
"""
|
| 155 |
+
logger.debug("Opening file %s", path)
|
| 156 |
+
if kwargs.get("autocommit", True) is False:
|
| 157 |
+
# writes to temporary file, move on commit
|
| 158 |
+
path2 = "/".join([self.temppath, str(uuid.uuid4())])
|
| 159 |
+
f = self.ftp.open(path2, mode, bufsize=block_size if block_size else -1)
|
| 160 |
+
f.temppath = path2
|
| 161 |
+
f.targetpath = path
|
| 162 |
+
f.fs = self
|
| 163 |
+
f.commit = types.MethodType(commit_a_file, f)
|
| 164 |
+
f.discard = types.MethodType(discard_a_file, f)
|
| 165 |
+
else:
|
| 166 |
+
f = self.ftp.open(path, mode, bufsize=block_size if block_size else -1)
|
| 167 |
+
return f
|
| 168 |
+
|
| 169 |
+
def _rm(self, path):
|
| 170 |
+
if self.isdir(path):
|
| 171 |
+
self.ftp.rmdir(path)
|
| 172 |
+
else:
|
| 173 |
+
self.ftp.remove(path)
|
| 174 |
+
|
| 175 |
+
def mv(self, old, new):
|
| 176 |
+
new = self._strip_protocol(new)
|
| 177 |
+
old = self._strip_protocol(old)
|
| 178 |
+
logger.debug("Renaming %s into %s", old, new)
|
| 179 |
+
self.ftp.posix_rename(old, new)
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def commit_a_file(self):
|
| 183 |
+
self.fs.mv(self.temppath, self.targetpath)
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def discard_a_file(self):
|
| 187 |
+
self.fs._rm(self.temppath)
|
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/webhdfs.py
ADDED
|
@@ -0,0 +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|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
import os
|
| 5 |
+
import secrets
|
| 6 |
+
import shutil
|
| 7 |
+
import tempfile
|
| 8 |
+
import uuid
|
| 9 |
+
from contextlib import suppress
|
| 10 |
+
from datetime import datetime
|
| 11 |
+
from urllib.parse import quote
|
| 12 |
+
|
| 13 |
+
import requests
|
| 14 |
+
|
| 15 |
+
from ..spec import AbstractBufferedFile, AbstractFileSystem
|
| 16 |
+
from ..utils import infer_storage_options, tokenize
|
| 17 |
+
|
| 18 |
+
logger = logging.getLogger("webhdfs")
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class WebHDFS(AbstractFileSystem):
|
| 22 |
+
"""
|
| 23 |
+
Interface to HDFS over HTTP using the WebHDFS API. Supports also HttpFS gateways.
|
| 24 |
+
|
| 25 |
+
Four auth mechanisms are supported:
|
| 26 |
+
|
| 27 |
+
insecure: no auth is done, and the user is assumed to be whoever they
|
| 28 |
+
say they are (parameter ``user``), or a predefined value such as
|
| 29 |
+
"dr.who" if not given
|
| 30 |
+
spnego: when kerberos authentication is enabled, auth is negotiated by
|
| 31 |
+
requests_kerberos https://github.com/requests/requests-kerberos .
|
| 32 |
+
This establishes a session based on existing kinit login and/or
|
| 33 |
+
specified principal/password; parameters are passed with ``kerb_kwargs``
|
| 34 |
+
token: uses an existing Hadoop delegation token from another secured
|
| 35 |
+
service. Indeed, this client can also generate such tokens when
|
| 36 |
+
not insecure. Note that tokens expire, but can be renewed (by a
|
| 37 |
+
previously specified user) and may allow for proxying.
|
| 38 |
+
basic-auth: used when both parameter ``user`` and parameter ``password``
|
| 39 |
+
are provided.
|
| 40 |
+
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
tempdir = str(tempfile.gettempdir())
|
| 44 |
+
protocol = "webhdfs", "webHDFS"
|
| 45 |
+
|
| 46 |
+
def __init__(
|
| 47 |
+
self,
|
| 48 |
+
host,
|
| 49 |
+
port=50070,
|
| 50 |
+
kerberos=False,
|
| 51 |
+
token=None,
|
| 52 |
+
user=None,
|
| 53 |
+
password=None,
|
| 54 |
+
proxy_to=None,
|
| 55 |
+
kerb_kwargs=None,
|
| 56 |
+
data_proxy=None,
|
| 57 |
+
use_https=False,
|
| 58 |
+
session_cert=None,
|
| 59 |
+
session_verify=True,
|
| 60 |
+
**kwargs,
|
| 61 |
+
):
|
| 62 |
+
"""
|
| 63 |
+
Parameters
|
| 64 |
+
----------
|
| 65 |
+
host: str
|
| 66 |
+
Name-node address
|
| 67 |
+
port: int
|
| 68 |
+
Port for webHDFS
|
| 69 |
+
kerberos: bool
|
| 70 |
+
Whether to authenticate with kerberos for this connection
|
| 71 |
+
token: str or None
|
| 72 |
+
If given, use this token on every call to authenticate. A user
|
| 73 |
+
and user-proxy may be encoded in the token and should not be also
|
| 74 |
+
given
|
| 75 |
+
user: str or None
|
| 76 |
+
If given, assert the user name to connect with
|
| 77 |
+
password: str or None
|
| 78 |
+
If given, assert the password to use for basic auth. If password
|
| 79 |
+
is provided, user must be provided also
|
| 80 |
+
proxy_to: str or None
|
| 81 |
+
If given, the user has the authority to proxy, and this value is
|
| 82 |
+
the user in who's name actions are taken
|
| 83 |
+
kerb_kwargs: dict
|
| 84 |
+
Any extra arguments for HTTPKerberosAuth, see
|
| 85 |
+
`<https://github.com/requests/requests-kerberos/blob/master/requests_kerberos/kerberos_.py>`_
|
| 86 |
+
data_proxy: dict, callable or None
|
| 87 |
+
If given, map data-node addresses. This can be necessary if the
|
| 88 |
+
HDFS cluster is behind a proxy, running on Docker or otherwise has
|
| 89 |
+
a mismatch between the host-names given by the name-node and the
|
| 90 |
+
address by which to refer to them from the client. If a dict,
|
| 91 |
+
maps host names ``host->data_proxy[host]``; if a callable, full
|
| 92 |
+
URLs are passed, and function must conform to
|
| 93 |
+
``url->data_proxy(url)``.
|
| 94 |
+
use_https: bool
|
| 95 |
+
Whether to connect to the Name-node using HTTPS instead of HTTP
|
| 96 |
+
session_cert: str or Tuple[str, str] or None
|
| 97 |
+
Path to a certificate file, or tuple of (cert, key) files to use
|
| 98 |
+
for the requests.Session
|
| 99 |
+
session_verify: str, bool or None
|
| 100 |
+
Path to a certificate file to use for verifying the requests.Session.
|
| 101 |
+
kwargs
|
| 102 |
+
"""
|
| 103 |
+
if self._cached:
|
| 104 |
+
return
|
| 105 |
+
super().__init__(**kwargs)
|
| 106 |
+
self.url = f"{'https' if use_https else 'http'}://{host}:{port}/webhdfs/v1"
|
| 107 |
+
self.kerb = kerberos
|
| 108 |
+
self.kerb_kwargs = kerb_kwargs or {}
|
| 109 |
+
self.pars = {}
|
| 110 |
+
self.proxy = data_proxy or {}
|
| 111 |
+
if token is not None:
|
| 112 |
+
if user is not None or proxy_to is not None:
|
| 113 |
+
raise ValueError(
|
| 114 |
+
"If passing a delegation token, must not set "
|
| 115 |
+
"user or proxy_to, as these are encoded in the"
|
| 116 |
+
" token"
|
| 117 |
+
)
|
| 118 |
+
self.pars["delegation"] = token
|
| 119 |
+
self.user = user
|
| 120 |
+
self.password = password
|
| 121 |
+
|
| 122 |
+
if password is not None:
|
| 123 |
+
if user is None:
|
| 124 |
+
raise ValueError(
|
| 125 |
+
"If passing a password, the user must also be"
|
| 126 |
+
"set in order to set up the basic-auth"
|
| 127 |
+
)
|
| 128 |
+
else:
|
| 129 |
+
if user is not None:
|
| 130 |
+
self.pars["user.name"] = user
|
| 131 |
+
|
| 132 |
+
if proxy_to is not None:
|
| 133 |
+
self.pars["doas"] = proxy_to
|
| 134 |
+
if kerberos and user is not None:
|
| 135 |
+
raise ValueError(
|
| 136 |
+
"If using Kerberos auth, do not specify the "
|
| 137 |
+
"user, this is handled by kinit."
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
self.session_cert = session_cert
|
| 141 |
+
self.session_verify = session_verify
|
| 142 |
+
|
| 143 |
+
self._connect()
|
| 144 |
+
|
| 145 |
+
self._fsid = f"webhdfs_{tokenize(host, port)}"
|
| 146 |
+
|
| 147 |
+
@property
|
| 148 |
+
def fsid(self):
|
| 149 |
+
return self._fsid
|
| 150 |
+
|
| 151 |
+
def _connect(self):
|
| 152 |
+
self.session = requests.Session()
|
| 153 |
+
|
| 154 |
+
if self.session_cert:
|
| 155 |
+
self.session.cert = self.session_cert
|
| 156 |
+
|
| 157 |
+
self.session.verify = self.session_verify
|
| 158 |
+
|
| 159 |
+
if self.kerb:
|
| 160 |
+
from requests_kerberos import HTTPKerberosAuth
|
| 161 |
+
|
| 162 |
+
self.session.auth = HTTPKerberosAuth(**self.kerb_kwargs)
|
| 163 |
+
|
| 164 |
+
if self.user is not None and self.password is not None:
|
| 165 |
+
from requests.auth import HTTPBasicAuth
|
| 166 |
+
|
| 167 |
+
self.session.auth = HTTPBasicAuth(self.user, self.password)
|
| 168 |
+
|
| 169 |
+
def _call(self, op, method="get", path=None, data=None, redirect=True, **kwargs):
|
| 170 |
+
path = self._strip_protocol(path) if path is not None else ""
|
| 171 |
+
url = self._apply_proxy(self.url + quote(path, safe="/="))
|
| 172 |
+
args = kwargs.copy()
|
| 173 |
+
args.update(self.pars)
|
| 174 |
+
args["op"] = op.upper()
|
| 175 |
+
logger.debug("sending %s with %s", url, method)
|
| 176 |
+
out = self.session.request(
|
| 177 |
+
method=method.upper(),
|
| 178 |
+
url=url,
|
| 179 |
+
params=args,
|
| 180 |
+
data=data,
|
| 181 |
+
allow_redirects=redirect,
|
| 182 |
+
)
|
| 183 |
+
if out.status_code in [400, 401, 403, 404, 500]:
|
| 184 |
+
try:
|
| 185 |
+
err = out.json()
|
| 186 |
+
msg = err["RemoteException"]["message"]
|
| 187 |
+
exp = err["RemoteException"]["exception"]
|
| 188 |
+
except (ValueError, KeyError):
|
| 189 |
+
pass
|
| 190 |
+
else:
|
| 191 |
+
if exp in ["IllegalArgumentException", "UnsupportedOperationException"]:
|
| 192 |
+
raise ValueError(msg)
|
| 193 |
+
elif exp in ["SecurityException", "AccessControlException"]:
|
| 194 |
+
raise PermissionError(msg)
|
| 195 |
+
elif exp in ["FileNotFoundException"]:
|
| 196 |
+
raise FileNotFoundError(msg)
|
| 197 |
+
else:
|
| 198 |
+
raise RuntimeError(msg)
|
| 199 |
+
out.raise_for_status()
|
| 200 |
+
return out
|
| 201 |
+
|
| 202 |
+
def _open(
|
| 203 |
+
self,
|
| 204 |
+
path,
|
| 205 |
+
mode="rb",
|
| 206 |
+
block_size=None,
|
| 207 |
+
autocommit=True,
|
| 208 |
+
replication=None,
|
| 209 |
+
permissions=None,
|
| 210 |
+
**kwargs,
|
| 211 |
+
):
|
| 212 |
+
"""
|
| 213 |
+
|
| 214 |
+
Parameters
|
| 215 |
+
----------
|
| 216 |
+
path: str
|
| 217 |
+
File location
|
| 218 |
+
mode: str
|
| 219 |
+
'rb', 'wb', etc.
|
| 220 |
+
block_size: int
|
| 221 |
+
Client buffer size for read-ahead or write buffer
|
| 222 |
+
autocommit: bool
|
| 223 |
+
If False, writes to temporary file that only gets put in final
|
| 224 |
+
location upon commit
|
| 225 |
+
replication: int
|
| 226 |
+
Number of copies of file on the cluster, write mode only
|
| 227 |
+
permissions: str or int
|
| 228 |
+
posix permissions, write mode only
|
| 229 |
+
kwargs
|
| 230 |
+
|
| 231 |
+
Returns
|
| 232 |
+
-------
|
| 233 |
+
WebHDFile instance
|
| 234 |
+
"""
|
| 235 |
+
block_size = block_size or self.blocksize
|
| 236 |
+
return WebHDFile(
|
| 237 |
+
self,
|
| 238 |
+
path,
|
| 239 |
+
mode=mode,
|
| 240 |
+
block_size=block_size,
|
| 241 |
+
tempdir=self.tempdir,
|
| 242 |
+
autocommit=autocommit,
|
| 243 |
+
replication=replication,
|
| 244 |
+
permissions=permissions,
|
| 245 |
+
)
|
| 246 |
+
|
| 247 |
+
@staticmethod
|
| 248 |
+
def _process_info(info):
|
| 249 |
+
info["type"] = info["type"].lower()
|
| 250 |
+
info["size"] = info["length"]
|
| 251 |
+
return info
|
| 252 |
+
|
| 253 |
+
@classmethod
|
| 254 |
+
def _strip_protocol(cls, path):
|
| 255 |
+
return infer_storage_options(path)["path"]
|
| 256 |
+
|
| 257 |
+
@staticmethod
|
| 258 |
+
def _get_kwargs_from_urls(urlpath):
|
| 259 |
+
out = infer_storage_options(urlpath)
|
| 260 |
+
out.pop("path", None)
|
| 261 |
+
out.pop("protocol", None)
|
| 262 |
+
if "username" in out:
|
| 263 |
+
out["user"] = out.pop("username")
|
| 264 |
+
return out
|
| 265 |
+
|
| 266 |
+
def info(self, path):
|
| 267 |
+
out = self._call("GETFILESTATUS", path=path)
|
| 268 |
+
info = out.json()["FileStatus"]
|
| 269 |
+
info["name"] = path
|
| 270 |
+
return self._process_info(info)
|
| 271 |
+
|
| 272 |
+
def created(self, path):
|
| 273 |
+
"""Return the created timestamp of a file as a datetime.datetime"""
|
| 274 |
+
# The API does not provide creation time, so we use modification time
|
| 275 |
+
info = self.info(path)
|
| 276 |
+
mtime = info.get("modificationTime", None)
|
| 277 |
+
if mtime is not None:
|
| 278 |
+
return datetime.fromtimestamp(mtime / 1000)
|
| 279 |
+
raise RuntimeError("Could not retrieve creation time (modification time).")
|
| 280 |
+
|
| 281 |
+
def modified(self, path):
|
| 282 |
+
"""Return the modified timestamp of a file as a datetime.datetime"""
|
| 283 |
+
info = self.info(path)
|
| 284 |
+
mtime = info.get("modificationTime", None)
|
| 285 |
+
if mtime is not None:
|
| 286 |
+
return datetime.fromtimestamp(mtime / 1000)
|
| 287 |
+
raise RuntimeError("Could not retrieve modification time.")
|
| 288 |
+
|
| 289 |
+
def ls(self, path, detail=False, **kwargs):
|
| 290 |
+
out = self._call("LISTSTATUS", path=path)
|
| 291 |
+
infos = out.json()["FileStatuses"]["FileStatus"]
|
| 292 |
+
for info in infos:
|
| 293 |
+
self._process_info(info)
|
| 294 |
+
info["name"] = path.rstrip("/") + "/" + info["pathSuffix"]
|
| 295 |
+
if detail:
|
| 296 |
+
return sorted(infos, key=lambda i: i["name"])
|
| 297 |
+
else:
|
| 298 |
+
return sorted(info["name"] for info in infos)
|
| 299 |
+
|
| 300 |
+
def content_summary(self, path):
|
| 301 |
+
"""Total numbers of files, directories and bytes under path"""
|
| 302 |
+
out = self._call("GETCONTENTSUMMARY", path=path)
|
| 303 |
+
return out.json()["ContentSummary"]
|
| 304 |
+
|
| 305 |
+
def ukey(self, path):
|
| 306 |
+
"""Checksum info of file, giving method and result"""
|
| 307 |
+
out = self._call("GETFILECHECKSUM", path=path, redirect=False)
|
| 308 |
+
if "Location" in out.headers:
|
| 309 |
+
location = self._apply_proxy(out.headers["Location"])
|
| 310 |
+
out2 = self.session.get(location)
|
| 311 |
+
out2.raise_for_status()
|
| 312 |
+
return out2.json()["FileChecksum"]
|
| 313 |
+
else:
|
| 314 |
+
out.raise_for_status()
|
| 315 |
+
return out.json()["FileChecksum"]
|
| 316 |
+
|
| 317 |
+
def home_directory(self):
|
| 318 |
+
"""Get user's home directory"""
|
| 319 |
+
out = self._call("GETHOMEDIRECTORY")
|
| 320 |
+
return out.json()["Path"]
|
| 321 |
+
|
| 322 |
+
def get_delegation_token(self, renewer=None):
|
| 323 |
+
"""Retrieve token which can give the same authority to other uses
|
| 324 |
+
|
| 325 |
+
Parameters
|
| 326 |
+
----------
|
| 327 |
+
renewer: str or None
|
| 328 |
+
User who may use this token; if None, will be current user
|
| 329 |
+
"""
|
| 330 |
+
if renewer:
|
| 331 |
+
out = self._call("GETDELEGATIONTOKEN", renewer=renewer)
|
| 332 |
+
else:
|
| 333 |
+
out = self._call("GETDELEGATIONTOKEN")
|
| 334 |
+
t = out.json()["Token"]
|
| 335 |
+
if t is None:
|
| 336 |
+
raise ValueError("No token available for this user/security context")
|
| 337 |
+
return t["urlString"]
|
| 338 |
+
|
| 339 |
+
def renew_delegation_token(self, token):
|
| 340 |
+
"""Make token live longer. Returns new expiry time"""
|
| 341 |
+
out = self._call("RENEWDELEGATIONTOKEN", method="put", token=token)
|
| 342 |
+
return out.json()["long"]
|
| 343 |
+
|
| 344 |
+
def cancel_delegation_token(self, token):
|
| 345 |
+
"""Stop the token from being useful"""
|
| 346 |
+
self._call("CANCELDELEGATIONTOKEN", method="put", token=token)
|
| 347 |
+
|
| 348 |
+
def chmod(self, path, mod):
|
| 349 |
+
"""Set the permission at path
|
| 350 |
+
|
| 351 |
+
Parameters
|
| 352 |
+
----------
|
| 353 |
+
path: str
|
| 354 |
+
location to set (file or directory)
|
| 355 |
+
mod: str or int
|
| 356 |
+
posix epresentation or permission, give as oct string, e.g, '777'
|
| 357 |
+
or 0o777
|
| 358 |
+
"""
|
| 359 |
+
self._call("SETPERMISSION", method="put", path=path, permission=mod)
|
| 360 |
+
|
| 361 |
+
def chown(self, path, owner=None, group=None):
|
| 362 |
+
"""Change owning user and/or group"""
|
| 363 |
+
kwargs = {}
|
| 364 |
+
if owner is not None:
|
| 365 |
+
kwargs["owner"] = owner
|
| 366 |
+
if group is not None:
|
| 367 |
+
kwargs["group"] = group
|
| 368 |
+
self._call("SETOWNER", method="put", path=path, **kwargs)
|
| 369 |
+
|
| 370 |
+
def set_replication(self, path, replication):
|
| 371 |
+
"""
|
| 372 |
+
Set file replication factor
|
| 373 |
+
|
| 374 |
+
Parameters
|
| 375 |
+
----------
|
| 376 |
+
path: str
|
| 377 |
+
File location (not for directories)
|
| 378 |
+
replication: int
|
| 379 |
+
Number of copies of file on the cluster. Should be smaller than
|
| 380 |
+
number of data nodes; normally 3 on most systems.
|
| 381 |
+
"""
|
| 382 |
+
self._call("SETREPLICATION", path=path, method="put", replication=replication)
|
| 383 |
+
|
| 384 |
+
def mkdir(self, path, **kwargs):
|
| 385 |
+
self._call("MKDIRS", method="put", path=path)
|
| 386 |
+
|
| 387 |
+
def makedirs(self, path, exist_ok=False):
|
| 388 |
+
if exist_ok is False and self.exists(path):
|
| 389 |
+
raise FileExistsError(path)
|
| 390 |
+
self.mkdir(path)
|
| 391 |
+
|
| 392 |
+
def mv(self, path1, path2, **kwargs):
|
| 393 |
+
self._call("RENAME", method="put", path=path1, destination=path2)
|
| 394 |
+
|
| 395 |
+
def rm(self, path, recursive=False, **kwargs):
|
| 396 |
+
self._call(
|
| 397 |
+
"DELETE",
|
| 398 |
+
method="delete",
|
| 399 |
+
path=path,
|
| 400 |
+
recursive="true" if recursive else "false",
|
| 401 |
+
)
|
| 402 |
+
|
| 403 |
+
def rm_file(self, path, **kwargs):
|
| 404 |
+
self.rm(path)
|
| 405 |
+
|
| 406 |
+
def cp_file(self, lpath, rpath, **kwargs):
|
| 407 |
+
with self.open(lpath) as lstream:
|
| 408 |
+
tmp_fname = "/".join([self._parent(rpath), f".tmp.{secrets.token_hex(16)}"])
|
| 409 |
+
# Perform an atomic copy (stream to a temporary file and
|
| 410 |
+
# move it to the actual destination).
|
| 411 |
+
try:
|
| 412 |
+
with self.open(tmp_fname, "wb") as rstream:
|
| 413 |
+
shutil.copyfileobj(lstream, rstream)
|
| 414 |
+
self.mv(tmp_fname, rpath)
|
| 415 |
+
except BaseException:
|
| 416 |
+
with suppress(FileNotFoundError):
|
| 417 |
+
self.rm(tmp_fname)
|
| 418 |
+
raise
|
| 419 |
+
|
| 420 |
+
def _apply_proxy(self, location):
|
| 421 |
+
if self.proxy and callable(self.proxy):
|
| 422 |
+
location = self.proxy(location)
|
| 423 |
+
elif self.proxy:
|
| 424 |
+
# as a dict
|
| 425 |
+
for k, v in self.proxy.items():
|
| 426 |
+
location = location.replace(k, v, 1)
|
| 427 |
+
return location
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
class WebHDFile(AbstractBufferedFile):
|
| 431 |
+
"""A file living in HDFS over webHDFS"""
|
| 432 |
+
|
| 433 |
+
def __init__(self, fs, path, **kwargs):
|
| 434 |
+
super().__init__(fs, path, **kwargs)
|
| 435 |
+
kwargs = kwargs.copy()
|
| 436 |
+
if kwargs.get("permissions", None) is None:
|
| 437 |
+
kwargs.pop("permissions", None)
|
| 438 |
+
if kwargs.get("replication", None) is None:
|
| 439 |
+
kwargs.pop("replication", None)
|
| 440 |
+
self.permissions = kwargs.pop("permissions", 511)
|
| 441 |
+
tempdir = kwargs.pop("tempdir")
|
| 442 |
+
if kwargs.pop("autocommit", False) is False:
|
| 443 |
+
self.target = self.path
|
| 444 |
+
self.path = os.path.join(tempdir, str(uuid.uuid4()))
|
| 445 |
+
|
| 446 |
+
def _upload_chunk(self, final=False):
|
| 447 |
+
"""Write one part of a multi-block file upload
|
| 448 |
+
|
| 449 |
+
Parameters
|
| 450 |
+
==========
|
| 451 |
+
final: bool
|
| 452 |
+
This is the last block, so should complete file, if
|
| 453 |
+
self.autocommit is True.
|
| 454 |
+
"""
|
| 455 |
+
out = self.fs.session.post(
|
| 456 |
+
self.location,
|
| 457 |
+
data=self.buffer.getvalue(),
|
| 458 |
+
headers={"content-type": "application/octet-stream"},
|
| 459 |
+
)
|
| 460 |
+
out.raise_for_status()
|
| 461 |
+
return True
|
| 462 |
+
|
| 463 |
+
def _initiate_upload(self):
|
| 464 |
+
"""Create remote file/upload"""
|
| 465 |
+
kwargs = self.kwargs.copy()
|
| 466 |
+
if "a" in self.mode:
|
| 467 |
+
op, method = "APPEND", "POST"
|
| 468 |
+
else:
|
| 469 |
+
op, method = "CREATE", "PUT"
|
| 470 |
+
kwargs["overwrite"] = "true"
|
| 471 |
+
out = self.fs._call(op, method, self.path, redirect=False, **kwargs)
|
| 472 |
+
location = self.fs._apply_proxy(out.headers["Location"])
|
| 473 |
+
if "w" in self.mode:
|
| 474 |
+
# create empty file to append to
|
| 475 |
+
out2 = self.fs.session.put(
|
| 476 |
+
location, headers={"content-type": "application/octet-stream"}
|
| 477 |
+
)
|
| 478 |
+
out2.raise_for_status()
|
| 479 |
+
# after creating empty file, change location to append to
|
| 480 |
+
out2 = self.fs._call("APPEND", "POST", self.path, redirect=False, **kwargs)
|
| 481 |
+
self.location = self.fs._apply_proxy(out2.headers["Location"])
|
| 482 |
+
|
| 483 |
+
def _fetch_range(self, start, end):
|
| 484 |
+
start = max(start, 0)
|
| 485 |
+
end = min(self.size, end)
|
| 486 |
+
if start >= end or start >= self.size:
|
| 487 |
+
return b""
|
| 488 |
+
out = self.fs._call(
|
| 489 |
+
"OPEN", path=self.path, offset=start, length=end - start, redirect=False
|
| 490 |
+
)
|
| 491 |
+
out.raise_for_status()
|
| 492 |
+
if "Location" in out.headers:
|
| 493 |
+
location = out.headers["Location"]
|
| 494 |
+
out2 = self.fs.session.get(self.fs._apply_proxy(location))
|
| 495 |
+
return out2.content
|
| 496 |
+
else:
|
| 497 |
+
return out.content
|
| 498 |
+
|
| 499 |
+
def commit(self):
|
| 500 |
+
self.fs.mv(self.path, self.target)
|
| 501 |
+
|
| 502 |
+
def discard(self):
|
| 503 |
+
self.fs.rm(self.path)
|
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/registry.py
ADDED
|
@@ -0,0 +1,337 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import importlib
|
| 4 |
+
import types
|
| 5 |
+
import warnings
|
| 6 |
+
|
| 7 |
+
__all__ = ["registry", "get_filesystem_class", "default"]
|
| 8 |
+
|
| 9 |
+
# internal, mutable
|
| 10 |
+
_registry: dict[str, type] = {}
|
| 11 |
+
|
| 12 |
+
# external, immutable
|
| 13 |
+
registry = types.MappingProxyType(_registry)
|
| 14 |
+
default = "file"
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def register_implementation(name, cls, clobber=False, errtxt=None):
|
| 18 |
+
"""Add implementation class to the registry
|
| 19 |
+
|
| 20 |
+
Parameters
|
| 21 |
+
----------
|
| 22 |
+
name: str
|
| 23 |
+
Protocol name to associate with the class
|
| 24 |
+
cls: class or str
|
| 25 |
+
if a class: fsspec-compliant implementation class (normally inherits from
|
| 26 |
+
``fsspec.AbstractFileSystem``, gets added straight to the registry. If a
|
| 27 |
+
str, the full path to an implementation class like package.module.class,
|
| 28 |
+
which gets added to known_implementations,
|
| 29 |
+
so the import is deferred until the filesystem is actually used.
|
| 30 |
+
clobber: bool (optional)
|
| 31 |
+
Whether to overwrite a protocol with the same name; if False, will raise
|
| 32 |
+
instead.
|
| 33 |
+
errtxt: str (optional)
|
| 34 |
+
If given, then a failure to import the given class will result in this
|
| 35 |
+
text being given.
|
| 36 |
+
"""
|
| 37 |
+
if isinstance(cls, str):
|
| 38 |
+
if name in known_implementations and clobber is False:
|
| 39 |
+
if cls != known_implementations[name]["class"]:
|
| 40 |
+
raise ValueError(
|
| 41 |
+
f"Name ({name}) already in the known_implementations and clobber "
|
| 42 |
+
f"is False"
|
| 43 |
+
)
|
| 44 |
+
else:
|
| 45 |
+
known_implementations[name] = {
|
| 46 |
+
"class": cls,
|
| 47 |
+
"err": errtxt or f"{cls} import failed for protocol {name}",
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
else:
|
| 51 |
+
if name in registry and clobber is False:
|
| 52 |
+
if _registry[name] is not cls:
|
| 53 |
+
raise ValueError(
|
| 54 |
+
f"Name ({name}) already in the registry and clobber is False"
|
| 55 |
+
)
|
| 56 |
+
else:
|
| 57 |
+
_registry[name] = cls
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
# protocols mapped to the class which implements them. This dict can be
|
| 61 |
+
# updated with register_implementation
|
| 62 |
+
known_implementations = {
|
| 63 |
+
"abfs": {
|
| 64 |
+
"class": "adlfs.AzureBlobFileSystem",
|
| 65 |
+
"err": "Install adlfs to access Azure Datalake Gen2 and Azure Blob Storage",
|
| 66 |
+
},
|
| 67 |
+
"adl": {
|
| 68 |
+
"class": "adlfs.AzureDatalakeFileSystem",
|
| 69 |
+
"err": (
|
| 70 |
+
"Azure Data Lake Storage Gen1 is retired and no longer supported. Please "
|
| 71 |
+
"install adlfs and use the `az://` protocol to access Azure Blob Storage "
|
| 72 |
+
"and Azure Data Lake Storage Gen2 instead."
|
| 73 |
+
),
|
| 74 |
+
},
|
| 75 |
+
"arrow_hdfs": {
|
| 76 |
+
"class": "fsspec.implementations.arrow.HadoopFileSystem",
|
| 77 |
+
"err": "pyarrow and local java libraries required for HDFS",
|
| 78 |
+
},
|
| 79 |
+
"async_wrapper": {
|
| 80 |
+
"class": "fsspec.implementations.asyn_wrapper.AsyncFileSystemWrapper",
|
| 81 |
+
},
|
| 82 |
+
"asynclocal": {
|
| 83 |
+
"class": "morefs.asyn_local.AsyncLocalFileSystem",
|
| 84 |
+
"err": "Install 'morefs[asynclocalfs]' to use AsyncLocalFileSystem",
|
| 85 |
+
},
|
| 86 |
+
"asyncwrapper": {
|
| 87 |
+
"class": "fsspec.implementations.asyn_wrapper.AsyncFileSystemWrapper",
|
| 88 |
+
},
|
| 89 |
+
"az": {
|
| 90 |
+
"class": "adlfs.AzureBlobFileSystem",
|
| 91 |
+
"err": "Install adlfs to access Azure Datalake Gen2 and Azure Blob Storage",
|
| 92 |
+
},
|
| 93 |
+
"blockcache": {"class": "fsspec.implementations.cached.CachingFileSystem"},
|
| 94 |
+
"box": {
|
| 95 |
+
"class": "boxfs.BoxFileSystem",
|
| 96 |
+
"err": "Please install boxfs to access BoxFileSystem",
|
| 97 |
+
},
|
| 98 |
+
"cached": {"class": "fsspec.implementations.cached.CachingFileSystem"},
|
| 99 |
+
"dask": {
|
| 100 |
+
"class": "fsspec.implementations.dask.DaskWorkerFileSystem",
|
| 101 |
+
"err": "Install dask distributed to access worker file system",
|
| 102 |
+
},
|
| 103 |
+
"data": {"class": "fsspec.implementations.data.DataFileSystem"},
|
| 104 |
+
"dbfs": {
|
| 105 |
+
"class": "fsspec.implementations.dbfs.DatabricksFileSystem",
|
| 106 |
+
"err": "Install the requests package to use the DatabricksFileSystem",
|
| 107 |
+
},
|
| 108 |
+
"dir": {"class": "fsspec.implementations.dirfs.DirFileSystem"},
|
| 109 |
+
"dropbox": {
|
| 110 |
+
"class": "dropboxdrivefs.DropboxDriveFileSystem",
|
| 111 |
+
"err": (
|
| 112 |
+
'DropboxFileSystem requires "dropboxdrivefs","requests" and "'
|
| 113 |
+
'"dropbox" to be installed'
|
| 114 |
+
),
|
| 115 |
+
},
|
| 116 |
+
"dvc": {
|
| 117 |
+
"class": "dvc.api.DVCFileSystem",
|
| 118 |
+
"err": "Install dvc to access DVCFileSystem",
|
| 119 |
+
},
|
| 120 |
+
"file": {"class": "fsspec.implementations.local.LocalFileSystem"},
|
| 121 |
+
"filecache": {"class": "fsspec.implementations.cached.WholeFileCacheFileSystem"},
|
| 122 |
+
"ftp": {"class": "fsspec.implementations.ftp.FTPFileSystem"},
|
| 123 |
+
"gcs": {
|
| 124 |
+
"class": "gcsfs.GCSFileSystem",
|
| 125 |
+
"err": "Please install gcsfs to access Google Storage",
|
| 126 |
+
},
|
| 127 |
+
"gdrive": {
|
| 128 |
+
"class": "gdrive_fsspec.GoogleDriveFileSystem",
|
| 129 |
+
"err": "Please install gdrive_fs for access to Google Drive",
|
| 130 |
+
},
|
| 131 |
+
"generic": {"class": "fsspec.generic.GenericFileSystem"},
|
| 132 |
+
"gist": {
|
| 133 |
+
"class": "fsspec.implementations.gist.GistFileSystem",
|
| 134 |
+
"err": "Install the requests package to use the gist FS",
|
| 135 |
+
},
|
| 136 |
+
"git": {
|
| 137 |
+
"class": "fsspec.implementations.git.GitFileSystem",
|
| 138 |
+
"err": "Install pygit2 to browse local git repos",
|
| 139 |
+
},
|
| 140 |
+
"github": {
|
| 141 |
+
"class": "fsspec.implementations.github.GithubFileSystem",
|
| 142 |
+
"err": "Install the requests package to use the github FS",
|
| 143 |
+
},
|
| 144 |
+
"gs": {
|
| 145 |
+
"class": "gcsfs.GCSFileSystem",
|
| 146 |
+
"err": "Please install gcsfs to access Google Storage",
|
| 147 |
+
},
|
| 148 |
+
"hdfs": {
|
| 149 |
+
"class": "fsspec.implementations.arrow.HadoopFileSystem",
|
| 150 |
+
"err": "pyarrow and local java libraries required for HDFS",
|
| 151 |
+
},
|
| 152 |
+
"hf": {
|
| 153 |
+
"class": "huggingface_hub.HfFileSystem",
|
| 154 |
+
"err": "Install huggingface_hub to access HfFileSystem",
|
| 155 |
+
},
|
| 156 |
+
"http": {
|
| 157 |
+
"class": "fsspec.implementations.http.HTTPFileSystem",
|
| 158 |
+
"err": 'HTTPFileSystem requires "requests" and "aiohttp" to be installed',
|
| 159 |
+
},
|
| 160 |
+
"https": {
|
| 161 |
+
"class": "fsspec.implementations.http.HTTPFileSystem",
|
| 162 |
+
"err": 'HTTPFileSystem requires "requests" and "aiohttp" to be installed',
|
| 163 |
+
},
|
| 164 |
+
"jlab": {
|
| 165 |
+
"class": "fsspec.implementations.jupyter.JupyterFileSystem",
|
| 166 |
+
"err": "Jupyter FS requires requests to be installed",
|
| 167 |
+
},
|
| 168 |
+
"jupyter": {
|
| 169 |
+
"class": "fsspec.implementations.jupyter.JupyterFileSystem",
|
| 170 |
+
"err": "Jupyter FS requires requests to be installed",
|
| 171 |
+
},
|
| 172 |
+
"lakefs": {
|
| 173 |
+
"class": "lakefs_spec.LakeFSFileSystem",
|
| 174 |
+
"err": "Please install lakefs-spec to access LakeFSFileSystem",
|
| 175 |
+
},
|
| 176 |
+
"libarchive": {
|
| 177 |
+
"class": "fsspec.implementations.libarchive.LibArchiveFileSystem",
|
| 178 |
+
"err": "LibArchive requires to be installed",
|
| 179 |
+
},
|
| 180 |
+
"local": {"class": "fsspec.implementations.local.LocalFileSystem"},
|
| 181 |
+
"memory": {"class": "fsspec.implementations.memory.MemoryFileSystem"},
|
| 182 |
+
"oci": {
|
| 183 |
+
"class": "ocifs.OCIFileSystem",
|
| 184 |
+
"err": "Install ocifs to access OCI Object Storage",
|
| 185 |
+
},
|
| 186 |
+
"ocilake": {
|
| 187 |
+
"class": "ocifs.OCIFileSystem",
|
| 188 |
+
"err": "Install ocifs to access OCI Data Lake",
|
| 189 |
+
},
|
| 190 |
+
"oss": {
|
| 191 |
+
"class": "ossfs.OSSFileSystem",
|
| 192 |
+
"err": "Install ossfs to access Alibaba Object Storage System",
|
| 193 |
+
},
|
| 194 |
+
"pyscript": {
|
| 195 |
+
"class": "pyscript_fsspec_client.client.PyscriptFileSystem",
|
| 196 |
+
"err": "This only runs in a pyscript context",
|
| 197 |
+
},
|
| 198 |
+
"reference": {"class": "fsspec.implementations.reference.ReferenceFileSystem"},
|
| 199 |
+
"root": {
|
| 200 |
+
"class": "fsspec_xrootd.XRootDFileSystem",
|
| 201 |
+
"err": (
|
| 202 |
+
"Install fsspec-xrootd to access xrootd storage system. "
|
| 203 |
+
"Note: 'root' is the protocol name for xrootd storage systems, "
|
| 204 |
+
"not referring to root directories"
|
| 205 |
+
),
|
| 206 |
+
},
|
| 207 |
+
"s3": {"class": "s3fs.S3FileSystem", "err": "Install s3fs to access S3"},
|
| 208 |
+
"s3a": {"class": "s3fs.S3FileSystem", "err": "Install s3fs to access S3"},
|
| 209 |
+
"sftp": {
|
| 210 |
+
"class": "fsspec.implementations.sftp.SFTPFileSystem",
|
| 211 |
+
"err": 'SFTPFileSystem requires "paramiko" to be installed',
|
| 212 |
+
},
|
| 213 |
+
"simplecache": {"class": "fsspec.implementations.cached.SimpleCacheFileSystem"},
|
| 214 |
+
"smb": {
|
| 215 |
+
"class": "fsspec.implementations.smb.SMBFileSystem",
|
| 216 |
+
"err": 'SMB requires "smbprotocol" or "smbprotocol[kerberos]" installed',
|
| 217 |
+
},
|
| 218 |
+
"ssh": {
|
| 219 |
+
"class": "fsspec.implementations.sftp.SFTPFileSystem",
|
| 220 |
+
"err": 'SFTPFileSystem requires "paramiko" to be installed',
|
| 221 |
+
},
|
| 222 |
+
"tar": {"class": "fsspec.implementations.tar.TarFileSystem"},
|
| 223 |
+
"tos": {
|
| 224 |
+
"class": "tosfs.TosFileSystem",
|
| 225 |
+
"err": "Install tosfs to access ByteDance volcano engine Tinder Object Storage",
|
| 226 |
+
},
|
| 227 |
+
"tosfs": {
|
| 228 |
+
"class": "tosfs.TosFileSystem",
|
| 229 |
+
"err": "Install tosfs to access ByteDance volcano engine Tinder Object Storage",
|
| 230 |
+
},
|
| 231 |
+
"wandb": {"class": "wandbfs.WandbFS", "err": "Install wandbfs to access wandb"},
|
| 232 |
+
"webdav": {
|
| 233 |
+
"class": "webdav4.fsspec.WebdavFileSystem",
|
| 234 |
+
"err": "Install webdav4 to access WebDAV",
|
| 235 |
+
},
|
| 236 |
+
"webhdfs": {
|
| 237 |
+
"class": "fsspec.implementations.webhdfs.WebHDFS",
|
| 238 |
+
"err": 'webHDFS access requires "requests" to be installed',
|
| 239 |
+
},
|
| 240 |
+
"zip": {"class": "fsspec.implementations.zip.ZipFileSystem"},
|
| 241 |
+
}
|
| 242 |
+
|
| 243 |
+
assert list(known_implementations) == sorted(known_implementations), (
|
| 244 |
+
"Not in alphabetical order"
|
| 245 |
+
)
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def get_filesystem_class(protocol):
|
| 249 |
+
"""Fetch named protocol implementation from the registry
|
| 250 |
+
|
| 251 |
+
The dict ``known_implementations`` maps protocol names to the locations
|
| 252 |
+
of classes implementing the corresponding file-system. When used for the
|
| 253 |
+
first time, appropriate imports will happen and the class will be placed in
|
| 254 |
+
the registry. All subsequent calls will fetch directly from the registry.
|
| 255 |
+
|
| 256 |
+
Some protocol implementations require additional dependencies, and so the
|
| 257 |
+
import may fail. In this case, the string in the "err" field of the
|
| 258 |
+
``known_implementations`` will be given as the error message.
|
| 259 |
+
"""
|
| 260 |
+
if not protocol:
|
| 261 |
+
protocol = default
|
| 262 |
+
|
| 263 |
+
if protocol not in registry:
|
| 264 |
+
if protocol not in known_implementations:
|
| 265 |
+
raise ValueError(f"Protocol not known: {protocol}")
|
| 266 |
+
bit = known_implementations[protocol]
|
| 267 |
+
try:
|
| 268 |
+
register_implementation(protocol, _import_class(bit["class"]))
|
| 269 |
+
except ImportError as e:
|
| 270 |
+
raise ImportError(bit.get("err")) from e
|
| 271 |
+
cls = registry[protocol]
|
| 272 |
+
if getattr(cls, "protocol", None) in ("abstract", None):
|
| 273 |
+
cls.protocol = protocol
|
| 274 |
+
|
| 275 |
+
return cls
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
s3_msg = """Your installed version of s3fs is very old and known to cause
|
| 279 |
+
severe performance issues, see also https://github.com/dask/dask/issues/10276
|
| 280 |
+
|
| 281 |
+
To fix, you should specify a lower version bound on s3fs, or
|
| 282 |
+
update the current installation.
|
| 283 |
+
"""
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def _import_class(fqp: str):
|
| 287 |
+
"""Take a fully-qualified path and return the imported class or identifier.
|
| 288 |
+
|
| 289 |
+
``fqp`` is of the form "package.module.klass" or
|
| 290 |
+
"package.module:subobject.klass".
|
| 291 |
+
|
| 292 |
+
Warnings
|
| 293 |
+
--------
|
| 294 |
+
This can import arbitrary modules. Make sure you haven't installed any modules
|
| 295 |
+
that may execute malicious code at import time.
|
| 296 |
+
"""
|
| 297 |
+
if ":" in fqp:
|
| 298 |
+
mod, name = fqp.rsplit(":", 1)
|
| 299 |
+
else:
|
| 300 |
+
mod, name = fqp.rsplit(".", 1)
|
| 301 |
+
|
| 302 |
+
is_s3 = mod == "s3fs"
|
| 303 |
+
mod = importlib.import_module(mod)
|
| 304 |
+
if is_s3 and mod.__version__.split(".") < ["0", "5"]:
|
| 305 |
+
warnings.warn(s3_msg)
|
| 306 |
+
for part in name.split("."):
|
| 307 |
+
mod = getattr(mod, part)
|
| 308 |
+
|
| 309 |
+
if not isinstance(mod, type):
|
| 310 |
+
raise TypeError(f"{fqp} is not a class")
|
| 311 |
+
|
| 312 |
+
return mod
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
def filesystem(protocol, **storage_options):
|
| 316 |
+
"""Instantiate filesystems for given protocol and arguments
|
| 317 |
+
|
| 318 |
+
``storage_options`` are specific to the protocol being chosen, and are
|
| 319 |
+
passed directly to the class.
|
| 320 |
+
"""
|
| 321 |
+
if protocol == "arrow_hdfs":
|
| 322 |
+
warnings.warn(
|
| 323 |
+
"The 'arrow_hdfs' protocol has been deprecated and will be "
|
| 324 |
+
"removed in the future. Specify it as 'hdfs'.",
|
| 325 |
+
DeprecationWarning,
|
| 326 |
+
)
|
| 327 |
+
|
| 328 |
+
cls = get_filesystem_class(protocol)
|
| 329 |
+
return cls(**storage_options)
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
def available_protocols():
|
| 333 |
+
"""Return a list of the implemented protocols.
|
| 334 |
+
|
| 335 |
+
Note that any given protocol may require extra packages to be importable.
|
| 336 |
+
"""
|
| 337 |
+
return list(known_implementations)
|
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/tests/abstract/__init__.py
ADDED
|
@@ -0,0 +1,290 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from hashlib import md5
|
| 3 |
+
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
from fsspec.implementations.local import LocalFileSystem
|
| 7 |
+
from fsspec.tests.abstract.copy import AbstractCopyTests # noqa: F401
|
| 8 |
+
from fsspec.tests.abstract.get import AbstractGetTests # noqa: F401
|
| 9 |
+
from fsspec.tests.abstract.open import AbstractOpenTests # noqa: F401
|
| 10 |
+
from fsspec.tests.abstract.pipe import AbstractPipeTests # noqa: F401
|
| 11 |
+
from fsspec.tests.abstract.put import AbstractPutTests # noqa: F401
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class BaseAbstractFixtures:
|
| 15 |
+
"""
|
| 16 |
+
Abstract base class containing fixtures that are used by but never need to
|
| 17 |
+
be overridden in derived filesystem-specific classes to run the abstract
|
| 18 |
+
tests on such filesystems.
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
@pytest.fixture
|
| 22 |
+
def fs_bulk_operations_scenario_0(self, fs, fs_join, fs_path):
|
| 23 |
+
"""
|
| 24 |
+
Scenario on remote filesystem that is used for many cp/get/put tests.
|
| 25 |
+
|
| 26 |
+
Cleans up at the end of each test it which it is used.
|
| 27 |
+
"""
|
| 28 |
+
source = self._bulk_operations_scenario_0(fs, fs_join, fs_path)
|
| 29 |
+
yield source
|
| 30 |
+
fs.rm(source, recursive=True)
|
| 31 |
+
|
| 32 |
+
@pytest.fixture
|
| 33 |
+
def fs_glob_edge_cases_files(self, fs, fs_join, fs_path):
|
| 34 |
+
"""
|
| 35 |
+
Scenario on remote filesystem that is used for glob edge cases cp/get/put tests.
|
| 36 |
+
|
| 37 |
+
Cleans up at the end of each test it which it is used.
|
| 38 |
+
"""
|
| 39 |
+
source = self._glob_edge_cases_files(fs, fs_join, fs_path)
|
| 40 |
+
yield source
|
| 41 |
+
fs.rm(source, recursive=True)
|
| 42 |
+
|
| 43 |
+
@pytest.fixture
|
| 44 |
+
def fs_dir_and_file_with_same_name_prefix(self, fs, fs_join, fs_path):
|
| 45 |
+
"""
|
| 46 |
+
Scenario on remote filesystem that is used to check cp/get/put on directory
|
| 47 |
+
and file with the same name prefixes.
|
| 48 |
+
|
| 49 |
+
Cleans up at the end of each test it which it is used.
|
| 50 |
+
"""
|
| 51 |
+
source = self._dir_and_file_with_same_name_prefix(fs, fs_join, fs_path)
|
| 52 |
+
yield source
|
| 53 |
+
fs.rm(source, recursive=True)
|
| 54 |
+
|
| 55 |
+
@pytest.fixture
|
| 56 |
+
def fs_10_files_with_hashed_names(self, fs, fs_join, fs_path):
|
| 57 |
+
"""
|
| 58 |
+
Scenario on remote filesystem that is used to check cp/get/put files order
|
| 59 |
+
when source and destination are lists.
|
| 60 |
+
|
| 61 |
+
Cleans up at the end of each test it which it is used.
|
| 62 |
+
"""
|
| 63 |
+
source = self._10_files_with_hashed_names(fs, fs_join, fs_path)
|
| 64 |
+
yield source
|
| 65 |
+
fs.rm(source, recursive=True)
|
| 66 |
+
|
| 67 |
+
@pytest.fixture
|
| 68 |
+
def fs_target(self, fs, fs_join, fs_path):
|
| 69 |
+
"""
|
| 70 |
+
Return name of remote directory that does not yet exist to copy into.
|
| 71 |
+
|
| 72 |
+
Cleans up at the end of each test it which it is used.
|
| 73 |
+
"""
|
| 74 |
+
target = fs_join(fs_path, "target")
|
| 75 |
+
yield target
|
| 76 |
+
if fs.exists(target):
|
| 77 |
+
fs.rm(target, recursive=True)
|
| 78 |
+
|
| 79 |
+
@pytest.fixture
|
| 80 |
+
def local_bulk_operations_scenario_0(self, local_fs, local_join, local_path):
|
| 81 |
+
"""
|
| 82 |
+
Scenario on local filesystem that is used for many cp/get/put tests.
|
| 83 |
+
|
| 84 |
+
Cleans up at the end of each test it which it is used.
|
| 85 |
+
"""
|
| 86 |
+
source = self._bulk_operations_scenario_0(local_fs, local_join, local_path)
|
| 87 |
+
yield source
|
| 88 |
+
local_fs.rm(source, recursive=True)
|
| 89 |
+
|
| 90 |
+
@pytest.fixture
|
| 91 |
+
def local_glob_edge_cases_files(self, local_fs, local_join, local_path):
|
| 92 |
+
"""
|
| 93 |
+
Scenario on local filesystem that is used for glob edge cases cp/get/put tests.
|
| 94 |
+
|
| 95 |
+
Cleans up at the end of each test it which it is used.
|
| 96 |
+
"""
|
| 97 |
+
source = self._glob_edge_cases_files(local_fs, local_join, local_path)
|
| 98 |
+
yield source
|
| 99 |
+
local_fs.rm(source, recursive=True)
|
| 100 |
+
|
| 101 |
+
@pytest.fixture
|
| 102 |
+
def local_dir_and_file_with_same_name_prefix(
|
| 103 |
+
self, local_fs, local_join, local_path
|
| 104 |
+
):
|
| 105 |
+
"""
|
| 106 |
+
Scenario on local filesystem that is used to check cp/get/put on directory
|
| 107 |
+
and file with the same name prefixes.
|
| 108 |
+
|
| 109 |
+
Cleans up at the end of each test it which it is used.
|
| 110 |
+
"""
|
| 111 |
+
source = self._dir_and_file_with_same_name_prefix(
|
| 112 |
+
local_fs, local_join, local_path
|
| 113 |
+
)
|
| 114 |
+
yield source
|
| 115 |
+
local_fs.rm(source, recursive=True)
|
| 116 |
+
|
| 117 |
+
@pytest.fixture
|
| 118 |
+
def local_10_files_with_hashed_names(self, local_fs, local_join, local_path):
|
| 119 |
+
"""
|
| 120 |
+
Scenario on local filesystem that is used to check cp/get/put files order
|
| 121 |
+
when source and destination are lists.
|
| 122 |
+
|
| 123 |
+
Cleans up at the end of each test it which it is used.
|
| 124 |
+
"""
|
| 125 |
+
source = self._10_files_with_hashed_names(local_fs, local_join, local_path)
|
| 126 |
+
yield source
|
| 127 |
+
local_fs.rm(source, recursive=True)
|
| 128 |
+
|
| 129 |
+
@pytest.fixture
|
| 130 |
+
def local_target(self, local_fs, local_join, local_path):
|
| 131 |
+
"""
|
| 132 |
+
Return name of local directory that does not yet exist to copy into.
|
| 133 |
+
|
| 134 |
+
Cleans up at the end of each test it which it is used.
|
| 135 |
+
"""
|
| 136 |
+
target = local_join(local_path, "target")
|
| 137 |
+
yield target
|
| 138 |
+
if local_fs.exists(target):
|
| 139 |
+
local_fs.rm(target, recursive=True)
|
| 140 |
+
|
| 141 |
+
def _glob_edge_cases_files(self, some_fs, some_join, some_path):
|
| 142 |
+
"""
|
| 143 |
+
Scenario that is used for glob edge cases cp/get/put tests.
|
| 144 |
+
Creates the following directory and file structure:
|
| 145 |
+
|
| 146 |
+
📁 source
|
| 147 |
+
├── 📄 file1
|
| 148 |
+
├── 📄 file2
|
| 149 |
+
├── 📁 subdir0
|
| 150 |
+
│ ├── 📄 subfile1
|
| 151 |
+
│ ├── 📄 subfile2
|
| 152 |
+
│ └── 📁 nesteddir
|
| 153 |
+
│ └── 📄 nestedfile
|
| 154 |
+
└── 📁 subdir1
|
| 155 |
+
├── 📄 subfile1
|
| 156 |
+
├── 📄 subfile2
|
| 157 |
+
└── 📁 nesteddir
|
| 158 |
+
└── 📄 nestedfile
|
| 159 |
+
"""
|
| 160 |
+
source = some_join(some_path, "source")
|
| 161 |
+
some_fs.touch(some_join(source, "file1"))
|
| 162 |
+
some_fs.touch(some_join(source, "file2"))
|
| 163 |
+
|
| 164 |
+
for subdir_idx in range(2):
|
| 165 |
+
subdir = some_join(source, f"subdir{subdir_idx}")
|
| 166 |
+
nesteddir = some_join(subdir, "nesteddir")
|
| 167 |
+
some_fs.makedirs(nesteddir)
|
| 168 |
+
some_fs.touch(some_join(subdir, "subfile1"))
|
| 169 |
+
some_fs.touch(some_join(subdir, "subfile2"))
|
| 170 |
+
some_fs.touch(some_join(nesteddir, "nestedfile"))
|
| 171 |
+
|
| 172 |
+
return source
|
| 173 |
+
|
| 174 |
+
def _bulk_operations_scenario_0(self, some_fs, some_join, some_path):
|
| 175 |
+
"""
|
| 176 |
+
Scenario that is used for many cp/get/put tests. Creates the following
|
| 177 |
+
directory and file structure:
|
| 178 |
+
|
| 179 |
+
📁 source
|
| 180 |
+
├── 📄 file1
|
| 181 |
+
├── 📄 file2
|
| 182 |
+
└── 📁 subdir
|
| 183 |
+
├── 📄 subfile1
|
| 184 |
+
├── 📄 subfile2
|
| 185 |
+
└── 📁 nesteddir
|
| 186 |
+
└── 📄 nestedfile
|
| 187 |
+
"""
|
| 188 |
+
source = some_join(some_path, "source")
|
| 189 |
+
subdir = some_join(source, "subdir")
|
| 190 |
+
nesteddir = some_join(subdir, "nesteddir")
|
| 191 |
+
some_fs.makedirs(nesteddir)
|
| 192 |
+
some_fs.touch(some_join(source, "file1"))
|
| 193 |
+
some_fs.touch(some_join(source, "file2"))
|
| 194 |
+
some_fs.touch(some_join(subdir, "subfile1"))
|
| 195 |
+
some_fs.touch(some_join(subdir, "subfile2"))
|
| 196 |
+
some_fs.touch(some_join(nesteddir, "nestedfile"))
|
| 197 |
+
return source
|
| 198 |
+
|
| 199 |
+
def _dir_and_file_with_same_name_prefix(self, some_fs, some_join, some_path):
|
| 200 |
+
"""
|
| 201 |
+
Scenario that is used to check cp/get/put on directory and file with
|
| 202 |
+
the same name prefixes. Creates the following directory and file structure:
|
| 203 |
+
|
| 204 |
+
📁 source
|
| 205 |
+
├── 📄 subdir.txt
|
| 206 |
+
└── 📁 subdir
|
| 207 |
+
└── 📄 subfile.txt
|
| 208 |
+
"""
|
| 209 |
+
source = some_join(some_path, "source")
|
| 210 |
+
subdir = some_join(source, "subdir")
|
| 211 |
+
file = some_join(source, "subdir.txt")
|
| 212 |
+
subfile = some_join(subdir, "subfile.txt")
|
| 213 |
+
some_fs.makedirs(subdir)
|
| 214 |
+
some_fs.touch(file)
|
| 215 |
+
some_fs.touch(subfile)
|
| 216 |
+
return source
|
| 217 |
+
|
| 218 |
+
def _10_files_with_hashed_names(self, some_fs, some_join, some_path):
|
| 219 |
+
"""
|
| 220 |
+
Scenario that is used to check cp/get/put files order when source and
|
| 221 |
+
destination are lists. Creates the following directory and file structure:
|
| 222 |
+
|
| 223 |
+
📁 source
|
| 224 |
+
└── 📄 {hashed([0-9])}.txt
|
| 225 |
+
"""
|
| 226 |
+
source = some_join(some_path, "source")
|
| 227 |
+
for i in range(10):
|
| 228 |
+
hashed_i = md5(str(i).encode("utf-8")).hexdigest()
|
| 229 |
+
path = some_join(source, f"{hashed_i}.txt")
|
| 230 |
+
some_fs.pipe(path=path, value=f"{i}".encode())
|
| 231 |
+
return source
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
class AbstractFixtures(BaseAbstractFixtures):
|
| 235 |
+
"""
|
| 236 |
+
Abstract base class containing fixtures that may be overridden in derived
|
| 237 |
+
filesystem-specific classes to run the abstract tests on such filesystems.
|
| 238 |
+
|
| 239 |
+
For any particular filesystem some of these fixtures must be overridden,
|
| 240 |
+
such as ``fs`` and ``fs_path``, and others may be overridden if the
|
| 241 |
+
default functions here are not appropriate, such as ``fs_join``.
|
| 242 |
+
"""
|
| 243 |
+
|
| 244 |
+
@pytest.fixture
|
| 245 |
+
def fs(self):
|
| 246 |
+
raise NotImplementedError("This function must be overridden in derived classes")
|
| 247 |
+
|
| 248 |
+
@pytest.fixture
|
| 249 |
+
def fs_join(self):
|
| 250 |
+
"""
|
| 251 |
+
Return a function that joins its arguments together into a path.
|
| 252 |
+
|
| 253 |
+
Most fsspec implementations join paths in a platform-dependent way,
|
| 254 |
+
but some will override this to always use a forward slash.
|
| 255 |
+
"""
|
| 256 |
+
return os.path.join
|
| 257 |
+
|
| 258 |
+
@pytest.fixture
|
| 259 |
+
def fs_path(self):
|
| 260 |
+
raise NotImplementedError("This function must be overridden in derived classes")
|
| 261 |
+
|
| 262 |
+
@pytest.fixture(scope="class")
|
| 263 |
+
@classmethod
|
| 264 |
+
def local_fs(cls):
|
| 265 |
+
# Maybe need an option for auto_mkdir=False? This is only relevant
|
| 266 |
+
# for certain implementations.
|
| 267 |
+
return LocalFileSystem(auto_mkdir=True)
|
| 268 |
+
|
| 269 |
+
@pytest.fixture
|
| 270 |
+
def local_join(self):
|
| 271 |
+
"""
|
| 272 |
+
Return a function that joins its arguments together into a path, on
|
| 273 |
+
the local filesystem.
|
| 274 |
+
"""
|
| 275 |
+
return os.path.join
|
| 276 |
+
|
| 277 |
+
@pytest.fixture
|
| 278 |
+
def local_path(self, tmpdir):
|
| 279 |
+
return tmpdir
|
| 280 |
+
|
| 281 |
+
@pytest.fixture
|
| 282 |
+
def supports_empty_directories(self):
|
| 283 |
+
"""
|
| 284 |
+
Return whether this implementation supports empty directories.
|
| 285 |
+
"""
|
| 286 |
+
return True
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
GLOB_EDGE_CASES_TESTS = {
|
| 2 |
+
"argnames": ("path", "recursive", "maxdepth", "expected"),
|
| 3 |
+
"argvalues": [
|
| 4 |
+
("fil?1", False, None, ["file1"]),
|
| 5 |
+
("fil?1", True, None, ["file1"]),
|
| 6 |
+
("file[1-2]", False, None, ["file1", "file2"]),
|
| 7 |
+
("file[1-2]", True, None, ["file1", "file2"]),
|
| 8 |
+
("*", False, None, ["file1", "file2"]),
|
| 9 |
+
(
|
| 10 |
+
"*",
|
| 11 |
+
True,
|
| 12 |
+
None,
|
| 13 |
+
[
|
| 14 |
+
"file1",
|
| 15 |
+
"file2",
|
| 16 |
+
"subdir0/subfile1",
|
| 17 |
+
"subdir0/subfile2",
|
| 18 |
+
"subdir0/nesteddir/nestedfile",
|
| 19 |
+
"subdir1/subfile1",
|
| 20 |
+
"subdir1/subfile2",
|
| 21 |
+
"subdir1/nesteddir/nestedfile",
|
| 22 |
+
],
|
| 23 |
+
),
|
| 24 |
+
("*", True, 1, ["file1", "file2"]),
|
| 25 |
+
(
|
| 26 |
+
"*",
|
| 27 |
+
True,
|
| 28 |
+
2,
|
| 29 |
+
[
|
| 30 |
+
"file1",
|
| 31 |
+
"file2",
|
| 32 |
+
"subdir0/subfile1",
|
| 33 |
+
"subdir0/subfile2",
|
| 34 |
+
"subdir1/subfile1",
|
| 35 |
+
"subdir1/subfile2",
|
| 36 |
+
],
|
| 37 |
+
),
|
| 38 |
+
("*1", False, None, ["file1"]),
|
| 39 |
+
(
|
| 40 |
+
"*1",
|
| 41 |
+
True,
|
| 42 |
+
None,
|
| 43 |
+
[
|
| 44 |
+
"file1",
|
| 45 |
+
"subdir1/subfile1",
|
| 46 |
+
"subdir1/subfile2",
|
| 47 |
+
"subdir1/nesteddir/nestedfile",
|
| 48 |
+
],
|
| 49 |
+
),
|
| 50 |
+
("*1", True, 2, ["file1", "subdir1/subfile1", "subdir1/subfile2"]),
|
| 51 |
+
(
|
| 52 |
+
"**",
|
| 53 |
+
False,
|
| 54 |
+
None,
|
| 55 |
+
[
|
| 56 |
+
"file1",
|
| 57 |
+
"file2",
|
| 58 |
+
"subdir0/subfile1",
|
| 59 |
+
"subdir0/subfile2",
|
| 60 |
+
"subdir0/nesteddir/nestedfile",
|
| 61 |
+
"subdir1/subfile1",
|
| 62 |
+
"subdir1/subfile2",
|
| 63 |
+
"subdir1/nesteddir/nestedfile",
|
| 64 |
+
],
|
| 65 |
+
),
|
| 66 |
+
(
|
| 67 |
+
"**",
|
| 68 |
+
True,
|
| 69 |
+
None,
|
| 70 |
+
[
|
| 71 |
+
"file1",
|
| 72 |
+
"file2",
|
| 73 |
+
"subdir0/subfile1",
|
| 74 |
+
"subdir0/subfile2",
|
| 75 |
+
"subdir0/nesteddir/nestedfile",
|
| 76 |
+
"subdir1/subfile1",
|
| 77 |
+
"subdir1/subfile2",
|
| 78 |
+
"subdir1/nesteddir/nestedfile",
|
| 79 |
+
],
|
| 80 |
+
),
|
| 81 |
+
("**", True, 1, ["file1", "file2"]),
|
| 82 |
+
(
|
| 83 |
+
"**",
|
| 84 |
+
True,
|
| 85 |
+
2,
|
| 86 |
+
[
|
| 87 |
+
"file1",
|
| 88 |
+
"file2",
|
| 89 |
+
"subdir0/subfile1",
|
| 90 |
+
"subdir0/subfile2",
|
| 91 |
+
"subdir0/nesteddir/nestedfile",
|
| 92 |
+
"subdir1/subfile1",
|
| 93 |
+
"subdir1/subfile2",
|
| 94 |
+
"subdir1/nesteddir/nestedfile",
|
| 95 |
+
],
|
| 96 |
+
),
|
| 97 |
+
(
|
| 98 |
+
"**",
|
| 99 |
+
False,
|
| 100 |
+
2,
|
| 101 |
+
[
|
| 102 |
+
"file1",
|
| 103 |
+
"file2",
|
| 104 |
+
"subdir0/subfile1",
|
| 105 |
+
"subdir0/subfile2",
|
| 106 |
+
"subdir1/subfile1",
|
| 107 |
+
"subdir1/subfile2",
|
| 108 |
+
],
|
| 109 |
+
),
|
| 110 |
+
("**/*1", False, None, ["file1", "subdir0/subfile1", "subdir1/subfile1"]),
|
| 111 |
+
(
|
| 112 |
+
"**/*1",
|
| 113 |
+
True,
|
| 114 |
+
None,
|
| 115 |
+
[
|
| 116 |
+
"file1",
|
| 117 |
+
"subdir0/subfile1",
|
| 118 |
+
"subdir1/subfile1",
|
| 119 |
+
"subdir1/subfile2",
|
| 120 |
+
"subdir1/nesteddir/nestedfile",
|
| 121 |
+
],
|
| 122 |
+
),
|
| 123 |
+
("**/*1", True, 1, ["file1"]),
|
| 124 |
+
(
|
| 125 |
+
"**/*1",
|
| 126 |
+
True,
|
| 127 |
+
2,
|
| 128 |
+
["file1", "subdir0/subfile1", "subdir1/subfile1", "subdir1/subfile2"],
|
| 129 |
+
),
|
| 130 |
+
("**/*1", False, 2, ["file1", "subdir0/subfile1", "subdir1/subfile1"]),
|
| 131 |
+
("**/subdir0", False, None, []),
|
| 132 |
+
("**/subdir0", True, None, ["subfile1", "subfile2", "nesteddir/nestedfile"]),
|
| 133 |
+
("**/subdir0/nested*", False, 2, []),
|
| 134 |
+
("**/subdir0/nested*", True, 2, ["nestedfile"]),
|
| 135 |
+
("subdir[1-2]", False, None, []),
|
| 136 |
+
("subdir[1-2]", True, None, ["subfile1", "subfile2", "nesteddir/nestedfile"]),
|
| 137 |
+
("subdir[1-2]", True, 2, ["subfile1", "subfile2"]),
|
| 138 |
+
("subdir[0-1]", False, None, []),
|
| 139 |
+
(
|
| 140 |
+
"subdir[0-1]",
|
| 141 |
+
True,
|
| 142 |
+
None,
|
| 143 |
+
[
|
| 144 |
+
"subdir0/subfile1",
|
| 145 |
+
"subdir0/subfile2",
|
| 146 |
+
"subdir0/nesteddir/nestedfile",
|
| 147 |
+
"subdir1/subfile1",
|
| 148 |
+
"subdir1/subfile2",
|
| 149 |
+
"subdir1/nesteddir/nestedfile",
|
| 150 |
+
],
|
| 151 |
+
),
|
| 152 |
+
(
|
| 153 |
+
"subdir[0-1]/*fil[e]*",
|
| 154 |
+
False,
|
| 155 |
+
None,
|
| 156 |
+
[
|
| 157 |
+
"subdir0/subfile1",
|
| 158 |
+
"subdir0/subfile2",
|
| 159 |
+
"subdir1/subfile1",
|
| 160 |
+
"subdir1/subfile2",
|
| 161 |
+
],
|
| 162 |
+
),
|
| 163 |
+
(
|
| 164 |
+
"subdir[0-1]/*fil[e]*",
|
| 165 |
+
True,
|
| 166 |
+
None,
|
| 167 |
+
[
|
| 168 |
+
"subdir0/subfile1",
|
| 169 |
+
"subdir0/subfile2",
|
| 170 |
+
"subdir1/subfile1",
|
| 171 |
+
"subdir1/subfile2",
|
| 172 |
+
],
|
| 173 |
+
),
|
| 174 |
+
],
|
| 175 |
+
}
|
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/tests/abstract/copy.py
ADDED
|
@@ -0,0 +1,557 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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| 10 |
+
def test_copy_file_to_existing_directory(
|
| 11 |
+
self,
|
| 12 |
+
fs,
|
| 13 |
+
fs_join,
|
| 14 |
+
fs_bulk_operations_scenario_0,
|
| 15 |
+
fs_target,
|
| 16 |
+
supports_empty_directories,
|
| 17 |
+
):
|
| 18 |
+
# Copy scenario 1a
|
| 19 |
+
source = fs_bulk_operations_scenario_0
|
| 20 |
+
|
| 21 |
+
target = fs_target
|
| 22 |
+
fs.mkdir(target)
|
| 23 |
+
if not supports_empty_directories:
|
| 24 |
+
# Force target directory to exist by adding a dummy file
|
| 25 |
+
fs.touch(fs_join(target, "dummy"))
|
| 26 |
+
assert fs.isdir(target)
|
| 27 |
+
|
| 28 |
+
target_file2 = fs_join(target, "file2")
|
| 29 |
+
target_subfile1 = fs_join(target, "subfile1")
|
| 30 |
+
|
| 31 |
+
# Copy from source directory
|
| 32 |
+
fs.cp(fs_join(source, "file2"), target)
|
| 33 |
+
assert fs.isfile(target_file2)
|
| 34 |
+
|
| 35 |
+
# Copy from sub directory
|
| 36 |
+
fs.cp(fs_join(source, "subdir", "subfile1"), target)
|
| 37 |
+
assert fs.isfile(target_subfile1)
|
| 38 |
+
|
| 39 |
+
# Remove copied files
|
| 40 |
+
fs.rm([target_file2, target_subfile1])
|
| 41 |
+
assert not fs.exists(target_file2)
|
| 42 |
+
assert not fs.exists(target_subfile1)
|
| 43 |
+
|
| 44 |
+
# Repeat with trailing slash on target
|
| 45 |
+
fs.cp(fs_join(source, "file2"), target + "/")
|
| 46 |
+
assert fs.isdir(target)
|
| 47 |
+
assert fs.isfile(target_file2)
|
| 48 |
+
|
| 49 |
+
fs.cp(fs_join(source, "subdir", "subfile1"), target + "/")
|
| 50 |
+
assert fs.isfile(target_subfile1)
|
| 51 |
+
|
| 52 |
+
def test_copy_file_to_new_directory(
|
| 53 |
+
self, fs, fs_join, fs_bulk_operations_scenario_0, fs_target
|
| 54 |
+
):
|
| 55 |
+
# Copy scenario 1b
|
| 56 |
+
source = fs_bulk_operations_scenario_0
|
| 57 |
+
|
| 58 |
+
target = fs_target
|
| 59 |
+
fs.mkdir(target)
|
| 60 |
+
|
| 61 |
+
fs.cp(
|
| 62 |
+
fs_join(source, "subdir", "subfile1"), fs_join(target, "newdir/")
|
| 63 |
+
) # Note trailing slash
|
| 64 |
+
assert fs.isdir(target)
|
| 65 |
+
assert fs.isdir(fs_join(target, "newdir"))
|
| 66 |
+
assert fs.isfile(fs_join(target, "newdir", "subfile1"))
|
| 67 |
+
|
| 68 |
+
def test_copy_file_to_file_in_existing_directory(
|
| 69 |
+
self,
|
| 70 |
+
fs,
|
| 71 |
+
fs_join,
|
| 72 |
+
fs_bulk_operations_scenario_0,
|
| 73 |
+
fs_target,
|
| 74 |
+
supports_empty_directories,
|
| 75 |
+
):
|
| 76 |
+
# Copy scenario 1c
|
| 77 |
+
source = fs_bulk_operations_scenario_0
|
| 78 |
+
|
| 79 |
+
target = fs_target
|
| 80 |
+
fs.mkdir(target)
|
| 81 |
+
if not supports_empty_directories:
|
| 82 |
+
# Force target directory to exist by adding a dummy file
|
| 83 |
+
fs.touch(fs_join(target, "dummy"))
|
| 84 |
+
assert fs.isdir(target)
|
| 85 |
+
|
| 86 |
+
fs.cp(fs_join(source, "subdir", "subfile1"), fs_join(target, "newfile"))
|
| 87 |
+
assert fs.isfile(fs_join(target, "newfile"))
|
| 88 |
+
|
| 89 |
+
def test_copy_file_to_file_in_new_directory(
|
| 90 |
+
self, fs, fs_join, fs_bulk_operations_scenario_0, fs_target
|
| 91 |
+
):
|
| 92 |
+
# Copy scenario 1d
|
| 93 |
+
source = fs_bulk_operations_scenario_0
|
| 94 |
+
|
| 95 |
+
target = fs_target
|
| 96 |
+
fs.mkdir(target)
|
| 97 |
+
|
| 98 |
+
fs.cp(
|
| 99 |
+
fs_join(source, "subdir", "subfile1"), fs_join(target, "newdir", "newfile")
|
| 100 |
+
)
|
| 101 |
+
assert fs.isdir(fs_join(target, "newdir"))
|
| 102 |
+
assert fs.isfile(fs_join(target, "newdir", "newfile"))
|
| 103 |
+
|
| 104 |
+
def test_copy_directory_to_existing_directory(
|
| 105 |
+
self,
|
| 106 |
+
fs,
|
| 107 |
+
fs_join,
|
| 108 |
+
fs_bulk_operations_scenario_0,
|
| 109 |
+
fs_target,
|
| 110 |
+
supports_empty_directories,
|
| 111 |
+
):
|
| 112 |
+
# Copy scenario 1e
|
| 113 |
+
source = fs_bulk_operations_scenario_0
|
| 114 |
+
|
| 115 |
+
target = fs_target
|
| 116 |
+
fs.mkdir(target)
|
| 117 |
+
if not supports_empty_directories:
|
| 118 |
+
# Force target directory to exist by adding a dummy file
|
| 119 |
+
dummy = fs_join(target, "dummy")
|
| 120 |
+
fs.touch(dummy)
|
| 121 |
+
assert fs.isdir(target)
|
| 122 |
+
|
| 123 |
+
for source_slash, target_slash in zip([False, True], [False, True]):
|
| 124 |
+
s = fs_join(source, "subdir")
|
| 125 |
+
if source_slash:
|
| 126 |
+
s += "/"
|
| 127 |
+
t = target + "/" if target_slash else target
|
| 128 |
+
|
| 129 |
+
# Without recursive does nothing
|
| 130 |
+
fs.cp(s, t)
|
| 131 |
+
assert fs.ls(target, detail=False) == (
|
| 132 |
+
[] if supports_empty_directories else [dummy]
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
# With recursive
|
| 136 |
+
fs.cp(s, t, recursive=True)
|
| 137 |
+
if source_slash:
|
| 138 |
+
assert fs.isfile(fs_join(target, "subfile1"))
|
| 139 |
+
assert fs.isfile(fs_join(target, "subfile2"))
|
| 140 |
+
assert fs.isdir(fs_join(target, "nesteddir"))
|
| 141 |
+
assert fs.isfile(fs_join(target, "nesteddir", "nestedfile"))
|
| 142 |
+
assert not fs.exists(fs_join(target, "subdir"))
|
| 143 |
+
|
| 144 |
+
fs.rm(
|
| 145 |
+
[
|
| 146 |
+
fs_join(target, "subfile1"),
|
| 147 |
+
fs_join(target, "subfile2"),
|
| 148 |
+
fs_join(target, "nesteddir"),
|
| 149 |
+
],
|
| 150 |
+
recursive=True,
|
| 151 |
+
)
|
| 152 |
+
else:
|
| 153 |
+
assert fs.isdir(fs_join(target, "subdir"))
|
| 154 |
+
assert fs.isfile(fs_join(target, "subdir", "subfile1"))
|
| 155 |
+
assert fs.isfile(fs_join(target, "subdir", "subfile2"))
|
| 156 |
+
assert fs.isdir(fs_join(target, "subdir", "nesteddir"))
|
| 157 |
+
assert fs.isfile(fs_join(target, "subdir", "nesteddir", "nestedfile"))
|
| 158 |
+
|
| 159 |
+
fs.rm(fs_join(target, "subdir"), recursive=True)
|
| 160 |
+
assert fs.ls(target, detail=False) == (
|
| 161 |
+
[] if supports_empty_directories else [dummy]
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
# Limit recursive by maxdepth
|
| 165 |
+
fs.cp(s, t, recursive=True, maxdepth=1)
|
| 166 |
+
if source_slash:
|
| 167 |
+
assert fs.isfile(fs_join(target, "subfile1"))
|
| 168 |
+
assert fs.isfile(fs_join(target, "subfile2"))
|
| 169 |
+
assert not fs.exists(fs_join(target, "nesteddir"))
|
| 170 |
+
assert not fs.exists(fs_join(target, "subdir"))
|
| 171 |
+
|
| 172 |
+
fs.rm(
|
| 173 |
+
[
|
| 174 |
+
fs_join(target, "subfile1"),
|
| 175 |
+
fs_join(target, "subfile2"),
|
| 176 |
+
],
|
| 177 |
+
recursive=True,
|
| 178 |
+
)
|
| 179 |
+
else:
|
| 180 |
+
assert fs.isdir(fs_join(target, "subdir"))
|
| 181 |
+
assert fs.isfile(fs_join(target, "subdir", "subfile1"))
|
| 182 |
+
assert fs.isfile(fs_join(target, "subdir", "subfile2"))
|
| 183 |
+
assert not fs.exists(fs_join(target, "subdir", "nesteddir"))
|
| 184 |
+
|
| 185 |
+
fs.rm(fs_join(target, "subdir"), recursive=True)
|
| 186 |
+
assert fs.ls(target, detail=False) == (
|
| 187 |
+
[] if supports_empty_directories else [dummy]
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
def test_copy_directory_to_new_directory(
|
| 191 |
+
self,
|
| 192 |
+
fs,
|
| 193 |
+
fs_join,
|
| 194 |
+
fs_bulk_operations_scenario_0,
|
| 195 |
+
fs_target,
|
| 196 |
+
supports_empty_directories,
|
| 197 |
+
):
|
| 198 |
+
# Copy scenario 1f
|
| 199 |
+
source = fs_bulk_operations_scenario_0
|
| 200 |
+
|
| 201 |
+
target = fs_target
|
| 202 |
+
fs.mkdir(target)
|
| 203 |
+
|
| 204 |
+
for source_slash, target_slash in zip([False, True], [False, True]):
|
| 205 |
+
s = fs_join(source, "subdir")
|
| 206 |
+
if source_slash:
|
| 207 |
+
s += "/"
|
| 208 |
+
t = fs_join(target, "newdir")
|
| 209 |
+
if target_slash:
|
| 210 |
+
t += "/"
|
| 211 |
+
|
| 212 |
+
# Without recursive does nothing
|
| 213 |
+
fs.cp(s, t)
|
| 214 |
+
if supports_empty_directories:
|
| 215 |
+
assert fs.ls(target) == []
|
| 216 |
+
else:
|
| 217 |
+
with pytest.raises(FileNotFoundError):
|
| 218 |
+
fs.ls(target)
|
| 219 |
+
|
| 220 |
+
# With recursive
|
| 221 |
+
fs.cp(s, t, recursive=True)
|
| 222 |
+
assert fs.isdir(fs_join(target, "newdir"))
|
| 223 |
+
assert fs.isfile(fs_join(target, "newdir", "subfile1"))
|
| 224 |
+
assert fs.isfile(fs_join(target, "newdir", "subfile2"))
|
| 225 |
+
assert fs.isdir(fs_join(target, "newdir", "nesteddir"))
|
| 226 |
+
assert fs.isfile(fs_join(target, "newdir", "nesteddir", "nestedfile"))
|
| 227 |
+
assert not fs.exists(fs_join(target, "subdir"))
|
| 228 |
+
|
| 229 |
+
fs.rm(fs_join(target, "newdir"), recursive=True)
|
| 230 |
+
assert not fs.exists(fs_join(target, "newdir"))
|
| 231 |
+
|
| 232 |
+
# Limit recursive by maxdepth
|
| 233 |
+
fs.cp(s, t, recursive=True, maxdepth=1)
|
| 234 |
+
assert fs.isdir(fs_join(target, "newdir"))
|
| 235 |
+
assert fs.isfile(fs_join(target, "newdir", "subfile1"))
|
| 236 |
+
assert fs.isfile(fs_join(target, "newdir", "subfile2"))
|
| 237 |
+
assert not fs.exists(fs_join(target, "newdir", "nesteddir"))
|
| 238 |
+
assert not fs.exists(fs_join(target, "subdir"))
|
| 239 |
+
|
| 240 |
+
fs.rm(fs_join(target, "newdir"), recursive=True)
|
| 241 |
+
assert not fs.exists(fs_join(target, "newdir"))
|
| 242 |
+
|
| 243 |
+
def test_copy_glob_to_existing_directory(
|
| 244 |
+
self,
|
| 245 |
+
fs,
|
| 246 |
+
fs_join,
|
| 247 |
+
fs_bulk_operations_scenario_0,
|
| 248 |
+
fs_target,
|
| 249 |
+
supports_empty_directories,
|
| 250 |
+
):
|
| 251 |
+
# Copy scenario 1g
|
| 252 |
+
source = fs_bulk_operations_scenario_0
|
| 253 |
+
|
| 254 |
+
target = fs_target
|
| 255 |
+
fs.mkdir(target)
|
| 256 |
+
if not supports_empty_directories:
|
| 257 |
+
# Force target directory to exist by adding a dummy file
|
| 258 |
+
dummy = fs_join(target, "dummy")
|
| 259 |
+
fs.touch(dummy)
|
| 260 |
+
assert fs.isdir(target)
|
| 261 |
+
|
| 262 |
+
for target_slash in [False, True]:
|
| 263 |
+
t = target + "/" if target_slash else target
|
| 264 |
+
|
| 265 |
+
# Without recursive
|
| 266 |
+
fs.cp(fs_join(source, "subdir", "*"), t)
|
| 267 |
+
assert fs.isfile(fs_join(target, "subfile1"))
|
| 268 |
+
assert fs.isfile(fs_join(target, "subfile2"))
|
| 269 |
+
assert not fs.isdir(fs_join(target, "nesteddir"))
|
| 270 |
+
assert not fs.exists(fs_join(target, "nesteddir", "nestedfile"))
|
| 271 |
+
assert not fs.exists(fs_join(target, "subdir"))
|
| 272 |
+
|
| 273 |
+
fs.rm(
|
| 274 |
+
[
|
| 275 |
+
fs_join(target, "subfile1"),
|
| 276 |
+
fs_join(target, "subfile2"),
|
| 277 |
+
],
|
| 278 |
+
recursive=True,
|
| 279 |
+
)
|
| 280 |
+
assert fs.ls(target, detail=False) == (
|
| 281 |
+
[] if supports_empty_directories else [dummy]
|
| 282 |
+
)
|
| 283 |
+
|
| 284 |
+
# With recursive
|
| 285 |
+
for glob, recursive in zip(["*", "**"], [True, False]):
|
| 286 |
+
fs.cp(fs_join(source, "subdir", glob), t, recursive=recursive)
|
| 287 |
+
assert fs.isfile(fs_join(target, "subfile1"))
|
| 288 |
+
assert fs.isfile(fs_join(target, "subfile2"))
|
| 289 |
+
assert fs.isdir(fs_join(target, "nesteddir"))
|
| 290 |
+
assert fs.isfile(fs_join(target, "nesteddir", "nestedfile"))
|
| 291 |
+
assert not fs.exists(fs_join(target, "subdir"))
|
| 292 |
+
|
| 293 |
+
fs.rm(
|
| 294 |
+
[
|
| 295 |
+
fs_join(target, "subfile1"),
|
| 296 |
+
fs_join(target, "subfile2"),
|
| 297 |
+
fs_join(target, "nesteddir"),
|
| 298 |
+
],
|
| 299 |
+
recursive=True,
|
| 300 |
+
)
|
| 301 |
+
assert fs.ls(target, detail=False) == (
|
| 302 |
+
[] if supports_empty_directories else [dummy]
|
| 303 |
+
)
|
| 304 |
+
|
| 305 |
+
# Limit recursive by maxdepth
|
| 306 |
+
fs.cp(
|
| 307 |
+
fs_join(source, "subdir", glob), t, recursive=recursive, maxdepth=1
|
| 308 |
+
)
|
| 309 |
+
assert fs.isfile(fs_join(target, "subfile1"))
|
| 310 |
+
assert fs.isfile(fs_join(target, "subfile2"))
|
| 311 |
+
assert not fs.exists(fs_join(target, "nesteddir"))
|
| 312 |
+
assert not fs.exists(fs_join(target, "subdir"))
|
| 313 |
+
|
| 314 |
+
fs.rm(
|
| 315 |
+
[
|
| 316 |
+
fs_join(target, "subfile1"),
|
| 317 |
+
fs_join(target, "subfile2"),
|
| 318 |
+
],
|
| 319 |
+
recursive=True,
|
| 320 |
+
)
|
| 321 |
+
assert fs.ls(target, detail=False) == (
|
| 322 |
+
[] if supports_empty_directories else [dummy]
|
| 323 |
+
)
|
| 324 |
+
|
| 325 |
+
def test_copy_glob_to_new_directory(
|
| 326 |
+
self, fs, fs_join, fs_bulk_operations_scenario_0, fs_target
|
| 327 |
+
):
|
| 328 |
+
# Copy scenario 1h
|
| 329 |
+
source = fs_bulk_operations_scenario_0
|
| 330 |
+
|
| 331 |
+
target = fs_target
|
| 332 |
+
fs.mkdir(target)
|
| 333 |
+
|
| 334 |
+
for target_slash in [False, True]:
|
| 335 |
+
t = fs_join(target, "newdir")
|
| 336 |
+
if target_slash:
|
| 337 |
+
t += "/"
|
| 338 |
+
|
| 339 |
+
# Without recursive
|
| 340 |
+
fs.cp(fs_join(source, "subdir", "*"), t)
|
| 341 |
+
assert fs.isdir(fs_join(target, "newdir"))
|
| 342 |
+
assert fs.isfile(fs_join(target, "newdir", "subfile1"))
|
| 343 |
+
assert fs.isfile(fs_join(target, "newdir", "subfile2"))
|
| 344 |
+
assert not fs.exists(fs_join(target, "newdir", "nesteddir"))
|
| 345 |
+
assert not fs.exists(fs_join(target, "newdir", "nesteddir", "nestedfile"))
|
| 346 |
+
assert not fs.exists(fs_join(target, "subdir"))
|
| 347 |
+
assert not fs.exists(fs_join(target, "newdir", "subdir"))
|
| 348 |
+
|
| 349 |
+
fs.rm(fs_join(target, "newdir"), recursive=True)
|
| 350 |
+
assert not fs.exists(fs_join(target, "newdir"))
|
| 351 |
+
|
| 352 |
+
# With recursive
|
| 353 |
+
for glob, recursive in zip(["*", "**"], [True, False]):
|
| 354 |
+
fs.cp(fs_join(source, "subdir", glob), t, recursive=recursive)
|
| 355 |
+
assert fs.isdir(fs_join(target, "newdir"))
|
| 356 |
+
assert fs.isfile(fs_join(target, "newdir", "subfile1"))
|
| 357 |
+
assert fs.isfile(fs_join(target, "newdir", "subfile2"))
|
| 358 |
+
assert fs.isdir(fs_join(target, "newdir", "nesteddir"))
|
| 359 |
+
assert fs.isfile(fs_join(target, "newdir", "nesteddir", "nestedfile"))
|
| 360 |
+
assert not fs.exists(fs_join(target, "subdir"))
|
| 361 |
+
assert not fs.exists(fs_join(target, "newdir", "subdir"))
|
| 362 |
+
|
| 363 |
+
fs.rm(fs_join(target, "newdir"), recursive=True)
|
| 364 |
+
assert not fs.exists(fs_join(target, "newdir"))
|
| 365 |
+
|
| 366 |
+
# Limit recursive by maxdepth
|
| 367 |
+
fs.cp(
|
| 368 |
+
fs_join(source, "subdir", glob), t, recursive=recursive, maxdepth=1
|
| 369 |
+
)
|
| 370 |
+
assert fs.isdir(fs_join(target, "newdir"))
|
| 371 |
+
assert fs.isfile(fs_join(target, "newdir", "subfile1"))
|
| 372 |
+
assert fs.isfile(fs_join(target, "newdir", "subfile2"))
|
| 373 |
+
assert not fs.exists(fs_join(target, "newdir", "nesteddir"))
|
| 374 |
+
assert not fs.exists(fs_join(target, "subdir"))
|
| 375 |
+
assert not fs.exists(fs_join(target, "newdir", "subdir"))
|
| 376 |
+
|
| 377 |
+
fs.rm(fs_join(target, "newdir"), recursive=True)
|
| 378 |
+
assert not fs.exists(fs_join(target, "newdir"))
|
| 379 |
+
|
| 380 |
+
@pytest.mark.parametrize(
|
| 381 |
+
GLOB_EDGE_CASES_TESTS["argnames"],
|
| 382 |
+
GLOB_EDGE_CASES_TESTS["argvalues"],
|
| 383 |
+
)
|
| 384 |
+
def test_copy_glob_edge_cases(
|
| 385 |
+
self,
|
| 386 |
+
path,
|
| 387 |
+
recursive,
|
| 388 |
+
maxdepth,
|
| 389 |
+
expected,
|
| 390 |
+
fs,
|
| 391 |
+
fs_join,
|
| 392 |
+
fs_glob_edge_cases_files,
|
| 393 |
+
fs_target,
|
| 394 |
+
fs_sanitize_path,
|
| 395 |
+
):
|
| 396 |
+
# Copy scenario 1g
|
| 397 |
+
source = fs_glob_edge_cases_files
|
| 398 |
+
|
| 399 |
+
target = fs_target
|
| 400 |
+
|
| 401 |
+
for new_dir, target_slash in product([True, False], [True, False]):
|
| 402 |
+
fs.mkdir(target)
|
| 403 |
+
|
| 404 |
+
t = fs_join(target, "newdir") if new_dir else target
|
| 405 |
+
t = t + "/" if target_slash else t
|
| 406 |
+
|
| 407 |
+
fs.copy(fs_join(source, path), t, recursive=recursive, maxdepth=maxdepth)
|
| 408 |
+
|
| 409 |
+
output = fs.find(target)
|
| 410 |
+
if new_dir:
|
| 411 |
+
prefixed_expected = [
|
| 412 |
+
fs_sanitize_path(fs_join(target, "newdir", p)) for p in expected
|
| 413 |
+
]
|
| 414 |
+
else:
|
| 415 |
+
prefixed_expected = [
|
| 416 |
+
fs_sanitize_path(fs_join(target, p)) for p in expected
|
| 417 |
+
]
|
| 418 |
+
assert sorted(output) == sorted(prefixed_expected)
|
| 419 |
+
|
| 420 |
+
try:
|
| 421 |
+
fs.rm(target, recursive=True)
|
| 422 |
+
except FileNotFoundError:
|
| 423 |
+
pass
|
| 424 |
+
|
| 425 |
+
def test_copy_list_of_files_to_existing_directory(
|
| 426 |
+
self,
|
| 427 |
+
fs,
|
| 428 |
+
fs_join,
|
| 429 |
+
fs_bulk_operations_scenario_0,
|
| 430 |
+
fs_target,
|
| 431 |
+
supports_empty_directories,
|
| 432 |
+
):
|
| 433 |
+
# Copy scenario 2a
|
| 434 |
+
source = fs_bulk_operations_scenario_0
|
| 435 |
+
|
| 436 |
+
target = fs_target
|
| 437 |
+
fs.mkdir(target)
|
| 438 |
+
if not supports_empty_directories:
|
| 439 |
+
# Force target directory to exist by adding a dummy file
|
| 440 |
+
dummy = fs_join(target, "dummy")
|
| 441 |
+
fs.touch(dummy)
|
| 442 |
+
assert fs.isdir(target)
|
| 443 |
+
|
| 444 |
+
source_files = [
|
| 445 |
+
fs_join(source, "file1"),
|
| 446 |
+
fs_join(source, "file2"),
|
| 447 |
+
fs_join(source, "subdir", "subfile1"),
|
| 448 |
+
]
|
| 449 |
+
|
| 450 |
+
for target_slash in [False, True]:
|
| 451 |
+
t = target + "/" if target_slash else target
|
| 452 |
+
|
| 453 |
+
fs.cp(source_files, t)
|
| 454 |
+
assert fs.isfile(fs_join(target, "file1"))
|
| 455 |
+
assert fs.isfile(fs_join(target, "file2"))
|
| 456 |
+
assert fs.isfile(fs_join(target, "subfile1"))
|
| 457 |
+
|
| 458 |
+
fs.rm(
|
| 459 |
+
[
|
| 460 |
+
fs_join(target, "file1"),
|
| 461 |
+
fs_join(target, "file2"),
|
| 462 |
+
fs_join(target, "subfile1"),
|
| 463 |
+
],
|
| 464 |
+
recursive=True,
|
| 465 |
+
)
|
| 466 |
+
assert fs.ls(target, detail=False) == (
|
| 467 |
+
[] if supports_empty_directories else [dummy]
|
| 468 |
+
)
|
| 469 |
+
|
| 470 |
+
def test_copy_list_of_files_to_new_directory(
|
| 471 |
+
self, fs, fs_join, fs_bulk_operations_scenario_0, fs_target
|
| 472 |
+
):
|
| 473 |
+
# Copy scenario 2b
|
| 474 |
+
source = fs_bulk_operations_scenario_0
|
| 475 |
+
|
| 476 |
+
target = fs_target
|
| 477 |
+
fs.mkdir(target)
|
| 478 |
+
|
| 479 |
+
source_files = [
|
| 480 |
+
fs_join(source, "file1"),
|
| 481 |
+
fs_join(source, "file2"),
|
| 482 |
+
fs_join(source, "subdir", "subfile1"),
|
| 483 |
+
]
|
| 484 |
+
|
| 485 |
+
fs.cp(source_files, fs_join(target, "newdir") + "/") # Note trailing slash
|
| 486 |
+
assert fs.isdir(fs_join(target, "newdir"))
|
| 487 |
+
assert fs.isfile(fs_join(target, "newdir", "file1"))
|
| 488 |
+
assert fs.isfile(fs_join(target, "newdir", "file2"))
|
| 489 |
+
assert fs.isfile(fs_join(target, "newdir", "subfile1"))
|
| 490 |
+
|
| 491 |
+
def test_copy_two_files_new_directory(
|
| 492 |
+
self, fs, fs_join, fs_bulk_operations_scenario_0, fs_target
|
| 493 |
+
):
|
| 494 |
+
# This is a duplicate of test_copy_list_of_files_to_new_directory and
|
| 495 |
+
# can eventually be removed.
|
| 496 |
+
source = fs_bulk_operations_scenario_0
|
| 497 |
+
|
| 498 |
+
target = fs_target
|
| 499 |
+
assert not fs.exists(target)
|
| 500 |
+
fs.cp([fs_join(source, "file1"), fs_join(source, "file2")], target)
|
| 501 |
+
|
| 502 |
+
assert fs.isdir(target)
|
| 503 |
+
assert fs.isfile(fs_join(target, "file1"))
|
| 504 |
+
assert fs.isfile(fs_join(target, "file2"))
|
| 505 |
+
|
| 506 |
+
def test_copy_directory_without_files_with_same_name_prefix(
|
| 507 |
+
self,
|
| 508 |
+
fs,
|
| 509 |
+
fs_join,
|
| 510 |
+
fs_target,
|
| 511 |
+
fs_dir_and_file_with_same_name_prefix,
|
| 512 |
+
supports_empty_directories,
|
| 513 |
+
):
|
| 514 |
+
# Create the test dirs
|
| 515 |
+
source = fs_dir_and_file_with_same_name_prefix
|
| 516 |
+
target = fs_target
|
| 517 |
+
|
| 518 |
+
# Test without glob
|
| 519 |
+
fs.cp(fs_join(source, "subdir"), target, recursive=True)
|
| 520 |
+
|
| 521 |
+
assert fs.isfile(fs_join(target, "subfile.txt"))
|
| 522 |
+
assert not fs.isfile(fs_join(target, "subdir.txt"))
|
| 523 |
+
|
| 524 |
+
fs.rm([fs_join(target, "subfile.txt")])
|
| 525 |
+
if supports_empty_directories:
|
| 526 |
+
assert fs.ls(target) == []
|
| 527 |
+
else:
|
| 528 |
+
assert not fs.exists(target)
|
| 529 |
+
|
| 530 |
+
# Test with glob
|
| 531 |
+
fs.cp(fs_join(source, "subdir*"), target, recursive=True)
|
| 532 |
+
|
| 533 |
+
assert fs.isdir(fs_join(target, "subdir"))
|
| 534 |
+
assert fs.isfile(fs_join(target, "subdir", "subfile.txt"))
|
| 535 |
+
assert fs.isfile(fs_join(target, "subdir.txt"))
|
| 536 |
+
|
| 537 |
+
def test_copy_with_source_and_destination_as_list(
|
| 538 |
+
self, fs, fs_target, fs_join, fs_10_files_with_hashed_names
|
| 539 |
+
):
|
| 540 |
+
# Create the test dir
|
| 541 |
+
source = fs_10_files_with_hashed_names
|
| 542 |
+
target = fs_target
|
| 543 |
+
|
| 544 |
+
# Create list of files for source and destination
|
| 545 |
+
source_files = []
|
| 546 |
+
destination_files = []
|
| 547 |
+
for i in range(10):
|
| 548 |
+
hashed_i = md5(str(i).encode("utf-8")).hexdigest()
|
| 549 |
+
source_files.append(fs_join(source, f"{hashed_i}.txt"))
|
| 550 |
+
destination_files.append(fs_join(target, f"{hashed_i}.txt"))
|
| 551 |
+
|
| 552 |
+
# Copy and assert order was kept
|
| 553 |
+
fs.copy(path1=source_files, path2=destination_files)
|
| 554 |
+
|
| 555 |
+
for i in range(10):
|
| 556 |
+
file_content = fs.cat(destination_files[i]).decode("utf-8")
|
| 557 |
+
assert file_content == str(i)
|
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/tests/abstract/get.py
ADDED
|
@@ -0,0 +1,587 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from hashlib import md5
|
| 2 |
+
from itertools import product
|
| 3 |
+
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
from fsspec.implementations.local import make_path_posix
|
| 7 |
+
from fsspec.tests.abstract.common import GLOB_EDGE_CASES_TESTS
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class AbstractGetTests:
|
| 11 |
+
def test_get_file_to_existing_directory(
|
| 12 |
+
self,
|
| 13 |
+
fs,
|
| 14 |
+
fs_join,
|
| 15 |
+
fs_bulk_operations_scenario_0,
|
| 16 |
+
local_fs,
|
| 17 |
+
local_join,
|
| 18 |
+
local_target,
|
| 19 |
+
):
|
| 20 |
+
# Copy scenario 1a
|
| 21 |
+
source = fs_bulk_operations_scenario_0
|
| 22 |
+
|
| 23 |
+
target = local_target
|
| 24 |
+
local_fs.mkdir(target)
|
| 25 |
+
assert local_fs.isdir(target)
|
| 26 |
+
|
| 27 |
+
target_file2 = local_join(target, "file2")
|
| 28 |
+
target_subfile1 = local_join(target, "subfile1")
|
| 29 |
+
|
| 30 |
+
# Copy from source directory
|
| 31 |
+
fs.get(fs_join(source, "file2"), target)
|
| 32 |
+
assert local_fs.isfile(target_file2)
|
| 33 |
+
|
| 34 |
+
# Copy from sub directory
|
| 35 |
+
fs.get(fs_join(source, "subdir", "subfile1"), target)
|
| 36 |
+
assert local_fs.isfile(target_subfile1)
|
| 37 |
+
|
| 38 |
+
# Remove copied files
|
| 39 |
+
local_fs.rm([target_file2, target_subfile1])
|
| 40 |
+
assert not local_fs.exists(target_file2)
|
| 41 |
+
assert not local_fs.exists(target_subfile1)
|
| 42 |
+
|
| 43 |
+
# Repeat with trailing slash on target
|
| 44 |
+
fs.get(fs_join(source, "file2"), target + "/")
|
| 45 |
+
assert local_fs.isdir(target)
|
| 46 |
+
assert local_fs.isfile(target_file2)
|
| 47 |
+
|
| 48 |
+
fs.get(fs_join(source, "subdir", "subfile1"), target + "/")
|
| 49 |
+
assert local_fs.isfile(target_subfile1)
|
| 50 |
+
|
| 51 |
+
def test_get_file_to_new_directory(
|
| 52 |
+
self,
|
| 53 |
+
fs,
|
| 54 |
+
fs_join,
|
| 55 |
+
fs_bulk_operations_scenario_0,
|
| 56 |
+
local_fs,
|
| 57 |
+
local_join,
|
| 58 |
+
local_target,
|
| 59 |
+
):
|
| 60 |
+
# Copy scenario 1b
|
| 61 |
+
source = fs_bulk_operations_scenario_0
|
| 62 |
+
|
| 63 |
+
target = local_target
|
| 64 |
+
local_fs.mkdir(target)
|
| 65 |
+
|
| 66 |
+
fs.get(
|
| 67 |
+
fs_join(source, "subdir", "subfile1"), local_join(target, "newdir/")
|
| 68 |
+
) # Note trailing slash
|
| 69 |
+
|
| 70 |
+
assert local_fs.isdir(target)
|
| 71 |
+
assert local_fs.isdir(local_join(target, "newdir"))
|
| 72 |
+
assert local_fs.isfile(local_join(target, "newdir", "subfile1"))
|
| 73 |
+
|
| 74 |
+
def test_get_file_to_file_in_existing_directory(
|
| 75 |
+
self,
|
| 76 |
+
fs,
|
| 77 |
+
fs_join,
|
| 78 |
+
fs_bulk_operations_scenario_0,
|
| 79 |
+
local_fs,
|
| 80 |
+
local_join,
|
| 81 |
+
local_target,
|
| 82 |
+
):
|
| 83 |
+
# Copy scenario 1c
|
| 84 |
+
source = fs_bulk_operations_scenario_0
|
| 85 |
+
|
| 86 |
+
target = local_target
|
| 87 |
+
local_fs.mkdir(target)
|
| 88 |
+
|
| 89 |
+
fs.get(fs_join(source, "subdir", "subfile1"), local_join(target, "newfile"))
|
| 90 |
+
assert local_fs.isfile(local_join(target, "newfile"))
|
| 91 |
+
|
| 92 |
+
def test_get_file_to_file_in_new_directory(
|
| 93 |
+
self,
|
| 94 |
+
fs,
|
| 95 |
+
fs_join,
|
| 96 |
+
fs_bulk_operations_scenario_0,
|
| 97 |
+
local_fs,
|
| 98 |
+
local_join,
|
| 99 |
+
local_target,
|
| 100 |
+
):
|
| 101 |
+
# Copy scenario 1d
|
| 102 |
+
source = fs_bulk_operations_scenario_0
|
| 103 |
+
|
| 104 |
+
target = local_target
|
| 105 |
+
local_fs.mkdir(target)
|
| 106 |
+
|
| 107 |
+
fs.get(
|
| 108 |
+
fs_join(source, "subdir", "subfile1"),
|
| 109 |
+
local_join(target, "newdir", "newfile"),
|
| 110 |
+
)
|
| 111 |
+
assert local_fs.isdir(local_join(target, "newdir"))
|
| 112 |
+
assert local_fs.isfile(local_join(target, "newdir", "newfile"))
|
| 113 |
+
|
| 114 |
+
def test_get_directory_to_existing_directory(
|
| 115 |
+
self,
|
| 116 |
+
fs,
|
| 117 |
+
fs_join,
|
| 118 |
+
fs_bulk_operations_scenario_0,
|
| 119 |
+
local_fs,
|
| 120 |
+
local_join,
|
| 121 |
+
local_target,
|
| 122 |
+
):
|
| 123 |
+
# Copy scenario 1e
|
| 124 |
+
source = fs_bulk_operations_scenario_0
|
| 125 |
+
|
| 126 |
+
target = local_target
|
| 127 |
+
local_fs.mkdir(target)
|
| 128 |
+
assert local_fs.isdir(target)
|
| 129 |
+
|
| 130 |
+
for source_slash, target_slash in zip([False, True], [False, True]):
|
| 131 |
+
s = fs_join(source, "subdir")
|
| 132 |
+
if source_slash:
|
| 133 |
+
s += "/"
|
| 134 |
+
t = target + "/" if target_slash else target
|
| 135 |
+
|
| 136 |
+
# Without recursive does nothing
|
| 137 |
+
fs.get(s, t)
|
| 138 |
+
assert local_fs.ls(target) == []
|
| 139 |
+
|
| 140 |
+
# With recursive
|
| 141 |
+
fs.get(s, t, recursive=True)
|
| 142 |
+
if source_slash:
|
| 143 |
+
assert local_fs.isfile(local_join(target, "subfile1"))
|
| 144 |
+
assert local_fs.isfile(local_join(target, "subfile2"))
|
| 145 |
+
assert local_fs.isdir(local_join(target, "nesteddir"))
|
| 146 |
+
assert local_fs.isfile(local_join(target, "nesteddir", "nestedfile"))
|
| 147 |
+
assert not local_fs.exists(local_join(target, "subdir"))
|
| 148 |
+
|
| 149 |
+
local_fs.rm(
|
| 150 |
+
[
|
| 151 |
+
local_join(target, "subfile1"),
|
| 152 |
+
local_join(target, "subfile2"),
|
| 153 |
+
local_join(target, "nesteddir"),
|
| 154 |
+
],
|
| 155 |
+
recursive=True,
|
| 156 |
+
)
|
| 157 |
+
else:
|
| 158 |
+
assert local_fs.isdir(local_join(target, "subdir"))
|
| 159 |
+
assert local_fs.isfile(local_join(target, "subdir", "subfile1"))
|
| 160 |
+
assert local_fs.isfile(local_join(target, "subdir", "subfile2"))
|
| 161 |
+
assert local_fs.isdir(local_join(target, "subdir", "nesteddir"))
|
| 162 |
+
assert local_fs.isfile(
|
| 163 |
+
local_join(target, "subdir", "nesteddir", "nestedfile")
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
local_fs.rm(local_join(target, "subdir"), recursive=True)
|
| 167 |
+
assert local_fs.ls(target) == []
|
| 168 |
+
|
| 169 |
+
# Limit recursive by maxdepth
|
| 170 |
+
fs.get(s, t, recursive=True, maxdepth=1)
|
| 171 |
+
if source_slash:
|
| 172 |
+
assert local_fs.isfile(local_join(target, "subfile1"))
|
| 173 |
+
assert local_fs.isfile(local_join(target, "subfile2"))
|
| 174 |
+
assert not local_fs.exists(local_join(target, "nesteddir"))
|
| 175 |
+
assert not local_fs.exists(local_join(target, "subdir"))
|
| 176 |
+
|
| 177 |
+
local_fs.rm(
|
| 178 |
+
[
|
| 179 |
+
local_join(target, "subfile1"),
|
| 180 |
+
local_join(target, "subfile2"),
|
| 181 |
+
],
|
| 182 |
+
recursive=True,
|
| 183 |
+
)
|
| 184 |
+
else:
|
| 185 |
+
assert local_fs.isdir(local_join(target, "subdir"))
|
| 186 |
+
assert local_fs.isfile(local_join(target, "subdir", "subfile1"))
|
| 187 |
+
assert local_fs.isfile(local_join(target, "subdir", "subfile2"))
|
| 188 |
+
assert not local_fs.exists(local_join(target, "subdir", "nesteddir"))
|
| 189 |
+
|
| 190 |
+
local_fs.rm(local_join(target, "subdir"), recursive=True)
|
| 191 |
+
assert local_fs.ls(target) == []
|
| 192 |
+
|
| 193 |
+
def test_get_directory_to_new_directory(
|
| 194 |
+
self,
|
| 195 |
+
fs,
|
| 196 |
+
fs_join,
|
| 197 |
+
fs_bulk_operations_scenario_0,
|
| 198 |
+
local_fs,
|
| 199 |
+
local_join,
|
| 200 |
+
local_target,
|
| 201 |
+
):
|
| 202 |
+
# Copy scenario 1f
|
| 203 |
+
source = fs_bulk_operations_scenario_0
|
| 204 |
+
|
| 205 |
+
target = local_target
|
| 206 |
+
local_fs.mkdir(target)
|
| 207 |
+
|
| 208 |
+
for source_slash, target_slash in zip([False, True], [False, True]):
|
| 209 |
+
s = fs_join(source, "subdir")
|
| 210 |
+
if source_slash:
|
| 211 |
+
s += "/"
|
| 212 |
+
t = local_join(target, "newdir")
|
| 213 |
+
if target_slash:
|
| 214 |
+
t += "/"
|
| 215 |
+
|
| 216 |
+
# Without recursive does nothing
|
| 217 |
+
fs.get(s, t)
|
| 218 |
+
assert local_fs.ls(target) == []
|
| 219 |
+
|
| 220 |
+
# With recursive
|
| 221 |
+
fs.get(s, t, recursive=True)
|
| 222 |
+
assert local_fs.isdir(local_join(target, "newdir"))
|
| 223 |
+
assert local_fs.isfile(local_join(target, "newdir", "subfile1"))
|
| 224 |
+
assert local_fs.isfile(local_join(target, "newdir", "subfile2"))
|
| 225 |
+
assert local_fs.isdir(local_join(target, "newdir", "nesteddir"))
|
| 226 |
+
assert local_fs.isfile(
|
| 227 |
+
local_join(target, "newdir", "nesteddir", "nestedfile")
|
| 228 |
+
)
|
| 229 |
+
assert not local_fs.exists(local_join(target, "subdir"))
|
| 230 |
+
|
| 231 |
+
local_fs.rm(local_join(target, "newdir"), recursive=True)
|
| 232 |
+
assert local_fs.ls(target) == []
|
| 233 |
+
|
| 234 |
+
# Limit recursive by maxdepth
|
| 235 |
+
fs.get(s, t, recursive=True, maxdepth=1)
|
| 236 |
+
assert local_fs.isdir(local_join(target, "newdir"))
|
| 237 |
+
assert local_fs.isfile(local_join(target, "newdir", "subfile1"))
|
| 238 |
+
assert local_fs.isfile(local_join(target, "newdir", "subfile2"))
|
| 239 |
+
assert not local_fs.exists(local_join(target, "newdir", "nesteddir"))
|
| 240 |
+
assert not local_fs.exists(local_join(target, "subdir"))
|
| 241 |
+
|
| 242 |
+
local_fs.rm(local_join(target, "newdir"), recursive=True)
|
| 243 |
+
assert not local_fs.exists(local_join(target, "newdir"))
|
| 244 |
+
|
| 245 |
+
def test_get_glob_to_existing_directory(
|
| 246 |
+
self,
|
| 247 |
+
fs,
|
| 248 |
+
fs_join,
|
| 249 |
+
fs_bulk_operations_scenario_0,
|
| 250 |
+
local_fs,
|
| 251 |
+
local_join,
|
| 252 |
+
local_target,
|
| 253 |
+
):
|
| 254 |
+
# Copy scenario 1g
|
| 255 |
+
source = fs_bulk_operations_scenario_0
|
| 256 |
+
|
| 257 |
+
target = local_target
|
| 258 |
+
local_fs.mkdir(target)
|
| 259 |
+
|
| 260 |
+
for target_slash in [False, True]:
|
| 261 |
+
t = target + "/" if target_slash else target
|
| 262 |
+
|
| 263 |
+
# Without recursive
|
| 264 |
+
fs.get(fs_join(source, "subdir", "*"), t)
|
| 265 |
+
assert local_fs.isfile(local_join(target, "subfile1"))
|
| 266 |
+
assert local_fs.isfile(local_join(target, "subfile2"))
|
| 267 |
+
assert not local_fs.isdir(local_join(target, "nesteddir"))
|
| 268 |
+
assert not local_fs.exists(local_join(target, "nesteddir", "nestedfile"))
|
| 269 |
+
assert not local_fs.exists(local_join(target, "subdir"))
|
| 270 |
+
|
| 271 |
+
local_fs.rm(
|
| 272 |
+
[
|
| 273 |
+
local_join(target, "subfile1"),
|
| 274 |
+
local_join(target, "subfile2"),
|
| 275 |
+
],
|
| 276 |
+
recursive=True,
|
| 277 |
+
)
|
| 278 |
+
assert local_fs.ls(target) == []
|
| 279 |
+
|
| 280 |
+
# With recursive
|
| 281 |
+
for glob, recursive in zip(["*", "**"], [True, False]):
|
| 282 |
+
fs.get(fs_join(source, "subdir", glob), t, recursive=recursive)
|
| 283 |
+
assert local_fs.isfile(local_join(target, "subfile1"))
|
| 284 |
+
assert local_fs.isfile(local_join(target, "subfile2"))
|
| 285 |
+
assert local_fs.isdir(local_join(target, "nesteddir"))
|
| 286 |
+
assert local_fs.isfile(local_join(target, "nesteddir", "nestedfile"))
|
| 287 |
+
assert not local_fs.exists(local_join(target, "subdir"))
|
| 288 |
+
|
| 289 |
+
local_fs.rm(
|
| 290 |
+
[
|
| 291 |
+
local_join(target, "subfile1"),
|
| 292 |
+
local_join(target, "subfile2"),
|
| 293 |
+
local_join(target, "nesteddir"),
|
| 294 |
+
],
|
| 295 |
+
recursive=True,
|
| 296 |
+
)
|
| 297 |
+
assert local_fs.ls(target) == []
|
| 298 |
+
|
| 299 |
+
# Limit recursive by maxdepth
|
| 300 |
+
fs.get(
|
| 301 |
+
fs_join(source, "subdir", glob), t, recursive=recursive, maxdepth=1
|
| 302 |
+
)
|
| 303 |
+
assert local_fs.isfile(local_join(target, "subfile1"))
|
| 304 |
+
assert local_fs.isfile(local_join(target, "subfile2"))
|
| 305 |
+
assert not local_fs.exists(local_join(target, "nesteddir"))
|
| 306 |
+
assert not local_fs.exists(local_join(target, "subdir"))
|
| 307 |
+
|
| 308 |
+
local_fs.rm(
|
| 309 |
+
[
|
| 310 |
+
local_join(target, "subfile1"),
|
| 311 |
+
local_join(target, "subfile2"),
|
| 312 |
+
],
|
| 313 |
+
recursive=True,
|
| 314 |
+
)
|
| 315 |
+
assert local_fs.ls(target) == []
|
| 316 |
+
|
| 317 |
+
def test_get_glob_to_new_directory(
|
| 318 |
+
self,
|
| 319 |
+
fs,
|
| 320 |
+
fs_join,
|
| 321 |
+
fs_bulk_operations_scenario_0,
|
| 322 |
+
local_fs,
|
| 323 |
+
local_join,
|
| 324 |
+
local_target,
|
| 325 |
+
):
|
| 326 |
+
# Copy scenario 1h
|
| 327 |
+
source = fs_bulk_operations_scenario_0
|
| 328 |
+
|
| 329 |
+
target = local_target
|
| 330 |
+
local_fs.mkdir(target)
|
| 331 |
+
|
| 332 |
+
for target_slash in [False, True]:
|
| 333 |
+
t = fs_join(target, "newdir")
|
| 334 |
+
if target_slash:
|
| 335 |
+
t += "/"
|
| 336 |
+
|
| 337 |
+
# Without recursive
|
| 338 |
+
fs.get(fs_join(source, "subdir", "*"), t)
|
| 339 |
+
assert local_fs.isdir(local_join(target, "newdir"))
|
| 340 |
+
assert local_fs.isfile(local_join(target, "newdir", "subfile1"))
|
| 341 |
+
assert local_fs.isfile(local_join(target, "newdir", "subfile2"))
|
| 342 |
+
assert not local_fs.exists(local_join(target, "newdir", "nesteddir"))
|
| 343 |
+
assert not local_fs.exists(
|
| 344 |
+
local_join(target, "newdir", "nesteddir", "nestedfile")
|
| 345 |
+
)
|
| 346 |
+
assert not local_fs.exists(local_join(target, "subdir"))
|
| 347 |
+
assert not local_fs.exists(local_join(target, "newdir", "subdir"))
|
| 348 |
+
|
| 349 |
+
local_fs.rm(local_join(target, "newdir"), recursive=True)
|
| 350 |
+
assert local_fs.ls(target) == []
|
| 351 |
+
|
| 352 |
+
# With recursive
|
| 353 |
+
for glob, recursive in zip(["*", "**"], [True, False]):
|
| 354 |
+
fs.get(fs_join(source, "subdir", glob), t, recursive=recursive)
|
| 355 |
+
assert local_fs.isdir(local_join(target, "newdir"))
|
| 356 |
+
assert local_fs.isfile(local_join(target, "newdir", "subfile1"))
|
| 357 |
+
assert local_fs.isfile(local_join(target, "newdir", "subfile2"))
|
| 358 |
+
assert local_fs.isdir(local_join(target, "newdir", "nesteddir"))
|
| 359 |
+
assert local_fs.isfile(
|
| 360 |
+
local_join(target, "newdir", "nesteddir", "nestedfile")
|
| 361 |
+
)
|
| 362 |
+
assert not local_fs.exists(local_join(target, "subdir"))
|
| 363 |
+
assert not local_fs.exists(local_join(target, "newdir", "subdir"))
|
| 364 |
+
|
| 365 |
+
local_fs.rm(local_join(target, "newdir"), recursive=True)
|
| 366 |
+
assert not local_fs.exists(local_join(target, "newdir"))
|
| 367 |
+
|
| 368 |
+
# Limit recursive by maxdepth
|
| 369 |
+
fs.get(
|
| 370 |
+
fs_join(source, "subdir", glob), t, recursive=recursive, maxdepth=1
|
| 371 |
+
)
|
| 372 |
+
assert local_fs.isdir(local_join(target, "newdir"))
|
| 373 |
+
assert local_fs.isfile(local_join(target, "newdir", "subfile1"))
|
| 374 |
+
assert local_fs.isfile(local_join(target, "newdir", "subfile2"))
|
| 375 |
+
assert not local_fs.exists(local_join(target, "newdir", "nesteddir"))
|
| 376 |
+
assert not local_fs.exists(local_join(target, "subdir"))
|
| 377 |
+
assert not local_fs.exists(local_join(target, "newdir", "subdir"))
|
| 378 |
+
|
| 379 |
+
local_fs.rm(local_fs.ls(target, detail=False), recursive=True)
|
| 380 |
+
assert not local_fs.exists(local_join(target, "newdir"))
|
| 381 |
+
|
| 382 |
+
@pytest.mark.parametrize(
|
| 383 |
+
GLOB_EDGE_CASES_TESTS["argnames"],
|
| 384 |
+
GLOB_EDGE_CASES_TESTS["argvalues"],
|
| 385 |
+
)
|
| 386 |
+
def test_get_glob_edge_cases(
|
| 387 |
+
self,
|
| 388 |
+
path,
|
| 389 |
+
recursive,
|
| 390 |
+
maxdepth,
|
| 391 |
+
expected,
|
| 392 |
+
fs,
|
| 393 |
+
fs_join,
|
| 394 |
+
fs_glob_edge_cases_files,
|
| 395 |
+
local_fs,
|
| 396 |
+
local_join,
|
| 397 |
+
local_target,
|
| 398 |
+
):
|
| 399 |
+
# Copy scenario 1g
|
| 400 |
+
source = fs_glob_edge_cases_files
|
| 401 |
+
|
| 402 |
+
target = local_target
|
| 403 |
+
|
| 404 |
+
for new_dir, target_slash in product([True, False], [True, False]):
|
| 405 |
+
local_fs.mkdir(target)
|
| 406 |
+
|
| 407 |
+
t = local_join(target, "newdir") if new_dir else target
|
| 408 |
+
t = t + "/" if target_slash else t
|
| 409 |
+
|
| 410 |
+
fs.get(fs_join(source, path), t, recursive=recursive, maxdepth=maxdepth)
|
| 411 |
+
|
| 412 |
+
output = local_fs.find(target)
|
| 413 |
+
if new_dir:
|
| 414 |
+
prefixed_expected = [
|
| 415 |
+
make_path_posix(local_join(target, "newdir", p)) for p in expected
|
| 416 |
+
]
|
| 417 |
+
else:
|
| 418 |
+
prefixed_expected = [
|
| 419 |
+
make_path_posix(local_join(target, p)) for p in expected
|
| 420 |
+
]
|
| 421 |
+
assert sorted(output) == sorted(prefixed_expected)
|
| 422 |
+
|
| 423 |
+
try:
|
| 424 |
+
local_fs.rm(target, recursive=True)
|
| 425 |
+
except FileNotFoundError:
|
| 426 |
+
pass
|
| 427 |
+
|
| 428 |
+
def test_get_list_of_files_to_existing_directory(
|
| 429 |
+
self,
|
| 430 |
+
fs,
|
| 431 |
+
fs_join,
|
| 432 |
+
fs_bulk_operations_scenario_0,
|
| 433 |
+
local_fs,
|
| 434 |
+
local_join,
|
| 435 |
+
local_target,
|
| 436 |
+
):
|
| 437 |
+
# Copy scenario 2a
|
| 438 |
+
source = fs_bulk_operations_scenario_0
|
| 439 |
+
|
| 440 |
+
target = local_target
|
| 441 |
+
local_fs.mkdir(target)
|
| 442 |
+
|
| 443 |
+
source_files = [
|
| 444 |
+
fs_join(source, "file1"),
|
| 445 |
+
fs_join(source, "file2"),
|
| 446 |
+
fs_join(source, "subdir", "subfile1"),
|
| 447 |
+
]
|
| 448 |
+
|
| 449 |
+
for target_slash in [False, True]:
|
| 450 |
+
t = target + "/" if target_slash else target
|
| 451 |
+
|
| 452 |
+
fs.get(source_files, t)
|
| 453 |
+
assert local_fs.isfile(local_join(target, "file1"))
|
| 454 |
+
assert local_fs.isfile(local_join(target, "file2"))
|
| 455 |
+
assert local_fs.isfile(local_join(target, "subfile1"))
|
| 456 |
+
|
| 457 |
+
local_fs.rm(
|
| 458 |
+
[
|
| 459 |
+
local_join(target, "file1"),
|
| 460 |
+
local_join(target, "file2"),
|
| 461 |
+
local_join(target, "subfile1"),
|
| 462 |
+
],
|
| 463 |
+
recursive=True,
|
| 464 |
+
)
|
| 465 |
+
assert local_fs.ls(target) == []
|
| 466 |
+
|
| 467 |
+
def test_get_list_of_files_to_new_directory(
|
| 468 |
+
self,
|
| 469 |
+
fs,
|
| 470 |
+
fs_join,
|
| 471 |
+
fs_bulk_operations_scenario_0,
|
| 472 |
+
local_fs,
|
| 473 |
+
local_join,
|
| 474 |
+
local_target,
|
| 475 |
+
):
|
| 476 |
+
# Copy scenario 2b
|
| 477 |
+
source = fs_bulk_operations_scenario_0
|
| 478 |
+
|
| 479 |
+
target = local_target
|
| 480 |
+
local_fs.mkdir(target)
|
| 481 |
+
|
| 482 |
+
source_files = [
|
| 483 |
+
fs_join(source, "file1"),
|
| 484 |
+
fs_join(source, "file2"),
|
| 485 |
+
fs_join(source, "subdir", "subfile1"),
|
| 486 |
+
]
|
| 487 |
+
|
| 488 |
+
fs.get(source_files, local_join(target, "newdir") + "/") # Note trailing slash
|
| 489 |
+
assert local_fs.isdir(local_join(target, "newdir"))
|
| 490 |
+
assert local_fs.isfile(local_join(target, "newdir", "file1"))
|
| 491 |
+
assert local_fs.isfile(local_join(target, "newdir", "file2"))
|
| 492 |
+
assert local_fs.isfile(local_join(target, "newdir", "subfile1"))
|
| 493 |
+
|
| 494 |
+
def test_get_directory_recursive(
|
| 495 |
+
self, fs, fs_join, fs_path, local_fs, local_join, local_target
|
| 496 |
+
):
|
| 497 |
+
# https://github.com/fsspec/filesystem_spec/issues/1062
|
| 498 |
+
# Recursive cp/get/put of source directory into non-existent target directory.
|
| 499 |
+
src = fs_join(fs_path, "src")
|
| 500 |
+
src_file = fs_join(src, "file")
|
| 501 |
+
fs.mkdir(src)
|
| 502 |
+
fs.touch(src_file)
|
| 503 |
+
|
| 504 |
+
target = local_target
|
| 505 |
+
|
| 506 |
+
# get without slash
|
| 507 |
+
assert not local_fs.exists(target)
|
| 508 |
+
for loop in range(2):
|
| 509 |
+
fs.get(src, target, recursive=True)
|
| 510 |
+
assert local_fs.isdir(target)
|
| 511 |
+
|
| 512 |
+
if loop == 0:
|
| 513 |
+
assert local_fs.isfile(local_join(target, "file"))
|
| 514 |
+
assert not local_fs.exists(local_join(target, "src"))
|
| 515 |
+
else:
|
| 516 |
+
assert local_fs.isfile(local_join(target, "file"))
|
| 517 |
+
assert local_fs.isdir(local_join(target, "src"))
|
| 518 |
+
assert local_fs.isfile(local_join(target, "src", "file"))
|
| 519 |
+
|
| 520 |
+
local_fs.rm(target, recursive=True)
|
| 521 |
+
|
| 522 |
+
# get with slash
|
| 523 |
+
assert not local_fs.exists(target)
|
| 524 |
+
for loop in range(2):
|
| 525 |
+
fs.get(src + "/", target, recursive=True)
|
| 526 |
+
assert local_fs.isdir(target)
|
| 527 |
+
assert local_fs.isfile(local_join(target, "file"))
|
| 528 |
+
assert not local_fs.exists(local_join(target, "src"))
|
| 529 |
+
|
| 530 |
+
def test_get_directory_without_files_with_same_name_prefix(
|
| 531 |
+
self,
|
| 532 |
+
fs,
|
| 533 |
+
fs_join,
|
| 534 |
+
local_fs,
|
| 535 |
+
local_join,
|
| 536 |
+
local_target,
|
| 537 |
+
fs_dir_and_file_with_same_name_prefix,
|
| 538 |
+
):
|
| 539 |
+
# Create the test dirs
|
| 540 |
+
source = fs_dir_and_file_with_same_name_prefix
|
| 541 |
+
target = local_target
|
| 542 |
+
|
| 543 |
+
# Test without glob
|
| 544 |
+
fs.get(fs_join(source, "subdir"), target, recursive=True)
|
| 545 |
+
|
| 546 |
+
assert local_fs.isfile(local_join(target, "subfile.txt"))
|
| 547 |
+
assert not local_fs.isfile(local_join(target, "subdir.txt"))
|
| 548 |
+
|
| 549 |
+
local_fs.rm([local_join(target, "subfile.txt")])
|
| 550 |
+
assert local_fs.ls(target) == []
|
| 551 |
+
|
| 552 |
+
# Test with glob
|
| 553 |
+
fs.get(fs_join(source, "subdir*"), target, recursive=True)
|
| 554 |
+
|
| 555 |
+
assert local_fs.isdir(local_join(target, "subdir"))
|
| 556 |
+
assert local_fs.isfile(local_join(target, "subdir", "subfile.txt"))
|
| 557 |
+
assert local_fs.isfile(local_join(target, "subdir.txt"))
|
| 558 |
+
|
| 559 |
+
def test_get_with_source_and_destination_as_list(
|
| 560 |
+
self,
|
| 561 |
+
fs,
|
| 562 |
+
fs_join,
|
| 563 |
+
local_fs,
|
| 564 |
+
local_join,
|
| 565 |
+
local_target,
|
| 566 |
+
fs_10_files_with_hashed_names,
|
| 567 |
+
):
|
| 568 |
+
# Create the test dir
|
| 569 |
+
source = fs_10_files_with_hashed_names
|
| 570 |
+
target = local_target
|
| 571 |
+
|
| 572 |
+
# Create list of files for source and destination
|
| 573 |
+
source_files = []
|
| 574 |
+
destination_files = []
|
| 575 |
+
for i in range(10):
|
| 576 |
+
hashed_i = md5(str(i).encode("utf-8")).hexdigest()
|
| 577 |
+
source_files.append(fs_join(source, f"{hashed_i}.txt"))
|
| 578 |
+
destination_files.append(
|
| 579 |
+
make_path_posix(local_join(target, f"{hashed_i}.txt"))
|
| 580 |
+
)
|
| 581 |
+
|
| 582 |
+
# Copy and assert order was kept
|
| 583 |
+
fs.get(rpath=source_files, lpath=destination_files)
|
| 584 |
+
|
| 585 |
+
for i in range(10):
|
| 586 |
+
file_content = local_fs.cat(destination_files[i]).decode("utf-8")
|
| 587 |
+
assert file_content == str(i)
|
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/tests/abstract/mv.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
|
| 5 |
+
import fsspec
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def test_move_raises_error_with_tmpdir(tmpdir):
|
| 9 |
+
# Create a file in the temporary directory
|
| 10 |
+
source = tmpdir.join("source_file.txt")
|
| 11 |
+
source.write("content")
|
| 12 |
+
|
| 13 |
+
# Define a destination that simulates a protected or invalid path
|
| 14 |
+
destination = tmpdir.join("non_existent_directory/destination_file.txt")
|
| 15 |
+
|
| 16 |
+
# Instantiate the filesystem (assuming the local file system interface)
|
| 17 |
+
fs = fsspec.filesystem("file")
|
| 18 |
+
|
| 19 |
+
# Use the actual file paths as string
|
| 20 |
+
with pytest.raises(FileNotFoundError):
|
| 21 |
+
fs.mv(str(source), str(destination))
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@pytest.mark.parametrize("recursive", (True, False))
|
| 25 |
+
def test_move_raises_error_with_tmpdir_permission(recursive, tmpdir):
|
| 26 |
+
# Create a file in the temporary directory
|
| 27 |
+
source = tmpdir.join("source_file.txt")
|
| 28 |
+
source.write("content")
|
| 29 |
+
|
| 30 |
+
# Create a protected directory (non-writable)
|
| 31 |
+
protected_dir = tmpdir.mkdir("protected_directory")
|
| 32 |
+
protected_path = str(protected_dir)
|
| 33 |
+
|
| 34 |
+
# Set the directory to read-only
|
| 35 |
+
if os.name == "nt":
|
| 36 |
+
os.system(f'icacls "{protected_path}" /deny Everyone:(W)')
|
| 37 |
+
else:
|
| 38 |
+
os.chmod(protected_path, 0o555) # Sets the directory to read-only
|
| 39 |
+
|
| 40 |
+
# Define a destination inside the protected directory
|
| 41 |
+
destination = protected_dir.join("destination_file.txt")
|
| 42 |
+
|
| 43 |
+
# Instantiate the filesystem (assuming the local file system interface)
|
| 44 |
+
fs = fsspec.filesystem("file")
|
| 45 |
+
|
| 46 |
+
# Try to move the file to the read-only directory, expecting a permission error
|
| 47 |
+
with pytest.raises(PermissionError):
|
| 48 |
+
fs.mv(str(source), str(destination), recursive=recursive)
|
| 49 |
+
|
| 50 |
+
# Assert the file was not created in the destination
|
| 51 |
+
assert not os.path.exists(destination)
|
| 52 |
+
|
| 53 |
+
# Cleanup: Restore permissions so the directory can be cleaned up
|
| 54 |
+
if os.name == "nt":
|
| 55 |
+
os.system(f'icacls "{protected_path}" /remove:d Everyone')
|
| 56 |
+
else:
|
| 57 |
+
os.chmod(protected_path, 0o755) # Restore write permission for cleanup
|