Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- micromamba_root/envs/hf_sync/Lib/site-packages/PySocks-1.7.1.dist-info/INSTALLER +1 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/PySocks-1.7.1.dist-info/LICENSE +22 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/PySocks-1.7.1.dist-info/METADATA +319 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/PySocks-1.7.1.dist-info/RECORD +12 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/PySocks-1.7.1.dist-info/REQUESTED +0 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/PySocks-1.7.1.dist-info/WHEEL +5 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/PySocks-1.7.1.dist-info/direct_url.json +1 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/PySocks-1.7.1.dist-info/top_level.txt +2 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/__pycache__/brotli.cpython-314.pyc +0 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/__pycache__/socks.cpython-314.pyc +0 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/__pycache__/sockshandler.cpython-314.pyc +0 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/__pycache__/win_inet_pton.cpython-314.pyc +0 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/_yaml/__init__.py +33 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/_yaml/__pycache__/__init__.cpython-314.pyc +0 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/filelock-3.29.0.dist-info/RECORD +36 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/filelock-3.29.0.dist-info/REQUESTED +0 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/filelock-3.29.0.dist-info/WHEEL +4 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/fsspec-2026.4.0.dist-info/INSTALLER +1 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/fsspec-2026.4.0.dist-info/METADATA +257 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/fsspec-2026.4.0.dist-info/RECORD +121 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/fsspec-2026.4.0.dist-info/REQUESTED +0 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/fsspec-2026.4.0.dist-info/WHEEL +4 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/fsspec-2026.4.0.dist-info/direct_url.json +1 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/fsspec/__init__.py +71 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/fsspec/_version.py +34 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/fsspec/archive.py +75 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/fsspec/asyn.py +1127 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/fsspec/caching.py +1004 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/fsspec/callbacks.py +324 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/fsspec/compression.py +185 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/fsspec/config.py +131 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/fsspec/conftest.py +125 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/fsspec/core.py +760 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/fsspec/dircache.py +98 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/fsspec/exceptions.py +18 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/fsspec/fuse.py +324 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/fsspec/generic.py +396 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/fsspec/gui.py +417 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/fsspec/json.py +112 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/fsspec/mapping.py +251 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/fsspec/parquet.py +572 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/fsspec/registry.py +337 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/fsspec/spec.py +2284 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/fsspec/transaction.py +90 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/fsspec/utils.py +748 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/h11-0.16.0.dist-info/INSTALLER +1 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/h11-0.16.0.dist-info/METADATA +202 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/h11-0.16.0.dist-info/RECORD +31 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/h11-0.16.0.dist-info/REQUESTED +0 -0
- micromamba_root/envs/hf_sync/Lib/site-packages/h11-0.16.0.dist-info/WHEEL +5 -0
micromamba_root/envs/hf_sync/Lib/site-packages/PySocks-1.7.1.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
conda
|
micromamba_root/envs/hf_sync/Lib/site-packages/PySocks-1.7.1.dist-info/LICENSE
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Copyright 2006 Dan-Haim. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Redistribution and use in source and binary forms, with or without modification,
|
| 4 |
+
are permitted provided that the following conditions are met:
|
| 5 |
+
1. Redistributions of source code must retain the above copyright notice, this
|
| 6 |
+
list of conditions and the following disclaimer.
|
| 7 |
+
2. Redistributions in binary form must reproduce the above copyright notice,
|
| 8 |
+
this list of conditions and the following disclaimer in the documentation
|
| 9 |
+
and/or other materials provided with the distribution.
|
| 10 |
+
3. Neither the name of Dan Haim nor the names of his contributors may be used
|
| 11 |
+
to endorse or promote products derived from this software without specific
|
| 12 |
+
prior written permission.
|
| 13 |
+
|
| 14 |
+
THIS SOFTWARE IS PROVIDED BY DAN HAIM "AS IS" AND ANY EXPRESS OR IMPLIED
|
| 15 |
+
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
|
| 16 |
+
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
|
| 17 |
+
EVENT SHALL DAN HAIM OR HIS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
| 18 |
+
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
| 19 |
+
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA
|
| 20 |
+
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
| 21 |
+
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
|
| 22 |
+
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMANGE.
|
micromamba_root/envs/hf_sync/Lib/site-packages/PySocks-1.7.1.dist-info/METADATA
ADDED
|
@@ -0,0 +1,319 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.1
|
| 2 |
+
Name: PySocks
|
| 3 |
+
Version: 1.7.1
|
| 4 |
+
Summary: A Python SOCKS client module. See https://github.com/Anorov/PySocks for more information.
|
| 5 |
+
Home-page: https://github.com/Anorov/PySocks
|
| 6 |
+
Author: Anorov
|
| 7 |
+
Author-email: anorov.vorona@gmail.com
|
| 8 |
+
License: BSD
|
| 9 |
+
Keywords: socks,proxy
|
| 10 |
+
Classifier: Programming Language :: Python :: 2
|
| 11 |
+
Classifier: Programming Language :: Python :: 2.7
|
| 12 |
+
Classifier: Programming Language :: Python :: 3
|
| 13 |
+
Classifier: Programming Language :: Python :: 3.4
|
| 14 |
+
Classifier: Programming Language :: Python :: 3.5
|
| 15 |
+
Classifier: Programming Language :: Python :: 3.6
|
| 16 |
+
Requires-Python: >=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*
|
| 17 |
+
Description-Content-Type: text/markdown
|
| 18 |
+
License-File: LICENSE
|
| 19 |
+
|
| 20 |
+
PySocks
|
| 21 |
+
=======
|
| 22 |
+
|
| 23 |
+
PySocks lets you send traffic through SOCKS and HTTP proxy servers. It is a modern fork of [SocksiPy](http://socksipy.sourceforge.net/) with bug fixes and extra features.
|
| 24 |
+
|
| 25 |
+
Acts as a drop-in replacement to the socket module. Seamlessly configure SOCKS proxies for any socket object by calling `socket_object.set_proxy()`.
|
| 26 |
+
|
| 27 |
+
----------------
|
| 28 |
+
|
| 29 |
+
Features
|
| 30 |
+
========
|
| 31 |
+
|
| 32 |
+
* SOCKS proxy client for Python 2.7 and 3.4+
|
| 33 |
+
* TCP supported
|
| 34 |
+
* UDP mostly supported (issues may occur in some edge cases)
|
| 35 |
+
* HTTP proxy client included but not supported or recommended (you should use urllib2's or requests' own HTTP proxy interface)
|
| 36 |
+
* urllib2 handler included. `pip install` / `setup.py install` will automatically install the `sockshandler` module.
|
| 37 |
+
|
| 38 |
+
Installation
|
| 39 |
+
============
|
| 40 |
+
|
| 41 |
+
pip install PySocks
|
| 42 |
+
|
| 43 |
+
Or download the tarball / `git clone` and...
|
| 44 |
+
|
| 45 |
+
python setup.py install
|
| 46 |
+
|
| 47 |
+
These will install both the `socks` and `sockshandler` modules.
|
| 48 |
+
|
| 49 |
+
Alternatively, include just `socks.py` in your project.
|
| 50 |
+
|
| 51 |
+
--------------------------------------------
|
| 52 |
+
|
| 53 |
+
*Warning:* PySocks/SocksiPy only supports HTTP proxies that use CONNECT tunneling. Certain HTTP proxies may not work with this library. If you wish to use HTTP (not SOCKS) proxies, it is recommended that you rely on your HTTP client's native proxy support (`proxies` dict for `requests`, or `urllib2.ProxyHandler` for `urllib2`) instead.
|
| 54 |
+
|
| 55 |
+
--------------------------------------------
|
| 56 |
+
|
| 57 |
+
Usage
|
| 58 |
+
=====
|
| 59 |
+
|
| 60 |
+
## socks.socksocket ##
|
| 61 |
+
|
| 62 |
+
import socks
|
| 63 |
+
|
| 64 |
+
s = socks.socksocket() # Same API as socket.socket in the standard lib
|
| 65 |
+
|
| 66 |
+
s.set_proxy(socks.SOCKS5, "localhost") # SOCKS4 and SOCKS5 use port 1080 by default
|
| 67 |
+
# Or
|
| 68 |
+
s.set_proxy(socks.SOCKS4, "localhost", 4444)
|
| 69 |
+
# Or
|
| 70 |
+
s.set_proxy(socks.HTTP, "5.5.5.5", 8888)
|
| 71 |
+
|
| 72 |
+
# Can be treated identical to a regular socket object
|
| 73 |
+
s.connect(("www.somesite.com", 80))
|
| 74 |
+
s.sendall("GET / HTTP/1.1 ...")
|
| 75 |
+
print s.recv(4096)
|
| 76 |
+
|
| 77 |
+
## Monkeypatching ##
|
| 78 |
+
|
| 79 |
+
To monkeypatch the entire standard library with a single default proxy:
|
| 80 |
+
|
| 81 |
+
import urllib2
|
| 82 |
+
import socket
|
| 83 |
+
import socks
|
| 84 |
+
|
| 85 |
+
socks.set_default_proxy(socks.SOCKS5, "localhost")
|
| 86 |
+
socket.socket = socks.socksocket
|
| 87 |
+
|
| 88 |
+
urllib2.urlopen("http://www.somesite.com/") # All requests will pass through the SOCKS proxy
|
| 89 |
+
|
| 90 |
+
Note that monkeypatching may not work for all standard modules or for all third party modules, and generally isn't recommended. Monkeypatching is usually an anti-pattern in Python.
|
| 91 |
+
|
| 92 |
+
## urllib2 Handler ##
|
| 93 |
+
|
| 94 |
+
Example use case with the `sockshandler` urllib2 handler. Note that you must import both `socks` and `sockshandler`, as the handler is its own module separate from PySocks. The module is included in the PyPI package.
|
| 95 |
+
|
| 96 |
+
import urllib2
|
| 97 |
+
import socks
|
| 98 |
+
from sockshandler import SocksiPyHandler
|
| 99 |
+
|
| 100 |
+
opener = urllib2.build_opener(SocksiPyHandler(socks.SOCKS5, "127.0.0.1", 9050))
|
| 101 |
+
print opener.open("http://www.somesite.com/") # All requests made by the opener will pass through the SOCKS proxy
|
| 102 |
+
|
| 103 |
+
--------------------------------------------
|
| 104 |
+
|
| 105 |
+
Original SocksiPy README attached below, amended to reflect API changes.
|
| 106 |
+
|
| 107 |
+
--------------------------------------------
|
| 108 |
+
|
| 109 |
+
SocksiPy
|
| 110 |
+
|
| 111 |
+
A Python SOCKS module.
|
| 112 |
+
|
| 113 |
+
(C) 2006 Dan-Haim. All rights reserved.
|
| 114 |
+
|
| 115 |
+
See LICENSE file for details.
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
*WHAT IS A SOCKS PROXY?*
|
| 119 |
+
|
| 120 |
+
A SOCKS proxy is a proxy server at the TCP level. In other words, it acts as
|
| 121 |
+
a tunnel, relaying all traffic going through it without modifying it.
|
| 122 |
+
SOCKS proxies can be used to relay traffic using any network protocol that
|
| 123 |
+
uses TCP.
|
| 124 |
+
|
| 125 |
+
*WHAT IS SOCKSIPY?*
|
| 126 |
+
|
| 127 |
+
This Python module allows you to create TCP connections through a SOCKS
|
| 128 |
+
proxy without any special effort.
|
| 129 |
+
It also supports relaying UDP packets with a SOCKS5 proxy.
|
| 130 |
+
|
| 131 |
+
*PROXY COMPATIBILITY*
|
| 132 |
+
|
| 133 |
+
SocksiPy is compatible with three different types of proxies:
|
| 134 |
+
|
| 135 |
+
1. SOCKS Version 4 (SOCKS4), including the SOCKS4a extension.
|
| 136 |
+
2. SOCKS Version 5 (SOCKS5).
|
| 137 |
+
3. HTTP Proxies which support tunneling using the CONNECT method.
|
| 138 |
+
|
| 139 |
+
*SYSTEM REQUIREMENTS*
|
| 140 |
+
|
| 141 |
+
Being written in Python, SocksiPy can run on any platform that has a Python
|
| 142 |
+
interpreter and TCP/IP support.
|
| 143 |
+
This module has been tested with Python 2.3 and should work with greater versions
|
| 144 |
+
just as well.
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
INSTALLATION
|
| 148 |
+
-------------
|
| 149 |
+
|
| 150 |
+
Simply copy the file "socks.py" to your Python's `lib/site-packages` directory,
|
| 151 |
+
and you're ready to go. [Editor's note: it is better to use `python setup.py install` for PySocks]
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
USAGE
|
| 155 |
+
------
|
| 156 |
+
|
| 157 |
+
First load the socks module with the command:
|
| 158 |
+
|
| 159 |
+
>>> import socks
|
| 160 |
+
>>>
|
| 161 |
+
|
| 162 |
+
The socks module provides a class called `socksocket`, which is the base to all of the module's functionality.
|
| 163 |
+
|
| 164 |
+
The `socksocket` object has the same initialization parameters as the normal socket
|
| 165 |
+
object to ensure maximal compatibility, however it should be noted that `socksocket` will only function with family being `AF_INET` and
|
| 166 |
+
type being either `SOCK_STREAM` or `SOCK_DGRAM`.
|
| 167 |
+
Generally, it is best to initialize the `socksocket` object with no parameters
|
| 168 |
+
|
| 169 |
+
>>> s = socks.socksocket()
|
| 170 |
+
>>>
|
| 171 |
+
|
| 172 |
+
The `socksocket` object has an interface which is very similiar to socket's (in fact
|
| 173 |
+
the `socksocket` class is derived from socket) with a few extra methods.
|
| 174 |
+
To select the proxy server you would like to use, use the `set_proxy` method, whose
|
| 175 |
+
syntax is:
|
| 176 |
+
|
| 177 |
+
set_proxy(proxy_type, addr[, port[, rdns[, username[, password]]]])
|
| 178 |
+
|
| 179 |
+
Explanation of the parameters:
|
| 180 |
+
|
| 181 |
+
`proxy_type` - The type of the proxy server. This can be one of three possible
|
| 182 |
+
choices: `PROXY_TYPE_SOCKS4`, `PROXY_TYPE_SOCKS5` and `PROXY_TYPE_HTTP` for SOCKS4,
|
| 183 |
+
SOCKS5 and HTTP servers respectively. `SOCKS4`, `SOCKS5`, and `HTTP` are all aliases, respectively.
|
| 184 |
+
|
| 185 |
+
`addr` - The IP address or DNS name of the proxy server.
|
| 186 |
+
|
| 187 |
+
`port` - The port of the proxy server. Defaults to 1080 for socks and 8080 for http.
|
| 188 |
+
|
| 189 |
+
`rdns` - This is a boolean flag than modifies the behavior regarding DNS resolving.
|
| 190 |
+
If it is set to True, DNS resolving will be preformed remotely, on the server.
|
| 191 |
+
If it is set to False, DNS resolving will be preformed locally. Please note that
|
| 192 |
+
setting this to True with SOCKS4 servers actually use an extension to the protocol,
|
| 193 |
+
called SOCKS4a, which may not be supported on all servers (SOCKS5 and http servers
|
| 194 |
+
always support DNS). The default is True.
|
| 195 |
+
|
| 196 |
+
`username` - For SOCKS5 servers, this allows simple username / password authentication
|
| 197 |
+
with the server. For SOCKS4 servers, this parameter will be sent as the userid.
|
| 198 |
+
This parameter is ignored if an HTTP server is being used. If it is not provided,
|
| 199 |
+
authentication will not be used (servers may accept unauthenticated requests).
|
| 200 |
+
|
| 201 |
+
`password` - This parameter is valid only for SOCKS5 servers and specifies the
|
| 202 |
+
respective password for the username provided.
|
| 203 |
+
|
| 204 |
+
Example of usage:
|
| 205 |
+
|
| 206 |
+
>>> s.set_proxy(socks.SOCKS5, "socks.example.com") # uses default port 1080
|
| 207 |
+
>>> s.set_proxy(socks.SOCKS4, "socks.test.com", 1081)
|
| 208 |
+
|
| 209 |
+
After the set_proxy method has been called, simply call the connect method with the
|
| 210 |
+
traditional parameters to establish a connection through the proxy:
|
| 211 |
+
|
| 212 |
+
>>> s.connect(("www.sourceforge.net", 80))
|
| 213 |
+
>>>
|
| 214 |
+
|
| 215 |
+
Connection will take a bit longer to allow negotiation with the proxy server.
|
| 216 |
+
Please note that calling connect without calling `set_proxy` earlier will connect
|
| 217 |
+
without a proxy (just like a regular socket).
|
| 218 |
+
|
| 219 |
+
Errors: Any errors in the connection process will trigger exceptions. The exception
|
| 220 |
+
may either be generated by the underlying socket layer or may be custom module
|
| 221 |
+
exceptions, whose details follow:
|
| 222 |
+
|
| 223 |
+
class `ProxyError` - This is a base exception class. It is not raised directly but
|
| 224 |
+
rather all other exception classes raised by this module are derived from it.
|
| 225 |
+
This allows an easy way to catch all proxy-related errors. It descends from `IOError`.
|
| 226 |
+
|
| 227 |
+
All `ProxyError` exceptions have an attribute `socket_err`, which will contain either a
|
| 228 |
+
caught `socket.error` exception, or `None` if there wasn't any.
|
| 229 |
+
|
| 230 |
+
class `GeneralProxyError` - When thrown, it indicates a problem which does not fall
|
| 231 |
+
into another category.
|
| 232 |
+
|
| 233 |
+
* `Sent invalid data` - This error means that unexpected data has been received from
|
| 234 |
+
the server. The most common reason is that the server specified as the proxy is
|
| 235 |
+
not really a SOCKS4/SOCKS5/HTTP proxy, or maybe the proxy type specified is wrong.
|
| 236 |
+
|
| 237 |
+
* `Connection closed unexpectedly` - The proxy server unexpectedly closed the connection.
|
| 238 |
+
This may indicate that the proxy server is experiencing network or software problems.
|
| 239 |
+
|
| 240 |
+
* `Bad proxy type` - This will be raised if the type of the proxy supplied to the
|
| 241 |
+
set_proxy function was not one of `SOCKS4`/`SOCKS5`/`HTTP`.
|
| 242 |
+
|
| 243 |
+
* `Bad input` - This will be raised if the `connect()` method is called with bad input
|
| 244 |
+
parameters.
|
| 245 |
+
|
| 246 |
+
class `SOCKS5AuthError` - This indicates that the connection through a SOCKS5 server
|
| 247 |
+
failed due to an authentication problem.
|
| 248 |
+
|
| 249 |
+
* `Authentication is required` - This will happen if you use a SOCKS5 server which
|
| 250 |
+
requires authentication without providing a username / password at all.
|
| 251 |
+
|
| 252 |
+
* `All offered authentication methods were rejected` - This will happen if the proxy
|
| 253 |
+
requires a special authentication method which is not supported by this module.
|
| 254 |
+
|
| 255 |
+
* `Unknown username or invalid password` - Self descriptive.
|
| 256 |
+
|
| 257 |
+
class `SOCKS5Error` - This will be raised for SOCKS5 errors which are not related to
|
| 258 |
+
authentication.
|
| 259 |
+
The parameter is a tuple containing a code, as given by the server,
|
| 260 |
+
and a description of the
|
| 261 |
+
error. The possible errors, according to the RFC, are:
|
| 262 |
+
|
| 263 |
+
* `0x01` - General SOCKS server failure - If for any reason the proxy server is unable to
|
| 264 |
+
fulfill your request (internal server error).
|
| 265 |
+
* `0x02` - connection not allowed by ruleset - If the address you're trying to connect to
|
| 266 |
+
is blacklisted on the server or requires authentication.
|
| 267 |
+
* `0x03` - Network unreachable - The target could not be contacted. A router on the network
|
| 268 |
+
had replied with a destination net unreachable error.
|
| 269 |
+
* `0x04` - Host unreachable - The target could not be contacted. A router on the network
|
| 270 |
+
had replied with a destination host unreachable error.
|
| 271 |
+
* `0x05` - Connection refused - The target server has actively refused the connection
|
| 272 |
+
(the requested port is closed).
|
| 273 |
+
* `0x06` - TTL expired - The TTL value of the SYN packet from the proxy to the target server
|
| 274 |
+
has expired. This usually means that there are network problems causing the packet
|
| 275 |
+
to be caught in a router-to-router "ping-pong".
|
| 276 |
+
* `0x07` - Command not supported - For instance if the server does not support UDP.
|
| 277 |
+
* `0x08` - Address type not supported - The client has provided an invalid address type.
|
| 278 |
+
When using this module, this error should not occur.
|
| 279 |
+
|
| 280 |
+
class `SOCKS4Error` - This will be raised for SOCKS4 errors. The parameter is a tuple
|
| 281 |
+
containing a code and a description of the error, as given by the server. The
|
| 282 |
+
possible error, according to the specification are:
|
| 283 |
+
|
| 284 |
+
* `0x5B` - Request rejected or failed - Will be raised in the event of an failure for any
|
| 285 |
+
reason other then the two mentioned next.
|
| 286 |
+
* `0x5C` - request rejected because SOCKS server cannot connect to identd on the client -
|
| 287 |
+
The Socks server had tried an ident lookup on your computer and has failed. In this
|
| 288 |
+
case you should run an identd server and/or configure your firewall to allow incoming
|
| 289 |
+
connections to local port 113 from the remote server.
|
| 290 |
+
* `0x5D` - request rejected because the client program and identd report different user-ids -
|
| 291 |
+
The Socks server had performed an ident lookup on your computer and has received a
|
| 292 |
+
different userid than the one you have provided. Change your userid (through the
|
| 293 |
+
username parameter of the set_proxy method) to match and try again.
|
| 294 |
+
|
| 295 |
+
class `HTTPError` - This will be raised for HTTP errors. The message will contain
|
| 296 |
+
the HTTP status code and provided error message.
|
| 297 |
+
|
| 298 |
+
After establishing the connection, the object behaves like a standard socket.
|
| 299 |
+
|
| 300 |
+
Methods like `makefile()` and `settimeout()` should behave just like regular sockets.
|
| 301 |
+
Call the `close()` method to close the connection.
|
| 302 |
+
|
| 303 |
+
In addition to the `socksocket` class, an additional function worth mentioning is the
|
| 304 |
+
`set_default_proxy` function. The parameters are the same as the `set_proxy` method.
|
| 305 |
+
This function will set default proxy settings for newly created `socksocket` objects,
|
| 306 |
+
in which the proxy settings haven't been changed via the `set_proxy` method.
|
| 307 |
+
This is quite useful if you wish to force 3rd party modules to use a SOCKS proxy,
|
| 308 |
+
by overriding the socket object.
|
| 309 |
+
For example:
|
| 310 |
+
|
| 311 |
+
>>> socks.set_default_proxy(socks.SOCKS5, "socks.example.com")
|
| 312 |
+
>>> socket.socket = socks.socksocket
|
| 313 |
+
>>> urllib.urlopen("http://www.sourceforge.net/")
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
PROBLEMS
|
| 317 |
+
---------
|
| 318 |
+
|
| 319 |
+
Please open a GitHub issue at https://github.com/Anorov/PySocks
|
micromamba_root/envs/hf_sync/Lib/site-packages/PySocks-1.7.1.dist-info/RECORD
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
PySocks-1.7.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
| 2 |
+
PySocks-1.7.1.dist-info/LICENSE,sha256=cCfiFOAU63i3rcwc7aWspxOnn8T2oMUsnaWz5wfm_-k,1401
|
| 3 |
+
PySocks-1.7.1.dist-info/METADATA,sha256=snuJ49RLchERn_OEVglGdbaQY-srgq78o84aaw3OwyI,13556
|
| 4 |
+
PySocks-1.7.1.dist-info/RECORD,,
|
| 5 |
+
PySocks-1.7.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 6 |
+
PySocks-1.7.1.dist-info/WHEEL,sha256=PZUExdf71Ui_so67QXpySuHtCi3-J3wvF4ORK6k_S8U,91
|
| 7 |
+
PySocks-1.7.1.dist-info/direct_url.json,sha256=TPdQXLghXC6TNv3uvwUbuW0ixPsIn6FxHApBBNvEyGI,68
|
| 8 |
+
PySocks-1.7.1.dist-info/top_level.txt,sha256=TKSOIfCFBoK9EY8FBYbYqC3PWd3--G15ph9n8-QHPDk,19
|
| 9 |
+
__pycache__/socks.cpython-39.pyc,,
|
| 10 |
+
__pycache__/sockshandler.cpython-39.pyc,,
|
| 11 |
+
socks.py,sha256=xOYn27t9IGrbTBzWsUUuPa0YBuplgiUykzkOB5V5iFY,31086
|
| 12 |
+
sockshandler.py,sha256=2SYGj-pwt1kjgLoZAmyeaEXCeZDWRmfVS_QG6kErGtY,3966
|
micromamba_root/envs/hf_sync/Lib/site-packages/PySocks-1.7.1.dist-info/REQUESTED
ADDED
|
File without changes
|
micromamba_root/envs/hf_sync/Lib/site-packages/PySocks-1.7.1.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: setuptools (75.6.0)
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py3-none-any
|
| 5 |
+
|
micromamba_root/envs/hf_sync/Lib/site-packages/PySocks-1.7.1.dist-info/direct_url.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"dir_info": {}, "url": "file:///D:/bld/pysocks_1733217287171/work"}
|
micromamba_root/envs/hf_sync/Lib/site-packages/PySocks-1.7.1.dist-info/top_level.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
socks
|
| 2 |
+
sockshandler
|
micromamba_root/envs/hf_sync/Lib/site-packages/__pycache__/brotli.cpython-314.pyc
ADDED
|
Binary file (1.9 kB). View file
|
|
|
micromamba_root/envs/hf_sync/Lib/site-packages/__pycache__/socks.cpython-314.pyc
ADDED
|
Binary file (35.1 kB). View file
|
|
|
micromamba_root/envs/hf_sync/Lib/site-packages/__pycache__/sockshandler.cpython-314.pyc
ADDED
|
Binary file (7.06 kB). View file
|
|
|
micromamba_root/envs/hf_sync/Lib/site-packages/__pycache__/win_inet_pton.cpython-314.pyc
ADDED
|
Binary file (5.13 kB). View file
|
|
|
micromamba_root/envs/hf_sync/Lib/site-packages/_yaml/__init__.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This is a stub package designed to roughly emulate the _yaml
|
| 2 |
+
# extension module, which previously existed as a standalone module
|
| 3 |
+
# and has been moved into the `yaml` package namespace.
|
| 4 |
+
# It does not perfectly mimic its old counterpart, but should get
|
| 5 |
+
# close enough for anyone who's relying on it even when they shouldn't.
|
| 6 |
+
import yaml
|
| 7 |
+
|
| 8 |
+
# in some circumstances, the yaml module we imoprted may be from a different version, so we need
|
| 9 |
+
# to tread carefully when poking at it here (it may not have the attributes we expect)
|
| 10 |
+
if not getattr(yaml, '__with_libyaml__', False):
|
| 11 |
+
from sys import version_info
|
| 12 |
+
|
| 13 |
+
exc = ModuleNotFoundError if version_info >= (3, 6) else ImportError
|
| 14 |
+
raise exc("No module named '_yaml'")
|
| 15 |
+
else:
|
| 16 |
+
from yaml._yaml import *
|
| 17 |
+
import warnings
|
| 18 |
+
warnings.warn(
|
| 19 |
+
'The _yaml extension module is now located at yaml._yaml'
|
| 20 |
+
' and its location is subject to change. To use the'
|
| 21 |
+
' LibYAML-based parser and emitter, import from `yaml`:'
|
| 22 |
+
' `from yaml import CLoader as Loader, CDumper as Dumper`.',
|
| 23 |
+
DeprecationWarning
|
| 24 |
+
)
|
| 25 |
+
del warnings
|
| 26 |
+
# Don't `del yaml` here because yaml is actually an existing
|
| 27 |
+
# namespace member of _yaml.
|
| 28 |
+
|
| 29 |
+
__name__ = '_yaml'
|
| 30 |
+
# If the module is top-level (i.e. not a part of any specific package)
|
| 31 |
+
# then the attribute should be set to ''.
|
| 32 |
+
# https://docs.python.org/3.8/library/types.html
|
| 33 |
+
__package__ = ''
|
micromamba_root/envs/hf_sync/Lib/site-packages/_yaml/__pycache__/__init__.cpython-314.pyc
ADDED
|
Binary file (833 Bytes). View file
|
|
|
micromamba_root/envs/hf_sync/Lib/site-packages/filelock-3.29.0.dist-info/RECORD
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
filelock-3.29.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
| 2 |
+
filelock-3.29.0.dist-info/METADATA,sha256=ITNdGUDKAIMOF1lOgentezkyEbHgPto8QRo1B79Z9Lc,1977
|
| 3 |
+
filelock-3.29.0.dist-info/RECORD,,
|
| 4 |
+
filelock-3.29.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 5 |
+
filelock-3.29.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
|
| 6 |
+
filelock-3.29.0.dist-info/direct_url.json,sha256=Vc-DK6khKX8pEHqozCDV_-5DIT3SjA-8_y3gtmQHhzA,104
|
| 7 |
+
filelock-3.29.0.dist-info/licenses/LICENSE,sha256=YIyJ1QYK6ZIa3M8yNmlbxlSplG4SMj72wCHfoE4pTUg,1088
|
| 8 |
+
filelock/__init__.py,sha256=Ig_QNvsAVtctz2-fkq9EUCgXmW6M5PDudiOC85szmis,2612
|
| 9 |
+
filelock/__pycache__/__init__.cpython-310.pyc,,
|
| 10 |
+
filelock/__pycache__/_api.cpython-310.pyc,,
|
| 11 |
+
filelock/__pycache__/_async_read_write.cpython-310.pyc,,
|
| 12 |
+
filelock/__pycache__/_error.cpython-310.pyc,,
|
| 13 |
+
filelock/__pycache__/_read_write.cpython-310.pyc,,
|
| 14 |
+
filelock/__pycache__/_soft.cpython-310.pyc,,
|
| 15 |
+
filelock/__pycache__/_unix.cpython-310.pyc,,
|
| 16 |
+
filelock/__pycache__/_util.cpython-310.pyc,,
|
| 17 |
+
filelock/__pycache__/_windows.cpython-310.pyc,,
|
| 18 |
+
filelock/__pycache__/asyncio.cpython-310.pyc,,
|
| 19 |
+
filelock/__pycache__/version.cpython-310.pyc,,
|
| 20 |
+
filelock/_api.py,sha256=UxKGuyzWqzb0Bji8_Czq75TVcQWIH1NTNhEHUxyx2js,21347
|
| 21 |
+
filelock/_async_read_write.py,sha256=C_cRi4sZ7_CWcqdEf0pcA5sdJ2m3EI_2tAW6kS_5P6I,7759
|
| 22 |
+
filelock/_error.py,sha256=mnelOh0EVyVeskG3rksL4kW3OArL4TMb2-PwmzQWIFg,788
|
| 23 |
+
filelock/_read_write.py,sha256=5tVPm1TDXvAu0sgva_LQJ4DH-SDo0rVxuYAFLEQGZw4,15323
|
| 24 |
+
filelock/_soft.py,sha256=t2Q3ikXjI5eVvNqNwntXH1i_Tm84_M9XSRBbtUOCrBc,7833
|
| 25 |
+
filelock/_soft_rw/__init__.py,sha256=_ktpGmVObzrvL0K1_EAV3LF7B9JarYxW-mx_eyGPhT0,370
|
| 26 |
+
filelock/_soft_rw/__pycache__/__init__.cpython-310.pyc,,
|
| 27 |
+
filelock/_soft_rw/__pycache__/_async.cpython-310.pyc,,
|
| 28 |
+
filelock/_soft_rw/__pycache__/_sync.cpython-310.pyc,,
|
| 29 |
+
filelock/_soft_rw/_async.py,sha256=3MdgJN0SBM-9-Msslt4HeikJtz2cc1tbeN1sWK9NV60,8704
|
| 30 |
+
filelock/_soft_rw/_sync.py,sha256=gBbGRLEEI42hh17uFGFB654HyAhkqJ0NJ4XFlvTX0Ac,34936
|
| 31 |
+
filelock/_unix.py,sha256=pbTsIi29Qv8zBtLsXqc3PzlS3wz2db53M1MIqVo9790,4579
|
| 32 |
+
filelock/_util.py,sha256=wPf-LvzmdHWHw4DinDeVJlB0GNVOYGNUeNKSnHBQuUU,1716
|
| 33 |
+
filelock/_windows.py,sha256=kJFOenaffOP6Qza2b3-yxgiPiDcyroWnzz9STGkCrgM,3943
|
| 34 |
+
filelock/asyncio.py,sha256=Hvcow3feO_EPvo24a_bgbsBoHkNeIiIqipUWoHrCWKk,14556
|
| 35 |
+
filelock/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 36 |
+
filelock/version.py,sha256=4Le-rJ-4B9xyzZ9-nsI0tuuRBBDrWPb68Dd8ybvGvJw,706
|
micromamba_root/envs/hf_sync/Lib/site-packages/filelock-3.29.0.dist-info/REQUESTED
ADDED
|
File without changes
|
micromamba_root/envs/hf_sync/Lib/site-packages/filelock-3.29.0.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: hatchling 1.29.0
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py3-none-any
|
micromamba_root/envs/hf_sync/Lib/site-packages/fsspec-2026.4.0.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
conda
|
micromamba_root/envs/hf_sync/Lib/site-packages/fsspec-2026.4.0.dist-info/METADATA
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.4
|
| 2 |
+
Name: fsspec
|
| 3 |
+
Version: 2026.4.0
|
| 4 |
+
Summary: File-system specification
|
| 5 |
+
Project-URL: Changelog, https://filesystem-spec.readthedocs.io/en/latest/changelog.html
|
| 6 |
+
Project-URL: Documentation, https://filesystem-spec.readthedocs.io/en/latest/
|
| 7 |
+
Project-URL: Homepage, https://github.com/fsspec/filesystem_spec
|
| 8 |
+
Maintainer-email: Martin Durant <mdurant@anaconda.com>
|
| 9 |
+
License-Expression: BSD-3-Clause
|
| 10 |
+
License-File: LICENSE
|
| 11 |
+
Keywords: file
|
| 12 |
+
Classifier: Development Status :: 4 - Beta
|
| 13 |
+
Classifier: Intended Audience :: Developers
|
| 14 |
+
Classifier: Operating System :: OS Independent
|
| 15 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 16 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 17 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 18 |
+
Classifier: Programming Language :: Python :: 3.13
|
| 19 |
+
Classifier: Programming Language :: Python :: 3.14
|
| 20 |
+
Requires-Python: >=3.10
|
| 21 |
+
Provides-Extra: abfs
|
| 22 |
+
Requires-Dist: adlfs; extra == 'abfs'
|
| 23 |
+
Provides-Extra: adl
|
| 24 |
+
Requires-Dist: adlfs; extra == 'adl'
|
| 25 |
+
Provides-Extra: arrow
|
| 26 |
+
Requires-Dist: pyarrow>=1; extra == 'arrow'
|
| 27 |
+
Provides-Extra: dask
|
| 28 |
+
Requires-Dist: dask; extra == 'dask'
|
| 29 |
+
Requires-Dist: distributed; extra == 'dask'
|
| 30 |
+
Provides-Extra: dev
|
| 31 |
+
Requires-Dist: pre-commit; extra == 'dev'
|
| 32 |
+
Requires-Dist: ruff>=0.5; extra == 'dev'
|
| 33 |
+
Provides-Extra: doc
|
| 34 |
+
Requires-Dist: numpydoc; extra == 'doc'
|
| 35 |
+
Requires-Dist: sphinx; extra == 'doc'
|
| 36 |
+
Requires-Dist: sphinx-design; extra == 'doc'
|
| 37 |
+
Requires-Dist: sphinx-rtd-theme; extra == 'doc'
|
| 38 |
+
Requires-Dist: yarl; extra == 'doc'
|
| 39 |
+
Provides-Extra: dropbox
|
| 40 |
+
Requires-Dist: dropbox; extra == 'dropbox'
|
| 41 |
+
Requires-Dist: dropboxdrivefs; extra == 'dropbox'
|
| 42 |
+
Requires-Dist: requests; extra == 'dropbox'
|
| 43 |
+
Provides-Extra: entrypoints
|
| 44 |
+
Provides-Extra: full
|
| 45 |
+
Requires-Dist: adlfs; extra == 'full'
|
| 46 |
+
Requires-Dist: aiohttp!=4.0.0a0,!=4.0.0a1; extra == 'full'
|
| 47 |
+
Requires-Dist: dask; extra == 'full'
|
| 48 |
+
Requires-Dist: distributed; extra == 'full'
|
| 49 |
+
Requires-Dist: dropbox; extra == 'full'
|
| 50 |
+
Requires-Dist: dropboxdrivefs; extra == 'full'
|
| 51 |
+
Requires-Dist: fusepy; extra == 'full'
|
| 52 |
+
Requires-Dist: gcsfs>2024.2.0; extra == 'full'
|
| 53 |
+
Requires-Dist: libarchive-c; extra == 'full'
|
| 54 |
+
Requires-Dist: ocifs; extra == 'full'
|
| 55 |
+
Requires-Dist: panel; extra == 'full'
|
| 56 |
+
Requires-Dist: paramiko; extra == 'full'
|
| 57 |
+
Requires-Dist: pyarrow>=1; extra == 'full'
|
| 58 |
+
Requires-Dist: pygit2; extra == 'full'
|
| 59 |
+
Requires-Dist: requests; extra == 'full'
|
| 60 |
+
Requires-Dist: s3fs>2024.2.0; extra == 'full'
|
| 61 |
+
Requires-Dist: smbprotocol; extra == 'full'
|
| 62 |
+
Requires-Dist: tqdm; extra == 'full'
|
| 63 |
+
Provides-Extra: fuse
|
| 64 |
+
Requires-Dist: fusepy; extra == 'fuse'
|
| 65 |
+
Provides-Extra: gcs
|
| 66 |
+
Requires-Dist: gcsfs>2024.2.0; extra == 'gcs'
|
| 67 |
+
Provides-Extra: git
|
| 68 |
+
Requires-Dist: pygit2; extra == 'git'
|
| 69 |
+
Provides-Extra: github
|
| 70 |
+
Requires-Dist: requests; extra == 'github'
|
| 71 |
+
Provides-Extra: gs
|
| 72 |
+
Requires-Dist: gcsfs; extra == 'gs'
|
| 73 |
+
Provides-Extra: gui
|
| 74 |
+
Requires-Dist: panel; extra == 'gui'
|
| 75 |
+
Provides-Extra: hdfs
|
| 76 |
+
Requires-Dist: pyarrow>=1; extra == 'hdfs'
|
| 77 |
+
Provides-Extra: http
|
| 78 |
+
Requires-Dist: aiohttp!=4.0.0a0,!=4.0.0a1; extra == 'http'
|
| 79 |
+
Provides-Extra: libarchive
|
| 80 |
+
Requires-Dist: libarchive-c; extra == 'libarchive'
|
| 81 |
+
Provides-Extra: oci
|
| 82 |
+
Requires-Dist: ocifs; extra == 'oci'
|
| 83 |
+
Provides-Extra: s3
|
| 84 |
+
Requires-Dist: s3fs>2024.2.0; extra == 's3'
|
| 85 |
+
Provides-Extra: sftp
|
| 86 |
+
Requires-Dist: paramiko; extra == 'sftp'
|
| 87 |
+
Provides-Extra: smb
|
| 88 |
+
Requires-Dist: smbprotocol; extra == 'smb'
|
| 89 |
+
Provides-Extra: ssh
|
| 90 |
+
Requires-Dist: paramiko; extra == 'ssh'
|
| 91 |
+
Provides-Extra: test
|
| 92 |
+
Requires-Dist: aiohttp!=4.0.0a0,!=4.0.0a1; extra == 'test'
|
| 93 |
+
Requires-Dist: numpy; extra == 'test'
|
| 94 |
+
Requires-Dist: pytest; extra == 'test'
|
| 95 |
+
Requires-Dist: pytest-asyncio!=0.22.0; extra == 'test'
|
| 96 |
+
Requires-Dist: pytest-benchmark; extra == 'test'
|
| 97 |
+
Requires-Dist: pytest-cov; extra == 'test'
|
| 98 |
+
Requires-Dist: pytest-mock; extra == 'test'
|
| 99 |
+
Requires-Dist: pytest-recording; extra == 'test'
|
| 100 |
+
Requires-Dist: pytest-rerunfailures; extra == 'test'
|
| 101 |
+
Requires-Dist: requests; extra == 'test'
|
| 102 |
+
Provides-Extra: test-downstream
|
| 103 |
+
Requires-Dist: aiobotocore<3.0.0,>=2.5.4; extra == 'test-downstream'
|
| 104 |
+
Requires-Dist: dask[dataframe,test]; extra == 'test-downstream'
|
| 105 |
+
Requires-Dist: moto[server]<5,>4; extra == 'test-downstream'
|
| 106 |
+
Requires-Dist: pytest-timeout; extra == 'test-downstream'
|
| 107 |
+
Requires-Dist: xarray; extra == 'test-downstream'
|
| 108 |
+
Provides-Extra: test-full
|
| 109 |
+
Requires-Dist: adlfs; extra == 'test-full'
|
| 110 |
+
Requires-Dist: aiohttp!=4.0.0a0,!=4.0.0a1; extra == 'test-full'
|
| 111 |
+
Requires-Dist: backports-zstd; (python_version < '3.14') and extra == 'test-full'
|
| 112 |
+
Requires-Dist: cloudpickle; extra == 'test-full'
|
| 113 |
+
Requires-Dist: dask; extra == 'test-full'
|
| 114 |
+
Requires-Dist: distributed; extra == 'test-full'
|
| 115 |
+
Requires-Dist: dropbox; extra == 'test-full'
|
| 116 |
+
Requires-Dist: dropboxdrivefs; extra == 'test-full'
|
| 117 |
+
Requires-Dist: fastparquet; extra == 'test-full'
|
| 118 |
+
Requires-Dist: fusepy; extra == 'test-full'
|
| 119 |
+
Requires-Dist: gcsfs; extra == 'test-full'
|
| 120 |
+
Requires-Dist: jinja2; extra == 'test-full'
|
| 121 |
+
Requires-Dist: kerchunk; extra == 'test-full'
|
| 122 |
+
Requires-Dist: libarchive-c; extra == 'test-full'
|
| 123 |
+
Requires-Dist: lz4; extra == 'test-full'
|
| 124 |
+
Requires-Dist: notebook; extra == 'test-full'
|
| 125 |
+
Requires-Dist: numpy; extra == 'test-full'
|
| 126 |
+
Requires-Dist: ocifs; extra == 'test-full'
|
| 127 |
+
Requires-Dist: pandas<3.0.0; extra == 'test-full'
|
| 128 |
+
Requires-Dist: panel; extra == 'test-full'
|
| 129 |
+
Requires-Dist: paramiko; extra == 'test-full'
|
| 130 |
+
Requires-Dist: pyarrow; extra == 'test-full'
|
| 131 |
+
Requires-Dist: pyarrow>=1; extra == 'test-full'
|
| 132 |
+
Requires-Dist: pyftpdlib; extra == 'test-full'
|
| 133 |
+
Requires-Dist: pygit2; extra == 'test-full'
|
| 134 |
+
Requires-Dist: pytest; extra == 'test-full'
|
| 135 |
+
Requires-Dist: pytest-asyncio!=0.22.0; extra == 'test-full'
|
| 136 |
+
Requires-Dist: pytest-benchmark; extra == 'test-full'
|
| 137 |
+
Requires-Dist: pytest-cov; extra == 'test-full'
|
| 138 |
+
Requires-Dist: pytest-mock; extra == 'test-full'
|
| 139 |
+
Requires-Dist: pytest-recording; extra == 'test-full'
|
| 140 |
+
Requires-Dist: pytest-rerunfailures; extra == 'test-full'
|
| 141 |
+
Requires-Dist: python-snappy; extra == 'test-full'
|
| 142 |
+
Requires-Dist: requests; extra == 'test-full'
|
| 143 |
+
Requires-Dist: smbprotocol; extra == 'test-full'
|
| 144 |
+
Requires-Dist: tqdm; extra == 'test-full'
|
| 145 |
+
Requires-Dist: urllib3; extra == 'test-full'
|
| 146 |
+
Requires-Dist: zarr; extra == 'test-full'
|
| 147 |
+
Requires-Dist: zstandard; (python_version < '3.14') and extra == 'test-full'
|
| 148 |
+
Provides-Extra: tqdm
|
| 149 |
+
Requires-Dist: tqdm; extra == 'tqdm'
|
| 150 |
+
Description-Content-Type: text/markdown
|
| 151 |
+
|
| 152 |
+
# filesystem_spec
|
| 153 |
+
|
| 154 |
+
[](https://pypi.python.org/pypi/fsspec/)
|
| 155 |
+
[](https://anaconda.org/conda-forge/fsspec)
|
| 156 |
+

|
| 157 |
+
[](https://filesystem-spec.readthedocs.io/en/latest/?badge=latest)
|
| 158 |
+
|
| 159 |
+
A specification for pythonic filesystems.
|
| 160 |
+
|
| 161 |
+
## Install
|
| 162 |
+
|
| 163 |
+
```bash
|
| 164 |
+
pip install fsspec
|
| 165 |
+
```
|
| 166 |
+
|
| 167 |
+
would install the base fsspec. Various optionally supported features might require specification of custom
|
| 168 |
+
extra require, e.g. `pip install fsspec[ssh]` will install dependencies for `ssh` backends support.
|
| 169 |
+
Use `pip install fsspec[full]` for installation of all known extra dependencies.
|
| 170 |
+
|
| 171 |
+
Up-to-date package also provided through conda-forge distribution:
|
| 172 |
+
|
| 173 |
+
```bash
|
| 174 |
+
conda install -c conda-forge fsspec
|
| 175 |
+
```
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
## Purpose
|
| 179 |
+
|
| 180 |
+
To produce a template or specification for a file-system interface, that specific implementations should follow,
|
| 181 |
+
so that applications making use of them can rely on a common behaviour and not have to worry about the specific
|
| 182 |
+
internal implementation decisions with any given backend. Many such implementations are included in this package,
|
| 183 |
+
or in sister projects such as `s3fs` and `gcsfs`.
|
| 184 |
+
|
| 185 |
+
In addition, if this is well-designed, then additional functionality, such as a key-value store or FUSE
|
| 186 |
+
mounting of the file-system implementation may be available for all implementations "for free".
|
| 187 |
+
|
| 188 |
+
## Documentation
|
| 189 |
+
|
| 190 |
+
Please refer to [RTD](https://filesystem-spec.readthedocs.io/en/latest/?badge=latest)
|
| 191 |
+
|
| 192 |
+
## Develop
|
| 193 |
+
|
| 194 |
+
fsspec uses GitHub Actions for CI. Environment files can be found
|
| 195 |
+
in the "ci/" directory. Note that the main environment is called "py38",
|
| 196 |
+
but it is expected that the version of python installed be adjustable at
|
| 197 |
+
CI runtime. For local use, pick a version suitable for you.
|
| 198 |
+
|
| 199 |
+
```bash
|
| 200 |
+
# For a new environment (mamba / conda).
|
| 201 |
+
mamba create -n fsspec -c conda-forge python=3.10 -y
|
| 202 |
+
conda activate fsspec
|
| 203 |
+
|
| 204 |
+
# Standard dev install with docs and tests.
|
| 205 |
+
pip install -e ".[dev,doc,test]"
|
| 206 |
+
|
| 207 |
+
# Full tests except for downstream
|
| 208 |
+
pip install s3fs
|
| 209 |
+
pip uninstall s3fs
|
| 210 |
+
pip install -e .[dev,doc,test_full]
|
| 211 |
+
pip install s3fs --no-deps
|
| 212 |
+
pytest -v
|
| 213 |
+
|
| 214 |
+
# Downstream tests.
|
| 215 |
+
sh install_s3fs.sh
|
| 216 |
+
# Windows powershell.
|
| 217 |
+
install_s3fs.sh
|
| 218 |
+
```
|
| 219 |
+
|
| 220 |
+
### Testing
|
| 221 |
+
|
| 222 |
+
Tests can be run in the dev environment, if activated, via ``pytest fsspec``.
|
| 223 |
+
|
| 224 |
+
The full fsspec suite requires a system-level docker, docker-compose, and fuse
|
| 225 |
+
installation. If only making changes to one backend implementation, it is
|
| 226 |
+
not generally necessary to run all tests locally.
|
| 227 |
+
|
| 228 |
+
It is expected that contributors ensure that any change to fsspec does not
|
| 229 |
+
cause issues or regressions for either other fsspec-related packages such
|
| 230 |
+
as gcsfs and s3fs, nor for downstream users of fsspec. The "downstream" CI
|
| 231 |
+
run and corresponding environment file run a set of tests from the dask
|
| 232 |
+
test suite, and very minimal tests against pandas and zarr from the
|
| 233 |
+
test_downstream.py module in this repo.
|
| 234 |
+
|
| 235 |
+
### Code Formatting
|
| 236 |
+
|
| 237 |
+
fsspec uses [Black](https://black.readthedocs.io/en/stable) to ensure
|
| 238 |
+
a consistent code format throughout the project.
|
| 239 |
+
Run ``black fsspec`` from the root of the filesystem_spec repository to
|
| 240 |
+
auto-format your code. Additionally, many editors have plugins that will apply
|
| 241 |
+
``black`` as you edit files. ``black`` is included in the ``tox`` environments.
|
| 242 |
+
|
| 243 |
+
Optionally, you may wish to setup [pre-commit hooks](https://pre-commit.com) to
|
| 244 |
+
automatically run ``black`` when you make a git commit.
|
| 245 |
+
Run ``pre-commit install --install-hooks`` from the root of the
|
| 246 |
+
filesystem_spec repository to setup pre-commit hooks. ``black`` will now be run
|
| 247 |
+
before you commit, reformatting any changed files. You can format without
|
| 248 |
+
committing via ``pre-commit run`` or skip these checks with ``git commit
|
| 249 |
+
--no-verify``.
|
| 250 |
+
|
| 251 |
+
## Support
|
| 252 |
+
|
| 253 |
+
Work on this repository is supported in part by:
|
| 254 |
+
|
| 255 |
+
"Anaconda, Inc. - Advancing AI through open source."
|
| 256 |
+
|
| 257 |
+
<a href="https://anaconda.com/"><img src="https://camo.githubusercontent.com/b8555ef2222598ed37ce38ac86955febbd25de7619931bb7dd3c58432181d3b6/68747470733a2f2f626565776172652e6f72672f636f6d6d756e6974792f6d656d626572732f616e61636f6e64612f616e61636f6e64612d6c617267652e706e67" alt="anaconda logo" width="40%"/></a>
|
micromamba_root/envs/hf_sync/Lib/site-packages/fsspec-2026.4.0.dist-info/RECORD
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fsspec-2026.4.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
| 2 |
+
fsspec-2026.4.0.dist-info/METADATA,sha256=j0nEQEtQcYKslT39RVFkHfC_Nsz2fgisimjM4yO_HUw,10524
|
| 3 |
+
fsspec-2026.4.0.dist-info/RECORD,,
|
| 4 |
+
fsspec-2026.4.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 5 |
+
fsspec-2026.4.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
|
| 6 |
+
fsspec-2026.4.0.dist-info/direct_url.json,sha256=-Eo-yqU3gMabIVL38ARhUbN2D6bAAoYRbZc0ZirH2C8,102
|
| 7 |
+
fsspec-2026.4.0.dist-info/licenses/LICENSE,sha256=LcNUls5TpzB5FcAIqESq1T53K0mzTN0ARFBnaRQH7JQ,1513
|
| 8 |
+
fsspec/__init__.py,sha256=L7qwNBU1iMNQd8Of87HYSNFT9gWlNMSESaJC8fY0AaQ,2053
|
| 9 |
+
fsspec/__pycache__/__init__.cpython-310.pyc,,
|
| 10 |
+
fsspec/__pycache__/_version.cpython-310.pyc,,
|
| 11 |
+
fsspec/__pycache__/archive.cpython-310.pyc,,
|
| 12 |
+
fsspec/__pycache__/asyn.cpython-310.pyc,,
|
| 13 |
+
fsspec/__pycache__/caching.cpython-310.pyc,,
|
| 14 |
+
fsspec/__pycache__/callbacks.cpython-310.pyc,,
|
| 15 |
+
fsspec/__pycache__/compression.cpython-310.pyc,,
|
| 16 |
+
fsspec/__pycache__/config.cpython-310.pyc,,
|
| 17 |
+
fsspec/__pycache__/conftest.cpython-310.pyc,,
|
| 18 |
+
fsspec/__pycache__/core.cpython-310.pyc,,
|
| 19 |
+
fsspec/__pycache__/dircache.cpython-310.pyc,,
|
| 20 |
+
fsspec/__pycache__/exceptions.cpython-310.pyc,,
|
| 21 |
+
fsspec/__pycache__/fuse.cpython-310.pyc,,
|
| 22 |
+
fsspec/__pycache__/generic.cpython-310.pyc,,
|
| 23 |
+
fsspec/__pycache__/gui.cpython-310.pyc,,
|
| 24 |
+
fsspec/__pycache__/json.cpython-310.pyc,,
|
| 25 |
+
fsspec/__pycache__/mapping.cpython-310.pyc,,
|
| 26 |
+
fsspec/__pycache__/parquet.cpython-310.pyc,,
|
| 27 |
+
fsspec/__pycache__/registry.cpython-310.pyc,,
|
| 28 |
+
fsspec/__pycache__/spec.cpython-310.pyc,,
|
| 29 |
+
fsspec/__pycache__/transaction.cpython-310.pyc,,
|
| 30 |
+
fsspec/__pycache__/utils.cpython-310.pyc,,
|
| 31 |
+
fsspec/_version.py,sha256=L6bg65FquXTdggUUrxNrzQfQ_PFoq2hhtHnBDAFLAVA,710
|
| 32 |
+
fsspec/archive.py,sha256=vM6t_lgV6lBWbBYwpm3S4ofBQFQxUPr5KkDQrrQcQro,2411
|
| 33 |
+
fsspec/asyn.py,sha256=8vfpg8iNXerqo9byws0HmMzygZJ_LrMJ_jhS5b3sI10,37585
|
| 34 |
+
fsspec/caching.py,sha256=YJm7SjQTxOgyavKvAE0CST_GR0mpnEjnIIWCdE1QbLk,34024
|
| 35 |
+
fsspec/callbacks.py,sha256=BDIwLzK6rr_0V5ch557fSzsivCElpdqhXr5dZ9Te-EE,9210
|
| 36 |
+
fsspec/compression.py,sha256=3v_Fe39gzRRWfaeXpzNjAGPqgTzmETYRCo3qHVqD3po,5132
|
| 37 |
+
fsspec/config.py,sha256=mHKzAgjXa_LwqtO_VoTJJ568VqwYkbK3gUp4J6JZJp4,4238
|
| 38 |
+
fsspec/conftest.py,sha256=uWfm_Qs5alPRxOhRpDfQ0-1jqSJ54pni4y96IxOREXM,3446
|
| 39 |
+
fsspec/core.py,sha256=lc7XSnZU6_C6xljp7Z_xEGN3V7704hbeQLkxvPP0wds,24173
|
| 40 |
+
fsspec/dircache.py,sha256=YzogWJrhEastHU7vWz-cJiJ7sdtLXFXhEpInGKd4EcM,2717
|
| 41 |
+
fsspec/exceptions.py,sha256=pauSLDMxzTJMOjvX1WEUK0cMyFkrFxpWJsyFywav7A8,331
|
| 42 |
+
fsspec/fuse.py,sha256=Q-3NOOyLqBfYa4Db5E19z_ZY36zzYHtIs1mOUasItBQ,10177
|
| 43 |
+
fsspec/generic.py,sha256=9QHQYMNb-8w8-eYuIqShcTjO_LeHXFoQTyt8J5oEq5Q,13482
|
| 44 |
+
fsspec/gui.py,sha256=CQ7QsrTpaDlWSLNOpwNoJc7khOcYXIZxmrAJN9bHWQU,14002
|
| 45 |
+
fsspec/implementations/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 46 |
+
fsspec/implementations/__pycache__/__init__.cpython-310.pyc,,
|
| 47 |
+
fsspec/implementations/__pycache__/arrow.cpython-310.pyc,,
|
| 48 |
+
fsspec/implementations/__pycache__/asyn_wrapper.cpython-310.pyc,,
|
| 49 |
+
fsspec/implementations/__pycache__/cache_mapper.cpython-310.pyc,,
|
| 50 |
+
fsspec/implementations/__pycache__/cache_metadata.cpython-310.pyc,,
|
| 51 |
+
fsspec/implementations/__pycache__/cached.cpython-310.pyc,,
|
| 52 |
+
fsspec/implementations/__pycache__/chained.cpython-310.pyc,,
|
| 53 |
+
fsspec/implementations/__pycache__/dask.cpython-310.pyc,,
|
| 54 |
+
fsspec/implementations/__pycache__/data.cpython-310.pyc,,
|
| 55 |
+
fsspec/implementations/__pycache__/dbfs.cpython-310.pyc,,
|
| 56 |
+
fsspec/implementations/__pycache__/dirfs.cpython-310.pyc,,
|
| 57 |
+
fsspec/implementations/__pycache__/ftp.cpython-310.pyc,,
|
| 58 |
+
fsspec/implementations/__pycache__/gist.cpython-310.pyc,,
|
| 59 |
+
fsspec/implementations/__pycache__/git.cpython-310.pyc,,
|
| 60 |
+
fsspec/implementations/__pycache__/github.cpython-310.pyc,,
|
| 61 |
+
fsspec/implementations/__pycache__/http.cpython-310.pyc,,
|
| 62 |
+
fsspec/implementations/__pycache__/http_sync.cpython-310.pyc,,
|
| 63 |
+
fsspec/implementations/__pycache__/jupyter.cpython-310.pyc,,
|
| 64 |
+
fsspec/implementations/__pycache__/libarchive.cpython-310.pyc,,
|
| 65 |
+
fsspec/implementations/__pycache__/local.cpython-310.pyc,,
|
| 66 |
+
fsspec/implementations/__pycache__/memory.cpython-310.pyc,,
|
| 67 |
+
fsspec/implementations/__pycache__/reference.cpython-310.pyc,,
|
| 68 |
+
fsspec/implementations/__pycache__/sftp.cpython-310.pyc,,
|
| 69 |
+
fsspec/implementations/__pycache__/smb.cpython-310.pyc,,
|
| 70 |
+
fsspec/implementations/__pycache__/tar.cpython-310.pyc,,
|
| 71 |
+
fsspec/implementations/__pycache__/webhdfs.cpython-310.pyc,,
|
| 72 |
+
fsspec/implementations/__pycache__/zip.cpython-310.pyc,,
|
| 73 |
+
fsspec/implementations/arrow.py,sha256=8FhvcvOYLZNMMegCYFFCEHgEqig8AkOU7Ehb8XfcgnA,8890
|
| 74 |
+
fsspec/implementations/asyn_wrapper.py,sha256=3lfJkGs6D_AwRBdxTSYlL-RCVdaXBZ9Itys2P5o5Si0,3738
|
| 75 |
+
fsspec/implementations/cache_mapper.py,sha256=W4wlxyPxZbSp9ItJ0pYRVBMh6bw9eFypgP6kUYuuiI4,2421
|
| 76 |
+
fsspec/implementations/cache_metadata.py,sha256=_AGOfy46vIDseS7eQRk7IgmKMbKhEksOv9PuW7Lo5YA,8502
|
| 77 |
+
fsspec/implementations/cached.py,sha256=38B4qVDDXRh65Zb_JXy2-lJOxtdgUdBgNdy-oBe6jGw,36375
|
| 78 |
+
fsspec/implementations/chained.py,sha256=iGivpNaHUFjB_ea0-HAPhcmm6CL8qnDf270PSj7JwuE,680
|
| 79 |
+
fsspec/implementations/dask.py,sha256=CXZbJzIVOhKV8ILcxuy3bTvcacCueAbyQxmvAkbPkrk,4466
|
| 80 |
+
fsspec/implementations/data.py,sha256=IhOGDkacYp5gkl9jhEu4msQfZPb0gS5Q_ml7Mbr6dgQ,1627
|
| 81 |
+
fsspec/implementations/dbfs.py,sha256=1cvvC6KBWOb8pBVpc01xavVbEPXO1xsgZvPD7H73M9k,16217
|
| 82 |
+
fsspec/implementations/dirfs.py,sha256=5JAp_nn9v1OjKY3MwuRkLrqeZ8gGYlILSQRqkQQdz7k,12624
|
| 83 |
+
fsspec/implementations/ftp.py,sha256=fJhaMIKq2RvzYlLwG3bewy2jq4iRqjVt1aIpwtUIRwI,13235
|
| 84 |
+
fsspec/implementations/gist.py,sha256=Y6jTDrE-wuTwvpPyAQDuuOMBGxlajafKWoB1_yX6jdY,8528
|
| 85 |
+
fsspec/implementations/git.py,sha256=qBDWMz5LNllPqVjr5jf_1FuNha4P5lyQI3IlhYg-wUE,3731
|
| 86 |
+
fsspec/implementations/github.py,sha256=aCsZL8UvXZgdkcB1RUs3DdLeNrjLKcFsFYeQFDWbBFo,11653
|
| 87 |
+
fsspec/implementations/http.py,sha256=1uWwxllOjPe8mQD54IrCYQJHU1YaAXh_cDmXBk-AoQ8,30894
|
| 88 |
+
fsspec/implementations/http_sync.py,sha256=UmBqd938ebwVjYgVtzg-ysG3ZoGhIJw0wFtQAfxV3Aw,30332
|
| 89 |
+
fsspec/implementations/jupyter.py,sha256=q1PlQ66AAswGFyr8MFKWyobaV2YekMWRtqENBDQtD28,4002
|
| 90 |
+
fsspec/implementations/libarchive.py,sha256=SpIA1F-zf7kb2-VYUVuhMrXTBOhBxUXKgEW1RaAdDoA,7098
|
| 91 |
+
fsspec/implementations/local.py,sha256=aVEUnAB2hkxmweXLCiB4XD_KPwDL-gMX4dN9Fz-pk7k,17161
|
| 92 |
+
fsspec/implementations/memory.py,sha256=TDdLtSPWXxZKrrVGwmc3uS3oK_2mlcVTk2BiqR8IeII,10507
|
| 93 |
+
fsspec/implementations/reference.py,sha256=9FDzS7nzxifOnd9azaeBiuSuspSDTQ0YiTYdflJrEFs,49198
|
| 94 |
+
fsspec/implementations/sftp.py,sha256=v7t-LpD4hEycHnw1kbepyoNgrhClshXQXitFuY4mBWE,5951
|
| 95 |
+
fsspec/implementations/smb.py,sha256=5fhu8h06nOLBPh2c48aT7WBRqh9cEcbIwtyu06wTjec,15236
|
| 96 |
+
fsspec/implementations/tar.py,sha256=0gqTHdwmwQI1Ia8rNQjuAVjNgrEFKPbdPkmndR9vpmk,4451
|
| 97 |
+
fsspec/implementations/webhdfs.py,sha256=osF2m0nhDil6sbMzYW_4DZzhxF4ygtb59XDiybd9Fyg,17589
|
| 98 |
+
fsspec/implementations/zip.py,sha256=GPDJh4UtUNJmaqijUQ0eiEZIGpwusQjkIcbhsrmLSi0,6263
|
| 99 |
+
fsspec/json.py,sha256=4EBZ-xOmRiyxmIqPIwxmDImosRQ7io7qBM2xjJPsEE4,3768
|
| 100 |
+
fsspec/mapping.py,sha256=m2ndB_gtRBXYmNJg0Ie1-BVR75TFleHmIQBzC-yWhjU,8343
|
| 101 |
+
fsspec/parquet.py,sha256=0SzfswUTc2k5nAj7xZNYPPyvUkFNXznFRXXtBRhr-iE,20506
|
| 102 |
+
fsspec/registry.py,sha256=KeDNL9HOyHX_D4D4qQGAI-Y3DQhiLeUC1VK2I81NZaE,12344
|
| 103 |
+
fsspec/spec.py,sha256=XKhR4bDdhuhaGcMhgKThCmi6sBwv6cSRMr0SSFmCBHE,77766
|
| 104 |
+
fsspec/tests/abstract/__init__.py,sha256=4xUJrv7gDgc85xAOz1p-V_K1hrsdMWTSa0rviALlJk8,10181
|
| 105 |
+
fsspec/tests/abstract/__pycache__/__init__.cpython-310.pyc,,
|
| 106 |
+
fsspec/tests/abstract/__pycache__/common.cpython-310.pyc,,
|
| 107 |
+
fsspec/tests/abstract/__pycache__/copy.cpython-310.pyc,,
|
| 108 |
+
fsspec/tests/abstract/__pycache__/get.cpython-310.pyc,,
|
| 109 |
+
fsspec/tests/abstract/__pycache__/mv.cpython-310.pyc,,
|
| 110 |
+
fsspec/tests/abstract/__pycache__/open.cpython-310.pyc,,
|
| 111 |
+
fsspec/tests/abstract/__pycache__/pipe.cpython-310.pyc,,
|
| 112 |
+
fsspec/tests/abstract/__pycache__/put.cpython-310.pyc,,
|
| 113 |
+
fsspec/tests/abstract/common.py,sha256=1GQwNo5AONzAnzZj0fWgn8NJPLXALehbsuGxS3FzWVU,4973
|
| 114 |
+
fsspec/tests/abstract/copy.py,sha256=gU5-d97U3RSde35Vp4RxPY4rWwL744HiSrJ8IBOp9-8,19967
|
| 115 |
+
fsspec/tests/abstract/get.py,sha256=vNR4HztvTR7Cj56AMo7_tx7TeYz1Jgr_2Wb8Lv-UiBY,20755
|
| 116 |
+
fsspec/tests/abstract/mv.py,sha256=k8eUEBIrRrGMsBY5OOaDXdGnQUKGwDIfQyduB6YD3Ns,1982
|
| 117 |
+
fsspec/tests/abstract/open.py,sha256=Fi2PBPYLbRqysF8cFm0rwnB41kMdQVYjq8cGyDXp3BU,329
|
| 118 |
+
fsspec/tests/abstract/pipe.py,sha256=LFzIrLCB5GLXf9rzFKJmE8AdG7LQ_h4bJo70r8FLPqM,402
|
| 119 |
+
fsspec/tests/abstract/put.py,sha256=7aih17OKB_IZZh1Mkq1eBDIjobhtMQmI8x-Pw-S_aZk,21201
|
| 120 |
+
fsspec/transaction.py,sha256=xliRG6U2Zf3khG4xcw9WiB-yAoqJSHEGK_VjHOdtgo0,2398
|
| 121 |
+
fsspec/utils.py,sha256=E24ji0XLWC6n3bw2sHA28OYxrGU9Wy_al2XydsRgrRk,23623
|
micromamba_root/envs/hf_sync/Lib/site-packages/fsspec-2026.4.0.dist-info/REQUESTED
ADDED
|
File without changes
|
micromamba_root/envs/hf_sync/Lib/site-packages/fsspec-2026.4.0.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: hatchling 1.29.0
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py3-none-any
|
micromamba_root/envs/hf_sync/Lib/site-packages/fsspec-2026.4.0.dist-info/direct_url.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"dir_info": {}, "url": "file:///home/conda/feedstock_root/build_artifacts/fsspec_1777547723461/work"}
|
micromamba_root/envs/hf_sync/Lib/site-packages/fsspec/__init__.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from . import caching
|
| 2 |
+
from ._version import __version__ # noqa: F401
|
| 3 |
+
from .callbacks import Callback
|
| 4 |
+
from .compression import available_compressions
|
| 5 |
+
from .core import get_fs_token_paths, open, open_files, open_local, url_to_fs
|
| 6 |
+
from .exceptions import FSTimeoutError
|
| 7 |
+
from .mapping import FSMap, get_mapper
|
| 8 |
+
from .registry import (
|
| 9 |
+
available_protocols,
|
| 10 |
+
filesystem,
|
| 11 |
+
get_filesystem_class,
|
| 12 |
+
register_implementation,
|
| 13 |
+
registry,
|
| 14 |
+
)
|
| 15 |
+
from .spec import AbstractFileSystem
|
| 16 |
+
|
| 17 |
+
__all__ = [
|
| 18 |
+
"AbstractFileSystem",
|
| 19 |
+
"FSTimeoutError",
|
| 20 |
+
"FSMap",
|
| 21 |
+
"filesystem",
|
| 22 |
+
"register_implementation",
|
| 23 |
+
"get_filesystem_class",
|
| 24 |
+
"get_fs_token_paths",
|
| 25 |
+
"get_mapper",
|
| 26 |
+
"open",
|
| 27 |
+
"open_files",
|
| 28 |
+
"open_local",
|
| 29 |
+
"registry",
|
| 30 |
+
"caching",
|
| 31 |
+
"Callback",
|
| 32 |
+
"available_protocols",
|
| 33 |
+
"available_compressions",
|
| 34 |
+
"url_to_fs",
|
| 35 |
+
]
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def process_entries():
|
| 39 |
+
try:
|
| 40 |
+
from importlib.metadata import entry_points
|
| 41 |
+
except ImportError:
|
| 42 |
+
return
|
| 43 |
+
if entry_points is not None:
|
| 44 |
+
try:
|
| 45 |
+
eps = entry_points()
|
| 46 |
+
except TypeError:
|
| 47 |
+
pass # importlib-metadata < 0.8
|
| 48 |
+
else:
|
| 49 |
+
if hasattr(eps, "select"): # Python 3.10+ / importlib_metadata >= 3.9.0
|
| 50 |
+
specs = eps.select(group="fsspec.specs")
|
| 51 |
+
else:
|
| 52 |
+
specs = eps.get("fsspec.specs", [])
|
| 53 |
+
registered_names = {}
|
| 54 |
+
for spec in specs:
|
| 55 |
+
err_msg = f"Unable to load filesystem from {spec}"
|
| 56 |
+
name = spec.name
|
| 57 |
+
if name in registered_names:
|
| 58 |
+
continue
|
| 59 |
+
registered_names[name] = True
|
| 60 |
+
register_implementation(
|
| 61 |
+
name,
|
| 62 |
+
spec.value.replace(":", "."),
|
| 63 |
+
errtxt=err_msg,
|
| 64 |
+
# We take our implementations as the ones to overload with if
|
| 65 |
+
# for some reason we encounter some, may be the same, already
|
| 66 |
+
# registered
|
| 67 |
+
clobber=True,
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
process_entries()
|
micromamba_root/envs/hf_sync/Lib/site-packages/fsspec/_version.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# file generated by setuptools-scm
|
| 2 |
+
# don't change, don't track in version control
|
| 3 |
+
|
| 4 |
+
__all__ = [
|
| 5 |
+
"__version__",
|
| 6 |
+
"__version_tuple__",
|
| 7 |
+
"version",
|
| 8 |
+
"version_tuple",
|
| 9 |
+
"__commit_id__",
|
| 10 |
+
"commit_id",
|
| 11 |
+
]
|
| 12 |
+
|
| 13 |
+
TYPE_CHECKING = False
|
| 14 |
+
if TYPE_CHECKING:
|
| 15 |
+
from typing import Tuple
|
| 16 |
+
from typing import Union
|
| 17 |
+
|
| 18 |
+
VERSION_TUPLE = Tuple[Union[int, str], ...]
|
| 19 |
+
COMMIT_ID = Union[str, None]
|
| 20 |
+
else:
|
| 21 |
+
VERSION_TUPLE = object
|
| 22 |
+
COMMIT_ID = object
|
| 23 |
+
|
| 24 |
+
version: str
|
| 25 |
+
__version__: str
|
| 26 |
+
__version_tuple__: VERSION_TUPLE
|
| 27 |
+
version_tuple: VERSION_TUPLE
|
| 28 |
+
commit_id: COMMIT_ID
|
| 29 |
+
__commit_id__: COMMIT_ID
|
| 30 |
+
|
| 31 |
+
__version__ = version = '2026.4.0'
|
| 32 |
+
__version_tuple__ = version_tuple = (2026, 4, 0)
|
| 33 |
+
|
| 34 |
+
__commit_id__ = commit_id = None
|
micromamba_root/envs/hf_sync/Lib/site-packages/fsspec/archive.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import operator
|
| 2 |
+
|
| 3 |
+
from fsspec import AbstractFileSystem
|
| 4 |
+
from fsspec.utils import tokenize
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class AbstractArchiveFileSystem(AbstractFileSystem):
|
| 8 |
+
"""
|
| 9 |
+
A generic superclass for implementing Archive-based filesystems.
|
| 10 |
+
|
| 11 |
+
Currently, it is shared amongst
|
| 12 |
+
:class:`~fsspec.implementations.zip.ZipFileSystem`,
|
| 13 |
+
:class:`~fsspec.implementations.libarchive.LibArchiveFileSystem` and
|
| 14 |
+
:class:`~fsspec.implementations.tar.TarFileSystem`.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
def __str__(self):
|
| 18 |
+
return f"<Archive-like object {type(self).__name__} at {id(self)}>"
|
| 19 |
+
|
| 20 |
+
__repr__ = __str__
|
| 21 |
+
|
| 22 |
+
def ukey(self, path):
|
| 23 |
+
return tokenize(path, self.fo, self.protocol)
|
| 24 |
+
|
| 25 |
+
def _all_dirnames(self, paths):
|
| 26 |
+
"""Returns *all* directory names for each path in paths, including intermediate
|
| 27 |
+
ones.
|
| 28 |
+
|
| 29 |
+
Parameters
|
| 30 |
+
----------
|
| 31 |
+
paths: Iterable of path strings
|
| 32 |
+
"""
|
| 33 |
+
if len(paths) == 0:
|
| 34 |
+
return set()
|
| 35 |
+
|
| 36 |
+
dirnames = {self._parent(path) for path in paths} - {self.root_marker}
|
| 37 |
+
return dirnames | self._all_dirnames(dirnames)
|
| 38 |
+
|
| 39 |
+
def info(self, path, **kwargs):
|
| 40 |
+
self._get_dirs()
|
| 41 |
+
path = self._strip_protocol(path)
|
| 42 |
+
if path in {"", "/"} and self.dir_cache:
|
| 43 |
+
return {"name": "", "type": "directory", "size": 0}
|
| 44 |
+
if path in self.dir_cache:
|
| 45 |
+
return self.dir_cache[path]
|
| 46 |
+
elif path + "/" in self.dir_cache:
|
| 47 |
+
return self.dir_cache[path + "/"]
|
| 48 |
+
else:
|
| 49 |
+
raise FileNotFoundError(path)
|
| 50 |
+
|
| 51 |
+
def ls(self, path, detail=True, **kwargs):
|
| 52 |
+
self._get_dirs()
|
| 53 |
+
paths = {}
|
| 54 |
+
for p, f in self.dir_cache.items():
|
| 55 |
+
p = p.rstrip("/")
|
| 56 |
+
if "/" in p:
|
| 57 |
+
root = p.rsplit("/", 1)[0]
|
| 58 |
+
else:
|
| 59 |
+
root = ""
|
| 60 |
+
if root == path.rstrip("/"):
|
| 61 |
+
paths[p] = f
|
| 62 |
+
elif all(
|
| 63 |
+
(a == b)
|
| 64 |
+
for a, b in zip(path.split("/"), [""] + p.strip("/").split("/"))
|
| 65 |
+
):
|
| 66 |
+
# root directory entry
|
| 67 |
+
ppath = p.rstrip("/").split("/", 1)[0]
|
| 68 |
+
if ppath not in paths:
|
| 69 |
+
out = {"name": ppath, "size": 0, "type": "directory"}
|
| 70 |
+
paths[ppath] = out
|
| 71 |
+
if detail:
|
| 72 |
+
out = sorted(paths.values(), key=operator.itemgetter("name"))
|
| 73 |
+
return out
|
| 74 |
+
else:
|
| 75 |
+
return sorted(paths)
|
micromamba_root/envs/hf_sync/Lib/site-packages/fsspec/asyn.py
ADDED
|
@@ -0,0 +1,1127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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+
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 get_loop():
|
| 124 |
+
"""Create or return the default fsspec IO loop
|
| 125 |
+
|
| 126 |
+
The loop will be running on a separate thread.
|
| 127 |
+
"""
|
| 128 |
+
if loop[0] is None:
|
| 129 |
+
with get_lock():
|
| 130 |
+
# repeat the check just in case the loop got filled between the
|
| 131 |
+
# previous two calls from another thread
|
| 132 |
+
if loop[0] is None:
|
| 133 |
+
loop[0] = asyncio.new_event_loop()
|
| 134 |
+
th = threading.Thread(target=loop[0].run_forever, name="fsspecIO")
|
| 135 |
+
th.daemon = True
|
| 136 |
+
th.start()
|
| 137 |
+
iothread[0] = th
|
| 138 |
+
return loop[0]
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def reset_after_fork():
|
| 142 |
+
global lock
|
| 143 |
+
loop[0] = None
|
| 144 |
+
iothread[0] = None
|
| 145 |
+
lock = None
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
if hasattr(os, "register_at_fork"):
|
| 149 |
+
# should be posix; this will do nothing for spawn or forkserver subprocesses
|
| 150 |
+
os.register_at_fork(after_in_child=reset_after_fork)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
if TYPE_CHECKING:
|
| 154 |
+
import resource
|
| 155 |
+
|
| 156 |
+
ResourceError = resource.error
|
| 157 |
+
else:
|
| 158 |
+
try:
|
| 159 |
+
import resource
|
| 160 |
+
except ImportError:
|
| 161 |
+
resource = None
|
| 162 |
+
ResourceError = OSError
|
| 163 |
+
else:
|
| 164 |
+
ResourceError = getattr(resource, "error", OSError)
|
| 165 |
+
|
| 166 |
+
_DEFAULT_BATCH_SIZE = 128
|
| 167 |
+
_NOFILES_DEFAULT_BATCH_SIZE = 1280
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def _get_batch_size(nofiles=False):
|
| 171 |
+
from fsspec.config import conf
|
| 172 |
+
|
| 173 |
+
if nofiles:
|
| 174 |
+
if "nofiles_gather_batch_size" in conf:
|
| 175 |
+
return conf["nofiles_gather_batch_size"]
|
| 176 |
+
else:
|
| 177 |
+
if "gather_batch_size" in conf:
|
| 178 |
+
return conf["gather_batch_size"]
|
| 179 |
+
if nofiles:
|
| 180 |
+
return _NOFILES_DEFAULT_BATCH_SIZE
|
| 181 |
+
if resource is None:
|
| 182 |
+
return _DEFAULT_BATCH_SIZE
|
| 183 |
+
|
| 184 |
+
try:
|
| 185 |
+
soft_limit, _ = resource.getrlimit(resource.RLIMIT_NOFILE)
|
| 186 |
+
except (ImportError, ValueError, ResourceError):
|
| 187 |
+
return _DEFAULT_BATCH_SIZE
|
| 188 |
+
|
| 189 |
+
if soft_limit == resource.RLIM_INFINITY:
|
| 190 |
+
return -1
|
| 191 |
+
else:
|
| 192 |
+
return soft_limit // 8
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def running_async() -> bool:
|
| 196 |
+
"""Being executed by an event loop?"""
|
| 197 |
+
try:
|
| 198 |
+
asyncio.get_running_loop()
|
| 199 |
+
return True
|
| 200 |
+
except RuntimeError:
|
| 201 |
+
return False
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
async def _run_coros_in_chunks(
|
| 205 |
+
coros,
|
| 206 |
+
batch_size=None,
|
| 207 |
+
callback=DEFAULT_CALLBACK,
|
| 208 |
+
timeout=None,
|
| 209 |
+
return_exceptions=False,
|
| 210 |
+
nofiles=False,
|
| 211 |
+
):
|
| 212 |
+
"""Run the given coroutines in chunks.
|
| 213 |
+
|
| 214 |
+
Parameters
|
| 215 |
+
----------
|
| 216 |
+
coros: list of coroutines to run
|
| 217 |
+
batch_size: int or None
|
| 218 |
+
Number of coroutines to submit/wait on simultaneously.
|
| 219 |
+
If -1, then it will not be any throttling. If
|
| 220 |
+
None, it will be inferred from _get_batch_size()
|
| 221 |
+
callback: fsspec.callbacks.Callback instance
|
| 222 |
+
Gets a relative_update when each coroutine completes
|
| 223 |
+
timeout: number or None
|
| 224 |
+
If given, each coroutine times out after this time. Note that, since
|
| 225 |
+
there are multiple batches, the total run time of this function will in
|
| 226 |
+
general be longer
|
| 227 |
+
return_exceptions: bool
|
| 228 |
+
Same meaning as in asyncio.gather
|
| 229 |
+
nofiles: bool
|
| 230 |
+
If inferring the batch_size, does this operation involve local files?
|
| 231 |
+
If yes, you normally expect smaller batches.
|
| 232 |
+
"""
|
| 233 |
+
|
| 234 |
+
if batch_size is None:
|
| 235 |
+
batch_size = _get_batch_size(nofiles=nofiles)
|
| 236 |
+
|
| 237 |
+
if batch_size == -1:
|
| 238 |
+
batch_size = len(coros)
|
| 239 |
+
|
| 240 |
+
assert batch_size > 0
|
| 241 |
+
|
| 242 |
+
async def _run_coro(coro, i):
|
| 243 |
+
try:
|
| 244 |
+
return await asyncio.wait_for(coro, timeout=timeout), i
|
| 245 |
+
except Exception as e:
|
| 246 |
+
if not return_exceptions:
|
| 247 |
+
raise
|
| 248 |
+
return e, i
|
| 249 |
+
finally:
|
| 250 |
+
callback.relative_update(1)
|
| 251 |
+
|
| 252 |
+
i = 0
|
| 253 |
+
n = len(coros)
|
| 254 |
+
results = [None] * n
|
| 255 |
+
pending = set()
|
| 256 |
+
|
| 257 |
+
while pending or i < n:
|
| 258 |
+
while len(pending) < batch_size and i < n:
|
| 259 |
+
pending.add(asyncio.ensure_future(_run_coro(coros[i], i)))
|
| 260 |
+
i += 1
|
| 261 |
+
|
| 262 |
+
if not pending:
|
| 263 |
+
break
|
| 264 |
+
|
| 265 |
+
done, pending = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)
|
| 266 |
+
first_exc = None
|
| 267 |
+
while done:
|
| 268 |
+
task = done.pop()
|
| 269 |
+
try:
|
| 270 |
+
result, k = await task
|
| 271 |
+
results[k] = result
|
| 272 |
+
except Exception as exc:
|
| 273 |
+
if first_exc is None:
|
| 274 |
+
first_exc = exc
|
| 275 |
+
|
| 276 |
+
if first_exc is not None:
|
| 277 |
+
for task in pending:
|
| 278 |
+
task.cancel()
|
| 279 |
+
if pending:
|
| 280 |
+
await asyncio.gather(*pending, return_exceptions=True)
|
| 281 |
+
raise first_exc
|
| 282 |
+
|
| 283 |
+
return results
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
# these methods should be implemented as async by any async-able backend
|
| 287 |
+
async_methods = [
|
| 288 |
+
"_ls",
|
| 289 |
+
"_cat_file",
|
| 290 |
+
"_get_file",
|
| 291 |
+
"_put_file",
|
| 292 |
+
"_rm_file",
|
| 293 |
+
"_cp_file",
|
| 294 |
+
"_pipe_file",
|
| 295 |
+
"_expand_path",
|
| 296 |
+
"_info",
|
| 297 |
+
"_isfile",
|
| 298 |
+
"_isdir",
|
| 299 |
+
"_exists",
|
| 300 |
+
"_walk",
|
| 301 |
+
"_glob",
|
| 302 |
+
"_find",
|
| 303 |
+
"_du",
|
| 304 |
+
"_size",
|
| 305 |
+
"_mkdir",
|
| 306 |
+
"_makedirs",
|
| 307 |
+
]
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
class AsyncFileSystem(AbstractFileSystem):
|
| 311 |
+
"""Async file operations, default implementations
|
| 312 |
+
|
| 313 |
+
Passes bulk operations to asyncio.gather for concurrent operation.
|
| 314 |
+
|
| 315 |
+
Implementations that have concurrent batch operations and/or async methods
|
| 316 |
+
should inherit from this class instead of AbstractFileSystem. Docstrings are
|
| 317 |
+
copied from the un-underscored method in AbstractFileSystem, if not given.
|
| 318 |
+
"""
|
| 319 |
+
|
| 320 |
+
# note that methods do not have docstring here; they will be copied
|
| 321 |
+
# for _* methods and inferred for overridden methods.
|
| 322 |
+
|
| 323 |
+
async_impl = True
|
| 324 |
+
mirror_sync_methods = True
|
| 325 |
+
disable_throttling = False
|
| 326 |
+
|
| 327 |
+
def __init__(self, *args, asynchronous=False, loop=None, batch_size=None, **kwargs):
|
| 328 |
+
self.asynchronous = asynchronous
|
| 329 |
+
self._pid = os.getpid()
|
| 330 |
+
if not asynchronous:
|
| 331 |
+
self._loop = loop or get_loop()
|
| 332 |
+
else:
|
| 333 |
+
self._loop = None
|
| 334 |
+
self.batch_size = batch_size
|
| 335 |
+
super().__init__(*args, **kwargs)
|
| 336 |
+
|
| 337 |
+
@property
|
| 338 |
+
def loop(self):
|
| 339 |
+
if self._pid != os.getpid():
|
| 340 |
+
raise RuntimeError("This class is not fork-safe")
|
| 341 |
+
return self._loop
|
| 342 |
+
|
| 343 |
+
async def _rm_file(self, path, **kwargs):
|
| 344 |
+
if (
|
| 345 |
+
inspect.iscoroutinefunction(self._rm)
|
| 346 |
+
and type(self)._rm is not AsyncFileSystem._rm
|
| 347 |
+
):
|
| 348 |
+
return await self._rm(path, recursive=False, batch_size=1, **kwargs)
|
| 349 |
+
raise NotImplementedError
|
| 350 |
+
|
| 351 |
+
async def _rm(self, path, recursive=False, batch_size=None, **kwargs):
|
| 352 |
+
# TODO: implement on_error
|
| 353 |
+
batch_size = batch_size or self.batch_size
|
| 354 |
+
path = await self._expand_path(path, recursive=recursive)
|
| 355 |
+
return await _run_coros_in_chunks(
|
| 356 |
+
[self._rm_file(p, **kwargs) for p in reversed(path)],
|
| 357 |
+
batch_size=batch_size,
|
| 358 |
+
nofiles=True,
|
| 359 |
+
)
|
| 360 |
+
|
| 361 |
+
async def _cp_file(self, path1, path2, **kwargs):
|
| 362 |
+
raise NotImplementedError
|
| 363 |
+
|
| 364 |
+
async def _mv_file(self, path1, path2):
|
| 365 |
+
await self._cp_file(path1, path2)
|
| 366 |
+
await self._rm_file(path1)
|
| 367 |
+
|
| 368 |
+
async def _copy(
|
| 369 |
+
self,
|
| 370 |
+
path1,
|
| 371 |
+
path2,
|
| 372 |
+
recursive=False,
|
| 373 |
+
on_error=None,
|
| 374 |
+
maxdepth=None,
|
| 375 |
+
batch_size=None,
|
| 376 |
+
**kwargs,
|
| 377 |
+
):
|
| 378 |
+
if on_error is None and recursive:
|
| 379 |
+
on_error = "ignore"
|
| 380 |
+
elif on_error is None:
|
| 381 |
+
on_error = "raise"
|
| 382 |
+
|
| 383 |
+
if isinstance(path1, list) and isinstance(path2, list):
|
| 384 |
+
# No need to expand paths when both source and destination
|
| 385 |
+
# are provided as lists
|
| 386 |
+
paths1 = path1
|
| 387 |
+
paths2 = path2
|
| 388 |
+
else:
|
| 389 |
+
source_is_str = isinstance(path1, str)
|
| 390 |
+
paths1 = await self._expand_path(
|
| 391 |
+
path1, maxdepth=maxdepth, recursive=recursive
|
| 392 |
+
)
|
| 393 |
+
if source_is_str and (not recursive or maxdepth is not None):
|
| 394 |
+
# Non-recursive glob does not copy directories
|
| 395 |
+
paths1 = [
|
| 396 |
+
p for p in paths1 if not (trailing_sep(p) or await self._isdir(p))
|
| 397 |
+
]
|
| 398 |
+
if not paths1:
|
| 399 |
+
return
|
| 400 |
+
|
| 401 |
+
source_is_file = len(paths1) == 1
|
| 402 |
+
dest_is_dir = isinstance(path2, str) and (
|
| 403 |
+
trailing_sep(path2) or await self._isdir(path2)
|
| 404 |
+
)
|
| 405 |
+
|
| 406 |
+
exists = source_is_str and (
|
| 407 |
+
(has_magic(path1) and source_is_file)
|
| 408 |
+
or (not has_magic(path1) and dest_is_dir and not trailing_sep(path1))
|
| 409 |
+
)
|
| 410 |
+
paths2 = other_paths(
|
| 411 |
+
paths1,
|
| 412 |
+
path2,
|
| 413 |
+
exists=exists,
|
| 414 |
+
flatten=not source_is_str,
|
| 415 |
+
)
|
| 416 |
+
|
| 417 |
+
batch_size = batch_size or self.batch_size
|
| 418 |
+
coros = [self._cp_file(p1, p2, **kwargs) for p1, p2 in zip(paths1, paths2)]
|
| 419 |
+
result = await _run_coros_in_chunks(
|
| 420 |
+
coros, batch_size=batch_size, return_exceptions=True, nofiles=True
|
| 421 |
+
)
|
| 422 |
+
|
| 423 |
+
for ex in filter(is_exception, result):
|
| 424 |
+
if on_error == "ignore" and isinstance(ex, FileNotFoundError):
|
| 425 |
+
continue
|
| 426 |
+
raise ex
|
| 427 |
+
|
| 428 |
+
async def _pipe_file(self, path, value, mode="overwrite", **kwargs):
|
| 429 |
+
raise NotImplementedError
|
| 430 |
+
|
| 431 |
+
async def _pipe(self, path, value=None, batch_size=None, **kwargs):
|
| 432 |
+
if isinstance(path, str):
|
| 433 |
+
path = {path: value}
|
| 434 |
+
batch_size = batch_size or self.batch_size
|
| 435 |
+
return await _run_coros_in_chunks(
|
| 436 |
+
[self._pipe_file(k, v, **kwargs) for k, v in path.items()],
|
| 437 |
+
batch_size=batch_size,
|
| 438 |
+
nofiles=True,
|
| 439 |
+
)
|
| 440 |
+
|
| 441 |
+
async def _process_limits(self, url, start, end):
|
| 442 |
+
"""Helper for "Range"-based _cat_file"""
|
| 443 |
+
size = None
|
| 444 |
+
suff = False
|
| 445 |
+
if start is not None and start < 0:
|
| 446 |
+
# if start is negative and end None, end is the "suffix length"
|
| 447 |
+
if end is None:
|
| 448 |
+
end = -start
|
| 449 |
+
start = ""
|
| 450 |
+
suff = True
|
| 451 |
+
else:
|
| 452 |
+
size = size or (await self._info(url))["size"]
|
| 453 |
+
start = size + start
|
| 454 |
+
elif start is None:
|
| 455 |
+
start = 0
|
| 456 |
+
if not suff:
|
| 457 |
+
if end is not None and end < 0:
|
| 458 |
+
if start is not None:
|
| 459 |
+
size = size or (await self._info(url))["size"]
|
| 460 |
+
end = size + end
|
| 461 |
+
elif end is None:
|
| 462 |
+
end = ""
|
| 463 |
+
if isinstance(end, numbers.Integral):
|
| 464 |
+
end -= 1 # bytes range is inclusive
|
| 465 |
+
return f"bytes={start}-{end}"
|
| 466 |
+
|
| 467 |
+
async def _cat_file(self, path, start=None, end=None, **kwargs):
|
| 468 |
+
raise NotImplementedError
|
| 469 |
+
|
| 470 |
+
async def _cat(
|
| 471 |
+
self, path, recursive=False, on_error="raise", batch_size=None, **kwargs
|
| 472 |
+
):
|
| 473 |
+
paths = await self._expand_path(path, recursive=recursive)
|
| 474 |
+
coros = [self._cat_file(path, **kwargs) for path in paths]
|
| 475 |
+
batch_size = batch_size or self.batch_size
|
| 476 |
+
out = await _run_coros_in_chunks(
|
| 477 |
+
coros, batch_size=batch_size, nofiles=True, return_exceptions=True
|
| 478 |
+
)
|
| 479 |
+
if on_error == "raise":
|
| 480 |
+
ex = next(filter(is_exception, out), False)
|
| 481 |
+
if ex:
|
| 482 |
+
raise ex
|
| 483 |
+
if (
|
| 484 |
+
len(paths) > 1
|
| 485 |
+
or isinstance(path, list)
|
| 486 |
+
or paths[0] != self._strip_protocol(path)
|
| 487 |
+
):
|
| 488 |
+
return {
|
| 489 |
+
k: v
|
| 490 |
+
for k, v in zip(paths, out)
|
| 491 |
+
if on_error != "omit" or not is_exception(v)
|
| 492 |
+
}
|
| 493 |
+
else:
|
| 494 |
+
return out[0]
|
| 495 |
+
|
| 496 |
+
async def _cat_ranges(
|
| 497 |
+
self,
|
| 498 |
+
paths,
|
| 499 |
+
starts,
|
| 500 |
+
ends,
|
| 501 |
+
max_gap=None,
|
| 502 |
+
batch_size=None,
|
| 503 |
+
on_error="return",
|
| 504 |
+
**kwargs,
|
| 505 |
+
):
|
| 506 |
+
"""Get the contents of byte ranges from one or more files
|
| 507 |
+
|
| 508 |
+
Parameters
|
| 509 |
+
----------
|
| 510 |
+
paths: list
|
| 511 |
+
A list of of filepaths on this filesystems
|
| 512 |
+
starts, ends: int or list
|
| 513 |
+
Bytes limits of the read. If using a single int, the same value will be
|
| 514 |
+
used to read all the specified files.
|
| 515 |
+
"""
|
| 516 |
+
# TODO: on_error
|
| 517 |
+
if max_gap is not None:
|
| 518 |
+
# use utils.merge_offset_ranges
|
| 519 |
+
raise NotImplementedError
|
| 520 |
+
if not isinstance(paths, list):
|
| 521 |
+
raise TypeError
|
| 522 |
+
if not isinstance(starts, Iterable):
|
| 523 |
+
starts = [starts] * len(paths)
|
| 524 |
+
if not isinstance(ends, Iterable):
|
| 525 |
+
ends = [ends] * len(paths)
|
| 526 |
+
if len(starts) != len(paths) or len(ends) != len(paths):
|
| 527 |
+
raise ValueError
|
| 528 |
+
coros = [
|
| 529 |
+
self._cat_file(p, start=s, end=e, **kwargs)
|
| 530 |
+
for p, s, e in zip(paths, starts, ends)
|
| 531 |
+
]
|
| 532 |
+
batch_size = batch_size or self.batch_size
|
| 533 |
+
return await _run_coros_in_chunks(
|
| 534 |
+
coros, batch_size=batch_size, nofiles=True, return_exceptions=True
|
| 535 |
+
)
|
| 536 |
+
|
| 537 |
+
async def _put_file(self, lpath, rpath, mode="overwrite", **kwargs):
|
| 538 |
+
raise NotImplementedError
|
| 539 |
+
|
| 540 |
+
async def _put(
|
| 541 |
+
self,
|
| 542 |
+
lpath,
|
| 543 |
+
rpath,
|
| 544 |
+
recursive=False,
|
| 545 |
+
callback=DEFAULT_CALLBACK,
|
| 546 |
+
batch_size=None,
|
| 547 |
+
maxdepth=None,
|
| 548 |
+
**kwargs,
|
| 549 |
+
):
|
| 550 |
+
"""Copy file(s) from local.
|
| 551 |
+
|
| 552 |
+
Copies a specific file or tree of files (if recursive=True). If rpath
|
| 553 |
+
ends with a "/", it will be assumed to be a directory, and target files
|
| 554 |
+
will go within.
|
| 555 |
+
|
| 556 |
+
The put_file method will be called concurrently on a batch of files. The
|
| 557 |
+
batch_size option can configure the amount of futures that can be executed
|
| 558 |
+
at the same time. If it is -1, then all the files will be uploaded concurrently.
|
| 559 |
+
The default can be set for this instance by passing "batch_size" in the
|
| 560 |
+
constructor, or for all instances by setting the "gather_batch_size" key
|
| 561 |
+
in ``fsspec.config.conf``, falling back to 1/8th of the system limit .
|
| 562 |
+
"""
|
| 563 |
+
if isinstance(lpath, list) and isinstance(rpath, list):
|
| 564 |
+
# No need to expand paths when both source and destination
|
| 565 |
+
# are provided as lists
|
| 566 |
+
rpaths = rpath
|
| 567 |
+
lpaths = lpath
|
| 568 |
+
else:
|
| 569 |
+
source_is_str = isinstance(lpath, str)
|
| 570 |
+
if source_is_str:
|
| 571 |
+
lpath = make_path_posix(lpath)
|
| 572 |
+
fs = LocalFileSystem()
|
| 573 |
+
lpaths = fs.expand_path(lpath, recursive=recursive, maxdepth=maxdepth)
|
| 574 |
+
if source_is_str and (not recursive or maxdepth is not None):
|
| 575 |
+
# Non-recursive glob does not copy directories
|
| 576 |
+
lpaths = [p for p in lpaths if not (trailing_sep(p) or fs.isdir(p))]
|
| 577 |
+
if not lpaths:
|
| 578 |
+
return
|
| 579 |
+
|
| 580 |
+
source_is_file = len(lpaths) == 1
|
| 581 |
+
dest_is_dir = isinstance(rpath, str) and (
|
| 582 |
+
trailing_sep(rpath) or await self._isdir(rpath)
|
| 583 |
+
)
|
| 584 |
+
|
| 585 |
+
rpath = self._strip_protocol(rpath)
|
| 586 |
+
exists = source_is_str and (
|
| 587 |
+
(has_magic(lpath) and source_is_file)
|
| 588 |
+
or (not has_magic(lpath) and dest_is_dir and not trailing_sep(lpath))
|
| 589 |
+
)
|
| 590 |
+
rpaths = other_paths(
|
| 591 |
+
lpaths,
|
| 592 |
+
rpath,
|
| 593 |
+
exists=exists,
|
| 594 |
+
flatten=not source_is_str,
|
| 595 |
+
)
|
| 596 |
+
|
| 597 |
+
is_dir = {l: os.path.isdir(l) for l in lpaths}
|
| 598 |
+
rdirs = [r for l, r in zip(lpaths, rpaths) if is_dir[l]]
|
| 599 |
+
file_pairs = [(l, r) for l, r in zip(lpaths, rpaths) if not is_dir[l]]
|
| 600 |
+
|
| 601 |
+
await asyncio.gather(*[self._makedirs(d, exist_ok=True) for d in rdirs])
|
| 602 |
+
batch_size = batch_size or self.batch_size
|
| 603 |
+
|
| 604 |
+
coros = []
|
| 605 |
+
callback.set_size(len(file_pairs))
|
| 606 |
+
for lfile, rfile in file_pairs:
|
| 607 |
+
put_file = callback.branch_coro(self._put_file)
|
| 608 |
+
coros.append(put_file(lfile, rfile, **kwargs))
|
| 609 |
+
|
| 610 |
+
return await _run_coros_in_chunks(
|
| 611 |
+
coros, batch_size=batch_size, callback=callback
|
| 612 |
+
)
|
| 613 |
+
|
| 614 |
+
async def _get_file(self, rpath, lpath, **kwargs):
|
| 615 |
+
raise NotImplementedError
|
| 616 |
+
|
| 617 |
+
async def _get(
|
| 618 |
+
self,
|
| 619 |
+
rpath,
|
| 620 |
+
lpath,
|
| 621 |
+
recursive=False,
|
| 622 |
+
callback=DEFAULT_CALLBACK,
|
| 623 |
+
maxdepth=None,
|
| 624 |
+
**kwargs,
|
| 625 |
+
):
|
| 626 |
+
"""Copy file(s) to local.
|
| 627 |
+
|
| 628 |
+
Copies a specific file or tree of files (if recursive=True). If lpath
|
| 629 |
+
ends with a "/", it will be assumed to be a directory, and target files
|
| 630 |
+
will go within. Can submit a list of paths, which may be glob-patterns
|
| 631 |
+
and will be expanded.
|
| 632 |
+
|
| 633 |
+
The get_file method will be called concurrently on a batch of files. The
|
| 634 |
+
batch_size option can configure the amount of futures that can be executed
|
| 635 |
+
at the same time. If it is -1, then all the files will be uploaded concurrently.
|
| 636 |
+
The default can be set for this instance by passing "batch_size" in the
|
| 637 |
+
constructor, or for all instances by setting the "gather_batch_size" key
|
| 638 |
+
in ``fsspec.config.conf``, falling back to 1/8th of the system limit .
|
| 639 |
+
"""
|
| 640 |
+
if isinstance(lpath, list) and isinstance(rpath, list):
|
| 641 |
+
# No need to expand paths when both source and destination
|
| 642 |
+
# are provided as lists
|
| 643 |
+
rpaths = rpath
|
| 644 |
+
lpaths = lpath
|
| 645 |
+
else:
|
| 646 |
+
source_is_str = isinstance(rpath, str)
|
| 647 |
+
# First check for rpath trailing slash as _strip_protocol removes it.
|
| 648 |
+
source_not_trailing_sep = source_is_str and not trailing_sep(rpath)
|
| 649 |
+
rpath = self._strip_protocol(rpath)
|
| 650 |
+
rpaths = await self._expand_path(
|
| 651 |
+
rpath, recursive=recursive, maxdepth=maxdepth
|
| 652 |
+
)
|
| 653 |
+
if source_is_str and (not recursive or maxdepth is not None):
|
| 654 |
+
# Non-recursive glob does not copy directories
|
| 655 |
+
rpaths = [
|
| 656 |
+
p for p in rpaths if not (trailing_sep(p) or await self._isdir(p))
|
| 657 |
+
]
|
| 658 |
+
if not rpaths:
|
| 659 |
+
return
|
| 660 |
+
|
| 661 |
+
lpath = make_path_posix(lpath)
|
| 662 |
+
source_is_file = len(rpaths) == 1
|
| 663 |
+
dest_is_dir = isinstance(lpath, str) and (
|
| 664 |
+
trailing_sep(lpath) or LocalFileSystem().isdir(lpath)
|
| 665 |
+
)
|
| 666 |
+
|
| 667 |
+
exists = source_is_str and (
|
| 668 |
+
(has_magic(rpath) and source_is_file)
|
| 669 |
+
or (not has_magic(rpath) and dest_is_dir and source_not_trailing_sep)
|
| 670 |
+
)
|
| 671 |
+
lpaths = other_paths(
|
| 672 |
+
rpaths,
|
| 673 |
+
lpath,
|
| 674 |
+
exists=exists,
|
| 675 |
+
flatten=not source_is_str,
|
| 676 |
+
)
|
| 677 |
+
|
| 678 |
+
[os.makedirs(os.path.dirname(lp), exist_ok=True) for lp in lpaths]
|
| 679 |
+
batch_size = kwargs.pop("batch_size", self.batch_size)
|
| 680 |
+
|
| 681 |
+
coros = []
|
| 682 |
+
callback.set_size(len(lpaths))
|
| 683 |
+
for lpath, rpath in zip(lpaths, rpaths):
|
| 684 |
+
get_file = callback.branch_coro(self._get_file)
|
| 685 |
+
coros.append(get_file(rpath, lpath, **kwargs))
|
| 686 |
+
return await _run_coros_in_chunks(
|
| 687 |
+
coros, batch_size=batch_size, callback=callback
|
| 688 |
+
)
|
| 689 |
+
|
| 690 |
+
async def _isfile(self, path):
|
| 691 |
+
try:
|
| 692 |
+
return (await self._info(path))["type"] == "file"
|
| 693 |
+
except: # noqa: E722
|
| 694 |
+
return False
|
| 695 |
+
|
| 696 |
+
async def _isdir(self, path):
|
| 697 |
+
try:
|
| 698 |
+
return (await self._info(path))["type"] == "directory"
|
| 699 |
+
except OSError:
|
| 700 |
+
return False
|
| 701 |
+
|
| 702 |
+
async def _size(self, path):
|
| 703 |
+
return (await self._info(path)).get("size", None)
|
| 704 |
+
|
| 705 |
+
async def _sizes(self, paths, batch_size=None):
|
| 706 |
+
batch_size = batch_size or self.batch_size
|
| 707 |
+
return await _run_coros_in_chunks(
|
| 708 |
+
[self._size(p) for p in paths], batch_size=batch_size
|
| 709 |
+
)
|
| 710 |
+
|
| 711 |
+
async def _exists(self, path, **kwargs):
|
| 712 |
+
try:
|
| 713 |
+
await self._info(path, **kwargs)
|
| 714 |
+
return True
|
| 715 |
+
except FileNotFoundError:
|
| 716 |
+
return False
|
| 717 |
+
|
| 718 |
+
async def _info(self, path, **kwargs):
|
| 719 |
+
raise NotImplementedError
|
| 720 |
+
|
| 721 |
+
async def _ls(self, path, detail=True, **kwargs):
|
| 722 |
+
raise NotImplementedError
|
| 723 |
+
|
| 724 |
+
async def _walk(self, path, maxdepth=None, on_error="omit", **kwargs):
|
| 725 |
+
if maxdepth is not None and maxdepth < 1:
|
| 726 |
+
raise ValueError("maxdepth must be at least 1")
|
| 727 |
+
|
| 728 |
+
path = self._strip_protocol(path)
|
| 729 |
+
full_dirs = {}
|
| 730 |
+
dirs = {}
|
| 731 |
+
files = {}
|
| 732 |
+
|
| 733 |
+
detail = kwargs.pop("detail", False)
|
| 734 |
+
try:
|
| 735 |
+
listing = await self._ls(path, detail=True, **kwargs)
|
| 736 |
+
except (FileNotFoundError, OSError) as e:
|
| 737 |
+
if on_error == "raise":
|
| 738 |
+
raise
|
| 739 |
+
elif callable(on_error):
|
| 740 |
+
on_error(e)
|
| 741 |
+
if detail:
|
| 742 |
+
yield path, {}, {}
|
| 743 |
+
else:
|
| 744 |
+
yield path, [], []
|
| 745 |
+
return
|
| 746 |
+
|
| 747 |
+
for info in listing:
|
| 748 |
+
# each info name must be at least [path]/part , but here
|
| 749 |
+
# we check also for names like [path]/part/
|
| 750 |
+
pathname = info["name"].rstrip("/")
|
| 751 |
+
name = pathname.rsplit("/", 1)[-1]
|
| 752 |
+
if info["type"] == "directory" and pathname != path:
|
| 753 |
+
# do not include "self" path
|
| 754 |
+
full_dirs[name] = pathname
|
| 755 |
+
dirs[name] = info
|
| 756 |
+
elif pathname == path:
|
| 757 |
+
# file-like with same name as give path
|
| 758 |
+
files[""] = info
|
| 759 |
+
else:
|
| 760 |
+
files[name] = info
|
| 761 |
+
|
| 762 |
+
if detail:
|
| 763 |
+
yield path, dirs, files
|
| 764 |
+
else:
|
| 765 |
+
yield path, list(dirs), list(files)
|
| 766 |
+
|
| 767 |
+
if maxdepth is not None:
|
| 768 |
+
maxdepth -= 1
|
| 769 |
+
if maxdepth < 1:
|
| 770 |
+
return
|
| 771 |
+
|
| 772 |
+
for d in dirs:
|
| 773 |
+
async for _ in self._walk(
|
| 774 |
+
full_dirs[d], maxdepth=maxdepth, detail=detail, **kwargs
|
| 775 |
+
):
|
| 776 |
+
yield _
|
| 777 |
+
|
| 778 |
+
async def _glob(self, path, maxdepth=None, **kwargs):
|
| 779 |
+
if maxdepth is not None and maxdepth < 1:
|
| 780 |
+
raise ValueError("maxdepth must be at least 1")
|
| 781 |
+
|
| 782 |
+
import re
|
| 783 |
+
|
| 784 |
+
seps = (os.path.sep, os.path.altsep) if os.path.altsep else (os.path.sep,)
|
| 785 |
+
ends_with_sep = path.endswith(seps) # _strip_protocol strips trailing slash
|
| 786 |
+
path = self._strip_protocol(path)
|
| 787 |
+
append_slash_to_dirname = ends_with_sep or path.endswith(
|
| 788 |
+
tuple(sep + "**" for sep in seps)
|
| 789 |
+
)
|
| 790 |
+
idx_star = path.find("*") if path.find("*") >= 0 else len(path)
|
| 791 |
+
idx_qmark = path.find("?") if path.find("?") >= 0 else len(path)
|
| 792 |
+
idx_brace = path.find("[") if path.find("[") >= 0 else len(path)
|
| 793 |
+
|
| 794 |
+
min_idx = min(idx_star, idx_qmark, idx_brace)
|
| 795 |
+
|
| 796 |
+
detail = kwargs.pop("detail", False)
|
| 797 |
+
withdirs = kwargs.pop("withdirs", True)
|
| 798 |
+
|
| 799 |
+
if not has_magic(path):
|
| 800 |
+
if await self._exists(path, **kwargs):
|
| 801 |
+
if not detail:
|
| 802 |
+
return [path]
|
| 803 |
+
else:
|
| 804 |
+
return {path: await self._info(path, **kwargs)}
|
| 805 |
+
else:
|
| 806 |
+
if not detail:
|
| 807 |
+
return [] # glob of non-existent returns empty
|
| 808 |
+
else:
|
| 809 |
+
return {}
|
| 810 |
+
elif "/" in path[:min_idx]:
|
| 811 |
+
first_wildcard_idx = min_idx
|
| 812 |
+
min_idx = path[:min_idx].rindex("/")
|
| 813 |
+
root = path[
|
| 814 |
+
: min_idx + 1
|
| 815 |
+
] # everything up to the last / before the first wildcard
|
| 816 |
+
prefix = path[
|
| 817 |
+
min_idx + 1 : first_wildcard_idx
|
| 818 |
+
] # stem between last "/" and first wildcard
|
| 819 |
+
depth = path[min_idx + 1 :].count("/") + 1
|
| 820 |
+
else:
|
| 821 |
+
root = ""
|
| 822 |
+
prefix = path[:min_idx] # stem up to the first wildcard
|
| 823 |
+
depth = path[min_idx + 1 :].count("/") + 1
|
| 824 |
+
|
| 825 |
+
if "**" in path:
|
| 826 |
+
if maxdepth is not None:
|
| 827 |
+
idx_double_stars = path.find("**")
|
| 828 |
+
depth_double_stars = path[idx_double_stars:].count("/") + 1
|
| 829 |
+
depth = depth - depth_double_stars + maxdepth
|
| 830 |
+
else:
|
| 831 |
+
depth = None
|
| 832 |
+
|
| 833 |
+
# Pass the filename stem as prefix= so backends that support it such as
|
| 834 |
+
# gcsfs, s3fs and adlfs can filter server-side up to the first wildcard.
|
| 835 |
+
if prefix:
|
| 836 |
+
kwargs["prefix"] = prefix
|
| 837 |
+
allpaths = await self._find(
|
| 838 |
+
root, maxdepth=depth, withdirs=withdirs, detail=True, **kwargs
|
| 839 |
+
)
|
| 840 |
+
|
| 841 |
+
pattern = glob_translate(path + ("/" if ends_with_sep else ""))
|
| 842 |
+
pattern = re.compile(pattern)
|
| 843 |
+
|
| 844 |
+
out = {
|
| 845 |
+
p: info
|
| 846 |
+
for p, info in sorted(allpaths.items())
|
| 847 |
+
if pattern.match(
|
| 848 |
+
p + "/"
|
| 849 |
+
if append_slash_to_dirname and info["type"] == "directory"
|
| 850 |
+
else p
|
| 851 |
+
)
|
| 852 |
+
}
|
| 853 |
+
|
| 854 |
+
if detail:
|
| 855 |
+
return out
|
| 856 |
+
else:
|
| 857 |
+
return list(out)
|
| 858 |
+
|
| 859 |
+
async def _du(self, path, total=True, maxdepth=None, **kwargs):
|
| 860 |
+
sizes = {}
|
| 861 |
+
# async for?
|
| 862 |
+
for f in await self._find(path, maxdepth=maxdepth, **kwargs):
|
| 863 |
+
info = await self._info(f)
|
| 864 |
+
sizes[info["name"]] = info["size"]
|
| 865 |
+
if total:
|
| 866 |
+
return sum(sizes.values())
|
| 867 |
+
else:
|
| 868 |
+
return sizes
|
| 869 |
+
|
| 870 |
+
async def _find(self, path, maxdepth=None, withdirs=False, **kwargs):
|
| 871 |
+
path = self._strip_protocol(path)
|
| 872 |
+
out = {}
|
| 873 |
+
detail = kwargs.pop("detail", False)
|
| 874 |
+
|
| 875 |
+
# Add the root directory if withdirs is requested
|
| 876 |
+
# This is needed for posix glob compliance
|
| 877 |
+
if withdirs and path != "" and await self._isdir(path):
|
| 878 |
+
out[path] = await self._info(path)
|
| 879 |
+
|
| 880 |
+
# async for?
|
| 881 |
+
async for _, dirs, files in self._walk(path, maxdepth, detail=True, **kwargs):
|
| 882 |
+
if withdirs:
|
| 883 |
+
files.update(dirs)
|
| 884 |
+
out.update({info["name"]: info for name, info in files.items()})
|
| 885 |
+
if not out and (await self._isfile(path)):
|
| 886 |
+
# walk works on directories, but find should also return [path]
|
| 887 |
+
# when path happens to be a file
|
| 888 |
+
out[path] = {}
|
| 889 |
+
names = sorted(out)
|
| 890 |
+
if not detail:
|
| 891 |
+
return names
|
| 892 |
+
else:
|
| 893 |
+
return {name: out[name] for name in names}
|
| 894 |
+
|
| 895 |
+
async def _expand_path(self, path, recursive=False, maxdepth=None):
|
| 896 |
+
if maxdepth is not None and maxdepth < 1:
|
| 897 |
+
raise ValueError("maxdepth must be at least 1")
|
| 898 |
+
|
| 899 |
+
if isinstance(path, str):
|
| 900 |
+
out = await self._expand_path([path], recursive, maxdepth)
|
| 901 |
+
else:
|
| 902 |
+
out = set()
|
| 903 |
+
path = [self._strip_protocol(p) for p in path]
|
| 904 |
+
for p in path: # can gather here
|
| 905 |
+
if has_magic(p):
|
| 906 |
+
bit = set(await self._glob(p, maxdepth=maxdepth))
|
| 907 |
+
out |= bit
|
| 908 |
+
if recursive:
|
| 909 |
+
# glob call above expanded one depth so if maxdepth is defined
|
| 910 |
+
# then decrement it in expand_path call below. If it is zero
|
| 911 |
+
# after decrementing then avoid expand_path call.
|
| 912 |
+
if maxdepth is not None and maxdepth <= 1:
|
| 913 |
+
continue
|
| 914 |
+
out |= set(
|
| 915 |
+
await self._expand_path(
|
| 916 |
+
list(bit),
|
| 917 |
+
recursive=recursive,
|
| 918 |
+
maxdepth=maxdepth - 1 if maxdepth is not None else None,
|
| 919 |
+
)
|
| 920 |
+
)
|
| 921 |
+
continue
|
| 922 |
+
elif recursive:
|
| 923 |
+
rec = set(await self._find(p, maxdepth=maxdepth, withdirs=True))
|
| 924 |
+
out |= rec
|
| 925 |
+
if p not in out and (recursive is False or (await self._exists(p))):
|
| 926 |
+
# should only check once, for the root
|
| 927 |
+
out.add(p)
|
| 928 |
+
if not out:
|
| 929 |
+
raise FileNotFoundError(path)
|
| 930 |
+
return sorted(out)
|
| 931 |
+
|
| 932 |
+
async def _mkdir(self, path, create_parents=True, **kwargs):
|
| 933 |
+
pass # not necessary to implement, may not have directories
|
| 934 |
+
|
| 935 |
+
async def _makedirs(self, path, exist_ok=False):
|
| 936 |
+
pass # not necessary to implement, may not have directories
|
| 937 |
+
|
| 938 |
+
async def open_async(self, path, mode="rb", **kwargs):
|
| 939 |
+
if "b" not in mode or kwargs.get("compression"):
|
| 940 |
+
raise ValueError
|
| 941 |
+
raise NotImplementedError
|
| 942 |
+
|
| 943 |
+
|
| 944 |
+
def mirror_sync_methods(obj):
|
| 945 |
+
"""Populate sync and async methods for obj
|
| 946 |
+
|
| 947 |
+
For each method will create a sync version if the name refers to an async method
|
| 948 |
+
(coroutine) and there is no override in the child class; will create an async
|
| 949 |
+
method for the corresponding sync method if there is no implementation.
|
| 950 |
+
|
| 951 |
+
Uses the methods specified in
|
| 952 |
+
- async_methods: the set that an implementation is expected to provide
|
| 953 |
+
- default_async_methods: that can be derived from their sync version in
|
| 954 |
+
AbstractFileSystem
|
| 955 |
+
- AsyncFileSystem: async-specific default coroutines
|
| 956 |
+
"""
|
| 957 |
+
from fsspec import AbstractFileSystem
|
| 958 |
+
|
| 959 |
+
for method in async_methods + dir(AsyncFileSystem):
|
| 960 |
+
if not method.startswith("_"):
|
| 961 |
+
continue
|
| 962 |
+
smethod = method[1:]
|
| 963 |
+
if private.match(method):
|
| 964 |
+
isco = inspect.iscoroutinefunction(getattr(obj, method, None))
|
| 965 |
+
unsync = getattr(getattr(obj, smethod, False), "__func__", None)
|
| 966 |
+
is_default = unsync is getattr(AbstractFileSystem, smethod, "")
|
| 967 |
+
if isco and is_default:
|
| 968 |
+
mth = sync_wrapper(getattr(obj, method), obj=obj)
|
| 969 |
+
setattr(obj, smethod, mth)
|
| 970 |
+
if not mth.__doc__:
|
| 971 |
+
mth.__doc__ = getattr(
|
| 972 |
+
getattr(AbstractFileSystem, smethod, None), "__doc__", ""
|
| 973 |
+
)
|
| 974 |
+
|
| 975 |
+
|
| 976 |
+
class FSSpecCoroutineCancel(Exception):
|
| 977 |
+
pass
|
| 978 |
+
|
| 979 |
+
|
| 980 |
+
def _dump_running_tasks(
|
| 981 |
+
printout=True, cancel=True, exc=FSSpecCoroutineCancel, with_task=False
|
| 982 |
+
):
|
| 983 |
+
import traceback
|
| 984 |
+
|
| 985 |
+
tasks = [t for t in asyncio.tasks.all_tasks(loop[0]) if not t.done()]
|
| 986 |
+
if printout:
|
| 987 |
+
[task.print_stack() for task in tasks]
|
| 988 |
+
out = [
|
| 989 |
+
{
|
| 990 |
+
"locals": task._coro.cr_frame.f_locals,
|
| 991 |
+
"file": task._coro.cr_frame.f_code.co_filename,
|
| 992 |
+
"firstline": task._coro.cr_frame.f_code.co_firstlineno,
|
| 993 |
+
"linelo": task._coro.cr_frame.f_lineno,
|
| 994 |
+
"stack": traceback.format_stack(task._coro.cr_frame),
|
| 995 |
+
"task": task if with_task else None,
|
| 996 |
+
}
|
| 997 |
+
for task in tasks
|
| 998 |
+
]
|
| 999 |
+
if cancel:
|
| 1000 |
+
for t in tasks:
|
| 1001 |
+
cbs = t._callbacks
|
| 1002 |
+
t.cancel()
|
| 1003 |
+
asyncio.futures.Future.set_exception(t, exc)
|
| 1004 |
+
asyncio.futures.Future.cancel(t)
|
| 1005 |
+
[cb[0](t) for cb in cbs] # cancels any dependent concurrent.futures
|
| 1006 |
+
try:
|
| 1007 |
+
t._coro.throw(exc) # exits coro, unless explicitly handled
|
| 1008 |
+
except exc:
|
| 1009 |
+
pass
|
| 1010 |
+
return out
|
| 1011 |
+
|
| 1012 |
+
|
| 1013 |
+
class AbstractAsyncStreamedFile(AbstractBufferedFile):
|
| 1014 |
+
# no read buffering, and always auto-commit
|
| 1015 |
+
# TODO: readahead might still be useful here, but needs async version
|
| 1016 |
+
|
| 1017 |
+
async def read(self, length=-1):
|
| 1018 |
+
"""
|
| 1019 |
+
Return data from cache, or fetch pieces as necessary
|
| 1020 |
+
|
| 1021 |
+
Parameters
|
| 1022 |
+
----------
|
| 1023 |
+
length: int (-1)
|
| 1024 |
+
Number of bytes to read; if <0, all remaining bytes.
|
| 1025 |
+
"""
|
| 1026 |
+
length = -1 if length is None else int(length)
|
| 1027 |
+
if self.mode != "rb":
|
| 1028 |
+
raise ValueError("File not in read mode")
|
| 1029 |
+
if length < 0:
|
| 1030 |
+
length = self.size - self.loc
|
| 1031 |
+
if self.closed:
|
| 1032 |
+
raise ValueError("I/O operation on closed file.")
|
| 1033 |
+
if length == 0:
|
| 1034 |
+
# don't even bother calling fetch
|
| 1035 |
+
return b""
|
| 1036 |
+
out = await self._fetch_range(self.loc, self.loc + length)
|
| 1037 |
+
self.loc += len(out)
|
| 1038 |
+
return out
|
| 1039 |
+
|
| 1040 |
+
async def write(self, data):
|
| 1041 |
+
"""
|
| 1042 |
+
Write data to buffer.
|
| 1043 |
+
|
| 1044 |
+
Buffer only sent on flush() or if buffer is greater than
|
| 1045 |
+
or equal to blocksize.
|
| 1046 |
+
|
| 1047 |
+
Parameters
|
| 1048 |
+
----------
|
| 1049 |
+
data: bytes
|
| 1050 |
+
Set of bytes to be written.
|
| 1051 |
+
"""
|
| 1052 |
+
if self.mode not in {"wb", "ab"}:
|
| 1053 |
+
raise ValueError("File not in write mode")
|
| 1054 |
+
if self.closed:
|
| 1055 |
+
raise ValueError("I/O operation on closed file.")
|
| 1056 |
+
if self.forced:
|
| 1057 |
+
raise ValueError("This file has been force-flushed, can only close")
|
| 1058 |
+
out = self.buffer.write(data)
|
| 1059 |
+
self.loc += out
|
| 1060 |
+
if self.buffer.tell() >= self.blocksize:
|
| 1061 |
+
await self.flush()
|
| 1062 |
+
return out
|
| 1063 |
+
|
| 1064 |
+
async def close(self):
|
| 1065 |
+
"""Close file
|
| 1066 |
+
|
| 1067 |
+
Finalizes writes, discards cache
|
| 1068 |
+
"""
|
| 1069 |
+
if getattr(self, "_unclosable", False):
|
| 1070 |
+
return
|
| 1071 |
+
if self.closed:
|
| 1072 |
+
return
|
| 1073 |
+
if self.mode == "rb":
|
| 1074 |
+
self.cache = None
|
| 1075 |
+
else:
|
| 1076 |
+
if not self.forced:
|
| 1077 |
+
await self.flush(force=True)
|
| 1078 |
+
|
| 1079 |
+
if self.fs is not None:
|
| 1080 |
+
self.fs.invalidate_cache(self.path)
|
| 1081 |
+
self.fs.invalidate_cache(self.fs._parent(self.path))
|
| 1082 |
+
|
| 1083 |
+
self.closed = True
|
| 1084 |
+
|
| 1085 |
+
async def flush(self, force=False):
|
| 1086 |
+
if self.closed:
|
| 1087 |
+
raise ValueError("Flush on closed file")
|
| 1088 |
+
if force and self.forced:
|
| 1089 |
+
raise ValueError("Force flush cannot be called more than once")
|
| 1090 |
+
if force:
|
| 1091 |
+
self.forced = True
|
| 1092 |
+
|
| 1093 |
+
if self.mode not in {"wb", "ab"}:
|
| 1094 |
+
# no-op to flush on read-mode
|
| 1095 |
+
return
|
| 1096 |
+
|
| 1097 |
+
if not force and self.buffer.tell() < self.blocksize:
|
| 1098 |
+
# Defer write on small block
|
| 1099 |
+
return
|
| 1100 |
+
|
| 1101 |
+
if self.offset is None:
|
| 1102 |
+
# Initialize a multipart upload
|
| 1103 |
+
self.offset = 0
|
| 1104 |
+
try:
|
| 1105 |
+
await self._initiate_upload()
|
| 1106 |
+
except:
|
| 1107 |
+
self.closed = True
|
| 1108 |
+
raise
|
| 1109 |
+
|
| 1110 |
+
if await self._upload_chunk(final=force) is not False:
|
| 1111 |
+
self.offset += self.buffer.seek(0, 2)
|
| 1112 |
+
self.buffer = io.BytesIO()
|
| 1113 |
+
|
| 1114 |
+
async def __aenter__(self):
|
| 1115 |
+
return self
|
| 1116 |
+
|
| 1117 |
+
async def __aexit__(self, exc_type, exc_val, exc_tb):
|
| 1118 |
+
await self.close()
|
| 1119 |
+
|
| 1120 |
+
async def _fetch_range(self, start, end):
|
| 1121 |
+
raise NotImplementedError
|
| 1122 |
+
|
| 1123 |
+
async def _initiate_upload(self):
|
| 1124 |
+
pass
|
| 1125 |
+
|
| 1126 |
+
async def _upload_chunk(self, final=False):
|
| 1127 |
+
raise NotImplementedError
|
micromamba_root/envs/hf_sync/Lib/site-packages/fsspec/caching.py
ADDED
|
@@ -0,0 +1,1004 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 |
+
end = min(end, self.size)
|
| 308 |
+
|
| 309 |
+
if start < self.blocksize:
|
| 310 |
+
if self.cache is None:
|
| 311 |
+
self.miss_count += 1
|
| 312 |
+
if end > self.blocksize:
|
| 313 |
+
self.total_requested_bytes += end
|
| 314 |
+
data = self.fetcher(0, end)
|
| 315 |
+
self.cache = data[: self.blocksize]
|
| 316 |
+
return data[start:]
|
| 317 |
+
self.cache = self.fetcher(0, self.blocksize)
|
| 318 |
+
self.total_requested_bytes += self.blocksize
|
| 319 |
+
part = self.cache[start:end]
|
| 320 |
+
if end > self.blocksize:
|
| 321 |
+
self.total_requested_bytes += end - self.blocksize
|
| 322 |
+
part += self.fetcher(self.blocksize, end)
|
| 323 |
+
self.hit_count += 1
|
| 324 |
+
return part
|
| 325 |
+
else:
|
| 326 |
+
self.miss_count += 1
|
| 327 |
+
self.total_requested_bytes += end - start
|
| 328 |
+
return self.fetcher(start, end)
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
class BlockCache(BaseCache):
|
| 332 |
+
"""
|
| 333 |
+
Cache holding memory as a set of blocks.
|
| 334 |
+
|
| 335 |
+
Requests are only ever made ``blocksize`` at a time, and are
|
| 336 |
+
stored in an LRU cache. The least recently accessed block is
|
| 337 |
+
discarded when more than ``maxblocks`` are stored.
|
| 338 |
+
|
| 339 |
+
Parameters
|
| 340 |
+
----------
|
| 341 |
+
blocksize : int
|
| 342 |
+
The number of bytes to store in each block.
|
| 343 |
+
Requests are only ever made for ``blocksize``, so this
|
| 344 |
+
should balance the overhead of making a request against
|
| 345 |
+
the granularity of the blocks.
|
| 346 |
+
fetcher : Callable
|
| 347 |
+
size : int
|
| 348 |
+
The total size of the file being cached.
|
| 349 |
+
maxblocks : int
|
| 350 |
+
The maximum number of blocks to cache for. The maximum memory
|
| 351 |
+
use for this cache is then ``blocksize * maxblocks``.
|
| 352 |
+
"""
|
| 353 |
+
|
| 354 |
+
name = "blockcache"
|
| 355 |
+
|
| 356 |
+
def __init__(
|
| 357 |
+
self, blocksize: int, fetcher: Fetcher, size: int, maxblocks: int = 32
|
| 358 |
+
) -> None:
|
| 359 |
+
super().__init__(blocksize, fetcher, size)
|
| 360 |
+
self.nblocks = math.ceil(size / blocksize)
|
| 361 |
+
self.maxblocks = maxblocks
|
| 362 |
+
self._fetch_block_cached = functools.lru_cache(maxblocks)(self._fetch_block)
|
| 363 |
+
|
| 364 |
+
def cache_info(self):
|
| 365 |
+
"""
|
| 366 |
+
The statistics on the block cache.
|
| 367 |
+
|
| 368 |
+
Returns
|
| 369 |
+
-------
|
| 370 |
+
NamedTuple
|
| 371 |
+
Returned directly from the LRU Cache used internally.
|
| 372 |
+
"""
|
| 373 |
+
return self._fetch_block_cached.cache_info()
|
| 374 |
+
|
| 375 |
+
def __getstate__(self) -> dict[str, Any]:
|
| 376 |
+
state = self.__dict__
|
| 377 |
+
del state["_fetch_block_cached"]
|
| 378 |
+
return state
|
| 379 |
+
|
| 380 |
+
def __setstate__(self, state: dict[str, Any]) -> None:
|
| 381 |
+
self.__dict__.update(state)
|
| 382 |
+
self._fetch_block_cached = functools.lru_cache(state["maxblocks"])(
|
| 383 |
+
self._fetch_block
|
| 384 |
+
)
|
| 385 |
+
|
| 386 |
+
def _fetch(self, start: int | None, end: int | None) -> bytes:
|
| 387 |
+
if start is None:
|
| 388 |
+
start = 0
|
| 389 |
+
if end is None:
|
| 390 |
+
end = self.size
|
| 391 |
+
if start >= self.size or start >= end:
|
| 392 |
+
return b""
|
| 393 |
+
|
| 394 |
+
return self._read_cache(
|
| 395 |
+
start, end, start // self.blocksize, (end - 1) // self.blocksize
|
| 396 |
+
)
|
| 397 |
+
|
| 398 |
+
def _fetch_block(self, block_number: int) -> bytes:
|
| 399 |
+
"""
|
| 400 |
+
Fetch the block of data for `block_number`.
|
| 401 |
+
"""
|
| 402 |
+
if block_number > self.nblocks:
|
| 403 |
+
raise ValueError(
|
| 404 |
+
f"'block_number={block_number}' is greater than "
|
| 405 |
+
f"the number of blocks ({self.nblocks})"
|
| 406 |
+
)
|
| 407 |
+
|
| 408 |
+
start = block_number * self.blocksize
|
| 409 |
+
end = start + self.blocksize
|
| 410 |
+
self.total_requested_bytes += end - start
|
| 411 |
+
self.miss_count += 1
|
| 412 |
+
logger.info("BlockCache fetching block %d", block_number)
|
| 413 |
+
block_contents = super()._fetch(start, end)
|
| 414 |
+
return block_contents
|
| 415 |
+
|
| 416 |
+
def _read_cache(
|
| 417 |
+
self, start: int, end: int, start_block_number: int, end_block_number: int
|
| 418 |
+
) -> bytes:
|
| 419 |
+
"""
|
| 420 |
+
Read from our block cache.
|
| 421 |
+
|
| 422 |
+
Parameters
|
| 423 |
+
----------
|
| 424 |
+
start, end : int
|
| 425 |
+
The start and end byte positions.
|
| 426 |
+
start_block_number, end_block_number : int
|
| 427 |
+
The start and end block numbers.
|
| 428 |
+
"""
|
| 429 |
+
start_pos = start % self.blocksize
|
| 430 |
+
end_pos = end % self.blocksize
|
| 431 |
+
if end_pos == 0:
|
| 432 |
+
end_pos = self.blocksize
|
| 433 |
+
|
| 434 |
+
self.hit_count += 1
|
| 435 |
+
if start_block_number == end_block_number:
|
| 436 |
+
block: bytes = self._fetch_block_cached(start_block_number)
|
| 437 |
+
return block[start_pos:end_pos]
|
| 438 |
+
|
| 439 |
+
else:
|
| 440 |
+
# read from the initial
|
| 441 |
+
out = [self._fetch_block_cached(start_block_number)[start_pos:]]
|
| 442 |
+
|
| 443 |
+
# intermediate blocks
|
| 444 |
+
# Note: it'd be nice to combine these into one big request. However
|
| 445 |
+
# that doesn't play nicely with our LRU cache.
|
| 446 |
+
out.extend(
|
| 447 |
+
map(
|
| 448 |
+
self._fetch_block_cached,
|
| 449 |
+
range(start_block_number + 1, end_block_number),
|
| 450 |
+
)
|
| 451 |
+
)
|
| 452 |
+
|
| 453 |
+
# final block
|
| 454 |
+
out.append(self._fetch_block_cached(end_block_number)[:end_pos])
|
| 455 |
+
|
| 456 |
+
return b"".join(out)
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
class BytesCache(BaseCache):
|
| 460 |
+
"""Cache which holds data in a in-memory bytes object
|
| 461 |
+
|
| 462 |
+
Implements read-ahead by the block size, for semi-random reads progressing
|
| 463 |
+
through the file.
|
| 464 |
+
|
| 465 |
+
Parameters
|
| 466 |
+
----------
|
| 467 |
+
trim: bool
|
| 468 |
+
As we read more data, whether to discard the start of the buffer when
|
| 469 |
+
we are more than a blocksize ahead of it.
|
| 470 |
+
"""
|
| 471 |
+
|
| 472 |
+
name: ClassVar[str] = "bytes"
|
| 473 |
+
|
| 474 |
+
def __init__(
|
| 475 |
+
self, blocksize: int, fetcher: Fetcher, size: int, trim: bool = True
|
| 476 |
+
) -> None:
|
| 477 |
+
super().__init__(blocksize, fetcher, size)
|
| 478 |
+
self.cache = b""
|
| 479 |
+
self.start: int | None = None
|
| 480 |
+
self.end: int | None = None
|
| 481 |
+
self.trim = trim
|
| 482 |
+
|
| 483 |
+
def _fetch(self, start: int | None, end: int | None) -> bytes:
|
| 484 |
+
# TODO: only set start/end after fetch, in case it fails?
|
| 485 |
+
# is this where retry logic might go?
|
| 486 |
+
if start is None:
|
| 487 |
+
start = 0
|
| 488 |
+
if end is None:
|
| 489 |
+
end = self.size
|
| 490 |
+
if start >= self.size or start >= end:
|
| 491 |
+
return b""
|
| 492 |
+
if (
|
| 493 |
+
self.start is not None
|
| 494 |
+
and start >= self.start
|
| 495 |
+
and self.end is not None
|
| 496 |
+
and end < self.end
|
| 497 |
+
):
|
| 498 |
+
# cache hit: we have all the required data
|
| 499 |
+
offset = start - self.start
|
| 500 |
+
self.hit_count += 1
|
| 501 |
+
return self.cache[offset : offset + end - start]
|
| 502 |
+
|
| 503 |
+
if self.blocksize:
|
| 504 |
+
bend = min(self.size, end + self.blocksize)
|
| 505 |
+
else:
|
| 506 |
+
bend = end
|
| 507 |
+
|
| 508 |
+
if bend == start or start > self.size:
|
| 509 |
+
return b""
|
| 510 |
+
|
| 511 |
+
if (self.start is None or start < self.start) and (
|
| 512 |
+
self.end is None or end > self.end
|
| 513 |
+
):
|
| 514 |
+
# First read, or extending both before and after
|
| 515 |
+
self.total_requested_bytes += bend - start
|
| 516 |
+
self.miss_count += 1
|
| 517 |
+
self.cache = self.fetcher(start, bend)
|
| 518 |
+
self.start = start
|
| 519 |
+
else:
|
| 520 |
+
assert self.start is not None
|
| 521 |
+
assert self.end is not None
|
| 522 |
+
self.miss_count += 1
|
| 523 |
+
|
| 524 |
+
if start < self.start:
|
| 525 |
+
if self.end is None or self.end - end > self.blocksize:
|
| 526 |
+
self.total_requested_bytes += bend - start
|
| 527 |
+
self.cache = self.fetcher(start, bend)
|
| 528 |
+
self.start = start
|
| 529 |
+
else:
|
| 530 |
+
self.total_requested_bytes += self.start - start
|
| 531 |
+
new = self.fetcher(start, self.start)
|
| 532 |
+
self.start = start
|
| 533 |
+
self.cache = new + self.cache
|
| 534 |
+
elif self.end is not None and bend > self.end:
|
| 535 |
+
if self.end > self.size:
|
| 536 |
+
pass
|
| 537 |
+
elif end - self.end > self.blocksize:
|
| 538 |
+
self.total_requested_bytes += bend - start
|
| 539 |
+
self.cache = self.fetcher(start, bend)
|
| 540 |
+
self.start = start
|
| 541 |
+
else:
|
| 542 |
+
self.total_requested_bytes += bend - self.end
|
| 543 |
+
new = self.fetcher(self.end, bend)
|
| 544 |
+
self.cache = self.cache + new
|
| 545 |
+
|
| 546 |
+
self.end = self.start + len(self.cache)
|
| 547 |
+
offset = start - self.start
|
| 548 |
+
out = self.cache[offset : offset + end - start]
|
| 549 |
+
if self.trim:
|
| 550 |
+
num = (self.end - self.start) // (self.blocksize + 1)
|
| 551 |
+
if num > 1:
|
| 552 |
+
self.start += self.blocksize * num
|
| 553 |
+
self.cache = self.cache[self.blocksize * num :]
|
| 554 |
+
return out
|
| 555 |
+
|
| 556 |
+
def __len__(self) -> int:
|
| 557 |
+
return len(self.cache)
|
| 558 |
+
|
| 559 |
+
|
| 560 |
+
class AllBytes(BaseCache):
|
| 561 |
+
"""Cache entire contents of the file"""
|
| 562 |
+
|
| 563 |
+
name: ClassVar[str] = "all"
|
| 564 |
+
|
| 565 |
+
def __init__(
|
| 566 |
+
self,
|
| 567 |
+
blocksize: int | None = None,
|
| 568 |
+
fetcher: Fetcher | None = None,
|
| 569 |
+
size: int | None = None,
|
| 570 |
+
data: bytes | None = None,
|
| 571 |
+
) -> None:
|
| 572 |
+
super().__init__(blocksize, fetcher, size) # type: ignore[arg-type]
|
| 573 |
+
if data is None:
|
| 574 |
+
self.miss_count += 1
|
| 575 |
+
self.total_requested_bytes += self.size
|
| 576 |
+
data = self.fetcher(0, self.size)
|
| 577 |
+
self.data = data
|
| 578 |
+
|
| 579 |
+
def _fetch(self, start: int | None, stop: int | None) -> bytes:
|
| 580 |
+
self.hit_count += 1
|
| 581 |
+
return self.data[start:stop]
|
| 582 |
+
|
| 583 |
+
|
| 584 |
+
class KnownPartsOfAFile(BaseCache):
|
| 585 |
+
"""
|
| 586 |
+
Cache holding known file parts.
|
| 587 |
+
|
| 588 |
+
Parameters
|
| 589 |
+
----------
|
| 590 |
+
blocksize: int
|
| 591 |
+
How far to read ahead in numbers of bytes
|
| 592 |
+
fetcher: func
|
| 593 |
+
Function of the form f(start, end) which gets bytes from remote as
|
| 594 |
+
specified
|
| 595 |
+
size: int
|
| 596 |
+
How big this file is
|
| 597 |
+
data: dict
|
| 598 |
+
A dictionary mapping explicit `(start, stop)` file-offset tuples
|
| 599 |
+
with known bytes.
|
| 600 |
+
strict: bool, default True
|
| 601 |
+
Whether to fetch reads that go beyond a known byte-range boundary.
|
| 602 |
+
If `False`, any read that ends outside a known part will be zero
|
| 603 |
+
padded. Note that zero padding will not be used for reads that
|
| 604 |
+
begin outside a known byte-range.
|
| 605 |
+
"""
|
| 606 |
+
|
| 607 |
+
name: ClassVar[str] = "parts"
|
| 608 |
+
|
| 609 |
+
def __init__(
|
| 610 |
+
self,
|
| 611 |
+
blocksize: int,
|
| 612 |
+
fetcher: Fetcher,
|
| 613 |
+
size: int,
|
| 614 |
+
data: dict[tuple[int, int], bytes] | None = None,
|
| 615 |
+
strict: bool = False,
|
| 616 |
+
**_: Any,
|
| 617 |
+
):
|
| 618 |
+
super().__init__(blocksize, fetcher, size)
|
| 619 |
+
self.strict = strict
|
| 620 |
+
|
| 621 |
+
# simple consolidation of contiguous blocks
|
| 622 |
+
if data:
|
| 623 |
+
old_offsets = sorted(data.keys())
|
| 624 |
+
offsets = [old_offsets[0]]
|
| 625 |
+
blocks = [data.pop(old_offsets[0])]
|
| 626 |
+
for start, stop in old_offsets[1:]:
|
| 627 |
+
start0, stop0 = offsets[-1]
|
| 628 |
+
if start == stop0:
|
| 629 |
+
offsets[-1] = (start0, stop)
|
| 630 |
+
blocks[-1] += data.pop((start, stop))
|
| 631 |
+
else:
|
| 632 |
+
offsets.append((start, stop))
|
| 633 |
+
blocks.append(data.pop((start, stop)))
|
| 634 |
+
|
| 635 |
+
self.data = dict(zip(offsets, blocks))
|
| 636 |
+
else:
|
| 637 |
+
self.data = {}
|
| 638 |
+
|
| 639 |
+
@property
|
| 640 |
+
def size(self):
|
| 641 |
+
return sum(_[1] - _[0] for _ in self.data)
|
| 642 |
+
|
| 643 |
+
@size.setter
|
| 644 |
+
def size(self, value):
|
| 645 |
+
pass
|
| 646 |
+
|
| 647 |
+
@property
|
| 648 |
+
def nblocks(self):
|
| 649 |
+
return len(self.data)
|
| 650 |
+
|
| 651 |
+
@nblocks.setter
|
| 652 |
+
def nblocks(self, value):
|
| 653 |
+
pass
|
| 654 |
+
|
| 655 |
+
def _fetch(self, start: int | None, stop: int | None) -> bytes:
|
| 656 |
+
logger.debug("Known parts request %s %s", start, stop)
|
| 657 |
+
if start is None:
|
| 658 |
+
start = 0
|
| 659 |
+
if stop is None:
|
| 660 |
+
stop = self.size
|
| 661 |
+
self.total_requested_bytes += stop - start
|
| 662 |
+
out = b""
|
| 663 |
+
started = False
|
| 664 |
+
loc_old = 0
|
| 665 |
+
for loc0, loc1 in sorted(self.data):
|
| 666 |
+
if (loc0 <= start < loc1) and (loc0 <= stop <= loc1):
|
| 667 |
+
# entirely within the block
|
| 668 |
+
off = start - loc0
|
| 669 |
+
self.hit_count += 1
|
| 670 |
+
return self.data[(loc0, loc1)][off : off + stop - start]
|
| 671 |
+
if stop <= loc0:
|
| 672 |
+
break
|
| 673 |
+
if started and loc0 > loc_old:
|
| 674 |
+
# a gap where we need data
|
| 675 |
+
self.miss_count += 1
|
| 676 |
+
if self.strict:
|
| 677 |
+
raise ValueError
|
| 678 |
+
out += b"\x00" * (loc0 - loc_old)
|
| 679 |
+
if loc0 <= start < loc1:
|
| 680 |
+
# found the start
|
| 681 |
+
self.hit_count += 1
|
| 682 |
+
off = start - loc0
|
| 683 |
+
out = self.data[(loc0, loc1)][off : off + stop - start]
|
| 684 |
+
started = True
|
| 685 |
+
elif start < loc0 and stop > loc1:
|
| 686 |
+
# the whole block
|
| 687 |
+
self.hit_count += 1
|
| 688 |
+
out += self.data[(loc0, loc1)]
|
| 689 |
+
elif loc0 <= stop <= loc1:
|
| 690 |
+
# end block
|
| 691 |
+
self.hit_count += 1
|
| 692 |
+
out = out + self.data[(loc0, loc1)][: stop - loc0]
|
| 693 |
+
return out
|
| 694 |
+
loc_old = loc1
|
| 695 |
+
self.miss_count += 1
|
| 696 |
+
if started and not self.strict:
|
| 697 |
+
out = out + b"\x00" * (stop - loc_old)
|
| 698 |
+
return out
|
| 699 |
+
raise ValueError
|
| 700 |
+
|
| 701 |
+
|
| 702 |
+
class UpdatableLRU(Generic[P, T]):
|
| 703 |
+
"""
|
| 704 |
+
Custom implementation of LRU cache that allows updating keys
|
| 705 |
+
|
| 706 |
+
Used by BackgroundBlockCache
|
| 707 |
+
"""
|
| 708 |
+
|
| 709 |
+
class CacheInfo(NamedTuple):
|
| 710 |
+
hits: int
|
| 711 |
+
misses: int
|
| 712 |
+
maxsize: int
|
| 713 |
+
currsize: int
|
| 714 |
+
|
| 715 |
+
def __init__(self, func: Callable[P, T], max_size: int = 128) -> None:
|
| 716 |
+
self._cache: OrderedDict[Any, T] = collections.OrderedDict()
|
| 717 |
+
self._func = func
|
| 718 |
+
self._max_size = max_size
|
| 719 |
+
self._hits = 0
|
| 720 |
+
self._misses = 0
|
| 721 |
+
self._lock = threading.Lock()
|
| 722 |
+
|
| 723 |
+
def __call__(self, *args: P.args, **kwargs: P.kwargs) -> T:
|
| 724 |
+
if kwargs:
|
| 725 |
+
raise TypeError(f"Got unexpected keyword argument {kwargs.keys()}")
|
| 726 |
+
with self._lock:
|
| 727 |
+
if args in self._cache:
|
| 728 |
+
self._cache.move_to_end(args)
|
| 729 |
+
self._hits += 1
|
| 730 |
+
return self._cache[args]
|
| 731 |
+
|
| 732 |
+
result = self._func(*args, **kwargs)
|
| 733 |
+
|
| 734 |
+
with self._lock:
|
| 735 |
+
self._cache[args] = result
|
| 736 |
+
self._misses += 1
|
| 737 |
+
if len(self._cache) > self._max_size:
|
| 738 |
+
self._cache.popitem(last=False)
|
| 739 |
+
|
| 740 |
+
return result
|
| 741 |
+
|
| 742 |
+
def is_key_cached(self, *args: Any) -> bool:
|
| 743 |
+
with self._lock:
|
| 744 |
+
return args in self._cache
|
| 745 |
+
|
| 746 |
+
def add_key(self, result: T, *args: Any) -> None:
|
| 747 |
+
with self._lock:
|
| 748 |
+
self._cache[args] = result
|
| 749 |
+
if len(self._cache) > self._max_size:
|
| 750 |
+
self._cache.popitem(last=False)
|
| 751 |
+
|
| 752 |
+
def cache_info(self) -> UpdatableLRU.CacheInfo:
|
| 753 |
+
with self._lock:
|
| 754 |
+
return self.CacheInfo(
|
| 755 |
+
maxsize=self._max_size,
|
| 756 |
+
currsize=len(self._cache),
|
| 757 |
+
hits=self._hits,
|
| 758 |
+
misses=self._misses,
|
| 759 |
+
)
|
| 760 |
+
|
| 761 |
+
|
| 762 |
+
class BackgroundBlockCache(BaseCache):
|
| 763 |
+
"""
|
| 764 |
+
Cache holding memory as a set of blocks with pre-loading of
|
| 765 |
+
the next block in the background.
|
| 766 |
+
|
| 767 |
+
Requests are only ever made ``blocksize`` at a time, and are
|
| 768 |
+
stored in an LRU cache. The least recently accessed block is
|
| 769 |
+
discarded when more than ``maxblocks`` are stored. If the
|
| 770 |
+
next block is not in cache, it is loaded in a separate thread
|
| 771 |
+
in non-blocking way.
|
| 772 |
+
|
| 773 |
+
Parameters
|
| 774 |
+
----------
|
| 775 |
+
blocksize : int
|
| 776 |
+
The number of bytes to store in each block.
|
| 777 |
+
Requests are only ever made for ``blocksize``, so this
|
| 778 |
+
should balance the overhead of making a request against
|
| 779 |
+
the granularity of the blocks.
|
| 780 |
+
fetcher : Callable
|
| 781 |
+
size : int
|
| 782 |
+
The total size of the file being cached.
|
| 783 |
+
maxblocks : int
|
| 784 |
+
The maximum number of blocks to cache for. The maximum memory
|
| 785 |
+
use for this cache is then ``blocksize * maxblocks``.
|
| 786 |
+
"""
|
| 787 |
+
|
| 788 |
+
name: ClassVar[str] = "background"
|
| 789 |
+
|
| 790 |
+
def __init__(
|
| 791 |
+
self, blocksize: int, fetcher: Fetcher, size: int, maxblocks: int = 32
|
| 792 |
+
) -> None:
|
| 793 |
+
super().__init__(blocksize, fetcher, size)
|
| 794 |
+
self.nblocks = math.ceil(size / blocksize)
|
| 795 |
+
self.maxblocks = maxblocks
|
| 796 |
+
self._fetch_block_cached = UpdatableLRU(self._fetch_block, maxblocks)
|
| 797 |
+
|
| 798 |
+
self._thread_executor = ThreadPoolExecutor(max_workers=1)
|
| 799 |
+
self._fetch_future_block_number: int | None = None
|
| 800 |
+
self._fetch_future: Future[bytes] | None = None
|
| 801 |
+
self._fetch_future_lock = threading.Lock()
|
| 802 |
+
|
| 803 |
+
def cache_info(self) -> UpdatableLRU.CacheInfo:
|
| 804 |
+
"""
|
| 805 |
+
The statistics on the block cache.
|
| 806 |
+
|
| 807 |
+
Returns
|
| 808 |
+
-------
|
| 809 |
+
NamedTuple
|
| 810 |
+
Returned directly from the LRU Cache used internally.
|
| 811 |
+
"""
|
| 812 |
+
return self._fetch_block_cached.cache_info()
|
| 813 |
+
|
| 814 |
+
def __getstate__(self) -> dict[str, Any]:
|
| 815 |
+
state = self.__dict__
|
| 816 |
+
del state["_fetch_block_cached"]
|
| 817 |
+
del state["_thread_executor"]
|
| 818 |
+
del state["_fetch_future_block_number"]
|
| 819 |
+
del state["_fetch_future"]
|
| 820 |
+
del state["_fetch_future_lock"]
|
| 821 |
+
return state
|
| 822 |
+
|
| 823 |
+
def __setstate__(self, state) -> None:
|
| 824 |
+
self.__dict__.update(state)
|
| 825 |
+
self._fetch_block_cached = UpdatableLRU(self._fetch_block, state["maxblocks"])
|
| 826 |
+
self._thread_executor = ThreadPoolExecutor(max_workers=1)
|
| 827 |
+
self._fetch_future_block_number = None
|
| 828 |
+
self._fetch_future = None
|
| 829 |
+
self._fetch_future_lock = threading.Lock()
|
| 830 |
+
|
| 831 |
+
def _fetch(self, start: int | None, end: int | None) -> bytes:
|
| 832 |
+
if start is None:
|
| 833 |
+
start = 0
|
| 834 |
+
if end is None:
|
| 835 |
+
end = self.size
|
| 836 |
+
if start >= self.size or start >= end:
|
| 837 |
+
return b""
|
| 838 |
+
|
| 839 |
+
# byte position -> block numbers
|
| 840 |
+
start_block_number = start // self.blocksize
|
| 841 |
+
end_block_number = end // self.blocksize
|
| 842 |
+
|
| 843 |
+
fetch_future_block_number = None
|
| 844 |
+
fetch_future = None
|
| 845 |
+
with self._fetch_future_lock:
|
| 846 |
+
# Background thread is running. Check we we can or must join it.
|
| 847 |
+
if self._fetch_future is not None:
|
| 848 |
+
assert self._fetch_future_block_number is not None
|
| 849 |
+
if self._fetch_future.done():
|
| 850 |
+
logger.info("BlockCache joined background fetch without waiting.")
|
| 851 |
+
self._fetch_block_cached.add_key(
|
| 852 |
+
self._fetch_future.result(), self._fetch_future_block_number
|
| 853 |
+
)
|
| 854 |
+
# Cleanup the fetch variables. Done with fetching the block.
|
| 855 |
+
self._fetch_future_block_number = None
|
| 856 |
+
self._fetch_future = None
|
| 857 |
+
else:
|
| 858 |
+
# Must join if we need the block for the current fetch
|
| 859 |
+
must_join = bool(
|
| 860 |
+
start_block_number
|
| 861 |
+
<= self._fetch_future_block_number
|
| 862 |
+
<= end_block_number
|
| 863 |
+
)
|
| 864 |
+
if must_join:
|
| 865 |
+
# Copy to the local variables to release lock
|
| 866 |
+
# before waiting for result
|
| 867 |
+
fetch_future_block_number = self._fetch_future_block_number
|
| 868 |
+
fetch_future = self._fetch_future
|
| 869 |
+
|
| 870 |
+
# Cleanup the fetch variables. Have a local copy.
|
| 871 |
+
self._fetch_future_block_number = None
|
| 872 |
+
self._fetch_future = None
|
| 873 |
+
|
| 874 |
+
# Need to wait for the future for the current read
|
| 875 |
+
if fetch_future is not None:
|
| 876 |
+
logger.info("BlockCache waiting for background fetch.")
|
| 877 |
+
# Wait until result and put it in cache
|
| 878 |
+
self._fetch_block_cached.add_key(
|
| 879 |
+
fetch_future.result(), fetch_future_block_number
|
| 880 |
+
)
|
| 881 |
+
|
| 882 |
+
# these are cached, so safe to do multiple calls for the same start and end.
|
| 883 |
+
for block_number in range(start_block_number, end_block_number + 1):
|
| 884 |
+
self._fetch_block_cached(block_number)
|
| 885 |
+
|
| 886 |
+
# fetch next block in the background if nothing is running in the background,
|
| 887 |
+
# the block is within file and it is not already cached
|
| 888 |
+
end_block_plus_1 = end_block_number + 1
|
| 889 |
+
with self._fetch_future_lock:
|
| 890 |
+
if (
|
| 891 |
+
self._fetch_future is None
|
| 892 |
+
and end_block_plus_1 <= self.nblocks
|
| 893 |
+
and not self._fetch_block_cached.is_key_cached(end_block_plus_1)
|
| 894 |
+
):
|
| 895 |
+
self._fetch_future_block_number = end_block_plus_1
|
| 896 |
+
self._fetch_future = self._thread_executor.submit(
|
| 897 |
+
self._fetch_block, end_block_plus_1, "async"
|
| 898 |
+
)
|
| 899 |
+
|
| 900 |
+
return self._read_cache(
|
| 901 |
+
start,
|
| 902 |
+
end,
|
| 903 |
+
start_block_number=start_block_number,
|
| 904 |
+
end_block_number=end_block_number,
|
| 905 |
+
)
|
| 906 |
+
|
| 907 |
+
def _fetch_block(self, block_number: int, log_info: str = "sync") -> bytes:
|
| 908 |
+
"""
|
| 909 |
+
Fetch the block of data for `block_number`.
|
| 910 |
+
"""
|
| 911 |
+
if block_number > self.nblocks:
|
| 912 |
+
raise ValueError(
|
| 913 |
+
f"'block_number={block_number}' is greater than "
|
| 914 |
+
f"the number of blocks ({self.nblocks})"
|
| 915 |
+
)
|
| 916 |
+
|
| 917 |
+
start = block_number * self.blocksize
|
| 918 |
+
end = start + self.blocksize
|
| 919 |
+
logger.info("BlockCache fetching block (%s) %d", log_info, block_number)
|
| 920 |
+
self.total_requested_bytes += end - start
|
| 921 |
+
self.miss_count += 1
|
| 922 |
+
block_contents = super()._fetch(start, end)
|
| 923 |
+
return block_contents
|
| 924 |
+
|
| 925 |
+
def _read_cache(
|
| 926 |
+
self, start: int, end: int, start_block_number: int, end_block_number: int
|
| 927 |
+
) -> bytes:
|
| 928 |
+
"""
|
| 929 |
+
Read from our block cache.
|
| 930 |
+
|
| 931 |
+
Parameters
|
| 932 |
+
----------
|
| 933 |
+
start, end : int
|
| 934 |
+
The start and end byte positions.
|
| 935 |
+
start_block_number, end_block_number : int
|
| 936 |
+
The start and end block numbers.
|
| 937 |
+
"""
|
| 938 |
+
start_pos = start % self.blocksize
|
| 939 |
+
end_pos = end % self.blocksize
|
| 940 |
+
|
| 941 |
+
# kind of pointless to count this as a hit, but it is
|
| 942 |
+
self.hit_count += 1
|
| 943 |
+
|
| 944 |
+
if start_block_number == end_block_number:
|
| 945 |
+
block = self._fetch_block_cached(start_block_number)
|
| 946 |
+
return block[start_pos:end_pos]
|
| 947 |
+
|
| 948 |
+
else:
|
| 949 |
+
# read from the initial
|
| 950 |
+
out = [self._fetch_block_cached(start_block_number)[start_pos:]]
|
| 951 |
+
|
| 952 |
+
# intermediate blocks
|
| 953 |
+
# Note: it'd be nice to combine these into one big request. However
|
| 954 |
+
# that doesn't play nicely with our LRU cache.
|
| 955 |
+
out.extend(
|
| 956 |
+
map(
|
| 957 |
+
self._fetch_block_cached,
|
| 958 |
+
range(start_block_number + 1, end_block_number),
|
| 959 |
+
)
|
| 960 |
+
)
|
| 961 |
+
|
| 962 |
+
# final block
|
| 963 |
+
out.append(self._fetch_block_cached(end_block_number)[:end_pos])
|
| 964 |
+
|
| 965 |
+
return b"".join(out)
|
| 966 |
+
|
| 967 |
+
|
| 968 |
+
caches: dict[str | None, type[BaseCache]] = {
|
| 969 |
+
# one custom case
|
| 970 |
+
None: BaseCache,
|
| 971 |
+
}
|
| 972 |
+
|
| 973 |
+
|
| 974 |
+
def register_cache(cls: type[BaseCache], clobber: bool = False) -> None:
|
| 975 |
+
"""'Register' cache implementation.
|
| 976 |
+
|
| 977 |
+
Parameters
|
| 978 |
+
----------
|
| 979 |
+
clobber: bool, optional
|
| 980 |
+
If set to True (default is False) - allow to overwrite existing
|
| 981 |
+
entry.
|
| 982 |
+
|
| 983 |
+
Raises
|
| 984 |
+
------
|
| 985 |
+
ValueError
|
| 986 |
+
"""
|
| 987 |
+
name = cls.name
|
| 988 |
+
if not clobber and name in caches:
|
| 989 |
+
raise ValueError(f"Cache with name {name!r} is already known: {caches[name]}")
|
| 990 |
+
caches[name] = cls
|
| 991 |
+
|
| 992 |
+
|
| 993 |
+
for c in (
|
| 994 |
+
BaseCache,
|
| 995 |
+
MMapCache,
|
| 996 |
+
BytesCache,
|
| 997 |
+
ReadAheadCache,
|
| 998 |
+
BlockCache,
|
| 999 |
+
FirstChunkCache,
|
| 1000 |
+
AllBytes,
|
| 1001 |
+
KnownPartsOfAFile,
|
| 1002 |
+
BackgroundBlockCache,
|
| 1003 |
+
):
|
| 1004 |
+
register_cache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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()
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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)
|
micromamba_root/envs/hf_sync/Lib/site-packages/fsspec/config.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import configparser
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
import warnings
|
| 7 |
+
from typing import Any
|
| 8 |
+
|
| 9 |
+
conf: dict[str, dict[str, Any]] = {}
|
| 10 |
+
default_conf_dir = os.path.join(os.path.expanduser("~"), ".config/fsspec")
|
| 11 |
+
conf_dir = os.environ.get("FSSPEC_CONFIG_DIR", default_conf_dir)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def set_conf_env(conf_dict, envdict=os.environ):
|
| 15 |
+
"""Set config values from environment variables
|
| 16 |
+
|
| 17 |
+
Looks for variables of the form ``FSSPEC_<protocol>`` and
|
| 18 |
+
``FSSPEC_<protocol>_<kwarg>``. For ``FSSPEC_<protocol>`` the value is parsed
|
| 19 |
+
as a json dictionary and used to ``update`` the config of the
|
| 20 |
+
corresponding protocol. For ``FSSPEC_<protocol>_<kwarg>`` there is no
|
| 21 |
+
attempt to convert the string value, but the kwarg keys will be lower-cased.
|
| 22 |
+
|
| 23 |
+
The ``FSSPEC_<protocol>_<kwarg>`` variables are applied after the
|
| 24 |
+
``FSSPEC_<protocol>`` ones.
|
| 25 |
+
|
| 26 |
+
Parameters
|
| 27 |
+
----------
|
| 28 |
+
conf_dict : dict(str, dict)
|
| 29 |
+
This dict will be mutated
|
| 30 |
+
envdict : dict-like(str, str)
|
| 31 |
+
Source for the values - usually the real environment
|
| 32 |
+
"""
|
| 33 |
+
envdict = dict(envdict)
|
| 34 |
+
kwarg_keys = []
|
| 35 |
+
for key in envdict:
|
| 36 |
+
if key.startswith("FSSPEC_") and len(key) > 7 and key[7] != "_":
|
| 37 |
+
try:
|
| 38 |
+
value = json.loads(envdict[key])
|
| 39 |
+
envdict[key] = value
|
| 40 |
+
except json.decoder.JSONDecodeError:
|
| 41 |
+
value = envdict[key]
|
| 42 |
+
if key.count("_") > 1:
|
| 43 |
+
kwarg_keys.append(key)
|
| 44 |
+
continue
|
| 45 |
+
else:
|
| 46 |
+
if isinstance(value, dict):
|
| 47 |
+
_, proto = key.split("_", 1)
|
| 48 |
+
conf_dict.setdefault(proto.lower(), {}).update(value)
|
| 49 |
+
else:
|
| 50 |
+
warnings.warn(
|
| 51 |
+
f"Ignoring environment variable {key} due to not being a dict:"
|
| 52 |
+
f" {type(value)}"
|
| 53 |
+
)
|
| 54 |
+
elif key.startswith("FSSPEC"):
|
| 55 |
+
warnings.warn(
|
| 56 |
+
f"Ignoring environment variable {key} due to having an unexpected name"
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
for key in kwarg_keys:
|
| 60 |
+
_, proto, kwarg = key.split("_", 2)
|
| 61 |
+
conf_dict.setdefault(proto.lower(), {})[kwarg.lower()] = envdict[key]
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def set_conf_files(cdir, conf_dict):
|
| 65 |
+
"""Set config values from files
|
| 66 |
+
|
| 67 |
+
Scans for INI and JSON files in the given dictionary, and uses their
|
| 68 |
+
contents to set the config. In case of repeated values, later values
|
| 69 |
+
win.
|
| 70 |
+
|
| 71 |
+
In the case of INI files, all values are strings, and these will not
|
| 72 |
+
be converted.
|
| 73 |
+
|
| 74 |
+
Parameters
|
| 75 |
+
----------
|
| 76 |
+
cdir : str
|
| 77 |
+
Directory to search
|
| 78 |
+
conf_dict : dict(str, dict)
|
| 79 |
+
This dict will be mutated
|
| 80 |
+
"""
|
| 81 |
+
if not os.path.isdir(cdir):
|
| 82 |
+
return
|
| 83 |
+
allfiles = sorted(os.listdir(cdir))
|
| 84 |
+
for fn in allfiles:
|
| 85 |
+
if fn.endswith(".ini"):
|
| 86 |
+
ini = configparser.ConfigParser()
|
| 87 |
+
ini.read(os.path.join(cdir, fn))
|
| 88 |
+
for key in ini:
|
| 89 |
+
if key == "DEFAULT":
|
| 90 |
+
continue
|
| 91 |
+
conf_dict.setdefault(key, {}).update(dict(ini[key]))
|
| 92 |
+
if fn.endswith(".json"):
|
| 93 |
+
with open(os.path.join(cdir, fn)) as f:
|
| 94 |
+
js = json.load(f)
|
| 95 |
+
for key in js:
|
| 96 |
+
conf_dict.setdefault(key, {}).update(dict(js[key]))
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def apply_config(cls, kwargs, conf_dict=None):
|
| 100 |
+
"""Supply default values for kwargs when instantiating class
|
| 101 |
+
|
| 102 |
+
Augments the passed kwargs, by finding entries in the config dict
|
| 103 |
+
which match the classes ``.protocol`` attribute (one or more str)
|
| 104 |
+
|
| 105 |
+
Parameters
|
| 106 |
+
----------
|
| 107 |
+
cls : file system implementation
|
| 108 |
+
kwargs : dict
|
| 109 |
+
conf_dict : dict of dict
|
| 110 |
+
Typically this is the global configuration
|
| 111 |
+
|
| 112 |
+
Returns
|
| 113 |
+
-------
|
| 114 |
+
dict : the modified set of kwargs
|
| 115 |
+
"""
|
| 116 |
+
if conf_dict is None:
|
| 117 |
+
conf_dict = conf
|
| 118 |
+
protos = cls.protocol if isinstance(cls.protocol, (tuple, list)) else [cls.protocol]
|
| 119 |
+
kw = {}
|
| 120 |
+
for proto in protos:
|
| 121 |
+
# default kwargs from the current state of the config
|
| 122 |
+
if proto in conf_dict:
|
| 123 |
+
kw.update(conf_dict[proto])
|
| 124 |
+
# explicit kwargs always win
|
| 125 |
+
kw.update(**kwargs)
|
| 126 |
+
kwargs = kw
|
| 127 |
+
return kwargs
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
set_conf_files(conf_dir, conf)
|
| 131 |
+
set_conf_env(conf)
|
micromamba_root/envs/hf_sync/Lib/site-packages/fsspec/conftest.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import shutil
|
| 3 |
+
import subprocess
|
| 4 |
+
import sys
|
| 5 |
+
import time
|
| 6 |
+
from collections import deque
|
| 7 |
+
from collections.abc import Generator, Sequence
|
| 8 |
+
|
| 9 |
+
import pytest
|
| 10 |
+
|
| 11 |
+
import fsspec
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@pytest.fixture()
|
| 15 |
+
def m():
|
| 16 |
+
"""
|
| 17 |
+
Fixture providing a memory filesystem.
|
| 18 |
+
"""
|
| 19 |
+
m = fsspec.filesystem("memory")
|
| 20 |
+
m.store.clear()
|
| 21 |
+
m.pseudo_dirs.clear()
|
| 22 |
+
m.pseudo_dirs.append("")
|
| 23 |
+
try:
|
| 24 |
+
yield m
|
| 25 |
+
finally:
|
| 26 |
+
m.store.clear()
|
| 27 |
+
m.pseudo_dirs.clear()
|
| 28 |
+
m.pseudo_dirs.append("")
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class InstanceCacheInspector:
|
| 32 |
+
"""
|
| 33 |
+
Helper class to inspect instance caches of filesystem classes in tests.
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
def clear(self) -> None:
|
| 37 |
+
"""
|
| 38 |
+
Clear instance caches of all currently imported filesystem classes.
|
| 39 |
+
"""
|
| 40 |
+
classes = deque([fsspec.spec.AbstractFileSystem])
|
| 41 |
+
while classes:
|
| 42 |
+
cls = classes.popleft()
|
| 43 |
+
cls.clear_instance_cache()
|
| 44 |
+
classes.extend(cls.__subclasses__())
|
| 45 |
+
|
| 46 |
+
def gather_counts(self, *, omit_zero: bool = True) -> dict[str, int]:
|
| 47 |
+
"""
|
| 48 |
+
Gather counts of filesystem instances in the instance caches
|
| 49 |
+
of all currently imported filesystem classes.
|
| 50 |
+
|
| 51 |
+
Parameters
|
| 52 |
+
----------
|
| 53 |
+
omit_zero:
|
| 54 |
+
Whether to omit instance types with no cached instances.
|
| 55 |
+
"""
|
| 56 |
+
out: dict[str, int] = {}
|
| 57 |
+
classes = deque([fsspec.spec.AbstractFileSystem])
|
| 58 |
+
while classes:
|
| 59 |
+
cls = classes.popleft()
|
| 60 |
+
count = len(cls._cache) # there is no public interface for the cache
|
| 61 |
+
# note: skip intermediate AbstractFileSystem subclasses
|
| 62 |
+
# if they proxy the protocol attribute via a property.
|
| 63 |
+
if isinstance(cls.protocol, (Sequence, str)):
|
| 64 |
+
key = cls.protocol if isinstance(cls.protocol, str) else cls.protocol[0]
|
| 65 |
+
if count or not omit_zero:
|
| 66 |
+
out[key] = count
|
| 67 |
+
classes.extend(cls.__subclasses__())
|
| 68 |
+
return out
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
@pytest.fixture(scope="function", autouse=True)
|
| 72 |
+
def instance_caches() -> Generator[InstanceCacheInspector, None, None]:
|
| 73 |
+
"""
|
| 74 |
+
Fixture to ensure empty filesystem instance caches before and after a test.
|
| 75 |
+
|
| 76 |
+
Used by default for all tests.
|
| 77 |
+
Clears caches of all imported filesystem classes.
|
| 78 |
+
Can be used to write test assertions about instance caches.
|
| 79 |
+
|
| 80 |
+
Usage:
|
| 81 |
+
|
| 82 |
+
def test_something(instance_caches):
|
| 83 |
+
# Test code here
|
| 84 |
+
fsspec.open("file://abc")
|
| 85 |
+
fsspec.open("memory://foo/bar")
|
| 86 |
+
|
| 87 |
+
# Test assertion
|
| 88 |
+
assert instance_caches.gather_counts() == {"file": 1, "memory": 1}
|
| 89 |
+
|
| 90 |
+
Returns
|
| 91 |
+
-------
|
| 92 |
+
instance_caches: An instance cache inspector for clearing and inspecting caches.
|
| 93 |
+
"""
|
| 94 |
+
ic = InstanceCacheInspector()
|
| 95 |
+
|
| 96 |
+
ic.clear()
|
| 97 |
+
try:
|
| 98 |
+
yield ic
|
| 99 |
+
finally:
|
| 100 |
+
ic.clear()
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
@pytest.fixture(scope="function")
|
| 104 |
+
def ftp_writable(tmpdir):
|
| 105 |
+
"""
|
| 106 |
+
Fixture providing a writable FTP filesystem.
|
| 107 |
+
"""
|
| 108 |
+
pytest.importorskip("pyftpdlib")
|
| 109 |
+
|
| 110 |
+
d = str(tmpdir)
|
| 111 |
+
with open(os.path.join(d, "out"), "wb") as f:
|
| 112 |
+
f.write(b"hello" * 10000)
|
| 113 |
+
P = subprocess.Popen(
|
| 114 |
+
[sys.executable, "-m", "pyftpdlib", "-d", d, "-u", "user", "-P", "pass", "-w"]
|
| 115 |
+
)
|
| 116 |
+
try:
|
| 117 |
+
time.sleep(1)
|
| 118 |
+
yield "localhost", 2121, "user", "pass"
|
| 119 |
+
finally:
|
| 120 |
+
P.terminate()
|
| 121 |
+
P.wait()
|
| 122 |
+
try:
|
| 123 |
+
shutil.rmtree(tmpdir)
|
| 124 |
+
except Exception:
|
| 125 |
+
pass
|
micromamba_root/envs/hf_sync/Lib/site-packages/fsspec/core.py
ADDED
|
@@ -0,0 +1,760 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import io
|
| 4 |
+
import logging
|
| 5 |
+
import os
|
| 6 |
+
import re
|
| 7 |
+
from glob import has_magic
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
# for backwards compat, we export cache things from here too
|
| 11 |
+
from fsspec.caching import ( # noqa: F401
|
| 12 |
+
BaseCache,
|
| 13 |
+
BlockCache,
|
| 14 |
+
BytesCache,
|
| 15 |
+
MMapCache,
|
| 16 |
+
ReadAheadCache,
|
| 17 |
+
caches,
|
| 18 |
+
)
|
| 19 |
+
from fsspec.compression import compr
|
| 20 |
+
from fsspec.config import conf
|
| 21 |
+
from fsspec.registry import available_protocols, filesystem, get_filesystem_class
|
| 22 |
+
from fsspec.utils import (
|
| 23 |
+
_unstrip_protocol,
|
| 24 |
+
build_name_function,
|
| 25 |
+
infer_compression,
|
| 26 |
+
stringify_path,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
logger = logging.getLogger("fsspec")
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class OpenFile:
|
| 33 |
+
"""
|
| 34 |
+
File-like object to be used in a context
|
| 35 |
+
|
| 36 |
+
Can layer (buffered) text-mode and compression over any file-system, which
|
| 37 |
+
are typically binary-only.
|
| 38 |
+
|
| 39 |
+
These instances are safe to serialize, as the low-level file object
|
| 40 |
+
is not created until invoked using ``with``.
|
| 41 |
+
|
| 42 |
+
Parameters
|
| 43 |
+
----------
|
| 44 |
+
fs: FileSystem
|
| 45 |
+
The file system to use for opening the file. Should be a subclass or duck-type
|
| 46 |
+
with ``fsspec.spec.AbstractFileSystem``
|
| 47 |
+
path: str
|
| 48 |
+
Location to open
|
| 49 |
+
mode: str like 'rb', optional
|
| 50 |
+
Mode of the opened file
|
| 51 |
+
compression: str or None, optional
|
| 52 |
+
Compression to apply
|
| 53 |
+
encoding: str or None, optional
|
| 54 |
+
The encoding to use if opened in text mode.
|
| 55 |
+
errors: str or None, optional
|
| 56 |
+
How to handle encoding errors if opened in text mode.
|
| 57 |
+
newline: None or str
|
| 58 |
+
Passed to TextIOWrapper in text mode, how to handle line endings.
|
| 59 |
+
autoopen: bool
|
| 60 |
+
If True, calls open() immediately. Mostly used by pickle
|
| 61 |
+
pos: int
|
| 62 |
+
If given and autoopen is True, seek to this location immediately
|
| 63 |
+
"""
|
| 64 |
+
|
| 65 |
+
def __init__(
|
| 66 |
+
self,
|
| 67 |
+
fs,
|
| 68 |
+
path,
|
| 69 |
+
mode="rb",
|
| 70 |
+
compression=None,
|
| 71 |
+
encoding=None,
|
| 72 |
+
errors=None,
|
| 73 |
+
newline=None,
|
| 74 |
+
):
|
| 75 |
+
self.fs = fs
|
| 76 |
+
self.path = path
|
| 77 |
+
self.mode = mode
|
| 78 |
+
self.compression = get_compression(path, compression)
|
| 79 |
+
self.encoding = encoding
|
| 80 |
+
self.errors = errors
|
| 81 |
+
self.newline = newline
|
| 82 |
+
self.fobjects = []
|
| 83 |
+
|
| 84 |
+
def __reduce__(self):
|
| 85 |
+
return (
|
| 86 |
+
OpenFile,
|
| 87 |
+
(
|
| 88 |
+
self.fs,
|
| 89 |
+
self.path,
|
| 90 |
+
self.mode,
|
| 91 |
+
self.compression,
|
| 92 |
+
self.encoding,
|
| 93 |
+
self.errors,
|
| 94 |
+
self.newline,
|
| 95 |
+
),
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
def __repr__(self):
|
| 99 |
+
return f"<OpenFile '{self.path}'>"
|
| 100 |
+
|
| 101 |
+
def __enter__(self):
|
| 102 |
+
mode = self.mode.replace("t", "").replace("b", "") + "b"
|
| 103 |
+
|
| 104 |
+
try:
|
| 105 |
+
f = self.fs.open(self.path, mode=mode)
|
| 106 |
+
except FileNotFoundError as e:
|
| 107 |
+
if has_magic(self.path):
|
| 108 |
+
raise FileNotFoundError(
|
| 109 |
+
"%s not found. The URL contains glob characters: you maybe needed\n"
|
| 110 |
+
"to pass expand=True in fsspec.open() or the storage_options of \n"
|
| 111 |
+
"your library. You can also set the config value 'open_expand'\n"
|
| 112 |
+
"before import, or fsspec.core.DEFAULT_EXPAND at runtime, to True.",
|
| 113 |
+
self.path,
|
| 114 |
+
) from e
|
| 115 |
+
raise
|
| 116 |
+
|
| 117 |
+
self.fobjects = [f]
|
| 118 |
+
|
| 119 |
+
if self.compression is not None:
|
| 120 |
+
compress = compr[self.compression]
|
| 121 |
+
f = compress(f, mode=mode[0])
|
| 122 |
+
self.fobjects.append(f)
|
| 123 |
+
|
| 124 |
+
if "b" not in self.mode:
|
| 125 |
+
# assume, for example, that 'r' is equivalent to 'rt' as in builtin
|
| 126 |
+
f = PickleableTextIOWrapper(
|
| 127 |
+
f, encoding=self.encoding, errors=self.errors, newline=self.newline
|
| 128 |
+
)
|
| 129 |
+
self.fobjects.append(f)
|
| 130 |
+
|
| 131 |
+
return self.fobjects[-1]
|
| 132 |
+
|
| 133 |
+
def __exit__(self, *args):
|
| 134 |
+
self.close()
|
| 135 |
+
|
| 136 |
+
@property
|
| 137 |
+
def full_name(self):
|
| 138 |
+
return _unstrip_protocol(self.path, self.fs)
|
| 139 |
+
|
| 140 |
+
def open(self):
|
| 141 |
+
"""Materialise this as a real open file without context
|
| 142 |
+
|
| 143 |
+
The OpenFile object should be explicitly closed to avoid enclosed file
|
| 144 |
+
instances persisting. You must, therefore, keep a reference to the OpenFile
|
| 145 |
+
during the life of the file-like it generates.
|
| 146 |
+
"""
|
| 147 |
+
return self.__enter__()
|
| 148 |
+
|
| 149 |
+
def close(self):
|
| 150 |
+
"""Close all encapsulated file objects"""
|
| 151 |
+
for f in reversed(self.fobjects):
|
| 152 |
+
if "r" not in self.mode and not f.closed:
|
| 153 |
+
f.flush()
|
| 154 |
+
f.close()
|
| 155 |
+
self.fobjects.clear()
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
class OpenFiles(list):
|
| 159 |
+
"""List of OpenFile instances
|
| 160 |
+
|
| 161 |
+
Can be used in a single context, which opens and closes all of the
|
| 162 |
+
contained files. Normal list access to get the elements works as
|
| 163 |
+
normal.
|
| 164 |
+
|
| 165 |
+
A special case is made for caching filesystems - the files will
|
| 166 |
+
be down/uploaded together at the start or end of the context, and
|
| 167 |
+
this may happen concurrently, if the target filesystem supports it.
|
| 168 |
+
"""
|
| 169 |
+
|
| 170 |
+
def __init__(self, *args, mode="rb", fs=None):
|
| 171 |
+
self.mode = mode
|
| 172 |
+
self.fs = fs
|
| 173 |
+
self.files = []
|
| 174 |
+
super().__init__(*args)
|
| 175 |
+
|
| 176 |
+
def __enter__(self):
|
| 177 |
+
if self.fs is None:
|
| 178 |
+
raise ValueError("Context has already been used")
|
| 179 |
+
|
| 180 |
+
fs = self.fs
|
| 181 |
+
while True:
|
| 182 |
+
if hasattr(fs, "open_many"):
|
| 183 |
+
# check for concurrent cache download; or set up for upload
|
| 184 |
+
self.files = fs.open_many(self)
|
| 185 |
+
return self.files
|
| 186 |
+
if hasattr(fs, "fs") and fs.fs is not None:
|
| 187 |
+
fs = fs.fs
|
| 188 |
+
else:
|
| 189 |
+
break
|
| 190 |
+
return [s.__enter__() for s in self]
|
| 191 |
+
|
| 192 |
+
def __exit__(self, *args):
|
| 193 |
+
fs = self.fs
|
| 194 |
+
[s.__exit__(*args) for s in self]
|
| 195 |
+
if "r" not in self.mode:
|
| 196 |
+
while True:
|
| 197 |
+
if hasattr(fs, "open_many"):
|
| 198 |
+
# check for concurrent cache upload
|
| 199 |
+
fs.commit_many(self.files)
|
| 200 |
+
return
|
| 201 |
+
if hasattr(fs, "fs") and fs.fs is not None:
|
| 202 |
+
fs = fs.fs
|
| 203 |
+
else:
|
| 204 |
+
break
|
| 205 |
+
|
| 206 |
+
def __getitem__(self, item):
|
| 207 |
+
out = super().__getitem__(item)
|
| 208 |
+
if isinstance(item, slice):
|
| 209 |
+
return OpenFiles(out, mode=self.mode, fs=self.fs)
|
| 210 |
+
return out
|
| 211 |
+
|
| 212 |
+
def __repr__(self):
|
| 213 |
+
return f"<List of {len(self)} OpenFile instances>"
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def open_files(
|
| 217 |
+
urlpath,
|
| 218 |
+
mode="rb",
|
| 219 |
+
compression=None,
|
| 220 |
+
encoding="utf8",
|
| 221 |
+
errors=None,
|
| 222 |
+
name_function=None,
|
| 223 |
+
num=1,
|
| 224 |
+
protocol=None,
|
| 225 |
+
newline=None,
|
| 226 |
+
auto_mkdir=True,
|
| 227 |
+
expand=True,
|
| 228 |
+
**kwargs,
|
| 229 |
+
):
|
| 230 |
+
"""Given a path or paths, return a list of ``OpenFile`` objects.
|
| 231 |
+
|
| 232 |
+
For writing, a str path must contain the "*" character, which will be filled
|
| 233 |
+
in by increasing numbers, e.g., "part*" -> "part1", "part2" if num=2.
|
| 234 |
+
|
| 235 |
+
For either reading or writing, can instead provide explicit list of paths.
|
| 236 |
+
|
| 237 |
+
Parameters
|
| 238 |
+
----------
|
| 239 |
+
urlpath: string or list
|
| 240 |
+
Absolute or relative filepath(s). Prefix with a protocol like ``s3://``
|
| 241 |
+
to read from alternative filesystems. To read from multiple files you
|
| 242 |
+
can pass a globstring or a list of paths, with the caveat that they
|
| 243 |
+
must all have the same protocol.
|
| 244 |
+
mode: 'rb', 'wt', etc.
|
| 245 |
+
compression: string or None
|
| 246 |
+
If given, open file using compression codec. Can either be a compression
|
| 247 |
+
name (a key in ``fsspec.compression.compr``) or "infer" to guess the
|
| 248 |
+
compression from the filename suffix.
|
| 249 |
+
encoding: str
|
| 250 |
+
For text mode only
|
| 251 |
+
errors: None or str
|
| 252 |
+
Passed to TextIOWrapper in text mode
|
| 253 |
+
name_function: function or None
|
| 254 |
+
if opening a set of files for writing, those files do not yet exist,
|
| 255 |
+
so we need to generate their names by formatting the urlpath for
|
| 256 |
+
each sequence number
|
| 257 |
+
num: int [1]
|
| 258 |
+
if writing mode, number of files we expect to create (passed to
|
| 259 |
+
name+function)
|
| 260 |
+
protocol: str or None
|
| 261 |
+
If given, overrides the protocol found in the URL.
|
| 262 |
+
newline: bytes or None
|
| 263 |
+
Used for line terminator in text mode. If None, uses system default;
|
| 264 |
+
if blank, uses no translation.
|
| 265 |
+
auto_mkdir: bool (True)
|
| 266 |
+
If in write mode, this will ensure the target directory exists before
|
| 267 |
+
writing, by calling ``fs.mkdirs(exist_ok=True)``.
|
| 268 |
+
expand: bool
|
| 269 |
+
**kwargs: dict
|
| 270 |
+
Extra options that make sense to a particular storage connection, e.g.
|
| 271 |
+
host, port, username, password, etc.
|
| 272 |
+
|
| 273 |
+
Examples
|
| 274 |
+
--------
|
| 275 |
+
>>> files = open_files('2015-*-*.csv') # doctest: +SKIP
|
| 276 |
+
>>> files = open_files(
|
| 277 |
+
... 's3://bucket/2015-*-*.csv.gz', compression='gzip'
|
| 278 |
+
... ) # doctest: +SKIP
|
| 279 |
+
|
| 280 |
+
Returns
|
| 281 |
+
-------
|
| 282 |
+
An ``OpenFiles`` instance, which is a list of ``OpenFile`` objects that can
|
| 283 |
+
be used as a single context
|
| 284 |
+
|
| 285 |
+
Notes
|
| 286 |
+
-----
|
| 287 |
+
For a full list of the available protocols and the implementations that
|
| 288 |
+
they map across to see the latest online documentation:
|
| 289 |
+
|
| 290 |
+
- For implementations built into ``fsspec`` see
|
| 291 |
+
https://filesystem-spec.readthedocs.io/en/latest/api.html#built-in-implementations
|
| 292 |
+
- For implementations in separate packages see
|
| 293 |
+
https://filesystem-spec.readthedocs.io/en/latest/api.html#other-known-implementations
|
| 294 |
+
"""
|
| 295 |
+
fs, fs_token, paths = get_fs_token_paths(
|
| 296 |
+
urlpath,
|
| 297 |
+
mode,
|
| 298 |
+
num=num,
|
| 299 |
+
name_function=name_function,
|
| 300 |
+
storage_options=kwargs,
|
| 301 |
+
protocol=protocol,
|
| 302 |
+
expand=expand,
|
| 303 |
+
)
|
| 304 |
+
if fs.protocol == "file":
|
| 305 |
+
fs.auto_mkdir = auto_mkdir
|
| 306 |
+
elif "r" not in mode and auto_mkdir:
|
| 307 |
+
parents = {fs._parent(path) for path in paths}
|
| 308 |
+
for parent in parents:
|
| 309 |
+
try:
|
| 310 |
+
fs.makedirs(parent, exist_ok=True)
|
| 311 |
+
except PermissionError:
|
| 312 |
+
pass
|
| 313 |
+
return OpenFiles(
|
| 314 |
+
[
|
| 315 |
+
OpenFile(
|
| 316 |
+
fs,
|
| 317 |
+
path,
|
| 318 |
+
mode=mode,
|
| 319 |
+
compression=compression,
|
| 320 |
+
encoding=encoding,
|
| 321 |
+
errors=errors,
|
| 322 |
+
newline=newline,
|
| 323 |
+
)
|
| 324 |
+
for path in paths
|
| 325 |
+
],
|
| 326 |
+
mode=mode,
|
| 327 |
+
fs=fs,
|
| 328 |
+
)
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
def _un_chain(path, kwargs):
|
| 332 |
+
# Avoid a circular import
|
| 333 |
+
from fsspec.implementations.chained import ChainedFileSystem
|
| 334 |
+
|
| 335 |
+
if "::" in path:
|
| 336 |
+
x = re.compile(".*[^a-z]+.*") # test for non protocol-like single word
|
| 337 |
+
known_protocols = set(available_protocols())
|
| 338 |
+
bits = []
|
| 339 |
+
|
| 340 |
+
# split on '::', then ensure each bit has a protocol
|
| 341 |
+
for p in path.split("::"):
|
| 342 |
+
if p in known_protocols:
|
| 343 |
+
bits.append(p + "://")
|
| 344 |
+
elif "://" in p or x.match(p):
|
| 345 |
+
bits.append(p)
|
| 346 |
+
else:
|
| 347 |
+
bits.append(p + "://")
|
| 348 |
+
else:
|
| 349 |
+
bits = [path]
|
| 350 |
+
|
| 351 |
+
# [[url, protocol, kwargs], ...]
|
| 352 |
+
out = []
|
| 353 |
+
previous_bit = None
|
| 354 |
+
kwargs = kwargs.copy()
|
| 355 |
+
|
| 356 |
+
for bit in reversed(bits):
|
| 357 |
+
protocol = kwargs.pop("protocol", None) or split_protocol(bit)[0] or "file"
|
| 358 |
+
cls = get_filesystem_class(protocol)
|
| 359 |
+
extra_kwargs = cls._get_kwargs_from_urls(bit)
|
| 360 |
+
kws = kwargs.pop(protocol, {})
|
| 361 |
+
|
| 362 |
+
if bit is bits[0]:
|
| 363 |
+
kws.update(kwargs)
|
| 364 |
+
|
| 365 |
+
kw = dict(
|
| 366 |
+
**{k: v for k, v in extra_kwargs.items() if k not in kws or v != kws[k]},
|
| 367 |
+
**kws,
|
| 368 |
+
)
|
| 369 |
+
bit = cls._strip_protocol(bit)
|
| 370 |
+
|
| 371 |
+
if (
|
| 372 |
+
"target_protocol" not in kw
|
| 373 |
+
and issubclass(cls, ChainedFileSystem)
|
| 374 |
+
and not bit
|
| 375 |
+
):
|
| 376 |
+
# replace bit if we are chaining and no path given
|
| 377 |
+
bit = previous_bit
|
| 378 |
+
|
| 379 |
+
out.append((bit, protocol, kw))
|
| 380 |
+
previous_bit = bit
|
| 381 |
+
|
| 382 |
+
out.reverse()
|
| 383 |
+
return out
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
def url_to_fs(url, **kwargs):
|
| 387 |
+
"""
|
| 388 |
+
Turn fully-qualified and potentially chained URL into filesystem instance
|
| 389 |
+
|
| 390 |
+
Parameters
|
| 391 |
+
----------
|
| 392 |
+
url : str
|
| 393 |
+
The fsspec-compatible URL
|
| 394 |
+
**kwargs: dict
|
| 395 |
+
Extra options that make sense to a particular storage connection, e.g.
|
| 396 |
+
host, port, username, password, etc.
|
| 397 |
+
|
| 398 |
+
Returns
|
| 399 |
+
-------
|
| 400 |
+
filesystem : FileSystem
|
| 401 |
+
The new filesystem discovered from ``url`` and created with
|
| 402 |
+
``**kwargs``.
|
| 403 |
+
urlpath : str
|
| 404 |
+
The file-systems-specific URL for ``url``.
|
| 405 |
+
"""
|
| 406 |
+
url = stringify_path(url)
|
| 407 |
+
# non-FS arguments that appear in fsspec.open()
|
| 408 |
+
# inspect could keep this in sync with open()'s signature
|
| 409 |
+
known_kwargs = {
|
| 410 |
+
"compression",
|
| 411 |
+
"encoding",
|
| 412 |
+
"errors",
|
| 413 |
+
"expand",
|
| 414 |
+
"mode",
|
| 415 |
+
"name_function",
|
| 416 |
+
"newline",
|
| 417 |
+
"num",
|
| 418 |
+
}
|
| 419 |
+
kwargs = {k: v for k, v in kwargs.items() if k not in known_kwargs}
|
| 420 |
+
chain = _un_chain(url, kwargs)
|
| 421 |
+
inkwargs = {}
|
| 422 |
+
# Reverse iterate the chain, creating a nested target_* structure
|
| 423 |
+
for i, ch in enumerate(reversed(chain)):
|
| 424 |
+
urls, protocol, kw = ch
|
| 425 |
+
if i == len(chain) - 1:
|
| 426 |
+
inkwargs = dict(**kw, **inkwargs)
|
| 427 |
+
continue
|
| 428 |
+
inkwargs["target_options"] = dict(**kw, **inkwargs)
|
| 429 |
+
inkwargs["target_protocol"] = protocol
|
| 430 |
+
inkwargs["fo"] = urls
|
| 431 |
+
urlpath, protocol, _ = chain[0]
|
| 432 |
+
fs = filesystem(protocol, **inkwargs)
|
| 433 |
+
return fs, urlpath
|
| 434 |
+
|
| 435 |
+
|
| 436 |
+
DEFAULT_EXPAND = conf.get("open_expand", False)
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
def open(
|
| 440 |
+
urlpath,
|
| 441 |
+
mode="rb",
|
| 442 |
+
compression=None,
|
| 443 |
+
encoding="utf8",
|
| 444 |
+
errors=None,
|
| 445 |
+
protocol=None,
|
| 446 |
+
newline=None,
|
| 447 |
+
expand=None,
|
| 448 |
+
**kwargs,
|
| 449 |
+
):
|
| 450 |
+
"""Given a path or paths, return one ``OpenFile`` object.
|
| 451 |
+
|
| 452 |
+
Parameters
|
| 453 |
+
----------
|
| 454 |
+
urlpath: string or list
|
| 455 |
+
Absolute or relative filepath. Prefix with a protocol like ``s3://``
|
| 456 |
+
to read from alternative filesystems. Should not include glob
|
| 457 |
+
character(s).
|
| 458 |
+
mode: 'rb', 'wt', etc.
|
| 459 |
+
compression: string or None
|
| 460 |
+
If given, open file using compression codec. Can either be a compression
|
| 461 |
+
name (a key in ``fsspec.compression.compr``) or "infer" to guess the
|
| 462 |
+
compression from the filename suffix.
|
| 463 |
+
encoding: str
|
| 464 |
+
For text mode only
|
| 465 |
+
errors: None or str
|
| 466 |
+
Passed to TextIOWrapper in text mode
|
| 467 |
+
protocol: str or None
|
| 468 |
+
If given, overrides the protocol found in the URL.
|
| 469 |
+
newline: bytes or None
|
| 470 |
+
Used for line terminator in text mode. If None, uses system default;
|
| 471 |
+
if blank, uses no translation.
|
| 472 |
+
expand: bool or None
|
| 473 |
+
Whether to regard file paths containing special glob characters as needing
|
| 474 |
+
expansion (finding the first match) or absolute. Setting False allows using
|
| 475 |
+
paths which do embed such characters. If None (default), this argument
|
| 476 |
+
takes its value from the DEFAULT_EXPAND module variable, which takes
|
| 477 |
+
its initial value from the "open_expand" config value at startup, which will
|
| 478 |
+
be False if not set.
|
| 479 |
+
**kwargs: dict
|
| 480 |
+
Extra options that make sense to a particular storage connection, e.g.
|
| 481 |
+
host, port, username, password, etc.
|
| 482 |
+
|
| 483 |
+
Examples
|
| 484 |
+
--------
|
| 485 |
+
>>> openfile = open('2015-01-01.csv') # doctest: +SKIP
|
| 486 |
+
>>> openfile = open(
|
| 487 |
+
... 's3://bucket/2015-01-01.csv.gz', compression='gzip'
|
| 488 |
+
... ) # doctest: +SKIP
|
| 489 |
+
>>> with openfile as f:
|
| 490 |
+
... df = pd.read_csv(f) # doctest: +SKIP
|
| 491 |
+
...
|
| 492 |
+
|
| 493 |
+
Returns
|
| 494 |
+
-------
|
| 495 |
+
``OpenFile`` object.
|
| 496 |
+
|
| 497 |
+
Notes
|
| 498 |
+
-----
|
| 499 |
+
For a full list of the available protocols and the implementations that
|
| 500 |
+
they map across to see the latest online documentation:
|
| 501 |
+
|
| 502 |
+
- For implementations built into ``fsspec`` see
|
| 503 |
+
https://filesystem-spec.readthedocs.io/en/latest/api.html#built-in-implementations
|
| 504 |
+
- For implementations in separate packages see
|
| 505 |
+
https://filesystem-spec.readthedocs.io/en/latest/api.html#other-known-implementations
|
| 506 |
+
"""
|
| 507 |
+
expand = DEFAULT_EXPAND if expand is None else expand
|
| 508 |
+
out = open_files(
|
| 509 |
+
urlpath=[urlpath],
|
| 510 |
+
mode=mode,
|
| 511 |
+
compression=compression,
|
| 512 |
+
encoding=encoding,
|
| 513 |
+
errors=errors,
|
| 514 |
+
protocol=protocol,
|
| 515 |
+
newline=newline,
|
| 516 |
+
expand=expand,
|
| 517 |
+
**kwargs,
|
| 518 |
+
)
|
| 519 |
+
if not out:
|
| 520 |
+
raise FileNotFoundError(urlpath)
|
| 521 |
+
return out[0]
|
| 522 |
+
|
| 523 |
+
|
| 524 |
+
def open_local(
|
| 525 |
+
url: str | list[str] | Path | list[Path],
|
| 526 |
+
mode: str = "rb",
|
| 527 |
+
**storage_options: dict,
|
| 528 |
+
) -> str | list[str]:
|
| 529 |
+
"""Open file(s) which can be resolved to local
|
| 530 |
+
|
| 531 |
+
For files which either are local, or get downloaded upon open
|
| 532 |
+
(e.g., by file caching)
|
| 533 |
+
|
| 534 |
+
Parameters
|
| 535 |
+
----------
|
| 536 |
+
url: str or list(str)
|
| 537 |
+
mode: str
|
| 538 |
+
Must be read mode
|
| 539 |
+
storage_options:
|
| 540 |
+
passed on to FS for or used by open_files (e.g., compression)
|
| 541 |
+
"""
|
| 542 |
+
if "r" not in mode:
|
| 543 |
+
raise ValueError("Can only ensure local files when reading")
|
| 544 |
+
of = open_files(url, mode=mode, **storage_options)
|
| 545 |
+
if not getattr(of[0].fs, "local_file", False):
|
| 546 |
+
raise ValueError(
|
| 547 |
+
"open_local can only be used on a filesystem which"
|
| 548 |
+
" has attribute local_file=True"
|
| 549 |
+
)
|
| 550 |
+
with of as files:
|
| 551 |
+
paths = [f.name for f in files]
|
| 552 |
+
if (isinstance(url, str) and not has_magic(url)) or isinstance(url, Path):
|
| 553 |
+
return paths[0]
|
| 554 |
+
return paths
|
| 555 |
+
|
| 556 |
+
|
| 557 |
+
def get_compression(urlpath, compression):
|
| 558 |
+
if compression == "infer":
|
| 559 |
+
compression = infer_compression(urlpath)
|
| 560 |
+
if compression is not None and compression not in compr:
|
| 561 |
+
raise ValueError(f"Compression type {compression} not supported")
|
| 562 |
+
return compression
|
| 563 |
+
|
| 564 |
+
|
| 565 |
+
def split_protocol(urlpath):
|
| 566 |
+
"""Return protocol, path pair"""
|
| 567 |
+
urlpath = stringify_path(urlpath)
|
| 568 |
+
if "://" in urlpath:
|
| 569 |
+
protocol, path = urlpath.split("://", 1)
|
| 570 |
+
if len(protocol) > 1:
|
| 571 |
+
# excludes Windows paths
|
| 572 |
+
return protocol, path
|
| 573 |
+
if urlpath.startswith("data:"):
|
| 574 |
+
return urlpath.split(":", 1)
|
| 575 |
+
return None, urlpath
|
| 576 |
+
|
| 577 |
+
|
| 578 |
+
def strip_protocol(urlpath):
|
| 579 |
+
"""Return only path part of full URL, according to appropriate backend"""
|
| 580 |
+
protocol, _ = split_protocol(urlpath)
|
| 581 |
+
cls = get_filesystem_class(protocol)
|
| 582 |
+
return cls._strip_protocol(urlpath)
|
| 583 |
+
|
| 584 |
+
|
| 585 |
+
def expand_paths_if_needed(paths, mode, num, fs, name_function):
|
| 586 |
+
"""Expand paths if they have a ``*`` in them (write mode) or any of ``*?[]``
|
| 587 |
+
in them (read mode).
|
| 588 |
+
|
| 589 |
+
:param paths: list of paths
|
| 590 |
+
mode: str
|
| 591 |
+
Mode in which to open files.
|
| 592 |
+
num: int
|
| 593 |
+
If opening in writing mode, number of files we expect to create.
|
| 594 |
+
fs: filesystem object
|
| 595 |
+
name_function: callable
|
| 596 |
+
If opening in writing mode, this callable is used to generate path
|
| 597 |
+
names. Names are generated for each partition by
|
| 598 |
+
``urlpath.replace('*', name_function(partition_index))``.
|
| 599 |
+
:return: list of paths
|
| 600 |
+
"""
|
| 601 |
+
expanded_paths = []
|
| 602 |
+
paths = list(paths)
|
| 603 |
+
|
| 604 |
+
if "w" in mode: # read 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
|
micromamba_root/envs/hf_sync/Lib/site-packages/fsspec/dircache.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import time
|
| 2 |
+
from collections.abc import MutableMapping
|
| 3 |
+
from functools import lru_cache
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class DirCache(MutableMapping):
|
| 7 |
+
"""
|
| 8 |
+
Caching of directory listings, in a structure like::
|
| 9 |
+
|
| 10 |
+
{"path0": [
|
| 11 |
+
{"name": "path0/file0",
|
| 12 |
+
"size": 123,
|
| 13 |
+
"type": "file",
|
| 14 |
+
...
|
| 15 |
+
},
|
| 16 |
+
{"name": "path0/file1",
|
| 17 |
+
},
|
| 18 |
+
...
|
| 19 |
+
],
|
| 20 |
+
"path1": [...]
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
Parameters to this class control listing expiry or indeed turn
|
| 24 |
+
caching off
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
def __init__(
|
| 28 |
+
self,
|
| 29 |
+
use_listings_cache=True,
|
| 30 |
+
listings_expiry_time=None,
|
| 31 |
+
max_paths=None,
|
| 32 |
+
**kwargs,
|
| 33 |
+
):
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
Parameters
|
| 37 |
+
----------
|
| 38 |
+
use_listings_cache: bool
|
| 39 |
+
If False, this cache never returns items, but always reports KeyError,
|
| 40 |
+
and setting items has no effect
|
| 41 |
+
listings_expiry_time: int or float (optional)
|
| 42 |
+
Time in seconds that a listing is considered valid. If None,
|
| 43 |
+
listings do not expire.
|
| 44 |
+
max_paths: int (optional)
|
| 45 |
+
The number of most recent listings that are considered valid; 'recent'
|
| 46 |
+
refers to when the entry was set.
|
| 47 |
+
"""
|
| 48 |
+
self._cache = {}
|
| 49 |
+
self._times = {}
|
| 50 |
+
if max_paths:
|
| 51 |
+
self._q = lru_cache(max_paths + 1)(lambda key: self._cache.pop(key, None))
|
| 52 |
+
self.use_listings_cache = use_listings_cache
|
| 53 |
+
self.listings_expiry_time = listings_expiry_time
|
| 54 |
+
self.max_paths = max_paths
|
| 55 |
+
|
| 56 |
+
def __getitem__(self, item):
|
| 57 |
+
if self.listings_expiry_time is not None:
|
| 58 |
+
if self._times.get(item, 0) - time.time() < -self.listings_expiry_time:
|
| 59 |
+
del self._cache[item]
|
| 60 |
+
if self.max_paths:
|
| 61 |
+
self._q(item)
|
| 62 |
+
return self._cache[item] # maybe raises KeyError
|
| 63 |
+
|
| 64 |
+
def clear(self):
|
| 65 |
+
self._cache.clear()
|
| 66 |
+
|
| 67 |
+
def __len__(self):
|
| 68 |
+
return len(self._cache)
|
| 69 |
+
|
| 70 |
+
def __contains__(self, item):
|
| 71 |
+
try:
|
| 72 |
+
self[item]
|
| 73 |
+
return True
|
| 74 |
+
except KeyError:
|
| 75 |
+
return False
|
| 76 |
+
|
| 77 |
+
def __setitem__(self, key, value):
|
| 78 |
+
if not self.use_listings_cache:
|
| 79 |
+
return
|
| 80 |
+
if self.max_paths:
|
| 81 |
+
self._q(key)
|
| 82 |
+
self._cache[key] = value
|
| 83 |
+
if self.listings_expiry_time is not None:
|
| 84 |
+
self._times[key] = time.time()
|
| 85 |
+
|
| 86 |
+
def __delitem__(self, key):
|
| 87 |
+
del self._cache[key]
|
| 88 |
+
|
| 89 |
+
def __iter__(self):
|
| 90 |
+
entries = list(self._cache)
|
| 91 |
+
|
| 92 |
+
return (k for k in entries if k in self)
|
| 93 |
+
|
| 94 |
+
def __reduce__(self):
|
| 95 |
+
return (
|
| 96 |
+
DirCache,
|
| 97 |
+
(self.use_listings_cache, self.listings_expiry_time, self.max_paths),
|
| 98 |
+
)
|
micromamba_root/envs/hf_sync/Lib/site-packages/fsspec/exceptions.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
fsspec user-defined exception classes
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import asyncio
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class BlocksizeMismatchError(ValueError):
|
| 9 |
+
"""
|
| 10 |
+
Raised when a cached file is opened with a different blocksize than it was
|
| 11 |
+
written with
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class FSTimeoutError(asyncio.TimeoutError):
|
| 16 |
+
"""
|
| 17 |
+
Raised when a fsspec function timed out occurs
|
| 18 |
+
"""
|
micromamba_root/envs/hf_sync/Lib/site-packages/fsspec/fuse.py
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import logging
|
| 3 |
+
import os
|
| 4 |
+
import stat
|
| 5 |
+
import threading
|
| 6 |
+
import time
|
| 7 |
+
from errno import EIO, ENOENT
|
| 8 |
+
|
| 9 |
+
from fuse import FUSE, FuseOSError, LoggingMixIn, Operations
|
| 10 |
+
|
| 11 |
+
from fsspec import __version__
|
| 12 |
+
from fsspec.core import url_to_fs
|
| 13 |
+
|
| 14 |
+
logger = logging.getLogger("fsspec.fuse")
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class FUSEr(Operations):
|
| 18 |
+
def __init__(self, fs, path, ready_file=False):
|
| 19 |
+
self.fs = fs
|
| 20 |
+
self.cache = {}
|
| 21 |
+
self.root = path.rstrip("/") + "/"
|
| 22 |
+
self.counter = 0
|
| 23 |
+
logger.info("Starting FUSE at %s", path)
|
| 24 |
+
self._ready_file = ready_file
|
| 25 |
+
|
| 26 |
+
def getattr(self, path, fh=None):
|
| 27 |
+
logger.debug("getattr %s", path)
|
| 28 |
+
if self._ready_file and path in ["/.fuse_ready", ".fuse_ready"]:
|
| 29 |
+
return {"type": "file", "st_size": 5}
|
| 30 |
+
|
| 31 |
+
path = "".join([self.root, path.lstrip("/")]).rstrip("/")
|
| 32 |
+
try:
|
| 33 |
+
info = self.fs.info(path)
|
| 34 |
+
except FileNotFoundError as exc:
|
| 35 |
+
raise FuseOSError(ENOENT) from exc
|
| 36 |
+
|
| 37 |
+
data = {"st_uid": info.get("uid", 1000), "st_gid": info.get("gid", 1000)}
|
| 38 |
+
perm = info.get("mode", 0o777)
|
| 39 |
+
|
| 40 |
+
if info["type"] != "file":
|
| 41 |
+
data["st_mode"] = stat.S_IFDIR | perm
|
| 42 |
+
data["st_size"] = 0
|
| 43 |
+
data["st_blksize"] = 0
|
| 44 |
+
else:
|
| 45 |
+
data["st_mode"] = stat.S_IFREG | perm
|
| 46 |
+
data["st_size"] = info["size"]
|
| 47 |
+
data["st_blksize"] = 5 * 2**20
|
| 48 |
+
data["st_nlink"] = 1
|
| 49 |
+
data["st_atime"] = info["atime"] if "atime" in info else time.time()
|
| 50 |
+
data["st_ctime"] = info["ctime"] if "ctime" in info else time.time()
|
| 51 |
+
data["st_mtime"] = info["mtime"] if "mtime" in info else time.time()
|
| 52 |
+
return data
|
| 53 |
+
|
| 54 |
+
def readdir(self, path, fh):
|
| 55 |
+
logger.debug("readdir %s", path)
|
| 56 |
+
path = "".join([self.root, path.lstrip("/")])
|
| 57 |
+
files = self.fs.ls(path, False)
|
| 58 |
+
files = [os.path.basename(f.rstrip("/")) for f in files]
|
| 59 |
+
return [".", ".."] + files
|
| 60 |
+
|
| 61 |
+
def mkdir(self, path, mode):
|
| 62 |
+
path = "".join([self.root, path.lstrip("/")])
|
| 63 |
+
self.fs.mkdir(path)
|
| 64 |
+
return 0
|
| 65 |
+
|
| 66 |
+
def rmdir(self, path):
|
| 67 |
+
path = "".join([self.root, path.lstrip("/")])
|
| 68 |
+
self.fs.rmdir(path)
|
| 69 |
+
return 0
|
| 70 |
+
|
| 71 |
+
def read(self, path, size, offset, fh):
|
| 72 |
+
logger.debug("read %s", (path, size, offset))
|
| 73 |
+
if self._ready_file and path in ["/.fuse_ready", ".fuse_ready"]:
|
| 74 |
+
# status indicator
|
| 75 |
+
return b"ready"
|
| 76 |
+
|
| 77 |
+
f = self.cache[fh]
|
| 78 |
+
f.seek(offset)
|
| 79 |
+
out = f.read(size)
|
| 80 |
+
return out
|
| 81 |
+
|
| 82 |
+
def write(self, path, data, offset, fh):
|
| 83 |
+
logger.debug("write %s", (path, offset))
|
| 84 |
+
f = self.cache[fh]
|
| 85 |
+
f.seek(offset)
|
| 86 |
+
f.write(data)
|
| 87 |
+
return len(data)
|
| 88 |
+
|
| 89 |
+
def create(self, path, flags, fi=None):
|
| 90 |
+
logger.debug("create %s", (path, flags))
|
| 91 |
+
fn = "".join([self.root, path.lstrip("/")])
|
| 92 |
+
self.fs.touch(fn) # OS will want to get attributes immediately
|
| 93 |
+
f = self.fs.open(fn, "wb")
|
| 94 |
+
self.cache[self.counter] = f
|
| 95 |
+
self.counter += 1
|
| 96 |
+
return self.counter - 1
|
| 97 |
+
|
| 98 |
+
def open(self, path, flags):
|
| 99 |
+
logger.debug("open %s", (path, flags))
|
| 100 |
+
fn = "".join([self.root, path.lstrip("/")])
|
| 101 |
+
if flags % 2 == 0:
|
| 102 |
+
# read
|
| 103 |
+
mode = "rb"
|
| 104 |
+
else:
|
| 105 |
+
# write/create
|
| 106 |
+
mode = "wb"
|
| 107 |
+
self.cache[self.counter] = self.fs.open(fn, mode)
|
| 108 |
+
self.counter += 1
|
| 109 |
+
return self.counter - 1
|
| 110 |
+
|
| 111 |
+
def truncate(self, path, length, fh=None):
|
| 112 |
+
fn = "".join([self.root, path.lstrip("/")])
|
| 113 |
+
if length != 0:
|
| 114 |
+
raise NotImplementedError
|
| 115 |
+
# maybe should be no-op since open with write sets size to zero anyway
|
| 116 |
+
self.fs.touch(fn)
|
| 117 |
+
|
| 118 |
+
def unlink(self, path):
|
| 119 |
+
fn = "".join([self.root, path.lstrip("/")])
|
| 120 |
+
try:
|
| 121 |
+
self.fs.rm(fn, False)
|
| 122 |
+
except (OSError, FileNotFoundError) as exc:
|
| 123 |
+
raise FuseOSError(EIO) from exc
|
| 124 |
+
|
| 125 |
+
def release(self, path, fh):
|
| 126 |
+
try:
|
| 127 |
+
if fh in self.cache:
|
| 128 |
+
f = self.cache[fh]
|
| 129 |
+
f.close()
|
| 130 |
+
self.cache.pop(fh)
|
| 131 |
+
except Exception as e:
|
| 132 |
+
print(e)
|
| 133 |
+
return 0
|
| 134 |
+
|
| 135 |
+
def chmod(self, path, mode):
|
| 136 |
+
if hasattr(self.fs, "chmod"):
|
| 137 |
+
path = "".join([self.root, path.lstrip("/")])
|
| 138 |
+
return self.fs.chmod(path, mode)
|
| 139 |
+
raise NotImplementedError
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def run(
|
| 143 |
+
fs,
|
| 144 |
+
path,
|
| 145 |
+
mount_point,
|
| 146 |
+
foreground=True,
|
| 147 |
+
threads=False,
|
| 148 |
+
ready_file=False,
|
| 149 |
+
ops_class=FUSEr,
|
| 150 |
+
):
|
| 151 |
+
"""Mount stuff in a local directory
|
| 152 |
+
|
| 153 |
+
This uses fusepy to make it appear as if a given path on an fsspec
|
| 154 |
+
instance is in fact resident within the local file-system.
|
| 155 |
+
|
| 156 |
+
This requires that fusepy by installed, and that FUSE be available on
|
| 157 |
+
the system (typically requiring a package to be installed with
|
| 158 |
+
apt, yum, brew, etc.).
|
| 159 |
+
|
| 160 |
+
Parameters
|
| 161 |
+
----------
|
| 162 |
+
fs: file-system instance
|
| 163 |
+
From one of the compatible implementations
|
| 164 |
+
path: str
|
| 165 |
+
Location on that file-system to regard as the root directory to
|
| 166 |
+
mount. Note that you typically should include the terminating "/"
|
| 167 |
+
character.
|
| 168 |
+
mount_point: str
|
| 169 |
+
An empty directory on the local file-system where the contents of
|
| 170 |
+
the remote path will appear.
|
| 171 |
+
foreground: bool
|
| 172 |
+
Whether or not calling this function will block. Operation will
|
| 173 |
+
typically be more stable if True.
|
| 174 |
+
threads: bool
|
| 175 |
+
Whether or not to create threads when responding to file operations
|
| 176 |
+
within the mounter directory. Operation will typically be more
|
| 177 |
+
stable if False.
|
| 178 |
+
ready_file: bool
|
| 179 |
+
Whether the FUSE process is ready. The ``.fuse_ready`` file will
|
| 180 |
+
exist in the ``mount_point`` directory if True. Debugging purpose.
|
| 181 |
+
ops_class: FUSEr or Subclass of FUSEr
|
| 182 |
+
To override the default behavior of FUSEr. For Example, logging
|
| 183 |
+
to file.
|
| 184 |
+
|
| 185 |
+
"""
|
| 186 |
+
func = lambda: FUSE(
|
| 187 |
+
ops_class(fs, path, ready_file=ready_file),
|
| 188 |
+
mount_point,
|
| 189 |
+
nothreads=not threads,
|
| 190 |
+
foreground=foreground,
|
| 191 |
+
)
|
| 192 |
+
if not foreground:
|
| 193 |
+
th = threading.Thread(target=func)
|
| 194 |
+
th.daemon = True
|
| 195 |
+
th.start()
|
| 196 |
+
return th
|
| 197 |
+
else: # pragma: no cover
|
| 198 |
+
try:
|
| 199 |
+
func()
|
| 200 |
+
except KeyboardInterrupt:
|
| 201 |
+
pass
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def main(args):
|
| 205 |
+
"""Mount filesystem from chained URL to MOUNT_POINT.
|
| 206 |
+
|
| 207 |
+
Examples:
|
| 208 |
+
|
| 209 |
+
python3 -m fsspec.fuse memory /usr/share /tmp/mem
|
| 210 |
+
|
| 211 |
+
python3 -m fsspec.fuse local /tmp/source /tmp/local \\
|
| 212 |
+
-l /tmp/fsspecfuse.log
|
| 213 |
+
|
| 214 |
+
You can also mount chained-URLs and use special settings:
|
| 215 |
+
|
| 216 |
+
python3 -m fsspec.fuse 'filecache::zip::file://data.zip' \\
|
| 217 |
+
/ /tmp/zip \\
|
| 218 |
+
-o 'filecache-cache_storage=/tmp/simplecache'
|
| 219 |
+
|
| 220 |
+
You can specify the type of the setting by using `[int]` or `[bool]`,
|
| 221 |
+
(`true`, `yes`, `1` represents the Boolean value `True`):
|
| 222 |
+
|
| 223 |
+
python3 -m fsspec.fuse 'simplecache::ftp://ftp1.at.proftpd.org' \\
|
| 224 |
+
/historic/packages/RPMS /tmp/ftp \\
|
| 225 |
+
-o 'simplecache-cache_storage=/tmp/simplecache' \\
|
| 226 |
+
-o 'simplecache-check_files=false[bool]' \\
|
| 227 |
+
-o 'ftp-listings_expiry_time=60[int]' \\
|
| 228 |
+
-o 'ftp-username=anonymous' \\
|
| 229 |
+
-o 'ftp-password=xieyanbo'
|
| 230 |
+
"""
|
| 231 |
+
|
| 232 |
+
class RawDescriptionArgumentParser(argparse.ArgumentParser):
|
| 233 |
+
def format_help(self):
|
| 234 |
+
usage = super().format_help()
|
| 235 |
+
parts = usage.split("\n\n")
|
| 236 |
+
parts[1] = self.description.rstrip()
|
| 237 |
+
return "\n\n".join(parts)
|
| 238 |
+
|
| 239 |
+
parser = RawDescriptionArgumentParser(prog="fsspec.fuse", description=main.__doc__)
|
| 240 |
+
parser.add_argument("--version", action="version", version=__version__)
|
| 241 |
+
parser.add_argument("url", type=str, help="fs url")
|
| 242 |
+
parser.add_argument("source_path", type=str, help="source directory in fs")
|
| 243 |
+
parser.add_argument("mount_point", type=str, help="local directory")
|
| 244 |
+
parser.add_argument(
|
| 245 |
+
"-o",
|
| 246 |
+
"--option",
|
| 247 |
+
action="append",
|
| 248 |
+
help="Any options of protocol included in the chained URL",
|
| 249 |
+
)
|
| 250 |
+
parser.add_argument(
|
| 251 |
+
"-l", "--log-file", type=str, help="Logging FUSE debug info (Default: '')"
|
| 252 |
+
)
|
| 253 |
+
parser.add_argument(
|
| 254 |
+
"-f",
|
| 255 |
+
"--foreground",
|
| 256 |
+
action="store_false",
|
| 257 |
+
help="Running in foreground or not (Default: False)",
|
| 258 |
+
)
|
| 259 |
+
parser.add_argument(
|
| 260 |
+
"-t",
|
| 261 |
+
"--threads",
|
| 262 |
+
action="store_false",
|
| 263 |
+
help="Running with threads support (Default: False)",
|
| 264 |
+
)
|
| 265 |
+
parser.add_argument(
|
| 266 |
+
"-r",
|
| 267 |
+
"--ready-file",
|
| 268 |
+
action="store_false",
|
| 269 |
+
help="The `.fuse_ready` file will exist after FUSE is ready. "
|
| 270 |
+
"(Debugging purpose, Default: False)",
|
| 271 |
+
)
|
| 272 |
+
args = parser.parse_args(args)
|
| 273 |
+
|
| 274 |
+
kwargs = {}
|
| 275 |
+
for item in args.option or []:
|
| 276 |
+
key, sep, value = item.partition("=")
|
| 277 |
+
if not sep:
|
| 278 |
+
parser.error(message=f"Wrong option: {item!r}")
|
| 279 |
+
val = value.lower()
|
| 280 |
+
if val.endswith("[int]"):
|
| 281 |
+
value = int(value[: -len("[int]")])
|
| 282 |
+
elif val.endswith("[bool]"):
|
| 283 |
+
value = val[: -len("[bool]")] in ["1", "yes", "true"]
|
| 284 |
+
|
| 285 |
+
if "-" in key:
|
| 286 |
+
fs_name, setting_name = key.split("-", 1)
|
| 287 |
+
if fs_name in kwargs:
|
| 288 |
+
kwargs[fs_name][setting_name] = value
|
| 289 |
+
else:
|
| 290 |
+
kwargs[fs_name] = {setting_name: value}
|
| 291 |
+
else:
|
| 292 |
+
kwargs[key] = value
|
| 293 |
+
|
| 294 |
+
if args.log_file:
|
| 295 |
+
logging.basicConfig(
|
| 296 |
+
level=logging.DEBUG,
|
| 297 |
+
filename=args.log_file,
|
| 298 |
+
format="%(asctime)s %(message)s",
|
| 299 |
+
)
|
| 300 |
+
|
| 301 |
+
class LoggingFUSEr(FUSEr, LoggingMixIn):
|
| 302 |
+
pass
|
| 303 |
+
|
| 304 |
+
fuser = LoggingFUSEr
|
| 305 |
+
else:
|
| 306 |
+
fuser = FUSEr
|
| 307 |
+
|
| 308 |
+
fs, url_path = url_to_fs(args.url, **kwargs)
|
| 309 |
+
logger.debug("Mounting %s to %s", url_path, str(args.mount_point))
|
| 310 |
+
run(
|
| 311 |
+
fs,
|
| 312 |
+
args.source_path,
|
| 313 |
+
args.mount_point,
|
| 314 |
+
foreground=args.foreground,
|
| 315 |
+
threads=args.threads,
|
| 316 |
+
ready_file=args.ready_file,
|
| 317 |
+
ops_class=fuser,
|
| 318 |
+
)
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
if __name__ == "__main__":
|
| 322 |
+
import sys
|
| 323 |
+
|
| 324 |
+
main(sys.argv[1:])
|
micromamba_root/envs/hf_sync/Lib/site-packages/fsspec/generic.py
ADDED
|
@@ -0,0 +1,396 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import inspect
|
| 4 |
+
import logging
|
| 5 |
+
import os
|
| 6 |
+
import shutil
|
| 7 |
+
import uuid
|
| 8 |
+
|
| 9 |
+
from .asyn import AsyncFileSystem, _run_coros_in_chunks, sync_wrapper
|
| 10 |
+
from .callbacks import DEFAULT_CALLBACK
|
| 11 |
+
from .core import filesystem, get_filesystem_class, split_protocol, url_to_fs
|
| 12 |
+
|
| 13 |
+
_generic_fs = {}
|
| 14 |
+
logger = logging.getLogger("fsspec.generic")
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def set_generic_fs(protocol, **storage_options):
|
| 18 |
+
"""Populate the dict used for method=="generic" lookups"""
|
| 19 |
+
_generic_fs[protocol] = filesystem(protocol, **storage_options)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _resolve_fs(url, method, protocol=None, storage_options=None):
|
| 23 |
+
"""Pick instance of backend FS"""
|
| 24 |
+
url = url[0] if isinstance(url, (list, tuple)) else url
|
| 25 |
+
protocol = protocol or split_protocol(url)[0]
|
| 26 |
+
storage_options = storage_options or {}
|
| 27 |
+
if method == "default":
|
| 28 |
+
return filesystem(protocol)
|
| 29 |
+
if method == "generic":
|
| 30 |
+
return _generic_fs[protocol]
|
| 31 |
+
if method == "current":
|
| 32 |
+
cls = get_filesystem_class(protocol)
|
| 33 |
+
return cls.current()
|
| 34 |
+
if method == "options":
|
| 35 |
+
fs, _ = url_to_fs(url, **storage_options.get(protocol, {}))
|
| 36 |
+
return fs
|
| 37 |
+
raise ValueError(f"Unknown FS resolution method: {method}")
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def rsync(
|
| 41 |
+
source,
|
| 42 |
+
destination,
|
| 43 |
+
delete_missing=False,
|
| 44 |
+
source_field="size",
|
| 45 |
+
dest_field="size",
|
| 46 |
+
update_cond="different",
|
| 47 |
+
inst_kwargs=None,
|
| 48 |
+
fs=None,
|
| 49 |
+
**kwargs,
|
| 50 |
+
):
|
| 51 |
+
"""Sync files between two directory trees
|
| 52 |
+
|
| 53 |
+
(experimental)
|
| 54 |
+
|
| 55 |
+
Parameters
|
| 56 |
+
----------
|
| 57 |
+
source: str
|
| 58 |
+
Root of the directory tree to take files from. This must be a directory, but
|
| 59 |
+
do not include any terminating "/" character
|
| 60 |
+
destination: str
|
| 61 |
+
Root path to copy into. The contents of this location should be
|
| 62 |
+
identical to the contents of ``source`` when done. This will be made a
|
| 63 |
+
directory, and the terminal "/" should not be included.
|
| 64 |
+
delete_missing: bool
|
| 65 |
+
If there are paths in the destination that don't exist in the
|
| 66 |
+
source and this is True, delete them. Otherwise, leave them alone.
|
| 67 |
+
source_field: str | callable
|
| 68 |
+
If ``update_field`` is "different", this is the key in the info
|
| 69 |
+
of source files to consider for difference. Maybe a function of the
|
| 70 |
+
info dict.
|
| 71 |
+
dest_field: str | callable
|
| 72 |
+
If ``update_field`` is "different", this is the key in the info
|
| 73 |
+
of destination files to consider for difference. May be a function of
|
| 74 |
+
the info dict.
|
| 75 |
+
update_cond: "different"|"always"|"never"
|
| 76 |
+
If "always", every file is copied, regardless of whether it exists in
|
| 77 |
+
the destination. If "never", files that exist in the destination are
|
| 78 |
+
not copied again. If "different" (default), only copy if the info
|
| 79 |
+
fields given by ``source_field`` and ``dest_field`` (usually "size")
|
| 80 |
+
are different. Other comparisons may be added in the future.
|
| 81 |
+
inst_kwargs: dict|None
|
| 82 |
+
If ``fs`` is None, use this set of keyword arguments to make a
|
| 83 |
+
GenericFileSystem instance
|
| 84 |
+
fs: GenericFileSystem|None
|
| 85 |
+
Instance to use if explicitly given. The instance defines how to
|
| 86 |
+
to make downstream file system instances from paths.
|
| 87 |
+
|
| 88 |
+
Returns
|
| 89 |
+
-------
|
| 90 |
+
dict of the copy operations that were performed, {source: destination}
|
| 91 |
+
"""
|
| 92 |
+
fs = fs or GenericFileSystem(**(inst_kwargs or {}))
|
| 93 |
+
source = fs._strip_protocol(source)
|
| 94 |
+
destination = fs._strip_protocol(destination)
|
| 95 |
+
allfiles = fs.find(source, withdirs=True, detail=True)
|
| 96 |
+
if not fs.isdir(source):
|
| 97 |
+
raise ValueError("Can only rsync on a directory")
|
| 98 |
+
otherfiles = fs.find(destination, withdirs=True, detail=True)
|
| 99 |
+
dirs = [
|
| 100 |
+
a
|
| 101 |
+
for a, v in allfiles.items()
|
| 102 |
+
if v["type"] == "directory" and a.replace(source, destination) not in otherfiles
|
| 103 |
+
]
|
| 104 |
+
logger.debug(f"{len(dirs)} directories to create")
|
| 105 |
+
if dirs:
|
| 106 |
+
fs.make_many_dirs(
|
| 107 |
+
[dirn.replace(source, destination) for dirn in dirs], exist_ok=True
|
| 108 |
+
)
|
| 109 |
+
allfiles = {a: v for a, v in allfiles.items() if v["type"] == "file"}
|
| 110 |
+
logger.debug(f"{len(allfiles)} files to consider for copy")
|
| 111 |
+
to_delete = [
|
| 112 |
+
o
|
| 113 |
+
for o, v in otherfiles.items()
|
| 114 |
+
if o.replace(destination, source) not in allfiles and v["type"] == "file"
|
| 115 |
+
]
|
| 116 |
+
for k, v in allfiles.copy().items():
|
| 117 |
+
otherfile = k.replace(source, destination)
|
| 118 |
+
if otherfile in otherfiles:
|
| 119 |
+
if update_cond == "always":
|
| 120 |
+
allfiles[k] = otherfile
|
| 121 |
+
elif update_cond == "never":
|
| 122 |
+
allfiles.pop(k)
|
| 123 |
+
elif update_cond == "different":
|
| 124 |
+
inf1 = source_field(v) if callable(source_field) else v[source_field]
|
| 125 |
+
v2 = otherfiles[otherfile]
|
| 126 |
+
inf2 = dest_field(v2) if callable(dest_field) else v2[dest_field]
|
| 127 |
+
if inf1 != inf2:
|
| 128 |
+
# details mismatch, make copy
|
| 129 |
+
allfiles[k] = otherfile
|
| 130 |
+
else:
|
| 131 |
+
# details match, don't copy
|
| 132 |
+
allfiles.pop(k)
|
| 133 |
+
else:
|
| 134 |
+
# file not in target yet
|
| 135 |
+
allfiles[k] = otherfile
|
| 136 |
+
logger.debug(f"{len(allfiles)} files to copy")
|
| 137 |
+
if allfiles:
|
| 138 |
+
source_files, target_files = zip(*allfiles.items())
|
| 139 |
+
fs.cp(source_files, target_files, **kwargs)
|
| 140 |
+
logger.debug(f"{len(to_delete)} files to delete")
|
| 141 |
+
if delete_missing and to_delete:
|
| 142 |
+
fs.rm(to_delete)
|
| 143 |
+
return allfiles
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
class GenericFileSystem(AsyncFileSystem):
|
| 147 |
+
"""Wrapper over all other FS types
|
| 148 |
+
|
| 149 |
+
<experimental!>
|
| 150 |
+
|
| 151 |
+
This implementation is a single unified interface to be able to run FS operations
|
| 152 |
+
over generic URLs, and dispatch to the specific implementations using the URL
|
| 153 |
+
protocol prefix.
|
| 154 |
+
|
| 155 |
+
Note: instances of this FS are always async, even if you never use it with any async
|
| 156 |
+
backend.
|
| 157 |
+
"""
|
| 158 |
+
|
| 159 |
+
protocol = "generic" # there is no real reason to ever use a protocol with this FS
|
| 160 |
+
|
| 161 |
+
def __init__(self, default_method="default", storage_options=None, **kwargs):
|
| 162 |
+
"""
|
| 163 |
+
|
| 164 |
+
Parameters
|
| 165 |
+
----------
|
| 166 |
+
default_method: str (optional)
|
| 167 |
+
Defines how to configure backend FS instances. Options are:
|
| 168 |
+
- "default": instantiate like FSClass(), with no
|
| 169 |
+
extra arguments; this is the default instance of that FS, and can be
|
| 170 |
+
configured via the config system
|
| 171 |
+
- "generic": takes instances from the `_generic_fs` dict in this module,
|
| 172 |
+
which you must populate before use. Keys are by protocol
|
| 173 |
+
- "options": expects storage_options, a dict mapping protocol to
|
| 174 |
+
kwargs to use when constructing the filesystem
|
| 175 |
+
- "current": takes the most recently instantiated version of each FS
|
| 176 |
+
"""
|
| 177 |
+
self.method = default_method
|
| 178 |
+
self.st_opts = storage_options
|
| 179 |
+
super().__init__(**kwargs)
|
| 180 |
+
|
| 181 |
+
def _parent(self, path):
|
| 182 |
+
fs = _resolve_fs(path, self.method, storage_options=self.st_opts)
|
| 183 |
+
return fs.unstrip_protocol(fs._parent(path))
|
| 184 |
+
|
| 185 |
+
def _strip_protocol(self, path):
|
| 186 |
+
# normalization only
|
| 187 |
+
fs = _resolve_fs(path, self.method, storage_options=self.st_opts)
|
| 188 |
+
return fs.unstrip_protocol(fs._strip_protocol(path))
|
| 189 |
+
|
| 190 |
+
async def _find(self, path, maxdepth=None, withdirs=False, detail=False, **kwargs):
|
| 191 |
+
fs = _resolve_fs(path, self.method, storage_options=self.st_opts)
|
| 192 |
+
if fs.async_impl:
|
| 193 |
+
out = await fs._find(
|
| 194 |
+
path, maxdepth=maxdepth, withdirs=withdirs, detail=True, **kwargs
|
| 195 |
+
)
|
| 196 |
+
else:
|
| 197 |
+
out = fs.find(
|
| 198 |
+
path, maxdepth=maxdepth, withdirs=withdirs, detail=True, **kwargs
|
| 199 |
+
)
|
| 200 |
+
result = {}
|
| 201 |
+
for k, v in out.items():
|
| 202 |
+
v = v.copy() # don't corrupt target FS dircache
|
| 203 |
+
name = fs.unstrip_protocol(k)
|
| 204 |
+
v["name"] = name
|
| 205 |
+
result[name] = v
|
| 206 |
+
if detail:
|
| 207 |
+
return result
|
| 208 |
+
return list(result)
|
| 209 |
+
|
| 210 |
+
async def _info(self, url, **kwargs):
|
| 211 |
+
fs = _resolve_fs(url, self.method)
|
| 212 |
+
if fs.async_impl:
|
| 213 |
+
out = await fs._info(url, **kwargs)
|
| 214 |
+
else:
|
| 215 |
+
out = fs.info(url, **kwargs)
|
| 216 |
+
out = out.copy() # don't edit originals
|
| 217 |
+
out["name"] = fs.unstrip_protocol(out["name"])
|
| 218 |
+
return out
|
| 219 |
+
|
| 220 |
+
async def _ls(
|
| 221 |
+
self,
|
| 222 |
+
url,
|
| 223 |
+
detail=True,
|
| 224 |
+
**kwargs,
|
| 225 |
+
):
|
| 226 |
+
fs = _resolve_fs(url, self.method)
|
| 227 |
+
if fs.async_impl:
|
| 228 |
+
out = await fs._ls(url, detail=True, **kwargs)
|
| 229 |
+
else:
|
| 230 |
+
out = fs.ls(url, detail=True, **kwargs)
|
| 231 |
+
out = [o.copy() for o in out] # don't edit originals
|
| 232 |
+
for o in out:
|
| 233 |
+
o["name"] = fs.unstrip_protocol(o["name"])
|
| 234 |
+
if detail:
|
| 235 |
+
return out
|
| 236 |
+
else:
|
| 237 |
+
return [o["name"] for o in out]
|
| 238 |
+
|
| 239 |
+
async def _cat_file(
|
| 240 |
+
self,
|
| 241 |
+
url,
|
| 242 |
+
**kwargs,
|
| 243 |
+
):
|
| 244 |
+
fs = _resolve_fs(url, self.method)
|
| 245 |
+
if fs.async_impl:
|
| 246 |
+
return await fs._cat_file(url, **kwargs)
|
| 247 |
+
else:
|
| 248 |
+
return fs.cat_file(url, **kwargs)
|
| 249 |
+
|
| 250 |
+
async def _pipe_file(
|
| 251 |
+
self,
|
| 252 |
+
path,
|
| 253 |
+
value,
|
| 254 |
+
**kwargs,
|
| 255 |
+
):
|
| 256 |
+
fs = _resolve_fs(path, self.method, storage_options=self.st_opts)
|
| 257 |
+
if fs.async_impl:
|
| 258 |
+
return await fs._pipe_file(path, value, **kwargs)
|
| 259 |
+
else:
|
| 260 |
+
return fs.pipe_file(path, value, **kwargs)
|
| 261 |
+
|
| 262 |
+
async def _rm(self, url, **kwargs):
|
| 263 |
+
urls = url
|
| 264 |
+
if isinstance(urls, str):
|
| 265 |
+
urls = [urls]
|
| 266 |
+
fs = _resolve_fs(urls[0], self.method)
|
| 267 |
+
if fs.async_impl:
|
| 268 |
+
await fs._rm(urls, **kwargs)
|
| 269 |
+
else:
|
| 270 |
+
fs.rm(url, **kwargs)
|
| 271 |
+
|
| 272 |
+
async def _makedirs(self, path, exist_ok=False):
|
| 273 |
+
logger.debug("Make dir %s", path)
|
| 274 |
+
fs = _resolve_fs(path, self.method, storage_options=self.st_opts)
|
| 275 |
+
if fs.async_impl:
|
| 276 |
+
await fs._makedirs(path, exist_ok=exist_ok)
|
| 277 |
+
else:
|
| 278 |
+
fs.makedirs(path, exist_ok=exist_ok)
|
| 279 |
+
|
| 280 |
+
def rsync(self, source, destination, **kwargs):
|
| 281 |
+
"""Sync files between two directory trees
|
| 282 |
+
|
| 283 |
+
See `func:rsync` for more details.
|
| 284 |
+
"""
|
| 285 |
+
rsync(source, destination, fs=self, **kwargs)
|
| 286 |
+
|
| 287 |
+
async def _cp_file(
|
| 288 |
+
self,
|
| 289 |
+
url,
|
| 290 |
+
url2,
|
| 291 |
+
blocksize=2**20,
|
| 292 |
+
callback=DEFAULT_CALLBACK,
|
| 293 |
+
tempdir: str | None = None,
|
| 294 |
+
**kwargs,
|
| 295 |
+
):
|
| 296 |
+
fs = _resolve_fs(url, self.method)
|
| 297 |
+
fs2 = _resolve_fs(url2, self.method)
|
| 298 |
+
if fs is fs2:
|
| 299 |
+
# pure remote
|
| 300 |
+
if fs.async_impl:
|
| 301 |
+
return await fs._copy(url, url2, **kwargs)
|
| 302 |
+
else:
|
| 303 |
+
return fs.copy(url, url2, **kwargs)
|
| 304 |
+
await copy_file_op(fs, [url], fs2, [url2], tempdir, 1, on_error="raise")
|
| 305 |
+
|
| 306 |
+
async def _make_many_dirs(self, urls, exist_ok=True):
|
| 307 |
+
fs = _resolve_fs(urls[0], self.method)
|
| 308 |
+
if fs.async_impl:
|
| 309 |
+
coros = [fs._makedirs(u, exist_ok=exist_ok) for u in urls]
|
| 310 |
+
await _run_coros_in_chunks(coros)
|
| 311 |
+
else:
|
| 312 |
+
for u in urls:
|
| 313 |
+
fs.makedirs(u, exist_ok=exist_ok)
|
| 314 |
+
|
| 315 |
+
make_many_dirs = sync_wrapper(_make_many_dirs)
|
| 316 |
+
|
| 317 |
+
async def _copy(
|
| 318 |
+
self,
|
| 319 |
+
path1: list[str],
|
| 320 |
+
path2: list[str],
|
| 321 |
+
recursive: bool = False,
|
| 322 |
+
on_error: str = "ignore",
|
| 323 |
+
maxdepth: int | None = None,
|
| 324 |
+
batch_size: int | None = None,
|
| 325 |
+
tempdir: str | None = None,
|
| 326 |
+
**kwargs,
|
| 327 |
+
):
|
| 328 |
+
# TODO: special case for one FS being local, which can use get/put
|
| 329 |
+
# TODO: special case for one being memFS, which can use cat/pipe
|
| 330 |
+
if recursive:
|
| 331 |
+
raise NotImplementedError("Please use fsspec.generic.rsync")
|
| 332 |
+
path1 = [path1] if isinstance(path1, str) else path1
|
| 333 |
+
path2 = [path2] if isinstance(path2, str) else path2
|
| 334 |
+
|
| 335 |
+
fs = _resolve_fs(path1, self.method)
|
| 336 |
+
fs2 = _resolve_fs(path2, self.method)
|
| 337 |
+
|
| 338 |
+
if fs is fs2:
|
| 339 |
+
if fs.async_impl:
|
| 340 |
+
return await fs._copy(path1, path2, **kwargs)
|
| 341 |
+
else:
|
| 342 |
+
return fs.copy(path1, path2, **kwargs)
|
| 343 |
+
|
| 344 |
+
await copy_file_op(
|
| 345 |
+
fs, path1, fs2, path2, tempdir, batch_size, on_error=on_error
|
| 346 |
+
)
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
async def copy_file_op(
|
| 350 |
+
fs1, url1, fs2, url2, tempdir=None, batch_size=20, on_error="ignore"
|
| 351 |
+
):
|
| 352 |
+
import tempfile
|
| 353 |
+
|
| 354 |
+
tempdir = tempdir or tempfile.mkdtemp()
|
| 355 |
+
try:
|
| 356 |
+
coros = [
|
| 357 |
+
_copy_file_op(
|
| 358 |
+
fs1,
|
| 359 |
+
u1,
|
| 360 |
+
fs2,
|
| 361 |
+
u2,
|
| 362 |
+
os.path.join(tempdir, uuid.uuid4().hex),
|
| 363 |
+
)
|
| 364 |
+
for u1, u2 in zip(url1, url2)
|
| 365 |
+
]
|
| 366 |
+
out = await _run_coros_in_chunks(
|
| 367 |
+
coros, batch_size=batch_size, return_exceptions=True
|
| 368 |
+
)
|
| 369 |
+
finally:
|
| 370 |
+
shutil.rmtree(tempdir)
|
| 371 |
+
if on_error == "return":
|
| 372 |
+
return out
|
| 373 |
+
elif on_error == "raise":
|
| 374 |
+
for o in out:
|
| 375 |
+
if isinstance(o, Exception):
|
| 376 |
+
raise o
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
async def _copy_file_op(fs1, url1, fs2, url2, local, on_error="ignore"):
|
| 380 |
+
if fs1.async_impl:
|
| 381 |
+
await fs1._get_file(url1, local)
|
| 382 |
+
else:
|
| 383 |
+
fs1.get_file(url1, local)
|
| 384 |
+
if fs2.async_impl:
|
| 385 |
+
await fs2._put_file(local, url2)
|
| 386 |
+
else:
|
| 387 |
+
fs2.put_file(local, url2)
|
| 388 |
+
os.unlink(local)
|
| 389 |
+
logger.debug("Copy %s -> %s; done", url1, url2)
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
async def maybe_await(cor):
|
| 393 |
+
if inspect.iscoroutine(cor):
|
| 394 |
+
return await cor
|
| 395 |
+
else:
|
| 396 |
+
return cor
|
micromamba_root/envs/hf_sync/Lib/site-packages/fsspec/gui.py
ADDED
|
@@ -0,0 +1,417 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import ast
|
| 2 |
+
import contextlib
|
| 3 |
+
import logging
|
| 4 |
+
import os
|
| 5 |
+
import re
|
| 6 |
+
from collections.abc import Sequence
|
| 7 |
+
from typing import ClassVar
|
| 8 |
+
|
| 9 |
+
import panel as pn
|
| 10 |
+
|
| 11 |
+
from .core import OpenFile, get_filesystem_class, split_protocol
|
| 12 |
+
from .registry import known_implementations
|
| 13 |
+
|
| 14 |
+
pn.extension()
|
| 15 |
+
logger = logging.getLogger("fsspec.gui")
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class SigSlot:
|
| 19 |
+
"""Signal-slot mixin, for Panel event passing
|
| 20 |
+
|
| 21 |
+
Include this class in a widget manager's superclasses to be able to
|
| 22 |
+
register events and callbacks on Panel widgets managed by that class.
|
| 23 |
+
|
| 24 |
+
The method ``_register`` should be called as widgets are added, and external
|
| 25 |
+
code should call ``connect`` to associate callbacks.
|
| 26 |
+
|
| 27 |
+
By default, all signals emit a DEBUG logging statement.
|
| 28 |
+
"""
|
| 29 |
+
|
| 30 |
+
# names of signals that this class may emit each of which must be
|
| 31 |
+
# set by _register for any new instance
|
| 32 |
+
signals: ClassVar[Sequence[str]] = []
|
| 33 |
+
# names of actions that this class may respond to
|
| 34 |
+
slots: ClassVar[Sequence[str]] = []
|
| 35 |
+
|
| 36 |
+
# each of which must be a method name
|
| 37 |
+
|
| 38 |
+
def __init__(self):
|
| 39 |
+
self._ignoring_events = False
|
| 40 |
+
self._sigs = {}
|
| 41 |
+
self._map = {}
|
| 42 |
+
self._setup()
|
| 43 |
+
|
| 44 |
+
def _setup(self):
|
| 45 |
+
"""Create GUI elements and register signals"""
|
| 46 |
+
self.panel = pn.pane.PaneBase()
|
| 47 |
+
# no signals to set up in the base class
|
| 48 |
+
|
| 49 |
+
def _register(
|
| 50 |
+
self, widget, name, thing="value", log_level=logging.DEBUG, auto=False
|
| 51 |
+
):
|
| 52 |
+
"""Watch the given attribute of a widget and assign it a named event
|
| 53 |
+
|
| 54 |
+
This is normally called at the time a widget is instantiated, in the
|
| 55 |
+
class which owns it.
|
| 56 |
+
|
| 57 |
+
Parameters
|
| 58 |
+
----------
|
| 59 |
+
widget : pn.layout.Panel or None
|
| 60 |
+
Widget to watch. If None, an anonymous signal not associated with
|
| 61 |
+
any widget.
|
| 62 |
+
name : str
|
| 63 |
+
Name of this event
|
| 64 |
+
thing : str
|
| 65 |
+
Attribute of the given widget to watch
|
| 66 |
+
log_level : int
|
| 67 |
+
When the signal is triggered, a logging event of the given level
|
| 68 |
+
will be fired in the dfviz logger.
|
| 69 |
+
auto : bool
|
| 70 |
+
If True, automatically connects with a method in this class of the
|
| 71 |
+
same name.
|
| 72 |
+
"""
|
| 73 |
+
if name not in self.signals:
|
| 74 |
+
raise ValueError(f"Attempt to assign an undeclared signal: {name}")
|
| 75 |
+
self._sigs[name] = {
|
| 76 |
+
"widget": widget,
|
| 77 |
+
"callbacks": [],
|
| 78 |
+
"thing": thing,
|
| 79 |
+
"log": log_level,
|
| 80 |
+
}
|
| 81 |
+
wn = "-".join(
|
| 82 |
+
[
|
| 83 |
+
getattr(widget, "name", str(widget)) if widget is not None else "none",
|
| 84 |
+
thing,
|
| 85 |
+
]
|
| 86 |
+
)
|
| 87 |
+
self._map[wn] = name
|
| 88 |
+
if widget is not None:
|
| 89 |
+
widget.param.watch(self._signal, thing, onlychanged=True)
|
| 90 |
+
if auto and hasattr(self, name):
|
| 91 |
+
self.connect(name, getattr(self, name))
|
| 92 |
+
|
| 93 |
+
def _repr_mimebundle_(self, *args, **kwargs):
|
| 94 |
+
"""Display in a notebook or a server"""
|
| 95 |
+
try:
|
| 96 |
+
return self.panel._repr_mimebundle_(*args, **kwargs)
|
| 97 |
+
except (ValueError, AttributeError) as exc:
|
| 98 |
+
raise NotImplementedError(
|
| 99 |
+
"Panel does not seem to be set up properly"
|
| 100 |
+
) from exc
|
| 101 |
+
|
| 102 |
+
def connect(self, signal, slot):
|
| 103 |
+
"""Associate call back with given event
|
| 104 |
+
|
| 105 |
+
The callback must be a function which takes the "new" value of the
|
| 106 |
+
watched attribute as the only parameter. If the callback return False,
|
| 107 |
+
this cancels any further processing of the given event.
|
| 108 |
+
|
| 109 |
+
Alternatively, the callback can be a string, in which case it means
|
| 110 |
+
emitting the correspondingly-named event (i.e., connect to self)
|
| 111 |
+
"""
|
| 112 |
+
self._sigs[signal]["callbacks"].append(slot)
|
| 113 |
+
|
| 114 |
+
def _signal(self, event):
|
| 115 |
+
"""This is called by a an action on a widget
|
| 116 |
+
|
| 117 |
+
Within an self.ignore_events context, nothing happens.
|
| 118 |
+
|
| 119 |
+
Tests can execute this method by directly changing the values of
|
| 120 |
+
widget components.
|
| 121 |
+
"""
|
| 122 |
+
if not self._ignoring_events:
|
| 123 |
+
wn = "-".join([event.obj.name, event.name])
|
| 124 |
+
if wn in self._map and self._map[wn] in self._sigs:
|
| 125 |
+
self._emit(self._map[wn], event.new)
|
| 126 |
+
|
| 127 |
+
@contextlib.contextmanager
|
| 128 |
+
def ignore_events(self):
|
| 129 |
+
"""Temporarily turn off events processing in this instance
|
| 130 |
+
|
| 131 |
+
(does not propagate to children)
|
| 132 |
+
"""
|
| 133 |
+
self._ignoring_events = True
|
| 134 |
+
try:
|
| 135 |
+
yield
|
| 136 |
+
finally:
|
| 137 |
+
self._ignoring_events = False
|
| 138 |
+
|
| 139 |
+
def _emit(self, sig, value=None):
|
| 140 |
+
"""An event happened, call its callbacks
|
| 141 |
+
|
| 142 |
+
This method can be used in tests to simulate message passing without
|
| 143 |
+
directly changing visual elements.
|
| 144 |
+
|
| 145 |
+
Calling of callbacks will halt whenever one returns False.
|
| 146 |
+
"""
|
| 147 |
+
logger.log(self._sigs[sig]["log"], f"{sig}: {value}")
|
| 148 |
+
for callback in self._sigs[sig]["callbacks"]:
|
| 149 |
+
if isinstance(callback, str):
|
| 150 |
+
self._emit(callback)
|
| 151 |
+
else:
|
| 152 |
+
try:
|
| 153 |
+
# running callbacks should not break the interface
|
| 154 |
+
ret = callback(value)
|
| 155 |
+
if ret is False:
|
| 156 |
+
break
|
| 157 |
+
except Exception as e:
|
| 158 |
+
logger.exception(
|
| 159 |
+
"Exception (%s) while executing callback for signal: %s",
|
| 160 |
+
e,
|
| 161 |
+
sig,
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
def show(self, threads=False):
|
| 165 |
+
"""Open a new browser tab and display this instance's interface"""
|
| 166 |
+
self.panel.show(threads=threads, verbose=False)
|
| 167 |
+
return self
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
class SingleSelect(SigSlot):
|
| 171 |
+
"""A multiselect which only allows you to select one item for an event"""
|
| 172 |
+
|
| 173 |
+
signals = ["_selected", "selected"] # the first is internal
|
| 174 |
+
slots = ["set_options", "set_selection", "add", "clear", "select"]
|
| 175 |
+
|
| 176 |
+
def __init__(self, **kwargs):
|
| 177 |
+
self.kwargs = kwargs
|
| 178 |
+
super().__init__()
|
| 179 |
+
|
| 180 |
+
def _setup(self):
|
| 181 |
+
self.panel = pn.widgets.MultiSelect(**self.kwargs)
|
| 182 |
+
self._register(self.panel, "_selected", "value")
|
| 183 |
+
self._register(None, "selected")
|
| 184 |
+
self.connect("_selected", self.select_one)
|
| 185 |
+
|
| 186 |
+
def _signal(self, *args, **kwargs):
|
| 187 |
+
super()._signal(*args, **kwargs)
|
| 188 |
+
|
| 189 |
+
def select_one(self, *_):
|
| 190 |
+
with self.ignore_events():
|
| 191 |
+
val = [self.panel.value[-1]] if self.panel.value else []
|
| 192 |
+
self.panel.value = val
|
| 193 |
+
self._emit("selected", self.panel.value)
|
| 194 |
+
|
| 195 |
+
def set_options(self, options):
|
| 196 |
+
self.panel.options = options
|
| 197 |
+
|
| 198 |
+
def clear(self):
|
| 199 |
+
self.panel.options = []
|
| 200 |
+
|
| 201 |
+
@property
|
| 202 |
+
def value(self):
|
| 203 |
+
return self.panel.value
|
| 204 |
+
|
| 205 |
+
def set_selection(self, selection):
|
| 206 |
+
self.panel.value = [selection]
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
class FileSelector(SigSlot):
|
| 210 |
+
"""Panel-based graphical file selector widget
|
| 211 |
+
|
| 212 |
+
Instances of this widget are interactive and can be displayed in jupyter by having
|
| 213 |
+
them as the output of a cell, or in a separate browser tab using ``.show()``.
|
| 214 |
+
"""
|
| 215 |
+
|
| 216 |
+
signals = [
|
| 217 |
+
"protocol_changed",
|
| 218 |
+
"selection_changed",
|
| 219 |
+
"directory_entered",
|
| 220 |
+
"home_clicked",
|
| 221 |
+
"up_clicked",
|
| 222 |
+
"go_clicked",
|
| 223 |
+
"filters_changed",
|
| 224 |
+
]
|
| 225 |
+
slots = ["set_filters", "go_home"]
|
| 226 |
+
|
| 227 |
+
def __init__(self, url=None, filters=None, ignore=None, kwargs=None):
|
| 228 |
+
"""
|
| 229 |
+
|
| 230 |
+
Parameters
|
| 231 |
+
----------
|
| 232 |
+
url : str (optional)
|
| 233 |
+
Initial value of the URL to populate the dialog; should include protocol
|
| 234 |
+
filters : list(str) (optional)
|
| 235 |
+
File endings to include in the listings. If not included, all files are
|
| 236 |
+
allowed. Does not affect directories.
|
| 237 |
+
If given, the endings will appear as checkboxes in the interface
|
| 238 |
+
ignore : list(str) (optional)
|
| 239 |
+
Regex(s) of file basename patterns to ignore, e.g., "\\." for typical
|
| 240 |
+
hidden files on posix
|
| 241 |
+
kwargs : dict (optional)
|
| 242 |
+
To pass to file system instance
|
| 243 |
+
"""
|
| 244 |
+
if url:
|
| 245 |
+
self.init_protocol, url = split_protocol(url)
|
| 246 |
+
else:
|
| 247 |
+
self.init_protocol, url = "file", os.getcwd()
|
| 248 |
+
self.init_url = url
|
| 249 |
+
self.init_kwargs = (kwargs if isinstance(kwargs, str) else str(kwargs)) or "{}"
|
| 250 |
+
self.filters = filters
|
| 251 |
+
self.ignore = [re.compile(i) for i in ignore or []]
|
| 252 |
+
self._fs = None
|
| 253 |
+
super().__init__()
|
| 254 |
+
|
| 255 |
+
def _setup(self):
|
| 256 |
+
self.url = pn.widgets.TextInput(
|
| 257 |
+
name="url",
|
| 258 |
+
value=self.init_url,
|
| 259 |
+
align="end",
|
| 260 |
+
sizing_mode="stretch_width",
|
| 261 |
+
width_policy="max",
|
| 262 |
+
)
|
| 263 |
+
self.protocol = pn.widgets.Select(
|
| 264 |
+
options=sorted(known_implementations),
|
| 265 |
+
value=self.init_protocol,
|
| 266 |
+
name="protocol",
|
| 267 |
+
align="center",
|
| 268 |
+
)
|
| 269 |
+
self.kwargs = pn.widgets.TextInput(
|
| 270 |
+
name="kwargs", value=self.init_kwargs, align="center"
|
| 271 |
+
)
|
| 272 |
+
self.go = pn.widgets.Button(name="⇨", align="end", width=45)
|
| 273 |
+
self.main = SingleSelect(size=10)
|
| 274 |
+
self.home = pn.widgets.Button(name="🏠", width=40, height=30, align="end")
|
| 275 |
+
self.up = pn.widgets.Button(name="‹", width=30, height=30, align="end")
|
| 276 |
+
|
| 277 |
+
self._register(self.protocol, "protocol_changed", auto=True)
|
| 278 |
+
self._register(self.go, "go_clicked", "clicks", auto=True)
|
| 279 |
+
self._register(self.up, "up_clicked", "clicks", auto=True)
|
| 280 |
+
self._register(self.home, "home_clicked", "clicks", auto=True)
|
| 281 |
+
self._register(None, "selection_changed")
|
| 282 |
+
self.main.connect("selected", self.selection_changed)
|
| 283 |
+
self._register(None, "directory_entered")
|
| 284 |
+
self.prev_protocol = self.protocol.value
|
| 285 |
+
self.prev_kwargs = self.storage_options
|
| 286 |
+
|
| 287 |
+
self.filter_sel = pn.widgets.CheckBoxGroup(
|
| 288 |
+
value=[], options=[], inline=False, align="end", width_policy="min"
|
| 289 |
+
)
|
| 290 |
+
self._register(self.filter_sel, "filters_changed", auto=True)
|
| 291 |
+
|
| 292 |
+
self.panel = pn.Column(
|
| 293 |
+
pn.Row(self.protocol, self.kwargs),
|
| 294 |
+
pn.Row(self.home, self.up, self.url, self.go, self.filter_sel),
|
| 295 |
+
self.main.panel,
|
| 296 |
+
)
|
| 297 |
+
self.set_filters(self.filters)
|
| 298 |
+
self.go_clicked()
|
| 299 |
+
|
| 300 |
+
def set_filters(self, filters=None):
|
| 301 |
+
self.filters = filters
|
| 302 |
+
if filters:
|
| 303 |
+
self.filter_sel.options = filters
|
| 304 |
+
self.filter_sel.value = filters
|
| 305 |
+
else:
|
| 306 |
+
self.filter_sel.options = []
|
| 307 |
+
self.filter_sel.value = []
|
| 308 |
+
|
| 309 |
+
@property
|
| 310 |
+
def storage_options(self):
|
| 311 |
+
"""Value of the kwargs box as a dictionary"""
|
| 312 |
+
return ast.literal_eval(self.kwargs.value) or {}
|
| 313 |
+
|
| 314 |
+
@property
|
| 315 |
+
def fs(self):
|
| 316 |
+
"""Current filesystem instance"""
|
| 317 |
+
if self._fs is None:
|
| 318 |
+
cls = get_filesystem_class(self.protocol.value)
|
| 319 |
+
self._fs = cls(**self.storage_options)
|
| 320 |
+
return self._fs
|
| 321 |
+
|
| 322 |
+
@property
|
| 323 |
+
def urlpath(self):
|
| 324 |
+
"""URL of currently selected item"""
|
| 325 |
+
return (
|
| 326 |
+
(f"{self.protocol.value}://{self.main.value[0]}")
|
| 327 |
+
if self.main.value
|
| 328 |
+
else None
|
| 329 |
+
)
|
| 330 |
+
|
| 331 |
+
def open_file(self, mode="rb", compression=None, encoding=None):
|
| 332 |
+
"""Create OpenFile instance for the currently selected item
|
| 333 |
+
|
| 334 |
+
For example, in a notebook you might do something like
|
| 335 |
+
|
| 336 |
+
.. code-block::
|
| 337 |
+
|
| 338 |
+
[ ]: sel = FileSelector(); sel
|
| 339 |
+
|
| 340 |
+
# user selects their file
|
| 341 |
+
|
| 342 |
+
[ ]: with sel.open_file('rb') as f:
|
| 343 |
+
... out = f.read()
|
| 344 |
+
|
| 345 |
+
Parameters
|
| 346 |
+
----------
|
| 347 |
+
mode: str (optional)
|
| 348 |
+
Open mode for the file.
|
| 349 |
+
compression: str (optional)
|
| 350 |
+
The interact with the file as compressed. Set to 'infer' to guess
|
| 351 |
+
compression from the file ending
|
| 352 |
+
encoding: str (optional)
|
| 353 |
+
If using text mode, use this encoding; defaults to UTF8.
|
| 354 |
+
"""
|
| 355 |
+
if self.urlpath is None:
|
| 356 |
+
raise ValueError("No file selected")
|
| 357 |
+
return OpenFile(self.fs, self.urlpath, mode, compression, encoding)
|
| 358 |
+
|
| 359 |
+
def filters_changed(self, values):
|
| 360 |
+
self.filters = values
|
| 361 |
+
self.go_clicked()
|
| 362 |
+
|
| 363 |
+
def selection_changed(self, *_):
|
| 364 |
+
if self.urlpath is None:
|
| 365 |
+
return
|
| 366 |
+
if self.fs.isdir(self.urlpath):
|
| 367 |
+
self.url.value = self.fs._strip_protocol(self.urlpath)
|
| 368 |
+
self.go_clicked()
|
| 369 |
+
|
| 370 |
+
def go_clicked(self, *_):
|
| 371 |
+
if (
|
| 372 |
+
self.prev_protocol != self.protocol.value
|
| 373 |
+
or self.prev_kwargs != self.storage_options
|
| 374 |
+
):
|
| 375 |
+
self._fs = None # causes fs to be recreated
|
| 376 |
+
self.prev_protocol = self.protocol.value
|
| 377 |
+
self.prev_kwargs = self.storage_options
|
| 378 |
+
listing = sorted(
|
| 379 |
+
self.fs.ls(self.url.value, detail=True), key=lambda x: x["name"]
|
| 380 |
+
)
|
| 381 |
+
listing = [
|
| 382 |
+
l
|
| 383 |
+
for l in listing
|
| 384 |
+
if not any(i.match(l["name"].rsplit("/", 1)[-1]) for i in self.ignore)
|
| 385 |
+
]
|
| 386 |
+
folders = {
|
| 387 |
+
"📁 " + o["name"].rsplit("/", 1)[-1]: o["name"]
|
| 388 |
+
for o in listing
|
| 389 |
+
if o["type"] == "directory"
|
| 390 |
+
}
|
| 391 |
+
files = {
|
| 392 |
+
"📄 " + o["name"].rsplit("/", 1)[-1]: o["name"]
|
| 393 |
+
for o in listing
|
| 394 |
+
if o["type"] == "file"
|
| 395 |
+
}
|
| 396 |
+
if self.filters:
|
| 397 |
+
files = {
|
| 398 |
+
k: v
|
| 399 |
+
for k, v in files.items()
|
| 400 |
+
if any(v.endswith(ext) for ext in self.filters)
|
| 401 |
+
}
|
| 402 |
+
self.main.set_options(dict(**folders, **files))
|
| 403 |
+
|
| 404 |
+
def protocol_changed(self, *_):
|
| 405 |
+
self._fs = None
|
| 406 |
+
self.main.options = []
|
| 407 |
+
self.url.value = ""
|
| 408 |
+
|
| 409 |
+
def home_clicked(self, *_):
|
| 410 |
+
self.protocol.value = self.init_protocol
|
| 411 |
+
self.kwargs.value = self.init_kwargs
|
| 412 |
+
self.url.value = self.init_url
|
| 413 |
+
self.go_clicked()
|
| 414 |
+
|
| 415 |
+
def up_clicked(self, *_):
|
| 416 |
+
self.url.value = self.fs._parent(self.url.value)
|
| 417 |
+
self.go_clicked()
|
micromamba_root/envs/hf_sync/Lib/site-packages/fsspec/json.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
from collections.abc import Callable, Mapping, Sequence
|
| 3 |
+
from contextlib import suppress
|
| 4 |
+
from pathlib import PurePath
|
| 5 |
+
from typing import Any, ClassVar
|
| 6 |
+
|
| 7 |
+
from .registry import _import_class, get_filesystem_class
|
| 8 |
+
from .spec import AbstractFileSystem
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class FilesystemJSONEncoder(json.JSONEncoder):
|
| 12 |
+
include_password: ClassVar[bool] = True
|
| 13 |
+
|
| 14 |
+
def default(self, o: Any) -> Any:
|
| 15 |
+
if isinstance(o, AbstractFileSystem):
|
| 16 |
+
return o.to_dict(include_password=self.include_password)
|
| 17 |
+
if isinstance(o, PurePath):
|
| 18 |
+
cls = type(o)
|
| 19 |
+
return {"cls": f"{cls.__module__}.{cls.__name__}", "str": str(o)}
|
| 20 |
+
|
| 21 |
+
return super().default(o)
|
| 22 |
+
|
| 23 |
+
def make_serializable(self, obj: Any) -> Any:
|
| 24 |
+
"""
|
| 25 |
+
Recursively converts an object so that it can be JSON serialized via
|
| 26 |
+
:func:`json.dumps` and :func:`json.dump`, without actually calling
|
| 27 |
+
said functions.
|
| 28 |
+
"""
|
| 29 |
+
if isinstance(obj, (str, int, float, bool)):
|
| 30 |
+
return obj
|
| 31 |
+
if isinstance(obj, Mapping):
|
| 32 |
+
return {k: self.make_serializable(v) for k, v in obj.items()}
|
| 33 |
+
if isinstance(obj, Sequence):
|
| 34 |
+
return [self.make_serializable(v) for v in obj]
|
| 35 |
+
|
| 36 |
+
return self.default(obj)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class FilesystemJSONDecoder(json.JSONDecoder):
|
| 40 |
+
def __init__(
|
| 41 |
+
self,
|
| 42 |
+
*,
|
| 43 |
+
object_hook: Callable[[dict[str, Any]], Any] | None = None,
|
| 44 |
+
parse_float: Callable[[str], Any] | None = None,
|
| 45 |
+
parse_int: Callable[[str], Any] | None = None,
|
| 46 |
+
parse_constant: Callable[[str], Any] | None = None,
|
| 47 |
+
strict: bool = True,
|
| 48 |
+
object_pairs_hook: Callable[[list[tuple[str, Any]]], Any] | None = None,
|
| 49 |
+
) -> None:
|
| 50 |
+
self.original_object_hook = object_hook
|
| 51 |
+
|
| 52 |
+
super().__init__(
|
| 53 |
+
object_hook=self.custom_object_hook,
|
| 54 |
+
parse_float=parse_float,
|
| 55 |
+
parse_int=parse_int,
|
| 56 |
+
parse_constant=parse_constant,
|
| 57 |
+
strict=strict,
|
| 58 |
+
object_pairs_hook=object_pairs_hook,
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
@classmethod
|
| 62 |
+
def try_resolve_path_cls(cls, dct: dict[str, Any]):
|
| 63 |
+
with suppress(Exception):
|
| 64 |
+
fqp = dct["cls"]
|
| 65 |
+
|
| 66 |
+
path_cls = _import_class(fqp)
|
| 67 |
+
|
| 68 |
+
if issubclass(path_cls, PurePath):
|
| 69 |
+
return path_cls
|
| 70 |
+
|
| 71 |
+
return None
|
| 72 |
+
|
| 73 |
+
@classmethod
|
| 74 |
+
def try_resolve_fs_cls(cls, dct: dict[str, Any]):
|
| 75 |
+
with suppress(Exception):
|
| 76 |
+
if "cls" in dct:
|
| 77 |
+
try:
|
| 78 |
+
fs_cls = _import_class(dct["cls"])
|
| 79 |
+
if issubclass(fs_cls, AbstractFileSystem):
|
| 80 |
+
return fs_cls
|
| 81 |
+
except Exception:
|
| 82 |
+
if "protocol" in dct: # Fallback if cls cannot be imported
|
| 83 |
+
return get_filesystem_class(dct["protocol"])
|
| 84 |
+
|
| 85 |
+
raise
|
| 86 |
+
|
| 87 |
+
return None
|
| 88 |
+
|
| 89 |
+
def custom_object_hook(self, dct: dict[str, Any]):
|
| 90 |
+
if "cls" in dct:
|
| 91 |
+
if (obj_cls := self.try_resolve_fs_cls(dct)) is not None:
|
| 92 |
+
return AbstractFileSystem.from_dict(dct)
|
| 93 |
+
if (obj_cls := self.try_resolve_path_cls(dct)) is not None:
|
| 94 |
+
return obj_cls(dct["str"])
|
| 95 |
+
|
| 96 |
+
if self.original_object_hook is not None:
|
| 97 |
+
return self.original_object_hook(dct)
|
| 98 |
+
|
| 99 |
+
return dct
|
| 100 |
+
|
| 101 |
+
def unmake_serializable(self, obj: Any) -> Any:
|
| 102 |
+
"""
|
| 103 |
+
Inverse function of :meth:`FilesystemJSONEncoder.make_serializable`.
|
| 104 |
+
"""
|
| 105 |
+
if isinstance(obj, dict):
|
| 106 |
+
obj = self.custom_object_hook(obj)
|
| 107 |
+
if isinstance(obj, dict):
|
| 108 |
+
return {k: self.unmake_serializable(v) for k, v in obj.items()}
|
| 109 |
+
if isinstance(obj, (list, tuple)):
|
| 110 |
+
return [self.unmake_serializable(v) for v in obj]
|
| 111 |
+
|
| 112 |
+
return obj
|
micromamba_root/envs/hf_sync/Lib/site-packages/fsspec/mapping.py
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import array
|
| 2 |
+
import logging
|
| 3 |
+
import posixpath
|
| 4 |
+
import warnings
|
| 5 |
+
from collections.abc import MutableMapping
|
| 6 |
+
from functools import cached_property
|
| 7 |
+
|
| 8 |
+
from fsspec.core import url_to_fs
|
| 9 |
+
|
| 10 |
+
logger = logging.getLogger("fsspec.mapping")
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class FSMap(MutableMapping):
|
| 14 |
+
"""Wrap a FileSystem instance as a mutable wrapping.
|
| 15 |
+
|
| 16 |
+
The keys of the mapping become files under the given root, and the
|
| 17 |
+
values (which must be bytes) the contents of those files.
|
| 18 |
+
|
| 19 |
+
Parameters
|
| 20 |
+
----------
|
| 21 |
+
root: string
|
| 22 |
+
prefix for all the files
|
| 23 |
+
fs: FileSystem instance
|
| 24 |
+
check: bool (=True)
|
| 25 |
+
performs a touch at the location, to check for write access.
|
| 26 |
+
|
| 27 |
+
Examples
|
| 28 |
+
--------
|
| 29 |
+
>>> fs = FileSystem(**parameters) # doctest: +SKIP
|
| 30 |
+
>>> d = FSMap('my-data/path/', fs) # doctest: +SKIP
|
| 31 |
+
or, more likely
|
| 32 |
+
>>> d = fs.get_mapper('my-data/path/')
|
| 33 |
+
|
| 34 |
+
>>> d['loc1'] = b'Hello World' # doctest: +SKIP
|
| 35 |
+
>>> list(d.keys()) # doctest: +SKIP
|
| 36 |
+
['loc1']
|
| 37 |
+
>>> d['loc1'] # doctest: +SKIP
|
| 38 |
+
b'Hello World'
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
def __init__(self, root, fs, check=False, create=False, missing_exceptions=None):
|
| 42 |
+
self.fs = fs
|
| 43 |
+
self.root = fs._strip_protocol(root)
|
| 44 |
+
self._root_key_to_str = fs._strip_protocol(posixpath.join(root, "x"))[:-1]
|
| 45 |
+
if missing_exceptions is None:
|
| 46 |
+
missing_exceptions = (
|
| 47 |
+
FileNotFoundError,
|
| 48 |
+
IsADirectoryError,
|
| 49 |
+
NotADirectoryError,
|
| 50 |
+
)
|
| 51 |
+
self.missing_exceptions = missing_exceptions
|
| 52 |
+
self.check = check
|
| 53 |
+
self.create = create
|
| 54 |
+
if create:
|
| 55 |
+
if not self.fs.exists(root):
|
| 56 |
+
self.fs.mkdir(root)
|
| 57 |
+
if check:
|
| 58 |
+
if not self.fs.exists(root):
|
| 59 |
+
raise ValueError(
|
| 60 |
+
f"Path {root} does not exist. Create "
|
| 61 |
+
f" with the ``create=True`` keyword"
|
| 62 |
+
)
|
| 63 |
+
self.fs.touch(root + "/a")
|
| 64 |
+
self.fs.rm(root + "/a")
|
| 65 |
+
|
| 66 |
+
@cached_property
|
| 67 |
+
def dirfs(self):
|
| 68 |
+
"""dirfs instance that can be used with the same keys as the mapper"""
|
| 69 |
+
from .implementations.dirfs import DirFileSystem
|
| 70 |
+
|
| 71 |
+
return DirFileSystem(path=self._root_key_to_str, fs=self.fs)
|
| 72 |
+
|
| 73 |
+
def clear(self):
|
| 74 |
+
"""Remove all keys below root - empties out mapping"""
|
| 75 |
+
logger.info("Clear mapping at %s", self.root)
|
| 76 |
+
try:
|
| 77 |
+
self.fs.rm(self.root, True)
|
| 78 |
+
self.fs.mkdir(self.root)
|
| 79 |
+
except: # noqa: E722
|
| 80 |
+
pass
|
| 81 |
+
|
| 82 |
+
def getitems(self, keys, on_error="raise"):
|
| 83 |
+
"""Fetch multiple items from the store
|
| 84 |
+
|
| 85 |
+
If the backend is async-able, this might proceed concurrently
|
| 86 |
+
|
| 87 |
+
Parameters
|
| 88 |
+
----------
|
| 89 |
+
keys: list(str)
|
| 90 |
+
They keys to be fetched
|
| 91 |
+
on_error : "raise", "omit", "return"
|
| 92 |
+
If raise, an underlying exception will be raised (converted to KeyError
|
| 93 |
+
if the type is in self.missing_exceptions); if omit, keys with exception
|
| 94 |
+
will simply not be included in the output; if "return", all keys are
|
| 95 |
+
included in the output, but the value will be bytes or an exception
|
| 96 |
+
instance.
|
| 97 |
+
|
| 98 |
+
Returns
|
| 99 |
+
-------
|
| 100 |
+
dict(key, bytes|exception)
|
| 101 |
+
"""
|
| 102 |
+
keys2 = [self._key_to_str(k) for k in keys]
|
| 103 |
+
oe = on_error if on_error == "raise" else "return"
|
| 104 |
+
try:
|
| 105 |
+
out = self.fs.cat(keys2, on_error=oe)
|
| 106 |
+
if isinstance(out, bytes):
|
| 107 |
+
out = {keys2[0]: out}
|
| 108 |
+
except self.missing_exceptions as e:
|
| 109 |
+
raise KeyError from e
|
| 110 |
+
out = {
|
| 111 |
+
k: (KeyError() if isinstance(v, self.missing_exceptions) else v)
|
| 112 |
+
for k, v in out.items()
|
| 113 |
+
}
|
| 114 |
+
return {
|
| 115 |
+
key: out[k2] if on_error == "raise" else out.get(k2, KeyError(k2))
|
| 116 |
+
for key, k2 in zip(keys, keys2)
|
| 117 |
+
if on_error == "return" or not isinstance(out[k2], BaseException)
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
def setitems(self, values_dict):
|
| 121 |
+
"""Set the values of multiple items in the store
|
| 122 |
+
|
| 123 |
+
Parameters
|
| 124 |
+
----------
|
| 125 |
+
values_dict: dict(str, bytes)
|
| 126 |
+
"""
|
| 127 |
+
values = {self._key_to_str(k): maybe_convert(v) for k, v in values_dict.items()}
|
| 128 |
+
self.fs.pipe(values)
|
| 129 |
+
|
| 130 |
+
def delitems(self, keys):
|
| 131 |
+
"""Remove multiple keys from the store"""
|
| 132 |
+
self.fs.rm([self._key_to_str(k) for k in keys])
|
| 133 |
+
|
| 134 |
+
def _key_to_str(self, key):
|
| 135 |
+
"""Generate full path for the key"""
|
| 136 |
+
if not isinstance(key, str):
|
| 137 |
+
# raise TypeError("key must be of type `str`, got `{type(key).__name__}`"
|
| 138 |
+
warnings.warn(
|
| 139 |
+
"from fsspec 2023.5 onward FSMap non-str keys will raise TypeError",
|
| 140 |
+
DeprecationWarning,
|
| 141 |
+
)
|
| 142 |
+
if isinstance(key, list):
|
| 143 |
+
key = tuple(key)
|
| 144 |
+
key = str(key)
|
| 145 |
+
return f"{self._root_key_to_str}{key}".rstrip("/")
|
| 146 |
+
|
| 147 |
+
def _str_to_key(self, s):
|
| 148 |
+
"""Strip path of to leave key name"""
|
| 149 |
+
return s[len(self.root) :].lstrip("/")
|
| 150 |
+
|
| 151 |
+
def __getitem__(self, key, default=None):
|
| 152 |
+
"""Retrieve data"""
|
| 153 |
+
k = self._key_to_str(key)
|
| 154 |
+
try:
|
| 155 |
+
result = self.fs.cat(k)
|
| 156 |
+
except self.missing_exceptions as exc:
|
| 157 |
+
if default is not None:
|
| 158 |
+
return default
|
| 159 |
+
raise KeyError(key) from exc
|
| 160 |
+
return result
|
| 161 |
+
|
| 162 |
+
def pop(self, key, default=None):
|
| 163 |
+
"""Pop data"""
|
| 164 |
+
result = self.__getitem__(key, default)
|
| 165 |
+
try:
|
| 166 |
+
del self[key]
|
| 167 |
+
except KeyError:
|
| 168 |
+
pass
|
| 169 |
+
return result
|
| 170 |
+
|
| 171 |
+
def __setitem__(self, key, value):
|
| 172 |
+
"""Store value in key"""
|
| 173 |
+
key = self._key_to_str(key)
|
| 174 |
+
self.fs.mkdirs(self.fs._parent(key), exist_ok=True)
|
| 175 |
+
self.fs.pipe_file(key, maybe_convert(value))
|
| 176 |
+
|
| 177 |
+
def __iter__(self):
|
| 178 |
+
return (self._str_to_key(x) for x in self.fs.find(self.root))
|
| 179 |
+
|
| 180 |
+
def __len__(self):
|
| 181 |
+
return len(self.fs.find(self.root))
|
| 182 |
+
|
| 183 |
+
def __delitem__(self, key):
|
| 184 |
+
"""Remove key"""
|
| 185 |
+
try:
|
| 186 |
+
self.fs.rm(self._key_to_str(key))
|
| 187 |
+
except Exception as exc:
|
| 188 |
+
raise KeyError from exc
|
| 189 |
+
|
| 190 |
+
def __contains__(self, key):
|
| 191 |
+
"""Does key exist in mapping?"""
|
| 192 |
+
path = self._key_to_str(key)
|
| 193 |
+
return self.fs.isfile(path)
|
| 194 |
+
|
| 195 |
+
def __reduce__(self):
|
| 196 |
+
return FSMap, (self.root, self.fs, False, False, self.missing_exceptions)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def maybe_convert(value):
|
| 200 |
+
if isinstance(value, array.array) or hasattr(value, "__array__"):
|
| 201 |
+
# bytes-like things
|
| 202 |
+
if hasattr(value, "dtype") and value.dtype.kind in "Mm":
|
| 203 |
+
# The buffer interface doesn't support datetime64/timdelta64 numpy
|
| 204 |
+
# arrays
|
| 205 |
+
value = value.view("int64")
|
| 206 |
+
value = bytes(memoryview(value))
|
| 207 |
+
return value
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def get_mapper(
|
| 211 |
+
url="",
|
| 212 |
+
check=False,
|
| 213 |
+
create=False,
|
| 214 |
+
missing_exceptions=None,
|
| 215 |
+
alternate_root=None,
|
| 216 |
+
**kwargs,
|
| 217 |
+
):
|
| 218 |
+
"""Create key-value interface for given URL and options
|
| 219 |
+
|
| 220 |
+
The URL will be of the form "protocol://location" and point to the root
|
| 221 |
+
of the mapper required. All keys will be file-names below this location,
|
| 222 |
+
and their values the contents of each key.
|
| 223 |
+
|
| 224 |
+
Also accepts compound URLs like zip::s3://bucket/file.zip , see ``fsspec.open``.
|
| 225 |
+
|
| 226 |
+
Parameters
|
| 227 |
+
----------
|
| 228 |
+
url: str
|
| 229 |
+
Root URL of mapping
|
| 230 |
+
check: bool
|
| 231 |
+
Whether to attempt to read from the location before instantiation, to
|
| 232 |
+
check that the mapping does exist
|
| 233 |
+
create: bool
|
| 234 |
+
Whether to make the directory corresponding to the root before
|
| 235 |
+
instantiating
|
| 236 |
+
missing_exceptions: None or tuple
|
| 237 |
+
If given, these exception types will be regarded as missing keys and
|
| 238 |
+
return KeyError when trying to read data. By default, you get
|
| 239 |
+
(FileNotFoundError, IsADirectoryError, NotADirectoryError)
|
| 240 |
+
alternate_root: None or str
|
| 241 |
+
In cases of complex URLs, the parser may fail to pick the correct part
|
| 242 |
+
for the mapper root, so this arg can override
|
| 243 |
+
|
| 244 |
+
Returns
|
| 245 |
+
-------
|
| 246 |
+
``FSMap`` instance, the dict-like key-value store.
|
| 247 |
+
"""
|
| 248 |
+
# Removing protocol here - could defer to each open() on the backend
|
| 249 |
+
fs, urlpath = url_to_fs(url, **kwargs)
|
| 250 |
+
root = alternate_root if alternate_root is not None else urlpath
|
| 251 |
+
return FSMap(root, fs, check, create, missing_exceptions=missing_exceptions)
|
micromamba_root/envs/hf_sync/Lib/site-packages/fsspec/parquet.py
ADDED
|
@@ -0,0 +1,572 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import io
|
| 2 |
+
import json
|
| 3 |
+
import warnings
|
| 4 |
+
|
| 5 |
+
import fsspec
|
| 6 |
+
|
| 7 |
+
from .core import url_to_fs
|
| 8 |
+
from .spec import AbstractBufferedFile
|
| 9 |
+
from .utils import merge_offset_ranges
|
| 10 |
+
|
| 11 |
+
# Parquet-Specific Utilities for fsspec
|
| 12 |
+
#
|
| 13 |
+
# Most of the functions defined in this module are NOT
|
| 14 |
+
# intended for public consumption. The only exception
|
| 15 |
+
# to this is `open_parquet_file`, which should be used
|
| 16 |
+
# place of `fs.open()` to open parquet-formatted files
|
| 17 |
+
# on remote file systems.
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class AlreadyBufferedFile(AbstractBufferedFile):
|
| 21 |
+
def _fetch_range(self, start, end):
|
| 22 |
+
raise NotImplementedError
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def open_parquet_files(
|
| 26 |
+
path: list[str],
|
| 27 |
+
fs: None | fsspec.AbstractFileSystem = None,
|
| 28 |
+
metadata=None,
|
| 29 |
+
columns: None | list[str] = None,
|
| 30 |
+
row_groups: None | list[int] = None,
|
| 31 |
+
storage_options: None | dict = None,
|
| 32 |
+
engine: str = "auto",
|
| 33 |
+
max_gap: int = 64_000,
|
| 34 |
+
max_block: int = 256_000_000,
|
| 35 |
+
footer_sample_size: int = 1_000_000,
|
| 36 |
+
filters: None | list[list[list[str]]] = None,
|
| 37 |
+
**kwargs,
|
| 38 |
+
):
|
| 39 |
+
"""
|
| 40 |
+
Return a file-like object for a single Parquet file.
|
| 41 |
+
|
| 42 |
+
The specified parquet `engine` will be used to parse the
|
| 43 |
+
footer metadata, and determine the required byte ranges
|
| 44 |
+
from the file. The target path will then be opened with
|
| 45 |
+
the "parts" (`KnownPartsOfAFile`) caching strategy.
|
| 46 |
+
|
| 47 |
+
Note that this method is intended for usage with remote
|
| 48 |
+
file systems, and is unlikely to improve parquet-read
|
| 49 |
+
performance on local file systems.
|
| 50 |
+
|
| 51 |
+
Parameters
|
| 52 |
+
----------
|
| 53 |
+
path: str
|
| 54 |
+
Target file path.
|
| 55 |
+
metadata: Any, optional
|
| 56 |
+
Parquet metadata object. Object type must be supported
|
| 57 |
+
by the backend parquet engine. For now, only the "fastparquet"
|
| 58 |
+
engine supports an explicit `ParquetFile` metadata object.
|
| 59 |
+
If a metadata object is supplied, the remote footer metadata
|
| 60 |
+
will not need to be transferred into local memory.
|
| 61 |
+
fs: AbstractFileSystem, optional
|
| 62 |
+
Filesystem object to use for opening the file. If nothing is
|
| 63 |
+
specified, an `AbstractFileSystem` object will be inferred.
|
| 64 |
+
engine : str, default "auto"
|
| 65 |
+
Parquet engine to use for metadata parsing. Allowed options
|
| 66 |
+
include "fastparquet", "pyarrow", and "auto". The specified
|
| 67 |
+
engine must be installed in the current environment. If
|
| 68 |
+
"auto" is specified, and both engines are installed,
|
| 69 |
+
"fastparquet" will take precedence over "pyarrow".
|
| 70 |
+
columns: list, optional
|
| 71 |
+
List of all column names that may be read from the file.
|
| 72 |
+
row_groups : list, optional
|
| 73 |
+
List of all row-groups that may be read from the file. This
|
| 74 |
+
may be a list of row-group indices (integers), or it may be
|
| 75 |
+
a list of `RowGroup` metadata objects (if the "fastparquet"
|
| 76 |
+
engine is used).
|
| 77 |
+
storage_options : dict, optional
|
| 78 |
+
Used to generate an `AbstractFileSystem` object if `fs` was
|
| 79 |
+
not specified.
|
| 80 |
+
max_gap : int, optional
|
| 81 |
+
Neighboring byte ranges will only be merged when their
|
| 82 |
+
inter-range gap is <= `max_gap`. Default is 64KB.
|
| 83 |
+
max_block : int, optional
|
| 84 |
+
Neighboring byte ranges will only be merged when the size of
|
| 85 |
+
the aggregated range is <= `max_block`. Default is 256MB.
|
| 86 |
+
footer_sample_size : int, optional
|
| 87 |
+
Number of bytes to read from the end of the path to look
|
| 88 |
+
for the footer metadata. If the sampled bytes do not contain
|
| 89 |
+
the footer, a second read request will be required, and
|
| 90 |
+
performance will suffer. Default is 1MB.
|
| 91 |
+
filters : list[list], optional
|
| 92 |
+
List of filters to apply to prevent reading row groups, of the
|
| 93 |
+
same format as accepted by the loading engines. Ignored if
|
| 94 |
+
``row_groups`` is specified.
|
| 95 |
+
**kwargs :
|
| 96 |
+
Optional key-word arguments to pass to `fs.open`
|
| 97 |
+
"""
|
| 98 |
+
|
| 99 |
+
# Make sure we have an `AbstractFileSystem` object
|
| 100 |
+
# to work with
|
| 101 |
+
if fs is None:
|
| 102 |
+
path0 = path
|
| 103 |
+
if isinstance(path, (list, tuple)):
|
| 104 |
+
path = path[0]
|
| 105 |
+
fs, path = url_to_fs(path, **(storage_options or {}))
|
| 106 |
+
else:
|
| 107 |
+
path0 = path
|
| 108 |
+
|
| 109 |
+
# For now, `columns == []` not supported, is the same
|
| 110 |
+
# as all columns
|
| 111 |
+
if columns is not None and len(columns) == 0:
|
| 112 |
+
columns = None
|
| 113 |
+
|
| 114 |
+
# Set the engine
|
| 115 |
+
engine = _set_engine(engine)
|
| 116 |
+
|
| 117 |
+
if isinstance(path0, (list, tuple)):
|
| 118 |
+
paths = path0
|
| 119 |
+
elif "*" in path:
|
| 120 |
+
paths = fs.glob(path)
|
| 121 |
+
elif path0.endswith("/"): # or fs.isdir(path):
|
| 122 |
+
paths = [
|
| 123 |
+
_
|
| 124 |
+
for _ in fs.find(path, withdirs=False, detail=False)
|
| 125 |
+
if _.endswith((".parquet", ".parq"))
|
| 126 |
+
]
|
| 127 |
+
else:
|
| 128 |
+
paths = [path]
|
| 129 |
+
|
| 130 |
+
data = _get_parquet_byte_ranges(
|
| 131 |
+
paths,
|
| 132 |
+
fs,
|
| 133 |
+
metadata=metadata,
|
| 134 |
+
columns=columns,
|
| 135 |
+
row_groups=row_groups,
|
| 136 |
+
engine=engine,
|
| 137 |
+
max_gap=max_gap,
|
| 138 |
+
max_block=max_block,
|
| 139 |
+
footer_sample_size=footer_sample_size,
|
| 140 |
+
filters=filters,
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
# Call self.open with "parts" caching
|
| 144 |
+
options = kwargs.pop("cache_options", {}).copy()
|
| 145 |
+
return [
|
| 146 |
+
AlreadyBufferedFile(
|
| 147 |
+
fs=None,
|
| 148 |
+
path=fn,
|
| 149 |
+
mode="rb",
|
| 150 |
+
cache_type="parts",
|
| 151 |
+
cache_options={
|
| 152 |
+
**options,
|
| 153 |
+
"data": ranges,
|
| 154 |
+
},
|
| 155 |
+
size=max(_[1] for _ in ranges),
|
| 156 |
+
**kwargs,
|
| 157 |
+
)
|
| 158 |
+
for fn, ranges in data.items()
|
| 159 |
+
]
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def open_parquet_file(*args, **kwargs):
|
| 163 |
+
"""Create files tailed to reading specific parts of parquet files
|
| 164 |
+
|
| 165 |
+
Please see ``open_parquet_files`` for details of the arguments. The
|
| 166 |
+
difference is, this function always returns a single ``AlreadyBufferedFile``,
|
| 167 |
+
whereas `open_parquet_files`` always returns a list of files, even if
|
| 168 |
+
there are one or zero matching parquet files.
|
| 169 |
+
"""
|
| 170 |
+
return open_parquet_files(*args, **kwargs)[0]
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def _get_parquet_byte_ranges(
|
| 174 |
+
paths,
|
| 175 |
+
fs,
|
| 176 |
+
metadata=None,
|
| 177 |
+
columns=None,
|
| 178 |
+
row_groups=None,
|
| 179 |
+
max_gap=64_000,
|
| 180 |
+
max_block=256_000_000,
|
| 181 |
+
footer_sample_size=1_000_000,
|
| 182 |
+
engine="auto",
|
| 183 |
+
filters=None,
|
| 184 |
+
):
|
| 185 |
+
"""Get a dictionary of the known byte ranges needed
|
| 186 |
+
to read a specific column/row-group selection from a
|
| 187 |
+
Parquet dataset. Each value in the output dictionary
|
| 188 |
+
is intended for use as the `data` argument for the
|
| 189 |
+
`KnownPartsOfAFile` caching strategy of a single path.
|
| 190 |
+
"""
|
| 191 |
+
|
| 192 |
+
# Set engine if necessary
|
| 193 |
+
if isinstance(engine, str):
|
| 194 |
+
engine = _set_engine(engine)
|
| 195 |
+
|
| 196 |
+
# Pass to a specialized function if metadata is defined
|
| 197 |
+
if metadata is not None:
|
| 198 |
+
# Use the provided parquet metadata object
|
| 199 |
+
# to avoid transferring/parsing footer metadata
|
| 200 |
+
return _get_parquet_byte_ranges_from_metadata(
|
| 201 |
+
metadata,
|
| 202 |
+
fs,
|
| 203 |
+
engine,
|
| 204 |
+
columns=columns,
|
| 205 |
+
row_groups=row_groups,
|
| 206 |
+
max_gap=max_gap,
|
| 207 |
+
max_block=max_block,
|
| 208 |
+
filters=filters,
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
# Populate global paths, starts, & ends
|
| 212 |
+
if columns is None and row_groups is None and filters is None:
|
| 213 |
+
# We are NOT selecting specific columns or row-groups.
|
| 214 |
+
#
|
| 215 |
+
# We can avoid sampling the footers, and just transfer
|
| 216 |
+
# all file data with cat_ranges
|
| 217 |
+
result = {path: {(0, len(data)): data} for path, data in fs.cat(paths).items()}
|
| 218 |
+
else:
|
| 219 |
+
# We ARE selecting specific columns or row-groups.
|
| 220 |
+
#
|
| 221 |
+
# Get file sizes asynchronously
|
| 222 |
+
file_sizes = fs.sizes(paths)
|
| 223 |
+
data_paths = []
|
| 224 |
+
data_starts = []
|
| 225 |
+
data_ends = []
|
| 226 |
+
# Gather file footers.
|
| 227 |
+
# We just take the last `footer_sample_size` bytes of each
|
| 228 |
+
# file (or the entire file if it is smaller than that)
|
| 229 |
+
footer_starts = [
|
| 230 |
+
max(0, file_size - footer_sample_size) for file_size in file_sizes
|
| 231 |
+
]
|
| 232 |
+
footer_samples = fs.cat_ranges(paths, footer_starts, file_sizes)
|
| 233 |
+
|
| 234 |
+
# Check our footer samples and re-sample if necessary.
|
| 235 |
+
large_footer = []
|
| 236 |
+
for i, path in enumerate(paths):
|
| 237 |
+
footer_size = int.from_bytes(footer_samples[i][-8:-4], "little")
|
| 238 |
+
real_footer_start = file_sizes[i] - (footer_size + 8)
|
| 239 |
+
if real_footer_start < footer_starts[i]:
|
| 240 |
+
large_footer.append((i, real_footer_start))
|
| 241 |
+
if large_footer:
|
| 242 |
+
warnings.warn(
|
| 243 |
+
f"Not enough data was used to sample the parquet footer. "
|
| 244 |
+
f"Try setting footer_sample_size >= {large_footer}."
|
| 245 |
+
)
|
| 246 |
+
path0 = [paths[i] for i, _ in large_footer]
|
| 247 |
+
starts = [_[1] for _ in large_footer]
|
| 248 |
+
ends = [file_sizes[i] - footer_sample_size for i, _ in large_footer]
|
| 249 |
+
data = fs.cat_ranges(path0, starts, ends)
|
| 250 |
+
for i, (path, start, block) in enumerate(zip(path0, starts, data)):
|
| 251 |
+
footer_samples[i] = block + footer_samples[i]
|
| 252 |
+
footer_starts[i] = start
|
| 253 |
+
result = {
|
| 254 |
+
path: {(start, size): data}
|
| 255 |
+
for path, start, size, data in zip(
|
| 256 |
+
paths, footer_starts, file_sizes, footer_samples
|
| 257 |
+
)
|
| 258 |
+
}
|
| 259 |
+
|
| 260 |
+
# Calculate required byte ranges for each path
|
| 261 |
+
for i, path in enumerate(paths):
|
| 262 |
+
# Use "engine" to collect data byte ranges
|
| 263 |
+
path_data_starts, path_data_ends = engine._parquet_byte_ranges(
|
| 264 |
+
columns,
|
| 265 |
+
row_groups=row_groups,
|
| 266 |
+
footer=footer_samples[i],
|
| 267 |
+
footer_start=footer_starts[i],
|
| 268 |
+
filters=filters,
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
+
data_paths += [path] * len(path_data_starts)
|
| 272 |
+
data_starts += path_data_starts
|
| 273 |
+
data_ends += path_data_ends
|
| 274 |
+
|
| 275 |
+
# Merge adjacent offset ranges
|
| 276 |
+
data_paths, data_starts, data_ends = merge_offset_ranges(
|
| 277 |
+
data_paths,
|
| 278 |
+
data_starts,
|
| 279 |
+
data_ends,
|
| 280 |
+
max_gap=max_gap,
|
| 281 |
+
max_block=max_block,
|
| 282 |
+
sort=True,
|
| 283 |
+
)
|
| 284 |
+
|
| 285 |
+
# Transfer the data byte-ranges into local memory
|
| 286 |
+
_transfer_ranges(fs, result, data_paths, data_starts, data_ends)
|
| 287 |
+
|
| 288 |
+
# Add b"PAR1" to headers
|
| 289 |
+
_add_header_magic(result)
|
| 290 |
+
|
| 291 |
+
return result
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
def _get_parquet_byte_ranges_from_metadata(
|
| 295 |
+
metadata,
|
| 296 |
+
fs,
|
| 297 |
+
engine,
|
| 298 |
+
columns=None,
|
| 299 |
+
row_groups=None,
|
| 300 |
+
max_gap=64_000,
|
| 301 |
+
max_block=256_000_000,
|
| 302 |
+
filters=None,
|
| 303 |
+
):
|
| 304 |
+
"""Simplified version of `_get_parquet_byte_ranges` for
|
| 305 |
+
the case that an engine-specific `metadata` object is
|
| 306 |
+
provided, and the remote footer metadata does not need to
|
| 307 |
+
be transferred before calculating the required byte ranges.
|
| 308 |
+
"""
|
| 309 |
+
|
| 310 |
+
# Use "engine" to collect data byte ranges
|
| 311 |
+
data_paths, data_starts, data_ends = engine._parquet_byte_ranges(
|
| 312 |
+
columns, row_groups=row_groups, metadata=metadata, filters=filters
|
| 313 |
+
)
|
| 314 |
+
|
| 315 |
+
# Merge adjacent offset ranges
|
| 316 |
+
data_paths, data_starts, data_ends = merge_offset_ranges(
|
| 317 |
+
data_paths,
|
| 318 |
+
data_starts,
|
| 319 |
+
data_ends,
|
| 320 |
+
max_gap=max_gap,
|
| 321 |
+
max_block=max_block,
|
| 322 |
+
sort=False, # Should be sorted
|
| 323 |
+
)
|
| 324 |
+
|
| 325 |
+
# Transfer the data byte-ranges into local memory
|
| 326 |
+
result = {fn: {} for fn in list(set(data_paths))}
|
| 327 |
+
_transfer_ranges(fs, result, data_paths, data_starts, data_ends)
|
| 328 |
+
|
| 329 |
+
# Add b"PAR1" to header
|
| 330 |
+
_add_header_magic(result)
|
| 331 |
+
|
| 332 |
+
return result
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
def _transfer_ranges(fs, blocks, paths, starts, ends):
|
| 336 |
+
# Use cat_ranges to gather the data byte_ranges
|
| 337 |
+
ranges = (paths, starts, ends)
|
| 338 |
+
for path, start, stop, data in zip(*ranges, fs.cat_ranges(*ranges)):
|
| 339 |
+
blocks[path][(start, stop)] = data
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
def _add_header_magic(data):
|
| 343 |
+
# Add b"PAR1" to file headers
|
| 344 |
+
for path in list(data):
|
| 345 |
+
add_magic = True
|
| 346 |
+
for k in data[path]:
|
| 347 |
+
if k[0] == 0 and k[1] >= 4:
|
| 348 |
+
add_magic = False
|
| 349 |
+
break
|
| 350 |
+
if add_magic:
|
| 351 |
+
data[path][(0, 4)] = b"PAR1"
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
def _set_engine(engine_str):
|
| 355 |
+
# Define a list of parquet engines to try
|
| 356 |
+
if engine_str == "auto":
|
| 357 |
+
try_engines = ("fastparquet", "pyarrow")
|
| 358 |
+
elif not isinstance(engine_str, str):
|
| 359 |
+
raise ValueError(
|
| 360 |
+
"Failed to set parquet engine! "
|
| 361 |
+
"Please pass 'fastparquet', 'pyarrow', or 'auto'"
|
| 362 |
+
)
|
| 363 |
+
elif engine_str not in ("fastparquet", "pyarrow"):
|
| 364 |
+
raise ValueError(f"{engine_str} engine not supported by `fsspec.parquet`")
|
| 365 |
+
else:
|
| 366 |
+
try_engines = [engine_str]
|
| 367 |
+
|
| 368 |
+
# Try importing the engines in `try_engines`,
|
| 369 |
+
# and choose the first one that succeeds
|
| 370 |
+
for engine in try_engines:
|
| 371 |
+
try:
|
| 372 |
+
if engine == "fastparquet":
|
| 373 |
+
return FastparquetEngine()
|
| 374 |
+
elif engine == "pyarrow":
|
| 375 |
+
return PyarrowEngine()
|
| 376 |
+
except ImportError:
|
| 377 |
+
pass
|
| 378 |
+
|
| 379 |
+
# Raise an error if a supported parquet engine
|
| 380 |
+
# was not found
|
| 381 |
+
raise ImportError(
|
| 382 |
+
f"The following parquet engines are not installed "
|
| 383 |
+
f"in your python environment: {try_engines}."
|
| 384 |
+
f"Please install 'fastparquert' or 'pyarrow' to "
|
| 385 |
+
f"utilize the `fsspec.parquet` module."
|
| 386 |
+
)
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
class FastparquetEngine:
|
| 390 |
+
# The purpose of the FastparquetEngine class is
|
| 391 |
+
# to check if fastparquet can be imported (on initialization)
|
| 392 |
+
# and to define a `_parquet_byte_ranges` method. In the
|
| 393 |
+
# future, this class may also be used to define other
|
| 394 |
+
# methods/logic that are specific to fastparquet.
|
| 395 |
+
|
| 396 |
+
def __init__(self):
|
| 397 |
+
import fastparquet as fp
|
| 398 |
+
|
| 399 |
+
self.fp = fp
|
| 400 |
+
|
| 401 |
+
def _parquet_byte_ranges(
|
| 402 |
+
self,
|
| 403 |
+
columns,
|
| 404 |
+
row_groups=None,
|
| 405 |
+
metadata=None,
|
| 406 |
+
footer=None,
|
| 407 |
+
footer_start=None,
|
| 408 |
+
filters=None,
|
| 409 |
+
):
|
| 410 |
+
# Initialize offset ranges and define ParqetFile metadata
|
| 411 |
+
pf = metadata
|
| 412 |
+
data_paths, data_starts, data_ends = [], [], []
|
| 413 |
+
if filters and row_groups:
|
| 414 |
+
raise ValueError("filters and row_groups cannot be used together")
|
| 415 |
+
if pf is None:
|
| 416 |
+
pf = self.fp.ParquetFile(io.BytesIO(footer))
|
| 417 |
+
|
| 418 |
+
# Convert columns to a set and add any index columns
|
| 419 |
+
# specified in the pandas metadata (just in case)
|
| 420 |
+
column_set = None if columns is None else {c.split(".", 1)[0] for c in columns}
|
| 421 |
+
if column_set is not None and hasattr(pf, "pandas_metadata"):
|
| 422 |
+
md_index = [
|
| 423 |
+
ind
|
| 424 |
+
for ind in pf.pandas_metadata.get("index_columns", [])
|
| 425 |
+
# Ignore RangeIndex information
|
| 426 |
+
if not isinstance(ind, dict)
|
| 427 |
+
]
|
| 428 |
+
column_set |= set(md_index)
|
| 429 |
+
|
| 430 |
+
# Check if row_groups is a list of integers
|
| 431 |
+
# or a list of row-group metadata
|
| 432 |
+
if filters:
|
| 433 |
+
from fastparquet.api import filter_row_groups
|
| 434 |
+
|
| 435 |
+
row_group_indices = None
|
| 436 |
+
row_groups = filter_row_groups(pf, filters)
|
| 437 |
+
elif row_groups and not isinstance(row_groups[0], int):
|
| 438 |
+
# Input row_groups contains row-group metadata
|
| 439 |
+
row_group_indices = None
|
| 440 |
+
else:
|
| 441 |
+
# Input row_groups contains row-group indices
|
| 442 |
+
row_group_indices = row_groups
|
| 443 |
+
row_groups = pf.row_groups
|
| 444 |
+
if column_set is not None:
|
| 445 |
+
column_set = [
|
| 446 |
+
_ if isinstance(_, list) else _.split(".") for _ in column_set
|
| 447 |
+
]
|
| 448 |
+
|
| 449 |
+
# Loop through column chunks to add required byte ranges
|
| 450 |
+
for r, row_group in enumerate(row_groups):
|
| 451 |
+
# Skip this row-group if we are targeting
|
| 452 |
+
# specific row-groups
|
| 453 |
+
if row_group_indices is None or r in row_group_indices:
|
| 454 |
+
# Find the target parquet-file path for `row_group`
|
| 455 |
+
fn = pf.row_group_filename(row_group)
|
| 456 |
+
|
| 457 |
+
for column in row_group.columns:
|
| 458 |
+
name = column.meta_data.path_in_schema
|
| 459 |
+
# Skip this column if we are targeting specific columns
|
| 460 |
+
if column_set is None or _cmp(name, column_set):
|
| 461 |
+
file_offset0 = column.meta_data.dictionary_page_offset
|
| 462 |
+
if file_offset0 is None:
|
| 463 |
+
file_offset0 = column.meta_data.data_page_offset
|
| 464 |
+
num_bytes = column.meta_data.total_compressed_size
|
| 465 |
+
if footer_start is None or file_offset0 < footer_start:
|
| 466 |
+
data_paths.append(fn)
|
| 467 |
+
data_starts.append(file_offset0)
|
| 468 |
+
data_ends.append(
|
| 469 |
+
min(
|
| 470 |
+
file_offset0 + num_bytes,
|
| 471 |
+
footer_start or (file_offset0 + num_bytes),
|
| 472 |
+
)
|
| 473 |
+
)
|
| 474 |
+
|
| 475 |
+
if metadata:
|
| 476 |
+
# The metadata in this call may map to multiple
|
| 477 |
+
# file paths. Need to include `data_paths`
|
| 478 |
+
return data_paths, data_starts, data_ends
|
| 479 |
+
return data_starts, data_ends
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
class PyarrowEngine:
|
| 483 |
+
# The purpose of the PyarrowEngine class is
|
| 484 |
+
# to check if pyarrow can be imported (on initialization)
|
| 485 |
+
# and to define a `_parquet_byte_ranges` method. In the
|
| 486 |
+
# future, this class may also be used to define other
|
| 487 |
+
# methods/logic that are specific to pyarrow.
|
| 488 |
+
|
| 489 |
+
def __init__(self):
|
| 490 |
+
import pyarrow.parquet as pq
|
| 491 |
+
|
| 492 |
+
self.pq = pq
|
| 493 |
+
|
| 494 |
+
def _parquet_byte_ranges(
|
| 495 |
+
self,
|
| 496 |
+
columns,
|
| 497 |
+
row_groups=None,
|
| 498 |
+
metadata=None,
|
| 499 |
+
footer=None,
|
| 500 |
+
footer_start=None,
|
| 501 |
+
filters=None,
|
| 502 |
+
):
|
| 503 |
+
if metadata is not None:
|
| 504 |
+
raise ValueError("metadata input not supported for PyarrowEngine")
|
| 505 |
+
if filters:
|
| 506 |
+
# there must be a way!
|
| 507 |
+
raise NotImplementedError
|
| 508 |
+
|
| 509 |
+
data_starts, data_ends = [], []
|
| 510 |
+
md = self.pq.ParquetFile(io.BytesIO(footer)).metadata
|
| 511 |
+
|
| 512 |
+
# Convert columns to a set and add any index columns
|
| 513 |
+
# specified in the pandas metadata (just in case)
|
| 514 |
+
column_set = None if columns is None else set(columns)
|
| 515 |
+
if column_set is not None:
|
| 516 |
+
schema = md.schema.to_arrow_schema()
|
| 517 |
+
has_pandas_metadata = (
|
| 518 |
+
schema.metadata is not None and b"pandas" in schema.metadata
|
| 519 |
+
)
|
| 520 |
+
if has_pandas_metadata:
|
| 521 |
+
md_index = [
|
| 522 |
+
ind
|
| 523 |
+
for ind in json.loads(
|
| 524 |
+
schema.metadata[b"pandas"].decode("utf8")
|
| 525 |
+
).get("index_columns", [])
|
| 526 |
+
# Ignore RangeIndex information
|
| 527 |
+
if not isinstance(ind, dict)
|
| 528 |
+
]
|
| 529 |
+
column_set |= set(md_index)
|
| 530 |
+
if column_set is not None:
|
| 531 |
+
column_set = [
|
| 532 |
+
_[:1] if isinstance(_, list) else _.split(".")[:1] for _ in column_set
|
| 533 |
+
]
|
| 534 |
+
|
| 535 |
+
# Loop through column chunks to add required byte ranges
|
| 536 |
+
for r in range(md.num_row_groups):
|
| 537 |
+
# Skip this row-group if we are targeting
|
| 538 |
+
# specific row-groups
|
| 539 |
+
if row_groups is None or r in row_groups:
|
| 540 |
+
row_group = md.row_group(r)
|
| 541 |
+
for c in range(row_group.num_columns):
|
| 542 |
+
column = row_group.column(c)
|
| 543 |
+
name = column.path_in_schema.split(".")
|
| 544 |
+
# Skip this column if we are targeting specific columns
|
| 545 |
+
if column_set is None or _cmp(name, column_set):
|
| 546 |
+
meta = column.to_dict()
|
| 547 |
+
# Any offset could be the first one
|
| 548 |
+
file_offset0 = min(
|
| 549 |
+
_
|
| 550 |
+
for _ in [
|
| 551 |
+
meta.get("dictionary_page_offset"),
|
| 552 |
+
meta.get("data_page_offset"),
|
| 553 |
+
meta.get("index_page_offset"),
|
| 554 |
+
]
|
| 555 |
+
if _ is not None
|
| 556 |
+
)
|
| 557 |
+
if file_offset0 < footer_start:
|
| 558 |
+
data_starts.append(file_offset0)
|
| 559 |
+
data_ends.append(
|
| 560 |
+
min(
|
| 561 |
+
meta["total_compressed_size"] + file_offset0,
|
| 562 |
+
footer_start,
|
| 563 |
+
)
|
| 564 |
+
)
|
| 565 |
+
|
| 566 |
+
data_starts.append(footer_start)
|
| 567 |
+
data_ends.append(footer_start + len(footer))
|
| 568 |
+
return data_starts, data_ends
|
| 569 |
+
|
| 570 |
+
|
| 571 |
+
def _cmp(name, column_set):
|
| 572 |
+
return any(all(a == b for a, b in zip(name, _)) for _ in column_set)
|
micromamba_root/envs/hf_sync/Lib/site-packages/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)
|
micromamba_root/envs/hf_sync/Lib/site-packages/fsspec/spec.py
ADDED
|
@@ -0,0 +1,2284 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import io
|
| 4 |
+
import json
|
| 5 |
+
import logging
|
| 6 |
+
import os
|
| 7 |
+
import threading
|
| 8 |
+
import warnings
|
| 9 |
+
import weakref
|
| 10 |
+
from errno import ESPIPE
|
| 11 |
+
from glob import has_magic
|
| 12 |
+
from hashlib import sha256
|
| 13 |
+
from typing import Any, ClassVar
|
| 14 |
+
|
| 15 |
+
from .callbacks import DEFAULT_CALLBACK
|
| 16 |
+
from .config import apply_config, conf
|
| 17 |
+
from .dircache import DirCache
|
| 18 |
+
from .transaction import Transaction
|
| 19 |
+
from .utils import (
|
| 20 |
+
_unstrip_protocol,
|
| 21 |
+
glob_translate,
|
| 22 |
+
isfilelike,
|
| 23 |
+
other_paths,
|
| 24 |
+
read_block,
|
| 25 |
+
stringify_path,
|
| 26 |
+
tokenize,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
logger = logging.getLogger("fsspec")
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def make_instance(cls, args, kwargs):
|
| 33 |
+
return cls(*args, **kwargs)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class _Cached(type):
|
| 37 |
+
"""
|
| 38 |
+
Metaclass for caching file system instances.
|
| 39 |
+
|
| 40 |
+
Notes
|
| 41 |
+
-----
|
| 42 |
+
Instances are cached according to
|
| 43 |
+
|
| 44 |
+
* The values of the class attributes listed in `_extra_tokenize_attributes`
|
| 45 |
+
* The arguments passed to ``__init__``.
|
| 46 |
+
|
| 47 |
+
This creates an additional reference to the filesystem, which prevents the
|
| 48 |
+
filesystem from being garbage collected when all *user* references go away.
|
| 49 |
+
A call to the :meth:`AbstractFileSystem.clear_instance_cache` must *also*
|
| 50 |
+
be made for a filesystem instance to be garbage collected.
|
| 51 |
+
"""
|
| 52 |
+
|
| 53 |
+
def __init__(cls, *args, **kwargs):
|
| 54 |
+
super().__init__(*args, **kwargs)
|
| 55 |
+
# Note: we intentionally create a reference here, to avoid garbage
|
| 56 |
+
# collecting instances when all other references are gone. To really
|
| 57 |
+
# delete a FileSystem, the cache must be cleared.
|
| 58 |
+
if conf.get("weakref_instance_cache"): # pragma: no cover
|
| 59 |
+
# debug option for analysing fork/spawn conditions
|
| 60 |
+
cls._cache = weakref.WeakValueDictionary()
|
| 61 |
+
else:
|
| 62 |
+
cls._cache = {}
|
| 63 |
+
cls._pid = os.getpid()
|
| 64 |
+
|
| 65 |
+
def __call__(cls, *args, **kwargs):
|
| 66 |
+
kwargs = apply_config(cls, kwargs)
|
| 67 |
+
extra_tokens = tuple(
|
| 68 |
+
getattr(cls, attr, None) for attr in cls._extra_tokenize_attributes
|
| 69 |
+
)
|
| 70 |
+
strip_tokenize_options = {
|
| 71 |
+
k: kwargs.pop(k) for k in cls._strip_tokenize_options if k in kwargs
|
| 72 |
+
}
|
| 73 |
+
token = tokenize(
|
| 74 |
+
cls, cls._pid, threading.get_ident(), *args, *extra_tokens, **kwargs
|
| 75 |
+
)
|
| 76 |
+
skip = kwargs.pop("skip_instance_cache", False)
|
| 77 |
+
if os.getpid() != cls._pid:
|
| 78 |
+
cls._cache.clear()
|
| 79 |
+
cls._pid = os.getpid()
|
| 80 |
+
if not skip and cls.cachable and token in cls._cache:
|
| 81 |
+
cls._latest = token
|
| 82 |
+
return cls._cache[token]
|
| 83 |
+
else:
|
| 84 |
+
obj = super().__call__(*args, **kwargs, **strip_tokenize_options)
|
| 85 |
+
# Setting _fs_token here causes some static linters to complain.
|
| 86 |
+
obj._fs_token_ = token
|
| 87 |
+
obj.storage_args = args
|
| 88 |
+
obj.storage_options = kwargs
|
| 89 |
+
if obj.async_impl and obj.mirror_sync_methods:
|
| 90 |
+
from .asyn import mirror_sync_methods
|
| 91 |
+
|
| 92 |
+
mirror_sync_methods(obj)
|
| 93 |
+
|
| 94 |
+
if cls.cachable and not skip:
|
| 95 |
+
cls._latest = token
|
| 96 |
+
cls._cache[token] = obj
|
| 97 |
+
return obj
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
class AbstractFileSystem(metaclass=_Cached):
|
| 101 |
+
"""
|
| 102 |
+
An abstract super-class for pythonic file-systems
|
| 103 |
+
|
| 104 |
+
Implementations are expected to be compatible with or, better, subclass
|
| 105 |
+
from here.
|
| 106 |
+
"""
|
| 107 |
+
|
| 108 |
+
cachable = True # this class can be cached, instances reused
|
| 109 |
+
_cached = False
|
| 110 |
+
blocksize = 2**22
|
| 111 |
+
sep = "/"
|
| 112 |
+
protocol: ClassVar[str | tuple[str, ...]] = "abstract"
|
| 113 |
+
_latest = None
|
| 114 |
+
async_impl = False
|
| 115 |
+
mirror_sync_methods = False
|
| 116 |
+
root_marker = "" # For some FSs, may require leading '/' or other character
|
| 117 |
+
transaction_type = Transaction
|
| 118 |
+
|
| 119 |
+
#: Extra *class attributes* that should be considered when hashing.
|
| 120 |
+
_extra_tokenize_attributes = ()
|
| 121 |
+
#: *storage options* that should not be considered when hashing.
|
| 122 |
+
_strip_tokenize_options = ()
|
| 123 |
+
|
| 124 |
+
# Set by _Cached metaclass
|
| 125 |
+
storage_args: tuple[Any, ...]
|
| 126 |
+
storage_options: dict[str, Any]
|
| 127 |
+
|
| 128 |
+
def __init__(self, *args, **storage_options):
|
| 129 |
+
"""Create and configure file-system instance
|
| 130 |
+
|
| 131 |
+
Instances may be cachable, so if similar enough arguments are seen
|
| 132 |
+
a new instance is not required. The token attribute exists to allow
|
| 133 |
+
implementations to cache instances if they wish.
|
| 134 |
+
|
| 135 |
+
A reasonable default should be provided if there are no arguments.
|
| 136 |
+
|
| 137 |
+
Subclasses should call this method.
|
| 138 |
+
|
| 139 |
+
Parameters
|
| 140 |
+
----------
|
| 141 |
+
use_listings_cache, listings_expiry_time, max_paths:
|
| 142 |
+
passed to ``DirCache``, if the implementation supports
|
| 143 |
+
directory listing caching. Pass use_listings_cache=False
|
| 144 |
+
to disable such caching.
|
| 145 |
+
skip_instance_cache: bool
|
| 146 |
+
If this is a cachable implementation, pass True here to force
|
| 147 |
+
creating a new instance even if a matching instance exists, and prevent
|
| 148 |
+
storing this instance.
|
| 149 |
+
asynchronous: bool
|
| 150 |
+
loop: asyncio-compatible IOLoop or None
|
| 151 |
+
"""
|
| 152 |
+
if self._cached:
|
| 153 |
+
# reusing instance, don't change
|
| 154 |
+
return
|
| 155 |
+
self._cached = True
|
| 156 |
+
self._intrans = False
|
| 157 |
+
self._transaction = None
|
| 158 |
+
self._invalidated_caches_in_transaction = []
|
| 159 |
+
self.dircache = DirCache(**storage_options)
|
| 160 |
+
|
| 161 |
+
if storage_options.pop("add_docs", None):
|
| 162 |
+
warnings.warn("add_docs is no longer supported.", FutureWarning)
|
| 163 |
+
|
| 164 |
+
if storage_options.pop("add_aliases", None):
|
| 165 |
+
warnings.warn("add_aliases has been removed.", FutureWarning)
|
| 166 |
+
# This is set in _Cached
|
| 167 |
+
self._fs_token_ = None
|
| 168 |
+
|
| 169 |
+
@property
|
| 170 |
+
def fsid(self):
|
| 171 |
+
"""Persistent filesystem id that can be used to compare filesystems
|
| 172 |
+
across sessions.
|
| 173 |
+
"""
|
| 174 |
+
raise NotImplementedError
|
| 175 |
+
|
| 176 |
+
@property
|
| 177 |
+
def _fs_token(self):
|
| 178 |
+
return self._fs_token_
|
| 179 |
+
|
| 180 |
+
def __dask_tokenize__(self):
|
| 181 |
+
return self._fs_token
|
| 182 |
+
|
| 183 |
+
def __hash__(self):
|
| 184 |
+
return int(self._fs_token, 16)
|
| 185 |
+
|
| 186 |
+
def __eq__(self, other):
|
| 187 |
+
return isinstance(other, type(self)) and self._fs_token == other._fs_token
|
| 188 |
+
|
| 189 |
+
def __reduce__(self):
|
| 190 |
+
return make_instance, (type(self), self.storage_args, self.storage_options)
|
| 191 |
+
|
| 192 |
+
@classmethod
|
| 193 |
+
def _strip_protocol(cls, path):
|
| 194 |
+
"""Turn path from fully-qualified to file-system-specific
|
| 195 |
+
|
| 196 |
+
May require FS-specific handling, e.g., for relative paths or links.
|
| 197 |
+
"""
|
| 198 |
+
if isinstance(path, list):
|
| 199 |
+
return [cls._strip_protocol(p) for p in path]
|
| 200 |
+
path = stringify_path(path)
|
| 201 |
+
protos = (cls.protocol,) if isinstance(cls.protocol, str) else cls.protocol
|
| 202 |
+
for protocol in protos:
|
| 203 |
+
if path.startswith(protocol + "://"):
|
| 204 |
+
path = path[len(protocol) + 3 :]
|
| 205 |
+
elif path.startswith(protocol + "::"):
|
| 206 |
+
path = path[len(protocol) + 2 :]
|
| 207 |
+
path = path.rstrip("/")
|
| 208 |
+
# use of root_marker to make minimum required path, e.g., "/"
|
| 209 |
+
return path or cls.root_marker
|
| 210 |
+
|
| 211 |
+
def unstrip_protocol(self, name: str) -> str:
|
| 212 |
+
"""Format FS-specific path to generic, including protocol"""
|
| 213 |
+
protos = (self.protocol,) if isinstance(self.protocol, str) else self.protocol
|
| 214 |
+
for protocol in protos:
|
| 215 |
+
if name.startswith(f"{protocol}://"):
|
| 216 |
+
return name
|
| 217 |
+
return f"{protos[0]}://{name}"
|
| 218 |
+
|
| 219 |
+
@staticmethod
|
| 220 |
+
def _get_kwargs_from_urls(path):
|
| 221 |
+
"""If kwargs can be encoded in the paths, extract them here
|
| 222 |
+
|
| 223 |
+
This should happen before instantiation of the class; incoming paths
|
| 224 |
+
then should be amended to strip the options in methods.
|
| 225 |
+
|
| 226 |
+
Examples may look like an sftp path "sftp://user@host:/my/path", where
|
| 227 |
+
the user and host should become kwargs and later get stripped.
|
| 228 |
+
"""
|
| 229 |
+
# by default, nothing happens
|
| 230 |
+
return {}
|
| 231 |
+
|
| 232 |
+
@classmethod
|
| 233 |
+
def current(cls):
|
| 234 |
+
"""Return the most recently instantiated FileSystem
|
| 235 |
+
|
| 236 |
+
If no instance has been created, then create one with defaults
|
| 237 |
+
"""
|
| 238 |
+
if cls._latest in cls._cache:
|
| 239 |
+
return cls._cache[cls._latest]
|
| 240 |
+
return cls()
|
| 241 |
+
|
| 242 |
+
@property
|
| 243 |
+
def transaction(self):
|
| 244 |
+
"""A context within which files are committed together upon exit
|
| 245 |
+
|
| 246 |
+
Requires the file class to implement `.commit()` and `.discard()`
|
| 247 |
+
for the normal and exception cases.
|
| 248 |
+
"""
|
| 249 |
+
if self._transaction is None:
|
| 250 |
+
self._transaction = self.transaction_type(self)
|
| 251 |
+
return self._transaction
|
| 252 |
+
|
| 253 |
+
def start_transaction(self):
|
| 254 |
+
"""Begin write transaction for deferring files, non-context version"""
|
| 255 |
+
self._intrans = True
|
| 256 |
+
self._transaction = self.transaction_type(self)
|
| 257 |
+
return self.transaction
|
| 258 |
+
|
| 259 |
+
def end_transaction(self):
|
| 260 |
+
"""Finish write transaction, non-context version"""
|
| 261 |
+
self.transaction.complete()
|
| 262 |
+
self._transaction = None
|
| 263 |
+
# The invalid cache must be cleared after the transaction is completed.
|
| 264 |
+
for path in self._invalidated_caches_in_transaction:
|
| 265 |
+
self.invalidate_cache(path)
|
| 266 |
+
self._invalidated_caches_in_transaction.clear()
|
| 267 |
+
|
| 268 |
+
def invalidate_cache(self, path=None):
|
| 269 |
+
"""
|
| 270 |
+
Discard any cached directory information
|
| 271 |
+
|
| 272 |
+
Parameters
|
| 273 |
+
----------
|
| 274 |
+
path: string or None
|
| 275 |
+
If None, clear all listings cached else listings at or under given
|
| 276 |
+
path.
|
| 277 |
+
"""
|
| 278 |
+
# Not necessary to implement invalidation mechanism, may have no cache.
|
| 279 |
+
# But if have, you should call this method of parent class from your
|
| 280 |
+
# subclass to ensure expiring caches after transacations correctly.
|
| 281 |
+
# See the implementation of FTPFileSystem in ftp.py
|
| 282 |
+
if self._intrans:
|
| 283 |
+
self._invalidated_caches_in_transaction.append(path)
|
| 284 |
+
|
| 285 |
+
def mkdir(self, path, create_parents=True, **kwargs):
|
| 286 |
+
"""
|
| 287 |
+
Create directory entry at path
|
| 288 |
+
|
| 289 |
+
For systems that don't have true directories, may create an for
|
| 290 |
+
this instance only and not touch the real filesystem
|
| 291 |
+
|
| 292 |
+
Parameters
|
| 293 |
+
----------
|
| 294 |
+
path: str
|
| 295 |
+
location
|
| 296 |
+
create_parents: bool
|
| 297 |
+
if True, this is equivalent to ``makedirs``
|
| 298 |
+
kwargs:
|
| 299 |
+
may be permissions, etc.
|
| 300 |
+
"""
|
| 301 |
+
pass # not necessary to implement, may not have directories
|
| 302 |
+
|
| 303 |
+
def makedirs(self, path, exist_ok=False):
|
| 304 |
+
"""Recursively make directories
|
| 305 |
+
|
| 306 |
+
Creates directory at path and any intervening required directories.
|
| 307 |
+
Raises exception if, for instance, the path already exists but is a
|
| 308 |
+
file.
|
| 309 |
+
|
| 310 |
+
Parameters
|
| 311 |
+
----------
|
| 312 |
+
path: str
|
| 313 |
+
leaf directory name
|
| 314 |
+
exist_ok: bool (False)
|
| 315 |
+
If False, will error if the target already exists
|
| 316 |
+
"""
|
| 317 |
+
pass # not necessary to implement, may not have directories
|
| 318 |
+
|
| 319 |
+
def rmdir(self, path):
|
| 320 |
+
"""Remove a directory, if empty"""
|
| 321 |
+
pass # not necessary to implement, may not have directories
|
| 322 |
+
|
| 323 |
+
def ls(self, path, detail=True, **kwargs):
|
| 324 |
+
"""List objects at path.
|
| 325 |
+
|
| 326 |
+
This should include subdirectories and files at that location. The
|
| 327 |
+
difference between a file and a directory must be clear when details
|
| 328 |
+
are requested.
|
| 329 |
+
|
| 330 |
+
The specific keys, or perhaps a FileInfo class, or similar, is TBD,
|
| 331 |
+
but must be consistent across implementations.
|
| 332 |
+
Must include:
|
| 333 |
+
|
| 334 |
+
- full path to the entry (without protocol)
|
| 335 |
+
- size of the entry, in bytes. If the value cannot be determined, will
|
| 336 |
+
be ``None``.
|
| 337 |
+
- type of entry, "file", "directory" or other
|
| 338 |
+
|
| 339 |
+
Additional information
|
| 340 |
+
may be present, appropriate to the file-system, e.g., generation,
|
| 341 |
+
checksum, etc.
|
| 342 |
+
|
| 343 |
+
May use refresh=True|False to allow use of self._ls_from_cache to
|
| 344 |
+
check for a saved listing and avoid calling the backend. This would be
|
| 345 |
+
common where listing may be expensive.
|
| 346 |
+
|
| 347 |
+
Parameters
|
| 348 |
+
----------
|
| 349 |
+
path: str
|
| 350 |
+
detail: bool
|
| 351 |
+
if True, gives a list of dictionaries, where each is the same as
|
| 352 |
+
the result of ``info(path)``. If False, gives a list of paths
|
| 353 |
+
(str).
|
| 354 |
+
kwargs: may have additional backend-specific options, such as version
|
| 355 |
+
information
|
| 356 |
+
|
| 357 |
+
Returns
|
| 358 |
+
-------
|
| 359 |
+
List of strings if detail is False, or list of directory information
|
| 360 |
+
dicts if detail is True.
|
| 361 |
+
"""
|
| 362 |
+
raise NotImplementedError
|
| 363 |
+
|
| 364 |
+
def _ls_from_cache(self, path):
|
| 365 |
+
"""Check cache for listing
|
| 366 |
+
|
| 367 |
+
Returns listing, if found (may be empty list for a directly that exists
|
| 368 |
+
but contains nothing), None if not in cache.
|
| 369 |
+
"""
|
| 370 |
+
parent = self._parent(path)
|
| 371 |
+
try:
|
| 372 |
+
return self.dircache[path.rstrip("/")]
|
| 373 |
+
except KeyError:
|
| 374 |
+
pass
|
| 375 |
+
try:
|
| 376 |
+
files = [
|
| 377 |
+
f
|
| 378 |
+
for f in self.dircache[parent]
|
| 379 |
+
if f["name"] == path
|
| 380 |
+
or (f["name"] == path.rstrip("/") and f["type"] == "directory")
|
| 381 |
+
]
|
| 382 |
+
if len(files) == 0:
|
| 383 |
+
# parent dir was listed but did not contain this file
|
| 384 |
+
raise FileNotFoundError(path)
|
| 385 |
+
return files
|
| 386 |
+
except KeyError:
|
| 387 |
+
pass
|
| 388 |
+
|
| 389 |
+
def walk(self, path, maxdepth=None, topdown=True, on_error="omit", **kwargs):
|
| 390 |
+
"""Return all files under the given path.
|
| 391 |
+
|
| 392 |
+
List all files, recursing into subdirectories; output is iterator-style,
|
| 393 |
+
like ``os.walk()``. For a simple list of files, ``find()`` is available.
|
| 394 |
+
|
| 395 |
+
When topdown is True, the caller can modify the dirnames list in-place (perhaps
|
| 396 |
+
using del or slice assignment), and walk() will
|
| 397 |
+
only recurse into the subdirectories whose names remain in dirnames;
|
| 398 |
+
this can be used to prune the search, impose a specific order of visiting,
|
| 399 |
+
or even to inform walk() about directories the caller creates or renames before
|
| 400 |
+
it resumes walk() again.
|
| 401 |
+
Modifying dirnames when topdown is False has no effect. (see os.walk)
|
| 402 |
+
|
| 403 |
+
Note that the "files" outputted will include anything that is not
|
| 404 |
+
a directory, such as links.
|
| 405 |
+
|
| 406 |
+
Parameters
|
| 407 |
+
----------
|
| 408 |
+
path: str
|
| 409 |
+
Root to recurse into
|
| 410 |
+
maxdepth: int
|
| 411 |
+
Maximum recursion depth. None means limitless, but not recommended
|
| 412 |
+
on link-based file-systems.
|
| 413 |
+
topdown: bool (True)
|
| 414 |
+
Whether to walk the directory tree from the top downwards or from
|
| 415 |
+
the bottom upwards.
|
| 416 |
+
on_error: "omit", "raise", a callable
|
| 417 |
+
if omit (default), path with exception will simply be empty;
|
| 418 |
+
If raise, an underlying exception will be raised;
|
| 419 |
+
if callable, it will be called with a single OSError instance as argument
|
| 420 |
+
kwargs: passed to ``ls``
|
| 421 |
+
"""
|
| 422 |
+
if maxdepth is not None and maxdepth < 1:
|
| 423 |
+
raise ValueError("maxdepth must be at least 1")
|
| 424 |
+
|
| 425 |
+
path = self._strip_protocol(path)
|
| 426 |
+
full_dirs = {}
|
| 427 |
+
dirs = {}
|
| 428 |
+
files = {}
|
| 429 |
+
|
| 430 |
+
detail = kwargs.pop("detail", False)
|
| 431 |
+
try:
|
| 432 |
+
listing = self.ls(path, detail=True, **kwargs)
|
| 433 |
+
except (FileNotFoundError, OSError) as e:
|
| 434 |
+
if on_error == "raise":
|
| 435 |
+
raise
|
| 436 |
+
if callable(on_error):
|
| 437 |
+
on_error(e)
|
| 438 |
+
return
|
| 439 |
+
|
| 440 |
+
for info in listing:
|
| 441 |
+
# each info name must be at least [path]/part , but here
|
| 442 |
+
# we check also for names like [path]/part/
|
| 443 |
+
pathname = info["name"].rstrip("/")
|
| 444 |
+
name = pathname.rsplit("/", 1)[-1]
|
| 445 |
+
if info["type"] == "directory" and pathname != path:
|
| 446 |
+
# do not include "self" path
|
| 447 |
+
full_dirs[name] = pathname
|
| 448 |
+
dirs[name] = info
|
| 449 |
+
elif pathname == path:
|
| 450 |
+
# file-like with same name as give path
|
| 451 |
+
files[""] = info
|
| 452 |
+
else:
|
| 453 |
+
files[name] = info
|
| 454 |
+
|
| 455 |
+
if not detail:
|
| 456 |
+
dirs = list(dirs)
|
| 457 |
+
files = list(files)
|
| 458 |
+
|
| 459 |
+
if topdown:
|
| 460 |
+
# Yield before recursion if walking top down
|
| 461 |
+
yield path, dirs, files
|
| 462 |
+
|
| 463 |
+
if maxdepth is not None:
|
| 464 |
+
maxdepth -= 1
|
| 465 |
+
if maxdepth < 1:
|
| 466 |
+
if not topdown:
|
| 467 |
+
yield path, dirs, files
|
| 468 |
+
return
|
| 469 |
+
|
| 470 |
+
for d in dirs:
|
| 471 |
+
yield from self.walk(
|
| 472 |
+
full_dirs[d],
|
| 473 |
+
maxdepth=maxdepth,
|
| 474 |
+
detail=detail,
|
| 475 |
+
topdown=topdown,
|
| 476 |
+
**kwargs,
|
| 477 |
+
)
|
| 478 |
+
|
| 479 |
+
if not topdown:
|
| 480 |
+
# Yield after recursion if walking bottom up
|
| 481 |
+
yield path, dirs, files
|
| 482 |
+
|
| 483 |
+
def find(self, path, maxdepth=None, withdirs=False, detail=False, **kwargs):
|
| 484 |
+
"""List all files below path.
|
| 485 |
+
|
| 486 |
+
Like posix ``find`` command without conditions
|
| 487 |
+
|
| 488 |
+
Parameters
|
| 489 |
+
----------
|
| 490 |
+
path : str
|
| 491 |
+
maxdepth: int or None
|
| 492 |
+
If not None, the maximum number of levels to descend
|
| 493 |
+
withdirs: bool
|
| 494 |
+
Whether to include directory paths in the output. This is True
|
| 495 |
+
when used by glob, but users usually only want files.
|
| 496 |
+
kwargs are passed to ``ls``.
|
| 497 |
+
"""
|
| 498 |
+
# TODO: allow equivalent of -name parameter
|
| 499 |
+
path = self._strip_protocol(path)
|
| 500 |
+
out = {}
|
| 501 |
+
|
| 502 |
+
# Add the root directory if withdirs is requested
|
| 503 |
+
# This is needed for posix glob compliance
|
| 504 |
+
if withdirs and path != "" and self.isdir(path):
|
| 505 |
+
out[path] = self.info(path)
|
| 506 |
+
|
| 507 |
+
for _, dirs, files in self.walk(path, maxdepth, detail=True, **kwargs):
|
| 508 |
+
if withdirs:
|
| 509 |
+
files.update(dirs)
|
| 510 |
+
out.update({info["name"]: info for name, info in files.items()})
|
| 511 |
+
if not out and self.isfile(path):
|
| 512 |
+
# walk works on directories, but find should also return [path]
|
| 513 |
+
# when path happens to be a file
|
| 514 |
+
out[path] = {}
|
| 515 |
+
names = sorted(out)
|
| 516 |
+
if not detail:
|
| 517 |
+
return names
|
| 518 |
+
else:
|
| 519 |
+
return {name: out[name] for name in names}
|
| 520 |
+
|
| 521 |
+
def du(self, path, total=True, maxdepth=None, withdirs=False, **kwargs):
|
| 522 |
+
"""Space used by files and optionally directories within a path
|
| 523 |
+
|
| 524 |
+
Directory size does not include the size of its contents.
|
| 525 |
+
|
| 526 |
+
Parameters
|
| 527 |
+
----------
|
| 528 |
+
path: str
|
| 529 |
+
total: bool
|
| 530 |
+
Whether to sum all the file sizes
|
| 531 |
+
maxdepth: int or None
|
| 532 |
+
Maximum number of directory levels to descend, None for unlimited.
|
| 533 |
+
withdirs: bool
|
| 534 |
+
Whether to include directory paths in the output.
|
| 535 |
+
kwargs: passed to ``find``
|
| 536 |
+
|
| 537 |
+
Returns
|
| 538 |
+
-------
|
| 539 |
+
Dict of {path: size} if total=False, or int otherwise, where numbers
|
| 540 |
+
refer to bytes used.
|
| 541 |
+
"""
|
| 542 |
+
sizes = {}
|
| 543 |
+
if withdirs and self.isdir(path):
|
| 544 |
+
# Include top-level directory in output
|
| 545 |
+
info = self.info(path)
|
| 546 |
+
sizes[info["name"]] = info["size"]
|
| 547 |
+
for f in self.find(path, maxdepth=maxdepth, withdirs=withdirs, **kwargs):
|
| 548 |
+
info = self.info(f)
|
| 549 |
+
sizes[info["name"]] = info["size"]
|
| 550 |
+
if total:
|
| 551 |
+
return sum(sizes.values())
|
| 552 |
+
else:
|
| 553 |
+
return sizes
|
| 554 |
+
|
| 555 |
+
def glob(self, path, maxdepth=None, **kwargs):
|
| 556 |
+
"""Find files by glob-matching.
|
| 557 |
+
|
| 558 |
+
Pattern matching capabilities for finding files that match the given pattern.
|
| 559 |
+
|
| 560 |
+
Parameters
|
| 561 |
+
----------
|
| 562 |
+
path: str
|
| 563 |
+
The glob pattern to match against
|
| 564 |
+
maxdepth: int or None
|
| 565 |
+
Maximum depth for ``'**'`` patterns. Applied on the first ``'**'`` found.
|
| 566 |
+
Must be at least 1 if provided.
|
| 567 |
+
kwargs:
|
| 568 |
+
Additional arguments passed to ``find`` (e.g., detail=True)
|
| 569 |
+
|
| 570 |
+
Returns
|
| 571 |
+
-------
|
| 572 |
+
List of matched paths, or dict of paths and their info if detail=True
|
| 573 |
+
|
| 574 |
+
Notes
|
| 575 |
+
-----
|
| 576 |
+
Supported patterns:
|
| 577 |
+
- '*': Matches any sequence of characters within a single directory level
|
| 578 |
+
- ``'**'``: Matches any number of directory levels (must be an entire path component)
|
| 579 |
+
- '?': Matches exactly one character
|
| 580 |
+
- '[abc]': Matches any character in the set
|
| 581 |
+
- '[a-z]': Matches any character in the range
|
| 582 |
+
- '[!abc]': Matches any character NOT in the set
|
| 583 |
+
|
| 584 |
+
Special behaviors:
|
| 585 |
+
- If the path ends with '/', only folders are returned
|
| 586 |
+
- Consecutive '*' characters are compressed into a single '*'
|
| 587 |
+
- Empty brackets '[]' never match anything
|
| 588 |
+
- Negated empty brackets '[!]' match any single character
|
| 589 |
+
- Special characters in character classes are escaped properly
|
| 590 |
+
|
| 591 |
+
Limitations:
|
| 592 |
+
- ``'**'`` must be a complete path component (e.g., ``'a/**/b'``, not ``'a**b'``)
|
| 593 |
+
- No brace expansion ('{a,b}.txt')
|
| 594 |
+
- No extended glob patterns ('+(pattern)', '!(pattern)')
|
| 595 |
+
"""
|
| 596 |
+
if maxdepth is not None and maxdepth < 1:
|
| 597 |
+
raise ValueError("maxdepth must be at least 1")
|
| 598 |
+
|
| 599 |
+
import re
|
| 600 |
+
|
| 601 |
+
seps = (os.path.sep, os.path.altsep) if os.path.altsep else (os.path.sep,)
|
| 602 |
+
ends_with_sep = path.endswith(seps) # _strip_protocol strips trailing slash
|
| 603 |
+
path = self._strip_protocol(path)
|
| 604 |
+
append_slash_to_dirname = ends_with_sep or path.endswith(
|
| 605 |
+
tuple(sep + "**" for sep in seps)
|
| 606 |
+
)
|
| 607 |
+
idx_star = path.find("*") if path.find("*") >= 0 else len(path)
|
| 608 |
+
idx_qmark = path.find("?") if path.find("?") >= 0 else len(path)
|
| 609 |
+
idx_brace = path.find("[") if path.find("[") >= 0 else len(path)
|
| 610 |
+
|
| 611 |
+
min_idx = min(idx_star, idx_qmark, idx_brace)
|
| 612 |
+
|
| 613 |
+
detail = kwargs.pop("detail", False)
|
| 614 |
+
withdirs = kwargs.pop("withdirs", True)
|
| 615 |
+
|
| 616 |
+
if not has_magic(path):
|
| 617 |
+
if self.exists(path, **kwargs):
|
| 618 |
+
if not detail:
|
| 619 |
+
return [path]
|
| 620 |
+
else:
|
| 621 |
+
return {path: self.info(path, **kwargs)}
|
| 622 |
+
else:
|
| 623 |
+
if not detail:
|
| 624 |
+
return [] # glob of non-existent returns empty
|
| 625 |
+
else:
|
| 626 |
+
return {}
|
| 627 |
+
elif "/" in path[:min_idx]:
|
| 628 |
+
min_idx = path[:min_idx].rindex("/")
|
| 629 |
+
root = path[: min_idx + 1]
|
| 630 |
+
depth = path[min_idx + 1 :].count("/") + 1
|
| 631 |
+
else:
|
| 632 |
+
root = ""
|
| 633 |
+
depth = path[min_idx + 1 :].count("/") + 1
|
| 634 |
+
|
| 635 |
+
if "**" in path:
|
| 636 |
+
if maxdepth is not None:
|
| 637 |
+
idx_double_stars = path.find("**")
|
| 638 |
+
depth_double_stars = path[idx_double_stars:].count("/") + 1
|
| 639 |
+
depth = depth - depth_double_stars + maxdepth
|
| 640 |
+
else:
|
| 641 |
+
depth = None
|
| 642 |
+
|
| 643 |
+
allpaths = self.find(
|
| 644 |
+
root, maxdepth=depth, withdirs=withdirs, detail=True, **kwargs
|
| 645 |
+
)
|
| 646 |
+
|
| 647 |
+
pattern = glob_translate(path + ("/" if ends_with_sep else ""))
|
| 648 |
+
pattern = re.compile(pattern)
|
| 649 |
+
|
| 650 |
+
out = {
|
| 651 |
+
p: info
|
| 652 |
+
for p, info in sorted(allpaths.items())
|
| 653 |
+
if pattern.match(
|
| 654 |
+
p + "/"
|
| 655 |
+
if append_slash_to_dirname and info["type"] == "directory"
|
| 656 |
+
else p
|
| 657 |
+
)
|
| 658 |
+
}
|
| 659 |
+
|
| 660 |
+
if detail:
|
| 661 |
+
return out
|
| 662 |
+
else:
|
| 663 |
+
return list(out)
|
| 664 |
+
|
| 665 |
+
def exists(self, path, **kwargs):
|
| 666 |
+
"""Is there a file at the given path"""
|
| 667 |
+
try:
|
| 668 |
+
self.info(path, **kwargs)
|
| 669 |
+
return True
|
| 670 |
+
except: # noqa: E722
|
| 671 |
+
# any exception allowed bar FileNotFoundError?
|
| 672 |
+
return False
|
| 673 |
+
|
| 674 |
+
def lexists(self, path, **kwargs):
|
| 675 |
+
"""If there is a file at the given path (including
|
| 676 |
+
broken links)"""
|
| 677 |
+
return self.exists(path)
|
| 678 |
+
|
| 679 |
+
def info(self, path, **kwargs):
|
| 680 |
+
"""Give details of entry at path
|
| 681 |
+
|
| 682 |
+
Returns a single dictionary, with exactly the same information as ``ls``
|
| 683 |
+
would with ``detail=True``.
|
| 684 |
+
|
| 685 |
+
The default implementation calls ls and could be overridden by a
|
| 686 |
+
shortcut. kwargs are passed on to ```ls()``.
|
| 687 |
+
|
| 688 |
+
Some file systems might not be able to measure the file's size, in
|
| 689 |
+
which case, the returned dict will include ``'size': None``.
|
| 690 |
+
|
| 691 |
+
Returns
|
| 692 |
+
-------
|
| 693 |
+
dict with keys: name (full path in the FS), size (in bytes), type (file,
|
| 694 |
+
directory, or something else) and other FS-specific keys.
|
| 695 |
+
"""
|
| 696 |
+
path = self._strip_protocol(path)
|
| 697 |
+
out = self.ls(self._parent(path), detail=True, **kwargs)
|
| 698 |
+
out = [o for o in out if o["name"].rstrip("/") == path]
|
| 699 |
+
if out:
|
| 700 |
+
return out[0]
|
| 701 |
+
out = self.ls(path, detail=True, **kwargs)
|
| 702 |
+
path = path.rstrip("/")
|
| 703 |
+
out1 = [o for o in out if o["name"].rstrip("/") == path]
|
| 704 |
+
if len(out1) == 1:
|
| 705 |
+
if "size" not in out1[0]:
|
| 706 |
+
out1[0]["size"] = None
|
| 707 |
+
return out1[0]
|
| 708 |
+
elif len(out1) > 1 or out:
|
| 709 |
+
return {"name": path, "size": 0, "type": "directory"}
|
| 710 |
+
else:
|
| 711 |
+
raise FileNotFoundError(path)
|
| 712 |
+
|
| 713 |
+
def checksum(self, path):
|
| 714 |
+
"""Unique value for current version of file
|
| 715 |
+
|
| 716 |
+
If the checksum is the same from one moment to another, the contents
|
| 717 |
+
are guaranteed to be the same. If the checksum changes, the contents
|
| 718 |
+
*might* have changed.
|
| 719 |
+
|
| 720 |
+
This should normally be overridden; default will probably capture
|
| 721 |
+
creation/modification timestamp (which would be good) or maybe
|
| 722 |
+
access timestamp (which would be bad)
|
| 723 |
+
"""
|
| 724 |
+
return int(tokenize(self.info(path)), 16)
|
| 725 |
+
|
| 726 |
+
def size(self, path):
|
| 727 |
+
"""Size in bytes of file"""
|
| 728 |
+
return self.info(path).get("size", None)
|
| 729 |
+
|
| 730 |
+
def sizes(self, paths):
|
| 731 |
+
"""Size in bytes of each file in a list of paths"""
|
| 732 |
+
return [self.size(p) for p in paths]
|
| 733 |
+
|
| 734 |
+
def isdir(self, path):
|
| 735 |
+
"""Is this entry directory-like?"""
|
| 736 |
+
try:
|
| 737 |
+
return self.info(path)["type"] == "directory"
|
| 738 |
+
except OSError:
|
| 739 |
+
return False
|
| 740 |
+
|
| 741 |
+
def isfile(self, path):
|
| 742 |
+
"""Is this entry file-like?"""
|
| 743 |
+
try:
|
| 744 |
+
return self.info(path)["type"] == "file"
|
| 745 |
+
except: # noqa: E722
|
| 746 |
+
return False
|
| 747 |
+
|
| 748 |
+
def read_text(self, path, encoding=None, errors=None, newline=None, **kwargs):
|
| 749 |
+
"""Get the contents of the file as a string.
|
| 750 |
+
|
| 751 |
+
Parameters
|
| 752 |
+
----------
|
| 753 |
+
path: str
|
| 754 |
+
URL of file on this filesystems
|
| 755 |
+
encoding, errors, newline: same as `open`.
|
| 756 |
+
"""
|
| 757 |
+
with self.open(
|
| 758 |
+
path,
|
| 759 |
+
mode="r",
|
| 760 |
+
encoding=encoding,
|
| 761 |
+
errors=errors,
|
| 762 |
+
newline=newline,
|
| 763 |
+
**kwargs,
|
| 764 |
+
) as f:
|
| 765 |
+
return f.read()
|
| 766 |
+
|
| 767 |
+
def write_text(
|
| 768 |
+
self, path, value, encoding=None, errors=None, newline=None, **kwargs
|
| 769 |
+
):
|
| 770 |
+
"""Write the text to the given file.
|
| 771 |
+
|
| 772 |
+
An existing file will be overwritten.
|
| 773 |
+
|
| 774 |
+
Parameters
|
| 775 |
+
----------
|
| 776 |
+
path: str
|
| 777 |
+
URL of file on this filesystems
|
| 778 |
+
value: str
|
| 779 |
+
Text to write.
|
| 780 |
+
encoding, errors, newline: same as `open`.
|
| 781 |
+
"""
|
| 782 |
+
with self.open(
|
| 783 |
+
path,
|
| 784 |
+
mode="w",
|
| 785 |
+
encoding=encoding,
|
| 786 |
+
errors=errors,
|
| 787 |
+
newline=newline,
|
| 788 |
+
**kwargs,
|
| 789 |
+
) as f:
|
| 790 |
+
return f.write(value)
|
| 791 |
+
|
| 792 |
+
def cat_file(self, path, start=None, end=None, **kwargs):
|
| 793 |
+
"""Get the content of a file
|
| 794 |
+
|
| 795 |
+
Parameters
|
| 796 |
+
----------
|
| 797 |
+
path: URL of file on this filesystems
|
| 798 |
+
start, end: int
|
| 799 |
+
Bytes limits of the read. If negative, backwards from end,
|
| 800 |
+
like usual python slices. Either can be None for start or
|
| 801 |
+
end of file, respectively
|
| 802 |
+
kwargs: passed to ``open()``.
|
| 803 |
+
"""
|
| 804 |
+
# explicitly set buffering off?
|
| 805 |
+
with self.open(path, "rb", **kwargs) as f:
|
| 806 |
+
if start is not None:
|
| 807 |
+
if start >= 0:
|
| 808 |
+
f.seek(start)
|
| 809 |
+
else:
|
| 810 |
+
f.seek(max(0, f.size + start))
|
| 811 |
+
if end is not None:
|
| 812 |
+
if end < 0:
|
| 813 |
+
end = f.size + end
|
| 814 |
+
return f.read(end - f.tell())
|
| 815 |
+
return f.read()
|
| 816 |
+
|
| 817 |
+
def pipe_file(self, path, value, mode="overwrite", **kwargs):
|
| 818 |
+
"""Set the bytes of given file"""
|
| 819 |
+
if mode == "create" and self.exists(path):
|
| 820 |
+
# non-atomic but simple way; or could use "xb" in open(), which is likely
|
| 821 |
+
# not as well supported
|
| 822 |
+
raise FileExistsError
|
| 823 |
+
with self.open(path, "wb", **kwargs) as f:
|
| 824 |
+
f.write(value)
|
| 825 |
+
|
| 826 |
+
def pipe(self, path, value=None, **kwargs):
|
| 827 |
+
"""Put value into path
|
| 828 |
+
|
| 829 |
+
(counterpart to ``cat``)
|
| 830 |
+
|
| 831 |
+
Parameters
|
| 832 |
+
----------
|
| 833 |
+
path: string or dict(str, bytes)
|
| 834 |
+
If a string, a single remote location to put ``value`` bytes; if a dict,
|
| 835 |
+
a mapping of {path: bytesvalue}.
|
| 836 |
+
value: bytes, optional
|
| 837 |
+
If using a single path, these are the bytes to put there. Ignored if
|
| 838 |
+
``path`` is a dict
|
| 839 |
+
"""
|
| 840 |
+
if isinstance(path, str):
|
| 841 |
+
self.pipe_file(self._strip_protocol(path), value, **kwargs)
|
| 842 |
+
elif isinstance(path, dict):
|
| 843 |
+
for k, v in path.items():
|
| 844 |
+
self.pipe_file(self._strip_protocol(k), v, **kwargs)
|
| 845 |
+
else:
|
| 846 |
+
raise ValueError("path must be str or dict")
|
| 847 |
+
|
| 848 |
+
def cat_ranges(
|
| 849 |
+
self, paths, starts, ends, max_gap=None, on_error="return", **kwargs
|
| 850 |
+
):
|
| 851 |
+
"""Get the contents of byte ranges from one or more files
|
| 852 |
+
|
| 853 |
+
Parameters
|
| 854 |
+
----------
|
| 855 |
+
paths: list
|
| 856 |
+
A list of of filepaths on this filesystems
|
| 857 |
+
starts, ends: int or list
|
| 858 |
+
Bytes limits of the read. If using a single int, the same value will be
|
| 859 |
+
used to read all the specified files.
|
| 860 |
+
"""
|
| 861 |
+
if max_gap is not None:
|
| 862 |
+
raise NotImplementedError
|
| 863 |
+
if not isinstance(paths, list):
|
| 864 |
+
raise TypeError
|
| 865 |
+
if not isinstance(starts, list):
|
| 866 |
+
starts = [starts] * len(paths)
|
| 867 |
+
if not isinstance(ends, list):
|
| 868 |
+
ends = [ends] * len(paths)
|
| 869 |
+
if len(starts) != len(paths) or len(ends) != len(paths):
|
| 870 |
+
raise ValueError
|
| 871 |
+
out = []
|
| 872 |
+
for p, s, e in zip(paths, starts, ends):
|
| 873 |
+
try:
|
| 874 |
+
out.append(self.cat_file(p, s, e))
|
| 875 |
+
except Exception as e:
|
| 876 |
+
if on_error == "return":
|
| 877 |
+
out.append(e)
|
| 878 |
+
else:
|
| 879 |
+
raise
|
| 880 |
+
return out
|
| 881 |
+
|
| 882 |
+
def cat(self, path, recursive=False, on_error="raise", **kwargs):
|
| 883 |
+
"""Fetch (potentially multiple) paths' contents
|
| 884 |
+
|
| 885 |
+
Parameters
|
| 886 |
+
----------
|
| 887 |
+
recursive: bool
|
| 888 |
+
If True, assume the path(s) are directories, and get all the
|
| 889 |
+
contained files
|
| 890 |
+
on_error : "raise", "omit", "return"
|
| 891 |
+
If raise, an underlying exception will be raised (converted to KeyError
|
| 892 |
+
if the type is in self.missing_exceptions); if omit, keys with exception
|
| 893 |
+
will simply not be included in the output; if "return", all keys are
|
| 894 |
+
included in the output, but the value will be bytes or an exception
|
| 895 |
+
instance.
|
| 896 |
+
kwargs: passed to cat_file
|
| 897 |
+
|
| 898 |
+
Returns
|
| 899 |
+
-------
|
| 900 |
+
dict of {path: contents} if there are multiple paths
|
| 901 |
+
or the path has been otherwise expanded
|
| 902 |
+
"""
|
| 903 |
+
paths = self.expand_path(path, recursive=recursive, **kwargs)
|
| 904 |
+
if (
|
| 905 |
+
len(paths) > 1
|
| 906 |
+
or isinstance(path, list)
|
| 907 |
+
or paths[0] != self._strip_protocol(path)
|
| 908 |
+
):
|
| 909 |
+
out = {}
|
| 910 |
+
for path in paths:
|
| 911 |
+
try:
|
| 912 |
+
out[path] = self.cat_file(path, **kwargs)
|
| 913 |
+
except Exception as e:
|
| 914 |
+
if on_error == "raise":
|
| 915 |
+
raise
|
| 916 |
+
if on_error == "return":
|
| 917 |
+
out[path] = e
|
| 918 |
+
return out
|
| 919 |
+
else:
|
| 920 |
+
return self.cat_file(paths[0], **kwargs)
|
| 921 |
+
|
| 922 |
+
def get_file(self, rpath, lpath, callback=DEFAULT_CALLBACK, outfile=None, **kwargs):
|
| 923 |
+
"""Copy single remote file to local"""
|
| 924 |
+
from .implementations.local import LocalFileSystem
|
| 925 |
+
|
| 926 |
+
if isfilelike(lpath):
|
| 927 |
+
outfile = lpath
|
| 928 |
+
elif self.isdir(rpath):
|
| 929 |
+
os.makedirs(lpath, exist_ok=True)
|
| 930 |
+
return None
|
| 931 |
+
|
| 932 |
+
fs = LocalFileSystem(auto_mkdir=True)
|
| 933 |
+
fs.makedirs(fs._parent(lpath), exist_ok=True)
|
| 934 |
+
|
| 935 |
+
with self.open(rpath, "rb", **kwargs) as f1:
|
| 936 |
+
if outfile is None:
|
| 937 |
+
outfile = open(lpath, "wb")
|
| 938 |
+
|
| 939 |
+
try:
|
| 940 |
+
callback.set_size(getattr(f1, "size", None))
|
| 941 |
+
data = True
|
| 942 |
+
while data:
|
| 943 |
+
data = f1.read(self.blocksize)
|
| 944 |
+
segment_len = outfile.write(data)
|
| 945 |
+
if segment_len is None:
|
| 946 |
+
segment_len = len(data)
|
| 947 |
+
callback.relative_update(segment_len)
|
| 948 |
+
finally:
|
| 949 |
+
if not isfilelike(lpath):
|
| 950 |
+
outfile.close()
|
| 951 |
+
|
| 952 |
+
def get(
|
| 953 |
+
self,
|
| 954 |
+
rpath,
|
| 955 |
+
lpath,
|
| 956 |
+
recursive=False,
|
| 957 |
+
callback=DEFAULT_CALLBACK,
|
| 958 |
+
maxdepth=None,
|
| 959 |
+
**kwargs,
|
| 960 |
+
):
|
| 961 |
+
"""Copy file(s) to local.
|
| 962 |
+
|
| 963 |
+
Copies a specific file or tree of files (if recursive=True). If lpath
|
| 964 |
+
ends with a "/", it will be assumed to be a directory, and target files
|
| 965 |
+
will go within. Can submit a list of paths, which may be glob-patterns
|
| 966 |
+
and will be expanded.
|
| 967 |
+
|
| 968 |
+
Calls get_file for each source.
|
| 969 |
+
"""
|
| 970 |
+
if isinstance(lpath, list) and isinstance(rpath, list):
|
| 971 |
+
# No need to expand paths when both source and destination
|
| 972 |
+
# are provided as lists
|
| 973 |
+
rpaths = rpath
|
| 974 |
+
lpaths = lpath
|
| 975 |
+
else:
|
| 976 |
+
from .implementations.local import (
|
| 977 |
+
LocalFileSystem,
|
| 978 |
+
make_path_posix,
|
| 979 |
+
trailing_sep,
|
| 980 |
+
)
|
| 981 |
+
|
| 982 |
+
source_is_str = isinstance(rpath, str)
|
| 983 |
+
rpaths = self.expand_path(
|
| 984 |
+
rpath, recursive=recursive, maxdepth=maxdepth, **kwargs
|
| 985 |
+
)
|
| 986 |
+
if source_is_str and (not recursive or maxdepth is not None):
|
| 987 |
+
# Non-recursive glob does not copy directories
|
| 988 |
+
rpaths = [p for p in rpaths if not (trailing_sep(p) or self.isdir(p))]
|
| 989 |
+
if not rpaths:
|
| 990 |
+
return
|
| 991 |
+
|
| 992 |
+
if isinstance(lpath, str):
|
| 993 |
+
lpath = make_path_posix(lpath)
|
| 994 |
+
|
| 995 |
+
source_is_file = len(rpaths) == 1
|
| 996 |
+
dest_is_dir = isinstance(lpath, str) and (
|
| 997 |
+
trailing_sep(lpath) or LocalFileSystem().isdir(lpath)
|
| 998 |
+
)
|
| 999 |
+
|
| 1000 |
+
exists = source_is_str and (
|
| 1001 |
+
(has_magic(rpath) and source_is_file)
|
| 1002 |
+
or (not has_magic(rpath) and dest_is_dir and not trailing_sep(rpath))
|
| 1003 |
+
)
|
| 1004 |
+
lpaths = other_paths(
|
| 1005 |
+
rpaths,
|
| 1006 |
+
lpath,
|
| 1007 |
+
exists=exists,
|
| 1008 |
+
flatten=not source_is_str,
|
| 1009 |
+
)
|
| 1010 |
+
|
| 1011 |
+
callback.set_size(len(lpaths))
|
| 1012 |
+
for lpath, rpath in callback.wrap(zip(lpaths, rpaths)):
|
| 1013 |
+
with callback.branched(rpath, lpath) as child:
|
| 1014 |
+
self.get_file(rpath, lpath, callback=child, **kwargs)
|
| 1015 |
+
|
| 1016 |
+
def put_file(
|
| 1017 |
+
self, lpath, rpath, callback=DEFAULT_CALLBACK, mode="overwrite", **kwargs
|
| 1018 |
+
):
|
| 1019 |
+
"""Copy single file to remote"""
|
| 1020 |
+
if mode == "create" and self.exists(rpath):
|
| 1021 |
+
raise FileExistsError
|
| 1022 |
+
if os.path.isdir(lpath):
|
| 1023 |
+
self.makedirs(rpath, exist_ok=True)
|
| 1024 |
+
return None
|
| 1025 |
+
|
| 1026 |
+
with open(lpath, "rb") as f1:
|
| 1027 |
+
size = f1.seek(0, 2)
|
| 1028 |
+
callback.set_size(size)
|
| 1029 |
+
f1.seek(0)
|
| 1030 |
+
|
| 1031 |
+
self.mkdirs(self._parent(os.fspath(rpath)), exist_ok=True)
|
| 1032 |
+
with self.open(rpath, "wb", **kwargs) as f2:
|
| 1033 |
+
while f1.tell() < size:
|
| 1034 |
+
data = f1.read(self.blocksize)
|
| 1035 |
+
segment_len = f2.write(data)
|
| 1036 |
+
if segment_len is None:
|
| 1037 |
+
segment_len = len(data)
|
| 1038 |
+
callback.relative_update(segment_len)
|
| 1039 |
+
|
| 1040 |
+
def put(
|
| 1041 |
+
self,
|
| 1042 |
+
lpath,
|
| 1043 |
+
rpath,
|
| 1044 |
+
recursive=False,
|
| 1045 |
+
callback=DEFAULT_CALLBACK,
|
| 1046 |
+
maxdepth=None,
|
| 1047 |
+
**kwargs,
|
| 1048 |
+
):
|
| 1049 |
+
"""Copy file(s) from local.
|
| 1050 |
+
|
| 1051 |
+
Copies a specific file or tree of files (if recursive=True). If rpath
|
| 1052 |
+
ends with a "/", it will be assumed to be a directory, and target files
|
| 1053 |
+
will go within.
|
| 1054 |
+
|
| 1055 |
+
Calls put_file for each source.
|
| 1056 |
+
"""
|
| 1057 |
+
if isinstance(lpath, list) and isinstance(rpath, list):
|
| 1058 |
+
# No need to expand paths when both source and destination
|
| 1059 |
+
# are provided as lists
|
| 1060 |
+
rpaths = rpath
|
| 1061 |
+
lpaths = lpath
|
| 1062 |
+
else:
|
| 1063 |
+
from .implementations.local import (
|
| 1064 |
+
LocalFileSystem,
|
| 1065 |
+
make_path_posix,
|
| 1066 |
+
trailing_sep,
|
| 1067 |
+
)
|
| 1068 |
+
|
| 1069 |
+
source_is_str = isinstance(lpath, str)
|
| 1070 |
+
if source_is_str:
|
| 1071 |
+
lpath = make_path_posix(lpath)
|
| 1072 |
+
fs = LocalFileSystem()
|
| 1073 |
+
lpaths = fs.expand_path(
|
| 1074 |
+
lpath, recursive=recursive, maxdepth=maxdepth, **kwargs
|
| 1075 |
+
)
|
| 1076 |
+
if source_is_str and (not recursive or maxdepth is not None):
|
| 1077 |
+
# Non-recursive glob does not copy directories
|
| 1078 |
+
lpaths = [p for p in lpaths if not (trailing_sep(p) or fs.isdir(p))]
|
| 1079 |
+
if not lpaths:
|
| 1080 |
+
return
|
| 1081 |
+
|
| 1082 |
+
source_is_file = len(lpaths) == 1
|
| 1083 |
+
dest_is_dir = isinstance(rpath, str) and (
|
| 1084 |
+
trailing_sep(rpath) or self.isdir(rpath)
|
| 1085 |
+
)
|
| 1086 |
+
|
| 1087 |
+
rpath = (
|
| 1088 |
+
self._strip_protocol(rpath)
|
| 1089 |
+
if isinstance(rpath, str)
|
| 1090 |
+
else [self._strip_protocol(p) for p in rpath]
|
| 1091 |
+
)
|
| 1092 |
+
exists = source_is_str and (
|
| 1093 |
+
(has_magic(lpath) and source_is_file)
|
| 1094 |
+
or (not has_magic(lpath) and dest_is_dir and not trailing_sep(lpath))
|
| 1095 |
+
)
|
| 1096 |
+
rpaths = other_paths(
|
| 1097 |
+
lpaths,
|
| 1098 |
+
rpath,
|
| 1099 |
+
exists=exists,
|
| 1100 |
+
flatten=not source_is_str,
|
| 1101 |
+
)
|
| 1102 |
+
|
| 1103 |
+
callback.set_size(len(rpaths))
|
| 1104 |
+
for lpath, rpath in callback.wrap(zip(lpaths, rpaths)):
|
| 1105 |
+
with callback.branched(lpath, rpath) as child:
|
| 1106 |
+
self.put_file(lpath, rpath, callback=child, **kwargs)
|
| 1107 |
+
|
| 1108 |
+
def head(self, path, size=1024):
|
| 1109 |
+
"""Get the first ``size`` bytes from file"""
|
| 1110 |
+
with self.open(path, "rb") as f:
|
| 1111 |
+
return f.read(size)
|
| 1112 |
+
|
| 1113 |
+
def tail(self, path, size=1024):
|
| 1114 |
+
"""Get the last ``size`` bytes from file"""
|
| 1115 |
+
with self.open(path, "rb") as f:
|
| 1116 |
+
f.seek(max(-size, -f.size), 2)
|
| 1117 |
+
return f.read()
|
| 1118 |
+
|
| 1119 |
+
def cp_file(self, path1, path2, **kwargs):
|
| 1120 |
+
raise NotImplementedError
|
| 1121 |
+
|
| 1122 |
+
def copy(
|
| 1123 |
+
self, path1, path2, recursive=False, maxdepth=None, on_error=None, **kwargs
|
| 1124 |
+
):
|
| 1125 |
+
"""Copy within two locations in the filesystem
|
| 1126 |
+
|
| 1127 |
+
on_error : "raise", "ignore"
|
| 1128 |
+
If raise, any not-found exceptions will be raised; if ignore any
|
| 1129 |
+
not-found exceptions will cause the path to be skipped; defaults to
|
| 1130 |
+
raise unless recursive is true, where the default is ignore
|
| 1131 |
+
"""
|
| 1132 |
+
if on_error is None and recursive:
|
| 1133 |
+
on_error = "ignore"
|
| 1134 |
+
elif on_error is None:
|
| 1135 |
+
on_error = "raise"
|
| 1136 |
+
|
| 1137 |
+
if isinstance(path1, list) and isinstance(path2, list):
|
| 1138 |
+
# No need to expand paths when both source and destination
|
| 1139 |
+
# are provided as lists
|
| 1140 |
+
paths1 = path1
|
| 1141 |
+
paths2 = path2
|
| 1142 |
+
else:
|
| 1143 |
+
from .implementations.local import trailing_sep
|
| 1144 |
+
|
| 1145 |
+
source_is_str = isinstance(path1, str)
|
| 1146 |
+
paths1 = self.expand_path(
|
| 1147 |
+
path1, recursive=recursive, maxdepth=maxdepth, **kwargs
|
| 1148 |
+
)
|
| 1149 |
+
if source_is_str and (not recursive or maxdepth is not None):
|
| 1150 |
+
# Non-recursive glob does not copy directories
|
| 1151 |
+
paths1 = [p for p in paths1 if not (trailing_sep(p) or self.isdir(p))]
|
| 1152 |
+
if not paths1:
|
| 1153 |
+
return
|
| 1154 |
+
|
| 1155 |
+
source_is_file = len(paths1) == 1
|
| 1156 |
+
dest_is_dir = isinstance(path2, str) and (
|
| 1157 |
+
trailing_sep(path2) or self.isdir(path2)
|
| 1158 |
+
)
|
| 1159 |
+
|
| 1160 |
+
exists = source_is_str and (
|
| 1161 |
+
(has_magic(path1) and source_is_file)
|
| 1162 |
+
or (not has_magic(path1) and dest_is_dir and not trailing_sep(path1))
|
| 1163 |
+
)
|
| 1164 |
+
paths2 = other_paths(
|
| 1165 |
+
paths1,
|
| 1166 |
+
path2,
|
| 1167 |
+
exists=exists,
|
| 1168 |
+
flatten=not source_is_str,
|
| 1169 |
+
)
|
| 1170 |
+
|
| 1171 |
+
for p1, p2 in zip(paths1, paths2):
|
| 1172 |
+
try:
|
| 1173 |
+
self.cp_file(p1, p2, **kwargs)
|
| 1174 |
+
except FileNotFoundError:
|
| 1175 |
+
if on_error == "raise":
|
| 1176 |
+
raise
|
| 1177 |
+
|
| 1178 |
+
def expand_path(self, path, recursive=False, maxdepth=None, **kwargs):
|
| 1179 |
+
"""Turn one or more globs or directories into a list of all matching paths
|
| 1180 |
+
to files or directories.
|
| 1181 |
+
|
| 1182 |
+
kwargs are passed to ``glob`` or ``find``, which may in turn call ``ls``
|
| 1183 |
+
"""
|
| 1184 |
+
|
| 1185 |
+
if maxdepth is not None and maxdepth < 1:
|
| 1186 |
+
raise ValueError("maxdepth must be at least 1")
|
| 1187 |
+
|
| 1188 |
+
if isinstance(path, (str, os.PathLike)):
|
| 1189 |
+
out = self.expand_path([path], recursive, maxdepth, **kwargs)
|
| 1190 |
+
else:
|
| 1191 |
+
out = set()
|
| 1192 |
+
path = [self._strip_protocol(p) for p in path]
|
| 1193 |
+
for p in path:
|
| 1194 |
+
if has_magic(p):
|
| 1195 |
+
bit = set(self.glob(p, maxdepth=maxdepth, **kwargs))
|
| 1196 |
+
out |= bit
|
| 1197 |
+
if recursive:
|
| 1198 |
+
# glob call above expanded one depth so if maxdepth is defined
|
| 1199 |
+
# then decrement it in expand_path call below. If it is zero
|
| 1200 |
+
# after decrementing then avoid expand_path call.
|
| 1201 |
+
if maxdepth is not None and maxdepth <= 1:
|
| 1202 |
+
continue
|
| 1203 |
+
out |= set(
|
| 1204 |
+
self.expand_path(
|
| 1205 |
+
list(bit),
|
| 1206 |
+
recursive=recursive,
|
| 1207 |
+
maxdepth=maxdepth - 1 if maxdepth is not None else None,
|
| 1208 |
+
**kwargs,
|
| 1209 |
+
)
|
| 1210 |
+
)
|
| 1211 |
+
continue
|
| 1212 |
+
elif recursive:
|
| 1213 |
+
rec = set(
|
| 1214 |
+
self.find(
|
| 1215 |
+
p, maxdepth=maxdepth, withdirs=True, detail=False, **kwargs
|
| 1216 |
+
)
|
| 1217 |
+
)
|
| 1218 |
+
out |= rec
|
| 1219 |
+
if p not in out and (recursive is False or self.exists(p)):
|
| 1220 |
+
# should only check once, for the root
|
| 1221 |
+
out.add(p)
|
| 1222 |
+
if not out:
|
| 1223 |
+
raise FileNotFoundError(path)
|
| 1224 |
+
return sorted(out)
|
| 1225 |
+
|
| 1226 |
+
def mv(self, path1, path2, recursive=False, maxdepth=None, **kwargs):
|
| 1227 |
+
"""Move file(s) from one location to another"""
|
| 1228 |
+
if path1 == path2:
|
| 1229 |
+
logger.debug("%s mv: The paths are the same, so no files were moved.", self)
|
| 1230 |
+
else:
|
| 1231 |
+
# explicitly raise exception to prevent data corruption
|
| 1232 |
+
self.copy(
|
| 1233 |
+
path1, path2, recursive=recursive, maxdepth=maxdepth, onerror="raise"
|
| 1234 |
+
)
|
| 1235 |
+
self.rm(path1, recursive=recursive)
|
| 1236 |
+
|
| 1237 |
+
def rm_file(self, path):
|
| 1238 |
+
"""Delete a file"""
|
| 1239 |
+
self._rm(path)
|
| 1240 |
+
|
| 1241 |
+
def _rm(self, path):
|
| 1242 |
+
"""Delete one file"""
|
| 1243 |
+
# this is the old name for the method, prefer rm_file
|
| 1244 |
+
raise NotImplementedError
|
| 1245 |
+
|
| 1246 |
+
def rm(self, path, recursive=False, maxdepth=None):
|
| 1247 |
+
"""Delete files.
|
| 1248 |
+
|
| 1249 |
+
Parameters
|
| 1250 |
+
----------
|
| 1251 |
+
path: str or list of str
|
| 1252 |
+
File(s) to delete.
|
| 1253 |
+
recursive: bool
|
| 1254 |
+
If file(s) are directories, recursively delete contents and then
|
| 1255 |
+
also remove the directory
|
| 1256 |
+
maxdepth: int or None
|
| 1257 |
+
Depth to pass to walk for finding files to delete, if recursive.
|
| 1258 |
+
If None, there will be no limit and infinite recursion may be
|
| 1259 |
+
possible.
|
| 1260 |
+
"""
|
| 1261 |
+
path = self.expand_path(path, recursive=recursive, maxdepth=maxdepth)
|
| 1262 |
+
for p in reversed(path):
|
| 1263 |
+
self.rm_file(p)
|
| 1264 |
+
|
| 1265 |
+
@classmethod
|
| 1266 |
+
def _parent(cls, path):
|
| 1267 |
+
path = cls._strip_protocol(path)
|
| 1268 |
+
if "/" in path:
|
| 1269 |
+
parent = path.rsplit("/", 1)[0].lstrip(cls.root_marker)
|
| 1270 |
+
return cls.root_marker + parent
|
| 1271 |
+
else:
|
| 1272 |
+
return cls.root_marker
|
| 1273 |
+
|
| 1274 |
+
def _open(
|
| 1275 |
+
self,
|
| 1276 |
+
path,
|
| 1277 |
+
mode="rb",
|
| 1278 |
+
block_size=None,
|
| 1279 |
+
autocommit=True,
|
| 1280 |
+
cache_options=None,
|
| 1281 |
+
**kwargs,
|
| 1282 |
+
):
|
| 1283 |
+
"""Return raw bytes-mode file-like from the file-system"""
|
| 1284 |
+
return AbstractBufferedFile(
|
| 1285 |
+
self,
|
| 1286 |
+
path,
|
| 1287 |
+
mode,
|
| 1288 |
+
block_size,
|
| 1289 |
+
autocommit,
|
| 1290 |
+
cache_options=cache_options,
|
| 1291 |
+
**kwargs,
|
| 1292 |
+
)
|
| 1293 |
+
|
| 1294 |
+
def open(
|
| 1295 |
+
self,
|
| 1296 |
+
path,
|
| 1297 |
+
mode="rb",
|
| 1298 |
+
block_size=None,
|
| 1299 |
+
cache_options=None,
|
| 1300 |
+
compression=None,
|
| 1301 |
+
**kwargs,
|
| 1302 |
+
):
|
| 1303 |
+
"""
|
| 1304 |
+
Return a file-like object from the filesystem
|
| 1305 |
+
|
| 1306 |
+
The resultant instance must function correctly in a context ``with``
|
| 1307 |
+
block.
|
| 1308 |
+
|
| 1309 |
+
Parameters
|
| 1310 |
+
----------
|
| 1311 |
+
path: str
|
| 1312 |
+
Target file
|
| 1313 |
+
mode: str like 'rb', 'w'
|
| 1314 |
+
See builtin ``open()``
|
| 1315 |
+
Mode "x" (exclusive write) may be implemented by the backend. Even if
|
| 1316 |
+
it is, whether it is checked up front or on commit, and whether it is
|
| 1317 |
+
atomic is implementation-dependent.
|
| 1318 |
+
block_size: int
|
| 1319 |
+
Some indication of buffering - this is a value in bytes
|
| 1320 |
+
cache_options : dict, optional
|
| 1321 |
+
Extra arguments to pass through to the cache.
|
| 1322 |
+
compression: string or None
|
| 1323 |
+
If given, open file using compression codec. Can either be a compression
|
| 1324 |
+
name (a key in ``fsspec.compression.compr``) or "infer" to guess the
|
| 1325 |
+
compression from the filename suffix.
|
| 1326 |
+
encoding, errors, newline: passed on to TextIOWrapper for text mode
|
| 1327 |
+
"""
|
| 1328 |
+
import io
|
| 1329 |
+
|
| 1330 |
+
path = self._strip_protocol(path)
|
| 1331 |
+
if "b" not in mode:
|
| 1332 |
+
mode = mode.replace("t", "") + "b"
|
| 1333 |
+
|
| 1334 |
+
text_kwargs = {
|
| 1335 |
+
k: kwargs.pop(k)
|
| 1336 |
+
for k in ["encoding", "errors", "newline"]
|
| 1337 |
+
if k in kwargs
|
| 1338 |
+
}
|
| 1339 |
+
return io.TextIOWrapper(
|
| 1340 |
+
self.open(
|
| 1341 |
+
path,
|
| 1342 |
+
mode,
|
| 1343 |
+
block_size=block_size,
|
| 1344 |
+
cache_options=cache_options,
|
| 1345 |
+
compression=compression,
|
| 1346 |
+
**kwargs,
|
| 1347 |
+
),
|
| 1348 |
+
**text_kwargs,
|
| 1349 |
+
)
|
| 1350 |
+
else:
|
| 1351 |
+
ac = kwargs.pop("autocommit", not self._intrans)
|
| 1352 |
+
f = self._open(
|
| 1353 |
+
path,
|
| 1354 |
+
mode=mode,
|
| 1355 |
+
block_size=block_size,
|
| 1356 |
+
autocommit=ac,
|
| 1357 |
+
cache_options=cache_options,
|
| 1358 |
+
**kwargs,
|
| 1359 |
+
)
|
| 1360 |
+
if compression is not None:
|
| 1361 |
+
from fsspec.compression import compr
|
| 1362 |
+
from fsspec.core import get_compression
|
| 1363 |
+
|
| 1364 |
+
compression = get_compression(path, compression)
|
| 1365 |
+
compress = compr[compression]
|
| 1366 |
+
f = compress(f, mode=mode[0])
|
| 1367 |
+
|
| 1368 |
+
if not ac and "r" not in mode:
|
| 1369 |
+
self.transaction.files.append(f)
|
| 1370 |
+
return f
|
| 1371 |
+
|
| 1372 |
+
def touch(self, path, truncate=True, **kwargs):
|
| 1373 |
+
"""Create empty file, or update timestamp
|
| 1374 |
+
|
| 1375 |
+
Parameters
|
| 1376 |
+
----------
|
| 1377 |
+
path: str
|
| 1378 |
+
file location
|
| 1379 |
+
truncate: bool
|
| 1380 |
+
If True, always set file size to 0; if False, update timestamp and
|
| 1381 |
+
leave file unchanged, if backend allows this
|
| 1382 |
+
"""
|
| 1383 |
+
if truncate or not self.exists(path):
|
| 1384 |
+
with self.open(path, "wb", **kwargs):
|
| 1385 |
+
pass
|
| 1386 |
+
else:
|
| 1387 |
+
raise NotImplementedError # update timestamp, if possible
|
| 1388 |
+
|
| 1389 |
+
def ukey(self, path):
|
| 1390 |
+
"""Hash of file properties, to tell if it has changed"""
|
| 1391 |
+
return sha256(str(self.info(path)).encode()).hexdigest()
|
| 1392 |
+
|
| 1393 |
+
def read_block(self, fn, offset, length, delimiter=None):
|
| 1394 |
+
"""Read a block of bytes from
|
| 1395 |
+
|
| 1396 |
+
Starting at ``offset`` of the file, read ``length`` bytes. If
|
| 1397 |
+
``delimiter`` is set then we ensure that the read starts and stops at
|
| 1398 |
+
delimiter boundaries that follow the locations ``offset`` and ``offset
|
| 1399 |
+
+ length``. If ``offset`` is zero then we start at zero. The
|
| 1400 |
+
bytestring returned WILL include the end delimiter string.
|
| 1401 |
+
|
| 1402 |
+
If offset+length is beyond the eof, reads to eof.
|
| 1403 |
+
|
| 1404 |
+
Parameters
|
| 1405 |
+
----------
|
| 1406 |
+
fn: string
|
| 1407 |
+
Path to filename
|
| 1408 |
+
offset: int
|
| 1409 |
+
Byte offset to start read
|
| 1410 |
+
length: int
|
| 1411 |
+
Number of bytes to read. If None, read to end.
|
| 1412 |
+
delimiter: bytes (optional)
|
| 1413 |
+
Ensure reading starts and stops at delimiter bytestring
|
| 1414 |
+
|
| 1415 |
+
Examples
|
| 1416 |
+
--------
|
| 1417 |
+
>>> fs.read_block('data/file.csv', 0, 13) # doctest: +SKIP
|
| 1418 |
+
b'Alice, 100\\nBo'
|
| 1419 |
+
>>> fs.read_block('data/file.csv', 0, 13, delimiter=b'\\n') # doctest: +SKIP
|
| 1420 |
+
b'Alice, 100\\nBob, 200\\n'
|
| 1421 |
+
|
| 1422 |
+
Use ``length=None`` to read to the end of the file.
|
| 1423 |
+
>>> fs.read_block('data/file.csv', 0, None, delimiter=b'\\n') # doctest: +SKIP
|
| 1424 |
+
b'Alice, 100\\nBob, 200\\nCharlie, 300'
|
| 1425 |
+
|
| 1426 |
+
See Also
|
| 1427 |
+
--------
|
| 1428 |
+
:func:`fsspec.utils.read_block`
|
| 1429 |
+
"""
|
| 1430 |
+
with self.open(fn, "rb") as f:
|
| 1431 |
+
size = f.size
|
| 1432 |
+
if length is None:
|
| 1433 |
+
length = size
|
| 1434 |
+
if size is not None and offset + length > size:
|
| 1435 |
+
length = size - offset
|
| 1436 |
+
return read_block(f, offset, length, delimiter)
|
| 1437 |
+
|
| 1438 |
+
def to_json(self, *, include_password: bool = True) -> str:
|
| 1439 |
+
"""
|
| 1440 |
+
JSON representation of this filesystem instance.
|
| 1441 |
+
|
| 1442 |
+
Parameters
|
| 1443 |
+
----------
|
| 1444 |
+
include_password: bool, default True
|
| 1445 |
+
Whether to include the password (if any) in the output.
|
| 1446 |
+
|
| 1447 |
+
Returns
|
| 1448 |
+
-------
|
| 1449 |
+
JSON string with keys ``cls`` (the python location of this class),
|
| 1450 |
+
protocol (text name of this class's protocol, first one in case of
|
| 1451 |
+
multiple), ``args`` (positional args, usually empty), and all other
|
| 1452 |
+
keyword arguments as their own keys.
|
| 1453 |
+
|
| 1454 |
+
Warnings
|
| 1455 |
+
--------
|
| 1456 |
+
Serialized filesystems may contain sensitive information which have been
|
| 1457 |
+
passed to the constructor, such as passwords and tokens. Make sure you
|
| 1458 |
+
store and send them in a secure environment!
|
| 1459 |
+
"""
|
| 1460 |
+
from .json import FilesystemJSONEncoder
|
| 1461 |
+
|
| 1462 |
+
return json.dumps(
|
| 1463 |
+
self,
|
| 1464 |
+
cls=type(
|
| 1465 |
+
"_FilesystemJSONEncoder",
|
| 1466 |
+
(FilesystemJSONEncoder,),
|
| 1467 |
+
{"include_password": include_password},
|
| 1468 |
+
),
|
| 1469 |
+
)
|
| 1470 |
+
|
| 1471 |
+
@staticmethod
|
| 1472 |
+
def from_json(blob: str) -> AbstractFileSystem:
|
| 1473 |
+
"""
|
| 1474 |
+
Recreate a filesystem instance from JSON representation.
|
| 1475 |
+
|
| 1476 |
+
See ``.to_json()`` for the expected structure of the input.
|
| 1477 |
+
|
| 1478 |
+
Parameters
|
| 1479 |
+
----------
|
| 1480 |
+
blob: str
|
| 1481 |
+
|
| 1482 |
+
Returns
|
| 1483 |
+
-------
|
| 1484 |
+
file system instance, not necessarily of this particular class.
|
| 1485 |
+
|
| 1486 |
+
Warnings
|
| 1487 |
+
--------
|
| 1488 |
+
This can import arbitrary modules (as determined by the ``cls`` key).
|
| 1489 |
+
Make sure you haven't installed any modules that may execute malicious code
|
| 1490 |
+
at import time.
|
| 1491 |
+
"""
|
| 1492 |
+
from .json import FilesystemJSONDecoder
|
| 1493 |
+
|
| 1494 |
+
return json.loads(blob, cls=FilesystemJSONDecoder)
|
| 1495 |
+
|
| 1496 |
+
def to_dict(self, *, include_password: bool = True) -> dict[str, Any]:
|
| 1497 |
+
"""
|
| 1498 |
+
JSON-serializable dictionary representation of this filesystem instance.
|
| 1499 |
+
|
| 1500 |
+
Parameters
|
| 1501 |
+
----------
|
| 1502 |
+
include_password: bool, default True
|
| 1503 |
+
Whether to include the password (if any) in the output.
|
| 1504 |
+
|
| 1505 |
+
Returns
|
| 1506 |
+
-------
|
| 1507 |
+
Dictionary with keys ``cls`` (the python location of this class),
|
| 1508 |
+
protocol (text name of this class's protocol, first one in case of
|
| 1509 |
+
multiple), ``args`` (positional args, usually empty), and all other
|
| 1510 |
+
keyword arguments as their own keys.
|
| 1511 |
+
|
| 1512 |
+
Warnings
|
| 1513 |
+
--------
|
| 1514 |
+
Serialized filesystems may contain sensitive information which have been
|
| 1515 |
+
passed to the constructor, such as passwords and tokens. Make sure you
|
| 1516 |
+
store and send them in a secure environment!
|
| 1517 |
+
"""
|
| 1518 |
+
from .json import FilesystemJSONEncoder
|
| 1519 |
+
|
| 1520 |
+
json_encoder = FilesystemJSONEncoder()
|
| 1521 |
+
|
| 1522 |
+
cls = type(self)
|
| 1523 |
+
proto = self.protocol
|
| 1524 |
+
|
| 1525 |
+
storage_options = dict(self.storage_options)
|
| 1526 |
+
if not include_password:
|
| 1527 |
+
storage_options.pop("password", None)
|
| 1528 |
+
|
| 1529 |
+
return dict(
|
| 1530 |
+
cls=f"{cls.__module__}:{cls.__name__}",
|
| 1531 |
+
protocol=proto[0] if isinstance(proto, (tuple, list)) else proto,
|
| 1532 |
+
args=json_encoder.make_serializable(self.storage_args),
|
| 1533 |
+
**json_encoder.make_serializable(storage_options),
|
| 1534 |
+
)
|
| 1535 |
+
|
| 1536 |
+
@staticmethod
|
| 1537 |
+
def from_dict(dct: dict[str, Any]) -> AbstractFileSystem:
|
| 1538 |
+
"""
|
| 1539 |
+
Recreate a filesystem instance from dictionary representation.
|
| 1540 |
+
|
| 1541 |
+
See ``.to_dict()`` for the expected structure of the input.
|
| 1542 |
+
|
| 1543 |
+
Parameters
|
| 1544 |
+
----------
|
| 1545 |
+
dct: Dict[str, Any]
|
| 1546 |
+
|
| 1547 |
+
Returns
|
| 1548 |
+
-------
|
| 1549 |
+
file system instance, not necessarily of this particular class.
|
| 1550 |
+
|
| 1551 |
+
Warnings
|
| 1552 |
+
--------
|
| 1553 |
+
This can import arbitrary modules (as determined by the ``cls`` key).
|
| 1554 |
+
Make sure you haven't installed any modules that may execute malicious code
|
| 1555 |
+
at import time.
|
| 1556 |
+
"""
|
| 1557 |
+
from .json import FilesystemJSONDecoder
|
| 1558 |
+
|
| 1559 |
+
json_decoder = FilesystemJSONDecoder()
|
| 1560 |
+
|
| 1561 |
+
dct = dict(dct) # Defensive copy
|
| 1562 |
+
|
| 1563 |
+
cls = FilesystemJSONDecoder.try_resolve_fs_cls(dct)
|
| 1564 |
+
if cls is None:
|
| 1565 |
+
raise ValueError("Not a serialized AbstractFileSystem")
|
| 1566 |
+
|
| 1567 |
+
dct.pop("cls", None)
|
| 1568 |
+
dct.pop("protocol", None)
|
| 1569 |
+
|
| 1570 |
+
return cls(
|
| 1571 |
+
*json_decoder.unmake_serializable(dct.pop("args", ())),
|
| 1572 |
+
**json_decoder.unmake_serializable(dct),
|
| 1573 |
+
)
|
| 1574 |
+
|
| 1575 |
+
def _get_pyarrow_filesystem(self):
|
| 1576 |
+
"""
|
| 1577 |
+
Make a version of the FS instance which will be acceptable to pyarrow
|
| 1578 |
+
"""
|
| 1579 |
+
# all instances already also derive from pyarrow
|
| 1580 |
+
return self
|
| 1581 |
+
|
| 1582 |
+
def get_mapper(self, root="", check=False, create=False, missing_exceptions=None):
|
| 1583 |
+
"""Create key/value store based on this file-system
|
| 1584 |
+
|
| 1585 |
+
Makes a MutableMapping interface to the FS at the given root path.
|
| 1586 |
+
See ``fsspec.mapping.FSMap`` for further details.
|
| 1587 |
+
"""
|
| 1588 |
+
from .mapping import FSMap
|
| 1589 |
+
|
| 1590 |
+
return FSMap(
|
| 1591 |
+
root,
|
| 1592 |
+
self,
|
| 1593 |
+
check=check,
|
| 1594 |
+
create=create,
|
| 1595 |
+
missing_exceptions=missing_exceptions,
|
| 1596 |
+
)
|
| 1597 |
+
|
| 1598 |
+
@classmethod
|
| 1599 |
+
def clear_instance_cache(cls):
|
| 1600 |
+
"""
|
| 1601 |
+
Clear the cache of filesystem instances.
|
| 1602 |
+
|
| 1603 |
+
Notes
|
| 1604 |
+
-----
|
| 1605 |
+
Unless overridden by setting the ``cachable`` class attribute to False,
|
| 1606 |
+
the filesystem class stores a reference to newly created instances. This
|
| 1607 |
+
prevents Python's normal rules around garbage collection from working,
|
| 1608 |
+
since the instances refcount will not drop to zero until
|
| 1609 |
+
``clear_instance_cache`` is called.
|
| 1610 |
+
"""
|
| 1611 |
+
cls._cache.clear()
|
| 1612 |
+
|
| 1613 |
+
def created(self, path):
|
| 1614 |
+
"""Return the created timestamp of a file as a datetime.datetime"""
|
| 1615 |
+
raise NotImplementedError
|
| 1616 |
+
|
| 1617 |
+
def modified(self, path):
|
| 1618 |
+
"""Return the modified timestamp of a file as a datetime.datetime"""
|
| 1619 |
+
raise NotImplementedError
|
| 1620 |
+
|
| 1621 |
+
def tree(
|
| 1622 |
+
self,
|
| 1623 |
+
path: str = "/",
|
| 1624 |
+
recursion_limit: int = 2,
|
| 1625 |
+
max_display: int = 25,
|
| 1626 |
+
display_size: bool = False,
|
| 1627 |
+
prefix: str = "",
|
| 1628 |
+
is_last: bool = True,
|
| 1629 |
+
first: bool = True,
|
| 1630 |
+
indent_size: int = 4,
|
| 1631 |
+
) -> str:
|
| 1632 |
+
"""
|
| 1633 |
+
Return a tree-like structure of the filesystem starting from the given path as a string.
|
| 1634 |
+
|
| 1635 |
+
Parameters
|
| 1636 |
+
----------
|
| 1637 |
+
path: Root path to start traversal from
|
| 1638 |
+
recursion_limit: Maximum depth of directory traversal
|
| 1639 |
+
max_display: Maximum number of items to display per directory
|
| 1640 |
+
display_size: Whether to display file sizes
|
| 1641 |
+
prefix: Current line prefix for visual tree structure
|
| 1642 |
+
is_last: Whether current item is last in its level
|
| 1643 |
+
first: Whether this is the first call (displays root path)
|
| 1644 |
+
indent_size: Number of spaces by indent
|
| 1645 |
+
|
| 1646 |
+
Returns
|
| 1647 |
+
-------
|
| 1648 |
+
str: A string representing the tree structure.
|
| 1649 |
+
|
| 1650 |
+
Example
|
| 1651 |
+
-------
|
| 1652 |
+
>>> from fsspec import filesystem
|
| 1653 |
+
|
| 1654 |
+
>>> fs = filesystem('ftp', host='test.rebex.net', user='demo', password='password')
|
| 1655 |
+
>>> tree = fs.tree(display_size=True, recursion_limit=3, indent_size=8, max_display=10)
|
| 1656 |
+
>>> print(tree)
|
| 1657 |
+
"""
|
| 1658 |
+
|
| 1659 |
+
def format_bytes(n: int) -> str:
|
| 1660 |
+
"""Format bytes as text."""
|
| 1661 |
+
for prefix, k in (
|
| 1662 |
+
("P", 2**50),
|
| 1663 |
+
("T", 2**40),
|
| 1664 |
+
("G", 2**30),
|
| 1665 |
+
("M", 2**20),
|
| 1666 |
+
("k", 2**10),
|
| 1667 |
+
):
|
| 1668 |
+
if n >= 0.9 * k:
|
| 1669 |
+
return f"{n / k:.2f} {prefix}b"
|
| 1670 |
+
return f"{n}B"
|
| 1671 |
+
|
| 1672 |
+
result = []
|
| 1673 |
+
|
| 1674 |
+
if first:
|
| 1675 |
+
result.append(path)
|
| 1676 |
+
|
| 1677 |
+
if recursion_limit:
|
| 1678 |
+
indent = " " * indent_size
|
| 1679 |
+
contents = self.ls(path, detail=True)
|
| 1680 |
+
contents.sort(
|
| 1681 |
+
key=lambda x: (x.get("type") != "directory", x.get("name", ""))
|
| 1682 |
+
)
|
| 1683 |
+
|
| 1684 |
+
if max_display is not None and len(contents) > max_display:
|
| 1685 |
+
displayed_contents = contents[:max_display]
|
| 1686 |
+
remaining_count = len(contents) - max_display
|
| 1687 |
+
else:
|
| 1688 |
+
displayed_contents = contents
|
| 1689 |
+
remaining_count = 0
|
| 1690 |
+
|
| 1691 |
+
for i, item in enumerate(displayed_contents):
|
| 1692 |
+
is_last_item = (i == len(displayed_contents) - 1) and (
|
| 1693 |
+
remaining_count == 0
|
| 1694 |
+
)
|
| 1695 |
+
|
| 1696 |
+
branch = (
|
| 1697 |
+
"└" + ("─" * (indent_size - 2))
|
| 1698 |
+
if is_last_item
|
| 1699 |
+
else "├" + ("─" * (indent_size - 2))
|
| 1700 |
+
)
|
| 1701 |
+
branch += " "
|
| 1702 |
+
new_prefix = prefix + (
|
| 1703 |
+
indent if is_last_item else "│" + " " * (indent_size - 1)
|
| 1704 |
+
)
|
| 1705 |
+
|
| 1706 |
+
name = os.path.basename(item.get("name", ""))
|
| 1707 |
+
|
| 1708 |
+
if display_size and item.get("type") == "directory":
|
| 1709 |
+
sub_contents = self.ls(item.get("name", ""), detail=True)
|
| 1710 |
+
num_files = sum(
|
| 1711 |
+
1 for sub_item in sub_contents if sub_item.get("type") == "file"
|
| 1712 |
+
)
|
| 1713 |
+
num_folders = sum(
|
| 1714 |
+
1
|
| 1715 |
+
for sub_item in sub_contents
|
| 1716 |
+
if sub_item.get("type") == "directory"
|
| 1717 |
+
)
|
| 1718 |
+
|
| 1719 |
+
if num_files == 0 and num_folders == 0:
|
| 1720 |
+
size = " (empty folder)"
|
| 1721 |
+
elif num_files == 0:
|
| 1722 |
+
size = f" ({num_folders} subfolder{'s' if num_folders > 1 else ''})"
|
| 1723 |
+
elif num_folders == 0:
|
| 1724 |
+
size = f" ({num_files} file{'s' if num_files > 1 else ''})"
|
| 1725 |
+
else:
|
| 1726 |
+
size = f" ({num_files} file{'s' if num_files > 1 else ''}, {num_folders} subfolder{'s' if num_folders > 1 else ''})"
|
| 1727 |
+
elif display_size and item.get("type") == "file":
|
| 1728 |
+
size = f" ({format_bytes(item.get('size', 0))})"
|
| 1729 |
+
else:
|
| 1730 |
+
size = ""
|
| 1731 |
+
|
| 1732 |
+
result.append(f"{prefix}{branch}{name}{size}")
|
| 1733 |
+
|
| 1734 |
+
if item.get("type") == "directory" and recursion_limit > 0:
|
| 1735 |
+
result.append(
|
| 1736 |
+
self.tree(
|
| 1737 |
+
path=item.get("name", ""),
|
| 1738 |
+
recursion_limit=recursion_limit - 1,
|
| 1739 |
+
max_display=max_display,
|
| 1740 |
+
display_size=display_size,
|
| 1741 |
+
prefix=new_prefix,
|
| 1742 |
+
is_last=is_last_item,
|
| 1743 |
+
first=False,
|
| 1744 |
+
indent_size=indent_size,
|
| 1745 |
+
)
|
| 1746 |
+
)
|
| 1747 |
+
|
| 1748 |
+
if remaining_count > 0:
|
| 1749 |
+
more_message = f"{remaining_count} more item(s) not displayed."
|
| 1750 |
+
result.append(
|
| 1751 |
+
f"{prefix}{'└' + ('─' * (indent_size - 2))} {more_message}"
|
| 1752 |
+
)
|
| 1753 |
+
|
| 1754 |
+
return "\n".join(_ for _ in result if _)
|
| 1755 |
+
|
| 1756 |
+
# ------------------------------------------------------------------------
|
| 1757 |
+
# Aliases
|
| 1758 |
+
|
| 1759 |
+
def read_bytes(self, path, start=None, end=None, **kwargs):
|
| 1760 |
+
"""Alias of `AbstractFileSystem.cat_file`."""
|
| 1761 |
+
return self.cat_file(path, start=start, end=end, **kwargs)
|
| 1762 |
+
|
| 1763 |
+
def write_bytes(self, path, value, **kwargs):
|
| 1764 |
+
"""Alias of `AbstractFileSystem.pipe_file`."""
|
| 1765 |
+
self.pipe_file(path, value, **kwargs)
|
| 1766 |
+
|
| 1767 |
+
def makedir(self, path, create_parents=True, **kwargs):
|
| 1768 |
+
"""Alias of `AbstractFileSystem.mkdir`."""
|
| 1769 |
+
return self.mkdir(path, create_parents=create_parents, **kwargs)
|
| 1770 |
+
|
| 1771 |
+
def mkdirs(self, path, exist_ok=False):
|
| 1772 |
+
"""Alias of `AbstractFileSystem.makedirs`."""
|
| 1773 |
+
return self.makedirs(path, exist_ok=exist_ok)
|
| 1774 |
+
|
| 1775 |
+
def listdir(self, path, detail=True, **kwargs):
|
| 1776 |
+
"""Alias of `AbstractFileSystem.ls`."""
|
| 1777 |
+
return self.ls(path, detail=detail, **kwargs)
|
| 1778 |
+
|
| 1779 |
+
def cp(self, path1, path2, **kwargs):
|
| 1780 |
+
"""Alias of `AbstractFileSystem.copy`."""
|
| 1781 |
+
return self.copy(path1, path2, **kwargs)
|
| 1782 |
+
|
| 1783 |
+
def move(self, path1, path2, **kwargs):
|
| 1784 |
+
"""Alias of `AbstractFileSystem.mv`."""
|
| 1785 |
+
return self.mv(path1, path2, **kwargs)
|
| 1786 |
+
|
| 1787 |
+
def stat(self, path, **kwargs):
|
| 1788 |
+
"""Alias of `AbstractFileSystem.info`."""
|
| 1789 |
+
return self.info(path, **kwargs)
|
| 1790 |
+
|
| 1791 |
+
def disk_usage(self, path, total=True, maxdepth=None, **kwargs):
|
| 1792 |
+
"""Alias of `AbstractFileSystem.du`."""
|
| 1793 |
+
return self.du(path, total=total, maxdepth=maxdepth, **kwargs)
|
| 1794 |
+
|
| 1795 |
+
def rename(self, path1, path2, **kwargs):
|
| 1796 |
+
"""Alias of `AbstractFileSystem.mv`."""
|
| 1797 |
+
return self.mv(path1, path2, **kwargs)
|
| 1798 |
+
|
| 1799 |
+
def delete(self, path, recursive=False, maxdepth=None):
|
| 1800 |
+
"""Alias of `AbstractFileSystem.rm`."""
|
| 1801 |
+
return self.rm(path, recursive=recursive, maxdepth=maxdepth)
|
| 1802 |
+
|
| 1803 |
+
def upload(self, lpath, rpath, recursive=False, **kwargs):
|
| 1804 |
+
"""Alias of `AbstractFileSystem.put`."""
|
| 1805 |
+
return self.put(lpath, rpath, recursive=recursive, **kwargs)
|
| 1806 |
+
|
| 1807 |
+
def download(self, rpath, lpath, recursive=False, **kwargs):
|
| 1808 |
+
"""Alias of `AbstractFileSystem.get`."""
|
| 1809 |
+
return self.get(rpath, lpath, recursive=recursive, **kwargs)
|
| 1810 |
+
|
| 1811 |
+
def sign(self, path, expiration=100, **kwargs):
|
| 1812 |
+
"""Create a signed URL representing the given path
|
| 1813 |
+
|
| 1814 |
+
Some implementations allow temporary URLs to be generated, as a
|
| 1815 |
+
way of delegating credentials.
|
| 1816 |
+
|
| 1817 |
+
Parameters
|
| 1818 |
+
----------
|
| 1819 |
+
path : str
|
| 1820 |
+
The path on the filesystem
|
| 1821 |
+
expiration : int
|
| 1822 |
+
Number of seconds to enable the URL for (if supported)
|
| 1823 |
+
|
| 1824 |
+
Returns
|
| 1825 |
+
-------
|
| 1826 |
+
URL : str
|
| 1827 |
+
The signed URL
|
| 1828 |
+
|
| 1829 |
+
Raises
|
| 1830 |
+
------
|
| 1831 |
+
NotImplementedError : if method is not implemented for a filesystem
|
| 1832 |
+
"""
|
| 1833 |
+
raise NotImplementedError("Sign is not implemented for this filesystem")
|
| 1834 |
+
|
| 1835 |
+
def _isfilestore(self):
|
| 1836 |
+
# Originally inherited from pyarrow DaskFileSystem. Keeping this
|
| 1837 |
+
# here for backwards compatibility as long as pyarrow uses its
|
| 1838 |
+
# legacy fsspec-compatible filesystems and thus accepts fsspec
|
| 1839 |
+
# filesystems as well
|
| 1840 |
+
return False
|
| 1841 |
+
|
| 1842 |
+
|
| 1843 |
+
class AbstractBufferedFile(io.IOBase):
|
| 1844 |
+
"""Convenient class to derive from to provide buffering
|
| 1845 |
+
|
| 1846 |
+
In the case that the backend does not provide a pythonic file-like object
|
| 1847 |
+
already, this class contains much of the logic to build one. The only
|
| 1848 |
+
methods that need to be overridden are ``_upload_chunk``,
|
| 1849 |
+
``_initiate_upload`` and ``_fetch_range``.
|
| 1850 |
+
"""
|
| 1851 |
+
|
| 1852 |
+
DEFAULT_BLOCK_SIZE = 5 * 2**20
|
| 1853 |
+
_details = None
|
| 1854 |
+
|
| 1855 |
+
def __init__(
|
| 1856 |
+
self,
|
| 1857 |
+
fs,
|
| 1858 |
+
path,
|
| 1859 |
+
mode="rb",
|
| 1860 |
+
block_size="default",
|
| 1861 |
+
autocommit=True,
|
| 1862 |
+
cache_type="readahead",
|
| 1863 |
+
cache_options=None,
|
| 1864 |
+
size=None,
|
| 1865 |
+
**kwargs,
|
| 1866 |
+
):
|
| 1867 |
+
"""
|
| 1868 |
+
Template for files with buffered reading and writing
|
| 1869 |
+
|
| 1870 |
+
Parameters
|
| 1871 |
+
----------
|
| 1872 |
+
fs: instance of FileSystem
|
| 1873 |
+
path: str
|
| 1874 |
+
location in file-system
|
| 1875 |
+
mode: str
|
| 1876 |
+
Normal file modes. Currently only 'wb', 'ab' or 'rb'. Some file
|
| 1877 |
+
systems may be read-only, and some may not support append.
|
| 1878 |
+
block_size: int
|
| 1879 |
+
Buffer size for reading or writing, 'default' for class default
|
| 1880 |
+
autocommit: bool
|
| 1881 |
+
Whether to write to final destination; may only impact what
|
| 1882 |
+
happens when file is being closed.
|
| 1883 |
+
cache_type: {"readahead", "none", "mmap", "bytes"}, default "readahead"
|
| 1884 |
+
Caching policy in read mode. See the definitions in ``core``.
|
| 1885 |
+
cache_options : dict
|
| 1886 |
+
Additional options passed to the constructor for the cache specified
|
| 1887 |
+
by `cache_type`.
|
| 1888 |
+
size: int
|
| 1889 |
+
If given and in read mode, suppressed having to look up the file size
|
| 1890 |
+
kwargs:
|
| 1891 |
+
Gets stored as self.kwargs
|
| 1892 |
+
"""
|
| 1893 |
+
from .core import caches
|
| 1894 |
+
|
| 1895 |
+
self.path = path
|
| 1896 |
+
self.fs = fs
|
| 1897 |
+
self.mode = mode
|
| 1898 |
+
self.blocksize = (
|
| 1899 |
+
self.DEFAULT_BLOCK_SIZE if block_size in ["default", None] else block_size
|
| 1900 |
+
)
|
| 1901 |
+
self.loc = 0
|
| 1902 |
+
self.autocommit = autocommit
|
| 1903 |
+
self.end = None
|
| 1904 |
+
self.start = None
|
| 1905 |
+
self.closed = False
|
| 1906 |
+
|
| 1907 |
+
if cache_options is None:
|
| 1908 |
+
cache_options = {}
|
| 1909 |
+
|
| 1910 |
+
if "trim" in kwargs:
|
| 1911 |
+
warnings.warn(
|
| 1912 |
+
"Passing 'trim' to control the cache behavior has been deprecated. "
|
| 1913 |
+
"Specify it within the 'cache_options' argument instead.",
|
| 1914 |
+
FutureWarning,
|
| 1915 |
+
)
|
| 1916 |
+
cache_options["trim"] = kwargs.pop("trim")
|
| 1917 |
+
|
| 1918 |
+
self.kwargs = kwargs
|
| 1919 |
+
|
| 1920 |
+
if mode not in {"ab", "rb", "wb", "xb"}:
|
| 1921 |
+
raise NotImplementedError("File mode not supported")
|
| 1922 |
+
if mode == "rb":
|
| 1923 |
+
if size is not None:
|
| 1924 |
+
self.size = size
|
| 1925 |
+
else:
|
| 1926 |
+
self.size = self.details["size"]
|
| 1927 |
+
self.cache = caches[cache_type](
|
| 1928 |
+
self.blocksize, self._fetch_range, self.size, **cache_options
|
| 1929 |
+
)
|
| 1930 |
+
else:
|
| 1931 |
+
self.buffer = io.BytesIO()
|
| 1932 |
+
self.offset = None
|
| 1933 |
+
self.forced = False
|
| 1934 |
+
self.location = None
|
| 1935 |
+
|
| 1936 |
+
@property
|
| 1937 |
+
def details(self):
|
| 1938 |
+
if self._details is None:
|
| 1939 |
+
self._details = self.fs.info(self.path)
|
| 1940 |
+
return self._details
|
| 1941 |
+
|
| 1942 |
+
@details.setter
|
| 1943 |
+
def details(self, value):
|
| 1944 |
+
self._details = value
|
| 1945 |
+
self.size = value["size"]
|
| 1946 |
+
|
| 1947 |
+
@property
|
| 1948 |
+
def full_name(self):
|
| 1949 |
+
return _unstrip_protocol(self.path, self.fs)
|
| 1950 |
+
|
| 1951 |
+
@property
|
| 1952 |
+
def closed(self):
|
| 1953 |
+
# get around this attr being read-only in IOBase
|
| 1954 |
+
# use getattr here, since this can be called during del
|
| 1955 |
+
return getattr(self, "_closed", True)
|
| 1956 |
+
|
| 1957 |
+
@closed.setter
|
| 1958 |
+
def closed(self, c):
|
| 1959 |
+
self._closed = c
|
| 1960 |
+
|
| 1961 |
+
def __hash__(self):
|
| 1962 |
+
if "w" in self.mode:
|
| 1963 |
+
return id(self)
|
| 1964 |
+
else:
|
| 1965 |
+
return int(tokenize(self.details), 16)
|
| 1966 |
+
|
| 1967 |
+
def __eq__(self, other):
|
| 1968 |
+
"""Files are equal if they have the same checksum, only in read mode"""
|
| 1969 |
+
if self is other:
|
| 1970 |
+
return True
|
| 1971 |
+
return (
|
| 1972 |
+
isinstance(other, type(self))
|
| 1973 |
+
and self.mode == "rb"
|
| 1974 |
+
and other.mode == "rb"
|
| 1975 |
+
and hash(self) == hash(other)
|
| 1976 |
+
)
|
| 1977 |
+
|
| 1978 |
+
def commit(self):
|
| 1979 |
+
"""Move from temp to final destination"""
|
| 1980 |
+
|
| 1981 |
+
def discard(self):
|
| 1982 |
+
"""Throw away temporary file"""
|
| 1983 |
+
|
| 1984 |
+
def info(self):
|
| 1985 |
+
"""File information about this path"""
|
| 1986 |
+
if self.readable():
|
| 1987 |
+
return self.details
|
| 1988 |
+
else:
|
| 1989 |
+
raise ValueError("Info not available while writing")
|
| 1990 |
+
|
| 1991 |
+
def tell(self):
|
| 1992 |
+
"""Current file location"""
|
| 1993 |
+
return self.loc
|
| 1994 |
+
|
| 1995 |
+
def seek(self, loc, whence=0):
|
| 1996 |
+
"""Set current file location
|
| 1997 |
+
|
| 1998 |
+
Parameters
|
| 1999 |
+
----------
|
| 2000 |
+
loc: int
|
| 2001 |
+
byte location
|
| 2002 |
+
whence: {0, 1, 2}
|
| 2003 |
+
from start of file, current location or end of file, resp.
|
| 2004 |
+
"""
|
| 2005 |
+
loc = int(loc)
|
| 2006 |
+
if not self.mode == "rb":
|
| 2007 |
+
raise OSError(ESPIPE, "Seek only available in read mode")
|
| 2008 |
+
if whence == 0:
|
| 2009 |
+
nloc = loc
|
| 2010 |
+
elif whence == 1:
|
| 2011 |
+
nloc = self.loc + loc
|
| 2012 |
+
elif whence == 2:
|
| 2013 |
+
nloc = self.size + loc
|
| 2014 |
+
else:
|
| 2015 |
+
raise ValueError(f"invalid whence ({whence}, should be 0, 1 or 2)")
|
| 2016 |
+
if nloc < 0:
|
| 2017 |
+
raise ValueError("Seek before start of file")
|
| 2018 |
+
self.loc = nloc
|
| 2019 |
+
return self.loc
|
| 2020 |
+
|
| 2021 |
+
def write(self, data):
|
| 2022 |
+
"""
|
| 2023 |
+
Write data to buffer.
|
| 2024 |
+
|
| 2025 |
+
Buffer only sent on flush() or if buffer is greater than
|
| 2026 |
+
or equal to blocksize.
|
| 2027 |
+
|
| 2028 |
+
Parameters
|
| 2029 |
+
----------
|
| 2030 |
+
data: bytes
|
| 2031 |
+
Set of bytes to be written.
|
| 2032 |
+
"""
|
| 2033 |
+
if not self.writable():
|
| 2034 |
+
raise ValueError("File not in write mode")
|
| 2035 |
+
if self.closed:
|
| 2036 |
+
raise ValueError("I/O operation on closed file.")
|
| 2037 |
+
if self.forced:
|
| 2038 |
+
raise ValueError("This file has been force-flushed, can only close")
|
| 2039 |
+
out = self.buffer.write(data)
|
| 2040 |
+
self.loc += out
|
| 2041 |
+
if self.buffer.tell() >= self.blocksize:
|
| 2042 |
+
self.flush()
|
| 2043 |
+
return out
|
| 2044 |
+
|
| 2045 |
+
def flush(self, force=False):
|
| 2046 |
+
"""
|
| 2047 |
+
Write buffered data to backend store.
|
| 2048 |
+
|
| 2049 |
+
Writes the current buffer, if it is larger than the block-size, or if
|
| 2050 |
+
the file is being closed.
|
| 2051 |
+
|
| 2052 |
+
Parameters
|
| 2053 |
+
----------
|
| 2054 |
+
force: bool
|
| 2055 |
+
When closing, write the last block even if it is smaller than
|
| 2056 |
+
blocks are allowed to be. Disallows further writing to this file.
|
| 2057 |
+
"""
|
| 2058 |
+
|
| 2059 |
+
if self.closed:
|
| 2060 |
+
raise ValueError("Flush on closed file")
|
| 2061 |
+
if force and self.forced:
|
| 2062 |
+
raise ValueError("Force flush cannot be called more than once")
|
| 2063 |
+
if force:
|
| 2064 |
+
self.forced = True
|
| 2065 |
+
|
| 2066 |
+
if self.readable():
|
| 2067 |
+
# no-op to flush on read-mode
|
| 2068 |
+
return
|
| 2069 |
+
|
| 2070 |
+
if not force and self.buffer.tell() < self.blocksize:
|
| 2071 |
+
# Defer write on small block
|
| 2072 |
+
return
|
| 2073 |
+
|
| 2074 |
+
if self.offset is None:
|
| 2075 |
+
# Initialize a multipart upload
|
| 2076 |
+
self.offset = 0
|
| 2077 |
+
try:
|
| 2078 |
+
self._initiate_upload()
|
| 2079 |
+
except:
|
| 2080 |
+
self.closed = True
|
| 2081 |
+
raise
|
| 2082 |
+
|
| 2083 |
+
if self._upload_chunk(final=force) is not False:
|
| 2084 |
+
self.offset += self.buffer.seek(0, 2)
|
| 2085 |
+
self.buffer = io.BytesIO()
|
| 2086 |
+
|
| 2087 |
+
def _upload_chunk(self, final=False):
|
| 2088 |
+
"""Write one part of a multi-block file upload
|
| 2089 |
+
|
| 2090 |
+
Parameters
|
| 2091 |
+
==========
|
| 2092 |
+
final: bool
|
| 2093 |
+
This is the last block, so should complete file, if
|
| 2094 |
+
self.autocommit is True.
|
| 2095 |
+
"""
|
| 2096 |
+
# may not yet have been initialized, may need to call _initialize_upload
|
| 2097 |
+
|
| 2098 |
+
def _initiate_upload(self):
|
| 2099 |
+
"""Create remote file/upload"""
|
| 2100 |
+
pass
|
| 2101 |
+
|
| 2102 |
+
def _fetch_range(self, start, end):
|
| 2103 |
+
"""Get the specified set of bytes from remote"""
|
| 2104 |
+
return self.fs.cat_file(self.path, start=start, end=end)
|
| 2105 |
+
|
| 2106 |
+
def read(self, length=-1):
|
| 2107 |
+
"""
|
| 2108 |
+
Return data from cache, or fetch pieces as necessary
|
| 2109 |
+
|
| 2110 |
+
Parameters
|
| 2111 |
+
----------
|
| 2112 |
+
length: int (-1)
|
| 2113 |
+
Number of bytes to read; if <0, all remaining bytes.
|
| 2114 |
+
"""
|
| 2115 |
+
length = -1 if length is None else int(length)
|
| 2116 |
+
if self.mode != "rb":
|
| 2117 |
+
raise ValueError("File not in read mode")
|
| 2118 |
+
if length < 0:
|
| 2119 |
+
length = self.size - self.loc
|
| 2120 |
+
if self.closed:
|
| 2121 |
+
raise ValueError("I/O operation on closed file.")
|
| 2122 |
+
if length == 0:
|
| 2123 |
+
# don't even bother calling fetch
|
| 2124 |
+
return b""
|
| 2125 |
+
out = self.cache._fetch(self.loc, self.loc + length)
|
| 2126 |
+
|
| 2127 |
+
logger.debug(
|
| 2128 |
+
"%s read: %i - %i %s",
|
| 2129 |
+
self,
|
| 2130 |
+
self.loc,
|
| 2131 |
+
self.loc + length,
|
| 2132 |
+
self.cache._log_stats(),
|
| 2133 |
+
)
|
| 2134 |
+
self.loc += len(out)
|
| 2135 |
+
return out
|
| 2136 |
+
|
| 2137 |
+
def readinto(self, b):
|
| 2138 |
+
"""mirrors builtin file's readinto method
|
| 2139 |
+
|
| 2140 |
+
https://docs.python.org/3/library/io.html#io.RawIOBase.readinto
|
| 2141 |
+
"""
|
| 2142 |
+
out = memoryview(b).cast("B")
|
| 2143 |
+
data = self.read(out.nbytes)
|
| 2144 |
+
out[: len(data)] = data
|
| 2145 |
+
return len(data)
|
| 2146 |
+
|
| 2147 |
+
def readuntil(self, char=b"\n", blocks=None):
|
| 2148 |
+
"""Return data between current position and first occurrence of char
|
| 2149 |
+
|
| 2150 |
+
char is included in the output, except if the end of the tile is
|
| 2151 |
+
encountered first.
|
| 2152 |
+
|
| 2153 |
+
Parameters
|
| 2154 |
+
----------
|
| 2155 |
+
char: bytes
|
| 2156 |
+
Thing to find
|
| 2157 |
+
blocks: None or int
|
| 2158 |
+
How much to read in each go. Defaults to file blocksize - which may
|
| 2159 |
+
mean a new read on every call.
|
| 2160 |
+
"""
|
| 2161 |
+
out = []
|
| 2162 |
+
while True:
|
| 2163 |
+
start = self.tell()
|
| 2164 |
+
part = self.read(blocks or self.blocksize)
|
| 2165 |
+
if len(part) == 0:
|
| 2166 |
+
break
|
| 2167 |
+
found = part.find(char)
|
| 2168 |
+
if found > -1:
|
| 2169 |
+
out.append(part[: found + len(char)])
|
| 2170 |
+
self.seek(start + found + len(char))
|
| 2171 |
+
break
|
| 2172 |
+
out.append(part)
|
| 2173 |
+
return b"".join(out)
|
| 2174 |
+
|
| 2175 |
+
def readline(self):
|
| 2176 |
+
"""Read until and including the first occurrence of newline character
|
| 2177 |
+
|
| 2178 |
+
Note that, because of character encoding, this is not necessarily a
|
| 2179 |
+
true line ending.
|
| 2180 |
+
"""
|
| 2181 |
+
return self.readuntil(b"\n")
|
| 2182 |
+
|
| 2183 |
+
def __next__(self):
|
| 2184 |
+
out = self.readline()
|
| 2185 |
+
if out:
|
| 2186 |
+
return out
|
| 2187 |
+
raise StopIteration
|
| 2188 |
+
|
| 2189 |
+
def __iter__(self):
|
| 2190 |
+
return self
|
| 2191 |
+
|
| 2192 |
+
def readlines(self):
|
| 2193 |
+
"""Return all data, split by the newline character, including the newline character"""
|
| 2194 |
+
data = self.read()
|
| 2195 |
+
lines = data.split(b"\n")
|
| 2196 |
+
out = [l + b"\n" for l in lines[:-1]]
|
| 2197 |
+
if data.endswith(b"\n"):
|
| 2198 |
+
return out
|
| 2199 |
+
else:
|
| 2200 |
+
return out + [lines[-1]]
|
| 2201 |
+
# return list(self) ???
|
| 2202 |
+
|
| 2203 |
+
def readinto1(self, b):
|
| 2204 |
+
return self.readinto(b)
|
| 2205 |
+
|
| 2206 |
+
def close(self):
|
| 2207 |
+
"""Close file
|
| 2208 |
+
|
| 2209 |
+
Finalizes writes, discards cache
|
| 2210 |
+
"""
|
| 2211 |
+
if getattr(self, "_unclosable", False):
|
| 2212 |
+
return
|
| 2213 |
+
if self.closed:
|
| 2214 |
+
return
|
| 2215 |
+
try:
|
| 2216 |
+
if self.mode == "rb":
|
| 2217 |
+
self.cache = None
|
| 2218 |
+
else:
|
| 2219 |
+
if not self.forced:
|
| 2220 |
+
self.flush(force=True)
|
| 2221 |
+
|
| 2222 |
+
if self.fs is not None:
|
| 2223 |
+
self.fs.invalidate_cache(self.path)
|
| 2224 |
+
self.fs.invalidate_cache(self.fs._parent(self.path))
|
| 2225 |
+
finally:
|
| 2226 |
+
self.closed = True
|
| 2227 |
+
|
| 2228 |
+
def readable(self):
|
| 2229 |
+
"""Whether opened for reading"""
|
| 2230 |
+
return "r" in self.mode and not self.closed
|
| 2231 |
+
|
| 2232 |
+
def seekable(self):
|
| 2233 |
+
"""Whether is seekable (only in read mode)"""
|
| 2234 |
+
return self.readable()
|
| 2235 |
+
|
| 2236 |
+
def writable(self):
|
| 2237 |
+
"""Whether opened for writing"""
|
| 2238 |
+
return self.mode in {"wb", "ab", "xb"} and not self.closed
|
| 2239 |
+
|
| 2240 |
+
def __reduce__(self):
|
| 2241 |
+
if self.mode != "rb":
|
| 2242 |
+
raise RuntimeError("Pickling a writeable file is not supported")
|
| 2243 |
+
|
| 2244 |
+
return reopen, (
|
| 2245 |
+
self.fs,
|
| 2246 |
+
self.path,
|
| 2247 |
+
self.mode,
|
| 2248 |
+
self.blocksize,
|
| 2249 |
+
self.loc,
|
| 2250 |
+
self.size,
|
| 2251 |
+
self.autocommit,
|
| 2252 |
+
self.cache.name if self.cache else "none",
|
| 2253 |
+
self.kwargs,
|
| 2254 |
+
)
|
| 2255 |
+
|
| 2256 |
+
def __del__(self):
|
| 2257 |
+
if not self.closed:
|
| 2258 |
+
self.close()
|
| 2259 |
+
|
| 2260 |
+
def __str__(self):
|
| 2261 |
+
return f"<File-like object {type(self.fs).__name__}, {self.path}>"
|
| 2262 |
+
|
| 2263 |
+
__repr__ = __str__
|
| 2264 |
+
|
| 2265 |
+
def __enter__(self):
|
| 2266 |
+
return self
|
| 2267 |
+
|
| 2268 |
+
def __exit__(self, *args):
|
| 2269 |
+
self.close()
|
| 2270 |
+
|
| 2271 |
+
|
| 2272 |
+
def reopen(fs, path, mode, blocksize, loc, size, autocommit, cache_type, kwargs):
|
| 2273 |
+
file = fs.open(
|
| 2274 |
+
path,
|
| 2275 |
+
mode=mode,
|
| 2276 |
+
block_size=blocksize,
|
| 2277 |
+
autocommit=autocommit,
|
| 2278 |
+
cache_type=cache_type,
|
| 2279 |
+
size=size,
|
| 2280 |
+
**kwargs,
|
| 2281 |
+
)
|
| 2282 |
+
if loc > 0:
|
| 2283 |
+
file.seek(loc)
|
| 2284 |
+
return file
|
micromamba_root/envs/hf_sync/Lib/site-packages/fsspec/transaction.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections import deque
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class Transaction:
|
| 5 |
+
"""Filesystem transaction write context
|
| 6 |
+
|
| 7 |
+
Gathers files for deferred commit or discard, so that several write
|
| 8 |
+
operations can be finalized semi-atomically. This works by having this
|
| 9 |
+
instance as the ``.transaction`` attribute of the given filesystem
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
def __init__(self, fs, **kwargs):
|
| 13 |
+
"""
|
| 14 |
+
Parameters
|
| 15 |
+
----------
|
| 16 |
+
fs: FileSystem instance
|
| 17 |
+
"""
|
| 18 |
+
self.fs = fs
|
| 19 |
+
self.files = deque()
|
| 20 |
+
|
| 21 |
+
def __enter__(self):
|
| 22 |
+
self.start()
|
| 23 |
+
return self
|
| 24 |
+
|
| 25 |
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
| 26 |
+
"""End transaction and commit, if exit is not due to exception"""
|
| 27 |
+
# only commit if there was no exception
|
| 28 |
+
self.complete(commit=exc_type is None)
|
| 29 |
+
if self.fs:
|
| 30 |
+
self.fs._intrans = False
|
| 31 |
+
self.fs._transaction = None
|
| 32 |
+
self.fs = None
|
| 33 |
+
|
| 34 |
+
def start(self):
|
| 35 |
+
"""Start a transaction on this FileSystem"""
|
| 36 |
+
self.files = deque() # clean up after previous failed completions
|
| 37 |
+
self.fs._intrans = True
|
| 38 |
+
|
| 39 |
+
def complete(self, commit=True):
|
| 40 |
+
"""Finish transaction: commit or discard all deferred files"""
|
| 41 |
+
while self.files:
|
| 42 |
+
f = self.files.popleft()
|
| 43 |
+
if commit:
|
| 44 |
+
f.commit()
|
| 45 |
+
else:
|
| 46 |
+
f.discard()
|
| 47 |
+
self.fs._intrans = False
|
| 48 |
+
self.fs._transaction = None
|
| 49 |
+
self.fs = None
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class FileActor:
|
| 53 |
+
def __init__(self):
|
| 54 |
+
self.files = []
|
| 55 |
+
|
| 56 |
+
def commit(self):
|
| 57 |
+
for f in self.files:
|
| 58 |
+
f.commit()
|
| 59 |
+
self.files.clear()
|
| 60 |
+
|
| 61 |
+
def discard(self):
|
| 62 |
+
for f in self.files:
|
| 63 |
+
f.discard()
|
| 64 |
+
self.files.clear()
|
| 65 |
+
|
| 66 |
+
def append(self, f):
|
| 67 |
+
self.files.append(f)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
class DaskTransaction(Transaction):
|
| 71 |
+
def __init__(self, fs):
|
| 72 |
+
"""
|
| 73 |
+
Parameters
|
| 74 |
+
----------
|
| 75 |
+
fs: FileSystem instance
|
| 76 |
+
"""
|
| 77 |
+
import distributed
|
| 78 |
+
|
| 79 |
+
super().__init__(fs)
|
| 80 |
+
client = distributed.default_client()
|
| 81 |
+
self.files = client.submit(FileActor, actor=True).result()
|
| 82 |
+
|
| 83 |
+
def complete(self, commit=True):
|
| 84 |
+
"""Finish transaction: commit or discard all deferred files"""
|
| 85 |
+
if commit:
|
| 86 |
+
self.files.commit().result()
|
| 87 |
+
else:
|
| 88 |
+
self.files.discard().result()
|
| 89 |
+
self.fs._intrans = False
|
| 90 |
+
self.fs = None
|
micromamba_root/envs/hf_sync/Lib/site-packages/fsspec/utils.py
ADDED
|
@@ -0,0 +1,748 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
| 7 |
+
import re
|
| 8 |
+
import sys
|
| 9 |
+
import tempfile
|
| 10 |
+
from collections.abc import Callable, Iterable, Iterator, Sequence
|
| 11 |
+
from functools import partial
|
| 12 |
+
from hashlib import md5
|
| 13 |
+
from importlib.metadata import version
|
| 14 |
+
from typing import IO, TYPE_CHECKING, Any, TypeVar
|
| 15 |
+
from urllib.parse import urlsplit
|
| 16 |
+
|
| 17 |
+
if TYPE_CHECKING:
|
| 18 |
+
import pathlib
|
| 19 |
+
from typing import TypeGuard
|
| 20 |
+
|
| 21 |
+
from fsspec.spec import AbstractFileSystem
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
DEFAULT_BLOCK_SIZE = 5 * 2**20
|
| 25 |
+
|
| 26 |
+
T = TypeVar("T")
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def infer_storage_options(
|
| 30 |
+
urlpath: str, inherit_storage_options: dict[str, Any] | None = None
|
| 31 |
+
) -> dict[str, Any]:
|
| 32 |
+
"""Infer storage options from URL path and merge it with existing storage
|
| 33 |
+
options.
|
| 34 |
+
|
| 35 |
+
Parameters
|
| 36 |
+
----------
|
| 37 |
+
urlpath: str or unicode
|
| 38 |
+
Either local absolute file path or URL (hdfs://namenode:8020/file.csv)
|
| 39 |
+
inherit_storage_options: dict (optional)
|
| 40 |
+
Its contents will get merged with the inferred information from the
|
| 41 |
+
given path
|
| 42 |
+
|
| 43 |
+
Returns
|
| 44 |
+
-------
|
| 45 |
+
Storage options dict.
|
| 46 |
+
|
| 47 |
+
Examples
|
| 48 |
+
--------
|
| 49 |
+
>>> infer_storage_options('/mnt/datasets/test.csv') # doctest: +SKIP
|
| 50 |
+
{"protocol": "file", "path", "/mnt/datasets/test.csv"}
|
| 51 |
+
>>> infer_storage_options(
|
| 52 |
+
... 'hdfs://username:pwd@node:123/mnt/datasets/test.csv?q=1',
|
| 53 |
+
... inherit_storage_options={'extra': 'value'},
|
| 54 |
+
... ) # doctest: +SKIP
|
| 55 |
+
{"protocol": "hdfs", "username": "username", "password": "pwd",
|
| 56 |
+
"host": "node", "port": 123, "path": "/mnt/datasets/test.csv",
|
| 57 |
+
"url_query": "q=1", "extra": "value"}
|
| 58 |
+
"""
|
| 59 |
+
# Handle Windows paths including disk name in this special case
|
| 60 |
+
if (
|
| 61 |
+
re.match(r"^[a-zA-Z]:[\\/]", urlpath)
|
| 62 |
+
or re.match(r"^[a-zA-Z0-9]+://", urlpath) is None
|
| 63 |
+
):
|
| 64 |
+
return {"protocol": "file", "path": urlpath}
|
| 65 |
+
|
| 66 |
+
parsed_path = urlsplit(urlpath)
|
| 67 |
+
protocol = parsed_path.scheme or "file"
|
| 68 |
+
if parsed_path.fragment:
|
| 69 |
+
path = "#".join([parsed_path.path, parsed_path.fragment])
|
| 70 |
+
else:
|
| 71 |
+
path = parsed_path.path
|
| 72 |
+
if protocol == "file":
|
| 73 |
+
# Special case parsing file protocol URL on Windows according to:
|
| 74 |
+
# https://msdn.microsoft.com/en-us/library/jj710207.aspx
|
| 75 |
+
windows_path = re.match(r"^/([a-zA-Z])[:|]([\\/].*)$", path)
|
| 76 |
+
if windows_path:
|
| 77 |
+
drive, path = windows_path.groups()
|
| 78 |
+
path = f"{drive}:{path}"
|
| 79 |
+
|
| 80 |
+
if protocol in ["http", "https"]:
|
| 81 |
+
# for HTTP, we don't want to parse, as requests will anyway
|
| 82 |
+
return {"protocol": protocol, "path": urlpath}
|
| 83 |
+
|
| 84 |
+
options: dict[str, Any] = {"protocol": protocol, "path": path}
|
| 85 |
+
|
| 86 |
+
if parsed_path.netloc:
|
| 87 |
+
# Parse `hostname` from netloc manually because `parsed_path.hostname`
|
| 88 |
+
# lowercases the hostname which is not always desirable (e.g. in S3):
|
| 89 |
+
# https://github.com/dask/dask/issues/1417
|
| 90 |
+
options["host"] = parsed_path.netloc.rsplit("@", 1)[-1].rsplit(":", 1)[0]
|
| 91 |
+
|
| 92 |
+
if protocol in ("s3", "s3a", "gcs", "gs"):
|
| 93 |
+
options["path"] = options["host"] + options["path"]
|
| 94 |
+
else:
|
| 95 |
+
options["host"] = options["host"]
|
| 96 |
+
if parsed_path.port:
|
| 97 |
+
options["port"] = parsed_path.port
|
| 98 |
+
if parsed_path.username:
|
| 99 |
+
options["username"] = parsed_path.username
|
| 100 |
+
if parsed_path.password:
|
| 101 |
+
options["password"] = parsed_path.password
|
| 102 |
+
|
| 103 |
+
if parsed_path.query:
|
| 104 |
+
options["url_query"] = parsed_path.query
|
| 105 |
+
if parsed_path.fragment:
|
| 106 |
+
options["url_fragment"] = parsed_path.fragment
|
| 107 |
+
|
| 108 |
+
if inherit_storage_options:
|
| 109 |
+
update_storage_options(options, inherit_storage_options)
|
| 110 |
+
|
| 111 |
+
return options
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def update_storage_options(
|
| 115 |
+
options: dict[str, Any], inherited: dict[str, Any] | None = None
|
| 116 |
+
) -> None:
|
| 117 |
+
if not inherited:
|
| 118 |
+
inherited = {}
|
| 119 |
+
collisions = set(options) & set(inherited)
|
| 120 |
+
if collisions:
|
| 121 |
+
for collision in collisions:
|
| 122 |
+
if options.get(collision) != inherited.get(collision):
|
| 123 |
+
raise KeyError(
|
| 124 |
+
f"Collision between inferred and specified storage "
|
| 125 |
+
f"option:\n{collision}"
|
| 126 |
+
)
|
| 127 |
+
options.update(inherited)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
# Compression extensions registered via fsspec.compression.register_compression
|
| 131 |
+
compressions: dict[str, str] = {}
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def infer_compression(filename: str) -> str | None:
|
| 135 |
+
"""Infer compression, if available, from filename.
|
| 136 |
+
|
| 137 |
+
Infer a named compression type, if registered and available, from filename
|
| 138 |
+
extension. This includes builtin (gz, bz2, zip) compressions, as well as
|
| 139 |
+
optional compressions. See fsspec.compression.register_compression.
|
| 140 |
+
"""
|
| 141 |
+
extension = os.path.splitext(filename)[-1].strip(".").lower()
|
| 142 |
+
if extension in compressions:
|
| 143 |
+
return compressions[extension]
|
| 144 |
+
return None
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def build_name_function(max_int: float) -> Callable[[int], str]:
|
| 148 |
+
"""Returns a function that receives a single integer
|
| 149 |
+
and returns it as a string padded by enough zero characters
|
| 150 |
+
to align with maximum possible integer
|
| 151 |
+
|
| 152 |
+
>>> name_f = build_name_function(57)
|
| 153 |
+
|
| 154 |
+
>>> name_f(7)
|
| 155 |
+
'07'
|
| 156 |
+
>>> name_f(31)
|
| 157 |
+
'31'
|
| 158 |
+
>>> build_name_function(1000)(42)
|
| 159 |
+
'0042'
|
| 160 |
+
>>> build_name_function(999)(42)
|
| 161 |
+
'042'
|
| 162 |
+
>>> build_name_function(0)(0)
|
| 163 |
+
'0'
|
| 164 |
+
"""
|
| 165 |
+
# handle corner cases max_int is 0 or exact power of 10
|
| 166 |
+
max_int += 1e-8
|
| 167 |
+
|
| 168 |
+
pad_length = int(math.ceil(math.log10(max_int)))
|
| 169 |
+
|
| 170 |
+
def name_function(i: int) -> str:
|
| 171 |
+
return str(i).zfill(pad_length)
|
| 172 |
+
|
| 173 |
+
return name_function
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def seek_delimiter(file: IO[bytes], delimiter: bytes, blocksize: int) -> bool:
|
| 177 |
+
r"""Seek current file to file start, file end, or byte after delimiter seq.
|
| 178 |
+
|
| 179 |
+
Seeks file to next chunk delimiter, where chunks are defined on file start,
|
| 180 |
+
a delimiting sequence, and file end. Use file.tell() to see location afterwards.
|
| 181 |
+
Note that file start is a valid split, so must be at offset > 0 to seek for
|
| 182 |
+
delimiter.
|
| 183 |
+
|
| 184 |
+
Parameters
|
| 185 |
+
----------
|
| 186 |
+
file: a file
|
| 187 |
+
delimiter: bytes
|
| 188 |
+
a delimiter like ``b'\n'`` or message sentinel, matching file .read() type
|
| 189 |
+
blocksize: int
|
| 190 |
+
Number of bytes to read from the file at once.
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
Returns
|
| 194 |
+
-------
|
| 195 |
+
Returns True if a delimiter was found, False if at file start or end.
|
| 196 |
+
|
| 197 |
+
"""
|
| 198 |
+
|
| 199 |
+
if file.tell() == 0:
|
| 200 |
+
# beginning-of-file, return without seek
|
| 201 |
+
return False
|
| 202 |
+
|
| 203 |
+
# Interface is for binary IO, with delimiter as bytes, but initialize last
|
| 204 |
+
# with result of file.read to preserve compatibility with text IO.
|
| 205 |
+
last: bytes | None = None
|
| 206 |
+
while True:
|
| 207 |
+
current = file.read(blocksize)
|
| 208 |
+
if not current:
|
| 209 |
+
# end-of-file without delimiter
|
| 210 |
+
return False
|
| 211 |
+
full = last + current if last else current
|
| 212 |
+
try:
|
| 213 |
+
if delimiter in full:
|
| 214 |
+
i = full.index(delimiter)
|
| 215 |
+
file.seek(file.tell() - (len(full) - i) + len(delimiter))
|
| 216 |
+
return True
|
| 217 |
+
elif len(current) < blocksize:
|
| 218 |
+
# end-of-file without delimiter
|
| 219 |
+
return False
|
| 220 |
+
except (OSError, ValueError):
|
| 221 |
+
pass
|
| 222 |
+
last = full[-len(delimiter) :]
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def read_block(
|
| 226 |
+
f: IO[bytes],
|
| 227 |
+
offset: int,
|
| 228 |
+
length: int | None,
|
| 229 |
+
delimiter: bytes | None = None,
|
| 230 |
+
split_before: bool = False,
|
| 231 |
+
) -> bytes:
|
| 232 |
+
"""Read a block of bytes from a file
|
| 233 |
+
|
| 234 |
+
Parameters
|
| 235 |
+
----------
|
| 236 |
+
f: File
|
| 237 |
+
Open file
|
| 238 |
+
offset: int
|
| 239 |
+
Byte offset to start read
|
| 240 |
+
length: int
|
| 241 |
+
Number of bytes to read, read through end of file if None
|
| 242 |
+
delimiter: bytes (optional)
|
| 243 |
+
Ensure reading starts and stops at delimiter bytestring
|
| 244 |
+
split_before: bool (optional)
|
| 245 |
+
Start/stop read *before* delimiter bytestring.
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
If using the ``delimiter=`` keyword argument we ensure that the read
|
| 249 |
+
starts and stops at delimiter boundaries that follow the locations
|
| 250 |
+
``offset`` and ``offset + length``. If ``offset`` is zero then we
|
| 251 |
+
start at zero, regardless of delimiter. The bytestring returned WILL
|
| 252 |
+
include the terminating delimiter string.
|
| 253 |
+
|
| 254 |
+
Examples
|
| 255 |
+
--------
|
| 256 |
+
|
| 257 |
+
>>> from io import BytesIO # doctest: +SKIP
|
| 258 |
+
>>> f = BytesIO(b'Alice, 100\\nBob, 200\\nCharlie, 300') # doctest: +SKIP
|
| 259 |
+
>>> read_block(f, 0, 13) # doctest: +SKIP
|
| 260 |
+
b'Alice, 100\\nBo'
|
| 261 |
+
|
| 262 |
+
>>> read_block(f, 0, 13, delimiter=b'\\n') # doctest: +SKIP
|
| 263 |
+
b'Alice, 100\\nBob, 200\\n'
|
| 264 |
+
|
| 265 |
+
>>> read_block(f, 10, 10, delimiter=b'\\n') # doctest: +SKIP
|
| 266 |
+
b'Bob, 200\\nCharlie, 300'
|
| 267 |
+
"""
|
| 268 |
+
if delimiter:
|
| 269 |
+
f.seek(offset)
|
| 270 |
+
found_start_delim = seek_delimiter(f, delimiter, 2**16)
|
| 271 |
+
if length is None:
|
| 272 |
+
return f.read()
|
| 273 |
+
start = f.tell()
|
| 274 |
+
length -= start - offset
|
| 275 |
+
|
| 276 |
+
f.seek(start + length)
|
| 277 |
+
found_end_delim = seek_delimiter(f, delimiter, 2**16)
|
| 278 |
+
end = f.tell()
|
| 279 |
+
|
| 280 |
+
# Adjust split location to before delimiter if seek found the
|
| 281 |
+
# delimiter sequence, not start or end of file.
|
| 282 |
+
if found_start_delim and split_before:
|
| 283 |
+
start -= len(delimiter)
|
| 284 |
+
|
| 285 |
+
if found_end_delim and split_before:
|
| 286 |
+
end -= len(delimiter)
|
| 287 |
+
|
| 288 |
+
offset = start
|
| 289 |
+
length = end - start
|
| 290 |
+
|
| 291 |
+
f.seek(offset)
|
| 292 |
+
|
| 293 |
+
# TODO: allow length to be None and read to the end of the file?
|
| 294 |
+
assert length is not None
|
| 295 |
+
b = f.read(length)
|
| 296 |
+
return b
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
def tokenize(*args: Any, **kwargs: Any) -> str:
|
| 300 |
+
"""Deterministic token
|
| 301 |
+
|
| 302 |
+
(modified from dask.base)
|
| 303 |
+
|
| 304 |
+
>>> tokenize([1, 2, '3'])
|
| 305 |
+
'9d71491b50023b06fc76928e6eddb952'
|
| 306 |
+
|
| 307 |
+
>>> tokenize('Hello') == tokenize('Hello')
|
| 308 |
+
True
|
| 309 |
+
"""
|
| 310 |
+
if kwargs:
|
| 311 |
+
args += (kwargs,)
|
| 312 |
+
try:
|
| 313 |
+
h = md5(str(args).encode())
|
| 314 |
+
except ValueError:
|
| 315 |
+
# FIPS systems: https://github.com/fsspec/filesystem_spec/issues/380
|
| 316 |
+
h = md5(str(args).encode(), usedforsecurity=False)
|
| 317 |
+
return h.hexdigest()
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
def stringify_path(filepath: str | os.PathLike[str] | pathlib.Path) -> str:
|
| 321 |
+
"""Attempt to convert a path-like object to a string.
|
| 322 |
+
|
| 323 |
+
Parameters
|
| 324 |
+
----------
|
| 325 |
+
filepath: object to be converted
|
| 326 |
+
|
| 327 |
+
Returns
|
| 328 |
+
-------
|
| 329 |
+
filepath_str: maybe a string version of the object
|
| 330 |
+
|
| 331 |
+
Notes
|
| 332 |
+
-----
|
| 333 |
+
Objects supporting the fspath protocol are coerced according to its
|
| 334 |
+
__fspath__ method.
|
| 335 |
+
|
| 336 |
+
For backwards compatibility with older Python version, pathlib.Path
|
| 337 |
+
objects are specially coerced.
|
| 338 |
+
|
| 339 |
+
Any other object is passed through unchanged, which includes bytes,
|
| 340 |
+
strings, buffers, or anything else that's not even path-like.
|
| 341 |
+
"""
|
| 342 |
+
if isinstance(filepath, str):
|
| 343 |
+
return filepath
|
| 344 |
+
elif hasattr(filepath, "__fspath__"):
|
| 345 |
+
return filepath.__fspath__()
|
| 346 |
+
elif hasattr(filepath, "path"):
|
| 347 |
+
return filepath.path
|
| 348 |
+
else:
|
| 349 |
+
return filepath # type: ignore[return-value]
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
def make_instance(
|
| 353 |
+
cls: Callable[..., T], args: Sequence[Any], kwargs: dict[str, Any]
|
| 354 |
+
) -> T:
|
| 355 |
+
inst = cls(*args, **kwargs)
|
| 356 |
+
inst._determine_worker() # type: ignore[attr-defined]
|
| 357 |
+
return inst
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
def common_prefix(paths: Iterable[str]) -> str:
|
| 361 |
+
"""For a list of paths, find the shortest prefix common to all"""
|
| 362 |
+
parts = [p.split("/") for p in paths]
|
| 363 |
+
lmax = min(len(p) for p in parts)
|
| 364 |
+
end = 0
|
| 365 |
+
for i in range(lmax):
|
| 366 |
+
end = all(p[i] == parts[0][i] for p in parts)
|
| 367 |
+
if not end:
|
| 368 |
+
break
|
| 369 |
+
i += end
|
| 370 |
+
return "/".join(parts[0][:i])
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
def other_paths(
|
| 374 |
+
paths: list[str],
|
| 375 |
+
path2: str | list[str],
|
| 376 |
+
exists: bool = False,
|
| 377 |
+
flatten: bool = False,
|
| 378 |
+
) -> list[str]:
|
| 379 |
+
"""In bulk file operations, construct a new file tree from a list of files
|
| 380 |
+
|
| 381 |
+
Parameters
|
| 382 |
+
----------
|
| 383 |
+
paths: list of str
|
| 384 |
+
The input file tree
|
| 385 |
+
path2: str or list of str
|
| 386 |
+
Root to construct the new list in. If this is already a list of str, we just
|
| 387 |
+
assert it has the right number of elements.
|
| 388 |
+
exists: bool (optional)
|
| 389 |
+
For a str destination, it is already exists (and is a dir), files should
|
| 390 |
+
end up inside.
|
| 391 |
+
flatten: bool (optional)
|
| 392 |
+
Whether to flatten the input directory tree structure so that the output files
|
| 393 |
+
are in the same directory.
|
| 394 |
+
|
| 395 |
+
Returns
|
| 396 |
+
-------
|
| 397 |
+
list of str
|
| 398 |
+
"""
|
| 399 |
+
|
| 400 |
+
if isinstance(path2, str):
|
| 401 |
+
path2 = path2.rstrip("/")
|
| 402 |
+
|
| 403 |
+
if flatten:
|
| 404 |
+
path2 = ["/".join((path2, p.split("/")[-1])) for p in paths]
|
| 405 |
+
else:
|
| 406 |
+
cp = common_prefix(paths)
|
| 407 |
+
if exists:
|
| 408 |
+
cp = cp.rsplit("/", 1)[0]
|
| 409 |
+
if not cp and all(not s.startswith("/") for s in paths):
|
| 410 |
+
path2 = ["/".join([path2, p]) for p in paths]
|
| 411 |
+
else:
|
| 412 |
+
path2 = [p.replace(cp, path2, 1) for p in paths]
|
| 413 |
+
else:
|
| 414 |
+
assert len(paths) == len(path2)
|
| 415 |
+
return path2
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
def is_exception(obj: Any) -> bool:
|
| 419 |
+
return isinstance(obj, BaseException)
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
def isfilelike(f: Any) -> TypeGuard[IO[bytes]]:
|
| 423 |
+
return all(hasattr(f, attr) for attr in ["read", "close", "tell"])
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
def get_protocol(url: str) -> str:
|
| 427 |
+
url = stringify_path(url)
|
| 428 |
+
parts = re.split(r"(\:\:|\://)", url, maxsplit=1)
|
| 429 |
+
if len(parts) > 1:
|
| 430 |
+
return parts[0]
|
| 431 |
+
return "file"
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
def get_file_extension(url: str) -> str:
|
| 435 |
+
url = stringify_path(url)
|
| 436 |
+
ext_parts = url.rsplit(".", 1)
|
| 437 |
+
if len(ext_parts) > 1:
|
| 438 |
+
return ext_parts[-1]
|
| 439 |
+
return ""
|
| 440 |
+
|
| 441 |
+
|
| 442 |
+
def can_be_local(path: str) -> bool:
|
| 443 |
+
"""Can the given URL be used with open_local?"""
|
| 444 |
+
from fsspec import get_filesystem_class
|
| 445 |
+
|
| 446 |
+
try:
|
| 447 |
+
return getattr(get_filesystem_class(get_protocol(path)), "local_file", False)
|
| 448 |
+
except (ValueError, ImportError):
|
| 449 |
+
# not in registry or import failed
|
| 450 |
+
return False
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
def get_package_version_without_import(name: str) -> str | None:
|
| 454 |
+
"""For given package name, try to find the version without importing it
|
| 455 |
+
|
| 456 |
+
Import and package.__version__ is still the backup here, so an import
|
| 457 |
+
*might* happen.
|
| 458 |
+
|
| 459 |
+
Returns either the version string, or None if the package
|
| 460 |
+
or the version was not readily found.
|
| 461 |
+
"""
|
| 462 |
+
if name in sys.modules:
|
| 463 |
+
mod = sys.modules[name]
|
| 464 |
+
if hasattr(mod, "__version__"):
|
| 465 |
+
return mod.__version__
|
| 466 |
+
try:
|
| 467 |
+
return version(name)
|
| 468 |
+
except: # noqa: E722
|
| 469 |
+
pass
|
| 470 |
+
try:
|
| 471 |
+
import importlib
|
| 472 |
+
|
| 473 |
+
mod = importlib.import_module(name)
|
| 474 |
+
return mod.__version__
|
| 475 |
+
except (ImportError, AttributeError):
|
| 476 |
+
return None
|
| 477 |
+
|
| 478 |
+
|
| 479 |
+
def setup_logging(
|
| 480 |
+
logger: logging.Logger | None = None,
|
| 481 |
+
logger_name: str | None = None,
|
| 482 |
+
level: str = "DEBUG",
|
| 483 |
+
clear: bool = True,
|
| 484 |
+
) -> logging.Logger:
|
| 485 |
+
if logger is None and logger_name is None:
|
| 486 |
+
raise ValueError("Provide either logger object or logger name")
|
| 487 |
+
logger = logger or logging.getLogger(logger_name)
|
| 488 |
+
handle = logging.StreamHandler()
|
| 489 |
+
formatter = logging.Formatter(
|
| 490 |
+
"%(asctime)s - %(name)s - %(levelname)s - %(funcName)s -- %(message)s"
|
| 491 |
+
)
|
| 492 |
+
handle.setFormatter(formatter)
|
| 493 |
+
if clear:
|
| 494 |
+
logger.handlers.clear()
|
| 495 |
+
logger.addHandler(handle)
|
| 496 |
+
logger.setLevel(level)
|
| 497 |
+
return logger
|
| 498 |
+
|
| 499 |
+
|
| 500 |
+
def _unstrip_protocol(name: str, fs: AbstractFileSystem) -> str:
|
| 501 |
+
return fs.unstrip_protocol(name)
|
| 502 |
+
|
| 503 |
+
|
| 504 |
+
def mirror_from(
|
| 505 |
+
origin_name: str, methods: Iterable[str]
|
| 506 |
+
) -> Callable[[type[T]], type[T]]:
|
| 507 |
+
"""Mirror attributes and methods from the given
|
| 508 |
+
origin_name attribute of the instance to the
|
| 509 |
+
decorated class"""
|
| 510 |
+
|
| 511 |
+
def origin_getter(method: str, self: Any) -> Any:
|
| 512 |
+
origin = getattr(self, origin_name)
|
| 513 |
+
return getattr(origin, method)
|
| 514 |
+
|
| 515 |
+
def wrapper(cls: type[T]) -> type[T]:
|
| 516 |
+
for method in methods:
|
| 517 |
+
wrapped_method = partial(origin_getter, method)
|
| 518 |
+
setattr(cls, method, property(wrapped_method))
|
| 519 |
+
return cls
|
| 520 |
+
|
| 521 |
+
return wrapper
|
| 522 |
+
|
| 523 |
+
|
| 524 |
+
@contextlib.contextmanager
|
| 525 |
+
def nullcontext(obj: T) -> Iterator[T]:
|
| 526 |
+
yield obj
|
| 527 |
+
|
| 528 |
+
|
| 529 |
+
def merge_offset_ranges(
|
| 530 |
+
paths: list[str],
|
| 531 |
+
starts: list[int] | int,
|
| 532 |
+
ends: list[int] | int,
|
| 533 |
+
max_gap: int = 0,
|
| 534 |
+
max_block: int | None = None,
|
| 535 |
+
sort: bool = True,
|
| 536 |
+
) -> tuple[list[str], list[int], list[int]]:
|
| 537 |
+
"""Merge adjacent byte-offset ranges when the inter-range
|
| 538 |
+
gap is <= `max_gap`, and when the merged byte range does not
|
| 539 |
+
exceed `max_block` (if specified). By default, this function
|
| 540 |
+
will re-order the input paths and byte ranges to ensure sorted
|
| 541 |
+
order. If the user can guarantee that the inputs are already
|
| 542 |
+
sorted, passing `sort=False` will skip the re-ordering.
|
| 543 |
+
"""
|
| 544 |
+
# Check input
|
| 545 |
+
if not isinstance(paths, list):
|
| 546 |
+
raise TypeError
|
| 547 |
+
if not isinstance(starts, list):
|
| 548 |
+
starts = [starts] * len(paths)
|
| 549 |
+
if not isinstance(ends, list):
|
| 550 |
+
ends = [ends] * len(paths)
|
| 551 |
+
if len(starts) != len(paths) or len(ends) != len(paths):
|
| 552 |
+
raise ValueError
|
| 553 |
+
|
| 554 |
+
# Early Return
|
| 555 |
+
if len(starts) <= 1:
|
| 556 |
+
return paths, starts, ends
|
| 557 |
+
|
| 558 |
+
starts = [s or 0 for s in starts]
|
| 559 |
+
# Sort by paths and then ranges if `sort=True`
|
| 560 |
+
if sort:
|
| 561 |
+
paths, starts, ends = (
|
| 562 |
+
list(v)
|
| 563 |
+
for v in zip(
|
| 564 |
+
*sorted(
|
| 565 |
+
zip(paths, starts, ends),
|
| 566 |
+
)
|
| 567 |
+
)
|
| 568 |
+
)
|
| 569 |
+
remove = []
|
| 570 |
+
for i, (path, start, end) in enumerate(zip(paths, starts, ends)):
|
| 571 |
+
if any(
|
| 572 |
+
e is not None and p == path and start >= s and end <= e and i != i2
|
| 573 |
+
for i2, (p, s, e) in enumerate(zip(paths, starts, ends))
|
| 574 |
+
):
|
| 575 |
+
remove.append(i)
|
| 576 |
+
paths = [p for i, p in enumerate(paths) if i not in remove]
|
| 577 |
+
starts = [s for i, s in enumerate(starts) if i not in remove]
|
| 578 |
+
ends = [e for i, e in enumerate(ends) if i not in remove]
|
| 579 |
+
|
| 580 |
+
if paths:
|
| 581 |
+
# Loop through the coupled `paths`, `starts`, and
|
| 582 |
+
# `ends`, and merge adjacent blocks when appropriate
|
| 583 |
+
new_paths = paths[:1]
|
| 584 |
+
new_starts = starts[:1]
|
| 585 |
+
new_ends = ends[:1]
|
| 586 |
+
for i in range(1, len(paths)):
|
| 587 |
+
if paths[i] == paths[i - 1] and new_ends[-1] is None:
|
| 588 |
+
continue
|
| 589 |
+
elif (
|
| 590 |
+
paths[i] != paths[i - 1]
|
| 591 |
+
or ((starts[i] - new_ends[-1]) > max_gap)
|
| 592 |
+
or (max_block is not None and (ends[i] - new_starts[-1]) > max_block)
|
| 593 |
+
):
|
| 594 |
+
# Cannot merge with previous block.
|
| 595 |
+
# Add new `paths`, `starts`, and `ends` elements
|
| 596 |
+
new_paths.append(paths[i])
|
| 597 |
+
new_starts.append(starts[i])
|
| 598 |
+
new_ends.append(ends[i])
|
| 599 |
+
else:
|
| 600 |
+
# Merge with the previous block by updating the
|
| 601 |
+
# last element of `ends`
|
| 602 |
+
new_ends[-1] = ends[i]
|
| 603 |
+
return new_paths, new_starts, new_ends
|
| 604 |
+
|
| 605 |
+
# `paths` is empty. Just return input lists
|
| 606 |
+
return paths, starts, ends
|
| 607 |
+
|
| 608 |
+
|
| 609 |
+
def file_size(filelike: IO[bytes]) -> int:
|
| 610 |
+
"""Find length of any open read-mode file-like"""
|
| 611 |
+
pos = filelike.tell()
|
| 612 |
+
try:
|
| 613 |
+
return filelike.seek(0, 2)
|
| 614 |
+
finally:
|
| 615 |
+
filelike.seek(pos)
|
| 616 |
+
|
| 617 |
+
|
| 618 |
+
@contextlib.contextmanager
|
| 619 |
+
def atomic_write(path: str, mode: str = "wb"):
|
| 620 |
+
"""
|
| 621 |
+
A context manager that opens a temporary file next to `path` and, on exit,
|
| 622 |
+
replaces `path` with the temporary file, thereby updating `path`
|
| 623 |
+
atomically.
|
| 624 |
+
"""
|
| 625 |
+
fd, fn = tempfile.mkstemp(
|
| 626 |
+
dir=os.path.dirname(path), prefix=os.path.basename(path) + "-"
|
| 627 |
+
)
|
| 628 |
+
try:
|
| 629 |
+
with open(fd, mode) as fp:
|
| 630 |
+
yield fp
|
| 631 |
+
except BaseException:
|
| 632 |
+
with contextlib.suppress(FileNotFoundError):
|
| 633 |
+
os.unlink(fn)
|
| 634 |
+
raise
|
| 635 |
+
else:
|
| 636 |
+
os.replace(fn, path)
|
| 637 |
+
|
| 638 |
+
|
| 639 |
+
def _translate(pat, STAR, QUESTION_MARK):
|
| 640 |
+
# Copied from: https://github.com/python/cpython/pull/106703.
|
| 641 |
+
res: list[str] = []
|
| 642 |
+
add = res.append
|
| 643 |
+
i, n = 0, len(pat)
|
| 644 |
+
while i < n:
|
| 645 |
+
c = pat[i]
|
| 646 |
+
i = i + 1
|
| 647 |
+
if c == "*":
|
| 648 |
+
# compress consecutive `*` into one
|
| 649 |
+
if (not res) or res[-1] is not STAR:
|
| 650 |
+
add(STAR)
|
| 651 |
+
elif c == "?":
|
| 652 |
+
add(QUESTION_MARK)
|
| 653 |
+
elif c == "[":
|
| 654 |
+
j = i
|
| 655 |
+
if j < n and pat[j] == "!":
|
| 656 |
+
j = j + 1
|
| 657 |
+
if j < n and pat[j] == "]":
|
| 658 |
+
j = j + 1
|
| 659 |
+
while j < n and pat[j] != "]":
|
| 660 |
+
j = j + 1
|
| 661 |
+
if j >= n:
|
| 662 |
+
add("\\[")
|
| 663 |
+
else:
|
| 664 |
+
stuff = pat[i:j]
|
| 665 |
+
if "-" not in stuff:
|
| 666 |
+
stuff = stuff.replace("\\", r"\\")
|
| 667 |
+
else:
|
| 668 |
+
chunks = []
|
| 669 |
+
k = i + 2 if pat[i] == "!" else i + 1
|
| 670 |
+
while True:
|
| 671 |
+
k = pat.find("-", k, j)
|
| 672 |
+
if k < 0:
|
| 673 |
+
break
|
| 674 |
+
chunks.append(pat[i:k])
|
| 675 |
+
i = k + 1
|
| 676 |
+
k = k + 3
|
| 677 |
+
chunk = pat[i:j]
|
| 678 |
+
if chunk:
|
| 679 |
+
chunks.append(chunk)
|
| 680 |
+
else:
|
| 681 |
+
chunks[-1] += "-"
|
| 682 |
+
# Remove empty ranges -- invalid in RE.
|
| 683 |
+
for k in range(len(chunks) - 1, 0, -1):
|
| 684 |
+
if chunks[k - 1][-1] > chunks[k][0]:
|
| 685 |
+
chunks[k - 1] = chunks[k - 1][:-1] + chunks[k][1:]
|
| 686 |
+
del chunks[k]
|
| 687 |
+
# Escape backslashes and hyphens for set difference (--).
|
| 688 |
+
# Hyphens that create ranges shouldn't be escaped.
|
| 689 |
+
stuff = "-".join(
|
| 690 |
+
s.replace("\\", r"\\").replace("-", r"\-") for s in chunks
|
| 691 |
+
)
|
| 692 |
+
# Escape set operations (&&, ~~ and ||).
|
| 693 |
+
stuff = re.sub(r"([&~|])", r"\\\1", stuff)
|
| 694 |
+
i = j + 1
|
| 695 |
+
if not stuff:
|
| 696 |
+
# Empty range: never match.
|
| 697 |
+
add("(?!)")
|
| 698 |
+
elif stuff == "!":
|
| 699 |
+
# Negated empty range: match any character.
|
| 700 |
+
add(".")
|
| 701 |
+
else:
|
| 702 |
+
if stuff[0] == "!":
|
| 703 |
+
stuff = "^" + stuff[1:]
|
| 704 |
+
elif stuff[0] in ("^", "["):
|
| 705 |
+
stuff = "\\" + stuff
|
| 706 |
+
add(f"[{stuff}]")
|
| 707 |
+
else:
|
| 708 |
+
add(re.escape(c))
|
| 709 |
+
assert i == n
|
| 710 |
+
return res
|
| 711 |
+
|
| 712 |
+
|
| 713 |
+
def glob_translate(pat):
|
| 714 |
+
# Copied from: https://github.com/python/cpython/pull/106703.
|
| 715 |
+
# The keyword parameters' values are fixed to:
|
| 716 |
+
# recursive=True, include_hidden=True, seps=None
|
| 717 |
+
"""Translate a pathname with shell wildcards to a regular expression."""
|
| 718 |
+
if os.path.altsep:
|
| 719 |
+
seps = os.path.sep + os.path.altsep
|
| 720 |
+
else:
|
| 721 |
+
seps = os.path.sep
|
| 722 |
+
escaped_seps = "".join(map(re.escape, seps))
|
| 723 |
+
any_sep = f"[{escaped_seps}]" if len(seps) > 1 else escaped_seps
|
| 724 |
+
not_sep = f"[^{escaped_seps}]"
|
| 725 |
+
one_last_segment = f"{not_sep}+"
|
| 726 |
+
one_segment = f"{one_last_segment}{any_sep}"
|
| 727 |
+
any_segments = f"(?:.+{any_sep})?"
|
| 728 |
+
any_last_segments = ".*"
|
| 729 |
+
results = []
|
| 730 |
+
parts = re.split(any_sep, pat)
|
| 731 |
+
last_part_idx = len(parts) - 1
|
| 732 |
+
for idx, part in enumerate(parts):
|
| 733 |
+
if part == "*":
|
| 734 |
+
results.append(one_segment if idx < last_part_idx else one_last_segment)
|
| 735 |
+
continue
|
| 736 |
+
if part == "**":
|
| 737 |
+
results.append(any_segments if idx < last_part_idx else any_last_segments)
|
| 738 |
+
continue
|
| 739 |
+
elif "**" in part:
|
| 740 |
+
raise ValueError(
|
| 741 |
+
"Invalid pattern: '**' can only be an entire path component"
|
| 742 |
+
)
|
| 743 |
+
if part:
|
| 744 |
+
results.extend(_translate(part, f"{not_sep}*", not_sep))
|
| 745 |
+
if idx < last_part_idx:
|
| 746 |
+
results.append(any_sep)
|
| 747 |
+
res = "".join(results)
|
| 748 |
+
return rf"(?s:{res})\Z"
|
micromamba_root/envs/hf_sync/Lib/site-packages/h11-0.16.0.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
conda
|
micromamba_root/envs/hf_sync/Lib/site-packages/h11-0.16.0.dist-info/METADATA
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.4
|
| 2 |
+
Name: h11
|
| 3 |
+
Version: 0.16.0
|
| 4 |
+
Summary: A pure-Python, bring-your-own-I/O implementation of HTTP/1.1
|
| 5 |
+
Home-page: https://github.com/python-hyper/h11
|
| 6 |
+
Author: Nathaniel J. Smith
|
| 7 |
+
Author-email: njs@pobox.com
|
| 8 |
+
License: MIT
|
| 9 |
+
Classifier: Development Status :: 3 - Alpha
|
| 10 |
+
Classifier: Intended Audience :: Developers
|
| 11 |
+
Classifier: License :: OSI Approved :: MIT License
|
| 12 |
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
| 13 |
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
| 14 |
+
Classifier: Programming Language :: Python :: 3
|
| 15 |
+
Classifier: Programming Language :: Python :: 3 :: Only
|
| 16 |
+
Classifier: Programming Language :: Python :: 3.8
|
| 17 |
+
Classifier: Programming Language :: Python :: 3.9
|
| 18 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 19 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 20 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 21 |
+
Classifier: Topic :: Internet :: WWW/HTTP
|
| 22 |
+
Classifier: Topic :: System :: Networking
|
| 23 |
+
Requires-Python: >=3.8
|
| 24 |
+
License-File: LICENSE.txt
|
| 25 |
+
Dynamic: author
|
| 26 |
+
Dynamic: author-email
|
| 27 |
+
Dynamic: classifier
|
| 28 |
+
Dynamic: description
|
| 29 |
+
Dynamic: home-page
|
| 30 |
+
Dynamic: license
|
| 31 |
+
Dynamic: license-file
|
| 32 |
+
Dynamic: requires-python
|
| 33 |
+
Dynamic: summary
|
| 34 |
+
|
| 35 |
+
h11
|
| 36 |
+
===
|
| 37 |
+
|
| 38 |
+
.. image:: https://travis-ci.org/python-hyper/h11.svg?branch=master
|
| 39 |
+
:target: https://travis-ci.org/python-hyper/h11
|
| 40 |
+
:alt: Automated test status
|
| 41 |
+
|
| 42 |
+
.. image:: https://codecov.io/gh/python-hyper/h11/branch/master/graph/badge.svg
|
| 43 |
+
:target: https://codecov.io/gh/python-hyper/h11
|
| 44 |
+
:alt: Test coverage
|
| 45 |
+
|
| 46 |
+
.. image:: https://readthedocs.org/projects/h11/badge/?version=latest
|
| 47 |
+
:target: http://h11.readthedocs.io/en/latest/?badge=latest
|
| 48 |
+
:alt: Documentation Status
|
| 49 |
+
|
| 50 |
+
This is a little HTTP/1.1 library written from scratch in Python,
|
| 51 |
+
heavily inspired by `hyper-h2 <https://hyper-h2.readthedocs.io/>`_.
|
| 52 |
+
|
| 53 |
+
It's a "bring-your-own-I/O" library; h11 contains no IO code
|
| 54 |
+
whatsoever. This means you can hook h11 up to your favorite network
|
| 55 |
+
API, and that could be anything you want: synchronous, threaded,
|
| 56 |
+
asynchronous, or your own implementation of `RFC 6214
|
| 57 |
+
<https://tools.ietf.org/html/rfc6214>`_ -- h11 won't judge you.
|
| 58 |
+
(Compare this to the current state of the art, where every time a `new
|
| 59 |
+
network API <https://trio.readthedocs.io/>`_ comes along then someone
|
| 60 |
+
gets to start over reimplementing the entire HTTP protocol from
|
| 61 |
+
scratch.) Cory Benfield made an `excellent blog post describing the
|
| 62 |
+
benefits of this approach
|
| 63 |
+
<https://lukasa.co.uk/2015/10/The_New_Hyper/>`_, or if you like video
|
| 64 |
+
then here's his `PyCon 2016 talk on the same theme
|
| 65 |
+
<https://www.youtube.com/watch?v=7cC3_jGwl_U>`_.
|
| 66 |
+
|
| 67 |
+
This also means that h11 is not immediately useful out of the box:
|
| 68 |
+
it's a toolkit for building programs that speak HTTP, not something
|
| 69 |
+
that could directly replace ``requests`` or ``twisted.web`` or
|
| 70 |
+
whatever. But h11 makes it much easier to implement something like
|
| 71 |
+
``requests`` or ``twisted.web``.
|
| 72 |
+
|
| 73 |
+
At a high level, working with h11 goes like this:
|
| 74 |
+
|
| 75 |
+
1) First, create an ``h11.Connection`` object to track the state of a
|
| 76 |
+
single HTTP/1.1 connection.
|
| 77 |
+
|
| 78 |
+
2) When you read data off the network, pass it to
|
| 79 |
+
``conn.receive_data(...)``; you'll get back a list of objects
|
| 80 |
+
representing high-level HTTP "events".
|
| 81 |
+
|
| 82 |
+
3) When you want to send a high-level HTTP event, create the
|
| 83 |
+
corresponding "event" object and pass it to ``conn.send(...)``;
|
| 84 |
+
this will give you back some bytes that you can then push out
|
| 85 |
+
through the network.
|
| 86 |
+
|
| 87 |
+
For example, a client might instantiate and then send a
|
| 88 |
+
``h11.Request`` object, then zero or more ``h11.Data`` objects for the
|
| 89 |
+
request body (e.g., if this is a POST), and then a
|
| 90 |
+
``h11.EndOfMessage`` to indicate the end of the message. Then the
|
| 91 |
+
server would then send back a ``h11.Response``, some ``h11.Data``, and
|
| 92 |
+
its own ``h11.EndOfMessage``. If either side violates the protocol,
|
| 93 |
+
you'll get a ``h11.ProtocolError`` exception.
|
| 94 |
+
|
| 95 |
+
h11 is suitable for implementing both servers and clients, and has a
|
| 96 |
+
pleasantly symmetric API: the events you send as a client are exactly
|
| 97 |
+
the ones that you receive as a server and vice-versa.
|
| 98 |
+
|
| 99 |
+
`Here's an example of a tiny HTTP client
|
| 100 |
+
<https://github.com/python-hyper/h11/blob/master/examples/basic-client.py>`_
|
| 101 |
+
|
| 102 |
+
It also has `a fine manual <https://h11.readthedocs.io/>`_.
|
| 103 |
+
|
| 104 |
+
FAQ
|
| 105 |
+
---
|
| 106 |
+
|
| 107 |
+
*Whyyyyy?*
|
| 108 |
+
|
| 109 |
+
I wanted to play with HTTP in `Curio
|
| 110 |
+
<https://curio.readthedocs.io/en/latest/tutorial.html>`__ and `Trio
|
| 111 |
+
<https://trio.readthedocs.io>`__, which at the time didn't have any
|
| 112 |
+
HTTP libraries. So I thought, no big deal, Python has, like, a dozen
|
| 113 |
+
different implementations of HTTP, surely I can find one that's
|
| 114 |
+
reusable. I didn't find one, but I did find Cory's call-to-arms
|
| 115 |
+
blog-post. So I figured, well, fine, if I have to implement HTTP from
|
| 116 |
+
scratch, at least I can make sure no-one *else* has to ever again.
|
| 117 |
+
|
| 118 |
+
*Should I use it?*
|
| 119 |
+
|
| 120 |
+
Maybe. You should be aware that it's a very young project. But, it's
|
| 121 |
+
feature complete and has an exhaustive test-suite and complete docs,
|
| 122 |
+
so the next step is for people to try using it and see how it goes
|
| 123 |
+
:-). If you do then please let us know -- if nothing else we'll want
|
| 124 |
+
to talk to you before making any incompatible changes!
|
| 125 |
+
|
| 126 |
+
*What are the features/limitations?*
|
| 127 |
+
|
| 128 |
+
Roughly speaking, it's trying to be a robust, complete, and non-hacky
|
| 129 |
+
implementation of the first "chapter" of the HTTP/1.1 spec: `RFC 7230:
|
| 130 |
+
HTTP/1.1 Message Syntax and Routing
|
| 131 |
+
<https://tools.ietf.org/html/rfc7230>`_. That is, it mostly focuses on
|
| 132 |
+
implementing HTTP at the level of taking bytes on and off the wire,
|
| 133 |
+
and the headers related to that, and tries to be anal about spec
|
| 134 |
+
conformance. It doesn't know about higher-level concerns like URL
|
| 135 |
+
routing, conditional GETs, cross-origin cookie policies, or content
|
| 136 |
+
negotiation. But it does know how to take care of framing,
|
| 137 |
+
cross-version differences in keep-alive handling, and the "obsolete
|
| 138 |
+
line folding" rule, so you can focus your energies on the hard /
|
| 139 |
+
interesting parts for your application, and it tries to support the
|
| 140 |
+
full specification in the sense that any useful HTTP/1.1 conformant
|
| 141 |
+
application should be able to use h11.
|
| 142 |
+
|
| 143 |
+
It's pure Python, and has no dependencies outside of the standard
|
| 144 |
+
library.
|
| 145 |
+
|
| 146 |
+
It has a test suite with 100.0% coverage for both statements and
|
| 147 |
+
branches.
|
| 148 |
+
|
| 149 |
+
Currently it supports Python 3 (testing on 3.8-3.12) and PyPy 3.
|
| 150 |
+
The last Python 2-compatible version was h11 0.11.x.
|
| 151 |
+
(Originally it had a Cython wrapper for `http-parser
|
| 152 |
+
<https://github.com/nodejs/http-parser>`_ and a beautiful nested state
|
| 153 |
+
machine implemented with ``yield from`` to postprocess the output. But
|
| 154 |
+
I had to take these out -- the new *parser* needs fewer lines-of-code
|
| 155 |
+
than the old *parser wrapper*, is written in pure Python, uses no
|
| 156 |
+
exotic language syntax, and has more features. It's sad, really; that
|
| 157 |
+
old state machine was really slick. I just need a few sentences here
|
| 158 |
+
to mourn that.)
|
| 159 |
+
|
| 160 |
+
I don't know how fast it is. I haven't benchmarked or profiled it yet,
|
| 161 |
+
so it's probably got a few pointless hot spots, and I've been trying
|
| 162 |
+
to err on the side of simplicity and robustness instead of
|
| 163 |
+
micro-optimization. But at the architectural level I tried hard to
|
| 164 |
+
avoid fundamentally bad decisions, e.g., I believe that all the
|
| 165 |
+
parsing algorithms remain linear-time even in the face of pathological
|
| 166 |
+
input like slowloris, and there are no byte-by-byte loops. (I also
|
| 167 |
+
believe that it maintains bounded memory usage in the face of
|
| 168 |
+
arbitrary/pathological input.)
|
| 169 |
+
|
| 170 |
+
The whole library is ~800 lines-of-code. You can read and understand
|
| 171 |
+
the whole thing in less than an hour. Most of the energy invested in
|
| 172 |
+
this so far has been spent on trying to keep things simple by
|
| 173 |
+
minimizing special-cases and ad hoc state manipulation; even though it
|
| 174 |
+
is now quite small and simple, I'm still annoyed that I haven't
|
| 175 |
+
figured out how to make it even smaller and simpler. (Unfortunately,
|
| 176 |
+
HTTP does not lend itself to simplicity.)
|
| 177 |
+
|
| 178 |
+
The API is ~feature complete and I don't expect the general outlines
|
| 179 |
+
to change much, but you can't judge an API's ergonomics until you
|
| 180 |
+
actually document and use it, so I'd expect some changes in the
|
| 181 |
+
details.
|
| 182 |
+
|
| 183 |
+
*How do I try it?*
|
| 184 |
+
|
| 185 |
+
.. code-block:: sh
|
| 186 |
+
|
| 187 |
+
$ pip install h11
|
| 188 |
+
$ git clone git@github.com:python-hyper/h11
|
| 189 |
+
$ cd h11/examples
|
| 190 |
+
$ python basic-client.py
|
| 191 |
+
|
| 192 |
+
and go from there.
|
| 193 |
+
|
| 194 |
+
*License?*
|
| 195 |
+
|
| 196 |
+
MIT
|
| 197 |
+
|
| 198 |
+
*Code of conduct?*
|
| 199 |
+
|
| 200 |
+
Contributors are requested to follow our `code of conduct
|
| 201 |
+
<https://github.com/python-hyper/h11/blob/master/CODE_OF_CONDUCT.md>`_ in
|
| 202 |
+
all project spaces.
|
micromamba_root/envs/hf_sync/Lib/site-packages/h11-0.16.0.dist-info/RECORD
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
h11-0.16.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
| 2 |
+
h11-0.16.0.dist-info/METADATA,sha256=KPMmCYrAn8unm48YD5YIfIQf4kViFct7hyqcfVzRnWQ,8348
|
| 3 |
+
h11-0.16.0.dist-info/RECORD,,
|
| 4 |
+
h11-0.16.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 5 |
+
h11-0.16.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
| 6 |
+
h11-0.16.0.dist-info/direct_url.json,sha256=BzX1cxpPkECDpsIlZ-i_WMfdC5fltaE2hWKj491RUuY,114
|
| 7 |
+
h11-0.16.0.dist-info/licenses/LICENSE.txt,sha256=N9tbuFkm2yikJ6JYZ_ELEjIAOuob5pzLhRE4rbjm82E,1124
|
| 8 |
+
h11-0.16.0.dist-info/top_level.txt,sha256=F7dC4jl3zeh8TGHEPaWJrMbeuoWbS379Gwdi-Yvdcis,4
|
| 9 |
+
h11/__init__.py,sha256=iO1KzkSO42yZ6ffg-VMgbx_ZVTWGUY00nRYEWn-s3kY,1507
|
| 10 |
+
h11/__pycache__/__init__.cpython-310.pyc,,
|
| 11 |
+
h11/__pycache__/_abnf.cpython-310.pyc,,
|
| 12 |
+
h11/__pycache__/_connection.cpython-310.pyc,,
|
| 13 |
+
h11/__pycache__/_events.cpython-310.pyc,,
|
| 14 |
+
h11/__pycache__/_headers.cpython-310.pyc,,
|
| 15 |
+
h11/__pycache__/_readers.cpython-310.pyc,,
|
| 16 |
+
h11/__pycache__/_receivebuffer.cpython-310.pyc,,
|
| 17 |
+
h11/__pycache__/_state.cpython-310.pyc,,
|
| 18 |
+
h11/__pycache__/_util.cpython-310.pyc,,
|
| 19 |
+
h11/__pycache__/_version.cpython-310.pyc,,
|
| 20 |
+
h11/__pycache__/_writers.cpython-310.pyc,,
|
| 21 |
+
h11/_abnf.py,sha256=ybixr0xsupnkA6GFAyMubuXF6Tc1lb_hF890NgCsfNc,4815
|
| 22 |
+
h11/_connection.py,sha256=k9YRVf6koZqbttBW36xSWaJpWdZwa-xQVU9AHEo9DuI,26863
|
| 23 |
+
h11/_events.py,sha256=I97aXoal1Wu7dkL548BANBUCkOIbe-x5CioYA9IBY14,11792
|
| 24 |
+
h11/_headers.py,sha256=P7D-lBNxHwdLZPLimmYwrPG-9ZkjElvvJZJdZAgSP-4,10412
|
| 25 |
+
h11/_readers.py,sha256=a4RypORUCC3d0q_kxPuBIM7jTD8iLt5X91TH0FsduN4,8590
|
| 26 |
+
h11/_receivebuffer.py,sha256=xrspsdsNgWFxRfQcTXxR8RrdjRXXTK0Io5cQYWpJ1Ws,5252
|
| 27 |
+
h11/_state.py,sha256=_5LG_BGR8FCcFQeBPH-TMHgm_-B-EUcWCnQof_9XjFE,13231
|
| 28 |
+
h11/_util.py,sha256=LWkkjXyJaFlAy6Lt39w73UStklFT5ovcvo0TkY7RYuk,4888
|
| 29 |
+
h11/_version.py,sha256=GVSsbPSPDcOuF6ptfIiXnVJoaEm3ygXbMnqlr_Giahw,686
|
| 30 |
+
h11/_writers.py,sha256=oFKm6PtjeHfbj4RLX7VB7KDc1gIY53gXG3_HR9ltmTA,5081
|
| 31 |
+
h11/py.typed,sha256=sow9soTwP9T_gEAQSVh7Gb8855h04Nwmhs2We-JRgZM,7
|
micromamba_root/envs/hf_sync/Lib/site-packages/h11-0.16.0.dist-info/REQUESTED
ADDED
|
File without changes
|
micromamba_root/envs/hf_sync/Lib/site-packages/h11-0.16.0.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: setuptools (80.9.0)
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py3-none-any
|
| 5 |
+
|