applied-ai-018 commited on
Commit
3afca5f
·
verified ·
1 Parent(s): e1bbc88

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. ckpts/universal/global_step20/zero/18.attention.dense.weight/exp_avg_sq.pt +3 -0
  2. ckpts/universal/global_step20/zero/20.mlp.dense_h_to_4h_swiglu.weight/exp_avg.pt +3 -0
  3. ckpts/universal/global_step20/zero/20.mlp.dense_h_to_4h_swiglu.weight/fp32.pt +3 -0
  4. ckpts/universal/global_step20/zero/3.mlp.dense_4h_to_h.weight/exp_avg_sq.pt +3 -0
  5. ckpts/universal/global_step20/zero/9.mlp.dense_4h_to_h.weight/exp_avg.pt +3 -0
  6. ckpts/universal/global_step20/zero/9.mlp.dense_4h_to_h.weight/exp_avg_sq.pt +3 -0
  7. venv/lib/python3.10/site-packages/click-8.1.7.dist-info/INSTALLER +1 -0
  8. venv/lib/python3.10/site-packages/click-8.1.7.dist-info/LICENSE.rst +28 -0
  9. venv/lib/python3.10/site-packages/click-8.1.7.dist-info/METADATA +103 -0
  10. venv/lib/python3.10/site-packages/click-8.1.7.dist-info/RECORD +39 -0
  11. venv/lib/python3.10/site-packages/click-8.1.7.dist-info/WHEEL +5 -0
  12. venv/lib/python3.10/site-packages/click-8.1.7.dist-info/top_level.txt +1 -0
  13. venv/lib/python3.10/site-packages/datasets/utils/__pycache__/__init__.cpython-310.pyc +0 -0
  14. venv/lib/python3.10/site-packages/datasets/utils/__pycache__/_dataset_viewer.cpython-310.pyc +0 -0
  15. venv/lib/python3.10/site-packages/datasets/utils/__pycache__/_dill.cpython-310.pyc +0 -0
  16. venv/lib/python3.10/site-packages/datasets/utils/__pycache__/_filelock.cpython-310.pyc +0 -0
  17. venv/lib/python3.10/site-packages/datasets/utils/__pycache__/beam_utils.cpython-310.pyc +0 -0
  18. venv/lib/python3.10/site-packages/datasets/utils/__pycache__/cache.cpython-310.pyc +0 -0
  19. venv/lib/python3.10/site-packages/datasets/utils/__pycache__/deprecation_utils.cpython-310.pyc +0 -0
  20. venv/lib/python3.10/site-packages/datasets/utils/__pycache__/doc_utils.cpython-310.pyc +0 -0
  21. venv/lib/python3.10/site-packages/datasets/utils/__pycache__/download_manager.cpython-310.pyc +0 -0
  22. venv/lib/python3.10/site-packages/datasets/utils/__pycache__/experimental.cpython-310.pyc +0 -0
  23. venv/lib/python3.10/site-packages/datasets/utils/__pycache__/extract.cpython-310.pyc +0 -0
  24. venv/lib/python3.10/site-packages/datasets/utils/__pycache__/file_utils.cpython-310.pyc +0 -0
  25. venv/lib/python3.10/site-packages/datasets/utils/__pycache__/filelock.cpython-310.pyc +0 -0
  26. venv/lib/python3.10/site-packages/datasets/utils/__pycache__/hub.cpython-310.pyc +0 -0
  27. venv/lib/python3.10/site-packages/datasets/utils/__pycache__/info_utils.cpython-310.pyc +0 -0
  28. venv/lib/python3.10/site-packages/datasets/utils/__pycache__/logging.cpython-310.pyc +0 -0
  29. venv/lib/python3.10/site-packages/datasets/utils/__pycache__/metadata.cpython-310.pyc +0 -0
  30. venv/lib/python3.10/site-packages/datasets/utils/__pycache__/patching.cpython-310.pyc +0 -0
  31. venv/lib/python3.10/site-packages/datasets/utils/__pycache__/py_utils.cpython-310.pyc +0 -0
  32. venv/lib/python3.10/site-packages/datasets/utils/__pycache__/readme.cpython-310.pyc +0 -0
  33. venv/lib/python3.10/site-packages/datasets/utils/__pycache__/sharding.cpython-310.pyc +0 -0
  34. venv/lib/python3.10/site-packages/datasets/utils/__pycache__/stratify.cpython-310.pyc +0 -0
  35. venv/lib/python3.10/site-packages/datasets/utils/__pycache__/tf_utils.cpython-310.pyc +0 -0
  36. venv/lib/python3.10/site-packages/datasets/utils/__pycache__/tqdm.cpython-310.pyc +0 -0
  37. venv/lib/python3.10/site-packages/datasets/utils/__pycache__/track.cpython-310.pyc +0 -0
  38. venv/lib/python3.10/site-packages/datasets/utils/__pycache__/typing.cpython-310.pyc +0 -0
  39. venv/lib/python3.10/site-packages/datasets/utils/__pycache__/version.cpython-310.pyc +0 -0
  40. venv/lib/python3.10/site-packages/datasets/utils/download_manager.py +1 -0
  41. venv/lib/python3.10/site-packages/datasets/utils/experimental.py +43 -0
  42. venv/lib/python3.10/site-packages/datasets/utils/extract.py +351 -0
  43. venv/lib/python3.10/site-packages/datasets/utils/file_utils.py +1674 -0
  44. venv/lib/python3.10/site-packages/datasets/utils/filelock.py +11 -0
  45. venv/lib/python3.10/site-packages/datasets/utils/hub.py +6 -0
  46. venv/lib/python3.10/site-packages/datasets/utils/info_utils.py +130 -0
  47. venv/lib/python3.10/site-packages/datasets/utils/metadata.py +320 -0
  48. venv/lib/python3.10/site-packages/datasets/utils/patching.py +119 -0
  49. venv/lib/python3.10/site-packages/datasets/utils/resources/__init__.py +0 -0
  50. venv/lib/python3.10/site-packages/datasets/utils/resources/__pycache__/__init__.cpython-310.pyc +0 -0
ckpts/universal/global_step20/zero/18.attention.dense.weight/exp_avg_sq.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9fdc582c1cb9cdd72e5a91b4d910340e048deee955cb62074345715273eef119
3
+ size 16778411
ckpts/universal/global_step20/zero/20.mlp.dense_h_to_4h_swiglu.weight/exp_avg.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dfdf0f0ea6c83a1bfc89fc3de2c403c56d3e3054562df5ec6dd03f77b8b0e823
3
+ size 33555612
ckpts/universal/global_step20/zero/20.mlp.dense_h_to_4h_swiglu.weight/fp32.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a32cac0a4414e7c6f10517f9c05f6e37665795c189d181f22829f61cbf115993
3
+ size 33555533
ckpts/universal/global_step20/zero/3.mlp.dense_4h_to_h.weight/exp_avg_sq.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:62f15184d7b2ab08fe2ec05f2d4a2d255d7d6fa821fe01c4067db991a168a941
3
+ size 33555627
ckpts/universal/global_step20/zero/9.mlp.dense_4h_to_h.weight/exp_avg.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ac484b01bfb3c4b14f57069150320cdbf300b46013be2b5b9eb21c8787857ed0
3
+ size 33555612
ckpts/universal/global_step20/zero/9.mlp.dense_4h_to_h.weight/exp_avg_sq.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:69ef46fd18ac766f9492995dc088dd49cbab9e2f6aa8e70ae03d2a8ece3d3d13
3
+ size 33555627
venv/lib/python3.10/site-packages/click-8.1.7.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
venv/lib/python3.10/site-packages/click-8.1.7.dist-info/LICENSE.rst ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright 2014 Pallets
2
+
3
+ Redistribution and use in source and binary forms, with or without
4
+ modification, are permitted provided that the following conditions are
5
+ met:
6
+
7
+ 1. Redistributions of source code must retain the above copyright
8
+ notice, this list of conditions and the following disclaimer.
9
+
10
+ 2. Redistributions in binary form must reproduce the above copyright
11
+ notice, this list of conditions and the following disclaimer in the
12
+ documentation and/or other materials provided with the distribution.
13
+
14
+ 3. Neither the name of the copyright holder nor the names of its
15
+ contributors may be used to endorse or promote products derived from
16
+ this software without specific prior written permission.
17
+
18
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
21
+ PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22
+ HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
24
+ TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
25
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
26
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
27
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
venv/lib/python3.10/site-packages/click-8.1.7.dist-info/METADATA ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: click
3
+ Version: 8.1.7
4
+ Summary: Composable command line interface toolkit
5
+ Home-page: https://palletsprojects.com/p/click/
6
+ Maintainer: Pallets
7
+ Maintainer-email: [email protected]
8
+ License: BSD-3-Clause
9
+ Project-URL: Donate, https://palletsprojects.com/donate
10
+ Project-URL: Documentation, https://click.palletsprojects.com/
11
+ Project-URL: Changes, https://click.palletsprojects.com/changes/
12
+ Project-URL: Source Code, https://github.com/pallets/click/
13
+ Project-URL: Issue Tracker, https://github.com/pallets/click/issues/
14
+ Project-URL: Chat, https://discord.gg/pallets
15
+ Classifier: Development Status :: 5 - Production/Stable
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: License :: OSI Approved :: BSD License
18
+ Classifier: Operating System :: OS Independent
19
+ Classifier: Programming Language :: Python
20
+ Requires-Python: >=3.7
21
+ Description-Content-Type: text/x-rst
22
+ License-File: LICENSE.rst
23
+ Requires-Dist: colorama ; platform_system == "Windows"
24
+ Requires-Dist: importlib-metadata ; python_version < "3.8"
25
+
26
+ \$ click\_
27
+ ==========
28
+
29
+ Click is a Python package for creating beautiful command line interfaces
30
+ in a composable way with as little code as necessary. It's the "Command
31
+ Line Interface Creation Kit". It's highly configurable but comes with
32
+ sensible defaults out of the box.
33
+
34
+ It aims to make the process of writing command line tools quick and fun
35
+ while also preventing any frustration caused by the inability to
36
+ implement an intended CLI API.
37
+
38
+ Click in three points:
39
+
40
+ - Arbitrary nesting of commands
41
+ - Automatic help page generation
42
+ - Supports lazy loading of subcommands at runtime
43
+
44
+
45
+ Installing
46
+ ----------
47
+
48
+ Install and update using `pip`_:
49
+
50
+ .. code-block:: text
51
+
52
+ $ pip install -U click
53
+
54
+ .. _pip: https://pip.pypa.io/en/stable/getting-started/
55
+
56
+
57
+ A Simple Example
58
+ ----------------
59
+
60
+ .. code-block:: python
61
+
62
+ import click
63
+
64
+ @click.command()
65
+ @click.option("--count", default=1, help="Number of greetings.")
66
+ @click.option("--name", prompt="Your name", help="The person to greet.")
67
+ def hello(count, name):
68
+ """Simple program that greets NAME for a total of COUNT times."""
69
+ for _ in range(count):
70
+ click.echo(f"Hello, {name}!")
71
+
72
+ if __name__ == '__main__':
73
+ hello()
74
+
75
+ .. code-block:: text
76
+
77
+ $ python hello.py --count=3
78
+ Your name: Click
79
+ Hello, Click!
80
+ Hello, Click!
81
+ Hello, Click!
82
+
83
+
84
+ Donate
85
+ ------
86
+
87
+ The Pallets organization develops and supports Click and other popular
88
+ packages. In order to grow the community of contributors and users, and
89
+ allow the maintainers to devote more time to the projects, `please
90
+ donate today`_.
91
+
92
+ .. _please donate today: https://palletsprojects.com/donate
93
+
94
+
95
+ Links
96
+ -----
97
+
98
+ - Documentation: https://click.palletsprojects.com/
99
+ - Changes: https://click.palletsprojects.com/changes/
100
+ - PyPI Releases: https://pypi.org/project/click/
101
+ - Source Code: https://github.com/pallets/click
102
+ - Issue Tracker: https://github.com/pallets/click/issues
103
+ - Chat: https://discord.gg/pallets
venv/lib/python3.10/site-packages/click-8.1.7.dist-info/RECORD ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ click-8.1.7.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ click-8.1.7.dist-info/LICENSE.rst,sha256=morRBqOU6FO_4h9C9OctWSgZoigF2ZG18ydQKSkrZY0,1475
3
+ click-8.1.7.dist-info/METADATA,sha256=qIMevCxGA9yEmJOM_4WHuUJCwWpsIEVbCPOhs45YPN4,3014
4
+ click-8.1.7.dist-info/RECORD,,
5
+ click-8.1.7.dist-info/WHEEL,sha256=5sUXSg9e4bi7lTLOHcm6QEYwO5TIF1TNbTSVFVjcJcc,92
6
+ click-8.1.7.dist-info/top_level.txt,sha256=J1ZQogalYS4pphY_lPECoNMfw0HzTSrZglC4Yfwo4xA,6
7
+ click/__init__.py,sha256=YDDbjm406dTOA0V8bTtdGnhN7zj5j-_dFRewZF_pLvw,3138
8
+ click/__pycache__/__init__.cpython-310.pyc,,
9
+ click/__pycache__/_compat.cpython-310.pyc,,
10
+ click/__pycache__/_termui_impl.cpython-310.pyc,,
11
+ click/__pycache__/_textwrap.cpython-310.pyc,,
12
+ click/__pycache__/_winconsole.cpython-310.pyc,,
13
+ click/__pycache__/core.cpython-310.pyc,,
14
+ click/__pycache__/decorators.cpython-310.pyc,,
15
+ click/__pycache__/exceptions.cpython-310.pyc,,
16
+ click/__pycache__/formatting.cpython-310.pyc,,
17
+ click/__pycache__/globals.cpython-310.pyc,,
18
+ click/__pycache__/parser.cpython-310.pyc,,
19
+ click/__pycache__/shell_completion.cpython-310.pyc,,
20
+ click/__pycache__/termui.cpython-310.pyc,,
21
+ click/__pycache__/testing.cpython-310.pyc,,
22
+ click/__pycache__/types.cpython-310.pyc,,
23
+ click/__pycache__/utils.cpython-310.pyc,,
24
+ click/_compat.py,sha256=5318agQpbt4kroKsbqDOYpTSWzL_YCZVUQiTT04yXmc,18744
25
+ click/_termui_impl.py,sha256=3dFYv4445Nw-rFvZOTBMBPYwB1bxnmNk9Du6Dm_oBSU,24069
26
+ click/_textwrap.py,sha256=10fQ64OcBUMuK7mFvh8363_uoOxPlRItZBmKzRJDgoY,1353
27
+ click/_winconsole.py,sha256=5ju3jQkcZD0W27WEMGqmEP4y_crUVzPCqsX_FYb7BO0,7860
28
+ click/core.py,sha256=j6oEWtGgGna8JarD6WxhXmNnxLnfRjwXglbBc-8jr7U,114086
29
+ click/decorators.py,sha256=-ZlbGYgV-oI8jr_oH4RpuL1PFS-5QmeuEAsLDAYgxtw,18719
30
+ click/exceptions.py,sha256=fyROO-47HWFDjt2qupo7A3J32VlpM-ovJnfowu92K3s,9273
31
+ click/formatting.py,sha256=Frf0-5W33-loyY_i9qrwXR8-STnW3m5gvyxLVUdyxyk,9706
32
+ click/globals.py,sha256=TP-qM88STzc7f127h35TD_v920FgfOD2EwzqA0oE8XU,1961
33
+ click/parser.py,sha256=LKyYQE9ZLj5KgIDXkrcTHQRXIggfoivX14_UVIn56YA,19067
34
+ click/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
35
+ click/shell_completion.py,sha256=Ty3VM_ts0sQhj6u7eFTiLwHPoTgcXTGEAUg2OpLqYKw,18460
36
+ click/termui.py,sha256=H7Q8FpmPelhJ2ovOhfCRhjMtCpNyjFXryAMLZODqsdc,28324
37
+ click/testing.py,sha256=1Qd4kS5bucn1hsNIRryd0WtTMuCpkA93grkWxT8POsU,16084
38
+ click/types.py,sha256=TZvz3hKvBztf-Hpa2enOmP4eznSPLzijjig5b_0XMxE,36391
39
+ click/utils.py,sha256=1476UduUNY6UePGU4m18uzVHLt1sKM2PP3yWsQhbItM,20298
venv/lib/python3.10/site-packages/click-8.1.7.dist-info/WHEEL ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.41.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
venv/lib/python3.10/site-packages/click-8.1.7.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ click
venv/lib/python3.10/site-packages/datasets/utils/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (580 Bytes). View file
 
venv/lib/python3.10/site-packages/datasets/utils/__pycache__/_dataset_viewer.cpython-310.pyc ADDED
Binary file (3.21 kB). View file
 
venv/lib/python3.10/site-packages/datasets/utils/__pycache__/_dill.cpython-310.pyc ADDED
Binary file (8.44 kB). View file
 
venv/lib/python3.10/site-packages/datasets/utils/__pycache__/_filelock.cpython-310.pyc ADDED
Binary file (1.69 kB). View file
 
venv/lib/python3.10/site-packages/datasets/utils/__pycache__/beam_utils.cpython-310.pyc ADDED
Binary file (2.11 kB). View file
 
venv/lib/python3.10/site-packages/datasets/utils/__pycache__/cache.cpython-310.pyc ADDED
Binary file (6.44 kB). View file
 
venv/lib/python3.10/site-packages/datasets/utils/__pycache__/deprecation_utils.cpython-310.pyc ADDED
Binary file (3.62 kB). View file
 
venv/lib/python3.10/site-packages/datasets/utils/__pycache__/doc_utils.cpython-310.pyc ADDED
Binary file (692 Bytes). View file
 
venv/lib/python3.10/site-packages/datasets/utils/__pycache__/download_manager.cpython-310.pyc ADDED
Binary file (190 Bytes). View file
 
venv/lib/python3.10/site-packages/datasets/utils/__pycache__/experimental.cpython-310.pyc ADDED
Binary file (1.43 kB). View file
 
venv/lib/python3.10/site-packages/datasets/utils/__pycache__/extract.cpython-310.pyc ADDED
Binary file (13.7 kB). View file
 
venv/lib/python3.10/site-packages/datasets/utils/__pycache__/file_utils.cpython-310.pyc ADDED
Binary file (51.2 kB). View file
 
venv/lib/python3.10/site-packages/datasets/utils/__pycache__/filelock.cpython-310.pyc ADDED
Binary file (364 Bytes). View file
 
venv/lib/python3.10/site-packages/datasets/utils/__pycache__/hub.cpython-310.pyc ADDED
Binary file (320 Bytes). View file
 
venv/lib/python3.10/site-packages/datasets/utils/__pycache__/info_utils.cpython-310.pyc ADDED
Binary file (5.72 kB). View file
 
venv/lib/python3.10/site-packages/datasets/utils/__pycache__/logging.cpython-310.pyc ADDED
Binary file (5.14 kB). View file
 
venv/lib/python3.10/site-packages/datasets/utils/__pycache__/metadata.cpython-310.pyc ADDED
Binary file (12.3 kB). View file
 
venv/lib/python3.10/site-packages/datasets/utils/__pycache__/patching.cpython-310.pyc ADDED
Binary file (3.49 kB). View file
 
venv/lib/python3.10/site-packages/datasets/utils/__pycache__/py_utils.cpython-310.pyc ADDED
Binary file (24 kB). View file
 
venv/lib/python3.10/site-packages/datasets/utils/__pycache__/readme.cpython-310.pyc ADDED
Binary file (8.96 kB). View file
 
venv/lib/python3.10/site-packages/datasets/utils/__pycache__/sharding.cpython-310.pyc ADDED
Binary file (4.53 kB). View file
 
venv/lib/python3.10/site-packages/datasets/utils/__pycache__/stratify.cpython-310.pyc ADDED
Binary file (3.17 kB). View file
 
venv/lib/python3.10/site-packages/datasets/utils/__pycache__/tf_utils.cpython-310.pyc ADDED
Binary file (17.7 kB). View file
 
venv/lib/python3.10/site-packages/datasets/utils/__pycache__/tqdm.cpython-310.pyc ADDED
Binary file (4.03 kB). View file
 
venv/lib/python3.10/site-packages/datasets/utils/__pycache__/track.cpython-310.pyc ADDED
Binary file (2.36 kB). View file
 
venv/lib/python3.10/site-packages/datasets/utils/__pycache__/typing.cpython-310.pyc ADDED
Binary file (442 Bytes). View file
 
venv/lib/python3.10/site-packages/datasets/utils/__pycache__/version.cpython-310.pyc ADDED
Binary file (4.03 kB). View file
 
venv/lib/python3.10/site-packages/datasets/utils/download_manager.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # deprecated, please use datasets.download.download_manager
venv/lib/python3.10/site-packages/datasets/utils/experimental.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Contains utilities to flag a feature as "experimental" in datasets."""
2
+
3
+ import warnings
4
+ from functools import wraps
5
+ from typing import Callable
6
+
7
+
8
+ def experimental(fn: Callable) -> Callable:
9
+ """Decorator to flag a feature as experimental.
10
+
11
+ An experimental feature trigger a warning when used as it might be subject to breaking changes in the future.
12
+
13
+ Args:
14
+ fn (`Callable`):
15
+ The function to flag as experimental.
16
+
17
+ Returns:
18
+ `Callable`: The decorated function.
19
+
20
+ Example:
21
+
22
+ ```python
23
+ >>> from datasets.utils import experimental
24
+
25
+ >>> @experimental
26
+ ... def my_function():
27
+ ... print("Hello world!")
28
+
29
+ >>> my_function()
30
+ UserWarning: 'my_function' is experimental and might be subject to breaking changes in the future.
31
+ Hello world!
32
+ ```
33
+ """
34
+
35
+ @wraps(fn)
36
+ def _inner_fn(*args, **kwargs):
37
+ warnings.warn(
38
+ (f"'{fn.__name__}' is experimental and might be subject to breaking changes in the future."),
39
+ UserWarning,
40
+ )
41
+ return fn(*args, **kwargs)
42
+
43
+ return _inner_fn
venv/lib/python3.10/site-packages/datasets/utils/extract.py ADDED
@@ -0,0 +1,351 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import bz2
2
+ import gzip
3
+ import lzma
4
+ import os
5
+ import shutil
6
+ import struct
7
+ import tarfile
8
+ import warnings
9
+ import zipfile
10
+ from abc import ABC, abstractmethod
11
+ from pathlib import Path
12
+ from typing import Dict, List, Optional, Type, Union
13
+
14
+ from .. import config
15
+ from ._filelock import FileLock
16
+ from .logging import get_logger
17
+
18
+
19
+ logger = get_logger(__name__)
20
+
21
+
22
+ class ExtractManager:
23
+ def __init__(self, cache_dir: Optional[str] = None):
24
+ self.extract_dir = (
25
+ os.path.join(cache_dir, config.EXTRACTED_DATASETS_DIR) if cache_dir else config.EXTRACTED_DATASETS_PATH
26
+ )
27
+ self.extractor = Extractor
28
+
29
+ def _get_output_path(self, path: str) -> str:
30
+ from .file_utils import hash_url_to_filename
31
+
32
+ # Path where we extract compressed archives
33
+ # We extract in the cache dir, and get the extracted path name by hashing the original path"
34
+ abs_path = os.path.abspath(path)
35
+ return os.path.join(self.extract_dir, hash_url_to_filename(abs_path))
36
+
37
+ def _do_extract(self, output_path: str, force_extract: bool) -> bool:
38
+ return force_extract or (
39
+ not os.path.isfile(output_path) and not (os.path.isdir(output_path) and os.listdir(output_path))
40
+ )
41
+
42
+ def extract(self, input_path: str, force_extract: bool = False) -> str:
43
+ extractor_format = self.extractor.infer_extractor_format(input_path)
44
+ if not extractor_format:
45
+ return input_path
46
+ output_path = self._get_output_path(input_path)
47
+ if self._do_extract(output_path, force_extract):
48
+ self.extractor.extract(input_path, output_path, extractor_format)
49
+ return output_path
50
+
51
+
52
+ class BaseExtractor(ABC):
53
+ @classmethod
54
+ @abstractmethod
55
+ def is_extractable(cls, path: Union[Path, str], **kwargs) -> bool: ...
56
+
57
+ @staticmethod
58
+ @abstractmethod
59
+ def extract(input_path: Union[Path, str], output_path: Union[Path, str]) -> None: ...
60
+
61
+
62
+ class MagicNumberBaseExtractor(BaseExtractor, ABC):
63
+ magic_numbers: List[bytes] = []
64
+
65
+ @staticmethod
66
+ def read_magic_number(path: Union[Path, str], magic_number_length: int):
67
+ with open(path, "rb") as f:
68
+ return f.read(magic_number_length)
69
+
70
+ @classmethod
71
+ def is_extractable(cls, path: Union[Path, str], magic_number: bytes = b"") -> bool:
72
+ if not magic_number:
73
+ magic_number_length = max(len(cls_magic_number) for cls_magic_number in cls.magic_numbers)
74
+ try:
75
+ magic_number = cls.read_magic_number(path, magic_number_length)
76
+ except OSError:
77
+ return False
78
+ return any(magic_number.startswith(cls_magic_number) for cls_magic_number in cls.magic_numbers)
79
+
80
+
81
+ class TarExtractor(BaseExtractor):
82
+ @classmethod
83
+ def is_extractable(cls, path: Union[Path, str], **kwargs) -> bool:
84
+ return tarfile.is_tarfile(path)
85
+
86
+ @staticmethod
87
+ def safemembers(members, output_path):
88
+ """
89
+ Fix for CVE-2007-4559
90
+ Desc:
91
+ Directory traversal vulnerability in the (1) extract and (2) extractall functions in the tarfile
92
+ module in Python allows user-assisted remote attackers to overwrite arbitrary files via a .. (dot dot)
93
+ sequence in filenames in a TAR archive, a related issue to CVE-2001-1267.
94
+ See: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2007-4559
95
+ From: https://stackoverflow.com/a/10077309
96
+ """
97
+
98
+ def resolved(path: str) -> str:
99
+ return os.path.realpath(os.path.abspath(path))
100
+
101
+ def badpath(path: str, base: str) -> bool:
102
+ # joinpath will ignore base if path is absolute
103
+ return not resolved(os.path.join(base, path)).startswith(base)
104
+
105
+ def badlink(info, base: str) -> bool:
106
+ # Links are interpreted relative to the directory containing the link
107
+ tip = resolved(os.path.join(base, os.path.dirname(info.name)))
108
+ return badpath(info.linkname, base=tip)
109
+
110
+ base = resolved(output_path)
111
+
112
+ for finfo in members:
113
+ if badpath(finfo.name, base):
114
+ logger.error(f"Extraction of {finfo.name} is blocked (illegal path)")
115
+ elif finfo.issym() and badlink(finfo, base):
116
+ logger.error(f"Extraction of {finfo.name} is blocked: Symlink to {finfo.linkname}")
117
+ elif finfo.islnk() and badlink(finfo, base):
118
+ logger.error(f"Extraction of {finfo.name} is blocked: Hard link to {finfo.linkname}")
119
+ else:
120
+ yield finfo
121
+
122
+ @staticmethod
123
+ def extract(input_path: Union[Path, str], output_path: Union[Path, str]) -> None:
124
+ os.makedirs(output_path, exist_ok=True)
125
+ tar_file = tarfile.open(input_path)
126
+ tar_file.extractall(output_path, members=TarExtractor.safemembers(tar_file, output_path))
127
+ tar_file.close()
128
+
129
+
130
+ class GzipExtractor(MagicNumberBaseExtractor):
131
+ magic_numbers = [b"\x1f\x8b"]
132
+
133
+ @staticmethod
134
+ def extract(input_path: Union[Path, str], output_path: Union[Path, str]) -> None:
135
+ with gzip.open(input_path, "rb") as gzip_file:
136
+ with open(output_path, "wb") as extracted_file:
137
+ shutil.copyfileobj(gzip_file, extracted_file)
138
+
139
+
140
+ class ZipExtractor(MagicNumberBaseExtractor):
141
+ magic_numbers = [
142
+ b"PK\x03\x04",
143
+ b"PK\x05\x06", # empty archive
144
+ b"PK\x07\x08", # spanned archive
145
+ ]
146
+
147
+ @classmethod
148
+ def is_extractable(cls, path: Union[Path, str], magic_number: bytes = b"") -> bool:
149
+ if super().is_extractable(path, magic_number=magic_number):
150
+ return True
151
+ try:
152
+ # Alternative version of zipfile.is_zipfile that has less false positives, but misses executable zip archives.
153
+ # From: https://github.com/python/cpython/pull/5053
154
+ from zipfile import (
155
+ _CD_SIGNATURE,
156
+ _ECD_DISK_NUMBER,
157
+ _ECD_DISK_START,
158
+ _ECD_ENTRIES_TOTAL,
159
+ _ECD_OFFSET,
160
+ _ECD_SIZE,
161
+ _EndRecData,
162
+ sizeCentralDir,
163
+ stringCentralDir,
164
+ structCentralDir,
165
+ )
166
+
167
+ with open(path, "rb") as fp:
168
+ endrec = _EndRecData(fp)
169
+ if endrec:
170
+ if endrec[_ECD_ENTRIES_TOTAL] == 0 and endrec[_ECD_SIZE] == 0 and endrec[_ECD_OFFSET] == 0:
171
+ return True # Empty zipfiles are still zipfiles
172
+ elif endrec[_ECD_DISK_NUMBER] == endrec[_ECD_DISK_START]:
173
+ fp.seek(endrec[_ECD_OFFSET]) # Central directory is on the same disk
174
+ if fp.tell() == endrec[_ECD_OFFSET] and endrec[_ECD_SIZE] >= sizeCentralDir:
175
+ data = fp.read(sizeCentralDir) # CD is where we expect it to be
176
+ if len(data) == sizeCentralDir:
177
+ centdir = struct.unpack(structCentralDir, data) # CD is the right size
178
+ if centdir[_CD_SIGNATURE] == stringCentralDir:
179
+ return True # First central directory entry has correct magic number
180
+ return False
181
+ except Exception: # catch all errors in case future python versions change the zipfile internals
182
+ return False
183
+
184
+ @staticmethod
185
+ def extract(input_path: Union[Path, str], output_path: Union[Path, str]) -> None:
186
+ os.makedirs(output_path, exist_ok=True)
187
+ with zipfile.ZipFile(input_path, "r") as zip_file:
188
+ zip_file.extractall(output_path)
189
+ zip_file.close()
190
+
191
+
192
+ class XzExtractor(MagicNumberBaseExtractor):
193
+ magic_numbers = [b"\xfd\x37\x7a\x58\x5a\x00"]
194
+
195
+ @staticmethod
196
+ def extract(input_path: Union[Path, str], output_path: Union[Path, str]) -> None:
197
+ with lzma.open(input_path) as compressed_file:
198
+ with open(output_path, "wb") as extracted_file:
199
+ shutil.copyfileobj(compressed_file, extracted_file)
200
+
201
+
202
+ class RarExtractor(MagicNumberBaseExtractor):
203
+ magic_numbers = [b"Rar!\x1a\x07\x00", b"Rar!\x1a\x07\x01\x00"] # RAR_ID # RAR5_ID
204
+
205
+ @staticmethod
206
+ def extract(input_path: Union[Path, str], output_path: Union[Path, str]) -> None:
207
+ if not config.RARFILE_AVAILABLE:
208
+ raise ImportError("Please pip install rarfile")
209
+ import rarfile
210
+
211
+ os.makedirs(output_path, exist_ok=True)
212
+ rf = rarfile.RarFile(input_path)
213
+ rf.extractall(output_path)
214
+ rf.close()
215
+
216
+
217
+ class ZstdExtractor(MagicNumberBaseExtractor):
218
+ magic_numbers = [b"\x28\xb5\x2f\xfd"]
219
+
220
+ @staticmethod
221
+ def extract(input_path: Union[Path, str], output_path: Union[Path, str]) -> None:
222
+ if not config.ZSTANDARD_AVAILABLE:
223
+ raise ImportError("Please pip install zstandard")
224
+ import zstandard as zstd
225
+
226
+ dctx = zstd.ZstdDecompressor()
227
+ with open(input_path, "rb") as ifh, open(output_path, "wb") as ofh:
228
+ dctx.copy_stream(ifh, ofh)
229
+
230
+
231
+ class Bzip2Extractor(MagicNumberBaseExtractor):
232
+ magic_numbers = [b"\x42\x5a\x68"]
233
+
234
+ @staticmethod
235
+ def extract(input_path: Union[Path, str], output_path: Union[Path, str]) -> None:
236
+ with bz2.open(input_path, "rb") as compressed_file:
237
+ with open(output_path, "wb") as extracted_file:
238
+ shutil.copyfileobj(compressed_file, extracted_file)
239
+
240
+
241
+ class SevenZipExtractor(MagicNumberBaseExtractor):
242
+ magic_numbers = [b"\x37\x7a\xbc\xaf\x27\x1c"]
243
+
244
+ @staticmethod
245
+ def extract(input_path: Union[Path, str], output_path: Union[Path, str]) -> None:
246
+ if not config.PY7ZR_AVAILABLE:
247
+ raise ImportError("Please pip install py7zr")
248
+ import py7zr
249
+
250
+ os.makedirs(output_path, exist_ok=True)
251
+ with py7zr.SevenZipFile(input_path, "r") as archive:
252
+ archive.extractall(output_path)
253
+
254
+
255
+ class Lz4Extractor(MagicNumberBaseExtractor):
256
+ magic_numbers = [b"\x04\x22\x4d\x18"]
257
+
258
+ @staticmethod
259
+ def extract(input_path: Union[Path, str], output_path: Union[Path, str]) -> None:
260
+ if not config.LZ4_AVAILABLE:
261
+ raise ImportError("Please pip install lz4")
262
+ import lz4.frame
263
+
264
+ with lz4.frame.open(input_path, "rb") as compressed_file:
265
+ with open(output_path, "wb") as extracted_file:
266
+ shutil.copyfileobj(compressed_file, extracted_file)
267
+
268
+
269
+ class Extractor:
270
+ # Put zip file to the last, b/c it is possible wrongly detected as zip (I guess it means: as tar or gzip)
271
+ extractors: Dict[str, Type[BaseExtractor]] = {
272
+ "tar": TarExtractor,
273
+ "gzip": GzipExtractor,
274
+ "zip": ZipExtractor,
275
+ "xz": XzExtractor,
276
+ "rar": RarExtractor,
277
+ "zstd": ZstdExtractor,
278
+ "bz2": Bzip2Extractor,
279
+ "7z": SevenZipExtractor, # <Added version="2.4.0"/>
280
+ "lz4": Lz4Extractor, # <Added version="2.4.0"/>
281
+ }
282
+
283
+ @classmethod
284
+ def _get_magic_number_max_length(cls):
285
+ return max(
286
+ len(extractor_magic_number)
287
+ for extractor in cls.extractors.values()
288
+ if issubclass(extractor, MagicNumberBaseExtractor)
289
+ for extractor_magic_number in extractor.magic_numbers
290
+ )
291
+
292
+ @staticmethod
293
+ def _read_magic_number(path: Union[Path, str], magic_number_length: int):
294
+ try:
295
+ return MagicNumberBaseExtractor.read_magic_number(path, magic_number_length=magic_number_length)
296
+ except OSError:
297
+ return b""
298
+
299
+ @classmethod
300
+ def is_extractable(cls, path: Union[Path, str], return_extractor: bool = False) -> bool:
301
+ warnings.warn(
302
+ "Method 'is_extractable' was deprecated in version 2.4.0 and will be removed in 3.0.0. "
303
+ "Use 'infer_extractor_format' instead.",
304
+ category=FutureWarning,
305
+ )
306
+ extractor_format = cls.infer_extractor_format(path)
307
+ if extractor_format:
308
+ return True if not return_extractor else (True, cls.extractors[extractor_format])
309
+ return False if not return_extractor else (False, None)
310
+
311
+ @classmethod
312
+ def infer_extractor_format(cls, path: Union[Path, str]) -> Optional[str]: # <Added version="2.4.0"/>
313
+ magic_number_max_length = cls._get_magic_number_max_length()
314
+ magic_number = cls._read_magic_number(path, magic_number_max_length)
315
+ for extractor_format, extractor in cls.extractors.items():
316
+ if extractor.is_extractable(path, magic_number=magic_number):
317
+ return extractor_format
318
+
319
+ @classmethod
320
+ def extract(
321
+ cls,
322
+ input_path: Union[Path, str],
323
+ output_path: Union[Path, str],
324
+ extractor_format: Optional[str] = None, # <Added version="2.4.0"/>
325
+ extractor: Optional[BaseExtractor] = "deprecated",
326
+ ) -> None:
327
+ os.makedirs(os.path.dirname(output_path), exist_ok=True)
328
+ # Prevent parallel extractions
329
+ lock_path = str(Path(output_path).with_suffix(".lock"))
330
+ with FileLock(lock_path):
331
+ shutil.rmtree(output_path, ignore_errors=True)
332
+ if extractor_format or extractor != "deprecated":
333
+ if extractor != "deprecated" or not isinstance(extractor_format, str): # passed as positional arg
334
+ warnings.warn(
335
+ "Parameter 'extractor' was deprecated in version 2.4.0 and will be removed in 3.0.0. "
336
+ "Use 'extractor_format' instead.",
337
+ category=FutureWarning,
338
+ )
339
+ extractor = extractor if extractor != "deprecated" else extractor_format
340
+ else:
341
+ extractor = cls.extractors[extractor_format]
342
+ return extractor.extract(input_path, output_path)
343
+ else:
344
+ warnings.warn(
345
+ "Parameter 'extractor_format' was made required in version 2.4.0 and not passing it will raise an "
346
+ "exception in 3.0.0.",
347
+ category=FutureWarning,
348
+ )
349
+ for extractor in cls.extractors.values():
350
+ if extractor.is_extractable(input_path):
351
+ return extractor.extract(input_path, output_path)
venv/lib/python3.10/site-packages/datasets/utils/file_utils.py ADDED
@@ -0,0 +1,1674 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Utilities for working with the local dataset cache.
3
+ This file is adapted from the AllenNLP library at https://github.com/allenai/allennlp
4
+ Copyright by the AllenNLP authors.
5
+ """
6
+
7
+ import copy
8
+ import glob
9
+ import io
10
+ import json
11
+ import multiprocessing
12
+ import os
13
+ import posixpath
14
+ import re
15
+ import shutil
16
+ import sys
17
+ import tarfile
18
+ import time
19
+ import urllib
20
+ import warnings
21
+ import xml.dom.minidom
22
+ import zipfile
23
+ from asyncio import TimeoutError
24
+ from contextlib import closing, contextmanager
25
+ from functools import partial
26
+ from io import BytesIO
27
+ from itertools import chain
28
+ from pathlib import Path, PurePosixPath
29
+ from typing import Any, Callable, Dict, Generator, List, Optional, Tuple, TypeVar, Union
30
+ from unittest.mock import patch
31
+ from urllib.parse import urljoin, urlparse
32
+ from xml.etree import ElementTree as ET
33
+
34
+ import fsspec
35
+ import huggingface_hub
36
+ import requests
37
+ from aiohttp.client_exceptions import ClientError
38
+ from fsspec.core import strip_protocol, url_to_fs
39
+ from fsspec.utils import can_be_local
40
+ from huggingface_hub.utils import EntryNotFoundError, insecure_hashlib
41
+ from packaging import version
42
+
43
+ from .. import __version__, config
44
+ from ..download.download_config import DownloadConfig
45
+ from ..filesystems import COMPRESSION_FILESYSTEMS
46
+ from . import _tqdm, logging
47
+ from . import tqdm as hf_tqdm
48
+ from ._filelock import FileLock
49
+ from .extract import ExtractManager
50
+ from .track import TrackedIterable
51
+
52
+
53
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
54
+
55
+ INCOMPLETE_SUFFIX = ".incomplete"
56
+
57
+ T = TypeVar("T", str, Path)
58
+
59
+
60
+ def init_hf_modules(hf_modules_cache: Optional[Union[Path, str]] = None) -> str:
61
+ """
62
+ Add hf_modules_cache to the python path.
63
+ By default hf_modules_cache='~/.cache/huggingface/modules'.
64
+ It can also be set with the environment variable HF_MODULES_CACHE.
65
+ This is used to add modules such as `datasets_modules`
66
+ """
67
+ hf_modules_cache = hf_modules_cache if hf_modules_cache is not None else config.HF_MODULES_CACHE
68
+ hf_modules_cache = str(hf_modules_cache)
69
+ if hf_modules_cache not in sys.path:
70
+ sys.path.append(hf_modules_cache)
71
+
72
+ os.makedirs(hf_modules_cache, exist_ok=True)
73
+ if not os.path.exists(os.path.join(hf_modules_cache, "__init__.py")):
74
+ with open(os.path.join(hf_modules_cache, "__init__.py"), "w"):
75
+ pass
76
+ return hf_modules_cache
77
+
78
+
79
+ def is_remote_url(url_or_filename: str) -> bool:
80
+ return urlparse(url_or_filename).scheme != "" and not os.path.ismount(urlparse(url_or_filename).scheme + ":/")
81
+
82
+
83
+ def is_local_path(url_or_filename: str) -> bool:
84
+ # On unix the scheme of a local path is empty (for both absolute and relative),
85
+ # while on windows the scheme is the drive name (ex: "c") for absolute paths.
86
+ # for details on the windows behavior, see https://bugs.python.org/issue42215
87
+ return urlparse(url_or_filename).scheme == "" or os.path.ismount(urlparse(url_or_filename).scheme + ":/")
88
+
89
+
90
+ def is_relative_path(url_or_filename: str) -> bool:
91
+ return urlparse(url_or_filename).scheme == "" and not os.path.isabs(url_or_filename)
92
+
93
+
94
+ def relative_to_absolute_path(path: T) -> T:
95
+ """Convert relative path to absolute path."""
96
+ abs_path_str = os.path.abspath(os.path.expanduser(os.path.expandvars(str(path))))
97
+ return Path(abs_path_str) if isinstance(path, Path) else abs_path_str
98
+
99
+
100
+ def hf_bucket_url(identifier: str, filename: str, use_cdn=False, dataset=True) -> str:
101
+ if dataset:
102
+ endpoint = config.CLOUDFRONT_DATASETS_DISTRIB_PREFIX if use_cdn else config.S3_DATASETS_BUCKET_PREFIX
103
+ else:
104
+ endpoint = config.CLOUDFRONT_METRICS_DISTRIB_PREFIX if use_cdn else config.S3_METRICS_BUCKET_PREFIX
105
+ return "/".join((endpoint, identifier, filename))
106
+
107
+
108
+ def head_hf_s3(
109
+ identifier: str, filename: str, use_cdn=False, dataset=True, max_retries=0
110
+ ) -> Union[requests.Response, Exception]:
111
+ return http_head(
112
+ hf_bucket_url(identifier=identifier, filename=filename, use_cdn=use_cdn, dataset=dataset),
113
+ max_retries=max_retries,
114
+ )
115
+
116
+
117
+ def hf_github_url(path: str, name: str, dataset=True, revision: Optional[str] = None) -> str:
118
+ default_revision = "main" if version.parse(__version__).is_devrelease else __version__
119
+ revision = revision or default_revision
120
+ if dataset:
121
+ return config.REPO_DATASETS_URL.format(revision=revision, path=path, name=name)
122
+ else:
123
+ return config.REPO_METRICS_URL.format(revision=revision, path=path, name=name)
124
+
125
+
126
+ def url_or_path_join(base_name: str, *pathnames: str) -> str:
127
+ if is_remote_url(base_name):
128
+ return posixpath.join(base_name, *(str(pathname).replace(os.sep, "/").lstrip("/") for pathname in pathnames))
129
+ else:
130
+ return Path(base_name, *pathnames).as_posix()
131
+
132
+
133
+ def url_or_path_parent(url_or_path: str) -> str:
134
+ if is_remote_url(url_or_path):
135
+ return url_or_path[: url_or_path.rindex("/")]
136
+ else:
137
+ return os.path.dirname(url_or_path)
138
+
139
+
140
+ def hash_url_to_filename(url, etag=None):
141
+ """
142
+ Convert `url` into a hashed filename in a repeatable way.
143
+ If `etag` is specified, append its hash to the url's, delimited
144
+ by a period.
145
+ If the url ends with .h5 (Keras HDF5 weights) adds '.h5' to the name
146
+ so that TF 2.0 can identify it as a HDF5 file
147
+ (see https://github.com/tensorflow/tensorflow/blob/00fad90125b18b80fe054de1055770cfb8fe4ba3/tensorflow/python/keras/engine/network.py#L1380)
148
+ """
149
+ url_bytes = url.encode("utf-8")
150
+ url_hash = insecure_hashlib.sha256(url_bytes)
151
+ filename = url_hash.hexdigest()
152
+
153
+ if etag:
154
+ etag_bytes = etag.encode("utf-8")
155
+ etag_hash = insecure_hashlib.sha256(etag_bytes)
156
+ filename += "." + etag_hash.hexdigest()
157
+
158
+ if url.endswith(".py"):
159
+ filename += ".py"
160
+
161
+ return filename
162
+
163
+
164
+ def cached_path(
165
+ url_or_filename,
166
+ download_config=None,
167
+ **download_kwargs,
168
+ ) -> str:
169
+ """
170
+ Given something that might be a URL (or might be a local path),
171
+ determine which. If it's a URL, download the file and cache it, and
172
+ return the path to the cached file. If it's already a local path,
173
+ make sure the file exists and then return the path.
174
+
175
+ Return:
176
+ Local path (string)
177
+
178
+ Raises:
179
+ FileNotFoundError: in case of non-recoverable file
180
+ (non-existent or no cache on disk)
181
+ ConnectionError: in case of unreachable url
182
+ and no cache on disk
183
+ ValueError: if it couldn't parse the url or filename correctly
184
+ requests.exceptions.ConnectionError: in case of internet connection issue
185
+ """
186
+ if download_config is None:
187
+ download_config = DownloadConfig(**download_kwargs)
188
+
189
+ cache_dir = download_config.cache_dir or config.DOWNLOADED_DATASETS_PATH
190
+ if isinstance(cache_dir, Path):
191
+ cache_dir = str(cache_dir)
192
+ if isinstance(url_or_filename, Path):
193
+ url_or_filename = str(url_or_filename)
194
+
195
+ # Convert fsspec URL in the format "file://local/path" to "local/path"
196
+ if can_be_local(url_or_filename):
197
+ url_or_filename = strip_protocol(url_or_filename)
198
+
199
+ if is_remote_url(url_or_filename):
200
+ # URL, so get it from the cache (downloading if necessary)
201
+ output_path = get_from_cache(
202
+ url_or_filename,
203
+ cache_dir=cache_dir,
204
+ force_download=download_config.force_download,
205
+ proxies=download_config.proxies,
206
+ resume_download=download_config.resume_download,
207
+ user_agent=download_config.user_agent,
208
+ local_files_only=download_config.local_files_only,
209
+ use_etag=download_config.use_etag,
210
+ max_retries=download_config.max_retries,
211
+ token=download_config.token,
212
+ ignore_url_params=download_config.ignore_url_params,
213
+ storage_options=download_config.storage_options,
214
+ download_desc=download_config.download_desc,
215
+ disable_tqdm=download_config.disable_tqdm,
216
+ )
217
+ elif os.path.exists(url_or_filename):
218
+ # File, and it exists.
219
+ output_path = url_or_filename
220
+ elif is_local_path(url_or_filename):
221
+ # File, but it doesn't exist.
222
+ raise FileNotFoundError(f"Local file {url_or_filename} doesn't exist")
223
+ else:
224
+ # Something unknown
225
+ raise ValueError(f"unable to parse {url_or_filename} as a URL or as a local path")
226
+
227
+ if output_path is None:
228
+ return output_path
229
+
230
+ if download_config.extract_compressed_file:
231
+ if download_config.extract_on_the_fly:
232
+ # Add a compression prefix to the compressed file so that it can be extracted
233
+ # as it's being read using xopen.
234
+ protocol = _get_extraction_protocol(output_path, download_config=download_config)
235
+ extension = _get_path_extension(url_or_filename.split("::")[0])
236
+ if (
237
+ protocol
238
+ and extension not in ["tgz", "tar"]
239
+ and not url_or_filename.split("::")[0].endswith((".tar.gz", ".tar.bz2", ".tar.xz"))
240
+ ):
241
+ output_path = relative_to_absolute_path(output_path)
242
+ if protocol in SINGLE_FILE_COMPRESSION_PROTOCOLS:
243
+ # there is one single file which is the uncompressed file
244
+ inner_file = os.path.basename(output_path)
245
+ inner_file = inner_file[: inner_file.rindex(".")] if "." in inner_file else inner_file
246
+ output_path = f"{protocol}://{inner_file}::{output_path}"
247
+ else:
248
+ output_path = f"{protocol}://::{output_path}"
249
+ return output_path
250
+
251
+ # Eager extraction
252
+ output_path = ExtractManager(cache_dir=download_config.cache_dir).extract(
253
+ output_path, force_extract=download_config.force_extract
254
+ )
255
+ return relative_to_absolute_path(output_path)
256
+
257
+
258
+ def get_datasets_user_agent(user_agent: Optional[Union[str, dict]] = None) -> str:
259
+ ua = f"datasets/{__version__}"
260
+ ua += f"; python/{config.PY_VERSION}"
261
+ ua += f"; huggingface_hub/{huggingface_hub.__version__}"
262
+ ua += f"; pyarrow/{config.PYARROW_VERSION}"
263
+ if config.TORCH_AVAILABLE:
264
+ ua += f"; torch/{config.TORCH_VERSION}"
265
+ if config.TF_AVAILABLE:
266
+ ua += f"; tensorflow/{config.TF_VERSION}"
267
+ if config.JAX_AVAILABLE:
268
+ ua += f"; jax/{config.JAX_VERSION}"
269
+ if config.BEAM_AVAILABLE:
270
+ ua += f"; apache_beam/{config.BEAM_VERSION}"
271
+ if isinstance(user_agent, dict):
272
+ ua += f"; {'; '.join(f'{k}/{v}' for k, v in user_agent.items())}"
273
+ elif isinstance(user_agent, str):
274
+ ua += "; " + user_agent
275
+ return ua
276
+
277
+
278
+ def get_authentication_headers_for_url(
279
+ url: str, token: Optional[Union[str, bool]] = None, use_auth_token: Optional[Union[str, bool]] = "deprecated"
280
+ ) -> dict:
281
+ """Handle the HF authentication"""
282
+ if use_auth_token != "deprecated":
283
+ warnings.warn(
284
+ "'use_auth_token' was deprecated in favor of 'token' in version 2.14.0 and will be removed in 3.0.0.\n"
285
+ f"You can remove this warning by passing 'token={use_auth_token}' instead.",
286
+ FutureWarning,
287
+ )
288
+ token = use_auth_token
289
+ if url.startswith(config.HF_ENDPOINT):
290
+ return huggingface_hub.utils.build_hf_headers(
291
+ token=token, library_name="datasets", library_version=__version__
292
+ )
293
+ else:
294
+ return {}
295
+
296
+
297
+ class OfflineModeIsEnabled(ConnectionError):
298
+ pass
299
+
300
+
301
+ def _raise_if_offline_mode_is_enabled(msg: Optional[str] = None):
302
+ """Raise an OfflineModeIsEnabled error (subclass of ConnectionError) if HF_DATASETS_OFFLINE is True."""
303
+ if config.HF_DATASETS_OFFLINE:
304
+ raise OfflineModeIsEnabled(
305
+ "Offline mode is enabled." if msg is None else "Offline mode is enabled. " + str(msg)
306
+ )
307
+
308
+
309
+ def _request_with_retry(
310
+ method: str,
311
+ url: str,
312
+ max_retries: int = 0,
313
+ base_wait_time: float = 0.5,
314
+ max_wait_time: float = 2,
315
+ timeout: float = 10.0,
316
+ **params,
317
+ ) -> requests.Response:
318
+ """Wrapper around requests to retry in case it fails with a ConnectTimeout, with exponential backoff.
319
+
320
+ Note that if the environment variable HF_DATASETS_OFFLINE is set to 1, then a OfflineModeIsEnabled error is raised.
321
+
322
+ Args:
323
+ method (str): HTTP method, such as 'GET' or 'HEAD'.
324
+ url (str): The URL of the resource to fetch.
325
+ max_retries (int): Maximum number of retries, defaults to 0 (no retries).
326
+ base_wait_time (float): Duration (in seconds) to wait before retrying the first time. Wait time between
327
+ retries then grows exponentially, capped by max_wait_time.
328
+ max_wait_time (float): Maximum amount of time between two retries, in seconds.
329
+ **params (additional keyword arguments): Params to pass to :obj:`requests.request`.
330
+ """
331
+ _raise_if_offline_mode_is_enabled(f"Tried to reach {url}")
332
+ tries, success = 0, False
333
+ while not success:
334
+ tries += 1
335
+ try:
336
+ response = requests.request(method=method.upper(), url=url, timeout=timeout, **params)
337
+ success = True
338
+ except (requests.exceptions.ConnectTimeout, requests.exceptions.ConnectionError) as err:
339
+ if tries > max_retries:
340
+ raise err
341
+ else:
342
+ logger.info(f"{method} request to {url} timed out, retrying... [{tries/max_retries}]")
343
+ sleep_time = min(max_wait_time, base_wait_time * 2 ** (tries - 1)) # Exponential backoff
344
+ time.sleep(sleep_time)
345
+ return response
346
+
347
+
348
+ def fsspec_head(url, storage_options=None):
349
+ _raise_if_offline_mode_is_enabled(f"Tried to reach {url}")
350
+ fs, path = url_to_fs(url, **(storage_options or {}))
351
+ return fs.info(path)
352
+
353
+
354
+ def stack_multiprocessing_download_progress_bars():
355
+ # Stack downloads progress bars automatically using HF_DATASETS_STACK_MULTIPROCESSING_DOWNLOAD_PROGRESS_BARS=1
356
+ # We use environment variables since the download may happen in a subprocess
357
+ return patch.dict(os.environ, {"HF_DATASETS_STACK_MULTIPROCESSING_DOWNLOAD_PROGRESS_BARS": "1"})
358
+
359
+
360
+ class TqdmCallback(fsspec.callbacks.TqdmCallback):
361
+ def __init__(self, tqdm_kwargs=None, *args, **kwargs):
362
+ if config.FSSPEC_VERSION < version.parse("2024.2.0"):
363
+ super().__init__(tqdm_kwargs, *args, **kwargs)
364
+ self._tqdm = _tqdm # replace tqdm module by datasets.utils.tqdm module
365
+ else:
366
+ kwargs["tqdm_cls"] = _tqdm.tqdm
367
+ super().__init__(tqdm_kwargs, *args, **kwargs)
368
+
369
+
370
+ def fsspec_get(url, temp_file, storage_options=None, desc=None, disable_tqdm=False):
371
+ _raise_if_offline_mode_is_enabled(f"Tried to reach {url}")
372
+ fs, path = url_to_fs(url, **(storage_options or {}))
373
+ callback = TqdmCallback(
374
+ tqdm_kwargs={
375
+ "desc": desc or "Downloading",
376
+ "unit": "B",
377
+ "unit_scale": True,
378
+ "position": multiprocessing.current_process()._identity[-1] # contains the ranks of subprocesses
379
+ if os.environ.get("HF_DATASETS_STACK_MULTIPROCESSING_DOWNLOAD_PROGRESS_BARS") == "1"
380
+ and multiprocessing.current_process()._identity
381
+ else None,
382
+ "disable": disable_tqdm,
383
+ }
384
+ )
385
+ fs.get_file(path, temp_file.name, callback=callback)
386
+
387
+
388
+ def ftp_head(url, timeout=10.0):
389
+ _raise_if_offline_mode_is_enabled(f"Tried to reach {url}")
390
+ try:
391
+ with closing(urllib.request.urlopen(url, timeout=timeout)) as r:
392
+ r.read(1)
393
+ except Exception:
394
+ return False
395
+ return True
396
+
397
+
398
+ def ftp_get(url, temp_file, timeout=10.0):
399
+ _raise_if_offline_mode_is_enabled(f"Tried to reach {url}")
400
+ try:
401
+ logger.info(f"Getting through FTP {url} into {temp_file.name}")
402
+ with closing(urllib.request.urlopen(url, timeout=timeout)) as r:
403
+ shutil.copyfileobj(r, temp_file)
404
+ except urllib.error.URLError as e:
405
+ raise ConnectionError(e) from None
406
+
407
+
408
+ def http_get(
409
+ url,
410
+ temp_file,
411
+ proxies=None,
412
+ resume_size=0,
413
+ headers=None,
414
+ cookies=None,
415
+ timeout=100.0,
416
+ max_retries=0,
417
+ desc=None,
418
+ disable_tqdm=False,
419
+ ) -> Optional[requests.Response]:
420
+ headers = dict(headers) if headers is not None else {}
421
+ headers["user-agent"] = get_datasets_user_agent(user_agent=headers.get("user-agent"))
422
+ if resume_size > 0:
423
+ headers["Range"] = f"bytes={resume_size:d}-"
424
+ response = _request_with_retry(
425
+ method="GET",
426
+ url=url,
427
+ stream=True,
428
+ proxies=proxies,
429
+ headers=headers,
430
+ cookies=cookies,
431
+ max_retries=max_retries,
432
+ timeout=timeout,
433
+ )
434
+ if temp_file is None:
435
+ return response
436
+ if response.status_code == 416: # Range not satisfiable
437
+ return
438
+ content_length = response.headers.get("Content-Length")
439
+ total = resume_size + int(content_length) if content_length is not None else None
440
+ with hf_tqdm(
441
+ unit="B",
442
+ unit_scale=True,
443
+ total=total,
444
+ initial=resume_size,
445
+ desc=desc or "Downloading",
446
+ position=multiprocessing.current_process()._identity[-1] # contains the ranks of subprocesses
447
+ if os.environ.get("HF_DATASETS_STACK_MULTIPROCESSING_DOWNLOAD_PROGRESS_BARS") == "1"
448
+ and multiprocessing.current_process()._identity
449
+ else None,
450
+ disable=disable_tqdm,
451
+ ) as progress:
452
+ for chunk in response.iter_content(chunk_size=1024):
453
+ progress.update(len(chunk))
454
+ temp_file.write(chunk)
455
+
456
+
457
+ def http_head(
458
+ url, proxies=None, headers=None, cookies=None, allow_redirects=True, timeout=10.0, max_retries=0
459
+ ) -> requests.Response:
460
+ headers = copy.deepcopy(headers) or {}
461
+ headers["user-agent"] = get_datasets_user_agent(user_agent=headers.get("user-agent"))
462
+ response = _request_with_retry(
463
+ method="HEAD",
464
+ url=url,
465
+ proxies=proxies,
466
+ headers=headers,
467
+ cookies=cookies,
468
+ allow_redirects=allow_redirects,
469
+ timeout=timeout,
470
+ max_retries=max_retries,
471
+ )
472
+ return response
473
+
474
+
475
+ def request_etag(
476
+ url: str, token: Optional[Union[str, bool]] = None, use_auth_token: Optional[Union[str, bool]] = "deprecated"
477
+ ) -> Optional[str]:
478
+ if use_auth_token != "deprecated":
479
+ warnings.warn(
480
+ "'use_auth_token' was deprecated in favor of 'token' in version 2.14.0 and will be removed in 3.0.0.\n"
481
+ f"You can remove this warning by passing 'token={use_auth_token}' instead.",
482
+ FutureWarning,
483
+ )
484
+ token = use_auth_token
485
+ if urlparse(url).scheme not in ("http", "https"):
486
+ return None
487
+ headers = get_authentication_headers_for_url(url, token=token)
488
+ response = http_head(url, headers=headers, max_retries=3)
489
+ response.raise_for_status()
490
+ etag = response.headers.get("ETag") if response.ok else None
491
+ return etag
492
+
493
+
494
+ def get_from_cache(
495
+ url,
496
+ cache_dir=None,
497
+ force_download=False,
498
+ proxies=None,
499
+ etag_timeout=100,
500
+ resume_download=False,
501
+ user_agent=None,
502
+ local_files_only=False,
503
+ use_etag=True,
504
+ max_retries=0,
505
+ token=None,
506
+ use_auth_token="deprecated",
507
+ ignore_url_params=False,
508
+ storage_options=None,
509
+ download_desc=None,
510
+ disable_tqdm=False,
511
+ ) -> str:
512
+ """
513
+ Given a URL, look for the corresponding file in the local cache.
514
+ If it's not there, download it. Then return the path to the cached file.
515
+
516
+ Return:
517
+ Local path (string)
518
+
519
+ Raises:
520
+ FileNotFoundError: in case of non-recoverable file
521
+ (non-existent or no cache on disk)
522
+ ConnectionError: in case of unreachable url
523
+ and no cache on disk
524
+ """
525
+ if use_auth_token != "deprecated":
526
+ warnings.warn(
527
+ "'use_auth_token' was deprecated in favor of 'token' in version 2.14.0 and will be removed in 3.0.0.\n"
528
+ f"You can remove this warning by passing 'token={use_auth_token}' instead.",
529
+ FutureWarning,
530
+ )
531
+ token = use_auth_token
532
+ if cache_dir is None:
533
+ cache_dir = config.HF_DATASETS_CACHE
534
+ if isinstance(cache_dir, Path):
535
+ cache_dir = str(cache_dir)
536
+
537
+ os.makedirs(cache_dir, exist_ok=True)
538
+
539
+ if ignore_url_params:
540
+ # strip all query parameters and #fragments from the URL
541
+ cached_url = urljoin(url, urlparse(url).path)
542
+ else:
543
+ cached_url = url # additional parameters may be added to the given URL
544
+
545
+ connected = False
546
+ response = None
547
+ cookies = None
548
+ etag = None
549
+ head_error = None
550
+ scheme = None
551
+
552
+ # Try a first time to file the file on the local file system without eTag (None)
553
+ # if we don't ask for 'force_download' then we spare a request
554
+ filename = hash_url_to_filename(cached_url, etag=None)
555
+ cache_path = os.path.join(cache_dir, filename)
556
+
557
+ if os.path.exists(cache_path) and not force_download and not use_etag:
558
+ return cache_path
559
+
560
+ # Prepare headers for authentication
561
+ headers = get_authentication_headers_for_url(url, token=token)
562
+ if user_agent is not None:
563
+ headers["user-agent"] = user_agent
564
+
565
+ # We don't have the file locally or we need an eTag
566
+ if not local_files_only:
567
+ scheme = urlparse(url).scheme
568
+ if scheme == "ftp":
569
+ connected = ftp_head(url)
570
+ elif scheme not in ("http", "https"):
571
+ response = fsspec_head(url, storage_options=storage_options)
572
+ # s3fs uses "ETag", gcsfs uses "etag"
573
+ etag = (response.get("ETag", None) or response.get("etag", None)) if use_etag else None
574
+ connected = True
575
+ try:
576
+ response = http_head(
577
+ url,
578
+ allow_redirects=True,
579
+ proxies=proxies,
580
+ timeout=etag_timeout,
581
+ max_retries=max_retries,
582
+ headers=headers,
583
+ )
584
+ if response.status_code == 200: # ok
585
+ etag = response.headers.get("ETag") if use_etag else None
586
+ for k, v in response.cookies.items():
587
+ # In some edge cases, we need to get a confirmation token
588
+ if k.startswith("download_warning") and "drive.google.com" in url:
589
+ url += "&confirm=" + v
590
+ cookies = response.cookies
591
+ connected = True
592
+ # Fix Google Drive URL to avoid Virus scan warning
593
+ if "drive.google.com" in url and "confirm=" not in url:
594
+ url += "&confirm=t"
595
+ # In some edge cases, head request returns 400 but the connection is actually ok
596
+ elif (
597
+ (response.status_code == 400 and "firebasestorage.googleapis.com" in url)
598
+ or (response.status_code == 405 and "drive.google.com" in url)
599
+ or (
600
+ response.status_code == 403
601
+ and (
602
+ re.match(r"^https?://github.com/.*?/.*?/releases/download/.*?/.*?$", url)
603
+ or re.match(r"^https://.*?s3.*?amazonaws.com/.*?$", response.url)
604
+ )
605
+ )
606
+ or (response.status_code == 403 and "ndownloader.figstatic.com" in url)
607
+ ):
608
+ connected = True
609
+ logger.info(f"Couldn't get ETag version for url {url}")
610
+ elif response.status_code == 401 and config.HF_ENDPOINT in url and token is None:
611
+ raise ConnectionError(
612
+ f"Unauthorized for URL {url}. Please use the parameter `token=True` after logging in with `huggingface-cli login`"
613
+ )
614
+ except (OSError, requests.exceptions.Timeout) as e:
615
+ # not connected
616
+ head_error = e
617
+ pass
618
+
619
+ # connected == False = we don't have a connection, or url doesn't exist, or is otherwise inaccessible.
620
+ # try to get the last downloaded one
621
+ if not connected:
622
+ if os.path.exists(cache_path) and not force_download:
623
+ return cache_path
624
+ if local_files_only:
625
+ raise FileNotFoundError(
626
+ f"Cannot find the requested files in the cached path at {cache_path} and outgoing traffic has been"
627
+ " disabled. To enable file online look-ups, set 'local_files_only' to False."
628
+ )
629
+ elif response is not None and response.status_code == 404:
630
+ raise FileNotFoundError(f"Couldn't find file at {url}")
631
+ _raise_if_offline_mode_is_enabled(f"Tried to reach {url}")
632
+ if head_error is not None:
633
+ raise ConnectionError(f"Couldn't reach {url} ({repr(head_error)})")
634
+ elif response is not None:
635
+ raise ConnectionError(f"Couldn't reach {url} (error {response.status_code})")
636
+ else:
637
+ raise ConnectionError(f"Couldn't reach {url}")
638
+
639
+ # Try a second time
640
+ filename = hash_url_to_filename(cached_url, etag)
641
+ cache_path = os.path.join(cache_dir, filename)
642
+
643
+ if os.path.exists(cache_path) and not force_download:
644
+ return cache_path
645
+
646
+ # From now on, connected is True.
647
+ # Prevent parallel downloads of the same file with a lock.
648
+ lock_path = cache_path + ".lock"
649
+ with FileLock(lock_path):
650
+ # Retry in case previously locked processes just enter after the precedent process releases the lock
651
+ if os.path.exists(cache_path) and not force_download:
652
+ return cache_path
653
+
654
+ incomplete_path = cache_path + ".incomplete"
655
+
656
+ @contextmanager
657
+ def temp_file_manager(mode="w+b"):
658
+ with open(incomplete_path, mode) as f:
659
+ yield f
660
+
661
+ resume_size = 0
662
+ if resume_download:
663
+ temp_file_manager = partial(temp_file_manager, mode="a+b")
664
+ if os.path.exists(incomplete_path):
665
+ resume_size = os.stat(incomplete_path).st_size
666
+
667
+ # Download to temporary file, then copy to cache path once finished.
668
+ # Otherwise, you get corrupt cache entries if the download gets interrupted.
669
+ with temp_file_manager() as temp_file:
670
+ logger.info(f"{url} not found in cache or force_download set to True, downloading to {temp_file.name}")
671
+
672
+ # GET file object
673
+ if scheme == "ftp":
674
+ ftp_get(url, temp_file)
675
+ elif scheme not in ("http", "https"):
676
+ fsspec_get(
677
+ url, temp_file, storage_options=storage_options, desc=download_desc, disable_tqdm=disable_tqdm
678
+ )
679
+ else:
680
+ http_get(
681
+ url,
682
+ temp_file=temp_file,
683
+ proxies=proxies,
684
+ resume_size=resume_size,
685
+ headers=headers,
686
+ cookies=cookies,
687
+ max_retries=max_retries,
688
+ desc=download_desc,
689
+ disable_tqdm=disable_tqdm,
690
+ )
691
+
692
+ logger.info(f"storing {url} in cache at {cache_path}")
693
+ shutil.move(temp_file.name, cache_path)
694
+ umask = os.umask(0o666)
695
+ os.umask(umask)
696
+ os.chmod(cache_path, 0o666 & ~umask)
697
+
698
+ logger.info(f"creating metadata file for {cache_path}")
699
+ meta = {"url": url, "etag": etag}
700
+ meta_path = cache_path + ".json"
701
+ with open(meta_path, "w", encoding="utf-8") as meta_file:
702
+ json.dump(meta, meta_file)
703
+
704
+ return cache_path
705
+
706
+
707
+ def add_start_docstrings(*docstr):
708
+ def docstring_decorator(fn):
709
+ fn.__doc__ = "".join(docstr) + "\n\n" + (fn.__doc__ if fn.__doc__ is not None else "")
710
+ return fn
711
+
712
+ return docstring_decorator
713
+
714
+
715
+ def add_end_docstrings(*docstr):
716
+ def docstring_decorator(fn):
717
+ fn.__doc__ = (fn.__doc__ if fn.__doc__ is not None else "") + "\n\n" + "".join(docstr)
718
+ return fn
719
+
720
+ return docstring_decorator
721
+
722
+
723
+ def estimate_dataset_size(paths):
724
+ return sum(path.stat().st_size for path in paths)
725
+
726
+
727
+ def readline(f: io.RawIOBase):
728
+ # From: https://github.com/python/cpython/blob/d27e2f4d118e7a9909b6a3e5da06c5ff95806a85/Lib/_pyio.py#L525
729
+ res = bytearray()
730
+ while True:
731
+ b = f.read(1)
732
+ if not b:
733
+ break
734
+ res += b
735
+ if res.endswith(b"\n"):
736
+ break
737
+ return bytes(res)
738
+
739
+
740
+ #######################
741
+ # Streaming utilities #
742
+ #######################
743
+
744
+ BASE_KNOWN_EXTENSIONS = [
745
+ "txt",
746
+ "csv",
747
+ "json",
748
+ "jsonl",
749
+ "tsv",
750
+ "conll",
751
+ "conllu",
752
+ "orig",
753
+ "parquet",
754
+ "pkl",
755
+ "pickle",
756
+ "rel",
757
+ "xml",
758
+ ]
759
+ COMPRESSION_EXTENSION_TO_PROTOCOL = {
760
+ # single file compression
761
+ **{fs_class.extension.lstrip("."): fs_class.protocol for fs_class in COMPRESSION_FILESYSTEMS},
762
+ # archive compression
763
+ "zip": "zip",
764
+ }
765
+ SINGLE_FILE_COMPRESSION_PROTOCOLS = {fs_class.protocol for fs_class in COMPRESSION_FILESYSTEMS}
766
+ SINGLE_SLASH_AFTER_PROTOCOL_PATTERN = re.compile(r"(?<!:):/")
767
+
768
+
769
+ MAGIC_NUMBER_TO_COMPRESSION_PROTOCOL = {
770
+ bytes.fromhex("504B0304"): "zip",
771
+ bytes.fromhex("504B0506"): "zip", # empty archive
772
+ bytes.fromhex("504B0708"): "zip", # spanned archive
773
+ bytes.fromhex("425A68"): "bz2",
774
+ bytes.fromhex("1F8B"): "gzip",
775
+ bytes.fromhex("FD377A585A00"): "xz",
776
+ bytes.fromhex("04224D18"): "lz4",
777
+ bytes.fromhex("28B52FFD"): "zstd",
778
+ }
779
+ MAGIC_NUMBER_TO_UNSUPPORTED_COMPRESSION_PROTOCOL = {
780
+ b"Rar!": "rar",
781
+ }
782
+ MAGIC_NUMBER_MAX_LENGTH = max(
783
+ len(magic_number)
784
+ for magic_number in chain(MAGIC_NUMBER_TO_COMPRESSION_PROTOCOL, MAGIC_NUMBER_TO_UNSUPPORTED_COMPRESSION_PROTOCOL)
785
+ )
786
+
787
+
788
+ class NonStreamableDatasetError(Exception):
789
+ pass
790
+
791
+
792
+ def _get_path_extension(path: str) -> str:
793
+ # Get extension: https://foo.bar/train.json.gz -> gz
794
+ extension = path.split(".")[-1]
795
+ # Remove query params ("dl=1", "raw=true"): gz?dl=1 -> gz
796
+ # Remove shards infos (".txt_1", ".txt-00000-of-00100"): txt_1 -> txt
797
+ for symb in "?-_":
798
+ extension = extension.split(symb)[0]
799
+ return extension
800
+
801
+
802
+ def _get_extraction_protocol_with_magic_number(f) -> Optional[str]:
803
+ """read the magic number from a file-like object and return the compression protocol"""
804
+ # Check if the file object is seekable even before reading the magic number (to avoid https://bugs.python.org/issue26440)
805
+ try:
806
+ f.seek(0)
807
+ except (AttributeError, io.UnsupportedOperation):
808
+ return None
809
+ magic_number = f.read(MAGIC_NUMBER_MAX_LENGTH)
810
+ f.seek(0)
811
+ for i in range(MAGIC_NUMBER_MAX_LENGTH):
812
+ compression = MAGIC_NUMBER_TO_COMPRESSION_PROTOCOL.get(magic_number[: MAGIC_NUMBER_MAX_LENGTH - i])
813
+ if compression is not None:
814
+ return compression
815
+ compression = MAGIC_NUMBER_TO_UNSUPPORTED_COMPRESSION_PROTOCOL.get(magic_number[: MAGIC_NUMBER_MAX_LENGTH - i])
816
+ if compression is not None:
817
+ raise NotImplementedError(f"Compression protocol '{compression}' not implemented.")
818
+
819
+
820
+ def _get_extraction_protocol(urlpath: str, download_config: Optional[DownloadConfig] = None) -> Optional[str]:
821
+ # get inner file: zip://train-00000.json.gz::https://foo.bar/data.zip -> zip://train-00000.json.gz
822
+ urlpath = str(urlpath)
823
+ path = urlpath.split("::")[0]
824
+ extension = _get_path_extension(path)
825
+ if (
826
+ extension in BASE_KNOWN_EXTENSIONS
827
+ or extension in ["tgz", "tar"]
828
+ or path.endswith((".tar.gz", ".tar.bz2", ".tar.xz"))
829
+ ):
830
+ return None
831
+ elif extension in COMPRESSION_EXTENSION_TO_PROTOCOL:
832
+ return COMPRESSION_EXTENSION_TO_PROTOCOL[extension]
833
+ urlpath, storage_options = _prepare_path_and_storage_options(urlpath, download_config=download_config)
834
+ try:
835
+ with fsspec.open(urlpath, **(storage_options or {})) as f:
836
+ return _get_extraction_protocol_with_magic_number(f)
837
+ except FileNotFoundError:
838
+ if urlpath.startswith(config.HF_ENDPOINT):
839
+ raise FileNotFoundError(
840
+ urlpath + "\nIf the repo is private or gated, make sure to log in with `huggingface-cli login`."
841
+ ) from None
842
+ else:
843
+ raise
844
+
845
+
846
+ def xjoin(a, *p):
847
+ """
848
+ This function extends os.path.join to support the "::" hop separator. It supports both paths and urls.
849
+
850
+ A shorthand, particularly useful where you have multiple hops, is to “chain” the URLs with the special separator "::".
851
+ This is used to access files inside a zip file over http for example.
852
+
853
+ Let's say you have a zip file at https://host.com/archive.zip, and you want to access the file inside the zip file at /folder1/file.txt.
854
+ Then you can just chain the url this way:
855
+
856
+ zip://folder1/file.txt::https://host.com/archive.zip
857
+
858
+ The xjoin function allows you to apply the join on the first path of the chain.
859
+
860
+ Example::
861
+
862
+ >>> xjoin("zip://folder1::https://host.com/archive.zip", "file.txt")
863
+ zip://folder1/file.txt::https://host.com/archive.zip
864
+ """
865
+ a, *b = str(a).split("::")
866
+ if is_local_path(a):
867
+ return os.path.join(a, *p)
868
+ else:
869
+ a = posixpath.join(a, *p)
870
+ return "::".join([a] + b)
871
+
872
+
873
+ def xdirname(a):
874
+ """
875
+ This function extends os.path.dirname to support the "::" hop separator. It supports both paths and urls.
876
+
877
+ A shorthand, particularly useful where you have multiple hops, is to “chain” the URLs with the special separator "::".
878
+ This is used to access files inside a zip file over http for example.
879
+
880
+ Let's say you have a zip file at https://host.com/archive.zip, and you want to access the file inside the zip file at /folder1/file.txt.
881
+ Then you can just chain the url this way:
882
+
883
+ zip://folder1/file.txt::https://host.com/archive.zip
884
+
885
+ The xdirname function allows you to apply the dirname on the first path of the chain.
886
+
887
+ Example::
888
+
889
+ >>> xdirname("zip://folder1/file.txt::https://host.com/archive.zip")
890
+ zip://folder1::https://host.com/archive.zip
891
+ """
892
+ a, *b = str(a).split("::")
893
+ if is_local_path(a):
894
+ a = os.path.dirname(Path(a).as_posix())
895
+ else:
896
+ a = posixpath.dirname(a)
897
+ # if we end up at the root of the protocol, we get for example a = 'http:'
898
+ # so we have to fix it by adding the '//' that was removed:
899
+ if a.endswith(":"):
900
+ a += "//"
901
+ return "::".join([a] + b)
902
+
903
+
904
+ def xexists(urlpath: str, download_config: Optional[DownloadConfig] = None):
905
+ """Extend `os.path.exists` function to support both local and remote files.
906
+
907
+ Args:
908
+ urlpath (`str`): URL path.
909
+ download_config : mainly use token or storage_options to support different platforms and auth types.
910
+
911
+ Returns:
912
+ `bool`
913
+ """
914
+
915
+ main_hop, *rest_hops = _as_str(urlpath).split("::")
916
+ if is_local_path(main_hop):
917
+ return os.path.exists(main_hop)
918
+ else:
919
+ urlpath, storage_options = _prepare_path_and_storage_options(urlpath, download_config=download_config)
920
+ main_hop, *rest_hops = urlpath.split("::")
921
+ fs, *_ = url_to_fs(urlpath, **storage_options)
922
+ return fs.exists(main_hop)
923
+
924
+
925
+ def xbasename(a):
926
+ """
927
+ This function extends os.path.basename to support the "::" hop separator. It supports both paths and urls.
928
+
929
+ A shorthand, particularly useful where you have multiple hops, is to “chain” the URLs with the special separator "::".
930
+ This is used to access files inside a zip file over http for example.
931
+
932
+ Let's say you have a zip file at https://host.com/archive.zip, and you want to access the file inside the zip file at /folder1/file.txt.
933
+ Then you can just chain the url this way:
934
+
935
+ zip://folder1/file.txt::https://host.com/archive.zip
936
+
937
+ The xbasename function allows you to apply the basename on the first path of the chain.
938
+
939
+ Example::
940
+
941
+ >>> xbasename("zip://folder1/file.txt::https://host.com/archive.zip")
942
+ file.txt
943
+ """
944
+ a, *b = str(a).split("::")
945
+ if is_local_path(a):
946
+ return os.path.basename(Path(a).as_posix())
947
+ else:
948
+ return posixpath.basename(a)
949
+
950
+
951
+ def xsplit(a):
952
+ """
953
+ This function extends os.path.split to support the "::" hop separator. It supports both paths and urls.
954
+
955
+ A shorthand, particularly useful where you have multiple hops, is to “chain” the URLs with the special separator "::".
956
+ This is used to access files inside a zip file over http for example.
957
+
958
+ Let's say you have a zip file at https://host.com/archive.zip, and you want to access the file inside the zip file at /folder1/file.txt.
959
+ Then you can just chain the url this way:
960
+
961
+ zip://folder1/file.txt::https://host.com/archive.zip
962
+
963
+ The xsplit function allows you to apply the xsplit on the first path of the chain.
964
+
965
+ Example::
966
+
967
+ >>> xsplit("zip://folder1/file.txt::https://host.com/archive.zip")
968
+ ('zip://folder1::https://host.com/archive.zip', 'file.txt')
969
+ """
970
+ a, *b = str(a).split("::")
971
+ if is_local_path(a):
972
+ return os.path.split(Path(a).as_posix())
973
+ else:
974
+ a, tail = posixpath.split(a)
975
+ return "::".join([a + "//" if a.endswith(":") else a] + b), tail
976
+
977
+
978
+ def xsplitext(a):
979
+ """
980
+ This function extends os.path.splitext to support the "::" hop separator. It supports both paths and urls.
981
+
982
+ A shorthand, particularly useful where you have multiple hops, is to “chain” the URLs with the special separator "::".
983
+ This is used to access files inside a zip file over http for example.
984
+
985
+ Let's say you have a zip file at https://host.com/archive.zip, and you want to access the file inside the zip file at /folder1/file.txt.
986
+ Then you can just chain the url this way:
987
+
988
+ zip://folder1/file.txt::https://host.com/archive.zip
989
+
990
+ The xsplitext function allows you to apply the splitext on the first path of the chain.
991
+
992
+ Example::
993
+
994
+ >>> xsplitext("zip://folder1/file.txt::https://host.com/archive.zip")
995
+ ('zip://folder1/file::https://host.com/archive.zip', '.txt')
996
+ """
997
+ a, *b = str(a).split("::")
998
+ if is_local_path(a):
999
+ return os.path.splitext(Path(a).as_posix())
1000
+ else:
1001
+ a, ext = posixpath.splitext(a)
1002
+ return "::".join([a] + b), ext
1003
+
1004
+
1005
+ def xisfile(path, download_config: Optional[DownloadConfig] = None) -> bool:
1006
+ """Extend `os.path.isfile` function to support remote files.
1007
+
1008
+ Args:
1009
+ path (`str`): URL path.
1010
+ download_config : mainly use token or storage_options to support different platforms and auth types.
1011
+
1012
+ Returns:
1013
+ `bool`
1014
+ """
1015
+ main_hop, *rest_hops = str(path).split("::")
1016
+ if is_local_path(main_hop):
1017
+ return os.path.isfile(path)
1018
+ else:
1019
+ path, storage_options = _prepare_path_and_storage_options(path, download_config=download_config)
1020
+ main_hop, *rest_hops = path.split("::")
1021
+ fs, *_ = url_to_fs(path, **storage_options)
1022
+ return fs.isfile(main_hop)
1023
+
1024
+
1025
+ def xgetsize(path, download_config: Optional[DownloadConfig] = None) -> int:
1026
+ """Extend `os.path.getsize` function to support remote files.
1027
+
1028
+ Args:
1029
+ path (`str`): URL path.
1030
+ download_config : mainly use token or storage_options to support different platforms and auth types.
1031
+
1032
+ Returns:
1033
+ `int`: optional
1034
+ """
1035
+ main_hop, *rest_hops = str(path).split("::")
1036
+ if is_local_path(main_hop):
1037
+ return os.path.getsize(path)
1038
+ else:
1039
+ path, storage_options = _prepare_path_and_storage_options(path, download_config=download_config)
1040
+ main_hop, *rest_hops = path.split("::")
1041
+ fs, *_ = fs, *_ = url_to_fs(path, **storage_options)
1042
+ try:
1043
+ size = fs.size(main_hop)
1044
+ except EntryNotFoundError:
1045
+ raise FileNotFoundError(f"No such file: {path}")
1046
+ if size is None:
1047
+ # use xopen instead of fs.open to make data fetching more robust
1048
+ with xopen(path, download_config=download_config) as f:
1049
+ size = len(f.read())
1050
+ return size
1051
+
1052
+
1053
+ def xisdir(path, download_config: Optional[DownloadConfig] = None) -> bool:
1054
+ """Extend `os.path.isdir` function to support remote files.
1055
+
1056
+ Args:
1057
+ path (`str`): URL path.
1058
+ download_config : mainly use token or storage_options to support different platforms and auth types.
1059
+
1060
+ Returns:
1061
+ `bool`
1062
+ """
1063
+ main_hop, *rest_hops = str(path).split("::")
1064
+ if is_local_path(main_hop):
1065
+ return os.path.isdir(path)
1066
+ else:
1067
+ path, storage_options = _prepare_path_and_storage_options(path, download_config=download_config)
1068
+ main_hop, *rest_hops = path.split("::")
1069
+ fs, *_ = fs, *_ = url_to_fs(path, **storage_options)
1070
+ inner_path = main_hop.split("://")[-1]
1071
+ if not inner_path.strip("/"):
1072
+ return True
1073
+ return fs.isdir(inner_path)
1074
+
1075
+
1076
+ def xrelpath(path, start=None):
1077
+ """Extend `os.path.relpath` function to support remote files.
1078
+
1079
+ Args:
1080
+ path (`str`): URL path.
1081
+ start (`str`): Start URL directory path.
1082
+
1083
+ Returns:
1084
+ `str`
1085
+ """
1086
+ main_hop, *rest_hops = str(path).split("::")
1087
+ if is_local_path(main_hop):
1088
+ return os.path.relpath(main_hop, start=start) if start else os.path.relpath(main_hop)
1089
+ else:
1090
+ return posixpath.relpath(main_hop, start=str(start).split("::")[0]) if start else os.path.relpath(main_hop)
1091
+
1092
+
1093
+ def _add_retries_to_file_obj_read_method(file_obj):
1094
+ read = file_obj.read
1095
+ max_retries = config.STREAMING_READ_MAX_RETRIES
1096
+
1097
+ def read_with_retries(*args, **kwargs):
1098
+ disconnect_err = None
1099
+ for retry in range(1, max_retries + 1):
1100
+ try:
1101
+ out = read(*args, **kwargs)
1102
+ break
1103
+ except (ClientError, TimeoutError) as err:
1104
+ disconnect_err = err
1105
+ logger.warning(
1106
+ f"Got disconnected from remote data host. Retrying in {config.STREAMING_READ_RETRY_INTERVAL}sec [{retry}/{max_retries}]"
1107
+ )
1108
+ time.sleep(config.STREAMING_READ_RETRY_INTERVAL)
1109
+ else:
1110
+ raise ConnectionError("Server Disconnected") from disconnect_err
1111
+ return out
1112
+
1113
+ try:
1114
+ file_obj.read = read_with_retries
1115
+ except AttributeError: # read-only attribute
1116
+ orig_file_obj = file_obj
1117
+ file_obj = io.RawIOBase()
1118
+ file_obj.read = read_with_retries
1119
+ file_obj.__getattr__ = lambda _, attr: getattr(orig_file_obj, attr)
1120
+ return file_obj
1121
+
1122
+
1123
+ def _prepare_path_and_storage_options(
1124
+ urlpath: str, download_config: Optional[DownloadConfig] = None
1125
+ ) -> Tuple[str, Dict[str, Dict[str, Any]]]:
1126
+ prepared_urlpath = []
1127
+ prepared_storage_options = {}
1128
+ for hop in urlpath.split("::"):
1129
+ hop, storage_options = _prepare_single_hop_path_and_storage_options(hop, download_config=download_config)
1130
+ prepared_urlpath.append(hop)
1131
+ prepared_storage_options.update(storage_options)
1132
+ return "::".join(prepared_urlpath), storage_options
1133
+
1134
+
1135
+ def _prepare_single_hop_path_and_storage_options(
1136
+ urlpath: str, download_config: Optional[DownloadConfig] = None
1137
+ ) -> Tuple[str, Dict[str, Dict[str, Any]]]:
1138
+ """
1139
+ Prepare the URL and the kwargs that must be passed to the HttpFileSystem or to requests.get/head
1140
+
1141
+ In particular it resolves google drive URLs
1142
+ It also adds the authentication headers for the Hugging Face Hub, for both https:// and hf:// paths.
1143
+
1144
+ Storage options are formatted in the form {protocol: storage_options_for_protocol}
1145
+ """
1146
+ token = None if download_config is None else download_config.token
1147
+ if urlpath.startswith(config.HF_ENDPOINT) and "/resolve/" in urlpath:
1148
+ urlpath = "hf://" + urlpath[len(config.HF_ENDPOINT) + 1 :].replace("/resolve/", "@", 1)
1149
+ protocol = urlpath.split("://")[0] if "://" in urlpath else "file"
1150
+ if download_config is not None and protocol in download_config.storage_options:
1151
+ storage_options = download_config.storage_options[protocol]
1152
+ elif download_config is not None and protocol not in download_config.storage_options:
1153
+ storage_options = {
1154
+ option_name: option_value
1155
+ for option_name, option_value in download_config.storage_options.items()
1156
+ if option_name not in fsspec.available_protocols()
1157
+ }
1158
+ else:
1159
+ storage_options = {}
1160
+ if storage_options:
1161
+ storage_options = {protocol: storage_options}
1162
+ if protocol in ["http", "https"]:
1163
+ storage_options[protocol] = {
1164
+ "headers": {
1165
+ **get_authentication_headers_for_url(urlpath, token=token),
1166
+ "user-agent": get_datasets_user_agent(),
1167
+ },
1168
+ "client_kwargs": {"trust_env": True}, # Enable reading proxy env variables.
1169
+ **(storage_options.get(protocol, {})),
1170
+ }
1171
+ if "drive.google.com" in urlpath:
1172
+ response = http_head(urlpath)
1173
+ cookies = None
1174
+ for k, v in response.cookies.items():
1175
+ if k.startswith("download_warning"):
1176
+ urlpath += "&confirm=" + v
1177
+ cookies = response.cookies
1178
+ storage_options[protocol] = {"cookies": cookies, **storage_options.get(protocol, {})}
1179
+ # Fix Google Drive URL to avoid Virus scan warning
1180
+ if "drive.google.com" in urlpath and "confirm=" not in urlpath:
1181
+ urlpath += "&confirm=t"
1182
+ if urlpath.startswith("https://raw.githubusercontent.com/"):
1183
+ # Workaround for served data with gzip content-encoding: https://github.com/fsspec/filesystem_spec/issues/389
1184
+ storage_options[protocol]["headers"]["Accept-Encoding"] = "identity"
1185
+ elif protocol == "hf":
1186
+ storage_options[protocol] = {
1187
+ "token": token,
1188
+ "endpoint": config.HF_ENDPOINT,
1189
+ **storage_options.get(protocol, {}),
1190
+ }
1191
+ # streaming with block_size=0 is only implemented in 0.21 (see https://github.com/huggingface/huggingface_hub/pull/1967)
1192
+ if config.HF_HUB_VERSION < version.parse("0.21.0"):
1193
+ storage_options[protocol]["block_size"] = "default"
1194
+ return urlpath, storage_options
1195
+
1196
+
1197
+ def xopen(file: str, mode="r", *args, download_config: Optional[DownloadConfig] = None, **kwargs):
1198
+ """Extend `open` function to support remote files using `fsspec`.
1199
+
1200
+ It also has a retry mechanism in case connection fails.
1201
+ The `args` and `kwargs` are passed to `fsspec.open`, except `token` which is used for queries to private repos on huggingface.co
1202
+
1203
+ Args:
1204
+ file (`str`): Path name of the file to be opened.
1205
+ mode (`str`, *optional*, default "r"): Mode in which the file is opened.
1206
+ *args: Arguments to be passed to `fsspec.open`.
1207
+ download_config : mainly use token or storage_options to support different platforms and auth types.
1208
+ **kwargs: Keyword arguments to be passed to `fsspec.open`.
1209
+
1210
+ Returns:
1211
+ file object
1212
+ """
1213
+ # This works as well for `xopen(str(Path(...)))`
1214
+ file_str = _as_str(file)
1215
+ main_hop, *rest_hops = file_str.split("::")
1216
+ if is_local_path(main_hop):
1217
+ # ignore fsspec-specific kwargs
1218
+ kwargs.pop("block_size", None)
1219
+ return open(main_hop, mode, *args, **kwargs)
1220
+ # add headers and cookies for authentication on the HF Hub and for Google Drive
1221
+ file, storage_options = _prepare_path_and_storage_options(file_str, download_config=download_config)
1222
+ kwargs = {**kwargs, **(storage_options or {})}
1223
+ try:
1224
+ file_obj = fsspec.open(file, mode=mode, *args, **kwargs).open()
1225
+ except ValueError as e:
1226
+ if str(e) == "Cannot seek streaming HTTP file":
1227
+ raise NonStreamableDatasetError(
1228
+ "Streaming is not possible for this dataset because data host server doesn't support HTTP range "
1229
+ "requests. You can still load this dataset in non-streaming mode by passing `streaming=False` (default)"
1230
+ ) from e
1231
+ else:
1232
+ raise
1233
+ except FileNotFoundError:
1234
+ if file.startswith(config.HF_ENDPOINT):
1235
+ raise FileNotFoundError(
1236
+ file + "\nIf the repo is private or gated, make sure to log in with `huggingface-cli login`."
1237
+ ) from None
1238
+ else:
1239
+ raise
1240
+ file_obj = _add_retries_to_file_obj_read_method(file_obj)
1241
+ return file_obj
1242
+
1243
+
1244
+ def xlistdir(path: str, download_config: Optional[DownloadConfig] = None) -> List[str]:
1245
+ """Extend `os.listdir` function to support remote files.
1246
+
1247
+ Args:
1248
+ path (`str`): URL path.
1249
+ download_config : mainly use token or storage_options to support different platforms and auth types.
1250
+
1251
+ Returns:
1252
+ `list` of `str`
1253
+ """
1254
+ main_hop, *rest_hops = _as_str(path).split("::")
1255
+ if is_local_path(main_hop):
1256
+ return os.listdir(path)
1257
+ else:
1258
+ # globbing inside a zip in a private repo requires authentication
1259
+ path, storage_options = _prepare_path_and_storage_options(path, download_config=download_config)
1260
+ main_hop, *rest_hops = path.split("::")
1261
+ fs, *_ = url_to_fs(path, **storage_options)
1262
+ inner_path = main_hop.split("://")[-1]
1263
+ if inner_path.strip("/") and not fs.isdir(inner_path):
1264
+ raise FileNotFoundError(f"Directory doesn't exist: {path}")
1265
+ paths = fs.listdir(inner_path, detail=False)
1266
+ return [os.path.basename(path.rstrip("/")) for path in paths]
1267
+
1268
+
1269
+ def xglob(urlpath, *, recursive=False, download_config: Optional[DownloadConfig] = None):
1270
+ """Extend `glob.glob` function to support remote files.
1271
+
1272
+ Args:
1273
+ urlpath (`str`): URL path with shell-style wildcard patterns.
1274
+ recursive (`bool`, default `False`): Whether to match the "**" pattern recursively to zero or more
1275
+ directories or subdirectories.
1276
+ download_config : mainly use token or storage_options to support different platforms and auth types.
1277
+
1278
+ Returns:
1279
+ `list` of `str`
1280
+ """
1281
+ main_hop, *rest_hops = _as_str(urlpath).split("::")
1282
+ if is_local_path(main_hop):
1283
+ return glob.glob(main_hop, recursive=recursive)
1284
+ else:
1285
+ # globbing inside a zip in a private repo requires authentication
1286
+ urlpath, storage_options = _prepare_path_and_storage_options(urlpath, download_config=download_config)
1287
+ main_hop, *rest_hops = urlpath.split("::")
1288
+ fs, *_ = url_to_fs(urlpath, **storage_options)
1289
+ inner_path = main_hop.split("://")[1]
1290
+ globbed_paths = fs.glob(inner_path)
1291
+ protocol = fs.protocol if isinstance(fs.protocol, str) else fs.protocol[-1]
1292
+ return ["::".join([f"{protocol}://{globbed_path}"] + rest_hops) for globbed_path in globbed_paths]
1293
+
1294
+
1295
+ def xwalk(urlpath, download_config: Optional[DownloadConfig] = None, **kwargs):
1296
+ """Extend `os.walk` function to support remote files.
1297
+
1298
+ Args:
1299
+ urlpath (`str`): URL root path.
1300
+ download_config : mainly use token or storage_options to support different platforms and auth types.
1301
+ **kwargs: Additional keyword arguments forwarded to the underlying filesystem.
1302
+
1303
+
1304
+ Yields:
1305
+ `tuple`: 3-tuple (dirpath, dirnames, filenames).
1306
+ """
1307
+ main_hop, *rest_hops = _as_str(urlpath).split("::")
1308
+ if is_local_path(main_hop):
1309
+ yield from os.walk(main_hop, **kwargs)
1310
+ else:
1311
+ # walking inside a zip in a private repo requires authentication
1312
+ urlpath, storage_options = _prepare_path_and_storage_options(urlpath, download_config=download_config)
1313
+ main_hop, *rest_hops = urlpath.split("::")
1314
+ fs, *_ = url_to_fs(urlpath, **storage_options)
1315
+ inner_path = main_hop.split("://")[-1]
1316
+ if inner_path.strip("/") and not fs.isdir(inner_path):
1317
+ return []
1318
+ protocol = fs.protocol if isinstance(fs.protocol, str) else fs.protocol[-1]
1319
+ for dirpath, dirnames, filenames in fs.walk(inner_path, **kwargs):
1320
+ yield "::".join([f"{protocol}://{dirpath}"] + rest_hops), dirnames, filenames
1321
+
1322
+
1323
+ class xPath(type(Path())):
1324
+ """Extension of `pathlib.Path` to support both local paths and remote URLs."""
1325
+
1326
+ def __str__(self):
1327
+ path_str = super().__str__()
1328
+ main_hop, *rest_hops = path_str.split("::")
1329
+ if is_local_path(main_hop):
1330
+ return main_hop
1331
+ path_as_posix = path_str.replace("\\", "/")
1332
+ path_as_posix = SINGLE_SLASH_AFTER_PROTOCOL_PATTERN.sub("://", path_as_posix)
1333
+ path_as_posix += "//" if path_as_posix.endswith(":") else "" # Add slashes to root of the protocol
1334
+ return path_as_posix
1335
+
1336
+ def exists(self, download_config: Optional[DownloadConfig] = None):
1337
+ """Extend `pathlib.Path.exists` method to support both local and remote files.
1338
+
1339
+ Args:
1340
+ download_config : mainly use token or storage_options to support different platforms and auth types.
1341
+
1342
+ Returns:
1343
+ `bool`
1344
+ """
1345
+ return xexists(str(self), download_config=download_config)
1346
+
1347
+ def glob(self, pattern, download_config: Optional[DownloadConfig] = None):
1348
+ """Glob function for argument of type :obj:`~pathlib.Path` that supports both local paths end remote URLs.
1349
+
1350
+ Args:
1351
+ pattern (`str`): Pattern that resulting paths must match.
1352
+ download_config : mainly use token or storage_options to support different platforms and auth types.
1353
+
1354
+ Yields:
1355
+ [`xPath`]
1356
+ """
1357
+ posix_path = self.as_posix()
1358
+ main_hop, *rest_hops = posix_path.split("::")
1359
+ if is_local_path(main_hop):
1360
+ yield from Path(main_hop).glob(pattern)
1361
+ else:
1362
+ # globbing inside a zip in a private repo requires authentication
1363
+ if rest_hops:
1364
+ urlpath = rest_hops[0]
1365
+ urlpath, storage_options = _prepare_path_and_storage_options(urlpath, download_config=download_config)
1366
+ storage_options = {urlpath.split("://")[0]: storage_options}
1367
+ posix_path = "::".join([main_hop, urlpath, *rest_hops[1:]])
1368
+ else:
1369
+ storage_options = None
1370
+ fs, *_ = url_to_fs(xjoin(posix_path, pattern), **(storage_options or {}))
1371
+ globbed_paths = fs.glob(xjoin(main_hop, pattern))
1372
+ for globbed_path in globbed_paths:
1373
+ yield type(self)("::".join([f"{fs.protocol}://{globbed_path}"] + rest_hops))
1374
+
1375
+ def rglob(self, pattern, **kwargs):
1376
+ """Rglob function for argument of type :obj:`~pathlib.Path` that supports both local paths end remote URLs.
1377
+
1378
+ Args:
1379
+ pattern (`str`): Pattern that resulting paths must match.
1380
+
1381
+ Yields:
1382
+ [`xPath`]
1383
+ """
1384
+ return self.glob("**/" + pattern, **kwargs)
1385
+
1386
+ @property
1387
+ def parent(self) -> "xPath":
1388
+ """Name function for argument of type :obj:`~pathlib.Path` that supports both local paths end remote URLs.
1389
+
1390
+ Returns:
1391
+ [`xPath`]
1392
+ """
1393
+ return type(self)(xdirname(self.as_posix()))
1394
+
1395
+ @property
1396
+ def name(self) -> str:
1397
+ """Name function for argument of type :obj:`~pathlib.Path` that supports both local paths end remote URLs.
1398
+
1399
+ Returns:
1400
+ `str`
1401
+ """
1402
+ return PurePosixPath(self.as_posix().split("::")[0]).name
1403
+
1404
+ @property
1405
+ def stem(self) -> str:
1406
+ """Stem function for argument of type :obj:`~pathlib.Path` that supports both local paths end remote URLs.
1407
+
1408
+ Returns:
1409
+ `str`
1410
+ """
1411
+ return PurePosixPath(self.as_posix().split("::")[0]).stem
1412
+
1413
+ @property
1414
+ def suffix(self) -> str:
1415
+ """Suffix function for argument of type :obj:`~pathlib.Path` that supports both local paths end remote URLs.
1416
+
1417
+ Returns:
1418
+ `str`
1419
+ """
1420
+ return PurePosixPath(self.as_posix().split("::")[0]).suffix
1421
+
1422
+ def open(self, *args, **kwargs):
1423
+ """Extend :func:`xopen` to support argument of type :obj:`~pathlib.Path`.
1424
+
1425
+ Args:
1426
+ **args: Arguments passed to :func:`fsspec.open`.
1427
+ **kwargs: Keyword arguments passed to :func:`fsspec.open`.
1428
+
1429
+ Returns:
1430
+ `io.FileIO`: File-like object.
1431
+ """
1432
+ return xopen(str(self), *args, **kwargs)
1433
+
1434
+ def joinpath(self, *p: Tuple[str, ...]) -> "xPath":
1435
+ """Extend :func:`xjoin` to support argument of type :obj:`~pathlib.Path`.
1436
+
1437
+ Args:
1438
+ *p (`tuple` of `str`): Other path components.
1439
+
1440
+ Returns:
1441
+ [`xPath`]
1442
+ """
1443
+ return type(self)(xjoin(self.as_posix(), *p))
1444
+
1445
+ def __truediv__(self, p: str) -> "xPath":
1446
+ return self.joinpath(p)
1447
+
1448
+ def with_suffix(self, suffix):
1449
+ main_hop, *rest_hops = str(self).split("::")
1450
+ if is_local_path(main_hop):
1451
+ return type(self)(str(super().with_suffix(suffix)))
1452
+ return type(self)("::".join([type(self)(PurePosixPath(main_hop).with_suffix(suffix)).as_posix()] + rest_hops))
1453
+
1454
+
1455
+ def _as_str(path: Union[str, Path, xPath]):
1456
+ return str(path) if isinstance(path, xPath) else str(xPath(str(path)))
1457
+
1458
+
1459
+ def xgzip_open(filepath_or_buffer, *args, download_config: Optional[DownloadConfig] = None, **kwargs):
1460
+ import gzip
1461
+
1462
+ if hasattr(filepath_or_buffer, "read"):
1463
+ return gzip.open(filepath_or_buffer, *args, **kwargs)
1464
+ else:
1465
+ filepath_or_buffer = str(filepath_or_buffer)
1466
+ return gzip.open(xopen(filepath_or_buffer, "rb", download_config=download_config), *args, **kwargs)
1467
+
1468
+
1469
+ def xnumpy_load(filepath_or_buffer, *args, download_config: Optional[DownloadConfig] = None, **kwargs):
1470
+ import numpy as np
1471
+
1472
+ if hasattr(filepath_or_buffer, "read"):
1473
+ return np.load(filepath_or_buffer, *args, **kwargs)
1474
+ else:
1475
+ filepath_or_buffer = str(filepath_or_buffer)
1476
+ return np.load(xopen(filepath_or_buffer, "rb", download_config=download_config), *args, **kwargs)
1477
+
1478
+
1479
+ def xpandas_read_csv(filepath_or_buffer, download_config: Optional[DownloadConfig] = None, **kwargs):
1480
+ import pandas as pd
1481
+
1482
+ if hasattr(filepath_or_buffer, "read"):
1483
+ return pd.read_csv(filepath_or_buffer, **kwargs)
1484
+ else:
1485
+ filepath_or_buffer = str(filepath_or_buffer)
1486
+ if kwargs.get("compression", "infer") == "infer":
1487
+ kwargs["compression"] = _get_extraction_protocol(filepath_or_buffer, download_config=download_config)
1488
+ return pd.read_csv(xopen(filepath_or_buffer, "rb", download_config=download_config), **kwargs)
1489
+
1490
+
1491
+ def xpandas_read_excel(filepath_or_buffer, download_config: Optional[DownloadConfig] = None, **kwargs):
1492
+ import pandas as pd
1493
+
1494
+ if hasattr(filepath_or_buffer, "read"):
1495
+ try:
1496
+ return pd.read_excel(filepath_or_buffer, **kwargs)
1497
+ except ValueError: # Cannot seek streaming HTTP file
1498
+ return pd.read_excel(BytesIO(filepath_or_buffer.read()), **kwargs)
1499
+ else:
1500
+ filepath_or_buffer = str(filepath_or_buffer)
1501
+ try:
1502
+ return pd.read_excel(xopen(filepath_or_buffer, "rb", download_config=download_config), **kwargs)
1503
+ except ValueError: # Cannot seek streaming HTTP file
1504
+ return pd.read_excel(
1505
+ BytesIO(xopen(filepath_or_buffer, "rb", download_config=download_config).read()), **kwargs
1506
+ )
1507
+
1508
+
1509
+ def xpyarrow_parquet_read_table(filepath_or_buffer, download_config: Optional[DownloadConfig] = None, **kwargs):
1510
+ import pyarrow.parquet as pq
1511
+
1512
+ if hasattr(filepath_or_buffer, "read"):
1513
+ return pq.read_table(filepath_or_buffer, **kwargs)
1514
+ else:
1515
+ filepath_or_buffer = str(filepath_or_buffer)
1516
+ return pq.read_table(xopen(filepath_or_buffer, mode="rb", download_config=download_config), **kwargs)
1517
+
1518
+
1519
+ def xsio_loadmat(filepath_or_buffer, download_config: Optional[DownloadConfig] = None, **kwargs):
1520
+ import scipy.io as sio
1521
+
1522
+ if hasattr(filepath_or_buffer, "read"):
1523
+ return sio.loadmat(filepath_or_buffer, **kwargs)
1524
+ else:
1525
+ return sio.loadmat(xopen(filepath_or_buffer, "rb", download_config=download_config), **kwargs)
1526
+
1527
+
1528
+ def xet_parse(source, parser=None, download_config: Optional[DownloadConfig] = None):
1529
+ """Extend `xml.etree.ElementTree.parse` function to support remote files.
1530
+
1531
+ Args:
1532
+ source: File path or file object.
1533
+ parser (`XMLParser`, *optional*, default `XMLParser`): Parser instance.
1534
+ download_config : mainly use token or storage_options to support different platforms and auth types.
1535
+
1536
+ Returns:
1537
+ `xml.etree.ElementTree.Element`: Root element of the given source document.
1538
+ """
1539
+ if hasattr(source, "read"):
1540
+ return ET.parse(source, parser=parser)
1541
+ else:
1542
+ with xopen(source, "rb", download_config=download_config) as f:
1543
+ return ET.parse(f, parser=parser)
1544
+
1545
+
1546
+ def xxml_dom_minidom_parse(filename_or_file, download_config: Optional[DownloadConfig] = None, **kwargs):
1547
+ """Extend `xml.dom.minidom.parse` function to support remote files.
1548
+
1549
+ Args:
1550
+ filename_or_file (`str` or file): File path or file object.
1551
+ download_config : mainly use token or storage_options to support different platforms and auth types.
1552
+ **kwargs (optional): Additional keyword arguments passed to `xml.dom.minidom.parse`.
1553
+
1554
+ Returns:
1555
+ :obj:`xml.dom.minidom.Document`: Parsed document.
1556
+ """
1557
+ if hasattr(filename_or_file, "read"):
1558
+ return xml.dom.minidom.parse(filename_or_file, **kwargs)
1559
+ else:
1560
+ with xopen(filename_or_file, "rb", download_config=download_config) as f:
1561
+ return xml.dom.minidom.parse(f, **kwargs)
1562
+
1563
+
1564
+ class _IterableFromGenerator(TrackedIterable):
1565
+ """Utility class to create an iterable from a generator function, in order to reset the generator when needed."""
1566
+
1567
+ def __init__(self, generator: Callable, *args, **kwargs):
1568
+ super().__init__()
1569
+ self.generator = generator
1570
+ self.args = args
1571
+ self.kwargs = kwargs
1572
+
1573
+ def __iter__(self):
1574
+ for x in self.generator(*self.args, **self.kwargs):
1575
+ self.last_item = x
1576
+ yield x
1577
+ self.last_item = None
1578
+
1579
+
1580
+ class ArchiveIterable(_IterableFromGenerator):
1581
+ """An iterable of (path, fileobj) from a TAR archive, used by `iter_archive`"""
1582
+
1583
+ @staticmethod
1584
+ def _iter_tar(f):
1585
+ stream = tarfile.open(fileobj=f, mode="r|*")
1586
+ for tarinfo in stream:
1587
+ file_path = tarinfo.name
1588
+ if not tarinfo.isreg():
1589
+ continue
1590
+ if file_path is None:
1591
+ continue
1592
+ if os.path.basename(file_path).startswith((".", "__")):
1593
+ # skipping hidden files
1594
+ continue
1595
+ file_obj = stream.extractfile(tarinfo)
1596
+ yield file_path, file_obj
1597
+ stream.members = []
1598
+ del stream
1599
+
1600
+ @staticmethod
1601
+ def _iter_zip(f):
1602
+ zipf = zipfile.ZipFile(f)
1603
+ for member in zipf.infolist():
1604
+ file_path = member.filename
1605
+ if member.is_dir():
1606
+ continue
1607
+ if file_path is None:
1608
+ continue
1609
+ if os.path.basename(file_path).startswith((".", "__")):
1610
+ # skipping hidden files
1611
+ continue
1612
+ file_obj = zipf.open(member)
1613
+ yield file_path, file_obj
1614
+
1615
+ @classmethod
1616
+ def _iter_from_fileobj(cls, f) -> Generator[Tuple, None, None]:
1617
+ compression = _get_extraction_protocol_with_magic_number(f)
1618
+ if compression == "zip":
1619
+ yield from cls._iter_zip(f)
1620
+ else:
1621
+ yield from cls._iter_tar(f)
1622
+
1623
+ @classmethod
1624
+ def _iter_from_urlpath(
1625
+ cls, urlpath: str, download_config: Optional[DownloadConfig] = None
1626
+ ) -> Generator[Tuple, None, None]:
1627
+ compression = _get_extraction_protocol(urlpath, download_config=download_config)
1628
+ # Set block_size=0 to get faster streaming
1629
+ # (e.g. for hf:// and https:// it uses streaming Requests file-like instances)
1630
+ with xopen(urlpath, "rb", download_config=download_config, block_size=0) as f:
1631
+ if compression == "zip":
1632
+ yield from cls._iter_zip(f)
1633
+ else:
1634
+ yield from cls._iter_tar(f)
1635
+
1636
+ @classmethod
1637
+ def from_buf(cls, fileobj) -> "ArchiveIterable":
1638
+ return cls(cls._iter_from_fileobj, fileobj)
1639
+
1640
+ @classmethod
1641
+ def from_urlpath(cls, urlpath_or_buf, download_config: Optional[DownloadConfig] = None) -> "ArchiveIterable":
1642
+ return cls(cls._iter_from_urlpath, urlpath_or_buf, download_config)
1643
+
1644
+
1645
+ class FilesIterable(_IterableFromGenerator):
1646
+ """An iterable of paths from a list of directories or files"""
1647
+
1648
+ @classmethod
1649
+ def _iter_from_urlpaths(
1650
+ cls, urlpaths: Union[str, List[str]], download_config: Optional[DownloadConfig] = None
1651
+ ) -> Generator[str, None, None]:
1652
+ if not isinstance(urlpaths, list):
1653
+ urlpaths = [urlpaths]
1654
+ for urlpath in urlpaths:
1655
+ if xisfile(urlpath, download_config=download_config):
1656
+ yield urlpath
1657
+ elif xisdir(urlpath, download_config=download_config):
1658
+ for dirpath, dirnames, filenames in xwalk(urlpath, download_config=download_config):
1659
+ # in-place modification to prune the search
1660
+ dirnames[:] = sorted([dirname for dirname in dirnames if not dirname.startswith((".", "__"))])
1661
+ if xbasename(dirpath).startswith((".", "__")):
1662
+ # skipping hidden directories
1663
+ continue
1664
+ for filename in sorted(filenames):
1665
+ if filename.startswith((".", "__")):
1666
+ # skipping hidden files
1667
+ continue
1668
+ yield xjoin(dirpath, filename)
1669
+ else:
1670
+ raise FileNotFoundError(urlpath)
1671
+
1672
+ @classmethod
1673
+ def from_urlpaths(cls, urlpaths, download_config: Optional[DownloadConfig] = None) -> "FilesIterable":
1674
+ return cls(cls._iter_from_urlpaths, urlpaths, download_config)
venv/lib/python3.10/site-packages/datasets/utils/filelock.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # deprecated, please use the `filelock` package instead
2
+
3
+ from filelock import ( # noqa: F401 # imported for backward compatibility TODO: remove in 3.0.0
4
+ BaseFileLock,
5
+ SoftFileLock,
6
+ Timeout,
7
+ UnixFileLock,
8
+ WindowsFileLock,
9
+ )
10
+
11
+ from ._filelock import FileLock # noqa: F401 # imported for backward compatibility. TODO: remove in 3.0.0
venv/lib/python3.10/site-packages/datasets/utils/hub.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ from functools import partial
2
+
3
+ from huggingface_hub import hf_hub_url
4
+
5
+
6
+ hf_dataset_url = partial(hf_hub_url, repo_type="dataset")
venv/lib/python3.10/site-packages/datasets/utils/info_utils.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import enum
2
+ import os
3
+ from typing import Optional
4
+
5
+ from huggingface_hub.utils import insecure_hashlib
6
+
7
+ from .. import config
8
+ from .logging import get_logger
9
+
10
+
11
+ logger = get_logger(__name__)
12
+
13
+
14
+ class VerificationMode(enum.Enum):
15
+ """`Enum` that specifies which verification checks to run.
16
+
17
+ The default mode is `BASIC_CHECKS`, which will perform only rudimentary checks to avoid slowdowns
18
+ when generating/downloading a dataset for the first time.
19
+
20
+ The verification modes:
21
+
22
+ | | Verification checks |
23
+ |---------------------------|------------------------------------------------------------------------------ |
24
+ | `ALL_CHECKS` | Split checks, uniqueness of the keys yielded in case of the GeneratorBuilder |
25
+ | | and the validity (number of files, checksums, etc.) of downloaded files |
26
+ | `BASIC_CHECKS` (default) | Same as `ALL_CHECKS` but without checking downloaded files |
27
+ | `NO_CHECKS` | None |
28
+
29
+ """
30
+
31
+ ALL_CHECKS = "all_checks"
32
+ BASIC_CHECKS = "basic_checks"
33
+ NO_CHECKS = "no_checks"
34
+
35
+
36
+ class ChecksumVerificationException(Exception):
37
+ """Exceptions during checksums verifications of downloaded files."""
38
+
39
+
40
+ class UnexpectedDownloadedFile(ChecksumVerificationException):
41
+ """Some downloaded files were not expected."""
42
+
43
+
44
+ class ExpectedMoreDownloadedFiles(ChecksumVerificationException):
45
+ """Some files were supposed to be downloaded but were not."""
46
+
47
+
48
+ class NonMatchingChecksumError(ChecksumVerificationException):
49
+ """The downloaded file checksum don't match the expected checksum."""
50
+
51
+
52
+ def verify_checksums(expected_checksums: Optional[dict], recorded_checksums: dict, verification_name=None):
53
+ if expected_checksums is None:
54
+ logger.info("Unable to verify checksums.")
55
+ return
56
+ if len(set(expected_checksums) - set(recorded_checksums)) > 0:
57
+ raise ExpectedMoreDownloadedFiles(str(set(expected_checksums) - set(recorded_checksums)))
58
+ if len(set(recorded_checksums) - set(expected_checksums)) > 0:
59
+ raise UnexpectedDownloadedFile(str(set(recorded_checksums) - set(expected_checksums)))
60
+ bad_urls = [url for url in expected_checksums if expected_checksums[url] != recorded_checksums[url]]
61
+ for_verification_name = " for " + verification_name if verification_name is not None else ""
62
+ if len(bad_urls) > 0:
63
+ raise NonMatchingChecksumError(
64
+ f"Checksums didn't match{for_verification_name}:\n"
65
+ f"{bad_urls}\n"
66
+ "Set `verification_mode='no_checks'` to skip checksums verification and ignore this error"
67
+ )
68
+ logger.info("All the checksums matched successfully" + for_verification_name)
69
+
70
+
71
+ class SplitsVerificationException(Exception):
72
+ """Exceptions during splis verifications"""
73
+
74
+
75
+ class UnexpectedSplits(SplitsVerificationException):
76
+ """The expected splits of the downloaded file is missing."""
77
+
78
+
79
+ class ExpectedMoreSplits(SplitsVerificationException):
80
+ """Some recorded splits are missing."""
81
+
82
+
83
+ class NonMatchingSplitsSizesError(SplitsVerificationException):
84
+ """The splits sizes don't match the expected splits sizes."""
85
+
86
+
87
+ def verify_splits(expected_splits: Optional[dict], recorded_splits: dict):
88
+ if expected_splits is None:
89
+ logger.info("Unable to verify splits sizes.")
90
+ return
91
+ if len(set(expected_splits) - set(recorded_splits)) > 0:
92
+ raise ExpectedMoreSplits(str(set(expected_splits) - set(recorded_splits)))
93
+ if len(set(recorded_splits) - set(expected_splits)) > 0:
94
+ raise UnexpectedSplits(str(set(recorded_splits) - set(expected_splits)))
95
+ bad_splits = [
96
+ {"expected": expected_splits[name], "recorded": recorded_splits[name]}
97
+ for name in expected_splits
98
+ if expected_splits[name].num_examples != recorded_splits[name].num_examples
99
+ ]
100
+ if len(bad_splits) > 0:
101
+ raise NonMatchingSplitsSizesError(str(bad_splits))
102
+ logger.info("All the splits matched successfully.")
103
+
104
+
105
+ def get_size_checksum_dict(path: str, record_checksum: bool = True) -> dict:
106
+ """Compute the file size and the sha256 checksum of a file"""
107
+ if record_checksum:
108
+ m = insecure_hashlib.sha256()
109
+ with open(path, "rb") as f:
110
+ for chunk in iter(lambda: f.read(1 << 20), b""):
111
+ m.update(chunk)
112
+ checksum = m.hexdigest()
113
+ else:
114
+ checksum = None
115
+ return {"num_bytes": os.path.getsize(path), "checksum": checksum}
116
+
117
+
118
+ def is_small_dataset(dataset_size):
119
+ """Check if `dataset_size` is smaller than `config.IN_MEMORY_MAX_SIZE`.
120
+
121
+ Args:
122
+ dataset_size (int): Dataset size in bytes.
123
+
124
+ Returns:
125
+ bool: Whether `dataset_size` is smaller than `config.IN_MEMORY_MAX_SIZE`.
126
+ """
127
+ if dataset_size and config.IN_MEMORY_MAX_SIZE:
128
+ return dataset_size < config.IN_MEMORY_MAX_SIZE
129
+ else:
130
+ return False
venv/lib/python3.10/site-packages/datasets/utils/metadata.py ADDED
@@ -0,0 +1,320 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import textwrap
3
+ from collections import Counter
4
+ from itertools import groupby
5
+ from operator import itemgetter
6
+ from pathlib import Path
7
+ from typing import Any, ClassVar, Dict, List, Optional, Tuple, Union
8
+
9
+ import yaml
10
+ from huggingface_hub import DatasetCardData
11
+
12
+ from ..config import METADATA_CONFIGS_FIELD
13
+ from ..info import DatasetInfo, DatasetInfosDict
14
+ from ..naming import _split_re
15
+ from ..utils.logging import get_logger
16
+ from .deprecation_utils import deprecated
17
+
18
+
19
+ logger = get_logger(__name__)
20
+
21
+
22
+ class _NoDuplicateSafeLoader(yaml.SafeLoader):
23
+ def _check_no_duplicates_on_constructed_node(self, node):
24
+ keys = [self.constructed_objects[key_node] for key_node, _ in node.value]
25
+ keys = [tuple(key) if isinstance(key, list) else key for key in keys]
26
+ counter = Counter(keys)
27
+ duplicate_keys = [key for key in counter if counter[key] > 1]
28
+ if duplicate_keys:
29
+ raise TypeError(f"Got duplicate yaml keys: {duplicate_keys}")
30
+
31
+ def construct_mapping(self, node, deep=False):
32
+ mapping = super().construct_mapping(node, deep=deep)
33
+ self._check_no_duplicates_on_constructed_node(node)
34
+ return mapping
35
+
36
+
37
+ def _split_yaml_from_readme(readme_content: str) -> Tuple[Optional[str], str]:
38
+ full_content = list(readme_content.splitlines())
39
+ if full_content and full_content[0] == "---" and "---" in full_content[1:]:
40
+ sep_idx = full_content[1:].index("---") + 1
41
+ yamlblock = "\n".join(full_content[1:sep_idx])
42
+ return yamlblock, "\n".join(full_content[sep_idx + 1 :])
43
+
44
+ return None, "\n".join(full_content)
45
+
46
+
47
+ @deprecated("Use `huggingface_hub.DatasetCardData` instead.")
48
+ class DatasetMetadata(dict):
49
+ # class attributes
50
+ _FIELDS_WITH_DASHES = {"train_eval_index"} # train-eval-index in the YAML metadata
51
+
52
+ @classmethod
53
+ def from_readme(cls, path: Union[Path, str]) -> "DatasetMetadata":
54
+ """Loads and validates the dataset metadata from its dataset card (README.md)
55
+
56
+ Args:
57
+ path (:obj:`Path`): Path to the dataset card (its README.md file)
58
+
59
+ Returns:
60
+ :class:`DatasetMetadata`: The dataset's metadata
61
+
62
+ Raises:
63
+ :obj:`TypeError`: If the dataset's metadata is invalid
64
+ """
65
+ with open(path, encoding="utf-8") as readme_file:
66
+ yaml_string, _ = _split_yaml_from_readme(readme_file.read())
67
+ if yaml_string is not None:
68
+ return cls.from_yaml_string(yaml_string)
69
+ else:
70
+ return cls()
71
+
72
+ def to_readme(self, path: Path):
73
+ if path.exists():
74
+ with open(path, encoding="utf-8") as readme_file:
75
+ readme_content = readme_file.read()
76
+ else:
77
+ readme_content = None
78
+ updated_readme_content = self._to_readme(readme_content)
79
+ with open(path, "w", encoding="utf-8") as readme_file:
80
+ readme_file.write(updated_readme_content)
81
+
82
+ def _to_readme(self, readme_content: Optional[str] = None) -> str:
83
+ if readme_content is not None:
84
+ _, content = _split_yaml_from_readme(readme_content)
85
+ full_content = "---\n" + self.to_yaml_string() + "---\n" + content
86
+ else:
87
+ full_content = "---\n" + self.to_yaml_string() + "---\n"
88
+ return full_content
89
+
90
+ @classmethod
91
+ def from_yaml_string(cls, string: str) -> "DatasetMetadata":
92
+ """Loads and validates the dataset metadata from a YAML string
93
+
94
+ Args:
95
+ string (:obj:`str`): The YAML string
96
+
97
+ Returns:
98
+ :class:`DatasetMetadata`: The dataset's metadata
99
+
100
+ Raises:
101
+ :obj:`TypeError`: If the dataset's metadata is invalid
102
+ """
103
+ metadata_dict = yaml.load(string, Loader=_NoDuplicateSafeLoader) or {}
104
+
105
+ # Convert the YAML keys to DatasetMetadata fields
106
+ metadata_dict = {
107
+ (key.replace("-", "_") if key.replace("-", "_") in cls._FIELDS_WITH_DASHES else key): value
108
+ for key, value in metadata_dict.items()
109
+ }
110
+ return cls(**metadata_dict)
111
+
112
+ def to_yaml_string(self) -> str:
113
+ return yaml.safe_dump(
114
+ {
115
+ (key.replace("_", "-") if key in self._FIELDS_WITH_DASHES else key): value
116
+ for key, value in self.items()
117
+ },
118
+ sort_keys=False,
119
+ allow_unicode=True,
120
+ encoding="utf-8",
121
+ ).decode("utf-8")
122
+
123
+
124
+ class MetadataConfigs(Dict[str, Dict[str, Any]]):
125
+ """Should be in format {config_name: {**config_params}}."""
126
+
127
+ FIELD_NAME: ClassVar[str] = METADATA_CONFIGS_FIELD
128
+
129
+ @staticmethod
130
+ def _raise_if_data_files_field_not_valid(metadata_config: dict):
131
+ yaml_data_files = metadata_config.get("data_files")
132
+ if yaml_data_files is not None:
133
+ yaml_error_message = textwrap.dedent(
134
+ f"""
135
+ Expected data_files in YAML to be either a string or a list of strings
136
+ or a list of dicts with two keys: 'split' and 'path', but got {yaml_data_files}
137
+ Examples of data_files in YAML:
138
+
139
+ data_files: data.csv
140
+
141
+ data_files: data/*.png
142
+
143
+ data_files:
144
+ - part0/*
145
+ - part1/*
146
+
147
+ data_files:
148
+ - split: train
149
+ path: train/*
150
+ - split: test
151
+ path: test/*
152
+
153
+ data_files:
154
+ - split: train
155
+ path:
156
+ - train/part1/*
157
+ - train/part2/*
158
+ - split: test
159
+ path: test/*
160
+
161
+ PS: some symbols like dashes '-' are not allowed in split names
162
+ """
163
+ )
164
+ if not isinstance(yaml_data_files, (list, str)):
165
+ raise ValueError(yaml_error_message)
166
+ if isinstance(yaml_data_files, list):
167
+ for yaml_data_files_item in yaml_data_files:
168
+ if (
169
+ not isinstance(yaml_data_files_item, (str, dict))
170
+ or isinstance(yaml_data_files_item, dict)
171
+ and not (
172
+ len(yaml_data_files_item) == 2
173
+ and "split" in yaml_data_files_item
174
+ and re.match(_split_re, yaml_data_files_item["split"])
175
+ and isinstance(yaml_data_files_item.get("path"), (str, list))
176
+ )
177
+ ):
178
+ raise ValueError(yaml_error_message)
179
+
180
+ @classmethod
181
+ def _from_exported_parquet_files_and_dataset_infos(
182
+ cls,
183
+ revision: str,
184
+ exported_parquet_files: List[Dict[str, Any]],
185
+ dataset_infos: DatasetInfosDict,
186
+ ) -> "MetadataConfigs":
187
+ metadata_configs = {
188
+ config_name: {
189
+ "data_files": [
190
+ {
191
+ "split": split_name,
192
+ "path": [
193
+ parquet_file["url"].replace("refs%2Fconvert%2Fparquet", revision)
194
+ for parquet_file in parquet_files_for_split
195
+ ],
196
+ }
197
+ for split_name, parquet_files_for_split in groupby(parquet_files_for_config, itemgetter("split"))
198
+ ],
199
+ "version": str(dataset_infos.get(config_name, DatasetInfo()).version or "0.0.0"),
200
+ }
201
+ for config_name, parquet_files_for_config in groupby(exported_parquet_files, itemgetter("config"))
202
+ }
203
+ if dataset_infos:
204
+ # Preserve order of configs and splits
205
+ metadata_configs = {
206
+ config_name: {
207
+ "data_files": [
208
+ data_file
209
+ for split_name in dataset_info.splits
210
+ for data_file in metadata_configs[config_name]["data_files"]
211
+ if data_file["split"] == split_name
212
+ ],
213
+ "version": metadata_configs[config_name]["version"],
214
+ }
215
+ for config_name, dataset_info in dataset_infos.items()
216
+ }
217
+ return cls(metadata_configs)
218
+
219
+ @classmethod
220
+ def from_dataset_card_data(cls, dataset_card_data: DatasetCardData) -> "MetadataConfigs":
221
+ if dataset_card_data.get(cls.FIELD_NAME):
222
+ metadata_configs = dataset_card_data[cls.FIELD_NAME]
223
+ if not isinstance(metadata_configs, list):
224
+ raise ValueError(f"Expected {cls.FIELD_NAME} to be a list, but got '{metadata_configs}'")
225
+ for metadata_config in metadata_configs:
226
+ if "config_name" not in metadata_config:
227
+ raise ValueError(
228
+ f"Each config must include `config_name` field with a string name of a config, "
229
+ f"but got {metadata_config}. "
230
+ )
231
+ cls._raise_if_data_files_field_not_valid(metadata_config)
232
+ return cls(
233
+ {
234
+ config["config_name"]: {param: value for param, value in config.items() if param != "config_name"}
235
+ for config in metadata_configs
236
+ }
237
+ )
238
+ return cls()
239
+
240
+ def to_dataset_card_data(self, dataset_card_data: DatasetCardData) -> None:
241
+ if self:
242
+ for metadata_config in self.values():
243
+ self._raise_if_data_files_field_not_valid(metadata_config)
244
+ current_metadata_configs = self.from_dataset_card_data(dataset_card_data)
245
+ total_metadata_configs = dict(sorted({**current_metadata_configs, **self}.items()))
246
+ for config_name, config_metadata in total_metadata_configs.items():
247
+ config_metadata.pop("config_name", None)
248
+ dataset_card_data[self.FIELD_NAME] = [
249
+ {"config_name": config_name, **config_metadata}
250
+ for config_name, config_metadata in total_metadata_configs.items()
251
+ ]
252
+
253
+ def get_default_config_name(self) -> Optional[str]:
254
+ default_config_name = None
255
+ for config_name, metadata_config in self.items():
256
+ if len(self) == 1 or config_name == "default" or metadata_config.get("default"):
257
+ if default_config_name is None:
258
+ default_config_name = config_name
259
+ else:
260
+ raise ValueError(
261
+ f"Dataset has several default configs: '{default_config_name}' and '{config_name}'."
262
+ )
263
+ return default_config_name
264
+
265
+
266
+ # DEPRECATED - just here to support old versions of evaluate like 0.2.2
267
+ # To support new tasks on the Hugging Face Hub, please open a PR for this file:
268
+ # https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/src/pipelines.ts
269
+ known_task_ids = {
270
+ "image-classification": [],
271
+ "translation": [],
272
+ "image-segmentation": [],
273
+ "fill-mask": [],
274
+ "automatic-speech-recognition": [],
275
+ "token-classification": [],
276
+ "sentence-similarity": [],
277
+ "audio-classification": [],
278
+ "question-answering": [],
279
+ "summarization": [],
280
+ "zero-shot-classification": [],
281
+ "table-to-text": [],
282
+ "feature-extraction": [],
283
+ "other": [],
284
+ "multiple-choice": [],
285
+ "text-classification": [],
286
+ "text-to-image": [],
287
+ "text2text-generation": [],
288
+ "zero-shot-image-classification": [],
289
+ "tabular-classification": [],
290
+ "tabular-regression": [],
291
+ "image-to-image": [],
292
+ "tabular-to-text": [],
293
+ "unconditional-image-generation": [],
294
+ "text-retrieval": [],
295
+ "text-to-speech": [],
296
+ "object-detection": [],
297
+ "audio-to-audio": [],
298
+ "text-generation": [],
299
+ "conversational": [],
300
+ "table-question-answering": [],
301
+ "visual-question-answering": [],
302
+ "image-to-text": [],
303
+ "reinforcement-learning": [],
304
+ "voice-activity-detection": [],
305
+ "time-series-forecasting": [],
306
+ "document-question-answering": [],
307
+ }
308
+
309
+
310
+ if __name__ == "__main__":
311
+ from argparse import ArgumentParser
312
+
313
+ ap = ArgumentParser(usage="Validate the yaml metadata block of a README.md file.")
314
+ ap.add_argument("readme_filepath")
315
+ args = ap.parse_args()
316
+
317
+ readme_filepath = Path(args.readme_filepath)
318
+ dataset_metadata = DatasetMetadata.from_readme(readme_filepath)
319
+ print(dataset_metadata)
320
+ dataset_metadata.to_readme(readme_filepath)
venv/lib/python3.10/site-packages/datasets/utils/patching.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from importlib import import_module
2
+
3
+ from .logging import get_logger
4
+
5
+
6
+ logger = get_logger(__name__)
7
+
8
+
9
+ class _PatchedModuleObj:
10
+ """Set all the modules components as attributes of the _PatchedModuleObj object."""
11
+
12
+ def __init__(self, module, attrs=None):
13
+ attrs = attrs or []
14
+ if module is not None:
15
+ for key in module.__dict__:
16
+ if key in attrs or not key.startswith("__"):
17
+ setattr(self, key, getattr(module, key))
18
+ self._original_module = module._original_module if isinstance(module, _PatchedModuleObj) else module
19
+
20
+
21
+ class patch_submodule:
22
+ """
23
+ Patch a submodule attribute of an object, by keeping all other submodules intact at all levels.
24
+
25
+ Example::
26
+
27
+ >>> import importlib
28
+ >>> from datasets.load import dataset_module_factory
29
+ >>> from datasets.streaming import patch_submodule, xjoin
30
+ >>>
31
+ >>> dataset_module = dataset_module_factory("snli")
32
+ >>> snli_module = importlib.import_module(dataset_module.module_path)
33
+ >>> patcher = patch_submodule(snli_module, "os.path.join", xjoin)
34
+ >>> patcher.start()
35
+ >>> assert snli_module.os.path.join is xjoin
36
+ """
37
+
38
+ _active_patches = []
39
+
40
+ def __init__(self, obj, target: str, new, attrs=None):
41
+ self.obj = obj
42
+ self.target = target
43
+ self.new = new
44
+ self.key = target.split(".")[0]
45
+ self.original = {}
46
+ self.attrs = attrs or []
47
+
48
+ def __enter__(self):
49
+ *submodules, target_attr = self.target.split(".")
50
+
51
+ # Patch modules:
52
+ # it's used to patch attributes of submodules like "os.path.join";
53
+ # in this case we need to patch "os" and "os.path"
54
+
55
+ for i in range(len(submodules)):
56
+ try:
57
+ submodule = import_module(".".join(submodules[: i + 1]))
58
+ except ModuleNotFoundError:
59
+ continue
60
+ # We iterate over all the globals in self.obj in case we find "os" or "os.path"
61
+ for attr in self.obj.__dir__():
62
+ obj_attr = getattr(self.obj, attr)
63
+ # We don't check for the name of the global, but rather if its value *is* "os" or "os.path".
64
+ # This allows to patch renamed modules like "from os import path as ospath".
65
+ if obj_attr is submodule or (
66
+ isinstance(obj_attr, _PatchedModuleObj) and obj_attr._original_module is submodule
67
+ ):
68
+ self.original[attr] = obj_attr
69
+ # patch at top level
70
+ setattr(self.obj, attr, _PatchedModuleObj(obj_attr, attrs=self.attrs))
71
+ patched = getattr(self.obj, attr)
72
+ # construct lower levels patches
73
+ for key in submodules[i + 1 :]:
74
+ setattr(patched, key, _PatchedModuleObj(getattr(patched, key, None), attrs=self.attrs))
75
+ patched = getattr(patched, key)
76
+ # finally set the target attribute
77
+ setattr(patched, target_attr, self.new)
78
+
79
+ # Patch attribute itself:
80
+ # it's used for builtins like "open",
81
+ # and also to patch "os.path.join" we may also need to patch "join"
82
+ # itself if it was imported as "from os.path import join".
83
+
84
+ if submodules: # if it's an attribute of a submodule like "os.path.join"
85
+ try:
86
+ attr_value = getattr(import_module(".".join(submodules)), target_attr)
87
+ except (AttributeError, ModuleNotFoundError):
88
+ return
89
+ # We iterate over all the globals in self.obj in case we find "os.path.join"
90
+ for attr in self.obj.__dir__():
91
+ # We don't check for the name of the global, but rather if its value *is* "os.path.join".
92
+ # This allows to patch renamed attributes like "from os.path import join as pjoin".
93
+ if getattr(self.obj, attr) is attr_value:
94
+ self.original[attr] = getattr(self.obj, attr)
95
+ setattr(self.obj, attr, self.new)
96
+ elif target_attr in globals()["__builtins__"]: # if it'a s builtin like "open"
97
+ self.original[target_attr] = globals()["__builtins__"][target_attr]
98
+ setattr(self.obj, target_attr, self.new)
99
+ else:
100
+ raise RuntimeError(f"Tried to patch attribute {target_attr} instead of a submodule.")
101
+
102
+ def __exit__(self, *exc_info):
103
+ for attr in list(self.original):
104
+ setattr(self.obj, attr, self.original.pop(attr))
105
+
106
+ def start(self):
107
+ """Activate a patch."""
108
+ self.__enter__()
109
+ self._active_patches.append(self)
110
+
111
+ def stop(self):
112
+ """Stop an active patch."""
113
+ try:
114
+ self._active_patches.remove(self)
115
+ except ValueError:
116
+ # If the patch hasn't been started this will fail
117
+ return None
118
+
119
+ return self.__exit__()
venv/lib/python3.10/site-packages/datasets/utils/resources/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/datasets/utils/resources/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (192 Bytes). View file