Ahmad2005 commited on
Commit
c0e1f92
·
verified ·
1 Parent(s): 6d4bcf3

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .cache/pip/http-v2/5/2/e/b/0/52eb09ff78f469a17d2b7efae5a925d94693634f88d734649f34a875 +0 -0
  2. .cache/pip/http-v2/5/9/1/a/0/591a0a7ea47d81cffb332bf5e1460e560ce743822558c6f345314d4b +0 -0
  3. .cache/pip/http-v2/5/e/c/8/b/5ec8b58bc827caa12672b72c08527dbd1c5456edeea815f1e76cb526 +0 -0
  4. .cache/pip/http-v2/d/3/2/9/d/d329d269473dcb26bc2fcf82e354619e8463ba8855d5a3b77637c124 +0 -0
  5. .cache/pip/http-v2/d/a/8/1/4/da8145136a84a44f3223fc3ee57fc18e4604ae09f030d21a21c2ecb5 +0 -0
  6. .cache/pip/http-v2/f/6/4/9/7/f64975d28276977ea56e4922737def644a797957c860c54f5b5bc122 +0 -0
  7. .cache/pip/http-v2/f/c/6/8/7/fc687abc6120c7bc7cfd867fe3788604e9f8e9dcf17e51396d803e25 +0 -0
  8. .cache/uv/archive-v0/B1KughA3sUutQPxXNCN4n/certifi/tests/test_certify.py +18 -0
  9. .cache/uv/archive-v0/BzSzHXZZWM1LPVXcPjaiI/yaml/_yaml.cpython-312-x86_64-linux-gnu.so +3 -0
  10. .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec-2026.7.0.dist-info/METADATA +257 -0
  11. .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec-2026.7.0.dist-info/RECORD +61 -0
  12. .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec-2026.7.0.dist-info/WHEEL +4 -0
  13. .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec-2026.7.0.dist-info/licenses/LICENSE +29 -0
  14. .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/archive.py +75 -0
  15. .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/config.py +131 -0
  16. .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/conftest.py +125 -0
  17. .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/dircache.py +98 -0
  18. .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/fuse.py +324 -0
  19. .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/generic.py +396 -0
  20. .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/local.py +517 -0
  21. .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/reference.py +1339 -0
  22. .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/smb.py +416 -0
  23. .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/tar.py +139 -0
  24. .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/zip.py +183 -0
  25. .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/json.py +112 -0
  26. .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/mapping.py +251 -0
  27. .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/parquet.py +572 -0
  28. .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/spec.py +2342 -0
  29. .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/transaction.py +90 -0
  30. .cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/utils.py +757 -0
  31. .cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/_hot_reload/__init__.py +13 -0
  32. .cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/_hot_reload/sse_client.py +144 -0
  33. .cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/_hot_reload/types.py +121 -0
  34. .cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/cli/__init__.py +14 -0
  35. .cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/cli/_city_game.py +661 -0
  36. .cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/cli/_completion.py +105 -0
  37. .cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/cli/_cp.py +253 -0
  38. .cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/cli/_errors.py +155 -0
  39. .cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/cli/_framework.py +645 -0
  40. .cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/cli/_output.py +379 -0
  41. .cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/cli/_skills.py +311 -0
  42. .cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/cli/buckets.py +679 -0
  43. .cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/cli/discussions.py +497 -0
  44. .cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/cli/download.py +225 -0
  45. .cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/cli/hf.py +142 -0
  46. .cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/cli/lfs.py +175 -0
  47. .cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/cli/spaces.py +1090 -0
  48. .cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/inference/_generated/__init__.py +0 -0
  49. .cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/inference/_generated/_async_client.py +0 -0
  50. .cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/inference/_generated/types/audio_classification.py +43 -0
.cache/pip/http-v2/5/2/e/b/0/52eb09ff78f469a17d2b7efae5a925d94693634f88d734649f34a875 ADDED
Binary file (1.23 kB). View file
 
.cache/pip/http-v2/5/9/1/a/0/591a0a7ea47d81cffb332bf5e1460e560ce743822558c6f345314d4b ADDED
Binary file (1.23 kB). View file
 
.cache/pip/http-v2/5/e/c/8/b/5ec8b58bc827caa12672b72c08527dbd1c5456edeea815f1e76cb526 ADDED
Binary file (1.2 kB). View file
 
.cache/pip/http-v2/d/3/2/9/d/d329d269473dcb26bc2fcf82e354619e8463ba8855d5a3b77637c124 ADDED
Binary file (1.9 kB). View file
 
.cache/pip/http-v2/d/a/8/1/4/da8145136a84a44f3223fc3ee57fc18e4604ae09f030d21a21c2ecb5 ADDED
Binary file (1.22 kB). View file
 
.cache/pip/http-v2/f/6/4/9/7/f64975d28276977ea56e4922737def644a797957c860c54f5b5bc122 ADDED
Binary file (1.28 kB). View file
 
.cache/pip/http-v2/f/c/6/8/7/fc687abc6120c7bc7cfd867fe3788604e9f8e9dcf17e51396d803e25 ADDED
Binary file (1.2 kB). View file
 
.cache/uv/archive-v0/B1KughA3sUutQPxXNCN4n/certifi/tests/test_certify.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import unittest
3
+
4
+ import certifi
5
+
6
+
7
+ class TestCertifi(unittest.TestCase):
8
+ def test_cabundle_exists(self) -> None:
9
+ assert os.path.exists(certifi.where())
10
+
11
+ def test_read_contents(self) -> None:
12
+ content = certifi.contents()
13
+ assert "-----BEGIN CERTIFICATE-----" in content
14
+
15
+ def test_py_typed_exists(self) -> None:
16
+ assert os.path.exists(
17
+ os.path.join(os.path.dirname(certifi.__file__), 'py.typed')
18
+ )
.cache/uv/archive-v0/BzSzHXZZWM1LPVXcPjaiI/yaml/_yaml.cpython-312-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:957a099a4521c1f7669306fb6f79ca63fa4b9a0b4c463f7cac833a65a5c5c0cb
3
+ size 2679264
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec-2026.7.0.dist-info/METADATA ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: fsspec
3
+ Version: 2026.7.0
4
+ Summary: File-system specification
5
+ Project-URL: Changelog, https://filesystem-spec.readthedocs.io/en/latest/changelog.html
6
+ Project-URL: Documentation, https://filesystem-spec.readthedocs.io/en/latest/
7
+ Project-URL: Homepage, https://github.com/fsspec/filesystem_spec
8
+ Maintainer-email: Martin Durant <mdurant@anaconda.com>
9
+ License-Expression: BSD-3-Clause
10
+ License-File: LICENSE
11
+ Keywords: file
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Requires-Python: >=3.10
21
+ Provides-Extra: abfs
22
+ Requires-Dist: adlfs; extra == 'abfs'
23
+ Provides-Extra: adl
24
+ Requires-Dist: adlfs; extra == 'adl'
25
+ Provides-Extra: arrow
26
+ Requires-Dist: pyarrow>=1; extra == 'arrow'
27
+ Provides-Extra: dask
28
+ Requires-Dist: dask; extra == 'dask'
29
+ Requires-Dist: distributed; extra == 'dask'
30
+ Provides-Extra: dev
31
+ Requires-Dist: pre-commit; extra == 'dev'
32
+ Requires-Dist: ruff>=0.5; extra == 'dev'
33
+ Provides-Extra: doc
34
+ Requires-Dist: numpydoc; extra == 'doc'
35
+ Requires-Dist: sphinx; extra == 'doc'
36
+ Requires-Dist: sphinx-design; extra == 'doc'
37
+ Requires-Dist: sphinx-rtd-theme; extra == 'doc'
38
+ Requires-Dist: yarl; extra == 'doc'
39
+ Provides-Extra: dropbox
40
+ Requires-Dist: dropbox; extra == 'dropbox'
41
+ Requires-Dist: dropboxdrivefs; extra == 'dropbox'
42
+ Requires-Dist: requests; extra == 'dropbox'
43
+ Provides-Extra: entrypoints
44
+ Provides-Extra: full
45
+ Requires-Dist: adlfs; extra == 'full'
46
+ Requires-Dist: aiohttp!=4.0.0a0,!=4.0.0a1; extra == 'full'
47
+ Requires-Dist: dask; extra == 'full'
48
+ Requires-Dist: distributed; extra == 'full'
49
+ Requires-Dist: dropbox; extra == 'full'
50
+ Requires-Dist: dropboxdrivefs; extra == 'full'
51
+ Requires-Dist: fusepy; extra == 'full'
52
+ Requires-Dist: gcsfs>=2026.4.0; extra == 'full'
53
+ Requires-Dist: libarchive-c; extra == 'full'
54
+ Requires-Dist: ocifs; extra == 'full'
55
+ Requires-Dist: panel; extra == 'full'
56
+ Requires-Dist: paramiko; extra == 'full'
57
+ Requires-Dist: pyarrow>=1; extra == 'full'
58
+ Requires-Dist: pygit2; extra == 'full'
59
+ Requires-Dist: requests; extra == 'full'
60
+ Requires-Dist: s3fs>=2026.6.0; extra == 'full'
61
+ Requires-Dist: smbprotocol; extra == 'full'
62
+ Requires-Dist: tqdm; extra == 'full'
63
+ Provides-Extra: fuse
64
+ Requires-Dist: fusepy; extra == 'fuse'
65
+ Provides-Extra: gcs
66
+ Requires-Dist: gcsfs>=2026.4.0; extra == 'gcs'
67
+ Provides-Extra: git
68
+ Requires-Dist: pygit2; extra == 'git'
69
+ Provides-Extra: github
70
+ Requires-Dist: requests; extra == 'github'
71
+ Provides-Extra: gs
72
+ Requires-Dist: gcsfs>=2026.4.0; extra == 'gs'
73
+ Provides-Extra: gui
74
+ Requires-Dist: panel; extra == 'gui'
75
+ Provides-Extra: hdfs
76
+ Requires-Dist: pyarrow>=1; extra == 'hdfs'
77
+ Provides-Extra: http
78
+ Requires-Dist: aiohttp!=4.0.0a0,!=4.0.0a1; extra == 'http'
79
+ Provides-Extra: libarchive
80
+ Requires-Dist: libarchive-c; extra == 'libarchive'
81
+ Provides-Extra: oci
82
+ Requires-Dist: ocifs; extra == 'oci'
83
+ Provides-Extra: s3
84
+ Requires-Dist: s3fs>=2026.6.0; extra == 's3'
85
+ Provides-Extra: sftp
86
+ Requires-Dist: paramiko; extra == 'sftp'
87
+ Provides-Extra: smb
88
+ Requires-Dist: smbprotocol; extra == 'smb'
89
+ Provides-Extra: ssh
90
+ Requires-Dist: paramiko; extra == 'ssh'
91
+ Provides-Extra: test
92
+ Requires-Dist: aiohttp!=4.0.0a0,!=4.0.0a1; extra == 'test'
93
+ Requires-Dist: numpy; extra == 'test'
94
+ Requires-Dist: pytest; extra == 'test'
95
+ Requires-Dist: pytest-asyncio!=0.22.0; extra == 'test'
96
+ Requires-Dist: pytest-benchmark; extra == 'test'
97
+ Requires-Dist: pytest-cov; extra == 'test'
98
+ Requires-Dist: pytest-mock; extra == 'test'
99
+ Requires-Dist: pytest-recording; extra == 'test'
100
+ Requires-Dist: pytest-rerunfailures; extra == 'test'
101
+ Requires-Dist: requests; extra == 'test'
102
+ Provides-Extra: test-downstream
103
+ Requires-Dist: aiobotocore<3.0.0,>=2.5.4; extra == 'test-downstream'
104
+ Requires-Dist: dask[dataframe,test]; extra == 'test-downstream'
105
+ Requires-Dist: moto[server]<5,>4; extra == 'test-downstream'
106
+ Requires-Dist: pytest-timeout; extra == 'test-downstream'
107
+ Requires-Dist: xarray; extra == 'test-downstream'
108
+ Provides-Extra: test-full
109
+ Requires-Dist: adlfs; extra == 'test-full'
110
+ Requires-Dist: aiohttp!=4.0.0a0,!=4.0.0a1; extra == 'test-full'
111
+ Requires-Dist: backports-zstd; (python_version < '3.14') and extra == 'test-full'
112
+ Requires-Dist: cloudpickle; extra == 'test-full'
113
+ Requires-Dist: dask; extra == 'test-full'
114
+ Requires-Dist: distributed; extra == 'test-full'
115
+ Requires-Dist: dropbox; extra == 'test-full'
116
+ Requires-Dist: dropboxdrivefs; extra == 'test-full'
117
+ Requires-Dist: fastparquet; extra == 'test-full'
118
+ Requires-Dist: fusepy; extra == 'test-full'
119
+ Requires-Dist: gcsfs>=2026.4.0; extra == 'test-full'
120
+ Requires-Dist: jinja2; extra == 'test-full'
121
+ Requires-Dist: kerchunk; extra == 'test-full'
122
+ Requires-Dist: libarchive-c; extra == 'test-full'
123
+ Requires-Dist: lz4; extra == 'test-full'
124
+ Requires-Dist: notebook; extra == 'test-full'
125
+ Requires-Dist: numpy; extra == 'test-full'
126
+ Requires-Dist: ocifs; extra == 'test-full'
127
+ Requires-Dist: pandas<3.0.0; extra == 'test-full'
128
+ Requires-Dist: panel; extra == 'test-full'
129
+ Requires-Dist: paramiko; extra == 'test-full'
130
+ Requires-Dist: pyarrow>=1; extra == 'test-full'
131
+ Requires-Dist: pyftpdlib; extra == 'test-full'
132
+ Requires-Dist: pygit2; extra == 'test-full'
133
+ Requires-Dist: pytest; extra == 'test-full'
134
+ Requires-Dist: pytest-asyncio!=0.22.0; extra == 'test-full'
135
+ Requires-Dist: pytest-benchmark; extra == 'test-full'
136
+ Requires-Dist: pytest-cov; extra == 'test-full'
137
+ Requires-Dist: pytest-mock; extra == 'test-full'
138
+ Requires-Dist: pytest-recording; extra == 'test-full'
139
+ Requires-Dist: pytest-rerunfailures; extra == 'test-full'
140
+ Requires-Dist: python-snappy; extra == 'test-full'
141
+ Requires-Dist: requests; extra == 'test-full'
142
+ Requires-Dist: s3fs>=2026.6.0; extra == 'test-full'
143
+ Requires-Dist: smbprotocol; extra == 'test-full'
144
+ Requires-Dist: tqdm; extra == 'test-full'
145
+ Requires-Dist: urllib3; extra == 'test-full'
146
+ Requires-Dist: zarr<3.2.0; extra == 'test-full'
147
+ Requires-Dist: zstandard; (python_version < '3.14') and extra == 'test-full'
148
+ Provides-Extra: tqdm
149
+ Requires-Dist: tqdm; extra == 'tqdm'
150
+ Description-Content-Type: text/markdown
151
+
152
+ # filesystem_spec
153
+
154
+ [![PyPI version](https://badge.fury.io/py/fsspec.svg)](https://pypi.python.org/pypi/fsspec/)
155
+ [![Anaconda-Server Badge](https://anaconda.org/conda-forge/fsspec/badges/version.svg)](https://anaconda.org/conda-forge/fsspec)
156
+ ![Build](https://github.com/fsspec/filesystem_spec/workflows/CI/badge.svg)
157
+ [![Docs](https://readthedocs.org/projects/filesystem-spec/badge/?version=latest)](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>
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec-2026.7.0.dist-info/RECORD ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ fsspec/__init__.py,sha256=xFcoHBD17fc5KamKUQAIA0rePGjLqIN1WBAd9NAoAi8,2111
2
+ fsspec/_version.py,sha256=XYrsnKX7E2XNoSiwqs7ALMtioidXl8y8KSliz3pL7S0,526
3
+ fsspec/archive.py,sha256=vM6t_lgV6lBWbBYwpm3S4ofBQFQxUPr5KkDQrrQcQro,2411
4
+ fsspec/asyn.py,sha256=V1Kig3HVzgWwZ-VtUYhys3QfdmiWRLG7EcP1E1PwM6M,39105
5
+ fsspec/caching.py,sha256=Glmc9tDtS8Ctp44sd7mJURJYq7sHkH_yD480q6IgbxE,34777
6
+ fsspec/callbacks.py,sha256=BDIwLzK6rr_0V5ch557fSzsivCElpdqhXr5dZ9Te-EE,9210
7
+ fsspec/compression.py,sha256=3v_Fe39gzRRWfaeXpzNjAGPqgTzmETYRCo3qHVqD3po,5132
8
+ fsspec/config.py,sha256=mHKzAgjXa_LwqtO_VoTJJ568VqwYkbK3gUp4J6JZJp4,4238
9
+ fsspec/conftest.py,sha256=uWfm_Qs5alPRxOhRpDfQ0-1jqSJ54pni4y96IxOREXM,3446
10
+ fsspec/core.py,sha256=EapTTO4bGR9G12rC90FiaBRemMhqo0ypx3ZqXj1zVuk,24189
11
+ fsspec/dircache.py,sha256=YzogWJrhEastHU7vWz-cJiJ7sdtLXFXhEpInGKd4EcM,2717
12
+ fsspec/exceptions.py,sha256=pauSLDMxzTJMOjvX1WEUK0cMyFkrFxpWJsyFywav7A8,331
13
+ fsspec/fuse.py,sha256=Q-3NOOyLqBfYa4Db5E19z_ZY36zzYHtIs1mOUasItBQ,10177
14
+ fsspec/generic.py,sha256=-LIADa9qRN79bfa3Hl9m3HaN6rlU2GNivawLNmybqxE,13752
15
+ fsspec/gui.py,sha256=CQ7QsrTpaDlWSLNOpwNoJc7khOcYXIZxmrAJN9bHWQU,14002
16
+ fsspec/json.py,sha256=4EBZ-xOmRiyxmIqPIwxmDImosRQ7io7qBM2xjJPsEE4,3768
17
+ fsspec/mapping.py,sha256=m2ndB_gtRBXYmNJg0Ie1-BVR75TFleHmIQBzC-yWhjU,8343
18
+ fsspec/parquet.py,sha256=0SzfswUTc2k5nAj7xZNYPPyvUkFNXznFRXXtBRhr-iE,20506
19
+ fsspec/registry.py,sha256=KeDNL9HOyHX_D4D4qQGAI-Y3DQhiLeUC1VK2I81NZaE,12344
20
+ fsspec/spec.py,sha256=3LTaRdAhOTIPCetwPCS9HC6MR1VlcdfLVBh4mWFrXns,79674
21
+ fsspec/transaction.py,sha256=xliRG6U2Zf3khG4xcw9WiB-yAoqJSHEGK_VjHOdtgo0,2398
22
+ fsspec/utils.py,sha256=T6x7JS-qHGdZ6hMPrT1tH6_41lHFw88g3WxgNIItYPc,24114
23
+ fsspec/implementations/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
24
+ fsspec/implementations/arrow.py,sha256=HSXhExZ3HKNkWEm6m36h2jrbVilt3u8MvJI60u1_6fU,9236
25
+ fsspec/implementations/asyn_wrapper.py,sha256=3lfJkGs6D_AwRBdxTSYlL-RCVdaXBZ9Itys2P5o5Si0,3738
26
+ fsspec/implementations/cache_mapper.py,sha256=W4wlxyPxZbSp9ItJ0pYRVBMh6bw9eFypgP6kUYuuiI4,2421
27
+ fsspec/implementations/cache_metadata.py,sha256=EPhQV27lgPlYREYprDET1vcMed15pVNMit-Ta1ljoyE,7942
28
+ fsspec/implementations/cached.py,sha256=A_QyiukZzVznBWSZgMXSLd6h6K7k-ueroqnsoVY4bZg,37134
29
+ fsspec/implementations/chained.py,sha256=iGivpNaHUFjB_ea0-HAPhcmm6CL8qnDf270PSj7JwuE,680
30
+ fsspec/implementations/dask.py,sha256=CXZbJzIVOhKV8ILcxuy3bTvcacCueAbyQxmvAkbPkrk,4466
31
+ fsspec/implementations/data.py,sha256=9tMcy1fyX1auvzFX2aANPK9CfPoarnxTCDLhX12usvs,2131
32
+ fsspec/implementations/dbfs.py,sha256=yHuLUGNmQd5pUCt9vpXleQNpjOpIZZwVZA08YauQU4U,16249
33
+ fsspec/implementations/dirfs.py,sha256=KaIHW18i4-eNqdv7NR9qXEvoobQ88trGCNrqb4XW9ew,13449
34
+ fsspec/implementations/ftp.py,sha256=S_y5XOv_QhBiYBw430qzFB5MfS9AzxNBOs3f87XehC0,13539
35
+ fsspec/implementations/gist.py,sha256=Y6jTDrE-wuTwvpPyAQDuuOMBGxlajafKWoB1_yX6jdY,8528
36
+ fsspec/implementations/git.py,sha256=qBDWMz5LNllPqVjr5jf_1FuNha4P5lyQI3IlhYg-wUE,3731
37
+ fsspec/implementations/github.py,sha256=aCsZL8UvXZgdkcB1RUs3DdLeNrjLKcFsFYeQFDWbBFo,11653
38
+ fsspec/implementations/http.py,sha256=1uWwxllOjPe8mQD54IrCYQJHU1YaAXh_cDmXBk-AoQ8,30894
39
+ fsspec/implementations/http_sync.py,sha256=UmBqd938ebwVjYgVtzg-ysG3ZoGhIJw0wFtQAfxV3Aw,30332
40
+ fsspec/implementations/jupyter.py,sha256=q1PlQ66AAswGFyr8MFKWyobaV2YekMWRtqENBDQtD28,4002
41
+ fsspec/implementations/libarchive.py,sha256=SpIA1F-zf7kb2-VYUVuhMrXTBOhBxUXKgEW1RaAdDoA,7098
42
+ fsspec/implementations/local.py,sha256=jpvvSYj8RaocLB8YuHjGlWOTMJAJNTnUBj9D_Zn32BA,17216
43
+ fsspec/implementations/memory.py,sha256=fXUYjKF1xr4_9FX26vDCazEhmFbE7Om4xUufIOQe2vA,14088
44
+ fsspec/implementations/reference.py,sha256=YKLzPBF6bLpOnHY9iM0MR5JLGRi5CB6x1cWIgMb6Ahg,49974
45
+ fsspec/implementations/sftp.py,sha256=v7t-LpD4hEycHnw1kbepyoNgrhClshXQXitFuY4mBWE,5951
46
+ fsspec/implementations/smb.py,sha256=5fhu8h06nOLBPh2c48aT7WBRqh9cEcbIwtyu06wTjec,15236
47
+ fsspec/implementations/tar.py,sha256=adO9r_Badc4ucfApmK-mrvbv1re0_qoxwBjgnSMIrh0,4601
48
+ fsspec/implementations/webhdfs.py,sha256=osF2m0nhDil6sbMzYW_4DZzhxF4ygtb59XDiybd9Fyg,17589
49
+ fsspec/implementations/zip.py,sha256=GPDJh4UtUNJmaqijUQ0eiEZIGpwusQjkIcbhsrmLSi0,6263
50
+ fsspec/tests/abstract/__init__.py,sha256=V0-8FqQPfHlHZ3xomJ0hyWl6t1QvqsDnQFJYHeSTlEw,10197
51
+ fsspec/tests/abstract/common.py,sha256=1GQwNo5AONzAnzZj0fWgn8NJPLXALehbsuGxS3FzWVU,4973
52
+ fsspec/tests/abstract/copy.py,sha256=gU5-d97U3RSde35Vp4RxPY4rWwL744HiSrJ8IBOp9-8,19967
53
+ fsspec/tests/abstract/get.py,sha256=vNR4HztvTR7Cj56AMo7_tx7TeYz1Jgr_2Wb8Lv-UiBY,20755
54
+ fsspec/tests/abstract/mv.py,sha256=k8eUEBIrRrGMsBY5OOaDXdGnQUKGwDIfQyduB6YD3Ns,1982
55
+ fsspec/tests/abstract/open.py,sha256=Fi2PBPYLbRqysF8cFm0rwnB41kMdQVYjq8cGyDXp3BU,329
56
+ fsspec/tests/abstract/pipe.py,sha256=LFzIrLCB5GLXf9rzFKJmE8AdG7LQ_h4bJo70r8FLPqM,402
57
+ fsspec/tests/abstract/put.py,sha256=7aih17OKB_IZZh1Mkq1eBDIjobhtMQmI8x-Pw-S_aZk,21201
58
+ fsspec-2026.7.0.dist-info/METADATA,sha256=iLFldYXeFOO7gqpSeKqVlbMKpMp06tBz2JUGFcgICZ0,10561
59
+ fsspec-2026.7.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
60
+ fsspec-2026.7.0.dist-info/licenses/LICENSE,sha256=LcNUls5TpzB5FcAIqESq1T53K0mzTN0ARFBnaRQH7JQ,1513
61
+ fsspec-2026.7.0.dist-info/RECORD,,
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec-2026.7.0.dist-info/WHEEL ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.31.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec-2026.7.0.dist-info/licenses/LICENSE ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2018, Martin Durant
4
+ All rights reserved.
5
+
6
+ Redistribution and use in source and binary forms, with or without
7
+ modification, are permitted provided that the following conditions are met:
8
+
9
+ * Redistributions of source code must retain the above copyright notice, this
10
+ list of conditions and the following disclaimer.
11
+
12
+ * Redistributions in binary form must reproduce the above copyright notice,
13
+ this list of conditions and the following disclaimer in the documentation
14
+ and/or other materials provided with the distribution.
15
+
16
+ * Neither the name of the copyright holder nor the names of its
17
+ contributors may be used to endorse or promote products derived from
18
+ this software without specific prior written permission.
19
+
20
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
24
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
26
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
27
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
28
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/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)
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/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)
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/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
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/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
+ )
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/fuse.py ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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:])
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/generic.py ADDED
@@ -0,0 +1,396 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import inspect
4
+ import logging
5
+ import os
6
+ import shutil
7
+ import uuid
8
+
9
+ from .asyn import AsyncFileSystem, _run_coros_in_chunks, sync_wrapper
10
+ from .callbacks import DEFAULT_CALLBACK
11
+ from .core import filesystem, get_filesystem_class, split_protocol, url_to_fs
12
+
13
+ _generic_fs = {}
14
+ logger = logging.getLogger("fsspec.generic")
15
+
16
+
17
+ def set_generic_fs(protocol, **storage_options):
18
+ """Populate the dict used for method=="generic" lookups"""
19
+ _generic_fs[protocol] = filesystem(protocol, **storage_options)
20
+
21
+
22
+ def _resolve_fs(url, method, protocol=None, storage_options=None):
23
+ """Pick instance of backend FS"""
24
+ url = url[0] if isinstance(url, (list, tuple)) else url
25
+ protocol = protocol or split_protocol(url)[0]
26
+ storage_options = storage_options or {}
27
+ if method == "default":
28
+ return filesystem(protocol)
29
+ if method == "generic":
30
+ return _generic_fs[protocol]
31
+ if method == "current":
32
+ cls = get_filesystem_class(protocol)
33
+ return cls.current()
34
+ if method == "options":
35
+ fs, _ = url_to_fs(url, **storage_options.get(protocol, {}))
36
+ return fs
37
+ raise ValueError(f"Unknown FS resolution method: {method}")
38
+
39
+
40
+ def rsync(
41
+ source,
42
+ destination,
43
+ delete_missing=False,
44
+ source_field="size",
45
+ dest_field="size",
46
+ update_cond="different",
47
+ inst_kwargs=None,
48
+ fs=None,
49
+ **kwargs,
50
+ ):
51
+ """Sync files between two directory trees
52
+
53
+ (experimental)
54
+
55
+ Parameters
56
+ ----------
57
+ source: str
58
+ Root of the directory tree to take files from. This must be a directory, but
59
+ do not include any terminating "/" character
60
+ destination: str
61
+ Root path to copy into. The contents of this location should be
62
+ identical to the contents of ``source`` when done. This will be made a
63
+ directory, and the terminal "/" should not be included.
64
+ delete_missing: bool
65
+ If there are paths in the destination that don't exist in the
66
+ source and this is True, delete them. Otherwise, leave them alone.
67
+ source_field: str | callable
68
+ If ``update_field`` is "different", this is the key in the info
69
+ of source files to consider for difference. Maybe a function of the
70
+ info dict.
71
+ dest_field: str | callable
72
+ If ``update_field`` is "different", this is the key in the info
73
+ of destination files to consider for difference. May be a function of
74
+ the info dict.
75
+ update_cond: "different"|"always"|"never"
76
+ If "always", every file is copied, regardless of whether it exists in
77
+ the destination. If "never", files that exist in the destination are
78
+ not copied again. If "different" (default), only copy if the info
79
+ fields given by ``source_field`` and ``dest_field`` (usually "size")
80
+ are different. Other comparisons may be added in the future.
81
+ inst_kwargs: dict|None
82
+ If ``fs`` is None, use this set of keyword arguments to make a
83
+ GenericFileSystem instance
84
+ fs: GenericFileSystem|None
85
+ Instance to use if explicitly given. The instance defines how to
86
+ to make downstream file system instances from paths.
87
+
88
+ Returns
89
+ -------
90
+ dict of the copy operations that were performed, {source: destination}
91
+ """
92
+ fs = fs or GenericFileSystem(**(inst_kwargs or {}))
93
+ source = fs._strip_protocol(source)
94
+ destination = fs._strip_protocol(destination)
95
+ allfiles = fs.find(source, withdirs=True, detail=True)
96
+ if not fs.isdir(source):
97
+ raise ValueError("Can only rsync on a directory")
98
+ otherfiles = fs.find(destination, withdirs=True, detail=True)
99
+ dirs = [
100
+ a
101
+ for a, v in allfiles.items()
102
+ if v["type"] == "directory" and a.replace(source, destination) not in otherfiles
103
+ ]
104
+ logger.debug(f"{len(dirs)} directories to create")
105
+ if dirs:
106
+ fs.make_many_dirs(
107
+ [dirn.replace(source, destination) for dirn in dirs], exist_ok=True
108
+ )
109
+ allfiles = {a: v for a, v in allfiles.items() if v["type"] == "file"}
110
+ logger.debug(f"{len(allfiles)} files to consider for copy")
111
+ to_delete = [
112
+ o
113
+ for o, v in otherfiles.items()
114
+ if o.replace(destination, source) not in allfiles and v["type"] == "file"
115
+ ]
116
+ for k, v in allfiles.copy().items():
117
+ otherfile = k.replace(source, destination)
118
+ if otherfile in otherfiles:
119
+ if update_cond == "always":
120
+ allfiles[k] = otherfile
121
+ elif update_cond == "never":
122
+ allfiles.pop(k)
123
+ elif update_cond == "different":
124
+ inf1 = source_field(v) if callable(source_field) else v[source_field]
125
+ v2 = otherfiles[otherfile]
126
+ inf2 = dest_field(v2) if callable(dest_field) else v2[dest_field]
127
+ if inf1 != inf2:
128
+ # details mismatch, make copy
129
+ allfiles[k] = otherfile
130
+ else:
131
+ # details match, don't copy
132
+ allfiles.pop(k)
133
+ else:
134
+ # file not in target yet
135
+ allfiles[k] = otherfile
136
+ logger.debug(f"{len(allfiles)} files to copy")
137
+ if allfiles:
138
+ source_files, target_files = zip(*allfiles.items())
139
+ fs.cp(source_files, target_files, **kwargs)
140
+ logger.debug(f"{len(to_delete)} files to delete")
141
+ if delete_missing and to_delete:
142
+ fs.rm(to_delete)
143
+ return allfiles
144
+
145
+
146
+ class GenericFileSystem(AsyncFileSystem):
147
+ """Wrapper over all other FS types
148
+
149
+ <experimental!>
150
+
151
+ This implementation is a single unified interface to be able to run FS operations
152
+ over generic URLs, and dispatch to the specific implementations using the URL
153
+ protocol prefix.
154
+
155
+ Note: instances of this FS are always async, even if you never use it with any async
156
+ backend.
157
+ """
158
+
159
+ protocol = "generic" # there is no real reason to ever use a protocol with this FS
160
+
161
+ def __init__(self, default_method="default", storage_options=None, **kwargs):
162
+ """
163
+
164
+ Parameters
165
+ ----------
166
+ default_method: str (optional)
167
+ Defines how to configure backend FS instances. Options are:
168
+ - "default": instantiate like FSClass(), with no
169
+ extra arguments; this is the default instance of that FS, and can be
170
+ configured via the config system
171
+ - "generic": takes instances from the `_generic_fs` dict in this module,
172
+ which you must populate before use. Keys are by protocol
173
+ - "options": expects storage_options, a dict mapping protocol to
174
+ kwargs to use when constructing the filesystem
175
+ - "current": takes the most recently instantiated version of each FS
176
+ """
177
+ self.method = default_method
178
+ self.st_opts = storage_options
179
+ super().__init__(**kwargs)
180
+
181
+ def _parent(self, path):
182
+ fs = _resolve_fs(path, self.method, storage_options=self.st_opts)
183
+ return fs.unstrip_protocol(fs._parent(path))
184
+
185
+ def _strip_protocol(self, path):
186
+ # normalization only
187
+ fs = _resolve_fs(path, self.method, storage_options=self.st_opts)
188
+ return fs.unstrip_protocol(fs._strip_protocol(path))
189
+
190
+ async def _find(self, path, maxdepth=None, withdirs=False, detail=False, **kwargs):
191
+ fs = _resolve_fs(path, self.method, storage_options=self.st_opts)
192
+ if fs.async_impl:
193
+ out = await fs._find(
194
+ path, maxdepth=maxdepth, withdirs=withdirs, detail=True, **kwargs
195
+ )
196
+ else:
197
+ out = fs.find(
198
+ path, maxdepth=maxdepth, withdirs=withdirs, detail=True, **kwargs
199
+ )
200
+ result = {}
201
+ for k, v in out.items():
202
+ v = v.copy() # don't corrupt target FS dircache
203
+ name = fs.unstrip_protocol(k)
204
+ v["name"] = name
205
+ result[name] = v
206
+ if detail:
207
+ return result
208
+ return list(result)
209
+
210
+ async def _info(self, url, **kwargs):
211
+ fs = _resolve_fs(url, self.method, storage_options=self.st_opts)
212
+ if fs.async_impl:
213
+ out = await fs._info(url, **kwargs)
214
+ else:
215
+ out = fs.info(url, **kwargs)
216
+ out = out.copy() # don't edit originals
217
+ out["name"] = fs.unstrip_protocol(out["name"])
218
+ return out
219
+
220
+ async def _ls(
221
+ self,
222
+ url,
223
+ detail=True,
224
+ **kwargs,
225
+ ):
226
+ fs = _resolve_fs(url, self.method, storage_options=self.st_opts)
227
+ if fs.async_impl:
228
+ out = await fs._ls(url, detail=True, **kwargs)
229
+ else:
230
+ out = fs.ls(url, detail=True, **kwargs)
231
+ out = [o.copy() for o in out] # don't edit originals
232
+ for o in out:
233
+ o["name"] = fs.unstrip_protocol(o["name"])
234
+ if detail:
235
+ return out
236
+ else:
237
+ return [o["name"] for o in out]
238
+
239
+ async def _cat_file(
240
+ self,
241
+ url,
242
+ **kwargs,
243
+ ):
244
+ fs = _resolve_fs(url, self.method, storage_options=self.st_opts)
245
+ if fs.async_impl:
246
+ return await fs._cat_file(url, **kwargs)
247
+ else:
248
+ return fs.cat_file(url, **kwargs)
249
+
250
+ async def _pipe_file(
251
+ self,
252
+ path,
253
+ value,
254
+ **kwargs,
255
+ ):
256
+ fs = _resolve_fs(path, self.method, storage_options=self.st_opts)
257
+ if fs.async_impl:
258
+ return await fs._pipe_file(path, value, **kwargs)
259
+ else:
260
+ return fs.pipe_file(path, value, **kwargs)
261
+
262
+ async def _rm(self, url, **kwargs):
263
+ urls = url
264
+ if isinstance(urls, str):
265
+ urls = [urls]
266
+ fs = _resolve_fs(urls[0], self.method, storage_options=self.st_opts)
267
+ if fs.async_impl:
268
+ await fs._rm(urls, **kwargs)
269
+ else:
270
+ fs.rm(url, **kwargs)
271
+
272
+ async def _makedirs(self, path, exist_ok=False):
273
+ logger.debug("Make dir %s", path)
274
+ fs = _resolve_fs(path, self.method, storage_options=self.st_opts)
275
+ if fs.async_impl:
276
+ await fs._makedirs(path, exist_ok=exist_ok)
277
+ else:
278
+ fs.makedirs(path, exist_ok=exist_ok)
279
+
280
+ def rsync(self, source, destination, **kwargs):
281
+ """Sync files between two directory trees
282
+
283
+ See `func:rsync` for more details.
284
+ """
285
+ rsync(source, destination, fs=self, **kwargs)
286
+
287
+ async def _cp_file(
288
+ self,
289
+ url,
290
+ url2,
291
+ blocksize=2**20,
292
+ callback=DEFAULT_CALLBACK,
293
+ tempdir: str | None = None,
294
+ **kwargs,
295
+ ):
296
+ fs = _resolve_fs(url, self.method, storage_options=self.st_opts)
297
+ fs2 = _resolve_fs(url2, self.method, storage_options=self.st_opts)
298
+ if fs is fs2:
299
+ # pure remote
300
+ if fs.async_impl:
301
+ return await fs._copy(url, url2, **kwargs)
302
+ else:
303
+ return fs.copy(url, url2, **kwargs)
304
+ await copy_file_op(fs, [url], fs2, [url2], tempdir, 1, on_error="raise")
305
+
306
+ async def _make_many_dirs(self, urls, exist_ok=True):
307
+ fs = _resolve_fs(urls[0], self.method, storage_options=self.st_opts)
308
+ if fs.async_impl:
309
+ coros = [fs._makedirs(u, exist_ok=exist_ok) for u in urls]
310
+ await _run_coros_in_chunks(coros)
311
+ else:
312
+ for u in urls:
313
+ fs.makedirs(u, exist_ok=exist_ok)
314
+
315
+ make_many_dirs = sync_wrapper(_make_many_dirs)
316
+
317
+ async def _copy(
318
+ self,
319
+ path1: list[str],
320
+ path2: list[str],
321
+ recursive: bool = False,
322
+ on_error: str = "ignore",
323
+ maxdepth: int | None = None,
324
+ batch_size: int | None = None,
325
+ tempdir: str | None = None,
326
+ **kwargs,
327
+ ):
328
+ # TODO: special case for one FS being local, which can use get/put
329
+ # TODO: special case for one being memFS, which can use cat/pipe
330
+ if recursive:
331
+ raise NotImplementedError("Please use fsspec.generic.rsync")
332
+ path1 = [path1] if isinstance(path1, str) else path1
333
+ path2 = [path2] if isinstance(path2, str) else path2
334
+
335
+ fs = _resolve_fs(path1, self.method, storage_options=self.st_opts)
336
+ fs2 = _resolve_fs(path2, self.method, storage_options=self.st_opts)
337
+
338
+ if fs is fs2:
339
+ if fs.async_impl:
340
+ return await fs._copy(path1, path2, **kwargs)
341
+ else:
342
+ return fs.copy(path1, path2, **kwargs)
343
+
344
+ await copy_file_op(
345
+ fs, path1, fs2, path2, tempdir, batch_size, on_error=on_error
346
+ )
347
+
348
+
349
+ async def copy_file_op(
350
+ fs1, url1, fs2, url2, tempdir=None, batch_size=20, on_error="ignore"
351
+ ):
352
+ import tempfile
353
+
354
+ tempdir = tempdir or tempfile.mkdtemp()
355
+ try:
356
+ coros = [
357
+ _copy_file_op(
358
+ fs1,
359
+ u1,
360
+ fs2,
361
+ u2,
362
+ os.path.join(tempdir, uuid.uuid4().hex),
363
+ )
364
+ for u1, u2 in zip(url1, url2)
365
+ ]
366
+ out = await _run_coros_in_chunks(
367
+ coros, batch_size=batch_size, return_exceptions=True
368
+ )
369
+ finally:
370
+ shutil.rmtree(tempdir)
371
+ if on_error == "return":
372
+ return out
373
+ elif on_error == "raise":
374
+ for o in out:
375
+ if isinstance(o, Exception):
376
+ raise o
377
+
378
+
379
+ async def _copy_file_op(fs1, url1, fs2, url2, local, on_error="ignore"):
380
+ if fs1.async_impl:
381
+ await fs1._get_file(url1, local)
382
+ else:
383
+ fs1.get_file(url1, local)
384
+ if fs2.async_impl:
385
+ await fs2._put_file(local, url2)
386
+ else:
387
+ fs2.put_file(local, url2)
388
+ os.unlink(local)
389
+ logger.debug("Copy %s -> %s; done", url1, url2)
390
+
391
+
392
+ async def maybe_await(cor):
393
+ if inspect.iscoroutine(cor):
394
+ return await cor
395
+ else:
396
+ return cor
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/local.py ADDED
@@ -0,0 +1,517 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime
2
+ import io
3
+ import logging
4
+ import os
5
+ import os.path as osp
6
+ import shutil
7
+ import stat
8
+ import tempfile
9
+ from functools import lru_cache
10
+
11
+ from fsspec import AbstractFileSystem
12
+ from fsspec.compression import compr
13
+ from fsspec.core import get_compression
14
+ from fsspec.utils import isfilelike, stringify_path
15
+
16
+ logger = logging.getLogger("fsspec.local")
17
+
18
+
19
+ class LocalFileSystem(AbstractFileSystem):
20
+ """Interface to files on local storage
21
+
22
+ Parameters
23
+ ----------
24
+ auto_mkdir: bool
25
+ Whether, when opening a file, the directory containing it should
26
+ be created (if it doesn't already exist). This is assumed by pyarrow
27
+ code.
28
+ """
29
+
30
+ root_marker = "/"
31
+ protocol = "file", "local"
32
+ local_file = True
33
+
34
+ def __init__(self, auto_mkdir=False, **kwargs):
35
+ super().__init__(**kwargs)
36
+ self.auto_mkdir = auto_mkdir
37
+
38
+ @property
39
+ def fsid(self):
40
+ return "local"
41
+
42
+ def mkdir(self, path, create_parents=True, **kwargs):
43
+ path = self._strip_protocol(path)
44
+ if self.exists(path):
45
+ raise FileExistsError(path)
46
+ if create_parents:
47
+ self.makedirs(path, exist_ok=True)
48
+ else:
49
+ os.mkdir(path, **kwargs)
50
+
51
+ def makedirs(self, path, exist_ok=False):
52
+ path = self._strip_protocol(path)
53
+ os.makedirs(path, exist_ok=exist_ok)
54
+
55
+ def rmdir(self, path):
56
+ path = self._strip_protocol(path)
57
+ os.rmdir(path)
58
+
59
+ def ls(self, path, detail=False, **kwargs):
60
+ path = self._strip_protocol(path)
61
+ path_info = self.info(path)
62
+ infos = []
63
+ if path_info["type"] == "directory":
64
+ with os.scandir(path) as it:
65
+ for f in it:
66
+ try:
67
+ # Only get the info if requested since it is a bit expensive (the stat call inside)
68
+ # The strip_protocol is also used in info() and calls make_path_posix to always return posix paths
69
+ info = self.info(f) if detail else self._strip_protocol(f.path)
70
+ infos.append(info)
71
+ except FileNotFoundError:
72
+ pass
73
+ else:
74
+ infos = [path_info] if detail else [path_info["name"]]
75
+
76
+ return infos
77
+
78
+ def info(self, path, **kwargs):
79
+ if isinstance(path, os.DirEntry):
80
+ # scandir DirEntry
81
+ out = path.stat(follow_symlinks=False)
82
+ link = path.is_symlink()
83
+ if path.is_dir(follow_symlinks=False):
84
+ t = "directory"
85
+ elif path.is_file(follow_symlinks=False):
86
+ t = "file"
87
+ else:
88
+ t = "other"
89
+
90
+ size = out.st_size
91
+ if link:
92
+ try:
93
+ out2 = path.stat(follow_symlinks=True)
94
+ size = out2.st_size
95
+ except OSError:
96
+ size = 0
97
+ path = self._strip_protocol(path.path)
98
+ else:
99
+ # str or path-like
100
+ path = self._strip_protocol(path)
101
+ out = os.stat(path, follow_symlinks=False)
102
+ link = stat.S_ISLNK(out.st_mode)
103
+ if link:
104
+ out = os.stat(path, follow_symlinks=True)
105
+ size = out.st_size
106
+ if stat.S_ISDIR(out.st_mode):
107
+ t = "directory"
108
+ elif stat.S_ISREG(out.st_mode):
109
+ t = "file"
110
+ else:
111
+ t = "other"
112
+
113
+ # Check for the 'st_birthtime' attribute, which is not always present; fallback to st_ctime
114
+ created_time = getattr(out, "st_birthtime", out.st_ctime)
115
+
116
+ result = {
117
+ "name": path,
118
+ "size": size,
119
+ "type": t,
120
+ "created": created_time,
121
+ "islink": link,
122
+ }
123
+ for field in ["mode", "uid", "gid", "mtime", "ino", "nlink"]:
124
+ result[field] = getattr(out, f"st_{field}")
125
+ if link:
126
+ result["destination"] = os.readlink(path)
127
+ return result
128
+
129
+ def lexists(self, path, **kwargs):
130
+ return osp.lexists(path)
131
+
132
+ def cp_file(self, path1, path2, **kwargs):
133
+ path1 = self._strip_protocol(path1)
134
+ path2 = self._strip_protocol(path2)
135
+ if self.auto_mkdir:
136
+ self.makedirs(self._parent(path2), exist_ok=True)
137
+ if self.isfile(path1):
138
+ shutil.copyfile(path1, path2)
139
+ elif self.isdir(path1):
140
+ self.mkdirs(path2, exist_ok=True)
141
+ else:
142
+ raise FileNotFoundError(path1)
143
+
144
+ def isfile(self, path):
145
+ path = self._strip_protocol(path)
146
+ return os.path.isfile(path)
147
+
148
+ def isdir(self, path):
149
+ path = self._strip_protocol(path)
150
+ return os.path.isdir(path)
151
+
152
+ def get_file(self, path1, path2, callback=None, **kwargs):
153
+ if isfilelike(path2):
154
+ with open(path1, "rb") as f:
155
+ shutil.copyfileobj(f, path2)
156
+ else:
157
+ return self.cp_file(path1, path2, **kwargs)
158
+
159
+ def put_file(self, path1, path2, callback=None, **kwargs):
160
+ return self.cp_file(path1, path2, **kwargs)
161
+
162
+ def mv(self, path1, path2, recursive: bool = True, **kwargs):
163
+ """Move files/directories
164
+ For the specific case of local, all ops on directories are recursive and
165
+ the recursive= kwarg is ignored.
166
+ """
167
+ path1 = self._strip_protocol(path1)
168
+ path2 = self._strip_protocol(path2)
169
+
170
+ if self.auto_mkdir:
171
+ self.makedirs(self._parent(path2), exist_ok=True)
172
+
173
+ shutil.move(path1, path2)
174
+
175
+ def link(self, src, dst, **kwargs):
176
+ src = self._strip_protocol(src)
177
+ dst = self._strip_protocol(dst)
178
+ os.link(src, dst, **kwargs)
179
+
180
+ def symlink(self, src, dst, **kwargs):
181
+ src = self._strip_protocol(src)
182
+ dst = self._strip_protocol(dst)
183
+ os.symlink(src, dst, **kwargs)
184
+
185
+ def islink(self, path) -> bool:
186
+ return os.path.islink(self._strip_protocol(path))
187
+
188
+ def rm_file(self, path):
189
+ os.remove(self._strip_protocol(path))
190
+
191
+ def rm(self, path, recursive=False, maxdepth=None):
192
+ if not isinstance(path, list):
193
+ path = [path]
194
+
195
+ for p in path:
196
+ p = self._strip_protocol(p)
197
+ if self.isdir(p) and not self.islink(p):
198
+ if not recursive:
199
+ raise ValueError("Cannot delete directory, set recursive=True")
200
+ if osp.abspath(p) == os.getcwd():
201
+ raise ValueError("Cannot delete current working directory")
202
+ shutil.rmtree(p)
203
+ else:
204
+ os.remove(p)
205
+
206
+ def unstrip_protocol(self, name):
207
+ protocol = self.protocol if isinstance(self.protocol, str) else self.protocol[0]
208
+ name = self._strip_protocol(name) # normalise for local/win/...
209
+ return f"{protocol}://{name}"
210
+
211
+ def _open(self, path, mode="rb", block_size=None, **kwargs):
212
+ path = self._strip_protocol(path)
213
+ if self.auto_mkdir and ("w" in mode or "x" in mode or "a" in mode):
214
+ self.makedirs(self._parent(path), exist_ok=True)
215
+ return LocalFileOpener(path, mode, fs=self, **kwargs)
216
+
217
+ def touch(self, path, truncate=True, **kwargs):
218
+ path = self._strip_protocol(path)
219
+ if self.auto_mkdir:
220
+ self.makedirs(self._parent(path), exist_ok=True)
221
+ if self.exists(path):
222
+ os.utime(path, None)
223
+ else:
224
+ open(path, "a").close()
225
+ if truncate:
226
+ os.truncate(path, 0)
227
+
228
+ def created(self, path):
229
+ info = self.info(path=path)
230
+ return datetime.datetime.fromtimestamp(
231
+ info["created"], tz=datetime.timezone.utc
232
+ )
233
+
234
+ def modified(self, path):
235
+ info = self.info(path=path)
236
+ return datetime.datetime.fromtimestamp(info["mtime"], tz=datetime.timezone.utc)
237
+
238
+ @classmethod
239
+ def _parent(cls, path):
240
+ path = cls._strip_protocol(path)
241
+ if os.sep == "/":
242
+ # posix native
243
+ return path.rsplit("/", 1)[0] or "/"
244
+ else:
245
+ # NT
246
+ path_ = path.rsplit("/", 1)[0]
247
+ if len(path_) <= 3:
248
+ if path_[1:2] == ":":
249
+ # nt root (something like c:/)
250
+ return path_[0] + ":/"
251
+ # More cases may be required here
252
+ return path_
253
+
254
+ @classmethod
255
+ def _strip_protocol(cls, path):
256
+ path = stringify_path(path)
257
+ protos = (cls.protocol,) if isinstance(cls.protocol, str) else cls.protocol
258
+ prefixes = (protocol + sep for protocol in protos for sep in ("://", ":"))
259
+ for prefix in prefixes:
260
+ if path.startswith(prefix):
261
+ path = path.removeprefix(prefix)
262
+ break
263
+
264
+ path = make_path_posix(path)
265
+ if os.sep != "/":
266
+ # This code-path is a stripped down version of
267
+ # > drive, path = ntpath.splitdrive(path)
268
+ if path[1:2] == ":":
269
+ # Absolute drive-letter path, e.g. X:\Windows
270
+ # Relative path with drive, e.g. X:Windows
271
+ drive, path = path[:2], path[2:]
272
+ elif path[:2] == "//":
273
+ # UNC drives, e.g. \\server\share or \\?\UNC\server\share
274
+ # Device drives, e.g. \\.\device or \\?\device
275
+ if (index1 := path.find("/", 2)) == -1 or (
276
+ index2 := path.find("/", index1 + 1)
277
+ ) == -1:
278
+ drive, path = path, ""
279
+ else:
280
+ drive, path = path[:index2], path[index2:]
281
+ else:
282
+ # Relative path, e.g. Windows
283
+ drive = ""
284
+
285
+ path = path.rstrip("/") or cls.root_marker
286
+ return drive + path
287
+
288
+ else:
289
+ return path.rstrip("/") or cls.root_marker
290
+
291
+ def _isfilestore(self):
292
+ # Inheriting from DaskFileSystem makes this False (S3, etc. were)
293
+ # the original motivation. But we are a posix-like file system.
294
+ # See https://github.com/dask/dask/issues/5526
295
+ return True
296
+
297
+ def chmod(self, path, mode):
298
+ path = stringify_path(path)
299
+ return os.chmod(path, mode)
300
+
301
+
302
+ def make_path_posix(path):
303
+ """Make path generic and absolute for current OS"""
304
+ if not isinstance(path, str):
305
+ if isinstance(path, (list, set, tuple)):
306
+ return type(path)(make_path_posix(p) for p in path)
307
+ else:
308
+ path = stringify_path(path)
309
+ if not isinstance(path, str):
310
+ raise TypeError(f"could not convert {path!r} to string")
311
+ if os.sep == "/":
312
+ # Native posix
313
+ if path.startswith("/"):
314
+ # most common fast case for posix
315
+ return path
316
+ elif path.startswith("~"):
317
+ return osp.expanduser(path)
318
+ elif path.startswith("./"):
319
+ path = path[2:]
320
+ elif path == ".":
321
+ path = ""
322
+ return f"{os.getcwd()}/{path}"
323
+ else:
324
+ # NT handling
325
+ if path[0:1] == "/" and path[2:3] == ":":
326
+ # path is like "/c:/local/path"
327
+ path = path[1:]
328
+ if path[1:2] == ":":
329
+ # windows full path like "C:\\local\\path"
330
+ if len(path) <= 3:
331
+ # nt root (something like c:/)
332
+ return path[0] + ":/"
333
+ path = path.replace("\\", "/")
334
+ return path
335
+ elif path[0:1] == "~":
336
+ return make_path_posix(osp.expanduser(path))
337
+ elif path.startswith(("\\\\", "//")):
338
+ # windows UNC/DFS-style paths
339
+ return "//" + path[2:].replace("\\", "/")
340
+ elif path.startswith(("\\", "/")):
341
+ # windows relative path with root
342
+ path = path.replace("\\", "/")
343
+ return f"{osp.splitdrive(os.getcwd())[0]}{path}"
344
+ else:
345
+ path = path.replace("\\", "/")
346
+ if path.startswith("./"):
347
+ path = path[2:]
348
+ elif path == ".":
349
+ path = ""
350
+ return f"{make_path_posix(os.getcwd())}/{path}"
351
+
352
+
353
+ def trailing_sep(path):
354
+ """Return True if the path ends with a path separator.
355
+
356
+ A forward slash is always considered a path separator, even on Operating
357
+ Systems that normally use a backslash.
358
+ """
359
+ # TODO: if all incoming paths were posix-compliant then separator would
360
+ # always be a forward slash, simplifying this function.
361
+ # See https://github.com/fsspec/filesystem_spec/pull/1250
362
+ return path.endswith(os.sep) or (os.altsep is not None and path.endswith(os.altsep))
363
+
364
+
365
+ @lru_cache(maxsize=1)
366
+ def get_umask(mask: int = 0o666) -> int:
367
+ """Get the current umask.
368
+
369
+ Follows https://stackoverflow.com/a/44130549 to get the umask.
370
+ Temporarily sets the umask to the given value, and then resets it to the
371
+ original value.
372
+ """
373
+ value = os.umask(mask)
374
+ os.umask(value)
375
+ return value
376
+
377
+
378
+ class LocalFileOpener(io.IOBase):
379
+ def __init__(
380
+ self, path, mode, autocommit=True, fs=None, compression=None, **kwargs
381
+ ):
382
+ logger.debug("open file: %s", path)
383
+ self.path = path
384
+ self.mode = mode
385
+ self.fs = fs
386
+ self.f = None
387
+ self.autocommit = autocommit
388
+ self.compression = get_compression(path, compression)
389
+ self.blocksize = io.DEFAULT_BUFFER_SIZE
390
+ self._open()
391
+
392
+ def _open(self):
393
+ if self.f is None or self.f.closed:
394
+ if self.autocommit or "w" not in self.mode:
395
+ self.f = open(self.path, mode=self.mode)
396
+ if self.compression:
397
+ compress = compr[self.compression]
398
+ self.f = compress(self.f, mode=self.mode)
399
+ else:
400
+ # TODO: check if path is writable?
401
+ i, name = tempfile.mkstemp()
402
+ os.close(i) # we want normal open and normal buffered file
403
+ self.temp = name
404
+ self.f = open(name, mode=self.mode)
405
+ if "w" not in self.mode:
406
+ self.size = self.f.seek(0, 2)
407
+ self.f.seek(0)
408
+ self.f.size = self.size
409
+
410
+ def _fetch_range(self, start, end):
411
+ # probably only used by cached FS
412
+ if "r" not in self.mode:
413
+ raise ValueError
414
+ self._open()
415
+ self.f.seek(start)
416
+ return self.f.read(end - start)
417
+
418
+ def __setstate__(self, state):
419
+ self.f = None
420
+ loc = state.pop("loc", None)
421
+ self.__dict__.update(state)
422
+ if "r" in state["mode"]:
423
+ self.f = None
424
+ self._open()
425
+ self.f.seek(loc)
426
+
427
+ def __getstate__(self):
428
+ d = self.__dict__.copy()
429
+ d.pop("f")
430
+ if "r" in self.mode:
431
+ d["loc"] = self.f.tell()
432
+ else:
433
+ if not self.f.closed:
434
+ raise ValueError("Cannot serialise open write-mode local file")
435
+ return d
436
+
437
+ def commit(self):
438
+ if self.autocommit:
439
+ raise RuntimeError("Can only commit if not already set to autocommit")
440
+ try:
441
+ shutil.move(self.temp, self.path)
442
+ except PermissionError as e:
443
+ # shutil.move raises PermissionError if os.rename
444
+ # and the default copy2 fallback with shutil.copystats fail.
445
+ # The file should be there nonetheless, but without copied permissions.
446
+ # If it doesn't exist, there was no permission to create the file.
447
+ if not os.path.exists(self.path):
448
+ raise e
449
+ else:
450
+ # If PermissionError is not raised, permissions can be set.
451
+ try:
452
+ mask = 0o666
453
+ os.chmod(self.path, mask & ~get_umask(mask))
454
+ except RuntimeError:
455
+ pass
456
+
457
+ def discard(self):
458
+ if self.autocommit:
459
+ raise RuntimeError("Cannot discard if set to autocommit")
460
+ os.remove(self.temp)
461
+
462
+ def readable(self) -> bool:
463
+ return True
464
+
465
+ def writable(self) -> bool:
466
+ return "r" not in self.mode
467
+
468
+ def read(self, *args, **kwargs):
469
+ return self.f.read(*args, **kwargs)
470
+
471
+ def write(self, *args, **kwargs):
472
+ return self.f.write(*args, **kwargs)
473
+
474
+ def tell(self, *args, **kwargs):
475
+ return self.f.tell(*args, **kwargs)
476
+
477
+ def seek(self, *args, **kwargs):
478
+ return self.f.seek(*args, **kwargs)
479
+
480
+ def seekable(self, *args, **kwargs):
481
+ return self.f.seekable(*args, **kwargs)
482
+
483
+ def readline(self, *args, **kwargs):
484
+ return self.f.readline(*args, **kwargs)
485
+
486
+ def readlines(self, *args, **kwargs):
487
+ return self.f.readlines(*args, **kwargs)
488
+
489
+ def close(self):
490
+ return self.f.close()
491
+
492
+ def truncate(self, size=None) -> int:
493
+ return self.f.truncate(size)
494
+
495
+ @property
496
+ def closed(self):
497
+ return self.f.closed
498
+
499
+ def fileno(self):
500
+ return self.raw.fileno()
501
+
502
+ def flush(self) -> None:
503
+ self.f.flush()
504
+
505
+ def __iter__(self):
506
+ return self.f.__iter__()
507
+
508
+ def __getattr__(self, item):
509
+ return getattr(self.f, item)
510
+
511
+ def __enter__(self):
512
+ self._incontext = True
513
+ return self
514
+
515
+ def __exit__(self, exc_type, exc_value, traceback):
516
+ self._incontext = False
517
+ self.f.__exit__(exc_type, exc_value, traceback)
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/reference.py ADDED
@@ -0,0 +1,1339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import collections
3
+ import io
4
+ import itertools
5
+ import logging
6
+ import math
7
+ import os
8
+ from functools import lru_cache
9
+ from itertools import chain
10
+ from typing import TYPE_CHECKING, Literal
11
+
12
+ import fsspec.core
13
+ from fsspec.spec import AbstractBufferedFile
14
+
15
+ try:
16
+ import ujson as json
17
+ except ImportError:
18
+ if not TYPE_CHECKING:
19
+ import json
20
+
21
+ from fsspec.asyn import AsyncFileSystem
22
+ from fsspec.callbacks import DEFAULT_CALLBACK
23
+ from fsspec.core import filesystem, open, split_protocol
24
+ from fsspec.implementations.asyn_wrapper import AsyncFileSystemWrapper
25
+ from fsspec.utils import (
26
+ isfilelike,
27
+ merge_offset_ranges,
28
+ other_paths,
29
+ )
30
+
31
+ logger = logging.getLogger("fsspec.reference")
32
+
33
+
34
+ class ReferenceNotReachable(RuntimeError):
35
+ def __init__(self, reference, target, *args):
36
+ super().__init__(*args)
37
+ self.reference = reference
38
+ self.target = target
39
+
40
+ def __str__(self):
41
+ return f'Reference "{self.reference}" failed to fetch target {self.target}'
42
+
43
+
44
+ def _first(d):
45
+ return next(iter(d.values()))
46
+
47
+
48
+ def _prot_in_references(path, references):
49
+ ref = references.get(path)
50
+ if isinstance(ref, (list, tuple)) and isinstance(ref[0], str):
51
+ return split_protocol(ref[0])[0] if ref[0] else ref[0]
52
+
53
+
54
+ def _protocol_groups(paths, references):
55
+ if isinstance(paths, str):
56
+ return {_prot_in_references(paths, references): [paths]}
57
+ out = {}
58
+ for path in paths:
59
+ protocol = _prot_in_references(path, references)
60
+ out.setdefault(protocol, []).append(path)
61
+ return out
62
+
63
+
64
+ class RefsValuesView(collections.abc.ValuesView):
65
+ def __iter__(self):
66
+ for val in self._mapping.zmetadata.values():
67
+ yield json.dumps(val).encode()
68
+ yield from self._mapping._items.values()
69
+ for field in self._mapping.listdir():
70
+ chunk_sizes = self._mapping._get_chunk_sizes(field)
71
+ if len(chunk_sizes) == 0:
72
+ yield self._mapping[field + "/0"]
73
+ continue
74
+ yield from self._mapping._generate_all_records(field)
75
+
76
+
77
+ class RefsItemsView(collections.abc.ItemsView):
78
+ def __iter__(self):
79
+ return zip(self._mapping.keys(), self._mapping.values())
80
+
81
+
82
+ def ravel_multi_index(idx, sizes):
83
+ val = 0
84
+ mult = 1
85
+ for i, s in zip(idx[::-1], sizes[::-1]):
86
+ val += i * mult
87
+ mult *= s
88
+ return val
89
+
90
+
91
+ class LazyReferenceMapper(collections.abc.MutableMapping):
92
+ """This interface can be used to read/write references from Parquet stores.
93
+ It is not intended for other types of references.
94
+ It can be used with Kerchunk's MultiZarrToZarr method to combine
95
+ references into a parquet store.
96
+ Examples of this use-case can be found here:
97
+ https://fsspec.github.io/kerchunk/advanced.html?highlight=parquet#parquet-storage"""
98
+
99
+ # import is class level to prevent numpy dep requirement for fsspec
100
+ @property
101
+ def np(self):
102
+ import numpy as np
103
+
104
+ return np
105
+
106
+ @property
107
+ def pd(self):
108
+ import pandas as pd
109
+
110
+ return pd
111
+
112
+ def __init__(
113
+ self,
114
+ root,
115
+ fs=None,
116
+ out_root=None,
117
+ cache_size=128,
118
+ categorical_threshold=10,
119
+ engine: Literal["fastparquet", "pyarrow"] = "fastparquet",
120
+ ):
121
+ """
122
+
123
+ This instance will be writable, storing changes in memory until full partitions
124
+ are accumulated or .flush() is called.
125
+
126
+ To create an empty lazy store, use .create()
127
+
128
+ Parameters
129
+ ----------
130
+ root : str
131
+ Root of parquet store
132
+ fs : fsspec.AbstractFileSystem
133
+ fsspec filesystem object, default is local filesystem.
134
+ cache_size : int, default=128
135
+ Maximum size of LRU cache, where cache_size*record_size denotes
136
+ the total number of references that can be loaded in memory at once.
137
+ categorical_threshold : int
138
+ Encode urls as pandas.Categorical to reduce memory footprint if the ratio
139
+ of the number of unique urls to total number of refs for each variable
140
+ is greater than or equal to this number. (default 10)
141
+ engine: Literal["fastparquet","pyarrow"]
142
+ Engine choice for reading parquet files. (default is "fastparquet")
143
+ """
144
+
145
+ self.root = root
146
+ self.chunk_sizes = {}
147
+ self.cat_thresh = categorical_threshold
148
+ self.engine = engine
149
+ self.cache_size = cache_size
150
+ self.url = self.root + "/{field}/refs.{record}.parq"
151
+ # TODO: derive fs from `root`
152
+ self.fs = fsspec.filesystem("file") if fs is None else fs
153
+ self.out_root = self.fs.unstrip_protocol(out_root or self.root)
154
+
155
+ from importlib.util import find_spec
156
+
157
+ if self.engine == "pyarrow" and find_spec("pyarrow") is None:
158
+ raise ImportError("engine choice `pyarrow` is not installed.")
159
+
160
+ # Apply `lru_cache` decorator manually per instance.
161
+ # This way `self` reference is not held on class level.
162
+ # WARNING: However, this means that self and its members are not reflected
163
+ # in the cache key, so we expect they won't be mutated once a value is cached.
164
+ self.listdir = lru_cache()(self.listdir)
165
+ self._key_to_record = lru_cache(maxsize=4096)(self._key_to_record)
166
+
167
+ def __getattr__(self, item):
168
+ if item in ("_items", "record_size", "zmetadata"):
169
+ self.setup()
170
+ # avoid possible recursion if setup fails somehow
171
+ return self.__dict__[item]
172
+ raise AttributeError(item)
173
+
174
+ def setup(self):
175
+ self._items = {}
176
+ self._items[".zmetadata"] = self.fs.cat_file(
177
+ "/".join([self.root, ".zmetadata"])
178
+ )
179
+ met = json.loads(self._items[".zmetadata"])
180
+ self.record_size = met["record_size"]
181
+ self.zmetadata = met["metadata"]
182
+
183
+ # Define function to open and decompress refs
184
+ @lru_cache(maxsize=self.cache_size)
185
+ def open_refs(field, record):
186
+ """cached parquet file loader"""
187
+ path = self.url.format(field=field, record=record)
188
+ data = io.BytesIO(self.fs.cat_file(path))
189
+ try:
190
+ df = self.pd.read_parquet(data, engine=self.engine)
191
+ refs = {c: df[c].to_numpy(copy=True) for c in df.columns}
192
+ except OSError:
193
+ refs = None
194
+ return refs
195
+
196
+ self.open_refs = open_refs
197
+
198
+ @staticmethod
199
+ def create(root, storage_options=None, fs=None, record_size=10000, **kwargs):
200
+ """Make empty parquet reference set
201
+
202
+ First deletes the contents of the given directory, if it exists.
203
+
204
+ Parameters
205
+ ----------
206
+ root: str
207
+ Directory to contain the output; will be created
208
+ storage_options: dict | None
209
+ For making the filesystem to use for writing is fs is None
210
+ fs: FileSystem | None
211
+ Filesystem for writing
212
+ record_size: int
213
+ Number of references per parquet file
214
+ kwargs: passed to __init__
215
+
216
+ Returns
217
+ -------
218
+ LazyReferenceMapper instance
219
+ """
220
+ met = {"metadata": {}, "record_size": record_size}
221
+ if fs is None:
222
+ fs, root = fsspec.core.url_to_fs(root, **(storage_options or {}))
223
+ if fs.exists(root):
224
+ fs.rm(root, recursive=True)
225
+ fs.makedirs(root, exist_ok=True)
226
+ fs.pipe("/".join([root, ".zmetadata"]), json.dumps(met).encode())
227
+ return LazyReferenceMapper(root, fs, **kwargs)
228
+
229
+ def listdir(self):
230
+ """List top-level directories"""
231
+ dirs = (p.rsplit("/", 1)[0] for p in self.zmetadata if not p.startswith(".z"))
232
+ return set(dirs)
233
+
234
+ def ls(self, path="", detail=True):
235
+ """Shortcut file listings"""
236
+ path = path.rstrip("/")
237
+ pathdash = path + "/" if path else ""
238
+ dirnames = self.listdir()
239
+ dirs = [
240
+ d
241
+ for d in dirnames
242
+ if d.startswith(pathdash) and "/" not in d.lstrip(pathdash)
243
+ ]
244
+ if dirs:
245
+ others = {
246
+ f
247
+ for f in chain(
248
+ [".zmetadata"],
249
+ (name for name in self.zmetadata),
250
+ (name for name in self._items),
251
+ )
252
+ if f.startswith(pathdash) and "/" not in f.lstrip(pathdash)
253
+ }
254
+ if detail is False:
255
+ others.update(dirs)
256
+ return sorted(others)
257
+ dirinfo = [{"name": name, "type": "directory", "size": 0} for name in dirs]
258
+ fileinfo = [
259
+ {
260
+ "name": name,
261
+ "type": "file",
262
+ "size": len(
263
+ json.dumps(self.zmetadata[name])
264
+ if name in self.zmetadata
265
+ else self._items[name]
266
+ ),
267
+ }
268
+ for name in others
269
+ ]
270
+ return sorted(dirinfo + fileinfo, key=lambda s: s["name"])
271
+ field = path
272
+ others = set(
273
+ [name for name in self.zmetadata if name.startswith(f"{path}/")]
274
+ + [name for name in self._items if name.startswith(f"{path}/")]
275
+ )
276
+ fileinfo = [
277
+ {
278
+ "name": name,
279
+ "type": "file",
280
+ "size": len(
281
+ json.dumps(self.zmetadata[name])
282
+ if name in self.zmetadata
283
+ else self._items[name]
284
+ ),
285
+ }
286
+ for name in others
287
+ ]
288
+ keys = self._keys_in_field(field)
289
+
290
+ if detail is False:
291
+ return list(others) + list(keys)
292
+ recs = self._generate_all_records(field)
293
+ recinfo = [
294
+ {"name": name, "type": "file", "size": rec[-1]}
295
+ for name, rec in zip(keys, recs)
296
+ if rec[0] # filters out path==None, deleted/missing
297
+ ]
298
+ return fileinfo + recinfo
299
+
300
+ def _load_one_key(self, key):
301
+ """Get the reference for one key
302
+
303
+ Returns bytes, one-element list or three-element list.
304
+ """
305
+ if key in self._items:
306
+ return self._items[key]
307
+ elif key in self.zmetadata:
308
+ return json.dumps(self.zmetadata[key]).encode()
309
+ elif "/" not in key or self._is_meta(key):
310
+ raise KeyError(key)
311
+ field, _ = key.rsplit("/", 1)
312
+ record, ri, chunk_size = self._key_to_record(key)
313
+ maybe = self._items.get((field, record), {}).get(ri, False)
314
+ if maybe is None:
315
+ # explicitly deleted
316
+ raise KeyError
317
+ elif maybe:
318
+ return maybe
319
+ elif chunk_size == 0:
320
+ return b""
321
+
322
+ # Chunk keys can be loaded from row group and cached in LRU cache
323
+ try:
324
+ refs = self.open_refs(field, record)
325
+ except (ValueError, TypeError, FileNotFoundError) as exc:
326
+ raise KeyError(key) from exc
327
+ columns = ["path", "offset", "size", "raw"]
328
+ selection = [refs[c][ri] if c in refs else None for c in columns]
329
+ raw = selection[-1]
330
+ if raw is not None:
331
+ return raw
332
+ if selection[0] is None:
333
+ raise KeyError("This reference does not exist or has been deleted")
334
+ if selection[1:3] == [0, 0]:
335
+ # URL only
336
+ return selection[:1]
337
+ # URL, offset, size
338
+ return selection[:3]
339
+
340
+ def _key_to_record(self, key):
341
+ """Details needed to construct a reference for one key"""
342
+ field, chunk = key.rsplit("/", 1)
343
+ chunk_sizes = self._get_chunk_sizes(field)
344
+ if len(chunk_sizes) == 0:
345
+ return 0, 0, 0
346
+ chunk_idx = [int(c) for c in chunk.split(".")]
347
+ chunk_number = ravel_multi_index(chunk_idx, chunk_sizes)
348
+ record = chunk_number // self.record_size
349
+ ri = chunk_number % self.record_size
350
+ return record, ri, len(chunk_sizes)
351
+
352
+ def _get_chunk_sizes(self, field):
353
+ """The number of chunks along each axis for a given field"""
354
+ if field not in self.chunk_sizes:
355
+ zarray = self.zmetadata[f"{field}/.zarray"]
356
+ size_ratio = [
357
+ math.ceil(s / c) for s, c in zip(zarray["shape"], zarray["chunks"])
358
+ ]
359
+ self.chunk_sizes[field] = size_ratio or [1]
360
+ return self.chunk_sizes[field]
361
+
362
+ def _generate_record(self, field, record):
363
+ """The references for a given parquet file of a given field"""
364
+ refs = self.open_refs(field, record)
365
+ it = iter(zip(*refs.values()))
366
+ if len(refs) == 3:
367
+ # All urls
368
+ return (list(t) for t in it)
369
+ elif len(refs) == 1:
370
+ # All raws
371
+ return refs["raw"]
372
+ else:
373
+ # Mix of urls and raws
374
+ return (list(t[:3]) if not t[3] else t[3] for t in it)
375
+
376
+ def _generate_all_records(self, field):
377
+ """Load all the references within a field by iterating over the parquet files"""
378
+ nrec = 1
379
+ for ch in self._get_chunk_sizes(field):
380
+ nrec *= ch
381
+ nrec = math.ceil(nrec / self.record_size)
382
+ for record in range(nrec):
383
+ yield from self._generate_record(field, record)
384
+
385
+ def values(self):
386
+ return RefsValuesView(self)
387
+
388
+ def items(self):
389
+ return RefsItemsView(self)
390
+
391
+ def __hash__(self):
392
+ return id(self)
393
+
394
+ def __getitem__(self, key):
395
+ return self._load_one_key(key)
396
+
397
+ def __setitem__(self, key, value):
398
+ if "/" in key and not self._is_meta(key):
399
+ field, chunk = key.rsplit("/", 1)
400
+ record, i, _ = self._key_to_record(key)
401
+ subdict = self._items.setdefault((field, record), {})
402
+ subdict[i] = value
403
+ if len(subdict) == self.record_size:
404
+ self.write(field, record)
405
+ else:
406
+ # metadata or top-level
407
+ if hasattr(value, "to_bytes"):
408
+ val = value.to_bytes().decode()
409
+ elif isinstance(value, bytes):
410
+ val = value.decode()
411
+ else:
412
+ val = value
413
+ self._items[key] = val
414
+ new_value = json.loads(val)
415
+ self.zmetadata[key] = {**self.zmetadata.get(key, {}), **new_value}
416
+
417
+ @staticmethod
418
+ def _is_meta(key):
419
+ return key.startswith(".z") or "/.z" in key
420
+
421
+ def __delitem__(self, key):
422
+ if key in self._items:
423
+ del self._items[key]
424
+ elif key in self.zmetadata:
425
+ del self.zmetadata[key]
426
+ else:
427
+ if "/" in key and not self._is_meta(key):
428
+ field, _ = key.rsplit("/", 1)
429
+ record, i, _ = self._key_to_record(key)
430
+ subdict = self._items.setdefault((field, record), {})
431
+ subdict[i] = None
432
+ if len(subdict) == self.record_size:
433
+ self.write(field, record)
434
+ else:
435
+ # metadata or top-level
436
+ self._items[key] = None
437
+
438
+ def write(self, field, record, base_url=None, storage_options=None):
439
+ # extra requirements if writing
440
+ import kerchunk.df
441
+ import numpy as np
442
+ import pandas as pd
443
+
444
+ partition = self._items[(field, record)]
445
+ original = False
446
+ if len(partition) < self.record_size:
447
+ try:
448
+ original = self.open_refs(field, record)
449
+ except OSError:
450
+ pass
451
+
452
+ if original:
453
+ paths = original["path"]
454
+ offsets = original["offset"]
455
+ sizes = original["size"]
456
+ raws = original["raw"]
457
+ else:
458
+ paths = np.full(self.record_size, np.nan, dtype="O")
459
+ offsets = np.zeros(self.record_size, dtype="int64")
460
+ sizes = np.zeros(self.record_size, dtype="int64")
461
+ raws = np.full(self.record_size, np.nan, dtype="O")
462
+ for j, data in partition.items():
463
+ if isinstance(data, list):
464
+ if (
465
+ str(paths.dtype) == "category"
466
+ and data[0] not in paths.dtype.categories
467
+ ):
468
+ paths = paths.add_categories(data[0])
469
+ paths[j] = data[0]
470
+ if len(data) > 1:
471
+ offsets[j] = data[1]
472
+ sizes[j] = data[2]
473
+ elif data is None:
474
+ # delete
475
+ paths[j] = None
476
+ offsets[j] = 0
477
+ sizes[j] = 0
478
+ raws[j] = None
479
+ else:
480
+ # this is the only call into kerchunk, could remove
481
+ raws[j] = kerchunk.df._proc_raw(data)
482
+ # TODO: only save needed columns
483
+ df = pd.DataFrame(
484
+ {
485
+ "path": paths,
486
+ "offset": offsets,
487
+ "size": sizes,
488
+ "raw": raws,
489
+ },
490
+ copy=False,
491
+ )
492
+ if df.path.count() / (df.path.nunique() or 1) > self.cat_thresh:
493
+ df["path"] = df["path"].astype("category")
494
+ object_encoding = {"raw": "bytes", "path": "utf8"}
495
+ has_nulls = ["path", "raw"]
496
+
497
+ fn = f"{base_url or self.out_root}/{field}/refs.{record}.parq"
498
+ self.fs.mkdirs(f"{base_url or self.out_root}/{field}", exist_ok=True)
499
+
500
+ if self.engine == "pyarrow":
501
+ df_backend_kwargs = {"write_statistics": False}
502
+ elif self.engine == "fastparquet":
503
+ df_backend_kwargs = {
504
+ "stats": False,
505
+ "object_encoding": object_encoding,
506
+ "has_nulls": has_nulls,
507
+ }
508
+ else:
509
+ raise NotImplementedError(f"{self.engine} not supported")
510
+ df.to_parquet(
511
+ fn,
512
+ engine=self.engine,
513
+ storage_options=storage_options
514
+ or getattr(self.fs, "storage_options", None),
515
+ compression="zstd",
516
+ index=False,
517
+ **df_backend_kwargs,
518
+ )
519
+
520
+ partition.clear()
521
+ self._items.pop((field, record))
522
+
523
+ def flush(self, base_url=None, storage_options=None):
524
+ """Output any modified or deleted keys
525
+
526
+ Parameters
527
+ ----------
528
+ base_url: str
529
+ Location of the output
530
+ """
531
+
532
+ # write what we have so far and clear sub chunks
533
+ for thing in list(self._items):
534
+ if isinstance(thing, tuple):
535
+ field, record = thing
536
+ self.write(
537
+ field,
538
+ record,
539
+ base_url=base_url,
540
+ storage_options=storage_options,
541
+ )
542
+
543
+ # gather .zmetadata from self._items and write that too
544
+ for k in list(self._items):
545
+ if k != ".zmetadata" and ".z" in k:
546
+ self.zmetadata[k] = json.loads(self._items.pop(k))
547
+ met = {"metadata": self.zmetadata, "record_size": self.record_size}
548
+ self._items.clear()
549
+ self._items[".zmetadata"] = json.dumps(met).encode()
550
+ self.fs.pipe(
551
+ "/".join([base_url or self.out_root, ".zmetadata"]),
552
+ self._items[".zmetadata"],
553
+ )
554
+
555
+ # TODO: only clear those that we wrote to?
556
+ self.open_refs.cache_clear()
557
+
558
+ def __len__(self):
559
+ # Caveat: This counts expected references, not actual - but is fast
560
+ count = 0
561
+ for field in self.listdir():
562
+ if field.startswith("."):
563
+ count += 1
564
+ else:
565
+ count += math.prod(self._get_chunk_sizes(field))
566
+ count += len(self.zmetadata) # all metadata keys
567
+ # any other files not in reference partitions
568
+ count += sum(1 for _ in self._items if not isinstance(_, tuple))
569
+ return count
570
+
571
+ def __iter__(self):
572
+ # Caveat: returns only existing keys, so the number of these does not
573
+ # match len(self)
574
+ metas = set(self.zmetadata)
575
+ metas.update(self._items)
576
+ for bit in metas:
577
+ if isinstance(bit, str):
578
+ yield bit
579
+ for field in self.listdir():
580
+ for k in self._keys_in_field(field):
581
+ if k in self:
582
+ yield k
583
+
584
+ def __contains__(self, item):
585
+ try:
586
+ self._load_one_key(item)
587
+ return True
588
+ except KeyError:
589
+ return False
590
+
591
+ def _keys_in_field(self, field):
592
+ """List key names in given field
593
+
594
+ Produces strings like "field/x.y" appropriate from the chunking of the array
595
+ """
596
+ chunk_sizes = self._get_chunk_sizes(field)
597
+ if len(chunk_sizes) == 0:
598
+ yield field + "/0"
599
+ return
600
+ inds = itertools.product(*(range(i) for i in chunk_sizes))
601
+ for ind in inds:
602
+ yield field + "/" + ".".join([str(c) for c in ind])
603
+
604
+
605
+ class ReferenceFileSystem(AsyncFileSystem):
606
+ """View byte ranges of some other file as a file system
607
+ Initial version: single file system target, which must support
608
+ async, and must allow start and end args in _cat_file. Later versions
609
+ may allow multiple arbitrary URLs for the targets.
610
+ This FileSystem is read-only. It is designed to be used with async
611
+ targets (for now). We do not get original file details from the target FS.
612
+ Configuration is by passing a dict of references at init, or a URL to
613
+ a JSON file containing the same; this dict
614
+ can also contain concrete data for some set of paths.
615
+ Reference dict format:
616
+ {path0: bytes_data, path1: (target_url, offset, size)}
617
+ https://github.com/fsspec/kerchunk/blob/main/README.md
618
+
619
+ simple_references: if True (default), no jinja interpreting is done,
620
+ which is the safe option.
621
+ """
622
+
623
+ protocol = "reference"
624
+ cachable = False
625
+
626
+ def __init__(
627
+ self,
628
+ fo,
629
+ target=None,
630
+ ref_storage_args=None,
631
+ target_protocol=None,
632
+ target_options=None,
633
+ remote_protocol=None,
634
+ remote_options=None,
635
+ fs=None,
636
+ template_overrides=None,
637
+ simple_templates=True,
638
+ max_gap=64_000,
639
+ max_block=256_000_000,
640
+ cache_size=128,
641
+ **kwargs,
642
+ ):
643
+ """
644
+ Parameters
645
+ ----------
646
+ fo : dict or str
647
+ The set of references to use for this instance, with a structure as above.
648
+ If str referencing a JSON file, will use fsspec.open, in conjunction
649
+ with target_options and target_protocol to open and parse JSON at this
650
+ location. If a directory, then assume references are a set of parquet
651
+ files to be loaded lazily.
652
+ target : str
653
+ For any references having target_url as None, this is the default file
654
+ target to use
655
+ ref_storage_args : dict
656
+ If references is a str, use these kwargs for loading the JSON file.
657
+ Deprecated: use target_options instead.
658
+ target_protocol : str
659
+ Used for loading the reference file, if it is a path. If None, protocol
660
+ will be derived from the given path
661
+ target_options : dict
662
+ Extra FS options for loading the reference file ``fo``, if given as a path
663
+ remote_protocol : str
664
+ The protocol of the filesystem on which the references will be evaluated
665
+ (unless fs is provided). If not given, will be derived from the first
666
+ URL that has a protocol in the templates or in the references, in that
667
+ order.
668
+ remote_options : dict
669
+ kwargs to go with remote_protocol
670
+ fs : AbstractFileSystem | dict(str, (AbstractFileSystem | dict))
671
+ Directly provide a file system(s):
672
+ - a single filesystem instance
673
+ - a dict of protocol:filesystem, where each value is either a filesystem
674
+ instance, or a dict of kwargs that can be used to create in
675
+ instance for the given protocol
676
+
677
+ If this is given, remote_options and remote_protocol are ignored.
678
+ template_overrides : dict
679
+ Swap out any templates in the references file with these - useful for
680
+ testing.
681
+ simple_templates: bool
682
+ Whether templates can be processed with simple replace (True) or if
683
+ jinja is needed (False, much slower). All reference sets produced by
684
+ ``kerchunk`` are simple in this sense, but the spec allows for complex.
685
+ max_gap, max_block: int
686
+ For merging multiple concurrent requests to the same remote file.
687
+ Neighboring byte ranges will only be merged when their
688
+ inter-range gap is <= ``max_gap``. Default is 64KB. Set to 0
689
+ to only merge when it requires no extra bytes. Pass a negative
690
+ number to disable merging, appropriate for local target files.
691
+ Neighboring byte ranges will only be merged when the size of
692
+ the aggregated range is <= ``max_block``. Default is 256MB.
693
+ cache_size : int
694
+ Maximum size of LRU cache, where cache_size*record_size denotes
695
+ the total number of references that can be loaded in memory at once.
696
+ Only used for lazily loaded references.
697
+ kwargs : passed to parent class
698
+ """
699
+ super().__init__(**kwargs)
700
+ self.target = target
701
+ self.template_overrides = template_overrides
702
+ self.simple_templates = simple_templates
703
+ self.templates = {}
704
+ self.fss = {}
705
+ self._dircache = {}
706
+ self.max_gap = max_gap
707
+ self.max_block = max_block
708
+ if isinstance(fo, str):
709
+ dic = dict(
710
+ **(ref_storage_args or target_options or {}), protocol=target_protocol
711
+ )
712
+ ref_fs, fo2 = fsspec.core.url_to_fs(fo, **dic)
713
+ if ".json" not in fo2 and (
714
+ fo.endswith(("parq", "parquet", "/")) or ref_fs.isdir(fo2)
715
+ ):
716
+ # Lazy parquet refs
717
+ logger.info("Open lazy reference dict from URL %s", fo)
718
+ self.references = LazyReferenceMapper(
719
+ fo2,
720
+ fs=ref_fs,
721
+ cache_size=cache_size,
722
+ )
723
+ else:
724
+ # text JSON
725
+ with fsspec.open(fo, "rb", **dic) as f:
726
+ logger.info("Read reference from URL %s", fo)
727
+ text = json.load(f)
728
+ self._process_references(text, template_overrides)
729
+ else:
730
+ # dictionaries
731
+ self._process_references(fo, template_overrides)
732
+ if isinstance(fs, dict):
733
+ self.fss = {
734
+ k: (
735
+ fsspec.filesystem(k.split(":", 1)[0], **opts)
736
+ if isinstance(opts, dict)
737
+ else opts
738
+ )
739
+ for k, opts in fs.items()
740
+ }
741
+ if None not in self.fss:
742
+ self.fss[None] = filesystem("file")
743
+ return
744
+ if fs is not None:
745
+ # single remote FS
746
+ remote_protocol = (
747
+ fs.protocol[0] if isinstance(fs.protocol, tuple) else fs.protocol
748
+ )
749
+ self.fss[remote_protocol] = fs
750
+
751
+ if remote_protocol is None:
752
+ # get single protocol from any templates
753
+ for ref in self.templates.values():
754
+ if callable(ref):
755
+ ref = ref()
756
+ protocol, _ = fsspec.core.split_protocol(ref)
757
+ if protocol and protocol not in self.fss:
758
+ fs = filesystem(protocol, **(remote_options or {}))
759
+ self.fss[protocol] = fs
760
+ if remote_protocol is None:
761
+ # get single protocol from references
762
+ # TODO: warning here, since this can be very expensive?
763
+ for ref in self.references.values():
764
+ if callable(ref):
765
+ ref = ref()
766
+ if isinstance(ref, list) and ref[0]:
767
+ protocol, _ = fsspec.core.split_protocol(ref[0])
768
+ if protocol not in self.fss:
769
+ fs = filesystem(protocol, **(remote_options or {}))
770
+ self.fss[protocol] = fs
771
+ # only use first remote URL
772
+ break
773
+
774
+ if remote_protocol and remote_protocol not in self.fss:
775
+ fs = filesystem(remote_protocol, **(remote_options or {}))
776
+ self.fss[remote_protocol] = fs
777
+
778
+ self.fss[None] = fs or filesystem("file") # default one
779
+ # Wrap any non-async filesystems to ensure async methods are available below
780
+ for k, f in self.fss.items():
781
+ if not f.async_impl:
782
+ self.fss[k] = AsyncFileSystemWrapper(f, asynchronous=self.asynchronous)
783
+ elif self.asynchronous ^ f.asynchronous:
784
+ raise ValueError(
785
+ "Reference-FS's target filesystem must have same value "
786
+ "of asynchronous"
787
+ )
788
+
789
+ def _cat_common(self, path, start=None, end=None):
790
+ path = self._strip_protocol(path)
791
+ logger.debug(f"cat: {path}")
792
+ try:
793
+ part = self.references[path]
794
+ except KeyError as exc:
795
+ raise FileNotFoundError(path) from exc
796
+ if isinstance(part, str):
797
+ part = part.encode()
798
+ if hasattr(part, "to_bytes"):
799
+ part = part.to_bytes()
800
+ if isinstance(part, bytes):
801
+ logger.debug(f"Reference: {path}, type bytes")
802
+ if part.startswith(b"base64:"):
803
+ part = base64.b64decode(part[7:])
804
+ return part, None, None
805
+
806
+ if len(part) == 1:
807
+ logger.debug(f"Reference: {path}, whole file => {part}")
808
+ url = part[0]
809
+ start1, end1 = start, end
810
+ else:
811
+ url, start0, size = part
812
+ logger.debug(f"Reference: {path} => {url}, offset {start0}, size {size}")
813
+ end0 = start0 + size
814
+
815
+ if start is not None:
816
+ if start >= 0:
817
+ start1 = start0 + start
818
+ else:
819
+ start1 = end0 + start
820
+ else:
821
+ start1 = start0
822
+ if end is not None:
823
+ if end >= 0:
824
+ end1 = start0 + end
825
+ else:
826
+ end1 = end0 + end
827
+ else:
828
+ end1 = end0
829
+ if url is None:
830
+ url = self.target
831
+ return url, start1, end1
832
+
833
+ async def _cat_file(self, path, start=None, end=None, **kwargs):
834
+ part_or_url, start0, end0 = self._cat_common(path, start=start, end=end)
835
+ if isinstance(part_or_url, bytes):
836
+ return part_or_url[start:end]
837
+ protocol, _ = split_protocol(part_or_url)
838
+ try:
839
+ return await self.fss[protocol]._cat_file(
840
+ part_or_url, start=start0, end=end0
841
+ )
842
+ except Exception as e:
843
+ raise ReferenceNotReachable(path, part_or_url) from e
844
+
845
+ def cat_file(self, path, start=None, end=None, **kwargs):
846
+ part_or_url, start0, end0 = self._cat_common(path, start=start, end=end)
847
+ if isinstance(part_or_url, bytes):
848
+ return part_or_url[start:end]
849
+ protocol, _ = split_protocol(part_or_url)
850
+ try:
851
+ return self.fss[protocol].cat_file(part_or_url, start=start0, end=end0)
852
+ except Exception as e:
853
+ raise ReferenceNotReachable(path, part_or_url) from e
854
+
855
+ def pipe_file(self, path, value, **_):
856
+ """Temporarily add binary data or reference as a file"""
857
+ self.references[path] = value
858
+
859
+ async def _get_file(self, rpath, lpath, **kwargs):
860
+ if self.isdir(rpath):
861
+ return os.makedirs(lpath, exist_ok=True)
862
+ data = await self._cat_file(rpath)
863
+ with open(lpath, "wb") as f:
864
+ f.write(data)
865
+
866
+ def get_file(self, rpath, lpath, callback=DEFAULT_CALLBACK, **kwargs):
867
+ if self.isdir(rpath):
868
+ return os.makedirs(lpath, exist_ok=True)
869
+ data = self.cat_file(rpath, **kwargs)
870
+ callback.set_size(len(data))
871
+ if isfilelike(lpath):
872
+ lpath.write(data)
873
+ else:
874
+ with open(lpath, "wb") as f:
875
+ f.write(data)
876
+ callback.absolute_update(len(data))
877
+
878
+ def get(self, rpath, lpath, recursive=False, **kwargs):
879
+ if recursive:
880
+ # trigger directory build
881
+ self.ls("")
882
+ rpath = self.expand_path(rpath, recursive=recursive)
883
+ fs = fsspec.filesystem("file", auto_mkdir=True)
884
+ targets = other_paths(rpath, lpath)
885
+ if recursive:
886
+ data = self.cat([r for r in rpath if not self.isdir(r)])
887
+ else:
888
+ data = self.cat(rpath)
889
+ for remote, local in zip(rpath, targets):
890
+ if remote in data:
891
+ fs.pipe_file(local, data[remote])
892
+
893
+ def cat(self, path, recursive=False, on_error="raise", **kwargs):
894
+ if isinstance(path, str) and recursive:
895
+ raise NotImplementedError
896
+ if isinstance(path, list) and (recursive or any("*" in p for p in path)):
897
+ raise NotImplementedError
898
+ # TODO: if references is lazy, pre-fetch all paths in batch before access
899
+ proto_dict = _protocol_groups(path, self.references)
900
+ out = {}
901
+ for proto, paths in proto_dict.items():
902
+ fs = self.fss[proto]
903
+ urls, starts, ends, valid_paths = [], [], [], []
904
+ for p in paths:
905
+ # find references or label not-found. Early exit if any not
906
+ # found and on_error is "raise"
907
+ try:
908
+ u, s, e = self._cat_common(p)
909
+ if not isinstance(u, (bytes, str)):
910
+ # nan/None from parquet
911
+ continue
912
+ except FileNotFoundError as err:
913
+ if on_error == "raise":
914
+ raise
915
+ if on_error != "omit":
916
+ out[p] = err
917
+ else:
918
+ urls.append(u)
919
+ starts.append(s)
920
+ ends.append(e)
921
+ valid_paths.append(p)
922
+
923
+ # process references into form for merging
924
+ urls2 = []
925
+ starts2 = []
926
+ ends2 = []
927
+ paths2 = []
928
+ whole_files = set()
929
+ for u, s, e, p in zip(urls, starts, ends, valid_paths):
930
+ if isinstance(u, bytes):
931
+ # data
932
+ out[p] = u
933
+ elif s is None:
934
+ # whole file - limits are None, None, but no further
935
+ # entries take for this file
936
+ whole_files.add(u)
937
+ urls2.append(u)
938
+ starts2.append(s)
939
+ ends2.append(e)
940
+ paths2.append(p)
941
+ for u, s, e, p in zip(urls, starts, ends, valid_paths):
942
+ # second run to account for files that are to be loaded whole
943
+ if s is not None and u not in whole_files:
944
+ urls2.append(u)
945
+ starts2.append(s)
946
+ ends2.append(e)
947
+ paths2.append(p)
948
+
949
+ # merge and fetch consolidated ranges
950
+ new_paths, new_starts, new_ends = merge_offset_ranges(
951
+ list(urls2),
952
+ list(starts2),
953
+ list(ends2),
954
+ sort=True,
955
+ max_gap=self.max_gap,
956
+ max_block=self.max_block,
957
+ )
958
+ bytes_out = fs.cat_ranges(new_paths, new_starts, new_ends)
959
+
960
+ # unbundle from merged bytes - simple approach
961
+ for u, s, e, p in zip(urls, starts, ends, valid_paths):
962
+ if p in out:
963
+ continue # was bytes, already handled
964
+ for np, ns, ne, b in zip(new_paths, new_starts, new_ends, bytes_out):
965
+ if np == u and (ns is None or ne is None):
966
+ if isinstance(b, Exception):
967
+ out[p] = b
968
+ else:
969
+ out[p] = b[s:e]
970
+ elif np == u and s >= ns and e <= ne:
971
+ if isinstance(b, Exception):
972
+ out[p] = b
973
+ else:
974
+ out[p] = b[s - ns : (e - ne) or None]
975
+
976
+ for k, v in out.copy().items():
977
+ # these were valid references, but fetch failed, so transform exc
978
+ if isinstance(v, Exception) and k in self.references:
979
+ ex = out[k]
980
+ new_ex = ReferenceNotReachable(k, self.references[k])
981
+ new_ex.__cause__ = ex
982
+ if on_error == "raise":
983
+ raise new_ex
984
+ elif on_error != "omit":
985
+ out[k] = new_ex
986
+
987
+ if len(out) == 1 and isinstance(path, str) and "*" not in path:
988
+ return _first(out)
989
+ return out
990
+
991
+ def _process_references(self, references, template_overrides=None):
992
+ vers = references.get("version", None)
993
+ if vers is None:
994
+ self._process_references0(references)
995
+ elif vers == 1:
996
+ self._process_references1(references, template_overrides=template_overrides)
997
+ else:
998
+ raise ValueError(f"Unknown reference spec version: {vers}")
999
+ # TODO: we make dircache by iterating over all entries, but for Spec >= 1,
1000
+ # can replace with programmatic. Is it even needed for mapper interface?
1001
+
1002
+ def _process_references0(self, references):
1003
+ """Make reference dict for Spec Version 0"""
1004
+ if isinstance(references, dict):
1005
+ # do not do this for lazy/parquet backend, which will not make dicts,
1006
+ # but must remain writable in the original object
1007
+ references = {
1008
+ key: json.dumps(val) if isinstance(val, dict) else val
1009
+ for key, val in references.items()
1010
+ }
1011
+ self.references = references
1012
+
1013
+ def _process_references1(self, references, template_overrides=None):
1014
+ if not self.simple_templates or self.templates:
1015
+ import jinja2.sandbox
1016
+ self.references = {}
1017
+ self._process_templates(references.get("templates", {}))
1018
+
1019
+ @lru_cache(1000)
1020
+ def _render_jinja(u):
1021
+ return (
1022
+ jinja2.sandbox.SandboxedEnvironment()
1023
+ .from_string(u)
1024
+ .render(**self.templates)
1025
+ )
1026
+
1027
+ for k, v in references.get("refs", {}).items():
1028
+ if isinstance(v, str):
1029
+ if v.startswith("base64:"):
1030
+ self.references[k] = base64.b64decode(v[7:])
1031
+ self.references[k] = v
1032
+ elif isinstance(v, dict):
1033
+ self.references[k] = json.dumps(v)
1034
+ elif self.templates:
1035
+ u = v[0]
1036
+ if "{{" in u:
1037
+ if self.simple_templates:
1038
+ u = (
1039
+ u.replace("{{", "{")
1040
+ .replace("}}", "}")
1041
+ .format(**self.templates)
1042
+ )
1043
+ else:
1044
+ u = _render_jinja(u)
1045
+ self.references[k] = [u] if len(v) == 1 else [u, v[1], v[2]]
1046
+ else:
1047
+ self.references[k] = v
1048
+ self.references.update(self._process_gen(references.get("gen", [])))
1049
+
1050
+ def _process_templates(self, tmp):
1051
+ self.templates = {}
1052
+ if self.template_overrides is not None:
1053
+ tmp.update(self.template_overrides)
1054
+ for k, v in tmp.items():
1055
+ if "{{" in v:
1056
+ import jinja2.sandbox
1057
+
1058
+ self.templates[k] = (
1059
+ lambda temp=v, **kwargs: jinja2.sandbox.SandboxedEnvironment()
1060
+ .from_string(temp)
1061
+ .render(**kwargs)
1062
+ )
1063
+ else:
1064
+ self.templates[k] = v
1065
+
1066
+ def _process_gen(self, gens):
1067
+ out = {}
1068
+ if self.simple_templates:
1069
+ return out
1070
+ for gen in gens:
1071
+ dimension = {
1072
+ k: (
1073
+ v
1074
+ if isinstance(v, list)
1075
+ else range(v.get("start", 0), v["stop"], v.get("step", 1))
1076
+ )
1077
+ for k, v in gen["dimensions"].items()
1078
+ }
1079
+ products = (
1080
+ dict(zip(dimension.keys(), values))
1081
+ for values in itertools.product(*dimension.values())
1082
+ )
1083
+ for pr in products:
1084
+ import jinja2.sandbox
1085
+
1086
+ key = (
1087
+ jinja2.sandbox.SandboxedEnvironment()
1088
+ .from_string(gen["key"])
1089
+ .render(**pr, **self.templates)
1090
+ )
1091
+ url = (
1092
+ jinja2.sandbox.SandboxedEnvironment()
1093
+ .from_string(gen["url"])
1094
+ .render(**pr, **self.templates)
1095
+ )
1096
+ if ("offset" in gen) and ("length" in gen):
1097
+ offset = int(
1098
+ jinja2.sandbox.SandboxedEnvironment()
1099
+ .from_string(gen["offset"])
1100
+ .render(**pr, **self.templates)
1101
+ )
1102
+ length = int(
1103
+ jinja2.sandbox.SandboxedEnvironment()
1104
+ .from_string(gen["length"])
1105
+ .render(**pr, **self.templates)
1106
+ )
1107
+ out[key] = [url, offset, length]
1108
+ elif ("offset" in gen) ^ ("length" in gen):
1109
+ raise ValueError(
1110
+ "Both 'offset' and 'length' are required for a "
1111
+ "reference generator entry if either is provided."
1112
+ )
1113
+ else:
1114
+ out[key] = [url]
1115
+ return out
1116
+
1117
+ def _dircache_from_items(self):
1118
+ self.dircache = {"": []}
1119
+ it = self.references.items()
1120
+ for path, part in it:
1121
+ if isinstance(part, (bytes, str)) or hasattr(part, "to_bytes"):
1122
+ size = len(part)
1123
+ elif len(part) == 1:
1124
+ size = None
1125
+ else:
1126
+ _, _, size = part
1127
+ par = path.rsplit("/", 1)[0] if "/" in path else ""
1128
+ par0 = par
1129
+ subdirs = [par0]
1130
+ while par0 and par0 not in self.dircache:
1131
+ # collect parent directories
1132
+ par0 = self._parent(par0)
1133
+ subdirs.append(par0)
1134
+
1135
+ subdirs.reverse()
1136
+ for parent, child in zip(subdirs, subdirs[1:]):
1137
+ # register newly discovered directories
1138
+ assert child not in self.dircache
1139
+ assert parent in self.dircache
1140
+ self.dircache[parent].append(
1141
+ {"name": child, "type": "directory", "size": 0}
1142
+ )
1143
+ self.dircache[child] = []
1144
+
1145
+ self.dircache[par].append({"name": path, "type": "file", "size": size})
1146
+
1147
+ def _open(self, path, mode="rb", block_size=None, cache_options=None, **kwargs):
1148
+ part_or_url, start0, end0 = self._cat_common(path)
1149
+ # This logic is kept outside `ReferenceFile` to avoid unnecessary redirection.
1150
+ # That does mean `_cat_common` gets called twice if it eventually reaches `ReferenceFile`.
1151
+ if isinstance(part_or_url, bytes):
1152
+ return io.BytesIO(part_or_url[start0:end0])
1153
+
1154
+ protocol, _ = split_protocol(part_or_url)
1155
+ if start0 is None and end0 is None:
1156
+ return self.fss[protocol]._open(
1157
+ part_or_url,
1158
+ mode,
1159
+ block_size=block_size,
1160
+ cache_options=cache_options,
1161
+ **kwargs,
1162
+ )
1163
+
1164
+ return ReferenceFile(
1165
+ self,
1166
+ path,
1167
+ mode,
1168
+ block_size=block_size,
1169
+ cache_options=cache_options,
1170
+ **kwargs,
1171
+ )
1172
+
1173
+ def ls(self, path, detail=True, **kwargs):
1174
+ logger.debug("list %s", path)
1175
+ path = self._strip_protocol(path)
1176
+ if isinstance(self.references, LazyReferenceMapper):
1177
+ try:
1178
+ return self.references.ls(path, detail)
1179
+ except KeyError:
1180
+ pass
1181
+ raise FileNotFoundError(f"'{path}' is not a known key")
1182
+ if not self.dircache:
1183
+ self._dircache_from_items()
1184
+ out = self._ls_from_cache(path)
1185
+ if out is None:
1186
+ raise FileNotFoundError(path)
1187
+ if detail:
1188
+ return out
1189
+ return [o["name"] for o in out]
1190
+
1191
+ def exists(self, path, **kwargs): # overwrite auto-sync version
1192
+ return self.isdir(path) or self.isfile(path)
1193
+
1194
+ def isdir(self, path): # overwrite auto-sync version
1195
+ if self.dircache:
1196
+ return path in self.dircache
1197
+ elif isinstance(self.references, LazyReferenceMapper):
1198
+ return path in self.references.listdir()
1199
+ else:
1200
+ # this may be faster than building dircache for single calls, but
1201
+ # by looping will be slow for many calls; could cache it?
1202
+ return any(_.startswith(f"{path}/") for _ in self.references)
1203
+
1204
+ def isfile(self, path): # overwrite auto-sync version
1205
+ return path in self.references
1206
+
1207
+ async def _ls(self, path, detail=True, **kwargs): # calls fast sync code
1208
+ return self.ls(path, detail, **kwargs)
1209
+
1210
+ def find(self, path, maxdepth=None, withdirs=False, detail=False, **kwargs):
1211
+ if withdirs:
1212
+ return super().find(
1213
+ path, maxdepth=maxdepth, withdirs=withdirs, detail=detail, **kwargs
1214
+ )
1215
+ if path:
1216
+ path = self._strip_protocol(path)
1217
+ r = sorted(k for k in self.references if k.startswith(path))
1218
+ else:
1219
+ r = sorted(self.references)
1220
+ if detail:
1221
+ if not self.dircache:
1222
+ self._dircache_from_items()
1223
+ return {k: self._ls_from_cache(k)[0] for k in r}
1224
+ else:
1225
+ return r
1226
+
1227
+ def info(self, path, **kwargs):
1228
+ out = self.references.get(path)
1229
+ if out is not None:
1230
+ if isinstance(out, (str, bytes)):
1231
+ # decode base64 here
1232
+ return {"name": path, "type": "file", "size": len(out)}
1233
+ elif len(out) > 1:
1234
+ return {"name": path, "type": "file", "size": out[2]}
1235
+ else:
1236
+ out0 = [{"name": path, "type": "file", "size": None}]
1237
+ else:
1238
+ out = self.ls(path, True)
1239
+ out0 = [o for o in out if o["name"] == path]
1240
+ if not out0:
1241
+ return {"name": path, "type": "directory", "size": 0}
1242
+ if out0[0]["size"] is None:
1243
+ # if this is a whole remote file, update size using remote FS
1244
+ prot, _ = split_protocol(self.references[path][0])
1245
+ out0[0]["size"] = self.fss[prot].size(self.references[path][0])
1246
+ return out0[0]
1247
+
1248
+ async def _info(self, path, **kwargs): # calls fast sync code
1249
+ return self.info(path)
1250
+
1251
+ async def _rm_file(self, path, **kwargs):
1252
+ self.references.pop(
1253
+ path, None
1254
+ ) # ignores FileNotFound, just as well for directories
1255
+ self.dircache.clear() # this is a bit heavy handed
1256
+
1257
+ async def _pipe_file(self, path, data, mode="overwrite", **kwargs):
1258
+ if mode == "create" and self.exists(path):
1259
+ raise FileExistsError
1260
+ # can be str or bytes
1261
+ self.references[path] = data
1262
+ self.dircache.clear() # this is a bit heavy handed
1263
+
1264
+ async def _put_file(self, lpath, rpath, mode="overwrite", **kwargs):
1265
+ # puts binary
1266
+ if mode == "create" and self.exists(rpath):
1267
+ raise FileExistsError
1268
+ with open(lpath, "rb") as f:
1269
+ self.references[rpath] = f.read()
1270
+ self.dircache.clear() # this is a bit heavy handed
1271
+
1272
+ def save_json(self, url, **storage_options):
1273
+ """Write modified references into new location"""
1274
+ out = {}
1275
+ for k, v in self.references.items():
1276
+ if isinstance(v, bytes):
1277
+ try:
1278
+ out[k] = v.decode("ascii")
1279
+ except UnicodeDecodeError:
1280
+ out[k] = (b"base64:" + base64.b64encode(v)).decode()
1281
+ else:
1282
+ out[k] = v
1283
+ with fsspec.open(url, "wb", **storage_options) as f:
1284
+ f.write(json.dumps({"version": 1, "refs": out}).encode())
1285
+
1286
+
1287
+ class ReferenceFile(AbstractBufferedFile):
1288
+ def __init__(
1289
+ self,
1290
+ fs,
1291
+ path,
1292
+ mode="rb",
1293
+ block_size="default",
1294
+ autocommit=True,
1295
+ cache_type="readahead",
1296
+ cache_options=None,
1297
+ size=None,
1298
+ **kwargs,
1299
+ ):
1300
+ super().__init__(
1301
+ fs,
1302
+ path,
1303
+ mode=mode,
1304
+ block_size=block_size,
1305
+ autocommit=autocommit,
1306
+ size=size,
1307
+ cache_type=cache_type,
1308
+ cache_options=cache_options,
1309
+ **kwargs,
1310
+ )
1311
+ part_or_url, self.start, self.end = self.fs._cat_common(self.path)
1312
+ protocol, _ = split_protocol(part_or_url)
1313
+ self.src_fs = self.fs.fss[protocol]
1314
+ self.src_path = part_or_url
1315
+ self._f = None
1316
+
1317
+ @property
1318
+ def f(self):
1319
+ if self._f is None or self._f.closed:
1320
+ self._f = self.src_fs._open(
1321
+ self.src_path,
1322
+ mode=self.mode,
1323
+ block_size=self.blocksize,
1324
+ autocommit=self.autocommit,
1325
+ cache_type="none",
1326
+ **self.kwargs,
1327
+ )
1328
+ return self._f
1329
+
1330
+ def close(self):
1331
+ if self._f is not None:
1332
+ self._f.close()
1333
+ return super().close()
1334
+
1335
+ def _fetch_range(self, start, end):
1336
+ start = start + self.start
1337
+ end = min(end + self.start, self.end)
1338
+ self.f.seek(start)
1339
+ return self.f.read(end - start)
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/smb.py ADDED
@@ -0,0 +1,416 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This module contains SMBFileSystem class responsible for handling access to
3
+ Windows Samba network shares by using package smbprotocol
4
+ """
5
+
6
+ import datetime
7
+ import re
8
+ import uuid
9
+ from stat import S_ISDIR, S_ISLNK
10
+
11
+ import smbclient
12
+ import smbprotocol.exceptions
13
+
14
+ from .. import AbstractFileSystem
15
+ from ..utils import infer_storage_options
16
+
17
+ # ! pylint: disable=bad-continuation
18
+
19
+
20
+ class SMBFileSystem(AbstractFileSystem):
21
+ """Allow reading and writing to Windows and Samba network shares.
22
+
23
+ When using `fsspec.open()` for getting a file-like object the URI
24
+ should be specified as this format:
25
+ ``smb://workgroup;user:password@server:port/share/folder/file.csv``.
26
+
27
+ Example::
28
+
29
+ >>> import fsspec
30
+ >>> with fsspec.open(
31
+ ... 'smb://myuser:mypassword@myserver.com/' 'share/folder/file.csv'
32
+ ... ) as smbfile:
33
+ ... df = pd.read_csv(smbfile, sep='|', header=None)
34
+
35
+ Note that you need to pass in a valid hostname or IP address for the host
36
+ component of the URL. Do not use the Windows/NetBIOS machine name for the
37
+ host component.
38
+
39
+ The first component of the path in the URL points to the name of the shared
40
+ folder. Subsequent path components will point to the directory/folder/file.
41
+
42
+ The URL components ``workgroup`` , ``user``, ``password`` and ``port`` may be
43
+ optional.
44
+
45
+ .. note::
46
+
47
+ For working this source require `smbprotocol`_ to be installed, e.g.::
48
+
49
+ $ pip install smbprotocol
50
+ # or
51
+ # pip install smbprotocol[kerberos]
52
+
53
+ .. _smbprotocol: https://github.com/jborean93/smbprotocol#requirements
54
+
55
+ Note: if using this with the ``open`` or ``open_files``, with full URLs,
56
+ there is no way to tell if a path is relative, so all paths are assumed
57
+ to be absolute.
58
+ """
59
+
60
+ protocol = "smb"
61
+
62
+ # pylint: disable=too-many-arguments
63
+ def __init__(
64
+ self,
65
+ host,
66
+ port=None,
67
+ username=None,
68
+ password=None,
69
+ timeout=60,
70
+ encrypt=None,
71
+ share_access=None,
72
+ register_session_retries=4,
73
+ register_session_retry_wait=1,
74
+ register_session_retry_factor=10,
75
+ auto_mkdir=False,
76
+ **kwargs,
77
+ ):
78
+ """
79
+ You can use _get_kwargs_from_urls to get some kwargs from
80
+ a reasonable SMB url.
81
+
82
+ Authentication will be anonymous or integrated if username/password are not
83
+ given.
84
+
85
+ Parameters
86
+ ----------
87
+ host: str
88
+ The remote server name/ip to connect to
89
+ port: int or None
90
+ Port to connect with. Usually 445, sometimes 139.
91
+ username: str or None
92
+ Username to connect with. Required if Kerberos auth is not being used.
93
+ password: str or None
94
+ User's password on the server, if using username
95
+ timeout: int
96
+ Connection timeout in seconds
97
+ encrypt: bool
98
+ Whether to force encryption or not, once this has been set to True
99
+ the session cannot be changed back to False.
100
+ share_access: str or None
101
+ Specifies the default access applied to file open operations
102
+ performed with this file system object.
103
+ This affects whether other processes can concurrently open a handle
104
+ to the same file.
105
+
106
+ - None (the default): exclusively locks the file until closed.
107
+ - 'r': Allow other handles to be opened with read access.
108
+ - 'w': Allow other handles to be opened with write access.
109
+ - 'd': Allow other handles to be opened with delete access.
110
+ register_session_retries: int
111
+ Number of retries to register a session with the server. Retries are not performed
112
+ for authentication errors, as they are considered as invalid credentials and not network
113
+ issues. If set to negative value, no register attempts will be performed.
114
+ register_session_retry_wait: int
115
+ Time in seconds to wait between each retry. Number must be non-negative.
116
+ register_session_retry_factor: int
117
+ Base factor for the wait time between each retry. The wait time
118
+ is calculated using exponential function. For factor=1 all wait times
119
+ will be equal to `register_session_retry_wait`. For any number of retries,
120
+ the last wait time will be equal to `register_session_retry_wait` and for retries>1
121
+ the first wait time will be equal to `register_session_retry_wait / factor`.
122
+ Number must be equal to or greater than 1. Optimal factor is 10.
123
+ auto_mkdir: bool
124
+ Whether, when opening a file, the directory containing it should
125
+ be created (if it doesn't already exist). This is assumed by pyarrow
126
+ and zarr-python code.
127
+ """
128
+ super().__init__(**kwargs)
129
+ self.host = host
130
+ self.port = port
131
+ self.username = username
132
+ self.password = password
133
+ self.timeout = timeout
134
+ self.encrypt = encrypt
135
+ self.temppath = kwargs.pop("temppath", "")
136
+ self.share_access = share_access
137
+ self.register_session_retries = register_session_retries
138
+ if register_session_retry_wait < 0:
139
+ raise ValueError(
140
+ "register_session_retry_wait must be a non-negative integer"
141
+ )
142
+ self.register_session_retry_wait = register_session_retry_wait
143
+ if register_session_retry_factor < 1:
144
+ raise ValueError(
145
+ "register_session_retry_factor must be a positive "
146
+ "integer equal to or greater than 1"
147
+ )
148
+ self.register_session_retry_factor = register_session_retry_factor
149
+ self.auto_mkdir = auto_mkdir
150
+ self._connect()
151
+
152
+ @property
153
+ def _port(self):
154
+ return 445 if self.port is None else self.port
155
+
156
+ def _connect(self):
157
+ import time
158
+
159
+ if self.register_session_retries <= -1:
160
+ return
161
+
162
+ retried_errors = []
163
+
164
+ wait_time = self.register_session_retry_wait
165
+ n_waits = (
166
+ self.register_session_retries - 1
167
+ ) # -1 = No wait time after the last retry
168
+ factor = self.register_session_retry_factor
169
+
170
+ # Generate wait times for each retry attempt.
171
+ # Wait times are calculated using exponential function. For factor=1 all wait times
172
+ # will be equal to `wait`. For any number of retries the last wait time will be
173
+ # equal to `wait` and for retries>2 the first wait time will be equal to `wait / factor`.
174
+ wait_times = iter(
175
+ factor ** (n / n_waits - 1) * wait_time for n in range(0, n_waits + 1)
176
+ )
177
+
178
+ for attempt in range(self.register_session_retries + 1):
179
+ try:
180
+ smbclient.register_session(
181
+ self.host,
182
+ username=self.username,
183
+ password=self.password,
184
+ port=self._port,
185
+ encrypt=self.encrypt,
186
+ connection_timeout=self.timeout,
187
+ )
188
+ return
189
+ except (
190
+ smbprotocol.exceptions.SMBAuthenticationError,
191
+ smbprotocol.exceptions.LogonFailure,
192
+ ):
193
+ # These exceptions should not be repeated, as they clearly indicate
194
+ # that the credentials are invalid and not a network issue.
195
+ raise
196
+ except ValueError as exc:
197
+ if re.findall(r"\[Errno -\d+]", str(exc)):
198
+ # This exception is raised by the smbprotocol.transport:Tcp.connect
199
+ # and originates from socket.gaierror (OSError). These exceptions might
200
+ # be raised due to network instability. We will retry to connect.
201
+ retried_errors.append(exc)
202
+ else:
203
+ # All another ValueError exceptions should be raised, as they are not
204
+ # related to network issues.
205
+ raise
206
+ except Exception as exc:
207
+ # Save the exception and retry to connect. This except might be dropped
208
+ # in the future, once all exceptions suited for retry are identified.
209
+ retried_errors.append(exc)
210
+
211
+ if attempt < self.register_session_retries:
212
+ time.sleep(next(wait_times))
213
+
214
+ # Raise last exception to inform user about the connection issues.
215
+ # Note: Should we use ExceptionGroup to raise all exceptions?
216
+ raise retried_errors[-1]
217
+
218
+ @classmethod
219
+ def _strip_protocol(cls, path):
220
+ return infer_storage_options(path)["path"]
221
+
222
+ @staticmethod
223
+ def _get_kwargs_from_urls(path):
224
+ # smb://workgroup;user:password@host:port/share/folder/file.csv
225
+ out = infer_storage_options(path)
226
+ out.pop("path", None)
227
+ out.pop("protocol", None)
228
+ return out
229
+
230
+ def mkdir(self, path, create_parents=True, **kwargs):
231
+ wpath = _as_unc_path(self.host, path)
232
+ if create_parents:
233
+ smbclient.makedirs(wpath, exist_ok=False, port=self._port, **kwargs)
234
+ else:
235
+ smbclient.mkdir(wpath, port=self._port, **kwargs)
236
+
237
+ def makedirs(self, path, exist_ok=False):
238
+ if _share_has_path(path):
239
+ wpath = _as_unc_path(self.host, path)
240
+ smbclient.makedirs(wpath, exist_ok=exist_ok, port=self._port)
241
+
242
+ def rmdir(self, path):
243
+ if _share_has_path(path):
244
+ wpath = _as_unc_path(self.host, path)
245
+ smbclient.rmdir(wpath, port=self._port)
246
+
247
+ def info(self, path, **kwargs):
248
+ wpath = _as_unc_path(self.host, path)
249
+ stats = smbclient.stat(wpath, port=self._port, **kwargs)
250
+ if S_ISDIR(stats.st_mode):
251
+ stype = "directory"
252
+ elif S_ISLNK(stats.st_mode):
253
+ stype = "link"
254
+ else:
255
+ stype = "file"
256
+ res = {
257
+ "name": path + "/" if stype == "directory" else path,
258
+ "size": stats.st_size,
259
+ "type": stype,
260
+ "uid": stats.st_uid,
261
+ "gid": stats.st_gid,
262
+ "time": stats.st_atime,
263
+ "mtime": stats.st_mtime,
264
+ }
265
+ return res
266
+
267
+ def created(self, path):
268
+ """Return the created timestamp of a file as a datetime.datetime"""
269
+ wpath = _as_unc_path(self.host, path)
270
+ stats = smbclient.stat(wpath, port=self._port)
271
+ return datetime.datetime.fromtimestamp(stats.st_ctime, tz=datetime.timezone.utc)
272
+
273
+ def modified(self, path):
274
+ """Return the modified timestamp of a file as a datetime.datetime"""
275
+ wpath = _as_unc_path(self.host, path)
276
+ stats = smbclient.stat(wpath, port=self._port)
277
+ return datetime.datetime.fromtimestamp(stats.st_mtime, tz=datetime.timezone.utc)
278
+
279
+ def ls(self, path, detail=True, **kwargs):
280
+ unc = _as_unc_path(self.host, path)
281
+ listed = smbclient.listdir(unc, port=self._port, **kwargs)
282
+ dirs = ["/".join([path.rstrip("/"), p]) for p in listed]
283
+ if detail:
284
+ dirs = [self.info(d) for d in dirs]
285
+ return dirs
286
+
287
+ # pylint: disable=too-many-arguments
288
+ def _open(
289
+ self,
290
+ path,
291
+ mode="rb",
292
+ block_size=-1,
293
+ autocommit=True,
294
+ cache_options=None,
295
+ **kwargs,
296
+ ):
297
+ """
298
+ block_size: int or None
299
+ If 0, no buffering, 1, line buffering, >1, buffer that many bytes
300
+
301
+ Notes
302
+ -----
303
+ By specifying 'share_access' in 'kwargs' it is possible to override the
304
+ default shared access setting applied in the constructor of this object.
305
+ """
306
+ if self.auto_mkdir and "w" in mode:
307
+ self.makedirs(self._parent(path), exist_ok=True)
308
+ bls = block_size if block_size is not None and block_size >= 0 else -1
309
+ wpath = _as_unc_path(self.host, path)
310
+ share_access = kwargs.pop("share_access", self.share_access)
311
+ if "w" in mode and autocommit is False:
312
+ temp = _as_temp_path(self.host, path, self.temppath)
313
+ return SMBFileOpener(
314
+ wpath, temp, mode, port=self._port, block_size=bls, **kwargs
315
+ )
316
+ return smbclient.open_file(
317
+ wpath,
318
+ mode,
319
+ buffering=bls,
320
+ share_access=share_access,
321
+ port=self._port,
322
+ **kwargs,
323
+ )
324
+
325
+ def copy(self, path1, path2, **kwargs):
326
+ """Copy within two locations in the same filesystem"""
327
+ wpath1 = _as_unc_path(self.host, path1)
328
+ wpath2 = _as_unc_path(self.host, path2)
329
+ if self.auto_mkdir:
330
+ self.makedirs(self._parent(path2), exist_ok=True)
331
+ smbclient.copyfile(wpath1, wpath2, port=self._port, **kwargs)
332
+
333
+ def _rm(self, path):
334
+ if _share_has_path(path):
335
+ wpath = _as_unc_path(self.host, path)
336
+ stats = smbclient.stat(wpath, port=self._port)
337
+ if S_ISDIR(stats.st_mode):
338
+ smbclient.rmdir(wpath, port=self._port)
339
+ else:
340
+ smbclient.remove(wpath, port=self._port)
341
+
342
+ def mv(self, path1, path2, recursive=None, maxdepth=None, **kwargs):
343
+ wpath1 = _as_unc_path(self.host, path1)
344
+ wpath2 = _as_unc_path(self.host, path2)
345
+ smbclient.rename(wpath1, wpath2, port=self._port, **kwargs)
346
+
347
+
348
+ def _as_unc_path(host, path):
349
+ rpath = path.replace("/", "\\")
350
+ unc = f"\\\\{host}{rpath}"
351
+ return unc
352
+
353
+
354
+ def _as_temp_path(host, path, temppath):
355
+ share = path.split("/")[1]
356
+ temp_file = f"/{share}{temppath}/{uuid.uuid4()}"
357
+ unc = _as_unc_path(host, temp_file)
358
+ return unc
359
+
360
+
361
+ def _share_has_path(path):
362
+ parts = path.count("/")
363
+ if path.endswith("/"):
364
+ return parts > 2
365
+ return parts > 1
366
+
367
+
368
+ class SMBFileOpener:
369
+ """writes to remote temporary file, move on commit"""
370
+
371
+ def __init__(self, path, temp, mode, port=445, block_size=-1, **kwargs):
372
+ self.path = path
373
+ self.temp = temp
374
+ self.mode = mode
375
+ self.block_size = block_size
376
+ self.kwargs = kwargs
377
+ self.smbfile = None
378
+ self._incontext = False
379
+ self.port = port
380
+ self._open()
381
+
382
+ def _open(self):
383
+ if self.smbfile is None or self.smbfile.closed:
384
+ self.smbfile = smbclient.open_file(
385
+ self.temp,
386
+ self.mode,
387
+ port=self.port,
388
+ buffering=self.block_size,
389
+ **self.kwargs,
390
+ )
391
+
392
+ def commit(self):
393
+ """Move temp file to definitive on success."""
394
+ # TODO: use transaction support in SMB protocol
395
+ smbclient.replace(self.temp, self.path, port=self.port)
396
+
397
+ def discard(self):
398
+ """Remove the temp file on failure."""
399
+ smbclient.remove(self.temp, port=self.port)
400
+
401
+ def __fspath__(self):
402
+ return self.path
403
+
404
+ def __iter__(self):
405
+ return self.smbfile.__iter__()
406
+
407
+ def __getattr__(self, item):
408
+ return getattr(self.smbfile, item)
409
+
410
+ def __enter__(self):
411
+ self._incontext = True
412
+ return self.smbfile.__enter__()
413
+
414
+ def __exit__(self, exc_type, exc_value, traceback):
415
+ self._incontext = False
416
+ self.smbfile.__exit__(exc_type, exc_value, traceback)
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/tar.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import re
3
+ import tarfile
4
+
5
+ import fsspec
6
+ from fsspec.archive import AbstractArchiveFileSystem
7
+ from fsspec.compression import compr
8
+ from fsspec.utils import infer_compression
9
+
10
+ typemap = {b"0": "file", b"5": "directory"}
11
+
12
+ logger = logging.getLogger("tar")
13
+
14
+
15
+ class TarFileSystem(AbstractArchiveFileSystem):
16
+ """Compressed Tar archives as a file-system (read-only)
17
+
18
+ Supports the following formats:
19
+ tar.gz, tar.bz2, tar.xz
20
+ """
21
+
22
+ root_marker = ""
23
+ protocol = "tar"
24
+ cachable = False
25
+
26
+ def __init__(
27
+ self,
28
+ fo="",
29
+ index_store=None,
30
+ target_options=None,
31
+ target_protocol=None,
32
+ compression=None,
33
+ **kwargs,
34
+ ):
35
+ super().__init__(**kwargs)
36
+ target_options = target_options or {}
37
+
38
+ if isinstance(fo, str):
39
+ self.of = fsspec.open(fo, protocol=target_protocol, **target_options)
40
+ fo = self.of.open() # keep the reference
41
+
42
+ # Try to infer compression.
43
+ if compression is None:
44
+ name = None
45
+
46
+ # Try different ways to get hold of the filename. `fo` might either
47
+ # be a `fsspec.LocalFileOpener`, an `io.BufferedReader` or an
48
+ # `fsspec.AbstractFileSystem` instance.
49
+ try:
50
+ # Amended io.BufferedReader or similar.
51
+ # This uses a "protocol extension" where original filenames are
52
+ # propagated to archive-like filesystems in order to let them
53
+ # infer the right compression appropriately.
54
+ if hasattr(fo, "original"):
55
+ name = fo.original
56
+
57
+ # fsspec.LocalFileOpener
58
+ elif hasattr(fo, "path"):
59
+ name = fo.path
60
+
61
+ # io.BufferedReader
62
+ elif hasattr(fo, "name"):
63
+ name = fo.name
64
+
65
+ # fsspec.AbstractFileSystem
66
+ elif hasattr(fo, "info"):
67
+ name = fo.info()["name"]
68
+
69
+ except Exception as ex:
70
+ logger.warning(
71
+ f"Unable to determine file name, not inferring compression: {ex}"
72
+ )
73
+
74
+ if name is not None:
75
+ compression = infer_compression(name)
76
+ logger.info(f"Inferred compression {compression} from file name {name}")
77
+
78
+ if compression is not None:
79
+ # TODO: tarfile already implements compression with modes like "'r:gz'",
80
+ # but then would seek to offset in the file work?
81
+ fo = compr[compression](fo)
82
+
83
+ self._fo_ref = fo
84
+ self.fo = fo # the whole instance is a context
85
+ self.tar = tarfile.TarFile(fileobj=self.fo)
86
+ self.dir_cache = None
87
+
88
+ self.index_store = index_store
89
+ self.index = None
90
+ self._index()
91
+
92
+ def _index(self):
93
+ # TODO: load and set saved index, if exists
94
+ out = {}
95
+ for ti in self.tar:
96
+ info = ti.get_info()
97
+ info["type"] = typemap.get(info["type"], "file")
98
+ orig_name = info["name"].rstrip("/")
99
+ # Collapse duplicate slashes in the filesystem-facing name.
100
+ name = re.sub("/+", "/", orig_name)
101
+ info["name"] = name
102
+ out[name] = (info, ti.offset_data, orig_name)
103
+
104
+ self.index = out
105
+ # TODO: save index to self.index_store here, if set
106
+
107
+ def _get_dirs(self):
108
+ if self.dir_cache is not None:
109
+ return
110
+
111
+ # This enables ls to get directories as children as well as files
112
+ self.dir_cache = {
113
+ dirname: {"name": dirname, "size": 0, "type": "directory"}
114
+ for dirname in self._all_dirnames(self.index)
115
+ }
116
+ self.dir_cache.update(
117
+ {info["name"]: info for info, _, _ in self.index.values()}
118
+ )
119
+
120
+ def _open(self, path, mode="rb", **kwargs):
121
+ if mode != "rb":
122
+ raise ValueError("Read-only filesystem implementation")
123
+ # Accept paths containing the archive's duplicate slashes too.
124
+ path = re.sub("/+", "/", path)
125
+ details, _, orig_name = self.index[path]
126
+ if details["type"] != "file":
127
+ raise ValueError("Can only handle regular files")
128
+ return self.tar.extractfile(orig_name)
129
+
130
+ def close(self):
131
+ """Commits any write changes to the file. Done on ``del`` too."""
132
+ self.tar.close()
133
+
134
+ def __del__(self):
135
+ if hasattr(self, "tar"):
136
+ self.close()
137
+ del self.tar
138
+ if hasattr(self, "of") and hasattr(self.of, "__exit__"):
139
+ self.of.__exit__(None, None, None)
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/implementations/zip.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import zipfile
3
+
4
+ import fsspec
5
+ from fsspec.archive import AbstractArchiveFileSystem
6
+
7
+
8
+ class ZipFileSystem(AbstractArchiveFileSystem):
9
+ """Read/Write contents of ZIP archive as a file-system
10
+
11
+ Keeps file object open while instance lives.
12
+
13
+ This class is pickleable, but not necessarily thread-safe
14
+ """
15
+
16
+ root_marker = ""
17
+ protocol = "zip"
18
+ cachable = False
19
+
20
+ def __init__(
21
+ self,
22
+ fo="",
23
+ mode="r",
24
+ target_protocol=None,
25
+ target_options=None,
26
+ compression=zipfile.ZIP_STORED,
27
+ allowZip64=True,
28
+ compresslevel=None,
29
+ **kwargs,
30
+ ):
31
+ """
32
+ Parameters
33
+ ----------
34
+ fo: str or file-like
35
+ Contains ZIP, and must exist. If a str, will fetch file using
36
+ :meth:`~fsspec.open_files`, which must return one file exactly.
37
+ mode: str
38
+ Accept: "r", "w", "a"
39
+ target_protocol: str (optional)
40
+ If ``fo`` is a string, this value can be used to override the
41
+ FS protocol inferred from a URL
42
+ target_options: dict (optional)
43
+ Kwargs passed when instantiating the target FS, if ``fo`` is
44
+ a string.
45
+ compression, allowZip64, compresslevel: passed to ZipFile
46
+ Only relevant when creating a ZIP
47
+ """
48
+ super().__init__(self, **kwargs)
49
+ if mode not in set("rwa"):
50
+ raise ValueError(f"mode '{mode}' no understood")
51
+ self.mode = mode
52
+ if isinstance(fo, (str, os.PathLike)):
53
+ if mode == "a":
54
+ m = "r+b"
55
+ else:
56
+ m = mode + "b"
57
+ fo = fsspec.open(
58
+ fo, mode=m, protocol=target_protocol, **(target_options or {})
59
+ )
60
+ self.force_zip_64 = allowZip64
61
+ self.of = fo
62
+ self.fo = fo.__enter__() # the whole instance is a context
63
+ self.zip = zipfile.ZipFile(
64
+ self.fo,
65
+ mode=mode,
66
+ compression=compression,
67
+ allowZip64=allowZip64,
68
+ compresslevel=compresslevel,
69
+ )
70
+ self.dir_cache = None
71
+
72
+ @classmethod
73
+ def _strip_protocol(cls, path):
74
+ # zip file paths are always relative to the archive root
75
+ return super()._strip_protocol(path).lstrip("/")
76
+
77
+ def __del__(self):
78
+ if hasattr(self, "zip"):
79
+ self.close()
80
+ del self.zip
81
+ if hasattr(self, "of") and hasattr(self.of, "__exit__"):
82
+ self.of.__exit__(None, None, None)
83
+
84
+ def close(self):
85
+ """Commits any write changes to the file. Done on ``del`` too."""
86
+ self.zip.close()
87
+
88
+ def _get_dirs(self):
89
+ if self.dir_cache is None or self.mode in set("wa"):
90
+ # when writing, dir_cache is always in the ZipFile's attributes,
91
+ # not read from the file.
92
+ files = self.zip.infolist()
93
+ self.dir_cache = {
94
+ dirname.rstrip("/"): {
95
+ "name": dirname.rstrip("/"),
96
+ "size": 0,
97
+ "type": "directory",
98
+ }
99
+ for dirname in self._all_dirnames(self.zip.namelist())
100
+ }
101
+ for z in files:
102
+ f = {s: getattr(z, s, None) for s in zipfile.ZipInfo.__slots__}
103
+ f.update(
104
+ {
105
+ "name": z.filename.rstrip("/"),
106
+ "size": z.file_size,
107
+ "type": ("directory" if z.is_dir() else "file"),
108
+ }
109
+ )
110
+ self.dir_cache[f["name"]] = f
111
+
112
+ def pipe_file(self, path, value, **kwargs):
113
+ # override upstream, because we know the exact file size in this case
114
+ self.zip.writestr(path, value, **kwargs)
115
+
116
+ def _open(
117
+ self,
118
+ path,
119
+ mode="rb",
120
+ block_size=None,
121
+ autocommit=True,
122
+ cache_options=None,
123
+ **kwargs,
124
+ ):
125
+ path = self._strip_protocol(path)
126
+ if "r" in mode and self.mode in set("wa"):
127
+ if self.exists(path):
128
+ raise OSError("ZipFS can only be open for reading or writing, not both")
129
+ raise FileNotFoundError(path)
130
+ if "r" in self.mode and "w" in mode:
131
+ raise OSError("ZipFS can only be open for reading or writing, not both")
132
+ out = self.zip.open(path, mode.strip("b"), force_zip64=self.force_zip_64)
133
+ if "r" in mode:
134
+ info = self.info(path)
135
+ out.size = info["size"]
136
+ out.name = info["name"]
137
+ return out
138
+
139
+ def find(self, path, maxdepth=None, withdirs=False, detail=False, **kwargs):
140
+ if maxdepth is not None and maxdepth < 1:
141
+ raise ValueError("maxdepth must be at least 1")
142
+
143
+ def to_parts(_path: str):
144
+ return list(filter(None, _path.replace("\\", "/").split("/")))
145
+
146
+ if not isinstance(path, str):
147
+ path = str(path)
148
+
149
+ # Remove the leading slash, as the zip file paths are always
150
+ # given without a leading slash
151
+ path = path.lstrip("/")
152
+ path_parts = to_parts(path)
153
+ path_depth = len(path_parts)
154
+
155
+ self._get_dirs()
156
+
157
+ result = {}
158
+ # To match posix find, if an exact file name is given, we should
159
+ # return only that file
160
+ if path in self.dir_cache and self.dir_cache[path]["type"] == "file":
161
+ result[path] = self.dir_cache[path]
162
+ return result if detail else [path]
163
+
164
+ for file_path, file_info in self.dir_cache.items():
165
+ if len(file_parts := to_parts(file_path)) < path_depth or any(
166
+ a != b for a, b in zip(path_parts, file_parts)
167
+ ):
168
+ # skip parent folders and mismatching paths
169
+ continue
170
+
171
+ if file_info["type"] == "directory":
172
+ if withdirs and file_path not in result:
173
+ result[file_path.strip("/")] = file_info
174
+ continue
175
+
176
+ if file_path not in result:
177
+ result[file_path] = file_info if detail else None
178
+
179
+ if maxdepth:
180
+ result = {
181
+ k: v for k, v in result.items() if k.count("/") < maxdepth + path_depth
182
+ }
183
+ return result if detail else sorted(result)
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/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
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/mapping.py ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/parquet.py ADDED
@@ -0,0 +1,572 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/spec.py ADDED
@@ -0,0 +1,2342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ FORK_AVAILABLE = hasattr(os, "register_at_fork")
37
+
38
+
39
+ if FORK_AVAILABLE:
40
+ _registered_classes = weakref.WeakSet()
41
+
42
+ def _reset_instances_lock():
43
+ for cls in _registered_classes:
44
+ cls._instantiation_lock = threading.RLock()
45
+ cls._cache.clear()
46
+ cls._pid = os.getpid()
47
+
48
+ os.register_at_fork(after_in_child=_reset_instances_lock)
49
+
50
+
51
+ class _Cached(type):
52
+ """
53
+ Metaclass for caching file system instances.
54
+
55
+ Notes
56
+ -----
57
+ Instances are cached according to
58
+
59
+ * The values of the class attributes listed in `_extra_tokenize_attributes`
60
+ * The arguments passed to ``__init__``.
61
+
62
+ This creates an additional reference to the filesystem, which prevents the
63
+ filesystem from being garbage collected when all *user* references go away.
64
+ A call to the :meth:`AbstractFileSystem.clear_instance_cache` must *also*
65
+ be made for a filesystem instance to be garbage collected.
66
+ """
67
+
68
+ def __init__(cls, *args, **kwargs):
69
+ super().__init__(*args, **kwargs)
70
+
71
+ # Note: we intentionally create a reference here, to avoid garbage
72
+ # collecting instances when all other references are gone. To really
73
+ # delete a FileSystem, the cache must be cleared.
74
+ if conf.get("weakref_instance_cache"): # pragma: no cover
75
+ # debug option for analysing fork/spawn conditions
76
+ cls._cache = weakref.WeakValueDictionary()
77
+ else:
78
+ cls._cache = {}
79
+ cls._pid = os.getpid()
80
+ cls._instantiation_lock = threading.RLock()
81
+
82
+ if FORK_AVAILABLE:
83
+ _registered_classes.add(cls)
84
+
85
+ def _check_instance_cache(cls, token):
86
+ inst = cls._cache.get(token)
87
+ if inst is not None:
88
+ cls._latest = token
89
+ return inst
90
+
91
+ def __call__(cls, *args, **kwargs):
92
+ kwargs = apply_config(cls, kwargs)
93
+ extra_tokens = tuple(
94
+ getattr(cls, attr, None) for attr in cls._extra_tokenize_attributes
95
+ )
96
+ strip_tokenize_options = {
97
+ k: kwargs.pop(k) for k in cls._strip_tokenize_options if k in kwargs
98
+ }
99
+ pid = os.getpid()
100
+
101
+ if getattr(cls, "async_impl", False) and not kwargs.get("asynchronous", False):
102
+ token = tokenize(cls, pid, *args, *extra_tokens, **kwargs)
103
+ else:
104
+ token = tokenize(
105
+ cls, pid, threading.get_ident(), *args, *extra_tokens, **kwargs
106
+ )
107
+ skip = kwargs.pop("skip_instance_cache", False)
108
+
109
+ if pid != cls._pid:
110
+ with cls._instantiation_lock:
111
+ if pid != cls._pid:
112
+ cls._cache.clear()
113
+ cls._pid = pid
114
+
115
+ if not skip and cls.cachable:
116
+ inst = cls._check_instance_cache(token)
117
+ if inst is not None:
118
+ return inst
119
+
120
+ with cls._instantiation_lock:
121
+ # protect against the race condition that a new instance was created
122
+ # and inserted into the cache since the initial check just above
123
+ inst = cls._check_instance_cache(token)
124
+ if inst is not None:
125
+ return inst
126
+
127
+ obj = super().__call__(*args, **kwargs, **strip_tokenize_options)
128
+ # Setting _fs_token here causes some static linters to complain.
129
+ obj._fs_token_ = token
130
+ obj.storage_args = args
131
+ obj.storage_options = kwargs
132
+ if obj.async_impl and obj.mirror_sync_methods:
133
+ from .asyn import mirror_sync_methods
134
+
135
+ mirror_sync_methods(obj)
136
+
137
+ if cls.cachable and not skip:
138
+ with cls._instantiation_lock:
139
+ # another thread may have created the instance while we were calling
140
+ # super().__call__(), so we check again.
141
+ inst = cls._check_instance_cache(token)
142
+ if inst is not None:
143
+ return inst
144
+
145
+ cls._latest = token
146
+ cls._cache[token] = obj
147
+ return obj
148
+
149
+
150
+ class AbstractFileSystem(metaclass=_Cached):
151
+ """
152
+ An abstract super-class for pythonic file-systems
153
+
154
+ Implementations are expected to be compatible with or, better, subclass
155
+ from here.
156
+ """
157
+
158
+ cachable = True # this class can be cached, instances reused
159
+ _cached = False
160
+ blocksize = 2**22
161
+ sep = "/"
162
+ protocol: ClassVar[str | tuple[str, ...]] = "abstract"
163
+ _latest = None
164
+ async_impl = False
165
+ mirror_sync_methods = False
166
+ root_marker = "" # For some FSs, may require leading '/' or other character
167
+ transaction_type = Transaction
168
+
169
+ #: Extra *class attributes* that should be considered when hashing.
170
+ _extra_tokenize_attributes = ()
171
+ #: *storage options* that should not be considered when hashing.
172
+ _strip_tokenize_options = ()
173
+
174
+ # Set by _Cached metaclass
175
+ storage_args: tuple[Any, ...]
176
+ storage_options: dict[str, Any]
177
+
178
+ def __init__(self, *args, **storage_options):
179
+ """Create and configure file-system instance
180
+
181
+ Instances may be cachable, so if similar enough arguments are seen
182
+ a new instance is not required. The token attribute exists to allow
183
+ implementations to cache instances if they wish.
184
+
185
+ A reasonable default should be provided if there are no arguments.
186
+
187
+ Subclasses should call this method.
188
+
189
+ Parameters
190
+ ----------
191
+ use_listings_cache, listings_expiry_time, max_paths:
192
+ passed to ``DirCache``, if the implementation supports
193
+ directory listing caching. Pass use_listings_cache=False
194
+ to disable such caching.
195
+ skip_instance_cache: bool
196
+ If this is a cachable implementation, pass True here to force
197
+ creating a new instance even if a matching instance exists, and prevent
198
+ storing this instance.
199
+ asynchronous: bool
200
+ loop: asyncio-compatible IOLoop or None
201
+ """
202
+ if self._cached:
203
+ # reusing instance, don't change
204
+ return
205
+ self._cached = True
206
+ self._intrans = False
207
+ self._transaction = None
208
+ self._invalidated_caches_in_transaction = []
209
+ self.dircache = DirCache(**storage_options)
210
+
211
+ if storage_options.pop("add_docs", None):
212
+ warnings.warn("add_docs is no longer supported.", FutureWarning)
213
+
214
+ if storage_options.pop("add_aliases", None):
215
+ warnings.warn("add_aliases has been removed.", FutureWarning)
216
+ # This is set in _Cached
217
+ self._fs_token_ = None
218
+
219
+ @property
220
+ def fsid(self):
221
+ """Persistent filesystem id that can be used to compare filesystems
222
+ across sessions.
223
+ """
224
+ raise NotImplementedError
225
+
226
+ @property
227
+ def _fs_token(self):
228
+ return self._fs_token_
229
+
230
+ def __dask_tokenize__(self):
231
+ return self._fs_token
232
+
233
+ def __hash__(self):
234
+ return int(self._fs_token, 16)
235
+
236
+ def __eq__(self, other):
237
+ return isinstance(other, type(self)) and self._fs_token == other._fs_token
238
+
239
+ def __reduce__(self):
240
+ return make_instance, (type(self), self.storage_args, self.storage_options)
241
+
242
+ @classmethod
243
+ def _strip_protocol(cls, path):
244
+ """Turn path from fully-qualified to file-system-specific
245
+
246
+ May require FS-specific handling, e.g., for relative paths or links.
247
+ """
248
+ if isinstance(path, list):
249
+ return [cls._strip_protocol(p) for p in path]
250
+ path = stringify_path(path)
251
+ protos = (cls.protocol,) if isinstance(cls.protocol, str) else cls.protocol
252
+ for protocol in protos:
253
+ if path.startswith(protocol + "://"):
254
+ path = path[len(protocol) + 3 :]
255
+ elif path.startswith(protocol + "::"):
256
+ path = path[len(protocol) + 2 :]
257
+ path = path.rstrip("/")
258
+ # use of root_marker to make minimum required path, e.g., "/"
259
+ return path or cls.root_marker
260
+
261
+ def unstrip_protocol(self, name: str) -> str:
262
+ """Format FS-specific path to generic, including protocol"""
263
+ protos = (self.protocol,) if isinstance(self.protocol, str) else self.protocol
264
+ for protocol in protos:
265
+ if name.startswith(f"{protocol}://"):
266
+ return name
267
+ return f"{protos[0]}://{name}"
268
+
269
+ @staticmethod
270
+ def _get_kwargs_from_urls(path):
271
+ """If kwargs can be encoded in the paths, extract them here
272
+
273
+ This should happen before instantiation of the class; incoming paths
274
+ then should be amended to strip the options in methods.
275
+
276
+ Examples may look like an sftp path "sftp://user@host:/my/path", where
277
+ the user and host should become kwargs and later get stripped.
278
+ """
279
+ # by default, nothing happens
280
+ return {}
281
+
282
+ @classmethod
283
+ def current(cls):
284
+ """Return the most recently instantiated FileSystem
285
+
286
+ If no instance has been created, then create one with defaults
287
+ """
288
+ inst = cls._cache.get(cls._latest)
289
+ if inst is not None:
290
+ return inst
291
+ return cls()
292
+
293
+ @property
294
+ def transaction(self):
295
+ """A context within which files are committed together upon exit
296
+
297
+ Requires the file class to implement `.commit()` and `.discard()`
298
+ for the normal and exception cases.
299
+ """
300
+ if self._transaction is None:
301
+ self._transaction = self.transaction_type(self)
302
+ return self._transaction
303
+
304
+ def start_transaction(self):
305
+ """Begin write transaction for deferring files, non-context version"""
306
+ self._intrans = True
307
+ self._transaction = self.transaction_type(self)
308
+ return self.transaction
309
+
310
+ def end_transaction(self):
311
+ """Finish write transaction, non-context version"""
312
+ self.transaction.complete()
313
+ self._transaction = None
314
+ # The invalid cache must be cleared after the transaction is completed.
315
+ for path in self._invalidated_caches_in_transaction:
316
+ self.invalidate_cache(path)
317
+ self._invalidated_caches_in_transaction.clear()
318
+
319
+ def invalidate_cache(self, path=None):
320
+ """
321
+ Discard any cached directory information
322
+
323
+ Parameters
324
+ ----------
325
+ path: string or None
326
+ If None, clear all listings cached else listings at or under given
327
+ path.
328
+ """
329
+ # Not necessary to implement invalidation mechanism, may have no cache.
330
+ # But if have, you should call this method of parent class from your
331
+ # subclass to ensure expiring caches after transacations correctly.
332
+ # See the implementation of FTPFileSystem in ftp.py
333
+ if self._intrans:
334
+ self._invalidated_caches_in_transaction.append(path)
335
+
336
+ def mkdir(self, path, create_parents=True, **kwargs):
337
+ """
338
+ Create directory entry at path
339
+
340
+ For systems that don't have true directories, may create an for
341
+ this instance only and not touch the real filesystem
342
+
343
+ Parameters
344
+ ----------
345
+ path: str
346
+ location
347
+ create_parents: bool
348
+ if True, this is equivalent to ``makedirs``
349
+ kwargs:
350
+ may be permissions, etc.
351
+ """
352
+ pass # not necessary to implement, may not have directories
353
+
354
+ def makedirs(self, path, exist_ok=False):
355
+ """Recursively make directories
356
+
357
+ Creates directory at path and any intervening required directories.
358
+ Raises exception if, for instance, the path already exists but is a
359
+ file.
360
+
361
+ Parameters
362
+ ----------
363
+ path: str
364
+ leaf directory name
365
+ exist_ok: bool (False)
366
+ If False, will error if the target already exists
367
+ """
368
+ pass # not necessary to implement, may not have directories
369
+
370
+ def rmdir(self, path):
371
+ """Remove a directory, if empty"""
372
+ pass # not necessary to implement, may not have directories
373
+
374
+ def ls(self, path, detail=True, **kwargs):
375
+ """List objects at path.
376
+
377
+ This should include subdirectories and files at that location. The
378
+ difference between a file and a directory must be clear when details
379
+ are requested.
380
+
381
+ The specific keys, or perhaps a FileInfo class, or similar, is TBD,
382
+ but must be consistent across implementations.
383
+ Must include:
384
+
385
+ - full path to the entry (without protocol)
386
+ - size of the entry, in bytes. If the value cannot be determined, will
387
+ be ``None``.
388
+ - type of entry, "file", "directory" or other
389
+
390
+ Additional information
391
+ may be present, appropriate to the file-system, e.g., generation,
392
+ checksum, etc.
393
+
394
+ May use refresh=True|False to allow use of self._ls_from_cache to
395
+ check for a saved listing and avoid calling the backend. This would be
396
+ common where listing may be expensive.
397
+
398
+ Parameters
399
+ ----------
400
+ path: str
401
+ detail: bool
402
+ if True, gives a list of dictionaries, where each is the same as
403
+ the result of ``info(path)``. If False, gives a list of paths
404
+ (str).
405
+ kwargs: may have additional backend-specific options, such as version
406
+ information
407
+
408
+ Returns
409
+ -------
410
+ List of strings if detail is False, or list of directory information
411
+ dicts if detail is True.
412
+ """
413
+ raise NotImplementedError
414
+
415
+ def _ls_from_cache(self, path):
416
+ """Check cache for listing
417
+
418
+ Returns listing, if found (may be empty list for a directly that exists
419
+ but contains nothing), None if not in cache.
420
+ """
421
+ parent = self._parent(path)
422
+ try:
423
+ return self.dircache[path.rstrip("/")]
424
+ except KeyError:
425
+ pass
426
+ try:
427
+ files = [
428
+ f
429
+ for f in self.dircache[parent]
430
+ if f["name"] == path
431
+ or (f["name"] == path.rstrip("/") and f["type"] == "directory")
432
+ ]
433
+ if len(files) == 0:
434
+ # parent dir was listed but did not contain this file
435
+ raise FileNotFoundError(path)
436
+ return files
437
+ except KeyError:
438
+ pass
439
+
440
+ def walk(self, path, maxdepth=None, topdown=True, on_error="omit", **kwargs):
441
+ """Return all files under the given path.
442
+
443
+ List all files, recursing into subdirectories; output is iterator-style,
444
+ like ``os.walk()``. For a simple list of files, ``find()`` is available.
445
+
446
+ When topdown is True, the caller can modify the dirnames list in-place (perhaps
447
+ using del or slice assignment), and walk() will
448
+ only recurse into the subdirectories whose names remain in dirnames;
449
+ this can be used to prune the search, impose a specific order of visiting,
450
+ or even to inform walk() about directories the caller creates or renames before
451
+ it resumes walk() again.
452
+ Modifying dirnames when topdown is False has no effect. (see os.walk)
453
+
454
+ Note that the "files" outputted will include anything that is not
455
+ a directory, such as links.
456
+
457
+ Parameters
458
+ ----------
459
+ path: str
460
+ Root to recurse into
461
+ maxdepth: int
462
+ Maximum recursion depth. None means limitless, but not recommended
463
+ on link-based file-systems.
464
+ topdown: bool (True)
465
+ Whether to walk the directory tree from the top downwards or from
466
+ the bottom upwards.
467
+ on_error: "omit", "raise", a callable
468
+ if omit (default), path with exception will simply be empty;
469
+ If raise, an underlying exception will be raised;
470
+ if callable, it will be called with a single OSError instance as argument
471
+ kwargs: passed to ``ls``
472
+ """
473
+ if maxdepth is not None and maxdepth < 1:
474
+ raise ValueError("maxdepth must be at least 1")
475
+
476
+ path = self._strip_protocol(path)
477
+ full_dirs = {}
478
+ dirs = {}
479
+ files = {}
480
+
481
+ detail = kwargs.pop("detail", False)
482
+ try:
483
+ listing = self.ls(path, detail=True, **kwargs)
484
+ except (FileNotFoundError, OSError) as e:
485
+ if on_error == "raise":
486
+ raise
487
+ if callable(on_error):
488
+ on_error(e)
489
+ return
490
+
491
+ for info in listing:
492
+ # each info name must be at least [path]/part , but here
493
+ # we check also for names like [path]/part/
494
+ pathname = info["name"].rstrip("/")
495
+ name = pathname.rsplit("/", 1)[-1]
496
+ if info["type"] == "directory" and pathname != path:
497
+ # do not include "self" path
498
+ full_dirs[name] = pathname
499
+ dirs[name] = info
500
+ elif pathname == path:
501
+ # file-like with same name as give path
502
+ files[""] = info
503
+ else:
504
+ files[name] = info
505
+
506
+ if not detail:
507
+ dirs = list(dirs)
508
+ files = list(files)
509
+
510
+ if topdown:
511
+ # Yield before recursion if walking top down
512
+ yield path, dirs, files
513
+
514
+ if maxdepth is not None:
515
+ maxdepth -= 1
516
+ if maxdepth < 1:
517
+ if not topdown:
518
+ yield path, dirs, files
519
+ return
520
+
521
+ for d in dirs:
522
+ yield from self.walk(
523
+ full_dirs[d],
524
+ maxdepth=maxdepth,
525
+ detail=detail,
526
+ topdown=topdown,
527
+ **kwargs,
528
+ )
529
+
530
+ if not topdown:
531
+ # Yield after recursion if walking bottom up
532
+ yield path, dirs, files
533
+
534
+ def find(self, path, maxdepth=None, withdirs=False, detail=False, **kwargs):
535
+ """List all files below path.
536
+
537
+ Like posix ``find`` command without conditions
538
+
539
+ Parameters
540
+ ----------
541
+ path : str
542
+ maxdepth: int or None
543
+ If not None, the maximum number of levels to descend
544
+ withdirs: bool
545
+ Whether to include directory paths in the output. This is True
546
+ when used by glob, but users usually only want files.
547
+ kwargs are passed to ``ls``.
548
+ """
549
+ # TODO: allow equivalent of -name parameter
550
+ path = self._strip_protocol(path)
551
+ out = {}
552
+
553
+ # Add the root directory if withdirs is requested
554
+ # This is needed for posix glob compliance
555
+ if withdirs and path != "" and self.isdir(path):
556
+ out[path] = self.info(path)
557
+
558
+ for _, dirs, files in self.walk(path, maxdepth, detail=True, **kwargs):
559
+ if withdirs:
560
+ files.update(dirs)
561
+ out.update({info["name"]: info for name, info in files.items()})
562
+ if not out and self.isfile(path):
563
+ # walk works on directories, but find should also return [path]
564
+ # when path happens to be a file
565
+ out[path] = {}
566
+ names = sorted(out)
567
+ if not detail:
568
+ return names
569
+ else:
570
+ return {name: out[name] for name in names}
571
+
572
+ def du(self, path, total=True, maxdepth=None, withdirs=False, **kwargs):
573
+ """Space used by files and optionally directories within a path
574
+
575
+ Directory size does not include the size of its contents.
576
+
577
+ Parameters
578
+ ----------
579
+ path: str
580
+ total: bool
581
+ Whether to sum all the file sizes
582
+ maxdepth: int or None
583
+ Maximum number of directory levels to descend, None for unlimited.
584
+ withdirs: bool
585
+ Whether to include directory paths in the output.
586
+ kwargs: passed to ``find``
587
+
588
+ Returns
589
+ -------
590
+ Dict of {path: size} if total=False, or int otherwise, where numbers
591
+ refer to bytes used.
592
+ """
593
+ sizes = {}
594
+ if withdirs and self.isdir(path):
595
+ # Include top-level directory in output
596
+ info = self.info(path)
597
+ sizes[info["name"]] = info["size"]
598
+ for f in self.find(path, maxdepth=maxdepth, withdirs=withdirs, **kwargs):
599
+ info = self.info(f)
600
+ sizes[info["name"]] = info["size"]
601
+ if total:
602
+ return sum(sizes.values())
603
+ else:
604
+ return sizes
605
+
606
+ def glob(self, path, maxdepth=None, **kwargs):
607
+ """Find files by glob-matching.
608
+
609
+ Pattern matching capabilities for finding files that match the given pattern.
610
+
611
+ Parameters
612
+ ----------
613
+ path: str
614
+ The glob pattern to match against
615
+ maxdepth: int or None
616
+ Maximum depth for ``'**'`` patterns. Applied on the first ``'**'`` found.
617
+ Must be at least 1 if provided.
618
+ kwargs:
619
+ Additional arguments passed to ``find`` (e.g., detail=True)
620
+
621
+ Returns
622
+ -------
623
+ List of matched paths, or dict of paths and their info if detail=True
624
+
625
+ Notes
626
+ -----
627
+ Supported patterns:
628
+ - '*': Matches any sequence of characters within a single directory level
629
+ - ``'**'``: Matches any number of directory levels (must be an entire path component)
630
+ - '?': Matches exactly one character
631
+ - '[abc]': Matches any character in the set
632
+ - '[a-z]': Matches any character in the range
633
+ - '[!abc]': Matches any character NOT in the set
634
+
635
+ Special behaviors:
636
+ - If the path ends with '/', only folders are returned
637
+ - Consecutive '*' characters are compressed into a single '*'
638
+ - Empty set '[]' or negated empty negated set '[!]' never match anything
639
+ - Special characters in character classes are escaped properly
640
+
641
+ Limitations:
642
+ - ``'**'`` must be a complete path component (e.g., ``'a/**/b'``, not ``'a**b'``)
643
+ - No brace expansion ('{a,b}.txt')
644
+ - No extended glob patterns ('+(pattern)', '!(pattern)')
645
+ """
646
+ if maxdepth is not None and maxdepth < 1:
647
+ raise ValueError("maxdepth must be at least 1")
648
+
649
+ import re
650
+
651
+ seps = (os.path.sep, os.path.altsep) if os.path.altsep else (os.path.sep,)
652
+ ends_with_sep = path.endswith(seps) # _strip_protocol strips trailing slash
653
+ path = self._strip_protocol(path)
654
+ append_slash_to_dirname = ends_with_sep or path.endswith(
655
+ tuple(sep + "**" for sep in seps)
656
+ )
657
+ idx_star = path.find("*") if path.find("*") >= 0 else len(path)
658
+ idx_qmark = path.find("?") if path.find("?") >= 0 else len(path)
659
+ idx_brace = path.find("[") if path.find("[") >= 0 else len(path)
660
+
661
+ min_idx = min(idx_star, idx_qmark, idx_brace)
662
+
663
+ detail = kwargs.pop("detail", False)
664
+ withdirs = kwargs.pop("withdirs", True)
665
+
666
+ if not has_magic(path):
667
+ if self.exists(path, **kwargs):
668
+ if not detail:
669
+ return [path]
670
+ else:
671
+ return {path: self.info(path, **kwargs)}
672
+ else:
673
+ if not detail:
674
+ return [] # glob of non-existent returns empty
675
+ else:
676
+ return {}
677
+ elif "/" in path[:min_idx]:
678
+ min_idx = path[:min_idx].rindex("/")
679
+ root = path[: min_idx + 1]
680
+ depth = path[min_idx + 1 :].count("/") + 1
681
+ else:
682
+ root = ""
683
+ depth = path[min_idx + 1 :].count("/") + 1
684
+
685
+ if "**" in path:
686
+ if maxdepth is not None:
687
+ idx_double_stars = path.find("**")
688
+ depth_double_stars = path[idx_double_stars:].count("/") + 1
689
+ depth = depth - depth_double_stars + maxdepth
690
+ else:
691
+ depth = None
692
+
693
+ allpaths = self.find(
694
+ root, maxdepth=depth, withdirs=withdirs, detail=True, **kwargs
695
+ )
696
+
697
+ pattern = glob_translate(path + ("/" if ends_with_sep else ""))
698
+ pattern = re.compile(pattern)
699
+
700
+ out = {
701
+ p: info
702
+ for p, info in sorted(allpaths.items())
703
+ if pattern.match(
704
+ p + "/"
705
+ if append_slash_to_dirname and info["type"] == "directory"
706
+ else p
707
+ )
708
+ }
709
+
710
+ if detail:
711
+ return out
712
+ else:
713
+ return list(out)
714
+
715
+ def exists(self, path, **kwargs):
716
+ """Is there a file at the given path"""
717
+ try:
718
+ self.info(path, **kwargs)
719
+ return True
720
+ except: # noqa: E722
721
+ # any exception allowed bar FileNotFoundError?
722
+ return False
723
+
724
+ def lexists(self, path, **kwargs):
725
+ """If there is a file at the given path (including
726
+ broken links)"""
727
+ return self.exists(path)
728
+
729
+ def info(self, path, **kwargs):
730
+ """Give details of entry at path
731
+
732
+ Returns a single dictionary, with exactly the same information as ``ls``
733
+ would with ``detail=True``.
734
+
735
+ The default implementation calls ls and could be overridden by a
736
+ shortcut. kwargs are passed on to ```ls()``.
737
+
738
+ Some file systems might not be able to measure the file's size, in
739
+ which case, the returned dict will include ``'size': None``.
740
+
741
+ Returns
742
+ -------
743
+ dict with keys: name (full path in the FS), size (in bytes), type (file,
744
+ directory, or something else) and other FS-specific keys.
745
+ """
746
+ path = self._strip_protocol(path)
747
+ out = self.ls(self._parent(path), detail=True, **kwargs)
748
+ out = [o for o in out if o["name"].rstrip("/") == path]
749
+ if out:
750
+ return out[0]
751
+ out = self.ls(path, detail=True, **kwargs)
752
+ path = path.rstrip("/")
753
+ out1 = [o for o in out if o["name"].rstrip("/") == path]
754
+ if len(out1) == 1:
755
+ if "size" not in out1[0]:
756
+ out1[0]["size"] = None
757
+ return out1[0]
758
+ elif len(out1) > 1 or out:
759
+ return {"name": path, "size": 0, "type": "directory"}
760
+ else:
761
+ raise FileNotFoundError(path)
762
+
763
+ def checksum(self, path):
764
+ """Unique value for current version of file
765
+
766
+ If the checksum is the same from one moment to another, the contents
767
+ are guaranteed to be the same. If the checksum changes, the contents
768
+ *might* have changed.
769
+
770
+ This should normally be overridden; default will probably capture
771
+ creation/modification timestamp (which would be good) or maybe
772
+ access timestamp (which would be bad)
773
+ """
774
+ return int(tokenize(self.info(path)), 16)
775
+
776
+ def size(self, path):
777
+ """Size in bytes of file"""
778
+ return self.info(path).get("size", None)
779
+
780
+ def sizes(self, paths):
781
+ """Size in bytes of each file in a list of paths"""
782
+ return [self.size(p) for p in paths]
783
+
784
+ def isdir(self, path):
785
+ """Is this entry directory-like?"""
786
+ try:
787
+ return self.info(path)["type"] == "directory"
788
+ except OSError:
789
+ return False
790
+
791
+ def isfile(self, path):
792
+ """Is this entry file-like?"""
793
+ try:
794
+ return self.info(path)["type"] == "file"
795
+ except: # noqa: E722
796
+ return False
797
+
798
+ def read_text(self, path, encoding=None, errors=None, newline=None, **kwargs):
799
+ """Get the contents of the file as a string.
800
+
801
+ Parameters
802
+ ----------
803
+ path: str
804
+ URL of file on this filesystems
805
+ encoding, errors, newline: same as `open`.
806
+ """
807
+ with self.open(
808
+ path,
809
+ mode="r",
810
+ encoding=encoding,
811
+ errors=errors,
812
+ newline=newline,
813
+ **kwargs,
814
+ ) as f:
815
+ return f.read()
816
+
817
+ def write_text(
818
+ self, path, value, encoding=None, errors=None, newline=None, **kwargs
819
+ ):
820
+ """Write the text to the given file.
821
+
822
+ An existing file will be overwritten.
823
+
824
+ Parameters
825
+ ----------
826
+ path: str
827
+ URL of file on this filesystems
828
+ value: str
829
+ Text to write.
830
+ encoding, errors, newline: same as `open`.
831
+ """
832
+ with self.open(
833
+ path,
834
+ mode="w",
835
+ encoding=encoding,
836
+ errors=errors,
837
+ newline=newline,
838
+ **kwargs,
839
+ ) as f:
840
+ return f.write(value)
841
+
842
+ def cat_file(self, path, start=None, end=None, **kwargs):
843
+ """Get the content of a file
844
+
845
+ Parameters
846
+ ----------
847
+ path: URL of file on this filesystems
848
+ start, end: int
849
+ Bytes limits of the read. If negative, backwards from end,
850
+ like usual python slices. Either can be None for start or
851
+ end of file, respectively
852
+ kwargs: passed to ``open()``.
853
+ """
854
+ # explicitly set buffering off?
855
+ with self.open(path, "rb", **kwargs) as f:
856
+ if start is not None:
857
+ if start >= 0:
858
+ f.seek(start)
859
+ else:
860
+ f.seek(max(0, f.size + start))
861
+ if end is not None:
862
+ if end < 0:
863
+ end = f.size + end
864
+ return f.read(end - f.tell())
865
+ return f.read()
866
+
867
+ def pipe_file(self, path, value, mode="overwrite", **kwargs):
868
+ """Set the bytes of given file"""
869
+ if mode == "create" and self.exists(path):
870
+ # non-atomic but simple way; or could use "xb" in open(), which is likely
871
+ # not as well supported
872
+ raise FileExistsError
873
+ with self.open(path, "wb", **kwargs) as f:
874
+ f.write(value)
875
+
876
+ def pipe(self, path, value=None, **kwargs):
877
+ """Put value into path
878
+
879
+ (counterpart to ``cat``)
880
+
881
+ Parameters
882
+ ----------
883
+ path: string or dict(str, bytes)
884
+ If a string, a single remote location to put ``value`` bytes; if a dict,
885
+ a mapping of {path: bytesvalue}.
886
+ value: bytes, optional
887
+ If using a single path, these are the bytes to put there. Ignored if
888
+ ``path`` is a dict
889
+ """
890
+ if isinstance(path, str):
891
+ self.pipe_file(self._strip_protocol(path), value, **kwargs)
892
+ elif isinstance(path, dict):
893
+ for k, v in path.items():
894
+ self.pipe_file(self._strip_protocol(k), v, **kwargs)
895
+ else:
896
+ raise ValueError("path must be str or dict")
897
+
898
+ def cat_ranges(
899
+ self, paths, starts, ends, max_gap=None, on_error="return", **kwargs
900
+ ):
901
+ """Get the contents of byte ranges from one or more files
902
+
903
+ Parameters
904
+ ----------
905
+ paths: list
906
+ A list of of filepaths on this filesystems
907
+ starts, ends: int or list
908
+ Bytes limits of the read. If using a single int, the same value will be
909
+ used to read all the specified files.
910
+ """
911
+ if max_gap is not None:
912
+ raise NotImplementedError
913
+ if not isinstance(paths, list):
914
+ raise TypeError
915
+ if not isinstance(starts, list):
916
+ starts = [starts] * len(paths)
917
+ if not isinstance(ends, list):
918
+ ends = [ends] * len(paths)
919
+ if len(starts) != len(paths) or len(ends) != len(paths):
920
+ raise ValueError
921
+ out = []
922
+ for p, s, e in zip(paths, starts, ends):
923
+ try:
924
+ out.append(self.cat_file(p, s, e, **kwargs))
925
+ except Exception as e:
926
+ if on_error == "return":
927
+ out.append(e)
928
+ else:
929
+ raise
930
+ return out
931
+
932
+ def cat(self, path, recursive=False, on_error="raise", **kwargs):
933
+ """Fetch (potentially multiple) paths' contents
934
+
935
+ Parameters
936
+ ----------
937
+ recursive: bool
938
+ If True, assume the path(s) are directories, and get all the
939
+ contained files
940
+ on_error : "raise", "omit", "return"
941
+ If raise, an underlying exception will be raised (converted to KeyError
942
+ if the type is in self.missing_exceptions); if omit, keys with exception
943
+ will simply not be included in the output; if "return", all keys are
944
+ included in the output, but the value will be bytes or an exception
945
+ instance.
946
+ kwargs: passed to cat_file
947
+
948
+ Returns
949
+ -------
950
+ dict of {path: contents} if there are multiple paths
951
+ or the path has been otherwise expanded
952
+ """
953
+ paths = self.expand_path(path, recursive=recursive, **kwargs)
954
+ if (
955
+ len(paths) > 1
956
+ or isinstance(path, list)
957
+ or paths[0] != self._strip_protocol(path)
958
+ ):
959
+ out = {}
960
+ for path in paths:
961
+ try:
962
+ out[path] = self.cat_file(path, **kwargs)
963
+ except Exception as e:
964
+ if on_error == "raise":
965
+ raise
966
+ if on_error == "return":
967
+ out[path] = e
968
+ return out
969
+ else:
970
+ return self.cat_file(paths[0], **kwargs)
971
+
972
+ def get_file(self, rpath, lpath, callback=DEFAULT_CALLBACK, outfile=None, **kwargs):
973
+ """Copy single remote file to local"""
974
+ from .implementations.local import LocalFileSystem
975
+
976
+ if isfilelike(lpath):
977
+ outfile = lpath
978
+ elif self.isdir(rpath):
979
+ os.makedirs(lpath, exist_ok=True)
980
+ return None
981
+
982
+ fs = LocalFileSystem(auto_mkdir=True)
983
+ fs.makedirs(fs._parent(lpath), exist_ok=True)
984
+
985
+ with self.open(rpath, "rb", **kwargs) as f1:
986
+ if outfile is None:
987
+ outfile = open(lpath, "wb")
988
+
989
+ try:
990
+ callback.set_size(getattr(f1, "size", None))
991
+ data = True
992
+ while data:
993
+ data = f1.read(self.blocksize)
994
+ segment_len = outfile.write(data)
995
+ if segment_len is None:
996
+ segment_len = len(data)
997
+ callback.relative_update(segment_len)
998
+ finally:
999
+ if not isfilelike(lpath):
1000
+ outfile.close()
1001
+
1002
+ def get(
1003
+ self,
1004
+ rpath,
1005
+ lpath,
1006
+ recursive=False,
1007
+ callback=DEFAULT_CALLBACK,
1008
+ maxdepth=None,
1009
+ **kwargs,
1010
+ ):
1011
+ """Copy file(s) to local.
1012
+
1013
+ Copies a specific file or tree of files (if recursive=True). If lpath
1014
+ ends with a "/", it will be assumed to be a directory, and target files
1015
+ will go within. Can submit a list of paths, which may be glob-patterns
1016
+ and will be expanded.
1017
+
1018
+ Calls get_file for each source.
1019
+ """
1020
+ if isinstance(lpath, list) and isinstance(rpath, list):
1021
+ # No need to expand paths when both source and destination
1022
+ # are provided as lists
1023
+ rpaths = rpath
1024
+ lpaths = lpath
1025
+ else:
1026
+ from .implementations.local import (
1027
+ LocalFileSystem,
1028
+ make_path_posix,
1029
+ trailing_sep,
1030
+ )
1031
+
1032
+ source_is_str = isinstance(rpath, str)
1033
+ rpaths = self.expand_path(
1034
+ rpath, recursive=recursive, maxdepth=maxdepth, **kwargs
1035
+ )
1036
+ if source_is_str and (not recursive or maxdepth is not None):
1037
+ # Non-recursive glob does not copy directories
1038
+ rpaths = [p for p in rpaths if not (trailing_sep(p) or self.isdir(p))]
1039
+ if not rpaths:
1040
+ return
1041
+
1042
+ if isinstance(lpath, str):
1043
+ lpath = make_path_posix(lpath)
1044
+
1045
+ source_is_file = len(rpaths) == 1
1046
+ dest_is_dir = isinstance(lpath, str) and (
1047
+ trailing_sep(lpath) or LocalFileSystem().isdir(lpath)
1048
+ )
1049
+
1050
+ exists = source_is_str and (
1051
+ (has_magic(rpath) and source_is_file)
1052
+ or (not has_magic(rpath) and dest_is_dir and not trailing_sep(rpath))
1053
+ )
1054
+ lpaths = other_paths(
1055
+ rpaths,
1056
+ lpath,
1057
+ exists=exists,
1058
+ flatten=not source_is_str,
1059
+ )
1060
+
1061
+ callback.set_size(len(lpaths))
1062
+ for lpath, rpath in callback.wrap(zip(lpaths, rpaths)):
1063
+ with callback.branched(rpath, lpath) as child:
1064
+ self.get_file(rpath, lpath, callback=child, **kwargs)
1065
+
1066
+ def put_file(
1067
+ self, lpath, rpath, callback=DEFAULT_CALLBACK, mode="overwrite", **kwargs
1068
+ ):
1069
+ """Copy single file to remote"""
1070
+ if mode == "create" and self.exists(rpath):
1071
+ raise FileExistsError
1072
+ if os.path.isdir(lpath):
1073
+ self.makedirs(rpath, exist_ok=True)
1074
+ return None
1075
+
1076
+ with open(lpath, "rb") as f1:
1077
+ size = f1.seek(0, 2)
1078
+ callback.set_size(size)
1079
+ f1.seek(0)
1080
+
1081
+ self.mkdirs(self._parent(os.fspath(rpath)), exist_ok=True)
1082
+ with self.open(rpath, "wb", **kwargs) as f2:
1083
+ while f1.tell() < size:
1084
+ data = f1.read(self.blocksize)
1085
+ segment_len = f2.write(data)
1086
+ if segment_len is None:
1087
+ segment_len = len(data)
1088
+ callback.relative_update(segment_len)
1089
+
1090
+ def put(
1091
+ self,
1092
+ lpath,
1093
+ rpath,
1094
+ recursive=False,
1095
+ callback=DEFAULT_CALLBACK,
1096
+ maxdepth=None,
1097
+ **kwargs,
1098
+ ):
1099
+ """Copy file(s) from local.
1100
+
1101
+ Copies a specific file or tree of files (if recursive=True). If rpath
1102
+ ends with a "/", it will be assumed to be a directory, and target files
1103
+ will go within.
1104
+
1105
+ Calls put_file for each source.
1106
+ """
1107
+ if isinstance(lpath, list) and isinstance(rpath, list):
1108
+ # No need to expand paths when both source and destination
1109
+ # are provided as lists
1110
+ rpaths = rpath
1111
+ lpaths = lpath
1112
+ else:
1113
+ from .implementations.local import (
1114
+ LocalFileSystem,
1115
+ make_path_posix,
1116
+ trailing_sep,
1117
+ )
1118
+
1119
+ source_is_str = isinstance(lpath, str)
1120
+ if source_is_str:
1121
+ lpath = make_path_posix(lpath)
1122
+ fs = LocalFileSystem()
1123
+ lpaths = fs.expand_path(
1124
+ lpath, recursive=recursive, maxdepth=maxdepth, **kwargs
1125
+ )
1126
+ if source_is_str and (not recursive or maxdepth is not None):
1127
+ # Non-recursive glob does not copy directories
1128
+ lpaths = [p for p in lpaths if not (trailing_sep(p) or fs.isdir(p))]
1129
+ if not lpaths:
1130
+ return
1131
+
1132
+ source_is_file = len(lpaths) == 1
1133
+ dest_is_dir = isinstance(rpath, str) and (
1134
+ trailing_sep(rpath) or self.isdir(rpath)
1135
+ )
1136
+
1137
+ rpath = (
1138
+ self._strip_protocol(rpath)
1139
+ if isinstance(rpath, str)
1140
+ else [self._strip_protocol(p) for p in rpath]
1141
+ )
1142
+ exists = source_is_str and (
1143
+ (has_magic(lpath) and source_is_file)
1144
+ or (not has_magic(lpath) and dest_is_dir and not trailing_sep(lpath))
1145
+ )
1146
+ rpaths = other_paths(
1147
+ lpaths,
1148
+ rpath,
1149
+ exists=exists,
1150
+ flatten=not source_is_str,
1151
+ )
1152
+
1153
+ callback.set_size(len(rpaths))
1154
+ for lpath, rpath in callback.wrap(zip(lpaths, rpaths)):
1155
+ with callback.branched(lpath, rpath) as child:
1156
+ self.put_file(lpath, rpath, callback=child, **kwargs)
1157
+
1158
+ def head(self, path, size=1024):
1159
+ """Get the first ``size`` bytes from file"""
1160
+ with self.open(path, "rb") as f:
1161
+ return f.read(size)
1162
+
1163
+ def tail(self, path, size=1024):
1164
+ """Get the last ``size`` bytes from file"""
1165
+ with self.open(path, "rb") as f:
1166
+ f.seek(max(-size, -f.size), 2)
1167
+ return f.read()
1168
+
1169
+ def cp_file(self, path1, path2, **kwargs):
1170
+ raise NotImplementedError
1171
+
1172
+ def copy(
1173
+ self, path1, path2, recursive=False, maxdepth=None, on_error=None, **kwargs
1174
+ ):
1175
+ """Copy within two locations in the filesystem
1176
+
1177
+ on_error : "raise", "ignore"
1178
+ If raise, any not-found exceptions will be raised; if ignore any
1179
+ not-found exceptions will cause the path to be skipped; defaults to
1180
+ raise unless recursive is true, where the default is ignore
1181
+ """
1182
+ if on_error is None and recursive:
1183
+ on_error = "ignore"
1184
+ elif on_error is None:
1185
+ on_error = "raise"
1186
+
1187
+ if isinstance(path1, list) and isinstance(path2, list):
1188
+ # No need to expand paths when both source and destination
1189
+ # are provided as lists
1190
+ paths1 = path1
1191
+ paths2 = path2
1192
+ else:
1193
+ from .implementations.local import trailing_sep
1194
+
1195
+ source_is_str = isinstance(path1, str)
1196
+ paths1 = self.expand_path(
1197
+ path1, recursive=recursive, maxdepth=maxdepth, **kwargs
1198
+ )
1199
+ if source_is_str and (not recursive or maxdepth is not None):
1200
+ # Non-recursive glob does not copy directories
1201
+ paths1 = [p for p in paths1 if not (trailing_sep(p) or self.isdir(p))]
1202
+ if not paths1:
1203
+ return
1204
+
1205
+ source_is_file = len(paths1) == 1
1206
+ dest_is_dir = isinstance(path2, str) and (
1207
+ trailing_sep(path2) or self.isdir(path2)
1208
+ )
1209
+
1210
+ exists = source_is_str and (
1211
+ (has_magic(path1) and source_is_file)
1212
+ or (not has_magic(path1) and dest_is_dir and not trailing_sep(path1))
1213
+ )
1214
+ paths2 = other_paths(
1215
+ paths1,
1216
+ path2,
1217
+ exists=exists,
1218
+ flatten=not source_is_str,
1219
+ )
1220
+
1221
+ for p1, p2 in zip(paths1, paths2):
1222
+ try:
1223
+ self.cp_file(p1, p2, **kwargs)
1224
+ except FileNotFoundError:
1225
+ if on_error == "raise":
1226
+ raise
1227
+
1228
+ def expand_path(
1229
+ self, path, recursive=False, maxdepth=None, assume_literal=False, **kwargs
1230
+ ):
1231
+ """Turn one or more globs or directories into a list of all matching paths
1232
+ to files or directories.
1233
+
1234
+ kwargs are passed to ``glob`` or ``find``, which may in turn call ``ls``
1235
+ """
1236
+
1237
+ if maxdepth is not None and maxdepth < 1:
1238
+ raise ValueError("maxdepth must be at least 1")
1239
+
1240
+ if isinstance(path, (str, os.PathLike)):
1241
+ out = self.expand_path([path], recursive, maxdepth, **kwargs)
1242
+ else:
1243
+ out = set()
1244
+ path = [self._strip_protocol(p) for p in path]
1245
+ for p in path:
1246
+ if not assume_literal and has_magic(p):
1247
+ bit = set(self.glob(p, maxdepth=maxdepth, **kwargs))
1248
+ out |= bit
1249
+ if recursive:
1250
+ # glob call above expanded one depth so if maxdepth is defined
1251
+ # then decrement it in expand_path call below. If it is zero
1252
+ # after decrementing then avoid expand_path call.
1253
+ if maxdepth is not None and maxdepth <= 1:
1254
+ continue
1255
+ out |= set(
1256
+ self.expand_path(
1257
+ list(bit),
1258
+ recursive=recursive,
1259
+ maxdepth=maxdepth - 1 if maxdepth is not None else None,
1260
+ assume_literal=True,
1261
+ **kwargs,
1262
+ )
1263
+ )
1264
+ continue
1265
+ elif recursive:
1266
+ rec = set(
1267
+ self.find(
1268
+ p, maxdepth=maxdepth, withdirs=True, detail=False, **kwargs
1269
+ )
1270
+ )
1271
+ out |= rec
1272
+ if p not in out and (recursive is False or self.exists(p)):
1273
+ # should only check once, for the root
1274
+ out.add(p)
1275
+ if not out:
1276
+ raise FileNotFoundError(path)
1277
+ return sorted(out)
1278
+
1279
+ def mv(self, path1, path2, recursive=False, maxdepth=None, **kwargs):
1280
+ """Move file(s) from one location to another"""
1281
+ if path1 == path2:
1282
+ logger.debug("%s mv: The paths are the same, so no files were moved.", self)
1283
+ else:
1284
+ # explicitly raise exception to prevent data corruption
1285
+ self.copy(
1286
+ path1, path2, recursive=recursive, maxdepth=maxdepth, on_error="raise"
1287
+ )
1288
+ self.rm(path1, recursive=recursive)
1289
+
1290
+ def rm_file(self, path):
1291
+ """Delete a file"""
1292
+ self._rm(path)
1293
+
1294
+ def _rm(self, path):
1295
+ """Delete one file"""
1296
+ # this is the old name for the method, prefer rm_file
1297
+ raise NotImplementedError
1298
+
1299
+ def rm(self, path, recursive=False, maxdepth=None):
1300
+ """Delete files.
1301
+
1302
+ Parameters
1303
+ ----------
1304
+ path: str or list of str
1305
+ File(s) to delete.
1306
+ recursive: bool
1307
+ If file(s) are directories, recursively delete contents and then
1308
+ also remove the directory
1309
+ maxdepth: int or None
1310
+ Depth to pass to walk for finding files to delete, if recursive.
1311
+ If None, there will be no limit and infinite recursion may be
1312
+ possible.
1313
+ """
1314
+ path = self.expand_path(path, recursive=recursive, maxdepth=maxdepth)
1315
+ for p in reversed(path):
1316
+ self.rm_file(p)
1317
+
1318
+ @classmethod
1319
+ def _parent(cls, path):
1320
+ path = cls._strip_protocol(path)
1321
+ if "/" in path:
1322
+ parent = path.rsplit("/", 1)[0].lstrip(cls.root_marker)
1323
+ return cls.root_marker + parent
1324
+ else:
1325
+ return cls.root_marker
1326
+
1327
+ def _open(
1328
+ self,
1329
+ path,
1330
+ mode="rb",
1331
+ block_size=None,
1332
+ autocommit=True,
1333
+ cache_options=None,
1334
+ **kwargs,
1335
+ ):
1336
+ """Return raw bytes-mode file-like from the file-system"""
1337
+ return AbstractBufferedFile(
1338
+ self,
1339
+ path,
1340
+ mode,
1341
+ block_size,
1342
+ autocommit,
1343
+ cache_options=cache_options,
1344
+ **kwargs,
1345
+ )
1346
+
1347
+ def open(
1348
+ self,
1349
+ path,
1350
+ mode="rb",
1351
+ block_size=None,
1352
+ cache_options=None,
1353
+ compression=None,
1354
+ **kwargs,
1355
+ ):
1356
+ """
1357
+ Return a file-like object from the filesystem
1358
+
1359
+ The resultant instance must function correctly in a context ``with``
1360
+ block.
1361
+
1362
+ Parameters
1363
+ ----------
1364
+ path: str
1365
+ Target file
1366
+ mode: str like 'rb', 'w'
1367
+ See builtin ``open()``
1368
+ Mode "x" (exclusive write) may be implemented by the backend. Even if
1369
+ it is, whether it is checked up front or on commit, and whether it is
1370
+ atomic is implementation-dependent.
1371
+ block_size: int
1372
+ Some indication of buffering - this is a value in bytes
1373
+ cache_options : dict, optional
1374
+ Extra arguments to pass through to the cache.
1375
+ compression: string or None
1376
+ If given, open file using compression codec. Can either be a compression
1377
+ name (a key in ``fsspec.compression.compr``) or "infer" to guess the
1378
+ compression from the filename suffix.
1379
+ encoding, errors, newline: passed on to TextIOWrapper for text mode
1380
+ """
1381
+ import io
1382
+
1383
+ path = self._strip_protocol(path)
1384
+ if "b" not in mode:
1385
+ mode = mode.replace("t", "") + "b"
1386
+
1387
+ text_kwargs = {
1388
+ k: kwargs.pop(k)
1389
+ for k in ["encoding", "errors", "newline"]
1390
+ if k in kwargs
1391
+ }
1392
+ return io.TextIOWrapper(
1393
+ self.open(
1394
+ path,
1395
+ mode,
1396
+ block_size=block_size,
1397
+ cache_options=cache_options,
1398
+ compression=compression,
1399
+ **kwargs,
1400
+ ),
1401
+ **text_kwargs,
1402
+ )
1403
+ else:
1404
+ ac = kwargs.pop("autocommit", not self._intrans)
1405
+ f = self._open(
1406
+ path,
1407
+ mode=mode,
1408
+ block_size=block_size,
1409
+ autocommit=ac,
1410
+ cache_options=cache_options,
1411
+ **kwargs,
1412
+ )
1413
+ if compression is not None:
1414
+ from fsspec.compression import compr
1415
+ from fsspec.core import get_compression
1416
+
1417
+ compression = get_compression(path, compression)
1418
+ compress = compr[compression]
1419
+ f = compress(f, mode=mode[0])
1420
+
1421
+ if not ac and "r" not in mode:
1422
+ self.transaction.files.append(f)
1423
+ return f
1424
+
1425
+ def touch(self, path, truncate=True, **kwargs):
1426
+ """Create empty file, or update timestamp
1427
+
1428
+ Parameters
1429
+ ----------
1430
+ path: str
1431
+ file location
1432
+ truncate: bool
1433
+ If True, always set file size to 0; if False, update timestamp and
1434
+ leave file unchanged, if backend allows this
1435
+ """
1436
+ if truncate or not self.exists(path):
1437
+ with self.open(path, "wb", **kwargs):
1438
+ pass
1439
+ else:
1440
+ raise NotImplementedError # update timestamp, if possible
1441
+
1442
+ def ukey(self, path):
1443
+ """Hash of file properties, to tell if it has changed"""
1444
+ return sha256(str(self.info(path)).encode()).hexdigest()
1445
+
1446
+ def read_block(self, fn, offset, length, delimiter=None):
1447
+ """Read a block of bytes from
1448
+
1449
+ Starting at ``offset`` of the file, read ``length`` bytes. If
1450
+ ``delimiter`` is set then we ensure that the read starts and stops at
1451
+ delimiter boundaries that follow the locations ``offset`` and ``offset
1452
+ + length``. If ``offset`` is zero then we start at zero. The
1453
+ bytestring returned WILL include the end delimiter string.
1454
+
1455
+ If offset+length is beyond the eof, reads to eof.
1456
+
1457
+ Parameters
1458
+ ----------
1459
+ fn: string
1460
+ Path to filename
1461
+ offset: int
1462
+ Byte offset to start read
1463
+ length: int
1464
+ Number of bytes to read. If None, read to end.
1465
+ delimiter: bytes (optional)
1466
+ Ensure reading starts and stops at delimiter bytestring
1467
+
1468
+ Examples
1469
+ --------
1470
+ >>> fs.read_block('data/file.csv', 0, 13) # doctest: +SKIP
1471
+ b'Alice, 100\\nBo'
1472
+ >>> fs.read_block('data/file.csv', 0, 13, delimiter=b'\\n') # doctest: +SKIP
1473
+ b'Alice, 100\\nBob, 200\\n'
1474
+
1475
+ Use ``length=None`` to read to the end of the file.
1476
+ >>> fs.read_block('data/file.csv', 0, None, delimiter=b'\\n') # doctest: +SKIP
1477
+ b'Alice, 100\\nBob, 200\\nCharlie, 300'
1478
+
1479
+ See Also
1480
+ --------
1481
+ :func:`fsspec.utils.read_block`
1482
+ """
1483
+ with self.open(fn, "rb") as f:
1484
+ size = f.size
1485
+ if length is None:
1486
+ length = size
1487
+ if size is not None and offset + length > size:
1488
+ length = size - offset
1489
+ return read_block(f, offset, length, delimiter)
1490
+
1491
+ def to_json(self, *, include_password: bool = True) -> str:
1492
+ """
1493
+ JSON representation of this filesystem instance.
1494
+
1495
+ Parameters
1496
+ ----------
1497
+ include_password: bool, default True
1498
+ Whether to include the password (if any) in the output.
1499
+
1500
+ Returns
1501
+ -------
1502
+ JSON string with keys ``cls`` (the python location of this class),
1503
+ protocol (text name of this class's protocol, first one in case of
1504
+ multiple), ``args`` (positional args, usually empty), and all other
1505
+ keyword arguments as their own keys.
1506
+
1507
+ Warnings
1508
+ --------
1509
+ Serialized filesystems may contain sensitive information which have been
1510
+ passed to the constructor, such as passwords and tokens. Make sure you
1511
+ store and send them in a secure environment!
1512
+ """
1513
+ from .json import FilesystemJSONEncoder
1514
+
1515
+ return json.dumps(
1516
+ self,
1517
+ cls=type(
1518
+ "_FilesystemJSONEncoder",
1519
+ (FilesystemJSONEncoder,),
1520
+ {"include_password": include_password},
1521
+ ),
1522
+ )
1523
+
1524
+ @staticmethod
1525
+ def from_json(blob: str) -> AbstractFileSystem:
1526
+ """
1527
+ Recreate a filesystem instance from JSON representation.
1528
+
1529
+ See ``.to_json()`` for the expected structure of the input.
1530
+
1531
+ Parameters
1532
+ ----------
1533
+ blob: str
1534
+
1535
+ Returns
1536
+ -------
1537
+ file system instance, not necessarily of this particular class.
1538
+
1539
+ Warnings
1540
+ --------
1541
+ This can import arbitrary modules (as determined by the ``cls`` key).
1542
+ Make sure you haven't installed any modules that may execute malicious code
1543
+ at import time.
1544
+ """
1545
+ from .json import FilesystemJSONDecoder
1546
+
1547
+ return json.loads(blob, cls=FilesystemJSONDecoder)
1548
+
1549
+ def to_dict(self, *, include_password: bool = True) -> dict[str, Any]:
1550
+ """
1551
+ JSON-serializable dictionary representation of this filesystem instance.
1552
+
1553
+ Parameters
1554
+ ----------
1555
+ include_password: bool, default True
1556
+ Whether to include the password (if any) in the output.
1557
+
1558
+ Returns
1559
+ -------
1560
+ Dictionary with keys ``cls`` (the python location of this class),
1561
+ protocol (text name of this class's protocol, first one in case of
1562
+ multiple), ``args`` (positional args, usually empty), and all other
1563
+ keyword arguments as their own keys.
1564
+
1565
+ Warnings
1566
+ --------
1567
+ Serialized filesystems may contain sensitive information which have been
1568
+ passed to the constructor, such as passwords and tokens. Make sure you
1569
+ store and send them in a secure environment!
1570
+ """
1571
+ from .json import FilesystemJSONEncoder
1572
+
1573
+ json_encoder = FilesystemJSONEncoder()
1574
+
1575
+ cls = type(self)
1576
+ proto = self.protocol
1577
+
1578
+ storage_options = dict(self.storage_options)
1579
+ if not include_password:
1580
+ storage_options.pop("password", None)
1581
+
1582
+ return dict(
1583
+ cls=f"{cls.__module__}:{cls.__name__}",
1584
+ protocol=proto[0] if isinstance(proto, (tuple, list)) else proto,
1585
+ args=json_encoder.make_serializable(self.storage_args),
1586
+ **json_encoder.make_serializable(storage_options),
1587
+ )
1588
+
1589
+ @staticmethod
1590
+ def from_dict(dct: dict[str, Any]) -> AbstractFileSystem:
1591
+ """
1592
+ Recreate a filesystem instance from dictionary representation.
1593
+
1594
+ See ``.to_dict()`` for the expected structure of the input.
1595
+
1596
+ Parameters
1597
+ ----------
1598
+ dct: Dict[str, Any]
1599
+
1600
+ Returns
1601
+ -------
1602
+ file system instance, not necessarily of this particular class.
1603
+
1604
+ Warnings
1605
+ --------
1606
+ This can import arbitrary modules (as determined by the ``cls`` key).
1607
+ Make sure you haven't installed any modules that may execute malicious code
1608
+ at import time.
1609
+ """
1610
+ from .json import FilesystemJSONDecoder
1611
+
1612
+ json_decoder = FilesystemJSONDecoder()
1613
+
1614
+ dct = dict(dct) # Defensive copy
1615
+
1616
+ cls = FilesystemJSONDecoder.try_resolve_fs_cls(dct)
1617
+ if cls is None:
1618
+ raise ValueError("Not a serialized AbstractFileSystem")
1619
+
1620
+ dct.pop("cls", None)
1621
+ dct.pop("protocol", None)
1622
+
1623
+ return cls(
1624
+ *json_decoder.unmake_serializable(dct.pop("args", ())),
1625
+ **json_decoder.unmake_serializable(dct),
1626
+ )
1627
+
1628
+ def _get_pyarrow_filesystem(self):
1629
+ """
1630
+ Make a version of the FS instance which will be acceptable to pyarrow
1631
+ """
1632
+ # all instances already also derive from pyarrow
1633
+ return self
1634
+
1635
+ def get_mapper(self, root="", check=False, create=False, missing_exceptions=None):
1636
+ """Create key/value store based on this file-system
1637
+
1638
+ Makes a MutableMapping interface to the FS at the given root path.
1639
+ See ``fsspec.mapping.FSMap`` for further details.
1640
+ """
1641
+ from .mapping import FSMap
1642
+
1643
+ return FSMap(
1644
+ root,
1645
+ self,
1646
+ check=check,
1647
+ create=create,
1648
+ missing_exceptions=missing_exceptions,
1649
+ )
1650
+
1651
+ @classmethod
1652
+ def clear_instance_cache(cls):
1653
+ """
1654
+ Clear the cache of filesystem instances.
1655
+
1656
+ Notes
1657
+ -----
1658
+ Unless overridden by setting the ``cachable`` class attribute to False,
1659
+ the filesystem class stores a reference to newly created instances. This
1660
+ prevents Python's normal rules around garbage collection from working,
1661
+ since the instances refcount will not drop to zero until
1662
+ ``clear_instance_cache`` is called.
1663
+ """
1664
+ cls._cache.clear()
1665
+
1666
+ def created(self, path):
1667
+ """Return the created timestamp of a file as a datetime.datetime"""
1668
+ raise NotImplementedError
1669
+
1670
+ def modified(self, path):
1671
+ """Return the modified timestamp of a file as a datetime.datetime"""
1672
+ raise NotImplementedError
1673
+
1674
+ def tree(
1675
+ self,
1676
+ path: str = "/",
1677
+ recursion_limit: int = 2,
1678
+ max_display: int = 25,
1679
+ display_size: bool = False,
1680
+ prefix: str = "",
1681
+ is_last: bool = True,
1682
+ first: bool = True,
1683
+ indent_size: int = 4,
1684
+ ) -> str:
1685
+ """
1686
+ Return a tree-like structure of the filesystem starting from the given path as a string.
1687
+
1688
+ Parameters
1689
+ ----------
1690
+ path: Root path to start traversal from
1691
+ recursion_limit: Maximum depth of directory traversal
1692
+ max_display: Maximum number of items to display per directory
1693
+ display_size: Whether to display file sizes
1694
+ prefix: Current line prefix for visual tree structure
1695
+ is_last: Whether current item is last in its level
1696
+ first: Whether this is the first call (displays root path)
1697
+ indent_size: Number of spaces by indent
1698
+
1699
+ Returns
1700
+ -------
1701
+ str: A string representing the tree structure.
1702
+
1703
+ Example
1704
+ -------
1705
+ >>> from fsspec import filesystem
1706
+
1707
+ >>> fs = filesystem('ftp', host='test.rebex.net', user='demo', password='password')
1708
+ >>> tree = fs.tree(display_size=True, recursion_limit=3, indent_size=8, max_display=10)
1709
+ >>> print(tree)
1710
+ """
1711
+
1712
+ def format_bytes(n: int) -> str:
1713
+ """Format bytes as text."""
1714
+ for prefix, k in (
1715
+ ("P", 2**50),
1716
+ ("T", 2**40),
1717
+ ("G", 2**30),
1718
+ ("M", 2**20),
1719
+ ("k", 2**10),
1720
+ ):
1721
+ if n >= 0.9 * k:
1722
+ return f"{n / k:.2f} {prefix}b"
1723
+ return f"{n}B"
1724
+
1725
+ result = []
1726
+
1727
+ if first:
1728
+ result.append(path)
1729
+
1730
+ if recursion_limit:
1731
+ indent = " " * indent_size
1732
+ contents = self.ls(path, detail=True)
1733
+ contents.sort(
1734
+ key=lambda x: (x.get("type") != "directory", x.get("name", ""))
1735
+ )
1736
+
1737
+ if max_display is not None and len(contents) > max_display:
1738
+ displayed_contents = contents[:max_display]
1739
+ remaining_count = len(contents) - max_display
1740
+ else:
1741
+ displayed_contents = contents
1742
+ remaining_count = 0
1743
+
1744
+ for i, item in enumerate(displayed_contents):
1745
+ is_last_item = (i == len(displayed_contents) - 1) and (
1746
+ remaining_count == 0
1747
+ )
1748
+
1749
+ branch = (
1750
+ "└" + ("─" * (indent_size - 2))
1751
+ if is_last_item
1752
+ else "├" + ("─" * (indent_size - 2))
1753
+ )
1754
+ branch += " "
1755
+ new_prefix = prefix + (
1756
+ indent if is_last_item else "│" + " " * (indent_size - 1)
1757
+ )
1758
+
1759
+ name = os.path.basename(item.get("name", ""))
1760
+
1761
+ if display_size and item.get("type") == "directory":
1762
+ sub_contents = self.ls(item.get("name", ""), detail=True)
1763
+ num_files = sum(
1764
+ 1 for sub_item in sub_contents if sub_item.get("type") == "file"
1765
+ )
1766
+ num_folders = sum(
1767
+ 1
1768
+ for sub_item in sub_contents
1769
+ if sub_item.get("type") == "directory"
1770
+ )
1771
+
1772
+ if num_files == 0 and num_folders == 0:
1773
+ size = " (empty folder)"
1774
+ elif num_files == 0:
1775
+ size = f" ({num_folders} subfolder{'s' if num_folders > 1 else ''})"
1776
+ elif num_folders == 0:
1777
+ size = f" ({num_files} file{'s' if num_files > 1 else ''})"
1778
+ else:
1779
+ size = f" ({num_files} file{'s' if num_files > 1 else ''}, {num_folders} subfolder{'s' if num_folders > 1 else ''})"
1780
+ elif display_size and item.get("type") == "file":
1781
+ size = f" ({format_bytes(item.get('size', 0))})"
1782
+ else:
1783
+ size = ""
1784
+
1785
+ result.append(f"{prefix}{branch}{name}{size}")
1786
+
1787
+ if item.get("type") == "directory" and recursion_limit > 0:
1788
+ result.append(
1789
+ self.tree(
1790
+ path=item.get("name", ""),
1791
+ recursion_limit=recursion_limit - 1,
1792
+ max_display=max_display,
1793
+ display_size=display_size,
1794
+ prefix=new_prefix,
1795
+ is_last=is_last_item,
1796
+ first=False,
1797
+ indent_size=indent_size,
1798
+ )
1799
+ )
1800
+
1801
+ if remaining_count > 0:
1802
+ more_message = f"{remaining_count} more item(s) not displayed."
1803
+ result.append(
1804
+ f"{prefix}{'└' + ('─' * (indent_size - 2))} {more_message}"
1805
+ )
1806
+
1807
+ return "\n".join(_ for _ in result if _)
1808
+
1809
+ # ------------------------------------------------------------------------
1810
+ # Aliases
1811
+
1812
+ def read_bytes(self, path, start=None, end=None, **kwargs):
1813
+ """Alias of `AbstractFileSystem.cat_file`."""
1814
+ return self.cat_file(path, start=start, end=end, **kwargs)
1815
+
1816
+ def write_bytes(self, path, value, **kwargs):
1817
+ """Alias of `AbstractFileSystem.pipe_file`."""
1818
+ self.pipe_file(path, value, **kwargs)
1819
+
1820
+ def makedir(self, path, create_parents=True, **kwargs):
1821
+ """Alias of `AbstractFileSystem.mkdir`."""
1822
+ return self.mkdir(path, create_parents=create_parents, **kwargs)
1823
+
1824
+ def mkdirs(self, path, exist_ok=False):
1825
+ """Alias of `AbstractFileSystem.makedirs`."""
1826
+ return self.makedirs(path, exist_ok=exist_ok)
1827
+
1828
+ def listdir(self, path, detail=True, **kwargs):
1829
+ """Alias of `AbstractFileSystem.ls`."""
1830
+ return self.ls(path, detail=detail, **kwargs)
1831
+
1832
+ def cp(self, path1, path2, **kwargs):
1833
+ """Alias of `AbstractFileSystem.copy`."""
1834
+ return self.copy(path1, path2, **kwargs)
1835
+
1836
+ def move(self, path1, path2, **kwargs):
1837
+ """Alias of `AbstractFileSystem.mv`."""
1838
+ return self.mv(path1, path2, **kwargs)
1839
+
1840
+ def stat(self, path, **kwargs):
1841
+ """Alias of `AbstractFileSystem.info`."""
1842
+ return self.info(path, **kwargs)
1843
+
1844
+ def disk_usage(self, path, total=True, maxdepth=None, **kwargs):
1845
+ """Alias of `AbstractFileSystem.du`."""
1846
+ return self.du(path, total=total, maxdepth=maxdepth, **kwargs)
1847
+
1848
+ def rename(self, path1, path2, **kwargs):
1849
+ """Alias of `AbstractFileSystem.mv`."""
1850
+ return self.mv(path1, path2, **kwargs)
1851
+
1852
+ def delete(self, path, recursive=False, maxdepth=None):
1853
+ """Alias of `AbstractFileSystem.rm`."""
1854
+ return self.rm(path, recursive=recursive, maxdepth=maxdepth)
1855
+
1856
+ def upload(self, lpath, rpath, recursive=False, **kwargs):
1857
+ """Alias of `AbstractFileSystem.put`."""
1858
+ return self.put(lpath, rpath, recursive=recursive, **kwargs)
1859
+
1860
+ def download(self, rpath, lpath, recursive=False, **kwargs):
1861
+ """Alias of `AbstractFileSystem.get`."""
1862
+ return self.get(rpath, lpath, recursive=recursive, **kwargs)
1863
+
1864
+ def sign(self, path, expiration=100, **kwargs):
1865
+ """Create a signed URL representing the given path
1866
+
1867
+ Some implementations allow temporary URLs to be generated, as a
1868
+ way of delegating credentials.
1869
+
1870
+ Parameters
1871
+ ----------
1872
+ path : str
1873
+ The path on the filesystem
1874
+ expiration : int
1875
+ Number of seconds to enable the URL for (if supported)
1876
+
1877
+ Returns
1878
+ -------
1879
+ URL : str
1880
+ The signed URL
1881
+
1882
+ Raises
1883
+ ------
1884
+ NotImplementedError : if method is not implemented for a filesystem
1885
+ """
1886
+ raise NotImplementedError("Sign is not implemented for this filesystem")
1887
+
1888
+ def _isfilestore(self):
1889
+ # Originally inherited from pyarrow DaskFileSystem. Keeping this
1890
+ # here for backwards compatibility as long as pyarrow uses its
1891
+ # legacy fsspec-compatible filesystems and thus accepts fsspec
1892
+ # filesystems as well
1893
+ return False
1894
+
1895
+
1896
+ class AbstractBufferedFile(io.IOBase):
1897
+ """Convenient class to derive from to provide buffering
1898
+
1899
+ In the case that the backend does not provide a pythonic file-like object
1900
+ already, this class contains much of the logic to build one. The only
1901
+ methods that need to be overridden are ``_upload_chunk``,
1902
+ ``_initiate_upload`` and ``_fetch_range``.
1903
+ """
1904
+
1905
+ DEFAULT_BLOCK_SIZE = 5 * 2**20
1906
+ _details = None
1907
+
1908
+ def __init__(
1909
+ self,
1910
+ fs,
1911
+ path,
1912
+ mode="rb",
1913
+ block_size="default",
1914
+ autocommit=True,
1915
+ cache_type="readahead",
1916
+ cache_options=None,
1917
+ size=None,
1918
+ **kwargs,
1919
+ ):
1920
+ """
1921
+ Template for files with buffered reading and writing
1922
+
1923
+ Parameters
1924
+ ----------
1925
+ fs: instance of FileSystem
1926
+ path: str
1927
+ location in file-system
1928
+ mode: str
1929
+ Normal file modes. Currently only 'wb', 'ab' or 'rb'. Some file
1930
+ systems may be read-only, and some may not support append.
1931
+ block_size: int
1932
+ Buffer size for reading or writing, 'default' for class default
1933
+ autocommit: bool
1934
+ Whether to write to final destination; may only impact what
1935
+ happens when file is being closed.
1936
+ cache_type: {"readahead", "none", "mmap", "bytes"}, default "readahead"
1937
+ Caching policy in read mode. See the definitions in ``core``.
1938
+ cache_options : dict
1939
+ Additional options passed to the constructor for the cache specified
1940
+ by `cache_type`.
1941
+ size: int
1942
+ If given and in read mode, suppressed having to look up the file size
1943
+ kwargs:
1944
+ Gets stored as self.kwargs
1945
+ """
1946
+ from .core import caches
1947
+
1948
+ self.path = path
1949
+ self.fs = fs
1950
+ self.mode = mode
1951
+ self.blocksize = (
1952
+ self.DEFAULT_BLOCK_SIZE if block_size in ["default", None] else block_size
1953
+ )
1954
+ self.loc = 0
1955
+ self.autocommit = autocommit
1956
+ self.end = None
1957
+ self.start = None
1958
+ self.closed = False
1959
+
1960
+ if cache_options is None:
1961
+ cache_options = {}
1962
+
1963
+ if "trim" in kwargs:
1964
+ warnings.warn(
1965
+ "Passing 'trim' to control the cache behavior has been deprecated. "
1966
+ "Specify it within the 'cache_options' argument instead.",
1967
+ FutureWarning,
1968
+ )
1969
+ cache_options["trim"] = kwargs.pop("trim")
1970
+
1971
+ self.kwargs = kwargs
1972
+
1973
+ if mode not in {"ab", "rb", "wb", "xb"}:
1974
+ raise NotImplementedError("File mode not supported")
1975
+ if mode == "rb":
1976
+ if size is not None:
1977
+ self.size = size
1978
+ else:
1979
+ self.size = self.details["size"]
1980
+ self.cache = caches[cache_type](
1981
+ self.blocksize, self._fetch_range, self.size, **cache_options
1982
+ )
1983
+ else:
1984
+ self.buffer = io.BytesIO()
1985
+ self.offset = None
1986
+ self.forced = False
1987
+ self.location = None
1988
+
1989
+ @property
1990
+ def details(self):
1991
+ if self._details is None:
1992
+ self._details = self.fs.info(self.path)
1993
+ return self._details
1994
+
1995
+ @details.setter
1996
+ def details(self, value):
1997
+ self._details = value
1998
+ self.size = value["size"]
1999
+
2000
+ @property
2001
+ def full_name(self):
2002
+ return _unstrip_protocol(self.path, self.fs)
2003
+
2004
+ @property
2005
+ def closed(self):
2006
+ # get around this attr being read-only in IOBase
2007
+ # use getattr here, since this can be called during del
2008
+ return getattr(self, "_closed", True)
2009
+
2010
+ @closed.setter
2011
+ def closed(self, c):
2012
+ self._closed = c
2013
+
2014
+ def __hash__(self):
2015
+ if "w" in self.mode:
2016
+ return id(self)
2017
+ else:
2018
+ return int(tokenize(self.details), 16)
2019
+
2020
+ def __eq__(self, other):
2021
+ """Files are equal if they have the same checksum, only in read mode"""
2022
+ if self is other:
2023
+ return True
2024
+ return (
2025
+ isinstance(other, type(self))
2026
+ and self.mode == "rb"
2027
+ and other.mode == "rb"
2028
+ and hash(self) == hash(other)
2029
+ )
2030
+
2031
+ def commit(self):
2032
+ """Move from temp to final destination"""
2033
+
2034
+ def discard(self):
2035
+ """Throw away temporary file"""
2036
+
2037
+ def info(self):
2038
+ """File information about this path"""
2039
+ if self.readable():
2040
+ return self.details
2041
+ else:
2042
+ raise ValueError("Info not available while writing")
2043
+
2044
+ def tell(self):
2045
+ """Current file location"""
2046
+ return self.loc
2047
+
2048
+ def seek(self, loc, whence=0):
2049
+ """Set current file location
2050
+
2051
+ Parameters
2052
+ ----------
2053
+ loc: int
2054
+ byte location
2055
+ whence: {0, 1, 2}
2056
+ from start of file, current location or end of file, resp.
2057
+ """
2058
+ loc = int(loc)
2059
+ if not self.mode == "rb":
2060
+ raise OSError(ESPIPE, "Seek only available in read mode")
2061
+ if whence == 0:
2062
+ nloc = loc
2063
+ elif whence == 1:
2064
+ nloc = self.loc + loc
2065
+ elif whence == 2:
2066
+ nloc = self.size + loc
2067
+ else:
2068
+ raise ValueError(f"invalid whence ({whence}, should be 0, 1 or 2)")
2069
+ if nloc < 0:
2070
+ raise ValueError("Seek before start of file")
2071
+ self.loc = nloc
2072
+ return self.loc
2073
+
2074
+ def write(self, data):
2075
+ """
2076
+ Write data to buffer.
2077
+
2078
+ Buffer only sent on flush() or if buffer is greater than
2079
+ or equal to blocksize.
2080
+
2081
+ Parameters
2082
+ ----------
2083
+ data: bytes
2084
+ Set of bytes to be written.
2085
+ """
2086
+ if not self.writable():
2087
+ raise ValueError("File not in write mode")
2088
+ if self.closed:
2089
+ raise ValueError("I/O operation on closed file.")
2090
+ if self.forced:
2091
+ raise ValueError("This file has been force-flushed, can only close")
2092
+ out = self.buffer.write(data)
2093
+ self.loc += out
2094
+ if self.buffer.tell() >= self.blocksize:
2095
+ self.flush()
2096
+ return out
2097
+
2098
+ def flush(self, force=False):
2099
+ """
2100
+ Write buffered data to backend store.
2101
+
2102
+ Writes the current buffer, if it is larger than the block-size, or if
2103
+ the file is being closed.
2104
+
2105
+ Parameters
2106
+ ----------
2107
+ force: bool
2108
+ When closing, write the last block even if it is smaller than
2109
+ blocks are allowed to be. Disallows further writing to this file.
2110
+ """
2111
+
2112
+ if self.closed:
2113
+ raise ValueError("Flush on closed file")
2114
+ if force and self.forced:
2115
+ raise ValueError("Force flush cannot be called more than once")
2116
+ if force:
2117
+ self.forced = True
2118
+
2119
+ if self.readable():
2120
+ # no-op to flush on read-mode
2121
+ return
2122
+
2123
+ if not force and self.buffer.tell() < self.blocksize:
2124
+ # Defer write on small block
2125
+ return
2126
+
2127
+ if self.offset is None:
2128
+ # Initialize a multipart upload
2129
+ self.offset = 0
2130
+ try:
2131
+ self._initiate_upload()
2132
+ except Exception:
2133
+ self.closed = True
2134
+ raise
2135
+
2136
+ if self._upload_chunk(final=force) is not False:
2137
+ self.offset += self.buffer.seek(0, 2)
2138
+ self.buffer = io.BytesIO()
2139
+
2140
+ def _upload_chunk(self, final=False):
2141
+ """Write one part of a multi-block file upload
2142
+
2143
+ Parameters
2144
+ ==========
2145
+ final: bool
2146
+ This is the last block, so should complete file, if
2147
+ self.autocommit is True.
2148
+ """
2149
+ # may not yet have been initialized, may need to call _initialize_upload
2150
+
2151
+ def _initiate_upload(self):
2152
+ """Create remote file/upload"""
2153
+ pass
2154
+
2155
+ def _fetch_range(self, start, end):
2156
+ """Get the specified set of bytes from remote"""
2157
+ return self.fs.cat_file(self.path, start=start, end=end)
2158
+
2159
+ def read(self, length=-1):
2160
+ """
2161
+ Return data from cache, or fetch pieces as necessary
2162
+
2163
+ Parameters
2164
+ ----------
2165
+ length: int (-1)
2166
+ Number of bytes to read; if <0, all remaining bytes.
2167
+ """
2168
+ length = -1 if length is None else int(length)
2169
+ if self.mode != "rb":
2170
+ raise ValueError("File not in read mode")
2171
+ if length < 0:
2172
+ length = self.size - self.loc
2173
+ if self.closed:
2174
+ raise ValueError("I/O operation on closed file.")
2175
+ if length == 0:
2176
+ # don't even bother calling fetch
2177
+ return b""
2178
+ out = self.cache._fetch(self.loc, self.loc + length)
2179
+
2180
+ logger.debug(
2181
+ "%s read: %i - %i %s",
2182
+ self,
2183
+ self.loc,
2184
+ self.loc + length,
2185
+ self.cache._log_stats(),
2186
+ )
2187
+ self.loc += len(out)
2188
+ return out
2189
+
2190
+ def readinto(self, b):
2191
+ """mirrors builtin file's readinto method
2192
+
2193
+ https://docs.python.org/3/library/io.html#io.RawIOBase.readinto
2194
+ """
2195
+ out = memoryview(b).cast("B")
2196
+ data = self.read(out.nbytes)
2197
+ out[: len(data)] = data
2198
+ return len(data)
2199
+
2200
+ def readuntil(self, char=b"\n", blocks=None):
2201
+ """Return data between current position and first occurrence of char
2202
+
2203
+ char is included in the output, except if the end of the tile is
2204
+ encountered first.
2205
+
2206
+ Parameters
2207
+ ----------
2208
+ char: bytes
2209
+ Thing to find
2210
+ blocks: None or int
2211
+ How much to read in each go. Defaults to file blocksize - which may
2212
+ mean a new read on every call.
2213
+ """
2214
+ out = []
2215
+ while True:
2216
+ start = self.tell()
2217
+ part = self.read(blocks or self.blocksize)
2218
+ if len(part) == 0:
2219
+ break
2220
+ found = part.find(char)
2221
+ if found > -1:
2222
+ out.append(part[: found + len(char)])
2223
+ self.seek(start + found + len(char))
2224
+ break
2225
+ out.append(part)
2226
+ return b"".join(out)
2227
+
2228
+ def readline(self):
2229
+ """Read until and including the first occurrence of newline character
2230
+
2231
+ Note that, because of character encoding, this is not necessarily a
2232
+ true line ending.
2233
+ """
2234
+ return self.readuntil(b"\n")
2235
+
2236
+ def __next__(self):
2237
+ out = self.readline()
2238
+ if out:
2239
+ return out
2240
+ raise StopIteration
2241
+
2242
+ def __iter__(self):
2243
+ return self
2244
+
2245
+ def readlines(self):
2246
+ """Return all data, split by the newline character, including the newline character"""
2247
+ data = self.read()
2248
+ lines = data.split(b"\n")
2249
+ out = [l + b"\n" for l in lines[:-1]]
2250
+ if data.endswith(b"\n"):
2251
+ return out
2252
+ else:
2253
+ return out + [lines[-1]]
2254
+ # return list(self) ???
2255
+
2256
+ def readinto1(self, b):
2257
+ return self.readinto(b)
2258
+
2259
+ def close(self):
2260
+ """Close file
2261
+
2262
+ Finalizes writes, discards cache
2263
+ """
2264
+ if getattr(self, "_unclosable", False):
2265
+ return
2266
+ if self.closed:
2267
+ return
2268
+ try:
2269
+ if self.mode == "rb":
2270
+ cache = getattr(self, "cache", None)
2271
+ if cache is not None:
2272
+ close = getattr(cache, "close", None)
2273
+ if callable(close):
2274
+ close()
2275
+ self.cache = None
2276
+ else:
2277
+ if not getattr(self, "forced", True):
2278
+ self.flush(force=True)
2279
+
2280
+ if self.fs is not None:
2281
+ self.fs.invalidate_cache(self.path)
2282
+ self.fs.invalidate_cache(self.fs._parent(self.path))
2283
+ finally:
2284
+ self.closed = True
2285
+
2286
+ def readable(self):
2287
+ """Whether opened for reading"""
2288
+ return "r" in self.mode and not self.closed
2289
+
2290
+ def seekable(self):
2291
+ """Whether is seekable (only in read mode)"""
2292
+ return self.readable()
2293
+
2294
+ def writable(self):
2295
+ """Whether opened for writing"""
2296
+ return self.mode in {"wb", "ab", "xb"} and not self.closed
2297
+
2298
+ def __reduce__(self):
2299
+ if self.mode != "rb":
2300
+ raise RuntimeError("Pickling a writeable file is not supported")
2301
+
2302
+ return reopen, (
2303
+ self.fs,
2304
+ self.path,
2305
+ self.mode,
2306
+ self.blocksize,
2307
+ self.loc,
2308
+ self.size,
2309
+ self.autocommit,
2310
+ self.cache.name if self.cache else "none",
2311
+ self.kwargs,
2312
+ )
2313
+
2314
+ def __del__(self):
2315
+ if not self.closed:
2316
+ self.close()
2317
+
2318
+ def __str__(self):
2319
+ return f"<File-like object {type(self.fs).__name__}, {self.path}>"
2320
+
2321
+ __repr__ = __str__
2322
+
2323
+ def __enter__(self):
2324
+ return self
2325
+
2326
+ def __exit__(self, *args):
2327
+ self.close()
2328
+
2329
+
2330
+ def reopen(fs, path, mode, blocksize, loc, size, autocommit, cache_type, kwargs):
2331
+ file = fs.open(
2332
+ path,
2333
+ mode=mode,
2334
+ block_size=blocksize,
2335
+ autocommit=autocommit,
2336
+ cache_type=cache_type,
2337
+ size=size,
2338
+ **kwargs,
2339
+ )
2340
+ if loc > 0:
2341
+ file.seek(loc)
2342
+ return file
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/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
.cache/uv/archive-v0/V5c0Q0k7mTLalPi1vkIGO/fsspec/utils.py ADDED
@@ -0,0 +1,757 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import contextlib
4
+ import logging
5
+ import math
6
+ import os
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
+
60
+ # Discover Windows paths including disk name in this special case.
61
+ is_filesystem = re.match(r"^[a-zA-Z]:[\\/]", urlpath)
62
+
63
+ # Discover URI according to RFC 3986: Scheme names consist of a
64
+ # sequence of characters beginning with a letter and followed by
65
+ # any combination of letters, digits, plus ("+"), period ("."),
66
+ # or hyphen ("-").
67
+ # https://datatracker.ietf.org/doc/html/rfc3986#section-3.1
68
+ is_uri = re.match(r"^[a-zA-Z0-9+.-]+://", urlpath)
69
+
70
+ if is_filesystem or is_uri is None:
71
+ return {"protocol": "file", "path": urlpath}
72
+
73
+ parsed_path = urlsplit(urlpath)
74
+ protocol = parsed_path.scheme or "file"
75
+ if parsed_path.fragment:
76
+ path = "#".join([parsed_path.path, parsed_path.fragment])
77
+ else:
78
+ path = parsed_path.path
79
+ if protocol == "file":
80
+ # Special case parsing file protocol URL on Windows according to:
81
+ # https://msdn.microsoft.com/en-us/library/jj710207.aspx
82
+ windows_path = re.match(r"^/([a-zA-Z])[:|]([\\/].*)$", path)
83
+ if windows_path:
84
+ drive, path = windows_path.groups()
85
+ path = f"{drive}:{path}"
86
+
87
+ if protocol in ["http", "https"]:
88
+ # for HTTP, we don't want to parse, as requests will anyway
89
+ return {"protocol": protocol, "path": urlpath}
90
+
91
+ options: dict[str, Any] = {"protocol": protocol, "path": path}
92
+
93
+ if parsed_path.netloc:
94
+ # Parse `hostname` from netloc manually because `parsed_path.hostname`
95
+ # lowercases the hostname which is not always desirable (e.g. in S3):
96
+ # https://github.com/dask/dask/issues/1417
97
+ options["host"] = parsed_path.netloc.rsplit("@", 1)[-1].rsplit(":", 1)[0]
98
+
99
+ if protocol in ("s3", "s3a", "gcs", "gs"):
100
+ options["path"] = options["host"] + options["path"]
101
+ else:
102
+ options["host"] = options["host"]
103
+ if parsed_path.port:
104
+ options["port"] = parsed_path.port
105
+ if parsed_path.username:
106
+ options["username"] = parsed_path.username
107
+ if parsed_path.password:
108
+ options["password"] = parsed_path.password
109
+
110
+ if parsed_path.query:
111
+ options["url_query"] = parsed_path.query
112
+ if parsed_path.fragment:
113
+ options["url_fragment"] = parsed_path.fragment
114
+
115
+ if inherit_storage_options:
116
+ update_storage_options(options, inherit_storage_options)
117
+
118
+ return options
119
+
120
+
121
+ def update_storage_options(
122
+ options: dict[str, Any], inherited: dict[str, Any] | None = None
123
+ ) -> None:
124
+ if not inherited:
125
+ inherited = {}
126
+ collisions = set(options) & set(inherited)
127
+ if collisions:
128
+ for collision in collisions:
129
+ if options.get(collision) != inherited.get(collision):
130
+ raise KeyError(
131
+ f"Collision between inferred and specified storage "
132
+ f"option:\n{collision}"
133
+ )
134
+ options.update(inherited)
135
+
136
+
137
+ # Compression extensions registered via fsspec.compression.register_compression
138
+ compressions: dict[str, str] = {}
139
+
140
+
141
+ def infer_compression(filename: str) -> str | None:
142
+ """Infer compression, if available, from filename.
143
+
144
+ Infer a named compression type, if registered and available, from filename
145
+ extension. This includes builtin (gz, bz2, zip) compressions, as well as
146
+ optional compressions. See fsspec.compression.register_compression.
147
+ """
148
+ extension = os.path.splitext(filename)[-1].strip(".").lower()
149
+ if extension in compressions:
150
+ return compressions[extension]
151
+ return None
152
+
153
+
154
+ def build_name_function(max_int: float) -> Callable[[int], str]:
155
+ """Returns a function that receives a single integer
156
+ and returns it as a string padded by enough zero characters
157
+ to align with maximum possible integer
158
+
159
+ >>> name_f = build_name_function(57)
160
+
161
+ >>> name_f(7)
162
+ '07'
163
+ >>> name_f(31)
164
+ '31'
165
+ >>> build_name_function(1000)(42)
166
+ '0042'
167
+ >>> build_name_function(999)(42)
168
+ '042'
169
+ >>> build_name_function(0)(0)
170
+ '0'
171
+ """
172
+ # handle corner cases max_int is 0 or exact power of 10
173
+ max_int += 1e-8
174
+
175
+ pad_length = int(math.ceil(math.log10(max_int)))
176
+
177
+ def name_function(i: int) -> str:
178
+ return str(i).zfill(pad_length)
179
+
180
+ return name_function
181
+
182
+
183
+ def seek_delimiter(file: IO[bytes], delimiter: bytes, blocksize: int) -> bool:
184
+ r"""Seek current file to file start, file end, or byte after delimiter seq.
185
+
186
+ Seeks file to next chunk delimiter, where chunks are defined on file start,
187
+ a delimiting sequence, and file end. Use file.tell() to see location afterwards.
188
+ Note that file start is a valid split, so must be at offset > 0 to seek for
189
+ delimiter.
190
+
191
+ Parameters
192
+ ----------
193
+ file: a file
194
+ delimiter: bytes
195
+ a delimiter like ``b'\n'`` or message sentinel, matching file .read() type
196
+ blocksize: int
197
+ Number of bytes to read from the file at once.
198
+
199
+
200
+ Returns
201
+ -------
202
+ Returns True if a delimiter was found, False if at file start or end.
203
+
204
+ """
205
+
206
+ if file.tell() == 0:
207
+ # beginning-of-file, return without seek
208
+ return False
209
+
210
+ # Interface is for binary IO, with delimiter as bytes, but initialize last
211
+ # with result of file.read to preserve compatibility with text IO.
212
+ last: bytes | None = None
213
+ while True:
214
+ current = file.read(blocksize)
215
+ if not current:
216
+ # end-of-file without delimiter
217
+ return False
218
+ full = last + current if last else current
219
+ try:
220
+ if delimiter in full:
221
+ i = full.index(delimiter)
222
+ file.seek(file.tell() - (len(full) - i) + len(delimiter))
223
+ return True
224
+ elif len(current) < blocksize:
225
+ # end-of-file without delimiter
226
+ return False
227
+ except (OSError, ValueError):
228
+ pass
229
+ last = full[-len(delimiter) :]
230
+
231
+
232
+ def read_block(
233
+ f: IO[bytes],
234
+ offset: int,
235
+ length: int | None,
236
+ delimiter: bytes | None = None,
237
+ split_before: bool = False,
238
+ ) -> bytes:
239
+ """Read a block of bytes from a file
240
+
241
+ Parameters
242
+ ----------
243
+ f: File
244
+ Open file
245
+ offset: int
246
+ Byte offset to start read
247
+ length: int
248
+ Number of bytes to read, read through end of file if None
249
+ delimiter: bytes (optional)
250
+ Ensure reading starts and stops at delimiter bytestring
251
+ split_before: bool (optional)
252
+ Start/stop read *before* delimiter bytestring.
253
+
254
+
255
+ If using the ``delimiter=`` keyword argument we ensure that the read
256
+ starts and stops at delimiter boundaries that follow the locations
257
+ ``offset`` and ``offset + length``. If ``offset`` is zero then we
258
+ start at zero, regardless of delimiter. The bytestring returned WILL
259
+ include the terminating delimiter string.
260
+
261
+ Examples
262
+ --------
263
+
264
+ >>> from io import BytesIO # doctest: +SKIP
265
+ >>> f = BytesIO(b'Alice, 100\\nBob, 200\\nCharlie, 300') # doctest: +SKIP
266
+ >>> read_block(f, 0, 13) # doctest: +SKIP
267
+ b'Alice, 100\\nBo'
268
+
269
+ >>> read_block(f, 0, 13, delimiter=b'\\n') # doctest: +SKIP
270
+ b'Alice, 100\\nBob, 200\\n'
271
+
272
+ >>> read_block(f, 10, 10, delimiter=b'\\n') # doctest: +SKIP
273
+ b'Bob, 200\\nCharlie, 300'
274
+ """
275
+ if delimiter:
276
+ f.seek(offset)
277
+ found_start_delim = seek_delimiter(f, delimiter, 2**16)
278
+ if length is None:
279
+ return f.read()
280
+ start = f.tell()
281
+ length -= start - offset
282
+
283
+ f.seek(start + length)
284
+ found_end_delim = seek_delimiter(f, delimiter, 2**16)
285
+ end = f.tell()
286
+
287
+ # Adjust split location to before delimiter if seek found the
288
+ # delimiter sequence, not start or end of file.
289
+ if found_start_delim and split_before:
290
+ start -= len(delimiter)
291
+
292
+ if found_end_delim and split_before:
293
+ end -= len(delimiter)
294
+
295
+ offset = start
296
+ length = end - start
297
+
298
+ f.seek(offset)
299
+
300
+ # TODO: allow length to be None and read to the end of the file?
301
+ assert length is not None
302
+ b = f.read(length)
303
+ return b
304
+
305
+
306
+ def tokenize(*args: Any, **kwargs: Any) -> str:
307
+ """Deterministic token
308
+
309
+ (modified from dask.base)
310
+
311
+ >>> tokenize([1, 2, '3'])
312
+ '9d71491b50023b06fc76928e6eddb952'
313
+
314
+ >>> tokenize('Hello') == tokenize('Hello')
315
+ True
316
+ """
317
+ if kwargs:
318
+ args += (kwargs,)
319
+ try:
320
+ h = md5(str(args).encode())
321
+ except ValueError:
322
+ # FIPS systems: https://github.com/fsspec/filesystem_spec/issues/380
323
+ h = md5(str(args).encode(), usedforsecurity=False)
324
+ return h.hexdigest()
325
+
326
+
327
+ def stringify_path(filepath: str | os.PathLike[str] | pathlib.Path) -> str:
328
+ """Attempt to convert a path-like object to a string.
329
+
330
+ Parameters
331
+ ----------
332
+ filepath: object to be converted
333
+
334
+ Returns
335
+ -------
336
+ filepath_str: maybe a string version of the object
337
+
338
+ Notes
339
+ -----
340
+ Objects supporting the fspath protocol are coerced according to its
341
+ __fspath__ method.
342
+
343
+ For backwards compatibility with older Python version, pathlib.Path
344
+ objects are specially coerced.
345
+
346
+ Any other object is passed through unchanged, which includes bytes,
347
+ strings, buffers, or anything else that's not even path-like.
348
+ """
349
+ if isinstance(filepath, str):
350
+ return filepath
351
+ elif hasattr(filepath, "__fspath__"):
352
+ return filepath.__fspath__()
353
+ elif hasattr(filepath, "path"):
354
+ return filepath.path
355
+ else:
356
+ return filepath # type: ignore[return-value]
357
+
358
+
359
+ def make_instance(
360
+ cls: Callable[..., T], args: Sequence[Any], kwargs: dict[str, Any]
361
+ ) -> T:
362
+ inst = cls(*args, **kwargs)
363
+ inst._determine_worker() # type: ignore[attr-defined]
364
+ return inst
365
+
366
+
367
+ def common_prefix(paths: Iterable[str]) -> str:
368
+ """For a list of paths, find the shortest prefix common to all"""
369
+ parts = [p.split("/") for p in paths]
370
+ lmax = min(len(p) for p in parts)
371
+ end = 0
372
+ for i in range(lmax):
373
+ end = all(p[i] == parts[0][i] for p in parts)
374
+ if not end:
375
+ break
376
+ i += end
377
+ return "/".join(parts[0][:i])
378
+
379
+
380
+ def other_paths(
381
+ paths: list[str],
382
+ path2: str | list[str],
383
+ exists: bool = False,
384
+ flatten: bool = False,
385
+ ) -> list[str]:
386
+ """In bulk file operations, construct a new file tree from a list of files
387
+
388
+ Parameters
389
+ ----------
390
+ paths: list of str
391
+ The input file tree
392
+ path2: str or list of str
393
+ Root to construct the new list in. If this is already a list of str, we just
394
+ assert it has the right number of elements.
395
+ exists: bool (optional)
396
+ For a str destination, it is already exists (and is a dir), files should
397
+ end up inside.
398
+ flatten: bool (optional)
399
+ Whether to flatten the input directory tree structure so that the output files
400
+ are in the same directory.
401
+
402
+ Returns
403
+ -------
404
+ list of str
405
+ """
406
+
407
+ if isinstance(path2, str):
408
+ path2 = path2.rstrip("/")
409
+
410
+ if flatten:
411
+ path2 = ["/".join((path2, p.split("/")[-1])) for p in paths]
412
+ else:
413
+ cp = common_prefix(paths)
414
+ if exists:
415
+ cp = cp.rsplit("/", 1)[0]
416
+ if not cp and all(not s.startswith("/") for s in paths):
417
+ path2 = ["/".join([path2, p]) for p in paths]
418
+ else:
419
+ path2 = [p.replace(cp, path2, 1) for p in paths]
420
+ else:
421
+ assert len(paths) == len(path2)
422
+ return path2
423
+
424
+
425
+ def is_exception(obj: Any) -> bool:
426
+ return isinstance(obj, BaseException)
427
+
428
+
429
+ def isfilelike(f: Any) -> TypeGuard[IO[bytes]]:
430
+ return all(hasattr(f, attr) for attr in ["read", "close", "tell"])
431
+
432
+
433
+ def get_protocol(url: str) -> str:
434
+ url = stringify_path(url)
435
+ parts = re.split(r"(\:\:|\://)", url, maxsplit=1)
436
+ if len(parts) > 1:
437
+ return parts[0]
438
+ return "file"
439
+
440
+
441
+ def get_file_extension(url: str) -> str:
442
+ url = stringify_path(url)
443
+ # Only consider the final path component: a "." in a parent directory name
444
+ # (e.g. "/path/to.dir/file") is not the file's extension.
445
+ ext_parts = url.rsplit("/", 1)[-1].rsplit(".", 1)
446
+ if len(ext_parts) > 1:
447
+ return ext_parts[-1]
448
+ return ""
449
+
450
+
451
+ def can_be_local(path: str) -> bool:
452
+ """Can the given URL be used with open_local?"""
453
+ from fsspec import get_filesystem_class
454
+
455
+ try:
456
+ return getattr(get_filesystem_class(get_protocol(path)), "local_file", False)
457
+ except (ValueError, ImportError):
458
+ # not in registry or import failed
459
+ return False
460
+
461
+
462
+ def get_package_version_without_import(name: str) -> str | None:
463
+ """For given package name, try to find the version without importing it
464
+
465
+ Import and package.__version__ is still the backup here, so an import
466
+ *might* happen.
467
+
468
+ Returns either the version string, or None if the package
469
+ or the version was not readily found.
470
+ """
471
+ if name in sys.modules:
472
+ mod = sys.modules[name]
473
+ if hasattr(mod, "__version__"):
474
+ return mod.__version__
475
+ try:
476
+ return version(name)
477
+ except: # noqa: E722
478
+ pass
479
+ try:
480
+ import importlib
481
+
482
+ mod = importlib.import_module(name)
483
+ return mod.__version__
484
+ except (ImportError, AttributeError):
485
+ return None
486
+
487
+
488
+ def setup_logging(
489
+ logger: logging.Logger | None = None,
490
+ logger_name: str | None = None,
491
+ level: str = "DEBUG",
492
+ clear: bool = True,
493
+ ) -> logging.Logger:
494
+ if logger is None and logger_name is None:
495
+ raise ValueError("Provide either logger object or logger name")
496
+ logger = logger or logging.getLogger(logger_name)
497
+ handle = logging.StreamHandler()
498
+ formatter = logging.Formatter(
499
+ "%(asctime)s - %(name)s - %(levelname)s - %(funcName)s -- %(message)s"
500
+ )
501
+ handle.setFormatter(formatter)
502
+ if clear:
503
+ logger.handlers.clear()
504
+ logger.addHandler(handle)
505
+ logger.setLevel(level)
506
+ return logger
507
+
508
+
509
+ def _unstrip_protocol(name: str, fs: AbstractFileSystem) -> str:
510
+ return fs.unstrip_protocol(name)
511
+
512
+
513
+ def mirror_from(
514
+ origin_name: str, methods: Iterable[str]
515
+ ) -> Callable[[type[T]], type[T]]:
516
+ """Mirror attributes and methods from the given
517
+ origin_name attribute of the instance to the
518
+ decorated class"""
519
+
520
+ def origin_getter(method: str, self: Any) -> Any:
521
+ origin = getattr(self, origin_name)
522
+ return getattr(origin, method)
523
+
524
+ def wrapper(cls: type[T]) -> type[T]:
525
+ for method in methods:
526
+ wrapped_method = partial(origin_getter, method)
527
+ setattr(cls, method, property(wrapped_method))
528
+ return cls
529
+
530
+ return wrapper
531
+
532
+
533
+ @contextlib.contextmanager
534
+ def nullcontext(obj: T) -> Iterator[T]:
535
+ yield obj
536
+
537
+
538
+ def merge_offset_ranges(
539
+ paths: list[str],
540
+ starts: list[int] | int,
541
+ ends: list[int] | int,
542
+ max_gap: int = 0,
543
+ max_block: int | None = None,
544
+ sort: bool = True,
545
+ ) -> tuple[list[str], list[int], list[int]]:
546
+ """Merge adjacent byte-offset ranges when the inter-range
547
+ gap is <= `max_gap`, and when the merged byte range does not
548
+ exceed `max_block` (if specified). By default, this function
549
+ will re-order the input paths and byte ranges to ensure sorted
550
+ order. If the user can guarantee that the inputs are already
551
+ sorted, passing `sort=False` will skip the re-ordering.
552
+ """
553
+ # Check input
554
+ if not isinstance(paths, list):
555
+ raise TypeError
556
+ if not isinstance(starts, list):
557
+ starts = [starts] * len(paths)
558
+ if not isinstance(ends, list):
559
+ ends = [ends] * len(paths)
560
+ if len(starts) != len(paths) or len(ends) != len(paths):
561
+ raise ValueError
562
+
563
+ # Early Return
564
+ if len(starts) <= 1:
565
+ return paths, starts, ends
566
+
567
+ starts = [s or 0 for s in starts]
568
+ # Sort by paths and then ranges if `sort=True`
569
+ if sort:
570
+ paths, starts, ends = (
571
+ list(v)
572
+ for v in zip(
573
+ *sorted(
574
+ zip(paths, starts, ends),
575
+ )
576
+ )
577
+ )
578
+ remove = []
579
+ for i, (path, start, end) in enumerate(zip(paths, starts, ends)):
580
+ if any(
581
+ e is not None and p == path and start >= s and end <= e and i != i2
582
+ for i2, (p, s, e) in enumerate(zip(paths, starts, ends))
583
+ ):
584
+ remove.append(i)
585
+ paths = [p for i, p in enumerate(paths) if i not in remove]
586
+ starts = [s for i, s in enumerate(starts) if i not in remove]
587
+ ends = [e for i, e in enumerate(ends) if i not in remove]
588
+
589
+ if paths:
590
+ # Loop through the coupled `paths`, `starts`, and
591
+ # `ends`, and merge adjacent blocks when appropriate
592
+ new_paths = paths[:1]
593
+ new_starts = starts[:1]
594
+ new_ends = ends[:1]
595
+ for i in range(1, len(paths)):
596
+ if paths[i] == paths[i - 1] and new_ends[-1] is None:
597
+ continue
598
+ elif (
599
+ paths[i] != paths[i - 1]
600
+ or ((starts[i] - new_ends[-1]) > max_gap)
601
+ or (max_block is not None and (ends[i] - new_starts[-1]) > max_block)
602
+ ):
603
+ # Cannot merge with previous block.
604
+ # Add new `paths`, `starts`, and `ends` elements
605
+ new_paths.append(paths[i])
606
+ new_starts.append(starts[i])
607
+ new_ends.append(ends[i])
608
+ else:
609
+ # Merge with the previous block by updating the
610
+ # last element of `ends`
611
+ new_ends[-1] = ends[i]
612
+ return new_paths, new_starts, new_ends
613
+
614
+ # `paths` is empty. Just return input lists
615
+ return paths, starts, ends
616
+
617
+
618
+ def file_size(filelike: IO[bytes]) -> int:
619
+ """Find length of any open read-mode file-like"""
620
+ pos = filelike.tell()
621
+ try:
622
+ return filelike.seek(0, 2)
623
+ finally:
624
+ filelike.seek(pos)
625
+
626
+
627
+ @contextlib.contextmanager
628
+ def atomic_write(path: str, mode: str = "wb"):
629
+ """
630
+ A context manager that opens a temporary file next to `path` and, on exit,
631
+ replaces `path` with the temporary file, thereby updating `path`
632
+ atomically.
633
+ """
634
+ fd, fn = tempfile.mkstemp(
635
+ dir=os.path.dirname(path), prefix=os.path.basename(path) + "-"
636
+ )
637
+ try:
638
+ with open(fd, mode) as fp:
639
+ yield fp
640
+ except BaseException:
641
+ with contextlib.suppress(FileNotFoundError):
642
+ os.unlink(fn)
643
+ raise
644
+ else:
645
+ os.replace(fn, path)
646
+
647
+
648
+ def _translate(pat, STAR, QUESTION_MARK):
649
+ # Copied from: https://github.com/python/cpython/pull/106703.
650
+ res: list[str] = []
651
+ add = res.append
652
+ i, n = 0, len(pat)
653
+ while i < n:
654
+ c = pat[i]
655
+ i = i + 1
656
+ if c == "*":
657
+ # compress consecutive `*` into one
658
+ if (not res) or res[-1] is not STAR:
659
+ add(STAR)
660
+ elif c == "?":
661
+ add(QUESTION_MARK)
662
+ elif c == "[":
663
+ j = i
664
+ if j < n and pat[j] == "!":
665
+ j = j + 1
666
+ if j < n and pat[j] == "]":
667
+ j = j + 1
668
+ while j < n and pat[j] != "]":
669
+ j = j + 1
670
+ if j >= n:
671
+ add("\\[")
672
+ else:
673
+ stuff = pat[i:j]
674
+ if "-" not in stuff:
675
+ stuff = stuff.replace("\\", r"\\")
676
+ else:
677
+ chunks = []
678
+ k = i + 2 if pat[i] == "!" else i + 1
679
+ while True:
680
+ k = pat.find("-", k, j)
681
+ if k < 0:
682
+ break
683
+ chunks.append(pat[i:k])
684
+ i = k + 1
685
+ k = k + 3
686
+ chunk = pat[i:j]
687
+ if chunk:
688
+ chunks.append(chunk)
689
+ else:
690
+ chunks[-1] += "-"
691
+ # Remove empty ranges -- invalid in RE.
692
+ for k in range(len(chunks) - 1, 0, -1):
693
+ if chunks[k - 1][-1] > chunks[k][0]:
694
+ chunks[k - 1] = chunks[k - 1][:-1] + chunks[k][1:]
695
+ del chunks[k]
696
+ # Escape backslashes and hyphens for set difference (--).
697
+ # Hyphens that create ranges shouldn't be escaped.
698
+ stuff = "-".join(
699
+ s.replace("\\", r"\\").replace("-", r"\-") for s in chunks
700
+ )
701
+ # Escape set operations (&&, ~~ and ||).
702
+ stuff = re.sub(r"([&~|])", r"\\\1", stuff)
703
+ i = j + 1
704
+ if not stuff:
705
+ # Empty range: never match.
706
+ add("(?!)")
707
+ elif stuff == "!":
708
+ # Negated empty range: match any character.
709
+ add(".")
710
+ else:
711
+ if stuff[0] == "!":
712
+ stuff = "^" + stuff[1:]
713
+ elif stuff[0] in ("^", "["):
714
+ stuff = "\\" + stuff
715
+ add(f"[{stuff}]")
716
+ else:
717
+ add(re.escape(c))
718
+ assert i == n
719
+ return res
720
+
721
+
722
+ def glob_translate(pat):
723
+ # Copied from: https://github.com/python/cpython/pull/106703.
724
+ # The keyword parameters' values are fixed to:
725
+ # recursive=True, include_hidden=True, seps=None
726
+ """Translate a pathname with shell wildcards to a regular expression."""
727
+ if os.path.altsep:
728
+ seps = os.path.sep + os.path.altsep
729
+ else:
730
+ seps = os.path.sep
731
+ escaped_seps = "".join(map(re.escape, seps))
732
+ any_sep = f"[{escaped_seps}]" if len(seps) > 1 else escaped_seps
733
+ not_sep = f"[^{escaped_seps}]"
734
+ one_last_segment = f"{not_sep}+"
735
+ one_segment = f"{one_last_segment}{any_sep}"
736
+ any_segments = f"(?:.+{any_sep})?"
737
+ any_last_segments = ".*"
738
+ results = []
739
+ parts = re.split(any_sep, pat)
740
+ last_part_idx = len(parts) - 1
741
+ for idx, part in enumerate(parts):
742
+ if part == "*":
743
+ results.append(one_segment if idx < last_part_idx else one_last_segment)
744
+ continue
745
+ if part == "**":
746
+ results.append(any_segments if idx < last_part_idx else any_last_segments)
747
+ continue
748
+ elif "**" in part:
749
+ raise ValueError(
750
+ "Invalid pattern: '**' can only be an entire path component"
751
+ )
752
+ if part:
753
+ results.extend(_translate(part, f"{not_sep}*", not_sep))
754
+ if idx < last_part_idx:
755
+ results.append(any_sep)
756
+ res = "".join(results)
757
+ return rf"(?s:{res})\Z"
.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/_hot_reload/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/_hot_reload/sse_client.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Vendored file: Server Side Events (SSE) client for Python.
3
+
4
+ Source:
5
+ - Author: Maxime Petazzoni <maxime.petazzoni@bulix.org>
6
+ - Repository: https://github.com/mpetazzoni/sseclient
7
+ - File: https://github.com/mpetazzoni/sseclient/blob/main/sseclient/__init__.py
8
+
9
+ License:
10
+ - Apache-2.0 (from upstream project)
11
+
12
+ Provides a generator of SSE received through an existing HTTP response.
13
+ """
14
+
15
+ import logging
16
+
17
+ __author__ = 'Maxime Petazzoni <maxime.petazzoni@bulix.org>'
18
+ __email__ = 'maxime.petazzoni@bulix.org'
19
+ __all__ = ['SSEClient']
20
+
21
+ _FIELD_SEPARATOR = ':'
22
+
23
+
24
+ class SSEClient:
25
+ """Implementation of a SSE client.
26
+
27
+ See http://www.w3.org/TR/2009/WD-eventsource-20091029/ for the
28
+ specification.
29
+ """
30
+
31
+ def __init__(self, event_source, char_enc='utf-8'):
32
+ """Initialize the SSE client over an existing, ready to consume
33
+ event source.
34
+
35
+ The event source is expected to be a binary stream and have a close()
36
+ method. That would usually be something that implements
37
+ io.BinaryIOBase, like an httplib or urllib3 HTTPResponse object.
38
+ """
39
+ self._logger = logging.getLogger(self.__class__.__module__)
40
+ self._logger.debug('Initialized SSE client from event source %s',
41
+ event_source)
42
+ self._event_source = event_source
43
+ self._char_enc = char_enc
44
+
45
+ def _read(self):
46
+ """Read the incoming event source stream and yield event chunks.
47
+
48
+ Unfortunately it is possible for some servers to decide to break an
49
+ event into multiple HTTP chunks in the response. It is thus necessary
50
+ to correctly stitch together consecutive response chunks and find the
51
+ SSE delimiter (empty new line) to yield full, correct event chunks."""
52
+ data = b''
53
+ for chunk in self._event_source:
54
+ for line in chunk.splitlines(True):
55
+ data += line
56
+ if data.endswith((b'\r\r', b'\n\n', b'\r\n\r\n')):
57
+ yield data
58
+ data = b''
59
+ if data:
60
+ yield data
61
+
62
+ def events(self):
63
+ for chunk in self._read():
64
+ event = Event()
65
+ # Split before decoding so splitlines() only uses \r and \n
66
+ for line in chunk.splitlines():
67
+ # Decode the line.
68
+ line = line.decode(self._char_enc)
69
+
70
+ # Lines starting with a separator are comments and are to be
71
+ # ignored.
72
+ if not line.strip() or line.startswith(_FIELD_SEPARATOR):
73
+ continue
74
+
75
+ data = line.split(_FIELD_SEPARATOR, 1)
76
+ field = data[0]
77
+
78
+ # Ignore unknown fields.
79
+ if field not in event.__dict__:
80
+ self._logger.debug('Saw invalid field %s while parsing '
81
+ 'Server Side Event', field)
82
+ continue
83
+
84
+ if len(data) > 1:
85
+ # From the spec:
86
+ # "If value starts with a single U+0020 SPACE character,
87
+ # remove it from value."
88
+ if data[1].startswith(' '):
89
+ value = data[1][1:]
90
+ else:
91
+ value = data[1]
92
+ else:
93
+ # If no value is present after the separator,
94
+ # assume an empty value.
95
+ value = ''
96
+
97
+ # The data field may come over multiple lines and their values
98
+ # are concatenated with each other.
99
+ if field == 'data':
100
+ event.__dict__[field] += value + '\n'
101
+ else:
102
+ event.__dict__[field] = value
103
+
104
+ # Events with no data are not dispatched.
105
+ if not event.data:
106
+ continue
107
+
108
+ # If the data field ends with a newline, remove it.
109
+ if event.data.endswith('\n'):
110
+ event.data = event.data[0:-1]
111
+
112
+ # Empty event names default to 'message'
113
+ event.event = event.event or 'message'
114
+
115
+ # Dispatch the event
116
+ self._logger.debug('Dispatching %s...', event)
117
+ yield event
118
+
119
+ def close(self):
120
+ """Manually close the event source stream."""
121
+ self._event_source.close()
122
+
123
+
124
+ class Event:
125
+ """Representation of an event from the event stream."""
126
+
127
+ def __init__(self, id=None, event='message', data='', retry=None):
128
+ self.id = id
129
+ self.event = event
130
+ self.data = data
131
+ self.retry = retry
132
+
133
+ def __str__(self):
134
+ s = f'{self.event} event'
135
+ if self.id:
136
+ s += f' #{self.id}'
137
+ if self.data:
138
+ s += ', {} byte{}'.format(len(self.data),
139
+ 's' if len(self.data) else '')
140
+ else:
141
+ s += ', no data'
142
+ if self.retry:
143
+ s += f', retry in {self.retry}ms'
144
+ return s
.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/_hot_reload/types.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ from typing import Literal, TypedDict
17
+
18
+ from typing_extensions import NotRequired
19
+
20
+
21
+ class ReloadRegion(TypedDict):
22
+ startLine: int
23
+ startCol: int
24
+ endLine: int
25
+ endCol: int
26
+
27
+
28
+ class ReloadOperationObject(TypedDict):
29
+ kind: Literal["add", "update", "delete"]
30
+ region: ReloadRegion
31
+ objectType: str
32
+ objectName: str
33
+
34
+
35
+ class ReloadOperationRun(TypedDict):
36
+ kind: Literal["run"]
37
+ region: ReloadRegion
38
+ codeLines: str
39
+ stdout: NotRequired[str]
40
+ stderr: NotRequired[str]
41
+
42
+
43
+ class ReloadOperationException(TypedDict):
44
+ kind: Literal["exception"]
45
+ region: ReloadRegion
46
+ traceback: str
47
+
48
+
49
+ class ReloadOperationError(TypedDict):
50
+ kind: Literal["error"]
51
+ traceback: str
52
+
53
+
54
+ class ReloadOperationUI(TypedDict):
55
+ kind: Literal["ui"]
56
+ updated: bool
57
+
58
+
59
+ class ReloadOperationFile(TypedDict):
60
+ kind: Literal["file"]
61
+ created: bool
62
+
63
+
64
+ class ApiCreateReloadRequest(TypedDict):
65
+ filepath: str
66
+ contents: str
67
+ reloadId: NotRequired[str]
68
+
69
+
70
+ class ApiCreateReloadResponseSuccess(TypedDict):
71
+ status: Literal["created"]
72
+ reloadId: str
73
+
74
+
75
+ class ApiCreateReloadResponseError(TypedDict):
76
+ status: Literal["alreadyReloading", "fileNotFound"]
77
+
78
+
79
+ class ApiCreateReloadResponse(TypedDict):
80
+ res: ApiCreateReloadResponseError | ApiCreateReloadResponseSuccess
81
+
82
+
83
+ class ApiGetReloadRequest(TypedDict):
84
+ reloadId: str
85
+
86
+
87
+ class ApiGetReloadEventSourceData(TypedDict):
88
+ data: (
89
+ ReloadOperationError
90
+ | ReloadOperationException
91
+ | ReloadOperationObject
92
+ | ReloadOperationRun
93
+ | ReloadOperationUI
94
+ | ReloadOperationFile
95
+ )
96
+
97
+
98
+ class ApiGetStatusRequest(TypedDict):
99
+ revision: str
100
+
101
+
102
+ class ApiGetStatusResponse(TypedDict):
103
+ reloading: bool
104
+ uncommited: list[str]
105
+
106
+
107
+ class ApiFetchContentsRequest(TypedDict):
108
+ filepath: str
109
+
110
+
111
+ class ApiFetchContentsResponseError(TypedDict):
112
+ status: Literal["fileNotFound"]
113
+
114
+
115
+ class ApiFetchContentsResponseSuccess(TypedDict):
116
+ status: Literal["ok"]
117
+ contents: str
118
+
119
+
120
+ class ApiFetchContentsResponse(TypedDict):
121
+ res: ApiFetchContentsResponseError | ApiFetchContentsResponseSuccess
.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/cli/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from huggingface_hub.cli._output import out # noqa: F401
.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/cli/_city_game.py ADDED
@@ -0,0 +1,661 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Interactive isometric city explorer — easter egg for `hf repos ls --explore`."""
2
+
3
+ import dataclasses
4
+ import math
5
+ import os
6
+ import random
7
+ import re
8
+ import select
9
+ import shutil
10
+ import sys
11
+ import time
12
+
13
+ from huggingface_hub.hf_api import RepoStorageInfo
14
+
15
+ from ._file_listing import format_size
16
+
17
+
18
+ Color = tuple[int, int, int]
19
+
20
+ # (top_face, left_face, right_face) — lighter to darker for 3D effect
21
+ _TYPE_COLORS: dict[str, tuple[Color, Color, Color]] = {
22
+ "model": ((175, 148, 240), (138, 112, 208), (105, 80, 180)),
23
+ "dataset": ((245, 128, 128), (222, 92, 92), (190, 60, 60)),
24
+ "space": ((245, 175, 85), (218, 140, 55), (185, 110, 30)),
25
+ "bucket": ((112, 185, 242), (70, 150, 220), (40, 118, 192)),
26
+ }
27
+ _EXTRA_COLORS: tuple[Color, Color, Color] = ((168, 176, 188), (128, 136, 148), (90, 98, 110))
28
+ _GRID_COLOR: Color = (178, 182, 190)
29
+
30
+ _DX = 4 # isometric half-width (pixels)
31
+ _DY = 2 # isometric half-height (pixels)
32
+ _MAX_H = 16 # tallest tile (pixels)
33
+ _MIN_H = 1
34
+ _COLS = 6
35
+ _EXT = 1 # grid extension beyond tiles
36
+ _MAX_TILES = 30
37
+
38
+ # Cursor sprite — pixel art arrow pointer
39
+ _OUTLINE: Color = (30, 30, 30)
40
+ _FILL: Color = (255, 255, 255)
41
+
42
+ _CURSOR_GRID = [
43
+ " X ",
44
+ " XWX ",
45
+ "XWWWX",
46
+ " XWX ",
47
+ " X ",
48
+ ]
49
+ _CURSOR_PALETTE: dict[str, Color] = {
50
+ "X": _OUTLINE,
51
+ "W": _FILL,
52
+ }
53
+ _CURSOR_H = len(_CURSOR_GRID)
54
+
55
+ _MOVE_FRAMES = 8
56
+ _MOVE_DELAY = 0.03
57
+ _CURSOR_PAD = _CURSOR_H + 16
58
+ _GAP = 3
59
+ _MIN_TERM_W = 100
60
+ _MIN_TERM_H = 24
61
+ _SUMMARY_W = 24
62
+
63
+
64
+ # ---------------------------------------------------------------------------
65
+ # Data structures
66
+ # ---------------------------------------------------------------------------
67
+
68
+
69
+ @dataclasses.dataclass
70
+ class TileInfo:
71
+ grid_row: int
72
+ grid_col: int
73
+ height: int
74
+ top: Color
75
+ left: Color
76
+ right: Color
77
+ repo: RepoStorageInfo | None
78
+
79
+
80
+ @dataclasses.dataclass
81
+ class CityData:
82
+ tiles: list[TileInfo]
83
+ rows: int
84
+ cols: int
85
+ x_off: int
86
+ y_off: int
87
+ buf_w: int
88
+ buf_h: int
89
+ total_storage: int
90
+ extra_count: int
91
+ extra_storage: int
92
+ all_repos: list[RepoStorageInfo]
93
+
94
+
95
+ # ---------------------------------------------------------------------------
96
+ # City layout
97
+ # ---------------------------------------------------------------------------
98
+
99
+
100
+ def _prepare_city_data(repos: list[RepoStorageInfo]) -> CityData:
101
+ sorted_repos = sorted(repos, key=lambda r: r.storage, reverse=True)
102
+ display = sorted_repos[:_MAX_TILES]
103
+ extra_count = max(0, len(sorted_repos) - _MAX_TILES)
104
+ extra_storage = sum(r.storage for r in sorted_repos[_MAX_TILES:])
105
+ total_storage = sum(r.storage for r in repos)
106
+ max_storage = max(1, display[0].storage)
107
+
108
+ n = len(display) + (1 if extra_count > 0 else 0)
109
+ cols = min(n, _COLS)
110
+ rows = math.ceil(n / cols) if cols > 0 else 1
111
+
112
+ tiles: list[TileInfo] = []
113
+ for i, repo in enumerate(display):
114
+ r, c = divmod(i, cols)
115
+ h = max(_MIN_H, round(math.sqrt(repo.storage / max_storage) * _MAX_H))
116
+ top, left, right = _TYPE_COLORS.get(repo.type, _EXTRA_COLORS)
117
+ tiles.append(TileInfo(r, c, h, top, left, right, repo))
118
+ if extra_count > 0:
119
+ r, c = divmod(len(display), cols)
120
+ h = max(_MIN_H, round(math.sqrt(extra_storage / max_storage) * _MAX_H))
121
+ tiles.append(TileInfo(r, c, h, *_EXTRA_COLORS, None))
122
+
123
+ r_lo, r_hi = -_EXT, rows - 1 + _EXT
124
+ c_lo, c_hi = -_EXT, cols - 1 + _EXT
125
+
126
+ xs: list[int] = []
127
+ ys: list[int] = []
128
+ for rr in range(r_lo, r_hi + 1):
129
+ for cc in range(c_lo, c_hi + 1):
130
+ cx, cy = (cc - rr) * _DX, (cc + rr) * _DY
131
+ xs.extend([cx - _DX, cx + _DX])
132
+ ys.extend([cy, cy + 2 * _DY])
133
+ for tile in tiles:
134
+ ys.append((tile.grid_col + tile.grid_row) * _DY - tile.height)
135
+
136
+ x_off = -min(xs)
137
+ y_off = -min(ys)
138
+ buf_w = max(xs) - min(xs) + 1
139
+ buf_h = max(ys) - min(ys) + 1
140
+ if buf_h % 2:
141
+ buf_h += 1
142
+
143
+ return CityData(
144
+ tiles=tiles,
145
+ rows=rows,
146
+ cols=cols,
147
+ x_off=x_off,
148
+ y_off=y_off,
149
+ buf_w=buf_w,
150
+ buf_h=buf_h,
151
+ total_storage=total_storage,
152
+ extra_count=extra_count,
153
+ extra_storage=extra_storage,
154
+ all_repos=repos,
155
+ )
156
+
157
+
158
+ # ---------------------------------------------------------------------------
159
+ # Drawing primitives
160
+ # ---------------------------------------------------------------------------
161
+
162
+
163
+ def _draw_diamond_outline(buf: list[list[Color | None]], cx: int, cy: int) -> None:
164
+ t = (cx, cy)
165
+ r = (cx + _DX, cy + _DY)
166
+ b = (cx, cy + 2 * _DY)
167
+ ll = (cx - _DX, cy + _DY)
168
+ _draw_line(buf, *t, *r, _GRID_COLOR)
169
+ _draw_line(buf, *r, *b, _GRID_COLOR)
170
+ _draw_line(buf, *b, *ll, _GRID_COLOR)
171
+ _draw_line(buf, *ll, *t, _GRID_COLOR)
172
+
173
+
174
+ def _draw_block(
175
+ buf: list[list[Color | None]],
176
+ cx: int,
177
+ cy: int,
178
+ h: int,
179
+ top: Color,
180
+ left: Color,
181
+ right: Color,
182
+ ) -> None:
183
+ _fill_poly(
184
+ buf,
185
+ [(cx - _DX, cy + _DY - h), (cx, cy + 2 * _DY - h), (cx, cy + 2 * _DY), (cx - _DX, cy + _DY)],
186
+ left,
187
+ )
188
+ _fill_poly(
189
+ buf,
190
+ [(cx, cy + 2 * _DY - h), (cx + _DX, cy + _DY - h), (cx + _DX, cy + _DY), (cx, cy + 2 * _DY)],
191
+ right,
192
+ )
193
+ _fill_poly(
194
+ buf,
195
+ [(cx, cy - h), (cx + _DX, cy + _DY - h), (cx, cy + 2 * _DY - h), (cx - _DX, cy + _DY - h)],
196
+ top,
197
+ )
198
+
199
+
200
+ def _fill_poly(buf: list[list[Color | None]], verts: list[tuple[int, int]], color: Color) -> None:
201
+ bh = len(buf)
202
+ bw = len(buf[0]) if buf else 0
203
+ all_y = [v[1] for v in verts]
204
+ y0 = max(0, min(all_y))
205
+ y1 = min(bh - 1, max(all_y))
206
+ n = len(verts)
207
+ for y in range(y0, y1 + 1):
208
+ xl: float = float("inf")
209
+ xr: float = float("-inf")
210
+ for i in range(n):
211
+ ax, ay = verts[i]
212
+ bx, by = verts[(i + 1) % n]
213
+ if ay == by:
214
+ if y == ay:
215
+ xl = min(xl, float(min(ax, bx)))
216
+ xr = max(xr, float(max(ax, bx)))
217
+ continue
218
+ if not (min(ay, by) <= y <= max(ay, by)):
219
+ continue
220
+ t = (y - ay) / (by - ay)
221
+ ix = ax + t * (bx - ax)
222
+ xl = min(xl, ix)
223
+ xr = max(xr, ix)
224
+ if xl <= xr:
225
+ for x in range(max(0, round(xl)), min(bw, round(xr) + 1)):
226
+ buf[y][x] = color
227
+
228
+
229
+ def _draw_line(buf: list[list[Color | None]], x0: int, y0: int, x1: int, y1: int, color: Color) -> None:
230
+ bh = len(buf)
231
+ bw = len(buf[0]) if buf else 0
232
+ dx = abs(x1 - x0)
233
+ dy = abs(y1 - y0)
234
+ steps = max(dx, dy)
235
+ if steps == 0:
236
+ if 0 <= y0 < bh and 0 <= x0 < bw:
237
+ buf[y0][x0] = color
238
+ return
239
+ xi = (x1 - x0) / steps
240
+ yi = (y1 - y0) / steps
241
+ fx, fy = float(x0), float(y0)
242
+ for _ in range(steps + 1):
243
+ px, py = round(fx), round(fy)
244
+ if 0 <= py < bh and 0 <= px < bw:
245
+ buf[py][px] = color
246
+ fx += xi
247
+ fy += yi
248
+
249
+
250
+ # ---------------------------------------------------------------------------
251
+ # Pixel buffer → terminal
252
+ # ---------------------------------------------------------------------------
253
+
254
+ _ANSI_RE = re.compile(r"\033\[[0-9;]*m")
255
+
256
+
257
+ def _strip_ansi(s: str) -> str:
258
+ return _ANSI_RE.sub("", s)
259
+
260
+
261
+ def _visible_len(s: str) -> int:
262
+ return len(_strip_ansi(s))
263
+
264
+
265
+ def _pixels_to_lines(buf: list[list[Color | None]]) -> list[str]:
266
+ height = len(buf)
267
+ width = len(buf[0]) if buf else 0
268
+ lines: list[str] = []
269
+ for row in range(0, height, 2):
270
+ last = -1
271
+ for col in range(width - 1, -1, -1):
272
+ top = buf[row][col]
273
+ bot = buf[row + 1][col] if row + 1 < height else None
274
+ if top or bot:
275
+ last = col
276
+ break
277
+ if last < 0:
278
+ lines.append("")
279
+ continue
280
+
281
+ parts: list[str] = []
282
+ cfg: Color | None = None
283
+ cbg: Color | None = None
284
+
285
+ for col in range(last + 1):
286
+ top = buf[row][col]
287
+ bot = buf[row + 1][col] if row + 1 < height else None
288
+
289
+ if not top and not bot:
290
+ if cfg is not None or cbg is not None:
291
+ parts.append("\033[0m")
292
+ cfg = cbg = None
293
+ parts.append(" ")
294
+ continue
295
+
296
+ if top and bot and top == bot:
297
+ nfg, nbg, ch = top, None, "█"
298
+ elif top and bot:
299
+ nfg, nbg, ch = bot, top, "▄"
300
+ elif top:
301
+ nfg, nbg, ch = top, None, "▀"
302
+ else:
303
+ nfg, nbg, ch = bot, None, "▄" # type: ignore[assignment]
304
+
305
+ esc = ""
306
+ if nfg != cfg:
307
+ esc += f"\033[38;2;{nfg[0]};{nfg[1]};{nfg[2]}m"
308
+ cfg = nfg
309
+ if nbg != cbg:
310
+ esc += "\033[49m" if nbg is None else f"\033[48;2;{nbg[0]};{nbg[1]};{nbg[2]}m"
311
+ cbg = nbg
312
+ parts.append(esc + ch)
313
+
314
+ if cfg is not None or cbg is not None:
315
+ parts.append("\033[0m")
316
+ lines.append("".join(parts))
317
+ return lines
318
+
319
+
320
+ # ---------------------------------------------------------------------------
321
+ # Rendering
322
+ # ---------------------------------------------------------------------------
323
+
324
+
325
+ def _render_base_buffer(city: CityData) -> list[list[Color | None]]:
326
+ buf: list[list[Color | None]] = [[None] * city.buf_w for _ in range(city.buf_h)]
327
+
328
+ for tile in city.tiles:
329
+ cx = city.x_off + (tile.grid_col - tile.grid_row) * _DX
330
+ cy = city.y_off + (tile.grid_col + tile.grid_row) * _DY
331
+ _draw_diamond_outline(buf, cx, cy)
332
+
333
+ sorted_tiles = sorted(city.tiles, key=lambda t: (t.grid_row + t.grid_col, t.grid_col))
334
+ for tile in sorted_tiles:
335
+ cx = city.x_off + (tile.grid_col - tile.grid_row) * _DX
336
+ cy = city.y_off + (tile.grid_col + tile.grid_row) * _DY
337
+ _draw_block(buf, cx, cy, tile.height, tile.top, tile.left, tile.right)
338
+
339
+ return buf
340
+
341
+
342
+ # ---------------------------------------------------------------------------
343
+ # Summary panel
344
+ # ---------------------------------------------------------------------------
345
+
346
+
347
+ def _colored_square(color: Color) -> str:
348
+ return f"\033[38;2;{color[0]};{color[1]};{color[2]}m■\033[0m"
349
+
350
+
351
+ def _build_summary(
352
+ repos: list[RepoStorageInfo],
353
+ total_storage: int,
354
+ extra_count: int,
355
+ ) -> list[str]:
356
+ lines: list[str] = [""]
357
+ lines.append(" Storage Overview")
358
+ lines.append(" " + "─" * 16)
359
+ lines.append(f" {format_size(total_storage, human_readable=True)} total")
360
+ lines.append("")
361
+
362
+ order = ["model", "dataset", "space", "bucket"]
363
+ labels = {"model": "Models", "dataset": "Datasets", "space": "Spaces", "bucket": "Buckets"}
364
+ for rtype in order:
365
+ group = [r for r in repos if r.type == rtype]
366
+ if not group:
367
+ continue
368
+ storage = sum(r.storage for r in group)
369
+ sq = _colored_square(_TYPE_COLORS[rtype][0])
370
+ lines.append(f" {sq} {labels[rtype]}")
371
+ lines.append(f" {len(group)} repos · {format_size(storage, human_readable=True)}")
372
+ lines.append("")
373
+
374
+ if extra_count > 0:
375
+ sq = _colored_square(_EXTRA_COLORS[0])
376
+ lines.append(f" {sq} +{extra_count} more repos")
377
+
378
+ return lines
379
+
380
+
381
+ # ---------------------------------------------------------------------------
382
+ # Cursor
383
+ # ---------------------------------------------------------------------------
384
+
385
+
386
+ def _build_cursor() -> list[tuple[int, int, Color]]:
387
+ pixels: list[tuple[int, int, Color]] = []
388
+ for ri, row in enumerate(_CURSOR_GRID):
389
+ for ci, ch in enumerate(row):
390
+ if ch in _CURSOR_PALETTE:
391
+ pixels.append((ci - len(row) // 2, ri - _CURSOR_H + 1, _CURSOR_PALETTE[ch]))
392
+ return pixels
393
+
394
+
395
+ _CURSOR_PIXELS = _build_cursor()
396
+
397
+
398
+ # ---------------------------------------------------------------------------
399
+ # Interactive game
400
+ # ---------------------------------------------------------------------------
401
+
402
+
403
+ def run_city_game(repos: list[RepoStorageInfo]) -> None:
404
+ """Launch the interactive city explorer."""
405
+ if not repos:
406
+ print("No repositories found.")
407
+ return
408
+
409
+ try:
410
+ import termios
411
+ import tty
412
+ except ImportError:
413
+ print("Interactive mode requires a Unix-like terminal (Linux/macOS).")
414
+ return
415
+
416
+ if not sys.stdin.isatty() or not sys.stdout.isatty():
417
+ print("Interactive mode requires a terminal.")
418
+ return
419
+
420
+ term = shutil.get_terminal_size()
421
+ if term.columns < _MIN_TERM_W or term.lines < _MIN_TERM_H:
422
+ print(f"Your terminal is {term.columns}×{term.lines} characters.")
423
+ print(f"Please resize to at least {_MIN_TERM_W}×{_MIN_TERM_H} to explore the city!")
424
+ return
425
+
426
+ city = _prepare_city_data(repos)
427
+
428
+ tiles_with_repos = [t for t in city.tiles if t.repo is not None]
429
+ start_tile = random.choice(tiles_with_repos) if tiles_with_repos else city.tiles[0]
430
+
431
+ fd = sys.stdin.fileno()
432
+ old_settings = termios.tcgetattr(fd)
433
+ try:
434
+ tty.setraw(fd)
435
+ sys.stdout.write("\033[?1049h\033[?25l\033[2J")
436
+ sys.stdout.flush()
437
+ _game_loop(city, start_tile.grid_row, start_tile.grid_col)
438
+ finally:
439
+ sys.stdout.write("\033[?25h\033[?1049l")
440
+ sys.stdout.flush()
441
+ termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
442
+
443
+
444
+ def _game_loop(city: CityData, cur_row: int, cur_col: int) -> None:
445
+ tile_map: dict[tuple[int, int], TileInfo] = {(t.grid_row, t.grid_col): t for t in city.tiles}
446
+ city = dataclasses.replace(city, buf_h=city.buf_h + _CURSOR_PAD, y_off=city.y_off + _CURSOR_PAD)
447
+ base_buf = _render_base_buffer(city)
448
+
449
+ summary = _build_summary(city.all_repos, city.total_storage, city.extra_count)
450
+
451
+ # Intro: cursor drops onto starting tile
452
+ tx, ty = _tile_top_center(city, cur_row, cur_col, tile_map)
453
+ for i in range(1, _MOVE_FRAMES + 1):
454
+ t = i / _MOVE_FRAMES
455
+ t = t * t * (3 - 2 * t)
456
+ drop_y = ty - 16 * (1 - t)
457
+ frame = _copy_buf(base_buf)
458
+ _highlight_tile(frame, city, tile_map[(cur_row, cur_col)])
459
+ _draw_cursor(frame, tx, round(drop_y))
460
+ _present(city, frame, tile_map.get((cur_row, cur_col)), summary)
461
+ time.sleep(_MOVE_DELAY)
462
+
463
+ while True:
464
+ cx, cy = _tile_top_center(city, cur_row, cur_col, tile_map)
465
+ frame = _copy_buf(base_buf)
466
+ _highlight_tile(frame, city, tile_map[(cur_row, cur_col)])
467
+ _draw_cursor(frame, cx, cy)
468
+ _present(city, frame, tile_map.get((cur_row, cur_col)), summary)
469
+
470
+ key = _read_key()
471
+ if key in ("q", "Q", "esc", "\x03"):
472
+ return
473
+
474
+ dr, dc = _key_to_direction(key)
475
+ if dr == 0 and dc == 0:
476
+ continue
477
+
478
+ nr, nc = cur_row + dr, cur_col + dc
479
+ if (nr, nc) not in tile_map:
480
+ continue
481
+
482
+ ex, ey = _tile_top_center(city, nr, nc, tile_map)
483
+ for i in range(1, _MOVE_FRAMES + 1):
484
+ t = i / _MOVE_FRAMES
485
+ t = t * t * (3 - 2 * t)
486
+ bx = cx + (ex - cx) * t
487
+ by = cy + (ey - cy) * t
488
+ frame = _copy_buf(base_buf)
489
+ _highlight_tile(frame, city, tile_map[(nr, nc)])
490
+ _draw_cursor(frame, round(bx), round(by))
491
+ _present(city, frame, tile_map.get((nr, nc)), summary)
492
+ time.sleep(_MOVE_DELAY)
493
+
494
+ cur_row, cur_col = nr, nc
495
+
496
+
497
+ def _tile_top_center(city: CityData, row: int, col: int, tile_map: dict[tuple[int, int], TileInfo]) -> tuple[int, int]:
498
+ tile = tile_map.get((row, col))
499
+ h = tile.height if tile else 1
500
+ cx = city.x_off + (col - row) * _DX
501
+ cy = city.y_off + (col + row) * _DY
502
+ return cx, cy + _DY - h
503
+
504
+
505
+ def _key_to_direction(key: str) -> tuple[int, int]:
506
+ match key:
507
+ case "w" | "W" | "\x1b[A":
508
+ return -1, 0
509
+ case "s" | "S" | "\x1b[B":
510
+ return 1, 0
511
+ case "a" | "A" | "\x1b[D":
512
+ return 0, -1
513
+ case "d" | "D" | "\x1b[C":
514
+ return 0, 1
515
+ case _:
516
+ return 0, 0
517
+
518
+
519
+ def _draw_cursor(buf: list[list[Color | None]], cx: int, cy: int) -> None:
520
+ bh = len(buf)
521
+ bw = len(buf[0]) if buf else 0
522
+ for dx, dy, color in _CURSOR_PIXELS:
523
+ px, py = cx + dx, cy + dy
524
+ if 0 <= py < bh and 0 <= px < bw:
525
+ buf[py][px] = color
526
+
527
+
528
+ def _highlight_tile(buf: list[list[Color | None]], city: CityData, tile: TileInfo) -> None:
529
+ cx = city.x_off + (tile.grid_col - tile.grid_row) * _DX
530
+ cy = city.y_off + (tile.grid_col + tile.grid_row) * _DY
531
+ h = tile.height
532
+ _fill_poly(
533
+ buf,
534
+ [(cx, cy - h), (cx + _DX, cy + _DY - h), (cx, cy + 2 * _DY - h), (cx - _DX, cy + _DY - h)],
535
+ _brighten(tile.top, 35),
536
+ )
537
+
538
+
539
+ def _brighten(color: Color, amount: int) -> Color:
540
+ return (min(255, color[0] + amount), min(255, color[1] + amount), min(255, color[2] + amount))
541
+
542
+
543
+ def _present(
544
+ city: CityData,
545
+ buf: list[list[Color | None]],
546
+ tile: TileInfo | None,
547
+ summary: list[str],
548
+ ) -> None:
549
+ city_lines = _pixels_to_lines(buf)
550
+ while city_lines and not _strip_ansi(city_lines[0]).strip():
551
+ city_lines.pop(0)
552
+ while city_lines and not _strip_ansi(city_lines[-1]).strip():
553
+ city_lines.pop()
554
+
555
+ city_w = max((_visible_len(line) for line in city_lines), default=0)
556
+ term = shutil.get_terminal_size()
557
+ panel_max_w = max(20, term.columns - city_w - _SUMMARY_W - 2 * _GAP)
558
+
559
+ info = _build_info_panel(tile, city, panel_max_w)
560
+
561
+ n = max(len(summary), len(city_lines), len(info))
562
+ summary_lo = max(0, (n - len(summary)) // 2)
563
+ info_lo = max(0, (n - len(info)) // 2)
564
+
565
+ lines: list[str] = []
566
+ for i in range(n):
567
+ si = i - summary_lo
568
+ lt = summary[si] if 0 <= si < len(summary) else ""
569
+ lpad = max(0, _SUMMARY_W - _visible_len(lt))
570
+
571
+ ct = city_lines[i] if i < len(city_lines) else ""
572
+ cpad = max(0, city_w - _visible_len(ct))
573
+
574
+ ri = i - info_lo
575
+ rt = info[ri] if 0 <= ri < len(info) else ""
576
+
577
+ lines.append(lt + " " * lpad + " " * _GAP + ct + " " * cpad + " " * _GAP + rt)
578
+
579
+ lines.append("")
580
+ lines.append(" \033[90mWASD/Arrows: move · Q/ESC: quit\033[0m")
581
+
582
+ while len(lines) < term.lines - 1:
583
+ lines.append("")
584
+
585
+ output = "\033[H"
586
+ for line in lines[: term.lines - 1]:
587
+ output += line + "\033[K\r\n"
588
+ sys.stdout.write(output)
589
+ sys.stdout.flush()
590
+
591
+
592
+ def _build_info_panel(tile: TileInfo | None, city: CityData, max_w: int) -> list[str]:
593
+ reset = "\033[0m"
594
+ gray = "\033[90m"
595
+ bold = "\033[1m"
596
+ indent = " "
597
+ content_w = max_w - len(indent)
598
+
599
+ lines: list[str] = [""]
600
+ lines.append(f"{indent}{bold}City Explorer{reset}")
601
+ lines.append(indent + "─" * min(22, content_w))
602
+ lines.append("")
603
+
604
+ if tile is None:
605
+ lines.append(f"{indent}{gray}Move to a tile")
606
+ lines.append(f"{indent}to see details.{reset}")
607
+ return lines
608
+
609
+ if tile.repo is None:
610
+ lines.append(f"{indent}{gray}+{city.extra_count} more repos{reset}")
611
+ lines.append(f"{indent}{gray}{format_size(city.extra_storage, human_readable=True)} combined{reset}")
612
+ return lines
613
+
614
+ repo = tile.repo
615
+ name = repo.id
616
+ if len(name) > content_w:
617
+ name = name[: content_w - 3] + "..."
618
+ lines.append(f"{indent}{bold}{name}{reset}")
619
+ lines.append("")
620
+
621
+ type_ansi = {
622
+ "model": "\033[38;2;175;148;240m",
623
+ "dataset": "\033[38;2;245;128;128m",
624
+ "space": "\033[38;2;245;175;85m",
625
+ "bucket": "\033[38;2;112;185;242m",
626
+ }
627
+ tc = type_ansi.get(repo.type, "")
628
+
629
+ lines.append(f"{indent}Type {tc}{repo.type}{reset}")
630
+ lines.append(f"{indent}Visibility {repo.visibility}")
631
+ lines.append(f"{indent}Storage {format_size(repo.storage, human_readable=True)}")
632
+ lines.append(f"{indent}Usage {repo.storage_percent:.1f}%")
633
+ lines.append("")
634
+
635
+ bar_w = min(18, content_w)
636
+ filled = max(0, min(bar_w, round(repo.storage_percent / 100 * bar_w)))
637
+ lines.append(f"{indent}{tc}{'█' * filled}{gray}{'░' * (bar_w - filled)}{reset}")
638
+
639
+ return lines
640
+
641
+
642
+ def _copy_buf(buf: list[list[Color | None]]) -> list[list[Color | None]]:
643
+ return [row[:] for row in buf]
644
+
645
+
646
+ def _read_key() -> str:
647
+ fd = sys.stdin.fileno()
648
+ ch = os.read(fd, 1)
649
+ if ch == b"\x1b":
650
+ if _has_input(fd, 0.05):
651
+ ch2 = os.read(fd, 1)
652
+ if ch2 == b"[" and _has_input(fd, 0.05):
653
+ ch3 = os.read(fd, 1)
654
+ return f"\x1b[{ch3.decode()}"
655
+ return "esc"
656
+ return ch.decode("utf-8", errors="replace")
657
+
658
+
659
+ def _has_input(fd: int, timeout: float) -> bool:
660
+ r, _, _ = select.select([fd], [], [], timeout)
661
+ return bool(r)
.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/cli/_completion.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Shell completion for the ``hf`` CLI, built on Click's native completion.
15
+
16
+ Click generates completion scripts activated by the ``_HF_COMPLETE`` env var (this
17
+ works out of the box because ``hf`` is a Click command). This module exposes the two
18
+ conveniences Typer used to provide — ``--install-completion`` / ``--show-completion``
19
+ — as thin eager options over that machinery.
20
+ """
21
+
22
+ import os
23
+ from pathlib import Path
24
+ from typing import Annotated
25
+
26
+ import click
27
+ from click.shell_completion import get_completion_class
28
+
29
+ from ._framework import Option
30
+
31
+
32
+ _COMPLETE_VAR = "_HF_COMPLETE"
33
+
34
+ # Shells with a shared rc file: the line that activates completion (appended once).
35
+ _RC_ACTIVATION: dict[str, tuple[Path, str]] = {
36
+ "bash": (Path.home() / ".bashrc", f'eval "$({_COMPLETE_VAR}=bash_source hf)"'),
37
+ "zsh": (Path.home() / ".zshrc", f'eval "$({_COMPLETE_VAR}=zsh_source hf)"'),
38
+ }
39
+ # Fish auto-loads per-command files from its completions directory. The file is dedicated
40
+ # to `hf`, so the full script is written there directly (overwriting any stale version)
41
+ # instead of re-generating it via `hf` on every shell startup.
42
+ _FISH_COMPLETION_PATH = Path.home() / ".config" / "fish" / "completions" / "hf.fish"
43
+
44
+
45
+ def _detect_shell() -> str:
46
+ return Path(os.environ.get("SHELL", "")).name or "bash"
47
+
48
+
49
+ def _completion_script(shell: str) -> str:
50
+ # Imported lazily to avoid a circular import (hf.py imports the options below).
51
+ from .hf import app
52
+
53
+ completion_cls = get_completion_class(shell)
54
+ if completion_cls is None:
55
+ raise click.ClickException(f"Shell '{shell}' is not supported for completion.")
56
+ return completion_cls(app, {}, "hf", _COMPLETE_VAR).source()
57
+
58
+
59
+ def _show_completion(value: bool) -> None:
60
+ if not value:
61
+ return
62
+ click.echo(_completion_script(_detect_shell()))
63
+ raise click.exceptions.Exit()
64
+
65
+
66
+ def _install_completion(value: bool) -> None:
67
+ if not value:
68
+ return
69
+ shell = _detect_shell()
70
+ if shell == "fish":
71
+ path = _FISH_COMPLETION_PATH
72
+ path.parent.mkdir(parents=True, exist_ok=True)
73
+ path.write_text(_completion_script("fish"))
74
+ elif shell in _RC_ACTIVATION:
75
+ path, activation = _RC_ACTIVATION[shell]
76
+ path.parent.mkdir(parents=True, exist_ok=True)
77
+ existing = path.read_text() if path.exists() else ""
78
+ if activation not in existing:
79
+ with path.open("a") as file:
80
+ file.write(f"\n{activation}\n")
81
+ else:
82
+ raise click.ClickException(f"Shell '{shell}' is not supported for completion.")
83
+ click.echo(f"{shell} completion installed in {path}. Restart your shell for it to take effect.")
84
+ raise click.exceptions.Exit()
85
+
86
+
87
+ InstallCompletionOpt = Annotated[
88
+ bool,
89
+ Option(
90
+ "--install-completion",
91
+ callback=_install_completion,
92
+ is_eager=True,
93
+ help="Install completion for the current shell.",
94
+ ),
95
+ ]
96
+
97
+ ShowCompletionOpt = Annotated[
98
+ bool,
99
+ Option(
100
+ "--show-completion",
101
+ callback=_show_completion,
102
+ is_eager=True,
103
+ help="Show completion for the current shell, to copy it or customize the installation.",
104
+ ),
105
+ ]
.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/cli/_cp.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026-present, the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Shared ``cp`` command to copy files between local paths, repositories and buckets.
15
+
16
+ This single command backs three identical CLI entry points: ``hf cp`` (top-level),
17
+ ``hf repos cp`` and ``hf buckets cp``. It supports any source/destination combination
18
+ of local file, repo/bucket ``hf://`` URI, and ``-`` (stdin/stdout), with two exceptions:
19
+ - bucket-to-repo copies are not supported (server limitation), and
20
+ - local-to-local copies (use a regular ``cp`` for that).
21
+ """
22
+
23
+ import os
24
+ import sys
25
+ from dataclasses import replace
26
+ from typing import Annotated, Literal
27
+
28
+ import click
29
+
30
+ from huggingface_hub import HfApi
31
+ from huggingface_hub.errors import CLIError
32
+ from huggingface_hub.utils import HfUri, SoftTemporaryDirectory, disable_progress_bars, is_hf_uri, parse_hf_uri
33
+
34
+ from ._cli_utils import TokenOpt, get_hf_api
35
+ from ._framework import Argument
36
+ from ._output import out
37
+
38
+
39
+ CP_EXAMPLES = [
40
+ # Download (repo or bucket -> local / stdout)
41
+ "hf cp hf://username/my-model/config.json",
42
+ "hf cp hf://username/my-model/config.json ./config.json",
43
+ "hf cp hf://datasets/username/my-dataset/data.csv ./data/",
44
+ "hf cp hf://buckets/username/my-bucket/config.json -",
45
+ # Upload (local / stdin -> repo or bucket)
46
+ "hf cp ./model.safetensors hf://username/my-model/model.safetensors",
47
+ "hf cp ./config.json hf://buckets/username/my-bucket/logs/",
48
+ "hf cp - hf://buckets/username/my-bucket/config.json",
49
+ # Remote to remote (repo/bucket -> repo/bucket, server-side when possible)
50
+ "hf cp hf://username/source-model/ hf://username/dest-model/",
51
+ "hf cp hf://datasets/username/my-dataset/processed/ hf://buckets/username/my-bucket/processed/",
52
+ "hf cp hf://buckets/username/my-bucket/logs/ hf://buckets/username/archive-bucket/ # copies contents only",
53
+ ]
54
+
55
+
56
+ # Which alias registered the command, used to restrict the remote endpoint type (see `_enforce_context`).
57
+ CpContext = Literal["repos", "buckets"]
58
+
59
+
60
+ def make_cp(context: CpContext | None = None):
61
+ """Build the ``cp`` command function for a given alias.
62
+
63
+ The three entry points (`hf cp`, `hf repos cp`, `hf buckets cp`) share the exact same logic;
64
+ 'context' only adds a guardrail on the remote endpoint type (see `_enforce_context`).
65
+ """
66
+
67
+ def cp(
68
+ src: Annotated[
69
+ str,
70
+ Argument(help="Source: local file, hf:// URI (repo or bucket), or - for stdin."),
71
+ ],
72
+ dst: Annotated[
73
+ str | None,
74
+ Argument(help="Destination: local path, hf:// URI (repo or bucket), or - for stdout."),
75
+ ] = None,
76
+ token: TokenOpt = None,
77
+ ) -> None:
78
+ """Copy files between local paths, repositories, and buckets.
79
+
80
+ Handles uploads (local/stdin -> repo/bucket), downloads (repo/bucket -> local/stdout) and
81
+ remote-to-remote copies (repo/bucket -> repo/bucket). Bucket-to-repo and local-to-local
82
+ copies are not supported. For directories, use `hf upload`/`hf download` (repos) or
83
+ `hf buckets sync` (buckets). Remote-to-remote copies only work within the same storage
84
+ region (https://huggingface.co/docs/hub/storage-regions).
85
+ """
86
+ _enforce_context(context, src, dst)
87
+ _run_cp(src, dst, token)
88
+
89
+ return cp
90
+
91
+
92
+ def _enforce_context(context: CpContext | None, src: str, dst: str | None) -> None:
93
+ """Guardrail for the `hf repos cp` / `hf buckets cp` aliases.
94
+
95
+ These aliases are exact duplicates of `hf cp`, so a bare `hf repos cp` could otherwise touch a
96
+ bucket (and vice versa). We validate the type of the remote side: the destination for uploads and
97
+ remote-to-remote copies, or the source when downloading to a local path / stdout. The top-level
98
+ `hf cp` (i.e. 'context' is None) accepts any combination.
99
+ """
100
+ if context is None:
101
+ return
102
+ # The remote endpoint is the destination when it is an hf:// URI, otherwise the source (download).
103
+ remote = dst if (dst is not None and is_hf_uri(dst)) else src
104
+ if not is_hf_uri(remote):
105
+ return
106
+ if context == "repos" and parse_hf_uri(remote).is_bucket:
107
+ raise CLIError("`hf repos cp` only works with repositories. Use `hf cp` or `hf buckets cp` for buckets.")
108
+ if context == "buckets" and not parse_hf_uri(remote).is_bucket:
109
+ raise CLIError("`hf buckets cp` only works with buckets. Use `hf cp` or `hf repos cp` for repositories.")
110
+
111
+
112
+ def _run_cp(src: str, dst: str | None, token: str | None) -> None:
113
+ api = get_hf_api(token=token)
114
+
115
+ src_is_stdin = src == "-"
116
+ dst_is_stdout = dst == "-"
117
+ src_is_hf = is_hf_uri(src)
118
+ dst_is_hf = dst is not None and is_hf_uri(dst)
119
+
120
+ # --- Remote to remote: delegate to copy_files (repo/bucket -> repo/bucket) ---
121
+ if src_is_hf and dst_is_hf:
122
+ assert dst is not None # guaranteed by dst_is_hf
123
+ api.copy_files(src, dst)
124
+ out.result("Copied", src=src, dst=dst)
125
+ return
126
+
127
+ # --- At least one side must be a remote hf:// URI (rules out local->local, stdin->local, etc.) ---
128
+ if not src_is_hf and not dst_is_hf:
129
+ if dst is None:
130
+ raise click.BadParameter("Missing destination. Provide a repo or bucket hf:// URI as DST.")
131
+ raise click.BadParameter(
132
+ "One of SRC or DST must be a repo (hf://username/...) or bucket (hf://buckets/...) URI."
133
+ )
134
+
135
+ # --- Download: repo/bucket -> local file or stdout ---
136
+ if src_is_hf:
137
+ if dst_is_stdout:
138
+ _download_file_to_stdout(api, src)
139
+ return
140
+ _download_file_to_local(api, src, dst)
141
+ return
142
+
143
+ # --- Upload: local file or stdin -> repo/bucket ---
144
+ assert dst is not None # guaranteed: reaching here means dst_is_hf is True
145
+ _upload_file_to_remote(api, src, dst, src_is_stdin=src_is_stdin)
146
+
147
+
148
+ def _download_file_to_stdout(api: HfApi, src: str) -> None:
149
+ uri = parse_hf_uri(src)
150
+ filename = _source_filename(uri, src)
151
+ # Suppress progress bars to avoid polluting the piped output.
152
+ with disable_progress_bars():
153
+ with SoftTemporaryDirectory() as tmp_dir:
154
+ tmp_path = os.path.join(tmp_dir, filename)
155
+ _download_single(api, uri, tmp_path)
156
+ with open(tmp_path, "rb") as f:
157
+ while chunk := f.read(32_000_000): # 32MB chunks
158
+ sys.stdout.buffer.write(chunk)
159
+
160
+
161
+ def _download_file_to_local(api: HfApi, src: str, dst: str | None) -> None:
162
+ uri = parse_hf_uri(src)
163
+ filename = _source_filename(uri, src)
164
+
165
+ if dst is None:
166
+ local_path = filename
167
+ elif os.path.isdir(dst) or dst.endswith(os.sep) or dst.endswith("/"):
168
+ local_path = os.path.join(dst, filename)
169
+ else:
170
+ local_path = dst
171
+
172
+ parent_dir = os.path.dirname(local_path)
173
+ if parent_dir:
174
+ os.makedirs(parent_dir, exist_ok=True)
175
+
176
+ _download_single(api, uri, local_path)
177
+ out.result("Downloaded", src=src, dst=local_path)
178
+
179
+
180
+ def _download_single(api: HfApi, uri: HfUri, local_path: str) -> None:
181
+ """Download a single file (repo or bucket) to ``local_path``.
182
+
183
+ Used by `_download_file_to_local` and `_download_file_to_stdout`.
184
+ """
185
+ if uri.is_bucket:
186
+ api.download_bucket_files(uri.id, [(uri.path_in_repo, local_path)], raise_on_missing_files=True)
187
+ else:
188
+ # Download into a temporary folder next to the destination (rather than the shared cache)
189
+ # so the final move stays on the same filesystem and is instant. The temp folder is
190
+ # cleaned up automatically once the move is complete.
191
+ parent_dir = os.path.dirname(local_path) or "."
192
+ with SoftTemporaryDirectory(prefix=".tmp", dir=parent_dir) as tmp_dir:
193
+ downloaded_path = api.hf_hub_download(
194
+ repo_id=uri.id,
195
+ repo_type=uri.type,
196
+ filename=uri.path_in_repo,
197
+ revision=uri.revision,
198
+ local_dir=tmp_dir,
199
+ )
200
+ os.replace(downloaded_path, local_path)
201
+
202
+
203
+ def _source_filename(uri: HfUri, src: str) -> str:
204
+ if uri.path_in_repo == "" or src.endswith("/"):
205
+ raise click.BadParameter(
206
+ "Source path must include a file name, not just a repo/bucket or directory path."
207
+ " Use `hf download` or `hf buckets sync` to copy directories."
208
+ )
209
+ return uri.path_in_repo.rsplit("/", 1)[-1]
210
+
211
+
212
+ def _upload_file_to_remote(api: HfApi, src: str, dst: str, *, src_is_stdin: bool) -> None:
213
+ uri = parse_hf_uri(dst)
214
+
215
+ if src_is_stdin:
216
+ if uri.path_in_repo == "" or dst.endswith("/"):
217
+ raise click.BadParameter("Stdin upload requires a full destination path including filename.")
218
+ data = sys.stdin.buffer.read()
219
+ _upload_single(api, uri, data, uri.path_in_repo)
220
+ out.result("Uploaded", src="stdin", dst=uri.to_uri())
221
+ return
222
+
223
+ if os.path.isdir(src):
224
+ raise click.BadParameter(
225
+ "Source must be a file, not a directory. Use `hf upload` or `hf buckets sync` for directories."
226
+ )
227
+ if not os.path.isfile(src):
228
+ raise click.BadParameter(f"Source file not found: {src}")
229
+
230
+ prefix = uri.path_in_repo
231
+ if prefix == "":
232
+ remote_path = os.path.basename(src)
233
+ elif dst.endswith("/"):
234
+ remote_path = prefix + "/" + os.path.basename(src)
235
+ else:
236
+ remote_path = prefix
237
+
238
+ _upload_single(api, uri, src, remote_path)
239
+ out.result("Uploaded", src=src, dst=replace(uri, path_in_repo=remote_path).to_uri())
240
+
241
+
242
+ def _upload_single(api: HfApi, uri: HfUri, source: str | bytes, remote_path: str) -> None:
243
+ """Upload a single file or bytes (to a repo or bucket)."""
244
+ if uri.is_bucket:
245
+ api.batch_bucket_files(uri.id, add=[(source, remote_path)])
246
+ else:
247
+ api.upload_file(
248
+ path_or_fileobj=source,
249
+ path_in_repo=remote_path,
250
+ repo_id=uri.id,
251
+ repo_type=uri.type,
252
+ revision=uri.revision,
253
+ )
.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/cli/_errors.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """CLI error handling utilities."""
15
+
16
+ import traceback
17
+ from collections.abc import Callable
18
+
19
+ from huggingface_hub.errors import (
20
+ BucketNotFoundError,
21
+ CLIError,
22
+ CLIExtensionInstallError,
23
+ DeviceCodeError,
24
+ EntryNotFoundError,
25
+ GatedRepoError,
26
+ HfHubHTTPError,
27
+ HfUriError,
28
+ IncompleteSnapshotError,
29
+ LocalEntryNotFoundError,
30
+ LocalTokenNotFoundError,
31
+ OfflineModeIsEnabled,
32
+ OIDCError,
33
+ RemoteEntryNotFoundError,
34
+ RepositoryNotFoundError,
35
+ RevisionNotFoundError,
36
+ )
37
+
38
+
39
+ def _format_repo_not_found(error: RepositoryNotFoundError) -> str:
40
+ label = error.repo_type.capitalize() if error.repo_type else "Repository"
41
+ if error.repo_id:
42
+ msg = f"{label} '{error.repo_id}' not found."
43
+ else:
44
+ msg = f"{label} not found."
45
+ msg += "\nIf the repo is private, make sure you are authenticated and your token has the required permissions."
46
+
47
+ msg += "\nIf the repo does not exist, create it with: "
48
+ if error.repo_id is not None:
49
+ type_flag = f" --type {error.repo_type}" if error.repo_type and error.repo_type != "model" else ""
50
+ msg += f"hf repos create {error.repo_id}{type_flag}"
51
+ else:
52
+ msg += "hf repos create <repo_id>"
53
+
54
+ return msg
55
+
56
+
57
+ def _format_gated_repo(error: GatedRepoError) -> str:
58
+ label = error.repo_type if error.repo_type else "repository"
59
+ if error.repo_id:
60
+ return f"Access denied. {label.capitalize()} '{error.repo_id}' requires approval."
61
+ return f"Access denied. This {label} requires approval."
62
+
63
+
64
+ def _format_bucket_not_found(error: BucketNotFoundError) -> str:
65
+ if error.bucket_id:
66
+ msg = f"Bucket '{error.bucket_id}' not found."
67
+ cmd = f"hf buckets create {error.bucket_id}"
68
+ else:
69
+ msg = "Bucket not found."
70
+ cmd = "hf buckets create <bucket_id>"
71
+ msg += "\nIf the bucket is private, make sure you are authenticated and your token has the required permissions."
72
+ msg += f"\nIf the bucket does not exist, create it with: {cmd}"
73
+ return msg
74
+
75
+
76
+ def _format_entry_not_found(error: RemoteEntryNotFoundError) -> str:
77
+ label = error.repo_type if error.repo_type else "repository"
78
+ url = str(error.response.url) if error.response else None
79
+ if error.repo_id:
80
+ msg = f"File not found in {label} '{error.repo_id}'."
81
+ else:
82
+ msg = f"File not found in {label}."
83
+ if url:
84
+ msg += f"\nURL: {url}"
85
+ return msg
86
+
87
+
88
+ def _format_local_entry_not_found(error: LocalEntryNotFoundError) -> str:
89
+ cause = error.__cause__
90
+ if cause is not None:
91
+ return f"Local entry not found. {cause}"
92
+ return f"Local entry not found. {error}"
93
+
94
+
95
+ def _format_incomplete_snapshot(error: IncompleteSnapshotError) -> str:
96
+ msg = _format_local_entry_not_found(error)
97
+ msg += f"\nIncomplete snapshot available at: {error.snapshot_path}"
98
+ return msg
99
+
100
+
101
+ def _format_revision_not_found(error: RevisionNotFoundError) -> str:
102
+ label = error.repo_type if error.repo_type else "repository"
103
+ if error.repo_id:
104
+ return f"Revision not found in {label} '{error.repo_id}'."
105
+ return f"Revision not found in {label}. Check the revision parameter."
106
+
107
+
108
+ def _format_cli_error(error: CLIError) -> str:
109
+ """No traceback, just the error message."""
110
+ return str(error)
111
+
112
+
113
+ def _format_cli_extension_install_error(error: CLIExtensionInstallError) -> str:
114
+ """Format a CLI extension installation error.
115
+
116
+ The error is likely to be a tricky subprocess error to investigate. In this specific case we want to format the
117
+ traceback of the root cause while keeping the "nicely formatted" error message of the CLIExtensionInstallError
118
+ as a 1-line message.
119
+ """
120
+ cause_tb = (
121
+ "".join(traceback.format_exception(type(error.__cause__), error.__cause__, error.__cause__.__traceback__))
122
+ if error.__cause__ is not None
123
+ else ""
124
+ )
125
+ return f"{cause_tb}\n{error}"
126
+
127
+
128
+ CLI_ERROR_MAPPINGS: dict[type[Exception], Callable[..., str]] = {
129
+ OfflineModeIsEnabled: lambda error: str(error),
130
+ # GatedRepoError must come before RepositoryNotFoundError (it's a subclass).
131
+ GatedRepoError: _format_gated_repo,
132
+ BucketNotFoundError: _format_bucket_not_found,
133
+ RepositoryNotFoundError: _format_repo_not_found,
134
+ RevisionNotFoundError: _format_revision_not_found,
135
+ LocalTokenNotFoundError: lambda _: "Not logged in. Run 'hf auth login' first.",
136
+ OIDCError: lambda error: f"OIDC Exchange failed. {error}",
137
+ DeviceCodeError: lambda error: f"Login failed: {error}",
138
+ RemoteEntryNotFoundError: _format_entry_not_found,
139
+ # IncompleteSnapshotError must come before LocalEntryNotFoundError (it's a subclass).
140
+ IncompleteSnapshotError: _format_incomplete_snapshot,
141
+ LocalEntryNotFoundError: _format_local_entry_not_found,
142
+ EntryNotFoundError: lambda error: str(error),
143
+ HfHubHTTPError: lambda error: str(error),
144
+ HfUriError: lambda error: f"Invalid HF URI: {error.uri}. {error.msg}",
145
+ ValueError: lambda error: f"Invalid value. {error}",
146
+ CLIExtensionInstallError: _format_cli_extension_install_error,
147
+ CLIError: _format_cli_error,
148
+ }
149
+
150
+
151
+ def format_known_exception(error: Exception) -> str | None:
152
+ for exc_type, formatter in CLI_ERROR_MAPPINGS.items():
153
+ if isinstance(error, exc_type):
154
+ return formatter(error)
155
+ return None
.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/cli/_framework.py ADDED
@@ -0,0 +1,645 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Minimal declaration layer over Click 8.x for the ``hf`` CLI.
15
+
16
+ This module vendors *only* the slice of Typer the CLI actually uses: turning
17
+ annotated function signatures (``Annotated[T, Option(...)]`` / ``Argument(...)``)
18
+ into Click parameters, and rendering argument/option help the way Typer did.
19
+ It exists so the CLI depends on Click's stable public API instead of Typer's
20
+ now-internal vendored Click (``typer._click``), which Typer reserves the right
21
+ to refactor at any release.
22
+
23
+ Deliberately *not* implemented (add a case here only when a command needs it):
24
+ rich rendering, shell-completion install commands, prompts/confirmation options,
25
+ env-var options, ``File``/``UUID`` params, ``count`` options, ``default_factory``.
26
+ Click's own machinery already handles exceptions, aborts, exits, and native
27
+ ``_HF_COMPLETE`` shell completion, so none of Typer's ``main()`` overrides are
28
+ reproduced here.
29
+
30
+ The interesting logic mirrors four Typer functions, kept faithful so ``--help``
31
+ output stays byte-identical:
32
+ - :func:`_get_click_type` <- ``typer.main.get_click_type``
33
+ - :func:`_build_click_param` <- ``typer.main.get_click_param``
34
+ - :func:`_make_handler` <- ``typer.main.get_callback``
35
+ - :class:`HfArgument` / :class:`HfOption` help records <- ``typer.core.Typer*``
36
+ """
37
+
38
+ import enum
39
+ import functools
40
+ import inspect
41
+ from collections.abc import Callable, Sequence
42
+ from datetime import datetime
43
+ from pathlib import Path
44
+ from types import UnionType
45
+ from typing import Annotated, Any, Literal, Union, get_args, get_origin
46
+
47
+ import click
48
+
49
+
50
+ def get_command_name(name: str) -> str:
51
+ """Normalize a Python identifier to a CLI name (``force_download`` -> ``force-download``)."""
52
+ return name.lower().replace("_", "-")
53
+
54
+
55
+ # ---------------------------------------------------------------------------
56
+ # 1. Declaration markers — replace ``typer.Option`` / ``typer.Argument``.
57
+ # Attached in ``Annotated[T, Option(...)]``; the ``= value`` in the function
58
+ # signature carries the default (never the marker).
59
+ # ---------------------------------------------------------------------------
60
+
61
+
62
+ class ParameterInfo:
63
+ """Base marker holding the (tiny) set of Click knobs the CLI actually sets.
64
+
65
+ ``callback`` is a Typer-style value parser ``fn(value) -> parsed`` — it does NOT
66
+ receive Click's ``(ctx, param, value)``. It consumes the enum/list convertors, so
67
+ ``value`` is already converted when it runs.
68
+ """
69
+
70
+ def __init__(
71
+ self,
72
+ *param_decls: str,
73
+ help: str | None = None,
74
+ show_default: bool | str = True,
75
+ hidden: bool = False,
76
+ is_eager: bool = False,
77
+ callback: Callable[..., Any] | None = None,
78
+ min: int | None = None,
79
+ click_type: click.ParamType | None = None,
80
+ ) -> None:
81
+ self.param_decls = list(param_decls)
82
+ self.help = help
83
+ self.show_default = show_default
84
+ self.hidden = hidden
85
+ self.is_eager = is_eager
86
+ self.callback = callback
87
+ self.min = min
88
+ self.click_type = click_type
89
+
90
+
91
+ class Option(ParameterInfo):
92
+ """Declare a CLI option, e.g. ``Annotated[str | None, Option("--revision")]``."""
93
+
94
+
95
+ class Argument(ParameterInfo):
96
+ """Declare a positional CLI argument, e.g. ``Annotated[str, Argument()]``."""
97
+
98
+
99
+ # ---------------------------------------------------------------------------
100
+ # 2. Annotation -> Click type + value convertors.
101
+ # ---------------------------------------------------------------------------
102
+
103
+
104
+ def _get_click_type(annotation: Any, info: ParameterInfo) -> click.ParamType:
105
+ """Map a (already unwrapped) annotation to a Click ``ParamType``."""
106
+ if info.click_type is not None:
107
+ return info.click_type
108
+ if annotation is str:
109
+ return click.STRING
110
+ if annotation is bool:
111
+ return click.BOOL
112
+ if annotation is int:
113
+ return click.IntRange(min=info.min) if info.min is not None else click.INT
114
+ if annotation is float:
115
+ return click.FloatRange(min=info.min) if info.min is not None else click.FLOAT
116
+ if annotation is Path:
117
+ return click.Path(path_type=Path)
118
+ if annotation is datetime:
119
+ return click.DateTime()
120
+ if isinstance(annotation, type) and issubclass(annotation, enum.Enum):
121
+ values = [item.value for item in annotation]
122
+ if not all(isinstance(value, str) for value in values):
123
+ # A non-str member default would fail Choice validation at parse time with a
124
+ # cryptic error; fail at build time with a clear one instead.
125
+ raise TypeError(f"Unsupported enum {annotation.__name__!r}: only str-valued enums are supported.")
126
+ return click.Choice(values)
127
+ if get_origin(annotation) is Literal:
128
+ return click.Choice([str(value) for value in get_args(annotation)])
129
+ raise TypeError(f"Unsupported CLI annotation {annotation!r}. Add a case in `_framework._get_click_type()`.")
130
+
131
+
132
+ def _enum_convertor(enum_type: type[enum.Enum]) -> Callable[[Any], Any]:
133
+ """Map a parsed choice string back to its ``Enum`` member (mirrors Typer)."""
134
+ value_map = {str(member.value): member for member in enum_type}
135
+
136
+ def convertor(value: Any) -> Any:
137
+ if value is not None:
138
+ return value_map.get(str(value))
139
+ return None
140
+
141
+ return convertor
142
+
143
+
144
+ def _list_convertor(
145
+ inner: Callable[[Any], Any] | None, default_value: Any | None
146
+ ) -> Callable[[Sequence[Any] | None], list[Any] | None]:
147
+ """Turn Click's tuple (from ``multiple=True``) into a list, applying ``inner`` per item."""
148
+
149
+ def convertor(value: Sequence[Any] | None) -> list[Any] | None:
150
+ if value is None or (default_value is None and len(value) == 0):
151
+ return None
152
+ return [inner(item) if inner else item for item in value]
153
+
154
+ return convertor
155
+
156
+
157
+ def _make_convertor(
158
+ annotation: Any, is_list: bool, default_value: Any | None, info: ParameterInfo
159
+ ) -> Callable[[Any], Any] | None:
160
+ """Build the value convertor for a param (``None`` when no coercion is needed).
161
+
162
+ An explicit ``click_type`` (e.g. ``SoftChoice``) owns its own conversion, so no
163
+ enum convertor is added on top of it.
164
+ """
165
+ inner = None
166
+ if info.click_type is None and isinstance(annotation, type) and issubclass(annotation, enum.Enum):
167
+ inner = _enum_convertor(annotation)
168
+ if is_list:
169
+ return _list_convertor(inner, default_value)
170
+ return inner
171
+
172
+
173
+ def _unwrap_optional_and_list(annotation: Any) -> tuple[Any, bool]:
174
+ """Strip ``T | None`` / ``Optional[T]`` and ``list[T]``; return ``(base_type, is_list)``."""
175
+ origin = get_origin(annotation)
176
+ if origin in (Union, UnionType):
177
+ non_none = [arg for arg in get_args(annotation) if arg is not type(None)]
178
+ if len(non_none) != 1:
179
+ raise TypeError(f"Unsupported union annotation {annotation!r}; only ``T | None`` is supported.")
180
+ annotation = non_none[0]
181
+ origin = get_origin(annotation)
182
+ if origin in (list, Sequence):
183
+ return get_args(annotation)[0], True
184
+ return annotation, False
185
+
186
+
187
+ def _split_annotated(annotation: Any) -> tuple[Any, ParameterInfo | None]:
188
+ """Split ``Annotated[T, Option(...)]`` into ``(T, marker)``; ``(annotation, None)`` otherwise."""
189
+ if get_origin(annotation) is Annotated:
190
+ args = get_args(annotation)
191
+ marker = next((meta for meta in args[1:] if isinstance(meta, ParameterInfo)), None)
192
+ if marker is None and (typer_marker := next((meta for meta in args[1:] if _is_typer_marker(meta)), None)):
193
+ marker = _from_typer_marker(typer_marker, from_annotated=True)
194
+ return args[0], marker
195
+ return annotation, None
196
+
197
+
198
+ # ---------------------------------------------------------------------------
199
+ # Typer-marker compatibility shim (transition helper).
200
+ #
201
+ # ``typer_factory`` is exposed publicly and downstream CLIs (e.g. `transformers`)
202
+ # still register commands whose parameters carry ``typer.Option`` /
203
+ # ``typer.Argument`` markers. Recognize those markers structurally (no typer
204
+ # import required) and translate the fields this framework supports, so such
205
+ # commands keep working while downstream migrates.
206
+ # TODO: remove once transformers pins huggingface_hub>=1.22.0.
207
+ # ---------------------------------------------------------------------------
208
+
209
+
210
+ def _is_typer_marker(obj: Any) -> bool:
211
+ return type(obj).__module__.partition(".")[0] == "typer" and type(obj).__name__ in ("OptionInfo", "ArgumentInfo")
212
+
213
+
214
+ def _from_typer_marker(meta: Any, *, from_annotated: bool) -> ParameterInfo:
215
+ """Translate a ``typer.models.OptionInfo`` / ``ArgumentInfo`` into our marker."""
216
+ param_decls = list(getattr(meta, "param_decls", None) or ())
217
+ if type(meta).__name__ == "OptionInfo":
218
+ # In ``Annotated[...]`` usage typer stores the first flag name in ``default``
219
+ # (``Option("--flag", "-f")`` -> ``default="--flag"``, ``param_decls=("-f",)``).
220
+ default = getattr(meta, "default", ...)
221
+ if from_annotated and isinstance(default, str):
222
+ param_decls = [default, *param_decls]
223
+ cls: type[ParameterInfo] = Option
224
+ else:
225
+ cls = Argument
226
+ return cls(
227
+ *param_decls,
228
+ help=getattr(meta, "help", None),
229
+ show_default=getattr(meta, "show_default", True),
230
+ hidden=getattr(meta, "hidden", False),
231
+ is_eager=getattr(meta, "is_eager", False),
232
+ callback=getattr(meta, "callback", None),
233
+ min=getattr(meta, "min", None),
234
+ click_type=getattr(meta, "click_type", None),
235
+ )
236
+
237
+
238
+ # ---------------------------------------------------------------------------
239
+ # 3. Signature -> Click parameters (mirrors ``typer.main.get_click_param``).
240
+ # ---------------------------------------------------------------------------
241
+
242
+
243
+ def _wrap_param_callback(
244
+ user_callback: Callable[[Any], Any], convertor: Callable[[Any], Any] | None
245
+ ) -> Callable[[click.Context, click.Parameter, Any], Any]:
246
+ """Adapt a Typer-style value parser ``fn(value) -> parsed`` to a Click param callback."""
247
+
248
+ def click_callback(ctx: click.Context, param: click.Parameter, value: Any) -> Any:
249
+ return user_callback(convertor(value) if convertor else value)
250
+
251
+ return click_callback
252
+
253
+
254
+ def _build_click_param(
255
+ name: str, annotation: Any, info: ParameterInfo | None, signature_default: Any
256
+ ) -> tuple[click.Parameter, Callable[[Any], Any] | None]:
257
+ """Build a Click ``Parameter`` (and its post-parse value convertor) for one function param."""
258
+ required = signature_default is inspect.Parameter.empty
259
+ default_value = None if required else signature_default
260
+ if isinstance(default_value, enum.Enum):
261
+ default_value = default_value.value
262
+ if info is None:
263
+ # A bare annotation with no marker: required positional -> Argument, else Option.
264
+ info = Argument() if required else Option()
265
+
266
+ base_type, is_list = _unwrap_optional_and_list(annotation)
267
+ convertor = _make_convertor(base_type, is_list, default_value, info)
268
+
269
+ # A user ``callback`` consumes the value itself (and the convertor with it); otherwise the
270
+ # convertor runs later in the command handler wrapper. This keeps conversion single-pass.
271
+ if info.callback is not None:
272
+ param_callback: Callable[..., Any] | None = _wrap_param_callback(info.callback, convertor)
273
+ handler_convertor: Callable[[Any], Any] | None = None
274
+ else:
275
+ param_callback = None
276
+ handler_convertor = convertor
277
+
278
+ if isinstance(info, Argument):
279
+ argument = HfArgument(
280
+ [name],
281
+ type=_get_click_type(base_type, info),
282
+ required=required,
283
+ default=default_value,
284
+ nargs=-1 if is_list else 1,
285
+ is_eager=info.is_eager,
286
+ callback=param_callback,
287
+ help=info.help,
288
+ show_default=info.show_default,
289
+ hidden=info.hidden,
290
+ )
291
+ return argument, handler_convertor
292
+
293
+ # Option: prepend the Python name so ``click.Parameter.name`` matches the function kwarg,
294
+ # regardless of the user-facing flag names ("-v"/"--version", "--type"/"--repo-type", ...).
295
+ is_flag = base_type is bool
296
+ decls = [name]
297
+ if info.param_decls:
298
+ decls.extend(info.param_decls)
299
+ else:
300
+ kebab = get_command_name(name)
301
+ decls.append(f"--{kebab}/--no-{kebab}" if is_flag else f"--{kebab}")
302
+ option = HfOption(
303
+ decls,
304
+ # Click infers the flag type itself; passing a type alongside ``is_flag`` is rejected.
305
+ type=None if is_flag else _get_click_type(base_type, info),
306
+ required=required,
307
+ default=default_value,
308
+ is_flag=is_flag,
309
+ multiple=is_list,
310
+ is_eager=info.is_eager,
311
+ callback=param_callback,
312
+ help=info.help,
313
+ show_default=info.show_default,
314
+ hidden=info.hidden,
315
+ )
316
+ return option, handler_convertor
317
+
318
+
319
+ def _build_params(
320
+ func: Callable[..., Any],
321
+ ) -> tuple[list[click.Parameter], dict[str, Callable[[Any], Any]], str | None]:
322
+ """Introspect ``func`` and return ``(params, convertors, context_param_name)``."""
323
+ params: list[click.Parameter] = []
324
+ convertors: dict[str, Callable[[Any], Any]] = {}
325
+ context_param_name: str | None = None
326
+ for name, sig_param in inspect.signature(func).parameters.items():
327
+ # Read raw signature annotations rather than ``typing.get_type_hints``: the CLI never uses
328
+ # ``from __future__ import annotations``, so annotations are already live objects, and
329
+ # get_type_hints mangles ``Annotated[X | None, ...]`` on Python 3.10 (drops the origin).
330
+ annotation = sig_param.annotation if sig_param.annotation is not inspect.Parameter.empty else str
331
+ base_type, info = _split_annotated(annotation)
332
+ if isinstance(base_type, type) and (
333
+ issubclass(base_type, click.Context)
334
+ # typer.Context subclasses typer's *vendored* click since typer 0.26, so an
335
+ # issubclass check against real click misses it. Match it structurally.
336
+ or (base_type.__module__.partition(".")[0] == "typer" and base_type.__name__ == "Context")
337
+ ):
338
+ context_param_name = name
339
+ continue
340
+ signature_default = sig_param.default
341
+ if _is_typer_marker(signature_default):
342
+ # Old typer style: the marker *is* the signature default and carries the value.
343
+ if info is None:
344
+ info = _from_typer_marker(signature_default, from_annotated=False)
345
+ marker_default = getattr(signature_default, "default", ...)
346
+ signature_default = inspect.Parameter.empty if marker_default is ... else marker_default
347
+ click_param, convertor = _build_click_param(name, base_type, info, signature_default)
348
+ if convertor is not None and click_param.name is not None:
349
+ convertors[click_param.name] = convertor
350
+ params.append(click_param)
351
+ return params, convertors, context_param_name
352
+
353
+
354
+ def _make_handler(
355
+ func: Callable[..., Any],
356
+ convertors: dict[str, Callable[[Any], Any]],
357
+ context_param_name: str | None,
358
+ ) -> Callable[..., Any]:
359
+ """Wrap ``func`` so Click's kwargs map back to it, applying convertors and injecting the ctx."""
360
+
361
+ def handler(**kwargs: Any) -> Any:
362
+ call_kwargs = {key: (convertors[key](value) if key in convertors else value) for key, value in kwargs.items()}
363
+ if context_param_name is not None:
364
+ call_kwargs[context_param_name] = click.get_current_context()
365
+ return func(**call_kwargs)
366
+
367
+ functools.update_wrapper(handler, func)
368
+ return handler
369
+
370
+
371
+ # ---------------------------------------------------------------------------
372
+ # 4. Click parameter subclasses — port Typer's help records so arguments show up
373
+ # in ``--help`` (plain ``click.Argument`` renders none) and defaults/metavars
374
+ # read identically. Rich/env-var branches are dropped (never enabled here).
375
+ # ---------------------------------------------------------------------------
376
+
377
+
378
+ def _split_opt(opt: str) -> tuple[str, str]:
379
+ """Split an option string into ``(prefix, name)`` (Click's ``split_opt``, inlined)."""
380
+ first = opt[:1]
381
+ if first.isalnum():
382
+ return "", opt
383
+ if opt[1:2] == first:
384
+ return opt[:2], opt[2:]
385
+ return first, opt[1:]
386
+
387
+
388
+ def _extract_default_help_str(param: click.Parameter, ctx: click.Context) -> Any:
389
+ # Resilient parsing avoids type casting failing while rendering the default.
390
+ resilient = ctx.resilient_parsing
391
+ ctx.resilient_parsing = True
392
+ try:
393
+ return param.get_default(ctx, call=False)
394
+ finally:
395
+ ctx.resilient_parsing = resilient
396
+
397
+
398
+ def _default_string(
399
+ param: "HfArgument | HfOption", ctx: click.Context, show_default_is_str: bool, default_value: Any
400
+ ) -> str:
401
+ if show_default_is_str:
402
+ return f"({param.show_default})"
403
+ if isinstance(default_value, (list, tuple)):
404
+ return ", ".join(_default_string(param, ctx, show_default_is_str, item) for item in default_value)
405
+ if isinstance(default_value, enum.Enum):
406
+ return str(default_value.value)
407
+ if inspect.isfunction(default_value):
408
+ return "(dynamic)"
409
+ if isinstance(param, HfOption) and param.is_bool_flag and param.secondary_opts:
410
+ # Boolean toggle: show the opt name (without prefix) matching the current default.
411
+ if default_value:
412
+ return _split_opt(param.opts[0])[1] if param.opts else str(default_value)
413
+ return _split_opt(param.secondary_opts[0])[1]
414
+ if isinstance(param, HfOption) and param.is_bool_flag and not param.secondary_opts and not default_value:
415
+ return ""
416
+ return str(default_value)
417
+
418
+
419
+ def _describe_number_range(param_type: "click.IntRange | click.FloatRange") -> str:
420
+ """Human-readable range hint like ``x>=1`` or ``1<=x<10``.
421
+
422
+ Reproduces click's private ``_NumberRangeBase._describe_range()`` using the public
423
+ ``IntRange``/``FloatRange`` attributes, so the framework stays on Click's public API.
424
+ """
425
+ if param_type.min is None:
426
+ return f"x{'<' if param_type.max_open else '<='}{param_type.max}"
427
+ if param_type.max is None:
428
+ return f"x{'>' if param_type.min_open else '>='}{param_type.min}"
429
+ left = "<" if param_type.min_open else "<="
430
+ right = "<" if param_type.max_open else "<="
431
+ return f"{param_type.min}{left}x{right}{param_type.max}"
432
+
433
+
434
+ def _build_help_extra(param: "HfArgument | HfOption", ctx: click.Context, base_help: str) -> str:
435
+ """Append the ``[default: ...; required]`` suffix to a help string (shared by arg/option)."""
436
+ extra: list[str] = []
437
+ default_value = _extract_default_help_str(param, ctx)
438
+ show_default_is_str = isinstance(param.show_default, str)
439
+ if show_default_is_str or (default_value is not None and (param.show_default or ctx.show_default)):
440
+ default_string = _default_string(param, ctx, show_default_is_str, default_value)
441
+ if default_string:
442
+ extra.append(f"default: {default_string}")
443
+ # Numeric range hints are shown for options only (matches Typer; arguments omit them).
444
+ if isinstance(param, HfOption) and isinstance(param.type, (click.IntRange, click.FloatRange)):
445
+ range_str = _describe_number_range(param.type)
446
+ if range_str:
447
+ extra.append(range_str)
448
+ if param.required:
449
+ extra.append("required")
450
+ if extra:
451
+ suffix = f"[{'; '.join(extra)}]"
452
+ return f"{base_help} {suffix}" if base_help else suffix
453
+ return base_help
454
+
455
+
456
+ class HfArgument(click.Argument):
457
+ """Positional argument that renders help text and a metavar (Click's does neither)."""
458
+
459
+ def __init__(
460
+ self,
461
+ param_decls: Sequence[str],
462
+ *,
463
+ help: str | None = None,
464
+ show_default: bool | str = True,
465
+ hidden: bool = False,
466
+ **attrs: Any,
467
+ ) -> None:
468
+ self.help = help
469
+ self.show_default = show_default
470
+ self.hidden = hidden
471
+ super().__init__(param_decls, **attrs)
472
+
473
+ def make_metavar(self, ctx: click.Context) -> str:
474
+ if self.metavar is not None:
475
+ var = self.metavar
476
+ if not self.required and not var.startswith("["):
477
+ var = f"[{var}]"
478
+ return var
479
+ var = (self.name or "").upper()
480
+ if not self.required:
481
+ var = f"[{var}]"
482
+ type_var = self.type.get_metavar(self, ctx=ctx)
483
+ if type_var:
484
+ var += f":{type_var}"
485
+ if self.nargs != 1:
486
+ var += "..."
487
+ return var
488
+
489
+ def get_help_record(self, ctx: click.Context) -> tuple[str, str] | None:
490
+ if self.hidden:
491
+ return None
492
+ return self.make_metavar(ctx=ctx), _build_help_extra(self, ctx, self.help or "")
493
+
494
+
495
+ class HfOption(click.Option):
496
+ """Option whose help record ports Typer's default/metavar rendering verbatim."""
497
+
498
+ show_default: bool | str
499
+
500
+ def get_help_record(self, ctx: click.Context) -> tuple[str, str] | None:
501
+ if self.hidden:
502
+ return None
503
+
504
+ any_prefix_is_slash = False
505
+
506
+ def _write_opts(opts: Sequence[str]) -> str:
507
+ nonlocal any_prefix_is_slash
508
+ rv, any_slashes = click.formatting.join_options(opts)
509
+ if any_slashes:
510
+ any_prefix_is_slash = True
511
+ if not self.is_flag and not self.count:
512
+ rv += f" {self.make_metavar(ctx=ctx)}"
513
+ return rv
514
+
515
+ rv = [_write_opts(self.opts)]
516
+ if self.secondary_opts:
517
+ rv.append(_write_opts(self.secondary_opts))
518
+
519
+ help_text = _build_help_extra(self, ctx, self.help or "")
520
+ return ("; " if any_prefix_is_slash else " / ").join(rv), help_text
521
+
522
+
523
+ # ---------------------------------------------------------------------------
524
+ # 5. Command / group base classes and the decorator API (replace ``typer.Typer``).
525
+ # ---------------------------------------------------------------------------
526
+
527
+
528
+ def _format_params(command: click.Command, ctx: click.Context, formatter: click.HelpFormatter) -> None:
529
+ """Render params split into "Arguments" and "Options" sections (mirrors Typer)."""
530
+ args: list[tuple[str, str]] = []
531
+ opts: list[tuple[str, str]] = []
532
+ for param in command.get_params(ctx):
533
+ record = param.get_help_record(ctx)
534
+ if record is None:
535
+ continue
536
+ if param.param_type_name == "argument":
537
+ args.append(record)
538
+ elif param.param_type_name == "option":
539
+ opts.append(record)
540
+ if args:
541
+ with formatter.section("Arguments"):
542
+ formatter.write_dl(args)
543
+ if opts:
544
+ with formatter.section("Options"):
545
+ formatter.write_dl(opts)
546
+
547
+
548
+ class HfCommand(click.Command):
549
+ """Leaf command that renders arguments and options in separate help sections."""
550
+
551
+ def format_options(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:
552
+ _format_params(self, ctx, formatter)
553
+
554
+
555
+ def build_command(
556
+ func: Callable[..., Any],
557
+ *,
558
+ name: str | None = None,
559
+ cls: type[click.Command] | None = None,
560
+ help: str | None = None,
561
+ epilog: str | None = None,
562
+ short_help: str | None = None,
563
+ options_metavar: str = "[OPTIONS]",
564
+ add_help_option: bool = True,
565
+ no_args_is_help: bool = False,
566
+ hidden: bool = False,
567
+ deprecated: bool = False,
568
+ context_settings: dict[str, Any] | None = None,
569
+ ) -> click.Command:
570
+ """Build a Click ``Command`` from a function with ``Annotated`` params.
571
+
572
+ Replaces ``typer.main.get_command_from_info``.
573
+ """
574
+ params, convertors, context_param_name = _build_params(func)
575
+ handler = _make_handler(func, convertors, context_param_name)
576
+ command_help = inspect.cleandoc(help) if help else inspect.getdoc(func)
577
+ return (cls or HfCommand)(
578
+ name=name if name is not None else get_command_name(func.__name__),
579
+ callback=handler,
580
+ params=params,
581
+ help=command_help,
582
+ epilog=epilog,
583
+ short_help=short_help,
584
+ options_metavar=options_metavar,
585
+ add_help_option=add_help_option,
586
+ no_args_is_help=no_args_is_help,
587
+ hidden=hidden,
588
+ deprecated=deprecated,
589
+ context_settings=context_settings or {},
590
+ )
591
+
592
+
593
+ class HfGroup(click.Group):
594
+ """Command group with the decorator API the CLI relies on (``command``/``callback``/``add_group``).
595
+
596
+ Subclasses (see ``HFCliTyperGroup``) layer on styling, aliases, topics and error
597
+ enrichment; this base only wires functions to Click via :func:`build_command`.
598
+ """
599
+
600
+ #: Command class used by ``@group.command()`` unless overridden per call.
601
+ command_class: type[click.Command] = HfCommand
602
+
603
+ def format_options(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:
604
+ _format_params(self, ctx, formatter)
605
+ self.format_commands(ctx, formatter)
606
+
607
+ def list_commands(self, ctx: click.Context) -> list[str]:
608
+ # Preserve declaration order rather than Click's alphabetical default.
609
+ return list(self.commands)
610
+
611
+ def command( # type: ignore # deliberately narrows click.Group.command (builds from annotated signatures)
612
+ self, name: str | None = None, *, cls: type[click.Command] | None = None, **kwargs: Any
613
+ ) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
614
+ def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
615
+ command = build_command(func, name=name, cls=cls or self.command_class, **kwargs)
616
+ self.add_command(command, command.name)
617
+ return func
618
+
619
+ return decorator
620
+
621
+ def add_group(self, group: click.Group, *, name: str, hidden: bool = False) -> None:
622
+ """Register a subgroup under ``name`` (which may carry pipe aliases, e.g. ``"repos | repo"``)."""
623
+ group.name = name
624
+ group.hidden = hidden
625
+ self.add_command(group, name)
626
+
627
+ def group_callback(
628
+ self, *, invoke_without_command: bool = False
629
+ ) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
630
+ """Register the function invoked for this group (named ``group_callback`` because Click
631
+ already uses the ``callback`` attribute for the group's own handler)."""
632
+
633
+ def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
634
+ params, convertors, context_param_name = _build_params(func)
635
+ self.callback = _make_handler(func, convertors, context_param_name)
636
+ self.params = [*self.params, *params]
637
+ self.invoke_without_command = invoke_without_command
638
+ if invoke_without_command:
639
+ # Match Typer: the subcommand is optional when the group runs without one.
640
+ self.subcommand_metavar = "[COMMAND] [ARGS]..."
641
+ if self.help is None and func.__doc__:
642
+ self.help = inspect.cleandoc(func.__doc__)
643
+ return func
644
+
645
+ return decorator
.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/cli/_output.py ADDED
@@ -0,0 +1,379 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Output framework for the `hf` CLI."""
15
+
16
+ import dataclasses
17
+ import datetime
18
+ import json
19
+ import re
20
+ import shutil
21
+ import sys
22
+ from collections.abc import Sequence
23
+ from enum import Enum
24
+ from functools import cache
25
+ from typing import Any, cast
26
+
27
+ import click
28
+
29
+ from huggingface_hub.errors import ConfirmationError
30
+ from huggingface_hub.utils import ANSI, StatusLine, disable_progress_bars, is_agent, tabulate
31
+
32
+
33
+ class OutputFormat(str, Enum):
34
+ """Output format for CLI commands with auto detection of agent/human mode."""
35
+
36
+ agent = "agent"
37
+ auto = "auto"
38
+ human = "human"
39
+ json = "json"
40
+ quiet = "quiet"
41
+
42
+
43
+ def _print_flush(*values: Any, **kwargs: Any) -> None:
44
+ """Like `print`, but always flushed: some CLI flows block on user action right after
45
+ printing (e.g. the device-code login), so output must not stay buffered."""
46
+ print(*values, **kwargs, flush=True)
47
+
48
+
49
+ class Output:
50
+ """Output sink for the `hf` CLI.
51
+
52
+ Mode is resolved once at init time based on `is_agent()` auto-detection
53
+ and can be overridden per-command via `set_mode()`.
54
+ """
55
+
56
+ mode: OutputFormat
57
+ no_truncate: bool
58
+
59
+ def __init__(self) -> None:
60
+ self.no_truncate = False
61
+ self.set_mode()
62
+
63
+ def set_mode(self, mode: OutputFormat = OutputFormat.auto) -> None:
64
+ """Override the output mode (called once at startup and again per '--format' flag)."""
65
+ if mode == OutputFormat.auto:
66
+ mode = OutputFormat.agent if is_agent() else OutputFormat.human
67
+ self.mode = mode
68
+ if mode != OutputFormat.human:
69
+ disable_progress_bars()
70
+
71
+ def set_no_truncate(self, no_truncate: bool) -> None:
72
+ """Toggle off cell truncation for human table output."""
73
+ self.no_truncate = no_truncate
74
+
75
+ def is_quiet(self) -> bool:
76
+ return self.mode == OutputFormat.quiet
77
+
78
+ def text(self, msg: str | None = None, *, human: str | None = None, agent: str | None = None) -> None:
79
+ """Print a free-form text message to stdout."""
80
+ if msg is not None:
81
+ if human is not None or agent is not None:
82
+ raise ValueError("Cannot mix 'msg' with 'human'/'agent'.")
83
+ human = msg
84
+ agent = _strip_ansi(msg)
85
+
86
+ match self.mode:
87
+ case OutputFormat.human:
88
+ if human is not None:
89
+ _print_flush(human)
90
+ case OutputFormat.agent:
91
+ if agent is not None:
92
+ _print_flush(agent)
93
+ # json/quiet: no-op
94
+
95
+ def table(
96
+ self,
97
+ items: Sequence[dict[str, Any]],
98
+ *,
99
+ headers: list[str] | None = None,
100
+ id_key: str | None = None,
101
+ alignments: dict[str, str] | None = None,
102
+ ) -> None:
103
+ """Print tabular data to stdout.
104
+
105
+ Args:
106
+ items: List of dicts. Headers are auto-detected from keys if not provided.
107
+ headers: Explicit column names. If None, derived from dict keys (all-None columns filtered).
108
+ id_key: Key to print in quiet mode. If None, uses the first header.
109
+ alignments: Optional mapping of header name to "left" or "right". Defaults to "left".
110
+ """
111
+ if not items:
112
+ match self.mode:
113
+ case OutputFormat.agent | OutputFormat.human:
114
+ _print_flush("No results found.")
115
+ case OutputFormat.json:
116
+ _print_flush("[]")
117
+ return
118
+
119
+ if headers is None:
120
+ all_columns = list(items[0].keys())
121
+ headers = [col for col in all_columns if any(item.get(col) is not None for item in items)]
122
+ rows = [[item.get(h) for h in headers] for item in items]
123
+
124
+ match self.mode:
125
+ case OutputFormat.human: # padded table, adaptive truncation, SCREAMING_SNAKE headers
126
+ screaming_headers = [_to_header(h) for h in headers]
127
+ formatted_rows: list[list[str]] = [[_format_table_value_human(v) for v in row] for row in rows]
128
+
129
+ is_truncated = _truncate_columns(screaming_headers, formatted_rows, no_truncate=self.no_truncate)
130
+
131
+ inferred = {**_infer_alignments(headers, rows), **(alignments or {})}
132
+ screaming_alignments = {_to_header(k): v for k, v in inferred.items()}
133
+ _print_flush(
134
+ tabulate(
135
+ cast("list[list[str | int]]", formatted_rows),
136
+ headers=screaming_headers,
137
+ alignments=screaming_alignments,
138
+ ),
139
+ )
140
+ if is_truncated:
141
+ self.hint("Use `--no-truncate` or `--format json` to display full values.")
142
+ case OutputFormat.agent: # TSV, no truncation, full timestamps
143
+ _print_flush("\t".join(headers))
144
+ for row in rows:
145
+ _print_flush("\t".join(_format_table_cell_agent(v) for v in row))
146
+ case OutputFormat.json: # compact JSON array
147
+ _print_flush(json.dumps(list(items), default=str))
148
+ case OutputFormat.quiet: # id_key column (or first column), one per line
149
+ quiet_key = id_key or headers[0]
150
+ for item in items:
151
+ _print_flush(item.get(quiet_key, ""))
152
+
153
+ def dict(self, data: Any, *, id_key: str | None = None) -> None:
154
+ """Print structured data as JSON in all modes (indented for human, compact otherwise).
155
+
156
+ Accepts a dict or a dataclass.
157
+ """
158
+ if dataclasses.is_dataclass(data) and not isinstance(data, type):
159
+ data = _dataclass_to_dict(data)
160
+ if self.mode == OutputFormat.quiet and id_key is not None:
161
+ _print_flush(data.get(id_key, ""))
162
+ return
163
+ indent = 2 if self.mode == OutputFormat.human else None
164
+ _print_flush(json.dumps(data, indent=indent, default=str))
165
+
166
+ def result(self, message: str, **data: Any) -> None:
167
+ """Print a success summary to stdout."""
168
+ match self.mode:
169
+ case OutputFormat.human: # ✓ message + key: value lines
170
+ parts = [ANSI.green(f"{_ascii_safe('✓', '[OK]')} {message}")]
171
+ for k, v in data.items():
172
+ if v is not None:
173
+ parts.append(f" {k}: {v}")
174
+ _print_flush("\n".join(parts))
175
+ case OutputFormat.agent: # key=val pairs, space-separated
176
+ parts = [f"{k}={v}" for k, v in data.items() if v is not None]
177
+ _print_flush(" ".join(parts) if parts else message)
178
+ case OutputFormat.json: # json.dumps(data), message ignored
179
+ _print_flush(json.dumps(data, default=str) if data else "")
180
+ case OutputFormat.quiet: # first value only
181
+ values = list(data.values())
182
+ if values:
183
+ _print_flush(values[0])
184
+
185
+ def confirm(self, message: str, *, default: bool = False, yes: bool = False, confirm_param: str = "--yes") -> None:
186
+ """
187
+ Ask for confirmation. Raises `ConfirmationError` in non-human modes.
188
+ """
189
+ if yes:
190
+ return
191
+ if self.mode != OutputFormat.human:
192
+ raise ConfirmationError(f"{message} Use {confirm_param} to skip confirmation.")
193
+ click.confirm(message, default=default, abort=True)
194
+
195
+ def status(self, message: str | None = None) -> StatusLine:
196
+ """Return a status line that emits only in human mode (no-op otherwise)."""
197
+ status = StatusLine(enabled=self.mode == OutputFormat.human)
198
+ if message is not None:
199
+ status.update(message)
200
+ return status
201
+
202
+ def warning(self, message: str) -> None:
203
+ """Print a non-fatal warning to stderr (all modes)."""
204
+ if self.mode == OutputFormat.human:
205
+ _print_flush(ANSI.yellow(f"Warning: {message}"), file=sys.stderr)
206
+ else:
207
+ _print_flush(f"Warning: {message}", file=sys.stderr)
208
+
209
+ def error(self, message: str) -> None:
210
+ """Print an error to stderr (all modes)."""
211
+ if self.mode == OutputFormat.human:
212
+ _print_flush(ANSI.red(f"Error: {message}"), file=sys.stderr)
213
+ else:
214
+ _print_flush(f"Error: {message}", file=sys.stderr)
215
+
216
+ def log(self, message: str) -> None:
217
+ """Print a text message to stderr (human: gray, json/agent: plain text).
218
+
219
+ Suppressed in quiet mode. Kept in json mode (like agent) since agents
220
+ commonly run with ``--format json`` and the message goes to stderr so
221
+ it never pollutes the parsed stdout.
222
+ """
223
+ if self.mode == OutputFormat.quiet:
224
+ return
225
+ if self.mode == OutputFormat.human:
226
+ _print_flush(ANSI.gray(message), file=sys.stderr)
227
+ else:
228
+ _print_flush(message, file=sys.stderr)
229
+
230
+ def hint(self, message: str) -> None:
231
+ """Print a helpful hint to stderr (human: gray, json/agent: plain text).
232
+
233
+ Suppressed in quiet mode. Kept in json mode (like agent) since agents
234
+ commonly run with ``--format json`` and the next-command hints are useful
235
+ there; hints go to stderr so they never pollute the parsed stdout.
236
+ """
237
+ self.log(f"Hint: {message}")
238
+
239
+
240
+ # HELPERS
241
+
242
+
243
+ @cache
244
+ def _ascii_safe(char: str, fallback: str) -> str:
245
+ """Return `char`, or `fallback` if stdout cannot encode it.
246
+
247
+ On Windows, `sys.stdout` uses the ANSI code page (e.g. cp1252) instead of the console
248
+ encoding whenever it is not attached to a console (output redirected, piped, captured by
249
+ a CI step). Printing a decoration like "✓" then raises `UnicodeEncodeError` - a
250
+ `ValueError` subclass, so it surfaces as a confusing "Invalid value." error and aborts
251
+ the command. Cached since the stream encoding is fixed for the lifetime of the process.
252
+ """
253
+ encoding = getattr(sys.stdout, "encoding", None) or "utf-8"
254
+ try:
255
+ char.encode(encoding)
256
+ except (LookupError, UnicodeEncodeError):
257
+ return fallback
258
+ return char
259
+
260
+
261
+ def _serialize_value(v: object) -> object:
262
+ """Recursively serialize a value to be JSON-compatible."""
263
+ if isinstance(v, datetime.datetime):
264
+ return v.isoformat()
265
+ elif isinstance(v, dict):
266
+ return {key: _serialize_value(val) for key, val in v.items() if val is not None}
267
+ elif isinstance(v, list):
268
+ return [_serialize_value(item) for item in v]
269
+ return v
270
+
271
+
272
+ def _dataclass_to_dict(info: Any) -> dict[str, Any]:
273
+ """Convert a dataclass to a json-serializable dict."""
274
+ return {k: _serialize_value(v) for k, v in dataclasses.asdict(info).items() if v is not None}
275
+
276
+
277
+ _ANSI_RE = re.compile(r"\033\[[0-9;]*m")
278
+
279
+
280
+ def _strip_ansi(text: str) -> str:
281
+ return _ANSI_RE.sub("", text)
282
+
283
+
284
+ def _single_line(text: str) -> str:
285
+ return " ".join(text.split())
286
+
287
+
288
+ def _to_header(name: str) -> str:
289
+ """Convert a camelCase or PascalCase string to SCREAMING_SNAKE_CASE."""
290
+ s = re.sub(r"([a-z])([A-Z])", r"\1_\2", name)
291
+ return s.upper()
292
+
293
+
294
+ def _infer_alignments(headers: list[str], rows: list[list[Any]]) -> dict[str, str]:
295
+ """Return ``{"col": "right"}`` for columns where every non-None value is numeric."""
296
+ result: dict[str, str] = {}
297
+ for c, h in enumerate(headers):
298
+ if all(row[c] is None or (isinstance(row[c], (int, float)) and not isinstance(row[c], bool)) for row in rows):
299
+ result[h] = "right"
300
+ return result
301
+
302
+
303
+ def _format_table_value_human(value: Any) -> str:
304
+ """Convert a value to string for terminal display."""
305
+ if value is None:
306
+ return ""
307
+ if isinstance(value, bool):
308
+ return _ascii_safe("✔", "yes") if value else ""
309
+ if isinstance(value, datetime.datetime):
310
+ return value.strftime("%Y-%m-%d")
311
+ if isinstance(value, str) and re.match(r"^\d{4}-\d{2}-\d{2}T", value):
312
+ return value[:10]
313
+ if isinstance(value, str):
314
+ return _single_line(value)
315
+ if isinstance(value, list):
316
+ return ", ".join(_format_table_value_human(v) for v in value)
317
+ elif isinstance(value, dict):
318
+ if "name" in value: # Likely to be a user or org => print name
319
+ return _single_line(str(value["name"]))
320
+ return _single_line(json.dumps(value))
321
+ return _single_line(str(value))
322
+
323
+
324
+ def _truncate_columns(
325
+ headers: list[str],
326
+ rows: list[list[str]],
327
+ *,
328
+ no_truncate: bool,
329
+ ) -> bool:
330
+ """Truncate cells in-place to fit the current terminal width.
331
+
332
+ Returns `True` if any cell was truncated, so the caller can emit a hint.
333
+ `shutil.get_terminal_size` is cross-platform: it honors `$COLUMNS`, then
334
+ queries the OS-native API, then falls back to `(80, 24)`.
335
+ """
336
+ if no_truncate or not rows:
337
+ return False
338
+
339
+ n = len(headers)
340
+ # Per-column natural width: longest of header label and cell values.
341
+ natural = [max(len(headers[c]), *(len(rows[r][c]) for r in range(len(rows)))) for c in range(n)]
342
+
343
+ # `max(0, n - 1)` accounts for the single-space separator between columns.
344
+ budget = shutil.get_terminal_size().columns - max(0, n - 1)
345
+ if sum(natural) <= budget:
346
+ return False
347
+
348
+ # Shrink the widest column 1 char at a time. Floors keep the header label
349
+ # visible; the `4` is the smallest cap that still shows "x..." (one content
350
+ # char plus the "..." marker).
351
+ caps = natural.copy()
352
+ min_widths = [max(len(h), 4) for h in headers]
353
+ while sum(caps) > budget:
354
+ widest = max(
355
+ (i for i, w in enumerate(caps) if w > min_widths[i]),
356
+ key=lambda i: caps[i],
357
+ default=-1,
358
+ )
359
+ if widest < 0:
360
+ break # everything at floor — table wraps slightly
361
+ caps[widest] -= 1
362
+
363
+ truncated = False
364
+ for row in rows:
365
+ for c, cell in enumerate(row):
366
+ if len(cell) > caps[c]:
367
+ truncated = True
368
+ row[c] = cell[: caps[c] - 3] + "..."
369
+ return truncated
370
+
371
+
372
+ def _format_table_cell_agent(value: Any) -> str:
373
+ """Format a cell value for agent TSV output (ISO timestamps, tabs escaped)."""
374
+ if isinstance(value, datetime.datetime):
375
+ return value.isoformat()
376
+ return _single_line(str(value))
377
+
378
+
379
+ out = Output()
.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/cli/_skills.py ADDED
@@ -0,0 +1,311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Internal helpers for Hugging Face marketplace skill installation and upgrades."""
2
+
3
+ import json
4
+ import re
5
+ import shutil
6
+ import tempfile
7
+ from collections.abc import Callable
8
+ from dataclasses import dataclass, replace
9
+ from pathlib import Path, PurePosixPath
10
+ from typing import Any, Literal
11
+
12
+ from huggingface_hub._buckets import BucketFile
13
+ from huggingface_hub.errors import CLIError
14
+
15
+ from ..utils import disable_progress_bars
16
+ from ._cli_utils import get_hf_api
17
+
18
+
19
+ DEFAULT_SKILL_ID = "hf-cli"
20
+ DEFAULT_SKILLS_BUCKET_ID = "huggingface/skills"
21
+ MARKETPLACE_PATH = "marketplace.json"
22
+ # Empty marker file dropped into managed skill installs so `hf skills update` knows
23
+ # to touch them and leave user-placed skill dirs alone. Filename is historical (used
24
+ # to be a JSON manifest with a revision); we keep it for backward compat with installs
25
+ # made by previous versions.
26
+ MANAGED_MARKER_FILENAME = ".hf-skill-manifest.json"
27
+
28
+ SkillUpdateStatus = Literal["up_to_date", "unmanaged", "source_unreachable"]
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class MarketplaceSkill:
33
+ name: str
34
+ repo_path: str
35
+ description: str | None = None
36
+
37
+
38
+ @dataclass(frozen=True)
39
+ class SkillUpdateInfo:
40
+ name: str
41
+ skill_dir: Path
42
+ status: SkillUpdateStatus
43
+ detail: str | None = None
44
+
45
+
46
+ def add_skill(skill_name: str, destination_root: Path, force: bool = False) -> Path:
47
+ """Resolve a marketplace skill by name and install it."""
48
+ api = get_hf_api()
49
+ with disable_progress_bars():
50
+ marketplace_skills = _load_marketplace_skills(api)
51
+ skill = _select_marketplace_skill(marketplace_skills, skill_name)
52
+ if skill is None:
53
+ raise CLIError(
54
+ f"Skill '{skill_name}' not found in {DEFAULT_SKILLS_BUCKET_ID}. "
55
+ "Try `hf skills add` to install `hf-cli` or use a known skill name."
56
+ )
57
+ return _install_marketplace_skill(api, skill, destination_root, force=force)
58
+
59
+
60
+ def install_generated_skill(content: str, destination_root: Path, force: bool = False) -> Path:
61
+ """Install the `hf-cli` skill from locally generated SKILL.md content (no bucket download)."""
62
+
63
+ def populate(install_dir: Path) -> None:
64
+ install_dir.mkdir(parents=True, exist_ok=True)
65
+ (install_dir / "SKILL.md").write_text(content, encoding="utf-8")
66
+ (install_dir / MANAGED_MARKER_FILENAME).touch()
67
+
68
+ return _install_skill(DEFAULT_SKILL_ID, destination_root, populate=populate, force=force)
69
+
70
+
71
+ def update_skills(roots: list[Path], selector: str | None = None, *, hf_cli_content: str) -> list[SkillUpdateInfo]:
72
+ """Re-sync managed skill installs (`hf-cli` is rewritten from `hf_cli_content`, the rest from the bucket)."""
73
+ skill_dirs = _iter_unique_skill_dirs(roots)
74
+ if selector is not None:
75
+ selector_lower = selector.strip().lower()
76
+ skill_dirs = [d for d in skill_dirs if d.name.lower() == selector_lower]
77
+ if not skill_dirs:
78
+ raise CLIError(f"No installed skill matches '{selector}'. Install it with `hf skills add {selector}`.")
79
+
80
+ # `hf-cli` is regenerated locally, so only hit the marketplace when another managed skill needs it.
81
+ needs_marketplace = any(d.name != DEFAULT_SKILL_ID and (d / MANAGED_MARKER_FILENAME).exists() for d in skill_dirs)
82
+ api = None
83
+ marketplace_skills: dict[str, MarketplaceSkill] = {}
84
+ if needs_marketplace:
85
+ api = get_hf_api()
86
+ with disable_progress_bars():
87
+ marketplace_skills = {skill.name.lower(): skill for skill in _load_marketplace_skills(api)}
88
+
89
+ return [_apply_single_update(api, skill_dir, marketplace_skills, hf_cli_content) for skill_dir in skill_dirs]
90
+
91
+
92
+ def _load_marketplace_skills(api) -> list[MarketplaceSkill]:
93
+ payload = _load_marketplace_payload(api)
94
+ plugins = payload.get("plugins")
95
+ if not isinstance(plugins, list):
96
+ raise CLIError("Invalid marketplace payload: expected a top-level 'plugins' list.")
97
+
98
+ skills: list[MarketplaceSkill] = []
99
+ for plugin in plugins:
100
+ if not isinstance(plugin, dict):
101
+ continue
102
+ name = plugin.get("name")
103
+ source = plugin.get("source")
104
+ if not isinstance(name, str) or not isinstance(source, str):
105
+ continue
106
+ description = plugin.get("description")
107
+ skills.append(
108
+ MarketplaceSkill(
109
+ name=name,
110
+ repo_path=_normalize_repo_path(source),
111
+ description=description if isinstance(description, str) else None,
112
+ )
113
+ )
114
+ return skills
115
+
116
+
117
+ def _install_marketplace_skill(api, skill: MarketplaceSkill, destination_root: Path, force: bool = False) -> Path:
118
+ """Install a marketplace skill into a local skills directory."""
119
+
120
+ def populate(install_dir: Path) -> None:
121
+ install_dir.mkdir(parents=True, exist_ok=True)
122
+ bucket_files = _list_skill_files(api, skill)
123
+ _download_skill_files(api, skill, bucket_files, install_dir)
124
+ _validate_installed_skill_dir(install_dir)
125
+ (install_dir / MANAGED_MARKER_FILENAME).touch()
126
+
127
+ return _install_skill(skill.name, destination_root, populate=populate, force=force)
128
+
129
+
130
+ _VALID_SKILL_NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*")
131
+
132
+
133
+ def _install_skill(
134
+ name: str,
135
+ destination_root: Path,
136
+ populate: Callable[[Path], None],
137
+ force: bool = False,
138
+ ) -> Path:
139
+ """Install a skill into ``destination_root`` by calling ``populate(install_dir)`` to fill it.
140
+
141
+ Used by both the marketplace install (populate = download from bucket) and the
142
+ locally-generated install (populate = write content). When the install already
143
+ exists and ``force`` is set, the new content is staged in a sibling tempdir and
144
+ atomically swapped in, so the existing install stays intact if ``populate``
145
+ fails halfway through.
146
+ """
147
+ # `name` may come from the remote marketplace payload and the install dir is removed on
148
+ # reinstall: validate it as defense-in-depth against path traversal.
149
+ if not _VALID_SKILL_NAME.fullmatch(name):
150
+ raise CLIError(f"Invalid skill name '{name}'.")
151
+ destination_root = destination_root.expanduser().resolve()
152
+ destination_root.mkdir(parents=True, exist_ok=True)
153
+ install_dir = destination_root / name
154
+ already_exists = install_dir.exists()
155
+
156
+ if already_exists and not force:
157
+ raise FileExistsError(f"Skill already exists: {install_dir}")
158
+
159
+ if already_exists:
160
+ with tempfile.TemporaryDirectory(dir=destination_root, prefix=f".{install_dir.name}.install-") as tmp_dir_str:
161
+ staged_dir = Path(tmp_dir_str) / install_dir.name
162
+ populate(staged_dir)
163
+ _atomic_replace_directory(existing_dir=install_dir, staged_dir=staged_dir)
164
+ return install_dir
165
+
166
+ try:
167
+ populate(install_dir)
168
+ except Exception:
169
+ if install_dir.exists():
170
+ shutil.rmtree(install_dir)
171
+ raise
172
+ return install_dir
173
+
174
+
175
+ def _load_marketplace_payload(api) -> dict[str, Any]:
176
+ with tempfile.TemporaryDirectory() as tmp_dir:
177
+ local_path = Path(tmp_dir) / "marketplace.json"
178
+ api.download_bucket_files(
179
+ DEFAULT_SKILLS_BUCKET_ID,
180
+ [(MARKETPLACE_PATH, local_path)],
181
+ raise_on_missing_files=True,
182
+ )
183
+ parsed = json.loads(local_path.read_text(encoding="utf-8"))
184
+
185
+ if not isinstance(parsed, dict):
186
+ raise CLIError("Invalid marketplace payload: expected a JSON object.")
187
+ return parsed
188
+
189
+
190
+ def _select_marketplace_skill(skills: list[MarketplaceSkill], selector: str) -> MarketplaceSkill | None:
191
+ selector_lower = selector.strip().lower()
192
+ for skill in skills:
193
+ if skill.name.lower() == selector_lower:
194
+ return skill
195
+ return None
196
+
197
+
198
+ def _normalize_repo_path(path: str) -> str:
199
+ normalized = path.strip()
200
+ while normalized.startswith("./"):
201
+ normalized = normalized[2:]
202
+ normalized = normalized.strip("/")
203
+ if not normalized:
204
+ raise CLIError("Invalid marketplace entry: empty source path.")
205
+ return normalized
206
+
207
+
208
+ def _validate_installed_skill_dir(skill_dir: Path) -> None:
209
+ skill_file = skill_dir / "SKILL.md"
210
+ if not skill_file.is_file():
211
+ raise RuntimeError(f"Installed skill is missing SKILL.md: {skill_file}")
212
+
213
+
214
+ def _list_skill_files(api, skill: MarketplaceSkill) -> list[BucketFile]:
215
+ """List all files under `skill.repo_path` in the marketplace bucket."""
216
+ prefix = skill.repo_path.rstrip("/")
217
+ files: list[BucketFile] = [
218
+ item
219
+ for item in api.list_bucket_tree(DEFAULT_SKILLS_BUCKET_ID, prefix=prefix, recursive=True)
220
+ if isinstance(item, BucketFile)
221
+ ]
222
+ if not files:
223
+ raise FileNotFoundError(f"Path '{prefix}' not found in bucket '{DEFAULT_SKILLS_BUCKET_ID}'.")
224
+ return files
225
+
226
+
227
+ def _download_skill_files(api, skill: MarketplaceSkill, files: list[BucketFile], install_dir: Path) -> None:
228
+ """Download bucket files into `install_dir`."""
229
+ prefix = skill.repo_path.rstrip("/")
230
+ prefix_with_slash = f"{prefix}/"
231
+
232
+ # `list_bucket_tree(prefix=...)` matches as a raw string prefix, so e.g. asking for
233
+ # "skills/gradio" can also return "skills/gradio-tools/...". Filter on the trailing
234
+ # slash to keep only files actually inside the directory, then strip it so files land
235
+ # directly under `install_dir` preserving any nested structure.
236
+ download_specs: list[tuple[str | BucketFile, str | Path]] = []
237
+ for bucket_file in files:
238
+ if not bucket_file.path.startswith(prefix_with_slash):
239
+ continue
240
+ relative = bucket_file.path[len(prefix_with_slash) :]
241
+ local_file = install_dir.joinpath(*PurePosixPath(relative).parts)
242
+ local_file.parent.mkdir(parents=True, exist_ok=True)
243
+ download_specs.append((bucket_file, local_file))
244
+
245
+ if not download_specs:
246
+ raise FileNotFoundError(f"No files found under '{prefix}' in bucket '{DEFAULT_SKILLS_BUCKET_ID}'.")
247
+
248
+ api.download_bucket_files(DEFAULT_SKILLS_BUCKET_ID, download_specs)
249
+
250
+
251
+ def _atomic_replace_directory(existing_dir: Path, staged_dir: Path) -> None:
252
+ backup_dir = staged_dir.parent / f"{existing_dir.name}.backup"
253
+ try:
254
+ existing_dir.rename(backup_dir)
255
+ staged_dir.rename(existing_dir)
256
+ shutil.rmtree(backup_dir)
257
+ except Exception:
258
+ if backup_dir.exists() and not existing_dir.exists():
259
+ backup_dir.rename(existing_dir)
260
+ raise
261
+
262
+
263
+ def _iter_unique_skill_dirs(roots: list[Path]) -> list[Path]:
264
+ seen: set[Path] = set()
265
+ discovered: list[Path] = []
266
+ for root in roots:
267
+ root = root.expanduser().resolve()
268
+ if not root.is_dir():
269
+ continue
270
+ for child in sorted(root.iterdir()):
271
+ if child.name.startswith("."):
272
+ continue
273
+ if not child.is_dir() and not child.is_symlink():
274
+ continue
275
+ resolved = child.resolve()
276
+ if resolved in seen or not resolved.is_dir():
277
+ continue
278
+ seen.add(resolved)
279
+ discovered.append(resolved)
280
+ return discovered
281
+
282
+
283
+ def _apply_single_update(
284
+ api, skill_dir: Path, marketplace_skills: dict[str, MarketplaceSkill], hf_cli_content: str
285
+ ) -> SkillUpdateInfo:
286
+ base = SkillUpdateInfo(name=skill_dir.name, skill_dir=skill_dir, status="unmanaged")
287
+
288
+ if not (skill_dir / MANAGED_MARKER_FILENAME).exists():
289
+ return base
290
+
291
+ if skill_dir.name == DEFAULT_SKILL_ID:
292
+ try:
293
+ install_generated_skill(hf_cli_content, skill_dir.parent, force=True)
294
+ except Exception as exc:
295
+ return replace(base, status="source_unreachable", detail=str(exc))
296
+ return replace(base, status="up_to_date")
297
+
298
+ skill = marketplace_skills.get(skill_dir.name.lower())
299
+ if skill is None:
300
+ return replace(
301
+ base,
302
+ status="source_unreachable",
303
+ detail=f"Skill '{skill_dir.name}' is no longer available in {DEFAULT_SKILLS_BUCKET_ID}.",
304
+ )
305
+
306
+ try:
307
+ _install_marketplace_skill(api, skill, skill_dir.parent, force=True)
308
+ except Exception as exc:
309
+ return replace(base, status="source_unreachable", detail=str(exc))
310
+
311
+ return replace(base, status="up_to_date")
.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/cli/buckets.py ADDED
@@ -0,0 +1,679 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025-present, the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Contains commands to interact with buckets via the CLI."""
15
+
16
+ from typing import Annotated
17
+
18
+ import click
19
+
20
+ from huggingface_hub import logging
21
+ from huggingface_hub._buckets import (
22
+ BUCKET_PREFIX,
23
+ BucketFile,
24
+ FilterMatcher,
25
+ _parse_bucket_uri,
26
+ )
27
+
28
+ from ..hf_api import REPO_REGIONS
29
+ from ._cli_utils import (
30
+ SearchOpt,
31
+ TokenOpt,
32
+ get_hf_api,
33
+ typer_factory,
34
+ )
35
+ from ._cp import make_cp
36
+ from ._file_listing import format_size, print_file_listing
37
+ from ._framework import Argument, Option
38
+ from ._output import OutputFormat, out
39
+
40
+
41
+ logger = logging.get_logger(__name__)
42
+
43
+
44
+ buckets_cli = typer_factory(help="Commands to interact with buckets.")
45
+
46
+
47
+ @buckets_cli.command(
48
+ name="create",
49
+ examples=[
50
+ "hf buckets create my-bucket",
51
+ "hf buckets create user/my-bucket",
52
+ "hf buckets create hf://buckets/user/my-bucket",
53
+ "hf buckets create user/my-bucket --private",
54
+ "hf buckets create user/my-bucket --exist-ok",
55
+ "hf buckets create user/my-bucket --region us",
56
+ ],
57
+ )
58
+ def create(
59
+ bucket_id: Annotated[
60
+ str,
61
+ Argument(
62
+ help="Bucket ID: bucket_name, namespace/bucket_name, or hf://buckets/namespace/bucket_name",
63
+ ),
64
+ ],
65
+ private: Annotated[
66
+ bool,
67
+ Option(
68
+ "--private",
69
+ help="Create a private bucket.",
70
+ ),
71
+ ] = False,
72
+ region: Annotated[
73
+ REPO_REGIONS | None,
74
+ Option(
75
+ "--region",
76
+ help="Cloud region in which to create the bucket. Can be one of 'us' or 'eu'. Requires Team plan or above.",
77
+ ),
78
+ ] = None,
79
+ exist_ok: Annotated[
80
+ bool,
81
+ Option(
82
+ "--exist-ok",
83
+ help="Do not raise an error if the bucket already exists.",
84
+ ),
85
+ ] = False,
86
+ token: TokenOpt = None,
87
+ ) -> None:
88
+ """Create a new bucket."""
89
+ api = get_hf_api(token=token)
90
+
91
+ if bucket_id.startswith(BUCKET_PREFIX):
92
+ parsed = _parse_bucket_uri(bucket_id)
93
+ if parsed.path_in_repo:
94
+ raise click.BadParameter(
95
+ f"Cannot specify a prefix for bucket creation: {bucket_id}."
96
+ f" Use namespace/bucket_name or {BUCKET_PREFIX}namespace/bucket_name."
97
+ )
98
+ bucket_id = parsed.id
99
+
100
+ bucket_url = api.create_bucket(
101
+ bucket_id,
102
+ private=private if private else None,
103
+ region=region,
104
+ exist_ok=exist_ok,
105
+ )
106
+ out.result("Bucket created", uri=bucket_url.uri.to_uri(), url=bucket_url.url)
107
+
108
+
109
+ def _is_bucket_id(argument: str) -> bool:
110
+ """Check if argument is a bucket ID (namespace/name) vs just a namespace."""
111
+ if argument.startswith(BUCKET_PREFIX):
112
+ path = argument[len(BUCKET_PREFIX) :]
113
+ else:
114
+ path = argument
115
+ return "/" in path
116
+
117
+
118
+ @buckets_cli.command(
119
+ name="list | ls",
120
+ examples=[
121
+ "hf buckets list",
122
+ "hf buckets list huggingface",
123
+ 'hf buckets list --search "my-prefix"',
124
+ "hf buckets list user/my-bucket",
125
+ "hf buckets list user/my-bucket -R",
126
+ "hf buckets list user/my-bucket -h",
127
+ "hf buckets list user/my-bucket --tree",
128
+ "hf buckets list user/my-bucket --tree -h",
129
+ "hf buckets list hf://buckets/user/my-bucket",
130
+ "hf buckets list user/my-bucket/sub -R",
131
+ ],
132
+ )
133
+ def list_cmd(
134
+ argument: Annotated[
135
+ str | None,
136
+ Argument(
137
+ help=(
138
+ "Namespace (user or org) to list buckets, or bucket ID"
139
+ " (namespace/bucket_name(/prefix) or hf://buckets/...) to list files."
140
+ ),
141
+ ),
142
+ ] = None,
143
+ human_readable: Annotated[
144
+ bool,
145
+ Option(
146
+ "--human-readable",
147
+ "-h",
148
+ help="Show sizes in human readable format.",
149
+ ),
150
+ ] = False,
151
+ as_tree: Annotated[
152
+ bool,
153
+ Option(
154
+ "--tree",
155
+ help="List files in tree format (only for listing files).",
156
+ ),
157
+ ] = False,
158
+ recursive: Annotated[
159
+ bool,
160
+ Option(
161
+ "--recursive",
162
+ "-R",
163
+ help="List files recursively (only for listing files).",
164
+ ),
165
+ ] = False,
166
+ search: SearchOpt = None,
167
+ token: TokenOpt = None,
168
+ ) -> None:
169
+ """List buckets or files in a bucket.
170
+
171
+ When called with no argument or a namespace, lists buckets.
172
+ When called with a bucket ID (namespace/bucket_name), lists files in the bucket.
173
+ """
174
+ # Determine mode: listing buckets or listing files
175
+ is_file_mode = argument is not None and _is_bucket_id(argument)
176
+
177
+ if is_file_mode:
178
+ if search is not None:
179
+ raise click.BadParameter("Cannot use --search when listing files.")
180
+ _list_files(
181
+ argument=argument, # type: ignore
182
+ human_readable=human_readable,
183
+ as_tree=as_tree,
184
+ recursive=recursive,
185
+ token=token,
186
+ )
187
+ else:
188
+ _list_buckets(
189
+ namespace=argument,
190
+ search=search,
191
+ human_readable=human_readable,
192
+ as_tree=as_tree,
193
+ recursive=recursive,
194
+ token=token,
195
+ )
196
+
197
+
198
+ def _list_buckets(
199
+ namespace: str | None,
200
+ search: str | None,
201
+ human_readable: bool,
202
+ as_tree: bool,
203
+ recursive: bool,
204
+ token: str | None,
205
+ ) -> None:
206
+ """List buckets in a namespace."""
207
+ # Validate incompatible flags
208
+ if as_tree:
209
+ raise click.BadParameter("Cannot use --tree when listing buckets.")
210
+ if recursive:
211
+ raise click.BadParameter("Cannot use --recursive when listing buckets.")
212
+
213
+ # Handle hf://buckets/namespace format
214
+ if namespace is not None and namespace.startswith(BUCKET_PREFIX):
215
+ namespace = namespace[len(BUCKET_PREFIX) :]
216
+ # Strip trailing slash if any
217
+ namespace = namespace.rstrip("/")
218
+
219
+ api = get_hf_api(token=token)
220
+ items = [
221
+ {
222
+ "id": bucket.id,
223
+ "private": bucket.private,
224
+ "size": format_size(bucket.size, human_readable) if human_readable else bucket.size,
225
+ "total_files": bucket.total_files,
226
+ "created_at": bucket.created_at,
227
+ }
228
+ for bucket in api.list_buckets(namespace=namespace, search=search)
229
+ ]
230
+ out.table(items, alignments={"size": "right"})
231
+
232
+
233
+ def _list_files(
234
+ argument: str,
235
+ human_readable: bool,
236
+ as_tree: bool,
237
+ recursive: bool,
238
+ token: str | None,
239
+ ) -> None:
240
+ """List files in a bucket."""
241
+ if as_tree and out.mode == OutputFormat.json:
242
+ raise click.BadParameter("Cannot use --tree with --format json.")
243
+
244
+ api = get_hf_api(token=token)
245
+ parsed = _parse_bucket_uri(argument)
246
+ items = list(
247
+ api.list_bucket_tree(
248
+ parsed.id,
249
+ prefix=parsed.path_in_repo or None,
250
+ recursive=recursive,
251
+ )
252
+ )
253
+
254
+ print_file_listing(items, human_readable=human_readable, as_tree=as_tree, recursive=recursive)
255
+
256
+
257
+ @buckets_cli.command(
258
+ name="info",
259
+ examples=[
260
+ "hf buckets info user/my-bucket",
261
+ "hf buckets info hf://buckets/user/my-bucket",
262
+ ],
263
+ )
264
+ def info(
265
+ bucket_id: Annotated[
266
+ str,
267
+ Argument(
268
+ help="Bucket ID: namespace/bucket_name or hf://buckets/namespace/bucket_name",
269
+ ),
270
+ ],
271
+ token: TokenOpt = None,
272
+ ) -> None:
273
+ """Get info about a bucket."""
274
+ api = get_hf_api(token=token)
275
+ parsed = _parse_bucket_uri(bucket_id)
276
+ bucket = api.bucket_info(parsed.id)
277
+ out.dict(bucket, id_key="id")
278
+
279
+
280
+ @buckets_cli.command(
281
+ name="delete",
282
+ examples=[
283
+ "hf buckets delete user/my-bucket",
284
+ "hf buckets delete hf://buckets/user/my-bucket",
285
+ "hf buckets delete user/my-bucket --yes",
286
+ "hf buckets delete user/my-bucket --missing-ok",
287
+ ],
288
+ )
289
+ def delete(
290
+ bucket_id: Annotated[
291
+ str,
292
+ Argument(
293
+ help="Bucket ID: namespace/bucket_name or hf://buckets/namespace/bucket_name",
294
+ ),
295
+ ],
296
+ yes: Annotated[
297
+ bool,
298
+ Option(
299
+ "--yes",
300
+ "-y",
301
+ help="Skip confirmation prompt.",
302
+ ),
303
+ ] = False,
304
+ missing_ok: Annotated[
305
+ bool,
306
+ Option(
307
+ "--missing-ok",
308
+ help="Do not raise an error if the bucket does not exist.",
309
+ ),
310
+ ] = False,
311
+ token: TokenOpt = None,
312
+ ) -> None:
313
+ """Delete a bucket.
314
+
315
+ This deletes the entire bucket and all its contents. Use `hf buckets rm` to remove individual files.
316
+ """
317
+ if bucket_id.startswith(BUCKET_PREFIX):
318
+ parsed = _parse_bucket_uri(bucket_id)
319
+ if parsed.path_in_repo:
320
+ raise click.BadParameter(
321
+ f"Cannot specify a prefix for bucket deletion: {bucket_id}."
322
+ f" Use namespace/bucket_name or {BUCKET_PREFIX}namespace/bucket_name."
323
+ )
324
+ bucket_id = parsed.id
325
+ elif "/" not in bucket_id:
326
+ raise click.BadParameter(
327
+ f"Invalid bucket ID: {bucket_id}."
328
+ f" Must be in format namespace/bucket_name or {BUCKET_PREFIX}namespace/bucket_name."
329
+ )
330
+
331
+ out.confirm(f"Are you sure you want to delete bucket '{bucket_id}'?", yes=yes)
332
+
333
+ api = get_hf_api(token=token)
334
+ api.delete_bucket(bucket_id, missing_ok=missing_ok)
335
+ out.result("Bucket deleted", bucket_id=bucket_id)
336
+
337
+
338
+ @buckets_cli.command(
339
+ name="remove | rm",
340
+ examples=[
341
+ "hf buckets remove user/my-bucket/file.txt",
342
+ "hf buckets rm hf://buckets/user/my-bucket/file.txt",
343
+ "hf buckets rm user/my-bucket/logs/ --recursive",
344
+ 'hf buckets rm user/my-bucket --recursive --include "*.tmp"',
345
+ "hf buckets rm user/my-bucket/data/ --recursive --dry-run",
346
+ ],
347
+ )
348
+ def remove(
349
+ argument: Annotated[
350
+ str,
351
+ Argument(
352
+ help=(
353
+ "Bucket path: namespace/bucket_name/path or hf://buckets/namespace/bucket_name/path."
354
+ " With --recursive, namespace/bucket_name is also accepted to target all files."
355
+ ),
356
+ ),
357
+ ],
358
+ recursive: Annotated[
359
+ bool,
360
+ Option(
361
+ "--recursive",
362
+ "-R",
363
+ help="Remove files recursively under the given prefix.",
364
+ ),
365
+ ] = False,
366
+ yes: Annotated[
367
+ bool,
368
+ Option(
369
+ "--yes",
370
+ "-y",
371
+ help="Skip confirmation prompt.",
372
+ ),
373
+ ] = False,
374
+ dry_run: Annotated[
375
+ bool,
376
+ Option(
377
+ "--dry-run",
378
+ help="Preview what would be deleted without actually deleting.",
379
+ ),
380
+ ] = False,
381
+ include: Annotated[
382
+ list[str] | None,
383
+ Option(
384
+ help="Include only files matching pattern (can specify multiple). Requires --recursive.",
385
+ ),
386
+ ] = None,
387
+ exclude: Annotated[
388
+ list[str] | None,
389
+ Option(
390
+ help="Exclude files matching pattern (can specify multiple). Requires --recursive.",
391
+ ),
392
+ ] = None,
393
+ token: TokenOpt = None,
394
+ ) -> None:
395
+ """Remove files from a bucket.
396
+
397
+ To delete an entire bucket, use `hf buckets delete` instead.
398
+ """
399
+ parsed = _parse_bucket_uri(argument)
400
+ bucket_id = parsed.id
401
+ prefix = parsed.path_in_repo
402
+
403
+ if prefix == "" and not recursive:
404
+ raise click.BadParameter(
405
+ f"No file path specified. To remove files, provide a path"
406
+ f" (e.g. '{bucket_id}/FILE') or use --recursive to remove all files."
407
+ f" To delete the entire bucket, use `hf buckets delete {bucket_id}`."
408
+ )
409
+
410
+ if (include or exclude) and not recursive:
411
+ raise click.BadParameter("--include and --exclude require --recursive.")
412
+
413
+ api = get_hf_api(token=token)
414
+
415
+ if recursive:
416
+ status = out.status("Listing files from remote")
417
+
418
+ all_files: list[BucketFile] = []
419
+ for item in api.list_bucket_tree(
420
+ bucket_id,
421
+ prefix=prefix or None,
422
+ recursive=True,
423
+ ):
424
+ if isinstance(item, BucketFile):
425
+ all_files.append(item)
426
+ status.update(f"Listing files from remote ({len(all_files)} files)")
427
+ status.done(f"Listing files from remote ({len(all_files)} files)")
428
+
429
+ if include or exclude:
430
+ matcher = FilterMatcher(include_patterns=include, exclude_patterns=exclude)
431
+ matched_files = [f for f in all_files if matcher.matches(f.path)]
432
+ else:
433
+ matched_files = all_files
434
+
435
+ file_paths = [f.path for f in matched_files]
436
+ total_size = sum(f.size for f in matched_files)
437
+ size_str = format_size(total_size, human_readable=True)
438
+
439
+ if not file_paths:
440
+ out.text("No files to remove.")
441
+ return
442
+
443
+ count_label = f"{len(file_paths)} file(s) totaling {size_str}"
444
+
445
+ if not yes and not dry_run:
446
+ out.text("\n".join(f" {path}" for path in file_paths))
447
+ out.confirm(f"Remove {count_label} from '{bucket_id}'?", yes=False)
448
+
449
+ if dry_run:
450
+ out.text("\n".join(f"delete: {BUCKET_PREFIX}{bucket_id}/{path}" for path in file_paths))
451
+ out.text(f"(dry run) {count_label} would be removed.")
452
+ return
453
+
454
+ api.batch_bucket_files(bucket_id, delete=file_paths)
455
+ out.result(
456
+ f"Removed {count_label} from '{bucket_id}'",
457
+ bucket_id=bucket_id,
458
+ files_deleted=len(file_paths),
459
+ size=size_str,
460
+ )
461
+
462
+ else:
463
+ file_path = prefix
464
+ if not file_path:
465
+ raise click.BadParameter("File path cannot be empty.")
466
+
467
+ if dry_run:
468
+ out.text(f"delete: {BUCKET_PREFIX}{bucket_id}/{file_path}")
469
+ out.text("(dry run) 1 file would be removed.")
470
+ return
471
+
472
+ out.confirm(f"Remove '{file_path}' from '{bucket_id}'?", yes=yes)
473
+
474
+ api.batch_bucket_files(bucket_id, delete=[file_path])
475
+ out.result("File removed", path=file_path, bucket_id=bucket_id)
476
+
477
+
478
+ @buckets_cli.command(
479
+ name="move",
480
+ examples=[
481
+ "hf buckets move user/old-bucket user/new-bucket",
482
+ "hf buckets move user/my-bucket my-org/my-bucket",
483
+ "hf buckets move hf://buckets/user/old-bucket hf://buckets/user/new-bucket",
484
+ ],
485
+ )
486
+ def move(
487
+ from_id: Annotated[
488
+ str,
489
+ Argument(
490
+ help="Source bucket ID: namespace/bucket_name or hf://buckets/namespace/bucket_name",
491
+ ),
492
+ ],
493
+ to_id: Annotated[
494
+ str,
495
+ Argument(
496
+ help="Destination bucket ID: namespace/bucket_name or hf://buckets/namespace/bucket_name",
497
+ ),
498
+ ],
499
+ token: TokenOpt = None,
500
+ ) -> None:
501
+ """Move (rename) a bucket to a new name or namespace."""
502
+ # Parse from_id
503
+ parsed_from = _parse_bucket_uri(from_id)
504
+ if parsed_from.path_in_repo:
505
+ raise click.BadParameter(
506
+ f"Cannot specify a prefix for bucket move: {from_id}."
507
+ f" Use namespace/bucket_name or {BUCKET_PREFIX}namespace/bucket_name."
508
+ )
509
+
510
+ # Parse to_id
511
+ parsed_to = _parse_bucket_uri(to_id)
512
+ if parsed_to.path_in_repo:
513
+ raise click.BadParameter(
514
+ f"Cannot specify a prefix for bucket move: {to_id}."
515
+ f" Use namespace/bucket_name or {BUCKET_PREFIX}namespace/bucket_name."
516
+ )
517
+
518
+ api = get_hf_api(token=token)
519
+ api.move_bucket(from_id=parsed_from.id, to_id=parsed_to.id)
520
+ out.result("Bucket moved", from_id=parsed_from.id, to_id=parsed_to.id)
521
+
522
+
523
+ # =============================================================================
524
+ # Sync command
525
+ # =============================================================================
526
+
527
+
528
+ @buckets_cli.command(
529
+ name="sync",
530
+ examples=[
531
+ "hf buckets sync ./data hf://buckets/user/my-bucket",
532
+ "hf buckets sync hf://buckets/user/my-bucket ./data",
533
+ "hf buckets sync ./data hf://buckets/user/my-bucket --delete",
534
+ 'hf buckets sync hf://buckets/user/my-bucket ./data --include "*.safetensors" --exclude "*.tmp"',
535
+ "hf buckets sync ./data hf://buckets/user/my-bucket --plan sync-plan.jsonl",
536
+ "hf buckets sync --apply sync-plan.jsonl",
537
+ "hf buckets sync ./data hf://buckets/user/my-bucket --dry-run",
538
+ "hf buckets sync ./data hf://buckets/user/my-bucket --dry-run | jq .",
539
+ ],
540
+ )
541
+ def sync(
542
+ source: Annotated[
543
+ str | None,
544
+ Argument(
545
+ help="Source path: local directory or hf://buckets/namespace/bucket_name(/prefix)",
546
+ ),
547
+ ] = None,
548
+ dest: Annotated[
549
+ str | None,
550
+ Argument(
551
+ help="Destination path: local directory or hf://buckets/namespace/bucket_name(/prefix)",
552
+ ),
553
+ ] = None,
554
+ delete: Annotated[
555
+ bool,
556
+ Option(
557
+ help="Delete destination files not present in source.",
558
+ ),
559
+ ] = False,
560
+ ignore_times: Annotated[
561
+ bool,
562
+ Option(
563
+ "--ignore-times",
564
+ help="Skip files only based on size, ignoring modification times.",
565
+ ),
566
+ ] = False,
567
+ ignore_sizes: Annotated[
568
+ bool,
569
+ Option(
570
+ "--ignore-sizes",
571
+ help="Skip files only based on modification times, ignoring sizes.",
572
+ ),
573
+ ] = False,
574
+ plan: Annotated[
575
+ str | None,
576
+ Option(
577
+ help="Save sync plan to JSONL file for review instead of executing.",
578
+ ),
579
+ ] = None,
580
+ apply: Annotated[
581
+ str | None,
582
+ Option(
583
+ help="Apply a previously saved plan file.",
584
+ ),
585
+ ] = None,
586
+ dry_run: Annotated[
587
+ bool,
588
+ Option(
589
+ "--dry-run",
590
+ help="Print sync plan to stdout as JSONL without executing.",
591
+ ),
592
+ ] = False,
593
+ include: Annotated[
594
+ list[str] | None,
595
+ Option(
596
+ help="Include files matching pattern (can specify multiple).",
597
+ ),
598
+ ] = None,
599
+ exclude: Annotated[
600
+ list[str] | None,
601
+ Option(
602
+ help="Exclude files matching pattern (can specify multiple).",
603
+ ),
604
+ ] = None,
605
+ filter_from: Annotated[
606
+ str | None,
607
+ Option(
608
+ help="Read include/exclude patterns from file.",
609
+ ),
610
+ ] = None,
611
+ existing: Annotated[
612
+ bool,
613
+ Option(
614
+ "--existing",
615
+ help="Skip creating new files on receiver (only update existing files).",
616
+ ),
617
+ ] = False,
618
+ ignore_existing: Annotated[
619
+ bool,
620
+ Option(
621
+ "--ignore-existing",
622
+ help="Skip updating files that exist on receiver (only create new files).",
623
+ ),
624
+ ] = False,
625
+ verbose: Annotated[
626
+ bool,
627
+ Option(
628
+ "--verbose",
629
+ "-v",
630
+ help="Show detailed logging with reasoning.",
631
+ ),
632
+ ] = False,
633
+ token: TokenOpt = None,
634
+ ) -> None:
635
+ """Sync files between local directory and a bucket."""
636
+ api = get_hf_api(token=token)
637
+ api.sync_bucket(
638
+ source=source,
639
+ dest=dest,
640
+ delete=delete,
641
+ ignore_times=ignore_times,
642
+ ignore_sizes=ignore_sizes,
643
+ existing=existing,
644
+ ignore_existing=ignore_existing,
645
+ include=include,
646
+ exclude=exclude,
647
+ filter_from=filter_from,
648
+ plan=plan,
649
+ apply=apply,
650
+ dry_run=dry_run,
651
+ verbose=verbose,
652
+ quiet=out.is_quiet(),
653
+ )
654
+ if plan and not out.is_quiet():
655
+ out.hint(f"Run `hf buckets sync --apply {plan}` to execute this plan.")
656
+
657
+
658
+ # =============================================================================
659
+ # Cp command
660
+ # =============================================================================
661
+
662
+
663
+ # `hf buckets cp` is an alias for the top-level `hf cp` command (see `cli/_cp.py`).
664
+ buckets_cli.command(
665
+ name="cp",
666
+ examples=[
667
+ # Download (repo or bucket -> local / stdout)
668
+ "hf buckets cp hf://buckets/username/my-bucket/config.json config.json",
669
+ "hf buckets cp hf://buckets/username/my-bucket/data.csv data/",
670
+ "hf buckets cp hf://buckets/username/my-bucket/config.json -",
671
+ # Upload (local / stdin -> bucket)
672
+ "hf buckets cp model.safetensors hf://buckets/username/my-bucket/model.safetensors",
673
+ "hf buckets cp config.json hf://buckets/username/my-bucket/logs/",
674
+ "hf buckets cp - hf://buckets/username/my-bucket/config.json",
675
+ # Remote to remote (repo or bucket -> bucket)
676
+ "hf buckets cp hf://buckets/username/my-bucket/data.csv hf://buckets/username/dest-bucket/",
677
+ "hf buckets cp hf://buckets/username/source-bucket/logs/ hf://buckets/username/dest-bucket/logs/",
678
+ ],
679
+ )(make_cp("buckets"))
.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/cli/discussions.py ADDED
@@ -0,0 +1,497 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Contains commands to interact with discussions and pull requests on the Hugging Face Hub."""
15
+
16
+ import enum
17
+ import sys
18
+ from pathlib import Path
19
+ from typing import Annotated
20
+
21
+ import click
22
+
23
+ from huggingface_hub import constants
24
+
25
+ from ._cli_utils import (
26
+ AuthorOpt,
27
+ LimitOpt,
28
+ RepoIdArg,
29
+ RepoType,
30
+ RepoTypeOpt,
31
+ TokenOpt,
32
+ get_hf_api,
33
+ typer_factory,
34
+ )
35
+ from ._framework import Argument, Option
36
+ from ._output import _dataclass_to_dict, out
37
+
38
+
39
+ class DiscussionStatus(str, enum.Enum):
40
+ open = "open"
41
+ closed = "closed"
42
+ merged = "merged"
43
+ draft = "draft"
44
+ all = "all"
45
+
46
+
47
+ class DiscussionKind(str, enum.Enum):
48
+ all = "all"
49
+ discussion = "discussion"
50
+ pull_request = "pull_request"
51
+
52
+
53
+ # "merged" and "draft" are valid Discussion statuses but the Hub API filter
54
+ # (DiscussionStatusFilter) only accepts "all", "open", "closed". When the user
55
+ # asks for merged/draft we fetch with api_status=None (i.e. all) and filter
56
+ # client-side.
57
+ _CLIENT_SIDE_STATUSES = {"merged", "draft"}
58
+
59
+
60
+ DiscussionNumArg = Annotated[
61
+ int,
62
+ Argument(
63
+ help="The discussion or pull request number.",
64
+ min=1,
65
+ ),
66
+ ]
67
+
68
+
69
+ def _read_body(body: str | None, body_file: Path | None) -> str | None:
70
+ """Resolve body text from --body or --body-file (supports '-' for stdin)."""
71
+ if body is not None and body_file is not None:
72
+ raise click.BadParameter("Cannot use both --body and --body-file.")
73
+ if body_file is not None:
74
+ if str(body_file) == "-":
75
+ return sys.stdin.read()
76
+ return body_file.read_text(encoding="utf-8")
77
+ return body
78
+
79
+
80
+ discussions_cli = typer_factory(help="Manage discussions and pull requests on the Hub.")
81
+
82
+
83
+ @discussions_cli.command(
84
+ "list | ls",
85
+ examples=[
86
+ "hf discussions list username/my-model",
87
+ "hf discussions list username/my-model --kind pull_request --status merged",
88
+ "hf discussions list username/my-dataset --type dataset --status closed",
89
+ "hf discussions list username/my-model --author alice --format json",
90
+ ],
91
+ )
92
+ def discussion_list(
93
+ repo_id: RepoIdArg,
94
+ status: Annotated[
95
+ DiscussionStatus,
96
+ Option(
97
+ "-s",
98
+ "--status",
99
+ help="Filter by status (open, closed, merged, draft, all).",
100
+ ),
101
+ ] = DiscussionStatus.open,
102
+ kind: Annotated[
103
+ DiscussionKind,
104
+ Option(
105
+ "-k",
106
+ "--kind",
107
+ help="Filter by kind (discussion, pull_request, all).",
108
+ ),
109
+ ] = DiscussionKind.all,
110
+ author: AuthorOpt = None,
111
+ limit: LimitOpt = 30,
112
+ repo_type: RepoTypeOpt = RepoType.model,
113
+ token: TokenOpt = None,
114
+ ) -> None:
115
+ """List discussions and pull requests on a repo."""
116
+ api = get_hf_api(token=token)
117
+
118
+ api_status: constants.DiscussionStatusFilter | None
119
+ if status == DiscussionStatus.open:
120
+ api_status = "open"
121
+ elif status == DiscussionStatus.closed:
122
+ api_status = "closed"
123
+ else:
124
+ api_status = None
125
+
126
+ api_discussion_type: constants.DiscussionTypeFilter | None
127
+ if kind == DiscussionKind.all:
128
+ api_discussion_type = None
129
+ else:
130
+ api_discussion_type = kind.value # type: ignore[assignment]
131
+
132
+ discussions = []
133
+ for d in api.get_repo_discussions(
134
+ repo_id=repo_id,
135
+ author=author,
136
+ discussion_type=api_discussion_type,
137
+ discussion_status=api_status,
138
+ repo_type=repo_type.value,
139
+ ):
140
+ if status.value in _CLIENT_SIDE_STATUSES and d.status != status.value:
141
+ continue
142
+ discussions.append(d)
143
+ if len(discussions) >= limit:
144
+ break
145
+
146
+ items = [_dataclass_to_dict(d) for d in discussions]
147
+ out.table(
148
+ items,
149
+ headers=["num", "title", "is_pull_request", "status", "author", "created_at"],
150
+ id_key="num",
151
+ )
152
+
153
+
154
+ @discussions_cli.command(
155
+ "info",
156
+ examples=[
157
+ "hf discussions info username/my-model 5",
158
+ "hf discussions info username/my-model 5 --format json",
159
+ ],
160
+ )
161
+ def discussion_info(
162
+ repo_id: RepoIdArg,
163
+ num: DiscussionNumArg,
164
+ repo_type: RepoTypeOpt = RepoType.model,
165
+ token: TokenOpt = None,
166
+ ) -> None:
167
+ """Get info about a discussion or pull request."""
168
+ api = get_hf_api(token=token)
169
+ details = api.get_discussion_details(
170
+ repo_id=repo_id,
171
+ discussion_num=num,
172
+ repo_type=repo_type.value,
173
+ )
174
+ out.dict(details)
175
+
176
+
177
+ @discussions_cli.command(
178
+ "create",
179
+ examples=[
180
+ 'hf discussions create username/my-model --title "Bug report"',
181
+ 'hf discussions create username/my-model --title "Feature request" --body "Please add X"',
182
+ 'hf discussions create username/my-model --title "Fix typo" --pull-request',
183
+ 'hf discussions create username/my-dataset --type dataset --title "Data quality issue"',
184
+ ],
185
+ )
186
+ def discussion_create(
187
+ repo_id: RepoIdArg,
188
+ title: Annotated[
189
+ str,
190
+ Option(
191
+ "--title",
192
+ help="The title of the discussion or pull request.",
193
+ ),
194
+ ],
195
+ body: Annotated[
196
+ str | None,
197
+ Option(
198
+ "--body",
199
+ help="The description (supports Markdown).",
200
+ ),
201
+ ] = None,
202
+ body_file: Annotated[
203
+ Path | None,
204
+ Option(
205
+ "--body-file",
206
+ help="Read the description from a file. Use '-' for stdin.",
207
+ ),
208
+ ] = None,
209
+ pull_request: Annotated[
210
+ bool,
211
+ Option(
212
+ "--pull-request",
213
+ "--pr",
214
+ help="Create a pull request instead of a discussion.",
215
+ ),
216
+ ] = False,
217
+ repo_type: RepoTypeOpt = RepoType.model,
218
+ token: TokenOpt = None,
219
+ ) -> None:
220
+ """Create a new discussion or pull request on a repo."""
221
+ description = _read_body(body, body_file)
222
+ api = get_hf_api(token=token)
223
+ discussion = api.create_discussion(
224
+ repo_id=repo_id,
225
+ title=title,
226
+ description=description,
227
+ repo_type=repo_type.value,
228
+ pull_request=pull_request,
229
+ )
230
+ kind = "pull request" if pull_request else "discussion"
231
+ ref = f"refs/pr/{discussion.num}" if pull_request else None
232
+ out.result(f"Created {kind} #{discussion.num} on {repo_id}", num=discussion.num, url=discussion.url, ref=ref)
233
+
234
+
235
+ @discussions_cli.command(
236
+ "comment",
237
+ examples=[
238
+ 'hf discussions comment username/my-model 5 --body "Thanks for reporting!"',
239
+ 'hf discussions comment username/my-model 5 --body "LGTM!"',
240
+ ],
241
+ )
242
+ def discussion_comment(
243
+ repo_id: RepoIdArg,
244
+ num: DiscussionNumArg,
245
+ body: Annotated[
246
+ str | None,
247
+ Option(
248
+ "--body",
249
+ help="The comment text (supports Markdown).",
250
+ ),
251
+ ] = None,
252
+ body_file: Annotated[
253
+ Path | None,
254
+ Option(
255
+ "--body-file",
256
+ help="Read the comment from a file. Use '-' for stdin.",
257
+ ),
258
+ ] = None,
259
+ repo_type: RepoTypeOpt = RepoType.model,
260
+ token: TokenOpt = None,
261
+ ) -> None:
262
+ """Comment on a discussion or pull request."""
263
+ comment = _read_body(body, body_file)
264
+ if comment is None:
265
+ raise click.BadParameter("Either --body or --body-file is required.")
266
+ api = get_hf_api(token=token)
267
+ api.comment_discussion(
268
+ repo_id=repo_id,
269
+ discussion_num=num,
270
+ comment=comment,
271
+ repo_type=repo_type.value,
272
+ )
273
+ out.result(f"Commented on #{num} in {repo_id}", num=num, repo=repo_id)
274
+
275
+
276
+ @discussions_cli.command(
277
+ "edit",
278
+ examples=[
279
+ 'hf discussions edit username/my-model 5 abc123 --body "Updated comment."',
280
+ "hf discussions edit username/my-model 5 abc123 --body-file fixed.md",
281
+ ],
282
+ )
283
+ def discussion_edit(
284
+ repo_id: RepoIdArg,
285
+ num: DiscussionNumArg,
286
+ comment_id: Annotated[
287
+ str,
288
+ Argument(
289
+ help="The ID of the comment to edit (see 'hf discussions info ... --format json').",
290
+ ),
291
+ ],
292
+ body: Annotated[
293
+ str | None,
294
+ Option(
295
+ "--body",
296
+ help="The new comment text (supports Markdown).",
297
+ ),
298
+ ] = None,
299
+ body_file: Annotated[
300
+ Path | None,
301
+ Option(
302
+ "--body-file",
303
+ help="Read the new comment from a file. Use '-' for stdin.",
304
+ ),
305
+ ] = None,
306
+ repo_type: RepoTypeOpt = RepoType.model,
307
+ token: TokenOpt = None,
308
+ ) -> None:
309
+ """Edit an existing comment on a discussion or pull request."""
310
+ new_content = _read_body(body, body_file)
311
+ if new_content is None:
312
+ raise click.BadParameter("Either --body or --body-file is required.")
313
+ api = get_hf_api(token=token)
314
+ api.edit_discussion_comment(
315
+ repo_id=repo_id,
316
+ discussion_num=num,
317
+ comment_id=comment_id,
318
+ new_content=new_content,
319
+ repo_type=repo_type.value,
320
+ )
321
+ out.result(f"Edited comment {comment_id} on #{num} in {repo_id}", num=num, repo=repo_id, comment_id=comment_id)
322
+
323
+
324
+ @discussions_cli.command(
325
+ "close",
326
+ examples=[
327
+ "hf discussions close username/my-model 5",
328
+ 'hf discussions close username/my-model 5 --comment "Closing as resolved."',
329
+ ],
330
+ )
331
+ def discussion_close(
332
+ repo_id: RepoIdArg,
333
+ num: DiscussionNumArg,
334
+ comment: Annotated[
335
+ str | None,
336
+ Option(
337
+ "--comment",
338
+ help="An optional comment to post when closing.",
339
+ ),
340
+ ] = None,
341
+ yes: Annotated[
342
+ bool,
343
+ Option(
344
+ "--yes",
345
+ "-y",
346
+ help="Skip confirmation prompt.",
347
+ ),
348
+ ] = False,
349
+ repo_type: RepoTypeOpt = RepoType.model,
350
+ token: TokenOpt = None,
351
+ ) -> None:
352
+ """Close a discussion or pull request."""
353
+ out.confirm(f"Close #{num} on '{repo_id}'?", yes=yes)
354
+ api = get_hf_api(token=token)
355
+ api.change_discussion_status(
356
+ repo_id=repo_id,
357
+ discussion_num=num,
358
+ new_status="closed",
359
+ comment=comment,
360
+ repo_type=repo_type.value,
361
+ )
362
+ out.result(f"Closed #{num} in {repo_id}", num=num, repo=repo_id)
363
+
364
+
365
+ @discussions_cli.command(
366
+ "reopen",
367
+ examples=[
368
+ "hf discussions reopen username/my-model 5",
369
+ 'hf discussions reopen username/my-model 5 --comment "Reopening for further investigation."',
370
+ ],
371
+ )
372
+ def discussion_reopen(
373
+ repo_id: RepoIdArg,
374
+ num: DiscussionNumArg,
375
+ comment: Annotated[
376
+ str | None,
377
+ Option(
378
+ "--comment",
379
+ help="An optional comment to post when reopening.",
380
+ ),
381
+ ] = None,
382
+ yes: Annotated[
383
+ bool,
384
+ Option(
385
+ "--yes",
386
+ "-y",
387
+ help="Skip confirmation prompt.",
388
+ ),
389
+ ] = False,
390
+ repo_type: RepoTypeOpt = RepoType.model,
391
+ token: TokenOpt = None,
392
+ ) -> None:
393
+ """Reopen a closed discussion or pull request."""
394
+ out.confirm(f"Reopen #{num} on '{repo_id}'?", yes=yes)
395
+ api = get_hf_api(token=token)
396
+ api.change_discussion_status(
397
+ repo_id=repo_id,
398
+ discussion_num=num,
399
+ new_status="open",
400
+ comment=comment,
401
+ repo_type=repo_type.value,
402
+ )
403
+ out.result(f"Reopened #{num} in {repo_id}", num=num, repo=repo_id)
404
+
405
+
406
+ @discussions_cli.command(
407
+ "rename",
408
+ examples=[
409
+ 'hf discussions rename username/my-model 5 "Updated title"',
410
+ ],
411
+ )
412
+ def discussion_rename(
413
+ repo_id: RepoIdArg,
414
+ num: DiscussionNumArg,
415
+ new_title: Annotated[
416
+ str,
417
+ Argument(
418
+ help="The new title.",
419
+ ),
420
+ ],
421
+ repo_type: RepoTypeOpt = RepoType.model,
422
+ token: TokenOpt = None,
423
+ ) -> None:
424
+ """Rename a discussion or pull request."""
425
+ api = get_hf_api(token=token)
426
+ api.rename_discussion(
427
+ repo_id=repo_id,
428
+ discussion_num=num,
429
+ new_title=new_title,
430
+ repo_type=repo_type.value,
431
+ )
432
+ out.result(f"Renamed #{num} in {repo_id}", num=num, repo=repo_id, title=new_title)
433
+
434
+
435
+ @discussions_cli.command(
436
+ "merge",
437
+ examples=[
438
+ "hf discussions merge username/my-model 5",
439
+ 'hf discussions merge username/my-model 5 --comment "Merging, thanks!"',
440
+ ],
441
+ )
442
+ def discussion_merge(
443
+ repo_id: RepoIdArg,
444
+ num: DiscussionNumArg,
445
+ comment: Annotated[
446
+ str | None,
447
+ Option(
448
+ "--comment",
449
+ help="An optional comment to post when merging.",
450
+ ),
451
+ ] = None,
452
+ yes: Annotated[
453
+ bool,
454
+ Option(
455
+ "--yes",
456
+ "-y",
457
+ help="Skip confirmation prompt.",
458
+ ),
459
+ ] = False,
460
+ repo_type: RepoTypeOpt = RepoType.model,
461
+ token: TokenOpt = None,
462
+ ) -> None:
463
+ """Merge a pull request."""
464
+ out.confirm(f"Merge #{num} on '{repo_id}'?", yes=yes)
465
+ api = get_hf_api(token=token)
466
+ api.merge_pull_request(
467
+ repo_id=repo_id,
468
+ discussion_num=num,
469
+ comment=comment,
470
+ repo_type=repo_type.value,
471
+ )
472
+ out.result(f"Merged #{num} in {repo_id}", num=num, repo=repo_id)
473
+
474
+
475
+ @discussions_cli.command(
476
+ "diff",
477
+ examples=[
478
+ "hf discussions diff username/my-model 5",
479
+ ],
480
+ )
481
+ def discussion_diff(
482
+ repo_id: RepoIdArg,
483
+ num: DiscussionNumArg,
484
+ repo_type: RepoTypeOpt = RepoType.model,
485
+ token: TokenOpt = None,
486
+ ) -> None:
487
+ """Show the diff of a pull request."""
488
+ api = get_hf_api(token=token)
489
+ details = api.get_discussion_details(
490
+ repo_id=repo_id,
491
+ discussion_num=num,
492
+ repo_type=repo_type.value,
493
+ )
494
+ if details.diff:
495
+ out.text(details.diff)
496
+ else:
497
+ out.text("No diff available.")
.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/cli/download.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 202-present, the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Contains command to download files from the Hub with the CLI."""
15
+
16
+ import warnings
17
+ from typing import Annotated
18
+
19
+ from huggingface_hub import constants
20
+ from huggingface_hub._snapshot_download import snapshot_download
21
+ from huggingface_hub.errors import CLIError
22
+ from huggingface_hub.file_download import DryRunFileInfo, hf_hub_download
23
+ from huggingface_hub.utils import _format_size, parse_hf_uri
24
+
25
+ from ._cli_utils import RepoIdArg, RepoType, RepoTypeOptionalOpt, RevisionOpt, TokenOpt
26
+ from ._framework import Argument, Option
27
+ from ._output import out
28
+
29
+
30
+ DOWNLOAD_EXAMPLES = [
31
+ "hf download meta-llama/Llama-3.2-1B-Instruct",
32
+ "hf download meta-llama/Llama-3.2-1B-Instruct config.json tokenizer.json",
33
+ 'hf download meta-llama/Llama-3.2-1B-Instruct --include "*.safetensors" --exclude "*.bin"',
34
+ "hf download meta-llama/Llama-3.2-1B-Instruct --local-dir ./models/llama",
35
+ "hf download HuggingFaceM4/FineVision art/ --repo-type dataset",
36
+ "hf download hf://datasets/HuggingFaceH4/ultrachat_200k",
37
+ ]
38
+
39
+
40
+ def download(
41
+ repo_id: RepoIdArg,
42
+ filenames: Annotated[
43
+ list[str] | None,
44
+ Argument(
45
+ help="Files to download (e.g. `config.json`, `data/metadata.jsonl`).",
46
+ ),
47
+ ] = None,
48
+ repo_type: RepoTypeOptionalOpt = None,
49
+ revision: RevisionOpt = None,
50
+ include: Annotated[
51
+ list[str] | None,
52
+ Option(
53
+ help="Glob patterns to include from files to download. eg: *.json",
54
+ ),
55
+ ] = None,
56
+ exclude: Annotated[
57
+ list[str] | None,
58
+ Option(
59
+ help="Glob patterns to exclude from files to download.",
60
+ ),
61
+ ] = None,
62
+ cache_dir: Annotated[
63
+ str | None,
64
+ Option(
65
+ help="Directory where to save files.",
66
+ ),
67
+ ] = None,
68
+ local_dir: Annotated[
69
+ str | None,
70
+ Option(
71
+ help="If set, the downloaded file will be placed under this directory. Check out https://huggingface.co/docs/huggingface_hub/guides/download#download-files-to-a-local-folder for more details.",
72
+ ),
73
+ ] = None,
74
+ force_download: Annotated[
75
+ bool,
76
+ Option(
77
+ help="If True, the files will be downloaded even if they are already cached.",
78
+ ),
79
+ ] = False,
80
+ dry_run: Annotated[
81
+ bool,
82
+ Option(
83
+ help="If True, perform a dry run without actually downloading the file.",
84
+ ),
85
+ ] = False,
86
+ token: TokenOpt = None,
87
+ max_workers: Annotated[
88
+ int,
89
+ Option(
90
+ help="Maximum number of workers to use for downloading files. Default is 8.",
91
+ ),
92
+ ] = 8,
93
+ ) -> None:
94
+ """Download files from the Hub."""
95
+ if local_dir is not None and cache_dir is not None:
96
+ raise CLIError(
97
+ "Cannot use both `--local-dir` and `--cache-dir` at the same time. "
98
+ "Use `--cache-dir` (or set the HF_HOME environment variable) for shared caching, "
99
+ "or `--local-dir` for a one-off download to a specific directory."
100
+ )
101
+
102
+ # `repo_id` may be a plain repo id or an `hf://` URI (e.g. `hf://datasets/my-org/my-dataset@v1.0/data/`).
103
+ # When a URI is provided, it is authoritative for the repo type, revision and (optionally) file path,
104
+ # so explicit `--repo-type` / `--revision` options are forbidden alongside it.
105
+ # We branch on the `hf://` prefix (the user's *intent*) rather than on whether the string parses as a
106
+ # valid URI: a malformed URI then surfaces a precise `HfUriError` (formatted globally in `cli/_errors.py`)
107
+ # instead of silently falling through to the plain-repo-id path and failing later with an opaque error.
108
+ if repo_id.startswith(constants.HF_PROTOCOL):
109
+ if repo_type is not None:
110
+ raise CLIError(f"'--repo-type' cannot be used with an 'hf://' URI ('{repo_id}').")
111
+ if revision is not None:
112
+ raise CLIError(f"'--revision' cannot be used with an 'hf://' URI ('{repo_id}').")
113
+ uri = parse_hf_uri(repo_id)
114
+ if uri.is_bucket:
115
+ raise CLIError("Buckets are not supported by `hf download`. Use `hf sync` instead.")
116
+ # The URI parser strips trailing slashes, but `hf download` uses a trailing '/' to denote a subfolder
117
+ # download (e.g. `data/` -> `data/**`). Re-append it when the URI explicitly ended with '/' so a folder
118
+ # URI keeps routing through the subfolder code path below.
119
+ path_in_repo = uri.path_in_repo
120
+ if path_in_repo and repo_id.endswith("/"):
121
+ path_in_repo += "/"
122
+ repo_id, repo_type_str, revision = uri.id, uri.type, uri.revision
123
+ if path_in_repo:
124
+ if filenames:
125
+ raise CLIError(
126
+ f"Cannot combine a file path in the hf:// URI ('{path_in_repo}') with positional filenames {filenames}."
127
+ )
128
+ filenames = [path_in_repo]
129
+ else:
130
+ repo_type_str = (repo_type or RepoType.model).value
131
+
132
+ def run_download() -> str | DryRunFileInfo | list[DryRunFileInfo]:
133
+ filenames_list = filenames if filenames is not None else []
134
+
135
+ # Separate subfolder patterns (ending with '/') from regular filenames
136
+ # Subfolders like "art/" are converted to include patterns like "art/**"
137
+ subfolders = [f for f in filenames_list if f.endswith("/")]
138
+ subfolder_patterns = [f"{f.rstrip('/')}/**" for f in subfolders]
139
+ regular_filenames = [f for f in filenames_list if not f.endswith("/")]
140
+
141
+ # Error if subfolder patterns are combined with --include/--exclude
142
+ # Guide user to use --include instead of subfolder argument
143
+ if len(subfolder_patterns) > 0:
144
+ if include is not None and len(include) > 0:
145
+ raise CLIError(
146
+ f"Cannot combine subfolder argument ('{subfolders[0]}') with `--include`. "
147
+ f'Please use `--include "{subfolders[0]}*"` instead.'
148
+ )
149
+ if exclude is not None and len(exclude) > 0:
150
+ raise CLIError(
151
+ f"Cannot combine subfolder argument ('{subfolders[0]}') with `--exclude`. "
152
+ f'Please use `--include "{subfolders[0]}*"` with `--exclude` instead.'
153
+ )
154
+
155
+ # Warn user if patterns are ignored (only if regular filenames are provided)
156
+ if len(regular_filenames) > 0:
157
+ if include is not None and len(include) > 0:
158
+ warnings.warn("Ignoring `--include` since filenames have been explicitly set.")
159
+ if exclude is not None and len(exclude) > 0:
160
+ warnings.warn("Ignoring `--exclude` since filenames have been explicitly set.")
161
+
162
+ # Single file to download (not a subfolder): use `hf_hub_download`
163
+ if len(regular_filenames) == 1 and len(subfolder_patterns) == 0:
164
+ return hf_hub_download(
165
+ repo_id=repo_id,
166
+ repo_type=repo_type_str,
167
+ revision=revision,
168
+ filename=regular_filenames[0],
169
+ cache_dir=cache_dir,
170
+ force_download=force_download,
171
+ token=token,
172
+ local_dir=local_dir,
173
+ library_name="huggingface-cli",
174
+ dry_run=dry_run,
175
+ )
176
+
177
+ # Otherwise: use `snapshot_download` to ensure all files comes from same revision
178
+ if len(regular_filenames) == 0 and len(subfolder_patterns) == 0:
179
+ # No filenames provided: use include/exclude patterns
180
+ allow_patterns = include
181
+ ignore_patterns = exclude
182
+ else:
183
+ # Combine regular filenames and subfolder patterns as allow_patterns
184
+ allow_patterns = regular_filenames + subfolder_patterns
185
+ ignore_patterns = None
186
+
187
+ return snapshot_download(
188
+ repo_id=repo_id,
189
+ repo_type=repo_type_str,
190
+ revision=revision,
191
+ allow_patterns=allow_patterns,
192
+ ignore_patterns=ignore_patterns,
193
+ force_download=force_download,
194
+ cache_dir=cache_dir,
195
+ token=token,
196
+ local_dir=local_dir,
197
+ library_name="huggingface-cli",
198
+ max_workers=max_workers,
199
+ dry_run=dry_run,
200
+ )
201
+
202
+ def _print_result(result: str | DryRunFileInfo | list[DryRunFileInfo]) -> None:
203
+ if isinstance(result, str):
204
+ out.result("Downloaded", path=result)
205
+ return
206
+
207
+ # Print dry run info
208
+ if isinstance(result, DryRunFileInfo):
209
+ result = [result]
210
+ will_download = [r for r in result if r.will_download]
211
+ out.text(
212
+ f"[dry-run] Will download {len(will_download)} files"
213
+ f" (out of {len(result)})"
214
+ f" totalling {_format_size(sum(r.file_size for r in will_download))}."
215
+ )
216
+ items = [
217
+ {
218
+ "file": info.filename,
219
+ "size": _format_size(info.file_size) if info.will_download else "-",
220
+ }
221
+ for info in sorted(result, key=lambda x: x.filename)
222
+ ]
223
+ out.table(items)
224
+
225
+ _print_result(run_download())
.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/cli/hf.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import os
16
+ import sys
17
+ import traceback
18
+ from typing import Annotated
19
+
20
+ import click
21
+
22
+ from huggingface_hub import __version__, constants
23
+ from huggingface_hub.cli._cli_utils import check_cli_update, fallback_typer_group_factory, typer_factory
24
+ from huggingface_hub.cli._cp import CP_EXAMPLES, make_cp
25
+ from huggingface_hub.cli._errors import format_known_exception
26
+ from huggingface_hub.cli._output import out
27
+ from huggingface_hub.cli.auth import auth_cli
28
+ from huggingface_hub.cli.buckets import buckets_cli, sync
29
+ from huggingface_hub.cli.cache import cache_cli
30
+ from huggingface_hub.cli.collections import collections_cli
31
+ from huggingface_hub.cli.datasets import datasets_cli
32
+ from huggingface_hub.cli.discussions import discussions_cli
33
+ from huggingface_hub.cli.download import DOWNLOAD_EXAMPLES, download
34
+ from huggingface_hub.cli.extensions import (
35
+ dispatch_unknown_top_level_extension,
36
+ extensions_cli,
37
+ list_installed_extensions_for_help,
38
+ )
39
+ from huggingface_hub.cli.inference_endpoints import ie_cli
40
+ from huggingface_hub.cli.jobs import jobs_cli
41
+ from huggingface_hub.cli.lfs import lfs_enable_largefiles, lfs_multipart_upload
42
+ from huggingface_hub.cli.models import models_cli
43
+ from huggingface_hub.cli.papers import papers_cli
44
+ from huggingface_hub.cli.repo_files import repo_files_cli
45
+ from huggingface_hub.cli.repos import repos_cli
46
+ from huggingface_hub.cli.sandbox import sandbox_cli
47
+ from huggingface_hub.cli.skills import skills_cli
48
+ from huggingface_hub.cli.spaces import spaces_cli
49
+ from huggingface_hub.cli.system import env, update, version
50
+ from huggingface_hub.cli.upload import UPLOAD_EXAMPLES, upload
51
+ from huggingface_hub.cli.upload_large_folder import UPLOAD_LARGE_FOLDER_EXAMPLES, upload_large_folder
52
+ from huggingface_hub.cli.webhooks import webhooks_cli
53
+ from huggingface_hub.utils import logging
54
+
55
+ from ._completion import _COMPLETE_VAR, InstallCompletionOpt, ShowCompletionOpt
56
+ from ._framework import Option
57
+
58
+
59
+ app = typer_factory(
60
+ help="Hugging Face Hub CLI",
61
+ cls=fallback_typer_group_factory(
62
+ dispatch_unknown_top_level_extension,
63
+ extra_commands_provider=list_installed_extensions_for_help,
64
+ ),
65
+ )
66
+
67
+
68
+ def _version_callback(value: bool) -> None:
69
+ if value:
70
+ print(__version__)
71
+ raise click.exceptions.Exit()
72
+
73
+
74
+ @app.group_callback(invoke_without_command=True)
75
+ def app_callback(
76
+ version: Annotated[
77
+ bool | None, Option("-v", "--version", callback=_version_callback, is_eager=True, hidden=True)
78
+ ] = None,
79
+ install_completion: InstallCompletionOpt = False,
80
+ show_completion: ShowCompletionOpt = False,
81
+ ) -> None:
82
+ pass
83
+
84
+
85
+ # top level single commands (defined in their respective files)
86
+ app.command(examples=CP_EXAMPLES)(make_cp())
87
+ app.command()(sync)
88
+ app.command(examples=DOWNLOAD_EXAMPLES)(download)
89
+ app.command(examples=UPLOAD_EXAMPLES)(upload)
90
+ app.command(examples=UPLOAD_LARGE_FOLDER_EXAMPLES)(upload_large_folder)
91
+
92
+ app.command(topic="help")(env)
93
+ app.command(topic="help")(update)
94
+ app.command(topic="help")(version)
95
+
96
+ app.command(hidden=True)(lfs_enable_largefiles)
97
+ app.command(hidden=True)(lfs_multipart_upload)
98
+
99
+ # command groups
100
+ app.add_group(auth_cli, name="auth")
101
+ app.add_group(buckets_cli, name="buckets")
102
+ app.add_group(cache_cli, name="cache")
103
+ app.add_group(collections_cli, name="collections")
104
+ app.add_group(datasets_cli, name="datasets")
105
+ app.add_group(discussions_cli, name="discussions")
106
+ app.add_group(jobs_cli, name="jobs")
107
+ app.add_group(models_cli, name="models")
108
+ app.add_group(papers_cli, name="papers")
109
+ app.add_group(repos_cli, name="repos | repo")
110
+ app.add_group(repo_files_cli, name="repo-files", hidden=True)
111
+ app.add_group(sandbox_cli, name="sandbox")
112
+ app.add_group(skills_cli, name="skills")
113
+ app.add_group(spaces_cli, name="spaces")
114
+ app.add_group(webhooks_cli, name="webhooks")
115
+ app.add_group(ie_cli, name="endpoints")
116
+ app.add_group(extensions_cli, name="extensions | ext")
117
+
118
+
119
+ def main():
120
+ # Shell-completion requests must stay fast and emit nothing but candidates:
121
+ # skip the startup work and let click handle the env var inside `app()`.
122
+ if _COMPLETE_VAR not in os.environ:
123
+ if not constants.HF_DEBUG:
124
+ logging.set_verbosity_info()
125
+ check_cli_update("huggingface_hub")
126
+
127
+ try:
128
+ app()
129
+ except Exception as e:
130
+ message = format_known_exception(e)
131
+ if message:
132
+ out.error(message)
133
+ if constants.HF_DEBUG:
134
+ traceback.print_exc()
135
+ else:
136
+ out.hint("set HF_DEBUG=1 as environment variable for full traceback.")
137
+ sys.exit(1)
138
+ raise
139
+
140
+
141
+ if __name__ == "__main__":
142
+ main()
.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/cli/lfs.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Implementation of a custom transfer agent for the transfer type "multipart" for
3
+ git-lfs.
4
+
5
+ Inspired by:
6
+ github.com/cbartz/git-lfs-swift-transfer-agent/blob/master/git_lfs_swift_transfer.py
7
+
8
+ Spec is: github.com/git-lfs/git-lfs/blob/master/docs/custom-transfers.md
9
+
10
+
11
+ To launch debugger while developing:
12
+
13
+ ``` [lfs "customtransfer.multipart"]
14
+ path = /path/to/huggingface_hub/.venv/bin/python args = -m debugpy --listen 5678
15
+ --wait-for-client
16
+ /path/to/huggingface_hub/src/huggingface_hub/commands/huggingface_cli.py
17
+ lfs-multipart-upload ```"""
18
+
19
+ import json
20
+ import os
21
+ import subprocess
22
+ import sys
23
+ from typing import Annotated
24
+
25
+ from huggingface_hub.errors import CLIError
26
+ from huggingface_hub.lfs import LFS_MULTIPART_UPLOAD_COMMAND
27
+
28
+ from ..utils import get_session, hf_raise_for_status, logging
29
+ from ..utils._lfs import SliceFileObj
30
+ from ._framework import Argument
31
+ from ._output import out
32
+
33
+
34
+ logger = logging.get_logger(__name__)
35
+
36
+
37
+ def lfs_enable_largefiles(
38
+ path: Annotated[
39
+ str,
40
+ Argument(
41
+ help="Local path to repository you want to configure.",
42
+ ),
43
+ ],
44
+ ) -> None:
45
+ """
46
+ Configure your repository to enable upload of files > 5GB.
47
+
48
+ This command sets up git-lfs to use the custom multipart transfer agent
49
+ which enables efficient uploading of large files in chunks.
50
+ """
51
+ local_path = os.path.abspath(path)
52
+ if not os.path.isdir(local_path):
53
+ raise CLIError("This does not look like a valid git repo.")
54
+ subprocess.run(
55
+ "git config lfs.customtransfer.multipart.path hf".split(),
56
+ check=True,
57
+ cwd=local_path,
58
+ )
59
+ subprocess.run(
60
+ f"git config lfs.customtransfer.multipart.args {LFS_MULTIPART_UPLOAD_COMMAND}".split(),
61
+ check=True,
62
+ cwd=local_path,
63
+ )
64
+ out.result("Local repo set up for largefiles", path=local_path)
65
+
66
+
67
+ def write_msg(msg: dict):
68
+ """Write out the message in Line delimited JSON."""
69
+ msg_str = json.dumps(msg) + "\n"
70
+ sys.stdout.write(msg_str)
71
+ sys.stdout.flush()
72
+
73
+
74
+ def read_msg() -> dict | None:
75
+ """Read Line delimited JSON from stdin."""
76
+ msg = json.loads(sys.stdin.readline().strip())
77
+
78
+ if "terminate" in (msg.get("type"), msg.get("event")):
79
+ # terminate message received
80
+ return None
81
+
82
+ if msg.get("event") not in ("download", "upload"):
83
+ logger.critical("Received unexpected message")
84
+ sys.exit(1)
85
+
86
+ return msg
87
+
88
+
89
+ def lfs_multipart_upload() -> None:
90
+ """Internal git-lfs custom transfer agent for multipart uploads.
91
+
92
+ This function implements the custom transfer protocol for git-lfs multipart uploads.
93
+ Handles chunked uploads of large files to Hugging Face Hub.
94
+ """
95
+ # Immediately after invoking a custom transfer process, git-lfs
96
+ # sends initiation data to the process over stdin.
97
+ # This tells the process useful information about the configuration.
98
+ init_msg = json.loads(sys.stdin.readline().strip())
99
+ if not (init_msg.get("event") == "init" and init_msg.get("operation") == "upload"):
100
+ write_msg({"error": {"code": 32, "message": "Wrong lfs init operation"}})
101
+ sys.exit(1)
102
+
103
+ # The transfer process should use the information it needs from the
104
+ # initiation structure, and also perform any one-off setup tasks it
105
+ # needs to do. It should then respond on stdout with a simple empty
106
+ # confirmation structure, as follows:
107
+ write_msg({})
108
+
109
+ # After the initiation exchange, git-lfs will send any number of
110
+ # transfer requests to the stdin of the transfer process, in a serial sequence.
111
+ while True:
112
+ msg = read_msg()
113
+ if msg is None:
114
+ # When all transfers have been processed, git-lfs will send
115
+ # a terminate event to the stdin of the transfer process.
116
+ # On receiving this message the transfer process should
117
+ # clean up and terminate. No response is expected.
118
+ sys.exit(0)
119
+
120
+ oid = msg["oid"]
121
+ filepath = msg["path"]
122
+ completion_url = msg["action"]["href"]
123
+ header = msg["action"]["header"]
124
+ chunk_size = int(header.pop("chunk_size"))
125
+ presigned_urls: list[str] = list(header.values())
126
+
127
+ # Send a "started" progress event to allow other workers to start.
128
+ # Otherwise they're delayed until first "progress" event is reported,
129
+ # i.e. after the first 5GB by default (!)
130
+ write_msg(
131
+ {
132
+ "event": "progress",
133
+ "oid": oid,
134
+ "bytesSoFar": 1,
135
+ "bytesSinceLast": 0,
136
+ }
137
+ )
138
+
139
+ parts = []
140
+ with open(filepath, "rb") as file:
141
+ for i, presigned_url in enumerate(presigned_urls):
142
+ with SliceFileObj(
143
+ file,
144
+ seek_from=i * chunk_size,
145
+ read_limit=chunk_size,
146
+ ) as data:
147
+ r = get_session().put(presigned_url, data=data)
148
+ hf_raise_for_status(r)
149
+ parts.append(
150
+ {
151
+ "etag": r.headers.get("etag"),
152
+ "partNumber": i + 1,
153
+ }
154
+ )
155
+ # In order to support progress reporting while data is uploading / downloading,
156
+ # the transfer process should post messages to stdout
157
+ write_msg(
158
+ {
159
+ "event": "progress",
160
+ "oid": oid,
161
+ "bytesSoFar": (i + 1) * chunk_size,
162
+ "bytesSinceLast": chunk_size,
163
+ }
164
+ )
165
+
166
+ r = get_session().post(
167
+ completion_url,
168
+ json={
169
+ "oid": oid,
170
+ "parts": parts,
171
+ },
172
+ )
173
+ hf_raise_for_status(r)
174
+
175
+ write_msg({"event": "complete", "oid": oid})
.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/cli/spaces.py ADDED
@@ -0,0 +1,1090 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Contains commands to interact with spaces on the Hugging Face Hub."""
15
+
16
+ import enum
17
+ import functools
18
+ import itertools
19
+ import os
20
+ import shlex
21
+ import shutil
22
+ import subprocess
23
+ import sys
24
+ import tempfile
25
+ import time
26
+ from collections import deque
27
+ from pathlib import Path
28
+ from typing import TYPE_CHECKING, Annotated, Literal, get_args
29
+
30
+ import click
31
+ from packaging import version
32
+ from typing_extensions import assert_never
33
+
34
+ from huggingface_hub._hot_reload.client import multi_replica_reload_events
35
+ from huggingface_hub._hot_reload.types import ApiGetReloadEventSourceData, ReloadRegion
36
+ from huggingface_hub._space_api import SpaceHardware, SpaceStage
37
+ from huggingface_hub.cli._cli_utils import SoftChoice
38
+ from huggingface_hub.errors import CLIError, RemoteEntryNotFoundError, RepositoryNotFoundError, RevisionNotFoundError
39
+ from huggingface_hub.file_download import hf_hub_download
40
+ from huggingface_hub.hf_api import ExpandSpaceProperty_T, HfApi, SpaceSort_T
41
+ from huggingface_hub.repocard import SpaceCard
42
+ from huggingface_hub.utils import disable_progress_bars
43
+ from huggingface_hub.utils._parsing import parse_duration
44
+
45
+ from ._cli_utils import (
46
+ REPO_LIST_DEFAULT_LIMIT,
47
+ AuthorOpt,
48
+ EnvFileOpt,
49
+ EnvOpt,
50
+ FilterOpt,
51
+ LimitOpt,
52
+ RevisionOpt,
53
+ SearchOpt,
54
+ SecretsFileOpt,
55
+ SecretsOpt,
56
+ SshDryRunOpt,
57
+ SshIdentityFileOpt,
58
+ TokenOpt,
59
+ VolumesOpt,
60
+ exec_ssh,
61
+ get_hf_api,
62
+ make_expand_properties_parser,
63
+ parse_env_map,
64
+ parse_volumes,
65
+ typer_factory,
66
+ )
67
+ from ._file_listing import list_repo_files_cmd
68
+ from ._framework import Argument, Option
69
+ from ._output import _dataclass_to_dict, out
70
+
71
+
72
+ HOT_RELOADING_MIN_GRADIO = "6.1.0"
73
+
74
+
75
+ _EXPAND_PROPERTIES = sorted(get_args(ExpandSpaceProperty_T))
76
+ _SORT_OPTIONS = get_args(SpaceSort_T)
77
+ SpaceSortEnum = enum.Enum("SpaceSortEnum", {s: s for s in _SORT_OPTIONS}, type=str) # type: ignore[misc]
78
+
79
+
80
+ ExpandOpt = Annotated[
81
+ str | None,
82
+ Option(
83
+ help=f"Comma-separated properties to return. When used, only the listed properties (and id) are returned. Example: '--expand=likes,tags'. Valid: {', '.join(_EXPAND_PROPERTIES)}.",
84
+ callback=make_expand_properties_parser(_EXPAND_PROPERTIES),
85
+ ),
86
+ ]
87
+
88
+ spaces_cli = typer_factory(help="Interact with spaces on the Hub.")
89
+ volumes_cli = typer_factory(help="Manage volumes for a Space on the Hub.")
90
+ secrets_cli = typer_factory(help="Manage secrets for a Space on the Hub.")
91
+ variables_cli = typer_factory(help="Manage environment variables for a Space on the Hub.")
92
+ spaces_cli.add_group(volumes_cli, name="volumes")
93
+ spaces_cli.add_group(secrets_cli, name="secrets")
94
+ spaces_cli.add_group(variables_cli, name="variables")
95
+
96
+
97
+ @spaces_cli.command(
98
+ "list | ls",
99
+ examples=[
100
+ "hf spaces ls --limit 10",
101
+ 'hf spaces ls --search "chatbot" --author huggingface',
102
+ "hf spaces ls victor/deepsite",
103
+ "hf spaces ls victor/deepsite -R",
104
+ "hf spaces ls victor/deepsite --tree -h",
105
+ ],
106
+ )
107
+ def spaces_ls(
108
+ repo_id: Annotated[
109
+ str | None,
110
+ Argument(help="Space ID (e.g. `username/repo-name`) to list files from. If omitted, lists spaces."),
111
+ ] = None,
112
+ search: SearchOpt = None,
113
+ author: AuthorOpt = None,
114
+ filter: FilterOpt = None,
115
+ sort: Annotated[
116
+ SpaceSortEnum | None,
117
+ Option(help="Sort results."),
118
+ ] = None,
119
+ limit: LimitOpt = REPO_LIST_DEFAULT_LIMIT,
120
+ expand: ExpandOpt = None,
121
+ human_readable: Annotated[
122
+ bool,
123
+ Option("--human-readable", "-h", help="Show sizes in human readable format (only for listing files)."),
124
+ ] = False,
125
+ as_tree: Annotated[
126
+ bool,
127
+ Option("--tree", help="List files in tree format (only for listing files)."),
128
+ ] = False,
129
+ recursive: Annotated[
130
+ bool,
131
+ Option("--recursive", "-R", help="List files recursively (only for listing files)."),
132
+ ] = False,
133
+ revision: RevisionOpt = None,
134
+ token: TokenOpt = None,
135
+ ) -> None:
136
+ """List spaces on the Hub, or files in a space repo.
137
+
138
+ When called with no argument, lists spaces on the Hub.
139
+ When called with a space ID, lists files in that space repo.
140
+ """
141
+ if repo_id is not None:
142
+ if search is not None:
143
+ raise click.BadParameter("Cannot use --search when listing files.")
144
+ if author is not None:
145
+ raise click.BadParameter("Cannot use --author when listing files.")
146
+ if filter is not None:
147
+ raise click.BadParameter("Cannot use --filter when listing files.")
148
+ if sort is not None:
149
+ raise click.BadParameter("Cannot use --sort when listing files.")
150
+ if limit != REPO_LIST_DEFAULT_LIMIT:
151
+ raise click.BadParameter("Cannot use --limit when listing files.")
152
+ if expand is not None:
153
+ raise click.BadParameter("Cannot use --expand when listing files.")
154
+ return list_repo_files_cmd(
155
+ repo_id=repo_id,
156
+ repo_type="space",
157
+ human_readable=human_readable,
158
+ as_tree=as_tree,
159
+ recursive=recursive,
160
+ revision=revision,
161
+ token=token,
162
+ )
163
+
164
+ if as_tree:
165
+ raise click.BadParameter("Cannot use --tree when listing spaces.")
166
+ if recursive:
167
+ raise click.BadParameter("Cannot use --recursive when listing spaces.")
168
+ if human_readable:
169
+ raise click.BadParameter("Cannot use --human-readable when listing spaces.")
170
+ if revision is not None:
171
+ raise click.BadParameter("Cannot use --revision when listing spaces.")
172
+ api = get_hf_api(token=token)
173
+ sort_key = sort.value if sort else None
174
+ results = [
175
+ _dataclass_to_dict(space_info)
176
+ for space_info in api.list_spaces(
177
+ filter=filter,
178
+ author=author,
179
+ search=search,
180
+ sort=sort_key,
181
+ limit=limit,
182
+ expand=expand, # type: ignore[arg-type]
183
+ )
184
+ ]
185
+ out.table(results)
186
+
187
+
188
+ @spaces_cli.command(
189
+ "info",
190
+ examples=[
191
+ "hf spaces info enzostvs/deepsite",
192
+ "hf spaces info gradio/theme_builder --expand sdk,runtime,likes",
193
+ ],
194
+ )
195
+ def spaces_info(
196
+ space_id: Annotated[str, Argument(help="The space ID (e.g. `username/repo-name`).")],
197
+ revision: RevisionOpt = None,
198
+ expand: ExpandOpt = None,
199
+ token: TokenOpt = None,
200
+ ) -> None:
201
+ """Get info about a space on the Hub."""
202
+ api = get_hf_api(token=token)
203
+ try:
204
+ info = api.space_info(repo_id=space_id, revision=revision, expand=expand) # type: ignore[arg-type]
205
+ except RepositoryNotFoundError as e:
206
+ raise CLIError(f"Space '{space_id}' not found.") from e
207
+ except RevisionNotFoundError as e:
208
+ raise CLIError(f"Revision '{revision}' not found on '{space_id}'.") from e
209
+ out.dict(info)
210
+
211
+
212
+ @spaces_cli.command(
213
+ "card",
214
+ examples=[
215
+ "hf spaces card mteb/leaderboard",
216
+ "hf spaces card mteb/leaderboard --metadata",
217
+ "hf spaces card mteb/leaderboard --metadata --format json",
218
+ "hf spaces card mteb/leaderboard --text",
219
+ ],
220
+ )
221
+ def spaces_card(
222
+ space_id: Annotated[str, Argument(help="The space ID (e.g. `username/repo-name`).")],
223
+ metadata: Annotated[bool, Option("--metadata", help="Output only the metadata from the card.")] = False,
224
+ text: Annotated[bool, Option("--text", help="Output only the text body (no metadata).")] = False,
225
+ token: TokenOpt = None,
226
+ ) -> None:
227
+ """Get the Space card (README) for a Space on the Hub."""
228
+ if metadata and text:
229
+ raise CLIError("--metadata and --text are mutually exclusive.")
230
+ card = SpaceCard.load(space_id, token=token)
231
+ if metadata:
232
+ out.dict(card.data.to_dict())
233
+ elif text:
234
+ out.text(card.text)
235
+ else:
236
+ out.text(card.content)
237
+ out.hint(f"Use `hf spaces card {space_id} --metadata` to extract only the card metadata.")
238
+
239
+
240
+ @spaces_cli.command(
241
+ "templates",
242
+ examples=["hf spaces templates"],
243
+ )
244
+ def spaces_templates(
245
+ token: TokenOpt = None,
246
+ ) -> None:
247
+ """List the available Space templates.
248
+
249
+ The `repo_id` (or `name`) of a template can be passed to `hf repos create --template ...` to
250
+ create a new Space from that template.
251
+ """
252
+ api = get_hf_api(token=token)
253
+ templates = [_dataclass_to_dict(template) for template in api.list_space_templates()]
254
+ out.table(templates, id_key="name")
255
+ out.hint(
256
+ "Create a Space from a template with `hf repos create <id> --type space --space-sdk <sdk> --template <repo_id>`."
257
+ )
258
+
259
+
260
+ @spaces_cli.command(
261
+ "search",
262
+ examples=[
263
+ 'hf spaces search "generate image"',
264
+ 'hf spaces search "identify objects in pictures" --sdk gradio --limit 5',
265
+ 'hf spaces search "remove background from photo" --description --json',
266
+ ],
267
+ )
268
+ def spaces_search(
269
+ query: Annotated[str, Argument(help="Search query.")],
270
+ filter: FilterOpt = None,
271
+ sdk: Annotated[list[str] | None, Option(help="Filter by SDK (e.g. gradio, docker, static).")] = None,
272
+ include_non_running: Annotated[bool, Option(help="Include non-running spaces in results.")] = False,
273
+ description: Annotated[bool, Option(help="Show AI-generated descriptions.")] = False,
274
+ limit: LimitOpt = 10,
275
+ token: TokenOpt = None,
276
+ ) -> None:
277
+ """Search spaces on the Hub using semantic search."""
278
+ api = get_hf_api(token=token)
279
+ results = api.search_spaces(
280
+ query=query,
281
+ filter=filter,
282
+ sdk=sdk,
283
+ include_non_running=include_non_running,
284
+ token=token,
285
+ )
286
+ items = []
287
+ for r in itertools.islice(results, limit):
288
+ item: dict = {
289
+ "id": r.id,
290
+ "title": r.title,
291
+ "sdk": r.sdk,
292
+ "likes": r.likes,
293
+ "stage": r.runtime.stage if r.runtime else None,
294
+ "category": r.ai_category,
295
+ "score": round(r.semantic_relevancy_score, 2) if r.semantic_relevancy_score is not None else None,
296
+ }
297
+ if description:
298
+ item["description"] = r.ai_short_description
299
+ items.append(item)
300
+ out.table(items)
301
+ if not description:
302
+ out.hint("Use --description to show AI-generated descriptions.")
303
+
304
+
305
+ @spaces_cli.command(
306
+ "wait",
307
+ examples=[
308
+ "hf spaces wait username/my-space",
309
+ "hf spaces wait username/my-space --timeout 5m",
310
+ ],
311
+ )
312
+ def spaces_wait(
313
+ space_id: Annotated[str, Argument(help="The space ID (e.g. `username/repo-name`).")],
314
+ timeout: Annotated[
315
+ str | None,
316
+ Option(
317
+ help="Max time to wait: int with s (seconds, default), m (minutes), h (hours) or d (days).",
318
+ ),
319
+ ] = None,
320
+ token: TokenOpt = None,
321
+ ) -> None:
322
+ """Wait for a Space to finish building/starting.
323
+
324
+ Blocks until the Space leaves an intermediate stage (BUILDING, APP_STARTING, etc.)
325
+ and reaches a settled stage. Exits with code 0 if the Space is RUNNING,
326
+ or a non-zero exit code otherwise (e.g. BUILD_ERROR, RUNTIME_ERROR).
327
+ """
328
+ timeout_secs = parse_duration(timeout) if timeout is not None else None
329
+ api = get_hf_api(token=token)
330
+ status = out.status("Waiting for Space to be ready...")
331
+ try:
332
+ runtime = api.wait_for_space(space_id, timeout=timeout_secs)
333
+ except TimeoutError:
334
+ status.done("Timed out.")
335
+ raise CLIError(f"Timed out after {timeout} waiting for Space '{space_id}' to be ready.") from None
336
+ status.done(f"Space reached stage '{runtime.stage}'.")
337
+ if runtime.stage != SpaceStage.RUNNING:
338
+ raise CLIError(f"Space '{space_id}' is not running (stage='{runtime.stage}').")
339
+ out.result("Space ready", space_id=space_id, stage=str(runtime.stage))
340
+ out.hint(f"Use `hf spaces logs {space_id}` to view run logs.")
341
+
342
+
343
+ @spaces_cli.command(
344
+ "dev-mode",
345
+ examples=[
346
+ "hf spaces dev-mode my-user-name/deepsite",
347
+ ],
348
+ )
349
+ def dev_mode(
350
+ space_id: Annotated[str, Argument(help="The space ID (e.g. `username/repo-name`).")],
351
+ stop: Annotated[bool, Option(help="Stop dev mode.")] = False,
352
+ token: TokenOpt = None,
353
+ ):
354
+ """
355
+ Enable or disable dev mode on a Space.
356
+
357
+ Spaces Dev Mode eases the debugging of your application and makes iterating on Spaces faster by allowing you to
358
+ restart your application without stopping the Space container itself. This feature is available as part of a PRO
359
+ or Team & Enterprise plan.
360
+
361
+ See docs: https://huggingface.co/docs/hub/spaces-dev-mode
362
+ """
363
+ api = get_hf_api(token=token)
364
+ if stop:
365
+ api.disable_space_dev_mode(space_id)
366
+ print(f"Dev mode disabled for '{space_id}'")
367
+ return
368
+ api.enable_space_dev_mode(space_id)
369
+ runtime = api.wait_for_space(space_id)
370
+ if runtime.stage != SpaceStage.RUNNING:
371
+ out.warning(f"Dev mode is not ready (stage='{runtime.stage}')")
372
+ return
373
+ info = api.space_info(space_id)
374
+ folder = getattr(info.card_data, "dev-mode-folder", "" if info.sdk == "docker" else "/home/user/app")
375
+ folder_query_param = f"folder={folder}" if folder else ""
376
+ print("Connect to dev environment:")
377
+ print("")
378
+ print("Web:")
379
+ vscode_web_url = f"https://huggingface.co/spaces/{info.id}/dev-mode/vscode-web"
380
+ if folder_query_param:
381
+ vscode_web_url += f"?{folder_query_param}"
382
+ ssh_host = f"{info.subdomain}@ssh.hf.space"
383
+ print(f" * VSCode: {vscode_web_url}")
384
+ print("")
385
+ print("Local:")
386
+ print("1. Add your SSH key to https://huggingface.co/settings/keys")
387
+ print(f"2. SSH with `hf spaces ssh {space_id}` (or `ssh -i <your_key> {ssh_host}`)")
388
+ print(" Or open")
389
+ print(f" * VSCode: vscode://vscode-remote/ssh-remote+{ssh_host}{folder}")
390
+ print(f" * Cursor: cursor://vscode-remote/ssh-remote+{ssh_host}{folder}")
391
+ print("")
392
+ print("PS: Dev mode stops after 48h of inactivity, don't forget to save your changes regularly.")
393
+
394
+
395
+ @spaces_cli.command(
396
+ "ssh",
397
+ examples=[
398
+ "hf spaces ssh username/my-space",
399
+ "hf spaces ssh username/my-space --dry-run",
400
+ "hf spaces ssh username/my-space -i ~/.ssh/id_ed25519",
401
+ "hf spaces ssh username/my-space --auto",
402
+ ],
403
+ )
404
+ def spaces_ssh(
405
+ space_id: Annotated[str, Argument(help="The space ID (e.g. `username/repo-name`).")],
406
+ identity_file: SshIdentityFileOpt = None,
407
+ dry_run: SshDryRunOpt = False,
408
+ auto: Annotated[
409
+ bool,
410
+ Option("--auto", help="Enable Dev Mode without prompting if not already enabled."),
411
+ ] = False,
412
+ token: TokenOpt = None,
413
+ ) -> None:
414
+ """SSH into a Space's Dev Mode container.
415
+
416
+ Requires Dev Mode to be running on the Space and your SSH public key to be registered at https://huggingface.co/settings/keys.
417
+
418
+ See: https://huggingface.co/docs/hub/spaces-dev-mode
419
+ """
420
+ api = get_hf_api(token=token)
421
+ info = api.space_info(space_id)
422
+ if info.runtime is None or not info.runtime.dev_mode:
423
+ out.confirm(
424
+ f"Dev Mode is disabled on '{space_id}'. Enable it now?", yes=auto, default=True, confirm_param="--auto"
425
+ )
426
+ api.enable_space_dev_mode(space_id)
427
+ runtime = api.wait_for_space(space_id)
428
+ if runtime.stage != SpaceStage.RUNNING:
429
+ raise CLIError(f"Space '{space_id}' is not running (stage='{runtime.stage}').")
430
+ info = api.space_info(space_id)
431
+ exec_ssh(f"{info.subdomain}@ssh.hf.space", identity_file=identity_file, dry_run=dry_run)
432
+
433
+
434
+ @spaces_cli.command(
435
+ "pause",
436
+ examples=[
437
+ "hf spaces pause username/my-space",
438
+ ],
439
+ )
440
+ def spaces_pause(
441
+ space_id: Annotated[str, Argument(help="The space ID (e.g. `username/repo-name`).")],
442
+ token: TokenOpt = None,
443
+ ) -> None:
444
+ """Pause a Space."""
445
+ api = get_hf_api(token=token)
446
+ runtime = api.pause_space(space_id)
447
+ out.result("Space paused", space_id=space_id, stage=runtime.stage)
448
+ out.hint(f"Use `hf spaces restart {space_id}` to restart it.")
449
+ out.hint(
450
+ f"Mount a Volume or bucket to persist data across restarts: `hf spaces volumes set {space_id} -v hf://...`"
451
+ )
452
+
453
+
454
+ @spaces_cli.command(
455
+ "restart",
456
+ examples=[
457
+ "hf spaces restart username/my-space",
458
+ "hf spaces restart username/my-space --factory-reboot",
459
+ ],
460
+ )
461
+ def spaces_restart(
462
+ space_id: Annotated[str, Argument(help="The space ID (e.g. `username/repo-name`).")],
463
+ factory_reboot: Annotated[
464
+ bool,
465
+ Option(
466
+ "--factory-reboot",
467
+ help="Rebuild the Space from scratch without using the build cache.",
468
+ ),
469
+ ] = False,
470
+ token: TokenOpt = None,
471
+ ) -> None:
472
+ """Restart a Space."""
473
+ api = get_hf_api(token=token)
474
+ runtime = api.restart_space(space_id, factory_reboot=factory_reboot)
475
+ out.result(
476
+ "Space restart triggered",
477
+ space_id=space_id,
478
+ stage=runtime.stage,
479
+ factory_reboot=factory_reboot,
480
+ )
481
+ out.hint(f"Use `hf spaces wait {space_id}` to wait until the Space is ready.")
482
+ out.hint(
483
+ f"Mount a Volume or bucket to persist data across restarts: `hf spaces volumes set {space_id} -v hf://...`"
484
+ )
485
+
486
+
487
+ @spaces_cli.command(
488
+ "hardware",
489
+ examples=[
490
+ "hf spaces hardware",
491
+ ],
492
+ )
493
+ def spaces_hardware(token: TokenOpt = None) -> None:
494
+ """List available hardware options for Spaces."""
495
+ api = get_hf_api(token=token)
496
+ hardware_list = api.list_spaces_hardware()
497
+ items = []
498
+ for hw in hardware_list:
499
+ accelerator = (
500
+ f"{hw.accelerator.quantity}x {hw.accelerator.model} ({hw.accelerator.vram})" if hw.accelerator else None
501
+ )
502
+ cost_min = f"${hw.unit_cost_usd:.4f}" if hw.unit_cost_usd else "free"
503
+ cost_hour = f"${hw.unit_cost_usd * 60:.2f}" if hw.unit_cost_usd else "free"
504
+ items.append(
505
+ {
506
+ "name": hw.name,
507
+ "pretty name": hw.pretty_name,
508
+ "cpu": hw.cpu,
509
+ "ram": hw.ram,
510
+ "accelerator": accelerator,
511
+ "cost/min": cost_min,
512
+ "cost/hour": cost_hour,
513
+ }
514
+ )
515
+ out.table(items)
516
+ out.hint("Use `hf spaces settings <space_id> --hardware <name>` to request hardware for a Space.")
517
+
518
+
519
+ @spaces_cli.command(
520
+ "settings",
521
+ examples=[
522
+ "hf spaces settings username/my-space --sleep-time 300",
523
+ "hf spaces settings username/my-space --hardware t4-medium",
524
+ ],
525
+ )
526
+ def spaces_settings(
527
+ space_id: Annotated[str, Argument(help="The space ID (e.g. `username/repo-name`).")],
528
+ sleep_time: Annotated[
529
+ int | None,
530
+ Option(
531
+ "--sleep-time",
532
+ help="Idle time in seconds after which the Space goes to sleep. Use -1 to never sleep. Only available on upgraded hardware.",
533
+ ),
534
+ ] = None,
535
+ hardware: Annotated[
536
+ str | None,
537
+ Option(
538
+ "--hardware",
539
+ help="Space hardware flavor (e.g. 'cpu-basic', 't4-medium', 'l4x4'). Run 'hf spaces hardware' to list available options.",
540
+ click_type=SoftChoice(SpaceHardware),
541
+ ),
542
+ ] = None,
543
+ token: TokenOpt = None,
544
+ ) -> None:
545
+ """Update the settings of a Space."""
546
+ api = get_hf_api(token=token)
547
+ if hardware is not None:
548
+ runtime = api.request_space_hardware(space_id, hardware=hardware, sleep_time=sleep_time) # type: ignore[arg-type]
549
+ elif sleep_time is not None:
550
+ runtime = api.set_space_sleep_time(space_id, sleep_time=sleep_time)
551
+ else:
552
+ raise CLIError("Specify at least one setting to update.")
553
+ out.result(
554
+ "Space settings updated",
555
+ space_id=space_id,
556
+ hardware=runtime.requested_hardware,
557
+ sleep_time=runtime.sleep_time,
558
+ )
559
+ out.hint(f"Use `hf spaces info {space_id}` to verify the runtime configuration.")
560
+
561
+
562
+ @spaces_cli.command(
563
+ "logs",
564
+ examples=[
565
+ "hf spaces logs username/my-space",
566
+ "hf spaces logs username/my-space --build",
567
+ "hf spaces logs -f username/my-space",
568
+ "hf spaces logs -n 50 username/my-space",
569
+ ],
570
+ )
571
+ def spaces_logs(
572
+ space_id: Annotated[str, Argument(help="The space ID (e.g. `username/repo-name`).")],
573
+ build: Annotated[
574
+ bool,
575
+ Option(
576
+ "--build",
577
+ help="Fetch the container build logs instead of the run logs. Useful when a Space is stuck in BUILD_ERROR.",
578
+ ),
579
+ ] = False,
580
+ follow: Annotated[
581
+ bool,
582
+ Option(
583
+ "-f",
584
+ "--follow",
585
+ help="Follow log output (stream until the server closes the stream). Without this flag, only currently available logs are printed.",
586
+ ),
587
+ ] = False,
588
+ tail: Annotated[
589
+ int | None,
590
+ Option(
591
+ "-n",
592
+ "--tail",
593
+ help="Number of lines to show from the end of the logs.",
594
+ ),
595
+ ] = None,
596
+ token: TokenOpt = None,
597
+ ) -> None:
598
+ """Fetch the run or build logs of a Space.
599
+
600
+ By default, prints currently available run logs and exits (non-blocking, like
601
+ `docker logs`). Use --follow/-f to stream until the server closes the stream.
602
+ Use --build to see the container build logs instead (useful when a Space is
603
+ stuck in BUILD_ERROR).
604
+ """
605
+ if follow and tail is not None:
606
+ raise CLIError(
607
+ "Cannot use --follow and --tail together. Use --follow to stream logs or --tail to show recent logs."
608
+ )
609
+
610
+ api = get_hf_api(token=token)
611
+ logs = api.fetch_space_logs(space_id, build=build, follow=follow)
612
+ if tail is not None:
613
+ logs = deque(logs, maxlen=tail)
614
+ found_logs = False
615
+ for line in logs:
616
+ clean_line = line.strip()
617
+ out.text(clean_line)
618
+ if clean_line:
619
+ found_logs = True
620
+ if not found_logs and not build:
621
+ out.hint(f"No run logs found for space {space_id}. Try passing --build to fetch build logs instead.")
622
+
623
+
624
+ @spaces_cli.command(
625
+ "hot-reload",
626
+ examples=[
627
+ "hf spaces hot-reload username/repo-name app.py # Open an interactive editor to the remote app.py file",
628
+ "hf spaces hot-reload username/repo-name -f app.py # Take local version from ./app.py and patch app.py remotely",
629
+ "hf spaces hot-reload username/repo-name app.py -f src/app.py # Take local version from ./src/app.py",
630
+ ],
631
+ )
632
+ def spaces_hot_reload(
633
+ space_id: Annotated[
634
+ str,
635
+ Argument(
636
+ help="The space ID (e.g. `username/repo-name`).",
637
+ ),
638
+ ],
639
+ filename: Annotated[
640
+ str | None,
641
+ Argument(
642
+ help="Path to the Python file in the Space repository. Can be omitted when --local-file is specified and path in repository matches."
643
+ ),
644
+ ] = None,
645
+ local_file: Annotated[
646
+ Path | None,
647
+ Option(
648
+ "--local-file",
649
+ "-f",
650
+ help="Path of local file. Interactive editor mode if not specified",
651
+ ),
652
+ ] = None,
653
+ skip_checks: Annotated[bool, Option(help="Skip hot-reload compatibility checks.")] = False,
654
+ skip_summary: Annotated[bool, Option(help="Skip summary display after hot-reload is triggered")] = False,
655
+ token: TokenOpt = None,
656
+ ) -> None:
657
+ """
658
+ Hot-reload any Python file of a Space without a full rebuild + restart.
659
+
660
+ ⚠ This feature is experimental ⚠
661
+
662
+ Only works with Gradio SDK (6.1+)
663
+ Opens an interactive editor unless --local-file/-f is specified.
664
+
665
+ This command patches the live Python process using https://github.com/breuleux/jurigged
666
+ (AST-based diffing, in-place function updates, etc.), integrated with Gradio's native hot-reload support
667
+ (meaning that Gradio demo object changes are reflected in the UI)
668
+
669
+ The command creates a remote commit.
670
+ If you are working from a local clone, run `git pull --autostash` afterwards
671
+ to bring the commit back and keep your local git state in sync.
672
+ """
673
+
674
+ click.secho("This feature is experimental and subject to change", fg="bright_black")
675
+
676
+ api = get_hf_api(token=token)
677
+
678
+ if not skip_checks:
679
+ space_info = api.space_info(space_id)
680
+ if space_info.sdk != "gradio":
681
+ raise CLIError(f"Hot-reloading is only available on Gradio SDK. Found {space_info.sdk} SDK")
682
+ if (card_data := space_info.card_data) is None:
683
+ raise CLIError(f"Unable to read cardData for Space {space_id}")
684
+ if (sdk_version := card_data.sdk_version) is None:
685
+ raise CLIError(f"Unable to read sdk_version from {space_id} cardData")
686
+ if version.parse(sdk_version) < version.Version(HOT_RELOADING_MIN_GRADIO):
687
+ raise CLIError(f"Hot-reloading requires Gradio >= {HOT_RELOADING_MIN_GRADIO} (found {sdk_version})")
688
+ if (current_sha := space_info.sha) is None:
689
+ raise CLIError(f"Unexpected `None` running SHA for Space {space_id}")
690
+ else:
691
+ current_sha = None
692
+
693
+ if local_file:
694
+ local_path = str(local_file)
695
+ filename = local_file.as_posix() if filename is None else filename
696
+ elif filename:
697
+ if not skip_checks:
698
+ try:
699
+ api.auth_check(
700
+ repo_type="space",
701
+ repo_id=space_id,
702
+ write=True,
703
+ )
704
+ except RepositoryNotFoundError as e:
705
+ raise CLIError(
706
+ f"Write access check to {space_id} repository failed. Make sure that you are authenticated"
707
+ ) from e
708
+ temp_dir = tempfile.TemporaryDirectory()
709
+ local_path = os.path.join(temp_dir.name, filename)
710
+ with disable_progress_bars():
711
+ try:
712
+ hf_hub_download(repo_type="space", repo_id=space_id, filename=filename, local_dir=temp_dir.name)
713
+ except RemoteEntryNotFoundError:
714
+ click.secho(f"{filename} not found in remote repository. Assuming new file", fg="bright_black")
715
+
716
+ editor_res = _editor_open(local_path)
717
+ if editor_res == "no-tty":
718
+ persistent_temp_dir = tempfile.mkdtemp()
719
+ shutil.copytree(temp_dir.name, persistent_temp_dir, dirs_exist_ok=True)
720
+ local_path = os.path.join(persistent_temp_dir, filename)
721
+ click.secho("No TTY detected. Non-interactive fallback:")
722
+ click.secho(f"- Edit {local_path}")
723
+ click.secho(f"- Run `hf spaces hot-reload {space_id} {filename} -f {local_path}`")
724
+ return
725
+ if editor_res == "no-editor":
726
+ raise CLIError("No editor found in local environment. Use -f flag to hot-reload from local path")
727
+ if editor_res != 0:
728
+ raise CLIError(f"Editor returned a non-zero exit code while attempting to edit {local_path}")
729
+ else:
730
+ raise CLIError("Either filename or --local-file/-f must be specified")
731
+
732
+ commit_info = api.upload_file(
733
+ repo_type="space",
734
+ repo_id=space_id,
735
+ path_or_fileobj=local_path,
736
+ path_in_repo=filename,
737
+ parent_commit=current_sha,
738
+ _hot_reload=True,
739
+ )
740
+
741
+ if local_file is not None and local_file.resolve().is_relative_to(Path.cwd()):
742
+ click.secho(f"Created commit {commit_info.oid} in remote Space repository.")
743
+ click.secho("Consider running `git pull --autostash` to stay synced if you are working from a local clone.")
744
+
745
+ if not skip_summary:
746
+ click.secho("Hot-reload summary:")
747
+ _spaces_hot_reload_summary(
748
+ api=api,
749
+ space_id=space_id,
750
+ current_sha=current_sha,
751
+ commit_sha=commit_info.oid,
752
+ local_path=local_path if local_file else filename,
753
+ filename=filename,
754
+ token=token,
755
+ )
756
+
757
+
758
+ def _spaces_hot_reload_summary(
759
+ api: HfApi,
760
+ space_id: str,
761
+ current_sha: str | None,
762
+ commit_sha: str,
763
+ filename: str,
764
+ local_path: str,
765
+ token: str | None,
766
+ ) -> None:
767
+ while (space_info := api.space_info(space_id)).sha == current_sha:
768
+ if current_sha is None or current_sha == commit_sha:
769
+ break
770
+ click.secho("Waiting for up-to-date Space infos", fg="bright_black", err=True)
771
+ time.sleep(2)
772
+ if space_info.sha != commit_sha:
773
+ raise CLIError(f"Expected SHA {commit_sha} after hot-reload but got {space_info.sha}")
774
+ if (runtime := space_info.runtime) is None:
775
+ raise CLIError(f"Unable to read SpaceRuntime from {space_id} infos")
776
+ if (hot_reloading := runtime.hot_reloading) is None:
777
+ raise CLIError(f"Space {space_id} current running version has not been hot-reloaded")
778
+ if hot_reloading.status != "created":
779
+ click.echo(f"Failed creating hot-reloaded commit. {hot_reloading.replica_statuses=}")
780
+ return
781
+
782
+ if (space_host := space_info.host) is None:
783
+ raise CLIError("Unexpected None host on hotReloaded Space")
784
+ if (space_subdomain := space_info.subdomain) is None:
785
+ raise CLIError("Unexpected None subdomain on hotReloaded Space")
786
+
787
+ def render_region(region: ReloadRegion) -> str:
788
+ res = f"{local_path}, "
789
+ if region["startLine"] == region["endLine"]:
790
+ res += f"line {region['startLine'] - 1}"
791
+ else:
792
+ res += f"lines {region['startLine'] - 1}-{region['endLine']}"
793
+ return res
794
+
795
+ def display_event(event: ApiGetReloadEventSourceData) -> None:
796
+ if event["data"]["kind"] == "error":
797
+ click.secho("✘ Unexpected hot-reloading error", bold=True)
798
+ click.secho(event["data"]["traceback"], italic=True)
799
+ elif event["data"]["kind"] == "exception":
800
+ click.secho(f"✘ Exception at {render_region(event['data']['region'])}", bold=True)
801
+ click.secho(event["data"]["traceback"], italic=True)
802
+ elif event["data"]["kind"] == "add":
803
+ click.secho(f"✔︎ Created {event['data']['objectName']} {event['data']['objectType']}", bold=True)
804
+ elif event["data"]["kind"] == "delete":
805
+ click.secho(f"∅ Deleted {event['data']['objectName']} {event['data']['objectType']}", bold=True)
806
+ elif event["data"]["kind"] == "update":
807
+ click.secho(f"✔︎ Updated {event['data']['objectName']} {event['data']['objectType']}", bold=True)
808
+ elif event["data"]["kind"] == "run":
809
+ click.secho(f"▶ Run {render_region(event['data']['region'])}", bold=True)
810
+ click.secho(event["data"]["codeLines"], italic=True)
811
+ elif event["data"]["kind"] == "ui":
812
+ if event["data"]["updated"]:
813
+ click.secho("⟳ UI updated", bold=True)
814
+ else:
815
+ click.secho("∅ UI untouched", bold=True)
816
+ elif event["data"]["kind"] == "file":
817
+ if event["data"]["created"]:
818
+ click.secho(f"✔︎ {filename} created", bold=True)
819
+ else:
820
+ click.secho(f"✔︎ {filename} updated", bold=True)
821
+ else:
822
+ click.secho(f"❓ Unknown update event: {event=}")
823
+ if TYPE_CHECKING:
824
+ assert_never(event["data"]["kind"])
825
+
826
+ for replica_stream_event in multi_replica_reload_events(
827
+ commit_sha=commit_sha,
828
+ host=space_host,
829
+ subdomain=space_subdomain,
830
+ replica_hashes=[hash for hash, _ in hot_reloading.replica_statuses],
831
+ token=token,
832
+ ):
833
+ if replica_stream_event["kind"] == "event":
834
+ display_event(replica_stream_event["event"])
835
+ elif replica_stream_event["kind"] == "replicaHash":
836
+ click.secho(f"---- Replica {replica_stream_event['hash']} ----")
837
+ elif replica_stream_event["kind"] == "fullMatch":
838
+ click.echo("✔︎ Same as first replica")
839
+ elif replica_stream_event["kind"] == "warning":
840
+ click.secho(f"⚠ {replica_stream_event['message']}", fg="bright_black")
841
+ else:
842
+ assert_never(replica_stream_event)
843
+
844
+
845
+ PREFERRED_EDITORS = (
846
+ ("code", "code --wait"),
847
+ ("nvim", "nvim"),
848
+ ("nano", "nano"),
849
+ ("vim", "vim"),
850
+ ("vi", "vi"),
851
+ )
852
+
853
+
854
+ @functools.cache
855
+ def _get_editor_command() -> str | None:
856
+ for env in ("HF_EDITOR", "VISUAL", "EDITOR"):
857
+ if command := os.getenv(env, "").strip():
858
+ return command
859
+ for binary_path, editor_command in PREFERRED_EDITORS:
860
+ if shutil.which(binary_path) is not None:
861
+ return editor_command
862
+ return None
863
+
864
+
865
+ def _editor_open(local_path: str) -> int | Literal["no-tty", "no-editor"]:
866
+ if not (sys.stdin.isatty() and sys.stdout.isatty()):
867
+ return "no-tty"
868
+ if (editor_command := _get_editor_command()) is None:
869
+ return "no-editor"
870
+ command = [*shlex.split(editor_command), local_path]
871
+ res = subprocess.run(command, start_new_session=True)
872
+ return res.returncode
873
+
874
+
875
+ @volumes_cli.command(
876
+ "list | ls",
877
+ examples=[
878
+ "hf spaces volumes ls username/my-space",
879
+ ],
880
+ )
881
+ def volumes_ls(
882
+ space_id: Annotated[str, Argument(help="The space ID (e.g. `username/repo-name`).")],
883
+ token: TokenOpt = None,
884
+ ) -> None:
885
+ """List volumes mounted in a Space."""
886
+ api = get_hf_api(token=token)
887
+ info = api.space_info(space_id)
888
+ if info.runtime is None:
889
+ raise CLIError(f"Runtime not available for Space '{space_id}'.")
890
+ volumes = info.runtime.volumes or []
891
+ items = [_dataclass_to_dict(v) for v in volumes]
892
+ out.table(items)
893
+ out.hint(
894
+ f"Use `hf spaces volumes set {space_id} -v hf://<repo_type>/<repo_id>:/<mount_path>` to set volumes for a Space."
895
+ )
896
+
897
+
898
+ @volumes_cli.command(
899
+ "set",
900
+ examples=[
901
+ "hf spaces volumes set username/my-space -v hf://models/username/my-model:/models",
902
+ "hf spaces volumes set username/my-space -v hf://buckets/username/my-bucket:/data -v hf://datasets/username/my-dataset:/datasets:ro",
903
+ ],
904
+ )
905
+ def volumes_set(
906
+ space_id: Annotated[str, Argument(help="The space ID (e.g. `username/repo-name`).")],
907
+ volume: VolumesOpt = None,
908
+ token: TokenOpt = None,
909
+ ) -> None:
910
+ """Set (replace) volumes for a Space."""
911
+ volumes = parse_volumes(volume)
912
+ if not volumes:
913
+ raise CLIError("At least one volume must be specified with -v/--volume.")
914
+ api = get_hf_api(token=token)
915
+ api.set_space_volumes(space_id, volumes=volumes)
916
+ out.result("Volumes set", space_id=space_id, volumes=[v.to_uri() for v in volumes])
917
+ out.hint(f"Use `hf spaces volumes ls {space_id}` to list volumes for a Space.")
918
+
919
+
920
+ @volumes_cli.command(
921
+ "delete",
922
+ examples=[
923
+ "hf spaces volumes delete username/my-space",
924
+ "hf spaces volumes delete username/my-space --yes",
925
+ ],
926
+ )
927
+ def volumes_delete(
928
+ space_id: Annotated[str, Argument(help="The space ID (e.g. `username/repo-name`).")],
929
+ yes: Annotated[
930
+ bool,
931
+ Option(
932
+ "-y",
933
+ "--yes",
934
+ help="Answer Yes to prompt automatically.",
935
+ ),
936
+ ] = False,
937
+ token: TokenOpt = None,
938
+ ) -> None:
939
+ """Remove all volumes from a Space."""
940
+ out.confirm(f"You are about to remove all volumes from Space '{space_id}'. Proceed?", yes=yes)
941
+ api = get_hf_api(token=token)
942
+ api.delete_space_volumes(space_id)
943
+ out.result("Volumes deleted", space_id=space_id)
944
+ out.hint(
945
+ f"Use `hf spaces volumes set {space_id} -v hf://<repo_type>/<repo_id>:/<mount_path>` to set volumes for a Space."
946
+ )
947
+
948
+
949
+ @secrets_cli.command(
950
+ "list | ls",
951
+ examples=["hf spaces secrets ls username/my-space"],
952
+ )
953
+ def secrets_ls(
954
+ space_id: Annotated[str, Argument(help="The space ID (e.g. `username/repo-name`).")],
955
+ token: TokenOpt = None,
956
+ ) -> None:
957
+ """List secrets for a Space. Secret values are write-only and not returned."""
958
+ api = get_hf_api(token=token)
959
+ secrets = api.get_space_secrets(space_id)
960
+ items = [_dataclass_to_dict(s) for s in secrets.values()]
961
+ out.table(items)
962
+ out.hint(f"Use `hf spaces secrets add {space_id} -s KEY=VALUE` to add secrets to a Space.")
963
+
964
+
965
+ @secrets_cli.command(
966
+ "add",
967
+ examples=[
968
+ "hf spaces secrets add username/my-space -s HF_TOKEN",
969
+ "hf spaces secrets add username/my-space -s OPENAI_API_KEY=sk-... -s ANTHROPIC_API_KEY=sk-...",
970
+ "hf spaces secrets add username/my-space --secrets-file .env.secrets",
971
+ ],
972
+ )
973
+ def secrets_add(
974
+ space_id: Annotated[str, Argument(help="The space ID (e.g. `username/repo-name`).")],
975
+ secrets: SecretsOpt = None,
976
+ secrets_file: SecretsFileOpt = None,
977
+ token: TokenOpt = None,
978
+ ) -> None:
979
+ """Add or update secrets for a Space."""
980
+ secrets_map = parse_env_map(secrets, secrets_file)
981
+ if not secrets_map:
982
+ raise CLIError("At least one secret must be specified with -s/--secrets or --secrets-file.")
983
+ api = get_hf_api(token=token)
984
+ for key, value in secrets_map.items():
985
+ api.add_space_secret(space_id, key=key, value=value or "")
986
+ out.result("Secrets added", space_id=space_id, keys=list(secrets_map))
987
+ out.hint(f"Use `hf spaces secrets delete {space_id} <key>` to remove a secret from a Space.")
988
+
989
+
990
+ @secrets_cli.command(
991
+ "delete",
992
+ examples=[
993
+ "hf spaces secrets delete username/my-space HF_TOKEN",
994
+ "hf spaces secrets delete username/my-space HF_TOKEN --yes",
995
+ ],
996
+ )
997
+ def secrets_delete(
998
+ space_id: Annotated[str, Argument(help="The space ID (e.g. `username/repo-name`).")],
999
+ key: Annotated[str, Argument(help="Name of the secret to remove.")],
1000
+ yes: Annotated[
1001
+ bool,
1002
+ Option(
1003
+ "-y",
1004
+ "--yes",
1005
+ help="Answer Yes to prompt automatically.",
1006
+ ),
1007
+ ] = False,
1008
+ token: TokenOpt = None,
1009
+ ) -> None:
1010
+ """Remove a secret from a Space."""
1011
+ out.confirm(
1012
+ f"You are about to remove secret '{key}' from Space '{space_id}'. The value cannot be recovered. Proceed?",
1013
+ yes=yes,
1014
+ )
1015
+ api = get_hf_api(token=token)
1016
+ api.delete_space_secret(space_id, key=key)
1017
+ out.result("Secret deleted", space_id=space_id, key=key)
1018
+ out.hint(f"Use `hf spaces secrets add {space_id} -s {key}=<value>` to re-add a secret to a Space.")
1019
+
1020
+
1021
+ @variables_cli.command(
1022
+ "list | ls",
1023
+ examples=["hf spaces variables ls username/my-space"],
1024
+ )
1025
+ def variables_ls(
1026
+ space_id: Annotated[str, Argument(help="The space ID (e.g. `username/repo-name`).")],
1027
+ token: TokenOpt = None,
1028
+ ) -> None:
1029
+ """List environment variables for a Space."""
1030
+ api = get_hf_api(token=token)
1031
+ variables = api.get_space_variables(space_id)
1032
+ items = [_dataclass_to_dict(v) for v in variables.values()]
1033
+ out.table(items)
1034
+ out.hint(f"Use `hf spaces variables add {space_id} -e KEY=VALUE` to add variables to a Space.")
1035
+
1036
+
1037
+ @variables_cli.command(
1038
+ "add",
1039
+ examples=[
1040
+ "hf spaces variables add username/my-space -e DEBUG=1",
1041
+ "hf spaces variables add username/my-space -e MODEL_ID=gpt2 -e MAX_TOKENS=512",
1042
+ "hf spaces variables add username/my-space --env-file .env",
1043
+ ],
1044
+ )
1045
+ def variables_add(
1046
+ space_id: Annotated[str, Argument(help="The space ID (e.g. `username/repo-name`).")],
1047
+ env: EnvOpt = None,
1048
+ env_file: EnvFileOpt = None,
1049
+ token: TokenOpt = None,
1050
+ ) -> None:
1051
+ """Add or update environment variables for a Space."""
1052
+ env_map = parse_env_map(env, env_file)
1053
+ if not env_map:
1054
+ raise CLIError("At least one variable must be specified with -e/--env or --env-file.")
1055
+ api = get_hf_api(token=token)
1056
+ for key, value in env_map.items():
1057
+ api.add_space_variable(space_id, key=key, value=value or "")
1058
+ out.result("Variables added", space_id=space_id, keys=list(env_map))
1059
+ out.hint(f"Use `hf spaces variables ls {space_id}` to list variables for a Space.")
1060
+
1061
+
1062
+ @variables_cli.command(
1063
+ "delete",
1064
+ examples=[
1065
+ "hf spaces variables delete username/my-space DEBUG",
1066
+ "hf spaces variables delete username/my-space DEBUG --yes",
1067
+ ],
1068
+ )
1069
+ def variables_delete(
1070
+ space_id: Annotated[str, Argument(help="The space ID (e.g. `username/repo-name`).")],
1071
+ key: Annotated[str, Argument(help="Name of the variable to remove.")],
1072
+ yes: Annotated[
1073
+ bool,
1074
+ Option(
1075
+ "-y",
1076
+ "--yes",
1077
+ help="Answer Yes to prompt automatically.",
1078
+ ),
1079
+ ] = False,
1080
+ token: TokenOpt = None,
1081
+ ) -> None:
1082
+ """Remove an environment variable from a Space."""
1083
+ out.confirm(
1084
+ f"You are about to remove variable '{key}' from Space '{space_id}'. Proceed?",
1085
+ yes=yes,
1086
+ )
1087
+ api = get_hf_api(token=token)
1088
+ api.delete_space_variable(space_id, key=key)
1089
+ out.result("Variable deleted", space_id=space_id, key=key)
1090
+ out.hint(f"Use `hf spaces variables ls {space_id}` to list remaining variables for a Space.")
.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/inference/_generated/__init__.py ADDED
File without changes
.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/inference/_generated/_async_client.py ADDED
The diff for this file is too large to render. See raw diff
 
.cache/uv/archive-v0/YbGpm6nADP0vFoZFy8BvB/huggingface_hub/inference/_generated/types/audio_classification.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Inference code generated from the JSON schema spec in @huggingface/tasks.
2
+ #
3
+ # See:
4
+ # - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts
5
+ # - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.
6
+ from typing import Literal, Optional
7
+
8
+ from .base import BaseInferenceType, dataclass_with_extra
9
+
10
+
11
+ AudioClassificationOutputTransform = Literal["sigmoid", "softmax", "none"]
12
+
13
+
14
+ @dataclass_with_extra
15
+ class AudioClassificationParameters(BaseInferenceType):
16
+ """Additional inference parameters for Audio Classification"""
17
+
18
+ function_to_apply: Optional["AudioClassificationOutputTransform"] = None
19
+ """The function to apply to the model outputs in order to retrieve the scores."""
20
+ top_k: int | None = None
21
+ """When specified, limits the output to the top K most probable classes."""
22
+
23
+
24
+ @dataclass_with_extra
25
+ class AudioClassificationInput(BaseInferenceType):
26
+ """Inputs for Audio Classification inference"""
27
+
28
+ inputs: str
29
+ """The input audio data as a base64-encoded string. If no `parameters` are provided, you can
30
+ also provide the audio data as a raw bytes payload.
31
+ """
32
+ parameters: AudioClassificationParameters | None = None
33
+ """Additional inference parameters for Audio Classification"""
34
+
35
+
36
+ @dataclass_with_extra
37
+ class AudioClassificationOutputElement(BaseInferenceType):
38
+ """Outputs for Audio Classification inference"""
39
+
40
+ label: str
41
+ """The predicted class label."""
42
+ score: float
43
+ """The corresponding probability."""